From a7dd2e846efd8d9f15f6183751421856789ad640 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Sun, 22 Nov 2026 09:44:36 -0800 Subject: [PATCH] Translator: the binder's plan goes, with everything only it reaches, and the TexelRows and YCbCrInPlace forms The runtime never made a plan (it binds each draw and dispatch by the pipeline's interface), and since the census digests each pipeline's content alone (two commits back) nothing in the tree calls one. What only the plan reached goes with it: - bind: BindState, BindShape and their shapes, BindingPlan and its instantiation (DispatchCommands, DrawCommands, push, descriptor and root-table templates and writes), plan.rs and plan/ (compute, resources, slots), instantiate.rs, resident.rs, the neutral resources' plan side, the heap's member planning and table bytes, the mesh arguments pass (MeshArguments, MeshArgumentsForm, fold_object_grid, metal_object_grid), ExecutionStatus and StatusBits as public items, TextureShape::Buffer, IndirectRef with the four indirect call variants (Dispatch::ThreadgroupsIndirect, DrawCall::Indirect, PatchesIndirect, MeshThreadgroupsIndirect) and IndexBufferRef::fetch_end. Dispatch, DrawCall and IndexBufferRef stay: validation states its cases' calls with them. - error::BindError leaves the public surface; a crate-private BindError of three variants stays as the error of the heap's view derivation, which lower::texture::slot's storage-read check reads (bind::heap::tier_read_gaps). That check keeps only the storage view's format: the sampled-view branch and ImageViewDesc were reached by the plan alone. - vk::DrawCommand, the plan's draw output. - pipeline: ComputePipeline::plan, RenderPipeline::plan; cache: VariantKey::covers and large_buffer_form. - The TexelRows form (bind::texel_rows, LoweringInputs::texel_rows, RuntimeFact and PushField TexelRows) and the YCbCrInPlace form (bind::ycbcr_in_place, lower/sampler/in_place.rs, LoweringInputs::ycbcr_in_place and ycbcr_planes_sampled, RuntimeFact and PushField YCbCrInPlace, PrecisionNote FloatSampleFilter and HalfSampleFilter, Routine::Quad). Only the binder set those inputs. - The tests of the deleted items, and the plan halves of mixed tests. Of 6810 tests (`#[test]` functions in the workspace) 309 leave and 11 come in their place: the lowering halves of mixed tests, kept without the plan (the heap layout, the stage-in stride and region facts, the emulated-simdgroup and bicubic facts, the iris-xe storage classes), and the kept tests of the two renamed files. 50 others are edited to drop a plan half or a deleted item (the api_surface round trips; the simd_emulated, extended-range, recursion, dynamic-root, handles, heap-storage-read and mesh lowering cases). 6512 remain. engine_graphics_binder.rs and engine_heap_binder.rs keep one and two tests and are renamed engine_unattached_colors.rs and engine_heap_groups.rs. - The runtime guard test's list of files the runtime inputs reach without being inputs drops the seven no input reaches since the cut: cache/digest.rs, lower/simd/divergent.rs, lower/simd/workgroup.rs, pipeline/artifact.rs, pipeline/layout.rs, pipeline/stage_io.rs and pipeline/vertex.rs; three of its reasons that named the plan or the binder say what reaches the file now. 559 public items leave (api_signatures.tsv: 55 structs, 26 enums, 140 variants, 245 fields, 52 methods, 24 associated constants, 7 constants, 5 functions, 5 impls). Consumer search, the consumer's development at 92ffbed817, `git grep -w NAME` of each of the 112 removed names: 0 hits for 105; the others are the consumer's own items: TessellationFactors 4 (its Bound::TessellationFactors), YCbCrMatrix 3 (its own string and doc), texel_rows 2 (its own fn), ThreadgroupsIndirect 6 (its own Dispatch enums and rt::Dispatch::Indirect), DrawIndexed 1 (a doc naming MTLIndirectCommandType values), covers 109 and plan 105 (generic words; the `.covers(` calls are its Extent's, the `.plan(` calls its video encoder's rate.plan). Its one import of metal2vulkan::bind is the argument-buffer layout types, which stay. The forms' audit. A texture over a buffer: the runtime's tests::over::every_device_holds_a_texture_over_a_buffer_in_place. A two-plane YCbCr sample: no runtime test; the runtime makes no texture of a two-plane YCbCr format (Gap::TextureFormat, the runtime README's "A format is made where the translator's format table maps it" row), the conformance cases ycbcr_gathers and ycbcr_textures record Metal's answers, and known-gaps-rt.tsv lists the runtime's refusals (ycbcr-gathers-*, ycbcr-texel-reads-420v). Versions: - RUNTIME_VERSION 2550: it covers plan instantiation and the binder's run-time data. Nothing calls those since step 2: the runtime never used the binder, and the own-context executor is gone. A run of an unchanged artifact does nothing different, so the guard hash (runtime-sources.sha256) moves alone, and the RUNTIME_VERSION doc is rewritten to name what it still covers. - SEMANTICS_VERSION 2273: no output changes for any input that still exists. The TexelRows and YCbCrInPlace forms, their facts, push fields and the two notes were reachable only through LoweringInputs::ycbcr_in_place, ycbcr_planes_sampled and texel_rows. Only the binder set those; the runtime sets none. The function key appended each of them only when set, so every surviving key hashes the same bytes. Two type declarations stay where they were, so module words do not move: bool in the bicubic types, uvec4 in the bicubic routines. Byte-identical modules are expected, not verified here; the 252-row hash probe is the check. - ARTIFACT_FORMAT_VERSION 591: the codec tags enum variants by name. The removed RuntimeFact, PushField and PrecisionNote variants leave their tags unused, which cache/mod.rs's rule says needs no bump: an old entry holding one fails to decode, which is a miss. No codec_struct field is removed. That is why SamplerDesc.ycbcr stays. The guard hash (crates/metal2vulkan-validation/runtime-sources.sha256) moves for the bind/ sources this deletes and edits and for vk/draw.rs, which leaves its list. No run of an unchanged artifact changes: what stays in bind/ computes what it did (the heap's tier check takes the same storage format; its removed sampled branch had no caller). Docs: docs/API.md (section 5 is the interface; the binding and plan sections go), README.md, docs/ARCHITECTURE.md, docs/HOWTO.md, docs/VALIDATION.md, the runtime README's DrawInput and identity-domain rows, docs/REFUSALS.md (regenerated; the binder's section goes), api_reference.md, api_signatures.tsv (blessed: removals only), tests/api_surface.rs, the signatures floor (5000), the bind modules' own docs, and the public field docs of PushField, RuntimeFact and SpecKey that named BindState, BindShape or BindingPlan. AGENTS.md: the project table names pipelines and their interfaces, not binding plans; its "core lives in" line stays true (bind/ still holds what the lowering reads). Verified on 31692939d4, this commit's tree (steelbrain/cutbinder-probe-6): job m3-max-68107, fmt, signatures, refusal surface, clippy -D warnings (workspace plain, --cfg m2v_gpu, --cfg m2v_cpu_icd; the translator with no feature and with each alone; the AIR crate alone), workspace Rustdoc -D warnings, each crate's private intra-doc links at 0, api-docs; job m3-max-68109, the product, validation and conformance suites, doctests, and on lavapipe the validation and runtime suites under --cfg m2v_cpu_icd, the conformance replay and the public cases' qualification. --- AGENTS.md | 2 +- README.md | 4 +- .../src/cases/pixel_downscales.rs | 4 +- .../src/cases/pixel_samplers.rs | 3 +- .../src/cases/sampler_crossings.rs | 5 - .../src/cases/sampler_filtering.rs | 5 - .../src/degradation.rs | 10 - crates/metal2vulkan-conformance/src/replay.rs | 7 +- crates/metal2vulkan-runtime/README.md | 9 +- crates/metal2vulkan-runtime/src/render.rs | 2 +- crates/metal2vulkan-validation/build.rs | 10 +- .../runtime-sources.sha256 | 2 +- .../src/candidate/engine/artifact/tests.rs | 13 +- .../candidate/platform/graphics_pipeline.rs | 5 +- .../executor_contract/render_target_array.rs | 4 +- .../src/executor_contract/stage_inputs.rs | 4 +- .../src/executor_contract/tessellation.rs | 4 +- .../src/observation_contract/comparison.rs | 8 - .../observation_contract/comparison/tests.rs | 2 - crates/metal2vulkan/examples/api_preview.rs | 168 +- crates/metal2vulkan/src/api_reference.md | 24 +- crates/metal2vulkan/src/bind/dispatch.rs | 1436 +------ .../metal2vulkan/src/bind/dispatch/tests.rs | 1225 ------ crates/metal2vulkan/src/bind/graphics.rs | 3592 +---------------- .../metal2vulkan/src/bind/graphics/tests.rs | 2060 ---------- crates/metal2vulkan/src/bind/heap.rs | 1969 +-------- crates/metal2vulkan/src/bind/heap/tests.rs | 1032 +---- crates/metal2vulkan/src/bind/instantiate.rs | 861 ---- .../src/bind/instantiate/tests.rs | 705 ---- .../metal2vulkan/src/bind/mesh_arguments.rs | 295 +- .../src/bind/mesh_arguments/tests.rs | 97 - crates/metal2vulkan/src/bind/mod.rs | 131 +- crates/metal2vulkan/src/bind/neutral.rs | 236 +- crates/metal2vulkan/src/bind/neutral/tests.rs | 131 - crates/metal2vulkan/src/bind/plan.rs | 938 ----- crates/metal2vulkan/src/bind/plan/compute.rs | 968 ----- .../src/bind/plan/compute/tests.rs | 60 - .../metal2vulkan/src/bind/plan/resources.rs | 2059 ---------- .../src/bind/plan/resources/tests.rs | 1376 ------- crates/metal2vulkan/src/bind/plan/slots.rs | 856 ---- .../metal2vulkan/src/bind/plan/slots/tests.rs | 872 ---- crates/metal2vulkan/src/bind/rate_map.rs | 4 +- crates/metal2vulkan/src/bind/replay.rs | 5 +- crates/metal2vulkan/src/bind/resident.rs | 174 - .../metal2vulkan/src/bind/resident/tests.rs | 362 -- crates/metal2vulkan/src/bind/state.rs | 1354 +------ crates/metal2vulkan/src/bind/status.rs | 152 +- crates/metal2vulkan/src/bind/table.rs | 133 +- crates/metal2vulkan/src/bind/texel_parts.rs | 11 +- crates/metal2vulkan/src/bind/texel_rows.rs | 66 - crates/metal2vulkan/src/bind/ycbcr_convert.rs | 22 +- .../metal2vulkan/src/bind/ycbcr_in_place.rs | 392 -- crates/metal2vulkan/src/cache/codec.rs | 6 - crates/metal2vulkan/src/cache/digest.rs | 355 -- crates/metal2vulkan/src/cache/digest/tests.rs | 169 - crates/metal2vulkan/src/cache/mod.rs | 301 +- crates/metal2vulkan/src/cache/tests.rs | 522 +-- crates/metal2vulkan/src/device/derive.rs | 3 +- crates/metal2vulkan/src/device/mechanism.rs | 5 - crates/metal2vulkan/src/device/profile.rs | 35 +- .../src/device/tests/mechanism.rs | 16 +- crates/metal2vulkan/src/error/mod.rs | 142 +- .../metal2vulkan/src/lower/access/dynamic.rs | 4 +- crates/metal2vulkan/src/lower/access/tile.rs | 7 +- .../src/lower/arith/tests/bicubic.rs | 12 +- .../src/lower/arith/tests/texel_round.rs | 68 - .../src/lower/arith/texel_round.rs | 161 +- crates/metal2vulkan/src/lower/dispatch.rs | 8 +- .../metal2vulkan/src/lower/dispatch/tests.rs | 4 +- .../metal2vulkan/src/lower/fragment/color.rs | 3 - crates/metal2vulkan/src/lower/push.rs | 4 - .../src/lower/sampler/anisotropic/tests.rs | 120 - .../metal2vulkan/src/lower/sampler/bicubic.rs | 29 +- .../src/lower/sampler/bicubic/routines.rs | 458 +-- .../src/lower/sampler/extended.rs | 60 +- .../src/lower/sampler/face/tests/routines.rs | 21 +- .../src/lower/sampler/heap_raw.rs | 1 - .../src/lower/sampler/in_place.rs | 1093 ----- .../metal2vulkan/src/lower/sampler/linear.rs | 5 +- crates/metal2vulkan/src/lower/sampler/mod.rs | 9 - .../src/lower/sampler/position.rs | 4 +- .../src/lower/sampler/position/tests.rs | 2 +- .../metal2vulkan/src/lower/sampler/select.rs | 260 -- crates/metal2vulkan/src/lower/select.rs | 7 +- crates/metal2vulkan/src/lower/texture/emit.rs | 129 +- crates/metal2vulkan/src/lower/texture/mod.rs | 83 +- crates/metal2vulkan/src/lower/texture/slot.rs | 225 +- crates/metal2vulkan/src/memory/handles.rs | 38 +- crates/metal2vulkan/src/memory/roots.rs | 16 +- crates/metal2vulkan/src/metal/format/mod.rs | 32 +- crates/metal2vulkan/src/metal/mod.rs | 20 - crates/metal2vulkan/src/metal/sampler.rs | 192 +- crates/metal2vulkan/src/metal/texel_format.rs | 272 +- crates/metal2vulkan/src/metal/vertex.rs | 9 - crates/metal2vulkan/src/pipeline/api_tests.rs | 491 +-- crates/metal2vulkan/src/pipeline/artifact.rs | 37 +- .../metal2vulkan/src/pipeline/compile/api.rs | 8 +- .../metal2vulkan/src/pipeline/compile/key.rs | 15 - .../src/pipeline/compile/tests.rs | 627 +-- crates/metal2vulkan/src/pipeline/facts.rs | 101 +- crates/metal2vulkan/src/pipeline/graphics.rs | 6 +- crates/metal2vulkan/src/pipeline/link.rs | 2 +- .../metal2vulkan/src/pipeline/lower_inputs.rs | 25 - crates/metal2vulkan/src/pipeline/mod.rs | 17 +- crates/metal2vulkan/src/pipeline/sym.rs | 62 +- crates/metal2vulkan/src/spirv/ir/module.rs | 4 +- .../metal2vulkan/src/spirv/serialize/mod.rs | 2 +- .../metal2vulkan/src/tests/bind_shape_of.rs | 95 - .../src/tests/constant_blob_footprint.rs | 9 +- .../src/tests/engine_amplification.rs | 686 +--- .../src/tests/engine_argument_tables.rs | 632 +-- .../metal2vulkan/src/tests/engine_atomics.rs | 6 +- .../metal2vulkan/src/tests/engine_binder.rs | 1268 ------ .../src/tests/engine_cross_class.rs | 477 +-- .../src/tests/engine_device_replay.rs | 832 +--- .../metal2vulkan/src/tests/engine_dispatch.rs | 6 +- .../src/tests/engine_draw_bases.rs | 72 +- .../src/tests/engine_dynamic_roots.rs | 185 +- .../src/tests/engine_extended_range.rs | 243 +- .../tests/engine_extended_range/bicubic.rs | 101 +- .../src/tests/engine_extended_range/heap.rs | 296 -- .../src/tests/engine_extended_range/levels.rs | 49 +- .../tests/engine_extended_range/samples.rs | 163 +- .../tests/engine_extended_range/volumes.rs | 32 +- .../src/tests/engine_fragment_depth_clamp.rs | 133 +- .../src/tests/engine_graphics_binder.rs | 2378 ----------- .../metal2vulkan/src/tests/engine_handles.rs | 91 +- .../src/tests/engine_heap_binder.rs | 2689 ------------ .../src/tests/engine_heap_groups.rs | 238 ++ .../src/tests/engine_heap_residency.rs | 156 - .../src/tests/engine_heap_storage_reads.rs | 178 +- .../metal2vulkan/src/tests/engine_identity.rs | 224 +- .../src/tests/engine_image_shapes.rs | 9 +- .../src/tests/engine_imageblock.rs | 240 +- .../src/tests/engine_kernel_stage_in.rs | 1336 +----- .../src/tests/engine_line_band.rs | 163 +- crates/metal2vulkan/src/tests/engine_mesh.rs | 497 +-- .../src/tests/engine_mesh_barriers.rs | 81 +- .../src/tests/engine_multisample.rs | 107 +- .../src/tests/engine_opencl_mode.rs | 210 - .../src/tests/engine_partial_threadgroups.rs | 507 +-- .../src/tests/engine_pointer_memory.rs | 8 +- .../src/tests/engine_pointer_values.rs | 3 +- .../src/tests/engine_primitive_ids.rs | 268 -- .../src/tests/engine_pull_model.rs | 230 +- .../src/tests/engine_ray_tracing.rs | 320 +- .../src/tests/engine_recursion.rs | 108 +- .../src/tests/engine_region_viewports.rs | 95 +- .../src/tests/engine_render_target_slice.rs | 152 +- .../src/tests/engine_rotated_weights.rs | 113 +- .../src/tests/engine_separate_samplers.rs | 113 +- .../src/tests/engine_simd_emulated.rs | 628 +-- .../src/tests/engine_simd_unit_axes.rs | 373 -- .../src/tests/engine_sparse_unmapped.rs | 77 +- .../src/tests/engine_srgb_decode.rs | 505 +-- .../src/tests/engine_swizzled_storage.rs | 478 +-- .../src/tests/engine_tessellation.rs | 251 +- .../src/tests/engine_texel_rows.rs | 310 -- .../src/tests/engine_texture_levels.rs | 429 +- .../src/tests/engine_texture_oob.rs | 203 +- .../src/tests/engine_texture_oob/through.rs | 311 -- .../src/tests/engine_texture_ulong.rs | 95 - .../src/tests/engine_threadgroup_floats.rs | 68 - crates/metal2vulkan/src/tests/engine_tile.rs | 679 +--- .../src/tests/engine_unattached_colors.rs | 125 + .../src/tests/engine_ycbcr_in_place.rs | 1489 ------- .../src/tests/engine_zeroed_colors.rs | 253 +- crates/metal2vulkan/src/tests/fuzz_interp.rs | 5 +- crates/metal2vulkan/src/tests/mod.rs | 10 +- .../src/tests/stage_in_element_bytes.rs | 15 - crates/metal2vulkan/src/vk/draw.rs | 69 - crates/metal2vulkan/src/vk/mod.rs | 9 +- crates/metal2vulkan/tests/api_signatures.tsv | 597 --- crates/metal2vulkan/tests/api_surface.rs | 441 +- docs/API.md | 462 +-- docs/ARCHITECTURE.md | 4 +- docs/HOWTO.md | 8 +- docs/REFUSALS.md | 112 +- docs/VALIDATION.md | 8 +- scripts/api-signatures/signatures.py | 2 +- scripts/refusal-surface/reach.tsv | 8 - scripts/refusal-surface/refusal_surface.py | 31 +- 182 files changed, 1913 insertions(+), 52117 deletions(-) delete mode 100644 crates/metal2vulkan/src/bind/dispatch/tests.rs delete mode 100644 crates/metal2vulkan/src/bind/graphics/tests.rs delete mode 100644 crates/metal2vulkan/src/bind/instantiate.rs delete mode 100644 crates/metal2vulkan/src/bind/instantiate/tests.rs delete mode 100644 crates/metal2vulkan/src/bind/mesh_arguments/tests.rs delete mode 100644 crates/metal2vulkan/src/bind/plan.rs delete mode 100644 crates/metal2vulkan/src/bind/plan/compute.rs delete mode 100644 crates/metal2vulkan/src/bind/plan/compute/tests.rs delete mode 100644 crates/metal2vulkan/src/bind/plan/resources.rs delete mode 100644 crates/metal2vulkan/src/bind/plan/resources/tests.rs delete mode 100644 crates/metal2vulkan/src/bind/plan/slots.rs delete mode 100644 crates/metal2vulkan/src/bind/plan/slots/tests.rs delete mode 100644 crates/metal2vulkan/src/bind/resident.rs delete mode 100644 crates/metal2vulkan/src/bind/resident/tests.rs delete mode 100644 crates/metal2vulkan/src/bind/texel_rows.rs delete mode 100644 crates/metal2vulkan/src/bind/ycbcr_in_place.rs delete mode 100644 crates/metal2vulkan/src/lower/sampler/in_place.rs delete mode 100644 crates/metal2vulkan/src/tests/bind_shape_of.rs delete mode 100644 crates/metal2vulkan/src/tests/engine_binder.rs delete mode 100644 crates/metal2vulkan/src/tests/engine_graphics_binder.rs delete mode 100644 crates/metal2vulkan/src/tests/engine_heap_binder.rs create mode 100644 crates/metal2vulkan/src/tests/engine_heap_groups.rs delete mode 100644 crates/metal2vulkan/src/tests/engine_heap_residency.rs delete mode 100644 crates/metal2vulkan/src/tests/engine_simd_unit_axes.rs delete mode 100644 crates/metal2vulkan/src/tests/engine_texel_rows.rs create mode 100644 crates/metal2vulkan/src/tests/engine_unattached_colors.rs delete mode 100644 crates/metal2vulkan/src/tests/engine_ycbcr_in_place.rs delete mode 100644 crates/metal2vulkan/src/vk/draw.rs diff --git a/AGENTS.md b/AGENTS.md index 530db200e..4d6a02a5c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -10,7 +10,7 @@ manifest at the root) of seven crates under `crates/`: | Crate | Published | What it is | |---|---|---| -| `crates/metal2vulkan` | yes | The translator: Metal AIR to SPIR-V through a Metal-shaped API (device, library, pipelines, binding plans), and the `metal2vulkan` command (feature `cli`) | +| `crates/metal2vulkan` | yes | The translator: Metal AIR to SPIR-V through a Metal-shaped API (device, library, pipelines and their interfaces), and the `metal2vulkan` command (feature `cli`) | | `crates/metal2vulkan-runtime` | yes | The runtime: the Metal API on Vulkan with one path for every device, built only on the translator's public API | | `crates/metal2vulkan-air` | yes | The AIR front end: container, bitstream, bitcode, typed IR, metadata ABI, intrinsics, canonicalization, `graph`, `budget` | | `crates/metal2vulkan-validation` | no | Authored semantic cases, Metal and Vulkan execution, harvest, the corpus index and audits | diff --git a/README.md b/README.md index 9c8879316..3631e1387 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ of a Vulkan device. | Crate | Directory | What it is | |---|---|---| -| `metal2vulkan` | [`crates/metal2vulkan`](crates/metal2vulkan) | The translator. A Metal-shaped API (device, library, pipeline descriptors, binding plans) that compiles compute, render, tessellation, tile and mesh pipelines for a described Vulkan device: SPIR-V per stage, one pipeline layout, fixed-function state, and per-draw descriptor writes and push constants. The `cli` feature builds the `metal2vulkan` command. | +| `metal2vulkan` | [`crates/metal2vulkan`](crates/metal2vulkan) | The translator. A Metal-shaped API (device, library, pipeline descriptors) that compiles compute, render, tessellation, tile and mesh pipelines for a described Vulkan device: SPIR-V per stage, one pipeline layout, fixed-function state, and the interface a consumer binds each draw and dispatch by. The `cli` feature builds the `metal2vulkan` command. | | `metal2vulkan-runtime` | [`crates/metal2vulkan-runtime`](crates/metal2vulkan-runtime) | The Metal API on Vulkan, with one path for every device: devices, memory blocks and buffers, textures, sampler states, command queues, command buffers and events, encoders and pipeline states, run on a Vulkan device through `ash`. It uses only the translator's public API. | | `metal2vulkan-air` | [`crates/metal2vulkan-air`](crates/metal2vulkan-air) | The AIR front end: the metallib container, the bitcode reader, a typed IR, AIR's metadata ABI, intrinsics and canonicalization. For tools that read AIR without translating it. | | `metal2vulkan-validation` | [`crates/metal2vulkan-validation`](crates/metal2vulkan-validation) | Not published. Authored cases run on Metal and on Vulkan and compared, and bounded audits over a private corpus. | @@ -121,7 +121,7 @@ let kernel = FunctionDescriptor::new(library.function("my_kernel")?); let descriptor = ComputePipelineDescriptor::new(StageSource::Function(kernel)); let pipeline = device.compile_compute_pipeline(&descriptor, &Budget::standard())?; // pipeline.stage.spirv, pipeline.layout, pipeline.interface: create the Vulkan objects from these, -// then pipeline.plan(...) and plan.instantiate_dispatch(...) per dispatch. +// and bind each dispatch by the interface, as metal2vulkan-runtime does. ``` [docs/API.md](docs/API.md) walks the whole flow on a runnable example, diff --git a/crates/metal2vulkan-conformance/src/cases/pixel_downscales.rs b/crates/metal2vulkan-conformance/src/cases/pixel_downscales.rs index f15444de7..adf1a459d 100644 --- a/crates/metal2vulkan-conformance/src/cases/pixel_downscales.rs +++ b/crates/metal2vulkan-conformance/src/cases/pixel_downscales.rs @@ -412,8 +412,8 @@ impl Case for PixelDownscales { // These are the kinds a run provoked (see `pixel_samplers`): the device reads the pixel // coordinate divided by the size, not Metal's `1/256` cell of it. A venue that announces // another reads as divergent there until someone names it with a run. The device's own - // filter and sRGB decode (`float-sample-filter`, `srgb-texel-decode`) are native notes the - // suite declares for every case (`crate::replay::NATIVE_NOTES`). + // sRGB decode (`srgb-texel-decode`) is a native note the suite declares for every case + // (`crate::replay::NATIVE_NOTES`). // // **Each is a declaration and loosens nothing.** Each sits at the notices site alone, so // a texel that differs still fails the case wherever it differs. diff --git a/crates/metal2vulkan-conformance/src/cases/pixel_samplers.rs b/crates/metal2vulkan-conformance/src/cases/pixel_samplers.rs index 016899cef..b1c249ff0 100644 --- a/crates/metal2vulkan-conformance/src/cases/pixel_samplers.rs +++ b/crates/metal2vulkan-conformance/src/cases/pixel_samplers.rs @@ -30,8 +30,7 @@ //! reads in its own arithmetic: at a sub-texel step it may read the neighbouring step, which the //! runtime announces on every device (`pixel-sampler-scaling`, and //! `argument-pixel-sampler-scaling` for `arg`). The `slot` site announces it under a nearest -//! state too, as the function does not know the bound state. A device that converts an 8-bit texel to a float -//! its own way announces `float-sample-filter`. +//! state too, as the function does not know the bound state. //! Each notice is declared at the notices site alone, so a texel that differs still fails the case //! where it differs, and is a `known-gaps-rt.tsv` row naming the note. //! diff --git a/crates/metal2vulkan-conformance/src/cases/sampler_crossings.rs b/crates/metal2vulkan-conformance/src/cases/sampler_crossings.rs index 1887b9677..e7027c1c3 100644 --- a/crates/metal2vulkan-conformance/src/cases/sampler_crossings.rs +++ b/crates/metal2vulkan-conformance/src/cases/sampler_crossings.rs @@ -950,11 +950,6 @@ impl Case for SamplerCrossings { // a border colour, a level clamp and a comparison -- so nothing is emulated; what is // declared is what a device announces about its own sampling. // - // Where the device filters a float texture its own way (`float-sample-filter`, the - // address-mode triples and the three mip-filter rows on llvmpipe and the 5080), the note is - // the device's own answer, which the suite declares for every case - // (`crate::replay::NATIVE_NOTES`). - // // The `compare-filters` row's `Depth32Float` texture: on every device (no runtime enables // `VK_EXT_depth_range_unrestricted`) the comparing stage records that its texels hold no // value outside [0, 1] (`restricted-depth-range`). Its depths all lie in [0, 1], so the diff --git a/crates/metal2vulkan-conformance/src/cases/sampler_filtering.rs b/crates/metal2vulkan-conformance/src/cases/sampler_filtering.rs index 49bcb9e1c..360045fe6 100644 --- a/crates/metal2vulkan-conformance/src/cases/sampler_filtering.rs +++ b/crates/metal2vulkan-conformance/src/cases/sampler_filtering.rs @@ -863,11 +863,6 @@ impl Case for SamplerFiltering { // notices site is the whole of the difference. The other families provoke no notice and // declare none, so a notice any of them starts announcing reads as divergent at once. // - // Where the device filters a float texture its own way (`float-sample-filter`, - // `sampler-mip-linear` and `sampler-r-address-modes` on llvmpipe and the 5080), the note - // is the device's own answer, which the suite declares for every case - // (`crate::replay::NATIVE_NOTES`). - // // And every family samples through the runtime sampler at `[[sampler(0)]]`, which the // runtime's pipelines note as scaled (`crate::replay::pixel_sampler_scaling_notice` holds // why). Measured through the rt side on lavapipe, the Radeon 780M and the RX 550: it fired diff --git a/crates/metal2vulkan-conformance/src/degradation.rs b/crates/metal2vulkan-conformance/src/degradation.rs index 4cae3c512..77983c431 100644 --- a/crates/metal2vulkan-conformance/src/degradation.rs +++ b/crates/metal2vulkan-conformance/src/degradation.rs @@ -77,12 +77,8 @@ pub enum Degradation { CubeGradientFootprint, /// `metal2vulkan-degrade-half-texel-conversion`. HalfTexelConversion, - /// `metal2vulkan-degrade-half-sample-filter`. - HalfSampleFilter, /// `metal2vulkan-degrade-srgb-texel-decode`. SrgbTexelDecode, - /// `metal2vulkan-degrade-float-sample-filter`. - FloatSampleFilter, /// `metal2vulkan-degrade-function-storage-assumed`. FunctionStorageAssumed, /// `metal2vulkan-degrade-quads-counted-before-discard`. @@ -213,9 +209,7 @@ impl Degradation { Degradation::RestrictedDepthRange, Degradation::CubeGradientFootprint, Degradation::HalfTexelConversion, - Degradation::HalfSampleFilter, Degradation::SrgbTexelDecode, - Degradation::FloatSampleFilter, Degradation::FunctionStorageAssumed, Degradation::QuadsCountedBeforeDiscard, Degradation::ViewBaseTexelOffset, @@ -314,9 +308,7 @@ impl Degradation { Degradation::RestrictedDepthRange => "metal2vulkan-degrade-restricted-depth-range", Degradation::CubeGradientFootprint => "metal2vulkan-degrade-cube-gradient-footprint", Degradation::HalfTexelConversion => "metal2vulkan-degrade-half-texel-conversion", - Degradation::HalfSampleFilter => "metal2vulkan-degrade-half-sample-filter", Degradation::SrgbTexelDecode => "metal2vulkan-degrade-srgb-texel-decode", - Degradation::FloatSampleFilter => "metal2vulkan-degrade-float-sample-filter", Degradation::FunctionStorageAssumed => "metal2vulkan-degrade-function-storage-assumed", Degradation::QuadsCountedBeforeDiscard => { "metal2vulkan-degrade-quads-counted-before-discard" @@ -423,9 +415,7 @@ impl Degradation { PrecisionNote::RestrictedDepthRange => Degradation::RestrictedDepthRange, PrecisionNote::CubeGradientFootprint => Degradation::CubeGradientFootprint, PrecisionNote::HalfTexelConversion => Degradation::HalfTexelConversion, - PrecisionNote::HalfSampleFilter => Degradation::HalfSampleFilter, PrecisionNote::SrgbTexelDecode => Degradation::SrgbTexelDecode, - PrecisionNote::FloatSampleFilter => Degradation::FloatSampleFilter, PrecisionNote::FunctionStorageAssumed => Degradation::FunctionStorageAssumed, PrecisionNote::QuadsCountedBeforeDiscard => Degradation::QuadsCountedBeforeDiscard, PrecisionNote::ViewBaseTexelOffset => Degradation::ViewBaseTexelOffset, diff --git a/crates/metal2vulkan-conformance/src/replay.rs b/crates/metal2vulkan-conformance/src/replay.rs index 4aa780c80..e13c21b2f 100644 --- a/crates/metal2vulkan-conformance/src/replay.rs +++ b/crates/metal2vulkan-conformance/src/replay.rs @@ -460,9 +460,8 @@ pub fn reads_opaque_black_border(spec: &crate::case::SamplerSpec) -> bool { /// - **texel, vertex and colour conversions**: `device-texel-conversion`, /// `half-texel-conversion`, `srgb-texel-decode`, the device's fixed-function conversion of a /// normalized vertex attribute (`device-vertex-conversion`), `device-color-conversion`; -/// - **sampling and filtering**: `device-sampling`, `device-sample-level`, the device's filter of a -/// generated mipmap chain (`device-filtered-mipmaps`), and Vulkan's Y′CbCr model filtering a -/// two-plane texture's planes read in place (`half-sample-filter`, `float-sample-filter`); +/// - **sampling and filtering**: `device-sampling`, `device-sample-level`, and the device's filter +/// of a generated mipmap chain (`device-filtered-mipmaps`); /// - **logic operations**: the device's `logicOp` on a 10-bit or signed normalized format's own /// codes (`native-logic-operation`, where Metal operates on 10-bit codes widened to 16 bits, and /// reads and stores a signed lowest code as the code above it); @@ -519,8 +518,6 @@ pub const NATIVE_NOTES: &[crate::degradation::Degradation] = { D::DeviceSampling, D::DeviceSampleLevel, D::DeviceFilteredMipmaps, - D::HalfSampleFilter, - D::FloatSampleFilter, D::NativeLogicOperation, D::DeviceRoundedResolve, D::DeviceAlphaCoverage, diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index c59d42832..6fb837d9b 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -3049,9 +3049,8 @@ cache is answered compile-required on both. - a value from the encoder that the function reads and the identity domains do not source ("an encoder value the function reads as F", `F` the `PushField`: a texture buffer's bind offset, `SlotBindOffset`; a texture's level count, `TextureLevels`; the draw's `InstanceCount` or - `BaseVertexInstance`; a stage-in stride, `StageInStride`; a two-plane texture read in place, - `YCbCrInPlace`, which `tests::engine_ycbcr_in_place` asserts; and the others the translator - pushes beside the identity fields): no other test yet; + `BaseVertexInstance`; a stage-in stride, `StageInStride`; and the others the translator + pushes beside the identity fields): no test yet; - a buffer argument not reached through its device address ("a buffer argument not reached through its device address"): no test yet; - a texture argument of a type the identity arrays hold no element of, or whose bound texture's @@ -3066,7 +3065,7 @@ cache is answered compile-required on both. - other state of a bound texture or sampler beyond its resource ID ("state of a bound texture or sampler beyond its resource ID (F)", `F` the `RuntimeFact`), among them an argument buffer's texture that the function only queries (`HeapNumericType`): - `tests::engine_heap_binder`'s + `tests::engine_heap_groups`'s `a_query_only_argument_buffer_texture_is_refused_naming_its_numeric_type` asserts the text for a 2D texture and a cube array, and the golden table holds the refusal's class for `engine/tail_cases`' `tail_heap_cube_queries`; @@ -3484,7 +3483,7 @@ cache is answered compile-required on both. 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, + that reads what a draw does not supply (`DrawInput`: a function table, a pointer or handle translation table, a parameter block past the push range, a push field or bind-time fact the encoder does not fill, 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 diff --git a/crates/metal2vulkan-runtime/src/render.rs b/crates/metal2vulkan-runtime/src/render.rs index e4f2949a5..bb90dfad7 100644 --- a/crates/metal2vulkan-runtime/src/render.rs +++ b/crates/metal2vulkan-runtime/src/render.rs @@ -594,7 +594,7 @@ fn draw_input() -> Error { /// through ([`RenderCompiled::numbered`]), and what a draw of it supplies. /// /// Err: [`Gap::RenderPipeline`] of [`RenderPipelineKind::DrawInput`] for a pipeline that reads -/// what a draw does not supply: a function table, a table the binder builds, a parameter block +/// what a draw does not supply: a function table, a pointer or handle translation table, a parameter block /// longer than a ring chunk, push bytes past the device's push `window` /// (`DeviceProfile::push_window`), a push field or bind-time fact the encoder does not fill, or an /// unnormalized constexpr sampler. diff --git a/crates/metal2vulkan-validation/build.rs b/crates/metal2vulkan-validation/build.rs index 82bb9c879..39d4a2348 100644 --- a/crates/metal2vulkan-validation/build.rs +++ b/crates/metal2vulkan-validation/build.rs @@ -113,8 +113,9 @@ fn main() { // The product's runtime: the modules that act on a compiled pipeline after the compile, whose // behaviour C3's currency holds to `metal2vulkan::cache::RUNTIME_VERSION` beside an artifact's - // content digest. That is the binder (`src/bind`: planning, instantiation, the device replay, - // resident sets, status decoding), the device a run opens and what it enables (`src/device`, + // content digest. That is `src/bind` (argument-buffer layouts, the texel decoders, rate maps, + // indirect-command records, the device replay's helpers, the heap classes and status words), + // the device a run opens and what it enables (`src/device`, // `src/ash_interop`), the Vulkan and Metal vocabularies the runtime maps (`src/vk`, // `src/metal`, and the AIR front end's `metal2vulkan-air/src/metal`, whose `MTLDataType` // `metal` re-exports), the record and table formats it writes (indirect commands, the rate and @@ -127,7 +128,7 @@ fn main() { // encode the YCbCr write takes from `air.pack`'s lowering (`src/lower/arith/pack.rs`), and // half-float conversion. The translator's paths above are below its crate (`metal2vulkan/src/...`). Each // path is a product file below the workspace's crates/ directory, this crate's parent: those - // listed here and the binder's Rust sources under `metal2vulkan/src/bind/`, test modules aside + // listed here and the Rust sources under `metal2vulkan/src/bind/`, test modules aside // (`runtime_files`, so a file added there joins), all sorted as strings. The guard test in // `candidate::engine::artifact` requires this hash to be the one validation pins // (`runtime-sources.sha256`), and the inputs to be closed over the module files their non-test @@ -182,7 +183,6 @@ fn main() { "metal2vulkan/src/metal/vertex.rs", "metal2vulkan/src/pipeline/table.rs", "metal2vulkan/src/pipeline/tile_map.rs", - "metal2vulkan/src/vk/draw.rs", "metal2vulkan/src/vk/generated.rs", "metal2vulkan/src/vk/mod.rs", "metal2vulkan/src/vk/structs.rs", @@ -227,7 +227,7 @@ fn crate_files(root: &Path) -> Vec { /// Every Rust source below `relative` under `product` but test modules (a `tests` directory, a /// `tests.rs` or `*_tests.rs` file) and hidden files, pushed as paths relative to `product` with -/// `/` separators: the binder's (`metal2vulkan/src/bind/`), whose non-test code reads no data file +/// `/` separators: those of `metal2vulkan/src/bind/`, whose non-test code reads no data file /// (its `.txt` files are its tests' measured answers). Cargo reruns this script when anything /// under the directory changes, so a file added there joins the runtime's inputs. fn runtime_files(product: &Path, relative: &Path, output: &mut Vec) { diff --git a/crates/metal2vulkan-validation/runtime-sources.sha256 b/crates/metal2vulkan-validation/runtime-sources.sha256 index 43683ca92..b11a940b0 100644 --- a/crates/metal2vulkan-validation/runtime-sources.sha256 +++ b/crates/metal2vulkan-validation/runtime-sources.sha256 @@ -1 +1 @@ -d4a8dbf255778b56f0fc58f50a8556378c56517877849831693afc7ee8721453 +2cd56ba56f3577740c3c7f9d88157c79eb4d0c751a739358d48e877b0dd881ed diff --git a/crates/metal2vulkan-validation/src/candidate/engine/artifact/tests.rs b/crates/metal2vulkan-validation/src/candidate/engine/artifact/tests.rs index ceda0df91..20b442cc2 100644 --- a/crates/metal2vulkan-validation/src/candidate/engine/artifact/tests.rs +++ b/crates/metal2vulkan-validation/src/candidate/engine/artifact/tests.rs @@ -109,7 +109,7 @@ fn the_runtime_sources_are_the_committed_ones() { let compile = "compile-time translation, reached only from the compile-time parts of mixed runtime files; what it produces is in the pipeline the artifact digests"; let values = "the compiled pipeline's value types; the artifact digests their values"; - let spirv = "the SPIR-V builder: the binder's files reach it only through the merged draw's reads (bind/replay), which the compile emits into the merged variant; what they emit is in the pipeline the artifact digests"; + let spirv = "the SPIR-V builder: the bind module's files reach it only through the merged draw's reads (bind/replay), which the compile emits into the merged variant; what they emit is in the pipeline the artifact digests"; let packed = "compile-time translation, reached only through lower/arith/pack.rs's pack and unpack intrinsics, which the compile emits; the runtime's YCbCr write takes that file's sRGB encode (srgb_encode), which reaches none of it"; let not_runtime = BTreeMap::from([ ("metal2vulkan-air/src/abi/mod.rs", compile), @@ -119,12 +119,11 @@ fn the_runtime_sources_are_the_committed_ones() { ("metal2vulkan-air/src/intrinsics/mod.rs", packed), ("metal2vulkan-air/src/ir/mod.rs", compile), ("metal2vulkan-air/src/lib.rs", compile), - ("metal2vulkan/src/cache/digest.rs", "the content digest, which defines the artifact rather than acting on it"), - ("metal2vulkan/src/cache/mod.rs", "the plan's specialization and variant keys, whose values the plan digest holds, and RUNTIME_VERSION itself, which cannot be among the sources it versions"), + ("metal2vulkan/src/cache/mod.rs", "the `Hash256` re-export device/derive.rs names a profile's fingerprint with, and RUNTIME_VERSION itself, which cannot be among the sources it versions"), ("metal2vulkan/src/error/mod.rs", "the error vocabulary: the runtime's code decides which error a run reports, and a record keeps the error as reported"), ("metal2vulkan/src/lower/access/imageblock.rs", compile), ("metal2vulkan/src/lower/access/mod.rs", "compile-time translation, reached only from lower/dispatch.rs's kernel plan, which asks `identity` whether the profile takes the identity domains; what it produces is in the pipeline the artifact digests"), - ("metal2vulkan/src/lower/access/tile.rs", "compile-time translation, reached only from the compile-time parts of mixed runtime files; what it produces is in the pipeline the artifact digests; the tile staging format reaches a run through the plan"), + ("metal2vulkan/src/lower/access/tile.rs", "compile-time translation, reached only from the compile-time parts of mixed runtime files; what it produces is in the pipeline the artifact digests"), ("metal2vulkan/src/lower/arith/aggregate.rs", compile), // The block decode (`bind/block_decode.rs`) and its exact division // (`lower/arith/exact_division.rs`) reach the numeric forms and the constant emission at @@ -138,8 +137,6 @@ fn the_runtime_sources_are_the_committed_ones() { ("metal2vulkan/src/lower/mesh/mod.rs", "compile-time translation, reached only from the compile-time part of lower/dispatch.rs (plan_kernel's mesh wrapper builtins) and as the parent of its work-buffer layout (lower/mesh/work.rs, an input); what it produces is in the pipeline the artifact digests"), ("metal2vulkan/src/lower/push.rs", "the push window's lowering, reached only from device/derive.rs, which reads `LEAST_BYTES`, Vulkan's least maxPushConstantsSize, to refuse a description below it before any pipeline exists, and from device/profile.rs, whose `push_window` reads `MOST_BYTES` to cap the device's window; what the lowering makes of the window is in the pipeline the artifact digests"), ("metal2vulkan/src/lower/select.rs", compile), - ("metal2vulkan/src/lower/simd/divergent.rs", "compile-time translation (the predicated walk); the runtime reads only VOTE_BYTES, the vote word's size, which the compile also adds to the static threadgroup length the artifact reports, so a change to it moves the artifact digest"), - ("metal2vulkan/src/lower/simd/workgroup.rs","binding-plan construction; the artifact digests the plan it makes (the workgroup arena size)"), ("metal2vulkan/src/memory/abi_index.rs", compile), ("metal2vulkan/src/memory/contain.rs", "the containment encoding, a function of the device profile (the venue's profile key holds it), shared by compile and the vertex layout"), ("metal2vulkan/src/memory/leaf.rs", compile), @@ -148,7 +145,6 @@ fn the_runtime_sources_are_the_committed_ones() { ("metal2vulkan/src/memory/union_find.rs", compile), ("metal2vulkan/src/memory/views.rs", compile), ("metal2vulkan/src/metal/resource_word.rs", "the gpuResourceID texture word of the runtime's ID spec (docs/RESOURCE-ID.md); the product's run-time files reach it only as a child of metal/mod.rs and call none of it"), - ("metal2vulkan/src/pipeline/artifact.rs", values), ("metal2vulkan/src/pipeline/compile.rs", compile), ("metal2vulkan/src/pipeline/compile/key.rs", "the compile's cache key, which the artifact digest excludes"), ("metal2vulkan/src/pipeline/compile/partition.rs", "compile-time translation, reached only from the compile-time part of lower/dispatch.rs (plan_kernel's grid edge: whether a kernel observes its threadgroup partition, decided from its AIR); what it produces is in the pipeline the artifact digests"), @@ -156,12 +152,9 @@ fn the_runtime_sources_are_the_committed_ones() { ("metal2vulkan/src/pipeline/facts.rs", values), ("metal2vulkan/src/pipeline/graphics.rs", "the compiled pipeline's value types; the artifact digests their values (the graphics state)"), ("metal2vulkan/src/pipeline/interface.rs", values), - ("metal2vulkan/src/pipeline/layout.rs", values), ("metal2vulkan/src/pipeline/lower_inputs.rs", "the compiled pipeline's value types; the artifact digests their values (the storage image classes)"), ("metal2vulkan/src/pipeline/mod.rs", values), - ("metal2vulkan/src/pipeline/stage_io.rs", "the compiled pipeline's value types; the artifact digests their values (a kernel's `[[stage_in]]` fetches, which its binding plan carries for the stage-in reach the binder decides)"), ("metal2vulkan/src/pipeline/sym.rs", "the compiled pipeline's value types; the artifact digests their values (slots, push fields, handle classes)"), - ("metal2vulkan/src/pipeline/vertex.rs", "the compiled pipeline's value types; the artifact digests their values (the vertex layout)"), ("metal2vulkan/src/spirv/builder/constructs.rs", spirv), ("metal2vulkan/src/spirv/builder/mod.rs", spirv), ("metal2vulkan/src/spirv/error.rs", spirv), diff --git a/crates/metal2vulkan-validation/src/candidate/platform/graphics_pipeline.rs b/crates/metal2vulkan-validation/src/candidate/platform/graphics_pipeline.rs index 9c8683130..0485d3c37 100644 --- a/crates/metal2vulkan-validation/src/candidate/platform/graphics_pipeline.rs +++ b/crates/metal2vulkan-validation/src/candidate/platform/graphics_pipeline.rs @@ -1,6 +1,5 @@ -//! The Vulkan graphics pipeline of an engine `RenderPipeline`: one builder that L4 driver -//! acceptance ([`super::acceptance`]) and the render executor ([`super::render`]) share, so a -//! pipeline the sweep creates is the pipeline the executor draws with. +//! The Vulkan graphics pipeline of an engine `RenderPipeline`, as L4 driver acceptance +//! ([`super::acceptance`]) creates it. //! //! Everything comes from the artifact's graphics state and vertex input: the render pass //! ([`create_render_pass`]: every color attachment at its Metal index, each framebuffer-fetch diff --git a/crates/metal2vulkan-validation/src/executor_contract/render_target_array.rs b/crates/metal2vulkan-validation/src/executor_contract/render_target_array.rs index 5e8917dd6..d2428fdf2 100644 --- a/crates/metal2vulkan-validation/src/executor_contract/render_target_array.rs +++ b/crates/metal2vulkan-validation/src/executor_contract/render_target_array.rs @@ -1,6 +1,6 @@ //! The render pass's render target array length both executors draw a case with: the Metal oracle's -//! `MTLRenderPassDescriptor.renderTargetArrayLength` and the engine candidate's -//! `BindState::render_target_array_length`, derived once, so the two agree. +//! `MTLRenderPassDescriptor.renderTargetArrayLength` and the runtime candidate's +//! `RenderPassDescriptor::render_target_array_length`, derived once, so the two agree. use crate::air::meta::{parse_air_fragment_meta, parse_air_vertex_meta, FragRole, VertOutRole}; use crate::case::Stage; diff --git a/crates/metal2vulkan-validation/src/executor_contract/stage_inputs.rs b/crates/metal2vulkan-validation/src/executor_contract/stage_inputs.rs index bac2c46e0..a0da67767 100644 --- a/crates/metal2vulkan-validation/src/executor_contract/stage_inputs.rs +++ b/crates/metal2vulkan-validation/src/executor_contract/stage_inputs.rs @@ -1,7 +1,7 @@ //! How both executors fetch a kernel case's `[[stage_in]]` data: the Metal oracle's //! `MTLStageInputOutputDescriptor` and `setStageInRegion:`, and the engine candidate's -//! `ComputePipelineDescriptor::stage_input` and `BindState::stage_in_region`, derived once here, so -//! the two agree. +//! `ComputePipelineDescriptor::stage_input` and stage-in region, derived once here, so the two +//! agree. //! //! Each authored stage input's data is its own buffer at the slot the shared slot rule gives its //! location ([`stage_input_slots`]), read as the case's format at offset 0 with the case's stride, diff --git a/crates/metal2vulkan-validation/src/executor_contract/tessellation.rs b/crates/metal2vulkan-validation/src/executor_contract/tessellation.rs index b8905035c..c7a756c43 100644 --- a/crates/metal2vulkan-validation/src/executor_contract/tessellation.rs +++ b/crates/metal2vulkan-validation/src/executor_contract/tessellation.rs @@ -1,8 +1,8 @@ //! How both executors draw a tessellation case: the Metal oracle's `MTLRenderPipelineDescriptor` //! tessellation fields, `setTessellationFactorBuffer:offset: instanceStride:`, `setCullMode:`, and //! `drawPatches:...`, and the engine candidate's `RenderPipelineDescriptor::tessellation`, -//! `BindState::tessellation_factors`, cull mode, and `DrawCall::Patches`, derived once here, so the -//! two agree. +//! tessellation factor buffer, cull mode, and `DrawCall::Patches`, derived once here, so the two +//! agree. //! //! A case's patches are drawn from patch 0 with no patch index buffer, as many instances as the //! case states from base instance 0, `numberOfPatchControlPoints` the function's diff --git a/crates/metal2vulkan-validation/src/observation_contract/comparison.rs b/crates/metal2vulkan-validation/src/observation_contract/comparison.rs index 78c44e4c8..683aba2ac 100644 --- a/crates/metal2vulkan-validation/src/observation_contract/comparison.rs +++ b/crates/metal2vulkan-validation/src/observation_contract/comparison.rs @@ -188,15 +188,9 @@ impl UlpTable { /// - `HalfTexelConversion`: unbounded: a format whose conversion to `half` is not measured keeps /// the device's quantize of its `f32` texel, so a lane can differ from Metal's by any amount (an /// sRGB texel's decode). -/// - `HalfSampleFilter`: unbounded: a filtered `half` sample of a two-plane YCbCr texture whose -/// planes the function reads in place blends the codes by Vulkan's Y′CbCr model, off Metal's -/// sum on the format's grid, which no tolerance is derived from. /// - `SrgbTexelDecode`: unbounded: an 8-bit sRGB texel the device decodes where Metal decodes its /// raw code through a twelve-bit table; Vulkan bounds the device's decode only by its precision /// rules, and Metal's `float` gathers of sRGB texels are not measured. -/// - `FloatSampleFilter`: unbounded: a filtered `float` sample of a two-plane YCbCr texture whose -/// planes the function reads in place blends the codes by Vulkan's Y′CbCr model, off Metal's -/// sum on the format's grid, which no tolerance is derived from. /// - `QuadsCountedBeforeDiscard`: unbounded: a non-quad simdgroup operation before a discard, in a /// shape whose placement by Metal's compiler is not known, takes, among its lanes, the quads the /// discard drops, which moves a count, a ballot, or a reduction by whole lanes. @@ -291,9 +285,7 @@ pub fn allowance(note: PrecisionNote) -> Allowance { | N::RestrictedDepthRange | N::CubeGradientFootprint | N::HalfTexelConversion - | N::HalfSampleFilter | N::SrgbTexelDecode - | N::FloatSampleFilter | N::QuadsCountedBeforeDiscard | N::DeviceInterpolation | N::ExtrapolatedInterpolation diff --git a/crates/metal2vulkan-validation/src/observation_contract/comparison/tests.rs b/crates/metal2vulkan-validation/src/observation_contract/comparison/tests.rs index c670d9945..eaede1eb2 100644 --- a/crates/metal2vulkan-validation/src/observation_contract/comparison/tests.rs +++ b/crates/metal2vulkan-validation/src/observation_contract/comparison/tests.rs @@ -60,9 +60,7 @@ fn every_precision_note_has_its_table_row() { (N::RestrictedDepthRange, Allowance::Unbounded), (N::CubeGradientFootprint, Allowance::Unbounded), (N::HalfTexelConversion, Allowance::Unbounded), - (N::HalfSampleFilter, Allowance::Unbounded), (N::SrgbTexelDecode, Allowance::Unbounded), - (N::FloatSampleFilter, Allowance::Unbounded), (N::FunctionStorageAssumed, Allowance::Recorded), (N::ViewBaseTexelOffset, Allowance::Recorded), (N::DeviceColorConversion, Allowance::Recorded), diff --git a/crates/metal2vulkan/examples/api_preview.rs b/crates/metal2vulkan/examples/api_preview.rs index daf0439e9..ba5317478 100644 --- a/crates/metal2vulkan/examples/api_preview.rs +++ b/crates/metal2vulkan/examples/api_preview.rs @@ -10,33 +10,26 @@ //! fixtures are committed as LLVM text, so the example assembles them with `llvm-as` (LLVM 21 or //! newer) from `PATH` first, as a consumer holding `.ll` would. //! -//! It compiles a kernel for the committed `moltenvk-m3` profile under the resident-table domains, -//! the policy the translator's binder plans (and the same kernel as a bare -//! module's entry, linked alone), prints its pipeline interface, layout, and binding plan, -//! instantiates one dispatch, round-trips the pipeline through its cache encoding, answers a -//! pipeline-input request, shows a typed refusal on `runtime-floor`, dispatches a kernel with -//! `[[stage_in]]`, and compiles, plans, and draws a render pipeline and a tessellation pipeline. `tests/api_preview_example.rs` runs it in the gate and checks that -//! every code block of `docs/API.md` is quoted from it. +//! It compiles a kernel for the committed `moltenvk-m3` profile under the runtime's policy (and the +//! same kernel as a bare module's entry, linked alone), prints its pipeline interface and layout, +//! round-trips the pipeline through its cache encoding, answers a pipeline-input request, shows a +//! typed refusal on `runtime-floor`, compiles a kernel with `[[stage_in]]`, and compiles a render +//! pipeline and a tessellation pipeline. `tests/api_preview_example.rs` runs it in the gate and +//! checks that every code block of `docs/API.md` is quoted from it. use std::path::{Path, PathBuf}; use std::process::Command; -use metal2vulkan::bind::{ - BindState, BoundBuffer, BoundSampler, BoundTexture, Dispatch, DrawCall, SamplerDescriptor, - StageInRegion, StageTable, TessellationFactorBuffer, TessellationFactors, TextureFacts, -}; use metal2vulkan::cache::PipelineArtifact; use metal2vulkan::device::{Device, DeviceDescription, DevicePolicy}; -use metal2vulkan::error::{BindError, Error, Needs, RuntimeInput}; +use metal2vulkan::error::{Error, Needs, RuntimeInput}; use metal2vulkan::library::{ CompiledFunction, FunctionConstantValue, FunctionConstantValues, Library, }; -use metal2vulkan::metal::{ - AttributeFormat, DataType, PixelFormat, StepFunction, TextureType, VertexFormat, -}; +use metal2vulkan::metal::{AttributeFormat, DataType, PixelFormat, StepFunction, VertexFormat}; use metal2vulkan::pipeline::{ ColorAttachmentDescriptor, ComputePipeline, ComputePipelineDescriptor, EntryDescriptor, - EntryRef, FunctionDescriptor, LoweringInputs, RenderPipelineDescriptor, Stage, + EntryRef, FunctionDescriptor, LoweringInputs, RenderPipelineDescriptor, StageInputAttributeDescriptor, StageInputDescriptor, StageInputLayoutDescriptor, StageSource, TessellationDescriptor, VertexAttributeDescriptor, VertexBufferLayoutDescriptor, VertexDescriptor, @@ -77,7 +70,7 @@ fn profile_json(stem: &str) -> Result { } /// The device a runtime compiles for on committed profile `stem`: the default policy, the -/// identity domains. The runtime binds what such a device's pipelines push itself. +/// identity domains. fn runtime_device(stem: &str) -> Result { let json = profile_json(stem)?; let description = DeviceDescription::from_khronos_json(&json, None)?; @@ -85,42 +78,14 @@ fn runtime_device(stem: &str) -> Result { Ok(device) } -/// The tour's device for committed profile `stem`: the resident-table domains, the policy the -/// translator's binder plans (step 5 and the stage-in, render and tessellation walks), which a -/// runtime's device does not take ([`runtime_device`]). -fn committed_device(stem: &str) -> Result { - let json = profile_json(stem)?; - let description = DeviceDescription::from_khronos_json(&json, None)?; - let device = Device::from_queries(description, DevicePolicy::RESIDENT_TABLES)?; - Ok(device) -} - -/// A buffer bound at `offset` in a `length`-byte allocation whose Metal `gpuAddress` and Vulkan -/// device address are both `0x1_0000`, as the runtime makes them. -fn buffer(length: u64, offset: u64) -> BoundBuffer { - BoundBuffer::Buffer { - length, - offset, - gpu_address: 0x1_0000, - device_address: Some(0x1_0000), - attribute_stride: None, - } -} - /// Lowercase hex of a digest. fn hex(digest: &[u8]) -> String { digest.iter().map(|b| format!("{b:02x}")).collect() } pub fn main() -> Result<()> { - // 1. A device: what the consumer enabled, and its policy. A runtime's device takes the - // default policy; the tour's takes the resident-table domains, which its binding plans need. - let runtime = runtime_device("moltenvk-m3")?; - println!( - "runtime's device: profile {}", - hex(&runtime.profile().fingerprint()) - ); - let device = committed_device("moltenvk-m3")?; + // 1. A device: what the consumer enabled, and its policy, the runtime's default. + let device = runtime_device("moltenvk-m3")?; let enables = device.required_enables(); println!( "device: profile {}, {} features and {} extensions to enable", @@ -193,43 +158,7 @@ pub fn main() -> Result<()> { println!(" precision notes: {:?}", pipeline.stage.precision_notes); println!(" Metal info: {:?}", pipeline.metal_info); - // 5. What is bound (Metal-shaped), the plan for its shape, and one dispatch. - let mut table = StageTable::default(); - table.buffers.insert(0, buffer(4096, 0)); - let facts = TextureFacts::new(TextureType::Type2D, PixelFormat::RGBA8Unorm); - let texture = BoundTexture::Texture { - facts, - resource_id: None, - }; - table.textures.insert(0, texture); - let sampler = BoundSampler::new(SamplerDescriptor::new()); - table.samplers.insert(0, sampler); - let mut state = BindState::default(); - state.stages.insert(Stage::Kernel, table); - - let plan = pipeline.plan(&device, &state.shape())?; - assert!(plan.variant.is_empty(), "this shape needs no other variant"); - for write in &plan.descriptors { - println!( - " write set {} binding {}[{}] {:?}: {:?}", - write.set, write.binding, write.array_element, write.ty, write.source - ); - } - let dispatch = Dispatch::Threads { - threads: [100, 1, 1], - threads_per_group: [32, 1, 1], - }; - let commands = plan.instantiate_dispatch(&state, &dispatch)?; - for region in &commands.regions { - println!( - " region: {:?} groups, specialization {:?}", - region.group_count, region.specialization - ); - } - println!(" descriptor ranges: {:?}", commands.descriptor_ranges); - println!(" push holes: {:?}", commands.push_holes); - - // 6. The cache: a pipeline encodes under its key and decodes for the same device. + // 5. The cache: a pipeline encodes under its key and decodes for the same device. let bytes = pipeline.to_bytes(); let cached = ComputePipeline::from_bytes_for_key(&bytes, &pipeline.key, &device)?; assert_eq!(cached, pipeline); @@ -255,7 +184,7 @@ pub fn main() -> Result<()> { bytes.len() ); - // 7. A function-constant value, supplied by index. A constant left undefined compiles too, as + // 6. A function-constant value, supplied by index. A constant left undefined compiles too, as // Metal's does: `is_function_constant_defined` names it false, and a value of it alone is zero. let library = Library::from_air(&fixture_bitcode("kernel_vector_function_constant")?)?; let function = library.function("kernel_vector_function_constant")?; @@ -270,9 +199,9 @@ pub fn main() -> Result<()> { assert_ne!(undefined.key, specialized.key); println!("function constant supplied: {:?}", specialized.key); - // 8. A typed refusal: fragment function `sample_min_lod` clamps its level of detail, which + // 7. A typed refusal: fragment function `sample_min_lod` clamps its level of detail, which // needs `shaderResourceMinLod`; the `runtime-floor` profile lacks it. - let floor = committed_device("runtime-floor")?; + let floor = runtime_device("runtime-floor")?; let min_lod = FunctionDescriptor::new(sampling.function("sample_min_lod")?); match floor.compile_function(&min_lod, &LoweringInputs::new(), &Budget::standard()) { Err(Error::Unsupported(refusal)) => match (&refusal.feature, &refusal.needs) { @@ -290,8 +219,8 @@ pub fn main() -> Result<()> { tessellation(&device) } -/// A kernel with `[[stage_in]]` on `device`: the stage-input descriptor it asks for, the kernel -/// compiled on its own under it, and a dispatch that needs the encoder's stage-in region. +/// A kernel with `[[stage_in]]` on `device`: the stage-input descriptor it asks for, and the kernel +/// compiled on its own under it. fn stage_in(device: &Device, budget: &Budget) -> Result<()> { let library = Library::from_air(&fixture_bitcode("kernel_stage_in")?)?; let kernel = FunctionDescriptor::new(library.function("stage_in_region")?); @@ -318,30 +247,10 @@ fn stage_in(device: &Device, budget: &Budget) -> Result<()> { let mut linked = descriptor.clone(); linked.kernel = StageSource::Compiled(compiled); assert_eq!(device.compile_compute_pipeline(&linked, budget)?, pipeline); - - let mut table = StageTable::default(); - table.buffers.insert(0, buffer(4096, 0)); - table.buffers.insert(1, buffer(256, 0)); - let mut state = BindState::default(); - state.stages.insert(Stage::Kernel, table); - let plan = pipeline.plan(device, &state.shape())?; - let dispatch = Dispatch::Threads { - threads: [64, 1, 1], - threads_per_group: [32, 1, 1], - }; - match plan.instantiate_dispatch(&state, &dispatch) { - Err(BindError::MissingStageInRegion) => {} - other => return Err(format!("expected a missing stage-in region: {other:?}").into()), - } - state.stage_in_region = Some(StageInRegion::new([0, 0, 0], [64, 1, 1])); - let commands = plan.instantiate_dispatch(&state, &dispatch)?; - for region in &commands.regions { - println!(" region push constants: {:?}", region.push_constants); - } Ok(()) } -/// A render pipeline on `device`: compile, plan, and one draw. +/// A render pipeline on `device`: its stages and its vertex input. fn render(device: &Device) -> Result<()> { let library = Library::from_air(&fixture_bitcode("stage_io")?)?; let vertex = FunctionDescriptor::new(library.function("stage_io_vertex")?); @@ -378,27 +287,10 @@ fn render(device: &Device) -> Result<()> { ); } println!(" vertex input: {:?}", pipeline.vertex_input); - - let mut table = StageTable::default(); - table.buffers.insert(0, buffer(24 * 64, 0)); - table.buffers.insert(1, buffer(256, 16)); - let mut state = BindState::default(); - state.stages.insert(Stage::Vertex, table); - let plan = pipeline.plan(device, &state.shape())?; - let draw = DrawCall::Primitives { - vertex_start: 0, - vertex_count: 6, - instance_count: 1, - base_instance: 0, - }; - let commands = plan.instantiate_draw(&state, &draw)?; - println!(" draw: {:?}", commands.draw); - println!(" vertex buffer offsets: {:?}", commands.buffer_offsets); - println!(" push constants: {:?}", commands.push_constants); Ok(()) } -/// A tessellation pipeline on `device`: a post-tessellation vertex function, and a patch draw. +/// A tessellation pipeline on `device`: a post-tessellation vertex function. fn tessellation(device: &Device) -> Result<()> { let library = Library::from_air(&fixture_bitcode("tessellation")?)?; let vertex = FunctionDescriptor::new(library.function("tess_quad_buffer")?); @@ -408,25 +300,5 @@ fn tessellation(device: &Device) -> Result<()> { let stages: Vec<_> = pipeline.stages.iter().map(|stage| stage.stage).collect(); println!("tessellation pipeline {:?}: {stages:?}", pipeline.key); println!(" {:?}", pipeline.graphics.tessellation); - - let mut table = StageTable::default(); - table.buffers.insert(0, buffer(4096, 0)); - let mut state = BindState::default(); - state.stages.insert(Stage::Vertex, table); - let factors = TessellationFactorBuffer::new(4096, 0, 0); - state.tessellation_factors = TessellationFactors::new(Some(factors), 1.0); - let plan = pipeline.plan(device, &state.shape())?; - let draw = DrawCall::Patches { - control_points: 4, - patch_start: 0, - patch_count: 16, - patch_index: None, - instance_count: 1, - base_instance: 0, - control_point_index: None, - }; - let commands = plan.instantiate_draw(&state, &draw)?; - println!(" draw: {:?}", commands.draw); - println!(" push constants: {:?}", commands.push_constants); Ok(()) } diff --git a/crates/metal2vulkan/src/api_reference.md b/crates/metal2vulkan/src/api_reference.md index 89c514d82..9b2c9bd2d 100644 --- a/crates/metal2vulkan/src/api_reference.md +++ b/crates/metal2vulkan/src/api_reference.md @@ -1,7 +1,7 @@ metal2vulkan: the API (reference) -Metal AIR in; Vulkan SPIR-V, pipeline layouts, and per-draw binding instructions out, through an -API shaped like Metal's object lifecycle. The consumer never parses AIR, never parses or patches +Metal AIR in; Vulkan SPIR-V, pipeline layouts, and the interface a runtime binds them by out, +through an API shaped like Metal's object lifecycle. The consumer never parses AIR, never parses or patches SPIR-V, never infers binding numbers from Metal indices, and never classifies errors by message text. @@ -23,8 +23,8 @@ This reference shows exactly the API's frozen surface. A walkthrough with a runn `new`, `Default`, or their constants and assign fields, and match enums with a wildcard arm. The exceptions are exhaustive by design, because their fields are their identity or are fixed by Vulkan: [`pipeline::SlotRef`], [`pipeline::ResourceSlot`], [`pipeline::AirUserKey`], - [`pipeline::VaryingKey`], [`device::ApiVersion`], [`device::OpBits`], [`bind::StatusBits`], - [`bind::ExecutionStatus`], [`vk::ComponentMapping`], and [`vk::SpecializationMapEntry`]. + [`pipeline::VaryingKey`], [`device::ApiVersion`], [`device::OpBits`], + [`vk::ComponentMapping`], and [`vk::SpecializationMapEntry`]. - **Semver.** The crate is `0.x`: a breaking change bumps the minor version. - **Everything else is internal.** An item this reference does not show is not API: every submodule of `library`, `pipeline`, `bind`, and `device` (name a type by its root path, @@ -45,18 +45,13 @@ This reference shows exactly the API's frozen surface. A walkthrough with a runn [`pipeline::RenderPipelineDescriptor`]) and compile it with [`device::Device::compile_compute_pipeline`] or [`device::Device::compile_render_pipeline`]: SPIR-V per stage, one pipeline layout, vertex input and fixed-function state, and the - [`pipeline::PipelineInterface`]. -4. **A plan.** Describe what is bound, keyed by Metal slot ([`bind::BindState`]), and plan the - pipeline for its shape ([`bind::BindingPlan`]): the descriptor writes, vertex buffers, and - resource uses. Memoize it per shape. -5. **Commands.** Instantiate the plan per dispatch or draw ([`bind::DispatchCommands`], - [`bind::DrawCommands`]): descriptor ranges, push-constant bytes, table uploads, and the Vulkan - dispatches or draw to record. The binder never calls Vulkan. -6. **Caching.** Keys are known before compiling ([`cache::PipelineKey`], + [`pipeline::PipelineInterface`] (what each Metal slot binds as), and the bind-time state the + pipeline depends on (its `dependencies`), which a runtime binds, pushes or specializes. +4. **Caching.** Keys are known before compiling ([`cache::PipelineKey`], [`library::FunctionCompileKey`]), and artifacts encode and decode through [`cache::PipelineArtifact`]. The crate keeps no cache. -Failures are typed ([`error::Error`], [`error::BindError`]): a refusal +Failures are typed ([`error::Error`]): a refusal ([`error::Unsupported`]) names the Metal feature and what would make it translatable, and a pipeline input the compile needs ([`error::RuntimeInput`]) is asked for, never guessed. Where an output accepts a documented difference from Metal, its stage says so @@ -72,8 +67,7 @@ The library needs none of them. - `ash`: `From` conversions between [`vk`] values and `ash::vk`, and `DeviceDescription::query`, which reads a physical device into a description (`ash_interop`). - `serde`: `Serialize` and `Deserialize` on the plain-data values: device descriptions and - policies, bind states and shapes, plans and commands, pipeline interfaces and layouts, and the - Metal and Vulkan enums. Not on artifacts, which have their own encoding + policies, pipeline interfaces and layouts, and the Metal and Vulkan enums. Not on artifacts, which have their own encoding ([`cache::PipelineArtifact`]), nor on descriptors that hold a library. - `cli`: the `metal2vulkan` command-line tool (`cargo install metal2vulkan --features cli`), which compiles one pipeline with this API and writes its SPIR-V. It enables `serde` and adds nothing diff --git a/crates/metal2vulkan/src/bind/dispatch.rs b/crates/metal2vulkan/src/bind/dispatch.rs index cb12b40a6..0898abb37 100644 --- a/crates/metal2vulkan/src/bind/dispatch.rs +++ b/crates/metal2vulkan/src/bind/dispatch.rs @@ -1,129 +1,7 @@ -//! Compute dispatches and their instantiation: [`BindingPlan::instantiate_dispatch`]. -//! -//! **Regions**. A Metal dispatch becomes one or more regular Vulkan dispatches, each of an exact -//! local size, so Metal's `threads_per_threadgroup` and barrier semantics hold: -//! -//! - `Threadgroups` within `maxComputeWorkGroupCount`, and every `ThreadgroupsIndirect`, is one -//! region with `MultiRegion = 0`: the grid comes from `NumWorkgroups`, so GPU-written counts -//! need no CPU read (an indirect region's group counts are never an input of the plan). On the -//! plan of a partial-threadgroups variant a `Threadgroups` region has `MultiRegion = 1`, as that -//! plan's `Threads` regions do, so one `VkPipeline` of a threadgroup size runs both. -//! - `Threads` with a grid that is not a multiple of the threadgroup size becomes up to eight -//! regions per group-count chunk: the interior, and per axis an edge of one threadgroup of the -//! remaining threads, all with `MultiRegion = 1`, so the grid and the region base come from the -//! `DispatchRegion` push field. On the plan of a flat variant ([`VariantKey::flat_grid`]) it is -//! one region instead, of the dispatch's own threadgroup size: its invocations count the grid's -//! threads in order and each takes the one it counts to, those past the last returning before -//! the body, so no edge and no group-count chunk is planned ([`regions`]). On the plan of a -//! partial-threadgroups variant ([`VariantKey::partial_threadgroups`]) it is the threadgroups -//! its threads fill, rounded up, at the dispatch's threadgroup size, per group-count chunk, all -//! with `MultiRegion = 1` and their `DispatchRegion` flagged `lower::dispatch::NONUNIFORM`: the -//! kernel's last threadgroup along an axis answers Metal's partial threadgroup, so no edge is -//! planned and one `VkPipeline` of the dispatch's size runs every such grid. A grid of whole -//! threadgroups takes the same regions there, unflagged: every thread is live. On the plan of a -//! kernel's grid tiles (`LocalRules::grid_tiles`), `Threads` and `Threadgroups` both run their -//! threads in [`grid_tile`]'s tiles, one workgroup of [`GRID_TILE_THREADS`] each, per -//! group-count chunk, with `MultiRegion = 1`, the tile as the nominal size, and the -//! `DispatchRegion` flagged where the tile does not divide the grid; `ThreadgroupRange` runs at -//! its own size with `MultiRegion = 0`, its base in the push field. -//! - A count above `maxComputeWorkGroupCount` on an axis is split into chunks, each a region -//! with `MultiRegion = 1` and its base in the push field. At most [`MAX_REGIONS`] regions are -//! planned; more is `Unsupported{GroupCount}`. -//! - `ThreadgroupRange` (a tile dispatch over a region) is the range's chunks, each with -//! `MultiRegion = 1`, its base the range's first threadgroup, and the grid the whole dispatch's. -//! - A tile function whose threadgroup is the tile (`LocalRules::tile_threadgroup`) runs its -//! threads per tile in each region, but every region has `MultiRegion = 1` and carries the tile -//! as Metal's threadgroup and the tiles times the tile as the grid, as plain Metal answers them -//! under `threadgroupSizeMatchesTileSize`. -//! -//! Every region's local size is checked: in the flattened tiers, and in a region deeper than -//! `DEEP_THREADGROUP` of a kernel that declares `SpecKey::DeepThreadgroup` (which the region sets), -//! `sn = x·y·z` against `maxComputeWorkGroupSize[0]`, `maxComputeWorkGroupInvocations`, and -//! `maxComputeWorkgroupSubgroups · S`; otherwise each axis and the product; and against every -//! `LocalSizeConstraint{multiple}` (`ComputeDerivatives` outside the flattened tiers). Metal's -//! nominal size must be 1..=1024 per axis (the `DispatchRegion` packing). -//! -//! **Partial simdgroups**. A flattened tier runs whole subgroups of its size `S` only, so a -//! dispatch with a region whose `sn` is not a multiple of `S` (a partial simdgroup, or in -//! `Cluster32` simdgroups that do not fill a subgroup) runs on the kernel's emulated-simdgroups -//! variant (`VariantKey::emulated_simdgroups`), whose tier is exact for every threadgroup size and -//! whose local size is not flattened. The whole dispatch runs on the variant, so every region of -//! it, its whole-subgroup regions included, is checked against the variant's limits: each axis and -//! the product. The dispatch's variant ([`BindingPlan::dispatch_variant`]) is then the plan's with -//! emulated simdgroups, and instantiating it on the plan of another variant is -//! `BindError::NeedsVariant`, before anything is written. Only the variant's scratch is left to the -//! variant's own plan, since only its compile knows it. A dispatch of whole subgroups keeps the -//! flattened pipeline, and so does a region of one row of a kernel whose only simdgroup semantics -//! are lockstep barriers that order pairs meeting across rows (`RuntimeFact::RowLockstep`): its -//! simdgroups lie within the row, where no pair meets, so it runs whatever its width, without -//! `REQUIRE_FULL_SUBGROUPS`. -//! -//! **One row**. A dispatch of such a kernel whose every region is one row (`y` and `z` 1) asks -//! for the kernel's one-row variant (`VariantKey::one_row`): its simdgroups lie within their rows, -//! so the variant leaves the lockstep simdgroup barriers out and keeps the threadgroup ones, and, -//! with no simdgroup semantics left, its tier pins no subgroup size and flattens no local size. -//! The planned pipeline still runs such a dispatch. The variant's plan runs every dispatch of -//! one-row regions, and a dispatch with a region of more rows on it is `BindError::NeedsVariant` -//! for the variant without it. -//! -//! **Unit axes**. A kernel walked predicated whose threads' positions alone steer some of its -//! synchronizations, along some axes, states which masks of axes relieve it -//! (`LocalRules::unit_relief`, `RuntimeFact::UnitAxes`). A dispatch whose threadgroups have one thread along such -//! a mask's axes, Metal's `threads_per_threadgroup` 1 there and every region's local size too, -//! may run on the kernel's unit-axes variant (`VariantKey::unit_axes`); the plan's own variant -//! runs it too, and gives the same answers. The variant's plan runs every dispatch of threadgroups -//! of one thread along its axes, and a dispatch of more is `BindError::NeedsVariant` for the -//! variant without them. -//! -//! **Push bytes.** Each region's push write covers the stage's whole push range, so every -//! statically used push byte is written (VUID-vkCmdDispatch-maintenance4-08602): the -//! `DispatchRegion` bytes (`lower::dispatch::region_bytes`) in every region, `MultiRegion` or -//! not, the stage-in region, the residual bind offsets, the slot guest bases, and zero at the -//! address holes the consumer fills ([`PushHole`]). -//! -//! **Stage-in region**. A kernel that reads the region (a `[[stage_in]]` step by thread position, -//! `[[grid_origin]]`, or `[[grid_size]]`) is dispatched only with one the encoder set: without it, -//! `BindError::MissingStageInRegion`, since what Metal reads then is not established. A step at a -//! rate above 1 adds the region's origin to the quotient, and an indexed step adds it to the index -//! it looks up at the thread position, as an M4 and an M3 Max read (`lower::stage_io::stage_in`): -//! the binder writes the region whatever its origin. Each region's `SpecKey::StageInReach` says -//! whether an element of a thread-position step may lie past the first `2^32` bytes from its bind -//! offset ([`stage_in_reach`]). It is false where none can, which drops the fetch's reach check, -//! so only a dispatch that can reach takes the `VkPipeline` that keeps it. -//! -//! **Indirect.** An indirect dispatch's region reads Metal's group counts from its buffer -//! ([`IndirectArgs::Buffer`]): a count above the device's `maxComputeWorkGroupCount` is the GPU's -//! to read, which Vulkan leaves undefined. - -use crate::bind::graphics::zeroed; -use crate::bind::instantiate::{ - bind_buffers, put, slot_field, texel_ranges, BufferExtent, DescriptorBytes, DescriptorRange, - FieldBytes, IndirectRef, PushConstantWrite, PushHole, RootEntry, RootTable, -}; -use crate::bind::plan::compute::{internal, not_implemented, spec_key_into}; -use crate::bind::plan::{ - AccessClass, BindingPlan, ByteRange, ComputeTemplate, LocalRules, ResourceUse, UseTarget, -}; -use crate::bind::resident::{stage_root_table, table_entries}; -use crate::bind::state::{BindState, BoundBuffer, StageInRegion}; -use crate::cache::{SpecializationKey, VariantKey}; -use crate::device::requirements::VkLimit; -use crate::error::{BindError, Capability, Feature, LowerFamily, Unsupported}; -use crate::lower::dispatch::{ - grid_tile, nonuniform_region_bytes, pack_nominal, region_bytes, DEEP_THREADGROUP, - GRID_TILE_THREADS, -}; -use crate::metal::vertex::vertex_bytes; -use crate::metal::{StepFunction, VertexFormat}; -use crate::pipeline::interface::{AccessSet, PushLoc}; -use crate::pipeline::stage_io::StageInFetch; -use crate::pipeline::sym::{Axis, PushField, SpecKey, Stage}; -use crate::vk; - -/// The most regions one dispatch is split into. Every committed profile's -/// `maxComputeWorkGroupCount` is at least 65535 per axis, so a grid within `2^16 · 65535` groups -/// per axis stays well inside it. -pub const MAX_REGIONS: u64 = 4096; +//! A Metal compute dispatch in Metal's terms ([`Dispatch`]), and the threadgroup bounds a tile +//! function's threadgroup takes. How a dispatch becomes Vulkan dispatches (its regions and their +//! `DispatchRegion` push field, `lower::dispatch::region_bytes`), after the pipeline's interface +//! and push fields, is the consumer's. /// A Metal compute dispatch. #[non_exhaustive] @@ -135,16 +13,11 @@ pub enum Dispatch { groups: [u32; 3], threads_per_group: [u32; 3], }, - /// `dispatchThreads:threadsPerThreadgroup:` (non-uniform edges become extra regions). + /// `dispatchThreads:threadsPerThreadgroup:`. Threads { threads: [u32; 3], threads_per_group: [u32; 3], }, - /// `dispatchThreadgroupsWithIndirectBuffer:` (GPU-written group counts). - ThreadgroupsIndirect { - indirect: IndirectRef, - threads_per_group: [u32; 3], - }, /// The threadgroups `first .. first + count` of `dispatchThreadgroups:` of `groups`, each /// axis's range cut to the grid: each runs as in the whole dispatch (its /// `threadgroup_position_in_grid`, and the grid of `groups * threads_per_group` threads), @@ -169,9 +42,6 @@ impl Dispatch { | Dispatch::Threads { threads_per_group, .. } - | Dispatch::ThreadgroupsIndirect { - threads_per_group, .. - } | Dispatch::ThreadgroupRange { threads_per_group, .. } => threads_per_group, @@ -179,1301 +49,5 @@ impl Dispatch { } } -/// What the consumer records for one dispatch: upload `descriptor_bytes` and `root_table`, bind -/// every plan descriptor (buffer descriptors over exactly `descriptor_ranges`), fill the -/// `push_holes` in every region's push bytes, and then record each region in order. -#[non_exhaustive] -#[derive(Clone, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct DispatchCommands { - /// One regular Vulkan dispatch per region: the uniform interior, `dispatchThreads` edges, and - /// group-count splits. Empty when the grid is empty. - pub regions: Vec, - /// The stage's `ArgumentTable` contents and its handle table. - pub descriptor_bytes: Vec, - /// The range of every buffer descriptor the plan writes as `Buffer` or `InlineBytes`. - pub descriptor_ranges: Vec, - /// Per bound buffer slot, the window this dispatch can touch. - pub extents: Vec, - pub push_holes: Vec, - /// The 32-byte region record a direct dispatch on a flat variant - /// ([`VariantKey::flat_grid`]) reads: the consumer writes exactly these bytes where the - /// device reads them by address, 16-byte aligned, and fills the single - /// [`PushHole::ReplayRegionAddress`] with that address. `None` for every other dispatch: a - /// replayed one's record its preprocess writes, and a plan that is not a flat variant's reads - /// its region from its own push bytes. - pub region_record: Option<[u8; 32]>, - /// The resident root table, when the function reads it. - pub root_table: Option, - /// The dispatch's own resources beyond the plan's `uses`: the 12 bytes of its indirect - /// arguments, read by `vkCmdDispatchIndirect` in `DRAW_INDIRECT`. The range is relative to - /// the arguments' offset. - pub uses: Vec, -} - -impl DispatchCommands { - /// No dispatch's commands, which an instantiation writes over (`instantiate`). - fn none() -> DispatchCommands { - DispatchCommands { - regions: Vec::new(), - descriptor_bytes: Vec::new(), - descriptor_ranges: Vec::new(), - extents: Vec::new(), - push_holes: Vec::new(), - region_record: None, - root_table: None, - uses: Vec::new(), - } - } -} - -/// Where an indirect region reads its group counts. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub enum IndirectArgs { - /// Metal's arguments, directly (`vkCmdDispatchIndirect` from this buffer and offset). - Buffer(IndirectRef), - /// The device replay's arguments for the replayed command and this variant, which its - /// preprocess wrote in the replay's scratch. - Replay, -} - -/// One Vulkan dispatch of a Metal dispatch. -#[non_exhaustive] -#[derive(Clone, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct DispatchRegion { - /// The complete specialization of this region's pipeline: the plan's constants, the local - /// size (and `sn` in the flattened tiers), and `MultiRegion`. - pub specialization: SpecializationKey, - /// Ignored for an indirect region. - pub group_count: [u32; 3], - pub push_constants: Vec, - /// `vkCmdDispatchIndirect` from here instead of a direct dispatch. - pub indirect: Option, - /// `REQUIRE_FULL_SUBGROUPS` when the tier needs it. - pub stage_flags: vk::PipelineShaderStageCreateFlags, - /// `requiredSubgroupSize` when the tier pins one. - pub required_subgroup_size: Option, -} - -const AXES: [Axis; 3] = [Axis::X, Axis::Y, Axis::Z]; - -fn limit(feature: Feature, limit: VkLimit, required: u64, available: u64) -> BindError { - BindError::Unsupported(Unsupported::needs( - feature, - Capability::Limit { - limit, - required, - available, - }, - )) -} - -/// Which pipeline runs a dispatch. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum Fit { - /// The planned pipeline. - Planned, - /// The kernel's emulated-simdgroups variant: a region's threadgroup is not whole subgroups of - /// the flattened tier's size. - EmulatedSimdgroups, -} - -/// A flattened tier's region of local size `r` that is not whole subgroups of its size: every -/// multiple of a flattened plan is its tier's subgroup size, since the flattened tiers refuse -/// derivatives (`ComputeDerivativesWithSimd`). -fn unwhole(rules: &LocalRules, r: [u32; 3]) -> bool { - let n: u64 = r.iter().map(|&x| u64::from(x)).product(); - rules.flat - && rules - .multiples - .iter() - .any(|&m| m > 0 && !n.is_multiple_of(u64::from(m))) -} - -/// A region that is not whole subgroups ([`unwhole`]) and needs emulated simdgroups: any but a -/// region of one row of a kernel whose simdgroup semantics need no simdgroup spanning two rows -/// (`LocalRules::rows`), whose simdgroups then lie within its row, where no pair meets. -fn partial(rules: &LocalRules, r: [u32; 3]) -> bool { - unwhole(rules, r) && !(rules.rows && r[1] == 1 && r[2] == 1) -} - -/// The stage flags of a region of local size `r` on the planned pipeline: the pipeline's, but -/// `REQUIRE_FULL_SUBGROUPS` for a region that is not whole subgroups, a row [`partial`] admits. -fn region_flags(rules: &LocalRules, r: [u32; 3]) -> vk::PipelineShaderStageCreateFlags { - if unwhole(rules, r) { - rules - .stage_flags - .difference(vk::PipelineShaderStageCreateFlags::REQUIRE_FULL_SUBGROUPS) - } else { - rules.stage_flags - } -} - -/// The local-size rules of the kernel's emulated-simdgroups variant as the plan of its flattened -/// variant knows them: the same device limits, a local size that is not flattened, a threadgroup -/// deeper than [`DEEP_THREADGROUP`] run as one row, and no whole subgroups (the flattened plan's -/// multiples are all its tier's, [`partial`]). The variant is of the `Spec` form, and a kernel of -/// a flattened tier has no compute derivatives (`lower::dispatch::plan_kernel` refuses them -/// there), so it declares `SpecKey::DeepThreadgroup`, as its own plan reads it. The variant's -/// scratch only its own plan knows. -fn emulated_rules(rules: &LocalRules) -> LocalRules { - LocalRules { - flat: false, - deep: true, - multiples: Vec::new(), - required_subgroup_size: None, - stage_flags: vk::PipelineShaderStageCreateFlags::empty(), - scratch: None, - rows: false, - ..rules.clone() - } -} - -/// The pipeline that runs a dispatch whose regions have the local sizes `locals` (every axis at -/// least 1), with every region checked against that pipeline's rules. A flattened tier's dispatch -/// with a region that is not whole subgroups runs whole on the emulated-simdgroups variant, so each -/// of its regions is checked against the variant's rules ([`emulated_rules`]). -pub(crate) fn fit( - rules: &LocalRules, - mut locals: impl Iterator + Clone, -) -> Result { - if locals.clone().any(|r| partial(rules, r)) { - let emulated = emulated_rules(rules); - locals.try_for_each(|r| check_local(&emulated, r))?; - Ok(Fit::EmulatedSimdgroups) - } else { - locals.try_for_each(|r| check_local(rules, r))?; - Ok(Fit::Planned) - } -} - -/// The checks of one region's local size `r` (every axis at least 1) under the rules of the -/// pipeline that runs it: a flattened tier's region is whole subgroups here ([`fit`]). -fn check_local(rules: &LocalRules, r: [u32; 3]) -> Result<(), BindError> { - let n: u64 = r.iter().map(|&x| u64::from(x)).product(); - let total = Feature::LocalSize { axis: None }; - if rules.flat || (rules.deep && r[2] > DEEP_THREADGROUP) { - let x = Feature::LocalSize { - axis: Some(Axis::X), - }; - if n > u64::from(rules.max_size[0]) { - let max = u64::from(rules.max_size[0]); - return Err(limit(x, VkLimit::MaxComputeWorkGroupSize(0), n, max)); - } - if let Some(s) = rules.required_subgroup_size { - let groups = n.div_ceil(u64::from(s.max(1))); - let max = u64::from(rules.max_subgroups); - if groups > max { - return Err(limit( - total.clone(), - VkLimit::MaxComputeWorkgroupSubgroups, - groups, - max, - )); - } - } - } else { - for (i, (&x, &max)) in r.iter().zip(&rules.max_size).enumerate() { - if x > max { - let axis = Feature::LocalSize { - axis: Some(AXES[i]), - }; - let l = VkLimit::MaxComputeWorkGroupSize(i as u8); - return Err(limit(axis, l, u64::from(x), u64::from(max))); - } - } - } - if n > u64::from(rules.max_invocations) { - let max = u64::from(rules.max_invocations); - return Err(limit( - total, - VkLimit::MaxComputeWorkGroupInvocations, - n, - max, - )); - } - // Outside the flattened tiers a multiple is a derivative group's. - if !rules.flat { - for &m in &rules.multiples { - if m > 0 && !n.is_multiple_of(u64::from(m)) { - return Err(BindError::Unsupported(Unsupported::not_representable( - Feature::ComputeDerivatives, - ))); - } - } - } - // Emulated simdgroups: the region's scratch beside the fixed threadgroup memory. - if let Some(s) = rules.scratch { - let required = n - .div_ceil(32) - .saturating_mul(u64::from(s.per_simdgroup)) - .saturating_add(s.fixed); - let available = u64::from(s.available); - if required > available { - return Err(limit( - Feature::ThreadgroupMemorySize, - VkLimit::MaxComputeSharedMemorySize, - required, - available, - )); - } - } - Ok(()) -} - -/// One Vulkan dispatch before its bytes: exact local size, group count, first threadgroup in the -/// Metal grid, and whether it takes the grid from the push field. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) struct Region { - pub local: [u32; 3], - pub groups: [u32; 3], - pub base: [u32; 3], - pub multi: bool, -} - -/// One piece of an axis: `(base, count, local)`. -type Piece = (u32, u32, u32); - -/// One axis's pieces: `count` groups of `local` threads from group `base`, in chunks of at most -/// `max`, then the edge piece where there is one. Held as these numbers alone, so a dispatch's -/// regions are planned with no list of each axis's pieces, nor of the regions ([`Regions`]). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -struct Pieces { - base: u32, - count: u32, - local: u32, - max: u32, - /// How many chunks `count` takes: `count / max`, rounded up. - chunks: u32, - edge: Option, -} - -impl Pieces { - /// `count` groups of `local` threads from group `base`, in chunks of at most `max`. - fn chunks(base: u32, count: u32, local: u32, max: u32) -> Pieces { - let max = max.max(1); - Pieces { - base, - count, - local, - max, - chunks: count.div_ceil(max), - edge: None, - } - } - - /// The one piece `(base, count, local)`, whatever its count (0 for an indirect region's). - fn one(base: u32, count: u32, local: u32) -> Pieces { - Pieces { - base, - count: 0, - local, - max: 1, - chunks: 0, - edge: Some((base, count, local)), - } - } - - /// How many pieces the axis has. - fn len(&self) -> u64 { - u64::from(self.chunks) + u64::from(self.edge.is_some()) - } - - /// Piece `k` in order: each chunk, then the edge; `None` past the last. - fn piece(&self, k: u64) -> Option { - match u32::try_from(k) { - // Each chunk starts below `count`, so no start overflows. - Ok(k) if k < self.chunks => { - let done = k * self.max; - Some(( - self.base + done, - (self.count - done).min(self.max), - self.local, - )) - } - Ok(k) if k == self.chunks => self.edge, - _ => None, - } - } - - /// The widest local size of its pieces, 0 where it has none. - fn widest(&self) -> u32 { - let chunk = if self.chunks > 0 { self.local } else { 0 }; - chunk.max(self.edge.map_or(0, |(_, _, local)| local)) - } -} - -/// The regions of a dispatch: the product of each axis's pieces, x slowest, each region taking one -/// piece of every axis, all of one `MultiRegion`. Held as these numbers alone, so planning a -/// dispatch makes no list of its regions: [`Regions::iter`] gives them in order. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) struct Regions { - pieces: [Pieces; 3], - multi: bool, -} - -impl Regions { - /// No region. - fn none() -> Regions { - Regions { - pieces: [Pieces::chunks(0, 0, 0, 1); 3], - multi: false, - } - } - - /// The one region `r`. - fn one(r: Region) -> Regions { - Regions { - pieces: std::array::from_fn(|i| Pieces::one(r.base[i], r.groups[i], r.local[i])), - multi: r.multi, - } - } - - /// How many regions there are. - pub(crate) fn len(&self) -> usize { - self.pieces.iter().map(Pieces::len).product::() as usize - } - - pub(crate) fn is_empty(&self) -> bool { - self.len() == 0 - } - - /// The regions in order. - pub(crate) fn iter(&self) -> RegionsIter { - RegionsIter { - regions: *self, - at: [0; 3], - left: self.len(), - } - } - - /// The widest local size along `axis` of any region, 0 where there is none: each piece of an - /// axis is some region's where there is a region. - fn widest(&self, axis: usize) -> u32 { - match self.is_empty() { - true => 0, - false => self.pieces[axis].widest(), - } - } -} - -/// [`Regions::iter`]: each region in order, the piece of each axis it takes counted from x -/// slowest to z fastest. -#[derive(Clone)] -pub(crate) struct RegionsIter { - regions: Regions, - at: [u64; 3], - left: usize, -} - -impl Iterator for RegionsIter { - type Item = Region; - - fn next(&mut self) -> Option { - self.left = self.left.checked_sub(1)?; - let pieces = &self.regions.pieces; - let [x, y, z] = [0, 1, 2].map(|i| pieces[i].piece(self.at[i])); - let ((bx, cx, lx), (by, cy, ly), (bz, cz, lz)) = (x?, y?, z?); - for i in [2, 1, 0] { - self.at[i] += 1; - if i == 0 || self.at[i] < pieces[i].len() { - break; - } - self.at[i] = 0; - } - Some(Region { - local: [lx, ly, lz], - groups: [cx, cy, cz], - base: [bx, by, bz], - multi: self.regions.multi, - }) - } -} - -/// The regions of a direct dispatch whose axes split into `pieces`; `MultiRegion` whenever there -/// is more than one region or `force_multi`. -fn product(pieces: [Pieces; 3], force_multi: bool) -> Result { - let total: u64 = pieces.iter().map(Pieces::len).product(); - if total > MAX_REGIONS { - let (i, _) = pieces - .iter() - .enumerate() - .max_by_key(|(_, p)| p.len()) - .unwrap_or((0, &pieces[0])); - return Err(BindError::Unsupported(Unsupported::not_representable( - Feature::GroupCount { - axis: Some(AXES[i]), - }, - ))); - } - Ok(Regions { - pieces, - multi: force_multi || total > 1, - }) -} - -/// Whether a region of `planned` has more than one row (`y` or `z` above 1), where a simdgroup -/// may span two rows. -/// The axes along which every threadgroup of `planned` has one thread (bit 0 `x`, bit 1 `y`, bit -/// 2 `z`): Metal's `threads_per_threadgroup` there is 1, and so is every region's local size. -fn unit_axes(planned: &Planned) -> u8 { - (0..3) - .filter(|&a| planned.nominal[a] == 1 && planned.regions.widest(a) <= 1) - .fold(0, |axes, a| axes | 1 << a) -} - -/// Whether the unit-axes variant of `axes` (`VariantKey::unit_axes`) runs `planned`: every one of -/// its threadgroups has one thread along each of those axes. -fn unit_axes_run(axes: u8, planned: &Planned) -> bool { - unit_axes(planned) & axes == axes -} - -fn multi_row(planned: &Planned) -> bool { - planned.regions.widest(1) > 1 || planned.regions.widest(2) > 1 -} - -/// The regions of a dispatch. -#[derive(Clone, Debug, PartialEq, Eq)] -pub(crate) struct Planned { - pub regions: Regions, - /// The Metal grid (`threads_per_grid`) the `DispatchRegion` field reports (0 for an indirect - /// dispatch, whose grid only the GPU knows). - pub grid: [u32; 3], - /// Metal's `threads_per_threadgroup`. - pub nominal: [u32; 3], - /// Some region runs only on the kernel's emulated-simdgroups variant. - pub emulated: bool, - /// The regions run a partial-threadgroups variant's ragged grid: their `DispatchRegion` is - /// flagged `lower::dispatch::NONUNIFORM` ([`Ragged::Partial`]). - pub nonuniform: bool, -} - -/// How a plan runs a `Threads` dispatch whose grid is not a whole number of threadgroups. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum Ragged { - /// Its interior and, per axis, an edge region of the remainder, each of an exact local size. - Split, - /// One region of the dispatch's threadgroup size, on a flat variant - /// ([`VariantKey::flat_grid`]). - Flat, - /// The threadgroups its threads fill at the dispatch's threadgroup size, per group-count - /// chunk, flagged `lower::dispatch::NONUNIFORM`, on a partial-threadgroups variant - /// ([`VariantKey::partial_threadgroups`]). A whole grid takes the same regions unflagged, and - /// a `Threadgroups` dispatch's regions read the region too (`MultiRegion` 1). - Partial, -} - -impl Ragged { - /// The form the plan of a pipeline compiled under `variant` runs a ragged grid in. - pub(crate) fn of(variant: &VariantKey) -> Ragged { - if variant.flat_grid { - Ragged::Flat - } else if variant.partial_threadgroups { - Ragged::Partial - } else { - Ragged::Split - } - } -} - /// The widest tile threadgroup, and the tallest: Metal's largest tile, 32x32. pub(crate) const TILE_THREADGROUP_SIDE: u32 = 32; - -/// Whether the lowering runs a `width x height x 1` tile threadgroup in Metal's layout -/// (`lower::dispatch`'s `tile_pos` and `tile_index`, the order measured on an Apple M3 Max for every -/// side from 1 to 32): both sides even from 2 to 32, where every quad is whole so `sg · 32 + lane` -/// numbers the threads densely, or the single thread. A threadgroup with an odd side leaves the -/// lanes of the threads past it empty in its quads, which no Vulkan workgroup leaves. -fn tile_layout_measured(width: u32, height: u32) -> bool { - if (width, height) == (1, 1) { - return true; - } - let side = |n: u32| n.is_multiple_of(2) && (2..=TILE_THREADGROUP_SIDE).contains(&n); - side(width) && side(height) -} - -/// A tile function's dispatch: one threadgroup per tile, `Dispatch::Threadgroups`, of a threadgroup -/// the lowering lays out as Metal does ([`tile_layout_measured`]); any other is -/// `Unsupported{TileShading, NotImplemented}`: a threadgroup with an odd side, whose empty lanes -/// are not built, or one deeper than 1. -fn check_tile_dispatch(dispatch: &Dispatch) -> Result<(), BindError> { - match *dispatch { - Dispatch::Threadgroups { - threads_per_group: [x, y, 1], - .. - } - | Dispatch::ThreadgroupRange { - threads_per_group: [x, y, 1], - .. - } if tile_layout_measured(x, y) => Ok(()), - _ => Err(not_implemented(Feature::TileShading)), - } -} - -/// The grid of `groups` threadgroups of `l` threads, each axis at most `2^32 - 1` threads -/// (`Unsupported{GroupCount}` otherwise). -fn threadgroup_grid(groups: [u32; 3], l: [u32; 3]) -> Result<[u32; 3], BindError> { - let mut grid = [0u32; 3]; - for i in 0..3 { - grid[i] = groups[i].checked_mul(l[i]).ok_or_else(|| { - BindError::Unsupported(Unsupported::not_representable(Feature::GroupCount { - axis: Some(AXES[i]), - })) - })?; - } - Ok(grid) -} - -/// The group counts of the one region a flat variant runs `need` threadgroups in: `need` spread -/// over x, then y, then z within `rules.max_count`, so their product is at least `need` (the -/// surplus invocations lie past the grid's last thread, which the lowering's guard retires). A -/// `need` the limits cannot hold is `Unsupported{GroupCount}`. -fn spread(need: u64, max_count: [u32; 3]) -> Result<[u32; 3], BindError> { - let mut left = need; - let mut out = [1u32; 3]; - for i in 0..3 { - let max = u64::from(max_count[i].max(1)); - let take = left.min(max); - out[i] = take as u32; - left = left.div_ceil(take); - } - if left > 1 { - return Err(BindError::Unsupported(Unsupported::not_representable( - Feature::GroupCount { - axis: Some(AXES[2]), - }, - ))); - } - Ok(out) -} - -/// The regions of `dispatch` under `rules`, a `Threads` grid that is not a whole number of -/// threadgroups in the form `ragged` names: an interior and its edges, one region of the -/// dispatch's own threadgroup size on a flat variant ([`VariantKey::flat_grid`]), or the -/// threadgroups its threads fill on a partial-threadgroups variant -/// ([`VariantKey::partial_threadgroups`]). On the last, a whole `Threads` grid and a -/// `Threadgroups` dispatch take regions that read the region too (`MultiRegion` 1), so the -/// variant's one `VkPipeline` of a threadgroup size runs them as well. -pub(crate) fn regions( - rules: &LocalRules, - dispatch: &Dispatch, - ragged: Ragged, -) -> Result { - if rules.tile { - check_tile_dispatch(dispatch)?; - } - let l = dispatch.threads_per_group(); - // Metal's threadgroup: the tile where a tile function's threadgroup is the tile, which every - // region then carries (`MultiRegion` 1), else the dispatch's. - let nominal = rules.tile_threadgroup.unwrap_or(l); - let tile_sized = rules.tile_threadgroup.is_some(); - for (i, (&x, &n)) in l.iter().zip(&nominal).enumerate() { - if x == 0 || n == 0 || pack_nominal([x.max(n), 1, 1]).is_none() { - return Err(BindError::Unsupported(Unsupported::not_representable( - Feature::LocalSize { - axis: Some(AXES[i]), - }, - ))); - } - } - let empty = |v: [u32; 3]| v.contains(&0); - // A kernel's grid tiles run a direct dispatch's threads in [`grid_tile`]'s tiles, one - // workgroup of `GRID_TILE_THREADS` each, with the tile as the nominal size (`MultiRegion` 1); - // a dispatch of a range of threadgroups runs at its own size (`MultiRegion` 0), from each - // region's base. The pieces carry the workgroup's size, so the unit axes and rows the plan - // reads see one row of 256 whatever the tile: the kernel reads no SIMD group or barrier. - let tiled = |threads: [u32; 3]| -> Result { - let tile = grid_tile(threads); - let local = [GRID_TILE_THREADS, 1, 1]; - let fit = fit(rules, std::iter::once(local))?; - let pieces = std::array::from_fn(|i| { - Pieces::chunks( - 0, - threads[i].div_ceil(tile[i]), - local[i], - rules.max_count[i], - ) - }); - Ok(Planned { - emulated: fit == Fit::EmulatedSimdgroups, - regions: product(pieces, true)?, - grid: threads, - nominal: tile, - nonuniform: (0..3).any(|i| !threads[i].is_multiple_of(tile[i])), - }) - }; - let planned = |regions: Regions, grid, emulated: bool| Planned { - emulated: emulated && !regions.is_empty(), - regions, - grid, - nominal, - nonuniform: false, - }; - match *dispatch { - Dispatch::Threadgroups { groups, .. } => { - let fit = fit(rules, std::iter::once(l))?; - let grid = threadgroup_grid(groups, nominal)?; - if empty(groups) { - return Ok(planned(Regions::none(), grid, false)); - } - if rules.grid_tiles { - return tiled(grid); - } - let pieces = - std::array::from_fn(|i| Pieces::chunks(0, groups[i], l[i], rules.max_count[i])); - // A partial-threadgroups variant's regions read their region, as its `Threads` - // regions do, so both run on its one `VkPipeline` of the dispatch's size. - let multi = tile_sized || ragged == Ragged::Partial; - Ok(planned( - product(pieces, multi)?, - grid, - fit == Fit::EmulatedSimdgroups, - )) - } - Dispatch::ThreadgroupRange { - groups, - first, - count, - .. - } => { - let fit = fit(rules, std::iter::once(l))?; - let grid = threadgroup_grid(groups, nominal)?; - let start: [u32; 3] = std::array::from_fn(|i| first[i].min(groups[i])); - let end: [u32; 3] = - std::array::from_fn(|i| first[i].saturating_add(count[i]).min(groups[i])); - if (0..3).any(|i| end[i] <= start[i]) { - return Ok(planned(Regions::none(), grid, false)); - } - let pieces = std::array::from_fn(|i| { - Pieces::chunks(start[i], end[i] - start[i], l[i], rules.max_count[i]) - }); - // Every region takes its first threadgroup from the push field; a kernel's grid tiles - // read it at `MultiRegion` 0, where their threadgroup is the pipeline's. - let mut regions = product(pieces, true)?; - if rules.grid_tiles { - regions.multi = false; - } - Ok(planned(regions, grid, fit == Fit::EmulatedSimdgroups)) - } - Dispatch::Threads { threads, .. } => { - if empty(threads) { - return Ok(planned(Regions::none(), threads, false)); - } - if rules.grid_tiles { - return tiled(threads); - } - // A flat variant runs the whole grid in one region of the dispatch's own threadgroup - // size: invocation `((wz · ny + wy) · nx + wx) · N + LocalInvocationIndex`, with - // `N = l.x·l.y·l.z`, counts the grid's threads `x` fastest and takes the one it counts - // to, and one past the grid's last thread returns before the body. The count runs over - // the single dispatch's group counts, so splitting them into regions would restart it - // in each and run the same threads again: the region is never chunked, and its counts - // only have to cover the grid ([`spread`]). - if ragged == Ragged::Flat { - let fit = fit(rules, std::iter::once(l))?; - let n: u64 = l.iter().map(|&x| u64::from(x)).product(); - let total: u128 = threads.iter().map(|&x| u128::from(x)).product(); - let need = u64::try_from(total.div_ceil(u128::from(n))).map_err(|_| { - BindError::Unsupported(Unsupported::not_representable(Feature::GroupCount { - axis: None, - })) - })?; - let region = Region { - local: l, - groups: spread(need, rules.max_count)?, - base: [0; 3], - // As the one region of a flat variant's indirect dispatch, so that both run on - // the variant's one `VkPipeline`: a flat grid reads its threads from the - // region record whatever this says. - multi: false, - }; - return Ok(planned( - Regions::one(region), - threads, - fit == Fit::EmulatedSimdgroups, - )); - } - // A partial-threadgroups variant runs the threadgroups the grid's threads fill, rounded - // up, at the dispatch's threadgroup size, per chunk of group counts, each region - // reading its base and the grid: the last threadgroup along an axis answers the - // threads left where the region is flagged. A whole grid's regions are unflagged, so - // every thread is live, on the same `VkPipeline` of the dispatch's size. - let nonuniform = (0..3).any(|i| !threads[i].is_multiple_of(l[i])); - if ragged == Ragged::Partial { - let pieces = std::array::from_fn(|i| { - Pieces::chunks(0, threads[i].div_ceil(l[i]), l[i], rules.max_count[i]) - }); - let fit = fit(rules, std::iter::once(l))?; - let mut out = planned( - product(pieces, true)?, - threads, - fit == Fit::EmulatedSimdgroups, - ); - out.nonuniform = nonuniform; - return Ok(out); - } - let mut edges = false; - let pieces = std::array::from_fn(|i| { - let (full, rem) = (threads[i] / l[i], threads[i] % l[i]); - let mut p = Pieces::chunks(0, full, l[i], rules.max_count[i]); - if rem > 0 { - edges = true; - p.edge = Some((full, 1, rem)); - } - p - }); - let out = product(pieces, edges)?; - let fit = fit(rules, out.iter().map(|r| r.local))?; - Ok(planned(out, threads, fit == Fit::EmulatedSimdgroups)) - } - Dispatch::ThreadgroupsIndirect { .. } => { - let fit = fit(rules, std::iter::once(l))?; - let region = Region { - local: l, - groups: [0; 3], - base: [0; 3], - multi: false, - }; - Ok(planned( - Regions::one(region), - [0; 3], - fit == Fit::EmulatedSimdgroups, - )) - } - } -} - -/// The `StageInRegion` push field's bytes (two `uvec4`): the origin and the size of region `r`, -/// each padded with a zero `w`. -fn stage_in_region_bytes(r: StageInRegion) -> FieldBytes { - let words = [r.origin, r.size] - .into_iter() - .flat_map(|v| v.into_iter().chain([0])); - words.flat_map(|x| x.to_le_bytes()).collect() -} - -impl BindingPlan { - /// The commands of one compute dispatch of `state`. `state` must have the shape the plan was - /// made for; the result depends on its offsets, lengths, and addresses and on the dispatch, - /// never on the contents of an indirect buffer. A dispatch that runs on another variant of the - /// pipeline ([`BindingPlan::dispatch_variant`]) is `BindError::NeedsVariant`. - /// - /// The plan of a flat variant ([`VariantKey::flat_grid`]) runs a `Threads` dispatch as one - /// region, which reads the grid from a 32-byte region record whose device address fills its - /// single `PushHole::ReplayRegionAddress`, at group counts of its own: enough threadgroups of - /// its own threadgroup size to cover the grid, whatever a whole number of them that grid is - /// (`regions`, a private reader that spreads the count a grid needs over the axes the device - /// admits); the record is [`DispatchCommands::region_record`], which the consumer writes. Any - /// other dispatch of a flat variant, and every dispatch of a folded variant - /// ([`VariantKey::folded_groups`]), whose records only a device replay's preprocess writes, - /// is `Unsupported{GpuEncodedIndirectCommands, - /// NotImplemented}`. - /// - /// The plan of a partial-threadgroups variant ([`VariantKey::partial_threadgroups`]) runs a - /// `Threads` dispatch whose grid is not a whole number of threadgroups as the threadgroups its - /// threads fill, rounded up, at the dispatch's threadgroup size, one region per chunk of group - /// counts, each `MultiRegion` 1 with its `DispatchRegion` flagged - /// `lower::dispatch::NONUNIFORM`; a `Threads` dispatch of a whole number of threadgroups as the - /// same regions unflagged, every thread live, and a `Threadgroups` dispatch as its regions, - /// each `MultiRegion` 1, so one `VkPipeline` of a threadgroup size runs all three; any other - /// dispatch as the plan of the pipeline without it. - pub fn instantiate_dispatch( - &self, - state: &BindState, - dispatch: &Dispatch, - ) -> Result { - let mut commands = DispatchCommands::none(); - self.instantiate_dispatch_into(state, dispatch, &mut commands)?; - Ok(commands) - } - - /// [`instantiate_dispatch`](Self::instantiate_dispatch)'s commands, written over `commands`: - /// every field is set as `instantiate_dispatch` sets it, and the vectors (each region's - /// specialization and push write's bytes, and the argument table's, among them) keep the - /// storage the commands written there before left, so a consumer that keeps one - /// `DispatchCommands` from dispatch to dispatch allocates none of it again once it holds as - /// much. On an error `commands` holds no dispatch's commands. - pub fn instantiate_dispatch_into( - &self, - state: &BindState, - dispatch: &Dispatch, - commands: &mut DispatchCommands, - ) -> Result<(), BindError> { - let t = self.compute_template("instantiate_dispatch")?; - let flat = self.variant.flat_grid; - let ragged = Ragged::of(&self.variant); - let records = match (flat || self.variant.folded_groups, dispatch) { - (false, _) => Records::Binder, - // A flat variant takes a direct dispatch, whose record the consumer writes - // ([`DispatchCommands::region_record`]). - (true, Dispatch::Threads { .. }) if flat => Records::Flat, - (true, _) => return Err(not_implemented(Feature::GpuEncodedIndirectCommands)), - }; - let planned = regions(&t.local, dispatch, ragged)?; - if planned.emulated { - return Err(BindError::NeedsVariant { - variant: Box::new(self.emulated_variant()), - }); - } - // The one-row variant runs one-row threadgroups only. - if self.variant.one_row && multi_row(&planned) { - return Err(BindError::NeedsVariant { - variant: Box::new(self.one_row_variant(false)), - }); - } - // The unit-axes variant runs threadgroups of one thread along its axes only. - if !unit_axes_run(self.variant.unit_axes, &planned) { - return Err(BindError::NeedsVariant { - variant: Box::new(self.unit_axes_key(0)), - }); - } - instantiate(t, planned, (state, dispatch), records, commands) - } - - /// The variant of the pipeline a compute dispatch runs on: the plan's - /// [`variant`](BindingPlan::variant), with `emulated_simdgroups` when a threadgroup of the - /// dispatch has a partial simdgroup the kernel's flattened simd tier cannot run (its - /// `threads_per_threadgroup`, or a `dispatchThreads` edge region, is not a multiple of the - /// tier's subgroup size); else with `one_row` when every region of the dispatch is one row of - /// a kernel whose lockstep simdgroup barriers order only pairs meeting across rows - /// (`RuntimeFact::RowLockstep`), and without it on the one-row variant's plan when a region - /// has more rows. A pure function of the plan and the dispatch, so a consumer can - /// compile the variant before it binds. It reports the dispatch's local-size refusals as - /// [`BindingPlan::instantiate_dispatch`] does, each region checked against the limits of the - /// pipeline the result names: a result names a variant whose plan, for the same shape, states - /// it and runs every region of the dispatch, except that the variant's plan checks the scratch - /// its emulated simdgroups take beside the threadgroup memory (`ThreadgroupMemorySize`), which - /// only the variant's compile knows. - pub fn dispatch_variant(&self, dispatch: &Dispatch) -> Result { - let t = self.compute_template("dispatch_variant")?; - let planned = regions(&t.local, dispatch, Ragged::of(&self.variant))?; - // A unit-axes variant's plan sends threadgroups of more threads along one of its axes to - // the variant without them. - if !unit_axes_run(self.variant.unit_axes, &planned) { - let mut base = self.clone(); - base.variant.unit_axes = 0; - return base.dispatch_variant(dispatch); - } - Ok(if planned.emulated { - self.emulated_variant() - } else if t.local.rows && !planned.regions.is_empty() && !multi_row(&planned) { - // Each simdgroup lies within its row, where no pair the lockstep simdgroup barriers - // order meets: the variant without them. - self.one_row_variant(true) - } else if self.variant.one_row && multi_row(&planned) { - self.one_row_variant(false) - } else { - self.variant.clone() - }) - } - - /// The plan's variant with `unit_axes` `axes`. - fn unit_axes_key(&self, axes: u8) -> VariantKey { - let mut v = self.variant.clone(); - v.unit_axes = axes; - v - } - - /// The plan's variant with emulated simdgroups. - fn emulated_variant(&self) -> VariantKey { - let mut v = self.variant.clone(); - v.emulated_simdgroups = true; - v - } - - /// The plan's variant with or without `one_row`. - fn one_row_variant(&self, one_row: bool) -> VariantKey { - let mut v = self.variant.clone(); - v.one_row = one_row; - v - } - - fn compute_template(&self, call: &str) -> Result<&ComputeTemplate, BindError> { - self.compute - .as_ref() - .ok_or_else(|| internal(format!("{call} of a plan that is not a compute plan"))) - } -} - -/// The specialization of a region of `local` threads of `t`, written over `key` in the storage -/// its lists hold ([`spec_key_into`]): the template's fixed constants, the local size, whether the -/// region reads its record (`MultiRegion`, `multi`), whether a stage-in element it fetches may lie -/// past the first `2^32` bytes from its bind offset (`StageInReach`, `reach`, -/// [`stage_in_reach`]), and whether it runs as one row (`DeepThreadgroup`, deeper than -/// [`DEEP_THREADGROUP`]). -/// -/// The template's fixed constants are the plan's value of every other constant of the layout, in -/// the layout's order, each a function of its key alone (`plan::compute`): each is taken where the -/// one before left off, and found from the start only where that one is another key's, so a -/// region's key takes no search of them. -fn region_specialization_into( - t: &ComputeTemplate, - (local, multi, reach): ([u32; 3], bool, bool), - key: &mut SpecializationKey, -) { - let n: u64 = local.iter().map(|&x| u64::from(x)).product(); - let next = std::cell::Cell::new(0); - let value = |k| match k { - SpecKey::LocalSize(a) => Some(u64::from(local[a as usize])), - SpecKey::FlatLocalSize => Some(n), - SpecKey::MultiRegion => Some(u64::from(multi)), - SpecKey::StageInReach => Some(u64::from(reach)), - SpecKey::DeepThreadgroup => Some(u64::from(local[2] > DEEP_THREADGROUP)), - other => match t.fixed.get(next.get()) { - Some(&(at, v)) if at == other => { - next.set(next.get() + 1); - Some(v) - } - _ => t.fixed.iter().find(|(key, _)| *key == other).map(|f| f.1), - }, - }; - spec_key_into(&t.spec, value, key); -} - -/// The stride the compute encoder binds kernel buffer `index` with in `state` -/// (`setBuffer:offset:attributeStride:atIndex:` and its forms, `MTLAttributeStrideStatic`'s low -/// 32 bits), 0 where it binds none: what a stage-in layout of `MTLBufferLayoutStrideDynamic` -/// fetches at. -fn stage_in_stride(state: &BindState, index: u32) -> u32 { - match state - .stages - .get(&Stage::Kernel) - .and_then(|k| k.buffers.get(&index)) - { - Some( - &BoundBuffer::Buffer { - attribute_stride: Some(s), - .. - } - | &BoundBuffer::Bytes { - attribute_stride: Some(s), - .. - }, - ) => s, - _ => 0, - } -} - -/// The axis (0 for x, 1 for y) of fetch `f`'s thread-position step; `None` for any other step. -/// These are the steps whose element the region clamps, and which `SpecKey::StageInReach` bounds -/// (`lower::stage_io::stage_in`). -pub(super) fn grid_axis(f: &StageInFetch) -> Option { - match f.step_function { - StepFunction::ThreadPositionInGridX => Some(0), - StepFunction::ThreadPositionInGridY => Some(1), - _ => None, - } -} - -/// The end of fetch `f`'s attribute bytes in an element: its offset plus its format's store -/// size ([`vertex_bytes`]; `MTLAttributeFormat` lists `MTLVertexFormat`'s formats at the same -/// values). An element `e` at stride `s` lies in the first `2^32` bytes from the bind offset -/// exactly where `e · s` plus this end is at most `2^32` (`lower::stage_io::fetch`'s -/// `within_reach`). `None` for a format no fetch decodes. -fn element_end(f: &StageInFetch) -> Option { - let format = VertexFormat::try_from(f.format.as_raw()).ok()?; - let bytes = vertex_bytes(format)?; - Some(u64::from(f.offset) + u64::from(bytes)) -} - -/// The `SpecKey::StageInReach` of a dispatch of `t` over Metal's `grid` (0 on each axis for an -/// indirect dispatch, whose grid only the GPU knows) in stage-in region `region`, under `state`'s -/// strides. It says whether an element that a thread-position fetch reads may lie past the first -/// `2^32` bytes from its bind offset, where the fetch's reach check reads it as zero -/// (`lower::stage_io::fetch`). Each element is `origin + min(position / rate, size - 1)` on the -/// step's axis, so it is at most the origin plus the smaller of the region's last element and the -/// grid's last position over the rate. In a region of size 0 on the axis, whose size less 1 clamps -/// nothing, it is bounded by the grid alone. Where that bound is unknown (an indirect grid over -/// such a region) or the sum leaves 32 bits (the shader's add wraps), any element may be read. -fn stage_in_reach( - t: &ComputeTemplate, - region: Option, - grid: [u32; 3], - state: &BindState, -) -> bool { - let Some(region) = region else { - return !t.stage_in_grid.is_empty(); - }; - t.stage_in_grid.iter().any(|f| { - let (Some(axis), Some(end)) = (grid_axis(f), element_end(f)) else { - return true; - }; - let stride = f - .stride - .unwrap_or_else(|| stage_in_stride(state, f.buffer_index)); - // At stride 0 every element is the attribute's own bytes at the bind offset. - if stride == 0 { - return end > 1 << 32; - } - let rate = f.step_rate.max(1); - let positions = grid[axis].checked_sub(1).map(|p| p / rate); - let last = match (region.size[axis].checked_sub(1), positions) { - (None, None) => return true, - (None, Some(p)) => p, - (Some(z), None) => z, - (Some(z), Some(p)) => z.min(p), - }; - let Some(element) = region.origin[axis].checked_add(last) else { - return true; - }; - u64::from(element) * u64::from(stride) + end > 1 << 32 - }) -} - -/// What writes a dispatch's region records and group counts. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Records { - /// None: the binder writes each region's `DispatchRegion`, and an indirect dispatch's counts - /// are Metal's, read where it wrote them. - Binder, - /// A flat variant's record at its `ReplayRegionAddress`, which the consumer writes for a - /// direct dispatch ([`DispatchCommands::region_record`]); the region takes its own group - /// counts. - Flat, - /// The device replay's preprocess: the records per command and region, the arguments, and the - /// slot table that stands for the root table. - Replay, -} - -/// The commands of `dispatch` planned as `planned`, whose region records and group counts -/// `records` writes: for a device-replay variant (whose `dispatch` is the `ThreadgroupsIndirect` of -/// its threadgroup size) the region reads the replay's arguments and no root table is built. -/// Written over `out`: each of its fields set, its vectors cleared or their values overwritten in -/// place (each region's specialization and push write, the argument table's bytes), never -/// replaced. On an error `out` holds no dispatch's commands. -fn instantiate( - t: &ComputeTemplate, - planned: Planned, - (state, dispatch): (&BindState, &Dispatch), - records: Records, - out: &mut DispatchCommands, -) -> Result<(), BindError> { - let DispatchCommands { - regions: regions_out, - descriptor_bytes, - descriptor_ranges, - extents, - push_holes, - region_record: region_record_out, - root_table: root_table_out, - uses, - } = out; - let replay = records == Records::Replay; - // A kernel that reads the stage-in region needs the encoder's. - let region = match t.stage_in_region { - false => None, - true => Some( - state - .stage_in_region - .ok_or(BindError::MissingStageInRegion)?, - ), - }; - let (push_start, push_size) = t.push_range.unwrap_or((0, 0)); - let compute = vk::ShaderStageFlags::COMPUTE; - // One region of the commands per planned region, each over the one a dispatch before left - // at its place where there is one. - let count = planned.regions.len(); - regions_out.truncate(count); - while regions_out.len() < count { - regions_out.push(DispatchRegion { - specialization: SpecializationKey::new(), - group_count: [0; 3], - push_constants: Vec::new(), - indirect: None, - stage_flags: vk::PipelineShaderStageCreateFlags::empty(), - required_subgroup_size: None, - }); - } - // Each region's one push write, where the plan pushes bytes. - for r in regions_out.iter_mut() { - let writes = &mut r.push_constants; - writes.truncate(usize::from(push_size > 0)); - if push_size > 0 && writes.is_empty() { - writes.push(PushConstantWrite { - stages: compute, - offset: push_start, - bytes: Vec::new(), - }); - } - for w in writes.iter_mut() { - w.stages = compute; - w.offset = push_start; - } - } - // The push bytes every region shares, written in the first region's write (a grid of no - // region pushes none, and writes them apart), and the argument table, in the first - // descriptor bytes. - let mut apart = Vec::new(); - let push = match regions_out - .first_mut() - .and_then(|r| r.push_constants.first_mut()) - { - Some(write) => zeroed(&mut write.bytes, push_size as usize), - None => zeroed(&mut apart, push_size as usize), - }; - descriptor_bytes.truncate(usize::from(t.table.is_some())); - let mut no_table = Vec::new(); - let table = match t.table { - Some((set, binding, size)) => { - if descriptor_bytes.is_empty() { - descriptor_bytes.push(DescriptorBytes { - set, - binding, - bytes: Vec::new(), - }); - } - let written = &mut descriptor_bytes[0]; - written.set = set; - written.binding = binding; - zeroed(&mut written.bytes, size as usize) - } - None => &mut no_table, - }; - - // Buffer slots: descriptor ranges and residuals, root entries, extents; texel buffers. - descriptor_ranges.clear(); - extents.clear(); - let bound = bind_buffers(&t.buffers, state, descriptor_ranges, extents)?; - descriptor_ranges.extend(texel_ranges(&t.resources, state)?); - - // The root table: the Psb entries and the resident set. - push_holes.clear(); - *root_table_out = match t.root_first { - // A replay variant's root table is its command's slot table. - Some(_) if replay => None, - Some(first) => { - let statics: Vec<(u32, RootEntry)> = bound - .statics - .iter() - .map(|(slot, e)| (slot.index, *e)) - .collect(); - Some(stage_root_table(&statics, first, &table_entries(state))) - } - None => None, - }; - - // Push fields that do not change per region. - for f in &t.fields { - let bytes: FieldBytes = match f.field { - // Only a preprocess writes region records. - PushField::ReplayRegionAddress if records == Records::Binder => { - return Err(not_implemented(Feature::GpuEncodedIndirectCommands)); - } - PushField::RootTableAddress - | PushField::ExecutionStatusAddress - | PushField::ReplayRegionAddress => { - let PushLoc::Push { offset } = f.loc else { - return Err(not_implemented(Feature::Lowering(LowerFamily::Dispatch))); - }; - push_holes.push(match f.field { - PushField::RootTableAddress => PushHole::RootTableAddress { - stages: compute, - offset, - }, - PushField::ExecutionStatusAddress => PushHole::ExecutionStatusAddress { - stages: compute, - offset, - }, - _ => PushHole::ReplayRegionAddress { - stages: compute, - offset, - }, - }); - continue; - } - PushField::DispatchRegion => continue, - PushField::StageInRegion => stage_in_region_bytes(region.ok_or_else(|| { - internal("a stage-in region push field without the region's fact") - })?), - // The stride the encoder bound the stage-in buffer or inline bytes with, 0 without - // one, as Metal reads a dynamic layout: `MTLAttributeStrideStatic`'s is its low 32 - // bits, whose elements past the first the fetch reads past the bind offset's 2^32 - // bytes (`lower::stage_io::fetch`). - PushField::StageInStride(index) => { - FieldBytes::of(&stage_in_stride(state, index).to_le_bytes()) - } - field => slot_field(field, &bound.residuals, &t.resources, state) - .ok_or_else(|| internal(format!("a compute push field {field:?}")))?, - }; - put(push, push_start, table, f.loc, &bytes)?; - } - let region_field = t - .fields - .iter() - .find(|f| f.field == PushField::DispatchRegion) - .map(|f| f.loc); - // Every later region's push bytes start as the first's. - if let Some((first, rest)) = regions_out.split_first_mut() { - if let Some(shared) = first.push_constants.first() { - for r in rest { - for w in &mut r.push_constants { - w.bytes.clone_from(&shared.bytes); - } - } - } - } - - // Regions. - let Planned { - regions: planned, - grid, - nominal, - nonuniform, - .. - } = planned; - let reach = stage_in_reach(t, region, grid, state); - for (r, out) in planned.iter().zip(regions_out.iter_mut()) { - if let Some(loc) = region_field { - let b = match nonuniform { - true => nonuniform_region_bytes(r.base, grid, nominal), - false => region_bytes(r.base, grid, nominal), - } - .ok_or_else(|| internal("an unpackable nominal threadgroup size"))?; - let bytes = match out.push_constants.first_mut() { - Some(write) => &mut write.bytes[..], - None => &mut [], - }; - put(bytes, push_start, &mut [], loc, &b)?; - } - region_specialization_into(t, (r.local, r.multi, reach), &mut out.specialization); - out.indirect = match *dispatch { - Dispatch::ThreadgroupsIndirect { .. } if replay => Some(IndirectArgs::Replay), - Dispatch::ThreadgroupsIndirect { indirect, .. } => Some(IndirectArgs::Buffer(indirect)), - _ => None, - }; - out.group_count = r.groups; - out.stage_flags = region_flags(&t.local, r.local); - out.required_subgroup_size = t.local.required_subgroup_size; - } - - // A direct dispatch on a flat variant reads its region from the record the consumer writes - // (base 0, the dispatch's threadgroup size, and the grid in threads), since the flat lowering - // reads the record by address wherever its group counts come from. - *region_record_out = match (records, *dispatch) { - (Records::Binder, _) => None, - (Records::Flat, _) => Some( - region_bytes([0; 3], grid, nominal) - .ok_or_else(|| internal("an unpackable nominal threadgroup size"))?, - ), - (Records::Replay, _) => None, - }; - descriptor_bytes.extend(crate::bind::heap::table_bytes(&t.resources, state)?); - uses.clear(); - if let Dispatch::ThreadgroupsIndirect { .. } = *dispatch { - // Metal's three words of group counts, which `vkCmdDispatchIndirect` reads. - uses.push(ResourceUse { - resource: UseTarget::Indirect, - access: AccessSet::READ, - class: AccessClass::Indirect, - stages: vk::PipelineStageFlags2::DRAW_INDIRECT, - range: Some(ByteRange { offset: 0, len: 12 }), - }); - } - Ok(()) -} - -#[cfg(test)] -mod tests; diff --git a/crates/metal2vulkan/src/bind/dispatch/tests.rs b/crates/metal2vulkan/src/bind/dispatch/tests.rs deleted file mode 100644 index a2e6a201d..000000000 --- a/crates/metal2vulkan/src/bind/dispatch/tests.rs +++ /dev/null @@ -1,1225 +0,0 @@ -//! Dispatch regions, splits, local-size checks, and instantiation on synthetic templates, including -//! the required test: a `ThreadgroupsIndirect` plan has no CPU-argument dependency; and the -//! emulated-simdgroups variant a partial simdgroup asks for. - -use super::*; -use crate::bind::plan::{BoundKind, PlannedBuffer}; -use crate::bind::state::{BoundBuffer, ResourceClass, StageTable, UsedResource}; -use crate::pipeline::artifact::SpecConstant; -use crate::pipeline::interface::{AccessSet, BufferForm, PlacedField, Window}; -use crate::pipeline::sym::{SlotClass, SlotRef, Stage}; - -/// `BindingPlan::instantiate_dispatch` of a compute plan of template `t` with no variant. -fn instantiate( - t: &ComputeTemplate, - s: &BindState, - d: &Dispatch, -) -> Result { - compute_plan(t, VariantKey::new()).instantiate_dispatch(s, d) -} - -fn compute_plan(t: &ComputeTemplate, variant: VariantKey) -> BindingPlan { - BindingPlan { - variant, - compute: Some(t.clone()), - ..BindingPlan::default() - } -} - -fn rules() -> LocalRules { - LocalRules { - deep: false, - flat: false, - multiples: Vec::new(), - max_size: [1024, 1024, 64], - max_invocations: 1024, - max_subgroups: 32, - max_count: [65535, 65535, 65535], - required_subgroup_size: None, - stage_flags: vk::PipelineShaderStageCreateFlags::empty(), - scratch: None, - rows: false, - unit_relief: 0, - tile: false, - tile_threadgroup: None, - grid_tiles: false, - } -} - -fn kslot(index: u32) -> SlotRef { - SlotRef { - stage: Stage::Kernel, - class: SlotClass::Buffer, - index, - } -} - -fn spec(id: u32, key: SpecKey) -> SpecConstant { - SpecConstant { - id, - key, - size: 4, - default: 1, - unread_bits: 0, - } -} - -/// A kernel reading grid builtins with one storage slot, the region field at 16, and one -/// residual at 48 (after the root and status addresses at 0 and 8). -fn template() -> ComputeTemplate { - let f = |field, offset, size| PlacedField { - field, - loc: PushLoc::Push { offset }, - size, - }; - ComputeTemplate { - buffers: vec![PlannedBuffer { - slot: kslot(0), - window: Window::Bounded { start: 0, len: 64 }, - form: BufferForm::Descriptor, - access: AccessSet::READ_WRITE, - binding: Some((0, 0)), - alignment: 64, - max_range: 1 << 27, - bound: BoundKind::Buffer { - device_address: false, - length_class: crate::bind::state::length_class(4096), - }, - }], - spec: vec![ - spec(0, SpecKey::LocalSize(Axis::X)), - spec(1, SpecKey::LocalSize(Axis::Y)), - spec(2, SpecKey::LocalSize(Axis::Z)), - spec(3, SpecKey::MultiRegion), - ], - fixed: Vec::new(), - local: rules(), - fields: vec![ - f(PushField::DispatchRegion, 0, 32), - f(PushField::SlotBindOffset(kslot(0)), 32, 4), - ], - push_range: Some((0, 36)), - table: None, - root_first: None, - resources: Default::default(), - stage_in_region: false, - stage_in_grid: Vec::new(), - } -} - -fn state(offset: u64) -> BindState { - let mut t = StageTable::default(); - t.buffers.insert( - 0, - BoundBuffer::Buffer { - length: 4096, - offset, - gpu_address: 0x1_0000, - device_address: None, - attribute_stride: None, - }, - ); - let mut s = BindState::default(); - s.stages.insert(Stage::Kernel, t); - s -} - -fn spec_value(key: &SpecializationKey, id: u32) -> Option { - let e = key.entries.iter().find(|e| e.constant_id == id)?; - let at = e.offset as usize; - Some(u32::from_le_bytes(key.data[at..at + 4].try_into().ok()?)) -} - -fn push_words(r: &DispatchRegion) -> Vec { - r.push_constants[0] - .bytes - .as_chunks::<4>() - .0 - .iter() - .map(|c| u32::from_le_bytes(*c)) - .collect() -} - -#[test] -fn a_threadgroups_indirect_plan_has_no_cpu_argument_dependency() { - let t = template(); - let d = |token, offset| Dispatch::ThreadgroupsIndirect { - indirect: IndirectRef { token, offset }, - threads_per_group: [8, 4, 2], - }; - let a = instantiate(&t, &state(0), &d(1, 0)).expect("a"); - let b = instantiate(&t, &state(0), &d(9, 4096)).expect("b"); - assert_eq!(a.regions.len(), 1); - let (ra, rb) = (&a.regions[0], &b.regions[0]); - // One region, `MultiRegion = 0`, the grid from `NumWorkgroups`: nothing but the argument - // reference differs, so the commands cannot depend on the GPU-written counts. - assert_eq!(spec_value(&ra.specialization, 3), Some(0)); - assert_eq!(ra.specialization, rb.specialization); - assert_eq!(ra.push_constants, rb.push_constants); - assert_eq!(ra.group_count, [0; 3]); - assert_eq!( - (ra.indirect, rb.indirect), - ( - Some(IndirectArgs::Buffer(IndirectRef { - token: 1, - offset: 0 - })), - Some(IndirectArgs::Buffer(IndirectRef { - token: 9, - offset: 4096 - })) - ) - ); - // The region field is written anyway (VUID-vkCmdDispatch-maintenance4-08602): base 0, - // the nominal size packed, the unknown grid 0. - let w = push_words(ra); - assert_eq!(&w[..8], &[0, 0, 0, 7 | 3 << 10 | 1 << 20, 0, 0, 0, 0]); - // The arguments are a use of the dispatch: `vkCmdDispatchIndirect` reads them. - assert_eq!( - a.uses, - vec![ResourceUse { - resource: UseTarget::Indirect, - access: AccessSet::READ, - class: AccessClass::Indirect, - stages: vk::PipelineStageFlags2::DRAW_INDIRECT, - range: Some(ByteRange { offset: 0, len: 12 }), - }] - ); - // A direct dispatch has no uses of its own. - let direct = Dispatch::Threadgroups { - groups: [1, 1, 1], - threads_per_group: [8, 4, 2], - }; - assert!(instantiate(&t, &state(0), &direct) - .expect("direct") - .uses - .is_empty()); -} - -#[test] -fn dispatch_threads_edges_become_multi_region_dispatches() { - let t = template(); - let d = Dispatch::Threads { - threads: [40, 3, 1], - threads_per_group: [16, 2, 1], - }; - let c = instantiate(&t, &state(0), &d).expect("threads"); - let got: Vec<([u32; 3], [u32; 3], Option, Vec)> = c - .regions - .iter() - .map(|r| { - let local = [0, 1, 2].map(|id| spec_value(&r.specialization, id).unwrap_or(0)); - ( - local, - r.group_count, - spec_value(&r.specialization, 3), - push_words(r)[..8].to_vec(), - ) - }) - .collect(); - let nominal = 15 | 1 << 10; - let words = |base: [u32; 3]| vec![base[0], base[1], base[2], nominal, 40, 3, 1, 0]; - assert_eq!( - got, - vec![ - ([16, 2, 1], [2, 1, 1], Some(1), words([0, 0, 0])), - ([16, 1, 1], [2, 1, 1], Some(1), words([0, 1, 0])), - ([8, 2, 1], [1, 1, 1], Some(1), words([2, 0, 0])), - ([8, 1, 1], [1, 1, 1], Some(1), words([2, 1, 0])), - ] - ); - // A multiple of the threadgroup size is one `MultiRegion = 0` region. - let d = Dispatch::Threads { - threads: [64, 4, 1], - threads_per_group: [16, 2, 1], - }; - let c = instantiate(&t, &state(0), &d).expect("uniform"); - assert_eq!(c.regions.len(), 1); - assert_eq!(c.regions[0].group_count, [4, 2, 1]); - assert_eq!(spec_value(&c.regions[0].specialization, 3), Some(0)); - // An empty grid dispatches nothing. - let d = Dispatch::Threads { - threads: [0, 4, 1], - threads_per_group: [16, 2, 1], - }; - assert!(instantiate(&t, &state(0), &d) - .expect("empty") - .regions - .is_empty()); -} - -/// `instantiate_dispatch_into` over commands a dispatch before left, of more regions, fewer, none, -/// another state: each time the commands a fresh `instantiate_dispatch` gives, in the storage -/// kept (a region's specialization written over a key of as many constants allocates nothing). -#[test] -fn instantiating_over_kept_commands_gives_a_fresh_instantiation() { - let plan = compute_plan(&template(), VariantKey::new()); - let threads = |threads| Dispatch::Threads { - threads, - threads_per_group: [16, 2, 1], - }; - let split = Dispatch::Threadgroups { - groups: [70000, 1, 2], - threads_per_group: [1, 1, 1], - }; - let dispatches = [ - (threads([40, 3, 1]), 0), - (threads([64, 4, 1]), 64), - (split, 0), - (threads([0, 4, 1]), 64), - (threads([40, 3, 1]), 128), - (threads([64, 4, 1]), 128), - ]; - let mut kept = plan - .instantiate_dispatch(&state(0), &threads([64, 4, 1])) - .expect("first"); - for (at, (d, offset)) in dispatches.into_iter().enumerate() { - let s = state(offset); - let data = kept.regions.first().map(|r| r.specialization.data.as_ptr()); - plan.instantiate_dispatch_into(&s, &d, &mut kept) - .expect("into"); - let fresh = plan.instantiate_dispatch(&s, &d).expect("fresh"); - assert_eq!(kept, fresh, "dispatch {at}"); - // The first region's key, kept, is written in the storage it held. - let first = kept.regions.first().map(|r| r.specialization.data.as_ptr()); - if let (Some(was), Some(now)) = (data, first) { - assert_eq!(was, now, "dispatch {at}: the key's storage"); - } - } -} - -/// `instantiate_dispatch_into` over commands a dispatch of as many regions or more left allocates -/// nothing: the regions are planned as numbers (`Regions`), and each region's key and push write, -/// the ranges and the extents are written in the storage kept. -#[test] -fn instantiating_over_kept_commands_allocates_nothing() { - use crate::tests::constant_blob_footprint::allocations_during; - let plan = compute_plan(&template(), VariantKey::new()); - let ragged = Dispatch::Threads { - threads: [40, 3, 1], - threads_per_group: [16, 2, 1], - }; - let whole = Dispatch::Threadgroups { - groups: [4, 2, 1], - threads_per_group: [16, 2, 1], - }; - let mut kept = plan - .instantiate_dispatch(&state(0), &ragged) - .expect("first"); - assert_eq!(kept.regions.len(), 4, "the interior and three edges"); - for (at, (d, offset)) in [(ragged, 64), (ragged, 128), (whole, 192)] - .into_iter() - .enumerate() - { - let s = state(offset); - let (into, made) = allocations_during(|| plan.instantiate_dispatch_into(&s, &d, &mut kept)); - into.expect("into"); - assert_eq!(made, 0, "dispatch {at}: allocations"); - let fresh = plan.instantiate_dispatch(&s, &d).expect("fresh"); - assert_eq!(kept, fresh, "dispatch {at}"); - } -} - -/// A region's key takes each fixed constant of the template where the walk of the layout left -/// off, the order the planner lists them in, and finds one listed out of that order: the same key -/// either way, each constant at its own value. -#[test] -fn a_regions_key_takes_its_fixed_constants_in_any_order() { - let mut t = template(); - t.spec = vec![ - spec(0, SpecKey::LocalSize(Axis::X)), - spec(1, SpecKey::TgLength(0)), - spec(2, SpecKey::LocalSize(Axis::Y)), - spec(3, SpecKey::TgLength(1)), - spec(4, SpecKey::LocalSize(Axis::Z)), - spec(5, SpecKey::MultiRegion), - spec(6, SpecKey::TgLength(2)), - ]; - let fixed = [ - (SpecKey::TgLength(0), 16), - (SpecKey::TgLength(1), 32), - (SpecKey::TgLength(2), 48), - ]; - let d = Dispatch::Threadgroups { - groups: [4, 2, 1], - threads_per_group: [16, 2, 1], - }; - let mut keys = Vec::new(); - for order in [[0, 1, 2], [2, 0, 1], [1, 2, 0]] { - t.fixed = order.iter().map(|&i| fixed[i]).collect(); - let c = instantiate(&t, &state(0), &d).expect("one region"); - let key = c.regions[0].specialization.clone(); - let values: Vec<_> = (0..7).map(|id| spec_value(&key, id)).collect(); - let expected = [16, 16, 2, 32, 1, 0, 48].map(Some); - assert_eq!(values, expected, "{order:?}"); - keys.push(key); - } - assert!(keys.windows(2).all(|k| k[0] == k[1])); -} - -#[test] -fn group_counts_above_the_limit_are_split_with_their_base() { - let t = template(); - let d = Dispatch::Threadgroups { - groups: [70000, 1, 2], - threads_per_group: [1, 1, 1], - }; - let c = instantiate(&t, &state(0), &d).expect("split"); - let got: Vec<([u32; 3], [u32; 3])> = c - .regions - .iter() - .map(|r| { - let w = push_words(r); - (r.group_count, [w[0], w[1], w[2]]) - }) - .collect(); - assert_eq!( - got, - vec![([65535, 1, 2], [0, 0, 0]), ([4465, 1, 2], [65535, 0, 0])] - ); - for r in &c.regions { - assert_eq!(spec_value(&r.specialization, 3), Some(1)); - assert_eq!(&push_words(r)[4..7], &[70000, 1, 2], "the whole grid"); - } - // Within the limits: one region without `MultiRegion`, the grid still written. - let d = Dispatch::Threadgroups { - groups: [3, 1, 1], - threads_per_group: [32, 1, 1], - }; - let c = instantiate(&t, &state(0), &d).expect("one"); - assert_eq!(c.regions.len(), 1); - assert_eq!(spec_value(&c.regions[0].specialization, 3), Some(0)); - assert_eq!(&push_words(&c.regions[0])[..8], &[0, 0, 0, 31, 96, 1, 1, 0]); - // Past `MAX_REGIONS`: a typed refusal naming the axis. - let mut t = template(); - t.local.max_count = [1, 1, 1]; - let d = Dispatch::Threadgroups { - groups: [1, 5000, 1], - threads_per_group: [1, 1, 1], - }; - let e = instantiate(&t, &state(0), &d).expect_err("too many"); - assert!( - matches!(&e, BindError::Unsupported(u) if u.feature == Feature::GroupCount { axis: Some(Axis::Y) }), - "{e:?}" - ); - // A grid past 2^32 - 1 threads on an axis is not Metal's. - let d = Dispatch::Threadgroups { - groups: [1 << 22, 1, 1], - threads_per_group: [1024, 1, 1], - }; - assert!(instantiate(&template(), &state(0), &d).is_err()); -} - -#[test] -fn local_sizes_are_checked_against_every_d4_limit() { - let mut r = rules(); - assert!(check_local(&r, [1024, 1, 1]).is_ok()); - let e = check_local(&r, [1, 1, 65]).expect_err("z"); - assert!( - matches!(&e, BindError::Unsupported(u) if u.feature == Feature::LocalSize { axis: Some(Axis::Z) }), - "{e:?}" - ); - assert!(check_local(&r, [64, 32, 1]).is_err(), "invocations"); - // Flattened: `sn` against size[0], invocations, and subgroups · S; the multiple. - r.flat = true; - r.max_size = [512, 1024, 64]; - r.required_subgroup_size = Some(32); - r.max_subgroups = 8; - r.multiples = vec![32]; - assert!(check_local(&r, [16, 16, 1]).is_ok()); - assert!(check_local(&r, [32, 32, 1]).is_err(), "sn > size[0]"); - r.max_size = [1024, 1024, 64]; - let e = check_local(&r, [32, 16, 1]).expect_err("subgroups"); - assert!( - matches!(&e, BindError::Unsupported(u) if matches!(u.needs, crate::error::Needs::AnyOf(ref a) if a[0][0] == Capability::Limit { limit: VkLimit::MaxComputeWorkgroupSubgroups, required: 16, available: 8 })), - "{e:?}" - ); - // A partial simdgroup runs on the emulated-simdgroups variant, whose local size is not - // flattened: each axis and the product are checked, not `sn` and the subgroups. - assert_eq!( - fit(&r, std::iter::once([33, 1, 1])).expect("partial"), - Fit::EmulatedSimdgroups - ); - assert_eq!( - fit(&r, std::iter::once([32, 1, 1])).expect("full"), - Fit::Planned - ); - assert_eq!( - fit(&r, std::iter::once([1, 1, 1])).expect("one thread"), - Fit::EmulatedSimdgroups - ); - r.max_subgroups = 1; - assert_eq!( - fit(&r, std::iter::once([60, 1, 1])).expect("the subgroup limit is the flattened tier's"), - Fit::EmulatedSimdgroups - ); - // The variant runs a region deeper than `DEEP_THREADGROUP` as one row (it declares - // `SpecKey::DeepThreadgroup`), so a z past the device's 64 is checked as `sn`. - assert_eq!( - fit(&r, std::iter::once([1, 1, 65])).expect("a partial region of z 65, as one row"), - Fit::EmulatedSimdgroups - ); - let e = fit(&r, std::iter::once([1, 2, 600])).expect_err("sn of a deep partial region"); - assert!( - matches!(&e, BindError::Unsupported(u) if u.feature == Feature::LocalSize { axis: Some(Axis::X) }), - "{e:?}" - ); - let e = fit(&r, std::iter::once([33, 33, 1])).expect_err("invocations of a partial region"); - assert!( - matches!(&e, BindError::Unsupported(u) if u.feature == Feature::LocalSize { axis: None }), - "{e:?}" - ); - // The whole dispatch runs on the variant, so every region of a dispatch with a partial one - // is checked against the variant's limits, its whole-subgroup regions included: [1, 1, 96] - // runs as one row of 96 there, and [1, 1, 64], past the flattened tier's subgroups, is within - // them. - assert_eq!( - fit(&r, [[1, 1, 96], [1, 1, 4]].into_iter()).expect("a deep whole region"), - Fit::EmulatedSimdgroups - ); - assert!( - fit(&r, std::iter::once([1, 1, 64])).is_err(), - "two subgroups on the flattened tier" - ); - assert_eq!( - fit(&r, [[1, 1, 64], [1, 1, 36]].into_iter()).expect("mixed"), - Fit::EmulatedSimdgroups - ); - // Outside the flattened tiers a multiple is a derivative group's, and stays refused. - let mut d4 = rules(); - d4.multiples = vec![4]; - assert_eq!( - fit(&d4, std::iter::once([8, 1, 1])).expect("quads"), - Fit::Planned - ); - let e = fit(&d4, std::iter::once([6, 1, 1])).expect_err("a partial quad"); - assert!( - matches!(&e, BindError::Unsupported(u) if u.feature == Feature::ComputeDerivatives), - "{e:?}" - ); - // Metal's nominal size is 1..=1024 per axis. - let d = Dispatch::Threadgroups { - groups: [1, 1, 1], - threads_per_group: [0, 1, 1], - }; - assert!(regions(&rules(), &d, Ragged::Split).is_err()); - let d = Dispatch::Threadgroups { - groups: [1, 1, 1], - threads_per_group: [1025, 1, 1], - }; - assert!(regions(&rules(), &d, Ragged::Split).is_err()); - // An edge region is checked too: a flattened kernel's partial edge runs on the - // emulated-simdgroups variant, and a full grid on the flattened pipeline. - let mut r = rules(); - r.multiples = vec![32]; - r.flat = true; - let d = Dispatch::Threads { - threads: [40, 1, 1], - threads_per_group: [32, 1, 1], - }; - assert!(regions(&r, &d, Ragged::Split).expect("edge").emulated); - let d = Dispatch::Threads { - threads: [64, 1, 1], - threads_per_group: [32, 1, 1], - }; - assert!(!regions(&r, &d, Ragged::Split).expect("full").emulated); -} - -/// A flattened (Direct) kernel's template: `sn` in one spec constant, whole 32-lane subgroups. -fn flat_template() -> ComputeTemplate { - let mut t = template(); - t.spec.push(spec(4, SpecKey::FlatLocalSize)); - t.local.flat = true; - t.local.multiples = vec![32]; - t.local.required_subgroup_size = Some(32); - t.local.stage_flags = vk::PipelineShaderStageCreateFlags::REQUIRE_FULL_SUBGROUPS; - t -} - -fn groups(threads_per_group: [u32; 3]) -> Dispatch { - Dispatch::Threadgroups { - groups: [2, 1, 1], - threads_per_group, - } -} - -/// A dispatch of a flattened kernel whose threadgroup has a partial simdgroup (1, 4, or 16 threads, -/// the authored cases' sizes; a `dispatchThreads` edge; an indirect dispatch) runs on the kernel's -/// emulated-simdgroups variant: `dispatch_variant` adds it to the plan's key, and -/// `instantiate_dispatch` names that key instead of writing anything. Whole simdgroups keep the -/// planned pipeline, and so does an empty grid. -#[test] -fn a_partial_simdgroup_asks_for_the_emulated_simdgroups_variant() { - let t = flat_template(); - let mut base = VariantKey::new(); - base.psb_slots.insert(kslot(3)); - let plan = compute_plan(&t, base.clone()); - let mut emulated = base.clone(); - emulated.emulated_simdgroups = true; - let partial = [ - groups([1, 1, 1]), - groups([4, 1, 1]), - groups([16, 1, 1]), - groups([8, 2, 1]), - groups([33, 1, 1]), - Dispatch::Threads { - threads: [100, 1, 1], - threads_per_group: [32, 1, 1], - }, - Dispatch::ThreadgroupsIndirect { - indirect: IndirectRef { - token: 0, - offset: 0, - }, - threads_per_group: [8, 1, 1], - }, - ]; - for d in &partial { - assert_eq!(plan.dispatch_variant(d), Ok(emulated.clone()), "{d:?}"); - assert_eq!( - plan.instantiate_dispatch(&state(0), d), - Err(BindError::NeedsVariant { - variant: Box::new(emulated.clone()) - }), - "{d:?}" - ); - } - let whole = [ - groups([32, 1, 1]), - groups([8, 4, 2]), - Dispatch::Threads { - threads: [96, 2, 1], - threads_per_group: [32, 1, 1], - }, - Dispatch::Threadgroups { - groups: [0, 1, 1], - threads_per_group: [16, 1, 1], - }, - ]; - for d in &whole { - assert_eq!(plan.dispatch_variant(d), Ok(base.clone()), "{d:?}"); - assert!(plan.instantiate_dispatch(&state(0), d).is_ok(), "{d:?}"); - } - // A limit every tier has is reported, not answered with a variant that cannot run it. - let too_many = groups([33, 33, 1]); - assert!(matches!( - plan.dispatch_variant(&too_many), - Err(BindError::Unsupported(_)) - )); - assert!(matches!( - plan.instantiate_dispatch(&state(0), &too_many), - Err(BindError::Unsupported(_)) - )); - // A `dispatchThreads` grid whose edge is partial runs whole on the variant, so its interior - // is checked against the variant's limits, not the flattened `sn`. The variant's own plan - // declares `SpecKey::DeepThreadgroup`, so an interior of z 96, past the device's 64 here, runs - // as one row, and one of z 64 runs as it is: the answer is the variant, whose plan runs both - // regions. - let mixed = |tpg_z| Dispatch::Threads { - threads: [1, 1, 100], - threads_per_group: [1, 1, tpg_z], - }; - let mut deep = template(); - deep.spec.push(spec(4, SpecKey::DeepThreadgroup)); - deep.local.deep = true; - let variant = compute_plan(&deep, emulated.clone()); - for z in [96, 64] { - assert_eq!( - plan.dispatch_variant(&mixed(z)), - Ok(emulated.clone()), - "{z}" - ); - let c = variant - .instantiate_dispatch(&state(0), &mixed(z)) - .expect("the variant runs both regions"); - assert_eq!(c.regions.len(), 2, "{z}"); - } - // `Cluster32` runs whole 64-lane subgroups: one simdgroup of 32 threads is a partial - // subgroup there. - let mut cluster = flat_template(); - cluster.local.multiples = vec![64]; - let cluster = compute_plan(&cluster, VariantKey::new()); - let mut only = VariantKey::new(); - only.emulated_simdgroups = true; - assert_eq!(cluster.dispatch_variant(&groups([32, 1, 1])), Ok(only)); - assert_eq!( - cluster.dispatch_variant(&groups([64, 1, 1])), - Ok(VariantKey::new()) - ); -} - -/// A flattened kernel whose simdgroup semantics are only lockstep barriers that order pairs -/// meeting across rows (`LocalRules::rows`, `RuntimeFact::RowLockstep`) runs a threadgroup of one -/// row on its planned pipeline whatever its width, that region without `REQUIRE_FULL_SUBGROUPS` -/// where it is not whole subgroups: its simdgroups lie within the row. Such a dispatch asks for -/// the one-row variant (`VariantKey::one_row`), which leaves those barriers out. A partial -/// threadgroup of two rows, or a `dispatchThreads` grid with such an edge, still asks for the -/// emulated-simdgroups variant, and whole subgroups keep the flag. -#[test] -fn a_row_of_a_row_lockstep_kernel_runs_on_the_planned_pipeline() { - let mut t = flat_template(); - t.local.rows = true; - let plan = compute_plan(&t, VariantKey::new()); - let mut emulated = VariantKey::new(); - emulated.emulated_simdgroups = true; - let mut one_row = VariantKey::new(); - one_row.one_row = true; - let full = vk::PipelineShaderStageCreateFlags::REQUIRE_FULL_SUBGROUPS; - for (n, flags) in [ - (1, vk::PipelineShaderStageCreateFlags::empty()), - (16, vk::PipelineShaderStageCreateFlags::empty()), - (48, vk::PipelineShaderStageCreateFlags::empty()), - (32, full), - (64, full), - ] { - let d = groups([n, 1, 1]); - assert_eq!(plan.dispatch_variant(&d), Ok(one_row.clone()), "{n}"); - let c = plan.instantiate_dispatch(&state(0), &d).expect("runs"); - assert_eq!(c.regions.len(), 1); - assert_eq!(c.regions[0].stage_flags, flags, "{n}"); - assert_eq!(c.regions[0].required_subgroup_size, Some(32), "{n}"); - } - // A grid of rows whose edge is one partial row: the whole rows keep the flag. - let edge = Dispatch::Threads { - threads: [100, 1, 1], - threads_per_group: [32, 1, 1], - }; - assert_eq!(plan.dispatch_variant(&edge), Ok(one_row)); - let c = plan.instantiate_dispatch(&state(0), &edge).expect("runs"); - let flags: Vec<_> = c.regions.iter().map(|r| r.stage_flags).collect(); - assert_eq!(flags, [full, vk::PipelineShaderStageCreateFlags::empty()]); - for d in [ - groups([8, 2, 1]), - groups([5, 3, 1]), - Dispatch::Threads { - threads: [16, 4, 1], - threads_per_group: [16, 3, 1], - }, - ] { - assert_eq!(plan.dispatch_variant(&d), Ok(emulated.clone()), "{d:?}"); - } - // Without the fact every partial region asks for the variant. - let plain = compute_plan(&flat_template(), VariantKey::new()); - assert_eq!(plain.dispatch_variant(&groups([16, 1, 1])), Ok(emulated)); -} - -/// The plan of the emulated-simdgroups variant (its local size not flattened, no multiple) states -/// the key and runs every threadgroup size with the local size as Metal gave it. -#[test] -fn the_emulated_variant_runs_every_threadgroup_size() { - let mut emulated = VariantKey::new(); - emulated.emulated_simdgroups = true; - let plan = compute_plan(&template(), emulated.clone()); - for n in [1, 4, 16, 32, 33] { - let d = groups([n, 1, 1]); - assert_eq!(plan.dispatch_variant(&d), Ok(emulated.clone())); - let c = plan.instantiate_dispatch(&state(0), &d).expect("runs"); - assert_eq!(c.regions.len(), 1); - let r = &c.regions[0]; - assert_eq!(spec_value(&r.specialization, 0), Some(n)); - assert_eq!(r.stage_flags, vk::PipelineShaderStageCreateFlags::empty()); - assert_eq!(r.required_subgroup_size, None); - } -} - -#[test] -fn residuals_ranges_extents_and_holes_follow_the_state() { - let mut t = template(); - t.fields.insert( - 0, - PlacedField { - field: PushField::RootTableAddress, - loc: PushLoc::Push { offset: 40 }, - size: 8, - }, - ); - t.fields.push(PlacedField { - field: PushField::ExecutionStatusAddress, - loc: PushLoc::Push { offset: 48 }, - size: 8, - }); - t.push_range = Some((0, 56)); - t.root_first = Some(2); - let mut s = state(100); - let mut heap = UsedResource::new(ResourceClass::Heap, 7); - heap.gpu_address = Some(0x8000); - heap.length = 0x100; - heap.device_address = Some(0x9_0000); - s.used_resources.push(heap); - let d = Dispatch::Threadgroups { - groups: [1, 1, 1], - threads_per_group: [1, 1, 1], - }; - let c = instantiate(&t, &s, &d).expect("instantiate"); - assert_eq!(c.descriptor_ranges.len(), 1); - // A bounded storage window binds the range its bind offsets share, the buffer from its start - // (`bind::instantiate::shared_range`), the bind offset its residual. - let r = c.descriptor_ranges[0].range; - assert_eq!((r.offset, r.range), (0, 4096)); - assert_eq!(push_words(&c.regions[0])[8], 100, "residual 100 - 0"); - assert_eq!(c.extents.len(), 1); - assert_eq!( - c.push_holes, - vec![ - PushHole::RootTableAddress { - stages: vk::ShaderStageFlags::COMPUTE, - offset: 40 - }, - PushHole::ExecutionStatusAddress { - stages: vk::ShaderStageFlags::COMPUTE, - offset: 48 - }, - ] - ); - // The resident set holds the heap only: the bound buffer has no device address. - let table = c.root_table.expect("root table"); - assert_eq!(table.bytes.len(), 3 * 32); - let word = |at: usize| u64::from_le_bytes(table.bytes[at..at + 8].try_into().expect("u64")); - assert_eq!((word(40), word(48)), (2, 1), "R0 = 2, N = 1"); - assert_eq!((word(64), word(72), word(80)), (0x9_0000, 0x8000, 0x100)); - // A state of another shape is the consumer's bug, reported, never guessed. - let e = instantiate(&t, &BindState::default(), &d).expect_err("shape"); - assert!(matches!(e, BindError::Internal(_)), "{e:?}"); -} - -/// A kernel with emulated simdgroups takes its scratch per simdgroup of each region beside its -/// fixed threadgroup memory; a region whose total exceeds the limit is refused, and an edge region -/// is checked with its own (smaller) size. -#[test] -fn emulated_simdgroup_scratch_is_checked_per_region() { - use crate::bind::plan::ScratchRule; - let mut r = rules(); - r.scratch = Some(ScratchRule { - per_simdgroup: 512, - fixed: 28 * 1024, - available: 32 * 1024, - }); - // 8 simdgroups: 28 KiB + 4 KiB fits; 257 threads are 9 simdgroups. - assert!(check_local(&r, [16, 16, 1]).is_ok()); - let e = check_local(&r, [257, 1, 1]).expect_err("scratch"); - assert!( - matches!(&e, BindError::Unsupported(u) if u.feature == Feature::ThreadgroupMemorySize && matches!(u.needs, crate::error::Needs::AnyOf(ref a) if a[0][0] == Capability::Limit { limit: VkLimit::MaxComputeSharedMemorySize, required: 28 * 1024 + 9 * 512, available: 32 * 1024 })), - "{e:?}" - ); - // `dispatchThreads`: a region of 300 threads does not fit; one of 256 with an edge region - // of 44 does. - let d = Dispatch::Threads { - threads: [300, 1, 1], - threads_per_group: [300, 1, 1], - }; - assert!(regions(&r, &d, Ragged::Split).is_err()); - let d = Dispatch::Threads { - threads: [300, 1, 1], - threads_per_group: [256, 1, 1], - }; - assert!( - regions(&r, &d, Ragged::Split).is_ok(), - "256 + an edge of 44" - ); -} - -/// A range of a dispatch's threadgroups (a region tile dispatch) runs those threadgroups alone, -/// each region taking its first threadgroup and the whole dispatch's grid from the push field -/// (`MultiRegion` 1), split at the group-count limit as any dispatch; the range is cut to the -/// grid, and one that holds no threadgroup of it runs nothing. -#[test] -fn a_threadgroup_range_runs_its_threadgroups_of_the_whole_grid() { - let t = template(); - let range = |first, count| Dispatch::ThreadgroupRange { - groups: [4, 3, 1], - first, - count, - threads_per_group: [8, 8, 1], - }; - let c = instantiate(&t, &state(0), &range([1, 1, 0], [2, 1, 1])).expect("range"); - assert_eq!(c.regions.len(), 1); - let r = &c.regions[0]; - assert_eq!(r.group_count, [2, 1, 1]); - assert_eq!(spec_value(&r.specialization, 3), Some(1)); - let w = push_words(r); - assert_eq!(&w[..3], &[1, 1, 0], "the first threadgroup"); - assert_eq!(&w[4..7], &[32, 24, 1], "the whole grid"); - // Cut to the grid. - let c = instantiate(&t, &state(0), &range([3, 2, 0], [5, 5, 1])).expect("cut"); - assert_eq!( - c.regions.iter().map(|r| r.group_count).collect::>(), - vec![[1, 1, 1]] - ); - // Nothing of the grid. - for (first, count) in [([4, 0, 0], [1, 1, 1]), ([0, 0, 0], [0, 1, 1])] { - let c = instantiate(&t, &state(0), &range(first, count)).expect("empty"); - assert!(c.regions.is_empty(), "{first:?} {count:?}"); - } - // Split at the group-count limit, each chunk from its own first threadgroup. - let mut t = template(); - t.local.max_count = [2, 65535, 65535]; - let c = instantiate(&t, &state(0), &range([1, 0, 0], [3, 1, 1])).expect("split"); - let got: Vec<([u32; 3], [u32; 3])> = c - .regions - .iter() - .map(|r| { - let w = push_words(r); - (r.group_count, [w[0], w[1], w[2]]) - }) - .collect(); - assert_eq!(got, vec![([2, 1, 1], [1, 0, 0]), ([1, 1, 1], [3, 0, 0])]); -} - -/// A tile function whose threadgroup is the tile (`threadgroupSizeMatchesTileSize`) runs its -/// threads per tile, 8x8 here, in workgroups of that size, but every region carries the 16x16 -/// tile as Metal's threadgroup and the tiles times the tile as the grid (`MultiRegion` 1), as -/// plain Metal answers them (on an M3 Max and an M4); a region of the tiles alike. -#[test] -fn a_tile_sized_threadgroup_carries_the_tile_in_every_region() { - let mut t = template(); - t.local.tile = true; - t.local.tile_threadgroup = Some([16, 16, 1]); - let tile_nominal = 15 | 15 << 10; - let d = Dispatch::Threadgroups { - groups: [4, 2, 1], - threads_per_group: [8, 8, 1], - }; - let c = instantiate(&t, &state(0), &d).expect("tiles"); - assert_eq!(c.regions.len(), 1); - let r = &c.regions[0]; - let local = [0, 1, 2].map(|id| spec_value(&r.specialization, id).unwrap_or(0)); - assert_eq!(local, [8, 8, 1], "the threads per tile run"); - assert_eq!(r.group_count, [4, 2, 1]); - assert_eq!(spec_value(&r.specialization, 3), Some(1)); - assert_eq!(push_words(r)[..8], [0, 0, 0, tile_nominal, 64, 32, 1, 0]); - let range = Dispatch::ThreadgroupRange { - groups: [4, 2, 1], - first: [1, 1, 0], - count: [2, 1, 1], - threads_per_group: [8, 8, 1], - }; - let c = instantiate(&t, &state(0), &range).expect("range"); - let r = &c.regions[0]; - assert_eq!(r.group_count, [2, 1, 1]); - assert_eq!(push_words(r)[..8], [1, 1, 0, tile_nominal, 64, 32, 1, 0]); - // Without it the nominal threadgroup is the dispatch's, one region needing no push field. - t.local.tile_threadgroup = None; - let c = instantiate(&t, &state(0), &d).expect("plain"); - assert_eq!(spec_value(&c.regions[0].specialization, 3), Some(0)); - assert_eq!(push_words(&c.regions[0])[3..7], [7 | 7 << 10, 32, 16, 1]); -} - -/// A flat variant's template (`VariantKey::flat_grid`): the 32-byte region record at -/// `ReplayRegionAddress`, in place of the `DispatchRegion` push bytes an ordinary kernel reads. -fn flat_grid_template() -> ComputeTemplate { - let f = |field, offset, size| PlacedField { - field, - loc: PushLoc::Push { offset }, - size, - }; - ComputeTemplate { - fields: vec![ - f(PushField::ReplayRegionAddress, 0, 8), - f(PushField::SlotBindOffset(kslot(0)), 8, 4), - ], - push_range: Some((0, 12)), - ..template() - } -} - -fn flat_variant() -> VariantKey { - let mut v = VariantKey::new(); - v.flat_grid = true; - v -} - -/// A `dispatchThreads:` whose grid is not a whole number of threadgroups is the interior and its -/// ragged edges on an ordinary plan, each region a local size of its own; on the plan of a flat -/// variant it is one region of the dispatch's own threadgroup size, at group counts that cover the -/// grid, whose record the consumer writes (base 0, the threadgroup size, the grid in threads) where -/// its `ReplayRegionAddress` hole points. The variant's direct and indirect dispatches take the -/// same region key, so one `VkPipeline` runs both. -#[test] -fn a_flat_plan_runs_a_ragged_dispatch_in_one_region() { - let threads = [100, 50, 3]; - let local = [8, 8, 1]; - let d = Dispatch::Threads { - threads, - threads_per_group: local, - }; - let s = state(0); - - // The split: 96 + 4 threads on x, 48 + 2 on y, 3 whole threadgroups on z. - let split = instantiate(&template(), &s, &d).expect("the split regions"); - assert_eq!(split.regions.len(), 4); - assert_eq!(split.region_record, None); - let locals: Vec<[u32; 3]> = split - .regions - .iter() - .map(|r| [0, 1, 2].map(|id| spec_value(&r.specialization, id).expect("a local size axis"))) - .collect(); - assert_eq!( - locals, - vec![[8, 8, 1], [8, 2, 1], [4, 8, 1], [4, 2, 1]], - "the interior and its ragged edges" - ); - - let t = flat_grid_template(); - let flat = compute_plan(&t, flat_variant()) - .instantiate_dispatch(&s, &d) - .expect("the flat region"); - assert_eq!(flat.regions.len(), 1); - let r = &flat.regions[0]; - assert_eq!(r.indirect, None); - assert_eq!( - [0, 1, 2].map(|id| spec_value(&r.specialization, id)), - local.map(Some), - "the dispatch's own threadgroup size, not an edge's" - ); - // 100 x 50 x 3 threads is 15,000, which 235 threadgroups of 64 cover. - assert_eq!(r.group_count, [235, 1, 1]); - let covered: u32 = r.group_count.iter().product::() * local.iter().product::(); - assert!(covered >= threads.iter().product::()); - assert_eq!( - flat.region_record, - Some(region_bytes([0; 3], threads, local).expect("a packable threadgroup size")), - ); - assert_eq!( - flat.push_holes, - vec![PushHole::ReplayRegionAddress { - stages: vk::ShaderStageFlags::COMPUTE, - offset: 0, - }], - ); - - // The variant's indirect dispatch outside a device replay is not built: only the replay's - // preprocess writes such a dispatch's record. - let indirect = Dispatch::ThreadgroupsIndirect { - indirect: IndirectRef { - token: 0, - offset: 0, - }, - threads_per_group: local, - }; - assert!(compute_plan(&t, flat_variant()) - .instantiate_dispatch(&s, &indirect) - .is_err()); -} - -/// The flat form's counting, exhaustively over every grid up to 9 x 5 x 3 threads and every -/// threadgroup up to 4 x 3 x 2, with group counts that spread over all three axes (a tight -/// `maxComputeWorkGroupCount`) and group counts that do not: the one region's invocation -/// `((wz · ny + wy) · nx + wx) · N + LocalInvocationIndex`, with `N = l.x·l.y·l.z`, counted over -/// the grid `x` fastest, reaches every thread of the grid exactly once and no thread outside it, -/// and the region holds at least the grid's threads (`nx·ny·nz·N >= threads.x·threads.y·threads.z`) -/// so that none is left out. This is what makes the one region exact where the split's interior and -/// edges are: every grid thread runs, and no thread past the grid does. -#[test] -fn a_flat_region_counts_every_grid_thread_exactly_once() { - for max_count in [[8, 8, 8], [65535, 65535, 65535]] { - let mut rules = rules(); - rules.max_count = max_count; - for tx in 1..=9 { - for ty in 1..=5 { - for tz in 1..=3 { - for lx in 1..=4 { - for ly in 1..=3 { - for lz in 1..=2 { - let threads = [tx, ty, tz]; - let local = [lx, ly, lz]; - let d = Dispatch::Threads { - threads, - threads_per_group: local, - }; - let planned = - regions(&rules, &d, Ragged::Flat).expect("one flat region"); - let what = format!("{threads:?} threads of {local:?}"); - assert_eq!(planned.regions.len(), 1, "{what}"); - assert_eq!(planned.grid, threads, "{what}"); - assert_eq!(planned.nominal, local, "{what}"); - let r = planned.regions.iter().next().expect("a region"); - assert_eq!(r.local, local, "{what}"); - assert_eq!(r.base, [0; 3], "{what}"); - for (&count, &limit) in r.groups.iter().zip(&max_count) { - assert!(count >= 1 && count <= limit, "{what}"); - } - let n = u64::from(lx) * u64::from(ly) * u64::from(lz); - let [nx, ny, nz] = r.groups.map(u64::from); - let [gx, gy, gz] = threads.map(u64::from); - let total = gx * gy * gz; - assert!(nx * ny * nz * n >= total, "{what}"); - // The lowering's walk: each invocation takes the grid thread its - // index counts to, and one whose `z` is past the grid returns - // before the body (`lower::dispatch`'s `KernelDecl::flat`). - let mut seen = vec![0u32; total as usize]; - for wz in 0..nz { - for wy in 0..ny { - for wx in 0..nx { - for lin in 0..n { - let group = (wz * ny + wy) * nx + wx; - let index = group * n + lin; - let x = index % gx; - let row = index / gx; - let (y, z) = (row % gy, row / gy); - if z >= gz { - continue; - } - seen[((z * gy + y) * gx + x) as usize] += 1; - } - } - } - } - let wrong = seen.iter().filter(|&&n| n != 1).count(); - assert_eq!(wrong, 0, "{what}: {wrong} threads not run once"); - } - } - } - } - } - } - } -} - -/// A grid the flat form's threadgroups cannot cover within the device's `maxComputeWorkGroupCount` -/// is `Unsupported{GroupCount}`, so the dispatch keeps its exact split (`compute::flat_direct`). -#[test] -fn a_flat_region_that_cannot_cover_the_grid_is_refused() { - let mut rules = rules(); - rules.max_count = [2, 2, 2]; - let d = Dispatch::Threads { - threads: [9, 5, 3], - threads_per_group: [1, 1, 1], - }; - let e = regions(&rules, &d, Ragged::Flat).expect_err("135 threadgroups in 8"); - assert!( - matches!(&e, BindError::Unsupported(u) if matches!( - u.feature, - Feature::GroupCount { axis: Some(Axis::Z) } - )), - "{e:?}" - ); - // The split covers it: 9 x 5 x 3 threadgroups in chunks of two per axis. - let planned = regions(&rules, &d, Ragged::Split).expect("the split"); - assert_eq!(planned.regions.len(), 5 * 3 * 2); -} - -/// A dispatch's `StageInReach` is false exactly where every element a thread-position fetch reads -/// ends in the first `2^32` bytes from its bind offset: the element `origin + min(position / rate, -/// size - 1)` at its furthest, at the layout's stride, plus the end of its attribute's bytes. It is -/// true where nothing bounds the element (an indirect grid over a region of size 0) or the origin's -/// add wraps. -#[test] -fn a_dispatch_reaches_where_an_element_may_end_past_four_gigabytes() { - use crate::metal::{AttributeFormat, StepFunction}; - use crate::pipeline::stage_io::StageInFetch; - // A `uint` at offset 4 of an element of buffer 1: an element's bytes end 8 past its start. - let fetch = |stride, step_function, step_rate| StageInFetch { - format: AttributeFormat::UInt, - buffer_index: 1, - offset: 4, - stride, - step_function, - step_rate, - index: None, - }; - let (x, y) = ( - StepFunction::ThreadPositionInGridX, - StepFunction::ThreadPositionInGridY, - ); - let bound = |stride: Option| { - let mut s = state(0); - let kernel = s.stages.get_mut(&Stage::Kernel).expect("kernel"); - kernel.buffers.insert( - 1, - BoundBuffer::Buffer { - length: 4096, - offset: 0, - gpu_address: 0x2_0000, - device_address: None, - attribute_stride: stride, - }, - ); - s - }; - let unbound = bound(None); - let along_x = |o: u32, z: u32| StageInRegion::new([o, 0, 0], [z, 1, 1]); - let reach = |fetches: Vec, region, grid, state: &BindState| { - let mut t = template(); - t.stage_in_region = true; - t.stage_in_grid = fetches; - stage_in_reach(&t, Some(region), grid, state) - }; - let quarter = 1 << 30; - // At a fixed 2^30, elements 0 to 3 end by 3 · 2^30 + 8, and element 4 at 2^32 + 8. - let fixed = || vec![fetch(Some(quarter), x, 1)]; - assert!(!reach(fixed(), along_x(0, 4), [64, 1, 1], &unbound)); - assert!(reach(fixed(), along_x(0, 5), [64, 1, 1], &unbound)); - // The origin adds to every element. - assert!(reach(fixed(), along_x(1, 4), [64, 1, 1], &unbound)); - // The grid's last position bounds a larger region, over the step's rate. - assert!(!reach(fixed(), along_x(0, 64), [4, 1, 1], &unbound)); - let quartered = || vec![fetch(Some(quarter), x, 4)]; - assert!(!reach(quartered(), along_x(0, 64), [16, 1, 1], &unbound)); - assert!(reach(quartered(), along_x(0, 64), [17, 1, 1], &unbound)); - // A region of size 0 clamps nothing: the grid alone bounds it, and an indirect one, whose - // grid only the GPU knows, nothing; a region of a size bounds an indirect grid. - assert!(!reach(fixed(), along_x(0, 0), [4, 1, 1], &unbound)); - assert!(reach(fixed(), along_x(0, 0), [0; 3], &unbound)); - assert!(!reach(fixed(), along_x(0, 4), [0; 3], &unbound)); - // The step's axis: a region of 4 along y, of 64 along x. - let rows = StageInRegion::new([0; 3], [64, 4, 1]); - assert!(!reach( - vec![fetch(Some(quarter), y, 1)], - rows, - [64, 64, 1], - &unbound - )); - assert!(reach( - vec![fetch(Some(quarter), x, 1)], - rows, - [64, 64, 1], - &unbound - )); - // An origin whose add wraps reaches any element. - assert!(reach( - vec![fetch(Some(4), x, 1)], - along_x(u32::MAX, 2), - [64, 1, 1], - &unbound - )); - // At stride 0 every element is the first one's bytes. - assert!(!reach( - vec![fetch(Some(0), x, 1)], - along_x(u32::MAX, 2), - [64, 1, 1], - &unbound - )); - // A dynamic layout reads the bound stride, 0 where none is bound; `MTLAttributeStrideStatic` - // is its low 32 bits, past which only the first element is held. - let dynamic = || vec![fetch(None, x, 1)]; - assert!(!reach(dynamic(), along_x(0, 64), [64, 1, 1], &unbound)); - assert!(!reach( - dynamic(), - along_x(0, 1), - [64, 1, 1], - &bound(Some(u32::MAX)) - )); - assert!(reach( - dynamic(), - along_x(0, 2), - [64, 1, 1], - &bound(Some(u32::MAX)) - )); - assert!(!reach( - dynamic(), - along_x(0, 2), - [64, 1, 1], - &bound(Some((1 << 31) + 4)) - )); - assert!(reach( - dynamic(), - along_x(0, 3), - [64, 1, 1], - &bound(Some((1 << 31) + 4)) - )); - // Any fetch that may reach makes the region's key true. - let both = vec![fetch(Some(4), x, 1), fetch(Some(quarter), x, 1)]; - assert!(reach(both, along_x(0, 5), [64, 1, 1], &unbound)); - // A kernel without a thread-position fetch reaches nothing. - assert!(!reach(Vec::new(), along_x(0, 64), [64, 1, 1], &unbound)); -} diff --git a/crates/metal2vulkan/src/bind/graphics.rs b/crates/metal2vulkan/src/bind/graphics.rs index 2dffddfb4..36d88767c 100644 --- a/crates/metal2vulkan/src/bind/graphics.rs +++ b/crates/metal2vulkan/src/bind/graphics.rs @@ -1,259 +1,28 @@ -//! Render planning and draws: [`RenderPipeline::plan`] and [`BindingPlan::instantiate_draw`]. -//! -//! A render plan is the compute plan's algorithm over the pipeline's two Metal stages: -//! -//! - **Descriptors.** Every set-0 binding of the layout gets one write: a buffer slot of the -//! vertex or fragment stage its `Buffer`, `InlineBytes`, or `ZeroBuffer` neutral (a pulled -//! vertex buffer is a read-only, `Whole`-window storage slot of the vertex stage); each stage's -//! `ArgumentTable` and `ConstantBlob`; textures, samplers, combined image samplers, texel -//! buffers, and input attachments through the shared resource planner (`plan::resources`); each -//! 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 -//! 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. -//! - **Vertex buffers.** One [`VertexBufferBind`] per fixed-function binding of the pipeline's -//! `VertexInputState`; the slot must be bound (`UnboundVertexBuffer`), and a `PerBind` stride -//! is the bind's `attributeStride`: 0 for a buffer or inline bytes bound without one, as plain -//! Metal's encoder reads them (its debug layer stops the draw); `MTLAttributeStrideStatic`'s is -//! its low 32 bits, `2^32 - 1`, which the pulled fetch reads as element 0 and zeros past it, as -//! plain Metal does (an M4 over inline bytes, an M3 Max over a buffer). A binding the shape binds where fixed-function input cannot fetch it (a -//! bind offset whose alignment class misses an attribute's Vulkan alignment; a per-bind stride -//! past `maxVertexInputBindingStride`, not a multiple of the alignment, breaking the portability -//! subset's stride rule, or as dynamic state below an element's attributes) names its layout in -//! the plan's pulled-vertex-buffer variant, which pulls the layout's attributes, and so does a -//! binding whose layout the shape names among those the device cannot fetch for the draw -//! (`BindShape::far_vertex_buffers`: one a draw may fetch past `2^32` bytes of its bind offset -//! on a driver whose fixed-function input wraps there, or every one of a draw replay's, whose -//! commands bind their own buffers), which needs no bound buffer; a pipeline -//! compiled under such a variant keeps naming its layouts, so the key is a fixed point. Per draw, -//! a binding's extent is the bytes its vertex or instance range fetches, and with dynamic strides -//! every binding's stride is listed. -//! - **Push fields** per stage window: the root-table and status addresses are holes the consumer -//! fills (one root table per stage that reads one: its `Psb` entries are that stage's slots), -//! `BaseVertexInstance` is the draw's Vulkan base vertex and first instance, -//! `SlotBindOffset`/`SlotGuestBase` as in compute, and `VertexBufferStride` a pulled layout's -//! static stride, or for a per-bind one the bind's `attributeStride` (0 without one, inline -//! bytes' as a buffer's, as for fixed function). -//! - **Specialization.** One key over both stages' constants (link numbers `SpecId`s over the -//! pipeline, so a key's entries are disjoint per id): `Presence`, `SamplerState` (the bound -//! sampler's word masked by the fields the function reads), `BicubicTexels` (the bound format's -//! treatment under Metal's bicubic filter), `SampleCount` (the pipeline's rasterization samples), -//! `AmplificationCount` (the shape's vertex amplification count), and a fragment function's tile -//! threadgroup memory's (`TgOffset`, `TileThreadgroupLength`, `TileGridWidth`, and the pass's -//! tile as `ImageblockWidth` and `ImageblockHeight`). -//! - **Views**. A count of 0, above 1 for a pipeline whose `maxVertexAmplificationCount` is 1, or -//! with fewer view mappings than the count is `InvalidVertexAmplification`. A count above a -//! larger maximum draws that many amplifications, as plain Metal draws them where its validation -//! stops the count (a Metal probe: 3 and 4 on a maximum of 2, 4 on 3, 8 on 2 and on 4, an M4). -//! Amplification `a` renders into the layer of the pass its render target offset `rto[a]` (plus -//! the slice the vertex function chooses, if it does) names where that is below the pass's -//! `renderTargetArrayLength`, and into the first layer where it is not, every one in a pass of at -//! most one layer (`nil` mappings are offsets of 0; a Metal probe on an M4, the rule for an -//! index), and a pipeline of `maxVertexAmplificationCount` 1 takes no mapping (its draws render -//! the first layer through viewport 0; Metal probes); through the viewport its viewport offset -//! `vpo[a]` plus the function's index names; and Metal renders every primitive of every instance -//! of one amplification before the next's (a Metal probe on an M3 Max and an M4, with and without -//! API validation). The plan's `views` are Vulkan multiview, amplification `a` view `a` in -//! attachment layer `a`, where that is exact: the mappings add no viewport offset, those layers -//! are consecutive (`l[a] = l[0] + a`, `l[0]` the views' base layer), the count is within the -//! device's `maxMultiviewViewCount`, the shape does not ask for one draw per amplification -//! (`VertexAmplification::one_at_a_time`, under a visibility query), and no stage declares -//! `Layer` and the vertex function chooses its slice in no variant (a multiview pipeline cannot -//! declare it) unless the count is 1 into the first layer; a count of 1 draws without multiview -//! into layer `l[0]`. Every other amplification draws one amplification at a time: the plan's -//! variant is `amplification_draws` (`layered` in a pass of more than one layer, `viewports` -//! where an offset is not 0), whose stages read the amplification's id and offsets from push -//! fields (`PushField::AmplificationId`, `AmplificationLayerOffset`, -//! `AmplificationViewportOffset`), and `DrawCommands::amplifications` writes them before each -//! draw. A tessellation pipeline drawn so is not implemented. -//! - **Render target slice**. A vertex function that writes `[[render_target_array_index]]` -//! (`RuntimeFact::RenderTargetArrayLength`) selects a slice only in a pass of at least two -//! layers. In every pass the pipeline writes `Layer` as 0 for an index at or past its -//! `PushField::RenderTargetArrayLength`, the pass's length -//! (`BindState::render_target_array_length`), which each draw writes as at least 1: Metal -//! renders such an index into the pass's first layer, and in a pass of at most one layer (a -//! length of 0, Metal's default, or 1) every index renders slice 0, so a one-layer framebuffer -//! is never written an out-of-range `Layer`, which Vulkan leaves undefined. -//! - **Viewport count**. A vertex function that writes `[[viewport_array_index]]` -//! (`RuntimeFact::ViewportCount`) stores `ViewportIndex` as 0 for an index at or past its -//! `PushField::ViewportCount`, the encoder's viewport count (`BindState::viewport_count`), which -//! each draw writes: Metal draws such an index through viewport 0. -//! - **Zeroed colors**. A draw into a pass with color attachments its pipeline has no pixel format -//! for (`BindShape::zeroed_colors`), where plain Metal stores zero bytes at every sample the draw -//! covers, runs the variant whose pipeline has them, written whole and unblended, and whose -//! fragment function writes zero to them (`VariantKey::zeroed_colors`); and its colors the pass -//! 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. -//! - **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 -//! (`VariantKey::depth_clamp_range`), from the draw's `PushField::DepthClampRange` -//! (`BindState::depth_clamp_range`), as Metal stores a negative NaN as 0 past the range. -//! - **Rotated weights**. A draw of triangles drawn with Metal's last vertex first -//! (`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`). -//! - **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, the plan is -//! multiview or the draw is indexed, in which case `indirect_needs_arguments` asks for the CPU -//! read. -//! `VerticesPerPrimitive` (a vertex function that writes the primitive ID, -//! `LoweringInputs::primitive_id_varying`) is the draw's primitive type's vertices per -//! primitive (`BindState::primitive_type`; `MissingPrimitiveType` without one), a direct or -//! indirect draw's alike. An indexed draw of such a pipeline, whose vertices primitives share, -//! runs its de-indexed variant of the draw's index type (`BindShape::primitive_id_indices`, -//! `VariantKey::primitive_id_indices`): `index count` vertices from 0 with its instances, -//! layout `[0, index count, base instance, base vertex]` (`PushField::CaptureLayout`), leaving -//! `PushHole::CaptureIndexAddress` to the consumer (its first index's address), and reading its -//! indices in the vertex stage as storage (`DrawCommands::uses`); any other draw of that variant is -//! `NeedsVariant` without it. A strip, an indirect indexed draw, indices past their buffer and -//! an indexed draw of a plan without the form are `NotImplemented(PrimitiveId)`. A draw of one -//! of Metal's private primitive types in the private list form (`BindShape::private_list`, -//! `VariantKey::private_list`) is the consumer's list, which it draws without indices from the -//! list's first index as first vertex whatever the call it gave: its vertices per primitive are -//! its list's, twice that where the list holds Metal's quads as two triangles a quad -//! (`BindState::quad_primitive_ids`), and it leaves `PushHole::CaptureIndexAddress` to the -//! consumer (its list's address, whose word before its first index holds Metal's base -//! vertex). A direct -//! draw of a multiview plan whose last instance index exceeds `maxMultiviewInstanceIndex` is -//! `Unsupported{VertexAmplification; Limit}`. `DrawCommands.uses` lists the draw's index buffer -//! and indirect arguments. A draw of a rate-mapped pass's regions several at a time -//! (`BindShape::region_viewports`) runs the variant whose vertex function stores its draw's -//! index among a multi-draw's as `ViewportIndex` (`VariantKey::region_viewports`), where its -//! pipeline is a vertex pipeline without tessellation drawn in one pass of no views; a mesh, -//! tessellated or amplified draw keeps the plain variant, and the consumer draws its regions one -//! at a time: the plan's variant says which. -//! - **Index buffer bounds**. A direct indexed draw whose indices run past where Metal's fetch -//! stops reading its index buffer (`IndexBufferRef::fetch_end`: the length rounded up to 4 bytes; -//! Metal's API validation rejects the draw, and Apple's GPUs read index 0 past there) is clamped -//! to the indices wholly before there, since Vulkan requires every index inside the bound range -//! without `robustBufferAccess2`, which the translator leaves no fetch to -//! (`VUID-vkCmdDrawIndexed-robustBufferAccess2-08798`); `DrawCommands::index_overrun` records -//! it. Vulkan names no index for a fetch past the bound range even under `robustBufferAccess2`, -//! so the runtime draws such a draw from a copy of its indices padded with zeros, which leaves no -//! overrun here. The check is on the CPU: no shader reads anything for it. An indexed indirect -//! draw's counts are in GPU memory, so it asks for its arguments on the CPU -//! (`indirect_needs_arguments`), and the direct draw is bounded as above. -//! - **Tessellation**. A tessellation pipeline's Metal stages are its evaluation stage (the vertex -//! function, whose push range, bindings, and uses name `TESSELLATION_EVALUATION`) and its -//! fragment stage; its synthesized vertex and control stages bind nothing of Metal's. The control -//! stage's factor buffer is the encoder's (`BindState::tessellation_factors`, -//! `WriteSource::TessellationFactors`, read in `TESSELLATION_CONTROL_SHADER`), or the zero -//! buffer, whose patches are all culled, when the encoder set none. Its draws draw patches -//! (`DrawCall::Patches`, `DrawCall::PatchesIndirect`): one vertex per patch, from the patch -//! start, with the draw's instances; each pushes the control stage's range (the factor buffer's -//! residual bind offset, instance stride rounded down to a multiple of 4, and scale rounded to -//! `half`) and binds the factors it reads (`patch_draw`). A draw's patch index buffer binds the -//! control stage's `WriteSource::PatchIndices` over the indices it reads (read in -//! `TESSELLATION_CONTROL_SHADER`), and its push range says the draw has one; a draw without one -//! leaves the zero buffer there. A pipeline with a control-point index type draws indexed patches -//! only, each binding its control-point index buffer (`WriteSource::ControlPointIndices`, read in -//! `TESSELLATION_CONTROL_SHADER`) over the indices it reads, whose residual bind offset its push -//! range holds; one without draws patches without such a buffer only. A draw of primitives with -//! it, a draw of patches with any other pipeline, another control-point count than the -//! function's, a patch draw whose indexing differs from the pipeline's, misaligned or overlong -//! factors, patch indices or control-point indices, and a scale that is not a positive normal -//! `half` (which Metal forbids, and which keeps every float the control stage computes finite) -//! are `BindError`s. On a device without `drawIndirectFirstInstance` an indirect draw asks for -//! its arguments on the CPU (`DrawCommands::indirect_needs_arguments`). -//! - **Mesh draws**. A mesh render pipeline's Metal stages are its object function, when it has one -//! (`TASK_EXT`), its mesh function (`MESH_EXT`) and its fragment function. It draws only mesh -//! draws (`DrawCall::MeshThreadgroups`, `MeshThreads`, `MeshThreadgroupsIndirect`), and only it -//! does (`BindError::InvalidMeshDraw`). Each stage's threadgroup size is a specialization each -//! draw decides, as a kernel's region's is, the object function's under keys of its own -//! (`SpecKey::ObjectLocalSize`): the plan's `specialization` leaves them out, and each draw's -//! `DrawCommands::specialization` is the complete key. A direct draw is `vkCmdDrawMeshTasksEXT` -//! of the first stage's threadgroups (without an object function, `drawMeshThreads`' threads -//! rounded down to whole mesh threadgroups, Metal's answer; with one, its object threadgroups, of -//! `drawMeshThreads` the threads fill, rounded up, the last along an axis running only the -//! threads left, as Metal runs it: its region flagged `lower::dispatch::NONUNIFORM`, which an -//! object function of `RuntimeFact::PartialObjectThreadgroups` reads, and not implemented for an -//! object function whose body holds a workgroup barrier) and each stage reads its grid from -//! `NumWorkgroups` (`MultiRegion` 0, each `DispatchRegion` written all the same, but 1 for a -//! partial object threadgroup's draw); a threadgroup of no thread or of more than -//! Metal's 1024, a grid of none, and indirect arguments at an offset that is not a multiple of 4 -//! launch nothing, as plain Metal draws nothing. A threadgroup or a grid past the device's limits -//! for its stage is `Unsupported{MeshShading}` naming the limit (an object grid only where the -//! object function is not folded, below). An object function's threadgroup -//! memory arguments are the encoder's lengths (`setObjectThreadgroupMemoryLength:atIndex:`, the -//! object stage's `threadgroup_lengths`, 0 where unset), each rounded up to 16 as a kernel's -//! are; its arena with them past the object stage's workgroup memory limit is -//! `Unsupported{ThreadgroupMemorySize}` naming it (`RuntimeFact::ObjectThreadgroupArena`). A -//! mesh function's arguments, which no encoder sets, are not implemented. A mesh grid Metal -//! draws nothing for (an axis past 65,535, or more than 1,048,575 threadgroups: -//! `bind::mesh_arguments`) launches nothing. An indirect draw reads the counts an arguments -//! pass writes (`DrawCommands::mesh_arguments`, `MeshArguments`): Metal's where Metal draws -//! them and the device's first stage launches them, else none. A folded object function -//! (`lower::mesh::folds_object_grids`) runs any object grid in pieces within the task stage's -//! limits instead, reading its grid from its region record: a direct draw's fold is the -//! consumer's upload (`DrawCommands::object_fold`), an indirect one's its arguments pass's. A -//! direct object grid is Metal's (`metal_object_grid`: its threads per grid wrap at 2^32, and it -//! runs the threadgroups they fill); one of more threadgroups than Metal runs -//! (`METAL_OBJECT_GRID_TOTAL`) launches nothing and fails its command buffer as Metal's GPU -//! discards it (`DrawCommands::discards_command_buffer`), on every device. -//! A mesh function writes `Layer` in every variant: a pass of more layers than -//! `maxMeshOutputLayers`, into which a mesh function choosing its slice could render, is -//! `Unsupported{MeshShading}` naming it. A view mapping with a viewport offset, or with a slice -//! offset where the mesh function chooses its slice, is not implemented: the mesh function does -//! not add it. A mesh pipeline draws with an amplification count of 1 (its -//! `maxVertexAmplificationCount`). +//! A Metal draw call in Metal's terms ([`DrawCall`], with its index buffer, [`IndexBufferRef`]), +//! and the code a pipeline's private alpha test compares with ([`alpha_test_code`]). How a draw +//! becomes Vulkan draws, after the pipeline's interface and push fields, is the consumer's. -use std::collections::BTreeMap; - -use crate::bind::heap::{planner, HeapPlanner}; -use crate::bind::instantiate::{ - bind_buffers, descriptor_range, put, slot_field, BufferExtent, BufferRange, DescriptorBytes, - DescriptorRange, FieldBytes, IndexBufferRef, IndirectRef, PushConstantWrite, PushHole, - RangeError, RootTable, -}; -use crate::bind::mesh_arguments::{ - fold_object_grid, metal_mesh_grid_draws_nothing, metal_object_grid, MeshArguments, - MeshArgumentsForm, MeshGridLimits, ObjectFold, METAL_OBJECT_GRID_TOTAL, -}; -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, - check_sparse_textures, cross_variant, cubic_variant, heap_raw, plan_buffer, psb_variant, - range_variant, record_noted, srgb_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, 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, 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::{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; -use crate::pipeline::artifact::RenderPipeline; -use crate::pipeline::facts::RuntimeFact; -use crate::pipeline::interface::{ - AccessSet, BufferForm, BufferSlot, PushLoc, SlotInterface, Window, -}; -use crate::pipeline::layout::BindingSource; -use crate::pipeline::sym::{ - Axis, DispatchKeys, PushField, SlotClass, SlotRef, SpecKey, Stage, SyntheticBinding, -}; -use crate::pipeline::vertex::{VertexAttribute, VertexStride}; -use crate::pipeline::AmplificationDraws; use crate::vk; +/// A consumer-owned index buffer. +#[non_exhaustive] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct IndexBufferRef { + /// The consumer's id for the buffer. + pub token: u32, + /// The end of the buffer's bytes (`MTLBuffer.length`), in the offsets the draw binds the + /// `VkBuffer` at (the length itself where the consumer binds the buffer from its start). + pub length: u64, +} + +impl IndexBufferRef { + /// The consumer's index buffer `token`, `length` bytes long. + pub fn new(token: u32, length: u64) -> IndexBufferRef { + IndexBufferRef { token, length } + } +} + /// A Metal draw call. #[non_exhaustive] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] @@ -266,8 +35,7 @@ pub enum DrawCall { instance_count: u32, base_instance: u32, }, - /// `drawIndexedPrimitives:indexCount:indexType:indexBuffer:indexBufferOffset:…`. Indices - /// past `index_buffer`'s length are bounded as [`DrawCommands::index_overrun`] states. + /// `drawIndexedPrimitives:indexCount:indexType:indexBuffer:indexBufferOffset:…`. Indexed { index_type: vk::IndexType, index_buffer: IndexBufferRef, @@ -277,13 +45,6 @@ pub enum DrawCall { base_vertex: i32, base_instance: u32, }, - /// `drawPrimitives:indirectBuffer:…`, or the indexed form when `indexed` is set (its index - /// type, buffer, and index offset). The indexed form, whose index fetch nothing bounds, asks - /// for its arguments on the CPU ([`DrawCommands::indirect_needs_arguments`]). - Indirect { - indirect: IndirectRef, - indexed: Option<(vk::IndexType, IndexBufferRef, u64)>, - }, /// `drawPatches:patchStart:patchCount:patchIndexBuffer:patchIndexBufferOffset:instanceCount: /// baseInstance:` of a tessellation pipeline. `control_points` is `numberOfPatchControlPoints`; /// `patch_index` the patch index buffer and its offset, a multiple of 4 (`None` for `nil`): the @@ -302,16 +63,6 @@ pub enum DrawCall { base_instance: u32, control_point_index: Option<(IndexBufferRef, u64)>, }, - /// `drawPatches:patchIndexBuffer:patchIndexBufferOffset:indirectBuffer: - /// indirectBufferOffset:`, whose `MTLDrawPatchIndirectArguments` (`patchCount`, - /// `instanceCount`, `patchStart`, `baseInstance`) are a `VkDrawIndirectCommand`, or with - /// `control_point_index`, `drawIndexedPatches:...indirectBuffer:indirectBufferOffset:`. - PatchesIndirect { - control_points: u32, - patch_index: Option<(IndexBufferRef, u64)>, - indirect: IndirectRef, - control_point_index: Option<(IndexBufferRef, u64)>, - }, /// `drawMeshThreadgroups:threadsPerObjectThreadgroup:threadsPerMeshThreadgroup:` of a mesh /// render pipeline: `groups` object threadgroups of `threads_per_object_group` threads, each /// launching the mesh grid it sets, or, without an object function, `groups` mesh @@ -329,1375 +80,6 @@ pub enum DrawCall { threads_per_object_group: [u32; 3], threads_per_mesh_group: [u32; 3], }, - /// `drawMeshThreadgroupsWithIndirectBuffer:indirectBufferOffset:threadsPerObjectThreadgroup: - /// threadsPerMeshThreadgroup:`, whose `MTLDispatchThreadgroupsIndirectArguments` are the - /// direct form's `groups` (GPU-written). - MeshThreadgroupsIndirect { - indirect: IndirectRef, - threads_per_object_group: [u32; 3], - threads_per_mesh_group: [u32; 3], - }, -} - -/// What the consumer records for one draw: upload `descriptor_bytes` and each stage's root table, -/// bind every plan descriptor (buffer and texel-buffer descriptors over exactly -/// `descriptor_ranges`), bind the plan's vertex buffers at `buffer_offsets` (with -/// `vertex_strides` as dynamic strides), fill the `push_holes`, push `push_constants`, and record -/// `draw`. -#[non_exhaustive] -#[derive(Clone, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct DrawCommands { - /// One write per stage with push fields, covering the stage's whole push range. - pub push_constants: Vec, - /// Each stage's `ArgumentTable` contents, then the plan's heap tables (its handle tables, - /// sampler tables and function-table directories). - pub descriptor_bytes: Vec, - /// Vertex-buffer offsets by Vulkan vertex binding (`vkCmdBindVertexBuffers`). - pub buffer_offsets: Vec<(u32, u64)>, - pub draw: vk::DrawCommand, - /// The command is indirect but the profile emulates base vertex/instance through push fields - /// (`BaseVertexInstance` without `shaderDrawParameters`), the plan's draws are multiview, whose - /// instances must stay within `maxMultiviewInstanceIndex`, or the device lacks - /// `drawIndirectFirstInstance`, without which an indirect command's `firstInstance` must be 0 - /// while Metal's indirect arguments may carry a base instance - /// (`VUID-VkDrawIndirectCommand-firstInstance-00501`), or nothing bounds an indexed draw's - /// index fetch (the device lacks `robustBufferAccess2`, without which every index must lie - /// inside the bound range, or the index offset is at or past the buffer's length): the consumer - /// must read the indirect arguments on the CPU and instantiate a direct draw instead. An - /// indexed draw's direct `index_offset` is the indirect one plus `indexStart` indices. - pub indirect_needs_arguments: bool, - /// Per bound buffer slot and vertex buffer, the window this draw can touch (a fixed-function - /// vertex buffer's is what the draw's vertex or instance range fetches, and `Whole` when those - /// are GPU-side). - pub extents: Vec, - pub push_holes: Vec, - /// The range of every buffer and texel-buffer descriptor the plan writes. - pub descriptor_ranges: Vec, - /// The resident root table of each stage that reads one; the stage's - /// `PushHole::RootTableAddress` takes its address. - pub root_tables: Vec<(vk::ShaderStageFlags, RootTable)>, - /// Vertex strides by Vulkan vertex binding, in binding order. When the pipeline's strides are - /// dynamic state (`GraphicsState.dynamic_states` holds `VERTEX_INPUT_BINDING_STRIDE`), every - /// binding's stride, static ones included: `vkCmdBindVertexBuffers2` takes one per binding in - /// `pStrides`. Otherwise each `VertexStride::PerBind` binding's, which a profile without - /// dynamic strides makes static pipeline state. - pub vertex_strides: Vec<(u32, u32)>, - /// The draw's own resources beyond the plan's `uses`: its index buffer and indirect - /// arguments. A de-indexed draw reads its indices in the vertex stage as storage - /// (`VERTEX_SHADER`, from the index offset over its indices), by address, and binds no index - /// buffer. - pub uses: Vec, - /// A direct indexed draw that reads indices past its index buffer: how `draw` - /// treats those index positions. `None` for every other draw. - pub index_overrun: Option, - /// A plan that draws each vertex amplification as a draw of its own (`BindingPlan::variant`'s - /// `amplification_draws`): one entry per amplification, in order, the push writes that make the - /// next draw that amplification's (its id and its view mapping's offsets, in each stage that - /// reads them). The consumer records `draw` once per entry, each after `push_constants` and the - /// entry's writes, all in one render pass instance: Metal renders every primitive of every - /// instance of one amplification before the next amplification's (a Metal probe on the M3 Max - /// and an M4), which these draws reproduce. An indirect draw is recorded from the same - /// arguments each time. Empty for every other plan, whose draw is recorded once. - pub amplifications: Vec>, - /// A mesh draw's complete specialization, which replaces the plan's: the plan's constants, - /// the mesh threadgroup's size (`SpecKey::LocalSize`, and its product where the stage's local - /// size is flattened), and `SpecKey::MultiRegion` 0, and an object function's likewise - /// (`SpecKey::ObjectLocalSize`, `ObjectFlatLocalSize`, `ObjectMultiRegion`). The consumer creates the draw's - /// `VkPipeline` with it. `None` for every other draw, whose pipeline takes the plan's. - pub specialization: Option, - /// An indirect mesh draw on a device with `VK_EXT_mesh_shader`, whose first stage's group - /// counts `vkCmdDrawMeshTasksIndirectEXT` requires within the device's limits: the form of the - /// arguments pass the consumer records before the draw ([`MeshArguments`]), whose scratch the - /// draw then reads in place of Metal's arguments (`draw` keeps Metal's offset; the consumer substitutes the scratch's - /// buffer and offset). Its read of Metal's 12 bytes is among `uses`, in the compute stage. - /// `None` for every other draw. - /// - /// The folded object form's (`MeshArgumentsForm::FoldedObject`, a folded object function's - /// draw) `draw` is `DrawMeshTasksIndirectCount`, both of whose offsets are into the scratch - /// (the consumer adds the scratch's offset), and the object stage's - /// `PushHole::ReplayRegionAddress` takes the device address of the scratch's region record; - /// its scratch needs `SHADER_DEVICE_ADDRESS` usage and a 16-aligned address. - pub mesh_arguments: Option, - /// A direct mesh draw of a folded object function's pipeline: the fold of its object grid - /// ([`ObjectFold`]), whose region record, piece count and pieces' commands the consumer - /// uploads at a 16-aligned device address of a buffer of `SHADER_DEVICE_ADDRESS` and `INDIRECT_BUFFER` - /// usage, where the host's write is visible to the draw. The object stage's - /// `PushHole::ReplayRegionAddress` takes that address, and a `draw` of `DrawMeshTasksIndirect` - /// (its pieces) reads its commands from the upload, its offset into it. A fold `past` the - /// device's pieces draws nothing (`draw` launches no threadgroup), and the consumer fails the - /// command buffer as for `ExecutionStatus`'s `MESH_GRID_PAST_LIMITS`. `None` for every other - /// draw. - pub object_fold: Option, - /// A direct mesh draw whose object grid Metal's GPU discards: more threadgroups than - /// [`METAL_OBJECT_GRID_TOTAL`], past what Metal runs within its watchdog's 5 seconds - /// (`bind::mesh_arguments`). `draw` launches no threadgroup, and the consumer fails the command - /// buffer from the draw's encoder on as Metal does: the encoder and every one after it run - /// nothing, and the command buffer completes with `MTLCommandBufferErrorInternal` (1, - /// "Discarded (victim of GPU error/recovery)"). - pub discards_command_buffer: bool, -} - -/// No draw's commands: empty vectors and a draw of no vertices, which -/// [`BindingPlan::instantiate_draw_into`] writes over. -impl Default for DrawCommands { - fn default() -> DrawCommands { - DrawCommands { - push_constants: Vec::new(), - descriptor_bytes: Vec::new(), - buffer_offsets: Vec::new(), - draw: vk::DrawCommand::Draw { - vertex_count: 0, - instance_count: 0, - first_vertex: 0, - first_instance: 0, - }, - indirect_needs_arguments: false, - extents: Vec::new(), - push_holes: Vec::new(), - descriptor_ranges: Vec::new(), - root_tables: Vec::new(), - vertex_strides: Vec::new(), - uses: Vec::new(), - index_overrun: None, - mesh_arguments: None, - object_fold: None, - discards_command_buffer: false, - amplifications: Vec::new(), - specialization: None, - } - } -} - -/// How a direct indexed draw treats its index positions past the index buffer: the positions whose -/// bytes do not lie wholly before where Metal's fetch stops reading it -/// ([`IndexBufferRef::fetch_end`], the length rounded up to 4 bytes). Metal's API validation -/// rejects such a draw (`indexBufferOffset + indexCount × size` must be at most the buffer's -/// length), and Apple documents no result for it; on an Apple M3 Max (macOS 26.7) and an M4 -/// (macOS 27.0.1) each such position reads index 0, to which the base vertex is added. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub enum IndexOverrun { - /// Not drawn: without `robustBufferAccess2` every index a Vulkan draw reads must lie inside - /// the bound index buffer range (`VUID-vkCmdDrawIndexed-robustBufferAccess2-08798`), so - /// `draw` takes only the indices wholly before [`IndexBufferRef::fetch_end`]. A draw with - /// no index before there draws no index, bound at offset 0, since its index offset may lie - /// past the `VkBuffer`, where it cannot be bound. - Clamped { - /// The index positions past the buffer, which `draw` leaves out. - past_end: u32, - }, -} - -impl RenderPipeline { - /// The shape-level binding plan of this pipeline for `shape`: a pure function of the pipeline, - /// `device` (the device that compiled it), and the shape. Per-draw bytes come from - /// [`BindingPlan::instantiate_draw`]. - pub fn plan(&self, device: &Device, shape: &BindShape) -> Result { - plan(self, device, shape) - } -} - -/// The Metal stage of each of a render pipeline's modules `stages` (in pipeline order) that runs -/// a Metal function, with its Vulkan stage: a tessellation pipeline's (`tessellated`) synthesized -/// vertex and control stages run none, and its post-tessellation vertex function is its -/// evaluation stage; a mesh render pipeline's object and mesh functions are its task and mesh -/// stages; a band variant's (`banded`) control and evaluation stages (`link::band`) run none -/// and bind nothing. -fn metal_stages( - stages: impl ExactSizeIterator, - (tessellated, banded): (bool, bool), -) -> Result, BindError> { - let mut out = Vec::with_capacity(stages.len()); - for s in stages { - let stage = if s == vk::ShaderStage::FRAGMENT { - Stage::Fragment - } else if s == vk::ShaderStage::MESH_EXT { - Stage::Mesh - } else if s == vk::ShaderStage::TASK_EXT { - Stage::Object - } else if s == vk::ShaderStage::VERTEX && !tessellated - || s == vk::ShaderStage::TESSELLATION_EVALUATION && tessellated - { - Stage::Vertex - } else if tessellated - && (s == vk::ShaderStage::VERTEX || s == vk::ShaderStage::TESSELLATION_CONTROL) - || banded - && (s == vk::ShaderStage::TESSELLATION_CONTROL - || s == vk::ShaderStage::TESSELLATION_EVALUATION) - { - continue; - } else { - return Err(internal(format!("a render pipeline stage {s:?}"))); - }; - out.push((stage, s)); - } - Ok(out) -} - -/// Whether a module of mesh render pipeline `p` other than its object function's declares -/// threadgroup memory arguments (`SpecKey::TgLength`): a mesh function's, whose lengths no encoder -/// setter sets. The object module is the task stage, as [`metal_stages`] names it. -fn other_stage_lengths(p: &RenderPipeline) -> bool { - p.stages.iter().any(|m| { - m.stage != vk::ShaderStage::TASK_EXT - && m.specialization - .constants - .iter() - .any(|c| matches!(c.key, SpecKey::TgLength(_))) - }) -} - -/// The vertex-stage buffer slot of Metal buffer index `index`. -fn vertex_buffer(index: u32) -> SlotRef { - SlotRef { - stage: Stage::Vertex, - class: SlotClass::Buffer, - index, - } -} - -fn pipeline_stage(stage: Stage) -> vk::PipelineStageFlags2 { - match stage { - Stage::Vertex => vk::PipelineStageFlags2::VERTEX_SHADER, - Stage::Fragment => vk::PipelineStageFlags2::FRAGMENT_SHADER, - Stage::Kernel => vk::PipelineStageFlags2::COMPUTE_SHADER, - Stage::Object => vk::PipelineStageFlags2::TASK_SHADER_EXT, - Stage::Mesh => vk::PipelineStageFlags2::MESH_SHADER_EXT, - } -} - -/// [`pipeline_stage`] of a tessellation pipeline, whose vertex function is its evaluation stage. -fn tessellated_pipeline_stage(stage: Stage) -> vk::PipelineStageFlags2 { - match stage { - Stage::Vertex => vk::PipelineStageFlags2::TESSELLATION_EVALUATION_SHADER, - other => pipeline_stage(other), - } -} - -/// How a plan draws the shape's vertex amplification. -#[derive(Clone, Debug, PartialEq, Eq)] -enum Route { - /// As Vulkan multiview views (at a count of 1, into one layer without multiview). - Views(ViewSetup), - /// One draw per amplification, in amplification order: the `(render target slice offset, - /// viewport offset)` of each, in a pass of more than one layer when `layered`. - Draws { - offsets: Vec<[u32; 2]>, - layered: bool, - }, -} - -/// The route of draws under vertex amplification `amp` with a pipeline whose -/// `maxVertexAmplificationCount` is `max` and in which a stage chooses or reads the render -/// target slice when `declares_layer`, in a pass whose `renderTargetArrayLength` is `length`, -/// on a device of `max_views` multiview views (see the module docs). -fn route( - amp: &VertexAmplification, - max: u32, - declares_layer: bool, - length: u32, - max_views: u32, -) -> Result { - let count = amp.count; - let given = u32::try_from(amp.view_mappings.len()).unwrap_or(u32::MAX); - if count == 0 || (count > 1 && max == 1) || (given != 0 && given < count) { - return Err(BindError::InvalidVertexAmplification { - count, - max, - view_mappings: given, - }); - } - // A pipeline of `maxVertexAmplificationCount` 1 takes no mapping; the layer amplification `a` - // renders into is its offset below the pass's layers, the first layer at or past them (a Metal - // probe on an M4). - let mapping = |a: u32| amp.mapping(a, max); - let layer = |a: u32| amp.layer(a, length, max); - let base_layer = layer(0); - let consecutive = (0..count).all(|a| { - mapping(a).viewport_array_index_offset == 0 && Some(layer(a)) == base_layer.checked_add(a) - }); - let as_views = consecutive - && (count == 1 || (count <= max_views && !amp.one_at_a_time)) - && !(declares_layer && (count > 1 || base_layer != 0)); - if !as_views { - // Metal renders amplification-major, every primitive of every instance of one amplification - // before the next's (a Metal probe on the M3 Max and an M4): exactly a draw of each in - // turn. - return Ok(Route::Draws { - offsets: (0..count) - .map(|a| { - let m = mapping(a); - [ - m.render_target_array_index_offset, - m.viewport_array_index_offset, - ] - }) - .collect(), - layered: length > 1, - }); - } - Ok(Route::Views(ViewSetup { - view_mask: if count == 1 { - 0 - } else { - 1u32.checked_shl(count).map_or(u32::MAX, |bit| bit - 1) - }, - base_layer, - })) -} - -/// Whether the vertex function of `p` chooses its render target slice, and if so whether it was -/// compiled without its `Layer` output (`RuntimeFact::RenderTargetArrayLength`). -fn vertex_layer(p: &RenderPipeline) -> Option { - p.dependencies.iter().find_map(|d| match d.fact { - RuntimeFact::RenderTargetArrayLength { layer_dropped } => Some(layer_dropped), - _ => None, - }) -} - -fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result { - check_slots(shape)?; - let tessellation = p.graphics.tessellation.is_some(); - let modules = metal_stages( - p.stages.iter().map(|m| m.stage), - ( - p.graphics.tessellation.is_some(), - p.graphics.line_band.is_some(), - ), - )?; - let stages: Vec = modules.iter().map(|(stage, _)| *stage).collect(); - // A mesh render pipeline (`Device::compile_mesh_pipeline`) is drawn by mesh draws. - let mesh = stages.contains(&Stage::Mesh); - // A vertex function that chooses its slice is never drawn amplified as views, whether or - // not this variant writes `Layer`: its amplified draws are draws of one amplification each. - let vertex_layer = vertex_layer(p); - // A fragment function compiled to read its slice as the amplification's offset declares `Layer` - // in the pipeline this variant is of: the route stays that pipeline's. - let reads_layer_offset = p.interface.push.iter().any(|pl| { - pl.stage == Stage::Fragment - && pl - .fields - .iter() - .any(|f| f.field == PushField::AmplificationLayerOffset) - }); - // A pipeline whose vertex function writes the primitive ID's varying runs an indexed draw - // in its de-indexed form, of the draw's index type. - let writes_primitive_ids = p.interface.push.iter().any(|pl| { - pl.stage == Stage::Vertex - && pl - .fields - .iter() - .any(|f| f.field == PushField::VerticesPerPrimitive) - }); - let primitive_id_indices = shape.primitive_id_indices.filter(|_| writes_primitive_ids); - // A draw of Metal's private quads, listed as two triangles a quad, whose fragment function - // reads Vulkan's `PrimitiveId` (not the varying a vertex function writes): the variant that - // reads the quad's. - let quad_primitive_ids = - shape.quad_primitive_ids && p.graphics.reads_primitive_id && !writes_primitive_ids; - let compiled_quads = p - .dependencies - .iter() - .any(|d| d.fact == RuntimeFact::QuadPrimitiveIds); - // A draw of one of Metal's private primitive types the consumer draws in the pulled list - // form: the variant that runs it so. - let private_list = shape.private_list; - let compiled_list = p - .dependencies - .iter() - .any(|d| d.fact == RuntimeFact::PrivateList); - let compiled_regions = p - .dependencies - .iter() - .any(|d| d.fact == RuntimeFact::RegionViewports); - let route = route( - &shape.vertex_amplification, - p.graphics.max_vertex_amplification_count, - p.graphics.declares_layer || vertex_layer.is_some() || reads_layer_offset, - shape.render_target_array_length, - device.profile().fields().limits.max_multiview_view_count, - )?; - let (views, amplification_draws, amplifications) = match route { - // A mesh pipeline's draw of more than one amplification is not built: multiview may run - // the task stage once a view, where Metal runs the object function once a draw, and a - // mesh function does not add a view mapping's offsets yet, as a draw of each amplification - // in turn would need. One amplification draws as a pipeline without amplification does. - Route::Views(views) if mesh && views.view_mask != 0 => { - return Err(not_implemented(Feature::VertexAmplification)) - } - Route::Views(views) => (views, None, Vec::new()), - // A tessellation pipeline's patches are not drawn one amplification at a time. - Route::Draws { .. } if tessellation => { - return Err(not_implemented(Feature::VertexAmplification)) - } - Route::Draws { .. } if mesh => return Err(not_implemented(Feature::VertexAmplification)), - Route::Draws { offsets, layered } => { - let viewports = offsets.iter().any(|&[_, viewport]| viewport != 0); - ( - ViewSetup::default(), - Some(AmplificationDraws::new(layered, viewports)), - offsets, - ) - } - }; - // A draw of a rate-mapped pass's regions several at a time, each a draw of a multi-draw: the - // variant whose vertex function stores its draw's index as `ViewportIndex`, where the - // pipeline is a vertex pipeline drawn in one pass of no views; a mesh or amplified draw keeps - // the plain variant, which the consumer draws region by region. - let region_viewports = shape.region_viewports - && !mesh - && !tessellation - && amplification_draws.is_none() - && views.view_mask == 0; - // The variant the pipeline was compiled under: its vertex function states it. - let compiled_draws = p.dependencies.iter().find_map(|d| match d.fact { - RuntimeFact::AmplificationDraws { layered, viewports } => { - Some(AmplificationDraws::new(layered, viewports)) - } - _ => None, - }); - // 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. - let tile_memory = tile_memory(&p.dependencies, device, shape)?; - if tile_memory.is_some() - && (shape.render_target_array_length > 1 || shape.vertex_amplification.count > 1) - { - return Err(not_implemented(Feature::TileShading)); - } - let profile = device.profile(); - let limits = &profile.fields().limits; - // The pass's colors the pipeline lacks, which plain Metal zeroes where the draw covers them: - // the variant whose pipeline has them and whose fragment function writes the zero. A mesh - // pipeline's is not built; a pipeline without a fragment function rasterizes into no color, - // and what Metal stores there is unmeasured, so a consumer zeroes none for it. - let zeroed_colors = shape.zeroed_colors.clone(); - if !zeroed_colors.is_empty() && mesh { - return Err(not_implemented(Feature::MeshShading)); - } - if !zeroed_colors.is_empty() && !stages.contains(&Stage::Fragment) { - return Err(internal( - "colors zeroed for a pipeline without a fragment function", - )); - } - let compiled_zeroed: std::collections::BTreeMap = p - .dependencies - .iter() - .filter_map(|d| match d.fact { - RuntimeFact::ZeroedColor { color, format } => Some((color, format)), - _ => None, - }) - .collect(); - // The pipeline's colors the pass lacks, whose writes plain Metal drops: the variant whose - // fragment function keeps no output there, so the pipeline writes no location without an - // attachment. A mesh pipeline's is not built. - let dropped_colors = shape.dropped_colors.clone(); - if !dropped_colors.is_empty() && mesh { - return Err(not_implemented(Feature::MeshShading)); - } - if !dropped_colors.is_empty() && !stages.contains(&Stage::Fragment) { - return Err(internal( - "colors dropped for a pipeline without a fragment function", - )); - } - let compiled_dropped: std::collections::BTreeSet = p - .dependencies - .iter() - .filter_map(|d| match d.fact { - RuntimeFact::DroppedColor { color } => Some(color), - _ => 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. - let depth_clamp_range = shape.depth_clamp_range && p.graphics.writes_depth; - let compiled_range = p - .dependencies - .iter() - .any(|d| d.fact == RuntimeFact::DepthClampRange); - // A draw of triangles with Metal's last vertex first: the variant whose fragment function - // takes Metal's barycentric weights back from the drawn triangle's. A pipeline whose fragment - // function reads no weights has none to take. - let rotated_weights = shape.rotated_weights && p.graphics.reads_barycentric_coord; - let compiled_rotated = p - .dependencies - .iter() - .any(|d| d.fact == RuntimeFact::RotatedWeights); - // A draw of lines, or of triangles' edges, as bands: the variant whose synthesized - // 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 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; - if mesh && vertex_layer.is_some() && shape.render_target_array_length > mesh_layers { - return Err(BindError::Unsupported(Unsupported::needs( - Feature::MeshShading, - Capability::Limit { - limit: VkLimit::MaxMeshOutputLayers, - required: u64::from(shape.render_target_array_length), - available: u64::from(mesh_layers), - }, - ))); - } - // The Vulkan stage of a Metal stage's module. - let vk_of = |stage: Stage| { - modules - .iter() - .find(|(s, _)| *s == stage) - .map_or_else(|| vk_stage(stage), |(_, m)| *m) - }; - let stage_flags: fn(Stage) -> vk::PipelineStageFlags2 = match &p.graphics.tessellation { - Some(_) => tessellated_pipeline_stage, - None => pipeline_stage, - }; - let bindings = bindings(&p.layout); - let stage_shape = |s: Stage| shape.stages.get(&s); - - // Buffer slots: the interface's. Every pulled source buffer is one of them, in the form the - // access family chose (a storage view or a device address, shared with a buffer argument of - // its index or its own). - let mut slots: BTreeMap = BTreeMap::new(); - for (&slot, iface) in &p.interface.slots { - match iface { - SlotInterface::Buffer(b) if stages.contains(&slot.stage) => { - slots.insert(slot, *b); - } - SlotInterface::Buffer(_) => { - return Err(internal(format!("a render pipeline uses {slot:?}"))) - } - SlotInterface::Texture(_) | SlotInterface::Sampler(_) => {} - } - } - if let Some(a) = p - .vertex_input - .pulled - .iter() - .find(|a| !slots.contains_key(&vertex_buffer(a.buffer_index))) - { - return Err(internal(format!( - "pulled vertex buffer {} without an interface slot", - a.buffer_index - ))); - } - let replayed = (p.dependencies.iter()).any(|d| d.fact == RuntimeFact::ReplayBindings); - let mut buffers = Vec::with_capacity(slots.len()); - for (slot, b) in &slots { - let bound = stage_shape(slot.stage).and_then(|s| s.buffers.get(&slot.index)); - buffers.push(plan_buffer((*slot, b, bound), replayed, limits, &bindings)?); - } - let planned = |slot: SlotRef| buffers.iter().find(|b| b.slot == slot); - // The layout stride of each pulled layout (one per Metal buffer index). - let pulled_stride = |layout: u32| { - p.vertex_input - .pulled - .iter() - .find(|a| a.buffer_index == layout) - .map(|a| a.stride) - }; - let mut pulled_strides: Vec<(u32, u32)> = p - .vertex_input - .pulled - .iter() - .filter_map(|a| match a.stride { - VertexStride::Static(s) => Some((a.buffer_index, s)), - VertexStride::PerBind => None, - }) - .collect(); - pulled_strides.sort_unstable(); - pulled_strides.dedup(); - - // Push placement, per stage. - let mut push = PushTemplate::default(); - let mut templates = Vec::new(); - for &stage in &stages { - let placement = p.interface.push.iter().find(|pl| pl.stage == stage); - let fields = placement.map(|pl| pl.fields.clone()).unwrap_or_default(); - let mut reads_root_table = false; - for field in &fields { - let hole = matches!( - field.field, - PushField::RootTableAddress - | PushField::ExecutionStatusAddress - | PushField::CaptureIndexAddress - | PushField::MergedDrawAddress - | PushField::ReplayRegionAddress - ); - match field.field { - PushField::RootTableAddress => reads_root_table = true, - PushField::ExecutionStatusAddress => {} - // A de-indexed or private list draw's indices, and its draw's layout: the address - // is the consumer's hole, the layout instantiation writes from the draw. - PushField::CaptureIndexAddress | PushField::CaptureLayout - if stage == Stage::Vertex => {} - PushField::BaseVertexInstance if stage == Stage::Vertex => {} - // A merged draw replay's header, which its vertex function and a fragment - // function that reads a command's buffers read: the consumer's hole. - PushField::MergedDrawAddress - if matches!(stage, Stage::Vertex | Stage::Fragment) => {} - // The draw's vertices per primitive, which instantiation writes from its - // primitive type. - PushField::VerticesPerPrimitive if stage == Stage::Vertex => {} - 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. - PushField::SlotGuestBase(slot) - if planned(slot).is_some_and(|b| b.bound != BoundKind::Bytes) => {} - PushField::SlotGuestBase(slot) if planned(slot).is_some() => { - return Err(BindError::MissingGuestAddress { slot }) - } - // The bound buffer's bytes before its bind offset and its length, which - // instantiation reads from the state. - PushField::SlotBounds(slot) if planned(slot).is_some() => {} - // The identity domains' zero range and private arena are the runtime's own - // memory, and their bicubic slot's format treatment the runtime's own field. - PushField::ZeroAddress - | PushField::BicubicTexels(_) - | PushField::PrivateArenaAddress => { - return Err(not_implemented(Feature::IdentityDomains)) - } - // Under the identity domains a texture's or sampler's word is its resource ID, a - // constexpr sampler's the runtime's own sampler, and a fetched color, the - // tessellation factors' address and an indirect command's range, sequence and - // base the runtime's own: fields the runtime pushes itself, which no binding state - // holds. - PushField::SlotGuestBase(SlotRef { - class: SlotClass::Texture | SlotClass::Sampler, - .. - }) - | PushField::ConstexprSampler(_) - | PushField::FetchedColor { .. } - | PushField::TessellationFactorAddress - | PushField::IndirectRange - | PushField::IndirectSequence - | PushField::IndirectBase => return Err(not_implemented(Feature::IdentityDomains)), - PushField::SlotBindOffset(SlotRef { - class: SlotClass::Texture, - .. - }) => return Err(not_implemented(Feature::TexelBuffer)), - // A storage texture's level count and integer channel widths, which the resource - // plan records. - PushField::TextureLevels(_) | PushField::TextureIntegerChannels(_) => {} - // A structure's instance count, which instantiation reads from the state. - PushField::InstanceCount(_) => {} - // 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 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) => {} - // The pass's array length, which instantiation reads from the state. - PushField::RenderTargetArrayLength - if matches!(stage, Stage::Vertex | Stage::Mesh) => {} - // A mesh draw's grid of each stage's threadgroups, which instantiation writes from - // the draw. - PushField::DispatchRegion if matches!(stage, Stage::Object | Stage::Mesh) => {} - // A folded object function's region record (`bind::mesh_arguments`): the - // consumer's hole. - PushField::ReplayRegionAddress if stage == Stage::Object => {} - // The draw's depth clamp range, which instantiation reads from the state. - PushField::DepthClampRange if stage == Stage::Fragment => {} - // The encoder's alpha test reference, which instantiation reads from the state. - PushField::AlphaTestReference if stage == Stage::Fragment => {} - // The encoder's blend color, which instantiation reads from the state. - PushField::HalfBlendColor 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. - PushField::AmplificationId - | PushField::AmplificationLayerOffset - | PushField::AmplificationViewportOffset - if matches!(field.loc, PushLoc::Push { .. }) => {} - PushField::VertexBufferStride(layout) if stage == Stage::Vertex => { - match pulled_stride(layout) { - Some(VertexStride::Static(_)) => {} - Some(VertexStride::PerBind) => { - // A buffer's or inline bytes' stride is its bind's, 0 without one. - match stage_shape(Stage::Vertex).and_then(|s| s.buffers.get(&layout)) { - Some(BufferShape::Buffer { .. } | BufferShape::Bytes { .. }) => {} - _ => { - return Err(internal(format!( - "the stride of vertex buffer {layout} bound by nothing" - ))) - } - } - } - None => { - return Err(internal(format!( - "the stride of vertex buffer {layout} without a pulled layout" - ))) - } - } - } - other => { - return Err(internal(format!( - "a {stage:?} push field {other:?} in a render pipeline" - ))) - } - } - if hole && !matches!(field.loc, PushLoc::Push { .. }) { - // The placement order puts the addresses first, so a stage window always holds - // them. - return Err(not_implemented(Feature::Lowering(LowerFamily::StageIo))); - } - push.fields.push(PushFieldPlacement { - stage, - field: field.field, - location: match field.loc { - PushLoc::Push { offset } => FieldLocation::PushWindow { offset }, - PushLoc::ArgumentTable { offset } => FieldLocation::ArgumentTable { offset }, - }, - size: field.size, - }); - } - let root_first = reads_root_table.then(|| { - let top = buffers - .iter() - .filter(|b| b.slot.stage == stage && b.form == BufferForm::Psb) - .map(|b| b.slot.index + 1) - .max() - .unwrap_or(0); - 2 + top - }); - templates.push(StageTemplate { - stage, - flags: vk_of(stage).flags(), - fields, - push_range: placement.and_then(|pl| pl.push_range), - table: None, - table_size: placement.map_or(0, |pl| pl.argument_table_size), - root_first, - }); - } - - // Descriptors. - let mut resources = ResourcePlanner { - profile, - shape: &shape.stages, - slots: &p.interface.slots, - dependencies: &p.dependencies, - stage_flags, - variant: Default::default(), - diagnostics: Vec::new(), - uses: Vec::new(), - template: Default::default(), - alpha_red_texels: Default::default(), - }; - let heap_reach = |s: metal::RenderStages| { - let mut out = Vec::new(); - for (flag, stage) in [ - (metal::RenderStages::VERTEX, Stage::Vertex), - (metal::RenderStages::FRAGMENT, Stage::Fragment), - (metal::RenderStages::OBJECT, Stage::Object), - (metal::RenderStages::MESH, Stage::Mesh), - ] { - if s.contains(flag) && stages.contains(&stage) { - out.push(stage); - } - } - out - }; - let mut heap = HeapPlanner::new(profile, &p.layout, &p.dependencies, shape, heap_reach)?; - let mut descriptors = Vec::new(); - let separate = separate_samplers(&p.layout); - let mut factor_binding = None; - let mut patch_index_binding = None; - let mut control_point_index_binding = None; - for set in &p.layout.sets { - for b in &set.bindings { - if let BindingSource::Heap(_) = b.source { - descriptors.extend(planner(&mut heap)?.array(set.set, b)?); - continue; - } - // A constexpr sampler array: the layout's immutable samplers, no write. - if let BindingSource::SamplerArray { .. } = b.source { - continue; - } - // A separate sampler: a constexpr one is the layout's immutable sampler, no write; a - // runtime one the sampler bound at its slot, made for the use. - if let BindingSource::SeparateSampler { stage, sampler } = b.source { - let source = - resources.separate_sampler(stage, sampler, b.immutable_sampler.as_ref())?; - if let Some(source) = source { - descriptors.push(DescriptorWrite { - set: set.set, - binding: b.binding, - array_element: 0, - ty: b.ty, - source, - }); - } - continue; - } - if let BindingSource::HeapSampler { stage, sampler } = b.source { - // A constexpr heap sampler is the layout's immutable sampler: no write. A runtime - // one is the sampler bound at its slot, made for the use. - let runtime = - planner(&mut heap)?.sampler(stage, sampler, b.immutable_sampler.as_ref())?; - if let Some(slot) = runtime { - descriptors.push(DescriptorWrite { - set: set.set, - binding: b.binding, - array_element: 0, - ty: b.ty, - source: resources.heap_sampler(slot, sampler)?, - }); - } - continue; - } - // A storage slot's level views, or a texture buffer's parts. - if let (0, BindingSource::Texture(slot)) = (set.set, b.source) { - if b.count > 1 { - let views = resources.slot_views(set.set, b.binding, b.ty, slot, b.count)?; - descriptors.extend(views.into_iter().zip(0..).map(|(source, i)| { - DescriptorWrite { - set: set.set, - binding: b.binding, - array_element: i, - ty: b.ty, - source, - } - })); - continue; - } - } - if set.set != 0 || b.count != 1 { - return Err(internal(format!( - "a {:?} binding of {} descriptors in set {}", - b.source, b.count, set.set - ))); - } - let source = match b.source { - BindingSource::Buffer(slot) => { - let pb = planned(slot).ok_or_else(|| { - internal(format!("binding of {slot:?} without an interface slot")) - })?; - match pb.bound { - BoundKind::Buffer { .. } => WriteSource::Buffer { slot }, - BoundKind::Bytes => WriteSource::InlineBytes { slot }, - BoundKind::Unbound => WriteSource::Neutral(NeutralResource::ZeroBuffer { - min_bytes: zero_buffer_bytes(profile), - }), - } - } - BindingSource::Texture(slot) => { - resources.texture(set.set, b.binding, b.ty, slot)? - } - BindingSource::Sampler(slot) => resources.sampler(slot)?, - BindingSource::CombinedTextureSampler { texture, sampler } => { - resources.combined(texture, sampler, b.immutable_sampler.as_ref())? - } - BindingSource::SeparateTexture { texture, sampler } => { - let immutable = separate.get(&(texture.stage, sampler)).ok_or_else(|| { - internal(format!( - "separate texture {texture:?} without its sampler {sampler:?}" - )) - })?; - resources.separate_texture(texture, sampler, *immutable)? - } - BindingSource::InputAttachment(color_index) => { - WriteSource::Attachment { color_index } - } - BindingSource::Synthetic { stage, binding } => match binding { - SyntheticBinding::ArgumentTable => { - let t = templates - .iter_mut() - .find(|t| t.stage == stage) - .ok_or_else(|| internal(format!("an ArgumentTable of {stage:?}")))?; - if t.table_size == 0 { - return Err(internal("an ArgumentTable binding without fields")); - } - t.table = Some((set.set, b.binding)); - WriteSource::ArgumentTable { - stage, - bytes_len: t.table_size, - } - } - // Each stage binds its own blob. - SyntheticBinding::ConstantBlob - if p.stages - .iter() - .any(|m| m.stage == vk_of(stage) && m.constant_blob.is_some()) => - { - WriteSource::ConstantBlob { stage } - } - // The control stage's factor buffer, or the zero buffer when the encoder - // set none: every patch reads zero factors and is culled. - SyntheticBinding::TessellationFactors if p.graphics.tessellation.is_some() => { - if shape.tessellation_factor_buffer { - factor_binding = Some((set.set, b.binding)); - WriteSource::TessellationFactors - } else { - WriteSource::Neutral(NeutralResource::ZeroBuffer { - min_bytes: zero_buffer_bytes(profile), - }) - } - } - // The draw's patch index buffer, or the zero buffer for a draw without one. - SyntheticBinding::PatchIndices if tessellation => { - patch_index_binding = Some((set.set, b.binding)); - WriteSource::PatchIndices { - min_bytes: zero_buffer_bytes(profile), - } - } - // The draw's control-point index buffer, of a pipeline with a control-point - // index type. - SyntheticBinding::ControlPointIndices if tessellation => { - control_point_index_binding = Some((set.set, b.binding)); - WriteSource::ControlPointIndices - } - SyntheticBinding::HandleTable => { - planner(&mut heap)?.table(stage, set.set, b.binding)? - } - SyntheticBinding::SamplerTable => { - planner(&mut heap)?.sampler_table(stage, set.set, b.binding)? - } - SyntheticBinding::FunctionTableDirectory => { - planner(&mut heap)?.directory(stage, set.set, b.binding)? - } - // The tables' words on a device without the array's features. - SyntheticBinding::FunctionTableSnapshot => { - planner(&mut heap)?.snapshot(stage, set.set, b.binding)? - } - // The pass's tile threadgroup memory. - SyntheticBinding::TileMemory if stage == Stage::Fragment => { - match &tile_memory { - Some(memory) => WriteSource::TileMemory { - bytes: memory.bytes(), - }, - None => { - return Err(internal("a tile memory binding without its facts")) - } - } - } - // 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:?}"))), - }, - BindingSource::Heap(_) - | BindingSource::HeapSampler { .. } - | BindingSource::SamplerArray { .. } => { - return Err(internal("a heap binding outside the heap planner")) - } - // The identity domains' arrays are the consumer's, written as it makes textures. - BindingSource::IdentityArray => { - return Err(internal("an identity array in the binder's plan")) - } - BindingSource::SeparateSampler { .. } => { - return Err(internal("a separate sampler outside its planner")) - } - // The consumer builds the structures. - BindingSource::AccelerationStructure { slot, level } => { - WriteSource::AccelerationStructure { slot, level } - } - // 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 two-plane YCbCr texture's planes image, through the device's conversion. - BindingSource::YCbCrPlanes(slot) => resources.planes_image_write(slot)?, - }; - descriptors.push(DescriptorWrite { - set: set.set, - binding: b.binding, - array_element: 0, - ty: b.ty, - source, - }); - } - } - - // Vertex buffers (fixed function), and the pulled-vertex-buffer variant: a layout the shape - // binds where fixed-function input cannot fetch it is pulled in the variant, and a pipeline - // compiled under such a variant keeps pulling its layouts. - let vertex_strides = StrideRules { - max: limits.max_vertex_input_binding_stride, - portability_alignment: limits.min_vertex_input_binding_stride_alignment, - dynamic: p - .graphics - .dynamic_states - .contains(&vk::DynamicState::VERTEX_INPUT_BINDING_STRIDE), - within_stride: profile - .fields() - .enabled - .portability_withholds(VkFeature::VertexAttributeAccessBeyondStride), - }; - let vs = stage_shape(Stage::Vertex); - let mut vertex_buffers = Vec::new(); - let mut planned_vertex = Vec::new(); - let mut pulled_vertex_buffers = p.vertex_input.variant_pulled.clone(); - for vb in &p.vertex_input.bindings { - let slot = vertex_buffer(vb.buffer_index); - let (alignment, reads) = attribute_reads(&p.vertex_input.attributes, vb.binding)?; - if let VertexStride::Static(s) = vb.stride { - // Link pulls what a static stride under dynamic state does not cover (06209). - if vertex_strides.dynamic && s != 0 && s < reads.1 { - return Err(internal(format!( - "static stride {s} of vertex binding {} under dynamic strides", - vb.binding - ))); - } - } - let planned = PlannedVertexBuffer { - binding: vb.binding, - slot, - stride: vb.stride, - input_rate: vb.input_rate, - divisor: vb.divisor, - alignment, - reads, - }; - // A layout the shape names among those the device cannot fetch for the draw - // (`BindShape::far_vertex_buffers`) is pulled whatever the encoder binds there: a draw - // replay's commands bind their own, which the encoder usually has none of. - let far = shape.far_vertex_buffers.contains(&vb.buffer_index); - let fetchable = match (vs.and_then(|s| s.buffers.get(&vb.buffer_index)), vb.stride) { - _ if far => false, - (None, _) => return Err(BindError::UnboundVertexBuffer { slot }), - // The consumer places inline bytes at an offset of its own (aligned); a per-bind - // layout reads them at their bind's stride, 0 without one, as a buffer's. - (Some(&BufferShape::Bytes { attribute_stride }), stride) => { - let per_bind = match stride { - VertexStride::PerBind => Some(attribute_stride.unwrap_or(0)), - VertexStride::Static(_) => None, - }; - fetchable( - &planned, - &vertex_strides, - metal::vertex::MAX_VERTEX_ALIGNMENT, - per_bind, - ) - } - ( - Some(&BufferShape::Buffer { - attribute_stride, - offset_alignment, - .. - }), - stride, - ) => { - // A buffer bound without a stride reads a per-bind layout at stride 0. - let per_bind = match stride { - VertexStride::PerBind => Some(attribute_stride.unwrap_or(0)), - VertexStride::Static(_) => None, - }; - fetchable(&planned, &vertex_strides, offset_alignment, per_bind) - } - }; - // A layout the device cannot fetch for the draw is pulled as an unfetchable bind's is. - if !fetchable { - pulled_vertex_buffers.insert(vb.buffer_index); - } - vertex_buffers.push(VertexBufferBind { - binding: vb.binding, - buffer_index: vb.buffer_index, - per_bind_stride: vb.stride == VertexStride::PerBind, - }); - planned_vertex.push(planned); - } - - // Specialization the shape decides, over both stages. - let mut layout: Vec = p - .stages - .iter() - .flat_map(|m| m.specialization.constants.iter().copied()) - .collect(); - layout.sort_by_key(|c| c.id); - layout.dedup_by_key(|c| c.id); - let samples = u64::from(p.graphics.rasterization_samples.as_raw().max(1)); - check_sparse_textures(&p.dependencies, profile, shape)?; - // An object function's threadgroup memory arguments, whose lengths the encoder sets - // (`setObjectThreadgroupMemoryLength:atIndex:`): its arena's facts, and the total of its - // specialized lengths. - let object_arena = p.dependencies.iter().find_map(|d| match d.fact { - RuntimeFact::ObjectThreadgroupArena { - static_bytes, - payload, - } => Some((static_bytes, payload)), - _ => None, - }); - if mesh && other_stage_lengths(p) { - // A mesh function's arguments, whose lengths no Metal setter sets. - return Err(not_implemented(Feature::MeshShading)); - } - let mut object_regions: Option = None; - let mut fixed = Vec::new(); - for c in &layout { - if let Some(v) = bound_value(c.key, shape, &resources)? { - fixed.push((c.key, v)); - continue; - } - let v = match c.key { - SpecKey::SampleCount => samples, - SpecKey::AmplificationCount => u64::from(shape.vertex_amplification.count), - // A mesh draw's threadgroup sizes and grid forms, which each draw decides - // (`DrawCommands::specialization`). - SpecKey::LocalSize(_) - | SpecKey::FlatLocalSize - | SpecKey::MultiRegion - | SpecKey::ObjectLocalSize(_) - | SpecKey::ObjectFlatLocalSize - | SpecKey::ObjectMultiRegion - if mesh => - { - continue - } - // An object function's threadgroup memory arguments: the encoder's lengths, each - // rounded up to 16 as a kernel's are (an unset one is 0). - SpecKey::TgLength(n) if mesh && object_arena.is_some() => { - let len = stage_shape(Stage::Object) - .and_then(|s| s.threadgroup_lengths.get(&n)) - .map_or(0, |&len| u64::from(len)) - .next_multiple_of(crate::memory::arena::REGION_ALIGN); - object_regions = Some(object_regions.unwrap_or(0).saturating_add(len)); - len - } - SpecKey::TgLength(_) if mesh => return Err(not_implemented(Feature::MeshShading)), - // A fragment function's tile threadgroup memory and the pass's tile. - SpecKey::TgOffset(_) - | SpecKey::TileThreadgroupLength - | SpecKey::TileGridWidth - | SpecKey::ImageblockWidth - | SpecKey::ImageblockHeight => tile_memory - .as_ref() - .and_then(|m| m.spec(c.key)) - .ok_or_else(|| internal(format!("{:?} without its facts", c.key)))?, - // What a stage's handles can name: its raw arms drop where it names no texture held - // by its raw texels. - SpecKey::HeapRawTextures(stage) => u64::from(heap_raw(shape, stage, &heap_reach)), - other => { - return Err(internal(format!( - "a render specialization constant {other:?}" - ))) - } - }; - fixed.push((c.key, v)); - } - // The object function's arena with those lengths, within its stage's workgroup memory limit. - if let (Some((static_bytes, payload)), Some(regions)) = (object_arena, object_regions) { - crate::lower::mesh::stage_workgroup_limit(Stage::Object, profile, payload.map(u64::from)) - .check(u64::from(static_bytes).saturating_add(regions)) - .map_err(|e| match e { - crate::error::Error::Unsupported(u) => BindError::Unsupported(u), - other => internal(format!("an object function's threadgroup memory: {other}")), - })?; - } - record_noted(&p.stages, shape, &mut resources, &heap_reach)?; - let specialization = spec_key(&layout, |k| { - fixed.iter().find(|(key, _)| *key == k).map(|(_, v)| *v) - }); - let m = &limits.mesh; - let mesh = mesh.then(|| MeshTemplate { - multiples: p - .dependencies - .iter() - .filter_map(|d| match d.fact { - RuntimeFact::LocalSizeConstraint { multiple } => Some(multiple), - _ => None, - }) - .collect(), - spec: layout, - fixed, - mesh: GroupLimits { - size: m.max_mesh_work_group_size, - invocations: m.max_mesh_work_group_invocations, - count: m.max_mesh_work_group_count, - total: m.max_mesh_work_group_total_count, - stage: GroupStage::Mesh, - }, - object: stages.contains(&Stage::Object).then_some(GroupLimits { - size: m.max_task_work_group_size, - invocations: m.max_task_work_group_invocations, - count: m.max_task_work_group_count, - total: m.max_task_work_group_total_count, - stage: GroupStage::Task, - }), - folded: p - .dependencies - .iter() - .any(|d| d.fact == RuntimeFact::FoldedGroups), - partial_groups: p - .dependencies - .iter() - .any(|d| d.fact == RuntimeFact::PartialObjectThreadgroups), - }); - - // Uses: bound buffer slots, vertex buffers, textures, attachments, used resources. - let mut uses: Vec = buffers - .iter() - .filter(|b| matches!(b.bound, BoundKind::Buffer { .. })) - .map(|b| buffer_use(b, stage_flags(b.slot.stage))) - .collect(); - // The factors, the control stage's. - if factor_binding.is_some() { - uses.push(ResourceUse { - resource: UseTarget::TessellationFactors, - access: AccessSet::READ, - class: AccessClass::Storage, - stages: vk::PipelineStageFlags2::TESSELLATION_CONTROL_SHADER, - range: None, - }); - } - for vb in &planned_vertex { - uses.push(ResourceUse { - resource: UseTarget::Slot(vb.slot), - access: AccessSet::READ, - class: AccessClass::VertexInput, - stages: vk::PipelineStageFlags2::VERTEX_ATTRIBUTE_INPUT, - range: None, - }); - } - uses.append(&mut resources.uses); - let reach = |s: metal::RenderStages| { - let mut f = vk::PipelineStageFlags2::empty(); - for (flag, stage) in [ - (metal::RenderStages::VERTEX, Stage::Vertex), - (metal::RenderStages::FRAGMENT, Stage::Fragment), - (metal::RenderStages::OBJECT, Stage::Object), - (metal::RenderStages::MESH, Stage::Mesh), - ] { - if s.contains(flag) && stages.contains(&stage) { - f |= stage_flags(stage); - } - } - f - }; - // The stages whose function may write memory: a vertex or fragment function the compile - // found storing nothing writes no used resource (`GraphicsState::vertex_writes_memory`, - // `fragment_writes_memory`); an object or mesh function has no such fact. - let writers = stages - .iter() - .filter(|stage| match stage { - Stage::Vertex => p.graphics.vertex_writes_memory, - Stage::Fragment => p.graphics.fragment_writes_memory, - _ => true, - }) - .fold(vk::PipelineStageFlags2::empty(), |all, &stage| { - all | stage_flags(stage) - }); - uses.extend(used_uses( - &shape.used, - p.interface.needs_pointer_translation, - p.interface.needs_handle_translation, - reach, - writers, - )); - - let mut diagnostics = resources.diagnostics; - let mut template = resources.template; - template.biased_slot_words = crate::lower::access::identity(profile); - if let Some(h) = heap { - h.finish( - &mut descriptors, - &mut uses, - stage_flags, - &mut template, - &mut diagnostics, - ); - } - let mut variant = resources.variant; - variant.psb_slots = psb_variant(&p.dependencies, &buffers, profile); - variant.cross_class = cross_variant(&p.dependencies, &p.interface.slots, shape); - variant.srgb_textures = srgb_variant(profile, &p.dependencies, shape, &variant.cross_class); - variant.ycbcr_in_place = ycbcr_in_place_variant(&p.dependencies, shape); - variant.ycbcr_planes_sampled = - ycbcr_planes_sampled_variant(&p.dependencies, shape, &variant.ycbcr_in_place); - variant.texel_buffer_parts = texel_buffer_parts_variant(&p.dependencies, shape); - variant.address_maps = address_map_variant(&p.dependencies, shape); - variant.cubic_samplers = cubic_variant(&p.dependencies, shape)?; - variant.anisotropic_samplers = anisotropic_variant(&p.dependencies, shape); - // A layout the variant newly pulls is read through a `Whole` storage slot, which declares - // `BufferRangeLimit`: the variant's pipeline would ask for its device address when the bound - // buffer is large, so the key names it now and stays a fixed point. - for &layout in &pulled_vertex_buffers { - let slot = vertex_buffer(layout); - let bound = BoundKind::of(vs.and_then(|s| s.buffers.get(&layout))); - if !p.vertex_input.variant_pulled.contains(&layout) && range_variant(slot, bound, profile) { - variant.psb_slots.insert(slot); - } - } - variant.pulled_vertex_buffers = pulled_vertex_buffers; - variant.amplification_draws = amplification_draws; - // A pipeline compiled for a draw replay's bindings states its variant. - variant.replay_bindings = replayed; - variant.merged_draws = p - .dependencies - .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; - variant.zeroed_colors = zeroed_colors; - variant.dropped_colors = dropped_colors; - variant.depth_clamp_range = depth_clamp_range; - variant.rotated_weights = rotated_weights; - variant.line_band = line_band; - variant.primitive_id_indices = primitive_id_indices; - variant.quad_primitive_ids = quad_primitive_ids; - variant.private_list = private_list; - variant.region_viewports = region_viewports; - // Tables that may pass `maxStorageBufferRange`: the variant that reads them at their - // addresses (and a pipeline compiled so states it). - variant.addressed_function_tables = crate::bind::heap::addressed_function_tables( - profile, - &p.dependencies, - &shape.function_tables, - ); - Ok(BindingPlan { - variant, - specialization, - descriptors, - vertex_buffers, - uses, - push, - diagnostics, - compute: None, - graphics: Some(GraphicsTemplate { - buffers, - stages: templates, - vertex_buffers: planned_vertex, - pulled_strides, - resources: template, - vertex_strides, - multiview_instance_limit: (views.view_mask != 0) - .then_some(limits.max_multiview_instance_index), - other_layer_variant: compiled_draws != amplification_draws - || other_colors - || compiled_range != depth_clamp_range - || compiled_rotated != rotated_weights - || compiled_band != line_band - || compiled_quads != quad_primitive_ids - || compiled_list != private_list - || compiled_regions != region_viewports, - amplifications, - indirect_first_instance_missing: !profile - .fields() - .enabled - .features - .contains(&VkFeature::DrawIndirectFirstInstance), - tessellation: factor_template( - p, - ( - factor_binding, - patch_index_binding, - control_point_index_binding, - ), - ( - limits.min_storage_buffer_offset_alignment, - u64::from(limits.max_storage_buffer_range), - ), - )?, - mesh, - deindexed: primitive_id_indices, - private_list, - line_band: p.graphics.line_band.map(|b| b.push_offset), - }), - views, - }) } /// The 8-bit unorm code Metal's private alpha test compares the reference `reference` as @@ -1714,1931 +96,3 @@ pub fn alpha_test_code(reference: f32) -> u32 { }; (clamped * 255.0).round_ties_even() as u32 } - -/// The address alignment and the element bytes the fixed-function attributes of `binding` read -/// ([`PlannedVertexBuffer::alignment`] and `reads`): each attribute's format block gives its -/// Vulkan alignment (the component size, or the whole word of a packed format) and size. -fn attribute_reads( - attributes: &[VertexAttribute], - binding: u32, -) -> Result<(u32, (u32, u32)), BindError> { - let mut alignment = 1; - let mut reads: Option<(u32, u32)> = None; - for a in attributes.iter().filter(|a| a.binding == binding) { - let block = a - .format - .block() - .ok_or_else(|| internal(format!("a vertex attribute of {:?}", a.format)))?; - let align = block - .vertex_alignment() - .ok_or_else(|| internal(format!("a vertex attribute of {:?}", a.format)))?; - alignment = alignment.max(align); - let end = a - .offset - .checked_add(block.size) - .ok_or_else(|| internal("a vertex attribute past 2^32 bytes"))?; - reads = Some(match reads { - Some((lo, hi)) => (lo.min(a.offset), hi.max(end)), - None => (a.offset, end), - }); - } - let reads = - reads.ok_or_else(|| internal(format!("vertex binding {binding} without attributes")))?; - Ok((alignment, reads)) -} - -impl BindingPlan { - /// The commands of one draw of `state`. `state` must have the shape the plan was made for; the - /// result depends on its offsets, lengths, strides, and addresses and on the draw, never on the - /// contents of an indirect buffer. - pub fn instantiate_draw( - &self, - state: &BindState, - draw: &DrawCall, - ) -> Result { - let mut commands = DrawCommands::default(); - self.instantiate_draw_into(state, draw, &mut commands)?; - Ok(commands) - } - - /// [`instantiate_draw`](Self::instantiate_draw)'s commands, written over `commands`: every - /// field is set as `instantiate_draw` sets it, and the vectors (each push write's bytes and - /// each table's among them) keep the storage the commands written there before left, so a - /// consumer that keeps one `DrawCommands` from draw to draw allocates none of it again once - /// it holds as much. On an error `commands` holds no draw's commands. - pub fn instantiate_draw_into( - &self, - state: &BindState, - draw: &DrawCall, - commands: &mut DrawCommands, - ) -> Result<(), BindError> { - instantiate(self.drawn(draw)?, state, draw, commands) - } - - /// The render template `draw` instantiates: this plan's, where the draw runs on its variant. - fn drawn(&self, draw: &DrawCall) -> Result<&GraphicsTemplate, BindError> { - let t = self - .graphics - .as_ref() - .ok_or_else(|| internal("instantiate_draw of a plan that is not a render plan"))?; - if t.other_layer_variant { - return Err(BindError::NeedsVariant { - variant: Box::new(self.variant.clone()), - }); - } - // An indexed draw of a pipeline that writes the primitive ID runs on its de-indexed - // variant of the draw's index type, and every other draw on the variant without it. - if t.deindexed.is_some() { - let asked = draw_index_type(draw); - if asked != t.deindexed { - return Err(BindError::NeedsVariant { - variant: Box::new(VariantKey { - primitive_id_indices: asked, - ..self.variant.clone() - }), - }); - } - } - Ok(t) - } -} - -/// The Vulkan draw of a Metal draw, and the base vertex and first instance the -/// `BaseVertexInstance` field reports (Vulkan's `BaseVertex` and `BaseInstance`). A direct -/// indexed draw whose indices run past its index buffer ([`index_overrun`]) draws as `overrun` -/// states: a `Clamped` one draws only its indices inside the buffer. A draw of no index binds the -/// buffer at offset 0 where its own offset may lie past the `VkBuffer`, which cannot be bound -/// there (`VUID-vkCmdBindIndexBuffer-offset-08782`): when it is a `Clamped` draw of none, or its -/// offset is at or past the buffer's length (a draw of no index has no overrun to record). -fn vk_draw(draw: &DrawCall, overrun: Option) -> (vk::DrawCommand, [u32; 2]) { - match *draw { - DrawCall::Primitives { - vertex_start, - vertex_count, - instance_count, - base_instance, - } => ( - vk::DrawCommand::Draw { - vertex_count, - instance_count, - first_vertex: vertex_start, - first_instance: base_instance, - }, - [vertex_start, base_instance], - ), - DrawCall::Indexed { - index_type, - index_buffer, - index_count, - index_offset, - instance_count, - base_vertex, - base_instance, - } => { - let clamped = matches!(overrun, Some(IndexOverrun::Clamped { .. })); - let index_count = match overrun { - Some(IndexOverrun::Clamped { past_end }) => index_count.saturating_sub(past_end), - None => index_count, - }; - let unbindable = clamped || index_offset >= index_buffer.length; - let index_buffer_offset = if index_count == 0 && unbindable { - 0 - } else { - index_offset - }; - ( - vk::DrawCommand::DrawIndexed { - index_type, - index_buffer_offset, - index_count, - instance_count, - first_index: 0, - vertex_offset: base_vertex, - first_instance: base_instance, - }, - [base_vertex as u32, base_instance], - ) - } - DrawCall::Indirect { - indirect, - indexed: None, - } - | DrawCall::PatchesIndirect { indirect, .. } => ( - vk::DrawCommand::DrawIndirect { - offset: indirect.offset, - draw_count: 1, - stride: 16, - }, - [0, 0], - ), - // One vertex per patch: the synthesized vertex stage's `VertexIndex` is Metal's patch - // index. - DrawCall::Patches { - patch_start, - patch_count, - instance_count, - base_instance, - .. - } => ( - vk::DrawCommand::Draw { - vertex_count: patch_count, - instance_count, - first_vertex: patch_start, - first_instance: base_instance, - }, - [patch_start, base_instance], - ), - DrawCall::Indirect { - indirect, - indexed: Some((index_type, _, index_offset)), - } => ( - vk::DrawCommand::DrawIndexedIndirect { - index_type, - index_buffer_offset: index_offset, - offset: indirect.offset, - draw_count: 1, - stride: 20, - }, - [0, 0], - ), - DrawCall::MeshThreadgroups { - groups, - threads_per_mesh_group, - .. - } => (mesh_tasks(groups, threads_per_mesh_group), [0, 0]), - // Metal launches the whole mesh threadgroups the threads fill. - DrawCall::MeshThreads { - threads, - threads_per_mesh_group: l, - .. - } => ( - mesh_tasks( - std::array::from_fn(|i| threads[i].checked_div(l[i]).unwrap_or(0)), - l, - ), - [0, 0], - ), - // Plain Metal draws nothing from arguments at an offset that is not a multiple of 4, where - // Vulkan's offset must be one too. - DrawCall::MeshThreadgroupsIndirect { - indirect, - threads_per_mesh_group, - .. - } if indirect.offset.is_multiple_of(4) && !mesh_draws_nothing(threads_per_mesh_group) => ( - vk::DrawCommand::DrawMeshTasksIndirect { - offset: indirect.offset, - draw_count: 1, - stride: 12, - }, - [0, 0], - ), - DrawCall::MeshThreadgroupsIndirect { .. } => (mesh_tasks([0; 3], [0; 3]), [0, 0]), - } -} - -/// Metal's most threads of a mesh threadgroup (`maxTotalThreadsPerMeshThreadgroup`). -const METAL_MESH_THREADS: u64 = 1024; - -/// Whether Metal draws nothing for a mesh threadgroup of `l` threads: one of no thread, or of -/// more than [`METAL_MESH_THREADS`], past which plain Metal draws nothing (its debug layer stops -/// the draw). -fn mesh_draws_nothing(l: [u32; 3]) -> bool { - let n: u64 = l.iter().map(|&x| u64::from(x)).product(); - n == 0 || n > METAL_MESH_THREADS -} - -/// `vkCmdDrawMeshTasksEXT` of `groups` mesh threadgroups of `l` threads: none where Metal draws -/// nothing. -fn mesh_tasks(groups: [u32; 3], l: [u32; 3]) -> vk::DrawCommand { - let [x, y, z] = if mesh_draws_nothing(l) { - [0; 3] - } else { - groups - }; - vk::DrawCommand::DrawMeshTasks { - group_count_x: x, - group_count_y: y, - group_count_z: z, - } -} - -/// A mesh draw's threads per object threadgroup and per mesh threadgroup; `None` for every other -/// draw. -fn mesh_threads(draw: &DrawCall) -> Option<[[u32; 3]; 2]> { - match *draw { - DrawCall::MeshThreadgroups { - threads_per_object_group, - threads_per_mesh_group, - .. - } - | DrawCall::MeshThreadgroupsIndirect { - threads_per_object_group, - threads_per_mesh_group, - .. - } - | DrawCall::MeshThreads { - threads_per_object_group, - threads_per_mesh_group, - .. - } => Some([threads_per_object_group, threads_per_mesh_group]), - DrawCall::Primitives { .. } - | DrawCall::Indexed { .. } - | DrawCall::Indirect { .. } - | DrawCall::Patches { .. } - | DrawCall::PatchesIndirect { .. } => None, - } -} - -/// What a mesh draw adds to its commands: the Vulkan draw, its complete specialization, and each -/// stage's `DispatchRegion` bytes. -struct MeshDraw { - command: vk::DrawCommand, - specialization: SpecializationKey, - /// The object stage's region, of a pipeline with an object function. - object_region: Option<[u8; 32]>, - mesh_region: [u8; 32], - /// A direct draw's fold of its object grid, of a folded object function - /// (`DrawCommands::object_fold`). - fold: Option, - /// A direct draw whose object grid Metal's GPU discards - /// (`DrawCommands::discards_command_buffer`). - discards: bool, -} - -impl MeshDraw { - /// The `DispatchRegion` bytes of `stage`. - fn region(&self, stage: Stage) -> Option<[u8; 32]> { - match stage { - Stage::Object => self.object_region, - Stage::Mesh => Some(self.mesh_region), - _ => None, - } - } -} - -/// A refusal of a mesh draw past the device's `limit`. -fn mesh_limit(limit: VkLimit, required: u64, available: u32) -> BindError { - BindError::Unsupported(Unsupported::needs( - Feature::MeshShading, - Capability::Limit { - limit, - required, - available: u64::from(available), - }, - )) -} - -/// The limits that name a stage's threadgroup and grid: the task stage's for an object -/// function and the mesh stage's for a mesh function. -struct GroupLimitNames { - size: fn(u8) -> VkLimit, - invocations: VkLimit, - count: fn(u8) -> VkLimit, - total: VkLimit, -} - -impl GroupLimitNames { - fn of(stage: GroupStage) -> GroupLimitNames { - match stage { - GroupStage::Task => GroupLimitNames { - size: VkLimit::MaxTaskWorkGroupSize, - invocations: VkLimit::MaxTaskWorkGroupInvocations, - count: VkLimit::MaxTaskWorkGroupCount, - total: VkLimit::MaxTaskWorkGroupTotalCount, - }, - GroupStage::Mesh => GroupLimitNames { - size: VkLimit::MaxMeshWorkGroupSize, - invocations: VkLimit::MaxMeshWorkGroupInvocations, - count: VkLimit::MaxMeshWorkGroupCount, - total: VkLimit::MaxMeshWorkGroupTotalCount, - }, - } - } -} - -/// The check of a threadgroup of `l` threads of a stage of `limits` (named for the object stage -/// where `object`): each axis and the product (as one axis where the stage's local size is -/// `flat`), and whole subgroups of each of `multiples` (a stage has no emulated-simdgroups -/// variant: `NotImplemented`). -fn check_group( - limits: &GroupLimits, - l: [u32; 3], - flat: bool, - multiples: &[u32], -) -> Result<(), BindError> { - let names = GroupLimitNames::of(limits.stage); - let n: u64 = l.iter().map(|&x| u64::from(x)).product(); - if flat { - if n > u64::from(limits.size[0]) { - return Err(mesh_limit((names.size)(0), n, limits.size[0])); - } - } else if let Some(i) = (0..3).find(|&i| l[i] > limits.size[i]) { - return Err(mesh_limit( - (names.size)(i as u8), - u64::from(l[i]), - limits.size[i], - )); - } - if n > u64::from(limits.invocations) { - return Err(mesh_limit(names.invocations, n, limits.invocations)); - } - if multiples - .iter() - .any(|&m| m > 0 && !n.is_multiple_of(u64::from(m))) - { - return Err(not_implemented(Feature::MeshShading)); - } - Ok(()) -} - -/// The check of a direct draw's grid of `g` threadgroups of a stage of `limits`: each axis and -/// the product. -fn check_grid(limits: &GroupLimits, g: [u32; 3]) -> Result<(), BindError> { - let names = GroupLimitNames::of(limits.stage); - if let Some(i) = (0..3).find(|&i| g[i] > limits.count[i]) { - return Err(mesh_limit( - (names.count)(i as u8), - u64::from(g[i]), - limits.count[i], - )); - } - let total: u64 = g.iter().map(|&x| u64::from(x)).product(); - if total > u64::from(limits.total) { - return Err(mesh_limit(names.total, total, limits.total)); - } - Ok(()) -} - -/// The value a mesh draw specializes `key` of a stage of `keys` with, for its threadgroup of `l` -/// threads: an axis of `l`, its product, and `MultiRegion` 0. `None` for any other key. -fn size_value(keys: &DispatchKeys, key: SpecKey, l: [u32; 3]) -> Option { - if let Some(i) = keys.axis(key) { - return Some(u64::from(l[i])); - } - if key == keys.flat { - return Some(l.iter().map(|&x| u64::from(x)).product()); - } - (key == keys.multi_region).then_some(0) -} - -/// The mesh draw of `draw` under `t`, whose plain Vulkan draw is `command` (`vk_draw`'s, which a -/// pipeline without an object function draws). -/// -/// Without an object function a draw launches mesh threadgroups: `drawMeshThreads` launches the -/// whole threadgroups its threads fill, whose threads are the grid Metal's builtins report -/// (measured, a probe: 10 by 3 threads in threadgroups of 4 by 2 report a grid of 8 by 2), as -/// `NumWorkgroups` gives it. With one it launches object threadgroups, each launching the mesh grid -/// it sets: `drawMeshThreads` launches the threadgroups its threads fill, rounded up, and one that -/// leaves a partial object threadgroup runs that threadgroup with the threads left, as Metal does -/// (probe 4): one draw of whole threadgroups, `MultiRegion` 1, Metal's threads per grid and its -/// region flagged `lower::dispatch::NONUNIFORM`, whose object function answers the smaller -/// threadgroup and runs its invocations past it none of its body -/// (`RuntimeFact::PartialObjectThreadgroups`). A -/// draw whose object threadgroup Metal draws nothing for (no thread, or past 1024) launches -/// nothing. A direct draw's object grid is Metal's ([`metal_object_grid`], measured): each -/// axis's threads per grid wrap at 2^32, the draw runs the threadgroups the wrapped threads fill, -/// and the builtins report the wrapped threads, from the object stage's region (`MultiRegion` 1) -/// where they leave a partial threadgroup. -/// -/// A draw that launches threadgroups has each stage's threadgroup checked against the device's -/// limits for it ([`check_group`]: the mesh stage's `maxMeshWorkGroup*`, the task stage's -/// `maxTaskWorkGroup*`), and a direct one its grid of the first stage's threadgroups -/// ([`check_grid`]). A grid the object function sets is bounded in the shader -/// (`lower::mesh`). Each stage takes its grid from `NumWorkgroups` (`MultiRegion` 0), as does an -/// indirect draw, whose counts its arguments pass writes within the device's limits -/// (`DrawCommands::mesh_arguments`). A draw that launches nothing is made with the smallest -/// threadgroups its stages can be made with. -/// -/// A folded object function (`MeshTemplate::folded`) reads its grid from its region record -/// instead, and its draws run their object grids in pieces within the task stage's limits -/// (`bind::mesh_arguments`): a direct one's fold ([`fold_object_grid`], `DrawCommands::object_fold`) -/// is `vkCmdDrawMeshTasksEXT` of its one piece, or `vkCmdDrawMeshTasksIndirectEXT` of its pieces' -/// commands in the uploaded fold, and an indirect one is `vkCmdDrawMeshTasksIndirectCountEXT` of -/// its arguments pass's pieces. Its grid is held to no device limit. -fn mesh_draw( - t: &MeshTemplate, - draw: &DrawCall, - command: vk::DrawCommand, -) -> Result { - let Some([lo, lm]) = mesh_threads(draw) else { - return Err(internal(format!("a mesh draw of {draw:?}"))); - }; - let command = match (&t.object, *draw) { - // A mesh grid Metal draws nothing for (`bind::mesh_arguments`). - (None, _) - if matches!(command, vk::DrawCommand::DrawMeshTasks { - group_count_x: x, - group_count_y: y, - group_count_z: z, - } if metal_mesh_grid_draws_nothing([x, y, z])) => - { - mesh_tasks([0; 3], [0; 3]) - } - (None, _) => command, - (Some(_), _) if mesh_draws_nothing(lo) => mesh_tasks([0; 3], [0; 3]), - // The object threadgroups the threads fill, rounded up (`lower::dispatch`'s partial - // object threadgroups). - (Some(_), DrawCall::MeshThreads { threads, .. }) => { - mesh_tasks(std::array::from_fn(|i| threads[i].div_ceil(lo[i])), lm) - } - (Some(_), _) => command, - }; - // A `drawMeshThreads` of an object function: Metal's threads per grid, which leave a partial - // threadgroup where an axis is not whole threadgroups. An object function whose body holds a - // workgroup barrier does not run one (`RuntimeFact::PartialObjectThreadgroups`). - let asked = match (&t.object, *draw) { - (Some(_), DrawCall::MeshThreads { threads, .. }) if !mesh_draws_nothing(lo) => { - Some(threads) - } - _ => None, - }; - let nonuniform = asked.is_some_and(|threads| (0..3).any(|i| !threads[i].is_multiple_of(lo[i]))); - let folded = t.folded && t.object.is_some(); - // An unfolded object stage's direct grid as Metal runs it (`metal_object_grid`): each axis's - // threads per grid wrap at 2^32, the draw runs the threadgroups the wrapped threads fill, and - // the builtins report the wrapped threads; past what Metal runs, Metal's GPU discards it. - let (command, wrapped, discards) = match command { - vk::DrawCommand::DrawMeshTasks { - group_count_x: x, - group_count_y: y, - group_count_z: z, - } if t.object.is_some() && !folded => { - let (runs, threads) = match asked { - Some(threads) => ([x, y, z], threads), - None => metal_object_grid([x, y, z], lo, true).unwrap_or_default(), - }; - let n: u64 = runs.iter().map(|&c| u64::from(c)).product(); - let discards = n > u64::from(METAL_OBJECT_GRID_TOTAL); - let runs = if discards || runs.contains(&0) { - [0; 3] - } else { - runs - }; - (mesh_tasks(runs, lo), Some((threads, runs)), discards) - } - other => (other, None, false), - }; - let groups = match command { - vk::DrawCommand::DrawMeshTasks { - group_count_x, - group_count_y, - group_count_z, - } => Some([group_count_x, group_count_y, group_count_z]), - vk::DrawCommand::DrawMeshTasksIndirect { .. } => None, - other => return Err(internal(format!("a mesh draw of {other:?}"))), - }; - let launches = groups.is_none_or(|g| !g.contains(&0)); - if nonuniform && launches && !t.partial_groups { - return Err(not_implemented(Feature::MeshShading)); - } - // Where the wrapped threads leave a partial threadgroup, `NumWorkgroups · L` passes them: the - // object stage reads its grid from its region (`MultiRegion` 1). - let partial = launches - && wrapped.is_some_and(|(threads, runs)| { - (0..3).any(|i| u64::from(runs[i]) * u64::from(lo[i]) != u64::from(threads[i])) - }); - // The multiples are subgroup sizes, powers of two, so their largest is a multiple of each. - let smallest = t.multiples.iter().copied().max().unwrap_or(1).max(1); - let size = |l: [u32; 3]| if launches { l } else { [smallest, 1, 1] }; - let (lo, lm) = (size(lo), size(lm)); - let mesh_keys = SpecKey::dispatch_keys(Stage::Mesh); - let object_keys = SpecKey::dispatch_keys(Stage::Object); - let flat = |keys: &DispatchKeys| t.spec.iter().any(|c| c.key == keys.flat); - if launches { - check_group(&t.mesh, lm, flat(&mesh_keys), &t.multiples)?; - if let Some(o) = &t.object { - check_group(o, lo, flat(&object_keys), &t.multiples)?; - } - match (groups, t.object.as_ref()) { - (Some(_), Some(_)) if folded => {} - (Some(g), Some(o)) => check_grid(o, g)?, - (Some(g), None) => check_grid(&t.mesh, g)?, - (None, _) => {} - } - } - let object = t.object.is_some(); - // A folded object function reads every grid builtin from its region record, and an unfolded - // one whose wrapped grid leaves a partial threadgroup from its region (`MultiRegion` 1). - let specialization = spec_key(&t.spec, |k| { - size_value(&mesh_keys, k, lm) - .or_else(|| ((folded || partial) && k == object_keys.multi_region).then_some(1)) - .or_else(|| object.then(|| size_value(&object_keys, k, lo)).flatten()) - .or_else(|| t.fixed.iter().find(|(key, _)| *key == k).map(|f| f.1)) - }); - // A folded object function's draw runs its pieces (`bind::mesh_arguments`). - let (command, fold) = match (folded, groups, &t.object) { - (true, Some(g), Some(o)) => { - let task = MeshGridLimits { - axes: o.count, - total: o.total, - }; - let g = if launches { g } else { [0; 3] }; - let fold = match asked.filter(|_| launches) { - Some(threads) => { - crate::bind::mesh_arguments::fold_object_threads(threads, lo, task) - } - None => fold_object_grid(g, lo, task, true), - } - .ok_or_else(|| internal(format!("a fold of threadgroups of {lo:?} threads")))?; - let command = match fold.pieces { - 0 | 1 => vk::DrawCommand::DrawMeshTasks { - group_count_x: fold.dispatch[0], - group_count_y: fold.dispatch[1], - group_count_z: fold.dispatch[2], - }, - pieces => vk::DrawCommand::DrawMeshTasksIndirect { - offset: u64::from(MeshArguments::OBJECT_COMMANDS), - draw_count: pieces, - stride: 12, - }, - }; - (command, Some(fold)) - } - (true, None, _) => ( - vk::DrawCommand::DrawMeshTasksIndirectCount { - offset: u64::from(MeshArguments::OBJECT_COMMANDS), - count_offset: u64::from(MeshArguments::OBJECT_COUNT), - max_draw_count: MeshArguments::OBJECT_PIECES, - stride: 12, - }, - None, - ), - _ => (command, None), - }; - // The grid Metal reports of the first stage's threadgroups (`MultiRegion` 0 reads - // `NumWorkgroups` instead): 0 for an indirect draw, whose counts only the GPU knows, and for - // the mesh stage under an object function, whose grid the object function sets; an unfolded - // object function's wrapped threads; a folded one reads its record instead. - let first = if object { lo } else { lm }; - let mut grid = [0u32; 3]; - let counted = groups.filter(|_| !folded).unwrap_or_default(); - for (i, g) in counted.into_iter().enumerate() { - grid[i] = match wrapped { - Some((threads, _)) => threads[i], - None => g.checked_mul(first[i]).ok_or_else(|| { - BindError::Unsupported(Unsupported::not_representable(Feature::GroupCount { - axis: Some([Axis::X, Axis::Y, Axis::Z][i]), - })) - })?, - }; - } - let region = |grid, l: [u32; 3]| { - region_bytes([0; 3], grid, l) - .ok_or_else(|| internal(format!("a mesh draw's threadgroup of {l:?} threads"))) - }; - let (object_region, mesh_region) = if object { - // A partial object threadgroup's draw flags its region (`lower::dispatch::NONUNIFORM`). - let object_region = match nonuniform && launches { - true => crate::lower::dispatch::partial_region_bytes(grid, lo) - .ok_or_else(|| internal(format!("a mesh draw's threadgroup of {lo:?} threads")))?, - false => region(grid, lo)?, - }; - (Some(object_region), region([0; 3], lm)?) - } else { - (None, region(grid, lm)?) - }; - let discards = discards || fold.is_some_and(|f| f.discarded); - Ok(MeshDraw { - command, - specialization, - object_region, - mesh_region, - fold, - discards, - }) -} - -/// What a patch draw of `p` instantiates ([`FactorTemplate`]), from the layout's factor, patch -/// index and control-point index bindings and the device's `(minStorageBufferOffsetAlignment, -/// maxStorageBufferRange)`: `None` for a pipeline that draws no patches. The control stage binds -/// the patch index buffer, and the control-point index buffer exactly when the pipeline has a -/// control-point index type. -fn factor_template( - p: &RenderPipeline, - (factors, patch_indices, control_point_indices): ( - Option<(u32, u32)>, - Option<(u32, u32)>, - Option<(u32, u32)>, - ), - (alignment, max_range): (u64, u64), -) -> Result, BindError> { - use metal::TessellationControlPointIndexType as T; - let Some(t) = p.graphics.tessellation else { - return Ok(None); - }; - let Some(patch_indices) = patch_indices else { - return Err(internal( - "a tessellation pipeline's layout without its patch index buffer", - )); - }; - let ty = t.control_point_index_type; - let control_point_indices = match (ty, control_point_indices) { - (T::None, None) => None, - (T::UInt16, Some(b)) => Some((b, 2)), - (T::UInt32, Some(b)) => Some((b, 4)), - _ => { - return Err(internal(format!( - "a tessellation pipeline of control-point index type {ty:?} with binding \ - {control_point_indices:?}" - ))) - } - }; - Ok(Some(FactorTemplate { - step: t.factor_step_function, - patch_bytes: crate::lower::tessellation::factors::factor_bytes(t.domain), - alignment, - max_range, - control_points: t.control_points, - patch_indices, - control_point_indices, - push_offset: t.push_offset, - factor_binding: factors, - })) -} - -/// `+∞` as a `half`'s bits. -const HALF_INFINITY: u16 = 0x7c00; - -/// The scale the control stage is pushed for a scale that is infinite as a `half`, which -/// multiplies every positive factor past the maximum level, as Metal's does (70000 and `+∞` drew -/// what the maximum factor draws). 2^32 does so finitely, as the control stage requires (its module -/// docs): its product with the least positive `half` factor, 2^-24, is 2^8, past every level (at -/// most 64), and with the largest finite one below 2^48. -const INFINITE_SCALE: f32 = 4_294_967_296.0; - -/// What a patch draw binds and writes ([`patch_binding`]): the factor buffer's range, residual bind -/// offset, instance stride and scale, and the patch and control-point index buffers' ranges and -/// fields. -struct PatchBinding { - /// The factor buffer's range, where the encoder set one. - factors: Option, - /// The factor buffer's residual bind offset. - residual: u32, - /// Its instance stride, rounded down to a multiple of 4. - stride: u32, - /// The scale, rounded to `half` as Metal rounds it, an infinite one as `INFINITE_SCALE`. - scale: f32, - /// The patch index buffer's descriptor range, where the draw has one. - patch_indices: Option, - /// Its residual bind offset. - index_residual: u32, - /// Whether the draw has a patch index buffer (1 or 0). - indexed: u32, - /// The control-point index buffer's descriptor range, where the draw has one. - control_point_indices: Option, - /// Its residual bind offset (0 without one). - point_residual: u32, -} - -/// The control stage's writes of a patch draw of a tessellation pipeline (`factors` is the -/// plan's, `None` for any other pipeline): [`patch_binding`]'s, as [`control_writes`] pushes and -/// binds them. -fn patch_draw( - factors: Option<&FactorTemplate>, - state: &BindState, - draw: &DrawCall, -) -> Result)>, BindError> { - match (patch_binding(factors, state, draw)?, factors) { - (Some(b), Some(t)) => control_writes(b, t.push_offset, t.factor_binding).map(Some), - _ => Ok(None), - } -} - -/// The bindings of a patch draw of a tessellation pipeline (`factors` is the plan's, `None` for -/// any other pipeline): the draw draws patches exactly when the pipeline is one, with the control -/// points the function states, indexed exactly when the pipeline has a control-point index type. -/// The factor buffer is bound over the factors the draw reads ([`factor_window`]), from any even -/// byte, at an instance stride rounded down to a multiple of 4, its scale rounded to `half` as -/// Metal rounds it (an infinite one as `INFINITE_SCALE`); the patch index buffer over the indices -/// it reads (a direct draw's from its patch start, an indirect one's from the offset to the -/// buffer's end), and the control-point index buffer over the indices it reads -/// ([`control_point_window`]). -fn patch_binding( - factors: Option<&FactorTemplate>, - state: &BindState, - draw: &DrawCall, -) -> Result, BindError> { - let (control_points, patch_index, control_point_index) = match *draw { - DrawCall::Patches { - control_points, - patch_index, - control_point_index, - .. - } - | DrawCall::PatchesIndirect { - control_points, - patch_index, - control_point_index, - .. - } => (control_points, patch_index, control_point_index), - _ if factors.is_some() => return Err(BindError::InvalidDrawKind { patches: false }), - _ => return Ok(None), - }; - let Some(t) = factors else { - return Err(BindError::InvalidDrawKind { patches: true }); - }; - if t.control_points != 0 && control_points != t.control_points { - return Err(BindError::PatchControlPoints { - given: control_points, - expected: t.control_points, - }); - } - if control_point_index.is_some() != t.control_point_indices.is_some() { - return Err(BindError::ControlPointIndexing { - indexed: control_point_index.is_some(), - }); - } - let f = state.tessellation_factors; - // Metal takes the scale as a `half`, rounded to nearest even, and multiplies the factors by a - // positive one, subnormal and infinite ones included; one that is - // 0, negative or NaN as a `half` is refused. - let scale = f32_to_f16_bits(f.scale); - if !(0x0001..=HALF_INFINITY).contains(&scale) { - return Err(BindError::InvalidTessellationFactorScale { - bits: f.scale.to_bits(), - }); - } - let (factor_range, residual, stride) = - match (t.factor_binding.is_some(), f.buffer) { - (false, None) => (None, 0, 0), - (true, Some(b)) => { - // The factors are read from any even byte: an odd offset from the byte below, and - // each instance's at the stride rounded down to a multiple of 4, an odd one too, as - // plain Metal reads them. - let offset = b.offset - b.offset % 2; - let instance_stride = b.instance_stride - b.instance_stride % 4; - let window = factor_window(t, instance_stride, draw); - let (range, residual) = - descriptor_range(offset, b.length, window, t.alignment, t.max_range).map_err( - |e| match e { - RangeError::TooLarge { needed } => BindError::TessellationFactorRange { - needed, - limit: t.max_range, - }, - RangeError::Empty => BindError::Unsupported( - Unsupported::not_representable(Feature::BufferRange), - ), - }, - )?; - // The reading stage adds `instance · stride` in `u32`: a direct draw's factors lie - // within the bound range, whose end is below 2^32; an indirect draw's beyond it are - // past the buffer's end, a read Metal leaves undefined. - let stride = (instance_stride & u64::from(u32::MAX)) as u32; - (Some(range), residual, stride) - } - _ => return Err(internal( - "the bind state's shape differs from the plan's at the tessellation factor buffer", - )), - }; - // The patch index buffer: its words from the offset (a multiple of 4, as Metal requires), - // over the indices the draw reads. - let (patch_indices, index_residual, indexed) = match patch_index { - None => (None, 0, 0), - Some((buffer, offset)) => { - if !offset.is_multiple_of(4) { - return Err(BindError::InvalidPatchIndexBuffer { offset }); - } - let (set, binding) = t.patch_indices; - let window = match *draw { - DrawCall::Patches { - patch_start, - patch_count, - .. - } => Window::Bounded { - start: 4 * i64::from(patch_start), - len: 4 * u64::from(patch_count), - }, - _ => Window::Whole, - }; - let (range, residual) = - descriptor_range(offset, buffer.length, window, t.alignment, t.max_range).map_err( - |e| match e { - RangeError::TooLarge { needed } => BindError::PatchIndexRange { - needed, - limit: t.max_range, - }, - RangeError::Empty => BindError::Unsupported( - Unsupported::not_representable(Feature::BufferRange), - ), - }, - )?; - let range = DescriptorRange { - set, - binding, - element: 0, - range, - }; - (Some(range), residual, 1u32) - } - }; - // The control-point index buffer: its indices from the offset (a multiple of the index - // size, as Metal requires), over the indices the draw reads. - let (control_point_indices, point_residual) = - match (control_point_index, t.control_point_indices) { - (Some((buffer, offset)), Some(((set, binding), size))) => { - if !offset.is_multiple_of(size) { - return Err(BindError::InvalidControlPointIndexBuffer { offset }); - } - let window = control_point_window(size, draw); - let (range, residual) = - descriptor_range(offset, buffer.length, window, t.alignment, t.max_range) - .map_err(|e| match e { - RangeError::TooLarge { needed } => BindError::ControlPointIndexRange { - needed, - limit: t.max_range, - }, - RangeError::Empty => BindError::Unsupported( - Unsupported::not_representable(Feature::BufferRange), - ), - })?; - let range = DescriptorRange { - set, - binding, - element: 0, - range, - }; - (Some(range), residual) - } - _ => (None, 0), - }; - let scale = match scale { - HALF_INFINITY => INFINITE_SCALE, - finite => f16_bits_to_f32(finite), - }; - Ok(Some(PatchBinding { - factors: factor_range, - residual, - stride, - scale, - patch_indices, - index_residual, - indexed, - control_point_indices, - point_residual, - })) -} - -/// A tessellation pipeline's control stage's writes for a patch draw `b` -/// ([`patch_binding`]), whose control stage's push range is at `push_offset` and whose factor -/// buffer binds at `binding`: its push range holds the factor buffer's residual bind offset, -/// instance stride and scale, then the patch index buffer's residual bind offset and whether the -/// draw has one, then the control-point index buffer's residual bind offset (0 without one); and -/// the factor, patch index and control-point index buffers' descriptor ranges. -fn control_writes( - b: PatchBinding, - push_offset: u32, - binding: Option<(u32, u32)>, -) -> Result<(PushConstantWrite, Vec), BindError> { - let mut ranges = Vec::with_capacity(3); - match (b.factors, binding) { - (Some(range), Some((set, binding))) => ranges.push(DescriptorRange { - set, - binding, - element: 0, - range, - }), - (None, None) => {} - _ => { - return Err(internal( - "a factor range without its control stage's binding", - )) - } - } - ranges.extend(b.patch_indices); - ranges.extend(b.control_point_indices); - let mut bytes = Vec::with_capacity(24); - bytes.extend_from_slice(&b.residual.to_le_bytes()); - bytes.extend_from_slice(&b.stride.to_le_bytes()); - bytes.extend_from_slice(&b.scale.to_bits().to_le_bytes()); - bytes.extend_from_slice(&b.index_residual.to_le_bytes()); - bytes.extend_from_slice(&b.indexed.to_le_bytes()); - bytes.extend_from_slice(&b.point_residual.to_le_bytes()); - Ok(( - PushConstantWrite { - stages: vk::ShaderStageFlags::TESSELLATION_CONTROL, - offset: push_offset, - bytes, - }, - ranges, - )) -} - -/// The bytes of the control-point index buffer an indexed patch draw reads, relative to its -/// offset, indices `size` bytes each: the control points of the patches `[patchStart, patchStart + -/// patchCount)` of a direct draw without a patch index buffer (Metal's validation holds the buffer -/// to the first `(patchStart + patchCount) · N` indices); `Whole` for an indirect draw, a draw with -/// a patch index buffer (whose patch indices Metal does not check against the buffer), or a window -/// past `i64`. -fn control_point_window(size: u64, draw: &DrawCall) -> Window { - let DrawCall::Patches { - control_points, - patch_start, - patch_count, - patch_index: None, - .. - } = *draw - else { - return Window::Whole; - }; - let per_patch = u128::from(control_points) * u128::from(size); - let start = u128::from(patch_start) * per_patch; - let len = u128::from(patch_count) * per_patch; - match ( - i64::try_from(start), - u64::try_from(len), - i64::try_from(start + len), - ) { - (Ok(start), Ok(len), Ok(_)) => Window::Bounded { start, len }, - _ => Window::Whole, - } -} - -/// The bytes of the factor buffer a patch draw reads, relative to its bind offset: the patches -/// `[patchStart, patchStart + patchCount)` of a per-patch step and the instances `[baseInstance, -/// baseInstance + instanceCount)` of a per-instance one (Metal's instance index includes the base -/// instance), each `patch_bytes` long; `Whole` for an indirect draw or a window past `i64`, and -/// empty for a draw of no patches or instances. -fn factor_window(t: &FactorTemplate, instance_stride: u64, draw: &DrawCall) -> Window { - use metal::TessellationFactorStepFunction as S; - let DrawCall::Patches { - patch_start, - patch_count, - instance_count, - base_instance, - .. - } = *draw - else { - return Window::Whole; - }; - if patch_count == 0 || instance_count == 0 { - return Window::Bounded { start: 0, len: 0 }; - } - let size = u128::from(t.patch_bytes); - let per_patch = matches!(t.step, S::PerPatch | S::PerPatchAndPerInstance); - let per_instance = matches!(t.step, S::PerInstance | S::PerPatchAndPerInstance); - let span = |on: bool, first: u32, count: u32, stride: u128| { - if on { - let first = u128::from(first); - (first * stride, (first + u128::from(count) - 1) * stride) - } else { - (0, 0) - } - }; - let (p0, p1) = span(per_patch, patch_start, patch_count, size); - let (i0, i1) = span( - per_instance, - base_instance, - instance_count, - u128::from(instance_stride), - ); - let (start, end) = (p0 + i0, p1 + i1 + size); - match (i64::try_from(start), u64::try_from(end - start)) { - (Ok(start), Ok(len)) if i64::try_from(end).is_ok() => Window::Bounded { start, len }, - _ => Window::Whole, - } -} - -/// A direct draw of a multiview plan (`limit` is the device's `maxMultiviewInstanceIndex`) must -/// keep its last instance index within the limit -/// (`VUID-vkCmdDraw-maxMultiviewInstanceIndex-02688`); an indirect one asks for the CPU read of its -/// arguments. -fn multiview_instances(limit: Option, draw: &DrawCall) -> Result<(), BindError> { - let Some(available) = limit else { - return Ok(()); - }; - let (instance_count, base_instance) = match *draw { - DrawCall::Primitives { - instance_count, - base_instance, - .. - } - | DrawCall::Indexed { - instance_count, - base_instance, - .. - } - | DrawCall::Patches { - instance_count, - base_instance, - .. - } => (instance_count, base_instance), - // A mesh pipeline's draws are never multiview. - DrawCall::Indirect { .. } - | DrawCall::PatchesIndirect { .. } - | DrawCall::MeshThreadgroups { .. } - | DrawCall::MeshThreads { .. } - | DrawCall::MeshThreadgroupsIndirect { .. } => return Ok(()), - }; - let last = u64::from(base_instance) + u64::from(instance_count); - if instance_count == 0 || last - 1 <= u64::from(available) { - return Ok(()); - } - Err(BindError::Unsupported(Unsupported::needs( - Feature::VertexAmplification, - Capability::Limit { - limit: VkLimit::MaxMultiviewInstanceIndex, - required: last - 1, - available: u64::from(available), - }, - ))) -} - -/// The index type of `draw`, a direct indexed draw of one of Metal's index types; `None` for any -/// other draw. -fn draw_index_type(draw: &DrawCall) -> Option { - match *draw { - DrawCall::Indexed { index_type, .. } if index_type == vk::IndexType::UINT16 => { - Some(metal::IndexType::UInt16) - } - DrawCall::Indexed { index_type, .. } if index_type == vk::IndexType::UINT32 => { - Some(metal::IndexType::UInt32) - } - _ => None, - } -} - -/// How an indexed draw runs on the primitive ID's de-indexed variant -/// ([`deindexed_draw`]): `PushField::CaptureLayout`'s words, the Vulkan draw it runs as and its -/// index read. -struct DeindexedDraw { - layout: [u32; 4], - /// Without indices, `index count` vertices from 0, with the draw's instances. - command: vk::DrawCommand, - /// Its read of its indices, from the index offset, as storage in the vertex stage. - indices: ResourceUse, -} - -/// `PushField::VerticesPerPrimitive` for `draw` of primitive type `primitive` -/// (`MissingPrimitiveType` without one): 3 for a triangle list, 2 for a line list and 1 for a -/// strip or points. The vertex function reads the draw's first vertex as its base vertex, an -/// indirect draw's from its arguments as the GPU draws it. An indexed draw shares a vertex among -/// primitives, whose flat inputs read it alike: it runs `from_zero`, its indices drawn as -/// vertices from 0 (the de-indexed form, [`deindexed_draw`]), and is -/// otherwise `NotImplemented(PrimitiveId)`. A draw in the private list form (`listed`) is the -/// consumer's list, run without indices whatever its call: twice that where it lists Metal's -/// quads or quad strip as two triangles a quad (`quads`), whose primitive Metal counts once. -fn vertices_per_primitive( - draw: &DrawCall, - primitive: Option, - (from_zero, listed, quads): (bool, bool, bool), -) -> Result { - let per_primitive = match primitive.ok_or(BindError::MissingPrimitiveType)? { - metal::PrimitiveType::Triangle => 3, - metal::PrimitiveType::Line => 2, - metal::PrimitiveType::Point - | metal::PrimitiveType::LineStrip - | metal::PrimitiveType::TriangleStrip => 1, - }; - match draw { - _ if listed && quads => Ok(2 * per_primitive), - _ if listed => Ok(per_primitive), - DrawCall::Primitives { .. } | DrawCall::Indirect { indexed: None, .. } => Ok(per_primitive), - DrawCall::Indexed { .. } if from_zero => Ok(per_primitive), - _ => Err(not_implemented(Feature::PrimitiveId)), - } -} - -/// How an indexed draw runs on the primitive ID's de-indexed variant of index type `ty` -/// (`VariantKey::primitive_id_indices`): `index count` vertices from 0 without indices, with the -/// draw's instances, its layout `[0, index count, base instance, base vertex]`, its indices read -/// in the vertex stage. A line or triangle strip, which Metal restarts at the all-ones index, an -/// indexed draw whose indices run past its buffer or whose index offset is not a multiple of the -/// index size, and any other draw are `NotImplemented(PrimitiveId)` (`MissingPrimitiveType` -/// without a primitive type). A draw of another index type never reaches here -/// (`instantiate_draw` asks for its variant). -fn deindexed_draw( - ty: metal::IndexType, - draw: &DrawCall, - overrun: Option, - primitive: Option, -) -> Result { - let listed = match primitive.ok_or(BindError::MissingPrimitiveType)? { - metal::PrimitiveType::Point - | metal::PrimitiveType::Line - | metal::PrimitiveType::Triangle => true, - metal::PrimitiveType::LineStrip | metal::PrimitiveType::TriangleStrip => false, - }; - let DrawCall::Indexed { - index_type, - index_count, - index_offset, - instance_count, - base_vertex, - base_instance, - .. - } = *draw - else { - return Err(not_implemented(Feature::PrimitiveId)); - }; - if !listed { - return Err(not_implemented(Feature::PrimitiveId)); - } - if draw_index_type(draw) != Some(ty) { - return Err(internal( - "a de-indexed draw of another index type than its plan's", - )); - } - let size = index_bytes(index_type) - .ok_or_else(|| internal("a de-indexed draw without an index size"))?; - if overrun.is_some() || !index_offset.is_multiple_of(size) { - return Err(not_implemented(Feature::PrimitiveId)); - } - Ok(DeindexedDraw { - // The base vertex's two's-complement bits: the function adds it wrapping. - layout: [0, index_count, base_instance, base_vertex as u32], - command: vk::DrawCommand::Draw { - vertex_count: index_count, - instance_count, - first_vertex: 0, - first_instance: base_instance, - }, - indices: ResourceUse { - resource: UseTarget::IndexBuffer, - access: AccessSet::READ, - class: AccessClass::Storage, - stages: vk::PipelineStageFlags2::VERTEX_SHADER, - range: Some(ByteRange { - offset: 0, - len: u64::from(index_count) * size, - }), - }, - }) -} - -/// The commands of `draw` of `state`, written over `out` (`BindingPlan::instantiate_draw_into`): -/// each of its fields set, its vectors cleared or their values overwritten in place, never -/// replaced; the heap tables among its descriptor bytes. -fn instantiate( - t: &GraphicsTemplate, - state: &BindState, - draw: &DrawCall, - out: &mut DrawCommands, -) -> Result<(), BindError> { - let DrawCommands { - push_constants, - descriptor_bytes, - buffer_offsets, - draw: draw_command, - indirect_needs_arguments, - extents, - push_holes, - descriptor_ranges, - root_tables, - vertex_strides, - uses, - index_overrun: overrun_out, - amplifications: amplifications_out, - specialization: specialization_out, - mesh_arguments: mesh_arguments_out, - object_fold: object_fold_out, - discards_command_buffer: discards_out, - } = out; - let overrun = index_overrun(draw); - let (command, base) = vk_draw(draw, overrun); - let deindexed = match t.deindexed { - Some(ty) => Some(deindexed_draw(ty, draw, overrun, state.primitive_type)?), - None => None, - }; - let command = deindexed.as_ref().map_or(command, |d| d.command); - // A mesh render pipeline makes mesh draws, and only it does. - let mesh = match (&t.mesh, mesh_threads(draw)) { - (Some(m), Some(_)) => Some(mesh_draw(m, draw, command)?), - (None, None) => None, - (_, given) => { - return Err(BindError::InvalidMeshDraw { - mesh: given.is_some(), - }) - } - }; - let command = mesh.as_ref().map_or(command, |m| m.command); - descriptor_ranges.clear(); - extents.clear(); - let bound = bind_buffers(&t.buffers, state, descriptor_ranges, extents)?; - descriptor_ranges.extend(crate::bind::instantiate::texel_ranges(&t.resources, state)?); - let tables = crate::bind::heap::table_bytes(&t.resources, state)?; - // A patch draw: its control stage's writes. - let control = patch_draw(t.tessellation.as_ref(), state, draw)?; - multiview_instances(t.multiview_instance_limit, draw)?; - let resident = if t.stages.iter().any(|s| s.root_first.is_some()) { - Some(table_entries(state)) - } else { - None - }; - let vertex = state.stages.get(&Stage::Vertex); - - push_holes.clear(); - root_tables.clear(); - // The push writes and stage tables written so far, each over the one a draw before left at - // its place where there is one. - let (mut pushes, mut tables_written) = (0, 0); - let mut reads_base = false; - for st in &t.stages { - let (push_start, push_size) = st.push_range.unwrap_or((0, 0)); - // Each stage's push bytes and table, zeroed; empty where it has none. - let (mut no_push, mut no_table) = (Vec::new(), Vec::new()); - let push = match push_size { - 0 => &mut no_push, - size => { - let write = reused(push_constants, pushes, || PushConstantWrite { - stages: st.flags, - offset: push_start, - bytes: Vec::new(), - }); - pushes += 1; - write.stages = st.flags; - write.offset = push_start; - zeroed(&mut write.bytes, size as usize) - } - }; - let table = match st.table { - Some((set, binding)) => { - let written = reused(descriptor_bytes, tables_written, || DescriptorBytes { - set, - binding, - bytes: Vec::new(), - }); - tables_written += 1; - written.set = set; - written.binding = binding; - zeroed(&mut written.bytes, st.table_size as usize) - } - None => &mut no_table, - }; - for f in &st.fields { - let bytes: FieldBytes = match f.field { - PushField::RootTableAddress - | PushField::ExecutionStatusAddress - | PushField::CaptureIndexAddress - | PushField::MergedDrawAddress - | PushField::ReplayRegionAddress => { - let PushLoc::Push { offset } = f.loc else { - return Err(not_implemented(Feature::Lowering(LowerFamily::StageIo))); - }; - let stages = st.flags; - push_holes.push(match f.field { - PushField::RootTableAddress => { - PushHole::RootTableAddress { stages, offset } - } - PushField::ExecutionStatusAddress => { - PushHole::ExecutionStatusAddress { stages, offset } - } - PushField::MergedDrawAddress => { - PushHole::MergedDrawAddress { stages, offset } - } - PushField::ReplayRegionAddress => { - PushHole::ReplayRegionAddress { stages, offset } - } - _ => PushHole::CaptureIndexAddress { stages, offset }, - }); - continue; - } - PushField::CaptureLayout => match &deindexed { - Some(d) => FieldBytes::words(d.layout.iter().copied()), - None => return Err(internal("a draw layout without its de-indexed form")), - }, - PushField::DispatchRegion => match mesh.as_ref().and_then(|m| m.region(st.stage)) { - Some(region) => FieldBytes::of(®ion), - None => return Err(internal("a dispatch region outside a mesh draw")), - }, - PushField::ViewportCount => FieldBytes::of(&state.viewport_count.to_le_bytes()), - // At least 1: Metal renders a length of 0 as one of 1, and the function stores - // `Layer` as 0 at or past the length either way. - PushField::RenderTargetArrayLength => { - FieldBytes::of(&state.render_target_array_length.max(1).to_le_bytes()) - } - // Metal's own `[0, 1]` where the state holds none. - PushField::DepthClampRange => state - .depth_clamp_range - .unwrap_or([0.0, 1.0]) - .iter() - .flat_map(|v| v.to_le_bytes()) - .collect(), - // 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(), - ), - // The blend color as the encoder set it, which a blend the shader computes reads. - PushField::HalfBlendColor => state - .blend_color - .iter() - .flat_map(|c| c.to_bits().to_le_bytes()) - .collect(), - // The first amplification's; `amplifications` writes each before its draw. - PushField::AmplificationId - | PushField::AmplificationLayerOffset - | PushField::AmplificationViewportOffset => FieldBytes::of( - &lification_word(f.field, 0, &t.amplifications)?.to_le_bytes(), - ), - PushField::BaseVertexInstance => { - reads_base = true; - FieldBytes::words(base) - } - PushField::VerticesPerPrimitive => { - let from_zero = deindexed.is_some(); - let form = (from_zero, t.private_list, state.quad_primitive_ids); - FieldBytes::of( - &vertices_per_primitive(draw, state.primitive_type, form)?.to_le_bytes(), - ) - } - PushField::VertexBufferStride(layout) => pulled_stride(t, state, layout)?, - field => slot_field(field, &bound.residuals, &t.resources, state) - .ok_or_else(|| internal(format!("a render push field {field:?}")))?, - }; - put(&mut push[..], push_start, &mut table[..], f.loc, &bytes)?; - } - if let (Some(first), Some(resident)) = (st.root_first, resident.as_ref()) { - let statics: Vec<_> = bound - .statics - .iter() - .filter(|(slot, _)| slot.stage == st.stage) - .map(|(slot, e)| (slot.index, *e)) - .collect(); - root_tables.push((st.flags, stage_root_table(&statics, first, resident))); - } - } - push_constants.truncate(pushes); - descriptor_bytes.truncate(tables_written); - - // Vertex buffers: offsets, per-bind strides, the address rules, and the bytes the draw's - // vertex and instance ranges fetch. - buffer_offsets.clear(); - vertex_strides.clear(); - for vb in &t.vertex_buffers { - match vertex.and_then(|v| v.buffers.get(&vb.slot.index)) { - Some(&BoundBuffer::Buffer { - offset, - attribute_stride, - .. - }) => { - let (stride, per_bind) = match vb.stride { - VertexStride::Static(s) => (s, None), - VertexStride::PerBind => { - let s = attribute_stride.unwrap_or(0); - (s, Some(s)) - } - }; - // The plan put a layout fixed function cannot fetch as bound into its variant, - // whose pipeline pulls it; this plan's pipeline is not that one. - if !fetchable(vb, &t.vertex_strides, offset_alignment(offset), per_bind) { - return Err(internal(format!( - "a draw of {:?} as the plan's pulled-vertex-buffer variant binds it; \ - compile and plan the variant", - vb.slot - ))); - } - // Dynamic strides take every binding's (`pStrides`). - if per_bind.is_some() || t.vertex_strides.dynamic { - vertex_strides.push((vb.binding, stride)); - } - buffer_offsets.push((vb.binding, offset)); - let window = fetch_window(vb, stride, draw); - match extents.iter_mut().find(|e| e.slot == vb.slot) { - // A buffer argument at the same index: both uses' bytes. - Some(e) => e.window = hull(e.window, window), - None => extents.push(BufferExtent { - slot: vb.slot, - window, - }), - } - } - Some(&BoundBuffer::Bytes { - attribute_stride, .. - }) => { - // Inline bytes, at their bind's stride where the layout's is per bind (0 without - // one, as a buffer's), at an aligned offset of the consumer's. - let (stride, per_bind) = match vb.stride { - VertexStride::Static(s) => (s, None), - VertexStride::PerBind => { - let s = attribute_stride.unwrap_or(0); - (s, Some(s)) - } - }; - let aligned = metal::vertex::MAX_VERTEX_ALIGNMENT; - if !fetchable(vb, &t.vertex_strides, aligned, per_bind) { - return Err(internal(format!( - "a draw of {:?} as the plan's pulled-vertex-buffer variant binds it; \ - compile and plan the variant", - vb.slot - ))); - } - if per_bind.is_some() || t.vertex_strides.dynamic { - vertex_strides.push((vb.binding, stride)); - } - buffer_offsets.push((vb.binding, 0)); - } - None => return Err(BindError::UnboundVertexBuffer { slot: vb.slot }), - } - } - descriptor_bytes.extend(tables); - if let Some((push, ranges)) = control { - push_constants.push(push); - descriptor_ranges.extend(ranges); - } - // A band variant's draw pushes its band to the evaluation stage's own range. - if let Some(offset) = t.line_band { - let (_, band) = state - .line_band - .ok_or_else(|| internal("a draw of a band pipeline without its band"))?; - push_constants.push(PushConstantWrite { - stages: vk::ShaderStageFlags::TESSELLATION_EVALUATION, - offset, - bytes: band.iter().flat_map(|v| v.to_le_bytes()).collect(), - }); - } - // The CPU reads the arguments of an indirect draw whose base vertex and instance the profile - // emulates, of a multiview plan, or without `drawIndirectFirstInstance`, and of an indexed one - // whose index fetch nothing bounds, which the GPU pass may bound instead. - let arguments_elsewhere = - (reads_base || t.multiview_instance_limit.is_some() || t.indirect_first_instance_missing) - && matches!( - draw, - DrawCall::Indirect { .. } | DrawCall::PatchesIndirect { .. } - ); - // An indirect mesh draw's GPU-written group counts must lie within the device's limits - // (`VUID-VkDrawMeshTasksIndirectCommandEXT-TaskEXT-07326` and its siblings): the arguments - // pass writes the counts the draw reads. - // A folded object function's direct draw reads its uploaded fold instead. - let object_fold = mesh.as_ref().and_then(|m| m.fold); - let discards = mesh.as_ref().is_some_and(|m| m.discards); - let mesh_arguments = match (command, &t.mesh) { - (vk::DrawCommand::DrawMeshTasksIndirectCount { .. }, Some(_)) => { - Some(MeshArgumentsForm::FoldedObject) - } - (vk::DrawCommand::DrawMeshTasksIndirect { .. }, Some(m)) if object_fold.is_none() => { - Some(match m.object { - Some(_) => MeshArgumentsForm::Object, - None => MeshArgumentsForm::Mesh, - }) - } - _ => None, - }; - let index_unbounded = indirect_indices_unbounded(draw); - let amplifications = amplification_writes(t)?; - let specialization = mesh.map(|m| m.specialization); - // The de-indexed form reads its indices in the vertex stage, by address, and binds no index - // buffer. - uses.clear(); - match deindexed.as_ref().map(|d| d.indices) { - Some(indices) => uses.push(indices), - None => draw_uses(uses, draw, overrun, t.tessellation.as_ref()), - } - // An indirect mesh draw's arguments pass reads Metal's 12 bytes in the compute stage. - if mesh_arguments.is_some() { - uses.push(ResourceUse { - resource: UseTarget::Indirect, - access: AccessSet::READ, - class: AccessClass::Storage, - stages: vk::PipelineStageFlags2::COMPUTE_SHADER, - range: Some(ByteRange { offset: 0, len: 12 }), - }); - } - *indirect_needs_arguments = arguments_elsewhere || index_unbounded; - *mesh_arguments_out = mesh_arguments; - *object_fold_out = object_fold; - *discards_out = discards; - *draw_command = command; - *overrun_out = overrun; - *amplifications_out = amplifications; - *specialization_out = specialization; - Ok(()) -} - -/// `PushField::VertexBufferStride(layout)`: the stride the pulled layout `layout` reads, the -/// pipeline's where it is static, else the vertex buffer's bind's there. -fn pulled_stride( - t: &GraphicsTemplate, - state: &BindState, - layout: u32, -) -> Result { - let fixed = t.pulled_strides.iter().find(|(l, _)| *l == layout); - let vertex = state.stages.get(&Stage::Vertex); - let stride = match (fixed, vertex.and_then(|v| v.buffers.get(&layout))) { - (Some(&(_, s)), _) => s, - ( - None, - Some(&BoundBuffer::Buffer { - attribute_stride, .. - }), - ) => attribute_stride.unwrap_or(0), - ( - None, - Some(&BoundBuffer::Bytes { - attribute_stride, .. - }), - ) => attribute_stride.unwrap_or(0), - _ => { - return Err(internal(format!( - "the bind state's shape differs from the plan's at vertex buffer {layout}" - ))) - } - }; - Ok(FieldBytes::of(&stride.to_le_bytes())) -} - -/// The `at`th value of `list`, which holds at least `at`: the one a draw before left there, else -/// `made`, pushed. -fn reused(list: &mut Vec, at: usize, made: impl FnOnce() -> T) -> &mut T { - if list.len() == at { - list.push(made()); - } - &mut list[at] -} - -/// `bytes`, made `len` zero bytes in the storage it holds. -pub(crate) fn zeroed(bytes: &mut Vec, len: usize) -> &mut Vec { - bytes.clear(); - bytes.resize(len, 0); - bytes -} - -/// The `u32` of amplification push field `field` for amplification `a` of a plan drawing -/// `offsets`: the amplification itself, or its render target slice or viewport offset. -fn amplification_word(field: PushField, a: usize, offsets: &[[u32; 2]]) -> Result { - let [layer, viewport] = match offsets.get(a) { - Some(&o) => o, - None if a == 0 => [0, 0], - None => return Err(internal(format!("amplification {a} of {}", offsets.len()))), - }; - Ok(match field { - PushField::AmplificationId => { - u32::try_from(a).map_err(|_| internal("an amplification past 2^32"))? - } - PushField::AmplificationLayerOffset => layer, - PushField::AmplificationViewportOffset => viewport, - other => return Err(internal(format!("{other:?} is no amplification field"))), - }) -} - -/// The push writes that make a draw of a plan drawing one amplification each that amplification's -/// (`DrawCommands::amplifications`): per amplification, in order, each of its fields in each stage -/// that reads one, in that stage's push window, where the placement order puts them. -fn amplification_writes(t: &GraphicsTemplate) -> Result>, BindError> { - let mut out = Vec::with_capacity(t.amplifications.len()); - for a in 0..t.amplifications.len() { - let mut writes = Vec::new(); - for st in &t.stages { - for f in &st.fields { - if !matches!( - f.field, - PushField::AmplificationId - | PushField::AmplificationLayerOffset - | PushField::AmplificationViewportOffset - ) { - continue; - } - let PushLoc::Push { offset } = f.loc else { - return Err(internal("an amplification field outside the push window")); - }; - let word = amplification_word(f.field, a, &t.amplifications)?; - writes.push(PushConstantWrite { - stages: st.flags, - offset, - bytes: word.to_le_bytes().to_vec(), - }); - } - } - out.push(writes); - } - Ok(out) -} - -/// Whether fixed-function vertex input can fetch vertex buffer `vb` bound at an offset of -/// alignment class `offset_alignment` ([`offset_alignment`]) with the per-bind stride -/// `per_bind` (`None` for a static stride, which link already made fetchable) under `rules`: -/// -/// - the bind offset is a multiple of every attribute's alignment (the attribute address is the -/// bind offset plus multiples of component-aligned offsets and strides, "Vertex Input Address -/// Calculation", `VUID-vkCmdDraw-format-10389`/`-10390`); -/// - a per-bind stride is at most `maxVertexInputBindingStride` -/// (`VUID-vkCmdBindVertexBuffers2-pStrides-03362`, `VUID-VkVertexInputBindingDescription-stride-00619`), -/// a multiple of every attribute's alignment, a multiple of and at least the portability -/// subset's `minVertexInputBindingStrideAlignment` (`VUID-VkVertexInputBindingDescription-stride-04456` -/// for the static stride a per-bind one stands for; MoltenVK passes it to Metal either way), -/// as dynamic state either 0 or covering an element's attributes -/// (`VUID-vkCmdBindVertexBuffers2-pStrides-06209`), and covering them, 0 not excepted, where -/// the portability subset withholds `vertexAttributeAccessBeyondStride` -/// (`VUID-VkVertexInputAttributeDescription-vertexAttributeAccessBeyondStride-04457`). -/// -/// Otherwise the pulled fetch reads it (any offset, any `u32` stride): the plan asks for the -/// pulled-vertex-buffer variant. -fn fetchable( - vb: &PlannedVertexBuffer, - rules: &StrideRules, - offset_alignment: u32, - per_bind: Option, -) -> bool { - let offset = offset_alignment.is_multiple_of(vb.alignment); - let stride = per_bind.is_none_or(|s| { - s <= rules.max - && s.is_multiple_of(vb.alignment) - && portable_vertex_stride(rules.portability_alignment, s) - && (!rules.dynamic || s == 0 || s >= vb.reads.1) - && (!rules.within_stride || s >= vb.reads.1) - }); - offset && stride -} - -/// The bytes of a fixed-function vertex buffer a draw can fetch, relative to its bind offset: the -/// elements its vertex range (a per-vertex binding) or instance range (a per-instance one, Vulkan's -/// element `firstInstance + i / divisor`) reaches, each read at `reads` of the element. `Whole` -/// when the elements are GPU-side (an indirect draw, or the vertices of an indexed draw) or the -/// window's end is past `i64`; empty for a draw of no vertices or instances. -fn fetch_window(vb: &PlannedVertexBuffer, stride: u32, draw: &DrawCall) -> Window { - let empty = Window::Bounded { start: 0, len: 0 }; - let per_instance = vb.input_rate == vk::VertexInputRate::INSTANCE; - let (first, count) = match *draw { - DrawCall::Primitives { - vertex_count: 0, .. - } - | DrawCall::Primitives { - instance_count: 0, .. - } - | DrawCall::Indexed { index_count: 0, .. } - | DrawCall::Indexed { - instance_count: 0, .. - } => return empty, - DrawCall::Primitives { - vertex_start, - vertex_count, - .. - } if !per_instance => (vertex_start, vertex_count), - DrawCall::Primitives { - base_instance, - instance_count, - .. - } - | DrawCall::Indexed { - base_instance, - instance_count, - .. - } if per_instance => { - let elements = match vb.divisor { - 0 => 1, - d => instance_count.div_ceil(d), - }; - (base_instance, elements) - } - // A tessellation pipeline fetches no fixed-function vertex buffer, nor does a mesh - // pipeline. - DrawCall::Primitives { .. } - | DrawCall::Indexed { .. } - | DrawCall::Indirect { .. } - | DrawCall::Patches { .. } - | DrawCall::PatchesIndirect { .. } - | DrawCall::MeshThreadgroups { .. } - | DrawCall::MeshThreads { .. } - | DrawCall::MeshThreadgroupsIndirect { .. } => return Window::Whole, - }; - let (lo, hi) = vb.reads; - let stride = i128::from(stride); - let start = i128::from(first) * stride + i128::from(lo); - let end = (i128::from(first) + i128::from(count) - 1) * stride + i128::from(hi); - // Both ends in `i64` (`0 <= start < end`), so `start + len` is representable too. - match (i64::try_from(start), i64::try_from(end)) { - (Ok(s), Ok(e)) => Window::Bounded { - start: s, - len: e.abs_diff(s), - }, - _ => Window::Whole, - } -} - -/// The smallest window holding both `a` and `b` (an empty bounded window holds nothing). -fn hull(a: Window, b: Window) -> Window { - match (a, b) { - (Window::Bounded { len: 0, .. }, w) | (w, Window::Bounded { len: 0, .. }) => w, - (Window::Bounded { start: s, len: l }, Window::Bounded { start: t, len: m }) => { - let lo = i128::from(s.min(t)); - let hi = (i128::from(s) + i128::from(l)).max(i128::from(t) + i128::from(m)); - match u64::try_from(hi - lo) { - Ok(len) => Window::Bounded { - start: lo as i64, - len, - }, - Err(_) => Window::Whole, - } - } - _ => Window::Whole, - } -} - -/// The index positions of a direct indexed draw that lie past its index buffer: those whose bytes -/// do not lie wholly before [`IndexBufferRef::fetch_end`]. `None` when there are none, for any -/// other draw, and for an index type without a fixed size. The draw is `Clamped` to the indices -/// before there. -fn index_overrun(draw: &DrawCall) -> Option { - let DrawCall::Indexed { - index_type, - index_buffer, - index_count, - index_offset, - .. - } = *draw - else { - return None; - }; - let size = index_bytes(index_type)?; - let inside = index_buffer - .fetch_end(index_offset) - .checked_sub(index_offset) - .map_or(0, |bytes| bytes / size); - let inside = u32::try_from(inside).unwrap_or(u32::MAX).min(index_count); - match index_count - inside { - 0 => None, - past_end => Some(IndexOverrun::Clamped { past_end }), - } -} - -/// Whether nothing bounds the index fetch of `draw`, an indexed indirect draw, whose counts are in -/// GPU memory: without `robustBufferAccess2` Vulkan requires every index inside the bound range -/// (`VUID-VkDrawIndexedIndirectCommand-robustBufferAccess2-08798`), which the binder cannot -/// check. Its arguments are then read on the CPU, and the direct draw is bounded by -/// [`index_overrun`]. -fn indirect_indices_unbounded(draw: &DrawCall) -> bool { - matches!( - draw, - DrawCall::Indirect { - indexed: Some(_), - .. - } - ) -} - -/// The read of a draw's `len` bytes of indirect arguments (`DRAW_INDIRECT`), from its argument -/// offset. -fn indirect_use(len: u64) -> ResourceUse { - ResourceUse { - resource: UseTarget::Indirect, - access: AccessSet::READ, - class: AccessClass::Indirect, - stages: vk::PipelineStageFlags2::DRAW_INDIRECT, - range: Some(ByteRange { offset: 0, len }), - } -} - -/// The draw's own resources, pushed onto `uses`: its index buffer (`INDEX_INPUT`; the indices of a -/// direct draw from the -/// index offset, the rest of the buffer for an indirect one), a patch draw's patch index buffer -/// (`TESSELLATION_CONTROL_SHADER`, as storage; the indices of a direct draw's patches, the rest of -/// the buffer for an indirect one) and control-point index buffer (likewise; the indices -/// [`control_point_window`] bounds, of the size `factors` states), and its indirect arguments -/// (`DRAW_INDIRECT`; 16 bytes, 20 indexed; a mesh draw's are its pipeline's to decide, -/// `instantiate`), all read. -/// Ranges are relative to the draw's index offset, patch index offset, control-point index offset, -/// and argument offset. A direct draw whose indices run past the buffer (`overrun`, `Clamped`) -/// reads only the indices it draws (none, from offset 0, when it draws none). -fn draw_uses( - uses: &mut Vec, - draw: &DrawCall, - overrun: Option, - factors: Option<&FactorTemplate>, -) { - let index = |range| ResourceUse { - resource: UseTarget::IndexBuffer, - access: AccessSet::READ, - class: AccessClass::Index, - stages: vk::PipelineStageFlags2::INDEX_INPUT, - range, - }; - // A patch draw's index buffers, read by the control stage. - let control = |resource, range| ResourceUse { - resource, - access: AccessSet::READ, - class: AccessClass::Storage, - stages: vk::PipelineStageFlags2::TESSELLATION_CONTROL_SHADER, - range, - }; - let reads_patch_indices = factors.is_some(); - if let ( - DrawCall::Patches { - patch_index: Some(_), - .. - } - | DrawCall::PatchesIndirect { - patch_index: Some(_), - .. - }, - true, - ) = (*draw, reads_patch_indices) - { - // A direct draw's indices from its patch start, an indirect one's from the offset on. - let range = match *draw { - DrawCall::Patches { - patch_start, - patch_count, - .. - } => Some(ByteRange { - offset: 4 * u64::from(patch_start), - len: 4 * u64::from(patch_count), - }), - _ => None, - }; - uses.push(control(UseTarget::PatchIndices, range)); - } - if let ( - DrawCall::Patches { - control_point_index: Some(_), - .. - } - | DrawCall::PatchesIndirect { - control_point_index: Some(_), - .. - }, - Some(&FactorTemplate { - control_point_indices: Some((_, size)), - .. - }), - ) = (*draw, factors) - { - let range = match control_point_window(size, draw) { - Window::Bounded { start, len } => u64::try_from(start) - .ok() - .map(|offset| ByteRange { offset, len }), - _ => None, - }; - uses.push(control(UseTarget::ControlPointIndices, range)); - } - match *draw { - // A mesh draw's arguments are its pipeline's to decide (`instantiate`). - DrawCall::Primitives { .. } - | DrawCall::Patches { .. } - | DrawCall::MeshThreadgroups { .. } - | DrawCall::MeshThreads { .. } - | DrawCall::MeshThreadgroupsIndirect { .. } => {} - DrawCall::Indexed { - index_type, - index_count, - .. - } => uses.push(index(index_bytes(index_type).map(|size| ByteRange { - offset: 0, - len: match overrun { - None => u64::from(index_count) * size, - Some(IndexOverrun::Clamped { past_end }) => { - u64::from(index_count.saturating_sub(past_end)) * size - } - }, - }))), - DrawCall::Indirect { indexed: None, .. } | DrawCall::PatchesIndirect { .. } => { - uses.push(indirect_use(16)) - } - DrawCall::Indirect { - indexed: Some(_), .. - } => uses.extend([index(None), indirect_use(20)]), - } -} - -/// Bytes of one index of `ty`, when it is a fixed-size index type. -fn index_bytes(ty: vk::IndexType) -> Option { - if ty == vk::IndexType::UINT16 { - Some(2) - } else if ty == vk::IndexType::UINT32 { - Some(4) - } else if ty == vk::IndexType::UINT8 { - Some(1) - } else { - None - } -} - -#[cfg(test)] -mod tests; diff --git a/crates/metal2vulkan/src/bind/graphics/tests.rs b/crates/metal2vulkan/src/bind/graphics/tests.rs deleted file mode 100644 index f0eb6bfc0..000000000 --- a/crates/metal2vulkan/src/bind/graphics/tests.rs +++ /dev/null @@ -1,2060 +0,0 @@ -//! Draw mapping, vertex-buffer windows, bind rules, and draw uses on synthetic templates. Render -//! plans of compiled pipelines are tested end to end in `src/tests/engine_graphics_binder.rs`. - -use super::*; -use crate::bind::plan::{PlannedBuffer, ResourceTemplate}; -use crate::bind::state::{length_class, StageTable}; -use std::cell::RefCell; - -thread_local! { - /// The commands every [`instantiate`] of a test writes over, from one call to the next. - static KEPT: RefCell = RefCell::new(DrawCommands::default()); -} - -/// The commands of `draw` ([`super::instantiate`]) written over no draw's, which must be what -/// writing them over those of every draw of the test before it gives (and its error the same). -fn instantiate( - t: &GraphicsTemplate, - state: &BindState, - draw: &DrawCall, -) -> Result { - let mut fresh = DrawCommands::default(); - let made = super::instantiate(t, state, draw, &mut fresh).map(|()| fresh); - KEPT.with(|kept| { - let mut kept = kept.borrow_mut(); - let over = super::instantiate(t, state, draw, &mut kept).map(|()| kept.clone()); - assert_eq!(over, made, "the commands written over those before"); - }); - made -} - -/// The draw's own resources ([`super::draw_uses`]), in a list of their own. -fn draw_uses( - draw: &DrawCall, - overrun: Option, - factors: Option<&FactorTemplate>, -) -> Vec { - let mut uses = Vec::new(); - super::draw_uses(&mut uses, draw, overrun, factors); - uses -} - -/// Every Metal draw maps to the Vulkan draw of the same arguments, and the base-vertex push field -/// reports Vulkan's `BaseVertex` (first vertex, or the vertex offset of an indexed draw) and -/// `BaseInstance`; indirect draws report zero (their arguments stay on the GPU). -#[test] -fn draws_map_to_the_vulkan_draw_of_the_same_arguments() { - let (d, base) = vk_draw( - &DrawCall::Primitives { - vertex_start: 7, - vertex_count: 3, - instance_count: 4, - base_instance: 2, - }, - None, - ); - assert_eq!( - d, - vk::DrawCommand::Draw { - vertex_count: 3, - instance_count: 4, - first_vertex: 7, - first_instance: 2 - } - ); - assert_eq!(base, [7, 2]); - let (d, base) = vk_draw( - &DrawCall::Indexed { - index_type: vk::IndexType::UINT32, - index_buffer: IndexBufferRef::new(1, 48), - index_count: 9, - index_offset: 12, - instance_count: 1, - base_vertex: -3, - base_instance: 5, - }, - None, - ); - assert_eq!( - d, - vk::DrawCommand::DrawIndexed { - index_type: vk::IndexType::UINT32, - index_buffer_offset: 12, - index_count: 9, - instance_count: 1, - first_index: 0, - vertex_offset: -3, - first_instance: 5 - } - ); - assert_eq!(base, [(-3i32) as u32, 5]); - let (d, base) = vk_draw( - &DrawCall::Indirect { - indirect: IndirectRef { - token: 2, - offset: 40, - }, - indexed: Some((vk::IndexType::UINT16, IndexBufferRef::new(3, 64), 8)), - }, - None, - ); - assert_eq!( - d, - vk::DrawCommand::DrawIndexedIndirect { - index_type: vk::IndexType::UINT16, - index_buffer_offset: 8, - offset: 40, - draw_count: 1, - stride: 20 - } - ); - assert_eq!(base, [0, 0]); -} - -/// A render plan names only vertex and fragment stages; a tessellation pipeline's vertex -/// function is its evaluation stage, and its synthesized vertex and control stages are none, as -/// are a band's control and evaluation stages; a geometry stage is no render stage. -#[test] -fn only_vertex_and_fragment_stages_are_render_stages() { - use vk::ShaderStage as S; - let stages = - |modules: &[S], tessellated| metal_stages(modules.iter().copied(), (tessellated, false)); - let tessellation = [ - S::VERTEX, - S::TESSELLATION_CONTROL, - S::TESSELLATION_EVALUATION, - S::FRAGMENT, - ]; - assert_eq!( - metal_stages(tessellation.iter().copied(), (false, true)), - Ok(vec![ - (Stage::Vertex, S::VERTEX), - (Stage::Fragment, S::FRAGMENT) - ]) - ); - assert_eq!( - stages(&[S::VERTEX, S::FRAGMENT], false), - Ok(vec![ - (Stage::Vertex, S::VERTEX), - (Stage::Fragment, S::FRAGMENT) - ]) - ); - assert_eq!( - stages( - &[ - S::VERTEX, - S::TESSELLATION_CONTROL, - S::TESSELLATION_EVALUATION, - S::FRAGMENT - ], - true - ), - Ok(vec![ - (Stage::Vertex, S::TESSELLATION_EVALUATION), - (Stage::Fragment, S::FRAGMENT) - ]) - ); - for (modules, tessellated) in [ - (&[S::COMPUTE][..], false), - (&[S::VERTEX, S::GEOMETRY, S::FRAGMENT][..], false), - (&[S::TESSELLATION_EVALUATION][..], false), - (&[S::TESSELLATION_CONTROL][..], false), - (&[S::COMPUTE][..], true), - ] { - assert!(matches!( - stages(modules, tessellated), - Err(BindError::Internal(_)) - )); - } - assert_eq!( - pipeline_stage(Stage::Fragment), - vk::PipelineStageFlags2::FRAGMENT_SHADER - ); - assert_eq!( - tessellated_pipeline_stage(Stage::Vertex), - vk::PipelineStageFlags2::TESSELLATION_EVALUATION_SHADER - ); - assert_eq!( - tessellated_pipeline_stage(Stage::Fragment), - vk::PipelineStageFlags2::FRAGMENT_SHADER - ); -} - -fn vslot(index: u32) -> SlotRef { - SlotRef { - stage: Stage::Vertex, - class: SlotClass::Buffer, - index, - } -} - -/// A per-vertex buffer of static stride 24 whose attributes read bytes `[0, 24)` at alignment 4 -/// (binding 0, slot 1), and a per-instance buffer of per-bind stride, divisor 2, reading bytes -/// `[4, 8)` at alignment 2 (binding 1, slot 2). -fn vertex_buffers() -> Vec { - vec![ - PlannedVertexBuffer { - binding: 0, - slot: vslot(1), - stride: VertexStride::Static(24), - input_rate: vk::VertexInputRate::VERTEX, - divisor: 1, - alignment: 4, - reads: (0, 24), - }, - PlannedVertexBuffer { - binding: 1, - slot: vslot(2), - stride: VertexStride::PerBind, - input_rate: vk::VertexInputRate::INSTANCE, - divisor: 2, - alignment: 2, - reads: (4, 8), - }, - ] -} - -fn rules(portability_alignment: Option, dynamic: bool) -> StrideRules { - StrideRules { - max: 2048, - portability_alignment, - dynamic, - within_stride: false, - } -} - -fn primitives(vertex_start: u32, vertex_count: u32, instances: (u32, u32)) -> DrawCall { - DrawCall::Primitives { - vertex_start, - vertex_count, - instance_count: instances.1, - base_instance: instances.0, - } -} - -fn indexed(index_count: u32, instances: (u32, u32)) -> DrawCall { - DrawCall::Indexed { - index_type: vk::IndexType::UINT16, - index_buffer: IndexBufferRef::new(7, 4096), - index_count, - index_offset: 64, - instance_count: instances.1, - base_vertex: 5, - base_instance: instances.0, - } -} - -/// A fixed-function buffer's window is what the draw's vertex (per-vertex) or instance -/// (per-instance, Vulkan's `firstInstance + i / divisor`) range fetches; the vertices of an -/// indexed draw and everything of an indirect draw are GPU-side (`Whole`); a draw of nothing -/// fetches nothing; a window past `i64` is `Whole`. -#[test] -fn vertex_windows_follow_the_vertex_and_instance_ranges() { - let [per_vertex, per_instance] = vertex_buffers()[..] else { - panic!("two buffers") - }; - let bounded = |start, len| Window::Bounded { start, len }; - let empty = bounded(0, 0); - // Vertices 2..=4 at stride 24: bytes 48..120. - assert_eq!( - fetch_window(&per_vertex, 24, &primitives(2, 3, (0, 1))), - bounded(48, 72) - ); - // Instances 1..=3 (five instances from 1, divisor 2) at stride 8, bytes 4..8 of each. - assert_eq!( - fetch_window(&per_instance, 8, &primitives(2, 3, (1, 5))), - bounded(12, 20) - ); - assert_eq!( - fetch_window(&per_instance, 8, &indexed(6, (1, 5))), - bounded(12, 20) - ); - let mut zero = per_instance; - zero.divisor = 0; - assert_eq!( - fetch_window(&zero, 8, &primitives(0, 3, (3, 9))), - bounded(28, 4) - ); - // A zero stride reads one element for every vertex. - assert_eq!( - fetch_window(&per_vertex, 0, &primitives(9, 100, (0, 1))), - bounded(0, 24) - ); - assert_eq!( - fetch_window(&per_vertex, 24, &indexed(6, (0, 1))), - Window::Whole - ); - let indirect = DrawCall::Indirect { - indirect: IndirectRef { - token: 1, - offset: 0, - }, - indexed: None, - }; - assert_eq!(fetch_window(&per_vertex, 24, &indirect), Window::Whole); - assert_eq!(fetch_window(&per_instance, 8, &indirect), Window::Whole); - for draw in [ - primitives(2, 0, (0, 1)), - primitives(2, 3, (0, 0)), - indexed(0, (0, 1)), - indexed(6, (0, 0)), - ] { - assert_eq!(fetch_window(&per_vertex, 24, &draw), empty, "{draw:?}"); - assert_eq!(fetch_window(&per_instance, 8, &draw), empty, "{draw:?}"); - } - assert_eq!( - fetch_window(&per_vertex, 1 << 31, &primitives(1 << 31, 1, (0, 1))), - bounded(1 << 62, 24) - ); - assert_eq!( - fetch_window(&per_vertex, u32::MAX, &primitives(u32::MAX, 1, (0, 1))), - Window::Whole, - "past i64" - ); - // A start inside `i64` whose end is past it (`start + len` would overflow) is `Whole`. - assert_eq!( - fetch_window(&per_vertex, 1 << 31, &primitives(1 << 31, u32::MAX, (0, 1))), - Window::Whole, - "end past i64" - ); - // The hull of two windows holds both; an empty one adds nothing; `Whole` absorbs. - assert_eq!(hull(bounded(0, 16), bounded(48, 72)), bounded(0, 120)); - assert_eq!(hull(bounded(-8, 4), bounded(0, 4)), bounded(-8, 12)); - assert_eq!(hull(empty, bounded(48, 72)), bounded(48, 72)); - assert_eq!(hull(bounded(48, 72), empty), bounded(48, 72)); - assert_eq!(hull(bounded(0, 16), Window::Whole), Window::Whole); -} - -/// Fixed-function input fetches a vertex buffer when its bind offset is a multiple of the -/// attributes' alignment and a per-bind stride is at most `maxVertexInputBindingStride`, a -/// multiple of the attributes' alignment and of the portability alignment (and at least it), and -/// as dynamic state 0 or covering an element's attributes, and covering them (0 too) where the -/// portability subset withholds `vertexAttributeAccessBeyondStride`; otherwise the plan pulls the -/// layout. -#[test] -fn fixed_function_fetches_only_what_vulkan_can_bind() { - let vb = vertex_buffers()[1]; - let per_bind = |rules: StrideRules, stride| fetchable(&vb, &rules, 4, Some(stride)); - assert!(per_bind(rules(None, true), 8)); - assert!(per_bind(rules(None, true), 0)); - assert!( - !per_bind(rules(None, true), 6), - "does not cover bytes [4, 8)" - ); - assert!(per_bind(rules(None, false), 6)); - assert!(!per_bind(rules(None, false), 3), "not a multiple of 2"); - assert!(per_bind(rules(Some(4), true), 12)); - assert!(!per_bind(rules(Some(4), true), 10)); - assert!(!per_bind(rules(Some(4), false), 0)); - assert!(!per_bind(rules(Some(1), true), 0)); - assert!(per_bind(rules(None, true), 2048)); - assert!(!per_bind(rules(None, true), 2050), "past the limit"); - // Without `vertexAttributeAccessBeyondStride` a stride must cover bytes [4, 8) (a zero one - // already breaks the portability subset's stride alignment). - let within = StrideRules { - within_stride: true, - ..rules(Some(1), false) - }; - assert!(per_bind(within, 8)); - assert!(!per_bind(within, 6), "does not cover bytes [4, 8)"); - assert!(per_bind(rules(Some(1), false), 6)); - // The bind offset's alignment class against the attributes' alignment (2 here, 4 for the - // first buffer); a static stride is link's. - assert!(fetchable(&vb, &rules(None, true), 2, None)); - assert!(!fetchable(&vb, &rules(None, true), 1, None)); - let first = vertex_buffers()[0]; - assert!(fetchable(&first, &rules(None, true), 4, None)); - assert!(!fetchable(&first, &rules(None, true), 2, None)); - // Classed up to 4. - let offsets = [0, 1, 2, 3, 4, 6, 8, 12, 64, 192, 1 << 40, (1 << 40) + 2]; - assert_eq!( - offsets.map(offset_alignment), - [4, 1, 2, 1, 4, 2, 4, 4, 4, 4, 4, 2] - ); -} - -/// An attribute's alignment is its component size (the whole word of a packed format) and the -/// binding's element bytes run from the smallest offset to the largest end. -#[test] -fn attribute_reads_take_the_widest_alignment_and_the_element_hull() { - let attr = |binding, format, offset| VertexAttribute { - location: 0, - binding, - format, - offset, - }; - let attributes = [ - attr(0, vk::Format::R16G16_SFLOAT, 4), - attr(0, vk::Format::R8G8B8A8_UNORM, 1), - attr(1, vk::Format::R32G32B32_SFLOAT, 0), - attr(0, vk::Format::A2B10G10R10_UNORM_PACK32, 12), - ]; - assert_eq!(attribute_reads(&attributes, 0), Ok((4, (1, 16)))); - assert_eq!(attribute_reads(&attributes, 1), Ok((4, (0, 12)))); - assert!(matches!( - attribute_reads(&attributes, 2), - Err(BindError::Internal(_)) - )); - assert!(matches!( - attribute_reads(&[attr(0, vk::Format::BC1_RGB_UNORM_BLOCK, 0)], 0), - Err(BindError::Internal(_)) - )); -} - -/// A draw lists its index buffer (the direct draw's indices from the index offset, the rest of -/// the buffer for an indirect one) and its indirect arguments as uses. -#[test] -fn draws_list_their_index_and_indirect_buffers() { - let index = |range| ResourceUse { - resource: UseTarget::IndexBuffer, - access: AccessSet::READ, - class: AccessClass::Index, - stages: vk::PipelineStageFlags2::INDEX_INPUT, - range, - }; - let args = |len| ResourceUse { - resource: UseTarget::Indirect, - access: AccessSet::READ, - class: AccessClass::Indirect, - stages: vk::PipelineStageFlags2::DRAW_INDIRECT, - range: Some(ByteRange { offset: 0, len }), - }; - assert!(draw_uses(&primitives(0, 3, (0, 1)), None, None).is_empty()); - assert_eq!( - draw_uses(&indexed(6, (0, 1)), None, None), - vec![index(Some(ByteRange { offset: 0, len: 12 }))] - ); - let mut wide = indexed(6, (0, 1)); - if let DrawCall::Indexed { index_type, .. } = &mut wide { - *index_type = vk::IndexType::UINT32; - } - assert_eq!( - draw_uses(&wide, None, None), - vec![index(Some(ByteRange { offset: 0, len: 24 }))] - ); - assert_eq!( - draw_uses( - &DrawCall::Indirect { - indirect: IndirectRef { - token: 1, - offset: 32 - }, - indexed: None, - }, - None, - None - ), - vec![args(16)] - ); - assert_eq!( - draw_uses( - &DrawCall::Indirect { - indirect: IndirectRef { - token: 1, - offset: 32 - }, - indexed: Some((vk::IndexType::UINT32, IndexBufferRef::new(2, 64), 8)), - }, - None, - None - ), - vec![index(None), args(20)] - ); -} - -/// A direct indexed draw of `index_count` indices of `index_type` from `index_offset` in an -/// index buffer of `length` bytes. -fn indexed_in( - index_type: vk::IndexType, - length: u64, - index_offset: u64, - index_count: u32, -) -> DrawCall { - DrawCall::Indexed { - index_type, - index_buffer: IndexBufferRef::new(7, length), - index_count, - index_offset, - instance_count: 2, - base_vertex: -5, - base_instance: 1, - } -} - -/// The index positions past the buffer are those whose bytes do not lie wholly inside it, counted -/// from the index offset in each index size; a draw to the buffer's last byte has none. They are -/// clamped; other draws and sizeless index types have none. -#[test] -fn index_positions_past_the_buffer_are_counted_from_the_index_offset() { - use vk::IndexType as T; - let clamped = |past_end| Some(IndexOverrun::Clamped { past_end }); - for (draw, past) in [ - // 12 halves from byte 64 of 88 bytes end at its last byte. - (indexed_in(T::UINT16, 88, 64, 12), None), - (indexed_in(T::UINT16, 88, 64, 15), Some(3)), - // Metal's fetch reads bytes up to the length rounded up to 4 (`fetch_end`): the half at - // byte 88 of 89 bytes reads byte 89 too, and the one at 90 is past the end. - (indexed_in(T::UINT16, 89, 64, 14), None), - (indexed_in(T::UINT16, 89, 64, 15), Some(1)), - (indexed_in(T::UINT32, 18, 0, 5), None), - (indexed_in(T::UINT32, 18, 0, 8), Some(3)), - (indexed_in(T::UINT32, 66, 64, 3), Some(2)), - (indexed_in(T::UINT8, 10, 3, 9), None), - (indexed_in(T::UINT8, 10, 3, 11), Some(2)), - // A draw of no index reads none, at its offset or past the end (its bind is - // `a_draw_of_no_index_binds_inside_the_buffer`'s). - (indexed_in(T::UINT32, 64, 32, 0), None), - (indexed_in(T::UINT32, 64, 64, 0), None), - (indexed_in(T::UINT32, 64, 4096, 0), None), - // The largest buffer holds every index a `u32` count can name. - (indexed_in(T::UINT32, u64::MAX, u64::MAX - 8, 2), None), - ( - indexed_in(T::UINT32, u64::MAX, u64::MAX - 8, u32::MAX), - Some(u32::MAX - 2), - ), - ] { - assert_eq!(index_overrun(&draw), past.and_then(clamped), "{draw:?}"); - } - // No index inside the buffer: an offset at or past its end cannot be bound, so the draw is - // clamped to none. The rounding to 4 bytes applies only from an offset before the length. - for draw in [ - indexed_in(T::UINT32, 64, 64, 3), - indexed_in(T::UINT32, 64, 4096, 3), - indexed_in(T::UINT16, 66, 66, 3), - ] { - assert_eq!(index_overrun(&draw), clamped(3), "{draw:?}"); - } - let sizeless = indexed_in(T::NONE_KHR, 4, 0, 64); - let indirect = DrawCall::Indirect { - indirect: IndirectRef { - token: 1, - offset: 0, - }, - indexed: Some((T::UINT32, IndexBufferRef::new(2, 4), 0)), - }; - for draw in [sizeless, indirect, primitives(0, 3, (0, 1))] { - assert_eq!(index_overrun(&draw), None, "{draw:?}"); - } -} - -/// A clamped draw draws its indices inside the buffer from the same offset, and one with none binds -/// the buffer at offset 0 and draws no index. Uses follow: a clamped draw reads the indices it -/// draws. -#[test] -fn an_overrunning_draw_draws_and_reads_as_its_overrun_states() { - let draw = indexed_in(vk::IndexType::UINT16, 89, 64, 15); - let vk_indexed = |index_buffer_offset, index_count| vk::DrawCommand::DrawIndexed { - index_type: vk::IndexType::UINT16, - index_buffer_offset, - index_count, - instance_count: 2, - first_index: 0, - vertex_offset: -5, - first_instance: 1, - }; - let index = |len| ResourceUse { - resource: UseTarget::IndexBuffer, - access: AccessSet::READ, - class: AccessClass::Index, - stages: vk::PipelineStageFlags2::INDEX_INPUT, - range: Some(ByteRange { offset: 0, len }), - }; - // 14 halves lie before byte 92, the length rounded up to 4 (`fetch_end`). - let clamped = Some(IndexOverrun::Clamped { past_end: 1 }); - assert_eq!(index_overrun(&draw), clamped); - assert_eq!( - vk_draw(&draw, clamped), - (vk_indexed(64, 14), [(-5i32) as u32, 1]) - ); - assert_eq!(draw_uses(&draw, clamped, None), vec![index(28)]); - assert_eq!(vk_draw(&draw, None).0, vk_indexed(64, 15)); - assert_eq!(draw_uses(&draw, None, None), vec![index(30)]); - let past = indexed_in(vk::IndexType::UINT16, 64, 64, 4); - let none = Some(IndexOverrun::Clamped { past_end: 4 }); - assert_eq!(vk_draw(&past, none).0, vk_indexed(0, 0)); - assert_eq!(draw_uses(&past, none, None), vec![index(0)]); -} - -/// End to end on a synthetic template: instantiation records the overrun and draws the indices -/// inside the buffer, and leaves a draw inside the buffer unchanged. -#[test] -fn instantiation_bounds_a_draw_by_its_index_buffer() { - let t = GraphicsTemplate { - buffers: Vec::new(), - stages: Vec::new(), - vertex_buffers: Vec::new(), - pulled_strides: Vec::new(), - resources: ResourceTemplate::default(), - vertex_strides: rules(None, false), - multiview_instance_limit: None, - other_layer_variant: false, - amplifications: Vec::new(), - tessellation: None, - indirect_first_instance_missing: false, - mesh: None, - deindexed: None, - private_list: false, - line_band: None, - }; - let state = BindState::default(); - let past = indexed_in(vk::IndexType::UINT32, 40, 8, 10); - let inside = indexed_in(vk::IndexType::UINT32, 48, 8, 10); - let count = |cmds: &DrawCommands| match cmds.draw { - vk::DrawCommand::DrawIndexed { index_count, .. } => index_count, - _ => panic!("an indexed draw: {:?}", cmds.draw), - }; - let cmds = instantiate(&t, &state, &inside).expect("inside"); - assert_eq!((count(&cmds), cmds.index_overrun), (10, None)); - let cmds = instantiate(&t, &state, &past).expect("past"); - assert_eq!( - (count(&cmds), cmds.index_overrun), - (8, Some(IndexOverrun::Clamped { past_end: 2 })) - ); - assert!(!cmds.indirect_needs_arguments); -} - -/// A draw of no index binds the buffer at offset 0 where its own offset is at or past the buffer's -/// length, which may lie past the `VkBuffer` (`VUID-vkCmdBindIndexBuffer-offset-08782`), for every -/// index type; it records no overrun. One whose offset lies inside the buffer keeps it. -#[test] -fn a_draw_of_no_index_binds_inside_the_buffer() { - let t = GraphicsTemplate { - buffers: Vec::new(), - stages: Vec::new(), - vertex_buffers: Vec::new(), - pulled_strides: Vec::new(), - resources: ResourceTemplate::default(), - vertex_strides: rules(None, false), - multiview_instance_limit: None, - other_layer_variant: false, - amplifications: Vec::new(), - tessellation: None, - indirect_first_instance_missing: false, - mesh: None, - deindexed: None, - private_list: false, - line_band: None, - }; - let state = BindState::default(); - let bound = |cmds: &DrawCommands| match cmds.draw { - vk::DrawCommand::DrawIndexed { - index_buffer_offset, - index_count, - .. - } => (index_buffer_offset, index_count), - _ => panic!("an indexed draw: {:?}", cmds.draw), - }; - for ty in [ - vk::IndexType::UINT8, - vk::IndexType::UINT16, - vk::IndexType::UINT32, - vk::IndexType::NONE_KHR, - ] { - for (offset, at) in [ - (32, 32), - (60, 60), - (64, 0), - (66, 0), - (4096, 0), - (u64::MAX, 0), - ] { - let draw = indexed_in(ty, 64, offset, 0); - let cmds = instantiate(&t, &state, &draw).expect("draw"); - assert_eq!(bound(&cmds), (at, 0), "{ty:?} {offset}"); - assert_eq!(cmds.index_overrun, None, "{ty:?} {offset}"); - assert_eq!(vk_draw(&draw, None).0, cmds.draw); - } - } -} - -/// An indexed indirect draw, whose counts are in GPU memory and whose index fetch nothing bounds, -/// asks for its arguments on the CPU, at any index offset. A draw without indices stays -/// GPU-side. -#[test] -fn an_unbounded_indexed_indirect_draw_reads_its_arguments() { - let indirect = |indexed| DrawCall::Indirect { - indirect: IndirectRef { - token: 1, - offset: 0, - }, - indexed, - }; - let at = |offset| Some((vk::IndexType::UINT32, IndexBufferRef::new(2, 64), offset)); - for (draw, unbounded) in [ - (indirect(at(0)), true), - (indirect(at(60)), true), - (indirect(at(64)), true), - (indirect(at(4096)), true), - (indirect(None), false), - (indexed_in(vk::IndexType::UINT32, 64, 0, 99), false), - ] { - assert_eq!(indirect_indices_unbounded(&draw), unbounded, "{draw:?}"); - } - let template = |indirect_first_instance_missing| GraphicsTemplate { - buffers: Vec::new(), - stages: Vec::new(), - vertex_buffers: Vec::new(), - pulled_strides: Vec::new(), - resources: ResourceTemplate::default(), - vertex_strides: rules(None, false), - multiview_instance_limit: None, - other_layer_variant: false, - amplifications: Vec::new(), - tessellation: None, - indirect_first_instance_missing, - mesh: None, - deindexed: None, - private_list: false, - line_band: None, - }; - let state = BindState::default(); - let t = template(false); - let cmds = instantiate(&t, &state, &indirect(at(8))).expect("indexed"); - assert!(cmds.indirect_needs_arguments); - assert_eq!(cmds.index_overrun, None); - let cmds = instantiate(&t, &state, &indirect(at(64))).expect("indexed past"); - assert!(cmds.indirect_needs_arguments); - let cmds = instantiate(&t, &state, &indirect(None)).expect("indirect"); - assert!(!cmds.indirect_needs_arguments); - // Another reason asks for the CPU read too. - let t = template(true); - let cmds = instantiate(&t, &state, &indirect(None)).expect("indirect"); - assert!(cmds.indirect_needs_arguments); -} - -/// Instantiation binds each vertex buffer at its offset (which must be a multiple of the -/// attributes' alignment), checks and passes per-bind strides, and gives each buffer the window -/// its draw fetches, joined with the window of a buffer argument at the same index. -#[test] -fn draws_bind_vertex_buffers_at_aligned_offsets_with_their_windows() { - let template = |rules| GraphicsTemplate { - buffers: vec![PlannedBuffer { - slot: vslot(1), - window: Window::Bounded { start: 0, len: 16 }, - form: BufferForm::Descriptor, - access: AccessSet::READ, - binding: Some((0, 0)), - alignment: 16, - max_range: 1 << 27, - bound: BoundKind::Buffer { - device_address: false, - length_class: length_class(4096), - }, - }], - stages: Vec::new(), - vertex_buffers: vertex_buffers(), - pulled_strides: Vec::new(), - resources: ResourceTemplate::default(), - vertex_strides: rules, - multiview_instance_limit: None, - other_layer_variant: false, - amplifications: Vec::new(), - tessellation: None, - indirect_first_instance_missing: false, - mesh: None, - deindexed: None, - private_list: false, - line_band: None, - }; - let state = |offsets: (u64, u64), stride| { - let buffer = |offset, attribute_stride| BoundBuffer::Buffer { - length: 4096, - offset, - gpu_address: 0x1_0000, - device_address: None, - attribute_stride, - }; - let mut t = StageTable::default(); - t.buffers.insert(1, buffer(offsets.0, None)); - t.buffers.insert(2, buffer(offsets.1, Some(stride))); - let mut s = BindState::default(); - s.stages.insert(Stage::Vertex, t); - s - }; - let t = template(rules(None, true)); - let draw = primitives(2, 3, (1, 5)); - let cmds = instantiate(&t, &state((64, 6), 8), &draw).expect("draw"); - assert_eq!(cmds.buffer_offsets, vec![(0, 64), (1, 6)]); - // Dynamic strides list every binding's, the static one included (`pStrides`). - assert_eq!(cmds.vertex_strides, vec![(0, 24), (1, 8)]); - let window = |slot| { - cmds.extents - .iter() - .find(|e| e.slot == slot) - .map(|e| e.window) - }; - assert_eq!( - window(vslot(1)), - Some(Window::Bounded { start: 0, len: 120 }) - ); - assert_eq!( - window(vslot(2)), - Some(Window::Bounded { start: 12, len: 20 }) - ); - assert!(cmds.uses.is_empty()); - let cmds = instantiate(&t, &state((64, 6), 8), &indexed(6, (1, 5))).expect("indexed"); - assert_eq!( - cmds.extents - .iter() - .find(|e| e.slot == vslot(1)) - .map(|e| e.window), - Some(Window::Whole) - ); - assert_eq!(cmds.uses.len(), 1); - // Offsets and strides fixed function cannot fetch are the plan's pulled variant: a draw of this - // plan with them is an internal error. - let pulled = |r: Result| matches!(r, Err(BindError::Internal(_))); - assert!(pulled(instantiate(&t, &state((66, 6), 8), &draw))); - assert!(pulled(instantiate(&t, &state((64, 7), 8), &draw))); - assert!(pulled(instantiate(&t, &state((64, 6), 6), &draw))); - let t = template(rules(None, false)); - let cmds = instantiate(&t, &state((64, 6), 6), &draw).expect("static strides"); - assert_eq!( - cmds.vertex_strides, - vec![(1, 6)], - "only the per-bind stride" - ); - let t = template(rules(Some(4), false)); - assert!(pulled(instantiate(&t, &state((64, 6), 6), &draw))); - assert!(instantiate(&t, &state((64, 6), 12), &draw).is_ok()); -} - -/// Inline vertex bytes at a per-bind layout read at their bind's stride, 0 without one, as plain -/// Metal reads them (`setVertexBytes:length:atIndex:` read vertex 0 for every -/// vertex, the stride form at 0, 4 and 8 its stride); and a stride fixed function cannot fetch is -/// the plan's pulled variant, `MTLAttributeStrideStatic`'s (`u32::MAX`) among them, which the -/// pulled fetch reads as element 0 and zeros past it, as an M4 read them. -#[test] -fn inline_vertex_bytes_bind_the_strides_a_dynamic_layout_reads() { - let mut template = GraphicsTemplate { - buffers: Vec::new(), - stages: Vec::new(), - vertex_buffers: vertex_buffers(), - pulled_strides: Vec::new(), - resources: ResourceTemplate::default(), - vertex_strides: rules(None, true), - multiview_instance_limit: None, - other_layer_variant: false, - amplifications: Vec::new(), - tessellation: None, - indirect_first_instance_missing: false, - mesh: None, - deindexed: None, - private_list: false, - line_band: None, - }; - let state = |attribute_stride| { - let mut t = StageTable::default(); - t.buffers.insert( - 1, - BoundBuffer::Bytes { - len: 256, - attribute_stride: None, - }, - ); - t.buffers.insert( - 2, - BoundBuffer::Bytes { - len: 256, - attribute_stride, - }, - ); - let mut s = BindState::default(); - s.stages.insert(Stage::Vertex, t); - s - }; - let draw = primitives(2, 3, (1, 5)); - for (stride, read) in [(None, 0), (Some(0), 0), (Some(8), 8), (Some(16), 16)] { - let cmds = instantiate(&template, &state(stride), &draw).expect("draw"); - assert_eq!(cmds.buffer_offsets, vec![(0, 0), (1, 0)], "{stride:?}"); - // Dynamic strides list every binding's, the static one included (`pStrides`). - assert_eq!(cmds.vertex_strides, vec![(0, 24), (1, read)], "{stride:?}"); - } - // A stride fixed function cannot fetch (past the attributes' alignment, below the bytes an - // element reads, or past `maxVertexInputBindingStride`) is the plan's pulled variant: a draw of - // this plan with it is an internal error. - let pulled = |r: Result| matches!(r, Err(BindError::Internal(_))); - assert!(pulled(instantiate( - &template, - &state(Some(u32::MAX)), - &draw - ))); - assert!(pulled(instantiate(&template, &state(Some(7)), &draw))); - assert!(pulled(instantiate(&template, &state(Some(6)), &draw))); - template.vertex_strides = rules(None, false); - let cmds = instantiate(&template, &state(Some(6)), &draw).expect("static strides"); - assert_eq!( - cmds.vertex_strides, - vec![(1, 6)], - "only the per-bind stride" - ); -} - -fn factor_template(step: metal::TessellationFactorStepFunction, bound: bool) -> FactorTemplate { - FactorTemplate { - step, - patch_bytes: 12, - alignment: 16, - max_range: 1 << 20, - control_points: 4, - patch_indices: (0, 4), - control_point_indices: None, - push_offset: 20, - factor_binding: bound.then_some((0, 3)), - } -} - -fn patches( - patch_start: u32, - patch_count: u32, - instance_count: u32, - base_instance: u32, -) -> DrawCall { - DrawCall::Patches { - control_points: 4, - patch_start, - patch_count, - patch_index: None, - instance_count, - base_instance, - control_point_index: None, - } -} - -fn factor_state(offset: u64, instance_stride: u64, scale: f32) -> BindState { - BindState { - tessellation_factors: crate::bind::state::TessellationFactors::new( - Some(crate::bind::state::TessellationFactorBuffer::new( - 4096, - offset, - instance_stride, - )), - scale, - ), - ..BindState::default() - } -} - -/// A patch draw is one vertex per patch from the patch start, with the draw's instances; its -/// indirect form reads `MTLDrawPatchIndirectArguments` as a `VkDrawIndirectCommand`. -#[test] -fn patch_draws_draw_one_vertex_per_patch() { - let (d, base) = vk_draw(&patches(5, 9, 3, 2), None); - assert_eq!( - d, - vk::DrawCommand::Draw { - vertex_count: 9, - instance_count: 3, - first_vertex: 5, - first_instance: 2 - } - ); - assert_eq!(base, [5, 2]); - let indirect = DrawCall::PatchesIndirect { - control_points: 4, - patch_index: None, - indirect: IndirectRef { - token: 1, - offset: 48, - }, - control_point_index: None, - }; - assert_eq!( - vk_draw(&indirect, None).0, - vk::DrawCommand::DrawIndirect { - offset: 48, - draw_count: 1, - stride: 16 - } - ); - assert_eq!(draw_uses(&patches(0, 1, 1, 0), None, None), Vec::new()); - assert_eq!(draw_uses(&indirect, None, None).len(), 1); -} - -/// A patch draw's patch index buffer: bound over the indices of the draw's patches (an indirect -/// draw's from its offset to the buffer's end), its residual offset and 1 pushed after the factors' -/// words, and read by the control stage; an offset that is not a multiple of 4 is refused, as -/// Metal's validation refuses it. -#[test] -fn patch_draws_bind_their_patch_index_buffers() { - use metal::TessellationFactorStepFunction as S; - let t = factor_template(S::PerPatch, false); - let indexed = |offset| DrawCall::Patches { - control_points: 4, - patch_start: 5, - patch_count: 3, - patch_index: Some((IndexBufferRef::new(2, 4096), offset)), - instance_count: 1, - base_instance: 0, - control_point_index: None, - }; - let (push, ranges) = patch_draw(Some(&t), &BindState::default(), &indexed(36)) - .expect("draw") - .expect("a patch draw"); - // Indices at bytes [36 + 20, 36 + 32) of the buffer: bound from 48 (16-aligned) to 80. - let [range] = ranges[..] else { - panic!("{ranges:?}: one bound patch index buffer") - }; - assert_eq!((range.set, range.binding), (0, 4)); - assert_eq!((range.range.offset, range.range.range), (48, 32)); - let word = |k: usize| u32::from_le_bytes(push.bytes[4 * k..4 * k + 4].try_into().unwrap()); - assert_eq!(push.bytes.len(), 24); - assert_eq!((word(3), word(4)), (36u32.wrapping_sub(48), 1)); - assert_eq!( - draw_uses(&indexed(36), None, Some(&t)), - [ResourceUse { - resource: UseTarget::PatchIndices, - access: AccessSet::READ, - class: AccessClass::Storage, - stages: vk::PipelineStageFlags2::TESSELLATION_CONTROL_SHADER, - range: Some(ByteRange { - offset: 20, - len: 12 - }), - }] - ); - let indirect = DrawCall::PatchesIndirect { - control_points: 4, - patch_index: Some((IndexBufferRef::new(2, 100), 40)), - indirect: IndirectRef { - token: 1, - offset: 0, - }, - control_point_index: None, - }; - let (push, ranges) = patch_draw(Some(&t), &BindState::default(), &indirect) - .expect("draw") - .expect("a patch draw"); - let [range] = ranges[..] else { - panic!("{ranges:?}: one bound patch index buffer") - }; - // From 32 (the offset aligned down) to the padded end, 112. - assert_eq!((range.range.offset, range.range.range), (32, 80)); - assert_eq!(push.bytes[12..], [8, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0]); - let uses = draw_uses(&indirect, None, Some(&t)); - assert_eq!(uses.len(), 2); - assert_eq!( - (uses[0].resource, uses[0].range), - (UseTarget::PatchIndices, None) - ); - assert_eq!( - patch_draw(Some(&t), &BindState::default(), &indexed(2)), - Err(BindError::InvalidPatchIndexBuffer { offset: 2 }) - ); -} - -/// A pipeline with a control-point index type draws indexed patches only, one without it plain -/// ones only, as Metal's validation requires. An indexed draw binds its control-point index buffer -/// over the indices of its patches' control points when it has no patch index buffer (from the -/// offset to the buffer's end otherwise, and for an indirect draw), pushes its residual offset -/// after the patch index words, and is read by the control stage; an offset that is not a multiple -/// of the index size is refused, as Metal's validation refuses it. -#[test] -fn indexed_patch_draws_bind_their_control_point_index_buffers() { - use metal::TessellationFactorStepFunction as S; - let mut t = factor_template(S::PerPatch, false); - t.control_point_indices = Some(((0, 5), 2)); - let indexed = |offset, patch_index| DrawCall::Patches { - control_points: 4, - patch_start: 5, - patch_count: 3, - patch_index, - instance_count: 1, - base_instance: 0, - control_point_index: Some((IndexBufferRef::new(3, 4096), offset)), - }; - let (push, ranges) = patch_draw(Some(&t), &BindState::default(), &indexed(38, None)) - .expect("draw") - .expect("a patch draw"); - // Indices at bytes [38 + 40, 38 + 64) of the buffer: bound from 64 (16-aligned) to 112. - let [range] = ranges[..] else { - panic!("{ranges:?}: one bound control-point index buffer") - }; - assert_eq!((range.set, range.binding), (0, 5)); - assert_eq!((range.range.offset, range.range.range), (64, 48)); - let word = |k: usize| u32::from_le_bytes(push.bytes[4 * k..4 * k + 4].try_into().unwrap()); - assert_eq!(push.bytes.len(), 24); - assert_eq!((word(4), word(5)), (0, 38u32.wrapping_sub(64))); - assert_eq!( - draw_uses(&indexed(38, None), None, Some(&t)), - [ResourceUse { - resource: UseTarget::ControlPointIndices, - access: AccessSet::READ, - class: AccessClass::Storage, - stages: vk::PipelineStageFlags2::TESSELLATION_CONTROL_SHADER, - range: Some(ByteRange { - offset: 40, - len: 24 - }), - }] - ); - // With a patch index buffer, every index from the offset: from 32 to the padded end. - let with_patch_index = indexed(38, Some((IndexBufferRef::new(2, 4096), 0))); - let (_, ranges) = patch_draw(Some(&t), &BindState::default(), &with_patch_index) - .expect("draw") - .expect("a patch draw"); - assert_eq!(ranges.len(), 2); - assert_eq!((ranges[1].set, ranges[1].binding), (0, 5)); - assert_eq!( - (ranges[1].range.offset, ranges[1].range.range), - (32, 4096 - 32) - ); - let uses = draw_uses(&with_patch_index, None, Some(&t)); - assert_eq!( - uses.iter() - .map(|u| (u.resource, u.range)) - .collect::>(), - [ - ( - UseTarget::PatchIndices, - Some(ByteRange { - offset: 20, - len: 12 - }) - ), - (UseTarget::ControlPointIndices, None) - ] - ); - let indirect = DrawCall::PatchesIndirect { - control_points: 4, - patch_index: None, - indirect: IndirectRef { - token: 1, - offset: 0, - }, - control_point_index: Some((IndexBufferRef::new(3, 100), 6)), - }; - let (push, ranges) = patch_draw(Some(&t), &BindState::default(), &indirect) - .expect("draw") - .expect("a patch draw"); - assert_eq!((ranges[0].range.offset, ranges[0].range.range), (0, 112)); - assert_eq!(push.bytes[20..], [6, 0, 0, 0]); - let uses = draw_uses(&indirect, None, Some(&t)); - assert_eq!( - uses.iter().map(|u| u.resource).collect::>(), - [UseTarget::ControlPointIndices, UseTarget::Indirect] - ); - assert_eq!(uses[0].range, None); - assert_eq!( - patch_draw(Some(&t), &BindState::default(), &indexed(3, None)), - Err(BindError::InvalidControlPointIndexBuffer { offset: 3 }) - ); - // Indexing that differs from the pipeline's. - assert_eq!( - patch_draw(Some(&t), &BindState::default(), &patches(0, 1, 1, 0)), - Err(BindError::ControlPointIndexing { indexed: false }) - ); - let plain = factor_template(S::PerPatch, false); - assert_eq!( - patch_draw(Some(&plain), &BindState::default(), &indexed(0, None)), - Err(BindError::ControlPointIndexing { indexed: true }) - ); -} - -/// The factor window of each step function: the draw's patches, its instances (from the base -/// instance), both, or the one struct; empty without patches or instances; whole when indirect. -#[test] -fn each_step_function_reads_its_factor_window() { - use metal::TessellationFactorStepFunction as S; - let window = |step, draw: &DrawCall| factor_window(&factor_template(step, true), 64, draw); - let draw = patches(2, 3, 4, 1); - assert_eq!( - window(S::Constant, &draw), - Window::Bounded { start: 0, len: 12 } - ); - assert_eq!( - window(S::PerPatch, &draw), - Window::Bounded { start: 24, len: 36 } - ); - assert_eq!( - window(S::PerInstance, &draw), - Window::Bounded { - start: 64, - len: 3 * 64 + 12 - } - ); - assert_eq!( - window(S::PerPatchAndPerInstance, &draw), - Window::Bounded { - start: 24 + 64, - len: 2 * 12 + 3 * 64 + 12 - } - ); - assert_eq!( - window(S::PerPatch, &patches(2, 0, 4, 1)), - Window::Bounded { start: 0, len: 0 } - ); - let indirect = DrawCall::PatchesIndirect { - control_points: 4, - patch_index: None, - indirect: IndirectRef { - token: 1, - offset: 0, - }, - control_point_index: None, - }; - assert_eq!(window(S::PerPatch, &indirect), Window::Whole); -} - -/// A patch draw pushes the factor buffer's residual bind offset, its instance stride rounded down -/// to a multiple of 4, and the scale rounded to `half`, and binds the factors it reads; without a -/// buffer it pushes zeros over the zero buffer. Draws Metal does not make with the pipeline are -/// refused. -#[test] -fn patch_draws_push_and_bind_their_factors() { - use metal::TessellationFactorStepFunction as S; - let t = factor_template(S::PerPatch, true); - let (push, range) = patch_draw(Some(&t), &factor_state(40, 64, 1.3), &patches(2, 3, 1, 0)) - .expect("draw") - .expect("a patch draw"); - // Factors at bytes [40 + 24, 40 + 60) of the buffer: bound from 64 (16-aligned) to 112. - let [range] = range[..] else { - panic!("{range:?}: one bound factor buffer") - }; - assert_eq!((range.set, range.binding), (0, 3)); - assert_eq!((range.range.offset, range.range.range), (64, 48)); - let half = f16_bits_to_f32(f32_to_f16_bits(1.3)); - assert_ne!(half, 1.3); - let mut bytes = (40u32.wrapping_sub(64)).to_le_bytes().to_vec(); - bytes.extend_from_slice(&64u32.to_le_bytes()); - bytes.extend_from_slice(&half.to_bits().to_le_bytes()); - bytes.extend_from_slice(&[0; 12]); - assert_eq!( - push, - PushConstantWrite { - stages: vk::ShaderStageFlags::TESSELLATION_CONTROL, - offset: 20, - bytes, - } - ); - // An offset 2 past a multiple of 4, which the control stage reads from that byte: factors at - // bytes [42 + 24, 42 + 60) bound from 64 to 112, the residual 42 - 64. A stride 2 past a - // multiple of 4 steps the instances by the multiple below, as Metal does: 66 pushes 64. - let (push, range) = patch_draw(Some(&t), &factor_state(42, 66, 1.0), &patches(2, 3, 1, 0)) - .expect("draw") - .expect("a patch draw"); - let [range] = range[..] else { - panic!("{range:?}: one bound factor buffer") - }; - assert_eq!((range.range.offset, range.range.range), (64, 48)); - let mut bytes = (42u32.wrapping_sub(64)).to_le_bytes().to_vec(); - bytes.extend_from_slice(&64u32.to_le_bytes()); - bytes.extend_from_slice(&1f32.to_bits().to_le_bytes()); - bytes.extend_from_slice(&[0; 12]); - assert_eq!(push.bytes, bytes); - // Per instance, the rounded stride bounds the factors read: instances 1 and 2 at 40 + 64 and - // 40 + 128, [104, 180) bound from 96 to 192. - let per_instance = factor_template(S::PerInstance, true); - let (push, range) = patch_draw( - Some(&per_instance), - &factor_state(40, 66, 1.0), - &patches(0, 1, 2, 1), - ) - .expect("draw") - .expect("a patch draw"); - let [range] = range[..] else { - panic!("{range:?}: one bound factor buffer") - }; - assert_eq!((range.range.offset, range.range.range), (96, 96)); - assert_eq!(push.bytes[4..8], 64u32.to_le_bytes()); - // No buffer: zeros over the zero buffer. - let unbound = factor_template(S::PerPatch, false); - let (push, range) = patch_draw(Some(&unbound), &BindState::default(), &patches(0, 1, 1, 0)) - .expect("draw") - .expect("a patch draw"); - assert_eq!(range, []); - let mut bytes = vec![0; 8]; - bytes.extend_from_slice(&1f32.to_bits().to_le_bytes()); - bytes.extend_from_slice(&[0; 12]); - assert_eq!(push.bytes, bytes); - // A state whose shape is not the plan's. - assert!(matches!( - patch_draw( - Some(&unbound), - &factor_state(0, 0, 1.0), - &patches(0, 1, 1, 0) - ), - Err(BindError::Internal(_)) - )); - // Primitives with a tessellation pipeline, patches with any other. - let primitives = DrawCall::Primitives { - vertex_start: 0, - vertex_count: 3, - instance_count: 1, - base_instance: 0, - }; - assert_eq!( - patch_draw(Some(&t), &BindState::default(), &primitives), - Err(BindError::InvalidDrawKind { patches: false }) - ); - assert_eq!( - patch_draw(None, &BindState::default(), &patches(0, 1, 1, 0)), - Err(BindError::InvalidDrawKind { patches: true }) - ); - assert_eq!( - patch_draw(None, &BindState::default(), &primitives), - Ok(None) - ); - // Another control-point count, unaligned factors, too many factors. - let mut three = patches(0, 1, 1, 0); - if let DrawCall::Patches { control_points, .. } = &mut three { - *control_points = 3; - } - assert_eq!( - patch_draw(Some(&t), &factor_state(0, 0, 1.0), &three), - Err(BindError::PatchControlPoints { - given: 3, - expected: 4 - }) - ); - // An odd offset is read from the byte below, an odd stride rounded down to a multiple of 4, - // as plain Metal reads them (one of 2 past a multiple of 4 is read from that byte). - for step in [S::PerPatch, S::PerInstance] { - let t = factor_template(step, true); - for (offset, stride, read) in [ - (1, 0, (0, 0)), - (0, 3, (0, 0)), - (3, 6, (2, 4)), - (7, 15, (6, 12)), - ] { - assert_eq!( - patch_draw( - Some(&t), - &factor_state(offset, stride, 1.0), - &patches(0, 1, 2, 0) - ), - patch_draw( - Some(&t), - &factor_state(read.0, read.1, 1.0), - &patches(0, 1, 2, 0) - ), - "{step:?}: offset {offset}, stride {stride}" - ); - } - } - let mut large = factor_state(0, 0, 1.0); - if let Some(b) = &mut large.tessellation_factors.buffer { - b.length = 1 << 24; - } - assert!(matches!( - patch_draw(Some(&t), &large, &patches(0, 1 << 20, 1, 0)), - Err(BindError::TessellationFactorRange { limit, .. }) if limit == 1 << 20 - )); - // A scale that is not a positive `half` once rounded: 0, negative, or NaN (2^-25 is a tie, - // which rounds to 0, its even neighbour). - for scale in [ - 0.0, - -0.0, - -1.0, - f32::NAN, - f32::NEG_INFINITY, - 2f32.powi(-25), - 2f32.powi(-30), - -1e-5, - ] { - assert_eq!( - patch_draw(Some(&t), &factor_state(0, 0, scale), &patches(0, 1, 1, 0)), - Err(BindError::InvalidTessellationFactorScale { - bits: scale.to_bits() - }), - "{scale}" - ); - } - // Every positive `half` is pushed as rounded, subnormal ones included, and an infinite one as - // 2^32, which takes every positive factor past the maximum level. - for (scale, pushed) in [ - (2f32.powi(-24), 2f32.powi(-24)), - (1.5 * 2f32.powi(-25), 2f32.powi(-24)), - (1e-6, f32::from_bits(0x3588_0000)), - (f32::from_bits(0x3880_0000), f32::from_bits(0x3880_0000)), - (1.3, f32::from_bits(0x3fa6_6000)), - (2.0005, 2.0), - (65504.0, 65504.0), - (65520.0, 2f32.powi(32)), - (1e6, 2f32.powi(32)), - (f32::INFINITY, 2f32.powi(32)), - ] { - let (push, _) = patch_draw(Some(&t), &factor_state(0, 0, scale), &patches(0, 1, 1, 0)) - .unwrap_or_else(|e| panic!("{scale}: {e:?}")) - .expect("a patch draw"); - let word = u32::from_le_bytes(push.bytes[8..12].try_into().unwrap()); - assert_eq!(f32::from_bits(word), pushed, "{scale}"); - } -} - -/// A mesh template of the RADV 780M's mesh limits (256 threads a threadgroup, 65535 threadgroups -/// an axis, `2^22` in all), whose mesh stage reads its grid from a `DispatchRegion` at offset 0 -/// and whose fragment stage decides `Presence` of buffer 0. -fn mesh_template(flat: bool, multiples: Vec) -> GraphicsTemplate { - use crate::bind::plan::{GroupLimits, GroupStage, MeshTemplate}; - use crate::pipeline::artifact::SpecConstant; - use crate::pipeline::interface::PlacedField; - let spec = |id, key| SpecConstant { - id, - key, - size: 4, - default: 1, - unread_bits: 0, - }; - let fragment_buffer = SlotRef { - stage: Stage::Fragment, - class: SlotClass::Buffer, - index: 0, - }; - let mut layout = vec![ - spec(0, SpecKey::LocalSize(Axis::X)), - spec(1, SpecKey::LocalSize(Axis::Y)), - spec(2, SpecKey::LocalSize(Axis::Z)), - spec(3, SpecKey::MultiRegion), - spec(4, SpecKey::Presence(fragment_buffer)), - ]; - if flat { - layout.push(spec(5, SpecKey::FlatLocalSize)); - } - GraphicsTemplate { - buffers: Vec::new(), - stages: vec![StageTemplate { - stage: Stage::Mesh, - flags: vk::ShaderStageFlags::MESH_EXT, - fields: vec![PlacedField { - field: PushField::DispatchRegion, - loc: PushLoc::Push { offset: 0 }, - size: 32, - }], - push_range: Some((0, 32)), - table: None, - table_size: 0, - root_first: None, - }], - vertex_buffers: Vec::new(), - pulled_strides: Vec::new(), - resources: ResourceTemplate::default(), - vertex_strides: rules(None, false), - multiview_instance_limit: None, - other_layer_variant: false, - amplifications: Vec::new(), - tessellation: None, - indirect_first_instance_missing: false, - mesh: Some(MeshTemplate { - spec: layout, - fixed: vec![(SpecKey::Presence(fragment_buffer), 1)], - multiples, - mesh: GroupLimits { - size: [256; 3], - invocations: 256, - count: [65535; 3], - total: 1 << 22, - stage: GroupStage::Mesh, - }, - object: None, - folded: false, - partial_groups: false, - }), - deindexed: None, - private_list: false, - line_band: None, - } -} - -/// [`mesh_template`]'s pipeline with an object function, of RADV's task limits (128 threads a -/// threadgroup): its object stage reads its grid from a `DispatchRegion` at offset 0 under its -/// own keys (constants 5 to 8), its mesh stage from one at 32. -fn object_template() -> GraphicsTemplate { - use crate::bind::plan::GroupLimits; - use crate::pipeline::artifact::SpecConstant; - use crate::pipeline::interface::PlacedField; - let mut t = mesh_template(false, Vec::new()); - let region = |offset| { - vec![PlacedField { - field: PushField::DispatchRegion, - loc: PushLoc::Push { offset }, - size: 32, - }] - }; - t.stages[0].fields = region(32); - t.stages[0].push_range = Some((32, 32)); - t.stages.insert( - 0, - StageTemplate { - stage: Stage::Object, - flags: vk::ShaderStageFlags::TASK_EXT, - fields: region(0), - push_range: Some((0, 32)), - table: None, - table_size: 0, - root_first: None, - }, - ); - let m = t.mesh.as_mut().expect("a mesh template"); - for (id, key) in [ - (5, SpecKey::ObjectLocalSize(Axis::X)), - (6, SpecKey::ObjectLocalSize(Axis::Y)), - (7, SpecKey::ObjectLocalSize(Axis::Z)), - (8, SpecKey::ObjectMultiRegion), - ] { - m.spec.push(SpecConstant { - id, - key, - size: 4, - default: 1, - unread_bits: 0, - }); - } - m.object = Some(GroupLimits { - size: [128; 3], - invocations: 128, - count: [65535; 3], - total: 1 << 22, - stage: crate::bind::plan::GroupStage::Task, - }); - t -} - -/// A draw of a pipeline with an object function launches object threadgroups, made with each -/// stage's threadgroup size under its own keys and writing each stage's `DispatchRegion` (the -/// object stage's grid; the mesh stage's grid is the object function's to set); a `drawMeshThreads` -/// whose threads fill whole object threadgroups launches them, and one that leaves a partial object -/// threadgroup launches the threadgroups its threads fill, rounded up, under `MultiRegion` 1 with -/// Metal's threads and the region flagged `NONUNIFORM`, where the object function runs partial -/// threadgroups (`RuntimeFact::PartialObjectThreadgroups`), and is not implemented where it does -/// not; an object threadgroup Metal draws nothing for launches nothing; -/// and each stage's threadgroup, and the object grid, are checked against the device's limits for -/// its stage. -#[test] -fn object_draws_specialize_each_stage_within_its_limits() { - let state = BindState::default(); - let t = object_template(); - let groups = |groups, lo, lm| DrawCall::MeshThreadgroups { - groups, - threads_per_object_group: lo, - threads_per_mesh_group: lm, - }; - let threads = |threads, lo| DrawCall::MeshThreads { - threads, - threads_per_object_group: lo, - threads_per_mesh_group: [2, 1, 1], - }; - let tasks = |x, y, z| vk::DrawCommand::DrawMeshTasks { - group_count_x: x, - group_count_y: y, - group_count_z: z, - }; - let values = |key: &SpecializationKey| -> Vec<(u32, u32)> { - key.entries - .iter() - .map(|e| { - let at = e.offset as usize; - let bytes = key.data[at..at + 4].try_into().expect("4 bytes"); - (e.constant_id, u32::from_le_bytes(bytes)) - }) - .collect() - }; - let cmds = instantiate(&t, &state, &groups([3, 1, 1], [4, 2, 1], [2, 1, 1])).expect("groups"); - assert_eq!(cmds.draw, tasks(3, 1, 1)); - assert_eq!( - values(cmds.specialization.as_ref().expect("a mesh draw's key")), - [ - (0, 2), - (1, 1), - (2, 1), - (3, 0), - (4, 1), - (5, 4), - (6, 2), - (7, 1), - (8, 0) - ] - ); - let region = |grid, l| region_bytes([0; 3], grid, l).expect("region").to_vec(); - assert_eq!( - cmds.push_constants, - [ - PushConstantWrite { - stages: vk::ShaderStageFlags::TASK_EXT, - offset: 0, - bytes: region([12, 2, 1], [4, 2, 1]), - }, - PushConstantWrite { - stages: vk::ShaderStageFlags::MESH_EXT, - offset: 32, - bytes: region([0; 3], [2, 1, 1]), - }, - ] - ); - // `drawMeshThreads` of whole object threadgroups: `MultiRegion` 0, the region unflagged. - let cmds = instantiate(&t, &state, &threads([8, 4, 1], [4, 2, 1])).expect("whole"); - assert_eq!(cmds.draw, tasks(2, 2, 1)); - let multi_region = |c: &DrawCommands| { - values(c.specialization.as_ref().expect("a mesh draw's key")) - .into_iter() - .find(|&(id, _)| id == 8) - .map(|(_, v)| v) - }; - assert_eq!(multi_region(&cmds), Some(0)); - assert_eq!(cmds.push_constants[0].bytes, region([8, 4, 1], [4, 2, 1])); - // One that leaves a partial object threadgroup, where the object function runs one: the - // threadgroups the threads fill, rounded up, Metal's threads, the region flagged. - let mut partial_template = t.clone(); - if let Some(m) = partial_template.mesh.as_mut() { - m.partial_groups = true; - } - for (draw, groups, grid, lo) in [ - ( - threads([6, 1, 1], [4, 1, 1]), - [2, 1, 1], - [6, 1, 1], - [4, 1, 1], - ), - ( - threads([5, 3, 1], [4, 2, 1]), - [2, 2, 1], - [5, 3, 1], - [4, 2, 1], - ), - ] { - let cmds = instantiate(&partial_template, &state, &draw).expect("a partial draw"); - assert_eq!( - cmds.draw, - tasks(groups[0], groups[1], groups[2]), - "{draw:?}" - ); - assert_eq!(multi_region(&cmds), Some(1), "{draw:?}"); - let flagged = crate::lower::dispatch::partial_region_bytes(grid, lo).expect("region"); - assert_eq!(cmds.push_constants[0].bytes, flagged.to_vec(), "{draw:?}"); - assert_eq!( - &flagged[28..], - &crate::lower::dispatch::NONUNIFORM.to_le_bytes(), - "{draw:?}" - ); - // Where it does not (a body that holds a workgroup barrier): not implemented. - assert_eq!( - instantiate(&t, &state, &draw).err(), - Some(not_implemented(Feature::MeshShading)), - "{draw:?}" - ); - } - // A partial draw with an axis of no thread draws nothing, as Metal does, either way. - for template in [&t, &partial_template] { - let cmds = instantiate(template, &state, &threads([6, 0, 1], [4, 1, 1])).expect("nothing"); - assert_eq!(cmds.draw, tasks(0, 0, 0)); - } - // Metal draws nothing: an object threadgroup of no thread or past 1024, as a mesh one. - for draw in [ - groups([3, 1, 1], [0, 1, 1], [2, 1, 1]), - groups([3, 1, 1], [1025, 1, 1], [2, 1, 1]), - groups([3, 1, 1], [4, 1, 1], [0, 1, 1]), - threads([8, 1, 1], [0, 1, 1]), - ] { - let cmds = instantiate(&t, &state, &draw).expect("nothing"); - assert_eq!(cmds.draw, tasks(0, 0, 0), "{draw:?}"); - } - let limit = |limit, required, available| { - Some(BindError::Unsupported(Unsupported::needs( - Feature::MeshShading, - Capability::Limit { - limit, - required, - available, - }, - ))) - }; - for (draw, refusal) in [ - ( - groups([1; 3], [256, 1, 1], [1; 3]), - limit(VkLimit::MaxTaskWorkGroupSize(0), 256, 128), - ), - ( - groups([1; 3], [16, 16, 1], [1; 3]), - limit(VkLimit::MaxTaskWorkGroupInvocations, 256, 128), - ), - ( - groups([1; 3], [1; 3], [512, 1, 1]), - limit(VkLimit::MaxMeshWorkGroupSize(0), 512, 256), - ), - ( - groups([1, 1, 65536], [1; 3], [1; 3]), - limit(VkLimit::MaxTaskWorkGroupCount(2), 65536, 65535), - ), - ( - groups([2048, 2049, 1], [1; 3], [1; 3]), - limit(VkLimit::MaxTaskWorkGroupTotalCount, 2048 * 2049, 1 << 22), - ), - ] { - assert_eq!(instantiate(&t, &state, &draw).err(), refusal, "{draw:?}"); - } - // Past what Metal runs: nothing drawn, and the command buffer discarded, ahead of the task - // limits. - for counts in [[(1 << 29) + 1, 1, 1], [65535, 65535, 1]] { - let cmds = instantiate(&t, &state, &groups(counts, [1; 3], [2, 1, 1])).expect("discarded"); - assert_eq!(cmds.draw, tasks(0, 0, 0), "{counts:?}"); - assert!(cmds.discards_command_buffer, "{counts:?}"); - } - // Threads per grid wrapped to 32 bits: the threadgroups they fill, rounded up (Metal's), none - // where they wrap to 0, held to the task limits; the region reports them, read (`MultiRegion` - // 1) where they leave a partial threadgroup. - for (counts, lo, runs, reported, multi_region) in [ - ([33_554_433, 1, 1], [128, 1, 1], [1, 1, 1], [128, 1, 1], 0), - ([44_739_243, 1, 1], [96, 1, 1], [1, 1, 1], [32, 1, 1], 1), - ([33_554_432, 1, 1], [128, 1, 1], [0, 0, 0], [0, 1, 1], 0), - ] { - let cmds = instantiate(&t, &state, &groups(counts, lo, [2, 1, 1])).expect("wraps"); - let [x, y, z] = runs; - assert_eq!(cmds.draw, tasks(x, y, z), "{counts:?}"); - if runs[0] == 0 { - continue; - } - let key = cmds.specialization.as_ref().expect("a mesh draw's key"); - assert!(values(key).contains(&(8, multi_region)), "{counts:?}"); - assert_eq!( - cmds.push_constants[0].bytes, - region(reported, lo), - "{counts:?}" - ); - } - // Indirect: its object threadgroups' counts, through the object form of the arguments pass; - // an object threadgroup Metal draws nothing for reads none. - let indirect = |lo| DrawCall::MeshThreadgroupsIndirect { - indirect: IndirectRef { - token: 1, - offset: 12, - }, - threads_per_object_group: lo, - threads_per_mesh_group: [32, 1, 1], - }; - let cmds = instantiate(&t, &state, &indirect([4, 1, 1])).expect("indirect"); - assert!(matches!( - cmds.draw, - vk::DrawCommand::DrawMeshTasksIndirect { offset: 12, .. } - )); - assert!(!cmds.indirect_needs_arguments && cmds.uses.len() == 1); - assert_eq!(cmds.mesh_arguments, Some(MeshArgumentsForm::Object)); - let cmds = instantiate(&t, &state, &indirect([0, 1, 1])).expect("indirect nothing"); - assert_eq!(cmds.draw, tasks(0, 0, 0)); - assert!(cmds.uses.is_empty() && cmds.mesh_arguments.is_none()); -} - -/// A folded object function's draws (`MeshTemplate::folded`): a direct draw runs its object grid -/// in the pieces of its fold within the task limits, as `vkCmdDrawMeshTasksEXT` of its one piece or -/// `vkCmdDrawMeshTasksIndirectEXT` of its pieces' uploaded commands, its object stage reading the -/// fold's record at its `ReplayRegionAddress` hole and every grid builtin from it (`MultiRegion` -/// 1); a grid past what runs draws nothing and says so; threads per grid wrap as Metal's; and an -/// indirect draw is `vkCmdDrawMeshTasksIndirectCountEXT` of the folded arguments pass's pieces. -#[test] -fn folded_object_draws_run_their_grid_in_pieces() { - use crate::bind::mesh_arguments::{fold_object_grid, MeshArguments, MeshGridLimits}; - use crate::pipeline::interface::PlacedField; - let state = BindState::default(); - let mut t = object_template(); - t.stages[0].fields = vec![PlacedField { - field: PushField::ReplayRegionAddress, - loc: PushLoc::Push { offset: 0 }, - size: 8, - }]; - t.stages[0].push_range = Some((0, 8)); - t.mesh.as_mut().expect("a mesh template").folded = true; - let task = MeshGridLimits { - axes: [65535; 3], - total: 1 << 22, - }; - let groups = |groups, lo| DrawCall::MeshThreadgroups { - groups, - threads_per_object_group: lo, - threads_per_mesh_group: [2, 1, 1], - }; - let tasks = |[x, y, z]: [u32; 3]| vk::DrawCommand::DrawMeshTasks { - group_count_x: x, - group_count_y: y, - group_count_z: z, - }; - let hole = PushHole::ReplayRegionAddress { - stages: vk::ShaderStageFlags::TASK_EXT, - offset: 0, - }; - // One piece, a grid past the task stage's axis among them: no refusal. - for (counts, lo, dispatch) in [ - ([3, 1, 1], [4, 2, 1], [3, 1, 1]), - ([1, 1, 65536], [1; 3], [65535, 2, 1]), - ([131_070, 2, 1], [1; 3], [65535, 4, 1]), - ] { - let cmds = instantiate(&t, &state, &groups(counts, lo)).expect("one piece"); - let fold = fold_object_grid(counts, lo, task, true).expect("fold"); - assert_eq!(fold.dispatch, dispatch, "{counts:?}"); - assert_eq!(cmds.draw, tasks(dispatch), "{counts:?}"); - assert_eq!(cmds.object_fold, Some(fold), "{counts:?}"); - assert!(cmds.push_holes.contains(&hole), "{counts:?}"); - assert!( - cmds.mesh_arguments.is_none() && cmds.uses.is_empty(), - "{counts:?}" - ); - let key = cmds.specialization.as_ref().expect("a mesh draw's key"); - let multi_region = key.entries.iter().find(|e| e.constant_id == 8).map(|e| { - let at = e.offset as usize; - u32::from_le_bytes(key.data[at..at + 4].try_into().expect("4 bytes")) - }); - assert_eq!(multi_region, Some(1), "{counts:?}"); - } - // Pieces: the uploaded commands, at their offset in the upload. - let cmds = instantiate(&t, &state, &groups([70_000, 100, 1], [1; 3])).expect("pieces"); - assert_eq!( - cmds.draw, - vk::DrawCommand::DrawMeshTasksIndirect { - offset: u64::from(MeshArguments::OBJECT_COMMANDS), - draw_count: 2, - stride: 12, - } - ); - let fold = cmds.object_fold.expect("a fold"); - assert_eq!( - (fold.dispatch, fold.pieces, fold.past), - ([65535, 64, 1], 2, false) - ); - assert!(cmds.mesh_arguments.is_none()); - // 2^29 threadgroups run, in 129 pieces of these limits; more, which Metal's GPU discards, - // draw nothing and discard the command buffer. - let cmds = instantiate(&t, &state, &groups([1 << 29, 1, 1], [1; 3])).expect("2^29"); - let fold = cmds.object_fold.expect("a fold"); - assert_eq!((fold.pieces, fold.discarded), (129, false)); - assert!(!cmds.discards_command_buffer); - for counts in [[65535, 65535, 1], [(1 << 29) + 1, 1, 1]] { - let cmds = instantiate(&t, &state, &groups(counts, [1; 3])).expect("discarded"); - assert_eq!(cmds.draw, tasks([0; 3]), "{counts:?}"); - assert!( - cmds.object_fold.is_some_and(|f| f.discarded && !f.past), - "{counts:?}" - ); - assert!(cmds.discards_command_buffer, "{counts:?}"); - } - // Threads per grid wrapped to 32 bits: a direct draw runs the threadgroups they fill, rounded - // up (Metal's), none where they wrap to 0, and the record reports them. - let cmds = instantiate(&t, &state, &groups([33_554_433, 1, 1], [128, 1, 1])).expect("wraps"); - assert_eq!(cmds.draw, tasks([1, 1, 1])); - let fold = cmds.object_fold.expect("a fold"); - assert_eq!(fold.record[..3], [1, 1, 1]); - assert_eq!(fold.record[4..7], [128, 1, 1]); - // Nothing Metal draws: no fold past anything. - for (counts, lo) in [([3, 0, 1], [4, 1, 1]), ([1 << 26, 1, 1], [128, 1, 1])] { - let cmds = instantiate(&t, &state, &groups(counts, lo)).expect("nothing"); - assert_eq!(cmds.draw, tasks([0; 3]), "{counts:?}"); - assert!( - cmds.object_fold.is_some_and(|f| !f.past && f.pieces == 0), - "{counts:?}" - ); - } - // Indirect: the folded arguments pass's pieces. - let indirect = DrawCall::MeshThreadgroupsIndirect { - indirect: IndirectRef { - token: 1, - offset: 12, - }, - threads_per_object_group: [4, 1, 1], - threads_per_mesh_group: [32, 1, 1], - }; - let cmds = instantiate(&t, &state, &indirect).expect("indirect"); - assert_eq!( - cmds.draw, - vk::DrawCommand::DrawMeshTasksIndirectCount { - offset: u64::from(MeshArguments::OBJECT_COMMANDS), - count_offset: u64::from(MeshArguments::OBJECT_COUNT), - max_draw_count: MeshArguments::OBJECT_PIECES, - stride: 12, - } - ); - assert_eq!(cmds.mesh_arguments, Some(MeshArgumentsForm::FoldedObject)); - assert!(cmds.object_fold.is_none() && cmds.push_holes.contains(&hole)); - assert!(!cmds.indirect_needs_arguments && cmds.uses.len() == 1); -} - -/// A mesh draw is `vkCmdDrawMeshTasksEXT` of its threadgroups, made with its threadgroup's size as -/// its specialization (`MultiRegion` 0 beside the plan's constants) and writing its grid in -/// `DispatchRegion`; `drawMeshThreads` launches the whole threadgroups its threads fill, and writes -/// their threads as its grid where the threads leave a partial threadgroup (Metal's builtins report -/// them, a probe); what Metal draws nothing for launches nothing, a grid with an axis past 65,535 -/// or of more than 1,048,575 threadgroups among it; the device's mesh limits refuse typed; an -/// indirect draw's arguments pass reads 12 bytes of arguments in the compute stage; and a mesh -/// draw of any other pipeline, or another draw of a mesh pipeline, is `InvalidMeshDraw`. -#[test] -fn mesh_draws_specialize_their_threadgroup_within_the_device() { - let state = BindState::default(); - let t = mesh_template(false, Vec::new()); - let mesh = |groups, l| DrawCall::MeshThreadgroups { - groups, - threads_per_object_group: [1; 3], - threads_per_mesh_group: l, - }; - let threads = |threads, l| DrawCall::MeshThreads { - threads, - threads_per_object_group: [1; 3], - threads_per_mesh_group: l, - }; - let tasks = |x, y, z| vk::DrawCommand::DrawMeshTasks { - group_count_x: x, - group_count_y: y, - group_count_z: z, - }; - // `(constant id, value)` of a key. - let values = |key: &SpecializationKey| -> Vec<(u32, u32)> { - key.entries - .iter() - .map(|e| { - let at = e.offset as usize; - let bytes = key.data[at..at + 4].try_into().expect("4 bytes"); - (e.constant_id, u32::from_le_bytes(bytes)) - }) - .collect() - }; - let cmds = instantiate(&t, &state, &mesh([3, 2, 1], [4, 2, 1])).expect("threadgroups"); - assert_eq!(cmds.draw, tasks(3, 2, 1)); - assert_eq!( - values(cmds.specialization.as_ref().expect("a mesh draw's key")), - [(0, 4), (1, 2), (2, 1), (3, 0), (4, 1)] - ); - assert_eq!( - cmds.push_constants, - [PushConstantWrite { - stages: vk::ShaderStageFlags::MESH_EXT, - offset: 0, - bytes: region_bytes([0; 3], [12, 4, 1], [4, 2, 1]) - .expect("region") - .to_vec(), - }] - ); - assert!(cmds.uses.is_empty() && !cmds.indirect_needs_arguments); - // `drawMeshThreads`: floor(t / m) threadgroups (20 by 16: one), whose threads are the grid, - // whether or not the function reads it (10 by 3 in 4 by 2: an 8 by 2 grid, a probe). - let mut grid_free = mesh_template(false, Vec::new()); - if let Some(m) = grid_free.mesh.as_mut() { - m.spec.retain(|c| c.key != SpecKey::MultiRegion); - } - let cmds = instantiate(&grid_free, &state, &threads([20, 1, 1], [16, 1, 1])).expect("threads"); - assert_eq!(cmds.draw, tasks(1, 1, 1)); - let cmds = instantiate(&t, &state, &threads([32, 4, 1], [16, 2, 1])).expect("whole"); - assert_eq!(cmds.draw, tasks(2, 2, 1)); - let cmds = instantiate(&t, &state, &threads([10, 3, 1], [4, 2, 1])).expect("partial"); - assert_eq!(cmds.draw, tasks(2, 1, 1)); - assert_eq!( - cmds.push_constants[0].bytes, - region_bytes([0; 3], [8, 2, 1], [4, 2, 1]) - .expect("region") - .to_vec() - ); - // Metal draws nothing: no thread, past 1024 threads, no threadgroup, a grid past Metal's - // (`bind::mesh_arguments`). Past the device's 256 threads but within Metal's 1024 is the - // device's limit. - for (draw, what) in [ - (mesh([3, 1, 1], [0, 1, 1]), "no thread"), - (mesh([3, 1, 1], [1025, 1, 1]), "past 1024"), - (mesh([3, 0, 1], [512, 1, 1]), "no threadgroup"), - (threads([15, 1, 1], [16, 1, 1]), "no whole threadgroup"), - (mesh([1, 65536, 1], [1; 3]), "65,536 along y"), - (mesh([65535, 65535, 1], [1; 3]), "past Metal's total"), - ] { - let cmds = instantiate(&t, &state, &draw).expect(what); - let vk::DrawCommand::DrawMeshTasks { - group_count_x, - group_count_y, - group_count_z, - } = cmds.draw - else { - panic!("{what}: {:?}", cmds.draw); - }; - assert!( - [group_count_x, group_count_y, group_count_z].contains(&0), - "{what}: {:?}", - cmds.draw - ); - assert!(cmds.specialization.is_some(), "{what}"); - } - let limit = |limit, required, available| { - Some(BindError::Unsupported(Unsupported::needs( - Feature::MeshShading, - Capability::Limit { - limit, - required, - available, - }, - ))) - }; - for (draw, refusal) in [ - ( - mesh([1; 3], [512, 1, 1]), - limit(VkLimit::MaxMeshWorkGroupSize(0), 512, 256), - ), - ( - mesh([1; 3], [1, 1, 300]), - limit(VkLimit::MaxMeshWorkGroupSize(2), 300, 256), - ), - ( - mesh([1; 3], [16, 32, 1]), - limit(VkLimit::MaxMeshWorkGroupInvocations, 512, 256), - ), - ] { - assert_eq!(instantiate(&t, &state, &draw).err(), refusal, "{draw:?}"); - } - // A flattened stage: its threads as one axis, whole subgroups of its tier only. - let flat = mesh_template(true, vec![32]); - let cmds = instantiate(&flat, &state, &mesh([1; 3], [8, 8, 1])).expect("flat"); - assert!(values(cmds.specialization.as_ref().expect("key")).contains(&(5, 64))); - assert_eq!( - instantiate(&flat, &state, &mesh([1; 3], [16, 17, 1])).err(), - limit(VkLimit::MaxMeshWorkGroupSize(0), 272, 256) - ); - assert_eq!( - instantiate(&flat, &state, &mesh([1; 3], [6, 1, 1])).err(), - Some(not_implemented(Feature::MeshShading)) - ); - // A draw that launches nothing takes a threadgroup the stage can be made with. - let cmds = instantiate(&flat, &state, &mesh([1; 3], [0, 1, 1])).expect("nothing"); - assert!(values(cmds.specialization.as_ref().expect("key")).contains(&(5, 32))); - // A grid Metal draws nothing for launches nothing, past the device's limits too. - for groups in [[65536, 1, 1], [1024, 1024, 1], [1, 1, 70000]] { - let cmds = instantiate(&t, &state, &mesh(groups, [32, 1, 1])).expect("nothing"); - assert_eq!(cmds.draw, tasks(0, 0, 0), "{groups:?}"); - } - // Indirect: 12 bytes of arguments, read by the mesh form of the arguments pass; at an offset - // that is not a multiple of 4, nothing. - let indirect = |offset| DrawCall::MeshThreadgroupsIndirect { - indirect: IndirectRef { token: 1, offset }, - threads_per_object_group: [1; 3], - threads_per_mesh_group: [32, 1, 1], - }; - let cmds = instantiate(&t, &state, &indirect(12)).expect("indirect"); - assert_eq!( - cmds.draw, - vk::DrawCommand::DrawMeshTasksIndirect { - offset: 12, - draw_count: 1, - stride: 12, - } - ); - assert!(!cmds.indirect_needs_arguments); - assert_eq!(cmds.mesh_arguments, Some(MeshArgumentsForm::Mesh)); - assert_eq!( - cmds.uses, - [ResourceUse { - resource: UseTarget::Indirect, - access: AccessSet::READ, - class: AccessClass::Storage, - stages: vk::PipelineStageFlags2::COMPUTE_SHADER, - range: Some(ByteRange { offset: 0, len: 12 }), - }] - ); - let cmds = instantiate(&t, &state, &indirect(2)).expect("misaligned"); - assert_eq!(cmds.draw, tasks(0, 0, 0)); - assert!(cmds.uses.is_empty() && cmds.mesh_arguments.is_none()); - // A draw of primitives with a mesh pipeline, and a mesh draw with another. - assert_eq!( - instantiate(&t, &state, &primitives(0, 3, (0, 1))).err(), - Some(BindError::InvalidMeshDraw { mesh: false }) - ); - let mut other = mesh_template(false, Vec::new()); - other.mesh = None; - other.stages.clear(); - assert_eq!( - instantiate(&other, &state, &mesh([1; 3], [1; 3])).err(), - Some(BindError::InvalidMeshDraw { mesh: true }) - ); - assert_eq!( - instantiate(&other, &state, &primitives(0, 3, (0, 1))).map(|c| c.specialization), - Ok(None) - ); -} diff --git a/crates/metal2vulkan/src/bind/heap.rs b/crates/metal2vulkan/src/bind/heap.rs index 75178e87a..8378525c5 100644 --- a/crates/metal2vulkan/src/bind/heap.rs +++ b/crates/metal2vulkan/src/bind/heap.rs @@ -1,220 +1,59 @@ -//! The set-1 descriptor heap and the handle table. +//! The set-1 heap's classes, as the lowering reads them. //! //! The heap arrays on a profile are of the image classes the core can declare and the four //! sampler classes. The texture lowering declares the handle table (`Synthetic(HandleTable)`, one //! per stage that loads a heap texture) and one heap array per class a heap texture reaches, and -//! link numbers them (set 1 for the arrays). The binder's half: +//! link numbers them (set 1 for the arrays). The consumer writes the arrays and the tables; this +//! module holds what the lowering decides from a class: //! -//! - **Members.** The textures a handle can name: every used image texture -//! (`BindShape.used`, by consumer token) and every image texture bound at a slot of a stage -//! with a handle table. A used texture reaches the stages its render stages name (compute: -//! the kernel), a bound one its own stage; a member reaching no stage with a table is left out. -//! Used textures come first, by token, then bound ones by slot; member `i` is element `i + 1` -//! of **every** class array, so the table maps a resource id to one element. Element 0 -//! ([`NEUTRAL_ELEMENT`]) is each class's neutral, the value of the null handle and of every -//! missed id. Texture buffers are no members: only a heap set a consumer keeps for every -//! command holds them, each at its resource ID's element of the texel-buffer classes, so a -//! planned heap's handle naming one misses. -//! - **Elements.** Element `e` of the array of a class holds member `e - 1` when it fits the -//! class (`fit`: the Metal texture type's dimension, arrayedness, and multisampling, a -//! sample count above 1 exactly when multisampled, the numeric type, a depth format for a -//! depth-comparison class (as a compared slot takes), `ShaderRead` usage for a sampled class and +//! - [`fit`]: how a texture fits a class's array: the Metal texture type's dimension, +//! arrayedness, and multisampling, a sample count above 1 exactly when multisampled, the numeric +//! type, a depth format for a depth-comparison class, `ShaderRead` usage for a sampled class and //! `ShaderWrite` or Apple's private `BlockWritesOnly` for a storage one (Metal's validation takes -//! a write of either), which never holds a depth or stencil format), through its -//! view: a sampled one as a slot's (`plan::resources::sampled_view`), a storage one the direct -//! format (an `A8Unorm` texture held in red its `R8_UNORM` image, whose texels a heap access -//! converts where the handle carries `A8Unorm`'s class), or the alias of a storage choice a heap -//! access converts by ([`storage_conversions`]: an 8-bit sRGB texture's UNORM twin, a blue-first -//! texture's RGBA-order twin, converted where the handle carries the texture's class and red-blue -//! order), which the class's formatless declaration serves exactly when the format's storage -//! choice for every access the device lets a heap make (`heap_storage_use`) is `Identity` (or -//! `AlphaInRed`) without an alias, or such an alias, and the view's format serves those accesses -//! without a format -//! (`metal::format::without_format_gaps`: the device's features and the format's own -//! `VkFormatFeatureFlags2` bits). On a device that reads storage without a format by the -//! formats' own bits alone (`DeviceProfile::storage_reads_by_format_bits`: ANV before Gfx12.5), -//! the device lets a heap write alone, and a storage view whose format lacks the read bit -//! holds its member for its writes, flagged [`FLAG_STORAGE_UNREADABLE`] ([`storage_unreadable`]), -//! whose storage read reads the null element. Metal's contract defines a `read_write` read of its -//! read-write tier formats, so a function that reads a storage class through a handle is -//! refused where one of them would be so held ([`tier_read_gaps`]). A fitting member the heap cannot view (another storage choice, a format the profile cannot -//! sample or store) is `Unsupported`, as for a slot: a handle may name it. A storage class -//! holds a texture whose writes Metal drops -//! (`metal::format::writes_dropped`: the 4:2:2 formats, the subsampled and packed two-plane -//! YCbCr ones) as its neutral ([`Fit::Dropped`]), which the writes leave as Metal leaves the -//! texture; a stage that reads such a class (`RuntimeFact::HeapStorageReads`) refuses such a -//! texture it reaches there, `Unsupported { feature: Format, needs: NotImplemented }`, as a slot -//! that reads one is refused. A 4:4:4 two-plane YCbCr texture, whose writes Metal stores into -//! its planes, has no storage choice, and a storage class refuses it as any member without one. Every other element up to the members' count is the class's neutral; the elements -//! past it are left unwritten (the arrays are `PARTIALLY_BOUND`, and no table entry names them). -//! All heap writes of one member share one layout, `GENERAL` when some storage array holds it; a -//! member bound at a slot shares it with the slot's own writes, `GENERAL` when either is a -//! storage image (`one_layout_per_slot`). The plan uses such a member once, at its slot (widened -//! when the slot's own use is narrower). -//! - **Placement** ([`HeapPlacement`]). The elements above are the planned ones, which a consumer -//! that writes a heap set per command uses as they are. Under `HeapPlacement::ResourceId` each -//! member and listed argument sampler is at the element its resource ID names instead (a sampler -//! at its `ArgumentSampler::element` where the consumer gives one), and the tables map each ID -//! there: the plan is the same, and each heap write's element is the one its resource ID names -//! (a member without an ID takes none: no handle names it), so commands whose IDs name the same -//! resources write the same elements alike and can share one heap set. A consumer that keeps one -//! heap set for every command buffer can hold every live texture there instead: it writes each -//! texture's elements as the texture is made and binds one table of every ID -//! ([`handle_entry`]) at each handle table, so an ID a function loads from memory reaches its -//! texture though no command named it, as Metal's does. -//! - **Query-only classes.** A class whose numeric type is a query-only group's default -//! (`RuntimeFact::HeapNumericType`) reports each member that fits it in everything but its -//! numeric type (`PlanDiagnostic::IncompatibleHeapEntry`), as a slot reports an incompatible -//! binding: a query through a handle to it answers the neutral's. -//! - **Capacity.** The members plus the null element must fit every heap array's count (link's -//! heap capacity, at most [`TABLE_CAPACITY`]), and a table without heap arrays (a function that -//! only tests handles for null) [`TABLE_CAPACITY`], else [`BindError::HeapTooLarge`]. -//! - **Tables** (`table_bytes`). A stage's table has one entry more than the members reaching -//! it (`WriteSource::HandleTable`); per draw or dispatch it holds each such member's -//! `(resource id, element, flags)` with a nonzero resource id (0 is the null entry's), -//! deduplicated by id (the lowest element wins: both name the same texture), sorted by id, -//! after leading null entries that pad it to its planned length, so it stays sorted, its first -//! entry is the null entry, and every id resolves as [`lookup_host`] says. A texture no member -//! names misses. A member's flags are [`FLAG_OUT_OF_BOUNDS_ALPHA_ONE`] where its pixel format -//! has no alpha (`metal::format::out_of_bounds_alpha_one`): a module whose shader-checked heap -//! read observes the alpha takes Metal's out-of-bounds alpha from it; [`FLAG_RED_BLUE`] where -//! its pixel format is blue-first (`metal::format::red_blue_exchanged`); its border texels in -//! [`FLAG_BORDER_TEXELS`] (`metal::sampler::border_texels` of its pixel format and swizzle, a -//! placeholder format's those of the neutral it reads), which a read through a sampler hands -//! back at a border; its texel class in -//! [`FLAG_TEXEL_CLASS`]; and [`FLAG_STORAGE_UNREADABLE`] where the plan's profile cannot read its -//! storage view without a format ([`storage_unreadable`], `HeapMember::unreadable`). Every other -//! bit is 0. -//! - **Heap samplers**. A heap image is sampled through a separate sampler binding -//! (`BindingSource::HeapSampler`) in set 0: a constexpr sampler is the layout's immutable sampler -//! and takes no write; a runtime `[[sampler(n)]]` is written with the sampler bound at slot `n` -//! made for the use, or the neutral sampler where none is. A sampling that chooses among -//! constexpr samplers by its sampler handle reads an element of a constexpr sampler array -//! (`BindingSource::SamplerArray`), whose elements are the layout's immutable samplers and take -//! no write, each checked as a constexpr heap sampler is. One with an opaque-black border (the -//! immutable sampler's, or the bound sampler's shape) meets every member a sampled array holds, -//! so each such member's sampled view must read that border exactly -//! (`metal::sampler::check_border_view`), as a separate slot sampler's textures must. One that -//! filters linearly (the immutable sampler's filters, or the filtering -//! `metal::sampler::vk_sampler` makes of the bound shape for the use) meets every member of its -//! stage that a sampled float array holds, so each such member's view format must have the filter -//! features it needs (`plan::resources::require_filter_features`), as a combined or separate -//! pair's texture must, else `Unsupported{Format}`. -//! - **Argument samplers**. A sampler loaded from an argument buffer is a handle into -//! `BindState::argument_samplers`, searched in the stage's sampler table -//! (`Synthetic(SamplerTable)`, the handle table's layout over the samplers' ids, whose flags are -//! each sampler's [`SamplerWord`]), and read from the set-1 sampler array of its use -//! (`HandleClass::Sampler`) at its entry's element. Every sampler array and sampler table holds -//! twice the entries of the shape's capacity class (`ArgumentSamplersShape::entries`, at most the -//! heap's capacity): element `i + 1` of each array is `WriteSource::ArgumentSampler` for listed -//! sampler `i`, made for the array's use, and element 0 that use's neutral sampler. The second -//! half is headroom for states made between a command's encoding and its command buffer's commit. -//! A class whose -//! least count does not fit the capacity is [`BindError::HeapTooLarge`] at plan time, and a list -//! longer than the planned entries at instantiation. Every listed shape must pass -//! `metal::sampler::check_argument_sampler` for every use the arrays declare (the plan cannot see -//! which sampler a buffer pairs with which use, so a pair that never meets can refuse), and an -//! opaque-black border among them meets every member a sampled array holds, as a heap sampler's -//! does. The table bytes list each listed sampler's `(resource id, element, flags)` with a -//! nonzero id, as a texture table does. A listed cubic sampler, whose bicubic filter no stage -//! emulates through an argument buffer, is listed with `SamplerWord::CUBIC` in its flags: a stage -//! that tests the bit (`RuntimeFact::CubicArgumentSampler`) fails its command buffer where it -//! reaches the sampler, and beside a stage that does not (a fragment stage never does, nor a -//! stage that cannot write the command buffer's status) the plan is refused -//! `NotImplemented(SamplerBicubicFilter)`. -//! - **Function tables**. A visible-function table loaded from an argument buffer is searched by -//! its resource id in the stage's function-table directory (`Synthetic(FunctionTableDirectory)`, -//! the handle table's layout over `BindState::function_tables`, flags 0), which holds the -//! entries of the shape's capacity class (`FunctionTablesShape::entries`, at most the handle -//! table's reach), and read from the stage's function-table snapshot -//! (`Synthetic(FunctionTableSnapshot)`), written `WriteSource::FunctionTableSnapshot`: the -//! directory gives each listed id its record's word offset there (`FunctionTableSnapshot` of the -//! listed sizes). A class whose least count does not fit the capacity is -//! [`BindError::HeapTooLarge`] at plan time, and a list longer than the planned entries at -//! instantiation. Where the listed tables' words may pass -//! `maxStorageBufferRange` (`FunctionTablesShape::may_pass`), the variant that reads them through -//! their device addresses (`ResourceTemplate::function_table_addresses`) declares no snapshot: the -//! directory's entry holds the table's address in its element and flags words, and a listed table -//! without one cannot be represented. +//! a write of either), which never holds a depth or stencil format. A storage class holds a +//! texture whose writes Metal drops (`metal::format::writes_dropped`) as its neutral +//! ([`Fit::Dropped`]), and a sampled float class holds a form a heap reads by its raw texels as +//! its neutral ([`Fit::Raw`]). +//! - [`tier_read_gaps`]: Metal's contract defines a `read_write` read of its read-write tier +//! formats, so a function that reads a storage class through a handle is refused where one of +//! them would be held for its writes alone: on a device that reads storage without a format by +//! the formats' own bits alone (`DeviceProfile::storage_reads_by_format_bits`), a storage view +//! whose format lacks the read bit. +//! - [`storage_conversions`]: the aliases a storage access through a handle converts by (an 8-bit +//! sRGB texture's UNORM twin, a blue-first texture's RGBA-order twin), where the handle carries +//! the texture's class and red-blue order. +//! - The bits of `SpecKey::HeapRawTextures` ([`HELD`], [`FILTERED`]) and of +//! `SpecKey::HeapNanFamilies` ([`NAN_SIXTEEN`], [`NAN_WIDE`], [`NAN_SMALL`], [`NAN_OTHER`]). -use std::cell::Cell; use std::collections::{BTreeMap, BTreeSet}; -#[cfg(test)] -use crate::bind::neutral::image_classes; -use crate::bind::neutral::NeutralResource; -use crate::bind::plan::compute::internal; -use crate::bind::plan::resources::{ - bind_error, desc_filtering, neutral, opaque_black_border, require_filter_features, - sampled_view, view_type, -}; -use crate::bind::plan::{ - AccessClass, BindingPlan, DescriptorWrite, ImageSource, ImageViewDesc, PlanDiagnostic, - ResourceTemplate, ResourceUse, UseTarget, WriteSource, -}; -use crate::bind::state::{ - ArgumentSamplersShape, BindShape, BindState, BoundTexture, FunctionTablesShape, HeapPlacement, - ResourceClass, SamplerShape, TextureFacts, TextureShape, UsedResource, -}; -use crate::bind::table::FunctionTableSnapshot; +use crate::bind::state::{TextureFacts, TextureShape}; use crate::device::requirements::FormatUsage; use crate::device::DeviceProfile; -use crate::error::{BindError, Feature, Unsupported}; -use crate::memory::handles::{ - lookup_host, ENTRY_ELEMENT, ENTRY_FLAGS, ENTRY_ID_HI, ENTRY_ID_LO, FLAG_BORDER_TEXELS, - FLAG_OUT_OF_BOUNDS_ALPHA_ONE, FLAG_RED_BLUE, FLAG_STORAGE_UNREADABLE, FLAG_TEXEL_CLASS, - NEUTRAL_ELEMENT, TABLE_CAPACITY, TABLE_ENTRY_BYTES, -}; +use crate::error::{BindError, Error, Feature, InternalError, InternalKind, Unsupported}; use crate::metal::format::{ is_depth_stencil, red_blue_exchanged, sampled_type, storage_choice, storage_view_formats, vk_format, without_format_gaps, writes_dropped, StorageUse, }; -use crate::metal::sampler::{ - check_argument_sampler, check_border_view, vk_filtering, SamplerUse, SamplerWord, -}; use crate::metal::{self, TextureType}; -use crate::pipeline::artifact::RuntimeDependency; -use crate::pipeline::facts::{Mechanism, RuntimeFact}; -use crate::pipeline::interface::AccessSet; -use crate::pipeline::layout::{BindingSource, DescriptorBinding, PipelineLayout}; use crate::pipeline::lower_inputs::StorageImageClass; -use crate::pipeline::sym::{ - CombinedSampler, HandleClass, ImageAccess, ImageDim, ImageHandleClass, SampledType, SamplerRef, - SlotClass, SlotRef, Stage, SyntheticBinding, -}; +use crate::pipeline::sym::{ImageAccess, ImageDim, ImageHandleClass, SampledType}; use crate::vk; -/// What a heap entry holds: a used resource (by consumer token) or the resource bound at a slot. -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub enum HeapSource { - Used(u32), - Bound(SlotRef), +/// An invariant failure of the view derivation. +fn internal(detail: impl Into) -> BindError { + BindError::Internal(InternalError::new(InternalKind::Invariant, detail)) } -/// One heap member (the module docs): element `i + 1` for `ResourceTemplate.heap_members[i]`. -#[derive(Clone, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub(crate) struct HeapMember { - pub source: HeapSource, - /// Its view facts as planned (`TextureShape::Texture`); the state's must be these. - pub shape: TextureShape, - /// The stages whose handle tables enter it. - pub stages: Vec, - /// Its view in the storage arrays cannot be read without a format on the plan's profile - /// ([`storage_unreadable`]): its entry's flags carry `FLAG_STORAGE_UNREADABLE`. - pub unreadable: bool, -} - -/// One stage's handle table. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub(crate) struct PlannedHandleTable { - pub set: u32, - pub binding: u32, - pub stage: Stage, - /// Its entries, the null entry included: one more than the members reaching the stage. - pub entries: u32, +/// A `metal`/`device` error as a [`BindError`]: capability refusals stay typed, a descriptor +/// error stays the descriptor's, anything else is an invariant failure. +fn bind_error(e: Error) -> BindError { + match e { + Error::Unsupported(u) => BindError::Unsupported(u), + Error::InvalidDescriptor(d) => BindError::InvalidDescriptor(d), + Error::Internal(i) => BindError::Internal(i), + other => internal(format!("{other:?}")), + } } /// How a member fits a heap class. @@ -261,8 +100,7 @@ pub(crate) fn fit(shape: &TextureShape, class: &ImageHandleClass) -> Fit { pixel_format, usage, .. - } => return buffer_fit(pixel_format, Some(usage), class), - TextureShape::Buffer { pixel_format, .. } => return buffer_fit(pixel_format, None, class), + } => return buffer_fit(pixel_format, usage, class), TextureShape::Texture { texture_type, pixel_format, @@ -303,13 +141,12 @@ pub(crate) fn fit(shape: &TextureShape, class: &ImageHandleClass) -> Fit { } } -/// How a texture buffer of `pixel_format` and `usage` (where its facts state one: a slot's bound -/// texture buffer states none) fits the heap array of `class`: a texel-buffer class of its numeric -/// type holds it where its usage has the class's access, as an image class's member's must, and -/// one of another numeric type fits it in everything but that. +/// How a texture buffer of `pixel_format` and `usage` fits the heap array of `class`: a +/// texel-buffer class of its numeric type holds it where its usage has the class's access, as an +/// image class's member's must, and one of another numeric type fits it in everything but that. fn buffer_fit( pixel_format: metal::PixelFormat, - usage: Option, + usage: metal::TextureUsage, class: &ImageHandleClass, ) -> Fit { let needs = match class.access { @@ -322,7 +159,7 @@ fn buffer_fit( || class.arrayed || class.multisampled || class.depth_compare - || usage.is_some_and(|usage| !usage.intersects(needs)) + || !usage.intersects(needs) { return Fit::No; } @@ -384,23 +221,19 @@ fn member_texel_view( /// Whether a member of facts `shape` is a texture a heap reads by its raw texels: an unswizzled, /// not sparse texture of one sample, of a form of `ExtendedRange::HEAP_READ`. pub(crate) fn raw_held(shape: &TextureShape) -> bool { - match *shape { - TextureShape::Texture { - pixel_format, - swizzle, - sparse, - sample_count, - .. - } => { - !sparse - && sample_count <= 1 - && swizzle.is_default() - && crate::metal::format::ExtendedRange::of(pixel_format) - .and_then(crate::metal::format::ExtendedRange::heap_read) - .is_some() - } - TextureShape::Buffer { .. } => false, - } + let TextureShape::Texture { + pixel_format, + swizzle, + sparse, + sample_count, + .. + } = *shape; + !sparse + && sample_count <= 1 + && swizzle.is_default() + && crate::metal::format::ExtendedRange::of(pixel_format) + .and_then(crate::metal::format::ExtendedRange::heap_read) + .is_some() } /// The bit of `SpecKey::HeapRawTextures`' value that a texture the stage's handles can name is held @@ -429,199 +262,80 @@ pub(crate) const NAN_SMALL: u32 = 4; /// may hold a NaN: its written NaN is the device's. pub(crate) const NAN_OTHER: u32 = 8; -/// The bit of `SpecKey::HeapNanFamilies` of a texture of pixel format `pf`: its class's family -/// (`metal::texel_format::TexelFormat`, as `lower::texture::half_write_nans` tests a bound -/// texture's), or 0 for a format whose texels hold no NaN (normalized, sRGB, extended-range, -/// another packed one) or that a float texture does not view (integer, stencil). -pub(crate) fn nan_family(pf: metal::PixelFormat) -> u32 { - use crate::metal::bicubic::BicubicTexels as B; - use crate::metal::texel_format::{PackedTexels, TexelFormat}; - use crate::pipeline::sym::SampledType; - if crate::metal::format::sampled_type(pf) != Some(SampledType::Float) { - return 0; - } - let class = crate::metal::format::bound_texel_format(pf); - let family = class & (B::LINEAR | B::HALF | TexelFormat::NAN_FREE); - match class & TexelFormat::PACKED_MASK { - p if p == PackedTexels::SmallFloat.class().0 => NAN_SMALL, - 0 if family == B::HALF => NAN_SIXTEEN, - 0 if family == B::LINEAR => NAN_WIDE, - 0 if family == 0 => NAN_OTHER, - _ => 0, - } -} - -/// The view through which the heap array of `class` holds a member of facts `shape`, in -/// `layout`, on `profile` (the module docs): a sampled class's as a slot's -/// (`plan::resources::sampled_view`), a storage class's the direct format (an `A8Unorm` texture -/// held in red its `R8_UNORM` image), which the class's formatless declaration must serve. -/// A storage member whose choice is an alias a heap access converts by ([`storage_conversions`]) -/// takes that alias. `Unsupported` where the array cannot view it: an extended-range format (its -/// raw texels need its function's decode) but a form a heap reads in the unsigned integer class -/// ([`Fit::Raw`]), its raw view, a storage member whose storage choice or format the formatless -/// declaration cannot serve (another alias, or a converting one whose swizzle loses its class), or -/// an `A8Unorm` one held in red whose swizzle moves its alpha (its handle's class is not +/// The format of the view through which the storage heap array of `class` holds a member of +/// facts `shape` on `profile`: the direct format (an `A8Unorm` texture held in red its +/// `R8_UNORM` image), which the class's formatless declaration must serve. A member whose choice +/// is an alias a heap access converts by ([`storage_conversions`]) takes that alias. +/// `Unsupported` where the array cannot view it: an extended-range format (its raw texels need +/// its function's decode), a member whose storage choice or format the formatless declaration +/// cannot serve (another alias, or a converting one whose swizzle loses its class), or an +/// `A8Unorm` one held in red whose swizzle moves its alpha (its handle's class is not /// `A8Unorm`'s). -fn member_view( +fn member_storage_format( profile: &DeviceProfile, shape: &TextureShape, - class: &ImageHandleClass, - layout: vk::ImageLayout, -) -> Result { - let TextureShape::Texture { pixel_format, .. } = *shape else { - return Err(internal("a texture-buffer heap member")); - }; - let raw = raw_held(shape) - && class.access == ImageAccess::Sampled - && class.sampled_type == SampledType::Uint; - if crate::metal::format::ExtendedRange::of(pixel_format).is_some() && !raw { +) -> Result { + let TextureShape::Texture { pixel_format, .. } = *shape; + if crate::metal::format::ExtendedRange::of(pixel_format).is_some() { return Err(BindError::Unsupported(Unsupported::not_implemented( Feature::ArgumentBufferTextures, ))); } - if class.access == ImageAccess::Storage { - // The class does not say which accesses the function makes, so the member serves - // every access the device lets a heap make. - let use_ = heap_storage_use(profile); - let c = storage_choice(pixel_format, use_, profile).map_err(bind_error)?; - // The class's one formatless declaration cannot convert per element: a member is viewed - // through its own format. - let per_element = c.class == StorageImageClass::Identity; - let aliased = c.alias.is_some(); - // An `A8Unorm` texture held in red (`StorageImageClass::AlphaInRed`): its `R8_UNORM` - // image, whose texels a heap access converts where the handle carries `A8Unorm`'s class - // (`metal::texel_format::heap_alpha_in_red_index`), which a swizzle that moves its alpha - // does not keep. - let alpha_in_red = c.class == StorageImageClass::AlphaInRed; - // A texture viewed through its storage choice's alias, whose channels a heap access - // exchanges or whose sRGB codes it decodes and encodes where the handle carries its - // class and red-blue order ([`storage_conversions`]): the alias, which its image lists - // among its view formats. - let converted = aliased - && !c.x_channel - && storage_conversions(profile).contains(&StorageConversion { - index: crate::metal::texel_format::heap_class_index(pixel_format, shape.swizzle()), - red_blue: red_blue_exchanged(pixel_format), - class: c.class, - }) - && storage_view_formats(pixel_format, profile).contains(&c.vk_format); - if alpha_in_red - && crate::metal::texel_format::heap_class_index(pixel_format, shape.swizzle()) - != crate::metal::texel_format::heap_alpha_in_red_index() - { - return Err(BindError::Unsupported(Unsupported::not_implemented( - Feature::ArgumentBufferTextures, - ))); - } - if !(per_element || alpha_in_red || converted) || (aliased && !converted) || c.x_channel { - return Err(BindError::Unsupported(Unsupported::not_implemented( - Feature::ArgumentBufferTextures, - ))); - } - let format = match alpha_in_red || converted { - true => c.vk_format, - false => crate::metal::format::direct_format(pixel_format) - .ok_or_else(|| internal("a storage heap member without a format"))?, - }; - // The declaration names no format, so the member's format must serve those accesses - // without one. Where the formats' own bits alone grant a read, a member whose view's - // format lacks the read bit is held for its writes and flagged ([`storage_unreadable`]). - let gaps = without_format_gaps(format, use_, profile); - if !gaps.is_empty() { - return Err(BindError::Unsupported(Unsupported::needs_any_of( - Feature::ArgumentBufferTextures, - vec![gaps], - ))); - } - return Ok(ImageViewDesc { - view_type: view_type(class)?, - format, - aspect: vk::ImageAspectFlags::COLOR, - layout, - components: vk::ComponentMapping::IDENTITY, - level: None, - shader_swizzle: false, - }); + // The class does not say which accesses the function makes, so the member serves + // every access the device lets a heap make. + let use_ = heap_storage_use(profile); + let c = storage_choice(pixel_format, use_, profile).map_err(bind_error)?; + // The class's one formatless declaration cannot convert per element: a member is viewed + // through its own format. + let per_element = c.class == StorageImageClass::Identity; + let aliased = c.alias.is_some(); + // An `A8Unorm` texture held in red (`StorageImageClass::AlphaInRed`): its `R8_UNORM` + // image, whose texels a heap access converts where the handle carries `A8Unorm`'s class + // (`metal::texel_format::heap_alpha_in_red_index`), which a swizzle that moves its alpha + // does not keep. + let alpha_in_red = c.class == StorageImageClass::AlphaInRed; + // A texture viewed through its storage choice's alias, whose channels a heap access + // exchanges or whose sRGB codes it decodes and encodes where the handle carries its + // class and red-blue order ([`storage_conversions`]): the alias, which its image lists + // among its view formats. + let converted = aliased + && !c.x_channel + && storage_conversions(profile).contains(&StorageConversion { + index: crate::metal::texel_format::heap_class_index(pixel_format, shape.swizzle()), + red_blue: red_blue_exchanged(pixel_format), + class: c.class, + }) + && storage_view_formats(pixel_format, profile).contains(&c.vk_format); + if alpha_in_red + && crate::metal::texel_format::heap_class_index(pixel_format, shape.swizzle()) + != crate::metal::texel_format::heap_alpha_in_red_index() + { + return Err(BindError::Unsupported(Unsupported::not_implemented( + Feature::ArgumentBufferTextures, + ))); } - let mut view = sampled_view(profile, pixel_format, class)?; - view.layout = layout; - Ok(view) -} - -/// The flags of a handle-table entry for a texture of view facts `shape`, `unreadable` its -/// [`storage_unreadable`]. -fn entry_flags(shape: &TextureShape, unreadable: bool) -> u32 { - let pixel_format = shape.pixel_format(); - let swizzle = shape.swizzle(); - let alpha = match crate::metal::format::out_of_bounds_alpha_one(pixel_format) { - Some(true) => FLAG_OUT_OF_BOUNDS_ALPHA_ONE, - _ => 0, - }; - let red_blue = match red_blue_exchanged(pixel_format) { - true => FLAG_RED_BLUE, - false => 0, - }; - // A placeholder pixel format's member reads its neutral, whose border texels a slot bound to - // one takes too. - let border = crate::metal::sampler::border_texels(pixel_format, swizzle) - .unwrap_or(crate::metal::sampler::NEUTRAL_BORDER_TEXELS) - << FLAG_BORDER_TEXELS.trailing_zeros(); - let index = crate::metal::texel_format::heap_class_index(pixel_format, swizzle); - let class = index << FLAG_TEXEL_CLASS.trailing_zeros(); - let unreadable = match unreadable { - true => FLAG_STORAGE_UNREADABLE, - false => 0, - }; - alpha | red_blue | unreadable | (border & FLAG_BORDER_TEXELS) | (class & FLAG_TEXEL_CLASS) -} - -/// Whether `profile` reads storage without a format by the formats' own bits alone -/// (`DeviceProfile::storage_reads_by_format_bits`) and the heap's storage arrays hold a texture of -/// view facts `shape` through a view it cannot read so: one whose format lacks -/// `VK_FORMAT_FEATURE_2_STORAGE_READ_WITHOUT_FORMAT_BIT` ([`storage_read_gaps`]). Such an array -/// holds it for its writes, which the device stores without a format as before; a storage read -/// through its handle reads the null element instead (`memory::handles::FLAG_STORAGE_UNREADABLE`), -/// as a nil texture's read does. A function that reads the array is compiled only where none of -/// Metal's read-write tier formats is so held ([`tier_read_gaps`]). False on every other profile, -/// and for a texture no storage array holds. -pub(crate) fn storage_unreadable(profile: &DeviceProfile, shape: &TextureShape) -> bool { - if !profile.storage_reads_by_format_bits() { - return false; + if !(per_element || alpha_in_red || converted) || (aliased && !converted) || c.x_channel { + return Err(BindError::Unsupported(Unsupported::not_implemented( + Feature::ArgumentBufferTextures, + ))); } - let texture_type = match *shape { - TextureShape::Texture { texture_type, .. } => texture_type, - TextureShape::Buffer { .. } => TextureType::TextureBuffer, + let format = match alpha_in_red || converted { + true => c.vk_format, + false => crate::metal::format::direct_format(pixel_format) + .ok_or_else(|| internal("a storage heap member without a format"))?, }; - let (pixel_format, swizzle) = (shape.pixel_format(), shape.swizzle()); - let Some(sampled_type) = sampled_type(pixel_format) else { - return false; - }; - // The storage class of the texture's own shape and numeric type, the one array that holds it - // ([`fit`]). - let (dim, arrayed, multisampled) = dims(texture_type); - let class = ImageHandleClass { - dim, - arrayed, - multisampled, - sampled_type, - depth_compare: false, - access: ImageAccess::Storage, - format: crate::pipeline::sym::StorageFormatClass::Unknown, - }; - if fit(shape, &class) != Fit::Holds { - return false; + // The declaration names no format, so the member's format must serve those accesses + // without one. Where the formats' own bits alone grant a read, a member whose view's + // format lacks the read bit is held for its writes and flagged + // (`memory::handles::FLAG_STORAGE_UNREADABLE`). + let gaps = without_format_gaps(format, use_, profile); + if !gaps.is_empty() { + return Err(BindError::Unsupported(Unsupported::needs_any_of( + Feature::ArgumentBufferTextures, + vec![gaps], + ))); } - let (format, texel_buffer) = match dim { - ImageDim::Buffer => match member_texel_view(profile, pixel_format, swizzle, &class) { - Ok(format) => (format, true), - Err(_) => return false, - }, - _ => match member_view(profile, shape, &class, vk::ImageLayout::GENERAL) { - Ok(view) => (view.format, false), - Err(_) => return false, - }, - }; - !storage_read_gaps(profile, format, texel_buffer).is_empty() + Ok(format) } /// What a storage view of `format` (`texel_buffer`: a texel buffer view) lacks for a read without a @@ -650,7 +364,7 @@ fn storage_read_gaps( /// each such view's [`storage_read_gaps`], so empty but where the profile reads storage without a /// format by the formats' own bits alone. A function that reads the array through a handle needs /// them (`lower::texture::slot`): without them it would read such a member as -/// [`storage_unreadable`]'s null element. +/// the null element (`memory::handles::FLAG_STORAGE_UNREADABLE`). pub(crate) fn tier_read_gaps( profile: &DeviceProfile, class: &ImageHandleClass, @@ -688,8 +402,7 @@ pub(crate) fn tier_read_gaps( ImageDim::Buffer => { member_texel_view(profile, pixel_format, member.swizzle(), class).map(|f| (f, true)) } - _ => member_view(profile, &member, class, vk::ImageLayout::GENERAL) - .map(|v| (v.format, false)), + _ => member_storage_format(profile, &member).map(|f| (f, false)), }; // A tier format the array cannot hold at all is not held for its writes either. let Ok((format, texel_buffer)) = view else { @@ -726,7 +439,7 @@ pub(crate) struct StorageConversion { /// out): an 8-bit sRGB texture where the device stores no sRGB format, and a blue-first one where /// it stores its RGBA-order twin only. A class and order whose formats choose otherwise (another /// alias, or `Identity` beside a converting one) has none: its converting member is refused, as -/// before. The binder views a member of such a choice through its alias ([`member_view`]) and the +/// before. A member of such a choice is viewed through its alias ([`member_storage_format`]) and the /// texture lowering converts where the handle carries the class and order /// (`lower::texture::heap_storage_conversions`); both come from this list, so the two agree. pub(crate) fn storage_conversions(profile: &DeviceProfile) -> Vec { @@ -767,1429 +480,6 @@ pub(crate) fn storage_conversions(profile: &DeviceProfile) -> Vec [u8; HANDLE_ENTRY_BYTES as usize] { - let mut bytes = [0u8; HANDLE_ENTRY_BYTES as usize]; - let mut put = |word: u32, v: u32| { - let at = 4 * word as usize; - bytes[at..at + 4].copy_from_slice(&v.to_le_bytes()); - }; - put(ENTRY_ID_LO, id as u32); - put(ENTRY_ID_HI, (id >> 32) as u32); - put(ENTRY_ELEMENT, element); - put(ENTRY_FLAGS, flags); - bytes -} - -/// The bytes of one handle-table entry ([`handle_entry`]). -pub const HANDLE_ENTRY_BYTES: u32 = TABLE_ENTRY_BYTES; - -/// The stages with a table of `kind` (a handle table or a sampler table) in `layout`, and each -/// table's `(set, binding)`. -fn tables(layout: &PipelineLayout, kind: SyntheticBinding) -> Vec<(Stage, u32, u32)> { - let mut out = Vec::new(); - for set in &layout.sets { - for b in &set.bindings { - if let BindingSource::Synthetic { stage, binding } = b.source { - if binding == kind { - out.push((stage, set.set, b.binding)); - } - } - } - } - out -} - -/// The heap members of `shape` for a pipeline whose handle tables are in `stages` (the module -/// docs); `reach` gives the stages a used resource's render stages reach. None is marked -/// unreadable: the planner marks each on its profile ([`storage_unreadable`]). -pub(crate) fn members( - shape: &BindShape, - stages: &[Stage], - reach: impl Fn(metal::RenderStages) -> Vec, -) -> Vec { - let image = |t: &TextureShape| { - matches!(t, TextureShape::Texture { texture_type, .. } - if *texture_type != TextureType::TextureBuffer) - }; - let mut out = Vec::new(); - for (&token, u) in &shape.used { - let crate::bind::state::UsedClass::Texture(t) = u.class else { - continue; - }; - let reached: Vec = reach(u.stages) - .into_iter() - .filter(|s| stages.contains(s)) - .collect(); - if image(&t) && !reached.is_empty() { - out.push(HeapMember { - source: HeapSource::Used(token), - shape: t, - stages: reached, - unreadable: false, - }); - } - } - for (&stage, s) in &shape.stages { - if !stages.contains(&stage) { - continue; - } - for (&index, t) in &s.textures { - if image(t) { - out.push(HeapMember { - source: HeapSource::Bound(SlotRef { - stage, - class: SlotClass::Texture, - index, - }), - shape: *t, - stages: vec![stage], - unreadable: false, - }); - } - } - } - out -} - -/// A heap sampler that filters linearly, and so needs filter features of the view format of -/// each member it samples: its stage, its filtering (`metal::sampler::vk_filtering` of a runtime -/// one's bound shape, or a constexpr one's immutable sampler), and its comparison. One that filters -/// nearest needs nothing of a format, and an integer texture's always does, so only float-texel -/// samplers are listed. -#[derive(Clone, Copy, Debug)] -struct HeapFilter { - stage: Stage, - filtering: (bool, vk::SamplerReductionMode), - compare: bool, -} - -/// What a plan's sampler arrays and tables hold of a sampler state of a shape its bind shape did -/// not list (`ArgumentSamplersShape::shapes`), as a consumer lists the states again when a -/// command buffer commits: the plan-time checks of a listed shape (`HeapPlanner::new`, the module docs), kept so that a state made between a -/// command's encoding and its commit is listed exactly where they pass. -#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub(crate) struct SamplerAdmission { - /// The classes of the plan's sampler arrays: each is a use that every listed shape must pass - /// (`metal::sampler::check_argument_sampler`). - pub classes: Vec, - /// Every stage with a sampler table tests its entries for a cubic filter - /// (`RuntimeFact::CubicArgumentSampler`). - pub cubic: bool, - /// The members a sampled heap array holds were checked against an opaque-black border - /// (`HeapPlanner::view`). - pub opaque_black: bool, -} - -impl SamplerAdmission { - /// The uses of the plan's sampler arrays. - fn uses(&self) -> impl Iterator + '_ { - self.classes.iter().filter_map(|c| c.sampler_use()) - } - - /// Whether the plan may list a sampler of shape `s` beside its stages' cubic tests: one - /// that is not cubic, or every stage tests, or no array samples through it. - fn cubic_held(&self, s: &SamplerShape) -> bool { - !s.cubic || self.cubic || self.uses().next().is_none() - } -} - -/// A plan's heap: its members, the pipeline's heap classes and handle tables, its argument -/// samplers, and what their writes need. A plan hands it every set-1 binding -/// ([`HeapPlanner::array`]), every handle table ([`HeapPlanner::table`]), and every sampler table -/// ([`HeapPlanner::sampler_table`]), then [`HeapPlanner::finish`]es its template. -pub(crate) struct HeapPlanner<'a> { - profile: &'a DeviceProfile, - members: Vec, - /// The image classes of the pipeline's heap arrays. - classes: Vec, - /// The handle tables, `(stage, set, binding)`. - tables: Vec<(Stage, u32, u32)>, - /// The classes whose numeric type is a query-only group's default. - defaulted: BTreeSet, - /// Per member, its views' layout. - layouts: Vec, - /// Some heap sampler has an opaque-black border. - opaque_black: bool, - /// The heap samplers that filter linearly. - filters: Vec, - /// The stages that may sample, gather, or query a level of a texture a heap holds by its raw - /// texels alone where they read the neutral (`RuntimeFact::HeapRawSamples`: with no sampler - /// slot, or naming one whose bound sampler states what the emulation does not answer). - sampling: BTreeSet, - /// The stages whose mode-2 heap writes the function has not built - /// (`RuntimeFact::HeapWriteRounding`), each with whether it writes `float` texels there. - write_rounding: BTreeMap, - /// The heap classes each stage reads where a member of another numeric class reads the - /// neutral (`RuntimeFact::HeapCrossClassNeutral`), each with whether every such member does - /// (else only one of a format a crossing read does not take). - cross_neutral: BTreeMap>, - /// The storage classes each stage reads (`RuntimeFact::HeapStorageReads`). - storage_reads: BTreeMap>, - /// The sampler tables, `(stage, set, binding)`. - sampler_tables: Vec<(Stage, u32, u32)>, - /// The argument samplers' shape, the entries of every sampler array and table, and what - /// they admit of a shape the bind shape did not list, when the pipeline has a sampler array - /// or table. - samplers: Option<(ArgumentSamplersShape, u32, SamplerAdmission)>, - /// The function-table directories, `(stage, set, binding)`. - directories: Vec<(Stage, u32, u32)>, - /// The function-table snapshots, `(stage, set, binding)`. - snapshots: Vec<(Stage, u32, u32)>, - /// The pipeline reads its function tables through the addresses its directories hold - /// (`VariantKey::addressed_function_tables`). - addressed_tables: bool, - /// The function tables' shape and the entries of every directory, when the pipeline has a - /// directory. - function_tables: Option<(FunctionTablesShape, u32)>, - /// Outputs: the tables planned, and the diagnostics. - planned: Vec, - planned_samplers: Vec, - planned_directories: Vec, - diagnostics: Vec, -} - -impl<'a> HeapPlanner<'a> { - /// The heap of a pipeline with `layout` and `dependencies` for `shape`, or `None` when the - /// pipeline has no handle or sampler table; `reach` as for [`members`]. - pub fn new( - profile: &'a DeviceProfile, - layout: &PipelineLayout, - dependencies: &[RuntimeDependency], - shape: &BindShape, - reach: impl Fn(metal::RenderStages) -> Vec, - ) -> Result>, BindError> { - let sampler_tables = tables(layout, SyntheticBinding::SamplerTable); - let directories = tables(layout, SyntheticBinding::FunctionTableDirectory); - let snapshots = tables(layout, SyntheticBinding::FunctionTableSnapshot); - let tables = tables(layout, SyntheticBinding::HandleTable); - let mut classes = Vec::new(); - let mut capacity = TABLE_CAPACITY; - let mut opaque_black = false; - let mut filters = Vec::new(); - // A stage that reads the neutral, or whose runtime sampler slot is bound to a sampler - // whose word states what the emulation does not answer (an unbound slot's word is 0, a - // nearest sampler's). - let sampling: BTreeSet = dependencies - .iter() - .filter_map(|d| match d.fact { - RuntimeFact::HeapRawSamples { - stage, - sampler: None, - } => Some(stage), - RuntimeFact::HeapRawSamples { - stage, - sampler: Some(n), - } => { - let word = shape - .stages - .get(&stage) - .and_then(|s| s.samplers.get(&n)) - .map_or(0, |s| s.word.0); - let filter = word & metal::sampler::SamplerWord::LINEAR_FILTER; - let answered = filter == 0 || filter == metal::sampler::SamplerWord::LINEAR; - (!answered).then_some(stage) - } - _ => None, - }) - .collect(); - let mut cross_neutral: BTreeMap> = BTreeMap::new(); - for d in dependencies { - if let RuntimeFact::HeapCrossClassNeutral { - stage, - class, - every_member, - } = d.fact - { - *cross_neutral - .entry(stage) - .or_default() - .entry(class) - .or_default() |= every_member; - } - } - let mut write_rounding = BTreeMap::new(); - for d in dependencies { - if let RuntimeFact::HeapWriteRounding { stage, halves } = d.fact { - *write_rounding.entry(stage).or_insert(false) |= halves; - } - } - let mut storage_reads: BTreeMap> = BTreeMap::new(); - for d in dependencies { - if let RuntimeFact::HeapStorageReads { stage, class } = d.fact { - storage_reads.entry(stage).or_default().insert(class); - } - } - for set in &layout.sets { - for b in &set.bindings { - match b.source { - BindingSource::Heap(class) => { - classes.push(class); - capacity = capacity.min(b.count); - } - // A constexpr sampler's border and filtering are its immutable sampler's; a - // runtime one's the sampler bound at its slot made for the use. An unbound one - // is the neutral sampler, which filters nearest. - BindingSource::HeapSampler { stage, sampler } => { - let (border, filtering) = match sampler.sampler { - SamplerRef::Constexpr(_) => match b.immutable_sampler.as_ref() { - Some(d) => (opaque_black_border(d), Some(desc_filtering(d))), - None => (false, None), - }, - SamplerRef::Slot(index) => match shape - .stages - .get(&stage) - .and_then(|s| s.samplers.get(&index)) - .map(|s| &s.shape) - { - Some(s) => ( - s.opaque_black_border, - Some(vk_filtering(s, sampler.sampler_use())), - ), - None => (false, None), - }, - }; - opaque_black |= border; - if let Some(filtering) = filtering.filter(|f| f.0 && !sampler.integer) { - filters.push(HeapFilter { - stage, - filtering, - compare: sampler.compare, - }); - } - } - // A constexpr sampler array's elements: each its immutable sampler's border - // and filtering. - BindingSource::SamplerArray { - stage, - compare, - integer, - } => { - for d in &b.immutable_samplers { - opaque_black |= opaque_black_border(d); - let filtering = desc_filtering(d); - if filtering.0 && !integer { - filters.push(HeapFilter { - stage, - filtering, - compare, - }); - } - } - } - _ => {} - } - } - } - // An argument sampler's uses, a cube's explicit gradients included. - let sampler_uses: Vec = - classes.iter().filter_map(|c| c.sampler_use()).collect(); - let images = classes - .iter() - .filter(|c| matches!(c, HandleClass::Image(_))) - .count(); - if images > 0 && tables.is_empty() { - return Err(internal("a heap array without a handle table")); - } - if !sampler_uses.is_empty() && sampler_tables.is_empty() { - return Err(internal("a sampler array without a sampler table")); - } - // Directories read the tables from a snapshot, or at the addresses they hold: one of the - // two, never both. - let addressed_tables = dependencies - .iter() - .any(|d| d.fact == RuntimeFact::FunctionTableRange { addressed: true }); - let homes = [!snapshots.is_empty(), addressed_tables] - .into_iter() - .filter(|&h| h) - .count(); - if homes != usize::from(!directories.is_empty()) { - return Err(internal( - "function-table directories without one home of the tables' words, or with two", - )); - } - if tables.is_empty() && sampler_tables.is_empty() && directories.is_empty() { - return Ok(None); - } - // The function tables: the class's entries. - let function_tables = if directories.is_empty() { - None - } else { - let t = &shape.function_tables; - if t.least_count() > u64::from(capacity) { - return Err(BindError::HeapTooLarge { - count: t.least_count(), - limit: u64::from(capacity), - }); - } - let entries = u32::try_from(t.entries().min(u64::from(capacity))) - .map_err(|_| internal("a function-table directory beyond u32 entries"))?; - Some((*t, entries)) - }; - // The argument samplers: the class's entries, each listed shape made for each use, and an - // opaque-black border meeting the members. - let samplers = if sampler_tables.is_empty() { - None - } else { - let a = &shape.argument_samplers; - if a.least_count() > u64::from(capacity) { - return Err(BindError::HeapTooLarge { - count: a.least_count(), - limit: u64::from(capacity), - }); - } - for s in &a.shapes { - for &use_ in &sampler_uses { - check_argument_sampler(s, use_, profile).map_err(bind_error)?; - } - } - // A cubic sampler's bicubic filter through an argument buffer is not built. - // A stage that tests its argument samplers' words for it marks the command buffer - // where it reaches one (`RuntimeFact::CubicArgumentSampler`), so a listed cubic - // sampler is refused only beside a stage's sampler table that does not test it. - let tested = |stage: Stage| { - dependencies - .iter() - .any(|d| d.fact == RuntimeFact::CubicArgumentSampler { stage }) - }; - // The same checks admit a shape the bind shape did not list as a command buffer - // commits; the members' border check is the plan's own - // (`finish`). - let admission = SamplerAdmission { - classes: classes - .iter() - .copied() - .filter(|c| c.sampler_use().is_some()) - .collect(), - cubic: sampler_tables.iter().all(|&(stage, ..)| tested(stage)), - opaque_black: false, - }; - if !a.shapes.iter().all(|s| admission.cubic_held(s)) { - return Err(BindError::Unsupported(Unsupported::not_implemented( - Feature::SamplerBicubicFilter, - ))); - } - if !sampler_uses.is_empty() { - opaque_black |= a.shapes.iter().any(|s| s.opaque_black_border); - } - // Twice the class's entries: headroom for the states made between a command's - // encoding and its command buffer's commit, which list again then. - let entries = u32::try_from(a.entries().saturating_mul(2).min(u64::from(capacity))) - .map_err(|_| internal("a sampler table beyond u32 entries"))?; - Some((a.clone(), entries, admission)) - }; - let stages: Vec = tables.iter().map(|t| t.0).collect(); - let members: Vec = members(shape, &stages, reach) - .into_iter() - .map(|m| HeapMember { - unreadable: storage_unreadable(profile, &m.shape), - ..m - }) - .collect(); - // A sparse texture a stage's handle tables reach where the stage observes the residency - // of its heap accesses, which answer the word of a texture that is not sparse - // (`RuntimeFact::HeapResidency`). - let residency: BTreeSet = dependencies - .iter() - .filter_map(|d| match d.fact { - RuntimeFact::HeapResidency { stage } => Some(stage), - _ => None, - }) - .collect(); - if members - .iter() - .any(|m| m.shape.sparse() && m.stages.iter().any(|s| residency.contains(s))) - { - return Err(BindError::Unsupported(Unsupported::not_implemented( - Feature::ArgumentBufferTextures, - ))); - } - let count = members.len() as u64 + 1; - if count > u64::from(capacity) { - return Err(BindError::HeapTooLarge { - count, - limit: u64::from(capacity), - }); - } - let classes: Vec = classes - .iter() - .filter_map(|c| match c { - HandleClass::Image(i) => Some(*i), - HandleClass::Sampler { .. } | HandleClass::FunctionTable => None, - }) - .collect(); - let layouts = members - .iter() - .map(|m| { - let storage = |c: &&ImageHandleClass| c.access == ImageAccess::Storage; - if classes - .iter() - .filter(storage) - .any(|c| fit(&m.shape, c) == Fit::Holds) - { - vk::ImageLayout::GENERAL - } else { - vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL - } - }) - .collect(); - let defaulted = dependencies - .iter() - .filter_map(|d| match d.fact { - RuntimeFact::HeapNumericType { class } => Some(class), - _ => None, - }) - .collect(); - Ok(Some(HeapPlanner { - profile, - members, - classes, - tables, - defaulted, - layouts, - opaque_black, - filters, - sampling, - write_rounding, - cross_neutral, - storage_reads, - sampler_tables, - samplers, - directories, - snapshots, - addressed_tables, - function_tables, - planned: Vec::new(), - planned_samplers: Vec::new(), - planned_directories: Vec::new(), - diagnostics: Vec::new(), - })) - } - - /// The write of `stage`'s handle table at `(set, binding)`. - pub fn table( - &mut self, - stage: Stage, - set: u32, - binding: u32, - ) -> Result { - if !self.tables.contains(&(stage, set, binding)) { - return Err(internal(format!( - "a handle table of {stage:?} out of place" - ))); - } - let reaching = self.members.iter().filter(|m| m.stages.contains(&stage)); - let entries = u32::try_from(reaching.count() + 1) - .map_err(|_| internal("a handle table beyond u32 entries"))?; - let bytes_len = entries - .checked_mul(TABLE_ENTRY_BYTES) - .ok_or_else(|| internal("a handle table beyond u32 bytes"))?; - self.planned.push(PlannedHandleTable { - set, - binding, - stage, - entries, - }); - Ok(WriteSource::HandleTable { stage, bytes_len }) - } - - /// The write of `stage`'s sampler table at `(set, binding)`: a handle table of the argument - /// samplers' class entries. - pub fn sampler_table( - &mut self, - stage: Stage, - set: u32, - binding: u32, - ) -> Result { - if !self.sampler_tables.contains(&(stage, set, binding)) { - return Err(internal(format!( - "a sampler table of {stage:?} out of place" - ))); - } - let entries = self.sampler_entries()?; - let bytes_len = entries - .checked_mul(TABLE_ENTRY_BYTES) - .ok_or_else(|| internal("a sampler table beyond u32 bytes"))?; - self.planned_samplers.push(PlannedHandleTable { - set, - binding, - stage, - entries, - }); - Ok(WriteSource::HandleTable { stage, bytes_len }) - } - - /// The write of `stage`'s function-table directory at `(set, binding)`: a handle table of the - /// function tables' class entries. - pub fn directory( - &mut self, - stage: Stage, - set: u32, - binding: u32, - ) -> Result { - if !self.directories.contains(&(stage, set, binding)) { - return Err(internal(format!( - "a function-table directory of {stage:?} out of place" - ))); - } - let entries = self.function_table_entries()?; - let bytes_len = entries - .checked_mul(TABLE_ENTRY_BYTES) - .ok_or_else(|| internal("a function-table directory beyond u32 bytes"))?; - self.planned_directories.push(PlannedHandleTable { - set, - binding, - stage, - entries, - }); - Ok(WriteSource::HandleTable { stage, bytes_len }) - } - - /// The write of `stage`'s function-table snapshot at `(set, binding)`: the listed tables' - /// words, which the consumer writes as the command buffer commits. - pub fn snapshot( - &mut self, - stage: Stage, - set: u32, - binding: u32, - ) -> Result { - if !self.snapshots.contains(&(stage, set, binding)) { - return Err(internal(format!( - "a function-table snapshot of {stage:?} out of place" - ))); - } - Ok(WriteSource::FunctionTableSnapshot) - } - - /// The entries of every function-table directory. - fn function_table_entries(&self) -> Result { - self.function_tables - .as_ref() - .map(|(_, entries)| *entries) - .ok_or_else(|| internal("function tables without a directory")) - } - - /// The entries of every sampler array and table. - fn sampler_entries(&self) -> Result { - self.samplers - .as_ref() - .map(|(_, entries, _)| *entries) - .ok_or_else(|| internal("argument samplers without a sampler table")) - } - - /// The runtime sampler slot that feeds `stage`'s heap sampler `sampler`, whose layout binding - /// carries `immutable`: `None` for a constexpr sampler, which is that immutable sampler and - /// takes no write, and the `[[sampler(n)]]` slot for a runtime one, whose write is the sampler - /// bound there made for the use (`ResourcePlanner::heap_sampler`). Every heap member a sampled - /// array holds meets a runtime sampler's opaque-black border and its filtering, so the border - /// and filter checks cover it (`HeapPlanner::new`, `HeapPlanner::array`). - pub fn sampler( - &self, - stage: Stage, - sampler: CombinedSampler, - immutable: Option<&vk::SamplerDesc>, - ) -> Result, BindError> { - match (sampler.sampler, immutable) { - (SamplerRef::Constexpr(_), Some(_)) => Ok(None), - (SamplerRef::Constexpr(_), None) => Err(internal( - "a constexpr heap sampler without its immutable sampler", - )), - (SamplerRef::Slot(index), None) => Ok(Some(SlotRef { - stage, - class: SlotClass::Sampler, - index, - })), - (SamplerRef::Slot(_), Some(_)) => { - Err(internal("a runtime heap sampler with an immutable sampler")) - } - } - } - - /// The writes of the heap array `b` of set `set`: element 0 and every member the array does - /// not hold its class's neutral, every member it holds that member's view. - pub fn array( - &mut self, - set: u32, - b: &DescriptorBinding, - ) -> Result, BindError> { - let (binding, ty) = (b.binding, b.ty); - let BindingSource::Heap(class) = b.source else { - return Err(internal(format!("{:?} is no heap array", b.source))); - }; - if set != 1 { - return Err(internal(format!("a heap array in set {set}"))); - } - let image = match class { - HandleClass::Image(image) => image, - // The array's `VkSampler`s are made for its use: the comparison and the texel class. - HandleClass::Sampler { compare, integer } => { - return self.sampler_array(set, b, (compare, integer)) - } - HandleClass::FunctionTable => return Err(internal("a function-table heap array")), - }; - let expected = match (image.access, image.dim == ImageDim::Buffer) { - (ImageAccess::Storage, false) => vk::DescriptorType::STORAGE_IMAGE, - (ImageAccess::Storage, true) => vk::DescriptorType::STORAGE_TEXEL_BUFFER, - (_, false) => vk::DescriptorType::SAMPLED_IMAGE, - (_, true) => vk::DescriptorType::UNIFORM_TEXEL_BUFFER, - }; - if ty != expected { - return Err(internal(format!("a heap array of {class:?} as {ty:?}"))); - } - let n = neutral(&image)?; - let write = |element: u32, source: WriteSource| DescriptorWrite { - set, - binding, - array_element: element, - ty, - source, - }; - let mut out = Vec::with_capacity(self.members.len() + 1); - out.push(write(NEUTRAL_ELEMENT, WriteSource::Neutral(n))); - for (i, m) in self.members.iter().enumerate() { - let element = - u32::try_from(i + 1).map_err(|_| internal("a heap element beyond u32"))?; - let fits = fit(&m.shape, &image); - // A texture whose writes Metal drops, in a storage class a stage it reaches reads: - // Metal's read of it is not measured. - if matches!(fits, Fit::Holds | Fit::Dropped) && self.reads_unmeasured(m, &image) { - return Err(BindError::Unsupported(Unsupported::not_implemented( - Feature::Format, - ))); - } - let source = match fits { - // A texture a stage may write by a mode-2 write the function has not built. - Fit::Holds if image.access == ImageAccess::Storage && self.rounds(m) => { - return Err(BindError::Unsupported(Unsupported::not_implemented( - Feature::PrivateRenderState( - crate::error::PrivateRenderField::TextureWriteRounding, - ), - ))); - } - Fit::Holds => { - let layout = self - .layouts - .get(i) - .copied() - .ok_or_else(|| internal("a heap member without a layout"))?; - let view = self.view(&m.shape, &image, layout)?; - self.check_filters(&image, &m.stages, view.format)?; - WriteSource::HeapEntry { - class, - element, - source: m.source, - view, - } - } - // The unsigned integer class holds its raw texels, which a stage's read decodes, - // and its sample or gather where the function emulates it; a stage that samples - // it otherwise would read this neutral (`RuntimeFact::HeapRawSamples`). - Fit::Raw if m.stages.iter().any(|s| self.sampling.contains(s)) => { - return Err(BindError::Unsupported(Unsupported::not_implemented( - Feature::ArgumentBufferTextures, - ))); - } - Fit::Raw => WriteSource::Neutral(n), - // The writes Metal drops leave the neutral as Metal leaves the texture. - Fit::Dropped => WriteSource::Neutral(n), - fit => { - if fit == Fit::NumericType && self.defaulted.contains(&image) { - self.diagnostics - .push(PlanDiagnostic::IncompatibleHeapEntry { - class, - element, - source: m.source, - substituted: n, - }); - } - // A member of another numeric class a stage reaches by an access that reads - // this neutral. - if fit == Fit::NumericType { - let crosses = match m.shape { - TextureShape::Texture { pixel_format, .. } => { - crate::metal::texel_format::crosses_classes(pixel_format) - } - _ => false, - }; - for &stage in &m.stages { - let reached = self - .cross_neutral - .get(&stage) - .and_then(|c| c.get(&image)) - .is_some_and(|&every| every || !crosses); - if reached { - self.diagnostics - .push(PlanDiagnostic::CrossClassHeapNeutral { - stage, - class, - element, - source: m.source, - }); - } - } - } - WriteSource::Neutral(n) - } - }; - out.push(write(element, source)); - } - Ok(out) - } - - /// Whether a stage member `m` reaches reads it in the storage class `class` - /// (`RuntimeFact::HeapStorageReads`) where `m` is a texture whose writes Metal drops - /// (`metal::format::writes_dropped`), whose read there is not measured. - fn reads_unmeasured(&self, m: &HeapMember, class: &ImageHandleClass) -> bool { - let TextureShape::Texture { pixel_format, .. } = m.shape else { - return false; - }; - class.access == ImageAccess::Storage - && writes_dropped(pixel_format) - && m.stages.iter().any(|s| { - self.storage_reads - .get(s) - .is_some_and(|classes| classes.contains(class)) - }) - } - - /// Whether a stage member `m` reaches writes it by a mode-2 write the function states it has - /// not built (`RuntimeFact::HeapWriteRounding`): `m` is an `RG11B10Float` or `RGB9E5Float` - /// texture, or a half-float one where the stage writes `float` texels - /// (`metal::texel_format::mode_two_rounds`). - fn rounds(&self, m: &HeapMember) -> bool { - let TextureShape::Texture { pixel_format, .. } = m.shape else { - return false; - }; - m.stages.iter().any(|s| { - self.write_rounding.get(s).is_some_and(|&halves| { - crate::metal::texel_format::mode_two_rounds(pixel_format, halves) - }) - }) - } - - /// The writes of the sampler array `b` of set `set` for the use (`compare`, `integer`): - /// element 0 the use's neutral sampler, element `i + 1` argument sampler `i` made for the use, - /// through the class's entries. - fn sampler_array( - &self, - set: u32, - b: &DescriptorBinding, - (compare, integer): (bool, bool), - ) -> Result, BindError> { - if b.ty != vk::DescriptorType::SAMPLER { - return Err(internal(format!( - "a sampler array of {:?} as {:?}", - b.source, b.ty - ))); - } - let entries = self.sampler_entries()?; - if entries > b.count { - return Err(internal("a sampler array shorter than its entries")); - } - let write = |element: u32, source: WriteSource| DescriptorWrite { - set, - binding: b.binding, - array_element: element, - ty: b.ty, - source, - }; - let mut out = Vec::with_capacity(entries as usize); - out.push(write( - NEUTRAL_ELEMENT, - WriteSource::Neutral(NeutralResource::Sampler { compare }), - )); - for element in 1..entries { - out.push(write( - element, - WriteSource::ArgumentSampler { - index: element - 1, - compare, - integer, - }, - )); - } - Ok(out) - } - - /// The view of a member of facts `shape` that the array of `class` holds, in `layout` - /// ([`member_view`]), checked against the plan's heap samplers' opaque-black border. - fn view( - &self, - shape: &TextureShape, - class: &ImageHandleClass, - layout: vk::ImageLayout, - ) -> Result { - if let ( - true, - TextureShape::Texture { - pixel_format, - swizzle, - .. - }, - ) = ( - self.opaque_black && class.access != ImageAccess::Storage, - *shape, - ) { - // A heap sampler's opaque-black border must read Metal's texel through the member's - // view, its swizzle composed. - let usages = [FormatUsage::SampledImage].into(); - let m = vk_format(pixel_format, &usages, self.profile).map_err(bind_error)?; - check_border_view(true, pixel_format, &m, swizzle, self.profile).map_err(bind_error)?; - } - member_view(self.profile, shape, class, layout) - } - - /// Check that a member reaching `stages` that the array of `class` holds through a view of - /// `format` has the filter features each heap sampler of those stages that filters linearly - /// needs of it (`plan::resources::require_filter_features`), as a combined or separate pair's - /// texture must, else `Unsupported{Format}` naming the first missing one. A float-texel sampler - /// samples only float classes, and a storage class is never sampled. The check is conservative - /// as the border's is: the layout does not say which float classes a heap sampler samples, so a - /// member of a class none of them reaches is checked too. - fn check_filters( - &self, - class: &ImageHandleClass, - stages: &[Stage], - format: vk::Format, - ) -> Result<(), BindError> { - if class.access != ImageAccess::Sampled || class.sampled_type != SampledType::Float { - return Ok(()); - } - for f in self.filters.iter().filter(|f| stages.contains(&f.stage)) { - require_filter_features(self.profile, f.filtering, f.compare, format)?; - } - Ok(()) - } - - /// Merge into `uses` the members bound at a slot that some heap array holds (a used texture - /// is in the plan's `uses` already): read, and written when a storage array holds it, in its - /// stage (`stages`). A slot the plan already uses keeps one use, widened to both. - fn merge_uses( - &self, - uses: &mut Vec, - stages: impl Fn(Stage) -> vk::PipelineStageFlags2, - ) { - for m in &self.members { - let HeapSource::Bound(slot) = m.source else { - continue; - }; - let held = |a: ImageAccess| { - self.classes - .iter() - .any(|c| c.access == a && fit(&m.shape, c) == Fit::Holds) - }; - let (sampled, storage) = (held(ImageAccess::Sampled), held(ImageAccess::Storage)); - if !(sampled || storage) { - continue; - } - let target = UseTarget::Slot(slot); - match uses.iter_mut().find(|u| u.resource == target) { - Some(u) => { - u.access.read = true; - u.access.write |= storage; - if storage { - u.class = AccessClass::StorageImage; - } - u.stages |= stages(slot.stage); - } - None => uses.push(ResourceUse { - resource: target, - access: AccessSet { - read: true, - write: storage, - }, - class: if storage { - AccessClass::StorageImage - } else { - AccessClass::Sampled - }, - stages: stages(slot.stage), - range: None, - }), - } - } - } - - /// Complete a plan: one layout per bound texture across its `descriptors` - /// ([`one_layout_per_slot`]), the members' `uses` merged in (in `stages`), the members and - /// tables into its `template`, and the diagnostics into its `diagnostics`. - pub fn finish( - self, - descriptors: &mut [DescriptorWrite], - uses: &mut Vec, - stages: impl Fn(Stage) -> vk::PipelineStageFlags2, - template: &mut ResourceTemplate, - diagnostics: &mut Vec, - ) { - one_layout_per_slot(descriptors); - self.merge_uses(uses, stages); - template.heap_members = self.members; - template.handle_tables = self.planned; - template.sampler_tables = self.planned_samplers; - // A shape admitted as a command buffer commits meets the members as the plan checked - // them against an opaque-black border. - let opaque_black = self.opaque_black; - let (shape, admission) = match self.samplers { - Some((shape, _, admission)) => ( - Some(shape), - SamplerAdmission { - opaque_black, - ..admission - }, - ), - None => (None, SamplerAdmission::default()), - }; - template.argument_samplers = shape; - template.sampler_admission = admission; - template.function_table_directories = self.planned_directories; - template.function_tables = self.function_tables.map(|(shape, _)| shape); - template.function_table_addresses = self.addressed_tables; - diagnostics.extend(self.diagnostics); - } -} - -/// The slot and view of a write of the texture bound at a slot: a plain or combined texture -/// write, or a heap element holding a bound member. -fn slot_view(w: &mut WriteSource) -> Option<(SlotRef, &mut ImageViewDesc)> { - match w { - WriteSource::Texture { slot, view } - | WriteSource::CombinedImageSampler { - image: ImageSource::Texture { slot, view }, - .. - } - | WriteSource::HeapEntry { - source: HeapSource::Bound(slot), - view, - .. - } => Some((*slot, view)), - _ => None, - } -} - -/// Give every write of a texture bound at a slot one layout: `GENERAL` when some write of it is a -/// storage image (its slot's own storage binding, or a storage heap array holding it), its views' -/// layout otherwise. A static slot's storage write and the heap's sampled element of the same -/// texture, or a sampled slot and a storage heap element, would otherwise name two layouts for one -/// texture. -pub(crate) fn one_layout_per_slot(descriptors: &mut [DescriptorWrite]) { - let mut general = BTreeSet::new(); - for d in descriptors.iter_mut() { - if d.ty == vk::DescriptorType::STORAGE_IMAGE { - if let Some((slot, _)) = slot_view(&mut d.source) { - general.insert(slot); - } - } - } - for d in descriptors.iter_mut() { - if let Some((slot, view)) = slot_view(&mut d.source) { - if general.contains(&slot) { - view.layout = vk::ImageLayout::GENERAL; - } - } - } -} - -/// The heap planner of a plan that writes a heap binding or a handle table. -pub(crate) fn planner<'p, 'a>( - heap: &'p mut Option>, -) -> Result<&'p mut HeapPlanner<'a>, BindError> { - heap.as_mut() - .ok_or_else(|| internal("a heap binding without a handle table")) -} - -/// The used resources of a bind state by token, in the state's order: a list the consumer gives -/// in token order (`BindState::used_in_token_order`), whose entries of a token a heap member finds -/// by search forward from where the last member's ended (a plan's members ascend by token, -/// [`members`]), so a plan's members together cost about the list's length; else gathered by -/// token once per instantiation, so each heap member finds its entries without rescanning the -/// state. -enum UsedByToken<'s> { - /// The list, and where the last lookup's entries ended in it. - Listed(&'s [UsedResource], Cell), - Gathered(BTreeMap>), -} - -#[cfg(test)] -thread_local! { - /// The entries of a listed state that lookups of its used resources compared - /// ([`forward`]), on this thread. - static LISTED_LOOKED_AT: Cell = const { Cell::new(0) }; -} - -/// The partition point of `items` under `below`, which holds of a prefix of them: found by -/// doubling a bound from their start, then searching under it, at the logarithm of the point -/// rather than of their count. -fn forward(items: &[T], below: impl Fn(&T) -> bool) -> usize { - let below = |item: &T| { - #[cfg(test)] - LISTED_LOOKED_AT.with(|looked| looked.set(looked.get() + 1)); - below(item) - }; - let mut end = 1; - while end <= items.len() && below(&items[end - 1]) { - end *= 2; - } - let start = end / 2; - start + items[start..end.min(items.len())].partition_point(below) -} - -impl<'s> UsedByToken<'s> { - /// `state`'s used resources by token. - fn of(state: &'s BindState) -> UsedByToken<'s> { - let used = &state.used_resources; - if state.used_in_token_order { - debug_assert!( - used.windows(2).all(|w| w[0].token <= w[1].token), - "used resources listed in token order are not" - ); - return UsedByToken::Listed(used, Cell::new(0)); - } - let mut gathered: BTreeMap> = BTreeMap::new(); - for u in used { - gathered.entry(u.token).or_default().push(u); - } - UsedByToken::Gathered(gathered) - } - - /// The entries of `token`, in the state's order; `None` where it lists none. A listed - /// state's are searched forward from where the last lookup's ended, where they lie past it, - /// else from the list's start. - fn get(&self, token: u32) -> Option + '_> { - let (listed, gathered): (&'s [UsedResource], &[&'s UsedResource]) = match self { - UsedByToken::Listed(used, from) => { - let before = from.get().checked_sub(1).and_then(|at| used.get(at)); - let base = match before { - Some(before) if before.token < token => from.get(), - Some(_) | None => 0, - }; - let start = base + forward(&used[base..], |u| u.token < token); - let end = start + forward(&used[start..], |u| u.token == token); - from.set(end); - (&used[start..end], &[]) - } - UsedByToken::Gathered(gathered) => (&[], gathered.get(&token)?), - }; - let none = listed.is_empty() && gathered.is_empty(); - (!none).then(|| listed.iter().chain(gathered.iter().copied())) - } -} - -/// The resource id of heap member `m` in `state` (whose used resources are `used`), checked -/// against the plan's shape. -fn member_id( - m: &HeapMember, - used: &UsedByToken<'_>, - state: &BindState, -) -> Result, BindError> { - let mismatch = || { - internal(format!( - "the bind state's shape differs from the plan's at heap member {:?}", - m.source - )) - }; - match m.source { - HeapSource::Used(token) => { - let mut id = None; - let entries = used.get(token).ok_or_else(mismatch)?; - for u in entries { - let ResourceClass::Texture(facts) = u.class else { - return Err(mismatch()); - }; - // A heap array views level 0 alone: the member's level count is not the - // plan's. - if facts.shape().at_one_level() != m.shape.at_one_level() { - return Err(mismatch()); - } - match (id, u.resource_id) { - (Some(a), Some(b)) if a != b => { - return Err(internal(format!( - "used resource {token} lists two resource ids" - ))) - } - (None, b) => id = b, - _ => {} - } - } - Ok(id) - } - HeapSource::Bound(slot) => match state - .stages - .get(&slot.stage) - .and_then(|t| t.textures.get(&slot.index)) - { - Some(&BoundTexture::Texture { facts, resource_id }) - if facts.shape().at_one_level() == m.shape.at_one_level() => - { - Ok(resource_id) - } - _ => Err(mismatch()), - }, - } -} - -/// The bytes of each planned handle table and sampler table of `template` for `state` (the module -/// docs): 16-byte entries `{id_lo, id_hi, element, flags}` of `u32` words, little-endian, a -/// member's flags its out-of-bounds-alpha flag, a sampler's its pixel-coordinate flag. Linear in -/// the members, the state's used resources, and its argument samplers (plus sorting each table). -pub(crate) fn table_bytes( - template: &ResourceTemplate, - state: &BindState, -) -> Result, BindError> { - let mut out = handle_table_bytes(&template.heap_members, &template.handle_tables, state)?; - if let Some(shape) = &template.argument_samplers { - out.extend(sampler_table_bytes(shape, &template.sampler_tables, state)?); - } else if !template.sampler_tables.is_empty() { - return Err(internal("a sampler table without its argument samplers")); - } - if let Some(shape) = &template.function_tables { - out.extend(directory_bytes( - shape, - &template.function_table_directories, - template.function_table_addresses, - state, - )?); - } else if !template.function_table_directories.is_empty() { - return Err(internal("a function-table directory without its tables")); - } - Ok(out) -} - -/// The bytes of the function-table directories `tables`, planned for the tables' `shape`, for -/// `state`: listed table `i` is the word offset of its record in the function-table snapshot of -/// the listed sizes, its flags 0, whatever the placement; with `addresses`, the device address of -/// its words, low word as the element and high word as the flags. A state of -/// another shape is the plan's misuse; a list longer than the planned entries is -/// [`BindError::HeapTooLarge`], a snapshot past `u32::MAX` words is not representable, and a listed -/// nonzero id without an address, or an addressed directory that lists no table (whose null entry's -/// loads need one's address), is the consumer's [`BindError::Unsupported`] (`DynamicCall`, not -/// representable). -fn directory_bytes( - shape: &FunctionTablesShape, - tables: &[PlannedHandleTable], - addresses: bool, - state: &BindState, -) -> Result, BindError> { - if FunctionTablesShape::of(&state.function_tables) != *shape { - return Err(internal( - "the bind state's shape differs from the plan's at its function tables", - )); - } - let offsets = match addresses { - true => None, - false => Some( - FunctionTableSnapshot::of(state.function_tables.iter().map(|f| f.size)).ok_or( - BindError::Unsupported(Unsupported::not_representable(Feature::DynamicCall)), - )?, - ), - }; - let element = |i: usize| { - offsets - .as_ref() - .and_then(|snapshot| snapshot.offsets().get(i).copied()) - .ok_or_else(|| internal("a listed table without its snapshot record")) - }; - let count = state.function_tables.len() as u64 + 1; - let mut out = Vec::with_capacity(tables.len()); - for t in tables { - if count > u64::from(t.entries) { - return Err(BindError::HeapTooLarge { - count, - limit: u64::from(t.entries), - }); - } - let mut entries = Vec::with_capacity(state.function_tables.len()); - let mut listed = false; - for (i, f) in state.function_tables.iter().enumerate() { - if f.resource_id == 0 { - continue; - } - if addresses { - if f.address == 0 { - return Err(BindError::Unsupported(Unsupported::not_representable( - Feature::DynamicCall, - ))); - } - listed = true; - entries.push((f.resource_id, f.address as u32, (f.address >> 32) as u32)); - continue; - } - entries.push((f.resource_id, element(i)?, 0)); - } - // The null entry's loads take the last entry's address, a listed table's: a directory of - // null entries alone gives them none. - if addresses && !listed { - return Err(BindError::Unsupported(Unsupported::not_representable( - Feature::DynamicCall, - ))); - } - out.push(table_of(t, entries)?); - } - Ok(out) -} - -/// The bytes of the handle tables `tables` of the heap members `members` for `state`. -fn handle_table_bytes( - members: &[HeapMember], - tables: &[PlannedHandleTable], - state: &BindState, -) -> Result, BindError> { - if members.is_empty() && tables.is_empty() { - return Ok(Vec::new()); - } - let used = UsedByToken::of(state); - let mut ids = Vec::with_capacity(members.len()); - for m in members { - ids.push(member_id(m, &used, state)?); - } - // A member's flags: Metal's out-of-bounds read of a pixel format without alpha returns - // alpha 1, and its texel class. - let flags: Vec = members - .iter() - .map(|m| entry_flags(&m.shape, m.unreadable)) - .collect(); - let mut out = Vec::with_capacity(tables.len()); - for t in tables { - let mut entries: Vec<(u64, u32, u32)> = Vec::new(); - for (i, ((m, id), &f)) in members.iter().zip(&ids).zip(&flags).enumerate() { - let Some(id) = id.filter(|&id| id != 0) else { - continue; - }; - if m.stages.contains(&t.stage) { - entries.push((id, placed(i, id, state.heap_placement)?, f)); - } - } - out.push(table_of(t, entries)?); - } - Ok(out) -} - -/// The bytes of the sampler tables `tables`, planned for the argument samplers' `shape`, for -/// `state`: listed sampler `i` is element `i + 1`, its flags its [`SamplerWord`]. A state of -/// another shape is the plan's misuse; a list longer than the planned entries (a class past the -/// heap's capacity) is [`BindError::HeapTooLarge`]. -fn sampler_table_bytes( - shape: &ArgumentSamplersShape, - tables: &[PlannedHandleTable], - state: &BindState, -) -> Result, BindError> { - if ArgumentSamplersShape::of(&state.argument_samplers) != *shape { - return Err(internal( - "the bind state's shape differs from the plan's at its argument samplers", - )); - } - listed_sampler_tables(tables, &state.argument_samplers, state.heap_placement) -} - -/// The bytes of the sampler tables `tables` listing `samplers` under `placement` -/// ([`sampler_table_bytes`]); a list longer than the planned entries is -/// [`BindError::HeapTooLarge`]. -fn listed_sampler_tables( - tables: &[PlannedHandleTable], - samplers: &[crate::bind::ArgumentSampler], - placement: HeapPlacement, -) -> Result, BindError> { - let count = samplers.len() as u64 + 1; - let mut out = Vec::with_capacity(tables.len()); - for t in tables { - if count > u64::from(t.entries) { - return Err(BindError::HeapTooLarge { - count, - limit: u64::from(t.entries), - }); - } - let mut entries = Vec::with_capacity(samplers.len()); - for (i, s) in samplers.iter().enumerate() { - if s.resource_id == 0 { - continue; - } - let element = placed(i, s.placed_at(), placement)?; - entries.push((s.resource_id, element, SamplerWord::of(&s.desc).0)); - } - out.push(table_of(t, entries)?); - } - Ok(out) -} - -/// Whether the plan of a pipeline of `dependencies` for a bind shape of function tables `shape` -/// reads the tables through their device addresses (`VariantKey::addressed_function_tables`): a -/// pipeline compiled so states it, and one that reads tables by their ids otherwise asks for it -/// where the shape's tables may pass `maxStorageBufferRange` and the fact's mechanism is a variant. -/// Where it is a plan-time check (a device without device addresses), the plan binds the tables' -/// words whole, as before such a variant, and the consumer refuses a table, or a snapshot, that -/// passes the range where it binds it (`BufferRange`, naming device addresses): the shape's class -/// is too coarse to refuse it here without refusing tables that fit. -pub(crate) fn addressed_function_tables( - profile: &DeviceProfile, - dependencies: &[RuntimeDependency], - shape: &FunctionTablesShape, -) -> bool { - let mut reads = dependencies.iter().filter_map(|d| match d.fact { - RuntimeFact::FunctionTableRange { addressed } => Some((addressed, d.mechanism)), - _ => None, - }); - let Some((addressed, mechanism)) = reads.next() else { - return false; - }; - addressed - || (mechanism == Mechanism::Variant - && shape.may_pass(profile.fields().limits.max_storage_buffer_range)) -} - -/// The element of planned member or listed sampler `i`, placed at `id` (nonzero: its resource -/// ID, or a listed sampler's element), under `placement`: `i + 1`, or `id` itself. -fn placed(i: usize, id: u64, placement: HeapPlacement) -> Result { - match placement { - HeapPlacement::Planned => { - u32::try_from(i + 1).map_err(|_| internal("a heap element beyond u32")) - } - HeapPlacement::ResourceId => u32::try_from(id).map_err(|_| BindError::HeapTooLarge { - count: id.saturating_add(1), - limit: u64::from(u32::MAX), - }), - } -} - -impl BindingPlan {} - -/// The bytes of table `t` holding `entries` (`(resource id, element, flags)`, ids nonzero): -/// deduplicated by id (the lowest element wins: both name the same resource), sorted by id, after -/// leading null entries that pad it to its planned length. -fn table_of( - t: &PlannedHandleTable, - mut entries: Vec<(u64, u32, u32)>, -) -> Result { - entries.sort_unstable(); - entries.dedup_by_key(|e| e.0); - let len = t.entries as usize; - if entries.len() >= len { - return Err(internal("a handle table over its planned length")); - } - let mut table = vec![(0u64, NEUTRAL_ELEMENT, 0u32); len - entries.len()]; - table.extend(entries); - debug_assert!(table.windows(2).all(|w| w[0].0 <= w[1].0)); - debug_assert!({ - let ids: Vec<(u64, u32)> = table.iter().map(|&(id, e, _)| (id, e)).collect(); - ids.iter() - .all(|&(id, e)| lookup_host(&ids, id) == e || id == 0) - }); - let bytes = table - .iter() - .flat_map(|&(id, element, f)| handle_entry(id, element, f)) - .collect(); - Ok(crate::bind::instantiate::DescriptorBytes { - set: t.set, - binding: t.binding, - bytes, - }) -} - /// The accesses a storage heap element may take: a read or a write through the class's /// formatless declaration wherever the device's `shaderStorageImage{Read,Write}WithoutFormat` /// allows one (the lowering refuses a heap access without its feature, `declare_heap`). @@ -2201,24 +491,5 @@ fn heap_storage_use(profile: &DeviceProfile) -> StorageUse { ) } -/// Every heap array class of `profile`, sorted and distinct: the image classes the core can declare -/// there, then the sampler classes of every use (with comparison or without, of an integer texture -/// or not). -#[cfg(test)] -pub(crate) fn heap_classes(profile: &DeviceProfile) -> Vec { - let mut out: Vec = image_classes(profile) - .into_iter() - .map(HandleClass::Image) - .collect(); - for compare in [false, true] { - for integer in [false, true] { - out.push(HandleClass::Sampler { compare, integer }); - } - } - out.sort(); - out.dedup(); - out -} - #[cfg(test)] mod tests; diff --git a/crates/metal2vulkan/src/bind/heap/tests.rs b/crates/metal2vulkan/src/bind/heap/tests.rs index 99b1e5cef..8115cf9ef 100644 --- a/crates/metal2vulkan/src/bind/heap/tests.rs +++ b/crates/metal2vulkan/src/bind/heap/tests.rs @@ -1,7 +1,5 @@ use super::*; -use crate::bind::state::{SamplerDescriptor, StageTable, TextureFacts, UsedResource}; -use crate::bind::state::{StageShape, UsedClass, UsedShape}; -use crate::metal::{PixelFormat, RenderStages, TextureUsage}; +use crate::metal::{PixelFormat, TextureUsage}; use crate::pipeline::sym::{SampledType, StorageFormatClass}; use crate::spirv::testing::committed_profiles; @@ -31,9 +29,6 @@ fn shape(ty: TextureType, pf: PixelFormat, samples: u32, usage: TextureUsage) -> TextureShape::Texture { address_modes: crate::metal::sampler::AddressModeMap::IDENTITY, offset_base_axes: 0, - ycbcr_in_place: false, - ycbcr_planes_sampler: None, - texel_rows: false, texture_type: ty, pixel_format: pf, sample_count: samples, @@ -88,17 +83,6 @@ fn fit_is_shape_samples_numeric_type_usage_and_aspect() { ); assert_eq!(fit(&shape(T::Type2D, rgba, 4, READ), &f2d), Fit::No); assert_eq!(fit(&shape(T::Cube, rgba, 1, READ), &f2d), Fit::No); - assert_eq!( - fit( - &TextureShape::Buffer { - pixel_format: rgba, - swizzle: crate::metal::TextureSwizzleChannels::DEFAULT, - parts: 1, - }, - &f2d - ), - Fit::No - ); let ms = class(ImageDim::D2, false, true, Float, Sampled); assert_eq!( fit(&shape(T::Type2DMultisample, rgba, 4, READ), &ms), @@ -172,491 +156,6 @@ fn fit_is_shape_samples_numeric_type_usage_and_aspect() { ); } -fn used_shape(t: TextureShape, stages: RenderStages) -> UsedShape { - let mut u = UsedResource::new( - ResourceClass::Texture(TextureFacts::new( - TextureType::Type2D, - PixelFormat::RGBA8Unorm, - )), - 0, - ); - u.stages = stages; - let mut state = BindState::default(); - state.used_resources.push(u); - let mut s = state.shape().used.remove(&0).expect("used"); - s.class = UsedClass::Texture(t); - s -} - -/// Members are the used image textures by token that reach a stage with a table, then the bound -/// image textures of those stages by slot; buffers, heaps, and texture buffers are not members. -#[test] -fn members_are_used_then_bound_image_textures_reaching_a_table() { - let t2d = shape(TextureType::Type2D, PixelFormat::RGBA8Unorm, 1, READ); - let buffer = TextureShape::Buffer { - pixel_format: PixelFormat::R32Float, - swizzle: crate::metal::TextureSwizzleChannels::DEFAULT, - parts: 1, - }; - let mut shape_ = BindShape::default(); - shape_ - .used - .insert(9, used_shape(t2d, RenderStages::FRAGMENT)); - shape_.used.insert(2, used_shape(t2d, RenderStages::VERTEX)); - shape_ - .used - .insert(3, used_shape(buffer, RenderStages::VERTEX)); - let mut heap_used = used_shape(t2d, RenderStages::VERTEX); - heap_used.class = UsedClass::Heap; - shape_.used.insert(4, heap_used); - for stage in [Stage::Vertex, Stage::Fragment] { - let mut s = StageShape::default(); - s.textures.insert(5, t2d); - s.textures.insert(1, buffer); - shape_.stages.insert(stage, s); - } - let reach = |s: RenderStages| { - let mut out = Vec::new(); - if s.contains(RenderStages::VERTEX) { - out.push(Stage::Vertex); - } - if s.contains(RenderStages::FRAGMENT) { - out.push(Stage::Fragment); - } - out - }; - // Only the vertex stage has a table: the fragment-only token and slot are not members. - let m = members(&shape_, &[Stage::Vertex], reach); - let texture = |stage, index| SlotRef { - stage, - class: SlotClass::Texture, - index, - }; - assert_eq!( - m.iter() - .map(|m| (m.source, m.stages.clone())) - .collect::>(), - vec![ - (HeapSource::Used(2), vec![Stage::Vertex]), - ( - HeapSource::Bound(texture(Stage::Vertex, 5)), - vec![Stage::Vertex] - ), - ] - ); - let m = members(&shape_, &[Stage::Vertex, Stage::Fragment], reach); - assert_eq!( - m.iter().map(|m| m.source).collect::>(), - vec![ - HeapSource::Used(2), - HeapSource::Used(9), - HeapSource::Bound(texture(Stage::Vertex, 5)), - HeapSource::Bound(texture(Stage::Fragment, 5)), - ] - ); -} - -/// A table's bytes: the members' nonzero ids (the lowest element of a repeated id), sorted, after -/// leading null entries up to the planned length; `lookup_host` resolves each to its element. -/// Over its planned length, a token with two ids, and a state of another shape are internal. -#[test] -fn table_bytes_are_sorted_deduplicated_and_padded() { - let t2d = shape(TextureType::Type2D, PixelFormat::RGBA8Unorm, 1, READ); - let ids = [ - Some(30u64), - Some(10), - None, - Some(0), - Some(30), - Some(u64::MAX), - ]; - let mut state = BindState::default(); - let mut members = Vec::new(); - for (i, id) in ids.iter().enumerate() { - let token = i as u32 + 1; - let mut u = UsedResource::new( - ResourceClass::Texture(TextureFacts::new( - TextureType::Type2D, - PixelFormat::RGBA8Unorm, - )), - token, - ); - u.resource_id = *id; - state.used_resources.push(u); - members.push(HeapMember { - source: HeapSource::Used(token), - shape: t2d, - stages: vec![Stage::Kernel], - unreadable: false, - }); - } - let planned = PlannedHandleTable { - set: 0, - binding: 4, - stage: Stage::Kernel, - entries: 7, - }; - let out = handle_table_bytes(&members, &[planned], &state).expect("bytes"); - assert_eq!((out[0].set, out[0].binding), (0, 4)); - let words: Vec = out[0] - .bytes - .chunks(4) - .map(|w| u32::from_le_bytes(w.try_into().expect("word"))) - .collect(); - let entries: Vec<(u64, u32)> = words - .chunks(4) - .map(|e| (u64::from(e[0]) | (u64::from(e[1]) << 32), e[2])) - .collect(); - assert_eq!( - entries, - vec![ - (0, 0), - (0, 0), - (0, 0), - (0, 0), - (10, 2), - (30, 1), - (u64::MAX, 6) - ] - ); - for (id, e) in [(10, 2), (30, 1), (u64::MAX, 6), (0, 0), (20, 0), (31, 0)] { - assert_eq!(lookup_host(&entries, id), e, "id {id}"); - } - // Too short a plan for the state's ids. - let short = PlannedHandleTable { - entries: 3, - ..planned - }; - assert!(matches!( - handle_table_bytes(&members, &[short], &state), - Err(BindError::Internal(_)) - )); - // One token listed twice with two ids. - let mut twice = state.clone(); - let mut again = twice.used_resources[0]; - again.resource_id = Some(99); - twice.used_resources.push(again); - assert!(matches!( - handle_table_bytes(&members, &[planned], &twice), - Err(BindError::Internal(_)) - )); - // A member whose facts differ from the plan's. - let mut other = state.clone(); - other.used_resources[1].class = - ResourceClass::Texture(TextureFacts::new(TextureType::Type2D, PixelFormat::R32Uint)); - assert!(matches!( - handle_table_bytes(&members, &[planned], &other), - Err(BindError::Internal(_)) - )); - // A bound member: its slot's id. - let slot = SlotRef { - stage: Stage::Kernel, - class: SlotClass::Texture, - index: 2, - }; - let mut k = StageTable::default(); - k.textures.insert( - 2, - BoundTexture::Texture { - facts: TextureFacts::new(TextureType::Type2D, PixelFormat::RGBA8Unorm), - resource_id: Some(7), - }, - ); - let mut bound = BindState::default(); - bound.stages.insert(Stage::Kernel, k); - let m = [HeapMember { - source: HeapSource::Bound(slot), - shape: t2d, - stages: vec![Stage::Kernel], - unreadable: false, - }]; - let two = PlannedHandleTable { - entries: 2, - ..planned - }; - let out = handle_table_bytes(&m, &[two], &bound).expect("bytes"); - assert_eq!(&out[0].bytes[16..28], &[7, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]); -} - -/// Under `HeapPlacement::ResourceId` each member and listed argument sampler is at the element -/// of its resource ID: the tables map each ID to itself. Under `Planned` (the default) the tables -/// are the planned ones. -#[test] -fn resource_id_placement_puts_members_and_samplers_at_their_ids() { - let t2d = shape(TextureType::Type2D, PixelFormat::RGBA8Unorm, 1, READ); - let mut state = BindState::default(); - let mut template = ResourceTemplate::default(); - for (token, id) in [(1, Some(5u64)), (2, Some(3)), (3, None)] { - let mut u = UsedResource::new( - ResourceClass::Texture(TextureFacts::new( - TextureType::Type2D, - PixelFormat::RGBA8Unorm, - )), - token, - ); - u.resource_id = id; - state.used_resources.push(u); - template.heap_members.push(HeapMember { - source: HeapSource::Used(token), - shape: t2d, - stages: vec![Stage::Kernel], - unreadable: false, - }); - } - for id in [7, 2] { - state - .argument_samplers - .push(crate::bind::ArgumentSampler::new( - SamplerDescriptor::new(), - id, - )); - } - let planned = PlannedHandleTable { - set: 0, - binding: 4, - stage: Stage::Kernel, - entries: 4, - }; - let entries = |state: &BindState| -> Vec<(u64, u32)> { - let out = handle_table_bytes(&template.heap_members, &[planned], state).expect("bytes"); - out[0] - .bytes - .chunks(16) - .map(|e| { - let word = |k: usize| u32::from_le_bytes(e[4 * k..4 * k + 4].try_into().unwrap()); - (u64::from(word(0)) | (u64::from(word(1)) << 32), word(2)) - }) - .collect() - }; - // Planned: elements 1 and 2 hold ids 5 and 3. - assert_eq!(entries(&state), vec![(0, 0), (0, 0), (3, 2), (5, 1)]); - - state.heap_placement = HeapPlacement::ResourceId; - assert_eq!(entries(&state), vec![(0, 0), (0, 0), (3, 3), (5, 5)]); - let samplers = PlannedHandleTable { - entries: 3, - ..planned - }; - let shape = ArgumentSamplersShape::of(&state.argument_samplers); - let out = sampler_table_bytes(&shape, &[samplers], &state).expect("sampler table"); - let ids: Vec<(u32, u32)> = out[0] - .bytes - .chunks(16) - .map(|e| { - let word = |k: usize| u32::from_le_bytes(e[4 * k..4 * k + 4].try_into().unwrap()); - (word(0), word(2)) - }) - .collect(); - assert_eq!(ids, vec![(0, 0), (2, 2), (7, 7)]); -} - -/// Under `HeapPlacement::ResourceId` a listed argument sampler that names an element is at that -/// element, wherever its resource ID lies: its table entry maps the ID there, under `Planned` too. -#[test] -fn resource_id_placement_puts_a_sampler_at_its_element() { - let mut state = BindState { - heap_placement: HeapPlacement::ResourceId, - ..BindState::default() - }; - for (id, element) in [(16380, 1), (2, 2)] { - state.argument_samplers.push(crate::bind::ArgumentSampler { - element: Some(element), - ..crate::bind::ArgumentSampler::new(SamplerDescriptor::new(), id) - }); - } - let planned = PlannedHandleTable { - set: 0, - binding: 4, - stage: Stage::Kernel, - entries: 3, - }; - let table = |state: &BindState| -> Vec<(u64, u32)> { - let shape = ArgumentSamplersShape::of(&state.argument_samplers); - let out = sampler_table_bytes(&shape, &[planned], state).expect("sampler table"); - out[0] - .bytes - .chunks(16) - .map(|e| { - let word = |k: usize| u32::from_le_bytes(e[4 * k..4 * k + 4].try_into().unwrap()); - (u64::from(word(0)) | (u64::from(word(1)) << 32), word(2)) - }) - .collect() - }; - assert_eq!(table(&state), vec![(0, 0), (2, 2), (16380, 1)]); - state.heap_placement = HeapPlacement::Planned; - assert_eq!(table(&state), vec![(0, 0), (2, 2), (16380, 1)]); -} - -/// A storage member is viewed through its direct format when its storage choice is `Identity` -/// without an alias, the view the class's formatless declaration serves, or a half-float format's -/// rounding, which a heap write takes from its handle's class. One whose choice is an alias a heap -/// access converts by (`storage_conversions`: an sRGB format through its UNORM twin where the -/// profile stores no sRGB format, a blue-first one through its RGBA-order twin where it stores -/// only that) is viewed through the alias, which the formatless declaration must serve and the -/// image lists among its view formats, while a swizzle that loses its class is refused; another -/// alias (`RGB9E5Float`'s word) is a typed refusal. An `A8Unorm` member held in red -/// (`StorageImageClass::AlphaInRed`) is viewed through its `R8_UNORM` image, whose texels a heap -/// access converts where the handle carries `A8Unorm`'s class: unswizzled, or swizzled to read as -/// unswizzled; a swizzle that moves its alpha carries another class and is refused. Each occurs on -/// the committed profiles; lavapipe views `RGBA8Unorm_sRGB`, `BGRA8Unorm_sRGB` and `BGR10A2Unorm` -/// members through their aliases, and the M3 Max's MoltenVK, which stores them, directly. -#[test] -fn a_storage_member_is_viewed_through_the_alias_a_heap_access_converts() { - let s2d = class( - ImageDim::D2, - false, - false, - SampledType::Float, - ImageAccess::Storage, - ); - let (mut direct, mut refused, mut in_red, mut converted) = (0, 0, 0, 0); - let mut lavapipe = BTreeSet::new(); - for (stem, p) in committed_profiles().expect("profiles") { - let planner = HeapPlanner { - profile: &p, - members: Vec::new(), - classes: vec![s2d], - tables: Vec::new(), - defaulted: BTreeSet::new(), - layouts: Vec::new(), - opaque_black: false, - filters: Vec::new(), - sampling: BTreeSet::new(), - write_rounding: BTreeMap::new(), - cross_neutral: BTreeMap::new(), - storage_reads: BTreeMap::new(), - sampler_tables: Vec::new(), - samplers: None, - directories: Vec::new(), - snapshots: Vec::new(), - addressed_tables: false, - function_tables: None, - planned: Vec::new(), - planned_samplers: Vec::new(), - planned_directories: Vec::new(), - diagnostics: Vec::new(), - }; - let conversions = storage_conversions(&p); - for pf in [ - PixelFormat::RGBA8Unorm, - PixelFormat::BGRA8Unorm, - PixelFormat::RGBA8UnormSRGB, - PixelFormat::BGRA8UnormSRGB, - PixelFormat::BGR10A2Unorm, - PixelFormat::RGB9E5Float, - PixelFormat::R16Float, - PixelFormat::RGBA16Float, - PixelFormat::A8Unorm, - ] { - let m = shape(TextureType::Type2D, pf, 1, WRITE); - let got = planner.view(&m, &s2d, vk::ImageLayout::GENERAL); - let half = matches!(pf, PixelFormat::R16Float | PixelFormat::RGBA16Float); - let use_ = heap_storage_use(&p); - use crate::metal::TextureSwizzle as S; - let swizzled = |swizzle: (S, S, S, S)| { - let mut swizzled = m; - if let TextureShape::Texture { swizzle: s, .. } = &mut swizzled { - *s = crate::metal::TextureSwizzleChannels::new( - swizzle.0, swizzle.1, swizzle.2, swizzle.3, - ); - } - planner.view(&swizzled, &s2d, vk::ImageLayout::GENERAL) - }; - let not_implemented = Err(BindError::Unsupported(Unsupported::not_implemented( - Feature::ArgumentBufferTextures, - ))); - if stem == "moltenvk-m3" - && !matches!(pf, PixelFormat::RGB9E5Float | PixelFormat::A8Unorm) - && !half - { - assert!( - got.as_ref() - .is_ok_and(|v| Some(v.format) == crate::metal::format::direct_format(pf)), - "{stem} {pf:?}: viewed directly" - ); - } - match storage_choice(pf, use_, &p) { - Ok(c) if half => { - let v = got.unwrap_or_else(|e| panic!("{stem} {pf:?} ({:?}): {e}", c.class)); - assert_eq!(Some(v.format), crate::metal::format::direct_format(pf)); - } - Ok(c) if c.class == StorageImageClass::Identity && c.alias.is_none() => { - let v = got.unwrap_or_else(|e| panic!("{stem} {pf:?}: {e}")); - assert_eq!(Some(v.format), crate::metal::format::direct_format(pf)); - assert_eq!(v.layout, vk::ImageLayout::GENERAL); - direct += 1; - } - Ok(c) if c.class == StorageImageClass::AlphaInRed => { - let v = got.unwrap_or_else(|e| panic!("{stem} {pf:?}: {e}")); - assert_eq!(v.format, vk::Format::R8_UNORM, "{stem}"); - for (swizzle, kept) in [ - ((S::Zero, S::Zero, S::Zero, S::Alpha), true), - ((S::Alpha, S::Zero, S::Zero, S::One), false), - ] { - let got = swizzled(swizzle); - match kept { - true => assert_eq!( - got.map(|v| v.format), - Ok(vk::Format::R8_UNORM), - "{stem} {swizzle:?}" - ), - false => assert_eq!(got, not_implemented, "{stem} {swizzle:?}"), - } - } - in_red += 1; - } - Ok(c) - if c.alias.is_some() - && conversions.contains(&StorageConversion { - index: crate::metal::texel_format::heap_class_index( - pf, - crate::metal::TextureSwizzleChannels::DEFAULT, - ), - red_blue: crate::metal::format::red_blue_exchanged(pf), - class: c.class, - }) => - { - match without_format_gaps(c.vk_format, use_, &p).is_empty() { - true => { - let v = got.unwrap_or_else(|e| panic!("{stem} {pf:?}: {e}")); - assert_eq!(v.format, c.vk_format, "{stem} {pf:?}"); - assert!(crate::metal::format::storage_view_formats(pf, &p) - .contains(&v.format)); - assert_eq!( - swizzled((S::Blue, S::Green, S::Red, S::Alpha)), - not_implemented, - "{stem} {pf:?}: a swizzle that loses the class" - ); - if stem == "lavapipe" { - lavapipe.insert(pf); - } - converted += 1; - } - false => assert!(got.is_err(), "{stem} {pf:?}"), - } - } - Ok(_) => { - assert_eq!(got, not_implemented, "{stem} {pf:?}"); - refused += 1; - } - Err(_) => assert!(got.is_err(), "{stem} {pf:?}"), - } - } - } - assert!( - direct > 0 && refused > 0 && in_red > 0 && converted > 0, - "direct {direct}, refused {refused}, in red {in_red}, converted {converted}" - ); - assert_eq!( - lavapipe, - BTreeSet::from([ - PixelFormat::RGBA8UnormSRGB, - PixelFormat::BGRA8UnormSRGB, - PixelFormat::BGR10A2Unorm, - ]) - ); -} - /// On lavapipe a heap's storage conversions are the alias a slot takes for each of the three /// formats `read-write-tier-held` sweeps beyond every tier, keyed apart from their red-first and /// UNORM kin by class and red-blue order; on the M3 Max's MoltenVK, which stores each format @@ -709,520 +208,9 @@ fn a_heap_converts_by_class_and_red_blue_order() { } } -/// One layout per bound texture: a slot whose own write or heap element is a storage image is -/// `GENERAL` in every write naming it (plain, combined, heap), and nothing else changes: a slot -/// only sampled, a used member, and a neutral keep theirs. -#[test] -fn a_storage_write_makes_every_write_of_its_slot_general() { - let s = |index| SlotRef { - stage: Stage::Kernel, - class: SlotClass::Texture, - index, - }; - let ro = vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL; - let general = vk::ImageLayout::GENERAL; - let view = |layout| ImageViewDesc { - view_type: vk::ImageViewType::TYPE_2D, - format: vk::Format::R8G8B8A8_UNORM, - aspect: vk::ImageAspectFlags::COLOR, - layout, - components: vk::ComponentMapping::IDENTITY, - level: None, - shader_swizzle: false, - }; - let sampled = HandleClass::Image(class( - ImageDim::D2, - false, - false, - SampledType::Float, - ImageAccess::Sampled, - )); - let storage = HandleClass::Image(class( - ImageDim::D2, - false, - false, - SampledType::Float, - ImageAccess::Storage, - )); - let write = |set, binding, array_element, ty, source| DescriptorWrite { - set, - binding, - array_element, - ty, - source, - }; - let entry = |class, element, source, layout| WriteSource::HeapEntry { - class, - element, - source, - view: view(layout), - }; - let HandleClass::Image(storage_image) = storage else { - unreachable!() - }; - let unbound = WriteSource::Neutral(neutral(&storage_image).expect("neutral")); - let (si, sm) = ( - vk::DescriptorType::STORAGE_IMAGE, - vk::DescriptorType::SAMPLED_IMAGE, - ); - let mut writes = vec![ - // Slot 0: a storage slot whose texture the sampled heap holds. - write( - 0, - 0, - 0, - si, - WriteSource::Texture { - slot: s(0), - view: view(general), - }, - ), - write(1, 0, 1, sm, entry(sampled, 1, HeapSource::Bound(s(0)), ro)), - // Slot 1: a sampled and a combined slot whose texture a storage heap array holds. - write( - 0, - 1, - 0, - sm, - WriteSource::Texture { - slot: s(1), - view: view(ro), - }, - ), - write( - 0, - 2, - 0, - vk::DescriptorType::COMBINED_IMAGE_SAMPLER, - WriteSource::CombinedImageSampler { - image: ImageSource::Texture { - slot: s(1), - view: view(ro), - }, - sampler: crate::bind::plan::SamplerSource::Immutable, - }, - ), - write( - 1, - 0, - 2, - sm, - entry(sampled, 2, HeapSource::Bound(s(1)), general), - ), - write( - 1, - 1, - 2, - si, - entry(storage, 2, HeapSource::Bound(s(1)), general), - ), - // Slot 2 only sampled, a used member, and a neutral: unchanged. - write( - 0, - 3, - 0, - sm, - WriteSource::Texture { - slot: s(2), - view: view(ro), - }, - ), - write(1, 0, 3, sm, entry(sampled, 3, HeapSource::Used(7), ro)), - write(1, 1, 1, si, unbound), - ]; - let before = writes.clone(); - one_layout_per_slot(&mut writes); - let layouts: Vec> = writes - .iter_mut() - .map(|w| match &mut w.source { - WriteSource::HeapEntry { view, .. } => Some(view.layout), - other => slot_view(other).map(|(_, v)| v.layout), - }) - .collect(); - assert_eq!( - layouts, - vec![ - Some(general), - Some(general), - Some(general), - Some(general), - Some(general), - Some(general), - Some(ro), - Some(ro), - None, - ] - ); - // Only layouts change. - for (a, b) in writes.iter_mut().zip(&before) { - if let Some((_, v)) = slot_view(&mut a.source) { - v.layout = vk::ImageLayout::UNDEFINED; - } - let mut b = b.clone(); - if let Some((_, v)) = slot_view(&mut b.source) { - v.layout = vk::ImageLayout::UNDEFINED; - } - assert_eq!(*a, b); - } -} - -/// A heap member is checked at one level: the bind state's texture of more levels is that member -/// (a heap array views level 0 alone), and one of another format is not. -#[test] -fn a_member_s_level_count_is_not_the_plan_s() { - let mut facts = TextureFacts::new(TextureType::Type2D, PixelFormat::RGBA8Unorm); - facts.usage = READ; - facts.mipmap_level_count = 3; - let mut used = UsedResource::new(ResourceClass::Texture(facts), 7); - used.resource_id = Some(42); - let mut state = BindState::default(); - state.used_resources.push(used); - let by_token = UsedByToken::Gathered(BTreeMap::from([( - 7, - state.used_resources.iter().collect::>(), - )])); - let member = |shape: TextureShape| HeapMember { - source: HeapSource::Used(7), - shape, - stages: vec![Stage::Kernel], - unreadable: false, - }; - let planned = facts.shape().at_one_level(); - assert_ne!(planned, facts.shape()); - assert_eq!( - member_id(&member(planned), &by_token, &state).unwrap(), - Some(42) - ); - assert_eq!( - member_id(&member(facts.shape()), &by_token, &state).unwrap(), - Some(42) - ); - let other = shape(TextureType::Type2D, PixelFormat::R32Float, 1, READ); - assert!(member_id(&member(other), &by_token, &state).is_err()); -} - -/// A texture of a form a heap reads (`ExtendedRange::HEAP_READ`: unswizzled, of one sample, not -/// sparse) is held raw: the unsigned integer class of its shape views it as a slot's read does -/// (its raw format), and the float class holds its neutral (`Fit::Raw`). A plan's float array -/// writes the neutral, or refuses it where a stage that enters it samples heap textures. -#[test] -fn a_form_a_heap_reads_is_held_raw_in_the_unsigned_class() { - use crate::metal::format::ExtendedRange; - use ImageAccess::Sampled; - use SampledType::{Float, Sint, Uint}; - fn refused() -> Result { - Err(BindError::Unsupported(Unsupported::not_implemented( - Feature::ArgumentBufferTextures, - ))) - } - let f2d = class(ImageDim::D2, false, false, Float, Sampled); - let u2d = class(ImageDim::D2, false, false, Uint, Sampled); - let i2d = class(ImageDim::D2, false, false, Sint, Sampled); - let layout = vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL; - let read: Vec = PixelFormat::ALL - .iter() - .copied() - .filter(|&pf| { - ExtendedRange::of(pf) - .and_then(ExtendedRange::heap_read) - .is_some() - }) - .collect(); - assert_eq!(read.len(), ExtendedRange::HEAP_READ.len()); - let profiles = committed_profiles().expect("profiles"); - for (stem, p) in &profiles { - for &pf in &read { - let s = shape(TextureType::Type2D, pf, 1, READ); - assert_eq!(fit(&s, &f2d), Fit::Raw, "{pf:?}"); - assert_eq!(fit(&s, &u2d), Fit::Holds, "{pf:?}"); - assert_eq!(fit(&s, &i2d), Fit::NumericType, "{pf:?}"); - let slot = crate::bind::plan::resources::sampled_view(p, pf, &u2d) - .unwrap_or_else(|e| panic!("{stem} {pf:?}: {e}")); - assert_eq!(slot.format, ExtendedRange::of(pf).unwrap().raw_format()); - } - } - - // A plan's float array holds the neutral, and its unsigned one the raw view; a stage that - // samples heap textures refuses the float array. - let (_, p) = &profiles[0]; - let pf = read[0]; - let planner = |classes: Vec, sampling: BTreeSet| HeapPlanner { - profile: p, - members: vec![HeapMember { - source: HeapSource::Used(1), - shape: shape(TextureType::Type2D, pf, 1, READ), - stages: vec![Stage::Kernel], - unreadable: false, - }], - classes, - tables: Vec::new(), - defaulted: BTreeSet::new(), - layouts: vec![layout], - opaque_black: false, - filters: Vec::new(), - sampling, - write_rounding: BTreeMap::new(), - cross_neutral: BTreeMap::new(), - storage_reads: BTreeMap::new(), - sampler_tables: Vec::new(), - samplers: None, - directories: Vec::new(), - snapshots: Vec::new(), - addressed_tables: false, - function_tables: None, - planned: Vec::new(), - planned_samplers: Vec::new(), - planned_directories: Vec::new(), - diagnostics: Vec::new(), - }; - let binding = |c: ImageHandleClass| DescriptorBinding { - binding: 0, - ty: vk::DescriptorType::SAMPLED_IMAGE, - count: 16, - stages: vk::ShaderStageFlags::COMPUTE, - source: BindingSource::Heap(HandleClass::Image(c)), - immutable_sampler: None, - flags: vk::DescriptorBindingFlags::empty(), - variables: 1, - immutable_samplers: Vec::new(), - }; - let mut reads = planner(vec![f2d, u2d], BTreeSet::new()); - let float = reads.array(1, &binding(f2d)).expect("float array"); - assert!( - matches!(float[1].source, WriteSource::Neutral(_)), - "{:?}", - float[1] - ); - let uint = reads.array(1, &binding(u2d)).expect("unsigned array"); - assert!( - matches!(uint[1].source, WriteSource::HeapEntry { view, .. } - if view.format == ExtendedRange::of(pf).unwrap().raw_format()), - "{:?}", - uint[1] - ); - let mut samples = planner(vec![f2d, u2d], BTreeSet::from([Stage::Kernel])); - assert_eq!(samples.array(1, &binding(f2d)), refused()); - let mut other = planner(vec![f2d, u2d], BTreeSet::from([Stage::Fragment])); - assert!( - other.array(1, &binding(f2d)).is_ok(), - "another stage samples" - ); -} - -/// A storage class array refuses a member that a stage of `RuntimeFact::HeapWriteRounding` reaches -/// where the stage's mode-2 write to it is unbuilt (`RG11B10Float`, `RGB9E5Float`, and a -/// half-float texture where the stage writes `float` texels), naming -/// `PrivateRenderField::TextureWriteRounding`; any other member, and one only another stage -/// reaches, is written as before. -#[test] -fn a_heap_member_a_mode_two_write_would_round_is_refused() { - use crate::error::PrivateRenderField; - let s2d = class( - ImageDim::D2, - false, - false, - SampledType::Float, - ImageAccess::Storage, - ); - let refused = Err(BindError::Unsupported(Unsupported::not_implemented( - Feature::PrivateRenderState(PrivateRenderField::TextureWriteRounding), - ))); - let binding = DescriptorBinding { - binding: 0, - ty: vk::DescriptorType::STORAGE_IMAGE, - count: 16, - stages: vk::ShaderStageFlags::FRAGMENT, - source: BindingSource::Heap(HandleClass::Image(s2d)), - immutable_sampler: None, - flags: vk::DescriptorBindingFlags::empty(), - variables: 1, - immutable_samplers: Vec::new(), - }; - let mut checked = 0; - for (stem, p) in committed_profiles().expect("profiles") { - for pf in [ - PixelFormat::RGBA8Unorm, - PixelFormat::R32Float, - PixelFormat::RG16Float, - PixelFormat::RGBA16Float, - PixelFormat::RG11B10Float, - PixelFormat::RGB9E5Float, - ] { - let member = shape(TextureType::Type2D, pf, 1, READ | WRITE); - if fit(&member, &s2d) != Fit::Holds { - continue; - } - for (stage, halves) in [ - (Stage::Fragment, true), - (Stage::Fragment, false), - (Stage::Vertex, true), - ] { - let mut planner = HeapPlanner { - profile: &p, - members: vec![HeapMember { - source: HeapSource::Used(1), - shape: member, - stages: vec![Stage::Fragment], - unreadable: false, - }], - classes: vec![s2d], - tables: Vec::new(), - defaulted: BTreeSet::new(), - layouts: vec![vk::ImageLayout::GENERAL], - opaque_black: false, - filters: Vec::new(), - sampling: BTreeSet::new(), - write_rounding: BTreeMap::from([(stage, halves)]), - cross_neutral: BTreeMap::new(), - storage_reads: BTreeMap::new(), - sampler_tables: Vec::new(), - samplers: None, - directories: Vec::new(), - snapshots: Vec::new(), - addressed_tables: false, - function_tables: None, - planned: Vec::new(), - planned_samplers: Vec::new(), - planned_directories: Vec::new(), - diagnostics: Vec::new(), - }; - let what = format!("{stem} {pf:?} {stage:?} halves {halves}"); - let rounds = stage == Stage::Fragment - && crate::metal::texel_format::mode_two_rounds(pf, halves); - let got = planner.array(1, &binding); - match rounds { - true => assert_eq!(got, refused, "{what}"), - false => assert_ne!(got, refused, "{what}"), - } - checked += usize::from(rounds); - } - } - } - assert!(checked > 0, "no profile holds a format the check refuses"); -} - -/// A state listed in token order (`BindState::used_in_token_order`) is searched, not gathered by -/// token, and gives the same tables as the same state listed so without the flag: among a buffer -/// per token around them, with a member listed twice under one id, and the same internal errors -/// for a member listed with two ids and a member not listed. -#[test] -fn a_state_in_token_order_finds_its_members_by_search() { - let t2d = shape(TextureType::Type2D, PixelFormat::RGBA8Unorm, 1, READ); - let texture = || { - ResourceClass::Texture(TextureFacts::new( - TextureType::Type2D, - PixelFormat::RGBA8Unorm, - )) - }; - let mut state = BindState::default(); - let mut template = ResourceTemplate::default(); - for token in 0..200u32 { - let member = token % 50 == 7; - let class = match member { - true => texture(), - false => ResourceClass::Buffer, - }; - let mut u = UsedResource::new(class, token); - u.resource_id = member.then_some(u64::from(token) + 1); - state.used_resources.push(u); - if token == 57 { - state.used_resources.push(u); - } - if member { - template.heap_members.push(HeapMember { - source: HeapSource::Used(token), - shape: t2d, - stages: vec![Stage::Kernel], - unreadable: false, - }); - } - } - state.heap_placement = HeapPlacement::ResourceId; - let planned = PlannedHandleTable { - set: 0, - binding: 4, - stage: Stage::Kernel, - entries: 8, - }; - let mut ordered = state.clone(); - ordered.used_in_token_order = true; - assert!(matches!(UsedByToken::of(&ordered), UsedByToken::Listed(..))); - assert!(matches!(UsedByToken::of(&state), UsedByToken::Gathered(_))); - let tables = |state: &BindState| handle_table_bytes(&template.heap_members, &[planned], state); - assert_eq!( - tables(&ordered).expect("ordered"), - tables(&state).expect("any") - ); - // Member 107 listed again with another id, beside its first entry. - for state in [&state, &ordered] { - let mut twice = state.clone(); - let at = 1 + twice - .used_resources - .iter() - .position(|u| u.token == 107) - .unwrap(); - let mut again = twice.used_resources[at - 1]; - again.resource_id = Some(999); - twice.used_resources.insert(at, again); - assert!(matches!(tables(&twice), Err(BindError::Internal(_)))); - let mut missing = state.clone(); - missing.used_resources.retain(|u| u.token != 157); - assert!(matches!(tables(&missing), Err(BindError::Internal(_)))); - } -} - -/// A state listed in token order finds its heap members' entries searching forward from where -/// the last member's ended, the plan's members ascending by token (`members`): 4096 textures, -/// each beside a buffer, compare a few entries a member (an upper bound of 8), not the logarithm -/// of the 8192 listed twice over, answering as the same state in no order does. -#[test] -fn a_state_in_token_order_finds_its_members_searching_forward() { - const MEMBERS: u32 = 4096; - let t2d = shape(TextureType::Type2D, PixelFormat::RGBA8Unorm, 1, READ); - let mut state = BindState::default(); - let mut template = ResourceTemplate::default(); - for member in 0..MEMBERS { - let token = 2 * member + 1; - state - .used_resources - .push(UsedResource::new(ResourceClass::Buffer, token - 1)); - let class = ResourceClass::Texture(TextureFacts::new( - TextureType::Type2D, - PixelFormat::RGBA8Unorm, - )); - let mut texture = UsedResource::new(class, token); - texture.resource_id = Some(u64::from(token) + 1); - state.used_resources.push(texture); - template.heap_members.push(HeapMember { - source: HeapSource::Used(token), - shape: t2d, - stages: vec![Stage::Kernel], - unreadable: false, - }); - } - state.heap_placement = HeapPlacement::ResourceId; - let planned = PlannedHandleTable { - set: 0, - binding: 4, - stage: Stage::Kernel, - entries: 2 * MEMBERS + 8, - }; - let mut ordered = state.clone(); - ordered.used_in_token_order = true; - let looked_at = |work: &dyn Fn()| { - LISTED_LOOKED_AT.with(|looked| looked.set(0)); - work(); - LISTED_LOOKED_AT.with(Cell::get) - }; - let tables = |state: &BindState| handle_table_bytes(&template.heap_members, &[planned], state); - let bound = 8 * u64::from(MEMBERS); - let looked = looked_at(&|| assert_eq!(tables(&ordered).unwrap(), tables(&state).unwrap())); - assert!(looked <= bound, "the tables' lookups compared {looked}"); -} - /// A texture buffer fits only a texel-buffer class: the one of its numeric type holds it, where its -/// usage has the class's access (its facts' usage; a slot's bound texture buffer states none), and -/// one of another numeric type fits it in everything but that; no image class fits it. +/// usage has the class's access, and one of another numeric type fits it in everything but that; +/// no image class fits it. #[test] fn a_texture_buffer_is_held_by_the_texel_buffer_class_of_its_numeric_type() { use ImageAccess::{Sampled, Storage}; @@ -1232,19 +220,11 @@ fn a_texture_buffer_is_held_by_the_texel_buffer_class_of_its_numeric_type() { let fsb = class(ImageDim::Buffer, false, false, Float, Storage); let f2d = class(ImageDim::D2, false, false, Float, Sampled); let rgba = PixelFormat::RGBA32Float; - let bound = TextureShape::Buffer { - pixel_format: rgba, - swizzle: crate::metal::TextureSwizzleChannels::DEFAULT, - parts: 1, - }; let read = shape(TextureType::TextureBuffer, rgba, 1, READ); let write = shape(TextureType::TextureBuffer, rgba, 1, WRITE); - for s in [&bound, &read] { - assert_eq!(fit(s, &fb), Fit::Holds); - assert_eq!(fit(s, &ub), Fit::NumericType); - assert_eq!(fit(s, &f2d), Fit::No); - } - assert_eq!(fit(&bound, &fsb), Fit::Holds); + assert_eq!(fit(&read, &fb), Fit::Holds); + assert_eq!(fit(&read, &ub), Fit::NumericType); + assert_eq!(fit(&read, &f2d), Fit::No); assert_eq!(fit(&read, &fsb), Fit::No); assert_eq!(fit(&write, &fsb), Fit::Holds); assert_eq!(fit(&write, &fb), Fit::No); diff --git a/crates/metal2vulkan/src/bind/instantiate.rs b/crates/metal2vulkan/src/bind/instantiate.rs deleted file mode 100644 index e06fce0ef..000000000 --- a/crates/metal2vulkan/src/bind/instantiate.rs +++ /dev/null @@ -1,861 +0,0 @@ -//! Per-draw and per-dispatch instantiation outputs shared by draws and dispatches, and the -//! arithmetic both share: descriptor ranges and residual bind offsets (`descriptor_range`), and the -//! resident root table ([`RootTable`]), and the buffer-slot, push-field, and texel-buffer -//! instantiation both share (`bind_buffers`, `slot_field`, `put`, `texel_ranges`). A push -//! field's bytes are held in place ([`FieldBytes`]), so a draw's fields allocate nothing. - -use crate::bind::plan::compute::internal; -use crate::bind::plan::{BoundKind, PlannedBuffer, ResourceTemplate}; -pub(crate) use crate::bind::resident::RootEntry; -use crate::bind::state::{BindState, BoundBuffer, BoundTexture}; -use crate::error::{BindError, Feature, Unsupported}; -use crate::memory::roots::{ - BIND_OFFSET, ENTRY_BYTES, GUEST, HOST, RESIDENT_COUNT, RESIDENT_FIRST, SINK_ROOT, SIZE, -}; -use crate::pipeline::interface::{BufferForm, PushLoc, Window}; -use crate::pipeline::sym::{PushField, SlotRef}; -use crate::vk; - -/// Push-constant bytes for one stage range (`vkCmdPushConstants`). -#[non_exhaustive] -#[derive(Clone, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct PushConstantWrite { - pub stages: vk::ShaderStageFlags, - pub offset: u32, - pub bytes: Vec, -} - -/// Bytes the consumer uploads into the buffer behind a plan binding (argument table, handle -/// table) before recording the draw or dispatch. -#[non_exhaustive] -#[derive(Clone, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct DescriptorBytes { - pub set: u32, - pub binding: u32, - pub bytes: Vec, -} - -/// The byte window of one bound buffer slot that this draw or dispatch can touch: the staging and -/// writeback window. `window` is relative to the bind offset, as in the interface. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct BufferExtent { - pub slot: SlotRef, - pub window: Window, -} - -/// A push-constant field the consumer fills after uploading `descriptor_bytes`: a declared field, -/// not a patch. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub enum PushHole { - /// The device address of the uploaded resident root table ([`RootTable`]), as a `u64` at - /// `offset` (absolute, in the push-constant block) of every region's push bytes. - RootTableAddress { - stages: vk::ShaderStageFlags, - offset: u32, - }, - /// The device address of the command buffer's `ExecutionStatus` buffer (a function that counts - /// resident-set misses, reaches it by address), as a `u64` at `offset` of every region's push - /// bytes. - ExecutionStatusAddress { - stages: vk::ShaderStageFlags, - offset: u32, - }, - /// The device address of the replayed indirect command buffer's record storage (its header), as - /// a `u64` at `offset` of the device replay's preprocess push bytes. - CommandRecordsAddress { - stages: vk::ShaderStageFlags, - offset: u32, - }, - /// The device address of the region record a device-replay variant's dispatch reads: the - /// dispatch's command and region's in the replay's scratch, as a `u64` at `offset` of the - /// variant's push bytes. A flat variant's dispatch outside a - /// replay (`BindingPlan::instantiate_dispatch`) reads the record its preprocess wrote beside - /// the group counts. A mesh draw of a folded object function (`TASK_EXT`) reads its scratch's - /// region record: the arguments pass's (`DrawCommands::mesh_arguments`) or the uploaded fold's - /// (`DrawCommands::object_fold`), at the scratch's first byte. - ReplayRegionAddress { - stages: vk::ShaderStageFlags, - offset: u32, - }, - /// The device address of a de-indexed draw's first index (`VariantKey::primitive_id_indices`), - /// as a `u64` at `offset` of the variant's vertex push bytes: the draw's index buffer's - /// address plus its index offset, which the binder requires to be a multiple of the index - /// size, in a buffer of `SHADER_DEVICE_ADDRESS` usage whose address is a multiple of 4; or a - /// private list form draw's list (`VariantKey::private_list`). The draw reads its indices - /// there in the vertex stage (`DrawCommands::uses`, as storage); a `u16` index is read in the - /// aligned 4-byte word that holds it, which lies inside the `VkBuffer` an `IndexBufferRef` - /// describes. - CaptureIndexAddress { - stages: vk::ShaderStageFlags, - offset: u32, - }, - /// The device address of a merged draw replay's header in the replay's scratch, as a `u64` at `offset` of a merged variant's vertex push bytes - /// (`VariantKey::merged_draws`, `PushField::MergedDrawAddress`). - MergedDrawAddress { - stages: vk::ShaderStageFlags, - offset: u32, - }, -} - -/// A consumer-owned indirect-argument buffer and the byte offset of the arguments. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct IndirectRef { - /// The consumer's id for the buffer. - pub token: u32, - pub offset: u64, -} - -/// A consumer-owned index buffer. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct IndexBufferRef { - /// The consumer's id for the buffer. - pub token: u32, - /// The end of the buffer's bytes (`MTLBuffer.length`), against which a draw's indices are - /// bounded ([`IndexBufferRef::fetch_end`]), in the offsets the draw binds the `VkBuffer` at - /// (the length itself where the consumer binds the buffer from its start). The buffer's byte 0 - /// lies at a multiple of 4 bytes of those offsets, and the `VkBuffer` behind it holds at least - /// the length rounded up to 16 bytes (the padding). - pub length: u64, -} - -impl IndexBufferRef { - /// The consumer's index buffer `token`, `length` bytes long. - pub fn new(token: u32, length: u64) -> IndexBufferRef { - IndexBufferRef { token, length } - } - - /// Where Metal's index fetch from `index_offset` stops reading bytes at their position: the - /// length rounded up to 4 bytes where the offset lies before the length, so a partial last - /// index reads the bytes past the length up to there (the padding, or a heap's bytes after a - /// placed buffer); the length otherwise, where no byte lies inside from the offset. A position - /// from there on reads index 0. Measured on an Apple M4 (macOS 27.0.1) from offsets that are - /// multiples of 4; from an offset at or past the length Metal reads the memory past the buffer, - /// which the bound replaces with index 0, a contained near-equivalent. - pub fn fetch_end(&self, index_offset: u64) -> u64 { - if index_offset < self.length { - self.length - .checked_next_multiple_of(4) - .unwrap_or(self.length) - } else { - self.length - } - } -} - -/// A byte range of a buffer: `range` bytes from `offset`. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct BufferRange { - pub offset: u64, - pub range: u64, -} - -/// The range a buffer descriptor of the plan binds for this draw or dispatch. For a -/// `WriteSource::Buffer`, `range.offset` is from the start of the bound allocation; for a -/// `WriteSource::InlineBytes`, from the start of the consumer's upload of the bytes, which the -/// consumer places at an offset aligned to the descriptor type's `min*BufferOffsetAlignment`. -/// The consumer binds exactly this range, never more. It is at least 16 bytes, inside the -/// allocation padded to 16 bytes, and its offset is a multiple of the alignment. For a -/// `WriteSource::TexelBuffer`, the bytes the texel buffer view of the binding's array element -/// `element` views in the bound texture buffer's `VkBuffer` (`texel_ranges`): element 0 for one -/// view, and element `k` for part `k` of a texture buffer bound through its parts -/// (`bind::texel_parts`). -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct DescriptorRange { - pub set: u32, - pub binding: u32, - /// The binding's array element the range is bound at: 0 but for a texture buffer's parts. - #[cfg_attr(feature = "serde", serde(default))] - pub element: u32, - pub range: BufferRange, -} - -/// The resident root table of a draw or dispatch: 32-byte entries `{host, guest, size, -/// bind_offset}: u64`, little-endian. -/// -/// Entry 0 is the null root (zero). Entry 1 is the sink: its `host` field (at -/// [`RootTable::SINK_HOST_OFFSET`]) is left 0 for the consumer to fill with the device address of -/// its `NeutralResource::Sink`; its `guest` and `size` fields hold the resident set's first root -/// `R0` and entry count `N`. Entry `2 + n` is the `BufferForm::Psb` slot `[[buffer(n)]]` (zero -/// when unbound, so every access through it is contained). Entries `R0 .. R0 + N` are the -/// resident set, sorted by guest address and disjoint, each with `bind_offset = 0`. The consumer -/// writes the sink address, uploads the bytes to memory with a 16-byte-aligned device address, -/// and fills `PushHole::RootTableAddress` with that address. -/// -/// `R0` counts 32-byte entries from the table's own address, modulo `2^64`, so a consumer may -/// point the table at a resident set it uploaded elsewhere: the table and the set -/// 32-byte-aligned, and the set holding at least the table's own ranges, it writes the set's address and its entry count over the -/// sink entry's `guest` and `size` fields. -#[non_exhaustive] -#[derive(Clone, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct RootTable { - pub bytes: Vec, -} - -impl RootTable { - /// Byte offset of the sink entry's `host` field, which the consumer fills. - pub const SINK_HOST_OFFSET: u32 = (SINK_ROOT * ENTRY_BYTES + HOST) as u32; - - /// The table with `statics` (entry `2 + n` for each `(n, entry)`, every `n < first - 2`) and - /// the resident set `resident` (already coalesced, - /// [`resident_set`](crate::bind::resident::resident_set)) from root `first`. - pub(crate) fn build(statics: &[(u32, RootEntry)], first: u64, resident: &[RootEntry]) -> Self { - let count = first as usize + resident.len(); - let mut bytes = vec![0u8; count * ENTRY_BYTES as usize]; - let mut put = |root: u64, field: u64, value: u64| { - let at = (root * ENTRY_BYTES + field) as usize; - bytes[at..at + 8].copy_from_slice(&value.to_le_bytes()); - }; - put(SINK_ROOT, RESIDENT_FIRST, first); - put(SINK_ROOT, RESIDENT_COUNT, resident.len() as u64); - let statics = statics.iter().map(|(n, e)| (2 + u64::from(*n), e)); - let resident = (first..).zip(resident); - for (root, e) in statics.chain(resident) { - put(root, HOST, e.host); - put(root, GUEST, e.guest); - put(root, SIZE, e.size); - put(root, BIND_OFFSET, e.bind_offset); - } - RootTable { bytes } - } -} - -/// One allocation of a resident set. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct ResidentRange { - /// Its Vulkan device address. - pub host: u64, - /// Its Metal address. - pub guest: u64, - /// Its length in bytes, which a set pads to a multiple of 16. - pub length: u64, -} - -/// `n` rounded up to a multiple of 16 (the allocation padding contract). -pub(crate) fn padded(n: u64) -> u64 { - n.saturating_add(15) & !15 -} - -/// Why [`descriptor_range`] has no range to bind. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum RangeError { - /// The allocation is empty: nothing can back a descriptor. - Empty, - /// The range exceeds the descriptor type's maximum (`needed` bytes). - TooLarge { needed: u64 }, -} - -/// The descriptor range and the `SlotBindOffset` residual of a descriptor-form slot, in checked -/// `i128` arithmetic, for an allocation of `length` bytes (padded to 16) bound at `bind_offset`, -/// with the slot's proven `window`, the descriptor base `alignment` `A` (at least 4 is used; a -/// Metal buffer slot's plan gives `max(minStorageBufferOffsetAlignment, 16)`, so a descriptor byte is -/// congruent to its Metal address modulo 16), and the view's maximum range `max_range`. -/// -/// - `Bounded{start, len}`: from `align_down(max(0, bind_offset + start), A)` to -/// `round_up(bind_offset + start + len, 16)`; `Whole`: from `align_down(bind_offset, A)` to the -/// padded end. The end is clamped to the padded allocation. -/// - A range shorter than 16 bytes (a window at or past the end of the allocation) is widened to -/// 16 bytes inside the allocation (its start moves down to an aligned offset), so a bound range -/// is never empty and a contained load of word 0 stays inside it. -/// - The residual is `bind_offset` minus the range's start, modulo `2^32`: a leaf reads byte -/// `residual + m` of the range for the `u32` Metal offset `m` from the bind offset. -pub(crate) fn descriptor_range( - bind_offset: u64, - length: u64, - window: Window, - alignment: u64, - max_range: u64, -) -> Result<(BufferRange, u32), RangeError> { - let end = i128::from(padded(length)); - if end == 0 { - return Err(RangeError::Empty); - } - let a = i128::from(alignment.max(4)); - let down = |x: i128| x - x.rem_euclid(a); - let b = i128::from(bind_offset); - let (mut lo, hi) = match window { - Window::Bounded { start, len } => { - let s = b + i128::from(start); - (down(s.max(0)), (s + i128::from(len) + 15) & !15) - } - Window::Whole => (down(b), end), - }; - let mut hi = hi.min(end); - if hi - lo < 16 { - lo = lo.min(down(end - 16)); - hi = hi.max(lo + 16); - } - // `0 <= lo < hi <= end <= 2^64`: both fit `u64`. - let range = (hi - lo) as u64; - if range > max_range { - return Err(RangeError::TooLarge { needed: range }); - } - let residual = (b - lo).rem_euclid(1 << 32) as u32; - Ok(( - BufferRange { - offset: lo as u64, - range, - }, - residual, - )) -} - -/// The descriptor range and the `SlotBindOffset` residual of a slot of `window` read at its -/// residual, bound at `bind_offset` of an allocation of `length` bytes (padded to 16), for the -/// descriptor base alignment `alignment` (at least 4 used) and the view's maximum range -/// `max_range`: a range that a run of bind offsets of the allocation shares, so a draw or dispatch -/// that moves only the slot's offset binds the same descriptor (and keeps its set 0) and moves -/// only its residual. For a `Bounded` window, `M` the smaller of `max_range` and `2^32` (a `u32` -/// residual and offset reach no further): the padded allocation whole where it fits `M`, from 0, -/// its residual the bind offset; else the block of `h` bytes the window's first byte lies in (`h` -/// the largest power of two at most half of `M`, a multiple of the alignment), to `M` past the -/// block's start or the padded end. A window of at most `M - h` bytes (at least half of `M`) that -/// starts in a block ends before `M` past the block's start, so it never straddles its block's -/// range; a longer one takes no block. Like [`descriptor_range`]'s, the range starts at a multiple of the -/// alignment, holds at least 16 bytes inside the padded allocation, and holds each byte `m` of -/// the window inside the allocation at `residual + m` (modulo `2^32`). `None` where no such range -/// holds the window (a `Whole` one, one at or past the padded end, one longer than its block -/// allows): the caller takes [`descriptor_range`]'s. -pub(crate) fn shared_range( - bind_offset: u64, - length: u64, - window: Window, - alignment: u64, - max_range: u64, -) -> Option<(BufferRange, u32)> { - let Window::Bounded { start, len } = window else { - return None; - }; - let end = i128::from(padded(length)); - let b = i128::from(bind_offset); - if b >= end { - return None; - } - let first = (b + i128::from(start)).max(0); - let last = (b + i128::from(start) + i128::from(len)).min(end); - // No range past `2^32` bytes: a `u32` residual and offset reach no further. - let max_range = max_range.min(1 << 32); - let (lo, hi) = if end <= i128::from(max_range) { - (0, end) - } else { - let a = alignment.max(4); - let block = 1u64 << (max_range / 2).checked_ilog2()?; - // The window's size limit: starting in the block, it ends inside the block's range. - if block < a || !block.is_multiple_of(a) || len > max_range - block { - return None; - } - let block = i128::from(block); - let lo = first - first.rem_euclid(block); - (lo, (lo + i128::from(max_range)).min(end)) - }; - debug_assert!(last <= hi, "a window past its shared range"); - let residual = b - lo; - if first >= hi || hi - lo < 16 || residual.abs() >= 1 << 32 { - return None; - } - // `0 <= lo < hi <= end <= 2^64`: both fit `u64`. - let range = BufferRange { - offset: lo as u64, - range: (hi - lo) as u64, - }; - Some((range, residual.rem_euclid(1 << 32) as u32)) -} - -/// The descriptor range and the `SlotBindOffset` residual of planned buffer slot `pb` bound at -/// `bind_offset` of an allocation of `length` bytes. Its function reads byte `residual + m` of the -/// range for the Metal offset `m`, the byte it read of the range from the bind offset, so a slot -/// binds a range its bind offsets share: -/// -/// - a `Whole` window takes its range from the start of the bound buffer's space (offset 0) to the -/// padded end, its residual the bind offset, so every bind offset of one buffer binds one -/// descriptor and a draw or dispatch that moves only the offset keeps its set 0 (a dynamic one's -/// offset moves with the space alone); the bytes before the bind offset, which the window does -/// not state, are reachable as Metal's own memory is. Where that range would exceed the view's -/// `max_range` or reach past `2^32` (a `u32` residual and offset), or the bind offset lies at or -/// past the padded end, it takes [`descriptor_range`]'s range; -/// - a `Bounded` window takes [`shared_range`]'s, where it holds the window; -/// - every other slot takes [`descriptor_range`]'s, which starts at the bind offset aligned down -/// to the descriptor base alignment. -pub(crate) fn planned_range( - pb: &PlannedBuffer, - bind_offset: u64, - length: u64, -) -> Result<(BufferRange, u32), RangeError> { - let end = padded(length); - let from_start = - pb.window == Window::Whole && bind_offset < end && end <= pb.max_range && end <= 1 << 32; - if !from_start { - let shared = shared_range(bind_offset, length, pb.window, pb.alignment, pb.max_range); - return match shared { - Some(shared) => Ok(shared), - None => descriptor_range(bind_offset, length, pb.window, pb.alignment, pb.max_range), - }; - } - // `bind_offset < end <= 2^32`: the residual is the bind offset. - let range = BufferRange { - offset: 0, - range: end, - }; - Ok((range, bind_offset as u32)) -} - -/// The bound buffer at `slot` of `state`, checked against the plan's shape. -pub(crate) fn bound_buffer( - state: &BindState, - slot: SlotRef, - expected: BoundKind, -) -> Result, BindError> { - let table = state.stages.get(&slot.stage); - let b = table.and_then(|t| t.buffers.get(&slot.index)); - // The kind alone is compared, which no offset class changes, its length classed as the - // table's buffer ranges class it in the shape. - let ranges = table.map(|t| t.buffer_ranges).unwrap_or_default(); - let kind = BoundKind::of_bound(b, ranges); - debug_assert_eq!(kind, BoundKind::of(b.map(|b| b.shape(ranges)).as_ref())); - if kind != expected { - return Err(internal(format!( - "the bind state's shape differs from the plan's at {slot:?}" - ))); - } - Ok(b) -} - -/// What a draw or dispatch binds for the plan's buffer slots beside their descriptor ranges and -/// extents ([`bind_buffers`]). -pub(crate) struct BoundBuffers { - /// The `SlotBindOffset` residual of every bound descriptor-form slot. - pub residuals: Residuals, - /// The root entry of every bound device-address slot. - pub statics: Vec<(SlotRef, RootEntry)>, -} - -/// The `SlotBindOffset` residuals a [`BoundBuffers`] holds that are kept in place, so a draw or -/// dispatch of no more descriptor-form slots allocates none. -const INLINE_RESIDUALS: usize = 8; - -/// The `SlotBindOffset` residual of every bound descriptor-form slot, in the order they were -/// added: the first [`INLINE_RESIDUALS`] in place, the rest after them. -#[derive(Default)] -pub(crate) struct Residuals { - inline: [Option<(SlotRef, u32)>; INLINE_RESIDUALS], - rest: Vec<(SlotRef, u32)>, -} - -impl Residuals { - /// Add `slot`'s residual last. - pub(crate) fn push(&mut self, slot: SlotRef, residual: u32) { - match self.inline.iter_mut().find(|r| r.is_none()) { - Some(free) => *free = Some((slot, residual)), - None => self.rest.push((slot, residual)), - } - } - - /// The first residual added for `slot`. - fn of(&self, slot: SlotRef) -> Option { - (self.inline.iter().flatten()) - .chain(&self.rest) - .find(|(s, _)| *s == slot) - .map(|r| r.1) - } -} - -/// Instantiate `buffers` for `state`: each descriptor-form slot's range, pushed onto -/// `descriptor_ranges`, and residual (checked `i128`, `DescriptorRangeExceeded` above the view's -/// limit, an empty allocation `Unsupported{BufferRange}`), each bound device-address slot's root -/// entry, and each bound buffer's extent, pushed onto `extents`. -pub(crate) fn bind_buffers( - buffers: &[PlannedBuffer], - state: &BindState, - descriptor_ranges: &mut Vec, - extents: &mut Vec, -) -> Result { - let mut out = BoundBuffers { - residuals: Residuals::default(), - statics: Vec::new(), - }; - for pb in buffers { - let bound = bound_buffer(state, pb.slot, pb.bound)?; - let (bind_offset, length) = match bound { - Some(&BoundBuffer::Buffer { length, offset, .. }) => { - extents.push(BufferExtent { - slot: pb.slot, - window: pb.window, - }); - (offset, length) - } - // `set*Bytes` data: the consumer uploads it at an aligned offset of its own. - Some(&BoundBuffer::Bytes { len, .. }) => (0, u64::from(len.max(1))), - None => continue, - }; - match (pb.form, pb.binding) { - (BufferForm::Descriptor, Some((set, binding))) => { - let (range, residual) = - planned_range(pb, bind_offset, length).map_err(|e| match e { - RangeError::TooLarge { needed } => BindError::DescriptorRangeExceeded { - slot: pb.slot, - needed, - limit: pb.max_range, - }, - RangeError::Empty => BindError::Unsupported( - Unsupported::not_representable(Feature::BufferRange), - ), - })?; - descriptor_ranges.push(DescriptorRange { - set, - binding, - element: 0, - range, - }); - out.residuals.push(pb.slot, residual); - } - (BufferForm::Psb, _) => { - if let Some(&BoundBuffer::Buffer { - length, - offset, - gpu_address, - device_address: Some(host), - .. - }) = bound - { - out.statics.push(( - pb.slot, - RootEntry { - host, - guest: gpu_address, - size: padded(length), - bind_offset: offset, - }, - )); - } - } - _ => return Err(internal(format!("{:?} without its descriptor", pb.slot))), - } - } - Ok(out) -} - -/// The bytes of one push field ([`put`]): held in place up to [`FieldBytes::INLINE`] bytes, as -/// every field of a few words is, so writing a draw's or a dispatch's fields allocates nothing; -/// a longer one on the heap. -pub(crate) enum FieldBytes { - /// The first `len` bytes of `bytes`. - Inline { - len: u8, - bytes: [u8; FieldBytes::INLINE], - }, - Heap(Vec), -} - -impl FieldBytes { - /// The most bytes a field holds in place: eight words. - pub(crate) const INLINE: usize = 32; - - /// A field of `bytes`. - pub(crate) fn of(bytes: &[u8]) -> FieldBytes { - match bytes.len() <= Self::INLINE { - true => { - let mut inline = [0; Self::INLINE]; - inline[..bytes.len()].copy_from_slice(bytes); - FieldBytes::Inline { - len: bytes.len() as u8, - bytes: inline, - } - } - false => FieldBytes::Heap(bytes.to_vec()), - } - } - - /// A field of `words`, each little-endian. - pub(crate) fn words(words: impl IntoIterator) -> FieldBytes { - words.into_iter().flat_map(u32::to_le_bytes).collect() - } -} - -impl std::ops::Deref for FieldBytes { - type Target = [u8]; - - fn deref(&self) -> &[u8] { - match self { - FieldBytes::Inline { len, bytes } => &bytes[..usize::from(*len)], - FieldBytes::Heap(bytes) => bytes, - } - } -} - -/// Bytes collected in place while they fit, else on the heap. -impl FromIterator for FieldBytes { - fn from_iter>(iter: I) -> FieldBytes { - let mut inline = [0; Self::INLINE]; - let mut len = 0; - let mut iter = iter.into_iter(); - for byte in iter.by_ref() { - if len == Self::INLINE { - let mut heap = inline.to_vec(); - heap.push(byte); - heap.extend(iter); - return FieldBytes::Heap(heap); - } - inline[len] = byte; - len += 1; - } - FieldBytes::Inline { - len: len as u8, - bytes: inline, - } - } -} - -/// The bytes of a slot push field (`SlotBindOffset`: the residual, 0 unbound; `SlotGuestBase`: the -/// slot's word of its `gpu_address + offset`, of 0 (Metal's `nil`) unbound ([`guest_word`]); -/// `TextureLevels`: the level count the plan bound; `InstanceCount`: the bound structure's instance -/// count), or `None` for another field. Planning refuses a `SlotGuestBase` of a `set*Bytes` slot -/// (`MissingGuestAddress`), so no inline-bytes slot is written as null here. -pub(crate) fn slot_field( - field: PushField, - residuals: &Residuals, - resources: &crate::bind::plan::ResourceTemplate, - state: &BindState, -) -> Option { - match field { - // The bound structure's instance count, 0 for an unbound slot. - PushField::InstanceCount(slot) => { - let count = state - .stages - .get(&slot.stage) - .and_then(|t| t.acceleration_structures.get(&slot.index)) - .map_or(0, |s| s.instance_count); - Some(FieldBytes::of(&count.to_le_bytes())) - } - // The in-place planes of the texture bound at the slot, zeros where none is (the plan - // names the slot's variant only where one is). - PushField::YCbCrInPlace(slot) => { - let words = match state - .stages - .get(&slot.stage) - .and_then(|t| t.textures.get(&slot.index)) - { - Some(BoundTexture::Texture { facts, .. }) => facts - .ycbcr_in_place - .map_or([0; crate::bind::YCbCrInPlace::WORDS], |p| p.words()), - _ => [0; crate::bind::YCbCrInPlace::WORDS], - }; - let mut bytes = [0u8; 4 * crate::bind::YCbCrInPlace::WORDS]; - for (chunk, word) in bytes.as_chunks_mut::<4>().0.iter_mut().zip(words) { - chunk.copy_from_slice(&word.to_le_bytes()); - } - Some(FieldBytes::of(&bytes)) - } - // The rows of the texture bound at the slot in its texel buffer view, zeros where none - // is (the plan names the slot's variant only where one is). - PushField::TexelRows(slot) => { - let words = match state - .stages - .get(&slot.stage) - .and_then(|t| t.textures.get(&slot.index)) - { - Some(BoundTexture::Texture { facts, .. }) => facts - .texel_rows - .map_or([0; crate::bind::TexelRows::WORDS], |r| r.words()), - _ => [0; crate::bind::TexelRows::WORDS], - }; - let mut bytes = [0u8; 4 * crate::bind::TexelRows::WORDS]; - for (chunk, word) in bytes.as_chunks_mut::<4>().0.iter_mut().zip(words) { - chunk.copy_from_slice(&word.to_le_bytes()); - } - Some(FieldBytes::of(&bytes)) - } - // The level count the plan bound. - PushField::TextureLevels(slot) => resources - .texture_levels - .iter() - .find(|(s, _)| *s == slot) - .map(|(_, levels)| FieldBytes::of(&levels.to_le_bytes())), - // The integer channel widths of the texture the plan bound. - PushField::TextureIntegerChannels(slot) => resources - .texture_integer_channels - .iter() - .find(|(s, _)| *s == slot) - .map(|(_, word)| FieldBytes::of(&word.to_le_bytes())), - PushField::SlotBindOffset(slot) => Some(FieldBytes::of(&slot_bind_offset(residuals, slot))), - PushField::SlotGuestBase(slot) => Some(FieldBytes::of(&slot_guest_base( - state, - slot, - resources.biased_slot_words, - ))), - PushField::SlotBounds(slot) => Some(FieldBytes::of(&slot_bounds(state, slot))), - _ => None, - } -} - -/// The bytes of `PushField::SlotBindOffset(slot)` ([`slot_field`]): the slot's residual, 0 -/// unbound. -fn slot_bind_offset(residuals: &Residuals, slot: SlotRef) -> [u8; 4] { - residuals.of(slot).unwrap_or(0).to_le_bytes() -} - -/// The `SlotGuestBase` word of Metal address `address`: the address, or where `biased` (a plan of a -/// device compiling under the identity domains, `ResourceTemplate::biased_slot_words`) the address -/// less [`SLOT_ADDRESS_BIAS`](crate::lower::access::SLOT_ADDRESS_BIAS), modulo 2^64, which the -/// pipeline's accesses add back. -pub(crate) fn guest_word(address: u64, biased: bool) -> u64 { - match biased { - true => address.wrapping_sub(crate::lower::access::SLOT_ADDRESS_BIAS), - false => address, - } -} - -/// The bytes of `PushField::SlotGuestBase(slot)` ([`slot_field`]): the word ([`guest_word`]) of the -/// slot's `gpu_address + offset`, of 0 (Metal's `nil`) where it binds no buffer. -pub(crate) fn slot_guest_base(state: &BindState, slot: SlotRef, biased: bool) -> [u8; 8] { - let base = match state - .stages - .get(&slot.stage) - .and_then(|t| t.buffers.get(&slot.index)) - { - Some(&BoundBuffer::Buffer { - gpu_address, - offset, - .. - }) => gpu_address.wrapping_add(offset), - _ => 0, - }; - guest_word(base, biased).to_le_bytes() -} - -/// The bytes of `PushField::SlotBounds(slot)` ([`slot_field`]): the bound buffer's bytes before -/// its bind offset, then its length, each at most `u32::MAX`; 0 and 0 where the slot binds no -/// buffer. -fn slot_bounds(state: &BindState, slot: SlotRef) -> [u8; 8] { - let (before, length) = match state - .stages - .get(&slot.stage) - .and_then(|t| t.buffers.get(&slot.index)) - { - Some(&BoundBuffer::Buffer { length, offset, .. }) => (offset, length), - _ => (0, 0), - }; - let word = |v: u64| u32::try_from(v).unwrap_or(u32::MAX).to_le_bytes(); - let mut bytes = [0; 8]; - bytes[..4].copy_from_slice(&word(before)); - bytes[4..].copy_from_slice(&word(length)); - bytes -} - -/// A field's bytes at its placed location: the push bytes (relative to the push range's start -/// `push_start`) or the argument table. -#[inline] -pub(crate) fn put( - push: &mut [u8], - push_start: u32, - table: &mut [u8], - loc: PushLoc, - bytes: &[u8], -) -> Result<(), BindError> { - let (buf, at) = match loc { - PushLoc::Push { offset } => (push, offset.checked_sub(push_start)), - PushLoc::ArgumentTable { offset } => (table, Some(offset)), - }; - let at = at.ok_or_else(|| internal("a push field before its range"))? as usize; - buf.get_mut(at..at + bytes.len()) - .ok_or_else(|| internal("a push field outside its range or table"))? - .copy_from_slice(bytes); - Ok(()) -} - -/// The texel-buffer view ranges of every bound texture buffer the plan writes: the view starts at -/// the texture buffer's offset, which must be a multiple of `minTexelBufferOffsetAlignment` (the -/// shader indexes from element 0 of the view; an unaligned offset is `Unsupported{TexelBuffer, -/// NotRepresentable}`), and spans the whole texel blocks of its length -/// (`VUID-VkBufferViewCreateInfo-range-00929`: a multiple of the view format's block size; bytes -/// past the last whole block hold no texel). Its element count, `⌊length / block size⌋ × texels per -/// block`, must be at most `maxTexelBufferElements` (`VUID-VkBufferViewCreateInfo-range-00930`), -/// else `TexelBufferTooLarge`; a view without a whole block is `Unsupported{TexelBuffer, -/// NotRepresentable}`. A texture buffer the plan binds through its parts (`PlannedTexel::parts`, -/// `bind::texel_parts`) takes one range per part, at its array element: part `k` from the -/// offset plus `k · P` texels, `P` texels long but the last, which holds the rest; one of a -/// format of blocks of several texels is `TexelBufferTooLarge` too. -pub(crate) fn texel_ranges( - t: &ResourceTemplate, - state: &BindState, -) -> Result, BindError> { - let mut out = Vec::new(); - for pt in &t.texel_buffers { - let bound = state - .stages - .get(&pt.slot.stage) - .and_then(|s| s.textures.get(&pt.slot.index)); - let Some(&BoundTexture::Buffer { offset, length, .. }) = bound else { - return Err(internal(format!( - "the bind state's shape differs from the plan's at {:?}", - pt.slot - ))); - }; - if offset % pt.alignment != 0 { - return Err(BindError::Unsupported(Unsupported::not_representable( - Feature::TexelBuffer, - ))); - } - let block = pt.block_size.max(1); - let blocks = length / block; - if blocks == 0 { - return Err(BindError::Unsupported(Unsupported::not_representable( - Feature::TexelBuffer, - ))); - } - let elements = blocks.saturating_mul(pt.texels_per_block); - let too_large = BindError::TexelBufferTooLarge { - slot: pt.slot, - elements, - limit: pt.max_elements, - }; - let range = |element: u32, offset: u64, range: u64| DescriptorRange { - set: pt.set, - binding: pt.binding, - element, - range: BufferRange { offset, range }, - }; - if pt.parts <= 1 { - if elements > pt.max_elements { - return Err(too_large); - } - out.push(range(0, offset, blocks * block)); - continue; - } - // Parts of `P` texels of one block each: every part but the last full, the last holding - // at least one texel. - let (part, parts) = (pt.part_texels, u64::from(pt.parts)); - if pt.texels_per_block != 1 || part == 0 { - return Err(too_large); - } - if elements > part.saturating_mul(parts) || elements <= part.saturating_mul(parts - 1) { - return Err(internal(format!( - "{elements} texels of a texture buffer at {:?} in {parts} parts of {part}", - pt.slot - ))); - } - for k in 0..pt.parts { - let first = part * u64::from(k); - let texels = part.min(elements - first); - out.push(range(k, offset + first * block, texels * block)); - } - } - Ok(out) -} - -#[cfg(test)] -mod tests; diff --git a/crates/metal2vulkan/src/bind/instantiate/tests.rs b/crates/metal2vulkan/src/bind/instantiate/tests.rs deleted file mode 100644 index 30211fbbc..000000000 --- a/crates/metal2vulkan/src/bind/instantiate/tests.rs +++ /dev/null @@ -1,705 +0,0 @@ -//! Range arithmetic at extremes, the residual, the resident set, and push fields' bytes. - -use super::*; - -const MAX: u64 = u64::MAX; - -/// The contract every range meets: aligned start, at least 16 bytes, inside the padded -/// allocation, and every Metal-defined byte of the window that lies in the allocation is at -/// `residual + m` inside the range. -fn check(bind_offset: u64, length: u64, window: Window, a: u64) { - let (r, residual) = descriptor_range(bind_offset, length, window, a, MAX) - .unwrap_or_else(|e| panic!("{bind_offset} {length} {window:?} {a}: {e:?}")); - let end = padded(length); - let a4 = a.max(4); - assert_eq!(r.offset % a4, 0, "aligned start"); - assert!(r.range >= 16, "at least 16 bytes"); - assert!(r.offset + r.range <= end, "inside the padded allocation"); - assert_eq!( - u64::from(residual), - bind_offset.wrapping_sub(r.offset) & 0xFFFF_FFFF, - "residual is bind offset minus base, mod 2^32" - ); - let (start, len) = match window { - Window::Bounded { start, len } => (i128::from(start), i128::from(len)), - Window::Whole => (0, i128::from(end) - i128::from(bind_offset)), - }; - // Probe the window's first and last byte and its middle. - for m in [start, start + len / 2, start + len - 1] { - if len <= 0 { - break; - } - let abs = i128::from(bind_offset) + m; - if abs < 0 || abs >= i128::from(end) { - continue; - } - let rel = (i128::from(residual) + m).rem_euclid(1 << 32); - let expect = abs - i128::from(r.offset); - assert_eq!(rel, expect.rem_euclid(1 << 32), "byte {m} of {window:?}"); - assert!( - expect >= 0 && expect < i128::from(r.range), - "byte {m} of {window:?} at {bind_offset} inside [{}, +{})", - r.offset, - r.range - ); - } -} - -#[test] -fn bounded_windows_bind_the_aligned_padded_window() { - // A 6-byte allocation: the last byte is covered by the 16-byte padded range. - let (r, res) = descriptor_range(0, 6, Window::Bounded { start: 5, len: 1 }, 16, MAX).unwrap(); - assert_eq!((r.offset, r.range, res), (0, 16, 0)); - // A window starting beyond the alignment block: the base moves up, the residual wraps. - let (r, res) = descriptor_range( - 8, - 4096, - Window::Bounded { - start: 256, - len: 16, - }, - 64, - MAX, - ) - .unwrap(); - assert_eq!(r.offset, 256); - assert_eq!(r.range, 32, "bytes 264..280 round up to 288"); - assert_eq!(res, 8u32.wrapping_sub(256)); - // A negative start clamps to 0: the residual is the bind offset. - let (r, res) = descriptor_range( - 100, - 4096, - Window::Bounded { - start: -200, - len: 400, - }, - 64, - MAX, - ) - .unwrap(); - assert_eq!((r.offset, res), (0, 100)); - assert_eq!(r.range, 304); - // Whole: from the aligned bind offset to the padded end. - let (r, res) = descriptor_range(100, 1000, Window::Whole, 64, MAX).unwrap(); - assert_eq!((r.offset, r.range, res), (64, 1008 - 64, 36)); -} - -#[test] -fn windows_past_the_allocation_still_bind_sixteen_bytes() { - // Bound past the end, or a window entirely outside: 16 bytes inside the allocation. - for (b, len, w) in [ - (4096, 4096, Window::Whole), - (1 << 40, 64, Window::Whole), - ( - 0, - 64, - Window::Bounded { - start: 1 << 20, - len: 4, - }, - ), - (0, 64, Window::Bounded { start: -64, len: 8 }), - (60, 64, Window::Bounded { start: 0, len: 4 }), - ] { - let (r, _) = descriptor_range(b, len, w, 16, MAX).unwrap(); - assert!( - r.range >= 16 && r.offset + r.range <= padded(len), - "{b} {w:?}" - ); - check(b, len, w, 16); - } - assert_eq!( - descriptor_range(0, 0, Window::Whole, 16, MAX), - Err(RangeError::Empty) - ); -} - -#[test] -fn ranges_hold_at_extremes_of_every_operand() { - let offsets = [ - 0, - 1, - 3, - 4, - 15, - 16, - 255, - 256, - (1 << 32) - 4, - (1 << 32) + 4, - (1 << 40) + 12, - MAX - 4095, - ]; - let lengths = [1, 6, 10, 16, 17, 4096, 1 << 33, MAX - 64]; - let windows = [ - Window::Whole, - Window::Bounded { start: 0, len: 1 }, - Window::Bounded { start: 5, len: 1 }, - Window::Bounded { start: -1, len: 2 }, - Window::Bounded { - start: -(1 << 31), - len: 1 << 32, - }, - Window::Bounded { - start: i64::MIN, - len: MAX, - }, - Window::Bounded { - start: i64::MAX, - len: MAX, - }, - Window::Bounded { - start: 1 << 32, - len: 64, - }, - ]; - for &b in &offsets { - for &len in &lengths { - for &w in &windows { - for a in [1, 4, 16, 64, 256] { - check(b, len, w, a); - } - } - } - } -} - -#[test] -fn ranges_above_the_descriptor_limit_are_refused() { - let w = Window::Bounded { - start: 0, - len: 1 << 20, - }; - assert_eq!( - descriptor_range(0, 1 << 30, w, 16, 65536), - Err(RangeError::TooLarge { needed: 1 << 20 }) - ); - assert!(descriptor_range(0, 1 << 30, w, 16, 1 << 20).is_ok()); - assert_eq!( - descriptor_range(0, 1 << 30, Window::Whole, 16, u64::from(u32::MAX)), - Ok(( - BufferRange { - offset: 0, - range: 1 << 30 - }, - 0 - )) - ); -} - -/// A planned buffer slot of `window`, under a view base alignment of `alignment` and a range limit -/// of `max_range`. -fn planned(window: Window, alignment: u64, max_range: u64) -> PlannedBuffer { - use crate::pipeline::sym::{SlotClass, Stage}; - PlannedBuffer { - slot: SlotRef { - stage: Stage::Vertex, - class: SlotClass::Buffer, - index: 0, - }, - window, - form: BufferForm::Descriptor, - access: crate::pipeline::interface::AccessSet::READ_WRITE, - binding: Some((0, 0)), - alignment, - max_range, - bound: BoundKind::Buffer { - device_address: false, - length_class: crate::bind::state::length_class(1 << 12), - }, - } -} - -/// A storage view of a whole buffer binds its space from 0 to the padded end at every bind offset -/// before the end, its residual the bind offset, so a draw that moves only the offset binds the -/// same descriptor; every byte from the bind offset to the end is at `residual + m`, inside the -/// range, as `descriptor_range` places it. -#[test] -fn a_storage_view_of_a_whole_buffer_binds_its_space_from_its_start() { - const LENGTH: u64 = 4096; - for alignment in [16, 64, 256] { - let pb = planned(Window::Whole, alignment, MAX); - for bind_offset in (0..LENGTH).step_by(4).chain([1, 15, LENGTH - 1]) { - let what = format!("{alignment} {bind_offset}"); - let (range, residual) = - planned_range(&pb, bind_offset, LENGTH).unwrap_or_else(|e| panic!("{what}: {e:?}")); - let whole = BufferRange { - offset: 0, - range: LENGTH, - }; - assert_eq!((range, u64::from(residual)), (whole, bind_offset), "{what}"); - // The byte `descriptor_range`'s range holds at `residual + m` for the Metal offset - // `m` is the same byte of the space here. - let (from_bind, at) = - descriptor_range(bind_offset, LENGTH, Window::Whole, alignment, MAX).unwrap(); - for m in [0, (LENGTH - bind_offset) / 2, LENGTH - bind_offset - 1] { - let byte = range.offset + u64::from(residual) + m; - assert!( - byte < range.offset + range.range, - "{what} {m}: inside the range" - ); - assert_eq!(byte, from_bind.offset + u64::from(at) + m, "{what} {m}"); - } - } - } - // A buffer of 2^32 bytes, bound at its last word: the residual still fits. - let pb = planned(Window::Whole, 16, MAX); - let last = (1 << 32) - 4; - let (range, residual) = planned_range(&pb, last, 1 << 32).unwrap(); - assert_eq!( - (range.offset, range.range, residual), - (0, 1 << 32, u32::MAX - 3) - ); -} - -/// Every other slot takes `descriptor_range`'s range: a storage view's range from 0 past the -/// view's limit or past `2^32`, a bind offset at or past the padded end, a bounded window no -/// shared range holds. A limit the range from the bind offset meets binds; one it does not is -/// refused as before. -#[test] -fn other_slots_bind_the_range_from_their_bind_offset() { - let same = |pb: &PlannedBuffer, bind_offset: u64, length: u64| { - assert_eq!( - planned_range(pb, bind_offset, length), - descriptor_range(bind_offset, length, pb.window, pb.alignment, pb.max_range), - "{:?} {:?} {bind_offset} {length}", - pb.window, - pb.form - ); - }; - let storage = |max_range| planned(Window::Whole, 64, max_range); - // Past the view's limit: the tail from the bind offset fits; the whole buffer from 0 is - // refused as before, at the range from the bind offset. - let limited = storage(1 << 16); - let length = 1 << 20; - same(&limited, length - 4096, length); - assert!(planned_range(&limited, length - 4096, length).is_ok()); - same(&limited, 64, length); - assert_eq!( - planned_range(&limited, 64, length), - Err(RangeError::TooLarge { - needed: length - 64 - }) - ); - // At the limit exactly, from 0. - let (range, _) = planned_range(&storage(length), 64, length).unwrap(); - assert_eq!(range.offset, 0); - // Past 2^32 bytes: a residual and an offset of 32 bits could not state the bind offset. - for length in [(1 << 32) + 16, 1 << 33] { - for bind_offset in [0, 64, 1 << 31, (1 << 32) - 64, 1 << 32] { - same(&storage(MAX), bind_offset, length); - } - } - // At or past the padded end, where the range is widened down into the allocation, a whole - // window's or a bounded one's. - for bind_offset in [4096, 4100, 8192, MAX] { - same(&storage(MAX), bind_offset, 4096); - same(&storage(MAX), bind_offset, 4090); - let bounded = Window::Bounded { start: 0, len: 16 }; - same(&planned(bounded, 64, MAX), bind_offset, 4096); - } -} - -/// The contract every shared range meets where it is given, as `descriptor_range`'s does: an -/// aligned start, at least 16 bytes, inside the padded allocation and the view's limit, and every -/// byte of the window inside the allocation at `residual + m` inside the range. -fn check_shared(bind_offset: u64, length: u64, window: Window, a: u64, max_range: u64) { - let Some((r, residual)) = shared_range(bind_offset, length, window, a, max_range) else { - return; - }; - let what = format!("{bind_offset} {length} {window:?} {a} {max_range}"); - let end = padded(length); - assert_eq!(r.offset % a.max(4), 0, "{what}: aligned start"); - assert!(r.range >= 16, "{what}: at least 16 bytes"); - assert!( - r.offset + r.range <= end, - "{what}: inside the padded allocation" - ); - assert!( - r.range <= max_range.min(1 << 32), - "{what}: inside the view's limit and 4 GiB" - ); - let Window::Bounded { start, len } = window else { - panic!("{what}: a shared range of a whole window"); - }; - let (start, len) = (i128::from(start), i128::from(len)); - for m in [start, start + len / 2, start + len - 1] { - if len <= 0 { - break; - } - let abs = i128::from(bind_offset) + m; - if abs < 0 || abs >= i128::from(end) { - continue; - } - let rel = (i128::from(residual) + m).rem_euclid(1 << 32); - let expect = abs - i128::from(r.offset); - assert_eq!(rel, expect.rem_euclid(1 << 32), "{what}: byte {m}"); - assert!( - expect >= 0 && expect < i128::from(r.range), - "{what}: byte {m} inside [{}, +{})", - r.offset, - r.range - ); - } -} - -#[test] -fn shared_ranges_hold_every_window_byte_at_the_residual() { - let offsets = [ - 0, - 4, - 16, - 255, - 256, - 32 * 1024 - 16, - 32 * 1024, - 65520, - 65536, - (1 << 20) - 16, - (1 << 32) - 4, - (1 << 32) + 4, - MAX - 4095, - ]; - let lengths = [1, 16, 4096, 65536, 65537, 1 << 20, 1 << 33, MAX - 64]; - let windows = [ - Window::Bounded { start: 0, len: 16 }, - Window::Bounded { start: 0, len: 1 }, - Window::Bounded { start: -8, len: 40 }, - Window::Bounded { - start: 256, - len: 16, - }, - Window::Bounded { - start: 0, - len: 40000, - }, - Window::Bounded { - start: i64::MIN, - len: MAX, - }, - Window::Bounded { - start: 1 << 32, - len: 64, - }, - ]; - for &b in &offsets { - for &len in &lengths { - for &w in &windows { - for a in [4, 16, 64, 256] { - for max_range in [64, 65536, 1 << 27, MAX] { - check_shared(b, len, w, a, max_range); - } - } - } - } - } -} - -/// A slot of a bounded window binds one range at every bind offset of a buffer that fits the -/// view's limit, from 0, its residual the bind offset. Past the limit, the bind offsets of one -/// block of half the limit share one; the next block binds the next. -#[test] -fn bounded_slots_read_at_their_residual_share_one_range_along_a_buffer() { - const CHUNK: u64 = 64 * 1024; - let bounded = Window::Bounded { start: 0, len: 16 }; - let limited = planned(bounded, 64, CHUNK); - let storage = planned(bounded, 64, 1 << 27); - let whole = BufferRange { - offset: 0, - range: CHUNK, - }; - for bind_offset in (0..CHUNK).step_by(256) { - let shared = (whole, bind_offset as u32); - assert_eq!( - planned_range(&limited, bind_offset, CHUNK), - Ok(shared), - "limited {bind_offset}" - ); - assert_eq!( - planned_range(&storage, bind_offset, CHUNK), - Ok(shared), - "storage {bind_offset}" - ); - } - // A buffer of 1 MiB, past the view's limit: blocks of 32 KiB. - let length = 1 << 20; - let block = CHUNK / 2; - for bind_offset in (0..length).step_by(256) { - let base = bind_offset - bind_offset % block; - let (range, residual) = planned_range(&limited, bind_offset, length).unwrap(); - assert_eq!( - (range.offset, range.range, u64::from(residual)), - (base, CHUNK.min(length - base), bind_offset - base), - "{bind_offset}" - ); - } - // A window never straddles its block's range: one of half the limit, starting in a block's - // last 16 bytes, ends inside the block's range; a longer one takes no block, and binds from - // its bind offset. - for start in [0, block - 16, 3 * block - 16] { - let half = Window::Bounded { - start: 0, - len: block, - }; - let (range, residual) = shared_range(start, length, half, 64, CHUNK).unwrap(); - assert_eq!(range.offset, start - start % block, "{start}"); - assert!( - u64::from(residual) + block <= range.range, - "{start}: the window inside its block's range" - ); - let longer = Window::Bounded { - start: 0, - len: block + 16, - }; - assert_eq!( - shared_range(start, length, longer, 64, CHUNK), - None, - "{start}" - ); - let pb = planned(longer, 64, CHUNK); - assert_eq!( - planned_range(&pb, start, length), - descriptor_range(start, length, longer, 64, CHUNK), - "{start}" - ); - } -} - -fn entry(host: u64, guest: u64, size: u64) -> RootEntry { - RootEntry { - host, - guest, - size, - bind_offset: 0, - } -} - -#[test] -fn the_root_table_follows_d76_layout() { - let statics = [(0, entry(0x10, 0x20, 0x30)), (3, entry(0x40, 0x50, 0x60))]; - let resident = [entry(0x100, 0x200, 0x300)]; - let mut e = statics[1].1; - e.bind_offset = 8; - let statics = [statics[0], (3, e)]; - let t = RootTable::build(&statics, 6, &resident); - let word = |root: u64, field: u64| { - let at = (root * ENTRY_BYTES + field) as usize; - u64::from_le_bytes(t.bytes[at..at + 8].try_into().unwrap()) - }; - assert_eq!(t.bytes.len(), 7 * 32); - assert!(t.bytes[..32].iter().all(|&b| b == 0), "entry 0 is null"); - assert_eq!(word(1, HOST), 0, "the consumer fills the sink address"); - assert_eq!(RootTable::SINK_HOST_OFFSET, 32); - assert_eq!((word(1, GUEST), word(1, SIZE)), (6, 1), "R0 and N"); - assert_eq!( - (word(2, HOST), word(2, GUEST), word(2, SIZE)), - (0x10, 0x20, 0x30) - ); - assert_eq!((word(5, HOST), word(5, BIND_OFFSET)), (0x40, 8)); - assert!(t.bytes[3 * 32..5 * 32].iter().all(|&b| b == 0), "unbound"); - assert_eq!( - (word(6, HOST), word(6, GUEST), word(6, SIZE)), - (0x100, 0x200, 0x300) - ); -} - -/// A texel-buffer view spans the whole blocks of the bound length and its element count -/// (`⌊length / block size⌋ × texels per block`) is checked exactly against -/// `maxTexelBufferElements`; an unaligned offset or a view without a whole block is not -/// representable. -#[test] -fn texel_views_count_whole_blocks_against_the_element_limit() { - use crate::bind::plan::PlannedTexel; - use crate::bind::state::StageTable; - use crate::pipeline::sym::{SlotClass, Stage}; - let slot = SlotRef { - stage: Stage::Kernel, - class: SlotClass::Texture, - index: 3, - }; - let block = vk::Format::R32G32B32_SFLOAT.block().expect("block"); - let template = ResourceTemplate { - texel_buffers: vec![PlannedTexel { - set: 0, - binding: 5, - slot, - alignment: 16, - max_elements: 100, - block_size: u64::from(block.size), - texels_per_block: u64::from(block.texels), - parts: 1, - part_texels: 96, - }], - ..ResourceTemplate::default() - }; - let state = |offset: u64, length: u64| { - let mut t = StageTable::default(); - t.textures.insert( - 3, - BoundTexture::Buffer { - pixel_format: crate::metal::PixelFormat::RGBA32Float, - offset, - length, - bytes_per_row: length, - resource_id: None, - swizzle: crate::metal::TextureSwizzleChannels::DEFAULT, - parts: 1, - }, - ); - let mut s = BindState::default(); - s.stages.insert(Stage::Kernel, t); - s - }; - let range = |offset, length| texel_ranges(&template, &state(offset, length)); - // 12-byte texels: 100 whole texels fit, the ragged tail is not part of the view. - assert_eq!(range(32, 1200).expect("at the limit")[0].range.range, 1200); - assert_eq!(range(32, 1210).expect("ragged")[0].range.range, 1200); - assert_eq!(range(0, 1211).expect("ragged")[0].range.range, 1200); - assert_eq!( - range(0, 1212), - Err(BindError::TexelBufferTooLarge { - slot, - elements: 101, - limit: 100 - }) - ); - let not_representable = Err(BindError::Unsupported(Unsupported::not_representable( - Feature::TexelBuffer, - ))); - assert_eq!(range(0, 11), not_representable, "no whole texel"); - assert_eq!(range(8, 120), not_representable, "unaligned offset"); - // A compressed block counts all of its texels. - let bc1 = vk::Format::BC1_RGB_UNORM_BLOCK.block().expect("block"); - let mut compressed = template.clone(); - compressed.texel_buffers[0].block_size = u64::from(bc1.size); - compressed.texel_buffers[0].texels_per_block = u64::from(bc1.texels); - assert!(texel_ranges(&compressed, &state(0, 48)).is_ok()); - assert_eq!( - texel_ranges(&compressed, &state(0, 56)), - Err(BindError::TexelBufferTooLarge { - slot, - elements: 112, - limit: 100 - }) - ); -} - -/// A texture buffer bound through its parts (`bind::texel_parts`) takes one range per part at its -/// array element: part `k` from the offset plus `k · P` texels, `P` long but the last, which -/// holds the rest; past one view's limit, the same buffer bound as one view is -/// `TexelBufferTooLarge`. A format of blocks of several texels takes no parts, and texels the -/// parts do not hold are the bind state's disagreement with the plan's shape. -#[test] -fn texel_parts_view_the_limit_s_texels_each() { - use crate::bind::plan::PlannedTexel; - use crate::bind::state::StageTable; - use crate::pipeline::sym::{SlotClass, Stage}; - let slot = SlotRef { - stage: Stage::Kernel, - class: SlotClass::Texture, - index: 2, - }; - // `R32_UINT` texels, 100 to a view, parts of 96 (100 rounded down to the 16-byte alignment's - // 16 texels). - let planned = |parts| ResourceTemplate { - texel_buffers: vec![PlannedTexel { - set: 0, - binding: 4, - slot, - alignment: 16, - max_elements: 100, - block_size: 4, - texels_per_block: 1, - parts, - part_texels: 96, - }], - ..ResourceTemplate::default() - }; - let state = |length: u64| { - let mut t = StageTable::default(); - t.textures.insert( - 2, - BoundTexture::Buffer { - pixel_format: crate::metal::PixelFormat::R32Uint, - offset: 64, - length, - bytes_per_row: length, - resource_id: None, - swizzle: crate::metal::TextureSwizzleChannels::DEFAULT, - parts: 2, - }, - ); - let mut s = BindState::default(); - s.stages.insert(Stage::Kernel, t); - s - }; - let at = |element, offset, range| DescriptorRange { - set: 0, - binding: 4, - element, - range: BufferRange { offset, range }, - }; - // 150 texels: 96 in part 0, 54 in part 1 from texel 96. - assert_eq!( - texel_ranges(&planned(2), &state(600)), - Ok(vec![at(0, 64, 384), at(1, 64 + 384, 216)]) - ); - // 192 texels: two full parts; a ragged tail past the last whole texel is no texel. - assert_eq!( - texel_ranges(&planned(2), &state(770)), - Ok(vec![at(0, 64, 384), at(1, 64 + 384, 384)]) - ); - // 97 texels: one past the first part, the last holding one. - assert_eq!( - texel_ranges(&planned(2), &state(388)), - Ok(vec![at(0, 64, 384), at(1, 64 + 384, 4)]) - ); - // The same buffer as one view: past the limit. - assert_eq!( - texel_ranges(&planned(1), &state(600)), - Err(BindError::TexelBufferTooLarge { - slot, - elements: 150, - limit: 100 - }) - ); - // Blocks of two texels take no parts. - let mut blocks = planned(2); - blocks.texel_buffers[0].texels_per_block = 2; - assert_eq!( - texel_ranges(&blocks, &state(600)), - Err(BindError::TexelBufferTooLarge { - slot, - elements: 300, - limit: 100 - }) - ); - // Texels two parts do not hold, too many or too few. - for length in [772, 384] { - assert!( - matches!( - texel_ranges(&planned(2), &state(length)), - Err(BindError::Internal(_)) - ), - "{length} bytes" - ); - } -} - -/// A push field's bytes are the bytes it was made of, however they were made: held in place up -/// to `FieldBytes::INLINE` bytes, past it on the heap, a collect that crosses the bound included. -#[test] -fn field_bytes_hold_what_they_were_made_of() { - for len in [0, 1, 4, 31, 32, 33, 64, 200] { - let bytes: Vec = (0..len).map(|i| (i * 7 + 3) as u8).collect(); - let of = FieldBytes::of(&bytes); - let collected: FieldBytes = bytes.iter().copied().collect(); - for field in [&of, &collected] { - assert_eq!(&field[..], &bytes[..], "{len} bytes"); - let inline = matches!(field, FieldBytes::Inline { .. }); - assert_eq!(inline, len <= FieldBytes::INLINE, "{len} bytes"); - } - } - let words = FieldBytes::words([1, 0x0403_0201, u32::MAX]); - assert_eq!(&words[..], &[1, 0, 0, 0, 1, 2, 3, 4, 255, 255, 255, 255]); -} diff --git a/crates/metal2vulkan/src/bind/mesh_arguments.rs b/crates/metal2vulkan/src/bind/mesh_arguments.rs index 199e54dc7..a6735cb3d 100644 --- a/crates/metal2vulkan/src/bind/mesh_arguments.rs +++ b/crates/metal2vulkan/src/bind/mesh_arguments.rs @@ -1,82 +1,15 @@ -//! The arguments pass of an indirect mesh draw on a device with `VK_EXT_mesh_shader`. +//! What Metal draws of a mesh grid. The object function's lowering holds the mesh grid an object +//! threadgroup sets to it (`lower::mesh`): past these limits it launches nothing. //! -//! `drawMeshThreadgroupsWithIndirectBuffer:` reads its group counts (an -//! `MTLDispatchThreadgroupsIndirectArguments`) as it runs. `vkCmdDrawMeshTasksIndirectEXT` requires -//! every count within the device's task or mesh limits, so the draw cannot read Metal's arguments -//! in place: the consumer records an arguments pass first, which reads Metal's three words and -//! writes what the draw reads into a scratch, by the rules below ([`MeshArguments`] names the -//! folded object form's words in it). -//! -//! **What Metal draws**, measured by our probe on an M3 Max (macOS 27.0.1), direct and indirect -//! draws alike, with and without API validation, which stops none of them: -//! -//! - Without an object function the counts are the mesh grid. A grid with an axis past -//! [`METAL_MESH_GRID_AXIS`] (65,535) draws nothing; so does one of exactly 2^20 threadgroups -//! (1024 by 1024, 128 by 128 by 64, 4096 by 256) and every one measured of 2^21 or more. Grids -//! of up to [`METAL_MESH_GRID_TOTAL`] (1,048,575, Apple's limit for the family) draw whole. Past -//! that Metal is erratic (17 by 61,681 and 65,535 by 24 drew, 1025 by 1025 and 33 by 32,768 did -//! not), and the module draws nothing, Metal's answer at 2^20 and above 2^21. -//! - With an object function the counts are the object grid, which Metal runs at every count -//! that its GPU finishes within its watchdog's 5 s. An object function that does next to nothing -//! ran 2^28 threadgroups in 2.4 s and 2^29 in 4.98 s, direct and indirect; 2^30 and 2^32 were -//! discarded at 5 s, as was 2^29 of a costlier function: the command buffer fails with -//! `MTLCommandBufferErrorInternal` (1, "Discarded (victim of GPU error/recovery)"), and nothing -//! of it runs from the draw's encoder on (its clear, its draws before the grid's, the encoders -//! after it; an encoder before it ran), nor does a command buffer of the queue committed while -//! it ran. [`METAL_OBJECT_GRID_TOTAL`] is the most Metal ran; past it the runtime fails the -//! command buffer so (`DrawCommands::discards_command_buffer`, `MESH_GRID_DISCARDED`). Metal's -//! threads per grid along an axis are -//! the axis's threadgroups times its threads per threadgroup wrapped to 32 bits, which its grid -//! builtins report (`threads_per_grid`, and `threadgroups_per_grid` those threads over the -//! threadgroup's, rounded up): an indirect draw runs every threadgroup of its arguments -//! (4,294,970 by 1000 threads ran 4,294,970 threadgroups that each read a grid of 2704 threads, -//! 3 threadgroups), a direct draw only the threadgroups the wrapped threads fill, rounded up -//! (that draw ran 3, 4,194,304 by 1024 none) ([`metal_object_grid`]). The mesh grid an object -//! threadgroup sets follows the rule above (65,536 along `x` or `y`, 1024 by 1024 and 2048 by -//! 1024 launch nothing from it; 1023 by 1025 and 65,535 by 16 launch whole), which the object -//! function's lowering holds it to (`lower::mesh`). -//! -//! **The mesh form's rule** (Metal's limits, its constants, and the device's for the first -//! stage, [`MeshGridLimits`]): where Metal draws nothing, the pass writes zero counts, which draw -//! nothing. Where Metal draws and the counts lie within the -//! device's `maxMeshWorkGroupCount` and `maxMeshWorkGroupTotalCount`, it copies them; every -//! committed profile with the extension holds Metal's mesh grids so. Where they do not, it writes -//! zero counts and sets `MESH_GRID_PAST_LIMITS` in the command buffer's `ExecutionStatus`, which the -//! consumer reports as a command-buffer error. -//! -//! **The folded object form** ([`MeshArgumentsForm::FoldedObject`]) runs any object grid in -//! pieces within the task stage's limits ([`fold_object_grid`], which a direct draw's binder -//! computes on the CPU): on a device that folds object grids (`lower::mesh::folds_object_grids`) -//! the object function is compiled folded (`LoweringInputs::folded_groups`), so a task workgroup -//! counts its Metal threadgroup from its workgroup's position, the dispatch's size and its -//! `DrawIndex`, reads the threadgroups Metal runs and its threads per grid from the 32-byte region -//! record at its `PushField::ReplayRegionAddress`, and launches nothing past Metal's last -//! threadgroup. The pass writes, into the scratch: -//! -//! - the region record: the threadgroups Metal runs along each axis in the base's words (which a -//! folded variant reads in their place, `lower::dispatch`), the packed threads per object -//! threadgroup, and Metal's threads per grid ([`metal_object_grid`]); -//! - the draw count `P` ([`MeshArguments::OBJECT_COUNT`]) and [`MeshArguments::OBJECT_PIECES`] -//! commands of one piece's dispatch ([`MeshArguments::OBJECT_COMMANDS`]), which -//! `vkCmdDrawMeshTasksIndirectCountEXT` reads. -//! -//! A grid with a zero count draws nothing. One of more than [`METAL_OBJECT_GRID_TOTAL`] -//! threadgroups draws nothing and sets `MESH_GRID_DISCARDED`: Metal's GPU discards it. One that -//! more pieces than [`MeshArguments::OBJECT_PIECES`] would take (none on a device of the task -//! limits Vulkan requires) draws nothing and sets `MESH_GRID_PAST_LIMITS`: the device cannot -//! launch it. -//! -//! **The unfolded object form** ([`MeshArgumentsForm::Object`], a device that does not fold -//! object grids) is the mesh form's rule with Metal's discard as its limit: a grid of more than -//! [`METAL_OBJECT_GRID_TOTAL`] threadgroups writes zero counts and sets `MESH_GRID_DISCARDED`; -//! otherwise Metal's counts where they lie within the device's `maxTaskWorkGroupCount` and -//! `maxTaskWorkGroupTotalCount`, else zero counts and `MESH_GRID_PAST_LIMITS`. -//! -//! **Synchronization** (consumer): the source write → `SHADER_READ` in `COMPUTE_SHADER` before -//! the pass; the scratch `SHADER_WRITE` → `INDIRECT_COMMAND_READ` in `DRAW_INDIRECT`, and for the -//! folded object form `SHADER_READ` in `TASK_SHADER`, between the pass and the draw. - -use crate::bind::instantiate::{BufferRange, IndirectRef}; +//! Measured by our probe on an M3 Max (macOS 27.0.1), direct and indirect draws alike, with and +//! without API validation, which stops none of them: a grid with an axis past +//! [`METAL_MESH_GRID_AXIS`] (65,535) draws nothing; so does one of exactly 2^20 threadgroups (1024 +//! by 1024, 128 by 128 by 64, 4096 by 256) and every one measured of 2^21 or more. Grids of up to +//! [`METAL_MESH_GRID_TOTAL`] (1,048,575, Apple's limit for the family) draw whole. Past that Metal +//! is erratic (17 by 61,681 and 65,535 by 24 drew, 1025 by 1025 and 33 by 32,768 did not); nothing +//! is Metal's answer at 2^20 and above 2^21. The mesh grid an object threadgroup sets follows the +//! same rule (65,536 along `x` or `y`, 1024 by 1024 and 2048 by 1024 launch nothing from it; 1023 +//! by 1025 and 65,535 by 16 launch whole). /// The most mesh threadgroups along an axis of a grid Metal draws without an object function /// (the module docs). @@ -85,209 +18,3 @@ pub const METAL_MESH_GRID_AXIS: u32 = 65_535; /// The most mesh threadgroups of a grid Metal draws whole without an object function (the module /// docs). pub const METAL_MESH_GRID_TOTAL: u32 = 1_048_575; - -/// The most object threadgroups of a draw the runtime runs: the most Metal's GPU ran within its -/// watchdog's 5 seconds, of an object function that does next to nothing (2^29 in 4.98 s on an -/// M3 Max; 2^30 was discarded, the module docs). A larger grid draws nothing and fails the -/// command buffer as Metal's GPU discards it. -pub const METAL_OBJECT_GRID_TOTAL: u32 = 1 << 29; - -/// Whether Metal draws nothing for a mesh grid of `groups` without an object function: an axis -/// past [`METAL_MESH_GRID_AXIS`], or more than [`METAL_MESH_GRID_TOTAL`] threadgroups. -pub(crate) fn metal_mesh_grid_draws_nothing(groups: [u32; 3]) -> bool { - let total: u128 = groups.iter().map(|&g| u128::from(g)).product(); - groups.iter().any(|&g| g > METAL_MESH_GRID_AXIS) || total > u128::from(METAL_MESH_GRID_TOTAL) -} - -/// The first stage of an indirect mesh draw, whose threadgroups Metal's arguments count. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub enum MeshArgumentsForm { - /// The mesh function's, of a pipeline without an object function. - Mesh, - /// The object function's, on a device that does not fold object grids - /// (`lower::mesh::folds_object_grids`): Metal's counts where the device's task stage launches - /// them. - Object, - /// The object function's, compiled folded on a device that folds object grids: the fold of - /// Metal's counts ([`fold_object_grid`]). - FoldedObject, -} - -/// A grid's limits: the largest count along each axis, and the largest product. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub struct MeshGridLimits { - /// The largest count along `x`, `y` and `z`. - pub axes: [u32; 3], - /// The largest product of the three counts. - pub total: u32, -} - -/// How a draw of an object grid runs on a device that folds object grids (the module docs): the -/// region record its object function reads, one piece's dispatch, and the pieces. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct ObjectFold { - /// The 32-byte region record: the threadgroups Metal runs along each axis (in the base's - /// words), the packed threads per object threadgroup, Metal's threads per grid - /// ([`metal_object_grid`]), and 0, or, for a `drawMeshThreads` that leaves a partial object - /// threadgroup, the flag that its last threadgroup along an axis runs only the threads left - /// (`lower::dispatch::NONUNIFORM`, 1). - pub record: [u32; 8], - /// The group counts of each piece's `VkDrawMeshTasksIndirectCommandEXT`, within the task - /// stage's limits. - pub dispatch: [u32; 3], - /// The pieces, each a draw whose `DrawIndex` is its number: 0 for a grid that draws nothing. - pub pieces: u32, - /// The grid has more than [`METAL_OBJECT_GRID_TOTAL`] threadgroups, which Metal's GPU - /// discards: it draws nothing, and the command buffer fails as Metal's does. - pub discarded: bool, - /// The grid takes more than [`MeshArguments::OBJECT_PIECES`] pieces (only on a device of task - /// limits below Vulkan's required least), which the device cannot launch: it draws nothing, - /// and the command buffer fails (not Metal's failure). - pub past: bool, -} - -/// Metal's grid of an object draw of `groups` threadgroups of `threads` threads each (the module -/// docs): the threadgroups it runs along each axis, and the threads per grid its builtins report, -/// `groups · threads` wrapped to 32 bits. An indirect draw (`direct` false) runs every threadgroup; -/// a direct one those the wrapped threads fill, rounded up (measured on the M3 Max). `None` where -/// an axis has no thread. -pub fn metal_object_grid( - groups: [u32; 3], - threads: [u32; 3], - direct: bool, -) -> Option<([u32; 3], [u32; 3])> { - if threads.contains(&0) { - return None; - } - let reported: [u32; 3] = std::array::from_fn(|i| groups[i].wrapping_mul(threads[i])); - let runs = match direct { - true => std::array::from_fn(|i| reported[i].div_ceil(threads[i])), - false => groups, - }; - Some((runs, reported)) -} - -/// The fold of an object draw of `groups` threadgroups of `threads` threads each (1 to 1024 an -/// axis), direct or indirect, on a task stage of `task`'s limits (the module docs); `None` when -/// `threads` does not pack. Each piece runs `nx` by `ny` workgroups of the threadgroups Metal runs -/// ([`metal_object_grid`]): `nx` the fewer of those and the axis and total limits, `ny` the -/// fewest rows that cover them within the `y` limit and the total. -pub fn fold_object_grid( - groups: [u32; 3], - threads: [u32; 3], - task: MeshGridLimits, - direct: bool, -) -> Option { - let packed = crate::lower::dispatch::pack_nominal(threads)?; - let (runs, reported) = metal_object_grid(groups, threads, direct)?; - fold_runs(runs, reported, packed, 0, task) -} - -/// The fold of a direct `drawMeshThreads` of `threads` threads in object threadgroups of `l` -/// threads each, on a task stage of `task`'s limits: the threadgroups the threads fill, rounded -/// up, whose last along an axis runs only the threads left, its record flagged -/// `lower::dispatch::NONUNIFORM` where one does (the partial object threadgroups the object -/// function runs, `RuntimeFact::PartialObjectThreadgroups`); `None` when `l` does not pack. -pub(crate) fn fold_object_threads( - threads: [u32; 3], - l: [u32; 3], - task: MeshGridLimits, -) -> Option { - let packed = crate::lower::dispatch::pack_nominal(l)?; - let runs = std::array::from_fn(|i| threads[i].div_ceil(l[i])); - let partial = (0..3).any(|i| !threads[i].is_multiple_of(l[i])); - let flags = match partial { - true => crate::lower::dispatch::NONUNIFORM, - false => 0, - }; - fold_runs(runs, threads, packed, flags, task) -} - -/// The fold of `runs` threadgroups of Metal's (packed threads per threadgroup `packed`) whose -/// grid builtins report `reported` threads, its record's last word `flags`. -fn fold_runs( - runs: [u32; 3], - reported: [u32; 3], - packed: u32, - flags: u32, - task: MeshGridLimits, -) -> Option { - let none = |discarded, past| ObjectFold { - record: [0, 0, 0, packed, 0, 0, 0, 0], - dispatch: [0; 3], - pieces: 0, - discarded, - past, - }; - if runs.contains(&0) { - return Some(none(false, false)); - } - let n = runs.iter().map(|&c| u64::from(c)).product::(); - if n > u64::from(METAL_OBJECT_GRID_TOTAL) { - return Some(none(true, false)); - } - let n = n as u32; - let total = object_total(task); - let nx = n.min(task.axes[0]).min(total).max(1); - let ny = n.div_ceil(nx).min(task.axes[1]).min(total / nx).max(1); - let pieces = n.div_ceil(nx * ny); - if pieces > MeshArguments::OBJECT_PIECES { - return Some(none(false, true)); - } - let [rx, ry, rz] = runs; - let [tx, ty, tz] = reported; - Some(ObjectFold { - record: [rx, ry, rz, packed, tx, ty, tz, flags], - dispatch: [nx, ny, 1], - pieces, - discarded: false, - past: false, - }) -} - -/// The task stage's total for a fold, at most 2^31 so that no division by it is the all-ones -/// integer's; a fold needs at most [`METAL_OBJECT_GRID_TOTAL`]. -fn object_total(task: MeshGridLimits) -> u32 { - task.total.min(1 << 31) -} - -/// An arguments pass the consumer records before an indirect mesh draw on a device with -/// `VK_EXT_mesh_shader` (the module docs): it reads Metal's arguments at `source` and writes, into -/// a scratch, the mesh form's `VkDrawMeshTasksIndirectCommandEXT` -/// (`DrawCommand::DrawMeshTasksIndirect` at offset 0 reads it; the unfolded object form's too) or -/// the folded object form's region record, draw count and commands -/// (`DrawCommand::DrawMeshTasksIndirectCount` reads them). -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct MeshArguments { - pub source: IndirectRef, - /// The module of the draw's first stage. - pub form: MeshArgumentsForm, - /// The range of the source buffer the pass reads: from `source.offset` aligned down to `minStorageBufferOffsetAlignment` (and to 4) through the - /// 12 argument bytes. - pub source_range: BufferRange, - /// The push constant bytes (`COMPUTE`, offset 0): the arguments' byte offset inside - /// `source_range`, then the packed threads per object threadgroup (0 but for the folded - /// object form). - pub push_constants: [u8; 8], -} - -impl MeshArguments { - /// The folded object form's draw count's byte offset in the scratch. - pub const OBJECT_COUNT: u32 = 32; - /// The folded object form's first command's byte offset in the scratch. - pub const OBJECT_COMMANDS: u32 = 36; - /// The folded object form's commands, the most pieces a draw takes: a piece of `nx` by `ny` - /// workgroups, `ny` the rows of `nx` the task total holds, runs more than half of the 2^22 - /// threadgroups every task stage launches per draw (`maxTaskWorkGroupTotalCount`'s required - /// least), so 256 pieces cover [`METAL_OBJECT_GRID_TOTAL`] on every device. - pub const OBJECT_PIECES: u32 = 256; -} - -#[cfg(test)] -mod tests; diff --git a/crates/metal2vulkan/src/bind/mesh_arguments/tests.rs b/crates/metal2vulkan/src/bind/mesh_arguments/tests.rs deleted file mode 100644 index 20528275a..000000000 --- a/crates/metal2vulkan/src/bind/mesh_arguments/tests.rs +++ /dev/null @@ -1,97 +0,0 @@ -//! Metal's object grid on the CPU, as Metal runs it. - -use super::*; - -/// Metal's object grids, as the M3 Max ran the owned fixture `mesh_object_grid` (macOS 27.0.1): -/// threads per grid wrap to 32 bits along each axis; an indirect draw runs every threadgroup, a -/// direct one those the wrapped threads fill, rounded up. -#[test] -fn metal_s_object_grid_wraps_its_threads_per_grid() { - for (groups, threads, direct, runs, reported) in [ - ( - [70_000, 1, 1], - [1, 1, 1], - true, - [70_000, 1, 1], - [70_000, 1, 1], - ), - ( - [300, 300, 2], - [4, 2, 1], - true, - [300, 300, 2], - [1200, 600, 2], - ), - ( - [4_194_303, 1, 1], - [1024, 1, 1], - true, - [4_194_303, 1, 1], - [4_294_966_272, 1, 1], - ), - ([4_194_304, 1, 1], [1024, 1, 1], true, [0, 1, 1], [0, 1, 1]), - ( - [4_194_304, 1, 1], - [1024, 1, 1], - false, - [4_194_304, 1, 1], - [0, 1, 1], - ), - ( - [4_194_305, 1, 1], - [1024, 1, 1], - true, - [1, 1, 1], - [1024, 1, 1], - ), - ( - [4_194_305, 1, 1], - [1024, 1, 1], - false, - [4_194_305, 1, 1], - [1024, 1, 1], - ), - ( - [4_294_968, 1, 1], - [1000, 1, 1], - true, - [1, 1, 1], - [704, 1, 1], - ), - ( - [4_294_970, 1, 1], - [1000, 1, 1], - true, - [3, 1, 1], - [2704, 1, 1], - ), - ( - [4_294_970, 1, 1], - [1000, 1, 1], - false, - [4_294_970, 1, 1], - [2704, 1, 1], - ), - ( - [2, 4_194_305, 1], - [1, 1024, 1], - true, - [2, 1, 1], - [2, 1024, 1], - ), - ( - [65536, 64, 1], - [1024, 1, 1], - true, - [65536, 64, 1], - [67_108_864, 64, 1], - ), - ] { - assert_eq!( - metal_object_grid(groups, threads, direct), - Some((runs, reported)), - "{groups:?} of {threads:?}, direct {direct}" - ); - } - assert_eq!(metal_object_grid([3, 1, 1], [0, 1, 1], true), None); -} diff --git a/crates/metal2vulkan/src/bind/mod.rs b/crates/metal2vulkan/src/bind/mod.rs index 3c2e4fc67..9ef4426c1 100644 --- a/crates/metal2vulkan/src/bind/mod.rs +++ b/crates/metal2vulkan/src/bind/mod.rs @@ -1,58 +1,29 @@ -//! The binder: from what the guest bound to what the consumer records, as plain data. +//! What a consumer computes from what the guest bound, as plain data, beside the pipelines. //! -//! The binder never calls Vulkan. The consumer describes what is bound for one draw or dispatch, -//! keyed by Metal slot, in a [`BindState`]: per [`Stage`](crate::pipeline::Stage) a [`StageTable`] -//! of [`BoundBuffer`]s, [`BoundTexture`]s, [`BoundSampler`]s, and threadgroup memory lengths, the -//! resources made resident with `useResource` or `useHeap` ([`UsedResource`]), the live sampler -//! states an argument buffer can name ([`ArgumentSampler`]), and encoder state -//! such as the compute encoder's stage-in region ([`StageInRegion`]) and the render encoder's -//! tessellation factor buffer ([`TessellationFactors`]). Binding then runs in two levels: +//! The translator binds nothing: a consumer (the runtime) binds each resource itself, under the +//! identity domains, as the pipeline's interface and push fields state. This module holds the +//! pieces of that work the translator's own semantics decide: //! -//! 1. **Plan, per shape.** [`BindState::shape`] keeps what can change a plan ([`BindShape`]: -//! which slots are bound with what kind of resource, formats, sampler modes, alignment -//! classes, and the like). `ComputePipeline::plan` and `RenderPipeline::plan` turn a pipeline -//! and a shape into a [`BindingPlan`]: one [`DescriptorWrite`] per layout binding (the resource -//! bound at a slot, a buffer the binder synthesizes, or a [`NeutralResource`] where nothing -//! compatible is bound), the vertex buffers, the [`ResourceUse`]s that drive staging, -//! writeback, and barriers, and where push fields go. A plan is a pure function of the -//! pipeline, the device, and the shape: memoize it on `(PipelineKey, BindShape)`. -//! 2. **Instantiate, per command.** [`BindingPlan::instantiate_dispatch`] of a [`Dispatch`] gives -//! [`DispatchCommands`], and [`BindingPlan::instantiate_draw`] of a [`DrawCall`] gives -//! [`DrawCommands`]: the range to bind each buffer descriptor over ([`DescriptorRange`]: -//! exactly that range, never more), the bytes to upload for argument and handle tables -//! ([`DescriptorBytes`]) and for the resident root table ([`RootTable`]), the push-constant -//! bytes with the device addresses the consumer fills in ([`PushHole`]), and the Vulkan -//! dispatches or draw to record. A Metal dispatch can become several Vulkan dispatches -//! ([`DispatchRegion`]), each with its complete specialization constants, so the consumer -//! creates one `VkPipeline` per distinct specialization. -//! -//! A plan whose [`variant`](BindingPlan::variant) is not empty asks for another variant of the -//! pipeline: compile that variant (see [`pipeline`](crate::pipeline)) and plan it for the same -//! shape. Refusals are [`BindError`](crate::error::BindError)s. -//! -//! Per command buffer, bind one [`ExecutionStatus`] buffer: initialize it with [`ExecutionStatus::initial`], and read it -//! back with [`ExecutionStatus::decode`], which reports resident-set misses and the other faults -//! [`StatusReport`] names. A command reaches it by its device address where the device addresses buffers, and -//! 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. -//! [`clamped_depth`] is a 32-bit float depth clamped into `[0, 1]`, as a copy into a depth image -//! of a device without `VK_EXT_depth_range_unrestricted` needs it. An ASTC texture -//! on a device without its block is read through a twin of Metal's decode of its blocks -//! ([`AstcDecode`], in the texels [`AstcTexels`] names); a PVRTC texture on a device without its -//! format through a twin of its texels' codes ([`PvrtcDecode`]); an ETC2 or EAC texture on a -//! device without the formats through a twin of its codes or an 11-bit format's values -//! ([`EtcDecode`], in the texels [`EtcTexels`] names). -//! [`sampler_desc`] gives the Vulkan sampler a plan's sampler write needs, and -//! [`FunctionTableSnapshot`] the one buffer of a command's visible-function tables' words. A -//! plan writes an acceleration structure as the top-level structure the consumer builds for it. -//! A [`RasterizationRateMap`] is the consumer's `MTLRasterizationRateMap`: it compiles a -//! [`RateMapDescriptor`], answers the map's queries, and gives the parameter data a -//! `rasterization_rate_map_decoder` reads. An [`ArgumentBufferLayout`] says where an argument -//! encoder (`MTLArgumentEncoder`) -//! writes each argument of an argument buffer: a function's (`Function::argument_buffer_layout`), -//! or one of [`ArgumentDescriptor`]s ([`ArgumentBufferLayout::from_descriptors`]). +//! - An [`ArgumentBufferLayout`] says where an argument encoder (`MTLArgumentEncoder`) writes each +//! argument of an argument buffer: a function's (`Function::argument_buffer_layout`), or one of +//! [`ArgumentDescriptor`]s ([`ArgumentBufferLayout::from_descriptors`]). +//! - An ASTC texture on a device without its block is read through a twin of Metal's decode of its +//! blocks ([`AstcDecode`], in the texels [`AstcTexels`] names); a PVRTC texture on a device +//! without its format through a twin of its texels' codes ([`PvrtcDecode`]); an ETC2 or EAC +//! texture on a device without the formats through a twin of its codes or an 11-bit format's +//! values ([`EtcDecode`], in the texels [`EtcTexels`] names). +//! - [`clamped_depth`] is a 32-bit float depth clamped into `[0, 1]`, as a copy into a depth image +//! of a device without `VK_EXT_depth_range_unrestricted` needs it. +//! - [`alpha_test_code`] is the code a pipeline's private alpha test compares with +//! (`PushField::AlphaTestReference`). +//! - A [`RasterizationRateMap`] is the consumer's `MTLRasterizationRateMap`: it compiles a +//! [`RateMapDescriptor`], answers the map's queries, and gives the parameter data a +//! `rasterization_rate_map_decoder` reads. +//! - [`SamplerDescriptor`] is `MTLSamplerDescriptor`; [`YCbCrPlanesSampler`] the conversion a +//! two-plane YCbCr texture's immutable sampler takes. +//! - [`Dispatch`], [`DrawCall`], [`IndexBufferRef`] and [`StageInRegion`] state a dispatch, a +//! draw, its index buffer and the compute encoder's stage-in region in Metal's terms; +//! [`indirect_commands`] lays out an indirect command buffer's records. //! //! The frozen surface is the items named at this root; the submodules are crate-private. @@ -64,21 +35,16 @@ pub(crate) mod etc_decode; pub(crate) mod graphics; pub(crate) mod heap; pub mod indirect_commands; -pub(crate) mod instantiate; pub(crate) mod mesh_arguments; pub(crate) mod neutral; -pub(crate) mod plan; pub(crate) mod pvrtc_decode; pub(crate) mod rate_map; pub(crate) mod replay; -pub(crate) mod resident; pub(crate) mod state; pub(crate) mod status; pub(crate) mod table; pub(crate) mod texel_parts; -pub(crate) mod texel_rows; pub(crate) mod ycbcr_convert; -pub(crate) mod ycbcr_in_place; pub use argument_buffer::{ ArgumentBufferLayout, ArgumentDescriptor, ArgumentLayoutError, ArgumentMember, ArgumentType, @@ -86,55 +52,20 @@ pub use argument_buffer::{ }; pub use astc_decode::{AstcDecode, AstcTexels}; pub use depth_clamp::clamped_depth; -pub use dispatch::{Dispatch, DispatchCommands, DispatchRegion, IndirectArgs}; +pub use dispatch::Dispatch; pub use etc_decode::{EtcDecode, EtcTexels}; -pub use graphics::{alpha_test_code, DrawCall, DrawCommands, IndexOverrun}; -#[cfg(test)] -pub(crate) use heap::heap_classes; -pub use heap::{handle_entry, HeapSource, HANDLE_ENTRY_BYTES}; -pub use instantiate::{ - BufferExtent, BufferRange, DescriptorBytes, DescriptorRange, IndexBufferRef, IndirectRef, - PushConstantWrite, PushHole, ResidentRange, RootTable, -}; -pub use mesh_arguments::{ - fold_object_grid, metal_object_grid, MeshArguments, MeshArgumentsForm, MeshGridLimits, - ObjectFold, METAL_MESH_GRID_AXIS, METAL_MESH_GRID_TOTAL, METAL_OBJECT_GRID_TOTAL, -}; -pub use neutral::NeutralResource; -pub use plan::resources::sampler_desc; -pub use plan::{ - AccessClass, BindingPlan, ByteRange, ComputeTemplate, DescriptorWrite, FieldLocation, - GraphicsTemplate, ImageSource, ImageViewDesc, PlanDiagnostic, PushFieldPlacement, PushTemplate, - ResourceUse, SamplerSource, UseTarget, VertexBufferBind, ViewSetup, WriteSource, -}; +pub use graphics::{alpha_test_code, DrawCall, IndexBufferRef}; +pub use pvrtc_decode::PvrtcDecode; #[cfg(test)] pub(crate) use rate_map::RateMapAxis; pub use rate_map::{ RasterizationRateMap, RateMapDescriptor, RateMapError, RateMapLayerDescriptor, UnpinnedCompile, MAX_SCREEN_EXTENT, }; -pub use replay::DRAW_ARGUMENT_BYTES; pub(crate) use replay::{merged_fragment_table, merged_vertex, MergedVertex}; -pub use replay::{DRAW_INDEX_ENTRY_BYTES, MERGED_REST_FIRST}; -pub use state::{ - ArgumentFunctionTable, ArgumentSampler, ArgumentSamplersShape, BindShape, BindState, - BoundAccelerationStructure, BoundBuffer, BoundSampler, BoundSamplerShape, BoundTexture, - BufferRanges, BufferShape, FunctionTablesShape, HeapPlacement, ImageblockSize, ResourceClass, - SamplerDescriptor, SamplerShape, StageInRegion, StageShape, StageTable, - TessellationFactorBuffer, TessellationFactors, TextureFacts, TextureShape, - TileThreadgroupArgument, TileThreadgroupMemory, UsedClass, UsedResource, UsedShape, - VertexAmplification, ViewMapping, -}; -// How `BindState::shape` classes a buffer: the crate reads it from `state`, and a consumer takes -// shapes from `BindState::shape`; only the crate's tests and validation reach it here. -pub use pvrtc_decode::PvrtcDecode; -pub use status::{ExecutionStatus, StatusBits, StatusReport, StatusWord}; -pub use table::FunctionTableSnapshot; +pub use state::{SamplerDescriptor, StageInRegion}; #[cfg(test)] pub(crate) use table::FunctionTableWords; -pub use texel_parts::part_texels; -pub use texel_rows::TexelRows; -#[cfg(test)] -pub(crate) use ycbcr_convert::YCbCrPlanes; -pub use ycbcr_convert::{YCbCrCodes, YCbCrMatrix, YCbCrOutput, YCbCrRange}; -pub use ycbcr_in_place::{YCbCrInPlace, YCbCrPlanesSampler}; +pub(crate) use texel_parts::part_texels; +pub use ycbcr_convert::YCbCrPlanesSampler; +pub(crate) use ycbcr_convert::{YCbCrCodes, YCbCrOutput}; diff --git a/crates/metal2vulkan/src/bind/neutral.rs b/crates/metal2vulkan/src/bind/neutral.rs index 78b760222..02a1cb2e5 100644 --- a/crates/metal2vulkan/src/bind/neutral.rs +++ b/crates/metal2vulkan/src/bind/neutral.rs @@ -1,139 +1,12 @@ -//! Neutral resources: stand-ins for statically used bindings with nothing (compatible) bound. -//! -//! Metal leaves reading an unbound argument undefined; Vulkan requires a valid descriptor of the -//! declared type for every layout binding. A plan therefore writes a neutral of the exact -//! descriptor, view, and numeric type the shader declares ([`NeutralResource::for_image`]). -//! -//! Neutral image and texel-buffer formats are chosen from Vulkan's mandatory format support -//! (`R8G8B8A8_{UNORM,SINT,UINT}` sampled, `D16_UNORM` depth, `R32_{SFLOAT,SINT,UINT}` storage and -//! texel buffers), except typed storage images, which must use exactly their declared format and -//! are listed only where the profile's format table supports it. +//! The numeric type a declaration of a format takes, and the format of a formatless storage +//! declaration's neutral: the stand-in a consumer binds where nothing compatible is bound, which +//! Vulkan requires for every statically used binding and Metal leaves undefined to read. Its +//! formats are of Vulkan's mandatory format support (`R32_{SFLOAT,SINT,UINT}` for storage images +//! and texel buffers). -use crate::device::profile::DeviceProfile; -#[cfg(test)] -use crate::device::requirements::FormatUsage; -use crate::pipeline::sym::{ - ImageAccess, ImageDim, ImageHandleClass, SampledType, StorageFormatClass, -}; +use crate::pipeline::sym::SampledType; use crate::vk; -/// A resource the consumer creates once per kind and binds wherever a plan asks for it. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub enum NeutralResource { - /// A zero-filled buffer of at least `min_bytes`, for uniform and storage buffer bindings. - ZeroBuffer { min_bytes: u32 }, - /// A write-only buffer of at least `min_bytes` that contained stores are redirected to. No - /// shader ever observes its contents. - Sink { min_bytes: u32 }, - /// A 1×1(×1) image with one level and one layer per view layer, viewed as `view_type`. - Image { - view_type: vk::ImageViewType, - /// The numeric type the shader reads; the image format has this numeric type. - sampled_type: SampledType, - /// A depth image for depth-comparison sampling (depth format). - depth_compare: bool, - samples: u32, - /// `Some(format)` for a storage image of exactly this format; `None` for a sampled image. - storage_format: Option, - }, - /// A texel buffer view of this format. - TexelBuffer { format: vk::Format }, - /// A sampler; `compare` enables depth comparison. - Sampler { compare: bool }, -} - -/// Sample count of every multisampled neutral image: Vulkan requires 4 in -/// `sampledImage{Color,Integer,Depth}SampleCounts`. -const NEUTRAL_SAMPLES: u32 = 4; - -impl NeutralResource { - /// Bytes of the sink buffer. - pub const SINK_BYTES: u32 = 64; - - /// The neutral for an image or texel-buffer binding whose declared type is `class`, or `None` - /// when `class` is not a type the core declares (a 3D array, a multisampled image that is not - /// 2D, a depth-comparison image that is not float, is a storage image, or is not 2D or cube, or - /// a storage format of another numeric type). Depth comparison is limited to 2D and cube - /// (arrayed or not, 2D also multisampled) because Metal has no other depth texture type, and - /// Vulkan does not guarantee a depth format for 1D or 3D images, so a neutral of that shape - /// could fail image creation. - pub fn for_image(class: &ImageHandleClass) -> Option { - let storage = class.access == ImageAccess::Storage; - let format = match (storage, class.format) { - (false, StorageFormatClass::NotStorage) => None, - (true, StorageFormatClass::Unknown) => Some(storage_neutral(class.sampled_type)), - (true, StorageFormatClass::Format(f)) if serves(f, class.sampled_type) => Some(f), - _ => return None, - }; - if class.depth_compare - && (storage - || class.sampled_type != SampledType::Float - || !matches!(class.dim, ImageDim::D2 | ImageDim::Cube)) - { - return None; - } - if class.dim == ImageDim::Buffer { - if class.arrayed || class.multisampled || class.depth_compare { - return None; - } - return Some(NeutralResource::TexelBuffer { - format: format.unwrap_or_else(|| storage_neutral(class.sampled_type)), - }); - } - if class.multisampled && class.dim != ImageDim::D2 { - return None; - } - let view_type = match (class.dim, class.arrayed) { - (ImageDim::D1, false) => vk::ImageViewType::TYPE_1D, - (ImageDim::D1, true) => vk::ImageViewType::TYPE_1D_ARRAY, - (ImageDim::D2, false) => vk::ImageViewType::TYPE_2D, - (ImageDim::D2, true) => vk::ImageViewType::TYPE_2D_ARRAY, - (ImageDim::D3, false) => vk::ImageViewType::TYPE_3D, - (ImageDim::Cube, false) => vk::ImageViewType::CUBE, - (ImageDim::Cube, true) => vk::ImageViewType::CUBE_ARRAY, - _ => return None, - }; - Some(NeutralResource::Image { - view_type, - sampled_type: class.sampled_type, - depth_compare: class.depth_compare, - samples: if class.multisampled { - NEUTRAL_SAMPLES - } else { - 1 - }, - storage_format: format, - }) - } - - /// The format of the image or texel buffer the consumer creates, or `None` for buffers and - /// samplers. - pub fn format(&self) -> Option { - match *self { - NeutralResource::Image { - sampled_type, - depth_compare, - storage_format, - .. - } => Some(storage_format.unwrap_or(if depth_compare { - vk::Format::D16_UNORM - } else { - match sampled_type { - SampledType::Sint => vk::Format::R8G8B8A8_SINT, - SampledType::Uint => vk::Format::R8G8B8A8_UINT, - // A `ulong` texture is `RG32Uint`. - SampledType::Uint64 => vk::Format::R32G32_UINT, - _ => vk::Format::R8G8B8A8_UNORM, - } - })), - NeutralResource::TexelBuffer { format } => Some(format), - _ => None, - } - } -} - /// The format of a formatless storage declaration's neutral of a numeric type: its 32-bit /// single-channel format (mandatory for storage images and both texel-buffer usages), or, for /// `ulong`, `RG32_UINT`, the view of the only format Metal binds to it, which its slot declares. @@ -146,15 +19,6 @@ pub(crate) fn storage_neutral(ty: SampledType) -> vk::Format { } } -/// Whether a storage image of `format` serves a declaration of numeric type `ty`: the format's -/// own numeric type, or, for `ulong`, `RG32_UINT`. -fn serves(format: vk::Format, ty: SampledType) -> bool { - match ty { - SampledType::Uint64 => format == vk::Format::R32G32_UINT, - _ => numeric_type(format) == Some(ty), - } -} - /// The sampled type a shader declares to read or write `format`: the registry's numeric type of /// the format's color components, or of its only depth or stencil aspect /// ([`vk::Format::numeric_type`], generated from `vk.xml`'s `numericFormat`). `None` for a @@ -169,93 +33,5 @@ pub(crate) fn numeric_type(format: vk::Format) -> Option { } } -/// Bytes of the `ZeroBuffer` neutral on `profile`: large enough for any uniform-buffer view -/// (`maxUniformBufferRange`, capped at 64 KiB), a multiple of 16. -pub fn zero_buffer_bytes(profile: &DeviceProfile) -> u32 { - let range = profile - .fields() - .limits - .max_uniform_buffer_range - .min(1 << 16); - (range & !15).max(16) -} - -/// Every image type the new core can declare on `profile` (heap classes and per-slot images): each -/// dimension, arrayed-ness, and sample count SPIR-V allows, each numeric type, depth comparison for -/// float 2D and cube images, sampled or storage with each storage format class the profile -/// supports. Cube arrays need `imageCubeArray`; a multisampled image is sampled only (no form of a -/// multisampled storage image is built). -#[cfg(test)] -pub(crate) fn image_classes(profile: &DeviceProfile) -> Vec { - let f = profile.fields(); - let types = [SampledType::Float, SampledType::Sint, SampledType::Uint]; - let shapes = [ - (ImageDim::D1, false, false), - (ImageDim::D1, true, false), - (ImageDim::D2, false, false), - (ImageDim::D2, true, false), - (ImageDim::D2, false, true), - (ImageDim::D2, true, true), - (ImageDim::D3, false, false), - (ImageDim::Cube, false, false), - (ImageDim::Cube, true, false), - (ImageDim::Buffer, false, false), - ]; - let mut out = Vec::new(); - for (dim, arrayed, multisampled) in shapes { - if dim == ImageDim::Cube && arrayed && !f.images.cube_array { - continue; - } - let class = |sampled_type, depth_compare, access, format| ImageHandleClass { - dim, - arrayed, - multisampled, - sampled_type, - depth_compare, - access, - format, - }; - for ty in types { - out.push(class( - ty, - false, - ImageAccess::Sampled, - StorageFormatClass::NotStorage, - )); - // Depth textures exist only as 2D (arrayed, multisampled) and cube (arrayed) in - // Metal, and only those shapes are guaranteed a depth format in Vulkan. - if ty == SampledType::Float && matches!(dim, ImageDim::D2 | ImageDim::Cube) { - out.push(class( - ty, - true, - ImageAccess::Sampled, - StorageFormatClass::NotStorage, - )); - } - if multisampled { - continue; - } - out.push(class( - ty, - false, - ImageAccess::Storage, - StorageFormatClass::Unknown, - )); - let usage = if dim == ImageDim::Buffer { - FormatUsage::StorageTexelBuffer - } else { - FormatUsage::StorageImage - }; - for (&format, usages) in &f.storage_formats.formats { - if usages.contains(&usage) && numeric_type(format) == Some(ty) { - let format = StorageFormatClass::Format(format); - out.push(class(ty, false, ImageAccess::Storage, format)); - } - } - } - } - out -} - #[cfg(test)] mod tests; diff --git a/crates/metal2vulkan/src/bind/neutral/tests.rs b/crates/metal2vulkan/src/bind/neutral/tests.rs index 6d7c04ccf..3bae9c845 100644 --- a/crates/metal2vulkan/src/bind/neutral/tests.rs +++ b/crates/metal2vulkan/src/bind/neutral/tests.rs @@ -1,138 +1,7 @@ //! The neutral resources: the zero buffer covers any uniform view, an undeclarable type has none, //! and their formats follow the declared type and the registry's numeric formats. -use std::path::PathBuf; - use super::*; -use crate::device::{Device, DeviceDescription, DevicePolicy}; - -/// A device for every committed profile (`validation/profiles/`, read-only), sorted by stem. -fn committed_devices() -> Vec<(String, Device)> { - let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../metal2vulkan-validation/profiles"); - let mut out: Vec<(String, Device)> = std::fs::read_dir(&dir) - .expect("validation/profiles is readable") - .map(|e| e.expect("directory entry").path()) - .filter(|p| p.extension().is_some_and(|x| x == "json")) - .map(|p| { - let stem = p.file_stem().unwrap().to_string_lossy().into_owned(); - let text = std::fs::read_to_string(&p).expect("profile is readable"); - let desc = DeviceDescription::from_khronos_json(&text, None).expect("profile parses"); - let device = - Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device derives"); - (stem, device) - }) - .collect(); - out.sort_by(|a, b| a.0.cmp(&b.0)); - assert!(out.len() >= 13, "committed profiles: {}", out.len()); - out -} - -#[test] -fn zero_buffer_covers_any_uniform_view_and_is_padded() { - for (stem, device) in committed_devices() { - let bytes = zero_buffer_bytes(device.profile()); - let range = device.profile().fields().limits.max_uniform_buffer_range; - assert_eq!(bytes % 16, 0, "{stem}"); - assert!(bytes >= range.min(1 << 16) & !15, "{stem}"); - assert!( - bytes >= 16384, - "{stem}: Vulkan's minimum maxUniformBufferRange" - ); - } -} - -fn class(dim: ImageDim, arrayed: bool, multisampled: bool) -> ImageHandleClass { - ImageHandleClass { - dim, - arrayed, - multisampled, - sampled_type: SampledType::Float, - depth_compare: false, - access: ImageAccess::Sampled, - format: StorageFormatClass::NotStorage, - } -} - -#[test] -fn undeclarable_types_have_no_neutral() { - let none = [ - class(ImageDim::D3, true, false), - class(ImageDim::D1, false, true), - class(ImageDim::Cube, false, true), - class(ImageDim::Buffer, true, false), - ImageHandleClass { - sampled_type: SampledType::Uint, - depth_compare: true, - ..class(ImageDim::D2, false, false) - }, - ImageHandleClass { - access: ImageAccess::Storage, - depth_compare: true, - format: StorageFormatClass::Unknown, - ..class(ImageDim::D2, false, false) - }, - // A storage format of another numeric type than the declared one. - ImageHandleClass { - access: ImageAccess::Storage, - format: StorageFormatClass::Format(vk::Format::R32_UINT), - ..class(ImageDim::D2, false, false) - }, - // Sampled images carry no storage format, storage images always one. - ImageHandleClass { - format: StorageFormatClass::Unknown, - ..class(ImageDim::D2, false, false) - }, - ImageHandleClass { - access: ImageAccess::Storage, - ..class(ImageDim::D2, false, false) - }, - ]; - // Depth comparison exists only for 2D and cube images. - let depth = [ - (ImageDim::D1, false), - (ImageDim::D1, true), - (ImageDim::D3, false), - (ImageDim::Buffer, false), - ] - .map(|(dim, arrayed)| ImageHandleClass { - depth_compare: true, - ..class(dim, arrayed, false) - }); - for c in none.into_iter().chain(depth) { - assert_eq!(NeutralResource::for_image(&c), None, "{c:?}"); - } -} - -#[test] -fn neutral_formats_follow_the_declared_type() { - let mut c = class(ImageDim::D2, true, false); - assert_eq!( - NeutralResource::for_image(&c).and_then(|n| n.format()), - Some(vk::Format::R8G8B8A8_UNORM) - ); - c.sampled_type = SampledType::Sint; - assert_eq!( - NeutralResource::for_image(&c).and_then(|n| n.format()), - Some(vk::Format::R8G8B8A8_SINT) - ); - c.access = ImageAccess::Storage; - c.format = StorageFormatClass::Unknown; - assert_eq!( - NeutralResource::for_image(&c).and_then(|n| n.format()), - Some(vk::Format::R32_SINT) - ); - let texel = ImageHandleClass { - sampled_type: SampledType::Uint, - ..class(ImageDim::Buffer, false, false) - }; - assert_eq!( - NeutralResource::for_image(&texel), - Some(NeutralResource::TexelBuffer { - format: vk::Format::R32_UINT - }) - ); - assert_eq!(NeutralResource::Sampler { compare: true }.format(), None); -} #[test] fn numeric_types_come_from_the_registry_numeric_formats() { diff --git a/crates/metal2vulkan/src/bind/plan.rs b/crates/metal2vulkan/src/bind/plan.rs deleted file mode 100644 index 14b45b45f..000000000 --- a/crates/metal2vulkan/src/bind/plan.rs +++ /dev/null @@ -1,938 +0,0 @@ -//! `BindingPlan`: the shape-level plan of a pipeline. -//! -//! A plan is a pure value of `(pipeline, BindShape)`, memoized by the consumer. It writes every -//! layout binding: a guest resource, a synthetic buffer, or a neutral stand-in of the exact -//! descriptor and view type. Compute planning is `ComputePipeline::plan` (`compute`); graphics -//! planning is `bind::plan::graphics`. - -pub(crate) mod compute; -pub(crate) mod resources; -pub(crate) mod slots; - -use crate::bind::heap::HeapSource; -use crate::bind::neutral::NeutralResource; -use crate::cache::{SpecializationKey, VariantKey}; -use crate::metal::sampler::OpaqueBlackBorder; -use crate::pipeline::artifact::SpecConstant; -use crate::pipeline::interface::{AccessSet, BufferForm, PlacedField, Window}; - -use crate::pipeline::sym::{ - AccelerationStructureLevel, HandleClass, PushField, SlotRef, SpecKey, Stage, -}; -use crate::pipeline::vertex::VertexStride; -use crate::vk; - -/// The shape-level binding plan of a pipeline. -#[non_exhaustive] -#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct BindingPlan { - /// The variant the shape requires: the storage-image choices, `BufferRangeLimit` device-address - /// slots, vertex buffers fixed-function input cannot fetch as bound, and a vertex function's - /// dropped `Layer` output in a pass of one layer. Empty on the common path; otherwise the consumer compiles the pipeline with - /// this variant (its keys `Device::render_variant_key`'s for a render pipeline) and plans that - /// pipeline, whose plan for the same shape states the same key. The descriptors are those of - /// the pipeline planned; a draw of a plan whose variant pulls a vertex buffer the pipeline - /// fetches fixed function is an internal error, and one whose variant drops (or keeps) the - /// vertex `Layer` output the pipeline keeps (or drops) is `BindError::NeedsVariant`. - pub variant: VariantKey, - /// Specialization of the pipeline for this shape: the constants the shape decides - /// (threadgroup lengths, slot presence). Each compute `DispatchRegion` carries the complete - /// key: these, plus its local size and `MultiRegion`. - pub specialization: SpecializationKey, - /// One write per layout binding and array element. - pub descriptors: Vec, - pub vertex_buffers: Vec, - /// Staging, writeback, and hazard facts. - pub uses: Vec, - /// Which push fields instantiation fills, and where. - pub push: PushTemplate, - pub diagnostics: Vec, - /// What `instantiate_dispatch` needs of the pipeline and the device (compute plans only). - pub compute: Option, - /// What `instantiate_draw` needs of the pipeline and the device (render plans only). - pub graphics: Option, - /// The views of a render plan's draws under the shape's vertex amplification; the default, no - /// multiview, for a compute plan. - pub views: ViewSetup, -} - -impl BindingPlan { - /// The value this plan's bound resources give `key` where a stage's specialized note alone - /// tests it (`SpecKey::BoundSamplerWord`, the bound sampler's word, and what the command's - /// handles can name), which nothing pushes; `None` for any other key. A pipeline's key carries - /// no such value, so a runtime reads a stage's notes that test it through - /// `StageModule::precision_notes_bound` with this. - pub fn specialized_value(&self, key: SpecKey) -> Option { - let resources = match (&self.compute, &self.graphics) { - (Some(c), _) => &c.resources, - (None, Some(g)) => &g.resources, - (None, None) => return None, - }; - resources - .specialized - .iter() - .find(|(k, _)| *k == key) - .map(|(_, v)| u64::from(*v)) - } -} - -// Adding a field to a plan type: a plan's content digest omits a field whose value is zero (`0`, -// `false`, `None`, empty), so a new field must hold its zero value exactly when the plan means what -// it meant before the field existed. If its zero would mean new behaviour for existing plans, the -// addition must also bump the runtime version or the validation executor's ABI (ask the -// orchestrator): the digest cannot see it (`cache::digest`, `docs/VALIDATION.md`). -#[cfg(feature = "serde")] -impl BindingPlan { - /// The plan's content digest: a SHA-256 of everything the plan states, by the rules of - /// `ComputePipeline::content_digest` (fields and enum variants by name, a field at its zero - /// value omitted), taken over its `serde` serialization. A plan names no cache key and no - /// version, so two builds that plan a pipeline for a shape alike give the same digest; it - /// changes whenever a value the plan states changes. Like the pipelines', it identifies content - /// and authenticates nothing. Fails only when a `Serialize` impl reports an error, which none - /// of the plan's types does. - pub fn content_digest(&self) -> Result { - crate::cache::digest::node_of(self) - .map(|node| node.root("binding plan")) - .map_err(|error| error.to_string()) - } -} - -/// How the consumer sets up the views of a render plan's draws. Vertex amplification is multiview: -/// amplification `a` of a draw is view `a`, which reads `a` as its `[[amplification_id]]` and -/// renders into layer `a` of each attachment view. A draw renders into the pass's layers from -/// `base_layer`: `view_mask`'s views of them, or without multiview the one layer there; the -/// default, both 0, renders the pass's every layer as a pass without amplification does. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct ViewSetup { - /// The multiview view mask: `(1 << count) - 1` for an amplification count above 1, and 0 - /// (no multiview) otherwise. The consumer creates the pipeline with it - /// (`VkPipelineRenderingCreateInfo::viewMask`, or its subpass's) and records the draw in a - /// render pass instance of the same view mask. - pub view_mask: u32, - /// The layer of the pass, counted from its first, that view 0 renders into (the first view - /// mapping's `renderTargetArrayIndexOffset` where it is below the pass's - /// `renderTargetArrayLength`, and 0 where it is not): the consumer's attachment views start - /// there, and view `a` renders into layer `base_layer + a`. Without multiview a draw whose - /// `base_layer` is not 0 renders into that one layer, through attachment views of it alone. - pub base_layer: u32, -} - -/// The pipeline and device facts a compute plan instantiates with: per buffer slot its form, -/// window, and descriptor; the specialization layout; the local-size rules; the push placement; and -/// the root-table layout. Opaque to the consumer. -#[non_exhaustive] -#[derive(Clone, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct ComputeTemplate { - /// Every statically used buffer slot, by slot. - pub(crate) buffers: Vec, - /// The stage's specialization constants, in `SpecId` order. - pub(crate) spec: Vec, - /// The values the shape decides, by key. - pub(crate) fixed: Vec<(SpecKey, u64)>, - pub(crate) local: LocalRules, - /// Every placed push field, in placement order. - pub(crate) fields: Vec, - /// `(offset, size)` of the push-constant range. - pub(crate) push_range: Option<(u32, u32)>, - /// `(set, binding, size)` of the stage's `ArgumentTable` uniform buffer. - pub(crate) table: Option<(u32, u32, u32)>, - /// The first root of the resident set (`R0`), when the function reads the root table. - pub(crate) root_first: Option, - /// The texel buffers the dispatch binds. - pub(crate) resources: ResourceTemplate, - /// Whether the kernel reads the stage-in region (`RuntimeFact::StageInRegion`): a dispatch - /// without a region is `BindError::MissingStageInRegion`. - #[cfg_attr(feature = "serde", serde(default))] - pub(crate) stage_in_region: bool, - /// The kernel's `[[stage_in]]` fetches of a thread-position step, whose elements decide each - /// region's `SpecKey::StageInReach` (`dispatch::stage_in_reach`); empty where the kernel - /// declares no such key. - #[cfg_attr(feature = "serde", serde(default))] - pub(crate) stage_in_grid: Vec, -} - -/// The pipeline and device facts a render plan instantiates with: the buffer slots of both stages, -/// each stage's push placement and tables, the fixed-function vertex buffers, and the texel -/// buffers. Opaque to the consumer. -#[non_exhaustive] -#[derive(Clone, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct GraphicsTemplate { - /// Every statically used buffer slot of both stages, by slot. - pub(crate) buffers: Vec, - /// Each stage, in pipeline order. - pub(crate) stages: Vec, - /// Every fixed-function vertex buffer, in binding order. - pub(crate) vertex_buffers: Vec, - /// `(layout, stride)` of every pulled layout with a static stride, by layout. - pub(crate) pulled_strides: Vec<(u32, u32)>, - pub(crate) resources: ResourceTemplate, - /// What a per-bind vertex stride must meet. - pub(crate) vertex_strides: StrideRules, - /// The device's `maxMultiviewInstanceIndex` when the plan's draws are multiview - /// (`ViewSetup::view_mask` is not 0); `None` otherwise. - #[cfg_attr(feature = "serde", serde(default))] - pub(crate) multiview_instance_limit: Option, - /// The pipeline planned is not the variant its vertex function's render target slice asks - /// for at the shape's render target array length: it writes `Layer` in a pass of one layer, or - /// does not in a pass of more; or not the variant the shape's vertex amplification asks for, - /// drawn as views or one amplification at a time. A draw is `BindError::NeedsVariant` with the - /// plan's `variant`. - #[cfg_attr(feature = "serde", serde(default))] - pub(crate) other_layer_variant: bool, - /// A plan whose draws draw one amplification each (`VariantKey::amplification_draws`): the - /// `(render target slice offset, viewport offset)` of each amplification, in order. Each draw - /// is recorded once per entry, after the push writes that make it that amplification's - /// (`DrawCommands::amplifications`). Empty for a plan whose draws are one draw each. A plan - /// whose pipeline is not the variant its amplification asks for sets `other_layer_variant`. - #[cfg_attr(feature = "serde", serde(default))] - pub(crate) amplifications: Vec<[u32; 2]>, - /// A tessellation pipeline's: its draws draw patches. - #[cfg_attr(feature = "serde", serde(default))] - pub(crate) tessellation: Option, - /// The device lacks `drawIndirectFirstInstance`: an indirect draw's arguments are read on - /// the CPU (`DrawCommands::indirect_needs_arguments`), since Metal's may carry a base - /// instance. - #[cfg_attr(feature = "serde", serde(default))] - pub(crate) indirect_first_instance_missing: bool, - /// A mesh render pipeline's mesh stage: its draws are mesh draws, each of its own - /// specialization. - #[cfg_attr(feature = "serde", serde(default))] - pub(crate) mesh: Option, - /// A pipeline compiled in the primitive ID's de-indexed form of this index type - /// (`VariantKey::primitive_id_indices`): its indexed draws write `PushField::CaptureLayout` - /// and run without indices. - #[cfg_attr(feature = "serde", serde(default))] - pub(crate) deindexed: Option, - /// A pipeline compiled in the private list form (`VariantKey::private_list`): its draws are - /// the consumer's lists of Metal's private primitive types, run without indices, of any - /// draw call. - #[cfg_attr(feature = "serde", serde(default))] - pub(crate) private_list: bool, - /// 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))] - pub(crate) line_band: Option, -} - -/// What a mesh draw of a mesh render pipeline instantiates: the pipeline's specialization layout -/// with the values the shape decides, which each draw completes with its threadgroups' sizes, and -/// the device's threadgroup limits of each stage. -#[derive(Clone, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub(crate) struct MeshTemplate { - /// Every stage's specialization constants, in `SpecId` order. - pub spec: Vec, - /// The values the shape decides, by key. - pub fixed: Vec<(SpecKey, u64)>, - /// Every `LocalSizeConstraint{multiple}` of the pipeline: a threadgroup of either stage must - /// be whole subgroups of the flattened tier's size. - pub multiples: Vec, - /// The mesh stage's limits (`maxMeshWorkGroup*`). - pub mesh: GroupLimits, - /// The task stage's limits (`maxTaskWorkGroup*`), of a pipeline with an object function. - pub object: Option, - /// The object function is compiled folded (`RuntimeFact::FoldedGroups`, - /// `lower::mesh::folds_object_grids`): each draw runs its object grid in pieces within the task - /// stage's limits (`bind::mesh_arguments`). - #[cfg_attr(feature = "serde", serde(default))] - pub folded: bool, - /// The object function runs a partial threadgroup as Metal does - /// (`RuntimeFact::PartialObjectThreadgroups`): a `drawMeshThreads` whose threads leave one - /// draws it, its region flagged `lower::dispatch::NONUNIFORM`. - #[cfg_attr(feature = "serde", serde(default))] - pub partial_groups: bool, -} - -/// A stage's threadgroup and grid limits. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub(crate) struct GroupLimits { - /// `max*WorkGroupSize`. - pub size: [u32; 3], - /// `max*WorkGroupInvocations`. - pub invocations: u32, - /// `max*WorkGroupCount`. - pub count: [u32; 3], - /// `max*WorkGroupTotalCount`. - pub total: u32, - /// The stage the limits are of, which names them. - pub stage: GroupStage, -} - -/// The Vulkan stage a mesh draw's threadgroups run in. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub(crate) enum GroupStage { - /// An object function's (`TASK_EXT`). - Task, - /// A mesh function's (`MESH_EXT`). - Mesh, -} - -/// 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)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub(crate) struct FactorTemplate { - pub step: crate::metal::TessellationFactorStepFunction, - /// Bytes of one patch's factors. - pub patch_bytes: u32, - /// `minStorageBufferOffsetAlignment`. - pub alignment: u64, - /// `maxStorageBufferRange`. - pub max_range: u64, - /// The `N` of the function's `[[patch(_, N)]]` (0 when unstated). - pub control_points: u32, - /// `(set, binding)` of the patch index buffer, which the control stage reads. - pub patch_indices: (u32, u32), - /// For a pipeline with a control-point index type, `(set, binding)` of the control-point index - /// buffer, which the control stage reads, and the bytes of one index (2 or 4); `None` for a - /// pipeline without one. - pub control_point_indices: Option<((u32, u32), u64)>, - /// The byte offset of the control stage's push range (`TessellationState::push_offset`), which - /// holds the draw's factor and index buffer fields. - pub push_offset: u32, - /// `(set, binding)` of the factor buffer when the plan writes it (a factor buffer is set); - /// `None` when the zero buffer stands in. - pub factor_binding: Option<(u32, u32)>, -} - -/// The device's and pipeline's rules for a per-bind vertex stride. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub(crate) struct StrideRules { - /// `maxVertexInputBindingStride`. - pub max: u32, - /// The portability subset's `minVertexInputBindingStrideAlignment`, when the device has one. - pub portability_alignment: Option, - /// The strides are dynamic state (`VK_DYNAMIC_STATE_VERTEX_INPUT_BINDING_STRIDE`): a nonzero - /// one must cover an element's attributes (`VUID-vkCmdBindVertexBuffers2-pStrides-06209`), - /// and a draw lists every binding's stride. - pub dynamic: bool, - /// The portability subset withholds `vertexAttributeAccessBeyondStride`: a stride, zero - /// included, must cover an element's attributes. - pub within_stride: bool, -} - -/// One stage of a render plan. -#[derive(Clone, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub(crate) struct StageTemplate { - pub stage: Stage, - pub flags: vk::ShaderStageFlags, - /// Every placed push field, in placement order. - pub fields: Vec, - /// `(offset, size)` of the stage's push-constant range. - pub push_range: Option<(u32, u32)>, - /// `(set, binding)` of the stage's `ArgumentTable` uniform buffer. - pub table: Option<(u32, u32)>, - /// Bytes of the stage's `ArgumentTable` (0 without one). - pub table_size: u32, - /// The first root of the resident set (`R0`), when the stage reads its root table. - pub root_first: Option, -} - -/// One fixed-function vertex buffer of a render plan. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub(crate) struct PlannedVertexBuffer { - /// The Vulkan vertex binding. - pub binding: u32, - /// The Metal vertex-stage buffer slot. - pub slot: SlotRef, - /// The pipeline's stride, or `PerBind` (the bind's `attributeStride`, dynamic state). - pub stride: VertexStride, - pub input_rate: vk::VertexInputRate, - /// The instance divisor (1 when not divided). - pub divisor: u32, - /// The largest Vulkan address alignment of the binding's attribute formats: the bind offset - /// and a per-bind stride must be multiples of it. - pub alignment: u32, - /// The bytes of one element the attributes read: the smallest attribute offset and the - /// largest `offset + format size` (`[start, end)`). - pub reads: (u32, u32), -} - -/// The texture resources a draw or dispatch instantiates: texel-buffer ranges, and the heap members -/// and handle tables. -#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub(crate) struct ResourceTemplate { - pub texel_buffers: Vec, - /// Every heap member, in element order: `heap_members[i]` is element `i + 1`. - pub heap_members: Vec, - /// Each stage's handle table. - pub handle_tables: Vec, - /// The level count the binder pushes for each slot whose level count a function reads - /// (`PushField::TextureLevels`): the bound texture's, 0 where a neutral stands in. - #[cfg_attr(feature = "serde", serde(default))] - pub texture_levels: Vec<(SlotRef, u32)>, - /// The integer channel widths of the bound texture, which the binder pushes for each slot - /// whose integer writes read them (`PushField::TextureIntegerChannels`): - /// `metal::format::integer_channels_word` of its format, 0 where a neutral stands in. - #[cfg_attr(feature = "serde", serde(default))] - pub texture_integer_channels: Vec<(SlotRef, u32)>, - /// The value of each key a specialized note's test alone reads (`SpecKey::BoundSamplerWord`, - /// and what the command's handles can name), which nothing pushes (`slots::record_noted`). - #[cfg_attr(feature = "serde", serde(default))] - pub specialized: Vec<(crate::pipeline::sym::SpecKey, u32)>, - /// Each stage's sampler table. - #[cfg_attr(feature = "serde", serde(default))] - pub sampler_tables: Vec, - /// The argument samplers' shape the sampler arrays and tables were planned for, when the - /// plan has one. - #[cfg_attr(feature = "serde", serde(default))] - pub argument_samplers: Option, - /// What the sampler arrays and tables admit of a sampler state of a shape - /// `argument_samplers` does not list, as a command buffer lists the states again. - #[cfg_attr(feature = "serde", serde(default))] - pub sampler_admission: crate::bind::heap::SamplerAdmission, - /// Each stage's function-table directory. - #[cfg_attr(feature = "serde", serde(default))] - pub function_table_directories: Vec, - /// The tables' shape the function-table directories were planned for, when the plan has one. - #[cfg_attr(feature = "serde", serde(default))] - pub function_tables: Option, - /// The directories hold each table's device address, not an element or a snapshot offset: the - /// pipeline reads the tables' words there. - #[cfg_attr(feature = "serde", serde(default))] - pub function_table_addresses: bool, - /// Each `SlotGuestBase` word is the slot's address less - /// [`SLOT_ADDRESS_BIAS`](crate::lower::access::SLOT_ADDRESS_BIAS), which the pipeline's - /// accesses add back: the device compiles under the identity domains (docs/API.md section 5). - #[cfg_attr(feature = "serde", serde(default))] - pub biased_slot_words: bool, -} - -/// One bound texel buffer of a plan. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub(crate) struct PlannedTexel { - pub set: u32, - pub binding: u32, - pub slot: SlotRef, - /// `minTexelBufferOffsetAlignment`. - pub alignment: u64, - /// `maxTexelBufferElements`. - pub max_elements: u64, - /// The view format's texel block: bytes and texels per block (`vk::Format::block`). - pub block_size: u64, - pub texels_per_block: u64, - /// The views the binding holds, the elements of its descriptor array: 1, or the parts of a - /// texture buffer bound under its parts variant (`VariantKey::texel_buffer_parts`, - /// `bind::texel_parts`). - #[cfg_attr(feature = "serde", serde(default = "one_view"))] - pub parts: u32, - /// The texels of each part but the last (`bind::part_texels`). - #[cfg_attr(feature = "serde", serde(default))] - pub part_texels: u64, -} - -/// The views of a planned texel buffer stated without them: one. -#[cfg(feature = "serde")] -fn one_view() -> u32 { - 1 -} - -/// One statically used buffer slot of a compute plan. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub(crate) struct PlannedBuffer { - pub slot: SlotRef, - pub window: Window, - pub form: BufferForm, - pub access: AccessSet, - /// `(set, binding)` of a descriptor-form slot. - pub binding: Option<(u32, u32)>, - /// The descriptor base alignment: `minStorageBufferOffsetAlignment`, at least 16 - /// (`views::base_alignment`). - pub alignment: u64, - /// `maxStorageBufferRange`. - pub max_range: u64, - /// What the shape binds at the slot. - pub bound: BoundKind, -} - -/// What a shape binds at a buffer slot. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub(crate) enum BoundKind { - Unbound, - Buffer { - device_address: bool, - /// The allocation's `BindShape` length class. - length_class: u8, - }, - Bytes, -} - -/// The local-size rules every dispatch region satisfies. -#[derive(Clone, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub(crate) struct LocalRules { - /// The flattened tiers' `(sn, 1, 1)` workgroup (`SpecKey::FlatLocalSize`). - pub flat: bool, - /// The kernel declares `SpecKey::DeepThreadgroup`: a region deeper than - /// [`crate::pipeline::DEEP_THREADGROUP`] runs as one row, checked as the flattened tiers'. - pub deep: bool, - /// Every `LocalSizeConstraint{multiple}` of the pipeline. - pub multiples: Vec, - pub max_size: [u32; 3], - pub max_invocations: u32, - /// `maxComputeWorkgroupSubgroups`. - pub max_subgroups: u32, - pub max_count: [u32; 3], - pub required_subgroup_size: Option, - pub stage_flags: vk::PipelineShaderStageCreateFlags, - /// The emulated simdgroups' scratch (`RuntimeFact::SimdgroupEmulation`). - pub scratch: Option, - /// A region of one row needs no whole subgroups (`RuntimeFact::RowLockstep`). - pub rows: bool, - /// The masks of axes whose unit-axes variant relieves the kernel's predicated walk - /// (`RuntimeFact::UnitAxes`'s `relief`: bit `m − 1` for mask `m`), 0 where none does or the - /// pipeline is that variant. - pub unit_relief: u8, - /// The pipeline is a tile function (`RuntimeFact::TileFunction`): its threads take Metal's - /// tile-dispatch layout, built for the threadgroups `dispatch::tile_layout_measured` takes, - /// dispatched by threadgroups. - pub tile: bool, - /// The threadgroup Metal answers a tile function whose threadgroup is the tile - /// (`RuntimeFact::TileThreadgroup` with `tile_sized`): the shape's tile, its imageblock size, - /// one deep. Every region of its dispatches carries it as the nominal threadgroup - /// (`MultiRegion` 1) and the grid of its tiles, whatever threads per tile run. - pub tile_threadgroup: Option<[u32; 3]>, - /// The kernel runs its grid in tiles (`RuntimeFact::GridTiles`): a direct dispatch's regions - /// are [`crate::pipeline::grid_tile`]'s tiles of its threads, one workgroup of - /// [`crate::pipeline::GRID_TILE_THREADS`] each. - pub grid_tiles: bool, -} - -/// A region of `N` threads takes `fixed + ⌈N / 32⌉ · per_simdgroup` bytes of threadgroup memory, -/// at most `available` (`maxComputeSharedMemorySize`), when the kernel's simdgroups are emulated. -/// `fixed` is the declared arena with its `[[threadgroup(n)]]` regions -/// (`lower::simd::workgroup::arena_bytes`: whole words and at least `MIN_ARENA_BYTES`). -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub(crate) struct ScratchRule { - pub per_simdgroup: u32, - pub fixed: u64, - pub available: u32, -} - -/// One descriptor write. -#[non_exhaustive] -#[derive(Clone, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct DescriptorWrite { - pub set: u32, - pub binding: u32, - pub array_element: u32, - pub ty: vk::DescriptorType, - pub source: WriteSource, -} - -/// What a descriptor write points at. -#[non_exhaustive] -#[derive(Clone, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub enum WriteSource { - /// The buffer bound at `slot`. The range is derived from the slot's window and bind offset: the - /// consumer binds exactly that range, never more. - Buffer { slot: SlotRef }, - /// `set*Bytes` data uploaded by the consumer. - InlineBytes { slot: SlotRef }, - /// The texture bound at `slot`, through this view. - Texture { slot: SlotRef, view: ImageViewDesc }, - /// A combined image sampler: its image and its sampler. - CombinedImageSampler { - image: ImageSource, - sampler: SamplerSource, - }, - /// The planes of the two-plane YCbCr texture bound at `slot`, read in place - /// (`TextureFacts::ycbcr_in_place`): a uniform texel buffer over the planes' bytes in - /// `R8G8_UINT` of 8-bit codes or `R16G16_UINT` of 10-bit ones, from the first byte of the - /// first plane through the last row of codes either plane holds. Only a slot under its - /// in-place variant binds it - /// (`VariantKey::ycbcr_in_place`). - YCbCrInPlace { slot: SlotRef }, - /// The planes of the two-plane YCbCr texture bound at `slot`, held as an image the device's - /// own sampler Y′CbCr conversion samples (`TextureShape::Texture::ycbcr_planes_sampler`): a - /// combined image sampler whose image is that image viewed with the conversion - /// (`bind::YCbCrPlanesSampler`) and whose sampler is the binding's immutable one, in - /// `GENERAL`. Only a slot under its planes-image variant binds it - /// (`VariantKey::ycbcr_planes_sampled`, `BindingSource::YCbCrPlanes`). - YCbCrPlanesImage { slot: SlotRef }, - /// The rows of the 2D texture bound at `slot`, read and written in place - /// (`TextureFacts::texel_rows`, `bind::texel_rows`): a texel buffer in `format` over the - /// texture's bytes, from its first texel, or before it where the device's texel buffer offset - /// alignment asks, through its last row's last texel; uniform where the slot's function only - /// reads the texture, storage where it writes it. Only a slot under its rows variant binds it - /// (`VariantKey::texel_rows`). - TexelRows { slot: SlotRef, format: vk::Format }, - /// The texture buffer bound at `slot`, as a texel buffer view. - TexelBuffer { - slot: SlotRef, - format: vk::Format, - window: Window, - }, - /// A `VkSampler` for the sampler bound at `slot`, made for this use: `compare` enables depth - /// comparison and `integer` selects integer border colors (`metal::sampler::SamplerUse`, - /// `bind::sampler_desc`). The plan checks what the shape states - /// (reduction); the rest of the descriptor is per bind. `opaque_black` says how an opaque-black - /// border is made to read Metal's texel through every texture the sampler meets - /// (`metal::sampler::OpaqueBlackBorder`). - Sampler { - slot: SlotRef, - compare: bool, - integer: bool, - opaque_black: OpaqueBlackBorder, - }, - /// The stage's argument table; instantiation fills the bytes. - ArgumentTable { stage: Stage, bytes_len: u32 }, - /// A handle table of `stage` (its texture table, or its sampler table), a read-only storage - /// buffer of `bytes_len` bytes whose contents instantiation gives (`DescriptorBytes`). The - /// consumer binds exactly `bytes_len` bytes: the shader counts the table's entries from the - /// bound range. - HandleTable { stage: Stage, bytes_len: u32 }, - /// The constant blob of `stage`: its `StageModule::constant_blob`, padded to 16 bytes by the - /// consumer. - ConstantBlob { stage: Stage }, - /// Element `element` of the set-1 heap array of `class`: the resident texture `source`, - /// through this view. Every write of one texture has one layout: `GENERAL` when some storage - /// array holds it or, for a texture bound at a slot, the slot's own binding is a storage image; - /// `SHADER_READ_ONLY_OPTIMAL` otherwise. - HeapEntry { - class: HandleClass, - element: u32, - source: HeapSource, - view: ImageViewDesc, - }, - /// Color attachment `color_index`, as an input attachment. - Attachment { color_index: u32 }, - /// A neutral stand-in: statically used, nothing (compatible) bound. - Neutral(NeutralResource), - /// The encoder's tessellation factor buffer (`BindState::tessellation_factors`), a - /// read-only storage buffer of the control stage over the draw's `DescriptorRange`. - TessellationFactors, - /// The top-level structure of the acceleration structure bound at buffer slot `slot` - /// (`setAccelerationStructure:atBufferIndex:`): the bound instance structure itself when - /// `level` is `Instance`, and, when `level` is `Primitive`, the top-level structure of one - /// instance over the bound primitive structure. A slot the guest left unbound takes a - /// top-level structure of no instances, which every ray misses. - AccelerationStructure { - slot: SlotRef, - level: AccelerationStructureLevel, - }, - /// 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 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, - }, - /// The tile map of the sparse texture bound at texture slot `slot`: a read-only storage - /// buffer of the map's words, a bit per tile of each level and slice set while Metal has the - /// tile mapped, from which a function answers the texture's residency where the device has no - /// shader residency. The consumer binds the map it keeps for that texture, holding the mappings - /// Metal's would hold when the command runs. A slot whose bound texture is not sparse takes the - /// zero buffer instead: the module reads no tile map there. - TileMap { slot: SlotRef }, - /// Element `index + 1` of a set-1 sampler array: a `VkSampler` for - /// `BindState::argument_samplers[index]`, made for this use as `Sampler` is - /// (`bind::sampler_desc` with `compare` and `integer`), or the neutral sampler - /// (`NeutralResource::Sampler { compare }`) where the state lists fewer samplers: no handle - /// names that element then. The plan writes every element of its shape's capacity class - /// (`ArgumentSamplersShape::entries`), so the list may grow or shrink within the class - /// without a new plan; the consumer resolves each write against the state it binds. - ArgumentSampler { - index: u32, - compare: bool, - integer: bool, - }, - /// A patch draw's patch index buffer (`DrawCall::Patches::patch_index`), a read-only storage - /// buffer of the control stage over the draw's `DescriptorRange`. A draw without one has no range for it, and the consumer binds - /// the zero buffer of `min_bytes` there (`NeutralResource::ZeroBuffer`'s), whose words the - /// stage discards: the draw pushes `PushField::PatchIndexBound` 0. - PatchIndices { min_bytes: u32 }, - /// An indexed patch draw's control-point index buffer - /// (`DrawCall::Patches::control_point_index`), a read-only storage buffer of the control - /// stage of a pipeline with a control-point index type over the draw's `DescriptorRange`. Every draw of such a pipeline has one. - ControlPointIndices, - /// The render pass's tile threadgroup memory (`SyntheticBinding::TileMemory`): a storage - /// buffer the consumer keeps for the pass, of at least `bytes` bytes (every tile of the - /// render area, each `SpecKey::TileThreadgroupLength` bytes), zeroed when the pass begins and - /// kept across its tile dispatches, bound whole. - TileMemory { bytes: u64 }, - /// The function-table snapshot (`SyntheticBinding::FunctionTableSnapshot`): a read-only - /// storage buffer of the words of `BindState::function_tables`, laid out as - /// [`FunctionTableSnapshot`](crate::bind::FunctionTableSnapshot) of the listed sizes gives - /// them, bound whole. The consumer writes it as the command's command buffer commits: the - /// command reads each table's entries as they stand then, where Metal reads them as they - /// stand when the command runs, which differs only for a CPU write racing the GPU. The - /// stage's directory gives each listed id its record's offset, by the same sizes. - FunctionTableSnapshot, - /// The command buffer's execution status (`SyntheticBinding::ExecutionStatus`) of a stage on - /// a device that does not address buffers: a storage buffer of the - /// [`ExecutionStatus`](crate::bind::ExecutionStatus) words, the same buffer every command of - /// the command buffer writes (where the device addresses buffers, the one whose address - /// `PushHole::ExecutionStatusAddress` takes), its - /// [`ExecutionStatus::BYTES`](crate::bind::ExecutionStatus::BYTES) bytes bound, starting all - /// zero ([`ExecutionStatus::initial`](crate::bind::ExecutionStatus::initial)). The consumer - /// reads it once the command buffer completes. - ExecutionStatus, -} - -/// The image of a combined image-sampler write. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub enum ImageSource { - /// The texture bound at `slot`, through this view. - Texture { slot: SlotRef, view: ImageViewDesc }, - /// A neutral image of the declared type. - Neutral(NeutralResource), -} - -/// The sampler of a combined image-sampler write. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub enum SamplerSource { - /// A `VkSampler` for the runtime sampler bound at `slot`, made for this use (as - /// `WriteSource::Sampler`). - Slot { - slot: SlotRef, - compare: bool, - integer: bool, - opaque_black: OpaqueBlackBorder, - }, - /// The layout's immutable (constexpr) sampler: the write carries only the image. - Immutable, - /// The neutral sampler: the runtime sampler slot is unbound. - Neutral(NeutralResource), -} - -/// The view the consumer creates for a texture write. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct ImageViewDesc { - pub view_type: vk::ImageViewType, - /// The view format: the texture's own (an 8-bit sRGB texture's UNORM twin where the device - /// holds one), or the storage alias the variant chose. - pub format: vk::Format, - pub aspect: vk::ImageAspectFlags, - /// The layout the texture is in while the draw or dispatch runs. Every write of one slot's - /// texture or one heap member has the same layout, `GENERAL` when one of them is a storage - /// image; the plan cannot see that two slots or members hold one texture. - pub layout: vk::ImageLayout, - pub components: vk::ComponentMapping, - /// The levels the view holds: `None` every level of the texture, `Some(i)` level `i` alone, - /// an element of a storage slot's level views (`RuntimeFact::StorageTextureLevelViews`). Levels - /// count from the bound texture's own first level: level `i` of a Metal texture view whose - /// first level is its parent's level `b` is the parent's level `b + i`. Every layer either way. - #[cfg_attr(feature = "serde", serde(default))] - pub level: Option, - /// The function applies the bound texture's swizzle (`MTLTexture.swizzle`) to the texels it - /// reads and writes through the view, so the view takes none: its component mapping is - /// `components` alone. Set for a storage view of a swizzled texture at a slot of - /// `VariantKey::swizzled_storage`, which a Vulkan storage view could not swizzle, and - /// for the sampled view of a swizzled extended-range texture at a slot of it, whose raw codes - /// the view's swizzle would move before the function decodes them, and of a swizzled packed - /// normalized texture, whose codes the function converts by each channel's own scale. Set too, - /// under no variant, for the storage view of a swizzled texture at a slot the function only - /// queries: it reads and writes no texel, and no swizzle reaches what a query answers. `false` - /// for every other view, on which the consumer composes the texture's swizzle with - /// `components` (and a swizzled storage view is the consumer's refusal). - #[cfg_attr(feature = "serde", serde(default))] - pub shader_swizzle: bool, -} - -/// A Vulkan vertex buffer binding fed by a Metal vertex-stage buffer slot. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct VertexBufferBind { - pub binding: u32, - /// The Metal buffer index in the vertex stage. - pub buffer_index: u32, - /// The stride comes from the bind (`attributeStride`), as dynamic state. - pub per_bind_stride: bool, -} - -/// Which push fields instantiation fills. -#[non_exhaustive] -#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct PushTemplate { - /// In placement order per stage. - pub fields: Vec, -} - -/// Where one push field of one stage lives. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct PushFieldPlacement { - pub stage: Stage, - pub field: PushField, - pub location: FieldLocation, - pub size: u32, -} - -/// A push field's location: the stage's push window, or its spill to the argument table. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub enum FieldLocation { - /// Byte offset in the pipeline's push-constant block. - PushWindow { offset: u32 }, - /// Byte offset in the stage's argument table. - ArgumentTable { offset: u32 }, -} - -/// Something the plan did that the consumer may want to log. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub enum PlanDiagnostic { - /// The resource bound at `slot` does not match the shader's declared type; a neutral of the - /// declared type is written instead (guest undefined behavior). - IncompatibleBinding { - slot: SlotRef, - substituted: NeutralResource, - }, - /// The resident texture `source` matches the heap array of `class` in everything but its - /// numeric type, and the array's numeric type is only the default of a heap group that is - /// only queried (`RuntimeFact::HeapNumericType`): element `element` of the array is the - /// neutral, so a query through a handle to `source` answers the neutral's. - IncompatibleHeapEntry { - class: HandleClass, - element: u32, - source: HeapSource, - substituted: NeutralResource, - }, - /// The texture bound at `slot` matches the shader's declared type in everything but its - /// numeric type (its format's class, float or signed or unsigned integer, is not the declared - /// one), and the plan has no exact answer for it: plain Metal reads such a texture in its own - /// class and hands back the words as the declared type (and stores a write's lanes' bits as - /// its own class), which the slot's variant (`VariantKey::cross_class`) gives for a color - /// texture where the function's compile states `RuntimeFact::CrossClassReads` (storage slots, - /// texture buffers, multisampled and sparse textures, writes, `short` and `ushort` results and - /// queries among them). A depth, stencil, extended-range or YCbCr texture, a depth slot, an - /// atomic or `ulong` access, a written slot over a swizzled texture and an integer write to an - /// `RGB9E5Float` texture are not measured. A neutral of the declared type is written instead, - /// which the runtime announces (`cross-class-texture-neutral`). - CrossClassNeutral { - slot: SlotRef, - substituted: NeutralResource, - }, - /// The resident texture `source`, which the `stage` function reaches, matches the heap array - /// of `class` in everything but its numeric type, and the stage reads that class by an access - /// with no answer for it (`RuntimeFact::HeapCrossClassNeutral`: a sample, gather or LOD - /// query, a write or atomic, a storage or multisampled group's read, a `short`, `ushort` or - /// `ulong` read; or any access, for a depth, stencil, extended-range or two-plane texture): - /// element `element` of the array is the neutral, which such an access reads, where plain - /// Metal reads the texture in its own class. The runtime announces it - /// (`cross-class-texture-neutral`). - CrossClassHeapNeutral { - stage: Stage, - class: HandleClass, - element: u32, - source: HeapSource, - }, - /// The texture bound at storage slot `slot` (a function's write, or read and write) is an - /// ASTC texture, whose blocks no storage view stores into: plain Metal completes the - /// function's writes, storing bytes no format defines into the blocks, and reads the blocks' - /// decode through a slot that also reads them. A neutral of the declared type is written - /// instead (its writes dropped, its reads zero, its size queries the neutral's), which leaves - /// the texture's blocks as they were; the runtime announces it (`astc-storage-neutral`). - AstcStorageNeutral { - slot: SlotRef, - substituted: NeutralResource, - }, -} - -/// How a draw or dispatch uses one resource: staging, writeback, and hazard facts. A plan's `uses` -/// are the shape's (bound slots, used resources); `DrawCommands.uses` and `DispatchCommands.uses` -/// add each command's index buffer and indirect arguments. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct ResourceUse { - pub resource: UseTarget, - /// Proven from lowering; unknown access is `READ_WRITE`. - pub access: AccessSet, - pub class: AccessClass, - pub stages: vk::PipelineStageFlags2, - /// `None`: the whole resource from the bound offset. The bound offset of a slot is its bind - /// offset; of the index buffer, the draw's index offset; of the indirect buffer, the - /// arguments' offset. - pub range: Option, -} - -/// The resource a [`ResourceUse`] names. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub enum UseTarget { - /// The resource bound at a slot. - Slot(SlotRef), - /// A used resource, by consumer token. - Used(u32), - /// The draw's index buffer. - IndexBuffer, - /// The draw's or dispatch's indirect buffer. - Indirect, - /// The encoder's tessellation factor buffer, from its bind offset. - TessellationFactors, - /// The tile map of the sparse texture bound at a texture slot, whole: the consumer's update of - /// the map before the command (a mapping change) needs a barrier to this read. - TileMap(SlotRef), - /// A patch draw's patch index buffer, from the draw's offset into it. - PatchIndices, - /// An indexed patch draw's control-point index buffer, from the draw's offset into it. - ControlPointIndices, -} - -/// How a resource is accessed, for barrier stage/access selection. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub enum AccessClass { - Storage, - Sampled, - StorageImage, - VertexInput, - Index, - Indirect, - Attachment, - /// A two-plane YCbCr texture's planes, read in place through the slot's uniform texel buffer - /// (`WriteSource::YCbCrInPlace`) or the image of them the device's conversion samples - /// (`WriteSource::YCbCrPlanesImage`): a read of the planes' bytes, not of the texture's image. - YCbCrPlanes, - /// A 2D texture's rows, read or written in place through the slot's texel buffer - /// (`WriteSource::TexelRows`): a use of the rows' bytes, not of the texture's image. - TexelRows, -} - -/// A byte range relative to the bound offset. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct ByteRange { - pub offset: u64, - pub len: u64, -} diff --git a/crates/metal2vulkan/src/bind/plan/compute.rs b/crates/metal2vulkan/src/bind/plan/compute.rs deleted file mode 100644 index 81f297c96..000000000 --- a/crates/metal2vulkan/src/bind/plan/compute.rs +++ /dev/null @@ -1,968 +0,0 @@ -//! Compute planning: [`ComputePipeline::plan`]. -//! -//! The plan is a pure function of the pipeline, the device it was compiled for, and the shape: -//! -//! - **Descriptors.** Every binding of the pipeline's layout gets one write: a bound buffer slot -//! its `Buffer` (the range comes per dispatch) or `InlineBytes`, an unbound one the `ZeroBuffer` -//! neutral, the stage's `ArgumentTable` UBO, and the pipeline's `ConstantBlob`. Textures, -//! samplers, combined image samplers, and texel buffers go through the shared resource planner -//! (`plan::resources`); the handle table and every element of the set-1 heap arrays up to the -//! heap's members through the heap planner (`bind::heap`). -//! - **Device addresses.** Every `BufferForm::Psb` slot is reached through its root-table entry, so -//! a buffer bound there without a device address, or `set*Bytes` data, is `MissingDeviceAddress`; -//! an unbound one gets a zero entry (every access contained). -//! - **Specialization.** Threadgroup lengths (`TgLength`, Metal's 16-byte rounding applied) and -//! slot presence are fixed here; the specialized threadgroup total -//! `static_threadgroup_memory_length + Σ round_up(len, 16)` must fit -//! `maxComputeSharedMemorySize`. With emulated simdgroups the static part is the arena's own -//! (`RuntimeFact::SimdgroupEmulation`), and every region also fits the scratch of its simdgroups -//! beside the declared arena. A predicated walk's vote word (`RuntimeFact::PredicationVote`) is -//! counted beside the arena too. Local size, `MultiRegion` and `StageInReach` are per region. -//! - **Variant.** The shape's storage-image choices and device-address slots, and the emulated -//! simdgroups of a pipeline compiled for them (`RuntimeFact::EmulatedSimdgroups`); a dispatch -//! adds those where its threadgroups need them (`BindingPlan::dispatch_variant`). The flat grid -//! of a pipeline compiled for one (`RuntimeFact::FlatGrid`), and the folded groups of one -//! compiled for them (`RuntimeFact::FoldedGroups`). -//! - **Imageblocks**. A kernel with an explicit imageblock (`RuntimeFact::ImageblockSize`) -//! specializes its extent from `BindState::imageblock_size`, which must be 1 to 65535 in each -//! axis (`BindError::InvalidImageblockSize`); its `width · height · cell_bytes` bytes are one -//! more 16-byte-aligned region of the threadgroup total, after the static part rounded to 16. A -//! slot receiving imageblock slices takes any pixel format: a narrow element's texel is its lanes -//! and zeros in every format, as Metal writes it. -//! - **Tile functions** (`RuntimeFact::TileFunction`). The render area (`BindState::render_area`, -//! at least one pixel in each axis, `BindError::InvalidRenderArea` otherwise) is specialized, a -//! layered pass is `Unsupported{TileShading, NotImplemented}`, and each attachment the function -//! stages is a `WriteSource::TileAttachment` in the view format its staging reads -//! (`lower::access::tile::staging_format`). -//! - **Tile threadgroup memory** (`RuntimeFact::TileThreadgroupMemory`). A tile function that reads -//! its `[[threadgroup(n)]]` arguments specializes each argument's offset in its tile's memory -//! (`SpecKey::TgOffset`, from `BindState::tile_threadgroup`), the tile's bytes -//! (`SpecKey::TileThreadgroupLength`, the pass's length rounded up to 16) and the tiles across -//! the render area (`SpecKey::TileGridWidth`), and binds the pass's tile memory -//! (`WriteSource::TileMemory`, every tile's bytes). An argument the encoder did not set is -//! `BindError::MissingThreadgroupMemory`. Every offset is placed, as plain Metal takes every -//! offset, at the offset floored to a multiple of 4, which is where plain Metal begins the -//! argument ([`tile_argument_offset`] carries the measurement). An argument's length bounds -//! nothing, as plain Metal's does not. The tile's bytes start the threadgroup total. -//! - **Kept imageblock bytes** (`RuntimeFact::TileImageblock`). A tile function whose explicit -//! imageblock stands alone, in a pass that keeps fewer bytes of its cells than its data -//! (`BindShape::kept_imageblock_bytes`), asks for `VariantKey::kept_imageblock_bytes`: plain -//! Metal reads the other words as zero and drops their writes. -//! - **Stage-in strides**. A layout of a fixed stride reads its own, whatever stride the shape -//! binds its buffer with; one of `MTLBufferLayoutStrideDynamic` (`RuntimeFact::StageInStride`) -//! reads the bound one, which instantiation pushes (`PushField::StageInStride`, 0 for a buffer -//! bound without one). The template keeps each fetch of a thread-position step, from whose -//! elements each region decides `SpecKey::StageInReach`. -//! - **Push fields.** Every placed field is one the binder fills: the root-table and status -//! addresses (holes the consumer fills), `DispatchRegion` (always written), `StageInRegion` (the -//! dispatch's `BindState::stage_in_region`), `StageInStride` (the bound buffer's attribute -//! stride), `SlotBindOffset`, and `SlotGuestBase` (the bound buffer's Metal address; a slot bound -//! with `set*Bytes` has none and is refused as `MissingGuestAddress`). - -use super::resources::{separate_samplers, ResourcePlanner}; -use super::slots::{ - address_map_variant, anisotropic_variant, bindings, bound_value, buffer_use, check_slots, - check_sparse_textures, cross_variant, cubic_variant, heap_raw, open_cl_line_variant, - plan_buffer, psb_variant, record_noted, srgb_variant, texel_buffer_parts_variant, used_uses, - ycbcr_in_place_variant, ycbcr_planes_sampled_variant, -}; -use super::{ - BindingPlan, BoundKind, ComputeTemplate, DescriptorWrite, FieldLocation, LocalRules, - PushFieldPlacement, PushTemplate, ResourceUse, ScratchRule, WriteSource, -}; -use crate::bind::heap::{planner, HeapPlanner}; -use crate::bind::neutral::{zero_buffer_bytes, NeutralResource}; -use crate::bind::state::{BindShape, StageShape}; -use crate::cache::{SpecializationKey, VariantKey}; -use crate::device::requirements::VkLimit; -use crate::device::Device; -use crate::error::{ - BindError, Capability, Feature, InternalError, InternalKind, LowerFamily, Unsupported, -}; -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::interface::{BufferForm, PushLoc, SlotInterface}; -use crate::pipeline::layout::BindingSource; -use crate::pipeline::sym::{PushField, SlotClass, SlotRef, SpecKey, Stage, SyntheticBinding}; -use crate::vk; -use std::collections::BTreeMap; - -/// Metal rounds every threadgroup-memory length to 16 bytes. -const TG_ALIGN: u64 = 16; - -/// What plain Metal floors a tile threadgroup argument's offset to, in bytes -/// ([`tile_argument_offset`] carries the measurement). -const TG_FLOOR: u32 = 4; - -pub(crate) fn internal(detail: impl Into) -> BindError { - BindError::Internal(InternalError::new(InternalKind::Invariant, detail)) -} - -pub(crate) fn not_implemented(feature: Feature) -> BindError { - BindError::Unsupported(Unsupported::not_implemented(feature)) -} - -/// The largest imageblock extent in either axis: `get_imageblock_width` is a `ushort`. -const MAX_IMAGEBLOCK_EXTENT: u32 = u16::MAX as u32; - -/// The bytes of the kernel's explicit imageblock for `shape`'s extent, rounded up to 16; `None` -/// without one. An extent of 0 or above 65535 in either axis is `BindError::InvalidImageblockSize`. -fn imageblock_bytes(p: &ComputePipeline, shape: &BindShape) -> Result, BindError> { - let Some(cell_bytes) = p.dependencies.iter().find_map(|d| match d.fact { - RuntimeFact::ImageblockSize { cell_bytes } => Some(cell_bytes), - _ => None, - }) else { - return Ok(None); - }; - let s = shape.imageblock_size; - let valid = |n: u32| (1..=MAX_IMAGEBLOCK_EXTENT).contains(&n); - if !valid(s.width) || !valid(s.height) { - return Err(BindError::InvalidImageblockSize { - width: s.width, - height: s.height, - }); - } - let bytes = u64::from(s.width) * u64::from(s.height) * u64::from(cell_bytes); - Ok(Some(bytes.next_multiple_of(TG_ALIGN))) -} - -/// A tile function's pass has a render area (`BindState::render_area` of at least one pixel in each -/// axis; `BindError::InvalidRenderArea` otherwise: the consumer never set it, and the function -/// would stage no pixel), and is not layered: what a tile dispatch of a layered pass runs, and what -/// `[[render_target_array_index]]` reads in it, is not read yet. -fn check_tile_pass(p: &ComputePipeline, shape: &BindShape) -> Result<(), BindError> { - if !is_tile_function(p) { - return Ok(()); - } - let [width, height] = shape.render_area; - if width == 0 || height == 0 { - return Err(BindError::InvalidRenderArea { width, height }); - } - if shape.render_target_array_length > 1 { - return Err(not_implemented(Feature::TileShading)); - } - Ok(()) -} - -/// A tile or fragment function's tile threadgroup memory as a bind shape places it -/// (`tile_memory`): each tile's bytes (the pass's `threadgroupMemoryLength` rounded up to 16), -/// the pass's tile, the tiles across and down the render area, and each argument's offset by -/// index. -pub(crate) struct TileMemoryPlan { - pub(crate) tile_bytes: u64, - pub(crate) tile: [u32; 2], - pub(crate) grid: [u32; 2], - pub(crate) offsets: BTreeMap, -} - -impl TileMemoryPlan { - /// The buffer's bytes: every tile's, and 16 at least, as a buffer of no bytes cannot be bound - /// (a pass of no threadgroup memory, whose arguments are all empty, reads none of them). - pub(crate) fn bytes(&self) -> u64 { - (u64::from(self.grid[0]) * u64::from(self.grid[1]) * self.tile_bytes).max(TG_ALIGN) - } - - /// The value of tile memory specialization constant `key` (`SpecKey::TgOffset`, - /// `TileThreadgroupLength` and `TileGridWidth`; a fragment function's tile, `ImageblockWidth` - /// and `ImageblockHeight`), or `None` for another key or an argument without its fact. - pub(crate) fn spec(&self, key: SpecKey) -> Option { - match key { - SpecKey::TgOffset(index) => self.offsets.get(&index).map(|&o| u64::from(o)), - SpecKey::TileThreadgroupLength => Some(self.tile_bytes), - SpecKey::TileGridWidth => Some(u64::from(self.grid[0])), - SpecKey::ImageblockWidth => Some(u64::from(self.tile[0])), - SpecKey::ImageblockHeight => Some(u64::from(self.tile[1])), - _ => None, - } - } -} - -/// Where an argument the encoder set at byte `offset` of its tile's threadgroup memory begins in -/// the threadgroup arena: `offset` floored to a multiple of 4, which is where plain Metal begins -/// it. -/// -/// Plain Metal takes every offset and places it by this one rule, measured on an Apple M3 Max -/// under macOS 27.0.1 over eighteen offsets, each in its own process with Metal's API validation -/// off: with a tile memory of 128 bytes whose word `t` held a value only a seeding dispatch could -/// have written, an argument at byte 0, 2, 4, 8, 16, 17, 20 and 32 began at word 0, 0, 1, 2, 4, 4, -/// 5 and 8. So the floor is to 4 and not to 16, which byte 17 alone cannot tell apart (both place -/// it at byte 16) but bytes 4, 8 and 20 do. -/// -/// Nothing is clamped. An offset at or past the tile's memory needs no clamp: every access from it -/// fails the arena's containment, which reads zero and drops the store (`memory::contain`), and -/// bytes 128 and 144 of that 128-byte memory read zero throughout. Nor may it be clamped, because -/// plain Metal's own address arithmetic wraps at 2^32 rather than reading zero from the memory's -/// end on for ever: an argument at `u64::MAX`, which is byte `0xfffffffc` after the truncation the -/// encoder applies, read zero and then the memory's words 0, 1 and 2 as its reads carried past -/// 2^32. The arena's offsets are `u32` and add with wrapping, so such accesses wrap where Metal's -/// do. -/// -/// A 4-byte-aligned base is exact here because the threadgroup arena has no 8- or 16-byte unit -/// (`memory::arena::ArenaMem` declares no `Units`), so an 8- or 16-byte access takes `Path::Vec2`'s -/// or `Path::Vec4`'s fallback to its words at `off / 4` rather than a `uvec2` index at `off / 8` or -/// a `uvec4` index at `off / 16` (`memory::leaf`): no access to the arena claims an alignment the -/// base does not hold. -fn tile_argument_offset(offset: u32) -> u32 { - offset - offset % TG_FLOOR -} - -/// The tile threadgroup memory of a pipeline of `dependencies` as `shape` places it on `device`; -/// `None` for a pipeline that reads no threadgroup argument (`RuntimeFact::TileThreadgroupMemory`: -/// a tile function's, or a fragment function's). An argument the encoder did not set is -/// `BindError::MissingThreadgroupMemory`. An argument's length takes no part in the layout and -/// bounds no access, and every offset is placed where plain Metal begins the argument -/// ([`tile_argument_offset`]), as plain Metal takes every length and every offset. A shape without -/// a render area or a tile is `InvalidRenderArea` or `InvalidImageblockSize`. A buffer of every -/// tile's memory past the device's `maxStorageBufferRange`, which one descriptor binds at most, is -/// `Unsupported`. -pub(crate) fn tile_memory( - dependencies: &[RuntimeDependency], - device: &Device, - shape: &BindShape, -) -> Result, BindError> { - let mut offsets = BTreeMap::new(); - let memory = &shape.tile_threadgroup; - for d in dependencies { - let RuntimeFact::TileThreadgroupMemory { index } = d.fact else { - continue; - }; - let argument = memory - .arguments - .get(&index) - .ok_or(BindError::MissingThreadgroupMemory { index })?; - offsets.insert(index, tile_argument_offset(argument.offset)); - } - if offsets.is_empty() { - return Ok(None); - } - let [width, height] = shape.render_area; - if width == 0 || height == 0 { - return Err(BindError::InvalidRenderArea { width, height }); - } - let tile = shape.imageblock_size; - if tile.width == 0 || tile.height == 0 { - return Err(BindError::InvalidImageblockSize { - width: tile.width, - height: tile.height, - }); - } - let plan = TileMemoryPlan { - tile_bytes: u64::from(memory.length).next_multiple_of(TG_ALIGN), - tile: [tile.width, tile.height], - grid: [ - shape.render_area[0].div_ceil(tile.width), - shape.render_area[1].div_ceil(tile.height), - ], - offsets, - }; - let available = u64::from(device.profile().fields().limits.max_storage_buffer_range); - if plan.bytes() > available { - return Err(BindError::Unsupported(Unsupported::needs( - Feature::TileShading, - Capability::Limit { - limit: VkLimit::MaxStorageBufferRange, - required: plan.bytes(), - available, - }, - ))); - } - Ok(Some(plan)) -} - -/// The bytes of each cell of `p`'s explicit imageblock standing alone -/// (`RuntimeFact::TileImageblock`) that `shape`'s pass keeps (`BindShape::kept_imageblock_bytes`), -/// where they are fewer than its data: `None` for every other pipeline and pass. -fn kept_imageblock_bytes(p: &ComputePipeline, shape: &BindShape) -> Option { - let data_size = p.dependencies.iter().find_map(|d| match d.fact { - RuntimeFact::TileImageblock { data_size, .. } => Some(data_size), - _ => None, - })?; - shape.kept_imageblock_bytes.filter(|&kept| kept < data_size) -} - -/// The threadgroup Metal answers `p`'s tile function in `shape`'s pass where its threadgroup is -/// the tile (`RuntimeFact::TileThreadgroup` with `tile_sized`): the tile, `shape`'s imageblock -/// size, at least 1 in each axis (`BindError::InvalidImageblockSize`). `None` for every other -/// pipeline. -fn tile_threadgroup(p: &ComputePipeline, shape: &BindShape) -> Result, BindError> { - let tile_sized = p - .dependencies - .iter() - .any(|d| d.fact == RuntimeFact::TileThreadgroup { tile_sized: true }); - if !tile_sized { - return Ok(None); - } - let tile = shape.imageblock_size; - if tile.width == 0 || tile.height == 0 { - return Err(BindError::InvalidImageblockSize { - width: tile.width, - height: tile.height, - }); - } - Ok(Some([tile.width, tile.height, 1])) -} - -/// Whether `p` is a tile function's pipeline (`RuntimeFact::TileFunction`). -fn is_tile_function(p: &ComputePipeline) -> bool { - p.dependencies - .iter() - .any(|d| d.fact == RuntimeFact::TileFunction) -} - -/// The view format of tile attachment `color` of `p` (`WriteSource::TileAttachment`): the staging -/// format (`lower::access::tile::staging_format`) of the pixel format the tile function stages it -/// in (`RuntimeFact::TileAttachmentFormat`). -fn tile_view_format(p: &ComputePipeline, color: u32) -> Result { - let pixel_format = p - .dependencies - .iter() - .find_map(|d| match d.fact { - RuntimeFact::TileAttachmentFormat { color: c, format } if c == color => Some(format), - _ => None, - }) - .ok_or_else(|| internal(format!("tile attachment {color} without its format")))?; - let view = crate::lower::access::tile::staging_format(pixel_format); - crate::metal::format::direct_format(view).ok_or_else(|| { - internal(format!( - "tile attachment {color}: no Vulkan format for {view:?}" - )) - }) -} - -impl ComputePipeline { - /// The shape-level binding plan of this pipeline for `shape`: a pure function of the pipeline, - /// `device` (the device that compiled it), and the shape, so the consumer memoizes it on - /// `(PipelineKey, BindShape)`. Per-dispatch bytes come from - /// [`BindingPlan::instantiate_dispatch`]. - pub fn plan(&self, device: &Device, shape: &BindShape) -> Result { - plan(self, device, shape) - } -} - -/// The specialization data of the constants in `layout` that `value` gives a value, in `SpecId` -/// order: each value's low `size` bytes, little-endian, without the bits no stage reads -/// (`SpecConstant::unread_bits`), so values that differ only there give one key, one `VkPipeline`, -/// and one specialization the driver sees. Its two lists are made at once, at the first constant -/// given a value, at the size it and every later constant take; a key of no value makes none. -pub(crate) fn spec_key( - layout: &[SpecConstant], - value: impl Fn(SpecKey) -> Option, -) -> SpecializationKey { - let mut key = SpecializationKey::new(); - spec_key_into(layout, value, &mut key); - key -} - -/// [`spec_key`]'s key, written over `key` in the storage its two lists hold: a key written over -/// one of as many constants allocates nothing. -pub(crate) fn spec_key_into( - layout: &[SpecConstant], - value: impl Fn(SpecKey) -> Option, - key: &mut SpecializationKey, -) { - key.entries.clear(); - key.data.clear(); - for (at, c) in layout.iter().enumerate() { - let Some(v) = value(c.key) else { continue }; - // Room for the rest of the layout at once, rather than growing a push at a time: a - // dispatch's regions each make one. - if key.entries.is_empty() { - let rest = &layout[at..]; - key.entries.reserve_exact(rest.len()); - (key.data).reserve_exact(rest.iter().map(|c| c.size.min(8) as usize).sum()); - } - let v = v & !c.unread_bits; - let size = c.size.min(8); - key.entries.push(vk::SpecializationMapEntry { - constant_id: c.id, - offset: key.data.len() as u32, - size, - }); - key.data - .extend_from_slice(&v.to_le_bytes()[..size as usize]); - } -} - -fn plan(p: &ComputePipeline, device: &Device, shape: &BindShape) -> Result { - check_slots(shape)?; - if p.stage.stage != vk::ShaderStage::COMPUTE { - return Err(internal("a compute pipeline whose stage is not compute")); - } - let f = device.profile().fields(); - let limits = &f.limits; - let empty = StageShape::default(); - let ks = shape.stages.get(&Stage::Kernel).unwrap_or(&empty); - - let bindings = bindings(&p.layout); - - // Buffer slots. - let replayed = (p.dependencies.iter()).any(|d| d.fact == RuntimeFact::ReplayBindings); - let mut buffers = Vec::new(); - for (&slot, iface) in &p.interface.slots { - let b = match iface { - SlotInterface::Buffer(b) if slot.stage == Stage::Kernel => b, - SlotInterface::Texture(_) | SlotInterface::Sampler(_) - if slot.stage == Stage::Kernel => - { - continue - } - SlotInterface::Buffer(_) | SlotInterface::Texture(_) | SlotInterface::Sampler(_) => { - return Err(internal(format!("a compute pipeline uses {slot:?}"))) - } - }; - buffers.push(plan_buffer( - (slot, b, ks.buffers.get(&slot.index)), - replayed, - limits, - &bindings, - )?); - } - let planned = |slot: SlotRef| buffers.iter().find(|b| b.slot == slot); - - // Push placement. - let placement = p.interface.push.iter().find(|pl| pl.stage == Stage::Kernel); - let fields = placement.map(|pl| pl.fields.clone()).unwrap_or_default(); - let mut push = PushTemplate::default(); - let mut reads_root_table = false; - for field in &fields { - let in_push = matches!(field.loc, PushLoc::Push { .. }); - match field.field { - PushField::RootTableAddress => reads_root_table = true, - PushField::ExecutionStatusAddress - | PushField::DispatchRegion - | PushField::ReplayRegionAddress - | PushField::StageInRegion => {} - 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. - PushField::SlotGuestBase(slot) - if planned(slot).is_some_and(|b| b.bound != BoundKind::Bytes) => {} - PushField::SlotGuestBase(slot) if planned(slot).is_some() => { - return Err(BindError::MissingGuestAddress { slot }) - } - // The bound buffer's bytes before its bind offset and its length, which instantiation - // reads from the state. - PushField::SlotBounds(slot) if planned(slot).is_some() => {} - // The identity domains' zero range and private arena are the runtime's own memory, and - // their bicubic slot's format treatment the runtime's own field. - PushField::ZeroAddress - | PushField::BicubicTexels(_) - | PushField::PrivateArenaAddress => { - return Err(not_implemented(Feature::IdentityDomains)) - } - // Under the identity domains a texture's or sampler's word is its resource ID and a - // constexpr sampler's the runtime's own sampler: fields the runtime pushes itself, - // which no binding state holds. - PushField::SlotGuestBase(SlotRef { - class: SlotClass::Texture | SlotClass::Sampler, - .. - }) - | PushField::ConstexprSampler(_) => { - return Err(not_implemented(Feature::IdentityDomains)) - } - PushField::SlotBindOffset(SlotRef { - class: SlotClass::Texture, - .. - }) => return Err(not_implemented(Feature::TexelBuffer)), - // A storage texture's level count and integer channel widths, which the resource plan - // records. - PushField::TextureLevels(_) | PushField::TextureIntegerChannels(_) => {} - // A structure's instance count, which instantiation reads from the state. - PushField::InstanceCount(_) => {} - // 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(_) => {} - // A stage-in buffer's bound stride, which instantiation reads from the state. - PushField::StageInStride(_) => {} - other => return Err(internal(format!("a compute push field {other:?}"))), - } - let per_region = matches!( - field.field, - PushField::RootTableAddress - | PushField::ExecutionStatusAddress - | PushField::DispatchRegion - | PushField::ReplayRegionAddress - ); - if per_region && !in_push { - // The placement order puts these first, so a compute window (128 bytes) always holds - // them. - return Err(not_implemented(Feature::Lowering(LowerFamily::Dispatch))); - } - push.fields.push(PushFieldPlacement { - stage: Stage::Kernel, - field: field.field, - location: match field.loc { - PushLoc::Push { offset } => FieldLocation::PushWindow { offset }, - PushLoc::ArgumentTable { offset } => FieldLocation::ArgumentTable { offset }, - }, - size: field.size, - }); - } - let root_first = reads_root_table.then(|| { - let top = buffers - .iter() - .filter(|b| b.form == BufferForm::Psb) - .map(|b| b.slot.index + 1) - .max() - .unwrap_or(0); - 2 + top - }); - - // A tile function's tile threadgroup memory. - let tile_memory = tile_memory(&p.dependencies, device, shape)?; - // Descriptors. - let mut resources = ResourcePlanner { - profile: device.profile(), - shape: &shape.stages, - slots: &p.interface.slots, - dependencies: &p.dependencies, - stage_flags: |_| vk::PipelineStageFlags2::COMPUTE_SHADER, - variant: VariantKey::new(), - diagnostics: Vec::new(), - uses: Vec::new(), - template: Default::default(), - alpha_red_texels: Default::default(), - }; - let mut heap = HeapPlanner::new(device.profile(), &p.layout, &p.dependencies, shape, |_| { - vec![Stage::Kernel] - })?; - let mut descriptors = Vec::new(); - let separate = separate_samplers(&p.layout); - let mut table = None; - for set in &p.layout.sets { - for b in &set.bindings { - if let BindingSource::Heap(_) = b.source { - descriptors.extend(planner(&mut heap)?.array(set.set, b)?); - continue; - } - // A constexpr sampler array: the layout's immutable samplers, no write. - if let BindingSource::SamplerArray { .. } = b.source { - continue; - } - // A separate sampler: a constexpr one is the layout's immutable sampler, no write; a - // runtime one the sampler bound at its slot, made for the use. - if let BindingSource::SeparateSampler { stage, sampler } = b.source { - let source = - resources.separate_sampler(stage, sampler, b.immutable_sampler.as_ref())?; - if let Some(source) = source { - descriptors.push(DescriptorWrite { - set: set.set, - binding: b.binding, - array_element: 0, - ty: b.ty, - source, - }); - } - continue; - } - if let BindingSource::HeapSampler { stage, sampler } = b.source { - // A constexpr heap sampler is the layout's immutable sampler: no write. A runtime - // one is the sampler bound at its slot, made for the use. - let runtime = - planner(&mut heap)?.sampler(stage, sampler, b.immutable_sampler.as_ref())?; - if let Some(slot) = runtime { - descriptors.push(DescriptorWrite { - set: set.set, - binding: b.binding, - array_element: 0, - ty: b.ty, - source: resources.heap_sampler(slot, sampler)?, - }); - } - continue; - } - // A storage slot's level views, or a texture buffer's parts. - if let (0, BindingSource::Texture(slot)) = (set.set, b.source) { - if b.count > 1 { - let views = resources.slot_views(set.set, b.binding, b.ty, slot, b.count)?; - descriptors.extend(views.into_iter().zip(0..).map(|(source, i)| { - DescriptorWrite { - set: set.set, - binding: b.binding, - array_element: i, - ty: b.ty, - source, - } - })); - continue; - } - } - if set.set != 0 || b.count != 1 { - return Err(internal(format!( - "a {:?} binding of {} descriptors in set {}", - b.source, b.count, set.set - ))); - } - let source = match b.source { - BindingSource::Buffer(slot) => { - let pb = planned(slot).ok_or_else(|| { - internal(format!("binding of {slot:?} without an interface slot")) - })?; - match pb.bound { - BoundKind::Buffer { .. } => WriteSource::Buffer { slot }, - BoundKind::Bytes => WriteSource::InlineBytes { slot }, - BoundKind::Unbound => WriteSource::Neutral(NeutralResource::ZeroBuffer { - min_bytes: zero_buffer_bytes(device.profile()), - }), - } - } - BindingSource::Synthetic { - stage: Stage::Kernel, - binding, - } => match binding { - SyntheticBinding::ArgumentTable => { - let size = placement.map_or(0, |pl| pl.argument_table_size); - if size == 0 { - return Err(internal("an ArgumentTable binding without fields")); - } - table = Some((set.set, b.binding, size)); - WriteSource::ArgumentTable { - stage: Stage::Kernel, - bytes_len: size, - } - } - SyntheticBinding::ConstantBlob if p.stage.constant_blob.is_some() => { - WriteSource::ConstantBlob { - stage: Stage::Kernel, - } - } - SyntheticBinding::HandleTable => { - planner(&mut heap)?.table(Stage::Kernel, set.set, b.binding)? - } - SyntheticBinding::SamplerTable => { - planner(&mut heap)?.sampler_table(Stage::Kernel, set.set, b.binding)? - } - SyntheticBinding::FunctionTableDirectory => { - planner(&mut heap)?.directory(Stage::Kernel, set.set, b.binding)? - } - // The tables' words on a device without the array's features. - SyntheticBinding::FunctionTableSnapshot => { - planner(&mut heap)?.snapshot(Stage::Kernel, set.set, b.binding)? - } - // The pass's tile threadgroup memory. - SyntheticBinding::TileMemory => match &tile_memory { - Some(memory) => WriteSource::TileMemory { - bytes: memory.bytes(), - }, - None => return Err(internal("a tile memory binding without its facts")), - }, - // The pass's imageblock storage, a tile function's explicit imageblock. - SyntheticBinding::Imageblock => WriteSource::Imageblock, - // The command buffer's status, on a device that does not address buffers. - SyntheticBinding::ExecutionStatus => WriteSource::ExecutionStatus, - other => return Err(internal(format!("a compute binding {other:?}"))), - }, - BindingSource::Texture(slot) => { - resources.texture(set.set, b.binding, b.ty, slot)? - } - BindingSource::Sampler(slot) => resources.sampler(slot)?, - BindingSource::CombinedTextureSampler { texture, sampler } => { - resources.combined(texture, sampler, b.immutable_sampler.as_ref())? - } - BindingSource::SeparateTexture { texture, sampler } => { - let immutable = separate.get(&(texture.stage, sampler)).ok_or_else(|| { - internal(format!( - "separate texture {texture:?} without its sampler {sampler:?}" - )) - })?; - resources.separate_texture(texture, sampler, *immutable)? - } - // The consumer builds the structures. - BindingSource::AccelerationStructure { slot, level } => { - WriteSource::AccelerationStructure { slot, level } - } - // A sparse texture's tile map. - BindingSource::TileMap(slot) => resources.tile_map(slot), - // A two-plane YCbCr texture's planes image, through the device's conversion. - BindingSource::YCbCrPlanes(slot) => resources.planes_image_write(slot)?, - // A tile function's attachment. - BindingSource::TileAttachment(color_index) => WriteSource::TileAttachment { - color_index, - format: tile_view_format(p, color_index)?, - }, - other => return Err(internal(format!("a compute binding {other:?}"))), - }; - descriptors.push(DescriptorWrite { - set: set.set, - binding: b.binding, - array_element: 0, - ty: b.ty, - source, - }); - } - } - - // Specialization the shape decides. - let layout = &p.stage.specialization.constants; - let imageblock = imageblock_bytes(p, shape)?; - check_tile_pass(p, shape)?; - check_sparse_textures(&p.dependencies, device.profile(), shape)?; - let mut fixed = Vec::new(); - // A tile function's tile threadgroup memory starts its arena. - let mut regions_total: Option = match (&tile_memory, imageblock) { - (Some(memory), imageblock) => Some(memory.tile_bytes + imageblock.unwrap_or(0)), - (None, imageblock) => imageblock, - }; - for c in layout { - if let Some(v) = bound_value(c.key, shape, &resources)? { - fixed.push((c.key, v)); - continue; - } - let v = match c.key { - // Each region decides these (`dispatch::region_specialization_into`). - SpecKey::LocalSize(_) - | SpecKey::FlatLocalSize - | SpecKey::MultiRegion - | SpecKey::StageInReach - | SpecKey::DeepThreadgroup => continue, - SpecKey::TgLength(n) => { - let len = u64::from(ks.threadgroup_lengths.get(&n).copied().unwrap_or(0)); - let len = len.next_multiple_of(TG_ALIGN); - regions_total = Some(regions_total.unwrap_or(0) + len); - len - } - SpecKey::ImageblockWidth if imageblock.is_some() => { - u64::from(shape.imageblock_size.width) - } - SpecKey::ImageblockHeight if imageblock.is_some() => { - u64::from(shape.imageblock_size.height) - } - // A tile dispatch's render area. - SpecKey::RenderAreaWidth => u64::from(shape.render_area[0]), - SpecKey::RenderAreaHeight => u64::from(shape.render_area[1]), - // A tile function's tile threadgroup memory. - SpecKey::TgOffset(_) | SpecKey::TileThreadgroupLength | SpecKey::TileGridWidth => { - tile_memory - .as_ref() - .and_then(|m| m.spec(c.key)) - .ok_or_else(|| internal(format!("{:?} without its facts", c.key)))? - } - // What the kernel's handles can name: its raw arms drop where it names no texture - // held by its raw texels. - SpecKey::HeapRawTextures(stage) => { - u64::from(heap_raw(shape, stage, &|_| vec![Stage::Kernel])) - } - other => return Err(internal(format!("a compute specialization {other:?}"))), - }; - fixed.push((c.key, v)); - } - record_noted([&p.stage], shape, &mut resources, &|_| vec![Stage::Kernel])?; - // Emulated simdgroups: the arena's own static part comes from the fact (the reported static - // length is Metal's layout's, without the arena's minimum). - let emulation = p.dependencies.iter().find_map(|d| match d.fact { - RuntimeFact::SimdgroupEmulation { - bytes_per_simdgroup, - arena, - } => Some((bytes_per_simdgroup, arena)), - _ => None, - }); - // A predicated walk's vote word sits beside the arena, counted in the total beside the static - // part, which the reported static length is. - let vote = if p - .dependencies - .iter() - .any(|d| d.fact == RuntimeFact::PredicationVote) - { - u64::from(VOTE_BYTES) - } else { - 0 - }; - let static_bytes = match emulation { - Some((_, arena)) => arena.map_or(0, u64::from), - None => u64::from(p.metal_info.static_threadgroup_memory_length), - }; - // The imageblock, the arena's last region, starts 16-byte aligned. - let static_bytes = if imageblock.is_some() { - static_bytes.next_multiple_of(TG_ALIGN) - } else { - static_bytes - }; - if let Some(regions) = regions_total { - let required = static_bytes + regions + vote; - let available = u64::from(limits.max_compute_shared_memory_size); - if required > available { - return Err(BindError::Unsupported(Unsupported::needs( - Feature::ThreadgroupMemorySize, - Capability::Limit { - limit: VkLimit::MaxComputeSharedMemorySize, - required, - available, - }, - ))); - } - } - let specialization = spec_key(layout, |k| { - fixed.iter().find(|(key, _)| *key == k).map(|(_, v)| *v) - }); - - // Local-size rules. - let multiples = p - .dependencies - .iter() - .filter_map(|d| match d.fact { - RuntimeFact::LocalSizeConstraint { multiple } => Some(multiple), - _ => None, - }) - .collect(); - // The unit axes a pipeline compiled as its unit-axes variant states, or the masks whose variant - // relieves its predicated walk (`RuntimeFact::UnitAxes`). - let unit_axes = (p.dependencies.iter()) - .find_map(|d| match d.fact { - RuntimeFact::UnitAxes { axes, relief } => Some((axes, relief)), - _ => None, - }) - .unwrap_or((0, 0)); - let local = LocalRules { - flat: layout.iter().any(|c| c.key == SpecKey::FlatLocalSize), - deep: layout.iter().any(|c| c.key == SpecKey::DeepThreadgroup), - multiples, - max_size: limits.max_compute_work_group_size, - max_invocations: limits.max_compute_work_group_invocations, - max_subgroups: f.subgroup.max_compute_workgroup_subgroups, - max_count: limits.max_compute_work_group_count, - required_subgroup_size: p.stage.required_subgroup_size, - stage_flags: p.stage.stage_flags, - scratch: emulation.map(|(per_simdgroup, arena)| ScratchRule { - per_simdgroup, - fixed: arena_bytes(arena, regions_total.unwrap_or(0)), - available: limits.max_compute_shared_memory_size, - }), - rows: p - .dependencies - .iter() - .any(|d| d.fact == RuntimeFact::RowLockstep), - unit_relief: unit_axes.1, - tile: is_tile_function(p), - tile_threadgroup: tile_threadgroup(p, shape)?, - grid_tiles: p - .dependencies - .iter() - .any(|d| d.fact == RuntimeFact::GridTiles), - }; - - // Uses: every bound buffer slot, with its proven access and window, and the used resources - // the function can reach. - let compute_stage = vk::PipelineStageFlags2::COMPUTE_SHADER; - let mut uses: Vec = buffers - .iter() - .filter(|b| matches!(b.bound, BoundKind::Buffer { .. })) - .map(|b| buffer_use(b, compute_stage)) - .collect(); - uses.extend(used_uses( - &shape.used, - p.interface.needs_pointer_translation, - p.interface.needs_handle_translation, - |_| compute_stage, - compute_stage, - )); - uses.append(&mut resources.uses); - let mut diagnostics = resources.diagnostics; - let mut template = resources.template; - template.biased_slot_words = crate::lower::access::identity(device.profile()); - if let Some(h) = heap { - h.finish( - &mut descriptors, - &mut uses, - |_| compute_stage, - &mut template, - &mut diagnostics, - ); - } - let mut variant = resources.variant; - variant.psb_slots = psb_variant(&p.dependencies, &buffers, device.profile()); - variant.cross_class = cross_variant(&p.dependencies, &p.interface.slots, shape); - variant.srgb_textures = srgb_variant( - device.profile(), - &p.dependencies, - shape, - &variant.cross_class, - ); - variant.ycbcr_in_place = ycbcr_in_place_variant(&p.dependencies, shape); - variant.ycbcr_planes_sampled = - ycbcr_planes_sampled_variant(&p.dependencies, shape, &variant.ycbcr_in_place); - variant.texel_buffer_parts = texel_buffer_parts_variant(&p.dependencies, shape); - variant.address_maps = address_map_variant(&p.dependencies, shape); - variant.cubic_samplers = cubic_variant(&p.dependencies, shape)?; - variant.anisotropic_samplers = anisotropic_variant(&p.dependencies, shape); - variant.open_cl_lines = open_cl_line_variant(&p.dependencies, &p.interface.slots, shape); - // A pipeline compiled for emulated simdgroups states its variant; a dispatch asks for it where - // the flattened tiers cannot run its threadgroups (`dispatch_variant`). - variant.emulated_simdgroups = p - .dependencies - .iter() - .any(|d| d.fact == RuntimeFact::EmulatedSimdgroups); - // A pipeline compiled as its one-row variant states it; a dispatch asks for it where every - // region is one row of a kernel with `RowLockstep` (`dispatch_variant`). - variant.one_row = p.dependencies.iter().any(|d| d.fact == RuntimeFact::OneRow); - // A pipeline compiled as its unit-axes variant states its axes; a consumer asks for it where a - // dispatch's threadgroups have one thread along axes that relieve the walk - // (`VariantKey::unit_axes`). - variant.unit_axes = unit_axes.0; - // A pipeline compiled for a flat grid states its variant, and one of the call's threadgroups - // states that too. - variant.flat_grid = p - .dependencies - .iter() - .any(|d| d.fact == RuntimeFact::FlatGrid); - variant.call_threadgroups = p - .dependencies - .iter() - .any(|d| d.fact == RuntimeFact::CallThreadgroups); - // And one compiled to fold its group counts, or to run a ragged grid's partial threadgroups. - variant.folded_groups = p - .dependencies - .iter() - .any(|d| d.fact == RuntimeFact::FoldedGroups); - variant.partial_threadgroups = p - .dependencies - .iter() - .any(|d| d.fact == RuntimeFact::PartialThreadgroups); - // A tile function's explicit imageblock standing alone in a pass that keeps fewer of its - // cells' bytes: the variant that reads the others as zero and drops their writes. - variant.kept_imageblock_bytes = kept_imageblock_bytes(p, shape); - // Tables that may pass `maxStorageBufferRange`: the variant that reads them at their - // addresses (and a pipeline compiled so states it). - variant.addressed_function_tables = crate::bind::heap::addressed_function_tables( - device.profile(), - &p.dependencies, - &shape.function_tables, - ); - - Ok(BindingPlan { - variant, - specialization, - descriptors, - vertex_buffers: Vec::new(), - uses, - push, - diagnostics, - graphics: None, - compute: Some(ComputeTemplate { - buffers, - spec: layout.clone(), - fixed, - local, - fields, - push_range: placement.and_then(|pl| pl.push_range), - table, - root_first, - resources: template, - stage_in_region: p - .dependencies - .iter() - .any(|d| d.fact == RuntimeFact::StageInRegion), - stage_in_grid: match layout.iter().any(|c| c.key == SpecKey::StageInReach) { - true => (p.interface.stage_in.iter().copied()) - .filter(|f| crate::bind::dispatch::grid_axis(f).is_some()) - .collect(), - false => Vec::new(), - }, - }), - views: Default::default(), - }) -} - -#[cfg(test)] -mod tests; diff --git a/crates/metal2vulkan/src/bind/plan/compute/tests.rs b/crates/metal2vulkan/src/bind/plan/compute/tests.rs deleted file mode 100644 index f8c1b3cf6..000000000 --- a/crates/metal2vulkan/src/bind/plan/compute/tests.rs +++ /dev/null @@ -1,60 +0,0 @@ -//! Specialization encoding of compute plans. Plans of compiled pipelines are -//! tested end to end in `src/tests/engine_binder.rs`. - -use super::*; -use crate::pipeline::sym::Axis; - -#[test] -fn specialization_data_packs_each_value_at_its_size_in_id_order() { - let c = |id, key, size| SpecConstant { - id, - key, - size, - default: 0, - unread_bits: 0, - }; - let layout = [ - c(0, SpecKey::LocalSize(Axis::X), 4), - c(1, SpecKey::MultiRegion, 4), - c(2, SpecKey::TgLength(3), 4), - ]; - let key = spec_key(&layout, |k| match k { - SpecKey::LocalSize(_) => Some(0x0102_0304), - SpecKey::TgLength(3) => Some(48), - _ => None, - }); - assert_eq!(key.data, vec![4, 3, 2, 1, 48, 0, 0, 0]); - let ids: Vec<(u32, u32, u32)> = key - .entries - .iter() - .map(|e| (e.constant_id, e.offset, e.size)) - .collect(); - assert_eq!(ids, vec![(0, 0, 4), (2, 4, 4)]); -} - -/// A key's lists are made at once at the size every constant of the layout takes, not grown a -/// push at a time: where each constant has a value, each list's capacity is its length. A key of -/// no value makes no list at all. -#[test] -fn specialization_lists_are_made_whole_at_once() { - let c = |id, key, size| SpecConstant { - id, - key, - size, - default: 0, - unread_bits: 0, - }; - let layout = [ - c(0, SpecKey::LocalSize(Axis::X), 4), - c(1, SpecKey::LocalSize(Axis::Y), 4), - c(2, SpecKey::LocalSize(Axis::Z), 4), - c(3, SpecKey::FlatLocalSize, 4), - c(4, SpecKey::MultiRegion, 1), - ]; - let key = spec_key(&layout, |_| Some(1)); - assert_eq!((key.entries.len(), key.data.len()), (5, 17)); - assert_eq!(key.entries.capacity(), key.entries.len()); - assert_eq!(key.data.capacity(), key.data.len()); - let none = spec_key(&layout, |_| None); - assert_eq!((none.entries.capacity(), none.data.capacity()), (0, 0)); -} diff --git a/crates/metal2vulkan/src/bind/plan/resources.rs b/crates/metal2vulkan/src/bind/plan/resources.rs deleted file mode 100644 index 877a73139..000000000 --- a/crates/metal2vulkan/src/bind/plan/resources.rs +++ /dev/null @@ -1,2059 +0,0 @@ -//! Texture, sampler, combined image-sampler, texel-buffer, and input-attachment writes, shared by -//! compute and render plans. -//! -//! Every such binding of the layout gets one write: -//! -//! - **Declared type.** A binding's image type is derived from the slot's interface (the Metal -//! texture type and sampled type), the binding's descriptor type (sampled or storage, image or -//! texel buffer), and the pipeline's facts: a cube with `ImageViewShape` is the 2D-array view -//! the function declared, a combined binding's depth comparison is its symbol's, and a storage -//! binding's format is the variant's storage-image choice, `Unknown` without one. -//! - **Bound and compatible:** a texture view of the bound format through `metal::format` -//! (sampled: `vk_format` for `SampledImage`, with the emulation's component mapping; storage: -//! the `StorageImageChoice`'s view format), a texel-buffer view format, or the runtime sampler slot, whose `VkSampler` instantiation makes -//! from the bound descriptor for the binding's use. -//! - **Unbound, or bound but incompatible** with the declared type (another texture type, sample -//! count, or numeric type, a texture buffer for an image, a color texture under a depth -//! comparison): the neutral of exactly the declared type; an incompatible binding is also a -//! `PlanDiagnostic::IncompatibleBinding` (guest undefined behavior). -//! - **Bound, its storage not held:** a storage slot a function only writes over a texture whose -//! writes Metal drops (`metal::format::writes_dropped`), and any storage slot over an ASTC -//! texture, whose blocks no storage view stores into (`PlanDiagnostic::AstcStorageNeutral`): -//! the neutral of the declared type, which the writes leave as Metal leaves the texture. -//! - **Variant**: a read or written storage slot's choice joins the plan's `VariantKey` unless the -//! declaration a pipeline compiled without one has serves it (an `Identity` choice without an -//! alias, where the profile accesses the slot's uses without a format), so the common path stays -//! empty. A slot whose texels take the bound format's numeric type -//! (`RuntimeFact::StorageTextureNumericType`) always joins it: a formatless choice keeps the -//! type. -//! - **Shape checks:** a runtime sampler's shape passes `metal::sampler::check_sampler` for the -//! binding's use (a non-average reduction needs `samplerFilterMinmax` and no comparison; -//! mirror-clamp, border colors, and LOD clamps; anisotropy needs nothing, its sampler isotropic -//! on a device without `samplerAnisotropy` and where the binding samples a cube with explicit -//! gradients), so `bind::sampler_desc` refuses per bind only what depends on the bound image -//! format; `SamplerState` specializes from the bound sampler's word, masked by the fields the -//! function reads. -//! - **Bicubic texels**: a texture slot sampled through Metal's bicubic filter specializes -//! `BicubicTexels` from the bound format's family (`metal::bicubic::texels`), and refuses a -//! format of no measured family. -//! - **Separate bindings**: a separate texture's write is the image its combined binding's would -//! be, with the same checks, and a separate sampler's is a constexpr sampler's layout immutable -//! sampler (no write) or the runtime sampler for its use. A runtime sampler meets its textures in -//! the shader, so each texture's write checks the bound sampler's filtering against its view at -//! plan time, which `bind::sampler_desc` does per bind for a combined write. - -use std::collections::{BTreeMap, BTreeSet}; - -use super::{ - AccessClass, ImageSource, ImageViewDesc, PlanDiagnostic, PlannedTexel, ResourceTemplate, - ResourceUse, SamplerSource, UseTarget, WriteSource, -}; -use crate::bind::neutral::NeutralResource; -use crate::bind::state::{SamplerShape, StageShape, TextureShape}; -use crate::bind::AstcDecode; -use crate::cache::VariantKey; -use crate::device::requirements::{FormatUsage, VkLimit}; -use crate::device::DeviceProfile; -use crate::error::{BindError, Capability, Error, Feature, LowerFamily, Unsupported}; -use crate::metal::bicubic::{texels as bicubic_texels, BicubicTexels}; -use crate::metal::format::{ - accessed_without_format, aspects, copies_only, direct_format, is_depth_stencil, sampled_type, - srgb_raw_twin, storage_choice, texel_buffer_alpha_in_red, vk_format, writes_dropped, - ExtendedRange, FormatMapping, StorageUse, -}; -use crate::metal::sampler::{ - check_border_view, check_sampler, opaque_black_reads_transparent, vk_filtering, - OpaqueBlackBorder, SamplerUse, SamplerWord, -}; -use crate::metal::texel_format::{reads_unswizzled, srgb_twin_on, texel_format}; -use crate::metal::{PixelFormat, SamplerMipFilter, TextureSwizzleChannels, TextureType}; -use crate::pipeline::artifact::RuntimeDependency; -use crate::pipeline::facts::RuntimeFact; -use crate::pipeline::interface::{ - AccessSet, SamplerSlot, SlotInterface, TextureAccess, TextureSlot, -}; -use crate::pipeline::lower_inputs::{StorageImageChoice, StorageImageClass}; -use crate::pipeline::sym::{ - CombinedSampler, ImageAccess, ImageDim, ImageHandleClass, SampledType, SamplerRef, SlotClass, - SlotRef, Stage, StorageFormatClass, -}; -use crate::vk; - -use super::compute::internal; - -/// A `metal`/`device` error as a bind error: capability refusals stay typed, a bound resource's -/// invalid descriptor is the guest's, anything else is an invariant failure. -pub(crate) fn bind_error(e: Error) -> BindError { - match e { - Error::Unsupported(u) => BindError::Unsupported(u), - Error::InvalidDescriptor(d) => BindError::InvalidDescriptor(d), - Error::Internal(i) => BindError::Internal(i), - other => internal(format!("{other:?}")), - } -} - -/// The `VkSampler` of the sampler bound at a plan's `WriteSource::Sampler`, -/// `WriteSource::ArgumentSampler` or `SamplerSource::Slot`: `metal::sampler::vk_sampler` for the -/// write's use (its `compare` and `integer`) on `device`, its opaque-black border -/// made as the write says (`opaque_black`, transparent black, or opaque black with the view's -/// mapping in `border_components`), and, when the sampler reads an image of `image_format` (a -/// combined write's view format), the format's linear-filtering and min/max features the -/// descriptor needs (checked against the bound sampler, not at texture creation). The plan already refused what the sampler's shape decides -/// (`metal::sampler::check_sampler`), so for a state of the plan's shape only the format features -/// can refuse here. -pub fn sampler_desc( - device: &crate::device::Device, - desc: &crate::bind::state::SamplerDescriptor, - use_: SamplerUse, - opaque_black: OpaqueBlackBorder, - image_format: Option, -) -> Result { - let profile = device.profile(); - let mut out = crate::metal::sampler::vk_sampler(desc, use_, profile).map_err(bind_error)?; - let black = [ - vk::BorderColor::FLOAT_OPAQUE_BLACK, - vk::BorderColor::INT_OPAQUE_BLACK, - ]; - if black.contains(&out.border_color) { - match opaque_black { - OpaqueBlackBorder::Stated => {} - OpaqueBlackBorder::Transparent => { - out.border_color = if out.border_color == black[0] { - vk::BorderColor::FLOAT_TRANSPARENT_BLACK - } else { - vk::BorderColor::INT_TRANSPARENT_BLACK - }; - } - OpaqueBlackBorder::Mapped(components) => out.border_components = Some(components), - } - } - if let Some(format) = image_format { - check_filter_features(profile, &out, format)?; - } - Ok(out) -} - -/// The format features Vulkan sampler `s` needs of the image view format `format` it reads. A -/// linear filter or mip mode needs `SAMPLED_IMAGE_FILTER_LINEAR` only under weighted-average -/// reduction without depth comparison (VUID-vkCmdDispatch-magFilter-04553, -/// VUID-vkCmdDispatch-mipmapMode-04770: a comparison sampler filters the comparison results, which -/// needs nothing of the format), and `SAMPLED_IMAGE_FILTER_MINMAX` only under a min or max -/// reduction (VUID-vkCmdDispatch-magFilter-09598, VUID-vkCmdDispatch-mipmapMode-09599). A nearest -/// sampler needs neither. A runtime sampler's ([`sampler_desc`]) and a layout's immutable one's -/// ([`ResourcePlanner::combined`]) are checked alike. -fn check_filter_features( - profile: &DeviceProfile, - s: &vk::SamplerDesc, - format: vk::Format, -) -> Result<(), BindError> { - require_filter_features(profile, desc_filtering(s), s.compare.is_some(), format) -} - -/// The filtering of Vulkan sampler `s`: whether some filter or its mip mode is linear, and its -/// reduction. -pub(crate) fn desc_filtering(s: &vk::SamplerDesc) -> (bool, vk::SamplerReductionMode) { - let linear = s.mag_filter == vk::Filter::LINEAR - || s.min_filter == vk::Filter::LINEAR - || s.mipmap_mode == vk::SamplerMipmapMode::LINEAR; - (linear, s.reduction) -} - -/// [`check_filter_features`] at plan time for the runtime sampler of `shape` bound for `use_`: the -/// filtering `metal::sampler::vk_sampler` makes of it for the use (`metal::sampler::vk_filtering`), -/// against the view format `format`. A separate sampler's write carries no image, so -/// `bind::sampler_desc` cannot check its textures' views per bind. -fn check_shape_filter_features( - profile: &DeviceProfile, - shape: &SamplerShape, - use_: SamplerUse, - format: vk::Format, -) -> Result<(), BindError> { - require_filter_features(profile, vk_filtering(shape, use_), use_.compare, format) -} - -/// The format features a sampler that filters linearly or not and reduces with `reduction` -/// (`filtering`), comparing or not, needs of the view format `format` it reads. -pub(crate) fn require_filter_features( - profile: &DeviceProfile, - (linear, reduction): (bool, vk::SamplerReductionMode), - compare: bool, - format: vk::Format, -) -> Result<(), BindError> { - use vk::SamplerReductionMode as R; - let filtered = linear && reduction == R::WEIGHTED_AVERAGE && !compare; - let minmax = linear && matches!(reduction, R::MIN | R::MAX); - for (needed, usage) in [ - (filtered, FormatUsage::SampledImageFilterLinear), - (minmax, FormatUsage::SampledImageFilterMinmax), - ] { - if needed && !profile.supports_format(format, usage) { - return Err(BindError::Unsupported(Unsupported::needs( - Feature::Format, - Capability::Format { format, usage }, - ))); - } - } - Ok(()) -} - -/// The immutable sampler of each separate sampler binding of `layout`, by its stage and use: `None` -/// for a runtime one. A separate texture's write reads its sampler's. -pub(crate) fn separate_samplers( - layout: &crate::pipeline::layout::PipelineLayout, -) -> BTreeMap<(Stage, CombinedSampler), Option<&vk::SamplerDesc>> { - layout - .sets - .iter() - .flat_map(|set| &set.bindings) - .filter_map(|b| match b.source { - crate::pipeline::layout::BindingSource::SeparateSampler { stage, sampler } => { - Some(((stage, sampler), b.immutable_sampler.as_ref())) - } - _ => None, - }) - .collect() -} - -/// Whether the Vulkan sampler `s` replaces texels with an opaque-black built-in border: some -/// axis clamps to the border and the color is `FLOAT_OPAQUE_BLACK` or `INT_OPAQUE_BLACK`. -pub(crate) fn opaque_black_border(s: &vk::SamplerDesc) -> bool { - [s.address_mode_u, s.address_mode_v, s.address_mode_w] - .contains(&vk::SamplerAddressMode::CLAMP_TO_BORDER) - && matches!( - s.border_color, - vk::BorderColor::FLOAT_OPAQUE_BLACK | vk::BorderColor::INT_OPAQUE_BLACK - ) -} - -/// What one plan's resource writes need from the pipeline, the device, and the shape. -pub(crate) struct ResourcePlanner<'a> { - pub profile: &'a DeviceProfile, - pub shape: &'a BTreeMap, - pub slots: &'a BTreeMap, - pub dependencies: &'a [RuntimeDependency], - pub stage_flags: fn(Stage) -> vk::PipelineStageFlags2, - /// Outputs. - pub variant: VariantKey, - pub diagnostics: Vec, - pub uses: Vec, - pub template: ResourceTemplate, - /// The texture-buffer slots whose texel view reads an `A8Unorm` texture buffer's bytes as - /// `R8_UNORM` with no storage class to convert them (`metal::format::texel_buffer_alpha_in_red`): - /// their reads take Metal's alpha from red through the slot's swizzle - /// ([`ResourcePlanner::texture_swizzle`]). - pub alpha_red_texels: BTreeSet, -} - -/// The type a texture binding declares (the neutral's input). -fn declared( - t: &TextureSlot, - ty: vk::DescriptorType, - cube_as_array: bool, - depth_compare: bool, - format: StorageFormatClass, -) -> Result { - use TextureType as T; - let (dim, arrayed, multisampled) = match t.texture_type { - T::Type1D => (ImageDim::D1, false, false), - T::Type1DArray => (ImageDim::D1, true, false), - T::Type2D => (ImageDim::D2, false, false), - T::Type2DArray => (ImageDim::D2, true, false), - T::Type2DMultisample => (ImageDim::D2, false, true), - T::Type2DMultisampleArray => (ImageDim::D2, true, true), - T::Cube if cube_as_array => (ImageDim::D2, true, false), - T::CubeArray if cube_as_array => (ImageDim::D2, true, false), - T::Cube => (ImageDim::Cube, false, false), - T::CubeArray => (ImageDim::Cube, true, false), - T::Type3D => (ImageDim::D3, false, false), - T::TextureBuffer => (ImageDim::Buffer, false, false), - }; - let buffer = matches!( - ty, - vk::DescriptorType::UNIFORM_TEXEL_BUFFER | vk::DescriptorType::STORAGE_TEXEL_BUFFER - ); - if buffer != (dim == ImageDim::Buffer) { - return Err(internal(format!( - "a {:?} texture slot bound as {ty:?}", - t.texture_type - ))); - } - let storage = matches!( - ty, - vk::DescriptorType::STORAGE_IMAGE | vk::DescriptorType::STORAGE_TEXEL_BUFFER - ); - Ok(ImageHandleClass { - dim, - arrayed, - multisampled, - sampled_type: t.sampled_type, - depth_compare, - access: if storage { - ImageAccess::Storage - } else { - ImageAccess::Sampled - }, - format: if storage { - format - } else { - StorageFormatClass::NotStorage - }, - }) -} - -/// The neutral of `class`. -pub(crate) fn neutral(class: &ImageHandleClass) -> Result { - NeutralResource::for_image(class) - .ok_or_else(|| internal(format!("no neutral for the declared type {class:?}"))) -} - -/// Whether a bound texture of `shape` is what the declared `t` (with `class`) may read: the same -/// Metal texture type, the declared numeric type, and a depth format under comparison. -fn compatible(shape: &TextureShape, t: &TextureSlot, class: &ImageHandleClass) -> bool { - match *shape { - TextureShape::Texture { - texture_type, - pixel_format, - sample_count, - .. - } => { - texture_type == t.texture_type - && (sample_count > 1) == class.multisampled - && texel_type_binds(pixel_format, t.sampled_type) - && (!class.depth_compare || is_depth_stencil(pixel_format)) - } - TextureShape::Buffer { pixel_format, .. } => { - class.dim == ImageDim::Buffer && texel_type_binds(pixel_format, t.sampled_type) - } - } -} - -/// Whether a bound texture of `shape` is what the declared `t` (with `class`) may read but for -/// its numeric type: the same Metal texture type and sample count, a depth format under -/// comparison, and another numeric type. The binder writes the declared type's neutral there -/// unless the slot's variant reads the texture in its own class ([`cross_class`]), and says so -/// (`PlanDiagnostic::CrossClassNeutral`). -fn only_numeric(shape: &TextureShape, t: &TextureSlot, class: &ImageHandleClass) -> bool { - let Some(ty) = bound_sampled_type(shape.pixel_format()) else { - return false; - }; - let typed = TextureSlot { - sampled_type: ty, - ..*t - }; - !compatible(shape, t, class) && compatible(shape, &typed, class) -} - -/// The numeric class Metal reads a texture of `shape` in at a slot declared `t`, where it is not -/// `t`'s and the slot's variant reads the texture in it (`VariantKey::cross_class`): a texture of -/// `t`'s Metal texture type (any sample count it has, sparse or not), or a texture buffer at a -/// texture-buffer slot, of a color format whose class (`metal::format::sampled_type`) is `Float`, -/// `Sint` or `Uint` and not `t`'s, which is one of those three too. Neither a depth or stencil -/// format, nor one another variant reads raw (an extended-range or bfloat one; a two-plane YCbCr -/// one). Plain Metal reads such a texture in its own class and hands back the words as `t`'s type, -/// a `half` result each word's low 16 bits (measured on Apple M3 Max and M4 for 28 formats); and -/// (on an Apple M3 Max) a `short` or `ushort` result an integer word's -/// low 16 bits or a float texel's `half` bits, a storage, multisampled, sparse or texture-buffer -/// read alike, and a write stores the written lanes' bits as the format's own class -/// (`lower::texture::cross_write`). Two writes are left out: a storage slot bound to a swizzled -/// texture (the swizzle's order against the cross-class conversion is not measured), and an -/// integer slot's write to an `RGB9E5Float` texture (its rounding is not measured). The slot's -/// compile must state `RuntimeFact::CrossClassReads`. -pub(crate) fn cross_class(t: &TextureSlot, shape: &TextureShape) -> Option { - let (pixel_format, same_type) = match *shape { - TextureShape::Texture { - texture_type, - pixel_format, - sample_count, - swizzle, - .. - } => { - let ms = matches!( - texture_type, - TextureType::Type2DMultisample | TextureType::Type2DMultisampleArray - ); - let unswizzled_store = !t.access.write || swizzle.is_default(); - ( - pixel_format, - texture_type == t.texture_type && (sample_count > 1) == ms && unswizzled_store, - ) - } - TextureShape::Buffer { pixel_format, .. } => { - (pixel_format, t.texture_type == TextureType::TextureBuffer) - } - }; - let classes = [SampledType::Float, SampledType::Sint, SampledType::Uint]; - let bound = sampled_type(pixel_format)?; - let integer_write = t.access.write && t.sampled_type != SampledType::Float; - let taken = same_type - && !t.depth_compare - && classes.contains(&t.sampled_type) - && bound != t.sampled_type - && crate::metal::texel_format::crosses_classes(pixel_format) - && !(integer_write && pixel_format == PixelFormat::RGB9E5Float); - taken.then_some(bound) -} - -/// `t`, a slot whose integer texels take their signedness from the bound format -/// (`RuntimeFact::StorageTextureNumericType`), with the bound integer format's numeric type: its -/// own is that of the format its compile was given, which may be another integer format's (a -/// runtime's stand-in). The bound format's choice then keys the variant that compiles the slot with -/// its type. A slot or format of another type keeps `t`'s. -pub(super) fn bound_integer_type(t: TextureSlot, shape: Option<&TextureShape>) -> TextureSlot { - let integer = |ty: SampledType| matches!(ty, SampledType::Sint | SampledType::Uint); - let bound = match shape { - Some( - TextureShape::Texture { pixel_format, .. } | TextureShape::Buffer { pixel_format, .. }, - ) => sampled_type(*pixel_format), - None => None, - }; - match bound { - Some(ty) if integer(ty) && integer(t.sampled_type) => TextureSlot { - sampled_type: ty, - ..t - }, - _ => t, - } -} - -/// Whether Metal binds a texture of `pf` to a parameter of texel type `ty`: the format's numeric -/// type, and for `ulong` only `RG32Uint`, which Metal's API validation requires ("incompatible -/// with the data type (`MTLDataTypeULong`)" for every other format, measured on Apple M3 Max). -fn texel_type_binds(pf: PixelFormat, ty: SampledType) -> bool { - match ty { - SampledType::Uint64 => pf == PixelFormat::RG32Uint, - _ => bound_sampled_type(pf) == Some(ty), - } -} - -/// Metal's numeric type of a texture of `pf` bound at a slot: the format table's -/// (`sampled_type`), and `Float` for a color format the table holds no representation of (the -/// 4:2:2 formats, whose texels the runtime holds raw for copies, and ASTC's 4x2 and 8x4 -/// footprints) or holds for copies alone (`copies_only`: the one-plane YCbCr formats, the padded -/// 10- and 12-bit display formats, the transfer-function twins of the 10-bit formats and -/// `ARGB8Unorm_sRGB`, whose emulation the table admits for no usage). -/// Metal reads each as floats, so a slot of that type holds such a texture, and its binding is -/// the format's own refusal (it has no sampled or storage view: `NotImplemented(Format)`), not a -/// mismatch a neutral stands in for. -/// A slot has an interface only where the function uses it, so a texture bound at an index the -/// function never reads is refused nothing. A heap's classes keep the table's type -/// (`heap::fit`): a resident texture the heap cannot view is the neutral at its element. -fn bound_sampled_type(pf: PixelFormat) -> Option { - sampled_type(pf).or_else(|| { - let placeholder = matches!(pf, PixelFormat::Invalid | PixelFormat::Unspecialized); - (!placeholder && (aspects(pf).is_none() || copies_only(pf))).then_some(SampledType::Float) - }) -} - -/// The aspect a sampled view of `pf` selects: depth for a depth or combined format, stencil for a -/// stencil-only one, color otherwise. -fn view_aspect(pf: PixelFormat) -> vk::ImageAspectFlags { - let a = aspects(pf).unwrap_or(vk::ImageAspectFlags::COLOR); - if a.contains(vk::ImageAspectFlags::DEPTH) { - vk::ImageAspectFlags::DEPTH - } else if a.contains(vk::ImageAspectFlags::STENCIL) { - vk::ImageAspectFlags::STENCIL - } else { - vk::ImageAspectFlags::COLOR - } -} - -/// The component mapping of a view that reads a depth format's depth without comparison: the -/// depth in red, green and blue and alpha one, `(d, d, d, 1)`, as Metal reads a depth texel -/// through a color texture type (`texture2d`, `texture2d`), where Vulkan converts it -/// to `(d, 0, 0, 1)`. In the canonical form `TextureSwizzleChannels::compose` makes (red from -/// itself is `IDENTITY`). Metal's border texels of such a read are the same replication of the -/// border's red: `(0, 0, 0, 1)` for either black and `(1, 1, 1, 1)` for opaque white, which the -/// device reads through this mapping too (Vulkan swizzles after the border's replacement). A -/// comparison's view keeps the identity: its value is one scalar. -pub(crate) const DEPTH_AS_COLOR: vk::ComponentMapping = vk::ComponentMapping { - r: vk::ComponentSwizzle::IDENTITY, - g: vk::ComponentSwizzle::R, - b: vk::ComponentSwizzle::R, - a: vk::ComponentSwizzle::ONE, -}; - -/// The component mapping of a sampled view of `pf`'s aspect `aspect` whose format maps with -/// `components`, read with comparison or not (`compare`): [`DEPTH_AS_COLOR`] for a depth aspect -/// without comparison (the format table's depth candidates map with the identity), else -/// `components`. -fn sampled_components( - aspect: vk::ImageAspectFlags, - components: vk::ComponentMapping, - compare: bool, -) -> vk::ComponentMapping { - match aspect == vk::ImageAspectFlags::DEPTH && !compare { - true => DEPTH_AS_COLOR, - false => components, - } -} - -/// The view of a sampled image of `pf` declared as `class` on `profile`: `vk_format` for -/// `SampledImage` with the emulation's component mapping, the depth (or stencil-only) aspect, in -/// `SHADER_READ_ONLY_OPTIMAL`. A depth that no comparison reads reads as Metal's `(d, d, d, 1)` -/// ([`DEPTH_AS_COLOR`]). -pub(crate) fn sampled_view( - profile: &DeviceProfile, - pf: PixelFormat, - class: &ImageHandleClass, -) -> Result { - let usages = [FormatUsage::SampledImage].into(); - let m = vk_format(pf, &usages, profile).map_err(bind_error)?; - let aspect = view_aspect(pf); - Ok(ImageViewDesc { - view_type: view_type(class)?, - format: m.format, - aspect, - layout: vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL, - components: sampled_components(aspect, m.components, class.depth_compare), - level: None, - shader_swizzle: false, - }) -} - -/// The view type of a declared image class (the binder's cube-as-2D-array view included). -pub(crate) fn view_type(class: &ImageHandleClass) -> Result { - use vk::ImageViewType as V; - Ok(match (class.dim, class.arrayed) { - (ImageDim::D1, false) => V::TYPE_1D, - (ImageDim::D1, true) => V::TYPE_1D_ARRAY, - (ImageDim::D2, false) => V::TYPE_2D, - (ImageDim::D2, true) => V::TYPE_2D_ARRAY, - (ImageDim::D3, false) => V::TYPE_3D, - (ImageDim::Cube, false) => V::CUBE, - (ImageDim::Cube, true) => V::CUBE_ARRAY, - _ => return Err(internal(format!("no view type for {class:?}"))), - }) -} - -/// Whether a storage slot of `use_` needs its storage choice `c` of a texture or texture buffer -/// viewed as `view` as a variant: a pipeline compiled without a choice declares the slot `Unknown` -/// with class `Identity` wherever the device accesses its uses without a format, which serves a -/// choice that converts nothing and aliases nothing exactly when the view's format serves those -/// uses without one ([`accessed_without_format`]: Vulkan grants it per format and per image or -/// buffer, not by the device's features alone). Any other choice is a compile input. -fn needs_variant( - c: &StorageImageChoice, - view: vk::Format, - use_: StorageUse, - profile: &DeviceProfile, -) -> bool { - !(c.class == StorageImageClass::Identity - && c.alias.is_none() - && !c.x_channel - && accessed_without_format(view, use_, profile)) -} - -/// The declared storage format class of a choice. -fn storage_class(c: Option<&StorageImageChoice>) -> StorageFormatClass { - match c { - Some(c) if c.vk_format != vk::Format::UNDEFINED => { - // A view format without a SPIR-V image format is declared formatless. - if crate::metal::format::spirv_image_format(c.vk_format).is_some() { - StorageFormatClass::Format(c.vk_format) - } else { - StorageFormatClass::Unknown - } - } - _ => StorageFormatClass::Unknown, - } -} - -fn texture_access(a: TextureAccess) -> AccessSet { - AccessSet { - read: a.read || a.sample, - write: a.write, - } -} - -impl ResourcePlanner<'_> { - fn has_fact(&self, fact: RuntimeFact) -> bool { - self.dependencies.iter().any(|d| d.fact == fact) - } - - fn stage_shape(&self, stage: Stage) -> Option<&StageShape> { - self.shape.get(&stage) - } - - fn texture_slot(&self, slot: SlotRef) -> Result<&TextureSlot, BindError> { - match self.slots.get(&slot) { - Some(SlotInterface::Texture(t)) => Ok(t), - _ => Err(internal(format!( - "texture binding {slot:?} without its interface" - ))), - } - } - - fn texture_shape(&self, slot: SlotRef) -> Option<&TextureShape> { - self.stage_shape(slot.stage) - .and_then(|s| s.textures.get(&slot.index)) - } - - fn sampler_shape(&self, slot: SlotRef) -> Option<&SamplerShape> { - self.stage_shape(slot.stage) - .and_then(|s| s.samplers.get(&slot.index)) - .map(|s| &s.shape) - } - - /// The neutral `n` for `slot`, declared `t` (with `class`), reported as a substitution where - /// `bound`, the shape there, binds something: as `PlanDiagnostic::CrossClassNeutral` where - /// only its numeric type differs ([`only_numeric`]), else as `IncompatibleBinding`. - fn substitute( - &mut self, - slot: SlotRef, - n: NeutralResource, - bound: Option<&TextureShape>, - (t, class): (&TextureSlot, &ImageHandleClass), - ) -> NeutralResource { - if let Some(shape) = bound { - let d = match only_numeric(shape, t, class) { - true => PlanDiagnostic::CrossClassNeutral { - slot, - substituted: n, - }, - false => PlanDiagnostic::IncompatibleBinding { - slot, - substituted: n, - }, - }; - self.diagnostics.push(d); - } - n - } - - /// The class the variant reads the texture bound at sampled slot `slot`, declared `t`, in - /// ([`cross_class`]), where the slot's compile states `RuntimeFact::CrossClassReads`. - fn cross_of(&self, slot: SlotRef, t: &TextureSlot) -> Option { - if !self.has_fact(RuntimeFact::CrossClassReads { slot }) { - return None; - } - cross_class(t, self.texture_shape(slot)?) - } - - /// The write of texture slot `slot`'s tile map: the sparse texture's map, read by the slot's - /// stage, or the zero buffer where the bound texture is not sparse (the module reads its map - /// only for a sparse texture, under `SpecKey::SparseTexture`). - pub(crate) fn tile_map(&mut self, slot: SlotRef) -> WriteSource { - let sparse = self - .shape - .get(&slot.stage) - .and_then(|s| s.textures.get(&slot.index)) - .is_some_and(TextureShape::sparse); - if !sparse { - return WriteSource::Neutral(NeutralResource::ZeroBuffer { - min_bytes: crate::bind::neutral::zero_buffer_bytes(self.profile), - }); - } - self.uses.push(ResourceUse { - resource: UseTarget::TileMap(slot), - access: AccessSet::READ, - class: AccessClass::Storage, - stages: (self.stage_flags)(slot.stage), - range: None, - }); - WriteSource::TileMap { slot } - } - - /// The write of `slot`'s binding under its in-place variant: the planes' texel buffer of the - /// two-plane YCbCr texture the shape binds there (`TextureFacts::ycbcr_in_place`), a read of - /// their bytes; the neutral texel buffer where it binds none, which the plan's choice of the - /// variant does not leave (`slots::ycbcr_in_place_variant`). - fn in_place_write(&mut self, slot: SlotRef) -> (WriteSource, NeutralResource) { - let neutral = NeutralResource::TexelBuffer { - format: vk::Format::R8G8_UINT, - }; - match self.texture_shape(slot) { - Some(TextureShape::Texture { - ycbcr_in_place: true, - .. - }) => { - self.uses.push(ResourceUse { - resource: UseTarget::Slot(slot), - access: AccessSet::READ, - class: AccessClass::YCbCrPlanes, - stages: (self.stage_flags)(slot.stage), - range: None, - }); - (WriteSource::YCbCrInPlace { slot }, neutral) - } - _ => (WriteSource::Neutral(neutral), neutral), - } - } - - /// The texel buffer format of the rows (`bind::texel_rows`) of the texture the shape binds at - /// `slot`, a storage slot where `storage`, where its function reads, writes and asks the size - /// of them through it (`RuntimeFact::TexelRows`): a single-sample 2D texture whose rows the - /// runtime states (`TextureShape::Texture::texel_rows`), of a color format of the slot's - /// numeric type that is no sRGB format, its texels unswizzled and unconverted (its image the - /// direct format, which holds Metal's bytes), whose direct format the device views as the - /// slot's texel buffer: a uniform one, or a storage one read and written as the function - /// does without a declared format. The device converts such a view's texels "in the same way - /// as they are for an image" (Uniform Texel Buffer, Storage Texel Buffer), so the function - /// reads and writes the texels the image route does. `None` for any other slot. - fn rows_format(&self, slot: SlotRef, storage: bool) -> Option { - if !self.has_fact(RuntimeFact::TexelRows { slot }) { - return None; - } - let Some(&TextureShape::Texture { - texture_type: TextureType::Type2D, - pixel_format: pf, - sample_count: 1, - swizzle, - texel_rows: true, - .. - }) = self.texture_shape(slot) - else { - return None; - }; - let t = self.texture_slot(slot).ok()?; - let plain = swizzle.is_default() - && !t.access.sample - && t.sampled_type != SampledType::Uint64 - && texel_type_binds(pf, t.sampled_type) - && !is_depth_stencil(pf) - && srgb_raw_twin(pf).is_none() - && ExtendedRange::of(pf).is_none(); - let format = crate::metal::format::byte_format(pf).filter(|_| plain)?; - if format.block().is_none_or(|b| b.texels != 1) { - return None; - } - let usage = match storage { - true => FormatUsage::StorageTexelBuffer, - false => FormatUsage::UniformTexelBuffer, - }; - let mapping = vk_format(pf, &[usage].into(), self.profile).ok()?; - let direct = mapping.format == format - && mapping.emulation == crate::metal::format::FormatEmulation::Direct; - let accessed = match storage { - true => accessed_without_format( - format, - StorageUse::texel_buffer(t.access.read, t.access.write), - self.profile, - ), - false => true, - }; - (direct && accessed).then_some(format) - } - - /// The write of `slot`'s binding under its rows variant (`VariantKey::texel_rows`), declared - /// `ty`, a texel buffer: the texel buffer of the rows of the texture the shape binds there - /// ([`rows_format`](Self::rows_format)), a use of their bytes; the neutral of the declared - /// texel buffer where the shape binds no such rows, which the plan's key then leaves. - fn rows_write( - &mut self, - ty: vk::DescriptorType, - slot: SlotRef, - ) -> Result<(WriteSource, NeutralResource), BindError> { - let t = *self.texture_slot(slot)?; - let storage = ty == vk::DescriptorType::STORAGE_TEXEL_BUFFER; - let buffer = TextureSlot { - texture_type: TextureType::TextureBuffer, - ..t - }; - let n = neutral(&declared( - &buffer, - ty, - false, - false, - StorageFormatClass::Unknown, - )?)?; - let Some(format) = self.rows_format(slot, storage) else { - return Ok((WriteSource::Neutral(n), n)); - }; - self.variant.texel_rows.insert(slot); - self.uses.push(ResourceUse { - resource: UseTarget::Slot(slot), - access: texture_access(t.access), - class: AccessClass::TexelRows, - stages: (self.stage_flags)(slot.stage), - range: None, - }); - Ok((WriteSource::TexelRows { slot, format }, n)) - } - - /// The write of `slot`'s binding under its planes-image variant (`BindingSource::YCbCrPlanes`, - /// `VariantKey::ycbcr_planes_sampled`): the image of the planes of the two-plane YCbCr texture - /// the shape binds there, viewed with the device's conversion of `TextureShape::Texture:: - /// ycbcr_planes_sampler`, a read of the planes' bytes. The plan takes the variant only where - /// the shape binds such a texture there (`slots::ycbcr_planes_sampled_variant`), so any other - /// is the binder's defect. - pub(crate) fn planes_image_write(&mut self, slot: SlotRef) -> Result { - match self.texture_shape(slot) { - Some(TextureShape::Texture { - ycbcr_planes_sampler: Some(_), - .. - }) => { - self.uses.push(ResourceUse { - resource: UseTarget::Slot(slot), - access: AccessSet::READ, - class: AccessClass::YCbCrPlanes, - stages: (self.stage_flags)(slot.stage), - range: None, - }); - Ok(WriteSource::YCbCrPlanesImage { slot }) - } - _ => Err(internal(format!( - "a planes image's binding of {slot:?}, which binds no texture whose planes are \ - held as an image" - ))), - } - } - - fn texture_use(&mut self, slot: SlotRef, t: &TextureSlot, storage: bool) { - self.uses.push(ResourceUse { - resource: UseTarget::Slot(slot), - access: texture_access(t.access), - class: if storage { - AccessClass::StorageImage - } else { - AccessClass::Sampled - }, - stages: (self.stage_flags)(slot.stage), - range: None, - }); - } - - /// The write of a plain texture binding `(set, binding)` of type `ty` fed by `slot`. - pub fn texture( - &mut self, - set: u32, - binding: u32, - ty: vk::DescriptorType, - slot: SlotRef, - ) -> Result { - Ok(self.texture_write(set, binding, ty, slot)?.0) - } - - /// The writes of texture slot `slot`'s binding `(set, binding)` of type `ty`, an array of - /// `count` descriptors: a texture buffer's parts where it is a texel buffer - /// ([`texel_parts`](Self::texel_parts)), else a storage slot's level views - /// ([`level_views`](Self::level_views)). - pub fn slot_views( - &mut self, - set: u32, - binding: u32, - ty: vk::DescriptorType, - slot: SlotRef, - count: u32, - ) -> Result, BindError> { - match ty { - vk::DescriptorType::UNIFORM_TEXEL_BUFFER | vk::DescriptorType::STORAGE_TEXEL_BUFFER => { - self.texel_parts(set, binding, ty, slot, count) - } - _ => self.level_views(set, binding, ty, slot, count), - } - } - - /// The writes of texture-buffer slot `slot`'s `count` parts, binding `(set, binding)` of type - /// `ty`, under its parts variant (`RuntimeFact::TexelBufferParts`, - /// `VariantKey::texel_buffer_parts`, `bind::texel_parts`): element `k` views part `k` of the - /// bound texture buffer in the format its one view would take, the range of each its - /// template's (`PlannedTexel::parts`, `texel_ranges`); every element is the neutral of the - /// declared type where the slot binds the neutral. - fn texel_parts( - &mut self, - set: u32, - binding: u32, - ty: vk::DescriptorType, - slot: SlotRef, - count: u32, - ) -> Result, BindError> { - if !self.has_fact(RuntimeFact::TexelBufferParts { slot }) { - return Err(internal(format!( - "a {ty:?} binding of {count} descriptors at {slot:?} without texel buffer parts" - ))); - } - let (write, _) = self.texture_write(set, binding, ty, slot)?; - match write { - WriteSource::TexelBuffer { .. } => { - let planned = self - .template - .texel_buffers - .last_mut() - .filter(|pt| (pt.set, pt.binding, pt.slot) == (set, binding, slot)) - .ok_or_else(|| internal(format!("texel buffer parts at {slot:?} unplanned")))?; - planned.parts = count; - } - WriteSource::Neutral(_) => {} - other => return Err(internal(format!("texel buffer parts of {other:?}"))), - } - Ok(vec![write; count as usize]) - } - - /// The writes of storage slot `slot`'s `count` level views, binding `(set, binding)` of type - /// `ty` (`RuntimeFact::StorageTextureLevelViews`): element `i` views level `i` of the bound - /// texture alone, and every element past its last level is the neutral of the declared type, as - /// is every element where the slot binds the neutral. `count` is the most levels a texture of - /// the slot's type has on the device, so a texture with more is larger than the device's - /// largest image of its type: refused, naming that limit. - pub fn level_views( - &mut self, - set: u32, - binding: u32, - ty: vk::DescriptorType, - slot: SlotRef, - count: u32, - ) -> Result, BindError> { - if ty != vk::DescriptorType::STORAGE_IMAGE - || !self.has_fact(RuntimeFact::StorageTextureLevelViews { slot }) - { - return Err(internal(format!( - "a {ty:?} binding of {count} descriptors at {slot:?} without level views" - ))); - } - let (write, neutral) = self.texture_write(set, binding, ty, slot)?; - let (view, levels) = match write { - WriteSource::Texture { view, .. } => (view, self.bound_levels(slot)), - WriteSource::Neutral(_) => return Ok(vec![write; count as usize]), - other => return Err(internal(format!("level views of {other:?}"))), - }; - if levels > count { - // Level `levels - 1` exists only on a texture at least `2^(levels - 1)` texels wide. - let t = self.texture_slot(slot)?.texture_type; - let l = &self.profile.fields().limits; - let (limit, available) = match t { - TextureType::Type1D | TextureType::Type1DArray => { - (VkLimit::MaxImageDimension1D, l.max_image_dimension_1d) - } - TextureType::Cube | TextureType::CubeArray => { - (VkLimit::MaxImageDimensionCube, l.max_image_dimension_cube) - } - TextureType::Type3D => (VkLimit::MaxImageDimension3D, l.max_image_dimension_3d), - _ => (VkLimit::MaxImageDimension2D, l.max_image_dimension_2d), - }; - return Err(BindError::Unsupported(Unsupported::needs( - Feature::Lowering(LowerFamily::Texture), - Capability::Limit { - limit, - required: 1u64 << (levels - 1).min(63), - available: u64::from(available), - }, - ))); - } - Ok((0..count) - .map(|i| { - if i < levels { - WriteSource::Texture { - slot, - view: ImageViewDesc { - level: Some(i), - ..view - }, - } - } else { - WriteSource::Neutral(neutral) - } - }) - .collect()) - } - - /// The level count of the texture the shape binds at `slot`. - fn bound_levels(&self, slot: SlotRef) -> u32 { - match self.texture_shape(slot) { - Some(TextureShape::Texture { - mipmap_level_count, .. - }) => *mipmap_level_count, - _ => 0, - } - } - - /// The write of a plain texture binding, and the neutral of its declared type. A slot whose - /// level count the function reads records the count the binder pushes - /// (`PushField::TextureLevels`): the bound texture's, or 0 where the neutral stands in (an - /// unbound slot, or a texture of another type). Such a slot binds a texture whatever its usage, - /// as plain Metal writes one made without `ShaderWrite` at every level (the consumer binds its - /// usage shadow where its image lacks the storage usage). - fn texture_write( - &mut self, - set: u32, - binding: u32, - ty: vk::DescriptorType, - slot: SlotRef, - ) -> Result<(WriteSource, NeutralResource), BindError> { - // A texture slot that is no texture buffer is declared a texel buffer only under its - // in-place variant (`VariantKey::ycbcr_in_place`), a uniform one, or its rows variant - // (`VariantKey::texel_rows`): the rows' where the shape binds a texture whose rows are - // read in place there, else the planes'. - let texel_buffer = matches!( - ty, - vk::DescriptorType::UNIFORM_TEXEL_BUFFER | vk::DescriptorType::STORAGE_TEXEL_BUFFER - ); - if texel_buffer && self.texture_slot(slot)?.texture_type != TextureType::TextureBuffer { - let rows = matches!( - self.texture_shape(slot), - Some(TextureShape::Texture { - texel_rows: true, - .. - }) - ); - return match rows || ty == vk::DescriptorType::STORAGE_TEXEL_BUFFER { - true => self.rows_write(ty, slot), - false => Ok(self.in_place_write(slot)), - }; - } - let levels_read = self.has_fact(RuntimeFact::StorageTextureLevels { slot }); - let write = self.plain_texture(set, binding, ty, slot)?; - self.write_rounding(slot, &write.0)?; - // A slot whose texture's rows are read in place takes its rows variant where its image is - // declared as the rows' texel buffer is, without a storage format - // ([`rows_format`](Self::rows_format)). - let storage = ty == vk::DescriptorType::STORAGE_IMAGE; - if matches!(write.0, WriteSource::Texture { .. }) - && !self.variant.storage_images.contains_key(&slot) - && self.rows_format(slot, storage).is_some() - { - self.variant.texel_rows.insert(slot); - } - if levels_read { - let levels = match write.0 { - WriteSource::Texture { .. } => self.bound_levels(slot), - _ => 0, - }; - self.template.texture_levels.push((slot, levels)); - } - if self.has_fact(RuntimeFact::StorageTextureIntegerChannels { slot }) { - let word = match (&write.0, self.texture_shape(slot)) { - ( - WriteSource::Texture { .. } | WriteSource::TexelBuffer { .. }, - Some( - TextureShape::Texture { pixel_format, .. } - | TextureShape::Buffer { pixel_format, .. }, - ), - ) => crate::metal::format::integer_channels_word(*pixel_format), - _ => 0, - }; - self.template.texture_integer_channels.push((slot, word)); - } - Ok(write) - } - - /// The refusal of `slot` bound (`write`, not a neutral) to a texture whose mode-2 write the - /// function states it has not built (`RuntimeFact::StorageTextureWriteRounding`): an - /// `RG11B10Float` or `RGB9E5Float` texture or texture buffer, and a half-float one where the - /// function writes `float` texels there (`metal::texel_format::mode_two_rounds`), - /// `NotImplemented(PrivateRenderState(TextureWriteRounding))`. Any other binding draws as - /// Metal's. - fn write_rounding(&self, slot: SlotRef, write: &WriteSource) -> Result<(), BindError> { - let fact = |halves| RuntimeFact::StorageTextureWriteRounding { slot, halves }; - let halves = self.has_fact(fact(true)); - if !(halves || self.has_fact(fact(false))) || matches!(write, WriteSource::Neutral(_)) { - return Ok(()); - } - let pf = match self.texture_shape(slot) { - Some( - TextureShape::Texture { pixel_format, .. } - | TextureShape::Buffer { pixel_format, .. }, - ) => *pixel_format, - _ => return Ok(()), - }; - match crate::metal::texel_format::mode_two_rounds(pf, halves) { - true => Err(BindError::Unsupported(Unsupported::not_implemented( - Feature::PrivateRenderState(crate::error::PrivateRenderField::TextureWriteRounding), - ))), - false => Ok(()), - } - } - - /// The write of slot `slot`'s texture binding `(set, binding)` of type `ty`, through the view - /// [`ResourcePlanner::texel_view`] gives a sampled one, and the neutral of its declared type. - fn plain_texture( - &mut self, - set: u32, - binding: u32, - ty: vk::DescriptorType, - slot: SlotRef, - ) -> Result<(WriteSource, NeutralResource), BindError> { - let shape = self.texture_shape(slot).copied(); - let numeric = self.has_fact(RuntimeFact::StorageTextureNumericType { slot }); - let t = *self.texture_slot(slot)?; - let t = if numeric { - bound_integer_type(t, shape.as_ref()) - } else { - t - }; - // A texture of another numeric class the slot's variant reads in its own class - // (`VariantKey::cross_class`, which `slots::cross_variant` states): its image is declared - // of that class, so the binding is the bound texture's view. - let crossed = self.cross_of(slot, &t).is_some(); - let t = match self.cross_of(slot, &t) { - Some(ty) => TextureSlot { - sampled_type: ty, - ..t - }, - None => t, - }; - let cube_as_array = self.has_fact(RuntimeFact::ImageViewShape { slot }); - let storage = matches!( - ty, - vk::DescriptorType::STORAGE_IMAGE | vk::DescriptorType::STORAGE_TEXEL_BUFFER - ); - let base = declared(&t, ty, cube_as_array, false, StorageFormatClass::Unknown)?; - let compat = shape.filter(|s| compatible(s, &t, &base)); - // A texture whose writes Metal drops (a 4:2:2 texture, and a YCbCr one; - // `metal::format::writes_dropped`) at a storage slot its function only writes: plain Metal - // completes the writes and stores nothing (a filled texture keeps its bytes; its validation - // stops the binding), so the slot takes its neutral, which the writes leave as Metal leaves - // the texture. A slot that reads it keeps the format's refusal (`metal::format`). - let only_written = storage && t.access.write && !t.access.read && !t.access.sample; - // An ASTC texture at a storage slot: no storage view stores into its blocks (no Vulkan - // format of a block is a storage image's). Plain Metal completes a function's writes, - // storing bytes no format defines into the blocks, and reads the blocks' decode through - // a slot that also reads them (our probe `astc_passes_writes_footprints`): the slot takes - // its neutral, so the writes leave the texture's blocks as they were, and the plan says - // so (`PlanDiagnostic::AstcStorageNeutral`). - let astc_storage = storage - && matches!(compat, Some(TextureShape::Texture { pixel_format, .. }) - if AstcDecode::of(pixel_format).is_some()); - let compat = compat.filter(|s| { - !astc_storage - && !(only_written - && matches!(s, TextureShape::Texture { .. }) - && writes_dropped(s.pixel_format())) - }); - // A texture of one of Apple's extended-range formats joins the variant, under which the - // function reads and writes its raw texels through a view of their unsigned integer - // format: a texture's, not yet a texture buffer's or a sparse texture's. - let extended = match compat { - Some(s) => match ExtendedRange::of(s.pixel_format()) { - Some(_) if matches!(s, TextureShape::Buffer { .. }) || s.sparse() => { - return Err(BindError::Unsupported(Unsupported::not_implemented( - Feature::Format, - ))); - } - form => form, - }, - None => None, - }; - let base = match extended { - Some(_) => ImageHandleClass { - sampled_type: SampledType::Uint, - ..base - }, - None => base, - }; - // The storage choice of a compatible bound format for the slot's accesses, when its texels - // are read or written; it joins the variant unless the default declaration serves it and - // the function does not depend on the format's numeric type. - let use_ = if t.texture_type == TextureType::TextureBuffer { - StorageUse::texel_buffer(t.access.read, t.access.write) - } else { - StorageUse::texture(t.access.read, t.access.write) - }; - let accessed = storage && (t.access.read || t.access.write); - let choice = match compat { - Some( - TextureShape::Texture { pixel_format, .. } - | TextureShape::Buffer { pixel_format, .. }, - ) if accessed => { - let c = storage_choice(pixel_format, use_, self.profile).map_err(bind_error)?; - let view = direct_format(pixel_format) - .ok_or_else(|| internal("a storage texture without a format"))?; - Some((c, view)) - } - _ => None, - }; - // A texture of another numeric class that the slot's variant writes: its choice declares - // the bound format, whose channels the write saturates or rounds to as Metal stores them - // (`lower::texture::cross_write`). - let choice = match choice { - Some((mut c, view)) if crossed && t.access.write => { - if c.vk_format == vk::Format::UNDEFINED { - c.vk_format = view; - c.numeric = None; - } - Some((c, view)) - } - other => other, - }; - // An `RGB9E5Float` texture through `R32_UINT` (`StorageImageClass::SharedExponentBits`): - // the slot is declared of the alias's numeric type, as its neutral is. - let base = match choice { - Some((c, _)) if c.class == StorageImageClass::SharedExponentBits => ImageHandleClass { - sampled_type: SampledType::Uint, - ..base - }, - _ => base, - }; - let mut variant = choice - .filter(|(c, view)| { - (crossed && t.access.write) - || numeric - || needs_variant(c, *view, use_, self.profile) - }) - .map(|(c, _)| c); - let choice = choice.map(|(c, _)| c); - if compat.is_none() && accessed { - // The neutral of the default declaration is `R32` of the slot's numeric type (`RG32` - // for `ulong`). Where it lacks the without-format usage its uses need (a texel buffer's - // buffer features carry no implied bit), the slot is declared with that format, as for - // a bound texture of it, and the neutral of the declared format stands in. - let neutral = crate::bind::neutral::storage_neutral(base.sampled_type); - if !accessed_without_format(neutral, use_, self.profile) { - variant = Some(StorageImageChoice::new( - neutral, - StorageImageClass::Identity, - )); - } - } - let class = ImageHandleClass { - format: if storage { - storage_class(variant.as_ref()) - } else { - StorageFormatClass::NotStorage - }, - ..base - }; - let n = neutral(&class)?; - if let Some(c) = variant { - self.variant.storage_images.insert(slot, c); - } - if let Some(form) = extended { - self.variant.extended_range.insert(slot, form); - } - let Some(shape) = compat else { - let n = match astc_storage { - true => { - let d = PlanDiagnostic::AstcStorageNeutral { - slot, - substituted: n, - }; - self.diagnostics.push(d); - n - } - false => self.substitute(slot, n, shape.as_ref(), (&t, &base)), - }; - return Ok((WriteSource::Neutral(n), n)); - }; - self.texture_use(slot, &t, storage); - match shape { - TextureShape::Buffer { - pixel_format, - swizzle, - .. - } => { - // Metal applies a texture buffer's swizzle to a function's reads, and a texel - // buffer view has none: the function applies it where its stage states so - // (`SpecKey::TextureSwizzle`). Every read of a texture-buffer slot does but a - // `ulong` one, whose swizzled texel Metal is not measured to give; a slot only - // queried or written reads no texel to swizzle. - if !swizzle.is_default() - && t.access.read - && !self.has_fact(RuntimeFact::TextureSwizzle { slot }) - { - return Err(BindError::Unsupported(Unsupported::not_implemented( - Feature::TextureSwizzle, - ))); - } - let usage = if storage { - FormatUsage::StorageTexelBuffer - } else { - FormatUsage::UniformTexelBuffer - }; - let view = match choice { - // The storage texel view reads the choice's view format (an alias of the - // bound format's bytes, or an `A8Unorm` texture buffer's bytes as `R8_UNORM`, - // Metal's alpha in red), which must itself support the usage. - Some(c) => Some( - match (c.alias, c.class) { - (Some(_), _) | (None, StorageImageClass::AlphaInRed) => { - Some(c.vk_format) - } - (None, _) => direct_format(pixel_format), - } - .ok_or_else(|| internal("a storage choice without a format"))?, - ), - // An `A8Unorm` texture buffer's bytes as `R8_UNORM` where the device views - // no `A8_UNORM` texels for the usage: the slot's reads take Metal's alpha - // from red through its swizzle, which every texture-buffer read applies but a - // `ulong` one, whose texel no `A8Unorm` texture buffer binds. - None => match texel_buffer_alpha_in_red(pixel_format, usage, self.profile) { - Some(held) => { - if t.access.read && !self.has_fact(RuntimeFact::TextureSwizzle { slot }) - { - return Err(BindError::Unsupported(Unsupported::not_implemented( - Feature::Format, - ))); - } - self.alpha_red_texels.insert(slot); - Some(held) - } - None => None, - }, - }; - let format = match view { - Some(view) => { - if !self.profile.supports_format(view, usage) { - return Err(BindError::Unsupported(Unsupported::needs( - Feature::TexelBuffer, - Capability::Format { - format: view, - usage, - }, - ))); - } - view - } - None => { - let usages = [usage].into(); - let m = - vk_format(pixel_format, &usages, self.profile).map_err(bind_error)?; - m.format - } - }; - let l = &self.profile.fields().limits; - let block = format - .block() - .ok_or_else(|| internal(format!("a texel view of {format:?}")))?; - self.template.texel_buffers.push(PlannedTexel { - set, - binding, - slot, - alignment: l.min_texel_buffer_offset_alignment.max(1), - max_elements: u64::from(l.max_texel_buffer_elements), - block_size: u64::from(block.size), - texels_per_block: u64::from(block.texels), - parts: 1, - part_texels: crate::bind::part_texels(l), - }); - let write = WriteSource::TexelBuffer { - slot, - format, - window: crate::pipeline::interface::Window::Whole, - }; - Ok((write, n)) - } - TextureShape::Texture { - pixel_format, - swizzle, - .. - } => { - // A storage view takes no swizzle (`VUID-VkWriteDescriptorSet-descriptorType-00336`), - // and plain Metal reads a swizzled texture's texels swizzled through a storage - // binding and writes them with the swizzle undone: the function does both under - // the variant, which takes the swizzle as the slot's `SpecKey::TextureSwizzle`, - // and the view takes none. An extended-range texture's - // sampled view holds its raw codes, which a swizzle in the view's component mapping - // would move before the function decodes them (a `One` reading the code 1, a border - // texel unswizzled), where plain Metal swizzles the decoded texel, border texels - // included: the function applies the swizzle there too, under the - // same variant, to the texels it reads, samples and gathers, and the view takes - // none. - let reads_extended = - !storage && extended.is_some() && (t.access.read || t.access.sample); - // A packed normalized format's texel converts by each channel's own code scale - // (`TexelFormat::PACKED`), which a swizzle in the view's component mapping would - // move onto another channel's lane before the function converts it, so its - // class would drop the field and a read, gather or one-texel sample keep the - // device's widening of a 4-, 5- or 6-bit code (NVIDIA's and ANV's replicate its - // bits, where Metal answers `c / (2^b - 1)`): the function converts the - // unswizzled texel by the format's whole class and swizzles it, under the same - // variant, and the view takes none. - let reads_packed = !storage - && extended.is_none() - && (t.access.read || t.access.sample) - && swizzled_packed(pixel_format, swizzle); - let decodes_srgb = !storage - && (t.access.read || t.access.sample) - && self.swizzles_decoded_srgb(slot, pixel_format, swizzle); - let shader_swizzle = (accessed || reads_extended || reads_packed || decodes_srgb) - && !swizzle.is_default(); - if shader_swizzle { - self.variant.swizzled_storage.insert(slot); - } - // A storage slot its function only queries reads and writes no texel, and what a - // query answers (the view's size, levels and layers, an OpenCL image's format - // words, which the third hidden buffer holds) no swizzle reaches: plain Metal's and - // OpenCL mode's queries of a swizzled view answer so (our probe - // `opencl_swizzled_images`, on an M3 Max). Its view takes none, under no variant. - let queried = storage && !t.access.read && !t.access.write && !swizzle.is_default(); - let view = if storage { - let format = match choice { - Some(c) if c.alias.is_some() => c.vk_format, - // The `R8_UNORM` image an `A8Unorm` texture holds its alpha in. - Some(c) if c.class == StorageImageClass::AlphaInRed => c.vk_format, - _ => direct_format(pixel_format) - .ok_or_else(|| internal("a storage texture without a format"))?, - }; - ImageViewDesc { - view_type: view_type(&class)?, - format, - aspect: vk::ImageAspectFlags::COLOR, - layout: vk::ImageLayout::GENERAL, - components: vk::ComponentMapping::IDENTITY, - level: None, - shader_swizzle: shader_swizzle || queried, - } - } else { - match self.texel_view(pixel_format, &class)? { - Some((view, _)) => ImageViewDesc { - shader_swizzle, - ..view - }, - None => return Ok((WriteSource::Neutral(n), n)), - } - }; - Ok((WriteSource::Texture { slot, view }, n)) - } - } - } - - /// The view of a sampled image of `pf` declared as `class`. - fn sampled_view( - &self, - pf: PixelFormat, - class: &ImageHandleClass, - ) -> Result { - sampled_view(self.profile, pf, class) - } - - /// The view a binding of a texture slot reads a texture of `pf` through (declared `class`): - /// its sampled view, an sRGB format's decoding its codes. Where the device cannot sample an - /// 8-bit sRGB format, whose sampled texture it holds as the format's UNORM twin - /// (`metal::format::srgb_raw_twin`), the twin's sampled view, which reads the codes, under the - /// slot's `VariantKey::srgb_textures`, whose function decodes them. With the view, the format - /// whose sampled view it is (the twin's, where the twin serves). - fn texel_view( - &self, - pf: PixelFormat, - class: &ImageHandleClass, - ) -> Result, BindError> { - let missing = match self.sampled_view(pf, class) { - Ok(own) => return Ok(Some((own, pf))), - Err(missing) => missing, - }; - match srgb_raw_twin(pf) { - Some(linear) => self - .sampled_view(linear, class) - .map(|view| Some((view, linear))) - .map_err(|_| missing), - None => Err(missing), - } - } - - /// Whether slot `slot`'s function decodes the codes of a texture of `pf` bound there with - /// `swizzle` by the device's transfer (`RuntimeFact::SrgbTexture`, an 8-bit sRGB format the - /// device holds as its UNORM twin, `srgb_twin_on`) where the swizzle moves a code between a - /// color lane and alpha: a view's component mapping would move it before the decode (a color - /// code onto alpha, read as alpha's `c / 255`; alpha's code onto a color lane, decoded), where plain Metal swizzles the decoded texel. The function then decodes the - /// unswizzled texel and swizzles it, every access of the slot alike, under - /// `VariantKey::swizzled_storage`, and the slot's views take no swizzle. A swizzle among the - /// color lanes, or to a constant (0 and 1 decode to themselves), reads the same either way and - /// keeps the view's. A format the device samples is decoded by the device's sRGB view, which - /// decodes before its component mapping swizzles, swizzle and all. - fn swizzles_decoded_srgb( - &self, - slot: SlotRef, - pf: PixelFormat, - swizzle: TextureSwizzleChannels, - ) -> bool { - use crate::metal::TextureSwizzle as S; - let color = |s: S| matches!(s, S::Red | S::Green | S::Blue); - let crosses = - color(swizzle.alpha) || [swizzle.red, swizzle.green, swizzle.blue].contains(&S::Alpha); - crosses - && self.has_fact(RuntimeFact::SrgbTexture { slot }) - && srgb_twin_on(pf, self.profile) - } - - /// The runtime sampler `slot` for a use, with the shape's value checks - /// (`metal::sampler::check_sampler`: reduction; address modes, border colors, and LOD - /// clamps), or the neutral sampler when the slot is unbound. The write keeps the use's - /// comparison, texel type and explicit cube gradients, which make the `VkSampler`, - /// and how its opaque-black border is made (`ResourcePlanner::opaque_black`); the shape alone - /// decides the cube-gradient check, so a descriptor of the plan's shape never fails it per - /// bind. - fn runtime_sampler( - &mut self, - slot: SlotRef, - use_: SamplerUse, - opaque_black: OpaqueBlackBorder, - ) -> Result { - let compare = use_.compare; - let Some(s) = self.sampler_shape(slot).copied() else { - return Ok(SamplerSource::Neutral(NeutralResource::Sampler { compare })); - }; - check_sampler(&s, use_, self.profile).map_err(bind_error)?; - Ok(SamplerSource::Slot { - slot, - compare, - integer: use_.integer_texture, - opaque_black, - }) - } - - /// The mapping of `pf`'s sampled view that a sampler without comparison reads - /// (`metal::format::vk_format`, a depth's [`DEPTH_AS_COLOR`]): the view an opaque-black - /// border is read through. A comparison's sampler meets depth textures alone, whose - /// opaque-black texel is their transparent-black one. - fn sampled_mapping(&self, pf: PixelFormat) -> Result { - let usages = [FormatUsage::SampledImage].into(); - let m = vk_format(pf, &usages, self.profile).map_err(bind_error)?; - Ok(FormatMapping { - components: sampled_components(view_aspect(pf), m.components, false), - ..m - }) - } - - /// The border check of an opaque-black border read through the sampled view of `pf` made with - /// `swizzle` by a sampler made for every view alike (`metal::sampler::check_border_view`). - fn check_border( - &self, - pf: PixelFormat, - swizzle: TextureSwizzleChannels, - ) -> Result<(), BindError> { - let m = self.sampled_mapping(pf)?; - check_border_view(true, pf, &m, swizzle, self.profile).map_err(bind_error) - } - - /// How the runtime sampler `slot`, meeting the `textures` (each its format and swizzle), makes - /// its border where the shape's is opaque black (`metal::sampler::opaque_black_border`): - /// transparent black where Metal reads that texel through every one of them, which every device - /// reads exactly; else opaque black as stated where every view reads Metal's texel so, or with - /// one view mapping every view has (`borderColorSwizzle` without - /// `borderColorSwizzleFromImage`). Textures whose views need different mappings, or a view the - /// device cannot read Metal's texel through, refuse (`Unsupported{SamplerBorderColor}`): the - /// first that does. - fn opaque_black( - &self, - slot: SlotRef, - textures: &[(PixelFormat, TextureSwizzleChannels)], - ) -> Result { - if !self - .sampler_shape(slot) - .is_some_and(|s| s.opaque_black_border) - { - return Ok(OpaqueBlackBorder::Stated); - } - if textures - .iter() - .all(|&(pf, swizzle)| opaque_black_reads_transparent(pf, swizzle)) - { - return Ok(OpaqueBlackBorder::Transparent); - } - // One sampler for every texture: as stated, or with the one mapping each view needs. - let mut reads = Vec::with_capacity(textures.len()); - for &(pf, swizzle) in textures { - let m = self.sampled_mapping(pf)?; - reads.push( - crate::metal::sampler::opaque_black_border(pf, &m, swizzle, self.profile) - .map_err(bind_error)?, - ); - } - match reads.split_first() { - Some((first, rest)) if rest.iter().all(|r| r == first) => Ok(*first), - Some(_) => { - // The views need different mappings: only the view's own swizzle of the border - // (`borderColorSwizzleFromImage`) serves them all. - for &(pf, swizzle) in textures { - self.check_border(pf, swizzle)?; - } - Ok(OpaqueBlackBorder::Stated) - } - None => Ok(OpaqueBlackBorder::Stated), - } - } - - /// The write of a plain sampler binding fed by `slot` (its interface's comparison, float - /// border colors). A separate sampler meets its textures in the shader, and the interface - /// does not state which: a bound sampler with an opaque-black border is made for every - /// texture the shape binds at a slot of its stage that the function samples - /// (`ResourcePlanner::sampled_textures`, `ResourcePlanner::opaque_black`; a pair that never - /// meets can refuse, never read a border that is not Metal's). - pub fn sampler(&mut self, slot: SlotRef) -> Result { - let compare = match self.slots.get(&slot) { - Some(SlotInterface::Sampler(SamplerSlot { compare, .. })) => *compare, - _ => { - return Err(internal(format!( - "sampler binding {slot:?} without its interface" - ))) - } - }; - let sampled = self.sampled_textures(slot.stage); - let opaque_black = self.opaque_black(slot, &sampled)?; - self.sampler_write(slot, SamplerUse::new(compare, false), opaque_black) - } - - /// The format and swizzle of each texture the shape binds at a slot of `stage` that the - /// function samples: what a sampler of the stage may meet where the interface does not say. - fn sampled_textures(&self, stage: Stage) -> Vec<(PixelFormat, TextureSwizzleChannels)> { - self.slots - .iter() - .filter(|(s, i)| { - s.stage == stage && matches!(i, SlotInterface::Texture(t) if t.access.sample) - }) - .filter_map(|(s, _)| match self.texture_shape(*s) { - Some(&TextureShape::Texture { - pixel_format, - swizzle, - .. - }) => Some((pixel_format, swizzle)), - _ => None, - }) - .collect() - } - - /// The write of the runtime sampler `slot` for `use_` (`ResourcePlanner::runtime_sampler`), - /// or the neutral sampler where none is bound. - fn sampler_write( - &mut self, - slot: SlotRef, - use_: SamplerUse, - opaque_black: OpaqueBlackBorder, - ) -> Result { - Ok(match self.runtime_sampler(slot, use_, opaque_black)? { - SamplerSource::Slot { - slot, - compare, - integer, - opaque_black, - } => WriteSource::Sampler { - slot, - compare, - integer, - opaque_black, - }, - SamplerSource::Neutral(n) => WriteSource::Neutral(n), - SamplerSource::Immutable => { - return Err(internal("a runtime sampler binding is immutable")) - } - }) - } - - /// The write of a heap sampler binding fed by the runtime sampler `slot`: the sampler bound - /// there made for the use `c` (its comparison, the texture's numeric type, and whether it takes - /// explicit cube gradients in the isotropic form, which makes it isotropic), or the neutral - /// sampler where none is bound. Its opaque-black border and its filtering meet the - /// heap's members, which the heap planner checks (`HeapPlanner::array`). - pub fn heap_sampler( - &mut self, - slot: SlotRef, - c: CombinedSampler, - ) -> Result { - match self.slots.get(&slot) { - Some(SlotInterface::Sampler(_)) => {} - _ => { - return Err(internal(format!( - "heap sampler binding {slot:?} without its interface" - ))) - } - } - self.sampler_write(slot, c.sampler_use(), OpaqueBlackBorder::Stated) - } - - /// The write of a combined image-sampler binding: the texture's own view type (a cube is a cube - /// view) with the symbol's comparison, and the runtime sampler for the symbol's use or the - /// layout's immutable sampler (`immutable`). A bound texture read with an - /// opaque-black border (the runtime sampler's shape, or the immutable sampler's clamp-to-border - /// modes and color) must read it exactly through its view - /// (`metal::sampler::check_border_view`). The immutable sampler's filters must be ones the - /// bound view's format supports ([`check_filter_features`]), as a runtime sampler's are when it - /// is instantiated. A use that reads texel coordinates (`CombinedSampler::unnormalized`) views - /// the texture's first level alone. - pub fn combined( - &mut self, - texture: SlotRef, - sampler: CombinedSampler, - immutable: Option<&vk::SamplerDesc>, - ) -> Result { - let (image, sampler) = self.pair(texture, sampler, immutable)?; - Ok(WriteSource::CombinedImageSampler { image, sampler }) - } - - /// The write of a separate texture binding: the image [`ResourcePlanner::combined`] writes for - /// the same pair, with the same checks, where `immutable` is the stage's separate sampler's (a - /// constexpr one's). A runtime sampler's write meets no image, so here its bound shape's - /// filtering is checked against the view's format (and a neutral's) at plan time - /// (`check_shape_filter_features`), as `bind::sampler_desc` checks a combined write's per - /// bind: a sampler shared by textures of several formats passes for each, and the first pair - /// that does not is the plan's refusal. - pub fn separate_texture( - &mut self, - texture: SlotRef, - sampler: CombinedSampler, - immutable: Option<&vk::SamplerDesc>, - ) -> Result { - let (image, source) = self.pair(texture, sampler, immutable)?; - if let SamplerSource::Slot { slot, .. } = source { - if let Some(shape) = self.sampler_shape(slot).copied() { - let format = match &image { - ImageSource::Texture { view, .. } => Some(view.format), - ImageSource::Neutral(n) => n.format(), - }; - if let Some(format) = format { - check_shape_filter_features( - self.profile, - &shape, - sampler.sampler_use(), - format, - )?; - } - } - } - Ok(match image { - ImageSource::Texture { slot, view } => WriteSource::Texture { slot, view }, - ImageSource::Neutral(n) => WriteSource::Neutral(n), - }) - } - - /// The write of separate sampler binding `sampler` of `stage`, whose layout binding carries - /// `immutable`: none for a constexpr sampler, which is that immutable sampler, and for a - /// runtime one the sampler bound at its slot made for the use, or the neutral sampler, its - /// opaque-black border made for every texture the stage samples, as a plain sampler's - /// ([`ResourcePlanner::sampler`]). Its textures' writes check each pair - /// ([`ResourcePlanner::separate_texture`]). - pub fn separate_sampler( - &mut self, - stage: Stage, - sampler: CombinedSampler, - immutable: Option<&vk::SamplerDesc>, - ) -> Result, BindError> { - match (sampler.sampler, immutable) { - (SamplerRef::Constexpr(_), Some(_)) => Ok(None), - (SamplerRef::Slot(index), None) => { - let slot = SlotRef { - stage, - class: SlotClass::Sampler, - index, - }; - match self.slots.get(&slot) { - Some(SlotInterface::Sampler(_)) => {} - _ => { - return Err(internal(format!( - "separate sampler binding {slot:?} without its interface" - ))) - } - } - let sampled = self.sampled_textures(stage); - let opaque_black = self.opaque_black(slot, &sampled)?; - self.sampler_write(slot, sampler.sampler_use(), opaque_black) - .map(Some) - } - (SamplerRef::Constexpr(_), None) => Err(internal( - "a constexpr separate sampler without its immutable sampler", - )), - (SamplerRef::Slot(_), Some(_)) => Err(internal( - "a runtime separate sampler with an immutable sampler", - )), - } - } - - /// The image of the pair (`texture`, `sampler`) of a combined or separate binding, with the - /// pair's checks, and the sampler source of a combined write ([`ResourcePlanner::combined`]). - fn pair( - &mut self, - texture: SlotRef, - sampler: CombinedSampler, - immutable: Option<&vk::SamplerDesc>, - ) -> Result<(ImageSource, SamplerSource), BindError> { - let t = *self.texture_slot(texture)?; - // A texture of another numeric class the slot's variant reads in its own class - // (`VariantKey::cross_class`): the variant's layout declares its image of that class and - // the sampler's use for it. A layout of another use (the pipeline compiled without the - // variant, whose plan only names it) takes the declared class's neutral image and the - // neutral sampler, and no `VkSampler` of the bound state. - let cross = self.cross_of(texture, &t); - let unlike = cross.is_some_and(|ty| (ty != SampledType::Float) != sampler.integer); - let t = match cross { - Some(ty) if !unlike => TextureSlot { - sampled_type: ty, - ..t - }, - _ => t, - }; - let class = declared( - &t, - vk::DescriptorType::SAMPLED_IMAGE, - false, - sampler.compare, - StorageFormatClass::NotStorage, - )?; - let n = neutral(&class)?; - if unlike { - let source = match sampler.sampler { - SamplerRef::Slot(_) => SamplerSource::Neutral(NeutralResource::Sampler { - compare: sampler.compare, - }), - SamplerRef::Constexpr(_) => SamplerSource::Immutable, - }; - return Ok((ImageSource::Neutral(n), source)); - } - let shape = self.texture_shape(texture).copied(); - // With the image, the bound texture the sampler reads: the format whose view it reads (an - // sRGB format's twin where the twin's view serves) and its swizzle. An extended-range - // texture's variant binds no sampler. - let mut extended = false; - let (image, read) = match shape.filter(|s| compatible(s, &t, &class)) { - // An extended-range texture is sampled by fetches of its raw texels under the slot's - // variant, which this plan asks for: the variant's function reads the slot's own image - // and only the word of a runtime sampler, which must state a filter the fetches - // emulate. - Some(TextureShape::Texture { - pixel_format, - swizzle, - .. - }) if ExtendedRange::of(pixel_format).is_some() => { - if let Some(form) = ExtendedRange::of(pixel_format) { - self.variant.extended_range.insert(texture, form); - } - // A swizzled one's function swizzles the decoded texels (`plain_texture`, which - // the variant's slot takes). - if !swizzle.is_default() { - self.variant.swizzled_storage.insert(texture); - } - if let (SamplerRef::Slot(index), Some(form)) = - (sampler.sampler, ExtendedRange::of(pixel_format)) - { - let slot = SlotRef { - stage: texture.stage, - class: SlotClass::Sampler, - index, - }; - let volume = t.texture_type == TextureType::Type3D; - self.extended_sampler(slot, form, volume)?; - } - extended = true; - (ImageSource::Neutral(n), Vec::new()) - } - Some(TextureShape::Texture { - pixel_format, - swizzle, - .. - }) => match self.texel_view(pixel_format, &class)? { - Some((view, viewed)) => { - self.texture_use(texture, &t, false); - // A swizzled packed normalized texture's sampled view takes no swizzle where - // the function converts its texels by the class and swizzles them, under the - // variant (`texture_write`'s `reads_packed`): its sampler reads the - // unswizzled texture's border texel, which the function swizzles. - let shader_swizzle = !swizzle.is_default() - && (swizzled_packed(pixel_format, swizzle) - || self.swizzles_decoded_srgb(texture, pixel_format, swizzle)); - if shader_swizzle { - self.variant.swizzled_storage.insert(texture); - } - // A pixel sampler's texel coordinates read through the device's unnormalized - // sampler, which reads a view of one level (and one layer: the slot's texture - // is no array). - let level = match sampler.unnormalized { - true => Some(0), - false => view.level, - }; - let image = ImageSource::Texture { - slot: texture, - view: ImageViewDesc { - shader_swizzle, - level, - ..view - }, - }; - let seen = match shader_swizzle { - true => TextureSwizzleChannels::DEFAULT, - false => swizzle, - }; - (image, vec![(viewed, seen)]) - } - None => (ImageSource::Neutral(n), Vec::new()), - }, - _ => ( - ImageSource::Neutral(self.substitute(texture, n, shape.as_ref(), (&t, &class))), - Vec::new(), - ), - }; - let sampler = match sampler.sampler { - // The variant's fetches read the word alone (`extended_sampler`), so this plan, which - // only names the variant, makes no `VkSampler` of the state: a mode the device's - // sampler lacks (`MirrorClampToEdge`) is the fetches' to address. - SamplerRef::Slot(_) if extended => SamplerSource::Neutral(NeutralResource::Sampler { - compare: sampler.compare, - }), - SamplerRef::Slot(index) => { - let slot = SlotRef { - stage: texture.stage, - class: SlotClass::Sampler, - index, - }; - let opaque_black = self.opaque_black(slot, &read)?; - self.runtime_sampler(slot, sampler.sampler_use(), opaque_black)? - } - // The layout's sampler is made once for every texture: its border must read Metal's - // texel through this one's view as it is. - SamplerRef::Constexpr(_) => { - if immutable.is_some_and(opaque_black_border) { - for &(pf, swizzle) in &read { - self.check_border(pf, swizzle)?; - } - } - SamplerSource::Immutable - } - }; - if let (ImageSource::Texture { view, .. }, SamplerSource::Immutable, Some(s)) = - (&image, &sampler, immutable) - { - check_filter_features(self.profile, s, view.format)?; - } - Ok((image, sampler)) - } - - /// Check the runtime sampler bound at `slot`, which samples an extended-range texture of - /// `form` (a 3D one where `volume`) by fetches: its word must state one filter for - /// minification and magnification (nearest or linear), no anisotropy, and no mip filter, a - /// nearest one, or a linear one where the form's levels' blend is built - /// (`ExtendedRange::blends_levels`; not a 3D texture's) and the clamp's maximum is past every - /// texture's last level (its word's `SamplerWord::LEVEL_MAX` 0, a nearest mip - /// filter's level at it 15: the function clamps a linear one's level by the clamp's minimum - /// alone, `lower::sampler::extended`): else `NotImplemented(Format)`. Every address mode is the - /// fetches' (a `MirrorClampToEdge` axis's taps mirrored once and clamped; a padded form's under - /// every mode, measured). An unbound slot's word is 0, a nearest sampler's. A word that states - /// a `Cubic` filter is the plan's cubic-sampler variant's (`VariantKey::cubic_samplers`), whose - /// function samples through Metal's bicubic filter of its state: the plan refuses a word whose - /// state that filter is not measured under before it names the variant - /// (`slots::cubic_variant`), and the variant's function refuses what else the filter's checks - /// refuse for its sample (`lower::sampler::extended`). - fn extended_sampler( - &self, - slot: SlotRef, - form: ExtendedRange, - volume: bool, - ) -> Result<(), BindError> { - let word = self - .stage_shape(slot.stage) - .and_then(|s| s.samplers.get(&slot.index)) - .map_or(0, |s| s.word.0); - let filter = word & (SamplerWord::MIN_LINEAR | SamplerWord::MAG_LINEAR); - let one_filter = filter == 0 || filter == SamplerWord::LINEAR; - let mip = (word & SamplerWord::MIP_FILTER) >> SamplerWord::MIP_FILTER_SHIFT; - let levels = match mip { - 0 => true, - m if m == SamplerMipFilter::Nearest.as_raw() => true, - m if m == SamplerMipFilter::Linear.as_raw() => { - form.blends_levels() && !volume && word & SamplerWord::LEVEL_MAX == 0 - } - _ => false, - }; - let isotropic = word & SamplerWord::ANISOTROPIC == 0; - if word & SamplerWord::CUBIC != 0 || (one_filter && levels && isotropic) { - return Ok(()); - } - Err(BindError::Unsupported(Unsupported::not_implemented( - Feature::Format, - ))) - } - - /// The `SamplerState { slot, fields }` specialization: the bound sampler's word masked by - /// `fields`, the bits the function reads; 0 where no sampler is bound. - pub fn sampler_state(&self, slot: SlotRef, fields: u32) -> u64 { - let word = self - .stage_shape(slot.stage) - .and_then(|s| s.samplers.get(&slot.index)) - .map_or(0, |s| s.word.0); - u64::from(word & fields) - } - - /// The `SamplerMinLevel(slot)` specialization: the level, in sixty-fourths, that Metal's - /// `calculate_clamped_lod` answers outside a fragment function through the sampler bound to - /// `slot` before the texture's last level bounds it; 0 for a slot bound to no sampler. - pub fn sampler_min_level(&self, slot: SlotRef) -> u64 { - self.stage_shape(slot.stage) - .and_then(|s| s.samplers.get(&slot.index)) - .map_or(0, |s| u64::from(s.min_level)) - } - - /// The `SamplerAnisotropy(slot)` specialization: `log2` of the degree the sampler bound to - /// `slot` filters with; 0 for a slot bound to an isotropic sampler or to none. - pub fn sampler_anisotropy(&self, slot: SlotRef) -> u64 { - self.stage_shape(slot.stage) - .and_then(|s| s.samplers.get(&slot.index)) - .map_or(0, |s| u64::from(s.degree)) - } - - /// The `NearestPixelSampler(slot)` specialization: 1 where the sampler bound to `slot` is a - /// nearest pixel sampler of one isotropic level (its word masked by - /// `SamplerWord::nearest_pixel(false)` is `SamplerWord::PIXEL_COORDINATES`), else 0; 0 for a - /// slot bound to no sampler. - pub fn nearest_pixel_sampler(&self, slot: SlotRef) -> u64 { - use crate::metal::sampler::SamplerWord; - let word = self - .stage_shape(slot.stage) - .and_then(|s| s.samplers.get(&slot.index)) - .map_or(0, |s| s.word.0); - u64::from(word & SamplerWord::nearest_pixel(false) == SamplerWord::PIXEL_COORDINATES) - } - - /// The `BicubicTexels(slot)` specialization: how Metal's bicubic filter treats the texels of - /// the format bound at texture `slot` (`metal::bicubic::texels`), with the border texels of the - /// bound texture's swizzle. A slot whose combined binding reads the neutral (unbound, bound - /// incompatibly, or bound in an extended-range format, whose texels the slot's variant this - /// plan asks for samples itself, `VariantKey::extended_range`) takes `BicubicTexels::NEUTRAL`; - /// another compatible format of no measured family is refused - /// `NotImplemented(SamplerBicubicFilter)`. - pub fn bicubic_texels(&self, slot: SlotRef) -> Result { - let t = *self.texture_slot(slot)?; - let class = declared( - &t, - vk::DescriptorType::SAMPLED_IMAGE, - false, - false, - StorageFormatClass::NotStorage, - )?; - let texels = match self.texture_shape(slot) { - _ if self.variant.extended_range.contains_key(&slot) => BicubicTexels::NEUTRAL, - Some(s @ TextureShape::Texture { pixel_format, .. }) if compatible(s, &t, &class) => { - bicubic_texels(*pixel_format) - .ok_or(BindError::Unsupported(Unsupported::not_implemented( - Feature::SamplerBicubicFilter, - )))? - .with_border(*pixel_format, self.border_swizzle(slot, s)) - } - _ => BicubicTexels::NEUTRAL, - }; - Ok(u64::from(texels.0)) - } - - /// The swizzle the border texels of texture `slot`'s class are read through: the bound - /// texture's, but none for a packed normalized texture whose function swizzles its texels - /// (`VariantKey::swizzled_storage`, [`swizzled_packed`]), whose border texel the function - /// swizzles with them. - fn border_swizzle(&self, slot: SlotRef, shape: &TextureShape) -> TextureSwizzleChannels { - match self.variant.swizzled_storage.contains(&slot) - && texel_format(shape.pixel_format()).packed_exact() - { - true => TextureSwizzleChannels::default(), - false => shape.swizzle(), - } - } - - /// The `TextureSwizzle(slot)` specialization: the swizzle of the texture buffer bound at - /// `slot`, as its word, which the function applies to its reads, or of the texture bound at a - /// storage slot of the plan's `VariantKey::swizzled_storage`, which it applies to its reads and - /// undoes on its writes, or at an extended-range sampled slot of it, which it applies to the - /// decoded texels it reads, samples and gathers. A slot bound to nothing, or to another - /// texture, takes the identity's. - pub fn texture_swizzle(&self, slot: SlotRef) -> u64 { - let swizzle = match self.texture_shape(slot) { - Some(&TextureShape::Buffer { swizzle, .. }) - if self.alpha_red_texels.contains(&slot) => - { - swizzle.alpha_in_red() - } - Some(&TextureShape::Buffer { swizzle, .. }) => swizzle, - Some(&TextureShape::Texture { swizzle, .. }) - if self.variant.swizzled_storage.contains(&slot) => - { - swizzle - } - _ => TextureSwizzleChannels::DEFAULT, - }; - u64::from(swizzle.word()) - } -} - -/// Whether a sampled slot bound to a texture of `pf` made with `swizzle` swizzles in its function -/// (`VariantKey::swizzled_storage`) on `profile`'s device: a packed normalized format -/// (`TexelFormat::packed_exact`), whose texel the function converts by each channel's own code -/// scale, under a swizzle that reads some texel as no unswizzled texture does -/// (`reads_unswizzled`). -fn swizzled_packed(pf: PixelFormat, swizzle: TextureSwizzleChannels) -> bool { - texel_format(pf).packed_exact() && !reads_unswizzled(pf, swizzle) -} - -#[cfg(test)] -mod tests; diff --git a/crates/metal2vulkan/src/bind/plan/resources/tests.rs b/crates/metal2vulkan/src/bind/plan/resources/tests.rs deleted file mode 100644 index f14675844..000000000 --- a/crates/metal2vulkan/src/bind/plan/resources/tests.rs +++ /dev/null @@ -1,1376 +0,0 @@ -//! Declared image types, binding compatibility, and views. - -use super::*; -use crate::bind::state::BoundSampler; -use crate::error::Needs; -use crate::metal::format::storage_choice; -use crate::pipeline::sym::SampledType; -use std::collections::BTreeSet; - -fn slot_iface(texture_type: TextureType, sampled_type: SampledType) -> TextureSlot { - TextureSlot { - texture_type, - sampled_type, - depth_compare: false, - access: TextureAccess::new(true, false, false), - storage: false, - declared_format: false, - } -} - -/// Every Metal texture type declares the dimension, arrayed-ness, and sample count of its SPIR-V -/// image, a cube with `ImageViewShape` declares the 2D array, and every declared type has a -/// neutral whose view type is the declaration's. -#[test] -fn declared_types_follow_the_texture_type_and_the_view_shape() { - use TextureType as T; - let sampled = vk::DescriptorType::SAMPLED_IMAGE; - let cases = [ - (T::Type1D, false, vk::ImageViewType::TYPE_1D), - (T::Type1DArray, false, vk::ImageViewType::TYPE_1D_ARRAY), - (T::Type2D, false, vk::ImageViewType::TYPE_2D), - (T::Type2DArray, false, vk::ImageViewType::TYPE_2D_ARRAY), - (T::Type2DMultisample, false, vk::ImageViewType::TYPE_2D), - ( - T::Type2DMultisampleArray, - false, - vk::ImageViewType::TYPE_2D_ARRAY, - ), - (T::Cube, false, vk::ImageViewType::CUBE), - (T::CubeArray, false, vk::ImageViewType::CUBE_ARRAY), - (T::Cube, true, vk::ImageViewType::TYPE_2D_ARRAY), - (T::CubeArray, true, vk::ImageViewType::TYPE_2D_ARRAY), - (T::Type3D, false, vk::ImageViewType::TYPE_3D), - ]; - for (ty, as_array, view) in cases { - let t = slot_iface(ty, SampledType::Float); - let class = - declared(&t, sampled, as_array, false, StorageFormatClass::Unknown).expect("declared"); - assert_eq!(view_type(&class), Ok(view), "{ty:?}"); - assert_eq!(class.format, StorageFormatClass::NotStorage); - assert_eq!( - class.multisampled, - matches!(ty, T::Type2DMultisample | T::Type2DMultisampleArray) - ); - match neutral(&class).expect("neutral") { - NeutralResource::Image { view_type, .. } => assert_eq!(view_type, view, "{ty:?}"), - other => panic!("{ty:?}: {other:?}"), - } - } - // A texture buffer is exactly a texel-buffer binding. - let tb = slot_iface(T::TextureBuffer, SampledType::Uint); - let class = declared( - &tb, - vk::DescriptorType::STORAGE_TEXEL_BUFFER, - false, - false, - StorageFormatClass::Unknown, - ) - .expect("texel buffer"); - assert_eq!( - neutral(&class), - Ok(NeutralResource::TexelBuffer { - format: vk::Format::R32_UINT - }) - ); - assert!(declared(&tb, sampled, false, false, StorageFormatClass::Unknown).is_err()); - assert!(declared( - &slot_iface(T::Type2D, SampledType::Float), - vk::DescriptorType::UNIFORM_TEXEL_BUFFER, - false, - false, - StorageFormatClass::Unknown - ) - .is_err()); -} - -/// A bound texture is compatible exactly when its Metal type, sample count, and numeric type are -/// the declared ones (and it has a depth aspect under comparison). -#[test] -fn compatibility_is_type_samples_numeric_type_and_depth() { - let t = slot_iface(TextureType::Type2D, SampledType::Float); - let sampled = vk::DescriptorType::SAMPLED_IMAGE; - let class = declared(&t, sampled, false, false, StorageFormatClass::NotStorage).expect("2d"); - let tex = |texture_type, pixel_format, sample_count| TextureShape::Texture { - address_modes: crate::metal::sampler::AddressModeMap::IDENTITY, - offset_base_axes: 0, - ycbcr_in_place: false, - ycbcr_planes_sampler: None, - texel_rows: false, - texture_type, - pixel_format, - sample_count, - usage: crate::metal::TextureUsage::SHADER_READ, - mipmap_level_count: 1, - sparse: false, - swizzle: crate::metal::TextureSwizzleChannels::DEFAULT, - }; - assert!(compatible( - &tex(TextureType::Type2D, PixelFormat::RGBA8Unorm, 1), - &t, - &class - )); - assert!(compatible( - &tex(TextureType::Type2D, PixelFormat::Depth32Float, 1), - &t, - &class - )); - assert!(!compatible( - &tex(TextureType::Type2DArray, PixelFormat::RGBA8Unorm, 1), - &t, - &class - )); - assert!(!compatible( - &tex(TextureType::Type2D, PixelFormat::RGBA8Uint, 1), - &t, - &class - )); - assert!(!compatible( - &TextureShape::Buffer { - pixel_format: PixelFormat::RGBA8Unorm, - swizzle: crate::metal::TextureSwizzleChannels::DEFAULT, - parts: 1, - }, - &t, - &class - )); - let depth = declared(&t, sampled, false, true, StorageFormatClass::NotStorage).expect("d"); - assert!(!compatible( - &tex(TextureType::Type2D, PixelFormat::RGBA8Unorm, 1), - &t, - &depth - )); - assert!(compatible( - &tex(TextureType::Type2D, PixelFormat::Depth32Float, 1), - &t, - &depth - )); - let ms = slot_iface(TextureType::Type2DMultisample, SampledType::Sint); - let msc = declared(&ms, sampled, false, false, StorageFormatClass::NotStorage).expect("ms"); - assert!(compatible( - &tex(TextureType::Type2DMultisample, PixelFormat::RGBA16Sint, 4), - &ms, - &msc - )); - assert!(!compatible( - &tex(TextureType::Type2DMultisample, PixelFormat::RGBA16Sint, 1), - &ms, - &msc - )); -} - -/// A `ulong` slot binds only an `RG32Uint` texture, the one format Metal's API validation lets a -/// `ulong` texture parameter take (measured on Apple M3 Max), as a texture and as a texture buffer; -/// unbound, its neutral is an `RG32_UINT` image or texel buffer, the format its declaration names. -#[test] -fn a_ulong_slot_binds_only_rg32uint_textures() { - let tex = |pixel_format| TextureShape::Texture { - address_modes: crate::metal::sampler::AddressModeMap::IDENTITY, - offset_base_axes: 0, - ycbcr_in_place: false, - ycbcr_planes_sampler: None, - texel_rows: false, - texture_type: TextureType::Type2D, - pixel_format, - sample_count: 1, - usage: crate::metal::TextureUsage::SHADER_READ, - mipmap_level_count: 1, - sparse: false, - swizzle: crate::metal::TextureSwizzleChannels::DEFAULT, - }; - let t = slot_iface(TextureType::Type2D, SampledType::Uint64); - for (ty, format) in [ - ( - vk::DescriptorType::SAMPLED_IMAGE, - StorageFormatClass::NotStorage, - ), - ( - vk::DescriptorType::STORAGE_IMAGE, - StorageFormatClass::Unknown, - ), - ] { - let class = declared(&t, ty, false, false, format).expect("2d"); - assert!(compatible(&tex(PixelFormat::RG32Uint), &t, &class)); - for other in [ - PixelFormat::RG32Sint, - PixelFormat::RG32Float, - PixelFormat::RGBA16Uint, - PixelFormat::RGBA16Sint, - PixelFormat::R32Uint, - PixelFormat::RGBA32Uint, - ] { - assert!(!compatible(&tex(other), &t, &class), "{other:?}"); - } - match neutral(&class).expect("neutral") { - n @ NeutralResource::Image { .. } => { - assert_eq!(n.format(), Some(vk::Format::R32G32_UINT), "{ty:?}") - } - other => panic!("{other:?}"), - } - } - let tb = slot_iface(TextureType::TextureBuffer, SampledType::Uint64); - let class = declared( - &tb, - vk::DescriptorType::STORAGE_TEXEL_BUFFER, - false, - false, - StorageFormatClass::Unknown, - ) - .expect("texel buffer"); - let buffer = |pixel_format| TextureShape::Buffer { - pixel_format, - swizzle: crate::metal::TextureSwizzleChannels::DEFAULT, - parts: 1, - }; - assert!(compatible(&buffer(PixelFormat::RG32Uint), &tb, &class)); - assert!(!compatible(&buffer(PixelFormat::RGBA16Uint), &tb, &class)); - assert_eq!( - neutral(&class), - Ok(NeutralResource::TexelBuffer { - format: vk::Format::R32G32_UINT - }) - ); -} - -/// A slot whose integer texels take their signedness from the bound format -/// (`StorageTextureNumericType`) binds a texture of either integer type, and the bound format's -/// choice keys the variant: its interface's type is the format's its compile was given, a runtime's -/// stand-in (`R32Uint` here) where the dispatch binds `RGBA16Sint`. A float format still does not -/// bind it, and without the fact the interface's type is the function's own. -#[test] -fn a_numeric_slot_binds_either_integer_type() { - let texture = SlotRef { - stage: Stage::Kernel, - class: SlotClass::Texture, - index: 1, - }; - let p = crate::pipeline::testing::profile( - "moltenvk-m3", - crate::device::DevicePolicy::RESIDENT_TABLES, - ) - .expect("profile"); - let slot = TextureSlot { - access: TextureAccess::new(false, false, true), - ..slot_iface(TextureType::Type2D, SampledType::Uint) - }; - let slots = BTreeMap::from([(texture, SlotInterface::Texture(slot))]); - let numeric = [RuntimeDependency { - fact: RuntimeFact::StorageTextureNumericType { slot: texture }, - mechanism: crate::pipeline::facts::Mechanism::Variant, - }]; - let plan = |pixel_format, dependencies: &[RuntimeDependency]| { - let mut stage = StageShape::default(); - stage.textures.insert( - texture.index, - TextureShape::Texture { - address_modes: crate::metal::sampler::AddressModeMap::IDENTITY, - offset_base_axes: 0, - ycbcr_in_place: false, - ycbcr_planes_sampler: None, - texel_rows: false, - texture_type: TextureType::Type2D, - pixel_format, - sample_count: 1, - usage: crate::metal::TextureUsage::SHADER_WRITE, - mipmap_level_count: 1, - sparse: false, - swizzle: crate::metal::TextureSwizzleChannels::DEFAULT, - }, - ); - let shape = BTreeMap::from([(Stage::Kernel, stage)]); - let mut planner = ResourcePlanner { - profile: &p, - shape: &shape, - slots: &slots, - dependencies, - stage_flags: |_| vk::PipelineStageFlags2::COMPUTE_SHADER, - variant: VariantKey::new(), - diagnostics: Vec::new(), - uses: Vec::new(), - template: Default::default(), - alpha_red_texels: Default::default(), - }; - let (write, _) = planner - .plain_texture(0, 1, vk::DescriptorType::STORAGE_IMAGE, texture) - .expect("plan"); - let bound = matches!(write, WriteSource::Texture { .. }); - (bound, planner.variant.storage_images.get(&texture).copied()) - }; - let choice = |pixel_format| { - storage_choice(pixel_format, StorageUse::texture(false, true), &p).expect("choice") - }; - for pf in [ - PixelFormat::RGBA16Sint, - PixelFormat::R32Uint, - PixelFormat::RG32Sint, - ] { - assert_eq!(plan(pf, &numeric), (true, Some(choice(pf))), "{pf:?}"); - } - assert!(!plan(PixelFormat::RGBA32Float, &numeric).0); - assert!(!plan(PixelFormat::RGBA16Sint, &[]).0); - assert!(plan(PixelFormat::RGBA16Uint, &[]).0); -} - -/// A texture of a format held for copies alone (`metal::format::copies_only`), which Metal reads as -/// floats, bound at a `float` slot that samples, reads, writes or reads and writes it, is the -/// format's own refusal, `NotImplemented(Format)`: its emulation is admitted for no usage, so no -/// view serves the slot. No neutral stands in for it, as one did while the binder took it for a -/// mismatch, so a kernel's read completed and read the neutral's zeros. At a `uint` slot it is a -/// mismatch, whose neutral the binder writes and reports. -#[test] -fn a_texture_held_for_copies_alone_is_refused_at_a_float_slot() { - let texture = SlotRef { - stage: Stage::Kernel, - class: SlotClass::Texture, - index: 0, - }; - let p = crate::pipeline::testing::profile( - "moltenvk-m3", - crate::device::DevicePolicy::RESIDENT_TABLES, - ) - .expect("profile"); - let plan = |pixel_format, access: TextureAccess, sampled_type, ty| { - let slot = TextureSlot { - access, - ..slot_iface(TextureType::Type2D, sampled_type) - }; - let slots = BTreeMap::from([(texture, SlotInterface::Texture(slot))]); - let mut stage = StageShape::default(); - stage.textures.insert( - texture.index, - TextureShape::Texture { - address_modes: crate::metal::sampler::AddressModeMap::IDENTITY, - offset_base_axes: 0, - ycbcr_in_place: false, - ycbcr_planes_sampler: None, - texel_rows: false, - texture_type: TextureType::Type2D, - pixel_format, - sample_count: 1, - usage: crate::metal::TextureUsage::SHADER_READ - | crate::metal::TextureUsage::SHADER_WRITE, - mipmap_level_count: 1, - sparse: false, - swizzle: crate::metal::TextureSwizzleChannels::DEFAULT, - }, - ); - let shape = BTreeMap::from([(Stage::Kernel, stage)]); - let mut planner = ResourcePlanner { - profile: &p, - shape: &shape, - slots: &slots, - dependencies: &[], - stage_flags: |_| vk::PipelineStageFlags2::COMPUTE_SHADER, - variant: VariantKey::new(), - diagnostics: Vec::new(), - uses: Vec::new(), - template: Default::default(), - alpha_red_texels: Default::default(), - }; - let planned = planner - .plain_texture(0, 0, ty, texture) - .map(|(write, _)| write); - (planned, planner.diagnostics) - }; - let sampled = vk::DescriptorType::SAMPLED_IMAGE; - let storage = vk::DescriptorType::STORAGE_IMAGE; - let uses = [ - ("sampled", TextureAccess::new(true, false, false), sampled), - ("read", TextureAccess::new(false, true, false), sampled), - ("written", TextureAccess::new(false, false, true), storage), - ( - "read and written", - TextureAccess::new(false, true, true), - storage, - ), - ]; - let held: Vec = (PixelFormat::ALL.iter().copied()) - .filter(|&pf| copies_only(pf)) - .collect(); - assert_eq!(held.len(), 20, "{held:?}"); - for pf in held { - for (name, access, ty) in uses { - match plan(pf, access, SampledType::Float, ty) { - (Err(BindError::Unsupported(u)), diagnostics) => { - assert_eq!( - (u.feature, u.needs), - (Feature::Format, Needs::NotImplemented), - "{pf:?} {name}" - ); - assert!(diagnostics.is_empty(), "{pf:?} {name}: {diagnostics:?}"); - } - other => panic!("{pf:?} {name}: {other:?}"), - } - } - let (mismatch, diagnostics) = plan( - pf, - TextureAccess::new(false, true, false), - SampledType::Uint, - sampled, - ); - assert!( - matches!(mismatch, Ok(WriteSource::Neutral(_))), - "{pf:?} at a uint slot: {mismatch:?}" - ); - assert!( - matches!( - diagnostics.as_slice(), - [PlanDiagnostic::IncompatibleBinding { .. } - | PlanDiagnostic::CrossClassNeutral { .. }] - ), - "{pf:?} at a uint slot: {diagnostics:?}" - ); - } -} - -/// A sampled view selects the depth aspect of a depth (or combined) format, the stencil aspect of -/// a stencil-only one, and color otherwise; the formatless `Identity` choice is the default -/// declaration and stays out of the variant. -#[test] -fn view_aspects_and_the_default_storage_choice() { - assert_eq!( - view_aspect(PixelFormat::Depth32FloatStencil8), - vk::ImageAspectFlags::DEPTH - ); - assert_eq!( - view_aspect(PixelFormat::Depth16Unorm), - vk::ImageAspectFlags::DEPTH - ); - assert_eq!( - view_aspect(PixelFormat::Stencil8), - vk::ImageAspectFlags::STENCIL - ); - assert_eq!( - view_aspect(PixelFormat::RGBA8Unorm), - vk::ImageAspectFlags::COLOR - ); - let rgba8 = StorageImageChoice::new(vk::Format::R8G8B8A8_UNORM, StorageImageClass::Identity); - assert_eq!( - storage_class(Some(&rgba8)), - StorageFormatClass::Format(vk::Format::R8G8B8A8_UNORM) - ); - assert_eq!(storage_class(None), StorageFormatClass::Unknown); - // The default declaration serves an `Identity` choice exactly where the view's format serves - // the uses without a format: the device's features, and the format's bits for an image or a - // texel buffer. - let write = StorageUse::texture(false, true); - let read_write = StorageUse::texture(true, true); - let rgba = vk::Format::R8G8B8A8_UNORM; - let mut alias = rgba8; - alias.class = StorageImageClass::SwizzleBgra; - alias.alias = Some(crate::pipeline::lower_inputs::AliasView::new( - vk::Format::B8G8R8A8_UNORM, - )); - let mut texel_variants = BTreeSet::new(); - for (stem, p) in crate::spirv::testing::committed_profiles().expect("profiles") { - let i = &p.fields().images; - // `R8G8B8A8_UNORM` is a storage image on every committed profile, and in the - // specification's list of formats the device features cover. - assert_eq!( - needs_variant(&rgba8, rgba, write, &p), - !i.storage_write_without_format, - "{stem}" - ); - assert_eq!( - needs_variant(&rgba8, rgba, read_write, &p), - !(i.storage_write_without_format && i.storage_read_without_format), - "{stem}" - ); - assert!(needs_variant(&alias, rgba, write, &p), "{stem}"); - // A texel buffer has no implied bit: its buffer features decide. - let r32 = StorageImageChoice::new(vk::Format::R32_UINT, StorageImageClass::Identity); - let buffer_write = StorageUse::texel_buffer(false, true); - let has = i.storage_write_without_format - && p.supports_format( - vk::Format::R32_UINT, - FormatUsage::StorageTexelBufferWriteWithoutFormat, - ); - assert_eq!( - needs_variant(&r32, vk::Format::R32_UINT, buffer_write, &p), - !has, - "{stem}" - ); - if !has { - texel_variants.insert(stem); - } - } - // SwiftShader's `R32_UINT` buffer features lack `STORAGE_WRITE_WITHOUT_FORMAT` though it has - // `shaderStorageImageWriteWithoutFormat`; lavapipe's state it. - assert!( - texel_variants.contains("runtime-floor"), - "{texel_variants:?}" - ); - assert!(!texel_variants.contains("lavapipe"), "{texel_variants:?}"); - // A view format without a SPIR-V image format is declared formatless. - let bgra = StorageImageChoice::new(vk::Format::B8G8R8A8_UNORM, StorageImageClass::SrgbEncode); - assert_eq!(storage_class(Some(&bgra)), StorageFormatClass::Unknown); -} - -/// Metal reads a depth texel through a colour texture type as `(d, d, d, 1)` (Apple M4: -/// `Depth16Unorm`, `Depth32Float` and `Depth32Float_Stencil8` through `texture2d` and -/// `texture2d`, read, sampled, gathered and sampled with gradients, in a kernel and a -/// fragment function), and a stencil texel through `texture2d` as `(s, 0, 0, 1)`, which -/// Vulkan's identity reads too. So every depth format's sampled view that no -/// comparison reads replicates the depth with alpha one, on every committed profile where the -/// format is sampled; a comparison's view and every stencil view keep the identity, and the -/// border check reads the depth through the same mapping. -#[test] -fn a_depth_read_as_colour_replicates_its_depth_as_metal_does() { - let t = TextureSlot { - depth_compare: true, - ..slot_iface(TextureType::Type2D, SampledType::Float) - }; - let class = |compare| { - declared( - &t, - vk::DescriptorType::SAMPLED_IMAGE, - false, - compare, - StorageFormatClass::NotStorage, - ) - .unwrap() - }; - let u = slot_iface(TextureType::Type2D, SampledType::Uint); - let uint = declared( - &u, - vk::DescriptorType::SAMPLED_IMAGE, - false, - false, - StorageFormatClass::NotStorage, - ) - .unwrap(); - let depths = [ - PixelFormat::Depth16Unorm, - PixelFormat::Depth32Float, - PixelFormat::Depth24UnormStencil8, - PixelFormat::Depth32FloatStencil8, - ]; - let stencils = [ - PixelFormat::Stencil8, - PixelFormat::X32Stencil8, - PixelFormat::X24Stencil8, - ]; - let mut seen = 0; - for (stem, p) in crate::spirv::testing::committed_profiles().expect("profiles") { - for pf in depths { - let Ok(read) = sampled_view(&p, pf, &class(false)) else { - continue; - }; - seen += 1; - assert_eq!( - (read.aspect, read.components), - (vk::ImageAspectFlags::DEPTH, DEPTH_AS_COLOR), - "{stem} {pf:?}" - ); - let compare = sampled_view(&p, pf, &class(true)).unwrap(); - assert_eq!( - compare.components, - vk::ComponentMapping::IDENTITY, - "{stem} {pf:?}" - ); - } - for pf in stencils { - let Ok(read) = sampled_view(&p, pf, &uint) else { - continue; - }; - assert_eq!( - (read.aspect, read.components), - ( - vk::ImageAspectFlags::STENCIL, - vk::ComponentMapping::IDENTITY - ), - "{stem} {pf:?}" - ); - } - } - assert!(seen > 0, "no profile samples a depth format"); -} - -/// A bound runtime sampler's values are checked at plan time from its shape, with exactly the -/// verdict `vk_sampler` gives the descriptor for the binding's use: mirror-clamp needs -/// `samplerMirrorClampToEdge`, and NaN or inverted LOD clamps are invalid descriptors; anisotropy is -/// refused nowhere (without `samplerAnisotropy` the Vulkan sampler is isotropic and the module -/// emulates Metal's filter or announces the device's), a min reduction reads the weighted average, -/// refused nowhere, and an axis clamping to zero beside one clamping to a white border reads the one -/// color, refused nowhere. Every refusal kind occurs on some committed profile or on -/// `runtime-floor` without `samplerMirrorClampToEdge` (below the runtime's floor, which requires it). -#[test] -fn runtime_sampler_values_are_checked_at_plan_time() { - use crate::bind::state::SamplerDescriptor; - use crate::metal::sampler::{vk_sampler, SamplerUse}; - use crate::metal::{SamplerAddressMode, SamplerBorderColor, SamplerReductionMode}; - let slot = SlotRef { - stage: Stage::Fragment, - class: SlotClass::Sampler, - index: 2, - }; - let base = SamplerDescriptor::new(); - let mut cases = vec![("default", base)]; - let mut d = base; - d.max_anisotropy = 16; - cases.push(("anisotropic", d)); - let mut d = base; - d.t_address_mode = SamplerAddressMode::MirrorClampToEdge; - cases.push(("mirror clamp", d)); - let mut d = base; - d.s_address_mode = SamplerAddressMode::ClampToZero; - d.r_address_mode = SamplerAddressMode::ClampToBorderColor; - d.border_color = SamplerBorderColor::OpaqueWhite; - cases.push(("zero beside a border", d)); - let mut d = base; - d.reduction_mode = SamplerReductionMode::Minimum; - cases.push(("min", d)); - let mut d = base; - d.lod_max_clamp = f32::NAN; - cases.push(("NaN LOD", d)); - let mut d = base; - d.lod_min_clamp = 3.0; - d.lod_max_clamp = 2.0; - cases.push(("inverted LOD", d)); - let mut refused = BTreeMap::new(); - let mut accepted = BTreeMap::new(); - let mut profiles = crate::spirv::testing::committed_profiles().expect("profiles"); - profiles.push(( - "runtime-floor without samplerMirrorClampToEdge".into(), - crate::pipeline::testing::profile_without( - "runtime-floor", - &[crate::device::requirements::VkFeature::SamplerMirrorClampToEdge], - crate::device::DevicePolicy::RESIDENT_TABLES, - ) - .expect("profile"), - )); - for (stem, p) in profiles { - for compare in [false, true] { - let mut slots = BTreeMap::new(); - slots.insert( - slot, - SlotInterface::Sampler(SamplerSlot { - compare, - coordinate_sensitive: false, - }), - ); - for (name, desc) in &cases { - let mut stage = StageShape::default(); - stage - .samplers - .insert(slot.index, BoundSampler::new(*desc).shape()); - let shape = BTreeMap::from([(Stage::Fragment, stage)]); - let mut planner = ResourcePlanner { - profile: &p, - shape: &shape, - slots: &slots, - dependencies: &[], - stage_flags: |_| vk::PipelineStageFlags2::FRAGMENT_SHADER, - variant: VariantKey::new(), - diagnostics: Vec::new(), - uses: Vec::new(), - template: Default::default(), - alpha_red_texels: Default::default(), - }; - let planned = planner.sampler(slot); - match vk_sampler(desc, SamplerUse::new(compare, false), &p) { - Ok(_) => { - assert_eq!( - planned, - Ok(WriteSource::Sampler { - slot, - compare, - integer: false, - opaque_black: crate::metal::sampler::OpaqueBlackBorder::Stated, - }), - "{stem} {name} compare={compare}" - ); - *accepted.entry(*name).or_insert(0) += 1; - } - Err(e) => { - assert_eq!(planned, Err(bind_error(e)), "{stem} {name} {compare}"); - *refused.entry(*name).or_insert(0) += 1; - } - } - } - // An unbound runtime sampler is the neutral of the use's comparison. - let shape = BTreeMap::new(); - let mut planner = ResourcePlanner { - profile: &p, - shape: &shape, - slots: &slots, - dependencies: &[], - stage_flags: |_| vk::PipelineStageFlags2::FRAGMENT_SHADER, - variant: VariantKey::new(), - diagnostics: Vec::new(), - uses: Vec::new(), - template: Default::default(), - alpha_red_texels: Default::default(), - }; - assert_eq!( - planner.sampler(slot), - Ok(WriteSource::Neutral(NeutralResource::Sampler { compare })) - ); - } - } - assert!( - refused.contains_key("mirror clamp"), - "mirror clamp is refused somewhere" - ); - assert!( - accepted.contains_key("mirror clamp"), - "mirror clamp is accepted somewhere" - ); - for name in ["NaN LOD", "inverted LOD"] { - assert!( - !accepted.contains_key(name), - "{name} is never a Vulkan sampler" - ); - } - for name in ["default", "anisotropic", "min", "zero beside a border"] { - assert!(!refused.contains_key(name), "{name} is refused"); - } -} - -/// A layout's immutable (constexpr) sampler reads the bound view as a runtime sampler does. Through -/// a linear sampler a float texture needs its view format's `SAMPLED_IMAGE_FILTER_LINEAR` (refused -/// where a committed profile lacks it for `R32_SFLOAT`), while an integer texture's immutable -/// sampler is nearest (`metal::sampler::vk_sampler`) and needs nothing. -#[test] -fn an_immutable_linear_sampler_needs_a_filterable_view() { - use crate::bind::state::SamplerDescriptor; - use crate::metal::sampler::{vk_sampler, SamplerUse}; - use crate::metal::SamplerMinMagFilter; - let texture = SlotRef { - stage: Stage::Kernel, - class: SlotClass::Texture, - index: 0, - }; - let mut linear = SamplerDescriptor::new(); - linear.min_filter = SamplerMinMagFilter::Linear; - linear.mag_filter = SamplerMinMagFilter::Linear; - let (mut refused, mut accepted) = (0, 0); - for (stem, p) in crate::spirv::testing::committed_profiles().expect("profiles") { - for (pf, sampled_type) in [ - (PixelFormat::R32Float, SampledType::Float), - (PixelFormat::R16Uint, SampledType::Uint), - ] { - let integer = sampled_type != SampledType::Float; - let t = slot_iface(TextureType::Type2D, sampled_type); - let slots = BTreeMap::from([(texture, SlotInterface::Texture(t))]); - let mut stage = StageShape::default(); - stage.textures.insert( - texture.index, - TextureShape::Texture { - address_modes: crate::metal::sampler::AddressModeMap::IDENTITY, - offset_base_axes: 0, - ycbcr_in_place: false, - ycbcr_planes_sampler: None, - texel_rows: false, - texture_type: TextureType::Type2D, - pixel_format: pf, - sample_count: 1, - usage: crate::metal::TextureUsage::SHADER_READ, - mipmap_level_count: 1, - sparse: false, - swizzle: crate::metal::TextureSwizzleChannels::DEFAULT, - }, - ); - let shape = BTreeMap::from([(Stage::Kernel, stage)]); - let mut planner = ResourcePlanner { - profile: &p, - shape: &shape, - slots: &slots, - dependencies: &[], - stage_flags: |_| vk::PipelineStageFlags2::COMPUTE_SHADER, - variant: VariantKey::new(), - diagnostics: Vec::new(), - uses: Vec::new(), - template: Default::default(), - alpha_red_texels: Default::default(), - }; - let immutable = vk_sampler(&linear, SamplerUse::new(false, integer), &p).expect("maps"); - let sampler = CombinedSampler::new(SamplerRef::Constexpr([0, 0]), false, integer); - let planned = planner.combined(texture, sampler, Some(&immutable)); - let class = declared( - &t, - vk::DescriptorType::SAMPLED_IMAGE, - false, - false, - StorageFormatClass::NotStorage, - ) - .expect("declared"); - let format = sampled_view(&p, pf, &class).expect("view").format; - let filterable = p.supports_format(format, FormatUsage::SampledImageFilterLinear); - if integer || filterable { - assert!( - matches!(planned, Ok(WriteSource::CombinedImageSampler { .. })), - "{stem} {pf:?}: {planned:?}" - ); - accepted += 1; - } else { - assert_eq!( - planned, - Err(BindError::Unsupported(Unsupported::needs( - Feature::Format, - Capability::Format { - format, - usage: FormatUsage::SampledImageFilterLinear - }, - ))), - "{stem} {pf:?}" - ); - refused += 1; - } - } - } - assert!( - refused > 0 && accepted > 0, - "{refused} refused, {accepted} accepted" - ); -} - -/// A linear comparison sampler (a PCF shadow sampler: `filter::linear`, `compare_func::less`) -/// filters the comparison results, so its depth view needs no `SAMPLED_IMAGE_FILTER_LINEAR` -/// (VUID-vkCmdDispatch-magFilter-04553 and -mipmapMode-04770 exclude `compareEnable`): bound as a -/// layout's immutable sampler to `Depth32Float` or `Depth16Unorm` it is accepted on every -/// committed profile, including those whose depth formats are not linearly filterable -/// (`vk12-floor`). The same sampler without comparison needs the feature there. -#[test] -fn a_linear_compare_sampler_needs_no_filterable_view() { - use crate::bind::state::SamplerDescriptor; - use crate::metal::sampler::{vk_sampler, SamplerUse}; - use crate::metal::{CompareFunction, SamplerMinMagFilter, SamplerMipFilter}; - let texture = SlotRef { - stage: Stage::Kernel, - class: SlotClass::Texture, - index: 0, - }; - let mut pcf = SamplerDescriptor::new(); - pcf.min_filter = SamplerMinMagFilter::Linear; - pcf.mag_filter = SamplerMinMagFilter::Linear; - pcf.mip_filter = SamplerMipFilter::Linear; - pcf.compare_function = CompareFunction::Less; - let (mut unfilterable, mut floor_seen) = (0, false); - for (stem, p) in crate::spirv::testing::committed_profiles().expect("profiles") { - for pf in [PixelFormat::Depth32Float, PixelFormat::Depth16Unorm] { - for compare in [true, false] { - let t = TextureSlot { - depth_compare: compare, - ..slot_iface(TextureType::Type2D, SampledType::Float) - }; - let slots = BTreeMap::from([(texture, SlotInterface::Texture(t))]); - let mut stage = StageShape::default(); - stage.textures.insert( - texture.index, - TextureShape::Texture { - address_modes: crate::metal::sampler::AddressModeMap::IDENTITY, - offset_base_axes: 0, - ycbcr_in_place: false, - ycbcr_planes_sampler: None, - texel_rows: false, - texture_type: TextureType::Type2D, - pixel_format: pf, - sample_count: 1, - usage: crate::metal::TextureUsage::SHADER_READ, - mipmap_level_count: 1, - sparse: false, - swizzle: crate::metal::TextureSwizzleChannels::DEFAULT, - }, - ); - let shape = BTreeMap::from([(Stage::Kernel, stage)]); - let mut planner = ResourcePlanner { - profile: &p, - shape: &shape, - slots: &slots, - dependencies: &[], - stage_flags: |_| vk::PipelineStageFlags2::COMPUTE_SHADER, - variant: VariantKey::new(), - diagnostics: Vec::new(), - uses: Vec::new(), - template: Default::default(), - alpha_red_texels: Default::default(), - }; - let immutable = - vk_sampler(&pcf, SamplerUse::new(compare, false), &p).expect("maps"); - assert_eq!(immutable.compare.is_some(), compare, "{stem}"); - let sampler = CombinedSampler::new(SamplerRef::Constexpr([0, 0]), compare, false); - let planned = planner.combined(texture, sampler, Some(&immutable)); - let class = declared( - &t, - vk::DescriptorType::SAMPLED_IMAGE, - false, - compare, - StorageFormatClass::NotStorage, - ) - .expect("declared"); - let format = sampled_view(&p, pf, &class).expect("view").format; - let filterable = p.supports_format(format, FormatUsage::SampledImageFilterLinear); - if compare || filterable { - assert!( - matches!(planned, Ok(WriteSource::CombinedImageSampler { .. })), - "{stem} {pf:?} compare={compare}: {planned:?}" - ); - } else { - assert_eq!( - planned, - Err(BindError::Unsupported(Unsupported::needs( - Feature::Format, - Capability::Format { - format, - usage: FormatUsage::SampledImageFilterLinear - }, - ))), - "{stem} {pf:?}" - ); - } - if compare && !filterable { - unfilterable += 1; - floor_seen |= stem == "runtime-floor"; - } - } - } - } - assert!( - unfilterable > 0 && floor_seen, - "no profile lacks linear filtering of a depth format ({unfilterable})" - ); -} - -/// A texture slot sampled through Metal's bicubic filter specializes `BicubicTexels` from the bound -/// format's family; an unbound slot or an incompatible binding (an integer format on a float slot) -/// takes the neutral treatment, and a compatible format of no measured family (a compressed one) is -/// refused. -#[test] -fn bicubic_texels_follow_the_bound_format() { - use crate::metal::bicubic::{texels, BicubicTexels}; - let texture = SlotRef { - stage: Stage::Kernel, - class: SlotClass::Texture, - index: 0, - }; - let p = crate::pipeline::testing::profile( - "moltenvk-m3", - crate::device::DevicePolicy::RESIDENT_TABLES, - ) - .expect("profile"); - let t = slot_iface(TextureType::Type2D, SampledType::Float); - let slots = BTreeMap::from([(texture, SlotInterface::Texture(t))]); - let plan = |pf: Option| { - let mut stage = StageShape::default(); - if let Some(pf) = pf { - stage.textures.insert( - texture.index, - TextureShape::Texture { - address_modes: crate::metal::sampler::AddressModeMap::IDENTITY, - offset_base_axes: 0, - ycbcr_in_place: false, - ycbcr_planes_sampler: None, - texel_rows: false, - texture_type: TextureType::Type2D, - pixel_format: pf, - sample_count: 1, - usage: crate::metal::TextureUsage::SHADER_READ, - mipmap_level_count: 1, - sparse: false, - swizzle: crate::metal::TextureSwizzleChannels::DEFAULT, - }, - ); - } - let shape = BTreeMap::from([(Stage::Kernel, stage)]); - let planner = ResourcePlanner { - profile: &p, - shape: &shape, - slots: &slots, - dependencies: &[], - stage_flags: |_| vk::PipelineStageFlags2::COMPUTE_SHADER, - variant: VariantKey::new(), - diagnostics: Vec::new(), - uses: Vec::new(), - template: Default::default(), - alpha_red_texels: Default::default(), - }; - planner.bicubic_texels(texture) - }; - for pf in [ - PixelFormat::RGBA8Unorm, - PixelFormat::R8Snorm, - PixelFormat::RGBA16Float, - PixelFormat::RG32Float, - PixelFormat::A8Unorm, - ] { - let want = texels(pf).expect("measured").0; - assert_eq!(plan(Some(pf)), Ok(u64::from(want)), "{pf:?}"); - } - let neutral = u64::from(BicubicTexels::NEUTRAL.0); - assert_eq!(plan(None), Ok(neutral)); - assert_eq!(plan(Some(PixelFormat::RGBA8Uint)), Ok(neutral)); - assert_eq!( - plan(Some(PixelFormat::BC1RGBA)), - Err(BindError::Unsupported(Unsupported::not_implemented( - Feature::SamplerBicubicFilter - ))) - ); -} - -/// A runtime sampler slot specializes `SamplerState` to the bound sampler's word masked by the -/// fields the function reads, and an unbound slot to 0. So the pixel predicate holds as it did of -/// `SamplerCoords`: pixel coordinates wherever the sampler uses them, whatever its filters. -#[test] -fn sampler_state_follows_the_bound_sampler() { - use crate::bind::state::SamplerDescriptor; - use crate::metal::sampler::SamplerWord as W; - use crate::metal::SamplerMinMagFilter as F; - let slot = SlotRef { - stage: Stage::Fragment, - class: SlotClass::Sampler, - index: 1, - }; - let p = crate::pipeline::testing::profile( - "moltenvk-m3", - crate::device::DevicePolicy::RESIDENT_TABLES, - ) - .expect("profile"); - let slots = BTreeMap::from([( - slot, - SlotInterface::Sampler(SamplerSlot { - compare: false, - coordinate_sensitive: true, - }), - )]); - let plan = |desc: Option| { - let mut stage = StageShape::default(); - if let Some(d) = desc { - stage - .samplers - .insert(slot.index, BoundSampler::new(d).shape()); - } - let shape = BTreeMap::from([(Stage::Fragment, stage)]); - let planner = ResourcePlanner { - profile: &p, - shape: &shape, - slots: &slots, - dependencies: &[], - stage_flags: |_| vk::PipelineStageFlags2::FRAGMENT_SHADER, - variant: VariantKey::new(), - diagnostics: Vec::new(), - uses: Vec::new(), - template: Default::default(), - alpha_red_texels: Default::default(), - }; - [W::PIXEL_COORDINATES, W::LINEAR, W::FIELDS] - .map(|fields| planner.sampler_state(slot, fields) as u32) - }; - let with = |normalized: bool, filter: F| { - let mut d = SamplerDescriptor::new(); - d.normalized_coordinates = normalized; - d.min_filter = filter; - d.mag_filter = filter; - d.t_address_mode = crate::metal::SamplerAddressMode::Repeat; - Some(d) - }; - let linear = W::MIN_LINEAR | W::MAG_LINEAR; - let repeat_t = crate::metal::SamplerAddressMode::Repeat.as_raw() << W::ADDRESS_SHIFT[1]; - let pixel = W::PIXEL_COORDINATES; - assert_eq!(plan(None), [0, 0, 0]); - assert_eq!(plan(with(true, F::Nearest)), [0, 0, repeat_t]); - assert_eq!(plan(with(true, F::Linear)), [0, linear, linear | repeat_t]); - assert_eq!(plan(with(false, F::Nearest)), [pixel, 0, pixel | repeat_t]); - assert_eq!( - plan(with(false, F::Linear)), - [pixel, linear, pixel | linear | repeat_t] - ); - // The pixel predicate: the word masked by it is exactly the pixel-coordinates bit. - let states = |desc| plan(desc)[0] == pixel; - assert!(!states(with(true, F::Nearest))); - assert!(states(with(false, F::Linear))); - assert!(states(with(false, F::Nearest))); - assert!(!states(None)); -} - -/// A separate texture's write is the image its combined binding's would be, with the same checks. A -/// constexpr pair checks the stage's separate sampler's immutable sampler against the bound view, -/// as the combined write does. A runtime sampler's write meets no image, so each of its textures' -/// writes checks the bound sampler's filtering against its view at plan time: a linear sampler on -/// `R32Float` is refused where a committed profile cannot filter it (the format named), and passes -/// elsewhere, as on `RGBA8Unorm` everywhere; a nearest one needs nothing; an unbound sampler is the -/// neutral, which needs nothing. The separate sampler's own write is the bound sampler for the use, -/// or none for a constexpr one. -#[test] -fn a_separate_pair_takes_the_combined_pairs_checks() { - use crate::bind::state::SamplerDescriptor; - use crate::metal::sampler::{vk_sampler, SamplerUse}; - use crate::metal::SamplerMinMagFilter; - let texture = SlotRef { - stage: Stage::Kernel, - class: SlotClass::Texture, - index: 3, - }; - let sampler_slot = SlotRef { - stage: Stage::Kernel, - class: SlotClass::Sampler, - index: 1, - }; - let mut linear = SamplerDescriptor::new(); - linear.min_filter = SamplerMinMagFilter::Linear; - linear.mag_filter = SamplerMinMagFilter::Linear; - let nearest = SamplerDescriptor::new(); - let (mut refused, mut passed) = (BTreeSet::new(), BTreeSet::new()); - for (stem, p) in crate::spirv::testing::committed_profiles().expect("profiles") { - let t = slot_iface(TextureType::Type2D, SampledType::Float); - for pf in [PixelFormat::R32Float, PixelFormat::RGBA8Unorm] { - let class = declared( - &t, - vk::DescriptorType::SAMPLED_IMAGE, - false, - false, - StorageFormatClass::NotStorage, - ) - .expect("declared"); - let view = sampled_view(&p, pf, &class).expect("view"); - let filterable = p.supports_format(view.format, FormatUsage::SampledImageFilterLinear); - let refusal = Err(BindError::Unsupported(Unsupported::needs( - Feature::Format, - Capability::Format { - format: view.format, - usage: FormatUsage::SampledImageFilterLinear, - }, - ))); - let bound = WriteSource::Texture { - slot: texture, - view, - }; - for (name, desc) in [ - ("linear", Some(linear)), - ("nearest", Some(nearest)), - ("unbound", None), - ] { - let slots = BTreeMap::from([ - (texture, SlotInterface::Texture(t)), - ( - sampler_slot, - SlotInterface::Sampler(SamplerSlot { - compare: false, - coordinate_sensitive: false, - }), - ), - ]); - let mut stage = StageShape::default(); - stage.textures.insert( - texture.index, - TextureShape::Texture { - address_modes: crate::metal::sampler::AddressModeMap::IDENTITY, - offset_base_axes: 0, - ycbcr_in_place: false, - ycbcr_planes_sampler: None, - texel_rows: false, - texture_type: TextureType::Type2D, - pixel_format: pf, - sample_count: 1, - usage: crate::metal::TextureUsage::SHADER_READ, - mipmap_level_count: 1, - sparse: false, - swizzle: crate::metal::TextureSwizzleChannels::DEFAULT, - }, - ); - if let Some(d) = desc { - stage - .samplers - .insert(sampler_slot.index, BoundSampler::new(d).shape()); - } - let shape = BTreeMap::from([(Stage::Kernel, stage)]); - let mut planner = ResourcePlanner { - profile: &p, - shape: &shape, - slots: &slots, - dependencies: &[], - stage_flags: |_| vk::PipelineStageFlags2::COMPUTE_SHADER, - variant: VariantKey::new(), - diagnostics: Vec::new(), - uses: Vec::new(), - template: Default::default(), - alpha_red_texels: Default::default(), - }; - // The runtime pair. - let runtime = - CombinedSampler::new(SamplerRef::Slot(sampler_slot.index), false, false); - let planned = planner.separate_texture(texture, runtime, None); - let what = format!("{stem} {pf:?} runtime {name}"); - if name == "linear" && !filterable { - assert_eq!(planned, refusal, "{what}"); - refused.insert(stem.clone()); - } else { - assert_eq!(planned, Ok(bound.clone()), "{what}"); - if name == "linear" && pf == PixelFormat::R32Float { - passed.insert(stem.clone()); - } - } - let written = planner.separate_sampler(Stage::Kernel, runtime, None); - let expected = match desc { - Some(_) => WriteSource::Sampler { - slot: sampler_slot, - compare: false, - integer: false, - opaque_black: crate::metal::sampler::OpaqueBlackBorder::Stated, - }, - None => WriteSource::Neutral(NeutralResource::Sampler { compare: false }), - }; - assert_eq!(written, Ok(Some(expected)), "{what}"); - // The constexpr pair: the immutable sampler against the view, as combined. - let Some(d) = desc else { continue }; - let immutable = vk_sampler(&d, SamplerUse::new(false, false), &p).expect("maps"); - let constexpr = CombinedSampler::new(SamplerRef::Constexpr([0, 0]), false, false); - let combined = planner.combined(texture, constexpr, Some(&immutable)); - let planned = planner.separate_texture(texture, constexpr, Some(&immutable)); - let what = format!("{stem} {pf:?} constexpr {name}"); - match combined { - Ok(WriteSource::CombinedImageSampler { - image: ImageSource::Texture { slot, view }, - sampler: SamplerSource::Immutable, - }) => assert_eq!(planned, Ok(WriteSource::Texture { slot, view }), "{what}"), - Err(e) => assert_eq!(planned, Err(e), "{what}"), - other => panic!("{what}: {other:?}"), - } - assert_eq!( - planner.separate_sampler(Stage::Kernel, constexpr, Some(&immutable)), - Ok(None), - "{what}" - ); - } - } - } - assert!( - !refused.is_empty() && !passed.is_empty(), - "refused on {refused:?}, passed on {passed:?}" - ); -} - -/// On a device without `A8_UNORM` (lavapipe's profile), an `A8Unorm` texture buffer's bytes are -/// viewed as `R8_UNORM`, Metal's alpha in red: a storage slot through its choice's class -/// (`StorageImageClass::AlphaInRed`), whose swizzle stays the texture's; a uniform one with no -/// class, whose swizzle takes the alpha from red (`TextureSwizzleChannels::alpha_in_red`). A -/// uniform slot that reads without applying the swizzle is refused there. Where the device has -/// `A8_UNORM` (MoltenVK's), the uniform view is `A8_UNORM` and its swizzle the texture's. -#[test] -fn an_a8_texture_buffer_without_a8_unorm_views_its_bytes_in_red() { - use crate::metal::{TextureSwizzle as S, TextureSwizzleChannels}; - use crate::pipeline::facts::{Mechanism, RuntimeFact}; - let slot = |index| SlotRef { - stage: Stage::Kernel, - class: SlotClass::Texture, - index, - }; - let (uniform, storage) = (slot(0), slot(1)); - let mut read = slot_iface(TextureType::TextureBuffer, SampledType::Float); - read.access = TextureAccess::new(false, true, false); - let mut read_write = read; - read_write.access = TextureAccess::new(false, true, true); - let slots = BTreeMap::from([ - (uniform, SlotInterface::Texture(read)), - (storage, SlotInterface::Texture(read_write)), - ]); - let shape = |swizzle| { - let mut stage = StageShape::default(); - for index in [0, 1] { - let pixel_format = PixelFormat::A8Unorm; - let buffer = TextureShape::Buffer { - pixel_format, - swizzle, - parts: 1, - }; - stage.textures.insert(index, buffer); - } - BTreeMap::from([(Stage::Kernel, stage)]) - }; - let swizzle = TextureSwizzleChannels::new(S::Alpha, S::Zero, S::Green, S::One); - let swizzled = shape(swizzle); - let stated = [uniform, storage].map(|slot| { - let fact = RuntimeFact::TextureSwizzle { slot }; - RuntimeDependency::new(fact, Mechanism::Specialization) - }); - fn make<'a>( - profile: &'a DeviceProfile, - shape: &'a BTreeMap, - slots: &'a BTreeMap, - dependencies: &'a [RuntimeDependency], - ) -> ResourcePlanner<'a> { - ResourcePlanner { - profile, - shape, - slots, - dependencies, - stage_flags: |_| vk::PipelineStageFlags2::COMPUTE_SHADER, - variant: VariantKey::new(), - diagnostics: Vec::new(), - uses: Vec::new(), - template: Default::default(), - alpha_red_texels: Default::default(), - } - } - let uniform_ty = vk::DescriptorType::UNIFORM_TEXEL_BUFFER; - let storage_ty = vk::DescriptorType::STORAGE_TEXEL_BUFFER; - for (profile, held) in [("lavapipe", true), ("moltenvk-m3", false)] { - let p = crate::pipeline::testing::profile( - profile, - crate::device::DevicePolicy::RESIDENT_TABLES, - ) - .expect("profile"); - let a8 = PixelFormat::A8Unorm; - assert_eq!( - crate::metal::format::alpha_in_red(a8, &p), - held, - "{profile}" - ); - let mut planner = make(&p, &swizzled, &slots, &stated); - let own = match held { - true => vk::Format::R8_UNORM, - false => vk::Format::A8_UNORM, - }; - let planned = planner.plain_texture(0, 0, uniform_ty, uniform); - let Ok((WriteSource::TexelBuffer { format, .. }, _)) = planned else { - panic!("{profile}: {planned:?}"); - }; - assert_eq!(format, own, "{profile}: the uniform view"); - let planned = planner.plain_texture(0, 1, storage_ty, storage); - let Ok((WriteSource::TexelBuffer { format, .. }, _)) = planned else { - panic!("{profile}: {planned:?}"); - }; - // A storage view takes `R8_UNORM` wherever `A8_UNORM` does not serve the use, the device's - // images aside. - let class = planner - .variant - .storage_images - .get(&storage) - .map(|c| c.class); - let in_red = class == Some(StorageImageClass::AlphaInRed); - assert!(in_red || !held, "{profile}: {class:?}"); - let view = match in_red { - true => vk::Format::R8_UNORM, - false => vk::Format::A8_UNORM, - }; - assert_eq!(format, view, "{profile}: the storage view"); - let read_swizzle = match held { - true => TextureSwizzleChannels::new(S::Red, S::Zero, S::Zero, S::One), - false => swizzle, - }; - assert_eq!( - planner.texture_swizzle(uniform), - u64::from(read_swizzle.word()), - "{profile}: the uniform slot's swizzle" - ); - assert_eq!( - planner.texture_swizzle(storage), - u64::from(swizzle.word()), - "{profile}: the storage slot's swizzle" - ); - // A read that does not apply the swizzle. - let plain = shape(TextureSwizzleChannels::DEFAULT); - let mut planner = make(&p, &plain, &slots, &[]); - let planned = planner.plain_texture(0, 0, uniform_ty, uniform); - match held { - true => assert_eq!( - planned.map(|(w, _)| w), - Err(BindError::Unsupported(Unsupported::not_implemented( - Feature::Format - ))), - "{profile}" - ), - false => assert!(planned.is_ok(), "{profile}: {planned:?}"), - } - } -} diff --git a/crates/metal2vulkan/src/bind/plan/slots.rs b/crates/metal2vulkan/src/bind/plan/slots.rs deleted file mode 100644 index 622487a8b..000000000 --- a/crates/metal2vulkan/src/bind/plan/slots.rs +++ /dev/null @@ -1,856 +0,0 @@ -//! Buffer-slot planning shared by compute and render plans: the Metal table bounds, one -//! [`PlannedBuffer`] per statically used buffer slot, the `BufferRangeLimit` variant a shape's -//! length classes require, and the `uses` of bound buffers and used resources. - -use std::collections::BTreeMap; - -use super::{AccessClass, BoundKind, ByteRange, PlannedBuffer, ResourceUse, UseTarget}; -use crate::bind::state::{ - BindShape, BoundBuffer, BufferRanges, BufferShape, TextureShape, UsedClass, UsedShape, -}; -use crate::device::profile::Limits; -use crate::device::requirements::VkFeature; -use crate::device::{mechanism, DeviceProfile}; -use crate::error::{BindError, Capability, Feature, Unsupported}; -use crate::metal; -use crate::pipeline::artifact::RuntimeDependency; -use crate::pipeline::facts::{Mechanism, RuntimeFact}; -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, SpecKey, Stage}; -use crate::vk; - -use super::compute::internal; -use super::resources::ResourcePlanner; - -/// Metal's argument-table sizes: `buffers[31]` (and `threadgroup_lengths[31]`), `textures[128]`, -/// `samplers[16]`. -pub(crate) const MAX_BUFFERS: u32 = 31; -pub(crate) const MAX_TEXTURES: u32 = 128; -pub(crate) const MAX_SAMPLERS: u32 = 16; - -/// Every slot index of `shape` inside Metal's argument tables. -pub(crate) fn check_slots(shape: &BindShape) -> Result<(), BindError> { - for (&stage, s) in &shape.stages { - let tables = [ - (SlotClass::Buffer, MAX_BUFFERS, s.buffers.keys().max()), - (SlotClass::Texture, MAX_TEXTURES, s.textures.keys().max()), - (SlotClass::Sampler, MAX_SAMPLERS, s.samplers.keys().max()), - // A threadgroup-memory index names no argument slot; it is reported with the buffer - // table's class, whose size it shares. - ( - SlotClass::Buffer, - MAX_BUFFERS, - s.threadgroup_lengths.keys().max(), - ), - ]; - for (class, max, top) in tables { - if let Some(&index) = top.filter(|&&i| i >= max) { - return Err(BindError::SlotOutOfRange { - slot: SlotRef { - stage, - class, - index, - }, - }); - } - } - } - Ok(()) -} - -/// Where each layout binding sits, by source. -pub(crate) fn bindings(layout: &PipelineLayout) -> BTreeMap { - let mut out = BTreeMap::new(); - for set in &layout.sets { - for b in &set.bindings { - out.insert(b.source, (set.set, b.binding)); - } - } - out -} - -impl BoundKind { - /// What `shape` binds at a buffer slot. - pub(crate) fn of(shape: Option<&BufferShape>) -> BoundKind { - match shape { - None => BoundKind::Unbound, - Some(&BufferShape::Buffer { - device_address, - length_class, - .. - }) => BoundKind::Buffer { - device_address, - length_class, - }, - Some(BufferShape::Bytes { .. }) => BoundKind::Bytes, - } - } - - /// What `bound` binds at a buffer slot of a table of buffer range limits `ranges`: [`of`](Self::of) - /// its shape, which no offset class changes, read without making the shape. - pub(crate) fn of_bound(bound: Option<&BoundBuffer>, ranges: BufferRanges) -> BoundKind { - match bound { - None => BoundKind::Unbound, - Some(&BoundBuffer::Buffer { - length, - device_address, - .. - }) => BoundKind::Buffer { - device_address: device_address.is_some(), - length_class: ranges.length_class(length), - }, - Some(BoundBuffer::Bytes { .. }) => BoundKind::Bytes, - } - } -} - -/// The plan of buffer slot `slot` with interface `b` and what the shape binds there: its descriptor -/// binding (the descriptor form), the storage view's descriptor base alignment and range limit, and a -/// `MissingDeviceAddress` refusal for a device-address slot bound without an address: a buffer -/// without one, or inline bytes, but in a pipeline compiled for a replay's bindings (`replayed`, -/// `RuntimeFact::ReplayBindings`), which reads every buffer through the slot table the replay's -/// preprocess writes, inline bytes the encoder bound at the consumer's upload of them. The base -/// alignment is -/// `max(minStorageBufferOffsetAlignment, 16)` (`views::base_alignment`): a descriptor byte is then -/// congruent to its Metal address modulo 16, which a `uvec4` view of the slot relies on. -pub(crate) fn plan_buffer( - (slot, b, shape): (SlotRef, &BufferSlot, Option<&BufferShape>), - replayed: bool, - limits: &Limits, - bindings: &BTreeMap, -) -> Result { - let bound = BoundKind::of(shape); - let alignment = - crate::memory::views::base_alignment(limits.min_storage_buffer_offset_alignment); - let max_range = u64::from(limits.max_storage_buffer_range); - let binding = match b.form { - BufferForm::Descriptor => Some( - bindings - .get(&BindingSource::Buffer(slot)) - .copied() - .ok_or_else(|| internal(format!("descriptor slot {slot:?} has no binding")))?, - ), - BufferForm::Psb => { - let unaddressed = match bound { - BoundKind::Bytes => !replayed, - BoundKind::Buffer { device_address, .. } => !device_address, - BoundKind::Unbound => false, - }; - if unaddressed { - return Err(BindError::MissingDeviceAddress { slot }); - } - None - } - }; - Ok(PlannedBuffer { - slot, - window: b.window, - form: b.form, - access: b.access, - binding, - alignment, - max_range, - bound, - }) -} - -/// The value of `key` for a draw or dispatch of `shape`, whose resources `resources` plans, where -/// the bound resources decide it: a slot's presence, a bound sampler's words, a bound texture's -/// class, swizzle, sparseness and view axes. It is what a specialization constant of `key` is set -/// to, the one place a plan computes it, and the bound sampler's whole word a specialized note's -/// test alone reads (`SpecKey::BoundSamplerWord`). `None` for a key the bound resources do not -/// decide (a threadgroup's, a tile's, a pass's). -pub(crate) fn bound_value( - key: SpecKey, - shape: &BindShape, - resources: &ResourcePlanner<'_>, -) -> Result, BindError> { - Ok(Some(match key { - SpecKey::Presence(slot) => u64::from(present(shape, slot)), - SpecKey::SamplerState { slot, fields } => resources.sampler_state(slot, fields), - SpecKey::SamplerMinLevel(slot) => resources.sampler_min_level(slot), - SpecKey::SamplerAnisotropy(slot) => resources.sampler_anisotropy(slot), - SpecKey::NearestPixelSampler(slot) => resources.nearest_pixel_sampler(slot), - SpecKey::BoundSamplerWord(slot) => { - resources.sampler_state(slot, metal::sampler::SamplerWord::FIELDS) - } - // An unbound slot, or one bound to a placeholder format, reads its neutral: its - // out-of-bounds texel is all zero. - SpecKey::OutOfBoundsAlpha(slot) => bound_texture(shape, slot) - .and_then(TextureShape::out_of_bounds_alpha) - .unwrap_or(0), - SpecKey::BorderTexels(slot) => bound_texture(shape, slot) - .and_then(TextureShape::border_texels) - .unwrap_or(u64::from(metal::sampler::NEUTRAL_BORDER_TEXELS)), - SpecKey::BicubicTexels(slot) => resources.bicubic_texels(slot)?, - SpecKey::TextureSwizzle(slot) => resources.texture_swizzle(slot), - SpecKey::SparseTexture(slot) => sparse_texture(shape, slot), - SpecKey::ConstantLanes(slot) => constant_lanes(shape, slot), - SpecKey::OffsetBaseAxes(slot) => offset_base_axes(shape, slot), - _ => return Ok(None), - })) -} - -/// Record in `resources`' template the value of each key a specialized note of `stages` tests that -/// no push carries but the bound resources decide (`SpecKey::BoundSamplerWord`), or what the -/// command's handles can name (`SpecKey::HeapRawTextures` and `SpecKey::HeapNanFamilies`, through -/// `reach`, the stages a used resource's render stages reach, as for the heap's members), which -/// `BindingPlan::specialized_value` gives the runtime at -/// each draw or dispatch, where it reads such a note (`StageModule::precision_notes_bound`). Nothing -/// pushes it: instantiation writes only the keys its push fields name. -pub(crate) fn record_noted<'a>( - stages: impl IntoIterator, - shape: &BindShape, - resources: &mut ResourcePlanner<'_>, - reach: &dyn Fn(metal::RenderStages) -> Vec, -) -> Result<(), BindError> { - let tested: Vec = stages - .into_iter() - .flat_map(|stage| &stage.specialized_notes) - .flat_map(|note| ¬e.when) - .flat_map(|clause| &clause.all) - .map(|test| test.key) - .filter(|key| { - matches!( - key, - SpecKey::BoundSamplerWord(_) - | SpecKey::HeapRawTextures(_) - | SpecKey::HeapNanFamilies(_) - ) - }) - .collect(); - for key in tested { - if resources - .template - .specialized - .iter() - .any(|(k, _)| *k == key) - { - continue; - } - let value = match key { - SpecKey::HeapRawTextures(stage) => u64::from(heap_raw(shape, stage, reach)), - SpecKey::HeapNanFamilies(stage) => u64::from(heap_nan_families(shape, stage, reach)), - key => bound_value(key, shape, resources)?.ok_or_else(|| { - internal(format!("a noted {key:?}, which no bound resource decides")) - })?, - }; - let value = u32::try_from(value) - .map_err(|_| internal(format!("a noted {key:?} of {value}, past a word")))?; - resources.template.specialized.push((key, value)); - } - Ok(()) -} - -/// The `SpecKey::HeapRawTextures` of `stage` for `shape`: of the heap members of `shape` that reach -/// `stage` (`bind::heap`'s members: a texture the command makes resident, its render stages through -/// `reach`, or binds at a texture slot of the stage), the bit `bind::heap::HELD` where one is a -/// texture a heap holds by its raw texels alone (`lower::texture::heap_raw_form`), which the stage's -/// `float` read, sample or gather decodes by the device's arithmetic, and the bit -/// `bind::heap::FILTERED` where one such is of a form whose sample the function filters (not a -/// bfloat one). Both the notes' value and the stage's constant, whose `HELD` bit gates its raw arms -/// (`lower::texture::heap_raw_form`). -pub(crate) fn heap_raw( - shape: &BindShape, - stage: Stage, - reach: &dyn Fn(metal::RenderStages) -> Vec, -) -> u32 { - use crate::bind::heap::{FILTERED, HELD}; - let mut bits = 0; - for m in crate::bind::heap::members(shape, &[stage], reach) { - let TextureShape::Texture { pixel_format, .. } = m.shape else { - continue; - }; - if !crate::bind::heap::raw_held(&m.shape) { - continue; - } - bits |= HELD; - if crate::metal::format::ExtendedRange::of(pixel_format).is_some_and(|f| !f.bfloat()) { - bits |= FILTERED; - } - } - bits -} - -/// The `SpecKey::HeapNanFamilies` of `stage` for `shape`: the bit of each family -/// (`bind::heap::nan_family`) of the heap members of `shape` that reach `stage` (as for -/// [`heap_raw`]), whose texels a stage's `half` or `float` write may store a NaN in. -fn heap_nan_families( - shape: &BindShape, - stage: Stage, - reach: &dyn Fn(metal::RenderStages) -> Vec, -) -> u32 { - crate::bind::heap::members(shape, &[stage], reach) - .iter() - .map(|m| match m.shape { - TextureShape::Texture { pixel_format, .. } => { - crate::bind::heap::nan_family(pixel_format) - } - TextureShape::Buffer { .. } => 0, - }) - .fold(0, |bits, family| bits | family) -} - -/// Whether `shape` binds anything at `slot`. -fn present(shape: &BindShape, slot: SlotRef) -> bool { - shape - .stages - .get(&slot.stage) - .is_some_and(|s| match slot.class { - SlotClass::Buffer => s.buffers.contains_key(&slot.index), - SlotClass::Texture => s.textures.contains_key(&slot.index), - SlotClass::Sampler => s.samplers.contains_key(&slot.index), - }) -} - -/// The `SpecKey::SparseTexture` of `slot` for `shape`: 1 where the slot binds a sparse texture -/// (`TextureFacts::sparse`), 0 where it binds one that is not sparse or nothing. -fn sparse_texture(shape: &BindShape, slot: SlotRef) -> u64 { - u64::from(bound_texture(shape, slot).is_some_and(TextureShape::sparse)) -} - -/// The `SpecKey::ConstantLanes` of `slot` for `shape`: the lanes the bound sparse texture's format -/// and swizzle make constants (`TextureShape::constant_lanes`), 0 where the slot binds a texture -/// that is not sparse or nothing. -fn constant_lanes(shape: &BindShape, slot: SlotRef) -> u64 { - bound_texture(shape, slot).map_or(0, TextureShape::constant_lanes) -} - -/// The `SpecKey::OffsetBaseAxes` of `slot` for `shape`: the plane axes on which the bound view's -/// parent's base-level size, which Metal's texel-offset rule reads, is not a power of two where -/// the view's own is (`TextureShape::offset_base_axes`); 0 where the slot binds any other texture -/// or nothing. -fn offset_base_axes(shape: &BindShape, slot: SlotRef) -> u64 { - bound_texture(shape, slot).map_or(0, TextureShape::offset_base_axes) -} - -/// The texture slots whose function decodes an 8-bit sRGB texel (`RuntimeFact::SrgbTexture`) at -/// which `shape` binds a texture of such a format that `profile`'s device holds as its UNORM twin -/// (`metal::texel_format::srgb_twin_on`: a format it cannot sample), whose views read the codes: -/// the plan's `VariantKey::srgb_textures`. So is each slot of `cross` that the variant reads in -/// the float class (an integer slot), whose accesses there take `float` results, which the codes -/// serve as a float slot's: the variant's compile states `SrgbTexture` there. A slot bound in an -/// sRGB format the device samples reads the device's decode and joins nothing. Derived from the -/// device's format features alone, as the runtime's image plan holds the twin; the variant's -/// compile states the same facts, so its plan for the same shape states the same key. -pub(crate) fn srgb_variant( - profile: &DeviceProfile, - dependencies: &[RuntimeDependency], - shape: &BindShape, - cross: &BTreeMap, -) -> std::collections::BTreeSet { - let read_float = cross - .iter() - .filter(|(_, ty)| **ty == SampledType::Float) - .map(|(slot, _)| *slot); - dependencies - .iter() - .filter_map(|d| match d.fact { - RuntimeFact::SrgbTexture { slot } => Some(slot), - _ => None, - }) - .chain(read_float) - .filter(|slot| { - matches!(bound_texture(shape, *slot), Some(TextureShape::Texture { pixel_format, .. }) - if metal::texel_format::srgb_twin_on(*pixel_format, profile)) - }) - .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 -/// (`resources::cross_class`), each with that class: the plan's `VariantKey::cross_class`. The -/// variant's compile states the same facts, and its interface the same declared types, so its -/// plan for the same shape states the same key. -pub(crate) fn cross_variant( - dependencies: &[RuntimeDependency], - slots: &BTreeMap, - shape: &BindShape, -) -> BTreeMap { - dependencies - .iter() - .filter_map(|d| match d.fact { - RuntimeFact::CrossClassReads { slot } => Some(slot), - _ => None, - }) - .filter_map(|slot| { - let Some(SlotInterface::Texture(t)) = slots.get(&slot) else { - return None; - }; - let bound = bound_texture(shape, slot)?; - // A storage slot whose integer texels take the bound format's signedness reads an - // integer texture of either signedness in its own class: only a float one crosses, as - // the binding sees it (`resources::plain_texture`). - let numeric = dependencies - .iter() - .any(|d| d.fact == RuntimeFact::StorageTextureNumericType { slot }); - let t = match numeric { - true => super::resources::bound_integer_type(*t, Some(bound)), - false => *t, - }; - let class = super::resources::cross_class(&t, bound)?; - Some((slot, class)) - }) - .collect() -} - -/// The texture slots of a kernel of OpenCL mode's 1D images (`RuntimeFact::OpenClLineTexture`), -/// read by the kernel, at which `shape` binds a 1D texture for a 1D image or a 1D array texture -/// for a 1D array image, where Apple's OpenCL binds a 2D texture of height 1: the plan's -/// `VariantKey::open_cl_lines`, under which the kernel declares each as that 1D texture. Any -/// other texture bound there (the 2D one Apple's OpenCL binds among them) binds as the slot -/// declares it. The base declares a 1D image's slot 2D (`TextureType::Type2D`, `Type2DArray`), -/// the variant 1D, of the same arrayness, so the variant's plan for the same shape states the -/// same key. -pub(crate) fn open_cl_line_variant( - dependencies: &[RuntimeDependency], - slots: &BTreeMap, - shape: &BindShape, -) -> std::collections::BTreeSet { - use metal::TextureType as T; - let arrayed = |t: T| matches!(t, T::Type1DArray | T::Type2DArray); - dependencies - .iter() - .filter_map(|d| match d.fact { - RuntimeFact::OpenClLineTexture { slot } => Some(slot), - _ => None, - }) - .filter(|slot| { - let Some(SlotInterface::Texture(t)) = slots.get(slot) else { - return false; - }; - matches!(bound_texture(shape, *slot), Some(TextureShape::Texture { texture_type, .. }) - if matches!(texture_type, T::Type1D | T::Type1DArray) - && arrayed(*texture_type) == arrayed(t.texture_type)) - }) - .collect() -} - -/// The texture slots whose function reads a two-plane YCbCr texture only as its in-place form -/// reads it (`RuntimeFact::YCbCrInPlace`) at which `shape` binds a texture whose planes are read -/// in place (`TextureShape::Texture::ycbcr_in_place`), and each runtime sampler the function -/// samples the slot through states a filter the form reads ([`in_place_word`]): the plan's -/// `VariantKey::ycbcr_in_place`. Any other slot binds the texture's image. The variant's compile -/// states the same facts, so its plan for the same shape states the same key. -pub(crate) fn ycbcr_in_place_variant( - dependencies: &[RuntimeDependency], - shape: &BindShape, -) -> std::collections::BTreeSet { - dependencies - .iter() - .filter_map(|d| match d.fact { - RuntimeFact::YCbCrInPlace { slot, samplers, .. } => Some((slot, samplers)), - _ => None, - }) - .filter(|&(slot, samplers)| { - let in_place = matches!( - bound_texture(shape, slot), - Some(TextureShape::Texture { - ycbcr_in_place: true, - .. - }) - ); - let stage = shape.stages.get(&slot.stage); - let words = (0..32).filter(|n| samplers >> n & 1 != 0).map(|n| { - stage - .and_then(|s| s.samplers.get(&n)) - .map_or(0, |s| s.word.0) - }); - in_place && words.into_iter().all(in_place_word) - }) - .map(|(slot, _)| slot) - .collect() -} - -/// The texture-buffer slots whose function reads the texture buffer bound there through its parts -/// (`RuntimeFact::TexelBufferParts`) at which `shape` binds a texture buffer of more texels than -/// one view holds (`TextureShape::Buffer::parts` past 1), each with those parts: the plan's -/// `VariantKey::texel_buffer_parts` (`bind::texel_parts`). A texture buffer one view holds adds -/// nothing, so its draws keep their key; any other slot binds one view, which -/// `maxTexelBufferElements` bounds. The variant's compile states the same facts, so its plan for -/// the same shape states the same key. -pub(crate) fn texel_buffer_parts_variant( - dependencies: &[RuntimeDependency], - shape: &BindShape, -) -> BTreeMap { - dependencies - .iter() - .filter_map(|d| match d.fact { - RuntimeFact::TexelBufferParts { slot } => Some(slot), - _ => None, - }) - .filter_map(|slot| match bound_texture(shape, slot) { - Some(&TextureShape::Buffer { parts, .. }) if parts > 1 => Some((slot, parts)), - _ => None, - }) - .collect() -} - -/// The slots of `in_place` (the plan's `VariantKey::ycbcr_in_place`) whose function's every sample -/// the device's own sampler Y′CbCr conversion takes (`RuntimeFact::YCbCrInPlace`'s `device`), at -/// which `shape` binds a texture whose planes are also held as an image it samples -/// (`TextureShape::Texture::ycbcr_planes_sampler`), and each runtime sampler the function samples -/// the slot through addresses no border on either plane axis ([`planes_word`]), each with that -/// conversion: the plan's `VariantKey::ycbcr_planes_sampled`. The variant's compile states the -/// same facts, so its plan for the same shape states the same key. -pub(crate) fn ycbcr_planes_sampled_variant( - dependencies: &[RuntimeDependency], - shape: &BindShape, - in_place: &std::collections::BTreeSet, -) -> BTreeMap { - dependencies - .iter() - .filter_map(|d| match d.fact { - RuntimeFact::YCbCrInPlace { - slot, - samplers, - device: true, - } if in_place.contains(&slot) => Some((slot, samplers)), - _ => None, - }) - .filter_map(|(slot, samplers)| { - let sampler = match bound_texture(shape, slot) { - Some(&TextureShape::Texture { - ycbcr_planes_sampler: Some(sampler), - .. - }) => sampler, - _ => return None, - }; - let stage = shape.stages.get(&slot.stage); - let mut words = (0..32).filter(|n| samplers >> n & 1 != 0).map(|n| { - stage - .and_then(|s| s.samplers.get(&n)) - .map_or(0, |s| s.word.0) - }); - words.all(planes_word).then_some((slot, sampler)) - }) - .collect() -} - -/// Whether a runtime sampler of word `word` samples a two-plane YCbCr texture in a way the device's -/// own sampler Y′CbCr conversion of its planes' image takes: no clamp-to-zero or border color on -/// the `s` or `t` axis, which a 4:2:0 texture reads as the border where that sampler clamps to the -/// edge (every other mode a 4:2:0 texture samples as clamp-to-edge). Its filter and coordinate -/// space are the function's to apply. -pub(crate) fn planes_word(word: u32) -> bool { - use crate::metal::sampler::SamplerWord; - use crate::metal::SamplerAddressMode as M; - let border = [M::ClampToZero.as_raw(), M::ClampToBorderColor.as_raw()]; - (0..2).all(|axis| { - let mode = (word & SamplerWord::ADDRESS[axis]) >> SamplerWord::ADDRESS_SHIFT[axis]; - !border.contains(&mode) - }) -} - -/// Whether a runtime sampler of word `word` samples a two-plane YCbCr texture in a way its -/// in-place form reads: one filter for minification and magnification (nearest or linear), no -/// anisotropy, no cubic filter, no comparison and the weighted-average reduction. Its mip filter -/// and level clamps read the texture's one level, as Metal's sample of it reads it whatever its -/// mip filter (`lower::sampler::in_place`); every address mode, border color and coordinate -/// space is the form's to address. An unbound slot's word is 0, a nearest sampler's. -pub(crate) fn in_place_word(word: u32) -> bool { - use crate::metal::sampler::SamplerWord; - let filter = word & (SamplerWord::MIN_LINEAR | SamplerWord::MAG_LINEAR); - let one_filter = filter == 0 || filter == SamplerWord::LINEAR; - let other = SamplerWord::CUBIC - | SamplerWord::ANISOTROPIC - | SamplerWord::COMPARE - | SamplerWord::REDUCTION; - one_filter && word & other == 0 -} - -/// The texture slots a constexpr sampler samples (`RuntimeFact::ConstexprSampled`) at which -/// `shape` binds a texture whose address-mode map changes a mode the slot's constexpr samplers -/// state, each with that map restricted to those modes (every other mode to itself): the plan's -/// `VariantKey::address_maps`. A texture whose map keeps them, every ordinary texture's among -/// them, adds nothing, so its draws keep their key; textures whose maps agree on them share a -/// variant. The variant's compile states the same facts, so its plan for the same shape states -/// the same key. -pub(crate) fn address_map_variant( - dependencies: &[RuntimeDependency], - shape: &BindShape, -) -> BTreeMap { - let mut out = BTreeMap::new(); - for d in dependencies { - let RuntimeFact::ConstexprSampled { slot, modes } = d.fact else { - continue; - }; - let Some(&TextureShape::Texture { address_modes, .. }) = bound_texture(shape, slot) else { - continue; - }; - let stated = out - .entry(slot) - .or_insert(metal::sampler::AddressModeMap::IDENTITY); - for mode in modes { - *stated = stated.with(mode, address_modes.mode(mode)); - } - } - out.retain(|_, map| !map.is_identity()); - out -} - -/// The runtime sampler slots whose function samples through them (`RuntimeFact::CubicSampler`) -/// at which `shape` binds a sampler whose min or mag filter is `Cubic`, each with the bound word -/// masked by `SamplerWord::CUBIC_STATE`: the plan's `VariantKey::cubic_samplers`. Metal samples -/// through such a sampler with its bicubic filter of that state. The variant's -/// compile states the same facts, so its plan for the same shape states the same key. A bound -/// word whose state the bicubic filter is not measured under, whatever the function samples -/// (`metal::bicubic::runtime_cubic_measured`: a mip filter, anisotropy, another reduction), is -/// `NotImplemented(SamplerBicubicFilter)` here, as the variant's compile would refuse it: the -/// draw is refused before any variant is compiled for it. -pub(crate) fn cubic_variant( - dependencies: &[RuntimeDependency], - shape: &BindShape, -) -> Result, BindError> { - use crate::metal::sampler::SamplerWord; - dependencies - .iter() - .filter_map(|d| match d.fact { - RuntimeFact::CubicSampler { slot } => Some(slot), - _ => None, - }) - .filter_map(|slot| { - let bound = shape - .stages - .get(&slot.stage) - .and_then(|s| s.samplers.get(&slot.index))?; - let word = bound.word.0 & SamplerWord::CUBIC_STATE; - bound.shape.cubic.then( - || match crate::metal::bicubic::runtime_cubic_measured(word) { - true => Ok((slot, word)), - false => Err(BindError::Unsupported(Unsupported::not_implemented( - Feature::SamplerBicubicFilter, - ))), - }, - ) - }) - .collect() -} - -/// The runtime sampler slots whose samples Metal's anisotropic filter, emulated, reaches -/// (`RuntimeFact::AnisotropicSampler`) at which `shape` binds a sampler whose word states -/// anisotropy (`SamplerWord::ANISOTROPIC`, `maxAnisotropy` above 1): the plan's -/// `VariantKey::anisotropic_samplers`. A function compiled without a slot named there takes the -/// plain sample at it, which is Metal's only where the bound word states no anisotropy, so the -/// variant names every such slot the word of whose bound sampler states it. The variant's compile -/// states the same facts, so its plan for the same shape states the same key. -pub(crate) fn anisotropic_variant( - dependencies: &[RuntimeDependency], - shape: &BindShape, -) -> std::collections::BTreeSet { - use crate::metal::sampler::SamplerWord; - dependencies - .iter() - .filter_map(|d| match d.fact { - RuntimeFact::AnisotropicSampler { slot } => Some(slot), - _ => None, - }) - .filter(|slot| { - shape - .stages - .get(&slot.stage) - .and_then(|s| s.samplers.get(&slot.index)) - .is_some_and(|bound| bound.word.0 & SamplerWord::ANISOTROPIC != 0) - }) - .collect() -} - -/// The texture `shape` binds at `slot`. -fn bound_texture(shape: &BindShape, slot: SlotRef) -> Option<&TextureShape> { - shape - .stages - .get(&slot.stage) - .and_then(|s| s.textures.get(&slot.index)) -} - -/// Check every slot whose function observes the residency of its accesses -/// (`RuntimeFact::SparseTexture`). A texture that is not sparse is resident everywhere, so its word -/// is answered on every device. A sparse one needs the module's tile-map arm (`tile_map`, on every -/// profile where the slot has one) or its sparse arm (`sparse_arm`, compiled only where the profile -/// enables `shaderResourceResidency` and the slot has no tile map). A slot the function writes -/// drops its writes to a sparse texture under the same specialization, as Metal does -/// (`RuntimeFact::SparseTextureWrites`). A sparse texture is refused, `Unsupported{SparseTexture { -/// slot }}`: -/// - `NotRepresentable` at a slot the function updates by a texture atomic, whose answer on Metal -/// is not deterministic; -/// - at a slot of observed residency without either arm, naming `shaderResourceResidency` where -/// the device lacks it (an access the tile map does not answer, which the device's residency -/// would), and `NotImplemented` where the device has it but the slot's accesses have no sparse -/// form (a bicubic sample). -/// -/// This is the shader's side only: the sparse arm reports the residency of the Vulkan image -/// bound and the tile-map arm that of the tile map bound, and that they mirror Metal's tile -/// mappings is the consumer's contract (`docs/API.md`; the profile does not describe sparse -/// binding). -pub(crate) fn check_sparse_textures( - dependencies: &[RuntimeDependency], - profile: &DeviceProfile, - shape: &BindShape, -) -> Result<(), BindError> { - for d in dependencies { - if let RuntimeFact::SparseTextureWrites { slot, atomic: true } = d.fact { - if sparse_texture(shape, slot) != 0 { - let feature = Feature::SparseTexture { slot }; - return Err(BindError::Unsupported(Unsupported::not_representable( - feature, - ))); - } - } - } - for d in dependencies { - let RuntimeFact::SparseTexture { - slot, - sparse_arm, - tile_map, - } = d.fact - else { - continue; - }; - if sparse_arm || tile_map || sparse_texture(shape, slot) == 0 { - continue; - } - let residency = profile - .fields() - .enabled - .features - .contains(&VkFeature::ShaderResourceResidency); - let feature = Feature::SparseTexture { slot }; - return Err(BindError::Unsupported(if residency { - Unsupported::not_implemented(feature) - } else { - Unsupported::needs( - feature, - Capability::Feature(VkFeature::ShaderResourceResidency), - ) - })); - } - Ok(()) -} - -/// Whether every range of an allocation of length class `class` fits `max_range`: its padded -/// length is below `2^class` (`BindShape` length class). -pub(crate) fn class_fits(class: u8, max_range: u64) -> bool { - (1u128 << class.min(127)) - 1 <= u128::from(max_range) -} - -/// The slots a `BufferRangeLimit` variant must move to device addresses for this shape: every slot -/// whose fact the profile honors by `Variant` and whose bound buffer's length class does not prove -/// that its range fits the view's limit. A slot already in device-address form (the variant's own -/// pipeline) is listed as well, so planning the variant's pipeline with the same shape gives the -/// same key (a fixed point). Profile F honors the fact at instantiation (`DescriptorRangeExceeded`, -/// exact) and needs no variant. -pub(crate) fn psb_variant( - dependencies: &[RuntimeDependency], - buffers: &[PlannedBuffer], - profile: &DeviceProfile, -) -> std::collections::BTreeSet { - let mut out = std::collections::BTreeSet::new(); - for d in dependencies { - let RuntimeFact::BufferRangeLimit { slot } = d.fact else { - continue; - }; - let large = buffers - .iter() - .any(|b| b.slot == slot && range_variant(slot, b.bound, profile)); - if large { - out.insert(slot); - } - } - out -} - -/// Whether a slot with the `BufferRangeLimit` fact bound as `bound` joins the variant's -/// device-address slots: the profile honors the fact by `Variant` and the bound buffer's length -/// class does not prove that its range fits `maxStorageBufferRange`. -pub(crate) fn range_variant(slot: SlotRef, bound: BoundKind, profile: &DeviceProfile) -> bool { - let storage = u64::from(profile.fields().limits.max_storage_buffer_range); - mechanism(&RuntimeFact::BufferRangeLimit { slot }, profile) == Mechanism::Variant - && matches!(bound, BoundKind::Buffer { length_class, .. } if !class_fits(length_class, storage)) -} - -/// The `uses` entry of a bound buffer slot: its proven access, `Storage`, `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: AccessClass::Storage, - stages, - range: match b.window { - Window::Bounded { start, len } if start >= 0 => Some(ByteRange { - offset: start as u64, - len, - }), - _ => None, - }, - } -} - -/// The `uses` of the used resources a pipeline can reach (the handback): buffers and heaps when a -/// function reads the resident root table (`pointer`), textures and heaps when one resolves handles -/// (`handle`). The access is the guest's declared `MTLResourceUsage` (`Read` and `Sample` read, -/// `Write` writes; no usage is `READ_WRITE`), since nothing proves a narrower one, but in the -/// stages whose function writes no memory: there a resource the usage lets the function write is -/// read, in a use of its own, as such a function stores to no buffer or texture and updates none -/// atomically (`StageInterface::writes_memory`). `writers` holds the pipeline stages whose function -/// may write memory. `stages` maps a used resource's render stages to the pipeline stages that -/// reach it (a compute plan maps every resource to `COMPUTE_SHADER`), and a resource reaching none -/// is not listed. -pub(crate) fn used_uses( - used: &BTreeMap, - pointer: bool, - handle: bool, - stages: impl Fn(metal::RenderStages) -> vk::PipelineStageFlags2, - writers: vk::PipelineStageFlags2, -) -> Vec { - let mut out = Vec::new(); - for (&token, u) in used { - let reachable = match u.class { - UsedClass::Buffer => pointer, - UsedClass::Texture(_) => handle, - UsedClass::Heap => pointer || handle, - }; - let stages = stages(u.stages); - if !reachable || stages.is_empty() { - continue; - } - let read = u - .usage - .intersects(metal::ResourceUsage::READ | metal::ResourceUsage::SAMPLE); - let write = u.usage.contains(metal::ResourceUsage::WRITE); - let access = match (read, write) { - (false, false) => AccessSet::READ_WRITE, - (read, write) => AccessSet { read, write }, - }; - let class = match u.class { - UsedClass::Texture(_) if write => AccessClass::StorageImage, - UsedClass::Texture(_) => AccessClass::Sampled, - UsedClass::Buffer | UsedClass::Heap => AccessClass::Storage, - }; - let (writing, reading) = match access.write { - true => ( - stages.intersection(writers), - vk::PipelineStageFlags2::from_raw(stages.as_raw() & !writers.as_raw()), - ), - false => (stages, vk::PipelineStageFlags2::empty()), - }; - for (stages, access) in [(writing, access), (reading, AccessSet::READ)] { - if !stages.is_empty() { - out.push(ResourceUse { - resource: UseTarget::Used(token), - access, - class, - stages, - range: None, - }); - } - } - } - out -} - -#[cfg(test)] -mod tests; diff --git a/crates/metal2vulkan/src/bind/plan/slots/tests.rs b/crates/metal2vulkan/src/bind/plan/slots/tests.rs deleted file mode 100644 index 642f486c0..000000000 --- a/crates/metal2vulkan/src/bind/plan/slots/tests.rs +++ /dev/null @@ -1,872 +0,0 @@ -//! Length classes, the `BufferRangeLimit` variant, and the uses of used resources. - -use super::*; -use crate::bind::state::{ - length_class, BindState, BoundBuffer, BufferRanges, ResourceClass, StageShape, StageTable, - UsedResource, -}; -use crate::device::profile::BufferAccess; -use crate::pipeline::facts::Mechanism; -use crate::pipeline::interface::BufferKind; -use crate::pipeline::sym::Stage; -use crate::spirv::testing::committed_profiles; - -fn slot(index: u32) -> SlotRef { - SlotRef { - stage: Stage::Kernel, - class: SlotClass::Buffer, - index, - } -} - -/// The class bounds the padded length from above and is the smallest such power of two. -#[test] -fn a_length_class_bounds_the_padded_length() { - for length in [ - 0u64, - 1, - 15, - 16, - 17, - 255, - 256, - 1 << 27, - (1 << 27) + 1, - u64::MAX, - ] { - let c = length_class(length); - let padded = u128::from(length).next_multiple_of(16); - assert!(padded < 1u128 << c, "{length}: class {c}"); - if padded > 0 { - assert!( - padded >= 1u128 << (c - 1), - "{length}: class {c} is not the smallest" - ); - } - } - assert_eq!(length_class(0), 0); - // A class proves a range fits exactly when every padded length below `2^class` does. - let limit = (1u64 << 27) - 1; - assert!(class_fits(length_class((1 << 27) - 16), limit)); - assert!(!class_fits(length_class(1 << 27), limit)); - assert!(class_fits( - length_class(u64::from(u32::MAX) - 15), - u64::from(u32::MAX) - )); -} - -fn planned(index: u32, bound: BoundKind, form: BufferForm) -> PlannedBuffer { - PlannedBuffer { - slot: slot(index), - window: Window::Whole, - form, - access: AccessSet::READ, - binding: None, - alignment: 16, - max_range: 0, - bound, - } -} - -/// On Profile A a large bound buffer under a `BufferRangeLimit` fact needs the variant, in either -/// form (a fixed point); a small one, an unbound slot, or a slot without the fact does not. -/// Profile F (below the runtime's floor, [`PROFILE_F`](crate::pipeline::testing::PROFILE_F)) -/// honors the fact at instantiation and never asks for a variant. -#[test] -fn a_large_buffer_needs_the_device_address_variant_on_profile_a_only() { - let deps = [0, 1, 2, 3].map(|n| RuntimeDependency { - fact: RuntimeFact::BufferRangeLimit { slot: slot(n) }, - mechanism: Mechanism::Variant, - }); - let storage = BufferForm::Descriptor; - let mut seen = [false; 2]; - let mut profiles = committed_profiles().expect("profiles"); - let f = crate::pipeline::testing::device_f(crate::device::DevicePolicy::RESIDENT_TABLES) - .expect("Profile F"); - profiles.push(( - crate::pipeline::testing::PROFILE_F.to_string(), - f.profile().clone(), - )); - for (stem, p) in profiles { - let max = u64::from(p.fields().limits.max_storage_buffer_range); - let big = length_class(max.saturating_add(1)); - let small = length_class(max / 4); - let buffers = [ - planned( - 0, - BoundKind::Buffer { - device_address: true, - length_class: big, - }, - storage, - ), - planned( - 1, - BoundKind::Buffer { - device_address: true, - length_class: big, - }, - BufferForm::Psb, - ), - planned( - 2, - BoundKind::Buffer { - device_address: true, - length_class: small, - }, - storage, - ), - planned(3, BoundKind::Unbound, storage), - planned( - 4, - BoundKind::Buffer { - device_address: true, - length_class: big, - }, - storage, - ), - ]; - let got = psb_variant(&deps, &buffers, &p); - match p.fields().buffer_access { - BufferAccess::Addressed => { - seen[0] = true; - assert_eq!(got, [slot(0), slot(1)].into(), "{stem}"); - } - BufferAccess::Floor => { - seen[1] = true; - assert!(got.is_empty(), "{stem}"); - } - } - } - assert_eq!(seen, [true, true], "both profile kinds are checked"); -} - -/// Used resources reach a plan's `uses` exactly when a function can reach them, with the guest's -/// declared usage, and the shape unions a token listed twice. -#[test] -fn used_resources_are_listed_when_the_pipeline_reaches_them() { - let mut state = BindState::default(); - let mut buffer = UsedResource::new(ResourceClass::Buffer, 1); - buffer.usage = metal::ResourceUsage::READ; - let mut again = buffer; - again.usage = metal::ResourceUsage::WRITE; - again.stages = metal::RenderStages::FRAGMENT; - let mut heap = UsedResource::new(ResourceClass::Heap, 2); - heap.stages = metal::RenderStages::VERTEX; - let mut texture = UsedResource::new( - ResourceClass::Texture(crate::bind::state::TextureFacts::new( - metal::TextureType::Type2D, - metal::PixelFormat::RGBA8Unorm, - )), - 3, - ); - texture.usage = metal::ResourceUsage::SAMPLE; - state.used_resources = vec![buffer, heap, texture, again]; - let shape = state.shape(); - assert_eq!( - shape.used[&1].usage, - metal::ResourceUsage::READ | metal::ResourceUsage::WRITE - ); - let compute = |_| vk::PipelineStageFlags2::COMPUTE_SHADER; - // The kernel may write memory. - let all = vk::PipelineStageFlags2::COMPUTE_SHADER; - let tokens = |uses: &[ResourceUse]| -> Vec<(UseTarget, AccessSet, AccessClass)> { - uses.iter() - .map(|u| (u.resource, u.access, u.class)) - .collect() - }; - assert!(used_uses(&shape.used, false, false, compute, all).is_empty()); - assert_eq!( - tokens(&used_uses(&shape.used, true, false, compute, all)), - vec![ - ( - UseTarget::Used(1), - AccessSet::READ_WRITE, - AccessClass::Storage - ), - ( - UseTarget::Used(2), - AccessSet::READ_WRITE, - AccessClass::Storage - ), - ] - ); - assert_eq!( - tokens(&used_uses(&shape.used, false, true, compute, all)), - vec![ - ( - UseTarget::Used(2), - AccessSet::READ_WRITE, - AccessClass::Storage - ), - (UseTarget::Used(3), AccessSet::READ, AccessClass::Sampled), - ] - ); - // A render plan lists a resource only in the stages it is used in. - let vertex = vk::PipelineStageFlags2::VERTEX_SHADER; - let vertex_only = |s: metal::RenderStages| { - if s.contains(metal::RenderStages::VERTEX) { - vk::PipelineStageFlags2::VERTEX_SHADER - } else { - vk::PipelineStageFlags2::empty() - } - }; - assert_eq!( - tokens(&used_uses(&shape.used, true, true, vertex_only, vertex)), - vec![( - UseTarget::Used(2), - AccessSet::READ_WRITE, - AccessClass::Storage - )] - ); -} - -/// A used resource the usage lets a function write is written only in the stages whose function -/// may write memory, and read in the others: a draw whose vertex function stores nothing reads a -/// buffer an earlier compute encoder made resident for writing, as its fragment function, which -/// stores, writes it. One only read keeps a single use; one no stage writes is read everywhere. -#[test] -fn used_resources_are_written_only_by_stages_that_write_memory() { - let mut state = BindState::default(); - let mut written = UsedResource::new(ResourceClass::Buffer, 1); - written.usage = metal::ResourceUsage::WRITE; - written.stages = metal::RenderStages::VERTEX.union(metal::RenderStages::FRAGMENT); - let mut read = UsedResource::new(ResourceClass::Buffer, 2); - read.usage = metal::ResourceUsage::READ; - read.stages = written.stages; - state.used_resources = vec![written, read]; - let shape = state.shape(); - let vertex = vk::PipelineStageFlags2::VERTEX_SHADER; - let fragment = vk::PipelineStageFlags2::FRAGMENT_SHADER; - let reach = |s: metal::RenderStages| { - let mut f = vk::PipelineStageFlags2::empty(); - if s.contains(metal::RenderStages::VERTEX) { - f |= vertex; - } - if s.contains(metal::RenderStages::FRAGMENT) { - f |= fragment; - } - f - }; - let listed = |writers| -> Vec<(UseTarget, AccessSet, vk::PipelineStageFlags2)> { - used_uses(&shape.used, true, false, reach, writers) - .iter() - .map(|u| (u.resource, u.access, u.stages)) - .collect() - }; - let write = AccessSet { - read: false, - write: true, - }; - assert_eq!( - listed(fragment), - vec![ - (UseTarget::Used(1), write, fragment), - (UseTarget::Used(1), AccessSet::READ, vertex), - (UseTarget::Used(2), AccessSet::READ, vertex | fragment), - ] - ); - assert_eq!( - listed(vk::PipelineStageFlags2::empty()), - vec![ - (UseTarget::Used(1), AccessSet::READ, vertex | fragment), - (UseTarget::Used(2), AccessSet::READ, vertex | fragment), - ] - ); - assert_eq!( - listed(vertex | fragment), - vec![ - (UseTarget::Used(1), write, vertex | fragment), - (UseTarget::Used(2), AccessSet::READ, vertex | fragment), - ] - ); -} - -/// A buffer range limit tells a buffer's length class apart as far as a plan reads it -/// (`BufferRanges::length_class`), under a 4 GiB limit (an RX 7900 XTX's), limits of 128 MiB, -/// 64 KiB and 16 KiB, and none (the default, every class its own): the class a buffer's shape -/// states of each length answers `class_fits` against the limit as the exact class does (all a -/// plan reads of it: `range_variant`), still bounds the padded length from above, and is the exact -/// one under none; and instantiation's kind check (`instantiate::bound_buffer`) takes a binding of -/// each length for the kind a plan of another length stored exactly where the two classes are -/// one, which is only where their exact classes answer the limit alike. -#[test] -fn length_classes_are_told_apart_as_far_as_a_plan_reads_them() { - let mut lengths = vec![0u64, 1, 15, 16, 17, u64::MAX]; - for bit in 4..64 { - lengths.extend([(1u64 << bit) - 1, 1 << bit, (1 << bit) + 1]); - } - let limits = [ - BufferRanges::default(), - BufferRanges { storage: u32::MAX }, - BufferRanges { storage: 1 << 27 }, - BufferRanges { storage: 1 << 16 }, - BufferRanges { storage: 1 << 14 }, - ]; - for ranges in limits { - let fits = |class| class_fits(class, u64::from(ranges.storage)); - let states: Vec = (lengths.iter()) - .map(|&length| { - let mut table = StageTable { - buffer_ranges: ranges, - ..StageTable::default() - }; - let bound = BoundBuffer::Buffer { - gpu_address: 0x1_0000, - length, - offset: 0, - device_address: Some(0x2_0000), - attribute_stride: None, - }; - table.buffers.insert(0, bound); - let mut state = BindState::default(); - state.stages.insert(Stage::Kernel, table); - state - }) - .collect(); - for (&a, state) in lengths.iter().zip(&states) { - let (exact, class) = (length_class(a), ranges.length_class(a)); - let what = format!("{ranges:?}, {a} bytes"); - assert_eq!( - fits(class), - fits(exact), - "{what}: class {class}, exact {exact}" - ); - let padded = u128::from(a).next_multiple_of(16); - assert!(padded < 1u128 << class, "{what}: class {class}"); - if ranges == BufferRanges::default() { - assert_eq!(class, exact, "{what}"); - } - let shape = state.shape(); - let expected = BoundKind::of(shape.stages[&Stage::Kernel].buffers.get(&0)); - for (&b, other) in lengths.iter().zip(&states) { - let took = crate::bind::instantiate::bound_buffer(other, slot(0), expected).is_ok(); - assert_eq!( - took, - ranges.length_class(b) == class, - "{what}: a binding of {b} bytes for its kind" - ); - if took { - assert_eq!( - fits(length_class(b)), - fits(exact), - "{what}: {b} bytes alike" - ); - } - } - } - } - // Under a 4 GiB limit every length up to 4 GiB is one class, past it each its own. - let ranges = limits[1]; - assert_eq!(ranges.length_class(1), ranges.length_class((1 << 32) - 16)); - assert_ne!(ranges.length_class(1), ranges.length_class(1 << 32)); - assert_ne!(ranges.length_class(1 << 32), ranges.length_class(1 << 33)); -} - -/// A buffer bound by shape and state agree on the bound kind, including the length class. -#[test] -fn the_bound_kind_carries_the_length_class() { - let b = BoundBuffer::Buffer { - length: 100, - offset: 4, - gpu_address: 0, - device_address: Some(8), - attribute_stride: None, - }; - assert_eq!( - BoundKind::of(Some(&b.shape(BufferRanges::default()))), - BoundKind::Buffer { - device_address: true, - length_class: 7 - } - ); - assert_eq!(BoundKind::of(None), BoundKind::Unbound); -} - -#[test] -fn slots_beyond_the_metal_tables_are_refused() { - let mut shape = BindShape::default(); - let mut s = StageShape::default(); - s.buffers.insert( - 30, - BufferShape::Bytes { - attribute_stride: None, - }, - ); - shape.stages.insert(Stage::Kernel, s.clone()); - assert_eq!(check_slots(&shape), Ok(())); - s.buffers.insert( - 31, - BufferShape::Bytes { - attribute_stride: None, - }, - ); - shape.stages.insert(Stage::Kernel, s); - assert_eq!( - check_slots(&shape), - Err(BindError::SlotOutOfRange { - slot: SlotRef { - stage: Stage::Kernel, - class: SlotClass::Buffer, - index: 31 - } - }) - ); - let mut s = StageShape::default(); - s.threadgroup_lengths.insert(31, 16); - shape.stages.insert(Stage::Kernel, s); - assert!(check_slots(&shape).is_err()); -} - -/// On every committed profile a storage view's descriptor base is aligned to -/// `max(minStorageBufferOffsetAlignment, 16)`, so whatever the bind offset and window, every byte -/// of the range sits at a descriptor offset congruent to its allocation offset modulo 16: a 16-byte -/// leaf whose Metal address is a multiple of 16 is one `uvec4` element of the view. -#[test] -fn descriptor_bases_are_sixteen_aligned_on_every_profile() { - let bindings: BTreeMap<_, _> = [(BindingSource::Buffer(slot(0)), (0, 0))].into(); - let shape = BufferShape::Buffer { - device_address: false, - length_class: length_class(4096), - attribute_stride: None, - offset_alignment: 4, - }; - for (stem, p) in committed_profiles().expect("profiles") { - let limits = &p.fields().limits; - let min = limits.min_storage_buffer_offset_alignment; - let b = BufferSlot { - access: AccessSet::READ, - window: Window::Whole, - form: BufferForm::Descriptor, - kind: BufferKind::Buffer, - }; - let pb = plan_buffer((slot(0), &b, Some(&shape)), false, limits, &bindings) - .unwrap_or_else(|e| panic!("{stem}: {e:?}")); - assert_eq!(pb.alignment, min.max(16), "{stem}"); - for bind_offset in (0..64).step_by(4) { - for window in [ - Window::Whole, - Window::Bounded { start: 0, len: 64 }, - Window::Bounded { start: 4, len: 28 }, - Window::Bounded { start: 52, len: 16 }, - Window::Bounded { start: -8, len: 40 }, - ] { - let (range, residual) = crate::bind::instantiate::descriptor_range( - bind_offset, - 4096, - window, - pb.alignment, - u64::MAX, - ) - .unwrap_or_else(|e| panic!("{stem}: {e:?}")); - assert_eq!(range.offset % 16, 0, "{stem} {bind_offset}"); - // Byte `m` from the bind offset is byte `residual + m` of the range. - assert_eq!( - u64::from(residual) % 16, - bind_offset % 16, - "{stem} {bind_offset} {window:?}" - ); - } - } - } -} - -/// 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 -/// `shaderResourceResidency` where the profile lacks it and `NotImplemented` where it has it (an -/// access without a sparse form). A slot the function writes binds a sparse texture (its writes -/// dropped under the specialization), and one it updates atomically refuses it as -/// `NotRepresentable` on every profile. -#[test] -fn a_sparse_texture_needs_the_slots_sparse_arm() { - use crate::bind::state::TextureFacts; - let at = SlotRef { - stage: Stage::Kernel, - class: SlotClass::Texture, - index: 2, - }; - let shape = |sparse: Option| { - let mut s = BindShape::default(); - let mut stage = StageShape::default(); - if let Some(sparse) = sparse { - let mut facts = - TextureFacts::new(metal::TextureType::Type2D, metal::PixelFormat::RGBA8Unorm); - facts.sparse = sparse; - stage.textures.insert(2, facts.shape()); - } - s.stages.insert(Stage::Kernel, stage); - s - }; - let arms = |sparse_arm: bool, tile_map: bool| { - vec![RuntimeDependency { - fact: RuntimeFact::SparseTexture { - slot: at, - sparse_arm, - tile_map, - }, - mechanism: if sparse_arm || tile_map { - Mechanism::Specialization - } else { - Mechanism::PlanTimeCheck - }, - }] - }; - let deps = |sparse_arm: bool| arms(sparse_arm, false); - let writes = |atomic: bool| { - vec![RuntimeDependency { - fact: RuntimeFact::SparseTextureWrites { slot: at, atomic }, - mechanism: if atomic { - Mechanism::PlanTimeCheck - } else { - Mechanism::Specialization - }, - }] - }; - assert_eq!(sparse_texture(&shape(Some(true)), at), 1); - assert_eq!(sparse_texture(&shape(Some(false)), at), 0); - assert_eq!(sparse_texture(&shape(None), at), 0); - let mut seen = [0; 2]; - for (stem, p) in committed_profiles().expect("profiles") { - for bound in [None, Some(false)] { - for arm in [false, true] { - check_sparse_textures(&deps(arm), &p, &shape(bound)) - .unwrap_or_else(|e| panic!("{stem}: {bound:?} {arm}: {e}")); - } - } - check_sparse_textures(&deps(true), &p, &shape(Some(true))) - .unwrap_or_else(|e| panic!("{stem}: sparse arm: {e}")); - // A tile-map arm answers a sparse texture too. - check_sparse_textures(&arms(false, true), &p, &shape(Some(true))) - .unwrap_or_else(|e| panic!("{stem}: tile-map arm: {e}")); - let residency = p - .fields() - .enabled - .features - .contains(&VkFeature::ShaderResourceResidency); - let feature = Feature::SparseTexture { slot: at }; - let want = if residency { - Unsupported::not_implemented(feature) - } else { - Unsupported::needs( - feature, - Capability::Feature(VkFeature::ShaderResourceResidency), - ) - }; - match check_sparse_textures(&deps(false), &p, &shape(Some(true))) { - Err(BindError::Unsupported(u)) => assert_eq!(u, want, "{stem}"), - other => panic!("{stem}: {other:?}"), - } - // A written slot binds a sparse texture, its writes dropped; one updated atomically refuses - // it, since Metal's answer there is not deterministic. - for bound in [None, Some(false), Some(true)] { - check_sparse_textures(&writes(false), &p, &shape(bound)) - .unwrap_or_else(|e| panic!("{stem}: written, {bound:?}: {e}")); - } - for bound in [None, Some(false)] { - check_sparse_textures(&writes(true), &p, &shape(bound)) - .unwrap_or_else(|e| panic!("{stem}: atomic, {bound:?}: {e}")); - } - let mut atomic = deps(false); - atomic.extend(writes(true)); - for deps in [writes(true), atomic] { - match check_sparse_textures(&deps, &p, &shape(Some(true))) { - Err(BindError::Unsupported(u)) => { - let feature = Feature::SparseTexture { slot: at }; - assert_eq!(u, Unsupported::not_representable(feature), "{stem}") - } - other => panic!("{stem}: atomic: {other:?}"), - } - } - seen[usize::from(residency)] += 1; - } - assert!(seen[0] > 0 && seen[1] > 0, "{seen:?}"); -} - -/// A constexpr-sampled slot enters `VariantKey::address_maps` only where the bound texture's -/// address-mode map changes a mode the slot's constexpr samplers state, with the map restricted -/// to those modes: a draw of an ordinary texture, or of a mapped one whose map keeps those modes, -/// keeps its key, and textures whose maps agree on them share a variant. A slot no constexpr -/// sampler samples takes no map, whatever its texture's. -#[test] -fn only_a_map_that_moves_a_constexpr_mode_enters_the_variant() { - use crate::bind::state::TextureFacts; - use crate::metal::sampler::AddressModeMap; - use crate::metal::SamplerAddressMode as M; - let texture = |index| SlotRef { - stage: Stage::Kernel, - class: SlotClass::Texture, - index, - }; - let identity = AddressModeMap::IDENTITY; - let edges = identity.with(M::Repeat, M::ClampToEdge); - // Every mode to the edge, as a two-plane 4:2:0 texture reads. - let all_edges = [ - M::MirrorClampToEdge, - M::Repeat, - M::MirrorRepeat, - M::ClampToZero, - M::ClampToBorderColor, - ] - .into_iter() - .fold(identity, |map, mode| map.with(mode, M::ClampToEdge)); - let shape = |maps: [AddressModeMap; 2]| { - let mut s = BindShape::default(); - let mut stage = StageShape::default(); - for (index, map) in (0..).zip(maps) { - let mut facts = - TextureFacts::new(metal::TextureType::Type2D, metal::PixelFormat::RGBA8Unorm); - facts.address_modes = map; - stage.textures.insert(index, facts.shape()); - } - s.stages.insert(Stage::Kernel, stage); - s - }; - // Slot 0 is constexpr-sampled, by a repeat sampler and by one of `other` modes; slot 1 is - // not. - let deps = |other: Option| { - let sampled = |mode| RuntimeDependency { - fact: RuntimeFact::ConstexprSampled { - slot: texture(0), - modes: [mode; 3], - }, - mechanism: Mechanism::Variant, - }; - let mut deps = vec![sampled(M::Repeat)]; - deps.extend(other.map(sampled)); - deps - }; - let repeat = deps(None); - assert!(address_map_variant(&repeat, &shape([identity, identity])).is_empty()); - assert!(address_map_variant(&repeat, &shape([identity, edges])).is_empty()); - assert!(address_map_variant(&[], &shape([edges, edges])).is_empty()); - assert_eq!( - address_map_variant(&repeat, &shape([edges, identity])), - BTreeMap::from([(texture(0), edges)]) - ); - // The map restricted to the stated modes: one that sends every mode to the edge states the - // same variant as one that sends repeat there alone. - assert_eq!( - address_map_variant(&repeat, &shape([all_edges, identity])), - BTreeMap::from([(texture(0), edges)]) - ); - // A map that keeps every stated mode adds nothing: a clamp-to-edge sampler of a texture whose - // every mode reads the edge samples it as before. - let edge = vec![RuntimeDependency { - fact: RuntimeFact::ConstexprSampled { - slot: texture(0), - modes: [M::ClampToEdge; 3], - }, - mechanism: Mechanism::Variant, - }]; - assert!(address_map_variant(&edge, &shape([all_edges, identity])).is_empty()); - // Two samplers of the slot: the map on the modes of both. - assert_eq!( - address_map_variant(&deps(Some(M::ClampToZero)), &shape([all_edges, identity])), - BTreeMap::from([(texture(0), edges.with(M::ClampToZero, M::ClampToEdge))]) - ); - // A slot with no texture bound takes no map. - assert!(address_map_variant(&repeat, &BindShape::default()).is_empty()); -} - -/// A slot that states the in-place form enters `VariantKey::ycbcr_in_place` only where the bound -/// texture's planes are read in place and each runtime sampler the slot samples through states a -/// filter the form reads: one filter, no anisotropy, cubic filter, comparison or other reduction. -#[test] -fn the_in_place_variant_takes_a_slot_its_texture_and_samplers_read() { - use crate::bind::state::{BoundSampler, SamplerDescriptor, TextureFacts}; - use crate::bind::ycbcr_convert::{YCbCrCodes, YCbCrMatrix, YCbCrPlanes, YCbCrRange}; - use crate::bind::YCbCrInPlace; - use metal::{CompareFunction, SamplerMinMagFilter as F, SamplerReductionMode}; - let texture = |index| SlotRef { - stage: Stage::Kernel, - class: SlotClass::Texture, - index, - }; - let pf = metal::PixelFormat::YCBCR84202P; - let codes = metal::format::ycbcr_format(pf) - .and_then(YCbCrCodes::of) - .expect("codes"); - let planes = YCbCrPlanes::new( - [8, 4], - [0, 16], - [64, 16], - (YCbCrRange::Video, YCbCrMatrix::Bt709), - codes, - ); - // Slot 0 and 1 bind textures whose planes are read in place, slot 2 one whose are not. - let shape = |sampler: SamplerDescriptor| { - let mut stage = StageShape::default(); - for (index, in_place) in [(0, true), (1, true), (2, false)] { - let mut facts = TextureFacts::new(metal::TextureType::Type2D, pf); - if in_place { - facts.ycbcr_in_place = YCbCrInPlace::of(&planes); - } - stage.textures.insert(index, facts.shape()); - } - stage.samplers.insert(3, BoundSampler::new(sampler).shape()); - let mut s = BindShape::default(); - s.stages.insert(Stage::Kernel, stage); - s - }; - let fact = |slot, samplers| RuntimeDependency { - fact: RuntimeFact::YCbCrInPlace { - slot, - samplers, - device: true, - }, - mechanism: Mechanism::Variant, - }; - // Slot 0 samples through constexpr samplers alone, slot 1 also through `[[sampler(3)]]`. - let deps = [ - fact(texture(0), 0), - fact(texture(1), 1 << 3), - fact(texture(2), 0), - ]; - let linear = SamplerDescriptor { - min_filter: F::Linear, - mag_filter: F::Linear, - ..SamplerDescriptor::new() - }; - let both = std::collections::BTreeSet::from([texture(0), texture(1)]); - let s = shape(linear); - let in_place = ycbcr_in_place_variant(&deps, &s); - assert_eq!(in_place, both); - assert_eq!( - ycbcr_in_place_variant(&deps, &shape(SamplerDescriptor::new())), - both - ); - // A sampler the form does not read keeps slot 1 from it, not slot 0. - let unread = [ - SamplerDescriptor { - min_filter: F::Linear, - ..SamplerDescriptor::new() - }, - SamplerDescriptor { - max_anisotropy: 4, - ..linear - }, - SamplerDescriptor { - min_filter: F::Cubic, - mag_filter: F::Cubic, - ..SamplerDescriptor::new() - }, - SamplerDescriptor { - compare_function: CompareFunction::Less, - ..linear - }, - SamplerDescriptor { - reduction_mode: SamplerReductionMode::Minimum, - ..linear - }, - ]; - for sampler in unread { - assert_eq!( - ycbcr_in_place_variant(&deps, &shape(sampler)), - std::collections::BTreeSet::from([texture(0)]), - "{sampler:?}" - ); - } - // A stage that states no form takes none, whatever its textures. - assert!(ycbcr_in_place_variant(&[], &s).is_empty()); - // No texture's planes are held as an image the device samples: no slot samples one. - assert!(ycbcr_planes_sampled_variant(&deps, &s, &in_place).is_empty()); -} - -/// An in-place slot enters `VariantKey::ycbcr_planes_sampled` only where the bound texture's -/// planes are held as an image the device's conversion samples, the function's every sample is one -/// that sampler takes (the fact's `device`), and each runtime sampler it samples through addresses -/// no border on the plane axes. -#[test] -fn the_planes_image_variant_takes_a_slot_the_device_s_sampler_reads() { - use crate::bind::state::{BoundSampler, SamplerDescriptor, TextureFacts}; - use crate::bind::ycbcr_convert::{YCbCrCodes, YCbCrMatrix, YCbCrPlanes, YCbCrRange}; - use crate::bind::YCbCrInPlace; - use metal::SamplerAddressMode as M; - let texture = |index| SlotRef { - stage: Stage::Kernel, - class: SlotClass::Texture, - index, - }; - let pf = metal::PixelFormat::YCBCR84202P; - let codes = metal::format::ycbcr_format(pf) - .and_then(YCbCrCodes::of) - .expect("codes"); - let planes = YCbCrPlanes::new( - [8, 4], - [0, 16], - [64, 16], - (YCbCrRange::Full, YCbCrMatrix::Bt601), - codes, - ); - let words = YCbCrInPlace::of(&planes).expect("in place"); - // Slots 0 to 2 bind textures whose planes are held as an image, slot 3 one whose are not. - let shape = |sampler: SamplerDescriptor| { - let mut stage = StageShape::default(); - for index in 0..4 { - let mut facts = TextureFacts::new(metal::TextureType::Type2D, pf); - facts.ycbcr_in_place = Some(match index { - 3 => words, - _ => words.with_planes_image(), - }); - stage.textures.insert(index, facts.shape()); - } - stage.samplers.insert(3, BoundSampler::new(sampler).shape()); - let mut s = BindShape::default(); - s.stages.insert(Stage::Kernel, stage); - s - }; - let fact = |slot, samplers, device| RuntimeDependency { - fact: RuntimeFact::YCbCrInPlace { - slot, - samplers, - device, - }, - mechanism: Mechanism::Variant, - }; - // Slot 0 samples through constexpr samplers the device takes, slot 1 also through - // `[[sampler(3)]]`, slot 2 through a constexpr sampler it does not take. - let deps = [ - fact(texture(0), 0, true), - fact(texture(1), 1 << 3, true), - fact(texture(2), 0, false), - fact(texture(3), 0, true), - ]; - let edge = SamplerDescriptor::new(); - let s = shape(edge); - let in_place = ycbcr_in_place_variant(&deps, &s); - assert_eq!(in_place.len(), 4); - let sampler = words.sampler(); - assert_eq!( - ycbcr_planes_sampled_variant(&deps, &s, &in_place), - BTreeMap::from([(texture(0), sampler), (texture(1), sampler)]) - ); - // A runtime sampler that addresses a border on a plane axis keeps slot 1 from it; one on `r` - // does not. - for (mode, axis, taken) in [ - (M::ClampToZero, 0, false), - (M::ClampToBorderColor, 1, false), - (M::Repeat, 0, true), - (M::MirrorClampToEdge, 1, true), - (M::ClampToBorderColor, 2, true), - ] { - let mut sampler_state = edge; - match axis { - 0 => sampler_state.s_address_mode = mode, - 1 => sampler_state.t_address_mode = mode, - _ => sampler_state.r_address_mode = mode, - } - let s = shape(sampler_state); - let in_place = ycbcr_in_place_variant(&deps, &s); - let got = ycbcr_planes_sampled_variant(&deps, &s, &in_place); - assert_eq!( - got.contains_key(&texture(1)), - taken, - "{mode:?} on axis {axis}" - ); - assert!(got.contains_key(&texture(0)), "{mode:?} on axis {axis}"); - } - // A slot outside the in-place variant takes no image. - let none = std::collections::BTreeSet::new(); - assert!(ycbcr_planes_sampled_variant(&deps, &s, &none).is_empty()); -} diff --git a/crates/metal2vulkan/src/bind/rate_map.rs b/crates/metal2vulkan/src/bind/rate_map.rs index 414894c05..5852ed2d1 100644 --- a/crates/metal2vulkan/src/bind/rate_map.rs +++ b/crates/metal2vulkan/src/bind/rate_map.rs @@ -21,7 +21,7 @@ //! `float` arithmetic is the device's: it computes the shader's //! answers bit for bit on a device that reads `float` denormals as Metal does, and with the //! device's own denormals elsewhere (`PrecisionNote::DeviceDenormals`), as the SPIR-V interpreter -//! keeps them. The buffer is then bound like any other ([`BoundBuffer::Buffer`]). +//! keeps them. The buffer is then bound like any other. //! //! **Compiling a descriptor.** Metal leaves the compiled map to the device: a layer's quality //! samples "may be rounded up ... depending on hardware support". [`RasterizationRateMap::new`] @@ -59,8 +59,6 @@ //! //! **Rendering a rate-mapped pass** (`MTLRenderPassDescriptor.rasterizationRateMap`) is the //! consumer's. -//! -//! [`BoundBuffer::Buffer`]: crate::bind::BoundBuffer::Buffer use std::fmt; diff --git a/crates/metal2vulkan/src/bind/replay.rs b/crates/metal2vulkan/src/bind/replay.rs index 72de355b8..567af8b74 100644 --- a/crates/metal2vulkan/src/bind/replay.rs +++ b/crates/metal2vulkan/src/bind/replay.rs @@ -1,6 +1,6 @@ //! What a merged draw's vertex and fragment variants read (`merged`): the header of a merged draw, -//! its commands' `VkDrawIndirectCommand`s ([`DRAW_ARGUMENT_BYTES`]) and index entries -//! ([`DRAW_INDEX_ENTRY_BYTES`]), and the SPIR-V helpers its reads are built from, reaching memory +//! its commands' `VkDrawIndirectCommand`s (`merged::DRAW_ARGUMENT_BYTES`) and index entries +//! (`merged::DRAW_INDEX_ENTRY_BYTES`), and the SPIR-V helpers its reads are built from, reaching memory //! by device address (`bufferDeviceAddress`, `shaderInt64`). use crate::memory::roots; @@ -11,7 +11,6 @@ use crate::spirv::ir::{BinOp, ConvOp, MemAccess}; mod merged; pub(crate) use merged::{merged_fragment_table, merged_vertex, MergedVertex}; -pub use merged::{DRAW_ARGUMENT_BYTES, DRAW_INDEX_ENTRY_BYTES, MERGED_REST_FIRST}; // ---- The module ---- diff --git a/crates/metal2vulkan/src/bind/resident.rs b/crates/metal2vulkan/src/bind/resident.rs deleted file mode 100644 index 9202cd359..000000000 --- a/crates/metal2vulkan/src/bind/resident.rs +++ /dev/null @@ -1,174 +0,0 @@ -//! The resident set and root tables. -//! -//! The resident set of a draw or dispatch is every bound buffer with a device address and every -//! `Buffer`/`Heap` used resource with both addresses, coalesced (`resident_set`): sorted by -//! guest address, an allocation inside another dropped (the outermost wins: a heap over its -//! sub-buffers), a partially overlapping one trimmed of its overlapping head (host and guest -//! advancing together), and empty ones dropped, of any count (At most 2¹⁶ entries before, else -//! `ResidentSetTooLarge`). Indirect command buffers' records (from `RECORDS_ADDRESS_BASE`) are -//! kept whole however they overlap, one a start: a kernel finds an ID's records only where they -//! start (`indirect_commands::records_address`). Each stage that reads a root table gets its own (`stage_root_table`): -//! its `Psb` entries are that stage's slots; the resident set is shared. - -use crate::bind::instantiate::{padded, RootTable}; -use crate::bind::state::{BindState, BoundBuffer, ResourceClass}; -use crate::indirect_commands::RECORDS_ADDRESS_BASE; -use std::cmp::Ordering; - -/// One root-table entry. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] -pub(crate) struct RootEntry { - /// The allocation's device address. - pub host: u64, - /// The allocation's Metal address. - pub guest: u64, - /// The allocation's size, padded to 16 bytes. - pub size: u64, - /// The Metal bind offset (parameter entries only; 0 in the resident set). - pub bind_offset: u64, -} - -/// The resident set of `all` allocations: sorted by guest address; an allocation inside another one -/// is dropped (the outermost wins: a heap over its sub-buffers); a partially overlapping one loses -/// its overlapping head (its host and guest addresses advance together, which is exact when both -/// ranges view one mapping); empty allocations are dropped. Records of indirect command buffers -/// (from `RECORDS_ADDRESS_BASE`, where no Metal allocation lies) are kept whole, one for each -/// start (the largest): an ID's records may run past later IDs' starts, and a kernel searches -/// them only at their start, so each start must stay an entry's. -pub(crate) fn resident_set(all: Vec) -> Vec { - coalesced_of_sorted(&sorted(all)) -} - -/// `all` as a resident set takes its allocations: the empty ones dropped, the rest sorted by guest -/// address, the larger first at one address, else in their order (a stable sort). -pub(crate) fn sorted(mut all: Vec) -> Vec { - all.retain(|e| e.size > 0); - all.sort_by(order); - all -} - -/// The order [`sorted`] takes allocations in. -fn order(a: &RootEntry, b: &RootEntry) -> Ordering { - a.guest.cmp(&b.guest).then(b.size.cmp(&a.size)) -} - -/// The resident set of `sorted`, allocations in [`sorted`]'s order. -pub(crate) fn coalesced_of_sorted(sorted: &[RootEntry]) -> Vec { - let mut out: Vec = Vec::with_capacity(sorted.len()); - for &e in sorted { - coalesce(&mut out, e); - } - out -} - -/// Add `e`, an allocation at or after every one `out` was made of in [`sorted`]'s order, to `out`, -/// the resident set of those: dropped where it lies inside the last entry, or a record's at the -/// last entry's start; trimmed of its head where it overlaps the last entry; else whole. Whether -/// it went in whole. -fn coalesce(out: &mut Vec, mut e: RootEntry) -> bool { - let end = |e: &RootEntry| u128::from(e.guest) + u128::from(e.size); - e.bind_offset = 0; - let Some(last) = out.last() else { - out.push(e); - return true; - }; - if e.guest >= RECORDS_ADDRESS_BASE { - if e.guest == last.guest { - return false; - } - out.push(e); - return true; - } - let last_end = end(last); - if end(&e) <= last_end { - return false; - } - if u128::from(e.guest) >= last_end { - out.push(e); - return true; - } - // `last_end - e.guest < e.size`, so the cut fits in `u64`. - let cut = (last_end - u128::from(e.guest)) as u64; - e.guest += cut; - e.host = e.host.wrapping_add(cut); - e.size -= cut; - out.push(e); - false -} - -/// The coalesced resident set of `state`: every bound buffer with a device address (every stage) -/// and every `Buffer`/`Heap` used resource with both addresses, at their padded sizes. -pub(crate) fn resident_entries(state: &BindState) -> Vec { - coalesced(resident_allocations(state)) -} - -/// The coalesced resident set a root table of `state` holds: [`resident_entries`], or, where the -/// consumer points its root tables at a set holding the used resources and the listed ranges -/// (`BindState::resident_apart`), the bound buffers' alone. -pub(crate) fn table_entries(state: &BindState) -> Vec { - match state.resident_apart { - true => coalesced(bound_allocations(state)), - false => resident_entries(state), - } -} - -/// The resident set of `allocations`, each `(host, guest, length)`, at their padded sizes. -fn coalesced(allocations: impl Iterator) -> Vec { - let all = allocations - .map(|(host, guest, length)| RootEntry { - host, - guest, - size: padded(length), - bind_offset: 0, - }) - .collect(); - resident_set(all) -} - -/// Every allocation of `state`'s resident set before coalescing, as `(host, guest, length)` at -/// its own length (before the padding): the bound buffers, the used buffers and heaps, and the -/// ranges listed apart (`BindState::resident_ranges`). -fn resident_allocations(state: &BindState) -> impl Iterator + '_ { - let used = state.used_resources.iter().filter_map(|u| { - match (u.class, u.gpu_address, u.device_address) { - (ResourceClass::Buffer | ResourceClass::Heap, Some(guest), Some(host)) => { - Some((host, guest, u.length)) - } - _ => None, - } - }); - let listed = state - .resident_ranges - .iter() - .map(|range| (range.host, range.guest, range.length)); - bound_allocations(state).chain(used).chain(listed) -} - -/// The bound buffers of `state` with a device address (every stage), as `(host, guest, length)` -/// at their own lengths. -fn bound_allocations(state: &BindState) -> impl Iterator + '_ { - state.stages.values().flat_map(|stage_table| { - stage_table.buffers.values().filter_map(|b| match *b { - BoundBuffer::Buffer { - length, - gpu_address, - device_address: Some(host), - .. - } => Some((host, gpu_address, length)), - _ => None, - }) - }) -} - -/// The root table of one stage: its `Psb` entries (`(n, entry)` for `[[buffer(n)]]`) and the -/// coalesced `resident` set from root `first`. -pub(crate) fn stage_root_table( - statics: &[(u32, RootEntry)], - first: u32, - resident: &[RootEntry], -) -> RootTable { - RootTable::build(statics, u64::from(first), resident) -} - -#[cfg(test)] -mod tests; diff --git a/crates/metal2vulkan/src/bind/resident/tests.rs b/crates/metal2vulkan/src/bind/resident/tests.rs deleted file mode 100644 index 6a81c7f7a..000000000 --- a/crates/metal2vulkan/src/bind/resident/tests.rs +++ /dev/null @@ -1,362 +0,0 @@ -//! Resident-set coalescing properties over deterministic pseudo-random sets. - -use super::*; - -/// A small deterministic generator (xorshift64*), so the properties need no dependency. -struct Rng(u64); - -impl Rng { - fn next(&mut self) -> u64 { - self.0 ^= self.0 >> 12; - self.0 ^= self.0 << 25; - self.0 ^= self.0 >> 27; - self.0.wrapping_mul(0x2545_F491_4F6C_DD1D) - } - - fn below(&mut self, n: u64) -> u64 { - self.next() % n - } -} - -/// Allocations that view one mapping (`host = guest + delta`), as heap sub-allocations do, placed -/// so that nesting, partial overlap, adjacency, and gaps all occur. -fn one_mapping(rng: &mut Rng, delta: u64) -> Vec { - let n = 1 + rng.below(24) as usize; - (0..n) - .map(|_| { - let guest = 0x1_0000 + 16 * rng.below(256); - let size = 16 * rng.below(40); - RootEntry { - host: guest.wrapping_add(delta), - guest, - size, - bind_offset: rng.below(64), - } - }) - .collect() -} - -fn covers(set: &[RootEntry], byte: u64) -> Option<&RootEntry> { - set.iter() - .find(|e| e.guest <= byte && u128::from(byte) < u128::from(e.guest) + u128::from(e.size)) -} - -/// The coalesced set is sorted, disjoint, and non-empty per entry; it covers exactly the bytes of -/// the input (every input byte in one entry, no other byte); every entry translates as the -/// mapping does; bind offsets are cleared; and coalescing is idempotent and independent of the -/// input order. -#[test] -fn coalescing_is_sorted_disjoint_exact_and_idempotent() { - let mut rng = Rng(0x9E37_79B9_7F4A_7C15); - for case in 0..500 { - let delta = rng.next() & !15; - let input = one_mapping(&mut rng, delta); - let out = resident_set(input.clone()); - for pair in out.windows(2) { - let end = u128::from(pair[0].guest) + u128::from(pair[0].size); - assert!(end <= u128::from(pair[1].guest), "case {case}: {pair:?}"); - } - for e in &out { - assert!(e.size > 0, "case {case}"); - assert_eq!(e.bind_offset, 0, "case {case}"); - assert_eq!(e.host, e.guest.wrapping_add(delta), "case {case}"); - } - let lo = input.iter().map(|e| e.guest).min().unwrap_or(0); - let hi = input.iter().map(|e| e.guest + e.size).max().unwrap_or(0); - for byte in (lo.saturating_sub(16)..hi + 16).step_by(8) { - let inside = input - .iter() - .any(|e| e.guest <= byte && byte < e.guest + e.size); - assert_eq!( - covers(&out, byte).is_some(), - inside, - "case {case}: byte {byte:#x}" - ); - } - assert_eq!(resident_set(out.clone()), out.clone(), "case {case}"); - let mut reversed = input; - reversed.reverse(); - assert_eq!(resident_set(reversed), out, "case {case}"); - } -} - -/// A heap and the buffers sub-allocated inside it coalesce to the heap alone (the outermost -/// wins); a partial overlap keeps the earlier allocation whole and trims the later one's head. -#[test] -fn the_outermost_allocation_wins_and_overlaps_are_trimmed() { - let e = |guest: u64, size: u64| RootEntry { - host: guest + 0x1000_0000, - guest, - size, - bind_offset: 3, - }; - let heap = e(0x1000, 0x1000); - let out = resident_set(vec![ - e(0x1100, 0x40), - heap, - e(0x1000, 0x10), - e(0x1FF0, 0x10), - ]); - assert_eq!( - out, - vec![RootEntry { - bind_offset: 0, - ..heap - }] - ); - let out = resident_set(vec![e(0x2000, 0x100), e(0x1F00, 0x180)]); - assert_eq!(out.len(), 2); - assert_eq!((out[0].guest, out[0].size), (0x1F00, 0x180)); - assert_eq!((out[1].guest, out[1].size), (0x2080, 0x80)); - assert_eq!(out[1].host, 0x2080 + 0x1000_0000); - assert_eq!(resident_set(vec![e(0x10, 0)]), Vec::new()); -} - -/// Coalescing counts entries after merging, duplicates of one allocation once; a set of more -/// than 2¹⁷ disjoint allocations is made whole. -#[test] -fn a_large_set_is_made_whole() { - let past = (1u64 << 17) + 3; - let e = |i: u64| RootEntry { - host: i * 32, - guest: i * 32, - size: 16, - bind_offset: 0, - }; - let all: Vec = (0..past).map(e).collect(); - assert_eq!(resident_set(all.clone()).len() as u64, past); - let mut dup = all.clone(); - dup.extend(all.iter().copied()); - assert_eq!(resident_set(dup), all); -} - -/// A state's resident set lists bound buffers of every stage and used buffers and heaps with both -/// addresses; textures, bytes, and buffers without a device address stay out. -#[test] -fn a_states_resident_set_comes_from_every_stage_and_the_used_resources() { - use crate::bind::state::{StageTable, TextureFacts, UsedResource}; - use crate::metal; - use crate::pipeline::sym::Stage; - let buffer = |gpu: u64, host: Option| BoundBuffer::Buffer { - length: 100, - offset: 8, - gpu_address: gpu, - device_address: host, - attribute_stride: None, - }; - let mut state = BindState::default(); - let mut v = StageTable::default(); - v.buffers.insert(0, buffer(0x1000, Some(0x9000))); - v.buffers.insert(1, buffer(0x2000, None)); - v.buffers.insert( - 2, - BoundBuffer::Bytes { - len: 64, - attribute_stride: None, - }, - ); - let mut f = StageTable::default(); - f.buffers.insert(0, buffer(0x3000, Some(0xA000))); - state.stages.insert(Stage::Vertex, v); - state.stages.insert(Stage::Fragment, f); - let mut heap = UsedResource::new(ResourceClass::Heap, 1); - heap.gpu_address = Some(0x4000); - heap.device_address = Some(0xB000); - heap.length = 0x100; - let mut tex = UsedResource::new( - ResourceClass::Texture(TextureFacts::new( - metal::TextureType::Type2D, - metal::PixelFormat::RGBA8Unorm, - )), - 2, - ); - tex.gpu_address = Some(0x5000); - tex.device_address = Some(0xC000); - tex.length = 0x100; - state.used_resources = vec![heap, tex]; - let got: Vec<(u64, u64, u64)> = resident_entries(&state) - .iter() - .map(|e| (e.guest, e.host, e.size)) - .collect(); - assert_eq!( - got, - vec![ - (0x1000, 0x9000, 112), - (0x3000, 0xA000, 112), - (0x4000, 0xB000, 0x100) - ] - ); -} - -fn entry(host: u64, guest: u64, size: u64) -> RootEntry { - RootEntry { - host, - guest, - size, - bind_offset: 0, - } -} - -#[test] -fn the_resident_set_is_sorted_disjoint_and_outermost() { - let heap = entry(0x9000, 0x1000, 0x1000); - let inner = entry(0x9100, 0x1100, 0x100); - let same_start = entry(0x9000, 0x1000, 0x10); - let after = entry(0x5000, 0x4000, 0x40); - let partial = entry(0x9f00, 0x1f00, 0x200); - let empty = entry(0x7000, 0x3000, 0); - let set = resident_set(vec![after, partial, inner, empty, same_start, heap]); - assert_eq!( - set, - vec![ - heap, - // The partially overlapping allocation loses its head, host and guest together. - entry(0xa000, 0x2000, 0x100), - after - ] - ); - for w in set.windows(2) { - assert!(w[0].guest + w[0].size <= w[1].guest, "disjoint and sorted"); - } - assert_eq!(resident_set(Vec::new()), Vec::new()); -} - -/// Indirect command buffers' records are kept whole however they overlap, one entry a start (the -/// largest of those at one start), past the Metal allocations, which coalesce as before: the -/// records of ID 5, 3 GiB long, run past ID 6's start, and ID 6's own stay an entry, so a search -/// at each ID's start finds that ID's records. -#[test] -fn records_are_kept_whole_one_entry_a_start() { - use crate::indirect_commands::records_address; - let gib = 1u64 << 30; - let metal = entry(0x9000, 0x1000, 0x1000); - let inner = entry(0x9100, 0x1100, 0x100); - let five = entry(0x10_0000_0000, records_address(5), 3 * gib); - let six = entry(0x20_0000_0000, records_address(6), 0x1000); - let six_again = entry(0x30_0000_0000, records_address(6), 0x100); - let seven = entry(0x40_0000_0000, records_address(7), 0x1000); - let set = resident_set(vec![seven, six_again, inner, six, five, metal]); - assert_eq!(set, vec![metal, five, six, seven]); - for id in [5, 6, 7] { - let start = records_address(id); - let found = set.iter().rposition(|e| e.guest <= start).unwrap(); - assert_eq!( - set[found].guest, start, - "ID {id}'s start is its own entry's" - ); - } -} - -/// Ranges listed apart (`BindState::resident_ranges`) join the resident set as used buffers do, -/// and leave the shape as it was. -#[test] -fn ranges_listed_apart_join_the_resident_set_and_not_the_shape() { - use crate::bind::state::UsedResource; - use crate::bind::ResidentRange; - let mut used = UsedResource::new(ResourceClass::Buffer, 0); - used.gpu_address = Some(0x2000); - used.device_address = Some(0x9_2000); - used.length = 100; - let state = BindState { - used_resources: vec![used], - ..BindState::default() - }; - let listed = BindState { - resident_ranges: vec![ - ResidentRange { - host: 0x9_1000, - guest: 0x1000, - length: 60, - }, - // Inside the used buffer's window: dropped as one inside another is. - ResidentRange { - host: 0x9_2010, - guest: 0x2010, - length: 16, - }, - ResidentRange { - host: 0x9_3000, - guest: 0x3000, - length: 0x20, - }, - ], - ..state.clone() - }; - let resident = resident_entries(&listed); - let got: Vec<(u64, u64, u64)> = resident.iter().map(|e| (e.guest, e.host, e.size)).collect(); - assert_eq!( - got, - vec![ - (0x1000, 0x9_1000, 64), - (0x2000, 0x9_2000, 112), - (0x3000, 0x9_3000, 0x20) - ] - ); - assert_eq!(listed.shape(), state.shape()); -} - -/// Under `BindState::resident_apart` a root table's own resident set is the bound buffers' alone, -/// and without it the whole set, over pseudo-random states whose bound buffers, used buffers and -/// heaps and listed ranges nest, overlap, touch and repeat. -#[test] -fn a_state_resident_apart_keeps_the_used_resources_out_of_its_tables() { - use crate::bind::state::{StageTable, UsedResource}; - use crate::bind::ResidentRange; - use crate::pipeline::sym::Stage; - let mut rng = Rng(0x5eed_0fa9_a7c3); - for _ in 0..300 { - let delta = 0x10_0000; - let mut state = BindState::default(); - let (mut vertex, mut fragment) = (StageTable::default(), StageTable::default()); - for (i, e) in one_mapping(&mut rng, delta).into_iter().enumerate() { - let length = e.size.saturating_sub(rng.below(16)); - match rng.below(4) { - 0 | 1 => { - let table = match rng.below(2) { - 0 => &mut vertex, - _ => &mut fragment, - }; - let buffer = BoundBuffer::Buffer { - length, - offset: 0, - gpu_address: e.guest, - device_address: Some(e.host), - attribute_stride: None, - }; - table.buffers.insert(i as u32, buffer); - } - 2 => { - let class = match rng.below(2) { - 0 => ResourceClass::Buffer, - _ => ResourceClass::Heap, - }; - let mut used = UsedResource::new(class, i as u32); - used.gpu_address = Some(e.guest); - used.device_address = Some(e.host); - used.length = length; - state.used_resources.push(used); - } - _ => { - let range = ResidentRange { - host: e.host, - guest: e.guest, - length, - }; - state.resident_ranges.push(range); - } - } - } - state.stages.insert(Stage::Vertex, vertex); - state.stages.insert(Stage::Fragment, fragment); - let mut apart = state.clone(); - apart.resident_apart = true; - assert_eq!(table_entries(&state), resident_entries(&state)); - let bound_only = BindState { - used_resources: Vec::new(), - resident_ranges: Vec::new(), - ..state.clone() - }; - assert_eq!(table_entries(&apart), resident_entries(&bound_only)); - assert_eq!(apart.shape(), state.shape()); - } -} diff --git a/crates/metal2vulkan/src/bind/state.rs b/crates/metal2vulkan/src/bind/state.rs index 907dd0af1..4469134a2 100644 --- a/crates/metal2vulkan/src/bind/state.rs +++ b/crates/metal2vulkan/src/bind/state.rs @@ -1,494 +1,10 @@ -//! `BindState` and `BindShape`: the Metal-shaped binder input. -//! -//! The consumer keeps its own resource handles; the binder sees facts about what is bound, keyed -//! by Metal slot, and returns instructions that reference slots and consumer tokens. A slot absent -//! from a table is unbound. [`BindShape`] is the hashable projection that can change a plan; -//! offsets, addresses, and lengths only change per-draw bytes ([`BindState::shape`]). +//! What is bound, as Metal states it: a texture's facts ([`TextureFacts`]) and their +//! [`TextureShape`], a sampler's descriptor ([`SamplerDescriptor`]) and its [`SamplerShape`], and +//! a compute encoder's stage-in region ([`StageInRegion`]). -use std::collections::{BTreeMap, BTreeSet}; use std::hash::Hash; -use crate::bind::ResidentRange; -use crate::device::profile::Limits; use crate::metal; -use crate::pipeline::sym::Stage; - -/// Everything bound for one draw or dispatch. -#[non_exhaustive] -#[derive(Clone, Debug, Default, PartialEq)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct BindState { - /// The argument tables of each Metal stage. - pub stages: BTreeMap, - /// `useResource` / `useResources` / `useHeap(s)`, and every other live allocation the guest - /// task may reach (a superset by contract). - /// - /// **Textures resident through `useHeap`**: a `Heap` entry makes the heap's address range - /// resident for buffer pointers; it names no texture. The consumer lists every texture the - /// guest allocated from a used heap as its own `Texture` entry (its facts and resource id, the - /// heap's usage and stages). A handle table holds exactly the textures listed here and those - /// bound at a slot, so a resource id it lacks misses: its reads and queries answer the - /// neutral's, its writes are dropped, and `is_null` answers true. A texture's entry carries - /// whether its pixel format has an alpha: a heap read the shader bounds-checks reads Metal's - /// out-of-bounds alpha from it, so a texture's facts must be the resident texture's. - pub used_resources: Vec, - /// The consumer lists `used_resources` in token order: each entry's token at least the one - /// before it, so a token's entries lie together. A heap member then finds its entries by - /// search, at the logarithm of their count (a debug build asserts the order), rather than - /// every command's instantiation reading every entry. Not part of the shape; `false` (the - /// default): listed in any order. - #[cfg_attr(feature = "serde", serde(default))] - pub used_in_token_order: bool, - /// The render encoder's vertex amplification (`setVertexAmplificationCount:viewMappings:`); - /// Metal's default of a count of 1 without view mappings otherwise. - #[cfg_attr(feature = "serde", serde(default))] - pub vertex_amplification: VertexAmplification, - /// The compute encoder's imageblock size (`setImageblockWidth:height:`); 0 by 0 when the - /// encoder never set it. - #[cfg_attr(feature = "serde", serde(default))] - pub imageblock_size: ImageblockSize, - /// The render pass's `renderTargetArrayLength` (`MTLRenderPassDescriptor`): the number of - /// layers a vertex function's `[[render_target_array_index]]` can select. Metal's default, 0, - /// is a pass that is not layered; 0 and 1 both render every primitive into one slice. A vertex - /// function that chooses its slice stores `Layer` as 0 for an index at or past the length, - /// which each draw writes to its push bytes as at least 1 - /// (`PushField::RenderTargetArrayLength`). 0 in a compute encoder. - #[cfg_attr(feature = "serde", serde(default))] - pub render_target_array_length: u32, - /// The compute encoder's stage-in region (`setStageInRegion:`): the origin a kernel's - /// `[[stage_in]]` attributes stepping by thread position start from, and its - /// `[[grid_origin]]` and `[[grid_size]]`. `None` when the encoder never set it: what Metal - /// reads then is not established, so a dispatch of a kernel that reads the region is - /// `BindError::MissingStageInRegion`. Only a dispatch's bytes depend on it, so it is not part - /// of the shape. - #[cfg_attr(feature = "serde", serde(default))] - pub stage_in_region: Option, - /// The render encoder's tessellation factor buffer and scale; Metal's defaults (no buffer, - /// scale 1) when the encoder never set them. Read by patch draws only. - #[cfg_attr(feature = "serde", serde(default))] - pub tessellation_factors: TessellationFactors, - /// The render area a tile dispatch covers, in pixels (`MTLRenderPassDescriptor`'s - /// `renderTargetWidth` and `renderTargetHeight`): a tile function stages the pixels of its - /// attachments inside it. `[0, 0]` outside a tile dispatch. With `imageblock_size` set to the - /// pass's tile size, a tile dispatch is `Dispatch::Threadgroups` of `ceil(render_area / tile - /// size)` groups of the `dispatchThreadsPerTile:` size. - #[cfg_attr(feature = "serde", serde(default))] - pub render_area: [u32; 2], - /// Every live sampler state the guest task made, with or without `supportArgumentBuffers` - /// (Metal's functions sample through either's `gpuResourceID`), in any order: the samplers an - /// argument buffer's sampler handle can name. The consumer keeps this registry at sampler - /// creation and release, as it lists every live allocation in `used_resources`. It is derived - /// from object lifetimes, never from argument-buffer memory: Metal keeps a sampler alive while - /// a command reads it and never changes a sampler state, so it holds every id a buffer can - /// validly hold however the buffer was written. A function's sampler handle names the sampler - /// of its id here, or misses and reads the neutral sampler. Only the shape of the list enters a - /// plan ([`ArgumentSamplersShape`]); the ids and descriptors are per draw. - #[cfg_attr(feature = "serde", serde(default))] - pub argument_samplers: Vec, - /// The render encoder's depth/stencil state (`setDepthStencilState:`); Metal's default - /// descriptor (no depth or stencil test) when the encoder never set it. Read only by a draw - /// whose pipeline runs a shader-side stencil (`GraphicsState::shadow_stencil`), which takes - /// its stencil state as push data; every other pipeline takes it as Vulkan state - /// (`metal::state::depth_stencil_state`). Only a draw's bytes depend on it, so it is not part - /// of the shape. - #[cfg_attr(feature = "serde", serde(default))] - pub depth_stencil: metal::state::DepthStencilDescriptor, - /// The draw's primitive type (`drawPrimitives:`'s or `drawIndexedPrimitives:`'s - /// `primitiveType`), which a draw of a pipeline whose vertex function writes the primitive ID - /// reads (`LoweringInputs::primitive_id_varying`): its `PushField::VerticesPerPrimitive` holds - /// the type's vertices per primitive, and an indexed strip, which Metal restarts at the index - /// type's all-ones index, does not run de-indexed. `None` where the consumer does not say; - /// such a draw is `BindError::MissingPrimitiveType`. Only a draw's bytes depend on it, so it - /// is not part of the shape. - #[cfg_attr(feature = "serde", serde(default))] - pub primitive_type: Option, - /// The index type of a direct indexed draw of a pipeline whose vertex function writes the - /// primitive ID's varying (`LoweringInputs::primitive_id_varying`): its primitives share - /// vertices, so it runs the variant that draws its indices as vertices from 0 - /// (`VariantKey::primitive_id_indices`). Part of the shape - /// (`BindShape::primitive_id_indices`); `None` for every other draw, whose plan otherwise - /// asks for it (`BindError::NeedsVariant`) or refuses the draw. - #[cfg_attr(feature = "serde", serde(default))] - pub primitive_id_indices: Option, - /// The draw is of Metal's private quads or quad strip, which the consumer lists as two - /// triangles a quad, each quad's adjacent: a pipeline whose fragment function reads Vulkan's - /// `PrimitiveId` runs the variant that reads the quad's, that value shifted right by one, as - /// Metal counts one primitive a quad - /// (`VariantKey::quad_primitive_ids`). Part of the shape (`BindShape::quad_primitive_ids`); - /// `false` for every other draw. - #[cfg_attr(feature = "serde", serde(default))] - pub quad_primitive_ids: bool, - /// The draw is of one of Metal's private primitive types, drawn in the pulled list form - /// (`VariantKey::private_list`): without indices, each position of the list the consumer - /// writes (Metal's base vertex in the word before its first index) run once, from the list's - /// first index as first vertex. Part of the shape (`BindShape::private_list`); `false` for - /// every other draw. - #[cfg_attr(feature = "serde", serde(default))] - pub private_list: bool, - /// The Metal vertex buffer indices of the layouts the draw fetches in fixed function that the - /// device's fixed-function input cannot fetch for it: the runtime names those a draw may fetch - /// past `2^32` bytes of their bind offset, on a driver whose fixed-function vertex input takes - /// that displacement modulo `2^32`, and every fixed-function binding's of a draw replay's - /// state, whose commands bind their own buffers. The plan pulls them - /// in the pulled-vertex-buffer variant (`VariantKey::pulled_vertex_buffers`), as it pulls a - /// layout bound at an offset or stride fixed-function input cannot fetch, and needs no buffer - /// bound at them; a layout the pipeline does not fetch in fixed function is left as it is. - /// Part of the shape (`BindShape::far_vertex_buffers`); empty for every other draw. - #[cfg_attr(feature = "serde", serde(default))] - pub far_vertex_buffers: BTreeSet, - /// The draw records a rasterization-rate-mapped pass's regions several at a time, each one - /// draw of a `vkCmdDrawMultiEXT` or `vkCmdDrawMultiIndexedEXT` whose index selects its - /// viewport and scissor: the pipeline runs the variant whose vertex function stores - /// `ViewportIndex` as `DrawIndex` (`VariantKey::region_viewports`), and its `VkPipeline` takes - /// as many viewports as a command draws regions. The plan's variant draws so only for a vertex - /// pipeline without tessellation drawn in one pass of no views (`bind::graphics`'s module - /// docs). Part of the shape (`BindShape::region_viewports`); `false` for every other draw. - #[cfg_attr(feature = "serde", serde(default))] - pub region_viewports: bool, - /// Where the heap arrays (set 1) hold the command's heap members and argument samplers - /// ([`HeapPlacement`]). Only the instantiated tables and the elements the consumer writes - /// depend on it, so it is not part of the shape. - #[cfg_attr(feature = "serde", serde(default))] - pub heap_placement: HeapPlacement, - /// The render encoder's viewport count (`setViewports:count:`): a vertex function's - /// `[[viewport_array_index]]` at or past it draws through viewport 0, as Metal's does - /// (`PushField::ViewportCount`). Metal's default is one viewport; 0, the default here, and 1 - /// both draw every index through viewport 0. Only a draw's bytes depend on it, so it is not - /// part of the shape. - #[cfg_attr(feature = "serde", serde(default))] - pub viewport_count: u32, - /// Every live visible-function table the command's pipeline state made, in any order: the - /// tables an argument buffer's `visible_function_table` member can name. The consumer keeps - /// this registry at table creation and release, as it keeps `argument_samplers`: Metal reads a - /// table through an argument buffer without `useResource`, so every live table of the state is - /// listed, resident or not. A function's table names the table of its id here, or misses and - /// reads the null table. Only the capacity class of the list enters a plan - /// ([`FunctionTablesShape`]); the ids and sizes are per command, and each table's words are the - /// consumer's (`WriteSource::FunctionTableSnapshot`, whose directory places each table by the - /// sizes before it). - #[cfg_attr(feature = "serde", serde(default))] - pub function_tables: Vec, - /// The render encoder's tile threadgroup memory: the render pass's `threadgroupMemoryLength` - /// and each argument `setThreadgroupMemoryLength:offset:atIndex:` placed in it, which a tile - /// function's `[[threadgroup(n)]]` arguments read (`RuntimeFact::TileThreadgroupMemory`). Empty - /// outside a render encoder. - #[cfg_attr(feature = "serde", serde(default))] - pub tile_threadgroup: TileThreadgroupMemory, - /// The color attachments of the draw's render pass its render pipeline has no pixel format - /// for, the pass's pixel format of each by color index: plain Metal stores zero bytes into - /// each at every sample the draw covers (Metal's validation stops the draw). Its variant is - /// part of the shape (`BindShape::zeroed_colors`); empty for every other draw. - #[cfg_attr(feature = "serde", serde(default))] - pub zeroed_colors: BTreeMap, - /// The color attachments the draw's render pipeline has a pixel format for and its render - /// pass has none, by color index: plain Metal drops what the fragment function writes there. - /// Its variant is part of the shape (`BindShape::dropped_colors`); empty for every other - /// draw. - #[cfg_attr(feature = "serde", serde(default))] - pub dropped_colors: BTreeSet, - /// The bytes of each cell of the tile function's explicit imageblock standing alone that the - /// dispatch's render pass keeps, where they are fewer than the cell holds: plain Metal reads - /// the block's words past them as zero and drops their writes (Metal's validation stops the - /// state's setting). Its variant is part of the shape (`BindShape::kept_imageblock_bytes`); - /// `None` for every other dispatch and for draws. - #[cfg_attr(feature = "serde", serde(default))] - pub kept_imageblock_bytes: Option, - /// The draw's depth clamp range `[low, high]` where its fragment function clamps the depth it - /// writes itself (`PushField::DepthClampRange`): a draw in depth clamp mode through a range - /// above 0, whose Vulkan depth clamp holds 0. Its variant is part of the shape - /// (`BindShape::depth_clamp_range`), its values only of the draw's bytes; `None` for every - /// other draw. - #[cfg_attr(feature = "serde", serde(default))] - pub depth_clamp_range: Option<[f32; 2]>, - /// Whether the draw draws triangles with Metal's last vertex first, `(c, a, b)` for Metal's - /// `(a, b, c)`: a list the consumer draws for triangles under Apple's last provoking vertex - /// (`setProvokingVertexMode:` 1) on a device that takes flat inputs from the first vertex. - /// A pipeline whose fragment function reads `[[barycentric_coord]]` runs the variant that takes - /// Metal's weights back from the drawn triangle's (`BindShape::rotated_weights`, - /// `VariantKey::rotated_weights`). Part of the shape; `false` for every other draw. - #[cfg_attr(feature = "serde", serde(default))] - pub rotated_weights: bool, - /// What the draw draws as bands of triangles, where it draws its lines or its triangles' - /// edges so, and its band (`PushField::LineBand`): `[sx, sy, h, f]`, the half extent of its - /// Vulkan viewport 0 (its height negative, as the viewport is), half the band's width in - /// pixels, and of triangles its front face's sign, 1 `CLOCKWISE` and -1 `COUNTER_CLOCKWISE` - /// (0 for lines; `LineBandState`, `pipeline::link::band`). Its variant is part of the shape - /// (`BindShape::line_band`, `VariantKey::line_band`), its values only of the draw's bytes; - /// `None` for every other draw. - #[cfg_attr(feature = "serde", serde(default))] - pub line_band: Option<(crate::pipeline::BandPrimitive, [f32; 4])>, - /// Allocations a pointer may reach that the consumer lists apart from `used_resources`, at - /// their own lengths: the resident set holds them beside the bound buffers and the used - /// resources, and a replay's extents count them (the runtime's live buffers of their own, - /// for a replay whose resident root table it does not point at its own set). Only the - /// resident sets of the root tables depend on them, so they are not part of the shape. - #[cfg_attr(feature = "serde", serde(default))] - pub resident_ranges: Vec, - /// The consumer points every root table of the command at a resident set it uploads apart - /// (its address and entry count written over the table's own fields) that holds every - /// allocation of `used_resources` (each `Buffer` and `Heap` entry with both addresses) and of - /// `resident_ranges`, at their padded lengths, as a root table's own set would, and every - /// range the table's entries hold. - /// A root table's own resident set then holds the command's bound buffers alone, and lists - /// only those: a command's instantiation costs its bindings, not every resource made - /// resident. A table never pointed so resolves only its bound buffers. Only the root tables - /// depend on it, so it is not part of the shape; `false` (the default): each root table holds - /// the whole set. - #[cfg_attr(feature = "serde", serde(default))] - pub resident_apart: bool, - /// 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 - /// (`PushField::HalfBlendColor`). Only a draw's bytes depend on it, so it is not part of the - /// shape. - #[cfg_attr(feature = "serde", serde(default))] - pub blend_color: [f32; 4], - /// The render encoder's alpha test reference (`setAlphaTestReferenceValue:`, Apple SPI); - /// `None` where the encoder never set it, which Metal's test compares as 1 (each encoder - /// starts there: a reference set in an earlier encoder is not kept). A fragment function that - /// runs the pipeline's private alpha test takes its code as push data - /// (`PushField::AlphaTestReference`). Only a draw's bytes depend on it, so it is not part of - /// the shape. - #[cfg_attr(feature = "serde", serde(default))] - pub alpha_test_reference: Option, -} - -/// 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 -/// sampler tables map each resource ID to the element that holds the resource. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub enum HeapPlacement { - /// Each at its planned element: every command writes a heap set of its own. - #[default] - Planned, - /// Each at the element its nonzero resource ID names, and the tables map each ID to itself; - /// an argument sampler with an [`element`](ArgumentSampler::element) at that element, and - /// its table entry maps its ID there: commands whose IDs name the same resources write the - /// same element alike, so they can share one heap set. For a consumer whose IDs (and - /// sampler elements) are dense and small, as the runtime's are: an element at or past the - /// heap's capacity is refused where the consumer places the writes. - ResourceId, -} - -/// One live sampler state an argument buffer can name (`BindState::argument_samplers`). -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct ArgumentSampler { - pub desc: SamplerDescriptor, - /// The guest `gpuResourceID`; 0 is the null handle's, which never names a sampler. - pub resource_id: u64, - /// Under [`HeapPlacement::ResourceId`], the element of the set-1 sampler arrays that holds - /// the state, which its table entry maps its resource ID to; `None`, the resource ID - /// itself. A consumer whose sampler IDs can lie past the arrays (a state placed at an ID) - /// gives each live state a dense element of its own. Ignored under [`HeapPlacement::Planned`]. - #[cfg_attr(feature = "serde", serde(default))] - pub element: Option, -} - -impl ArgumentSampler { - /// The sampler state of `desc` whose `gpuResourceID` is `resource_id`. - pub fn new(desc: SamplerDescriptor, resource_id: u64) -> ArgumentSampler { - ArgumentSampler { - desc, - resource_id, - element: None, - } - } - - /// The number that places the state under [`HeapPlacement::ResourceId`]: its element, else - /// its resource ID. - pub(crate) fn placed_at(&self) -> u64 { - self.element.map_or(self.resource_id, u64::from) - } -} - -/// One live visible-function table an argument buffer can name (`BindState::function_tables`). -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct ArgumentFunctionTable { - /// The table's `gpuResourceID`; 0 is the null table's, which never names a table. - pub resource_id: u64, - /// The table's size (`functionCount`): where a function-table snapshot places the tables - /// after it ([`FunctionTableSnapshot`](crate::bind::FunctionTableSnapshot)). - #[cfg_attr(feature = "serde", serde(default))] - pub size: u32, - /// The device address of the table's words (`bind::table`), which a pipeline compiled - /// to read tables through their addresses reads (`VariantKey::addressed_function_tables`); - /// 0 where the consumer has none, which such a pipeline's dispatch refuses. - #[cfg_attr(feature = "serde", serde(default))] - pub address: u64, -} - -/// A render encoder's tessellation factor state: `setTessellationFactorBuffer:offset: -/// instanceStride:` and `setTessellationFactorScale:`. A patch draw reads each patch's factors -/// (`MTLTriangleTessellationFactorsHalf` or `MTLQuadTessellationFactorsHalf`) from the buffer as -/// the pipeline's `tessellationFactorStepFunction` addresses them. The default is Metal's: no -/// buffer, whose patches the binder feeds zero factors (culled), and a scale of 1. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct TessellationFactors { - /// The factor buffer; `None` for `nil`. - pub buffer: Option, - /// `setTessellationFactorScale:`, applied when the pipeline enables - /// `tessellationFactorScaleEnabled` (Metal converts it to `half` first). - pub scale: f32, -} - -impl TessellationFactors { - /// The factor buffer `buffer` (`None` for `nil`) with scale `scale`. - pub fn new(buffer: Option, scale: f32) -> TessellationFactors { - TessellationFactors { buffer, scale } - } -} - -impl Default for TessellationFactors { - fn default() -> TessellationFactors { - TessellationFactors::new(None, 1.0) - } -} - -/// The buffer of `setTessellationFactorBuffer:offset:instanceStride:`. Metal's validation requires -/// the offset and the instance stride to be multiples of 4; plain Metal reads the factors from the -/// offset rounded down to a multiple of 2, and steps the instances by the stride rounded down to a -/// multiple of 4, as the binder does. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct TessellationFactorBuffer { - /// The allocation length (the consumer pads the backing `VkBuffer` to 16 bytes). - pub length: u64, - /// `offset`: the byte offset of the factors in the allocation. - pub offset: u64, - /// `instanceStride`: the byte stride between two instances' factors. - pub instance_stride: u64, -} - -impl TessellationFactorBuffer { - /// The factors of an allocation of `length` bytes from `offset`, `instance_stride` bytes per - /// instance. - pub fn new(length: u64, offset: u64, instance_stride: u64) -> TessellationFactorBuffer { - TessellationFactorBuffer { - length, - offset, - instance_stride, - } - } -} - -impl BindState { - /// The projection of this state that can change a plan: per stage, which slots are bound and - /// with what kind of resource, whether a buffer has a device address, its per-bind stride, its - /// length class as the table's [`StageTable::buffer_ranges`] tell it apart and bind-offset - /// alignment class (the largest power of two up to 4 that divides the offset), texture types - /// and formats, sampler modes, threadgroup - /// lengths, the vertex amplification, the render target array length, whether a - /// tessellation factor buffer is set, a tile dispatch's render area, the argument samplers' - /// capacity class and shapes ([`ArgumentSamplersShape::of`]), and the tile threadgroup memory - /// ([`TileThreadgroupMemory`]). Offsets, addresses, lengths, and resource ids are otherwise - /// left out: they only change per-draw bytes. A stage whose tables are all empty is left out, - /// so an empty table and an absent one have the same shape. - pub fn shape(&self) -> BindShape { - let stages = self - .stages - .iter() - .map(|(stage, t)| (*stage, t.shape())) - .filter(|(_, s)| *s != StageShape::default()) - .collect(); - BindShape { - stages, - used: self.used_shape(), - vertex_amplification: self.vertex_amplification.clone(), - imageblock_size: self.imageblock_size, - render_target_array_length: self.render_target_array_length, - tessellation_factor_buffer: self.tessellation_factors.buffer.is_some(), - render_area: self.render_area, - argument_samplers: ArgumentSamplersShape::of(&self.argument_samplers), - function_tables: FunctionTablesShape::of(&self.function_tables), - tile_threadgroup: self.tile_threadgroup.clone(), - zeroed_colors: self.zeroed_colors.clone(), - dropped_colors: self.dropped_colors.clone(), - kept_imageblock_bytes: self.kept_imageblock_bytes, - depth_clamp_range: self.depth_clamp_range.is_some(), - rotated_weights: self.rotated_weights, - line_band: self.line_band.map(|(primitive, _)| primitive), - primitive_id_indices: self.primitive_id_indices, - quad_primitive_ids: self.quad_primitive_ids, - private_list: self.private_list, - far_vertex_buffers: self.far_vertex_buffers.clone(), - region_viewports: self.region_viewports, - } - } - - /// `used_resources` by token ([`BindShape::used`]): one token names one resource, and listing - /// it twice unions its usage and stages. - fn used_shape(&self) -> BTreeMap { - let mut used: BTreeMap = BTreeMap::new(); - for u in &self.used_resources { - let e = used.entry(u.token).or_insert(UsedShape { - class: UsedClass::of(u.class), - usage: metal::ResourceUsage::empty(), - stages: metal::RenderStages::empty(), - }); - e.usage |= u.usage; - e.stages |= u.stages; - } - used - } -} - -/// A compute encoder's imageblock size in pixels (`setImageblockWidth:height:`): a kernel's -/// explicit imageblock holds `width · height` cells for each threadgroup of a dispatch. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct ImageblockSize { - pub width: u32, - pub height: u32, -} - -impl ImageblockSize { - /// The size `width` by `height`. - pub fn new(width: u32, height: u32) -> ImageblockSize { - ImageblockSize { width, height } - } -} - -/// A render encoder's tile threadgroup memory: each tile of the render pass holds `length` bytes, -/// the pass's `threadgroupMemoryLength`, which the pass keeps across its tile dispatches and starts -/// at zero; a tile function's threadgroup argument `n` is `arguments[n].length` bytes at -/// `arguments[n].offset` in its tile's memory, which the binder places where plain Metal begins it -/// (`bind::plan`). Arguments placed at overlapping offsets share their bytes, as Metal's do. -#[non_exhaustive] -#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct TileThreadgroupMemory { - /// The render pass's `threadgroupMemoryLength`: each tile's bytes, before Metal's rounding to - /// 16. - pub length: u32, - /// The encoder's `setThreadgroupMemoryLength:offset:atIndex:` by index. - pub arguments: BTreeMap, -} - -/// One tile threadgroup argument (`setThreadgroupMemoryLength:offset:atIndex:`): `length` bytes at -/// byte `offset` of the tile's threadgroup memory. -/// -/// Metal's API validation wants both to be multiples of 16, which plain Metal does not: it takes -/// every length and every offset. The length takes no part in the layout and bounds no access, as -/// plain Metal's does not, and the binder places the argument where plain Metal begins it, which is -/// not always `offset` itself (`bind::plan`). -#[non_exhaustive] -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct TileThreadgroupArgument { - pub length: u32, - pub offset: u32, -} /// A compute encoder's stage-in region (`setStageInRegion:`, `MTLRegion`), in threads. #[non_exhaustive] @@ -508,167 +24,11 @@ impl StageInRegion { } } -/// A render encoder's vertex amplification (`setVertexAmplificationCount:viewMappings:`): each -/// vertex of a draw is processed `count` times, amplification `a` offset by view mapping `a` when -/// the encoder gave mappings (`viewMappings` of `nil` is empty). The default is Metal's: a count of -/// 1 without mappings. -#[non_exhaustive] -#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct VertexAmplification { - pub count: u32, - /// `MTLVertexAmplificationViewMapping`s by amplification id; empty for `nil`. - pub view_mappings: Vec, - /// Draw a count above 1 one amplification at a time even where Vulkan multiview would draw it - /// as views (`BindingPlan::variant`'s `amplification_draws`): the consumer sets it while a - /// visibility result mode is set, since a query in a multiview render pass instance takes one - /// query per view, while draws of one amplification each add to the one query, as Metal counts - /// the samples of every amplification (a Metal probe on the M3 Max and an M4). Not set by - /// default. - #[cfg_attr(feature = "serde", serde(default))] - pub one_at_a_time: bool, -} - -impl VertexAmplification { - /// A count of `count` with `view_mappings` (empty for `nil`), drawn as views where they - /// express it. - pub fn new(count: u32, view_mappings: Vec) -> VertexAmplification { - VertexAmplification { - count, - view_mappings, - one_at_a_time: false, - } - } - - /// The view mapping amplification `a` takes under a pipeline whose - /// `maxVertexAmplificationCount` is `max`: its mapping (a `nil` one's offsets are 0), and - /// none under a pipeline of maximum count 1, which Metal applies no mapping to (Metal probes on - /// the M3 Max and an M4: a count of 1 whose mapping offsets the slice or the viewport draws - /// into the first layer through viewport 0 there, and moves under a pipeline of maximum count - /// 2). - pub fn mapping(&self, a: u32, max: u32) -> ViewMapping { - match max > 1 { - true => self - .view_mappings - .get(a as usize) - .copied() - .unwrap_or_default(), - false => ViewMapping::default(), - } - } - - /// The layer of a pass of `renderTargetArrayLength` `length` that amplification `a` renders - /// into under a pipeline whose `maxVertexAmplificationCount` is `max`, before any slice a - /// vertex function chooses: its mapping's render target offset ([`Self::mapping`]) where that - /// is below the pass's layers (`length`, at least 1), and the first layer where it is not (a - /// Metal probe on an M4, the rule for an index). - pub fn layer(&self, a: u32, length: u32, max: u32) -> u32 { - let offset = self.mapping(a, max).render_target_array_index_offset; - match offset < length.max(1) { - true => offset, - false => 0, - } - } -} - -impl Default for VertexAmplification { - fn default() -> VertexAmplification { - VertexAmplification::new(1, Vec::new()) - } -} - -/// `MTLVertexAmplificationViewMapping`: the offsets Metal adds to an amplification's viewport and -/// render target array indices. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct ViewMapping { - pub viewport_array_index_offset: u32, - pub render_target_array_index_offset: u32, -} - -impl StageTable { - /// The shape of this stage's tables ([`BindState::shape`]), the lengths of its buffers classed - /// under its [`buffer_ranges`](Self::buffer_ranges). - pub fn shape(&self) -> StageShape { - let ranges = self.buffer_ranges; - let buffer = |(i, b): (&u32, &BoundBuffer)| (*i, b.shape(ranges)); - StageShape { - buffers: self.buffers.iter().map(buffer).collect(), - textures: self.textures.iter().map(|(i, t)| (*i, t.shape())).collect(), - samplers: self.samplers.iter().map(|(i, s)| (*i, s.shape())).collect(), - threadgroup_lengths: self.threadgroup_lengths.clone(), - } - } -} - -impl BoundBuffer { - /// The shape of this binding, its bind offset classed (`BufferShape::Buffer`'s - /// `offset_alignment`) and its length under the buffer range limits `ranges` (its - /// `length_class`, [`BufferRanges::length_class`]). - pub fn shape(&self, ranges: BufferRanges) -> BufferShape { - match *self { - BoundBuffer::Buffer { - length, - offset, - device_address, - attribute_stride, - .. - } => BufferShape::Buffer { - attribute_stride, - device_address: device_address.is_some(), - length_class: ranges.length_class(length), - offset_alignment: offset_alignment(offset), - }, - BoundBuffer::Bytes { - attribute_stride, .. - } => BufferShape::Bytes { attribute_stride }, - } - } -} - -/// The alignment class of bind offset `offset` (a buffer's, -/// [`BufferShape::Buffer::offset_alignment`]): the largest power of two up to -/// [`MAX_VERTEX_ALIGNMENT`](metal::vertex::MAX_VERTEX_ALIGNMENT) that divides it (whether -/// fixed-function vertex input can fetch every attribute format at a buffer bound there). It is -/// the only predicate a plan reads of a bind offset, so offsets moving between multiples of 4 -/// keep one shape. -pub fn offset_alignment(offset: u64) -> u32 { - let mut a = metal::vertex::MAX_VERTEX_ALIGNMENT; - while a > 1 && !offset.is_multiple_of(u64::from(a)) { - a /= 2; - } - a -} - -impl BoundTexture { - /// The shape of this binding. - pub fn shape(&self) -> TextureShape { - match *self { - BoundTexture::Texture { facts, .. } => facts.shape(), - BoundTexture::Buffer { - pixel_format, - swizzle, - parts, - .. - } => TextureShape::Buffer { - pixel_format, - swizzle, - parts, - }, - } - } -} - impl TextureFacts { /// The facts of an image texture that can change a plan (its view facts): the type, the pixel /// format, the sample count, the usage, whether it is sparse, its level count, which decides a - /// storage slot's level views and pushed level count, its swizzle, its address-mode map, its - /// [`offset_base_axes`](Self::offset_base_axes), and whether its planes are read in place - /// ([`ycbcr_in_place`](Self::ycbcr_in_place), whose words the slot's push field carries, not - /// the shape) and through which device conversion where they are held as an image, and whether - /// its rows are read and written in place ([`texel_rows`](Self::texel_rows), whose words the - /// slot's push field carries). Its array length only changes the view's subresource range, which is every + /// storage slot's level views and pushed level count, its swizzle, its address-mode map and its + /// [`offset_base_axes`](Self::offset_base_axes). Its array length only changes the view's subresource range, which is every /// layer. /// /// The level count is stated whatever the usage: plain Metal writes a texture made without @@ -684,33 +44,15 @@ impl TextureFacts { swizzle: self.swizzle, address_modes: self.address_modes, offset_base_axes: self.offset_base_axes(), - ycbcr_in_place: self.ycbcr_in_place.is_some(), - ycbcr_planes_sampler: self.ycbcr_in_place.and_then(|p| p.planes_sampler()), - texel_rows: self.texel_rows.is_some(), - } - } -} - -impl BoundSampler { - /// The shape of this binding: its descriptor's [`SamplerDescriptor::shape`] and its - /// [`SamplerWord`](metal::sampler::SamplerWord), which the slot's specialization reads. - pub fn shape(&self) -> BoundSamplerShape { - BoundSamplerShape { - shape: self.desc.shape(), - word: metal::sampler::SamplerWord::of(&self.desc), - min_level: metal::sampler::query_min_level(&self.desc), - degree: metal::sampler::anisotropy_degree(&self.desc), } } } impl SamplerDescriptor { - /// The facts of this descriptor that can change a plan wherever the sampler is bound: the - /// reduction mode and comparison, whether each value the Vulkan sampler cannot take as is is - /// present, whether its border is opaque black, and whether it filters linearly, so a plan - /// refuses at plan time what `bind::sampler_desc` would refuse per bind and what the sampler's - /// textures' views cannot read. A slot's sampler also specializes its pipeline by its word - /// ([`BoundSampler::shape`]); an argument buffer's carries its word in the sampler table. + /// The facts of this descriptor that decide whether a sampler use takes it: the reduction + /// mode and comparison, whether each value the Vulkan sampler cannot take as is is present, + /// whether its border is opaque black, and whether it filters linearly + /// (`metal::sampler::check_sampler` reads them). pub fn shape(&self) -> SamplerShape { use metal::{SamplerAddressMode as A, SamplerBorderColor as B}; let modes = [ @@ -739,112 +81,6 @@ impl SamplerDescriptor { } } -/// One Metal stage's argument tables (`buffers[31]`, `textures[128]`, `samplers[16]`, -/// `threadgroup_lengths[31]`), sparse by index. -#[non_exhaustive] -#[derive(Clone, Debug, Default, PartialEq)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct StageTable { - pub buffers: BTreeMap, - pub textures: BTreeMap, - pub samplers: BTreeMap, - /// `setThreadgroupMemoryLength:atIndex:`, in bytes as the guest set them. - pub threadgroup_lengths: BTreeMap, - /// The acceleration structures bound at buffer slots (`setAccelerationStructure: - /// atBufferIndex:`), by buffer index: what the consumer knows of the Metal structure it holds. - /// A function that reads a structure's instance count reads the count stated here - /// (`PushField::InstanceCount`), 0 for a slot absent from this table. A structure the function - /// intersects is still the consumer's to build and bind (`WriteSource::AccelerationStructure`); - /// only the counts are read from this table, per dispatch or draw, so it is not part of the - /// shape. - #[cfg_attr(feature = "serde", serde(default))] - pub acceleration_structures: BTreeMap, - /// The device's buffer range limit, which the runtime sets: its buffers' length classes are - /// told apart only as far as that limit tells them apart ([`BufferRanges::length_class`]), - /// all a plan reads of a buffer's length, so its buffers of lengths it does not tell apart - /// keep one shape. None (the default) tells every class apart. - #[cfg_attr(feature = "serde", serde(default))] - pub buffer_ranges: BufferRanges, -} - -/// What the consumer knows of a Metal acceleration structure bound at a buffer slot. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct BoundAccelerationStructure { - /// The number of instances of an instance structure as it holds them when the command that - /// reads it runs: the `instanceCount` of the `MTLInstanceAccelerationStructureDescriptor` it - /// was last built with, which is what Metal's `get_instance_count()` reads. The binder pushes - /// it when the command is recorded, so it must be known then: for a structure built from an - /// indirect descriptor (its count in `instanceCountBuffer`), only once the consumer has waited - /// for that build and read the count back (docs/API.md); without that wait it is stale. 0 for - /// a primitive structure. - pub instance_count: u32, -} - -/// What is bound at a buffer slot. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub enum BoundBuffer { - /// A buffer at an offset. - Buffer { - /// The allocation length (the consumer pads the backing `VkBuffer` to 16 bytes). - length: u64, - offset: u64, - /// The Metal `gpuAddress` the guest sees. - gpu_address: u64, - /// The host Vulkan device address, when the buffer has one. - device_address: Option, - /// `setVertexBuffer:offset:attributeStride:`. - attribute_stride: Option, - }, - /// `set*Bytes`: inline bytes the consumer uploads. - Bytes { - len: u32, - /// `setVertexBytes:length:attributeStride:atIndex:` (and a compute encoder's - /// `setBytes:length:attributeStride:atIndex:`): the stride a layout of - /// `MTLBufferLayoutStrideDynamic` reads the bytes at; `None` for the plain setters, which - /// such a layout reads at stride 0, as plain Metal reads them. - /// `MTLAttributeStrideStatic` is `Some(u32::MAX)`, its low 32 bits: an M4 read element 0 - /// of inline bytes bound so and zeros past it, which the pulled fetch, a vertex - /// attribute's or a kernel stage-in's, reads at that stride (every element past the first - /// lies past the bytes). - #[cfg_attr(feature = "serde", serde(default))] - attribute_stride: Option, - }, -} - -/// What is bound at a texture slot. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub enum BoundTexture { - /// An image texture. - Texture { - facts: TextureFacts, - /// The guest `gpuResourceID`. - resource_id: Option, - }, - /// A texture buffer: a texel view of a buffer range. - Buffer { - pixel_format: metal::PixelFormat, - offset: u64, - length: u64, - bytes_per_row: u64, - resource_id: Option, - /// `MTLTexture.swizzle`: the source of each channel a function's reads of it return. - #[cfg_attr(feature = "serde", serde(default))] - swizzle: metal::TextureSwizzleChannels, - /// The texel buffer views its texels take on the device: 1 within the device's - /// `maxTexelBufferElements`, else its parts (`bind::texel_parts`), which a slot - /// whose function reads them so binds through its parts variant - /// (`VariantKey::texel_buffer_parts`). - #[cfg_attr(feature = "serde", serde(default = "one_part"))] - parts: u32, - }, -} - /// The view facts of an image texture. #[non_exhaustive] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] @@ -886,25 +122,6 @@ pub struct TextureFacts { /// (`SpecKey::OffsetBaseAxes`, [`TextureFacts::offset_base_axes`]). #[cfg_attr(feature = "serde", serde(default))] pub parent_base_size: [u32; 3], - /// The texture's two planes, where a function reads them in place - /// ([`YCbCrInPlace`](crate::bind::YCbCrInPlace), the runtime's extension): a two-plane YCbCr - /// texture of a converted 4:2:0 format whose planes the consumer views as one texel buffer. - /// A slot whose function reads it only as the in-place form reads - /// (`RuntimeFact::YCbCrInPlace`) takes its in-place variant (`VariantKey::ycbcr_in_place`), - /// which binds that texel buffer ([`WriteSource::YCbCrInPlace`](crate::bind::WriteSource)) - /// and pushes these words (`PushField::YCbCrInPlace`); any other slot binds the texture's - /// image. `None` for every other texture. - #[cfg_attr(feature = "serde", serde(default))] - pub ycbcr_in_place: Option, - /// The texture's rows in a texel buffer view of its buffer's bytes, where its image is a - /// shadow ([`TexelRows`](crate::bind::TexelRows), the runtime's extension): a 2D texture over a - /// buffer the device makes no image over. A slot whose function only reads, writes or asks - /// the size of it (`RuntimeFact::TexelRows`) takes its rows variant (`VariantKey::texel_rows`), - /// which binds that view ([`WriteSource::TexelRows`](crate::bind::WriteSource)) and pushes - /// these words (`PushField::TexelRows`); any other slot binds the texture's image. `None` for - /// every other texture. - #[cfg_attr(feature = "serde", serde(default))] - pub texel_rows: Option, } impl TextureFacts { @@ -922,8 +139,6 @@ impl TextureFacts { address_modes: metal::sampler::AddressModeMap::IDENTITY, parent_relative_level: 0, parent_base_size: [0; 3], - ycbcr_in_place: None, - texel_rows: None, } } @@ -962,18 +177,8 @@ impl TextureFacts { } } -/// What is bound at a sampler slot. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct BoundSampler { - pub desc: SamplerDescriptor, - /// The guest `gpuResourceID`. - pub resource_id: Option, -} - -/// The facts of an `MTLSamplerDescriptor`. [`sampler_desc`](crate::bind::sampler_desc) maps a -/// bound one to a `vk::SamplerDesc`. +/// The facts of an `MTLSamplerDescriptor`; `metal::sampler::vk_sampler` maps one to a +/// `vk::SamplerDesc`. #[non_exhaustive] #[derive(Clone, Copy, Debug, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] @@ -1041,425 +246,12 @@ impl Default for SamplerDescriptor { } } -impl BoundSampler { - /// A sampler of `desc` without a resource id. - pub fn new(desc: SamplerDescriptor) -> BoundSampler { - BoundSampler { - desc, - resource_id: None, - } - } -} - -/// A resource made resident with `useResource`/`useHeap`, or otherwise live in the guest task. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct UsedResource { - pub class: ResourceClass, - /// The Metal `gpuAddress` (buffers and heaps). - pub gpu_address: Option, - pub length: u64, - /// The host Vulkan device address, when it has one. - pub device_address: Option, - pub usage: metal::ResourceUsage, - /// Render stages; empty in compute encoders. - pub stages: metal::RenderStages, - /// The consumer's id for the resource; plans refer to it (`UseTarget::Used`, - /// `HeapSource::Used`). - pub token: u32, - /// The guest `gpuResourceID`. - pub resource_id: Option, -} - -impl UsedResource { - /// A used resource of `class` with the consumer's `token`: no addresses, length 0, no usage - /// or stages, no resource id. The fields are public; set the ones that apply. - pub fn new(class: ResourceClass, token: u32) -> UsedResource { - UsedResource { - class, - gpu_address: None, - length: 0, - device_address: None, - usage: metal::ResourceUsage::default(), - stages: metal::RenderStages::default(), - token, - resource_id: None, - } - } -} - -/// What kind of resource a [`UsedResource`] is. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub enum ResourceClass { - Buffer, - Texture(TextureFacts), - Heap, -} - -/// The length class of an allocation of `length` bytes: the bit length of its padded length, so -/// `padded(length) < 2^class`. A plan compares `2^class - 1` with a descriptor range limit to know -/// that every range of the buffer fits it without the exact length, which is per-draw data. A -/// buffer's shape states it as its stage table's [`BufferRanges`] tell it apart. -pub fn length_class(length: u64) -> u8 { - let padded = u128::from(length).next_multiple_of(16); - (u128::BITS - padded.leading_zeros()) as u8 -} - -/// The range limit of a device's buffer views (`maxStorageBufferRange`, [`BufferRanges::of`]), the -/// only value a plan compares a bound buffer's length class with (whether every range of the -/// buffer fits it), which the plan's caller sets on each stage table -/// ([`StageTable::buffer_ranges`]); the runtime builds no stage table. A buffer's shape tells apart only the classes that comparison tells apart -/// ([`BufferRanges::length_class`]), so buffers of lengths the device's limit does not tell apart -/// bind one shape and take one plan, as a stream of dispatches over buffers of many sizes binds -/// them. The default, 0, tells every class apart. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct BufferRanges { - /// `maxStorageBufferRange`. - pub storage: u32, -} - -impl BufferRanges { - /// The range limit of a device of `limits`. - pub fn of(limits: &Limits) -> BufferRanges { - BufferRanges { - storage: limits.max_storage_buffer_range, - } - } - - /// The length class a buffer's shape states of an allocation of `length` bytes - /// ([`BufferShape::Buffer`]'s `length_class`): its exact class rounded up to the greatest - /// class whose every range fits the limit, where it fits, so a plan's comparison of the class - /// with the limit answers as the exact class's does; a class past the limit is its own. - /// Rounded up, the class still bounds the padded length (`padded(length) < 2^class`), so under - /// a limit other than its device's no plan reads a range past it either: it may take only the - /// form a longer buffer takes. - pub fn length_class(&self, length: u64) -> u8 { - let class = length_class(length); - let widest = widest_class(self.storage); - if class <= widest { - widest - } else { - class - } - } -} - -/// The greatest length class whose every range fits a limit of `limit` bytes: -/// `2^class - 1 <= limit`. -fn widest_class(limit: u32) -> u8 { - (u64::from(limit) + 1).ilog2() as u8 -} - -/// The projection of a [`BindState`] that can change a [`BindingPlan`](super::plan::BindingPlan): -/// which slots are bound and with what kind of resource, texture types and formats, sampler modes, -/// threadgroup lengths, inline bytes, per-bind strides, buffer length and bind-offset alignment -/// classes, the used resources' classes, usages, and stages by consumer token, the vertex -/// amplification, the imageblock size, the render pass's render target array length, whether a -/// tessellation factor buffer is set, a tile dispatch's render area, and the tile threadgroup -/// memory. Hashable; plans memoize on `(PipelineKey, BindShape)`. -#[non_exhaustive] -#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct BindShape { - pub stages: BTreeMap, - /// `BindState.used_resources` by consumer token: what a plan lists in its `uses` for the - /// resources a function can reach through the root or handle table. - pub used: BTreeMap, - /// `BindState.vertex_amplification`: a render plan's views and amplification count. - #[cfg_attr(feature = "serde", serde(default))] - pub vertex_amplification: VertexAmplification, - /// `BindState.imageblock_size`: a compute plan's imageblock specialization. - #[cfg_attr(feature = "serde", serde(default))] - pub imageblock_size: ImageblockSize, - /// `BindState.render_target_array_length`: whether a vertex function's render target slice - /// renders into one layer (0 or 1) or selects among layers. - #[cfg_attr(feature = "serde", serde(default))] - pub render_target_array_length: u32, - /// The encoder set a tessellation factor buffer (`BindState.tessellation_factors`): a patch - /// draw's control stage reads it, or a zero buffer. - #[cfg_attr(feature = "serde", serde(default))] - pub tessellation_factor_buffer: bool, - /// `BindState.render_area`: a tile dispatch's render area specialization. - #[cfg_attr(feature = "serde", serde(default))] - pub render_area: [u32; 2], - /// `BindState.argument_samplers`: the sampler arrays' and tables' length class and the - /// samplers' shapes. - #[cfg_attr(feature = "serde", serde(default))] - pub argument_samplers: ArgumentSamplersShape, - /// `BindState.function_tables`: the function-table directories' length class. - #[cfg_attr(feature = "serde", serde(default))] - pub function_tables: FunctionTablesShape, - /// `BindState.tile_threadgroup`: a tile function's threadgroup offsets and tile memory - /// specialization. - #[cfg_attr(feature = "serde", serde(default))] - pub tile_threadgroup: TileThreadgroupMemory, - /// `BindState.zeroed_colors`: the variant whose pipeline has those attachments and whose - /// fragment function writes zero to them (`VariantKey::zeroed_colors`). - #[cfg_attr(feature = "serde", serde(default))] - pub zeroed_colors: BTreeMap, - /// `BindState.dropped_colors`: the variant whose fragment function keeps no output at them - /// (`VariantKey::dropped_colors`). - #[cfg_attr(feature = "serde", serde(default))] - pub dropped_colors: BTreeSet, - /// `BindState.kept_imageblock_bytes`: the variant whose tile function reads its explicit - /// imageblock's words past them as zero and writes them nowhere - /// (`VariantKey::kept_imageblock_bytes`). - #[cfg_attr(feature = "serde", serde(default))] - pub kept_imageblock_bytes: Option, - /// Whether `BindState.depth_clamp_range` is set: the variant whose fragment function clamps - /// the depth it writes to the draw's range itself (`VariantKey::depth_clamp_range`). - #[cfg_attr(feature = "serde", serde(default))] - pub depth_clamp_range: bool, - /// `BindState.rotated_weights`: the variant whose fragment function takes Metal's barycentric - /// weights back from triangles drawn with Metal's last vertex first - /// (`VariantKey::rotated_weights`). - #[cfg_attr(feature = "serde", serde(default))] - pub rotated_weights: bool, - /// What `BindState.line_band` draws as bands: the variant that draws its lines, or its - /// triangles' edges, so (`VariantKey::line_band`). - #[cfg_attr(feature = "serde", serde(default))] - pub line_band: Option, - /// `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))] - pub primitive_id_indices: Option, - /// `BindState.quad_primitive_ids`: a draw of Metal's private quads or quad strip, whose - /// pipeline's fragment function reads `[[primitive_id]]` from Vulkan's `PrimitiveId`, runs the - /// variant that reads the quad's (`VariantKey::quad_primitive_ids`). - #[cfg_attr(feature = "serde", serde(default))] - pub quad_primitive_ids: bool, - /// `BindState.private_list`: a draw of one of Metal's private primitive types in the pulled - /// list form runs the variant that draws it so (`VariantKey::private_list`). - #[cfg_attr(feature = "serde", serde(default))] - pub private_list: bool, - /// `BindState.far_vertex_buffers`: the layouts a draw pulls where the device's fixed-function - /// input cannot fetch them for it (past 4 GiB on a wrapping driver, or every one of a draw - /// replay's), in the pulled-vertex-buffer variant (`VariantKey::pulled_vertex_buffers`). - #[cfg_attr(feature = "serde", serde(default))] - pub far_vertex_buffers: BTreeSet, - /// `BindState.region_viewports`: a draw of a rate-mapped pass's regions several at a time - /// runs the variant whose vertex function stores `ViewportIndex` as `DrawIndex` - /// (`VariantKey::region_viewports`). - #[cfg_attr(feature = "serde", serde(default))] - pub region_viewports: bool, -} - -impl BindShape {} - -/// The projection of `BindState::argument_samplers` that can change a plan: the capacity class of -/// the list's length, and the distinct shapes of its samplers. A plan holds -/// [`ArgumentSamplersShape::entries`] entries in each sampler table and sampler array, so a -/// sampler made or released changes the shape (and needs a new plan) only when the count leaves -/// its class or the last sampler of a shape goes or a new shape comes; every other change is -/// per-draw bytes and the per-draw resolution of `WriteSource::ArgumentSampler`. -#[non_exhaustive] -#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct ArgumentSamplersShape { - /// The capacity class: the list's length plus the null entry is at most - /// `MIN_ENTRIES << class` (the least such class). - pub class: u8, - /// The distinct shapes of the listed samplers: every one is checked for every use of a plan's - /// sampler arrays (`metal::sampler::check_argument_sampler`), and an opaque-black border meets - /// every member a sampled heap array holds. - pub shapes: std::collections::BTreeSet, -} - -impl ArgumentSamplersShape { - /// The least entries of a class: a sampler table never holds fewer. - pub const MIN_ENTRIES: u64 = 16; - - /// The shape of the argument samplers `samplers`. - pub fn of(samplers: &[ArgumentSampler]) -> ArgumentSamplersShape { - ArgumentSamplersShape { - class: capacity_class(samplers.len()), - shapes: samplers.iter().map(|s| s.desc.shape()).collect(), - } - } - - /// The entries of the class (the null entry included): `MIN_ENTRIES << class`. - pub fn entries(&self) -> u64 { - Self::MIN_ENTRIES << self.class - } - - /// The least count of samplers plus the null entry a list of this class has: one more than - /// the previous class's entries. - pub fn least_count(&self) -> u64 { - least_count(self.class) - } -} - -/// The least capacity class (`MIN_ENTRIES << class` entries) that holds `len` listed objects -/// plus the null entry. -fn capacity_class(len: usize) -> u8 { - let count = len as u64 + 1; - let mut class = 0u8; - while (ArgumentSamplersShape::MIN_ENTRIES << class) < count { - class += 1; - } - class -} - -/// The least count of listed objects plus the null entry of capacity class `class`: one more -/// than the previous class's entries. -fn least_count(class: u8) -> u64 { - match class { - 0 => 1, - c => (ArgumentSamplersShape::MIN_ENTRIES << (c - 1)) + 1, - } -} - -/// The projection of `BindState::function_tables` that can change a plan: the capacity class of the -/// list's length, as [`ArgumentSamplersShape`]'s. A plan holds [`FunctionTablesShape::entries`] -/// entries in each function-table directory, so a table made or released changes the shape only -/// when the count leaves its class. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct FunctionTablesShape { - /// The capacity class: the list's length plus the null entry is at most - /// `ArgumentSamplersShape::MIN_ENTRIES << class` (the least such class). - pub class: u8, - /// The listed tables' bytes as the function-table snapshot holds them (the null record, - /// then each table's word count and words), at least any one table's words: 0 where they are - /// fewer than `2^27`, Vulkan's least `maxStorageBufferRange`, which every device reaches, else - /// their bit length, so that no listed table, nor the snapshot, passes a range of - /// `2^bytes_class - 1` or more ([`FunctionTablesShape::may_pass`]). A table made or released - /// changes it only when those bytes leave their power of two past 128 MiB. - #[cfg_attr(feature = "serde", serde(default))] - pub bytes_class: u8, -} - -impl FunctionTablesShape { - /// The bit length of Vulkan's least `maxStorageBufferRange`, `2^27` bytes: tables of fewer - /// bytes fit every device's ([`FunctionTablesShape::bytes_class`] 0). - const EVERY_RANGE_BITS: u32 = 27; - - /// The shape of the tables `tables`. - pub fn of(tables: &[ArgumentFunctionTable]) -> FunctionTablesShape { - let bytes = tables.iter().fold(4u64, |bytes, t| { - bytes.saturating_add(4 * (u64::from(t.size) + 3)) - }); - let bits = u64::BITS - bytes.leading_zeros(); - FunctionTablesShape { - class: capacity_class(tables.len()), - bytes_class: match bits <= Self::EVERY_RANGE_BITS { - true => 0, - false => bits as u8, - }, - } - } - - /// Whether a listed table's words, or their snapshot, may pass `max_storage_buffer_range` - /// bytes: whether `2^bytes_class - 1` does, never for class 0. - pub fn may_pass(&self, max_storage_buffer_range: u32) -> bool { - if self.bytes_class == 0 { - return false; - } - let most = 1u128 - .checked_shl(u32::from(self.bytes_class)) - .map_or(u128::MAX, |b| b - 1); - most > u128::from(max_storage_buffer_range) - } - - /// The entries of the class (the null entry included). - pub fn entries(&self) -> u64 { - ArgumentSamplersShape::MIN_ENTRIES << self.class - } - - /// The least count of tables plus the null entry a list of this class has. - pub fn least_count(&self) -> u64 { - least_count(self.class) - } -} - -/// The shape of one used resource: what a plan's `uses` states about it. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct UsedShape { - pub class: UsedClass, - pub usage: metal::ResourceUsage, - /// Render stages; empty in compute encoders. - pub stages: metal::RenderStages, -} - -/// The kind of a used resource; a texture with its view facts (a heap member's element and -/// views depend on them). -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub enum UsedClass { - Buffer, - Texture(TextureShape), - Heap, -} - -impl UsedClass { - /// The kind of a used resource of `class`. - fn of(class: ResourceClass) -> UsedClass { - match class { - ResourceClass::Buffer => UsedClass::Buffer, - ResourceClass::Texture(facts) => UsedClass::Texture(facts.shape()), - ResourceClass::Heap => UsedClass::Heap, - } - } -} - -/// The shape of one stage's argument tables. -#[non_exhaustive] -#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct StageShape { - pub buffers: BTreeMap, - pub textures: BTreeMap, - pub samplers: BTreeMap, - pub threadgroup_lengths: BTreeMap, -} - -/// The shape of a bound buffer. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub enum BufferShape { - Buffer { - /// The per-bind stride (`setVertexBuffer:offset:attributeStride:`): whether fixed-function - /// vertex input can fetch with it decides the pulled-vertex-buffer variant. - attribute_stride: Option, - device_address: bool, - /// The length class of the allocation as its stage table's buffer ranges tell it apart - /// ([`BufferRanges::length_class`]), as [`BindState::shape`] computes it. - length_class: u8, - /// The alignment class of the bind offset, as [`BindState::shape`] computes it: the - /// largest power of two up to 4 that divides it. - offset_alignment: u32, - }, - /// Inline bytes (`set*Bytes`). - Bytes { - /// The per-bind stride ([`BoundBuffer::Bytes`]), which decides the pulled-vertex-buffer - /// variant as a buffer's does. - #[cfg_attr(feature = "serde", serde(default))] - attribute_stride: Option, - }, -} - /// The level count of a texture shape stated without one. #[cfg(feature = "serde")] fn one_level() -> u32 { 1 } -/// The views of a texture buffer stated without them: one. -#[cfg(feature = "serde")] -fn one_part() -> u32 { - 1 -} - /// The shape of a bound texture. #[non_exhaustive] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] @@ -1498,133 +290,15 @@ pub enum TextureShape { /// rule specializes on them (`SpecKey::OffsetBaseAxes`). #[cfg_attr(feature = "serde", serde(default))] offset_base_axes: u8, - /// The texture's planes are read in place where a slot's function reads them so - /// ([`TextureFacts::ycbcr_in_place`]): such a slot takes its in-place variant - /// (`VariantKey::ycbcr_in_place`). - #[cfg_attr(feature = "serde", serde(default))] - ycbcr_in_place: bool, - /// The device's conversion of the texture's planes, where the consumer holds them as an - /// image it samples ([`YCbCrInPlace::planes_sampler`](crate::bind::YCbCrInPlace)): a slot - /// whose every sample the device's sampler takes samples that image - /// (`VariantKey::ycbcr_planes_sampled`). - #[cfg_attr(feature = "serde", serde(default))] - ycbcr_planes_sampler: Option, - /// The texture's rows are read and written in place where a slot's function only reads, - /// writes or asks the size of it ([`TextureFacts::texel_rows`]): such a slot takes its - /// rows variant (`VariantKey::texel_rows`). - #[cfg_attr(feature = "serde", serde(default))] - texel_rows: bool, - }, - Buffer { - pixel_format: metal::PixelFormat, - /// The texture buffer's swizzle (`BoundTexture::Buffer`'s): a slot whose reads apply it - /// specializes on it (`SpecKey::TextureSwizzle`). - #[cfg_attr(feature = "serde", serde(default))] - swizzle: metal::TextureSwizzleChannels, - /// The texel buffer views its texels take (`BoundTexture::Buffer`'s): past 1, a slot whose - /// function reads them through its parts (`RuntimeFact::TexelBufferParts`) takes the - /// parts variant (`VariantKey::texel_buffer_parts`). - #[cfg_attr(feature = "serde", serde(default = "one_part"))] - parts: u32, }, } impl TextureShape { - /// The bound texture's pixel format. - pub(crate) fn pixel_format(&self) -> metal::PixelFormat { - match *self { - TextureShape::Texture { pixel_format, .. } - | TextureShape::Buffer { pixel_format, .. } => pixel_format, - } - } - - /// The `SpecKey::OutOfBoundsAlpha` of a slot bound to this texture: 1 where an - /// out-of-bounds read of its pixel format reads alpha 1. `None` for a placeholder pixel format, - /// which has no sampled type, so no declared texture is compatible with it and the slot reads - /// its neutral. - pub(crate) fn out_of_bounds_alpha(&self) -> Option { - crate::metal::format::out_of_bounds_alpha_one(self.pixel_format()).map(u64::from) - } - - /// The `SpecKey::BorderTexels` of a slot bound to this texture: Metal's border texels of its - /// pixel format and swizzle (`metal::sampler::border_texels`). `None` for a placeholder pixel - /// format, whose slot reads its neutral. - pub(crate) fn border_texels(&self) -> Option { - crate::metal::sampler::border_texels(self.pixel_format(), self.swizzle()).map(u64::from) - } - - /// The bound texture's swizzle: a texture's or a texture buffer's. + /// The texture's swizzle. pub(crate) fn swizzle(&self) -> metal::TextureSwizzleChannels { - match *self { - TextureShape::Texture { swizzle, .. } | TextureShape::Buffer { swizzle, .. } => swizzle, - } + let TextureShape::Texture { swizzle, .. } = *self; + swizzle } - - /// The `SpecKey::OffsetBaseAxes` of a slot bound to this texture - /// ([`TextureFacts::offset_base_axes`]); a texture buffer's 0. - pub(crate) fn offset_base_axes(&self) -> u64 { - match *self { - TextureShape::Texture { - offset_base_axes, .. - } => u64::from(offset_base_axes), - TextureShape::Buffer { .. } => 0, - } - } - - /// The `SpecKey::ConstantLanes` of a slot bound to this texture: where the texture is sparse, - /// the lanes its format and swizzle make constants (`metal::sampler::constant_lanes`), which - /// the function sets after a sampled read whose texels a block that holds no mapped tile may - /// answer the device's value for; 0 elsewhere, where the device reads those lanes as Metal - /// does, and for a format whose channels are not stated (a depth or stencil format). - pub(crate) fn constant_lanes(&self) -> u64 { - match *self { - TextureShape::Texture { - pixel_format, - sparse: true, - swizzle, - .. - } => crate::metal::format::channels(pixel_format).map_or(0, |present| { - u64::from(crate::metal::sampler::constant_lanes(present, swizzle)) - }), - TextureShape::Texture { .. } | TextureShape::Buffer { .. } => 0, - } - } - - /// Whether the bound texture is sparse (`MTLTexture.isSparse`); a texture buffer never is. - pub(crate) fn sparse(&self) -> bool { - matches!(self, TextureShape::Texture { sparse: true, .. }) - } - - /// This shape with a level count of 1: what a heap member's shape is checked by (a heap - /// array views level 0 alone). - pub(crate) fn at_one_level(mut self) -> TextureShape { - if let TextureShape::Texture { - mipmap_level_count, .. - } = &mut self - { - *mipmap_level_count = 1; - } - self - } -} - -/// The shape of a sampler bound to a slot: its descriptor's [`SamplerShape`], its state word, which -/// the slot's `SpecKey::SamplerState` specialization masks by the fields its function reads, and -/// the level its `SpecKey::SamplerMinLevel` specialization states. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct BoundSamplerShape { - pub shape: SamplerShape, - pub word: metal::sampler::SamplerWord, - /// `metal::sampler::query_min_level` of the descriptor: the level, in sixty-fourths, that - /// Metal's `calculate_clamped_lod` answers outside a fragment function before the texture's - /// last level bounds it. - pub min_level: u32, - /// `metal::sampler::anisotropy_degree` of the descriptor: `log2` of the degree Metal filters - /// with, which the slot's `SpecKey::SamplerAnisotropy` specialization states. - #[cfg_attr(feature = "serde", serde(default))] - pub degree: u32, } /// The shape of a sampler: the modes that are runtime facts, and the descriptor values that decide diff --git a/crates/metal2vulkan/src/bind/status.rs b/crates/metal2vulkan/src/bind/status.rs index 08207ce9b..7b3de49e2 100644 --- a/crates/metal2vulkan/src/bind/status.rs +++ b/crates/metal2vulkan/src/bind/status.rs @@ -1,65 +1,9 @@ //! `ExecutionStatus` buffer layout: word indices and status bits. //! -//! One 16-byte buffer per command buffer, shared by every plan in it. The consumer initializes it -//! with [`ExecutionStatus::initial`] before the command buffer's first use and reads it back with -//! [`ExecutionStatus::decode`] after the last one (a `SHADER_WRITE -> HOST_READ` barrier first); -//! the resident-set miss counter, the index -//! bounds pass, an absent argument's read, a mesh draw's arguments pass, a sample -//! through a cubic argument sampler, and a sequentially consistent fence write the -//! words named here. - -/// The `ExecutionStatus` buffer. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub struct ExecutionStatus; - -impl ExecutionStatus { - /// Size of the buffer in bytes. - pub const BYTES: usize = 16; - - /// The buffer's initial bytes: every word 0. - pub const fn initial() -> [u8; ExecutionStatus::BYTES] { - [0; ExecutionStatus::BYTES] - } - - /// What the buffer's bytes report after the command buffer ran. The consumer maps a mesh grid - /// Metal's GPU discards or the device cannot launch, and a cubic argument sampler's sample, to a - /// command-buffer execution error, and treats resident-set misses by its own policy. - pub fn decode(bytes: &[u8; ExecutionStatus::BYTES]) -> StatusReport { - let word = |w: StatusWord| { - let at = w.byte_offset() as usize; - u32::from_le_bytes([bytes[at], bytes[at + 1], bytes[at + 2], bytes[at + 3]]) - }; - let bits = StatusBits(word(StatusWord::Status)); - StatusReport { - resident_miss: bits.contains(StatusBits::RESIDENT_MISS), - resident_misses: word(StatusWord::ResidentMisses), - cubic_argument_sampler: bits.contains(StatusBits::CUBIC_ARGUMENT_SAMPLER), - mesh_grid_discarded: bits.contains(StatusBits::MESH_GRID_DISCARDED), - mesh_grid_past_limits: bits.contains(StatusBits::MESH_GRID_PAST_LIMITS), - } - } -} - -/// What an `ExecutionStatus` buffer reports. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] -pub struct StatusReport { - /// An access missed the resident set. - pub resident_miss: bool, - /// The number of resident-set misses counted (a `u32` the device increments, wrapping after - /// `2^32` misses). - pub resident_misses: u32, - /// A function sampled through an argument buffer's sampler whose min or mag filter is - /// `Cubic`, whose bicubic filter it does not emulate there - /// (`RuntimeFact::CubicArgumentSampler`): no result of the command buffer is then Metal's. - pub cubic_argument_sampler: bool, - /// An indirect mesh draw's arguments pass met an object grid that Metal's GPU discards (`StatusBits::MESH_GRID_DISCARDED`): that draw drew - /// nothing, and the command buffer fails as Metal's does (`MTLCommandBufferErrorInternal`). - pub mesh_grid_discarded: bool, - /// An indirect mesh draw's arguments pass met a grid that Metal draws and the device cannot launch (`StatusBits::MESH_GRID_PAST_LIMITS`): - /// that draw drew nothing, and the command buffer fails (not Metal's failure). - pub mesh_grid_past_limits: bool, -} +//! One 16-byte buffer per command buffer, shared by every pipeline in it, which the consumer +//! zeroes before the command buffer's first use; the resident-set miss counter, an absent +//! argument's read, a sample through a cubic argument sampler, and a sequentially consistent +//! fence write the words named here. /// A word of the `ExecutionStatus` buffer. #[non_exhaustive] @@ -105,92 +49,4 @@ impl StatusBits { /// (`RuntimeFact::CubicArgumentSampler`): its result is the device's through a nearest /// placeholder, not Metal's. pub const CUBIC_ARGUMENT_SAMPLER: StatusBits = StatusBits(1 << 3); - /// An indirect mesh draw's arguments pass met a grid that Metal draws and the device cannot - /// launch: a mesh grid past the mesh stage's limits, an unfolded object grid past the task - /// stage's, or a folded one of more pieces than `MeshArguments::OBJECT_PIECES` (only under task - /// limits below Vulkan's required least); the draw drew nothing (`bind::MeshArguments`). - pub const MESH_GRID_PAST_LIMITS: StatusBits = StatusBits(1 << 4); - /// An indirect mesh draw's arguments pass met an object grid of more threadgroups than - /// `bind::METAL_OBJECT_GRID_TOTAL`, which Metal's GPU discards; the draw drew nothing - /// (`bind::MeshArguments`). - pub const MESH_GRID_DISCARDED: StatusBits = StatusBits(1 << 5); - /// Every bit in `other` is set in `self`. - pub const fn contains(self, other: StatusBits) -> bool { - self.0 & other.0 == other.0 - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn words_are_distinct_and_inside_the_buffer() { - let words = [ - StatusWord::Status, - StatusWord::ResidentMisses, - StatusWord::SeqCstFences, - ]; - for (i, w) in words.iter().enumerate() { - assert!( - words[..i].iter().all(|other| other.index() != w.index()), - "{w:?}" - ); - assert_eq!(w.byte_offset(), 4 * w.index(), "{w:?}"); - assert!( - w.byte_offset() as usize + 4 <= ExecutionStatus::BYTES, - "{w:?}" - ); - } - assert_eq!( - StatusWord::SeqCstFences.byte_offset() as usize + 4, - ExecutionStatus::BYTES - ); - } - - #[test] - fn status_bits_are_distinct() { - let bits = [ - StatusBits::RESIDENT_MISS, - StatusBits::CUBIC_ARGUMENT_SAMPLER, - StatusBits::MESH_GRID_PAST_LIMITS, - StatusBits::MESH_GRID_DISCARDED, - ]; - let mut all = 0u32; - for b in bits { - assert_eq!(b.0.count_ones(), 1); - assert_eq!(all & b.0, 0); - all |= b.0; - } - assert!(StatusBits(all).contains(StatusBits::CUBIC_ARGUMENT_SAMPLER)); - assert!(!StatusBits::RESIDENT_MISS.contains(StatusBits::CUBIC_ARGUMENT_SAMPLER)); - } - - /// The initial bytes are all zero, and `decode` of them reports nothing. - #[test] - fn initial_bytes_are_zero_and_decode_clean() { - let bytes = ExecutionStatus::initial(); - assert!(bytes.iter().all(|&b| b == 0)); - assert_eq!(ExecutionStatus::decode(&bytes), StatusReport::default()); - } - - #[test] - fn decode_reports_every_bit_and_counter() { - let mut bytes = [0u8; ExecutionStatus::BYTES]; - let bits = StatusBits::CUBIC_ARGUMENT_SAMPLER.0 | StatusBits::RESIDENT_MISS.0; - bytes[0..4].copy_from_slice(&bits.to_le_bytes()); - bytes[4..8].copy_from_slice(&7u32.to_le_bytes()); - let r = ExecutionStatus::decode(&bytes); - assert!(r.cubic_argument_sampler && r.resident_miss); - assert_eq!(r.resident_misses, 7); - bytes = [0u8; ExecutionStatus::BYTES]; - bytes[0..4].copy_from_slice(&StatusBits::CUBIC_ARGUMENT_SAMPLER.0.to_le_bytes()); - let r = ExecutionStatus::decode(&bytes); - assert!(r.cubic_argument_sampler && !r.resident_miss); - assert_eq!(r.resident_misses, 0); - let mut cubic = [0u8; ExecutionStatus::BYTES]; - cubic[0..4].copy_from_slice(&StatusBits::CUBIC_ARGUMENT_SAMPLER.0.to_le_bytes()); - let c = ExecutionStatus::decode(&cubic); - assert!(c.cubic_argument_sampler && !c.resident_miss); - } } diff --git a/crates/metal2vulkan/src/bind/table.rs b/crates/metal2vulkan/src/bind/table.rs index 563270a3b..f3799a457 100644 --- a/crates/metal2vulkan/src/bind/table.rs +++ b/crates/metal2vulkan/src/bind/table.rs @@ -1,97 +1,19 @@ -//! The buffer a visible-function table is bound as. +//! The words of a visible-function table's buffer, as the tests build them. //! //! A `visible_function_table` argument compiles to a read-only buffer at its Metal buffer index -//! (`pipeline::table` has the word layout), so the binder binds a table like any other buffer: -//! `setVisibleFunctionTable:atBufferIndex:` is a [`BoundBuffer::Buffer`] at that index of the -//! stage's table ([`StageTable::buffers`]), over a buffer the consumer owns for the -//! `MTLVisibleFunctionTable` and fills with the table's words. The shader reads its words -//! through the buffer slot only, never through the guest address, so the bound buffer's -//! `gpu_address` is not read for it. `setVisibleFunctionTable:nil` binds nothing: the slot gets -//! the plan's zero-filled neutral, whose word 0 makes `is_null_visible_function_table` true. -//! `setFunction:atIndex:` writes one entry: the word of the function's -//! [`FunctionHandle`] (`LinkedFunctions::function_handle` of the stage the table belongs to), or -//! [`FunctionHandle::NULL_WORD`] for a null entry. -//! -//! [`BoundBuffer::Buffer`]: crate::bind::BoundBuffer::Buffer -//! [`StageTable::buffers`]: crate::bind::StageTable::buffers +//! (`pipeline::table` has the word layout): `setVisibleFunctionTable:atBufferIndex:` binds a +//! buffer the consumer owns for the `MTLVisibleFunctionTable` and fills with the table's words. +//! The shader reads its words through the buffer slot only, never through the guest address, so +//! the bound buffer's `gpu_address` is not read for it. A slot bound to no table reads zeros, +//! whose word 0 makes `is_null_visible_function_table` true. `setFunction:atIndex:` writes one +//! entry: the word of the function's `FunctionHandle` (`LinkedFunctions::function_handle` of the +//! stage the table belongs to), or `FunctionHandle::NULL_WORD` for a null entry. -use crate::air::canon::function_table::FIRST_ENTRY_WORD; #[cfg(test)] -use crate::air::canon::function_table::{PRESENT_WORD, SIZE_WORD}; +use crate::air::canon::function_table::{FIRST_ENTRY_WORD, PRESENT_WORD, SIZE_WORD}; #[cfg(test)] use crate::pipeline::table::FunctionHandle; -/// The function-table snapshot: the words of a command's listed tables -/// (`BindState::function_tables`) in one read-only storage buffer, which the consumer writes as the -/// command's command buffer commits -/// ([`WriteSource::FunctionTableSnapshot`](crate::bind::WriteSource::FunctionTableSnapshot)). -/// -/// Word 0 is the null table's record: a word count of 0. Listed table `i`'s record follows the -/// records before it: its word count (its buffer's words: the table's header words and one -/// entry word for each of its size), then those words. The stage's function-table directory gives each listed -/// nonzero id the offset of its record's first word, and the null id and every id the directory -/// misses the null table's, 0: a read of word `w` of a table reads its record's word `1 + w` -/// below the record's count, and 0 at or past it. -#[derive(Clone, Debug, PartialEq, Eq, Hash)] -pub struct FunctionTableSnapshot { - /// The word offset of each listed table's record, in the list's order. - offsets: Vec, - /// The snapshot's length in words. - words: u32, -} - -impl FunctionTableSnapshot { - /// The snapshot of tables of `sizes` entries, in the list's order; `None` when it would pass - /// `u32::MAX` words. - pub fn of(sizes: impl IntoIterator) -> Option { - let mut offsets = Vec::new(); - let mut words: u32 = 1; - for size in sizes { - offsets.push(words); - let record = FIRST_ENTRY_WORD.checked_add(size)?.checked_add(1)?; - words = words.checked_add(record)?; - } - Some(FunctionTableSnapshot { offsets, words }) - } - - /// The word offset of each listed table's record, in the list's order: what the directory - /// gives its id. - pub fn offsets(&self) -> &[u32] { - &self.offsets - } - - /// The snapshot's length in bytes. - #[cfg(test)] - pub(crate) fn byte_len(&self) -> u64 { - u64::from(self.words) * 4 - } - - /// The snapshot's bytes (little-endian words), of the listed tables' buffers `tables` in the - /// list's order, each as [`FunctionTableWords::to_bytes`] gives it. `None` when `tables` is - /// not one buffer of its size's length for each listed table. - #[cfg(test)] - pub(crate) fn bytes<'a>(&self, tables: impl IntoIterator) -> Option> { - let len = usize::try_from(self.byte_len()).ok()?; - let mut out = Vec::with_capacity(len); - out.extend(0u32.to_le_bytes()); - let mut tables = tables.into_iter(); - for (i, &offset) in self.offsets.iter().enumerate() { - let end = self.offsets.get(i + 1).copied().unwrap_or(self.words); - let count = end - offset - 1; - let table = tables.next()?; - if table.len() as u64 != u64::from(count) * 4 { - return None; - } - out.extend(count.to_le_bytes()); - out.extend_from_slice(table); - } - match tables.next() { - Some(_) => None, - None => Some(out), - } - } -} - /// The words of one visible-function table's buffer: bound, its size, and its entries. #[cfg(test)] #[derive(Clone, Debug, PartialEq, Eq, Hash)] @@ -212,43 +134,6 @@ mod tests { assert_eq!(empty.size(), 0); } - /// A snapshot is the null table's record, then each table's word count and words; the - /// offsets are where each record starts, and buffers of other lengths than the sizes' make - /// none. - #[test] - fn a_snapshot_holds_each_table_after_its_word_count() { - let snapshot = FunctionTableSnapshot::of([3, 0]).expect("snapshot"); - assert_eq!(snapshot.offsets(), [1, 7]); - assert_eq!(snapshot.byte_len(), 4 * 10); - let mut t = FunctionTableWords::new(3); - assert!(t.set_opaque_triangle(1)); - let empty = FunctionTableWords::new(0); - let (t, empty) = (t.to_bytes(), empty.to_bytes()); - let bytes = snapshot - .bytes([t.as_slice(), empty.as_slice()]) - .expect("bytes"); - let words: Vec = bytes - .as_chunks::<4>() - .0 - .iter() - .map(|w| u32::from_le_bytes(*w)) - .collect(); - let entry = FunctionHandle::RESERVED_WORD; - assert_eq!(words, [0, 5, 1, 3, 0, entry, 0, 2, 1, 0]); - assert_eq!(snapshot.bytes([t.as_slice()]), None, "a table missing"); - assert_eq!( - snapshot.bytes([empty.as_slice(), t.as_slice()]), - None, - "the sizes out of order" - ); - assert_eq!( - FunctionTableSnapshot::of([]).expect("empty").byte_len(), - 4, - "the null table's record alone" - ); - assert_eq!(FunctionTableSnapshot::of([u32::MAX]), None); - } - /// An intersection function table's opaque triangle entry is the reserved word 1. #[test] fn the_opaque_triangle_entry_is_the_reserved_word() { diff --git a/crates/metal2vulkan/src/bind/texel_parts.rs b/crates/metal2vulkan/src/bind/texel_parts.rs index e3b4c7b55..64c3a05a5 100644 --- a/crates/metal2vulkan/src/bind/texel_parts.rs +++ b/crates/metal2vulkan/src/bind/texel_parts.rs @@ -5,9 +5,8 @@ //! view holds at most the device's `maxTexelBufferElements` texels //! (`VUID-VkBufferViewCreateInfo-range-00930`): 2^27 on ANV and lavapipe, 2^26 on MoltenVK. The //! consumer states with a texture buffer's binding how many parts its texels take -//! (`BoundTexture::Buffer::parts`: its texels over [`part_texels`], rounded up), which its shape carries -//! (`TextureShape::Buffer::parts`): one for every texture buffer within the limit, which binds one -//! view as it always has. +//! (its texels over [`part_texels`], rounded up): one for every texture buffer within the limit, +//! which binds one view. //! //! **The views.** Part `k` views the texels from `k · P`, `P` the device's [`part_texels`] (its //! `maxTexelBufferElements` rounded down to a multiple of its `minTexelBufferOffsetAlignment`, so @@ -19,13 +18,13 @@ //! **What a function reads.** A slot whose function reads, writes, updates by an atomic or asks //! the width of the texture buffer bound there, and does nothing else with it //! (`RuntimeFact::TexelBufferParts`), on a device that indexes arrays of its kind of texel buffer -//! by a `NonUniform` value, takes the parts variant where the shape binds more than one part -//! there (`VariantKey::texel_buffer_parts`). Under it the slot is declared as an array of its +//! by a `NonUniform` value, takes the parts variant where the bound texture buffer takes more than +//! one part (`VariantKey::texel_buffer_parts`). Under it the slot is declared as an array of its //! parts, and texel `i` is texel `i − k · P` of part `k = min(⌊i / P⌋, parts − 1)`. A texel past //! the last lies past the last part's end, so its read is Metal's out-of-bounds texel and its //! write is dropped, by the device's robustness or the function's own check as through one view. //! The width is `(parts − 1) · P` plus the last part's. Any other slot binds one view, which -//! `maxTexelBufferElements` bounds (`BindError::TexelBufferTooLarge`). +//! `maxTexelBufferElements` bounds. use crate::device::Limits; diff --git a/crates/metal2vulkan/src/bind/texel_rows.rs b/crates/metal2vulkan/src/bind/texel_rows.rs deleted file mode 100644 index dc7b01f5d..000000000 --- a/crates/metal2vulkan/src/bind/texel_rows.rs +++ /dev/null @@ -1,66 +0,0 @@ -//! A 2D texture over a buffer's rows whose image is a shadow, read and written in place through a -//! texel buffer view of the rows' bytes. -//! -//! **Where.** A texture over a buffer's bytes lies in an image over them where the device makes -//! one; where it makes none (the runtime's image refusals), the texture is a shadow, an image of -//! the runtime's own memory its commands' encoders copy the texels into and back. The buffer -//! itself is still in place. A texture in such a shadow states its rows in its facts -//! (`TextureFacts::texel_rows`), and a texture slot whose function only reads, writes or asks the -//! size of it (`RuntimeFact::TexelRows`: no sample, gather, atomic, read through a sampler or -//! level past the first) takes the slot's rows variant (`VariantKey::texel_rows`). -//! -//! **The binding.** Under the variant the slot's one descriptor is a texel buffer over the rows' -//! bytes (`WriteSource::TexelRows`), uniform where the function only reads the texture and storage -//! where it writes it, in the format a texture buffer of the texture's pixel format takes -//! (`bind::plan`'s texel formats: the format's own, an alias, or `R8_UNORM` for `A8Unorm`). Vulkan -//! states a texel buffer's texels "going through format conversion when read in a shader in the -//! same way as they are for an image" (Uniform Texel Buffer, Storage Texel Buffer), so a read -//! answers the device's conversion of the texel, as the shadow's image does. The view starts at -//! the texture's first texel, or before it where the device's texel buffer offset alignment asks: -//! the texture's size, its rows in texels and its first texel in the view are the slot's push -//! field (`PushField::TexelRows`, [`TexelRows::words`]). -//! -//! **What a function reads.** Texel `(x, y)` is the view's texel `first + y · row + x`. A read of -//! a texel outside the texture, or at a level past its one, is Metal's out-of-bounds texel, and a -//! write there is dropped, by the function's own test of the coordinate against the texture's -//! size: a coordinate past the width names a texel of the next row in the view, which the -//! device's robustness, bounding the view alone, would read. A size query answers the field's -//! size, at a level as at any texture, and the level count 1. -//! -//! **Ordering.** The slot's use is a use of the rows' bytes (`AccessClass::TexelRows`), as a -//! texture buffer's is: the consumer orders it against every use of the buffer, its shadow's -//! copies among them. A store to a texel buffer writes its texel's bytes alone (Vulkan's memory -//! model: "A memory operation must not affect memory at a memory location not within its set of -//! memory locations"), and a buffer view has no layout moves or load and store operations, so the -//! bytes between the rows keep whatever the CPU or another command writes there. - -/// A 2D texture's rows in a texel buffer view of its buffer's bytes, where its image is a shadow -/// (the module docs): the words of its slot's push field (`PushField::TexelRows`). A texture states -/// one in its facts -/// (`TextureFacts::texel_rows`), and a slot whose function only reads, writes or asks the size of -/// it (`RuntimeFact::TexelRows`) takes the rows variant (`VariantKey::texel_rows`), which binds -/// the view (`WriteSource::TexelRows`) and addresses texel `(x, y)` at `first + y · row + x`. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct TexelRows { - words: [u32; TexelRows::WORDS], -} - -impl TexelRows { - /// The words of the slot's push field ([`words`](Self::words)), one `uvec4`. - pub const WORDS: usize = 4; - /// Word: the texture's width in texels. - pub const WIDTH: usize = 0; - /// Word: the texture's height in texels. - pub const HEIGHT: usize = 1; - /// Word: the texels from one row's first to the next's in the view. - pub const ROW: usize = 2; - /// Word: the view's texel that is the texture's first. - pub const FIRST: usize = 3; - - /// The words of the slot's push field. - pub fn words(&self) -> [u32; Self::WORDS] { - self.words - } -} diff --git a/crates/metal2vulkan/src/bind/ycbcr_convert.rs b/crates/metal2vulkan/src/bind/ycbcr_convert.rs index 7a43512a2..872a697b0 100644 --- a/crates/metal2vulkan/src/bind/ycbcr_convert.rs +++ b/crates/metal2vulkan/src/bind/ycbcr_convert.rs @@ -61,9 +61,10 @@ use crate::metal::format::ChromaSubsampling; /// The range of a YCbCr surface's codes, which its pixel format names. +#[cfg(test)] #[non_exhaustive] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub enum YCbCrRange { +pub(crate) enum YCbCrRange { /// Video range: luma codes 16 to 235 span black to white (CoreVideo's `420v`). Video, /// Full range: luma codes 0 to 255 (CoreVideo's `420f`). @@ -72,9 +73,10 @@ pub enum YCbCrRange { /// The YCbCr matrix of a conversion: the surface's `IOSurfaceYCbCrMatrix` as Metal reads it when /// it makes the texture (none reads as BT.601). +#[cfg(test)] #[non_exhaustive] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub enum YCbCrMatrix { +pub(crate) enum YCbCrMatrix { /// ITU-R BT.601 (`ITU_R_601_4`, or no matrix). Bt601, /// ITU-R BT.709 (`ITU_R_709_2`). @@ -165,6 +167,7 @@ impl YCbCrCodes { /// The `(kb, kr)` of red, green and blue for `range` and `matrix`, in the units of the module /// docs' conversion (measured, the module docs). +#[cfg(test)] pub(crate) fn coefficients(range: YCbCrRange, matrix: YCbCrMatrix) -> [(i32, i32); 3] { match (range, matrix) { (YCbCrRange::Video, YCbCrMatrix::Bt601) => [(-9, 13123), (-3218, -6686), (16591, 9)], @@ -329,5 +332,20 @@ pub(crate) fn ycbcr_read( } } +/// The device's own sampler Y′CbCr conversion of a two-plane YCbCr texture's planes held as an +/// image of the multi-planar 4:2:0 format over their bytes: the codes' bits, the surface's range +/// and matrix, Metal's reconstruction (the chroma at the midpoint through a linear chroma filter) +/// and a linear filter. A slot that samples such a texture through it is a combined image sampler +/// whose immutable sampler is the device's conversion of this (`ResourceKind::YCbCrPlanes`, +/// `vk::SamplerDesc::ycbcr`); the consumer makes the image's view with the same conversion. +#[non_exhaustive] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct YCbCrPlanesSampler { + /// The conversion: the codes' bits in bits 0 to 7, full range in bit 8, and the matrix in bits + /// 9 and 10 (0 BT.601, 1 BT.709, 2 BT.2020). + pub(crate) conversion: u32, +} + #[cfg(test)] mod tests; diff --git a/crates/metal2vulkan/src/bind/ycbcr_in_place.rs b/crates/metal2vulkan/src/bind/ycbcr_in_place.rs deleted file mode 100644 index 1e40fbfcc..000000000 --- a/crates/metal2vulkan/src/bind/ycbcr_in_place.rs +++ /dev/null @@ -1,392 +0,0 @@ -//! A two-plane YCbCr texture's planes read in place: a function reads the codes from the planes' -//! own bytes and converts each texel as Metal does, where the texture's image of converted texels -//! (`ycbcr_convert`) would otherwise stand between them. -//! -//! **What it covers.** `YCBCR8_420_2P` and `YCBCR10_420_2P` (500 and 505) over a surface's two -//! planes, read converted ([`YCbCrOutput::Converted`]): the 4:2:0 layouts of unpacked codes, a -//! byte or the high 10 bits of a little-endian 16-bit word. A texture whose planes are those -//! states it in its facts (`TextureFacts::ycbcr_in_place`), and a texture -//! slot whose function reads it only as the in-place form reads -//! (`RuntimeFact::YCbCrInPlace`) takes the slot's in-place variant (`VariantKey::ycbcr_in_place`). -//! -//! **The binding.** The slot's one descriptor is a uniform texel buffer over the planes' bytes, -//! from the first byte of the first plane in memory, in `R8G8_UINT` -//! for 8-bit codes and `R16G16_UINT` for 10-bit ones, so one element holds two luma codes or one -//! chroma pair. Vulkan requires `VK_FORMAT_FEATURE_UNIFORM_TEXEL_BUFFER_BIT` of both formats on -//! every device (the specification's "Required Format Support": `R8G8_UINT` in "1-3 Byte-Sized -//! Components", `R16G16_UINT` in "16-bit Components"). The texture's size, its planes' places -//! and rows in elements, and its conversion are the slot's push field -//! (`PushField::YCbCrInPlace`, [`YCbCrInPlace::words`]). -//! -//! **What a function reads** is Metal's texel (`ycbcr_convert`'s module docs): the luma code at -//! the texel's place, the four nearest chroma pairs weighted 9/3/3/1 and rounded to a code, and -//! the conversion of the surface's range and matrix, each channel a step of `1 / 2048`, alpha 1. -//! A sample is Metal's filter of those texels on that grid (`lower::sampler::in_place`), exact, -//! as the image's emulated filter is. -//! -//! **Through the device's sampler.** Where the consumer also holds the planes as an image of the -//! multi-planar 4:2:0 format over their own bytes, which the device's sampler Y′CbCr conversion -//! reads with Metal's reconstruction (the chroma at the midpoint through a linear chroma filter), -//! the texture states it, and a slot whose every sample the -//! device's sampler takes (`RuntimeFact::YCbCrInPlace`'s `device`: no border address mode, no -//! texel offset placed by a parent's size) samples that image instead -//! (`VariantKey::ycbcr_planes_sampled`): its binding a combined image sampler whose immutable -//! sampler bakes the conversion ([`YCbCrPlanesSampler`], `ResourceKind::YCbCrPlanes`), each sample -//! the device's at level 0, a nearest one at the centre of the luma texel Metal reads. Its answer -//! is the device's conversion and filter of the codes, not Metal's. - -#[cfg(test)] -use super::ycbcr_convert::{YCbCrMatrix, YCbCrOutput, YCbCrPlanes, YCbCrRange}; -#[cfg(test)] -use crate::metal::format::ChromaSubsampling; -#[cfg(test)] -use crate::vk; - -/// A two-plane YCbCr texture's planes as a function reads them in place, where the texture's image -/// of converted texels would otherwise stand between them: the words of its slot's push field -/// (`PushField::YCbCrInPlace`), and the uniform texel buffer the slot binds over the planes' bytes -/// (`R8G8_UINT` of 8-bit codes, `R16G16_UINT` of 10-bit ones, from the first byte of the first -/// plane through the last row of codes either plane holds). A texture states one in its facts -/// (`TextureFacts::ycbcr_in_place`), and a slot whose function reads the texture only as this form -/// does (`RuntimeFact::YCbCrInPlace`) takes the in-place variant (`VariantKey::ycbcr_in_place`), -/// which fetches the codes and converts and filters them as Metal does: the luma code at the -/// texel's place, the four nearest chroma pairs weighted 9/3/3/1 and rounded to a code, the -/// surface's range and matrix, each channel a step of `1 / 2048`, alpha 1. Vulkan requires -/// `VK_FORMAT_FEATURE_UNIFORM_TEXEL_BUFFER_BIT` of both formats on every device. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct YCbCrInPlace { - words: [u32; YCbCrInPlace::WORDS], - /// The bytes the texel buffer views, from the planes' first byte: the end of the last row of - /// codes either plane holds, rounded up to a whole element. - bytes: u64, - /// The consumer holds the planes as an image the device's conversion samples. - #[cfg_attr(feature = "serde", serde(default))] - planes_image: bool, -} - -impl YCbCrInPlace { - /// The words of the slot's push field ([`words`](Self::words)), two `uvec4`s. - pub const WORDS: usize = 8; - /// Word: the texture's width in texels. - pub const WIDTH: usize = 0; - /// Word: the texture's height in texels. - pub const HEIGHT: usize = 1; - /// Word: the luma plane's first element in the texel buffer. - pub const LUMA_AT: usize = 2; - /// Word: the elements from one luma row to the next. - pub const LUMA_ROW: usize = 3; - /// Word: the chroma plane's first element in the texel buffer. - pub const CHROMA_AT: usize = 4; - /// Word: the elements from one chroma row to the next. - pub const CHROMA_ROW: usize = 5; - /// Word: the conversion: the codes' bits in bits 0 to 7, full range in bit 8, and the matrix - /// in bits 9 and 10 (0 BT.601, 1 BT.709, 2 BT.2020). - pub const CONVERSION: usize = 6; - - /// The device's conversion of the planes as an image ([`YCbCrPlanesSampler`]): their codes' - /// bits, range and matrix. - pub fn sampler(&self) -> YCbCrPlanesSampler { - YCbCrPlanesSampler { - conversion: self.words[Self::CONVERSION], - } - } - - /// [`sampler`](Self::sampler), where the consumer holds the planes as an image it samples; - /// `None` where it does not. - pub fn planes_sampler(&self) -> Option { - self.planes_image.then(|| self.sampler()) - } - - /// The words of the slot's push field. - pub fn words(&self) -> [u32; Self::WORDS] { - self.words - } - - /// The in-place form of `planes`, where a function reads them so: a - /// converted 4:2:0 layout of unpacked 8- or 10-bit codes, both planes in the bytes (a chroma - /// plane of rows; not the conversion's row of zeros), each plane's first byte and rows a - /// multiple of an element. `None` for any other: such a texture keeps its image of converted - /// texels alone. - #[cfg(test)] - pub(crate) fn of(planes: &YCbCrPlanes) -> Option { - let codes = planes.codes; - if codes.output != YCbCrOutput::Converted - || codes.subsampling != ChromaSubsampling::Chroma420 - || codes.packed - || !matches!((codes.bits, codes.bytes), (8, 1) | (10, 2)) - || planes.chroma[1] == 0 - { - return None; - } - let element = 2 * codes.bytes; - let [luma_at, luma_row] = planes.luma; - let [chroma_at, chroma_row] = planes.chroma; - if [luma_at, luma_row, chroma_at, chroma_row] - .iter() - .any(|v| v % element != 0) - { - return None; - } - let [w, h] = planes.size; - if w == 0 || h == 0 { - return None; - } - let [cw, ch] = planes.chroma_size().map(u64::from); - let unit = u64::from(codes.bytes); - let end = |at: u32, row: u32, rows: u64, bytes: u64| { - u64::from(at) + u64::from(row) * (rows - 1) + bytes - }; - let reach = end(luma_at, luma_row, u64::from(h), unit * u64::from(w)).max(end( - chroma_at, - chroma_row, - ch, - unit * 2 * cw, - )); - let bytes = reach.next_multiple_of(u64::from(element)); - let mut words = [0; Self::WORDS]; - words[Self::WIDTH] = w; - words[Self::HEIGHT] = h; - words[Self::LUMA_AT] = luma_at / element; - words[Self::LUMA_ROW] = luma_row / element; - words[Self::CHROMA_AT] = chroma_at / element; - words[Self::CHROMA_ROW] = chroma_row / element; - words[Self::CONVERSION] = conversion_word(codes.bits, planes.range, planes.matrix); - Some(YCbCrInPlace { - words, - bytes, - planes_image: false, - }) - } - - /// The form of the same planes where the consumer also holds them as an image of - /// [`sampler`](Self::sampler)'s format over their bytes, which the device's sampler Y′CbCr - /// conversion of it reads (the module docs): a slot whose every sample the device's sampler - /// takes samples that image (`VariantKey::ycbcr_planes_sampled`). - #[cfg(test)] - pub(crate) fn with_planes_image(self) -> YCbCrInPlace { - YCbCrInPlace { - planes_image: true, - ..self - } - } - - /// The codes' bits: 8 or 10. - #[cfg(test)] - pub(crate) fn bits(&self) -> u32 { - self.words[Self::CONVERSION] & 0xff - } - - /// The texel buffer's format: `R8G8_UINT` of 8-bit codes, `R16G16_UINT` of 10-bit ones. - #[cfg(test)] - pub(crate) fn format(&self) -> vk::Format { - match self.bits() { - 8 => vk::Format::R8G8_UINT, - _ => vk::Format::R16G16_UINT, - } - } - - /// The bytes of one element of the texel buffer: 2 of 8-bit codes, 4 of 10-bit ones. - #[cfg(test)] - pub(crate) fn element_bytes(&self) -> u64 { - match self.bits() { - 8 => 2, - _ => 4, - } - } - - /// The bytes the texel buffer views from the planes' first byte: through the last row of - /// codes either plane holds, a whole number of elements. - #[cfg(test)] - pub(crate) fn view_bytes(&self) -> u64 { - self.bytes - } - - /// The elements the texel buffer holds (`maxTexelBufferElements` bounds them). - #[cfg(test)] - pub(crate) fn elements(&self) -> u64 { - self.bytes / self.element_bytes() - } -} - -/// The device's own sampler Y′CbCr conversion of a two-plane YCbCr texture's planes held as an -/// image of the multi-planar 4:2:0 format over their bytes (the module docs, **Through the -/// device's sampler**): the codes' bits, the surface's range and matrix, Metal's reconstruction -/// (the chroma at the midpoint through a linear chroma filter) and a linear filter. A slot that -/// samples such a texture through it is a combined image sampler whose immutable sampler is the -/// device's conversion of this (`ResourceKind::YCbCrPlanes`, `vk::SamplerDesc::ycbcr`); the -/// consumer makes the image's view with the same conversion. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct YCbCrPlanesSampler { - /// The conversion word ([`YCbCrInPlace::CONVERSION`]). - pub(crate) conversion: u32, -} - -impl YCbCrPlanesSampler { - /// The codes' bits: 8 or 10. - #[cfg(test)] - pub(crate) fn bits(self) -> u32 { - self.conversion & 0xff - } - - /// The surface's range. - #[cfg(test)] - pub(crate) fn range(self) -> YCbCrRange { - match self.conversion >> 8 & 1 { - 1 => YCbCrRange::Full, - _ => YCbCrRange::Video, - } - } - - /// The surface's matrix. - #[cfg(test)] - pub(crate) fn matrix(self) -> YCbCrMatrix { - match self.conversion >> 9 & 3 { - 1 => YCbCrMatrix::Bt709, - 2 => YCbCrMatrix::Bt2020, - _ => YCbCrMatrix::Bt601, - } - } - - /// The multi-planar format of the planes' image: `G8_B8R8_2PLANE_420_UNORM` of 8-bit codes, - /// `G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16` of 10-bit ones (the high 10 bits of each - /// little-endian 16-bit word, as the planes hold them). - #[cfg(test)] - pub(crate) fn format(self) -> vk::Format { - match self.bits() { - 8 => vk::Format::G8_B8R8_2PLANE_420_UNORM, - _ => vk::Format::G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16, - } - } -} - -/// The conversion word ([`YCbCrInPlace::CONVERSION`]) of `bits`-bit codes of `range` and -/// `matrix`. -#[cfg(test)] -fn conversion_word(bits: u32, range: YCbCrRange, matrix: YCbCrMatrix) -> u32 { - let full = match range { - YCbCrRange::Video => 0, - YCbCrRange::Full => 1, - }; - let m = match matrix { - YCbCrMatrix::Bt601 => 0, - YCbCrMatrix::Bt709 => 1, - YCbCrMatrix::Bt2020 => 2, - }; - bits | full << 8 | m << 9 -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::bind::ycbcr_convert::YCbCrCodes; - use crate::metal::format::ycbcr_format; - use crate::metal::PixelFormat; - - fn planes(pf: PixelFormat, luma: [u32; 2], chroma: [u32; 2]) -> YCbCrPlanes { - let codes = ycbcr_format(pf).and_then(YCbCrCodes::of).expect("codes"); - YCbCrPlanes::new( - [7, 5], - luma, - chroma, - (YCbCrRange::Full, YCbCrMatrix::Bt709), - codes, - ) - } - - /// The two converted 4:2:0 formats take the form, in elements of their own width; every - /// other layout keeps its image. - #[test] - fn only_converted_four_two_zero_codes_read_in_place() { - let p8 = - YCbCrInPlace::of(&planes(PixelFormat::YCBCR84202P, [0, 16], [96, 16])).expect("8-bit"); - assert_eq!(p8.format(), vk::Format::R8G8_UINT); - assert_eq!( - p8.words(), - [ - 7, - 5, - 0, - 8, - 48, - 8, - conversion_word(8, YCbCrRange::Full, YCbCrMatrix::Bt709), - 0 - ] - ); - // The chroma plane's last row (3 rows of 4 pairs) ends at 96 + 32 + 8. - assert_eq!(p8.view_bytes(), 136); - assert_eq!(p8.elements(), 68); - let p10 = YCbCrInPlace::of(&planes(PixelFormat::YCBCR104202P, [0, 16], [96, 32])) - .expect("10-bit"); - assert_eq!(p10.format(), vk::Format::R16G16_UINT); - assert_eq!(p10.words()[YCbCrInPlace::LUMA_ROW], 4); - assert_eq!(p10.words()[YCbCrInPlace::CHROMA_AT], 24); - assert_eq!(p10.bits(), 10); - // The luma plane ends the bytes: its last row's seven codes round up to a whole element. - let tail = YCbCrInPlace::of(&planes(PixelFormat::YCBCR84202P, [64, 16], [0, 16])) - .expect("chroma first"); - assert_eq!(tail.view_bytes(), 64 + 4 * 16 + 8); - for pf in [ - PixelFormat::YCBCR84222P, - PixelFormat::YCBCR84442P, - PixelFormat::YCBCR84202PSRGB, - PixelFormat::RGB84202P, - PixelFormat::YCBCR104202PPACKED, - ] { - assert_eq!( - YCbCrInPlace::of(&planes(pf, [0, 16], [96, 16])), - None, - "{pf:?}" - ); - } - // The conversion's row of zeros is no chroma plane. - let zero = planes(PixelFormat::YCBCR84202P, [0, 16], [96, 0]); - assert_eq!(YCbCrInPlace::of(&zero), None); - } - - /// The planes' image's conversion is the codes' bits, range and matrix, of the format of - /// their bits; a texture states it only once the consumer holds the image. - #[test] - fn the_planes_sampler_is_the_conversion_word() { - let p8 = - YCbCrInPlace::of(&planes(PixelFormat::YCBCR84202P, [0, 16], [96, 16])).expect("8-bit"); - assert_eq!(p8.planes_sampler(), None); - let held = p8.with_planes_image(); - assert_eq!(held.words(), p8.words()); - let s = held.planes_sampler().expect("held"); - assert_eq!(s, p8.sampler()); - assert_eq!( - (s.bits(), s.range(), s.matrix(), s.format()), - ( - 8, - YCbCrRange::Full, - YCbCrMatrix::Bt709, - vk::Format::G8_B8R8_2PLANE_420_UNORM - ) - ); - let codes = ycbcr_format(PixelFormat::YCBCR104202P) - .and_then(YCbCrCodes::of) - .expect("codes"); - let p10 = YCbCrPlanes::new( - [8, 4], - [0, 16], - [64, 16], - (YCbCrRange::Video, YCbCrMatrix::Bt2020), - codes, - ); - let s = YCbCrInPlace::of(&p10).expect("10-bit").sampler(); - assert_eq!( - (s.bits(), s.range(), s.matrix(), s.format()), - ( - 10, - YCbCrRange::Video, - YCbCrMatrix::Bt2020, - vk::Format::G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16 - ) - ); - } -} diff --git a/crates/metal2vulkan/src/cache/codec.rs b/crates/metal2vulkan/src/cache/codec.rs index 7e8c94baf..ae71f7f66 100644 --- a/crates/metal2vulkan/src/cache/codec.rs +++ b/crates/metal2vulkan/src/cache/codec.rs @@ -885,9 +885,7 @@ codec_enum! { VerticesPerPrimitive, MergedDrawAddress, AlphaTestReference, - YCbCrInPlace(f0), LineBand, - TexelRows(f0), ArgumentTableAddress, ConstexprSampler(f0), TessellationFactorAddress, @@ -1257,12 +1255,10 @@ codec_enum! { MergedDraws, QuadPrimitiveIds, PrivateList, - YCbCrInPlace { slot, samplers, device }, PartialObjectThreadgroups, BorderTexels { slot }, RegionViewports, PartialThreadgroups, - TexelRows { slot }, UnitAxes { axes, relief }, TexelBufferParts { slot }, AddressAlignment { slot, align }, @@ -1390,9 +1386,7 @@ codec_enum! { RestrictedDepthRange, CubeGradientFootprint, HalfTexelConversion, - HalfSampleFilter, SrgbTexelDecode, - FloatSampleFilter, FunctionStorageAssumed, QuadsCountedBeforeDiscard, ViewBaseTexelOffset, diff --git a/crates/metal2vulkan/src/cache/digest.rs b/crates/metal2vulkan/src/cache/digest.rs index 76ada2c3a..3ad5e029c 100644 --- a/crates/metal2vulkan/src/cache/digest.rs +++ b/crates/metal2vulkan/src/cache/digest.rs @@ -185,360 +185,5 @@ impl Node { } } -#[cfg(feature = "serde")] -pub(crate) use serialized::node_of; - -/// The same nodes for a value through its `serde` serialization, for the types the cache does not -/// encode (a [`BindingPlan`](crate::bind::BindingPlan)). Struct and variant fields are named by -/// their serialized names, tuple fields by their positions; a map is the sequence of its entries -/// as pairs; a unit or unit struct is zero. Primitives are leaves over their little-endian bytes -/// (floats by their bits), strings and byte strings over their length and bytes, as the codec -/// writes them. -#[cfg(feature = "serde")] -mod serialized { - use serde::ser::{self, Serialize}; - - use super::Node; - - /// A serialization that refused: a `Serialize` impl reported an error of its own. - #[derive(Debug)] - pub(crate) struct NotDigested(pub(crate) String); - - impl std::fmt::Display for NotDigested { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "the value did not serialize: {}", self.0) - } - } - - impl std::error::Error for NotDigested {} - - impl ser::Error for NotDigested { - fn custom(msg: T) -> Self { - NotDigested(msg.to_string()) - } - } - - /// `value`'s node. - pub(crate) fn node_of(value: &T) -> Result { - value.serialize(Nodes) - } - - fn leaf(bytes: &[u8]) -> Node { - Node::leaf(|sink| sink(bytes)) - } - - fn counted(bytes: &[u8]) -> Node { - Node::leaf(|sink| { - sink(&u32::try_from(bytes.len()).unwrap_or(u32::MAX).to_le_bytes()); - sink(bytes); - }) - } - - /// The serializer whose output is a value's node. - struct Nodes; - - /// Positional field names, for tuple variants. - const POSITIONS: [&str; 16] = [ - "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", - ]; - - fn position(index: usize) -> Result<&'static str, NotDigested> { - POSITIONS - .get(index) - .copied() - .ok_or_else(|| NotDigested(format!("a tuple variant of more than {index} fields"))) - } - - /// The items of a sequence, a tuple, or a map's entries. - struct Items { - nodes: Vec, - tuple: bool, - key: Option, - } - - impl Items { - fn finish(self) -> Node { - if self.tuple { - Node::tuple(self.nodes) - } else { - Node::sequence(self.nodes) - } - } - } - - /// The named fields of a struct or a variant (`variant` names it). - struct Fields { - variant: Option<&'static str>, - fields: Vec<(&'static str, Node)>, - } - - impl Fields { - fn finish(mut self) -> Node { - match self.variant { - Some(name) => Node::variant(name, &mut self.fields), - None => Node::fields(&mut self.fields), - } - } - } - - impl ser::Serializer for Nodes { - type Ok = Node; - type Error = NotDigested; - type SerializeSeq = Items; - type SerializeTuple = Items; - type SerializeTupleStruct = Items; - type SerializeTupleVariant = Fields; - type SerializeMap = Items; - type SerializeStruct = Fields; - type SerializeStructVariant = Fields; - - fn serialize_bool(self, v: bool) -> Result { - Ok(leaf(&[u8::from(v)])) - } - fn serialize_i8(self, v: i8) -> Result { - Ok(leaf(&v.to_le_bytes())) - } - fn serialize_i16(self, v: i16) -> Result { - Ok(leaf(&v.to_le_bytes())) - } - fn serialize_i32(self, v: i32) -> Result { - Ok(leaf(&v.to_le_bytes())) - } - fn serialize_i64(self, v: i64) -> Result { - Ok(leaf(&v.to_le_bytes())) - } - fn serialize_i128(self, v: i128) -> Result { - Ok(leaf(&v.to_le_bytes())) - } - fn serialize_u8(self, v: u8) -> Result { - Ok(leaf(&[v])) - } - fn serialize_u16(self, v: u16) -> Result { - Ok(leaf(&v.to_le_bytes())) - } - fn serialize_u32(self, v: u32) -> Result { - Ok(leaf(&v.to_le_bytes())) - } - fn serialize_u64(self, v: u64) -> Result { - Ok(leaf(&v.to_le_bytes())) - } - fn serialize_u128(self, v: u128) -> Result { - Ok(leaf(&v.to_le_bytes())) - } - fn serialize_f32(self, v: f32) -> Result { - Ok(leaf(&v.to_bits().to_le_bytes())) - } - fn serialize_f64(self, v: f64) -> Result { - Ok(leaf(&v.to_bits().to_le_bytes())) - } - fn serialize_char(self, v: char) -> Result { - Ok(leaf(&u32::from(v).to_le_bytes())) - } - fn serialize_str(self, v: &str) -> Result { - Ok(counted(v.as_bytes())) - } - fn serialize_bytes(self, v: &[u8]) -> Result { - Ok(counted(v)) - } - fn serialize_none(self) -> Result { - Ok(Node::ZERO) - } - fn serialize_some(self, value: &T) -> Result { - Ok(Node::some(node_of(value)?)) - } - fn serialize_unit(self) -> Result { - Ok(Node::ZERO) - } - fn serialize_unit_struct(self, _: &'static str) -> Result { - Ok(Node::ZERO) - } - fn serialize_unit_variant( - self, - _: &'static str, - _: u32, - variant: &'static str, - ) -> Result { - Ok(Node::variant(variant, &mut [])) - } - fn serialize_newtype_struct( - self, - _: &'static str, - value: &T, - ) -> Result { - node_of(value) - } - fn serialize_newtype_variant( - self, - _: &'static str, - _: u32, - variant: &'static str, - value: &T, - ) -> Result { - Ok(Node::variant( - variant, - &mut [(POSITIONS[0], node_of(value)?)], - )) - } - fn serialize_seq(self, len: Option) -> Result { - Ok(Items { - nodes: Vec::with_capacity(len.unwrap_or(0)), - tuple: false, - key: None, - }) - } - fn serialize_tuple(self, len: usize) -> Result { - Ok(Items { - nodes: Vec::with_capacity(len), - tuple: true, - key: None, - }) - } - fn serialize_tuple_struct(self, _: &'static str, len: usize) -> Result { - self.serialize_tuple(len) - } - fn serialize_tuple_variant( - self, - _: &'static str, - _: u32, - variant: &'static str, - len: usize, - ) -> Result { - Ok(Fields { - variant: Some(variant), - fields: Vec::with_capacity(len), - }) - } - fn serialize_map(self, len: Option) -> Result { - self.serialize_seq(len) - } - fn serialize_struct(self, _: &'static str, len: usize) -> Result { - Ok(Fields { - variant: None, - fields: Vec::with_capacity(len), - }) - } - fn serialize_struct_variant( - self, - _: &'static str, - _: u32, - variant: &'static str, - len: usize, - ) -> Result { - Ok(Fields { - variant: Some(variant), - fields: Vec::with_capacity(len), - }) - } - } - - impl ser::SerializeSeq for Items { - type Ok = Node; - type Error = NotDigested; - fn serialize_element( - &mut self, - value: &T, - ) -> Result<(), NotDigested> { - self.nodes.push(node_of(value)?); - Ok(()) - } - fn end(self) -> Result { - Ok(self.finish()) - } - } - - impl ser::SerializeTuple for Items { - type Ok = Node; - type Error = NotDigested; - fn serialize_element( - &mut self, - value: &T, - ) -> Result<(), NotDigested> { - self.nodes.push(node_of(value)?); - Ok(()) - } - fn end(self) -> Result { - Ok(self.finish()) - } - } - - impl ser::SerializeTupleStruct for Items { - type Ok = Node; - type Error = NotDigested; - fn serialize_field(&mut self, value: &T) -> Result<(), NotDigested> { - self.nodes.push(node_of(value)?); - Ok(()) - } - fn end(self) -> Result { - Ok(self.finish()) - } - } - - /// A map is the sequence of its entries, each the pair of its key's and value's nodes. - impl ser::SerializeMap for Items { - type Ok = Node; - type Error = NotDigested; - fn serialize_key(&mut self, key: &T) -> Result<(), NotDigested> { - self.key = Some(node_of(key)?); - Ok(()) - } - fn serialize_value(&mut self, value: &T) -> Result<(), NotDigested> { - let key = self - .key - .take() - .ok_or_else(|| NotDigested("a map value without its key".into()))?; - self.nodes.push(Node::tuple([key, node_of(value)?])); - Ok(()) - } - fn end(self) -> Result { - Ok(self.finish()) - } - } - - impl ser::SerializeTupleVariant for Fields { - type Ok = Node; - type Error = NotDigested; - fn serialize_field(&mut self, value: &T) -> Result<(), NotDigested> { - let name = position(self.fields.len())?; - self.fields.push((name, node_of(value)?)); - Ok(()) - } - fn end(self) -> Result { - Ok(self.finish()) - } - } - - impl ser::SerializeStruct for Fields { - type Ok = Node; - type Error = NotDigested; - fn serialize_field( - &mut self, - key: &'static str, - value: &T, - ) -> Result<(), NotDigested> { - self.fields.push((key, node_of(value)?)); - Ok(()) - } - fn end(self) -> Result { - Ok(self.finish()) - } - } - - impl ser::SerializeStructVariant for Fields { - type Ok = Node; - type Error = NotDigested; - fn serialize_field( - &mut self, - key: &'static str, - value: &T, - ) -> Result<(), NotDigested> { - self.fields.push((key, node_of(value)?)); - Ok(()) - } - fn end(self) -> Result { - Ok(self.finish()) - } - } -} - #[cfg(test)] mod tests; diff --git a/crates/metal2vulkan/src/cache/digest/tests.rs b/crates/metal2vulkan/src/cache/digest/tests.rs index 63a4a96b1..62046bbcf 100644 --- a/crates/metal2vulkan/src/cache/digest/tests.rs +++ b/crates/metal2vulkan/src/cache/digest/tests.rs @@ -68,172 +68,3 @@ fn nodes_omit_only_struct_fields() { assert_ne!(node(1).root("a"), node(1).root("b")); assert_ne!(Node::ZERO.root("a"), node(1).root("a")); } - -#[cfg(feature = "serde")] -mod serialized { - use std::collections::BTreeMap; - - use serde::Serialize; - - use super::super::node_of; - use super::*; - - #[derive(Serialize)] - struct Before { - count: u32, - items: Vec, - mode: Mode, - } - - #[derive(Serialize)] - struct After { - added: Option, - mode: Mode, - count: u32, - items: Vec, - flag: bool, - pairs: Vec<(u32, u32)>, - } - - #[derive(Serialize)] - struct Item { - word: u64, - } - - #[derive(Serialize)] - struct ItemAfter { - word: u64, - view: Option, - } - - #[derive(Serialize)] - enum Mode { - Off, - Level(u32), - Pair(u32, u32), - Window { start: u32, len: u32 }, - } - - #[derive(Serialize)] - enum ModeInserted { - Window { start: u32, len: u32 }, - Auto, - Pair(u32, u32), - Level(u32), - Off, - } - - fn digest(value: &T) -> Node { - node_of(value).unwrap() - } - - /// The serde path follows the codec path's rules: an added field at zero moves nothing, and - /// its non-zero values do. - #[test] - fn an_added_field_at_zero_keeps_the_digest() { - let before = Before { - count: 2, - items: vec![Item { word: 5 }, Item { word: 0 }], - mode: Mode::Level(3), - }; - let after = After { - added: None, - mode: Mode::Level(3), - count: 2, - items: vec![ - ItemAfter { - word: 5, - view: None, - }, - ItemAfter { - word: 0, - view: None, - }, - ], - flag: false, - pairs: Vec::new(), - }; - assert_eq!(digest(&before), digest(&after)); - let moved = After { - added: Some(0), - ..after - }; - assert_ne!(digest(&before), digest(&moved)); - let moved = After { - added: None, - flag: true, - ..moved - }; - assert_ne!(digest(&before), digest(&moved)); - let moved = After { - flag: false, - pairs: vec![(0, 0)], - ..moved - }; - assert_ne!(digest(&before), digest(&moved)); - } - - /// Variants are named: reordering or inserting variants moves nothing, and switching a value - /// to another variant does. - #[test] - fn variants_are_named_not_numbered() { - let pairs = [ - (Mode::Off, ModeInserted::Off), - (Mode::Level(4), ModeInserted::Level(4)), - (Mode::Pair(1, 2), ModeInserted::Pair(1, 2)), - ( - Mode::Window { start: 1, len: 0 }, - ModeInserted::Window { start: 1, len: 0 }, - ), - ]; - for (mode, inserted) in &pairs { - assert_eq!(digest(mode), digest(inserted)); - } - let digests = [ - digest(&Mode::Off), - digest(&Mode::Level(0)), - digest(&Mode::Level(4)), - digest(&Mode::Pair(1, 2)), - digest(&Mode::Pair(2, 1)), - digest(&Mode::Window { start: 0, len: 0 }), - digest(&ModeInserted::Auto), - ]; - for (i, a) in digests.iter().enumerate() { - for b in &digests[i + 1..] { - assert_ne!(a, b); - } - } - } - - /// A map is the sequence of its entries as pairs, so it digests as a sequence of pairs does - /// (the plan's `serde_pairs` maps). - #[test] - fn a_map_is_its_entries() { - let map: BTreeMap = [(1, 5), (2, 0)].into(); - let pairs: Vec<(u32, u64)> = map.clone().into_iter().collect(); - assert_eq!(digest(&map), digest(&pairs)); - assert!(digest(&BTreeMap::::new()).is_zero()); - } - - /// A plan's digest is its serialization's, covers what the plan says, and is pinned. - #[test] - fn a_plan_digest_follows_the_plan() { - use crate::bind::BindingPlan; - let plan = BindingPlan::default(); - let digest = plan.content_digest().unwrap(); - assert_eq!(digest, node_of(&plan).unwrap().root("binding plan")); - let mut viewed = plan.clone(); - viewed.views.view_mask = 3; - assert_ne!(viewed.content_digest().unwrap(), digest); - let hex = viewed - .content_digest() - .unwrap() - .iter() - .map(|byte| format!("{byte:02x}")) - .collect::(); - assert_eq!( - hex, "a7fb58b1d327f235fb690324f99969bccd238a3488178ac0cacb8cac19e2ebe0", - "the plan digest's definition changed" - ); - } -} diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index f48b671bb..831720e92 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -15,9 +15,9 @@ //! checks the format and semantics versions, the key, the device's profile fingerprint, and a //! checksum, then scans the modules; it does not re-run the verifier. Every [`ArtifactError`] //! is a cache miss: compile again and replace the entry. -//! - A [`BindingPlan`](crate::bind::BindingPlan) memoizes in memory on `(PipelineKey, BindShape)`. //! -//! [`VariantKey`] names the variant of a pipeline a bind shape or a dispatch asks for, and +//! [`VariantKey`] names a variant of a pipeline, the lowering inputs each of its functions +//! compiles under ([`VariantKey::lowering_inputs`]), and //! [`SpecializationKey`] is the data of one `VkSpecializationInfo`. //! //! Three versions move independently: the crate's (the API), [`SEMANTICS_VERSION`] (the output: @@ -42,8 +42,7 @@ use crate::vk; mod artifacts; mod checksum; mod codec; -// Content digests: `ComputePipeline::content_digest`, `RenderPipeline::content_digest` and -// `BindingPlan::content_digest`. +// Content digests: `ComputePipeline::content_digest` and `RenderPipeline::content_digest`. pub(crate) mod digest; mod envelope; mod scan; @@ -73,20 +72,20 @@ pub const SEMANTICS_VERSION: u32 = 2273; /// bumps it says what changed; this comment keeps no history. pub const ARTIFACT_FORMAT_VERSION: u32 = 591; -/// 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 -/// tables, dispatch regions and draws), the device replay and its preprocess, resident sets, status -/// decoding, and the other run-time data the binder computes. Independent of -/// [`SEMANTICS_VERSION`] (what is compiled) and [`ARTIFACT_FORMAT_VERSION`] (how it is encoded): -/// two runs of byte-identical artifacts and plans under one runtime version do the same thing. A +/// The version of what this crate gives a runtime for the runs of a compiled pipeline, beside the +/// compile: the device a run opens and what it enables, the Vulkan and Metal vocabularies a runtime +/// maps, the record and table formats it writes (indirect commands, rate and tile maps, function +/// tables, argument-buffer layouts), the texel decoders, and the other run-time data `bind` holds. +/// Independent of [`SEMANTICS_VERSION`] (what is compiled) and [`ARTIFACT_FORMAT_VERSION`] (how it +/// is encoded): two runs of byte-identical artifacts under one runtime version do the same thing. A /// consumer that keeps records of what runs of an artifact did (its own regression records, or what /// a run refused) keys them on it beside the artifact, as it keys cached artifacts on /// [`SEMANTICS_VERSION`]. /// -/// Bump it whenever a run of an unchanged artifact and plan may do something else: an answer, a -/// refusal or its class, an announcement, or what the run records and submits. A field added to an -/// encoded artifact or a plan whose zero value would change what existing pipelines do needs the -/// same bump (or the executor's), since their digests omit it. +/// Bump it whenever a run of an unchanged artifact may do something else: an answer, a refusal or +/// its class, an announcement, or what the run records and submits. A field added to an encoded +/// artifact whose zero value would change what existing pipelines do needs the same bump (or the +/// executor's), since its digest omits it. /// /// This workspace's validation holds every recorded run to it beside the run's artifact content /// digest (`cache::digest`), and its runtime guard fails when the runtime's sources no longer hash @@ -131,13 +130,10 @@ impl fmt::Debug for PipelineKey { } } -/// The per-function variant choices a bind shape or a dispatch can require: storage-image choices -/// for slots whose `StorageTextureFormat` fact maps to `Variant`, slots that a `BufferRangeLimit` -/// variant moves to `BufferForm::Psb`, vertex buffers the shape binds where fixed-function vertex -/// input cannot fetch them, a kernel's emulated simdgroups for a dispatch whose threadgroup has a -/// partial simdgroup, a vertex function's dropped `Layer` output in a pass of one layer, and the -/// read-only slots Profile F's per-stage storage-buffer fallback keeps as storage views. Canonical -/// (ordered maps) and empty on the common path. +/// The per-function variant choices of a pipeline: storage-image choices for slots whose +/// `StorageTextureFormat` fact maps to `Variant`, slots that a `BufferRangeLimit` variant moves to +/// `BufferForm::Psb`, vertex buffers fetched in the shader, a kernel's emulated simdgroups, and the +/// other forms each field names. Canonical (ordered maps) and empty on the common path. /// /// [`VariantKey::lowering_inputs`] is each function's `LoweringInputs` under the key, so the /// choice reaches `select` and the `FunctionCompileKey`; a render pipeline's keys under one are @@ -156,80 +152,46 @@ pub struct VariantKey { pub pulled_vertex_buffers: BTreeSet, /// The kernel's simdgroups run in the emulated tier, which is exact for every threadgroup size: /// a dispatch whose threadgroup has a partial simdgroup asks for it where the kernel's own tier - /// runs simdgroups on whole subgroups (`BindingPlan::dispatch_variant`, - /// `BindError::NeedsVariant`), and the plan of a pipeline compiled under it states it. + /// runs simdgroups on whole subgroups. #[cfg_attr(feature = "serde", serde(default))] pub emulated_simdgroups: bool, - /// Every threadgroup of the dispatch is one row, so each of its simdgroups lies within the - /// row: a kernel whose lockstep simdgroup barriers order only pairs that meet where a - /// simdgroup spans two rows (`RuntimeFact::RowLockstep`) runs without them, keeping its - /// threadgroup ones, and without the subgroup size they pinned (`LoweringInputs::one_row`). - /// A dispatch whose every region is one row asks for it (`BindingPlan::dispatch_variant`), - /// and the plan of a pipeline compiled under it states it and asks another dispatch for the - /// variant without it. + /// Every threadgroup of the dispatch is one row, so each of its simdgroups lies within the row: + /// a kernel whose lockstep simdgroup barriers order only pairs that meet where a simdgroup + /// spans two rows (`RuntimeFact::RowLockstep`) runs without them, keeping its threadgroup ones, + /// and without the subgroup size they pinned (`LoweringInputs::one_row`). A dispatch whose + /// every region is one row asks for it. #[cfg_attr(feature = "serde", serde(default))] pub one_row: bool, - /// The axes along which every threadgroup of the dispatch has one thread (bit 0 `x`, bit 1 - /// `y`, bit 2 `z`): a kernel whose walk is predicated, where those axes' thread positions - /// alone make some of its synchronizations' blocks divergent (`RuntimeFact::UnitAxes`'s - /// `relief`), compiles with them uniform (`LoweringInputs::unit_axes`). The plan of a pipeline - /// compiled under it states it and asks a dispatch of more threads along such an axis for the - /// variant without it. + /// The axes along which every threadgroup of the dispatch has one thread (bit 0 `x`, bit 1 `y`, + /// bit 2 `z`): a kernel whose walk is predicated, where those axes' thread positions alone make + /// some of its synchronizations' blocks divergent (`RuntimeFact::UnitAxes`'s `relief`), + /// compiles with them uniform (`LoweringInputs::unit_axes`). #[cfg_attr(feature = "serde", serde(default))] pub unit_axes: u8, /// Texture slots bound to an 8-bit sRGB texture the device cannot sample, which the runtime /// holds as the format's UNORM twin (`metal::format::srgb_raw_twin`), whose views read the /// codes (`c / 255`): every slot of a `RuntimeFact::SrgbTexture` the shape binds in such a - /// format (`metal::texel_format::srgb_twin_on`). The function decodes what it reads there - /// by the MSL transfer through the device's `Pow`, as the device would through an sRGB view - /// it lacks - /// (`LoweringInputs::srgb_textures`); a slot bound in an sRGB format the device samples reads - /// the device's decode and is no slot of this. The plan of a pipeline compiled under it - /// states it. + /// format (`metal::texel_format::srgb_twin_on`). The function decodes what it reads there by + /// the MSL transfer through the device's `Pow`, as the device would through an sRGB view it + /// lacks (`LoweringInputs::srgb_textures`); a slot bound in an sRGB format the device samples + /// reads the device's decode and is no slot of this. #[cfg_attr(feature = "serde", serde(default))] pub srgb_textures: BTreeSet, - /// 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' - /// texel buffer alone, and its accesses read the codes and convert them as Metal does - /// (`bind::YCbCrInPlace`). The plan of a pipeline compiled under it states it. - #[cfg_attr(feature = "serde", serde(default))] - pub ycbcr_in_place: BTreeSet, - /// Slots of [`ycbcr_in_place`](Self::ycbcr_in_place) whose function's every sample the - /// device's own sampler Y′CbCr conversion takes, at which the shape binds a texture whose - /// planes are also held as an image it samples, each with that conversion - /// (`TextureShape::Texture::ycbcr_planes_sampler`, `RuntimeFact::YCbCrInPlace`'s `device`): - /// each such slot binds that image through an immutable sampler of the conversion, and its - /// samples are the device's (`bind::YCbCrPlanesSampler`). The plan of a pipeline compiled - /// under it states it. - #[cfg_attr( - feature = "serde", - serde(default, with = "crate::pipeline::serde_pairs") - )] - pub ycbcr_planes_sampled: BTreeMap, - /// Texture slots whose function only reads, writes or asks the size of the 2D texture the - /// shape binds there, whose rows are read and written in place: every slot of a - /// `RuntimeFact::TexelRows` the shape binds such a texture at - /// (`TextureShape::Texture::texel_rows`). Each such slot binds a texel buffer over the rows' - /// bytes alone (`bind::TexelRows`). The plan of a pipeline compiled under it states it. - #[cfg_attr(feature = "serde", serde(default))] - pub texel_rows: BTreeSet, /// Texture-buffer slots whose function reads it through its parts, each with the parts of the /// texture buffer the shape binds there: every slot of a `RuntimeFact::TexelBufferParts` the - /// shape binds a texture buffer of more texels than one view holds at - /// (`TextureShape::Buffer::parts`). Each such slot binds an array of that many texel buffer + /// shape binds a texture buffer of more texels than one view holds at. Each such slot binds an array of that many texel buffer /// views (`bind::texel_parts`). A texture buffer one view holds adds nothing, so its draws - /// keep their key. The plan of a pipeline compiled under it states it. + /// keep their key. #[cfg_attr( feature = "serde", serde(default, with = "crate::pipeline::serde_pairs") )] pub texel_buffer_parts: BTreeMap, - /// Texture slots a constexpr sampler samples, each with the address-mode map of the texture - /// the shape binds there where it is not the identity: every slot of a + /// Texture slots a constexpr sampler samples, each with the address-mode map of the texture the + /// shape binds there where it is not the identity: every slot of a /// `RuntimeFact::ConstexprSampled` the shape binds such a texture at. The function's constexpr - /// samplers sample the slot with their modes mapped; the plan of a pipeline compiled under it - /// states it. A texture of the identity map adds nothing, so ordinary draws keep their key. + /// samplers sample the slot with their modes mapped. A texture of the identity map adds + /// nothing, so ordinary draws keep their key. #[cfg_attr( feature = "serde", serde(default, with = "crate::pipeline::serde_pairs") @@ -238,20 +200,18 @@ pub struct VariantKey { /// The kernel runs its grid flat (`LoweringInputs::flat_grid`): one variant runs every grid /// and threadgroup size of a kernel that does not observe its threadgroup partition /// (`KernelFacts::partition_oblivious`), reading the grid from the region record at its - /// `PushField::ReplayRegionAddress`. The plan of a pipeline compiled under it states it. + /// `PushField::ReplayRegionAddress`. #[cfg_attr(feature = "serde", serde(default))] pub flat_grid: bool, /// With [`flat_grid`](Self::flat_grid), its dispatch's threadgroups are the call's /// (`LoweringInputs::call_threadgroups`): a one-row grid in threadgroups of one row, so a /// kernel that observes its partition through its simdgroups alone - /// (`KernelFacts::partition_simdgroups`) runs flat too. The plan of a pipeline compiled under - /// it states it. + /// (`KernelFacts::partition_simdgroups`) runs flat too. #[cfg_attr(feature = "serde", serde(default))] pub call_threadgroups: bool, /// The kernel, or the render pipeline's vertex and fragment functions, are a device-replay /// variant (`LoweringInputs::replay_bindings`): every buffer they read is at its device - /// address in the slot table a replay's preprocess writes for its command; a compute plan of - /// it does not state the key. The runtime compiles a kernel's with `flat_grid` per pipeline state an execution of + /// address in the slot table a replay's preprocess writes for its command. The runtime compiles a kernel's with `flat_grid` per pipeline state an execution of /// commands a kernel writes may name, to run it on the GPU alone; and a render pipeline's for /// the state an execution of GPU-written draws inherits, its draws' buffers the records'. #[cfg_attr(feature = "serde", serde(default))] @@ -259,78 +219,73 @@ pub struct VariantKey { /// With `replay_bindings`, the render pipeline's vertex and fragment functions run a draw /// replay merged into one draw (`LoweringInputs::merged_draws`): the variant the runtime /// compiles where an execution of GPU-written draws of one list type or points draws as one - /// draw. The plan of a pipeline compiled under it states it. + /// draw. #[cfg_attr(feature = "serde", serde(default))] pub merged_draws: bool, /// The render pipeline draws each vertex amplification as a draw of its own - /// (`LoweringInputs::amplification_draws` for its vertex and fragment functions): the - /// variant a shape whose amplification Vulkan multiview cannot draw as Metal renders it asks - /// for (a `nil` mapping above a count of 1, layers out of order, apart or repeated, a - /// viewport offset, a stage that chooses or reads its slice, or more amplifications than - /// the device has views; `bind::graphics`). The plan of a pipeline compiled under it states - /// it. + /// (`LoweringInputs::amplification_draws` for its vertex and fragment functions): the variant a + /// shape whose amplification Vulkan multiview cannot draw as Metal renders it asks for (a `nil` + /// mapping above a count of 1, layers out of order, apart or repeated, a viewport offset, a + /// stage that chooses or reads its slice, or more amplifications than the device has views; + /// `bind::graphics`). #[cfg_attr(feature = "serde", serde(default))] pub amplification_draws: Option, /// The kernel folds Metal's group counts into one dispatch within the device's limits /// (`LoweringInputs::folded_groups`): the variant a threadgroup dispatch whose group counts /// are GPU data runs on, for a kernel that observes its threadgroup partition, reading its /// group counts and every grid builtin's region from the region record at its - /// `PushField::ReplayRegionAddress`. The plan of a pipeline compiled under it states it. + /// `PushField::ReplayRegionAddress`. #[cfg_attr(feature = "serde", serde(default))] pub folded_groups: bool, - /// The kernel runs a ragged `dispatchThreads` grid in the threadgroups its threads fill, at - /// the call's threadgroup size, the last along an axis Metal's partial threadgroup + /// The kernel runs a ragged `dispatchThreads` grid in the threadgroups its threads fill, at the + /// call's threadgroup size, the last along an axis Metal's partial threadgroup /// (`LoweringInputs::partial_threadgroups`): the variant such a dispatch of a kernel that /// observes its threadgroup partition runs on, one `VkPipeline` of the call's size in place of - /// an edge region's of each remainder. The plan of a pipeline compiled under it states it, - /// and plans such a dispatch so (`BindingPlan::instantiate_dispatch`). + /// an edge region's of each remainder. #[cfg_attr(feature = "serde", serde(default))] pub partial_threadgroups: bool, /// Texture slots bound in one of Apple's extended-range formats, by the format /// (`LoweringInputs::extended_range`): the function reads and writes the bound texture's raw - /// texels there, decoding and encoding Metal's values. The plan of a pipeline compiled under - /// it states it. + /// texels there, decoding and encoding Metal's values. #[cfg_attr( feature = "serde", serde(default, with = "crate::pipeline::serde_pairs") )] pub extended_range: BTreeMap, /// Color attachments of the pass the render pipeline has no pixel format for, the pass's - /// pixel format of each by color index (`BindShape::zeroed_colors`): plain Metal stores zero + /// pixel format of each by color index: plain Metal stores zero /// bytes into each at every sample a draw covers. The variant's pipeline has each attachment /// in that format, written whole and unblended, and its fragment function writes zero to it - /// (`LoweringInputs::zeroed_colors`). The plan of a pipeline compiled under it states it. + /// (`LoweringInputs::zeroed_colors`). #[cfg_attr(feature = "serde", serde(default))] pub zeroed_colors: BTreeMap, /// Color attachments the render pipeline has a pixel format for and the pass has none, by - /// color index (`BindShape::dropped_colors`): plain Metal drops the fragment function's + /// color index: plain Metal drops the fragment function's /// writes there. The variant's fragment function keeps no output at each - /// (`LoweringInputs::dropped_colors`). The plan of a pipeline compiled under it states it. + /// (`LoweringInputs::dropped_colors`). #[cfg_attr(feature = "serde", serde(default))] pub dropped_colors: BTreeSet, /// The bytes of each cell of a tile function's explicit imageblock standing alone that the - /// render pass keeps, fewer than the cell holds (`BindShape::kept_imageblock_bytes`): plain + /// render pass keeps, fewer than the cell holds: plain /// Metal reads the block's other words as zero and drops their writes. The variant's - /// function does (`LoweringInputs::kept_imageblock_bytes`). The plan of a tile function with - /// such an imageblock states it. + /// function does (`LoweringInputs::kept_imageblock_bytes`). #[cfg_attr(feature = "serde", serde(default))] pub kept_imageblock_bytes: Option, /// The fragment function clamps the depth it writes to the draw's depth clamp range itself - /// (`BindShape::depth_clamp_range`, `LoweringInputs::depth_clamp_range`): the variant a draw + /// (`LoweringInputs::depth_clamp_range`): the variant a draw /// in depth clamp mode through a range above 0 runs, where Metal stores a negative NaN as 0. - /// The plan of a pipeline compiled under it states it. + /// #[cfg_attr(feature = "serde", serde(default))] pub depth_clamp_range: bool, /// The fragment function's triangles are drawn with Metal's last vertex first - /// (`BindShape::rotated_weights`, `LoweringInputs::rotated_weights`): the variant a listed + /// (`LoweringInputs::rotated_weights`): the variant a listed /// triangle draw under Apple's last provoking vertex runs, whose `[[barycentric_coord]]` reads - /// take Metal's weights back from the drawn triangle's. The plan of a pipeline compiled under - /// it states it. + /// take Metal's weights back from the drawn triangle's. #[cfg_attr(feature = "serde", serde(default))] pub rotated_weights: bool, /// The pipeline draws its lines, or its triangles' edges, as bands of triangles through /// synthesized tessellation stages, each patch one primitive of this kind - /// (`BindShape::line_band`, `pipeline::link::band`): the variant a draw of lines, or of + /// (`pipeline::link::band`): the variant a draw of lines, or of /// triangles in fill mode `Lines`, at an Apple `setLineWidth:` width the device's own lines do /// not draw runs. Its graphics state states it (`GraphicsState::line_band`). #[cfg_attr(feature = "serde", serde(default))] @@ -340,60 +295,55 @@ pub struct VariantKey { /// (`LoweringInputs::swizzled_storage`): a Vulkan storage view takes no swizzle, so the /// function applies the bound texture's swizzle to its reads and undoes it on its writes, as /// plain Metal does, under the slot's `SpecKey::TextureSwizzle`, and the slot's storage view - /// takes none (`ImageViewDesc::shader_swizzle`). The plan of a pipeline compiled under it - /// states it. It holds too each sampled slot of `extended_range` bound to such a texture whose - /// texels the function reads or samples: its view holds raw codes, so the function swizzles the - /// decoded texels and the view takes none. So does, on a device without Metal's own sampler, - /// each sampled slot bound to a swizzled packed normalized texture, whose texels the function - /// converts by each channel's own scale before it swizzles them. + /// takes none. It holds too each sampled slot of + /// `extended_range` bound to such a texture whose texels the function reads or samples: its + /// view holds raw codes, so the function swizzles the decoded texels and the view takes none. + /// So does, on a device without Metal's own sampler, each sampled slot bound to a swizzled + /// packed normalized texture, whose texels the function converts by each channel's own scale + /// before it swizzles them. #[cfg_attr(feature = "serde", serde(default))] pub swizzled_storage: BTreeSet, /// Every function that reads visible-function tables by their resource ids reads their /// words through their device addresses (`LoweringInputs::addressed_function_tables`): the /// variant a shape whose listed tables may pass `maxStorageBufferRange` asks for - /// (`FunctionTablesShape::bytes_class`). The plan of a pipeline compiled under it states it. + /// (`FunctionTablesShape::bytes_class`). #[cfg_attr(feature = "serde", serde(default))] pub addressed_function_tables: 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 + /// 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 - /// samples through each with Metal's bicubic filter of that state. The plan of a pipeline - /// compiled under it states it. + /// samples through each with Metal's bicubic filter of that state. #[cfg_attr( feature = "serde", serde(default, with = "crate::pipeline::serde_pairs") )] pub cubic_samplers: BTreeMap, /// The de-indexed form of a pipeline whose vertex function writes the primitive ID's varying - /// (`LoweringInputs::primitive_id_indices`, `BindShape::primitive_id_indices`): the vertex + /// (`LoweringInputs::primitive_id_indices`): the vertex /// function of an indexed draw of this index type runs the draw's indices as `index count` - /// vertices from 0, read at the draw's index address, so each primitive's stream position - /// names it. The runtime asks for it for an indexed draw of such a pipeline, and the plan of - /// a pipeline compiled under it states it. + /// vertices from 0, read at the draw's index address, so each primitive's stream position names + /// it. The runtime asks for it for an indexed draw of such a pipeline. #[cfg_attr(feature = "serde", serde(default))] pub primitive_id_indices: Option, /// A draw of Metal's private quads or quad strip, listed as two triangles a quad, of a - /// pipeline whose fragment function reads Vulkan's `PrimitiveId` (`BindShape:: - /// quad_primitive_ids`): the variant's fragment function reads `[[primitive_id]]` as that + /// pipeline whose fragment function reads Vulkan's `PrimitiveId`: the variant's fragment function reads `[[primitive_id]]` as that /// value shifted right by one, the quad's (`LoweringInputs::quad_primitive_ids`). The runtime - /// asks for it for such a draw, and the plan of a pipeline compiled under it states it - /// (`RuntimeFact::QuadPrimitiveIds`). + /// asks for it for such a draw (`RuntimeFact::QuadPrimitiveIds`). #[cfg_attr(feature = "serde", serde(default))] pub quad_primitive_ids: bool, /// A draw of one of Metal's private primitive types drawn in the pulled list form - /// (`BindShape::private_list`): the variant's vertex function runs each position of the + ///: the variant's vertex function runs each position of the /// consumer's list once, without indices, reading its index and Metal's base vertex at the /// list's address (`LoweringInputs::private_list`). The runtime asks for it for such a draw /// whose vertex function writes memory or the primitive ID's varying, or whose vertex start - /// a list's base vertex cannot carry, and the plan of a pipeline compiled under it states it - /// (`RuntimeFact::PrivateList`). + /// a list's base vertex cannot carry (`RuntimeFact::PrivateList`). #[cfg_attr(feature = "serde", serde(default))] pub private_list: bool, /// Sampled texture slots whose compile states `RuntimeFact::CrossClassReads` bound to a /// texture of a color format whose numeric class is not the slot's declared one, by the /// bound format's class (`LoweringInputs::cross_class`): the variant's function reads, /// samples and gathers the texture in its own class and hands back its words as the declared - /// type, as plain Metal does. The plan of a pipeline compiled under it states it. + /// type, as plain Metal does. #[cfg_attr( feature = "serde", serde(default, with = "crate::pipeline::serde_pairs") @@ -402,21 +352,19 @@ pub struct VariantKey { /// The runtime sampler slots of a `RuntimeFact::AnisotropicSampler` that the shape binds to a /// sampler whose word states anisotropy (`SamplerWord::ANISOTROPIC`, /// `LoweringInputs::anisotropic_samplers`): the variant whose function takes Metal's - /// anisotropic filter, emulated, at each one's samples. The plan of a pipeline compiled under - /// it states it. + /// anisotropic filter, emulated, at each one's samples. #[cfg_attr(feature = "serde", serde(default))] pub anisotropic_samplers: BTreeSet, /// The texture slots of a kernel of OpenCL mode whose `RuntimeFact::OpenClLineTexture` (a 1D /// image it reads as the 2D texture of height 1 Apple's OpenCL binds) the shape binds a 1D or /// 1D array texture at (`LoweringInputs::open_cl_lines`): the variant's kernel declares each - /// as that 1D texture and reads it. The plan of a pipeline compiled under it states it. + /// as that 1D texture and reads it. #[cfg_attr(feature = "serde", serde(default))] pub open_cl_lines: BTreeSet, /// The render pipeline draws a rasterization-rate-mapped pass's regions several at a time, - /// each one draw of a multi-draw whose index selects its viewport and scissor - /// (`BindShape::region_viewports`): its vertex function stores `ViewportIndex` as `DrawIndex` - /// (`LoweringInputs::region_viewports`). The plan of a pipeline compiled under it states it - /// (`RuntimeFact::RegionViewports`). + /// each one draw of a multi-draw whose index selects its viewport and scissor: its vertex + /// function stores `ViewportIndex` as `DrawIndex` + /// (`LoweringInputs::region_viewports`, `RuntimeFact::RegionViewports`). #[cfg_attr(feature = "serde", serde(default))] pub region_viewports: bool, } @@ -427,64 +375,6 @@ impl VariantKey { VariantKey::default() } - /// This key in the large-buffer form, for a pipeline of `dependencies` bound as `shape`: with - /// every slot a large buffer would move to its device address ([`psb_slots`](Self::psb_slots): - /// a `RuntimeFact::BufferRangeLimit` the pipeline honours by a variant) at its device address - /// whatever buffer is bound there, but those `shape` binds without one (inline bytes, or a - /// buffer without a device address). A pipeline of this key runs a dispatch or draw of any - /// buffer lengths at those slots ([`covers`](Self::covers)), so one compiled before the buffers - /// are known (an indirect command the GPU may write) is the one that runs. Every access inside - /// a slot's window reads and writes as in the form the bound buffers ask for; outside it, the - /// slot has a large buffer's containment. On a device without device addresses the fact is a - /// plan-time check, and the key is unchanged. - pub fn large_buffer_form( - &self, - dependencies: &[crate::pipeline::RuntimeDependency], - shape: &crate::bind::BindShape, - ) -> VariantKey { - use crate::bind::BufferShape; - use crate::pipeline::{Mechanism, RuntimeFact}; - let addressless = |slot: &SlotRef| { - let bound = shape - .stages - .get(&slot.stage) - .and_then(|stage| stage.buffers.get(&slot.index)); - matches!( - bound, - Some( - BufferShape::Bytes { .. } - | BufferShape::Buffer { - device_address: false, - .. - } - ) - ) - }; - let mut out = self.clone(); - out.psb_slots.extend( - dependencies - .iter() - .filter_map(|dependency| match dependency.fact { - RuntimeFact::BufferRangeLimit { slot } - if dependency.mechanism == Mechanism::Variant && !addressless(&slot) => - { - Some(slot) - } - _ => None, - }), - ); - out - } - - /// Whether a pipeline compiled under this key runs a dispatch or draw whose plan settles on - /// `settled`: the same key but for device-address slots this one adds, as - /// [`large_buffer_form`](Self::large_buffer_form) adds them. - pub fn covers(&self, settled: &VariantKey) -> bool { - let mut widened = settled.clone(); - widened.psb_slots.extend(self.psb_slots.iter().copied()); - widened == *self - } - /// Whether nothing needs a variant (the common path). pub fn is_empty(&self) -> bool { self.storage_images.is_empty() @@ -494,9 +384,6 @@ impl VariantKey { && !self.one_row && self.unit_axes == 0 && self.srgb_textures.is_empty() - && self.ycbcr_in_place.is_empty() - && self.ycbcr_planes_sampled.is_empty() - && self.texel_rows.is_empty() && self.texel_buffer_parts.is_empty() && self.address_maps.is_empty() && !self.flat_grid @@ -593,24 +480,6 @@ impl VariantKey { .filter(|s| s.stage == stage) .copied() .collect(); - out.ycbcr_in_place = self - .ycbcr_in_place - .iter() - .filter(|s| s.stage == stage) - .copied() - .collect(); - out.ycbcr_planes_sampled = self - .ycbcr_planes_sampled - .iter() - .filter(|(s, _)| s.stage == stage) - .map(|(s, sampler)| (*s, *sampler)) - .collect(); - out.texel_rows = self - .texel_rows - .iter() - .filter(|s| s.stage == stage) - .copied() - .collect(); out.texel_buffer_parts = self .texel_buffer_parts .iter() diff --git a/crates/metal2vulkan/src/cache/tests.rs b/crates/metal2vulkan/src/cache/tests.rs index 11552dd28..386732439 100644 --- a/crates/metal2vulkan/src/cache/tests.rs +++ b/crates/metal2vulkan/src/cache/tests.rs @@ -708,8 +708,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::SrgbTexture` and -/// `SrgbTexture`, and `PrecisionNote::HalfTexelConversion`, -/// `HalfSampleFilter`, `SrgbTexelDecode`, and `FloatSampleFilter`, +/// `SrgbTexture`, `PrecisionNote::HalfTexelConversion` and `SrgbTexelDecode`, /// `HandleClass::Sampler { compare, integer }` and /// `SyntheticBinding::SamplerTable`, each beside the others rather than only on its own side's /// fixtures. @@ -733,9 +732,7 @@ fn the_merged_members_round_trip_in_one_render_pipeline() { let notes = [ PrecisionNote::CubeGradientFootprint, PrecisionNote::HalfTexelConversion, - PrecisionNote::HalfSampleFilter, PrecisionNote::SrgbTexelDecode, - PrecisionNote::FloatSampleFilter, ]; let dev = device("moltenvk-m3"); let Some(bc) = fixture("stage_io") else { @@ -872,298 +869,6 @@ fn the_merged_members_round_trip_in_one_render_pipeline() { ); } -/// The emulated-simdgroups variant of a kernel moltenvk-m3 runs on whole subgroups round trips as a -/// function and as a pipeline, and the decoded pipeline's plan states the variant, so a cached -/// variant settles as the compiled one does. -#[test] -fn the_emulated_simdgroups_variant_round_trips() { - use crate::bind::BindShape; - use crate::cache::VariantKey; - use crate::pipeline::facts::RuntimeFact; - let dev = device("moltenvk-m3"); - let Some(bc) = fixture("simd_ops") else { - return; - }; - let f = Library::from_air(&bc) - .and_then(|lib| lib.function("simd_sum_k")) - .expect("kernel"); - let mut key = VariantKey::new(); - key.emulated_simdgroups = true; - let compiled = dev - .compile_function( - &FunctionDescriptor::new(f), - &key.lowering_inputs(Stage::Kernel), - &Budget::standard(), - ) - .expect("variant"); - assert!(compiled - .artifact() - .facts - .contains(&RuntimeFact::EmulatedSimdgroups)); - assert_eq!( - CompiledFunction::from_bytes(&compiled.to_bytes(), &dev), - Ok(compiled.clone()) - ); - let pipeline = dev - .compile_compute_pipeline( - &ComputePipelineDescriptor::new(StageSource::Compiled(compiled)), - &Budget::standard(), - ) - .expect("pipeline"); - let decoded = ComputePipeline::from_bytes(&pipeline.to_bytes(), &dev).expect("decoded"); - assert_eq!(decoded, pipeline); - let plan = decoded.plan(&dev, &BindShape::default()).expect("plan"); - assert_eq!(plan.variant, key); -} - -/// The `SrgbTexture` fact round trips, and a kernel compiled under the `SrgbTexture` variant (a -/// slot bound to an 8-bit sRGB format the device holds as its UNORM twin) round trips as a -/// function and as a pipeline, whose decoded plan for a shape binding such a texture at the slot -/// states the variant, so a cached variant settles as the compiled one does; a shape binding an -/// sRGB format the device samples states none. -#[test] -fn the_srgb_texture_variant_round_trips() { - use crate::bind::{BindState, BoundTexture, StageTable, TextureFacts}; - use crate::cache::VariantKey; - use crate::pipeline::artifact::PrecisionNote; - use crate::pipeline::facts::RuntimeFact; - let slot = SlotRef { - stage: Stage::Kernel, - class: SlotClass::Texture, - index: 2, - }; - let fact = RuntimeFact::SrgbTexture { slot }; - assert_eq!(decode::(&encode(&fact)), Ok(fact)); - let note = PrecisionNote::SrgbTexelDecode; - assert_eq!(decode::(&encode(¬e)), Ok(note)); - - let dev = device("lavapipe"); - let Some(bc) = fixture("texture_ops") else { - return; - }; - let f = Library::from_air(&bc) - .and_then(|lib| lib.function("short_texels")) - .expect("kernel"); - let mut key = VariantKey::new(); - key.srgb_textures.insert(slot); - let compiled = dev - .compile_function( - &FunctionDescriptor::new(f), - &key.lowering_inputs(Stage::Kernel), - &Budget::standard(), - ) - .expect("variant"); - assert!(compiled - .artifact() - .facts - .contains(&RuntimeFact::SrgbTexture { slot })); - assert_eq!( - CompiledFunction::from_bytes(&compiled.to_bytes(), &dev), - Ok(compiled.clone()) - ); - let pipeline = dev - .compile_compute_pipeline( - &ComputePipelineDescriptor::new(StageSource::Compiled(compiled)), - &Budget::standard(), - ) - .expect("pipeline"); - let decoded = ComputePipeline::from_bytes(&pipeline.to_bytes(), &dev).expect("decoded"); - assert_eq!(decoded, pipeline); - let mut table = StageTable::default(); - // lavapipe samples no `RG8Unorm_sRGB`, which the runtime holds as `RG8Unorm`, and samples - // `RGBA8Unorm_sRGB` itself. - for (pf, twin) in [ - (metal::PixelFormat::RG8UnormSRGB, true), - (metal::PixelFormat::RGBA8UnormSRGB, false), - ] { - let mut facts = TextureFacts::new(metal::TextureType::Type3D, pf); - facts.usage = metal::TextureUsage::SHADER_READ; - table.textures.insert( - 2, - BoundTexture::Texture { - facts, - resource_id: None, - }, - ); - let mut state = BindState::default(); - state.stages.insert(Stage::Kernel, table.clone()); - let plan = decoded.plan(&dev, &state.shape()).expect("plan"); - match twin { - true => assert_eq!(plan.variant.srgb_textures, key.srgb_textures, "{pf:?}"), - false => assert!(plan.variant.srgb_textures.is_empty(), "{pf:?}"), - } - } -} - -/// The `CubicSampler` fact round trips, and a kernel compiled under the cubic-sampler variant round -/// trips as a function and as a pipeline, whose decoded plan for a shape binding a sampler with a -/// `Cubic` filter at the slot states the variant (the bound word's `SamplerWord::CUBIC_STATE` -/// bits), so a cached variant settles as the compiled one does. A nearest sampler at the slot -/// states none; every sample through the slot states the fact, with the variant or without it. -#[test] -fn the_cubic_sampler_variant_round_trips() { - use crate::bind::{ - BindState, BoundSampler, BoundTexture, SamplerDescriptor, StageTable, TextureFacts, - }; - use crate::cache::VariantKey; - use crate::metal::sampler::SamplerWord; - use crate::pipeline::facts::RuntimeFact; - let slot = SlotRef { - stage: Stage::Kernel, - class: SlotClass::Sampler, - index: 0, - }; - let fact = RuntimeFact::CubicSampler { slot }; - assert_eq!(decode::(&encode(&fact)), Ok(fact)); - - let dev = device("lavapipe"); - let Some(bc) = fixture("gsm2_cubic_samplers") else { - return; - }; - let function = || { - Library::from_air(&bc) - .and_then(|lib| lib.function("gsm2_cubic_samples")) - .expect("kernel") - }; - let plain = dev - .compile_function( - &FunctionDescriptor::new(function()), - &LoweringInputs::new(), - &Budget::standard(), - ) - .expect("plain"); - assert!(plain.artifact().facts.contains(&fact)); - let mut cubic = SamplerDescriptor::new(); - cubic.min_filter = metal::SamplerMinMagFilter::Cubic; - cubic.mag_filter = metal::SamplerMinMagFilter::Linear; - cubic.s_address_mode = metal::SamplerAddressMode::Repeat; - cubic.t_address_mode = metal::SamplerAddressMode::ClampToBorderColor; - cubic.border_color = metal::SamplerBorderColor::OpaqueWhite; - let mut key = VariantKey::new(); - key.cubic_samplers - .insert(slot, SamplerWord::of(&cubic).0 & SamplerWord::CUBIC_STATE); - let compiled = dev - .compile_function( - &FunctionDescriptor::new(function()), - &key.lowering_inputs(Stage::Kernel), - &Budget::standard(), - ) - .expect("variant"); - assert!(compiled.artifact().facts.contains(&fact)); - assert_eq!( - CompiledFunction::from_bytes(&compiled.to_bytes(), &dev), - Ok(compiled.clone()) - ); - let pipeline = dev - .compile_compute_pipeline( - &ComputePipelineDescriptor::new(StageSource::Compiled(compiled)), - &Budget::standard(), - ) - .expect("pipeline"); - let decoded = ComputePipeline::from_bytes(&pipeline.to_bytes(), &dev).expect("decoded"); - assert_eq!(decoded, pipeline); - let shape = |desc: SamplerDescriptor| { - let mut table = StageTable::default(); - let mut facts = - TextureFacts::new(metal::TextureType::Type2D, metal::PixelFormat::RGBA8Unorm); - facts.usage = metal::TextureUsage::SHADER_READ; - table.textures.insert( - 0, - BoundTexture::Texture { - facts, - resource_id: None, - }, - ); - table.samplers.insert( - 0, - BoundSampler { - desc, - resource_id: None, - }, - ); - let mut state = BindState::default(); - state.stages.insert(Stage::Kernel, table); - state.shape() - }; - let plan = decoded.plan(&dev, &shape(cubic)).expect("plan"); - assert_eq!(plan.variant.cubic_samplers, key.cubic_samplers); - let plan = decoded - .plan(&dev, &shape(SamplerDescriptor::new())) - .expect("plan"); - assert!(plan.variant.cubic_samplers.is_empty()); -} - -/// A render pipeline compiled under the amplification draws variant round trips with its fact and -/// its amplification push fields, and the decoded pipeline's plan for a state whose amplification -/// multiview cannot express states the variant, so a cached variant settles as the compiled one -/// does. -#[test] -fn the_amplification_draws_variant_round_trips() { - use crate::bind::{BindState, VertexAmplification, ViewMapping}; - use crate::cache::VariantKey; - use crate::pipeline::facts::RuntimeFact; - use crate::pipeline::sym::PushField; - use crate::pipeline::AmplificationDraws; - let dev = device("nvidia-rtx50-linux"); - let Some(bc) = fixture("vertex_amplification") else { - return; - }; - let lib = Library::from_air(&bc).expect("library"); - let stage = |name: &str| { - StageSource::Function(FunctionDescriptor::new( - lib.function(name).expect("function"), - )) - }; - let mut d = RenderPipelineDescriptor::new(stage("amp_vertex")); - d.fragment = Some(stage("amp_fragment")); - d.max_vertex_amplification_count = 2; - let mut key = VariantKey::new(); - key.amplification_draws = Some(AmplificationDraws::new(true, true)); - let pipeline = dev - .compile_render_variant(&d, &key, &Budget::standard()) - .expect("pipeline"); - let decoded = RenderPipeline::from_bytes(&pipeline.to_bytes(), &dev).expect("decoded"); - assert_eq!(decoded, pipeline); - assert!(decoded.dependencies.iter().any(|d| d.fact - == RuntimeFact::AmplificationDraws { - layered: true, - viewports: true - })); - for field in [ - PushField::AmplificationId, - PushField::AmplificationLayerOffset, - PushField::AmplificationViewportOffset, - ] { - assert!( - decoded - .interface - .push - .iter() - .any(|p| p.fields.iter().any(|f| f.field == field)), - "{field:?}" - ); - } - let state = BindState { - render_target_array_length: 2, - vertex_amplification: VertexAmplification::new( - 2, - vec![ - ViewMapping { - viewport_array_index_offset: 1, - render_target_array_index_offset: 1, - }, - ViewMapping { - viewport_array_index_offset: 0, - render_target_array_index_offset: 0, - }, - ], - ), - ..Default::default() - }; - let plan = decoded.plan(&dev, &state.shape()).expect("plan"); - assert_eq!(plan.variant, key); -} - /// A kernel compiled under the storage-view variant round trips with its uniform-view facts (kept, /// viewed, spare, and the alias check), and the decoded pipeline's plan for a shape that binds a /// large buffer at the kept slot states the variant, so a cached variant settles as the compiled @@ -1571,231 +1276,6 @@ fn a_content_digest_is_the_content_not_the_key() { assert_ne!(edited.content_digest(), digest); } -/// A pipeline state's creation compile on a device that reads storage textures only with a declared -/// format takes stand-ins (`runtime::pipeline::stand_in`: the first of `R32Float`, `R32Uint` and -/// `R32Sint` each slot's texels take). On ANV on Iris Xe (RPL-P), the compile of -/// `a2_storage_read_formats` (a float, a uint and an int `read_write` texture, read) under those -/// stand-ins is the compile of the bind of those formats: its plan for that bind names its own key, -/// and the bind's compile has the same function and pipeline cache keys (what the disk cache stores -/// and loads them under) and byte-identical artifacts, so the compile carries nothing of the -/// stand-in beyond its key. Every bind of another format at any of the slots plans another key, -/// except where the plan does not bind that texture at all: a texture the slot cannot take is -/// replaced by the slot's neutral (`IncompatibleBinding`, `CrossClassNeutral` for a storage read -/// of another numeric class, or `AstcStorageNeutral` for an ASTC texture), an `R32` texture of the -/// slot's texel type, whose compile is the stand-in's. -#[test] -fn a_stand_in_compile_is_the_compile_of_its_formats_bind_and_no_other() { - use crate::bind::{BindState, BoundTexture, PlanDiagnostic, StageTable, TextureFacts}; - use crate::cache::VariantKey; - use crate::error::{Error, RuntimeInput}; - use crate::metal::format::storage_image_choice; - use crate::metal::{PixelFormat, TextureType, TextureUsage}; - - let Some(bc) = fixture("a2_storage_read_formats") else { - return; - }; - let dev = device("intel-irisxe-rplp-anv"); - let profile = dev.profile(); - assert!(!profile.fields().images.storage_read_without_format); - let descriptor = FunctionDescriptor::new( - Library::from_air(&bc) - .and_then(|lib| lib.function("a2_storage_read_formats")) - .expect("kernel"), - ); - let budget = Budget::standard(); - // The runtime's compile of a variant (`Variant::compiled`, without the cache). - let compile = |key: &VariantKey| -> Result<(CompiledFunction, ComputePipeline), Error> { - let inputs = key.lowering_inputs(Stage::Kernel); - let function = dev.compile_function(&descriptor, &inputs, &budget)?; - assert_eq!( - *function.key(), - dev.function_compile_key(&descriptor, &inputs) - ); - let pipeline = dev.compile_compute_pipeline( - &ComputePipelineDescriptor::new(StageSource::Compiled(function.clone())), - &budget, - )?; - Ok((function, pipeline)) - }; - let slot = |index: u32| SlotRef { - stage: Stage::Kernel, - class: SlotClass::Texture, - index, - }; - assert!(matches!( - compile(&VariantKey::new()), - Err(Error::NeedsInput(RuntimeInput::StorageTextureFormat { .. })) - )); - let formats = [ - (0, PixelFormat::R32Float), - (1, PixelFormat::R32Uint), - (2, PixelFormat::R32Sint), - ]; - let mut stand_in_key = VariantKey::new(); - for (index, pf) in formats { - let choice = storage_image_choice(pf, profile).expect("a stand-in's choice"); - stand_in_key.storage_images.insert(slot(index), choice); - } - let (stand_in_function, stand_in) = compile(&stand_in_key).expect("the stand-in compile"); - // The plan of a bind of `bound`, as the runtime's `settle` reads it off the creation compile. - let planned = |bound: &[(u32, PixelFormat)]| { - let mut table = StageTable::default(); - for &(index, pf) in bound { - let mut facts = TextureFacts::new(TextureType::Type2D, pf); - facts.usage = TextureUsage::SHADER_READ | TextureUsage::SHADER_WRITE; - let texture = BoundTexture::Texture { - facts, - resource_id: None, - }; - table.textures.insert(index, texture); - } - let mut state = BindState::default(); - state.stages.insert(Stage::Kernel, table); - stand_in.plan(&dev, &state.shape()) - }; - let own = planned(&formats).expect("the stand-ins' bind plans"); - assert!(own.diagnostics.is_empty(), "{:?}", own.diagnostics); - assert_eq!(own.variant, stand_in_key); - let (own_function, own_pipeline) = compile(&own.variant).expect("the bind's compile"); - assert_eq!(own_function.key(), stand_in_function.key()); - assert_eq!(own_pipeline.key(), stand_in.key()); - assert_eq!(own_function.to_bytes(), stand_in_function.to_bytes()); - assert_eq!(own_pipeline.to_bytes(), stand_in.to_bytes()); - // Any other format a texture can have, at any slot: another key, or the slot's neutral. - let (mut other_keys, mut replaced) = (0, 0); - let mut same = Vec::new(); - for at in 0..formats.len() { - for &pf in metal::PixelFormat::ALL { - if pf == formats[at].1 || pf == PixelFormat::Invalid { - continue; - } - let mut bound = formats; - bound[at].1 = pf; - let Ok(plan) = planned(&bound) else { - continue; - }; - let neutral = plan.diagnostics.iter().any(|d| match d { - PlanDiagnostic::IncompatibleBinding { slot: s, .. } - | PlanDiagnostic::CrossClassNeutral { slot: s, .. } - | PlanDiagnostic::AstcStorageNeutral { slot: s, .. } => *s == slot(bound[at].0), - _ => false, - }); - if neutral { - replaced += 1; - } else if plan.variant == stand_in_key { - same.push((at, pf)); - } else { - other_keys += 1; - } - } - } - assert!( - same.is_empty(), - "binds that plan the stand-ins' key: {same:?}" - ); - // An ASTC texture, of every profile and footprint, at a storage slot: the slot's neutral, and - // the plan says why (`PlanDiagnostic::AstcStorageNeutral`), which the runtime announces. - let astc = metal::PixelFormat::ALL - .iter() - .filter(|&&pf| crate::bind::AstcDecode::of(pf).is_some()); - for &pf in astc { - let mut bound = formats; - bound[0].1 = pf; - let plan = planned(&bound).unwrap_or_else(|e| panic!("{pf:?}: {e}")); - let said = plan.diagnostics.iter().any( - |d| matches!(d, PlanDiagnostic::AstcStorageNeutral { slot: s, .. } if *s == slot(0)), - ); - assert!(said, "{pf:?}: {:?}", plan.diagnostics); - } - assert!(other_keys > 0, "no other format plans"); - eprintln!( - "{other_keys} binds of other formats plan other keys; {replaced} are replaced by the \ - slot's neutral" - ); -} - -/// Kernel buffer slot `index`. -fn kernel_buffer(index: u32) -> SlotRef { - SlotRef { - stage: Stage::Kernel, - class: SlotClass::Buffer, - index, - } -} - -/// A variant key with device-address kernel buffer slots `slots`. -fn addressed(slots: &[u32]) -> super::VariantKey { - let mut key = super::VariantKey::new(); - key.psb_slots = slots.iter().copied().map(kernel_buffer).collect(); - key -} - -/// The large-buffer form's variant runs every dispatch or draw whose plan asks for fewer -/// device-address slots, and no other variant's. -#[test] -fn the_large_buffer_variant_covers_plans_of_fewer_device_address_slots() { - let large = addressed(&[0, 3]); - assert!(large.covers(&large)); - assert!(large.covers(&addressed(&[3]))); - assert!(large.covers(&super::VariantKey::new())); - assert!(!large.covers(&addressed(&[1]))); - assert!(!addressed(&[3]).covers(&large)); - let mut emulated = addressed(&[3]); - emulated.emulated_simdgroups = true; - assert!(!large.covers(&emulated)); -} - -/// The large-buffer form moves every slot whose range a large buffer exceeds to its device address, -/// unless the shape binds it without one (bytes), keeping what the key held; on a device without -/// device addresses (the fact a plan-time check) it moves none, so a variant still follows the -/// bound buffers there. -#[test] -fn the_large_buffer_form_moves_the_range_limited_slots_to_device_addresses() { - use crate::bind::{BindShape, BufferShape, StageShape}; - use crate::pipeline::{Mechanism, RuntimeDependency, RuntimeFact}; - let limited = |index, mechanism| { - let slot = kernel_buffer(index); - RuntimeDependency::new(RuntimeFact::BufferRangeLimit { slot }, mechanism) - }; - let addressed_device = [ - limited(0, Mechanism::Variant), - limited(2, Mechanism::Variant), - RuntimeDependency::new( - RuntimeFact::ThreadsPerThreadgroup, - Mechanism::Specialization, - ), - ]; - let unbound = BindShape::default(); - let empty = super::VariantKey::new(); - assert_eq!( - empty.large_buffer_form(&addressed_device, &unbound), - addressed(&[0, 2]) - ); - let mut stage = StageShape::default(); - stage.buffers.insert( - 2, - BufferShape::Bytes { - attribute_stride: None, - }, - ); - let mut bytes = BindShape::default(); - bytes.stages.insert(Stage::Kernel, stage); - assert_eq!( - empty.large_buffer_form(&addressed_device, &bytes), - addressed(&[0]) - ); - let mut emulated = addressed(&[5]); - emulated.emulated_simdgroups = true; - let mut widened = addressed(&[0, 5]); - widened.emulated_simdgroups = true; - assert_eq!( - emulated.large_buffer_form(&addressed_device, &bytes), - widened - ); - let floor_device = [limited(0, Mechanism::PlanTimeCheck)]; - assert_eq!(empty.large_buffer_form(&floor_device, &unbound), empty); -} - /// A render descriptor's linked-use answers and reflection decode as they were encoded, under /// their descriptor key on the device they were encoded for; another key or profile is /// `WrongDevice`, another kind of frame `Corrupt`, a changed byte `Corrupt`. diff --git a/crates/metal2vulkan/src/device/derive.rs b/crates/metal2vulkan/src/device/derive.rs index f273c5e63..2336d3de9 100644 --- a/crates/metal2vulkan/src/device/derive.rs +++ b/crates/metal2vulkan/src/device/derive.rs @@ -71,8 +71,7 @@ impl Device { /// coverage and the tessellator orders triangles as the device does (each module records its /// static note, `PrecisionNote::ClippedCoverageSplit` and /// `PrecisionNote::TessellationTriangleOrder`), `InterpolateAtOffset` reads from the pixel's center as GLSL.std.450 states, and a thread's - /// Function storage is the 16 KiB floor. A two-plane YCbCr texture's planes are read in place - /// on every device, whatever its type. Every stage output is 32-bit: a `half` color output + /// Function storage is the 16 KiB floor. Every stage output is 32-bit: a `half` color output /// reaches the device widened to `float`, whatever `storageInputOutput16` says. pub fn from_queries(desc: DeviceDescription, policy: DevicePolicy) -> Result { if desc.api_version < ApiVersion::V1_2 { diff --git a/crates/metal2vulkan/src/device/mechanism.rs b/crates/metal2vulkan/src/device/mechanism.rs index 763f80a8a..9609c8a67 100644 --- a/crates/metal2vulkan/src/device/mechanism.rs +++ b/crates/metal2vulkan/src/device/mechanism.rs @@ -166,11 +166,6 @@ pub fn mechanism(fact: &RuntimeFact, profile: &DeviceProfile) -> Mechanism { // The runtime pushes its arena's address, and sizes and orders the arena's slots by the // slot's bytes. RuntimeFact::PrivateArena { .. } => Mechanism::PushConstant, - // Keyed by the slots bound to a texture whose planes are read in place, on a profile that - // reads them so (`ProfileFields::ycbcr_in_place`). - RuntimeFact::YCbCrInPlace { .. } => Mechanism::Variant, - // Keyed by the slots bound to a texture whose rows are read and written in place. - RuntimeFact::TexelRows { .. } => Mechanism::Variant, // Keyed by the slots bound to a texture buffer of more texels than one view holds. RuntimeFact::TexelBufferParts { .. } => Mechanism::Variant, // The runtime refuses a dispatch whose slot address is not a multiple of the alignment. diff --git a/crates/metal2vulkan/src/device/profile.rs b/crates/metal2vulkan/src/device/profile.rs index b8b4fe314..6132d417e 100644 --- a/crates/metal2vulkan/src/device/profile.rs +++ b/crates/metal2vulkan/src/device/profile.rs @@ -359,14 +359,9 @@ pub struct ProfileFields { pub dynamic_vertex_stride: bool, /// The enabled capability sets `Requirements` are checked against. pub enabled: EnabledCaps, - /// Whether a two-plane YCbCr texture's planes may be read in place - /// (`bind::YCbCrInPlace`): on a device whose GPU reads the planes' memory with no bus between - /// (`VkPhysicalDeviceType` integrated or CPU), a texture slot whose function reads such a - /// texture only as the in-place form reads records `RuntimeFact::YCbCrInPlace`, and the - /// consumer states the planes of each texture it holds so. A discrete, virtual or other - /// device, or one of no stated type, keeps every such texture's image of converted texels, - /// which its refresh reads across the bus once per encoder where the in-place form would read - /// the planes there at every pass. Both forms read Metal's texels exactly. + /// Whether a two-plane YCbCr texture's planes may be read in place: true on every device + /// (`device::derive`). No lowering reads it; it is part of the profile's fingerprint, the + /// `Debug` text of these fields, which stored observations name. pub ycbcr_in_place: bool, /// The Function storage a thread holds correctly (`device::function_storage`): a stage's /// private memory, its call stacks included, may take this much a thread @@ -855,26 +850,4 @@ pub struct FormatTable { } #[cfg(test)] -mod tests { - use super::*; - use crate::device::requirements::Requirements; - use crate::pipeline::facts::{Mechanism, RuntimeFact}; - use crate::spirv::ids::{BlockId, DemoteTy, Value, VarId}; - - /// Vocabulary shared across threads by the consumer's worker pool. - #[test] - fn vocabulary_is_send_and_sync() { - fn send_sync() {} - send_sync::(); - send_sync::(); - send_sync::(); - send_sync::(); - send_sync::(); - send_sync::(); - send_sync::(); - send_sync::(); - send_sync::(); - send_sync::(); - send_sync::(); - } -} +mod tests {} diff --git a/crates/metal2vulkan/src/device/tests/mechanism.rs b/crates/metal2vulkan/src/device/tests/mechanism.rs index 0017eb054..fea9b74d7 100644 --- a/crates/metal2vulkan/src/device/tests/mechanism.rs +++ b/crates/metal2vulkan/src/device/tests/mechanism.rs @@ -128,12 +128,6 @@ fn every_fact() -> Vec { RuntimeFact::RegionViewports, RuntimeFact::PartialThreadgroups, RuntimeFact::GridTiles, - RuntimeFact::YCbCrInPlace { - slot, - samplers: 1, - device: true, - }, - RuntimeFact::TexelRows { slot }, RuntimeFact::ZeroedColor { color: 1, format: crate::metal::PixelFormat::RGBA8Unorm, @@ -287,15 +281,13 @@ fn variant(f: &RuntimeFact) -> usize { RuntimeFact::QuadPrimitiveIds => 54, RuntimeFact::RotatedWeights => 77, RuntimeFact::PrivateList => 80, - RuntimeFact::YCbCrInPlace { .. } => 60, RuntimeFact::PartialObjectThreadgroups => 83, RuntimeFact::OpenClMode => 85, RuntimeFact::RowLockstep => 86, - RuntimeFact::BorderTexels { .. } => 87, - RuntimeFact::HeapResidency { .. } => 88, + RuntimeFact::BorderTexels { .. } => 60, + RuntimeFact::HeapResidency { .. } => 78, RuntimeFact::CallThreadgroups => 84, RuntimeFact::PartialThreadgroups => 81, - RuntimeFact::TexelRows { .. } => 78, RuntimeFact::UnitAxes { .. } => 53, RuntimeFact::TexelBufferParts { .. } => 65, RuntimeFact::OpenClLineTexture { .. } => 69, @@ -309,7 +301,7 @@ fn variant(f: &RuntimeFact) -> usize { fn mechanism_is_total_over_every_fact_and_profile() { let facts = every_fact(); let covered: std::collections::BTreeSet = facts.iter().map(variant).collect(); - assert_eq!(covered, (0..89).collect(), "every_fact misses a variant"); + assert_eq!(covered, (0..87).collect(), "every_fact misses a variant"); for (stem, _) in super::committed_profiles() { let dev = device(&stem); let p = dev.profile(); @@ -384,8 +376,6 @@ fn mechanism_is_total_over_every_fact_and_profile() { | RuntimeFact::QuadPrimitiveIds | RuntimeFact::PrivateList | RuntimeFact::RegionViewports - | RuntimeFact::YCbCrInPlace { .. } - | RuntimeFact::TexelRows { .. } | RuntimeFact::TexelBufferParts { .. } | RuntimeFact::OpenClLineTexture { .. } | RuntimeFact::ZeroedColor { .. } diff --git a/crates/metal2vulkan/src/error/mod.rs b/crates/metal2vulkan/src/error/mod.rs index 294a2a7e8..6946d979b 100644 --- a/crates/metal2vulkan/src/error/mod.rs +++ b/crates/metal2vulkan/src/error/mod.rs @@ -1,8 +1,8 @@ -//! Errors: every way compiling or binding can fail, as typed values to match on. +//! Errors: every way compiling can fail, as typed values to match on. //! //! Compiling returns [`Error`]: `Device::from_queries`, `Library::parse`, every `Device::compile_*` -//! call, `Device::render_pipeline_key`, and the [`metal`](crate::metal) mappings. Planning and -//! instantiating a binding returns [`BindError`]. Decoding cached bytes returns +//! call, `Device::render_pipeline_key`, and the [`metal`](crate::metal) mappings. Decoding cached +//! bytes returns //! [`ArtifactError`](crate::cache::ArtifactError), which is always a cache miss. Match variants, //! not messages: `Display` is for logs. //! @@ -29,14 +29,7 @@ //! - [`Error::Internal`]: a translator bug ([`InternalError`]). A panic inside a compile entry //! point is caught and returned as one. //! -//! **Caching failures.** [`Error::retry`] says whether the same request can succeed later. A -//! [`BindError`] from a pipeline's `plan` depends only on the pipeline, the -//! device, and the [`BindShape`](crate::bind::BindShape), so it memoizes beside the plan on -//! `(PipelineKey, BindShape)`. One from `instantiate_dispatch` or `instantiate_draw` can also -//! depend on that dispatch or draw and on the bind state's per-draw values (offsets, lengths, -//! addresses, the stage-in region, the tessellation factor buffer), so it does not memoize on the -//! shape. [`BindError::NeedsVariant`] names the pipeline variant to plan or instantiate on -//! instead. +//! **Caching failures.** [`Error::retry`] says whether the same request can succeed later. //! //! Every enum here is `#[non_exhaustive]`, and so are [`Unsupported`], [`InputError`], and //! [`InternalError`]: new refusals and variants arrive additively, so match with a wildcard arm. @@ -1356,135 +1349,18 @@ pub enum DynamicLibraryProblem { FunctionConstants, } -/// A binder planning or instantiation error. A pipeline's `plan` sees only the pipeline, the -/// device, and the `BindShape`, so a planning error is permanent for its `(PipelineKey, -/// BindShape)` pair. An instantiation error can also depend on the dispatch or draw and on the -/// bind state's per-draw values (`MissingStageInRegion`, the patch-draw -/// errors, a descriptor range or texel buffer beyond its limit, ...), so it is not permanent for -/// the pair. `NeedsVariant` names the pipeline a dispatch or draw runs on instead. +/// Why the view of a texture a heap array may hold cannot be made (`bind::heap`): the storage-read +/// check of `lower::texture::slot` skips such a member. #[non_exhaustive] #[derive(Clone, Debug, PartialEq, Eq)] -pub enum BindError { - /// A slot index beyond the Metal maximum for its table. - SlotOutOfRange { slot: SlotRef }, - /// The bind shape needs something the device cannot do (local size limits, formats, - /// sampler reduction, GPU-encoded ICBs, …). +pub(crate) enum BindError { + /// The view needs something the device cannot do (a format, a view type). Unsupported(Unsupported), - /// A device-address slot received a buffer without a device address. - MissingDeviceAddress { slot: SlotRef }, - /// A descriptor-form slot's window exceeds the descriptor range limit (Profile F). - DescriptorRangeExceeded { - slot: SlotRef, - needed: u64, - limit: u64, - }, - /// A texture buffer bound through one texel buffer view exceeds `maxTexelBufferElements`: - /// one wider than that view binds through views of its parts (`bind::texel_parts`) except at - /// a slot whose function reads it through a sampler, on a device that indexes no array of - /// the slot's kind of texel buffer by a `NonUniform` value, or in a format whose block holds - /// several texels. - TexelBufferTooLarge { - slot: SlotRef, - elements: u64, - limit: u64, - }, - /// The pipeline and the binder disagree (a pipeline built by another device, or a binder - /// bug); always a bug, never the guest's. + /// A view the derivation cannot state; always a bug, never the guest's. Internal(InternalError), /// A bound resource's descriptor is invalid (e.g. a sampler whose LOD clamps are NaN or /// inverted). InvalidDescriptor(DescriptorError), - /// A render pipeline fetches a fixed-function vertex buffer that nothing is bound to. - UnboundVertexBuffer { slot: SlotRef }, - /// The set-1 heap's elements (one per resident texture a handle can name, plus the null - /// element) exceed the pipeline's heap capacity: the heap arrays' count, at most the handle - /// table's reach. - HeapTooLarge { count: u64, limit: u64 }, - /// A pipeline reads the Metal address of a buffer slot (`SlotGuestBase`: a pointer compare, - /// `ptrtoint`, or stored pointer) that is bound with `set*Bytes`, which gives the binder no - /// Metal address to write. - MissingGuestAddress { slot: SlotRef }, - /// The encoder's vertex amplification (`setVertexAmplificationCount:viewMappings:`) is not - /// one Metal draws this pipeline with: a count of 0, one above 1 for a pipeline whose - /// `maxVertexAmplificationCount` (`max`) is 1, or view mappings given for fewer - /// amplifications than the count. - InvalidVertexAmplification { - count: u32, - max: u32, - view_mappings: u32, - }, - /// The dispatch runs on another variant of the pipeline than the one planned: a threadgroup - /// with a partial simdgroup, which the kernel's flattened simd tier cannot run, runs on its - /// emulated-simdgroups variant (`VariantKey::emulated_simdgroups`). The consumer compiles the - /// pipeline under `variant` (the plan's key and what the dispatch adds, also - /// `BindingPlan::dispatch_variant`), plans it for the same shape, whose plan states `variant`, - /// and instantiates the dispatch there. Nothing is dispatched on the plan asked. A draw answers - /// it when the pipeline planned is not the variant the shape asks for (its amplification - /// draws, its colors, its depth clamp range, its rotated weights, its band, its tests, its - /// primitive IDs, its list or its regions); `variant` is then the plan's own. Boxed: a key holds a set per kind of variant, and the - /// error stays small. - NeedsVariant { - variant: Box, - }, - /// The compute encoder's imageblock size (`setImageblockWidth:height:`) is not one a kernel - /// with an imageblock dispatches with: a width or height of 0 (the encoder never set it) or - /// above 65535, which `get_imageblock_width` and `get_imageblock_height` cannot answer. - InvalidImageblockSize { width: u32, height: u32 }, - /// The kernel reads the compute encoder's stage-in region (a `[[stage_in]]` attribute - /// stepping by thread position, or `[[grid_origin]]` or `[[grid_size]]`) and the encoder - /// never set one (`setStageInRegion:`): what Metal reads then is not established. - MissingStageInRegion, - /// A draw Metal does not make with this pipeline: patches (`patches`) with a pipeline whose - /// vertex function is not post-tessellation, or primitives with one whose vertex function is. - InvalidDrawKind { patches: bool }, - /// A patch draw's `numberOfPatchControlPoints` (`given`) differs from the `N` the - /// post-tessellation vertex function's `[[patch(_, N)]]` states (`expected`). - PatchControlPoints { given: u32, expected: u32 }, - /// The tessellation factors a draw reads span more bytes (`needed`) than one storage-buffer - /// descriptor can bind (`limit`, `maxStorageBufferRange`), or an instance stride does. - TessellationFactorRange { needed: u64, limit: u64 }, - /// The encoder's tessellation factor scale (`bits`, the `float`'s) rounded to `half` is not a - /// positive `half` (it is negative, zero, or NaN). Metal's validation stops - /// `setTessellationFactorScale:` for a scale that is not a positive normal `float`, and - /// culls every patch for one that is 0 as a `half` (2^-30), which - /// a consumer draws as nothing. - InvalidTessellationFactorScale { bits: u32 }, - /// A tile function's render area (`BindState::render_area`) has a width or height of 0: the - /// encoder's render pass was never set, so the dispatch has no tile to run. - InvalidRenderArea { width: u32, height: u32 }, - /// A patch draw's patch index buffer is bound at an offset that is not a multiple of 4, which - /// Metal requires (a Metal probe on an M4: "patchIndexBufferOffset(2) must be a multiple of 4 - /// bytes"). - InvalidPatchIndexBuffer { offset: u64 }, - /// The patch indices a draw reads span more bytes (`needed`) than one storage-buffer - /// descriptor can bind (`limit`, `maxStorageBufferRange`). - PatchIndexRange { needed: u64, limit: u64 }, - /// A patch draw with a control-point index buffer (`indexed`, `drawIndexedPatches`) for a - /// pipeline whose `tessellationControlPointIndexType` is `None`, or one without it for a - /// pipeline whose type is not, which Metal's validation stops (a Metal probe on an M4: - /// "tessellationControlPointIndexType of MTLTessellationControlPointIndexTypeNone not valid for - /// drawIndexedPatches", and of `UInt32` for `drawPatches`). - ControlPointIndexing { indexed: bool }, - /// A patch draw's control-point index buffer is bound at an offset that is not a multiple of - /// its pipeline's index size, which Metal requires (a Metal probe on an M4: - /// "controlPointIndexBufferOffset(1) must be a multiple of 2 bytes"). - InvalidControlPointIndexBuffer { offset: u64 }, - /// The control-point indices a draw reads span more bytes (`needed`) than one storage-buffer - /// descriptor can bind (`limit`, `maxStorageBufferRange`). - ControlPointIndexRange { needed: u64, limit: u64 }, - /// A tile function reads its threadgroup argument `index`, which the encoder never set - /// (`BindState::tile_threadgroup`, `setThreadgroupMemoryLength:offset:atIndex:`): Metal's - /// validation stops the dispatch ("missing Threadgroup Memory binding"). - MissingThreadgroupMemory { index: u32 }, - /// A draw Metal does not make with this pipeline: a mesh draw (`mesh`) with a pipeline that is - /// not a mesh render pipeline, or a draw of primitives or patches with one (Metal ends the - /// process on `drawPrimitives` with a mesh pipeline state). - InvalidMeshDraw { mesh: bool }, - /// A draw of a pipeline whose vertex function writes the primitive ID - /// (`LoweringInputs::primitive_id_varying`) whose bind state names no primitive type - /// (`BindState::primitive_type`): its vertices per primitive, and whether an indexed draw - /// runs de-indexed (a strip's does not), depend on it. - MissingPrimitiveType, } impl fmt::Display for BindError { diff --git a/crates/metal2vulkan/src/lower/access/dynamic.rs b/crates/metal2vulkan/src/lower/access/dynamic.rs index 2944b6393..36c2a3d4c 100644 --- a/crates/metal2vulkan/src/lower/access/dynamic.rs +++ b/crates/metal2vulkan/src/lower/access/dynamic.rs @@ -245,8 +245,8 @@ pub enum Side { Null, } -/// SPIR-V words of the module's resident-set search ([`roots::resolve`], once per module): the -/// table's and the set's conversions, the hit test, and a function's frame (216); its two loops, +/// SPIR-V words of the module's resident-set search ([`roots::define_resolve`], once per module): +/// the table's and the set's conversions, the hit test, and a function's frame (216); its two loops, /// each with its two variables' stores and loads and the loop's and its exit's blocks (96 each); /// three steps (the halving, the entry's access chain and load, a compare, and a select, about 40 /// words each: one in the 64-bit narrowing, two in the 32-bit loop); and the window between them, diff --git a/crates/metal2vulkan/src/lower/access/tile.rs b/crates/metal2vulkan/src/lower/access/tile.rs index c7ab3bf9d..ba8869dc0 100644 --- a/crates/metal2vulkan/src/lower/access/tile.rs +++ b/crates/metal2vulkan/src/lower/access/tile.rs @@ -20,8 +20,8 @@ //! (`lower::dispatch`, measured for the threadgroups the binder alone runs, up to 32x32). //! //! **Tile staging.** The tile's cells are the threadgroup arena's imageblock region: its extent is -//! the tile size (`SpecKey::ImageblockWidth`/`Height`, which the binder specializes from -//! `BindState::imageblock_size`), and a cell holds each attachment's texel at its layout's offset +//! the tile size (`SpecKey::ImageblockWidth`/`Height`, which the consumer specializes from the +//! pass's tile size), and a cell holds each attachment's texel at its layout's offset //! (`memory::plan`: the aliased layout's, or the implicit layout's). The entry is a new function //! ([`wrap_entry`]) that loads the tile's pixels of every attachment the function reaches into the //! cells (a cell past the render area, `SpecKey::RenderAreaWidth`/`Height`, is zeroed: Metal leaves @@ -1013,9 +1013,6 @@ fn image_decl(s: &TileSlot) -> ImageDecl { level_views: None, extended: None, x_channel: false, - in_place: false, - planes_sampler: None, - rows: false, parts: None, } } diff --git a/crates/metal2vulkan/src/lower/arith/tests/bicubic.rs b/crates/metal2vulkan/src/lower/arith/tests/bicubic.rs index 5680bdcf3..a943ca95d 100644 --- a/crates/metal2vulkan/src/lower/arith/tests/bicubic.rs +++ b/crates/metal2vulkan/src/lower/arith/tests/bicubic.rs @@ -184,16 +184,8 @@ fn bicubic_routines_words_bound_their_emission() { routines::define_line(fb.module())?; Ok(x[0]) }) - without; - let quad = size(&|fb, x| { - routines::define_quad(fb.module())?; - Ok(x[0]) - }) - without; - eprintln!("bicubic routines: plane {plane} words, line {line} words, quad {quad} words"); - for (routine, words) in [ - (Routine::Plane, plane), - (Routine::Line, line), - (Routine::Quad, quad), - ] { + eprintln!("bicubic routines: plane {plane} words, line {line} words"); + for (routine, words) in [(Routine::Plane, plane), (Routine::Line, line)] { assert!( words <= routine.words() as usize, "{routine:?} is {words} words, bound {}", diff --git a/crates/metal2vulkan/src/lower/arith/tests/texel_round.rs b/crates/metal2vulkan/src/lower/arith/tests/texel_round.rs index c2620d93a..5cd819670 100644 --- a/crates/metal2vulkan/src/lower/arith/tests/texel_round.rs +++ b/crates/metal2vulkan/src/lower/arith/tests/texel_round.rs @@ -24,7 +24,6 @@ pub(super) fn half_of(x: f32, mode: HalfRounding) -> u32 { let q = a / ulp; let r = match mode { HalfRounding::NearestEven => q.round_ties_even(), - HalfRounding::NearestAway => q.round(), HalfRounding::TowardZeroSaturating => q.trunc(), } * ulp; let r = if r > 65504.0 { @@ -91,7 +90,6 @@ fn f32_to_half_rounds_exactly_in_every_mode() { .collect(); for mode in [ HalfRounding::NearestEven, - HalfRounding::NearestAway, HalfRounding::TowardZeroSaturating, ] { check( @@ -110,69 +108,3 @@ fn f32_to_half_rounds_exactly_in_every_mode() { ); } } - -/// The normalized grids the bicubic filter's exact sums land on: `16 · 255`, `16 · 127`, `65535`, -/// `32767`, and the sRGB step scale 4095. The grids: the bicubic sums', the sRGB table's, and the -/// normalized formats' fields' that a tile function's `half` member reads, down to a 2-bit alpha's -/// 3 and 1, where `3 · 2^24 / d` reaches `2^24`. -const GRIDS: [u32; 10] = [4080, 2032, 65535, 32767, 4095, 1023, 255, 127, 3, 1]; - -fn ratio_cases(d: u32) -> Vec { - let step = if d > 4095 { 13 } else { 1 }; - (0..=u64::from(d)) - .step_by(step) - .chain([1, 2, 3, 4, u64::from(d) - 1, u64::from(d)]) - // The quotients that round differently through `f32` (module docs). - .chain([65455, 65519, 32759]) - .filter(|k| *k <= u64::from(d)) - .map(|k| vec![vec![k], vec![u64::from(d)]]) - .collect() -} - -/// `ratio_to_f32` is correctly rounded with a run-time divisor on every grid. -#[test] -fn ratio_to_f32_is_correctly_rounded() { - let u = int(32); - for d in GRIDS { - check( - &format!("k / {d} to f32"), - &[u, u], - float(32), - &|fb, a| texel_round::ratio_to_f32(fb, u, a[0], a[1]), - &ratio_cases(d), - &|c| { - Some(vec![u64::from( - ((arg(c, 0) as f64 / d as f64) as f32).to_bits(), - )]) - }, - false, - ); - } -} - -/// `ratio_to_half` rounds `k / d` to `half` once, half denormals included, where rounding the -/// `f32` quotient would round twice. -#[test] -fn ratio_to_half_rounds_once() { - let u = int(32); - for d in GRIDS { - check( - &format!("k / {d} to half"), - &[u, u], - float(32), - &|fb, a| texel_round::ratio_to_half(fb, u, a[0], a[1]), - &ratio_cases(d), - &|c| { - let h = f64_to_f16(arg(c, 0) as f64 / d as f64); - Some(vec![u64::from((f16_to_f64(h) as f32).to_bits())]) - }, - false, - ); - } - // The quotients where the f32 detour differs exist: the test above covers them. - let twice = |k: u32, d: u32| { - let f = (f64::from(k) / f64::from(d)) as f32; - f64_to_f16(f64::from(f)) != f64_to_f16(f64::from(k) / f64::from(d)) - }; - assert!(twice(65455, 65535) && twice(65519, 65535) && twice(32759, 32767)); -} diff --git a/crates/metal2vulkan/src/lower/arith/texel_round.rs b/crates/metal2vulkan/src/lower/arith/texel_round.rs index 19b8c1eb4..dbc7e6be4 100644 --- a/crates/metal2vulkan/src/lower/arith/texel_round.rs +++ b/crates/metal2vulkan/src/lower/arith/texel_round.rs @@ -1,18 +1,11 @@ //! Exact conversions of texel values, shared by the sampling lowerings: integer sequences only, so //! every device and every fast-math mode answers alike. //! -//! - [`f32_to_half`]: an `f32` rounded to `half` to nearest even, to nearest with ties away from -//! zero, or toward zero saturating at the largest finite `half`; half denormals are kept. +//! - [`f32_to_half`]: an `f32` rounded to `half` to nearest even, or toward zero saturating at the +//! largest finite `half`; half denormals are kept. //! Metal converts a 32-bit float texel to a `half` result to nearest even when a shader reads //! it and toward zero, saturating at `±65504`, when it samples it (authored case //! `half-conversion-of-wider-texels-by-read-and-sample`). -//! - [`ratio_to_f32`] and [`ratio_to_half`]: `k / d` correctly rounded to `f32` or to `half` -//! (nearest even) for a divisor known only at run time, as a normalized channel's value `n / D` -//! on a format's grid is (the 8- and 16-bit normalized formats' bicubic sums). [`ratio_to_half`] -//! rounds once: rounding the `f32` quotient to `half` instead differs from it at `±65455 / -//! 65535`, `±65519 / 65535`, and `±32759 / 32767`. -//! - [`grid_value`]: a signed step's value `n / D` on a normalized format's grid exactly, the -//! bicubic sums'. //! //! Metal's texture reads and samples decode a raw sRGB code through its twelve-bit table, as its //! `air.unpack` does: the step `k` of [`srgb`](crate::lower::arith::srgb), then `k / 4095` @@ -34,8 +27,6 @@ use crate::spirv::ir::{BinOp, ConvOp, GlslOp}; pub enum HalfRounding { /// To nearest, ties to even; past the largest finite `half` to the infinity of the sign. NearestEven, - /// To nearest, ties away from zero; past the largest finite `half` to the infinity. - NearestAway, /// Toward zero; a finite value past the largest finite `half` becomes `±65504`. TowardZeroSaturating, } @@ -125,10 +116,6 @@ fn to_half(fb: &mut FunctionBuilder<'_>, f: Form, x: Value, rule: HalfRounding) let bias = even_bias(fb)?; bin(fb, BinOp::IAdd, mag, bias)? } - HalfRounding::NearestAway => { - let half = c(fb, 0x1000)?; - bin(fb, BinOp::IAdd, mag, half)? - } HalfRounding::TowardZeroSaturating => mag, }; let normal = bin(fb, BinOp::BitwiseAnd, biased, keep)?; @@ -136,7 +123,7 @@ fn to_half(fb: &mut FunctionBuilder<'_>, f: Form, x: Value, rule: HalfRounding) let over = bin(fb, BinOp::UGreaterThan, normal, max)?; let past = match rule { HalfRounding::TowardZeroSaturating => max, - HalfRounding::NearestEven | HalfRounding::NearestAway => inf, + HalfRounding::NearestEven => inf, }; let normal = fb.select(over, past, normal)?; // A denormal half (or zero): round on the grid 2^-24. @@ -171,7 +158,6 @@ fn to_half(fb: &mut FunctionBuilder<'_>, f: Form, x: Value, rule: HalfRounding) }; let up = match rule { HalfRounding::NearestEven => Some(even_up(fb)?), - HalfRounding::NearestAway => Some(bin(fb, BinOp::UGreaterThanEqual, rem, tie)?), HalfRounding::TowardZeroSaturating => None, }; let h = match up { @@ -190,144 +176,3 @@ fn to_half(fb: &mut FunctionBuilder<'_>, f: Form, x: Value, rule: HalfRounding) let ft = ty(fb, floats(f))?; fb.convert(ConvOp::Bitcast, r, ft) } - -/// The leading part of [`ratio_to_f32`] and [`ratio_to_half`]: for `1 <= k <= d < 2^16`, the -/// shift `e >= 0` that puts `a = k · 2^e` in `[d, 2d)`, and `a`. -fn normalize(fb: &mut FunctionBuilder<'_>, u: Form, k: Value, d: Value) -> BResult<(Value, Value)> { - let one = splat(fb, u, 1)?; - let m = fb.glsl(GlslOp::FindUMsb, &[k])?; - let top = fb.glsl(GlslOp::FindUMsb, &[d])?; - let e = bin(fb, BinOp::ISub, top, m)?; - let a = bin(fb, BinOp::ShiftLeftLogical, k, e)?; - let short = bin(fb, BinOp::ULessThan, a, d)?; - let a2 = bin(fb, BinOp::ShiftLeftLogical, a, one)?; - let a = fb.select(short, a2, a)?; - let e1 = bin(fb, BinOp::IAdd, e, one)?; - let e = fb.select(short, e1, e)?; - Ok((e, a)) -} - -/// Whether quotient `q` with remainder `r` of a division by `d` rounds up to nearest even. -fn round_up(fb: &mut FunctionBuilder<'_>, u: Form, q: Value, r: Value, d: Value) -> BResult { - let (z, one) = (splat(fb, u, 0)?, splat(fb, u, 1)?); - let twice = bin(fb, BinOp::ShiftLeftLogical, r, one)?; - let above = bin(fb, BinOp::UGreaterThan, twice, d)?; - let tie = bin(fb, BinOp::IEqual, twice, d)?; - let lsb = bin(fb, BinOp::BitwiseAnd, q, one)?; - let odd = bin(fb, BinOp::INotEqual, lsb, z)?; - let tie_up = bin(fb, BinOp::LogicalAnd, tie, odd)?; - bin(fb, BinOp::LogicalOr, above, tie_up) -} - -/// `k / d` correctly rounded to `f32` (nearest even), for `u32` lanes (form `u`) with -/// `0 <= k <= d` and `1 <= d < 2^16`, the divisor a run-time value, with integer operations only: -/// `k` shifted into `[d, 2d)`, two exact integer divisions for the significand and the last -/// remainder's rounding to nearest even, the divisor's leading bit found at run time. `k = 0` is -/// `+0`. -pub fn ratio_to_f32(fb: &mut FunctionBuilder<'_>, u: Form, k: Value, d: Value) -> BResult { - let c = |fb: &mut FunctionBuilder<'_>, v: u64| splat(fb, u, v); - let (z, one) = (c(fb, 0)?, c(fb, 1)?); - let zero = bin(fb, BinOp::IEqual, k, z)?; - let k = fb.glsl(GlslOp::UMax, &[k, one])?; - let (e, a) = normalize(fb, u, k, d)?; - // q = floor(a · 2^23 / d) in two exact divisions (a · 2^12 < 2^29). - let (k11, k12) = (c(fb, 11)?, c(fb, 12)?); - let hi = bin(fb, BinOp::ShiftLeftLogical, a, k12)?; - let q1 = bin(fb, BinOp::UDiv, hi, d)?; - let t = bin(fb, BinOp::IMul, q1, d)?; - let r1 = bin(fb, BinOp::ISub, hi, t)?; - let lo = bin(fb, BinOp::ShiftLeftLogical, r1, k11)?; - let q2 = bin(fb, BinOp::UDiv, lo, d)?; - let t = bin(fb, BinOp::IMul, q2, d)?; - let r2 = bin(fb, BinOp::ISub, lo, t)?; - let q = bin(fb, BinOp::ShiftLeftLogical, q1, k11)?; - let q = bin(fb, BinOp::BitwiseOr, q, q2)?; - let up = round_up(fb, u, q, r2, d)?; - let inc = fb.select(up, one, z)?; - let k126 = c(fb, 126)?; - let be = bin(fb, BinOp::ISub, k126, e)?; - let k23 = c(fb, 23)?; - let be = bin(fb, BinOp::ShiftLeftLogical, be, k23)?; - let bits = bin(fb, BinOp::IAdd, be, q)?; - let bits = bin(fb, BinOp::IAdd, bits, inc)?; - let bits = fb.select(zero, z, bits)?; - let ft = ty(fb, floats(u))?; - fb.convert(ConvOp::Bitcast, bits, ft) -} - -/// `k / d` correctly rounded to `half` (nearest even), held as its `f32`, for `u32` lanes (form -/// `u`) with `0 <= k <= d` and `1 <= d < 2^16`, the divisor a run-time value. `k = 0` is `+0`. -/// -/// A quotient of at least `2^-14` takes the 11-bit significand `floor(a · 2^10 / d)` of the -/// normalized `a` (`normalize`, one exact division: `a · 2^10 < 2^27`) and rounds it on the -/// remainder; the rounding carries into the exponent. A smaller one (then `k <= 3`) is -/// `k · 2^24 / d` rounded to an integer, its value on the denormal grid `2^-24`: at most `2^10`, -/// to which the step is clamped, so a lane that takes the normal quotient keeps the denormal -/// one's shifts in range (a grid `d <= 3` puts `3 · 2^24 / d` at `2^24` or more). -pub fn ratio_to_half(fb: &mut FunctionBuilder<'_>, u: Form, k: Value, d: Value) -> BResult { - let c = |fb: &mut FunctionBuilder<'_>, v: u64| splat(fb, u, v); - let (z, one) = (c(fb, 0)?, c(fb, 1)?); - let zero = bin(fb, BinOp::IEqual, k, z)?; - let kk = fb.glsl(GlslOp::UMax, &[k, one])?; - let (e, a) = normalize(fb, u, kk, d)?; - let k10 = c(fb, 10)?; - let hi = bin(fb, BinOp::ShiftLeftLogical, a, k10)?; - let q = bin(fb, BinOp::UDiv, hi, d)?; - let t = bin(fb, BinOp::IMul, q, d)?; - let r = bin(fb, BinOp::ISub, hi, t)?; - let up = round_up(fb, u, q, r, d)?; - let inc = fb.select(up, one, z)?; - // Bits: exponent 127 - e, significand (q - 2^10) << 13, the rounding added below it. - let k126 = c(fb, 126)?; - let be = bin(fb, BinOp::ISub, k126, e)?; - let k23 = c(fb, 23)?; - let be = bin(fb, BinOp::ShiftLeftLogical, be, k23)?; - let sig = bin(fb, BinOp::IAdd, q, inc)?; - let k13 = c(fb, 13)?; - let sig = bin(fb, BinOp::ShiftLeftLogical, sig, k13)?; - let normal = bin(fb, BinOp::IAdd, be, sig)?; - // Below 2^-14 (e >= 15): k <= 3, so k · 2^24 < 2^26. - let k3 = c(fb, 3)?; - let small_k = fb.glsl(GlslOp::UMin, &[kk, k3])?; - let k24 = c(fb, 24)?; - let n = bin(fb, BinOp::ShiftLeftLogical, small_k, k24)?; - let g = bin(fb, BinOp::UDiv, n, d)?; - let t = bin(fb, BinOp::IMul, g, d)?; - let gr = bin(fb, BinOp::ISub, n, t)?; - let gup = round_up(fb, u, g, gr, d)?; - let ginc = fb.select(gup, one, z)?; - let g = bin(fb, BinOp::IAdd, g, ginc)?; - let k1024 = c(fb, 1024)?; - let g = fb.glsl(GlslOp::UMin, &[g, k1024])?; - let denormal = grid_bits(fb, u, g)?; - let k15 = c(fb, 15)?; - let small = bin(fb, BinOp::UGreaterThanEqual, e, k15)?; - let bits = fb.select(small, denormal, normal)?; - let bits = fb.select(zero, z, bits)?; - let ft = ty(fb, floats(u))?; - fb.convert(ConvOp::Bitcast, bits, ft) -} - -/// The value `n / D` of signed grid step `n` (`i32` bits in `u32` lanes of form `u`, within -/// `[-D, D]`; `d` the grid `D` in `u32` lanes, `1 <= D < 2^16`): `+0` for zero, else the -/// magnitude `|n| / D` correctly rounded by `round` ([`ratio_to_f32`], [`ratio_to_half`], or a -/// choice of the two) with the sign of `n`. -pub fn grid_value( - fb: &mut FunctionBuilder<'_>, - u: Form, - n: Value, - d: Value, - round: impl FnOnce(&mut FunctionBuilder<'_>, Value, Value) -> BResult, -) -> BResult { - let z = splat(fb, u, 0)?; - let neg = bin(fb, BinOp::SLessThan, n, z)?; - let m = fb.glsl(GlslOp::SAbs, &[n])?; - let r = round(fb, m, d)?; - let ut = ty(fb, u)?; - let bits = fb.convert(ConvOp::Bitcast, r, ut)?; - let sign = splat(fb, u, 0x8000_0000)?; - let sign = fb.select(neg, sign, z)?; - let bits = bin(fb, BinOp::BitwiseOr, bits, sign)?; - let ft = ty(fb, floats(u))?; - fb.convert(ConvOp::Bitcast, bits, ft) -} diff --git a/crates/metal2vulkan/src/lower/dispatch.rs b/crates/metal2vulkan/src/lower/dispatch.rs index 24c6a32d1..7b1bd5690 100644 --- a/crates/metal2vulkan/src/lower/dispatch.rs +++ b/crates/metal2vulkan/src/lower/dispatch.rs @@ -63,7 +63,7 @@ //! partial object threadgroup's draw or a kernel's ragged grid on its partial-threadgroups //! variant (below). //! -//! With `MultiRegion = 0` (single-region `Threadgroups` and every `ThreadgroupsIndirect`) the push +//! With `MultiRegion = 0` (a single-region `dispatchThreadgroups:` and every indirect one) the push //! field is not read: the region base is 0, `L = (sx, sy, sz)`, `threadgroups_per_grid = //! NumWorkgroups`, and `threads_per_grid = NumWorkgroups · L`, so GPU-written indirect arguments //! work. With `MultiRegion = 1` (the edge regions of `dispatchThreads` and group-count splits, @@ -1203,12 +1203,6 @@ pub fn region_bytes(base: [u32; 3], threads: [u32; 3], l: [u32; 3]) -> Option<[u Some(out) } -/// The `DispatchRegion` bytes of a draw of the object threadgroups `threads` fill at nominal -/// size `l`, the last along an axis running only the threads left ([`NONUNIFORM`]). -pub fn partial_region_bytes(threads: [u32; 3], l: [u32; 3]) -> Option<[u8; 32]> { - nonuniform_region_bytes([0; 3], threads, l) -} - /// [`region_bytes`] of a region flagged [`NONUNIFORM`]: its threadgroups the ones `threads` fill /// at nominal size `l` from `base`, the last along an axis running only the threads left. pub fn nonuniform_region_bytes(base: [u32; 3], threads: [u32; 3], l: [u32; 3]) -> Option<[u8; 32]> { diff --git a/crates/metal2vulkan/src/lower/dispatch/tests.rs b/crates/metal2vulkan/src/lower/dispatch/tests.rs index 96d027183..3b379fca6 100644 --- a/crates/metal2vulkan/src/lower/dispatch/tests.rs +++ b/crates/metal2vulkan/src/lower/dispatch/tests.rs @@ -548,7 +548,7 @@ fn group_count_splits_match_the_single_dispatch() { /// A partial object threadgroups module's run of a draw of `threads` threads in threadgroups of /// `l` (one dispatch of the threadgroups the threads fill, rounded up, each of `l` invocations, -/// `MultiRegion` 1), its region flagged where `flagged` ([`partial_region_bytes`]): each +/// `MultiRegion` 1), its region flagged where `flagged` ([`nonuniform_region_bytes`]): each /// invocation's live word and builtins. fn run_partial( m: &TypedModule, @@ -571,7 +571,7 @@ fn run_partial( } spec.insert(SpecKey::MultiRegion, 1); let push = match flagged { - true => partial_region_bytes(threads, l), + true => nonuniform_region_bytes([0; 3], threads, l), false => region_bytes([0; 3], threads, l), }; let res = Resources { diff --git a/crates/metal2vulkan/src/lower/fragment/color.rs b/crates/metal2vulkan/src/lower/fragment/color.rs index d5742cc4c..c70038d61 100644 --- a/crates/metal2vulkan/src/lower/fragment/color.rs +++ b/crates/metal2vulkan/src/lower/fragment/color.rs @@ -307,9 +307,6 @@ pub(crate) fn texture_decl(class: ImageHandleClass) -> ImageDecl { level_views: None, extended: None, x_channel: false, - in_place: false, - planes_sampler: None, - rows: false, parts: None, } } diff --git a/crates/metal2vulkan/src/lower/push.rs b/crates/metal2vulkan/src/lower/push.rs index a6ca0d7c9..f08285ef5 100644 --- a/crates/metal2vulkan/src/lower/push.rs +++ b/crates/metal2vulkan/src/lower/push.rs @@ -195,10 +195,6 @@ pub const fn shape(f: PushField) -> FieldShape { // 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, - // An in-place YCbCr texture's size, planes and conversion. - PushField::YCbCrInPlace(_) => FieldShape::UVec4Array(2), - // A texture's size, rows and first texel in its texel buffer view. - PushField::TexelRows(_) => FieldShape::UVec4Array(1), // The residual is below `min{Storage,Uniform}BufferOffsetAlignment`. PushField::SlotBindOffset(_) | PushField::VertexBufferStride(_) => FieldShape::U32, // The bytes of a slot's buffer before its bind offset, and its length: each at most 2 GiB diff --git a/crates/metal2vulkan/src/lower/sampler/anisotropic/tests.rs b/crates/metal2vulkan/src/lower/sampler/anisotropic/tests.rs index ce528dccd..41c2cbd68 100644 --- a/crates/metal2vulkan/src/lower/sampler/anisotropic/tests.rs +++ b/crates/metal2vulkan/src/lower/sampler/anisotropic/tests.rs @@ -319,126 +319,6 @@ fn a_runtime_slot_takes_metals_filter_where_its_word_states_anisotropy() { assert!(!a.facts.contains(&fact)); } -/// The binder names a slot of the `AnisotropicSampler` fact in the plan's variant where the shape -/// binds a sampler whose word states anisotropy (`maxAnisotropy` above 1), whatever its filters, -/// and nowhere else; the variant's own plan for that shape states the same key, so a draw or -/// dispatch settles on it. Its compiled pipeline round trips as the cached form. On lavapipe -/// without `samplerAnisotropy`, where the emulation runs. -#[test] -fn a_bound_anisotropic_sampler_asks_for_the_variant() { - use crate::bind::{ - BindState, BoundSampler, BoundTexture, SamplerDescriptor, StageTable, TextureFacts, - }; - use crate::budget::Budget; - use crate::cache::{PipelineArtifact, VariantKey}; - use crate::device::DeviceDescription; - use crate::library::Library; - use crate::metal; - use crate::pipeline::artifact::ComputePipeline; - use crate::pipeline::descriptor::{ComputePipelineDescriptor, FunctionDescriptor, StageSource}; - let Some(bc) = assemble("binder", RUNTIME_KERNEL) else { - return; - }; - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../metal2vulkan-validation/profiles/lavapipe.json"); - let text = std::fs::read_to_string(&path).expect("profile"); - let mut desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); - assert!(desc.features.remove(&VkFeature::SamplerAnisotropy)); - let dev = Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device"); - let pipeline = |inputs: &LoweringInputs| { - let function = Library::from_air(&bc) - .and_then(|lib| lib.function("k")) - .expect("kernel"); - let compiled = dev - .compile_function( - &FunctionDescriptor::new(function), - inputs, - &Budget::standard(), - ) - .expect("function"); - dev.compile_compute_pipeline( - &ComputePipelineDescriptor::new(StageSource::Compiled(compiled)), - &Budget::standard(), - ) - .expect("pipeline") - }; - let shape = |desc: SamplerDescriptor| { - let mut table = StageTable::default(); - let mut facts = - TextureFacts::new(metal::TextureType::Type2D, metal::PixelFormat::RGBA8Unorm); - facts.usage = metal::TextureUsage::SHADER_READ; - facts.mipmap_level_count = 4; - table.textures.insert( - 0, - BoundTexture::Texture { - facts, - resource_id: None, - }, - ); - table.samplers.insert( - 0, - BoundSampler { - desc, - resource_id: None, - }, - ); - let mut state = BindState::default(); - state.stages.insert(Stage::Kernel, table); - state.shape() - }; - let sampler = |filter, mip, anisotropy| { - let mut desc = SamplerDescriptor::new(); - desc.min_filter = filter; - desc.mag_filter = filter; - desc.mip_filter = mip; - desc.max_anisotropy = anisotropy; - desc - }; - let mut key = VariantKey::new(); - key.anisotropic_samplers.insert(SLOT); - let base = pipeline(&LoweringInputs::new()); - let named = pipeline(&key.lowering_inputs(Stage::Kernel)); - let decoded = ComputePipeline::from_bytes(&named.to_bytes(), &dev).expect("decoded"); - assert_eq!(decoded, named); - let linear = metal::SamplerMinMagFilter::Linear; - let nearest = metal::SamplerMinMagFilter::Nearest; - let (none, near) = ( - metal::SamplerMipFilter::NotMipmapped, - metal::SamplerMipFilter::Nearest, - ); - // Anisotropic samplers, the consumer's (linear filters, a nearest mip filter) among them. - for desc in [ - sampler(linear, near, 16), - sampler(linear, near, 2), - sampler(nearest, none, 4), - ] { - let shape = shape(desc); - let plan = base.plan(&dev, &shape).expect("plan"); - assert_eq!( - plan.variant.anisotropic_samplers, key.anisotropic_samplers, - "{desc:?}" - ); - let plan = decoded.plan(&dev, &shape).expect("variant's plan"); - assert_eq!( - plan.variant.anisotropic_samplers, key.anisotropic_samplers, - "{desc:?}" - ); - } - // Isotropic samplers and none: the base. - for desc in [ - sampler(linear, none, 1), - sampler(linear, near, 1), - SamplerDescriptor::new(), - ] { - let plan = base.plan(&dev, &shape(desc)).expect("plan"); - assert!(plan.variant.anisotropic_samplers.is_empty(), "{desc:?}"); - } - let plan = base - .plan(&dev, &crate::bind::BindShape::default()) - .expect("plan"); - assert!(plan.variant.anisotropic_samplers.is_empty()); -} - /// A fragment function sampling slot 0, a texture of AIR type `tex_ty`, at its implicit level /// through the constexpr sampler of first state word `words`: `call` makes `%v` (a `float4`) of /// `%uv` (the position over 16) or `%uvw` (`%uv` and 0.5); `decl` is the intrinsic's declaration. diff --git a/crates/metal2vulkan/src/lower/sampler/bicubic.rs b/crates/metal2vulkan/src/lower/sampler/bicubic.rs index 1c8697fca..1bc985200 100644 --- a/crates/metal2vulkan/src/lower/sampler/bicubic.rs +++ b/crates/metal2vulkan/src/lower/sampler/bicubic.rs @@ -30,8 +30,9 @@ //! linear filter under the sampler's address modes: its sample equals a linear sampler's with //! the same modes on all 4,096 lanes of each run, under `clamp_to_edge`, `repeat`, //! `mirrored_repeat`, `clamp_to_zero`, and one mirrored axis beside a clamped one. The -//! emulation takes the linear 2D sample there ([`routines::Quad`]) over the footprint's inner -//! taps, which are the linear filter's (the bicubic and linear footprints share `q`). +//! emulation takes the linear 2D sample there ([`routines::Plane`]'s `bilinear` form) over the +//! footprint's inner taps, which are the linear filter's (the bicubic and linear footprints +//! share `q`). //! - On a level of at least four texels each way, a mirrored axis of a format Metal filters //! bicubically reads texel 1 at fraction 0 whatever the coordinate: with both axes mirrored //! every lane is texel `(1, 1)` exactly, and with one the sample varies with the other axis @@ -354,7 +355,6 @@ pub(super) struct Tys { pub(super) f32_: TypeId, i32_: TypeId, pub(super) u32_: TypeId, - pub(super) bool_: TypeId, pub(super) vec4: TypeId, } @@ -370,13 +370,13 @@ impl Tys { width: 32, signed: false, })?; - let bool_ = m.ty(SType::Bool)?; + // Declared here, so the module keeps the order of its type declarations. + m.ty(SType::Bool)?; let vec4 = m.ty(SType::Vector { elem: f32_, len: 4 })?; Ok(Tys { f32_, i32_, u32_, - bool_, vec4, }) } @@ -1098,25 +1098,6 @@ pub(super) fn footprint_of_image( footprint_at(fb, t, &at, (size, base, image), bits, taps) } -/// [`footprint_of_image`] of an image whose base-level size `size` (a `uvec2`) the caller states: -/// an in-place texture's (`super::in_place`), whose taps read the base level of its one level. -pub(super) fn footprint_sized( - fb: &mut FunctionBuilder<'_>, - t: &Tys, - (coord, layer, offset): (SValue, Option, Option<(SValue, u8)>), - (size, image): (SValue, CombinedImage), - bits: Bits, - (taps, parent): (&Taps<'_>, Option), -) -> BResult { - let at = At { - coord, - layer, - parent, - offset, - }; - footprint_at(fb, t, &at, (size, None, image), bits, taps) -} - /// The footprint of sample `s` over `taps` on an image of level-0 size `size` (image facts /// `image`), the border color seen through the channels of the bound format's treatment `bits`. pub(super) fn footprint_on( diff --git a/crates/metal2vulkan/src/lower/sampler/bicubic/routines.rs b/crates/metal2vulkan/src/lower/sampler/bicubic/routines.rs index ec8788cf8..8fa2cfbbe 100644 --- a/crates/metal2vulkan/src/lower/sampler/bicubic/routines.rs +++ b/crates/metal2vulkan/src/lower/sampler/bicubic/routines.rs @@ -3,9 +3,8 @@ //! //! Each routine takes the bound format's `BicubicTexels` bits (or its `TexelFormat` class) as an //! argument, the texture slot's specialization constant at every call, so once a device -//! specializes the module and inlines a call, the paths of the other formats fold away. The -//! texel routine (the in-place linear quad's sum) is a kept routine (`ModuleBuilder::kept_routine`), -//! declared `DontInline`; the others are plain functions. +//! specializes the module and inlines a call, the paths of the other formats fold away. They are +//! plain functions. //! //! - [`Plane`] (a 2D bicubic sample): the Catmull-Rom weights (`a = -1/2`) of each axis's fraction //! `k / 256` in `f32`, the footprint's sixteen taps summed row by row and then the rows, in the @@ -15,28 +14,14 @@ //! datapath (`PrecisionNote::BicubicFilterArithmetic`). //! - [`Line`] (a 1D bicubic sample, bilinear over taps `i` and `i + 1` whatever the format): the //! device's `FMix` of the two taps, then the normalized formats' clamps. -//! - [`Quad`] (a two-plane YCbCr texture's linear sample read in place, `super::super::in_place`, -//! bilinear over the footprint's taps `(i, j)`, `(i + 1, j)`, `(i, j + 1)`, and `(i + 1, j + 1)`). -//! `exact` weighs each tap `wx · wy` in units of `2^-16`, the integer weights `256 - k` and `k` -//! per axis (a merged axis's fraction arrives as 0), and truncates each code's term before the -//! half-up step, as Metal's 2D sums do: a packed field's by its own `s` -//! (`PackedTexels::filter_truncation`: 7 on YCbCr's grid `2048`). -//! -//! The codes are recovered exactly: a YCbCr field's channels (`PackedTexels::YCbCr2048`, -//! `YCbCr8192`, `YCbCrExtended8192`) arrive as their steps `k / D`, exact, and sum on the grid -//! `2048` or `8192` (`S = D`), each 2D term `k · w` truncated by `2^7`; the extended-range field's -//! steps are signed and reach `2D`, so its quotient divides by `2D` and doubles, exactly, and a -//! YCbCr field's `half` result rounds the exact `f32` with ties away from zero. use crate::lower::arith::legal::{FloatFmt, Form, Held}; use crate::lower::arith::ops::splat; -use crate::lower::arith::texel_round::{self, HalfRounding}; use crate::metal::bicubic::BicubicTexels; -use crate::metal::texel_format::{PackedTexels, TexelFormat}; use crate::spirv::builder::{FunctionBuilder, ModuleBuilder}; use crate::spirv::error::BResult; use crate::spirv::ids::{FuncId, TypeId, Value}; -use crate::spirv::ir::{BinOp, ConvOp, GlslOp, Type, UnOp}; +use crate::spirv::ir::{BinOp, ConvOp, GlslOp, Type}; /// The routines a module defines for its emulated samples, by the samples' dimension. #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] @@ -45,8 +30,6 @@ pub enum Routine { Plane, /// A 1D (or 1D array) texture's bicubic sample: [`Line`]. Line, - /// A two-plane YCbCr texture's linear sample read in place: [`Quad`]. - Quad, } impl Routine { @@ -56,7 +39,6 @@ impl Routine { match self { Routine::Plane => PLANE_WORDS, Routine::Line => LINE_WORDS, - Routine::Quad => 5440, } } @@ -65,7 +47,6 @@ impl Routine { match self { Routine::Plane => "sampler.bicubic.plane", Routine::Line => "sampler.bicubic.line", - Routine::Quad => "sampler.linear.quad", } } } @@ -221,23 +202,6 @@ fn clamped(fb: &mut FunctionBuilder<'_>, flags: Value, r: Value) -> BResult vec4`: the exact sum on the field's grid, taking a merged axis's fraction as 0. - pub exact: FuncId, -} - -/// Define the in-place linear sample's routine in `mb`. -pub fn define_quad(mb: &mut ModuleBuilder) -> BResult { - Ok(Quad { - exact: define_exact_quad(mb)?, - }) -} - // ---- Types and constants ---- /// The four lanes of a texel. @@ -260,13 +224,6 @@ fn fform(lanes: u8) -> Form { } } -fn bform(lanes: u8) -> Form { - Form { - held: Held::Bool, - lanes, - } -} - /// The routines' types. #[derive(Clone, Copy)] struct Tys { @@ -274,7 +231,6 @@ struct Tys { u: TypeId, b: TypeId, vf: TypeId, - vu: TypeId, } fn types(mb: &mut ModuleBuilder) -> BResult { @@ -288,32 +244,23 @@ fn types(mb: &mut ModuleBuilder) -> BResult { elem: f, len: LANES, })?; - let vu = mb.ty(Type::Vector { + // Declared here, so the module keeps the order of its type declarations. + mb.ty(Type::Vector { elem: u, len: LANES, })?; - Ok(Tys { f, u, b, vf, vu }) + Ok(Tys { f, u, b, vf }) } fn bin(fb: &mut FunctionBuilder<'_>, op: BinOp, a: Value, b: Value) -> BResult { fb.binary(op, a, b) } -/// A float operation no device may contract or regroup. -fn exact_op(fb: &mut FunctionBuilder<'_>, op: BinOp, a: Value, b: Value) -> BResult { - fb.binary_no_contraction(op, a, b) -} - /// The `u32` scalar `v`. fn u1(fb: &mut FunctionBuilder<'_>, v: u32) -> BResult { splat(fb, uform(1), u64::from(v)) } -/// The `uvec4` of `v` in every lane. -fn u4(fb: &mut FunctionBuilder<'_>, v: u32) -> BResult { - splat(fb, uform(LANES), u64::from(v)) -} - /// The `f32` scalar `x`. fn f1(fb: &mut FunctionBuilder<'_>, x: f32) -> BResult { splat(fb, fform(1), u64::from(x.to_bits())) @@ -342,396 +289,3 @@ fn finish(mut fb: FunctionBuilder<'_>, r: Value) -> BResult { fb.ret(Some(r))?; fb.finish() } - -// ---- The exact sums ---- - -/// The grid of an `EXACT` format: `D` (`16 · 255`, `16 · 127`, `65535`, -/// or `32767`; with `SRGB` `4095` for the color lanes and `16 · 255` for -/// alpha; with `EXTENDED` `16 · 510` for the color lanes, `8192` an `_sRGB` twin's, and `8 · 510` -/// for alpha) as `u32` lanes, the bounds of a tap's code (`±D`, `±2D` for `EXTENDED`) as `f32` -/// lanes, the bounds of a sum's step (`[0, D]`, `[-D, D]` for a signed format, -/// `[-2D, 2D]` for `EXTENDED`) as `i32` bits, and what the result's quotient reads: the grid it -/// divides by (`D`, or `2D` for `EXTENDED`, whose steps reach past `D`), the factor that restores -/// it (1 or 2, exact), and the lanes whose `half` result rounds ties away from zero (an -/// `EXTENDED` `_sRGB` twin's color lanes, a YCbCr field's). A tap's code is recovered on `scale` -/// (`f32` lanes) and -/// multiplied by `per` (`u32` lanes): `D` and 1 (no `per`), but on a packed normalized format's -/// lanes (its `TexelFormat::PACKED` field with `PackedTexels::filter_grids`, where the routine -/// reads such a class: [`Packed`]), which take the field's grid `D` each, their channel's code -/// scale `S` (also the code's bound) and `D / S`. Such a routine's grid also states whether the -/// field names its grids and the field's truncation `s` per lane -/// (`PackedTexels::filter_truncation`), which [`Truncation::of`] takes there. A field whose steps -/// reach `±2D` (`PackedTexels::filter_extended`) bounds its codes by `±2S` and divides by `2D`. -struct Grid { - scale: Value, - per: Option, - cap: Value, - neg_cap: Value, - lo: Value, - hi: Value, - divisor: Value, - factor: Value, - away: Value, - packed: Option<(Value, Value)>, -} - -/// Whether a routine's treatment may name a packed normalized format's grids: a `TexelFormat` -/// class's routine (the linear filter's), not a `BicubicTexels` one's. -#[derive(Clone, Copy, PartialEq, Eq)] -enum Packed { - Field, - No, -} - -fn grid(fb: &mut FunctionBuilder<'_>, t: Tys, flags: Value, packed: Packed) -> BResult { - let wide16 = flag(fb, flags, BicubicTexels::WIDE16)?; - let snorm = flag(fb, flags, BicubicTexels::SNORM)?; - let (d16s, d16u) = (u1(fb, 32767)?, u1(fb, 65535)?); - let (d8s, d8u) = (u1(fb, 16 * 127)?, u1(fb, 16 * 255)?); - let d16 = fb.select(snorm, d16s, d16u)?; - let d8 = fb.select(snorm, d8s, d8u)?; - let d = fb.select(wide16, d16, d8)?; - let d = broadcast(fb, t.vu, d)?; - let srgb = flag(fb, flags, BicubicTexels::SRGB)?; - let (color, alpha) = (u1(fb, 4095)?, u1(fb, 16 * 255)?); - let srgb_d = fb.composite_construct(t.vu, &[color, color, color, alpha])?; - let d = fb.select(srgb, srgb_d, d)?; - let extended = flag(fb, flags, BicubicTexels::EXTENDED)?; - let (linear, steps, alpha) = (u1(fb, 16 * 510)?, u1(fb, 8192)?, u1(fb, 8 * 510)?); - let color = fb.select(srgb, steps, linear)?; - let extended_d = fb.composite_construct(t.vu, &[color, color, color, alpha])?; - let d = fb.select(extended, extended_d, d)?; - let (one, two) = (u1(fb, 1)?, u1(fb, 2)?); - let factor_u = fb.select(extended, two, one)?; - let factor_u = broadcast(fb, t.vu, factor_u)?; - let divisor = bin(fb, BinOp::IMul, d, factor_u)?; - let factor = fb.convert(ConvOp::ConvertUToF, factor_u, t.vf)?; - let lo = |fb: &mut FunctionBuilder<'_>, divisor: Value| -> BResult { - let neg = fb.unary(UnOp::SNegate, divisor)?; - let z = u4(fb, 0)?; - let signed = bin(fb, BinOp::LogicalOr, snorm, extended)?; - fb.select(signed, neg, z) - }; - let srgb_steps = bin(fb, BinOp::LogicalAnd, extended, srgb)?; - let (yes, no) = (splat(fb, bform(1), 1)?, splat(fb, bform(1), 0)?); - let lanes = crate::lower::arith::ops::ty(fb, bform(LANES))?; - let color_lanes = fb.composite_construct(lanes, &[yes, yes, yes, no])?; - let none = splat(fb, bform(LANES), 0)?; - let away = fb.select(srgb_steps, color_lanes, none)?; - let Some(p) = packed_grids(fb, t, flags, packed)? else { - let cap = fb.convert(ConvOp::ConvertUToF, divisor, t.vf)?; - return Ok(Grid { - scale: fb.convert(ConvOp::ConvertUToF, d, t.vf)?, - per: None, - cap, - neg_cap: fb.unary(UnOp::FNegate, cap)?, - lo: lo(fb, divisor)?, - hi: divisor, - divisor, - factor, - away, - packed: None, - }); - }; - let packed = p.named; - // A packed field's lanes: its grids, each tap's code recovered on its channel's scale - // (clamped there, within `±2S` where the field's steps reach `±2D`) and moved onto the grid; - // such a field's step divided by `2D` and doubled, and a YCbCr field's `half` rounded with - // ties away from zero. - let scale = fb.select(packed, p.scales, d)?; - let scale = fb.convert(ConvOp::ConvertUToF, scale, t.vf)?; - let wide = bin(fb, BinOp::LogicalAnd, packed, p.wide)?; - let span = fb.select(wide, two, one)?; - let span = broadcast(fb, t.vu, span)?; - let field_cap = bin(fb, BinOp::IMul, p.scales, span)?; - let cap = fb.select(packed, field_cap, divisor)?; - let cap = fb.convert(ConvOp::ConvertUToF, cap, t.vf)?; - let neg_cap = fb.unary(UnOp::FNegate, cap)?; - let ones = u4(fb, 1)?; - let per = Some(fb.select(packed, p.per, ones)?); - let field_divisor = bin(fb, BinOp::IMul, p.d, span)?; - let divisor = fb.select(packed, field_divisor, divisor)?; - let span = fb.convert(ConvOp::ConvertUToF, span, t.vf)?; - let factor = fb.select(packed, span, factor)?; - let rounds_away = bin(fb, BinOp::LogicalAnd, packed, p.away)?; - let away = fb.select(rounds_away, color_lanes, away)?; - Ok(Grid { - scale, - per, - cap, - neg_cap, - lo: lo(fb, divisor)?, - hi: divisor, - divisor, - factor, - away, - packed: Some((packed, p.truncation)), - }) -} - -/// The code of normalized texel `x` on grid `g`, as `i32` bits: `RoundEven(x · D)` (module docs), -/// or on a packed normalized format's lane `RoundEven(x · S) · (D / S)`, its code on its channel's -/// scale `S` moved onto the grid (the device's value may miss `c / S` by more than half a grid -/// step, never by half a code). The product is clamped into the code bounds first (`[-D, D]`, -/// `[-2D, 2D]` for an extended-range lane, `[-S, S]` on a packed lane), which changes no texel's of -/// the format, so that a texel of a format this routine does not serve (its result is selected -/// away) still converts and shifts within range. -fn code(fb: &mut FunctionBuilder<'_>, g: &Grid, x: Value) -> BResult { - let y = fb.binary_no_contraction(BinOp::FMul, x, g.scale)?; - let y = fb.glsl(GlslOp::NClamp, &[y, g.neg_cap, g.cap])?; - let y = fb.glsl(GlslOp::RoundEven, &[y])?; - let it = crate::lower::arith::ops::ty(fb, uform(LANES))?; - let c = fb.convert(ConvOp::ConvertFToS, y, it)?; - match g.per { - Some(per) => bin(fb, BinOp::IMul, c, per), - None => Ok(c), - } -} - -/// The value `n / D` of grid step `n` (`i32` bits, within the grid's step bounds): `+0` for -/// zero, the magnitude divided exactly, rounded to `f32`, or to `half` when `half`, and the sign -/// set. An extended-range lane divides by `2D` and doubles, exactly; its `_sRGB` color lanes' -/// `half` is the exact `f32` rounded with ties away from zero. -fn ratio(fb: &mut FunctionBuilder<'_>, g: &Grid, n: Value, half: Value) -> BResult { - let rf = texel_round::grid_value(fb, uform(LANES), n, g.divisor, |fb, m, d| { - texel_round::ratio_to_f32(fb, uform(LANES), m, d) - })?; - let rh = texel_round::grid_value(fb, uform(LANES), n, g.divisor, |fb, m, d| { - texel_round::ratio_to_half(fb, uform(LANES), m, d) - })?; - let rf = exact_op(fb, BinOp::FMul, rf, g.factor)?; - let rh = exact_op(fb, BinOp::FMul, rh, g.factor)?; - let ra = texel_round::f32_to_half(fb, fform(LANES), rf, HalfRounding::NearestAway)?; - let rh = fb.select(g.away, ra, rh)?; - fb.select(half, rh, rf) -} - -/// The parameters of a [`Quad`] routine, in order. -struct QuadParams { - t00: Value, - t01: Value, - t10: Value, - t11: Value, - kx: Value, - ky: Value, - flags: Value, - half: Value, -} - -fn quad_params(fb: &mut FunctionBuilder<'_>, t: Tys) -> BResult { - Ok(QuadParams { - t00: fb.param(t.vf)?, - t01: fb.param(t.vf)?, - t10: fb.param(t.vf)?, - t11: fb.param(t.vf)?, - kx: fb.param(t.u)?, - ky: fb.param(t.u)?, - flags: fb.param(t.u)?, - half: fb.param(t.b)?, - }) -} - -/// `fn(t00, t01, t10, t11, kx, ky, flags, half) -> vec4` (module docs, [`Quad::exact`]): Metal's -/// sum over the four taps under the weights `w = wx · wy` in units of `2^-16`, the axes' weights -/// `256 - k` and `k` (a merged axis's fraction arrives as 0), each term truncated: `T = Σ ⌊c · w / -/// 2^s⌋` for the codes `c` on the format's grid, then the step `⌊(T + 2^(15 - s)) / 2^(16 - -/// s)⌋`, clamped and divided by the grid exactly. `s` is 8 for a 16-bit format's codes and 4 for -/// every 12-bit grid: an sRGB color lane's step is truncated, and an 8-bit lane's `16 · -/// code` term is a multiple of 16, so its sum is the exact one, rounded half up. An extended-range -/// format's `s` -/// is 7 on a color lane and 4 on alpha (every lane of random 2D footprints of the -/// four formats). An unsigned format's product `c · w` is below `2^32` (codes below `2^16`, weights -/// at most `2^16`), a `u32` word shifted logically; a signed format's codes (at most `2^15 - 1` in -/// magnitude) keep it below `2^31`, an `i32` shifted arithmetically (toward negative infinity), as -/// an extended-range format's do (below `2^14`). The terms' sum is below `2^24` in magnitude (the -/// weights sum to `2^16`, and the codes are below `2^12` where `s` is 4, below `2^14` where it is -/// 7, and below `2^16` where it is 8), and so is the biased one. -fn define_exact_quad(mb: &mut ModuleBuilder) -> BResult { - let t = types(mb)?; - let mut fb = mb.kept_routine(t.vf)?; - let q = quad_params(&mut fb, t)?; - let fb_ = &mut fb; - let g = grid(fb_, t, q.flags, Packed::Field)?; - let n = quad_sum(fb_, t, &g, &q, |fb, x| code(fb, &g, x))?; - let r = ratio(fb_, &g, n, q.half)?; - finish(fb, r) -} - -/// The exact quad's step ([`define_exact_quad`]) over grid `g` of `q`'s taps (`(i, j)`, `(i + 1, -/// j)`, `(i, j + 1)`, `(i + 1, j + 1)`), each tap's code `code_of` it (taken where its term is), -/// under `q`'s fractions and flags: the terms' step rounded half up and clamped into the grid's -/// step bounds, which the caller divides. -fn quad_sum( - fb_: &mut FunctionBuilder<'_>, - t: Tys, - g: &Grid, - q: &QuadParams, - mut code_of: impl FnMut(&mut FunctionBuilder<'_>, Value) -> BResult, -) -> BResult { - let (kx, ky, flags) = (q.kx, q.ky, q.flags); - let k256 = u1(fb_, 256)?; - let wx = [bin(fb_, BinOp::ISub, k256, kx)?, kx]; - let wy = [bin(fb_, BinOp::ISub, k256, ky)?, ky]; - let tr = Truncation::of(fb_, t, flags, g)?; - let rows = [[q.t00, q.t01], [q.t10, q.t11]]; - let mut total = u4(fb_, 0)?; - for (row, b) in rows.into_iter().zip(wy) { - for (x, a) in row.into_iter().zip(wx) { - let c = code_of(fb_, x)?; - let w = bin(fb_, BinOp::IMul, a, b)?; - let w = broadcast(fb_, t.vu, w)?; - let term = tr.term(fb_, c, w)?; - total = bin(fb_, BinOp::IAdd, total, term)?; - } - } - let n = tr.step(fb_, total)?; - fb_.glsl(GlslOp::SClamp, &[n, g.lo, g.hi]) -} - -/// How a 2D or 3D exact sum truncates its terms: `s` per lane (8 for a 16-bit format's codes, 4 for -/// every 12-bit grid, for an extended-range format 7 on a color lane and 4 on alpha, and on a -/// packed field's grids the field's own, `PackedTexels::filter_truncation`: 7 on YCbCr's grid -/// `2048`), the bias `2^(15 - s)` and shift `16 - s` of the step, and whether the codes are signed -/// (a signed normalized or an extended-range format's), whose terms and sum shift arithmetically -/// (toward negative infinity). -struct Truncation { - s: Value, - bias: Value, - shift: Value, - signed: Value, -} - -impl Truncation { - fn of(fb: &mut FunctionBuilder<'_>, t: Tys, flags: Value, g: &Grid) -> BResult { - let wide16 = flag(fb, flags, BicubicTexels::WIDE16)?; - let snorm = flag(fb, flags, BicubicTexels::SNORM)?; - let extended = flag(fb, flags, BicubicTexels::EXTENDED)?; - let (a, b) = (u1(fb, 8)?, u1(fb, 4)?); - let plain = fb.select(wide16, a, b)?; - let plain = broadcast(fb, t.vu, plain)?; - let seven = u1(fb, 7)?; - let lanes = fb.composite_construct(t.vu, &[seven, seven, seven, b])?; - let s = fb.select(extended, lanes, plain)?; - let s = match g.packed { - Some((named, own)) => fb.select(named, own, s)?, - None => s, - }; - let (k15, k16, one) = (u4(fb, 15)?, u4(fb, 16)?, u4(fb, 1)?); - let up = bin(fb, BinOp::ISub, k15, s)?; - let bias = bin(fb, BinOp::ShiftLeftLogical, one, up)?; - let shift = bin(fb, BinOp::ISub, k16, s)?; - let signed = bin(fb, BinOp::LogicalOr, snorm, extended)?; - Ok(Truncation { - s, - bias, - shift, - signed, - }) - } - - /// The term `⌊c · w / 2^s⌋` of code `c` under weight `w` (`uvec4` lanes). - fn term(&self, fb: &mut FunctionBuilder<'_>, c: Value, w: Value) -> BResult { - let prod = bin(fb, BinOp::IMul, c, w)?; - let unsigned = bin(fb, BinOp::ShiftRightLogical, prod, self.s)?; - let signed = bin(fb, BinOp::ShiftRightArithmetic, prod, self.s)?; - fb.select(self.signed, signed, unsigned) - } - - /// The grid step `⌊(T + 2^(15 - s)) / 2^(16 - s)⌋` of the terms' sum `T`. - fn step(&self, fb: &mut FunctionBuilder<'_>, total: Value) -> BResult { - let total = bin(fb, BinOp::IAdd, total, self.bias)?; - let unsigned = bin(fb, BinOp::ShiftRightLogical, total, self.shift)?; - let signed = bin(fb, BinOp::ShiftRightArithmetic, total, self.shift)?; - fb.select(self.signed, signed, unsigned) - } -} - -/// A packed field's grids ([`packed_grids`]), each `uvec4` lanes. -struct PackedGrids { - /// Whether the treatment names the field's grids. - named: Value, - /// The grids `D`. - d: Value, - /// The channels' code scales `S`. - scales: Value, - /// `D / S`. - per: Value, - /// The 2D and 3D sums' truncation `s` (`PackedTexels::filter_truncation`). - truncation: Value, - /// Whether the field's codes and steps reach `±2D` (`PackedTexels::filter_extended`), a - /// `bool`. - wide: Value, - /// Whether a `half` result rounds the step's value with ties away from zero - /// (`PackedTexels::ycbcr`), a `bool`. - away: Value, -} - -/// Whether treatment `flags` names a packed field's grids (its `TexelFormat::PACKED` field with -/// `PackedTexels::filter_grids`, under `BicubicTexels::EXACT`: `TexelFormat::packed_exact`), and -/// per lane that field's grids (each lane 1 for any other field); `None` for a routine whose -/// treatment names none. -fn packed_grids( - fb: &mut FunctionBuilder<'_>, - t: Tys, - flags: Value, - packed: Packed, -) -> BResult> { - if packed == Packed::No { - return Ok(None); - } - let shift = u1(fb, TexelFormat::PACKED)?; - let field = bin(fb, BinOp::ShiftRightLogical, flags, shift)?; - let four_bits = u1(fb, 0xF)?; - let field = bin(fb, BinOp::BitwiseAnd, field, four_bits)?; - let no = splat(fb, bform(1), 0)?; - let (mut named, mut wide, mut away) = (no, no, no); - let ones = u4(fb, 1)?; - let (mut d, mut s, mut per, mut truncation) = (ones, ones, ones, ones); - for p in PackedTexels::ALL { - let (Some(grids), Some(cut)) = (p.filter_grids(), p.filter_truncation()) else { - continue; - }; - // A field without code scales (a YCbCr field's exact steps) recovers its codes on the - // grids. - let scales = p.scales().unwrap_or(grids); - let k = u1(fb, p as u32)?; - let is = bin(fb, BinOp::IEqual, field, k)?; - let lanes = |fb: &mut FunctionBuilder<'_>, v: [u32; 4]| -> BResult { - let mut l = Vec::with_capacity(4); - for x in v { - l.push(u1(fb, x)?); - } - fb.composite_construct(t.vu, &l) - }; - let mut steps = grids; - for (g, s) in steps.iter_mut().zip(scales) { - *g /= s.max(1); - } - let these_d = lanes(fb, grids)?; - let these_s = lanes(fb, scales)?; - let these_per = lanes(fb, steps)?; - let these_cut = lanes(fb, cut)?; - d = fb.select(is, these_d, d)?; - s = fb.select(is, these_s, s)?; - per = fb.select(is, these_per, per)?; - truncation = fb.select(is, these_cut, truncation)?; - named = bin(fb, BinOp::LogicalOr, named, is)?; - if p.filter_extended() { - wide = bin(fb, BinOp::LogicalOr, wide, is)?; - } - if p.ties_away() { - away = bin(fb, BinOp::LogicalOr, away, is)?; - } - } - let exact = flag(fb, flags, BicubicTexels::EXACT)?; - let named = bin(fb, BinOp::LogicalAnd, named, exact)?; - Ok(Some(PackedGrids { - named, - d, - scales: s, - per, - truncation, - wide, - away, - })) -} diff --git a/crates/metal2vulkan/src/lower/sampler/extended.rs b/crates/metal2vulkan/src/lower/sampler/extended.rs index 904c42e2b..fb941e072 100644 --- a/crates/metal2vulkan/src/lower/sampler/extended.rs +++ b/crates/metal2vulkan/src/lower/sampler/extended.rs @@ -483,9 +483,6 @@ pub(super) struct Texture { /// The slot's `SpecKey::OffsetBaseAxes` tests, by which a texel offset is placed /// (`position::offset_dropped`), where the sample reads them ([`Sample::offset_base`]). pub parent: Option, - /// The base level's size (a `uvec2`) where the image's own query does not state it: an - /// in-place texture's, whose image is its planes' texel buffer (`super::in_place`). - pub size: Option, } /// How a sample's raw texels decode: by one form, a slot's variant's; or by the form a heap handle's class index names (`sampler::heap_raw`), through the @@ -503,9 +500,6 @@ pub(super) enum Decode { /// The routine of a `float` result, and of a `half` one where the access rounds to it. routines: (FuncId, Option), }, - /// The planes of a two-plane YCbCr texture read in place, each tap converted as Metal reads - /// it (`super::in_place::texel`). - InPlace(super::in_place::Planes), } /// Where a sample reads: its plane coordinate (two floats), a 2D array's layer (an integer), the @@ -688,7 +682,6 @@ fn sampled( flags: value(fb, flags)?, swizzle, parent, - size: None, }; let at = At { coord, @@ -787,7 +780,7 @@ fn sampled( } /// The footprint over `taps` of the sample at `at` of `tex`, the border color seen through the -/// channels `bits` state: its size the image's query of the taps' level, or `tex`'s stated size. +/// channels `bits` state: its size the image's query of the taps' level. fn footprint_of( fb: &mut FunctionBuilder<'_>, t: &Tys, @@ -796,24 +789,14 @@ fn footprint_of( bits: Bits, taps: &Taps<'_>, ) -> BResult { - match tex.size { - Some(size) => super::bicubic::footprint_sized( - fb, - t, - (at.coord, at.layer, at.passed), - (size, tex.image), - bits, - (taps, tex.parent), - ), - None => footprint_of_image( - fb, - t, - (at.coord, at.layer, at.passed), - (tex.img, tex.image), - bits, - (taps, tex.parent), - ), - } + footprint_of_image( + fb, + t, + (at.coord, at.layer, at.passed), + (tex.img, tex.image), + bits, + (taps, tex.parent), + ) } /// The filtered texel at `at` of `tex` (unswizzled) by `state`: a constexpr sampler's linear or @@ -1043,9 +1026,7 @@ fn swizzled(fb: &mut FunctionBuilder<'_>, tex: &Texture, x: SValue) -> BResult, fb: &mut FunctionBuilder<'_>, @@ -1054,19 +1035,6 @@ pub(super) fn filtered( tex: &Texture, addressing: Addressing<'_>, ) -> BResult { - if let Decode::InPlace(_) = tex.decode { - let Some(quad) = cx.decl.families.sampler.linear_quad else { - return Err(cx.fail("an in-place linear sample without its routines")); - }; - let mut args = quad_taps(cx, fb, t, at, tex, addressing)?.to_vec(); - args.push(tex.flags); - let half = fb.module().constant(Constant::Scalar { - ty: t.bool_, - bits: ConstBits(u64::from(at.half)), - })?; - args.push(value(fb, half)?); - return fb.call(quad.exact, &args)?.ok_or_else(missing_routine); - } let x = match tex.image.plane { 3 => { let (taps, [kx, ky, kz]) = block_taps(cx, fb, t, at, tex, addressing)?; @@ -1290,7 +1258,7 @@ pub(super) fn nearest( let v = texel(cx, fb, &fp, tex, &site, false)?; crate::lower::arith::extended_range::bfloat_sample_half(fb, v) } - (true, Decode::Form { .. } | Decode::InPlace(_)) => texel(cx, fb, &fp, tex, &site, true), + (true, Decode::Form { .. }) => texel(cx, fb, &fp, tex, &site, true), // A heap handle's form: both roundings of the one raw texel, chosen by the form. (true, Decode::Heap { bfloat, .. }) => { let (raw, inside) = tap(fb, &fp, tex, &site)?; @@ -1352,11 +1320,6 @@ pub(super) fn texel( site: &[Tap], half: bool, ) -> BResult { - if let Decode::InPlace(planes) = tex.decode { - let (at, inside) = fp.site(fb, site)?; - let v = super::in_place::texel(fb, &planes, tex.img, at, half)?; - return fp.border(fb, v, inside); - } let (raw, inside) = tap(fb, fp, tex, site)?; let v = decoded(cx, fb, tex, raw, half)?; fp.border(fb, v, inside) @@ -1400,7 +1363,6 @@ fn decoded( fb.call(routine, &[raw, form, inside])? .ok_or_else(missing_routine) } - Decode::InPlace(_) => Err(cx.fail("an in-place tap decoded as a raw texel")), } } diff --git a/crates/metal2vulkan/src/lower/sampler/face/tests/routines.rs b/crates/metal2vulkan/src/lower/sampler/face/tests/routines.rs index be1fd1654..f6f4c1d5c 100644 --- a/crates/metal2vulkan/src/lower/sampler/face/tests/routines.rs +++ b/crates/metal2vulkan/src/lower/sampler/face/tests/routines.rs @@ -1,5 +1,5 @@ -//! The sampling routines are routines: the in-place linear quad's exact sum states `DontInline`, -//! every other function none, and the entry states none. +//! The bicubic filters' sums are plain routines: each states no function control, as the entry +//! does. use super::kernel_on; use crate::lower::sampler::bicubic::routines; @@ -21,21 +21,16 @@ fn controls(words: &[u32]) -> Vec { out } -/// The linear and bicubic filters' sums beside a kernel entry: the in-place linear quad's exact -/// sum, a kept routine, states `DontInline` (0x2) and every other function `None`. +/// The bicubic filters' sums beside a kernel entry: each routine and the entry state `None`. #[test] -fn the_texel_routine_alone_is_declared_dont_inline() { +fn the_bicubic_routines_state_no_function_control() { let mut b = ModuleBuilder::new(); routines::define_plane(&mut b).expect("plane"); routines::define_line(&mut b).expect("line"); - routines::define_quad(&mut b).expect("quad"); let m = kernel_on(b, 3, &|_, p, _| Ok(p)).expect("kernel"); let words = serialize(m).expect("serialized").words; - let mut got = controls(&words); - got.sort_unstable(); - // 3 routines (the plane's, the line's and the quad's) and the entry. - assert!(got.len() >= 4, "{} functions", got.len()); - let mut want = vec![0; got.len() - 1]; - want.push(0x2); - assert_eq!(got, want, "each routine's control, and none on the entry"); + let got = controls(&words); + // 2 routines (the plane's and the line's) and the entry. + assert!(got.len() >= 3, "{} functions", got.len()); + assert_eq!(got, vec![0; got.len()], "each function's control"); } diff --git a/crates/metal2vulkan/src/lower/sampler/heap_raw.rs b/crates/metal2vulkan/src/lower/sampler/heap_raw.rs index bc8b839a3..ee685ddf8 100644 --- a/crates/metal2vulkan/src/lower/sampler/heap_raw.rs +++ b/crates/metal2vulkan/src/lower/sampler/heap_raw.rs @@ -214,7 +214,6 @@ pub(crate) fn emit( swizzle: None, // A heap element's access reads no slot's `OffsetBaseAxes`. parent: None, - size: None, }; let at = At { coord: super::emit::plane_coord(cx, fb, s)?, diff --git a/crates/metal2vulkan/src/lower/sampler/in_place.rs b/crates/metal2vulkan/src/lower/sampler/in_place.rs deleted file mode 100644 index 212f2e944..000000000 --- a/crates/metal2vulkan/src/lower/sampler/in_place.rs +++ /dev/null @@ -1,1093 +0,0 @@ -//! Samples of a two-plane YCbCr texture whose planes the function reads in place -//! (`bind::YCbCrInPlace`, `LoweringInputs::ycbcr_in_place`): the slot is the planes' uniform texel -//! buffer, and every tap of a sample is the texel Metal reads there, computed from the codes. -//! -//! **A tap** at texel `(x, y)` (`bind::ycbcr_convert`'s module docs, measured there): the luma -//! code at its place, the four nearest chroma pairs (column `⌊x / 2⌋` and the one after it for an -//! odd `x`, before it for an even one, each clamped to the plane, rows alike) weighted 9/3/3/1 and -//! rounded to a code, `C = (S + 8) >> 4`, each code the byte or the high 10 bits of its 16-bit -//! word; then the conversion of the surface's range and matrix (`bind::ycbcr_convert`): every -//! channel `v / 2048` exactly, alpha 1. An element of the texel buffer holds two luma codes or one -//! chroma pair, so a tap fetches five elements. The texture's size, its planes' first elements -//! and rows, and its conversion are the slot's push field (`PushField::YCbCrInPlace`), read once -//! where it dominates. -//! -//! **A sample** is Metal's filter of those texels: a nearest sample the tap at Metal's position, -//! a linear one the exact routine's sum of the four taps of Metal's footprint on the grid `2048` -//! (`PackedTexels::YCbCr2048`, the class the texture's image of converted texels is filtered -//! under), through the extended-range emulation's footprint and routines (`super::extended`), its -//! texel offset placed as there. Metal samples such a texture's one level whatever the sampler's -//! mip filter, level, bias or gradients, so the sample reads the base level alone. **A gather** of -//! a component is the four taps of the linear footprint, each the texel Metal reads there (a border -//! tap the border texel), that component of each in Vulkan's order, as the extended-range -//! emulation gathers (`extended::gathered`); it follows no filter. A 4:2:0 -//! texture samples repeat, mirrored repeat and mirror-clamp-to-edge as clamp-to-edge: a constexpr -//! sampler's modes arrive mapped (`LoweringInputs::address_maps`), and a runtime sampler's word is -//! mapped here ([`mapped_word`]). A border tap reads the border color through the format's -//! channels, alpha 1. -//! -//! **The model** (`YCbCrInPlacePolicy::Model`, the default): a linear sample that addresses no -//! border on either plane axis and whose texel offset no parent's size places is Vulkan's Y′CbCr -//! model of the codes, as the device's own conversion with a linear chroma filter computes it: -//! the four luma codes around the sample's point (in luma texels, its offset added) blended -//! bilinearly, the four chroma pairs around the same point of the chroma plane (half the luma -//! coordinate, Metal's midpoint siting) blended bilinearly, each index clamped to its plane's -//! edge; then the surface's range and matrix, Metal's coefficients -//! (`bind::ycbcr_convert::coefficients`) over `2^23` in `float`, each channel clamped into -//! `[0, 1]`, alpha 1. Eight fetches, where Metal's sum takes twenty. A constexpr sampler's state -//! decides it as the module is made; a runtime sampler's word as the function runs, a word that -//! filters nearest or addresses a border taking Metal's sample. Recorded -//! `PrecisionNote::HalfSampleFilter` or `FloatSampleFilter` (`select`'s `model_note`). -//! -//! **The device's sampler** (`LoweringInputs::ycbcr_planes_sampled`): where the consumer holds -//! the planes as an image of the multi-planar 4:2:0 format over their bytes and every sample of the -//! slot is one the device's own sampler Y′CbCr conversion takes (no border address mode, no texel -//! offset placed by a parent's size, no gather: `VUID-RuntimeSpirv-OpTypeSampledImage-12206` -//! admits only samples through that conversion), the slot is a combined image sampler whose immutable sampler -//! is that conversion (`ResourceKind::YCbCrPlanes`), and a sample is the device's sample of the -//! image at level 0: a linear one at Metal's coordinate (normalized from pixels by the push field's -//! size, its texel offset moved in texels), a nearest one at the centre of the luma texel Metal -//! reads, clamped to the edge (where the device's linear filter of its conversion reads that -//! texel's luma and Metal's 9/3/3/1 chroma weights). The answer is the device's conversion and -//! filter, not Metal's integer arithmetic. No `ConstOffset` or `Offset` reaches the sample -//! (`VUID-RuntimeSpirv-ConstOffset-10718`), and the size queries read the push field as above. - -use crate::air::ir::ValueId; -use crate::lower::emit::EmitCx; -use crate::metal::PixelFormat; -use crate::pipeline::sym::{PushField, SlotRef}; -use crate::spirv::builder::constructs::{ArmEnd, ArmFn, Merged}; -use crate::spirv::builder::FunctionBuilder; -use crate::spirv::error::BResult; -use crate::spirv::ids::{DemoteTy, TypeId, Value as SValue}; -use crate::spirv::ir::{BinOp, ConstBits, Constant, ConvOp, GlslOp, ImageOperands, Type as SType}; - -use super::bicubic::{Addressing, Tys}; -use super::extended::{Decode, State, Texture}; -use super::{CombinedImage, Pixel}; - -/// A sample of an in-place texture slot (module docs). -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct Sample { - /// The texture slot, under its in-place variant. - pub texture: u32, - /// The sampler's state the sample follows: a constexpr sampler's modes as the texture's map - /// sends them, or a runtime sampler's word. - pub state: State, - /// The constant texel offset Metal applies, per plane axis. - pub offset: Option>, - /// The offset moves an axis that may repeat or mirror: it is placed by the slot's - /// `SpecKey::OffsetBaseAxes` tests, as an extended-range sample places it. - pub offset_base: bool, - /// The plane coordinate: two floats. - pub coord: ValueId, - /// The result is `half`, else `float`. - pub half: bool, - /// A gather of this component (0 to 3, red first) instead of a sample (module docs). - pub gather: Option, - /// The sample follows Vulkan's Y′CbCr model (`YCbCrInPlacePolicy::Model`, the module docs' - /// **The model**) where its sampler addresses no border: a constexpr sampler's modes decide - /// now, a runtime sampler's word as the function runs. A gather and a sample whose offset a - /// parent's size places never do. - pub model: bool, - /// The lowered type of the result (`{T, i8}`, its status word 0). - pub result: DemoteTy, -} - -/// The census words of a slot's constants: the push field's words and the conversion's selects. -const PREPARE_WORDS: u32 = 192; -/// The census words of one tap: five fetches, the chroma filter, and the conversion. -const TAP_WORDS: u32 = 224; -/// The census words of a runtime sampler's mapped word. -const WORD_WORDS: u32 = 96; -/// The census words of the model's constants: the push field's words, the conversion's factors, -/// and the coordinate in texels. -const MODEL_PREPARE_WORDS: u32 = 192; -/// The census words of the model's linear sample: four luma fetches and their blend, four chroma -/// fetches and theirs, and the conversion. -const MODEL_LINEAR_WORDS: u32 = 320; - -impl Sample { - /// The census name of the sample's form. - pub(crate) fn name(&self) -> &'static str { - if self.gather.is_some() { - return "sampler.ycbcr_in_place.gather"; - } - if self.model { - return match self.state { - State::Constant { .. } => "sampler.ycbcr_in_place.model", - State::Slot { .. } => "sampler.ycbcr_in_place.model.runtime", - }; - } - match self.state { - State::Constant { linear: true, .. } => "sampler.ycbcr_in_place.linear", - State::Constant { linear: false, .. } => "sampler.ycbcr_in_place.nearest", - State::Slot { .. } => "sampler.ycbcr_in_place.runtime", - } - } - - /// The estimated words of the sample: the slot's constants, a linear filter's four taps and - /// its footprint (a runtime sampler's nearest tap and its own footprint besides, the word and - /// its branch; a gather's four taps and footprint alone, a runtime sampler's word besides), and - /// Metal's offset rule on each lane of an offset; the model's constants and its eight fetches - /// in place of Metal's linear sample, and beside it under a runtime sampler. - pub(crate) fn words(&self) -> u32 { - let position = 2 * super::position::POSITION_WORDS; - let linear = super::linear::PLANE_WORDS + 4 * TAP_WORDS + position; - let nearest = super::extended::NEAREST_WORDS + TAP_WORDS + position; - let rule = match self.offset_base { - true => super::position::OFFSET_RULE_WORDS + super::position::PARENT_RULE_WORDS, - false => super::position::OFFSET_RULE_WORDS, - }; - let offset = self.offset.as_deref().map_or(0, |o| o.len() as u32) * rule; - let filters = match (&self.state, self.gather) { - (State::Constant { .. }, Some(_)) => linear, - (State::Slot { .. }, Some(_)) => linear + WORD_WORDS, - (State::Constant { linear: true, .. }, None) => linear, - (State::Constant { linear: false, .. }, None) => nearest, - (State::Slot { .. }, None) => { - linear + nearest + WORD_WORDS + super::extended::BRANCH_WORDS - } - }; - let model = MODEL_PREPARE_WORDS + MODEL_LINEAR_WORDS + offset; - match (self.model, &self.state) { - (false, _) => {} - (true, State::Constant { .. }) => return model + 16, - // The word's test and branch, and Metal's sample it takes besides. - (true, State::Slot { .. }) => { - let test = WORD_WORDS + super::extended::BRANCH_WORDS; - return model + test + PREPARE_WORDS + filters + offset + 16; - } - } - PREPARE_WORDS + filters + offset + 16 - } -} - -/// The constants of an in-place texture's taps, read from the slot's push field -/// (`bind::YCbCrInPlace::words`). -#[derive(Clone, Copy)] -pub(crate) struct Planes { - /// The luma plane's first element and the elements between its rows (`u32`s). - luma: [SValue; 2], - /// The chroma plane's first element and the elements between its rows (`u32`s). - chroma: [SValue; 2], - /// The chroma plane's last column and row (`u32`s): `⌈w / 2⌉ - 1`, `⌈h / 2⌉ - 1`. - last: [SValue; 2], - /// The shift that takes an element's lane to its code: 6 of 10-bit codes, 0 of 8-bit ones. - code_shift: SValue, - /// The shift that counts a code as a 10-bit one: 0 of 10-bit codes, 2 of 8-bit ones. - up: SValue, - /// The codes are full range (a `bool`). - full: SValue, - /// The largest code `m = 2^b - 1`, and `⌊m / 2⌋`, of full range's luma (`u32`s). - max: [SValue; 2], - /// Red's, green's and blue's `(kb, kr)` (`i32`s) of the surface's range and matrix. - k: [[SValue; 2]; 3], -} - -/// The scalar and vector types a tap computes in. -struct T { - u32_: TypeId, - i32_: TypeId, - f32_: TypeId, - vec4: TypeId, - uvec2: TypeId, -} - -impl T { - fn new(fb: &mut FunctionBuilder<'_>) -> BResult { - let m = fb.module(); - let u32_ = m.ty(SType::Int { - width: 32, - signed: false, - })?; - let i32_ = m.ty(SType::Int { - width: 32, - signed: true, - })?; - let f32_ = m.ty(SType::Float { width: 32 })?; - let vec4 = m.ty(SType::Vector { elem: f32_, len: 4 })?; - let uvec2 = m.ty(SType::Vector { elem: u32_, len: 2 })?; - Ok(T { - u32_, - i32_, - f32_, - vec4, - uvec2, - }) - } - - fn k(&self, fb: &mut FunctionBuilder<'_>, ty: TypeId, bits: u32) -> BResult { - let c = fb.module().constant(Constant::Scalar { - ty, - bits: ConstBits(u64::from(bits)), - })?; - fb.module().const_value(c) - } - - fn u(&self, fb: &mut FunctionBuilder<'_>, v: u32) -> BResult { - self.k(fb, self.u32_, v) - } - - fn i(&self, fb: &mut FunctionBuilder<'_>, v: i32) -> BResult { - self.k(fb, self.i32_, v as u32) - } - - fn f(&self, fb: &mut FunctionBuilder<'_>, v: f32) -> BResult { - self.k(fb, self.f32_, v.to_bits()) - } -} - -/// The words of slot `slot`'s push field (`bind::YCbCrInPlace::words`), each a `u32`, in the -/// open block. -struct Words { - size: [SValue; 2], - luma: [SValue; 2], - chroma: [SValue; 2], - conversion: SValue, -} - -fn words(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, slot: SlotRef) -> BResult { - use crate::bind::YCbCrInPlace as W; - let field = cx.push_field(fb, PushField::YCbCrInPlace(slot))?; - let low = fb.composite_extract(field, &[0])?; - let high = fb.composite_extract(field, &[1])?; - // Word `i` of the field: lane `i % 4` of its first `uvec4` or its second. - let mut word = |i: usize| match i < 4 { - true => fb.composite_extract(low, &[i as u32]), - false => fb.composite_extract(high, &[(i - 4) as u32]), - }; - Ok(Words { - size: [word(W::WIDTH)?, word(W::HEIGHT)?], - luma: [word(W::LUMA_AT)?, word(W::LUMA_ROW)?], - chroma: [word(W::CHROMA_AT)?, word(W::CHROMA_ROW)?], - conversion: word(W::CONVERSION)?, - }) -} - -/// The width (`axis` 0) or the height (`axis` 1) of slot `slot`'s in-place texture, a `u32` -/// from its push field, in the open block: a size query's answer at its one level. -pub(crate) fn extent( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - slot: SlotRef, - axis: u8, -) -> BResult { - let [width, height] = words(cx, fb, slot)?.size; - match axis { - 0 => Ok(width), - 1 => Ok(height), - _ => Err(cx.fail("an in-place texture's extent past its two axes")), - } -} - -/// The constants of slot `slot`'s taps (its push field's words), and the texture's size (a -/// `uvec2`), in the open block. -pub(crate) fn prepare( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - slot: SlotRef, -) -> BResult<(Planes, SValue)> { - use crate::bind::{YCbCrMatrix as M, YCbCrRange as R}; - let t = T::new(fb)?; - let w = words(cx, fb, slot)?; - let size = fb.composite_construct(t.uvec2, &w.size)?; - let one = t.u(fb, 1)?; - // The chroma plane's last column and row, `⌈n / 2⌉ - 1`. - let last_of = |fb: &mut FunctionBuilder<'_>, n: SValue| -> BResult { - let up = fb.binary(BinOp::IAdd, n, one)?; - let half = fb.binary(BinOp::ShiftRightLogical, up, one)?; - fb.binary(BinOp::ISub, half, one) - }; - let [width, height] = w.size; - let last = [last_of(fb, width)?, last_of(fb, height)?]; - // The conversion word: the codes' bits, full range, the matrix. - let field_at = |fb: &mut FunctionBuilder<'_>, shift: u32, mask: u32| -> BResult { - let shift = t.u(fb, shift)?; - let mask = t.u(fb, mask)?; - let v = fb.binary(BinOp::ShiftRightLogical, w.conversion, shift)?; - fb.binary(BinOp::BitwiseAnd, v, mask) - }; - let bits = field_at(fb, 0, 0xff)?; - let ten = t.u(fb, 10)?; - let ten = fb.binary(BinOp::IEqual, bits, ten)?; - let pick = |fb: &mut FunctionBuilder<'_>, [a, b]: [u32; 2]| -> BResult { - let (a, b) = (t.u(fb, a)?, t.u(fb, b)?); - fb.select(ten, a, b) - }; - let code_shift = pick(fb, [6, 0])?; - let up = pick(fb, [0, 2])?; - let max = [pick(fb, [1023, 255])?, pick(fb, [511, 127])?]; - let full = field_at(fb, 8, 1)?; - let full = fb.binary(BinOp::IEqual, full, one)?; - let matrix = field_at(fb, 9, 3)?; - let bt709 = fb.binary(BinOp::IEqual, matrix, one)?; - let two = t.u(fb, 2)?; - let bt2020 = fb.binary(BinOp::IEqual, matrix, two)?; - // A coefficient of each matrix (BT.601, BT.709, BT.2020), chosen by the matrix. - let choose = |fb: &mut FunctionBuilder<'_>, [a, b, c]: [i32; 3]| -> BResult { - let (a, b, c) = (t.i(fb, a)?, t.i(fb, b)?, t.i(fb, c)?); - let low = fb.select(bt709, b, a)?; - fb.select(bt2020, c, low) - }; - // Per channel, each matrix's `(kb, kr)` of `range`. - let by_channel = |range| { - let of = crate::bind::ycbcr_convert::coefficients; - let [[a0, a1, a2], [b0, b1, b2], [c0, c1, c2]] = - [M::Bt601, M::Bt709, M::Bt2020].map(|m| of(range, m)); - [[a0, b0, c0], [a1, b1, c1], [a2, b2, c2]] - }; - let sides: [fn((i32, i32)) -> i32; 2] = [|(kb, _)| kb, |(_, kr)| kr]; - let zero = t.i(fb, 0)?; - let mut k = [[zero; 2]; 3]; - for ((video, full_range), out) in by_channel(R::Video) - .into_iter() - .zip(by_channel(R::Full)) - .zip(k.iter_mut()) - { - for (side, coefficient) in sides.into_iter().zip(out.iter_mut()) { - let v = choose(fb, video.map(side))?; - let f = choose(fb, full_range.map(side))?; - *coefficient = fb.select(full, f, v)?; - } - } - let planes = Planes { - luma: w.luma, - chroma: w.chroma, - last, - code_shift, - up, - full, - max, - k, - }; - Ok((planes, size)) -} - -/// The element `at + row · y + x` of the planes' texel buffer `img` (`u32`s): a `uvec4` whose -/// first two lanes it holds. -fn element( - fb: &mut FunctionBuilder<'_>, - img: SValue, - [at, row]: [SValue; 2], - [x, y]: [SValue; 2], -) -> BResult { - let r = fb.binary(BinOp::IMul, row, y)?; - let e = fb.binary(BinOp::IAdd, at, r)?; - let e = fb.binary(BinOp::IAdd, e, x)?; - fb.fetch(img, e, &ImageOperands::default()) -} - -/// The texel Metal reads at `at` (a `uvec2` inside the texture) of the in-place texture whose -/// planes' texel buffer is `img` and whose constants `p` holds (module docs): a `vec4` of its -/// converted red, green and blue, each a step of `1 / 2048`, and alpha 1. Every such step is a -/// `half` exactly, so a `half` result's rounding leaves it, whatever `_half` asks. -pub(crate) fn texel( - fb: &mut FunctionBuilder<'_>, - p: &Planes, - img: SValue, - at: SValue, - _half: bool, -) -> BResult { - let t = T::new(fb)?; - let x = fb.composite_extract(at, &[0])?; - let y = fb.composite_extract(at, &[1])?; - let (zero, one) = (t.u(fb, 0)?, t.u(fb, 1)?); - // The luma code: lane `x & 1` of element `⌊x / 2⌋` of its row. - let pair_x = fb.binary(BinOp::ShiftRightLogical, x, one)?; - let v = element(fb, img, p.luma, [pair_x, y])?; - let odd_x = fb.binary(BinOp::BitwiseAnd, x, one)?; - let odd_x = fb.binary(BinOp::INotEqual, odd_x, zero)?; - let l0 = fb.composite_extract(v, &[0])?; - let l1 = fb.composite_extract(v, &[1])?; - let luma = fb.select(odd_x, l1, l0)?; - let luma = fb.binary(BinOp::ShiftRightLogical, luma, p.code_shift)?; - // On each axis, the chroma texel's own column (or row) and its neighbour: the one after it - // for an odd index, before it for an even one, clamped to the plane. - let near = |fb: &mut FunctionBuilder<'_>, c: SValue, last: SValue| -> BResult<[SValue; 2]> { - let own = fb.binary(BinOp::ShiftRightLogical, c, one)?; - let odd = fb.binary(BinOp::BitwiseAnd, c, one)?; - let odd = fb.binary(BinOp::INotEqual, odd, zero)?; - let after = fb.binary(BinOp::IAdd, own, one)?; - let after = fb.glsl(GlslOp::UMin, &[after, last])?; - let before = fb.glsl(GlslOp::UMax, &[own, one])?; - let before = fb.binary(BinOp::ISub, before, one)?; - Ok([own, fb.select(odd, after, before)?]) - }; - let [cx0, cx1] = near(fb, x, p.last[0])?; - let [cy0, cy1] = near(fb, y, p.last[1])?; - let mut sums = [zero; 2]; - for (weight, site) in [ - (9, [cx0, cy0]), - (3, [cx1, cy0]), - (3, [cx0, cy1]), - (1, [cx1, cy1]), - ] { - let v = element(fb, img, p.chroma, site)?; - let w = t.u(fb, weight)?; - for (lane, sum) in sums.iter_mut().enumerate() { - let c = fb.composite_extract(v, &[lane as u32])?; - let c = fb.binary(BinOp::ShiftRightLogical, c, p.code_shift)?; - let c = fb.binary(BinOp::IMul, c, w)?; - *sum = fb.binary(BinOp::IAdd, *sum, c)?; - } - } - // Each chroma code `(S + 8) >> 4`, counted as a 10-bit code, less 512. - let (eight, four, mid) = (t.u(fb, 8)?, t.u(fb, 4)?, t.i(fb, 512)?); - let mut chroma = [mid; 2]; - for (c, sum) in chroma.iter_mut().zip(sums) { - let s = fb.binary(BinOp::IAdd, sum, eight)?; - let code = fb.binary(BinOp::ShiftRightLogical, s, four)?; - let code = fb.binary(BinOp::ShiftLeftLogical, code, p.up)?; - let code = fb.convert(ConvOp::Bitcast, code, t.i32_)?; - *c = fb.binary(BinOp::ISub, code, mid)?; - } - // The luma term: video range `9576 ((Y << u) - 64)`, full `256 ⌊(32768 Y + ⌊m / 2⌋) / m⌋`. - let video = fb.binary(BinOp::ShiftLeftLogical, luma, p.up)?; - let video = fb.convert(ConvOp::Bitcast, video, t.i32_)?; - let black = t.i(fb, 64)?; - let video = fb.binary(BinOp::ISub, video, black)?; - let scale = t.i(fb, 9576)?; - let video = fb.binary(BinOp::IMul, video, scale)?; - let wide = t.u(fb, 32768)?; - let full = fb.binary(BinOp::IMul, luma, wide)?; - let full = fb.binary(BinOp::IAdd, full, p.max[1])?; - let full = fb.binary(BinOp::UDiv, full, p.max[0])?; - let full = fb.convert(ConvOp::Bitcast, full, t.i32_)?; - let step = t.i(fb, 256)?; - let full = fb.binary(BinOp::IMul, full, step)?; - let l = fb.select(p.full, full, video)?; - // Each channel `clamp((L + kb Cb' + kr Cr' + 2048) >> 12, 0, 2048) / 2048`. - let (round, twelve, low) = (t.i(fb, 2048)?, t.u(fb, 12)?, t.i(fb, 0)?); - let grid = t.f(fb, 1.0 / 2048.0)?; - let mut lanes = Vec::with_capacity(4); - for [kb, kr] in p.k { - let b = fb.binary(BinOp::IMul, kb, chroma[0])?; - let r = fb.binary(BinOp::IMul, kr, chroma[1])?; - let sum = fb.binary(BinOp::IAdd, l, b)?; - let sum = fb.binary(BinOp::IAdd, sum, r)?; - let sum = fb.binary(BinOp::IAdd, sum, round)?; - let v = fb.binary(BinOp::ShiftRightArithmetic, sum, twelve)?; - let v = fb.glsl(GlslOp::SClamp, &[v, low, round])?; - let v = fb.convert(ConvOp::ConvertSToF, v, t.f32_)?; - lanes.push(fb.binary(BinOp::FMul, v, grid)?); - } - lanes.push(t.f(fb, 1.0)?); - fb.composite_construct(t.vec4, &lanes) -} - -/// The class bits a sample's exact routine and border texels read: the converted 4:2:0 formats' -/// (`metal::texel_format::texel_format`), one for both widths (`one_class_for_both_widths`). -pub(crate) fn class() -> u32 { - crate::metal::texel_format::texel_format(PixelFormat::YCBCR84202P).0 -} - -/// Runtime sampler word `word` with each plane axis's mode as a 4:2:0 texture samples it: -/// mirror-clamp-to-edge (1), repeat (2) and mirrored repeat (3) as clamp-to-edge (0). -fn mapped_word(fb: &mut FunctionBuilder<'_>, t: &T, word: SValue) -> BResult { - use crate::metal::sampler::SamplerWord; - let mut w = word; - let (one, three, seven) = (t.u(fb, 1)?, t.u(fb, 3)?, t.u(fb, 7)?); - for shift in SamplerWord::ADDRESS_SHIFT.into_iter().take(2) { - let s = t.u(fb, shift)?; - let mode = fb.binary(BinOp::ShiftRightLogical, w, s)?; - let mode = fb.binary(BinOp::BitwiseAnd, mode, seven)?; - let above = fb.binary(BinOp::UGreaterThanEqual, mode, one)?; - let within = fb.binary(BinOp::ULessThanEqual, mode, three)?; - let wraps = fb.binary(BinOp::LogicalAnd, above, within)?; - let keep = t.u(fb, !(7 << shift))?; - let edge = fb.binary(BinOp::BitwiseAnd, w, keep)?; - w = fb.select(wraps, edge, w)?; - } - Ok(w) -} - -/// The texel of in-place sample `s` through the device's own sampler Y′CbCr conversion -/// (`LoweringInputs::ycbcr_planes_sampled`, the module docs' **The device's sampler**), in the open -/// block: the slot's combined image `sampled` sampled at level 0, a linear sample at Metal's -/// coordinate (its texel offset moved in texels), a nearest one at the centre of the luma texel -/// Metal reads (clamped to the edge, as a 4:2:0 texture addresses every mode but a border one). -fn device_sample( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - s: &Sample, - slot: SlotRef, - (coord, sampled): (SValue, SValue), -) -> BResult { - let t = T::new(fb)?; - let w = words(cx, fb, slot)?; - let vec2 = fb.module().ty(SType::Vector { - elem: t.f32_, - len: 2, - })?; - let size = fb.composite_construct(t.uvec2, &w.size)?; - let size = fb.convert(ConvOp::ConvertUToF, size, vec2)?; - // Whether the sampler reads pixel coordinates and filters linearly: a constexpr sampler's - // state, or a runtime sampler's word. - let (pixel, linear) = match &s.state { - State::Constant { linear, pixel, .. } => (Known::Fixed(*pixel), Known::Fixed(*linear)), - State::Slot { sampler } => { - let word = super::emit::sampler_word(cx, fb, Pixel::Spec(*sampler))?; - let bit = t.u(fb, crate::metal::sampler::SamplerWord::PIXEL_COORDINATES)?; - let set = fb.binary(BinOp::BitwiseAnd, word, bit)?; - let pixel = fb.binary(BinOp::IEqual, set, bit)?; - let tys = Tys::new(fb)?; - let linear = super::extended::word_linear(fb, &tys, word)?; - (Known::Run(pixel), Known::Run(linear)) - } - }; - // The coordinate in texels, and normalized. - let texels = fb.binary(BinOp::FMul, coord, size)?; - let (mut texels, mut normal) = match pixel { - Known::Fixed(true) => (coord, fb.binary(BinOp::FDiv, coord, size)?), - Known::Fixed(false) => (texels, coord), - Known::Run(pixel) => { - let normal = fb.binary(BinOp::FDiv, coord, size)?; - let b2 = bvec2(fb)?; - let pixel2 = fb.composite_construct(b2, &[pixel, pixel])?; - ( - fb.select(pixel2, coord, texels)?, - fb.select(pixel2, normal, coord)?, - ) - } - }; - if let Some(offset) = s.offset.as_deref() { - let lanes: Vec = offset - .iter() - .map(|&k| t.f(fb, k as f32)) - .collect::>()?; - let k = fb.composite_construct(vec2, &lanes)?; - texels = fb.binary(BinOp::FAdd, texels, k)?; - let moved = fb.binary(BinOp::FDiv, k, size)?; - normal = fb.binary(BinOp::FAdd, normal, moved)?; - } - // A nearest sample's luma texel, clamped to the edge, at its centre. - let nearest = |fb: &mut FunctionBuilder<'_>| -> BResult { - let floor = fb.glsl(GlslOp::Floor, &[texels])?; - let zero = t.f(fb, 0.0)?; - let zero = fb.composite_construct(vec2, &[zero, zero])?; - let one = t.f(fb, 1.0)?; - let one = fb.composite_construct(vec2, &[one, one])?; - let last = fb.binary(BinOp::FSub, size, one)?; - let texel = fb.glsl(GlslOp::FClamp, &[floor, zero, last])?; - let half = t.f(fb, 0.5)?; - let half = fb.composite_construct(vec2, &[half, half])?; - let centre = fb.binary(BinOp::FAdd, texel, half)?; - fb.binary(BinOp::FDiv, centre, size) - }; - let at = match linear { - Known::Fixed(true) => normal, - Known::Fixed(false) => nearest(fb)?, - Known::Run(linear) => { - let centre = nearest(fb)?; - let b2 = bvec2(fb)?; - let linear2 = fb.composite_construct(b2, &[linear, linear])?; - fb.select(linear2, normal, centre)? - } - }; - let lod = t.f(fb, 0.0)?; - let ops = ImageOperands { - lod: Some(lod), - ..ImageOperands::default() - }; - let x = fb.sample(sampled, at, None, false, &ops)?; - // A `half` result is held widened, rounded to a `half` as every sampled texel's is - // (`texture::held_texel`). - match s.half { - false => Ok(x), - true => { - let half = crate::lower::arith::Form { - held: crate::lower::arith::Held::Float(crate::lower::arith::FloatFmt::Half), - lanes: 4, - }; - crate::lower::arith::narrow::round_texel(fb, half, x) - } - } -} - -/// A value fixed as the module is made, or known only as it runs. -#[derive(Clone, Copy)] -enum Known { - Fixed(bool), - Run(SValue), -} - -/// The `bvec2` type. -fn bvec2(fb: &mut FunctionBuilder<'_>) -> BResult { - let b = fb.module().ty(SType::Bool)?; - fb.module().ty(SType::Vector { elem: b, len: 2 }) -} - -/// The texel of in-place sample `s` in the open block, with its status word 0 (module docs). -pub(crate) fn emit( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - s: &Sample, -) -> BResult { - let coord = cx.operand(fb, s.coord)?; - let (decl, img) = crate::lower::texture::slot_image(cx, fb, s.texture)?; - let Some(slot) = cx - .plan - .families - .texture - .slots - .get(&s.texture) - .map(|p| p.slot) - else { - return Err(cx.fail(format!("texture slot {} is not planned", s.texture))); - }; - if decl.planes_sampler.is_some() { - // The device's conversion takes no gather (`device_takes` keeps such a slot off it). - if s.gather.is_some() { - return Err(cx.fail("an in-place gather under the device's sampler")); - } - let x = device_sample(cx, fb, s, slot, (coord, img))?; - return crate::lower::texture::with_word(cx, fb, &s.result, x, None); - } - let texel = decl.texel; - let x = match (s.model, &s.state) { - (false, _) => exact(cx, fb, s, slot, (coord, img), texel)?, - (true, State::Constant { pixel, .. }) => { - model(cx, fb, s, slot, (coord, img), Known::Fixed(*pixel))? - } - // A runtime sampler's word: the model's sample where it filters linearly and addresses no - // border on either plane axis, else Metal's. - (true, State::Slot { sampler }) => { - let t = T::new(fb)?; - let word = super::emit::sampler_word(cx, fb, Pixel::Spec(*sampler))?; - let tys = Tys::new(fb)?; - let linear = super::extended::word_linear(fb, &tys, word)?; - let edges = edges(fb, &t, word)?; - let takes = fb.binary(BinOp::LogicalAnd, linear, edges)?; - let pixel = word_pixel(fb, &t, word)?; - let model_arm: ArmFn<'_, EmitCx<'_>> = Box::new(move |fb, cx| { - let x = model(cx, fb, s, slot, (coord, img), Known::Run(pixel))?; - Ok(ArmEnd::FallThrough(vec![x])) - }); - let exact_arm: ArmFn<'_, EmitCx<'_>> = Box::new(move |fb, cx| { - let x = exact(cx, fb, s, slot, (coord, img), texel)?; - Ok(ArmEnd::FallThrough(vec![x])) - }); - let Merged(merged) = fb.if_(cx, takes, model_arm, Some(exact_arm))?; - match merged[..] { - [x] => x, - _ => return Err(cx.fail("an in-place sample's model branch without its texel")), - } - } - }; - crate::lower::texture::with_word(cx, fb, &s.result, x, None) -} - -/// Metal's texel of in-place sample `s` (`YCbCrInPlacePolicy::Exact`, and a sample the model -/// does not take), in the open block: each tap Metal's texel of the codes, and a linear sample -/// Metal's exact sum of the four taps (module docs). Its status word is the caller's. -fn exact( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - s: &Sample, - slot: SlotRef, - (coord, img): (SValue, SValue), - texel: crate::lower::texture::TexelClass, -) -> BResult { - let (planes, size) = prepare(cx, fb, slot)?; - let t = Tys::new(fb)?; - let tt = T::new(fb)?; - let parent = match s.offset_base { - true => match cx - .decl - .families - .texture - .offset_base - .get(&s.texture) - .copied() - { - Some(base) => Some(base), - None => { - return Err(cx.fail(format!( - "texture slot {} has no OffsetBaseAxes specialization", - s.texture - ))) - } - }, - false => None, - }; - let flags = tt.u(fb, class())?; - let tex = Texture { - img, - image: CombinedImage { - plane: 2, - arrayed: false, - texel, - }, - decode: Decode::InPlace(planes), - flags, - swizzle: None, - parent, - size: Some(size), - }; - let at = super::extended::At { - coord, - layer: None, - offset: s.offset.as_deref(), - passed: None, - level: None, - half: s.half, - }; - if let Some(component) = s.gather { - let addressing = match &s.state { - State::Constant { - address, - border, - pixel, - .. - } => Addressing::Modes { - address, - border: *border, - pixel: *pixel, - }, - State::Slot { sampler } => { - let word = super::emit::sampler_word(cx, fb, Pixel::Spec(*sampler))?; - let word = mapped_word(fb, &tt, word)?; - Addressing::Word { word, axes: 2 } - } - }; - return super::extended::gathered(cx, fb, &t, &at, &tex, addressing, component); - } - let x = match &s.state { - State::Constant { .. } => super::extended::filters(cx, fb, &t, &at, &tex, &s.state)?, - State::Slot { sampler } => { - let word = super::emit::sampler_word(cx, fb, Pixel::Spec(*sampler))?; - let word = mapped_word(fb, &tt, word)?; - let addressing = Addressing::Word { word, axes: 2 }; - let linear = super::extended::word_linear(fb, &t, word)?; - let (t, tex, at) = (&t, &tex, &at); - let filtered: ArmFn<'_, EmitCx<'_>> = Box::new(move |fb, cx| { - let x = super::extended::filtered(cx, fb, t, at, tex, addressing)?; - Ok(ArmEnd::FallThrough(vec![x])) - }); - let nearest: ArmFn<'_, EmitCx<'_>> = Box::new(move |fb, cx| { - let x = super::extended::nearest(cx, fb, t, at, tex, addressing)?; - Ok(ArmEnd::FallThrough(vec![x])) - }); - let Merged(merged) = fb.if_(cx, linear, filtered, Some(nearest))?; - match merged[..] { - [x] => x, - _ => return Err(cx.fail("an in-place sample's branch without its texel")), - } - } - }; - Ok(x) -} - -/// Whether runtime sampler word `word` addresses neither plane axis by a border (a `bool`): -/// clamp-to-zero (4) and clamp-to-border (5) are the modes from 4 on. -fn edges(fb: &mut FunctionBuilder<'_>, t: &T, word: SValue) -> BResult { - use crate::metal::sampler::SamplerWord; - let (four, seven) = (t.u(fb, 4)?, t.u(fb, 7)?); - let [s, t_, _] = SamplerWord::ADDRESS_SHIFT; - let mut edge = |shift: u32| -> BResult { - let shift = t.u(fb, shift)?; - let mode = fb.binary(BinOp::ShiftRightLogical, word, shift)?; - let mode = fb.binary(BinOp::BitwiseAnd, mode, seven)?; - fb.binary(BinOp::ULessThan, mode, four) - }; - let (s, t_) = (edge(s)?, edge(t_)?); - fb.binary(BinOp::LogicalAnd, s, t_) -} - -/// Whether runtime sampler word `word` reads pixel coordinates (a `bool`). -fn word_pixel(fb: &mut FunctionBuilder<'_>, t: &T, word: SValue) -> BResult { - let bit = t.u(fb, crate::metal::sampler::SamplerWord::PIXEL_COORDINATES)?; - let set = fb.binary(BinOp::BitwiseAnd, word, bit)?; - fb.binary(BinOp::IEqual, set, bit) -} - -/// The model's linear sample of in-place sample `s` (the module docs' **The model**), whose -/// sampler reads pixel coordinates where `pixel` holds, in the open block: a `vec4`, a `half` -/// result rounded as every sampled texel's is. Its status word is the caller's. -fn model( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - s: &Sample, - slot: SlotRef, - (coord, img): (SValue, SValue), - pixel: Known, -) -> BResult { - let t = T::new(fb)?; - let w = words(cx, fb, slot)?; - let m = fb.module(); - let vec2 = m.ty(SType::Vector { - elem: t.f32_, - len: 2, - })?; - let ivec2 = m.ty(SType::Vector { - elem: t.i32_, - len: 2, - })?; - let vec3 = m.ty(SType::Vector { - elem: t.f32_, - len: 3, - })?; - let size = fb.composite_construct(t.uvec2, &w.size)?; - let size_f = fb.convert(ConvOp::ConvertUToF, size, vec2)?; - // The coordinate in luma texels, its texel offset placed. - let scaled = fb.binary(BinOp::FMul, coord, size_f)?; - let mut texels = match pixel { - Known::Fixed(true) => coord, - Known::Fixed(false) => scaled, - Known::Run(pixel) => { - let b2 = bvec2(fb)?; - let pixel2 = fb.composite_construct(b2, &[pixel, pixel])?; - fb.select(pixel2, coord, scaled)? - } - }; - if let Some(offset) = s.offset.as_deref() { - let lanes: Vec = offset - .iter() - .map(|&k| t.f(fb, k as f32)) - .collect::>()?; - let k = fb.composite_construct(vec2, &lanes)?; - texels = fb.binary(BinOp::FAdd, texels, k)?; - } - let splat2 = |fb: &mut FunctionBuilder<'_>, v: SValue, ty: TypeId| -> BResult { - fb.composite_construct(ty, &[v, v]) - }; - let (half, one_i, zero_i) = (t.f(fb, 0.5)?, t.i(fb, 1)?, t.i(fb, 0)?); - let half2 = splat2(fb, half, vec2)?; - let one2 = splat2(fb, one_i, ivec2)?; - let zero2 = splat2(fb, zero_i, ivec2)?; - // The four texels around `at` (a `vec2` in a plane's texels) clamped into `[0, last]`, as - // `uvec2`s (x0, y0) and (x1, y1), and the weights of the second of each axis. - let footprint = |fb: &mut FunctionBuilder<'_>, - at: SValue, - last: SValue| - -> BResult<([SValue; 2], SValue)> { - let p = fb.binary(BinOp::FSub, at, half2)?; - let floor = fb.glsl(GlslOp::Floor, &[p])?; - let weight = fb.binary(BinOp::FSub, p, floor)?; - let first = fb.convert(ConvOp::ConvertFToS, floor, ivec2)?; - let second = fb.binary(BinOp::IAdd, first, one2)?; - let first = fb.glsl(GlslOp::SClamp, &[first, zero2, last])?; - let second = fb.glsl(GlslOp::SClamp, &[second, zero2, last])?; - let first = fb.convert(ConvOp::Bitcast, first, t.uvec2)?; - let second = fb.convert(ConvOp::Bitcast, second, t.uvec2)?; - Ok(([first, second], weight)) - }; - // The bilinear blend of the four values `[v00, v10, v01, v11]` by the weights `k` (a `vec2`): - // floats, or `vec2`s of a pair where `pair`, each lane weighed alike. - let blend = - |fb: &mut FunctionBuilder<'_>, [v00, v10, v01, v11]: [SValue; 4], k: SValue, pair: bool| { - let mut kx = fb.composite_extract(k, &[0])?; - let mut ky = fb.composite_extract(k, &[1])?; - if pair { - kx = fb.composite_construct(vec2, &[kx, kx])?; - ky = fb.composite_construct(vec2, &[ky, ky])?; - } - let low = fb.glsl(GlslOp::FMix, &[v00, v10, kx])?; - let high = fb.glsl(GlslOp::FMix, &[v01, v11, kx])?; - fb.glsl(GlslOp::FMix, &[low, high, ky]) - }; - let corners = - |fb: &mut FunctionBuilder<'_>, [a, b]: [SValue; 2]| -> BResult<[[SValue; 2]; 4]> { - let (x0, y0) = ( - fb.composite_extract(a, &[0])?, - fb.composite_extract(a, &[1])?, - ); - let (x1, y1) = ( - fb.composite_extract(b, &[0])?, - fb.composite_extract(b, &[1])?, - ); - Ok([[x0, y0], [x1, y0], [x0, y1], [x1, y1]]) - }; - let conversion = Conversion::of(fb, &t, w.conversion)?; - let (zero, one) = (t.u(fb, 0)?, t.u(fb, 1)?); - // Luma: its four texels, each lane `x & 1` of element `⌊x / 2⌋` of its row. - let ones = splat2(fb, one, t.uvec2)?; - let last = fb.binary(BinOp::ISub, size, ones)?; - let last = fb.convert(ConvOp::Bitcast, last, ivec2)?; - let (luma_at, luma_k) = footprint(fb, texels, last)?; - let mut luma = [zero; 4]; - for (out, [x, y]) in luma.iter_mut().zip(corners(fb, luma_at)?) { - let pair = fb.binary(BinOp::ShiftRightLogical, x, one)?; - let v = element(fb, img, w.luma, [pair, y])?; - let odd = fb.binary(BinOp::BitwiseAnd, x, one)?; - let odd = fb.binary(BinOp::INotEqual, odd, zero)?; - let l0 = fb.composite_extract(v, &[0])?; - let l1 = fb.composite_extract(v, &[1])?; - let code = fb.select(odd, l1, l0)?; - let code = fb.binary(BinOp::ShiftRightLogical, code, conversion.code_shift)?; - *out = fb.convert(ConvOp::ConvertUToF, code, t.f32_)?; - } - let y = blend(fb, luma, luma_k, false)?; - // Chroma: its plane's four texels around the same point, sited at their luma pairs' - // midpoints, each pair one element. - let chroma_at = fb.binary(BinOp::FMul, texels, half2)?; - let up = fb.binary(BinOp::IAdd, size, ones)?; - let halves = fb.binary(BinOp::ShiftRightLogical, up, ones)?; - let last = fb.binary(BinOp::ISub, halves, ones)?; - let last = fb.convert(ConvOp::Bitcast, last, ivec2)?; - let (chroma_at, chroma_k) = footprint(fb, chroma_at, last)?; - let mut pairs = [zero; 4]; - for (out, site) in pairs.iter_mut().zip(corners(fb, chroma_at)?) { - let v = element(fb, img, w.chroma, site)?; - let v = fb.vector_shuffle(v, v, &[0, 1])?; - let shift = splat2(fb, conversion.code_shift, t.uvec2)?; - let v = fb.binary(BinOp::ShiftRightLogical, v, shift)?; - *out = fb.convert(ConvOp::ConvertUToF, v, vec2)?; - } - let c = blend(fb, pairs, chroma_k, true)?; - let cb = fb.composite_extract(c, &[0])?; - let cr = fb.composite_extract(c, &[1])?; - // Each channel `clamp(a Y + kb Cb + kr Cr + d, 0, 1)` in the codes counted as 10-bit ones. - let y = fb.binary(BinOp::FMul, y, conversion.scale)?; - let cb = fb.binary(BinOp::FMul, cb, conversion.scale)?; - let cr = fb.binary(BinOp::FMul, cr, conversion.scale)?; - let ys = fb.composite_construct(vec3, &[y, y, y])?; - let cbs = fb.composite_construct(vec3, &[cb, cb, cb])?; - let crs = fb.composite_construct(vec3, &[cr, cr, cr])?; - let rgb = fb.binary(BinOp::FMul, ys, conversion.luma)?; - let rgb = fb.glsl(GlslOp::Fma, &[cbs, conversion.kb, rgb])?; - let rgb = fb.glsl(GlslOp::Fma, &[crs, conversion.kr, rgb])?; - let rgb = fb.binary(BinOp::FAdd, rgb, conversion.offset)?; - let (low, high) = (t.f(fb, 0.0)?, t.f(fb, 1.0)?); - let lows = fb.composite_construct(vec3, &[low, low, low])?; - let highs = fb.composite_construct(vec3, &[high, high, high])?; - let rgb = fb.glsl(GlslOp::FClamp, &[rgb, lows, highs])?; - let x = fb.composite_construct(t.vec4, &[rgb, high])?; - match s.half { - false => Ok(x), - true => { - let half = crate::lower::arith::Form { - held: crate::lower::arith::Held::Float(crate::lower::arith::FloatFmt::Half), - lanes: 4, - }; - crate::lower::arith::narrow::round_texel(fb, half, x) - } - } -} - -/// The model's conversion of a surface's codes (the module docs' **The model**), chosen as the -/// function runs by the push field's conversion word: Metal's coefficients of the range and the -/// matrix (`bind::ycbcr_convert::coefficients`), in floats. -struct Conversion { - /// The shift that takes an element's lane to its code: 6 of 10-bit codes, 0 of 8-bit ones. - code_shift: SValue, - /// The factor that counts a code as a 10-bit one: 1 of 10-bit codes, 4 of 8-bit ones. - scale: SValue, - /// Each channel's factor of the luma code (a `vec3`). - luma: SValue, - /// Each channel's factors of the Cb and Cr codes (`vec3`s). - kb: SValue, - kr: SValue, - /// Each channel's constant term (a `vec3`). - offset: SValue, -} - -impl Conversion { - fn of(fb: &mut FunctionBuilder<'_>, t: &T, word: SValue) -> BResult { - use crate::bind::{YCbCrMatrix as M, YCbCrRange as R}; - let one = t.u(fb, 1)?; - let field_at = |fb: &mut FunctionBuilder<'_>, shift: u32, mask: u32| -> BResult { - let shift = t.u(fb, shift)?; - let mask = t.u(fb, mask)?; - let v = fb.binary(BinOp::ShiftRightLogical, word, shift)?; - fb.binary(BinOp::BitwiseAnd, v, mask) - }; - let bits = field_at(fb, 0, 0xff)?; - let ten = t.u(fb, 10)?; - let ten = fb.binary(BinOp::IEqual, bits, ten)?; - let full = field_at(fb, 8, 1)?; - let full = fb.binary(BinOp::IEqual, full, one)?; - let matrix = field_at(fb, 9, 3)?; - let bt709 = fb.binary(BinOp::IEqual, matrix, one)?; - let two = t.u(fb, 2)?; - let bt2020 = fb.binary(BinOp::IEqual, matrix, two)?; - let pick_u = |fb: &mut FunctionBuilder<'_>, a: u32, b: u32| -> BResult { - let (a, b) = (t.u(fb, a)?, t.u(fb, b)?); - fb.select(ten, a, b) - }; - let code_shift = pick_u(fb, 6, 0)?; - let (one_f, four_f) = (t.f(fb, 1.0)?, t.f(fb, 4.0)?); - let scale = fb.select(ten, one_f, four_f)?; - // Metal's fixed point: a channel is `(L + kb Cb' + kr Cr') / 2^23` of the 10-bit codes, - // with `Cb' = Cb - 512`, video range's `L = 9576 (Y - 64)` and full range's - // `L = 2^23 Y / m` (`m` the largest code counted as a 10-bit one: 1023, or 4 · 255). - const GRID: f32 = 1.0 / 8_388_608.0; - let video_luma = t.f(fb, 9576.0 * GRID)?; - let full_ten = t.f(fb, 1.0 / 1023.0)?; - let full_eight = t.f(fb, 1.0 / 1020.0)?; - let full_luma = fb.select(ten, full_ten, full_eight)?; - let luma = fb.select(full, full_luma, video_luma)?; - let video_black = t.f(fb, -9576.0 * 64.0 * GRID)?; - let zero_f = t.f(fb, 0.0)?; - let black = fb.select(full, zero_f, video_black)?; - // A coefficient of each matrix (BT.601, BT.709, BT.2020), chosen by the matrix and the - // range. - let choose = |fb: &mut FunctionBuilder<'_>, video: [f32; 3], full_range: [f32; 3]| { - let mut sides = [zero_f; 2]; - for (side, k) in sides.iter_mut().zip([video, full_range]) { - let [a, b, c] = [t.f(fb, k[0])?, t.f(fb, k[1])?, t.f(fb, k[2])?]; - let low = fb.select(bt709, b, a)?; - *side = fb.select(bt2020, c, low)?; - } - fb.select(full, sides[1], sides[0]) - }; - let of = |range| { - [M::Bt601, M::Bt709, M::Bt2020] - .map(|m| crate::bind::ycbcr_convert::coefficients(range, m)) - }; - let (video, full_range) = (of(R::Video), of(R::Full)); - let vec3 = fb.module().ty(SType::Vector { - elem: t.f32_, - len: 3, - })?; - let (mut kb, mut kr, mut offset) = (Vec::new(), Vec::new(), Vec::new()); - let mid = t.f(fb, -512.0)?; - // Each channel's coefficients under the three matrices, of each range. - let channels = |[bt601, bt709, bt2020]: [[(i32, i32); 3]; 3]| { - bt601 - .into_iter() - .zip(bt709) - .zip(bt2020) - .map(|((a, b), c)| [a, b, c]) - }; - for (video, full_range) in channels(video).zip(channels(full_range)) { - let side = |k: [(i32, i32); 3], kr: bool| { - k.map(|(b, r)| (if kr { r } else { b }) as f32 * GRID) - }; - let b = choose(fb, side(video, false), side(full_range, false))?; - let r = choose(fb, side(video, true), side(full_range, true))?; - // The constant term: the black level's, and `-512 (kb + kr)` of the chroma's middle. - let sum = fb.binary(BinOp::FAdd, b, r)?; - let d = fb.glsl(GlslOp::Fma, &[sum, mid, black])?; - kb.push(b); - kr.push(r); - offset.push(d); - } - let lumas = fb.composite_construct(vec3, &[luma, luma, luma])?; - Ok(Conversion { - code_shift, - scale, - luma: lumas, - kb: fb.composite_construct(vec3, &kb)?, - kr: fb.composite_construct(vec3, &kr)?, - offset: fb.composite_construct(vec3, &offset)?, - }) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - /// Both widths' converted 4:2:0 formats filter on one class, with Metal's exact sum and its - /// border texels, so one variant serves both. - #[test] - fn one_class_for_both_widths() { - use crate::metal::bicubic::BicubicTexels; - let ten = crate::metal::texel_format::texel_format(PixelFormat::YCBCR104202P).0; - assert_eq!(class(), ten); - assert_ne!(class() & BicubicTexels::EXACT, 0); - assert_ne!(class() >> BicubicTexels::BORDER & 0xfff, 0); - } -} diff --git a/crates/metal2vulkan/src/lower/sampler/linear.rs b/crates/metal2vulkan/src/lower/sampler/linear.rs index 182302766..711f9553c 100644 --- a/crates/metal2vulkan/src/lower/sampler/linear.rs +++ b/crates/metal2vulkan/src/lower/sampler/linear.rs @@ -1,5 +1,5 @@ //! What the device-sampled filters share with the emulated ones the device has no form for -//! (`extended`, `heap_raw`, `in_place`, `bicubic`): the census words of a filter's footprint and +//! (`extended`, `heap_raw`, `bicubic`): the census words of a filter's footprint and //! of a runtime sampler's word, the rule of an axis whose two taps read one texel ([`merged`]), and //! the samplers that read one texel of one level ([`unfiltered`]). //! @@ -11,8 +11,7 @@ //! (`PackedTexels::YCbCr2048`), `8192` (`PackedTexels::YCbCr8192`), or `8192` signed within //! `[-2, 2]` (`PackedTexels::YCbCrExtended8192`). Metal's 2D linear sample sums the steps on the //! grid, each term truncated; the device's sampler filters the view's texels its own way -//! (`PrecisionNote::DeviceSampling`). A device whose memory is the host's reads a slot's planes in -//! place, Metal's filter exactly (`in_place`). +//! (`PrecisionNote::DeviceSampling`). use crate::air::abi::{Filter, MipFilter, SamplerState}; use crate::lower::select::{NoteOn, NoteTest}; diff --git a/crates/metal2vulkan/src/lower/sampler/mod.rs b/crates/metal2vulkan/src/lower/sampler/mod.rs index 2e88d5592..c72dcade8 100644 --- a/crates/metal2vulkan/src/lower/sampler/mod.rs +++ b/crates/metal2vulkan/src/lower/sampler/mod.rs @@ -166,7 +166,6 @@ pub mod extended; pub mod face; pub mod footprint; pub mod heap_raw; -pub mod in_place; pub mod level; pub mod linear; pub mod position; @@ -1312,8 +1311,6 @@ pub struct Declared { pub bicubic_plane: Option, /// The 1D bicubic samples' routine, when the module has one. pub bicubic_line: Option, - /// The in-place two-plane YCbCr linear samples' routines, when the module has one. - pub linear_quad: Option, /// Under the identity domains, the set-1 sampler array of each use ([`IdentitySampling`]). pub identity: BTreeMap, } @@ -1364,9 +1361,6 @@ pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> { level_views: None, extended: None, x_channel: false, - in_place: false, - planes_sampler: None, - rows: false, parts: None, }; if crate::lower::access::identity(cx.profile) { @@ -1857,9 +1851,6 @@ pub fn declare( bicubic::routines::Routine::Line => { d.bicubic_line = Some(bicubic::routines::define_line(mb)?); } - bicubic::routines::Routine::Quad => { - d.linear_quad = Some(bicubic::routines::define_quad(mb)?); - } } } Ok(d) diff --git a/crates/metal2vulkan/src/lower/sampler/position.rs b/crates/metal2vulkan/src/lower/sampler/position.rs index c801f2db5..9b64f7e3f 100644 --- a/crates/metal2vulkan/src/lower/sampler/position.rs +++ b/crates/metal2vulkan/src/lower/sampler/position.rs @@ -1,6 +1,6 @@ //! Metal's texel-space position of a normalized coordinate, which the filters the device has no -//! form for read their footprints from (`bicubic`, `extended`, `heap_raw`, `in_place`, and the -//! residency `footprint`), and Metal's placement of a texel offset on a repeating or mirrored axis. +//! form for read their footprints from (`bicubic`, `extended`, `heap_raw`, and the residency +//! `footprint`), and Metal's placement of a texel offset on a repeating or mirrored axis. //! //! **The position** (Apple M3 Max, macOS 26.7, and Apple M4, macOS 27.0.1, byte-identical; the //! tie, gather, and bicubic probes). Per axis of size `N` and normalized coordinate `u`, Apple's diff --git a/crates/metal2vulkan/src/lower/sampler/position/tests.rs b/crates/metal2vulkan/src/lower/sampler/position/tests.rs index ac33b700f..0fb41eeca 100644 --- a/crates/metal2vulkan/src/lower/sampler/position/tests.rs +++ b/crates/metal2vulkan/src/lower/sampler/position/tests.rs @@ -665,7 +665,7 @@ fn the_offset_rule_is_metals_by_level_and_base() { /// view's own, as before. #[test] fn the_offset_rule_reads_the_parent_s_base_through_the_view_bit() { - use crate::bind::TextureFacts; + use crate::bind::state::TextureFacts; use crate::metal::{PixelFormat, TextureType}; let rule = |n: u32, base: u32| (2..=7).contains(&n) && !base.is_power_of_two(); let mut lanes = Vec::new(); diff --git a/crates/metal2vulkan/src/lower/sampler/select.rs b/crates/metal2vulkan/src/lower/sampler/select.rs index 8ca8c87f2..59ff8ae9b 100644 --- a/crates/metal2vulkan/src/lower/sampler/select.rs +++ b/crates/metal2vulkan/src/lower/sampler/select.rs @@ -1300,9 +1300,6 @@ fn select_slot( } _ => sampler, }; - if let Some(sample) = select_in_place(cx, call, index, &sampler, arm, m)? { - return Ok(TextureStrategy::InPlaceSample(Box::new(sample))); - } match crate::lower::texture::extended_range(cx, ImageRef::Slot(index))? { Some(form) => select_extended(cx, call, (index, form), sampler, m), None => select_one(cx, call, ImageRef::Slot(index), sampler, arm, m) @@ -1310,263 +1307,6 @@ fn select_slot( } } -/// Observe sampling call `call` of texture slot `index` through `sampler` for the slot's in-place -/// form (`slot::InPlaceReads`), and where the slot's variant reads a two-plane YCbCr texture's -/// planes in place (`LoweringInputs::ycbcr_in_place`) select the form's sample -/// ([`in_place_sample`]); else `None`, and the slot's other forms sample it. A call the form does -/// not read keeps the slot from it, so its variant never meets one. -fn select_in_place( - cx: &mut SelectCx<'_>, - call: Call<'_>, - index: u32, - sampler: &SamplerArg, - arm: Option, - m: &mut Meter, -) -> Result, Error> { - let variant = crate::lower::texture::ycbcr_in_place(cx, index)?; - let Some((sample, samplers)) = in_place_sample(cx, call, index, sampler, arm)? else { - crate::lower::texture::not_in_place(cx, index); - return Ok(None); - }; - let Some(s) = cx.families.texture.slots.get_mut(&index) else { - return Err(cx.invariant("an unplanned texture slot")); - }; - s.in_place.samplers |= samplers; - s.in_place.device_blocked |= !device_takes(&sample); - if !variant { - return Ok(None); - } - // The slot's planes are fetched, as a read fetches texels. - s.observe(call.t.image, Some(TexelClass::Float))?; - s.uses.read = true; - s.offset_base |= sample.offset_base; - // The device's own conversion samples a planes image's slot (`in_place`'s **The device's - // sampler**), whose answers the runtime announces where it binds one: the model is the - // texel buffer's. - let mut sample = sample; - sample.model &= !cx.inputs.ycbcr_planes_sampled.contains_key(&s.slot); - // A runtime sampler's word states the filter, the coordinates, the address modes and the - // border color. - if let super::extended::State::Slot { sampler: n } = sample.state { - let Some(r) = cx.families.sampler.slots.get_mut(&n) else { - return Err(cx.invariant("an unplanned sampler slot")); - }; - r.linear = true; - } - // A linear filter's exact sum (a gather sums nothing, and the model's linear sample blends the - // codes; a runtime sampler's word may still take Metal's). - let sums = match sample.state { - super::extended::State::Constant { linear, .. } => linear && !sample.model, - super::extended::State::Slot { .. } => true, - }; - if sample.gather.is_none() && sums { - cx.families - .sampler - .bicubic_routines - .insert(super::bicubic::routines::Routine::Quad); - } - if sample.model { - model_note(cx, &sample, m)?; - } - Ok(Some(sample)) -} - -/// The note of the model's sample `s` (`super::in_place`'s **The model**): the codes' blend, not -/// Metal's exact filter of the format, `PrecisionNote::HalfSampleFilter` for a `half` result and -/// `FloatSampleFilter` for a `float` one, under the clause that the slot binds a converted 4:2:0 -/// format (`SpecKey::BoundTexelFormat`, which a consumer reads at each draw or dispatch, -/// `StageModule::precision_notes_bound`), and through a runtime sampler slot that the word bound -/// there filters linearly and addresses no border on either plane axis -/// (`SpecKey::BoundSamplerWord`), where the sample takes the model. -fn model_note( - cx: &mut SelectCx<'_>, - s: &super::in_place::Sample, - m: &mut Meter, -) -> Result<(), Error> { - use crate::metal::texel_format::{PackedTexels, TexelFormat}; - let note = match s.half { - true => PrecisionNote::HalfSampleFilter, - false => PrecisionNote::FloatSampleFilter, - }; - let format = NoteTest::equal( - NoteOn::Bound(s.texture), - TexelFormat::PACKED_MASK, - PackedTexels::YCbCr2048.class().0, - ); - let mut clause = crate::lower::select::NoteClause::from([format]); - if let super::extended::State::Slot { sampler: n } = s.state { - let on = NoteOn::BoundSampler(n); - let filter = SamplerWord::MIN_LINEAR | SamplerWord::MAG_LINEAR; - clause.insert(NoteTest::equal(on, filter, SamplerWord::LINEAR)); - // A mode from 4 on (clamp-to-zero, clamp-to-border) addresses a border. - for shift in SamplerWord::ADDRESS_SHIFT.into_iter().take(2) { - clause.insert(NoteTest::equal(on, 4 << shift, 0)); - } - } - cx.note_when(note, vec![clause], m) -} - -/// Whether the device's own sampler Y′CbCr conversion of a planes image takes in-place sample `s` -/// (`LoweringInputs::ycbcr_planes_sampled`, `super::in_place`'s **The device's sampler**): a -/// constexpr sampler that addresses no border on either plane axis (a 4:2:0 texture samples every -/// other mode as clamp-to-edge, as that sampler does), or a runtime sampler, whose bound word the -/// binder holds to the same (`bind::plan::slots::planes_word`); and no texel offset Metal places -/// by a parent's size; and no gather, which the conversion does not take -/// (`VUID-RuntimeSpirv-OpTypeSampledImage-12206`). -fn device_takes(s: &super::in_place::Sample) -> bool { - use super::bicubic::TapAddress; - let border = match &s.state { - super::extended::State::Constant { address, .. } => { - address.iter().any(|m| matches!(m, TapAddress::Border)) - } - super::extended::State::Slot { .. } => false, - }; - !border && !s.offset_base && s.gather.is_none() -} - -/// Sampling call `call` of texture slot `index` through `sampler` as the in-place form reads it -/// (`in_place`), with the runtime sampler slots it reads (bit `n` `[[sampler(n)]]`); `None` where -/// the form does not: anything but a 2D texture's sample or gradient sample without comparison, or -/// gather of a component without comparison (which follows no filter), with a `float` or `half` -/// result, a constant texel offset or none, no `min_lod_clamp`, and no -/// status word observed, through a constexpr sampler of one filter for minification and -/// magnification (nearest or linear), no anisotropy and the weighted-average reduction, or a -/// runtime sampler slot, whose bound word the binder holds to the same -/// (`bind::plan::slots::in_place_word`); and not an arm of a switch-at-use. Metal's sample reads -/// the texture's one level whatever the mip filter, the level, the bias or the gradients, so the -/// form reads none of them. -fn in_place_sample( - cx: &mut SelectCx<'_>, - call: Call<'_>, - index: u32, - sampler: &SamplerArg, - arm: Option, -) -> Result, Error> { - use super::bicubic::TapAddress; - use super::extended::State; - let Call { at, inst, t, args } = call; - let ops = Operands { t, args }; - let shape = t.image; - if arm.is_some() || shape.dim != ImageDim::D2 || shape.array || shape.ms || shape.depth { - return Ok(None); - } - let (has_offset, gather) = match t.op { - TexOp::Sample { - compare: false, - offset, - .. - } - | TexOp::SampleGrad { - compare: false, - offset, - } => (offset, None), - TexOp::Gather { - component, - compare: false, - offset, - } => { - use crate::air::intrinsics::Component as C; - let component = match component { - None | Some(C::X) => 0, - Some(C::Y) => 1, - Some(C::Z) => 2, - Some(C::W) => 3, - }; - (offset, Some(component)) - } - _ => return Ok(None), - }; - if clamp_value(cx, &ops)?.is_some() || crate::lower::texture::observes_status(cx, at) { - return Ok(None); - } - let offset = match fetch_offset(cx, &ops, has_offset, 2)? { - None => None, - Some(Offset::Const(k)) => Some(k), - Some(Offset::Dynamic(..)) => return Ok(None), - }; - let Ok((form, _)) = texel(t, 4) else { - return Ok(None); - }; - let half = match form.conv { - TexelConv::F16 => true, - TexelConv::F32 => false, - _ => return Ok(None), - }; - let (state, samplers) = match *sampler { - SamplerArg::Static(SamplerRef::Constexpr(words), _) => { - let s = super::state_of(words)?; - let linear = match (s.min_filter, s.mag_filter) { - (Filter::Linear, Filter::Linear) => true, - (Filter::Nearest, Filter::Nearest) => false, - _ => return Ok(None), - }; - if s.max_anisotropy > 1 || s.reduction != crate::air::abi::Reduction::WeightedAverage { - return Ok(None); - } - // A gather follows no filter. - let linear = linear && gather.is_none(); - let address = [s.address_s, s.address_t] - .into_iter() - .map(|m| match m { - AddressMode::ClampToEdge => TapAddress::Edge, - AddressMode::Repeat => TapAddress::Repeat, - AddressMode::MirroredRepeat => TapAddress::Mirror, - AddressMode::ClampToZero | AddressMode::ClampToBorder => TapAddress::Border, - }) - .collect(); - let state = State::Constant { - linear, - address, - border: s.border_color, - pixel: s.coordinates == Coordinates::Pixel, - }; - (state, 0) - } - SamplerArg::Static(SamplerRef::Slot(n), _) if n < 32 => { - (State::Slot { sampler: n }, 1 << n) - } - _ => return Ok(None), - }; - // An offset on an axis that may repeat or mirror is placed by Metal's rule, which reads a - // view's parent's base-level size: the slot's `OffsetBaseAxes` states where it differs. - let offset_base = offset.as_deref().is_some_and(|o| { - o.iter().enumerate().any(|(a, k)| { - *k != 0 - && match &state { - State::Constant { address, .. } => address - .get(a) - .is_some_and(|m| matches!(m, TapAddress::Repeat | TapAddress::Mirror)), - State::Slot { .. } => true, - } - }) - }); - let coord = ops - .get(TexRole::Coord) - .ok_or_else(|| cx.invariant("a sampling call without a coordinate"))?; - // The model takes a linear sample that addresses no border and whose offset no parent's size - // places: a constexpr sampler's state decides now, a runtime sampler's word as it runs. - let model = gather.is_none() - && !offset_base - && match &state { - State::Constant { - linear, address, .. - } => *linear && !address.iter().any(|m| matches!(m, TapAddress::Border)), - State::Slot { .. } => true, - }; - let sample = super::in_place::Sample { - texture: index, - state, - offset, - offset_base, - coord: id(cx, coord)?, - half, - gather, - model, - result: cx.lowered_repr(Value::Inst(at), inst.ty)?, - }; - Ok(Some((sample, samplers))) -} - /// Select sampling call `call` of texture slot `index`, whose variant binds the extended-range /// format `form`, through `sampler`: Metal's nearest or linear filter of the decoded texels, /// emulated by fetches of the raw texels on every device (`extended`). Built: a 2D or 2D array diff --git a/crates/metal2vulkan/src/lower/select.rs b/crates/metal2vulkan/src/lower/select.rs index 8845a18a6..134c9c999 100644 --- a/crates/metal2vulkan/src/lower/select.rs +++ b/crates/metal2vulkan/src/lower/select.rs @@ -1827,8 +1827,6 @@ fn identity_unsourced(f: &RuntimeFact) -> bool { | RuntimeFact::HeapStorageReads { .. } | RuntimeFact::AnisotropicSampler { .. } | RuntimeFact::StorageTextureIntegerChannels { .. } - | RuntimeFact::YCbCrInPlace { .. } - | RuntimeFact::TexelRows { .. } | RuntimeFact::TexelBufferParts { .. } ) } @@ -1976,10 +1974,7 @@ fn identity_refusal(plan: &Plan) -> Option { // at pixel coordinates, bicubic sample of a 1D texture (`Routine::Line`), or specialization of // a slot's state. Constexpr samplers a lane chooses among beside an argument buffer's texture // read the set-1 sampler array at the chosen candidate's pushed index - // (`SamplerPlan::heap_array_identity`) or are a switch over them. A two-plane texture's - // sample read in place (`Routine::Quad`) never reaches here: its slot's - // `PushField::YCbCrInPlace` is refused first, as an encoder value the identity domains do not - // source. + // (`SamplerPlan::heap_array_identity`) or are a switch over them. use crate::lower::sampler::bicubic::routines::Routine; let sampled = &plan.families.sampler; let refused = [ diff --git a/crates/metal2vulkan/src/lower/texture/emit.rs b/crates/metal2vulkan/src/lower/texture/emit.rs index f9f2ca544..4db855df4 100644 --- a/crates/metal2vulkan/src/lower/texture/emit.rs +++ b/crates/metal2vulkan/src/lower/texture/emit.rs @@ -88,7 +88,6 @@ fn value( return Ok(None); } TextureStrategy::ExtendedSample(e) => crate::lower::sampler::extended::emit(cx, fb, e)?, - TextureStrategy::InPlaceSample(e) => crate::lower::sampler::in_place::emit(cx, fb, e)?, TextureStrategy::AbsentArgument(a) => { return Ok(null_value(cx, fb, &a.value)?.first().copied()); } @@ -2416,20 +2415,7 @@ fn read_texel(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, r: &Read) -> BR // read through a sampler is tested as it accesses, with its addressed coordinate against the // size at its level, so only its layer or sample index can fail. let mut in_range = None; - if decl.rows { - // A rows slot's texel (`ImageDecl::rows`): its index in the view, of the coordinate - // clamped into the texture, and in range inside the texture at its one level (the select - // checks every such read). - let words = rows_words(cx, fb, &r.image)?; - let (index, mut inside) = rows_texel(fb, words, coord)?; - if let Some(l) = level.take() { - let zero = u32s(fb, 1, 0)?; - let first = fb.binary(BinOp::IEqual, l, zero)?; - inside = fb.binary(BinOp::LogicalAnd, inside, first)?; - } - coord = index; - in_range = Some(inside); - } else if (r.checked() || spec.is_some()) && !volume { + if (r.checked() || spec.is_some()) && !volume { let size = match (&through, level) { // The size at the level the read through a sampler accesses, which is the image's. (Some((_, a)), _) => a.size, @@ -2784,7 +2770,7 @@ pub(crate) fn heap_raw_form( /// Whether a texture `stage`'s handles can name is held by its raw texels alone: the /// `bind::heap::HELD` bit of `SpecKey::HeapRawTextures`, a `bool` fixed at pipeline creation, -/// which a plan gives from the command's heap members (`bind::plan::slots::heap_raw`). It defaults +/// which a consumer may specialize from the command's heap members. It defaults /// to every bit set, the module's every arm live, where nothing specializes it. fn raw_textures_held(fb: &mut FunctionBuilder<'_>, stage: Stage) -> BResult { use crate::bind::heap::{FILTERED, HELD}; @@ -3000,16 +2986,6 @@ fn write(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, w: &Write) -> BResul true => Some(volume_write(cx, fb, img, coord, w.level)?), false => None, }; - // A rows slot's write (`ImageDecl::rows`): to its texel's index in the view, stored only - // inside the texture, by the function's own test on every profile, as a two-plane 3D - // texture's is. - let volume = match (volume, decl.rows) { - (None, true) => { - let words = rows_words(cx, fb, &w.image)?; - Some(rows_texel(fb, words, coord)?) - } - (volume, _) => volume, - }; let coord = volume.map_or(coord, |(at, _)| at); // A texture buffer's parts: the part that holds the texel, at its index there; the check // below tests the texel against the whole width. @@ -3401,12 +3377,6 @@ fn query_value( q: &QueryOp, (decl, img, storage): (&ImageDecl, SValue, bool), ) -> BResult { - if decl.in_place { - return in_place_query(cx, fb, q); - } - if decl.rows { - return rows_query(cx, fb, q); - } let sampled_mips = decl.usage == ImageUsage::Sampled && !decl.multisampled && decl.dim != Dim::Buffer; let n = coord_len(decl); @@ -3500,101 +3470,6 @@ fn query_value( }) } -/// The answer of query `q` of a slot under its in-place variant (`sampler::in_place`): its -/// texture's width or height from the slot's push field, at a level as at any texture's -/// ([`level_extent`]), and its one level. -fn in_place_query( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - q: &QueryOp, -) -> BResult { - let ImageRef::Slot(index) = q.image else { - return Err(cx.fail("an in-place query of a heap element")); - }; - let Some(slot) = cx.plan.families.texture.slots.get(&index).map(|s| s.slot) else { - return Err(cx.fail(format!("texture slot {index} is not planned"))); - }; - match q.kind { - QueryKind::Size { component } => { - let e = crate::lower::sampler::in_place::extent(cx, fb, slot, component)?; - match q.level { - Some(l) => { - let l = cx.operand(fb, l)?; - level_extent(fb, e, l) - } - None => Ok(e), - } - } - QueryKind::Levels => u32s(fb, 1, 1), - _ => Err(cx.fail("an in-place query the form does not answer")), - } -} - -/// The answer of query `q` of a rows slot (`ImageDecl::rows`): its texture's width or height -/// from the slot's push field, at a level as at any texture's ([`level_extent`]), and its one -/// level. -fn rows_query(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, q: &QueryOp) -> BResult { - let words = rows_words(cx, fb, &q.image)?; - match q.kind { - QueryKind::Size { - component: c @ (0 | 1), - } => { - let e = fb.composite_extract(words, &[u32::from(c)])?; - match q.level { - Some(l) => { - let l = cx.operand(fb, l)?; - level_extent(fb, e, l) - } - None => Ok(e), - } - } - QueryKind::Levels => u32s(fb, 1, 1), - _ => Err(cx.fail("a rows query the rows do not answer")), - } -} - -/// The words of rows slot `image`'s push field (`PushField::TexelRows`, `bind::TexelRows`), a -/// `uvec4` of the texture's width, height, row and first texel in the view, in the open block. -fn rows_words( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - image: &ImageRef, -) -> BResult { - let ImageRef::Slot(index) = *image else { - return Err(cx.fail("the rows of a heap element")); - }; - let Some(slot) = cx.plan.families.texture.slots.get(&index).map(|s| s.slot) else { - return Err(cx.fail(format!("texture slot {index} is not planned"))); - }; - let field = cx.push_field(fb, crate::pipeline::sym::PushField::TexelRows(slot))?; - fb.composite_extract(field, &[0]) -} - -/// The texel at `coord` (a `uvec2`) of rows `words` ([`rows_words`]): its index in the view, -/// `first + y · row + x` of the coordinate clamped into the texture (whose width and height are -/// never 0), so the access stays inside the view, which ends at the last row's last texel; and -/// whether `coord` lies in the texture. -fn rows_texel( - fb: &mut FunctionBuilder<'_>, - words: SValue, - coord: SValue, -) -> BResult<(SValue, SValue)> { - use crate::bind::TexelRows as W; - let at = |i: usize| i as u32; - let size = fb.vector_shuffle(words, words, &[at(W::WIDTH), at(W::HEIGHT)])?; - let lt = fb.binary(BinOp::ULessThan, coord, size)?; - let inside = fb.unary(UnOp::All, lt)?; - let clamped = clamp_below(fb, coord, size, 2)?; - let x = fb.composite_extract(clamped, &[0])?; - let y = fb.composite_extract(clamped, &[1])?; - let row = fb.composite_extract(words, &[at(W::ROW)])?; - let first = fb.composite_extract(words, &[at(W::FIRST)])?; - let down = fb.binary(BinOp::IMul, y, row)?; - let start = fb.binary(BinOp::IAdd, first, down)?; - let index = fb.binary(BinOp::IAdd, start, x)?; - Ok((index, inside)) -} - /// The extent Metal answers at level `l` of a texture whose first level's extent is `e`: /// `max(1, e >> (l & 255))`, at every level, past the texture's level count too, a shift of 32 or /// more answering 1. Measured on an Apple M3 Max under macOS 27.0.1: the width, height, and depth diff --git a/crates/metal2vulkan/src/lower/texture/mod.rs b/crates/metal2vulkan/src/lower/texture/mod.rs index 4f15c7caf..721d1e4ef 100644 --- a/crates/metal2vulkan/src/lower/texture/mod.rs +++ b/crates/metal2vulkan/src/lower/texture/mod.rs @@ -665,9 +665,6 @@ pub enum TextureStrategy { /// A sample of a texture slot bound in an extended-range format, emulated by fetches of its /// raw texels (`sampler::extended`). ExtendedSample(Box), - /// A sample of a two-plane YCbCr texture slot whose variant reads its planes in place, - /// computed from their codes (`sampler::in_place`). - InPlaceSample(Box), /// An operation on the absent handle: a texture or sampler a function constant removed /// (`memory::handles::Candidate::Absent`). AbsentArgument(AbsentArgument), @@ -901,7 +898,6 @@ impl TextureStrategy { TextureStrategy::ImageblockSlice(s) if s.guard => "texture.imageblock_slice_guarded", TextureStrategy::ImageblockSlice(_) => "texture.imageblock_slice", TextureStrategy::ExtendedSample(e) => e.name(), - TextureStrategy::InPlaceSample(e) => e.name(), TextureStrategy::AbsentArgument(_) => AbsentArgument::NAME, }) } @@ -958,7 +954,6 @@ impl TextureStrategy { TextureStrategy::Switch(s) => s.words(), TextureStrategy::ImageblockSlice(s) => s.words(), TextureStrategy::ExtendedSample(e) => e.words(), - TextureStrategy::InPlaceSample(e) => e.words(), // The zero, a constant. TextureStrategy::AbsentArgument(_) => 0, } @@ -1242,19 +1237,7 @@ pub fn declare( } None => image, }; - // A planes image's slot is the combined image sampler of the device's conversion - // (`ResourceKind::YCbCrPlanes`). - let (ty, symbol) = match decl.planes_sampler { - Some(sampler) => ( - mb.ty(SType::SampledImage { image: ty })?, - crate::pipeline::sym::ResourceSlot { - stage: s.slot.stage, - kind: crate::pipeline::sym::ResourceKind::YCbCrPlanes(sampler), - index: s.slot.index, - }, - ), - None => (ty, crate::pipeline::sym::ResourceSlot::metal(s.slot)), - }; + let symbol = crate::pipeline::sym::ResourceSlot::metal(s.slot); let g = mb.resource(symbol, crate::spirv::ir::StorageClass::UniformConstant, ty)?; if s.volatile && volatile_decorated(plan) { mb.volatile(g)?; @@ -1805,8 +1788,6 @@ pub fn select( _ => Vec::new(), }; for index in slots { - not_in_place(cx, index); - not_rows(cx, index); if extended_range(cx, ImageRef::Slot(index))?.is_some() { return Err(Unsupported::not_implemented(Feature::Format).into()); } @@ -1850,8 +1831,6 @@ pub fn select( let arm = match c { // A switch-at-use's arm reads its slot's image. Candidate::Texture(index) => { - not_in_place(cx, index); - not_rows(cx, index); select_image(cx, (at, inst), t, &ops, ImageRef::Slot(index), m)? } Candidate::Absent => AbsentArgument::select(cx, at, inst)?, @@ -2454,29 +2433,6 @@ pub(crate) fn extended_range( Ok(cx.inputs.extended_range.get(&slot).copied()) } -/// Whether texture slot `index`'s variant reads a two-plane YCbCr texture's planes in place -/// (`LoweringInputs::ycbcr_in_place`, `sampler::in_place`). -pub(crate) fn ycbcr_in_place(cx: &SelectCx<'_>, index: u32) -> Result { - let slot = slot_of(cx, index)?.slot; - Ok(cx.inputs.ycbcr_in_place.contains(&slot)) -} - -/// Record an access of texture slot `index` that its in-place form does not read -/// (`slot::InPlaceReads::blocked`): no texture is read in place there. -pub(crate) fn not_in_place(cx: &mut SelectCx<'_>, index: u32) { - if let Some(s) = cx.families.texture.slots.get_mut(&index) { - s.in_place.blocked = true; - } -} - -/// Record an access of texture slot `index` that its texture's rows read in place do not answer -/// (`slot::SlotPlan::not_rows`): the slot takes no rows variant. -pub(crate) fn not_rows(cx: &mut SelectCx<'_>, index: u32) { - if let Some(s) = cx.families.texture.slots.get_mut(&index) { - s.not_rows = true; - } -} - /// Mark texture slot `index` as accessed in a way a texture buffer's parts do not answer /// (`slot::SlotPlan::not_parts`): the slot takes no parts variant. pub(crate) fn not_parts(cx: &mut SelectCx<'_>, index: u32) { @@ -2485,11 +2441,6 @@ pub(crate) fn not_parts(cx: &mut SelectCx<'_>, index: u32) { } } -/// Whether the function observes any of texture call `at`'s status word. -pub(crate) fn observes_status(cx: &mut SelectCx<'_>, at: InstId) -> bool { - status_use(cx, at).is_some() -} - /// The numeric class of the texture texture slot `image`'s variant binds where it is not the /// class the function declares there (`LoweringInputs::cross_class`), else `None`: the slot's /// image is declared of that class (`slot::image_class`), and its reads, samples and gathers take @@ -2582,16 +2533,6 @@ pub(crate) fn swizzled_storage(cx: &SelectCx<'_>, image: ImageRef) -> Result, image: ImageRef) -> Result { - let ImageRef::Slot(index) = image else { - return Ok(false); - }; - let slot = slot_of(cx, index)?.slot; - Ok(cx.inputs.texel_rows.contains(&slot)) -} - /// Record that texture slot `index`'s function applies its bound texture's swizzle: the slot's /// `TextureSwizzle` specialization (`RuntimeFact::TextureSwizzle`). pub(crate) fn swizzles(cx: &mut SelectCx<'_>, index: u32) -> Result<(), Error> { @@ -2669,25 +2610,7 @@ fn select_image( m: &mut Meter, ) -> Result { let shape = t.image; - // The in-place form reads a slot's width, height and level count, and nothing else here. if let ImageRef::Slot(index) = image { - if !matches!( - t.op, - TexOp::Query(Query::Width | Query::Height | Query::NumMipLevels) - ) { - not_in_place(cx, index); - } - // The rows read and write a texel by its coordinate, and answer the size, the level - // count and the presence; nothing else. - if !matches!( - t.op, - TexOp::Read - | TexOp::Write - | TexOp::IsNull - | TexOp::Query(Query::Width | Query::Height | Query::NumMipLevels) - ) { - not_rows(cx, index); - } // A texture buffer's parts read, write and update a texel by its index, and answer the // width, the presence and a fence; nothing else. if !matches!( @@ -2912,7 +2835,6 @@ fn select_read_as( if let Some(t) = through { select_through(cx, image, texel, t)?; if let ImageRef::Slot(index) = image { - not_rows(cx, index); not_parts(cx, index); } } @@ -2946,9 +2868,6 @@ fn select_read_as( } let check = match slot::read_check(cx, shape.dim == ImageDim::Buffer) { ReadCheck::Device if extended.is_some() => ReadCheck::Shader, - // A rows slot's coordinate past the width names the next row's texel in the view - // (`bind::texel_rows`): the shader selects Metal's out-of-bounds texel on every profile. - _ if texel_rows(cx, image)? => ReadCheck::Shader, c => c, }; // A storage read at a level reads the slot's level views, and past the bound level count diff --git a/crates/metal2vulkan/src/lower/texture/slot.rs b/crates/metal2vulkan/src/lower/texture/slot.rs index 3dbd7993d..42bd2bfab 100644 --- a/crates/metal2vulkan/src/lower/texture/slot.rs +++ b/crates/metal2vulkan/src/lower/texture/slot.rs @@ -91,22 +91,6 @@ pub struct Uses { pub narrow_result: bool, } -/// How a slot's accesses read a two-plane YCbCr texture bound there, for its planes read in -/// place (`sampler::in_place`, `RuntimeFact::YCbCrInPlace`). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] -pub struct InPlaceReads { - /// An access the form does not read: anything but a sample or gather it builds - /// (`sampler::select`'s `in_place_sample`) and a query of the width, the height or the level - /// count. - pub blocked: bool, - /// The runtime sampler slots the slot's samples and gathers read, bit `n` `[[sampler(n)]]`. - pub samplers: u32, - /// A sample the device's own sampler Y′CbCr conversion does not take - /// (`LoweringInputs::ycbcr_planes_sampled`): one through a constexpr sampler that addresses a - /// border, one that places a texel offset by a parent's size, or a gather. - pub device_blocked: bool, -} - /// The `OpTypeImage` a slot is declared as, and the conversion a storage image's class needs. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct ImageDecl { @@ -132,20 +116,6 @@ pub struct ImageDecl { /// after the class's conversion, its reads take alpha 1 and its writes store green in the /// fourth channel. pub x_channel: bool, - /// The slot's variant reads a two-plane YCbCr texture's planes in place - /// (`LoweringInputs::ycbcr_in_place`): the image is the planes' uniform texel buffer of - /// unsigned codes (`sampler::in_place`), the texture's size its push field's. - pub in_place: bool, - /// The slot's variant samples those planes as an image through the device's own sampler - /// Y′CbCr conversion (`LoweringInputs::ycbcr_planes_sampled`): the slot is a combined image - /// sampler of a sampled 2D `float` image (`ResourceKind::YCbCrPlanes`), whose immutable - /// sampler bakes the conversion; `in_place` holds, so its size is still the push field's. - pub planes_sampler: Option, - /// The slot's variant reads and writes a 2D texture's rows in place - /// (`LoweringInputs::texel_rows`, `bind::texel_rows`): the image is the rows' texel buffer, - /// uniform for a sampled slot and storage for a storage one, texel `(x, y)` its texel - /// `first + y · row + x` and the texture's size the push field's. - pub rows: bool, /// A texture-buffer slot under its parts variant (`LoweringInputs::texel_buffer_parts`, /// `bind::texel_parts`), declared as an array of its parts' texel buffers. pub parts: Option, @@ -247,12 +217,6 @@ pub struct SlotPlan { /// specialization, which states the axes on which the base-level size the rule reads, a /// view's parent's, is not a power of two where the bound view's is. pub offset_base: bool, - /// How its accesses read a two-plane YCbCr texture's planes in place. - pub in_place: InPlaceReads, - /// An access its texture's rows read in place do not answer (`bind::texel_rows`): anything - /// but a read or write of a texel by its coordinate, a query of the width, the height or the - /// level count, and a presence test. The uses rule out the rest ([`rows_reads`]). - pub not_rows: bool, /// An access a texture buffer's parts do not answer (`bind::texel_parts`): anything but a /// read of a texel by its index (not through a sampler), a write, an atomic, a width query, a /// presence test and a fence. The uses rule out the rest ([`parts_reads`]). @@ -281,8 +245,6 @@ impl SlotPlan { swizzle: false, constant_lanes: false, offset_base: false, - in_place: InPlaceReads::default(), - not_rows: false, not_parts: false, decl: None, } @@ -607,9 +569,6 @@ fn declare_heap( level_views: None, extended: None, x_channel: false, - in_place: false, - planes_sampler: None, - rows: false, parts: None, }; Ok((class, decl)) @@ -1096,107 +1055,6 @@ fn declare_slot( ) -> Result { let images = &cx.profile.fields().images; let storage = s.storage(); - // A slot that samples its texture's planes as an image through the device's own sampler - // Y′CbCr conversion is a combined image sampler of a 2D `float` image, with the field of the - // planes' words for its size (`sampler::in_place`). - if let Some(&sampler) = cx.inputs.ycbcr_planes_sampled.get(&s.slot) { - if !cx.inputs.ycbcr_in_place.contains(&s.slot) { - return Err(cx.invariant("a planes image's slot outside its in-place variant")); - } - push.push(PushField::YCbCrInPlace(s.slot)); - counts.sampled_images = counts.sampled_images.saturating_add(1); - counts.samplers = counts.samplers.saturating_add(1); - return Ok(ImageDecl { - dim: Dim::D2, - arrayed: false, - multisampled: false, - depth: false, - usage: ImageUsage::Sampled, - format: crate::spv::ImageFormat::Unknown, - texel: TexelClass::Float, - cube_as_array: false, - class: StorageImageClass::Identity, - level_views: None, - extended: None, - x_channel: false, - in_place: true, - planes_sampler: Some(sampler), - rows: false, - parts: None, - }); - } - // A slot under its in-place variant is the uniform texel buffer of its texture's planes, of - // unsigned codes, with the field of their words (`sampler::in_place`). - if cx.inputs.ycbcr_in_place.contains(&s.slot) { - push.push(PushField::YCbCrInPlace(s.slot)); - counts.sampled_images = counts.sampled_images.saturating_add(1); - return Ok(ImageDecl { - dim: Dim::Buffer, - arrayed: false, - multisampled: false, - depth: false, - usage: ImageUsage::Sampled, - format: crate::spv::ImageFormat::Unknown, - texel: TexelClass::Uint, - cube_as_array: false, - class: StorageImageClass::Identity, - level_views: None, - extended: None, - x_channel: false, - in_place: true, - planes_sampler: None, - rows: false, - parts: None, - }); - } - // A slot under its rows variant is the texel buffer of its texture's rows, with the field of - // their words (`bind::texel_rows`): a uniform one for a sampled slot, a storage one, declared - // as the slot's storage image would be, for a storage slot. - if cx.inputs.texel_rows.contains(&s.slot) { - if !rows_reads(s) { - return Err(cx.invariant("a rows slot whose accesses the rows do not answer")); - } - push.push(PushField::TexelRows(s.slot)); - let texel = image_class(cx.inputs, s); - let (format, class) = match storage { - true => { - facts.push(RuntimeFact::StorageTextureFormat { slot: s.slot }); - storage_format(cx, s, texel)? - } - false => ( - crate::spv::ImageFormat::Unknown, - StorageImageClass::Identity, - ), - }; - if class != StorageImageClass::Identity { - return Err(cx.invariant("a rows slot whose storage image converts its texels")); - } - match storage { - true => counts.storage_images = counts.storage_images.saturating_add(1), - false => counts.sampled_images = counts.sampled_images.saturating_add(1), - } - return Ok(ImageDecl { - dim: Dim::Buffer, - arrayed: false, - multisampled: false, - depth: false, - usage: match storage { - true => ImageUsage::Storage, - false => ImageUsage::Sampled, - }, - format, - texel, - cube_as_array: false, - class, - level_views: None, - extended: None, - x_channel: false, - in_place: false, - planes_sampler: None, - rows: true, - parts: None, - }); - } // A slot bound in an extended-range format holds its raw texels in an unsigned integer // image. let extended = cx.inputs.extended_range.get(&s.slot).copied(); @@ -1325,47 +1183,10 @@ fn declare_slot( level_views: views, extended, x_channel, - in_place: false, - planes_sampler: None, - rows: false, parts, }) } -/// Whether every access of slot `s` is one its texture's planes read in place answer -/// (`sampler::in_place`), on a profile that takes the form (`ProfileFields::ycbcr_in_place`): a -/// sampled 2D texture's (not an array, multisampled or depth one), of a `float` class or only -/// queried, used, and no access blocked ([`InPlaceReads::blocked`]). -fn in_place_reads(cx: &SelectCx<'_>, s: &SlotPlan) -> bool { - let used = s.uses.read || s.uses.query || s.uses.sample; - cx.profile.fields().ycbcr_in_place - && used - && !s.in_place.blocked - && !s.storage() - && s.shape - .is_some_and(|x| x.dim == ImageDim::D2 && !x.array && !x.ms && !x.depth) - && matches!(s.texel, None | Some(TexelClass::Float)) -} - -/// Whether every access of slot `s` is one its texture's rows read in place answer -/// (`bind::texel_rows`): a single-sample 2D color texture's (not an array, multisampled or depth -/// one) of a 32-bit class, read, written or asked its size, every access of a texel at the first -/// level of a storage slot (no level views), and nothing sampled, gathered, updated by an atomic, -/// read through a sampler or a switch, its residency observed or its integer channels read; no -/// access blocked ([`SlotPlan::not_rows`]). -fn rows_reads(s: &SlotPlan) -> bool { - let u = &s.uses; - (u.read || u.write || u.query) - && !(u.sample || u.compare || u.atomic || u.level_views || u.residency || u.faces) - && !(u.int_channels || u.narrow_result || s.not_rows) - && s.shape - .is_some_and(|x| x.dim == ImageDim::D2 && !x.array && !x.ms && !x.depth) - && matches!( - s.texel, - None | Some(TexelClass::Float | TexelClass::Sint | TexelClass::Uint) - ) -} - /// Whether every access of texture-buffer slot `s` is one its parts answer (`bind::texel_parts`), /// on a profile that indexes an array of its kind of texel buffer (storage where the function /// writes or updates it, else uniform) by a `NonUniform` value: read, written, updated by an @@ -1435,13 +1256,12 @@ pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> { } Err(error) => return Err(error), }; - // A rows slot's every load and store is the function's own test's, inside the view. - let volatile = !d.rows && forwards(cx, &s.uses, shape.dim == ImageDim::Buffer); + let volatile = forwards(cx, &s.uses, shape.dim == ImageDim::Buffer); decls.push((*index, d, volatile)); } - // The variants a slot may take by its bound texture (cross-class reads, planes read in place, - // a texture's rows, a texture buffer's parts): under the identity domains no binder chooses a - // variant, and the slot reads whatever texture its resource ID names through the plain form. + // The variants a slot may take by its bound texture (cross-class reads, a texture buffer's + // parts): under the identity domains no variant is chosen, and the slot reads whatever + // texture its resource ID names through the plain form. if !crate::lower::access::identity(cx.profile) { // The slots read, sampled or gathered in any class (a slot only sampled is declared by its // combined bindings, `sampler::finish`). @@ -1450,35 +1270,6 @@ pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> { facts.push(RuntimeFact::CrossClassReads { slot: s.slot }); } } - // The slots whose every access the in-place form reads, on a profile that takes it: their - // compile under the form states the same, which its plan holds to. - for s in cx.families.texture.slots.values() { - let reads = in_place_reads(cx, s); - if !reads && cx.inputs.ycbcr_in_place.contains(&s.slot) { - return Err( - cx.invariant("an in-place texture slot whose accesses the form does not read") - ); - } - if s.in_place.device_blocked && cx.inputs.ycbcr_planes_sampled.contains_key(&s.slot) { - return Err(cx.invariant( - "a planes image's texture slot with a sample the device's sampler does not take", - )); - } - if reads { - facts.push(RuntimeFact::YCbCrInPlace { - slot: s.slot, - samplers: s.in_place.samplers, - device: !s.in_place.device_blocked, - }); - } - } - // The slots whose every access the rows answer: their compile under the rows variant states - // the same, which its plan holds to. - for s in cx.families.texture.slots.values() { - if rows_reads(s) { - facts.push(RuntimeFact::TexelRows { slot: s.slot }); - } - } // The texture-buffer slots whose every access their parts answer: their compile under the // parts variant states the same, which its plan holds to. for s in cx.families.texture.slots.values() { @@ -1747,17 +1538,13 @@ impl SlotPlan { /// shader joins and splits, so its class is the unsigned integer one of its shape. A texture /// buffer's is a texel buffer's, uniform where the slot reads and storage where it writes, the /// element its resource ID holds in the texel-buffer arrays. `None` for a declaration the identity -/// arrays hold no element of yet: a cube viewed as an array, level views, a texture buffer's parts -/// or rows, planes, an extended-range or RGBX form, or a storage image with another format or a -/// conversion. +/// arrays hold no element of yet: a cube viewed as an array, level views, a texture buffer's parts, +/// an extended-range or RGBX form, or a storage image with another format or a conversion. pub(crate) fn identity_class(decl: &ImageDecl) -> Option { let plain = !decl.cube_as_array && decl.level_views.is_none() && decl.extended.is_none() && !decl.x_channel - && !decl.in_place - && decl.planes_sampler.is_none() - && !decl.rows && decl.parts.is_none() && decl.class == StorageImageClass::Identity; let dim = match decl.dim { diff --git a/crates/metal2vulkan/src/memory/handles.rs b/crates/metal2vulkan/src/memory/handles.rs index 2815f1108..a9c23499a 100644 --- a/crates/metal2vulkan/src/memory/handles.rs +++ b/crates/metal2vulkan/src/memory/handles.rs @@ -1687,25 +1687,6 @@ pub fn define_lookup(mb: &mut ModuleBuilder, t: Table, form: Lookup) -> BResult< fb.finish() } -/// The search [`lookup`] emits, on the host: the element of `id` in `table`, a slice of -/// `(resource_id, element)` entries sorted by id whose first entry is the null entry. The -/// emitter's reference model, which every table a binder builds must satisfy. -pub fn lookup_host(table: &[(u64, u32)], id: u64) -> u32 { - let (mut base, mut len) = (0usize, table.len()); - for _ in 0..SEARCH_STEPS { - let half = len >> 1; - let mid = base + half; - if table.get(mid).is_some_and(|(k, _)| *k <= id) { - base = mid; - } - len -= half; - } - match table.get(base) { - Some((k, e)) if *k == id => *e, - _ => NEUTRAL_ELEMENT, - } -} - #[cfg(test)] mod tests { use super::*; @@ -1876,19 +1857,6 @@ mod tests { .map_or(NEUTRAL_ELEMENT, |i| t[i].1) } - /// The host model finds every entry of sorted tables up to [`TABLE_CAPACITY`] entries in - /// [`SEARCH_STEPS`] steps, and maps every absent id (and the null id) to the neutral element. - #[test] - fn the_search_finds_every_entry_up_to_the_capacity() { - assert_eq!(1u64 << SEARCH_STEPS, u64::from(TABLE_CAPACITY)); - for n in [1, 2, 3, 4, 5, 16, 17, 100, 4097, TABLE_CAPACITY as usize] { - let t = table(n); - for id in keys(&t) { - assert_eq!(lookup_host(&t, id), reference(&t, id), "n {n} id {id:#x}"); - } - } - } - const KEYS: u32 = 8; /// A kernel that looks up the [`KEYS`] ids (low, high word pairs) at the start of the @@ -1948,7 +1916,7 @@ mod tests { /// The emitted search is the host model: over the CPU interpreter, every key of tables of /// several sizes up to [`TABLE_CAPACITY`] entries (the null id, present ids, absent ids between - /// and beyond them) gets [`lookup_host`]'s element, through an entry array (`u64` ids) and a + /// and beyond them) gets [`reference`]'s element, through an entry array (`u64` ids) and a /// word view. [`Lookup::Flagged`] also carries a found entry's [`FLAG_OUT_OF_BOUNDS_ALPHA_ONE`] /// in [`HANDLE_ALPHA_ONE`] where it carries the alpha, its texel class where it carries that, /// and its [`FLAG_RED_BLUE`] in [`HANDLE_RED_BLUE`] where it carries that, carrying no other @@ -2149,7 +2117,7 @@ mod tests { u32::from_le_bytes(io[at..at + 4].try_into().expect("word")) }; for (i, id) in chunk.iter().enumerate() { - let e = lookup_host(&t, *id); + let e = reference(&t, *id); let carried = |on: bool, flag: u32, bit: u32| match on { true if flags(e) & flag != 0 => bit, _ => 0, @@ -2227,7 +2195,7 @@ mod tests { for (i, id) in chunk.iter().enumerate() { let at = 4 * (2 * KEYS as usize + i); let got = u32::from_le_bytes(io[at..at + 4].try_into().expect("word")); - let e = lookup_host(&t, *id); + let e = reference(&t, *id); let carried = |on: bool, flag: u32, bit: u32| match on { true if flags(e) & flag != 0 => bit, _ => 0, diff --git a/crates/metal2vulkan/src/memory/roots.rs b/crates/metal2vulkan/src/memory/roots.rs index 50041bcca..a5c371ba4 100644 --- a/crates/metal2vulkan/src/memory/roots.rs +++ b/crates/metal2vulkan/src/memory/roots.rs @@ -16,17 +16,17 @@ //! entries `{host, guest, size, bind_offset}: u64`. Entry 0 is the null root (all fields 0: //! `guest = 0` makes a miss round-trip through a later `ptrtoint`, `size = 0` puts every access //! through it out of bounds). Entry 1 is the write-only sink (`host` its device address). Entry -//! `2 + n` is `[[buffer(n)]]`. The **resident set** (the bound arguments and -//! `BindState.used_resources`, overlaps coalesced into the outermost range) is the entries `R0 .. +//! `2 + n` is `[[buffer(n)]]`. The **resident set** (the bound arguments and the resources the +//! encoder makes resident, `useResource:`, overlaps coalesced into the outermost range) is the +//! entries `R0 .. //! R0 + N`, sorted by `guest` and disjoint but for indirect command buffers' records, which may //! overlap (each found only at its start, `lower::access::dynamic::search_start`), each with -//! `bind_offset = 0`. The binder states `R0` and +//! `bind_offset = 0`. The consumer states `R0` and //! `N` in the sink entry's otherwise unread `guest` and `size` fields ([`RESIDENT_FIRST`], -//! [`RESIDENT_COUNT`]); `N` is any count (At most 2¹⁶ before, a larger set -//! `BindError::ResidentSetTooLarge`). `R0` counts entries from the table's address modulo 2⁶⁴, so +//! [`RESIDENT_COUNT`]); `N` is any count. `R0` counts entries from the table's address modulo 2⁶⁴, so //! the set may lie apart from the table, below it too (a consumer's set shared by many tables). //! -//! **The search** ([`resolve`]) turns a guest address `i` into a wide pointer: a binary search for +//! **The search** ([`define_resolve`]) turns a guest address `i` into a wide pointer: a binary search for //! the last resident entry whose `guest ≤ i`, whose step halves the candidates whatever its //! compare gives (one entry load and a select, no branch on the address), so its trip count //! follows `N` alone and every invocation that searches one table takes the same branches. A set @@ -250,7 +250,7 @@ fn field_of(fb: &mut FunctionBuilder<'_>, e: Value, root: Value, field: u64) -> } /// The wide pointer `[root, at, host, size]` (four `u64`s) of guest address `guest` (a `u64`) -/// through the resident set of the root table at `table` ([`resolve`]): a hit's `at` is `i − +/// through the resident set of the root table at `table` ([`define_resolve`]): a hit's `at` is `i − /// guest` (a resident entry's `bind_offset` is 0) and `host` and `size` its entry's, read here /// once; a miss is `[0, i, 0, 0]`, the null root's fields. pub fn resolve_wide( @@ -280,7 +280,7 @@ struct Found { off: Value, } -/// The search of [`resolve`]. +/// The search of [`define_resolve`]. fn search(fb: &mut FunctionBuilder<'_>, table: Value, guest: Value) -> BResult { let e = entries(fb, table)?; let sink = k64(fb, SINK_ROOT)?; diff --git a/crates/metal2vulkan/src/metal/format/mod.rs b/crates/metal2vulkan/src/metal/format/mod.rs index 89f00617b..855207def 100644 --- a/crates/metal2vulkan/src/metal/format/mod.rs +++ b/crates/metal2vulkan/src/metal/format/mod.rs @@ -136,8 +136,7 @@ pub enum FormatEmulation { /// `R32G32B32A32_SFLOAT` of an `_sRGB` twin's (a grid of `1/8192`), and /// `A2B10G10R10_UNORM_PACK32` of the codes. Exact for a sampled image a function reads or /// fetches from; a linear sample is the device's filter of the texels, noted, off their grid - /// (`metal::texel_format::PackedTexels::YCbCr2048` and `YCbCr8192`), but where the function - /// reads the planes in place (`bind::YCbCrInPlace`), Metal's filter. Admitted for sampling only: + /// (`metal::texel_format::PackedTexels::YCbCr2048` and `YCbCr8192`). Admitted for sampling only: /// Metal drops a function's writes to a 4:2:0 or 4:2:2 format ([`writes_dropped`]), stores a /// 4:4:4 one's into both planes (refused here, `storage_choice`), and renders into such a /// texture by an inverse conversion, for which a pipeline into one of [`ycbcr_renders`] is @@ -1131,24 +1130,6 @@ pub fn alpha_in_red(pf: PixelFormat, profile: &DeviceProfile) -> bool { alpha_in_red_format(pf).is_some() && direct_format(pf).is_some_and(|own| !held(own)) } -/// The format a texel buffer view of a texture buffer of `pf` takes for `usage` (a texel buffer -/// usage) on `profile` where the format's own does not serve it and the bytes hold Metal's alpha in -/// red ([`FormatEmulation::AlphaInRed`]): `R8_UNORM` for `A8Unorm` on a device that views no -/// `A8_UNORM` texels for the usage (a Vulkan 1.2 device without `VK_KHR_maintenance5`), where it -/// views `R8_UNORM` ones. A view reads `(r, 0, 0, 1)` where Metal reads `(0, 0, 0, r)`: a storage -/// view's reads and writes convert by its choice's class (`StorageImageClass::AlphaInRed`, -/// [`storage_choice`]), and a uniform view's reads take the alpha from red through the slot's -/// swizzle (`TextureSwizzleChannels::alpha_in_red`). `None` elsewhere. -pub(crate) fn texel_buffer_alpha_in_red( - pf: PixelFormat, - usage: FormatUsage, - profile: &DeviceProfile, -) -> Option { - let own = direct_format(pf)?; - let held = alpha_in_red_format(pf)?; - (!profile.supports_format(own, usage) && profile.supports_format(held, usage)).then_some(held) -} - /// The format of `pf`'s image where the device holds no image of its direct format and `pf` /// holds Metal's alpha in red ([`FormatEmulation::AlphaInRed`]): `R8_UNORM` for `A8Unorm`, /// `None` for every other format. @@ -1873,10 +1854,10 @@ pub fn ycbcr(pf: PixelFormat) -> bool { /// kernel's write leaves both planes' bytes as they were, and Metal's validation stops the /// binding), and the packed ones, `YCBCR10_444_2P_PACKED` and its `_sRGB` twin among them (the /// M3 Max under macOS 27.0.1, our probe `ycw` over `p444` and `pf44` surfaces: every byte of both -/// planes kept, the command buffer completed; an Apple M4 stores them). A storage slot a function -/// only writes takes its neutral there (`bind::plan`), and so does a heap's storage class -/// (`bind::heap`, an argument buffer's texture, whose writes Metal drops alike: the M3 Max under -/// macOS 27.0.1, `YCBCR8_420_2P`), which the writes leave as Metal leaves the texture. +/// planes kept, the command buffer completed; an Apple M4 stores them). A heap's storage class +/// holds such a texture as its neutral (`bind::heap::fit`, an argument buffer's texture, whose +/// writes Metal drops alike: the M3 Max under macOS 27.0.1, `YCBCR8_420_2P`), which the writes +/// leave as Metal leaves the texture. /// /// An unpacked 4:4:4 YCbCr format's writes are not dropped: Metal stores each texel's codes into /// both planes, and a slot that writes one is refused (`storage_choice`). @@ -2661,8 +2642,7 @@ pub fn storage_image_choice( /// `SrgbEncode` (`BGRA8Unorm_sRGB`, where its twin is not accessed without a format, through /// `R8G8B8A8_UNORM` with `SrgbEncodeBgra`), `RGB9E5Float` through `R32_UINT` with /// `SharedExponentBits`, and `A8Unorm` through `R8_UNORM` with `AlphaInRed` (no alias: such a -/// texture's image is `R8_UNORM` itself, [`FormatEmulation::AlphaInRed`]; a texture buffer's bytes -/// take that view wherever `A8_UNORM` does not serve the use, [`texel_buffer_alpha_in_red`]). +/// texture's image is `R8_UNORM` itself, [`FormatEmulation::AlphaInRed`]). /// Anything else is `Unsupported{Format}` naming what each route lacks, a format's without-format /// usage included. /// diff --git a/crates/metal2vulkan/src/metal/mod.rs b/crates/metal2vulkan/src/metal/mod.rs index 550705f2b..d1f5ce703 100644 --- a/crates/metal2vulkan/src/metal/mod.rs +++ b/crates/metal2vulkan/src/metal/mod.rs @@ -375,26 +375,6 @@ impl TextureSwizzleChannels { a: channel(3, self.alpha), } } - - /// This swizzle of the texel `(0, 0, 0, a)` an `A8Unorm` texture buffer reads, as a swizzle - /// of the texel `(a, 0, 0, 1)` its bytes' `R8_UNORM` view reads - /// (`metal::format::texel_buffer_alpha_in_red`): each channel taken from red, green or blue is - /// zero, one taken from alpha the view's red, and `Zero` and `One` stay. - pub(crate) fn alpha_in_red(self) -> TextureSwizzleChannels { - let held = |s: TextureSwizzle| match s { - TextureSwizzle::Red | TextureSwizzle::Green | TextureSwizzle::Blue => { - TextureSwizzle::Zero - } - TextureSwizzle::Alpha => TextureSwizzle::Red, - constant => constant, - }; - TextureSwizzleChannels { - red: held(self.red), - green: held(self.green), - blue: held(self.blue), - alpha: held(self.alpha), - } - } } impl Default for TextureSwizzleChannels { diff --git a/crates/metal2vulkan/src/metal/sampler.rs b/crates/metal2vulkan/src/metal/sampler.rs index 7c26eb71d..20cb52554 100644 --- a/crates/metal2vulkan/src/metal/sampler.rs +++ b/crates/metal2vulkan/src/metal/sampler.rs @@ -396,42 +396,6 @@ pub fn check_sampler( Ok(()) } -/// [`check_sampler`] for a sampler an argument buffer lists, which a function reads without -/// knowing its state: anisotropy above 1 without `samplerAnisotropy` is refused too, since such a -/// function neither emulates Metal's anisotropic filter through it nor records the isotropic -/// filter its Vulkan sampler takes there (`lower::sampler::anisotropic`'s reach). -pub(crate) fn check_argument_sampler( - shape: &SamplerShape, - use_: SamplerUse, - profile: &DeviceProfile, -) -> Result<(), Error> { - check_sampler(shape, use_, profile)?; - if shape.anisotropic && !profile.fields().images.sampler_anisotropy { - return Err(Unsupported::needs( - Feature::SamplerAnisotropy, - Capability::Feature(VkFeature::SamplerAnisotropy), - ) - .into()); - } - Ok(()) -} - -/// What of the Vulkan sampler [`vk_sampler`] makes for a sampler of `shape` used as `use_` decides -/// the format features it needs of a view it reads (`bind::sampler_desc`): whether some filter is -/// linear (none for an integer use, which [`vk_sampler`] makes nearest), and its reduction, the -/// weighted average ([`vk_sampler`]). A plan reads it where a runtime sampler meets its textures -/// through separate descriptors, so the textures' views are checked against the bound sampler at -/// plan time as a combined write's view is per bind. -pub(crate) fn vk_filtering( - shape: &SamplerShape, - use_: SamplerUse, -) -> (bool, vk::SamplerReductionMode) { - ( - shape.linear && !use_.integer_texture, - vk::SamplerReductionMode::WEIGHTED_AVERAGE, - ) -} - /// The Vulkan sampler for a Metal sampler descriptor used as `use_` on `profile`. /// /// An integer texture is never filtered: Metal reads a linear filter on one as nearest (an Apple M3 @@ -926,39 +890,10 @@ pub(crate) fn border_texel( ] } -/// The first bit of a [`constant_lanes`] word that says a lane is the constant 1: bit +/// The first bit of a `SpecKey::ConstantLanes` word that says a lane is the constant 1: bit /// `CONSTANT_ONES + lane`, where bit `lane` says it is a constant. pub(crate) const CONSTANT_ONES: u32 = 4; -/// The lanes Metal reads as constants from every texel of a texture whose format holds the -/// channels `present` (red, green, blue, alpha; [`crate::metal::format::channels`]), made with -/// `swizzle`, as a word: bit `lane` (0 red to 3 alpha) where the lane's source is a channel the -/// format lacks or a `Zero` or `One` swizzle, and bit [`CONSTANT_ONES`]` + lane` where that -/// constant is 1 (a missing alpha, or `One`); a missing red, green or blue, and `Zero`, read 0. -/// Metal reads them so at a mapped texel, an unmapped one, and the border alike, and so after any -/// filter, which weighs constants alone there. -pub(crate) fn constant_lanes(present: [bool; 4], swizzle: TextureSwizzleChannels) -> u32 { - let lanes = [swizzle.red, swizzle.green, swizzle.blue, swizzle.alpha]; - let mut word = 0; - for (lane, source) in (0u32..).zip(lanes) { - let constant = match source { - TextureSwizzle::Zero => Some(false), - TextureSwizzle::One => Some(true), - TextureSwizzle::Red => (!present[0]).then_some(false), - TextureSwizzle::Green => (!present[1]).then_some(false), - TextureSwizzle::Blue => (!present[2]).then_some(false), - TextureSwizzle::Alpha => (!present[3]).then_some(true), - }; - if let Some(one) = constant { - word |= 1 << lane; - if one { - word |= 1 << (CONSTANT_ONES + lane); - } - } - } - word -} - /// Whether every component of `m` is the identity swizzle (Vulkan's "identity mapping": each /// component `IDENTITY` or its own channel). pub(crate) fn is_identity(m: vk::ComponentMapping) -> bool { @@ -1007,16 +942,6 @@ pub fn compare_op(f: CompareFunction) -> vk::CompareOp { } } -/// `log2` of the degree a sampler of `desc` filters with: its `maxAnisotropy` rounded up to a power -/// of two, 0 for an isotropic one; a pixel-coordinate sampler is isotropic. The runtime hands the -/// descriptor Metal samples with (`maxAnisotropy` 32 for 17 to 31), whose degree is then 5. -pub(crate) fn anisotropy_degree(desc: &SamplerDescriptor) -> u32 { - if !desc.normalized_coordinates || desc.max_anisotropy <= 1 { - return 0; - } - desc.max_anisotropy.next_power_of_two().trailing_zeros() -} - /// Metal's discrete sampler state as one `u32` word: what a shader reads of a sampler it learns /// only at run time. Each field holds its `MTLSamplerDescriptor` value's raw Metal enumeration /// value, so `MTLSamplerDescriptor`'s defaults are the word 0. The bits: @@ -1348,55 +1273,6 @@ mod tests { Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).unwrap() } - /// What a plan reads of a bound sampler's shape to check its separate textures' views - /// (`vk_filtering`) is exactly what `vk_sampler` makes of the descriptor for the use: a linear - /// filter or mip mode (none for an integer texture) and the reduction, the weighted average - /// whatever the descriptor's, with or without a comparison. - #[test] - fn the_shape_states_the_filtering_vk_sampler_makes() { - use SamplerMinMagFilter as F; - let dev = device(&[], &[VkFeature::SamplerFilterMinmax]); - let mut checked = 0; - for min in [F::Nearest, F::Linear] { - for mag in [F::Nearest, F::Linear] { - for mip in [ - SamplerMipFilter::NotMipmapped, - SamplerMipFilter::Nearest, - SamplerMipFilter::Linear, - ] { - for reduction in [ - SamplerReductionMode::WeightedAverage, - SamplerReductionMode::Minimum, - SamplerReductionMode::Maximum, - ] { - for (compare, integer) in - [(false, false), (true, false), (false, true), (true, true)] - { - let mut d = metal_default(); - d.min_filter = min; - d.mag_filter = mag; - d.mip_filter = mip; - d.reduction_mode = reduction; - let use_ = SamplerUse::new(compare, integer); - let s = vk_sampler(&d, use_, dev.profile()).expect("a sampler"); - assert_eq!(s.reduction, vk::SamplerReductionMode::WEIGHTED_AVERAGE); - let linear = s.mag_filter == vk::Filter::LINEAR - || s.min_filter == vk::Filter::LINEAR - || s.mipmap_mode == vk::SamplerMipmapMode::LINEAR; - assert_eq!( - vk_filtering(&d.shape(), use_), - (linear, s.reduction), - "{d:?} {use_:?}" - ); - checked += 1; - } - } - } - } - } - assert_eq!(checked, 12 * 3 * 4); - } - #[test] fn defaults_map_to_a_base_level_sampler() { let dev = device(&[], &[]); @@ -1409,16 +1285,14 @@ mod tests { assert_eq!(s.reduction, vk::SamplerReductionMode::WEIGHTED_AVERAGE); } - /// A descriptor's LOD bias makes, on every committed device and for every use, the binding - /// shape its zero bias makes, and the Vulkan sampler its zero bias makes but for its - /// `mipLodBias`: without `SamplerUse::lod_bias` (an Apple GPU of the families the runtime + /// A descriptor's LOD bias makes, on every committed device and for every use, the Vulkan + /// sampler its zero bias makes but for its `mipLodBias`: without `SamplerUse::lod_bias` (an Apple GPU of the families the runtime /// claims, which samples every level as with no bias) 0; with it (a Mac with an Intel or AMD /// GPU) `device_lod_bias`'s, the bias within the device's `maxSamplerLodBias` and none through /// a portability subset that withholds `samplerMipLodBias`, and 0 for a use of texel /// coordinates. Refused nowhere: past the limit, NaN or infinite, and withheld. #[test] fn a_lod_bias_is_the_device_s_where_the_use_adds_it() { - use crate::bind::state::BoundSampler; use SamplerMinMagFilter::{Linear, Nearest}; let biases = [ 1.0, @@ -1473,7 +1347,6 @@ mod tests { descs.push((pixel, SamplerUse::default().with_unnormalized(true))); for (unbiased, plain) in descs { let want = vk_sampler(&unbiased, plain, p); - let shape = BoundSampler::new(unbiased).shape(); for bias in biases { let mut d = unbiased; d.lod_bias = bias; @@ -1495,7 +1368,6 @@ mod tests { assert_eq!(got, want, "{stem}: bias {bias}, {d:?} {use_:?}"); checked += 1; } - assert_eq!(BoundSampler::new(d).shape(), shape, "{stem}: bias {bias}"); past_limit += usize::from(bias.abs() > limit); } } @@ -1895,64 +1767,6 @@ mod tests { assert_eq!(s.border_color, vk::BorderColor::FLOAT_TRANSPARENT_BLACK); } - /// Mirror-clamp needs its feature; anisotropy needs its own only through an argument buffer - /// (`check_argument_sampler`), the Vulkan sampler isotropic without it; a min or max - /// reduction needs none and reads the weighted average, with or without a comparison. - #[test] - fn optional_sampler_features_are_required_or_refused() { - let none = device( - &[], - &[ - VkFeature::SamplerMirrorClampToEdge, - VkFeature::SamplerFilterMinmax, - VkFeature::SamplerAnisotropy, - ], - ); - let all = device( - &[ - VkFeature::SamplerMirrorClampToEdge, - VkFeature::SamplerFilterMinmax, - VkFeature::SamplerAnisotropy, - ], - &[], - ); - let mut mirror = metal_default(); - mirror.r_address_mode = SamplerAddressMode::MirrorClampToEdge; - let mut minmax = metal_default(); - minmax.reduction_mode = SamplerReductionMode::Maximum; - // Linear filters: off Metal's sampler a nearest one is handed no anisotropy. - let mut aniso = metal_default(); - aniso.min_filter = SamplerMinMagFilter::Linear; - aniso.mag_filter = SamplerMinMagFilter::Linear; - aniso.max_anisotropy = 32; - let feature = |err: Error| { - let Error::Unsupported(u) = err else { - panic!("{err:?}") - }; - u.needs - }; - let needs = |f| crate::error::Needs::AnyOf(vec![vec![Capability::Feature(f)]]); - let err = vk_sampler(&mirror, SamplerUse::default(), none.profile()).unwrap_err(); - assert_eq!(feature(err), needs(VkFeature::SamplerMirrorClampToEdge)); - assert!(vk_sampler(&mirror, SamplerUse::default(), all.profile()).is_ok()); - let s = vk_sampler(&aniso, SamplerUse::default(), none.profile()).unwrap(); - assert_eq!(s.max_anisotropy, None, "isotropic without the feature"); - let s = vk_sampler(&aniso, SamplerUse::default(), all.profile()).unwrap(); - assert_eq!(s.max_anisotropy, Some(16.0), "clamped to the device limit"); - // An argument buffer's sampler needs the feature. - let shape = aniso.shape(); - let err = check_argument_sampler(&shape, SamplerUse::default(), none.profile()); - assert_eq!( - feature(err.unwrap_err()), - needs(VkFeature::SamplerAnisotropy) - ); - assert!(check_argument_sampler(&shape, SamplerUse::default(), all.profile()).is_ok()); - for (p, compare) in [(&none, false), (&none, true), (&all, false), (&all, true)] { - let s = vk_sampler(&minmax, SamplerUse::new(compare, false), p.profile()).unwrap(); - assert_eq!(s.reduction, vk::SamplerReductionMode::WEIGHTED_AVERAGE); - } - } - /// An opaque-black border through a non-identity view mapping, the texture's swizzle composed /// on the format's, needs the device to swizzle borders; a view whose /// border texel is not Metal's (`A8Unorm` through `A8_UNORM`) refuses; other borders, identity mappings, and samplers diff --git a/crates/metal2vulkan/src/metal/texel_format.rs b/crates/metal2vulkan/src/metal/texel_format.rs index c718865c1..c616b3704 100644 --- a/crates/metal2vulkan/src/metal/texel_format.rs +++ b/crates/metal2vulkan/src/metal/texel_format.rs @@ -67,7 +67,7 @@ //! 2D sample, and in 3D the half-float residue (about 0.3% of channels half a `half` ulp off). //! Its class is the half-float family. //! - **A cube's linear sample** of a packed format is not measured. A packed normalized format's -//! ([`TexelFormat::packed_exact`]) keeps the device's filter: its made-up corner texel lies off +//! (a [`BicubicTexels::EXACT`] class with a `PACKED` field) keeps the device's filter: its made-up corner texel lies off //! the code scale its sum recovers the codes on. A small float's takes the half-float family's //! emulation, an inference from its parts, each measured on the small floats: the face //! position (format-independent), the 2D sum above, and the corner tap, the `x` face's texel @@ -118,7 +118,7 @@ //! codes (`bind::AstcDecode`, `bind::PvrtcDecode`, `bind::EtcDecode`), its own decode again. //! //! A device that cannot sample an 8-bit sRGB format holds a sampled texture of it as the format's -//! UNORM twin (`metal::format::srgb_raw_twin`, [`srgb_twin_on`]: `R8Unorm_sRGB` and +//! UNORM twin (`metal::format::srgb_raw_twin`: `R8Unorm_sRGB` and //! `RG8Unorm_sRGB` on lavapipe, `RG8Unorm_sRGB` on ANV and NVIDIA among the committed profiles), //! whose views read the codes as `c / 255`. Having no sRGB decode there, the slot's //! `RuntimeFact::SrgbTexture` variant decodes what the view reads (one texel's codes, or the @@ -194,13 +194,6 @@ impl TexelFormat { pub fn has_channels(self) -> bool { self.0 >> BicubicTexels::PRESENT & 0xF != 0 } - - /// Whether the class sums its channels on its [`PACKED`](Self::PACKED) field's grids - /// ([`PackedTexels::filter_grids`]): a packed normalized format's [`BicubicTexels::EXACT`] - /// class (module docs). - pub fn packed_exact(self) -> bool { - self.0 & BicubicTexels::EXACT != 0 && self.0 & TexelFormat::PACKED_MASK != 0 - } } /// How Metal's cube gather reads the tap past both edges of a face of a format outside the @@ -320,8 +313,7 @@ pub enum PackedTexels { /// small float's is, so the field has no code scales. Metal's linear filter sums the steps on /// that grid, each 2D term `k · w` truncated by `2^7` (an Apple M3 Max on macOS 26.7 and an /// Apple M4 on macOS 27.0.1, byte-identical, every channel of `YCBCR8_420_2P`; every 8- and - /// 10-bit format, packed or not, at each subsampling and range; - /// [`filter_truncation`](Self::filter_truncation)). + /// 10-bit format, packed or not, at each subsampling and range). YCbCr2048 = 7, /// The `_sRGB` twins' and the unpacked 12-bit YCbCr formats' channels as their view holds them: /// steps `k / 8192` of `[0, 1]`, alpha 1, which Metal's linear filter sums as @@ -344,20 +336,6 @@ pub enum PackedTexels { } impl PackedTexels { - /// Every value, in field order. - pub const ALL: [PackedTexels; 10] = [ - PackedTexels::Rgb565, - PackedTexels::Rgb5A1, - PackedTexels::Rgba4, - PackedTexels::Rgb10A2, - PackedTexels::SmallFloat, - PackedTexels::Argb8, - PackedTexels::YCbCr2048, - PackedTexels::YCbCr8192, - PackedTexels::YCbCrExtended8192, - PackedTexels::Rgb10A2Srgb, - ]; - /// The packed channels of `pf`, where Metal's reads of them are measured, a two-plane YCbCr /// format's by its layout ([`of_ycbcr`](Self::of_ycbcr)). pub fn of(pf: PixelFormat) -> Option { @@ -403,24 +381,6 @@ impl PackedTexels { }) } - /// Each channel's code scale `2^b - 1`, red to alpha (an absent alpha's 1, which its value - /// 1 recovers), or `None` where the device's value is Metal's exactly: the small floats, the - /// YCbCr fields and `RGB10A2Unorm_sRGB`'s, whose function decodes Metal's values itself. - pub fn scales(self) -> Option<[u32; 4]> { - Some(match self { - PackedTexels::Rgb565 => [31, 63, 31, 1], - PackedTexels::Rgb5A1 => [31, 31, 31, 1], - PackedTexels::Rgba4 => [15; 4], - PackedTexels::Rgb10A2 => [1023, 1023, 1023, 3], - PackedTexels::Argb8 => [255; 4], - PackedTexels::SmallFloat - | PackedTexels::YCbCr2048 - | PackedTexels::YCbCr8192 - | PackedTexels::YCbCrExtended8192 - | PackedTexels::Rgb10A2Srgb => return None, - }) - } - /// This field in place. pub fn class(self) -> TexelFormat { TexelFormat((self as u32) << TexelFormat::PACKED) @@ -431,7 +391,7 @@ impl PackedTexels { /// 10, or 12 bits, `16 · 255` for a channel of 1, 2, or 4 bits, `4 · 1023` for one of 5 or 10, /// `4095` for one of 6; the YCbCr fields' `2048` or `8192`, on which their steps are their /// codes (`S = D` below). Each - /// is a multiple of the channel's code scale ([`scales`](Self::scales)), so a code `c` lies on + /// is a multiple of the channel's code scale, so a code `c` lies on /// it at `c · D / S`. `None` for the small floats, whose sum is a half-float format's, and for /// `ARGB8Unorm`, whose filter is not measured. pub fn filter_grids(self) -> Option<[u32; 4]> { @@ -448,41 +408,6 @@ impl PackedTexels { }) } - /// The bits `s` Metal's 2D and 3D linear sums drop from each term where - /// [`filter_grids`](Self::filter_grids) names the grids: the term of a code `c` on its grid - /// under the weight `w` (in units of `2^-16`) is `⌊c · w / 2^s⌋`, and the sum's grid step - /// `⌊(T + 2^(15 - s)) / 2^(16 - s)⌋` (module docs). 4 for a packed normalized format's 12-bit - /// grids, as for an 8-bit format's, and 7 for the YCbCr fields', measured on their 2D samples; - /// `RGB10A2Unorm_sRGB`'s 7 for its color channels and 4 for alpha. Red to alpha. - pub fn filter_truncation(self) -> Option<[u32; 4]> { - self.filter_grids().map(|_| match self { - PackedTexels::Rgb10A2Srgb => [7, 7, 7, 4], - _ if self.ycbcr() => [7; 4], - _ => [4; 4], - }) - } - - /// Whether a `half` result of the field's one texel or linear filter rounds with ties away - /// from zero: the two-plane YCbCr fields' ([`ycbcr`](Self::ycbcr)) and - /// `RGB10A2Unorm_sRGB`'s, whose color steps lie on the grid `8192` (its alpha's values are - /// never a tie). - pub fn ties_away(self) -> bool { - self.ycbcr() || self == PackedTexels::Rgb10A2Srgb - } - - /// Whether the field is a two-plane YCbCr format's: its view holds Metal's reads exactly, and a - /// `half` result of its linear filter is the step's value rounded with ties away from zero (on - /// the grid `8192`, where a step's value may lie between two halves; the grid `2048`'s are - /// halves), as is a `half` read or nearest sample of one texel (every channel of - /// `YCBCR8_420_2P_sRGB`, `YCBCR10_420_2P_sRGB` and three 12-bit and - /// extended-range formats on the grid `8192`). - pub fn ycbcr(self) -> bool { - matches!( - self, - PackedTexels::YCbCr2048 | PackedTexels::YCbCr8192 | PackedTexels::YCbCrExtended8192 - ) - } - /// Whether the filter's codes and steps are signed and reach `±2D` /// ([`YCbCrExtended8192`](Self::YCbCrExtended8192)): each step divided by `2D` and doubled, /// exactly. @@ -697,7 +622,7 @@ pub fn heap_numeric_base() -> u32 { /// Whether Metal's read of a texture of `pf` in another numeric class than its format's is /// measured: a color format of the float, signed or unsigned integer class, not a depth, stencil, /// extended-range (bfloat included) or two-plane YCbCr one. A slot of another class takes such a -/// texture under its cross-class variant (`bind::plan::resources::cross_class`), and a heap group's +/// texture under its cross-class variant, and a heap group's /// read of another class reads it in its own class ([`heap_numeric`]). pub fn crosses_classes(pf: PixelFormat) -> bool { use crate::metal::format::{is_depth_stencil, sampled_type, ycbcr_format, ExtendedRange}; @@ -731,23 +656,6 @@ pub fn heap_alpha_in_red_index() -> u32 { heap_class_index(PixelFormat::A8Unorm, TextureSwizzleChannels::DEFAULT) } -/// Whether a texture of pixel format `pf` holds 16-bit float channels of its own: its class is -/// the half-float family's without a packed field. -pub fn half_channels(pf: PixelFormat) -> bool { - use crate::metal::bicubic::BicubicTexels; - texel_format(pf).0 & (BicubicTexels::HALF | TexelFormat::PACKED_MASK) == BicubicTexels::HALF -} - -/// Whether Metal's `textureWriteRoundingMode` 2 stores a fragment function's write to a texture of -/// `pf` otherwise than its default, where the translation builds only the default's rule -/// (`RuntimeFact::StorageTextureWriteRounding`, `RuntimeFact::HeapWriteRounding`): an -/// `RG11B10Float` or `RGB9E5Float` texture's, and where `halves` (a `float` texel) a half-float -/// one's ([`half_channels`]). -pub fn mode_two_rounds(pf: PixelFormat, halves: bool) -> bool { - matches!(pf, PixelFormat::RG11B10Float | PixelFormat::RGB9E5Float) - || (halves && half_channels(pf)) -} - /// The index among the heap's classes of the class a heap texture of pixel format `pf` made with /// `swizzle` carries ([`heap_class`]); for an unswizzled texture of a form of /// `ExtendedRange::HEAP_READ`, that form's index past [`heap_extended_base`]; for an integer color @@ -814,17 +722,6 @@ pub fn srgb_coded(pf: PixelFormat) -> bool { ) } -/// Whether `profile`'s device holds a sampled texture of `pf` as its 8-bit sRGB format's UNORM twin -/// (`metal::format::srgb_raw_twin`): it samples no format of `pf`'s and samples the twin's, whose -/// views read the codes, so a function decodes them itself (module docs). The runtime's image plan -/// holds the twin by the same format features. -pub fn srgb_twin_on(pf: PixelFormat, profile: &crate::device::profile::DeviceProfile) -> bool { - use crate::device::requirements::FormatUsage; - let usages = [FormatUsage::SampledImage].into(); - let samples = |pf| crate::metal::format::vk_format(pf, &usages, profile).is_ok(); - !samples(pf) && crate::metal::format::srgb_raw_twin(pf).is_some_and(samples) -} - #[cfg(test)] mod tests { use super::*; @@ -966,8 +863,7 @@ mod tests { /// A format of a measured cube corner outside the families is its corner's field alone (no /// family, channel, or border bit, so every other access reads it as `OTHER`), but for a - /// packed format's family and field beside it; each field fits its four bits, and each grid - /// suits `texel_round::grid_value` (`1 <= D < 2^16`). + /// packed format's family and field beside it. #[test] fn a_cube_corner_alone_is_its_field() { let mut seen = std::collections::BTreeSet::new(); @@ -1014,162 +910,6 @@ mod tests { } } - /// Each packed format takes its field beside its corner, and nothing else does: the field fits - /// its four bits, each value has a format, each code scale suits `texel_round::grid_value` (`1 - /// <= S < 2^16`), and the field touches no other field's bit. `ARGB8Unorm`'s cube gathers and - /// linear filter are not measured: its field stands alone, as the linear PVRTC formats' does; - /// BC1 to BC3's unorm forms and the 8-bit linear ETC2 and EAC formats take it beside their - /// corner. No cube gather of a two-plane YCbCr format is measured: its field has - /// no corner. A packed normalized format's class is its normalized family's with `EXACT`, a - /// small float's the half-float family's, each with its channels and border texels, and a - /// two-plane format's the normalized family's with `EXACT` (signed where its field's steps are) - /// and its format's channels. A field with grids states its sums' truncation, and only it. - #[test] - fn a_packed_format_takes_its_field_beside_its_corner() { - let mut seen = std::collections::BTreeSet::new(); - for &pf in PixelFormat::ALL { - let class = texel_format(pf); - let field = class.0 & TexelFormat::PACKED_MASK; - match PackedTexels::of(pf) { - Some(p) => { - assert_eq!(field, p.class().0, "{pf:?}"); - let two_plane = crate::metal::format::ycbcr_format(pf).is_some(); - let blocks = matches!( - pf, - PixelFormat::BC1RGBA - | PixelFormat::BC2RGBA - | PixelFormat::BC3RGBA - | PixelFormat::ETC2RGB8 - | PixelFormat::ETC2RGB8A1 - | PixelFormat::EACRGBA8 - ); - assert_eq!( - CubeCorner::of(pf).is_some(), - (p != PackedTexels::Argb8 || blocks) && !two_plane, - "{pf:?}" - ); - assert_eq!(p.ycbcr(), two_plane && p != PackedTexels::Rgb10A2, "{pf:?}"); - let family = class.0 & !(TexelFormat::PACKED_MASK | CORNER_MASK); - let want = match p { - PackedTexels::SmallFloat => T::HALF, - PackedTexels::Argb8 => 0, - _ if p.filter_extended() => T::SNORM | T::EXACT, - _ => T::UNORM | T::EXACT, - }; - assert_eq!(family & !(0xF << T::PRESENT | 0xfff << T::BORDER), want); - // A two-plane format's channels are its format's, which the bicubic filter's - // treatment does not state: red, green and blue, alpha reading 1 at the border. - let t = match two_plane { - true => { - assert!(texels(pf).is_none(), "{pf:?}"); - T(0b0111 << T::PRESENT) - .with_border(pf, TextureSwizzleChannels::DEFAULT) - .0 - } - false => texels(pf).map_or(0, |t| t.0), - }; - assert_eq!(family, t | want, "{pf:?}"); - assert_eq!(class.packed_exact(), p.filter_grids().is_some(), "{pf:?}"); - seen.insert(p as u32); - } - None => { - assert_eq!(field, 0, "{pf:?}"); - assert!(!class.packed_exact(), "{pf:?}"); - } - } - } - // The two-plane YCbCr formats by the grid of Metal's reads: 9 on - // `1/2048`, 12 on `1/8192`, 9 on the signed `1/8192`, 6 of 10-bit codes; the 3 of 8-bit - // codes `RGBA8Unorm`'s family without a field; the 30 others (PQ, HLG, packed 12 bits) no - // class. - use crate::metal::format::YCbCrReads; - let mut by = std::collections::BTreeMap::new(); - for &pf in PixelFormat::ALL { - let Some(y) = crate::metal::format::ycbcr_format(pf) else { - continue; - }; - let class = texel_format(pf); - let key = match PackedTexels::of(pf) { - Some(p) => format!("{p:?}"), - None if class.0 == 0 => "other".to_owned(), - None => { - let rgb = T(T::UNORM | T::EXACT | 0b0111 << T::PRESENT) - .with_border(pf, TextureSwizzleChannels::DEFAULT); - assert_eq!(class.0, rgb.0, "{pf:?}"); - assert_eq!((y.bits, y.reads), (8, YCbCrReads::Codes), "{pf:?}"); - "codes8".to_owned() - } - }; - *by.entry(key).or_insert(0) += 1; - } - let want = [ - ("Rgb10A2", 6), - ("YCbCr2048", 9), - ("YCbCr8192", 12), - ("YCbCrExtended8192", 9), - ("codes8", 3), - ("other", 30), - ]; - assert_eq!( - by, - want.map(|(k, n)| (k.to_owned(), n)).into_iter().collect() - ); - for (pf, p) in [ - ( - PixelFormat::YCBCR104442PPACKED, - Some(PackedTexels::YCbCr2048), - ), - ( - PixelFormat::YCBCR104202PPACKEDSRGB, - Some(PackedTexels::YCbCr8192), - ), - (PixelFormat::YCBCR124222P, Some(PackedTexels::YCbCr8192)), - ( - PixelFormat::YCBCR104202PPACKEDXR, - Some(PackedTexels::YCbCrExtended8192), - ), - ( - PixelFormat::YCBCR124442PXR, - Some(PackedTexels::YCbCrExtended8192), - ), - (PixelFormat::YCBCR124202PPACKED, None), - (PixelFormat::YCBCR124202PPACKEDXR, None), - (PixelFormat::YCBCR104202PPQ, None), - (PixelFormat::YCBCR124442PHLG, None), - (PixelFormat::RGB104202PPACKED, Some(PackedTexels::Rgb10A2)), - ] { - assert_eq!(PackedTexels::of(pf), p, "{pf:?}"); - } - for (k, p) in PackedTexels::ALL.into_iter().enumerate() { - assert_eq!(p as u32, k as u32 + 1); - assert_eq!(p.class().0 & !TexelFormat::PACKED_MASK, 0); - for s in p.scales().into_iter().flatten() { - assert!((1..1 << 16).contains(&s), "{p:?}"); - } - // Each filter grid lies on its channel's code scale, below `2^12`. - if let (Some(s), Some(g)) = (p.scales(), p.filter_grids()) { - for (s, g) in s.into_iter().zip(g) { - assert_eq!(g % s, 0, "{p:?}"); - assert!(g < 1 << 12, "{p:?}"); - } - } - assert_eq!( - p.filter_truncation().is_some(), - p.filter_grids().is_some(), - "{p:?}" - ); - // `RGB10A2Unorm_sRGB`'s field is its extended-range form's class's - // (`lower::sampler::extended`), which no format's own class takes. - let extended = p == PackedTexels::Rgb10A2Srgb; - assert!( - seen.contains(&(p as u32)) || extended, - "{p:?} has no format" - ); - } - assert_eq!(TexelFormat::PACKED_MASK & CORNER_MASK, 0); - assert_eq!(TexelFormat::PACKED_MASK & 0xff_ffff, 0); - } - /// The heap classes are few enough for a handle-table entry's class field, `OTHER` first; each /// unswizzled format's index names its slot class with its border texels, and a swizzled /// texture's names `OTHER`. An unswizzled texture of a form a heap reads names that form past diff --git a/crates/metal2vulkan/src/metal/vertex.rs b/crates/metal2vulkan/src/metal/vertex.rs index 1bfbfcd81..facb0bde8 100644 --- a/crates/metal2vulkan/src/metal/vertex.rs +++ b/crates/metal2vulkan/src/metal/vertex.rs @@ -118,15 +118,6 @@ pub(crate) fn vk_scaled_vertex_format(format: VertexFormat) -> Option Option { - let f = vk_vertex_format(format).ok()?; - f.block().map(|b| b.size) -} - /// The alignment in bytes Vulkan's fixed-function vertex input requires of an attribute's address /// in `format` ("Vertex Input Address Calculation", `VUID-vkCmdDraw-format-10389`/`-10390`): the /// [`vk::FormatBlock::vertex_alignment`] of its Vulkan format, the component size or the whole diff --git a/crates/metal2vulkan/src/pipeline/api_tests.rs b/crates/metal2vulkan/src/pipeline/api_tests.rs index aa470f002..6e95c92ef 100644 --- a/crates/metal2vulkan/src/pipeline/api_tests.rs +++ b/crates/metal2vulkan/src/pipeline/api_tests.rs @@ -89,7 +89,7 @@ fn a_stage_s_notes_under_a_specialization_are_its_held_clauses() { precision_notes: vec![ PrecisionNote::GradFromBias, PrecisionNote::PixelSamplerScaling, - PrecisionNote::HalfSampleFilter, + PrecisionNote::SrgbTexelDecode, ], strategies: StrategyCensus::default(), constant_blob: None, @@ -110,7 +110,7 @@ fn a_stage_s_notes_under_a_specialization_are_its_held_clauses() { ], }, SpecializedNote { - note: PrecisionNote::HalfSampleFilter, + note: PrecisionNote::SrgbTexelDecode, when: vec![SpecClause { all: vec![SpecTest::equal(texel, 0x109, 0)], }], @@ -130,9 +130,9 @@ fn a_stage_s_notes_under_a_specialization_are_its_held_clauses() { } k }; - use PrecisionNote::{GradFromBias as G, HalfSampleFilter as H, PixelSamplerScaling as P}; + use PrecisionNote::{GradFromBias as G, PixelSamplerScaling as P, SrgbTexelDecode as H}; for (values, want) in [ - // Every default: the class 0 takes the filter note, the word 0 no scaling. + // Every default: the class 0 takes the sRGB note, the word 0 no scaling. (vec![], vec![G, H]), (vec![(3, 0x100)], vec![G]), (vec![(3, 0x100), (4, 1)], vec![G, P]), @@ -170,22 +170,6 @@ mod serde_round_trips { assert_eq!(&back, value, "{json}"); } - /// A planes image's conversion: an 8-bit 4:2:0 surface's, full range, BT.709. - fn planes_sampler() -> crate::bind::YCbCrPlanesSampler { - use crate::bind::{YCbCrCodes, YCbCrInPlace, YCbCrMatrix, YCbCrPlanes, YCbCrRange}; - let codes = metal::format::ycbcr_format(metal::PixelFormat::YCBCR84202P) - .and_then(YCbCrCodes::of) - .expect("codes"); - let planes = YCbCrPlanes::new( - [8, 4], - [0, 16], - [64, 16], - (YCbCrRange::Full, YCbCrMatrix::Bt709), - codes, - ); - YCbCrInPlace::of(&planes).expect("in place").sampler() - } - fn buffer(index: u32) -> SlotRef { slot(Stage::Fragment, SlotClass::Buffer, index) } @@ -216,12 +200,6 @@ mod serde_round_trips { one_row: true, unit_axes: 6, srgb_textures: BTreeSet::from([slot(Stage::Kernel, SlotClass::Texture, 4)]), - ycbcr_in_place: BTreeSet::from([slot(Stage::Kernel, SlotClass::Texture, 7)]), - ycbcr_planes_sampled: BTreeMap::from([( - slot(Stage::Kernel, SlotClass::Texture, 7), - planes_sampler(), - )]), - texel_rows: BTreeSet::from([slot(Stage::Kernel, SlotClass::Texture, 9)]), texel_buffer_parts: BTreeMap::from([(slot(Stage::Kernel, SlotClass::Texture, 11), 2)]), flat_grid: true, call_threadgroups: true, @@ -314,12 +292,6 @@ mod serde_round_trips { replay_bindings: true, merged_draws: true, srgb_textures: BTreeSet::from([slot(Stage::Fragment, SlotClass::Texture, 7)]), - ycbcr_in_place: BTreeSet::from([slot(Stage::Fragment, SlotClass::Texture, 9)]), - ycbcr_planes_sampled: BTreeMap::from([( - slot(Stage::Fragment, SlotClass::Texture, 9), - planes_sampler(), - )]), - texel_rows: BTreeSet::from([slot(Stage::Fragment, SlotClass::Texture, 10)]), texel_buffer_parts: BTreeMap::from([( slot(Stage::Fragment, SlotClass::Texture, 11), 4, @@ -773,457 +745,4 @@ fn descriptor_and_library_serde_round_trips() { } #[cfg(feature = "serde")] -mod bind_serde_round_trips { - use std::collections::{BTreeMap, BTreeSet}; - - use super::*; - use crate::bind::*; - use crate::cache::SpecializationKey; - use crate::metal; - use crate::pipeline::sym::{PushField, SampledType}; - - fn round_trip(value: &T) - where - T: serde::Serialize + serde::de::DeserializeOwned + PartialEq + std::fmt::Debug, - { - let json = serde_json::to_string(value).expect("serializes"); - let back: T = serde_json::from_str(&json).expect("deserializes"); - assert_eq!(&back, value, "{json}"); - } - - #[test] - fn bind_state_and_shape() { - let mut table = StageTable::default(); - table.buffers.insert( - 0, - BoundBuffer::Buffer { - length: 4096, - offset: 256, - gpu_address: 0x1_0000_0000, - device_address: Some(0xdead_0000), - attribute_stride: None, - }, - ); - table.buffers.insert( - 1, - BoundBuffer::Bytes { - len: 16, - attribute_stride: None, - }, - ); - table.textures.insert( - 3, - BoundTexture::Texture { - facts: TextureFacts::new( - metal::TextureType::Type2D, - metal::PixelFormat::RGBA8Unorm, - ), - resource_id: Some(9), - }, - ); - table.samplers.insert( - 0, - BoundSampler { - desc: SamplerDescriptor { - min_filter: metal::SamplerMinMagFilter::Linear, - mag_filter: metal::SamplerMinMagFilter::Nearest, - mip_filter: metal::SamplerMipFilter::Linear, - s_address_mode: metal::SamplerAddressMode::ClampToEdge, - t_address_mode: metal::SamplerAddressMode::ClampToEdge, - r_address_mode: metal::SamplerAddressMode::ClampToEdge, - border_color: metal::SamplerBorderColor::TransparentBlack, - normalized_coordinates: false, - lod_min_clamp: 0.0, - lod_max_clamp: 1000.0, - lod_average: false, - max_anisotropy: 1, - compare_function: metal::CompareFunction::Never, - reduction_mode: metal::SamplerReductionMode::WeightedAverage, - lod_bias: 1.5, - }, - resource_id: None, - }, - ); - table.threadgroup_lengths.insert(0, 1024); - let mut stages = BTreeMap::new(); - stages.insert(Stage::Kernel, table); - round_trip(&BindState { - stages, - used_resources: vec![UsedResource { - class: ResourceClass::Heap, - gpu_address: Some(0x2_0000_0000), - length: 1 << 20, - device_address: None, - usage: metal::ResourceUsage::READ, - stages: metal::RenderStages::empty(), - token: 7, - resource_id: None, - }], - used_in_token_order: true, - resident_apart: true, - vertex_amplification: VertexAmplification::new( - 2, - vec![ViewMapping { - viewport_array_index_offset: 0, - render_target_array_index_offset: 3, - }], - ), - imageblock_size: ImageblockSize::new(16, 8), - render_target_array_length: 6, - stage_in_region: Some(StageInRegion::new([1, 2, 3], [4, 5, 6])), - tessellation_factors: TessellationFactors::new( - Some(TessellationFactorBuffer::new(4096, 16, 64)), - 0.5, - ), - render_area: [40, 24], - argument_samplers: vec![ArgumentSampler::new( - SamplerDescriptor { - normalized_coordinates: false, - ..SamplerDescriptor::new() - }, - 0x5a17_0001, - )], - depth_stencil: metal::state::DepthStencilDescriptor { - front_face_stencil: metal::state::StencilDescriptor { - stencil_compare_function: metal::CompareFunction::LessEqual, - depth_stencil_pass_operation: metal::StencilOperation::IncrementWrap, - write_mask: 0x0F, - ..Default::default() - }, - depth_write_enabled: true, - ..Default::default() - }, - heap_placement: HeapPlacement::ResourceId, - viewport_count: 3, - function_tables: vec![crate::bind::ArgumentFunctionTable { - resource_id: 0x7ab1_0001, - size: 9, - address: 0, - }], - tile_threadgroup: tile_threadgroup(), - zeroed_colors: BTreeMap::from([(1, metal::PixelFormat::R32Uint)]), - dropped_colors: BTreeSet::from([4]), - kept_imageblock_bytes: Some(4), - depth_clamp_range: Some([0.25, 0.5]), - rotated_weights: true, - line_band: Some(( - crate::pipeline::BandPrimitive::Triangles, - [8.0, -8.0, 1.75, -1.0], - )), - resident_ranges: vec![crate::bind::ResidentRange { - host: 0x9_0000, - guest: 0x3_0000, - length: 100, - }], - blend_color: [0.25, -0.5, 1.5, 0.75], - alpha_test_reference: Some(0.375), - primitive_type: Some(metal::PrimitiveType::TriangleStrip), - primitive_id_indices: Some(metal::IndexType::UInt16), - quad_primitive_ids: true, - private_list: true, - far_vertex_buffers: BTreeSet::from([2]), - region_viewports: true, - }); - let mut shape = StageShape::default(); - shape.buffers.insert( - 0, - BufferShape::Buffer { - attribute_stride: Some(24), - device_address: false, - length_class: 20, - offset_alignment: 2, - }, - ); - shape.samplers.insert( - 0, - BoundSamplerShape { - shape: SamplerShape { - reduction: metal::SamplerReductionMode::Minimum, - compare: true, - anisotropic: true, - mirror_clamp_to_edge: false, - valid_lod_clamps: true, - opaque_black_border: true, - linear: true, - cubic: true, - }, - word: crate::metal::sampler::SamplerWord(0x0012_3456), - min_level: 160, - degree: 3, - }, - ); - let mut stages = BTreeMap::new(); - stages.insert(Stage::Fragment, shape); - round_trip(&BindShape { - stages, - used: BTreeMap::new(), - vertex_amplification: VertexAmplification::default(), - imageblock_size: ImageblockSize::new(32, 32), - render_target_array_length: 1, - tessellation_factor_buffer: true, - render_area: [1920, 1080], - argument_samplers: ArgumentSamplersShape::of(&[ArgumentSampler::new( - SamplerDescriptor::new(), - 3, - )]), - function_tables: crate::bind::FunctionTablesShape::of(&[ - crate::bind::ArgumentFunctionTable { - resource_id: 3, - size: 0, - address: 0, - }, - ]), - tile_threadgroup: tile_threadgroup(), - zeroed_colors: BTreeMap::from([(1, metal::PixelFormat::R32Uint)]), - dropped_colors: BTreeSet::from([4]), - kept_imageblock_bytes: Some(4), - depth_clamp_range: true, - rotated_weights: true, - line_band: Some(crate::pipeline::BandPrimitive::Lines), - primitive_id_indices: Some(metal::IndexType::UInt32), - quad_primitive_ids: true, - private_list: true, - far_vertex_buffers: BTreeSet::from([1, 30]), - region_viewports: true, - }); - } - - /// A tile threadgroup memory of 96 bytes with two arguments. - fn tile_threadgroup() -> crate::bind::TileThreadgroupMemory { - let mut memory = crate::bind::TileThreadgroupMemory { - length: 96, - arguments: BTreeMap::new(), - }; - for (index, length, offset) in [(0, 32, 0), (3, 64, 32)] { - memory.arguments.insert( - index, - crate::bind::TileThreadgroupArgument { length, offset }, - ); - } - memory - } - - #[test] - fn plans_and_commands() { - let slot = slot(Stage::Kernel, SlotClass::Buffer, 2); - let neutral = NeutralResource::Image { - view_type: vk::ImageViewType::TYPE_2D_ARRAY, - sampled_type: SampledType::Uint, - depth_compare: false, - samples: 1, - storage_format: Some(vk::Format::R32_UINT), - }; - round_trip(&BindingPlan { - variant: VariantKey::new(), - specialization: SpecializationKey::new(), - descriptors: vec![ - DescriptorWrite { - set: 0, - binding: 0, - array_element: 0, - ty: vk::DescriptorType::STORAGE_BUFFER, - source: WriteSource::Buffer { slot }, - }, - DescriptorWrite { - set: 0, - binding: 1, - array_element: 0, - ty: vk::DescriptorType::STORAGE_IMAGE, - source: WriteSource::Neutral(neutral), - }, - DescriptorWrite { - set: 1, - binding: 0, - array_element: 5, - ty: vk::DescriptorType::SAMPLER, - source: WriteSource::HeapEntry { - class: crate::pipeline::sym::HandleClass::Sampler { - compare: false, - integer: false, - }, - element: 5, - source: HeapSource::Used(3), - view: ImageViewDesc { - view_type: vk::ImageViewType::TYPE_2D, - format: vk::Format::R8G8B8A8_UNORM, - aspect: vk::ImageAspectFlags::COLOR, - layout: vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL, - components: vk::ComponentMapping::IDENTITY, - level: None, - shader_swizzle: false, - }, - }, - }, - ], - vertex_buffers: vec![VertexBufferBind { - binding: 0, - buffer_index: 30, - per_bind_stride: false, - }], - uses: vec![ResourceUse { - resource: UseTarget::Slot(slot), - access: AccessSet::WRITE, - class: AccessClass::Storage, - stages: vk::PipelineStageFlags2::COMPUTE_SHADER, - range: Some(ByteRange { offset: 0, len: 64 }), - }], - push: PushTemplate { - fields: vec![PushFieldPlacement { - stage: Stage::Kernel, - field: PushField::SlotBindOffset(slot), - location: FieldLocation::PushWindow { offset: 0 }, - size: 4, - }], - }, - diagnostics: vec![PlanDiagnostic::IncompatibleBinding { - slot: crate::pipeline::sym::SlotRef { - class: SlotClass::Texture, - ..slot - }, - substituted: neutral, - }], - compute: None, - graphics: None, - views: ViewSetup { - view_mask: 0b11, - base_layer: 4, - }, - }); - round_trip(&DispatchCommands { - regions: vec![DispatchRegion { - specialization: SpecializationKey::new(), - group_count: [4, 1, 1], - push_constants: vec![PushConstantWrite { - stages: vk::ShaderStageFlags::COMPUTE, - offset: 0, - bytes: vec![1, 2, 3, 4], - }], - indirect: None, - stage_flags: vk::PipelineShaderStageCreateFlags::empty(), - required_subgroup_size: Some(32), - }], - descriptor_bytes: vec![DescriptorBytes { - set: 0, - binding: 3, - bytes: vec![0; 8], - }], - extents: vec![BufferExtent { - slot, - window: Window::Whole, - }], - descriptor_ranges: Vec::new(), - push_holes: vec![PushHole::RootTableAddress { - stages: vk::ShaderStageFlags::COMPUTE, - offset: 8, - }], - region_record: Some([7; 32]), - root_table: None, - uses: vec![ResourceUse { - resource: UseTarget::Indirect, - access: AccessSet::READ, - class: AccessClass::Indirect, - stages: vk::PipelineStageFlags2::DRAW_INDIRECT, - range: Some(ByteRange { offset: 0, len: 12 }), - }], - }); - round_trip(&Dispatch::ThreadgroupsIndirect { - indirect: IndirectRef { - token: 2, - offset: 0, - }, - threads_per_group: [32, 1, 1], - }); - round_trip(&DrawCall::Indirect { - indirect: IndirectRef { - token: 4, - offset: 0, - }, - indexed: Some((vk::IndexType::UINT16, IndexBufferRef::new(5, 256), 64)), - }); - round_trip(&DrawCall::Patches { - control_points: 4, - patch_start: 2, - patch_count: 9, - patch_index: None, - instance_count: 3, - base_instance: 1, - control_point_index: Some((IndexBufferRef::new(7, 96), 2)), - }); - round_trip(&DrawCall::PatchesIndirect { - control_points: 3, - patch_index: Some((IndexBufferRef::new(6, 64), 8)), - indirect: IndirectRef { - token: 4, - offset: 16, - }, - control_point_index: None, - }); - round_trip(&WriteSource::TessellationFactors); - round_trip(&UseTarget::TessellationFactors); - round_trip(&WriteSource::PatchIndices { min_bytes: 16 }); - round_trip(&WriteSource::TileMemory { bytes: 480 }); - round_trip(&UseTarget::PatchIndices); - round_trip(&WriteSource::ControlPointIndices); - round_trip(&UseTarget::ControlPointIndices); - round_trip(&DrawCommands { - push_constants: Vec::new(), - descriptor_bytes: Vec::new(), - buffer_offsets: vec![(0, 256)], - draw: vk::DrawCommand::DrawIndexed { - index_type: vk::IndexType::UINT32, - index_buffer_offset: 0, - index_count: 36, - instance_count: 1, - first_index: 0, - vertex_offset: -4, - first_instance: 0, - }, - indirect_needs_arguments: false, - mesh_arguments: None, - object_fold: None, - discards_command_buffer: false, - extents: Vec::new(), - push_holes: Vec::new(), - descriptor_ranges: Vec::new(), - root_tables: Vec::new(), - vertex_strides: vec![(0, 32)], - uses: vec![ResourceUse { - resource: UseTarget::IndexBuffer, - access: AccessSet::READ, - class: AccessClass::Index, - stages: vk::PipelineStageFlags2::INDEX_INPUT, - range: Some(ByteRange { - offset: 0, - len: 144, - }), - }], - index_overrun: Some(IndexOverrun::Clamped { past_end: 4 }), - amplifications: vec![ - Vec::new(), - vec![PushConstantWrite { - stages: vk::ShaderStageFlags::VERTEX, - offset: 16, - bytes: 1u32.to_le_bytes().to_vec(), - }], - ], - specialization: None, - }); - // A mesh draw's commands. - round_trip(&vk::DrawCommand::DrawMeshTasks { - group_count_x: 2, - group_count_y: 1, - group_count_z: 1, - }); - round_trip(&vk::DrawCommand::DrawMeshTasksIndirect { - offset: 12, - draw_count: 1, - stride: 12, - }); - round_trip(&vk::DrawCommand::DrawMeshTasksIndirectCount { - offset: 36, - count_offset: 32, - max_draw_count: 128, - stride: 12, - }); - } -} +mod bind_serde_round_trips {} diff --git a/crates/metal2vulkan/src/pipeline/artifact.rs b/crates/metal2vulkan/src/pipeline/artifact.rs index 187eea609..66e8a988b 100644 --- a/crates/metal2vulkan/src/pipeline/artifact.rs +++ b/crates/metal2vulkan/src/pipeline/artifact.rs @@ -141,19 +141,14 @@ pub struct StageModule { pub entry_point: String, /// SPIR-V 1.5 words, relocated for this pipeline. pub spirv: Arc<[u32]>, - /// The specialization constants with their defaults. A kernel's defaults are placeholders the - /// binder replaces (a local size of 1): create each compute `VkPipeline` from a planned - /// dispatch's [`DispatchRegion`](crate::bind::DispatchRegion), its `specialization`, - /// `stage_flags`, and `required_subgroup_size`, never from this stage's defaults. + /// The specialization constants with their defaults. A kernel's defaults are placeholders (a + /// local size of 1): create each compute `VkPipeline` with the values its dispatch gives + /// the constants' keys, never from this stage's defaults. pub specialization: SpecializationLayout, - /// `VkPipelineShaderStageRequiredSubgroupSizeCreateInfo`, when the tier pins a size. For a - /// kernel, each [`DispatchRegion`](crate::bind::DispatchRegion) carries the value to create its - /// pipeline with. + /// `VkPipelineShaderStageRequiredSubgroupSizeCreateInfo`, when the tier pins a size. pub required_subgroup_size: Option, - /// Stage create flags (`REQUIRE_FULL_SUBGROUPS`). For a kernel, each - /// [`DispatchRegion`](crate::bind::DispatchRegion) carries the flags to create its pipeline - /// with: a region that is not whole subgroups runs on a variant without them. These flags at - /// the default specialization's local size of 1 are invalid usage + /// Stage create flags (`REQUIRE_FULL_SUBGROUPS`). These flags at the default specialization's + /// local size of 1 are invalid usage /// (`VUID-VkPipelineShaderStageCreateInfo-flags-02759`, or `-pNext-02757` with a required /// subgroup size). pub stage_flags: vk::PipelineShaderStageCreateFlags, @@ -206,7 +201,7 @@ impl StageModule { /// or dispatch binds the values `bound` gives, where a test of a key no pipeline's /// key carries (the bound format's class, `SpecKey::BoundTexelFormat`; a bound sampler's word, /// `SpecKey::BoundSamplerWord`; what the command's handles can name) reads the value `bound` - /// gives for it (`BindingPlan::specialized_value`); a test of a key neither gives holds. + /// gives for it; a test of a key neither gives holds. pub fn precision_notes_bound( &self, specialization: &SpecializationKey, @@ -854,7 +849,7 @@ pub enum PrecisionNote { /// slot bound in an 8-bit sRGB format the device holds as its UNORM twin decodes the code /// exactly instead, and a bicubic sample sums the codes' steps exactly, under the slot's /// `SrgbTexture` variant, and records nothing. What a filtered sample converts is the filter's - /// value ([`PrecisionNote::HalfSampleFilter`]). Validation derives no tolerance from it. + /// value. Validation derives no tolerance from it. /// /// Native device sampling (a texel conversion): every access with a `half` result records this /// note, a heap element's and a depth texture's included. The recorded bound: the device's @@ -865,15 +860,6 @@ pub enum PrecisionNote { /// saturates to `±65504` and the rounding takes to the infinity of its sign; a NaN is the /// device's decode ([`PrecisionNote::DeviceNanEncoding`]). HalfTexelConversion, - /// The module samples a texture with a `half` result through a filter (linear minification - /// or magnification, a linear mip filter, anisotropy, or a runtime sampler) by Vulkan's Y′CbCr - /// model of the codes of a two-plane YCbCr texture whose planes the function reads in place - /// (`lower::sampler::in_place`), which blends the codes, not Metal's exact filter of the - /// format, on every device: recorded under the slot's bound converted 4:2:0 format and, - /// through a runtime sampler slot, the bound word's linear filter that addresses no border. - /// The `float` result's counterpart is [`PrecisionNote::FloatSampleFilter`]. Validation derives - /// no tolerance from it: the class is unbounded. - HalfSampleFilter, /// The module reads, samples, or gathers a texture with a `half` or `float` result through /// the device's sRGB decode, or decodes the device's filter of its codes, where the texture may /// be bound in an 8-bit sRGB format (`metal::texel_format::srgb_coded`: the 8-bit sRGB formats @@ -909,13 +895,6 @@ pub enum PrecisionNote { /// it, where MoltenVK's `Pow` read within `1.83e-7` of the transfer through the alias. /// Validation derives no tolerance from it: the class is unbounded. SrgbTexelDecode, - /// The module samples a texture with a `float` result through a filter by Vulkan's Y′CbCr - /// model of the codes of a two-plane YCbCr texture whose planes the function reads in place - /// (`lower::sampler::in_place`), as [`PrecisionNote::HalfSampleFilter`] states for a `half` - /// result: a sample is filtered unless its sampler has nearest minification and - /// magnification, no mip filter or a nearest one, and no anisotropy. Validation derives no - /// tolerance from it: the class is unbounded. - FloatSampleFilter, /// A vertex or fragment function keeps more private memory (its `alloca`s, a call stack among /// them, or constants held as `Private` variables) than the floor, 16 KiB a thread, on a device /// whose Function storage was not measured, up to the 192 KiB a thread Metal was measured to diff --git a/crates/metal2vulkan/src/pipeline/compile/api.rs b/crates/metal2vulkan/src/pipeline/compile/api.rs index 25a7dce45..7d3e2f568 100644 --- a/crates/metal2vulkan/src/pipeline/compile/api.rs +++ b/crates/metal2vulkan/src/pipeline/compile/api.rs @@ -288,8 +288,7 @@ impl Device { /// descriptor's color attachment formats (`LoweringInputs::tile_attachments`, the color index /// of each attachment whose format is set), as a compute pipeline that runs one threadgroup per /// tile of the render area and stages the attachments it reaches (`lower::access::tile`). The - /// consumer dispatches it in place of `dispatchThreadsPerTile:` with - /// `BindState::imageblock_size` set to the pass's tile size and `BindState::render_area` to its + /// consumer dispatches it in place of `dispatchThreadsPerTile:` over the pass's tile size and /// render area, binding each attachment it reaches (`WriteSource::TileAttachment`). A /// `Compiled` tile function must have been compiled under the same formats: one compiled /// without tile inputs is `InvalidDescriptor(StageMismatch)`, and one that stages an attachment @@ -964,9 +963,8 @@ impl Device { metal = metal.min(cap); } // The static part of Metal's own layout, as Metal reports it: neither the emulated - // simdgroups' scratch nor a predicated walk's vote word, which are ours and which the - // planner counts in each dispatch's total (`bind::plan::compute`), refusing a threadgroup - // whose lengths fit beside this length and not beside them (`ThreadgroupMemorySize`). + // simdgroups' scratch nor a predicated walk's vote word, which are ours + // (`RuntimeFact::SimdgroupEmulation`, `RuntimeFact::PredicationVote`). // Metal reports it rounded up to 16 bytes, its threadgroup memory's granularity // (`threadgroup uint a[256]; threadgroup uint b;` answers 1040, not 1028, on the M3 Max, // macOS 27.0.1). diff --git a/crates/metal2vulkan/src/pipeline/compile/key.rs b/crates/metal2vulkan/src/pipeline/compile/key.rs index b0136c56b..1fb101fdb 100644 --- a/crates/metal2vulkan/src/pipeline/compile/key.rs +++ b/crates/metal2vulkan/src/pipeline/compile/key.rs @@ -229,21 +229,6 @@ pub fn function_key( .bytes(format!("{:?}", inputs.srgb_textures).as_bytes()); } // Appended only when set, as `signed_color_attachments`. - if !inputs.ycbcr_in_place.is_empty() { - h.bytes(b"ycbcr-in-place") - .bytes(format!("{:?}", inputs.ycbcr_in_place).as_bytes()); - } - // Appended only when set, as `signed_color_attachments`. - if !inputs.ycbcr_planes_sampled.is_empty() { - h.bytes(b"ycbcr-planes-sampled") - .bytes(format!("{:?}", inputs.ycbcr_planes_sampled).as_bytes()); - } - // Appended only when set, as `signed_color_attachments`. - if !inputs.texel_rows.is_empty() { - h.bytes(b"texel-rows") - .bytes(format!("{:?}", inputs.texel_rows).as_bytes()); - } - // Appended only when set, as `signed_color_attachments`. if !inputs.texel_buffer_parts.is_empty() { h.bytes(b"texel-buffer-parts") .bytes(format!("{:?}", inputs.texel_buffer_parts).as_bytes()); diff --git a/crates/metal2vulkan/src/pipeline/compile/tests.rs b/crates/metal2vulkan/src/pipeline/compile/tests.rs index d0d5e64fb..4cbc23f03 100644 --- a/crates/metal2vulkan/src/pipeline/compile/tests.rs +++ b/crates/metal2vulkan/src/pipeline/compile/tests.rs @@ -649,9 +649,6 @@ fn the_inputs_encoding_is_the_earlier_derived_debug() { .replace(", replay_bindings: false", "") .replace(", merged_draws: false", "") .replace(", srgb_textures: {}", "") - .replace(", ycbcr_in_place: {}", "") - .replace(", ycbcr_planes_sampled: {}", "") - .replace(", texel_rows: {}", "") .replace(", texel_buffer_parts: {}", "") .replace(", viewport_index_varying: false", "") .replace(", max_call_stack_depth: None", "") @@ -3043,461 +3040,6 @@ fn a_fragment_reading_through_a_loaded_pointer_writes_no_memory() { } } -/// A vertex function that writes `[[viewport_array_index]]` depends on the draw's viewport count, -/// which its push window holds and each draw writes from `BindState::viewport_count`, and writes -/// the index as written to a flat varying (`IoRole::ViewportIndex`). In its pipeline a fragment -/// function that reads the index compiles under `viewport_index_varying` and reads that varying, as -/// `render_pipeline_key` names, its push fields from the vertex function's push end -/// (`CompiledFunction::fragment_push_base`); one that does not read it compiles without -/// `viewport_index_varying`. A reading fragment compiled for the other kind of -/// vertex function is `NeedsInput(ViewportIndex)` either way. Every module passes L3. -#[test] -fn a_fragment_reads_the_viewport_index_its_vertex_function_wrote() { - use crate::bind::plan::FieldLocation; - use crate::bind::{BindState, DrawCall}; - use crate::error::RuntimeInput; - use crate::pipeline::facts::RuntimeFact; - use crate::pipeline::stage_io::{IoRole, StageBuiltin}; - use crate::pipeline::sym::{PushField, Stage, VaryingKey}; - let (Some(bc), Some(other)) = (fixture("rt6_viewports"), fixture("rt6_render_state")) else { - return; - }; - let lib = Library::from_air(&bc).expect("library"); - let other = Library::from_air(&other).expect("library"); - let function = |lib: &Library, name: &str| { - FunctionDescriptor::new(lib.function(name).unwrap_or_else(|e| panic!("{name}: {e}"))) - }; - let dev = device("moltenvk-m3"); - let budget = Budget::standard(); - let pipeline = |vertex: StageSource, fragment: StageSource| { - let mut d = RenderPipelineDescriptor::new(vertex); - d.fragment = Some(fragment); - d.color_attachments[0] = Some(ColorAttachmentDescriptor::new( - metal::PixelFormat::RGBA8Unorm, - )); - d - }; - let select = || StageSource::Function(function(&lib, "rt6_select")); - let reader = function(&lib, "rt6_viewport_read"); - - // The vertex function: the fact, the push field, the builtin, and the raw varying. - let vertex = dev - .compile_function( - &function(&lib, "rt6_select"), - &LoweringInputs::new(), - &budget, - ) - .expect("vertex"); - let a = vertex.artifact(); - assert!(a.facts.contains(&RuntimeFact::ViewportCount)); - assert!(a - .interface - .push - .fields - .iter() - .any(|f| f.field == PushField::ViewportCount)); - assert!(a - .interface - .io - .builtins - .contains(&StageBuiltin::ViewportIndex)); - let raw: Vec<_> = a - .interface - .io - .outputs - .iter() - .filter(|v| v.role == IoRole::ViewportIndex) - .collect(); - assert_eq!(raw.len(), 1); - assert_eq!(raw[0].key, VaryingKey::viewport_index()); - - // The reading fragment in the pipeline: the field, the varying, no builtin. - let d = pipeline(select(), StageSource::Function(reader.clone())); - let keys = dev.render_pipeline_key(&d, &budget).expect("keys"); - let inputs = keys.fragment_inputs.clone().expect("fragment inputs"); - assert!(inputs.viewport_index_varying); - let pipe = dev.compile_render_pipeline(&d, &budget).expect("pipeline"); - assert_eq!(pipe.key, keys.pipeline); - for s in &pipe.stages { - l3(&s.spirv, &pipe.requirements, &dev); - } - assert!(pipe - .dependencies - .iter() - .any(|d| d.fact == RuntimeFact::ViewportCount)); - let fragment = dev - .compile_function(&reader, &inputs, &budget) - .expect("fragment"); - assert_eq!(Some(*fragment.key()), keys.fragment); - let io = &fragment.artifact().interface.io; - assert!(io.inputs.iter().any(|v| v.role == IoRole::ViewportIndex)); - assert!(!io.builtins.contains(&StageBuiltin::ViewportIndex)); - - // A fragment that does not read the index keeps its key. - let white = function(&lib, "rt6_white"); - let keys = dev - .render_pipeline_key( - &pipeline(select(), StageSource::Function(white.clone())), - &budget, - ) - .expect("keys"); - let inputs = keys.fragment_inputs.clone().expect("fragment inputs"); - assert!(!inputs.viewport_index_varying); - assert_eq!( - keys.fragment, - Some(dev.function_compile_key(&white, &inputs)) - ); - - // Each draw writes the encoder's viewport count into the vertex push window. - let state = BindState { - viewport_count: 3, - ..BindState::default() - }; - let plan = pipe.plan(&dev, &state.shape()).expect("plan"); - let placed = plan - .push - .fields - .iter() - .find(|f| f.stage == Stage::Vertex && f.field == PushField::ViewportCount) - .expect("placed"); - let FieldLocation::PushWindow { offset } = placed.location else { - panic!("the count spilled: {placed:?}"); - }; - let draw = DrawCall::Primitives { - vertex_start: 0, - vertex_count: 3, - instance_count: 1, - base_instance: 4, - }; - let commands = plan.instantiate_draw(&state, &draw).expect("draw"); - let write = commands - .push_constants - .iter() - .find(|w| w.stages.contains(crate::vk::ShaderStageFlags::VERTEX)) - .expect("vertex push"); - let at = (offset - write.offset) as usize; - assert_eq!(write.bytes[at..at + 4], 3u32.to_le_bytes()); - - // Compiled for the other kind of vertex function: refused, never a wrong read. - let without = dev - .compile_function(&reader, &LoweringInputs::new(), &budget) - .expect("fragment"); - let mut under = LoweringInputs::new(); - under.viewport_index_varying = true; - let under = dev - .compile_function(&reader, &under, &budget) - .expect("fragment"); - let full = || StageSource::Function(function(&other, "rt6_full")); - for d in [ - pipeline(select(), StageSource::Compiled(without)), - pipeline(full(), StageSource::Compiled(under)), - ] { - assert_eq!( - dev.compile_render_pipeline(&d, &budget).err(), - Some(Error::NeedsInput(RuntimeInput::ViewportIndex)) - ); - } -} - -/// A merged draw replay's vertex function (`VariantKey::merged_draws`) reads its command's slot -/// table from the header at its `MergedDrawAddress`, a hole of the vertex stage, in place of a -/// `RootTableAddress`, and its plan states the variant. A fragment function that reads a buffer -/// reads its command's fragment slot table from the header too, at the command its vertex wrote -/// (`IoRole::MergedCommand`): `MergedDrawAddress` is its push field, `RootTableAddress` none. One -/// that reads `[[primitive_id]]`, which Metal counts per command, is refused, as is a merged key -/// without replay bindings. -#[test] -fn a_merged_draw_reads_its_command_s_table_from_its_header() { - use crate::cache::VariantKey; - use crate::pipeline::sym::PushField; - let dev = device("moltenvk-m3"); - let mut key = VariantKey::new(); - key.replay_bindings = true; - key.merged_draws = true; - let compile = |vertex: (&str, &str), - fragment: Option<(&str, &str, metal::PixelFormat)>, - key: &VariantKey| { - let function = |(file, name): (&str, &str)| { - let bc = fixture(file)?; - Some(FunctionDescriptor::new( - Library::from_air(&bc) - .expect("library") - .function(name) - .expect("function"), - )) - }; - let mut d = RenderPipelineDescriptor::new(StageSource::Function(function(vertex)?)); - match fragment { - Some((file, name, format)) => { - d.fragment = Some(StageSource::Function(function((file, name))?)); - d.color_attachments[0] = Some(ColorAttachmentDescriptor::new(format)); - } - None => d.rasterization_enabled = false, - } - Some(dev.compile_render_variant(&d, key, &Budget::standard())) - }; - let Some(merged) = compile(("primitive_ids", "pi_place"), None, &key) else { - return; - }; - let merged = merged.expect("merged"); - let fields: Vec = merged - .interface - .push - .iter() - .flat_map(|p| p.fields.iter().map(|f| f.field)) - .collect(); - assert!(fields.contains(&PushField::MergedDrawAddress), "{fields:?}"); - assert!(!fields.contains(&PushField::RootTableAddress), "{fields:?}"); - assert!( - !fields.contains(&PushField::BaseVertexInstance), - "{fields:?}" - ); - let plan = merged - .plan(&dev, &crate::bind::BindShape::default()) - .expect("plan"); - assert!(plan.variant.replay_bindings && plan.variant.merged_draws); - let placed: Vec<_> = plan - .push - .fields - .iter() - .filter(|f| f.field == PushField::MergedDrawAddress) - .map(|f| f.stage) - .collect(); - assert_eq!(placed, [crate::pipeline::sym::Stage::Vertex]); - let mut unreplayed = VariantKey::new(); - unreplayed.merged_draws = true; - let plain = compile(("primitive_ids", "pi_place"), None, &unreplayed) - .expect("fixture") - .expect("merged alone is no variant"); - assert!(!plain.interface.push.iter().any(|p| p - .fields - .iter() - .any(|f| f.field == PushField::MergedDrawAddress))); - let (vertex, fragment) = ( - ("primitive_ids", "pi_place"), - ("primitive_ids", "pi_ids", metal::PixelFormat::RGBA32Uint), - ); - compile(vertex, Some(fragment), &VariantKey::new()) - .expect("fixture") - .expect("plain"); - let refused = compile(vertex, Some(fragment), &key) - .expect("fixture") - .expect_err("a fragment's primitive ID under a merged draw"); - assert!( - format!("{refused:?}").contains("GpuEncodedIndirectCommands"), - "{fragment:?}: {refused:?}" - ); - let (vertex, fragment) = ( - ("a8r_targets", "a8r_vertex"), - ("a8r_targets", "a8r_fill", metal::PixelFormat::RGBA8Unorm), - ); - let buffered = compile(vertex, Some(fragment), &key) - .expect("fixture") - .expect("a fragment's buffer under a merged draw"); - let fragment_fields: Vec = (buffered.interface.push.iter()) - .filter(|p| p.stage == crate::pipeline::sym::Stage::Fragment) - .flat_map(|p| p.fields.iter().map(|f| f.field)) - .collect(); - assert!( - fragment_fields.contains(&PushField::MergedDrawAddress) - && !fragment_fields.contains(&PushField::RootTableAddress), - "{fragment_fields:?}" - ); -} - -/// A merged draw replay's functions find their command's slot tables before any entry hook reads -/// one: a fragment function that loads a pointer from its argument buffer reads that buffer's -/// root entry at entry (`access::dynamic::emit_entry`), from the fragment slot table the command -/// its vertex wrote names, and the merged variant of `icb_merged_arguments` (a vertex function -/// that fetches `[[stage_in]]` attributes, a fragment function whose argument buffer holds two -/// textures and a constant pointer) compiles on each device that has the replay, every stage -/// passing L3, its fragment stage reading the header at its `MergedDrawAddress`. -#[test] -fn a_merged_fragment_reads_its_argument_buffer_through_its_command_s_table() { - use crate::cache::VariantKey; - use crate::pipeline::sym::{PushField, Stage}; - let Some(bc) = fixture("icb_merged_arguments") else { - return; - }; - let lib = Library::from_air(&bc).expect("library"); - let function = |name: &str| { - StageSource::Function(FunctionDescriptor::new(lib.function(name).expect(name))) - }; - let mut d = RenderPipelineDescriptor::new(function("ica_vertex")); - d.fragment = Some(function("ica_fragment")); - d.color_attachments[0] = Some(ColorAttachmentDescriptor::new( - metal::PixelFormat::RGBA32Uint, - )); - let mut input = VertexDescriptor::new(); - input - .layouts - .insert(0, VertexBufferLayoutDescriptor::new(Some(8))); - input - .layouts - .insert(1, VertexBufferLayoutDescriptor::new(Some(4))); - input.attributes.insert( - 0, - VertexAttributeDescriptor::new(metal::VertexFormat::Float2, 0, 0), - ); - input.attributes.insert( - 1, - VertexAttributeDescriptor::new(metal::VertexFormat::UInt, 0, 1), - ); - d.vertex_descriptor = Some(input); - for stem in ["moltenvk-m3", "amd-780m-radv", "lavapipe"] { - let dev = device(stem); - let base = dev - .compile_render_variant(&d, &VariantKey::new(), &Budget::standard()) - .unwrap_or_else(|e| panic!("{stem}: base: {e}")); - let layouts = (base.vertex_input.bindings.iter()) - .map(|b| b.buffer_index) - .collect(); - let shape = crate::bind::BindShape { - far_vertex_buffers: layouts, - ..Default::default() - }; - let mut key = base.plan(&dev, &shape).expect("base plan").variant; - key.replay_bindings = true; - key.merged_draws = true; - let merged = dev - .compile_render_variant(&d, &key, &Budget::standard()) - .unwrap_or_else(|e| panic!("{stem}: merged: {e}")); - for stage in &merged.stages { - l3(&stage.spirv, &merged.requirements, &dev); - } - let fragment: Vec = (merged.interface.push.iter()) - .filter(|p| p.stage == Stage::Fragment) - .flat_map(|p| p.fields.iter().map(|f| f.field)) - .collect(); - assert!( - fragment.contains(&PushField::MergedDrawAddress) - && !fragment.contains(&PushField::RootTableAddress), - "{stem}: {fragment:?}" - ); - } -} - -/// A render pipeline compiled as a device-replay variant (`VariantKey::replay_bindings`) reads -/// every buffer its vertex function reaches through its root entry (`BufferForm::Psb`), from the -/// slot table at the stage's own `RootTableAddress`, and needs no `SlotGuestBase` -/// (`icb_render_replay_template`); its plan states the variant. A vertex function that fetches -/// a `[[stage_in]]` attribute (`icb_render_stride_template`) in fixed function, as it does under -/// the identity domains, is refused: fixed-function input reads no slot table. Outside them the -/// attribute is pulled, so the draw binds no fixed-function layout, and its replay variant -/// compiles, one draw per command and merged, binds no layout and pulls the attribute, whose read -/// reaches the slot table; every stage passes L3, and its plan states its key. -#[test] -fn a_replayed_draw_reads_its_buffers_through_the_slot_table() { - use crate::cache::VariantKey; - use crate::pipeline::interface::{BufferForm, SlotInterface}; - use crate::pipeline::sym::PushField; - let dev = device("moltenvk-m3"); - let mut key = VariantKey::new(); - key.replay_bindings = true; - let Some(bc) = fixture("icb_render_replay_template") else { - return; - }; - let vertex = Library::from_air(&bc) - .expect("library") - .function("icb_render_replay_template") - .expect("vertex"); - let mut d = - RenderPipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new(vertex))); - d.rasterization_enabled = false; - let plain = dev - .compile_render_variant(&d, &VariantKey::new(), &Budget::standard()) - .expect("plain"); - let replayed = dev - .compile_render_variant(&d, &key, &Budget::standard()) - .expect("replayed"); - let forms = |p: &crate::pipeline::artifact::RenderPipeline| -> Vec { - p.interface - .slots - .values() - .filter_map(|s| match s { - SlotInterface::Buffer(b) => Some(b.form), - _ => None, - }) - .collect() - }; - assert_eq!(forms(&replayed).len(), 2); - assert!(forms(&replayed).iter().all(|f| *f == BufferForm::Psb)); - assert!(forms(&plain).iter().any(|f| *f != BufferForm::Psb)); - let fields: Vec = replayed - .interface - .push - .iter() - .flat_map(|p| p.fields.iter().map(|f| f.field)) - .collect(); - assert!(fields.contains(&PushField::RootTableAddress)); - assert!(!fields - .iter() - .any(|f| matches!(f, PushField::SlotGuestBase(_)))); - let plan = replayed - .plan(&dev, &crate::bind::BindShape::default()) - .expect("plan"); - assert!(plan.variant.replay_bindings); - - // A fixed-function fetch is the identity domains' alone (the runtime's): outside them every - // attribute is pulled. - let idev = - Device::from_queries(description("moltenvk-m3"), DevicePolicy::default()).expect("device"); - let Some(bc) = fixture("icb_render_stride_template") else { - return; - }; - let vertex = Library::from_air(&bc) - .expect("library") - .function("icb_render_stride_template") - .expect("vertex"); - let mut d = - RenderPipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new(vertex))); - d.rasterization_enabled = false; - d.vertex_descriptor = Some(vertex_descriptor(&[(0, metal::VertexFormat::UInt)])); - let fetched = idev - .compile_render_variant(&d, &VariantKey::new(), &Budget::standard()) - .expect("fetched"); - assert_eq!(fetched.vertex_input.bindings.len(), 1); - let refused = idev - .compile_render_variant(&d, &key, &Budget::standard()) - .expect_err("a fetch under replay bindings"); - assert!( - format!("{refused:?}").contains("GpuEncodedIndirectCommands"), - "{refused:?}" - ); - let base = dev - .compile_render_variant(&d, &VariantKey::new(), &Budget::standard()) - .expect("pulled"); - assert!( - base.vertex_input.bindings.is_empty(), - "{:?}", - base.vertex_input.bindings - ); - for merged in [false, true] { - let mut replay = key.clone(); - replay.merged_draws = merged; - let p = dev - .compile_render_variant(&d, &replay, &Budget::standard()) - .unwrap_or_else(|e| panic!("merged {merged}: {e}")); - let input = &p.vertex_input; - assert!(input.bindings.is_empty(), "merged {merged}"); - assert_eq!(input.pulled.len(), 1, "merged {merged}"); - // The pulled layout's buffer is read through its root entry, as every other slot. - let slots = forms(&p); - assert!( - !slots.is_empty() && slots.iter().all(|f| *f == BufferForm::Psb), - "merged {merged}: {slots:?}" - ); - for stage in &p.stages { - l3(&stage.spirv, &p.requirements, &dev); - } - let replayed = p - .plan(&dev, &crate::bind::BindShape::default()) - .expect("the variant's plan"); - assert_eq!(replayed.variant, replay, "merged {merged}"); - assert!(replayed.vertex_buffers.is_empty(), "merged {merged}"); - } -} - /// Under the identity domains a device-replay variant (`VariantKey::replay_bindings`), which reads /// every buffer slot's address from its replayed command's root entry at the stage's /// `RootTableAddress`, is refused, typed (`Unsupported{IdentityDomains}` naming the field the @@ -3615,63 +3157,126 @@ fn a_pipeline_for_indirect_command_buffers_pulls_its_stage_in() { } } -/// A draw replay's variant reads every buffer through the slot table its replay's preprocess -/// writes, so inline bytes the encoder bound at a slot it reads are no refusal: commands that -/// inherit the encoder's buffers read them at the consumer's upload of them, whose address the -/// preprocess's entry takes (`bind::DrawReplayPreprocess::inherited_bytes`). Its plan for a shape -/// with inline bytes at every buffer slot plans; one with a buffer bound without a device -/// address there, which no entry can name, stays `MissingDeviceAddress`. +/// A vertex function that writes `[[viewport_array_index]]` depends on the draw's viewport count, +/// which its push window holds (`PushField::ViewportCount`), and writes the index as written to a +/// flat varying (`IoRole::ViewportIndex`). In its pipeline a fragment +/// function that reads the index compiles under `viewport_index_varying` and reads that varying, as +/// `render_pipeline_key` names, its push fields from the vertex function's push end +/// (`CompiledFunction::fragment_push_base`); one that does not read it compiles without +/// `viewport_index_varying`. A reading fragment compiled for the other kind of +/// vertex function is `NeedsInput(ViewportIndex)` either way. Every module passes L3. #[test] -fn a_replayed_draw_plans_inline_bytes_at_its_slots() { - use crate::bind::{BindShape, BufferShape, StageShape}; - use crate::cache::VariantKey; - use crate::error::BindError; - use crate::pipeline::interface::SlotInterface; - let dev = device("moltenvk-m3"); - let mut key = VariantKey::new(); - key.replay_bindings = true; - let Some(bc) = fixture("icb_render_replay_template") else { +fn a_fragment_reads_the_viewport_index_its_vertex_function_wrote() { + use crate::error::RuntimeInput; + use crate::pipeline::facts::RuntimeFact; + use crate::pipeline::stage_io::{IoRole, StageBuiltin}; + use crate::pipeline::sym::{PushField, VaryingKey}; + let (Some(bc), Some(other)) = (fixture("rt6_viewports"), fixture("rt6_render_state")) else { return; }; - let vertex = Library::from_air(&bc) - .expect("library") - .function("icb_render_replay_template") + let lib = Library::from_air(&bc).expect("library"); + let other = Library::from_air(&other).expect("library"); + let function = |lib: &Library, name: &str| { + FunctionDescriptor::new(lib.function(name).unwrap_or_else(|e| panic!("{name}: {e}"))) + }; + let dev = device("moltenvk-m3"); + let budget = Budget::standard(); + let pipeline = |vertex: StageSource, fragment: StageSource| { + let mut d = RenderPipelineDescriptor::new(vertex); + d.fragment = Some(fragment); + d.color_attachments[0] = Some(ColorAttachmentDescriptor::new( + metal::PixelFormat::RGBA8Unorm, + )); + d + }; + let select = || StageSource::Function(function(&lib, "rt6_select")); + let reader = function(&lib, "rt6_viewport_read"); + + // The vertex function: the fact, the push field, the builtin, and the raw varying. + let vertex = dev + .compile_function( + &function(&lib, "rt6_select"), + &LoweringInputs::new(), + &budget, + ) .expect("vertex"); - let mut d = - RenderPipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new(vertex))); - d.rasterization_enabled = false; - let replayed = dev - .compile_render_variant(&d, &key, &Budget::standard()) - .expect("replayed"); - let slots: Vec<_> = (replayed.interface.slots.iter()) - .filter(|(_, s)| matches!(s, SlotInterface::Buffer(_))) - .map(|(slot, _)| *slot) + let a = vertex.artifact(); + assert!(a.facts.contains(&RuntimeFact::ViewportCount)); + assert!(a + .interface + .push + .fields + .iter() + .any(|f| f.field == PushField::ViewportCount)); + assert!(a + .interface + .io + .builtins + .contains(&StageBuiltin::ViewportIndex)); + let raw: Vec<_> = a + .interface + .io + .outputs + .iter() + .filter(|v| v.role == IoRole::ViewportIndex) .collect(); - assert!(!slots.is_empty()); - let shape_with = |bound: BufferShape| { - let mut shape = BindShape::default(); - for slot in &slots { - let stage: &mut StageShape = shape.stages.entry(slot.stage).or_default(); - stage.buffers.insert(slot.index, bound); - } - shape - }; - let bytes = BufferShape::Bytes { - attribute_stride: None, - }; - let plan = replayed - .plan(&dev, &shape_with(bytes)) - .expect("inline bytes"); - assert!(plan.variant.replay_bindings); - let unaddressed = BufferShape::Buffer { - attribute_stride: None, - device_address: false, - length_class: 0, - offset_alignment: 4, - }; - let refused = replayed.plan(&dev, &shape_with(unaddressed)); - assert!( - matches!(refused, Err(BindError::MissingDeviceAddress { .. })), - "{refused:?}" + assert_eq!(raw.len(), 1); + assert_eq!(raw[0].key, VaryingKey::viewport_index()); + + // The reading fragment in the pipeline: the field, the varying, no builtin. + let d = pipeline(select(), StageSource::Function(reader.clone())); + let keys = dev.render_pipeline_key(&d, &budget).expect("keys"); + let inputs = keys.fragment_inputs.clone().expect("fragment inputs"); + assert!(inputs.viewport_index_varying); + let pipe = dev.compile_render_pipeline(&d, &budget).expect("pipeline"); + assert_eq!(pipe.key, keys.pipeline); + for s in &pipe.stages { + l3(&s.spirv, &pipe.requirements, &dev); + } + assert!(pipe + .dependencies + .iter() + .any(|d| d.fact == RuntimeFact::ViewportCount)); + let fragment = dev + .compile_function(&reader, &inputs, &budget) + .expect("fragment"); + assert_eq!(Some(*fragment.key()), keys.fragment); + let io = &fragment.artifact().interface.io; + assert!(io.inputs.iter().any(|v| v.role == IoRole::ViewportIndex)); + assert!(!io.builtins.contains(&StageBuiltin::ViewportIndex)); + + // A fragment that does not read the index keeps its key. + let white = function(&lib, "rt6_white"); + let keys = dev + .render_pipeline_key( + &pipeline(select(), StageSource::Function(white.clone())), + &budget, + ) + .expect("keys"); + let inputs = keys.fragment_inputs.clone().expect("fragment inputs"); + assert!(!inputs.viewport_index_varying); + assert_eq!( + keys.fragment, + Some(dev.function_compile_key(&white, &inputs)) ); + + // Compiled for the other kind of vertex function: refused, never a wrong read. + let without = dev + .compile_function(&reader, &LoweringInputs::new(), &budget) + .expect("fragment"); + let mut under = LoweringInputs::new(); + under.viewport_index_varying = true; + let under = dev + .compile_function(&reader, &under, &budget) + .expect("fragment"); + let full = || StageSource::Function(function(&other, "rt6_full")); + for d in [ + pipeline(select(), StageSource::Compiled(without)), + pipeline(full(), StageSource::Compiled(under)), + ] { + assert_eq!( + dev.compile_render_pipeline(&d, &budget).err(), + Some(Error::NeedsInput(RuntimeInput::ViewportIndex)) + ); + } } diff --git a/crates/metal2vulkan/src/pipeline/facts.rs b/crates/metal2vulkan/src/pipeline/facts.rs index c0570e28c..3caf2ff49 100644 --- a/crates/metal2vulkan/src/pipeline/facts.rs +++ b/crates/metal2vulkan/src/pipeline/facts.rs @@ -107,11 +107,10 @@ pub enum RuntimeFact { /// whatever the bind's, and records nothing. StageInStride { layout: 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`), - /// one threadgroup per tile, and stages the color attachments it reaches through the - /// threadgroup's imageblock. A layered pass is not modeled: the planner refuses a render - /// target array length above 1. + /// render pass's render area (`renderTargetWidth` and `renderTargetHeight`, + /// `SpecKey::RenderAreaWidth` and `SpecKey::RenderAreaHeight`) in tiles of the pass's tile + /// size, one threadgroup per tile, and stages the color attachments it reaches through the + /// threadgroup's imageblock. A layered pass is not modeled. TileFunction, /// The tile function stages color attachment `color` as a storage image of pixel format /// `format` (`LoweringInputs::tile_attachments`): its texel conversions and declared image @@ -161,8 +160,8 @@ pub enum RuntimeFact { /// resident everywhere, and the status word Metal returns for it is compiled in, exact on /// every device. `sparse_arm`: the module also answers a sparse texture, with the device's /// sparse residency (`OpImageSparse*` and `OpImageSparseTexelsResident` under - /// `shaderResourceResidency`), selected by `SpecKey::SparseTexture`. Without it the binder - /// refuses a sparse texture at the slot (`BindError::Unsupported`): naming + /// `shaderResourceResidency`), selected by `SpecKey::SparseTexture`. Without it a sparse + /// texture at the slot is refused (`Unsupported`): naming /// `shaderResourceResidency` where the device lacks it, `NotImplemented` where one of the /// slot's accesses has no sparse form (a bicubic sample), and `NotRepresentable` where the /// function updates the slot atomically (`SparseTextureWrites`). A slot the function writes @@ -214,8 +213,8 @@ pub enum RuntimeFact { /// The vertex function writes `[[viewport_array_index]]`, which selects a viewport only below /// the render encoder's viewport count (`setViewports:count:`): Metal draws a primitive whose /// index is at or past the count through viewport 0, so the function stores `ViewportIndex` - /// as 0 there, reading the count from `PushField::ViewportCount`, which the binder writes per - /// draw (`BindState::viewport_count`). + /// as 0 there, reading the count from `PushField::ViewportCount`, which the consumer writes per + /// draw. ViewportCount, /// The tile function aliases an explicit imageblock onto its implicit one /// (`air.alias_implicit_imageblock`), of `data_size` bytes (`air.imageblock_data_size`): a @@ -294,10 +293,10 @@ pub enum RuntimeFact { /// The tile function reads its threadgroup argument `index` (`[[threadgroup(index)]]`): /// memory of its tile that the render pass keeps across its tile dispatches, at the offset /// and in the tile memory the encoder sets (`setThreadgroupMemoryLength:offset:atIndex:` and - /// the pass's `threadgroupMemoryLength`, `BindState::tile_threadgroup`). The binder + /// the pass's `threadgroupMemoryLength`). The consumer /// specializes `SpecKey::TgOffset(index)`, `SpecKey::TileThreadgroupLength` and /// `SpecKey::TileGridWidth`, binds the pass's `SyntheticBinding::TileMemory`, and refuses an - /// index the encoder did not set (`BindError::MissingThreadgroupMemory`). A fragment + /// index the encoder did not set. A fragment /// function's threadgroup arguments are the same memory: its draws read and write it in the /// buffer, at its tile, which `SpecKey::ImageblockWidth` and `SpecKey::ImageblockHeight` (the /// pass's tile size) place. @@ -352,27 +351,24 @@ pub enum RuntimeFact { /// The fragment function was compiled under `VariantKey::zeroed_colors` /// (`LoweringInputs::zeroed_colors`): it writes zero to color attachment `color`, of pixel /// format `format`, which its Metal pipeline lacks and the pass has, as plain Metal stores - /// zero bytes there at every sample a draw covers. Its plans state the variant the shape asks - /// for (`BindShape::zeroed_colors`). + /// zero bytes there at every sample a draw covers. ZeroedColor { color: u32, format: crate::metal::PixelFormat, }, /// The fragment function was compiled under `LoweringInputs::dropped_colors` holding /// `color`: it keeps no output at that color attachment, which the render pass lacks and - /// whose writes plain Metal drops. A plan of a draw whose pass has the attachment asks for the - /// variant without it. + /// whose writes plain Metal drops. A draw whose pass has the attachment takes the variant + /// without it. DroppedColor { color: u32 }, /// The fragment function was compiled under `VariantKey::depth_clamp_range` /// (`LoweringInputs::depth_clamp_range`) and writes its depth: it clamps that depth to the - /// draw's depth clamp range itself, read from `PushField::DepthClampRange`, which the binder - /// writes from `BindState::depth_clamp_range`, a negative NaN storing 0 as Metal's does. Its - /// plans state the variant the shape asks for (`BindShape::depth_clamp_range`). + /// draw's depth clamp range itself, read from `PushField::DepthClampRange`, which the consumer + /// writes, a negative NaN storing 0 as Metal's does. DepthClampRange, /// The fragment function was compiled under `VariantKey::rotated_weights` /// (`LoweringInputs::rotated_weights`) and reads `[[barycentric_coord]]`: it takes Metal's - /// weights back from a triangle drawn with Metal's last vertex first. Its plans state the - /// variant the shape asks for (`BindShape::rotated_weights`). + /// weights back from a triangle drawn with Metal's last vertex first. RotatedWeights, /// The function reads, samples, gathers, or fetches through a sampler the color texture /// bound to the slot, on a profile whose sparse textures are sparse images (it enables @@ -394,8 +390,8 @@ pub enum RuntimeFact { /// per threadgroup or their `dispatch_` forms, its position in the grid, the threads per /// grid, or its thread or quadgroup index in the threadgroup), and was compiled under /// `tile_sized`, that flag (`LoweringInputs::threadgroup_size_matches_tile_size`). With - /// `tile_sized` the binder runs each dispatch with the pass's tile, its imageblock size - /// (`BindShape::imageblock_size`), as Metal's threadgroup in every region (`MultiRegion` 1), + /// `tile_sized` the consumer runs each dispatch with the pass's tile, its imageblock size, + /// as Metal's threadgroup in every region (`MultiRegion` 1), /// the threads per tile its workgroups; a tile pipeline whose descriptor gives the flag the /// other value is `InvalidDescriptor(TileThreadgroupSize)`. TileThreadgroup { tile_sized: bool }, @@ -427,10 +423,9 @@ pub enum RuntimeFact { /// not emulate there, it sets `StatusBits::CUBIC_ARGUMENT_SAMPLER` in the command buffer's /// `ExecutionStatus` buffer (through the address the stage's `ExecutionStatus` fact asks /// for), and a consumer that reads the bit reports the command buffer's execution as failed. A - /// run that never reaches such a sampler is Metal's exactly. The planner admits a cubic listed - /// state (`BindState::argument_samplers`) beside a stage's sampler table only where the stage - /// states this fact (a device that cannot write the buffer from the stage tests nothing, and - /// its stage is refused `NotImplemented(SamplerBicubicFilter)` there). A fragment stage never + /// run that never reaches such a sampler is Metal's exactly. A cubic argument sampler beside a + /// stage's sampler table is Metal's only where the stage states this fact (a device that + /// cannot write the buffer from the stage tests nothing). A fragment stage never /// states it: the mark is a store, which costs a fragment function the device's hidden-surface /// removal and early depth test although it never runs. CubicArgumentSampler { stage: Stage }, @@ -541,49 +536,13 @@ pub enum RuntimeFact { /// The render pipeline was compiled under `VariantKey::quad_primitive_ids`, and its fragment /// function reads `[[primitive_id]]` from Vulkan's `PrimitiveId` shifted right by one /// (`LoweringInputs::quad_primitive_ids`): for a draw of Metal's private quads or quad strip, - /// listed as two triangles a quad. Its plans state the variant the shape asks for - /// (`BindShape::quad_primitive_ids`). + /// listed as two triangles a quad. QuadPrimitiveIds, /// The render pipeline was compiled under `VariantKey::private_list`, and its vertex function /// runs the consumer's list of one of Metal's private primitive types in the pulled list form /// (`LoweringInputs::private_list`): its index and Metal's base vertex read at - /// `PushHole::CaptureIndexAddress`, each list position run once. Its plans state the variant - /// the shape asks for (`BindShape::private_list`). + /// `PushHole::CaptureIndexAddress`, each list position run once. PrivateList, - /// The function reads the texture bound to the slot only as the in-place form of a two-plane - /// YCbCr texture reads it (`bind::YCbCrInPlace`): sampled or gathered through a constexpr sampler - /// or through the runtime sampler slots whose bits `samplers` holds (bit `n` for - /// `[[sampler(n)]]` of the slot's stage), read, or its size queried, as a 2D `float` texture. - /// Recorded on a profile that reads planes in place (`ProfileFields::ycbcr_in_place`). Where - /// the binder binds a texture whose planes are read so (`TextureShape::Texture::ycbcr_in_place`) - /// and each of those samplers states a filter the form reads (one filter for minification and - /// magnification, no anisotropy, no cubic filter, comparison or reduction), the slot joins the - /// plan's variant (`VariantKey::ycbcr_in_place`, `LoweringInputs::ycbcr_in_place`), under - /// which the slot's one binding is the planes' texel buffer (`WriteSource::YCbCrInPlace`) and - /// every access of it reads the codes and converts them as Metal does, its words in the slot's - /// push field (`PushField::YCbCrInPlace`). Elsewhere the slot binds the texture's image as - /// before. `device`: every sample of the slot is one the device's own sampler Y′CbCr - /// conversion takes (none addresses a border through a constexpr sampler or places a texel - /// offset by a parent's size, and none is a gather): where the bound texture's planes are also held as an image it - /// samples (`TextureShape::Texture::ycbcr_planes_sampler`) and each runtime sampler addresses - /// no border on either axis, the slot samples that image instead - /// (`VariantKey::ycbcr_planes_sampled`, `bind::YCbCrPlanesSampler`). - YCbCrInPlace { - slot: SlotRef, - samplers: u32, - device: bool, - }, - /// The function only reads, writes or asks the size of the 2D texture bound to the slot - /// (`bind::TexelRows`): `read` at level 0 or a computed level, `write`, its width, height or - /// level count, `is_null` and a texture fence; no sample, gather, LOD query, atomic, read - /// through a sampler, imageblock slice or access of a level past the first through a storage - /// slot, and no arm of a handle that switches between slots. Where the binder binds a texture - /// whose rows are read and written in place (`TextureShape::Texture::texel_rows`), the slot - /// joins the plan's variant (`VariantKey::texel_rows`, `LoweringInputs::texel_rows`), under - /// which its one binding is a texel buffer over the rows' bytes (`WriteSource::TexelRows`), - /// texel `(x, y)` the view's `first + y · row + x`, those words in the slot's push field - /// (`PushField::TexelRows`). Elsewhere the slot binds the texture's image as before. - TexelRows { slot: SlotRef }, /// The object function runs a partial threadgroup of a `drawMeshThreads` as Metal does /// (`lower::dispatch`'s partial object threadgroups): where its `DispatchRegion` (or a folded /// variant's region record) carries `lower::dispatch::NONUNIFORM`, it answers its @@ -602,8 +561,7 @@ pub enum RuntimeFact { /// The render pipeline was compiled under `VariantKey::region_viewports`, and its vertex /// function stores `ViewportIndex` as `DrawIndex` (`LoweringInputs::region_viewports`): each /// draw of a multi-draw renders through the viewport and scissor at its index, the runtime's - /// draw of a rasterization-rate-mapped pass's regions several at a time. Its plans state the - /// variant the shape asks for (`BindShape::region_viewports`). + /// draw of a rasterization-rate-mapped pass's regions several at a time. RegionViewports, /// The kernel was compiled under `VariantKey::partial_threadgroups` /// (`LoweringInputs::partial_threadgroups`): where its `DispatchRegion` carries @@ -615,11 +573,10 @@ pub enum RuntimeFact { /// The function only reads, writes, updates by a texture atomic or asks the width of the /// texture buffer bound to the slot (`bind::texel_parts`): `read` (not through a sampler), /// `write`, an atomic, `get_width`, `is_null` and a texture fence, on a device that indexes an - /// array of the slot's kind of texel buffer by a `NonUniform` value. Where the binder binds a - /// texture buffer of more texels than one view holds there (`TextureShape::Buffer::parts` - /// past 1), the slot joins the plan's variant (`VariantKey::texel_buffer_parts`, - /// `LoweringInputs::texel_buffer_parts`), under which its binding is an array of the texture - /// buffer's parts, one texel buffer view each. Elsewhere the slot binds one view, which + /// array of the slot's kind of texel buffer by a `NonUniform` value. Where the consumer binds a + /// texture buffer of more texels than one view holds there, the slot takes the variant + /// (`VariantKey::texel_buffer_parts`, `LoweringInputs::texel_buffer_parts`), under which its + /// binding is an array of the texture buffer's parts, one texel buffer view each. Elsewhere the slot binds one view, which /// `maxTexelBufferElements` bounds (`TexelBufferRange`). TexelBufferParts { slot: SlotRef }, /// Under the identity domains, the buffer slot's address, its buffer's `gpuAddress` plus the @@ -738,8 +695,6 @@ impl RuntimeFact { RuntimeFact::ObjectThreadgroupArena { .. } => "ObjectThreadgroupArena", RuntimeFact::QuadPrimitiveIds => "QuadPrimitiveIds", RuntimeFact::PrivateList => "PrivateList", - RuntimeFact::YCbCrInPlace { .. } => "YCbCrInPlace", - RuntimeFact::TexelRows { .. } => "TexelRows", RuntimeFact::PartialObjectThreadgroups => "PartialObjectThreadgroups", RuntimeFact::BorderTexels { .. } => "BorderTexels", RuntimeFact::RegionViewports => "RegionViewports", diff --git a/crates/metal2vulkan/src/pipeline/graphics.rs b/crates/metal2vulkan/src/pipeline/graphics.rs index 72d8e6b7f..ee6be46ef 100644 --- a/crates/metal2vulkan/src/pipeline/graphics.rs +++ b/crates/metal2vulkan/src/pipeline/graphics.rs @@ -56,8 +56,8 @@ pub struct GraphicsState { /// Metal's `maxVertexAmplificationCount` (1 without vertex amplification): a draw with this /// pipeline amplifies each vertex by a count in `[1, max_vertex_amplification_count]`, or, /// above 1, by a larger count too, as plain Metal draws one. Above 1 the pipeline is a - /// multiview pipeline: the consumer creates it, and begins its render pass instance, with the - /// view mask its render plan states (`BindingPlan::views`). + /// multiview pipeline: the consumer creates it, and begins its render pass instance, with a + /// view mask of its amplification count's views. pub max_vertex_amplification_count: u32, /// A stage declares `Layer`: the vertex function chooses its render target slice, or the /// fragment function reads it. Such a pipeline cannot be multiview @@ -267,7 +267,7 @@ impl BandPrimitive { /// stage `TESSELLATION_EVALUATION`: the half extent of the draw's Vulkan viewport 0, its height /// negative as a Y-flipped viewport's is, half the width in framebuffer pixels, and for triangles /// 1 where the draw's front face is `CLOCKWISE` and -1 where it is `COUNTER_CLOCKWISE` (0 for -/// lines; the binder writes it from `BindState::line_band`). Create the pipeline in Vulkan's +/// lines; the consumer writes it per draw). Create the pipeline in Vulkan's /// default tessellation domain origin, `UPPER_LEFT`. #[non_exhaustive] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] diff --git a/crates/metal2vulkan/src/pipeline/link.rs b/crates/metal2vulkan/src/pipeline/link.rs index 51bbce535..48083ad73 100644 --- a/crates/metal2vulkan/src/pipeline/link.rs +++ b/crates/metal2vulkan/src/pipeline/link.rs @@ -36,7 +36,7 @@ //! a code change. Per-stage limits are `select`'s. //! - **Render state** ([`vertex`], [`graphics`]): `VertexInputState` and `GraphicsState` from the //! descriptor, checked against the vertex stage's compiled fetch projection, with the fragment -//! stage's framebuffer fetch over input attachments ([`fetch`]), and the +//! stage's framebuffer fetch over input attachments, 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 diff --git a/crates/metal2vulkan/src/pipeline/lower_inputs.rs b/crates/metal2vulkan/src/pipeline/lower_inputs.rs index 995e4617a..6967d7a39 100644 --- a/crates/metal2vulkan/src/pipeline/lower_inputs.rs +++ b/crates/metal2vulkan/src/pipeline/lower_inputs.rs @@ -132,31 +132,6 @@ pub struct LoweringInputs { /// `PrecisionNote::SrgbTexelDecode`. A slot of no such access is ignored. #[cfg_attr(feature = "serde", serde(default))] pub srgb_textures: BTreeSet, - /// 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 - /// convert them as Metal does (`bind::YCbCrInPlace`). Ignored on a profile that does not read - /// planes in place (`ProfileFields::ycbcr_in_place`). - #[cfg_attr(feature = "serde", serde(default))] - pub ycbcr_in_place: BTreeSet, - /// Slots of [`ycbcr_in_place`](Self::ycbcr_in_place) bound to a texture whose planes are also - /// held as an image the device's own sampler Y′CbCr conversion samples, each with that - /// conversion (`VariantKey::ycbcr_planes_sampled`): each is declared as a combined image - /// sampler whose immutable sampler is the conversion (`ResourceKind::YCbCrPlanes`), and its - /// samples are the device's at level 0 (`bind::YCbCrPlanesSampler`); its size queries read the - /// push field as the in-place form's do. - #[cfg_attr( - feature = "serde", - serde(default, with = "crate::pipeline::serde_pairs") - )] - pub ycbcr_planes_sampled: BTreeMap, - /// Texture slots bound to a 2D texture whose rows are read and written in place - /// (`VariantKey::texel_rows`, `RuntimeFact::TexelRows`): each is declared as a texel buffer of - /// the rows, uniform where the function only reads it and storage where it writes it, its - /// reads and writes of texel `(x, y)` addressing the view's `first + y · row + x` and its size - /// queries reading the slot's push field (`bind::TexelRows`). - #[cfg_attr(feature = "serde", serde(default))] - pub texel_rows: BTreeSet, /// Texture-buffer slots bound to a texture buffer of more texels than one view holds, each /// with its parts (`VariantKey::texel_buffer_parts`, `RuntimeFact::TexelBufferParts`): each is /// declared as an array of that many texel buffers, texel `i` of its reads, writes and atomics diff --git a/crates/metal2vulkan/src/pipeline/mod.rs b/crates/metal2vulkan/src/pipeline/mod.rs index 2a658a1e0..35cd658b4 100644 --- a/crates/metal2vulkan/src/pipeline/mod.rs +++ b/crates/metal2vulkan/src/pipeline/mod.rs @@ -34,9 +34,8 @@ //! decoding; `Device::render_pipeline_key` decodes (but does not lower) the vertex function to //! learn the attributes it reads, and returns [`RenderPipelineKeys`]: the pipeline's key, each //! stage's function key, and the [`LoweringInputs`] each function stage compiles under (see -//! [`cache`](crate::cache)). A binding plan can ask for another variant of the pipeline, named by -//! a [`VariantKey`](crate::cache::VariantKey) (`BindingPlan::variant`, -//! `BindError::NeedsVariant`). A render pipeline's keys under a variant are +//! [`cache`](crate::cache)). Another variant of the pipeline is named by a +//! [`VariantKey`](crate::cache::VariantKey). A render pipeline's keys under a variant are //! `Device::render_variant_key`'s; a compute pipeline compiles its kernel with //! `Device::compile_function` under `VariantKey::lowering_inputs(Stage::Kernel)` and links it as //! `StageSource::Compiled`. @@ -46,7 +45,7 @@ //! kernel compiled on its own for such a pipeline compiles under the same descriptor //! (`LoweringInputs::stage_input`). A dispatch of a kernel that steps an attribute by thread //! position, or reads `[[grid_origin]]` or `[[grid_size]]`, needs the encoder's stage-in region -//! (`BindState::stage_in_region`). A render pipeline whose vertex function is a post-tessellation +//! (`setStageInRegion:`). A render pipeline whose vertex function is a post-tessellation //! vertex function is a tessellation pipeline, under the descriptor's `tessellation` //! ([`TessellationDescriptor`], or Metal's defaults): a synthesized vertex and tessellation //! control stage, the function's evaluation stage, and the fragment stage when rasterization is @@ -55,17 +54,17 @@ //! **Tile pipelines.** `Device::compile_tile_pipeline` compiles a [`TileRenderPipelineDescriptor`] //! into a [`ComputePipeline`]: its tile function compiled under the descriptor's color attachment //! formats (`LoweringInputs::tile_attachments`), which the consumer dispatches over the render -//! area's tiles in place of `dispatchThreadsPerTile:`, with the pass's tile size -//! (`BindState::imageblock_size`) and render area (`BindState::render_area`), and the pass's -//! attachments bound as storage images in the plan's formats (`WriteSource::TileAttachment`: a +//! area's tiles in place of `dispatchThreadsPerTile:`, with the pass's tile size and render area, +//! and the pass's attachments bound as storage images in the interface's formats +//! (`WriteSource::TileAttachment`: a //! float attachment through the unsigned-integer format of its channels, so its bits move). //! //! **Mesh pipelines.** `Device::compile_mesh_pipeline` compiles a [`MeshPipelineDescriptor`] //! into a [`RenderPipeline`] whose stages are its object (`TASK_EXT`), mesh (`MESH_EXT`) and //! fragment stages, with no vertex input; its fragment function reads the mesh function's primitive -//! outputs per primitive (`LoweringInputs::primitive_varyings`). Its plan draws mesh draws +//! outputs per primitive (`LoweringInputs::primitive_varyings`). It draws mesh draws //! (`DrawCall::MeshThreadgroups` and its siblings), each with the specialization of its mesh -//! threadgroup's size (`DrawCommands::specialization`). +//! threadgroup's size. //! //! **Not implemented yet.** The plan of a mesh pipeline with an object function, an object //! function's payload, and a patch draw with a patch index buffer are refused, each as diff --git a/crates/metal2vulkan/src/pipeline/sym.rs b/crates/metal2vulkan/src/pipeline/sym.rs index cb24e6215..dbfebd516 100644 --- a/crates/metal2vulkan/src/pipeline/sym.rs +++ b/crates/metal2vulkan/src/pipeline/sym.rs @@ -213,10 +213,10 @@ pub enum SyntheticBinding { /// `x + y · SpecKey::TileGridWidth`, which the pass keeps across its draws and tile /// dispatches and starts at zero (`RuntimeFact::TileThreadgroupMemory`). TileMemory, - /// The function-table snapshot: a read-only storage buffer of words the binder writes per + /// The function-table snapshot: a read-only storage buffer of words the consumer writes per /// command, holding a null table's record at word 0 and then each listed table's record, its - /// word count and its words ([`FunctionTableSnapshot`](crate::bind::FunctionTableSnapshot)). The stage's - /// function-table directory gives each id the word offset of its table's record. + /// word count and its words. The stage's function-table directory gives each id the word + /// offset of its table's record. FunctionTableSnapshot, } @@ -268,9 +268,9 @@ pub enum ResourceKind { SeparateSampler(SamplerRef), /// 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 - /// image sampler whose immutable sampler is the device's conversion of this - /// (`vk::SamplerDesc::ycbcr`), whose image the consumer views with the same conversion. + /// sampler Y′CbCr conversion samples: a combined image sampler whose immutable sampler is the + /// device's conversion of this (`vk::SamplerDesc::ycbcr`), whose image the consumer views + /// with the same conversion. YCbCrPlanes(crate::bind::YCbCrPlanesSampler), /// The constexpr samplers one heap sampling chooses among by its sampler handle: an array of /// one immutable sampler per candidate, each made for this use (with comparison or without, @@ -335,7 +335,7 @@ pub struct CombinedSampler { pub sampler: SamplerRef, /// The shader hands the binding a pixel sampler's coordinate in texels: its `VkSampler` is /// the device's unnormalized one (`SamplerUse::unnormalized`), and its image a view of the - /// texture's first level alone (`bind::ImageViewDesc::level`). + /// texture's first level alone. #[cfg_attr(feature = "serde", serde(default))] pub unnormalized: bool, /// The shader samples with depth comparison through this binding. @@ -572,11 +572,9 @@ pub enum SpecKey { /// fragment function that reaches its tile's threadgroup memory, the render pass's tile /// height. ImageblockHeight, - /// The width of the render area a tile dispatch covers (`renderTargetWidth`, - /// `BindState::render_area`, default 0). + /// The width of the render area a tile dispatch covers (`renderTargetWidth`, default 0). RenderAreaWidth, - /// The height of the render area a tile dispatch covers (`renderTargetHeight`, - /// `BindState::render_area`, default 0). + /// The height of the render area a tile dispatch covers (`renderTargetHeight`, default 0). RenderAreaHeight, /// Boolean: an out-of-bounds read of the texture bound to the slot reads alpha 1, because its /// pixel format has no alpha component (or is a depth or stencil format, whose missing @@ -668,7 +666,7 @@ pub enum SpecKey { /// texture's map sends them), read by a specialized note's test alone /// ([`SpecTest`](crate::pipeline::SpecTest)): no stage declares it as a constant and no /// pipeline's key carries it, so the bound sampler decides the note without a `VkPipeline` of - /// its own. A plan gives it (`BindingPlan::specialized_value`), and the runtime reads such a + /// its own. The consumer gives it, and the runtime reads such a /// test at each draw or dispatch (`StageModule::precision_notes_bound`); where the sampler is /// not known, such a test /// holds. A slot bound to no sampler takes 0. @@ -680,8 +678,8 @@ pub enum SpecKey { /// where one such is of a form whose linear sample the function filters by the device's /// arithmetic (not a bfloat form, whose sample reads the nearest texel under either filter, /// `PrecisionNote::BicubicFilterArithmetic`): of the heap members of the command reaching the - /// stage, a member it makes resident (`BindShape::used`) or binds at a texture slot of the - /// stage (`bind::heap`'s members), and given by a plan (`BindingPlan::specialized_value`). A + /// stage, a member it makes resident (`useResource:`) or binds at a texture slot of the + /// stage, given by the consumer. A /// texture the command neither names nor makes resident, which a handle loaded from memory may /// still reach and whose read Metal leaves undefined, is not counted. A stage whose `float` /// read, sample, gather or query of a heap may meet such a texture declares it as a constant @@ -761,13 +759,6 @@ pub(crate) struct DispatchKeys { pub multi_region: SpecKey, } -impl DispatchKeys { - /// The axis `key` is the local size of, or `None` for any other key. - pub(crate) fn axis(&self, key: SpecKey) -> Option { - self.local.iter().position(|k| *k == key) - } -} - /// A push-constant field kind, in the fixed placement order (the derived `Ord`). /// /// `select` places a function's fields in this order into the stage's push window and spills the @@ -905,14 +896,12 @@ pub enum PushField { /// The render encoder's viewport count (`u32`, `setViewports:count:`) for a vertex function /// that writes `[[viewport_array_index]]` (`RuntimeFact::ViewportCount`): it stores /// `ViewportIndex` as 0 for an index at or past it. 0 where the encoder never set its - /// viewports, which keeps every index 0, as Metal's one default viewport does - /// (`BindState::viewport_count`). + /// viewports, which keeps every index 0, as Metal's one default viewport does. ViewportCount, /// The render pass's `renderTargetArrayLength` (`u32`) for a vertex function that writes /// `[[render_target_array_index]]` and writes `Layer` (`RuntimeFact::RenderTargetArrayLength` /// without `layer_dropped`): it stores `Layer` as 0 - /// for an index at or past it, as Metal renders the pass's first layer there - /// (`BindState::render_target_array_length`). + /// for an index at or past it, as Metal renders the pass's first layer there. RenderTargetArrayLength, /// The patch index buffer's residual bind offset (`u32`), as `SlotBindOffset`'s: a field of /// a tessellation pipeline's synthesized control stage. @@ -925,8 +914,7 @@ pub enum PushField { /// The draw's band of a pipeline variant that draws its lines as bands /// (`VariantKey::line_band`, `link::band`): one `vec4` of the synthesized evaluation stage's /// own push range, `[sx, sy, h, 0]`, the half extent of the draw's Vulkan viewport 0 (its - /// height negative, as the runtime's viewports are) and half the band's width in pixels - /// (`BindState::line_band`). + /// height negative, as the runtime's viewports are) and half the band's width in pixels. LineBand, /// The stride (`u32`) the compute encoder binds the kernel buffer at this Metal index with /// (`setBuffer:offset:attributeStride:atIndex:` and its forms, its low 32 bits, @@ -937,7 +925,7 @@ pub enum PushField { /// The draw's depth clamp range for a fragment function compiled under /// `LoweringInputs::depth_clamp_range` (`RuntimeFact::DepthClampRange`): one `uvec2` holding /// the bits of two `f32`s, `[low, high]`, which the function clamps the depth it writes to - /// after Metal's `[0, 1]` (`BindState::depth_clamp_range`). + /// after Metal's `[0, 1]`. DepthClampRange, /// The draw's layout for a vertex function compiled in the primitive ID's de-indexed form /// (`LoweringInputs::primitive_id_indices`), a `uvec4`, of a draw run from vertex 0: 0, the @@ -961,25 +949,13 @@ pub enum PushField { /// 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 rotated one's): one `uvec4` - /// holding the four `f32`s' bits as the encoder set them (`BindState::blend_color`). + /// holding the four `f32`s' bits as the encoder set them. HalfBlendColor, /// The render encoder's alpha test reference (`setAlphaTestReferenceValue:`) for a fragment /// function compiled under `LoweringInputs::alpha_test`: one `u32`, the reference's 8-bit - /// unorm code as Metal's alpha test compares it (`bind::alpha_test_code` of - /// `BindState::alpha_test_reference`), which the function compares its color 0's alpha's code - /// with. + /// unorm code as Metal's alpha test compares it (`bind::alpha_test_code` of the reference), + /// which the function compares its color 0's alpha's code with. AlphaTestReference, - /// The planes of the two-plane YCbCr texture bound to the slot, read in place - /// (`RuntimeFact::YCbCrInPlace`, `LoweringInputs::ycbcr_in_place`): two `uvec4`s, the - /// texture's size, its planes' first elements and rows in the slot's texel buffer, and its - /// conversion (`bind::YCbCrInPlace::words`), from the bound texture's facts - /// (`TextureFacts::ycbcr_in_place`). - YCbCrInPlace(SlotRef), - /// The rows of the 2D texture bound to the slot in its texel buffer view, read and written in - /// place (`RuntimeFact::TexelRows`, `LoweringInputs::texel_rows`): one `uvec4`, the texture's - /// width and height, its rows in texels and its first texel in the view - /// (`bind::TexelRows::words`), from the bound texture's facts (`TextureFacts::texel_rows`). - TexelRows(SlotRef), /// Under the identity domains, the sampler a sample takes through a constexpr sampler /// (`SamplerRef::Constexpr`), used as the field's [`CombinedSampler`] states: one `u32`, the /// index (1 to 3,999, `docs/RESOURCE-ID.md`) of the element of the set-1 sampler array of the diff --git a/crates/metal2vulkan/src/spirv/ir/module.rs b/crates/metal2vulkan/src/spirv/ir/module.rs index 2a6a22b6d..bafc87e5f 100644 --- a/crates/metal2vulkan/src/spirv/ir/module.rs +++ b/crates/metal2vulkan/src/spirv/ir/module.rs @@ -1220,8 +1220,8 @@ pub struct Function { pub blocks: Vec, /// `Function`-storage variables, declared at the top of the entry block. pub vars: Vec, - /// Whether the function is a kept routine (`ModuleBuilder::kept_routine`): a linear filter - /// emulation's sum or one combined binding's sample emulation, which `serialize` declares + /// Whether the function is a kept routine (`ModuleBuilder::kept_routine`): one combined + /// binding's sample emulation, which `serialize` declares /// `DontInline`, so a driver that honours the control compiles it once and calls it from each /// site. pub kept: bool, diff --git a/crates/metal2vulkan/src/spirv/serialize/mod.rs b/crates/metal2vulkan/src/spirv/serialize/mod.rs index 3c4fc5327..2b5b0a729 100644 --- a/crates/metal2vulkan/src/spirv/serialize/mod.rs +++ b/crates/metal2vulkan/src/spirv/serialize/mod.rs @@ -14,7 +14,7 @@ //! `?:` arm or a `&&`/`||` operand. A value SPIRV-Cross would forward into its one reader without //! the dependencies of its operands is written the same way (`forwards_without_dependencies`), so //! it is evaluated where the module does, before any later write overwrites what it reads. A kept -//! routine (a texel routine's sum or a sampling routine's emulation) is declared `DontInline`. +//! routine (a sampling routine's emulation) is declared `DontInline`. //! //! Every number link assigns (descriptor set and binding, `Location`/`Component`, `SpecId`) is a //! literal operand of an `OpDecorate`. The serializer writes 0 there and records a relocation diff --git a/crates/metal2vulkan/src/tests/bind_shape_of.rs b/crates/metal2vulkan/src/tests/bind_shape_of.rs deleted file mode 100644 index 68307e49c..000000000 --- a/crates/metal2vulkan/src/tests/bind_shape_of.rs +++ /dev/null @@ -1,95 +0,0 @@ -//! A bind state's shape (`BindState::shape`) over a buffer's bind offsets. - -use crate::bind::{ - ArgumentSampler, BindState, BoundBuffer, BoundSampler, BoundTexture, SamplerDescriptor, - StageTable, TextureFacts, -}; -use crate::metal::{CompareFunction, PixelFormat, SamplerMinMagFilter, TextureType}; -use crate::pipeline::sym::Stage; - -/// A buffer of `length` bytes bound at `offset`. -fn buffer(length: u64, offset: u64) -> BoundBuffer { - BoundBuffer::Buffer { - length, - offset, - gpu_address: 0x1000, - device_address: None, - attribute_stride: None, - } -} - -/// A 2D texture of `format`. -fn texture(format: PixelFormat) -> BoundTexture { - BoundTexture::Texture { - facts: TextureFacts::new(TextureType::Type2D, format), - resource_id: Some(7), - } -} - -/// A sampler that filters linearly where `linear`, and compares where `compares`. -fn sampler(linear: bool, compares: bool) -> SamplerDescriptor { - let mut desc = SamplerDescriptor::new(); - if linear { - desc.min_filter = SamplerMinMagFilter::Linear; - desc.mag_filter = SamplerMinMagFilter::Linear; - } - if compares { - desc.compare_function = CompareFunction::Less; - } - desc -} - -/// The base: a vertex buffer, a fragment texture and sampler, and one argument sampler. -fn base() -> BindState { - let mut state = BindState::default(); - let mut vertex = StageTable::default(); - vertex.buffers.insert(0, buffer(256, 0)); - state.stages.insert(Stage::Vertex, vertex); - let mut fragment = StageTable::default(); - fragment - .textures - .insert(0, texture(PixelFormat::RGBA8Unorm)); - fragment - .samplers - .insert(0, BoundSampler::new(sampler(false, false))); - state.stages.insert(Stage::Fragment, fragment); - state - .argument_samplers - .push(ArgumentSampler::new(sampler(false, false), 1)); - state -} - -/// The base changed by `change`. -fn with(change: impl FnOnce(&mut BindState)) -> BindState { - let mut state = base(); - change(&mut state); - state -} - -/// `state`'s vertex table. -fn vertex(state: &mut BindState) -> &mut StageTable { - state.stages.get_mut(&Stage::Vertex).unwrap() -} - -/// A buffer's bind offset cycling through the multiples of 16 up to 256 keeps one shape: no -/// alignment past 4 is told apart, and no shape is new on a second cycle. -#[test] -fn a_slot_s_offsets_moving_among_multiples_of_16_keep_their_shapes() { - let mut seen = Vec::new(); - for cycle in 0..2 { - for offset in (16..=256).step_by(16) { - let state = with(|s| { - vertex(s).buffers.insert(0, buffer(4096, offset)); - }); - let shape = state.shape(); - if !seen.contains(&shape) { - assert_eq!( - cycle, 0, - "a new shape at offset {offset} on the second cycle" - ); - seen.push(shape); - } - } - } - assert_eq!(seen.len(), 1); -} diff --git a/crates/metal2vulkan/src/tests/constant_blob_footprint.rs b/crates/metal2vulkan/src/tests/constant_blob_footprint.rs index 2e52c8748..4ed16a921 100644 --- a/crates/metal2vulkan/src/tests/constant_blob_footprint.rs +++ b/crates/metal2vulkan/src/tests/constant_blob_footprint.rs @@ -12,7 +12,7 @@ //! of one thread-local read. Its counters are the measuring thread's own: the translation runs on //! its caller's thread, so a measurement holds whether its test runs alone in its process (as //! nextest runs every test) or beside others on libtest's threads (`cargo test`), whose -//! allocations it does not see. Other tests count allocations with it ([`allocations_during`]). +//! allocations it does not see. //! //! `llvm-as` assembles the kernel; without it the test skips visibly. @@ -131,13 +131,6 @@ pub(crate) fn held_during(work: impl FnOnce() -> T) -> (T, u64) { (value, counts.peak.max(0) as u64) } -/// `work`'s result, and the allocations and reallocations it made while it ran (the calling -/// thread's). -pub(crate) fn allocations_during(work: impl FnOnce() -> T) -> (T, u64) { - let (value, counts) = measured(work); - (value, counts.allocations) -} - const DATALAYOUT: &str = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32"; /// Where a kernel's escaping constant is, if it has one ([`blob_kernel`]). diff --git a/crates/metal2vulkan/src/tests/engine_amplification.rs b/crates/metal2vulkan/src/tests/engine_amplification.rs index 76765b27c..5ccbb943b 100644 --- a/crates/metal2vulkan/src/tests/engine_amplification.rs +++ b/crates/metal2vulkan/src/tests/engine_amplification.rs @@ -31,19 +31,10 @@ use std::collections::BTreeMap; use std::path::Path; -use crate::bind::{ - BindState, DrawCall, IndirectRef, PushConstantWrite, VertexAmplification, ViewMapping, - ViewSetup, -}; -use crate::budget::Budget; -use crate::cache::VariantKey; -use crate::device::requirements::{VkFeature as F, VkLimit}; +use crate::device::requirements::VkFeature as F; use crate::device::{Device, DeviceDescription, DevicePolicy, DeviceProfile}; -use crate::error::{BindError, Capability, DescriptorError, Error, Feature, Needs}; -use crate::library::{FunctionArtifact, Library}; -use crate::pipeline::descriptor::{ - FunctionDescriptor, RenderPipelineDescriptor, StageSource, TessellationDescriptor, -}; +use crate::error::{Capability, Error, Feature, Needs}; +use crate::library::FunctionArtifact; use crate::pipeline::facts::RuntimeFact; use crate::pipeline::interface::PushLoc; use crate::pipeline::link::{link, LinkInputs}; @@ -55,7 +46,7 @@ use crate::pipeline::testing::{ compile, engine_dir, fixtures_dir, llvm_assemble, moltenvk_msl_compile, profile, typed_module, typed_module_with, AssembleError, }; -use crate::pipeline::{AmplificationDraws, RenderPipeline}; +use crate::pipeline::AmplificationDraws; use crate::spirv::interp::{run, Buffer, Config, Order, Resources, SubgroupSize}; use crate::spirv::testing::check_words_valid; @@ -87,10 +78,6 @@ fn description(stem: &str) -> DeviceDescription { DeviceDescription::from_khronos_json(&text, None).expect("description") } -fn device(stem: &str) -> Device { - Device::from_queries(description(stem), DevicePolicy::RESIDENT_TABLES).expect("device") -} - /// `nvidia-rtx50-linux` with `features` removed from its description (with `Multiview`, the /// multiview features that need it). fn nvidia_without(features: &[F]) -> Device { @@ -331,604 +318,6 @@ fn each_view_reads_its_amplification_id_and_the_specialized_count() { } } -/// A render pipeline of `vertex` and `fragment` from the fixture with -/// `maxVertexAmplificationCount` `max`. -fn render(bc: &[u8], vertex: &str, fragment: Option<&str>, max: u32) -> RenderPipelineDescriptor { - let lib = Library::from_air(bc).expect("library"); - let stage = |name: &str| { - StageSource::Function(FunctionDescriptor::new( - lib.function(name).expect("function"), - )) - }; - let mut d = RenderPipelineDescriptor::new(stage(vertex)); - d.fragment = fragment.map(stage); - d.max_vertex_amplification_count = max; - d -} - -/// The value of the render plan's `AmplificationCount` constant. -fn planned_count(p: &RenderPipeline, plan: &crate::bind::BindingPlan) -> u32 { - let id = p - .stages - .iter() - .flat_map(|m| m.specialization.constants.iter()) - .find(|c| c.key == SpecKey::AmplificationCount) - .expect("AmplificationCount constant") - .id; - let e = plan - .specialization - .entries - .iter() - .find(|e| e.constant_id == id) - .expect("AmplificationCount entry"); - let at = e.offset as usize; - u32::from_le_bytes( - plan.specialization.data[at..at + 4] - .try_into() - .expect("4 bytes"), - ) -} - -/// The bind state of `count` amplifications with `mappings` (viewport and render target offsets) -/// in a pass of `renderTargetArrayLength` 2. -fn amplified(count: u32, mappings: &[(u32, u32)]) -> BindState { - amplified_in(count, mappings, 2) -} - -/// [`amplified`] in a pass of `renderTargetArrayLength` `length`. -fn amplified_in(count: u32, mappings: &[(u32, u32)], length: u32) -> BindState { - let s = BindState { - render_target_array_length: length, - vertex_amplification: VertexAmplification::new( - count, - mappings - .iter() - .map(|&(viewport, layer)| ViewMapping { - viewport_array_index_offset: viewport, - render_target_array_index_offset: layer, - }) - .collect(), - ), - ..Default::default() - }; - s -} - -/// A pipeline of `maxVertexAmplificationCount` 2 is a multiview pipeline: it requires -/// `multiview` and two views, every stage module passes L3 under those requirements, and a render -/// plan states the draw's views and count from the encoder's amplification. -/// A pipeline of `maxVertexAmplificationCount` 1 takes no view mapping: a count of 1 whose -/// mapping offsets the render target slice or the viewport draws into the first layer through -/// viewport 0, without multiview and as one draw, as Metal draws it (Metal probes on the M3 Max and -/// an M4: a slice offset of 1, and a viewport offset of 1 over two viewports, moved nothing under -/// such a pipeline and moved the draw under one of 2). -#[test] -fn a_pipeline_that_does_not_amplify_takes_no_view_mapping() { - let Some(bc) = fixture() else { return }; - for stem in ["nvidia-rtx50-linux", "lavapipe"] { - let dev = device(stem); - let d = render(&bc, "amp_vertex", Some("amp_fragment"), 1); - let p = dev - .compile_render_pipeline(&d, &Budget::standard()) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - for mappings in [[(0, 2)], [(1, 0)], [(1, 2)]] { - let plan = p - .plan(&dev, &lified_in(1, &mappings, 4).shape()) - .unwrap_or_else(|e| panic!("{stem} {mappings:?}: {e:?}")); - assert_eq!(plan.views, ViewSetup::default(), "{stem} {mappings:?}"); - assert_eq!( - plan.variant.amplification_draws, None, - "{stem} {mappings:?}" - ); - } - } -} - -#[test] -fn an_amplified_render_pipeline_plans_its_views() { - let Some(bc) = fixture() else { return }; - for stem in ["nvidia-rtx50-linux", "lavapipe"] { - let dev = device(stem); - let d = render(&bc, "amp_vertex", Some("amp_fragment"), 2); - let p = dev - .compile_render_pipeline(&d, &Budget::standard()) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - assert_eq!(p.graphics.max_vertex_amplification_count, 2, "{stem}"); - assert!(!p.graphics.declares_layer, "{stem}"); - assert!(p.requirements.features.contains(&F::Multiview), "{stem}"); - assert_eq!( - p.requirements.limits.get(&VkLimit::MaxMultiviewViewCount), - Some(&2), - "{stem}" - ); - for m in &p.stages { - check_words_valid(&m.spirv, &p.requirements, dev.profile()) - .unwrap_or_else(|e| panic!("{stem} {:?}: L3: {e}", m.stage)); - } - - // Metal's default: one amplification, no multiview. - let plan = p.plan(&dev, &BindState::default().shape()).expect("plan"); - assert_eq!(plan.views, ViewSetup::default(), "{stem}"); - assert_eq!(planned_count(&p, &plan), 1, "{stem}"); - // Two amplifications into render target slices 3 and 4 of a pass of 5. - let plan = p - .plan(&dev, &lified_in(2, &[(0, 3), (0, 4)], 5).shape()) - .expect("plan"); - assert_eq!((plan.views.view_mask, plan.views.base_layer), (0b11, 3)); - assert_eq!(planned_count(&p, &plan), 2, "{stem}"); - // Asked to (under a visibility query), the same draws one amplification at a time, and a - // count of 1 stays a draw into one layer. - let mut one_at_a_time = amplified_in(2, &[(0, 3), (0, 4)], 5); - one_at_a_time.vertex_amplification.one_at_a_time = true; - let plan = p.plan(&dev, &one_at_a_time.shape()).expect("plan"); - assert_eq!(plan.views, ViewSetup::default(), "{stem}"); - assert_eq!( - plan.variant.amplification_draws, - Some(AmplificationDraws::new(true, false)), - "{stem}" - ); - let mut one = amplified_in(1, &[(0, 2)], 4); - one.vertex_amplification.one_at_a_time = true; - let plan = p.plan(&dev, &one.shape()).expect("plan"); - assert_eq!((plan.views.view_mask, plan.views.base_layer), (0, 2)); - assert_eq!(plan.variant.amplification_draws, None, "{stem}"); - // One into slice 2 of a pass of 4, without multiview, and into the first layer where the - // offset is at or past the pass's length, as Metal renders it (a Metal probe on an M4). - for (length, base_layer) in [(4, 2), (2, 0), (0, 0)] { - let plan = p - .plan(&dev, &lified_in(1, &[(0, 2)], length).shape()) - .expect("plan"); - assert_eq!( - (plan.views.view_mask, plan.views.base_layer), - (0, base_layer), - "{stem} {length}" - ); - assert_eq!(planned_count(&p, &plan), 1, "{stem}"); - } - - // A count above the maximum draws that many amplifications, as plain Metal draws it - // where its validation stops it (a Metal probe): as views where the device has them, and - // every one into the first slice under `nil` mappings. - let plan = p - .plan(&dev, &lified_in(3, &[(0, 0), (0, 1), (0, 2)], 4).shape()) - .expect("plan"); - assert_eq!((plan.views.view_mask, plan.views.base_layer), (0b111, 0)); - assert_eq!(planned_count(&p, &plan), 3, "{stem}"); - let plan = p.plan(&dev, &lified(3, &[]).shape()).expect("plan"); - assert_eq!(plan.views, ViewSetup::default(), "{stem}"); - assert_eq!(planned_count(&p, &plan), 3, "{stem}"); - // Counts Metal does not draw this pipeline with. - for (count, mappings) in [(0, vec![]), (2, vec![(0, 0)])] { - let err = p - .plan(&dev, &lified(count, &mappings).shape()) - .expect_err("invalid amplification"); - assert!( - matches!(err, BindError::InvalidVertexAmplification { max: 2, .. }), - "{stem} {count} {mappings:?}: {err:?}" - ); - } - // Mappings multiview cannot express draw one amplification at a time: every amplification - // into one slice (`nil`), a viewport offset, slices out of order, and an offset past the - // pass's length, whose amplification renders the first layer. The pipeline compiled without - // the variant does not draw them. - for (count, mappings, viewports) in [ - (2, vec![], false), - (2, vec![(0, 0), (1, 1)], true), - (2, vec![(0, 1), (0, 0)], false), - (2, vec![(0, 1), (0, 2)], false), - ] { - let what = format!("{stem} {count} {mappings:?}"); - let state = amplified(count, &mappings); - let plan = p - .plan(&dev, &state.shape()) - .unwrap_or_else(|e| panic!("{what}: {e:?}")); - assert_eq!(plan.views, ViewSetup::default(), "{what}"); - assert_eq!( - plan.variant.amplification_draws, - Some(AmplificationDraws::new(true, viewports)), - "{what}" - ); - assert_eq!(planned_count(&p, &plan), count, "{what}"); - assert_eq!( - plan.instantiate_draw(&state, &triangle()), - Err(BindError::NeedsVariant { - variant: Box::new(plan.variant.clone()) - }), - "{what}" - ); - } - } -} - -/// A direct draw of one triangle. -fn triangle() -> DrawCall { - DrawCall::Primitives { - vertex_start: 0, - vertex_count: 3, - instance_count: 1, - base_instance: 0, - } -} - -/// What multiview cannot express draws one amplification at a time: more amplifications than the -/// device's views (`lavapipe` has six), and a render target slice a stage chooses or reads, -/// amplified or into another layer than the first. A profile without `multiview` refuses the -/// pipeline, and a maximum of 0 is invalid. -#[test] -fn amplified_render_pipelines_draw_what_multiview_cannot_express_one_at_a_time() { - let Some(bc) = fixture() else { return }; - let budget = Budget::standard(); - let refusal = |r: Result| match r { - Err(Error::Unsupported(u)) => { - assert_eq!(u.feature, Feature::VertexAmplification); - u.needs - } - other => panic!("{other:?}"), - }; - let consecutive = |count: u32| -> Vec<(u32, u32)> { (0..count).map(|a| (0, a)).collect() }; - let lavapipe = device("lavapipe"); - let p = lavapipe - .compile_render_pipeline(&render(&bc, "amp_vertex", None, 8), &budget) - .expect("eight amplifications on six views"); - assert_eq!( - p.requirements.limits.get(&VkLimit::MaxMultiviewViewCount), - Some(&6) - ); - let plan = p - .plan(&lavapipe, &lified_in(6, &consecutive(6), 8).shape()) - .expect("six"); - assert_eq!( - (plan.views.view_mask, plan.views.base_layer), - (0b11_1111, 0) - ); - assert_eq!(plan.variant, VariantKey::new()); - let plan = p - .plan(&lavapipe, &lified_in(8, &consecutive(8), 8).shape()) - .expect("eight"); - assert_eq!(plan.views, ViewSetup::default()); - assert_eq!( - plan.variant.amplification_draws, - Some(AmplificationDraws::new(true, false)) - ); - assert_eq!(planned_count(&p, &plan), 8); - - let dev = device("nvidia-rtx50-linux"); - for (vertex, fragment) in [ - ("amp_vertex_layer", None), - ("amp_vertex", Some("amp_fragment_layer")), - ] { - let p = dev - .compile_render_pipeline(&render(&bc, vertex, fragment, 2), &budget) - .unwrap_or_else(|e| panic!("{vertex} {fragment:?}: {e}")); - assert!(p.graphics.declares_layer, "{vertex} {fragment:?}"); - // At a count of 1 into the first layer the layer is ordinary layered rendering; - // amplified, or into another layer, where Metal adds the offset to the slice chosen and - // read, each amplification is a draw of its own (a multiview pipeline cannot declare - // `Layer`). - let plan = p - .plan(&dev, &BindState::default().shape()) - .unwrap_or_else(|e| panic!("{vertex} {fragment:?}: {e:?}")); - assert_eq!(plan.views, ViewSetup::default(), "{vertex} {fragment:?}"); - assert_eq!( - plan.variant.amplification_draws, None, - "{vertex} {fragment:?}" - ); - for state in [amplified(2, &[(0, 0), (0, 1)]), amplified(1, &[(0, 1)])] { - let plan = p - .plan(&dev, &state.shape()) - .unwrap_or_else(|e| panic!("{vertex} {fragment:?}: {e:?}")); - assert_eq!(plan.views, ViewSetup::default(), "{vertex} {fragment:?}"); - assert_eq!( - plan.variant.amplification_draws, - Some(AmplificationDraws::new(true, false)), - "{vertex} {fragment:?}" - ); - } - } - let without = nvidia_without(&[ - F::Multiview, - F::MultiviewGeometryShader, - F::MultiviewTessellationShader, - ]); - assert_eq!( - refusal(without.compile_render_pipeline(&render(&bc, "amp_vertex", None, 2), &budget)), - Needs::AnyOf(vec![vec![Capability::Feature(F::Multiview)]]) - ); - assert!(matches!( - dev.compile_render_pipeline(&render(&bc, "amp_vertex", None, 0), &budget), - Err(Error::InvalidDescriptor( - DescriptorError::VertexAmplificationCount { count: 0 } - )) - )); -} - -/// The `u32` at push offset `offset` once `writes` are applied in order: the last covering -/// write's. -fn pushed_word<'a>( - writes: impl IntoIterator, - offset: u32, -) -> Option { - let mut word = None; - for w in writes { - let end = w.offset as usize + w.bytes.len(); - if w.offset <= offset && offset as usize + 4 <= end { - let at = (offset - w.offset) as usize; - word = Some(u32::from_le_bytes( - w.bytes[at..at + 4].try_into().expect("4 bytes"), - )); - } - } - word -} - -/// The push offset of each amplification field the stages of `p` read. -fn amplification_fields(p: &RenderPipeline) -> Vec<(Stage, PushField, u32)> { - p.interface - .push - .iter() - .flat_map(|pl| pl.fields.iter().map(move |f| (pl.stage, f))) - .filter(|(_, f)| { - matches!( - f.field, - PushField::AmplificationId - | PushField::AmplificationLayerOffset - | PushField::AmplificationViewportOffset - ) - }) - .map(|(stage, f)| match f.loc { - PushLoc::Push { offset } => (stage, f.field, offset), - other => panic!("{:?} at {other:?}", f.field), - }) - .collect() -} - -/// A plan whose amplification multiview cannot express states the variant that draws one -/// amplification at a time, which the pipeline compiled without it does not draw. Compiled, the -/// variant reads its amplification id from push data in both stages (no `ViewIndex`), adds the -/// mappings' offsets to the viewport the vertex function selects and writes the slice offset as -/// `Layer` in a pass of two layers (none in a pass of one, where a fragment function that reads -/// the slice reads the offset), passes L3, and states `RuntimeFact::AmplificationDraws`. Its plan -/// for the same state settles on itself, and the draw's commands write each amplification's id -/// and offsets in each stage that reads them, the first's in the draw's own push data. -#[test] -fn a_variant_draws_each_amplification_with_its_push_fields() { - let Some(bc) = fixture() else { return }; - let budget = Budget::standard(); - for stem in ["nvidia-rtx50-linux", "lavapipe"] { - let dev = device(stem); - // Each pipeline, and whether its vertex function selects a viewport itself. - for (vertex, fragment, selects) in [ - ("amp_vertex", "amp_fragment", true), - ("amp_vertex", "amp_fragment_layer", true), - ("amp_vertex_layer", "amp_fragment_layer", false), - ] { - let d = render(&bc, vertex, Some(fragment), 4); - let base = dev - .compile_render_pipeline(&d, &budget) - .unwrap_or_else(|e| panic!("{stem} {vertex} {fragment}: {e}")); - for (count, mappings, length) in [ - (3, vec![(1, 1), (0, 0), (2, 1)], 2), - (2, vec![(0, 1), (0, 0)], 1), - (2, vec![], 2), - ] { - let what = format!("{stem} {vertex} {fragment} {count} {mappings:?} {length}"); - let state = amplified_in(count, &mappings, length); - let plan = base - .plan(&dev, &state.shape()) - .unwrap_or_else(|e| panic!("{what}: {e:?}")); - let layered = length > 1; - let viewports = mappings.iter().any(|&(viewport, _)| viewport != 0); - let draws = AmplificationDraws::new(layered, viewports); - assert_eq!(plan.variant.amplification_draws, Some(draws), "{what}"); - let key = plan.variant.clone(); - let keys = dev - .render_variant_key(&d, &key, &budget, &crate::pipeline::StageEntries::new()) - .unwrap_or_else(|e| panic!("{what}: {e}")); - for inputs in [&keys.vertex_inputs, &keys.fragment_inputs] { - let inputs = inputs.as_ref().expect("inputs"); - assert_eq!(inputs.amplification_draws, Some(draws), "{what}"); - } - let p = dev - .compile_render_variant(&d, &key, &budget) - .unwrap_or_else(|e| panic!("{what}: {e}")); - assert_eq!(p.key, keys.pipeline, "{what}"); - for m in &p.stages { - check_words_valid(&m.spirv, &p.requirements, dev.profile()) - .unwrap_or_else(|e| panic!("{what} {:?}: L3: {e}", m.stage)); - } - // No stage reads `ViewIndex`. - assert!( - !p.requirements - .spirv_capabilities - .contains(&SpirvCapability::from_raw(Cap::MultiView as u32)), - "{what}" - ); - assert!( - p.dependencies - .iter() - .any(|d| d.fact == RuntimeFact::AmplificationDraws { layered, viewports }), - "{what}" - ); - assert_eq!(p.graphics.declares_layer, layered, "{what}"); - assert_eq!( - p.graphics.writes_viewport_index, - selects || viewports, - "{what}" - ); - - let plan = p - .plan(&dev, &state.shape()) - .unwrap_or_else(|e| panic!("{what}: {e:?}")); - assert_eq!(plan.variant, key, "{what}"); - assert_eq!(plan.views, ViewSetup::default(), "{what}"); - let commands = plan - .instantiate_draw(&state, &triangle()) - .unwrap_or_else(|e| panic!("{what}: {e:?}")); - assert_eq!(commands.amplifications.len(), count as usize, "{what}"); - let fields = amplification_fields(&p); - for stage in [Stage::Vertex, Stage::Fragment] { - assert!( - fields - .iter() - .any(|&(s, f, _)| s == stage && f == PushField::AmplificationId), - "{what} {stage:?}: {fields:?}" - ); - } - let mapping = |a: u32| mappings.get(a as usize).copied().unwrap_or((0, 0)); - for a in 0..count { - let (viewport, layer) = mapping(a); - for &(stage, field, offset) in &fields { - let want = match field { - PushField::AmplificationId => a, - PushField::AmplificationLayerOffset => layer, - _ => viewport, - }; - let writes = commands - .push_constants - .iter() - .chain(&commands.amplifications[a as usize]); - assert_eq!( - pushed_word(writes, offset), - Some(want), - "{what} amplification {a} {stage:?} {field:?}" - ); - if a == 0 { - assert_eq!( - pushed_word(&commands.push_constants, offset), - Some(want), - "{what} {stage:?} {field:?}" - ); - } - } - } - } - } - } -} - -/// The variant's layered `Layer` needs `shaderOutputLayer`, which `runtime-floor` without it (below -/// the runtime's floor) lacks; and a tessellation pipeline is drawn amplified only as views -/// (`lavapipe` has `multiviewTessellationShader`). -#[test] -fn amplification_draws_refuse_what_the_variant_cannot_be() { - let Some(bc) = fixture() else { return }; - let budget = Budget::standard(); - let dev = below_the_floor(); - let d = render(&bc, "amp_vertex_store", None, 2); - let p = dev.compile_render_pipeline(&d, &budget).expect("base"); - let state = amplified(2, &[(0, 1), (0, 0)]); - let plan = p.plan(&dev, &state.shape()).expect("plan"); - match dev.compile_render_variant(&d, &plan.variant, &budget) { - Err(Error::Unsupported(u)) => { - assert_eq!(u.feature, Feature::VertexAmplification); - assert_eq!(u.needs, output_layer()); - } - other => panic!("{:?}", other.map(|_| ())), - } - - let dev = device("lavapipe"); - let mut d = render(&bc, "amp_post_tessellation", None, 2); - d.tessellation = Some(TessellationDescriptor::default()); - let p = dev - .compile_render_pipeline(&d, &budget) - .expect("tessellation pipeline"); - let plan = p - .plan(&dev, &lified(2, &[(0, 0), (0, 1)]).shape()) - .expect("views"); - assert_eq!(plan.views.view_mask, 0b11); - match p.plan(&dev, &lified(2, &[(0, 1), (0, 0)]).shape()) { - Err(BindError::Unsupported(u)) => { - assert_eq!(u.feature, Feature::VertexAmplification); - assert_eq!(u.needs, Needs::NotImplemented); - } - other => panic!("{:?}", other.map(|_| ())), - } -} - -/// `runtime-floor` without `shaderOutputLayer`, which the runtime's floor requires: a device below -/// the floor, with neither the output nor `geometryShader`. -fn below_the_floor() -> Device { - let mut desc = description("runtime-floor"); - assert!(desc.features.remove(&F::ShaderOutputLayer)); - assert!(!desc.features.contains(&F::GeometryShader)); - Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device") -} - -/// What a variant that stores a layered amplification's slice needs on a device without -/// `shaderOutputLayer`: the feature. -fn output_layer() -> Needs { - Needs::AnyOf(vec![vec![Capability::Feature(F::ShaderOutputLayer)]]) -} - -/// On a profile without `shaderOutputLayer`, every amplified draw is drawn as Metal or refused -/// typed, never drawn into another slice: as views where multiview draws Metal's answer; one -/// amplification at a time in a pass of one layer or none, whose variant writes no `Layer` and -/// carries no geometry stage (every amplification renders the pass's one layer, as Metal's do: -/// Metal probe case `amp2_len1` on the M3 Max and an M4); and in a pass of more layers, whose -/// variant must store the amplification's slice as `Layer`, `Unsupported(VertexAmplification)` -/// needing the feature, `geometryShader` or not (`runtime-floor` and `lavapipe`, each without -/// `shaderOutputLayer`). -#[test] -fn a_profile_without_shader_output_layer_draws_or_refuses_every_amplification() { - let Some(bc) = fixture() else { return }; - let budget = Budget::standard(); - let mut lavapipe = description("lavapipe"); - assert!(lavapipe.features.remove(&F::ShaderOutputLayer)); - assert!(lavapipe.features.contains(&F::GeometryShader)); - let lavapipe = Device::from_queries(lavapipe, DevicePolicy::RESIDENT_TABLES).expect("device"); - for (stem, dev) in [ - ("runtime-floor without shaderOutputLayer", below_the_floor()), - ("lavapipe without shaderOutputLayer", lavapipe), - ] { - let d = render(&bc, "amp_vertex_store", None, 2); - let p = dev.compile_render_pipeline(&d, &budget).expect("base"); - let (mut views, mut drawn, mut refused) = (0, 0, 0); - for length in 0..4 { - for mappings in [ - vec![(0, 0), (0, 1)], - vec![(0, 1), (0, 2)], - vec![(0, 1), (0, 0)], - vec![(0, 0), (0, 2)], - vec![(0, 0), (0, 0)], - vec![], - ] { - let what = format!("{stem} {mappings:?} in a pass of {length} layers"); - let plan = p - .plan(&dev, &lified_in(2, &mappings, length).shape()) - .unwrap_or_else(|e| panic!("{what}: {e:?}")); - let Some(draws) = plan.variant.amplification_draws else { - assert_ne!(plan.views.view_mask, 0, "{what}"); - views += 1; - continue; - }; - assert_eq!(draws.layered, length > 1, "{what}"); - match dev.compile_render_variant(&d, &plan.variant, &budget) { - Ok(variant) => { - assert!(!draws.layered, "{what}: compiled"); - assert!(!variant.graphics.declares_layer, "{what}"); - drawn += 1; - for m in &variant.stages { - check_words_valid(&m.spirv, &variant.requirements, dev.profile()) - .unwrap_or_else(|e| panic!("{what} {:?}: L3: {e}", m.stage)); - } - } - Err(Error::Unsupported(u)) => { - assert!(draws.layered, "{what}: refused"); - assert_eq!(u.feature, Feature::VertexAmplification, "{what}"); - assert_eq!(u.needs, output_layer(), "{what}"); - refused += 1; - } - Err(e) => panic!("{what}: {e}"), - } - } - } - assert!( - views > 0 && drawn > 0 && refused > 0, - "{stem}: {views} {drawn} {refused}" - ); - } -} - #[test] fn each_amplification_draw_reads_its_pushed_id() { let Some(bc) = fixture() else { return }; @@ -990,70 +379,3 @@ fn each_amplification_draw_reads_its_pushed_id() { } assert_eq!(words(&out), want); } - -/// A multiview draw keeps its last instance index within `maxMultiviewInstanceIndex` -/// (`VUID-vkCmdDraw-maxMultiviewInstanceIndex-02688`; `nvidia-rtx50-linux` reports 2^27 - 1), and an -/// indirect one asks for the CPU read of its arguments; a draw without multiview is unaffected. -#[test] -fn multiview_draws_keep_their_instances_within_the_limit() { - let Some(bc) = fixture() else { return }; - let dev = device("nvidia-rtx50-linux"); - let p = dev - .compile_render_pipeline( - &render(&bc, "amp_vertex", Some("amp_fragment"), 2), - &Budget::standard(), - ) - .expect("pipeline"); - let draw = |instance_count: u32, base_instance: u32| DrawCall::Primitives { - vertex_start: 0, - vertex_count: 3, - instance_count, - base_instance, - }; - let indirect = DrawCall::Indirect { - indirect: IndirectRef { - token: 7, - offset: 0, - }, - indexed: None, - }; - let limit = (1u32 << 27) - 1; - - let two = amplified(2, &[(0, 0), (0, 1)]); - let plan = p.plan(&dev, &two.shape()).expect("plan"); - assert_ne!(plan.views.view_mask, 0); - plan.instantiate_draw(&two, &draw(1, limit)) - .expect("last instance at the limit"); - plan.instantiate_draw(&two, &draw(0, u32::MAX)) - .expect("no instances"); - match plan.instantiate_draw(&two, &draw(1, 1 << 27)) { - Err(BindError::Unsupported(u)) => { - assert_eq!(u.feature, Feature::VertexAmplification); - assert_eq!( - u.needs, - Needs::AnyOf(vec![vec![Capability::Limit { - limit: VkLimit::MaxMultiviewInstanceIndex, - required: 1 << 27, - available: u64::from(limit), - }]]) - ); - } - other => panic!("{other:?}"), - } - assert!( - plan.instantiate_draw(&two, &indirect) - .expect("indirect") - .indirect_needs_arguments - ); - - let one = BindState::default(); - let plan = p.plan(&dev, &one.shape()).expect("plan"); - plan.instantiate_draw(&one, &draw(1, 1 << 27)) - .expect("not multiview"); - assert!( - !plan - .instantiate_draw(&one, &indirect) - .expect("indirect") - .indirect_needs_arguments - ); -} diff --git a/crates/metal2vulkan/src/tests/engine_argument_tables.rs b/crates/metal2vulkan/src/tests/engine_argument_tables.rs index 1b3adc4e7..dc9335c7b 100644 --- a/crates/metal2vulkan/src/tests/engine_argument_tables.rs +++ b/crates/metal2vulkan/src/tests/engine_argument_tables.rs @@ -22,34 +22,18 @@ use std::path::Path; -use crate::bind::{ - ArgumentFunctionTable, BindState, DescriptorBytes, Dispatch, FunctionTableSnapshot, - FunctionTableWords, HeapPlacement, WriteSource, -}; -use crate::budget::{Budget, SPIRV_WORDS}; -use crate::cache::VariantKey; -use crate::device::profile::BufferAccess; +use crate::budget::SPIRV_WORDS; use crate::device::{Device, DeviceDescription, DevicePolicy, DeviceProfile}; -use crate::error::{Error, Feature}; -use crate::library::{FunctionConstantValues, Library}; +use crate::error::Error; +use crate::library::FunctionConstantValues; use crate::lower::access::function_table::{directory_symbol, snapshot_symbol}; use crate::lower::select::LowerInputs; -use crate::memory::handles::TABLE_ENTRY_BYTES; use crate::pipeline::compile::{compile_bitcode_linked, EntryRef, LinkedSource}; -use crate::pipeline::facts::RuntimeFact; -use crate::pipeline::layout::BindingSource; -use crate::pipeline::sym::{ResourceKind, ResourceSlot, Stage, SyntheticBinding}; +use crate::pipeline::sym::Stage; use crate::pipeline::testing::{ - engine_dir, link_and_validate, llvm_assemble, meter, typed_module_linked, AssembleError, + engine_dir, link_and_validate, llvm_assemble, meter, AssembleError, }; -use crate::pipeline::{ - ComputePipeline, ComputePipelineDescriptor, FunctionDescriptor, FunctionHandle, LinkedFunction, - LinkedFunctions, StageSource, -}; -use crate::spirv::interp::{run, Buffer, Config, Resources}; -use crate::spirv::ir::TypedModule; use crate::spirv::testing::committed_profiles; -use crate::vk; const CALLER: &str = "uni_argument_tables"; const FUNCTIONS: &str = "visible_table_functions"; @@ -63,16 +47,6 @@ const KERNELS: [&str; 3] = [ONE, ARRAY, SELECT]; /// The table's type's functions, then one of another type, in the order the tests link them. const LINKED: [&str; 4] = ["table_add", "table_mul", "table_sub", "table_half"]; -/// The listed tables' resource ids (`T`'s high word is nonzero), and one no table has. -const T: u64 = 0x1_0000_0010; -const U: u64 = 0x20; -const E: u64 = 0x30; -const UNKNOWN: u64 = 0x40; - -/// The tables' entries, by function in [`LINKED`] order (`None` a null entry). -const T_ENTRIES: [Option; 5] = [Some(0), Some(1), None, Some(2), Some(3)]; -const U_ENTRIES: [Option; 2] = [Some(2), Some(0)]; - /// The fixture `stem` assembled. fn fixture(stem: &str) -> Option> { match llvm_assemble(&engine_dir().join(format!("{stem}.ll"))) { @@ -170,599 +144,3 @@ pub(super) fn device(stem: &str) -> Device { let desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device") } - -/// The pipeline of kernel `entry` with the four functions linked, through the public API. -fn pipeline(dev: &Device, caller: &[u8], functions: &[u8], entry: &str) -> ComputePipeline { - let caller = Library::from_air(caller).expect("library"); - let lib = Library::from_air(functions).expect("library"); - let linked = LINKED.iter().fold(LinkedFunctions::new(), |l, name| { - l.with_function(lib.function(name).expect("function")) - }); - let d = ComputePipelineDescriptor::new(StageSource::Function( - FunctionDescriptor::new(caller.function(entry).expect("entry")).with_linked(linked), - )); - dev.compile_compute_pipeline(&d, &Budget::standard()) - .expect("pipeline") -} - -/// The handles of the four linked functions, in [`LINKED`] order, through the public API. -fn handles(functions: &[u8]) -> Vec { - let lib = Library::from_air(functions).expect("library"); - let linked = LINKED.iter().fold(LinkedFunctions::new(), |l, name| { - l.with_function(lib.function(name).expect("function")) - }); - LINKED - .iter() - .map(|name| { - linked - .function_handle(&LinkedFunction::new(lib.function(name).expect("function"))) - .expect("a handle") - }) - .collect() -} - -/// The words of a table holding `entries`. -fn table_bytes(handles: &[FunctionHandle], entries: &[Option]) -> Vec { - let mut t = FunctionTableWords::new(entries.len() as u32); - for (i, e) in entries.iter().enumerate() { - assert!(t.set(i as u32, e.map(|f| handles[f]))); - } - t.to_bytes() -} - -/// The bind state listing `T`, `U`, and `E` (elements 1, 2, 3; snapshot offsets 1, 9, 14). -fn state() -> BindState { - BindState { - function_tables: [(T, T_ENTRIES.len()), (U, U_ENTRIES.len()), (E, 0)] - .map(|(id, size)| ArgumentFunctionTable { - resource_id: id, - size: size as u32, - address: 0, - }) - .to_vec(), - ..Default::default() - } -} - -pub(super) fn one_group() -> Dispatch { - Dispatch::Threadgroups { - groups: [1, 1, 1], - threads_per_group: [1, 1, 1], - } -} - -/// The `(set, binding)` of the pipeline's kernel synthetic binding `binding`. -fn synthetic(p: &ComputePipeline, binding: SyntheticBinding) -> Option<(u32, u32)> { - p.layout.sets[0] - .bindings - .iter() - .find(|b| { - matches!( - b.source, - BindingSource::Synthetic { binding: found, .. } if found == binding - ) - }) - .map(|b| (0, b.binding)) -} - -/// The `(set, binding)` of the pipeline's kernel function-table directory. -pub(super) fn directory_binding(p: &ComputePipeline) -> (u32, u32) { - synthetic(p, SyntheticBinding::FunctionTableDirectory).expect("a function-table directory") -} - -/// The bytes at `(set, binding)` of `bytes`. -pub(super) fn bytes_at(bytes: &[DescriptorBytes], (set, binding): (u32, u32)) -> &[u8] { - &bytes - .iter() - .find(|b| b.set == set && b.binding == binding) - .expect("directory bytes") - .bytes -} - -/// The entries `(id, element, flags)` of a directory's bytes. -fn entries(bytes: &[u8]) -> Vec<(u64, u32, u32)> { - bytes - .chunks(TABLE_ENTRY_BYTES as usize) - .map(|e| { - let w = |i: usize| u32::from_le_bytes(e[4 * i..4 * i + 4].try_into().expect("word")); - (u64::from(w(0)) | (u64::from(w(1)) << 32), w(2), w(3)) - }) - .collect() -} - -/// On every device the kernel's snapshot is `FunctionTableSnapshot`, and its directory, a handle -/// table of the class's entries, gives each listed nonzero id its record's word offset in the -/// snapshot of the listed sizes, whatever the heap placement. Up to 15 listed tables keep the -/// class; a 16th leaves it, and a dispatch of the old plan over it is refused. -#[test] -fn the_plan_writes_the_snapshot_and_its_directory() { - let Some((caller, functions)) = fixtures() else { - return; - }; - for stem in ["runtime-floor", "moltenvk-m3"] { - let dev = device(stem); - let pipe = pipeline(&dev, &caller, &functions, ONE); - let snapshot = - synthetic(&pipe, SyntheticBinding::FunctionTableSnapshot).expect("a snapshot"); - let directory = directory_binding(&pipe); - let mut state = state(); - state.function_tables.push(ArgumentFunctionTable { - resource_id: 0, - size: 4, - address: 0, - }); - let plan = pipe.plan(&dev, &state.shape()).expect("plan"); - let write = |at: (u32, u32)| { - plan.descriptors - .iter() - .find(|d| (d.set, d.binding) == at) - .map(|d| (d.ty, d.source.clone())) - .expect("a write") - }; - assert_eq!( - write(snapshot), - ( - vk::DescriptorType::STORAGE_BUFFER, - WriteSource::FunctionTableSnapshot - ), - "{stem}" - ); - assert_eq!( - write(directory).1, - WriteSource::HandleTable { - stage: Stage::Kernel, - bytes_len: 16 * TABLE_ENTRY_BYTES, - }, - "{stem}" - ); - // `T` (5 entries) at 1, `U` (2) at 1 + 8, `E` (0) at 9 + 5; the id-less table is placed - // after them but named by nothing. - let layout = FunctionTableSnapshot::of(state.function_tables.iter().map(|f| f.size)) - .expect("snapshot"); - assert_eq!(layout.offsets(), [1, 9, 14, 17], "{stem}"); - let mut want = vec![(0, 0, 0); 13]; - want.extend([(U, 9, 0), (E, 14, 0), (T, 1, 0)]); - for placement in [HeapPlacement::Planned, HeapPlacement::ResourceId] { - state.heap_placement = placement; - let cmds = plan - .instantiate_dispatch(&state, &one_group()) - .expect("dispatch"); - assert_eq!( - entries(bytes_at(&cmds.descriptor_bytes, directory)), - want, - "{stem} {placement:?}" - ); - } - let mut sixteen = state.clone(); - sixteen - .function_tables - .extend((0..12).map(|i| ArgumentFunctionTable { - resource_id: 0x100 + i, - size: 1, - address: 0, - })); - assert_ne!(sixteen.shape(), state.shape(), "{stem}"); - assert!(plan.instantiate_dispatch(&sixteen, &one_group()).is_err()); - } -} - -/// Where a dispatch's tables' words are. -#[derive(Clone, Copy)] -enum Words<'a> { - /// The stage's function-table snapshot holds these bytes. - Snapshot(&'a [u8]), - /// These words lie at these device addresses. - Addressed(&'a [(u64, Vec)]), -} - -/// Run `m` over `n` threads with `args` at buffer 1, the directory `directory`, and the tables' -/// `words`: the words it writes. -fn dispatch( - m: &TypedModule, - n: u32, - args: Vec, - directory: &[u8], - words: Words<'_>, -) -> Vec { - let buffer = |slot: ResourceSlot, bytes: Vec| Buffer { - slot: Some(slot), - address: None, - bytes, - }; - let slot = |index| ResourceSlot { - stage: Stage::Kernel, - kind: ResourceKind::Buffer, - index, - }; - let mut buffers = vec![ - buffer(slot(0), vec![0; n as usize * 4]), - buffer(slot(1), args), - buffer(directory_symbol(Stage::Kernel), directory.to_vec()), - ]; - match words { - Words::Snapshot(bytes) => { - buffers.push(buffer(snapshot_symbol(Stage::Kernel), bytes.to_vec())); - } - Words::Addressed(tables) => { - buffers.extend(tables.iter().map(|(address, bytes)| Buffer { - slot: None, - address: Some(*address), - bytes: bytes.clone(), - })); - } - } - let res = Resources { - buffers, - push: vec![0; 128], - spec: Default::default(), - }; - let cfg = Config { - workgroups: [n, 1, 1], - ..Config::default() - }; - let out = run(m, &cfg, res).unwrap_or_else(|e| panic!("{e:?}")); - out.buffers[0] - .as_chunks::<4>() - .0 - .iter() - .map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]])) - .collect() -} - -/// What Metal answers for entry `i` of the table whose id is `id`, called with `(tid, k)`. -fn expect(id: u64, i: u32, tid: u32, k: u32) -> u32 { - let entries: &[Option] = match id { - T => &T_ENTRIES, - U => &U_ENTRIES, - E => &[], - _ => return 0xffff_ffff, - }; - if entries.is_empty() { - return 0xffff_fffe; - } - match entries[i as usize % entries.len()] { - None => 0xffff_fffd, - Some(0) => tid.wrapping_add(k), - Some(1) => tid.wrapping_mul(k), - Some(2) => tid.wrapping_sub(k), - // A function of another type: the default, zero. - Some(_) => 0, - } -} - -fn ids(list: &[u64]) -> Vec { - list.iter().flat_map(|id| id.to_le_bytes()).collect() -} - -/// The directory bytes a dispatch of kernel [`ONE`] gets with [`state`]'s tables listed, planned -/// on the device of profile `stem`. -fn directory_of(stem: &str, caller: &[u8], functions: &[u8]) -> Vec { - let dev = device(stem); - let pipe = pipeline(&dev, caller, functions, ONE); - let directory = directory_binding(&pipe); - let state = state(); - let plan = pipe.plan(&dev, &state.shape()).expect("plan"); - let cmds = plan - .instantiate_dispatch(&state, &one_group()) - .expect("dispatch"); - bytes_at(&cmds.descriptor_bytes, directory).to_vec() -} - -/// On every committed profile, each kernel calls the entry the table its argument buffer names -/// holds, through the snapshot of the tables' words and the binder's directory of their offsets -/// there: a listed table by its id (the high word too), a null entry, an empty table, and a null -/// table for the null id and for an id no listed table has. -#[test] -fn an_argument_table_call_calls_the_entry_its_table_holds() { - let Some((caller, functions)) = fixtures() else { - return; - }; - let h = handles(&functions); - let tables = [ - table_bytes(&h, &T_ENTRIES), - table_bytes(&h, &U_ENTRIES), - table_bytes(&h, &[]), - ]; - let snapshot = FunctionTableSnapshot::of(state().function_tables.iter().map(|f| f.size)) - .expect("snapshot") - .bytes(tables.iter().map(Vec::as_slice)) - .expect("snapshot bytes"); - let none = FunctionConstantValues::defaults(); - let linked = sources(&functions, &none); - const N: u32 = 40; - let words = Words::Snapshot(&snapshot); - for (stem, p) in committed_profiles().expect("profiles") { - let directory = &directory_of(&stem, &caller, &functions); - let module = |entry| { - typed_module_linked(&caller, entry, &p, &linked) - .unwrap_or_else(|e| panic!("{stem} {entry}: {e}")) - .1 - }; - let one = module(ONE); - for id in [T, U, E, 0, UNKNOWN] { - let want: Vec = (0..N).map(|tid| expect(id, tid, tid, 3)).collect(); - assert_eq!( - dispatch(&one, N, ids(&[id]), directory, words), - want, - "{stem} {ONE} {id:#x}" - ); - } - let array = module(ARRAY); - for pair in [[T, U], [E, UNKNOWN]] { - let mut args = vec![0; 8]; - args.extend(ids(&pair)); - let want: Vec = (0..N) - .map(|tid| expect(pair[(tid & 1) as usize], tid >> 1, tid, 5)) - .collect(); - assert_eq!( - dispatch(&array, N, args, directory, words), - want, - "{stem} {ARRAY} {pair:x?}" - ); - } - let select = module(SELECT); - for [a, b] in [[U, T], [0, E]] { - let want: Vec = (0..N) - .map(|tid| { - let id = if tid & 1 != 0 { a } else { b }; - expect(id, tid >> 1, tid, 7) - }) - .collect(); - assert_eq!( - dispatch(&select, N, ids(&[a, b]), directory, words), - want, - "{stem} {SELECT} {a:#x} {b:#x}" - ); - } - } -} - -/// A state listing no table: the directory holds only null entries, so every id reads the null -/// table. -#[test] -fn without_listed_tables_every_id_reads_the_null_table() { - let Some((caller, functions)) = fixtures() else { - return; - }; - let dev = device("moltenvk-m3"); - let pipe = pipeline(&dev, &caller, &functions, ONE); - let directory = directory_binding(&pipe); - let state = BindState::default(); - let plan = pipe.plan(&dev, &state.shape()).expect("plan"); - let cmds = plan - .instantiate_dispatch(&state, &one_group()) - .expect("dispatch"); - let directory = bytes_at(&cmds.descriptor_bytes, directory).to_vec(); - assert_eq!(entries(&directory), vec![(0, 0, 0); 16]); - let none = FunctionConstantValues::defaults(); - let linked = sources(&functions, &none); - let p = crate::pipeline::testing::profile("moltenvk-m3", DevicePolicy::RESIDENT_TABLES) - .expect("profile"); - let (_, one) = typed_module_linked(&caller, ONE, &p, &linked).expect("module"); - let null = FunctionTableSnapshot::of([]) - .expect("snapshot") - .bytes([]) - .expect("snapshot bytes"); - for id in [T, 0] { - assert_eq!( - dispatch(&one, 4, ids(&[id]), &directory, Words::Snapshot(&null)), - [0xffff_ffff; 4], - "{id:#x}" - ); - } -} - -/// The bind state listing `T`, `U` and `E`, and a table of `2^25 + 64` entries, whose words -/// (and their snapshot) pass 128 MiB, lavapipe's `maxStorageBufferRange` and Vulkan's least. -fn wide_state() -> BindState { - let mut s = state(); - s.function_tables.push(ArgumentFunctionTable { - resource_id: 0x50, - size: (1 << 25) + 64, - address: 0, - }); - s -} - -/// `state`'s tables, each at a device address whose high word is its list position plus one. -fn at_addresses(mut state: BindState) -> BindState { - for (i, t) in state.function_tables.iter_mut().enumerate() { - t.address = ((i as u64 + 1) << 32) | 0x40; - } - state -} - -/// The lowering inputs of the variant that reads tables at their addresses. -fn addressed_inputs() -> LowerInputs { - let mut key = VariantKey::new(); - key.addressed_function_tables = true; - key.lowering_inputs(Stage::Kernel) -} - -/// Kernel `entry` with the four functions linked, compiled to read its tables at their device -/// addresses (`VariantKey::addressed_function_tables`), through the public API. -fn addressed_pipeline( - dev: &Device, - caller: &[u8], - functions: &[u8], - entry: &str, -) -> Result { - let caller = Library::from_air(caller).expect("library"); - let lib = Library::from_air(functions).expect("library"); - let linked = LINKED.iter().fold(LinkedFunctions::new(), |l, name| { - l.with_function(lib.function(name).expect("function")) - }); - let f = FunctionDescriptor::new(caller.function(entry).expect("entry")).with_linked(linked); - let compiled = dev.compile_function(&f, &addressed_inputs(), &Budget::standard())?; - let d = ComputePipelineDescriptor::new(StageSource::Compiled(compiled)); - dev.compile_compute_pipeline(&d, &Budget::standard()) -} - -/// Whether `e` is `Unsupported{BufferRange}` naming device addresses. -fn needs_device_addresses(e: &Error) -> bool { - matches!(e, Error::Unsupported(u) if u.feature == Feature::BufferRange) -} - -/// A shape whose listed tables may pass the device's `maxStorageBufferRange` (lavapipe's 128 MiB) -/// asks for the variant that reads them at their device addresses, on a device with device -/// addresses; tables below 128 MiB, which every device's range reaches, ask for none, nor do they -/// where the range is 4 GiB. The variant declares the directory alone (no snapshot) and states `FunctionTableRange` with `addressed`; its plan keeps the key whatever the -/// shape, and writes each listed table's address into the directory, low word as the element and -/// high word as the flags. A listed table without an address is refused, as is a directory that -/// lists no table (its null entry's loads take a listed table's address). Without device addresses -/// (the Vulkan 1.2 floors) such a shape keeps the whole-bound words, as before the variant, whose -/// consumer refuses a table that passes the range where it binds it (the shape's class cannot tell -/// one that fits), and the variant does not compile. -#[test] -fn tables_past_the_storage_range_are_read_at_their_addresses() { - let Some((caller, functions)) = fixtures() else { - return; - }; - let wide = wide_state(); - assert_eq!(state().shape().function_tables.bytes_class, 0); - assert_eq!(wide.shape().function_tables.bytes_class, 28); - for stem in ["gate-lavapipe", "moltenvk-m3", "runtime-floor"] { - let dev = device(stem); - let addressed = dev.profile().fields().buffer_access == BufferAccess::Addressed; - let limit = dev.profile().fields().limits.max_storage_buffer_range; - let passes = wide.shape().function_tables.may_pass(limit); - assert_eq!(passes, limit < 1 << 28, "{stem}"); - let pipe = pipeline(&dev, &caller, &functions, ONE); - let small = pipe.plan(&dev, &state().shape()).expect("plan"); - assert!(!small.variant.addressed_function_tables, "{stem}"); - let plan = pipe.plan(&dev, &wide.shape()).expect("plan"); - assert_eq!( - plan.variant.addressed_function_tables, - addressed && passes, - "{stem}" - ); - let compiled = addressed_pipeline(&dev, &caller, &functions, ONE); - if !addressed { - let e = compiled.map(|_| ()).expect_err("no device addresses"); - assert!(needs_device_addresses(&e), "{stem}: {e:?}"); - continue; - } - let compiled = compiled.unwrap_or_else(|e| panic!("{stem}: {e}")); - assert_eq!( - synthetic(&compiled, SyntheticBinding::FunctionTableSnapshot), - None, - "{stem}" - ); - assert!(compiled - .dependencies - .iter() - .any(|d| d.fact == RuntimeFact::FunctionTableRange { addressed: true })); - let directory = directory_binding(&compiled); - for listed in [state(), wide.clone()] { - let plan = compiled.plan(&dev, &listed.shape()).expect("plan"); - assert!(plan.variant.addressed_function_tables, "{stem}"); - let cmds = plan - .instantiate_dispatch(&at_addresses(listed.clone()), &one_group()) - .expect("dispatch"); - let mut want: Vec<(u64, u32, u32)> = vec![(0, 0, 0); 16 - listed.function_tables.len()]; - want.extend([(U, 0x40, 2), (E, 0x40, 3)]); - if listed.function_tables.len() == 4 { - want.push((0x50, 0x40, 4)); - } - want.push((T, 0x40, 1)); - assert_eq!( - entries(bytes_at(&cmds.descriptor_bytes, directory)), - want, - "{stem}" - ); - assert!(plan.instantiate_dispatch(&listed, &one_group()).is_err()); - } - // A directory of null entries alone: their loads would have no listed table's address. - let none = BindState::default(); - let plan = compiled.plan(&dev, &none.shape()).expect("plan"); - assert!(plan.variant.addressed_function_tables, "{stem}"); - assert!(matches!( - plan.instantiate_dispatch(&none, &one_group()), - Err(crate::error::BindError::Unsupported(_)) - )); - } -} - -/// Under the variant that reads tables at their device addresses, each kernel calls the entry the -/// table its argument buffer names holds, with the binder's directory bytes and the tables' words -/// at their addresses: a listed table by its id (the high word too), a null entry, an empty table, -/// and a null table for the null id and for an id no listed table has; on every committed profile -/// with device addresses. -#[test] -fn an_addressed_table_call_calls_the_entry_its_table_holds() { - let Some((caller, functions)) = fixtures() else { - return; - }; - let h = handles(&functions); - let listed = at_addresses(state()); - let tables: Vec<(u64, Vec)> = [ - table_bytes(&h, &T_ENTRIES), - table_bytes(&h, &U_ENTRIES), - table_bytes(&h, &[]), - ] - .into_iter() - .zip(&listed.function_tables) - .map(|(bytes, t)| (t.address, bytes)) - .collect(); - let dev = device("moltenvk-m3"); - let pipe = addressed_pipeline(&dev, &caller, &functions, ONE).expect("pipeline"); - let plan = pipe.plan(&dev, &listed.shape()).expect("plan"); - let cmds = plan - .instantiate_dispatch(&listed, &one_group()) - .expect("dispatch"); - let directory = bytes_at(&cmds.descriptor_bytes, directory_binding(&pipe)).to_vec(); - let none = FunctionConstantValues::defaults(); - let linked = sources(&functions, &none); - let inputs = addressed_inputs(); - let words = Words::Addressed(&tables); - const N: u32 = 40; - let mut ran = 0; - for (stem, p) in committed_profiles().expect("profiles") { - if p.fields().buffer_access != BufferAccess::Addressed { - continue; - } - ran += 1; - let module = |entry| { - crate::pipeline::testing::typed_module_linked_with(&caller, entry, &p, &linked, &inputs) - .unwrap_or_else(|e| panic!("{stem} {entry}: {e}")) - .1 - }; - let one = module(ONE); - for id in [T, U, E, 0, UNKNOWN] { - let want: Vec = (0..N).map(|tid| expect(id, tid, tid, 3)).collect(); - assert_eq!( - dispatch(&one, N, ids(&[id]), &directory, words), - want, - "{stem} {ONE} {id:#x}" - ); - } - let array = module(ARRAY); - for pair in [[T, U], [E, UNKNOWN]] { - let mut args = vec![0; 8]; - args.extend(ids(&pair)); - let want: Vec = (0..N) - .map(|tid| expect(pair[(tid & 1) as usize], tid >> 1, tid, 5)) - .collect(); - assert_eq!( - dispatch(&array, N, args, &directory, words), - want, - "{stem} {ARRAY} {pair:x?}" - ); - } - let select = module(SELECT); - for [a, b] in [[U, T], [0, E]] { - let want: Vec = (0..N) - .map(|tid| { - let id = if tid & 1 != 0 { a } else { b }; - expect(id, tid >> 1, tid, 7) - }) - .collect(); - assert_eq!( - dispatch(&select, N, ids(&[a, b]), &directory, words), - want, - "{stem} {SELECT} {a:#x} {b:#x}" - ); - } - } - assert!(ran > 0, "a profile with device addresses"); -} diff --git a/crates/metal2vulkan/src/tests/engine_atomics.rs b/crates/metal2vulkan/src/tests/engine_atomics.rs index 3c28c7672..8fa2b30b0 100644 --- a/crates/metal2vulkan/src/tests/engine_atomics.rs +++ b/crates/metal2vulkan/src/tests/engine_atomics.rs @@ -140,6 +140,10 @@ const SINK_AT: u64 = 0x0000_0041_0000_0000; /// The command buffer's `ExecutionStatus` buffer (the `seq_cst` order). const STATUS_AT: u64 = 0x0000_0042_0000_0000; +/// The `ExecutionStatus` buffer's bytes: through its last word. +const STATUS_BYTES: usize = + crate::bind::status::StatusWord::SeqCstFences.byte_offset() as usize + 4; + /// Resources of a kernel with `threads` threads and buffers `[[buffer(i)]]` holding `init[i]`, /// bound at their starts. Every buffer is also at a device address with /// its root-table entry, for a plan that reaches slots by device address (typed atomics). @@ -199,7 +203,7 @@ fn resources(plan: &Plan, init: &[Vec], threads: u32) -> Resources { buffers.push(Buffer { slot: Some(crate::lower::access::absent::symbol(Stage::Kernel)), address: Some(STATUS_AT), - bytes: vec![0; crate::bind::status::ExecutionStatus::BYTES], + bytes: vec![0; STATUS_BYTES], }); Resources { buffers, diff --git a/crates/metal2vulkan/src/tests/engine_binder.rs b/crates/metal2vulkan/src/tests/engine_binder.rs deleted file mode 100644 index 42d59bca8..000000000 --- a/crates/metal2vulkan/src/tests/engine_binder.rs +++ /dev/null @@ -1,1268 +0,0 @@ -//! The compute binder end to end on the CPU interpreter. No device is opened. -//! -//! Each kernel goes through the public compile API (`Library::from_air`, -//! `Device::compile_compute_pipeline`), `ComputePipeline::plan`, and -//! `BindingPlan::instantiate_dispatch`; the harness then runs the pipeline's typed module on the -//! interpreter with exactly what the binder planned: every descriptor write (a buffer slot's -//! descriptor range sliced out of its allocation, the `ZeroBuffer` neutral, the argument table -//! bytes, the status buffer), every region's push bytes (with the root-table and status address -//! holes filled), its specialization, and its group count, region after region. Results are -//! compared with what Metal computes. -//! -//! - Plans are total on every committed profile: one write per layout binding, or a typed error. -//! - `dispatchThreads` edges and group-count splits compute Metal's grid builtins exactly. -//! - Bind offsets reach the right bytes through the range and the residual (the in-shader check -//! reads the bound range's length). -//! - `[[threadgroup(n)]]` lengths specialize the arena; a total above -//! `maxComputeSharedMemorySize` is refused at plan. -//! - Loaded pointers resolve through the binder's root table (resident set from bound buffers and -//! `used_resources`); a miss is counted in the `ExecutionStatus`; a parameter merged with a -//! loaded pointer is reached through its root entry, which needs a device address. -//! - An indirect dispatch reads its group counts from Metal's buffer. -//! -//! `llvm-as` assembles the kernels; without it the tests skip visibly. - -use std::collections::BTreeMap; -use std::path::Path; -use std::sync::atomic::{AtomicU64, Ordering}; - -use crate::bind::{ - BindState, BoundBuffer, Dispatch, DispatchCommands, ExecutionStatus, IndirectArgs, IndirectRef, - PushHole, ResourceClass, RootTable, StageTable, StatusReport, StatusWord, UsedResource, - WriteSource, -}; -use crate::budget::Budget; -use crate::device::requirements::VkFeature; -use crate::device::{Device, DeviceDescription, DevicePolicy}; -use crate::error::{BindError, Feature}; -use crate::library::Library; -use crate::pipeline::interface::{BufferForm, SlotInterface}; -use crate::pipeline::layout::BindingSource; -use crate::pipeline::sym::{ - PushField, ResourceKind, ResourceSlot, SlotClass, SlotRef, SpecKey, Stage, -}; -use crate::pipeline::testing::{engine_dir, llvm_assemble, typed_module, AssembleError}; -use crate::pipeline::{ - ComputePipeline, ComputePipelineDescriptor, FunctionDescriptor, LoweringInputs, StageSource, -}; -use crate::spirv::interp::{run, Buffer, Config, Order, Resources}; -use crate::spirv::ir::TypedModule; -use crate::spirv::testing::committed_profiles; - -const HEADER: &str = "target datalayout = \"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32\"\ntarget triple = \"air64_v28-apple-macosx26.0.0\"\n\n"; - -/// Device addresses of the consumer-owned objects the harness places. -const TABLE: u64 = 0x0000_0010_0000_0000; -const SINK: u64 = 0x0000_0011_0000_0000; -const STATUS: u64 = 0x0000_0012_0000_0000; - -pub(super) fn assemble_text(name: &str, text: &str) -> Option> { - static NEXT: AtomicU64 = AtomicU64::new(0); - let dir = std::env::temp_dir().join(format!( - "m2v-binder-{}-{}-{name}", - std::process::id(), - NEXT.fetch_add(1, Ordering::Relaxed) - )); - std::fs::create_dir_all(&dir).expect("scratch"); - let ll = dir.join("k.ll"); - std::fs::write(&ll, text).expect("write"); - let r = llvm_assemble(&ll); - let _ = std::fs::remove_dir_all(&dir); - match r { - Ok(b) => Some(b), - Err(AssembleError::Missing(why)) => { - eprintln!("SKIPPED: {why}"); - None - } - Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected {name}: {why}\n{text}"), - } -} - -fn fixture(stem: &str) -> Option> { - match llvm_assemble(&engine_dir().join(format!("{stem}.ll"))) { - Ok(b) => Some(b), - Err(AssembleError::Missing(why)) => { - eprintln!("SKIPPED: {why}"); - None - } - Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected {stem}.ll: {why}"), - } -} - -/// Committed profile `stem` as a device, after `tweak` edits its description. -pub(super) fn device(stem: &str, tweak: impl FnOnce(&mut DeviceDescription)) -> Device { - let 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"); - tweak(&mut desc); - Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device") -} - -/// Profile F: `runtime-floor` without device addresses, below the runtime's floor, whose buffers -/// are descriptors at its four storage buffers a stage. -fn no_addresses(desc: &mut DeviceDescription) { - desc.features.remove(&VkFeature::BufferDeviceAddress); -} - -fn pipeline(dev: &Device, bc: &[u8], entry: &str) -> Result { - let lib = Library::from_air(bc).map_err(|e| format!("library: {e}"))?; - let f = lib.function(entry).map_err(|e| format!("{entry}: {e}"))?; - let d = ComputePipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new(f))); - dev.compile_compute_pipeline(&d, &Budget::standard()) - .map_err(|e| format!("{entry}: {e}")) -} - -fn kslot(index: u32) -> SlotRef { - SlotRef { - stage: Stage::Kernel, - class: SlotClass::Buffer, - index, - } -} - -/// A bound Metal buffer: its allocation bytes and addresses. -#[derive(Clone)] -pub(super) struct Alloc { - pub(super) bytes: Vec, - offset: u64, - guest: u64, - host: Option, -} - -impl Alloc { - pub(super) fn new(len: usize, offset: u64) -> Alloc { - Alloc { - bytes: vec![0; len], - offset, - guest: 0, - host: None, - } - } -} - -/// What the consumer has: bound buffers by kernel slot, used resources (`(guest, host, bytes)`), -/// and the status buffer. -pub(super) struct World { - pub(super) buffers: BTreeMap, - used: Vec<(u64, u64, Vec)>, - status: [u8; ExecutionStatus::BYTES], -} - -impl World { - pub(super) fn new(buffers: impl IntoIterator) -> World { - World { - buffers: buffers.into_iter().collect(), - used: Vec::new(), - status: ExecutionStatus::initial(), - } - } - - pub(super) fn state(&self) -> BindState { - let mut t = StageTable::default(); - for (&i, a) in &self.buffers { - t.buffers.insert( - i, - BoundBuffer::Buffer { - length: a.bytes.len() as u64, - offset: a.offset, - gpu_address: a.guest, - device_address: a.host, - attribute_stride: None, - }, - ); - } - let mut s = BindState::default(); - s.stages.insert(Stage::Kernel, t); - for (i, (guest, host, bytes)) in self.used.iter().enumerate() { - let mut u = UsedResource::new(ResourceClass::Buffer, i as u32); - u.gpu_address = Some(*guest); - u.length = bytes.len() as u64; - u.device_address = Some(*host); - s.used_resources.push(u); - } - s - } - - fn report(&self) -> StatusReport { - ExecutionStatus::decode(&self.status) - } -} - -fn padded(mut v: Vec) -> Vec { - v.resize(v.len().next_multiple_of(16).max(16), 0); - v -} - -/// Where each interpreter buffer's final bytes go. -enum Back { - Slice { slot: u32, offset: usize }, - Whole { slot: u32 }, - Used(usize), - Status, - Nowhere, -} - -/// The typed-module symbol of a layout binding. -fn symbol(source: BindingSource) -> ResourceSlot { - match source { - BindingSource::Buffer(slot) => ResourceSlot { - stage: slot.stage, - kind: ResourceKind::Buffer, - index: slot.index, - }, - BindingSource::Synthetic { stage, binding } => ResourceSlot { - stage, - kind: ResourceKind::Synthetic(binding), - index: 0, - }, - other => panic!("a compute binding {other:?}"), - } -} - -/// Plan, instantiate, and run `dispatch` of `pipe` (whose typed module is `m`) over `world`. -fn execute( - dev: &Device, - pipe: &ComputePipeline, - m: &TypedModule, - world: &mut World, - dispatch: &Dispatch, -) -> Result { - execute_with(dev, (pipe, m), world, dispatch, Config::default()) -} - -/// [`execute`] with the interpreter's subgroup width and barrier rule `cfg`'s. -pub(super) fn execute_with( - dev: &Device, - (pipe, m): (&ComputePipeline, &TypedModule), - world: &mut World, - dispatch: &Dispatch, - cfg: Config, -) -> Result { - let state = world.state(); - let plan = pipe.plan(dev, &state.shape())?; - let cmds = plan.instantiate_dispatch(&state, dispatch)?; - let layout: BTreeMap<(u32, u32), BindingSource> = pipe - .layout - .sets - .iter() - .flat_map(|s| { - s.bindings - .iter() - .map(move |b| ((s.set, b.binding), b.source)) - }) - .collect(); - assert_eq!( - plan.descriptors.len(), - layout.len(), - "one write per binding" - ); - let ids: BTreeMap = pipe - .stage - .specialization - .constants - .iter() - .map(|c| (c.id, c.key)) - .collect(); - for region in &cmds.regions { - let mut buffers = Vec::new(); - let mut back = Vec::new(); - for w in &plan.descriptors { - let sym = symbol(layout[&(w.set, w.binding)]); - let range = cmds - .descriptor_ranges - .iter() - .find(|r| (r.set, r.binding) == (w.set, w.binding)) - .map(|r| r.range); - let (bytes, to) = match &w.source { - WriteSource::Buffer { slot } => { - let r = range.expect("a range for every buffer write"); - let a = &world.buffers[&slot.index]; - let all = padded(a.bytes.clone()); - let (o, n) = (r.offset as usize, r.range as usize); - ( - all[o..o + n].to_vec(), - Back::Slice { - slot: slot.index, - offset: o, - }, - ) - } - WriteSource::Neutral(_) => (vec![0; 4096], Back::Nowhere), - WriteSource::ArgumentTable { .. } => { - let d = cmds - .descriptor_bytes - .iter() - .find(|d| (d.set, d.binding) == (w.set, w.binding)) - .expect("argument table bytes"); - (d.bytes.clone(), Back::Nowhere) - } - WriteSource::ConstantBlob { stage } => ( - padded({ - assert_eq!(*stage, Stage::Kernel); - pipe.stage.constant_blob.as_deref().expect("blob").to_vec() - }), - Back::Nowhere, - ), - WriteSource::ExecutionStatus => (world.status.to_vec(), Back::Status), - other => panic!("unexpected write {other:?}"), - }; - buffers.push(Buffer { - slot: Some(sym), - address: None, - bytes, - }); - back.push(to); - } - for (&i, a) in &world.buffers { - if let Some(host) = a.host { - buffers.push(Buffer { - slot: None, - address: Some(host), - bytes: padded(a.bytes.clone()), - }); - back.push(Back::Whole { slot: i }); - } - } - for (i, (_, host, bytes)) in world.used.iter().enumerate() { - buffers.push(Buffer { - slot: None, - address: Some(*host), - bytes: padded(bytes.clone()), - }); - back.push(Back::Used(i)); - } - let mut push = Vec::new(); - if let Some(w) = region.push_constants.first() { - push = vec![0u8; (w.offset as usize) + w.bytes.len()]; - push[w.offset as usize..].copy_from_slice(&w.bytes); - } - for hole in &cmds.push_holes { - let (offset, address) = match *hole { - PushHole::RootTableAddress { offset, .. } => (offset, TABLE), - PushHole::ExecutionStatusAddress { offset, .. } => (offset, STATUS), - other => panic!("{other:?}"), - }; - let at = offset as usize; - push[at..at + 8].copy_from_slice(&address.to_le_bytes()); - if address == STATUS { - buffers.push(Buffer { - slot: None, - address: Some(STATUS), - bytes: world.status.to_vec(), - }); - back.push(Back::Status); - } - } - if let Some(RootTable { bytes, .. }) = &cmds.root_table { - let mut bytes = bytes.clone(); - let at = RootTable::SINK_HOST_OFFSET as usize; - bytes[at..at + 8].copy_from_slice(&SINK.to_le_bytes()); - buffers.push(Buffer { - slot: None, - address: Some(TABLE), - bytes, - }); - back.push(Back::Nowhere); - buffers.push(Buffer { - slot: None, - address: Some(SINK), - bytes: vec![0; 64], - }); - back.push(Back::Nowhere); - } - let mut spec = BTreeMap::new(); - for e in ®ion.specialization.entries { - let at = e.offset as usize; - let mut v = [0u8; 8]; - v[..e.size as usize] - .copy_from_slice(®ion.specialization.data[at..at + e.size as usize]); - spec.insert(ids[&e.constant_id], u64::from_le_bytes(v)); - } - let workgroups = match region.indirect { - None => region.group_count, - Some(IndirectArgs::Buffer(_)) => INDIRECT_ARGS, - Some(other) => panic!("{other:?}"), - }; - let res = Resources { - buffers, - push, - spec, - }; - let mut outs = Vec::new(); - for order in [Order::Forward, Order::Reverse] { - let cfg = Config { - workgroups, - order, - ..cfg - }; - outs.push(run(m, &cfg, res.clone()).expect("run").buffers); - } - assert_eq!(outs[0], outs[1], "the two scheduling orders agree"); - for (bytes, to) in outs.swap_remove(0).into_iter().zip(back) { - match to { - Back::Slice { slot, offset } => { - let a = world.buffers.get_mut(&slot).expect("slot"); - for (i, b) in bytes.into_iter().enumerate() { - if let Some(dst) = a.bytes.get_mut(offset + i) { - *dst = b; - } - } - } - Back::Whole { slot } => { - let a = world.buffers.get_mut(&slot).expect("slot"); - let n = a.bytes.len(); - a.bytes.copy_from_slice(&bytes[..n]); - } - Back::Used(i) => { - let n = world.used[i].2.len(); - world.used[i].2.copy_from_slice(&bytes[..n]); - } - Back::Status => world - .status - .copy_from_slice(&bytes[..ExecutionStatus::BYTES]), - Back::Nowhere => {} - } - } - } - Ok(cmds) -} - -/// The indirect arguments the harness keeps for `ThreadgroupsIndirect` (token 0). -static INDIRECT_ARGS: [u32; 3] = [3, 1, 1]; - -pub(super) fn words(bytes: &[u8]) -> Vec { - bytes - .as_chunks::<4>() - .0 - .iter() - .map(|c| u32::from_le_bytes(*c)) - .collect() -} - -/// `out[thread_position_in_grid] = threads_per_grid << 16 | threadgroup_position_in_grid`. -fn grid_ids() -> String { - format!( - "{HEADER}define void @grid_ids(ptr addrspace(1) noundef \"air-buffer-no-alias\" %0, i32 noundef %tid, i32 noundef %grp, i32 noundef %tpg) {{\n\ -entry:\n\ - %s = shl i32 %tpg, 16\n\ - %v = or i32 %s, %grp\n\ - %i = zext i32 %tid to i64\n\ - %p = getelementptr inbounds i32, ptr addrspace(1) %0, i64 %i\n\ - store i32 %v, ptr addrspace(1) %p, align 4\n\ - ret void\n\ -}}\n\n\ -!air.kernel = !{{!0}}\n!air.version = !{{!6}}\n!air.language_version = !{{!7}}\n\ -!0 = !{{ptr @grid_ids, !1, !2}}\n!1 = !{{}}\n!2 = !{{!3, !4, !5, !8}}\n\ -!3 = !{{i32 0, !\"air.buffer\", !\"air.location_index\", i32 0, i32 1, !\"air.read_write\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4, !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"out\"}}\n\ -!4 = !{{i32 1, !\"air.thread_position_in_grid\", !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"tid\"}}\n\ -!5 = !{{i32 2, !\"air.threadgroup_position_in_grid\", !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"grp\"}}\n\ -!8 = !{{i32 3, !\"air.threads_per_grid\", !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"tpg\"}}\n\ -!6 = !{{i32 2, i32 8, i32 0}}\n!7 = !{{!\"Metal\", i32 4, i32 0, i32 0}}\n" - ) -} - -/// Every profile with a compute-capable Vulkan 1.2 floor the M1 milestone names. -const PROFILES: [&str; 3] = ["moltenvk-m3", "lavapipe", "runtime-floor"]; - -#[test] -fn plans_are_total_on_every_committed_profile() { - let Some(grid) = assemble_text("grid_ids", &grid_ids()) else { - return; - }; - let Some(load) = fixture("buffer_end_byte_load") else { - return; - }; - let Some(constant) = fixture("buffer_end_byte_load_constant") else { - return; - }; - let kernels = [ - (&grid, "grid_ids"), - (&load, "buffer_end_byte_load"), - (&constant, "buffer_end_byte_load_constant"), - ]; - let (mut planned, mut refused) = (0, 0); - for (stem, _) in committed_profiles().expect("profiles") { - let dev = device(&stem, |_| {}); - for (bc, entry) in kernels { - let Ok(pipe) = pipeline(&dev, bc, entry) else { - refused += 1; - continue; - }; - let bindings: usize = pipe.layout.sets.iter().map(|s| s.bindings.len()).sum(); - let slots: Vec = pipe.interface.slots.keys().map(|s| s.index).collect(); - let shapes = [ - World::new(slots.iter().map(|&i| (i, Alloc::new(64, 0)))), - World::new([]), - World::new(slots.iter().map(|&i| (i, Alloc::new(64, 16)))), - ]; - for w in &shapes { - let state = w.state(); - let plan = pipe - .plan(&dev, &state.shape()) - .unwrap_or_else(|e| panic!("{stem} {entry}: {e}")); - assert_eq!(plan.descriptors.len(), bindings, "{stem} {entry}"); - for d in [ - Dispatch::Threadgroups { - groups: [2, 1, 1], - threads_per_group: [4, 1, 1], - }, - Dispatch::Threads { - threads: [9, 1, 1], - threads_per_group: [4, 1, 1], - }, - Dispatch::ThreadgroupsIndirect { - indirect: IndirectRef { - token: 0, - offset: 0, - }, - threads_per_group: [4, 1, 1], - }, - ] { - let c = plan - .instantiate_dispatch(&state, &d) - .unwrap_or_else(|e| panic!("{stem} {entry} {d:?}: {e}")); - assert!(!c.regions.is_empty()); - for r in &c.regions { - let push_bytes: usize = - r.push_constants.iter().map(|p| p.bytes.len()).sum(); - let range: u32 = pipe.layout.push_constants.iter().map(|p| p.size).sum(); - assert_eq!(push_bytes as u32, range, "every push byte is written"); - } - } - planned += 1; - } - } - } - assert!(planned > 0); - eprintln!("{planned} plans, {refused} compiles refused"); -} - -#[test] -fn dispatch_threads_edges_and_group_splits_compute_metal_grid_builtins() { - let Some(bc) = assemble_text("grid_ids", &grid_ids()) else { - return; - }; - for stem in PROFILES { - // A small group-count limit makes the splits reachable with a small grid. - let dev = device(stem, |d| d.limits.max_compute_work_group_count = [4, 4, 4]); - let pipe = pipeline(&dev, &bc, "grid_ids").expect(stem); - let (_, m) = typed_module(&bc, "grid_ids", dev.profile()).expect("module"); - let expect = |threads: u32, l: u32| -> Vec { - (0..threads).map(|t| (threads << 16) | (t / l)).collect() - }; - // 40 threads in groups of 16: an interior of two groups and an edge of 8 threads. - let mut w = World::new([(0, Alloc::new(4 * 64, 0))]); - let d = Dispatch::Threads { - threads: [40, 1, 1], - threads_per_group: [16, 1, 1], - }; - let c = execute(&dev, &pipe, &m, &mut w, &d).expect(stem); - assert_eq!(c.regions.len(), 2, "{stem}"); - assert_eq!(&words(&w.buffers[&0].bytes)[..40], expect(40, 16), "{stem}"); - assert!(words(&w.buffers[&0].bytes)[40..].iter().all(|&x| x == 0)); - // 10 groups of 4 with at most 4 groups per dispatch: three regions. - let mut w = World::new([(0, Alloc::new(4 * 64, 0))]); - let d = Dispatch::Threadgroups { - groups: [10, 1, 1], - threads_per_group: [4, 1, 1], - }; - let c = execute(&dev, &pipe, &m, &mut w, &d).expect(stem); - assert_eq!(c.regions.len(), 3, "{stem}"); - assert_eq!(&words(&w.buffers[&0].bytes)[..40], expect(40, 4), "{stem}"); - // Indirect: the dispatch reads Metal's 3 groups from its buffer. - let mut w = World::new([(0, Alloc::new(4 * 64, 0))]); - let d = Dispatch::ThreadgroupsIndirect { - indirect: IndirectRef { - token: 0, - offset: 0, - }, - threads_per_group: [4, 1, 1], - }; - let c = execute(&dev, &pipe, &m, &mut w, &d).expect(stem); - assert_eq!( - c.regions[0].indirect, - Some(IndirectArgs::Buffer(IndirectRef { - token: 0, - offset: 0 - })), - "{stem}" - ); - let got = words(&w.buffers[&0].bytes); - let want: Vec = (0..12).map(|t| (12 << 16) | (t / 4)).collect(); - assert_eq!( - &got[..12], - want, - "{stem}: NumWorkgroups grid of the buffer's counts" - ); - assert!(got[12..].iter().all(|&x| x == 0)); - } -} - -/// A kernel's `seq_cst` fence orders through the command buffer's status: on a device that does -/// not address buffers (Profile F, [`no_addresses`]) the plan binds it -/// (`WriteSource::ExecutionStatus`) and pushes no status address, and where the device addresses -/// buffers (`runtime-floor`, `moltenvk-m3`) it pushes the address and binds nothing. Either way each of the -/// dispatch's threads increments `StatusWord::SeqCstFences` of the one status the command buffer -/// keeps, and the store after the fence lands. -#[test] -fn a_seq_cst_fence_reaches_the_status_by_binding_or_address_as_the_device_allows() { - let Some(bc) = fixture("dispatch_builtins") else { - return; - }; - let same = |_: &mut DeviceDescription| {}; - for (stem, tweak, bound) in [ - ( - "runtime-floor", - no_addresses as fn(&mut DeviceDescription), - true, - ), - ("runtime-floor", same, false), - ("moltenvk-m3", same, false), - ] { - let dev = device(stem, tweak); - let stem = &format!("{stem}{}", if bound { " without addresses" } else { "" }); - let pipe = pipeline(&dev, &bc, "device_fence_store").expect(stem); - let (_, m) = typed_module(&bc, "device_fence_store", dev.profile()).expect("module"); - let mut w = World::new([(0, Alloc::new(16, 0))]); - let d = Dispatch::Threads { - threads: [24, 1, 1], - threads_per_group: [8, 1, 1], - }; - let c = execute(&dev, &pipe, &m, &mut w, &d).expect(stem); - let plan = pipe.plan(&dev, &w.state().shape()).expect(stem); - let writes = plan - .descriptors - .iter() - .filter(|write| write.source == WriteSource::ExecutionStatus) - .count(); - let holes = c - .push_holes - .iter() - .filter(|hole| matches!(hole, PushHole::ExecutionStatusAddress { .. })) - .count(); - assert_eq!( - (writes, holes), - (usize::from(bound), usize::from(!bound)), - "{stem}" - ); - let at = StatusWord::SeqCstFences.byte_offset() as usize; - let fences = u32::from_le_bytes(w.status[at..at + 4].try_into().expect("a word")); - assert_eq!(fences, 24, "{stem}: one increment a thread"); - assert_eq!(words(&w.buffers[&0].bytes)[0], 42, "{stem}"); - } -} - -/// `in` at a nonzero bind offset in a larger allocation, `out` too: the range and the residual -/// reach exactly Metal's bytes. -#[test] -fn bind_offsets_reach_metal_bytes_through_range_and_residual() { - let Some(load) = fixture("buffer_end_byte_load") else { - return; - }; - let Some(constant) = fixture("buffer_end_byte_load_constant") else { - return; - }; - let Some(store) = fixture("buffer_end_byte_store") else { - return; - }; - let one = Dispatch::Threadgroups { - groups: [1, 1, 1], - threads_per_group: [1, 1, 1], - }; - for stem in ["moltenvk-m3", "lavapipe", "runtime-floor"] { - let dev = device(stem, |_| {}); - for (bc, entry) in [ - (&load, "buffer_end_byte_load"), - (&constant, "buffer_end_byte_load_constant"), - ] { - let pipe = pipeline(&dev, bc, entry).expect(entry); - let (_, m) = typed_module(bc, entry, dev.profile()).expect("module"); - for (offset, out_offset) in [(0u64, 0u64), (100, 36), (250, 260), (1, 4)] { - let mut input = Alloc::new(offset as usize + 6, offset); - for (i, b) in input.bytes.iter_mut().enumerate() { - *b = (i as u8).wrapping_mul(7).wrapping_add(3); - } - let want = u32::from(input.bytes[offset as usize + 5]); - let mut w = World::new([ - (0, input), - (1, Alloc::new(out_offset as usize + 4, out_offset)), - ]); - execute(&dev, &pipe, &m, &mut w, &one) - .unwrap_or_else(|e| panic!("{stem} {entry}: {e}")); - let out = &w.buffers[&1].bytes[out_offset as usize..]; - assert_eq!(words(out)[0], want, "{stem} {entry} at {offset}"); - } - } - let pipe = pipeline(&dev, &store, "buffer_end_byte_store").expect("store"); - let (_, m) = typed_module(&store, "buffer_end_byte_store", dev.profile()).expect("m"); - for offset in [0u64, 3, 100] { - let mut a = Alloc::new(offset as usize + 6, offset); - a.bytes.iter_mut().for_each(|b| *b = 0x11); - let mut w = World::new([(0, a)]); - execute(&dev, &pipe, &m, &mut w, &one).expect("store"); - let b = &w.buffers[&0].bytes; - let at = offset as usize + 5; - assert_eq!(b[at], 0xA5, "{stem} at {offset}"); - assert!( - b.iter().enumerate().all(|(i, &x)| i == at || x == 0x11), - "{stem}: neighbours kept" - ); - } - } -} - -/// One `[[threadgroup(0)]]` region after a 12-byte static global: the region starts at 16. -fn tg_region() -> String { - format!( - "{HEADER}@s = internal addrspace(3) global [3 x i32] undef, align 4\n\n\ -define void @tg_region(ptr addrspace(3) %a, ptr addrspace(1) %out, i32 %t) {{\n\ - %pa = getelementptr inbounds i32, ptr addrspace(3) %a, i32 %t\n\ - store i32 %t, ptr addrspace(3) %pa, align 4\n\ - %first = icmp eq i32 %t, 0\n\ - br i1 %first, label %seed, label %sync\n\ -seed:\n\ - %ps = getelementptr inbounds [3 x i32], ptr addrspace(3) @s, i32 0, i32 2\n\ - store i32 1000, ptr addrspace(3) %ps, align 4\n\ - br label %sync\n\ -sync:\n\ - tail call void @air.wg.barrier(i32 2, i32 1)\n\ - %r = sub i32 63, %t\n\ - %qa = getelementptr inbounds i32, ptr addrspace(3) %a, i32 %r\n\ - %va = load i32, ptr addrspace(3) %qa, align 4\n\ - %qs = getelementptr inbounds [3 x i32], ptr addrspace(3) @s, i32 0, i32 2\n\ - %vs = load i32, ptr addrspace(3) %qs, align 4\n\ - %y = add i32 %va, %vs\n\ - %o = getelementptr inbounds i32, ptr addrspace(1) %out, i32 %t\n\ - store i32 %y, ptr addrspace(1) %o, align 4\n\ - ret void\n\ -}}\n\n\ -declare void @air.wg.barrier(i32, i32)\n\n\ -!air.kernel = !{{!0}}\n!air.version = !{{!6}}\n!air.language_version = !{{!7}}\n\ -!6 = !{{i32 2, i32 8, i32 0}}\n!7 = !{{!\"Metal\", i32 4, i32 0, i32 0}}\n\ -!0 = !{{ptr @tg_region, !1, !2}}\n!1 = !{{}}\n!2 = !{{!3, !4, !5}}\n\ -!3 = !{{i32 0, !\"air.buffer\", !\"air.location_index\", i32 0, i32 1, !\"air.read_write\", !\"air.address_space\", i32 3, !\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4, !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"a\"}}\n\ -!4 = !{{i32 1, !\"air.buffer\", !\"air.location_index\", i32 0, i32 1, !\"air.read_write\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4, !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"out\"}}\n\ -!5 = !{{i32 2, !\"air.thread_index_in_threadgroup\", !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"t\"}}\n" - ) -} - -#[test] -fn threadgroup_lengths_specialize_the_arena_and_are_checked() { - let Some(bc) = assemble_text("tg_region", &tg_region()) else { - return; - }; - for stem in ["moltenvk-m3", "lavapipe", "runtime-floor"] { - let dev = device(stem, |_| {}); - let pipe = pipeline(&dev, &bc, "tg_region").expect(stem); - assert_eq!( - pipe.metal_info.static_threadgroup_memory_length, 16, - "{stem}: the regions start at 16" - ); - let (_, m) = typed_module(&bc, "tg_region", dev.profile()).expect("module"); - let mut w = World::new([(0, Alloc::new(4 * 64, 0))]); - let state_len = |w: &World, len: u32| { - let mut s = w.state(); - s.stages - .get_mut(&Stage::Kernel) - .expect("kernel") - .threadgroup_lengths - .insert(0, len); - s - }; - let d = Dispatch::Threadgroups { - groups: [1, 1, 1], - threads_per_group: [64, 1, 1], - }; - // A 250-byte length specializes `TgLength(0)` to Metal's 16-byte rounding, 256. - let state = state_len(&w, 250); - let plan = pipe.plan(&dev, &state.shape()).expect("plan"); - let c = plan.instantiate_dispatch(&state, &d).expect("dispatch"); - let tg = pipe - .stage - .specialization - .constants - .iter() - .find(|k| k.key == SpecKey::TgLength(0)) - .expect("TgLength(0)"); - let e = c.regions[0] - .specialization - .entries - .iter() - .find(|e| e.constant_id == tg.id) - .expect("specialized"); - let at = e.offset as usize; - let data = &c.regions[0].specialization.data; - assert_eq!( - u32::from_le_bytes(data[at..at + 4].try_into().expect("u32")), - 256, - "{stem}: Metal's 16-byte rounding" - ); - run_regions(&pipe, &m, &mut w, &c); - let want: Vec = (0..64).map(|t| 63 - t + 1000).collect(); - assert_eq!(words(&w.buffers[&0].bytes), want, "{stem}"); - // Above `maxComputeSharedMemorySize`: refused at plan, naming the limit. - let max = dev.profile().fields().limits.max_compute_shared_memory_size; - let state = state_len(&w, max - 16 + 1); - match pipe.plan(&dev, &state.shape()) { - Err(BindError::Unsupported(u)) => { - assert_eq!(u.feature, Feature::ThreadgroupMemorySize); - assert!(format!("{:?}", u.needs).contains("MaxComputeSharedMemorySize")); - } - other => panic!("{stem}: {other:?}"), - } - let state = state_len(&w, max - 16); - assert!( - pipe.plan(&dev, &state.shape()).is_ok(), - "{stem}: exactly full" - ); - } -} - -/// Run already-instantiated commands of a descriptor-only kernel (no addresses) on `world`. -fn run_regions(pipe: &ComputePipeline, m: &TypedModule, world: &mut World, c: &DispatchCommands) { - let ids: BTreeMap = pipe - .stage - .specialization - .constants - .iter() - .map(|k| (k.id, k.key)) - .collect(); - for region in &c.regions { - let mut spec = BTreeMap::new(); - for e in ®ion.specialization.entries { - let at = e.offset as usize; - let v = u32::from_le_bytes( - region.specialization.data[at..at + 4] - .try_into() - .expect("u32"), - ); - spec.insert(ids[&e.constant_id], u64::from(v)); - } - let mut buffers = Vec::new(); - for r in &c.descriptor_ranges { - let binding = pipe.layout.sets[r.set as usize] - .bindings - .iter() - .find(|b| b.binding == r.binding) - .expect("binding"); - let BindingSource::Buffer(slot) = binding.source else { - panic!("a buffer range for {:?}", binding.source); - }; - let all = padded(world.buffers[&slot.index].bytes.clone()); - let (o, n) = (r.range.offset as usize, r.range.range as usize); - buffers.push(Buffer { - slot: Some(symbol(binding.source)), - address: None, - bytes: all[o..o + n].to_vec(), - }); - } - let push = region - .push_constants - .first() - .map(|w| { - let mut p = vec![0u8; w.offset as usize]; - p.extend_from_slice(&w.bytes); - p - }) - .unwrap_or_default(); - let cfg = Config { - workgroups: region.group_count, - ..Config::default() - }; - let res = Resources { - buffers, - push, - spec, - }; - let out = run(m, &cfg, res).expect("run").buffers; - for (r, bytes) in c.descriptor_ranges.iter().zip(out) { - let binding = pipe.layout.sets[r.set as usize] - .bindings - .iter() - .find(|b| b.binding == r.binding) - .expect("binding"); - let BindingSource::Buffer(slot) = binding.source else { - unreachable!() - }; - let a = world.buffers.get_mut(&slot.index).expect("slot"); - for (i, b) in bytes.into_iter().enumerate() { - if let Some(dst) = a.bytes.get_mut(r.range.offset as usize + i) { - *dst = b; - } - } - } - } -} - -/// Kernel metadata for `name` with three `device` buffers: 0 (read), 1 (read-write), 2 (read). -fn meta(name: &str) -> String { - format!( - "!air.kernel = !{{!9}}\n!air.version = !{{!17}}\n!air.language_version = !{{!18}}\n\ - !9 = !{{ptr @{name}, !10, !11}}\n!10 = !{{}}\n!11 = !{{!12, !13, !14}}\n\ - !12 = !{{i32 0, !\"air.buffer\", !\"air.location_index\", i32 0, i32 1, !\"air.read\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 8, !\"air.arg_type_align_size\", i32 8, !\"air.arg_type_name\", !\"ulong\", !\"air.arg_name\", !\"ptrs\"}}\n\ - !13 = !{{i32 1, !\"air.buffer\", !\"air.location_index\", i32 1, i32 1, !\"air.read_write\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4, !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"out\"}}\n\ - !14 = !{{i32 2, !\"air.buffer\", !\"air.location_index\", i32 2, i32 1, !\"air.read\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 8, !\"air.arg_type_align_size\", i32 8, !\"air.arg_type_name\", !\"ulong\", !\"air.arg_name\", !\"params\"}}\n\ - !17 = !{{i32 2, i32 8, i32 0}}\n!18 = !{{!\"Metal\", i32 4, i32 0, i32 0}}\n" - ) -} - -fn kernel3(name: &str, body: &str) -> String { - format!( - "{HEADER}define void @{name}(ptr addrspace(1) noundef \"air-buffer-no-alias\" %0, ptr addrspace(1) noundef \"air-buffer-no-alias\" %1, ptr addrspace(1) noundef \"air-buffer-no-alias\" %2) {{\nentry:\n{body} ret void\n}}\n\n{}", - meta(name) - ) -} - -/// The pointer at element `params[0]` of `ptrs`, displaced by the `i64` `params[1]`. -const CHASE: &str = " %k = load i32, ptr addrspace(1) %2, align 8\n\ - %op = getelementptr i8, ptr addrspace(1) %2, i64 8\n\ - %off = load i64, ptr addrspace(1) %op, align 8\n\ - %pp = getelementptr ptr addrspace(1), ptr addrspace(1) %0, i32 %k\n\ - %p = load ptr addrspace(1), ptr addrspace(1) %pp, align 8\n\ - %q = getelementptr i8, ptr addrspace(1) %p, i64 %off\n"; - -fn params(k: u32, off: u64) -> Alloc { - let mut a = Alloc::new(16, 0); - a.bytes[..4].copy_from_slice(&k.to_le_bytes()); - a.bytes[8..].copy_from_slice(&off.to_le_bytes()); - a -} - -fn table(entries: &[u64]) -> Alloc { - let mut a = Alloc::new(8 * entries.len(), 0); - for (i, e) in entries.iter().enumerate() { - a.bytes[8 * i..8 * i + 8].copy_from_slice(&e.to_le_bytes()); - } - a -} - -/// Two resident targets: guest `0x1_0000_0000 + 0x100 k`, host far away. -fn targets(w: &mut World) { - for k in 0..2u64 { - let bytes: Vec = (0..64u8).map(|b| b.wrapping_add(0x40 * k as u8)).collect(); - w.used.push(( - 0x1_0000_0000 + 0x100 * k, - 0x20_0000_0000 + 0x1_0000_0000 * k, - bytes, - )); - } -} - -#[test] -fn loaded_pointers_resolve_through_the_binders_root_table() { - let body = format!( - "{CHASE} %v = load i32, ptr addrspace(1) %q, align 4\n store i32 %v, ptr addrspace(1) %1, align 4\n" - ); - let Some(bc) = assemble_text("dyn_load", &kernel3("dyn_load", &body)) else { - return; - }; - let one = Dispatch::Threadgroups { - groups: [1, 1, 1], - threads_per_group: [1, 1, 1], - }; - for stem in ["moltenvk-m3", "lavapipe"] { - let dev = device(stem, |_| {}); - let pipe = pipeline(&dev, &bc, "dyn_load").expect(stem); - assert!(pipe.interface.needs_pointer_translation); - let (_, m) = typed_module(&bc, "dyn_load", dev.profile()).expect("module"); - let ptrs = [0x1_0000_0000u64, 0x1_0000_0100, 0x7_0000_0000]; - for (k, off, want, miss) in [ - (0, 4, u32::from_le_bytes([4, 5, 6, 7]), false), - (1, 60, u32::from_le_bytes([124, 125, 126, 127]), false), - (1, 64, 0, false), - (2, 0, 0, true), - ] { - let mut w = World::new([ - (0, table(&ptrs)), - (1, Alloc::new(16, 0)), - (2, params(k, off)), - ]); - targets(&mut w); - let c = - execute(&dev, &pipe, &m, &mut w, &one).unwrap_or_else(|e| panic!("{stem}: {e}")); - let table = c.root_table.expect("a root table"); - let n = u64::from_le_bytes(table.bytes[48..56].try_into().expect("N")); - assert_eq!(n, 2, "{stem}: the resident set is the two used resources"); - assert_eq!( - words(&w.buffers[&1].bytes)[0], - want, - "{stem} k={k} off={off}" - ); - let r = w.report(); - assert_eq!(r.resident_miss, miss, "{stem} k={k}"); - assert_eq!(r.resident_misses, u32::from(miss), "{stem} k={k}"); - } - } -} - -#[test] -fn a_parameter_merged_with_a_loaded_pointer_is_reached_through_its_root_entry() { - let body = format!( - "{CHASE} %cp = getelementptr i8, ptr addrspace(1) %2, i64 4\n\ - %c = load i32, ptr addrspace(1) %cp, align 4\n\ - %use_out = icmp ne i32 %c, 0\n\ - %t = select i1 %use_out, ptr addrspace(1) %1, ptr addrspace(1) %q\n\ - store i32 305419896, ptr addrspace(1) %t, align 4\n" - ); - let Some(bc) = assemble_text("merged", &kernel3("merged", &body)) else { - return; - }; - let one = Dispatch::Threadgroups { - groups: [1, 1, 1], - threads_per_group: [1, 1, 1], - }; - for stem in ["moltenvk-m3", "lavapipe"] { - let dev = device(stem, |_| {}); - let pipe = pipeline(&dev, &bc, "merged").expect(stem); - let (_, m) = typed_module(&bc, "merged", dev.profile()).expect("module"); - let ptrs = [0x1_0000_0000u64, 0x1_0000_0100]; - let world = |use_out: bool, host: Option| { - let mut p = params(1, 8); - p.bytes[4] = u8::from(use_out); - let mut out = Alloc::new(40, 24); - out.guest = 0x3_0000_0000; - out.host = host; - let mut w = World::new([(0, table(&ptrs)), (1, out), (2, p)]); - targets(&mut w); - w - }; - // `out` is a device-address slot: without an address the plan refuses. - let w = world(true, None); - assert_eq!( - pipe.plan(&dev, &w.state().shape()), - Err(BindError::MissingDeviceAddress { slot: kslot(1) }), - "{stem}" - ); - // Through its root entry `2 + 1`, at its bind offset. - let mut w = world(true, Some(0x30_0000_0000)); - let c = execute(&dev, &pipe, &m, &mut w, &one).expect("out"); - let table = c.root_table.expect("table"); - let entry = |f: usize| { - let at = 3 * 32 + 8 * f; - u64::from_le_bytes(table.bytes[at..at + 8].try_into().expect("u64")) - }; - assert_eq!( - (entry(0), entry(1), entry(2), entry(3)), - (0x30_0000_0000, 0x3_0000_0000, 48, 24), - "{stem}: host, guest, padded size, bind offset" - ); - let out = &w.buffers[&1].bytes; - assert_eq!(words(&out[24..28])[0], 0x1234_5678, "{stem}"); - assert!(out[..24].iter().chain(&out[28..]).all(|&b| b == 0)); - // Through the loaded pointer into the second target. - let mut w = world(false, Some(0x30_0000_0000)); - execute(&dev, &pipe, &m, &mut w, &one).expect("target"); - assert_eq!(words(&w.used[1].2[8..12])[0], 0x1234_5678, "{stem}"); - assert!(w.buffers[&1].bytes.iter().all(|&b| b == 0)); - } -} - -/// A descriptor-only kernel on the Vulkan 1.2 floor needs no root table, no address holes, and -/// no device addresses. -#[test] -fn descriptor_only_kernels_need_no_root_table_or_addresses() { - let Some(bc) = assemble_text("grid_ids", &grid_ids()) else { - return; - }; - let dev = device("runtime-floor", |_| {}); - let pipe = pipeline(&dev, &bc, "grid_ids").expect("runtime-floor"); - assert!(!pipe.interface.needs_pointer_translation); - let w = World::new([(0, Alloc::new(64, 0))]); - let state = w.state(); - let plan = pipe.plan(&dev, &state.shape()).expect("plan"); - assert!(plan - .push - .fields - .iter() - .all(|f| f.field != PushField::RootTableAddress)); - let c = plan - .instantiate_dispatch( - &state, - &Dispatch::Threadgroups { - groups: [1, 1, 1], - threads_per_group: [1, 1, 1], - }, - ) - .expect("dispatch"); - assert!(c.root_table.is_none() && c.push_holes.is_empty()); - // Stage modules bind no synthetic buffer: every write is a bound Metal buffer. - for d in &plan.descriptors { - assert!( - matches!(d.source, WriteSource::Buffer { .. }), - "{:?}", - d.source - ); - } -} - -/// The binder writes each compared slot's `SlotGuestBase` (the bound buffer's Metal address plus -/// its bind offset), so `ptrs == params` holds exactly when the two are bound at one Metal address -/// and `params == null` never holds for a bound buffer; a `set*Bytes` binding has no Metal address, -/// and a pipeline that reads one is refused at plan as `MissingGuestAddress` rather than seeing it -/// compare equal to null. -#[test] -fn compared_slots_get_their_guest_bases_and_inline_bytes_are_refused() { - let body = " %e = icmp eq ptr addrspace(1) %0, %2\n\ - %n = icmp eq ptr addrspace(1) %2, null\n\ - %re = zext i1 %e to i32\n\ - store i32 %re, ptr addrspace(1) %1, align 4\n\ - %rn = zext i1 %n to i32\n\ - %o = getelementptr inbounds i32, ptr addrspace(1) %1, i64 1\n\ - store i32 %rn, ptr addrspace(1) %o, align 4\n"; - let Some(bc) = assemble_text("guest_bases", &kernel3("guest_bases", body)) else { - return; - }; - let one = Dispatch::Threadgroups { - groups: [1, 1, 1], - threads_per_group: [1, 1, 1], - }; - for stem in ["moltenvk-m3", "runtime-floor"] { - let dev = device(stem, |_| {}); - let pipe = pipeline(&dev, &bc, "guest_bases").expect(stem); - let (_, m) = typed_module(&bc, "guest_bases", dev.profile()).expect("module"); - // (guest and bind offset of `ptrs`, of `params`, whether they are one address) - for (a, b, same) in [ - ((0x1_0000_0000, 0), (0x2_0000_0000, 0), false), - ((0x1_0000_0000, 16), (0x1_0000_0010, 0), true), - ((0x1_0000_0000, 0), (0x1_0000_0000, 16), false), - ] { - let mut ptrs = Alloc::new(64, a.1); - ptrs.guest = a.0; - let mut params = Alloc::new(64, b.1); - params.guest = b.0; - let mut w = World::new([(0, ptrs), (1, Alloc::new(16, 0)), (2, params)]); - execute(&dev, &pipe, &m, &mut w, &one).unwrap_or_else(|e| panic!("{stem}: {e}")); - assert_eq!( - words(&w.buffers[&1].bytes)[..2], - [u32::from(same), 0], - "{stem}: {a:?} {b:?}" - ); - } - let mut state = World::new([(0, Alloc::new(64, 0)), (1, Alloc::new(16, 0))]).state(); - if let Some(t) = state.stages.get_mut(&Stage::Kernel) { - t.buffers.insert( - 2, - BoundBuffer::Bytes { - len: 16, - attribute_stride: None, - }, - ); - } - assert_eq!( - pipe.plan(&dev, &state.shape()).err(), - Some(BindError::MissingGuestAddress { slot: kslot(2) }), - "{stem}" - ); - } -} - -/// The `descriptor_limit_uniform_views` fixture (its stem) and its first entry, whose slots are -/// `a`, `b`, `c` (`constant`), `p`, `d`, `out`. -const LIMIT_ENTRY: &str = "descriptor_limit_uniform_views"; - -/// A world for the fixture: `n` threads, and each read-only array holding `len[k]` words (at -/// least `n`), bound at an offset (`c`'s, 532, is not a multiple of 16); `p = {scale 3, bias -/// 0x5A5A}`. Returns it with the expected `out`. -fn limit_world(n: usize, len: [usize; 4]) -> (World, Vec) { - let arr = |seed: u32, words: usize, offset: u64| { - let mut a = Alloc::new(offset as usize + words * 4, offset); - for i in 0..words { - let v = (i as u32).wrapping_mul(2654435761).wrapping_add(seed); - a.bytes[offset as usize + 4 * i..][..4].copy_from_slice(&v.to_le_bytes()); - } - a - }; - let a = arr(1, len[0], 256); - let b = arr(2, len[1], 0); - let c = arr(3, len[2], 532); - let d = arr(4, len[3], 256); - let mut p = Alloc::new(272, 256); - p.bytes[256..264].copy_from_slice(&[3, 0, 0, 0, 0x5A, 0x5A, 0, 0]); - let at = |x: &Alloc, i: usize| words(&x.bytes[x.offset as usize..])[i]; - let want = (0..n) - .map(|i| { - at(&a, i) - .wrapping_add(at(&b, i).wrapping_mul(3)) - .wrapping_add(at(&c, i)) - .wrapping_add(at(&d, i) ^ 0x5A5A) - }) - .collect(); - let mut w = World::new([ - (0, a), - (1, b), - (2, c), - (3, p), - (4, d), - (5, Alloc::new(n * 4, 0)), - ]); - // Distinct Metal addresses: nothing aliases. - for (k, a) in w.buffers.iter_mut() { - a.guest = 0x10_0000_0000 + u64::from(*k) * 0x1_0000_0000; - } - (w, want) -} - -fn limit_dispatch(n: usize) -> Dispatch { - Dispatch::Threadgroups { - groups: [(n / 32) as u32, 1, 1], - threads_per_group: [32, 1, 1], - } -} - -fn form(pipe: &ComputePipeline, index: u32) -> BufferForm { - match pipe.interface.slots.get(&kslot(index)) { - Some(SlotInterface::Buffer(b)) => b.form, - other => panic!("slot {index}: {other:?}"), - } -} - -/// The fixture compiled for `dev` under `inputs` (a `VariantKey`'s kernel inputs). -fn limit_pipeline( - dev: &Device, - bc: &[u8], - inputs: &LoweringInputs, -) -> Result { - let lib = Library::from_air(bc).expect("library"); - let f = lib.function(LIMIT_ENTRY).expect("function"); - let compiled = - dev.compile_function(&FunctionDescriptor::new(f), inputs, &Budget::standard())?; - dev.compile_compute_pipeline( - &ComputePipelineDescriptor::new(StageSource::Compiled(compiled)), - &Budget::standard(), - ) -} - -/// On Profile F ([`no_addresses`]: four storage buffers per stage, no device addresses) the -/// fixture's six buffer slots exceed the stage's storage-buffer limit, and no slot can move to a -/// device address: the compile refuses the kernel (`DescriptorCount`). On a profile whose limit -/// holds them every slot is a storage view, and through the binder, on the interpreter, `out` is -/// Metal's. -#[test] -fn a_stage_past_the_storage_buffer_limit_without_device_addresses_is_refused() { - let Some(bc) = fixture(LIMIT_ENTRY) else { - return; - }; - let dev = device("runtime-floor", no_addresses); - match limit_pipeline(&dev, &bc, &LoweringInputs::new()) { - Err(crate::error::Error::Unsupported(u)) => { - assert_eq!(u.feature, Feature::DescriptorCount) - } - other => panic!("expected a DescriptorCount refusal, got {:?}", other.err()), - } - let n = 64; - let dev = device("moltenvk-m3", |_| {}); - let pipe = pipeline(&dev, &bc, LIMIT_ENTRY).expect("moltenvk-m3"); - assert!( - (0..6).all(|i| form(&pipe, i) == BufferForm::Descriptor), - "every slot a storage view" - ); - let (_, m) = typed_module(&bc, LIMIT_ENTRY, dev.profile()).expect("module"); - let (mut w, want) = limit_world(n, [n; 4]); - let state = w.state(); - let plan = pipe.plan(&dev, &state.shape()).expect("plan"); - assert!(plan.variant.is_empty(), "small buffers need no variant"); - execute(&dev, &pipe, &m, &mut w, &limit_dispatch(n)).expect("dispatch"); - assert_eq!(words(&w.buffers[&5].bytes), want); -} diff --git a/crates/metal2vulkan/src/tests/engine_cross_class.rs b/crates/metal2vulkan/src/tests/engine_cross_class.rs index 79d058a8a..52d1e015a 100644 --- a/crates/metal2vulkan/src/tests/engine_cross_class.rs +++ b/crates/metal2vulkan/src/tests/engine_cross_class.rs @@ -20,16 +20,11 @@ use std::collections::BTreeMap; use std::sync::atomic::{AtomicU64, Ordering}; -use crate::bind::{ - BindState, BoundBuffer, BoundTexture, ImageSource, PlanDiagnostic, StageTable, TextureFacts, - WriteSource, -}; -use crate::budget::{Budget, SPIRV_WORDS}; +use crate::budget::SPIRV_WORDS; use crate::device::DevicePolicy; -use crate::device::{Device, DeviceDescription}; -use crate::library::{FunctionConstantValues, Library}; +use crate::library::FunctionConstantValues; use crate::lower::select::{LowerInputs, Plan}; -use crate::metal::{self, PixelFormat, TextureType}; +use crate::metal::PixelFormat; use crate::pipeline::artifact::PrecisionNote; use crate::pipeline::compile::{compile_bitcode, EntryRef}; use crate::pipeline::facts::RuntimeFact; @@ -40,8 +35,6 @@ use crate::pipeline::testing::{ device_nan_bits, link_and_validate, llvm_assemble, meter, profile, typed_module_with, AssembleError, }; -use crate::pipeline::StageSource; -use crate::pipeline::{ComputePipeline, ComputePipelineDescriptor, FunctionDescriptor}; use crate::spirv::interp::{run_with_images, Buffer, Config, Image, Order, Resources}; use crate::spirv::ir::{GlobalKind, TypedModule}; @@ -114,18 +107,6 @@ impl Ty { } } -/// How the kernel accesses `texture2d` slot 0 at its thread's texel `gid`. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Access { - /// `t.read(gid)` of an `access::read` texture. - Read, - /// `t.sample(s, coord)` through a nearest constexpr sampler at the texel's centre. - Sample, - /// `t.gather(s, coord)` (component 0) through a nearest constexpr sampler at the texel's - /// centre. - Gather, -} - /// The words of a nearest constexpr sampler of normalized coordinates, every axis clamped to /// its edge, no mip filter (`engine_srgb_decode`'s `sampler_words(0, 0, false)`). fn nearest_words() -> u64 { @@ -134,51 +115,19 @@ fn nearest_words() -> u64 { BASE | edge | edge << 3 | edge << 6 } -/// A kernel accessing slot 0 as `access` with `ty` texels at thread `gid` (a 16 x 16 grid), -/// storing the texel to `out[gid.x + 16 gid.y]` (buffer 0). -fn kernel(access: Access, ty: Ty) -> String { +/// A kernel reading slot 0 (an `access::read` texture) with `ty` texels at thread `gid` (a 16 x 16 +/// grid), storing the texel to `out[gid.x + 16 gid.y]` (buffer 0). +fn kernel(ty: Ty) -> String { let (texel, vec4, size, suffix) = ty.spelling(); let out_ty = format!("{texel}4"); - let (tex_access, call, decl) = match access { - Access::Read => ( - "read", - format!( - "%rs = call ptr addrspace(2) @air.get_read_sampler()\n %r = call {{ {vec4}, i8 }} @air.read_texture_2d.{suffix}(ptr addrspace(1) %t, ptr addrspace(2) %rs, <2 x i32> %gid, <2 x i32> zeroinitializer, i32 0, i32 1)" - ), - format!( - "declare ptr addrspace(2) @air.get_read_sampler()\ndeclare {{ {vec4}, i8 }} @air.read_texture_2d.{suffix}(ptr addrspace(1), ptr addrspace(2), <2 x i32>, <2 x i32>, i32, i32)" - ), - ), - Access::Sample => ( - "sample", - format!( - "%r = call {{ {vec4}, i8 }} @air.sample_texture_2d.{suffix}(ptr addrspace(1) %t, ptr addrspace(2) @__air_sampler_state, <2 x float> %uv, i1 true, <2 x i32> zeroinitializer, i1 false, float 0.0, float 0.0, i32 0)" - ), - format!( - "declare {{ {vec4}, i8 }} @air.sample_texture_2d.{suffix}(ptr addrspace(1), ptr addrspace(2), <2 x float>, i1, <2 x i32>, i1, float, float, i32)" - ), - ), - Access::Gather => ( - "sample", - format!( - "%r = call {{ {vec4}, i8 }} @air.gather_texture_2d.{suffix}(ptr addrspace(1) %t, ptr addrspace(2) @__air_sampler_state, <2 x float> %uv, i1 true, <2 x i32> zeroinitializer, i32 0, i32 0)" - ), - format!( - "declare {{ {vec4}, i8 }} @air.gather_texture_2d.{suffix}(ptr addrspace(1), ptr addrspace(2), <2 x float>, i1, <2 x i32>, i32, i32)" - ), - ), - }; - let (state, states, state_md) = match access { - Access::Read => (String::new(), "", ""), - Access::Sample | Access::Gather => ( - format!( - "@__air_sampler_state = internal addrspace(2) constant [2 x i64] [i64 {}, i64 0], align 8\n\n", - nearest_words() - ), - "!air.sampler_states = !{!6}\n", - "!6 = !{!\"air.sampler_state\", ptr addrspace(2) @__air_sampler_state}\n", - ), - }; + let tex_access = "read"; + let call = format!( + "%rs = call ptr addrspace(2) @air.get_read_sampler()\n %r = call {{ {vec4}, i8 }} @air.read_texture_2d.{suffix}(ptr addrspace(1) %t, ptr addrspace(2) %rs, <2 x i32> %gid, <2 x i32> zeroinitializer, i32 0, i32 1)" + ); + let decl = format!( + "declare ptr addrspace(2) @air.get_read_sampler()\ndeclare {{ {vec4}, i8 }} @air.read_texture_2d.{suffix}(ptr addrspace(1), ptr addrspace(2), <2 x i32>, <2 x i32>, i32, i32)" + ); + let (state, states, state_md) = (String::new(), "", ""); format!( r#"{state}define void @k(ptr addrspace(1) %t, ptr addrspace(1) %out, <2 x i32> %gid) {{ %x = extractelement <2 x i32> %gid, i64 0 @@ -362,20 +311,17 @@ fn accesses_through_another_class_are_the_native_words() { }) .collect(); let mut checked = 0; - // The interpreter models no sample or gather: theirs compile and validate in - // `a_texture_of_another_class_joins_the_variant`, and run on the GPU lanes. - let access = Access::Read; for (ty, class) in pairs { // A `ushort` result of a float texture is the `half` result's bits. let native = match (ty, class) { (Ty::Ushort, S::Float) => Ty::Half, _ => Ty::of(class), }; - let name = format!("{access:?} {ty:?} over {class:?}"); - let Some(cross) = assemble(&name, &kernel(access, ty)) else { + let name = format!("Read {ty:?} over {class:?}"); + let Some(cross) = assemble(&name, &kernel(ty)) else { return; }; - let Some(own) = assemble(&name, &kernel(access, native)) else { + let Some(own) = assemble(&name, &kernel(native)) else { return; }; for (stem, p) in &profiles { @@ -423,237 +369,6 @@ fn accesses_through_another_class_are_the_native_words() { assert_eq!(checked, 10 * 2); } -fn devices() -> Vec<(String, Device)> { - let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../metal2vulkan-validation/profiles"); - let mut out = Vec::new(); - for e in std::fs::read_dir(&dir).expect("profiles") { - let path = e.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("profile"); - let desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); - out.push(( - stem, - Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device"), - )); - } - out.sort_by(|a, b| a.0.cmp(&b.0)); - out -} - -/// The kernel compiled into a compute pipeline under `inputs`. -fn pipeline(dev: &Device, bc: &[u8], inputs: &LowerInputs) -> ComputePipeline { - let lib = Library::from_air(bc).expect("library"); - let f = lib.function("k").expect("function"); - let compiled = dev - .compile_function(&FunctionDescriptor::new(f), inputs, &Budget::standard()) - .expect("compile"); - dev.compile_compute_pipeline( - &ComputePipelineDescriptor::new(StageSource::Compiled(compiled)), - &Budget::standard(), - ) - .expect("pipeline") -} - -/// A kernel's state: texture slot 0 bound in `pf` (shader read), buffer 0. -fn state(pf: PixelFormat) -> BindState { - let mut t = StageTable::default(); - let mut facts = TextureFacts::new(TextureType::Type2D, pf); - facts.usage = metal::TextureUsage::SHADER_READ; - t.textures.insert( - 0, - BoundTexture::Texture { - facts, - resource_id: None, - }, - ); - t.buffers.insert( - 0, - BoundBuffer::Buffer { - length: 65536, - offset: 0, - gpu_address: 0x1_0000, - device_address: None, - attribute_stride: None, - }, - ); - let mut s = BindState::default(); - s.stages.insert(Stage::Kernel, t); - s -} - -/// The view format of slot 0's image among a plan's writes, a combined binding's included. -fn view_format(plan: &crate::bind::BindingPlan) -> Option { - plan.descriptors.iter().find_map(|d| match &d.source { - WriteSource::Texture { view, .. } => Some(view.format), - WriteSource::CombinedImageSampler { - image: ImageSource::Texture { view, .. }, - .. - } => Some(view.format), - _ => None, - }) -} - -/// A slot whose compile states `CrossClassReads` bound to a texture of another class joins the -/// plan's variant, with the texture's class; the variant's plan states the same key and views -/// the texture's own format. An integer slot over an 8-bit sRGB texture joins the sRGB variant -/// too, whose raw codes its float reads decode: its gather views the raw format, as a `float` -/// slot's gather of the texture does, on a device that does not sample through Metal's own -/// sampler, whose gather is the table's decode (Metal's uint gather of an `RGBA8Unorm_sRGB` texture -/// is its float gather's bits, the table's decode, 240 of 240 on an M4 and an M3). On every -/// committed profile. -#[test] -fn a_texture_of_another_class_joins_the_variant() { - use SampledType as S; - let cases = [ - (Access::Read, Ty::Float, PixelFormat::R32Uint, S::Uint), - (Access::Read, Ty::Half, PixelFormat::RGBA8Sint, S::Sint), - (Access::Read, Ty::Int, PixelFormat::RGBA16Uint, S::Uint), - (Access::Read, Ty::Uint, PixelFormat::RGBA8Unorm, S::Float), - (Access::Sample, Ty::Float, PixelFormat::RGBA8Uint, S::Uint), - (Access::Sample, Ty::Int, PixelFormat::RGBA16Float, S::Float), - ( - Access::Sample, - Ty::Ushort, - PixelFormat::RGBA8Unorm, - S::Float, - ), - (Access::Read, Ty::Ushort, PixelFormat::RGBA16Sint, S::Sint), - ( - Access::Gather, - Ty::Uint, - PixelFormat::RGBA8UnormSRGB, - S::Float, - ), - ( - Access::Gather, - Ty::Uint, - PixelFormat::RG8UnormSRGB, - S::Float, - ), - ]; - let mut planned = 0; - for (access, ty, pf, class) in cases { - let name = format!("{access:?} {ty:?} over {pf:?}"); - let Some(bc) = assemble(&name, &kernel(access, ty)) else { - return; - }; - for (stem, dev) in devices() { - let what = format!("{name} on {stem}"); - let plain = pipeline(&dev, &bc, &LowerInputs::new()); - assert!( - plain - .dependencies - .iter() - .any(|d| d.fact == RuntimeFact::CrossClassReads { slot: TEXTURE }), - "{what}: no CrossClassReads" - ); - let shape = state(pf).shape(); - let plan = match plain.plan(&dev, &shape) { - Ok(plan) => plan, - // A device that cannot sample the format refuses it for the format. - Err(crate::error::BindError::Unsupported(u)) => { - eprintln!("{what}: {u:?}"); - continue; - } - Err(e) => panic!("{what}: {e}"), - }; - assert_eq!( - plan.variant.cross_class, - BTreeMap::from([(TEXTURE, class)]), - "{what}" - ); - // Only a format the device holds as its UNORM twin joins the sRGB variant. - let twin = crate::metal::texel_format::srgb_twin_on(pf, dev.profile()); - assert_eq!( - plan.variant.srgb_textures.contains(&TEXTURE), - twin, - "{what}" - ); - let key = plan.variant.lowering_inputs(Stage::Kernel); - assert_eq!(key.cross_class, plan.variant.cross_class, "{what}"); - validate(&bc, &key, dev.profile(), &what); - let variant = pipeline(&dev, &bc, &key); - let again = variant.plan(&dev, &shape).expect("variant plan"); - assert_eq!(again.variant, plan.variant, "{what}"); - assert!( - again.diagnostics.is_empty(), - "{what}: {:?}", - again.diagnostics - ); - let view = view_format(&again).unwrap_or_else(|| panic!("{what}: no view")); - // Every access views the texture's own format, an sRGB one's decoding its codes; a - // format held as its UNORM twin, the twin's. - let usages = [crate::device::FormatUsage::SampledImage].into(); - let held = match twin { - true => crate::metal::format::srgb_raw_twin(pf).expect("a twin"), - false => pf, - }; - let want = crate::metal::format::vk_format(held, &usages, dev.profile()) - .expect("the format") - .format; - assert_eq!(view, want, "{what}"); - planned += 1; - // A texture of the declared class leaves the variant. - let same = match ty { - Ty::Float | Ty::Half => PixelFormat::RGBA8Unorm, - Ty::Int => PixelFormat::RGBA8Sint, - _ => PixelFormat::RGBA8Uint, - }; - let other = variant.plan(&dev, &state(same).shape()).expect("plan"); - assert!(other.variant.cross_class.is_empty(), "{what}"); - } - } - assert!(planned > 0); -} - -/// A slot read with a `uint` result over a texture of a depth format, whose read in another -/// class the binder does not take (`metal::texel_format::crosses_classes`), binds the slot's -/// neutral, which the plan reports as `CrossClassNeutral`, and asks for no variant. On every -/// committed profile that samples the format. -#[test] -fn an_unanswered_result_binds_the_neutral_and_says_so() { - let Some(bc) = assemble("uint over depth", &kernel(Access::Read, Ty::Uint)) else { - return; - }; - let mut planned = 0; - for (stem, dev) in devices() { - let plain = pipeline(&dev, &bc, &LowerInputs::new()); - assert!( - plain - .dependencies - .iter() - .any(|d| d.fact == RuntimeFact::CrossClassReads { slot: TEXTURE }), - "{stem}" - ); - let plan = match plain.plan(&dev, &state(PixelFormat::Depth32Float).shape()) { - Ok(plan) => plan, - Err(crate::error::BindError::Unsupported(u)) => { - eprintln!("{stem}: {u:?}"); - continue; - } - Err(e) => panic!("{stem}: {e}"), - }; - assert!(plan.variant.cross_class.is_empty(), "{stem}"); - assert!( - plan.diagnostics.iter().any( - |d| matches!(d, PlanDiagnostic::CrossClassNeutral { slot, .. } if *slot == TEXTURE) - ), - "{stem}: {:?}", - plan.diagnostics - ); - assert_eq!(view_format(&plan), None, "{stem}"); - planned += 1; - } - assert!(planned > 0); -} - /// What a kernel does with the `texture2d` its argument buffer holds. #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Held { @@ -1230,161 +945,3 @@ fn integer_writes_into_narrow_floats_take_the_devices_conversion() { } assert_eq!(checked, 8); } - -/// A kernel's state for [`write_kernel`]: texture slot 0 bound in `pf` (shader write), buffer 0. -fn write_state(pf: PixelFormat) -> BindState { - let mut s = state(pf); - if let Some(t) = s.stages.get_mut(&Stage::Kernel) { - let mut facts = TextureFacts::new(TextureType::Type2D, pf); - facts.usage = metal::TextureUsage::SHADER_WRITE; - t.textures.insert( - 0, - BoundTexture::Texture { - facts, - resource_id: None, - }, - ); - } - s -} - -/// Through the device's binder: a write kernel's plan over a texture of each integer format, its -/// variant's compile, the dispatch's push bytes and specialization, run on the interpreter, stores -/// Metal's saturated words, whether the slot declares the format (a device without formatless -/// storage writes, or a texture of another class) or reads the binder's -/// `PushField::TextureIntegerChannels` word. On every committed profile that writes the format. -#[test] -fn the_binder_saturates_each_bound_formats_channels() { - use crate::bind::Dispatch; - use PixelFormat as P; - let cases = [ - (Ty::Uint, P::RGBA8Uint), - (Ty::Int, P::RGBA16Sint), - (Ty::Uint, P::RGB10A2Uint), - (Ty::Uint, P::R32Uint), - (Ty::Ushort, P::R8Uint), - (Ty::Int, P::RGBA8Uint), - ]; - let (mut worded, mut declared) = (0, 0); - for (ty, pf) in cases { - let name = format!("bound write {ty:?} over {pf:?}"); - let Some(bc) = assemble(&name, &write_kernel(ty)) else { - return; - }; - let sixteen = matches!(ty, Ty::Ushort | Ty::Short); - let format = crate::metal::format::direct_format(pf).expect("format"); - let signed = format.block().expect("block").color == Some(crate::vk::NumericFormat::Sint); - let bits = crate::metal::format::integer_channel_bits(format).expect("integer"); - let lane = |n: u32, c: usize| match sixteen { - true => u32::from(HALVES[(n as usize * 4 + c) * 5 % HALVES.len()]), - false => WORDS[(n as usize * 4 + c) * 5 % WORDS.len()], - }; - let src: Vec = (0..SIDE * SIDE) - .flat_map(|n| (0..4).map(move |c| (n, c))) - .flat_map(|(n, c)| match sixteen { - true => (lane(n, c) as u16).to_le_bytes().to_vec(), - false => lane(n, c).to_le_bytes().to_vec(), - }) - .collect(); - for (stem, dev) in devices() { - let what = format!("{name} on {stem}"); - let s = write_state(pf); - // A device that declares every storage image's format compiles the slot only under - // a plan's choice. - let lib = Library::from_air(&bc).expect("library"); - let f = FunctionDescriptor::new(lib.function("k").expect("function")); - let budget = Budget::standard(); - if let Err(e) = dev.compile_function(&f, &LowerInputs::new(), &budget) { - eprintln!("{what}: {e}"); - continue; - } - let plain = pipeline(&dev, &bc, &LowerInputs::new()); - let plan = match plain.plan(&dev, &s.shape()) { - Ok(plan) => plan, - Err(crate::error::BindError::Unsupported(u)) => { - eprintln!("{what}: {u:?}"); - continue; - } - Err(e) => panic!("{what}: {e}"), - }; - let key = plan.variant.lowering_inputs(Stage::Kernel); - let pipe = pipeline(&dev, &bc, &key); - let plan = pipe.plan(&dev, &s.shape()).expect("variant plan"); - let reads_word = pipe - .dependencies - .iter() - .any(|d| d.fact == RuntimeFact::StorageTextureIntegerChannels { slot: TEXTURE }); - match reads_word { - true => worded += 1, - false => declared += 1, - } - let cmds = plan - .instantiate_dispatch( - &s, - &Dispatch::Threadgroups { - groups: [SIDE, SIDE, 1], - threads_per_group: [1, 1, 1], - }, - ) - .expect("instantiate"); - let region = &cmds.regions[0]; - let mut push = Vec::new(); - if let Some(w) = region.push_constants.first() { - push = vec![0u8; w.offset as usize + w.bytes.len()]; - push[w.offset as usize..].copy_from_slice(&w.bytes); - } - let ids: BTreeMap = pipe - .stage - .specialization - .constants - .iter() - .map(|c| (c.id, c.key)) - .collect(); - let mut spec = BTreeMap::new(); - for e in ®ion.specialization.entries { - let at = e.offset as usize; - let mut v = [0u8; 8]; - v[..e.size as usize] - .copy_from_slice(®ion.specialization.data[at..at + e.size as usize]); - spec.insert(ids[&e.constant_id], u64::from_le_bytes(v)); - } - let (_, m) = typed_module_with(&bc, "k", dev.profile(), &key) - .unwrap_or_else(|e| panic!("{what}: {e}")); - let res = Resources { - buffers: vec![Buffer { - slot: Some(ResourceSlot { - stage: Stage::Kernel, - kind: ResourceKind::Buffer, - index: 0, - }), - address: None, - bytes: src.clone(), - }], - push, - spec, - }; - let img = Image::new(resource(&m), [SIDE, SIDE, 1], 1, 1, 1); - let cfg = Config { - workgroups: [SIDE, SIDE, 1], - ..Config::default() - }; - let (_, images) = run_with_images(&m, &cfg, res, vec![img]) - .unwrap_or_else(|e| panic!("{what}: interpreter: {e:?}")); - let img = images.into_iter().next().expect("image"); - for n in 0..SIDE * SIDE { - let at = img.index(0, 0, 0, [n % SIDE, n / SIDE, 0]).expect("texel"); - for (c, b) in bits.iter().enumerate() { - let want = metal_store(lane(n, c), sixteen, *b, signed); - assert_eq!( - img.texels[at][c], - want, - "{what}: texel {n} lane {c}: {:#x}", - lane(n, c) - ); - } - } - } - } - println!("integer channels: {worded} plans read the word, {declared} declare the format"); - assert!(worded > 0 && declared > 0, "{worded} {declared}"); -} diff --git a/crates/metal2vulkan/src/tests/engine_device_replay.rs b/crates/metal2vulkan/src/tests/engine_device_replay.rs index 5f2add26d..4a04e627f 100644 --- a/crates/metal2vulkan/src/tests/engine_device_replay.rs +++ b/crates/metal2vulkan/src/tests/engine_device_replay.rs @@ -17,49 +17,24 @@ //! //! `llvm-as` assembles the fixture; without it the tests skip visibly. -use std::collections::BTreeMap; -use std::num::NonZeroU64; use std::path::Path; use std::sync::atomic::{AtomicU64, Ordering}; -use crate::bind::{ - BindState, BoundBuffer, Dispatch, ExecutionStatus, IndirectRef, PushHole, ResourceClass, - RootTable, StageTable, UsedResource, WriteSource, -}; use crate::budget::Budget; use crate::cache::VariantKey; use crate::device::profile::BufferAccess; -use crate::device::requirements::VkFeature; use crate::device::{Device, DeviceDescription, DevicePolicy}; -use crate::error::{BindError, Error, Feature, Needs}; -use crate::indirect_commands::{Action, BufferBinding, BufferStage, CommandRecord}; +use crate::error::{Error, Feature, Needs}; use crate::library::Library; use crate::pipeline::facts::RuntimeFact; -use crate::pipeline::layout::BindingSource; -use crate::pipeline::sym::{PushField, ResourceKind, ResourceSlot, SpecKey, Stage}; -use crate::pipeline::testing::{engine_dir, llvm_assemble, typed_module_with, AssembleError}; +use crate::pipeline::sym::Stage; +use crate::pipeline::testing::{llvm_assemble, AssembleError}; use crate::pipeline::{ ComputePipeline, ComputePipelineDescriptor, FunctionDescriptor, LoweringInputs, StageSource, }; -use crate::spirv::interp::{run, Buffer, Config, Order, Resources}; -use crate::spirv::ir::TypedModule; -use crate::spirv::testing::refuses_threadgroup_memory; const HEADER: &str = "target datalayout = \"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32\"\ntarget triple = \"air64_v28-apple-macosx26.0.0\"\n\n"; -/// Device addresses of the consumer's objects. -const STATUS: u64 = 0x0000_0012_0000_0000; -const SINK: u64 = 0x0000_0011_0000_0000; - -/// The two resident allocations `(guest, host)`, `BYTES` each: the parameters and the output. -const PARAMS: (u64, u64) = (0x0000_0001_0000_0000, 0x0000_0020_0000_0000); -const OUT: (u64, u64) = (0x0000_0001_0001_0000, 0x0000_0021_0000_0000); -const BYTES: usize = 512; - -const TOKEN: u64 = 0x0123_4567_89ab_cdef; -/// The template's threadgroup length: one word per thread of a group. -const LENGTH: u32 = 32; - /// `text` (an AIR module body) assembled, with the AIR target header. fn assemble(name: &str, text: &str) -> Option> { static NEXT: AtomicU64 = AtomicU64::new(0); @@ -88,24 +63,6 @@ fn devices() -> Vec<(String, Device)> { devices_with(|_| {}) } -/// Every committed profile as a device, and lavapipe without `bufferDeviceAddress`: the committed -/// profiles without device addresses take no threadgroup memory, which the replayed kernels use. -fn devices_and_unaddressed() -> Vec<(String, Device)> { - let mut out = devices(); - let path = Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../metal2vulkan-validation/profiles/lavapipe.json"); - let text = std::fs::read_to_string(path).expect("profile"); - let mut desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); - desc.features.remove(&VkFeature::BufferDeviceAddress); - let dev = Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device"); - assert_ne!( - dev.profile().fields().buffer_access, - BufferAccess::Addressed - ); - out.push(("lavapipe without device addresses".into(), dev)); - out -} - /// Every committed profile as a device, by stem, with its description changed by `tweak`. fn devices_with(tweak: impl Fn(&mut DeviceDescription)) -> Vec<(String, Device)> { let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../metal2vulkan-validation/profiles"); @@ -132,12 +89,6 @@ fn devices_with(tweak: impl Fn(&mut DeviceDescription)) -> Vec<(String, Device)> out } -fn replay_inputs() -> LoweringInputs { - let mut inputs = LoweringInputs::new(); - inputs.replay_bindings = true; - inputs -} - /// Function `entry` of `bc` compiled under `inputs`, through the public API. fn pipeline( dev: &Device, @@ -152,360 +103,6 @@ fn pipeline( dev.compile_compute_pipeline(&d, &Budget::standard()) } -/// What every replayed command shares: threadgroup length 0 `length` (0: none) and the two -/// resident allocations; no kernel buffer. -fn shared_state(length: u32) -> BindState { - let mut kernel = StageTable::default(); - if length != 0 { - kernel.threadgroup_lengths.insert(0, length); - } - let mut s = BindState::default(); - s.stages.insert(Stage::Kernel, kernel); - for (i, (guest, host)) in [PARAMS, OUT].into_iter().enumerate() { - let mut u = UsedResource::new(ResourceClass::Buffer, i as u32); - u.gpu_address = Some(guest); - u.device_address = Some(host); - u.length = BYTES as u64; - s.used_resources.push(u); - } - s -} - -/// A record of `action` with the template's pipeline and threadgroup length, kernel buffer 0 at -/// `params` and kernel buffer 1 at `out` (guest addresses). -fn record(action: Action, params: u64, out: u64) -> CommandRecord { - let mut r = CommandRecord { - action, - ..CommandRecord::default() - }; - r.bindings.pipeline = NonZeroU64::new(TOKEN); - let kernel = r.bindings.buffers_mut(BufferStage::Kernel); - for (slot, address) in [(0, params), (1, out)] { - kernel[slot] = Some(BufferBinding { - address, - attribute_stride: None, - }); - } - r.threadgroup_memory_lengths[0] = LENGTH; - r -} - -fn words(bytes: &[u8]) -> Vec { - bytes - .as_chunks::<4>() - .0 - .iter() - .map(|c| u32::from_le_bytes(*c)) - .collect() -} - -/// Run `m` with `res`'s push and spec over `workgroups` in both scheduling orders; the buffers. -fn run_both(m: &TypedModule, workgroups: [u32; 3], res: Resources) -> Vec> { - let mut outs = Vec::new(); - for order in [Order::Forward, Order::Reverse] { - let cfg = Config { - workgroups, - order, - ..Config::default() - }; - outs.push(run(m, &cfg, res.clone()).expect("run").buffers); - } - assert_eq!(outs[0], outs[1], "the two scheduling orders agree"); - outs.swap_remove(0) -} - -/// The typed-module symbol of a layout binding. -fn symbol(source: BindingSource) -> ResourceSlot { - match source { - BindingSource::Buffer(slot) => ResourceSlot { - stage: slot.stage, - kind: ResourceKind::Buffer, - index: slot.index, - }, - BindingSource::Synthetic { stage, binding } => ResourceSlot { - stage, - kind: ResourceKind::Synthetic(binding), - index: 0, - }, - other => panic!("a compute binding {other:?}"), - } -} - -/// The template that observes its regions: each thread adds a weighted sum of its grid builtins and -/// its neighbour's staged index to `out[index % params[1]]`. -const GRID: &str = "icb_replay_grid_template"; -/// The grid template's threadgroup length: the 128-byte length its encoders set. -const GRID_LENGTH: u32 = 128; - -fn grid_fixture() -> Option> { - match llvm_assemble(&engine_dir().join(format!("{GRID}.ll"))) { - Ok(b) => Some(b), - Err(AssembleError::Missing(why)) => { - eprintln!("SKIPPED: {why}"); - None - } - Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected {GRID}.ll: {why}"), - } -} - -/// A grid-template command: `action` with the parameters window at `params` and the output -/// window at `out` (byte offsets into the two allocations), and the 128-byte length. -fn grid_record(action: Action, params: u64, out: u64) -> CommandRecord { - let mut r = record(action, PARAMS.0 + params, OUT.0 + out); - r.threadgroup_memory_lengths[0] = GRID_LENGTH; - r -} - -/// The parameters allocation: `(word offset, params[0], params[1])` windows. -fn grid_params(windows: &[(usize, u32, u32)]) -> Vec { - let mut params = vec![0u8; BYTES]; - for &(at, base, modulus) in windows { - params[4 * at..4 * at + 4].copy_from_slice(&base.to_le_bytes()); - params[4 * at + 4..4 * at + 8].copy_from_slice(&modulus.to_le_bytes()); - } - params -} - -/// The window of kernel buffer `slot` of `c`: its allocation `(guest, host)` and its offset. -fn window(c: &CommandRecord, slot: usize) -> ((u64, u64), u64) { - let address = c.bindings.buffers(BufferStage::Kernel)[slot] - .expect("a buffer set") - .address; - let allocation = [PARAMS, OUT] - .into_iter() - .find(|&(guest, _)| (guest..guest + BYTES as u64).contains(&address)) - .expect("an address in an allocation"); - (allocation, address - allocation.0) -} - -/// The bind state of command `c`'s own dispatch: its kernel buffers bound in their allocations, -/// its threadgroup lengths, and the two resident allocations; and each bound slot's allocation -/// (its guest address). -fn command_state(c: &CommandRecord) -> (BindState, BTreeMap) { - let mut state = shared_state(0); - let kernel = state.stages.get_mut(&Stage::Kernel).expect("kernel"); - let mut slots = BTreeMap::new(); - for slot in 0..2 { - let ((guest, host), offset) = window(c, slot); - kernel.buffers.insert( - slot as u32, - BoundBuffer::Buffer { - length: BYTES as u64, - offset, - gpu_address: guest, - device_address: Some(host), - attribute_stride: None, - }, - ); - slots.insert(slot as u32, guest); - } - for (i, &l) in c.threadgroup_memory_lengths.iter().enumerate() { - if l != 0 { - kernel.threadgroup_lengths.insert(i as u32, l); - } - } - (state, slots) -} - -/// The host replay of `commands` over `entry` of `bc` compiled as a flat variant -/// (`VariantKey::flat_grid`), on `dev`, with the parameters allocation holding `params`: each -/// `dispatchThreads:` command runs as the one direct region `instantiate_dispatch` plans, of the -/// command's own threadgroup size, binding its kernel buffers in their allocations and its -/// threadgroup lengths and reading the record the plan states (`DispatchCommands::region_record`), -/// in order. The output allocation it leaves. -fn host_replay( - stem: &str, - (dev, bc, entry): (&Device, &[u8], &str), - commands: &[CommandRecord], - params: &[u8], -) -> Vec { - const ROOT: u64 = 0x0000_0040_0000_0000; - const REGION: u64 = 0x0000_0041_0000_0000; - let mut key = VariantKey::new(); - key.flat_grid = true; - let inputs = key.lowering_inputs(Stage::Kernel); - let pipe = pipeline(dev, bc, entry, &inputs).unwrap_or_else(|e| panic!("{stem}: {e}")); - let (_, m) = typed_module_with(bc, entry, dev.profile(), &inputs) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - let layout: BTreeMap<(u32, u32), BindingSource> = pipe - .layout - .sets - .iter() - .flat_map(|s| { - s.bindings - .iter() - .map(move |b| ((s.set, b.binding), b.source)) - }) - .collect(); - let ids: BTreeMap = pipe - .stage - .specialization - .constants - .iter() - .map(|c| (c.id, c.key)) - .collect(); - // The two allocations, by guest address. - let mut memory: BTreeMap> = - BTreeMap::from([(PARAMS.0, params.to_vec()), (OUT.0, vec![0; BYTES])]); - for c in commands { - let dispatch = match c.action { - Action::Empty => continue, - Action::DispatchThreadgroups { grid, local_size } => Dispatch::Threadgroups { - groups: grid, - threads_per_group: local_size, - }, - Action::DispatchThreads { grid, local_size } => Dispatch::Threads { - threads: grid, - threads_per_group: local_size, - }, - other => panic!("{other:?}"), - }; - // A direct dispatch on a flat variant keeps its own counts and reads the record the plan - // states. - let volume = dispatch - .threads_per_group() - .iter() - .map(|&l| u64::from(l)) - .product::(); - if volume == 0 || volume > u64::from(FLAT_MAX) { - continue; - } - let (state, slots) = command_state(c); - let plan = pipe - .plan(dev, &state.shape()) - .unwrap_or_else(|e| panic!("{stem}: {e:?}")); - assert_eq!(plan.variant, key, "{stem}"); - let cmds = plan - .instantiate_dispatch(&state, &dispatch) - .unwrap_or_else(|e| panic!("{stem}: {dispatch:?}: {e:?}")); - // A direct dispatch on a flat variant: the record is the plan's, the consumer's to write. - let record = cmds - .region_record - .map_or_else(Vec::new, |bytes| bytes.to_vec()); - assert_eq!( - cmds.regions.len(), - 1, - "{stem}: a flat dispatch is one region" - ); - for region in &cmds.regions { - assert_eq!(region.indirect, None, "{stem}"); - assert!( - cmds.region_record.is_some(), - "{stem}: a direct dispatch on a flat variant states its own record" - ); - // Each buffer the region reaches, and the allocation and offset its bytes return to. - let mut buffers = Vec::new(); - let mut back: Vec> = Vec::new(); - for w in &plan.descriptors { - let sym = symbol(layout[&(w.set, w.binding)]); - let (bytes, to) = match &w.source { - WriteSource::Buffer { slot } => { - let r = cmds - .descriptor_ranges - .iter() - .find(|r| (r.set, r.binding) == (w.set, w.binding)) - .expect("a range for every buffer write") - .range; - let guest = slots[&slot.index]; - let (o, n) = (r.offset as usize, r.range as usize); - (memory[&guest][o..o + n].to_vec(), Some((guest, o))) - } - WriteSource::Neutral(_) => (vec![0; 4096], None), - WriteSource::ArgumentTable { .. } => ( - cmds.descriptor_bytes - .iter() - .find(|d| (d.set, d.binding) == (w.set, w.binding)) - .expect("argument table bytes") - .bytes - .clone(), - None, - ), - other => panic!("{stem}: a host-replayed write {other:?}"), - }; - buffers.push(Buffer { - slot: Some(sym), - address: None, - bytes, - }); - back.push(to); - } - for (guest, host) in [PARAMS, OUT] { - buffers.push(Buffer { - slot: None, - address: Some(host), - bytes: memory[&guest].clone(), - }); - back.push(Some((guest, 0))); - } - let mut table = Vec::new(); - if let Some(t) = &cmds.root_table { - table = t.bytes.clone(); - let at = RootTable::SINK_HOST_OFFSET as usize; - table[at..at + 8].copy_from_slice(&SINK.to_le_bytes()); - } - for (address, bytes) in [ - (ROOT, table), - (REGION, record.clone()), - (STATUS, ExecutionStatus::initial().to_vec()), - (SINK, vec![0; 64]), - ] { - buffers.push(Buffer { - slot: None, - address: Some(address), - bytes, - }); - back.push(None); - } - let mut push = Vec::new(); - if let Some(w) = region.push_constants.first() { - push = vec![0u8; (w.offset as usize) + w.bytes.len()]; - push[w.offset as usize..].copy_from_slice(&w.bytes); - } - for hole in &cmds.push_holes { - let (offset, address) = match *hole { - PushHole::RootTableAddress { offset, .. } => (offset, ROOT), - PushHole::ExecutionStatusAddress { offset, .. } => (offset, STATUS), - PushHole::ReplayRegionAddress { offset, .. } => (offset, REGION), - other => panic!("{stem}: {other:?}"), - }; - push[offset as usize..offset as usize + 8].copy_from_slice(&address.to_le_bytes()); - } - let mut spec = BTreeMap::new(); - for e in ®ion.specialization.entries { - let at = e.offset as usize; - let mut x = [0u8; 8]; - x[..e.size as usize] - .copy_from_slice(®ion.specialization.data[at..at + e.size as usize]); - spec.insert(ids[&e.constant_id], u64::from_le_bytes(x)); - } - let inputs: Vec> = buffers.iter().map(|b| b.bytes.clone()).collect(); - let res = Resources { - buffers, - push, - spec, - }; - let outs = run_both(&m, region.group_count, res); - // A region reaches each byte through one path: only the bytes it changed return. - for ((after, before), to) in outs.into_iter().zip(inputs).zip(back) { - let Some((guest, offset)) = to else { - continue; - }; - let target = memory.get_mut(&guest).expect("allocation"); - for (i, (a, b)) in after.into_iter().zip(before).enumerate() { - if a != b { - target[offset + i] = a; - } - } - } - } - } - assert_eq!( - memory[&PARAMS.0], params, - "{stem}: the parameters are only read" - ); - memory.remove(&OUT.0).expect("output") -} - /// `flat(b0, b1, p, g)`: each thread adds `b0[0] + 3 p.x + 5 p.y + 7 p.z + 11 g.x + 13 g.y + /// 17 g.z` to `b1[p.x + p.y g.x + p.z g.x g.y]` by a relaxed atomic whose result it does not /// read, reading only `thread_position_in_grid` and `threads_per_grid`: it does not observe its @@ -566,308 +163,6 @@ fn flat_rmw() -> String { ) } -/// The most threads per threadgroup of the flat tests' state. -const FLAT_MAX: u32 = 1024; - -/// What Metal computes for the flat kernel's `commands`: each command of a nonempty grid and a -/// threadgroup of 1 to `FLAT_MAX` threads adds each grid thread's value into its output window. -fn metal_flat(commands: &[CommandRecord], params: &[u8]) -> Vec { - let params = words(params); - let mut out = vec![0u32; BYTES / 4]; - for c in commands { - let (threads, local) = match c.action { - Action::Empty => continue, - Action::DispatchThreadgroups { grid, local_size } => ( - std::array::from_fn::(|i| grid[i] * local_size[i]), - local_size, - ), - Action::DispatchThreads { grid, local_size } => (grid, local_size), - other => panic!("{other:?}"), - }; - let volume = local.iter().map(|&l| u64::from(l)).product::(); - if volume == 0 || volume > u64::from(FLAT_MAX) { - continue; - } - let base = params[window(c, 0).1 as usize / 4]; - let o = window(c, 1).1 as usize / 4; - for z in 0..threads[2] { - for y in 0..threads[1] { - for x in 0..threads[0] { - let terms = [ - (3, x), - (5, y), - (7, z), - (11, threads[0]), - (13, threads[1]), - (17, threads[2]), - ]; - let v = terms - .iter() - .fold(base, |v, &(k, a)| v.wrapping_add(a.wrapping_mul(k))); - let at = o + (x + y * threads[0] + z * threads[0] * threads[1]) as usize; - out[at] = out[at].wrapping_add(v); - } - } - } - } - out.iter().flat_map(|w| w.to_le_bytes()).collect() -} - -/// A flat-kernel command: `action` with its base word at `params` and its output window at -/// `out` (byte offsets into the two allocations), with the template record's 32-byte length, -/// which the flat variant ignores. -fn flat_record(action: Action, params: u64, out: u64) -> CommandRecord { - record(action, PARAMS.0 + params, OUT.0 + out) -} - -/// The flat tests' commands, and their parameters: ragged thread grids and threadgroup grids of -/// threadgroup sizes other than a variant's, an empty command, and threadgroups with a zero axis -/// or above `FLAT_MAX` threads, which run nothing. -fn flat_commands() -> (Vec, Vec) { - let commands = vec![ - flat_record( - Action::DispatchThreads { - grid: [10, 3, 1], - local_size: [4, 2, 1], - }, - 0, - 0, - ), - flat_record( - Action::DispatchThreadgroups { - grid: [2, 2, 2], - local_size: [3, 1, 1], - }, - 4, - 128, - ), - CommandRecord::default(), - flat_record( - Action::DispatchThreads { - grid: [5, 1, 1], - local_size: [32, 32, 2], - }, - 8, - 400, - ), - flat_record( - Action::DispatchThreads { - grid: [5, 1, 1], - local_size: [0, 1, 1], - }, - 8, - 400, - ), - flat_record( - Action::DispatchThreads { - grid: [7, 2, 3], - local_size: [1, 1, 1], - }, - 12, - 224, - ), - ]; - let mut params = vec![0u8; BYTES]; - for (at, w) in [(0, 1000u32), (4, 7), (8, 99), (12, 0x8000_0000)] { - params[at..at + 4].copy_from_slice(&w.to_le_bytes()); - } - (commands, params) -} - -/// Outside a replay, on every profile with device addresses, the flat variant binds as any kernel -/// does: a direct `dispatchThreads:` of a flat plan is one region of its own threadgroup size, at -/// group counts that cover the grid, reading the record the plan states; a direct -/// `dispatchThreadgroups:` of one, and an indirect dispatch, whose record only a device replay's -/// preprocess writes, are refused. -#[test] -fn a_flat_variant_dispatches_outside_a_replay() { - let Some(bc) = assemble("flat", FLAT) else { - return; - }; - let (commands, _) = flat_commands(); - let mut key = VariantKey::new(); - key.flat_grid = true; - let mut ran = 0; - for (stem, dev) in devices() { - if dev.profile().fields().buffer_access != BufferAccess::Addressed { - continue; - } - ran += 1; - let pipe = pipeline(&dev, &bc, "flat", &key.lowering_inputs(Stage::Kernel)) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - let (state, _) = command_state(&commands[0]); - let plan = pipe - .plan(&dev, &state.shape()) - .unwrap_or_else(|e| panic!("{stem}: {e:?}")); - let direct = Dispatch::Threads { - threads: [10, 3, 1], - threads_per_group: [8, 1, 1], - }; - let cmds = plan - .instantiate_dispatch(&state, &direct) - .unwrap_or_else(|e| panic!("{stem}: {e:?}")); - assert_eq!(cmds.regions.len(), 1, "{stem}"); - assert_eq!(cmds.regions[0].indirect, None, "{stem}"); - // 10 x 3 threads is 30, which 4 threadgroups of 8 cover. - assert_eq!(cmds.regions[0].group_count, [4, 1, 1], "{stem}"); - assert_eq!( - cmds.region_record, - Some( - crate::lower::dispatch::region_bytes([0; 3], [10, 3, 1], [8, 1, 1]) - .expect("a packable threadgroup size") - ), - "{stem}" - ); - // Its threadgroups are the shader's, so a `dispatchThreadgroups:` has no flat form, and - // only a device replay's preprocess writes an indirect dispatch's record. - let groups = Dispatch::Threadgroups { - groups: [2, 1, 1], - threads_per_group: [8, 1, 1], - }; - let indirect = Dispatch::ThreadgroupsIndirect { - indirect: IndirectRef { - token: 0, - offset: 0, - }, - threads_per_group: [8, 1, 1], - }; - for refused in [groups, indirect] { - match plan.instantiate_dispatch(&state, &refused) { - Err(BindError::Unsupported(u)) => { - assert_eq!(u.feature, Feature::GpuEncodedIndirectCommands, "{stem}") - } - other => panic!("{stem}: {refused:?}: {:?}", other.map(|_| ())), - } - } - } - assert!(ran > 0, "no profile with device addresses"); -} - -/// A direct `dispatchThreads:` whose grid is not a whole number of threadgroups runs, on every -/// profile with device addresses, as one Vulkan dispatch of its own threadgroup size on the -/// kernel's flat variant, in place of the interior and ragged-edge regions a split records: the -/// kernel's own compiled SPIR-V, run over the plan's one region and the record the plan states, -/// adds exactly what Metal adds. The kernel accumulates into one slot per grid thread, so a thread -/// run twice, a thread not run, or an invocation past the grid taking a slot all move a word. -#[test] -fn a_direct_ragged_dispatch_on_a_flat_variant_runs_each_grid_thread_once() { - let Some(bc) = assemble("flat", FLAT) else { - return; - }; - // Ragged on two axes (four split regions), ragged with no whole threadgroup along x (one), - // ragged on all three (eight), and a grid that is a whole number of threadgroups (one), each - // with its own output window inside the fixture's allocation. - let commands = vec![ - flat_record( - Action::DispatchThreads { - grid: [10, 3, 1], - local_size: [4, 2, 1], - }, - 0, - 0, - ), - flat_record( - Action::DispatchThreads { - grid: [5, 1, 1], - local_size: [8, 1, 1], - }, - 4, - 120, - ), - flat_record( - Action::DispatchThreads { - grid: [5, 3, 5], - local_size: [4, 2, 3], - }, - 8, - 144, - ), - flat_record( - Action::DispatchThreads { - grid: [4, 2, 1], - local_size: [4, 2, 1], - }, - 12, - 448, - ), - ]; - let mut params = vec![0u8; BYTES]; - for (at, w) in [(0, 1000u32), (4, 7), (8, 99), (12, 0x8000_0000)] { - params[at..at + 4].copy_from_slice(&w.to_le_bytes()); - } - let metal = metal_flat(&commands, ¶ms); - let mut ran = 0; - for (stem, dev) in devices() { - if dev.profile().fields().buffer_access != BufferAccess::Addressed { - continue; - } - ran += 1; - let out = host_replay(&stem, (&dev, &bc, "flat"), &commands, ¶ms); - assert_eq!(words(&out), words(&metal), "{stem}"); - } - assert!(ran > 0, "no profile with device addresses"); -} - -/// A kernel that observes its threadgroup partition (the grid template reads its threadgroup's size -/// and position) is refused as a flat variant, with the replay's bindings or without. The flat -/// kernel compiles under `VariantKey::flat_grid` as any other kernel binds, and reads its grid from -/// the region record at `ReplayRegionAddress` (no `DispatchRegion`); it states -/// `RuntimeFact::FlatGrid`, so its plan states the key, and it refuses emulated simdgroups. A -/// profile without device addresses names what it lacks. -#[test] -fn a_flat_grid_is_a_partition_oblivious_variant_s() { - let (Some(grid), Some(flat)) = (grid_fixture(), assemble("flat", FLAT)) else { - return; - }; - let mut key = VariantKey::new(); - key.flat_grid = true; - let plain = key.lowering_inputs(Stage::Kernel); - let mut replayed = replay_inputs(); - replayed.flat_grid = true; - let mut emulated = plain.clone(); - emulated.emulated_simdgroups = true; - let mut ran = 0; - for (stem, dev) in devices() { - let refused = |r: Result| match r { - Err(Error::Unsupported(u)) => { - assert_eq!(u.feature, Feature::GpuEncodedIndirectCommands, "{stem}") - } - other => panic!("{stem}: {:?}", other.map(|_| ())), - }; - if dev.profile().fields().buffer_access != BufferAccess::Addressed { - refused(pipeline(&dev, &flat, "flat", &plain)); - continue; - } - ran += 1; - refused(pipeline(&dev, &grid, GRID, &replayed)); - refused(pipeline(&dev, &grid, GRID, &plain)); - refused(pipeline(&dev, &flat, "flat", &emulated)); - assert!(pipeline(&dev, &flat, "flat", &replayed).is_ok(), "{stem}"); - let pipe = pipeline(&dev, &flat, "flat", &plain).unwrap_or_else(|e| panic!("{stem}: {e}")); - assert!( - pipe.dependencies - .iter() - .any(|d| d.fact == RuntimeFact::FlatGrid), - "{stem}" - ); - let (typed, _) = typed_module_with(&flat, "flat", dev.profile(), &plain) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - let fields: Vec = typed.push.fields.iter().map(|f| f.field).collect(); - assert!( - fields.contains(&PushField::ReplayRegionAddress) - && !fields.contains(&PushField::DispatchRegion) - && !fields.contains(&PushField::RootTableAddress), - "{stem}: {fields:?}" - ); - let (state, _) = command_state(&flat_record(Action::Empty, 0, 0)); - let plan = pipe - .plan(&dev, &state.shape()) - .unwrap_or_else(|e| panic!("{stem}: {e:?}")); - assert_eq!(plan.variant, key, "{stem}"); - } - assert!(ran > 0, "no profile with device addresses"); -} - /// Known gap: [`flat_rmw`], the flat kernel's addition as a plain load and store of `b1[p.x + p.y /// g.x + p.z g.x g.y]`, takes a device lockstep barrier between them. The analysis proves two /// lanes' words apart only through their index in the simdgroup or the threadgroup, and two lanes @@ -1040,124 +335,3 @@ fn a_flat_grid_of_the_call_s_threadgroups_admits_a_kernel_of_simdgroups() { assert!(ran > 0, "no profile with device addresses"); assert!(sums > 0, "no profile ran the simdgroup sum flat"); } - -/// The folded tests' commands and parameters: threadgroup dispatches of the grid template, -/// three of them past a 3 x 2 x 64 device's `x` and `y`, and an empty command. -fn folded_commands() -> (Vec, Vec) { - let commands = vec![ - grid_record( - Action::DispatchThreadgroups { - grid: [7, 3, 1], - local_size: [2, 1, 1], - }, - 0, - 0, - ), - grid_record( - Action::DispatchThreadgroups { - grid: [2, 2, 1], - local_size: [4, 2, 1], - }, - 8, - 128, - ), - CommandRecord::default(), - grid_record( - Action::DispatchThreadgroups { - grid: [5, 1, 3], - local_size: [1, 1, 1], - }, - 16, - 256, - ), - grid_record( - Action::DispatchThreadgroups { - grid: [1, 9, 2], - local_size: [2, 2, 1], - }, - 24, - 384, - ), - ]; - let params = grid_params(&[(0, 5, 24), (2, 9, 32), (4, 0x8000_0000, 16), (6, 3, 32)]); - (commands, params) -} - -/// A folded variant of a kernel that observes its partition compiles under -/// `VariantKey::folded_groups` as any other kernel binds, reads its group counts and grid from -/// the region record at `ReplayRegionAddress` (no `DispatchRegion`), and states -/// `RuntimeFact::FoldedGroups`, so its plan states the key; outside a device replay, whose -/// preprocess alone writes its record, a direct or indirect dispatch of its plan is refused. With a flat grid or a replay's bindings it is refused, and a profile without device -/// addresses names what it lacks. -#[test] -fn a_folded_variant_states_its_key_and_runs_only_indirect_threadgroups() { - let Some(grid) = grid_fixture() else { - return; - }; - let mut key = VariantKey::new(); - key.folded_groups = true; - let plain = key.lowering_inputs(Stage::Kernel); - let mut flat = plain.clone(); - flat.flat_grid = true; - let mut replayed = replay_inputs(); - replayed.folded_groups = true; - let mut ran = 0; - for (stem, dev) in devices_and_unaddressed() { - let refused = |r: Result| match r { - Err(e) if refuses_threadgroup_memory(&e, dev.profile()) => {} - Err(Error::Unsupported(u)) => { - assert_eq!(u.feature, Feature::GpuEncodedIndirectCommands, "{stem}") - } - other => panic!("{stem}: {:?}", other.map(|_| ())), - }; - if dev.profile().fields().buffer_access != BufferAccess::Addressed { - refused(pipeline(&dev, &grid, GRID, &plain)); - continue; - } - ran += 1; - refused(pipeline(&dev, &grid, GRID, &flat)); - refused(pipeline(&dev, &grid, GRID, &replayed)); - let pipe = pipeline(&dev, &grid, GRID, &plain).unwrap_or_else(|e| panic!("{stem}: {e}")); - assert!( - pipe.dependencies - .iter() - .any(|d| d.fact == RuntimeFact::FoldedGroups), - "{stem}" - ); - let (typed, _) = typed_module_with(&grid, GRID, dev.profile(), &plain) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - let fields: Vec = typed.push.fields.iter().map(|f| f.field).collect(); - assert!( - fields.contains(&PushField::ReplayRegionAddress) - && !fields.contains(&PushField::DispatchRegion) - && !fields.contains(&PushField::RootTableAddress), - "{stem}: {fields:?}" - ); - let (commands, _) = folded_commands(); - let (state, _) = command_state(&commands[0]); - let plan = pipe - .plan(&dev, &state.shape()) - .unwrap_or_else(|e| panic!("{stem}: {e:?}")); - assert_eq!(plan.variant, key, "{stem}"); - let direct = Dispatch::Threadgroups { - groups: [7, 3, 1], - threads_per_group: [2, 1, 1], - }; - let indirect = Dispatch::ThreadgroupsIndirect { - indirect: IndirectRef { - token: 0, - offset: 0, - }, - threads_per_group: [2, 1, 1], - }; - for refused in [direct, indirect] { - match plan.instantiate_dispatch(&state, &refused) { - Err(BindError::Unsupported(u)) => { - assert_eq!(u.feature, Feature::GpuEncodedIndirectCommands, "{stem}") - } - other => panic!("{stem}: {refused:?}: {:?}", other.map(|_| ())), - } - } - } - assert!(ran > 0, "no profile with device addresses"); -} diff --git a/crates/metal2vulkan/src/tests/engine_dispatch.rs b/crates/metal2vulkan/src/tests/engine_dispatch.rs index cafdd35a3..c6923c116 100644 --- a/crates/metal2vulkan/src/tests/engine_dispatch.rs +++ b/crates/metal2vulkan/src/tests/engine_dispatch.rs @@ -71,6 +71,10 @@ fn single(local: [u32; 3], groups: [u32; 3]) -> Dispatch { /// The device address of the command buffer's `ExecutionStatus` buffer in [`run_word0`]. const STATUS_AT: u64 = 0x0000_0042_0000_0000; +/// The `ExecutionStatus` buffer's bytes: through its last word. +const STATUS_BYTES: usize = + crate::bind::status::StatusWord::SeqCstFences.byte_offset() as usize + 4; + /// Run `m` (planned as `plan`) once in each scheduling order with the planner's values and return /// word 0 of buffer 0. fn run_word0(plan: &Plan, m: &TypedModule, d: &Dispatch) -> u32 { @@ -121,7 +125,7 @@ fn run_word0(plan: &Plan, m: &TypedModule, d: &Dispatch) -> u32 { Buffer { slot: Some(crate::lower::access::absent::symbol(Stage::Kernel)), address: Some(STATUS_AT), - bytes: vec![0; crate::bind::status::ExecutionStatus::BYTES], + bytes: vec![0; STATUS_BYTES], }, ], push, diff --git a/crates/metal2vulkan/src/tests/engine_draw_bases.rs b/crates/metal2vulkan/src/tests/engine_draw_bases.rs index a490f8023..6575f19b9 100644 --- a/crates/metal2vulkan/src/tests/engine_draw_bases.rs +++ b/crates/metal2vulkan/src/tests/engine_draw_bases.rs @@ -15,16 +15,12 @@ use std::sync::Arc; -use crate::bind::{BindState, DrawCall}; -use crate::budget::{Budget, SPIRV_WORDS}; +use crate::budget::SPIRV_WORDS; use crate::device::requirements::VkFeature; -use crate::device::{Device, DeviceDescription, DevicePolicy, DeviceProfile}; +use crate::device::{DevicePolicy, DeviceProfile}; use crate::error::{Error, Feature}; -use crate::library::{FunctionArtifact, FunctionConstantValues, Library}; +use crate::library::{FunctionArtifact, FunctionConstantValues}; use crate::pipeline::compile::{compile_bitcode, EntryRef}; -use crate::pipeline::descriptor::{ - FunctionDescriptor, RenderPipelineDescriptor, StageSource, TessellationDescriptor, -}; use crate::pipeline::facts::RuntimeFact; use crate::pipeline::interface::PushLoc; use crate::pipeline::lower_inputs::LoweringInputs; @@ -36,7 +32,6 @@ use crate::pipeline::testing::{ }; use crate::spirv::interp::{run, Buffer, Config, Resources}; use crate::spirv::testing::committed_profiles; -use crate::vk; const WIDE: &str = "draw_bases_in_a_vertex_function"; const NARROW: &str = "narrow_draw_bases_in_a_vertex_function"; @@ -249,64 +244,3 @@ fn the_base_instance_after_tessellation_is_the_push_lane() { } assert!(ran > 0, "no profile has tessellationShader"); } - -fn device(stem: &str) -> Device { - 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 desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); - Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device") -} - -/// A draw of patches from base instance 7 writes `[patch_start, 7]` into the evaluation stage's -/// `BaseVertexInstance` lanes, so the post-tessellation function reads 7. -#[test] -fn a_draw_of_patches_pushes_its_base_instance() { - let Some(bc) = fixture() else { return }; - let lib = Library::from_air(&bc).expect("library"); - for stem in ["moltenvk-m3", "lavapipe", "runtime-floor"] { - let dev = device(stem); - let mut d = RenderPipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new( - lib.function(TESSELLATED).expect("function"), - ))); - d.rasterization_enabled = false; - d.tessellation = Some(TessellationDescriptor::default()); - let p = dev - .compile_render_pipeline(&d, &Budget::standard()) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - // Without a factor buffer the zero buffer stands in: the patches are culled, and the - // push lanes are written all the same. - let state = BindState::default(); - let plan = p.plan(&dev, &state.shape()).expect("plan"); - let draw = DrawCall::Patches { - control_points: 3, - patch_start: 2, - patch_count: 5, - patch_index: None, - instance_count: 2, - base_instance: 7, - control_point_index: None, - }; - let cmds = plan.instantiate_draw(&state, &draw).expect("draw"); - let field = p - .interface - .push - .iter() - .filter(|pl| pl.stage == Stage::Vertex) - .flat_map(|pl| &pl.fields) - .find(|f| f.field == PushField::BaseVertexInstance) - .unwrap_or_else(|| panic!("{stem}: no BaseVertexInstance field")); - let PushLoc::Push { offset } = field.loc else { - panic!("{stem}: the field spilled: {:?}", field.loc); - }; - let write = cmds - .push_constants - .iter() - .find(|w| w.stages == vk::ShaderStage::TESSELLATION_EVALUATION.flags()) - .unwrap_or_else(|| panic!("{stem}: no evaluation push")); - let at = (offset - write.offset) as usize; - assert_eq!(words(&write.bytes[at..at + 8]), [2, 7], "{stem}: the lanes"); - assert!(!cmds.indirect_needs_arguments, "{stem}"); - } -} diff --git a/crates/metal2vulkan/src/tests/engine_dynamic_roots.rs b/crates/metal2vulkan/src/tests/engine_dynamic_roots.rs index a1b14e014..b0beb9505 100644 --- a/crates/metal2vulkan/src/tests/engine_dynamic_roots.rs +++ b/crates/metal2vulkan/src/tests/engine_dynamic_roots.rs @@ -26,7 +26,7 @@ use std::collections::BTreeMap; use std::sync::atomic::{AtomicU64, Ordering}; -use crate::bind::status::{ExecutionStatus, StatusBits, StatusWord}; +use crate::bind::status::StatusWord; use crate::device::profile::DeviceProfile; use crate::device::requirements::VkFeature; use crate::device::DevicePolicy; @@ -38,9 +38,13 @@ use crate::pipeline::sym::{PushField, ResourceKind, ResourceSlot, SlotClass, Slo use crate::pipeline::testing::{ compile, device_f, link_and_validate, llvm_assemble, typed_module, AssembleError, PROFILE_F, }; -use crate::spirv::interp::{run, Buffer, Config, InterpError, Resources}; +use crate::spirv::interp::{run, Buffer, Config, Resources}; use crate::spirv::ir::{Inst, StorageClass, Type, TypedModule}; +/// The `ExecutionStatus` buffer's bytes, every word 0 at the start: through its last word. +const STATUS_BYTES: usize = + crate::bind::status::StatusWord::SeqCstFences.byte_offset() as usize + 4; + const HEADER: &str = "target datalayout = \"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32\"\ntarget triple = \"air64_v28-apple-macosx26.0.0\"\n\n"; /// Device addresses of the interpreter's address-backed buffers. @@ -128,7 +132,6 @@ const CHASE: &str = " %k = load i32, ptr addrspace(1) %2, align 8\n\ struct Leaf { name: &'static str, bytes: u64, - align: u64, body: &'static str, /// The stored bytes, for a store. store: Option<&'static [u8]>, @@ -138,28 +141,24 @@ const LEAVES: [Leaf; 4] = [ Leaf { name: "dyn_load_i32", bytes: 4, - align: 4, body: " %v = load i32, ptr addrspace(1) %q, align 4\n store i32 %v, ptr addrspace(1) %1, align 4\n", store: None, }, Leaf { name: "dyn_load_i8", bytes: 1, - align: 1, body: " %v = load i8, ptr addrspace(1) %q, align 1\n store i8 %v, ptr addrspace(1) %1, align 4\n", store: None, }, Leaf { name: "dyn_store_i32", bytes: 4, - align: 4, body: " store i32 305419896, ptr addrspace(1) %q, align 4\n", store: Some(&[0x78, 0x56, 0x34, 0x12]), }, Leaf { name: "dyn_store_i16", bytes: 2, - align: 1, body: " store i16 -21829, ptr addrspace(1) %q, align 1\n", store: Some(&[0xBB, 0xAA]), }, @@ -257,162 +256,6 @@ fn status_words(bytes: &[u8]) -> Vec { .collect() } -/// The offsets the chase kernels try: in bounds, at both ends, just outside, and wrapped (as a -/// 32-bit or 64-bit displacement), then 24 seeded random ones drawn around the same edges and -/// from the whole 64-bit range (the interpreter traps any access outside a bound buffer, so a -/// wrapped offset that escaped containment would fail the run, not only the comparison). -fn offsets() -> Vec { - let mut v = vec![0, 1, 4, 5, 30, 60, 61, 62, 63, 64, 65, 68, 128]; - v.extend([ - u64::MAX, - u64::MAX - 3, - (-4i64) as u64, - 0xFFFF_FFF0, - 0xFFFF_FFFC, - 0xFFFF_FFFF, - 0x1_0000_0000, - 0x1_0000_0004, - 1 << 63, - ]); - let mut x = 0x9E37_79B9_7F4A_7C15u64; - for i in 0..24u64 { - x ^= x << 13; - x ^= x >> 7; - x ^= x << 17; - let small = x % 96; - v.push(match i % 4 { - 0 => x, - 1 => 0x1_0000_0000u64.wrapping_sub(48).wrapping_add(small), - 2 => (small as i64 - 48) as u64, - _ => small, - }); - } - v -} - -/// A loaded pointer resolves to its allocation (a pointer into its middle included), every leaf is -/// exact in bounds and contained out of bounds at any 64-bit offset, and accesses through root 0 -/// (null, or an address outside the resident set) are contained and counted. -#[test] -fn a_loaded_pointer_is_exact_in_bounds_and_contained_elsewhere() { - // Element k of `ptrs`: allocation 0, allocation 1 at byte 16, a miss, null. - let targets: [(Option, u64); 4] = [ - (Some(0), guest(0)), - (Some(1), guest(1) + 16), - (None, guest(9)), - (None, 0), - ]; - let ptrs: Vec = targets.iter().flat_map(|(_, g)| g.to_le_bytes()).collect(); - for leaf in &LEAVES { - let Some(bc) = assemble_text( - leaf.name, - &kernel(leaf.name, &format!("{CHASE}{}", leaf.body)), - ) else { - return; - }; - for (what, p) in profiles() { - let what = format!("{} {what}", leaf.name); - let a = compile(&bc, leaf.name, &p).unwrap_or_else(|e| panic!("{what}: {e}")); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); - assert!(a.interface.needs_pointer_translation, "{what}"); - let (plan, m) = typed_module(&bc, leaf.name, &p).expect("module"); - assert!(plan.facts.contains(&RuntimeFact::ExecutionStatus), "{what}"); - // The slots stay descriptor views: no wide pointer reaches them. - for s in 0..3 { - match a.interface.slots.get(&SlotRef { - stage: Stage::Kernel, - class: SlotClass::Buffer, - index: s, - }) { - Some(SlotInterface::Buffer(b)) => { - assert!(matches!(b.form, BufferForm::Descriptor), "{what} {s}") - } - None if s == 1 && leaf.store.is_some() => {} - other => panic!("{what} slot {s}: {other:?}"), - } - } - let resident = [ - (host(0), guest(0), ALLOC), - (host(1), guest(1), ALLOC), - (host(2), guest(2), ALLOC), - ]; - for (k, (alloc, g)) in targets.iter().enumerate() { - for off in offsets() { - // Metal leaves a misaligned access undefined. - if off % leaf.align != 0 { - continue; - } - let mut params = vec![0u8; 16]; - params[..4].copy_from_slice(&(k as u32).to_le_bytes()); - params[8..].copy_from_slice(&off.to_le_bytes()); - let data: Vec> = (0..3).map(pattern).collect(); - let res = Resources { - buffers: vec![ - slot_buffer(0, ptrs.clone()), - slot_buffer(1, vec![0; 16]), - slot_buffer(2, params), - addressed(TABLE, root_table(&[(0, 0, 0, 0); 3], &resident)), - addressed(SINK, vec![0; 64]), - addressed(STATUS, vec![0; ExecutionStatus::BYTES]), - addressed(host(0), data[0].clone()), - addressed(host(1), data[1].clone()), - addressed(host(2), data[2].clone()), - ], - push: push_bytes(&plan), - spec: Default::default(), - }; - let case = format!("{what} k={k} off={off:#x}"); - let out = match run(&m, &Config::default(), res) { - Ok(o) => o, - Err(InterpError::Trap(t)) => panic!("{case}: trapped {t:?}"), - Err(e) => panic!("{case}: {e}"), - }; - // The byte offset inside the allocation, when the access is inside it. - let at = alloc.and_then(|a| { - let rel = (g - guest(a)).wrapping_add(off); - (ALLOC >= leaf.bytes && rel <= ALLOC - leaf.bytes) - .then_some((a as usize, rel as usize)) - }); - match leaf.store { - None => { - let mut want = vec![0u8; 16]; - if let Some((a, rel)) = at { - let n = leaf.bytes as usize; - want[..n].copy_from_slice(&data[a][rel..rel + n]); - } - assert_eq!(out.buffers[1], want, "{case}"); - } - Some(bytes) => { - for (i, d) in data.iter().enumerate() { - let mut want = d.clone(); - if let Some((a, rel)) = at { - if a == i { - want[rel..rel + bytes.len()].copy_from_slice(bytes); - } - } - assert_eq!(out.buffers[6 + i], want, "{case}: allocation {i}"); - } - } - } - let status = status_words(&out.buffers[5]); - let missed = alloc.is_none(); - assert_eq!( - status[StatusWord::ResidentMisses.index() as usize], - u32::from(missed), - "{case}: miss count" - ); - assert_eq!( - StatusBits(status[StatusWord::Status.index() as usize]) - .contains(StatusBits::RESIDENT_MISS), - missed, - "{case}: miss bit" - ); - } - } - } - } -} - /// The resident-set search (its loop of ⌈log₂ N⌉ steps) finds every address of every entry of sets /// of 0 to 33 entries, a pointer one past an entry's end included (its accesses are out of bounds, not /// misses), and misses addresses in the gaps, below the first entry, and above the last. @@ -448,7 +291,7 @@ fn inttoptr_resolves_every_resident_address() { slot_buffer(2, addr.to_le_bytes().to_vec()), addressed(TABLE, root_table(&[(0, 0, 0, 0); 3], &resident)), addressed(SINK, vec![0; 64]), - addressed(STATUS, vec![0; ExecutionStatus::BYTES]), + addressed(STATUS, vec![0; STATUS_BYTES]), ]; for k in 0..n { buffers.push(addressed(host(k), pattern(k))); @@ -512,7 +355,7 @@ fn inttoptr_resolves_addresses_of_large_sets() { slot_buffer(2, addr.to_le_bytes().to_vec()), addressed(TABLE, table.clone()), addressed(SINK, vec![0; 64]), - addressed(STATUS, vec![0; ExecutionStatus::BYTES]), + addressed(STATUS, vec![0; STATUS_BYTES]), ]; if let Some((k, _)) = want { buffers.push(addressed(host(k), pattern(k))); @@ -608,7 +451,7 @@ fn a_parameter_merged_with_loaded_pointers_walks_a_list() { }, node(guest(2), 17), ]; - let status = ExecutionStatus::initial().to_vec(); + let status = vec![0; STATUS_BYTES]; for steps in [1u32, 2, 3, 6] { let resident = [ (host(0), guest(0), ALLOC), @@ -737,7 +580,7 @@ fn loaded_pointers_compare_by_metal_address() { let mut head_alloc = vec![0xEEu8; 16]; head_alloc.extend(node(guest(0), 7)); let nodes = [node(guest(1), 11), node(guest(2), 13), node(last, 17)]; - let status = ExecutionStatus::initial().to_vec(); + let status = vec![0; STATUS_BYTES]; // The head's allocation is resident too (a bound argument), below the nodes. let resident = [ (head_host, head_guest, head_alloc.len() as u64), @@ -829,7 +672,6 @@ fn volatile_accesses_through_a_loaded_pointer_are_exact() { Leaf { name: "dyn_volatile_load", bytes: 4, - align: 4, body: " %v = load volatile i32, ptr addrspace(1) %q, align 4\n store i32 %v, ptr addrspace(1) %1, align 4\n", store: None, }, @@ -839,7 +681,6 @@ fn volatile_accesses_through_a_loaded_pointer_are_exact() { Leaf { name: "dyn_volatile_store", bytes: 4, - align: 4, body: " store volatile i32 305419896, ptr addrspace(1) %q, align 4\n", store: Some(&[0x78, 0x56, 0x34, 0x12]), }, @@ -849,7 +690,6 @@ fn volatile_accesses_through_a_loaded_pointer_are_exact() { Leaf { name: "dyn_volatile_copy_from", bytes: 4, - align: 4, body: " call void @llvm.memcpy.p1.p1.i64(ptr addrspace(1) align 4 %1, ptr addrspace(1) align 4 %q, i64 4, i1 true)\n", store: None, }, @@ -860,7 +700,6 @@ fn volatile_accesses_through_a_loaded_pointer_are_exact() { Leaf { name: "dyn_volatile_copy_to", bytes: 4, - align: 4, body: " call void @llvm.memcpy.p1.p1.i64(ptr addrspace(1) align 4 %q, ptr addrspace(1) align 4 %2, i64 4, i1 true)\n", store: Some(&[1, 0, 0, 0]), }, @@ -898,7 +737,7 @@ fn volatile_accesses_through_a_loaded_pointer_are_exact() { slot_buffer(2, params), addressed(TABLE, root_table(&[(0, 0, 0, 0); 3], &resident)), addressed(SINK, vec![0; 64]), - addressed(STATUS, vec![0; ExecutionStatus::BYTES]), + addressed(STATUS, vec![0; STATUS_BYTES]), addressed(host(0), data[0].clone()), addressed(host(1), data[1].clone()), ], @@ -964,7 +803,7 @@ fn a_volatile_pointer_load_through_a_loaded_pointer_is_exact() { slot_buffer(2, params.clone()), addressed(TABLE, root_table(&[(0, 0, 0, 0); 3], &resident)), addressed(SINK, vec![0; 64]), - addressed(STATUS, vec![0; ExecutionStatus::BYTES]), + addressed(STATUS, vec![0; STATUS_BYTES]), addressed(host(0), data[0].clone()), addressed(host(1), data[1].clone()), ], diff --git a/crates/metal2vulkan/src/tests/engine_extended_range.rs b/crates/metal2vulkan/src/tests/engine_extended_range.rs index b0b2aaf5b..a96a731f2 100644 --- a/crates/metal2vulkan/src/tests/engine_extended_range.rs +++ b/crates/metal2vulkan/src/tests/engine_extended_range.rs @@ -24,14 +24,13 @@ use std::collections::BTreeMap; use std::sync::atomic::{AtomicU64, Ordering}; -use crate::bind::{BindState, BoundBuffer, BoundTexture, StageTable, TextureFacts, WriteSource}; use crate::budget::{Budget, SPIRV_WORDS}; use crate::device::{Device, DeviceDescription, DevicePolicy}; use crate::error::Feature; use crate::library::{FunctionConstantValues, Library}; use crate::lower::select::{LowerInputs, Plan}; use crate::metal::format::ExtendedRange; -use crate::metal::{self, PixelFormat, TextureType}; +use crate::metal::{self, PixelFormat}; use crate::pipeline::compile::{compile_bitcode, EntryRef}; use crate::pipeline::interface::PushLoc; use crate::pipeline::lower_inputs::{StorageImageChoice, StorageImageClass}; @@ -40,8 +39,8 @@ use crate::pipeline::sym::{SpecKey, Stage}; use crate::pipeline::testing::{ link_and_validate, llvm_assemble, meter, profile, typed_module_with, AssembleError, }; +use crate::pipeline::FunctionDescriptor; use crate::pipeline::StageSource; -use crate::pipeline::{ComputePipeline, ComputePipelineDescriptor, FunctionDescriptor}; use crate::spirv::interp::{run_with_images, Buffer, Config, Image, Order, Resources}; use crate::spirv::ir::TypedModule; @@ -770,244 +769,6 @@ fn devices() -> Vec<(String, Device)> { out } -/// The kernel compiled into a compute pipeline under `inputs`, or `None` where the device needs a -/// storage slot's format as an input (it accesses no storage image without one). -fn pipeline(dev: &Device, bc: &[u8], inputs: &LowerInputs) -> Option { - pipeline_entry(dev, bc, "k", inputs) -} - -/// [`pipeline`] of the kernel `entry` of `bc`. -fn pipeline_entry( - dev: &Device, - bc: &[u8], - entry: &str, - inputs: &LowerInputs, -) -> Option { - let lib = Library::from_air(bc).expect("library"); - let f = lib.function(entry).expect("function"); - let compiled = - match dev.compile_function(&FunctionDescriptor::new(f), inputs, &Budget::standard()) { - Ok(c) => c, - Err(crate::error::Error::NeedsInput(_)) => return None, - Err(e) => panic!("compile: {e}"), - }; - Some( - dev.compile_compute_pipeline( - &ComputePipelineDescriptor::new(StageSource::Compiled(compiled)), - &Budget::standard(), - ) - .expect("pipeline"), - ) -} - -/// A kernel's state: texture slots 0 and 1 bound in `pf` (shader read and write), buffer 0. -fn state(pf: PixelFormat) -> BindState { - let mut t = StageTable::default(); - for index in [0, 1] { - let mut facts = TextureFacts::new(TextureType::Type2D, pf); - facts.usage = metal::TextureUsage::SHADER_READ | metal::TextureUsage::SHADER_WRITE; - t.textures.insert( - index, - BoundTexture::Texture { - facts, - resource_id: None, - }, - ); - } - t.buffers.insert( - 0, - BoundBuffer::Buffer { - length: 65536, - offset: 0, - gpu_address: 0x1_0000, - device_address: None, - attribute_stride: None, - }, - ); - let mut s = BindState::default(); - s.stages.insert(Stage::Kernel, t); - s -} - -/// A slot bound in an extended-range format joins the plan's variant, the variant's pipeline -/// plans the same key for the same shape, and both slots view the image in the format's raw -/// unsigned format; a slot bound in another format leaves the variant. On every committed -/// profile, for a sampled and a storage source. -#[test] -fn a_slot_bound_in_an_extended_range_format_joins_the_variant() { - let formats = [ - (PixelFormat::BGR10XR, ExtendedRange::Bgr10 { srgb: false }), - ( - PixelFormat::BGR10XRSRGB, - ExtendedRange::Bgr10 { srgb: true }, - ), - (PixelFormat::BGRA10XR, ExtendedRange::Bgra10 { srgb: false }), - ( - PixelFormat::BGRA10XRSRGB, - ExtendedRange::Bgra10 { srgb: true }, - ), - ( - PixelFormat::RGB10A82PXR10, - ExtendedRange::Planes { srgb: false }, - ), - ( - PixelFormat::RGB10A82PXR10SRGB, - ExtendedRange::Planes { srgb: true }, - ), - ]; - let mut planned = 0; - for source in [Source::Read, Source::ReadWrite] { - let Some(bc) = assemble("bind", &kernel(source, false, 0)) else { - return; - }; - for (stem, dev) in devices() { - let Some(plain) = pipeline(&dev, &bc, &LowerInputs::new()) else { - continue; - }; - for (pf, form) in formats { - let what = format!("{source:?} {pf:?} on {stem}"); - let shape = state(pf).shape(); - let plan = match plain.plan(&dev, &shape) { - Ok(plan) => plan, - // A profile without the raw format's storage refuses it for the format. - Err(crate::error::BindError::Unsupported(u)) - if u.feature == Feature::Format => - { - continue - } - Err(e) => panic!("{what}: {e}"), - }; - assert_eq!( - plan.variant.extended_range, - BTreeMap::from([(SOURCE, form), (TARGET, form)]), - "{what}" - ); - let key = plan.variant.lowering_inputs(Stage::Kernel); - assert_eq!(key.extended_range, plan.variant.extended_range, "{what}"); - let variant = pipeline(&dev, &bc, &key).expect("the variant's inputs"); - let again = variant.plan(&dev, &shape).expect("variant plan"); - assert_eq!(again.variant, plan.variant, "{what}"); - let views: Vec<_> = again - .descriptors - .iter() - .filter_map(|d| match &d.source { - WriteSource::Texture { view, .. } => Some(view.format), - _ => None, - }) - .collect(); - assert_eq!(views, [form.raw_format(); 2], "{what}"); - planned += 1; - let other = variant - .plan(&dev, &state(PixelFormat::RGBA16Float).shape()) - .expect("plan"); - assert!(other.variant.extended_range.is_empty(), "{what}"); - } - } - } - assert!(planned > 0); -} - -/// A swizzled extended-range, padded or bfloat texture joins the plan's variant -/// (`swizzled_storage`) at a sampled slot as at a storage slot: its view holds raw codes, which -/// a swizzle in the view's component mapping would move before the function decodes them, so the -/// view takes none (`shader_swizzle`) and the variant's function swizzles the decoded texel -/// under the slot's `TextureSwizzle` specialization, the swizzle's word. An -/// unswizzled texture leaves the variant. On every committed profile. -#[test] -fn a_swizzled_extended_texture_joins_the_variant_at_a_sampled_slot() { - use crate::metal::{TextureSwizzle as S, TextureSwizzleChannels}; - let swizzle = TextureSwizzleChannels::new(S::Alpha, S::Red, S::One, S::Zero); - let mut planned = 0; - for source in [Source::Read, Source::ReadWrite] { - let Some(bc) = assemble("extended swizzle", &kernel(source, false, 0)) else { - return; - }; - for (stem, dev) in devices() { - let Some(plain) = pipeline(&dev, &bc, &LowerInputs::new()) else { - continue; - }; - for pf in [ - PixelFormat::BGR10XR, - PixelFormat::BGR10XRSRGB, - PixelFormat::BGRA10XR, - PixelFormat::BGRA10XRSRGB, - PixelFormat::R10UnormX6, - PixelFormat::RG10UnormX12, - PixelFormat::R16Bfloat, - PixelFormat::RG16Bfloat, - PixelFormat::RGBA16Bfloat, - ] { - let what = format!("{source:?} {pf:?} on {stem}"); - let mut state = state(pf); - if let Some(BoundTexture::Texture { facts, .. }) = state - .stages - .get_mut(&Stage::Kernel) - .and_then(|t| t.textures.get_mut(&0)) - { - facts.swizzle = swizzle; - } - let shape = state.shape(); - let (plan, own) = match ( - plain.plan(&dev, &shape), - plain.plan(&dev, &self::state(pf).shape()), - ) { - // A profile without the raw format's storage refuses it for the format. - (_, Err(crate::error::BindError::Unsupported(u))) - if u.feature == Feature::Format => - { - continue - } - (Ok(plan), Ok(own)) => (plan, own), - (swizzled, unswizzled) => panic!( - "{what}: swizzled {:?}, unswizzled {:?}", - swizzled.map(|_| ()), - unswizzled.map(|_| ()) - ), - }; - assert!(plan.variant.swizzled_storage.contains(&SOURCE), "{what}"); - assert!(!own.variant.swizzled_storage.contains(&SOURCE), "{what}"); - let key = plan.variant.lowering_inputs(Stage::Kernel); - let variant = pipeline(&dev, &bc, &key).expect("the variant's inputs"); - let again = variant - .plan(&dev, &shape) - .unwrap_or_else(|e| panic!("{what}: variant {e}")); - assert_eq!(again.variant, plan.variant, "{what}"); - let view = again - .descriptors - .iter() - .find_map(|d| match &d.source { - WriteSource::Texture { slot, view } if *slot == SOURCE => Some(*view), - _ => None, - }) - .expect("the source's view"); - assert!(view.shader_swizzle, "{what}"); - let id = variant - .stage - .specialization - .constants - .iter() - .find_map(|c| (c.key == SpecKey::TextureSwizzle(SOURCE)).then_some(c.id)) - .unwrap_or_else(|| panic!("{what}: no TextureSwizzle constant")); - let e = again - .specialization - .entries - .iter() - .find(|e| e.constant_id == id) - .expect("TextureSwizzle entry"); - let at = e.offset as usize; - let word = u32::from_le_bytes( - again.specialization.data[at..at + 4] - .try_into() - .expect("a u32"), - ); - assert_eq!(word, swizzle.word(), "{what}"); - planned += 1; - } - } - } - assert!(planned > 0); -} - /// A `half` read of a slot bound in an extended-range form decodes the texel's codes and rounds /// the decoded `f32` through the device's conversion (`narrow::round_texel`). On `moltenvk-m3` the /// module records `NativeHalfConversion` for it and `DevicePackConversion`, which states the diff --git a/crates/metal2vulkan/src/tests/engine_extended_range/bicubic.rs b/crates/metal2vulkan/src/tests/engine_extended_range/bicubic.rs index 89b129a0c..9ab65bf37 100644 --- a/crates/metal2vulkan/src/tests/engine_extended_range/bicubic.rs +++ b/crates/metal2vulkan/src/tests/engine_extended_range/bicubic.rs @@ -16,7 +16,7 @@ use metal2vulkan_devtools::xr_bicubic::{self, KERNELS, SIZES}; -use super::samples::{form_of, run_samples, sample_kernel, sampled_state, words, Texels, Through}; +use super::samples::{form_of, run_samples, sample_kernel, words, Texels, Through}; use super::*; use crate::bind::SamplerDescriptor; use crate::error::Unsupported; @@ -195,81 +195,14 @@ fn unmeasured_bicubic_samples_are_refused() { } } -/// A texture bound in an extended-range format joins its slot's variant through a constexpr -/// bicubic sampler, and through a runtime sampler whose filters are `Cubic`, whose slot joins the -/// cubic-sampler variant too, under the word the interpreter's replay compiles: the pipeline as -/// compiled plans that variant, whose pipeline plans the same key. On every committed profile. +/// The variant of a runtime sampler whose filters are `Cubic` and whose state Metal's bicubic +/// filter is not measured under whatever a function samples (a mip filter, anisotropy, a minimum +/// reduction) is refused, `NotImplemented(SamplerBicubicFilter)`, at an extended-range slot as at +/// a slot of another format, on every committed profile, by one rule +/// (`metal::bicubic::runtime_cubic_measured`); a device without `samplerAnisotropy` (`vk12-floor`) +/// refuses an anisotropic one alike. #[test] -fn a_bicubic_sample_s_slots_join_the_variants() { - let bc = match llvm_assemble(&engine_dir().join("xr_bicubic.ll")) { - Ok(bc) => bc, - Err(AssembleError::Missing(why)) => { - eprintln!("SKIPPED: {why}"); - return; - } - Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected xr_bicubic: {why}"), - }; - let formats = [ - (PixelFormat::RGB10A82PXR10, 550), - (PixelFormat::RGB10A82PXR10SRGB, 551), - (PixelFormat::BGRA10XR, 552), - (PixelFormat::BGRA10XRSRGB, 553), - (PixelFormat::BGR10XR, 554), - (PixelFormat::BGR10XRSRGB, 555), - ]; - let mut cubic = SamplerDescriptor::new(); - cubic.min_filter = SamplerMinMagFilter::Cubic; - cubic.mag_filter = SamplerMinMagFilter::Cubic; - cubic.s_address_mode = SamplerAddressMode::ClampToEdge; - cubic.t_address_mode = SamplerAddressMode::ClampToEdge; - let word = SamplerWord::of(&cubic).0 & SamplerWord::CUBIC_STATE; - let mut planned = 0; - for (stem, dev) in devices() { - for kernel in ["xrb_edge", "xrb_runtime"] { - let plain = - pipeline_entry(&dev, &bc, kernel, &LowerInputs::new()).expect("a sampling kernel"); - let cubic_samplers = match kernel { - "xrb_runtime" => BTreeMap::from([(SAMPLER, word)]), - _ => BTreeMap::new(), - }; - for (pf, raw) in formats { - let what = format!("{kernel} {pf:?} on {stem}"); - let shape = sampled_state(pf, cubic).shape(); - let plan = plain - .plan(&dev, &shape) - .unwrap_or_else(|e| panic!("{what}: {e}")); - let form = form_of(&raw.to_string()); - assert_eq!( - plan.variant.extended_range, - BTreeMap::from([(SOURCE, form)]), - "{what}" - ); - assert_eq!(plan.variant.cubic_samplers, cubic_samplers, "{what}"); - let key = plan.variant.lowering_inputs(Stage::Kernel); - let variant = - pipeline_entry(&dev, &bc, kernel, &key).expect("the variant's inputs"); - let again = variant - .plan(&dev, &shape) - .unwrap_or_else(|e| panic!("{what}: the variant: {e}")); - assert_eq!(again.variant, plan.variant, "{what}"); - planned += 1; - } - } - } - assert!(planned > 0); -} - -/// A runtime sampler whose filters are `Cubic` and whose state Metal's bicubic filter is not -/// measured under whatever a function samples (a mip filter, anisotropy, a minimum reduction) is -/// refused by the plan of the pipeline as compiled, `NotImplemented(SamplerBicubicFilter)`, before -/// the plan names a variant: a dispatch of it compiles nothing, where the variant it would name -/// refuses the same word only once compiled, and the runtime keeps no compile that refused. At an -/// extended-range slot (which refused every `Cubic` word at planning before Metal's bicubic filter -/// of its texels was built) as at a slot of another format. On every committed profile, the -/// lowering refuses that variant by the same rule (`metal::bicubic::runtime_cubic_measured`), a -/// device without `samplerAnisotropy` (`vk12-floor`) an anisotropic one alike. -#[test] -fn an_unmeasured_cubic_sampler_is_refused_before_any_variant() { +fn an_unmeasured_cubic_sampler_s_variant_is_refused() { let bc = match llvm_assemble(&engine_dir().join("xr_bicubic.ll")) { Ok(bc) => bc, Err(AssembleError::Missing(why)) => { @@ -302,29 +235,11 @@ fn an_unmeasured_cubic_sampler_is_refused_before_any_variant() { let want = Unsupported::not_implemented(Feature::SamplerBicubicFilter); let mut refused = 0; for (stem, dev) in devices() { - let plain = pipeline_entry(&dev, &bc, "xrb_runtime", &LowerInputs::new()) - .expect("a sampling kernel"); - // The measured word plans its variant (`a_bicubic_sample_s_slots_join_the_variants`). - let measured = sampled_state(PixelFormat::BGRA10XR, cubic).shape(); - plain - .plan(&dev, &measured) - .unwrap_or_else(|e| panic!("the measured cubic word on {stem}: {e}")); for (state, sampler) in unmeasured { let word = SamplerWord::of(&sampler).0; assert!(word & SamplerWord::CUBIC != 0, "{state}"); for (pf, form) in formats { let what = format!("a cubic sampler with {state}, {pf:?}, on {stem}"); - match plain.plan(&dev, &sampled_state(pf, sampler).shape()) { - Err(crate::error::BindError::Unsupported(u)) => { - assert_eq!( - (&u.feature, &u.needs), - (&want.feature, &want.needs), - "{what}" - ) - } - other => panic!("{what}: planned {:?}", other.map(|p| p.variant)), - } - // The variant the word would name refuses it. let mut inputs = LowerInputs::new(); inputs .cubic_samplers diff --git a/crates/metal2vulkan/src/tests/engine_extended_range/heap.rs b/crates/metal2vulkan/src/tests/engine_extended_range/heap.rs index 4ae188caa..7fc2527fb 100644 --- a/crates/metal2vulkan/src/tests/engine_extended_range/heap.rs +++ b/crates/metal2vulkan/src/tests/engine_extended_range/heap.rs @@ -559,302 +559,6 @@ fn a_heap_sample_s_filter_note_follows_the_raw_texture_and_the_bound_sampler_wor } } -/// A heap `float` read's `DevicePackConversion` holds where its command can name a texture the heap -/// holds by its raw texels alone: on every committed profile with a sampled heap, a plan of its -/// pipeline gives `SpecKey::HeapRawTextures` bit 1 exactly where a texture the command makes -/// resident is such a texture (`BGRA10_XR`, `RGBA16Bfloat`, beside an `RGBA8Unorm` one too), bit 2 -/// where it is of a form the function filters (`BGRA10_XR`, not `RGBA16Bfloat`), and 0 where it -/// makes none or only `RGBA8Unorm` or `RGBA16Float` ones resident; the stage's note holds under the -/// plan's values exactly where bit 1 is set (`StageModule::precision_notes_bound`), and under no -/// known value (a reading of the module alone). The stage declares the key as a constant (default -/// 3, every raw arm live), which gates its raw arms (`lower::texture::heap_raw_form`), and the -/// pipeline's key carries the plan's value, so a command that can name no raw texture compiles -/// none of them. -#[test] -fn a_heap_decode_s_note_holds_where_its_command_can_name_a_raw_texture() { - use crate::bind::{ResourceClass, UsedResource}; - use crate::cache::SpecializationKey; - use crate::pipeline::PrecisionNote; - let note = PrecisionNote::DevicePackConversion; - let key = SpecKey::HeapRawTextures(Stage::Kernel); - let Some(bc) = assemble("heap_note_plan", &kernel(Use::Float)) else { - return; - }; - // A command making `formats` resident, at IDs of their own. - let state = |formats: &[PixelFormat]| BindState { - used_resources: (formats.iter().zip(1u32..)) - .map(|(&pf, token)| { - let mut facts = TextureFacts::new(TextureType::Type2D, pf); - facts.usage = metal::TextureUsage::SHADER_READ; - let mut u = UsedResource::new(ResourceClass::Texture(facts), token); - u.resource_id = Some(0x0000_0001_0000_0000 | u64::from(token) << 4); - u - }) - .collect(), - ..Default::default() - }; - // The formats, and the key's value: 1 a raw texture, 2 one of a form the function filters. - let cases: [(&[PixelFormat], u64); 6] = [ - (&[PixelFormat::BGRA10XR], 3), - (&[PixelFormat::RGBA16Bfloat], 1), - (&[PixelFormat::RGBA8Unorm, PixelFormat::BGRA10XR], 3), - (&[], 0), - (&[PixelFormat::RGBA8Unorm], 0), - (&[PixelFormat::RGBA16Float], 0), - ]; - let mut planned = 0; - for (stem, dev) in devices() { - let lib = Library::from_air(&bc).expect("library"); - let f = lib.function("k").expect("function"); - let d = ComputePipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new(f))); - let p = match dev.compile_compute_pipeline(&d, &Budget::standard()) { - Ok(p) => p, - Err(crate::error::Error::Unsupported(Unsupported { - feature: Feature::ArgumentBufferTextures, - .. - })) => continue, - Err(e) => panic!("{stem}: {e}"), - }; - assert!( - (p.stage) - .precision_notes_bound(&SpecializationKey::new(), &|_| None) - .contains(¬e), - "{stem}: {:?}", - p.stage.precision_notes - ); - let constant = (p.stage.specialization.constants.iter()) - .find(|c| c.key == key) - .unwrap_or_else(|| panic!("{stem}: no {key:?} constant")); - assert_eq!(constant.default, 3, "{stem}"); - for (formats, value) in cases { - let what = format!("{formats:?} on {stem}"); - let plan = p - .plan(&dev, &state(formats).shape()) - .unwrap_or_else(|e| panic!("{what}: {e}")); - assert_eq!(plan.specialized_value(key), Some(value), "{what}"); - let entry = (plan.specialization.entries.iter()) - .find(|e| e.constant_id == constant.id) - .unwrap_or_else(|| panic!("{what}: the key does not carry {key:?}")); - let at = entry.offset as usize; - let given = &plan.specialization.data[at..at + entry.size as usize]; - assert_eq!(given.first().copied().map(u64::from), Some(value), "{what}"); - let held = (p.stage) - .precision_notes_bound(&plan.specialization, &|k| plan.specialized_value(k)) - .contains(¬e); - assert_eq!(held, value & 1 == 1, "{what}"); - planned += 1; - } - } - assert!(planned > 0, "no committed profile has the sampled heap"); -} - -/// A heap linear sample's `BicubicFilterArithmetic` holds where its command can name a texture the -/// heap holds by its raw texels in a form the function filters: on every committed profile with a -/// sampled heap, under the plan's values (`StageModule::precision_notes_bound`) of a constexpr -/// linear sample's pipeline, it holds where the command makes a `BGRA10_XR` texture resident -/// (`SpecKey::HeapRawTextures` 3, beside an `RGBA8Unorm` one too), and not where it makes an -/// `RGBA16Bfloat` one alone resident (1: its sample reads the nearest texel), nor where it makes -/// none or an `RGBA8Unorm` one alone resident (0: the device's own sample); the stage's decode note -/// holds wherever a raw texture is resident. -#[test] -fn a_heap_sample_s_filter_note_holds_where_its_command_can_name_a_filtered_raw_texture() { - use crate::bind::{ResourceClass, UsedResource}; - use crate::pipeline::PrecisionNote; - let filter = PrecisionNote::BicubicFilterArithmetic; - let pack = PrecisionNote::DevicePackConversion; - let key = SpecKey::HeapRawTextures(Stage::Kernel); - let Some(bc) = assemble( - "heap_filter_plan", - &sampling_kernel(Sampling::Sample(words(true, false))), - ) else { - return; - }; - // A command making `formats` resident, at IDs of their own. - let state = |formats: &[PixelFormat]| BindState { - used_resources: (formats.iter().zip(1u32..)) - .map(|(&pf, token)| { - let mut facts = TextureFacts::new(TextureType::Type2D, pf); - facts.usage = metal::TextureUsage::SHADER_READ; - let mut u = UsedResource::new(ResourceClass::Texture(facts), token); - u.resource_id = Some(0x0000_0001_0000_0000 | u64::from(token) << 4); - u - }) - .collect(), - ..Default::default() - }; - // The formats, the key's value, and whether the filter's note holds. - let cases: [(&[PixelFormat], u64, bool); 5] = [ - (&[PixelFormat::BGRA10XR], 3, true), - (&[PixelFormat::RGBA8Unorm, PixelFormat::BGRA10XR], 3, true), - (&[PixelFormat::RGBA16Bfloat], 1, false), - (&[PixelFormat::RGBA8Unorm], 0, false), - (&[], 0, false), - ]; - let mut planned = 0; - for (stem, dev) in devices() { - let lib = Library::from_air(&bc).expect("library"); - let f = lib.function("k").expect("function"); - let d = ComputePipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new(f))); - let p = match dev.compile_compute_pipeline(&d, &Budget::standard()) { - Ok(p) => p, - Err(crate::error::Error::Unsupported(Unsupported { - feature: Feature::ArgumentBufferTextures, - .. - })) => continue, - Err(e) => panic!("{stem}: {e}"), - }; - for (formats, value, filtered) in cases { - let what = format!("{formats:?} on {stem}"); - let plan = p - .plan(&dev, &state(formats).shape()) - .unwrap_or_else(|e| panic!("{what}: {e}")); - assert_eq!(plan.specialized_value(key), Some(value), "{what}"); - let notes = (p.stage) - .precision_notes_bound(&plan.specialization, &|k| plan.specialized_value(k)); - assert_eq!(notes.contains(&filter), filtered, "{what}: {notes:?}"); - assert_eq!(notes.contains(&pack), value != 0, "{what}: {notes:?}"); - planned += 1; - } - } - assert!(planned > 0, "no committed profile has the sampled heap"); -} - -/// Synthetic AIR written for this test: kernel `k` writes buffer 0's `half4` at lane `gid` (its -/// bits) to texel `(gid, 0)` of the `texture2d` its argument buffer (buffer 2) holds. -const HALF_WRITE: &str = r#"define void @k(ptr addrspace(1) %v, ptr addrspace(2) %held, i32 %gid) { -entry: - %i = zext i32 %gid to i64 - %p = getelementptr <4 x i16>, ptr addrspace(1) %v, i64 %i - %w = load <4 x i16>, ptr addrspace(1) %p, align 8 - %h = bitcast <4 x i16> %w to <4 x half> - %at = insertelement <2 x i32> zeroinitializer, i32 %gid, i64 0 - %t = load ptr addrspace(1), ptr addrspace(2) %held, align 8 - tail call void @air.write_texture_2d.v4f16(ptr addrspace(1) %t, <2 x i32> %at, <4 x half> %h, i32 0, i32 2) - ret void -} - -declare void @air.write_texture_2d.v4f16(ptr addrspace(1), <2 x i32>, <4 x half>, i32, i32) - -!air.kernel = !{!0} -!air.version = !{!20} -!air.language_version = !{!21} -!0 = !{ptr @k, !1, !2} -!1 = !{} -!2 = !{!3, !4, !5} -!3 = !{i32 0, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 1, !"air.arg_type_size", i32 8, !"air.arg_type_align_size", i32 8, !"air.arg_type_name", !"ushort4", !"air.arg_name", !"v"} -!4 = !{i32 1, !"air.indirect_buffer", !"air.buffer_size", i32 8, !"air.location_index", i32 2, i32 1, !"air.read", !"air.address_space", i32 2, !"air.struct_type_info", !6, !"air.arg_type_size", i32 8, !"air.arg_type_align_size", i32 8, !"air.arg_type_name", !"Held", !"air.arg_name", !"held"} -!5 = !{i32 2, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"gid"} -!6 = !{i32 0, i32 8, i32 0, !"texture2d", !"t", !"air.indirect_argument", !7} -!7 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.write", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"t"} -!20 = !{i32 2, i32 8, i32 0} -!21 = !{!"Metal", i32 4, i32 0, i32 0} -"#; - -/// A `half` write through an argument buffer records `PrecisionNote::DeviceNanEncoding` under the -/// families of the textures its handles can name (`SpecKey::HeapNanFamilies`): on every committed -/// profile with a heap, one clause for each family, as each stores the device's NaN (a 16-bit -/// float format, a 32-bit one, a packed small float one, and a float format of none of those). A -/// plan gives the key from the command's resident textures (`R16Float` 1, -/// `RGBA32Float` 2, `RG11B10Float` 4, `RGBA8Unorm` and `R32Uint` 0), and the note holds under the -/// plan's values exactly where a resident texture is of a family of a clause. -#[test] -fn a_heap_half_write_s_nan_note_follows_the_families_its_command_can_name() { - use crate::bind::{ResourceClass, UsedResource}; - use crate::pipeline::{PrecisionNote, SpecClause}; - let note = PrecisionNote::DeviceNanEncoding; - let key = SpecKey::HeapNanFamilies(Stage::Kernel); - let Some(bc) = assemble("heap_half_write", HALF_WRITE) else { - return; - }; - // The families of the note's clauses: each a test of the key's own bit. - let noted = |specialized: &[crate::pipeline::SpecializedNote]| -> u32 { - let when: Vec<&SpecClause> = specialized - .iter() - .filter(|n| n.note == note) - .flat_map(|n| &n.when) - .collect(); - when.iter().fold(0, |bits, c| match &c.all[..] { - [t] if t.key == key && t.mask == t.bits && t.equal => bits | t.bits, - _ => panic!("a clause past the families: {c:?}"), - }) - }; - let consts = FunctionConstantValues::defaults(); - let entry = EntryRef::Name("k"); - let mut compiled = 0; - for (stem, p) in committed_profiles().expect("profiles") { - let a = match compile_bitcode( - &bc, - entry, - &consts, - &p, - &LowerInputs::new(), - &mut meter(), - SPIRV_WORDS, - ) { - Ok(a) => a, - Err(Error::Unsupported(Unsupported { - feature: Feature::ArgumentBufferTextures, - .. - })) => continue, - Err(e) => panic!("{stem}: {e}"), - }; - assert_eq!(noted(&a.specialized), 15, "{stem}: every family"); - assert!(a.precision.contains(¬e), "{stem}"); - compiled += 1; - } - assert!(compiled > 0, "no committed profile has the heap"); - // A command making `formats` resident, at IDs of their own. - let state = |formats: &[PixelFormat]| BindState { - used_resources: (formats.iter().zip(1u32..)) - .map(|(&pf, token)| { - let mut facts = TextureFacts::new(TextureType::Type2D, pf); - facts.usage = metal::TextureUsage::SHADER_READ; - let mut u = UsedResource::new(ResourceClass::Texture(facts), token); - u.resource_id = Some(0x0000_0001_0000_0000 | u64::from(token) << 4); - u - }) - .collect(), - ..Default::default() - }; - let cases: [(&[PixelFormat], u64); 7] = [ - (&[PixelFormat::R16Float], 1), - (&[PixelFormat::RGBA32Float], 2), - (&[PixelFormat::RG11B10Float], 4), - (&[PixelFormat::RGBA8Unorm], 0), - (&[PixelFormat::R32Uint], 0), - (&[PixelFormat::RGBA32Float, PixelFormat::RGBA8Unorm], 2), - (&[], 0), - ]; - let mut planned = 0; - for (stem, dev) in devices() { - let lib = Library::from_air(&bc).expect("library"); - let f = lib.function("k").expect("function"); - let d = ComputePipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new(f))); - let p = match dev.compile_compute_pipeline(&d, &Budget::standard()) { - Ok(p) => p, - Err(crate::error::Error::Unsupported(Unsupported { - feature: Feature::ArgumentBufferTextures, - .. - })) => continue, - Err(e) => panic!("{stem}: {e}"), - }; - let bits = u64::from(noted(&p.stage.specialized_notes)); - for (formats, value) in cases { - let what = format!("{formats:?} on {stem}"); - let plan = p - .plan(&dev, &state(formats).shape()) - .unwrap_or_else(|e| panic!("{what}: {e}")); - assert_eq!(plan.specialized_value(key), Some(value), "{what}"); - let held = (p.stage) - .precision_notes_bound(&plan.specialization, &|k| plan.specialized_value(k)) - .contains(¬e); - assert_eq!(held, value & bits != 0, "{what}: noted families {bits}"); - planned += 1; - } - } - assert!(planned > 0, "no profile has the heap"); -} - /// A `half` read, nearest sample or gather of a texture an argument buffer holds rounds its texel /// through the device's conversion of the texel's `f32` value (`narrow::round_texel`): the /// fetched texel's, merged with the decode routine's texel of a form a heap reads. On diff --git a/crates/metal2vulkan/src/tests/engine_extended_range/levels.rs b/crates/metal2vulkan/src/tests/engine_extended_range/levels.rs index b9da5ba4f..94a2c8765 100644 --- a/crates/metal2vulkan/src/tests/engine_extended_range/levels.rs +++ b/crates/metal2vulkan/src/tests/engine_extended_range/levels.rs @@ -13,7 +13,7 @@ //! measured, by the lowering for a constexpr sampler and by the binder for a runtime one, and a //! runtime sampler with a linear mip filter whose clamp's maximum the function does not read. -use super::samples::{form_of, raw_of, sampled_state, Through}; +use super::samples::{form_of, raw_of, Through}; use super::*; use crate::bind::SamplerDescriptor; use crate::error::Unsupported; @@ -546,9 +546,7 @@ fn grad_kernel(through: Through) -> String { /// A linear mip filter is built for the forms whose levels' blend is measured: the lowering /// refuses a constexpr sampler's of another form (a two-plane or padded one), -/// `NotImplemented(Format)`, and builds its nearest mip filter; the binder refuses a runtime -/// sampler's of such a form, and one whose clamp's maximum a nearest mip filter would read below -/// the last level, and plans the rest into the variant. +/// `NotImplemented(Format)`, and builds its nearest mip filter. #[test] fn unmeasured_linear_mip_filters_are_refused() { let forms = [ @@ -589,47 +587,4 @@ fn unmeasured_linear_mip_filters_are_refused() { } } } - let Some(bc) = assemble( - "runtime mip", - &level_kernel(Through::Runtime, false, false, false), - ) else { - return; - }; - for (stem, dev) in devices() { - let plain = pipeline(&dev, &bc, &LowerInputs::new()).expect("a sampling kernel"); - for (pf, form) in forms { - let short = descriptor(true, SamplerMipFilter::Linear, Some((0.0, 3.0))); - for (name, desc, planned) in [ - ( - "nearest", - descriptor(true, SamplerMipFilter::Nearest, None), - true, - ), - ( - "clamped nearest", - descriptor(false, SamplerMipFilter::Nearest, Some((0.75, 2.5))), - true, - ), - ( - "linear", - descriptor(true, SamplerMipFilter::Linear, None), - form.blends_levels(), - ), - ("short linear", short, false), - ] { - let what = format!("{name} {pf:?} on {stem}"); - match (plain.plan(&dev, &sampled_state(pf, desc).shape()), planned) { - (Ok(plan), true) => assert_eq!( - plan.variant.extended_range, - BTreeMap::from([(SOURCE, form)]), - "{what}" - ), - (Err(crate::error::BindError::Unsupported(u)), false) => { - assert_eq!(u, Unsupported::not_implemented(Feature::Format), "{what}") - } - (other, _) => panic!("{what}: {:?}", other.map(|_| ())), - } - } - } - } } diff --git a/crates/metal2vulkan/src/tests/engine_extended_range/samples.rs b/crates/metal2vulkan/src/tests/engine_extended_range/samples.rs index 099e9bca2..47003b03a 100644 --- a/crates/metal2vulkan/src/tests/engine_extended_range/samples.rs +++ b/crates/metal2vulkan/src/tests/engine_extended_range/samples.rs @@ -20,11 +20,11 @@ //! slot's own image in the raw format and binds no sampler. use super::*; -use crate::bind::{BoundSampler, SamplerDescriptor}; +use crate::bind::SamplerDescriptor; use crate::error::Unsupported; use crate::metal::format::extended_srgb::SRGB_DECODE_STEPS; use crate::metal::sampler::SamplerWord; -use crate::metal::{SamplerAddressMode, SamplerBorderColor, SamplerMinMagFilter}; +use crate::metal::{SamplerAddressMode, SamplerBorderColor}; /// Metal's linear samples, the files `xr_samples.tsv` and `xr_plane_samples.tsv` beside the owned /// fixture `xr_samples.metal`, one per line: the raw format (550 `RGB10A8_2P_XR10`, 551 its `_sRGB` @@ -1362,165 +1362,6 @@ fn replay_padded_samples(name: &str) { assert!(checked > 0); } -/// A kernel's state: texture slot 0 bound in `pf`, buffers 0 and 1, and sampler slot 0 bound to -/// `desc`. -pub(super) fn sampled_state(pf: PixelFormat, desc: SamplerDescriptor) -> BindState { - sampled_state_of(TextureType::Type2D, pf, desc) -} - -/// [`sampled_state`] with a texture of type `ty`. -pub(super) fn sampled_state_of( - ty: TextureType, - pf: PixelFormat, - desc: SamplerDescriptor, -) -> BindState { - let mut t = StageTable::default(); - t.textures.insert( - 0, - BoundTexture::Texture { - facts: TextureFacts::new(ty, pf), - resource_id: None, - }, - ); - for index in [0, 1] { - t.buffers.insert( - index, - BoundBuffer::Buffer { - length: 65536, - offset: 0, - gpu_address: 0x1_0000 * u64::from(index + 1), - device_address: None, - attribute_stride: None, - }, - ); - } - t.samplers.insert(0, BoundSampler::new(desc)); - let mut s = BindState::default(); - s.stages.insert(Stage::Kernel, t); - s -} - -/// A sampled slot bound in an extended-range format joins the plan's variant through a -/// constexpr and a runtime sampler: the variant's pipeline plans the same key, views the slot's -/// image in the raw format, and binds no sampler. The binder refuses a runtime sampler whose -/// word states mixed filters, `NotImplemented(Format)`, and plans one stating a nearest mip -/// filter, whose level the function reads (`levels`), or `MirrorClampToEdge`, whose taps the -/// fetches address. On every committed profile. -#[test] -fn a_sampled_slot_joins_the_variant() { - use SamplerMinMagFilter as F; - let formats = [ - (PixelFormat::BGR10XR, ExtendedRange::Bgr10 { srgb: false }), - ( - PixelFormat::BGRA10XRSRGB, - ExtendedRange::Bgra10 { srgb: true }, - ), - ( - PixelFormat::RGB10A82PXR10, - ExtendedRange::Planes { srgb: false }, - ), - (PixelFormat::R10UnormX6, ExtendedRange::R10X6), - (PixelFormat::RG10UnormX12, ExtendedRange::Rg10X12), - ]; - let mut linear = SamplerDescriptor::new(); - linear.min_filter = F::Linear; - linear.mag_filter = F::Linear; - let mut planned = 0; - for through in [ - Through::Constexpr(words(true, 1, false, 0)), - Through::Runtime, - ] { - let Some(bc) = assemble("bind sample", &sample_kernel(through, false, (0, 0), false)) - else { - return; - }; - for (stem, dev) in devices() { - let plain = pipeline(&dev, &bc, &LowerInputs::new()).expect("a sampling kernel"); - for (pf, form) in formats { - let what = format!("{through:?} {pf:?} on {stem}"); - let shape = sampled_state(pf, linear).shape(); - let plan = plain - .plan(&dev, &shape) - .unwrap_or_else(|e| panic!("{what}: {e}")); - assert_eq!( - plan.variant.extended_range, - BTreeMap::from([(SOURCE, form)]), - "{what}" - ); - let key = plan.variant.lowering_inputs(Stage::Kernel); - let variant = pipeline(&dev, &bc, &key).expect("the variant's inputs"); - let again = variant.plan(&dev, &shape).expect("variant plan"); - assert_eq!(again.variant, plan.variant, "{what}"); - let mut views = Vec::new(); - for d in &again.descriptors { - match &d.source { - WriteSource::Texture { view, .. } => views.push(view.format), - WriteSource::Sampler { .. } | WriteSource::CombinedImageSampler { .. } => { - panic!("{what}: the variant binds {:?}", d.source) - } - _ => {} - } - } - assert_eq!(views, [form.raw_format()], "{what}"); - planned += 1; - // A swizzled texture joins `swizzled_storage` too, under a border sampler as - // under this one, and the variant's pipeline plans the same key. - let mut border = linear; - border.s_address_mode = SamplerAddressMode::ClampToBorderColor; - border.t_address_mode = SamplerAddressMode::ClampToBorderColor; - border.border_color = SamplerBorderColor::OpaqueWhite; - for desc in [linear, border] { - let mut state = sampled_state(pf, desc); - if let Some(BoundTexture::Texture { facts, .. }) = state - .stages - .get_mut(&Stage::Kernel) - .and_then(|t| t.textures.get_mut(&0)) - { - use crate::metal::{TextureSwizzle as S, TextureSwizzleChannels as C}; - facts.swizzle = C::new(S::Alpha, S::Red, S::One, S::Zero); - } - let shape = state.shape(); - let what = format!("{what} swizzled {:?}", desc.s_address_mode); - let plan = plain - .plan(&dev, &shape) - .unwrap_or_else(|e| panic!("{what}: {e}")); - assert!(plan.variant.swizzled_storage.contains(&SOURCE), "{what}"); - let key = plan.variant.lowering_inputs(Stage::Kernel); - let variant = pipeline(&dev, &bc, &key).expect("the variant's inputs"); - let again = variant.plan(&dev, &shape).expect("variant plan"); - assert_eq!(again.variant, plan.variant, "{what}"); - } - if let Through::Runtime = through { - let mut mip = linear; - mip.mip_filter = crate::metal::SamplerMipFilter::Nearest; - let mut mixed = linear; - mixed.mag_filter = F::Nearest; - let mut clamp = linear; - clamp.t_address_mode = SamplerAddressMode::MirrorClampToEdge; - for (name, desc) in [("mirror clamp", clamp), ("mip", mip)] { - let shape = sampled_state(pf, desc).shape(); - for p in [&plain, &variant] { - let named = p - .plan(&dev, &shape) - .unwrap_or_else(|e| panic!("{what} {name}: {e}")); - assert_eq!(named.variant, plan.variant, "{what} {name}"); - } - } - match plain.plan(&dev, &sampled_state(pf, mixed).shape()) { - Err(crate::error::BindError::Unsupported(u)) => assert_eq!( - u, - Unsupported::not_implemented(Feature::Format), - "{what} mixed" - ), - other => panic!("{what} mixed: {:?}", other.map(|_| ())), - } - } - } - } - } - assert!(planned > 0); -} - /// [`sample_kernel`]'s `float` sample through `through` taken `n` times, the `i`-th at the /// coordinate plus `i / 8` on each axis, and where `offsets` at its own constant texel offset /// (`(i + 1, -i)`), the sum stored. diff --git a/crates/metal2vulkan/src/tests/engine_extended_range/volumes.rs b/crates/metal2vulkan/src/tests/engine_extended_range/volumes.rs index 245797a5c..1279ea787 100644 --- a/crates/metal2vulkan/src/tests/engine_extended_range/volumes.rs +++ b/crates/metal2vulkan/src/tests/engine_extended_range/volumes.rs @@ -11,7 +11,7 @@ //! constexpr sampler and by the binder for a runtime one, and a padded form's 3D sample. use super::levels::{constexpr_words, descriptor, level_kernel, probe_texture, run_levels, Shape}; -use super::samples::{form_of, sampled_state_of, Through}; +use super::samples::{form_of, Through}; use super::*; use crate::error::Unsupported; use crate::metal::{SamplerAddressMode, SamplerMipFilter}; @@ -190,8 +190,7 @@ fn volume_samples_are_metals_bytes() { /// A 3D texture's linear mip filter is not built (its blend of two levels fits no rule tried): /// the lowering refuses a constexpr sampler's, `NotImplemented(Format)`, and builds its nearest -/// one; the binder refuses a runtime sampler's and plans a nearest one into the variant. A padded -/// form's 3D sample is refused too (not measured). +/// one. A padded form's 3D sample is refused too (not measured). #[test] fn volume_linear_mip_filters_and_padded_forms_are_refused() { let forms = [ @@ -234,31 +233,4 @@ fn volume_linear_mip_filters_and_padded_forms_are_refused() { refused(&format!("{mip:?} R10X6 on {stem}"), r); } } - let Some(bc) = assemble("runtime 3D mip", &volume_kernel(Through::Runtime, false)) else { - return; - }; - for (stem, dev) in devices() { - let plain = pipeline(&dev, &bc, &LowerInputs::new()).expect("a sampling kernel"); - for (pf, form) in forms { - for (mip, planned) in [ - (SamplerMipFilter::Nearest, true), - (SamplerMipFilter::Linear, false), - ] { - let what = format!("{mip:?} {pf:?} on {stem}"); - let desc = volume_descriptor(true, mip, edge); - let state = sampled_state_of(TextureType::Type3D, pf, desc); - match (plain.plan(&dev, &state.shape()), planned) { - (Ok(plan), true) => assert_eq!( - plan.variant.extended_range, - BTreeMap::from([(SOURCE, form)]), - "{what}" - ), - (Err(crate::error::BindError::Unsupported(u)), false) => { - assert_eq!(u, Unsupported::not_implemented(Feature::Format), "{what}") - } - (other, _) => panic!("{what}: {:?}", other.map(|_| ())), - } - } - } - } } diff --git a/crates/metal2vulkan/src/tests/engine_fragment_depth_clamp.rs b/crates/metal2vulkan/src/tests/engine_fragment_depth_clamp.rs index cb7fdb416..2a9b00bfb 100644 --- a/crates/metal2vulkan/src/tests/engine_fragment_depth_clamp.rs +++ b/crates/metal2vulkan/src/tests/engine_fragment_depth_clamp.rs @@ -17,9 +17,8 @@ //! tool skips visibly. No GPU is used. use std::collections::BTreeMap; -use std::path::Path; -use crate::device::{Device, DeviceDescription, DevicePolicy, DeviceProfile}; +use crate::device::{DevicePolicy, DeviceProfile}; use crate::library::FunctionArtifact; use crate::pipeline::link::{link, LinkInputs}; use crate::pipeline::lower_inputs::LoweringInputs; @@ -172,133 +171,3 @@ fn a_depth_clamp_range_variant_clamps_the_depth_to_the_draws_range() { assert_eq!((kills(&a), kills(&b)), (1, 1), "{stem}: the kill"); } } - -/// A draw asking for the depth clamp range runs the variant whose fragment function clamps the -/// depth it writes, with the state's range at the function's push field; a pipeline whose -/// fragment function writes no depth has no such variant and draws as it is. -#[test] -fn a_depth_clamp_range_draw_runs_the_variant_with_the_states_range() { - use crate::bind::{BindState, DrawCall}; - use crate::budget::Budget; - use crate::error::BindError; - use crate::library::Library; - use crate::metal::PixelFormat; - use crate::pipeline::descriptor::{ - ColorAttachmentDescriptor, FunctionDescriptor, RenderPipelineDescriptor, StageSource, - }; - use crate::pipeline::facts::RuntimeFact; - use crate::pipeline::interface::PushLoc; - use crate::pipeline::sym::{PushField, Stage}; - let Some(bc) = fixture() else { - return; - }; - let budget = Budget::standard(); - let lib = Library::from_air(&bc).expect("library"); - let function = - |name| StageSource::Function(FunctionDescriptor::new(lib.function(name).expect(name))); - let triangle = DrawCall::Primitives { - vertex_start: 0, - vertex_count: 3, - instance_count: 1, - base_instance: 0, - }; - let range = [0.25f32, 0.5]; - let state = BindState { - depth_clamp_range: Some(range), - ..Default::default() - }; - for stem in ["moltenvk-m3", "lavapipe"] { - let 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 desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); - let dev = Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device"); - for (fragment, writes) in [("rfb_depth", true), ("rfb_position", false)] { - let what = format!("{stem} {fragment}"); - let mut d = RenderPipelineDescriptor::new(function("rfb_full")); - d.fragment = Some(function(fragment)); - d.color_attachments[0] = Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA32Float)); - d.depth_format = Some(PixelFormat::Depth32Float); - let base = dev - .compile_render_pipeline(&d, &budget) - .unwrap_or_else(|e| panic!("{what}: {e}")); - assert_eq!(base.graphics.writes_depth, writes, "{what}"); - let plan = base - .plan(&dev, &state.shape()) - .unwrap_or_else(|e| panic!("{what}: {e:?}")); - assert_eq!(plan.variant.depth_clamp_range, writes, "{what}"); - if !writes { - plan.instantiate_draw(&state, &triangle) - .unwrap_or_else(|e| panic!("{what}: {e:?}")); - continue; - } - assert_eq!( - plan.instantiate_draw(&state, &triangle), - Err(BindError::NeedsVariant { - variant: Box::new(plan.variant.clone()) - }), - "{what}" - ); - let key = plan.variant.clone(); - let v = dev - .compile_render_variant(&d, &key, &budget) - .unwrap_or_else(|e| panic!("{what}: {e}")); - for m in &v.stages { - check_words_valid(&m.spirv, &v.requirements, dev.profile()) - .unwrap_or_else(|e| panic!("{what} {:?}: L3: {e}", m.stage)); - } - assert!( - v.dependencies - .iter() - .any(|x| x.fact == RuntimeFact::DepthClampRange), - "{what}" - ); - let plan = v - .plan(&dev, &state.shape()) - .unwrap_or_else(|e| panic!("{what}: {e:?}")); - assert_eq!(plan.variant, key, "{what}"); - let commands = plan - .instantiate_draw(&state, &triangle) - .unwrap_or_else(|e| panic!("{what}: {e:?}")); - let offset = v - .interface - .push - .iter() - .filter(|pl| pl.stage == Stage::Fragment) - .flat_map(|pl| pl.fields.iter()) - .find(|f| f.field == PushField::DepthClampRange) - .map(|f| match f.loc { - PushLoc::Push { offset } => offset as usize, - other => panic!("{what}: {other:?}"), - }) - .unwrap_or_else(|| panic!("{what}: no range field")); - let mut pushed = vec![None; 256]; - for w in &commands.push_constants { - for (i, b) in w.bytes.iter().enumerate() { - if let Some(slot) = pushed.get_mut(w.offset as usize + i) { - *slot = Some(*b); - } - } - } - let bytes: Vec> = range - .iter() - .flat_map(|v| v.to_le_bytes()) - .map(Some) - .collect(); - assert_eq!(pushed.get(offset..offset + 8), Some(&bytes[..]), "{what}"); - // Without the range the variant asks for the base again. - let plan = v - .plan(&dev, &BindState::default().shape()) - .unwrap_or_else(|e| panic!("{what}: {e:?}")); - assert!(!plan.variant.depth_clamp_range, "{what}"); - assert!( - matches!( - plan.instantiate_draw(&BindState::default(), &triangle), - Err(BindError::NeedsVariant { .. }) - ), - "{what}" - ); - } - } -} diff --git a/crates/metal2vulkan/src/tests/engine_graphics_binder.rs b/crates/metal2vulkan/src/tests/engine_graphics_binder.rs deleted file mode 100644 index cf090fa7e..000000000 --- a/crates/metal2vulkan/src/tests/engine_graphics_binder.rs +++ /dev/null @@ -1,2378 +0,0 @@ -//! The graphics and texture binder end to end. No device is opened; nothing runs on a GPU. -//! -//! Pipelines go through the public compile API, `RenderPipeline::plan` / -//! `ComputePipeline::plan`, and `BindingPlan::instantiate_draw` / `instantiate_dispatch`: -//! -//! - A vertex + fragment pipeline (`engine/stage_io`) plans one write per layout binding, one -//! vertex-buffer bind per fixed-function binding, and draws map to the Vulkan draw of the same -//! arguments; an unbound vertex buffer and a missing per-bind stride are typed refusals. A -//! pulled layout's stride fills its push field (static from the pipeline, per bind from the -//! bind), and a pulled source buffer that is also a buffer argument is one binding. A draw's -//! vertex-buffer extent is what its vertex range fetches, its index and indirect buffers are -//! uses, and a bind offset or per-bind stride Vulkan cannot fetch is refused. -//! - Sampling kernels (`engine/sampling`) write combined image samplers: the bound texture's -//! view and the runtime sampler slot, the neutral of the declared type when unbound, and a -//! neutral with an `IncompatibleBinding` diagnostic for a texture of another type, the variant -//! for one of another numeric class; `SamplerState` follows the bound sampler's word; anisotropy -//! and LOD clamps are checked at plan time. -//! - Texture kernels (`engine/texture_ops`): a read cube is viewed as the 2D array it is -//! declared as (`ImageViewShape`); texel buffers get their view format and a range of whole -//! texels, checked exactly against `maxTexelBufferElements`. -//! - A storage texture (`engine/storage_texture_write`) bound as bgra8 asks for the storage -//! variant exactly where bgra8 lacks storage, and the rgba8 plan stays on the common path. -//! -//! `llvm-as` assembles the fixtures; without it the tests skip visibly. - -use std::collections::BTreeSet; -use std::path::Path; - -use crate::bind::{ - sampler_desc, AccessClass, BindState, BindingPlan, BoundBuffer, BoundSampler, BoundTexture, - Dispatch, DrawCall, DrawCommands, FieldLocation, ImageSource, IndexBufferRef, IndexOverrun, - IndirectRef, NeutralResource, PlanDiagnostic, SamplerDescriptor, SamplerSource, StageTable, - TextureFacts, UseTarget, WriteSource, -}; -use crate::budget::Budget; -use crate::device::{Device, DeviceDescription, DevicePolicy}; -use crate::error::{BindError, DescriptorError, Error, Feature}; -use crate::library::Library; -use crate::metal::sampler::{SamplerUse, SamplerWord}; -use crate::metal::{ - self, PixelFormat, SamplerMinMagFilter, SamplerMipFilter, SamplerReductionMode, TextureType, - VertexFormat, -}; -use crate::pipeline::descriptor::{ - ColorAttachmentDescriptor, VertexAttributeDescriptor, VertexBufferLayoutDescriptor, - VertexDescriptor, -}; -use crate::pipeline::interface::{AccessSet, BufferForm, SlotInterface, Window}; -use crate::pipeline::layout::BindingSource; -use crate::pipeline::sym::{PushField, SlotClass, SlotRef, SpecKey, Stage}; -use crate::pipeline::testing::{engine_dir, llvm_assemble, AssembleError}; -use crate::pipeline::VertexStride; -use crate::pipeline::{ - ComputePipeline, ComputePipelineDescriptor, FunctionDescriptor, RenderPipeline, - RenderPipelineDescriptor, StageSource, -}; -use crate::vk; - -fn fixture(stem: &str) -> Option> { - match llvm_assemble(&engine_dir().join(format!("{stem}.ll"))) { - Ok(b) => Some(b), - Err(AssembleError::Missing(why)) => { - eprintln!("SKIPPED: {why}"); - None - } - Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected {stem}.ll: {why}"), - } -} - -/// Every committed profile as a device, by stem. -fn devices() -> Vec<(String, Device)> { - let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../metal2vulkan-validation/profiles"); - let mut out = Vec::new(); - for e in std::fs::read_dir(&dir).expect("profiles") { - let path = e.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("profile"); - let desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); - out.push(( - stem, - Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device"), - )); - } - out.sort_by(|a, b| a.0.cmp(&b.0)); - out -} - -fn device(stem: &str) -> Device { - devices() - .into_iter() - .find(|(s, _)| s == stem) - .map(|(_, d)| d) - .expect("committed profile") -} - -fn slot(stage: Stage, class: SlotClass, index: u32) -> SlotRef { - SlotRef { - stage, - class, - index, - } -} - -fn buffer(length: u64, offset: u64, stride: Option) -> BoundBuffer { - BoundBuffer::Buffer { - length, - offset, - gpu_address: 0x1_0000, - device_address: None, - attribute_stride: stride, - } -} - -// ---- Render pipelines -------------------------------------------------------------------------- - -/// `stage_io_vertex`'s attributes: one interleaved per-vertex buffer at index 0. -fn vertex_descriptor() -> VertexDescriptor { - let mut d = VertexDescriptor::new(); - d.layouts - .insert(0, VertexBufferLayoutDescriptor::new(Some(24))); - for (index, format, offset) in [ - (0, VertexFormat::Float3, 0), - (1, VertexFormat::Half2, 12), - (4, VertexFormat::UShort2, 16), - (7, VertexFormat::UChar4, 20), - ] { - d.attributes - .insert(index, VertexAttributeDescriptor::new(format, offset, 0)); - } - d -} - -/// `stage_io`'s vertex + fragment pipeline descriptor. -fn render_descriptor(bc: &[u8]) -> RenderPipelineDescriptor { - let lib = Library::from_air(bc).expect("library"); - let v = lib.function("stage_io_vertex").expect("vertex"); - let f = lib.function("stage_io_fragment").expect("fragment"); - let mut d = RenderPipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new(v))); - d.fragment = Some(StageSource::Function(FunctionDescriptor::new(f))); - d.vertex_descriptor = Some(vertex_descriptor()); - d.color_attachments[0] = Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm)); - d.color_attachments[2] = Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA32Uint)); - d.depth_format = Some(PixelFormat::Depth32Float); - d -} - -fn render_pipeline(dev: &Device, bc: &[u8]) -> Result { - dev.compile_render_pipeline(&render_descriptor(bc), &Budget::standard()) -} - -/// A draw's own uses: each resource and its range, after checking that each is read in its -/// fixed-function stage. -fn uses(cmds: &crate::bind::DrawCommands) -> Vec<(UseTarget, Option<(u64, u64)>)> { - cmds.uses - .iter() - .map(|u| { - let (class, stages) = match u.resource { - UseTarget::IndexBuffer => { - (AccessClass::Index, vk::PipelineStageFlags2::INDEX_INPUT) - } - _ => ( - AccessClass::Indirect, - vk::PipelineStageFlags2::DRAW_INDIRECT, - ), - }; - assert_eq!( - (u.access, u.class, u.stages), - (AccessSet::READ, class, stages) - ); - (u.resource, u.range.map(|r| (r.offset, r.len))) - }) - .collect() -} - -/// The vertex buffer at 0 and the constant `scale` at 1. -fn render_state(scale_offset: u64) -> BindState { - let mut v = StageTable::default(); - v.buffers.insert(0, buffer(24 * 64, 48, None)); - v.buffers.insert(1, buffer(256, scale_offset, None)); - let mut s = BindState::default(); - s.stages.insert(Stage::Vertex, v); - s -} - -/// `Device::compile_render_pipeline` compiles a `Function` fragment stage with no output at a color -/// it writes that the pipeline has no attachment for, whose write Metal discards: the fixture's -/// fragment, writing colors 0 and 2, states color 0 alone among its color outputs in a pipeline of -/// attachment 0 alone, and both where it has both. Under alpha to coverage its color 0 stays -/// without attachment 0, the coverage reading its alpha. -#[test] -fn a_render_pipeline_writes_no_color_it_has_no_attachment_for() { - let Some(bc) = fixture("stage_io") else { - return; - }; - for stem in ["lavapipe", "moltenvk-m3", "amd-780m-radv"] { - let dev = device(stem); - let outputs = |edit: &dyn Fn(&mut RenderPipelineDescriptor)| { - let mut d = render_descriptor(&bc); - edit(&mut d); - dev.compile_render_pipeline(&d, &Budget::standard()) - .unwrap_or_else(|e| panic!("{stem}: {e}")) - .graphics - .color_outputs - }; - assert_eq!(outputs(&|_| {}), 0b101, "{stem}"); - assert_eq!(outputs(&|d| d.color_attachments[2] = None), 0b1, "{stem}"); - let covered = |d: &mut RenderPipelineDescriptor| { - d.color_attachments[0] = None; - d.alpha_to_coverage = true; - }; - assert_eq!(outputs(&covered), 0b101, "{stem}"); - } -} - -/// A vertex + fragment pipeline plans every binding (its vertex buffer pulled, so read through -/// its storage view) and maps each Metal draw to the Vulkan draw of the same arguments. -#[test] -fn a_render_pipeline_plans_and_draws() { - let Some(bc) = fixture("stage_io") else { - return; - }; - let mut planned = 0; - for stem in ["moltenvk-m3", "lavapipe", "amd-780m-radv"] { - let dev = device(stem); - let p = render_pipeline(&dev, &bc).unwrap_or_else(|e| panic!("{stem}: {e}")); - let state = render_state(16); - let plan = p.plan(&dev, &state.shape()).expect("plan"); - let bindings: usize = p.layout.sets.iter().map(|s| s.bindings.len()).sum(); - assert_eq!(plan.descriptors.len(), bindings, "{stem}"); - assert!(plan.variant.is_empty(), "{stem}"); - for d in &plan.descriptors { - let b = &p.layout.sets[0].bindings[d.binding as usize]; - if let BindingSource::Buffer(s) = b.source { - assert_eq!(d.source, WriteSource::Buffer { slot: s }, "{stem}"); - } - } - assert!(plan.vertex_buffers.is_empty(), "{stem}"); - - let draw = DrawCall::Primitives { - vertex_start: 3, - vertex_count: 6, - instance_count: 2, - base_instance: 5, - }; - let cmds = plan.instantiate_draw(&state, &draw).expect("draw"); - assert_eq!( - cmds.draw, - vk::DrawCommand::Draw { - vertex_count: 6, - instance_count: 2, - first_vertex: 3, - first_instance: 5 - } - ); - assert!(!cmds.indirect_needs_arguments); - assert!(cmds.uses.is_empty(), "{stem}"); - // The pulled attributes read the vertex buffer through its whole storage view. - let vb = slot(Stage::Vertex, SlotClass::Buffer, 0); - let extent = |cmds: &crate::bind::DrawCommands| { - cmds.extents - .iter() - .find(|e| e.slot == vb) - .map(|e| e.window) - .expect("vertex extent") - }; - assert_eq!(extent(&cmds), Window::Whole, "{stem}"); - // A layout the device cannot fetch for the draw (`BindShape::far_vertex_buffers`) that - // the pipeline fetches in no fixed-function binding is left as it is. - let mut far = state.clone(); - far.far_vertex_buffers = BTreeSet::from([7]); - assert!( - p.plan(&dev, &far.shape()).expect("plan").variant.is_empty(), - "{stem}" - ); - // Every push range of the layout is written once, over its whole range. - for r in &p.layout.push_constants { - let w = cmds - .push_constants - .iter() - .find(|w| w.stages == r.stages) - .unwrap_or_else(|| panic!("{stem}: no push write for {r:?}")); - assert_eq!((w.offset, w.bytes.len() as u32), (r.offset, r.size)); - } - // The constant buffer's range covers its window from the aligned bind offset. - for range in &cmds.descriptor_ranges { - assert!(range.range.range >= 16, "{stem}"); - } - let indexed = DrawCall::Indexed { - index_type: vk::IndexType::UINT16, - index_buffer: IndexBufferRef::new(9, 4096), - index_count: 12, - index_offset: 64, - instance_count: 1, - base_vertex: -2, - base_instance: 0, - }; - let cmds = plan.instantiate_draw(&state, &indexed).expect("indexed"); - assert_eq!(extent(&cmds), Window::Whole, "{stem}: GPU-side vertices"); - assert_eq!( - uses(&cmds), - vec![(UseTarget::IndexBuffer, Some((0, 24)))], - "{stem}" - ); - assert_eq!( - cmds.draw, - vk::DrawCommand::DrawIndexed { - index_type: vk::IndexType::UINT16, - index_buffer_offset: 64, - index_count: 12, - instance_count: 1, - first_index: 0, - vertex_offset: -2, - first_instance: 0 - } - ); - let indirect = DrawCall::Indirect { - indirect: IndirectRef { - token: 4, - offset: 32, - }, - indexed: None, - }; - let cmds = plan.instantiate_draw(&state, &indirect).expect("indirect"); - assert_eq!( - cmds.draw, - vk::DrawCommand::DrawIndirect { - offset: 32, - draw_count: 1, - stride: 16 - } - ); - assert_eq!(extent(&cmds), Window::Whole, "{stem}"); - assert_eq!( - uses(&cmds), - vec![(UseTarget::Indirect, Some((0, 16)))], - "{stem}" - ); - planned += 1; - - // An unbound buffer argument gets the zero buffer. - let mut neutral = state.clone(); - neutral - .stages - .get_mut(&Stage::Vertex) - .expect("vertex") - .buffers - .remove(&1); - let plan = p.plan(&dev, &neutral.shape()).expect("plan"); - assert!(plan.descriptors.iter().any(|d| matches!( - d.source, - WriteSource::Neutral(NeutralResource::ZeroBuffer { .. }) - ))); - // A shape the state does not have is an internal error at instantiation. - assert!(matches!( - plan.instantiate_draw(&state, &draw), - Err(BindError::Internal(_)) - )); - } - assert_eq!(planned, 3); -} - -/// A device without `drawIndirectFirstInstance` (as the Vulkan 1.2 floors are; here lavapipe's -/// description without it) takes an indirect draw's arguments on the CPU, since Metal's may carry a -/// base instance an indirect command there must not; one with it records the indirect command. A -/// direct draw is unaffected. -#[test] -fn an_indirect_draw_without_draw_indirect_first_instance_reads_its_arguments() { - let Some(bc) = fixture("stage_io") else { - return; - }; - let path = Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../metal2vulkan-validation/profiles/lavapipe.json"); - let text = std::fs::read_to_string(path).expect("profile"); - let edited = text.replace( - "\"drawIndirectFirstInstance\": true", - "\"drawIndirectFirstInstance\": false", - ); - assert_ne!(edited, text, "lavapipe states the feature"); - let without = DeviceDescription::from_khronos_json(&edited, None).expect("description"); - let without = Device::from_queries(without, DevicePolicy::RESIDENT_TABLES).expect("device"); - for (dev, missing) in [(without, true), (device("lavapipe"), false)] { - let stem = if missing { "without" } else { "lavapipe" }; - let p = render_pipeline(&dev, &bc).unwrap_or_else(|e| panic!("{stem}: {e}")); - let state = render_state(16); - let plan = p.plan(&dev, &state.shape()).expect("plan"); - let indirect = DrawCall::Indirect { - indirect: IndirectRef { - token: 4, - offset: 32, - }, - indexed: None, - }; - let cmds = plan.instantiate_draw(&state, &indirect).expect("indirect"); - assert_eq!(cmds.indirect_needs_arguments, missing, "{stem}"); - let direct = DrawCall::Primitives { - vertex_start: 0, - vertex_count: 3, - instance_count: 1, - base_instance: 2, - }; - let cmds = plan.instantiate_draw(&state, &direct).expect("direct"); - assert!(!cmds.indirect_needs_arguments, "{stem}"); - } -} - -/// A direct indexed draw whose indices run past its index buffer's length is clamped to the -/// indices inside the buffer, since Vulkan requires every index inside the bound range without -/// `robustBufferAccess2` (`VUID-vkCmdDrawIndexed-robustBufferAccess2-08798`); `index_overrun` -/// records it. A draw to the buffer's last byte is unchanged, and one with no index inside the -/// buffer draws none. Checked on every committed profile that compiles the pipeline, those that -/// state `robustBufferAccess2` among them. -#[test] -fn an_indexed_draw_past_its_index_buffer_is_bounded() { - let Some(bc) = fixture("stage_io") else { - return; - }; - let draw = |length, index_offset, index_count| DrawCall::Indexed { - index_type: vk::IndexType::UINT16, - index_buffer: IndexBufferRef::new(9, length), - index_count, - index_offset, - instance_count: 3, - base_vertex: 7, - base_instance: 0, - }; - let drawn = |cmds: &DrawCommands| match cmds.draw { - vk::DrawCommand::DrawIndexed { - index_buffer_offset, - index_count, - vertex_offset, - .. - } => (index_buffer_offset, index_count, vertex_offset), - other => panic!("an indexed draw: {other:?}"), - }; - let mut checked = 0; - for (stem, dev) in devices() { - // `vk12-floor` and `roadmap-2022` refuse the pipeline's depth attachment. - let Ok(p) = render_pipeline(&dev, &bc) else { - continue; - }; - checked += 1; - let state = render_state(16); - let plan = p.plan(&dev, &state.shape()).expect("plan"); - // 12 halves from byte 64 of 88 bytes: to the buffer's last byte. - let cmds = plan - .instantiate_draw(&state, &draw(88, 64, 12)) - .expect("inside"); - assert_eq!(cmds.index_overrun, None, "{stem}"); - assert_eq!(drawn(&cmds), (64, 12, 7), "{stem}"); - assert_eq!(uses(&cmds), vec![(UseTarget::IndexBuffer, Some((0, 24)))]); - // 86 bytes: Metal's fetch reads to byte 88, the length rounded up to 4 (`fetch_end`). - let cmds = plan - .instantiate_draw(&state, &draw(86, 64, 12)) - .expect("rounded"); - assert_eq!(cmds.index_overrun, None, "{stem}"); - assert_eq!(uses(&cmds), vec![(UseTarget::IndexBuffer, Some((0, 24)))]); - // 3 more: past the end. - let cmds = plan - .instantiate_draw(&state, &draw(88, 64, 15)) - .expect("past"); - assert_eq!( - cmds.index_overrun, - Some(IndexOverrun::Clamped { past_end: 3 }), - "{stem}" - ); - assert_eq!(drawn(&cmds), (64, 12, 7), "{stem}"); - assert_eq!(uses(&cmds), vec![(UseTarget::IndexBuffer, Some((0, 24)))]); - // An index offset at the buffer's end: no index inside it. - let cmds = plan - .instantiate_draw(&state, &draw(88, 88, 4)) - .expect("none"); - assert_eq!( - cmds.index_overrun, - Some(IndexOverrun::Clamped { past_end: 4 }), - "{stem}" - ); - assert_eq!(drawn(&cmds), (0, 0, 7), "{stem}"); - assert_eq!(uses(&cmds), vec![(UseTarget::IndexBuffer, Some((0, 0)))]); - // A draw of no index: at its offset inside the buffer, at offset 0 from its end or past. - for (offset, at) in [(64, 64), (88, 0), (200, 0)] { - let cmds = plan - .instantiate_draw(&state, &draw(88, offset, 0)) - .expect("no index"); - assert_eq!(cmds.index_overrun, None, "{stem}"); - assert_eq!(drawn(&cmds), (at, 0, 7), "{stem} {offset}"); - assert_eq!(uses(&cmds), vec![(UseTarget::IndexBuffer, Some((0, 0)))]); - } - } - assert!(checked > 0); -} - -/// An indexed indirect draw's counts are in GPU memory and nothing bounds its index fetch -/// (`VUID-VkDrawIndexedIndirectCommand-robustBufferAccess2-08798`), so it asks for its arguments -/// on the CPU, whose direct draw the binder bounds, at any index offset, where the same draw -/// without indices stays GPU-side unless something else asks for the read. Checked on every -/// committed profile that compiles the pipeline. -#[test] -fn an_indexed_indirect_draw_reads_its_arguments_where_nothing_bounds_its_indices() { - let Some(bc) = fixture("stage_io") else { - return; - }; - let indirect = |indexed| DrawCall::Indirect { - indirect: IndirectRef { - token: 4, - offset: 32, - }, - indexed, - }; - let at = |offset| Some((vk::IndexType::UINT16, IndexBufferRef::new(9, 256), offset)); - // Whether a profile read an indexed indirect draw on the CPU that it would otherwise have - // kept on the GPU. - let mut seen = false; - for (stem, dev) in devices() { - let Ok(p) = render_pipeline(&dev, &bc) else { - continue; - }; - let state = render_state(16); - let plan = p.plan(&dev, &state.shape()).expect("plan"); - let read = |draw| { - plan.instantiate_draw(&state, &draw) - .unwrap_or_else(|e| panic!("{stem}: {e}")) - .indirect_needs_arguments - }; - let otherwise = read(indirect(None)); - assert!(read(indirect(at(64))), "{stem}"); - assert!(read(indirect(at(256))), "{stem}: an offset at the end"); - seen |= !otherwise; - } - assert!( - seen, - "an indexed draw is read where the same draw without indices is not" - ); -} - -/// A pulled source buffer bound to an allocation too large for `maxStorageBufferRange` is a -/// device-address slot in the variant. Planning the default pipeline, which pulls every attribute, -/// for an unaligned, large vertex buffer names the source buffer's device-address slot alone, so -/// the variant's own plan states the same key. That plan writes no descriptor for the source -/// buffer: the vertex stage reads its root table, whose entry `2 + 0` is the bound buffer (its host -/// and guest addresses, padded size, and bind offset), and a bind without a device address is -/// refused. On a profile without device addresses (`lavapipe` without `bufferDeviceAddress`, below -/// the runtime's floor; the runtime floor's profile states no `Depth32Float` attachment) the -/// variant is the default pipeline, and the draw's descriptor range exceeds the limit. -#[test] -fn a_render_plan_reads_pulled_source_buffers_by_device_address() { - let Some(bc) = fixture("stage_io") else { - return; - }; - let draw = DrawCall::Primitives { - vertex_start: 0, - vertex_count: 3, - instance_count: 1, - base_instance: 0, - }; - let large = 1u64 << 40; - let (mut addressed, mut viewed) = (0, 0); - let no_addresses = { - let path = Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../metal2vulkan-validation/profiles/lavapipe.json"); - let text = std::fs::read_to_string(path).expect("profile"); - let mut desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); - desc.features - .remove(&crate::device::requirements::VkFeature::BufferDeviceAddress); - Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device") - }; - let devices = [ - ("moltenvk-m3", device("moltenvk-m3")), - ("lavapipe", device("lavapipe")), - ("lavapipe without bufferDeviceAddress", no_addresses), - ]; - for (stem, dev) in devices { - let d = render_descriptor(&bc); - let p = dev - .compile_render_pipeline(&d, &Budget::standard()) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - let host = 0x7_0000_0000; - let state = with_vertex_buffer( - &render_state(16), - BoundBuffer::Buffer { - length: large, - offset: 50, - gpu_address: 0x1_0000, - device_address: Some(host), - attribute_stride: None, - }, - ); - let plan = p.plan(&dev, &state.shape()).expect("plan"); - let vb = slot(Stage::Vertex, SlotClass::Buffer, 0); - assert!(plan.variant.pulled_vertex_buffers.is_empty(), "{stem}"); - let psb = dev.profile().fields().descriptors.buffer_device_address - && dev.profile().fields().leaf.int64; - assert_eq!( - plan.variant.psb_slots.contains(&vb), - psb, - "{stem}: {:?}", - plan.variant - ); - let v = dev - .compile_render_variant(&d, &plan.variant, &Budget::standard()) - .unwrap_or_else(|e| panic!("{stem} variant: {e}")); - let vplan = v.plan(&dev, &state.shape()).expect("variant plan"); - assert_eq!(vplan.variant, plan.variant, "{stem}: a fixed point"); - let source = v - .layout - .sets - .iter() - .flat_map(|s| &s.bindings) - .any(|b| b.source == BindingSource::Buffer(vb)); - if !psb { - assert!(source, "{stem}: a storage view"); - assert!( - matches!( - vplan.instantiate_draw(&state, &draw), - Err(BindError::DescriptorRangeExceeded { slot, .. }) if slot == vb - ), - "{stem}" - ); - viewed += 1; - continue; - } - assert!(!source, "{stem}: no descriptor for a device-address slot"); - assert!( - matches!( - v.interface.slots.get(&vb), - Some(SlotInterface::Buffer(b)) if b.form == BufferForm::Psb - ), - "{stem}" - ); - let cmds = vplan.instantiate_draw(&state, &draw).expect("draw"); - assert!(cmds.buffer_offsets.is_empty(), "{stem}"); - let (_, table) = cmds - .root_tables - .iter() - .find(|(stages, _)| stages.contains(vk::ShaderStageFlags::VERTEX)) - .unwrap_or_else(|| panic!("{stem}: no vertex root table")); - let word = |entry: usize, field: usize| { - let at = entry * 32 + field * 8; - u64::from_le_bytes(table.bytes[at..at + 8].try_into().expect("eight bytes")) - }; - assert_eq!( - [word(2, 0), word(2, 1), word(2, 2), word(2, 3)], - [host, 0x1_0000, large, 50], - "{stem}: entry 2 + 0 is the source buffer" - ); - let mut no_address = state.clone(); - no_address - .stages - .get_mut(&Stage::Vertex) - .expect("vertex") - .buffers - .insert( - 0, - BoundBuffer::Buffer { - length: large, - offset: 50, - gpu_address: 0x1_0000, - device_address: None, - attribute_stride: None, - }, - ); - assert_eq!( - v.plan(&dev, &no_address.shape()), - Err(BindError::MissingDeviceAddress { slot: vb }), - "{stem}" - ); - addressed += 1; - } - assert_eq!((addressed, viewed), (2, 1)); -} - -fn with_vertex_buffer(state: &BindState, b: BoundBuffer) -> BindState { - let mut s = state.clone(); - s.stages - .get_mut(&Stage::Vertex) - .expect("vertex") - .buffers - .insert(0, b); - s -} - -/// The `u32` a draw writes for vertex push field `field`. -fn vertex_push(plan: &BindingPlan, cmds: &DrawCommands, field: PushField) -> u32 { - stage_push( - plan, - cmds, - (Stage::Vertex, vk::ShaderStageFlags::VERTEX), - field, - ) -} - -/// The `u32` a draw writes for push field `field` of `stage` (whose Vulkan stage is `flags`). -fn stage_push( - plan: &BindingPlan, - cmds: &DrawCommands, - (stage, flags): (Stage, vk::ShaderStageFlags), - field: PushField, -) -> u32 { - let f = plan - .push - .fields - .iter() - .find(|f| f.stage == stage && f.field == field) - .unwrap_or_else(|| panic!("{field:?} is not placed")); - let FieldLocation::PushWindow { offset } = f.location else { - panic!("{field:?} spilled"); - }; - let w = cmds - .push_constants - .iter() - .find(|w| { - w.stages.contains(flags) - && w.offset <= offset - && offset + 4 <= w.offset + w.bytes.len() as u32 - }) - .unwrap_or_else(|| panic!("no push write covers {field:?}")); - let at = (offset - w.offset) as usize; - u32::from_le_bytes(w.bytes[at..at + 4].try_into().expect("four bytes")) -} - -/// Pulled attributes (signed formats into the `uint` attributes) from layout 1, the `scale` -/// argument's index, with a static stride, and from layout 2 with a per-bind stride, beside layout -/// 0's, pulled at its static stride as every attribute is outside the identity domains. Buffer 1 is -/// one binding (the argument's slot, widened to a `Whole` storage view); the static stride fills -/// its push field without a per-bind stride, and the per-bind one is the bind's `attributeStride`, -/// 0 without one (as for fixed function). -#[test] -fn pulled_layouts_take_their_stride_and_share_argument_slots() { - let Some(bc) = fixture("stage_io") else { - return; - }; - let dev = device("moltenvk-m3"); - let lib = Library::from_air(&bc).expect("library"); - let v = lib.function("stage_io_vertex").expect("vertex"); - let mut d = RenderPipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new(v))); - let mut vd = vertex_descriptor(); - vd.layouts - .insert(1, VertexBufferLayoutDescriptor::new(Some(4))); - vd.layouts - .insert(2, VertexBufferLayoutDescriptor::new(None)); - vd.attributes.insert( - 4, - VertexAttributeDescriptor::new(VertexFormat::Short2, 0, 2), - ); - vd.attributes - .insert(7, VertexAttributeDescriptor::new(VertexFormat::Char4, 0, 1)); - d.vertex_descriptor = Some(vd); - d.rasterization_enabled = false; - let p = dev - .compile_render_pipeline(&d, &Budget::standard()) - .unwrap_or_else(|e| panic!("pulled pipeline: {e}")); - let strides: Vec<(u32, VertexStride)> = p - .vertex_input - .pulled - .iter() - .map(|a| (a.buffer_index, a.stride)) - .collect(); - assert_eq!( - strides, - [ - (0, VertexStride::Static(24)), - (0, VertexStride::Static(24)), - (2, VertexStride::PerBind), - (1, VertexStride::Static(4)) - ] - ); - let scale = slot(Stage::Vertex, SlotClass::Buffer, 1); - assert!( - matches!( - p.interface.slots.get(&scale), - Some(SlotInterface::Buffer(b)) if b.access == AccessSet::READ - && b.window == Window::Whole - && b.form == BufferForm::Descriptor - ), - "{:?}", - p.interface.slots.get(&scale) - ); - let bindings = p - .layout - .sets - .iter() - .flat_map(|s| &s.bindings) - .filter(|b| b.source == BindingSource::Buffer(scale)) - .count(); - assert_eq!(bindings, 1, "the argument and the fetch share one binding"); - - let mut state = render_state(0); - let vertex = state.stages.get_mut(&Stage::Vertex).expect("vertex"); - vertex.buffers.insert(2, buffer(512, 8, None)); - let unstrided = p.plan(&dev, &state.shape()).expect("plan without a stride"); - let cmds = unstrided - .instantiate_draw( - &state, - &DrawCall::Primitives { - vertex_start: 0, - vertex_count: 3, - instance_count: 1, - base_instance: 0, - }, - ) - .expect("draw without a stride"); - assert_eq!( - vertex_push(&unstrided, &cmds, PushField::VertexBufferStride(2)), - 0 - ); - state - .stages - .get_mut(&Stage::Vertex) - .expect("vertex") - .buffers - .insert(2, buffer(512, 8, Some(12))); - let plan = p.plan(&dev, &state.shape()).expect("plan"); - let writes: Vec<&WriteSource> = plan - .descriptors - .iter() - .map(|w| &w.source) - .filter(|w| **w == WriteSource::Buffer { slot: scale }) - .collect(); - assert_eq!(writes.len(), 1); - let cmds = plan - .instantiate_draw( - &state, - &DrawCall::Primitives { - vertex_start: 0, - vertex_count: 3, - instance_count: 1, - base_instance: 0, - }, - ) - .expect("draw"); - assert_eq!( - vertex_push(&plan, &cmds, PushField::VertexBufferStride(1)), - 4 - ); - assert_eq!( - vertex_push(&plan, &cmds, PushField::VertexBufferStride(2)), - 12 - ); -} - -// ---- Textures and samplers --------------------------------------------------------------------- - -fn kernel(dev: &Device, bc: &[u8], entry: &str) -> Result { - let lib = Library::from_air(bc).expect("library"); - let f = lib.function(entry).expect("entry"); - let d = ComputePipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new(f))); - dev.compile_compute_pipeline(&d, &Budget::standard()) -} - -fn texture(ty: TextureType, pf: PixelFormat) -> BoundTexture { - let mut facts = TextureFacts::new(ty, pf); - facts.usage = metal::TextureUsage::SHADER_READ | metal::TextureUsage::SHADER_WRITE; - BoundTexture::Texture { - facts, - resource_id: None, - } -} - -fn sampler(normalized: bool, reduction: SamplerReductionMode) -> BoundSampler { - let mut desc = SamplerDescriptor::new(); - desc.min_filter = SamplerMinMagFilter::Linear; - desc.mag_filter = SamplerMinMagFilter::Linear; - desc.mip_filter = SamplerMipFilter::Nearest; - desc.normalized_coordinates = normalized; - desc.reduction_mode = reduction; - BoundSampler::new(desc) -} - -fn kernel_state( - textures: &[(u32, BoundTexture)], - samplers: &[(u32, BoundSampler)], - out: bool, -) -> BindState { - let mut t = StageTable::default(); - for (i, x) in textures { - t.textures.insert(*i, *x); - } - for (i, x) in samplers { - t.samplers.insert(*i, *x); - } - if out { - t.buffers.insert(0, buffer(4096, 0, None)); - } - let mut s = BindState::default(); - s.stages.insert(Stage::Kernel, t); - s -} - -fn combined(plan: &crate::bind::BindingPlan) -> Vec<(ImageSource, SamplerSource)> { - plan.descriptors - .iter() - .filter_map(|d| match d.source { - WriteSource::CombinedImageSampler { image, sampler } => Some((image, sampler)), - _ => None, - }) - .collect() -} - -/// An `ABGR4Unorm` texture sampled with an opaque-black border reads through an -/// `R4G4B4A4`/`B4G4R4A4` view, whose built-in opaque-black border an implementation may swap -/// unless it reports `rgba4OpaqueBlackSwizzled`: the plan refuses the pair where the profile -/// lacks it (moltenvk-m3 has no `VK_KHR_maintenance10`) and plans it where it has it; a -/// transparent-black border, and an `RGBA8Unorm` texture, plan everywhere. -#[test] -fn opaque_black_borders_read_exactly_through_their_views() { - use crate::device::requirements::VkProperty; - use crate::error::{Capability, Needs}; - let Some(bc) = fixture("sampling") else { - return; - }; - let border = |color: metal::SamplerBorderColor| { - let mut b = sampler(true, SamplerReductionMode::WeightedAverage); - b.desc.s_address_mode = metal::SamplerAddressMode::ClampToBorderColor; - b.desc.border_color = color; - b - }; - let (mut refused, mut planned) = (0, 0); - for (stem, dev) in devices() { - let Ok(p) = kernel(&dev, &bc, "sample_level") else { - continue; - }; - let state = |pf, s| kernel_state(&[(0, texture(TextureType::Type2D, pf))], &[(0, s)], true); - let plan = |pf, s| p.plan(&dev, &state(pf, s).shape()); - let black = border(metal::SamplerBorderColor::OpaqueBlack); - let clear = border(metal::SamplerBorderColor::TransparentBlack); - assert!(plan(PixelFormat::RGBA8Unorm, black).is_ok(), "{stem}"); - let abgr4 = PixelFormat::ABGR4Unorm; - // A profile that cannot sample the format at all refuses it for the format. - match plan(abgr4, clear) { - Ok(_) => {} - Err(BindError::Unsupported(u)) if u.feature == Feature::Format => continue, - Err(e) => panic!("{stem}: {e}"), - } - let has = dev - .profile() - .fields() - .enabled - .properties - .contains(&VkProperty::Rgba4OpaqueBlackSwizzled); - match plan(abgr4, black) { - Ok(_) if has => planned += 1, - Err(BindError::Unsupported(u)) if !has => { - assert_eq!(u.feature, Feature::SamplerBorderColor, "{stem}"); - let Needs::AnyOf(alternatives) = &u.needs else { - panic!("{stem}: {u:?}"); - }; - assert!( - alternatives - .iter() - .all(|a| a - .contains(&Capability::Property(VkProperty::Rgba4OpaqueBlackSwizzled))), - "{stem}: {u:?}" - ); - refused += 1; - } - other => panic!("{stem} (property {has}): {other:?}"), - } - } - assert!( - refused > 0 && planned > 0, - "refused {refused}, planned {planned}" - ); -} - -/// Metal reads an opaque-black border of an `A8Unorm` texture, and of a texture whose swizzle reads -/// no alpha channel of its own, as its transparent-black border, so the plan makes such a pair's -/// runtime sampler with transparent black, which every profile reads exactly. A texture read with -/// its own alpha keeps opaque black, which off Metal's sampler, where the swizzle moves that alpha, -/// the device reads through the view with both border-swizzle features, or through a sampler made -/// with the view's mapping with `borderColorSwizzle` alone; without it the pair is refused. -#[test] -fn opaque_black_borders_follow_metal_s_texel_through_the_swizzle() { - use crate::device::requirements::VkFeature; - use crate::metal::sampler::OpaqueBlackBorder as B; - use metal::TextureSwizzle as T; - let Some(bc) = fixture("sampling") else { - return; - }; - let mut black = sampler(true, SamplerReductionMode::WeightedAverage); - black.desc.s_address_mode = metal::SamplerAddressMode::ClampToBorderColor; - black.desc.border_color = metal::SamplerBorderColor::OpaqueBlack; - let own = metal::TextureSwizzleChannels::DEFAULT; - let argb = metal::TextureSwizzleChannels::new(T::Alpha, T::Red, T::Green, T::Blue); - let rrr1 = metal::TextureSwizzleChannels::new(T::Red, T::Red, T::Red, T::One); - let (mut refused, mut kept, mut mapped) = (0, 0, 0); - for (stem, dev) in devices() { - let Ok(p) = kernel(&dev, &bc, "sample_level") else { - continue; - }; - let plan = |pf, swizzle| { - let mut t = texture(TextureType::Type2D, pf); - if let BoundTexture::Texture { facts, .. } = &mut t { - facts.swizzle = swizzle; - } - p.plan(&dev, &kernel_state(&[(0, t)], &[(0, black)], true).shape()) - }; - let border = |plan: &crate::bind::BindingPlan| match combined(plan).as_slice() { - [(_, SamplerSource::Slot { opaque_black, .. })] => *opaque_black, - other => panic!("{stem}: {other:?}"), - }; - for (pf, swizzle) in [ - (PixelFormat::RGBA8Unorm, rrr1), - (PixelFormat::R8Unorm, own), - (PixelFormat::R8Unorm, argb), - (PixelFormat::A8Unorm, own), - (PixelFormat::A8Unorm, argb), - ] { - match plan(pf, swizzle) { - Ok(plan) => assert_eq!(border(&plan), B::Transparent, "{stem} {pf:?} {swizzle:?}"), - // A profile that cannot sample the format refuses it for the format. - Err(BindError::Unsupported(u)) if u.feature == Feature::Format => {} - Err(e) => panic!("{stem} {pf:?} {swizzle:?}: {e}"), - } - } - let rgba = plan(PixelFormat::RGBA8Unorm, own).unwrap_or_else(|e| panic!("{stem}: {e}")); - assert_eq!(border(&rgba), B::Stated, "{stem}"); - let f = dev.profile().fields(); - let has = |feature| f.enabled.features.contains(&feature); - let exact = - has(VkFeature::BorderColorSwizzle) && has(VkFeature::BorderColorSwizzleFromImage); - match plan(PixelFormat::RGBA8Unorm, argb) { - Ok(plan) if exact => { - assert_eq!(border(&plan), B::Stated, "{stem}"); - kept += 1; - } - // `borderColorSwizzle` alone: a sampler made for the view's mapping. - Ok(plan) if has(VkFeature::BorderColorSwizzle) => { - assert_eq!( - border(&plan), - B::Mapped(argb.compose(vk::ComponentMapping::IDENTITY)), - "{stem}" - ); - mapped += 1; - } - Err(BindError::Unsupported(u)) if !has(VkFeature::BorderColorSwizzle) => { - assert_eq!(u.feature, Feature::SamplerBorderColor, "{stem}"); - refused += 1; - } - other => panic!("{stem} (exact {exact}): {other:?}"), - } - } - assert!( - kept > 0 && mapped > 0, - "kept {kept}, mapped {mapped}, refused {refused}" - ); -} - -/// A runtime-sampled 2D texture: the bound texture's view and the sampler slot; the declared -/// type's neutrals when unbound; a neutral and a diagnostic for a texture of another type or -/// numeric type; `SamplerState` from the sampler's coordinate mode; a min/max sampler needs -/// `samplerFilterMinmax`. The plan is total over every committed profile where the kernel -/// compiles. -#[test] -fn sampled_textures_and_runtime_samplers() { - let Some(bc) = fixture("sampling") else { - return; - }; - let tex = slot(Stage::Kernel, SlotClass::Texture, 0); - let smp = slot(Stage::Kernel, SlotClass::Sampler, 0); - let mut planned = 0; - for (stem, dev) in devices() { - let Ok(p) = kernel(&dev, &bc, "sample_level") else { - continue; - }; - let bound = kernel_state( - &[(0, texture(TextureType::Type2D, PixelFormat::RGBA8Unorm))], - &[(0, sampler(true, SamplerReductionMode::WeightedAverage))], - true, - ); - // Vulkan 1.2 requires `R8G8B8A8_UNORM` sampled images, so every profile's format - // tables map the bound format. - let plan = p - .plan(&dev, &bound.shape()) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - let c = combined(&plan); - assert_eq!(c.len(), 1, "{stem}"); - match c[0] { - (ImageSource::Texture { slot: s, view }, SamplerSource::Slot { slot: ss, .. }) => { - assert_eq!((s, ss), (tex, smp), "{stem}"); - assert_eq!(view.view_type, vk::ImageViewType::TYPE_2D, "{stem}"); - assert_eq!(view.format, vk::Format::R8G8B8A8_UNORM, "{stem}"); - assert_eq!(view.aspect, vk::ImageAspectFlags::COLOR, "{stem}"); - } - other => panic!("{stem}: {other:?}"), - } - assert!(plan.diagnostics.is_empty(), "{stem}"); - // The pixel-coordinate path is selected by specialization when the kernel declares it: - // the bound sampler's word masked by the fields the kernel reads. - let state = p - .stage - .specialization - .constants - .iter() - .find_map(|c| match c.key { - SpecKey::SamplerState { slot, fields } if slot == smp => Some((c.id, fields)), - _ => None, - }); - if let Some((id, fields)) = state { - assert_ne!(fields & SamplerWord::PIXEL_COORDINATES, 0, "{stem}"); - let pixel_sampler = sampler(false, SamplerReductionMode::WeightedAverage); - let pixel = kernel_state( - &[(0, texture(TextureType::Type2D, PixelFormat::RGBA8Unorm))], - &[(0, pixel_sampler)], - true, - ); - let value = |plan: &crate::bind::BindingPlan| { - let e = plan - .specialization - .entries - .iter() - .find(|e| e.constant_id == id) - .expect("SamplerState entry"); - let at = e.offset as usize; - let bytes = &plan.specialization.data[at..at + 4]; - u32::from_le_bytes(bytes.try_into().expect("a u32")) - }; - let normalized = sampler(true, SamplerReductionMode::WeightedAverage); - let keyed = |word: u32| word & fields; - assert_eq!( - value(&plan), - keyed(SamplerWord::of(&normalized.desc).0), - "{stem}" - ); - assert_eq!( - value(&p.plan(&dev, &pixel.shape()).expect("pixel")), - keyed(SamplerWord::of(&pixel_sampler.desc).0), - "{stem}" - ); - } - // Unbound: the neutral of the declared type and the neutral sampler. - let empty = kernel_state(&[], &[], true); - let plan = p.plan(&dev, &empty.shape()).expect("unbound"); - match combined(&plan)[0] { - ( - ImageSource::Neutral(NeutralResource::Image { view_type, .. }), - SamplerSource::Neutral(NeutralResource::Sampler { compare: false }), - ) => { - assert_eq!(view_type, vk::ImageViewType::TYPE_2D, "{stem}"); - } - other => panic!("{stem}: {other:?}"), - } - // Another texture type: a neutral and a diagnostic. - let s = kernel_state( - &[( - 0, - texture(TextureType::Type2DArray, PixelFormat::RGBA8Unorm), - )], - &[(0, sampler(true, SamplerReductionMode::WeightedAverage))], - true, - ); - let plan = p.plan(&dev, &s.shape()).expect("incompatible"); - assert!( - matches!(combined(&plan)[0].0, ImageSource::Neutral(_)), - "{stem}" - ); - assert!( - matches!( - plan.diagnostics[..], - [PlanDiagnostic::IncompatibleBinding { slot, .. }] if slot == tex - ), - "{stem}" - ); - // Another numeric class: the variant that samples it in its own class. - let s = kernel_state( - &[(0, texture(TextureType::Type2D, PixelFormat::RGBA8Uint))], - &[(0, sampler(true, SamplerReductionMode::WeightedAverage))], - true, - ); - let plan = p.plan(&dev, &s.shape()).expect("cross-class"); - assert!( - plan.diagnostics.is_empty(), - "{stem}: {:?}", - plan.diagnostics - ); - assert_eq!( - plan.variant.cross_class.get(&tex), - Some(&crate::pipeline::sym::SampledType::Uint), - "{stem}" - ); - // A min/max reduction reads the weighted average on every device. - let minmax = kernel_state( - &[(0, texture(TextureType::Type2D, PixelFormat::RGBA8Unorm))], - &[(0, sampler(true, SamplerReductionMode::Minimum))], - true, - ); - let r = p.plan(&dev, &minmax.shape()); - assert!(r.is_ok(), "{stem}: {r:?}"); - // LOD clamps are checked at plan time from the shape, with the verdict `sampler_desc` - // gives the bound descriptor; anisotropy plans on every device, its Vulkan sampler - // isotropic without `samplerAnisotropy`. - let with = |f: &dyn Fn(&mut SamplerDescriptor)| { - let mut s = sampler(true, SamplerReductionMode::WeightedAverage); - f(&mut s.desc); - let state = kernel_state( - &[(0, texture(TextureType::Type2D, PixelFormat::RGBA8Unorm))], - &[(0, s)], - true, - ); - (p.plan(&dev, &state.shape()), s.desc) - }; - let (r, desc) = with(&|d| d.max_anisotropy = 8); - assert!(r.is_ok(), "{stem}: {r:?}"); - let made = sampler_desc( - &dev, - &desc, - SamplerUse::default(), - crate::metal::sampler::OpaqueBlackBorder::Stated, - None, - ) - .unwrap_or_else(|e| panic!("{stem}: {e:?}")); - assert_eq!( - made.max_anisotropy.is_some(), - dev.profile().fields().images.sampler_anisotropy, - "{stem}" - ); - let (r, _) = with(&|d| { - d.lod_min_clamp = 4.0; - d.lod_max_clamp = 1.0; - }); - assert_eq!( - r, - Err(BindError::InvalidDescriptor( - DescriptorError::SamplerLodClamp - )), - "{stem}" - ); - // The dispatch instantiates without texture-specific data. - let d = Dispatch::Threadgroups { - groups: [1, 1, 1], - threads_per_group: [32, 1, 1], - }; - let plan = p.plan(&dev, &bound.shape()).expect("plan"); - plan.instantiate_dispatch(&bound, &d).expect("dispatch"); - planned += 1; - } - assert!(planned >= 3, "sample_level planned on {planned} profiles"); -} - -/// A texture of a format the table holds no representation of (`ASTC_4x2_HDR`, whose footprint no -/// Vulkan block has) is refused with the format's refusal only at a slot its -/// function uses: at a sampled slot the plan is `Unsupported(Format)`, and bound at an index the -/// function does not declare, or at an argument the function declares and never reads -/// (`reflection/textures`'s `unused_tex`, `air.arg_unused`), the plan is the one without it. -#[test] -fn a_texture_without_a_representation_is_refused_only_where_its_function_reads_it() { - let (Some(sampling), Some(textures)) = ( - fixture("sampling"), - match llvm_assemble( - &engine_dir() - .with_file_name("reflection") - .join("textures.ll"), - ) { - Ok(b) => Some(b), - Err(AssembleError::Missing(why)) => { - eprintln!("SKIPPED: {why}"); - None - } - Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected textures.ll: {why}"), - }, - ) else { - return; - }; - let unheld = || texture(TextureType::Type2D, PixelFormat::RGB8Unorm); - let rgba = || texture(TextureType::Type2D, PixelFormat::RGBA8Unorm); - let linear = || sampler(true, SamplerReductionMode::WeightedAverage); - let refused = |r: &Result| matches!(r, Err(BindError::Unsupported(u)) if u.feature == Feature::Format); - let (mut sampled, mut declared) = (0, 0); - for (stem, dev) in devices() { - if let Ok(p) = kernel(&dev, &sampling, "sample_level") { - let r = p.plan( - &dev, - &kernel_state(&[(0, unheld())], &[(0, linear())], true).shape(), - ); - assert!(refused(&r), "{stem}: a sampled unheld texture: {r:?}"); - let plain = p - .plan( - &dev, - &kernel_state(&[(0, rgba())], &[(0, linear())], true).shape(), - ) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - let beside = p - .plan( - &dev, - &kernel_state(&[(0, rgba()), (5, unheld())], &[(0, linear())], true).shape(), - ) - .unwrap_or_else(|e| { - panic!("{stem}: an unheld texture at an undeclared index: {e}") - }); - assert_eq!(beside.descriptors, plain.descriptors, "{stem}"); - assert!(beside.diagnostics.is_empty(), "{stem}"); - sampled += 1; - } - if let Ok(p) = kernel(&dev, &textures, "reflection_textures") { - let unused = p - .plan( - &dev, - &kernel_state(&[(16, unheld())], &[(0, linear())], true).shape(), - ) - .unwrap_or_else(|e| { - panic!("{stem}: an unheld texture at the unread argument: {e}") - }); - let none = p - .plan(&dev, &kernel_state(&[], &[(0, linear())], true).shape()) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - assert_eq!(unused.descriptors, none.descriptors, "{stem}"); - assert!(unused.diagnostics.is_empty(), "{stem}"); - let read = p.plan( - &dev, - &kernel_state(&[(3, unheld())], &[(0, linear())], true).shape(), - ); - assert!( - refused(&read), - "{stem}: an unheld texture at a sampled argument: {read:?}" - ); - declared += 1; - } - } - assert!( - sampled >= 3 && declared >= 1, - "sample_level planned on {sampled} profiles, reflection_textures on {declared}" - ); -} - -/// A swizzled texture buffer: at the slot `texel_buffers` reads, the plan binds it and specializes -/// the slot's `TextureSwizzle` to its swizzle's word (the identity's for an unswizzled one); at the -/// slot it only writes, which reads no texel to swizzle, it binds with no such constant (Metal -/// makes no swizzled texture a function writes, so only a misuse binds one there); and at the slot -/// `unk_size_queries` only queries it binds too. -#[test] -fn a_swizzled_texel_buffer_specializes_the_slot_that_reads_it() { - use crate::metal::{TextureSwizzle as S, TextureSwizzleChannels as C}; - let Some(bc) = fixture("texture_ops") else { - return; - }; - let bgr1 = C::new(S::Blue, S::Green, S::Red, S::One); - let mut planned = 0; - let mut queried = 0; - for (stem, dev) in devices() { - let Ok(p) = kernel(&dev, &bc, "texel_buffers") else { - continue; - }; - let tb = |offset, swizzle| BoundTexture::Buffer { - pixel_format: PixelFormat::RGBA32Float, - offset, - length: 1024, - bytes_per_row: 1024, - resource_id: None, - swizzle, - parts: 1, - }; - let read = slot(Stage::Kernel, SlotClass::Texture, 0); - let id = p - .stage - .specialization - .constants - .iter() - .find_map(|c| (c.key == SpecKey::TextureSwizzle(read)).then_some(c.id)) - .unwrap_or_else(|| panic!("{stem}: no TextureSwizzle constant")); - let word = |plan: &BindingPlan| { - let e = plan - .specialization - .entries - .iter() - .find(|e| e.constant_id == id) - .expect("TextureSwizzle entry"); - let at = e.offset as usize; - u32::from_le_bytes( - plan.specialization.data[at..at + 4] - .try_into() - .expect("a u32"), - ) - }; - for swizzle in [C::DEFAULT, bgr1] { - let s = kernel_state(&[(0, tb(0, swizzle)), (1, tb(256, C::DEFAULT))], &[], false); - let plan = p - .plan(&dev, &s.shape()) - .unwrap_or_else(|e| panic!("{stem}: {swizzle:?} {e}")); - assert_eq!(word(&plan), swizzle.word(), "{stem}"); - } - let written = kernel_state(&[(0, tb(0, C::DEFAULT)), (1, tb(256, bgr1))], &[], false); - let plan = p - .plan(&dev, &written.shape()) - .unwrap_or_else(|e| panic!("{stem}: written {e}")); - assert_eq!(word(&plan), C::DEFAULT.word(), "{stem}"); - let unread = slot(Stage::Kernel, SlotClass::Texture, 1); - assert!( - !p.stage - .specialization - .constants - .iter() - .any(|c| c.key == SpecKey::TextureSwizzle(unread)), - "{stem}" - ); - if let Some(queries) = fixture("unk_size_queries") { - if let Ok(q) = kernel(&dev, &queries, "unk_size_queries") { - let s = kernel_state(&[(1, tb(0, bgr1))], &[], false); - q.plan(&dev, &s.shape()) - .unwrap_or_else(|e| panic!("{stem}: queried {e}")); - queried += 1; - } - } - planned += 1; - } - assert!( - planned > 0 && queried > 0, - "{planned} planned, {queried} queried" - ); -} - -/// A read cube is viewed as the 2D array it is declared as (`ImageViewShape`); a bound texture -/// buffer gets its view format and its range; an unaligned texture-buffer offset is refused. -#[test] -fn cube_views_and_texel_buffers() { - let Some(bc) = fixture("texture_ops") else { - return; - }; - let mut cubes = 0; - let mut texels = 0; - for (stem, dev) in devices() { - if let Ok(p) = kernel(&dev, &bc, "cube_faces") { - let s = kernel_state( - &[ - (0, texture(TextureType::Cube, PixelFormat::RGBA8Unorm)), - (1, texture(TextureType::CubeArray, PixelFormat::RGBA8Unorm)), - ], - &[], - true, - ); - // Vulkan 1.2 requires `R8G8B8A8_UNORM` sampled images. - let plan = p - .plan(&dev, &s.shape()) - .unwrap_or_else(|e| panic!("{stem}: cube {e}")); - let views: Vec = plan - .descriptors - .iter() - .filter_map(|d| match d.source { - WriteSource::Texture { view, .. } => Some(view.view_type), - _ => None, - }) - .collect(); - assert_eq!( - views, - vec![vk::ImageViewType::TYPE_2D_ARRAY; 2], - "{stem}: {plan:?}" - ); - cubes += 1; - } - if let Ok(p) = kernel(&dev, &bc, "texel_buffers") { - let tb = |offset| BoundTexture::Buffer { - pixel_format: PixelFormat::RGBA32Float, - offset, - length: 1024, - bytes_per_row: 1024, - resource_id: None, - swizzle: crate::metal::TextureSwizzleChannels::DEFAULT, - parts: 1, - }; - let s = kernel_state(&[(0, tb(0)), (1, tb(256))], &[], false); - // Vulkan 1.2 requires `R32G32B32A32_SFLOAT` uniform texel buffers. - let plan = p - .plan(&dev, &s.shape()) - .unwrap_or_else(|e| panic!("{stem}: texel {e}")); - let formats: Vec = plan - .descriptors - .iter() - .filter_map(|d| match d.source { - WriteSource::TexelBuffer { format, .. } => Some(format), - _ => None, - }) - .collect(); - assert_eq!(formats, vec![vk::Format::R32G32B32A32_SFLOAT; 2], "{stem}"); - let d = Dispatch::Threadgroups { - groups: [1, 1, 1], - threads_per_group: [1, 1, 1], - }; - let cmds = plan.instantiate_dispatch(&s, &d).expect("dispatch"); - let ranges: Vec<(u64, u64)> = cmds - .descriptor_ranges - .iter() - .map(|r| (r.range.offset, r.range.range)) - .collect(); - assert_eq!(ranges, vec![(0, 1024), (256, 1024)], "{stem}"); - // The view spans whole texel blocks (16 bytes of `RGBA32Float`), and its element - // count is checked exactly against `maxTexelBufferElements`. - let sized = |length| BoundTexture::Buffer { - pixel_format: PixelFormat::RGBA32Float, - offset: 0, - length, - bytes_per_row: length, - resource_id: None, - swizzle: crate::metal::TextureSwizzleChannels::DEFAULT, - parts: 1, - }; - let ragged = kernel_state(&[(0, sized(1030)), (1, tb(256))], &[], false); - let cmds = plan.instantiate_dispatch(&ragged, &d).expect("ragged"); - assert_eq!(cmds.descriptor_ranges[0].range.range, 1024, "{stem}"); - let limit = u64::from(dev.profile().fields().limits.max_texel_buffer_elements); - let full = kernel_state(&[(0, sized(limit * 16)), (1, tb(256))], &[], false); - assert!(plan.instantiate_dispatch(&full, &d).is_ok(), "{stem}"); - let over = kernel_state(&[(0, sized((limit + 1) * 16)), (1, tb(256))], &[], false); - assert_eq!( - plan.instantiate_dispatch(&over, &d), - Err(BindError::TexelBufferTooLarge { - slot: slot(Stage::Kernel, SlotClass::Texture, 0), - elements: limit + 1, - limit - }), - "{stem}" - ); - let a = dev - .profile() - .fields() - .limits - .min_texel_buffer_offset_alignment; - if a > 1 { - let unaligned = kernel_state(&[(0, tb(a / 2)), (1, tb(256))], &[], false); - assert!( - matches!( - plan.instantiate_dispatch(&unaligned, &d), - Err(BindError::Unsupported(_)) - ), - "{stem}" - ); - } - texels += 1; - } - } - assert!( - cubes >= 3 && texels >= 3, - "cubes {cubes}, texel buffers {texels}" - ); -} - -/// A written storage texture asks for the storage variant unless the formatless default -/// declaration serves its choice; the view is the alias format where the choice aliases (bgra8 -/// without storage), and the bound format otherwise. -#[test] -fn storage_textures_choose_their_variant() { - let Some(bc) = fixture("storage_texture_write") else { - return; - }; - let dst = slot(Stage::Kernel, SlotClass::Texture, 0); - let mut variants = 0; - for (stem, dev) in devices() { - let Ok(p) = kernel(&dev, &bc, "storage_texture_write") else { - continue; - }; - for (pf, format) in [ - (PixelFormat::RGBA8Unorm, vk::Format::R8G8B8A8_UNORM), - (PixelFormat::BGRA8Unorm, vk::Format::B8G8R8A8_UNORM), - ] { - let s = kernel_state(&[(0, texture(TextureType::Type2D, pf))], &[], false); - let plan = match p.plan(&dev, &s.shape()) { - Ok(plan) => plan, - Err(BindError::Unsupported(_)) => continue, - Err(e) => panic!("{stem}: {e}"), - }; - let view = plan - .descriptors - .iter() - .find_map(|d| match d.source { - WriteSource::Texture { slot, view } if slot == dst => Some(view), - _ => None, - }) - .unwrap_or_else(|| panic!("{stem}: no storage write")); - assert_eq!(view.layout, vk::ImageLayout::GENERAL); - match plan.variant.storage_images.get(&dst) { - None => assert_eq!(view.format, format, "{stem}"), - Some(choice) => { - variants += 1; - let expected = if choice.alias.is_some() { - choice.vk_format - } else { - format - }; - assert_eq!(view.format, expected, "{stem}: {choice:?}"); - } - } - } - } - eprintln!("storage variants planned: {variants}"); -} - -/// A written texture buffer is declared without a format only where the bound format's buffer -/// features state `STORAGE_WRITE_WITHOUT_FORMAT` (`VUID-vkCmdDispatch-OpTypeImage-07029`; nothing -/// implies the bit for a buffer). Elsewhere the plan names the declared format as the slot's -/// storage variant, bound or not (an unbound slot reads and writes its `R32` neutral), and the -/// variant plans to itself. -#[test] -fn a_written_texel_buffer_follows_its_buffer_features() { - use crate::device::requirements::FormatUsage; - use crate::pipeline::StorageImageClass; - let Some(bc) = fixture("ob1_texel_buffer") else { - return; - }; - let entry = "ob1_texel_buffer"; - let dst = slot(Stage::Kernel, SlotClass::Texture, 1); - let r32 = BoundTexture::Buffer { - pixel_format: PixelFormat::R32Uint, - offset: 0, - length: 16, - bytes_per_row: 16, - resource_id: None, - swizzle: crate::metal::TextureSwizzleChannels::DEFAULT, - parts: 1, - }; - let state = |textures: &[(u32, BoundTexture)]| { - let mut s = kernel_state(textures, &[], true); - if let Some(t) = s.stages.get_mut(&Stage::Kernel) { - t.buffers.insert(1, buffer(4096, 0, None)); - } - s - }; - let mut declared = BTreeSet::new(); - let mut formatless = BTreeSet::new(); - for (stem, dev) in devices() { - let Ok(p) = kernel(&dev, &bc, entry) else { - continue; - }; - let profile = dev.profile(); - let without = profile.fields().images.storage_write_without_format - && profile.supports_format( - vk::Format::R32_UINT, - FormatUsage::StorageTexelBufferWriteWithoutFormat, - ); - for (what, s) in [ - ("bound", state(&[(0, r32), (1, r32)])), - ("unbound", state(&[(0, r32)])), - ] { - let plan = p - .plan(&dev, &s.shape()) - .unwrap_or_else(|e| panic!("{stem} {what}: {e}")); - let Some(choice) = plan.variant.storage_images.get(&dst) else { - assert!(without, "{stem} {what}: no variant"); - formatless.insert(stem.clone()); - continue; - }; - assert!(!without, "{stem} {what}: {choice:?}"); - assert_eq!(choice.vk_format, vk::Format::R32_UINT, "{stem} {what}"); - assert_eq!(choice.class, StorageImageClass::Identity, "{stem} {what}"); - assert_eq!(choice.alias, None, "{stem} {what}"); - declared.insert(stem.clone()); - let lib = Library::from_air(&bc).expect("library"); - let f = lib.function(entry).expect("entry"); - let compiled = dev - .compile_function( - &FunctionDescriptor::new(f), - &plan.variant.lowering_inputs(Stage::Kernel), - &Budget::standard(), - ) - .unwrap_or_else(|e| panic!("{stem} {what}: {e}")); - let variant = dev - .compile_compute_pipeline( - &ComputePipelineDescriptor::new(StageSource::Compiled(compiled)), - &Budget::standard(), - ) - .unwrap_or_else(|e| panic!("{stem} {what}: {e}")); - let again = variant - .plan(&dev, &s.shape()) - .unwrap_or_else(|e| panic!("{stem} {what}: {e}")); - assert_eq!(again.variant, plan.variant, "{stem} {what}: a fixed point"); - } - } - // SwiftShader has `shaderStorageImageWriteWithoutFormat`, but its `R32_UINT` buffer features - // lack the bit; lavapipe's state it. - assert!(declared.contains("runtime-floor"), "{declared:?}"); - assert!(formatless.contains("lavapipe"), "{formatless:?}"); -} - -/// A texture buffer of more texels than one view holds binds through views of its parts -/// (`bind::texel_parts`) where its slot's function reads, writes or asks the width of it, on a -/// device that indexes texel buffer arrays by a `NonUniform` value: the plan asks for the parts -/// variant (`VariantKey::texel_buffer_parts`), whose pipeline declares the slot an array of its -/// parts and plans to itself, one write per part, the range of each part at its element. A -/// texture buffer one view holds asks for no parts: the pipeline the plan binds keeps its compile -/// key and its layout's one texel buffer at the slot. -#[test] -fn texture_buffers_past_the_limit_bind_their_parts() { - use crate::pipeline::facts::RuntimeFact; - let Some(bc) = fixture("ob1_texel_buffer") else { - return; - }; - let entry = "ob1_texel_buffer"; - let (src, dst) = ( - slot(Stage::Kernel, SlotClass::Texture, 0), - slot(Stage::Kernel, SlotClass::Texture, 1), - ); - let tb = |texels: u64, parts: u32| BoundTexture::Buffer { - pixel_format: PixelFormat::R32Uint, - offset: 0, - length: texels * 4, - bytes_per_row: texels * 4, - resource_id: None, - swizzle: crate::metal::TextureSwizzleChannels::DEFAULT, - parts, - }; - let state = |a: BoundTexture, b: BoundTexture| { - let mut s = kernel_state(&[(0, a), (1, b)], &[], true); - if let Some(t) = s.stages.get_mut(&Stage::Kernel) { - t.buffers.insert(1, buffer(4096, 0, None)); - } - s - }; - let d = Dispatch::Threadgroups { - groups: [1, 1, 1], - threads_per_group: [8, 1, 1], - }; - let counts = |p: &ComputePipeline| -> Vec<(u32, vk::DescriptorType)> { - let set = &p.layout.sets[0]; - [src, dst] - .iter() - .map(|&at| { - let b = set - .bindings - .iter() - .find(|b| b.source == BindingSource::Texture(at)); - let b = b.expect("the slot's binding"); - (b.count, b.ty) - }) - .collect() - }; - let mut parted = BTreeSet::new(); - for (stem, dev) in devices() { - let Ok(p) = kernel(&dev, &bc, entry) else { - continue; - }; - let limits = dev.profile().fields().limits; - let limit = u64::from(limits.max_texel_buffer_elements); - let part = crate::bind::part_texels(&limits); - let indexed = dev.profile().fields().descriptors; - let stated = |p: &ComputePipeline, at| { - p.dependencies - .iter() - .any(|d| d.fact == RuntimeFact::TexelBufferParts { slot: at }) - }; - assert_eq!( - stated(&p, src), - indexed.non_uniform_uniform_texel_buffer, - "{stem}" - ); - assert_eq!( - stated(&p, dst), - indexed.non_uniform_storage_texel_buffer, - "{stem}" - ); - // One view: no parts; the pipeline's bindings hold one texel buffer each. - let one = state(tb(limit, 1), tb(64, 1)); - let plan = p - .plan(&dev, &one.shape()) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - assert!(plan.variant.texel_buffer_parts.is_empty(), "{stem}"); - let single = vec![ - (1, vk::DescriptorType::UNIFORM_TEXEL_BUFFER), - (1, vk::DescriptorType::STORAGE_TEXEL_BUFFER), - ]; - assert_eq!(counts(&p), single, "{stem}"); - if plan.variant.is_empty() { - assert!(plan.instantiate_dispatch(&one, &d).is_ok(), "{stem}"); - } - if !stated(&p, src) || !stated(&p, dst) || part == 0 { - continue; - } - // Past the limit: the source one texel past it (two parts on every committed profile), - // the destination in three. - let src_parts = 2; - let past = state(tb(limit + 1, src_parts), tb(2 * part + 7, 3)); - let plan = p - .plan(&dev, &past.shape()) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - let want = std::collections::BTreeMap::from([(src, 2), (dst, 3)]); - assert_eq!(plan.variant.texel_buffer_parts, want, "{stem}"); - let lib = Library::from_air(&bc).expect("library"); - let f = lib.function(entry).expect("entry"); - let compiled = dev - .compile_function( - &FunctionDescriptor::new(f), - &plan.variant.lowering_inputs(Stage::Kernel), - &Budget::standard(), - ) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - let variant = dev - .compile_compute_pipeline( - &ComputePipelineDescriptor::new(StageSource::Compiled(compiled)), - &Budget::standard(), - ) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - assert_ne!(variant.key, p.key, "{stem}: a pipeline of its own"); - let arrays = vec![ - (2, vk::DescriptorType::UNIFORM_TEXEL_BUFFER), - (3, vk::DescriptorType::STORAGE_TEXEL_BUFFER), - ]; - assert_eq!(counts(&variant), arrays, "{stem}"); - let again = variant - .plan(&dev, &past.shape()) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - assert_eq!(again.variant, plan.variant, "{stem}: a fixed point"); - let elements: Vec<(SlotRef, u32)> = again - .descriptors - .iter() - .filter_map(|w| match w.source { - WriteSource::TexelBuffer { slot, .. } => Some((slot, w.array_element)), - _ => None, - }) - .collect(); - assert_eq!( - elements, - vec![(src, 0), (src, 1), (dst, 0), (dst, 1), (dst, 2)], - "{stem}" - ); - let cmds = again - .instantiate_dispatch(&past, &d) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - let texel_bindings: BTreeSet = (variant.layout.sets[0].bindings.iter()) - .filter(|b| matches!(b.source, BindingSource::Texture(_))) - .map(|b| b.binding) - .collect(); - let ranges: Vec<(u32, u64, u64)> = cmds - .descriptor_ranges - .iter() - .filter(|r| r.set == 0 && texel_bindings.contains(&r.binding)) - .map(|r| (r.element, r.range.offset, r.range.range)) - .collect(); - let tail = (limit + 1 - part) * 4; - assert_eq!( - ranges, - vec![ - (0, 0, part * 4), - (1, part * 4, tail), - (0, 0, part * 4), - (1, part * 4, part * 4), - (2, 2 * part * 4, 28), - ], - "{stem}" - ); - parted.insert(stem.clone()); - } - for stem in ["lavapipe", "moltenvk-m3"] { - assert!(parted.contains(stem), "{stem}: {parted:?}"); - } -} - -/// The value `plan` specializes constant `id` to (a `bool`'s low byte). -fn spec_value(plan: &BindingPlan, id: u32) -> u8 { - let e = plan - .specialization - .entries - .iter() - .find(|e| e.constant_id == id) - .expect("specialized"); - plan.specialization.data[e.offset as usize] -} - -/// A read the shader checks whose alpha the function observes takes its out-of-bounds alpha from -/// `OutOfBoundsAlpha`, which the plan sets from the bound pixel format: 1 for a format without -/// alpha, 0 for one with it, and 0 for an unbound slot or one bound to a placeholder format (the -/// slot reads its neutral, which reads zero). A compute texel buffer always declares it (the shader -/// checks every texel buffer read), a fragment texture where `robustImageAccess2` is. -#[test] -fn out_of_bounds_alpha_follows_the_bound_format() { - let (Some(ops), Some(io), Some(tail)) = ( - fixture("texture_ops"), - fixture("stage_io"), - fixture("sampling_tail"), - ) else { - return; - }; - let src = slot(Stage::Kernel, SlotClass::Texture, 0); - let frag = slot(Stage::Fragment, SlotClass::Texture, 0); - let tb = |pixel_format, offset| BoundTexture::Buffer { - pixel_format, - offset, - length: 1024, - bytes_per_row: 1024, - resource_id: None, - swizzle: crate::metal::TextureSwizzleChannels::DEFAULT, - parts: 1, - }; - let (mut kernels, mut fragments) = (0, 0); - // Every committed profile has `robustImageAccess2`; the specialization is on a device without - // it (below the runtime's floor). - let without = { - let path = Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../metal2vulkan-validation/profiles/runtime-floor.json"); - let text = std::fs::read_to_string(path).expect("profile"); - let mut desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); - desc.features - .remove(&crate::device::requirements::VkFeature::RobustImageAccess2); - Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device") - }; - let mut all = devices(); - all.push(("runtime-floor without robustImageAccess2".into(), without)); - for (stem, dev) in all { - let f = dev.profile().fields(); - let Ok(p) = kernel(&dev, &ops, "texel_buffers") else { - continue; - }; - let c = p - .stage - .specialization - .constants - .iter() - .find(|c| c.key == SpecKey::OutOfBoundsAlpha(src)); - assert!(c.is_some(), "{stem}"); - if let Some(c) = c { - // Vulkan 1.2 requires `R32_SFLOAT` and `R32G32B32A32_SFLOAT` uniform texel buffers. - for (pf, want) in [(PixelFormat::RGBA32Float, 0), (PixelFormat::R32Float, 1)] { - let s = kernel_state( - &[(0, tb(pf, 0)), (1, tb(PixelFormat::RGBA32Float, 256))], - &[], - false, - ); - let plan = p - .plan(&dev, &s.shape()) - .unwrap_or_else(|e| panic!("{stem}: {pf:?}: {e}")); - assert_eq!(spec_value(&plan, c.id), want, "{stem}: {pf:?}"); - } - let unbound = kernel_state(&[(1, tb(PixelFormat::RGBA32Float, 256))], &[], false); - let plan = p.plan(&dev, &unbound.shape()).expect("unbound"); - assert_eq!(spec_value(&plan, c.id), 0, "{stem}: unbound"); - let placeholder = kernel_state( - &[ - (0, tb(PixelFormat::Invalid, 0)), - (1, tb(PixelFormat::RGBA32Float, 256)), - ], - &[], - false, - ); - let plan = p.plan(&dev, &placeholder.shape()).expect("placeholder"); - assert_eq!(spec_value(&plan, c.id), 0, "{stem}: placeholder"); - kernels += 1; - } - let vertex = Library::from_air(&io).expect("library"); - let fragment = Library::from_air(&tail).expect("library"); - let mut d = RenderPipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new( - vertex.function("stage_io_vertex_position").expect("vertex"), - ))); - d.fragment = Some(StageSource::Function(FunctionDescriptor::new( - fragment - .function("fragment_read_across_blocks") - .expect("fragment"), - ))); - d.color_attachments[0] = Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm)); - let Ok(r) = dev.compile_render_pipeline(&d, &Budget::standard()) else { - continue; - }; - let c = r - .stages - .iter() - .flat_map(|m| m.specialization.constants.iter()) - .find(|c| c.key == SpecKey::OutOfBoundsAlpha(frag)) - .copied(); - assert_eq!(c.is_some(), !f.images.robust_image_access2, "{stem}"); - let Some(c) = c else { - continue; - }; - // Vulkan 1.2 requires `R8_UNORM` and `R8G8B8A8_UNORM` sampled images. - for (pf, want) in [(PixelFormat::RGBA8Unorm, 0), (PixelFormat::R8Unorm, 1)] { - let mut t = StageTable::default(); - t.textures.insert(0, texture(TextureType::Type2D, pf)); - t.buffers.insert(0, buffer(256, 0, None)); - let mut s = BindState::default(); - s.stages.insert(Stage::Fragment, t); - let plan = r - .plan(&dev, &s.shape()) - .unwrap_or_else(|e| panic!("{stem}: {pf:?}: {e}")); - assert_eq!(spec_value(&plan, c.id), want, "{stem}: fragment {pf:?}"); - } - fragments += 1; - } - assert!( - kernels > 0 && fragments > 0, - "kernels {kernels}, fragments {fragments}" - ); -} - -/// `a2_sparse_status` observes the residency of a sample and a gather of texture 0 through a -/// nearest, clamp-to-edge constexpr sampler, and of a read of texture 1. Each slot states -/// `RuntimeFact::SparseTexture`, its `SparseTexture` specialization, which the plan sets from the -/// bound texture's `sparse` (`MTLTexture.isSparse`). Slot 1's read has the tile-map arm on every -/// device, and so has slot 0 where the device has no `shaderResourceResidency`, its sample and -/// gather through Metal's footprint: a `ResourceKind::TileMap` binding the plan writes as the -/// slot's `WriteSource::TileMap` (read by the kernel) for a sparse texture and as the zero buffer -/// otherwise. Where the device has residency, slot 0's sample and gather are the device's sparse -/// accesses (the sparse arm), with no tile map. -#[test] -fn a_sparse_texture_is_answered_from_its_tile_map_where_the_device_has_no_residency() { - use crate::device::requirements::VkFeature; - use crate::pipeline::facts::RuntimeFact; - let Some(bc) = fixture("a2_sparse_status") else { - return; - }; - let bound = |sparse: bool| { - let mut t = texture(TextureType::Type2D, PixelFormat::RGBA32Float); - if let BoundTexture::Texture { facts, .. } = &mut t { - facts.sparse = sparse; - } - t - }; - let state = |s0: bool, s1: bool| kernel_state(&[(0, bound(s0)), (1, bound(s1))], &[], true); - let (mut with, mut without) = (0, 0); - for (stem, dev) in devices() { - let p = kernel(&dev, &bc, "a2_sparse_status").unwrap_or_else(|e| panic!("{stem}: {e}")); - let residency = dev - .profile() - .fields() - .enabled - .features - .contains(&VkFeature::ShaderResourceResidency); - let slots = [0, 1].map(|i| slot(Stage::Kernel, SlotClass::Texture, i)); - for (s, sampled) in slots.into_iter().zip([true, false]) { - let fact = RuntimeFact::SparseTexture { - slot: s, - sparse_arm: sampled && residency, - tile_map: !(sampled && residency), - }; - assert!( - p.dependencies.iter().any(|d| d.fact == fact), - "{stem}: {fact:?}" - ); - } - let ids = slots.map(|s| { - p.stage - .specialization - .constants - .iter() - .find(|c| c.key == SpecKey::SparseTexture(s)) - .map(|c| c.id) - }); - let [Some(a), Some(b)] = ids else { - panic!("{stem}: no SparseTexture constants: {ids:?}"); - }; - let tile_maps = |plan: &BindingPlan| { - plan.descriptors - .iter() - .filter_map(|d| match &d.source { - WriteSource::TileMap { slot } => Some(*slot), - _ => None, - }) - .collect::>() - }; - let plain = p - .plan(&dev, &state(false, false).shape()) - .unwrap_or_else(|e| panic!("{stem}: not sparse: {e}")); - assert_eq!(tile_maps(&plain), [], "{stem}"); - assert_eq!( - (spec_value(&plain, a), spec_value(&plain, b)), - (0, 0), - "{stem}" - ); - let plan = p - .plan(&dev, &state(true, false).shape()) - .unwrap_or_else(|e| panic!("{stem}: sparse slot 0: {e}")); - assert_eq!( - (spec_value(&plan, a), spec_value(&plan, b)), - (1, 0), - "{stem}" - ); - // Each sparse slot's tile map bound and read. - let mapped: &[SlotRef] = match residency { - true => &slots[1..], - false => &slots, - }; - assert_eq!(tile_maps(&plan), mapped[..mapped.len() - 1], "{stem}"); - let both = p - .plan(&dev, &state(true, true).shape()) - .unwrap_or_else(|e| panic!("{stem}: sparse slots: {e}")); - assert_eq!(tile_maps(&both), mapped, "{stem}"); - for &s in mapped { - assert!( - both.uses - .iter() - .any(|u| u.resource == UseTarget::TileMap(s)), - "{stem}: no tile-map use of {s:?}" - ); - } - if residency { - with += 1; - } else { - without += 1; - } - } - assert!(with > 0 && without > 0, "with {with}, without {without}"); -} - -/// `OpImageSparseSampleExplicitLod`, `OpImageSparseFetch`, and `OpImageSparseGather`. -const SPARSE_SAMPLE_EXPLICIT_LOD: u32 = 306; -const SPARSE_FETCH: u32 = 313; -const SPARSE_GATHER: u32 = 314; - -/// The opcodes of a SPIR-V module. -fn opcodes(words: &[u32]) -> BTreeSet { - let mut out = BTreeSet::new(); - let mut i = 5; - while let Some(&w) = words.get(i) { - out.insert(w & 0xFFFF); - i += usize::try_from(w >> 16).unwrap_or(1).max(1); - } - out -} - -/// `sps2_residency_probes` observes the residency of nearest and linear samples and a gather -/// through clamp-to-zero constexpr samplers at level 0, every one inside Metal's measured footprint -/// rule. Where the device has no `shaderResourceResidency` the module answers them from the texels -/// Metal counts, through the tile map of both slots, which bind a sparse texture: no sparse -/// access, and no note. Where it has, each is the device's sparse access, its residency the -/// device's, recorded as `PrecisionNote::SparseResidency`, and the sampled slot has no tile map; -/// the slot read alone keeps its own. -#[test] -fn a_sample_with_metals_footprint_is_answered_where_the_device_has_no_residency() { - use crate::device::requirements::VkFeature; - use crate::pipeline::artifact::PrecisionNote; - use crate::pipeline::facts::RuntimeFact; - let Some(bc) = fixture("sps2_residency_probes") else { - return; - }; - let bound = |sparse: bool| { - let mut t = texture(TextureType::Type2D, PixelFormat::RGBA8Unorm); - if let BoundTexture::Texture { facts, .. } = &mut t { - facts.sparse = sparse; - } - t - }; - let sparse = kernel_state(&[(0, bound(true)), (1, bound(true))], &[], true); - let mut seen = [0; 2]; - for (stem, dev) in devices() { - let p = - kernel(&dev, &bc, "sps2_residency_probes").unwrap_or_else(|e| panic!("{stem}: {e}")); - let residency = dev - .profile() - .fields() - .enabled - .features - .contains(&VkFeature::ShaderResourceResidency); - // Slot 1 is read alone, from its tile map on every device. - for (i, sampled) in [(0, true), (1, false)] { - let fact = RuntimeFact::SparseTexture { - slot: slot(Stage::Kernel, SlotClass::Texture, i), - sparse_arm: sampled && residency, - tile_map: !(sampled && residency), - }; - assert!( - p.dependencies.iter().any(|d| d.fact == fact), - "{stem}: {fact:?}" - ); - } - let ops = opcodes(&p.stage.spirv); - assert_eq!( - ops.contains(&SPARSE_SAMPLE_EXPLICIT_LOD), - residency, - "{stem}" - ); - assert_eq!(ops.contains(&SPARSE_GATHER), residency, "{stem}"); - // The sampled slot's read through its sparse arm: one texel's residency, exact. - assert_eq!(ops.contains(&SPARSE_FETCH), residency, "{stem}"); - assert_eq!( - p.stage - .precision_notes - .contains(&PrecisionNote::SparseResidency), - residency, - "{stem}" - ); - p.plan(&dev, &sparse.shape()) - .unwrap_or_else(|e| panic!("{stem}: sparse: {e}")); - seen[usize::from(residency)] += 1; - } - assert!(seen[0] > 0 && seen[1] > 0, "{seen:?}"); -} - -/// Where the profile's sparse textures are sparse images, `sps2_residency_probes`' sampled slot -/// specializes on `ConstantLanes`, which the plan sets from the bound texture: a sparse `R32Float` -/// texture's missing green and blue (0) and alpha (1), through its swizzle; 0 for a texture that is -/// not sparse, and for one whose format holds every channel. Elsewhere the slot declares no such -/// constant. -#[test] -fn a_sparse_texture_s_constant_lanes_are_its_format_s_through_its_swizzle() { - use crate::device::requirements::VkFeature; - use metal::{TextureSwizzle as T, TextureSwizzleChannels as S}; - let Some(bc) = fixture("sps2_residency_probes") else { - return; - }; - let bound = |pf: PixelFormat, sparse: bool, swizzle: S| { - let mut t = texture(TextureType::Type2D, pf); - if let BoundTexture::Texture { facts, .. } = &mut t { - facts.sparse = sparse; - facts.swizzle = swizzle; - } - t - }; - let cases = [ - ( - PixelFormat::R32Float, - true, - S::DEFAULT, - 0b1110 | 0b1000 << 4, - ), - (PixelFormat::R32Float, false, S::DEFAULT, 0), - (PixelFormat::RGBA8Unorm, true, S::DEFAULT, 0), - ( - PixelFormat::R32Float, - true, - S::new(T::Alpha, T::Red, T::One, T::Zero), - 0b1101 | 0b0101 << 4, - ), - ]; - let mut seen = [0; 2]; - for (stem, dev) in devices() { - let p = - kernel(&dev, &bc, "sps2_residency_probes").unwrap_or_else(|e| panic!("{stem}: {e}")); - let residency = dev - .profile() - .fields() - .enabled - .features - .contains(&VkFeature::ShaderResourceResidency); - seen[usize::from(residency)] += 1; - let s0 = slot(Stage::Kernel, SlotClass::Texture, 0); - let id = p - .stage - .specialization - .constants - .iter() - .find(|c| c.key == SpecKey::ConstantLanes(s0)) - .map(|c| c.id); - assert_eq!(id.is_some(), residency, "{stem}"); - let Some(id) = id else { - continue; - }; - for (pf, sparse, swizzle, want) in cases { - let state = kernel_state( - &[ - (0, bound(pf, sparse, swizzle)), - (1, bound(PixelFormat::R32Float, sparse, S::DEFAULT)), - ], - &[], - true, - ); - let plan = p - .plan(&dev, &state.shape()) - .unwrap_or_else(|e| panic!("{stem}: {pf:?} {swizzle:?}: {e}")); - assert_eq!( - spec_value(&plan, id), - want, - "{stem}: {pf:?} sparse {sparse} {swizzle:?}" - ); - } - } - assert!(seen[0] > 0 && seen[1] > 0, "{seen:?}"); -} - -/// Metal drops every write a function makes to a sparse texture. `spse_write_probes` writes the -/// texture whose residency it reads, so its slot states `SparseTextureWrites` and a residency arm -/// (the tile map on every device), and binds a texture that is sparse and one that is not on every -/// device. -#[test] -fn a_written_sparse_texture_binds() { - use crate::pipeline::facts::RuntimeFact; - let Some(bc) = fixture("spse_write_probes") else { - return; - }; - let at = slot(Stage::Kernel, SlotClass::Texture, 0); - let bound = |sparse: bool| { - let mut t = texture(TextureType::Type2D, PixelFormat::R32Float); - if let BoundTexture::Texture { facts, .. } = &mut t { - facts.sparse = sparse; - } - kernel_state(&[(0, t)], &[], true) - }; - let mut seen = 0; - for (stem, dev) in devices() { - let p = match kernel(&dev, &bc, "spse_write_probes") { - Ok(p) => p, - // A storage texture without a format the profile writes. - Err(Error::NeedsInput(_)) => continue, - Err(e) => panic!("{stem}: {e}"), - }; - for fact in [ - RuntimeFact::SparseTextureWrites { - slot: at, - atomic: false, - }, - RuntimeFact::SparseTexture { - slot: at, - sparse_arm: false, - tile_map: true, - }, - ] { - assert!( - p.dependencies.iter().any(|d| d.fact == fact), - "{stem}: {fact:?}" - ); - } - for sparse in [false, true] { - p.plan(&dev, &bound(sparse).shape()) - .unwrap_or_else(|e| panic!("{stem}: sparse {sparse}: {e}")); - } - seen += 1; - } - assert!(seen > 0); -} - -/// A 4:2:2 texture (`GBGR422`, `BGRG422`) at a storage slot its function only writes -/// (`storage_texture_write`) binds the slot's neutral with an `IncompatibleBinding` note: plain -/// Metal completes the writes and stores nothing. At a slot that samples it (`sampling`'s -/// `sample_level`) the plan samples the decoded twin's view of Metal's texels, `R8G8B8A8_UNORM` -/// (`FormatEmulation::Decoded`). -#[test] -fn a_four_two_two_texture_a_function_only_writes_binds_the_neutral() { - let (Some(write), Some(sampling)) = (fixture("storage_texture_write"), fixture("sampling")) - else { - return; - }; - let linear = || sampler(true, SamplerReductionMode::WeightedAverage); - let twin_view = |plan: &BindingPlan| { - plan.descriptors.iter().any(|d| { - matches!( - &d.source, - WriteSource::CombinedImageSampler { - image: ImageSource::Texture { view, .. }, - .. - } if view.format == vk::Format::R8G8B8A8_UNORM - ) - }) - }; - let (mut written, mut sampled) = (0, 0); - for (stem, dev) in devices() { - for pf in [PixelFormat::GBGR422, PixelFormat::BGRG422] { - let pairs = || texture(TextureType::Type2D, pf); - if let Ok(p) = kernel(&dev, &write, "storage_texture_write") { - let plan = p - .plan(&dev, &kernel_state(&[(0, pairs())], &[], false).shape()) - .unwrap_or_else(|e| panic!("{stem} {pf:?}: {e}")); - assert!( - plan.descriptors.iter().any(|d| matches!( - d.source, - WriteSource::Neutral(NeutralResource::Image { .. }) - )), - "{stem} {pf:?}: {:?}", - plan.descriptors - ); - assert!( - !plan - .descriptors - .iter() - .any(|d| matches!(d.source, WriteSource::Texture { .. })), - "{stem} {pf:?}" - ); - assert!( - matches!( - plan.diagnostics[..], - [PlanDiagnostic::IncompatibleBinding { .. }] - ), - "{stem} {pf:?}: {:?}", - plan.diagnostics - ); - written += 1; - } - if let Ok(p) = kernel(&dev, &sampling, "sample_level") { - let plan = p - .plan( - &dev, - &kernel_state(&[(0, pairs())], &[(0, linear())], true).shape(), - ) - .unwrap_or_else(|e| panic!("{stem} {pf:?}: a sampled 4:2:2 texture: {e}")); - assert!(twin_view(&plan), "{stem} {pf:?}: {:?}", plan.descriptors); - sampled += 1; - } - } - } - assert!( - written >= 6 && sampled >= 6, - "{written} written, {sampled} sampled" - ); -} diff --git a/crates/metal2vulkan/src/tests/engine_handles.rs b/crates/metal2vulkan/src/tests/engine_handles.rs index 4ee89bd8c..201eb1f7a 100644 --- a/crates/metal2vulkan/src/tests/engine_handles.rs +++ b/crates/metal2vulkan/src/tests/engine_handles.rs @@ -28,7 +28,6 @@ use std::sync::atomic::{AtomicU64, Ordering}; -use crate::bind::{heap_classes, BindState, BindingPlan, WriteSource}; use crate::budget::Budget; use crate::device::profile::DeviceProfile; use crate::device::DevicePolicy; @@ -1324,21 +1323,6 @@ fn is_table(k: &ResourceKind) -> bool { matches!(k, ResourceKind::Synthetic(SyntheticBinding::HandleTable)) } -/// Every heap array `a` declares is one of the binder's heap classes on `p`, so the binder has a -/// neutral of its type for element 0: one class, and its unsigned integer twin where a float read -/// or query of its sampled group declares one. -fn assert_binder_classes(a: &FunctionArtifact, p: &DeviceProfile, stem: &str) { - let classes = heap_classes(p); - let mut n = 0; - for d in &a.interface.descriptors { - if let ResourceKind::Heap(c) = d.slot.kind { - assert!(classes.contains(&c), "{stem}: {c:?}"); - n += 1; - } - } - assert_eq!(n, 1 + siblings(a), "{stem}"); -} - /// The sibling classes `a` declares: a sampled `Sint` or `Uint` heap class beside the sampled /// float class of its shape. A float read or query of that class's group declares the unsigned /// integer twin (its members of a form a heap reads held there raw, `HeapPlan::raw`), and its @@ -1393,7 +1377,6 @@ fn an_argument_buffer_texture_is_a_heap_lookup() { // No static texture slot: the texture is the heap's. assert!(texture_slots(&a).is_empty(), "{stem}"); assert_eq!(bindings_of(&t, is_heap), one_heap(&a), "{stem}"); - assert_binder_classes(&a, &p, &stem); let table = bindings_of(&t, is_table); assert_eq!(table.len(), 1, "{stem}"); assert_eq!(table[0].0, 0, "{stem}"); @@ -1411,11 +1394,10 @@ fn an_argument_buffer_texture_is_a_heap_lookup() { } /// Through the public compile API the heap pipeline's layout is the heap's (set 1, one partially -/// bound, update-after-bind array in an update-after-bind pool), the device accepts its -/// requirements, and with nothing resident the binder plans the table's null entry and the array's -/// neutral element 0 (`src/tests/engine_heap_binder.rs` binds textures). +/// bound, update-after-bind array in an update-after-bind pool), and the device accepts its +/// requirements. #[test] -fn a_heap_pipeline_compiles_and_plans() { +fn a_heap_pipeline_compiles_to_the_heap_layout() { let Some(bc) = fixture() else { return }; let dev = m3_device(); let lib = Library::from_air(&bc).expect("library"); @@ -1450,10 +1432,6 @@ fn a_heap_pipeline_compiles_and_plans() { .. } ))); - let plan = pipe - .plan(&dev, &BindState::default().shape()) - .expect("plan"); - assert_empty_heap(&plan, 1, 3); } /// Set 1 of a layout whose one sampled float class a read declares its siblings beside: the heap @@ -1479,34 +1457,11 @@ fn assert_siblings(bindings: &[crate::pipeline::layout::DescriptorBinding]) { } } -/// With nothing resident, a heap plan writes each handle table as its null entry alone and each -/// of the `arrays` heap arrays' element 0, the class's neutral. -fn assert_empty_heap(plan: &BindingPlan, tables: usize, arrays: usize) { - let table_writes: Vec<_> = plan - .descriptors - .iter() - .filter(|d| matches!(d.source, WriteSource::HandleTable { .. })) - .collect(); - assert_eq!(table_writes.len(), tables); - for d in table_writes { - assert!(matches!( - d.source, - WriteSource::HandleTable { bytes_len: 16, .. } - )); - } - let heap: Vec<_> = plan.descriptors.iter().filter(|d| d.set == 1).collect(); - assert_eq!(heap.len(), arrays); - for d in heap { - assert_eq!(d.array_element, 0); - assert!(matches!(d.source, WriteSource::Neutral(_))); - } -} - /// The binding flags of a pipeline's set-1 arrays, by its `requirements`: /// `PARTIALLY_BOUND | UPDATE_AFTER_BIND`, and `UPDATE_UNUSED_WHILE_PENDING` exactly where the /// pipeline requires `descriptorBindingUpdateUnusedWhilePending` (link's /// `heap_unused_while_pending`). -pub(super) fn heap_flags(requirements: &Requirements) -> vk::DescriptorBindingFlags { +fn heap_flags(requirements: &Requirements) -> vk::DescriptorBindingFlags { let flags = vk::DescriptorBindingFlags::PARTIALLY_BOUND | vk::DescriptorBindingFlags::UPDATE_AFTER_BIND; match requirements @@ -1529,7 +1484,7 @@ fn m3_device() -> Device { /// A render pipeline whose vertex and fragment functions both read a texture from an argument /// buffer: both stages share the one set-1 array of the class and each reads its own handle -/// table, which `RenderPipeline::plan` writes. +/// table. #[test] fn a_render_heap_pipeline_shares_its_array() { let Some(bc) = assemble( @@ -1616,12 +1571,7 @@ declare { <4 x float>, i8 } @air.read_texture_2d.v4f32(ptr addrspace(1), ptr add }) .count(); assert_eq!(tables, 2, "one handle table per stage"); - let plan = pipe - .plan(&dev, &BindState::default().shape()) - .expect("plan"); - assert_empty_heap(&plan, 2, 3); } - /// Two members of one argument buffer merged by a select form one heap group: a storage class /// written through a guard on the handle (a null handle drops the write), queried and tested /// for null through the same element. @@ -1737,7 +1687,6 @@ declare i32 @air.get_width_texture_2d(ptr addrspace(1), i32) assert_eq!(uses(&a, "texture.is_null.heap"), 1, "{stem}"); // One class: both members and the merged handle name one array. assert_eq!(bindings_of(&t, is_heap), one_heap(&a), "{stem}"); - assert_binder_classes(&a, &p, &stem); compiled += 1; } Err(e) => { @@ -1812,7 +1761,6 @@ fn a_heap_texel_write_is_the_devices_write() { } }; link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); - assert_binder_classes(&a, &p, &what); let classes = heap_image_classes(&a); assert_eq!(classes.len(), 1, "{what}: {classes:?}"); assert_eq!(classes[0].access, ImageAccess::Storage, "{what}"); @@ -1942,7 +1890,6 @@ fn a_selected_member_resource_id_is_a_heap_lookup() { assert_eq!(uses(&a, "access.handle.lookup"), 1, "{stem}"); assert_eq!(uses(&a, "texture.query.heap"), 1, "{stem}"); assert_eq!(bindings_of(&t, is_heap), one_heap(&a), "{stem}"); - assert_binder_classes(&a, &p, &stem); compiled += 1; } Err(e) => { @@ -2036,7 +1983,6 @@ fn dynamic_argument_buffer_elements_are_heap_lookups() { } assert!(texture_slots(&a).is_empty(), "{stem} {entry}"); assert_eq!(bindings_of(&t, is_heap), one_heap(&a), "{stem} {entry}"); - assert_binder_classes(&a, &p, &stem); compiled += 1; } Err(e) => { @@ -2097,9 +2043,6 @@ fn an_argument_buffer_depth_texture_reads_through_the_float_class() { && c.dim == ImageDim::D2), "{stem}: {classes:?}" ); - for c in &classes { - assert!(heap_classes(&p).contains(&HandleClass::Image(*c)), "{stem}"); - } // Every image type is 2D (Dim 1) and not a depth image. for (dim, depth, _) in image_types(&a) { assert_eq!((dim, depth), (1, 0), "{stem}"); @@ -2326,10 +2269,8 @@ fn a_heap_texture_samples_through_a_runtime_sampler() { /// A cube's explicit gradients through a sampler loaded from an argument buffer: the sample takes /// Metal's footprint as a slot's does (`PrecisionNote::CubeGradientFootprint`), the isotropic or -/// the anisotropic form by its table entry's word, through the set-1 sampler array of its own use, -/// and the plan takes an anisotropic listed sampler for it (`engine_heap_binder`). Every profile -/// with the -/// sampled heap compiles it and passes L3; it was `ArgumentBufferTextures NotImplemented` before. +/// the anisotropic form by its table entry's word, through the set-1 sampler array of its own use. +/// Every profile with the sampled heap compiles it and passes L3. #[test] fn a_cube_gradient_through_an_argument_buffer_sampler_reads_its_own_sampler_array() { let Some(bc) = assemble( @@ -2888,7 +2829,6 @@ fn an_argument_buffer_depth_texture_compares_through_the_depth_comparison_class( ), "{stem}" ); - assert!(heap_classes(&p).contains(&HandleClass::Image(c)), "{stem}"); // The one image type is 2D (Dim 1) and a depth image. assert_eq!( image_types(&a) @@ -2994,8 +2934,7 @@ define void @k(ptr addrspace(2) %m, ptr addrspace(1) %out{param}, i32 %gid) {{ /// A heap texture's linear sample, through a constexpr sampler of linear filters (2D and 3D), a /// runtime sampler slot, or the sampler its argument buffer holds, is the device's sample; the -/// census names the sample by its source, and the module records no `FloatSampleFilter`, outright -/// or specialized. A 2D sample through a constexpr or +/// census names the sample by its source. A 2D sample through a constexpr or /// runtime sampler also emulates a raw-held texture's, in a branch on the class the handle carries /// (the search's flagged form, whose masks and table the census counts under `HEAP_CLASS_CENSUS`). /// Each validates; a profile without the sampled heap refuses each. (The interpreter models no @@ -3052,9 +2991,6 @@ fn heap_linear_samples_are_the_device_s() { raw, "{what}" ); - let filter = PrecisionNote::FloatSampleFilter; - assert!(!a.precision.contains(&filter), "{what}"); - assert!(!a.specialized.iter().any(|s| s.note == filter), "{what}"); compiled += 1; } assert!( @@ -3349,12 +3285,6 @@ fn argument_buffer_textures_sample_through_heap_samplers() { .collect(); sampled.sort(); assert_eq!(sampled, classes, "{stem} {entry}"); - for c in heap_image_classes(&a) { - assert!( - heap_classes(&p).contains(&HandleClass::Image(c)), - "{stem} {entry}" - ); - } let hs = heap_samplers(&a); let integer: Vec = hs.iter().map(|c| c.integer).collect(); assert_eq!(integer, samplers, "{stem} {entry}"); @@ -4482,11 +4412,6 @@ fn argument_buffer_samplers_are_heap_lookups() { let heap = bindings_of(&t, is_heap); assert_eq!(heap.len(), 2, "{stem} {entry}"); assert!(heap.iter().all(|(set, _)| *set == 1), "{stem} {entry}"); - for d in &a.interface.descriptors { - if let ResourceKind::Heap(c) = d.slot.kind { - assert!(heap_classes(&p).contains(&c), "{stem} {entry}: {c:?}"); - } - } assert_eq!(count(&a, OP_SAMPLED_IMAGE), 1, "{stem} {entry}"); assert_eq!(count(&a, op), 1, "{stem} {entry}"); assert_eq!( diff --git a/crates/metal2vulkan/src/tests/engine_heap_binder.rs b/crates/metal2vulkan/src/tests/engine_heap_binder.rs deleted file mode 100644 index c568823dd..000000000 --- a/crates/metal2vulkan/src/tests/engine_heap_binder.rs +++ /dev/null @@ -1,2689 +0,0 @@ -//! The binder half of the handle domain. No device is opened. -//! -//! Heap pipelines go through the public compile API on `moltenvk-m3`, `ComputePipeline::plan` or -//! `RenderPipeline::plan`, and `instantiate_dispatch` or `instantiate_draw`: -//! -//! - One element per heap member (used image textures by token, then bound image textures), -//! shared by every class array: element 0 and every member a class does not hold are the -//! class's neutral; a held member is written through its view (sampled or storage, one layout per -//! member). Texture buffers, used buffers, and used textures reaching no stage with a table are -//! not members. A member bound at a slot shares one layout with the slot's own writes (`GENERAL` -//! when either is a storage image) and one use. -//! - Each stage's handle table has one entry per member reaching it plus the null entry; per -//! draw or dispatch its bytes are the members' nonzero resource ids, deduplicated, sorted, after -//! leading null entries. `lookup_host` finds each id's element in them, and so does a call of -//! the emitted search (`memory::handles::define_lookup`) on the CPU interpreter, fed the -//! binder's own bytes: the end-to-end path bind state, table bytes, emitted search, element. -//! Each entry's flags are its member's out-of-bounds-alpha flag (its pixel format has no -//! alpha), which the search's alpha form carries in the handle's bit 31. -//! - More members than the heap arrays hold is `HeapTooLarge`; a storage member the heap's -//! formatless class cannot view is a typed refusal. -//! - A heap texture sampled through a constexpr sampler reads a set-0 heap sampler, the layout's -//! immutable sampler, which the plan does not write; through a runtime sampler, a heap sampler -//! the plan writes with the sampler bound at its slot. An opaque-black border is checked against -//! every member the sampled arrays hold, and a linear filter against the view format of every -//! member of its stage the sampled float arrays hold. -//! - A sampler loaded from an argument buffer reads the set-1 sampler array of its use at the -//! element its stage's sampler table gives: the plan writes twice the shape's capacity class of -//! `ArgumentSampler` elements, the table bytes list `BindState::argument_samplers` by id with -//! their state word (`metal::sampler::SamplerWord`), the emitted search's entry form finds each -//! id's entry, and a sampler made or released replans only when the class or the set of shapes -//! changes; listed again as a command buffer commits, the states fit the plan up to its entries, -//! a new shape where the plan's checks pass. -//! - Loads of one argument-buffer member share a heap group, so a read of the member types its -//! queries (never the MSL type name); a group only queried is declared `Float` with -//! `RuntimeFact::HeapNumericType`, and its class reports a member of another numeric type -//! (`IncompatibleHeapEntry`). Under the identity domains such a group, a 2D texture's or a cube -//! array's alike, is `Unsupported{IdentityDomains}`, not implemented, naming that fact. -//! -//! `llvm-as` assembles the kernels; without it the tests skip visibly. - -use std::sync::atomic::{AtomicU64, Ordering}; - -use super::engine_word_phases::identity_profiles; -use crate::bind::{ - AccessClass, ArgumentSampler, BindState, BindingPlan, BoundSampler, BoundTexture, - DescriptorBytes, Dispatch, DrawCall, HeapSource, NeutralResource, PlanDiagnostic, - ResourceClass, ResourceUse, SamplerDescriptor, StageTable, TextureFacts, UseTarget, - UsedResource, WriteSource, -}; -use crate::budget::Budget; -use crate::device::requirements::FormatUsage; -use crate::device::{Device, DeviceDescription, DevicePolicy}; -use crate::error::{BindError, Capability, Error, Feature, Needs, Unsupported}; -use crate::library::{FunctionArtifact, Library}; -use crate::memory::handles::{ - declare_table, define_lookup, lookup_host, Lookup, FLAG_BORDER_TEXELS, - FLAG_OUT_OF_BOUNDS_ALPHA_ONE, FLAG_RED_BLUE, FLAG_TEXEL_CLASS, HANDLE_ALPHA_ONE, HANDLE_ENTRY, - TABLE_ENTRY_BYTES, -}; -use crate::memory::leaf::k32; -use crate::memory::views; -use crate::metal::format::storage_image_choice; -use crate::metal::sampler::SamplerWord; -use crate::metal::{ - PixelFormat, RenderStages, SamplerAddressMode, SamplerBorderColor, SamplerMinMagFilter, - TextureType, TextureUsage, -}; -use crate::pipeline::descriptor::ColorAttachmentDescriptor; -use crate::pipeline::facts::RuntimeFact; -use crate::pipeline::layout::BindingSource; -use crate::pipeline::lower_inputs::StorageImageClass; -use crate::pipeline::sym::{ - HandleClass, ImageAccess, ImageHandleClass, ResourceKind, ResourceSlot, SampledType, SlotClass, - SlotRef, Stage, SyntheticBinding, -}; -use crate::pipeline::testing::{ - compile, engine_dir, link_and_validate, llvm_assemble, profile, AssembleError, -}; -use crate::pipeline::{ - ComputePipeline, ComputePipelineDescriptor, FunctionDescriptor, RenderPipeline, - RenderPipelineDescriptor, StageSource, -}; -use crate::spirv::builder::ModuleBuilder; -use crate::spirv::interp::{run, Buffer, Config, Resources}; -use crate::spirv::ir::{ExecMode, ExecModel, MemAccess, Type}; -use crate::vk; - -const HEADER: &str = "target datalayout = \"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32\"\ntarget triple = \"air64_v28-apple-macosx26.0.0\"\n\n"; - -fn assembled(name: &str, r: Result, AssembleError>) -> Option> { - match r { - Ok(b) => Some(b), - Err(AssembleError::Missing(why)) => { - eprintln!("SKIPPED: {why}"); - None - } - Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected {name}: {why}"), - } -} - -fn assemble(name: &str, body: &str) -> Option> { - static NEXT: AtomicU64 = AtomicU64::new(0); - let dir = std::env::temp_dir().join(format!( - "m2v-heap-binder-{}-{}-{name}", - std::process::id(), - NEXT.fetch_add(1, Ordering::Relaxed) - )); - std::fs::create_dir_all(&dir).expect("scratch"); - let ll = dir.join("k.ll"); - std::fs::write(&ll, format!("{HEADER}{body}")).expect("write"); - let r = llvm_assemble(&ll); - let _ = std::fs::remove_dir_all(&dir); - assembled(name, r) -} - -/// The committed `moltenvk-m3` profile as a device. -fn m3() -> Device { - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../metal2vulkan-validation/profiles/moltenvk-m3.json"); - let text = std::fs::read_to_string(path).expect("profile"); - let desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); - Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device") -} - -fn compute(dev: &Device, bc: &[u8], entry: &str) -> ComputePipeline { - let lib = Library::from_air(bc).expect("library"); - let f = lib.function(entry).expect("entry"); - let d = ComputePipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new(f))); - dev.compile_compute_pipeline(&d, &Budget::standard()) - .unwrap_or_else(|e| panic!("{entry}: {e}")) -} - -/// `argument_buffer_read` of the owned `handles` fixture: one sampled `float` 2D heap class. -fn read_pipeline(dev: &Device) -> Option { - let bc = assembled("handles", llvm_assemble(&engine_dir().join("handles.ll")))?; - Some(compute(dev, &bc, "argument_buffer_read")) -} - -/// A used texture: token `token`, `ty`/`pf`, `usage`, resource id `id`. -fn used( - token: u32, - ty: TextureType, - pf: PixelFormat, - usage: TextureUsage, - id: Option, -) -> UsedResource { - let mut facts = TextureFacts::new(ty, pf); - facts.usage = usage; - if matches!( - ty, - TextureType::Type2DMultisample | TextureType::Type2DMultisampleArray - ) { - facts.sample_count = 4; - } - let mut u = UsedResource::new(ResourceClass::Texture(facts), token); - u.resource_id = id; - u -} - -fn read() -> TextureUsage { - TextureUsage::SHADER_READ -} - -fn bound(pf: PixelFormat, id: Option) -> BoundTexture { - BoundTexture::Texture { - facts: TextureFacts::new(TextureType::Type2D, pf), - resource_id: id, - } -} - -fn slot(stage: Stage, index: u32) -> SlotRef { - SlotRef { - stage, - class: SlotClass::Texture, - index, - } -} - -/// The heap writes of `plan`'s float array, by element ([`heap_writes_of`]). -fn heap_writes(plan: &BindingPlan) -> Vec<&WriteSource> { - heap_writes_of(plan, SampledType::Float) -} - -/// The heap writes of `plan`, by element: one heap array; but for the classes of its shape of -/// other numeric types beside a sampled class (the unsigned integer twin a float read or query -/// declares, and the classes a read or query of a member of another numeric class reads it -/// through), where the array is the one whose neutral at element 0 is of numeric type `own`: a -/// sampled one, or where there is none a storage one. -fn heap_writes_of(plan: &BindingPlan, own: SampledType) -> Vec<&WriteSource> { - let heap: Vec<_> = plan.descriptors.iter().filter(|d| d.set == 1).collect(); - let numeric = |binding: u32, storage: bool| { - heap.iter().find_map(|d| match d.source { - WriteSource::Neutral(NeutralResource::Image { - sampled_type, - storage_format, - .. - }) if d.binding == binding - && d.array_element == 0 - && storage_format.is_some() == storage => - { - Some(sampled_type) - } - _ => None, - }) - }; - let bindings: std::collections::BTreeSet = heap.iter().map(|d| d.binding).collect(); - let of = |storage: bool| -> Vec { - bindings - .iter() - .copied() - .filter(|&b| numeric(b, storage) == Some(own)) - .collect() - }; - let own: Vec = match bindings.len() { - 1 => bindings.iter().copied().collect(), - _ => match of(false) { - sampled if sampled.is_empty() => of(true), - sampled => sampled, - }, - }; - assert_eq!(own.len(), 1, "one heap array: {bindings:?}"); - let mut w: Vec<_> = heap.into_iter().filter(|d| d.binding == own[0]).collect(); - w.sort_by_key(|d| d.array_element); - for (e, d) in w.iter().enumerate() { - assert_eq!(d.array_element as usize, e, "one write per element"); - } - w.into_iter().map(|d| &d.source).collect() -} - -/// The `(set, binding, bytes_len)` of `stage`'s handle-table write. -fn table_write(plan: &BindingPlan, stage: Stage) -> (u32, u32, u32) { - plan.descriptors - .iter() - .find_map(|d| match d.source { - WriteSource::HandleTable { - stage: s, - bytes_len, - } if s == stage => Some((d.set, d.binding, bytes_len)), - _ => None, - }) - .expect("a handle-table write") -} - -/// The entries `(id, element)` of the table bytes at `(set, binding)`, checking the flags word. -fn table(bytes: &[DescriptorBytes], set: u32, binding: u32) -> Vec<(u64, u32)> { - entries(bytes, set, binding) - .into_iter() - .map(|(id, element, _)| (id, element)) - .collect() -} - -/// The entries `(id, element, flags)` of the table bytes at `(set, binding)`: a texture entry's -/// flags hold its out-of-bounds-alpha flag, its red-blue order, its border texels and its texel -/// class's index alone, and the null entry's none. -fn entries(bytes: &[DescriptorBytes], set: u32, binding: u32) -> Vec<(u64, u32, u32)> { - let b = &bytes - .iter() - .find(|b| b.set == set && b.binding == binding) - .expect("table bytes") - .bytes; - assert_eq!(b.len() % TABLE_ENTRY_BYTES as usize, 0); - b.chunks(TABLE_ENTRY_BYTES as usize) - .map(|e| { - let w = |i: usize| u32::from_le_bytes(e[4 * i..4 * i + 4].try_into().expect("word")); - let id = u64::from(w(0)) | (u64::from(w(1)) << 32); - let fields = FLAG_OUT_OF_BOUNDS_ALPHA_ONE - | FLAG_RED_BLUE - | FLAG_BORDER_TEXELS - | FLAG_TEXEL_CLASS; - assert_eq!(w(3) & !fields, 0, "other flags are reserved"); - if id == 0 { - assert_eq!(w(3), 0, "the null entry has no flags"); - } - (id, w(2), w(3)) - }) - .collect() -} - -/// The source and view format of a held element, or `None` for a neutral. -fn held(w: &WriteSource) -> Option<(HeapSource, vk::Format, vk::ImageLayout)> { - match w { - WriteSource::HeapEntry { source, view, .. } => Some((*source, view.format, view.layout)), - WriteSource::Neutral(_) => None, - other => panic!("a heap write {other:?}"), - } -} - -const KEYS: u32 = 8; - -/// A kernel that looks up the [`KEYS`] ids (low, high word pairs) at the start of the buffer at -/// slot 1 in the handle table at slot 0 by calling the emitted search function, as every heap -/// handle load does, and writes each handle (in `form`) after them. The table is an entry array -/// read as `u64` ids when `int64`, else a word view. -fn lookup_module(int64: bool, form: Lookup) -> crate::spirv::ir::TypedModule { - let sym = |index| ResourceSlot { - stage: Stage::Kernel, - kind: ResourceKind::Buffer, - index, - }; - let mut b = ModuleBuilder::new(); - let t = declare_table(&mut b, sym(0), int64).expect("table"); - let io = views::declare_at(&mut b, sym(1)).expect("io"); - let search = define_lookup(&mut b, t, form).expect("search"); - let void = b.ty(Type::Void).expect("void"); - let mut f = b.function(void).expect("function"); - for i in 0..KEYS { - let at_lo = k32(&mut f, 2 * i).expect("k"); - let at_hi = k32(&mut f, 2 * i + 1).expect("k"); - let lo = views::read_word(&mut f, io, at_lo).expect("lo"); - let hi = views::read_word(&mut f, io, at_hi).expect("hi"); - let e = f - .call(search, &[lo, hi]) - .expect("call") - .expect("the search returns the element"); - let at = k32(&mut f, 2 * KEYS + i).expect("k"); - let p = views::word_ptr(&mut f, io, at).expect("ptr"); - f.store(p, e, MemAccess::default()).expect("store"); - } - f.ret(None).expect("ret"); - let id = f.finish().expect("finish"); - b.entry( - ExecModel::GLCompute, - id, - vec![ExecMode::LocalSize { x: 1, y: 1, z: 1 }], - ) - .expect("entry"); - b.finalize().expect("module") -} - -/// The elements the emitted search finds for `keys` in the table `bytes`, on the interpreter: -/// the same through an entry array and a word view. -fn emitted_lookup(bytes: &[u8], keys: &[u64]) -> Vec { - emitted_lookup_in(bytes, keys, Lookup::Element) -} - -/// The handles the emitted search in `form` finds for `keys` in the table `bytes`, on the -/// interpreter: the same through an entry array and a word view. -fn emitted_lookup_in(bytes: &[u8], keys: &[u64], form: Lookup) -> Vec { - let wide = emitted_lookup_as(bytes, keys, true, form); - assert_eq!( - wide, - emitted_lookup_as(bytes, keys, false, form), - "u64 and word ids" - ); - wide -} - -fn emitted_lookup_as(bytes: &[u8], keys: &[u64], int64: bool, form: Lookup) -> Vec { - let m = lookup_module(int64, form); - let sym = |index| ResourceSlot { - stage: Stage::Kernel, - kind: ResourceKind::Buffer, - index, - }; - let mut out = Vec::new(); - for chunk in keys.chunks(KEYS as usize) { - let mut io = Vec::new(); - for i in 0..KEYS as usize { - let id = chunk.get(i).copied().unwrap_or(0); - io.extend((id as u32).to_le_bytes()); - io.extend(((id >> 32) as u32).to_le_bytes()); - } - io.extend(vec![0xAA; 4 * KEYS as usize]); - let res = Resources { - buffers: vec![ - Buffer { - slot: Some(sym(0)), - address: None, - bytes: bytes.to_vec(), - }, - Buffer { - slot: Some(sym(1)), - address: None, - bytes: io, - }, - ], - push: Vec::new(), - spec: Default::default(), - }; - let o = run(&m, &Config::default(), res).expect("run"); - let io = &o.buffers[1]; - for i in 0..chunk.len() { - let at = 4 * (2 * KEYS as usize + i); - out.push(u32::from_le_bytes(io[at..at + 4].try_into().expect("w"))); - } - } - out -} - -const A: u64 = 0x0000_0001_0000_0010; -const B: u64 = 0x0000_0001_0000_0020; -const C: u64 = 0x0000_0002_0000_0000; -const D: u64 = 0x0000_0000_ffff_fff0; -const E: u64 = 0xffff_ffff_ffff_fff0; -const F: u64 = 0x0000_0003_0000_0001; - -/// A sampled heap: every used image texture and every bound one is a member with one element; -/// the class holds exactly the `float` 2D `ShaderRead` members through their sampled views; the -/// table's bytes resolve every resident id to its element, by `lookup_host` and by the emitted -/// search on the interpreter, and every other id (0, a texture buffer's, an absent one) to 0. -#[test] -fn a_sampled_heap_writes_each_member_and_its_table() { - let dev = m3(); - let Some(pipe) = read_pipeline(&dev) else { - return; - }; - let mut state = BindState { - used_resources: vec![ - used( - 1, - TextureType::Type2D, - PixelFormat::RGBA8Unorm, - read(), - Some(A), - ), - // Another numeric type, no shader read, another type: other classes' members. - used( - 2, - TextureType::Type2D, - PixelFormat::R32Uint, - read(), - Some(B), - ), - used( - 3, - TextureType::Type2D, - PixelFormat::RGBA8Unorm, - TextureUsage::RENDER_TARGET, - Some(C), - ), - used( - 4, - TextureType::Type2DArray, - PixelFormat::RGBA8Unorm, - read(), - Some(D), - ), - UsedResource::new(ResourceClass::Buffer, 5), - // No resource id, the null id, and the id of token 1 again. - used( - 6, - TextureType::Type2D, - PixelFormat::RGBA8Unorm, - read(), - None, - ), - used( - 7, - TextureType::Type2D, - PixelFormat::RGBA8Unorm, - read(), - Some(0), - ), - used( - 8, - TextureType::Type2D, - PixelFormat::RGBA8Unorm, - read(), - Some(A), - ), - // A texture buffer is no member. - used( - 9, - TextureType::TextureBuffer, - PixelFormat::R32Float, - read(), - Some(E), - ), - ], - ..Default::default() - }; - let mut k = StageTable::default(); - k.textures - .insert(3, bound(PixelFormat::BGRA8Unorm, Some(F))); - state.stages.insert(Stage::Kernel, k); - - let plan = pipe.plan(&dev, &state.shape()).expect("plan"); - // Members: tokens 1, 2, 3, 4, 6, 7, 8 (elements 1..=7), then [[texture(3)]] (element 8). - let (set, binding, len) = table_write(&plan, Stage::Kernel); - assert_eq!(set, 0); - assert_eq!(len, 9 * TABLE_ENTRY_BYTES); - let w = heap_writes(&plan); - assert_eq!(w.len(), 9); - let neutral = match w[0] { - WriteSource::Neutral(n @ NeutralResource::Image { .. }) => *n, - other => panic!("element 0 {other:?}"), - }; - assert!(matches!( - neutral, - NeutralResource::Image { - sampled_type: SampledType::Float, - storage_format: None, - .. - } - )); - let rgba = vk::Format::R8G8B8A8_UNORM; - let ro = vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL; - let expected = [ - None, - Some((HeapSource::Used(1), rgba, ro)), - None, - None, - None, - Some((HeapSource::Used(6), rgba, ro)), - Some((HeapSource::Used(7), rgba, ro)), - Some((HeapSource::Used(8), rgba, ro)), - Some(( - HeapSource::Bound(slot(Stage::Kernel, 3)), - vk::Format::B8G8R8A8_UNORM, - ro, - )), - ]; - for (e, (got, want)) in w.iter().zip(expected).enumerate() { - assert_eq!(held(got), want, "element {e}"); - if want.is_none() { - assert_eq!(**got, WriteSource::Neutral(neutral), "element {e}"); - } - } - for got in &w { - if let WriteSource::HeapEntry { view, class, .. } = got { - assert_eq!(view.view_type, vk::ImageViewType::TYPE_2D); - assert_eq!(view.aspect, vk::ImageAspectFlags::COLOR); - assert!(matches!(class, HandleClass::Image(c) if c.access == ImageAccess::Sampled)); - } - } - // A typed class reports no member of another numeric type. - assert!(plan.diagnostics.is_empty(), "{:?}", plan.diagnostics); - // The bound member is used through the heap: read, sampled, in the kernel. - assert!(plan.uses.iter().any(|u| { - u.resource == UseTarget::Slot(slot(Stage::Kernel, 3)) - && u.access.read - && !u.access.write - && u.stages == vk::PipelineStageFlags2::COMPUTE_SHADER - })); - - let cmds = plan - .instantiate_dispatch( - &state, - &Dispatch::Threadgroups { - groups: [1, 1, 1], - threads_per_group: [1, 1, 1], - }, - ) - .expect("dispatch"); - let t = table(&cmds.descriptor_bytes, set, binding); - // Five resident ids (token 8's is token 1's, the lower element wins), after four leading - // null entries that pad the table to its planned nine. - assert_eq!( - t, - vec![ - (0, 0), - (0, 0), - (0, 0), - (0, 0), - (D, 4), - (A, 1), - (B, 2), - (C, 3), - (F, 8), - ] - ); - let keys = [A, B, C, D, F, 0, E, A + 1, u64::MAX, 1]; - let want = [1, 2, 3, 4, 8, 0, 0, 0, 0, 0]; - for (id, e) in keys.iter().zip(want) { - assert_eq!(lookup_host(&t, *id), e, "id {id:#x}"); - } - let bytes = &cmds - .descriptor_bytes - .iter() - .find(|b| b.set == set && b.binding == binding) - .expect("bytes") - .bytes; - assert_eq!(emitted_lookup(bytes, &keys), want.to_vec()); - // Each entry's flags are its member's out-of-bounds alpha: token 2's `R32Uint` has no alpha, - // every other member's format has one, and the null entries have none (beside its texel class - // and border texels, which `table_entries_state_each_members_texel_class` reads). - let flag = FLAG_OUT_OF_BOUNDS_ALPHA_ONE; - let listed = entries(&cmds.descriptor_bytes, set, binding); - let flags: Vec = listed - .iter() - .map(|e| e.2 & !(FLAG_TEXEL_CLASS | FLAG_RED_BLUE | FLAG_BORDER_TEXELS)) - .collect(); - assert_eq!(flags, vec![0, 0, 0, 0, 0, 0, flag, 0, 0]); - // And its red-blue order: `[[texture(3)]]`'s `BGRA8Unorm` (element 8) is blue-first, every - // other member red-first. - for &(id, element, flags) in &listed { - assert_eq!( - flags & FLAG_RED_BLUE != 0, - element == 8, - "id {id:#x} element {element}" - ); - } - // The search's flagged form carries the found entry's alpha flag in the handle's bit 31; a - // miss is the null handle without it. - let alpha: Vec = want - .iter() - .map(|&e| if e == 2 { e | HANDLE_ALPHA_ONE } else { e }) - .collect(); - let flagged = Lookup::Flagged { - alpha: true, - class: false, - red_blue: false, - unreadable: false, - }; - assert_eq!(emitted_lookup_in(bytes, &keys, flagged), alpha); - // The table's element of an id is the element the plan wrote that texture to. - for (source, id) in [ - (HeapSource::Used(1), A), - (HeapSource::Bound(slot(Stage::Kernel, 3)), F), - ] { - let e = w - .iter() - .position(|x| held(x).is_some_and(|h| h.0 == source)) - .expect("held"); - assert_eq!(lookup_host(&t, id), e as u32); - } -} - -/// The plan is total where the pipeline compiles: every committed profile with the sampled heap -/// plans one resident texture and instantiates its table. -#[test] -fn heap_plans_are_total_on_the_committed_profiles() { - let Some(bc) = assembled("handles", llvm_assemble(&engine_dir().join("handles.ll"))) else { - return; - }; - let mut planned = 0; - for (stem, _) in crate::spirv::testing::committed_profiles().expect("profiles") { - 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 desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); - let dev = Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device"); - let lib = Library::from_air(&bc).expect("library"); - let f = lib.function("argument_buffer_read").expect("entry"); - let d = ComputePipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new(f))); - let Ok(pipe) = dev.compile_compute_pipeline(&d, &Budget::standard()) else { - continue; - }; - let state = BindState { - used_resources: vec![used( - 1, - TextureType::Type2D, - PixelFormat::RGBA8Unorm, - read(), - Some(A), - )], - ..Default::default() - }; - let plan = pipe - .plan(&dev, &state.shape()) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - let cmds = plan - .instantiate_dispatch( - &state, - &Dispatch::Threadgroups { - groups: [1, 1, 1], - threads_per_group: [1, 1, 1], - }, - ) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - let (set, binding, _) = table_write(&plan, Stage::Kernel); - assert_eq!( - table(&cmds.descriptor_bytes, set, binding), - vec![(0, 0), (A, 1)], - "{stem}" - ); - planned += 1; - } - assert!(planned > 0); -} - -/// The most members a `moltenvk-m3` heap holds: its capacity (`TABLE_CAPACITY`) less the null -/// element. -const LARGE_HEAP: u32 = 65_535; - -/// Planning and instantiating are linear in the heap's members: every member's resource id is -/// found once (never by rescanning the bind state per member), so a full heap of [`LARGE_HEAP`] -/// used textures plans and instantiates inside a bound a per-member scan of the state cannot -/// meet (quadratic: 14 s at half this size in a debug build, about 4 times that here). Not a -/// benchmark: the bound is an order of magnitude above the linear cost. -#[test] -fn a_large_heap_plans_and_instantiates_in_linear_time() { - let dev = m3(); - let Some(pipe) = read_pipeline(&dev) else { - return; - }; - // Distinct, unordered, nonzero ids. - let id = |t: u32| (u64::from(t).wrapping_mul(0x9e37_79b9_7f4a_7c15) >> 1) | 1; - let state = BindState { - used_resources: (1..=LARGE_HEAP) - .map(|t| { - used( - t, - TextureType::Type2D, - PixelFormat::RGBA8Unorm, - read(), - Some(id(t)), - ) - }) - .collect(), - ..Default::default() - }; - let start = std::time::Instant::now(); - let plan = pipe.plan(&dev, &state.shape()).expect("plan"); - let planned = start.elapsed(); - let cmds = plan - .instantiate_dispatch( - &state, - &Dispatch::Threadgroups { - groups: [1, 1, 1], - threads_per_group: [1, 1, 1], - }, - ) - .expect("dispatch"); - let instantiated = start.elapsed() - planned; - eprintln!("{LARGE_HEAP} members: plan {planned:?}, instantiate {instantiated:?}"); - let (set, binding, _) = table_write(&plan, Stage::Kernel); - let t = table(&cmds.descriptor_bytes, set, binding); - assert_eq!(t.len(), LARGE_HEAP as usize + 1); - assert_eq!(t[0], (0, 0)); - for token in [1, 2, LARGE_HEAP / 2, LARGE_HEAP] { - assert_eq!(lookup_host(&t, id(token)), token, "token {token}"); - } - let bound = std::time::Duration::from_secs(5); - assert!( - planned < bound && instantiated < bound, - "plan {planned:?}, instantiate {instantiated:?}" - ); -} - -/// The members plus the null element must fit the heap arrays' count: one more member than the -/// capacity allows is `HeapTooLarge`, and a state of another shape is an internal error. -#[test] -fn the_heap_capacity_bounds_the_members() { - let dev = m3(); - let Some(mut pipe) = read_pipeline(&dev) else { - return; - }; - let heap = pipe.layout.sets[1] - .bindings - .iter_mut() - .find(|b| matches!(b.source, BindingSource::Heap(_))) - .expect("heap array"); - heap.count = 3; - let members = |n: u32| BindState { - used_resources: (1..=n) - .map(|t| { - used( - t, - TextureType::Type2D, - PixelFormat::RGBA8Unorm, - read(), - Some(u64::from(t)), - ) - }) - .collect(), - ..Default::default() - }; - let fits = members(2); - let plan = pipe - .plan(&dev, &fits.shape()) - .expect("two members fit three elements"); - assert_eq!(heap_writes(&plan).len(), 3); - assert_eq!( - pipe.plan(&dev, &members(3).shape()), - Err(BindError::HeapTooLarge { count: 4, limit: 3 }) - ); - // Instantiating with a member whose facts differ from the planned shape is internal. - let mut other = fits.clone(); - other.used_resources[1] = used( - 2, - TextureType::Type2D, - PixelFormat::R32Uint, - read(), - Some(2), - ); - assert!(matches!( - plan.instantiate_dispatch( - &other, - &Dispatch::Threadgroups { - groups: [1, 1, 1], - threads_per_group: [1, 1, 1], - }, - ), - Err(BindError::Internal(_)) - )); -} - -const STORAGE_KERNEL: &str = r#"%struct.T = type { ptr addrspace(1) } -%struct.R = type { %struct.T, %struct.T } -define void @heap_write(ptr addrspace(2) %r, ptr addrspace(1) %out, i32 %gid) { - %pt = getelementptr inbounds %struct.R, ptr addrspace(2) %r, i64 0, i32 0, i32 0 - %t = load ptr addrspace(1), ptr addrspace(2) %pt, align 8 - %pu = getelementptr inbounds %struct.R, ptr addrspace(2) %r, i64 0, i32 1, i32 0 - %u = load ptr addrspace(1), ptr addrspace(2) %pu, align 8 - %odd = trunc i32 %gid to i1 - %h = select i1 %odd, ptr addrspace(1) %t, ptr addrspace(1) %u - %c = insertelement <2 x i32> zeroinitializer, i32 %gid, i64 0 - call void @air.write_texture_2d.v4f32(ptr addrspace(1) %h, <2 x i32> %c, <4 x float> , i32 0, i32 2) - %w = call i32 @air.get_width_texture_2d(ptr addrspace(1) %h, i32 0) - %o = getelementptr inbounds i32, ptr addrspace(1) %out, i32 %gid - store i32 %w, ptr addrspace(1) %o, align 4 - ret void -} -declare void @air.write_texture_2d.v4f32(ptr addrspace(1), <2 x i32>, <4 x float>, i32, i32) -declare i32 @air.get_width_texture_2d(ptr addrspace(1), i32) -!air.kernel = !{!0} -!air.version = !{!9} -!air.language_version = !{!10} -!0 = !{ptr @heap_write, !1, !2} -!1 = !{} -!2 = !{!3, !7, !8} -!3 = !{i32 0, !"air.indirect_buffer", !"air.buffer_size", i32 16, !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.struct_type_info", !4, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 8, !"air.arg_type_name", !"R", !"air.arg_name", !"r"} -!4 = !{i32 0, i32 8, i32 0, !"texture2d", !"t", !"air.indirect_argument", !5, i32 8, i32 8, i32 0, !"texture2d", !"u", !"air.indirect_argument", !6} -!5 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.write", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"t"} -!6 = !{i32 1, !"air.texture", !"air.location_index", i32 1, i32 1, !"air.write", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"u"} -!7 = !{i32 1, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"out"} -!8 = !{i32 2, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"gid"} -!9 = !{i32 2, i32 8, i32 0} -!10 = !{!"Metal", i32 4, i32 0, i32 0} -"#; - -/// A storage heap holds the `ShaderWrite` members its formatless class can view (the direct -/// format, `GENERAL`), never a depth texture or a read-only one; a writable member whose storage -/// choice needs a conversion view is a typed refusal, since the class's one declaration cannot -/// convert per element. -#[test] -fn a_storage_heap_holds_writable_textures() { - let dev = m3(); - let Some(bc) = assemble("heap_write", STORAGE_KERNEL) else { - return; - }; - let pipe = compute(&dev, &bc, "heap_write"); - let rw = TextureUsage::SHADER_READ | TextureUsage::SHADER_WRITE; - let write = TextureUsage::SHADER_WRITE; - let mut state = BindState { - used_resources: vec![ - used(1, TextureType::Type2D, PixelFormat::RGBA8Unorm, rw, Some(A)), - used( - 2, - TextureType::Type2D, - PixelFormat::RGBA8Unorm, - read(), - Some(B), - ), - used( - 3, - TextureType::Type2D, - PixelFormat::Depth32Float, - write, - Some(C), - ), - used( - 4, - TextureType::Type2D, - PixelFormat::R32Float, - write, - Some(D), - ), - ], - ..Default::default() - }; - let plan = pipe.plan(&dev, &state.shape()).expect("plan"); - let w = heap_writes(&plan); - let general = vk::ImageLayout::GENERAL; - assert!(matches!( - w[0], - WriteSource::Neutral(NeutralResource::Image { - storage_format: Some(vk::Format::R32_SFLOAT), - .. - }) - )); - assert_eq!( - w.iter().map(|x| held(x)).collect::>(), - vec![ - None, - Some((HeapSource::Used(1), vk::Format::R8G8B8A8_UNORM, general)), - None, - None, - Some((HeapSource::Used(4), vk::Format::R32_SFLOAT, general)), - ] - ); - // An sRGB texture written through the heap: the plan follows its storage choice. - state.used_resources.push(used( - 5, - TextureType::Type2D, - PixelFormat::RGBA8UnormSRGB, - write, - Some(E), - )); - let direct = storage_image_choice(PixelFormat::RGBA8UnormSRGB, dev.profile()) - .is_ok_and(|c| c.class == StorageImageClass::Identity && c.alias.is_none()); - match pipe.plan(&dev, &state.shape()) { - Ok(_) => assert!(direct), - Err(BindError::Unsupported(u)) => { - assert!(!direct); - assert_eq!(u.feature, Feature::ArgumentBufferTextures); - assert_eq!(u.needs, Needs::NotImplemented); - } - Err(e) => panic!("{e}"), - } -} - -/// `argument_buffer_depth_read` of the owned `handles` fixture: a depth texture read through the -/// float 2D sampled class, and a texture written through the storage class. The sampled array holds -/// the depth texture through its depth-aspect view and the storage array the writable one; each -/// holds the other's element as its neutral. -#[test] -fn a_depth_member_is_held_by_the_float_class_through_its_depth_view() { - let dev = m3(); - let Some(bc) = assembled("handles", llvm_assemble(&engine_dir().join("handles.ll"))) else { - return; - }; - let pipe = compute(&dev, &bc, "argument_buffer_depth_read"); - let state = BindState { - used_resources: vec![ - used( - 1, - TextureType::Type2D, - PixelFormat::Depth32Float, - read(), - Some(A), - ), - used( - 2, - TextureType::Type2D, - PixelFormat::RGBA32Float, - TextureUsage::SHADER_WRITE, - Some(B), - ), - ], - ..Default::default() - }; - let plan = pipe.plan(&dev, &state.shape()).expect("plan"); - let heap = &pipe.layout.sets[1].bindings; - assert_eq!(heap.len(), 2); - for b in heap { - let BindingSource::Heap(HandleClass::Image(class)) = b.source else { - panic!("{:?}", b.source); - }; - let mut w: Vec<_> = plan - .descriptors - .iter() - .filter(|d| d.set == 1 && d.binding == b.binding) - .collect(); - w.sort_by_key(|d| d.array_element); - let views: Vec<_> = w - .iter() - .map(|d| match &d.source { - WriteSource::HeapEntry { source, view, .. } => Some((*source, view.aspect)), - WriteSource::Neutral(_) => None, - other => panic!("{other:?}"), - }) - .collect(); - match class.access { - ImageAccess::Sampled => { - assert_eq!(class.sampled_type, SampledType::Float); - assert!(!class.depth_compare); - assert_eq!( - views, - vec![ - None, - Some((HeapSource::Used(1), vk::ImageAspectFlags::DEPTH)), - None - ] - ); - } - _ => assert_eq!( - views, - vec![ - None, - None, - Some((HeapSource::Used(2), vk::ImageAspectFlags::COLOR)) - ] - ), - } - } -} - -/// `argument_buffer_sample_compare` of the owned `handles` fixture: a depth texture sampled with -/// comparison through the float 2D depth-comparison class. Its array holds the depth member through -/// its depth-aspect view and gives the color member, which a comparison cannot read, the class's -/// depth neutral; the comparison heap sampler is the layout's immutable sampler and takes no write. -#[test] -fn a_compared_depth_member_is_held_by_the_depth_comparison_class() { - let dev = m3(); - let Some(bc) = assembled("handles", llvm_assemble(&engine_dir().join("handles.ll"))) else { - return; - }; - let pipe = compute(&dev, &bc, "argument_buffer_sample_compare"); - let state = BindState { - used_resources: vec![ - used( - 1, - TextureType::Type2D, - PixelFormat::Depth32Float, - read(), - Some(A), - ), - used( - 2, - TextureType::Type2D, - PixelFormat::RGBA8Unorm, - read(), - Some(B), - ), - ], - ..Default::default() - }; - let plan = pipe.plan(&dev, &state.shape()).expect("plan"); - let heap = &pipe.layout.sets[1].bindings; - assert_eq!(heap.len(), 1); - let BindingSource::Heap(HandleClass::Image(class)) = heap[0].source else { - panic!("{:?}", heap[0].source); - }; - assert!(class.depth_compare); - assert_eq!(class.sampled_type, SampledType::Float); - let writes = heap_writes(&plan); - let views: Vec<_> = writes - .iter() - .map(|w| match w { - WriteSource::HeapEntry { source, view, .. } => Some((*source, view.aspect)), - WriteSource::Neutral(n) => { - assert!( - matches!( - n, - NeutralResource::Image { - depth_compare: true, - .. - } - ), - "{n:?}" - ); - None - } - other => panic!("{other:?}"), - }) - .collect(); - assert_eq!( - views, - vec![ - None, - Some((HeapSource::Used(1), vk::ImageAspectFlags::DEPTH)), - None - ] - ); - // The comparison heap sampler is immutable: the plan writes no sampler. - let samplers: Vec<_> = pipe.layout.sets[0] - .bindings - .iter() - .filter(|b| matches!(b.source, BindingSource::HeapSampler { .. })) - .collect(); - assert_eq!(samplers.len(), 1); - assert!(samplers[0].immutable_sampler.is_some()); - assert!(!plan - .descriptors - .iter() - .any(|d| d.set == 0 && d.binding == samplers[0].binding)); -} - -/// Each member's table entry states its texel class's index (`heap_class_index`, in -/// [`FLAG_TEXEL_CLASS`]) and its border texels (`metal::sampler::border_texels`, in -/// [`FLAG_BORDER_TEXELS`]) beside its out-of-bounds alpha (a depth format has no alpha). The -/// search's flagged form carries the alpha in the handle's bit 31 and the class in place where it -/// carries them, and its indexed form the entry's index in the top 16 bits; a miss carries -/// nothing. -#[test] -fn table_entries_state_each_members_texel_class() { - let dev = m3(); - let Some(bc) = assembled("handles", llvm_assemble(&engine_dir().join("handles.ll"))) else { - return; - }; - let pipe = compute(&dev, &bc, "argument_buffer_sample_compare"); - let state = BindState { - used_resources: vec![ - used( - 1, - TextureType::Type2D, - PixelFormat::Depth16Unorm, - read(), - Some(A), - ), - used( - 2, - TextureType::Type2D, - PixelFormat::Depth32Float, - read(), - Some(B), - ), - used( - 3, - TextureType::Type2D, - PixelFormat::Depth32FloatStencil8, - read(), - Some(C), - ), - used( - 4, - TextureType::Type2D, - PixelFormat::RGBA8Unorm, - read(), - Some(D), - ), - ], - ..Default::default() - }; - let plan = pipe.plan(&dev, &state.shape()).expect("plan"); - let (set, binding, _) = table_write(&plan, Stage::Kernel); - let cmds = plan - .instantiate_dispatch(&state, &one_group()) - .expect("dispatch"); - let alpha = FLAG_OUT_OF_BOUNDS_ALPHA_ONE; - let class = |pf| { - crate::metal::texel_format::heap_class_index( - pf, - crate::metal::TextureSwizzleChannels::DEFAULT, - ) << FLAG_TEXEL_CLASS.trailing_zeros() - }; - let border = |pf| { - crate::metal::sampler::border_texels(pf, crate::metal::TextureSwizzleChannels::DEFAULT) - .expect("border texels") - << FLAG_BORDER_TEXELS.trailing_zeros() - }; - let (d16, d32, d32s8, rgba8) = ( - class(PixelFormat::Depth16Unorm), - class(PixelFormat::Depth32Float), - class(PixelFormat::Depth32FloatStencil8), - class(PixelFormat::RGBA8Unorm), - ); - assert!(d16 != 0 && d32 != 0 && rgba8 != 0 && d16 != rgba8); - // A depth format's border texel is `(b, b, b, 1)`, a four-channel one's the color itself. - let (depth, four) = ( - border(PixelFormat::Depth16Unorm), - border(PixelFormat::RGBA8Unorm), - ); - assert_eq!(depth >> 3, 0b111_100_100_100); - assert_eq!(four >> 3, 0b110_100_100_100); - assert_eq!( - entries(&cmds.descriptor_bytes, set, binding), - vec![ - (0, 0, 0), - (D, 4, rgba8 | four), - (A, 1, alpha | depth | d16), - (B, 2, alpha | depth | d32), - (C, 3, alpha | depth | d32s8), - ] - ); - let bytes = &cmds - .descriptor_bytes - .iter() - .find(|b| b.set == set && b.binding == binding) - .expect("bytes") - .bytes; - let keys = [D, A, B, C, 0, E]; - let flagged = Lookup::Flagged { - alpha: true, - class: false, - red_blue: false, - unreadable: false, - }; - let one = HANDLE_ALPHA_ONE; - assert_eq!( - emitted_lookup_in(bytes, &keys, flagged), - vec![4, 1 | one, 2 | one, 3 | one, 0, 0] - ); - let classes = Lookup::Flagged { - alpha: false, - class: true, - red_blue: false, - unreadable: false, - }; - assert_eq!( - emitted_lookup_in(bytes, &keys, classes), - vec![4 | rgba8, 1 | d16, 2 | d32, 3 | d32s8, 0, 0] - ); - let indexed = Lookup::Indexed { - alpha: true, - class: true, - red_blue: false, - unreadable: false, - }; - let entry = |k: u32| k << HANDLE_ENTRY.trailing_zeros(); - assert_eq!( - emitted_lookup_in(bytes, &keys, indexed), - vec![4 | entry(1), 1 | entry(2), 2 | entry(3), 3 | entry(4), 0, 0] - ); -} - -/// A heap texture sampled through a constexpr sampler reads a set-0 heap sampler: a `SAMPLER` -/// binding whose immutable sampler is the constexpr one, which the plan never writes. An -/// opaque-black border meets every member the sampled array holds, so an `ABGR4Unorm` member is -/// refused `SamplerBorderColor` on `moltenvk-m3`, which cannot keep that border exactly through its -/// view, as a slot sampled with that border is; without the border it is held. -#[test] -fn heap_samplers_take_no_write_and_meet_every_held_member() { - let dev = m3(); - let Some(bc) = assembled("handles", llvm_assemble(&engine_dir().join("handles.ll"))) else { - return; - }; - let sampler_bindings = |p: &ComputePipeline| -> Vec { - p.layout.sets[0] - .bindings - .iter() - .filter(|b| matches!(b.source, BindingSource::HeapSampler { .. })) - .inspect(|b| { - assert_eq!(b.ty, vk::DescriptorType::SAMPLER); - assert_eq!(b.count, 1); - assert!(b.immutable_sampler.is_some()); - }) - .map(|b| b.binding) - .collect() - }; - let state = |pf| BindState { - used_resources: vec![ - used(1, TextureType::Type2D, pf, read(), Some(A)), - used( - 2, - TextureType::Type2D, - PixelFormat::RGBA32Float, - TextureUsage::SHADER_WRITE, - Some(B), - ), - ], - ..Default::default() - }; - let copy = compute(&dev, &bc, "argument_buffer_sample"); - let samplers = sampler_bindings(©); - assert_eq!(samplers.len(), 2); - for pf in [PixelFormat::RGBA8Unorm, PixelFormat::ABGR4Unorm] { - let plan = copy.plan(&dev, &state(pf).shape()).expect("plan"); - assert!(plan - .descriptors - .iter() - .all(|d| d.set != 0 || !samplers.contains(&d.binding))); - // The sampled member is held by the sampled class. - let held = plan.descriptors.iter().any(|d| { - matches!( - d.source, - WriteSource::HeapEntry { - source: HeapSource::Used(1), - .. - } - ) - }); - assert!(held, "{pf:?}"); - } - let border = compute(&dev, &bc, "argument_buffer_sample_border"); - assert_eq!(sampler_bindings(&border).len(), 1); - border - .plan(&dev, &state(PixelFormat::RGBA8Unorm).shape()) - .expect("an exact border"); - match border.plan(&dev, &state(PixelFormat::ABGR4Unorm).shape()) { - Err(BindError::Unsupported(u)) => assert_eq!(u.feature, Feature::SamplerBorderColor), - other => panic!("{other:?}"), - } -} - -/// Constexpr samplers a lane chooses among beside a heap texture are one set-0 sampler array -/// (`BindingSource::SamplerArray`): a `SAMPLER` binding of one element per candidate whose -/// immutable samplers are, element by element, exactly the immutable sampler a heap texture sampled -/// through that candidate alone bakes, and which the plan never writes. -#[test] -fn a_constexpr_sampler_array_bakes_each_candidates_own_sampler() { - use super::engine_handles::{chosen_sampler_kernel, CHOSEN_SAMPLERS}; - let dev = m3(); - let Some(bc) = assemble("chosen", &chosen_sampler_kernel(&[0, 1, 2], None)) else { - return; - }; - let pipe = compute(&dev, &bc, "chosen"); - let set = &pipe.layout.sets[0].bindings; - assert!( - !set.iter() - .any(|b| matches!(b.source, BindingSource::HeapSampler { .. })), - "{set:?}" - ); - let arrays: Vec<_> = set - .iter() - .filter(|b| matches!(b.source, BindingSource::SamplerArray { .. })) - .collect(); - assert_eq!(arrays.len(), 1, "{set:?}"); - let array = arrays[0]; - assert_eq!( - array.source, - BindingSource::SamplerArray { - stage: Stage::Kernel, - compare: false, - integer: false, - } - ); - assert_eq!(array.ty, vk::DescriptorType::SAMPLER); - assert_eq!(array.count, 3); - assert_eq!(array.immutable_sampler, None); - // Each element is the sampler a heap sample through that candidate alone bakes. - let alone: Vec = (0..CHOSEN_SAMPLERS.len()) - .map(|i| { - let bc = assemble("chosen_alone", &chosen_sampler_kernel(&[i], None)) - .expect("assembled once already"); - let one = compute(&dev, &bc, "chosen"); - let heap: Vec<_> = (one.layout.sets[0].bindings.iter()) - .filter(|b| matches!(b.source, BindingSource::HeapSampler { .. })) - .collect(); - assert_eq!(heap.len(), 1, "sampler {i}"); - heap[0].immutable_sampler.expect("a constexpr heap sampler") - }) - .collect(); - assert_eq!(array.immutable_samplers, alone); - let state = BindState { - used_resources: vec![used( - 1, - TextureType::Type2D, - PixelFormat::R32Float, - read(), - Some(A), - )], - ..Default::default() - }; - let plan = pipe.plan(&dev, &state.shape()).expect("plan"); - assert!( - !plan - .descriptors - .iter() - .any(|d| d.set == 0 && d.binding == array.binding), - "the plan writes an immutable sampler array" - ); -} - -/// `argument_buffer_runtime_sampler` of the owned `handles` fixture samples a heap texture through -/// its runtime `[[sampler(0)]]`. Its set-0 heap sampler binding has no immutable sampler; the plan -/// writes it with the sampler bound at the kernel's slot 0, made for the use (no comparison, a -/// float texel), or the neutral sampler where none is bound. A bound opaque-black border meets -/// every member the sampled array holds, as a constexpr one does: an `ABGR4Unorm` member is refused -/// `SamplerBorderColor` on `moltenvk-m3`, an `RGBA8Unorm` one is held. -#[test] -fn a_runtime_heap_sampler_is_written_with_the_bound_sampler() { - let dev = m3(); - let Some(bc) = assembled("handles", llvm_assemble(&engine_dir().join("handles.ll"))) else { - return; - }; - let pipe = compute(&dev, &bc, "argument_buffer_runtime_sampler"); - let samplers: Vec<_> = pipe.layout.sets[0] - .bindings - .iter() - .filter(|b| matches!(b.source, BindingSource::HeapSampler { .. })) - .collect(); - assert_eq!(samplers.len(), 1); - let binding = samplers[0].binding; - assert_eq!(samplers[0].ty, vk::DescriptorType::SAMPLER); - assert!(samplers[0].immutable_sampler.is_none()); - let state = |pf, s: Option| { - let mut state = BindState { - used_resources: vec![used(1, TextureType::Type2D, pf, read(), Some(A))], - ..Default::default() - }; - let mut t = StageTable::default(); - if let Some(s) = s { - t.samplers.insert(0, s); - } - state.stages.insert(Stage::Kernel, t); - state - }; - let written = |plan: &BindingPlan| -> Vec { - plan.descriptors - .iter() - .filter(|d| d.set == 0 && d.binding == binding) - .map(|d| d.source.clone()) - .collect() - }; - let border = |color| { - let mut d = SamplerDescriptor::new(); - d.s_address_mode = SamplerAddressMode::ClampToBorderColor; - d.border_color = color; - BoundSampler::new(d) - }; - let s0 = SlotRef { - stage: Stage::Kernel, - class: SlotClass::Sampler, - index: 0, - }; - let plan = pipe - .plan( - &dev, - &state( - PixelFormat::RGBA8Unorm, - Some(BoundSampler::new(SamplerDescriptor::new())), - ) - .shape(), - ) - .expect("plan"); - assert_eq!( - written(&plan), - vec![WriteSource::Sampler { - slot: s0, - compare: false, - integer: false, - opaque_black: crate::metal::sampler::OpaqueBlackBorder::Stated, - }] - ); - let plan = pipe - .plan(&dev, &state(PixelFormat::RGBA8Unorm, None).shape()) - .expect("plan"); - assert_eq!( - written(&plan), - vec![WriteSource::Neutral(NeutralResource::Sampler { - compare: false - })] - ); - let black = border(SamplerBorderColor::OpaqueBlack); - pipe.plan(&dev, &state(PixelFormat::RGBA8Unorm, Some(black)).shape()) - .expect("an exact border"); - match pipe.plan(&dev, &state(PixelFormat::ABGR4Unorm, Some(black)).shape()) { - Err(BindError::Unsupported(u)) => assert_eq!(u.feature, Feature::SamplerBorderColor), - other => panic!("{other:?}"), - } - let clear = border(SamplerBorderColor::TransparentBlack); - pipe.plan(&dev, &state(PixelFormat::ABGR4Unorm, Some(clear)).shape()) - .expect("a transparent border"); -} - -/// A heap sampler that filters linearly meets every member of its stage that a sampled float array -/// holds, so each such member's view format must have the filter features it needs, as a combined -/// pair's texture must. On every committed profile with the sampled heap, an `R32Float` member is -/// refused `Unsupported{Format}` naming `SampledImageFilterLinear` of `R32_SFLOAT` exactly where -/// the profile lacks it, through the constexpr linear sampler of `argument_buffer_sample` and -/// through a bound linear runtime sampler of `argument_buffer_runtime_sampler`. A nearest or -/// unbound runtime sampler (the neutral sampler filters nearest) plans everywhere, and so does an -/// `RGBA8Unorm` member, whose linear filtering Vulkan requires. -#[test] -fn heap_samplers_need_the_filter_features_of_every_held_member() { - let Some(bc) = assembled("handles", llvm_assemble(&engine_dir().join("handles.ll"))) else { - return; - }; - let state = |pf, s: Option| { - let mut state = BindState { - used_resources: vec![used(1, TextureType::Type2D, pf, read(), Some(A))], - ..Default::default() - }; - let mut t = StageTable::default(); - if let Some(s) = s { - t.samplers.insert(0, s); - } - state.stages.insert(Stage::Kernel, t); - state - }; - let sampler = |filter| { - let mut d = SamplerDescriptor::new(); - d.min_filter = filter; - d.mag_filter = filter; - BoundSampler::new(d) - }; - let linear = Some(sampler(SamplerMinMagFilter::Linear)); - let nearest = Some(sampler(SamplerMinMagFilter::Nearest)); - let missing = Unsupported::needs( - Feature::Format, - Capability::Format { - format: vk::Format::R32_SFLOAT, - usage: FormatUsage::SampledImageFilterLinear, - }, - ); - let (mut refused, mut passed) = (0, 0); - for (stem, p) in crate::spirv::testing::committed_profiles().expect("profiles") { - 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 desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); - let dev = Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device"); - let lib = Library::from_air(&bc).expect("library"); - let filters = p.supports_format( - vk::Format::R32_SFLOAT, - FormatUsage::SampledImageFilterLinear, - ); - for (entry, linear) in [ - ("argument_buffer_sample", None), - ("argument_buffer_runtime_sampler", linear), - ] { - let f = lib.function(entry).expect("entry"); - let d = - ComputePipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new(f))); - let Ok(pipe) = dev.compile_compute_pipeline(&d, &Budget::standard()) else { - continue; - }; - let what = format!("{entry} on {stem}"); - match pipe.plan(&dev, &state(PixelFormat::R32Float, linear).shape()) { - Ok(_) => { - assert!(filters, "{what} planned without linear filtering"); - passed += 1; - } - Err(BindError::Unsupported(u)) => { - assert!(!filters, "{what}: {u:?}"); - assert_eq!(u, missing, "{what}"); - refused += 1; - } - Err(e) => panic!("{what}: {e}"), - } - pipe.plan(&dev, &state(PixelFormat::RGBA8Unorm, linear).shape()) - .unwrap_or_else(|e| panic!("{what} RGBA8Unorm: {e}")); - if entry == "argument_buffer_runtime_sampler" { - for s in [nearest, None] { - pipe.plan(&dev, &state(PixelFormat::R32Float, s).shape()) - .unwrap_or_else(|e| panic!("{what} {s:?}: {e}")); - } - } - } - } - assert!( - refused > 0 && passed > 0, - "refused {refused}, passed {passed}" - ); -} - -/// Two kernels whose texture slot 0 may also be a heap member: `slot_write_heap_read` writes -/// `[[texture(0)]]` and reads a texture from an argument buffer; `slot_read_heap_write` reads -/// `[[texture(0)]]` and writes a texture from an argument buffer. -const SLOT_AND_HEAP_KERNELS: &str = r#"%struct.T = type { ptr addrspace(1) } -%struct.R = type { %struct.T } -define void @slot_write_heap_read(ptr addrspace(1) %o, ptr addrspace(2) %r, i32 %gid) { - %pt = getelementptr inbounds %struct.R, ptr addrspace(2) %r, i64 0, i32 0, i32 0 - %t = load ptr addrspace(1), ptr addrspace(2) %pt, align 8 - %s = tail call ptr addrspace(2) @air.get_read_sampler() - %c = insertelement <2 x i32> zeroinitializer, i32 %gid, i64 0 - %v = call { <4 x float>, i8 } @air.read_texture_2d.v4f32(ptr addrspace(1) %t, ptr addrspace(2) %s, <2 x i32> %c, <2 x i32> zeroinitializer, i32 0, i32 0) - %x = extractvalue { <4 x float>, i8 } %v, 0 - call void @air.write_texture_2d.v4f32(ptr addrspace(1) %o, <2 x i32> %c, <4 x float> %x, i32 0, i32 2) - ret void -} -define void @slot_read_heap_write(ptr addrspace(1) %i, ptr addrspace(2) %r, i32 %gid) { - %s = tail call ptr addrspace(2) @air.get_read_sampler() - %c = insertelement <2 x i32> zeroinitializer, i32 %gid, i64 0 - %v = call { <4 x float>, i8 } @air.read_texture_2d.v4f32(ptr addrspace(1) %i, ptr addrspace(2) %s, <2 x i32> %c, <2 x i32> zeroinitializer, i32 0, i32 0) - %x = extractvalue { <4 x float>, i8 } %v, 0 - %pt = getelementptr inbounds %struct.R, ptr addrspace(2) %r, i64 0, i32 0, i32 0 - %t = load ptr addrspace(1), ptr addrspace(2) %pt, align 8 - call void @air.write_texture_2d.v4f32(ptr addrspace(1) %t, <2 x i32> %c, <4 x float> %x, i32 0, i32 2) - ret void -} -declare ptr addrspace(2) @air.get_read_sampler() -declare { <4 x float>, i8 } @air.read_texture_2d.v4f32(ptr addrspace(1), ptr addrspace(2), <2 x i32>, <2 x i32>, i32, i32) -declare void @air.write_texture_2d.v4f32(ptr addrspace(1), <2 x i32>, <4 x float>, i32, i32) -!air.kernel = !{!0, !10} -!air.version = !{!8} -!air.language_version = !{!9} -!0 = !{ptr @slot_write_heap_read, !1, !2} -!1 = !{} -!2 = !{!3, !4, !7} -!3 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.write", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"o"} -!4 = !{i32 1, !"air.indirect_buffer", !"air.buffer_size", i32 8, !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.struct_type_info", !5, !"air.arg_type_size", i32 8, !"air.arg_type_align_size", i32 8, !"air.arg_type_name", !"R", !"air.arg_name", !"r"} -!5 = !{i32 0, i32 8, i32 0, !"texture2d", !"t", !"air.indirect_argument", !6} -!6 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.read", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"t"} -!7 = !{i32 2, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"gid"} -!8 = !{i32 2, i32 8, i32 0} -!9 = !{!"Metal", i32 4, i32 0, i32 0} -!10 = !{ptr @slot_read_heap_write, !1, !11} -!11 = !{!12, !13, !7} -!12 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.read", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"i"} -!13 = !{i32 1, !"air.indirect_buffer", !"air.buffer_size", i32 8, !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.struct_type_info", !14, !"air.arg_type_size", i32 8, !"air.arg_type_align_size", i32 8, !"air.arg_type_name", !"R", !"air.arg_name", !"r"} -!14 = !{i32 0, i32 8, i32 0, !"texture2d", !"t", !"air.indirect_argument", !15} -!15 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.write", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"t"} -"#; - -/// The layout of `slot`'s own write in `plan`, with its descriptor type. -fn slot_layout(plan: &BindingPlan, s: SlotRef) -> (vk::DescriptorType, vk::ImageLayout) { - let mut found = plan.descriptors.iter().filter_map(|d| match &d.source { - WriteSource::Texture { slot, view } if *slot == s => Some((d.ty, view.layout)), - _ => None, - }); - let one = found.next().expect("the slot's write"); - assert!(found.next().is_none(), "one write of {s:?}"); - one -} - -/// The uses of `s` in `plan`. -fn slot_uses(plan: &BindingPlan, s: SlotRef) -> Vec<&ResourceUse> { - plan.uses - .iter() - .filter(|u| u.resource == UseTarget::Slot(s)) - .collect() -} - -/// A texture bound at a slot and held by a heap array has one layout in every write of it: -/// `GENERAL` when the slot's own binding is a storage image (the heap's sampled element follows -/// it) or a storage heap array holds it (the slot's sampled view follows it). The plan uses the -/// slot once, widened to the heap's access; a texture no storage view reaches keeps its sampled -/// layout. -#[test] -fn a_bound_member_shares_its_slots_layout() { - let dev = m3(); - let Some(bc) = assemble("slot_and_heap", SLOT_AND_HEAP_KERNELS) else { - return; - }; - let s0 = slot(Stage::Kernel, 0); - let state = |usage: TextureUsage| { - let mut facts = TextureFacts::new(TextureType::Type2D, PixelFormat::RGBA8Unorm); - facts.usage = usage; - let mut k = StageTable::default(); - k.textures.insert( - 0, - BoundTexture::Texture { - facts, - resource_id: Some(A), - }, - ); - let mut state = BindState::default(); - state.stages.insert(Stage::Kernel, k); - state - }; - let rw = TextureUsage::SHADER_READ | TextureUsage::SHADER_WRITE; - let general = vk::ImageLayout::GENERAL; - let rgba = vk::Format::R8G8B8A8_UNORM; - - // A storage slot and a sampled heap: the heap element follows the slot. - let pipe = compute(&dev, &bc, "slot_write_heap_read"); - let st = state(rw); - let plan = pipe.plan(&dev, &st.shape()).expect("plan"); - assert_eq!( - slot_layout(&plan, s0), - (vk::DescriptorType::STORAGE_IMAGE, general) - ); - let w = heap_writes(&plan); - assert_eq!( - w.iter().map(|x| held(x)).collect::>(), - vec![None, Some((HeapSource::Bound(s0), rgba, general))] - ); - match slot_uses(&plan, s0).as_slice() { - [u] => { - assert!(u.access.read && u.access.write, "{u:?}"); - assert_eq!(u.class, AccessClass::StorageImage); - } - other => panic!("{other:?}"), - } - let cmds = plan - .instantiate_dispatch( - &st, - &Dispatch::Threadgroups { - groups: [1, 1, 1], - threads_per_group: [1, 1, 1], - }, - ) - .expect("dispatch"); - let (set, binding, _) = table_write(&plan, Stage::Kernel); - assert_eq!( - table(&cmds.descriptor_bytes, set, binding), - vec![(0, 0), (A, 1)] - ); - - // A sampled slot and a storage heap holding the texture: the slot follows the heap. - let pipe = compute(&dev, &bc, "slot_read_heap_write"); - let plan = pipe.plan(&dev, &state(rw).shape()).expect("plan"); - assert_eq!( - slot_layout(&plan, s0), - (vk::DescriptorType::SAMPLED_IMAGE, general) - ); - assert_eq!( - heap_writes(&plan) - .iter() - .map(|x| held(x)) - .collect::>(), - vec![None, Some((HeapSource::Bound(s0), rgba, general))] - ); - match slot_uses(&plan, s0).as_slice() { - [u] => { - assert!(u.access.read && u.access.write, "{u:?}"); - assert_eq!(u.class, AccessClass::StorageImage); - } - other => panic!("{other:?}"), - } - - // A read-only texture: the storage heap cannot hold it, so nothing makes it `GENERAL`. - let plan = pipe - .plan(&dev, &state(TextureUsage::SHADER_READ).shape()) - .expect("plan"); - assert_eq!( - slot_layout(&plan, s0), - ( - vk::DescriptorType::SAMPLED_IMAGE, - vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL - ) - ); - assert_eq!( - heap_writes(&plan) - .iter() - .map(|x| held(x)) - .collect::>(), - vec![None, None] - ); - match slot_uses(&plan, s0).as_slice() { - [u] => { - assert!(u.access.read && !u.access.write, "{u:?}"); - assert_eq!(u.class, AccessClass::Sampled); - } - other => panic!("{other:?}"), - } -} - -const RENDER: &str = r#"%struct.T = type { ptr addrspace(1) } -%struct.R = type { %struct.T } -define <{ <4 x float> }> @heap_vertex(i32 noundef %vid, ptr addrspace(2) %r) { - %pt = getelementptr inbounds %struct.R, ptr addrspace(2) %r, i64 0, i32 0, i32 0 - %t = load ptr addrspace(1), ptr addrspace(2) %pt, align 8 - %s = tail call ptr addrspace(2) @air.get_read_sampler() - %c = insertelement <2 x i32> zeroinitializer, i32 %vid, i64 0 - %v = call { <4 x float>, i8 } @air.read_texture_2d.v4f32(ptr addrspace(1) %t, ptr addrspace(2) %s, <2 x i32> %c, <2 x i32> zeroinitializer, i32 0, i32 0) - %p = extractvalue { <4 x float>, i8 } %v, 0 - %o = insertvalue <{ <4 x float> }> undef, <4 x float> %p, 0 - ret <{ <4 x float> }> %o -} -define <4 x float> @heap_fragment(<4 x float> noundef %pos, ptr addrspace(2) %r) { - %pt = getelementptr inbounds %struct.R, ptr addrspace(2) %r, i64 0, i32 0, i32 0 - %t = load ptr addrspace(1), ptr addrspace(2) %pt, align 8 - %s = tail call ptr addrspace(2) @air.get_read_sampler() - %v = call { <4 x float>, i8 } @air.read_texture_2d.v4f32(ptr addrspace(1) %t, ptr addrspace(2) %s, <2 x i32> zeroinitializer, <2 x i32> zeroinitializer, i32 0, i32 0) - %c = extractvalue { <4 x float>, i8 } %v, 0 - ret <4 x float> %c -} -declare ptr addrspace(2) @air.get_read_sampler() -declare { <4 x float>, i8 } @air.read_texture_2d.v4f32(ptr addrspace(1), ptr addrspace(2), <2 x i32>, <2 x i32>, i32, i32) -!air.vertex = !{!20} -!air.fragment = !{!0} -!air.version = !{!9} -!air.language_version = !{!10} -!0 = !{ptr @heap_fragment, !1, !2} -!1 = !{!11} -!11 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"float4"} -!2 = !{!12, !3} -!12 = !{i32 0, !"air.position", !"air.center", !"air.no_perspective", !"air.arg_type_name", !"float4", !"air.arg_name", !"pos"} -!3 = !{i32 1, !"air.indirect_buffer", !"air.buffer_size", i32 8, !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.struct_type_info", !4, !"air.arg_type_size", i32 8, !"air.arg_type_align_size", i32 8, !"air.arg_type_name", !"R", !"air.arg_name", !"r"} -!4 = !{i32 0, i32 8, i32 0, !"texture2d", !"t", !"air.indirect_argument", !5} -!5 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.read", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"t"} -!9 = !{i32 2, i32 8, i32 0} -!10 = !{!"Metal", i32 4, i32 0, i32 0} -!20 = !{ptr @heap_vertex, !21, !23} -!21 = !{!22} -!22 = !{!"air.position", !"air.arg_type_name", !"float4", !"air.arg_name", !"position"} -!23 = !{!24, !25} -!24 = !{i32 0, !"air.vertex_id", !"air.arg_type_name", !"uint", !"air.arg_name", !"vid"} -!25 = !{i32 1, !"air.indirect_buffer", !"air.buffer_size", i32 8, !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.struct_type_info", !4, !"air.arg_type_size", i32 8, !"air.arg_type_align_size", i32 8, !"air.arg_type_name", !"R", !"air.arg_name", !"r"} -"#; - -fn render(dev: &Device) -> Option { - let bc = assemble("heap_render", RENDER)?; - let lib = Library::from_air(&bc).expect("library"); - let v = lib.function("heap_vertex").expect("vertex"); - let f = lib.function("heap_fragment").expect("fragment"); - let mut d = RenderPipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new(v))); - d.fragment = Some(StageSource::Function(FunctionDescriptor::new(f))); - d.color_attachments[0] = Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm)); - Some( - dev.compile_render_pipeline(&d, &Budget::standard()) - .expect("render pipeline"), - ) -} - -/// A render heap: both stages share the members' elements in the one array, and each stage's -/// table enters the members that reach it (a used texture's render stages, a bound texture's own -/// stage); a used texture of no render stage is no member. -#[test] -fn render_stages_share_the_heap_and_keep_their_tables() { - let dev = m3(); - let Some(pipe) = render(&dev) else { - return; - }; - let tex = |token, stages, id| { - let mut u = used( - token, - TextureType::Type2D, - PixelFormat::RGBA8Unorm, - read(), - Some(id), - ); - u.stages = stages; - u - }; - let mut state = BindState { - used_resources: vec![ - tex(1, RenderStages::VERTEX, A), - tex(2, RenderStages::FRAGMENT, B), - tex(3, RenderStages::VERTEX | RenderStages::FRAGMENT, C), - tex(4, RenderStages::empty(), D), - ], - ..Default::default() - }; - let mut v = StageTable::default(); - v.textures - .insert(0, bound(PixelFormat::RGBA8Unorm, Some(E))); - state.stages.insert(Stage::Vertex, v); - let mut f = StageTable::default(); - f.textures - .insert(2, bound(PixelFormat::RGBA8Unorm, Some(F))); - state.stages.insert(Stage::Fragment, f); - - let plan = pipe.plan(&dev, &state.shape()).expect("plan"); - // Members: tokens 1, 2, 3 (elements 1..=3), vertex [[texture(0)]] (4), fragment - // [[texture(2)]] (5). - let w = heap_writes(&plan); - assert_eq!( - w.iter().map(|x| held(x).map(|h| h.0)).collect::>(), - vec![ - None, - Some(HeapSource::Used(1)), - Some(HeapSource::Used(2)), - Some(HeapSource::Used(3)), - Some(HeapSource::Bound(slot(Stage::Vertex, 0))), - Some(HeapSource::Bound(slot(Stage::Fragment, 2))), - ] - ); - let vt = table_write(&plan, Stage::Vertex); - let ft = table_write(&plan, Stage::Fragment); - assert_ne!((vt.0, vt.1), (ft.0, ft.1)); - assert_eq!(vt.2, 4 * TABLE_ENTRY_BYTES); - assert_eq!(ft.2, 4 * TABLE_ENTRY_BYTES); - let cmds = plan - .instantiate_draw( - &state, - &DrawCall::Primitives { - vertex_start: 0, - vertex_count: 3, - instance_count: 1, - base_instance: 0, - }, - ) - .expect("draw"); - let vertex = table(&cmds.descriptor_bytes, vt.0, vt.1); - let fragment = table(&cmds.descriptor_bytes, ft.0, ft.1); - assert_eq!(vertex, vec![(0, 0), (A, 1), (C, 3), (E, 4)]); - assert_eq!(fragment, vec![(0, 0), (B, 2), (C, 3), (F, 5)]); - // A texture resident for the other stage only misses (Metal's residency is per stage). - assert_eq!(lookup_host(&vertex, B), 0); - assert_eq!(lookup_host(&fragment, A), 0); - assert_eq!(lookup_host(&vertex, D), 0); -} - -/// Two kernels over one argument-buffer member that only the MSL type name calls an integer -/// texture: `heap_query` only queries it, `heap_query_read` also reads it as `uint`. -const QUERY_KERNELS: &str = r#"%struct.T = type { ptr addrspace(1) } -%struct.R = type { %struct.T } -define void @heap_query(ptr addrspace(2) %r, ptr addrspace(1) %out, i32 %gid) { - %pt = getelementptr inbounds %struct.R, ptr addrspace(2) %r, i64 0, i32 0, i32 0 - %t = load ptr addrspace(1), ptr addrspace(2) %pt, align 8 - %w = call i32 @air.get_width_texture_2d(ptr addrspace(1) %t, i32 0) - %o = getelementptr inbounds i32, ptr addrspace(1) %out, i32 %gid - store i32 %w, ptr addrspace(1) %o, align 4 - ret void -} -define void @heap_query_read(ptr addrspace(2) %r, ptr addrspace(1) %out, i32 %gid) { - %pt = getelementptr inbounds %struct.R, ptr addrspace(2) %r, i64 0, i32 0, i32 0 - %t = load ptr addrspace(1), ptr addrspace(2) %pt, align 8 - %w = call i32 @air.get_width_texture_2d(ptr addrspace(1) %t, i32 0) - %t2 = load ptr addrspace(1), ptr addrspace(2) %pt, align 8 - %s = tail call ptr addrspace(2) @air.get_read_sampler() - %c = insertelement <2 x i32> zeroinitializer, i32 %gid, i64 0 - %v = call { <4 x i32>, i8 } @air.read_texture_2d.u.v4i32(ptr addrspace(1) %t2, ptr addrspace(2) %s, <2 x i32> %c, <2 x i32> zeroinitializer, i32 0, i32 0) - %x4 = extractvalue { <4 x i32>, i8 } %v, 0 - %x = extractelement <4 x i32> %x4, i64 0 - %sum = add i32 %w, %x - %o = getelementptr inbounds i32, ptr addrspace(1) %out, i32 %gid - store i32 %sum, ptr addrspace(1) %o, align 4 - ret void -} -declare ptr addrspace(2) @air.get_read_sampler() -declare i32 @air.get_width_texture_2d(ptr addrspace(1), i32) -declare { <4 x i32>, i8 } @air.read_texture_2d.u.v4i32(ptr addrspace(1), ptr addrspace(2), <2 x i32>, <2 x i32>, i32, i32) -!air.kernel = !{!0, !11} -!air.version = !{!9} -!air.language_version = !{!10} -!0 = !{ptr @heap_query, !1, !2} -!1 = !{} -!2 = !{!3, !7, !8} -!3 = !{i32 0, !"air.indirect_buffer", !"air.buffer_size", i32 8, !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.struct_type_info", !4, !"air.arg_type_size", i32 8, !"air.arg_type_align_size", i32 8, !"air.arg_type_name", !"R", !"air.arg_name", !"r"} -!4 = !{i32 0, i32 8, i32 0, !"texture2d", !"t", !"air.indirect_argument", !5} -!5 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.read", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"t"} -!7 = !{i32 1, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"out"} -!8 = !{i32 2, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"gid"} -!9 = !{i32 2, i32 8, i32 0} -!10 = !{!"Metal", i32 4, i32 0, i32 0} -!11 = !{ptr @heap_query_read, !1, !2} -"#; - -/// An integer texture in a query-only heap group: its class is the `Float` default -/// (`RuntimeFact::HeapNumericType`), so the texture's element is the neutral and the plan reports -/// it (`IncompatibleHeapEntry`), as a slot reports an incompatible binding; a `float` texture is -/// held. Where a read of the member types the group, the integer texture is held and nothing is -/// reported. -#[test] -fn an_integer_texture_in_a_query_only_group_is_reported() { - let dev = m3(); - let Some(bc) = assemble("heap_query", QUERY_KERNELS) else { - return; - }; - let state = BindState { - used_resources: vec![ - used( - 1, - TextureType::Type2D, - PixelFormat::R32Uint, - read(), - Some(A), - ), - used( - 2, - TextureType::Type2D, - PixelFormat::RGBA8Unorm, - read(), - Some(B), - ), - // Another texture type: another class's, not reported. - used( - 3, - TextureType::Type3D, - PixelFormat::R32Uint, - read(), - Some(C), - ), - ], - ..Default::default() - }; - let pipe = compute(&dev, &bc, "heap_query"); - let plan = pipe.plan(&dev, &state.shape()).expect("plan"); - let w = heap_writes(&plan); - assert_eq!( - w.iter().map(|x| held(x).map(|h| h.0)).collect::>(), - vec![None, None, Some(HeapSource::Used(2)), None] - ); - let WriteSource::Neutral(neutral) = w[1] else { - panic!("element 1 {:?}", w[1]); - }; - match plan.diagnostics.as_slice() { - [PlanDiagnostic::IncompatibleHeapEntry { - class: HandleClass::Image(c), - element: 1, - source: HeapSource::Used(1), - substituted, - }] => { - assert_eq!(c.sampled_type, SampledType::Float); - assert_eq!(substituted, neutral); - } - other => panic!("{other:?}"), - } - - let pipe = compute(&dev, &bc, "heap_query_read"); - let plan = pipe.plan(&dev, &state.shape()).expect("plan"); - assert_eq!( - heap_writes_of(&plan, SampledType::Uint) - .iter() - .map(|x| held(x).map(|h| h.0)) - .collect::>(), - vec![None, Some(HeapSource::Used(1)), None, None] - ); - assert!(plan.diagnostics.is_empty(), "{:?}", plan.diagnostics); -} - -/// The heap classes a function declares. -fn heap_classes_of(a: &FunctionArtifact) -> Vec { - a.interface - .descriptors - .iter() - .filter_map(|d| match d.slot.kind { - ResourceKind::Heap(HandleClass::Image(c)) => Some(c), - _ => None, - }) - .collect() -} - -/// A heap group that is only queried has no texel class: its array is declared `Float`, and -/// `RuntimeFact::HeapNumericType` says so. A load of the same member that is read types every -/// group loaded from it: the member has one declared type. -#[test] -fn a_member_read_anywhere_types_its_queries() { - let Some(bc) = assemble("heap_query", QUERY_KERNELS) else { - return; - }; - let p = profile("moltenvk-m3", DevicePolicy::RESIDENT_TABLES).expect("profile"); - let a = compile(&bc, "heap_query", &p).expect("heap_query"); - link_and_validate(&a, &p).expect("L3"); - let classes = heap_classes_of(&a); - // The float class, and its unsigned integer twin, which a member of a form a heap reads is - // queried through. - assert_eq!(classes.len(), 2); - assert_eq!(classes[0].sampled_type, SampledType::Float); - assert_eq!( - classes[1], - ImageHandleClass { - sampled_type: SampledType::Uint, - ..classes[0] - } - ); - assert!(a - .facts - .contains(&RuntimeFact::HeapNumericType { class: classes[0] })); - - let a = compile(&bc, "heap_query_read", &p).expect("heap_query_read"); - link_and_validate(&a, &p).expect("L3"); - assert_eq!( - a.strategies - .entries - .get("access.handle.lookup") - .map_or(0, |u| u.uses), - 2 - ); - // Both loads of the member share the unsigned integer class; the read and the query read a - // member of another numeric class through its shape's class of that type. - let mut classes = heap_classes_of(&a); - classes.sort_by_key(|c| c.sampled_type); - assert_eq!( - classes, - [SampledType::Float, SampledType::Sint, SampledType::Uint].map(|sampled_type| { - ImageHandleClass { - sampled_type, - ..classes[0] - } - }), - "both loads of the member share one class" - ); - assert!(!a - .facts - .iter() - .any(|f| matches!(f, RuntimeFact::HeapNumericType { .. }))); -} - -/// Two kernels that only query an argument buffer's texture: `abq_2d` a `texture2d`'s -/// width, `abq_cube_array` a `texturecube_array`'s array size. -const QUERY_ONLY_KERNELS: &str = r#"%struct.Q = type { ptr addrspace(1) } -define void @abq_2d(ptr addrspace(2) %q, ptr addrspace(1) %out, i32 %gid) { - %pt = getelementptr inbounds %struct.Q, ptr addrspace(2) %q, i64 0, i32 0 - %t = load ptr addrspace(1), ptr addrspace(2) %pt, align 8 - %w = call i32 @air.get_width_texture_2d(ptr addrspace(1) %t, i32 0) - %o = getelementptr inbounds i32, ptr addrspace(1) %out, i32 %gid - store i32 %w, ptr addrspace(1) %o, align 4 - ret void -} -define void @abq_cube_array(ptr addrspace(2) %q, ptr addrspace(1) %out, i32 %gid) { - %pt = getelementptr inbounds %struct.Q, ptr addrspace(2) %q, i64 0, i32 0 - %t = load ptr addrspace(1), ptr addrspace(2) %pt, align 8 - %n = call i32 @air.get_array_size_texture_cube_array(ptr addrspace(1) %t) - %o = getelementptr inbounds i32, ptr addrspace(1) %out, i32 %gid - store i32 %n, ptr addrspace(1) %o, align 4 - ret void -} -declare i32 @air.get_width_texture_2d(ptr addrspace(1), i32) -declare i32 @air.get_array_size_texture_cube_array(ptr addrspace(1)) -!air.kernel = !{!0, !9} -!air.version = !{!7} -!air.language_version = !{!8} -!0 = !{ptr @abq_2d, !1, !2} -!1 = !{} -!2 = !{!3, !5, !6} -!3 = !{i32 0, !"air.indirect_buffer", !"air.buffer_size", i32 8, !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.struct_type_info", !4, !"air.arg_type_size", i32 8, !"air.arg_type_align_size", i32 8, !"air.arg_type_name", !"Q", !"air.arg_name", !"q"} -!4 = !{i32 0, i32 8, i32 0, !"texture2d", !"t", !"air.indirect_argument", !12} -!5 = !{i32 1, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"out"} -!6 = !{i32 2, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"gid"} -!7 = !{i32 2, i32 8, i32 0} -!8 = !{!"Metal", i32 4, i32 0, i32 0} -!9 = !{ptr @abq_cube_array, !1, !10} -!10 = !{!11, !5, !6} -!11 = !{i32 0, !"air.indirect_buffer", !"air.buffer_size", i32 8, !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.struct_type_info", !13, !"air.arg_type_size", i32 8, !"air.arg_type_align_size", i32 8, !"air.arg_type_name", !"Q", !"air.arg_name", !"q"} -!12 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.sample", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"t"} -!13 = !{i32 0, i32 8, i32 0, !"texturecube_array", !"t", !"air.indirect_argument", !14} -!14 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.sample", !"air.arg_type_name", !"texturecube_array", !"air.arg_name", !"t"} -"#; - -/// Under the identity domains, an argument buffer's texture that a kernel only queries is -/// refused, whatever its shape: its group has no texel class, and the identity domains source no -/// `RuntimeFact::HeapNumericType`. Each kernel of [`QUERY_ONLY_KERNELS`] is -/// `Unsupported{IdentityDomains}`, not implemented, naming that fact of its member's shape, on -/// every profile the identity domains derive. -#[test] -fn a_query_only_argument_buffer_texture_is_refused_naming_its_numeric_type() { - let Some(bc) = assemble("query_only", QUERY_ONLY_KERNELS) else { - return; - }; - let profiles = identity_profiles(); - assert!( - !profiles.is_empty(), - "no profile the identity domains derive" - ); - let form = "state of a bound texture or sampler beyond its resource ID (HeapNumericType {"; - for (stem, p) in profiles { - for (entry, shape) in [ - ("abq_2d", "dim: D2, arrayed: false"), - ("abq_cube_array", "dim: Cube, arrayed: true"), - ] { - let Err(Error::Unsupported(u)) = compile(&bc, entry, &p) else { - panic!("{stem}: {entry}: not refused"); - }; - assert_eq!( - (u.feature, u.needs), - (Feature::IdentityDomains, Needs::NotImplemented), - "{stem}: {entry}" - ); - let symbol = u.symbol.map(|s| s.to_string()).unwrap_or_default(); - assert!( - symbol.starts_with(form) && symbol.contains(shape), - "{stem}: {entry}: {symbol}" - ); - } - } -} - -/// An entry of the owned `tail_argument_samplers` fixture on `dev`. -fn argument_sampler_pipeline(dev: &Device, entry: &str) -> Option { - let bc = assembled( - "tail_argument_samplers", - llvm_assemble(&engine_dir().join("tail_argument_samplers.ll")), - )?; - Some(compute(dev, &bc, entry)) -} - -/// An argument sampler of `desc` whose resource id is `id`. -fn argument_sampler(desc: SamplerDescriptor, id: u64) -> ArgumentSampler { - ArgumentSampler::new(desc, id) -} - -/// A pixel-coordinate sampler (nearest, clamp to edge). -fn pixel_sampler() -> SamplerDescriptor { - let mut d = SamplerDescriptor::new(); - d.normalized_coordinates = false; - d -} - -/// A bind state with the used `RGBA8Unorm` texture `A` (token 1) and the argument samplers -/// `samplers`. -fn sampler_state(samplers: Vec) -> BindState { - BindState { - used_resources: vec![used( - 1, - TextureType::Type2D, - PixelFormat::RGBA8Unorm, - read(), - Some(A), - )], - argument_samplers: samplers, - ..Default::default() - } -} - -/// A set-1 sampler array's binding and its use `(compare, integer)`. -type SamplerArray = (u32, (bool, bool)); - -/// The bindings and uses of the pipeline's set-1 sampler arrays, and the `(set, binding)` of its -/// sampler table. -fn sampler_layout(p: &ComputePipeline) -> (Vec, (u32, u32)) { - let arrays = p.layout.sets[1] - .bindings - .iter() - .filter_map(|b| match b.source { - BindingSource::Heap(HandleClass::Sampler { compare, integer }) => { - assert_eq!(b.ty, vk::DescriptorType::SAMPLER); - assert_eq!(b.flags, super::engine_handles::heap_flags(&p.requirements)); - Some((b.binding, (compare, integer))) - } - _ => None, - }) - .collect(); - let table = p.layout.sets[0] - .bindings - .iter() - .find(|b| { - matches!( - b.source, - BindingSource::Synthetic { - binding: SyntheticBinding::SamplerTable, - .. - } - ) - }) - .map(|b| (0, b.binding)) - .expect("a sampler table"); - (arrays, table) -} - -/// The writes of the set-1 sampler array at `binding`, by element. -fn sampler_writes(plan: &BindingPlan, binding: u32) -> Vec { - let mut w: Vec<_> = plan - .descriptors - .iter() - .filter(|d| d.set == 1 && d.binding == binding) - .collect(); - w.sort_by_key(|d| d.array_element); - for (e, d) in w.iter().enumerate() { - assert_eq!(d.array_element as usize, e, "one write per element"); - assert_eq!(d.ty, vk::DescriptorType::SAMPLER); - } - w.into_iter().map(|d| d.source.clone()).collect() -} - -/// The entries `(id, element, flags)` of the sampler table at `(set, binding)` in `bytes`: a -/// sampler's flags are its word, within [`SamplerWord::FIELDS`]. -fn sampler_entries(bytes: &[DescriptorBytes], set: u32, binding: u32) -> Vec<(u64, u32, u32)> { - let b = &bytes - .iter() - .find(|b| b.set == set && b.binding == binding) - .expect("sampler table bytes") - .bytes; - b.chunks(TABLE_ENTRY_BYTES as usize) - .map(|e| { - let w = |i: usize| u32::from_le_bytes(e[4 * i..4 * i + 4].try_into().expect("word")); - let id = u64::from(w(0)) | (u64::from(w(1)) << 32); - assert_eq!(w(3) & !SamplerWord::FIELDS, 0, "other bits are reserved"); - (id, w(2), w(3)) - }) - .collect() -} - -fn one_group() -> Dispatch { - Dispatch::Threadgroups { - groups: [1, 1, 1], - threads_per_group: [1, 1, 1], - } -} - -/// A sampler loaded from an argument buffer reads the set-1 sampler array of its use at the element -/// its sampler table gives. The plan writes element 0 of each array with the use's neutral sampler -/// and every other element of twice the shape's capacity class (32 entries for up to 15 samplers) -/// with `ArgumentSampler` of that listed sampler, made for the use; the sampler table is a handle -/// table of as many entries. Per dispatch its bytes list each listed sampler's nonzero id with its -/// element and its state word, deduplicated and sorted after leading null entries, and the emitted -/// search's entry form finds each id's entry, the last null entry for the null id and the first (0) -/// for any other id. An integer texel or a comparison reads the array of its own use. -#[test] -fn argument_samplers_fill_their_arrays_and_tables() { - let dev = m3(); - let Some(pipe) = argument_sampler_pipeline(&dev, "argument_sampler_sample") else { - return; - }; - let (arrays, (tset, tbinding)) = sampler_layout(&pipe); - assert_eq!(arrays.len(), 1); - let (binding, use_) = arrays[0]; - assert_eq!(use_, (false, false)); - let linear = { - let mut d = SamplerDescriptor::new(); - d.min_filter = crate::metal::SamplerMinMagFilter::Linear; - d.mag_filter = crate::metal::SamplerMinMagFilter::Linear; - d - }; - // The second sampler's id repeats the first's (one sampler listed twice), the third has no - // id, and the fourth uses pixel coordinates. - let state = sampler_state(vec![ - argument_sampler(linear, C), - argument_sampler(linear, C), - argument_sampler(SamplerDescriptor::new(), 0), - argument_sampler(pixel_sampler(), B), - ]); - let plan = pipe.plan(&dev, &state.shape()).expect("plan"); - let writes = sampler_writes(&plan, binding); - assert_eq!(writes.len(), 32); - assert_eq!( - writes[0], - WriteSource::Neutral(NeutralResource::Sampler { compare: false }) - ); - for (e, w) in writes.iter().enumerate().skip(1) { - assert_eq!( - *w, - WriteSource::ArgumentSampler { - index: e as u32 - 1, - compare: false, - integer: false, - } - ); - } - let sampler_table = plan - .descriptors - .iter() - .find(|d| d.set == tset && d.binding == tbinding) - .expect("the sampler table's write"); - assert_eq!( - sampler_table.source, - WriteSource::HandleTable { - stage: Stage::Kernel, - bytes_len: 32 * TABLE_ENTRY_BYTES, - } - ); - let cmds = plan - .instantiate_dispatch(&state, &one_group()) - .expect("dispatch"); - let entries = sampler_entries(&cmds.descriptor_bytes, tset, tbinding); - let mut want = vec![(0, 0, 0); 30]; - want.push((B, 4, SamplerWord::of(&pixel_sampler()).0)); - want.push((C, 1, SamplerWord::MIN_LINEAR | SamplerWord::MAG_LINEAR)); - assert_eq!(entries, want); - let bytes = &cmds - .descriptor_bytes - .iter() - .find(|b| b.set == tset && b.binding == tbinding) - .expect("bytes") - .bytes; - assert_eq!( - emitted_lookup_in(bytes, &[C, B, 0, A, D], Lookup::Entry), - vec![31, 30, 29, 0, 0] - ); - // The texture's own table is unchanged by the samplers. - let (set, b, _) = table_write(&plan, Stage::Kernel); - assert_eq!(table(&cmds.descriptor_bytes, set, b), vec![(0, 0), (A, 1)]); - - // A comparison and an integer texel read the arrays of their uses. - for (entry, use_) in [ - ("argument_sampler_compare", (true, false)), - ("argument_sampler_integer", (false, true)), - ] { - let Some(pipe) = argument_sampler_pipeline(&dev, entry) else { - return; - }; - let (arrays, _) = sampler_layout(&pipe); - assert_eq!(arrays.len(), 1, "{entry}"); - assert_eq!(arrays[0].1, use_, "{entry}"); - let mut state = sampler_state(vec![argument_sampler(SamplerDescriptor::new(), C)]); - state.used_resources.clear(); - match pipe.plan(&dev, &state.shape()) { - Ok(plan) => { - let writes = sampler_writes(&plan, arrays[0].0); - assert_eq!( - writes[0], - WriteSource::Neutral(NeutralResource::Sampler { compare: use_.0 }), - "{entry}" - ); - assert_eq!( - writes[1], - WriteSource::ArgumentSampler { - index: 0, - compare: use_.0, - integer: use_.1, - }, - "{entry}" - ); - } - // The device withholds mutable comparison samplers (portability). - Err(BindError::Unsupported(u)) if use_.0 => { - assert_eq!(u.feature, Feature::SamplerCompare, "{entry}") - } - Err(e) => panic!("{entry}: {e}"), - } - } -} - -/// A kernel sampling the cube of its constant argument buffer `M { texturecube t; sampler s; }` -/// with explicit gradients through the member sampler. -const CUBE_GRADIENT: &str = r#"%struct.M = type { ptr addrspace(1), ptr addrspace(2) } -define void @argument_sampler_cube_grad(ptr addrspace(2) %m, ptr addrspace(1) %out, i32 %gid) { - %pt = getelementptr inbounds %struct.M, ptr addrspace(2) %m, i64 0, i32 0 - %t = load ptr addrspace(1), ptr addrspace(2) %pt, align 8 - %ps = getelementptr inbounds %struct.M, ptr addrspace(2) %m, i64 0, i32 1 - %s = load ptr addrspace(2), ptr addrspace(2) %ps, align 8 - %v = call { <4 x float>, i8 } @air.sample_texture_cube_grad.v4f32(ptr addrspace(1) %t, ptr addrspace(2) %s, <3 x float> , <3 x float> , <3 x float> , float 0.0, i32 0) - %x = extractvalue { <4 x float>, i8 } %v, 0 - %o = getelementptr inbounds <4 x float>, ptr addrspace(1) %out, i32 %gid - store <4 x float> %x, ptr addrspace(1) %o, align 16 - ret void -} -declare { <4 x float>, i8 } @air.sample_texture_cube_grad.v4f32(ptr addrspace(1), ptr addrspace(2), <3 x float>, <3 x float>, <3 x float>, float, i32) -!air.kernel = !{!0} -!air.version = !{!11} -!air.language_version = !{!12} -!0 = !{ptr @argument_sampler_cube_grad, !1, !2} -!1 = !{} -!2 = !{!3, !8, !9} -!3 = !{i32 0, !"air.indirect_buffer", !"air.buffer_size", i32 16, !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.struct_type_info", !4, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 8, !"air.arg_type_name", !"M", !"air.arg_name", !"m"} -!4 = !{i32 0, i32 8, i32 0, !"texturecube", !"t", !"air.indirect_argument", !5, i32 8, i32 8, i32 0, !"sampler", !"s", !"air.indirect_argument", !6} -!5 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.sample", !"air.arg_type_name", !"texturecube", !"air.arg_name", !"t"} -!6 = !{i32 1, !"air.sampler", !"air.location_index", i32 1, i32 1, !"air.arg_type_name", !"sampler", !"air.arg_name", !"s"} -!8 = !{i32 1, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"out"} -!9 = !{i32 2, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"gid"} -!11 = !{i32 2, i32 8, i32 0} -!12 = !{!"Metal", i32 4, i32 0, i32 0} -"#; - -/// A cube's explicit gradients through an argument buffer's sampler take their footprint by the -/// sampler's table entry word, so the plan takes every listed sampler for that use, an anisotropic -/// one included: an isotropic sampler plans with the array's `ArgumentSampler` writes, as an -/// anisotropic one does, under Vulkan's rule, the device's reading. Run on every committed -/// profile that compiles the use, `moltenvk-m3` among them. -#[test] -fn a_cube_gradient_use_takes_an_anisotropic_argument_sampler_by_its_word() { - let Some(bc) = assemble("argument_sampler_cube_grad", CUBE_GRADIENT) else { - return; - }; - let description = |stem: &str| { - 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"); - DeviceDescription::from_khronos_json(&text, None).expect("description") - }; - let devices: Vec<(String, Device)> = crate::spirv::testing::committed_profiles() - .expect("profiles") - .into_iter() - .map(|(stem, _)| { - let dev = Device::from_queries(description(&stem), DevicePolicy::RESIDENT_TABLES) - .expect("device"); - (stem, dev) - }) - .collect(); - let (mut taken_on, mut m3_on) = (0, 0); - for (stem, dev) in devices { - let lib = Library::from_air(&bc).expect("library"); - let f = lib.function("argument_sampler_cube_grad").expect("entry"); - let d = ComputePipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new(f))); - let Ok(pipe) = dev.compile_compute_pipeline(&d, &Budget::standard()) else { - assert_ne!(stem, "moltenvk-m3", "moltenvk-m3 compiles the use"); - continue; - }; - let arrays: Vec<(u32, HandleClass)> = pipe.layout.sets[1] - .bindings - .iter() - .filter_map(|b| match b.source { - BindingSource::Heap(c @ HandleClass::Sampler { .. }) => Some((b.binding, c)), - _ => None, - }) - .collect(); - let cube_class = HandleClass::Sampler { - compare: false, - integer: false, - }; - assert_eq!(arrays.len(), 1, "{stem}"); - assert_eq!(arrays[0].1, cube_class, "{stem}"); - let cube_state = |samplers: Vec| BindState { - used_resources: vec![used( - 1, - TextureType::Cube, - PixelFormat::RGBA8Unorm, - read(), - Some(A), - )], - argument_samplers: samplers, - ..Default::default() - }; - let linear = { - let mut d = SamplerDescriptor::new(); - d.min_filter = crate::metal::SamplerMinMagFilter::Linear; - d.mag_filter = crate::metal::SamplerMinMagFilter::Linear; - d - }; - let anisotropic = { - let mut d = linear; - d.max_anisotropy = 4; - d - }; - let write = WriteSource::ArgumentSampler { - index: 0, - compare: false, - integer: false, - }; - for (what, desc) in [("isotropic", linear), ("anisotropic", anisotropic)] { - let plan = pipe - .plan(&dev, &cube_state(vec![argument_sampler(desc, C)]).shape()) - .unwrap_or_else(|e| panic!("{stem}: an {what} sampler plans: {e}")); - assert_eq!( - sampler_writes(&plan, arrays[0].0)[1], - write, - "{stem} {what}" - ); - } - taken_on += 1; - m3_on += usize::from(stem == "moltenvk-m3"); - } - assert!(taken_on > 0, "no profile took the anisotropic sampler"); - assert_eq!(m3_on, 1, "moltenvk-m3 takes it"); -} - -/// A plan depends on the argument samplers only through their shape (`ArgumentSamplersShape`: the -/// capacity class of their count and their distinct shapes). A sampler made or released within the -/// class whose shape another listed sampler shares keeps the shape, so the memoized plan serves -/// both states unchanged and only the per-dispatch table bytes and the resolution of its -/// `ArgumentSampler` writes differ; a pixel sampler shares the default sampler's shape, its -/// coordinates being its table word's. A sampler of a new shape is a new shape key, hence a whole -/// replan, which here plans the same writes; a count leaving its class replans the sampler arrays -/// and tables at twice the next class's entries and nothing else. -#[test] -fn an_unrelated_argument_sampler_keeps_the_plan() { - let dev = m3(); - let Some(pipe) = argument_sampler_pipeline(&dev, "argument_sampler_sample") else { - return; - }; - let (arrays, (tset, tbinding)) = sampler_layout(&pipe); - let binding = arrays[0].0; - let samplers = |n: u64, desc: SamplerDescriptor| -> Vec { - (1..=n) - .map(|i| argument_sampler(desc, 0x1000 + i)) - .collect() - }; - let before = sampler_state(samplers(3, SamplerDescriptor::new())); - let plan = pipe.plan(&dev, &before.shape()).expect("plan"); - // One more sampler of a listed shape: the same shape, so the same plan. - let mut same = before.clone(); - same.argument_samplers - .push(argument_sampler(SamplerDescriptor::new(), 0x2000)); - assert_eq!(same.shape(), before.shape()); - let cmds = plan - .instantiate_dispatch(&same, &one_group()) - .expect("dispatch"); - let entries = sampler_entries(&cmds.descriptor_bytes, tset, tbinding); - assert_eq!(entries.last(), Some(&(0x2000, 4, 0))); - assert_eq!(entries.iter().filter(|e| e.0 != 0).count(), 4); - // Released again: still the same plan. - let fewer = sampler_state(samplers(1, SamplerDescriptor::new())); - assert_eq!(fewer.shape(), before.shape()); - plan.instantiate_dispatch(&fewer, &one_group()) - .expect("dispatch"); - // A pixel sampler keeps the shape: its coordinates are its table word's, so only the bytes - // differ. - let mut pixel = before.clone(); - pixel - .argument_samplers - .push(argument_sampler(pixel_sampler(), 0x3000)); - assert_eq!(pixel.shape(), before.shape()); - // A sampler of a new shape (a linear one): another shape key (a replan, of the same writes); - // a state of another shape is refused by the plan made for the first. - let mut linear = SamplerDescriptor::new(); - linear.min_filter = crate::metal::SamplerMinMagFilter::Linear; - let mut new_shape = before.clone(); - new_shape - .argument_samplers - .push(argument_sampler(linear, 0x3000)); - assert_ne!(new_shape.shape(), before.shape()); - let replanned = pipe.plan(&dev, &new_shape.shape()).expect("plan"); - assert_eq!(replanned.descriptors, plan.descriptors); - assert!(matches!( - plan.instantiate_dispatch(&new_shape, &one_group()), - Err(BindError::Internal(_)) - )); - // Sixteen samplers leave the first class (16 entries, the null one included): twice the - // next class's 32 entries, in the sampler array and the table alone. - let more = sampler_state(samplers(16, SamplerDescriptor::new())); - assert_ne!(more.shape(), before.shape()); - assert_eq!( - sampler_state(samplers(15, SamplerDescriptor::new())).shape(), - before.shape() - ); - let grown = pipe.plan(&dev, &more.shape()).expect("plan"); - assert_eq!(sampler_writes(&grown, binding).len(), 64); - let other = |p: &BindingPlan| -> Vec<_> { - p.descriptors - .iter() - .filter(|d| { - !(d.set == 1 && d.binding == binding) && !(d.set == tset && d.binding == tbinding) - }) - .cloned() - .collect() - }; - assert_eq!(other(&grown), other(&plan)); - let table_len = |p: &BindingPlan| { - p.descriptors - .iter() - .find(|d| d.set == tset && d.binding == tbinding) - .map(|d| d.source.clone()) - }; - assert_eq!( - table_len(&grown), - Some(WriteSource::HandleTable { - stage: Stage::Kernel, - bytes_len: 64 * TABLE_ENTRY_BYTES, - }) - ); -} - -/// The argument samplers plus the null entry must fit the heap's capacity. A class whose least -/// count does not fit is `HeapTooLarge` at plan time; a class straddling the capacity plans its -/// entries clamped to it, and a list past them is `HeapTooLarge` at instantiation. Every listed -/// shape is checked for every use the arrays declare, and an opaque-black border among them meets -/// every member the sampled image arrays hold. -#[test] -fn argument_samplers_are_bounded_and_checked() { - let dev = m3(); - let Some(mut pipe) = argument_sampler_pipeline(&dev, "argument_sampler_sample") else { - return; - }; - for set in &mut pipe.layout.sets { - for b in &mut set.bindings { - if matches!(b.source, BindingSource::Heap(_)) { - b.count = 20; - } - } - } - let (arrays, _) = sampler_layout(&pipe); - let samplers = |n: u64| -> Vec { - (1..=n) - .map(|i| argument_sampler(SamplerDescriptor::new(), i)) - .collect() - }; - // 17 to 31 samplers: class 1 (32 entries), clamped to the arrays' 20. - let fits = sampler_state(samplers(19)); - let plan = pipe.plan(&dev, &fits.shape()).expect("plan"); - assert_eq!(sampler_writes(&plan, arrays[0].0).len(), 20); - plan.instantiate_dispatch(&fits, &one_group()) - .expect("19 samplers and the null entry fit 20"); - let past = sampler_state(samplers(20)); - assert_eq!(past.shape(), fits.shape()); - assert_eq!( - plan.instantiate_dispatch(&past, &one_group()).map(|_| ()), - Err(BindError::HeapTooLarge { - count: 21, - limit: 20 - }) - ); - // 32 samplers: class 2, whose least count (33) exceeds 20. - assert_eq!( - pipe.plan(&dev, &sampler_state(samplers(32)).shape()) - .map(|_| ()), - Err(BindError::HeapTooLarge { - count: 33, - limit: 20 - }) - ); - // A listed sampler that cannot be made for the use refuses the plan, though no buffer may - // pair it with the use: here invalid LOD clamps. - let mut lod = SamplerDescriptor::new(); - lod.lod_min_clamp = 2.0; - lod.lod_max_clamp = 1.0; - let mut bad = sampler_state(samplers(1)); - bad.argument_samplers.push(argument_sampler(lod, 99)); - assert!(matches!( - pipe.plan(&dev, &bad.shape()), - Err(BindError::InvalidDescriptor(_)) - )); - // An opaque-black border meets the members the sampled arrays hold. - let mut black = SamplerDescriptor::new(); - black.s_address_mode = SamplerAddressMode::ClampToBorderColor; - black.border_color = SamplerBorderColor::OpaqueBlack; - let mut state = sampler_state(vec![argument_sampler(black, 7)]); - pipe.plan(&dev, &state.shape()).expect("an exact border"); - state.used_resources = vec![used( - 1, - TextureType::Type2D, - PixelFormat::ABGR4Unorm, - read(), - Some(A), - )]; - match pipe.plan(&dev, &state.shape()) { - Err(BindError::Unsupported(u)) => assert_eq!(u.feature, Feature::SamplerBorderColor), - other => panic!("{other:?}"), - } -} - -/// A stage sampling through argument samplers tests each one's entry for a cubic filter -/// (`RuntimeFact::CubicArgumentSampler`), so a listed cubic sampler is planned beside it, listed -/// with `SamplerWord::CUBIC` in its entry's flags, which the stage's test reads where a buffer -/// names it; the null entry's flags hold no such bit. A stage compiled without the test (its -/// dependencies without the fact) is refused `NotImplemented(SamplerBicubicFilter)` where a -/// cubic sampler is listed, and planned where none is. -#[test] -fn a_listed_cubic_sampler_is_planned_beside_a_stage_that_tests_it() { - let dev = m3(); - let Some(pipe) = argument_sampler_pipeline(&dev, "argument_sampler_sample") else { - return; - }; - let tests = RuntimeFact::CubicArgumentSampler { - stage: Stage::Kernel, - }; - assert!(pipe.dependencies.iter().any(|d| d.fact == tests)); - assert!(pipe - .dependencies - .iter() - .any(|d| d.fact == RuntimeFact::ExecutionStatus)); - let (_, (tset, tbinding)) = sampler_layout(&pipe); - let mut cubic = SamplerDescriptor::new(); - cubic.min_filter = SamplerMinMagFilter::Cubic; - cubic.mag_filter = SamplerMinMagFilter::Cubic; - let state = sampler_state(vec![ - argument_sampler(SamplerDescriptor::new(), B), - argument_sampler(cubic, C), - ]); - let plan = pipe - .plan(&dev, &state.shape()) - .expect("a stage that tests its samplers meets a cubic one"); - let cmds = plan - .instantiate_dispatch(&state, &one_group()) - .expect("dispatch"); - let entries = sampler_entries(&cmds.descriptor_bytes, tset, tbinding); - let flags = |id: u64| { - entries - .iter() - .find(|e| e.0 == id) - .map(|e| e.2) - .expect("listed") - }; - assert_eq!(flags(C) & SamplerWord::CUBIC, SamplerWord::CUBIC); - assert_eq!(flags(B) & SamplerWord::CUBIC, 0); - assert_eq!(flags(0), 0, "the null entry is no cubic sampler"); - // Without the test, a listed cubic sampler is refused; a list without one is planned. - let Some(mut untested) = argument_sampler_pipeline(&dev, "argument_sampler_sample") else { - return; - }; - untested.dependencies.retain(|d| d.fact != tests); - match untested.plan(&dev, &state.shape()) { - Err(BindError::Unsupported(u)) => assert_eq!(u.feature, Feature::SamplerBicubicFilter), - other => panic!("{:?}", other.map(|_| ())), - } - let plain = sampler_state(vec![argument_sampler(SamplerDescriptor::new(), B)]); - untested - .plan(&dev, &plain.shape()) - .expect("no cubic sampler"); -} diff --git a/crates/metal2vulkan/src/tests/engine_heap_groups.rs b/crates/metal2vulkan/src/tests/engine_heap_groups.rs new file mode 100644 index 000000000..47698a8d6 --- /dev/null +++ b/crates/metal2vulkan/src/tests/engine_heap_groups.rs @@ -0,0 +1,238 @@ +//! Heap groups: the loads of one argument-buffer member share a heap group, so a read of the +//! member types its queries (never the MSL type name); a group only queried is declared `Float` +//! with `RuntimeFact::HeapNumericType`. Under the identity domains such a group, a 2D texture's or +//! a cube array's alike, is `Unsupported{IdentityDomains}`, not implemented, naming that fact. No +//! device is opened. +//! +//! `llvm-as` assembles the kernels; without it the tests skip visibly. + +use std::sync::atomic::{AtomicU64, Ordering}; + +use super::engine_word_phases::identity_profiles; +use crate::device::DevicePolicy; +use crate::error::{Error, Feature, Needs}; +use crate::library::FunctionArtifact; +use crate::pipeline::facts::RuntimeFact; +use crate::pipeline::sym::{HandleClass, ImageHandleClass, ResourceKind, SampledType}; +use crate::pipeline::testing::{compile, link_and_validate, llvm_assemble, profile, AssembleError}; + +const HEADER: &str = "target datalayout = \"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32\"\ntarget triple = \"air64_v28-apple-macosx26.0.0\"\n\n"; + +fn assembled(name: &str, r: Result, AssembleError>) -> Option> { + match r { + Ok(b) => Some(b), + Err(AssembleError::Missing(why)) => { + eprintln!("SKIPPED: {why}"); + None + } + Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected {name}: {why}"), + } +} + +fn assemble(name: &str, body: &str) -> Option> { + static NEXT: AtomicU64 = AtomicU64::new(0); + let dir = std::env::temp_dir().join(format!( + "m2v-heap-binder-{}-{}-{name}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + std::fs::create_dir_all(&dir).expect("scratch"); + let ll = dir.join("k.ll"); + std::fs::write(&ll, format!("{HEADER}{body}")).expect("write"); + let r = llvm_assemble(&ll); + let _ = std::fs::remove_dir_all(&dir); + assembled(name, r) +} + +/// Two kernels over one argument-buffer member that only the MSL type name calls an integer +/// texture: `heap_query` only queries it, `heap_query_read` also reads it as `uint`. +const QUERY_KERNELS: &str = r#"%struct.T = type { ptr addrspace(1) } +%struct.R = type { %struct.T } +define void @heap_query(ptr addrspace(2) %r, ptr addrspace(1) %out, i32 %gid) { + %pt = getelementptr inbounds %struct.R, ptr addrspace(2) %r, i64 0, i32 0, i32 0 + %t = load ptr addrspace(1), ptr addrspace(2) %pt, align 8 + %w = call i32 @air.get_width_texture_2d(ptr addrspace(1) %t, i32 0) + %o = getelementptr inbounds i32, ptr addrspace(1) %out, i32 %gid + store i32 %w, ptr addrspace(1) %o, align 4 + ret void +} +define void @heap_query_read(ptr addrspace(2) %r, ptr addrspace(1) %out, i32 %gid) { + %pt = getelementptr inbounds %struct.R, ptr addrspace(2) %r, i64 0, i32 0, i32 0 + %t = load ptr addrspace(1), ptr addrspace(2) %pt, align 8 + %w = call i32 @air.get_width_texture_2d(ptr addrspace(1) %t, i32 0) + %t2 = load ptr addrspace(1), ptr addrspace(2) %pt, align 8 + %s = tail call ptr addrspace(2) @air.get_read_sampler() + %c = insertelement <2 x i32> zeroinitializer, i32 %gid, i64 0 + %v = call { <4 x i32>, i8 } @air.read_texture_2d.u.v4i32(ptr addrspace(1) %t2, ptr addrspace(2) %s, <2 x i32> %c, <2 x i32> zeroinitializer, i32 0, i32 0) + %x4 = extractvalue { <4 x i32>, i8 } %v, 0 + %x = extractelement <4 x i32> %x4, i64 0 + %sum = add i32 %w, %x + %o = getelementptr inbounds i32, ptr addrspace(1) %out, i32 %gid + store i32 %sum, ptr addrspace(1) %o, align 4 + ret void +} +declare ptr addrspace(2) @air.get_read_sampler() +declare i32 @air.get_width_texture_2d(ptr addrspace(1), i32) +declare { <4 x i32>, i8 } @air.read_texture_2d.u.v4i32(ptr addrspace(1), ptr addrspace(2), <2 x i32>, <2 x i32>, i32, i32) +!air.kernel = !{!0, !11} +!air.version = !{!9} +!air.language_version = !{!10} +!0 = !{ptr @heap_query, !1, !2} +!1 = !{} +!2 = !{!3, !7, !8} +!3 = !{i32 0, !"air.indirect_buffer", !"air.buffer_size", i32 8, !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.struct_type_info", !4, !"air.arg_type_size", i32 8, !"air.arg_type_align_size", i32 8, !"air.arg_type_name", !"R", !"air.arg_name", !"r"} +!4 = !{i32 0, i32 8, i32 0, !"texture2d", !"t", !"air.indirect_argument", !5} +!5 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.read", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"t"} +!7 = !{i32 1, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"out"} +!8 = !{i32 2, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"gid"} +!9 = !{i32 2, i32 8, i32 0} +!10 = !{!"Metal", i32 4, i32 0, i32 0} +!11 = !{ptr @heap_query_read, !1, !2} +"#; + +/// The heap classes a function declares. +fn heap_classes_of(a: &FunctionArtifact) -> Vec { + a.interface + .descriptors + .iter() + .filter_map(|d| match d.slot.kind { + ResourceKind::Heap(HandleClass::Image(c)) => Some(c), + _ => None, + }) + .collect() +} + +/// A heap group that is only queried has no texel class: its array is declared `Float`, and +/// `RuntimeFact::HeapNumericType` says so. A load of the same member that is read types every +/// group loaded from it: the member has one declared type. +#[test] +fn a_member_read_anywhere_types_its_queries() { + let Some(bc) = assemble("heap_query", QUERY_KERNELS) else { + return; + }; + let p = profile("moltenvk-m3", DevicePolicy::RESIDENT_TABLES).expect("profile"); + let a = compile(&bc, "heap_query", &p).expect("heap_query"); + link_and_validate(&a, &p).expect("L3"); + let classes = heap_classes_of(&a); + // The float class, and its unsigned integer twin, which a member of a form a heap reads is + // queried through. + assert_eq!(classes.len(), 2); + assert_eq!(classes[0].sampled_type, SampledType::Float); + assert_eq!( + classes[1], + ImageHandleClass { + sampled_type: SampledType::Uint, + ..classes[0] + } + ); + assert!(a + .facts + .contains(&RuntimeFact::HeapNumericType { class: classes[0] })); + + let a = compile(&bc, "heap_query_read", &p).expect("heap_query_read"); + link_and_validate(&a, &p).expect("L3"); + assert_eq!( + a.strategies + .entries + .get("access.handle.lookup") + .map_or(0, |u| u.uses), + 2 + ); + // Both loads of the member share the unsigned integer class; the read and the query read a + // member of another numeric class through its shape's class of that type. + let mut classes = heap_classes_of(&a); + classes.sort_by_key(|c| c.sampled_type); + assert_eq!( + classes, + [SampledType::Float, SampledType::Sint, SampledType::Uint].map(|sampled_type| { + ImageHandleClass { + sampled_type, + ..classes[0] + } + }), + "both loads of the member share one class" + ); + assert!(!a + .facts + .iter() + .any(|f| matches!(f, RuntimeFact::HeapNumericType { .. }))); +} + +/// Two kernels that only query an argument buffer's texture: `abq_2d` a `texture2d`'s +/// width, `abq_cube_array` a `texturecube_array`'s array size. +const QUERY_ONLY_KERNELS: &str = r#"%struct.Q = type { ptr addrspace(1) } +define void @abq_2d(ptr addrspace(2) %q, ptr addrspace(1) %out, i32 %gid) { + %pt = getelementptr inbounds %struct.Q, ptr addrspace(2) %q, i64 0, i32 0 + %t = load ptr addrspace(1), ptr addrspace(2) %pt, align 8 + %w = call i32 @air.get_width_texture_2d(ptr addrspace(1) %t, i32 0) + %o = getelementptr inbounds i32, ptr addrspace(1) %out, i32 %gid + store i32 %w, ptr addrspace(1) %o, align 4 + ret void +} +define void @abq_cube_array(ptr addrspace(2) %q, ptr addrspace(1) %out, i32 %gid) { + %pt = getelementptr inbounds %struct.Q, ptr addrspace(2) %q, i64 0, i32 0 + %t = load ptr addrspace(1), ptr addrspace(2) %pt, align 8 + %n = call i32 @air.get_array_size_texture_cube_array(ptr addrspace(1) %t) + %o = getelementptr inbounds i32, ptr addrspace(1) %out, i32 %gid + store i32 %n, ptr addrspace(1) %o, align 4 + ret void +} +declare i32 @air.get_width_texture_2d(ptr addrspace(1), i32) +declare i32 @air.get_array_size_texture_cube_array(ptr addrspace(1)) +!air.kernel = !{!0, !9} +!air.version = !{!7} +!air.language_version = !{!8} +!0 = !{ptr @abq_2d, !1, !2} +!1 = !{} +!2 = !{!3, !5, !6} +!3 = !{i32 0, !"air.indirect_buffer", !"air.buffer_size", i32 8, !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.struct_type_info", !4, !"air.arg_type_size", i32 8, !"air.arg_type_align_size", i32 8, !"air.arg_type_name", !"Q", !"air.arg_name", !"q"} +!4 = !{i32 0, i32 8, i32 0, !"texture2d", !"t", !"air.indirect_argument", !12} +!5 = !{i32 1, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"out"} +!6 = !{i32 2, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"gid"} +!7 = !{i32 2, i32 8, i32 0} +!8 = !{!"Metal", i32 4, i32 0, i32 0} +!9 = !{ptr @abq_cube_array, !1, !10} +!10 = !{!11, !5, !6} +!11 = !{i32 0, !"air.indirect_buffer", !"air.buffer_size", i32 8, !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.struct_type_info", !13, !"air.arg_type_size", i32 8, !"air.arg_type_align_size", i32 8, !"air.arg_type_name", !"Q", !"air.arg_name", !"q"} +!12 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.sample", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"t"} +!13 = !{i32 0, i32 8, i32 0, !"texturecube_array", !"t", !"air.indirect_argument", !14} +!14 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.sample", !"air.arg_type_name", !"texturecube_array", !"air.arg_name", !"t"} +"#; + +/// Under the identity domains, an argument buffer's texture that a kernel only queries is +/// refused, whatever its shape: its group has no texel class, and the identity domains source no +/// `RuntimeFact::HeapNumericType`. Each kernel of [`QUERY_ONLY_KERNELS`] is +/// `Unsupported{IdentityDomains}`, not implemented, naming that fact of its member's shape, on +/// every profile the identity domains derive. +#[test] +fn a_query_only_argument_buffer_texture_is_refused_naming_its_numeric_type() { + let Some(bc) = assemble("query_only", QUERY_ONLY_KERNELS) else { + return; + }; + let profiles = identity_profiles(); + assert!( + !profiles.is_empty(), + "no profile the identity domains derive" + ); + let form = "state of a bound texture or sampler beyond its resource ID (HeapNumericType {"; + for (stem, p) in profiles { + for (entry, shape) in [ + ("abq_2d", "dim: D2, arrayed: false"), + ("abq_cube_array", "dim: Cube, arrayed: true"), + ] { + let Err(Error::Unsupported(u)) = compile(&bc, entry, &p) else { + panic!("{stem}: {entry}: not refused"); + }; + assert_eq!( + (u.feature, u.needs), + (Feature::IdentityDomains, Needs::NotImplemented), + "{stem}: {entry}" + ); + let symbol = u.symbol.map(|s| s.to_string()).unwrap_or_default(); + assert!( + symbol.starts_with(form) && symbol.contains(shape), + "{stem}: {entry}: {symbol}" + ); + } + } +} diff --git a/crates/metal2vulkan/src/tests/engine_heap_residency.rs b/crates/metal2vulkan/src/tests/engine_heap_residency.rs deleted file mode 100644 index 735d25198..000000000 --- a/crates/metal2vulkan/src/tests/engine_heap_residency.rs +++ /dev/null @@ -1,156 +0,0 @@ -//! The residency of a texture an argument buffer holds. -//! -//! The owned fixture `engine/tail_argument_sparse_samples` samples the material texture of its -//! constant argument buffer 0 with `sparse_sample` through a constexpr sampler that filters -//! linearly between levels with anisotropy: `argument_sparse_fragment` returns the value where -//! `resident()` holds and else the sample clamped by the material's `min_lod_clamp`, the two -//! samples' `{half4, i8}` results merged in a `phi` and the word tested `(status & 1) == 0`; -//! `argument_sparse_residency_fragment` returns the residency it read beside the value. -//! -//! Each fragment compiles behind `argument_sparse_vertex` wherever the device has what it uses, -//! its heap access answering the word of a texture that is not sparse (resident) and the stage -//! stating `RuntimeFact::HeapResidency`; before, the observed word of a heap element was refused -//! (`Lowering(Texture)`, `NotImplemented`). Its plan holds a texture that is not sparse in the -//! heap, and refuses a sparse one the fragment's handle table reaches, whose residency the -//! module does not answer. No GPU is used. - -use std::path::Path; - -use crate::bind::{BindState, ResourceClass, TextureFacts, UsedResource}; -use crate::budget::Budget; -use crate::device::{Device, DeviceDescription, DevicePolicy}; -use crate::error::{BindError, Error, Feature, Needs, Unsupported}; -use crate::library::Library; -use crate::metal::{PixelFormat, RenderStages, TextureType, TextureUsage}; -use crate::pipeline::artifact::RenderPipeline; -use crate::pipeline::descriptor::{ - ColorAttachmentDescriptor, FunctionDescriptor, RenderPipelineDescriptor, StageSource, -}; -use crate::pipeline::facts::RuntimeFact; -use crate::pipeline::sym::Stage; -use crate::pipeline::testing::{engine_dir, llvm_assemble, AssembleError}; -use crate::spirv::testing::{check_words_valid, committed_profiles}; - -/// The fixture's fragment functions. -const FRAGMENTS: [&str; 2] = [ - "argument_sparse_fragment", - "argument_sparse_residency_fragment", -]; - -/// The committed profiles each fragment must compile on. -const COMPILES_ON: [&str; 3] = ["moltenvk-m3", "lavapipe", "amd-780m-radv"]; - -/// The fixture's library, assembled with `llvm-as`; `None` where the tool is missing (the test -/// then skips visibly). -fn fixture_library() -> Option { - match llvm_assemble(&engine_dir().join("tail_argument_sparse_samples.ll")) { - Ok(bc) => Some(Library::from_air(&bc).expect("library")), - Err(AssembleError::Missing(why)) => { - eprintln!("SKIPPED: {why}"); - None - } - Err(AssembleError::Rejected(why)) => { - panic!("llvm-as rejected tail_argument_sparse_samples: {why}") - } - } -} - -/// The device of committed profile `stem`. -fn device(stem: &str) -> Device { - let path = Path::new(env!("CARGO_MANIFEST_DIR")) - .join(format!("../metal2vulkan-validation/profiles/{stem}.json")); - let text = std::fs::read_to_string(path).expect("profile"); - let desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); - Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device") -} - -/// The pipeline of fragment `entry` behind `argument_sparse_vertex`, color 0 `RGBA16Float`. -fn pipeline(dev: &Device, library: &Library, entry: &str) -> Result { - let function = |name: &str| { - StageSource::Function(FunctionDescriptor::new( - library.function(name).expect("function"), - )) - }; - let mut d = RenderPipelineDescriptor::new(function("argument_sparse_vertex")); - d.fragment = Some(function(entry)); - d.color_attachments[0] = Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA16Float)); - dev.compile_render_pipeline(&d, &Budget::standard()) -} - -/// Whether `pipe` states the fragment's heap residency. -fn states_residency(pipe: &RenderPipeline) -> bool { - pipe.dependencies.iter().any(|d| { - d.fact - == RuntimeFact::HeapResidency { - stage: Stage::Fragment, - } - }) -} - -/// A 2D `RGBA16Float` texture the fragment stage reads, sparse where `sparse`. -fn material(sparse: bool) -> UsedResource { - let mut facts = TextureFacts::new(TextureType::Type2D, PixelFormat::RGBA16Float); - facts.usage = TextureUsage::SHADER_READ; - facts.sparse = sparse; - let mut u = UsedResource::new(ResourceClass::Texture(facts), 1); - u.resource_id = Some(0x5150_0001); - u.stages = RenderStages::FRAGMENT; - u -} - -#[test] -fn a_heap_textures_observed_residency_compiles_and_a_sparse_member_is_refused() { - let Some(library) = fixture_library() else { - return; - }; - let mut compiled = Vec::new(); - for (stem, _) in committed_profiles().expect("profiles") { - let dev = device(&stem); - for entry in FRAGMENTS { - let what = format!("{stem} {entry}"); - match pipeline(&dev, &library, entry) { - Ok(pipe) => { - assert!(states_residency(&pipe), "{what}: {:?}", pipe.dependencies); - for s in &pipe.stages { - check_words_valid(&s.spirv, &pipe.requirements, dev.profile()) - .unwrap_or_else(|e| panic!("{what}: L3: {e}")); - } - compiled.push(what); - } - // A device that lacks what the fragment uses (`shaderResourceMinLod` for the - // clamp, or the heap's own needs) refuses it by name. - Err(Error::Unsupported(Unsupported { - needs: Needs::AnyOf(_), - .. - })) => assert!(!COMPILES_ON.contains(&stem.as_str()), "{what}"), - Err(e) => panic!("{what}: {e}"), - } - } - } - for stem in COMPILES_ON { - for entry in FRAGMENTS { - let what = format!("{stem} {entry}"); - assert!(compiled.contains(&what), "{what} did not compile"); - } - } - // The plan: a texture that is not sparse is a member, a sparse one the fragment reaches is - // refused. - let dev = device("moltenvk-m3"); - for entry in FRAGMENTS { - let pipe = pipeline(&dev, &library, entry).expect("pipeline"); - let state = |sparse: bool| BindState { - used_resources: vec![material(sparse)], - ..Default::default() - }; - pipe.plan(&dev, &state(false).shape()) - .unwrap_or_else(|e| panic!("{entry}: {e}")); - match pipe.plan(&dev, &state(true).shape()) { - Err(BindError::Unsupported(u)) => { - assert_eq!(u.feature, Feature::ArgumentBufferTextures, "{entry}"); - assert_eq!(u.needs, Needs::NotImplemented, "{entry}"); - } - Ok(_) => panic!("{entry}: a sparse member is planned"), - Err(e) => panic!("{entry}: {e}"), - } - } -} diff --git a/crates/metal2vulkan/src/tests/engine_heap_storage_reads.rs b/crates/metal2vulkan/src/tests/engine_heap_storage_reads.rs index 4042d07c6..5693b23da 100644 --- a/crates/metal2vulkan/src/tests/engine_heap_storage_reads.rs +++ b/crates/metal2vulkan/src/tests/engine_heap_storage_reads.rs @@ -14,11 +14,9 @@ use std::collections::BTreeMap; use std::path::Path; +use std::sync::atomic::{AtomicU64, Ordering}; -use crate::bind::heap::{storage_unreadable, tier_read_gaps}; -use crate::bind::{ - handle_entry, BindState, ResourceClass, TextureFacts, UsedResource, WriteSource, -}; +use crate::bind::heap::tier_read_gaps; use crate::budget::Budget; use crate::device::metal::read_write_tier_formats; use crate::device::requirements::{FormatUsage, SpirvCapability, VkFeature}; @@ -26,19 +24,39 @@ use crate::device::{Device, DeviceDescription, DevicePolicy}; use crate::error::{Capability, Error, Feature, Needs}; use crate::library::Library; use crate::memory::handles::{Lookup, FLAG_STORAGE_UNREADABLE}; -use crate::metal::{PixelFormat, TextureType, TextureUsage}; use crate::pipeline::sym::{ Axis, HandleClass, ImageAccess, ImageHandleClass, ResourceKind, ResourceSlot, SpecKey, Stage, SyntheticBinding, }; -use crate::pipeline::testing::typed_module; +use crate::pipeline::testing::{llvm_assemble, typed_module, AssembleError}; use crate::pipeline::{ ComputePipeline, ComputePipelineDescriptor, FunctionDescriptor, StageSource, }; use crate::spirv::interp::{run_with_images, Buffer, Config, Image, Resources}; use crate::vk; -use super::engine_binder::assemble_text; +/// `text` assembled by `llvm-as`, or `None` (printed as skipped) where the tool is missing. +fn assemble_text(name: &str, text: &str) -> Option> { + static NEXT: AtomicU64 = AtomicU64::new(0); + let dir = std::env::temp_dir().join(format!( + "m2v-binder-{}-{}-{name}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + std::fs::create_dir_all(&dir).expect("scratch"); + let ll = dir.join("k.ll"); + std::fs::write(&ll, text).expect("write"); + let r = llvm_assemble(&ll); + let _ = std::fs::remove_dir_all(&dir); + match r { + Ok(b) => Some(b), + Err(AssembleError::Missing(why)) => { + eprintln!("SKIPPED: {why}"); + None + } + Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected {name}: {why}\n{text}"), + } +} const HEADER: &str = "target datalayout = \"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32\"\ntarget triple = \"air64_v28-apple-macosx26.0.0\"\n\n"; @@ -122,38 +140,6 @@ fn storage_class() -> ImageHandleClass { } } -/// A 2D `read_write` texture of `pf`. -fn read_write(pf: PixelFormat) -> TextureFacts { - let mut f = TextureFacts::new(TextureType::Type2D, pf); - f.usage = TextureUsage::SHADER_READ | TextureUsage::SHADER_WRITE; - f -} - -/// A command making the textures of `members` resident, each with its resource ID. -fn state(members: &[(TextureFacts, u64)]) -> BindState { - BindState { - used_resources: (members.iter().zip(1u32..)) - .map(|(&(f, id), token)| { - let mut u = UsedResource::new(ResourceClass::Texture(f), token); - u.resource_id = Some(id); - u - }) - .collect(), - ..Default::default() - } -} - -/// The non-tier formats whose storage view the Iris Xe cannot read without a format (Mesa's isl -/// table: no typed reads of `R10G10B10A2`, `B10G10R10A2`, `R11G11B10_FLOAT` or `B8G8R8A8` below -/// Gfx12.5; `BGR10A2Unorm` through its `A2B10G10R10` twin as well). -const IRIS_UNREADABLE: [PixelFormat; 5] = [ - PixelFormat::RGB10A2Unorm, - PixelFormat::RGB10A2Uint, - PixelFormat::BGR10A2Unorm, - PixelFormat::RG11B10Float, - PixelFormat::BGRA8Unorm, -]; - /// The heap's storage read compiles where the formats' own bits grant it: on the Iris Xe, without /// `shaderStorageImageReadWithoutFormat`, the pipeline requires the SPIR-V capability (which /// Vulkan 1.3 enables) and not the feature, and its handle-table search carries the unreadable @@ -250,11 +236,17 @@ fn a_flagged_member_reads_the_null_element() { images[2].texels = texels(10.0); // The table: the null entry, the readable member at element 1, the flagged one at 2. let table: Vec = [ - handle_entry(0, 0, 0), - handle_entry(READABLE_ID, 1, 0), - handle_entry(FLAGGED_ID, 2, FLAG_STORAGE_UNREADABLE), + (0, 0, 0), + (READABLE_ID, 1, 0), + (FLAGGED_ID, 2, FLAG_STORAGE_UNREADABLE), ] - .concat(); + .into_iter() + .flat_map(|(id, element, flags): (u64, u32, u32)| { + [id as u32, (id >> 32) as u32, element, flags] + .into_iter() + .flat_map(u32::to_le_bytes) + }) + .collect(); let buffer = |kind, index, bytes| Buffer { slot: Some(ResourceSlot { stage: Stage::Kernel, @@ -300,13 +292,11 @@ fn a_flagged_member_reads_the_null_element() { } } -/// On every committed profile that reads storage without a format by the formats' bits alone, -/// where a view of one of Metal's read-write tier formats on the profile cannot be read so -/// (flagged), a function reading its storage class is refused for it ([`tier_read_gaps`]): no tier -/// format reads zero. On the Iris Xe none is flagged; the non-tier formats its view cannot read -/// are flagged; on lavapipe, which has the feature, nothing is flagged. +/// Some committed profile reads storage without a format by the formats' bits alone, and on the +/// Iris Xe, one such, a function reading the storage class of any of Metal's read-write tier +/// formats on the profile has nothing to lack ([`tier_read_gaps`]). #[test] -fn only_a_view_the_device_cannot_read_is_flagged() { +fn the_iris_xe_reads_every_tier_format_s_storage_class() { let mut bits_alone = 0; for (stem, profile) in crate::spirv::testing::committed_profiles().expect("profiles") { let profile = &profile; @@ -314,109 +304,36 @@ fn only_a_view_the_device_cannot_read_is_flagged() { continue; } bits_alone += 1; + if stem != IRIS { + continue; + } let tiers = read_write_tier_formats(profile); for &pf in tiers.iter().flat_map(|tier| tier.iter()) { - let facts = read_write(pf); let class = ImageHandleClass { sampled_type: crate::metal::format::sampled_type(pf).expect("type"), ..storage_class() }; - let flagged = storage_unreadable(profile, &facts.shape()); let gaps = tier_read_gaps(profile, &class); - assert!(!flagged || !gaps.is_empty(), "{stem}: {pf:?} reads zero"); - if stem == IRIS { - assert!(!flagged && gaps.is_empty(), "{stem}: {pf:?}: {gaps:?}"); - } + assert!(gaps.is_empty(), "{stem}: {pf:?}: {gaps:?}"); } } assert!( bits_alone > 0, "no committed profile reads by the bits alone" ); - - let iris = device(IRIS); - let lavapipe = device("lavapipe"); - for pf in IRIS_UNREADABLE { - let shape = read_write(pf).shape(); - assert!(storage_unreadable(iris.profile(), &shape), "{pf:?}"); - assert!(!storage_unreadable(lavapipe.profile(), &shape), "{pf:?}"); - } -} - -/// A plan on the Iris Xe holds an `RGBA16Float` member and an `RG11B10Float` one in the storage -/// class and flags only the second's table entry. -#[test] -fn a_plan_flags_its_unreadable_members() { - let Some(bc) = kernel() else { - return; - }; - let iris = device(IRIS); - let pipe = pipeline(&iris, &bc).expect("pipeline"); - let state = state(&[ - (read_write(PixelFormat::RGBA16Float), READABLE_ID), - (read_write(PixelFormat::RG11B10Float), FLAGGED_ID), - ]); - let bplan = pipe.plan(&iris, &state.shape()).expect("plan"); - let views: Vec<(u32, vk::Format)> = (bplan.descriptors.iter()) - .filter_map(|d| match &d.source { - WriteSource::HeapEntry { element, view, .. } => Some((*element, view.format)), - _ => None, - }) - .collect(); - assert_eq!( - views, - vec![ - (1, vk::Format::R16G16B16A16_SFLOAT), - (2, vk::Format::B10G11R11_UFLOAT_PACK32) - ] - ); - let dispatch = crate::bind::Dispatch::Threadgroups { - groups: [1, 1, 1], - threads_per_group: [1, 1, 1], - }; - let cmds = bplan - .instantiate_dispatch(&state, &dispatch) - .expect("dispatch"); - let (set, binding) = (bplan.descriptors.iter()) - .find_map(|d| { - matches!(d.source, WriteSource::HandleTable { .. }).then_some((d.set, d.binding)) - }) - .expect("a handle table"); - let table = &(cmds.descriptor_bytes.iter()) - .find(|b| (b.set, b.binding) == (set, binding)) - .expect("table bytes") - .bytes; - let flags: Vec<(u64, u32)> = table - .chunks(16) - .map(|e| { - let word = |w: usize| u32::from_le_bytes(e[4 * w..4 * w + 4].try_into().unwrap()); - ( - u64::from(word(0)) | u64::from(word(1)) << 32, - word(3) & FLAG_STORAGE_UNREADABLE, - ) - }) - .filter(|(id, _)| *id != 0) - .collect(); - assert_eq!( - flags, - vec![(READABLE_ID, 0), (FLAGGED_ID, FLAG_STORAGE_UNREADABLE)] - ); } /// A function that reads a storage class one of Metal's read-write tier formats is held in through -/// a view the device cannot read without a format is refused, naming the view's bit, and the member -/// is flagged unreadable: on the Iris Xe with `R16G16B16A16_SFLOAT`'s `STORAGE_READ_WITHOUT_FORMAT` -/// bit cleared (a synthetic profile), the kernel is `Unsupported` naming that bit alone (the -/// class's neutral, `R32_SFLOAT`, keeps its own), and an `RGBA16Float` member is flagged. The -/// committed profile compiles the kernel and leaves the member unflagged. +/// a view the device cannot read without a format is refused, naming the view's bit: on the Iris +/// Xe with `R16G16B16A16_SFLOAT`'s `STORAGE_READ_WITHOUT_FORMAT` bit cleared (a synthetic +/// profile), the kernel is `Unsupported` naming that bit alone (the class's neutral, `R32_SFLOAT`, +/// keeps its own). The committed profile compiles the kernel. #[test] fn a_tier_format_without_its_read_bit_is_refused() { let Some(bc) = kernel() else { return; }; - let shape = read_write(PixelFormat::RGBA16Float).shape(); let iris = device(IRIS); - assert!(!storage_unreadable(iris.profile(), &shape)); pipeline(&iris, &bc).expect("the committed profile"); let mut desc = description(IRIS); let format = vk::Format::R16G16B16A16_SFLOAT; @@ -441,5 +358,4 @@ fn a_tier_format_without_its_read_bit_is_refused() { } other => panic!("the kernel: {:?}", other.map(|_| ())), } - assert!(storage_unreadable(cleared.profile(), &shape)); } diff --git a/crates/metal2vulkan/src/tests/engine_identity.rs b/crates/metal2vulkan/src/tests/engine_identity.rs index 4b234c371..f649a1a5d 100644 --- a/crates/metal2vulkan/src/tests/engine_identity.rs +++ b/crates/metal2vulkan/src/tests/engine_identity.rs @@ -16,9 +16,7 @@ //! whole dispatch, one split in two pieces at a base, and an indirect one (a zero grid, its grid //! `NumWorkgroups · L`) store the same answers, and a ragged grid split into a region of its //! threadgroup size and an edge region of fewer threads, at 1 with Metal's threadgroup size in -//! the region, stores Metal's answers. Through the binder (`BindingPlan::instantiate_dispatch`) -//! a ragged `dispatchThreads` grid's regions, edges of fewer threads among them, set -//! `MultiRegion` 1 and store Metal's answers. +//! the region, stores Metal's answers. //! - A kernel's partial-threadgroups variant (`partial`, generated) dispatched at its whole //! threadgroup size over a ragged grid, its pushed region flagged `NONUNIFORM`, answers each //! edge threadgroup's own size, and its invocations past the grid store nothing. @@ -125,7 +123,6 @@ use std::collections::{BTreeMap, BTreeSet}; use std::sync::atomic::{AtomicU64, Ordering}; use super::engine_word_phases::{bounds_word, slot_word, ZERO_UNMAPPED}; -use crate::bind::{BindState, BoundBuffer, Dispatch, StageTable}; use crate::budget::Budget; use crate::device::profile::{DeviceProfile, HandleDomain, PointerDomain}; use crate::device::requirements::VkFeature; @@ -2700,103 +2697,6 @@ fn from_queries_reads_every_regions_base_and_its_size_by_multi_region() { } } -/// Through the binder on `Device::from_queries`' profile: a ragged `dispatchThreads` grid of -/// [`grid_kernel`] is planned as edge regions of fewer threads than Metal's threadgroup, each with -/// `MultiRegion` 1, and every region, run on the CPU interpreter with the push bytes, the -/// specialization and the group counts the binder planned, stores Metal's answers for the grid. -#[test] -fn the_binders_edge_regions_set_multi_region_on_from_queries_and_store_metals_grid() { - let Some(bc) = assemble_text("grid", &grid_kernel("grid")) else { - return; - }; - const L: [u32; 3] = [4, 2, 1]; - const GRID: [u32; 3] = [7, 5, 1]; - let threads = (GRID[0] * GRID[1]) as usize; - let groups = [GRID[0].div_ceil(L[0]), GRID[1].div_ceil(L[1])]; - let value = GRID[0] | GRID[1] << 8 | groups[0] << 16 | groups[1] << 24; - let want: Vec = (0..threads).flat_map(|_| value.to_le_bytes()).collect(); - for stem in PROFILES { - let desc = crate::pipeline::testing::description(stem).unwrap_or_else(|e| panic!("{e}")); - let dev = Device::from_queries(desc, identity()).unwrap_or_else(|e| panic!("{e}")); - let lib = Library::from_air(&bc).unwrap_or_else(|e| panic!("{stem}: {e}")); - let f = lib - .function("grid") - .unwrap_or_else(|e| panic!("{stem}: {e}")); - let d = ComputePipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new(f))); - let pipe = dev - .compile_compute_pipeline(&d, &Budget::standard()) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - let (_, _, module) = - compile_kept(&bc, "grid", dev.profile()).unwrap_or_else(|e| panic!("{stem}: {e}")); - let mut table = StageTable::default(); - table.buffers.insert( - 0, - BoundBuffer::Buffer { - length: 4 * threads as u64, - offset: 0, - gpu_address: OUT, - device_address: Some(OUT), - attribute_stride: None, - }, - ); - let mut state = BindState::default(); - state.stages.insert(Stage::Kernel, table); - let plan = pipe - .plan(&dev, &state.shape()) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - let dispatch = Dispatch::Threads { - threads: GRID, - threads_per_group: L, - }; - let commands = plan - .instantiate_dispatch(&state, &dispatch) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - let keys: BTreeMap = (pipe.stage.specialization.constants.iter()) - .map(|c| (c.id, c.key)) - .collect(); - let mut out = vec![0u8; 4 * threads]; - let mut edges = 0; - for region in &commands.regions { - let mut spec = BTreeMap::new(); - for e in ®ion.specialization.entries { - let at = e.offset as usize; - let mut v = [0u8; 8]; - v[..e.size as usize] - .copy_from_slice(®ion.specialization.data[at..at + e.size as usize]); - spec.insert(keys[&e.constant_id], u64::from_le_bytes(v)); - } - let local = [Axis::X, Axis::Y].map(|a| spec.get(&SpecKey::LocalSize(a)).copied()); - if spec.get(&SpecKey::MultiRegion) == Some(&1) - && local != [Some(u64::from(L[0])), Some(u64::from(L[1]))] - { - edges += 1; - } - let mut push = Vec::new(); - if let Some(w) = region.push_constants.first() { - push = vec![0u8; w.offset as usize + w.bytes.len()]; - push[w.offset as usize..].copy_from_slice(&w.bytes); - } - let res = Resources { - buffers: vec![Buffer { - slot: None, - address: Some(OUT), - bytes: out, - }], - push, - spec, - }; - let cfg = Config { - workgroups: region.group_count, - ..Config::default() - }; - let got = run(&module, &cfg, res).unwrap_or_else(|e| panic!("{stem}: {e}")); - out = got.buffers.into_iter().next().expect("out"); - } - assert!(edges > 0, "{stem}: an edge region of fewer threads"); - assert_eq!(out, want, "{stem}"); - } -} - /// A kernel storing, at its position in the grid `y · 7 + x` (the grid is 7 wide), its /// threadgroup's threads along `x` and `y` (bits 0-7, 8-15). fn partial_kernel() -> String { @@ -2973,67 +2873,6 @@ fn a_deep_threadgroup_runs_as_one_row_on_from_queries() { ); } -/// Through the binder on `Device::from_queries`' profile of a device that holds 64 threads along -/// `z` (NVIDIA's): a dispatch of [`deep_kernel`] in threadgroups 320 deep is planned, its region -/// setting `SpecKey::DeepThreadgroup`, and one 4 deep is planned with it unset. -#[test] -fn the_binder_sets_deep_threadgroup_for_a_threadgroup_deeper_than_the_floor() { - let Some(bc) = assemble_text("deep", &deep_kernel()) else { - return; - }; - let desc = crate::pipeline::testing::description("nvidia-rtx50-linux") - .unwrap_or_else(|e| panic!("{e}")); - let dev = Device::from_queries(desc, identity()).unwrap_or_else(|e| panic!("{e}")); - let lib = Library::from_air(&bc).unwrap_or_else(|e| panic!("{e}")); - let f = FunctionDescriptor::new(lib.function("deep").unwrap_or_else(|e| panic!("{e}"))); - let compiled = dev - .compile_function(&f, &LowerInputs::new(), &Budget::standard()) - .unwrap_or_else(|e| panic!("{e}")); - let d = ComputePipelineDescriptor::new(StageSource::Compiled(compiled)); - let pipe = dev - .compile_compute_pipeline(&d, &Budget::standard()) - .unwrap_or_else(|e| panic!("{e}")); - let mut table = StageTable::default(); - table.buffers.insert( - 0, - BoundBuffer::Buffer { - length: 1 << 20, - offset: 0, - gpu_address: OUT, - device_address: Some(OUT), - attribute_stride: None, - }, - ); - let mut state = BindState::default(); - state.stages.insert(Stage::Kernel, table); - let plan = pipe - .plan(&dev, &state.shape()) - .unwrap_or_else(|e| panic!("{e}")); - let id = (pipe.stage.specialization.constants.iter()) - .find(|c| c.key == SpecKey::DeepThreadgroup) - .map(|c| c.id) - .expect("the kernel declares DeepThreadgroup"); - for (threads_per_group, deep) in [([1, 1, 320], true), ([4, 4, 4], false)] { - let dispatch = Dispatch::Threadgroups { - groups: [2, 1, 1], - threads_per_group, - }; - let commands = plan - .instantiate_dispatch(&state, &dispatch) - .unwrap_or_else(|e| panic!("{threads_per_group:?}: {e}")); - assert!(!commands.regions.is_empty()); - for region in &commands.regions { - let entry = (region.specialization.entries.iter()) - .find(|e| e.constant_id == id) - .expect("every region sets DeepThreadgroup"); - let at = entry.offset as usize; - let set = - (region.specialization.data[at..at + entry.size as usize].iter()).any(|&b| b != 0); - assert_eq!(set, deep, "{threads_per_group:?}"); - } - } -} - /// A partial-threadgroups variant over a ragged grid, its region flagged `NONUNIFORM`, answers /// each edge threadgroup's own size, and its invocations past the grid store nothing. #[test] @@ -3963,67 +3802,6 @@ fn a_seq_cst_fence_is_refused_naming_its_form_under_the_identity_domains() { } } -/// The translator's binder supplies no field the runtime pushes itself under the identity domains: -/// planning a kernel that samples a texture slot through a sampler slot (owned fixture `sampling`'s -/// `sample_level`, whose words there are the two resource IDs) is -/// `Unsupported{IdentityDomains, NotImplemented}`, typed, never an internal invariant. The runtime -/// binds those words itself and never plans through the binder. -#[test] -fn the_binder_refuses_a_texture_and_sampler_slots_resource_ids_typed() { - let Some(bc) = assemble("sampling") else { - return; - }; - let desc = - crate::pipeline::testing::description("moltenvk-m3").unwrap_or_else(|e| panic!("{e}")); - let dev = Device::from_queries(desc, identity()).unwrap_or_else(|e| panic!("{e}")); - let lib = Library::from_air(&bc).unwrap_or_else(|e| panic!("{e}")); - let f = lib - .function("sample_level") - .unwrap_or_else(|e| panic!("{e}")); - let d = ComputePipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new(f))); - let pipe = dev - .compile_compute_pipeline(&d, &Budget::standard()) - .unwrap_or_else(|e| panic!("{e}")); - let mut table = StageTable::default(); - table.buffers.insert( - 0, - BoundBuffer::Buffer { - length: 4096, - offset: 0, - gpu_address: OUT, - device_address: Some(OUT), - attribute_stride: None, - }, - ); - table.textures.insert( - 0, - crate::bind::BoundTexture::Texture { - facts: crate::bind::TextureFacts::new( - crate::metal::TextureType::Type2D, - PixelFormat::RGBA8Unorm, - ), - resource_id: None, - }, - ); - table.samplers.insert( - 0, - crate::bind::BoundSampler::new(crate::bind::SamplerDescriptor::new()), - ); - let mut state = BindState::default(); - state.stages.insert(Stage::Kernel, table); - match pipe.plan(&dev, &state.shape()) { - Err(crate::error::BindError::Unsupported(u)) => { - let shown = u.to_string(); - assert_eq!( - (u.feature, u.needs), - (Feature::IdentityDomains, Needs::NotImplemented), - "{shown}" - ); - } - other => panic!("{other:?}"), - } -} - /// The golden table's storage pair under the identity domains (owned fixture /// `storage_texture_write`, a write through `texture2d`, given each format's storage /// choice as its input). A choice the identity arrays hold an element of, the bound format's own diff --git a/crates/metal2vulkan/src/tests/engine_image_shapes.rs b/crates/metal2vulkan/src/tests/engine_image_shapes.rs index eb0e52495..854e82c46 100644 --- a/crates/metal2vulkan/src/tests/engine_image_shapes.rs +++ b/crates/metal2vulkan/src/tests/engine_image_shapes.rs @@ -3,13 +3,12 @@ //! old engine's reflected `texture_shape` until 0.2.0 deleted both. //! //! Vulkan requires an image view's type to match the `Dim` and `Arrayed` of the image variable a -//! descriptor is read through, and its sample count the variable's `MS`. The binder makes each +//! descriptor is read through, and its sample count the variable's `MS`. A consumer makes each //! view from what the interface reports: the slot's Metal texture type, and the pipeline's //! `ImageViewShape` fact for a cube viewed as the 2D array it is declared as (SPIR-V has no texel -//! read of a cube). `bind::plan::resources`' own tests pin the binder's mapping from those to a -//! view. This file pins the other half: an independent walk of the final words finds every -//! variable a texture slot's binding names and requires its image to be the one that mapping -//! gives, so a module never declares an image its view cannot show. +//! read of a cube). This file pins the module's half: an independent walk of the final words finds +//! every variable a texture slot's binding names and requires its image to be the one that +//! mapping gives, so a module never declares an image its view cannot show. //! //! The mapping, written out again here: 1D, 2D and 3D types are their dimension, an array type //! is arrayed, a multisample type is multisampled, a cube is a cube, a cube array an arrayed diff --git a/crates/metal2vulkan/src/tests/engine_imageblock.rs b/crates/metal2vulkan/src/tests/engine_imageblock.rs index 61e7a840c..c63612c1e 100644 --- a/crates/metal2vulkan/src/tests/engine_imageblock.rs +++ b/crates/metal2vulkan/src/tests/engine_imageblock.rs @@ -29,17 +29,16 @@ use std::collections::BTreeMap; -use crate::bind::{BindState, BindingPlan, BoundTexture, ImageblockSize, StageTable, TextureFacts}; use crate::budget::Budget; use crate::cache::VariantKey; use crate::device::profile::DeviceProfile; use crate::device::{Device, DeviceDescription, DevicePolicy}; -use crate::error::{BindError, Error, Feature, LowerFamily, Needs, RuntimeInput}; +use crate::error::{Error, Feature, LowerFamily, Needs, RuntimeInput}; use crate::library::Library; use crate::lower::select::LowerInputs; use crate::lower::select::Plan; use crate::metal::format::storage_image_choice; -use crate::metal::{PixelFormat, TextureType, TextureUsage}; +use crate::metal::PixelFormat; use crate::pipeline::facts::{Mechanism, RuntimeFact}; use crate::pipeline::interface::PushLoc; use crate::pipeline::lower_inputs::{StorageImageChoice, StorageImageClass}; @@ -50,9 +49,7 @@ use crate::pipeline::testing::{ engine_dir, fixtures_dir, llvm_assemble, typed_module, typed_module_with, AssembleError, Scratch, }; -use crate::pipeline::{ - ComputePipeline, ComputePipelineDescriptor, FunctionDescriptor, StageSource, -}; +use crate::pipeline::{ComputePipelineDescriptor, FunctionDescriptor, StageSource}; use crate::spirv::interp::{run_with_images, Buffer, Config, Image, Order, Resources}; use crate::spirv::ir::TypedModule; use crate::spirv::testing::threadgroup_profiles; @@ -695,194 +692,6 @@ fn device(stem: &str) -> Device { Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device") } -fn pipeline(dev: &Device, bc: &[u8], entry: &str) -> ComputePipeline { - let lib = Library::from_air(bc).expect("library"); - let f = lib.function(entry).expect("function"); - let d = ComputePipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new(f))); - dev.compile_compute_pipeline(&d, &Budget::standard()) - .unwrap_or_else(|e| panic!("{entry}: {e}")) -} - -/// The value `plan` specializes `key` to. -fn specialized(pipe: &ComputePipeline, plan: &BindingPlan, key: SpecKey) -> Option { - let id = pipe - .stage - .specialization - .constants - .iter() - .find(|c| c.key == key)? - .id; - let e = plan - .specialization - .entries - .iter() - .find(|e| e.constant_id == id)?; - let at = e.offset as usize; - Some(u32::from_le_bytes( - plan.specialization.data[at..at + 4] - .try_into() - .expect("u32"), - )) -} - -/// The binder specializes the imageblock's extent from `BindState::imageblock_size`, refuses an -/// extent the encoder never set or `get_width` cannot answer, and charges the imageblock, after -/// the `[[threadgroup(0)]]` region, to `maxComputeSharedMemorySize`: exactly full plans, one -/// more cell does not. -#[test] -fn the_binder_specializes_and_charges_the_imageblock() { - let Some(bc) = owned() else { return }; - for stem in ["moltenvk-m3", "lavapipe", "runtime-floor"] { - let dev = device(stem); - let pipe = pipeline(&dev, &bc, "imageblock_after_threadgroup"); - assert!(pipe - .dependencies - .iter() - .any(|d| d.fact == RuntimeFact::ImageblockSize { cell_bytes: 8 })); - let state = |w: u32, h: u32| { - let mut table = StageTable::default(); - table.threadgroup_lengths.insert(0, 64); - let mut s = BindState::default(); - s.stages.insert(Stage::Kernel, table); - s.imageblock_size = ImageblockSize::new(w, h); - s - }; - for (w, h) in [(0, 0), (4, 0), (65536, 1)] { - assert_eq!( - pipe.plan(&dev, &state(w, h).shape()).map(|_| ()), - Err(BindError::InvalidImageblockSize { - width: w, - height: h - }), - "{stem}" - ); - } - let plan = pipe.plan(&dev, &state(4, 3).shape()).expect("plan"); - assert_eq!(specialized(&pipe, &plan, SpecKey::ImageblockWidth), Some(4)); - assert_eq!( - specialized(&pipe, &plan, SpecKey::ImageblockHeight), - Some(3) - ); - assert_eq!(specialized(&pipe, &plan, SpecKey::TgLength(0)), Some(64)); - // 64 region bytes, then 8-byte cells: `cells` of them fill the limit exactly. - let max = dev.profile().fields().limits.max_compute_shared_memory_size; - let cells = (max - 64) / 8; - assert!(pipe.plan(&dev, &state(cells, 1).shape()).is_ok(), "{stem}"); - match pipe.plan(&dev, &state(cells + 1, 1).shape()) { - Err(BindError::Unsupported(u)) => { - assert_eq!(u.feature, Feature::ThreadgroupMemorySize, "{stem}"); - assert!(format!("{:?}", u.needs).contains("MaxComputeSharedMemorySize")); - } - other => panic!("{stem}: {:?}", other.map(|_| ())), - } - } -} - -/// On a profile that writes storage images without a format, the binder keys an integer slice's -/// slot although the formatless declaration would serve its format: the function compiled under -/// the slot's choice depends on the numeric type it keeps (`StorageTextureNumericType`), so the -/// plan of a signed bound format asks for exactly the key it was compiled under, which every signed -/// format shares. The float slot keys nothing. -#[test] -fn a_formatless_profile_keys_an_integer_slice_type() { - let Some(bc) = owned() else { return }; - let dev = device("moltenvk-m3"); - let images = &dev.profile().fields().images; - assert!(images.storage_read_without_format && images.storage_write_without_format); - let budget = Budget::standard(); - let lib = Library::from_air(&bc).expect("library"); - let f = FunctionDescriptor::new(lib.function("imageblock_runtime_region").expect("function")); - match dev.compile_function(&f, &LowerInputs::new(), &budget) { - Err(Error::NeedsInput(RuntimeInput::StorageTextureFormat { slot })) => { - assert_eq!(slot, kernel_texture(0)); - } - other => panic!("{:?}", other.map(|_| ())), - } - let mut key = VariantKey::new(); - let choice = storage_image_choice(PixelFormat::RGBA16Sint, dev.profile()).expect("choice"); - assert_eq!(choice.vk_format, vk::Format::UNDEFINED); - key.storage_images.insert(kernel_texture(0), choice); - let compiled = dev - .compile_function(&f, &key.lowering_inputs(Stage::Kernel), &budget) - .expect("compiles under the choice"); - let pipe = dev - .compile_compute_pipeline( - &ComputePipelineDescriptor::new(StageSource::Compiled(compiled)), - &budget, - ) - .expect("pipeline"); - assert!(pipe.dependencies.iter().any(|d| d.fact - == RuntimeFact::StorageTextureNumericType { - slot: kernel_texture(0) - } - && d.mechanism == Mechanism::Variant)); - let state = |code: PixelFormat| { - let mut table = StageTable::default(); - for (index, pf) in [(0, code), (1, PixelFormat::R32Float)] { - let mut facts = TextureFacts::new(TextureType::Type2D, pf); - facts.usage = TextureUsage::SHADER_WRITE; - table.textures.insert( - index, - BoundTexture::Texture { - facts, - resource_id: None, - }, - ); - } - let mut s = BindState::default(); - s.stages.insert(Stage::Kernel, table); - s.imageblock_size = ImageblockSize::new(4, 4); - s - }; - // Every signed format shares the key; the float slot keys nothing. - for pf in [PixelFormat::RGBA16Sint, PixelFormat::R32Sint] { - let plan = pipe.plan(&dev, &state(pf).shape()).expect("plan"); - assert_eq!(plan.variant, key, "{pf:?}"); - } - assert_eq!( - key.storage_images[&kernel_texture(0)].numeric, - Some(SampledType::Sint) - ); -} - -/// A two-lane slice plans against a bound format of any component count, as Metal writes its -/// lanes and zeros whatever the format; an unbound texture drops the write. -#[test] -fn a_narrow_slice_plans_against_any_bound_format() { - let Some(bc) = owned() else { return }; - let dev = device("moltenvk-m3"); - let pipe = pipeline(&dev, &bc, "imageblock_sized_slice"); - let state = |pf: Option| { - let mut table = StageTable::default(); - if let Some(pf) = pf { - let mut facts = TextureFacts::new(TextureType::Type2D, pf); - facts.usage = TextureUsage::SHADER_WRITE; - table.textures.insert( - 0, - BoundTexture::Texture { - facts, - resource_id: None, - }, - ); - } - let mut s = BindState::default(); - s.stages.insert(Stage::Kernel, table); - s.imageblock_size = ImageblockSize::new(4, 4); - s - }; - for pf in [ - Some(PixelFormat::RG16Float), - None, - Some(PixelFormat::R16Float), - Some(PixelFormat::RGBA16Float), - Some(PixelFormat::RGBA32Float), - ] { - if let Err(e) = pipe.plan(&dev, &state(pf).shape()) { - panic!("{pf:?}: {e:?}"); - } - } -} - /// A kernel whose 4x4 threads each store their cell `(x, y, 7, 9)`, then, after the imageblock /// barrier and `between`, under the guard `guard` (which defines `%g`), write the whole imageblock /// to texture 0 at their threadgroup's position times 4: the shape `texture::cooperative` shares @@ -1161,3 +970,46 @@ fn a_cell_holds_the_widest_access_through_its_pointer() { } assert!(ran > 0); } + +/// On a profile that writes storage images without a format, an integer slice's slot is keyed +/// although the formatless declaration would serve its format: the function asks for the slot's +/// format (`NeedsInput(StorageTextureFormat)`), and compiled under a signed format's choice it +/// depends on the numeric type the choice keeps (`StorageTextureNumericType`), `Sint`. +#[test] +fn a_formatless_profile_keys_an_integer_slice_type() { + let Some(bc) = owned() else { return }; + let dev = device("moltenvk-m3"); + let images = &dev.profile().fields().images; + assert!(images.storage_read_without_format && images.storage_write_without_format); + let budget = Budget::standard(); + let lib = Library::from_air(&bc).expect("library"); + let f = FunctionDescriptor::new(lib.function("imageblock_runtime_region").expect("function")); + match dev.compile_function(&f, &LowerInputs::new(), &budget) { + Err(Error::NeedsInput(RuntimeInput::StorageTextureFormat { slot })) => { + assert_eq!(slot, kernel_texture(0)); + } + other => panic!("{:?}", other.map(|_| ())), + } + let mut key = VariantKey::new(); + let choice = storage_image_choice(PixelFormat::RGBA16Sint, dev.profile()).expect("choice"); + assert_eq!(choice.vk_format, vk::Format::UNDEFINED); + key.storage_images.insert(kernel_texture(0), choice); + let compiled = dev + .compile_function(&f, &key.lowering_inputs(Stage::Kernel), &budget) + .expect("compiles under the choice"); + let pipe = dev + .compile_compute_pipeline( + &ComputePipelineDescriptor::new(StageSource::Compiled(compiled)), + &budget, + ) + .expect("pipeline"); + assert!(pipe.dependencies.iter().any(|d| d.fact + == RuntimeFact::StorageTextureNumericType { + slot: kernel_texture(0) + } + && d.mechanism == Mechanism::Variant)); + assert_eq!( + key.storage_images[&kernel_texture(0)].numeric, + Some(SampledType::Sint) + ); +} diff --git a/crates/metal2vulkan/src/tests/engine_kernel_stage_in.rs b/crates/metal2vulkan/src/tests/engine_kernel_stage_in.rs index 5e58f158a..6d9411212 100644 --- a/crates/metal2vulkan/src/tests/engine_kernel_stage_in.rs +++ b/crates/metal2vulkan/src/tests/engine_kernel_stage_in.rs @@ -1,42 +1,24 @@ -//! Kernel `[[stage_in]]` through the pulled fetch, end to end on the CPU interpreter. No device is -//! opened. +//! Kernel `[[stage_in]]` through the pulled fetch. No device is opened. //! //! Each kernel of the owned fixture `kernel_stage_in` goes through the public compile API under a -//! compute pipeline's stage-input descriptor, `ComputePipeline::plan`, and -//! `BindingPlan::instantiate_dispatch`; the harness runs the typed module on the interpreter with -//! exactly what the binder planned (descriptor writes, every region's push bytes, its -//! specialization and group count), in both scheduling orders. The source buffers hold one -//! distinct value per element, so an element taken from the wrong step, rate, origin, stride, -//! offset, or index lands a value that exists nowhere else. +//! compute pipeline's stage-input descriptor: //! -//! - Every step Metal defines for a compute layout: `Constant`, `ThreadPositionInGridX`/`Y` at -//! rate 1 (from the stage-in region's origin) and above it, and `...Indexed` through 16- and -//! 32-bit indices; attributes sharing a layout, missing components, sign extension, and half -//! bits. -//! - `[[grid_origin]]` and `[[grid_size]]` read the region the binder writes, as 32-bit vectors -//! and 16-bit pairs. -//! - A layout of a fixed stride reads it whatever stride the buffer is bound with; one of -//! `MTLBufferLayoutStrideDynamic` reads the bound stride, 0 without one. -//! - A thread past the stage-in region reads the region's last element on each axis, before an -//! index lookup and with the origin added after it; a region of size 0 clamps nothing. The -//! descriptor refusals are typed. +//! - The descriptor refusals are typed. //! - A `Compiled` kernel's fetches must be the pipeline descriptor's; keys take the descriptor //! canonically. //! - Every committed profile validates the modules (L3). +//! - A kernel the stage-in region reaches is never a device-replay variant. +//! - A dynamic layout records its stride, a fixed one none; a step by thread position records +//! the region. //! //! `llvm-as` assembles the fixture; without it the tests skip visibly. -use std::collections::BTreeMap; use std::path::Path; -use crate::bind::{ - BindState, BoundBuffer, Dispatch, DispatchCommands, ExecutionStatus, PushHole, RootTable, - StageInRegion, StageTable, WriteSource, -}; use crate::budget::{Budget, SPIRV_WORDS}; use crate::device::profile::BufferAccess; use crate::device::{Device, DeviceDescription, DevicePolicy}; -use crate::error::{BindError, DescriptorError, Error, Feature, LowerFamily, Needs, RuntimeInput}; +use crate::error::{DescriptorError, Error, Feature, LowerFamily, Needs, RuntimeInput}; use crate::library::{FunctionConstantValues, Library}; use crate::metal::{AttributeFormat, IndexType, StepFunction}; use crate::pipeline::compile::{compile_bitcode, plan_bitcode, EntryRef}; @@ -44,27 +26,16 @@ use crate::pipeline::descriptor::{ StageInputAttributeDescriptor, StageInputDescriptor, StageInputLayoutDescriptor, }; use crate::pipeline::facts::RuntimeFact; -use crate::pipeline::layout::BindingSource; use crate::pipeline::lower_inputs::LoweringInputs; -use crate::pipeline::sym::{ResourceKind, ResourceSlot, SlotClass, SlotRef, SpecKey, Stage}; +use crate::pipeline::sym::{SlotClass, SlotRef, Stage}; use crate::pipeline::testing::{ - engine_dir, link_and_validate, llvm_assemble, meter, typed_module_with, AssembleError, + engine_dir, link_and_validate, llvm_assemble, meter, AssembleError, }; use crate::pipeline::{ ComputePipeline, ComputePipelineDescriptor, FunctionDescriptor, StageSource, }; -use crate::spirv::interp::{run, Buffer, Config, Order, Resources}; -use crate::spirv::ir::TypedModule; use crate::spirv::testing::committed_profiles; -/// Device addresses of the consumer-owned objects the harness places. -const TABLE: u64 = 0x0000_0010_0000_0000; -const SINK: u64 = 0x0000_0011_0000_0000; -const STATUS: u64 = 0x0000_0012_0000_0000; - -/// Profiles the dispatches run on. -const PROFILES: [&str; 2] = ["moltenvk-m3", "lavapipe"]; - fn fixture() -> Option> { match llvm_assemble(&engine_dir().join("kernel_stage_in.ll")) { Ok(b) => Some(b), @@ -86,32 +57,6 @@ fn device(stem: &str) -> Device { Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device") } -/// Each profile of [`PROFILES`] and Profile F (`runtime-floor` without device addresses, below -/// the runtime's floor, whose buffers are all descriptors). -fn devices() -> Vec<(String, Device)> { - use crate::pipeline::testing::{description_f, PROFILE_F}; - let mut out: Vec<(String, Device)> = PROFILES - .into_iter() - .map(|stem| (stem.to_owned(), device(stem))) - .collect(); - let f = description_f().expect("Profile F"); - let f = Device::from_queries(f, DevicePolicy::RESIDENT_TABLES).expect("Profile F's device"); - out.push((PROFILE_F.to_owned(), f)); - out -} - -/// The pipeline, or `None` when the device lacks a capability it needs (a descriptor limit). -fn compiled(what: &str, r: Result) -> Option { - match r { - Ok(p) => Some(p), - Err(Error::Unsupported(u)) if u.needs != Needs::NotImplemented => { - eprintln!("{what}: {u}"); - None - } - Err(e) => panic!("{what}: {e}"), - } -} - /// A stage-input descriptor: `attributes` as `(index, format, offset, buffer)`, `layouts` as /// `(buffer, stride, step, rate)`, and the index buffer. fn descriptor( @@ -199,1215 +144,6 @@ fn pipeline( dev.compile_compute_pipeline(&compute(function(bc, entry), d), &Budget::standard()) } -/// A bound Metal buffer. -#[derive(Clone)] -struct Alloc { - bytes: Vec, - offset: u64, -} - -/// What the consumer has: bound kernel buffers by index, the attribute strides they are bound -/// with (`setBuffer:offset:attributeStride:atIndex:`), the stage-in region the encoder set (if -/// any), the status buffer. -struct World { - buffers: BTreeMap, - strides: BTreeMap, - region: Option, - status: [u8; ExecutionStatus::BYTES], -} - -impl World { - fn new( - buffers: impl IntoIterator, - region: impl Into>, - ) -> World { - World { - buffers: buffers.into_iter().collect(), - strides: BTreeMap::new(), - region: region.into(), - status: ExecutionStatus::initial(), - } - } - - /// The world with each buffer of `strides` bound at its attribute stride. - fn with_strides(mut self, strides: impl IntoIterator) -> World { - self.strides = strides.into_iter().collect(); - self - } - - fn state(&self) -> BindState { - let mut t = StageTable::default(); - for (&i, a) in &self.buffers { - t.buffers.insert( - i, - BoundBuffer::Buffer { - length: a.bytes.len() as u64, - offset: a.offset, - gpu_address: 0, - device_address: None, - attribute_stride: self.strides.get(&i).copied(), - }, - ); - } - let mut s = BindState::default(); - s.stages.insert(Stage::Kernel, t); - s.stage_in_region = self.region; - s - } -} - -fn padded(mut v: Vec) -> Vec { - v.resize(v.len().next_multiple_of(16).max(16), 0); - v -} - -/// Where each interpreter buffer's final bytes go. -enum Back { - Slice { slot: u32, offset: usize }, - Status, - Nowhere, -} - -fn symbol(source: BindingSource) -> ResourceSlot { - match source { - BindingSource::Buffer(slot) => ResourceSlot { - stage: slot.stage, - kind: ResourceKind::Buffer, - index: slot.index, - }, - BindingSource::Synthetic { stage, binding } => ResourceSlot { - stage, - kind: ResourceKind::Synthetic(binding), - index: 0, - }, - other => panic!("a compute binding {other:?}"), - } -} - -/// Plan, instantiate, and run `dispatch` of `pipe` (whose typed module is `m`) over `world`. -fn execute( - dev: &Device, - pipe: &ComputePipeline, - m: &TypedModule, - world: &mut World, - dispatch: &Dispatch, -) -> Result { - let state = world.state(); - let plan = pipe.plan(dev, &state.shape())?; - let cmds = plan.instantiate_dispatch(&state, dispatch)?; - let layout: BTreeMap<(u32, u32), BindingSource> = pipe - .layout - .sets - .iter() - .flat_map(|s| { - s.bindings - .iter() - .map(move |b| ((s.set, b.binding), b.source)) - }) - .collect(); - let ids: BTreeMap = pipe - .stage - .specialization - .constants - .iter() - .map(|c| (c.id, c.key)) - .collect(); - for region in &cmds.regions { - let mut buffers = Vec::new(); - let mut back = Vec::new(); - for w in &plan.descriptors { - let sym = symbol(layout[&(w.set, w.binding)]); - let range = cmds - .descriptor_ranges - .iter() - .find(|r| (r.set, r.binding) == (w.set, w.binding)) - .map(|r| r.range); - let (bytes, to) = match &w.source { - WriteSource::Buffer { slot } => { - let r = range.expect("a range for every buffer write"); - let all = padded(world.buffers[&slot.index].bytes.clone()); - let (o, n) = (r.offset as usize, r.range as usize); - ( - all[o..o + n].to_vec(), - Back::Slice { - slot: slot.index, - offset: o, - }, - ) - } - WriteSource::Neutral(_) => (vec![0; 4096], Back::Nowhere), - WriteSource::ArgumentTable { .. } => { - let d = cmds - .descriptor_bytes - .iter() - .find(|d| (d.set, d.binding) == (w.set, w.binding)) - .expect("argument table bytes"); - (d.bytes.clone(), Back::Nowhere) - } - WriteSource::ConstantBlob { .. } => ( - padded(pipe.stage.constant_blob.as_deref().expect("blob").to_vec()), - Back::Nowhere, - ), - other => panic!("unexpected write {other:?}"), - }; - buffers.push(Buffer { - slot: Some(sym), - address: None, - bytes, - }); - back.push(to); - } - let mut push = Vec::new(); - if let Some(w) = region.push_constants.first() { - push = vec![0u8; (w.offset as usize) + w.bytes.len()]; - push[w.offset as usize..].copy_from_slice(&w.bytes); - } - for hole in &cmds.push_holes { - let (offset, address) = match *hole { - PushHole::RootTableAddress { offset, .. } => (offset, TABLE), - PushHole::ExecutionStatusAddress { offset, .. } => (offset, STATUS), - other => panic!("{other:?}"), - }; - let at = offset as usize; - push[at..at + 8].copy_from_slice(&address.to_le_bytes()); - if address == STATUS { - buffers.push(Buffer { - slot: None, - address: Some(STATUS), - bytes: world.status.to_vec(), - }); - back.push(Back::Status); - } - } - if let Some(RootTable { bytes, .. }) = &cmds.root_table { - let mut bytes = bytes.clone(); - let at = RootTable::SINK_HOST_OFFSET as usize; - bytes[at..at + 8].copy_from_slice(&SINK.to_le_bytes()); - buffers.push(Buffer { - slot: None, - address: Some(TABLE), - bytes, - }); - back.push(Back::Nowhere); - buffers.push(Buffer { - slot: None, - address: Some(SINK), - bytes: vec![0; 64], - }); - back.push(Back::Nowhere); - } - let mut spec = BTreeMap::new(); - for e in ®ion.specialization.entries { - let at = e.offset as usize; - let mut v = [0u8; 8]; - v[..e.size as usize] - .copy_from_slice(®ion.specialization.data[at..at + e.size as usize]); - spec.insert(ids[&e.constant_id], u64::from_le_bytes(v)); - } - let res = Resources { - buffers, - push, - spec, - }; - let mut outs = Vec::new(); - for order in [Order::Forward, Order::Reverse] { - let cfg = Config { - workgroups: region.group_count, - order, - ..Config::default() - }; - outs.push(run(m, &cfg, res.clone()).expect("run").buffers); - } - assert_eq!(outs[0], outs[1], "the two scheduling orders agree"); - for (bytes, to) in outs.swap_remove(0).into_iter().zip(back) { - match to { - Back::Slice { slot, offset } => { - let a = world.buffers.get_mut(&slot).expect("slot"); - for (i, b) in bytes.into_iter().enumerate() { - if let Some(dst) = a.bytes.get_mut(offset + i) { - *dst = b; - } - } - } - Back::Status => world - .status - .copy_from_slice(&bytes[..ExecutionStatus::BYTES]), - Back::Nowhere => {} - } - } - } - Ok(cmds) -} - -fn words(bytes: &[u8]) -> Vec { - bytes - .as_chunks::<4>() - .0 - .iter() - .map(|c| u32::from_le_bytes(*c)) - .collect() -} - -/// The dispatch grid of the fetch kernel: 5 x 3 threads in 2 x 2 threadgroups (edges on both -/// axes). -const W: u32 = 5; -const H: u32 = 3; - -fn threads(w: u32, h: u32) -> Dispatch { - Dispatch::Threads { - threads: [w, h, 1], - threads_per_group: [2, 2, 1], - } -} - -/// Elements the source buffers hold: enough for every step below, an index plus an origin -/// included. -const ELEMENTS: u32 = 24; - -/// Indices the index buffer holds. -const INDICES: u32 = 16; - -/// Layout 1's element `e` (stride 24): `f = (10e + 1, 10e + 2, 10e + 3)` at offset 4 and -/// `h = (bits 0x3c00 + e, 0x4000 + e)` at offset 16. -fn layout1() -> Vec { - let mut b = vec![0xAA; (24 * ELEMENTS) as usize]; - for e in 0..ELEMENTS { - let at = (24 * e) as usize; - for k in 0..3u32 { - let v = (10 * e + k + 1) as f32; - b[at + 4 + 4 * k as usize..][..4].copy_from_slice(&v.to_le_bytes()); - } - b[at + 16..][..2].copy_from_slice(&(0x3c00 + e as u16).to_le_bytes()); - b[at + 18..][..2].copy_from_slice(&(0x4000 + e as u16).to_le_bytes()); - } - b -} - -/// Layout 2's element `e` (stride 8): `u = (e, e + 100, e + 200, 0xffff - e)` as `ushort4`. -fn layout2() -> Vec { - let mut b = Vec::new(); - for e in 0..ELEMENTS as u16 { - for v in [e, e + 100, e + 200, 0xffff - e] { - b.extend_from_slice(&v.to_le_bytes()); - } - } - b -} - -/// Layout 3: the constant `i`, a `char` of -7 at offset 5. -fn layout3() -> Vec { - let mut b = vec![0x11; 16]; - b[5] = (-7i8) as u8; - b -} - -/// The index buffer: `index[k] = (7k + 3) mod INDICES`, in 2- or 4-byte indices. -fn index_of(k: u32) -> u32 { - (7 * k + 3) % INDICES -} - -fn index_buffer(t: IndexType) -> Vec { - let mut b = Vec::new(); - for k in 0..INDICES { - match t { - IndexType::UInt16 => b.extend_from_slice(&(index_of(k) as u16).to_le_bytes()), - _ => b.extend_from_slice(&index_of(k).to_le_bytes()), - } - } - b -} - -/// The three `uint4` the fetch kernel writes for a thread that reads layout 1's element `ex` and -/// layout 2's element `ey`, at position `t`. -fn expected_fetch(ex: u32, ey: u32, t: u32) -> [u32; 12] { - let f = |k: u32| ((10 * ex + k + 1) as f32).to_bits(); - [ - f(0), - f(1), - f(2), - 1.0f32.to_bits(), - ey, - ey + 100, - ey + 200, - 0xffff - ey, - (-7i32) as u32, - 0x3c00 + ex, - 0x4000 + ex, - t, - ] -} - -/// The element a step of a layout reads for thread position `at` on its axis under a stage-in -/// region of `origin` and `size` on that axis, as an M4 and an M3 Max read it: the position divided -/// by the rate, or the index at the position, clamped to the region's last element (its size less -/// 1, which wraps at a size of 0 and clamps nothing), plus the origin. -fn element(step: StepFunction, rate: u32, origin: u32, size: u32, at: u32) -> u32 { - let last = size.wrapping_sub(1); - match step { - StepFunction::ThreadPositionInGridX | StepFunction::ThreadPositionInGridY => { - origin.wrapping_add((at / rate).min(last)) - } - StepFunction::ThreadPositionInGridXIndexed | StepFunction::ThreadPositionInGridYIndexed => { - index_of(at.min(last)).wrapping_add(origin) - } - other => panic!("{other:?}"), - } -} - -/// The stage-in region of the fetch grid from `origin`. -fn grid_region(origin: [u32; 3]) -> StageInRegion { - StageInRegion::new(origin, [W, H, 1]) -} - -/// Run the fetch kernel under `x` (layout 1) and `y` (layout 2) with stage-in region `region` on -/// every device, and compare every thread's report. -fn run_fetch( - bc: &[u8], - x: (StepFunction, u32), - y: (StepFunction, u32), - index: IndexType, - region: StageInRegion, -) { - let d = fetch_descriptor(x, y, index); - let mut ran = 0; - for (what, dev) in devices() { - let Some(pipe) = compiled(&what, pipeline(&dev, bc, "stage_in_fetch", Some(&d))) else { - continue; - }; - ran += 1; - let (_, m) = typed_module_with(bc, "stage_in_fetch", dev.profile(), &inputs(&d)) - .unwrap_or_else(|e| panic!("{what}: {e}")); - let mut world = World::new( - [ - ( - 0, - Alloc { - bytes: vec![0; (48 * W * H) as usize], - offset: 0, - }, - ), - ( - 1, - Alloc { - bytes: layout1(), - offset: 0, - }, - ), - ( - 2, - Alloc { - bytes: layout2(), - offset: 0, - }, - ), - ( - 3, - Alloc { - bytes: layout3(), - offset: 0, - }, - ), - ( - 4, - Alloc { - bytes: index_buffer(index), - offset: 0, - }, - ), - ], - region, - ); - execute(&dev, &pipe, &m, &mut world, &threads(W, H)) - .unwrap_or_else(|e| panic!("{what}: {e}")); - let out = words(&world.buffers[&0].bytes); - let (origin, size) = (region.origin, region.size); - for gy in 0..H { - for gx in 0..W { - let t = gy * W + gx; - let ex = element(x.0, x.1, origin[0], size[0], gx); - let ey = element(y.0, y.1, origin[1], size[1], gy); - let at = (12 * t) as usize; - assert_eq!( - out[at..at + 12], - expected_fetch(ex, ey, t), - "{what} {x:?} {y:?} {index:?} {region:?}: thread ({gx}, {gy})" - ); - } - } - } - assert!(ran >= PROFILES.len(), "ran on {ran} devices"); -} - -/// Steps by thread position at rate 1 read the element at the region's origin plus the position, on -/// each axis; the constant step reads its offset alone; attributes sharing a layout read the same -/// element; `float3` into `float4` reads `w = 1`, `char` sign-extends, and half bits reach a half -/// attribute exactly. -#[test] -fn grid_steps_read_the_element_at_the_origin_plus_the_position() { - let Some(bc) = fixture() else { return }; - let x = (StepFunction::ThreadPositionInGridX, 1); - let y = (StepFunction::ThreadPositionInGridY, 1); - for origin in [[0, 0, 0], [2, 1, 4]] { - run_fetch(&bc, x, y, IndexType::UInt16, grid_region(origin)); - } - // The steps swapped: layout 1 by y and layout 2 by x. - let (sx, sy) = ( - (StepFunction::ThreadPositionInGridY, 1), - (StepFunction::ThreadPositionInGridX, 1), - ); - let d = fetch_descriptor(sx, sy, IndexType::UInt16); - let dev = device("moltenvk-m3"); - let pipe = pipeline(&dev, &bc, "stage_in_fetch", Some(&d)).expect("pipeline"); - let (_, m) = typed_module_with(&bc, "stage_in_fetch", dev.profile(), &inputs(&d)).expect("m"); - let mut world = World::new( - [ - ( - 0, - Alloc { - bytes: vec![0; (48 * W * H) as usize], - offset: 0, - }, - ), - ( - 1, - Alloc { - bytes: layout1(), - offset: 0, - }, - ), - ( - 2, - Alloc { - bytes: layout2(), - offset: 0, - }, - ), - ( - 3, - Alloc { - bytes: layout3(), - offset: 0, - }, - ), - ], - StageInRegion::new([1, 3, 0], [W, H, 1]), - ); - execute(&dev, &pipe, &m, &mut world, &threads(W, H)).expect("dispatch"); - let out = words(&world.buffers[&0].bytes); - for gy in 0..H { - for gx in 0..W { - let t = gy * W + gx; - let at = (12 * t) as usize; - assert_eq!( - out[at..at + 12], - expected_fetch(3 + gy, 1 + gx, t), - "({gx}, {gy})" - ); - } - } -} - -/// A step rate `n > 1` reads a new element every `n` threads on its axis. -#[test] -fn step_rates_divide_the_position() { - let Some(bc) = fixture() else { return }; - run_fetch( - &bc, - (StepFunction::ThreadPositionInGridX, 2), - (StepFunction::ThreadPositionInGridY, 3), - IndexType::UInt16, - grid_region([0, 0, 0]), - ); -} - -/// An indexed step reads the element the index buffer holds at the position, through 16- and 32-bit -/// indices; both axes read the one index buffer. -#[test] -fn indexed_steps_read_the_index_at_the_position() { - let Some(bc) = fixture() else { return }; - for index in [IndexType::UInt16, IndexType::UInt32] { - run_fetch( - &bc, - (StepFunction::ThreadPositionInGridXIndexed, 1), - (StepFunction::ThreadPositionInGridYIndexed, 1), - index, - grid_region([0, 0, 0]), - ); - } - // An indexed step beside a step at rate 1 on the other axis, which adds its origin. - run_fetch( - &bc, - (StepFunction::ThreadPositionInGridXIndexed, 1), - (StepFunction::ThreadPositionInGridY, 1), - IndexType::UInt32, - grid_region([0, 2, 0]), - ); -} - -/// A step at a rate above 1 adds the region's origin to the quotient, and an indexed step adds it -/// to the index it looks up at the position, not to the position looked up, as an M4 and an M3 Max -/// read; every step by thread position states that the kernel reads the region. -#[test] -fn a_nonzero_origin_adds_to_the_quotient_and_the_index() { - let Some(bc) = fixture() else { return }; - let dev = device("moltenvk-m3"); - for x in [ - (StepFunction::ThreadPositionInGridX, 2), - (StepFunction::ThreadPositionInGridXIndexed, 1), - (StepFunction::ThreadPositionInGridX, 1), - ] { - let d = fetch_descriptor(x, (StepFunction::Constant, 0), IndexType::UInt16); - let pipe = pipeline(&dev, &bc, "stage_in_fetch", Some(&d)).expect("pipeline"); - assert!( - pipe.dependencies - .iter() - .any(|f| f.fact == RuntimeFact::StageInRegion), - "{x:?}: {:?}", - pipe.dependencies - ); - } - run_fetch( - &bc, - (StepFunction::ThreadPositionInGridX, 2), - (StepFunction::ThreadPositionInGridY, 3), - IndexType::UInt16, - grid_region([2, 1, 4]), - ); - for index in [IndexType::UInt16, IndexType::UInt32] { - run_fetch( - &bc, - (StepFunction::ThreadPositionInGridXIndexed, 1), - (StepFunction::ThreadPositionInGridYIndexed, 1), - index, - grid_region([1, 3, 0]), - ); - } -} - -/// A thread past the stage-in region reads the region's last element on its axis, each axis apart: -/// a step by thread position clamps its quotient, and an indexed step the position it looks up, -/// before the origin is added. A region of size 0 on an axis clamps nothing there (its size less 1 -/// wraps), and a region of size 1 reads one element. -#[test] -fn a_thread_past_the_region_reads_its_last_element() { - let Some(bc) = fixture() else { return }; - let grid = ( - (StepFunction::ThreadPositionInGridX, 1), - (StepFunction::ThreadPositionInGridY, 1), - ); - let rates = ( - (StepFunction::ThreadPositionInGridX, 2), - (StepFunction::ThreadPositionInGridY, 3), - ); - let indexed = ( - (StepFunction::ThreadPositionInGridXIndexed, 1), - (StepFunction::ThreadPositionInGridYIndexed, 1), - ); - for (x, y) in [grid, rates, indexed] { - for region in [ - StageInRegion::new([0, 0, 0], [3, 2, 1]), - StageInRegion::new([2, 1, 0], [3, 2, 1]), - StageInRegion::new([1, 2, 0], [0, 0, 1]), - StageInRegion::new([0, 3, 0], [1, 1, 1]), - StageInRegion::new([2, 0, 0], [0, 1, 0]), - ] { - run_fetch(&bc, x, y, IndexType::UInt16, region); - } - } -} - -/// The sixteen `MTLAttributeFormat` values that cross the numeric classes — the unnormalized 8- -/// and 16-bit integer codings, which Metal converts into a float attribute — each with its -/// component count, its component width in bits and its signedness. -const CROSSINGS: [(AttributeFormat, usize, u32, bool); 16] = [ - (AttributeFormat::UChar, 1, 8, false), - (AttributeFormat::UChar2, 2, 8, false), - (AttributeFormat::UChar3, 3, 8, false), - (AttributeFormat::UChar4, 4, 8, false), - (AttributeFormat::Char, 1, 8, true), - (AttributeFormat::Char2, 2, 8, true), - (AttributeFormat::Char3, 3, 8, true), - (AttributeFormat::Char4, 4, 8, true), - (AttributeFormat::UShort, 1, 16, false), - (AttributeFormat::UShort2, 2, 16, false), - (AttributeFormat::UShort3, 3, 16, false), - (AttributeFormat::UShort4, 4, 16, false), - (AttributeFormat::Short, 1, 16, true), - (AttributeFormat::Short2, 2, 16, true), - (AttributeFormat::Short3, 3, 16, true), - (AttributeFormat::Short4, 4, 16, true), -]; - -/// The values a crossing format of `bits` bits and signedness `signed` carries on its components: -/// both ends of its range, zero and one, so a component read at the other signedness or the other -/// width lands a value none of the others holds. Each is exact in `f32`. -fn crossing_values(bits: u32, signed: bool) -> [i64; 4] { - match (bits, signed) { - (8, true) => [-128, -1, 0, 127], - (8, false) => [0, 1, 200, 255], - (_, true) => [-32768, -1, 0, 32767], - (_, false) => [0, 1, 40000, 65535], - } -} - -/// Layout 1's element 0 holding `count` components of `bits` bits at byte `at` — the values -/// [`crossing_values`] gives them — over [`layout1`]'s own element 0, so every other attribute -/// of the element reads what the rest of this file expects of it. -fn crossing_element(at: usize, count: usize, bits: u32, signed: bool) -> Vec { - let mut b = layout1(); - let width = (bits / 8) as usize; - for (k, value) in crossing_values(bits, signed).iter().take(count).enumerate() { - let raw = (*value as u64).to_le_bytes(); - b[at + k * width..][..width].copy_from_slice(&raw[..width]); - } - b -} - -/// The twelve words the fetch kernel's one thread reports for a crossing format carried by -/// attribute `declared`: each component's integer value as the attribute's own float class, the -/// components the format lacks as `(0, 0, 0, 1)` on the `float4` and as zero on the `half2`, and -/// every other attribute as [`expected_fetch`]'s element 0. -fn expected_crossing(declared: u32, count: usize, bits: u32, signed: bool) -> [u32; 12] { - let mut out = expected_fetch(0, 0, 0); - let values = crossing_values(bits, signed); - let value = |lane: usize| { - if lane < count { - values[lane] as f32 - } else { - f32::from(lane == 3) - } - }; - if declared == 0 { - for (lane, slot) in out[..4].iter_mut().enumerate() { - *slot = value(lane).to_bits(); - } - } else { - for (lane, slot) in out[9..11].iter_mut().enumerate() { - *slot = u32::from(crate::float16::f32_to_f16_bits(value(lane))); - } - } - out -} - -/// An unnormalized 8- or 16-bit integer format on a float-class `[[stage_in]]` attribute reads -/// each component's integer value, zero- or sign-extended by the format's signedness, as that -/// attribute's own float class — the conversion a pulled vertex attribute of the same format gets -/// (`fetch::class_match`'s `IntToFloat`), which Metal's stage-in fetch answers the same bits for as -/// its fixed-function vertex fetch. All sixteen crossing formats make the pipeline, on the `float4` -/// attribute and on the `half2` one, whose value is rounded to nearest even (65520 and above to -/// infinity). -#[test] -fn integer_formats_cross_into_a_float_attribute_as_their_values() { - let Some(bc) = fixture() else { return }; - let dispatch = Dispatch::Threads { - threads: [1, 1, 1], - threads_per_group: [1, 1, 1], - }; - let mut ran = 0; - for (what, dev) in devices() { - let mut here = 0; - // Attribute 0 (`float4`) at byte 4 and attribute 3 (`half2`) at byte 16 of layout 1, each - // in turn carrying the crossing format while the other three stay in their own class, so - // nothing but the crossing is in question. - for (declared, at) in [(0u32, 4usize), (3, 16)] { - for (format, count, bits, signed) in CROSSINGS { - let held = |index: u32, own: AttributeFormat| { - if index == declared { - format - } else { - own - } - }; - let d = descriptor( - &[ - (0, held(0, AttributeFormat::Float3), 4, 1), - (1, AttributeFormat::UShort4, 0, 2), - (2, AttributeFormat::Char, 5, 3), - (3, held(3, AttributeFormat::Half2), 16, 1), - ], - &[ - (1, 24, StepFunction::ThreadPositionInGridX, 1), - (2, 8, StepFunction::ThreadPositionInGridY, 1), - (3, 999, StepFunction::Constant, 0), - ], - (IndexType::UInt16, 4), - ); - let what = format!("{what} {format:?} on attribute {declared}"); - let Some(pipe) = compiled(&what, pipeline(&dev, &bc, "stage_in_fetch", Some(&d))) - else { - continue; - }; - let (_, m) = typed_module_with(&bc, "stage_in_fetch", dev.profile(), &inputs(&d)) - .unwrap_or_else(|e| panic!("{what}: {e}")); - let alloc = |bytes| Alloc { bytes, offset: 0 }; - let mut world = World::new( - [ - (0, alloc(vec![0; 48])), - (1, alloc(crossing_element(at, count, bits, signed))), - (2, alloc(layout2())), - (3, alloc(layout3())), - (4, alloc(index_buffer(IndexType::UInt16))), - ], - StageInRegion::new([0; 3], [1, 1, 1]), - ); - execute(&dev, &pipe, &m, &mut world, &dispatch) - .unwrap_or_else(|e| panic!("{what}: {e}")); - assert_eq!( - words(&world.buffers[&0].bytes), - expected_crossing(declared, count, bits, signed), - "{what}" - ); - here += 1; - } - } - assert_eq!(here, 2 * CROSSINGS.len(), "{what}: made {here} pipelines"); - ran += 1; - } - assert!(ran >= PROFILES.len(), "ran on {ran} devices"); -} - -/// The fetch kernel's buffers: its output, layouts 1 to 3, and a 16-bit index buffer. -fn fetch_buffers() -> [(u32, Alloc); 5] { - let alloc = |bytes| Alloc { bytes, offset: 0 }; - [ - (0, alloc(vec![0; (48 * W * H) as usize])), - (1, alloc(layout1())), - (2, alloc(layout2())), - (3, alloc(layout3())), - (4, alloc(index_buffer(IndexType::UInt16))), - ] -} - -/// What Metal reads as the stage-in region when the encoder never set one is not established, so a -/// kernel that reads the region (a step by thread position at any rate or through the index buffer, -/// `[[grid_origin]]`, `[[grid_size]]`) is not dispatched without it: `MissingStageInRegion`, before -/// anything is written. A kernel whose attributes all step `Constant` reads no region and -/// dispatches without one. -#[test] -fn a_kernel_that_reads_the_region_needs_the_encoders_region() { - let Some(bc) = fixture() else { return }; - let dev = device("moltenvk-m3"); - let constant = (StepFunction::Constant, 0); - for (x, y, reads) in [ - (constant, constant, false), - ((StepFunction::ThreadPositionInGridX, 1), constant, true), - ((StepFunction::ThreadPositionInGridX, 2), constant, true), - ( - constant, - (StepFunction::ThreadPositionInGridYIndexed, 1), - true, - ), - ] { - let d = fetch_descriptor(x, y, IndexType::UInt16); - let pipe = pipeline(&dev, &bc, "stage_in_fetch", Some(&d)).expect("pipeline"); - let (_, m) = - typed_module_with(&bc, "stage_in_fetch", dev.profile(), &inputs(&d)).expect("m"); - let mut world = World::new(fetch_buffers(), None); - let r = execute(&dev, &pipe, &m, &mut world, &threads(W, H)); - if reads { - assert_eq!( - r.err(), - Some(BindError::MissingStageInRegion), - "{x:?} {y:?}" - ); - let mut world = World::new(fetch_buffers(), StageInRegion::new([0; 3], [W, H, 1])); - execute(&dev, &pipe, &m, &mut world, &threads(W, H)) - .unwrap_or_else(|e| panic!("{x:?} {y:?}: {e}")); - } else { - r.unwrap_or_else(|e| panic!("{x:?} {y:?}: {e}")); - let out = words(&world.buffers[&0].bytes); - // Every thread reads element 0 of layouts 1 and 2. - let want = expected_fetch(0, 0, 0); - for t in 0..W * H { - let at = (12 * t) as usize; - assert_eq!(out[at..at + 11], want[..11], "thread {t}"); - } - } - } - let pipe = pipeline(&dev, &bc, "stage_in_region_short", None).expect("pipeline"); - let (_, m) = typed_module_with( - &bc, - "stage_in_region_short", - dev.profile(), - &LoweringInputs::new(), - ) - .expect("m"); - let out = || { - [( - 0, - Alloc { - bytes: vec![0; 8 * 4], - offset: 0, - }, - )] - }; - let mut world = World::new(out(), None); - assert_eq!( - execute(&dev, &pipe, &m, &mut world, &threads(4, 1)).err(), - Some(BindError::MissingStageInRegion) - ); - let mut world = World::new(out(), StageInRegion::new([0; 3], [4, 1, 1])); - execute(&dev, &pipe, &m, &mut world, &threads(4, 1)).expect("dispatch"); -} - -/// The three `uint4` the fetch kernel writes for a thread at position `t` that reads layout 1's -/// attributes at byte `a1` of [`layout1`] and layout 2's at byte `a2` of [`layout2`], decoded from -/// the bytes there whatever their alignment (an element boundary or not). -fn expected_at(a1: usize, a2: usize, t: u32) -> [u32; 12] { - let (l1, l2) = (layout1(), layout2()); - let word = |b: &[u8], at: usize| u32::from_le_bytes(b[at..at + 4].try_into().expect("word")); - let half = |b: &[u8], at: usize| u32::from(u16::from_le_bytes([b[at], b[at + 1]])); - [ - word(&l1, a1 + 4), - word(&l1, a1 + 8), - word(&l1, a1 + 12), - 1.0f32.to_bits(), - half(&l2, a2), - half(&l2, a2 + 2), - half(&l2, a2 + 4), - half(&l2, a2 + 6), - (-7i32) as u32, - half(&l1, a1 + 16), - half(&l1, a1 + 18), - t, - ] -} - -/// [`expected_at`] where layout 1's or layout 2's element lies past the first `2^32` bytes from its -/// bind offset (`None`): that layout's attributes read zero bytes, and the float3's missing -/// component 1. -fn expected_reaching(a1: Option, a2: Option, t: u32) -> [u32; 12] { - let mut out = expected_at(a1.unwrap_or(0), a2.unwrap_or(0), t); - if a1.is_none() { - out[0..3].copy_from_slice(&[0; 3]); - out[9..11].copy_from_slice(&[0; 2]); - } - if a2.is_none() { - out[4..8].copy_from_slice(&[0; 4]); - } - out -} - -/// Run the fetch kernel under `d` (layout 1 stepping by x, layout 2 by y, both at rate 1) with -/// the source buffers bound at `strides`, on every device, and compare every thread's report -/// with the bytes at `s1 · x` of layout 1 and `s2 · y` of layout 2. -fn run_strided(bc: &[u8], d: &StageInputDescriptor, strides: &[(u32, u32)], s1: u32, s2: u32) { - run_reaching( - bc, - d, - strides, - |gx| Some((s1 * gx) as usize), - |gy| Some((s2 * gy) as usize), - ); -} - -/// The `SpecKey::StageInReach` each region of `cmds` takes, which `pipe`'s kernel declares. -fn reach_values(pipe: &ComputePipeline, cmds: &DispatchCommands) -> Vec { - let id = (pipe.stage.specialization.constants.iter()) - .find(|c| c.key == SpecKey::StageInReach) - .map(|c| c.id) - .expect("a thread-position fetch declares StageInReach"); - (cmds.regions.iter()) - .map(|r| { - let key = &r.specialization; - let e = (key.entries.iter()) - .find(|e| e.constant_id == id) - .expect("each region sets StageInReach"); - let bytes = &key.data[e.offset as usize..][..e.size as usize]; - bytes.iter().rev().fold(0, |v, &b| v << 8 | u64::from(b)) - }) - .collect() -} - -/// [`run_strided`] where `at1(x)` and `at2(y)` name the byte each thread reads layout 1 and -/// layout 2 at, `None` where its element lies past the first `2^32` bytes and reads zero. -fn run_reaching( - bc: &[u8], - d: &StageInputDescriptor, - strides: &[(u32, u32)], - at1: impl Fn(u32) -> Option, - at2: impl Fn(u32) -> Option, -) { - let mut ran = 0; - for (what, dev) in devices() { - let Some(pipe) = compiled(&what, pipeline(&dev, bc, "stage_in_fetch", Some(d))) else { - continue; - }; - ran += 1; - let (_, m) = typed_module_with(bc, "stage_in_fetch", dev.profile(), &inputs(d)) - .unwrap_or_else(|e| panic!("{what}: {e}")); - let mut world = World::new(fetch_buffers(), StageInRegion::new([0; 3], [W, H, 1])) - .with_strides(strides.iter().copied()); - let cmds = execute(&dev, &pipe, &m, &mut world, &threads(W, H)) - .unwrap_or_else(|e| panic!("{what} {strides:?}: {e}")); - // Each region keeps the reach check (`StageInReach` 1) exactly where an element lies past - // the first `2^32` bytes, and drops it everywhere else. - let reaches = (0..W).any(|gx| at1(gx).is_none()) || (0..H).any(|gy| at2(gy).is_none()); - assert_eq!( - reach_values(&pipe, &cmds), - vec![u64::from(reaches); cmds.regions.len()], - "{what} {strides:?}" - ); - let out = words(&world.buffers[&0].bytes); - for gy in 0..H { - for gx in 0..W { - let t = gy * W + gx; - let at = (12 * t) as usize; - assert_eq!( - out[at..at + 12], - expected_reaching(at1(gx), at2(gy), t), - "{what} {strides:?}: thread ({gx}, {gy})" - ); - } - } - } - assert!(ran >= PROFILES.len(), "ran on {ran} devices"); -} - -/// A layout of a fixed stride fetches at it whatever stride the encoder binds its buffer with, as -/// an M4 reads one (a fixed 16 read at 16 under a bound 8): such a kernel -/// records no `RuntimeFact::StageInStride` and pushes no stride. -#[test] -fn a_fixed_layout_reads_its_own_stride_whatever_the_bind() { - let Some(bc) = fixture() else { return }; - let d = fetch_descriptor( - (StepFunction::ThreadPositionInGridX, 1), - (StepFunction::ThreadPositionInGridY, 1), - IndexType::UInt16, - ); - let dev = device("moltenvk-m3"); - let pipe = pipeline(&dev, &bc, "stage_in_fetch", Some(&d)).expect("pipeline"); - assert!( - !pipe - .dependencies - .iter() - .any(|f| matches!(f.fact, RuntimeFact::StageInStride { .. })), - "{:?}", - pipe.dependencies - ); - run_strided(&bc, &d, &[(1, 32), (2, 4), (3, 12)], 24, 8); -} - -/// A layout of `MTLBufferLayoutStrideDynamic` fetches at the stride the encoder binds its buffer -/// with, as an M4 reads it (element `e` at `e · stride` from the bind offset -/// for strides 0, 2, 4, 6, 8, 12, 16 and 256, unaligned ones byte-exact); a buffer bound without -/// one reads at stride 0, as Metal does without its validation layer (which reads every element -/// past the first as zeros instead). The kernel records `RuntimeFact::StageInStride` for each -/// dynamic layout it reads, and a constant step's layout reads no stride. -#[test] -fn a_dynamic_layout_reads_the_bound_stride() { - let Some(bc) = fixture() else { return }; - let mut d = fetch_descriptor( - (StepFunction::ThreadPositionInGridX, 1), - (StepFunction::ThreadPositionInGridY, 1), - IndexType::UInt16, - ); - for layout in [1, 2, 3] { - d.layouts.get_mut(&layout).expect("layout").stride = None; - } - let dev = device("moltenvk-m3"); - let pipe = pipeline(&dev, &bc, "stage_in_fetch", Some(&d)).expect("pipeline"); - let strides: Vec = pipe - .dependencies - .iter() - .filter_map(|f| match f.fact { - RuntimeFact::StageInStride { layout } => Some(layout), - _ => None, - }) - .collect(); - assert_eq!(strides, [1, 2], "{:?}", pipe.dependencies); - // The layouts' own strides, then others: none, unaligned, and a halfword one. - for (s1, s2) in [(24, 8), (0, 16), (12, 2), (6, 0), (25, 3)] { - run_strided(&bc, &d, &[(1, s1), (2, s2), (3, 7)], s1, s2); - } - // Bound without a stride: 0. - run_strided(&bc, &d, &[(1, 24)], 24, 0); - run_strided(&bc, &d, &[], 0, 0); -} - -/// An element whose bytes lie past the first `2^32` bytes from the bind offset reads zero bytes, -/// on every device: Metal places an element at `e · stride + offset` in 64 bits, past every buffer -/// the runtime does not refuse the dispatch for, where the `u32` displacement wraps back into the -/// buffer. A dynamic layout bound with `MTLAttributeStrideStatic` reads at its low 32 bits, -/// `2^32 - 1`, so its first element is the one at the bind offset and every element past it reads -/// zero, as plain Metal on an Apple M3 Max under macOS 27.0.1 answered each of the four stride -/// forms (`metal2vulkan-conformance`'s `attribute-stride-*`). Without the reach check element 1 of -/// layout 1 reads its float3 at byte `2^32 - 1 + 4`, which wraps to byte 3. -#[test] -fn an_element_past_four_gigabytes_reads_zero() { - let Some(bc) = fixture() else { return }; - let mut d = fetch_descriptor( - (StepFunction::ThreadPositionInGridX, 1), - (StepFunction::ThreadPositionInGridY, 1), - IndexType::UInt16, - ); - for layout in [1, 2] { - d.layouts.get_mut(&layout).expect("layout").stride = None; - } - let first = |e: u32| (e == 0).then_some(0); - // `MTLAttributeStrideStatic` on both layouts, and on one beside a stride of its own. - run_reaching(&bc, &d, &[(1, u32::MAX), (2, u32::MAX)], first, first); - run_reaching(&bc, &d, &[(1, u32::MAX), (2, 8)], first, |gy| { - Some((8 * gy) as usize) - }); - // Element 1 of layout 1 ends 8 bytes past `2^32` (its float3's 12 bytes at 4 + `2^32 - 8`), - // and element 2's `2^33 - 16` wraps to `2^32 - 16` in 32 bits: both read zero. - run_reaching(&bc, &d, &[(1, u32::MAX - 7), (2, 8)], first, |gy| { - Some((8 * gy) as usize) - }); -} - -/// A source buffer's bind offset moves the fetch with it (the range and the residual), and one -/// bound too short reads zero bytes past its end through the in-shader check. -#[test] -fn bind_offsets_and_short_buffers_reach_the_right_bytes() { - let Some(bc) = fixture() else { return }; - let d = fetch_descriptor( - (StepFunction::ThreadPositionInGridX, 1), - (StepFunction::ThreadPositionInGridY, 1), - IndexType::UInt16, - ); - for (what, dev) in devices() { - let pipe = pipeline(&dev, &bc, "stage_in_fetch", Some(&d)).expect("pipeline"); - let (_, m) = - typed_module_with(&bc, "stage_in_fetch", dev.profile(), &inputs(&d)).expect("m"); - // Layout 1 bound 72 bytes (three elements) into its allocation; layout 2 holds two - // elements, so rows 2 and above read zeros. - let mut shifted = vec![0x55; 72]; - shifted.extend(layout1()); - let short: Vec = layout2()[..16].to_vec(); - let mut world = World::new( - [ - ( - 0, - Alloc { - bytes: vec![0; (48 * W * H) as usize], - offset: 0, - }, - ), - ( - 1, - Alloc { - bytes: shifted, - offset: 72, - }, - ), - ( - 2, - Alloc { - bytes: short, - offset: 0, - }, - ), - ( - 3, - Alloc { - bytes: layout3(), - offset: 0, - }, - ), - ], - StageInRegion::new([0, 0, 0], [W, H, 1]), - ); - execute(&dev, &pipe, &m, &mut world, &threads(W, H)) - .unwrap_or_else(|e| panic!("{what}: {e}")); - let out = words(&world.buffers[&0].bytes); - for gy in 0..H { - for gx in 0..W { - let t = gy * W + gx; - let at = (12 * t) as usize; - let mut want = expected_fetch(gx, gy, t); - if gy >= 2 { - want[4..8].copy_from_slice(&[0; 4]); - } - assert_eq!(out[at..at + 12], want, "{what}: thread ({gx}, {gy})"); - } - } - } -} - -/// `[[grid_origin]]` and `[[grid_size]]` read the stage-in region the binder writes, as `uint3` and -/// as `ushort2`, beside a fetch at the origin. -#[test] -fn the_region_builtins_read_the_bound_region() { - let Some(bc) = fixture() else { return }; - let d = descriptor( - &[(0, AttributeFormat::Float, 0, 1)], - &[(1, 4, StepFunction::ThreadPositionInGridX, 1)], - (IndexType::UInt16, 0), - ); - let samples: Vec = (0..ELEMENTS) - .flat_map(|e| (e as f32 + 0.5).to_le_bytes()) - .collect(); - let (origin, size) = ([3, 0, 7], [10, 20, 30]); - for (what, dev) in devices() { - let pipe = pipeline(&dev, &bc, "stage_in_region", Some(&d)).expect("pipeline"); - let (_, m) = - typed_module_with(&bc, "stage_in_region", dev.profile(), &inputs(&d)).expect("m"); - let mut world = World::new( - [ - ( - 0, - Alloc { - bytes: vec![0; 32 * 8], - offset: 0, - }, - ), - ( - 1, - Alloc { - bytes: samples.clone(), - offset: 0, - }, - ), - ], - StageInRegion::new(origin, size), - ); - execute(&dev, &pipe, &m, &mut world, &threads(8, 1)).expect("dispatch"); - let out = words(&world.buffers[&0].bytes); - for t in 0..8u32 { - let at = (8 * t) as usize; - let v = ((origin[0] + t) as f32 + 0.5).to_bits(); - assert_eq!( - out[at..at + 8], - [v, 3, 0, 7, 10, 20, 30, t], - "{what}: thread {t}" - ); - } - - // Without a stage input, as 16-bit pairs: no descriptor needed. - let pipe = pipeline(&dev, &bc, "stage_in_region_short", None).expect("pipeline"); - let (_, m) = typed_module_with( - &bc, - "stage_in_region_short", - dev.profile(), - &LoweringInputs::new(), - ) - .expect("m"); - let mut world = World::new( - [( - 0, - Alloc { - bytes: vec![0; 8 * 4], - offset: 0, - }, - )], - StageInRegion::new([1, 2, 3], [300, 40000, 5]), - ); - execute(&dev, &pipe, &m, &mut world, &threads(4, 1)).expect("dispatch"); - let out = &world.buffers[&0].bytes; - for t in 0..4usize { - let h: Vec = out[8 * t..8 * t + 8] - .as_chunks::<2>() - .0 - .iter() - .map(|c| u16::from_le_bytes([c[0], c[1]])) - .collect(); - assert_eq!(h, [1, 2, 300, 40000], "{what}: thread {t}"); - } - } -} - fn not_implemented(r: Result, feature: Feature) { match r { Err(Error::Unsupported(u)) => { @@ -1798,3 +534,57 @@ fn a_kernel_the_stage_in_region_reaches_is_no_replay_variant() { } assert!(checked > 0, "no committed profile with device addresses"); } + +/// A layout of a fixed stride fetches at it whatever stride the encoder binds its buffer with, so +/// a kernel whose layouts all have one records no `RuntimeFact::StageInStride`. A layout of +/// `MTLBufferLayoutStrideDynamic` reads the stride its buffer is bound with: the kernel records +/// `RuntimeFact::StageInStride` for each dynamic layout it reads, and a constant step's layout reads +/// no stride. +#[test] +fn a_dynamic_layout_records_its_stride_and_a_fixed_one_none() { + let Some(bc) = fixture() else { return }; + let mut d = fetch_descriptor( + (StepFunction::ThreadPositionInGridX, 1), + (StepFunction::ThreadPositionInGridY, 1), + IndexType::UInt16, + ); + let dev = device("moltenvk-m3"); + let strides = |d: &StageInputDescriptor| -> Vec { + let pipe = pipeline(&dev, &bc, "stage_in_fetch", Some(d)).expect("pipeline"); + pipe.dependencies + .iter() + .filter_map(|f| match f.fact { + RuntimeFact::StageInStride { layout } => Some(layout), + _ => None, + }) + .collect() + }; + assert!(strides(&d).is_empty(), "fixed strides"); + for layout in [1, 2, 3] { + d.layouts.get_mut(&layout).expect("layout").stride = None; + } + assert_eq!(strides(&d), [1, 2], "dynamic strides"); +} + +/// A step by thread position at any rate or through the index buffer reads the stage-in region, +/// so the kernel records `RuntimeFact::StageInRegion`. +#[test] +fn a_step_by_thread_position_records_the_region() { + let Some(bc) = fixture() else { return }; + let dev = device("moltenvk-m3"); + for x in [ + (StepFunction::ThreadPositionInGridX, 2), + (StepFunction::ThreadPositionInGridXIndexed, 1), + (StepFunction::ThreadPositionInGridX, 1), + ] { + let d = fetch_descriptor(x, (StepFunction::Constant, 0), IndexType::UInt16); + let pipe = pipeline(&dev, &bc, "stage_in_fetch", Some(&d)).expect("pipeline"); + assert!( + pipe.dependencies + .iter() + .any(|f| f.fact == RuntimeFact::StageInRegion), + "{x:?}: {:?}", + pipe.dependencies + ); + } +} diff --git a/crates/metal2vulkan/src/tests/engine_line_band.rs b/crates/metal2vulkan/src/tests/engine_line_band.rs index b5e038dbf..5bcad28ac 100644 --- a/crates/metal2vulkan/src/tests/engine_line_band.rs +++ b/crates/metal2vulkan/src/tests/engine_line_band.rs @@ -21,7 +21,6 @@ //! //! `llvm-as` assembles the fixtures; a missing tool skips visibly. No GPU is used. -use crate::bind::BindState; use crate::budget::Budget; use crate::cache::VariantKey; use crate::device::requirements::VkFeature as F; @@ -36,9 +35,7 @@ use crate::pipeline::descriptor::{ use crate::pipeline::link::band; use crate::pipeline::testing::{compile, engine_dir, llvm_assemble, AssembleError}; use crate::pipeline::BandPrimitive; -use crate::pipeline::RenderPipeline; -use crate::spirv::testing::{check_words_valid, committed_profiles}; -use crate::vk; +use crate::spirv::testing::committed_profiles; fn assemble(name: &str) -> Option> { let path = engine_dir().join(name); @@ -81,164 +78,6 @@ fn band_key(primitive: BandPrimitive) -> VariantKey { key } -/// The `OutputVertices` execution mode of module `words`. -fn output_vertices(words: &[u32]) -> Option { - use crate::spirv_binary::{parse_bytes, Operand}; - use crate::spv::{ExecutionMode as M, Op as O}; - let bytes: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); - let parsed = parse_bytes(&bytes).expect("parse"); - (parsed.instructions.iter()) - .filter(|i| i.opcode == O::ExecutionMode) - .find_map(|i| match i.operands.as_slice() { - [_, Operand::Word(m), Operand::Word(n)] if *m == M::OutputVertices as u32 => Some(*n), - _ => None, - }) -} - -/// Each stage of `p` valid on `dev`; and `p`'s stages in order. -fn valid_stages(p: &RenderPipeline, dev: &Device, what: &str) -> Vec { - for m in &p.stages { - check_words_valid(&m.spirv, &p.requirements, dev.profile()) - .unwrap_or_else(|e| panic!("{what} {:?}: L3: {e}", m.stage)); - } - p.stages.iter().map(|m| m.stage).collect() -} - -/// On every committed profile with `tessellationShader`, the band variant of either primitive -/// carries the two synthesized stages after the vertex stage, each valid, draws a patch list of -/// the primitive's control points and pushes its band to the evaluation stage's own range; without -/// the variant, no stage. -#[test] -fn the_band_variant_draws_patches_of_its_primitive_through_valid_stages() { - let Some(provoking) = assemble("rt6_provoking.ll") else { - return; - }; - let Some(stage_io) = assemble("stage_io.ll") else { - return; - }; - let pipelines = [ - ( - "flat and smooth", - render(&provoking, "pv_vertex", "pv_flat", PixelFormat::RGBA8Unorm), - ), - ( - "smooth", - render( - &provoking, - "pv_vertex_smooth", - "pv_smooth", - PixelFormat::RGBA8Unorm, - ), - ), - ( - "clip distances", - render( - &stage_io, - "stage_io_vertex_clip", - "stage_io_fragment_primitive", - PixelFormat::RGBA8Unorm, - ), - ), - ]; - let budget = Budget::standard(); - let mut drawn = [0; 2]; - for (stem, dev) in committed_devices() { - let tessellates = (dev.profile().enabled().features).contains(&F::TessellationShader); - for ((what, d), (k, primitive)) in pipelines - .iter() - .flat_map(|p| std::iter::repeat(p).zip(PRIMITIVES.into_iter().enumerate())) - { - let what = format!("{stem} {what} {primitive:?}"); - let plain = match dev.compile_render_pipeline(d, &budget) { - Ok(p) => p, - // A pipeline the profile refuses without a band has no band to test. - Err(Error::Unsupported(_)) => continue, - Err(e) => panic!("{what}: {e}"), - }; - assert!(plain.graphics.line_band.is_none(), "{what}"); - assert!( - !valid_stages(&plain, &dev, &what).contains(&vk::ShaderStage::TESSELLATION_CONTROL), - "{what}" - ); - let banded = match dev.compile_render_variant(d, &band_key(primitive), &budget) { - Ok(p) => p, - Err(Error::Unsupported(u)) if !tessellates => { - assert_eq!(u.feature, Feature::WideLines, "{what}"); - assert_eq!( - u.needs, - Needs::AnyOf(vec![vec![Capability::Feature(F::TessellationShader)]]), - "{what}" - ); - continue; - } - Err(e) => panic!("{what}: {e}"), - }; - assert!(tessellates, "{what}: a band without tessellationShader"); - assert_eq!( - valid_stages(&banded, &dev, &what), - [ - vk::ShaderStage::VERTEX, - vk::ShaderStage::TESSELLATION_CONTROL, - vk::ShaderStage::TESSELLATION_EVALUATION, - vk::ShaderStage::FRAGMENT, - ], - "{what}" - ); - let g = &banded.graphics; - assert_eq!(g.topology, vk::PrimitiveTopology::PATCH_LIST, "{what}"); - assert!( - !g.dynamic_states.iter().any(|&s| matches!( - s, - vk::DynamicState::PRIMITIVE_TOPOLOGY - | vk::DynamicState::PRIMITIVE_RESTART_ENABLE - )), - "{what}" - ); - let band = g.line_band.expect("the band's state"); - assert_eq!(band.primitive, primitive, "{what}"); - assert_eq!( - output_vertices(&banded.stages[1].spirv), - Some(primitive.patch_control_points()), - "{what}" - ); - let ranges = &banded.layout.push_constants; - let own = ranges - .iter() - .find(|r| r.stages == vk::ShaderStageFlags::TESSELLATION_EVALUATION) - .unwrap_or_else(|| panic!("{what}: the band's push range")); - assert_eq!((own.offset, own.size), (band.push_offset, 16), "{what}"); - for r in ranges.iter().filter(|r| r.stages != own.stages) { - assert!( - r.offset + r.size <= own.offset || own.offset + own.size <= r.offset, - "{what}: {r:?} overlaps the band's range" - ); - } - assert!( - banded - .requirements - .features - .contains(&F::TessellationShader), - "{what}" - ); - assert_ne!(banded.key, plain.key, "{what}: the variant's own key"); - // The binder plans it for a shape that draws bands: its synthesized stages run no - // Metal function. - let state = BindState { - line_band: Some((primitive, [8.0, -8.0, 1.0, 1.0])), - ..BindState::default() - }; - banded - .plan(&dev, &state.shape()) - .unwrap_or_else(|e| panic!("{what}: the band's plan: {e:?}")); - drawn[k] += 1; - } - } - assert!( - drawn.iter().all(|&n| n > 0), - "a primitive no profile drew: {drawn:?}" - ); -} - /// A flat varying, or an integer one, is the first control point's at every corner; a smooth one /// is its endpoint's. #[test] diff --git a/crates/metal2vulkan/src/tests/engine_mesh.rs b/crates/metal2vulkan/src/tests/engine_mesh.rs index 024ce894b..549e97dc7 100644 --- a/crates/metal2vulkan/src/tests/engine_mesh.rs +++ b/crates/metal2vulkan/src/tests/engine_mesh.rs @@ -537,12 +537,10 @@ fn per_primitive_decorations(words: &[u32]) -> usize { /// A mesh render pipeline links its mesh function with a fragment function compiled for it: the /// fragment reads per primitive (`PerPrimitiveEXT`, flat) exactly the inputs the mesh function /// writes per primitive, and its other inputs as varyings. The pipeline's stages are the mesh and -/// fragment stages, each valid under the pipeline's requirements, with no vertex input, and the -/// binder plans its mesh draws ([`mesh_draws`]). A fragment function compiled for another pipeline -/// is `NeedsInput(PrimitiveVaryings)`, one compiled alone under the mesh function's primitive keys -/// links, and a pipeline with an object function passing a payload has its task stage first, each -/// stage valid, and its draws specialize each stage's threadgroup under its own keys -/// ([`object_draws`]). +/// fragment stages, each valid under the pipeline's requirements, with no vertex input. A fragment +/// function compiled for another pipeline is `NeedsInput(PrimitiveVaryings)`, one compiled alone +/// under the mesh function's primitive keys links, and a pipeline with an object function passing a +/// payload has its task stage first, each stage valid. #[test] fn a_mesh_pipeline_reads_its_primitive_outputs_per_primitive() { use crate::budget::Budget; @@ -616,7 +614,6 @@ fn a_mesh_pipeline_reads_its_primitive_outputs_per_primitive() { *per_primitive, "{what}: the fragment's per-primitive inputs" ); - mesh_draws(&dev, &pipeline, &what); } // The points' fragment function compiled on its own: for a render pipeline it reads the // primitive's `pc` per vertex, and under the mesh function's primitive keys it links. @@ -681,7 +678,6 @@ fn a_mesh_pipeline_reads_its_primitive_outputs_per_primitive() { check_words_valid(&m.spirv, &pipeline.requirements, dev.profile()) .unwrap_or_else(|e| panic!("{stem} {:?}: L3: {e}", m.stage)); } - object_draws(&dev, &pipeline, &stem); } } @@ -815,284 +811,6 @@ fn without_the_extension_a_mesh_pipeline_is_refused() { } } -/// Whether a draw's push constants hold the flagged region of a partial object threadgroup's draw -/// of `threads` in threadgroups of `l` (`lower::dispatch::partial_region_bytes`), or its argument -/// tables do, where the region is placed there. -fn flags_region(cmds: &crate::bind::DrawCommands, threads: [u32; 3], l: [u32; 3]) -> bool { - let flagged = crate::lower::dispatch::partial_region_bytes(threads, l).expect("a region"); - let holds = |bytes: &[u8]| bytes.windows(flagged.len()).any(|b| b == flagged); - cmds.push_constants.iter().any(|w| holds(&w.bytes)) - || cmds.descriptor_bytes.iter().any(|t| holds(&t.bytes)) -} - -/// The binder's draws of mesh pipeline `p` with an object function: each stage's threadgroup size -/// is a specialization of its own ids, which a draw of object threadgroups states beside each -/// other. -fn object_draws(dev: &crate::device::Device, p: &crate::pipeline::RenderPipeline, what: &str) { - use crate::bind::{BindState, DrawCall}; - use crate::pipeline::sym::Axis; - use crate::vk; - let state = BindState::default(); - let plan = p - .plan(dev, &state.shape()) - .unwrap_or_else(|e| panic!("{what}: plan: {e}")); - let constants: Vec<_> = p - .stages - .iter() - .flat_map(|s| s.specialization.constants.iter()) - .collect(); - let id = |key: SpecKey| constants.iter().find(|c| c.key == key).map(|c| c.id); - let object = [Axis::X, Axis::Y, Axis::Z].map(|a| id(SpecKey::ObjectLocalSize(a))); - let mesh = [Axis::X, Axis::Y, Axis::Z].map(|a| id(SpecKey::LocalSize(a))); - assert!( - object.iter().chain(&mesh).all(Option::is_some) && object != mesh, - "{what}: {constants:?}" - ); - let draw = DrawCall::MeshThreadgroups { - groups: [2, 1, 1], - threads_per_object_group: [4, 1, 1], - threads_per_mesh_group: [8, 1, 1], - }; - let cmds = plan - .instantiate_draw(&state, &draw) - .unwrap_or_else(|e| panic!("{what}: an object draw: {e}")); - assert_eq!( - cmds.draw, - vk::DrawCommand::DrawMeshTasks { - group_count_x: 2, - group_count_y: 1, - group_count_z: 1, - }, - "{what}" - ); - let key = cmds.specialization.as_ref().expect("a mesh draw's key"); - let value = |id: u32| { - key.entries.iter().find(|e| e.constant_id == id).map(|e| { - let at = e.offset as usize; - u32::from_le_bytes(key.data[at..at + 4].try_into().expect("4 bytes")) - }) - }; - assert_eq!( - object.map(|i| i.and_then(value)), - [Some(4), Some(1), Some(1)], - "{what}" - ); - assert_eq!( - mesh.map(|i| i.and_then(value)), - [Some(8), Some(1), Some(1)], - "{what}" - ); - // A `drawMeshThreads` that leaves a partial object threadgroup, which the object function - // (no barrier in its body) runs: the threadgroups its threads fill, rounded up, at their whole - // size, the region (or a folded variant's record) flagged. - assert!( - p.dependencies - .iter() - .any(|d| d.fact == crate::pipeline::facts::RuntimeFact::PartialObjectThreadgroups), - "{what}" - ); - let partial = DrawCall::MeshThreads { - threads: [6, 1, 1], - threads_per_object_group: [4, 1, 1], - threads_per_mesh_group: [8, 1, 1], - }; - let cmds = plan - .instantiate_draw(&state, &partial) - .unwrap_or_else(|e| panic!("{what}: a partial object threadgroup: {e}")); - assert_eq!( - cmds.draw, - vk::DrawCommand::DrawMeshTasks { - group_count_x: 2, - group_count_y: 1, - group_count_z: 1, - }, - "{what}" - ); - match &cmds.object_fold { - Some(fold) => assert_eq!( - fold.record, - [2, 1, 1, 3, 6, 1, 1, crate::lower::dispatch::NONUNIFORM], - "{what}" - ), - None => assert!( - flags_region(&cmds, [6, 1, 1], [4, 1, 1]), - "{what}: {:?}", - cmds.push_constants - ), - } - // Where the device folds object grids, the object function reads its region record, and a - // grid past the task stage's limits runs in pieces (`bind::mesh_arguments`). - let folds = crate::lower::mesh::folds_object_grids(dev.profile()); - assert_eq!( - p.dependencies - .iter() - .any(|d| d.fact == crate::pipeline::facts::RuntimeFact::FoldedGroups), - folds, - "{what}" - ); - if !folds { - return; - } - let hole = |c: &crate::bind::DrawCommands| { - c.push_holes.iter().any(|h| { - matches!(h, crate::bind::PushHole::ReplayRegionAddress { stages, .. } - if *stages == vk::ShaderStageFlags::TASK_EXT) - }) - }; - assert!(hole(&cmds) && cmds.object_fold.is_some(), "{what}"); - let task = dev.profile().fields().limits.mesh.max_task_work_group_count; - let draw = DrawCall::MeshThreadgroups { - groups: [task[0].saturating_add(1), 100, 1], - threads_per_object_group: [4, 1, 1], - threads_per_mesh_group: [8, 1, 1], - }; - let cmds = plan - .instantiate_draw(&state, &draw) - .unwrap_or_else(|e| panic!("{what}: a folded object draw: {e}")); - let fold = cmds.object_fold.expect("a fold"); - assert!( - fold.pieces >= 1 && !fold.past && hole(&cmds), - "{what}: {fold:?}" - ); - let indirect = DrawCall::MeshThreadgroupsIndirect { - indirect: crate::bind::IndirectRef { - token: 1, - offset: 0, - }, - threads_per_object_group: [4, 1, 1], - threads_per_mesh_group: [8, 1, 1], - }; - let cmds = plan - .instantiate_draw(&state, &indirect) - .unwrap_or_else(|e| panic!("{what}: a folded indirect object draw: {e}")); - assert!( - matches!( - cmds.draw, - vk::DrawCommand::DrawMeshTasksIndirectCount { .. } - ) && hole(&cmds), - "{what}: {:?}", - cmds.draw - ); -} - -/// The binder's plan of mesh pipeline `p` on `dev` and its mesh draws: the plan leaves the mesh -/// threadgroup's size to each draw, whose specialization states it beside the plan's constants, and -/// whose `DispatchRegion` is the draw's grid where the mesh function reads it; a draw of primitives -/// is `InvalidMeshDraw`; a mesh function that chooses its slice is planned for a pass of up to -/// `maxMeshOutputLayers` layers and no more. -fn mesh_draws(dev: &crate::device::Device, p: &crate::pipeline::RenderPipeline, what: &str) { - use crate::bind::{BindState, DrawCall}; - use crate::device::requirements::VkLimit; - use crate::error::BindError; - use crate::pipeline::sym::Axis; - use crate::vk; - let state = BindState::default(); - let plan = p - .plan(dev, &state.shape()) - .unwrap_or_else(|e| panic!("{what}: plan: {e}")); - let constants = &p.stages[0].specialization.constants; - let id = |key: SpecKey| constants.iter().find(|c| c.key == key).map(|c| c.id); - let local = [Axis::X, Axis::Y, Axis::Z].map(|a| id(SpecKey::LocalSize(a))); - assert!(local.iter().all(Option::is_some), "{what}: {constants:?}"); - assert!( - plan.specialization - .entries - .iter() - .all(|e| !local.contains(&Some(e.constant_id))), - "{what}: the plan's key leaves the threadgroup to the draw" - ); - let draw = DrawCall::MeshThreadgroups { - groups: [2, 1, 1], - threads_per_object_group: [1; 3], - threads_per_mesh_group: [8, 1, 1], - }; - let cmds = plan - .instantiate_draw(&state, &draw) - .unwrap_or_else(|e| panic!("{what}: a mesh draw: {e}")); - assert_eq!( - cmds.draw, - vk::DrawCommand::DrawMeshTasks { - group_count_x: 2, - group_count_y: 1, - group_count_z: 1, - }, - "{what}" - ); - let key = cmds.specialization.as_ref().expect("a mesh draw's key"); - let value = |id: u32| { - key.entries.iter().find(|e| e.constant_id == id).map(|e| { - let at = e.offset as usize; - u32::from_le_bytes(key.data[at..at + 4].try_into().expect("4 bytes")) - }) - }; - assert_eq!( - local.map(|i| i.and_then(value)), - [Some(8), Some(1), Some(1)], - "{what}" - ); - if let Some(multi) = id(SpecKey::MultiRegion) { - assert_eq!(value(multi), Some(0), "{what}"); - let region = - crate::lower::dispatch::region_bytes([0; 3], [16, 1, 1], [8, 1, 1]).expect("region"); - let mesh = vk::ShaderStageFlags::MESH_EXT; - let field = plan - .push - .fields - .iter() - .find(|f| f.stage == Stage::Mesh && f.field == PushField::DispatchRegion) - .expect("the mesh function's region"); - // Past the floor's one window the region is placed in the stage's argument table. - if let crate::bind::FieldLocation::PushWindow { offset } = field.location { - let write = cmds - .push_constants - .iter() - .find(|w| w.stages == mesh) - .expect("the mesh stage's push"); - let at = (offset - write.offset) as usize; - assert_eq!(write.bytes[at..at + 32], region, "{what}"); - } - } - assert_eq!( - plan.instantiate_draw( - &state, - &DrawCall::Primitives { - vertex_start: 0, - vertex_count: 3, - instance_count: 1, - base_instance: 0, - } - ) - .err(), - Some(BindError::InvalidMeshDraw { mesh: false }), - "{what}" - ); - // A pass of more layers than the mesh entry may write, where the function chooses its slice. - let chooses = p - .dependencies - .iter() - .any(|d| matches!(d.fact, RuntimeFact::RenderTargetArrayLength { .. })); - if chooses { - let layers = dev.profile().fields().limits.mesh.max_mesh_output_layers; - let mut shape = state.shape(); - shape.render_target_array_length = layers; - p.plan(dev, &shape) - .unwrap_or_else(|e| panic!("{what}: a pass of {layers} layers: {e}")); - shape.render_target_array_length = layers + 1; - assert_eq!( - p.plan(dev, &shape).err(), - Some(BindError::Unsupported(crate::error::Unsupported::needs( - Feature::MeshShading, - Capability::Limit { - limit: VkLimit::MaxMeshOutputLayers, - required: u64::from(layers) + 1, - available: u64::from(layers), - }, - ))), - "{what}" - ); - } -} - /// A mesh type's member under `[[function_constant(..)]]` (the VFX framework's particle meshes) is /// an output only where its constant holds; gated off, the mesh type has no such member, its write /// stores nothing, and the stage interface omits it. @@ -1349,7 +1067,7 @@ fn a_mesh_functions_buffer_writes_need_no_stage_store_feature() { /// object function; a maximum past 1024; a required size of other threads than its stage's /// maximum, in either stage (Metal's first compile); a function's maximum other than the /// descriptor's; a payload past 16384 bytes. An amplification count of 0 is refused as a render -/// pipeline's, and one of 2 is made, as Metal makes it ([`an_amplified_mesh_pipeline_draws_one_amplification`]). +/// pipeline's, and one of 2 is made, as Metal makes it. #[test] fn a_mesh_descriptor_metal_refuses_is_refused_as_its_rule() { use crate::budget::Budget; @@ -1576,69 +1294,6 @@ fn a_mesh_descriptor_metal_refuses_is_refused_as_its_rule() { } } -/// A mesh render pipeline of `maxVertexAmplificationCount` 2, which Metal makes (the -/// `mesh-limits-amplification-2` conformance recording, an M3 Max under macOS 27.0.1), is made on -/// every committed profile with `VK_EXT_mesh_shader`, without multiview, and draws one amplification, Metal's default, as a -/// pipeline without amplification does. Its draw of two is refused -/// `NotImplemented(VertexAmplification)`: Vulkan's multiview may run the task stage once a view, -/// where Metal runs the object function once a draw, and a mesh function does not add a view -/// mapping's offsets, as a draw of each amplification in turn would need. -#[test] -fn an_amplified_mesh_pipeline_draws_one_amplification() { - use crate::bind::{BindState, DrawCall, VertexAmplification}; - use crate::budget::Budget; - use crate::library::Library; - use crate::pipeline::descriptor::{FunctionDescriptor, MeshPipelineDescriptor, StageSource}; - let Some(draws) = fixture("mesh_draws") else { - return; - }; - let draws = Library::from_air(&draws).expect("library"); - let stage = |name: &str| { - StageSource::Function(FunctionDescriptor::new( - draws.function(name).expect("function"), - )) - }; - for (stem, _) in mesh_profiles() { - let dev = device(&stem); - let mut d = MeshPipelineDescriptor::new(stage("mesh_draws_mesh")); - d.object = Some(stage("mesh_draws_object")); - d.rasterization_enabled = false; - d.max_vertex_amplification_count = 2; - let p = dev - .compile_mesh_pipeline(&d, &Budget::standard()) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - assert_eq!(p.graphics.max_vertex_amplification_count, 2, "{stem}"); - assert!( - !p.requirements.features.contains(&VkFeature::Multiview), - "{stem}" - ); - let state = BindState::default(); - let plan = p - .plan(&dev, &state.shape()) - .unwrap_or_else(|e| panic!("{stem}: plan: {e}")); - let draw = DrawCall::MeshThreadgroups { - groups: [2, 1, 1], - threads_per_object_group: [1; 3], - threads_per_mesh_group: [8, 1, 1], - }; - plan.instantiate_draw(&state, &draw) - .unwrap_or_else(|e| panic!("{stem}: a draw: {e}")); - for mappings in [Vec::new(), vec![Default::default(); 2]] { - let two = BindState { - vertex_amplification: VertexAmplification::new(2, mappings), - ..Default::default() - }; - assert_eq!( - p.plan(&dev, &two.shape()).err(), - Some(crate::bind::plan::compute::not_implemented( - Feature::VertexAmplification - )), - "{stem}" - ); - } - } -} - /// `payloadMemoryLength` sizes the payload of both stages: in the mesh render pipeline of /// `mesh_outputs_object`, which declares 16 bytes, and `mesh_outputs_triangles`, which declares 16 /// and reads 64, a length of 64 gives the object function's arena and the mesh function's its 64 @@ -1702,145 +1357,3 @@ fn the_descriptors_payload_length_sizes_both_stages_payloads() { ); } } - -/// An object function's `[[threadgroup(n)]]` arguments take the render encoder's lengths -/// (`setObjectThreadgroupMemoryLength:atIndex:`, the object stage's `threadgroup_lengths`): in the -/// pipeline of `mesh_outputs_object` (its payload 64 bytes, [`wide_object_payload`]) and -/// `mesh_outputs_triangles`, a draw specializes `TgLength(0)` to the length rounded up to 16, as -/// a kernel's, and to 0 where it is unset. The artifact states the arena's static -/// part and its payload (`RuntimeFact::ObjectThreadgroupArena`). The plan checks the arena with the -/// lengths against the object stage's workgroup memory limit: the task stage's -/// (`maxTaskSharedMemorySize`, beside the wrapper's 12-byte grid), whose 76 bytes fit a 64-byte -/// length and not a 65-byte one. -#[test] -fn an_object_functions_threadgroup_memory_is_the_encoders_lengths() { - use crate::bind::{BindState, DrawCall}; - use crate::budget::Budget; - use crate::device::requirements::VkLimit; - use crate::device::{Device, DeviceDescription, DevicePolicy}; - use crate::error::{BindError, Unsupported}; - use crate::library::Library; - use crate::pipeline::descriptor::{FunctionDescriptor, MeshPipelineDescriptor, StageSource}; - let Some(wide) = wide_object_payload() else { - return; - }; - let wide = Library::from_air(&wide).expect("library"); - let function = |name: &str| { - StageSource::Function(FunctionDescriptor::new( - wide.function(name).expect("function"), - )) - }; - let budget = Budget::standard(); - let pipeline = |dev: &Device| { - let mut d = MeshPipelineDescriptor::new(function("mesh_outputs_triangles")); - d.object = Some(function("mesh_outputs_object")); - d.rasterization_enabled = false; - dev.compile_mesh_pipeline(&d, &budget) - }; - let with_length = |len: Option| { - let mut state = BindState::default(); - if let Some(len) = len { - state - .stages - .entry(Stage::Object) - .or_default() - .threadgroup_lengths - .insert(0, len); - } - state - }; - let draw = DrawCall::MeshThreadgroups { - groups: [1, 1, 1], - threads_per_object_group: [4, 1, 1], - threads_per_mesh_group: [8, 1, 1], - }; - let refused_limit = |r: Result| match r { - Err(BindError::Unsupported(Unsupported { - feature: Feature::ThreadgroupMemorySize, - needs: Needs::AnyOf(alternatives), - .. - })) => match alternatives.as_slice() { - [one] => match one.as_slice() { - [Capability::Limit { - limit, - required, - available, - }] => Some((*limit, *required, *available)), - _ => None, - }, - _ => None, - }, - _ => None, - }; - for (stem, p) in mesh_profiles() { - let dev = device(&stem); - let made = pipeline(&dev).unwrap_or_else(|e| panic!("{stem}: {e}")); - let arena: Vec<_> = made - .dependencies - .iter() - .filter_map(|d| match d.fact { - RuntimeFact::ObjectThreadgroupArena { - static_bytes, - payload, - } => Some((static_bytes, payload)), - _ => None, - }) - .collect(); - assert_eq!(arena, [(0, Some(64))], "{stem}"); - let id = made - .stages - .iter() - .flat_map(|s| s.specialization.constants.iter()) - .find(|c| c.key == SpecKey::TgLength(0)) - .map(|c| c.id) - .unwrap_or_else(|| panic!("{stem}: the object function's TgLength(0)")); - for (len, want) in [(None, 0), (Some(20), 32), (Some(64), 64)] { - let state = with_length(len); - let plan = made - .plan(&dev, &state.shape()) - .unwrap_or_else(|e| panic!("{stem} {len:?}: plan: {e}")); - let cmds = plan - .instantiate_draw(&state, &draw) - .unwrap_or_else(|e| panic!("{stem} {len:?}: draw: {e}")); - let key = cmds.specialization.as_ref().expect("a mesh draw's key"); - let value = key.entries.iter().find(|e| e.constant_id == id).map(|e| { - let at = e.offset as usize; - u32::from_le_bytes(key.data[at..at + 4].try_into().expect("4 bytes")) - }); - assert_eq!( - value, - Some(want), - "{stem} {len:?}: Metal's 16-byte rounding" - ); - } - // Past the object stage's limit, refused at plan naming it. - let past = p.fields().limits.mesh.max_task_shared_memory_size; - let refused = refused_limit(made.plan(&dev, &with_length(Some(past)).shape())); - let named = refused.map(|(limit, _, _)| limit); - assert!( - matches!( - named, - Some(VkLimit::MaxTaskSharedMemorySize) - | Some(VkLimit::MaxTaskPayloadAndSharedMemorySize) - ), - "{stem}: {refused:?}" - ); - } - // The task stage's limit: 76 bytes hold the wrapper's 12 and a 64-byte length, and a 65-byte - // length, 80 rounded, is refused naming it. - let (stem, _) = &mesh_profiles()[0]; - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join(format!("../metal2vulkan-validation/profiles/{stem}.json")); - let text = std::fs::read_to_string(path).expect("profile"); - let mut desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); - desc.limits.mesh.max_task_shared_memory_size = 76; - let dev = Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device"); - let made = pipeline(&dev).unwrap_or_else(|e| panic!("{stem} at 76: {e}")); - made.plan(&dev, &with_length(Some(64)).shape()) - .unwrap_or_else(|e| panic!("{stem} at 76: 64 bytes: {e}")); - assert_eq!( - refused_limit(made.plan(&dev, &with_length(Some(65)).shape())), - Some((VkLimit::MaxTaskSharedMemorySize, 92, 76)), - "{stem} at 76: 65 bytes" - ); -} diff --git a/crates/metal2vulkan/src/tests/engine_mesh_barriers.rs b/crates/metal2vulkan/src/tests/engine_mesh_barriers.rs index e41b10411..97da51b7c 100644 --- a/crates/metal2vulkan/src/tests/engine_mesh_barriers.rs +++ b/crates/metal2vulkan/src/tests/engine_mesh_barriers.rs @@ -12,11 +12,7 @@ //! //! `llvm-as` assembles the fixtures; a missing tool skips visibly. -use super::engine_mesh::{device, fixture, mesh_profiles}; -use crate::bind::{BindState, DrawCall}; -use crate::budget::Budget; -use crate::library::Library; -use crate::pipeline::descriptor::{FunctionDescriptor, MeshPipelineDescriptor, StageSource}; +use super::engine_mesh::{fixture, mesh_profiles}; use crate::pipeline::facts::RuntimeFact; use crate::pipeline::sym::Stage; use crate::pipeline::testing::typed_module; @@ -96,78 +92,3 @@ fn object_and_mesh_functions_wait_at_their_barriers_predicated() { } } } - -/// An object function whose body waits at a threadgroup barrier draws a `drawMeshThreads` that -/// leaves a partial object threadgroup: its pipeline records -/// `PartialObjectThreadgroups`, and both whole and partial draws instantiate, a partial one at the -/// threadgroups its threads fill, rounded up. `icb_object_threadgroup_object`'s barriers stand -/// under its thread 0's condition, the fixture's in uniform control flow. -#[test] -fn a_partial_object_threadgroup_of_a_body_with_a_barrier_draws() { - let (Some(icb), Some(partial)) = ( - fixture("icb_object_threadgroup"), - fixture("mesh_partial_barrier"), - ) else { - return; - }; - let icb = Library::from_air(&icb).expect("library"); - let partial = Library::from_air(&partial).expect("library"); - let function = |lib: &Library, name: &str| { - StageSource::Function(FunctionDescriptor::new( - lib.function(name).expect("function"), - )) - }; - let pipelines = [ - ( - &icb, - "icb_object_threadgroup_object", - "icb_object_threadgroup_mesh", - ), - ( - &partial, - "mesh_partial_barrier_uniform", - "mesh_partial_barrier_mesh", - ), - ]; - let draw = |threads| DrawCall::MeshThreads { - threads, - threads_per_object_group: [4, 1, 1], - threads_per_mesh_group: [8, 1, 1], - }; - for (stem, _) in mesh_profiles() { - let dev = device(&stem); - for (lib, object, mesh) in pipelines { - let what = format!("{stem} {object}"); - let mut d = MeshPipelineDescriptor::new(function(lib, mesh)); - d.object = Some(function(lib, object)); - d.rasterization_enabled = false; - let made = dev - .compile_mesh_pipeline(&d, &Budget::standard()) - .unwrap_or_else(|e| panic!("{what}: {e}")); - assert!( - made.dependencies - .iter() - .any(|d| d.fact == RuntimeFact::PartialObjectThreadgroups), - "{what}" - ); - let state = BindState::default(); - let plan = made - .plan(&dev, &state.shape()) - .unwrap_or_else(|e| panic!("{what}: plan: {e}")); - plan.instantiate_draw(&state, &draw([8, 1, 1])) - .unwrap_or_else(|e| panic!("{what}: whole object threadgroups: {e}")); - let cmds = plan - .instantiate_draw(&state, &draw([6, 1, 1])) - .unwrap_or_else(|e| panic!("{what}: a partial object threadgroup: {e}")); - let groups = match &cmds.draw { - crate::vk::DrawCommand::DrawMeshTasks { - group_count_x, - group_count_y, - group_count_z, - } => [*group_count_x, *group_count_y, *group_count_z], - other => panic!("{what}: {other:?}"), - }; - assert_eq!(groups, [2, 1, 1], "{what}"); - } - } -} diff --git a/crates/metal2vulkan/src/tests/engine_multisample.rs b/crates/metal2vulkan/src/tests/engine_multisample.rs index d0a19e05a..9b272209e 100644 --- a/crates/metal2vulkan/src/tests/engine_multisample.rs +++ b/crates/metal2vulkan/src/tests/engine_multisample.rs @@ -32,11 +32,10 @@ use std::path::Path; -use crate::bind::BindState; use crate::budget::Budget; use crate::device::requirements::{VkExtension, VkFeature, VkProperty}; use crate::device::{Device, DeviceDescription, DevicePolicy}; -use crate::error::{Capability, Error, Feature, LowerFamily, Needs, Unsupported}; +use crate::error::{Capability, Error, Feature, Unsupported}; use crate::library::Library; use crate::metal::{PixelFormat, VertexFormat}; use crate::pipeline::artifact::PrecisionNote; @@ -44,12 +43,8 @@ use crate::pipeline::descriptor::{ ColorAttachmentDescriptor, FunctionDescriptor, RenderPipelineDescriptor, StageSource, VertexAttributeDescriptor, VertexBufferLayoutDescriptor, VertexDescriptor, }; -use crate::pipeline::facts::RuntimeFact; use crate::pipeline::lower_inputs::LoweringInputs; -use crate::pipeline::sym::SpecKey; -use crate::pipeline::testing::{ - compile, engine_dir, llvm_assemble, moltenvk_msl_compile, AssembleError, Scratch, -}; +use crate::pipeline::testing::{engine_dir, llvm_assemble, moltenvk_msl_compile, AssembleError}; use crate::pipeline::RenderPipeline; use crate::spirv::testing::check_words_valid; @@ -629,101 +624,3 @@ fn a_center_varying_at_sample_rate_needs_the_interpolation_functions() { } } } - -/// The value of the planned specialization constant `key` of `p`. -pub(super) fn planned(p: &RenderPipeline, plan: &crate::bind::BindingPlan, key: SpecKey) -> u32 { - let id = p - .stages - .iter() - .flat_map(|m| m.specialization.constants.iter()) - .find(|c| c.key == key) - .unwrap_or_else(|| panic!("no {key:?} constant")) - .id; - let e = plan - .specialization - .entries - .iter() - .find(|e| e.constant_id == id) - .unwrap_or_else(|| panic!("no {key:?} entry")); - let at = e.offset as usize; - u32::from_le_bytes( - plan.specialization.data[at..at + 4] - .try_into() - .expect("4 bytes"), - ) -} - -/// `get_num_samples()` (`air.get_num_samples.i32` with operand 0, the owned fixture -/// `engine/spc_num_samples`) reads the `SampleCount` specialization constant, default 1, -/// and states `RuntimeFact::SampleCount`; a render pipeline's plan sets it to the pipeline's -/// sample count, at one and at four samples. Another operand has no established meaning and is -/// refused. -#[test] -fn get_num_samples_reads_the_pipeline_sample_count() { - let Some(ms) = fixture() else { return }; - let path = engine_dir().join("spc_num_samples.ll"); - let bc = match llvm_assemble(&path) { - Ok(b) => b, - Err(AssembleError::Missing(why)) => { - eprintln!("SKIPPED: {why}"); - return; - } - Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected spc_num_samples.ll: {why}"), - }; - let lib = Library::from_air(&bc).expect("library"); - let mut checked = 0; - for stem in ["moltenvk-m3", "lavapipe"] { - let dev = - Device::from_queries(description(stem), DevicePolicy::RESIDENT_TABLES).expect("device"); - let a = compile(&bc, "spc_num_samples", dev.profile()).expect("spc_num_samples"); - assert!(a.facts.contains(&RuntimeFact::SampleCount), "{stem}"); - for samples in [1, 4] { - let what = format!("{stem} at {samples}"); - let stage = |l: &Library, name: &str| { - StageSource::Function(FunctionDescriptor::new(l.function(name).expect("function"))) - }; - let mut d = RenderPipelineDescriptor::new(stage(&ms, VERTEX)); - d.fragment = Some(stage(&lib, "spc_num_samples")); - d.color_attachments[0] = Some(ColorAttachmentDescriptor::new(PixelFormat::R32Uint)); - d.raster_sample_count = samples; - let p = match dev.compile_render_pipeline(&d, &Budget::standard()) { - Err(Error::Unsupported(u)) if u.feature == Feature::RasterSampleCount => { - assert!(samples > 1 && stem != "moltenvk-m3", "{what}: {u:?}"); - eprintln!("{what}: not a framebuffer sample count of an integer attachment"); - continue; - } - p => p.unwrap_or_else(|e| panic!("{what}: {e}")), - }; - validate(&p, &dev, &what); - let plan = p.plan(&dev, &BindState::default().shape()).expect("plan"); - assert_eq!(planned(&p, &plan, SpecKey::SampleCount), samples, "{what}"); - checked += 1; - } - } - assert_eq!( - checked, 3, - "moltenvk-m3 at one and four samples, lavapipe at one" - ); - // The same call with operand 1. - let text = std::fs::read_to_string(&path).expect("fixture text"); - let other = text.replace( - "@air.get_num_samples.i32(i32 0)", - "@air.get_num_samples.i32(i32 1)", - ); - assert_ne!(other, text); - let scratch = Scratch::new("m2v-num-samples"); - let dir = scratch.path(); - let ll = dir.join("num_samples_one.ll"); - std::fs::write(&ll, other).expect("write"); - let bc = llvm_assemble(&ll); - let bc = bc.expect("assembled"); - let p = Device::from_queries(description("lavapipe"), DevicePolicy::RESIDENT_TABLES) - .expect("device"); - match compile(&bc, "spc_num_samples", p.profile()) { - Err(Error::Unsupported(u)) => { - assert_eq!(u.feature, Feature::Lowering(LowerFamily::Fragment)); - assert_eq!(u.needs, Needs::NotImplemented); - } - other => panic!("operand 1: {:?}", other.map(|_| ())), - } -} diff --git a/crates/metal2vulkan/src/tests/engine_opencl_mode.rs b/crates/metal2vulkan/src/tests/engine_opencl_mode.rs index ada2b1bb1..458de0d6d 100644 --- a/crates/metal2vulkan/src/tests/engine_opencl_mode.rs +++ b/crates/metal2vulkan/src/tests/engine_opencl_mode.rs @@ -11,15 +11,12 @@ //! by value is a read-only buffer of its own type, size and alignment, a struct's `Struct`. The //! modules are LLVM text written here (`llvm-as`). -use crate::bind::{BindState, BoundBuffer, BoundTexture, PlanDiagnostic, StageTable}; -use crate::bind::{TextureFacts, WriteSource}; use crate::budget::Budget; use crate::error::{DescriptorError, Error, Feature, LowerFamily}; use crate::library::Library; use crate::lower::select::LowerInputs; use crate::metal::{BindingAccess, BindingType, DataType}; use crate::pipeline::facts::RuntimeFact; -use crate::pipeline::sym::{SlotClass, SlotRef, Stage as SymStage}; use crate::pipeline::testing::AssembleError; use crate::pipeline::{ComputePipelineDescriptor, FunctionDescriptor, StageSource}; @@ -663,213 +660,6 @@ fn an_opencl_mode_kernel_binds_its_1d_images_as_2d_textures() { } } -/// `kernel void plain(texture2d t [[texture(0)]], device float4 *o -/// [[buffer(0)]], uint x [[thread_position_in_grid]])`: `o[x] = t.read(uint2(x, 0))`, a kernel of -/// no OpenCL mode. -const PLAIN_2D: &str = "target datalayout = \"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32\"\n\ -target triple = \"air64_v29-apple-macosx27.0.0\"\n\ -define void @plain(ptr addrspace(1) %t, ptr addrspace(1) %o, i32 %x) #0 {\n\ -entry:\n\ - %c = insertelement <2 x i32> , i32 %x, i64 0\n\ - %rs = tail call ptr addrspace(2) @air.get_read_sampler() #1\n\ - %r = tail call { <4 x float>, i8 } @air.read_texture_2d.v4f32(ptr addrspace(1) %t, ptr addrspace(2) %rs, <2 x i32> %c, <2 x i32> zeroinitializer, i32 0, i32 1) #1\n\ - %v = extractvalue { <4 x float>, i8 } %r, 0\n\ - %p = getelementptr inbounds <4 x float>, ptr addrspace(1) %o, i32 %x\n\ - store <4 x float> %v, ptr addrspace(1) %p, align 16\n\ - ret void\n}\n\ -declare ptr addrspace(2) @air.get_read_sampler() #1\n\ -declare { <4 x float>, i8 } @air.read_texture_2d.v4f32(ptr addrspace(1), ptr addrspace(2), <2 x i32>, <2 x i32>, i32, i32) #1\n\ -attributes #0 = { nounwind }\n\ -attributes #1 = { nounwind readonly willreturn }\n\ -!air.kernel = !{!0}\n\ -!air.version = !{!6}\n\ -!air.language_version = !{!7}\n\ -!0 = !{ptr @plain, !1, !2}\n\ -!1 = !{}\n\ -!2 = !{!3, !4, !5}\n\ -!3 = !{i32 0, !\"air.texture\", !\"air.location_index\", i32 0, i32 1, !\"air.read\", !\"air.arg_type_name\", !\"texture2d\", !\"air.arg_name\", !\"t\"}\n\ -!4 = !{i32 1, !\"air.buffer\", !\"air.location_index\", i32 0, i32 1, !\"air.read_write\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 16, !\"air.arg_type_align_size\", i32 16, !\"air.arg_type_name\", !\"float4\", !\"air.arg_name\", !\"o\"}\n\ -!5 = !{i32 2, !\"air.thread_position_in_grid\", !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"x\"}\n\ -!6 = !{i32 2, i32 9, i32 0}\n\ -!7 = !{!\"Metal\", i32 4, i32 0, i32 0}\n"; - -/// A bind state of a kernel: a buffer at each index of `buffers`, and at each texture index of -/// `textures` an `RGBA32Float` texture of its type. -fn bound( - buffers: std::ops::Range, - textures: &[(u32, crate::metal::TextureType)], -) -> BindState { - let mut t = StageTable::default(); - for index in buffers { - t.buffers.insert( - index, - BoundBuffer::Buffer { - length: 4096, - offset: 0, - gpu_address: 0x10_0000 * u64::from(index + 1), - device_address: None, - attribute_stride: None, - }, - ); - } - for &(index, texture_type) in textures { - let mut facts = TextureFacts::new(texture_type, crate::metal::PixelFormat::RGBA32Float); - facts.usage = - crate::metal::TextureUsage::SHADER_READ | crate::metal::TextureUsage::SHADER_WRITE; - t.textures.insert( - index, - BoundTexture::Texture { - facts, - resource_id: None, - }, - ); - } - let mut s = BindState::default(); - s.stages.insert(SymStage::Kernel, t); - s -} - -/// Kernel texture slot `index`. -fn texture_slot(index: u32) -> SlotRef { - SlotRef { - stage: SymStage::Kernel, - class: SlotClass::Texture, - index, - } -} - -/// The view the plan binds at kernel texture slot `index`, `None` where it binds the neutral. -fn view_at(plan: &crate::bind::BindingPlan, index: u32) -> Option { - plan.descriptors.iter().find_map(|w| match &w.source { - WriteSource::Texture { slot, view } if *slot == texture_slot(index) => Some(view.view_type), - _ => None, - }) -} - -/// Whether the plan says the texture bound at kernel texture slot `index` is not what the slot -/// declares (`PlanDiagnostic::IncompatibleBinding`), where it binds the neutral. -fn incompatible_at(plan: &crate::bind::BindingPlan, index: u32) -> bool { - plan.diagnostics.iter().any( - |d| matches!(d, PlanDiagnostic::IncompatibleBinding { slot, .. } if *slot == texture_slot(index)), - ) -} - -/// An OpenCL-mode kernel states each 1D image's slot (`RuntimeFact::OpenClLineTexture`). Bound as -/// Apple's OpenCL binds them (2D textures of height 1), its plan keeps the base: no variant, each -/// texture's 2D view. A real 1D texture at the 1D image and a 1D array texture at the 1D array -/// image (which Apple's OpenCL never binds) ask for the variant that names those two slots -/// (`VariantKey::open_cl_lines`); the variant's kernel declares them `Type1D` and `Type1DArray`, -/// and its plan for the same bind binds their 1D views and states the same key. On the base each -/// is the declared 2D type's neutral (`PlanDiagnostic::IncompatibleBinding`), which reads zeros. -#[test] -fn an_opencl_mode_kernel_reads_real_1d_textures_through_its_variant() { - use crate::metal::TextureType; - use crate::pipeline::interface::SlotInterface; - use crate::vk::ImageViewType; - let Some(k) = function(LINES, "__entry_lines") else { - return; - }; - let dev = device("moltenvk-m3"); - let b = Budget::standard(); - let base = dev - .compile_compute_pipeline(&descriptor(StageSource::Function(k.clone()), true), &b) - .expect("an OpenCL-mode pipeline"); - let lines: Vec<_> = (base.dependencies.iter()) - .filter_map(|d| match d.fact { - RuntimeFact::OpenClLineTexture { slot } => Some(slot), - _ => None, - }) - .collect(); - assert_eq!(lines, [texture_slot(0), texture_slot(1), texture_slot(2)]); - - // As Apple's OpenCL binds them: the base, each a 2D view. - let apple = bound( - 0..4, - &[ - (0, TextureType::Type2D), - (1, TextureType::Type2DArray), - (2, TextureType::Type2D), - ], - ); - let plan = base.plan(&dev, &apple.shape()).expect("plan"); - assert!(plan.variant.open_cl_lines.is_empty()); - assert_eq!(view_at(&plan, 0), Some(ImageViewType::TYPE_2D)); - assert_eq!(view_at(&plan, 1), Some(ImageViewType::TYPE_2D_ARRAY)); - - // Real 1D textures at the two images that read. - let real = bound( - 0..4, - &[ - (0, TextureType::Type1D), - (1, TextureType::Type1DArray), - (2, TextureType::Type2D), - ], - ); - let plan = base.plan(&dev, &real.shape()).expect("plan"); - assert_eq!( - plan.variant.open_cl_lines, - std::collections::BTreeSet::from([texture_slot(0), texture_slot(1)]) - ); - assert!(incompatible_at(&plan, 0) && incompatible_at(&plan, 1)); - assert_eq!((view_at(&plan, 0), view_at(&plan, 1)), (None, None)); - let key = plan.variant; - - let mut inputs = key.lowering_inputs(SymStage::Kernel); - inputs.open_cl_mode = true; - let compiled = dev.compile_function(&k, &inputs, &b).expect("the variant"); - let variant = dev - .compile_compute_pipeline(&descriptor(StageSource::Compiled(compiled), true), &b) - .expect("the variant's pipeline"); - let textures: Vec<_> = (variant.interface.slots.iter()) - .filter_map(|(slot, s)| match s { - SlotInterface::Texture(t) => Some((slot.index, t.texture_type)), - _ => None, - }) - .collect(); - assert_eq!( - textures, - [ - (0, TextureType::Type1D), - (1, TextureType::Type1DArray), - (2, TextureType::Type2D), - ] - ); - let plan = variant - .plan(&dev, &real.shape()) - .expect("the variant's plan"); - assert_eq!(plan.variant, key); - assert_eq!(view_at(&plan, 0), Some(ImageViewType::TYPE_1D)); - assert_eq!(view_at(&plan, 1), Some(ImageViewType::TYPE_1D_ARRAY)); - assert!(!incompatible_at(&plan, 0) && !incompatible_at(&plan, 1)); -} - -/// A 1D texture bound at a 2D texture slot of a kernel of no OpenCL mode keeps the binder's answer: -/// the declared type's neutral, said as `PlanDiagnostic::IncompatibleBinding`, and no variant. The -/// kernel states no `RuntimeFact::OpenClLineTexture`, which only an OpenCL-mode 1D image does. -#[test] -fn a_plain_2d_texture_slot_given_a_1d_texture_binds_the_neutral() { - use crate::cache::VariantKey; - use crate::metal::TextureType; - let Some(k) = function(PLAIN_2D, "plain") else { - return; - }; - let dev = device("moltenvk-m3"); - let b = Budget::standard(); - let p = dev - .compile_compute_pipeline(&descriptor(StageSource::Function(k), false), &b) - .expect("a pipeline"); - assert!(!p - .dependencies - .iter() - .any(|d| matches!(d.fact, RuntimeFact::OpenClLineTexture { .. }))); - let plan = p - .plan(&dev, &bound(0..1, &[(0, TextureType::Type1D)]).shape()) - .expect("plan"); - assert_eq!(plan.variant, VariantKey::new()); - assert_eq!(view_at(&plan, 0), None); - assert!(incompatible_at(&plan, 0)); -} - /// `__kernel void vsh(__global const float *a, __global half *o)`: `vstore_half_rtz(a[i], i, o)`, /// and `__kernel void trunc(__global const float *a, __global half *o)`: `o[i] = (half)a[i]`, for /// `i = get_global_id(0)`, in the shape the OpenCL compiler writes them. diff --git a/crates/metal2vulkan/src/tests/engine_partial_threadgroups.rs b/crates/metal2vulkan/src/tests/engine_partial_threadgroups.rs index 19543fa82..758834381 100644 --- a/crates/metal2vulkan/src/tests/engine_partial_threadgroups.rs +++ b/crates/metal2vulkan/src/tests/engine_partial_threadgroups.rs @@ -1,105 +1,59 @@ -//! A kernel's partial-threadgroups variant (`LoweringInputs::partial_threadgroups`) end to end on -//! the CPU interpreter. -//! -//! A `dispatchThreads` grid that is not a whole number of threadgroups goes through the public -//! compile API and `BindingPlan::instantiate_dispatch` twice: on the plain pipeline's plan, which -//! splits it into its interior and edge regions (on the emulated-simdgroups variant where an edge -//! is not whole subgroups, as the runtime runs it), and on the partial-threadgroups variant's, -//! which runs the threadgroups its threads fill at the call's size, per chunk of group counts, -//! flagged `lower::dispatch::NONUNIFORM`. A grid of whole threadgroups, of either dispatch form, -//! runs on the variant's plan as the same regions unflagged, every thread live, on the one -//! specialization its threadgroup size's ragged grids take. Each region runs on the interpreter -//! under Vulkan's barrier rule (`BarrierRule::Vulkan`: an invocation that returned while others -//! wait at a barrier traps), in both scheduling orders, at the subgroup width the region pins. -//! Both give Metal's -//! words: the partial threadgroup's `threads_per_threadgroup`, its threads' positions and indices -//! over its own size, its simdgroups' indices, and, behind a threadgroup barrier, a neighbour's -//! threadgroup word and its simdgroup's sum over the live lanes alone. The variant's module passes -//! `spirv-val` and holds no workgroup barrier in a block its own uniformity does not prove -//! uniform; where its simdgroups are emulated it is refused -//! (`Unsupported{PartialThreadgroups, NotImplemented}`), so the split stays. No GPU is used. +//! A kernel's partial-threadgroups variant (`LoweringInputs::partial_threadgroups`): it is +//! refused with another form of the kernel's (a flat grid, folded groups, a replay's bindings, or +//! emulated simdgroups). No GPU is used. //! //! `llvm-as` assembles the kernels; a missing tool skips visibly. -use super::engine_binder::{assemble_text, device, execute_with, words, Alloc, World}; -use crate::bind::{Dispatch, DispatchCommands}; +use std::path::Path; +use std::sync::atomic::{AtomicU64, Ordering}; + use crate::budget::Budget; -use crate::cache::VariantKey; -use crate::device::subgroup::Tier; -use crate::device::Device; -use crate::error::{BindError, Error, Feature}; +use crate::device::{Device, DeviceDescription, DevicePolicy}; +use crate::error::{Error, Feature}; use crate::library::Library; -use crate::pipeline::sym::Stage; -use crate::pipeline::testing::{compile_with, link_and_validate, typed_module_with}; +use crate::pipeline::testing::{llvm_assemble, typed_module_with, AssembleError}; use crate::pipeline::{ - ComputePipeline, ComputePipelineDescriptor, FunctionDescriptor, LoweringInputs, RuntimeFact, - StageSource, + ComputePipeline, ComputePipelineDescriptor, FunctionDescriptor, LoweringInputs, StageSource, }; -use crate::spirv::interp::{BarrierRule, Config, SubgroupSize}; use crate::spirv::ir::TypedModule; -use crate::spirv::testing::barriers::workgroup_barriers; -/// Profiles whose kernels run on 32-wide subgroups (Apple through MoltenVK, AMD, NVIDIA, Intel), -/// and one whose simdgroups are emulated (`lavapipe`). -const PROFILES: [&str; 5] = [ - "moltenvk-m3", - "amd-780m-radv", - "nvidia-rtx50-linux", - "intel-irisxe-rplp-anv", - "lavapipe", -]; +/// `text` assembled by `llvm-as`, or `None` (printed as skipped) where the tool is missing. +fn assemble_text(name: &str, text: &str) -> Option> { + static NEXT: AtomicU64 = AtomicU64::new(0); + let dir = std::env::temp_dir().join(format!( + "m2v-binder-{}-{}-{name}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + std::fs::create_dir_all(&dir).expect("scratch"); + let ll = dir.join("k.ll"); + std::fs::write(&ll, text).expect("write"); + let r = llvm_assemble(&ll); + let _ = std::fs::remove_dir_all(&dir); + match r { + Ok(b) => Some(b), + Err(AssembleError::Missing(why)) => { + eprintln!("SKIPPED: {why}"); + None + } + Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected {name}: {why}\n{text}"), + } +} -/// The poison every output word starts as. -const POISON: u8 = 0xAB; +/// The device of the committed profile `stem`, its description changed by `tweak`, under the +/// resident tables. +fn device(stem: &str, tweak: impl FnOnce(&mut DeviceDescription)) -> Device { + let 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"); + tweak(&mut desc); + Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device") +} const HEADER: &str = "target datalayout = \"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32\"\ntarget triple = \"air64_v28-apple-macosx26.0.0\"\n\n"; -/// `shape`: for the thread at `pos` of a grid `grid` wide, `out[2i] = n.x | n.y << 8 | local.x << -/// 16 | local.y << 24` and `out[2i + 1] = index | simdgroup << 16`, `i = pos.y · grid.x + pos.x`, -/// `n` its threadgroup's `threads_per_threadgroup`, `local` its position in it, `index` its -/// `thread_index_in_threadgroup` and `simdgroup` its `simdgroup_index_in_threadgroup`. -fn shape() -> String { - format!( - "{HEADER}define void @shape(ptr addrspace(1) noundef %out, <2 x i32> noundef %pos, <2 x i32> noundef %grid, <2 x i32> noundef %n, <2 x i32> noundef %local, i32 noundef %index, i32 noundef %sg) {{\n\ -entry:\n\ - %px = extractelement <2 x i32> %pos, i64 0\n\ - %py = extractelement <2 x i32> %pos, i64 1\n\ - %gx = extractelement <2 x i32> %grid, i64 0\n\ - %row = mul i32 %py, %gx\n\ - %i = add i32 %row, %px\n\ - %i2 = shl i32 %i, 1\n\ - %nx = extractelement <2 x i32> %n, i64 0\n\ - %ny = extractelement <2 x i32> %n, i64 1\n\ - %lx = extractelement <2 x i32> %local, i64 0\n\ - %ly = extractelement <2 x i32> %local, i64 1\n\ - %w1 = shl i32 %ny, 8\n\ - %w2 = shl i32 %lx, 16\n\ - %w3 = shl i32 %ly, 24\n\ - %a = or i32 %nx, %w1\n\ - %b = or i32 %a, %w2\n\ - %w = or i32 %b, %w3\n\ - %s = shl i32 %sg, 16\n\ - %v = or i32 %index, %s\n\ - %iz = zext i32 %i2 to i64\n\ - %p0 = getelementptr inbounds i32, ptr addrspace(1) %out, i64 %iz\n\ - store i32 %w, ptr addrspace(1) %p0, align 4\n\ - %p1 = getelementptr inbounds i32, ptr addrspace(1) %p0, i64 1\n\ - store i32 %v, ptr addrspace(1) %p1, align 4\n\ - ret void\n\ -}}\n\n\ -!air.kernel = !{{!0}}\n!air.version = !{{!10}}\n!air.language_version = !{{!11}}\n\ -!0 = !{{ptr @shape, !1, !2}}\n!1 = !{{}}\n!2 = !{{!3, !4, !5, !6, !7, !8, !9}}\n\ -!3 = !{{i32 0, !\"air.buffer\", !\"air.location_index\", i32 0, i32 1, !\"air.read_write\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4, !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"out\"}}\n\ -!4 = !{{i32 1, !\"air.thread_position_in_grid\", !\"air.arg_type_name\", !\"uint2\", !\"air.arg_name\", !\"pos\"}}\n\ -!5 = !{{i32 2, !\"air.threads_per_grid\", !\"air.arg_type_name\", !\"uint2\", !\"air.arg_name\", !\"grid\"}}\n\ -!6 = !{{i32 3, !\"air.threads_per_threadgroup\", !\"air.arg_type_name\", !\"uint2\", !\"air.arg_name\", !\"n\"}}\n\ -!7 = !{{i32 4, !\"air.thread_position_in_threadgroup\", !\"air.arg_type_name\", !\"uint2\", !\"air.arg_name\", !\"local\"}}\n\ -!8 = !{{i32 5, !\"air.thread_index_in_threadgroup\", !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"index\"}}\n\ -!9 = !{{i32 6, !\"air.simdgroup_index_in_threadgroup\", !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"sg\"}}\n\ -!10 = !{{i32 2, i32 8, i32 0}}\n!11 = !{{!\"Metal\", i32 4, i32 0, i32 0}}\n" - ) -} - /// `neighbour`: `a[t] = 3t + 1; threadgroup barrier; out[pos] = n << 24 | a[(t + 1) mod n] << 12 | /// simd_sum(t)`, `t` the thread's `thread_index_in_threadgroup` and `n` its threadgroup's /// `threads_per_threadgroup`; without `simd`, the sum's word is 0. @@ -149,49 +103,6 @@ attributes #0 = {{ convergent mustprogress nounwind willreturn }}\n\n\ ) } -/// The threads Metal's threadgroup at `group` of a grid of `grid` threads in threadgroups of `l` -/// runs along each axis: `l`, but the threads left in the last. -fn metal_threads(grid: [u32; 3], l: [u32; 3], group: [u32; 3]) -> [u32; 3] { - std::array::from_fn(|i| (grid[i] - group[i] * l[i]).min(l[i])) -} - -/// The words Metal's `dispatchThreads` of `grid` in threadgroups of `l` leaves for [`shape`]. -fn metal_shape(grid: [u32; 3], l: [u32; 3]) -> Vec { - let mut out = vec![0; 2 * (grid[0] * grid[1]) as usize]; - for y in 0..grid[1] { - for x in 0..grid[0] { - let group = [x / l[0], y / l[1], 0]; - let n = metal_threads(grid, l, group); - let (lx, ly) = (x % l[0], y % l[1]); - let index = ly * n[0] + lx; - let i = 2 * (y * grid[0] + x) as usize; - out[i] = n[0] | n[1] << 8 | lx << 16 | ly << 24; - out[i + 1] = index | (index / 32) << 16; - } - } - out -} - -/// The words Metal's `dispatchThreads` of `threads` threads in threadgroups of `l` leaves for -/// [`neighbour`]: its partial threadgroup's threads synchronize among themselves, and its last -/// simdgroup sums its live lanes alone. -fn metal_neighbour(threads: u32, l: u32, simd: bool) -> Vec { - (0..threads) - .map(|pos| { - let n = metal_threads([threads, 1, 1], [l, 1, 1], [pos / l, 0, 0])[0]; - let t = pos % l; - let got = ((t + 1) % n) * 3 + 1; - let first = t - t % 32; - let lanes = (n - first).min(32); - let sum = match simd { - true => (first..first + lanes).sum(), - false => 0, - }; - n << 24 | got << 12 | sum - }) - .collect() -} - /// The compute pipeline of `entry` in `bc` on `dev` under `inputs`, and the typed module the /// interpreter runs. fn pipeline( @@ -209,338 +120,6 @@ fn pipeline( Ok((pipe, m)) } -/// The interpreter's subgroup width for the commands' regions: the one they pin, else 32. -fn width(c: &DispatchCommands) -> SubgroupSize { - match c.regions.first().and_then(|r| r.required_subgroup_size) { - Some(64) => SubgroupSize::W64, - Some(16) => SubgroupSize::W16, - Some(8) => SubgroupSize::W8, - _ => SubgroupSize::W32, - } -} - -/// Run `dispatch` of `pipe` (module `m`) over an output of `words` words under Vulkan's barrier -/// rule: its commands and the words it left. -fn run_on( - dev: &Device, - (pipe, m): (&ComputePipeline, &TypedModule), - words_out: usize, - dispatch: &Dispatch, -) -> Result<(DispatchCommands, Vec), BindError> { - let mut w = World::new([(0, Alloc::new(4 * words_out, 0))]); - w.buffers.get_mut(&0).expect("out").bytes.fill(POISON); - let state = w.state(); - let plan = pipe.plan(dev, &state.shape())?; - let lanes = width(&plan.instantiate_dispatch(&state, dispatch)?); - let cfg = Config { - subgroup: lanes, - barriers: BarrierRule::Vulkan, - ..Config::default() - }; - let c = execute_with(dev, (pipe, m), &mut w, dispatch, cfg)?; - Ok((c, words(&w.buffers[&0].bytes))) -} - -/// What the split answers for `dispatch` of `entry`: the plain pipeline's regions, on the variant -/// the plan asks for where it asks for one (emulated simdgroups for an edge that is not whole -/// subgroups), as the runtime runs it. -fn split( - dev: &Device, - bc: &[u8], - entry: &str, - words_out: usize, - dispatch: &Dispatch, -) -> (DispatchCommands, Vec) { - let (pipe, m) = pipeline(dev, bc, entry, &LoweringInputs::new()).expect("the plain pipeline"); - match run_on(dev, (&pipe, &m), words_out, dispatch) { - Ok(out) => out, - Err(BindError::NeedsVariant { variant }) => { - let inputs = variant.lowering_inputs(Stage::Kernel); - let (pipe, m) = pipeline(dev, bc, entry, &inputs).expect("the split's variant"); - run_on(dev, (&pipe, &m), words_out, dispatch).expect("the split's variant runs it") - } - Err(e) => panic!("the split: {e:?}"), - } -} - -/// The partial-threadgroups variant of `entry` for threadgroups of `l` on `dev`, as the runtime -/// asks for it (`ComputePipelineState::settle_partial`): the key the plain plan names for a -/// threadgroup dispatch of `l`, with the partial threadgroups. `None` where that key emulates -/// simdgroups, which no partial variant runs. -fn partial_inputs(dev: &Device, bc: &[u8], entry: &str, l: [u32; 3]) -> Option { - let (pipe, _) = pipeline(dev, bc, entry, &LoweringInputs::new()).expect("the plain pipeline"); - let state = World::new([(0, Alloc::new(4, 0))]).state(); - let plan = pipe.plan(dev, &state.shape()).expect("plan"); - let whole = Dispatch::Threadgroups { - groups: [1, 1, 1], - threads_per_group: l, - }; - let mut key = plan - .dispatch_variant(&whole) - .expect("the threadgroup's variant"); - if key.emulated_simdgroups { - return None; - } - key.partial_threadgroups = true; - Some(key) -} - -/// A `dispatchThreads` of `threads` in threadgroups of `l`. -fn threads(threads: [u32; 3], l: [u32; 3]) -> Dispatch { - Dispatch::Threads { - threads, - threads_per_group: l, - } -} - -/// A `dispatchThreadgroups` of `groups` threadgroups of `l`. -fn groups(groups: [u32; 3], l: [u32; 3]) -> Dispatch { - Dispatch::Threadgroups { - groups, - threads_per_group: l, - } -} - -/// The grid and the threadgroup of a direct dispatch. -fn grid_of(d: &Dispatch) -> ([u32; 3], [u32; 3]) { - match *d { - Dispatch::Threads { - threads, - threads_per_group, - } => (threads, threads_per_group), - Dispatch::Threadgroups { - groups, - threads_per_group, - } => ( - std::array::from_fn(|i| groups[i] * threads_per_group[i]), - threads_per_group, - ), - _ => panic!("not a direct dispatch"), - } -} - -/// Check the partial-threadgroups variant of `entry` on `stem` against the split and `metal` for -/// every dispatch of `grids` (the dispatch, the split's regions, the variant's): both give -/// Metal's words, on the region counts given, and every region of the variant's plan of a -/// threadgroup size takes one specialization, whatever its grid. The variant's module is valid, -/// walks no workgroup barrier in non-uniform control flow and states its fact. `false` where the variant is refused or its key would emulate simdgroups (the split -/// stays). -fn check( - stem: &str, - (bc, entry): (&[u8], &str), - grids: &[(Dispatch, usize, usize)], - metal: impl Fn([u32; 3], [u32; 3]) -> Vec, - words_out: impl Fn([u32; 3]) -> usize, -) -> bool { - let dev = device(stem, |d| d.limits.max_compute_work_group_count = [4, 4, 4]); - let mut ran = false; - let mut specializations = Vec::new(); - for (d, split_regions, partial_regions) in grids { - let (threads, l) = grid_of(d); - let Some(key) = partial_inputs(&dev, bc, entry, l) else { - continue; - }; - let inputs = key.lowering_inputs(Stage::Kernel); - let (pipe, m) = match pipeline(&dev, bc, entry, &inputs) { - Ok(p) => p, - Err(Error::Unsupported(u)) if u.feature == Feature::PartialThreadgroups => { - return false; - } - Err(e) => panic!("{stem} {entry}: the partial variant: {e}"), - }; - if !ran { - let a = compile_with(bc, entry, dev.profile(), &inputs).expect("artifact"); - assert!( - a.facts.contains(&RuntimeFact::PartialThreadgroups), - "{stem} {entry}: the variant's fact" - ); - link_and_validate(&a, dev.profile()).unwrap_or_else(|e| panic!("{stem} {entry}: {e}")); - let (_, tm) = - typed_module_with(bc, entry, dev.profile(), &inputs).expect("typed module"); - let report = workgroup_barriers(&tm).expect("barriers"); - assert!( - report.nonuniform.is_empty(), - "{stem} {entry}: workgroup barriers in non-uniform blocks {:?}", - report.nonuniform - ); - ran = true; - } - let n = words_out(threads); - let want = metal(threads, l); - let (sc, split_words) = split(&dev, bc, entry, n, d); - let (pc, partial_words) = - run_on(&dev, (&pipe, &m), n, d).unwrap_or_else(|e| panic!("{stem} {entry}: {e:?}")); - let form = match d { - Dispatch::Threadgroups { .. } => "threadgroups", - _ => "threads", - }; - let tag = format!("{stem} {entry} {threads:?} in {l:?} ({form})"); - assert_eq!(&split_words[..want.len()], &want[..], "{tag}: the split"); - assert_eq!(&partial_words[..want.len()], &want[..], "{tag}: partial"); - assert_eq!( - sc.regions.len(), - *split_regions, - "{tag}: the split's regions" - ); - assert_eq!(pc.regions.len(), *partial_regions, "{tag}: partial regions"); - // Every partial region runs the call's threadgroup size: one specialization, a whole - // grid's the ragged ones'. - let first = &pc.regions[0].specialization; - assert!( - (pc.regions.iter()).all(|r| r.specialization == *first), - "{tag}: one specialization" - ); - match specializations.iter().find(|(size, _)| *size == l) { - Some((_, kept)) => assert!(kept == first, "{tag}: its threadgroup size's"), - None => specializations.push((l, first.clone())), - } - } - ran -} - -/// A ragged grid of a kernel that reads its threadgroup's size, its position and index in it, -/// and its simdgroup's index runs on the partial-threadgroups variant as the split runs its edges, -/// as Metal answers: in one region of the call's threadgroup size per chunk of group counts (the -/// device's limit lowered to 4 a dispatch), where the split runs the interior and an edge per -/// axis and corner. -#[test] -fn a_ragged_grid_runs_partial_threadgroups_as_the_split_runs_its_edges() { - let Some(bc) = assemble_text("shape", &shape()) else { - return; - }; - // (dispatch, the split's regions, the variant's). - let grids = [ - // 3 by 2 threadgroups of 8x8, the last column 5 wide and the last row 5 high. - (threads([21, 13, 1], [8, 8, 1]), 4, 1), - // A grid narrower and shorter than one threadgroup: the split's corner alone. - (threads([5, 3, 1], [8, 4, 1]), 1, 1), - // 10 threadgroups of 32 in chunks of at most 4, the last of 2 threads: the split's 9 - // whole ones in 3 chunks and its edge. - (threads([290, 1, 1], [32, 1, 1]), 4, 3), - // One row of 100 in threadgroups of 64. - (threads([100, 1, 1], [64, 1, 1]), 2, 1), - ]; - let mut ran = Vec::new(); - for stem in PROFILES { - let emulated = tier_of(stem, &bc, "shape") == Tier::Emulated; - let partial = check(stem, (&bc, "shape"), &grids, metal_shape, |t: [u32; 3]| { - 2 * (t[0] * t[1]) as usize - }); - assert_eq!(partial, !emulated, "{stem}: runs partial threadgroups"); - if partial { - ran.push(stem); - } - } - println!("PARTIAL-THREADGROUPS shape: the variant ran on {ran:?}"); - assert!( - ran.len() >= 4, - "the subgroup profiles run the variant: {ran:?}" - ); -} - -/// A ragged grid of a kernel that reads a neighbour's threadgroup word behind a threadgroup -/// barrier, and sums its simdgroup's thread indices, runs on the partial-threadgroups variant as -/// the split runs its edge: the partial threadgroup's threads synchronize among themselves and -/// its last simdgroup sums its live lanes alone. Where the kernel's simdgroups are emulated -/// (`lavapipe`), the variant is refused and the split stays; without the sum it runs there too. -#[test] -fn a_barrier_and_a_simdgroup_sum_run_partial_threadgroups_as_metal() { - let (Some(sum), Some(plain)) = ( - assemble_text("neighbour_sum", &neighbour(true)), - assemble_text("neighbour", &neighbour(false)), - ) else { - return; - }; - // (dispatch, the split's regions, the variant's). - let grids = [ - (threads([100, 1, 1], [64, 1, 1]), 2, 1), - (threads([45, 1, 1], [32, 1, 1]), 2, 1), - (threads([16, 1, 1], [64, 1, 1]), 1, 1), - ]; - for (bc, simd) in [(&sum, true), (&plain, false)] { - let metal = |t: [u32; 3], l: [u32; 3]| metal_neighbour(t[0], l[0], simd); - let mut ran = Vec::new(); - for stem in PROFILES { - let emulated = tier_of(stem, bc, "neighbour") == Tier::Emulated; - let partial = check(stem, (bc, "neighbour"), &grids, metal, |t| t[0] as usize); - assert_eq!( - partial, !emulated, - "{stem} simd {simd}: runs partial threadgroups" - ); - if partial { - ran.push(stem); - } - } - println!("PARTIAL-THREADGROUPS neighbour simd {simd}: the variant ran on {ran:?}"); - } -} - -/// A grid of whole threadgroups, of a `dispatchThreads` or a `dispatchThreadgroups`, runs on the -/// partial-threadgroups variant's plan as its ragged grids do, every thread live: as the same -/// regions unflagged, on the one specialization a ragged grid of its threadgroup size takes, with -/// the plain pipeline's words and Metal's. -#[test] -fn whole_grids_run_on_the_partial_plan_with_every_thread_live() { - let (Some(shape_bc), Some(neighbour_bc)) = ( - assemble_text("shape_whole", &shape()), - assemble_text("neighbour_whole", &neighbour(true)), - ) else { - return; - }; - // (dispatch, the split's regions, the variant's): a ragged grid, then whole ones of its - // threadgroup size; 10 threadgroups of 32 in chunks of at most 4. - let shapes = [ - (threads([21, 13, 1], [8, 8, 1]), 4, 1), - (threads([24, 16, 1], [8, 8, 1]), 1, 1), - (groups([3, 2, 1], [8, 8, 1]), 1, 1), - (threads([290, 1, 1], [32, 1, 1]), 4, 3), - (threads([320, 1, 1], [32, 1, 1]), 3, 3), - (groups([10, 1, 1], [32, 1, 1]), 3, 3), - ]; - let neighbours = [ - (threads([100, 1, 1], [64, 1, 1]), 2, 1), - (threads([128, 1, 1], [64, 1, 1]), 1, 1), - (groups([2, 1, 1], [64, 1, 1]), 1, 1), - ]; - let metal = |t: [u32; 3], l: [u32; 3]| metal_neighbour(t[0], l[0], true); - let mut ran = Vec::new(); - for stem in PROFILES { - let words = |t: [u32; 3]| 2 * (t[0] * t[1]) as usize; - let shape = check(stem, (&shape_bc, "shape"), &shapes, metal_shape, words); - let runs = tier_of(stem, &shape_bc, "shape") != Tier::Emulated; - assert_eq!(shape, runs, "{stem}: shape runs partial threadgroups"); - let words = |t: [u32; 3]| t[0] as usize; - let neighbour = check( - stem, - (&neighbour_bc, "neighbour"), - &neighbours, - metal, - words, - ); - let runs = tier_of(stem, &neighbour_bc, "neighbour") != Tier::Emulated; - assert_eq!( - neighbour, runs, - "{stem}: neighbour runs partial threadgroups" - ); - if shape && neighbour { - ran.push(stem); - } - } - println!("PARTIAL-THREADGROUPS whole grids: the variant ran on {ran:?}"); - assert!( - ran.len() >= 4, - "the subgroup profiles run the variant: {ran:?}" - ); -} - -/// The simd tier `stem` compiles `bc`'s `entry` in. -fn tier_of(stem: &str, bc: &[u8], entry: &str) -> Tier { - let dev = device(stem, |_| {}); - let (plan, _) = - typed_module_with(bc, entry, dev.profile(), &LoweringInputs::new()).expect("plan"); - plan.simd.1 -} - /// The variant is refused with another form of the kernel's: a flat grid, folded groups, a /// replay's bindings, or emulated simdgroups. #[test] diff --git a/crates/metal2vulkan/src/tests/engine_pointer_memory.rs b/crates/metal2vulkan/src/tests/engine_pointer_memory.rs index 18de970a0..845b610da 100644 --- a/crates/metal2vulkan/src/tests/engine_pointer_memory.rs +++ b/crates/metal2vulkan/src/tests/engine_pointer_memory.rs @@ -23,7 +23,7 @@ use std::collections::BTreeMap; use std::path::Path; use std::sync::atomic::{AtomicU64, Ordering}; -use crate::bind::status::{ExecutionStatus, StatusWord}; +use crate::bind::status::StatusWord; use crate::budget::SPIRV_WORDS; use crate::device::profile::DeviceProfile; use crate::device::requirements::VkFeature; @@ -42,6 +42,10 @@ use crate::pipeline::testing::{ use crate::spirv::interp::{run, Buffer, Config, Order, Resources, TrapKind}; use crate::spirv::ir::{AtomicOp, Inst, StorageClass, Type, TypedModule}; +/// The `ExecutionStatus` buffer's bytes, every word 0 at the start: through its last word. +const STATUS_BYTES: usize = + crate::bind::status::StatusWord::SeqCstFences.byte_offset() as usize + 4; + const HEADER: &str = "target datalayout = \"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32\"\ntarget triple = \"air64_v28-apple-macosx26.0.0\"\n\n"; /// Device addresses of the interpreter's address-backed buffers. @@ -332,7 +336,7 @@ fn resources_bound(plan: &Plan, mem: &Memory, threads: u32, binds: &[Bind]) -> ( buffers.push(Buffer { slot: None, address: Some(STATUS), - bytes: ExecutionStatus::initial().to_vec(), + bytes: vec![0; STATUS_BYTES], }); ( Resources { diff --git a/crates/metal2vulkan/src/tests/engine_pointer_values.rs b/crates/metal2vulkan/src/tests/engine_pointer_values.rs index cafde8d20..42b67e8b0 100644 --- a/crates/metal2vulkan/src/tests/engine_pointer_values.rs +++ b/crates/metal2vulkan/src/tests/engine_pointer_values.rs @@ -18,7 +18,6 @@ use std::collections::BTreeMap; use std::path::Path; use std::sync::atomic::{AtomicU64, Ordering}; -use crate::bind::status::ExecutionStatus; use crate::budget::SPIRV_WORDS; use crate::device::profile::{BufferAccess, DeviceProfile}; use crate::device::{Device, DeviceDescription, DevicePolicy}; @@ -244,7 +243,7 @@ fn resources( buffers.push(Buffer { slot: None, address: Some(STATUS), - bytes: ExecutionStatus::initial().to_vec(), + bytes: vec![0; crate::bind::status::StatusWord::SeqCstFences.byte_offset() as usize + 4], }); if let Some(b) = &plan.families.access.blob { let mut bytes = b.bytes.to_vec(); diff --git a/crates/metal2vulkan/src/tests/engine_primitive_ids.rs b/crates/metal2vulkan/src/tests/engine_primitive_ids.rs index 5c9b57c7e..2a8e7916a 100644 --- a/crates/metal2vulkan/src/tests/engine_primitive_ids.rs +++ b/crates/metal2vulkan/src/tests/engine_primitive_ids.rs @@ -338,202 +338,6 @@ fn the_fragment_reads_the_id_flat() { // ---- Indexed draws: the de-indexed form (VariantKey::primitive_id_indices) ------------------- -/// A state binding `pi_place`'s and `pi_counts`' buffers, at device addresses. -fn bound() -> crate::bind::BindState { - use crate::bind::{BindState, BoundBuffer, StageTable}; - let buffer = |length| BoundBuffer::Buffer { - length, - offset: 0, - gpu_address: 0x1_0000, - device_address: Some(0x7_0000_0000), - attribute_stride: None, - }; - let mut v = StageTable::default(); - for (index, length) in [(0, 1024), (1, 256), (2, 256)] { - v.buffers.insert(index, buffer(length)); - } - let mut s = BindState::default(); - s.stages.insert(crate::pipeline::sym::Stage::Vertex, v); - s -} - -/// The `u16` indexed draw of 12 indices from index 2, base vertex 10, two instances from 1. -fn indexed() -> crate::bind::DrawCall { - crate::bind::DrawCall::Indexed { - index_type: vk::IndexType::UINT16, - index_buffer: crate::bind::IndexBufferRef::new(1, 64), - index_count: 12, - index_offset: 4, - instance_count: 2, - base_vertex: 10, - base_instance: 1, - } -} - -/// The words of `field`'s place in `commands`' vertex push bytes, under `plan`. -fn pushed( - plan: &crate::bind::BindingPlan, - commands: &crate::bind::DrawCommands, - field: PushField, - words: usize, -) -> Vec { - let place = plan - .push - .fields - .iter() - .find(|f| f.stage == crate::pipeline::sym::Stage::Vertex && f.field == field) - .expect("placed"); - let crate::bind::FieldLocation::PushWindow { offset } = place.location else { - panic!("{field:?} spilled: {place:?}"); - }; - let write = commands - .push_constants - .iter() - .find(|w| w.stages.contains(vk::ShaderStageFlags::VERTEX)) - .expect("vertex push"); - let at = (offset - write.offset) as usize; - write.bytes[at..at + 4 * words] - .chunks(4) - .map(|w| u32::from_le_bytes(w.try_into().expect("a word"))) - .collect() -} - -/// An indexed draw of a pipeline whose vertex function writes the ID asks for the de-indexed -/// variant of its index type through the shape (`BindState::primitive_id_indices`). That variant -/// reads its indices at `PushField::CaptureIndexAddress`, writes the ID as `VertexIndex / n` (no -/// base vertex), and draws the indices as `index count` vertices from 0 with layout -/// `[0, index count, base instance, base vertex]`. Every module is valid. A draw without indices -/// asks for the variant without the form; an indexed strip is not implemented. -#[test] -fn an_indexed_draw_runs_the_de_indexed_variant() { - use crate::bind::{DrawCall, PushHole}; - use crate::error::BindError; - use crate::error::{Feature, Unsupported}; - use crate::metal::{IndexType, PrimitiveType}; - let Some(bc) = fixture() else { return }; - let dev = withheld(8); - let d = pipeline(&bc, "pi_place", Some("pi_ids"), 1); - let base = compile(&dev, &d).expect("base"); - let mut state = bound(); - state.primitive_type = Some(PrimitiveType::Triangle); - state.primitive_id_indices = Some(IndexType::UInt16); - let plan = base.plan(&dev, &state.shape()).expect("base plan"); - assert_eq!(plan.variant.primitive_id_indices, Some(IndexType::UInt16)); - let key = plan.variant.clone(); - let p = dev - .compile_render_variant(&d, &key, &Budget::standard()) - .expect("de-indexed variant"); - validate(&p, &dev); - assert!(reads_layout(&p)); - assert!(reads_field(&p, PushField::CaptureIndexAddress)); - assert!(reads_field(&p, PushField::CaptureLayout)); - assert!(!reads_field(&p, PushField::BaseVertexInstance)); - let plan = p.plan(&dev, &state.shape()).expect("plan"); - assert_eq!(plan.variant, key); - let commands = plan.instantiate_draw(&state, &indexed()).expect("draw"); - assert_eq!( - commands.draw, - vk::DrawCommand::Draw { - vertex_count: 12, - instance_count: 2, - first_vertex: 0, - first_instance: 1, - } - ); - assert!(commands - .push_holes - .iter() - .any(|h| matches!(h, PushHole::CaptureIndexAddress { .. }))); - assert_eq!( - pushed(&plan, &commands, PushField::CaptureLayout, 4), - [0, 12, 1, 10] - ); - assert_eq!( - pushed(&plan, &commands, PushField::VerticesPerPrimitive, 1), - [3] - ); - let not_implemented = Err(BindError::Unsupported(Unsupported::not_implemented( - Feature::PrimitiveId, - ))); - let mut strip = state.clone(); - strip.primitive_type = Some(PrimitiveType::TriangleStrip); - assert_eq!( - plan.instantiate_draw(&strip, &indexed()).map(|_| ()), - not_implemented - ); - let unindexed = DrawCall::Primitives { - vertex_start: 0, - vertex_count: 3, - instance_count: 1, - base_instance: 0, - }; - assert_eq!( - plan.instantiate_draw(&state, &unindexed).map(|_| ()), - Err(BindError::NeedsVariant { - variant: Box::new(VariantKey { - primitive_id_indices: None, - ..key.clone() - }), - }) - ); - // Without the shape's index type, the base plan refuses the indexed draw. - let mut plain = state.clone(); - plain.primitive_id_indices = None; - let plan = base.plan(&dev, &plain.shape()).expect("plan"); - assert!(plan.variant.is_empty()); - assert_eq!( - plan.instantiate_draw(&plain, &indexed()).map(|_| ()), - not_implemented - ); - // A pipeline that writes no ID asks for no such variant. - let none = compile(&dev, &pipeline(&bc, "pi_place", None, 0)).expect("no fragment"); - let plan = none.plan(&dev, &state.shape()).expect("plan"); - assert_eq!(plan.variant.primitive_id_indices, None); -} - -/// A vertex function with a `[[stage_in]]` attribute (`pi_attrib`'s `float2` at stride 8) reaches -/// link in the de-indexed and private list forms (`pipeline::link::vertex`'s item 8): the variant -/// the base plan asks for links, its vertex input binds no layout and pulls the attribute, its -/// plan states the same variant, and every module is valid. Its base pulls the attribute too, as -/// every attribute is outside the identity domains, which refuse the fixture's primitive-ID -/// fragment. -#[test] -fn a_stage_in_attribute_links_pulled_in_the_de_indexed_and_list_forms() { - use crate::metal::{IndexType, PrimitiveType}; - let Some(bc) = fixture() else { return }; - let mut d = pipeline(&bc, "pi_attrib", Some("pi_ids"), 1); - d.vertex_descriptor = Some(attribute_descriptor()); - for (dev, form) in [ - (withheld(8), "de-indexed"), - (withheld(8), "listed"), - (device("lavapipe"), "listed"), - ] { - let base = compile(&dev, &d).expect("base"); - assert!(base.vertex_input.bindings.is_empty(), "{form}: the base"); - assert_eq!(base.vertex_input.pulled.len(), 1, "{form}: the base"); - let mut state = bound(); - state.primitive_type = Some(PrimitiveType::Triangle); - match form { - "de-indexed" => state.primitive_id_indices = Some(IndexType::UInt16), - _ => state.private_list = true, - } - let plan = base.plan(&dev, &state.shape()).expect("base plan"); - let key = plan.variant.clone(); - assert!( - key.primitive_id_indices.is_some() || key.private_list, - "{form}: {key:?}" - ); - let p = dev - .compile_render_variant(&d, &key, &Budget::standard()) - .unwrap_or_else(|e| panic!("{form}: the variant: {e}")); - validate(&p, &dev); - assert!(p.vertex_input.bindings.is_empty(), "{form}"); - assert_eq!(p.vertex_input.pulled.len(), 1, "{form}"); - let plan = p.plan(&dev, &state.shape()).expect("variant plan"); - assert_eq!(plan.variant, key, "{form}"); - } -} - /// A vertex function that writes device memory (`pi_counts`' atomic counter) would run once per /// index in the de-indexed form: that variant is `NotImplemented(PrimitiveId)`, and its draws /// without indices still run. @@ -554,75 +358,3 @@ fn a_memory_writing_vertex_function_is_refused_de_indexed() { other => panic!("{:?}", other.map(|_| ())), } } - -/// A private type's draw in the private list form (`BindState::private_list`) asks for the listed -/// variant through the shape. It reads its list's address (`PushField::CaptureIndexAddress`, a -/// push hole the consumer fills) and no capture layout, and draws the list's positions without -/// indices from the call's first vertex, the list's first index, with its instances; its vertices -/// per primitive are the list's, twice that for Metal's quads listed as two triangles a quad. A -/// vertex function that writes memory, which the de-indexed form refuses, runs in it, on a device -/// with both features too, where nothing reads the primitive ID's varying. Every module is valid. -#[test] -fn a_private_draw_in_the_list_form_runs_the_listed_variant() { - use crate::bind::{DrawCall, PushHole}; - use crate::metal::PrimitiveType; - use crate::pipeline::RuntimeFact; - let Some(bc) = fixture() else { return }; - let listed = |dev: &Device, vertex: &str| { - let d = pipeline(&bc, vertex, Some("pi_ids"), 1); - let base = compile(dev, &d).expect("base"); - let mut state = bound(); - state.primitive_type = Some(PrimitiveType::Triangle); - state.private_list = true; - let plan = base.plan(dev, &state.shape()).expect("base plan"); - assert!(plan.variant.private_list, "{vertex}: the plan's variant"); - let key = plan.variant.clone(); - let p = dev - .compile_render_variant(&d, &key, &Budget::standard()) - .unwrap_or_else(|e| panic!("{vertex}: the listed variant: {e}")); - validate(&p, dev); - assert!(p - .dependencies - .iter() - .any(|d| d.fact == RuntimeFact::PrivateList)); - assert!(reads_field(&p, PushField::CaptureIndexAddress), "{vertex}"); - assert!(!reads_field(&p, PushField::CaptureLayout), "{vertex}"); - let plan = p.plan(dev, &state.shape()).expect("plan"); - assert_eq!(plan.variant, key); - let draw = DrawCall::Primitives { - vertex_start: 1, - vertex_count: 12, - instance_count: 2, - base_instance: 1, - }; - let commands = plan.instantiate_draw(&state, &draw).expect("draw"); - assert_eq!( - commands.draw, - vk::DrawCommand::Draw { - vertex_count: 12, - instance_count: 2, - first_vertex: 1, - first_instance: 1, - } - ); - assert!(commands - .push_holes - .iter() - .any(|h| matches!(h, PushHole::CaptureIndexAddress { .. }))); - (plan, state, draw) - }; - let (plan, mut state, draw) = listed(&withheld(8), "pi_place"); - let commands = plan.instantiate_draw(&state, &draw).expect("draw"); - assert_eq!( - pushed(&plan, &commands, PushField::VerticesPerPrimitive, 1), - [3] - ); - state.quad_primitive_ids = true; - let commands = plan.instantiate_draw(&state, &draw).expect("quads"); - assert_eq!( - pushed(&plan, &commands, PushField::VerticesPerPrimitive, 1), - [6] - ); - listed(&withheld(8), "pi_counts"); - listed(&device("lavapipe"), "pi_counts"); -} diff --git a/crates/metal2vulkan/src/tests/engine_pull_model.rs b/crates/metal2vulkan/src/tests/engine_pull_model.rs index e618bd6ef..27bc4471b 100644 --- a/crates/metal2vulkan/src/tests/engine_pull_model.rs +++ b/crates/metal2vulkan/src/tests/engine_pull_model.rs @@ -25,84 +25,17 @@ //! Every pipeline that compiles passes L3 (`spirv-val` and requirements within the profile) for each //! stage module. `llvm-as` assembles the fixture; a missing tool skips visibly. No GPU is used. -use super::engine_multisample::{ - description, ext_insts, fragment_words, library, pixel_form, planned, stems, validate, -}; -use crate::bind::BindState; +use super::engine_multisample::{description, library, stems}; use crate::budget::Budget; -use crate::device::requirements::{VkExtension, VkFeature, VkProperty}; -use crate::device::{Device, DeviceDescription, DevicePolicy}; +use crate::device::{Device, DevicePolicy}; use crate::error::{Error, Feature, Needs}; use crate::metal::PixelFormat; -use crate::pipeline::artifact::PrecisionNote; use crate::pipeline::descriptor::{ ColorAttachmentDescriptor, FunctionDescriptor, RenderPipelineDescriptor, StageSource, }; -use crate::pipeline::sym::SpecKey; -use crate::pipeline::RenderPipeline; -use crate::vk::ShaderStage; - -/// `runtime-floor` without `sampleRateShading` (below the runtime's floor). -const NO_SAMPLE_RATE: &str = "runtime-floor without sampleRateShading"; const VERTEX: &str = "pm_place"; -/// The fragment function that reads its no-perspective interpolant alone, at a sample and an -/// offset. -const LINEAR: &str = "pm_linear"; - -/// `GLSL.std.450` instruction numbers. -const INTERPOLATE_AT_CENTROID: u32 = 76; -const INTERPOLATE_AT_SAMPLE: u32 = 77; -const INTERPOLATE_AT_OFFSET: u32 = 78; -const N_CLAMP: u32 = 81; - -/// The bits of 7/16, where an interpolation offset range may end. -const SEVEN_SIXTEENTHS: u32 = 0x3EE0_0000; - -/// Where a fragment function reads its interpolants. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum At { - Center, - Centroid, - Sample, - Offset, -} - -/// Each fragment function of the fixture that compiles somewhere, its color attachments' format -/// and count, and where it reads. -const FRAGMENTS: [(&str, PixelFormat, usize, &[At]); 9] = [ - ( - LINEAR, - PixelFormat::RGBA32Float, - 2, - &[At::Sample, At::Offset], - ), - ("pm_center", PixelFormat::RGBA32Float, 2, &[At::Center]), - ("pm_centroid", PixelFormat::RGBA32Float, 2, &[At::Centroid]), - ("pm_sample", PixelFormat::RGBA32Float, 2, &[At::Sample]), - ("pm_sample_id", PixelFormat::RGBA32Float, 2, &[At::Sample]), - ("pm_offset", PixelFormat::RGBA32Float, 2, &[At::Offset]), - ( - "pm_offset_sweep", - PixelFormat::RGBA32Float, - 2, - &[At::Offset], - ), - ( - "pm_narrow", - PixelFormat::RGBA32Float, - 4, - &[At::Center, At::Centroid, At::Sample, At::Offset], - ), - ( - "pm_half", - PixelFormat::RGBA16Float, - 4, - &[At::Center, At::Centroid, At::Sample, At::Offset], - ), -]; - /// The pipeline of `pm_place` and `fragment` into `count` attachments of `format` at `samples`. fn render( lib: &crate::library::Library, @@ -124,165 +57,6 @@ fn render( d } -/// Whether `dev` has the interpolation functions: `sampleRateShading`, and on a -/// portability-subset device `shaderSampleRateInterpolationFunctions`. -fn interpolation_functions(dev: &Device) -> bool { - let fields = dev.profile().fields(); - let withheld = fields - .enabled - .extensions - .contains(&VkExtension::KhrPortabilitySubset) - && !fields - .enabled - .features - .contains(&VkFeature::ShaderSampleRateInterpolationFunctions); - fields.fragment.sample_rate_shading && !withheld -} - -/// Whether `words` hold an `OpConstant` whose value is `bits`. -fn holds_constant(words: &[u32], bits: u32) -> bool { - let mut i = 5; - while let Some(&w) = words.get(i) { - let (len, op) = ((w >> 16) as usize, w & 0xFFFF); - if op == 43 && len == 4 && words.get(i + 3) == Some(&bits) { - return true; - } - if len == 0 { - break; - } - i += len; - } - false -} - -/// Whether the fragment module of `p` records `note`. -fn noted(p: &RenderPipeline, note: PrecisionNote) -> bool { - p.stages - .iter() - .filter(|m| m.stage == ShaderStage::FRAGMENT) - .any(|m| m.precision_notes.contains(¬e)) -} - -/// Every fragment function at one and four samples on every committed profile compiles where the -/// device has what its reads need, with the instructions, mask, origin, clamp, note and -/// requirements the module docs state, and passes L3; elsewhere it is refused for its reason. -#[test] -fn interpolants_read_where_their_functions_say_or_are_refused() { - let Some(lib) = library("pull_model_interpolants") else { - return; - }; - let mut compiled = 0usize; - let mut refused = Vec::new(); - // Every committed profile has `sampleRateShading`; a device without it is below the runtime's - // floor. - let mut descriptions: Vec<(String, DeviceDescription)> = stems() - .into_iter() - .map(|s| (s.clone(), description(&s))) - .collect(); - let mut without = description("runtime-floor"); - without.features.remove(&VkFeature::SampleRateShading); - descriptions.push((NO_SAMPLE_RATE.into(), without)); - for (stem, desc) in descriptions { - let dev = Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device"); - let functions = interpolation_functions(&dev); - let fields = dev.profile().fields(); - let origin = VkProperty::InterpolateAtOffsetCentered; - assert!(fields.enabled.properties.contains(&origin), "{stem}"); - let ends_at_seven = fields.limits.max_interpolation_offset_bits == SEVEN_SIXTEENTHS; - for (fragment, format, count, reads) in FRAGMENTS { - let reads_at = |at| reads.contains(&at); - let beyond_center = reads.iter().any(|&at| at != At::Center); - for samples in [1, 4] { - let what = format!("{stem} {fragment} at {samples}"); - let d = render(&lib, fragment, (format, count), samples); - let result = dev.compile_render_pipeline(&d, &Budget::standard()); - if beyond_center && !functions { - let e = result.expect_err(&what); - assert!( - matches!(&e, Error::Unsupported(u) - if u.feature == Feature::PullModelInterpolation), - "{what}: {e:?}" - ); - refused.push(what); - continue; - } - let p = match result { - // A sample count the profile's attachments do not take. - Err(Error::Unsupported(u)) if u.feature == Feature::RasterSampleCount => { - assert!(samples > 1, "{what}: {u:?}"); - continue; - } - p => p.unwrap_or_else(|e| panic!("{what}: {e}")), - }; - validate(&p, &dev, &what); - let words = fragment_words(&p); - let ext = ext_insts(words); - let pixel_center = reads_at(At::Center) && samples > 1 && pixel_form(&dev); - assert_eq!( - ext.contains(&INTERPOLATE_AT_CENTROID), - reads_at(At::Centroid), - "{what}: InterpolateAtCentroid" - ); - assert_eq!( - ext.contains(&INTERPOLATE_AT_SAMPLE), - reads_at(At::Sample), - "{what}: InterpolateAtSample" - ); - assert_eq!( - ext.contains(&INTERPOLATE_AT_OFFSET), - reads_at(At::Offset) || pixel_center, - "{what}: InterpolateAtOffset" - ); - assert_eq!( - ext.contains(&N_CLAMP), - reads_at(At::Offset), - "{what}: the offset's clamp" - ); - assert_eq!( - noted(&p, PrecisionNote::DeviceInterpolationOffset), - reads_at(At::Offset), - "{what}: the offset note" - ); - // Every function but `pm_linear` reads its perspective interpolant where it reads. - let perspective = fragment != LINEAR; - assert_eq!( - noted(&p, PrecisionNote::ExtrapolatedInterpolation), - perspective && (reads_at(At::Sample) || reads_at(At::Offset)), - "{what}: the extrapolation note" - ); - assert_eq!( - p.requirements.properties.contains(&origin), - reads_at(At::Offset) || pixel_center, - "{what}: {origin:?}" - ); - // 7/16 is no device's origin; a range may end there, and then the clamp holds it. - let seven = holds_constant(words, SEVEN_SIXTEENTHS); - assert!(!seven || ends_at_seven, "{what}: the 7/16 origin"); - if reads_at(At::Sample) && fragment != "pm_sample_id" { - let plan = p.plan(&dev, &BindState::default().shape()).expect("plan"); - assert_eq!( - planned(&p, &plan, SpecKey::SampleCount), - samples, - "{what}: the sample mask's count" - ); - } - compiled += 1; - } - } - } - eprintln!( - "{compiled} pipelines compiled, {} refused: {refused:?}", - refused.len() - ); - assert!(compiled > 100, "{compiled}"); - assert!( - refused - .iter() - .any(|r| r.starts_with(&format!("{NO_SAMPLE_RATE} "))), - "a profile without sampleRateShading refuses: {refused:?}" - ); -} - /// An interpolant chosen at run time, a `select` of two interpolant handles (`pm_selected`), is /// not lowered on any profile: `NotImplemented(PullModelInterpolation)`. #[test] diff --git a/crates/metal2vulkan/src/tests/engine_ray_tracing.rs b/crates/metal2vulkan/src/tests/engine_ray_tracing.rs index f6fa14896..049c6f1b4 100644 --- a/crates/metal2vulkan/src/tests/engine_ray_tracing.rs +++ b/crates/metal2vulkan/src/tests/engine_ray_tracing.rs @@ -16,31 +16,23 @@ //! interpreter runs it over the binder's instantiated push bytes. use crate::air::error::IntrinsicError; -use crate::bind::{ - BindState, BoundAccelerationStructure, BoundBuffer, Dispatch, StageTable, WriteSource, -}; use crate::budget::{Budget, Meter, LEDGER_BYTES, SPIRV_WORDS}; use crate::device::requirements::VkFeature; -use crate::device::{Device, DeviceDescription, DevicePolicy, DeviceProfile}; +use crate::device::{DevicePolicy, DeviceProfile}; use crate::error::{ Capability, DiagName, Error, Feature, InputErrorKind, Limit, Location, LowerFamily, Needs, Unsupported, }; -use crate::library::{FunctionConstantValues, Library}; +use crate::library::FunctionConstantValues; use crate::lower::select::LowerInputs; use crate::pipeline::compile::{compile_bitcode, compile_bitcode_linked, EntryRef, LinkedSource}; use crate::pipeline::facts::RuntimeFact; use crate::pipeline::interface::{AccessSet, BufferForm, SlotInterface, Window}; -use crate::pipeline::sym::{ - AccelerationStructureLevel, Axis, PushField, ResourceKind, ResourceSlot, SlotClass, SlotRef, - SpecKey, Stage, -}; +use crate::pipeline::sym::{PushField, SlotClass, SlotRef, Stage}; use crate::pipeline::testing::{ - compile, engine_dir, link_and_validate, llvm_assemble, meter, specialized_entry, AssembleError, - Scratch, + compile, link_and_validate, llvm_assemble, meter, specialized_entry, AssembleError, Scratch, }; -use crate::pipeline::{ComputePipelineDescriptor, FunctionDescriptor, PrecisionNote, StageSource}; -use crate::spirv::interp::{run, Buffer, Config, Resources}; +use crate::pipeline::PrecisionNote; use crate::spirv::testing::{committed_profiles, is_moltenvk_capture, spirv_dis}; const HEADER: &str = "target datalayout = \"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32\"\ntarget triple = \"air64_v28-apple-macosx26.0.0\"\n\n"; @@ -424,58 +416,6 @@ fn an_intersection_function_table_is_read_per_candidate() { } } -/// The binder plans a structure argument as the consumer's top-level structure of the Metal -/// structure bound at its slot, at the argument's level, and the table argument as the buffer -/// bound at its slot: the consumer builds the structures. -#[test] -fn the_binder_writes_the_structure_and_the_table_the_consumer_binds() { - let Some(bc) = assemble("plan", &table_kernel("")) else { - return; - }; - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../metal2vulkan-validation/profiles"); - let text = std::fs::read_to_string(path.join("lavapipe.json")).expect("profile"); - let desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); - let dev = Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device"); - let lib = Library::from_air(&bc).expect("library"); - let f = lib.function("k").expect("entry"); - let d = ComputePipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new(f))); - let pipe = dev - .compile_compute_pipeline(&d, &Budget::standard()) - .expect("compiled"); - let slot = |index| SlotRef { - stage: Stage::Kernel, - class: SlotClass::Buffer, - index, - }; - let mut table = StageTable::default(); - for index in [0, 2] { - table.buffers.insert( - index, - BoundBuffer::Buffer { - length: 16, - offset: 0, - gpu_address: 0, - device_address: None, - attribute_stride: None, - }, - ); - } - let mut state = BindState::default(); - state.stages.insert(Stage::Kernel, table); - let plan = pipe.plan(&dev, &state.shape()).expect("planned"); - let sources: Vec<&WriteSource> = plan.descriptors.iter().map(|w| &w.source).collect(); - for expected in [ - WriteSource::AccelerationStructure { - slot: slot(1), - level: AccelerationStructureLevel::Primitive, - }, - WriteSource::Buffer { slot: slot(2) }, - ] { - assert!(sources.contains(&&expected), "{expected:?}: {sources:?}"); - } -} - /// An intersection function table argument read other than as an intersector's table (here /// compared with null) is refused as an intersection function table at that reader. #[test] @@ -2040,144 +1980,6 @@ fn a_structures_other_queries_stay_refused() { } } -/// The owned fixture's bitcode (`validation/fixtures/public/engine/.ll`). -fn fixture(stem: &str) -> Option> { - match llvm_assemble(&engine_dir().join(format!("{stem}.ll"))) { - Ok(b) => Some(b), - Err(AssembleError::Missing(why)) => { - eprintln!("SKIPPED: {why}"); - None - } - Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected {stem}.ll: {why}"), - } -} - -/// The profiles the count kernels run on: two without ray queries, MoltenVK's, and one with them. -const COUNT_PROFILES: [&str; 3] = ["runtime-floor", "moltenvk-m3", "lavapipe"]; - -/// `entry` of `bc` end to end on `stem`: compiled through the device, planned for a stage table -/// that binds a 16-byte buffer at index 0 and each of `counts` (buffer index, instance count) as -/// an acceleration structure, instantiated for one group of `threads` threads, and run on the -/// interpreter over the instantiated push bytes, with buffer 0 starting as `initial`. Returns -/// buffer 0's final bytes. The plan writes no acceleration-structure descriptor. -fn run_counts( - bc: &[u8], - entry: &str, - stem: &str, - counts: &[(u32, u32)], - threads: u32, - initial: [u8; 16], -) -> Vec { - let what = format!("{entry} on {stem} with {counts:?}"); - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../metal2vulkan-validation/profiles"); - let text = std::fs::read_to_string(path.join(format!("{stem}.json"))).expect("profile"); - let desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); - let dev = Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device"); - let lib = Library::from_air(bc).expect("library"); - let f = lib.function(entry).expect("entry"); - let d = ComputePipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new(f))); - let pipe = dev - .compile_compute_pipeline(&d, &Budget::standard()) - .unwrap_or_else(|e| panic!("{what}: {e}")); - let p = - crate::pipeline::testing::profile(stem, DevicePolicy::RESIDENT_TABLES).expect("profile"); - let (_, m) = crate::pipeline::testing::typed_module(bc, entry, &p) - .unwrap_or_else(|e| panic!("{what}: {e}")); - let mut table = StageTable::default(); - table.buffers.insert( - 0, - BoundBuffer::Buffer { - length: 16, - offset: 0, - gpu_address: 0, - device_address: None, - attribute_stride: None, - }, - ); - for &(index, n) in counts { - table - .acceleration_structures - .insert(index, BoundAccelerationStructure { instance_count: n }); - } - let mut state = BindState::default(); - state.stages.insert(Stage::Kernel, table); - let plan = pipe.plan(&dev, &state.shape()).expect("planned"); - assert!( - !plan - .descriptors - .iter() - .any(|w| matches!(w.source, WriteSource::AccelerationStructure { .. })), - "{what}: {:?}", - plan.descriptors - ); - let cmds = plan - .instantiate_dispatch( - &state, - &Dispatch::Threadgroups { - groups: [1, 1, 1], - threads_per_group: [threads, 1, 1], - }, - ) - .expect("instantiated"); - let region = &cmds.regions[0]; - let mut push = Vec::new(); - for w in ®ion.push_constants { - let end = w.offset as usize + w.bytes.len(); - if push.len() < end { - push.resize(end, 0); - } - push[w.offset as usize..end].copy_from_slice(&w.bytes); - } - let mut spec = std::collections::BTreeMap::new(); - for (axis, n) in [Axis::X, Axis::Y, Axis::Z] - .into_iter() - .zip([u64::from(threads), 1, 1]) - { - spec.insert(SpecKey::LocalSize(axis), n); - } - spec.insert(SpecKey::FlatLocalSize, u64::from(threads)); - let res = Resources { - buffers: vec![Buffer { - slot: Some(ResourceSlot { - stage: Stage::Kernel, - kind: ResourceKind::Buffer, - index: 0, - }), - address: None, - bytes: initial.to_vec(), - }], - push, - spec, - }; - let cfg = Config { - workgroups: [1, 1, 1], - ..Config::default() - }; - let mut out = run(&m, &cfg, res).unwrap_or_else(|e| panic!("{what}: {e:?}")); - out.buffers.swap_remove(0) -} - -/// `rt_instance_count` end to end on a device without ray queries and on one with them: the -/// binder plans no descriptor for the structure and pushes the count -/// `StageTable::acceleration_structures` states for its slot, 0 for an unbound slot, and running -/// the module over the instantiated push bytes writes `count * 3 + gid`. -#[test] -fn the_binder_pushes_the_bound_structures_instance_count() { - let Some(bc) = fixture("rt_instance_count") else { - return; - }; - for stem in COUNT_PROFILES { - for count in [Some(5u32), Some(0), None] { - let bound: Vec<(u32, u32)> = count.map(|n| (1, n)).into_iter().collect(); - let out = run_counts(&bc, "rt_instance_count", stem, &bound, 4, [0xAB; 16]); - let n = count.unwrap_or(0); - let want: Vec = (0..4u32).flat_map(|g| (n * 3 + g).to_le_bytes()).collect(); - assert_eq!(out, want, "{stem}: {count:?}"); - } - } -} - /// The declaration of `get_instance_count()`. const COUNT_DECL: &str = "declare i32 @air.get_instance_count_instance_acceleration_structure(ptr addrspace(1))"; @@ -2190,118 +1992,6 @@ fn count_of(name: &str, structure: &str) -> String { ) } -/// `k` of `bc` on every committed profile: translated and valid with neither a ray query nor an -/// acceleration structure in the module, stating the count's runtime fact and push field for -/// exactly the structures at `slots`. -fn assert_counts_everywhere(tag: &str, bc: &[u8], slots: &[u32]) { - let want: Vec = slots - .iter() - .map(|&index| SlotRef { - stage: Stage::Kernel, - class: SlotClass::Buffer, - index, - }) - .collect(); - for (stem, p) in committed_profiles().expect("committed profiles") { - let a = compile(bc, "k", &p).unwrap_or_else(|e| panic!("{tag} on {stem}: {e}")); - let mut facts: Vec = a - .facts - .iter() - .filter_map(|f| match f { - RuntimeFact::AccelerationStructureInstanceCount { slot } => Some(*slot), - _ => None, - }) - .collect(); - facts.sort(); - assert_eq!(facts, want, "{tag} on {stem}: {:?}", a.facts); - let mut fields: Vec = a - .interface - .push - .fields - .iter() - .filter_map(|f| match &f.field { - PushField::InstanceCount(slot) => Some(*slot), - _ => None, - }) - .collect(); - fields.sort(); - assert_eq!(fields, want, "{tag} on {stem}: {:?}", a.interface.push); - let (_, words) = - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{tag} on {stem}: {e}")); - let dis = spirv_dis(&words); - for needle in ["RayQueryKHR", "AccelerationStructureKHR"] { - assert!(!dis.contains(needle), "{tag} on {stem}: {needle} present"); - } - } -} - -/// Two structures, each counted: each count is its own slot's push field, so the binder's two -/// counts reach their own stores, and an unbound one reads 0. -#[test] -fn several_structures_read_their_own_counts() { - let body = format!( - "{}{} store i32 %a, ptr addrspace(1) %0, align 4\n %p1 = getelementptr i32, ptr \ - addrspace(1) %0, i64 1\n store i32 %b, ptr addrspace(1) %p1, align 4\n ret void\n", - count_of("a", "%1"), - count_of("b", "%2"), - ); - let text = kernel_with( - ", ptr addrspace(1) %1, ptr addrspace(1) %2", - &[structure(1, "instance"), structure(2, "instance")], - &body, - COUNT_DECL, - ); - let Some(bc) = assemble("two-counts", &text) else { - return; - }; - assert_counts_everywhere("two-counts", &bc, &[1, 2]); - for stem in COUNT_PROFILES { - for (bound, a, b) in [ - (vec![(1, 7), (2, 9)], 7u32, 9u32), - (vec![(2, 9)], 0, 9), - (vec![(1, 7)], 7, 0), - ] { - let out = run_counts(&bc, "k", stem, &bound, 1, [0xAB; 16]); - let mut want = [0xAB; 16]; - want[..4].copy_from_slice(&a.to_le_bytes()); - want[4..8].copy_from_slice(&b.to_le_bytes()); - assert_eq!(out, want, "{stem}: {bound:?}"); - } - } -} - -/// A count read in one arm of a branch and merged by a phi is the binder's count where that arm -/// runs, and the other arm's value where it does not. -#[test] -fn a_count_under_control_flow_is_the_binders() { - let body = format!( - " %v = load i32, ptr addrspace(1) %0, align 4\n %c = icmp eq i32 %v, 0\n br i1 %c, \ - label %then, label %join\nthen:\n{} br label %join\njoin:\n %r = phi i32 [ %n, %then \ - ], [ 99, %2 ]\n store i32 %r, ptr addrspace(1) %0, align 4\n ret void\n", - count_of("n", "%1"), - ); - let text = kernel_with( - ", ptr addrspace(1) %1", - &[structure(1, "instance")], - &body, - COUNT_DECL, - ); - let Some(bc) = assemble("branch-count", &text) else { - return; - }; - assert_counts_everywhere("branch-count", &bc, &[1]); - for stem in COUNT_PROFILES { - for (first, want) in [(0u32, 5u32), (1, 99)] { - let mut initial = [0xAB; 16]; - initial[..4].copy_from_slice(&first.to_le_bytes()); - let out = run_counts(&bc, "k", stem, &[(1, 5)], 1, initial); - let mut expected = initial; - expected[..4].copy_from_slice(&want.to_le_bytes()); - assert_eq!(out, expected, "{stem}: out[0] = {first}"); - } - } -} - /// A count of a structure that is not an entry argument has no slot the binder knows, so it is /// refused, typed, on every committed profile, never translated: through a `select` or a `phi` /// of two arguments (where the device traces rays, the merge itself; elsewhere the arguments, diff --git a/crates/metal2vulkan/src/tests/engine_recursion.rs b/crates/metal2vulkan/src/tests/engine_recursion.rs index a2a45f3a0..d6d3afa47 100644 --- a/crates/metal2vulkan/src/tests/engine_recursion.rs +++ b/crates/metal2vulkan/src/tests/engine_recursion.rs @@ -36,8 +36,8 @@ //! //! `llvm-as` assembles the module; a missing tool skips visibly. -use super::engine_argument_tables::{bytes_at, device, directory_binding, one_group}; -use crate::bind::{ArgumentFunctionTable, BindState, FunctionTableSnapshot, FunctionTableWords}; +use super::engine_argument_tables::device; +use crate::bind::FunctionTableWords; use crate::budget::{Budget, SPIRV_WORDS}; use crate::device::VkLimit; use crate::error::{Capability, DescriptorError, Error, Feature, Limit, Unsupported}; @@ -589,35 +589,6 @@ fn pipeline(bitcode: &[u8], entry: &str, k: u32) -> (ComputePipeline, Vec (Vec, Vec) { - let dev = device("moltenvk-m3"); - let directory = directory_binding(pipe); - let state = BindState { - function_tables: vec![ArgumentFunctionTable { - resource_id: T, - size: handles.len() as u32, - address: 0, - }], - ..Default::default() - }; - let plan = pipe.plan(&dev, &state.shape()).expect("plan"); - let cmds = plan - .instantiate_dispatch(&state, &one_group()) - .expect("dispatch"); - let directory = bytes_at(&cmds.descriptor_bytes, directory).to_vec(); - let mut table = FunctionTableWords::new(handles.len() as u32); - for (i, h) in handles.iter().enumerate() { - assert!(table.set(i as u32, Some(*h))); - } - let snapshot = FunctionTableSnapshot::of(state.function_tables.iter().map(|f| f.size)) - .expect("snapshot") - .bytes([table.to_bytes().as_slice()]) - .expect("snapshot bytes"); - (directory, snapshot) -} - /// Kernel buffer `index`. pub(super) fn slot(index: u32) -> ResourceSlot { ResourceSlot { @@ -749,29 +720,29 @@ fn direct_recursion_makes_one_call_fewer_than_its_depth() { } } -/// Recursion through a table holds the frames Metal reached: within them each sum and parity is -/// Metal's, past them the sum stops and the parity is zero. -#[test] -fn table_recursion_reaches_the_frames_metal_reaches() { - let Some(bitcode) = module() else { - return; +/// The directory bytes a dispatch gets with table [`T`] listed, and the snapshot of table [`T`] +/// holding `handles` in order (`lower::access::function_table`): the directory is the handle +/// table's layout (`memory::handles`), its null entry and then [`T`]'s, whose element is the word +/// offset of its record in the snapshot (1, after the null table's word count, 0); the record is +/// the table's word count and its words. +fn table_inputs(handles: &[FunctionHandle]) -> (Vec, Vec) { + let entry = |id: u64, element: u32| { + [id as u32, (id >> 32) as u32, element, 0] + .into_iter() + .flat_map(u32::to_le_bytes) }; - let p = profile("moltenvk-m3", crate::device::DevicePolicy::RESIDENT_TABLES).expect("profile"); - for (k, frames) in TABLE_FRAMES { - let (pipe, handles) = pipeline(&bitcode, TABLE, k); - let tables = table_inputs(&pipe, &handles); - let m = typed(&bitcode, TABLE, k, &p); - let ds = depths(frames); - let want: Vec = ds - .iter() - .flat_map(|&d| [sum(d, frames), even(d, frames)]) - .collect(); - assert_eq!( - dispatch(&m, &ds, 2, Some(&tables)), - want, - "depth {k}: {ds:?}" - ); + let directory = entry(0, crate::memory::handles::NEUTRAL_ELEMENT) + .chain(entry(T, 1)) + .collect(); + let mut table = FunctionTableWords::new(handles.len() as u32); + for (i, h) in handles.iter().enumerate() { + assert!(table.set(i as u32, Some(*h))); } + let words = table.to_bytes(); + let mut snapshot = 0u32.to_le_bytes().to_vec(); + snapshot.extend((words.len() as u32 / 4).to_le_bytes()); + snapshot.extend(words); + (directory, snapshot) } /// A frame keeps its function's private array across the recursive call: at depth 8 every one of @@ -783,8 +754,8 @@ fn a_recursive_frame_keeps_its_private_array() { return; }; let p = profile("moltenvk-m3", crate::device::DevicePolicy::RESIDENT_TABLES).expect("profile"); - let (pipe, handles) = pipeline(&bitcode, BIG, 8); - let tables = table_inputs(&pipe, &handles); + let (_, handles) = pipeline(&bitcode, BIG, 8); + let tables = table_inputs(&handles); let m = typed(&bitcode, BIG, 8, &p); let ds: Vec = vec![0, 1, 2, 5, 6, 7, 8]; let want: Vec = ds.iter().map(|&d| big(d, 8)).collect(); @@ -815,8 +786,8 @@ fn recursive_kernels_validate_and_agree_on_every_profile() { let Some(bitcode) = module() else { return; }; - let (pipe, handles) = pipeline(&bitcode, TABLE, 8); - let tables = table_inputs(&pipe, &handles); + let (_, handles) = pipeline(&bitcode, TABLE, 8); + let tables = table_inputs(&handles); let check = |stem: &str, entry: &str, p: &crate::device::DeviceProfile| { let a = compile(&bitcode, entry, 8, p).unwrap_or_else(|e| panic!("{stem}: {e}")); link_and_validate(&a, p).unwrap_or_else(|e| panic!("{stem} {entry}: L3: {e}")); @@ -1114,3 +1085,28 @@ fn recursion_through_a_pointer_passed_as_a_value_makes_one_call_fewer_than_its_d } } } + +/// Recursion through a table holds the frames Metal reached: within them each sum and parity is +/// Metal's, past them the sum stops and the parity is zero. +#[test] +fn table_recursion_reaches_the_frames_metal_reaches() { + let Some(bitcode) = module() else { + return; + }; + let p = profile("moltenvk-m3", crate::device::DevicePolicy::RESIDENT_TABLES).expect("profile"); + for (k, frames) in TABLE_FRAMES { + let (_, handles) = pipeline(&bitcode, TABLE, k); + let tables = table_inputs(&handles); + let m = typed(&bitcode, TABLE, k, &p); + let ds = depths(frames); + let want: Vec = ds + .iter() + .flat_map(|&d| [sum(d, frames), even(d, frames)]) + .collect(); + assert_eq!( + dispatch(&m, &ds, 2, Some(&tables)), + want, + "depth {k}: {ds:?}" + ); + } +} diff --git a/crates/metal2vulkan/src/tests/engine_region_viewports.rs b/crates/metal2vulkan/src/tests/engine_region_viewports.rs index cb79a4426..2126e8e07 100644 --- a/crates/metal2vulkan/src/tests/engine_region_viewports.rs +++ b/crates/metal2vulkan/src/tests/engine_region_viewports.rs @@ -8,32 +8,23 @@ //! stores `ViewportIndex` (needing `shaderDrawParameters` and `shaderOutputViewportIndex`) while //! its contract states no viewport selection, and passes L3 (`spirv-val` and requirements //! within the profile), adding a bounded handful of words; compiled without it, it reads no -//! `DrawIndex` and stores no `ViewportIndex`. The variant's pipeline selects none of the encoder's viewports -//! (`GraphicsState::writes_viewport_index`), so a rate-mapped pass's plan admits it. +//! `DrawIndex` and stores no `ViewportIndex`. The variant's pipeline selects none of the +//! encoder's viewports (`GraphicsState::writes_viewport_index`). //! - A fragment function compiled under it that reads `[[viewport_array_index]]` reads 0 and //! declares no `ViewportIndex`. //! - A vertex function that selects its own viewport, a post-tessellation one, and one under //! draws of one amplification each is //! `NotImplemented(RasterizationRateMap)`; a device without `shaderDrawParameters` names the //! three features the variant needs. -//! - A render plan whose shape asks for it states the variant, which the pipeline compiled -//! without it does not draw (`BindError::NeedsVariant`); compiled, the variant states the fact -//! and its plan settles on itself. //! //! `llvm-as` assembles the fixtures; a missing tool skips visibly. No GPU is used. use std::path::Path; -use crate::bind::{BindState, DrawCall}; -use crate::budget::Budget; use crate::device::requirements::VkFeature as F; use crate::device::{Device, DeviceDescription, DevicePolicy, DeviceProfile}; -use crate::error::{BindError, Capability, Error, Feature, Unsupported}; -use crate::library::{FunctionArtifact, Library}; -use crate::metal::PixelFormat; -use crate::pipeline::descriptor::{ - ColorAttachmentDescriptor, FunctionDescriptor, RenderPipelineDescriptor, StageSource, -}; +use crate::error::{Capability, Error, Feature, Unsupported}; +use crate::library::FunctionArtifact; use crate::pipeline::facts::RuntimeFact; use crate::pipeline::link::{link, LinkInputs}; use crate::pipeline::lower_inputs::{AmplificationDraws, LoweringInputs}; @@ -209,81 +200,3 @@ fn region_viewports_refuse_what_is_drawn_region_by_region() { ); compile_with(&viewports, "rfb_full", &without, &inputs(false)).expect("without the field"); } - -/// A plan whose shape draws regions several at a time states the variant, which the base -/// pipeline does not draw; compiled, the variant's modules pass L3, it states the fact, and its -/// plan settles on itself and draws. -#[test] -fn a_region_draw_runs_its_variant() { - let Some(bc) = fixture("rt6_viewports") else { - return; - }; - let budget = Budget::standard(); - let lib = Library::from_air(&bc).expect("library"); - let Some(full) = fixture("rfb_viewports") else { - return; - }; - let full = Library::from_air(&full).expect("library"); - let mut d = RenderPipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new( - full.function("rfb_full").expect("function"), - ))); - d.fragment = Some(StageSource::Function(FunctionDescriptor::new( - lib.function("rt6_viewport_read").expect("function"), - ))); - d.color_attachments[0] = Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm)); - let triangle = DrawCall::Primitives { - vertex_start: 0, - vertex_count: 3, - instance_count: 1, - base_instance: 0, - }; - for stem in ["lavapipe", "intel-irisxe-rplp-anv"] { - let dev = - Device::from_queries(description(stem), DevicePolicy::RESIDENT_TABLES).expect("device"); - let base = dev - .compile_render_pipeline(&d, &budget) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - let state = BindState { - region_viewports: true, - ..Default::default() - }; - let plan = base - .plan(&dev, &state.shape()) - .unwrap_or_else(|e| panic!("{stem}: {e:?}")); - assert!(plan.variant.region_viewports, "{stem}"); - assert_eq!( - plan.instantiate_draw(&state, &triangle), - Err(BindError::NeedsVariant { - variant: Box::new(plan.variant.clone()) - }), - "{stem}" - ); - let key = plan.variant.clone(); - let p = dev - .compile_render_variant(&d, &key, &budget) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - for m in &p.stages { - check_words_valid(&m.spirv, &p.requirements, dev.profile()) - .unwrap_or_else(|e| panic!("{stem} {:?}: L3: {e}", m.stage)); - } - assert!( - p.dependencies - .iter() - .any(|x| x.fact == RuntimeFact::RegionViewports), - "{stem}" - ); - // It selects none of the encoder's viewports: a rate-mapped pass's plan admits it. - assert!(!p.graphics.writes_viewport_index, "{stem}"); - let plan = p - .plan(&dev, &state.shape()) - .unwrap_or_else(|e| panic!("{stem}: {e:?}")); - assert_eq!(plan.variant, key, "{stem}"); - plan.instantiate_draw(&state, &triangle) - .unwrap_or_else(|e| panic!("{stem}: {e:?}")); - // Drawn one region at a time, the base pipeline's plan is its own. - let plain = base - .plan(&dev, &BindState::default().shape()) - .unwrap_or_else(|e| panic!("{stem}: {e:?}")); - assert!(!plain.variant.region_viewports, "{stem}"); - } -} diff --git a/crates/metal2vulkan/src/tests/engine_render_target_slice.rs b/crates/metal2vulkan/src/tests/engine_render_target_slice.rs index b4525efff..418777477 100644 --- a/crates/metal2vulkan/src/tests/engine_render_target_slice.rs +++ b/crates/metal2vulkan/src/tests/engine_render_target_slice.rs @@ -17,8 +17,6 @@ use std::path::Path; -use crate::bind::plan::FieldLocation; -use crate::bind::{BindState, DrawCall, VertexAmplification, ViewMapping, ViewSetup}; use crate::budget::Budget; use crate::cache::VariantKey; use crate::device::{Device, DeviceDescription, DevicePolicy}; @@ -28,11 +26,10 @@ use crate::pipeline::descriptor::{FunctionDescriptor, RenderPipelineDescriptor, use crate::pipeline::facts::RuntimeFact; use crate::pipeline::lower_inputs::LoweringInputs; use crate::pipeline::stage_io::{IoRole, StageBuiltin}; -use crate::pipeline::sym::{PushField, Stage, VaryingKey}; -use crate::pipeline::testing::{engine_dir, fixtures_dir, llvm_assemble, AssembleError}; -use crate::pipeline::{AmplificationDraws, RenderPipeline}; +use crate::pipeline::sym::{Stage, VaryingKey}; +use crate::pipeline::testing::{engine_dir, llvm_assemble, AssembleError}; +use crate::pipeline::RenderPipeline; use crate::spirv::testing::check_words_valid; -use crate::vk; fn assemble(path: &Path) -> Option> { match llvm_assemble(path) { @@ -72,23 +69,6 @@ fn render(bc: &[u8], vertex: &str, fragment: Option<&str>, max: u32) -> RenderPi d } -/// A bind state of a pass of `length` layers. -fn pass(length: u32) -> BindState { - BindState { - render_target_array_length: length, - ..Default::default() - } -} - -fn draw() -> DrawCall { - DrawCall::Primitives { - vertex_start: 0, - vertex_count: 3, - instance_count: 1, - base_instance: 0, - } -} - /// The `RenderTargetArrayLength` fact of `p`'s vertex function, if it chooses its slice. fn layer_fact(p: &RenderPipeline) -> Option { p.dependencies.iter().find_map(|d| match d.fact { @@ -97,41 +77,6 @@ fn layer_fact(p: &RenderPipeline) -> Option { }) } -/// Whether `p`'s vertex stage reads the pass's length from its push data. -fn reads_length(p: &RenderPipeline) -> bool { - p.interface.push.iter().any(|pl| { - pl.stage == Stage::Vertex - && pl - .fields - .iter() - .any(|f| f.field == PushField::RenderTargetArrayLength) - }) -} - -/// The bytes of `p`'s vertex push data that hold the pass's length, in the draw of a pass of -/// `length` layers. -fn length_word(p: &RenderPipeline, dev: &Device, length: u32) -> [u8; 4] { - let state = pass(length); - let plan = p.plan(dev, &state.shape()).expect("plan"); - let placed = plan - .push - .fields - .iter() - .find(|f| f.stage == Stage::Vertex && f.field == PushField::RenderTargetArrayLength) - .expect("placed"); - let FieldLocation::PushWindow { offset } = placed.location else { - panic!("the length spilled: {placed:?}"); - }; - let commands = plan.instantiate_draw(&state, &draw()).expect("draw"); - let write = commands - .push_constants - .iter() - .find(|w| w.stages.contains(vk::ShaderStageFlags::VERTEX)) - .expect("vertex push"); - let at = (offset - write.offset) as usize; - write.bytes[at..at + 4].try_into().expect("a word") -} - /// Every stage of `p` passes L3 on `dev`. fn valid(p: &RenderPipeline, dev: &Device, what: &str) { for m in &p.stages { @@ -140,97 +85,6 @@ fn valid(p: &RenderPipeline, dev: &Device, what: &str) { } } -/// The vertex function that chooses its slice writes `Layer` in a pass of any length: each plan -/// states no variant, and each draw writes the pass's length as at least 1, which the function -/// reads (at 0 and 1 it stores 0 for every index). Amplified draws in a pass of one layer are -/// drawn one amplification at a time, without `Layer`, never as views. -#[test] -fn every_pass_runs_the_vertex_function_that_writes_its_layer() { - let Some(bc) = assemble(&engine_dir().join("vertex_amplification.ll")) else { - return; - }; - let Some(public) = assemble(&fixtures_dir().join("vertex_amplification_id_layer.ll")) else { - return; - }; - let budget = Budget::standard(); - let pipelines = [ - (&bc, "amp_vertex_layer", None), - (&bc, "amp_vertex_layer", Some("amp_fragment_layer")), - (&public, "vertex_amplification_id_layer", None), - ]; - for stem in ["amd-780m-radv", "lavapipe"] { - let dev = device(stem); - for (bc, vertex, fragment) in pipelines { - let what = format!("{stem} {vertex} {fragment:?}"); - let d = render(bc, vertex, fragment, 2); - let written = dev - .compile_render_pipeline(&d, &budget) - .unwrap_or_else(|e| panic!("{what}: {e}")); - valid(&written, &dev, &what); - assert_eq!(layer_fact(&written), Some(false), "{what}"); - assert!(written.graphics.declares_layer, "{what}"); - assert!(reads_length(&written), "{what}"); - for length in [0, 1, 4] { - assert_eq!( - length_word(&written, &dev, length), - length.max(1).to_le_bytes(), - "{what} {length}" - ); - let plan = written.plan(&dev, &pass(length).shape()).expect("plan"); - assert!(plan.variant.is_empty(), "{what} {length}"); - plan.instantiate_draw(&pass(length), &draw()) - .unwrap_or_else(|e| panic!("{what} {length}: {e:?}")); - } - let mut amplified = pass(1); - amplified.vertex_amplification = VertexAmplification::new( - 2, - vec![ - ViewMapping { - viewport_array_index_offset: 0, - render_target_array_index_offset: 0, - }, - ViewMapping { - viewport_array_index_offset: 0, - render_target_array_index_offset: 1, - }, - ], - ); - let plan = written - .plan(&dev, &lified.shape()) - .unwrap_or_else(|e| panic!("{what}: {e:?}")); - assert_eq!(plan.views, ViewSetup::default(), "{what}"); - assert_eq!( - plan.variant.amplification_draws, - Some(AmplificationDraws::new(false, false)), - "{what}" - ); - } - } -} - -/// A fragment function that reads its slice behind a vertex function that does not choose one -/// asks for no variant at any length: there is no `Layer` output to drop. -#[test] -fn a_fragment_reading_its_slice_alone_asks_for_no_variant() { - let Some(bc) = assemble(&engine_dir().join("vertex_amplification.ll")) else { - return; - }; - let dev = device("amd-780m-radv"); - let p = dev - .compile_render_pipeline( - &render(&bc, "amp_vertex", Some("amp_fragment_layer"), 1), - &Budget::standard(), - ) - .expect("pipeline"); - assert_eq!(layer_fact(&p), None); - for length in [0, 1, 4] { - let plan = p.plan(&dev, &pass(length).shape()).expect("plan"); - assert!(plan.variant.is_empty(), "{length}"); - plan.instantiate_draw(&pass(length), &draw()) - .unwrap_or_else(|e| panic!("{length}: {e:?}")); - } -} - /// A vertex function that writes `[[render_target_array_index]]` writes the index as written to a /// flat varying (`IoRole::RenderTargetArrayIndex`), stores `Layer` and reads the pass's length from /// its push data. In its pipeline a fragment function that reads the slice compiles under diff --git a/crates/metal2vulkan/src/tests/engine_rotated_weights.rs b/crates/metal2vulkan/src/tests/engine_rotated_weights.rs index f112a9a4a..e93d40cfb 100644 --- a/crates/metal2vulkan/src/tests/engine_rotated_weights.rs +++ b/crates/metal2vulkan/src/tests/engine_rotated_weights.rs @@ -9,17 +9,12 @@ //! `1 - (x + y)` once more than without it, each operation `NoContraction`; a `float` read //! reads lane 1 where it read lane 0. //! - A function that reads no weights is the same module under it, and states nothing. -//! - A draw whose shape draws its triangles rotated (`BindState::rotated_weights`) runs the -//! variant where its pipeline reads the weights (`BindError::NeedsVariant` from the base), -//! whose plan states it; a pipeline that reads none draws as it is. //! //! What the weights hold is a Metal probe's (the M3 Max, macOS 27.0.1: the first weight bit for //! bit, the others within `2^-15`). Every module passes L3. `llvm-as` assembles the fixtures; a //! missing tool skips visibly. No GPU is used. -use std::path::Path; - -use crate::device::{Device, DeviceDescription, DevicePolicy, DeviceProfile}; +use crate::device::{DevicePolicy, DeviceProfile}; use crate::library::FunctionArtifact; use crate::pipeline::facts::RuntimeFact; use crate::pipeline::link::{link, LinkInputs}; @@ -171,109 +166,3 @@ fn rotated_weights_take_metal_s_weights_from_the_drawn_triangle_s() { ); } } - -/// A draw that draws its triangles rotated runs the variant of a pipeline that reads the weights, -/// whose plan states it and draws; one that reads none draws as it is. -#[test] -fn a_rotated_draw_runs_the_rotated_weights_variant() { - use crate::bind::{BindState, DrawCall}; - use crate::budget::Budget; - use crate::error::BindError; - use crate::library::Library; - use crate::metal::PixelFormat; - use crate::pipeline::descriptor::{ - ColorAttachmentDescriptor, FunctionDescriptor, RenderPipelineDescriptor, StageSource, - }; - let Some(bc) = fixture("rt6_provoking") else { - return; - }; - let budget = Budget::standard(); - let lib = Library::from_air(&bc).expect("library"); - let function = - |name| StageSource::Function(FunctionDescriptor::new(lib.function(name).expect(name))); - let triangle = DrawCall::Primitives { - vertex_start: 0, - vertex_count: 3, - instance_count: 1, - base_instance: 0, - }; - let state = BindState { - rotated_weights: true, - ..Default::default() - }; - for stem in ["moltenvk-m3", "amd-780m-radv"] { - let 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 desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); - let dev = Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device"); - for (fragment, reads) in [("pv_both", true), ("pv_flat", false)] { - let what = format!("{stem} {fragment}"); - let mut d = RenderPipelineDescriptor::new(function("pv_vertex")); - d.fragment = Some(function(fragment)); - for (i, format) in [ - PixelFormat::RGBA32Float, - PixelFormat::RGBA32Float, - PixelFormat::RGBA32Uint, - ] - .into_iter() - .enumerate() - { - d.color_attachments[i] = Some(ColorAttachmentDescriptor::new(format)); - } - let base = dev - .compile_render_pipeline(&d, &budget) - .unwrap_or_else(|e| panic!("{what}: {e}")); - assert_eq!(base.graphics.reads_barycentric_coord, reads, "{what}"); - let plan = base - .plan(&dev, &state.shape()) - .unwrap_or_else(|e| panic!("{what}: {e:?}")); - assert_eq!(plan.variant.rotated_weights, reads, "{what}"); - if !reads { - plan.instantiate_draw(&state, &triangle) - .unwrap_or_else(|e| panic!("{what}: {e:?}")); - continue; - } - assert_eq!( - plan.instantiate_draw(&state, &triangle), - Err(BindError::NeedsVariant { - variant: Box::new(plan.variant.clone()) - }), - "{what}" - ); - let key = plan.variant.clone(); - let v = dev - .compile_render_variant(&d, &key, &budget) - .unwrap_or_else(|e| panic!("{what}: {e}")); - for m in &v.stages { - check_words_valid(&m.spirv, &v.requirements, dev.profile()) - .unwrap_or_else(|e| panic!("{what} {:?}: L3: {e}", m.stage)); - } - assert!( - v.dependencies - .iter() - .any(|x| x.fact == RuntimeFact::RotatedWeights), - "{what}" - ); - let plan = v - .plan(&dev, &state.shape()) - .unwrap_or_else(|e| panic!("{what}: {e:?}")); - assert_eq!(plan.variant, key, "{what}"); - plan.instantiate_draw(&state, &triangle) - .unwrap_or_else(|e| panic!("{what}: {e:?}")); - // Drawn as it is, the variant asks for the base again. - let plan = v - .plan(&dev, &BindState::default().shape()) - .unwrap_or_else(|e| panic!("{what}: {e:?}")); - assert!(!plan.variant.rotated_weights, "{what}"); - assert!( - matches!( - plan.instantiate_draw(&BindState::default(), &triangle), - Err(BindError::NeedsVariant { .. }) - ), - "{what}" - ); - } - } -} diff --git a/crates/metal2vulkan/src/tests/engine_separate_samplers.rs b/crates/metal2vulkan/src/tests/engine_separate_samplers.rs index 7fb666142..a59142ca9 100644 --- a/crates/metal2vulkan/src/tests/engine_separate_samplers.rs +++ b/crates/metal2vulkan/src/tests/engine_separate_samplers.rs @@ -18,24 +18,17 @@ //! //! `llvm-as` assembles the fixtures; without it the tests skip visibly. -use crate::bind::{ - BindState, BoundBuffer, BoundSampler, BoundTexture, NeutralResource, SamplerDescriptor, - StageTable, TextureFacts, WriteSource, -}; -use crate::budget::Budget; use crate::device::profile::DeviceProfile; use crate::device::requirements::VkLimit; use crate::device::{Device, DeviceDescription, DevicePolicy}; use crate::error::{Capability, Error, Feature, Needs}; -use crate::library::{FunctionArtifact, Library}; -use crate::metal::{PixelFormat, SamplerMinMagFilter, TextureType}; +use crate::library::FunctionArtifact; use crate::pipeline::layout::BindingSource; use crate::pipeline::link::{link, LinkInputs}; -use crate::pipeline::sym::{ResourceKind, SamplerRef, SlotClass, SlotRef, Stage}; +use crate::pipeline::sym::{ResourceKind, SamplerRef, Stage}; use crate::pipeline::testing::{ compile, engine_dir, link_and_validate, llvm_assemble, AssembleError, }; -use crate::pipeline::{ComputePipelineDescriptor, FunctionDescriptor, StageSource}; use crate::spirv::testing::committed_profiles; use crate::vk; @@ -222,105 +215,3 @@ fn the_trigger_is_the_sampler_limit() { assert_ne!(a31.module.words, a32.module.words, "{name}"); } } - -/// `smp_runtime_array` on `moltenvk-m3` samples 32 separate textures through one runtime separate -/// sampler. The plan writes the sampler with the one bound at the kernel's slot 0, made for the use -/// (the neutral sampler where none is bound), and each separate texture with its bound texture's -/// view; a texture slot left unbound reads the neutral image. -#[test] -fn the_binder_writes_a_runtime_separate_sampler_and_its_textures() { - let Some(bc) = fixture("smp_runtime_array") else { - return; - }; - let dev = m3_with(|_| {}); - let lib = Library::from_air(&bc).expect("library"); - let f = lib.function("smp_runtime_array").expect("entry"); - let d = ComputePipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new(f))); - let pipe = dev - .compile_compute_pipeline(&d, &Budget::standard()) - .expect("pipeline"); - let sampler_binding = pipe.layout.sets[0] - .bindings - .iter() - .find(|b| matches!(b.source, BindingSource::SeparateSampler { .. })) - .expect("separate sampler") - .binding; - let state = |bound: u32, sampler: Option| { - let mut t = StageTable::default(); - for i in 0..bound { - t.textures.insert( - i, - BoundTexture::Texture { - facts: TextureFacts::new(TextureType::Type2D, PixelFormat::RGBA16Float), - resource_id: None, - }, - ); - } - if let Some(s) = sampler { - t.samplers.insert(0, s); - } - t.buffers.insert( - 0, - BoundBuffer::Buffer { - length: 32 * 16, - offset: 0, - gpu_address: 0x1000_0000, - device_address: None, - attribute_stride: None, - }, - ); - let mut state = BindState::default(); - state.stages.insert(Stage::Kernel, t); - state - }; - let mut linear = SamplerDescriptor::new(); - linear.min_filter = SamplerMinMagFilter::Linear; - linear.mag_filter = SamplerMinMagFilter::Linear; - let s0 = SlotRef { - stage: Stage::Kernel, - class: SlotClass::Sampler, - index: 0, - }; - for (bound, sampler, want) in [ - ( - 32, - Some(BoundSampler::new(linear)), - WriteSource::Sampler { - slot: s0, - compare: false, - integer: false, - opaque_black: crate::metal::sampler::OpaqueBlackBorder::Stated, - }, - ), - ( - 31, - None, - WriteSource::Neutral(NeutralResource::Sampler { compare: false }), - ), - ] { - let plan = pipe - .plan(&dev, &state(bound, sampler).shape()) - .expect("plan"); - let written: Vec<_> = plan - .descriptors - .iter() - .filter(|w| w.set == 0 && w.binding == sampler_binding) - .map(|w| w.source.clone()) - .collect(); - assert_eq!(written, vec![want]); - let mut textures = 0; - let mut neutral = 0; - for w in &plan.descriptors { - match &w.source { - WriteSource::Texture { slot, .. } if slot.class == SlotClass::Texture => { - assert_eq!(w.ty, vk::DescriptorType::SAMPLED_IMAGE); - textures += 1; - } - WriteSource::Neutral(NeutralResource::Image { .. }) => neutral += 1, - WriteSource::CombinedImageSampler { .. } => panic!("a combined write"), - _ => {} - } - } - assert_eq!((textures, neutral), (bound, 32 - bound)); - } -} diff --git a/crates/metal2vulkan/src/tests/engine_simd_emulated.rs b/crates/metal2vulkan/src/tests/engine_simd_emulated.rs index 2ad0fd447..3898d3069 100644 --- a/crates/metal2vulkan/src/tests/engine_simd_emulated.rs +++ b/crates/metal2vulkan/src/tests/engine_simd_emulated.rs @@ -31,13 +31,12 @@ use std::collections::BTreeMap; -use crate::bind::{BindState, BoundBuffer, Dispatch, StageTable}; use crate::budget::Budget; use crate::cache::VariantKey; use crate::device::profile::{DeviceProfile, HandleDomain, PointerDomain}; use crate::device::subgroup::{OpBits, SimdClass, SubgroupRequirement, Tier}; use crate::device::{Device, DeviceDescription, DevicePolicy}; -use crate::error::{BindError, Error, Feature}; +use crate::error::{Error, Feature}; use crate::library::Library; use crate::lower::dispatch::{region_bytes, LocalSizeForm}; use crate::lower::select::Plan; @@ -56,7 +55,6 @@ use crate::pipeline::{ use crate::spirv::interp::{run, BarrierRule, Buffer, Config, Order, Resources, SubgroupSize}; use crate::spirv::ir::TypedModule; use crate::spirv::testing::spirv_dis; -use crate::vk; /// The committed profiles whose kernels' simdgroups are emulated. const PROFILES: [&str; 2] = ["lavapipe", "runtime-floor"]; @@ -1512,8 +1510,7 @@ fn the_static_length_is_rounded_up_to_16_bytes_as_metal_reports_it() { /// The scratch takes 128 bytes per simdgroup and word beside the kernel's threadgroup memory. A /// kernel whose arena leaves less than one simdgroup's scratch is refused at compile time; /// otherwise the pipeline reports the threads whose scratch fits as its maximum and its own -/// threadgroup memory as its static length, as Metal reports it, and the planner refuses a larger -/// threadgroup as `ThreadgroupMemorySize`. +/// threadgroup memory as its static length, as Metal reports it. #[test] fn the_scratch_must_fit_beside_the_threadgroup_memory() { // roadmap-2022: 16 KiB. An arena of exactly 16 KiB leaves nothing for the scratch. @@ -1543,19 +1540,13 @@ fn the_scratch_must_fit_beside_the_threadgroup_memory() { let pipe = pipeline(&dev, &bc, "barrier_k"); assert_eq!(pipe.metal_info.max_total_threads_per_threadgroup, 256); assert_eq!(pipe.metal_info.static_threadgroup_memory_length, 31 * 1024); - let state = bind_state(None); - let plan = pipe.plan(&dev, &state.shape()).expect("plan"); - assert!(plan.instantiate_dispatch(&state, &threads(256)).is_ok()); - assert_memory_refused(plan.instantiate_dispatch(&state, &threads(257)), 32896); } /// A kernel that reads a `[[threadgroup(0)]]` region declares the threadgroup arena, a `u32` array /// of at least `MIN_ARENA_BYTES` even when the region is empty, beside the scratch. `region_k` /// publishes eight words per lane (1 KiB per simdgroup): lavapipe's 32 KiB fits 31 simdgroups /// beside the 32-byte arena, not 32. The reported static length is the kernel's own, 0, as Metal -/// reports it: neither the arena's minimum nor the scratch, which the planner still counts, so the -/// remainder a Metal client gives the region beside that length is refused at the most threads -/// (the device's gap, `ThreadgroupMemorySize`), and a region that fits beside the scratch runs. +/// reports it: neither the arena's minimum nor the scratch. #[test] fn an_empty_region_declares_the_arena_beside_the_scratch() { let Some(bc) = assemble("simd_uniform") else { @@ -1563,28 +1554,8 @@ fn an_empty_region_declares_the_arena_beside_the_scratch() { }; let dev = lavapipe(); let pipe = pipeline(&dev, &bc, "region_k"); - let state = bind_state(Some(0)); - let plan = pipe.plan(&dev, &state.shape()).expect("plan"); - assert_memory_refused( - plan.instantiate_dispatch(&state, &threads(1024)), - 32 + 32 * 1024, - ); - assert!(plan.instantiate_dispatch(&state, &threads(31 * 32)).is_ok()); assert_eq!(pipe.metal_info.max_total_threads_per_threadgroup, 31 * 32); assert_eq!(pipe.metal_info.static_threadgroup_memory_length, 0); - // The remainder beside the reported static length, at the most threads: the arena and the - // scratch of 31 simdgroups do not fit beside it. - let remainder = 32 * 1024 - pipe.metal_info.static_threadgroup_memory_length; - let state = bind_state(Some(remainder)); - let plan = pipe.plan(&dev, &state.shape()).expect("plan"); - match plan.instantiate_dispatch(&state, &threads(31 * 32)) { - Err(BindError::Unsupported(u)) => assert_eq!(u.feature, Feature::ThreadgroupMemorySize), - other => panic!("{other:?}"), - } - // A region that fits beside the arena and the scratch runs. - let state = bind_state(Some(32 * 1024 - 32 - 31 * 1024)); - let plan = pipe.plan(&dev, &state.shape()).expect("plan"); - assert!(plan.instantiate_dispatch(&state, &threads(31 * 32)).is_ok()); } /// An emulated operation exchanges through workgroup memory between workgroup barriers in @@ -1672,45 +1643,6 @@ fn pipeline(dev: &Device, bc: &[u8], kernel: &str) -> ComputePipeline { .unwrap_or_else(|e| panic!("{kernel}: {e}")) } -/// Buffer 0 bound, and `[[threadgroup(0)]]` set to `region` bytes. -fn bind_state(region: Option) -> BindState { - let mut table = StageTable::default(); - table.buffers.insert( - 0, - BoundBuffer::Buffer { - length: 4096, - offset: 0, - gpu_address: 0x1_0000, - device_address: None, - attribute_stride: None, - }, - ); - if let Some(len) = region { - table.threadgroup_lengths.insert(0, len); - } - let mut state = BindState::default(); - state.stages.insert(Stage::Kernel, table); - state -} - -fn threads(n: u32) -> Dispatch { - Dispatch::Threadgroups { - groups: [1, 1, 1], - threads_per_group: [n, 1, 1], - } -} - -fn assert_memory_refused(r: Result, required: u64) { - match r { - Err(BindError::Unsupported(u)) => { - assert_eq!(u.feature, Feature::ThreadgroupMemorySize); - let needs = format!("{:?}", u.needs); - assert!(needs.contains(&format!("required: {required},")), "{needs}"); - } - other => panic!("{other:?}"), - } -} - /// The committed profile whose kernels run their simdgroups on whole 32-lane subgroups /// (`Direct`, `REQUIRE_FULL_SUBGROUPS`): a threadgroup with a partial simdgroup runs on the /// kernel's emulated-simdgroups variant. @@ -1741,12 +1673,6 @@ fn emulated_key() -> VariantKey { key } -fn one_row_key() -> VariantKey { - let mut key = VariantKey::new(); - key.one_row = true; - key -} - /// `kernel` of `bc` on `DIRECT`: its own tier is `Direct` with a multiple-of-32 constraint, and /// under the emulated-simdgroups input the `Emulated` tier, which depends on the variant, passes /// L3 without a subgroup instruction, and gives the reading (a partial simdgroup's active lanes are @@ -1826,238 +1752,6 @@ fn partial_simdgroups_run_on_the_emulated_variant_of_a_direct_kernel() { } } -/// Through the public API on `DIRECT`: the plan of a kernel whose simdgroups run on whole subgroups -/// asks for the emulated-simdgroups variant exactly for the dispatches with a partial simdgroup -/// (and a `dispatchThreads` grid whose edge has one), instead of refusing them; the pipeline -/// compiled under that key states it in its plan and runs each of them, and a full one, with -/// Metal's local size and no subgroup requirement. A profile that emulates every kernel's -/// simdgroups never asks. -#[test] -fn the_plan_asks_for_the_emulated_variant_only_for_partial_simdgroups() { - let Some(bc) = assemble("simd_ops") else { - return; - }; - let dev = direct(); - let budget = Budget::standard(); - let f = Library::from_air(&bc) - .and_then(|lib| lib.function("simd_sum_k")) - .expect("kernel"); - let fd = FunctionDescriptor::new(f); - let base = pipeline(&dev, &bc, "simd_sum_k"); - let state = bind_state(None); - let shape = state.shape(); - let plan = base.plan(&dev, &shape).expect("plan"); - assert!(plan.variant.is_empty()); - let key = emulated_key(); - let edge = Dispatch::Threads { - threads: [40, 1, 1], - threads_per_group: [32, 1, 1], - }; - for d in [threads(1), threads(4), threads(8), threads(16), edge] { - assert_eq!(plan.dispatch_variant(&d), Ok(key.clone()), "{d:?}"); - assert_eq!( - plan.instantiate_dispatch(&state, &d), - Err(BindError::NeedsVariant { - variant: Box::new(key.clone()) - }), - "{d:?}" - ); - } - // Whole simdgroups keep the flattened pipeline. - for n in [32, 64] { - assert_eq!(plan.dispatch_variant(&threads(n)), Ok(VariantKey::new())); - let c = plan - .instantiate_dispatch(&state, &threads(n)) - .expect("full"); - assert!(c.regions[0] - .stage_flags - .contains(vk::PipelineShaderStageCreateFlags::REQUIRE_FULL_SUBGROUPS)); - } - - // The variant the plan asked for. - let compiled = dev - .compile_function(&fd, &key.lowering_inputs(Stage::Kernel), &budget) - .expect("variant"); - assert_ne!( - *compiled.key(), - dev.function_compile_key(&fd, &LoweringInputs::new()) - ); - let variant = dev - .compile_compute_pipeline( - &ComputePipelineDescriptor::new(StageSource::Compiled(compiled)), - &budget, - ) - .expect("variant pipeline"); - assert_ne!(variant.key, base.key); - assert!(variant - .dependencies - .iter() - .any(|d| d.fact == RuntimeFact::EmulatedSimdgroups && d.mechanism == Mechanism::Variant)); - assert_eq!(variant.stage.required_subgroup_size, None); - assert!(variant.stage.stage_flags.is_empty()); - let vplan = variant.plan(&dev, &shape).expect("variant plan"); - assert_eq!(vplan.variant, key, "the variant's plan states its key"); - for d in [threads(1), threads(4), threads(16), threads(32), edge] { - assert_eq!(vplan.dispatch_variant(&d), Ok(key.clone()), "{d:?}"); - let c = vplan.instantiate_dispatch(&state, &d).expect("runs"); - for r in &c.regions { - assert!(r.stage_flags.is_empty(), "{d:?}"); - assert_eq!(r.required_subgroup_size, None, "{d:?}"); - } - } - - // lavapipe emulates every kernel's simdgroups: no dispatch asks for a variant. - let lava = lavapipe(); - let own = pipeline(&lava, &bc, "simd_sum_k"); - let lplan = own.plan(&lava, &shape).expect("plan"); - assert_eq!(lplan.dispatch_variant(&threads(16)), Ok(VariantKey::new())); - assert!(lplan.instantiate_dispatch(&state, &threads(16)).is_ok()); -} - -/// The emulated tier's own limits stay refusals when a partial simdgroup asks for the variant. A -/// matrix multiply-add in a divergent block compiles in both; a kernel whose threadgroup memory -/// leaves no room for one simdgroup's scratch is `ThreadgroupMemorySize` at the variant's compile; -/// and one that leaves room for some is refused at the variant's plan for a threadgroup whose -/// scratch does not fit, which the `Direct` pipeline runs when its simdgroups are whole. -#[test] -fn the_emulated_tiers_limits_stay_refused_for_partial_simdgroups() { - let dev = direct(); - let p = dev.profile(); - let emulated = |bc: &[u8], kernel: &str| { - let f = Library::from_air(bc) - .and_then(|lib| lib.function(kernel)) - .expect("kernel"); - dev.compile_function( - &FunctionDescriptor::new(f), - &emulated_inputs(), - &Budget::standard(), - ) - }; - - let text = std::fs::read_to_string(engine_dir().join("simd_matrix.ll")).expect("read"); - let text = text.replacen( - " %5 = shl i32 %3, 1\n", - " %c = icmp ult i32 %3, 16\n br i1 %c, label %go, label %done\n\ngo:\n %5 = shl i32 %3, 1\n", - 1, - ); - let text = text.replacen( - "<2 x i64> zeroinitializer) #5\n ret void\n}", - "<2 x i64> zeroinitializer) #5\n br label %done\n\ndone:\n ret void\n}", - 1, - ); - assert!(text.contains("label %go") && text.contains("\ndone:\n")); - let Some(bc) = assemble_text("direct-divergent-matrix", &text) else { - return; - }; - compile(&bc, "matrix_thread_elements", p).expect("Direct"); - let variant = emulated(&bc, "matrix_thread_elements").expect("the variant"); - assert!(variant - .artifact() - .facts - .contains(&RuntimeFact::EmulatedSimdgroups)); - - // 32 KiB of shared memory: an arena of 32 KiB leaves nothing for the scratch. - assert_eq!(p.fields().limits.max_compute_shared_memory_size, 32 * 1024); - let Some(full) = arena_kernel(8192) else { - return; - }; - compile(&full, "barrier_k", p).expect("Direct"); - match emulated(&full, "barrier_k") { - Err(Error::Unsupported(u)) => { - assert_eq!(u.feature, Feature::ThreadgroupMemorySize); - let needs = format!("{:?}", u.needs); - assert!(needs.contains("required: 32896"), "{needs}"); - } - other => panic!("{other:?}"), - } - - // An arena of 31 KiB leaves the scratch of 8 simdgroups. - let Some(bc) = arena_kernel(31 * 256) else { - return; - }; - let state = bind_state(None); - let shape = state.shape(); - let base = pipeline(&dev, &bc, "barrier_k"); - let plan = base.plan(&dev, &shape).expect("plan"); - assert!(plan.instantiate_dispatch(&state, &threads(512)).is_ok()); - assert_eq!( - plan.dispatch_variant(&threads(260)), - Ok(emulated_key()), - "a partial simdgroup" - ); - let variant = dev - .compile_compute_pipeline( - &ComputePipelineDescriptor::new(StageSource::Compiled( - emulated(&bc, "barrier_k").expect("variant"), - )), - &Budget::standard(), - ) - .expect("variant pipeline"); - let vplan = variant.plan(&dev, &shape).expect("variant plan"); - assert!(vplan.instantiate_dispatch(&state, &threads(250)).is_ok()); - assert_memory_refused( - vplan.instantiate_dispatch(&state, &threads(260)), - 31 * 1024 + 9 * 128, - ); -} - -/// A `dispatchThreads` grid whose edge is a partial simdgroup runs whole on the variant, so its -/// interior is checked against the variant's limits, not the flattened tier's: those of a kernel -/// that runs a threadgroup deeper than `DEEP_THREADGROUP` as one row. On nvidia-rtx50-linux -/// (`Direct`, z at most 64), an interior of `[1, 1, 96]`, which the flattened pipeline runs alone, -/// asks for no variant, and a grid of `[1, 1, 100]` in threadgroups of `[1, 1, 96]` or `[1, 1, 64]` -/// asks for the variant, whose plan runs both regions: the flattened plan's check and the -/// variant's plan agree. -#[test] -fn a_mixed_dispatch_is_checked_against_the_variants_limits() { - let Some(bc) = assemble("simd_ops") else { - return; - }; - let dev = device("nvidia-rtx50-linux"); - assert_eq!( - dev.profile().fields().limits.max_compute_work_group_size[2], - 64 - ); - let (own, _) = typed_module(&bc, "simd_sum_k", dev.profile()).expect("simd_sum_k"); - assert_eq!(own.simd.1, Tier::Direct); - let budget = Budget::standard(); - let state = bind_state(None); - let shape = state.shape(); - let plan = pipeline(&dev, &bc, "simd_sum_k") - .plan(&dev, &shape) - .expect("plan"); - let f = Library::from_air(&bc) - .and_then(|lib| lib.function("simd_sum_k")) - .expect("kernel"); - let compiled = dev - .compile_function(&FunctionDescriptor::new(f), &emulated_inputs(), &budget) - .expect("variant"); - let vplan = dev - .compile_compute_pipeline( - &ComputePipelineDescriptor::new(StageSource::Compiled(compiled)), - &budget, - ) - .expect("variant pipeline") - .plan(&dev, &shape) - .expect("variant plan"); - let mixed = |z| Dispatch::Threads { - threads: [1, 1, 100], - threads_per_group: [1, 1, z], - }; - - let interior = Dispatch::Threads { - threads: [1, 1, 96], - threads_per_group: [1, 1, 96], - }; - assert_eq!(plan.dispatch_variant(&interior), Ok(VariantKey::new())); - assert!(plan.instantiate_dispatch(&state, &interior).is_ok()); - for z in [96, 64] { - let variant = plan.dispatch_variant(&mixed(z)); - let regions = (vplan.instantiate_dispatch(&state, &mixed(z))).map(|c| c.regions.len()); - assert_eq!((variant, regions), (Ok(emulated_key()), Ok(2)), "z {z}"); - } -} - /// The committed moltenvk-m3 profile (32-lane subgroups that require whole subgroups). fn direct() -> Device { device(DIRECT) @@ -2206,36 +1900,13 @@ attributes #0 = {{ convergent mustprogress nounwind willreturn }} ) } -/// Buffers 0 and 1 bound. -fn two_buffers() -> BindState { - let mut state = bind_state(None); - if let Some(table) = state.stages.get_mut(&Stage::Kernel) { - table.buffers.insert( - 1, - BoundBuffer::Buffer { - length: 4, - offset: 0, - gpu_address: 0x2_0000, - device_address: None, - attribute_stride: None, - }, - ); - } - state -} - /// A kernel whose only simdgroup semantics are the barrier its lockstep order took, between a /// read and a write of `b[gid]` that two threads of one simdgroup meet at only where the /// simdgroup spans two rows of its threadgroup (the shape of OpenCL C's `if (i < n) b[i] *= k`), -/// keeps the RTX 5080's `Direct` tier and records `RowLockstep`. A threadgroup of one row (1, 16 -/// or 48 threads, or a whole 32) asks for its one-row variant (`VariantKey::one_row`), and the -/// planned pipeline still runs one without whole subgroups: no emulated-simdgroups variant is -/// compiled, so none is announced. A threadgroup of two rows that is not whole subgroups still -/// asks for the emulated variant. The same kernel at `b[gid >> 1]` (two threads of a row meet) or -/// reading its simdgroup lane keeps every partial threadgroup on the emulated variant and a whole -/// one on its pinned pipeline. +/// keeps the RTX 5080's `Direct` tier and records `RowLockstep`. The same kernel at `b[gid >> 1]` +/// (two threads of a row meet) or reading its simdgroup lane does not record it. #[test] -fn a_row_of_a_lockstep_only_kernel_takes_one_compile() { +fn a_row_of_a_lockstep_only_kernel_records_its_row_lockstep() { let x = "%x = zext i32 %gid to i64"; let none = "%e = add i32 0, 0"; let kernels = [ @@ -2250,8 +1921,6 @@ fn a_row_of_a_lockstep_only_kernel_takes_one_compile() { ]; let dev = device("nvidia-rtx5080-laptop"); let p = dev.profile(); - let state = two_buffers(); - let shape = state.shape(); for (name, index, extra, rows) in kernels { let Some(bc) = assemble_text(name, &row_kernel(name, index, extra)) else { return; @@ -2268,53 +1937,6 @@ fn a_row_of_a_lockstep_only_kernel_takes_one_compile() { rows, "{name}" ); - let base = pipeline(&dev, &bc, name); - let plan = base.plan(&dev, &shape).expect("plan"); - for n in [1, 16, 48] { - let want = if rows { one_row_key() } else { emulated_key() }; - assert_eq!( - plan.dispatch_variant(&threads(n)), - Ok(want), - "{name} at {n}" - ); - } - for n in [32, 64] { - let want = if rows { - one_row_key() - } else { - VariantKey::new() - }; - assert_eq!( - plan.dispatch_variant(&threads(n)), - Ok(want), - "{name} at {n}" - ); - } - let two_rows = Dispatch::Threadgroups { - groups: [1, 1, 1], - threads_per_group: [8, 2, 1], - }; - assert_eq!( - plan.dispatch_variant(&two_rows), - Ok(emulated_key()), - "{name}" - ); - if rows { - let c = plan - .instantiate_dispatch(&state, &threads(16)) - .expect("one row on the planned pipeline"); - assert_eq!( - c.regions[0].stage_flags, - vk::PipelineShaderStageCreateFlags::empty() - ); - assert_eq!(c.regions[0].required_subgroup_size, Some(32)); - let c = plan - .instantiate_dispatch(&state, &threads(32)) - .expect("whole subgroups"); - assert!(c.regions[0] - .stage_flags - .contains(vk::PipelineShaderStageCreateFlags::REQUIRE_FULL_SUBGROUPS)); - } } } @@ -2485,11 +2107,11 @@ fn run_local(plan: &Plan, m: &TypedModule, local: [u32; 3], lanes: SubgroupSize) /// 32-lane subgroups makes that barrier a tangle barrier). Its own pipeline keeps the barrier, /// takes `CrossLane(BASIC)` and `Direct` (32 lanes pinned), records `RowLockstep`, and leaves /// Metal's words in a threadgroup 144 wide and 2 tall, which runs on it, the shared lane's word -/// included. A dispatch of one row (128 or 48 threads) asks for the one-row variant, which keeps -/// the threadgroup barrier the `@nb` pair takes, has no simdgroup barrier, no simd class and no -/// pinned subgroup, states `OneRow`, and leaves Metal's words at every width; its plan sends a -/// threadgroup of two rows back. The same kernel with a simdgroup sum keeps its pinned pipeline -/// for every threadgroup of whole simdgroups, one row or not. +/// included. Its one-row variant (`LoweringInputs::one_row`) keeps the threadgroup barrier the +/// `@nb` pair takes, has no simdgroup barrier, no simd class and no pinned subgroup, states +/// `OneRow`, and leaves Metal's words in a threadgroup of one row (128 or 48 threads) at every +/// width. The same kernel with a simdgroup sum keeps its pinned pipeline and records no +/// `RowLockstep`. #[test] fn a_one_row_dispatch_drops_the_lockstep_simdgroup_barriers() { let dev = device("intel-irisxe-rplp-anv"); @@ -2556,52 +2178,6 @@ fn a_one_row_dispatch_drops_the_lockstep_simdgroup_barriers() { } } - // The binder's choice. - let state = bind_state(None); - let shape = state.shape(); - let plan = pipeline(&dev, &bc, name).plan(&dev, &shape).expect("plan"); - let two_rows = Dispatch::Threadgroups { - groups: [1, 1, 1], - threads_per_group: wide, - }; - assert_eq!(plan.dispatch_variant(&threads(128)), Ok(one_row_key())); - assert_eq!(plan.dispatch_variant(&threads(48)), Ok(one_row_key())); - assert_eq!(plan.dispatch_variant(&two_rows), Ok(VariantKey::new())); - let f = Library::from_air(&bc) - .ok() - .and_then(|lib| lib.function(name).ok()) - .expect("kernel"); - let budget = Budget::standard(); - let compiled = dev - .compile_function( - &FunctionDescriptor::new(f), - &one_row_key().lowering_inputs(Stage::Kernel), - &budget, - ) - .expect("variant"); - let variant = dev - .compile_compute_pipeline( - &ComputePipelineDescriptor::new(StageSource::Compiled(compiled)), - &budget, - ) - .expect("variant pipeline"); - assert_eq!(variant.stage.required_subgroup_size, None); - let vplan = variant.plan(&dev, &shape).expect("variant plan"); - assert_eq!( - vplan.variant, - one_row_key(), - "the variant's plan states its key" - ); - assert_eq!(vplan.dispatch_variant(&threads(128)), Ok(one_row_key())); - assert!(vplan.instantiate_dispatch(&state, &threads(48)).is_ok()); - assert_eq!(vplan.dispatch_variant(&two_rows), Ok(VariantKey::new())); - assert_eq!( - vplan.instantiate_dispatch(&state, &two_rows), - Err(BindError::NeedsVariant { - variant: Box::new(VariantKey::new()) - }) - ); - // With a simdgroup operation of its own the kernel keeps its pinned pipeline. let summed = "row_tile_sum"; let Some(bc) = assemble_text( @@ -2617,12 +2193,6 @@ fn a_one_row_dispatch_drops_the_lockstep_simdgroup_barriers() { let (own, _) = typed_module(&bc, summed, p).unwrap_or_else(|e| panic!("{summed}: {e}")); assert_eq!(own.simd.1, Tier::Direct); assert!(!own.facts.contains(&RuntimeFact::RowLockstep)); - let plan = pipeline(&dev, &bc, summed) - .plan(&dev, &shape) - .expect("plan"); - for d in [threads(32), threads(128), two_rows] { - assert_eq!(plan.dispatch_variant(&d), Ok(VariantKey::new()), "{d:?}"); - } } /// A wave64-only device: the committed RDNA3 description, which reconverges maximally, with its @@ -2708,26 +2278,6 @@ attributes #0 = {{ convergent mustprogress nounwind willreturn }} ) } -/// A multisampled texture of four samples in `format` bound at texture 0 for reading, and -/// buffer 0. -fn samples_state(format: crate::metal::PixelFormat) -> BindState { - let mut state = bind_state(None); - let mut facts = - crate::bind::TextureFacts::new(crate::metal::TextureType::Type2DMultisample, format); - facts.sample_count = 4; - facts.usage = crate::metal::TextureUsage::SHADER_READ; - if let Some(table) = state.stages.get_mut(&Stage::Kernel) { - table.textures.insert( - 0, - crate::bind::BoundTexture::Texture { - facts, - resource_id: None, - }, - ); - } - state -} - /// A texel's samples read into a buffer, `out[(y * w + x) * n + s]` over `s < n` with `n` the /// texture's sample count (`wsm_samples`'s kernels, as the Metal compiler emits them): the store /// meets itself in a later iteration only where two threads of a simdgroup share a pixel, which @@ -2736,25 +2286,20 @@ fn samples_state(format: crate::metal::PixelFormat) -> BindState { /// `Cluster32` tier, and a multiple of 64 threads. In a row its threads' `x` differ and their `y` /// are equal, and each thread's cells `(y * w + x) * n + s` lie below the next pixel's, `s` a /// counter that starts at 0 below `n` (the branch before the loop tested `n != 0`, as a `select` -/// or an `and`) and leaves the loop on reaching it: the kernel records `RowLockstep`, and a -/// threadgroup of one row (1, 16, 32 or 48 threads) asks for its one-row variant, not the -/// emulated-simdgroups variant. Two rows of 16 still ask for the latter. Negative controls keep -/// every partial threadgroup on the variant: the row scaled by the width rather than by `n` -/// (cells of two pixels may meet), the latch testing the counter rather than the next value (the -/// body runs at `s == n`, the next pixel's first cell), and the loop entered without the `n != 0` -/// test (at `n == 0` every pixel writes cell 0). +/// or an `and`) and leaves the loop on reaching it: the kernel records `RowLockstep`. Negative +/// controls do not: the row scaled by the width rather than by `n` (cells of two pixels may meet), +/// the latch testing the counter rather than the next value (the body runs at `s == n`, the next +/// pixel's first cell), and the loop entered without the `n != 0` test (at `n == 0` every pixel +/// writes cell 0). #[test] fn a_texel_s_samples_in_a_row_need_no_emulated_simdgroups_on_wave64() { let compiler = "select i1 %iny, i1 %some, i1 false"; - let mut kernels: Vec<(String, Vec, crate::metal::PixelFormat, bool)> = Vec::new(); + let mut kernels: Vec<(String, Vec, bool)> = Vec::new(); let Some(fixture) = assemble("wsm_samples") else { return; }; - for (name, format) in [ - ("wsm_read_f", crate::metal::PixelFormat::RGBA32Float), - ("wsm_read_u", crate::metal::PixelFormat::R32Uint), - ] { - kernels.push((name.into(), fixture.clone(), format, true)); + for name in ["wsm_read_f", "wsm_read_u"] { + kernels.push((name.into(), fixture.clone(), true)); } for (name, guard, mult, tested, rows) in [ ("cells", compiler, "%n", "%next", true), @@ -2772,11 +2317,11 @@ fn a_texel_s_samples_in_a_row_need_no_emulated_simdgroups_on_wave64() { let Some(bc) = assemble_text(name, &cells_kernel(name, guard, mult, tested)) else { return; }; - kernels.push((name.into(), bc, crate::metal::PixelFormat::R32Uint, rows)); + kernels.push((name.into(), bc, rows)); } let dev = wave64(); let p = dev.profile(); - for (name, bc, format, rows) in kernels { + for (name, bc, rows) in kernels { let (own, _) = typed_module(&bc, &name, p).unwrap_or_else(|e| panic!("{name}: {e}")); assert_eq!(own.simd.1, Tier::Cluster32, "{name}"); assert!( @@ -2790,27 +2335,6 @@ fn a_texel_s_samples_in_a_row_need_no_emulated_simdgroups_on_wave64() { rows, "{name}" ); - let state = samples_state(format); - let plan = pipeline(&dev, &bc, &name) - .plan(&dev, &state.shape()) - .unwrap_or_else(|e| panic!("{name}: {e:?}")); - let want = if rows { one_row_key() } else { emulated_key() }; - for n in [1, 16, 32, 48] { - assert_eq!( - plan.dispatch_variant(&threads(n)), - Ok(want.clone()), - "{name} at {n}" - ); - } - let two_rows = Dispatch::Threadgroups { - groups: [1, 1, 1], - threads_per_group: [16, 2, 1], - }; - assert_eq!( - plan.dispatch_variant(&two_rows), - Ok(emulated_key()), - "{name}" - ); } } @@ -3045,3 +2569,113 @@ fn a_kernel_without_a_lockstep_pair_records_no_access_order_note() { ordered.precision ); } + +/// Through the public API on `DIRECT`, a kernel whose simdgroups run on whole subgroups compiled +/// under the emulated-simdgroups key is another function and another pipeline, which states the +/// variant as its mechanism for `EmulatedSimdgroups` and runs with no subgroup requirement and no +/// stage flags. +#[test] +fn the_emulated_simdgroups_variant_compiles_without_a_subgroup_requirement() { + let Some(bc) = assemble("simd_ops") else { + return; + }; + let dev = direct(); + let budget = Budget::standard(); + let f = Library::from_air(&bc) + .and_then(|lib| lib.function("simd_sum_k")) + .expect("kernel"); + let fd = FunctionDescriptor::new(f); + let base = pipeline(&dev, &bc, "simd_sum_k"); + let key = emulated_key(); + let compiled = dev + .compile_function(&fd, &key.lowering_inputs(Stage::Kernel), &budget) + .expect("variant"); + assert_ne!( + *compiled.key(), + dev.function_compile_key(&fd, &LoweringInputs::new()) + ); + let variant = dev + .compile_compute_pipeline( + &ComputePipelineDescriptor::new(StageSource::Compiled(compiled)), + &budget, + ) + .expect("variant pipeline"); + assert_ne!(variant.key, base.key); + assert!(variant + .dependencies + .iter() + .any(|d| d.fact == RuntimeFact::EmulatedSimdgroups && d.mechanism == Mechanism::Variant)); + assert_eq!(variant.stage.required_subgroup_size, None); + assert!(variant.stage.stage_flags.is_empty()); +} + +/// The emulated tier's own limits stay refusals in the emulated-simdgroups variant. A matrix +/// multiply-add in a divergent block compiles in both; a kernel whose threadgroup memory leaves no +/// room for one simdgroup's scratch is `ThreadgroupMemorySize` at the variant's compile; and one +/// that leaves room for some states as its maximum the threads whose scratch fits. +#[test] +fn the_emulated_tiers_limits_stay_refused_for_partial_simdgroups() { + let dev = direct(); + let p = dev.profile(); + let emulated = |bc: &[u8], kernel: &str| { + let f = Library::from_air(bc) + .and_then(|lib| lib.function(kernel)) + .expect("kernel"); + dev.compile_function( + &FunctionDescriptor::new(f), + &emulated_inputs(), + &Budget::standard(), + ) + }; + + let text = std::fs::read_to_string(engine_dir().join("simd_matrix.ll")).expect("read"); + let text = text.replacen( + " %5 = shl i32 %3, 1\n", + " %c = icmp ult i32 %3, 16\n br i1 %c, label %go, label %done\n\ngo:\n %5 = shl i32 %3, 1\n", + 1, + ); + let text = text.replacen( + "<2 x i64> zeroinitializer) #5\n ret void\n}", + "<2 x i64> zeroinitializer) #5\n br label %done\n\ndone:\n ret void\n}", + 1, + ); + assert!(text.contains("label %go") && text.contains("\ndone:\n")); + let Some(bc) = assemble_text("direct-divergent-matrix", &text) else { + return; + }; + compile(&bc, "matrix_thread_elements", p).expect("Direct"); + let variant = emulated(&bc, "matrix_thread_elements").expect("the variant"); + assert!(variant + .artifact() + .facts + .contains(&RuntimeFact::EmulatedSimdgroups)); + + // 32 KiB of shared memory: an arena of 32 KiB leaves nothing for the scratch. + assert_eq!(p.fields().limits.max_compute_shared_memory_size, 32 * 1024); + let Some(full) = arena_kernel(8192) else { + return; + }; + compile(&full, "barrier_k", p).expect("Direct"); + match emulated(&full, "barrier_k") { + Err(Error::Unsupported(u)) => { + assert_eq!(u.feature, Feature::ThreadgroupMemorySize); + let needs = format!("{:?}", u.needs); + assert!(needs.contains("required: 32896"), "{needs}"); + } + other => panic!("{other:?}"), + } + + // An arena of 31 KiB leaves the scratch of 8 simdgroups. + let Some(bc) = arena_kernel(31 * 256) else { + return; + }; + let variant = dev + .compile_compute_pipeline( + &ComputePipelineDescriptor::new(StageSource::Compiled( + emulated(&bc, "barrier_k").expect("variant"), + )), + &Budget::standard(), + ) + .expect("variant pipeline"); + assert_eq!(variant.metal_info.max_total_threads_per_threadgroup, 256); +} diff --git a/crates/metal2vulkan/src/tests/engine_simd_unit_axes.rs b/crates/metal2vulkan/src/tests/engine_simd_unit_axes.rs deleted file mode 100644 index 6ff1858d7..000000000 --- a/crates/metal2vulkan/src/tests/engine_simd_unit_axes.rs +++ /dev/null @@ -1,373 +0,0 @@ -//! A kernel's unit-axes variant (`VariantKey::unit_axes`, `LoweringInputs::unit_axes`). -//! -//! In a threadgroup of one thread along an axis (Metal's `threads_per_threadgroup` 1 there), every -//! thread's position along it is 0 in its threadgroup and its threadgroup's in the grid, so a -//! branch on it is uniform across the threadgroup. A kernel whose emulated simdgroups are walked -//! predicated only because such a position steers a synchronization states the axes whose variant -//! relieves the walk (`RuntimeFact::UnitAxes`), which its plan states (`unit_relief`). The -//! authored kernel here sums its -//! simdgroup in a loop whose trip count reads `thread_position_in_grid.y` (and, for the control, -//! `.x`). Each module runs on the CPU interpreter at 8, 16 and 32 subgroup lanes in both -//! scheduling orders, under Vulkan's barrier rule. No GPU is used. -//! -//! `llvm-as` assembles the kernels; a missing tool skips visibly. - -use std::collections::BTreeMap; - -use crate::bind::{BindState, BoundBuffer, Dispatch, StageTable}; -use crate::budget::Budget; -use crate::cache::VariantKey; -use crate::device::subgroup::Tier; -use crate::device::{Device, DevicePolicy}; -use crate::error::BindError; -use crate::library::Library; -use crate::lower::select::Plan; -use crate::pipeline::facts::RuntimeFact; -use crate::pipeline::sym::{Axis, ResourceKind, ResourceSlot, SpecKey, Stage}; -use crate::pipeline::testing::{ - llvm_assemble, typed_module, typed_module_with, AssembleError, Scratch, -}; -use crate::pipeline::{ - ComputePipeline, ComputePipelineDescriptor, FunctionDescriptor, LoweringInputs, StageSource, -}; -use crate::spirv::interp::{ - run, BarrierRule, Buffer, Config, InterpError, Order, Resources, SubgroupSize, TrapKind, -}; -use crate::spirv::ir::TypedModule; - -/// `kernel void name(device uint *out [[buffer(0)]], uint3 gid [[thread_position_in_grid]], -/// uint t [[thread_index_in_threadgroup]])`: with `g = gid[axis]`, a loop of `(g & 3) + 1` -/// iterations, each adding `simd_sum(t + i)`, then `out[t + N gid.y] = acc`, `N` the -/// threadgroup's threads (a constant here: `n`). -fn kernel(name: &str, axis: u32, n: u32) -> String { - format!( - r#"target datalayout = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32" -target triple = "air64_v28-apple-macosx26.0.0" - -define void @{name}(ptr addrspace(1) %out, <3 x i32> %gid, i32 %t) #0 {{ -entry: - %g = extractelement <3 x i32> %gid, i64 {axis} - %k = and i32 %g, 3 - %trip = add i32 %k, 1 - br label %loop -loop: - %i = phi i32 [ 0, %entry ], [ %i1, %loop ] - %acc = phi i32 [ 0, %entry ], [ %acc1, %loop ] - %v = add i32 %t, %i - %s = tail call i32 @air.simd_sum.u.i32(i32 %v) - %acc1 = add i32 %acc, %s - %i1 = add i32 %i, 1 - %more = icmp ult i32 %i1, %trip - br i1 %more, label %loop, label %done -done: - %y = extractelement <3 x i32> %gid, i64 1 - %row = mul i32 %y, {n} - %at32 = add i32 %row, %t - %at = zext i32 %at32 to i64 - %p = getelementptr inbounds i32, ptr addrspace(1) %out, i64 %at - store i32 %acc1, ptr addrspace(1) %p, align 4 - ret void -}} - -declare i32 @air.simd_sum.u.i32(i32) #1 - -attributes #0 = {{ convergent mustprogress nounwind willreturn }} -attributes #1 = {{ convergent mustprogress nounwind willreturn memory(none) }} - -!air.kernel = !{{!0}} -!air.version = !{{!6}} -!air.language_version = !{{!7}} - -!0 = !{{ptr @{name}, !1, !2}} -!1 = !{{}} -!2 = !{{!3, !4, !5}} -!3 = !{{i32 0, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"out"}} -!4 = !{{i32 1, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint3", !"air.arg_name", !"gid"}} -!5 = !{{i32 2, !"air.thread_index_in_threadgroup", !"air.arg_type_name", !"uint", !"air.arg_name", !"t"}} -!6 = !{{i32 2, i32 8, i32 0}} -!7 = !{{!"Metal", i32 4, i32 0, i32 0}} -"# - ) -} - -/// The threadgroup every run takes: 8 x 1 x 8, two simdgroups, one thread along `y`. -const LOCAL: [u32; 3] = [8, 1, 8]; -/// The threadgroups along `y` a run dispatches: trip counts 1 to 4 on the `y` kernel. -const ROWS: u32 = 4; -/// `RuntimeFact::UnitAxes`'s `relief` of a kernel whose loop reads `y`: the masks with `y` -/// (`y`, `x | y`, `y | z`, `x | y | z`), bit `m - 1` for mask `m`. -const RELIEF_Y: u8 = 1 << 1 | 1 << 2 | 1 << 5 | 1 << 6; -/// The same for a loop that reads `x`: the masks with `x`. -const RELIEF_X: u8 = 1 | 1 << 2 | 1 << 4 | 1 << 6; - -fn assemble(name: &str, text: &str) -> Option> { - let scratch = Scratch::new(&format!("m2v-unit-axes-{name}")); - let path = scratch.path().join("kernel.ll"); - std::fs::write(&path, text).expect("write"); - match llvm_assemble(&path) { - Ok(b) => Some(b), - Err(AssembleError::Missing(why)) => { - eprintln!("SKIPPED: {why}"); - None - } - Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected {name}: {why}"), - } -} - -fn lavapipe() -> Device { - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../metal2vulkan-validation/profiles/lavapipe.json"); - let text = std::fs::read_to_string(path).expect("profile"); - let desc = - crate::device::DeviceDescription::from_khronos_json(&text, None).expect("description"); - Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device") -} - -/// The unit axes `plan` states, with their relief (`RuntimeFact::UnitAxes`). -fn unit_axes(plan: &Plan) -> Option<(u8, u8)> { - plan.facts.iter().find_map(|fact| match *fact { - RuntimeFact::UnitAxes { axes, relief } => Some((axes, relief)), - _ => None, - }) -} - -/// The module of `name` under unit axes `axes`. -fn module(bc: &[u8], name: &str, dev: &Device, axes: u8) -> (Plan, TypedModule) { - let mut inputs = LoweringInputs::new(); - inputs.unit_axes = axes; - match axes { - 0 => typed_module(bc, name, dev.profile()), - _ => typed_module_with(bc, name, dev.profile(), &inputs), - } - .unwrap_or_else(|e| panic!("{name} under {axes}: {e}")) -} - -/// Buffer 0 after `ROWS` threadgroups of `local` along `y` ran `m` (planned as `plan`) with -/// `lanes`-wide subgroups, identical in both scheduling orders; or why a run did not complete. -fn run_rows( - plan: &Plan, - m: &TypedModule, - local: [u32; 3], - lanes: SubgroupSize, -) -> Result, InterpError> { - let mut spec = BTreeMap::new(); - for (a, v) in [Axis::X, Axis::Y, Axis::Z].into_iter().zip(local) { - spec.insert(SpecKey::LocalSize(a), u64::from(v)); - } - let n: u32 = local.iter().product(); - spec.insert(SpecKey::FlatLocalSize, u64::from(n)); - let res = Resources { - buffers: vec![Buffer { - slot: Some(ResourceSlot { - stage: Stage::Kernel, - kind: ResourceKind::Buffer, - index: 0, - }), - address: None, - bytes: vec![0; (n * ROWS * local[1]) as usize * 4], - }], - push: vec![0u8; plan.push.push_range.map_or(0, |(_, end)| end as usize)], - spec, - }; - let mut outs = Vec::new(); - for order in [Order::Forward, Order::Reverse] { - let cfg = Config { - workgroups: [1, ROWS, 1], - subgroup: lanes, - order, - barriers: BarrierRule::Vulkan, - ..Config::default() - }; - outs.push(run(m, &cfg, res.clone())?.buffers.swap_remove(0)); - } - assert_eq!(outs[0], outs[1], "order independent"); - let bytes = outs.swap_remove(0); - Ok(bytes - .as_chunks::<4>() - .0 - .iter() - .map(|w| u32::from_le_bytes(*w)) - .collect()) -} - -/// Metal's words for `LOCAL` threadgroups of the kernel whose loop reads `axis`: thread `t` of -/// threadgroup `w` runs `(g & 3) + 1` iterations, `g` its grid position on the axis (`t mod 8` -/// on `x`, `w` on `y`), each adding the sum of `t' + i` over the threads `t'` of its simdgroup -/// (32 consecutive threads) still in the loop. -fn expected(axis: u32) -> Vec { - let n: u32 = LOCAL.iter().product(); - let trip = |t: u32, w: u32| match axis { - 0 => ((t % LOCAL[0]) & 3) + 1, - _ => (w & 3) + 1, - }; - let mut words = Vec::new(); - for w in 0..ROWS { - for t in 0..n { - let group = (t / 32) * 32..((t / 32) * 32 + 32).min(n); - let acc = (0..trip(t, w)) - .map(|i| { - group - .clone() - .filter(|&u| trip(u, w) > i) - .map(|u| u + i) - .sum::() - }) - .sum(); - words.push(acc); - } - } - words -} - -fn pipeline(dev: &Device, bc: &[u8], name: &str, key: &VariantKey) -> ComputePipeline { - let f = Library::from_air(bc) - .ok() - .and_then(|lib| lib.function(name).ok()) - .expect("kernel"); - let budget = Budget::standard(); - let compiled = dev - .compile_function( - &FunctionDescriptor::new(f), - &key.lowering_inputs(Stage::Kernel), - &budget, - ) - .unwrap_or_else(|e| panic!("{name}: {e}")); - dev.compile_compute_pipeline( - &ComputePipelineDescriptor::new(StageSource::Compiled(compiled)), - &budget, - ) - .unwrap_or_else(|e| panic!("{name}: {e}")) -} - -fn bind_state() -> BindState { - let mut table = StageTable::default(); - table.buffers.insert( - 0, - BoundBuffer::Buffer { - length: 4096, - offset: 0, - gpu_address: 0x1_0000, - device_address: None, - attribute_stride: None, - }, - ); - let mut state = BindState::default(); - state.stages.insert(Stage::Kernel, table); - state -} - -fn groups(threads_per_group: [u32; 3]) -> Dispatch { - Dispatch::Threadgroups { - groups: [1, ROWS, 1], - threads_per_group, - } -} - -fn keyed(axes: u8) -> VariantKey { - let mut key = VariantKey::new(); - key.unit_axes = axes; - key -} - -/// The emulated walk of a kernel whose simdgroup sum sits in a loop steered by -/// `thread_position_in_grid.y` is predicated, and its module states the masks of unit axes that -/// relieve it (every mask with `y`). Compiled for unit `y` it is walked unpredicated, states its -/// axes, and gives Metal's words in threadgroups of one thread along `y` at every width, the -/// same as the predicated module's; in a threadgroup of two threads along `y` it is not Metal's -/// kernel (two trip counts meet the exchange's barrier: Vulkan's rule traps), which its plan -/// never runs, sending such a dispatch back to the plain variant. Unit `x` relieves nothing of -/// it, and the same kernel steered by `.x` is relieved by no mask without `x`. -#[test] -fn a_unit_axis_relieves_the_predicated_walk() { - let dev = lavapipe(); - let (y, x) = ("unit_axes_y", "unit_axes_x"); - let n: u32 = LOCAL.iter().product(); - let Some(ybc) = assemble(y, &kernel(y, 1, n)) else { - return; - }; - let Some(xbc) = assemble(x, &kernel(x, 0, n)) else { - return; - }; - let lanes = [SubgroupSize::W8, SubgroupSize::W16, SubgroupSize::W32]; - - // The kernel's own module: predicated, relieved by every mask with `y`. - let (base, bm) = module(&ybc, y, &dev, 0); - assert_eq!(base.simd.1, Tier::Emulated); - assert!( - base.families.simd.predication.is_some(), - "walked predicated" - ); - assert_eq!(unit_axes(&base), Some((0, RELIEF_Y))); - // Its variant for unit `y`: unpredicated, stating its axes. - let (unit, um) = module(&ybc, y, &dev, 0b010); - assert_eq!(unit.simd.1, Tier::Emulated); - assert!( - unit.families.simd.predication.is_none(), - "walked unpredicated" - ); - assert_eq!(unit_axes(&unit), Some((0b010, 0))); - let want = expected(1); - for w in lanes { - assert_eq!(run_rows(&base, &bm, LOCAL, w).as_ref(), Ok(&want), "{w:?}"); - assert_eq!(run_rows(&unit, &um, LOCAL, w).as_ref(), Ok(&want), "{w:?}"); - } - // Two threads along `y`: the variant's barrier is met by two trip counts. - match run_rows(&unit, &um, [8, 2, 4], SubgroupSize::W32) { - Err(InterpError::Trap(trap)) => assert_eq!(trap.kind, TrapKind::NonUniformBarrier), - other => panic!("the unit-y module at two threads along y: {other:?}"), - } - // Unit `x` relieves nothing. - let (other, _) = module(&ybc, y, &dev, 0b001); - assert!(other.families.simd.predication.is_some(), "unit x"); - assert_eq!(unit_axes(&other), Some((0b001, 0))); - - // The kernel steered by `x`: no relief for unit `y`. - let (xbase, xm) = module(&xbc, x, &dev, 0); - assert!(xbase.families.simd.predication.is_some()); - assert_eq!(unit_axes(&xbase), Some((0, RELIEF_X))); - let (xunit, _) = module(&xbc, x, &dev, 0b010); - assert!(xunit.families.simd.predication.is_some(), "x under unit y"); - let want = expected(0); - for w in lanes { - assert_eq!(run_rows(&xbase, &xm, LOCAL, w).as_ref(), Ok(&want), "{w:?}"); - } - - // The binder's plan. - let state = bind_state(); - let shape = state.shape(); - let plan = pipeline(&dev, &ybc, y, &VariantKey::new()) - .plan(&dev, &shape) - .expect("plan"); - assert_eq!( - plan.compute.as_ref().map(|c| c.local.unit_relief), - Some(RELIEF_Y) - ); - let row = groups(LOCAL); - assert_eq!(plan.dispatch_variant(&row), Ok(VariantKey::new())); - // The plain variant runs the dispatch, as it ran before. - assert!(plan.instantiate_dispatch(&state, &row).is_ok()); - - // The variant's plan: runs threadgroups of one thread along `y` only. - let variant = pipeline(&dev, &ybc, y, &keyed(0b010)); - assert!(variant.dependencies.iter().any(|d| d.fact - == RuntimeFact::UnitAxes { - axes: 0b010, - relief: 0 - })); - let vplan = variant.plan(&dev, &shape).expect("variant plan"); - assert_eq!( - vplan.variant, - keyed(0b010), - "the variant's plan states its key" - ); - assert_eq!(vplan.dispatch_variant(&row), Ok(keyed(0b010))); - assert!(vplan.instantiate_dispatch(&state, &row).is_ok()); - let two = groups([8, 2, 4]); - assert_eq!(vplan.dispatch_variant(&two), Ok(VariantKey::new())); - assert_eq!( - vplan.instantiate_dispatch(&state, &two), - Err(BindError::NeedsVariant { - variant: Box::new(VariantKey::new()) - }) - ); -} diff --git a/crates/metal2vulkan/src/tests/engine_sparse_unmapped.rs b/crates/metal2vulkan/src/tests/engine_sparse_unmapped.rs index 4f3faf018..cff8a5c5e 100644 --- a/crates/metal2vulkan/src/tests/engine_sparse_unmapped.rs +++ b/crates/metal2vulkan/src/tests/engine_sparse_unmapped.rs @@ -220,63 +220,30 @@ fn gather(component: u32) -> String { format!("@air.gather_texture_2d.v4f32(ptr addrspace(1) %t, ptr addrspace(2) @__air_sampler_state, <2 x float> %uv, i1 true, <2 x i32> zeroinitializer, i32 {component}, i32 0)") } -/// The `ConstantLanes` word of an `R32Float` texture made with `swizzle`. +/// The `ConstantLanes` word of an `R32Float` texture made with `swizzle`: bit `lane` (0 red to 3 +/// alpha) where Metal reads the lane as a constant (a channel the format lacks, or a `Zero` or `One` +/// swizzle), and bit `CONSTANT_ONES + lane` where that constant is 1. fn r32_lanes(swizzle: TextureSwizzleChannels) -> u64 { let present = crate::metal::format::channels(PixelFormat::R32Float).expect("channels"); - u64::from(crate::metal::sampler::constant_lanes(present, swizzle)) -} - -/// The lanes Metal reads as constants are the channels a format lacks (red, green and blue 0, -/// alpha 1) and the `Zero` and `One` swizzles, through the texture's swizzle; a format holding -/// every channel has none under its own swizzle; a depth format states none. -#[test] -fn the_constant_lanes_are_the_channels_a_format_lacks_through_its_swizzle() { - use crate::metal::format::channels; - use crate::metal::sampler::constant_lanes; - use TextureSwizzle as T; - let s = TextureSwizzleChannels::new; - let id = TextureSwizzleChannels::DEFAULT; - let lanes = |pf: PixelFormat, sw: TextureSwizzleChannels| { - constant_lanes(channels(pf).expect("channels"), sw) - }; - // R8: green and blue read 0, alpha 1. - assert_eq!(lanes(PixelFormat::R8Unorm, id), 0b1110 | 0b1000 << 4); - assert_eq!(lanes(PixelFormat::R32Float, id), 0b1110 | 0b1000 << 4); - assert_eq!(lanes(PixelFormat::BC4RUnorm, id), 0b1110 | 0b1000 << 4); - // RG: blue 0, alpha 1; RGB: alpha 1. - assert_eq!(lanes(PixelFormat::RG8Unorm, id), 0b1100 | 0b1000 << 4); - assert_eq!(lanes(PixelFormat::B5G6R5Unorm, id), 0b1000 | 0b1000 << 4); - assert_eq!(lanes(PixelFormat::ETC2RGB8, id), 0b1000 | 0b1000 << 4); - // A8: red, green and blue 0. - assert_eq!(lanes(PixelFormat::A8Unorm, id), 0b0111); - // Every channel: none, but a swizzle's constants. - assert_eq!(lanes(PixelFormat::RGBA8Unorm, id), 0); - assert_eq!( - lanes( - PixelFormat::RGBA8Unorm, - s(T::Red, T::Green, T::Zero, T::One) - ), - 0b1100 | 0b1000 << 4 - ); - // Through a swizzle: each lane takes its source's constant. - assert_eq!( - lanes( - PixelFormat::R8Unorm, - s(T::Alpha, T::Alpha, T::Alpha, T::Alpha) - ), - 0b1111 | 0b1111 << 4 - ); - assert_eq!( - lanes(PixelFormat::R8Unorm, s(T::Alpha, T::Red, T::Green, T::Blue)), - 0b1101 | 0b0001 << 4 - ); - assert_eq!( - lanes(PixelFormat::A8Unorm, s(T::Alpha, T::Red, T::One, T::Alpha)), - 0b0110 | 0b0100 << 4 - ); - assert_eq!(channels(PixelFormat::Depth32Float), None); - assert_eq!(channels(PixelFormat::Stencil8), None); - assert_eq!(channels(PixelFormat::Invalid), None); + let lanes = [swizzle.red, swizzle.green, swizzle.blue, swizzle.alpha]; + let mut word = 0; + for (lane, source) in (0u32..).zip(lanes) { + let constant = match source { + TextureSwizzle::Zero => Some(false), + TextureSwizzle::One => Some(true), + TextureSwizzle::Red => (!present[0]).then_some(false), + TextureSwizzle::Green => (!present[1]).then_some(false), + TextureSwizzle::Blue => (!present[2]).then_some(false), + TextureSwizzle::Alpha => (!present[3]).then_some(true), + }; + if let Some(one) = constant { + word |= 1 << lane; + if one { + word |= 1 << (crate::metal::sampler::CONSTANT_ONES + lane); + } + } + } + word } /// On the interpreter: a nearest, clamp-to-edge pixel sampler's fetch of a 2x2 sparse `R32Float` diff --git a/crates/metal2vulkan/src/tests/engine_srgb_decode.rs b/crates/metal2vulkan/src/tests/engine_srgb_decode.rs index 0e721ca18..1909460b3 100644 --- a/crates/metal2vulkan/src/tests/engine_srgb_decode.rs +++ b/crates/metal2vulkan/src/tests/engine_srgb_decode.rs @@ -14,29 +14,21 @@ //! //! `llvm-as` assembles the kernels; without it the tests skip visibly. -use std::collections::BTreeSet; use std::sync::atomic::{AtomicU64, Ordering}; -use crate::bind::{ - BindState, BoundBuffer, BoundTexture, ImageSource, StageTable, TextureFacts, WriteSource, -}; -use crate::budget::{Budget, SPIRV_WORDS}; -use crate::device::{Device, DeviceDescription, DevicePolicy, FormatUsage}; -use crate::library::{FunctionConstantValues, Library}; +use crate::budget::SPIRV_WORDS; +use crate::device::DevicePolicy; +use crate::library::FunctionConstantValues; use crate::lower::select::LowerInputs; use crate::metal::format::bound_texel_format; -use crate::metal::texel_format::srgb_twin_on; -use crate::metal::{self, PixelFormat, TextureType}; +use crate::metal::PixelFormat; use crate::pipeline::compile::{compile_bitcode, EntryRef}; use crate::pipeline::facts::RuntimeFact; use crate::pipeline::sym::{SlotClass, SlotRef, SpecKey, Stage}; use crate::pipeline::testing::{ link_and_validate, llvm_assemble, meter, profile, typed_module_with, AssembleError, }; -use crate::pipeline::{ - ComputePipeline, ComputePipelineDescriptor, FunctionDescriptor, PrecisionNote, SpecializedNote, - StageSource, -}; +use crate::pipeline::{PrecisionNote, SpecializedNote}; use crate::spirv::testing::committed_profiles; const HEADER: &str = "target datalayout = \"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32\"\ntarget triple = \"air64_v28-apple-macosx26.0.0\"\n\n"; @@ -228,78 +220,13 @@ fn m3() -> crate::device::profile::DeviceProfile { profile("moltenvk-m3", DevicePolicy::RESIDENT_TABLES).expect("profile") } -/// The plan of a slot bound with a swizzle in an 8-bit sRGB format the device holds as its UNORM -/// twin names the slot in `VariantKey::swizzled_storage`, and its views take no swizzle, exactly -/// where the swizzle moves a code between a color lane and alpha (the function decodes, then -/// swizzles); a swizzle among the color lanes or to constants keeps the views' component mapping, -/// which reads the same. A format the device samples is decoded by its sRGB view before the -/// view's component mapping swizzles, so its views take every swizzle. -#[test] -fn an_srgb_swizzle_across_alpha_swizzles_in_the_function_on_a_twin() { - use crate::metal::{TextureSwizzle as S, TextureSwizzleChannels}; - let Some(bc) = assemble("read float", &kernel(Access::Read, false)) else { - return; - }; - let channels = |red, green, blue, alpha| TextureSwizzleChannels { - red, - green, - blue, - alpha, - }; - let cases = [ - (channels(S::Alpha, S::Blue, S::Green, S::Red), true), - (channels(S::Red, S::Green, S::Blue, S::Red), true), - (channels(S::Alpha, S::Green, S::Blue, S::Alpha), true), - (channels(S::Blue, S::Green, S::Red, S::Alpha), false), - (channels(S::Red, S::Red, S::Red, S::One), false), - (channels(S::Zero, S::Green, S::One, S::Alpha), false), - ]; - let (mut planned, mut swizzled) = (0, 0); - for (stem, dev) in devices() { - let plain = pipeline(&dev, &bc, &inputs(false)); - for pf in [PixelFormat::RGBA8UnormSRGB, PixelFormat::RG8UnormSRGB] { - let twin = srgb_twin_on(pf, dev.profile()); - for (swizzle, crosses) in cases { - let what = format!("{stem} {pf:?} {swizzle:?}"); - let mut state = state(Some(pf)); - if let Some(BoundTexture::Texture { facts, .. }) = state - .stages - .get_mut(&Stage::Kernel) - .and_then(|t| t.textures.get_mut(&0)) - { - facts.swizzle = swizzle; - } - let Ok(plan) = plain.plan(&dev, &state.shape()) else { - continue; - }; - let in_function = crosses && twin; - assert_eq!( - plan.variant.swizzled_storage.contains(&TEXTURE), - in_function, - "{what}" - ); - let views = slot_views(&plan, TEXTURE); - assert!(!views.is_empty(), "{what}"); - for v in views { - assert_eq!(v.shader_swizzle, in_function, "{what}"); - } - planned += 1; - swizzled += usize::from(in_function); - } - } - } - assert!(planned > 0, "no committed profile planned the texture"); - assert!(swizzled > 0, "no committed profile holds a twin"); -} - /// Every access of an 8-bit sRGB texture slot records `RuntimeFact::SrgbTexture`. Without the /// variant every one of them (a read, a fetch, a nearest, linear, mipmapped or bicubic sample, a /// gather, a runtime sampler's sample) reads the device's own decode and declares no Metal table: /// on lavapipe and MoltenVK it notes `PrecisionNote::SrgbTexelDecode` under the bound format's /// class (an `RGBA8Unorm_sRGB` or ASTC sRGB texture's, not an `RGBA8Unorm` one's). Under the /// variant every access decodes what the twin's view reads by the MSL transfer through the -/// device's `Pow`, declaring no table, and notes `SrgbTexelDecode` outright, on both devices. No -/// access records `PrecisionNote::HalfSampleFilter` or `PrecisionNote::FloatSampleFilter`. Every +/// device's `Pow`, declaring no table, and notes `SrgbTexelDecode` outright, on both devices. Every /// form validates on both devices. #[test] fn the_device_decodes_every_access_and_a_twin_takes_its_pow() { @@ -359,12 +286,6 @@ fn the_device_decodes_every_access_and_a_twin_takes_its_pow() { assert_eq!(noted(pf), !variant, "{what} {pf:?}"); } assert!(!noted(PixelFormat::RGBA8Unorm), "{what}"); - for note in [ - PrecisionNote::FloatSampleFilter, - PrecisionNote::HalfSampleFilter, - ] { - assert!(!plan.precision.contains(¬e), "{what}: {note:?}"); - } let a = compile_bitcode( &bc, EntryRef::Name("k"), @@ -593,417 +514,3 @@ fn every_srgb_form_validates() { } // ---- The binder ------------------------------------------------------------------------------- - -fn devices() -> Vec<(String, Device)> { - let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../metal2vulkan-validation/profiles"); - let mut out = Vec::new(); - for e in std::fs::read_dir(&dir).expect("profiles") { - let path = e.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("profile"); - let desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); - out.push(( - stem, - Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device"), - )); - } - out.sort_by(|a, b| a.0.cmp(&b.0)); - out -} - -/// The kernel compiled into a compute pipeline under `inputs`. -fn pipeline(dev: &Device, bc: &[u8], inputs: &LowerInputs) -> ComputePipeline { - let lib = Library::from_air(bc).expect("library"); - let f = lib.function("k").expect("function"); - let compiled = dev - .compile_function(&FunctionDescriptor::new(f), inputs, &Budget::standard()) - .expect("compile"); - dev.compile_compute_pipeline( - &ComputePipelineDescriptor::new(StageSource::Compiled(compiled)), - &Budget::standard(), - ) - .expect("pipeline") -} - -/// A kernel's state: texture slot 0 bound in `pf` (or nothing), buffer 0 bound. -fn state(pf: Option) -> BindState { - let mut t = StageTable::default(); - if let Some(pf) = pf { - let mut facts = TextureFacts::new(TextureType::Type2D, pf); - facts.usage = metal::TextureUsage::SHADER_READ; - t.textures.insert( - 0, - BoundTexture::Texture { - facts, - resource_id: None, - }, - ); - } - t.buffers.insert( - 0, - BoundBuffer::Buffer { - length: 4096, - offset: 0, - gpu_address: 0x1_0000, - device_address: None, - attribute_stride: None, - }, - ); - let mut s = BindState::default(); - s.stages.insert(Stage::Kernel, t); - s -} - -/// The image views `plan` writes for texture slot `slot`, through a texture or a combined write. -fn slot_views(plan: &crate::bind::BindingPlan, slot: SlotRef) -> Vec { - plan.descriptors - .iter() - .filter_map(|d| match &d.source { - WriteSource::Texture { slot: s, view } if *s == slot => Some(*view), - WriteSource::CombinedImageSampler { - image: ImageSource::Texture { slot: s, view }, - .. - } if *s == slot => Some(*view), - _ => None, - }) - .collect() -} - -/// A slot bound in an 8-bit sRGB format joins the plan's variant exactly where the device holds -/// the format as its UNORM twin (`metal::texel_format::srgb_twin_on`), from the device's format -/// features alone. Where the device samples the format the slot joins nothing, every binding of -/// the slot views the image in that sRGB format (the device decodes it), and the pipeline notes -/// `PrecisionNote::SrgbTexelDecode` under the bound format, which -/// an `RGBA8Unorm` texture does not take. Where the device holds the twin, the variant's pipeline -/// plans the same key, every binding of the slot views the twin, and every access (the device's -/// codes or its filter of them, decoded by the device's transfer) notes `SrgbTexelDecode`, -/// outright; each variant validates. A device that samples neither form refuses the format. Every committed profile, for -/// a read, a nearest sample and a runtime sampler's sample. -#[test] -fn a_slot_bound_in_srgb_joins_the_variant_only_where_the_device_holds_its_twin() { - use crate::device::requirements::FormatUsage as U; - let forms = [ - ("read", Access::Read), - ("nearest", Access::Sample(sampler_words(0, 0, false))), - ("runtime", Access::Runtime), - ]; - let (mut decoded, mut twinned) = (0, 0); - for (name, access) in forms { - let Some(bc) = assemble(name, &kernel(access, false)) else { - return; - }; - for (stem, dev) in devices() { - let plain = pipeline(&dev, &bc, &inputs(false)); - for pf in [ - PixelFormat::RGBA8UnormSRGB, - PixelFormat::BGRA8UnormSRGB, - PixelFormat::R8UnormSRGB, - PixelFormat::RG8UnormSRGB, - ] { - let what = format!("{name} on {stem} {pf:?}"); - let shape = state(Some(pf)).shape(); - let sampled = - crate::metal::format::vk_format(pf, &[U::SampledImage].into(), dev.profile()); - let twin = srgb_twin_on(pf, dev.profile()); - assert!(!(twin && sampled.is_ok()), "{what}"); - let plan = match plain.plan(&dev, &shape) { - Ok(plan) => plan, - Err(crate::error::BindError::Unsupported(u)) - if u.feature == crate::error::Feature::Format - && sampled.is_err() - && !twin => - { - continue - } - Err(e) => panic!("{what}: {e}"), - }; - let views = slot_views(&plan, TEXTURE); - assert!(!views.is_empty(), "{what}"); - if let Ok(s) = sampled { - assert!(plan.variant.srgb_textures.is_empty(), "{what}"); - for v in &views { - assert_eq!(v.format, s.format, "{what}"); - assert_eq!( - v.format.block().and_then(|b| b.color), - Some(crate::vk::NumericFormat::Srgb), - "{what}" - ); - } - decoded += 1; - continue; - } - assert!(twin, "{what}"); - assert_eq!( - plan.variant.srgb_textures, - BTreeSet::from([TEXTURE]), - "{what}" - ); - let held = crate::metal::format::srgb_raw_twin(pf) - .and_then(crate::metal::format::direct_format) - .expect(&what); - for v in &views { - assert_eq!(v.format, held, "{what}"); - } - let key = plan.variant.lowering_inputs(Stage::Kernel); - assert_eq!(key.srgb_textures, BTreeSet::from([TEXTURE]), "{what}"); - let variant = pipeline(&dev, &bc, &key); - assert!( - variant - .stage - .precision_notes - .contains(&PrecisionNote::SrgbTexelDecode), - "{what}" - ); - let a = compile_bitcode( - &bc, - EntryRef::Name("k"), - &FunctionConstantValues::defaults(), - dev.profile(), - &key, - &mut meter(), - SPIRV_WORDS, - ) - .unwrap_or_else(|e| panic!("{what}: {e}")); - link_and_validate(&a, dev.profile()).unwrap_or_else(|e| panic!("{what}: {e}")); - let again = variant - .plan(&dev, &shape) - .unwrap_or_else(|e| panic!("{what}: {e}")); - assert_eq!(again.variant, plan.variant, "{what}"); - for v in slot_views(&again, TEXTURE) { - assert_eq!(v.format, held, "{what}"); - } - twinned += 1; - // Another format, or nothing, leaves the variant. - for other in [Some(PixelFormat::RGBA8Unorm), None] { - let shape = state(other).shape(); - let plan = variant.plan(&dev, &shape).expect("plan"); - assert!(plan.variant.srgb_textures.is_empty(), "{what} {other:?}"); - } - } - } - } - assert!(decoded > 0, "no committed profile samples an sRGB format"); - assert!( - twinned > 0, - "no committed profile samples an sRGB format only through its twin" - ); -} - -/// An ASTC sRGB slot samples the device's decode wherever the device samples a format of it: its -/// own block where the device has ASTC (ANV, MoltenVK), its decoded twin's `R8G8B8A8_SRGB` view -/// elsewhere (`bind::AstcDecode`). It joins no variant, and the pipeline notes -/// `PrecisionNote::SrgbTexelDecode` under the bound format. -#[test] -fn an_astc_srgb_slot_samples_the_devices_decode() { - let Some(bc) = assemble("astc read", &kernel(Access::Read, true)) else { - return; - }; - let (mut decoded, mut native) = (0, 0); - for (stem, dev) in devices() { - let plain = pipeline(&dev, &bc, &inputs(false)); - for pf in [PixelFormat::ASTC4x4SRGB, PixelFormat::ASTC12x10SRGB] { - let what = format!("{stem} {pf:?}"); - let sampled = crate::metal::format::vk_format( - pf, - &[FormatUsage::SampledImage].into(), - dev.profile(), - ) - .unwrap_or_else(|e| panic!("{what}: {e}")); - assert!(!srgb_twin_on(pf, dev.profile()), "{what}"); - let plan = plain.plan(&dev, &state(Some(pf)).shape()).expect(&what); - assert!(plan.variant.srgb_textures.is_empty(), "{what}"); - let views = slot_views(&plan, TEXTURE); - assert!(!views.is_empty(), "{what}"); - for v in &views { - assert_eq!(v.format, sampled.format, "{what}"); - } - if sampled.emulation == crate::metal::format::FormatEmulation::Decoded { - assert_eq!(sampled.format, crate::vk::Format::R8G8B8A8_SRGB, "{what}"); - decoded += 1; - } else { - native += 1; - } - } - } - assert!(decoded > 0, "no committed profile holds an ASTC sRGB twin"); - assert!( - native > 0, - "no committed profile samples an ASTC sRGB block" - ); -} - -/// A `half` sample the device decodes and filters (a linear one with a linear mip filter) -/// rounds the device's `f32` texel to nearest even: on lavapipe and MoltenVK, whose decode and -/// conversion are the device's, the pipeline records `PrecisionNote::HalfTexelConversion` -/// outright, which holds under every bound format. -#[test] -fn the_device_s_srgb_decode_converts_to_half_noted() { - let Some(bc) = assemble( - "mip linear half", - &kernel(Access::Sample(sampler_words(1, 2, false)), true), - ) else { - return; - }; - let mut seen = 0; - for (stem, dev) in devices() { - if !matches!(stem.as_str(), "lavapipe" | "moltenvk-m3") { - continue; - } - seen += 1; - let p = pipeline(&dev, &bc, &inputs(false)); - for pf in [PixelFormat::RGBA8UnormSRGB, PixelFormat::BGRA8UnormSRGB] { - let plan = p.plan(&dev, &state(Some(pf)).shape()).expect("plan"); - assert!(plan.variant.srgb_textures.is_empty(), "{stem} {pf:?}"); - let notes = p - .stage - .precision_notes_bound(&plan.specialization, &|_| None); - assert!( - notes.contains(&PrecisionNote::HalfTexelConversion), - "{stem} {pf:?}: {notes:?}" - ); - } - assert!( - p.stage - .precision_notes - .contains(&PrecisionNote::HalfTexelConversion), - "{stem}: {:?}", - p.stage.precision_notes - ); - assert!( - !p.stage - .specialized_notes - .iter() - .any(|s| s.note == PrecisionNote::HalfTexelConversion), - "{stem}: {:?}", - p.stage.specialized_notes - ); - } - assert_eq!(seen, 2); -} - -/// A render pipeline: a vertex function placing vertex `vid`, and a fragment function returning -/// texel `(0, 0)` of its `texture2d` slot 0. -const RENDER: &str = r#"define <{ <4 x float> }> @v(i32 noundef %vid) { - %f = uitofp i32 %vid to float - %p = insertelement <4 x float> , float %f, i64 0 - %o = insertvalue <{ <4 x float> }> undef, <4 x float> %p, 0 - ret <{ <4 x float> }> %o -} -define <4 x float> @f(<4 x float> noundef %pos, ptr addrspace(1) %t) { - %s = tail call ptr addrspace(2) @air.get_read_sampler() - %r = call { <4 x float>, i8 } @air.read_texture_2d.v4f32(ptr addrspace(1) %t, ptr addrspace(2) %s, <2 x i32> zeroinitializer, <2 x i32> zeroinitializer, i32 0, i32 1) - %c = extractvalue { <4 x float>, i8 } %r, 0 - ret <4 x float> %c -} -declare ptr addrspace(2) @air.get_read_sampler() -declare { <4 x float>, i8 } @air.read_texture_2d.v4f32(ptr addrspace(1), ptr addrspace(2), <2 x i32>, <2 x i32>, i32, i32) -!air.vertex = !{!20} -!air.fragment = !{!0} -!air.version = !{!9} -!air.language_version = !{!10} -!0 = !{ptr @f, !1, !2} -!1 = !{!11} -!11 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"float4"} -!2 = !{!12, !3} -!12 = !{i32 0, !"air.position", !"air.center", !"air.no_perspective", !"air.arg_type_name", !"float4", !"air.arg_name", !"pos"} -!3 = !{i32 1, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.read", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"t"} -!9 = !{i32 2, i32 8, i32 0} -!10 = !{!"Metal", i32 4, i32 0, i32 0} -!20 = !{ptr @v, !21, !23} -!21 = !{!22} -!22 = !{!"air.position", !"air.arg_type_name", !"float4", !"air.arg_name", !"position"} -!23 = !{!24} -!24 = !{i32 0, !"air.vertex_id", !"air.arg_type_name", !"uint", !"air.arg_name", !"vid"} -"#; - -/// A render pipeline's fragment slot bound in an 8-bit sRGB format the device holds as its UNORM -/// twin (`RG8Unorm_sRGB` on lavapipe) joins the plan's variant; `compile_render_variant` compiles -/// it, its plan states the same key, and the fragment's binding views the twin. A format the -/// device samples (`RGBA8Unorm_sRGB` everywhere, `RG8Unorm_sRGB` on MoltenVK and RADV) joins -/// nothing, and the binding views the image in that sRGB format. -#[test] -fn a_fragment_slot_bound_in_a_twin_joins_the_render_variant() { - use crate::pipeline::descriptor::ColorAttachmentDescriptor; - use crate::pipeline::RenderPipelineDescriptor; - let Some(bc) = assemble("render", RENDER) else { - return; - }; - let fragment = SlotRef { - stage: Stage::Fragment, - ..TEXTURE - }; - let state = |pf: PixelFormat| { - let mut f = StageTable::default(); - let mut facts = TextureFacts::new(TextureType::Type2D, pf); - facts.usage = metal::TextureUsage::SHADER_READ; - f.textures.insert( - 0, - BoundTexture::Texture { - facts, - resource_id: None, - }, - ); - let mut s = BindState::default(); - s.stages.insert(Stage::Fragment, f); - s - }; - let (mut ran, mut twinned) = (0, 0); - for (stem, dev) in devices() { - if !["lavapipe", "moltenvk-m3", "amd-780m-radv"].contains(&stem.as_str()) { - continue; - } - ran += 1; - let lib = Library::from_air(&bc).expect("library"); - let v = lib.function("v").expect("vertex"); - let f = lib.function("f").expect("fragment"); - let mut d = - RenderPipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new(v))); - d.fragment = Some(StageSource::Function(FunctionDescriptor::new(f))); - d.color_attachments[0] = Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm)); - let p = dev - .compile_render_pipeline(&d, &Budget::standard()) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - for pf in [PixelFormat::RGBA8UnormSRGB, PixelFormat::RG8UnormSRGB] { - let what = format!("{stem} {pf:?}"); - let shape = state(pf).shape(); - let plan = p.plan(&dev, &shape).expect("plan"); - let views = slot_views(&plan, fragment); - assert_eq!(views.len(), 1, "{what}: {views:?}"); - if !srgb_twin_on(pf, dev.profile()) { - assert!(plan.variant.srgb_textures.is_empty(), "{what}"); - let sampled = crate::metal::format::vk_format( - pf, - &[FormatUsage::SampledImage].into(), - dev.profile(), - ) - .unwrap_or_else(|e| panic!("{what}: {e}")); - assert_eq!(views[0].format, sampled.format, "{what}"); - continue; - } - assert_eq!( - plan.variant.srgb_textures, - BTreeSet::from([fragment]), - "{what}" - ); - let held = crate::metal::format::srgb_raw_twin(pf) - .and_then(crate::metal::format::direct_format); - assert_eq!(Some(views[0].format), held, "{what}"); - let variant = dev - .compile_render_variant(&d, &plan.variant, &Budget::standard()) - .unwrap_or_else(|e| panic!("{what} variant: {e}")); - let again = variant.plan(&dev, &shape).expect("variant plan"); - assert_eq!(again.variant, plan.variant, "{what}: a fixed point"); - assert_eq!(slot_views(&again, fragment), views, "{what}"); - twinned += 1; - } - } - assert_eq!(ran, 3); - assert!(twinned > 0, "lavapipe holds no twin"); -} diff --git a/crates/metal2vulkan/src/tests/engine_swizzled_storage.rs b/crates/metal2vulkan/src/tests/engine_swizzled_storage.rs index 266030b3e..bc66afa82 100644 --- a/crates/metal2vulkan/src/tests/engine_swizzled_storage.rs +++ b/crates/metal2vulkan/src/tests/engine_swizzled_storage.rs @@ -11,27 +11,18 @@ //! `read_write`, stores channel `c` from the first lane whose source is `c`, else lane `c`. An //! atomic ignores the swizzle. //! - A `ulong` read under the variant is refused (`NotImplemented(TextureSwizzle)`). -//! - The binder joins a storage slot bound to a swizzled texture to the variant, which plans the -//! same key again, views the texture unswizzled (`ImageViewDesc::shader_swizzle`) and -//! specializes the slot's swizzle word; a storage slot the function only queries views it -//! unswizzled under no variant; a sampled slot keeps its swizzled view. A swizzled -//! texture's shape states its level count. //! //! `llvm-as` assembles the kernels; without it the tests skip visibly. -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::BTreeMap; use std::sync::atomic::{AtomicU64, Ordering}; -use crate::bind::{BindState, BoundBuffer, BoundTexture, StageTable, TextureFacts, WriteSource}; -use crate::budget::Budget; use crate::device::profile::DeviceProfile; use crate::device::requirements::VkFeature; use crate::device::{Device, DeviceDescription, DevicePolicy}; use crate::error::{Error, Feature}; -use crate::library::Library; use crate::lower::select::{LowerInputs, Plan}; -use crate::metal::{self, PixelFormat, TextureSwizzle as S, TextureSwizzleChannels as C}; -use crate::metal::{TextureType, TextureUsage}; +use crate::metal::{TextureSwizzle as S, TextureSwizzleChannels as C}; use crate::pipeline::facts::RuntimeFact; use crate::pipeline::interface::PushLoc; use crate::pipeline::lower_inputs::{StorageImageChoice, StorageImageClass}; @@ -40,8 +31,6 @@ use crate::pipeline::sym::{SpecKey, Stage}; use crate::pipeline::testing::{ engine_dir, link_and_validate, llvm_assemble, typed_module_with, AssembleError, }; -use crate::pipeline::StageSource; -use crate::pipeline::{ComputePipeline, ComputePipelineDescriptor, FunctionDescriptor}; use crate::spirv::interp::{run_with_images, Buffer, Config, Image, Order, Resources}; use crate::spirv::ir::TypedModule; use crate::vk; @@ -676,466 +665,3 @@ fn a_ulong_read_under_the_variant_is_refused() { } // ---- The binder ------------------------------------------------------------------------------- - -fn devices() -> Vec<(String, Device)> { - let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../metal2vulkan-validation/profiles"); - let mut out = Vec::new(); - for e in std::fs::read_dir(&dir).expect("profiles") { - let path = e.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("profile"); - let desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); - out.push(( - stem, - Device::from_queries(desc, crate::device::DevicePolicy::RESIDENT_TABLES) - .expect("device"), - )); - } - out.sort_by(|a, b| a.0.cmp(&b.0)); - out -} - -/// The kernel compiled into a compute pipeline under `inputs`, or `None` where the device needs a -/// storage slot's format as an input. -fn pipeline(dev: &Device, bc: &[u8], inputs: &LowerInputs) -> Option { - pipeline_of(dev, bc, "k", inputs) -} - -/// [`pipeline`] of the kernel `entry`. -fn pipeline_of( - dev: &Device, - bc: &[u8], - entry: &str, - inputs: &LowerInputs, -) -> Option { - let lib = Library::from_air(bc).expect("library"); - let f = lib.function(entry).expect("function"); - let compiled = - match dev.compile_function(&FunctionDescriptor::new(f), inputs, &Budget::standard()) { - Ok(c) => c, - Err(Error::NeedsInput(_)) => return None, - Err(e) => panic!("compile: {e}"), - }; - Some( - dev.compile_compute_pipeline( - &ComputePipelineDescriptor::new(StageSource::Compiled(compiled)), - &Budget::standard(), - ) - .expect("pipeline"), - ) -} - -/// The facts of an `RGBA8Unorm` texture through `swizzle`: a view made with a swizzle, whose -/// usage Metal keeps only `ShaderRead` and `PixelFormatView` of, of 3 levels. -fn swizzled_facts(swizzle: C) -> TextureFacts { - let mut facts = TextureFacts::new(TextureType::Type2D, PixelFormat::RGBA8Unorm); - facts.usage = TextureUsage::SHADER_READ | TextureUsage::PIXEL_FORMAT_VIEW; - facts.swizzle = swizzle; - facts.mipmap_level_count = 3; - facts -} - -/// A kernel's state: texture slot 0 holding `facts`, buffer 0. -fn state(facts: TextureFacts) -> BindState { - let mut t = StageTable::default(); - t.textures.insert( - 0, - BoundTexture::Texture { - facts, - resource_id: None, - }, - ); - t.buffers.insert( - 0, - BoundBuffer::Buffer { - length: 65536, - offset: 0, - gpu_address: 0x1_0000, - device_address: None, - attribute_stride: None, - }, - ); - let mut s = BindState::default(); - s.stages.insert(Stage::Kernel, t); - s -} - -/// A storage slot bound to a swizzled view joins the plan's variant; the variant's pipeline plans -/// the same key for the same shape, binds the view unswizzled for the function to swizzle -/// (`shader_swizzle`, the identity mapping) and specializes the slot's `TextureSwizzle` to the -/// swizzle's word. An unswizzled texture leaves the variant, and a sampled slot (`access::read`) -/// keeps its view's swizzle, which the consumer composes. On every committed profile. -#[test] -fn a_storage_slot_bound_to_a_swizzled_texture_joins_the_variant() { - let gbar = C::new(S::Green, S::Blue, S::Alpha, S::Red); - let (mut planned, mut sampled) = (0, 0); - for access in ["read_write", "read"] { - let Some(bc) = assemble(access, &read_kernel(Texel::Float, access, 0)) else { - return; - }; - for (stem, dev) in devices() { - let Some(plain) = pipeline(&dev, &bc, &LowerInputs::new()) else { - continue; - }; - let what = format!("{access} on {stem}"); - let shape = state(swizzled_facts(gbar)).shape(); - let plan = plain - .plan(&dev, &shape) - .unwrap_or_else(|e| panic!("{what}: {e}")); - let view = |plan: &crate::bind::BindingPlan| { - plan.descriptors - .iter() - .find_map(|d| match &d.source { - WriteSource::Texture { view, .. } => Some(*view), - _ => None, - }) - .expect("the texture's view") - }; - if access == "read" { - assert!(plan.variant.swizzled_storage.is_empty(), "{what}"); - assert!(!view(&plan).shader_swizzle, "{what}"); - sampled += 1; - continue; - } - assert_eq!( - plan.variant.swizzled_storage, - BTreeSet::from([SLOT]), - "{what}" - ); - let key = plan.variant.lowering_inputs(Stage::Kernel); - assert_eq!( - key.swizzled_storage, plan.variant.swizzled_storage, - "{what}" - ); - let variant = pipeline(&dev, &bc, &key).expect("the variant's inputs"); - let again = variant - .plan(&dev, &shape) - .unwrap_or_else(|e| panic!("{what}: variant {e}")); - assert_eq!(again.variant, plan.variant, "{what}"); - let v = view(&again); - assert!(v.shader_swizzle, "{what}"); - assert_eq!(v.components, vk::ComponentMapping::IDENTITY, "{what}"); - let id = variant - .stage - .specialization - .constants - .iter() - .find_map(|c| (c.key == SpecKey::TextureSwizzle(SLOT)).then_some(c.id)) - .unwrap_or_else(|| panic!("{what}: no TextureSwizzle constant")); - let e = again - .specialization - .entries - .iter() - .find(|e| e.constant_id == id) - .expect("TextureSwizzle entry"); - let at = e.offset as usize; - let word = u32::from_le_bytes( - again.specialization.data[at..at + 4] - .try_into() - .expect("a u32"), - ); - assert_eq!(word, gbar.word(), "{what}"); - let own = plain - .plan(&dev, &state(swizzled_facts(C::DEFAULT)).shape()) - .unwrap_or_else(|e| panic!("{what}: unswizzled {e}")); - assert!(own.variant.swizzled_storage.is_empty(), "{what}"); - planned += 1; - } - } - assert!( - planned > 0 && sampled > 0, - "{planned} planned, {sampled} sampled" - ); -} - -/// A kernel storing texture slot 0's width (`access` `write` or `read_write`), which it neither -/// reads nor writes, to `out[0]` (buffer 0). -fn query_kernel(access: &str) -> String { - format!( - r#"define void @k(ptr addrspace(1) %t, ptr addrspace(1) %out) {{ - %w = call i32 @air.get_width_texture_2d(ptr addrspace(1) %t, i32 0) - store i32 %w, ptr addrspace(1) %out, align 4 - ret void -}} - -declare i32 @air.get_width_texture_2d(ptr addrspace(1), i32) - -!air.kernel = !{{!0}} -!0 = !{{ptr @k, !1, !2}} -!1 = !{{}} -!2 = !{{!3, !4}} -!3 = !{{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.{access}", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"t"}} -!4 = !{{i32 1, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"out"}} -"# - ) -} - -/// A storage slot its function only queries, bound to a swizzled view, reads and writes no texel, -/// and no swizzle reaches its width (Metal answers the view's size: our probe -/// `opencl_swizzled_images`, job m3-max-16336): its plan joins no variant and binds the view with -/// no swizzle (`shader_swizzle`, the identity mapping), where a Vulkan storage view could take -/// none and the consumer refused it. On every committed profile. -#[test] -fn a_storage_slot_only_queried_binds_a_swizzled_texture_unswizzled() { - let bgra = C::new(S::Blue, S::Green, S::Red, S::Alpha); - let mut planned = 0; - for access in ["write", "read_write"] { - let Some(bc) = assemble(&format!("query {access}"), &query_kernel(access)) else { - return; - }; - for (stem, dev) in devices() { - let Some(plain) = pipeline(&dev, &bc, &LowerInputs::new()) else { - continue; - }; - let what = format!("{access} on {stem}"); - let plan = plain - .plan(&dev, &state(swizzled_facts(bgra)).shape()) - .unwrap_or_else(|e| panic!("{what}: {e}")); - assert!(plan.variant.swizzled_storage.is_empty(), "{what}"); - let view = plan - .descriptors - .iter() - .find_map(|d| match &d.source { - WriteSource::Texture { view, .. } => Some(*view), - _ => None, - }) - .unwrap_or_else(|| panic!("{what}: the texture's view")); - assert!(view.shader_swizzle, "{what}"); - assert_eq!(view.components, vk::ComponentMapping::IDENTITY, "{what}"); - planned += 1; - } - } - assert!(planned > 0); -} - -/// The value `plan` specializes `pipeline`'s constant `key` to. -fn spec_word(pipeline: &ComputePipeline, plan: &crate::bind::BindingPlan, key: SpecKey) -> u32 { - let id = pipeline - .stage - .specialization - .constants - .iter() - .find_map(|c| (c.key == key).then_some(c.id)) - .unwrap_or_else(|| panic!("no {key:?} constant")); - let e = plan - .specialization - .entries - .iter() - .find(|e| e.constant_id == id) - .unwrap_or_else(|| panic!("no {key:?} entry")); - let at = e.offset as usize; - u32::from_le_bytes( - plan.specialization.data[at..at + 4] - .try_into() - .expect("a u32"), - ) -} - -/// A sampled slot (`access::read`) bound to a swizzled texture of a packed normalized format -/// joins the plan's variant: the device's view's swizzle would move a channel's code onto another channel's lane before the function -/// converts it by its own code scale: the variant's pipeline plans the same key for the same -/// shape, binds the view unswizzled for the function to swizzle (`shader_swizzle`, the -/// unswizzled texture's mapping) and specializes the slot's `TextureSwizzle` to the swizzle's word. -/// A swizzle that reads every -/// texel as none does (`RGB1` of `B5G6R5Unorm`, whose alpha reads 1) leaves the variant. On every -/// committed profile that holds the format. -#[test] -fn a_sampled_slot_bound_to_a_swizzled_packed_texture_swizzles_in_its_function() { - let gbar = C::new(S::Green, S::Blue, S::Alpha, S::Red); - let rgb1 = C::new(S::Red, S::Green, S::Blue, S::One); - let Some(bc) = assemble("packed read", &read_kernel(Texel::Float, "read", 0)) else { - return; - }; - let facts = |pf: PixelFormat, swizzle: C| { - let mut facts = swizzled_facts(swizzle); - facts.pixel_format = pf; - facts - }; - let view = |plan: &crate::bind::BindingPlan| { - plan.descriptors - .iter() - .find_map(|d| match &d.source { - WriteSource::Texture { view, .. } => Some(*view), - _ => None, - }) - .expect("the texture's view") - }; - let mut joined = 0; - for (stem, dev) in devices() { - let Some(plain) = pipeline(&dev, &bc, &LowerInputs::new()) else { - continue; - }; - for pf in [ - PixelFormat::B5G6R5Unorm, - PixelFormat::A1BGR5Unorm, - PixelFormat::BGR5A1Unorm, - PixelFormat::ABGR4Unorm, - ] { - let what = format!("{pf:?} on {stem}"); - let shape = state(facts(pf, gbar)).shape(); - let plan = match plain.plan(&dev, &shape) { - Ok(plan) => plan, - // A device that holds no such texture refuses it unswizzled too. - Err(e) => { - let own = plain.plan(&dev, &state(facts(pf, C::DEFAULT)).shape()); - assert!(own.is_err(), "{what}: {e}, but unswizzled it plans"); - continue; - } - }; - assert_eq!( - plan.variant.swizzled_storage, - BTreeSet::from([SLOT]), - "{what}" - ); - let key = plan.variant.lowering_inputs(Stage::Kernel); - let variant = pipeline(&dev, &bc, &key).expect("the variant's inputs"); - let again = variant - .plan(&dev, &shape) - .unwrap_or_else(|e| panic!("{what}: variant {e}")); - assert_eq!(again.variant, plan.variant, "{what}"); - // The view's mapping is the unswizzled texture's: its format's own alone. - let own = plain - .plan(&dev, &state(facts(pf, C::DEFAULT)).shape()) - .unwrap_or_else(|e| panic!("{what}: unswizzled {e}")); - let v = view(&again); - assert!(v.shader_swizzle, "{what}"); - assert_eq!(v.components, view(&own).components, "{what}"); - let word = spec_word(&variant, &again, SpecKey::TextureSwizzle(SLOT)); - assert_eq!(word, gbar.word(), "{what}"); - if pf == PixelFormat::B5G6R5Unorm { - let own = plain - .plan(&dev, &state(facts(pf, rgb1)).shape()) - .unwrap_or_else(|e| panic!("{what}: RGB1 {e}")); - assert!(own.variant.swizzled_storage.is_empty(), "{what}"); - } - joined += 1; - } - } - assert!(joined > 0, "no profile joined the variant"); -} - -/// A sample through a runtime sampler (`fpv_swizzled_reads`' `fpv_swz_sample`, a combined image -/// sampler) of a swizzled packed normalized texture joins the variant as a read does, on every -/// committed profile: its combined image's view takes no swizzle (`shader_swizzle`, the -/// unswizzled texture's mapping), the variant plans the same key again and specializes the slot's -/// swizzle. -#[test] -fn a_combined_sampler_of_a_swizzled_packed_texture_swizzles_in_its_function() { - use crate::bind::{BoundSampler, ImageSource, SamplerDescriptor}; - let gbar = C::new(S::Green, S::Blue, S::Alpha, S::Red); - let Some(bc) = (match llvm_assemble(&engine_dir().join("fpv_swizzled_reads.ll")) { - Ok(b) => Some(b), - Err(AssembleError::Missing(why)) => { - eprintln!("SKIPPED: {why}"); - None - } - Err(AssembleError::Rejected(why)) => panic!("fpv_swizzled_reads.ll: {why}"), - }) else { - return; - }; - let shape = |pf: PixelFormat, swizzle: C| { - let mut facts = swizzled_facts(swizzle); - facts.pixel_format = pf; - let mut s = state(facts); - let t = s - .stages - .get_mut(&Stage::Kernel) - .expect("the kernel's table"); - t.buffers.insert( - 1, - BoundBuffer::Buffer { - length: 65536, - offset: 0, - gpu_address: 0x2_0000, - device_address: None, - attribute_stride: None, - }, - ); - t.samplers - .insert(0, BoundSampler::new(SamplerDescriptor::new())); - s.shape() - }; - let view = |plan: &crate::bind::BindingPlan| { - plan.descriptors - .iter() - .find_map(|d| match &d.source { - WriteSource::CombinedImageSampler { - image: ImageSource::Texture { view, .. }, - .. - } => Some(*view), - _ => None, - }) - .expect("the combined image's view") - }; - let mut joined = 0; - for (stem, dev) in devices() { - let entry = "fpv_swz_sample"; - let Some(plain) = pipeline_of(&dev, &bc, entry, &LowerInputs::new()) else { - continue; - }; - for pf in [ - PixelFormat::B5G6R5Unorm, - PixelFormat::A1BGR5Unorm, - PixelFormat::BGR5A1Unorm, - PixelFormat::ABGR4Unorm, - ] { - let what = format!("{pf:?} on {stem}"); - let swizzled = shape(pf, gbar); - let Ok(plan) = plain.plan(&dev, &swizzled) else { - let own = plain.plan(&dev, &shape(pf, C::DEFAULT)); - assert!( - own.is_err(), - "{what}: refused swizzled, but unswizzled it plans" - ); - continue; - }; - assert_eq!( - plan.variant.swizzled_storage, - BTreeSet::from([SLOT]), - "{what}" - ); - let key = plan.variant.lowering_inputs(Stage::Kernel); - let variant = pipeline_of(&dev, &bc, entry, &key).expect("the variant's inputs"); - let again = variant - .plan(&dev, &swizzled) - .unwrap_or_else(|e| panic!("{what}: variant {e}")); - assert_eq!(again.variant, plan.variant, "{what}"); - let own = plain - .plan(&dev, &shape(pf, C::DEFAULT)) - .unwrap_or_else(|e| panic!("{what}: unswizzled {e}")); - let v = view(&again); - assert!(v.shader_swizzle, "{what}"); - assert_eq!(v.components, view(&own).components, "{what}"); - let word = spec_word(&variant, &again, SpecKey::TextureSwizzle(SLOT)); - assert_eq!(word, gbar.word(), "{what}"); - joined += 1; - } - } - assert!(joined > 0, "no profile joined the variant"); -} - -/// A swizzled texture's shape states its level count, which a storage slot reading its levels -/// needs, though Metal strips its usage of `ShaderWrite`; an unswizzled texture without -/// `ShaderWrite` states it too, as plain Metal writes one at every level. -#[test] -fn a_swizzled_texture_s_shape_states_its_levels() { - let gbar = C::new(S::Green, S::Blue, S::Alpha, S::Red); - let levels = |facts: TextureFacts| match facts.shape() { - crate::bind::TextureShape::Texture { - mipmap_level_count, .. - } => mipmap_level_count, - other => panic!("{other:?}"), - }; - assert_eq!(levels(swizzled_facts(gbar)), 3); - assert_eq!(levels(swizzled_facts(C::DEFAULT)), 3); - let mut written = swizzled_facts(C::DEFAULT); - written.usage = metal::TextureUsage::SHADER_READ | metal::TextureUsage::SHADER_WRITE; - assert_eq!(levels(written), 3); -} diff --git a/crates/metal2vulkan/src/tests/engine_tessellation.rs b/crates/metal2vulkan/src/tests/engine_tessellation.rs index bc1fa9402..7e5d460d5 100644 --- a/crates/metal2vulkan/src/tests/engine_tessellation.rs +++ b/crates/metal2vulkan/src/tests/engine_tessellation.rs @@ -14,16 +14,10 @@ use std::collections::BTreeMap; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Arc; -use crate::bind::{ - BindState, BoundBuffer, DrawCall, IndexBufferRef, IndirectRef, StageTable, - TessellationFactorBuffer, TessellationFactors, UseTarget, WriteSource, -}; use crate::budget::{Budget, SPIRV_WORDS}; use crate::device::requirements::{VkFeature, VkProperty}; use crate::device::{Device, DeviceDescription, DevicePolicy, DeviceProfile}; -use crate::error::{ - BindError, Capability, DescriptorError, Error, Feature, LowerFamily, Needs, RuntimeInput, -}; +use crate::error::{Capability, DescriptorError, Error, Feature, LowerFamily, Needs, RuntimeInput}; use crate::library::{FunctionArtifact, FunctionConstantValues, Library}; use crate::metal::{ TessellationControlPointIndexType, TessellationFactorStepFunction, TessellationPartitionMode, @@ -1082,249 +1076,6 @@ fn what_the_control_stage_cannot_do_is_refused_typed() { } } -/// A tessellation pipeline's plan writes the encoder's factor buffer at the control stage's binding -/// (a zero buffer without one), pushes each stage's range at its Vulkan stage, and draws patches: -/// one vertex per patch from the patch start, the control stage's push range holding the factor -/// buffer's residual bind offset, instance stride, and `half` scale, and the factor buffer bound -/// over the factors the draw reads. A draw of primitives is refused. -#[test] -fn a_tessellation_plan_draws_patches() { - let Some(bc) = fixture() else { return }; - let Some(fragments) = assemble_text("fragments", FRAGMENTS) else { - return; - }; - let t = TessellationDescriptor { - factor_step_function: TessellationFactorStepFunction::PerPatchAndPerInstance, - factor_scale_enabled: true, - ..Default::default() - }; - for stem in ["moltenvk-m3", "lavapipe", "nvidia-rtx5080-laptop"] { - let dev = device(stem); - let d = tessellation_pipeline( - &bc, - &fragments, - "tess_triangle_points", - Some("tess_fragment"), - Some(t), - ); - let p = dev - .compile_render_pipeline(&d, &Budget::standard()) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - let ts = p.graphics.tessellation.expect("tessellation state"); - let factors = p - .layout - .sets - .iter() - .flat_map(|s| s.bindings.iter().map(move |b| (s.set, b))) - .find(|(_, b)| { - b.source - == BindingSource::Synthetic { - stage: Stage::Vertex, - binding: SyntheticBinding::TessellationFactors, - } - }) - .map(|(set, b)| (set, b.binding)) - .expect("factor binding"); - - let mut state = BindState::default(); - let mut table = StageTable::default(); - for index in [0, 1] { - table.buffers.insert( - index, - BoundBuffer::Buffer { - length: 4096, - offset: 0, - gpu_address: 0x1_0000, - device_address: None, - attribute_stride: None, - }, - ); - } - state.stages.insert(Stage::Vertex, table); - // Without a factor buffer the zero buffer stands in and every patch is culled. - let plan = p.plan(&dev, &state.shape()).expect("plan"); - let write = |plan: &crate::bind::BindingPlan| { - plan.descriptors - .iter() - .find(|w| (w.set, w.binding) == factors) - .map(|w| w.source.clone()) - .expect("a factor write") - }; - assert!(matches!(write(&plan), WriteSource::Neutral(_)), "{stem}"); - - let (offset, stride) = (64, 256); - state.tessellation_factors = TessellationFactors::new( - Some(TessellationFactorBuffer::new(4096, offset, stride)), - 1.3, - ); - let plan = p.plan(&dev, &state.shape()).expect("plan"); - assert_eq!(write(&plan), WriteSource::TessellationFactors, "{stem}"); - assert!(plan - .uses - .iter() - .any(|u| u.resource == UseTarget::TessellationFactors - && u.stages == vk::PipelineStageFlags2::TESSELLATION_CONTROL_SHADER)); - let draw = DrawCall::Patches { - control_points: 3, - patch_start: 2, - patch_count: 5, - patch_index: None, - instance_count: 2, - base_instance: 1, - control_point_index: None, - }; - let cmds = plan.instantiate_draw(&state, &draw).expect("draw"); - assert_eq!( - cmds.draw, - vk::DrawCommand::Draw { - vertex_count: 5, - instance_count: 2, - first_vertex: 2, - first_instance: 1 - } - ); - // Every push write is one of the layout's ranges, at its stage. - for w in &cmds.push_constants { - assert!( - p.layout.push_constants.iter().any(|r| r.stages == w.stages - && r.offset == w.offset - && r.size as usize == w.bytes.len()), - "{stem}: {w:?} is not a layout range" - ); - assert!( - !w.stages.contains(vk::ShaderStage::VERTEX.flags()), - "{stem}" - ); - } - let control = cmds - .push_constants - .iter() - .find(|w| w.stages == vk::ShaderStage::TESSELLATION_CONTROL.flags()) - .expect("control push"); - assert_eq!(control.offset, ts.push_offset); - // Patches 2..7 of instances 1..3, 8 bytes each, 256 bytes an instance. - let start = offset + 2 * 8 + 256; - let end = offset + 6 * 8 + 2 * 256 + 8; - let a = dev - .profile() - .fields() - .limits - .min_storage_buffer_offset_alignment - .max(4); - let lo = start - start % a; - let range = cmds - .descriptor_ranges - .iter() - .find(|r| (r.set, r.binding) == factors) - .expect("factor range"); - assert_eq!(range.range.offset, lo, "{stem}"); - assert_eq!(range.range.range, end.next_multiple_of(16) - lo, "{stem}"); - let word = - |k: usize| u32::from_le_bytes(control.bytes[4 * k..4 * k + 4].try_into().unwrap()); - assert_eq!(word(0), (offset as u32).wrapping_sub(lo as u32), "{stem}"); - assert_eq!(word(1), stride as u32); - // 1.3 as a `half`: 1 + 307/1024. - assert_eq!(f32::from_bits(word(2)), 1.0 + 307.0 / 1024.0); - // No patch index buffer: none bound, and the control stage told so. - assert_eq!((word(3), word(4)), (0, 0), "{stem}"); - let patch_indices = p - .layout - .sets - .iter() - .flat_map(|s| s.bindings.iter().map(move |b| (s.set, b))) - .find(|(_, b)| { - b.source - == BindingSource::Synthetic { - stage: Stage::Vertex, - binding: SyntheticBinding::PatchIndices, - } - }) - .map(|(set, b)| (set, b.binding)) - .expect("patch index binding"); - assert!(matches!( - plan.descriptors - .iter() - .find(|w| (w.set, w.binding) == patch_indices) - .map(|w| &w.source), - Some(WriteSource::PatchIndices { .. }) - )); - assert!(!cmds - .descriptor_ranges - .iter() - .any(|r| (r.set, r.binding) == patch_indices)); - // A patch index buffer: bound over the indices of patches 2..7 from offset 64, its - // residual and 1 pushed, read in the control stage. - let indexed = DrawCall::Patches { - control_points: 3, - patch_start: 2, - patch_count: 5, - patch_index: Some((IndexBufferRef::new(7, 4096), 64)), - instance_count: 2, - base_instance: 1, - control_point_index: None, - }; - let cmds = plan - .instantiate_draw(&state, &indexed) - .expect("indexed draw"); - let range = cmds - .descriptor_ranges - .iter() - .find(|r| (r.set, r.binding) == patch_indices) - .expect("patch index range"); - let start = 64 + 2 * 4; - assert_eq!(range.range.offset, start - start % a, "{stem}"); - let control = cmds - .push_constants - .iter() - .find(|w| w.stages == vk::ShaderStage::TESSELLATION_CONTROL.flags()) - .expect("control push"); - let word = - |k: usize| u32::from_le_bytes(control.bytes[4 * k..4 * k + 4].try_into().unwrap()); - assert_eq!( - (word(3), word(4)), - (64u32.wrapping_sub(range.range.offset as u32), 1), - "{stem}" - ); - assert!(cmds - .uses - .iter() - .any(|u| u.resource == UseTarget::PatchIndices - && u.stages == vk::PipelineStageFlags2::TESSELLATION_CONTROL_SHADER)); - - assert_eq!( - plan.instantiate_draw( - &state, - &DrawCall::Primitives { - vertex_start: 0, - vertex_count: 3, - instance_count: 1, - base_instance: 0 - } - ), - Err(BindError::InvalidDrawKind { patches: false }) - ); - let indirect = DrawCall::PatchesIndirect { - control_points: 3, - patch_index: None, - indirect: IndirectRef { - token: 9, - offset: 32, - }, - control_point_index: None, - }; - let cmds = plan.instantiate_draw(&state, &indirect).expect("indirect"); - assert_eq!( - cmds.draw, - vk::DrawCommand::DrawIndirect { - offset: 32, - draw_count: 1, - stride: 16 - } - ); - assert!(!cmds.indirect_needs_arguments, "{stem}"); - } -} - /// A post-tessellation vertex function's compile key and lowering inputs are the same for every /// tessellation state: the state is its pipeline's control stage's, not the function's. #[test] diff --git a/crates/metal2vulkan/src/tests/engine_texel_rows.rs b/crates/metal2vulkan/src/tests/engine_texel_rows.rs deleted file mode 100644 index d8571dc3b..000000000 --- a/crates/metal2vulkan/src/tests/engine_texel_rows.rs +++ /dev/null @@ -1,310 +0,0 @@ -//! A 2D texture's rows read and written in place through a texel buffer (`bind::texel_rows`), on -//! the CPU interpreter. -//! -//! - A slot whose function only reads, writes or asks the size of its texture states -//! `RuntimeFact::TexelRows`; one that samples it states none. -//! - Under the rows variant (`LoweringInputs::texel_rows`) the slot is a texel buffer (uniform -//! for an `access::read` slot, storage for an `access::write` or `read_write` one) that the -//! profile validates, and its push field holds the rows' words. -//! - A read of texel `(x, y)` reads the view's texel `first + y · row + x`, and Metal's -//! out-of-bounds texel past the texture's width or height; a write stores there, and nothing -//! past the texture, so the texels between the rows and before the first keep their values; -//! a size query answers the field's size. The interpreter's texel buffer traps every access -//! outside the view, so each access lies within it. -//! -//! The kernels are the runtime's device tests' (`examples/texel_rows.metal`). `llvm-as` assembles -//! them; without it the tests skip visibly. - -use std::collections::BTreeMap; - -use crate::device::profile::DeviceProfile; -use crate::device::DevicePolicy; -use crate::lower::select::{LowerInputs, Plan}; -use crate::pipeline::facts::RuntimeFact; -use crate::pipeline::interface::PushLoc; -use crate::pipeline::sym::{Axis, PushField, ResourceKind, ResourceSlot, SlotClass, SlotRef}; -use crate::pipeline::sym::{SpecKey, Stage}; -use crate::pipeline::testing::{ - compile, compile_with, fixtures_dir, link_and_validate, llvm_assemble, profile, - typed_module_with, AssembleError, -}; -use crate::spirv::interp::{run_with_images, Buffer, Config, Image, Order, Resources}; -use crate::spirv::ir::{Dim, GlobalKind, ImageUsage, Type as SType, TypedModule}; - -const TEXTURE: SlotRef = SlotRef { - stage: Stage::Kernel, - class: SlotClass::Texture, - index: 0, -}; - -/// The texture's width and height, its rows' texels apart in the view, and the view's texel -/// that is its first: rows of 5 texels 7 apart, after 3 texels of the view. -const SIZE: [u32; 2] = [5, 4]; -const ROW: u32 = 7; -const FIRST: u32 = 3; -/// The rows' push words (`TexelRows::words`): the size, the row and the first texel. -const ROWS: [u32; 4] = [SIZE[0], SIZE[1], ROW, FIRST]; -/// The texels the view holds, from its first through the texture's last. -const ELEMENTS: u32 = FIRST + ROW * (SIZE[1] - 1) + SIZE[0]; - -/// The grid: past the texture's width and height, so its edges are crossed. -const GRID: [u32; 2] = [8, 6]; - -/// The kernels' bitcode, or `None` without `llvm-as`. -fn bitcode() -> Option> { - let ll = fixtures_dir().join("examples/texel_rows.ll"); - match llvm_assemble(&ll) { - Ok(x) => Some(x), - Err(AssembleError::Missing(why)) => { - eprintln!("SKIPPED: {why}"); - None - } - Err(AssembleError::Rejected(why)) => panic!("texel_rows.ll: {why}"), - } -} - -fn lavapipe() -> DeviceProfile { - profile("lavapipe", DevicePolicy::RESIDENT_TABLES).expect("profile") -} - -/// The rows variant's inputs: slot 0's rows. -fn rows_inputs() -> LowerInputs { - let mut inputs = LowerInputs::new(); - inputs.texel_rows.insert(TEXTURE); - inputs -} - -/// The view's texel `i` before any write: a value of its own in each lane, as `float` bits. -fn view_texel(i: u32) -> [u32; 4] { - std::array::from_fn(|lane| (i as f32 * 4.0 + lane as f32 + 0.25).to_bits()) -} - -/// Each texel of the texture by its view index, `(x, y)` row-major. -fn texture_indices() -> Vec<((u32, u32), u32)> { - let [w, h] = SIZE; - (0..h) - .flat_map(|y| (0..w).map(move |x| ((x, y), FIRST + y * ROW + x))) - .collect() -} - -/// The texture's binding, a texel buffer of `usage`. -fn rows_binding(m: &TypedModule, usage: ImageUsage) -> ResourceSlot { - let (slot, pointee) = m - .globals() - .iter() - .find_map(|g| match g.kind { - GlobalKind::Resource( - s @ ResourceSlot { - kind: ResourceKind::Texture, - index: 0, - .. - }, - ) => Some((s, g.pointee)), - _ => None, - }) - .expect("the texture's binding"); - match m.types().get(pointee).expect("its type") { - SType::Image(i) => { - assert_eq!(i.dim, Dim::Buffer, "the rows' binding is a texel buffer"); - assert_eq!(i.usage, usage, "the rows' texel buffer's kind"); - } - other => panic!("the rows' binding is {other:?}"), - } - slot -} - -/// The view, `elements` texels of [`view_texel`], bound at `slot`. -fn view(slot: ResourceSlot) -> Image { - let n = ELEMENTS; - let mut image = Image::new(slot, [n, 1, 1], 1, 1, 1); - for x in 0..n { - let i = image.index(0, 0, 0, [x, 0, 0]).expect("element"); - image.texels[i] = view_texel(x); - } - image -} - -/// Resources of a dispatch of one-thread threadgroups: `[[buffer(i)]]` holding `init[i]`, the -/// slot's push field holding the rows' words, and Metal's out-of-bounds alpha of a format with -/// alpha (0). -fn resources(plan: &Plan, init: &[Vec]) -> Resources { - let mut spec = BTreeMap::new(); - for axis in [Axis::X, Axis::Y, Axis::Z] { - spec.insert(SpecKey::LocalSize(axis), 1); - } - spec.insert(SpecKey::FlatLocalSize, 1); - spec.insert(SpecKey::OutOfBoundsAlpha(TEXTURE), 0); - let mut push = vec![0u8; plan.push.push_range.map_or(0, |(_, end)| end as usize)]; - let mut written = false; - for f in &plan.push.fields { - if let (PushField::TexelRows(TEXTURE), PushLoc::Push { offset }) = (f.field, f.loc) { - let at = offset as usize; - for (i, w) in ROWS.into_iter().enumerate() { - push[at + 4 * i..at + 4 * i + 4].copy_from_slice(&w.to_le_bytes()); - } - written = true; - } - } - assert!(written, "the rows' push field"); - let buffers = init - .iter() - .enumerate() - .map(|(i, b)| Buffer { - slot: Some(ResourceSlot { - stage: Stage::Kernel, - kind: ResourceKind::Buffer, - index: i as u32, - }), - address: None, - bytes: b.clone(), - }) - .collect(); - Resources { - buffers, - push, - spec, - } -} - -/// `m` over the grid with `image` bound, in both scheduling orders, which must agree: the final -/// buffers and the view. -fn run(m: &TypedModule, res: &Resources, image: &Image) -> (Vec>, Image) { - let mut outs = Vec::new(); - for order in [Order::Forward, Order::Reverse] { - let cfg = Config { - workgroups: [GRID[0], GRID[1], 1], - order, - ..Config::default() - }; - let (o, images) = run_with_images(m, &cfg, res.clone(), vec![image.clone()]) - .unwrap_or_else(|e| panic!("interpreter: {e:?}")); - let image = images.into_iter().next().expect("the view"); - outs.push((o.buffers, image.texels.clone(), image)); - } - assert_eq!(outs[0].0, outs[1].0, "the scheduling orders disagree"); - assert_eq!(outs[0].1, outs[1].1, "the scheduling orders disagree"); - let (buffers, _, image) = outs.swap_remove(0); - (buffers, image) -} - -/// The grid's columns, as the kernels' `constant uint &columns`. -fn columns() -> Vec { - GRID[0].to_le_bytes().to_vec() -} - -/// A slot whose function only reads, writes or asks the size of its texture states its rows; a -/// slot that samples it states none. -#[test] -fn reads_writes_and_sizes_state_rows_and_samples_do_not() { - let Some(bitcode) = bitcode() else { return }; - let p = lavapipe(); - let fact = RuntimeFact::TexelRows { slot: TEXTURE }; - for entry in ["rows_invert", "rows_read", "rows_write"] { - let a = compile(&bitcode, entry, &p).unwrap_or_else(|e| panic!("{entry}: {e}")); - assert!(a.facts.contains(&fact), "{entry} states its rows"); - } - let a = compile(&bitcode, "rows_sample", &p).expect("rows_sample"); - assert!(!a.facts.contains(&fact), "a sample states no rows"); -} - -/// Under the rows variant each kernel's module validates on the profile, the slot a texel -/// buffer: uniform for a slot that only reads, storage for one that writes. -#[test] -fn the_rows_variant_validates() { - let Some(bitcode) = bitcode() else { return }; - let p = lavapipe(); - for (entry, usage) in [ - ("rows_invert", ImageUsage::Storage), - ("rows_read", ImageUsage::Sampled), - ("rows_write", ImageUsage::Storage), - ] { - let a = compile_with(&bitcode, entry, &p, &rows_inputs()) - .unwrap_or_else(|e| panic!("{entry}: {e}")); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{entry}: {e}")); - let (_, m) = typed_module_with(&bitcode, entry, &p, &rows_inputs()).expect(entry); - rows_binding(&m, usage); - let fact = RuntimeFact::TexelRows { slot: TEXTURE }; - assert!( - a.facts.contains(&fact), - "{entry}'s variant states its rows, as the plan holds it to" - ); - } -} - -/// A read of texel `(x, y)` reads the view's texel `first + y · row + x`, and Metal's zero texel -/// past the texture's width or height, never the next row's. -#[test] -fn a_read_takes_its_texel_by_row() { - let Some(bitcode) = bitcode() else { return }; - let p = lavapipe(); - let (plan, m) = typed_module_with(&bitcode, "rows_read", &p, &rows_inputs()).expect("module"); - let slot = rows_binding(&m, ImageUsage::Sampled); - let out = vec![0u8; (GRID[0] * GRID[1] * 16) as usize]; - let res = resources(&plan, &[out, columns()]); - let (buffers, _) = run(&m, &res, &view(slot)); - let (words, _) = buffers[0].as_chunks::<4>(); - let texels: Vec<[u32; 4]> = (words.as_chunks::<4>().0.iter()) - .map(|t| t.map(u32::from_le_bytes)) - .collect(); - let inside: BTreeMap<(u32, u32), u32> = texture_indices().into_iter().collect(); - for y in 0..GRID[1] { - for x in 0..GRID[0] { - let got = texels[(y * GRID[0] + x) as usize]; - let want = inside.get(&(x, y)).map_or([0; 4], |&i| view_texel(i)); - assert_eq!(got, want, "texel ({x}, {y})"); - } - } -} - -/// A write of texel `(x, y)` stores the view's texel `first + y · row + x`, and nothing past the -/// texture: the texels before the first and between the rows keep their values. -#[test] -fn a_write_stores_its_texel_by_row_and_nothing_else() { - let Some(bitcode) = bitcode() else { return }; - let p = lavapipe(); - let (plan, m) = typed_module_with(&bitcode, "rows_write", &p, &rows_inputs()).expect("module"); - let slot = rows_binding(&m, ImageUsage::Storage); - let value = |x: u32, y: u32| -> [u32; 4] { - std::array::from_fn(|lane| { - (1000.0 + (y * GRID[0] + x) as f32 * 4.0 + lane as f32).to_bits() - }) - }; - let mut input = Vec::new(); - for y in 0..GRID[1] { - for x in 0..GRID[0] { - for lane in value(x, y) { - input.extend(lane.to_le_bytes()); - } - } - } - let res = resources(&plan, &[input, columns()]); - let (_, image) = run(&m, &res, &view(slot)); - let mut want: Vec<[u32; 4]> = (0..ELEMENTS).map(view_texel).collect(); - for ((x, y), i) in texture_indices() { - want[i as usize] = value(x, y); - } - assert_eq!(image.texels, want, "the view after the writes"); -} - -/// A kernel that asks the size, reads and writes inverts each texel inside the texture by its -/// row, and nothing else. -#[test] -fn a_read_write_kernel_asks_the_rows_size() { - let Some(bitcode) = bitcode() else { return }; - let p = lavapipe(); - let (plan, m) = typed_module_with(&bitcode, "rows_invert", &p, &rows_inputs()).expect("module"); - let slot = rows_binding(&m, ImageUsage::Storage); - let res = resources(&plan, &[]); - let (_, image) = run(&m, &res, &view(slot)); - let mut want: Vec<[u32; 4]> = (0..ELEMENTS).map(view_texel).collect(); - for (_, i) in texture_indices() { - let t = view_texel(i).map(f32::from_bits); - want[i as usize] = [ - (1.0 - t[0]).to_bits(), - (1.0 - t[1]).to_bits(), - (1.0 - t[2]).to_bits(), - t[3].to_bits(), - ]; - } - assert_eq!(image.texels, want, "the view after the inversion"); -} diff --git a/crates/metal2vulkan/src/tests/engine_texture_levels.rs b/crates/metal2vulkan/src/tests/engine_texture_levels.rs index 7a39074d9..fcd9f8330 100644 --- a/crates/metal2vulkan/src/tests/engine_texture_levels.rs +++ b/crates/metal2vulkan/src/tests/engine_texture_levels.rs @@ -24,30 +24,22 @@ use std::path::Path; use std::sync::atomic::{AtomicU64, Ordering}; use crate::air::intrinsics::ImageDim; -use crate::bind::{BindState, BoundBuffer, BoundTexture, Dispatch, StageTable, TextureFacts}; -use crate::bind::{BindingPlan, FieldLocation, PlanDiagnostic, WriteSource}; -use crate::budget::Budget; use crate::device::profile::DeviceProfile; use crate::device::requirements::VkFeature; use crate::device::requirements::VkLimit; use crate::device::{Device, DeviceDescription, DevicePolicy}; -use crate::error::{BindError, Capability, Error, Feature, LowerFamily, Needs, Unsupported}; -use crate::library::{FunctionArtifact, Library}; +use crate::error::{Capability, Error, Feature, LowerFamily, Needs, Unsupported}; +use crate::library::FunctionArtifact; use crate::lower::select::Plan; use crate::lower::texture::max_levels; -use crate::metal::{PixelFormat, TextureType, TextureUsage}; use crate::pipeline::facts::RuntimeFact; use crate::pipeline::interface::PushLoc; -use crate::pipeline::layout::BindingSource; use crate::pipeline::sym::{ Axis, PushField, ResourceKind, ResourceSlot, SlotClass, SlotRef, SpecKey, Stage, }; use crate::pipeline::testing::{ compile, engine_dir, link_and_validate, llvm_assemble, profile, typed_module, AssembleError, }; -use crate::pipeline::{ - ComputePipeline, ComputePipelineDescriptor, FunctionDescriptor, StageSource, -}; use crate::spirv::interp::{run_with_images, Buffer, Config, Image, Order, Resources}; use crate::spirv::ir::TypedModule; use crate::spirv::testing::committed_profiles; @@ -1424,420 +1416,3 @@ fn one_d_textures_have_no_levels() { } // ---- The binder, end to end ---- - -fn device(stem: &str) -> Device { - let 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 desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); - Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device") -} - -fn pipeline(dev: &Device, bc: &[u8], entry: &str) -> ComputePipeline { - let lib = Library::from_air(bc).expect("library"); - let f = FunctionDescriptor::new(lib.function(entry).expect("function")); - let d = ComputePipelineDescriptor::new(StageSource::Function(f)); - dev.compile_compute_pipeline(&d, &Budget::standard()) - .unwrap_or_else(|e| panic!("{entry}: {e}")) -} - -/// A bind state of `txt_level_write`: two bytes of level at buffer 0 and, when `levels` is -/// `Some`, a 2D `RGBA16Float` texture of that many levels at texture 0. -fn state(levels: Option) -> BindState { - let mut t = StageTable::default(); - t.buffers.insert( - 0, - BoundBuffer::Bytes { - len: 2, - attribute_stride: None, - }, - ); - if let Some(n) = levels { - let mut facts = TextureFacts::new(TextureType::Type2D, PixelFormat::RGBA16Float); - facts.usage = TextureUsage::SHADER_READ | TextureUsage::SHADER_WRITE; - facts.mipmap_level_count = n; - t.textures.insert( - 0, - BoundTexture::Texture { - facts, - resource_id: None, - }, - ); - } - let mut s = BindState::default(); - s.stages.insert(Stage::Kernel, t); - s -} - -/// The binder plans `txt_level_write`'s level views (one write per element: element `i` a view -/// of level `i` alone, the neutral past the last level or for an unbound slot) and pushes the -/// bound level count; running the module over exactly those writes and push bytes writes the -/// level the buffer names and nothing past the count. Plans of textures with different level -/// counts differ (the shape carries the count). -#[test] -fn the_binder_binds_each_level_and_pushes_the_count() { - let Some(bc) = fixture("txt_level_write") else { - return; - }; - for stem in ["moltenvk-m3", "lavapipe"] { - let dev = device(stem); - let p = profile(stem, DevicePolicy::RESIDENT_TABLES).expect("profile"); - let pipe = pipeline(&dev, &bc, "txt_level_write"); - let (_, m) = typed_module(&bc, "txt_level_write", &p).expect("module"); - let n = max_levels(&p, ImageDim::D2); - let binding = pipe - .layout - .sets - .iter() - .flat_map(|s| s.bindings.iter().map(move |b| (s.set, b))) - .find(|(_, b)| b.source == BindingSource::Texture(tslot(0))) - .map(|(set, b)| (set, b.binding)) - .expect("the texture binding"); - assert_ne!(state(Some(3)).shape(), state(Some(2)).shape(), "{stem}"); - for (levels, lod) in [(Some(3), 2u16), (Some(3), 3), (Some(1), 0), (None, 0)] { - let what = format!("{stem}: {levels:?} levels, lod {lod}"); - let s = state(levels); - let plan = pipe.plan(&dev, &s.shape()).expect("plan"); - let writes: Vec<_> = plan - .descriptors - .iter() - .filter(|w| (w.set, w.binding) == binding) - .collect(); - assert_eq!(writes.len(), n as usize, "{what}"); - let bound = levels.unwrap_or(0); - let mut imgs = Vec::new(); - for (i, w) in writes.iter().enumerate() { - let i = i as u32; - assert_eq!(w.array_element, i, "{what}"); - let extent = match &w.source { - WriteSource::Texture { view, .. } => { - assert!(i < bound, "{what}: element {i}"); - assert_eq!(view.level, Some(i), "{what}"); - [4 >> i, 4 >> i, 1] - } - WriteSource::Neutral(_) => { - assert!(i >= bound, "{what}: element {i}"); - [1, 1, 1] - } - other => panic!("{what}: {other:?}"), - }; - let mut img = Image::new(texture(0), extent, 1, 1, 1).at_element(i); - img.texels.fill(POISON); - imgs.push(img); - } - let (push, spec) = bound_inputs(&pipe, &plan, &s, [1, 1, 1]); - let res = Resources { - buffers: vec![Buffer { - slot: Some(ResourceSlot { - stage: Stage::Kernel, - kind: ResourceKind::Buffer, - index: 0, - }), - address: None, - bytes: lod_bytes(u32::from(lod)), - }], - push, - spec, - }; - let cfg = Config { - workgroups: [1, 1, 1], - ..Config::default() - }; - let (_, out) = run_with_images(&m, &cfg, res, imgs).expect("run"); - for img in &out { - let want = if u32::from(lod) < bound && img.element == u32::from(lod) { - [fl(0.0), fl(0.0), fl(1.0), fl(0.5)] - } else { - POISON - }; - assert_eq!(img.texels[0], want, "{what}: element {}", img.element); - } - } - } -} - -/// The push bytes and specialization values `plan` instantiates for `s` (a dispatch of `groups` -/// one-thread threadgroups), each value by its key. -fn bound_inputs( - pipe: &ComputePipeline, - plan: &BindingPlan, - s: &BindState, - groups: [u32; 3], -) -> (Vec, BTreeMap) { - let cmds = plan - .instantiate_dispatch( - s, - &Dispatch::Threadgroups { - groups, - threads_per_group: [1, 1, 1], - }, - ) - .expect("instantiate"); - let region = &cmds.regions[0]; - let mut push = Vec::new(); - if let Some(w) = region.push_constants.first() { - push = vec![0u8; w.offset as usize + w.bytes.len()]; - push[w.offset as usize..].copy_from_slice(&w.bytes); - } - let ids: BTreeMap = pipe - .stage - .specialization - .constants - .iter() - .map(|c| (c.id, c.key)) - .collect(); - let mut spec = BTreeMap::new(); - for e in ®ion.specialization.entries { - let at = e.offset as usize; - let mut v = [0u8; 8]; - v[..e.size as usize].copy_from_slice(®ion.specialization.data[at..at + e.size as usize]); - spec.insert(ids[&e.constant_id], u64::from_le_bytes(v)); - } - (push, spec) -} - -/// The binder specializes a level-view read's out-of-bounds alpha from the bound texture's -/// format, as it does a checked read's, on profiles whose robustness leaves the coordinates to the -/// device: 1 for `R32Float`, which has no alpha, 0 for `RGBA32Float` and an unbound slot. Running -/// `read_level` over the binder's level views, push bytes, and specialization reads Metal's -/// out-of-bounds texel at a missing level, `(0, 0, 0, 1)` exactly for the format without alpha, and -/// the bound level below the count. -#[test] -fn the_binder_specializes_a_level_reads_alpha_from_the_bound_format() { - let Some(bc) = assemble("level_reads", LEVEL_READS) else { - return; - }; - let key = SpecKey::OutOfBoundsAlpha(tslot(0)); - // p[0] reads (1, 1) of level 1, p[1] (0, 0) of the missing level 5. - let rows: Vec = [[1u32, 1, 1, 0], [0, 0, 5, 0]] - .iter() - .flatten() - .flat_map(|w| w.to_le_bytes()) - .collect(); - let texel = [fl(1.0), fl(2.0), fl(3.0), fl(4.0)]; - for stem in ["moltenvk-m3", "lavapipe"] { - let dev = device(stem); - let p = profile(stem, DevicePolicy::RESIDENT_TABLES).expect("profile"); - assert!(p.fields().images.robust_image_access2, "{stem}"); - let pipe = pipeline(&dev, &bc, "read_level"); - let (_, m) = typed_module(&bc, "read_level", &p).expect("module"); - assert!(pipe - .stage - .specialization - .constants - .iter() - .any(|c| c.key == key)); - let n = max_levels(&p, ImageDim::D2); - for (format, alpha) in [ - (Some(PixelFormat::R32Float), fl(1.0)), - (Some(PixelFormat::RGBA32Float), 0), - (None, 0), - ] { - let what = format!("{stem}: {format:?}"); - let mut t = StageTable::default(); - t.buffers.insert( - 0, - BoundBuffer::Bytes { - len: 32, - attribute_stride: None, - }, - ); - t.buffers.insert( - 1, - BoundBuffer::Bytes { - len: 32, - attribute_stride: None, - }, - ); - if let Some(f) = format { - let mut facts = TextureFacts::new(TextureType::Type2D, f); - facts.usage = TextureUsage::SHADER_READ | TextureUsage::SHADER_WRITE; - facts.mipmap_level_count = 3; - t.textures.insert( - 0, - BoundTexture::Texture { - facts, - resource_id: None, - }, - ); - } - let mut s = BindState::default(); - s.stages.insert(Stage::Kernel, t); - let plan = pipe.plan(&dev, &s.shape()).expect("plan"); - let (push, spec) = bound_inputs(&pipe, &plan, &s, [2, 1, 1]); - assert_eq!(spec.get(&key), Some(&u64::from(alpha != 0)), "{what}"); - let mut imgs = Vec::new(); - for w in plan - .descriptors - .iter() - .filter(|w| matches!(w.ty, crate::vk::DescriptorType::STORAGE_IMAGE)) - { - let i = w.array_element; - let extent = match &w.source { - WriteSource::Texture { view, .. } => { - assert_eq!(view.level, Some(i), "{what}"); - [4 >> i, 4 >> i, 1] - } - WriteSource::Neutral(_) => [1, 1, 1], - other => panic!("{what}: {other:?}"), - }; - let mut img = Image::new(texture(0), extent, 1, 1, 1).at_element(i); - img.texels.fill(if i == 1 && format.is_some() { - texel - } else { - POISON - }); - img.robust = Some([0, 0, 0, alpha]); - imgs.push(img); - } - assert_eq!(imgs.len(), n as usize, "{what}"); - let res = Resources { - buffers: [rows.clone(), vec![0; 32]] - .into_iter() - .enumerate() - .map(|(i, bytes)| Buffer { - slot: Some(ResourceSlot { - stage: Stage::Kernel, - kind: ResourceKind::Buffer, - index: i as u32, - }), - address: None, - bytes, - }) - .collect(), - push, - spec, - }; - let cfg = Config { - workgroups: [2, 1, 1], - ..Config::default() - }; - let (out, _) = run_with_images(&m, &cfg, res, imgs).expect("run"); - let first = if format.is_some() { - texel - } else { - [0, 0, 0, 0] - }; - assert_eq!(words(&out.buffers[1][..16]), first, "{what}: level 1"); - assert_eq!( - words(&out.buffers[1][16..]), - [0, 0, 0, alpha], - "{what}: level 5" - ); - } - } -} - -/// The pushed level count of `plan`'s texture slot 0, as instantiated for `s`. -fn pushed_levels(plan: &BindingPlan, s: &BindState) -> u32 { - let at = plan - .push - .fields - .iter() - .find(|f| f.field == PushField::TextureLevels(tslot(0))) - .map(|f| match f.location { - FieldLocation::PushWindow { offset } => offset as usize, - other => panic!("{other:?}"), - }) - .expect("a level-count field"); - let cmds = plan - .instantiate_dispatch( - s, - &Dispatch::Threadgroups { - groups: [1, 1, 1], - threads_per_group: [1, 1, 1], - }, - ) - .expect("instantiate"); - let w = cmds.regions[0].push_constants.first().expect("push bytes"); - let i = at - w.offset as usize; - u32::from_le_bytes(w.bytes[i..i + 4].try_into().expect("u32")) -} - -/// A level slot binds a texture of any usage at its levels: plain Metal writes a texture made -/// without `ShaderWrite` at every level, through every write form, as one made with it -/// (CoreAnimation's blur textures are `ShaderRead | RenderTarget | BlockWritesOnly`), -/// where the binder bound the neutral there and dropped the writes. Its shape states its levels -/// whatever the usage. A texture with more levels than the views hold is larger than the device's -/// largest 2D image: refused, naming `maxImageDimension2D`. -#[test] -fn level_slots_bind_textures_of_every_usage_the_device_can_hold() { - let Some(bc) = fixture("txt_level_write") else { - return; - }; - let stem = "moltenvk-m3"; - let dev = device(stem); - let p = profile(stem, DevicePolicy::RESIDENT_TABLES).expect("profile"); - let pipe = pipeline(&dev, &bc, "txt_level_write"); - let n = max_levels(&p, ImageDim::D2); - let with_usage = |levels: Option, usage: TextureUsage| { - let mut s = state(levels); - if let Some(BoundTexture::Texture { facts, .. }) = s - .stages - .get_mut(&Stage::Kernel) - .and_then(|t| t.textures.get_mut(&0)) - { - facts.usage = usage; - } - s - }; - let private = - TextureUsage::SHADER_READ | TextureUsage::RENDER_TARGET | TextureUsage::BLOCK_WRITES_ONLY; - for usage in [ - TextureUsage::SHADER_READ, - TextureUsage::RENDER_TARGET, - TextureUsage::BLOCK_WRITES_ONLY, - private, - TextureUsage::empty(), - ] { - let what = format!("{usage:?}"); - let (three, one) = (with_usage(Some(3), usage), with_usage(Some(1), usage)); - assert_ne!(three.shape(), one.shape(), "{what}"); - - let plan = pipe.plan(&dev, &three.shape()).expect("plan"); - let writes: Vec<_> = plan - .descriptors - .iter() - .filter(|w| matches!(w.ty, crate::vk::DescriptorType::STORAGE_IMAGE)) - .collect(); - assert_eq!(writes.len(), n as usize, "{what}"); - for (i, w) in writes.iter().enumerate() { - match &w.source { - WriteSource::Texture { view, .. } => { - assert!(i < 3, "{what}: element {i}"); - assert_eq!(view.level, Some(i as u32), "{what}"); - } - WriteSource::Neutral(_) => assert!(i >= 3, "{what}: element {i}"), - other => panic!("{what}: {other:?}"), - } - } - assert!( - !plan.diagnostics.iter().any( - |d| matches!(d, PlanDiagnostic::IncompatibleBinding { slot, .. } if *slot == tslot(0)) - ), - "{what}: {:?}", - plan.diagnostics - ); - assert_eq!(pushed_levels(&plan, &three), 3, "{what}"); - } - - let s = state(Some(3)); - let plan = pipe.plan(&dev, &s.shape()).expect("plan"); - assert_eq!(pushed_levels(&plan, &s), 3); - - let want = Unsupported::needs( - Feature::Lowering(LowerFamily::Texture), - Capability::Limit { - limit: VkLimit::MaxImageDimension2D, - required: 1 << n, - available: u64::from(p.fields().limits.max_image_dimension_2d), - }, - ); - match pipe.plan(&dev, &state(Some(n + 1)).shape()) { - Err(BindError::Unsupported(u)) => { - assert_eq!((u.feature, u.needs), (want.feature, want.needs)) - } - other => panic!("{:?}", other.map(|_| ())), - } -} diff --git a/crates/metal2vulkan/src/tests/engine_texture_oob.rs b/crates/metal2vulkan/src/tests/engine_texture_oob.rs index c08e037b2..c4ade49e2 100644 --- a/crates/metal2vulkan/src/tests/engine_texture_oob.rs +++ b/crates/metal2vulkan/src/tests/engine_texture_oob.rs @@ -31,27 +31,22 @@ use std::collections::BTreeMap; use std::sync::atomic::{AtomicU64, Ordering}; -use crate::bind::{BindState, Dispatch, ResourceClass, TextureFacts, UsedResource, WriteSource}; -use crate::budget::Budget; use crate::device::profile::DeviceProfile; use crate::device::requirements::VkFeature; use crate::device::{Device, DeviceDescription, DevicePolicy}; use crate::error::{Capability, Error, Feature, LowerFamily, Unsupported}; -use crate::library::Library; use crate::lower::select::{LowerInputs, Plan}; -use crate::metal::{PixelFormat, TextureType}; +use crate::metal::PixelFormat; use crate::pipeline::facts::RuntimeFact; use crate::pipeline::interface::PushLoc; use crate::pipeline::lower_inputs::{StorageImageChoice, StorageImageClass}; use crate::pipeline::sym::{ - Axis, HandleClass, PushField, ResourceKind, ResourceSlot, SlotClass, SlotRef, SpecKey, Stage, - SyntheticBinding, + Axis, PushField, ResourceKind, ResourceSlot, SlotClass, SlotRef, SpecKey, Stage, }; use crate::pipeline::testing::{ compile, engine_dir, link_and_validate, llvm_assemble, typed_module, typed_module_with, AssembleError, }; -use crate::pipeline::{ComputePipelineDescriptor, FunctionDescriptor, StageSource}; use crate::spirv::interp::{run_with_images, Buffer, Config, Image, Order, Resources}; use crate::spirv::ir::TypedModule; use crate::spirv::testing::committed_profiles; @@ -2057,200 +2052,6 @@ fn only_an_observed_alpha_is_specialized() { } } -/// An argument-buffer texture's format is the resident texture's, which the binder states per -/// handle-table entry, its out-of-bounds-alpha flag: a heap read the shader checks whose alpha it -/// observes reads Metal's out-of-bounds alpha from the entry its handle names. End to end on the -/// interpreter, the binder's table bytes for two resident textures (an `R32Float`, whose missing -/// alpha Metal reads as 1, and an `RGBA32Float`), the emitted search, and reads in and past the -/// texture; a missed id reads the null texture's zero. Where the device's robustness is Metal's -/// texel the search stays the element's alone. -#[test] -fn a_heap_read_takes_its_out_of_bounds_alpha_from_its_table_entry() { - let bc = match llvm_assemble(&engine_dir().join("handles.ll")) { - Ok(b) => b, - Err(AssembleError::Missing(why)) => { - eprintln!("SKIPPED: {why}"); - return; - } - Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected handles.ll: {why}"), - }; - const NO_ALPHA: u64 = 0x0000_0001_0000_0010; - const ALPHA: u64 = 0x0000_0001_0000_0020; - const MISSED: u64 = 0x0000_0002_0000_0000; - let entry = "argument_buffer_read"; - let unrobust = [VkFeature::RobustImageAccess, VkFeature::RobustImageAccess2]; - let devices = [ - ("moltenvk-m3", device("moltenvk-m3", &[])), - ( - "moltenvk-m3 robust1", - device("moltenvk-m3", &[VkFeature::RobustImageAccess2]), - ), - ("moltenvk-m3 unrobust", device("moltenvk-m3", &unrobust)), - ("runtime-floor", device("runtime-floor", &[])), - ]; - let mut ran = Vec::new(); - for (stem, dev) in devices { - let lib = Library::from_air(&bc).expect("library"); - let f = lib.function(entry).expect("entry"); - let desc = - ComputePipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new(f))); - let pipe = match dev.compile_compute_pipeline(&desc, &Budget::standard()) { - Ok(p) => p, - Err(Error::Unsupported(u)) if u.feature == Feature::ArgumentBufferTextures => continue, - Err(e) => panic!("{stem}: {e}"), - }; - // Members: token 1 (element 1), then token 2 (element 2). - let used = |token, pf, id| { - let mut u = UsedResource::new( - ResourceClass::Texture(TextureFacts::new(TextureType::Type2D, pf)), - token, - ); - u.resource_id = Some(id); - u - }; - let state = BindState { - used_resources: vec![ - used(1, PixelFormat::R32Float, NO_ALPHA), - used(2, PixelFormat::RGBA32Float, ALPHA), - ], - ..Default::default() - }; - let bplan = pipe.plan(&dev, &state.shape()).expect("plan"); - let dispatch = Dispatch::Threadgroups { - groups: [4, 1, 1], - threads_per_group: [1, 1, 1], - }; - let cmds = bplan - .instantiate_dispatch(&state, &dispatch) - .expect("dispatch"); - let (set, binding) = bplan - .descriptors - .iter() - .find_map(|d| { - matches!(d.source, WriteSource::HandleTable { .. }).then_some((d.set, d.binding)) - }) - .expect("a handle table"); - let table = cmds - .descriptor_bytes - .iter() - .find(|b| (b.set, b.binding) == (set, binding)) - .expect("table bytes") - .bytes - .clone(); - - let (plan, m) = typed_module(&bc, entry, dev.profile()).expect("module"); - let class = class(dev.profile(), false); - assert_eq!( - plan.families.access.heap_alpha, - class != Class::Device, - "{stem}: the search carries the flag only where the shader checks the read" - ); - let heap = plan - .families - .texture - .heap - .values() - .find_map(|h| h.class) - .expect("a heap class"); - let slot = ResourceSlot { - stage: Stage::Kernel, - kind: ResourceKind::Heap(HandleClass::Image(heap)), - index: 0, - }; - // Element 0 is the class's neutral; 1 views the `R32Float` texture (lanes 1 and 2 read 0, - // lane 3 reads 1 through its view), 2 the `RGBA32Float` one. Each is 2 x 1. - let element = |e: u32, extent: [u32; 3], texel: &dyn Fn(u32) -> [u32; 4], alpha: u32| { - let mut img = Image::new(slot, extent, 1, 1, 1).at_element(e); - for (x, t) in img.texels.iter_mut().enumerate() { - *t = texel(x as u32); - } - img.robust = robust(class, alpha); - img - }; - let images = vec![ - element(0, [1, 1, 1], &|_| [0; 4], 0), - element( - 1, - [2, 1, 1], - &|x| [fl(3.0 + x as f32), 0, 0, fl(1.0)], - fl(1.0), - ), - element( - 2, - [2, 1, 1], - &|x| [fl(5.0 + x as f32), fl(6.0), fl(7.0), fl(8.0)], - 0, - ), - ]; - for (id, inside, outside) in [ - ( - NO_ALPHA, - [[fl(3.0), 0, 0, fl(1.0)], [fl(4.0), 0, 0, fl(1.0)]], - [0, 0, 0, fl(1.0)], - ), - ( - ALPHA, - [ - [fl(5.0), fl(6.0), fl(7.0), fl(8.0)], - [fl(6.0), fl(6.0), fl(7.0), fl(8.0)], - ], - [0; 4], - ), - (MISSED, [[0; 4], [0; 4]], [0; 4]), - ] { - let mut spec = BTreeMap::new(); - for axis in [Axis::X, Axis::Y, Axis::Z] { - spec.insert(SpecKey::LocalSize(axis), 1); - } - spec.insert(SpecKey::FlatLocalSize, 1); - let buffer = |kind, bytes| Buffer { - slot: Some(ResourceSlot { - stage: Stage::Kernel, - kind, - index: 0, - }), - address: None, - bytes, - }; - let mut out = buffer(ResourceKind::Buffer, vec![0xAB; 4 * 16]); - if let Some(s) = out.slot.as_mut() { - s.index = 1; - } - let res = Resources { - buffers: vec![ - buffer(ResourceKind::Buffer, id.to_le_bytes().to_vec()), - out, - buffer( - ResourceKind::Synthetic(SyntheticBinding::HandleTable), - table.clone(), - ), - ], - push: vec![0u8; plan.push.push_range.map_or(0, |(_, end)| end as usize)], - spec, - }; - for order in [Order::Forward, Order::Reverse] { - let cfg = Config { - workgroups: [4, 1, 1], - order, - ..Config::default() - }; - let (o, _) = run_with_images(&m, &cfg, res.clone(), images.clone()) - .unwrap_or_else(|e| panic!("{stem}: {id:#x}: {e:?}")); - // Threads 0 and 1 read in bounds, 2 and 3 past the texture's width. - let want: Vec = [inside[0], inside[1], outside, outside] - .iter() - .flat_map(|t| Out::Vec4.bytes(*t)) - .collect(); - assert_eq!(o.buffers[1], want, "{stem}: id {id:#x}, {order:?}"); - } - } - ran.push(class); - } - ran.sort(); - ran.dedup(); - assert_eq!(ran, ALL); -} - /// [`EDGE_READS`] with `edge_2d`'s read edited by hand to take 16-bit coordinates and offset /// `(-1, -1)`. Metal 4.1 has no such overload: its `read(sampler, ...)` takes `int` coordinates, /// and `metal -std=metal4.1` rejects a `short2` one. diff --git a/crates/metal2vulkan/src/tests/engine_texture_oob/through.rs b/crates/metal2vulkan/src/tests/engine_texture_oob/through.rs index 159c1e525..de6170733 100644 --- a/crates/metal2vulkan/src/tests/engine_texture_oob/through.rs +++ b/crates/metal2vulkan/src/tests/engine_texture_oob/through.rs @@ -773,317 +773,6 @@ fn every_read_through_a_sampler_validates_or_is_refused_typed() { assert!(heap > 0, "no argument buffer's texture read translated"); } -/// The handle table's entry `(id, element, flags)` list of `bytes`. -fn table_entries(bytes: &[u8]) -> Vec<(u64, u32, u32)> { - use crate::memory::handles::TABLE_ENTRY_BYTES; - bytes - .as_chunks::<{ TABLE_ENTRY_BYTES as usize }>() - .0 - .iter() - .map(|e| { - let w = |i: usize| u32::from_le_bytes(e[4 * i..4 * i + 4].try_into().expect("word")); - (u64::from(w(0)) | u64::from(w(1)) << 32, w(2), w(3)) - }) - .collect() -} - -/// An argument buffer's texture read through a sampler hands back Metal's border texels of the -/// resident texture, its pixel format's and swizzle's, which the binder writes in the texture's -/// handle-table entry (`memory::handles::FLAG_BORDER_TEXELS`) and the read loads from the entry its -/// handle names (the search's indexed form, `memory::handles::Lookup::Indexed`). End to end on the -/// interpreter: the binder's table bytes for two resident textures of two levels, an `RGBA32Float` -/// made with the swizzle `(G, R, 1, 0)` and an `R32Float`, the emitted search, and reads in and -/// past each through `clamp_to_zero` (`rt_heap_zero`), an opaque white `clamp_to_border` -/// (`rt_heap_ow`), and a runtime sampler (`rt_heap_arg`) of each border color, of `clamp_to_edge`, -/// and of a border with a mip filter; a missed id reads zero in every lane. Before the entry held -/// them, the swizzled texture read `(0, 0, 0, 0)` past its edge through `clamp_to_zero`, where the -/// M3 reads `(0, 0, 1, 0)`, and the other two reads were refused. -#[test] -fn an_argument_buffer_texture_reads_its_border_texels_from_its_table_entry() { - use crate::memory::handles::Lookup; - use crate::metal::TextureSwizzle as S; - let Some(bc) = read_through() else { - return; - }; - const SWIZZLED: u64 = 0x0000_0001_0000_0010; - const RED: u64 = 0x0000_0001_0000_0020; - const MISSED: u64 = 0x0000_0002_0000_0000; - let swizzle = TextureSwizzleChannels { - red: S::Green, - green: S::Red, - blue: S::One, - alpha: S::Zero, - }; - let textures = [ - (SWIZZLED, PixelFormat::RGBA32Float, swizzle), - (RED, PixelFormat::R32Float, TextureSwizzleChannels::DEFAULT), - ]; - let unrobust = [VkFeature::RobustImageAccess, VkFeature::RobustImageAccess2]; - let devices = [ - ("moltenvk-m3", device("moltenvk-m3", &[])), - ( - "moltenvk-m3 robust1", - device("moltenvk-m3", &[VkFeature::RobustImageAccess2]), - ), - ("moltenvk-m3 unrobust", device("moltenvk-m3", &unrobust)), - ("lavapipe", device("lavapipe", &[])), - ("amd-780m-radv", device("amd-780m-radv", &[])), - ]; - // Inside, past each edge, at level 1 (the base level's texel without a mip filter), past the - // last level. - let base = |border: Want| { - vec![ - ([1, 2, 0, 0], at(0, [1, 2, 0])), - ([4, 0, 0, 0], border), - ([int(-1), 3, 0, 0], border), - ([3, 3, 0, 1], at(0, [3, 3, 0])), - ([0, 0, 0, 2], Want::Zero), - ] - }; - let edge = vec![ - ([1, 2, 0, 0], at(0, [1, 2, 0])), - ([4, 0, 0, 0], at(0, [3, 0, 0])), - ([int(-1), 3, 0, 0], at(0, [0, 3, 0])), - ([0, 0, 0, 2], Want::Zero), - ]; - // Under a mip filter the read reads its own level, 2 x 2. - let mip = |border: Want| { - vec![ - ([1, 0, 0, 1], at(1, [1, 0, 0])), - ([3, 3, 0, 1], border), - ([0, 0, 0, 2], Want::Zero), - ] - }; - let mut reads: Vec<(&str, Option, Vec<([u32; 4], Want)>)> = vec![ - ("rt_heap_zero", None, base(Want::Border(TB))), - ("rt_heap_ow", None, base(Want::Border(OW))), - ("rt_heap_arg", Some(word([EDGE; 3], OW, 0)), edge), - ( - "rt_heap_arg", - Some(word([ZERO; 3], OB, 0)), - base(Want::Border(OB)), - ), - ( - "rt_heap_arg", - Some(word([BORDER, ZERO, BORDER], OW, 1)), - mip(Want::Border(OW)), - ), - ]; - for b in [TB, OB, OW] { - reads.push(( - "rt_heap_arg", - Some(word([BORDER; 3], b, 0)), - base(Want::Border(b)), - )); - } - let not_implemented = Unsupported::not_implemented(Feature::ArgumentBufferTextures); - let mut ran = Vec::new(); - let mut entries_ran = std::collections::BTreeSet::new(); - for (stem, dev) in devices { - for (entry, sampler, rows) in &reads { - let lib = Library::from_air(&bc).expect("library"); - let f = lib.function(entry).expect("entry"); - let desc = - ComputePipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new(f))); - let pipe = match dev.compile_compute_pipeline(&desc, &Budget::standard()) { - Ok(p) => p, - // A device without the descriptor-indexing features a handle heap needs. - Err(Error::Unsupported(u)) - if u.feature == Feature::ArgumentBufferTextures - && u.needs != not_implemented.needs => - { - continue - } - Err(e) => panic!("{stem}: {entry}: {e}"), - }; - let used = |token, (id, pf, swizzle): (u64, PixelFormat, TextureSwizzleChannels)| { - let mut facts = TextureFacts::new(TextureType::Type2D, pf); - facts.mipmap_level_count = 2; - facts.swizzle = swizzle; - let mut u = UsedResource::new(ResourceClass::Texture(facts), token); - u.resource_id = Some(id); - u - }; - let state = BindState { - used_resources: vec![used(1, textures[0]), used(2, textures[1])], - ..Default::default() - }; - let bplan = pipe.plan(&dev, &state.shape()).expect("plan"); - let dispatch = Dispatch::Threadgroups { - groups: [rows.len() as u32, 1, 1], - threads_per_group: [1, 1, 1], - }; - let cmds = bplan - .instantiate_dispatch(&state, &dispatch) - .expect("dispatch"); - let (set, binding) = bplan - .descriptors - .iter() - .find_map(|d| { - matches!(d.source, WriteSource::HandleTable { .. }) - .then_some((d.set, d.binding)) - }) - .expect("a handle table"); - let table = cmds - .descriptor_bytes - .iter() - .find(|b| (b.set, b.binding) == (set, binding)) - .expect("table bytes") - .bytes - .clone(); - let entries = table_entries(&table); - let element = |id: u64| { - entries - .iter() - .find(|e| e.0 == id) - .map(|e| e.1) - .expect("a listed id") - }; - - let (plan, m) = typed_module(&bc, entry, dev.profile()).expect("module"); - assert!( - matches!(plan.families.access.lookup(), Lookup::Indexed { .. }), - "{stem}: {entry}: the search names each handle's entry" - ); - let class = class(dev.profile(), false); - let heap = plan - .families - .texture - .heap - .values() - .find_map(|h| h.class) - .expect("a heap class"); - let slot = ResourceSlot { - stage: Stage::Kernel, - kind: ResourceKind::Heap(HandleClass::Image(heap)), - index: 0, - }; - // Element 0 is the class's neutral; each texture's element views it (the swizzled - // one's texels as its view reads them), 4 x 4 and 2 x 2, each texel naming itself. - let image = |e: u32, pf: PixelFormat| { - let mut img = Image::new(slot, [4, 4, 1], 1, 2, 1).at_element(e); - for (i, t) in img.texels.iter_mut().enumerate() { - let i = i as f32; - *t = match pf { - PixelFormat::R32Float => [fl(1.0 + i), 0, 0, fl(1.0)], - _ => [fl(1.0 + i), fl(100.0 + i), fl(200.0 + i), fl(300.0 + i)], - }; - } - let alpha = match pf { - PixelFormat::R32Float => fl(1.0), - _ => 0, - }; - img.robust = robust(class, alpha); - img - }; - let mut neutral = Image::new(slot, [1, 1, 1], 1, 1, 1).at_element(0); - neutral.robust = robust(class, 0); - let mut images = vec![neutral]; - for (id, pf, _) in textures { - images.push(image(element(id), pf)); - } - images.sort_by_key(|i| i.element); - let ids = textures - .iter() - .map(|&(id, pf, swizzle)| (id, Some((pf, swizzle)))) - .chain([(MISSED, None)]); - for (id, texture) in ids { - let bits = texture.map_or(0, |(pf, swizzle)| { - border_texels(pf, swizzle).expect("border texels") - }); - let img = match texture { - Some(_) => images.iter().find(|i| i.element == element(id)), - None => None, - }; - let mut spec = BTreeMap::new(); - for axis in [Axis::X, Axis::Y, Axis::Z] { - spec.insert(SpecKey::LocalSize(axis), 1); - } - spec.insert(SpecKey::FlatLocalSize, 1); - if let Some(w) = sampler { - let fields = SamplerWord::READ_STATE; - let key = SpecKey::SamplerState { - slot: SAMPLER, - fields, - }; - spec.insert(key, u64::from(w & fields)); - } - let buffer = |kind, index, bytes| Buffer { - slot: Some(ResourceSlot { - stage: Stage::Kernel, - kind, - index, - }), - address: None, - bytes, - }; - let p_rows: Vec = rows - .iter() - .flat_map(|(r, _)| r.iter().flat_map(|w| w.to_le_bytes())) - .collect(); - let res = Resources { - buffers: vec![ - buffer(ResourceKind::Buffer, 0, p_rows), - buffer(ResourceKind::Buffer, 1, vec![0xAB; rows.len() * 16]), - buffer(ResourceKind::Buffer, 2, id.to_le_bytes().to_vec()), - buffer( - ResourceKind::Synthetic(SyntheticBinding::HandleTable), - 0, - table.clone(), - ), - ], - push: vec![0u8; plan.push.push_range.map_or(0, |(_, end)| end as usize)], - spec, - }; - let (bufs, _) = run_both(&m, &res, &images, rows.len() as u32, stem); - let want: Vec = rows - .iter() - .flat_map(|(_, want)| { - let t = match (want, img) { - (_, None) | (Want::Zero, _) => [0; 4], - (Want::At((level, layer, sample, xyz)), Some(img)) => { - let i = - img.index(*level, *layer, *sample, *xyz).expect("in bounds"); - img.texels[i] - } - (Want::Border(b), Some(_)) => { - std::array::from_fn(|c| match bits >> (3 * c as u32 + b) & 1 { - 1 => fl(1.0), - _ => 0, - }) - } - (Want::Oob, Some(_)) => panic!("no sample index here"), - }; - Out::Vec4.bytes(t) - }) - .collect(); - for (i, (got, want)) in bufs[1] - .as_chunks::<16>() - .0 - .iter() - .zip(want.as_chunks::<16>().0) - .enumerate() - { - assert_eq!( - got, want, - "{stem}: {entry} {sampler:?} id {id:#x} row {i} {:?}", - rows[i].0 - ); - } - } - ran.push(class); - entries_ran.insert(*entry); - } - } - ran.sort(); - ran.dedup(); - assert_eq!(ran, ALL); - assert_eq!( - entries_ran.into_iter().collect::>(), - ["rt_heap_arg", "rt_heap_ow", "rt_heap_zero"] - ); -} - /// Metal's border texels per format (`metal::sampler::border_texels`), as the M3 Max read them /// through `clamp_to_border` and `clamp_to_zero`: the color in the format's channels (a missing /// red, green or blue 0, a missing alpha 1), `A8Unorm`'s alpha the color's red, a depth format diff --git a/crates/metal2vulkan/src/tests/engine_texture_ulong.rs b/crates/metal2vulkan/src/tests/engine_texture_ulong.rs index c0da1d1f1..3aee63655 100644 --- a/crates/metal2vulkan/src/tests/engine_texture_ulong.rs +++ b/crates/metal2vulkan/src/tests/engine_texture_ulong.rs @@ -28,15 +28,11 @@ use std::collections::BTreeMap; -use crate::bind::{BindState, BoundBuffer, BoundTexture, StageTable, TextureFacts}; -use crate::budget::Budget; use crate::device::profile::DeviceProfile; use crate::device::requirements::VkFeature; use crate::device::{Device, DeviceDescription, DevicePolicy}; use crate::error::{Error, Feature, Needs, Unsupported}; -use crate::library::Library; use crate::lower::select::Plan; -use crate::metal::{PixelFormat, TextureType, TextureUsage}; use crate::pipeline::interface::{PushLoc, SlotInterface}; use crate::pipeline::sym::{ Axis, PushField, ResourceKind, ResourceSlot, SampledType, SlotClass, SpecKey, Stage, @@ -44,9 +40,6 @@ use crate::pipeline::sym::{ use crate::pipeline::testing::{ compile, engine_dir, link_and_validate, llvm_assemble, typed_module, AssembleError, }; -use crate::pipeline::{ - ComputePipeline, ComputePipelineDescriptor, FunctionDescriptor, StageSource, -}; use crate::spirv::interp::{run_with_images, Buffer, Config, Image, Order, Resources}; use crate::spirv::ir::TypedModule; use crate::spirv::testing::committed_profiles; @@ -504,91 +497,3 @@ fn ulong_atomics_are_refused_on_every_device() { } assert!(refused >= profiles.len(), "{refused}"); } - -fn device(stem: &str) -> Device { - 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 desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); - Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device") -} - -fn pipeline(dev: &Device, bc: &[u8], entry: &str) -> ComputePipeline { - let lib = Library::from_air(bc).expect("library"); - let f = FunctionDescriptor::new(lib.function(entry).expect("function")); - let d = ComputePipelineDescriptor::new(StageSource::Function(f)); - dev.compile_compute_pipeline(&d, &Budget::standard()) - .unwrap_or_else(|e| panic!("{entry}: {e}")) -} - -/// A bind state with `RG32Uint` textures of `types` at texture slots 0, 1, ... (`None`: left -/// unbound), Metal's usage for atomics, and a buffer at slot 0. -fn ulong_state(types: &[Option]) -> BindState { - let mut t = StageTable::default(); - t.buffers.insert( - 0, - BoundBuffer::Bytes { - len: 4096, - attribute_stride: None, - }, - ); - for (i, ty) in types.iter().enumerate() { - let Some(ty) = *ty else { continue }; - let mut facts = TextureFacts::new(ty, PixelFormat::RG32Uint); - facts.usage = - TextureUsage::SHADER_READ | TextureUsage::SHADER_WRITE | TextureUsage::SHADER_ATOMIC; - t.textures.insert( - i as u32, - BoundTexture::Texture { - facts, - resource_id: None, - }, - ); - } - let mut s = BindState::default(); - s.stages.insert(Stage::Kernel, t); - s -} - -/// A texture buffer made with a swizzle at a slot the function reads as `ulong` texels is refused -/// (`Unsupported { feature: TextureSwizzle }`): the read applies no swizzle, and Metal's swizzled -/// `ulong` texel is not measured. Unswizzled, it binds. -#[test] -fn a_swizzled_texture_buffer_read_as_ulong_is_refused() { - use crate::metal::{TextureSwizzle as S, TextureSwizzleChannels as C}; - let Some(bc) = fixture("unk_ulong_rw") else { - return; - }; - let dev = device("amd-780m-radv"); - let rw = pipeline(&dev, &bc, "unk_ulong_rw"); - let state = |swizzle| { - let mut t = ulong_state(&[]); - t.stages - .get_mut(&Stage::Kernel) - .expect("kernel") - .textures - .insert( - 5, - BoundTexture::Buffer { - pixel_format: PixelFormat::RG32Uint, - offset: 0, - length: 256, - bytes_per_row: 256, - resource_id: None, - swizzle, - parts: 1, - }, - ); - t - }; - rw.plan(&dev, &state(C::DEFAULT).shape()).expect("plan"); - let bgr1 = C::new(S::Blue, S::Green, S::Red, S::One); - match rw.plan(&dev, &state(bgr1).shape()) { - Err(crate::error::BindError::Unsupported(u)) => assert_eq!( - u, - crate::error::Unsupported::not_implemented(Feature::TextureSwizzle) - ), - other => panic!("{other:?}"), - } -} diff --git a/crates/metal2vulkan/src/tests/engine_threadgroup_floats.rs b/crates/metal2vulkan/src/tests/engine_threadgroup_floats.rs index eb1fdb962..4aaaedef0 100644 --- a/crates/metal2vulkan/src/tests/engine_threadgroup_floats.rs +++ b/crates/metal2vulkan/src/tests/engine_threadgroup_floats.rs @@ -18,12 +18,8 @@ use std::collections::BTreeMap; use std::sync::atomic::{AtomicU64, Ordering}; -use crate::bind::{BindState, BoundBuffer, StageTable}; -use crate::budget::Budget; use crate::device::profile::DeviceProfile; use crate::device::{Device, DevicePolicy}; -use crate::error::{BindError, Feature}; -use crate::library::Library; use crate::lower::select::Plan; use crate::memory::arena::TgWords; use crate::pipeline::interface::PushLoc; @@ -31,7 +27,6 @@ use crate::pipeline::sym::{Axis, PushField, ResourceKind, ResourceSlot, SpecKey, use crate::pipeline::testing::{ compile, description, link_and_validate, llvm_assemble, typed_module, AssembleError, }; -use crate::pipeline::{ComputePipelineDescriptor, FunctionDescriptor, StageSource}; use crate::spirv::interp::{run, Buffer, Config, Order, Resources, SubgroupSize}; use crate::spirv::ir::TypedModule; @@ -548,69 +543,6 @@ fn no_threadgroup_access_is_contained_through_from_queries() { } } -/// The array is Metal's allocation: through `from_queries`, a region filling `maxComputeSharedMemorySize` is planned and one 16 bytes longer is refused -/// (`ThreadgroupMemorySize`). A static arena two words short of the limit is an array of its own -/// words. -#[test] -fn the_float_array_is_metals_allocation() { - let Some(bc) = assemble("tg_region", ®ion_kernel()) else { - return; - }; - for stem in PROFILES { - let dev = queried_device(stem); - let what = stem; - let lib = Library::from_air(&bc).expect("library"); - let f = lib.function("tg_region").expect("function"); - let d = ComputePipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new(f))); - let pipe = dev - .compile_compute_pipeline(&d, &Budget::standard()) - .unwrap_or_else(|e| panic!("{what}: {e}")); - assert_eq!( - pipe.metal_info.static_threadgroup_memory_length, 0, - "{what}" - ); - let state = |len: u32| { - let mut t = StageTable::default(); - t.buffers.insert( - 0, - BoundBuffer::Buffer { - length: 192 * 4, - offset: 0, - gpu_address: 0, - device_address: None, - attribute_stride: None, - }, - ); - t.threadgroup_lengths.insert(0, len); - let mut s = BindState::default(); - s.stages.insert(Stage::Kernel, t); - s - }; - let max = dev.profile().fields().limits.max_compute_shared_memory_size; - assert!( - pipe.plan(&dev, &state(max).shape()).is_ok(), - "{what}: exactly full" - ); - match pipe.plan(&dev, &state(max + 16).shape()) { - Err(BindError::Unsupported(u)) => { - assert_eq!(u.feature, Feature::ThreadgroupMemorySize, "{what}"); - } - other => panic!("{what}: {other:?}"), - } - let prof = queried(stem); - let words = prof.fields().limits.max_compute_shared_memory_size / 4; - let what = format!("a static arena of {} words on {stem}", words - 2); - let Some(big) = assemble("tg_static", &static_kernel(words - 2)) else { - return; - }; - let a = compile(&big, "tg_static", &prof).unwrap_or_else(|e| panic!("{what}: {e}")); - link_and_validate(&a, &prof).unwrap_or_else(|e| panic!("{what}: L3: {e}")); - let s = shape(&a.module.words); - assert_eq!(s.float_arrays, vec![Some(32)], "{what}: {s:?}"); - assert_eq!(s.lengths, vec![words - 2], "{what}: {s:?}"); - } -} - /// An arena filling the workgroup limit answers every word in range: a `[[threadgroup(0)]]` /// region of the limit's bytes, and a static arena two words short of it, every word stored and /// loaded back through `from_queries` ([`FILL`]), as a scalar and as a `float4`. diff --git a/crates/metal2vulkan/src/tests/engine_tile.rs b/crates/metal2vulkan/src/tests/engine_tile.rs index 8315eab7a..00d7caf0d 100644 --- a/crates/metal2vulkan/src/tests/engine_tile.rs +++ b/crates/metal2vulkan/src/tests/engine_tile.rs @@ -36,11 +36,10 @@ use std::collections::BTreeMap; -use crate::bind::{BindState, BindingPlan, Dispatch, ImageblockSize, StageTable, WriteSource}; use crate::budget::Budget; use crate::device::profile::DeviceProfile; use crate::device::{Device, DeviceDescription, DevicePolicy}; -use crate::error::{BindError, DescriptorError, Error, Feature, MetalAnswer, Needs, RuntimeInput}; +use crate::error::{DescriptorError, Error, Feature, MetalAnswer, Needs, RuntimeInput}; use crate::library::Library; use crate::lower::select::{LowerInputs, Plan}; use crate::lower::texture::TexelClass; @@ -58,7 +57,6 @@ use crate::pipeline::{ use crate::spirv::interp::{run_with_images, Buffer, Config, Image, Order, Resources}; use crate::spirv::ir::TypedModule; use crate::spirv::testing::{committed_profiles, refuses_threadgroup_memory}; -use crate::vk; fn assemble(stem: &str) -> Option> { let path = engine_dir().join(format!("{stem}.ll")); @@ -497,66 +495,6 @@ fn an_aliased_layout_reads_each_attachment_at_its_member() { assert!(ran > 0); } -/// A float attachment is bound through the unsigned-integer format of its channels and widths, -/// so the dispatch moves its texels' bits: Vulkan would decode a float view's texel to a value, -/// keeping neither a NaN's payload nor, in a shader that flushes its inputs, a denormal. The -/// pipeline records its aliased layout's size, a tile state's `imageblockSampleLength`. -#[test] -fn a_float_attachment_is_bound_through_its_bits() { - let Some(bc) = assemble("k10ts_alias_probe") else { - return; - }; - let formats = [ - Some(PixelFormat::R16Float), - Some(PixelFormat::R32Float), - Some(PixelFormat::RGBA16Float), - Some(PixelFormat::R16Float), - ]; - let views = [ - vk::Format::R16_UINT, - vk::Format::R32_UINT, - vk::Format::R16G16B16A16_UINT, - vk::Format::R16_UINT, - ]; - let mut planned = 0; - for stem in ["moltenvk-m3", "lavapipe", "amd-rdna2-apu-radv"] { - let dev = device(stem); - let d = descriptor(&bc, "k10ts_alias_probe", &formats); - let pipe = match dev.compile_tile_pipeline(&d, &Budget::standard()) { - Ok(p) => p, - // A profile without the extended storage formats refuses the 16-bit views. - Err(Error::Unsupported(u)) if u.feature == Feature::Format => continue, - Err(e) => panic!("{stem}: {e}"), - }; - // The aliased layout's size, a tile state's sample length whatever the formats pack to - // (18 here), as Metal answers for this struct and these formats. - assert!( - pipe.dependencies - .iter() - .any(|x| x.fact == RuntimeFact::AliasedImageblock { data_size: 24 }), - "{stem}" - ); - let mut s = BindState::default(); - s.stages.insert(Stage::Kernel, StageTable::default()); - s.imageblock_size = ImageblockSize::new(16, 16); - s.render_area = [16, 16]; - let plan = pipe.plan(&dev, &s.shape()).expect("plan"); - for (c, view) in views.into_iter().enumerate() { - assert!( - plan.descriptors.iter().any(|w| w.source - == WriteSource::TileAttachment { - color_index: c as u32, - format: view, - }), - "{stem} {c}: {:?}", - plan.descriptors - ); - } - planned += 1; - } - assert!(planned > 0); -} - /// A tile function's `[[threadgroup(n)]]` argument is its tile's threadgroup memory, which the /// render pass keeps: the function compiles, recording the argument's fact, where a tile function /// that declares a threadgroup variable is refused as Metal refuses its pipeline. The same kernels @@ -767,143 +705,6 @@ fn a_tiles_threadgroup_memory_persists_across_dispatches() { assert!(ran > 0); } -/// The binder places a tile function's threadgroup arguments where the encoder set them: it -/// specializes each offset, the tile's bytes (the pass's length rounded up to 16) and the tiles -/// across the render area, and binds the pass's tile memory of every tile's bytes. An argument's -/// length takes no part in the layout and bounds no access, as plain Metal's does not, so a length -/// that is not a multiple of 16 and one that ends past the tile's memory are both planned at their -/// offset (plain Metal on an M3 Max under macOS 27.0.1 takes every length, and reads zero from the -/// tile's memory's end on, which the arena's containment gives). Every offset is planned too, where -/// plain Metal begins the argument: at the offset floored to a multiple of 4, with no clamp, since -/// the containment reads zero past the tile's memory and Metal's own arithmetic wraps at 2^32. An -/// argument the encoder did not set is refused, and so is a tile memory past one storage-buffer -/// descriptor's range. -#[test] -fn a_tile_pipeline_places_its_threadgroup_arguments() { - use crate::bind::{TileThreadgroupArgument, TileThreadgroupMemory}; - let Some(bc) = assemble("cfit_tile_memory") else { - return; - }; - let formats = [Some(PixelFormat::R32Uint)]; - let d = descriptor(&bc, "cfit_tile_memory_shift", &formats); - let state = |length: u32, arguments: &[(u32, u32, u32)]| { - let mut s = BindState::default(); - s.stages.insert(Stage::Kernel, StageTable::default()); - s.imageblock_size = ImageblockSize::new(16, 16); - s.render_area = [40, 24]; - let mut memory = TileThreadgroupMemory { - length, - arguments: std::collections::BTreeMap::new(), - }; - for &(index, length, offset) in arguments { - memory - .arguments - .insert(index, TileThreadgroupArgument { length, offset }); - } - s.tile_threadgroup = memory; - s - }; - for stem in ["moltenvk-m3", "lavapipe", "runtime-floor"] { - let dev = device(stem); - let pipe = dev - .compile_tile_pipeline(&d, &Budget::standard()) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - for index in [0, 1] { - assert!( - pipe.dependencies - .iter() - .any(|x| x.fact == RuntimeFact::TileThreadgroupMemory { index }), - "{stem} {index}" - ); - } - let plan = pipe - .plan(&dev, &state(72, &[(0, 64, 0), (1, 48, 16)]).shape()) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - assert_eq!(specialized(&pipe, &plan, SpecKey::TgOffset(0)), Some(0)); - assert_eq!(specialized(&pipe, &plan, SpecKey::TgOffset(1)), Some(16)); - assert_eq!( - specialized(&pipe, &plan, SpecKey::TileThreadgroupLength), - Some(80) - ); - assert_eq!(specialized(&pipe, &plan, SpecKey::TileGridWidth), Some(3)); - assert!( - plan.descriptors - .iter() - .any(|w| w.source == WriteSource::TileMemory { bytes: 6 * 80 }), - "{stem}" - ); - let refused = |arguments: &[(u32, u32, u32)]| { - pipe.plan(&dev, &state(72, arguments).shape()).map(|_| ()) - }; - assert_eq!( - refused(&[(0, 64, 0)]), - Err(BindError::MissingThreadgroupMemory { index: 1 }), - "{stem}" - ); - // A length that is not a multiple of 16, and an argument that ends past the tile's - // memory, are planned at their offset: plain Metal takes either. - for (length, offset) in [(56, 16), (64, 16), (1, 64), (0, 0), (u32::MAX, 32)] { - let plan = pipe - .plan(&dev, &state(72, &[(0, 64, 0), (1, length, offset)]).shape()) - .unwrap_or_else(|e| panic!("{stem}: {length} at {offset}: {e}")); - assert_eq!( - specialized(&pipe, &plan, SpecKey::TgOffset(1)), - Some(offset), - "{stem} {length} at {offset}" - ); - assert_eq!( - specialized(&pipe, &plan, SpecKey::TileThreadgroupLength), - Some(80), - "{stem} {length} at {offset}" - ); - } - // Every offset is placed where plain Metal begins the argument: at the offset floored to - // a multiple of 4, and nothing is clamped, since an access from a base past the tile's - // memory is contained, reads zero and drops its store, and Metal's own arithmetic wraps at - // 2^32 rather than reading zero for ever. The offsets below are the ones the planner used - // to refuse; `(2, 0)`, `(20, 20)` and `(70, 68)` are what a floor to 16 would place - // differently from a floor to 4. - for (offset, at) in [ - (8, 8), - (4, 4), - (2, 0), - (17, 16), - (20, 20), - (70, 68), - (72, 72), - (80, 80), - (1 << 20, 1 << 20), - (u32::MAX, u32::MAX - 3), - ] { - let plan = pipe - .plan(&dev, &state(72, &[(0, 64, 0), (1, 16, offset)]).shape()) - .unwrap_or_else(|e| panic!("{stem}: 16 at {offset}: {e}")); - assert_eq!( - specialized(&pipe, &plan, SpecKey::TgOffset(1)), - Some(at), - "{stem} 16 at {offset}" - ); - } - } - // Every tile's memory is one storage-buffer descriptor. - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../metal2vulkan-validation/profiles/lavapipe.json"); - let text = std::fs::read_to_string(path).expect("profile"); - let mut desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); - desc.limits.max_storage_buffer_range = 256; - let dev = Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device"); - let pipe = dev - .compile_tile_pipeline(&d, &Budget::standard()) - .expect("a tile pipeline"); - match pipe.plan(&dev, &state(80, &[(0, 64, 0), (1, 64, 16)]).shape()) { - Err(BindError::Unsupported(u)) => assert_eq!(u.feature, Feature::TileShading), - other => panic!( - "a tile memory past the range planned: {:?}", - other.map(|_| ()) - ), - } -} - fn device(stem: &str) -> Device { let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) .join("../metal2vulkan-validation/profiles") @@ -928,233 +729,6 @@ fn descriptor( d } -/// The value `plan` specializes `key` to. -fn specialized(pipe: &ComputePipeline, plan: &BindingPlan, key: SpecKey) -> Option { - let id = pipe - .stage - .specialization - .constants - .iter() - .find(|c| c.key == key)? - .id; - let e = plan - .specialization - .entries - .iter() - .find(|e| e.constant_id == id)?; - let at = e.offset as usize; - Some(u32::from_le_bytes( - plan.specialization.data[at..at + 4] - .try_into() - .expect("u32"), - )) -} - -/// `Device::compile_tile_pipeline` compiles the tile function under the descriptor's formats; -/// its binding plan specializes the tile size and the render area, binds each attachment as -/// `WriteSource::TileAttachment` in its staging format (a float attachment through the -/// unsigned-integer format of its channels), refuses an empty render area and a layered pass, -/// and answers `maxTotalThreadsPerThreadgroup` with Metal's 1024 where the device runs it, the -/// largest tile threadgroup it runs, and records no aliased imageblock, so a tile state's `imageblockSampleLength` is its -/// attachments' texels, packed. The key is the descriptor's. -#[test] -fn a_tile_pipeline_binds_its_attachments() { - let Some(bc) = assemble("k10ts_tile_grid") else { - return; - }; - let formats = [ - Some(PixelFormat::R32Float), - Some(PixelFormat::R32Uint), - Some(PixelFormat::R32Uint), - ]; - for stem in ["moltenvk-m3", "lavapipe", "runtime-floor"] { - let dev = device(stem); - let d = descriptor(&bc, "k10ts_tile_grid", &formats); - let pipe = dev - .compile_tile_pipeline(&d, &Budget::standard()) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - assert!(pipe - .dependencies - .iter() - .any(|x| x.fact == RuntimeFact::TileFunction)); - let sources: Vec = pipe - .layout - .sets - .iter() - .flat_map(|s| s.bindings.iter().map(|b| b.source)) - .collect(); - for c in 0..3 { - assert!( - sources.contains(&BindingSource::TileAttachment(c)), - "{stem} {c}" - ); - } - let state = |layers: u32| { - let mut s = BindState::default(); - s.stages.insert(Stage::Kernel, StageTable::default()); - s.imageblock_size = ImageblockSize::new(16, 16); - s.render_area = [40, 24]; - s.render_target_array_length = layers; - s - }; - let plan = pipe.plan(&dev, &state(0).shape()).expect("plan"); - assert_eq!( - specialized(&pipe, &plan, SpecKey::ImageblockWidth), - Some(16) - ); - assert_eq!( - specialized(&pipe, &plan, SpecKey::RenderAreaWidth), - Some(40) - ); - assert_eq!( - specialized(&pipe, &plan, SpecKey::RenderAreaHeight), - Some(24) - ); - // The float attachment's bits move through its `uint` view; the others are `uint`. - for c in 0..3 { - assert!( - plan.descriptors.iter().any(|w| w.source - == WriteSource::TileAttachment { - color_index: c, - format: vk::Format::R32_UINT, - }), - "{stem} {c}" - ); - } - match pipe.plan(&dev, &state(2).shape()) { - Err(BindError::Unsupported(u)) => assert_eq!(u.feature, Feature::TileShading), - other => panic!("{stem}: a layered pass planned: {:?}", other.map(|_| ())), - } - // A tile dispatch is one threadgroup per tile of a threadgroup whose layout is measured. - let tiles = |threads_per_group: [u32; 3]| Dispatch::Threadgroups { - groups: [3, 2, 1], - threads_per_group, - }; - // A measured threadgroup runs where the device's local-size limits take it. - for [w, h] in [ - [1, 1], - [2, 2], - [4, 4], - [8, 8], - [16, 16], - [32, 32], - [8, 4], - [4, 2], - [8, 2], - [2, 32], - [32, 4], - [16, 32], - [32, 16], - [16, 2], - [32, 2], - [6, 6], - [24, 24], - [30, 2], - [2, 14], - ] { - match plan.dispatch_variant(&tiles([w, h, 1])) { - Ok(_) => {} - Err(BindError::Unsupported(u)) => { - assert!( - matches!(u.feature, Feature::LocalSize { .. }), - "{stem} {w}x{h}: {u:?}" - ) - } - Err(e) => panic!("{stem} {w}x{h}: {e}"), - } - } - // A threadgroup with an odd side leaves the lanes of its missing threads empty, which - // is not built, and a tile threadgroup is one deep. - for refused in [ - tiles([16, 1, 1]), - tiles([8, 1, 1]), - tiles([1, 8, 1]), - tiles([3, 3, 1]), - tiles([5, 2, 1]), - tiles([2, 31, 1]), - tiles([8, 8, 2]), - tiles([64, 16, 1]), - Dispatch::Threads { - threads: [40, 24, 1], - threads_per_group: [8, 8, 1], - }, - ] { - match plan.dispatch_variant(&refused) { - Err(BindError::Unsupported(u)) => { - assert_eq!( - (u.feature, u.needs), - (Feature::TileShading, Needs::NotImplemented), - "{stem} {refused:?}" - ) - } - other => panic!("{stem}: {refused:?} dispatched: {other:?}"), - } - } - // A tile dispatch outside a render pass (the encoder never set the area) has no tile. - for area in [[0, 0], [40, 0], [0, 24]] { - let mut s = state(0); - s.render_area = area; - assert_eq!( - pipe.plan(&dev, &s.shape()).map(|_| ()), - Err(BindError::InvalidRenderArea { - width: area[0], - height: area[1], - }), - "{stem} {area:?}" - ); - } - // An implicit imageblock aliases no layout: a tile state's sample length is the - // attachments' texels, packed. - assert!( - !pipe - .dependencies - .iter() - .any(|x| matches!(x.fact, RuntimeFact::AliasedImageblock { .. })), - "{stem}" - ); - // Metal's 1024, the 32x32 threadgroup the binder runs, where the - // device's limits take it. - let max = pipe.metal_info.max_total_threads_per_threadgroup; - assert!(max <= 1024, "{stem}: {max}"); - if stem == "moltenvk-m3" { - assert_eq!(max, 1024); - } - // Metal's own answer, before the device's limits: 1024 on every profile. - assert_eq!( - pipe.metal_info.metal_max_total_threads_per_threadgroup, 1024, - "{stem}" - ); - // The descriptor's limit lowers it, never raises it, and is part of the key; Metal's 0 is - // no limit. A limit answers the most threads of a threadgroup of even sides within it, as - // Metal's does (on an M3 Max and an M4: 1000 answers 960, 255 252, 3 none). - let unlimited = pipe.key; - for (limit, metal) in [ - (Some(64), 64), - (Some(1024), 1024), - (Some(0), 1024), - (Some(1000), 960), - (Some(255), 252), - (Some(3), 0), - ] { - let expected = metal.min(max); - let mut limited = d.clone(); - limited.max_total_threads_per_threadgroup = limit; - let pipe = dev - .compile_tile_pipeline(&limited, &Budget::standard()) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - assert_eq!( - pipe.metal_info.max_total_threads_per_threadgroup, expected, - "{stem} {limit:?}" - ); - assert_eq!( - pipe.metal_info.metal_max_total_threads_per_threadgroup, metal, - "{stem} {limit:?}: Metal's own" - ); - assert_ne!(pipe.key, unlimited, "{stem} {limit:?}"); - } - } -} - /// The refusals are typed: a tile function compiled without tile inputs needs them, a format /// whose texel converts into a member of another type (a `float` over `RGBA8Unorm`) is not /// implemented, an attachment its layout holds without a format, or @@ -1528,164 +1102,6 @@ fn a_tile_sized_threadgroup_numbers_its_threads_by_simdgroup() { assert!(ran > 0); } -/// A tile function's explicit imageblock that stands alone is the pass's imageblock storage: each -/// function of `cfit_tile_imageblock` that reaches its cells compiles on every committed profile -/// that compiles a tile function, records its size and alignment -/// (`RuntimeFact::TileImageblock`), and plans the storage at `SyntheticBinding::Imageblock` -/// (`WriteSource::Imageblock`) beside no staged attachment; the layout aliased onto the -/// attachment records neither and stages the attachment. -#[test] -fn a_tile_functions_explicit_imageblock_alone_is_the_pass_storage() { - let Some(bc) = assemble("cfit_tile_imageblock") else { - return; - }; - let formats = [Some(PixelFormat::R32Uint)]; - let mut planned = 0; - for stem in ["moltenvk-m3", "lavapipe", "amd-rdna2-apu-radv"] { - let dev = device(stem); - let mut s = BindState::default(); - s.stages.insert(Stage::Kernel, StageTable::default()); - s.imageblock_size = ImageblockSize::new(16, 16); - s.render_area = [40, 24]; - for entry in [ - "cfit_ib_tile_clear", - "cfit_ib_tile_add", - "cfit_ib_tile_resolve", - "cfit_ib_tile_resolve_halves", - ] { - let d = descriptor(&bc, entry, &formats); - let pipe = dev - .compile_tile_pipeline(&d, &Budget::standard()) - .unwrap_or_else(|e| panic!("{stem} {entry}: {e}")); - assert!( - pipe.dependencies.iter().any(|x| x.fact - == RuntimeFact::TileImageblock { - data_size: 8, - alignment: 4, - }), - "{stem} {entry}" - ); - assert!( - !pipe - .dependencies - .iter() - .any(|x| matches!(x.fact, RuntimeFact::TileAttachmentFormat { .. })), - "{stem} {entry}" - ); - let plan = pipe.plan(&dev, &s.shape()).expect("plan"); - let sources: Vec<_> = plan.descriptors.iter().map(|w| &w.source).collect(); - assert!( - sources.contains(&&WriteSource::Imageblock), - "{stem} {entry}: {sources:?}" - ); - assert!( - !sources - .iter() - .any(|w| matches!(w, WriteSource::TileAttachment { .. })), - "{stem} {entry}: {sources:?}" - ); - planned += 1; - } - let d = descriptor(&bc, "cfit_ib_tile_aliased", &formats); - let pipe = dev - .compile_tile_pipeline(&d, &Budget::standard()) - .unwrap_or_else(|e| panic!("{stem} aliased: {e}")); - assert!( - !pipe - .dependencies - .iter() - .any(|x| matches!(x.fact, RuntimeFact::TileImageblock { .. })), - "{stem}" - ); - let plan = pipe.plan(&dev, &s.shape()).expect("plan"); - assert!( - !plan - .descriptors - .iter() - .any(|w| w.source == WriteSource::Imageblock), - "{stem}" - ); - } - assert_eq!(planned, 12); -} - -/// A tile function's explicit imageblock standing alone in a pass that keeps fewer of its cells' -/// bytes: the plan of a shape stating them (`BindShape::kept_imageblock_bytes`) asks for the -/// variant that keeps them where they are fewer than the block's data, and none otherwise; the -/// function compiles under them (`LoweringInputs::kept_imageblock_bytes`) with its plan's cells -/// keeping them, and kept bytes that are not a cell's first whole words, or given to a function -/// whose cells are not the pass's imageblock storage, are refused. -#[test] -fn a_pass_keeping_fewer_imageblock_bytes_asks_for_the_kept_variant() { - let Some(bc) = assemble("cfit_tile_imageblock") else { - return; - }; - let formats = [Some(PixelFormat::R32Uint)]; - for stem in ["moltenvk-m3", "lavapipe"] { - let dev = device(stem); - let entry = "cfit_ib_tile_clear"; - let d = descriptor(&bc, entry, &formats); - let pipe = dev - .compile_tile_pipeline(&d, &Budget::standard()) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - let mut s = BindState::default(); - s.stages.insert(Stage::Kernel, StageTable::default()); - s.imageblock_size = ImageblockSize::new(16, 16); - s.render_area = [40, 24]; - // The eight-byte cell: four bytes kept ask for the variant; eight, or none, do not. - for (kept, wanted) in [ - (Some(4), Some(4)), - (Some(0), Some(0)), - (Some(8), None), - (None, None), - ] { - s.kept_imageblock_bytes = kept; - let plan = pipe.plan(&dev, &s.shape()).expect("plan"); - assert_eq!( - plan.variant.kept_imageblock_bytes, wanted, - "{stem} {kept:?}" - ); - } - let mut inputs = tile_inputs(&[PixelFormat::R32Uint]); - inputs.kept_imageblock_bytes = Some(4); - let (plan, _) = typed_module_with(&bc, entry, dev.profile(), &inputs) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - let tile = plan.families.access.tile.as_ref().expect("the tile plan"); - assert_eq!(tile.kept_bytes, Some(4), "{stem}"); - crate::pipeline::testing::compile_with(&bc, entry, dev.profile(), &inputs) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - // Not a cell's first whole words. - for kept in [2, 8] { - inputs.kept_imageblock_bytes = Some(kept); - assert!( - matches!( - typed_module_with(&bc, entry, dev.profile(), &inputs), - Err(Error::Internal(_)) - ), - "{stem} {kept}" - ); - } - // The layout aliased onto the attachment, and a kernel without tile inputs. - inputs.kept_imageblock_bytes = Some(4); - assert!( - matches!( - typed_module_with(&bc, "cfit_ib_tile_aliased", dev.profile(), &inputs), - Err(Error::Internal(_)) - ), - "{stem} aliased" - ); - let mut plain = LowerInputs::new(); - plain.kept_imageblock_bytes = Some(4); - assert!( - matches!( - typed_module_with(&bc, entry, dev.profile(), &plain), - Err(Error::Internal(_)) - ), - "{stem} without tile inputs" - ); - } -} - /// A channel of a normalized format: an unsigned or signed normalized one of its width, or an /// Metal's 12-bit linear value of each 8-bit sRGB code, `round(decode(k) * 4095)` (probes, the M3 /// Max and the M4 alike). @@ -2375,96 +1791,3 @@ fn a_normalized_attachment_stores_halves_as_metal_does() { } assert!(ran > 0); } - -/// A normalized attachment is staged through the unsigned-integer view of its texel's bytes in -/// 32-bit words (`R32Uint`, `RG32Uint`, or `R16Uint` for two bytes), through a `float` member or -/// a `half` one, and a member of other lanes than its channels or four, or a format whose texel is -/// one byte, is not implemented. -#[test] -fn a_normalized_attachment_is_bound_through_its_bits() { - let Some(bc) = assemble("cfb_tile_norm") else { - return; - }; - let not_implemented = |r: Result| match r { - Err(Error::Unsupported(u)) => { - u.feature == Feature::TileShading && u.needs == Needs::NotImplemented - } - _ => false, - }; - let cases = [ - ( - "cfb_tn_read4", - PixelFormat::RGBA8UnormSRGB, - vk::Format::R32_UINT, - ), - ( - "cfb_tn_write4", - PixelFormat::BGR10A2Unorm, - vk::Format::R32_UINT, - ), - ( - "cfb_tn_read4", - PixelFormat::RGBA16Snorm, - vk::Format::R32G32_UINT, - ), - ("cfb_tn_write2", PixelFormat::RG8Unorm, vk::Format::R16_UINT), - ("cfb_tn_read4", PixelFormat::R16Unorm, vk::Format::R16_UINT), - ( - "cfb_tn_hread4", - PixelFormat::RGBA8Unorm, - vk::Format::R32_UINT, - ), - ( - "cfb_tn_hwrite2", - PixelFormat::RG16Snorm, - vk::Format::R32_UINT, - ), - ("cfb_tn_hread1", PixelFormat::R16Unorm, vk::Format::R16_UINT), - ]; - let mut planned = 0; - for stem in ["moltenvk-m3", "lavapipe", "amd-rdna2-apu-radv"] { - let dev = device(stem); - let b = Budget::standard(); - let mut s = BindState::default(); - s.stages.insert(Stage::Kernel, StageTable::default()); - s.imageblock_size = ImageblockSize::new(16, 16); - s.render_area = [16, 16]; - for (entry, pf, view) in cases { - let pipe = match dev.compile_tile_pipeline(&descriptor(&bc, entry, &[Some(pf)]), &b) { - Ok(p) => p, - // A profile without the extended storage formats refuses the 16-bit views. - Err(Error::Unsupported(u)) if u.feature == Feature::Format => continue, - Err(e) => panic!("{stem} {entry} {pf:?}: {e}"), - }; - let plan = pipe.plan(&dev, &s.shape()).expect("plan"); - assert!( - plan.descriptors.iter().any(|w| w.source - == WriteSource::TileAttachment { - color_index: 0, - format: view, - }), - "{stem} {entry} {pf:?}: {:?}", - plan.descriptors - ); - planned += 1; - } - for (entry, pf) in [ - ("cfb_tn_read1", PixelFormat::RGBA8Unorm), - ("cfb_tn_read2", PixelFormat::R16Unorm), - ("cfb_tn_read2", PixelFormat::RGBA16Unorm), - ("cfb_tn_read4", PixelFormat::R8Unorm), - ("cfb_tn_read4", PixelFormat::RG8UnormSRGB), - ("cfb_tn_hread1", PixelFormat::RGBA8Unorm), - ("cfb_tn_hwrite2", PixelFormat::RGBA16Snorm), - ("cfb_tn_hread2", PixelFormat::R16Unorm), - ("cfb_tn_hread4", PixelFormat::R8Unorm), - ] { - let d = descriptor(&bc, entry, &[Some(pf)]); - assert!( - not_implemented(dev.compile_tile_pipeline(&d, &b)), - "{stem} {entry} {pf:?}" - ); - } - } - assert!(planned > 0); -} diff --git a/crates/metal2vulkan/src/tests/engine_unattached_colors.rs b/crates/metal2vulkan/src/tests/engine_unattached_colors.rs new file mode 100644 index 000000000..15ee689a4 --- /dev/null +++ b/crates/metal2vulkan/src/tests/engine_unattached_colors.rs @@ -0,0 +1,125 @@ +//! A render pipeline's fragment function keeps no output at a color it writes that the pipeline +//! has no attachment for, whose write Metal discards. No device is opened; nothing runs on a GPU. +//! +//! `llvm-as` assembles the fixtures; without it the tests skip visibly. + +use std::path::Path; + +use crate::budget::Budget; +use crate::device::{Device, DeviceDescription, DevicePolicy}; +use crate::library::Library; +use crate::metal::{PixelFormat, VertexFormat}; +use crate::pipeline::descriptor::{ + ColorAttachmentDescriptor, VertexAttributeDescriptor, VertexBufferLayoutDescriptor, + VertexDescriptor, +}; +use crate::pipeline::testing::{engine_dir, llvm_assemble, AssembleError}; +use crate::pipeline::{FunctionDescriptor, RenderPipelineDescriptor, StageSource}; + +fn fixture(stem: &str) -> Option> { + match llvm_assemble(&engine_dir().join(format!("{stem}.ll"))) { + Ok(b) => Some(b), + Err(AssembleError::Missing(why)) => { + eprintln!("SKIPPED: {why}"); + None + } + Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected {stem}.ll: {why}"), + } +} + +/// Every committed profile as a device, by stem. +fn devices() -> Vec<(String, Device)> { + let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../metal2vulkan-validation/profiles"); + let mut out = Vec::new(); + for e in std::fs::read_dir(&dir).expect("profiles") { + let path = e.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("profile"); + let desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); + out.push(( + stem, + Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device"), + )); + } + out.sort_by(|a, b| a.0.cmp(&b.0)); + out +} + +fn device(stem: &str) -> Device { + devices() + .into_iter() + .find(|(s, _)| s == stem) + .map(|(_, d)| d) + .expect("committed profile") +} + +// ---- Render pipelines -------------------------------------------------------------------------- + +/// `stage_io_vertex`'s attributes: one interleaved per-vertex buffer at index 0. +fn vertex_descriptor() -> VertexDescriptor { + let mut d = VertexDescriptor::new(); + d.layouts + .insert(0, VertexBufferLayoutDescriptor::new(Some(24))); + for (index, format, offset) in [ + (0, VertexFormat::Float3, 0), + (1, VertexFormat::Half2, 12), + (4, VertexFormat::UShort2, 16), + (7, VertexFormat::UChar4, 20), + ] { + d.attributes + .insert(index, VertexAttributeDescriptor::new(format, offset, 0)); + } + d +} + +/// `stage_io`'s vertex + fragment pipeline descriptor. +fn render_descriptor(bc: &[u8]) -> RenderPipelineDescriptor { + let lib = Library::from_air(bc).expect("library"); + let v = lib.function("stage_io_vertex").expect("vertex"); + let f = lib.function("stage_io_fragment").expect("fragment"); + let mut d = RenderPipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new(v))); + d.fragment = Some(StageSource::Function(FunctionDescriptor::new(f))); + d.vertex_descriptor = Some(vertex_descriptor()); + d.color_attachments[0] = Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm)); + d.color_attachments[2] = Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA32Uint)); + d.depth_format = Some(PixelFormat::Depth32Float); + d +} + +/// `Device::compile_render_pipeline` compiles a `Function` fragment stage with no output at a color +/// it writes that the pipeline has no attachment for, whose write Metal discards: the fixture's +/// fragment, writing colors 0 and 2, states color 0 alone among its color outputs in a pipeline of +/// attachment 0 alone, and both where it has both. Under alpha to coverage its color 0 stays +/// without attachment 0, the coverage reading its alpha. +#[test] +fn a_render_pipeline_writes_no_color_it_has_no_attachment_for() { + let Some(bc) = fixture("stage_io") else { + return; + }; + for stem in ["lavapipe", "moltenvk-m3", "amd-780m-radv"] { + let dev = device(stem); + let outputs = |edit: &dyn Fn(&mut RenderPipelineDescriptor)| { + let mut d = render_descriptor(&bc); + edit(&mut d); + dev.compile_render_pipeline(&d, &Budget::standard()) + .unwrap_or_else(|e| panic!("{stem}: {e}")) + .graphics + .color_outputs + }; + assert_eq!(outputs(&|_| {}), 0b101, "{stem}"); + assert_eq!(outputs(&|d| d.color_attachments[2] = None), 0b1, "{stem}"); + let covered = |d: &mut RenderPipelineDescriptor| { + d.color_attachments[0] = None; + d.alpha_to_coverage = true; + }; + assert_eq!(outputs(&covered), 0b101, "{stem}"); + } +} + +// ---- Textures and samplers --------------------------------------------------------------------- diff --git a/crates/metal2vulkan/src/tests/engine_ycbcr_in_place.rs b/crates/metal2vulkan/src/tests/engine_ycbcr_in_place.rs deleted file mode 100644 index 3aed3db6a..000000000 --- a/crates/metal2vulkan/src/tests/engine_ycbcr_in_place.rs +++ /dev/null @@ -1,1489 +0,0 @@ -//! A two-plane YCbCr texture's planes read in place (`lower::sampler::in_place`), on the CPU -//! interpreter against Metal's texels and Metal's filter of them, bit for bit. -//! -//! The slot under its in-place variant (`LoweringInputs::ycbcr_in_place`) is a uniform texel -//! buffer of the planes' codes (`R8G8_UINT` elements of 8-bit codes, `R16G16_UINT` ones of 10-bit -//! codes, each 10-bit code the high bits of its word over junk low bits), and its push field -//! states the texture's size, its planes' places and rows, and its conversion -//! (`bind::YCbCrInPlace::words`). Each texel the samples read is Metal's (`ycbcr_convert`'s module -//! docs: the luma code, the chroma pairs' 9/3/3/1 filter, the range's and the matrix's -//! conversion), and a nearest sample is the texel at Metal's position. A linear sample is Vulkan's -//! Y′CbCr model of the codes (`model`), within the `float` arithmetic's rounding, where the -//! model takes it, and Metal's filter of the steps on the grid `2048` (`metal_step`) elsewhere. The texel buffer -//! traps every fetch outside it, so each tap's elements lie within the planes. - -use std::collections::BTreeMap; -use std::sync::atomic::{AtomicU64, Ordering}; - -use crate::bind::ycbcr_convert::{ycbcr_read, YCbCrCodes, YCbCrMatrix, YCbCrPlanes, YCbCrRange}; -use crate::bind::YCbCrInPlace; -use crate::device::profile::DeviceProfile; -use crate::device::DevicePolicy; -use crate::lower::select::{LowerInputs, Plan}; -use crate::metal::format::ycbcr_format; -use crate::metal::sampler::SamplerWord; -use crate::metal::{PixelFormat, SamplerAddressMode}; -use crate::pipeline::facts::RuntimeFact; -use crate::pipeline::interface::PushLoc; -use crate::pipeline::sym::{ - Axis, PushField, ResourceKind, ResourceSlot, SlotClass, SlotRef, SpecKey, Stage, -}; -use crate::pipeline::testing::{ - compile_with, link_and_validate, llvm_assemble, profile, typed_module_with, AssembleError, -}; -use crate::spirv::interp::{run_with_images, Buffer, Config, Image, Order, Resources}; -use crate::spirv::ir::{GlobalKind, TypedModule}; - -const HEADER: &str = "target datalayout = \"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32\"\ntarget triple = \"air64_v28-apple-macosx26.0.0\"\n\n"; - -/// Bitcode of the module `body` (after the AIR header), or `None` without `llvm-as`. -fn assemble(name: &str, body: &str) -> Option> { - static NEXT: AtomicU64 = AtomicU64::new(0); - let dir = std::env::temp_dir().join(format!( - "m2v-linear-half-{}-{}-{}", - std::process::id(), - NEXT.fetch_add(1, Ordering::Relaxed), - name.replace(' ', "-") - )); - std::fs::create_dir_all(&dir).expect("scratch"); - let ll = dir.join("k.ll"); - std::fs::write(&ll, format!("{HEADER}{body}")).expect("write"); - let r = llvm_assemble(&ll); - let _ = std::fs::remove_dir_all(&dir); - match r { - Ok(x) => Some(x), - Err(AssembleError::Missing(why)) => { - eprintln!("SKIPPED: {why}"); - None - } - Err(AssembleError::Rejected(why)) => panic!("{name}: {why}"), - } -} - -fn lavapipe() -> DeviceProfile { - profile("lavapipe", DevicePolicy::RESIDENT_TABLES).expect("profile") -} - -fn m3() -> DeviceProfile { - profile("moltenvk-m3", DevicePolicy::RESIDENT_TABLES).expect("profile") -} - -/// The words of `constexpr sampler(filter::linear, ...)`: minification and magnification -/// `filter` (AIR code: 0 nearest, 1 linear), mip filter `mip` (0 none, 2 linear), every axis -/// addressed by `address` (0 zero or border, 1 edge, 2 repeat, 3 mirrored repeat), `pixel` -/// coordinates, and border color code `border` (0 transparent black, 2 opaque white), with the -/// fields Apple's compiler writes for the rest (the `hlf_half_address` fixture's sampler). -fn sampler_words(filter: u64, mip: u64, address: u64, pixel: bool, border: u64) -> u64 { - const BASE: u64 = 0x007b_ff00_0008_0000; - BASE | address - | address << 3 - | address << 6 - | filter << 9 - | filter << 11 - | mip << 13 - | u64::from(pixel) << 15 - | border << 56 -} - -fn linear(address: u64, pixel: bool, border: u64) -> u64 { - sampler_words(1, 0, address, pixel, border) -} - -/// How a test kernel samples its `half` texture. -#[derive(Clone, Copy, Debug)] -enum Form { - /// `texture2d`: `t.sample(s, coord[tid], offset)` with constant `offset`. - Plain { offset: (i32, i32) }, - /// `texture2d` with `min_lod_clamp(1)`. - MinLodClamp, - /// `texture2d` with lane `tid`'s dynamic `int2` offset (buffer 2). - DynamicOffset, - /// `texture3d` at `float4` buffer 0's lane `tid`'s `xyz`, with constant `offset`. - ThreeD { offset: (i32, i32, i32) }, - /// `texture2d`: a `float` result. - Float, - /// `texture2d`: `t.gather(s, coord[tid], int2(0), component)`, `component` 0 to 3. - Gather { component: u32 }, - /// `texture2d`: a sample, then a gather of red, of one coordinate, written to elements - /// `2 tid` and `2 tid + 1`: the shape of a probe that samples or gathers as a lane asks. - SampleAndGather, -} - -/// A kernel sampling texture slot 0 through sampler `sampler` (a constexpr sampler's words, or -/// `None` for the runtime `[[sampler(0)]]`) at `float2` buffer 0's lane `tid`, storing the -/// `half4` (`float4` for [`Form::Float`]) to buffer 1. -fn kernel(sampler: Option, form: Form) -> String { - kernel_of(sampler, form, matches!(form, Form::Float)) -} - -/// [`kernel`] with a `float` result when `float`, whatever the form. -fn kernel_of(sampler: Option, form: Form, float: bool) -> String { - let half = !float; - let (texel, vec4, size) = if half { - ("half", "<4 x half>", 8) - } else { - ("float", "<4 x float>", 16) - }; - let suffix = if half { "v4f16" } else { "v4f32" }; - let s = if sampler.is_some() { - "@__air_sampler_state" - } else { - "%s" - }; - const SAMPLE_2D: &str = - "ptr addrspace(1), ptr addrspace(2), <2 x float>, i1, <2 x i32>, i1, float, float, i32"; - const GATHER_2D: &str = - "ptr addrspace(1), ptr addrspace(2), <2 x float>, i1, <2 x i32>, i32, i32"; - let plain = format!("texture2d<{texel}, sample>"); - let gather = |component: u32| { - ( - "gather_texture_2d", - GATHER_2D, - format!("<2 x float> %uv, i1 true, <2 x i32> zeroinitializer, i32 {component}, i32 0"), - ) - }; - let (tex_ty, calls) = match form { - Form::Plain { offset: (ox, oy) } => ( - plain, - vec![( - "sample_texture_2d", - SAMPLE_2D, - format!("<2 x float> %uv, i1 true, <2 x i32> , i1 false, float 0.0, float 0.0, i32 0"), - )], - ), - Form::Float => ( - plain, - vec![( - "sample_texture_2d", - SAMPLE_2D, - "<2 x float> %uv, i1 true, <2 x i32> zeroinitializer, i1 false, float 0.0, float 0.0, i32 0".to_string(), - )], - ), - Form::MinLodClamp => ( - plain, - vec![( - "sample_texture_2d", - SAMPLE_2D, - "<2 x float> %uv, i1 true, <2 x i32> zeroinitializer, i1 false, float 0.0, float 1.0, i32 0".to_string(), - )], - ), - Form::DynamicOffset => ( - plain, - vec![( - "sample_texture_2d", - SAMPLE_2D, - "<2 x float> %uv, i1 true, <2 x i32> %o, i1 false, float 0.0, float 0.0, i32 0".to_string(), - )], - ), - Form::ThreeD { offset: (ox, oy, oz) } => ( - format!("texture3d<{texel}, sample>"), - vec![( - "sample_texture_3d", - "ptr addrspace(1), ptr addrspace(2), <3 x float>, i1, <3 x i32>, i1, float, float, i32", - format!("<3 x float> %uvw, i1 true, <3 x i32> , i1 false, float 0.0, float 0.0, i32 0"), - )], - ), - Form::Gather { component } => (plain, vec![gather(component)]), - Form::SampleAndGather => ( - plain, - vec![ - ( - "sample_texture_2d", - SAMPLE_2D, - "<2 x float> %uv, i1 true, <2 x i32> zeroinitializer, i1 false, float 0.0, float 0.0, i32 0".to_string(), - ), - gather(0), - ], - ), - }; - // Each call's result to element `tid` of `out`, or of two calls `2 tid + k`. - let mut body = String::new(); - let mut decls = String::new(); - if calls.len() > 1 { - body.push_str(" %i2 = mul i64 %i, 2\n"); - } - for (k, (intrinsic, args, call_args)) in calls.iter().enumerate() { - let at = match calls.len() { - 1 => "%i".to_string(), - _ => { - body.push_str(&format!(" %i2_{k} = add i64 %i2, {k}\n")); - format!("%i2_{k}") - } - }; - body.push_str(&format!( - " %r{k} = call {{ {vec4}, i8 }} @air.{intrinsic}.{suffix}(ptr addrspace(1) %t, ptr addrspace(2) {s}, {call_args})\n %v{k} = extractvalue {{ {vec4}, i8 }} %r{k}, 0\n %q{k} = getelementptr inbounds {vec4}, ptr addrspace(1) %out, i64 {at}\n store {vec4} %v{k}, ptr addrspace(1) %q{k}, align {size}\n" - )); - decls.push_str(&format!( - "declare {{ {vec4}, i8 }} @air.{intrinsic}.{suffix}({args})\n" - )); - } - let dynamic = matches!(form, Form::DynamicOffset); - let runtime = sampler.is_none(); - // Parameters after `out`: the offsets buffer, then the runtime sampler. - let mut params = String::new(); - let mut mds = Vec::new(); - let mut next = 3; - if dynamic { - params.push_str(", ptr addrspace(1) %offs"); - mds.push(format!("!{{i32 {next}, !\"air.buffer\", !\"air.location_index\", i32 2, i32 1, !\"air.read\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 8, !\"air.arg_type_align_size\", i32 8, !\"air.arg_type_name\", !\"int2\", !\"air.arg_name\", !\"offs\"}}")); - next += 1; - } - if runtime { - params.push_str(", ptr addrspace(2) %s"); - mds.push(format!("!{{i32 {next}, !\"air.sampler\", !\"air.location_index\", i32 0, i32 1, !\"air.arg_type_name\", !\"sampler\", !\"air.arg_name\", !\"s\"}}")); - next += 1; - } - mds.push(format!("!{{i32 {next}, !\"air.thread_position_in_grid\", !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"tid\"}}")); - let first = 7; - let arg_mds: Vec = (0..mds.len()).map(|i| format!("!{}", first + i)).collect(); - let tail: String = mds - .iter() - .enumerate() - .map(|(i, m)| format!("!{} = {m}\n", first + i)) - .collect(); - let load_offset = if dynamic { - " %po = getelementptr inbounds <2 x i32>, ptr addrspace(1) %offs, i64 %i\n %o = load <2 x i32>, ptr addrspace(1) %po, align 8\n" - } else { - "" - }; - let state = match sampler { - Some(w) => format!( - "@__air_sampler_state = internal addrspace(2) constant [2 x i64] [i64 {w}, i64 0], align 8\n\n" - ), - None => String::new(), - }; - let (states, state_md) = if sampler.is_some() { - ( - "!air.sampler_states = !{!6}\n", - "!6 = !{!\"air.sampler_state\", ptr addrspace(2) @__air_sampler_state}\n", - ) - } else { - ("", "") - }; - let half_name = if half { "half4" } else { "float4" }; - // A 3D sample's coordinates are a `float4`'s `xyz`, every other's a `float2`. - let (load_coord, coord_size, coord_name) = if matches!(form, Form::ThreeD { .. }) { - ( - " %p = getelementptr inbounds <4 x float>, ptr addrspace(1) %c, i64 %i\n %c4 = load <4 x float>, ptr addrspace(1) %p, align 16\n %uvw = shufflevector <4 x float> %c4, <4 x float> zeroinitializer, <3 x i32> \n", - 16, - "float4", - ) - } else { - ( - " %p = getelementptr inbounds <2 x float>, ptr addrspace(1) %c, i64 %i\n %uv = load <2 x float>, ptr addrspace(1) %p, align 8\n", - 8, - "float2", - ) - }; - format!( - r#"{state}define void @k(ptr addrspace(1) %t, ptr addrspace(1) %c, ptr addrspace(1) %out{params}, i32 %tid) {{ - %i = zext i32 %tid to i64 -{load_coord}{load_offset}{body} ret void -}} - -{decls} -!air.kernel = !{{!0}} -{states}!0 = !{{ptr @k, !1, !2}} -!1 = !{{}} -!2 = !{{!3, !4, !5, {arg_mds}}} -!3 = !{{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.sample", !"air.arg_type_name", !"{tex_ty}", !"air.arg_name", !"t"}} -!4 = !{{i32 1, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 1, !"air.arg_type_size", i32 {coord_size}, !"air.arg_type_align_size", i32 {coord_size}, !"air.arg_type_name", !"{coord_name}", !"air.arg_name", !"c"}} -!5 = !{{i32 2, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 {size}, !"air.arg_type_align_size", i32 {size}, !"air.arg_type_name", !"{half_name}", !"air.arg_name", !"out"}} -{state_md}{tail}"#, - arg_mds = arg_mds.join(", "), - ) -} - -const TEXTURE: SlotRef = SlotRef { - stage: Stage::Kernel, - class: SlotClass::Texture, - index: 0, -}; - -/// `res` with each `SamplerState` specialization artifact `a` declares valued by runtime sampler -/// word `word`, masked by its fields; unchanged without a word. -fn with_word( - mut res: Resources, - a: &crate::library::FunctionArtifact, - word: Option, -) -> Resources { - let Some(word) = word else { - return res; - }; - let mut declared = 0; - for key in a.interface.read_keys() { - if let SpecKey::SamplerState { fields, .. } = key { - res.spec.insert(key, u64::from(word & fields)); - declared += 1; - } - } - assert_eq!( - declared, 1, - "the runtime sampler's `SamplerState` specialization" - ); - res -} - -/// `m` over `groups` one-thread threadgroups with `image` bound, in both scheduling orders, which -/// must agree: buffer 1's `half4`s (`float4`s unless `half`), as bits. -fn run(m: &TypedModule, res: &Resources, image: &Image, groups: u32, half: bool) -> Vec<[u32; 4]> { - run_images(m, res, std::slice::from_ref(image), groups, half) -} - -/// [`run`] with `images` bound. -fn run_images( - m: &TypedModule, - res: &Resources, - images: &[Image], - groups: u32, - half: bool, -) -> Vec<[u32; 4]> { - let mut outs = Vec::new(); - for order in [Order::Forward, Order::Reverse] { - let cfg = Config { - workgroups: [groups, 1, 1], - order, - ..Config::default() - }; - let (o, _) = run_with_images(m, &cfg, res.clone(), images.to_vec()) - .unwrap_or_else(|e| panic!("interpreter: {e:?}")); - outs.push(o.buffers); - } - assert_eq!(outs[0], outs[1], "the scheduling orders disagree"); - let size = if half { 2 } else { 4 }; - outs[0][1] - .chunks_exact(4 * size) - .map(|c| { - std::array::from_fn(|k| { - let mut b = [0u8; 4]; - b[..size].copy_from_slice(&c[size * k..size * (k + 1)]); - u32::from_le_bytes(b) - }) - }) - .collect() -} - -/// A deterministic source: a 64-bit LCG. -struct Lcg(u64); - -impl Lcg { - fn next(&mut self) -> u64 { - self.0 = self - .0 - .wrapping_mul(6_364_136_223_846_793_005) - .wrapping_add(1_442_695_040_888_963_407); - self.0 >> 11 - } -} - -/// Metal's step of a 2D linear sample of a YCbCr format: the taps' steps `k` (`(i, j)`, `(i + 1, -/// j)`, `(i, j + 1)`, `(i + 1, j + 1)`) under the fractions `a` and `b` in 1/256 steps, a merged -/// axis's 0; a signed term and sum floored. -fn metal_step(taps: [i64; 4], a: i64, b: i64) -> i64 { - let w = [(256 - a) * (256 - b), a * (256 - b), (256 - a) * b, a * b]; - let t: i64 = taps.iter().zip(w).map(|(k, w)| (k * w) >> 7).sum(); - (t + 256) >> 9 -} - -/// The `half` bits of `k / d` (`d` a power of two, `1 <= |k| / d`'s binade above `2^-14`, or `k -/// = 0`), rounded with ties away from zero. -fn half_away(k: i64, d: i64) -> u16 { - if k == 0 { - return 0; - } - let sign = if k < 0 { 0x8000 } else { 0 }; - let m = k.unsigned_abs(); - let lead = i64::from(63 - m.leading_zeros()); - let e = lead - i64::from(d.trailing_zeros()); - assert!(e >= -14, "{k} / {d} is below the normal halves"); - // The significand's 11 bits: the magnitude rounded half up there, a carry raising `e`. - let shift = lead - 10; - let q = match shift > 0 { - true => (m + (1 << (shift - 1))) >> shift, - false => m << -shift, - }; - let (q, e) = if q == 2048 { (1024, e + 1) } else { (q, e) }; - sign | ((e + 15) as u16) << 10 | (q as u16 - 1024) -} - -/// The result lanes of steps `steps` on grid `d` (alpha 1): `k / d` as `f32` bits (exact), or as -/// `half` bits rounded with ties away from zero when `half`. -fn result_bits(steps: [i64; 3], half: bool, d: i64) -> [u32; 4] { - let lanes = [steps[0], steps[1], steps[2], d]; - lanes.map(|k| match half { - true => u32::from(half_away(k, d)), - false => (k as f32 / d as f32).to_bits(), - }) -} - -/// The texture's width and height: odd, so the chroma plane's last pair serves one column and one -/// row alone. -const W: u32 = 7; -const H: u32 = 5; - -/// Lowering inputs with texture slot 0 under its in-place variant, or none. -fn inputs(in_place: bool) -> LowerInputs { - let mut i = LowerInputs::new(); - if in_place { - i.ycbcr_in_place.insert(TEXTURE); - } - i -} - -/// One texture's planes: their codes by texel, where they lie, and the texel buffer's elements. -struct Planes { - planes: YCbCrPlanes, - words: YCbCrInPlace, - /// Each element's two lanes, as the texel buffer's format reads them. - elements: Vec<[u32; 2]>, - luma: Vec, - chroma: Vec<[u16; 2]>, -} - -impl Planes { - /// Random planes of `pf` (`YCBCR8_420_2P` or `YCBCR10_420_2P`) under `conversion`: the chroma - /// plane first, three elements in, then the luma plane, each row padded past its codes. - fn random(pf: PixelFormat, conversion: (YCbCrRange, YCbCrMatrix), rng: &mut Lcg) -> Planes { - let codes = ycbcr_format(pf).and_then(YCbCrCodes::of).expect("codes"); - let unit = codes.bytes; - let element = 2 * unit; - let [cw, ch] = [W.div_ceil(2), H.div_ceil(2)]; - let chroma = [3 * element, (cw + 2) * element]; - let luma_at = (chroma[0] + ch * chroma[1]).next_multiple_of(element) + element; - let luma = [luma_at, (W.div_ceil(2) + 1) * element]; - let planes = YCbCrPlanes::new([W, H], luma, chroma, conversion, codes); - let words = YCbCrInPlace::of(&planes).expect("in place"); - let max = (1u64 << codes.bits) - 1; - let mut code = || (rng.next() % (max + 1)) as u16; - let luma_codes: Vec = (0..W * H).map(|_| code()).collect(); - let chroma_codes: Vec<[u16; 2]> = (0..cw * ch).map(|_| [code(), code()]).collect(); - // Every lane a junk value, then each code's place written: a 10-bit code is the high bits - // of its 16-bit word. - let n = words.elements() as usize; - let mut lanes: Vec = (0..2 * n) - .map(|_| (rng.next() % (1 << (8 * unit))) as u32) - .collect(); - let shift = 8 * unit - codes.bits; - let mut put = |byte: u32, code: u16, junk: u64| { - let lane = (byte / unit) as usize; - lanes[lane] = (u32::from(code) << shift) | (junk as u32 & ((1 << shift) - 1)); - }; - for y in 0..H { - for x in 0..W { - let c = luma_codes[(y * W + x) as usize]; - put(luma[0] + y * luma[1] + x * unit, c, rng.next()); - } - } - for y in 0..ch { - for x in 0..cw { - let [cb, cr] = chroma_codes[(y * cw + x) as usize]; - let at = chroma[0] + y * chroma[1] + 2 * x * unit; - put(at, cb, rng.next()); - put(at + unit, cr, rng.next()); - } - } - let elements = lanes.as_chunks::<2>().0.to_vec(); - Planes { - planes, - words, - elements, - luma: luma_codes, - chroma: chroma_codes, - } - } - - /// Metal's texel `(x, y)`: each channel's step on the grid `2048`. - fn texel(&self, x: i64, y: i64) -> [i64; 3] { - let [cw, ch] = [W.div_ceil(2), H.div_ceil(2)].map(i64::from); - // An axis's chroma texels weighted 3 and 1: its own, and the one after it for an odd - // index, before it for an even one, clamped to the plane. - let taps = |q: i64, n: i64| -> [(i64, u32); 2] { - let own = q / 2; - let other = if q % 2 == 1 { own + 1 } else { own - 1 }; - [(own, 3), (other.clamp(0, n - 1), 1)] - }; - let mut sums = [0u32; 2]; - for (cy, wy) in taps(y, ch) { - for (cx, wx) in taps(x, cw) { - let pair = self.chroma[(cy * cw + cx) as usize]; - for (sum, c) in sums.iter_mut().zip(pair) { - *sum += wx * wy * u32::from(c); - } - } - } - let [cb, cr] = sums.map(|s| ((s + 8) >> 4) as u16); - let luma = self.luma[(y * i64::from(W) + x) as usize]; - let p = &self.planes; - ycbcr_read(p.codes, (p.range, p.matrix), [luma, cb, cr]).map(i64::from) - } - - /// The texel buffer bound at `slot`. - fn image(&self, slot: ResourceSlot) -> Image { - let n = self.elements.len() as u32; - let mut image = Image::new(slot, [n, 1, 1], 1, 1, 1); - for (x, [a, b]) in (0u32..).zip(&self.elements) { - let i = image.index(0, 0, 0, [x, 0, 0]).expect("element"); - image.texels[i] = [*a, *b, 0, 1]; - } - image - } -} - -/// The texel buffer binding a module declares for texture slot 0. -fn texel_buffer(m: &TypedModule) -> ResourceSlot { - m.globals() - .iter() - .find_map(|g| match g.kind { - GlobalKind::Resource( - s @ ResourceSlot { - kind: ResourceKind::Texture, - index: 0, - .. - }, - ) => Some(s), - _ => None, - }) - .expect("the planes' binding") -} - -/// Resources of a dispatch of one-thread threadgroups: `[[buffer(i)]]` holding `init[i]`, and -/// the slot's push field holding `words`. -fn resources(plan: &Plan, init: &[Vec], words: &YCbCrInPlace) -> Resources { - let mut spec = BTreeMap::new(); - for axis in [Axis::X, Axis::Y, Axis::Z] { - spec.insert(SpecKey::LocalSize(axis), 1); - } - spec.insert(SpecKey::FlatLocalSize, 1); - let mut push = vec![0u8; plan.push.push_range.map_or(0, |(_, end)| end as usize)]; - let mut written = false; - for f in &plan.push.fields { - match (f.field, f.loc) { - (PushField::YCbCrInPlace(TEXTURE), PushLoc::Push { offset }) => { - let at = offset as usize; - for (i, w) in words.words().into_iter().enumerate() { - push[at + 4 * i..at + 4 * i + 4].copy_from_slice(&w.to_le_bytes()); - } - written = true; - } - (PushField::SlotBindOffset(_) | PushField::DispatchRegion, PushLoc::Push { .. }) => {} - other => panic!("unexpected push field {other:?}"), - } - } - assert!(written, "the planes' push field"); - let buffers = init - .iter() - .enumerate() - .map(|(i, b)| Buffer { - slot: Some(ResourceSlot { - stage: Stage::Kernel, - kind: ResourceKind::Buffer, - index: i as u32, - }), - address: None, - bytes: b.clone(), - }) - .collect(); - Resources { - buffers, - push, - spec, - } -} - -/// A sampler a test samples through: a constexpr sampler's words, or a runtime sampler's word. -#[derive(Clone, Copy, Debug)] -enum Through { - Constexpr(u64), - Runtime(u32), -} - -/// The word of a runtime sampler of `filter` (linear, else nearest), every axis addressed by -/// `mode`, normalized coordinates, transparent black. -fn word(linear: bool, mode: SamplerAddressMode) -> u32 { - let mut w = if linear { SamplerWord::LINEAR } else { 0 }; - for shift in SamplerWord::ADDRESS_SHIFT { - w |= mode.as_raw() << shift; - } - w -} - -/// Metal's sample of `planes` at footprint position `q` (`256 (x - 1/2)` per axis, the texel -/// coordinate `x`) offset by `offset` texels, clamped to the edge: linear, the rule's steps of -/// the four taps; nearest, the texel at `⌊x⌋`. -fn metal(planes: &Planes, linear: bool, (qx, qy): (i64, i64), offset: (i64, i64)) -> [i64; 3] { - let edge = |i: i64, n: u32| i.clamp(0, i64::from(n) - 1); - if !linear { - let x = edge(((qx + 128) >> 8) + offset.0, W); - let y = edge(((qy + 128) >> 8) + offset.1, H); - return planes.texel(x, y); - } - let (i, j) = ((qx >> 8) + offset.0, (qy >> 8) + offset.1); - let (i0, i1) = (edge(i, W), edge(i + 1, W)); - let (j0, j1) = (edge(j, H), edge(j + 1, H)); - let a = if i0 == i1 { 0 } else { qx & 255 }; - let b = if j0 == j1 { 0 } else { qy & 255 }; - let taps = [ - planes.texel(i0, j0), - planes.texel(i1, j0), - planes.texel(i0, j1), - planes.texel(i1, j1), - ]; - std::array::from_fn(|c| metal_step(taps.map(|t| t[c]), a, b)) -} - -/// Every sample the model does not take (a constexpr nearest sampler's) of each format's random -/// planes under each conversion, `float` and `half` results, on lavapipe and on MoltenVK, is -/// Metal's: a quarter of the positions past an edge. -#[test] -fn in_place_samples_are_metals() { - let conversions = [ - (YCbCrRange::Video, YCbCrMatrix::Bt601), - (YCbCrRange::Video, YCbCrMatrix::Bt709), - (YCbCrRange::Video, YCbCrMatrix::Bt2020), - (YCbCrRange::Full, YCbCrMatrix::Bt601), - (YCbCrRange::Full, YCbCrMatrix::Bt709), - (YCbCrRange::Full, YCbCrMatrix::Bt2020), - ]; - let mut rng = Lcg(0x1c_bc_7a_1e); - let planes: Vec = [PixelFormat::YCBCR84202P, PixelFormat::YCBCR104202P] - .into_iter() - .flat_map(|pf| conversions.map(|c| (pf, c))) - .map(|(pf, c)| Planes::random(pf, c, &mut rng)) - .collect(); - // Footprint positions `q = 256 (x - 1/2)`, each axis within one and a half texels of the - // texture; a nearest sample's off the texel edges, where `⌊x⌋` holds for any rounding. - let positions: Vec<(i64, i64)> = (0..64) - .map(|_| { - let mut q = |n: u32| { - let q = (rng.next() % (256 * u64::from(n) + 768)) as i64 - 384; - match (q + 128) & 255 { - 0..8 => q + 8, - 248.. => q - 8, - _ => q, - } - }; - (q(W), q(H)) - }) - .collect(); - let out = |q: i64, n: u32| q < 0 || q >= 256 * (i64::from(n) - 1); - let edges = positions - .iter() - .filter(|&&(qx, qy)| out(qx, W) || out(qy, H)) - .count(); - assert!(edges >= positions.len() / 4, "{edges} past an edge"); - let coords: Vec = positions - .iter() - .flat_map(|&(qx, qy)| { - let n = |q: i64, n: u32| (q + 128) as f32 / (256 * i64::from(n)) as f32; - [n(qx, W).to_le_bytes(), n(qy, H).to_le_bytes()] - }) - .flatten() - .collect(); - { - let (name, through, linear, offset) = ( - "constexpr nearest", - Through::Constexpr(sampler_words(0, 0, 1, false, 0)), - false, - (0, 0), - ); - for half in [false, true] { - let sampler = match through { - Through::Constexpr(w) => Some(w), - Through::Runtime(_) => None, - }; - let form = Form::Plain { - offset: (offset.0 as i32, offset.1 as i32), - }; - let Some(bc) = assemble(name, &kernel_of(sampler, form, !half)) else { - return; - }; - for stem in ["lavapipe", "moltenvk-m3"] { - let p = profile(stem, DevicePolicy::RESIDENT_TABLES).expect("profile"); - let what = format!("{name} half={half} on {stem}"); - let a = compile_with(&bc, "k", &p, &inputs(true)) - .unwrap_or_else(|e| panic!("{what}: {e}")); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: {e}")); - let forms: Vec<&String> = a.strategies.entries.keys().collect(); - assert!( - forms - .iter() - .any(|k| k.starts_with("sampler.ycbcr_in_place.")) - && !forms - .iter() - .any(|k| k.starts_with("sampler.ycbcr_in_place.model")), - "{what}: {forms:?}" - ); - let (plan, m) = typed_module_with(&bc, "k", &p, &inputs(true)) - .unwrap_or_else(|e| panic!("{what}: {e}")); - let slot = texel_buffer(&m); - let n = positions.len(); - let size = if half { 8 } else { 16 }; - for planes in &planes { - let init = [coords.clone(), vec![0xab; size * n]]; - let res = resources(&plan, &init, &planes.words); - let word = match through { - Through::Runtime(w) => Some(w), - Through::Constexpr(_) => None, - }; - let res = with_word(res, &a, word); - let got = run(&m, &res, &planes.image(slot), n as u32, half); - for (q, g) in positions.iter().zip(got) { - let want = metal(planes, linear, *q, offset); - let p = &planes.planes; - assert_eq!( - g, - result_bits(want, half, 2048), - "{what} {:?} {}-bit q {q:?}: {g:x?}", - (p.range, p.matrix), - p.codes.bits, - ); - } - } - } - } - } -} - -/// The model's sample (`in_place`'s **The model**) of `planes` at texel coordinate `(x, y)`, in -/// `f64`: each channel's value. The luma codes around the point blended bilinearly, the chroma -/// pairs around half the point blended bilinearly, each index clamped to its plane, then Metal's -/// coefficients over `2^23`, each channel clamped into `[0, 1]`. -fn model(planes: &Planes, (x, y): (f64, f64)) -> [f64; 3] { - let p = &planes.planes; - let [cw, ch] = [W.div_ceil(2), H.div_ceil(2)]; - let blend = |(x, y): (f64, f64), [w, h]: [u32; 2], v: &dyn Fn(usize) -> f64| -> f64 { - let (px, py) = (x - 0.5, y - 0.5); - let (fx, fy) = (px.floor(), py.floor()); - let (kx, ky) = (px - fx, py - fy); - let edge = |i: f64, n: u32| (i as i64).clamp(0, i64::from(n) - 1) as usize; - let (x0, x1) = (edge(fx, w), edge(fx + 1.0, w)); - let (y0, y1) = (edge(fy, h), edge(fy + 1.0, h)); - let at = |x: usize, y: usize| v(y * w as usize + x); - let low = at(x0, y0) * (1.0 - kx) + at(x1, y0) * kx; - let high = at(x0, y1) * (1.0 - kx) + at(x1, y1) * kx; - low * (1.0 - ky) + high * ky - }; - let luma = blend((x, y), [W, H], &|i| f64::from(planes.luma[i])); - let chroma = |c: usize| { - blend((x / 2.0, y / 2.0), [cw, ch], &|i| { - f64::from(planes.chroma[i][c]) - }) - }; - let bits = p.codes.bits; - let scale = f64::from(1u32 << (10 - bits)); - let (l, cb, cr) = (luma * scale, chroma(0) * scale, chroma(1) * scale); - let grid = f64::from(1u32 << 23); - let term = match p.range { - YCbCrRange::Video => 9576.0 * (l - 64.0) / grid, - YCbCrRange::Full => l / (scale * f64::from((1u32 << bits) - 1)), - }; - crate::bind::ycbcr_convert::coefficients(p.range, p.matrix).map(|(kb, kr)| { - let c = f64::from(kb) * (cb - 512.0) + f64::from(kr) * (cr - 512.0); - (term + c / grid).clamp(0.0, 1.0) - }) -} - -/// The value of `half` bits `h` (a finite value). -fn half_value(h: u32) -> f64 { - let sign = if h & 0x8000 != 0 { -1.0 } else { 1.0 }; - let (e, m) = ((h >> 10) & 0x1f, f64::from(h & 0x3ff)); - sign * match e { - 0 => m * 2f64.powi(-24), - _ => (1.0 + m / 1024.0) * 2f64.powi(e as i32 - 15), - } -} - -/// A linear sample of each format's random planes -/// under each conversion, through a constexpr sampler (normalized and pixel coordinates, with a -/// texel offset on edge axes) and a runtime one (clamp-to-edge, and repeat sampled as -/// clamp-to-edge), `float` and `half` results, on lavapipe and on MoltenVK, is the model's within -/// the `float` arithmetic's rounding (and a `half`'s), alpha 1, and its compile records the filter -/// note under the bound format (and the bound word's linear filter that addresses no border); -/// a runtime sampler's nearest word takes Metal's sample, bit for bit. A constexpr nearest or -/// border sampler takes Metal's sample. -#[test] -fn in_place_linear_samples_are_the_model_s() { - use crate::pipeline::artifact::PrecisionNote; - let conversions = [ - (YCbCrRange::Video, YCbCrMatrix::Bt601), - (YCbCrRange::Video, YCbCrMatrix::Bt709), - (YCbCrRange::Video, YCbCrMatrix::Bt2020), - (YCbCrRange::Full, YCbCrMatrix::Bt601), - (YCbCrRange::Full, YCbCrMatrix::Bt709), - (YCbCrRange::Full, YCbCrMatrix::Bt2020), - ]; - let mut rng = Lcg(0x3d_e1_5a); - let planes: Vec = [PixelFormat::YCBCR84202P, PixelFormat::YCBCR104202P] - .into_iter() - .flat_map(|pf| conversions.map(|c| (pf, c))) - .map(|(pf, c)| Planes::random(pf, c, &mut rng)) - .collect(); - // Footprint positions as `in_place_samples_are_metals` takes them. - let positions: Vec<(i64, i64)> = (0..64) - .map(|_| { - let mut q = |n: u32| { - let q = (rng.next() % (256 * u64::from(n) + 768)) as i64 - 384; - match (q + 128) & 255 { - 0..8 => q + 8, - 248.. => q - 8, - _ => q, - } - }; - (q(W), q(H)) - }) - .collect(); - let coords = |pixel: bool| -> Vec { - positions - .iter() - .flat_map(|&(qx, qy)| { - let n = |q: i64, n: u32| match pixel { - true => (q + 128) as f32 / 256.0, - false => (q + 128) as f32 / (256 * i64::from(n)) as f32, - }; - [n(qx, W).to_le_bytes(), n(qy, H).to_le_bytes()] - }) - .flatten() - .collect() - }; - let edge = SamplerAddressMode::ClampToEdge; - // Each case: its sampler, its coordinates in pixels, its offset, and whether the model takes - // it (else Metal's nearest sample). - let cases = [ - ( - "constexpr", - Through::Constexpr(linear(1, false, 0)), - false, - (0, 0), - true, - ), - ( - "constexpr pixel", - Through::Constexpr(linear(1, true, 0)), - true, - (0, 0), - true, - ), - ( - "constexpr offset", - Through::Constexpr(linear(1, false, 0)), - false, - (2, -1), - true, - ), - ( - "runtime", - Through::Runtime(word(true, edge)), - false, - (0, 0), - true, - ), - ( - "runtime repeat", - Through::Runtime(word(true, SamplerAddressMode::Repeat)), - false, - (0, 0), - true, - ), - ( - "runtime nearest", - Through::Runtime(word(false, edge)), - false, - (0, 0), - false, - ), - ]; - for (name, through, pixel, offset, takes) in cases { - for half in [false, true] { - let sampler = match through { - Through::Constexpr(w) => Some(w), - Through::Runtime(_) => None, - }; - let form = Form::Plain { - offset: (offset.0 as i32, offset.1 as i32), - }; - let Some(bc) = assemble(name, &kernel_of(sampler, form, !half)) else { - return; - }; - let note = match half { - true => PrecisionNote::HalfSampleFilter, - false => PrecisionNote::FloatSampleFilter, - }; - for (stem, p) in [("lavapipe", lavapipe()), ("moltenvk-m3", m3())] { - let what = format!("{name} half={half} on {stem}"); - let a = compile_with(&bc, "k", &p, &inputs(true)) - .unwrap_or_else(|e| panic!("{what}: {e}")); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: {e}")); - let form = match through { - Through::Constexpr(_) => "sampler.ycbcr_in_place.model", - Through::Runtime(_) => "sampler.ycbcr_in_place.model.runtime", - }; - assert!( - a.strategies.entries.contains_key(form), - "{what}: {:?}", - a.strategies.entries.keys().collect::>() - ); - let noted: Vec<_> = a - .specialized - .iter() - .filter(|s| s.note == note) - .flat_map(|s| &s.when) - .collect(); - let words = match through { - Through::Constexpr(_) => 0, - Through::Runtime(_) => 3, - }; - assert!( - noted.len() == 1 - && noted[0].all.len() == 1 + words - && noted[0] - .all - .iter() - .any(|t| t.key == SpecKey::BoundTexelFormat(TEXTURE)), - "{what}: {:?}", - a.specialized - ); - let (plan, m) = typed_module_with(&bc, "k", &p, &inputs(true)) - .unwrap_or_else(|e| panic!("{what}: {e}")); - let slot = texel_buffer(&m); - let n = positions.len(); - let size = if half { 8 } else { 16 }; - for planes in &planes { - let init = [coords(pixel), vec![0xab; size * n]]; - let res = resources(&plan, &init, &planes.words); - let word = match through { - Through::Runtime(w) => Some(w), - Through::Constexpr(_) => None, - }; - let res = with_word(res, &a, word); - let got = run(&m, &res, &planes.image(slot), n as u32, half); - let pl = &planes.planes; - let conversion = ((pl.range, pl.matrix), pl.codes.bits); - for (&(qx, qy), g) in positions.iter().zip(got) { - if !takes { - let want = metal(planes, false, (qx, qy), offset); - assert_eq!( - g, - result_bits(want, half, 2048), - "{what} {conversion:?} q {:?}", - (qx, qy) - ); - continue; - } - let x = (qx + 128) as f64 / 256.0 + offset.0 as f64; - let y = (qy + 128) as f64 / 256.0 + offset.1 as f64; - let want = model(planes, (x, y)); - let (value, within) = match half { - true => (half_value as fn(u32) -> f64, 3e-4), - false => ((|b| f64::from(f32::from_bits(b))) as fn(u32) -> f64, 2e-5), - }; - for c in 0..3 { - let v = value(g[c]); - assert!( - (v - want[c]).abs() <= within, - "{what} {conversion:?} q {:?} channel {c}: {v} against {}", - (qx, qy), - want[c] - ); - } - assert_eq!(value(g[3]), 1.0, "{what}: alpha"); - } - } - } - } - } - // A constexpr nearest sampler and a border one take Metal's sample under the model too. - for (name, words, form) in [ - ( - "nearest", - sampler_words(0, 0, 1, false, 0), - "sampler.ycbcr_in_place.nearest", - ), - ( - "border", - linear(0, false, 0), - "sampler.ycbcr_in_place.linear", - ), - ] { - let Some(bc) = assemble(name, &kernel(Some(words), Form::Float)) else { - return; - }; - let a = compile_with(&bc, "k", &lavapipe(), &inputs(true)) - .unwrap_or_else(|e| panic!("{name}: {e}")); - assert!( - a.strategies.entries.contains_key(form) - && !a - .specialized - .iter() - .any(|s| s.note == PrecisionNote::FloatSampleFilter), - "{name}: {:?} {:?}", - a.strategies.entries.keys().collect::>(), - a.specialized - ); - } -} - -/// Metal's gather of component `c` of `planes` at footprint position `q` (`256 (x - 1/2)` per -/// axis, the texel coordinate `x`), clamped to the edge: component `c`'s steps of the taps -/// `(i, j + 1)`, `(i + 1, j + 1)`, `(i + 1, j)` and `(i, j)` (`i = ⌊q / 256⌋` per axis, each tap -/// clamped), in that order; alpha's step `2048` at every tap. -fn metal_gather(planes: &Planes, (qx, qy): (i64, i64), c: usize) -> [i64; 4] { - let edge = |i: i64, n: u32| i.clamp(0, i64::from(n) - 1); - let (i, j) = (qx >> 8, qy >> 8); - let (i0, i1) = (edge(i, W), edge(i + 1, W)); - let (j0, j1) = (edge(j, H), edge(j + 1, H)); - let step = |x: i64, y: i64| match c { - 3 => 2048, - _ => planes.texel(x, y)[c], - }; - [step(i0, j1), step(i1, j1), step(i1, j0), step(i0, j0)] -} - -/// Every gather of each component of each format's random planes under each conversion, through -/// constexpr and runtime samplers (either filter, which a gather does not follow; a runtime -/// sampler's repeat gathered as clamp-to-edge, as a 4:2:0 texture's), `float` and `half` results, -/// on lavapipe and on MoltenVK, is Metal's taps of the texels Metal reads: a quarter of the -/// positions past an edge. -#[test] -fn in_place_gathers_are_metals() { - let conversions = [ - (YCbCrRange::Video, YCbCrMatrix::Bt601), - (YCbCrRange::Full, YCbCrMatrix::Bt709), - (YCbCrRange::Video, YCbCrMatrix::Bt2020), - ]; - let mut rng = Lcg(0x6a_7e_42); - let planes: Vec = [PixelFormat::YCBCR84202P, PixelFormat::YCBCR104202P] - .into_iter() - .flat_map(|pf| conversions.map(|c| (pf, c))) - .map(|(pf, c)| Planes::random(pf, c, &mut rng)) - .collect(); - // Footprint positions `q = 256 (x - 1/2)`, each axis within one and a half texels of the - // texture, off the places where `⌊q / 256⌋` changes, which hold for any rounding of the - // coordinate. - let positions: Vec<(i64, i64)> = (0..64) - .map(|_| { - let mut q = |n: u32| { - let q = (rng.next() % (256 * u64::from(n) + 768)) as i64 - 384; - match q & 255 { - 0..16 => q + 16, - 240.. => q - 16, - _ => q, - } - }; - (q(W), q(H)) - }) - .collect(); - let out = |q: i64, n: u32| q < 0 || q >= 256 * (i64::from(n) - 1); - let edges = positions - .iter() - .filter(|&&(qx, qy)| out(qx, W) || out(qy, H)) - .count(); - assert!(edges >= positions.len() / 4, "{edges} past an edge"); - let coords: Vec = positions - .iter() - .flat_map(|&(qx, qy)| { - let n = |q: i64, n: u32| (q + 128) as f32 / (256 * i64::from(n)) as f32; - [n(qx, W).to_le_bytes(), n(qy, H).to_le_bytes()] - }) - .flatten() - .collect(); - let edge = SamplerAddressMode::ClampToEdge; - let cases = [ - ( - "constexpr linear gather", - Through::Constexpr(linear(1, false, 0)), - &[0, 1, 2, 3][..], - ), - ( - "constexpr nearest gather", - Through::Constexpr(sampler_words(0, 0, 1, false, 0)), - &[0, 2][..], - ), - ( - "runtime linear gather", - Through::Runtime(word(true, edge)), - &[0, 1, 2, 3][..], - ), - ( - "runtime repeat gather", - Through::Runtime(word(false, SamplerAddressMode::Repeat)), - &[0, 2][..], - ), - ]; - for (name, through, components) in cases { - for &component in components { - for half in [false, true] { - let sampler = match through { - Through::Constexpr(w) => Some(w), - Through::Runtime(_) => None, - }; - let body = kernel_of(sampler, Form::Gather { component }, !half); - let Some(bc) = assemble(name, &body) else { - return; - }; - for (stem, p) in [("lavapipe", lavapipe()), ("moltenvk-m3", m3())] { - let what = format!("{name} of {component} half={half} on {stem}"); - let a = compile_with(&bc, "k", &p, &inputs(true)) - .unwrap_or_else(|e| panic!("{what}: {e}")); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: {e}")); - assert!( - a.strategies - .entries - .contains_key("sampler.ycbcr_in_place.gather"), - "{what}: {:?}", - a.strategies.entries.keys().collect::>() - ); - let (plan, m) = typed_module_with(&bc, "k", &p, &inputs(true)) - .unwrap_or_else(|e| panic!("{what}: {e}")); - let slot = texel_buffer(&m); - let n = positions.len(); - let size = if half { 8 } else { 16 }; - for planes in &planes { - let init = [coords.clone(), vec![0xab; size * n]]; - let res = resources(&plan, &init, &planes.words); - let word = match through { - Through::Runtime(w) => Some(w), - Through::Constexpr(_) => None, - }; - let res = with_word(res, &a, word); - let got = run(&m, &res, &planes.image(slot), n as u32, half); - for (q, g) in positions.iter().zip(got) { - let want = metal_gather(planes, *q, component as usize); - let want = want.map(|k| match half { - true => u32::from(half_away(k, 2048)), - false => (k as f32 / 2048.0).to_bits(), - }); - let p = &planes.planes; - assert_eq!( - g, - want, - "{what} {:?} {}-bit q {q:?}: {g:x?}", - (p.range, p.matrix), - p.codes.bits, - ); - } - } - } - } - } - } -} - -/// A function that samples a slot and gathers it through one runtime sampler, as a probe that -/// samples or gathers as each lane asks: its compile on MoltenVK on the M3 binds the texture's -/// image and samples it through the device's sampler (`PrecisionNote::DeviceSampling`), noting no -/// filter of the format (`PrecisionNote::HalfSampleFilter`, `FloatSampleFilter`), and states the -/// in-place form with the sampler, whose compile reads the planes for both and notes no pixel -/// sampler's scaling: the model's sample where the bound word filters linearly and addresses no -/// border, noting the filter there alone, and Metal's taps. -#[test] -fn a_slot_that_samples_and_gathers_reads_its_planes_in_place() { - use crate::pipeline::artifact::PrecisionNote; - for half in [false, true] { - let what = format!("sample and gather half={half}"); - let Some(bc) = assemble(&what, &kernel_of(None, Form::SampleAndGather, !half)) else { - return; - }; - let filter = match half { - true => PrecisionNote::HalfSampleFilter, - false => PrecisionNote::FloatSampleFilter, - }; - let p = m3(); - let notes = |a: &crate::library::FunctionArtifact| -> Vec { - let specialized = a.specialized.iter().map(|s| s.note); - a.precision.iter().copied().chain(specialized).collect() - }; - let image = - compile_with(&bc, "k", &p, &inputs(false)).unwrap_or_else(|e| panic!("{what}: {e}")); - assert!( - notes(&image).contains(&PrecisionNote::DeviceSampling) - && !notes(&image).contains(&filter), - "{what}: {:?}", - notes(&image) - ); - assert!( - image.facts.contains(&RuntimeFact::YCbCrInPlace { - slot: TEXTURE, - samplers: 1, - device: false, - }), - "{what}: {:?}", - image.facts - ); - { - let (policy, p, sample) = ("model", m3(), "sampler.ycbcr_in_place.model.runtime"); - let what = format!("{what}, in place, {policy}"); - let a = - compile_with(&bc, "k", &p, &inputs(true)).unwrap_or_else(|e| panic!("{what}: {e}")); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: {e}")); - for form in [sample, "sampler.ycbcr_in_place.gather"] { - assert!( - a.strategies.entries.contains_key(form), - "{what}: {:?}", - a.strategies.entries.keys().collect::>() - ); - } - assert!( - !notes(&a).contains(&PrecisionNote::PixelSamplerScaling), - "{what}" - ); - let other = match half { - true => PrecisionNote::FloatSampleFilter, - false => PrecisionNote::HalfSampleFilter, - }; - assert!(!notes(&a).contains(&other), "{what}: {:?}", notes(&a)); - // The model's note holds only under the bound format and word, never outright. - let clauses: Vec<_> = a - .specialized - .iter() - .filter(|s| s.note == filter) - .flat_map(|s| &s.when) - .collect(); - let word = |c: &&crate::pipeline::artifact::SpecClause| { - c.all - .iter() - .any(|t| matches!(t.key, SpecKey::BoundSamplerWord(_))) - }; - assert_eq!( - !clauses.is_empty() && clauses.iter().all(word), - policy == "model", - "{what}: {:?}", - a.specialized - ); - assert_eq!( - notes(&a).contains(&filter), - policy == "model", - "{what}: {:?}", - notes(&a) - ); - } - } -} - -/// A slot whose every access the form reads states `RuntimeFact::YCbCrInPlace` with the runtime -/// samplers it samples through, on every profile (lavapipe, a CPU device; MoltenVK on the M3, an -/// integrated one; the RTX 5080, a discrete one); a dynamic offset, -/// `min_lod_clamp` and a 3D texture keep it from the form, and a gather from the device's own -/// conversion alone (`device`). Its compile under the variant states the same fact, so its plan -/// names the same variant. -#[test] -fn a_slot_states_the_in_place_form_where_it_reads_only_it() { - let fact = |samplers, device| RuntimeFact::YCbCrInPlace { - slot: TEXTURE, - samplers, - device, - }; - let reads = [ - ( - "linear", - kernel(Some(linear(1, false, 0)), Form::Float), - Some((0, true)), - ), - ("runtime", kernel(None, Form::Float), Some((1, true))), - ( - "gather", - kernel(Some(linear(1, false, 0)), Form::Gather { component: 2 }), - Some((0, false)), - ), - ( - "runtime sample and gather", - kernel(None, Form::SampleAndGather), - Some((1, false)), - ), - ( - "dynamic offset", - kernel(Some(linear(1, false, 0)), Form::DynamicOffset), - None, - ), - ( - "min_lod_clamp", - kernel(Some(linear(1, false, 0)), Form::MinLodClamp), - None, - ), - ( - "3d", - kernel( - Some(linear(1, false, 0)), - Form::ThreeD { offset: (0, 0, 0) }, - ), - None, - ), - ]; - for (name, body, samplers) in reads { - let Some(bc) = assemble(name, &body) else { - return; - }; - for stem in ["lavapipe", "moltenvk-m3", "nvidia-rtx5080-laptop"] { - let p = profile(stem, DevicePolicy::RESIDENT_TABLES).expect("profile"); - assert!(p.fields().ycbcr_in_place, "{stem}"); - let what = format!("{name} on {stem}"); - let (plan, _) = typed_module_with(&bc, "k", &p, &inputs(false)) - .unwrap_or_else(|e| panic!("{what}: {e}")); - let stated = plan.facts.iter().find_map(|f| match f { - RuntimeFact::YCbCrInPlace { - slot, - samplers, - device, - } if *slot == TEXTURE => Some((*samplers, *device)), - _ => None, - }); - assert_eq!(stated, samplers, "{what}"); - if let Some((s, device)) = samplers { - let (variant, _) = typed_module_with(&bc, "k", &p, &inputs(true)) - .unwrap_or_else(|e| panic!("{what}, in place: {e}")); - assert!(variant.facts.contains(&fact(s, device)), "{what}, in place"); - } - } - } -} - -/// Under the planes-image variant (`LoweringInputs::ycbcr_planes_sampled`) the slot is one -/// combined image sampler of the device's conversion (`ResourceKind::YCbCrPlanes`), every sample -/// is the device's `OpImageSampleExplicitLod` at level 0 with no offset operand -/// (`VUID-RuntimeSpirv-ConstOffset-10718`), and the module is valid, through a constexpr sampler -/// (nearest and linear, normalized and pixel coordinates, with a texel offset on edge axes) and a -/// runtime one. A sample through a border mode, or with an offset on an axis that repeats, states -/// the in-place fact without `device`, so no plan takes the variant for it. -#[test] -fn a_planes_image_slot_samples_through_the_device_s_conversion() { - use crate::pipeline::interface::StageDescriptor; - use crate::vk; - let codes = ycbcr_format(PixelFormat::YCBCR84202P) - .and_then(YCbCrCodes::of) - .expect("codes"); - let planes = YCbCrPlanes::new( - [8, 4], - [0, 16], - [64, 16], - (YCbCrRange::Video, YCbCrMatrix::Bt709), - codes, - ); - let sampler = YCbCrInPlace::of(&planes).expect("in place").sampler(); - let device_inputs = || { - let mut i = inputs(true); - i.ycbcr_planes_sampled.insert(TEXTURE, sampler); - i - }; - let nearest = sampler_words(0, 0, 1, false, 0); - let device_state = |plan: &Plan| { - plan.facts.iter().find_map(|f| match f { - RuntimeFact::YCbCrInPlace { slot, device, .. } if *slot == TEXTURE => Some(*device), - _ => None, - }) - }; - let taken = [ - ("device linear", Some(linear(1, false, 0)), (0, 0)), - ("device nearest", Some(nearest), (0, 0)), - ("device pixel", Some(linear(1, true, 0)), (0, 0)), - ("device offset", Some(linear(1, false, 0)), (1, -2)), - ("device runtime", None, (0, 0)), - ]; - for (name, sampler_words, offset) in taken { - for half in [false, true] { - let form = Form::Plain { offset }; - let Some(bc) = assemble(name, &kernel_of(sampler_words, form, !half)) else { - return; - }; - for (stem, p) in [("lavapipe", lavapipe()), ("moltenvk-m3", m3())] { - let what = format!("{name} half={half} on {stem}"); - let (plan, _) = typed_module_with(&bc, "k", &p, &inputs(true)) - .unwrap_or_else(|e| panic!("{what}: {e}")); - assert_eq!(device_state(&plan), Some(true), "{what}"); - let a = compile_with(&bc, "k", &p, &device_inputs()) - .unwrap_or_else(|e| panic!("{what}, planes image: {e}")); - let want = StageDescriptor::new( - ResourceSlot { - stage: Stage::Kernel, - kind: ResourceKind::YCbCrPlanes(sampler), - index: 0, - }, - vk::DescriptorType::COMBINED_IMAGE_SAMPLER, - 1, - ); - assert!( - a.interface.descriptors.contains(&want), - "{what}: {:?}", - a.interface.descriptors - ); - assert!( - a.facts.iter().any(|f| matches!( - f, - RuntimeFact::YCbCrInPlace { slot, device: true, .. } if *slot == TEXTURE - )), - "{what}: the variant states the same fact" - ); - let (_, words) = - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: {e}")); - // Every sample: `OpImageSampleExplicitLod` (88) whose operands are `Lod` (0x2) - // alone. - let mut samples = 0; - let mut at = 5; - while let Some(&first) = words.get(at) { - let (count, op) = ((first >> 16) as usize, first & 0xffff); - assert!(count > 0, "{what}: a zero-length instruction"); - if op == 88 { - samples += 1; - assert_eq!(words.get(at + 5), Some(&0x2), "{what}: operands"); - assert_eq!(count, 7, "{what}: the Lod operand alone"); - } - assert!( - !(87..=94).contains(&op) || op == 88, - "{what}: another sample opcode {op}" - ); - at += count; - } - assert_eq!(samples, 1, "{what}"); - } - } - } - // Through a border mode, or with an offset on an axis that repeats: no device sample. - let kept = [ - ("device border", Some(linear(0, false, 0)), (0, 0)), - ("device repeat offset", Some(linear(2, false, 0)), (1, 0)), - ]; - for (name, sampler_words, offset) in kept { - let Some(bc) = assemble( - name, - &kernel_of(sampler_words, Form::Plain { offset }, false), - ) else { - return; - }; - let (plan, _) = typed_module_with(&bc, "k", &lavapipe(), &inputs(true)) - .unwrap_or_else(|e| panic!("{name}: {e}")); - assert_eq!(device_state(&plan), Some(false), "{name}"); - } -} - -/// Under the identity domains a linear sample through a runtime sampler of a two-plane texture -/// whose planes are read in place (`Routine::Quad`) is refused, not implemented, naming the encoder -/// value its slot reads, `PushField::YCbCrInPlace`, which the identity domains refuse before any -/// sampler form. -#[test] -fn an_in_place_linear_sample_is_refused_as_its_slot_s_encoder_value_under_the_identity_domains() { - use crate::device::profile::{HandleDomain, PointerDomain}; - use crate::error::{Error, Feature, Needs}; - let Some(bc) = assemble("identity runtime", &kernel(None, Form::Float)) else { - return; - }; - let identity = DevicePolicy { - pointer_domain: PointerDomain::Identity, - handle_domain: HandleDomain::Identity, - ..DevicePolicy::RESIDENT_TABLES - }; - let p = profile("lavapipe", identity).expect("profile"); - match compile_with(&bc, "k", &p, &inputs(true)) { - Err(Error::Unsupported(u)) => { - assert_eq!( - (u.feature, u.needs), - (Feature::IdentityDomains, Needs::NotImplemented) - ); - assert_eq!( - u.symbol.map(|f| f.to_string()).as_deref(), - Some( - "an encoder value the function reads as YCbCrInPlace(SlotRef { stage: Kernel, \ - class: Texture, index: 0 })" - ) - ); - } - other => panic!("{other:?}"), - } -} diff --git a/crates/metal2vulkan/src/tests/engine_zeroed_colors.rs b/crates/metal2vulkan/src/tests/engine_zeroed_colors.rs index 9fb730dd6..2b3729585 100644 --- a/crates/metal2vulkan/src/tests/engine_zeroed_colors.rs +++ b/crates/metal2vulkan/src/tests/engine_zeroed_colors.rs @@ -1,42 +1,18 @@ //! A pass's color attachments its render pipeline lacks (`VariantKey::zeroed_colors`), over the -//! owned fixtures `engine/rt6_render_state` (Metal's fullscreen triangle and a white fragment -//! function writing color 0) and `engine/stage_io` (a fragment function writing colors 0 and -//! 2): -//! -//! - A render plan whose shape zeroes colors states the variant, which the pipeline compiled -//! without it does not draw (`BindError::NeedsVariant`). Compiled, the variant's modules pass -//! L3; it states `RuntimeFact::ZeroedColor` for each color, and its fragment function declares -//! an output there of the format's numeric class (`float`, `uint`, `int`), four lanes; its -//! pipeline has the attachment in that format, every channel written, unblended; and its plan -//! settles on itself. Without the colors the variant asks for the base again. -//! - A function that writes a color it would zero stores the zero there in place of its own -//! value, as plain Metal does (a Metal probe): its one output at that color is the zero's. -//! - A render plan whose shape drops colors (`VariantKey::dropped_colors`: the pipeline's colors -//! the pass lacks) states the variant, which the base pipeline does not draw; compiled, it -//! passes L3, states `RuntimeFact::DroppedColor` for each color, written or not, and its -//! fragment function keeps no output there; its plan settles on itself. +//! owned fixture `engine/stage_io` (a fragment function writing colors 0 and 2): a function that +//! writes a color it would zero stores the zero there in place of its own value, as plain Metal +//! does (a Metal probe): its one output at that color is the zero's. //! //! `llvm-as` assembles the fixtures; a missing tool skips visibly. No GPU is used. -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::BTreeMap; use std::path::Path; -use crate::bind::{BindState, DrawCall}; -use crate::budget::Budget; use crate::device::{Device, DeviceDescription, DevicePolicy}; -use crate::error::BindError; -use crate::library::Library; use crate::metal::PixelFormat; -use crate::pipeline::descriptor::{ - ColorAttachmentDescriptor, FunctionDescriptor, RenderPipelineDescriptor, StageSource, -}; -use crate::pipeline::facts::RuntimeFact; use crate::pipeline::lower_inputs::LoweringInputs; use crate::pipeline::stage_io::{IoNumeric, IoRole}; -use crate::pipeline::sym::Stage; use crate::pipeline::testing::{compile_with, engine_dir, llvm_assemble, AssembleError}; -use crate::spirv::testing::check_words_valid; -use crate::vk; /// The bitcode of the owned fixture `stem` (`engine/.ll`), or `None` (printed) where /// `llvm-as` is missing. @@ -59,132 +35,6 @@ fn description(stem: &str) -> DeviceDescription { DeviceDescription::from_khronos_json(&text, None).expect("description") } -/// A draw into a pass whose colors the pipeline (color 0, `RGBA8Unorm`) lacks: the variant, which -/// the base pipeline does not draw; compiled, its modules, facts, outputs, attachments and -/// settled plan; without the colors, the base again. -#[test] -fn a_draw_into_colors_the_pipeline_lacks_runs_the_variant_writing_zero() { - let Some(bc) = fixture("rt6_render_state") else { - return; - }; - let budget = Budget::standard(); - let lib = Library::from_air(&bc).expect("library"); - let mut d = RenderPipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new( - lib.function("rt6_full").expect("vertex"), - ))); - d.fragment = Some(StageSource::Function(FunctionDescriptor::new( - lib.function("rt6_white").expect("fragment"), - ))); - d.color_attachments[0] = Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm)); - let triangle = DrawCall::Primitives { - vertex_start: 0, - vertex_count: 3, - instance_count: 1, - base_instance: 0, - }; - let cases = [ - ( - BTreeMap::from([(1, PixelFormat::RGBA8Unorm)]), - [(1, IoNumeric::Float)].as_slice(), - ), - ( - BTreeMap::from([(1, PixelFormat::R32Uint), (3, PixelFormat::RGBA32Sint)]), - [(1, IoNumeric::Uint), (3, IoNumeric::Sint)].as_slice(), - ), - ]; - for stem in ["moltenvk-m3", "lavapipe"] { - let dev = - Device::from_queries(description(stem), DevicePolicy::RESIDENT_TABLES).expect("device"); - let base = dev - .compile_render_pipeline(&d, &budget) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - for (zeroed, numerics) in &cases { - let what = format!("{stem} {zeroed:?}"); - let state = BindState { - zeroed_colors: zeroed.clone(), - ..Default::default() - }; - let plan = base - .plan(&dev, &state.shape()) - .unwrap_or_else(|e| panic!("{what}: {e:?}")); - assert_eq!(plan.variant.zeroed_colors, *zeroed, "{what}"); - assert_eq!( - plan.instantiate_draw(&state, &triangle), - Err(BindError::NeedsVariant { - variant: Box::new(plan.variant.clone()) - }), - "{what}" - ); - let key = plan.variant.clone(); - let p = dev - .compile_render_variant(&d, &key, &budget) - .unwrap_or_else(|e| panic!("{what}: {e}")); - for m in &p.stages { - check_words_valid(&m.spirv, &p.requirements, dev.profile()) - .unwrap_or_else(|e| panic!("{what} {:?}: L3: {e}", m.stage)); - } - for (&color, &format) in zeroed { - assert!( - p.dependencies - .iter() - .any(|x| x.fact == RuntimeFact::ZeroedColor { color, format }), - "{what}: the fact of color {color}" - ); - let state = p.graphics.color_attachments.get(color as usize); - let state = state.and_then(Option::as_ref); - let all = vk::ColorComponentFlags::R - | vk::ColorComponentFlags::G - | vk::ColorComponentFlags::B - | vk::ColorComponentFlags::A; - assert!( - state.is_some_and(|s| s.write_mask == all && s.blend.is_none()), - "{what}: the attachment of color {color}: {state:?}" - ); - } - // The fragment function compiled alone under the variant's inputs declares each - // color's output of its format's numeric class. - let fragment = compile_with( - &bc, - "rt6_white", - dev.profile(), - &key.lowering_inputs(Stage::Fragment), - ) - .unwrap_or_else(|e| panic!("{what}: {e}")); - for &(color, numeric) in numerics.iter() { - let output = fragment.interface.io.outputs.iter().find(|o| { - o.role - == IoRole::Color { - attachment: color, - index: 0, - } - }); - assert!( - output.is_some_and(|o| o.ty.numeric == numeric && o.ty.components == 4), - "{what}: the output of color {color}: {output:?}" - ); - } - let plan = p - .plan(&dev, &state.shape()) - .unwrap_or_else(|e| panic!("{what}: {e:?}")); - assert_eq!(plan.variant, key, "{what}"); - plan.instantiate_draw(&state, &triangle) - .unwrap_or_else(|e| panic!("{what}: {e:?}")); - // Without the colors the variant asks for the base again. - let plan = p - .plan(&dev, &BindState::default().shape()) - .unwrap_or_else(|e| panic!("{what}: {e:?}")); - assert!(plan.variant.zeroed_colors.is_empty(), "{what}"); - assert!( - matches!( - plan.instantiate_draw(&BindState::default(), &triangle), - Err(BindError::NeedsVariant { .. }) - ), - "{what}" - ); - } - } -} - /// A fragment function writing a color it would zero (`stage_io_fragment` writes colors 0 and /// 2, color 2 a `uint4`) stores the zero there in place of its own value, as plain Metal does: its /// one output at color 2 is the zero's, of the zeroed format's numeric class (a `float` one too, @@ -232,98 +82,3 @@ fn a_function_writing_a_color_it_would_zero_stores_the_zero_there() { assert!(a.interface.io.unattached_colors.is_empty(), "{format:?}"); } } - -/// A draw whose pass lacks colors the pipeline has: the variant that drops what the fragment -/// function writes there, which the base pipeline does not draw; compiled, its modules, facts and -/// outputs, and its settled plan. A function compiled alone drops a color it writes and states -/// one it does not. -#[test] -fn a_draw_without_colors_the_pipeline_has_runs_the_variant_dropping_them() { - let Some(bc) = fixture("rt6_render_state") else { - return; - }; - let budget = Budget::standard(); - let lib = Library::from_air(&bc).expect("library"); - let mut d = RenderPipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new( - lib.function("rt6_full").expect("vertex"), - ))); - d.fragment = Some(StageSource::Function(FunctionDescriptor::new( - lib.function("rt6_white").expect("fragment"), - ))); - d.color_attachments[0] = Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm)); - d.color_attachments[1] = Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm)); - let triangle = DrawCall::Primitives { - vertex_start: 0, - vertex_count: 3, - instance_count: 1, - base_instance: 0, - }; - for stem in ["moltenvk-m3", "lavapipe"] { - let dev = - Device::from_queries(description(stem), DevicePolicy::RESIDENT_TABLES).expect("device"); - let base = dev - .compile_render_pipeline(&d, &budget) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - // The fixture writes color 0 alone: dropping it leaves no color output; dropping color - // 1 changes no output but is stated. - for dropped in [BTreeSet::from([0]), BTreeSet::from([1])] { - let what = format!("{stem} {dropped:?}"); - let state = BindState { - dropped_colors: dropped.clone(), - ..Default::default() - }; - let plan = base - .plan(&dev, &state.shape()) - .unwrap_or_else(|e| panic!("{what}: {e:?}")); - assert_eq!(plan.variant.dropped_colors, dropped, "{what}"); - assert_eq!( - plan.instantiate_draw(&state, &triangle), - Err(BindError::NeedsVariant { - variant: Box::new(plan.variant.clone()) - }), - "{what}" - ); - let key = plan.variant.clone(); - let p = dev - .compile_render_variant(&d, &key, &budget) - .unwrap_or_else(|e| panic!("{what}: {e}")); - for m in &p.stages { - check_words_valid(&m.spirv, &p.requirements, dev.profile()) - .unwrap_or_else(|e| panic!("{what} {:?}: L3: {e}", m.stage)); - } - for &color in &dropped { - assert!( - p.dependencies - .iter() - .any(|x| x.fact == RuntimeFact::DroppedColor { color }), - "{what}: the fact of color {color}" - ); - } - let fragment = compile_with( - &bc, - "rt6_white", - dev.profile(), - &key.lowering_inputs(Stage::Fragment), - ) - .unwrap_or_else(|e| panic!("{what}: {e}")); - let colors: BTreeSet = fragment - .interface - .io - .outputs - .iter() - .filter_map(|o| match o.role { - IoRole::Color { attachment, .. } => Some(attachment), - _ => None, - }) - .collect(); - let kept: BTreeSet = BTreeSet::from([0]).difference(&dropped).copied().collect(); - assert_eq!(colors, kept, "{what}: the color outputs"); - let plan = p - .plan(&dev, &state.shape()) - .unwrap_or_else(|e| panic!("{what}: {e:?}")); - assert_eq!(plan.variant, key, "{what}"); - plan.instantiate_draw(&state, &triangle) - .unwrap_or_else(|e| panic!("{what}: {e:?}")); - } - } -} diff --git a/crates/metal2vulkan/src/tests/fuzz_interp.rs b/crates/metal2vulkan/src/tests/fuzz_interp.rs index 2368245b5..b8125a4a9 100644 --- a/crates/metal2vulkan/src/tests/fuzz_interp.rs +++ b/crates/metal2vulkan/src/tests/fuzz_interp.rs @@ -30,7 +30,6 @@ use std::collections::BTreeMap; -use crate::bind::ExecutionStatus; use crate::budget::SPIRV_WORDS; use crate::device::{DevicePolicy, DeviceProfile, SubgroupSizes}; use crate::pipeline::compile::compile_bitcode_kept; @@ -148,7 +147,7 @@ fn widths(sizes: SubgroupSizes, pinned: Option) -> Result } /// The `ExecutionStatus` buffer's 32-bit words. -const STATUS_WORDS: usize = ExecutionStatus::BYTES / 4; +const STATUS_WORDS: usize = crate::bind::status::StatusWord::SeqCstFences.index() as usize + 1; /// Check every word of the `ExecutionStatus` buffer `bytes` after a run: a run that misses /// nothing leaves every word 0 (no status bit, no resident-set miss, reserved words untouched). @@ -349,7 +348,7 @@ impl Execute for CpuInterp { buffers.push(Buffer { slot: None, address: Some(STATUS), - bytes: ExecutionStatus::initial().to_vec(), + bytes: vec![0; 4 * STATUS_WORDS], }); buffers.len() - 1 }); diff --git a/crates/metal2vulkan/src/tests/mod.rs b/crates/metal2vulkan/src/tests/mod.rs index 5f2ec9844..722f69a32 100644 --- a/crates/metal2vulkan/src/tests/mod.rs +++ b/crates/metal2vulkan/src/tests/mod.rs @@ -8,7 +8,6 @@ mod air_abi; mod air_canon; mod air_input; mod argument_buffers; -mod bind_shape_of; pub(crate) mod constant_blob_footprint; mod core_image_libraries; mod engine_absent_handles; @@ -31,7 +30,6 @@ mod engine_async_copy; mod engine_atomics; mod engine_bias_reach; mod engine_bicubic; -mod engine_binder; mod engine_bit_manipulation; mod engine_buffer_table; mod engine_chosen_pointers; @@ -67,12 +65,10 @@ mod engine_gated_texture_slots; mod engine_generic_pointers; mod engine_gep_index; mod engine_global_builtins; -mod engine_graphics_binder; mod engine_half_hold; mod engine_half_moves; mod engine_handles; -mod engine_heap_binder; -mod engine_heap_residency; +mod engine_heap_groups; mod engine_heap_storage_reads; mod engine_heap_texel_buffers; mod engine_helper_threads; @@ -161,7 +157,6 @@ mod engine_simd_matrix; mod engine_simd_partly_live; mod engine_simd_past_n; mod engine_simd_products; -mod engine_simd_unit_axes; mod engine_skeleton; mod engine_sparse_unmapped; mod engine_spec_bits; @@ -179,7 +174,6 @@ mod engine_table_copies; mod engine_tables; mod engine_target_indices; mod engine_tessellation; -mod engine_texel_rows; mod engine_texture; mod engine_texture_atomic_unk; mod engine_texture_interp; @@ -195,6 +189,7 @@ mod engine_tiny_products; mod engine_trip_carries; mod engine_typed_clamp; mod engine_typed_threadgroup; +mod engine_unattached_colors; mod engine_uniform_varyings; mod engine_unmeasured_speculation; mod engine_unread_attribute; @@ -207,7 +202,6 @@ mod engine_widest_pin; mod engine_word_attachments; mod engine_word_phases; mod engine_workgroup_layout; -mod engine_ycbcr_in_place; mod engine_zero_factors; mod engine_zeroed_colors; mod engine_zeroed_threadgroup; diff --git a/crates/metal2vulkan/src/tests/stage_in_element_bytes.rs b/crates/metal2vulkan/src/tests/stage_in_element_bytes.rs index 9b1e594bc..a0f47529a 100644 --- a/crates/metal2vulkan/src/tests/stage_in_element_bytes.rs +++ b/crates/metal2vulkan/src/tests/stage_in_element_bytes.rs @@ -7,18 +7,3 @@ //! encoding (`lower::stage_io::fetch::Encoding::bytes`). Where the two disagreed, a key of false //! would drop a check the fetch needs, or a key of true keep one it does not: this holds them //! equal for every format. - -use crate::lower::stage_io::fetch::encoding; -use crate::metal::vertex::vertex_bytes; -use crate::metal::VertexFormat; - -#[test] -fn the_binder_s_attribute_size_is_the_fetch_s_for_every_format() { - for &format in VertexFormat::ALL { - let fetched = encoding(format).ok().map(|e| e.bytes()); - assert_eq!(vertex_bytes(format), fetched, "{format:?}"); - } - assert_eq!(vertex_bytes(VertexFormat::Invalid), None); - assert_eq!(vertex_bytes(VertexFormat::Float3), Some(12)); - assert_eq!(vertex_bytes(VertexFormat::UChar3), Some(3)); -} diff --git a/crates/metal2vulkan/src/vk/draw.rs b/crates/metal2vulkan/src/vk/draw.rs deleted file mode 100644 index 8fc0af07a..000000000 --- a/crates/metal2vulkan/src/vk/draw.rs +++ /dev/null @@ -1,69 +0,0 @@ -//! `vk::DrawCommand`: the Vulkan draw call a draw plan instantiates to. -//! -//! Hand-written plain data, owned (the binder's draw output); the binder produces it and -//! `ash_interop` may add conversions. The buffers themselves are the consumer's: indirect and index -//! buffers are named by the `DrawCall` the consumer passed in. - -use super::IndexType; - -/// One Vulkan draw command, with the parameters of the matching `vkCmdDraw*` call. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub enum DrawCommand { - /// `vkCmdDraw`. - Draw { - vertex_count: u32, - instance_count: u32, - first_vertex: u32, - first_instance: u32, - }, - /// `vkCmdBindIndexBuffer` + `vkCmdDrawIndexed`. - DrawIndexed { - index_type: IndexType, - /// Byte offset of the index buffer binding. - index_buffer_offset: u64, - index_count: u32, - instance_count: u32, - first_index: u32, - vertex_offset: i32, - first_instance: u32, - }, - /// `vkCmdDrawIndirect`, reading `VkDrawIndirectCommand` from the indirect buffer (layout-equal - /// to `MTLDrawPrimitivesIndirectArguments`). - DrawIndirect { - offset: u64, - draw_count: u32, - stride: u32, - }, - /// `vkCmdBindIndexBuffer` + `vkCmdDrawIndexedIndirect` (layout-equal to - /// `MTLDrawIndexedPrimitivesIndirectArguments`). - DrawIndexedIndirect { - index_type: IndexType, - index_buffer_offset: u64, - offset: u64, - draw_count: u32, - stride: u32, - }, - /// `vkCmdDrawMeshTasksEXT` (`VK_EXT_mesh_shader`) of a mesh render pipeline. - DrawMeshTasks { - group_count_x: u32, - group_count_y: u32, - group_count_z: u32, - }, - /// `vkCmdDrawMeshTasksIndirectEXT`, reading `VkDrawMeshTasksIndirectCommandEXT` from the - /// indirect buffer (layout-equal to `MTLDispatchThreadgroupsIndirectArguments`). - DrawMeshTasksIndirect { - offset: u64, - draw_count: u32, - stride: u32, - }, - /// `vkCmdDrawMeshTasksIndirectCountEXT` (`drawIndirectCount`): the draw count is the `u32` at - /// `count_offset`, at most `max_draw_count`, and the commands start at `offset`, both in the - /// buffer the draw names. - DrawMeshTasksIndirectCount { - offset: u64, - count_offset: u64, - max_draw_count: u32, - stride: u32, - }, -} diff --git a/crates/metal2vulkan/src/vk/mod.rs b/crates/metal2vulkan/src/vk/mod.rs index adbaa1379..9b75511df 100644 --- a/crates/metal2vulkan/src/vk/mod.rs +++ b/crates/metal2vulkan/src/vk/mod.rs @@ -14,18 +14,15 @@ //! extensions define each format value. //! //! The hand-written structs mirror Vulkan's: [`SpecializationMapEntry`], [`ComponentMapping`], -//! [`SamplerDesc`] (the translation-relevant part of `VkSamplerCreateInfo`), and [`DrawCommand`] -//! (the parameters of one `vkCmdDraw*` call), with [`FormatBlock`] and [`NumericFormat`] for the -//! registry's format facts. +//! and [`SamplerDesc`] (the translation-relevant part of `VkSamplerCreateInfo`), with +//! [`FormatBlock`] and [`NumericFormat`] for the registry's format facts. // `generated.rs` is written by `scripts/regen-vk-types/` (never hand-edited); the hand-written -// structs live in `structs.rs`, and `DrawCommand` in `draw.rs`. +// structs live in `structs.rs`. // The generated file invokes the macros below, so it is declared after them (textual scoping). -mod draw; mod structs; -pub use draw::DrawCommand; pub use generated::*; pub use structs::{ ComponentMapping, FormatBlock, FormatExposure, NumericFormat, NumericType, SamplerDesc, diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 6a8f56a87..d3de90bb5 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -59,31 +59,7 @@ assoc-const metal2vulkan-runtime::ResourceUsage::READ pub const READ: ResourceUs assoc-const metal2vulkan-runtime::ResourceUsage::SAMPLE pub const SAMPLE: ResourceUsage assoc-const metal2vulkan-runtime::ResourceUsage::WRITE pub const WRITE: ResourceUsage assoc-const metal2vulkan-runtime::TextureSwizzleChannels::DEFAULT pub const DEFAULT: TextureSwizzleChannels -assoc-const metal2vulkan::bind::ArgumentSamplersShape::MIN_ENTRIES pub const MIN_ENTRIES: u64 assoc-const metal2vulkan::bind::AstcDecode::BLOCK_BYTES pub const BLOCK_BYTES: u32 -assoc-const metal2vulkan::bind::ExecutionStatus::BYTES pub const BYTES: usize -assoc-const metal2vulkan::bind::MeshArguments::OBJECT_COMMANDS pub const OBJECT_COMMANDS: u32 -assoc-const metal2vulkan::bind::MeshArguments::OBJECT_COUNT pub const OBJECT_COUNT: u32 -assoc-const metal2vulkan::bind::MeshArguments::OBJECT_PIECES pub const OBJECT_PIECES: u32 -assoc-const metal2vulkan::bind::NeutralResource::SINK_BYTES pub const SINK_BYTES: u32 -assoc-const metal2vulkan::bind::RootTable::SINK_HOST_OFFSET pub const SINK_HOST_OFFSET: u32 -assoc-const metal2vulkan::bind::StatusBits::CUBIC_ARGUMENT_SAMPLER pub const CUBIC_ARGUMENT_SAMPLER: StatusBits -assoc-const metal2vulkan::bind::StatusBits::MESH_GRID_DISCARDED pub const MESH_GRID_DISCARDED: StatusBits -assoc-const metal2vulkan::bind::StatusBits::MESH_GRID_PAST_LIMITS pub const MESH_GRID_PAST_LIMITS: StatusBits -assoc-const metal2vulkan::bind::StatusBits::RESIDENT_MISS pub const RESIDENT_MISS: StatusBits -assoc-const metal2vulkan::bind::TexelRows::FIRST pub const FIRST: usize -assoc-const metal2vulkan::bind::TexelRows::HEIGHT pub const HEIGHT: usize -assoc-const metal2vulkan::bind::TexelRows::ROW pub const ROW: usize -assoc-const metal2vulkan::bind::TexelRows::WIDTH pub const WIDTH: usize -assoc-const metal2vulkan::bind::TexelRows::WORDS pub const WORDS: usize -assoc-const metal2vulkan::bind::YCbCrInPlace::CHROMA_AT pub const CHROMA_AT: usize -assoc-const metal2vulkan::bind::YCbCrInPlace::CHROMA_ROW pub const CHROMA_ROW: usize -assoc-const metal2vulkan::bind::YCbCrInPlace::CONVERSION pub const CONVERSION: usize -assoc-const metal2vulkan::bind::YCbCrInPlace::HEIGHT pub const HEIGHT: usize -assoc-const metal2vulkan::bind::YCbCrInPlace::LUMA_AT pub const LUMA_AT: usize -assoc-const metal2vulkan::bind::YCbCrInPlace::LUMA_ROW pub const LUMA_ROW: usize -assoc-const metal2vulkan::bind::YCbCrInPlace::WIDTH pub const WIDTH: usize -assoc-const metal2vulkan::bind::YCbCrInPlace::WORDS pub const WORDS: usize assoc-const metal2vulkan::bind::indirect_commands::BufferBinding::MIN_BUFFER_ADDRESS pub const MIN_BUFFER_ADDRESS: u64 assoc-const metal2vulkan::bind::indirect_commands::RenderDraws::PRIMITIVES pub const PRIMITIVES: RenderDraws assoc-const metal2vulkan::device::ApiVersion::V1_2 pub const V1_2: ApiVersion @@ -232,31 +208,7 @@ assoc-const-value metal2vulkan-runtime::ResourceUsage::READ ResourceUsage(1) assoc-const-value metal2vulkan-runtime::ResourceUsage::SAMPLE ResourceUsage(4) assoc-const-value metal2vulkan-runtime::ResourceUsage::WRITE ResourceUsage(2) assoc-const-value metal2vulkan-runtime::TextureSwizzleChannels::DEFAULT TextureSwizzleChannels -assoc-const-value metal2vulkan::bind::ArgumentSamplersShape::MIN_ENTRIES 16 assoc-const-value metal2vulkan::bind::AstcDecode::BLOCK_BYTES 16 -assoc-const-value metal2vulkan::bind::ExecutionStatus::BYTES 16 -assoc-const-value metal2vulkan::bind::MeshArguments::OBJECT_COMMANDS 36 -assoc-const-value metal2vulkan::bind::MeshArguments::OBJECT_COUNT 32 -assoc-const-value metal2vulkan::bind::MeshArguments::OBJECT_PIECES 256 -assoc-const-value metal2vulkan::bind::NeutralResource::SINK_BYTES 64 -assoc-const-value metal2vulkan::bind::RootTable::SINK_HOST_OFFSET (SINK_ROOT * ENTRY_BYTES + HOST) as u32 -assoc-const-value metal2vulkan::bind::StatusBits::CUBIC_ARGUMENT_SAMPLER StatusBits(1 <<3) -assoc-const-value metal2vulkan::bind::StatusBits::MESH_GRID_DISCARDED StatusBits(1 <<5) -assoc-const-value metal2vulkan::bind::StatusBits::MESH_GRID_PAST_LIMITS StatusBits(1 <<4) -assoc-const-value metal2vulkan::bind::StatusBits::RESIDENT_MISS StatusBits(1 <<0) -assoc-const-value metal2vulkan::bind::TexelRows::FIRST 3 -assoc-const-value metal2vulkan::bind::TexelRows::HEIGHT 1 -assoc-const-value metal2vulkan::bind::TexelRows::ROW 2 -assoc-const-value metal2vulkan::bind::TexelRows::WIDTH 0 -assoc-const-value metal2vulkan::bind::TexelRows::WORDS 4 -assoc-const-value metal2vulkan::bind::YCbCrInPlace::CHROMA_AT 4 -assoc-const-value metal2vulkan::bind::YCbCrInPlace::CHROMA_ROW 5 -assoc-const-value metal2vulkan::bind::YCbCrInPlace::CONVERSION 6 -assoc-const-value metal2vulkan::bind::YCbCrInPlace::HEIGHT 1 -assoc-const-value metal2vulkan::bind::YCbCrInPlace::LUMA_AT 2 -assoc-const-value metal2vulkan::bind::YCbCrInPlace::LUMA_ROW 3 -assoc-const-value metal2vulkan::bind::YCbCrInPlace::WIDTH 0 -assoc-const-value metal2vulkan::bind::YCbCrInPlace::WORDS 8 assoc-const-value metal2vulkan::bind::indirect_commands::BufferBinding::MIN_BUFFER_ADDRESS 1 <<32 assoc-const-value metal2vulkan::bind::indirect_commands::RenderDraws::PRIMITIVES RenderDraws assoc-const-value metal2vulkan::device::ApiVersion::V1_2 ApiVersion @@ -398,14 +350,7 @@ const metal2vulkan-runtime::floor::OPTIONAL_INSTANCE_EXTENSIONS pub const OPTION const metal2vulkan-runtime::floor::TIME_DOMAINS pub const TIME_DOMAINS: [vk::TimeDomainKHR; 2] const metal2vulkan-runtime::floor::VERSION pub const VERSION: u32 const metal2vulkan::bind::ARGUMENT_HANDLE_BYTES pub const ARGUMENT_HANDLE_BYTES: u64 -const metal2vulkan::bind::DRAW_ARGUMENT_BYTES pub const DRAW_ARGUMENT_BYTES: u64 -const metal2vulkan::bind::DRAW_INDEX_ENTRY_BYTES pub const DRAW_INDEX_ENTRY_BYTES: u64 -const metal2vulkan::bind::HANDLE_ENTRY_BYTES pub const HANDLE_ENTRY_BYTES: u32 const metal2vulkan::bind::MAX_SCREEN_EXTENT pub const MAX_SCREEN_EXTENT: u32 -const metal2vulkan::bind::MERGED_REST_FIRST pub const MERGED_REST_FIRST: u32 -const metal2vulkan::bind::METAL_MESH_GRID_AXIS pub const METAL_MESH_GRID_AXIS: u32 -const metal2vulkan::bind::METAL_MESH_GRID_TOTAL pub const METAL_MESH_GRID_TOTAL: u32 -const metal2vulkan::bind::METAL_OBJECT_GRID_TOTAL pub const METAL_OBJECT_GRID_TOTAL: u32 const metal2vulkan::bind::indirect_commands::BINDING_COUNT pub const BINDING_COUNT: usize const metal2vulkan::bind::indirect_commands::COMMAND_BUFFER_HEADER_BYTES pub const COMMAND_BUFFER_HEADER_BYTES: usize const metal2vulkan::bind::indirect_commands::COMMAND_BYTES pub const COMMAND_BYTES: usize @@ -470,14 +415,7 @@ const-value metal2vulkan-runtime::floor::OPTIONAL_INSTANCE_EXTENSIONS &[ash::khr const-value metal2vulkan-runtime::floor::TIME_DOMAINS [vk::TimeDomainKHR::DEVICE, crate::times::HOST_DOMAIN] const-value metal2vulkan-runtime::floor::VERSION vk::API_VERSION_1_3 const-value metal2vulkan::bind::ARGUMENT_HANDLE_BYTES 8 -const-value metal2vulkan::bind::DRAW_ARGUMENT_BYTES 16 -const-value metal2vulkan::bind::DRAW_INDEX_ENTRY_BYTES 16 -const-value metal2vulkan::bind::HANDLE_ENTRY_BYTES TABLE_ENTRY_BYTES const-value metal2vulkan::bind::MAX_SCREEN_EXTENT 1 <<16 -const-value metal2vulkan::bind::MERGED_REST_FIRST 1 <<31 -const-value metal2vulkan::bind::METAL_MESH_GRID_AXIS 65_535 -const-value metal2vulkan::bind::METAL_MESH_GRID_TOTAL 1_048_575 -const-value metal2vulkan::bind::METAL_OBJECT_GRID_TOTAL 1 <<29 const-value metal2vulkan::bind::indirect_commands::BINDING_COUNT 32 const-value metal2vulkan::bind::indirect_commands::COMMAND_BUFFER_HEADER_BYTES 16 const-value metal2vulkan::bind::indirect_commands::COMMAND_BYTES ((THREADGROUP_WORD + THREADGROUP_COUNT + 2) * 4).next_multiple_of(8) @@ -676,39 +614,15 @@ enum metal2vulkan-runtime::VariantStart #[derive(Clone, Copy, Debug, PartialEq, enum metal2vulkan-runtime::VisibilityResultMode #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum VisibilityResultMode enum metal2vulkan-runtime::VisibilityResultType #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum VisibilityResultType enum metal2vulkan-runtime::floor::Missing #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub enum Missing -enum metal2vulkan::bind::AccessClass #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum AccessClass enum metal2vulkan::bind::ArgumentLayoutError #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub enum ArgumentLayoutError enum metal2vulkan::bind::ArgumentType #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum ArgumentType enum metal2vulkan::bind::AstcTexels #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum AstcTexels -enum metal2vulkan::bind::BoundBuffer #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum BoundBuffer -enum metal2vulkan::bind::BoundTexture #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum BoundTexture -enum metal2vulkan::bind::BufferShape #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum BufferShape enum metal2vulkan::bind::Dispatch #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum Dispatch enum metal2vulkan::bind::DrawCall #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum DrawCall enum metal2vulkan::bind::EtcDecode #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum EtcDecode enum metal2vulkan::bind::EtcTexels #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum EtcTexels -enum metal2vulkan::bind::FieldLocation #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum FieldLocation -enum metal2vulkan::bind::HeapPlacement #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum HeapPlacement -enum metal2vulkan::bind::HeapSource #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum HeapSource -enum metal2vulkan::bind::ImageSource #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum ImageSource -enum metal2vulkan::bind::IndexOverrun #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum IndexOverrun -enum metal2vulkan::bind::IndirectArgs #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum IndirectArgs -enum metal2vulkan::bind::MeshArgumentsForm #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum MeshArgumentsForm -enum metal2vulkan::bind::NeutralResource #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum NeutralResource -enum metal2vulkan::bind::PlanDiagnostic #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum PlanDiagnostic -enum metal2vulkan::bind::PushHole #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum PushHole enum metal2vulkan::bind::RateMapError #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub enum RateMapError -enum metal2vulkan::bind::ResourceClass #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum ResourceClass -enum metal2vulkan::bind::SamplerSource #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum SamplerSource -enum metal2vulkan::bind::StatusWord #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum StatusWord -enum metal2vulkan::bind::TextureShape #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum TextureShape enum metal2vulkan::bind::UnpinnedCompile #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub enum UnpinnedCompile -enum metal2vulkan::bind::UseTarget #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum UseTarget -enum metal2vulkan::bind::UsedClass #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum UsedClass -enum metal2vulkan::bind::WriteSource #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum WriteSource -enum metal2vulkan::bind::YCbCrMatrix #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum YCbCrMatrix -enum metal2vulkan::bind::YCbCrOutput #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum YCbCrOutput -enum metal2vulkan::bind::YCbCrRange #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum YCbCrRange enum metal2vulkan::bind::indirect_commands::Action #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum Action enum metal2vulkan::bind::indirect_commands::AddressError #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] pub enum AddressError enum metal2vulkan::bind::indirect_commands::BindingError #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum BindingError @@ -740,7 +654,6 @@ enum metal2vulkan::device::VkLimit #[derive(Clone, Copy, Debug, PartialEq, Eq, P enum metal2vulkan::device::VkProperty #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum VkProperty enum metal2vulkan::error::AbiError #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub enum AbiError enum metal2vulkan::error::Attachment #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum Attachment -enum metal2vulkan::error::BindError #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub enum BindError enum metal2vulkan::error::BitcodeError #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub enum BitcodeError enum metal2vulkan::error::BitstreamError #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub enum BitstreamError enum metal2vulkan::error::BudgetExceeded #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum BudgetExceeded @@ -823,7 +736,6 @@ enum metal2vulkan::pipeline::Window #[cfg_attr(feature = "serde", derive(serde:: enum metal2vulkan::reflection::LinkedUseGap #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum LinkedUseGap enum metal2vulkan::reflection::SlotWritability #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum SlotWritability enum metal2vulkan::reflection::SlotWriteGap #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum SlotWriteGap -enum metal2vulkan::vk::DrawCommand #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum DrawCommand enum metal2vulkan::vk::NumericFormat #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum NumericFormat enum metal2vulkan::vk::NumericType #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum NumericType field metal2vulkan-air::ConstValue.bytes pub bytes: Box<[u8]> @@ -1906,9 +1818,6 @@ field metal2vulkan::bind::ArgumentDescriptor.constant_block_alignment pub consta field metal2vulkan::bind::ArgumentDescriptor.data_type pub data_type: DataType field metal2vulkan::bind::ArgumentDescriptor.index pub index: u32 field metal2vulkan::bind::ArgumentDescriptor.texture_type pub texture_type: TextureType -field metal2vulkan::bind::ArgumentFunctionTable.address pub address: u64 -field metal2vulkan::bind::ArgumentFunctionTable.resource_id pub resource_id: u64 -field metal2vulkan::bind::ArgumentFunctionTable.size pub size: u32 field metal2vulkan::bind::ArgumentMember.count pub count: u32 field metal2vulkan::bind::ArgumentMember.id pub id: u32 field metal2vulkan::bind::ArgumentMember.ids_per_element pub ids_per_element: u32 @@ -1917,168 +1826,12 @@ field metal2vulkan::bind::ArgumentMember.offset pub offset: u64 field metal2vulkan::bind::ArgumentMember.size pub size: u64 field metal2vulkan::bind::ArgumentMember.stride pub stride: u64 field metal2vulkan::bind::ArgumentMember.ty pub ty: ArgumentType -field metal2vulkan::bind::ArgumentSampler.desc pub desc: SamplerDescriptor -field metal2vulkan::bind::ArgumentSampler.element pub element: Option -field metal2vulkan::bind::ArgumentSampler.resource_id pub resource_id: u64 -field metal2vulkan::bind::ArgumentSamplersShape.class pub class: u8 -field metal2vulkan::bind::ArgumentSamplersShape.shapes pub shapes: std::collections::BTreeSet field metal2vulkan::bind::AstcDecode.hdr pub hdr: bool field metal2vulkan::bind::AstcDecode.height pub height: u32 field metal2vulkan::bind::AstcDecode.srgb pub srgb: bool field metal2vulkan::bind::AstcDecode.width pub width: u32 -field metal2vulkan::bind::BindShape.argument_samplers pub argument_samplers: ArgumentSamplersShape -field metal2vulkan::bind::BindShape.depth_clamp_range pub depth_clamp_range: bool -field metal2vulkan::bind::BindShape.dropped_colors pub dropped_colors: BTreeSet -field metal2vulkan::bind::BindShape.far_vertex_buffers pub far_vertex_buffers: BTreeSet -field metal2vulkan::bind::BindShape.function_tables pub function_tables: FunctionTablesShape -field metal2vulkan::bind::BindShape.imageblock_size pub imageblock_size: ImageblockSize -field metal2vulkan::bind::BindShape.kept_imageblock_bytes pub kept_imageblock_bytes: Option -field metal2vulkan::bind::BindShape.line_band pub line_band: Option -field metal2vulkan::bind::BindShape.primitive_id_indices pub primitive_id_indices: Option -field metal2vulkan::bind::BindShape.private_list pub private_list: bool -field metal2vulkan::bind::BindShape.quad_primitive_ids pub quad_primitive_ids: bool -field metal2vulkan::bind::BindShape.region_viewports pub region_viewports: bool -field metal2vulkan::bind::BindShape.render_area pub render_area: [u32; 2] -field metal2vulkan::bind::BindShape.render_target_array_length pub render_target_array_length: u32 -field metal2vulkan::bind::BindShape.rotated_weights pub rotated_weights: bool -field metal2vulkan::bind::BindShape.stages pub stages: BTreeMap -field metal2vulkan::bind::BindShape.tessellation_factor_buffer pub tessellation_factor_buffer: bool -field metal2vulkan::bind::BindShape.tile_threadgroup pub tile_threadgroup: TileThreadgroupMemory -field metal2vulkan::bind::BindShape.used pub used: BTreeMap -field metal2vulkan::bind::BindShape.vertex_amplification pub vertex_amplification: VertexAmplification -field metal2vulkan::bind::BindShape.zeroed_colors pub zeroed_colors: BTreeMap -field metal2vulkan::bind::BindState.alpha_test_reference pub alpha_test_reference: Option -field metal2vulkan::bind::BindState.argument_samplers pub argument_samplers: Vec -field metal2vulkan::bind::BindState.blend_color pub blend_color: [f32; 4] -field metal2vulkan::bind::BindState.depth_clamp_range pub depth_clamp_range: Option<[f32; 2]> -field metal2vulkan::bind::BindState.depth_stencil pub depth_stencil: metal::state::DepthStencilDescriptor -field metal2vulkan::bind::BindState.dropped_colors pub dropped_colors: BTreeSet -field metal2vulkan::bind::BindState.far_vertex_buffers pub far_vertex_buffers: BTreeSet -field metal2vulkan::bind::BindState.function_tables pub function_tables: Vec -field metal2vulkan::bind::BindState.heap_placement pub heap_placement: HeapPlacement -field metal2vulkan::bind::BindState.imageblock_size pub imageblock_size: ImageblockSize -field metal2vulkan::bind::BindState.kept_imageblock_bytes pub kept_imageblock_bytes: Option -field metal2vulkan::bind::BindState.line_band pub line_band: Option<(crate::pipeline::BandPrimitive, [f32; 4])> -field metal2vulkan::bind::BindState.primitive_id_indices pub primitive_id_indices: Option -field metal2vulkan::bind::BindState.primitive_type pub primitive_type: Option -field metal2vulkan::bind::BindState.private_list pub private_list: bool -field metal2vulkan::bind::BindState.quad_primitive_ids pub quad_primitive_ids: bool -field metal2vulkan::bind::BindState.region_viewports pub region_viewports: bool -field metal2vulkan::bind::BindState.render_area pub render_area: [u32; 2] -field metal2vulkan::bind::BindState.render_target_array_length pub render_target_array_length: u32 -field metal2vulkan::bind::BindState.resident_apart pub resident_apart: bool -field metal2vulkan::bind::BindState.resident_ranges pub resident_ranges: Vec -field metal2vulkan::bind::BindState.rotated_weights pub rotated_weights: bool -field metal2vulkan::bind::BindState.stage_in_region pub stage_in_region: Option -field metal2vulkan::bind::BindState.stages pub stages: BTreeMap -field metal2vulkan::bind::BindState.tessellation_factors pub tessellation_factors: TessellationFactors -field metal2vulkan::bind::BindState.tile_threadgroup pub tile_threadgroup: TileThreadgroupMemory -field metal2vulkan::bind::BindState.used_in_token_order pub used_in_token_order: bool -field metal2vulkan::bind::BindState.used_resources pub used_resources: Vec -field metal2vulkan::bind::BindState.vertex_amplification pub vertex_amplification: VertexAmplification -field metal2vulkan::bind::BindState.viewport_count pub viewport_count: u32 -field metal2vulkan::bind::BindState.zeroed_colors pub zeroed_colors: BTreeMap -field metal2vulkan::bind::BindingPlan.compute pub compute: Option -field metal2vulkan::bind::BindingPlan.descriptors pub descriptors: Vec -field metal2vulkan::bind::BindingPlan.diagnostics pub diagnostics: Vec -field metal2vulkan::bind::BindingPlan.graphics pub graphics: Option -field metal2vulkan::bind::BindingPlan.push pub push: PushTemplate -field metal2vulkan::bind::BindingPlan.specialization pub specialization: SpecializationKey -field metal2vulkan::bind::BindingPlan.uses pub uses: Vec -field metal2vulkan::bind::BindingPlan.variant pub variant: VariantKey -field metal2vulkan::bind::BindingPlan.vertex_buffers pub vertex_buffers: Vec -field metal2vulkan::bind::BindingPlan.views pub views: ViewSetup -field metal2vulkan::bind::BoundAccelerationStructure.instance_count pub instance_count: u32 -field metal2vulkan::bind::BoundSampler.desc pub desc: SamplerDescriptor -field metal2vulkan::bind::BoundSampler.resource_id pub resource_id: Option -field metal2vulkan::bind::BoundSamplerShape.degree pub degree: u32 -field metal2vulkan::bind::BoundSamplerShape.min_level pub min_level: u32 -field metal2vulkan::bind::BoundSamplerShape.shape pub shape: SamplerShape -field metal2vulkan::bind::BoundSamplerShape.word pub word: metal::sampler::SamplerWord -field metal2vulkan::bind::BufferExtent.slot pub slot: SlotRef -field metal2vulkan::bind::BufferExtent.window pub window: Window -field metal2vulkan::bind::BufferRange.offset pub offset: u64 -field metal2vulkan::bind::BufferRange.range pub range: u64 -field metal2vulkan::bind::BufferRanges.storage pub storage: u32 -field metal2vulkan::bind::ByteRange.len pub len: u64 -field metal2vulkan::bind::ByteRange.offset pub offset: u64 -field metal2vulkan::bind::DescriptorBytes.binding pub binding: u32 -field metal2vulkan::bind::DescriptorBytes.bytes pub bytes: Vec -field metal2vulkan::bind::DescriptorBytes.set pub set: u32 -field metal2vulkan::bind::DescriptorRange.binding pub binding: u32 -field metal2vulkan::bind::DescriptorRange.element pub element: u32 -field metal2vulkan::bind::DescriptorRange.range pub range: BufferRange -field metal2vulkan::bind::DescriptorRange.set pub set: u32 -field metal2vulkan::bind::DescriptorWrite.array_element pub array_element: u32 -field metal2vulkan::bind::DescriptorWrite.binding pub binding: u32 -field metal2vulkan::bind::DescriptorWrite.set pub set: u32 -field metal2vulkan::bind::DescriptorWrite.source pub source: WriteSource -field metal2vulkan::bind::DescriptorWrite.ty pub ty: vk::DescriptorType -field metal2vulkan::bind::DispatchCommands.descriptor_bytes pub descriptor_bytes: Vec -field metal2vulkan::bind::DispatchCommands.descriptor_ranges pub descriptor_ranges: Vec -field metal2vulkan::bind::DispatchCommands.extents pub extents: Vec -field metal2vulkan::bind::DispatchCommands.push_holes pub push_holes: Vec -field metal2vulkan::bind::DispatchCommands.region_record pub region_record: Option<[u8; 32]> -field metal2vulkan::bind::DispatchCommands.regions pub regions: Vec -field metal2vulkan::bind::DispatchCommands.root_table pub root_table: Option -field metal2vulkan::bind::DispatchCommands.uses pub uses: Vec -field metal2vulkan::bind::DispatchRegion.group_count pub group_count: [u32; 3] -field metal2vulkan::bind::DispatchRegion.indirect pub indirect: Option -field metal2vulkan::bind::DispatchRegion.push_constants pub push_constants: Vec -field metal2vulkan::bind::DispatchRegion.required_subgroup_size pub required_subgroup_size: Option -field metal2vulkan::bind::DispatchRegion.specialization pub specialization: SpecializationKey -field metal2vulkan::bind::DispatchRegion.stage_flags pub stage_flags: vk::PipelineShaderStageCreateFlags -field metal2vulkan::bind::DrawCommands.amplifications pub amplifications: Vec> -field metal2vulkan::bind::DrawCommands.buffer_offsets pub buffer_offsets: Vec<(u32, u64)> -field metal2vulkan::bind::DrawCommands.descriptor_bytes pub descriptor_bytes: Vec -field metal2vulkan::bind::DrawCommands.descriptor_ranges pub descriptor_ranges: Vec -field metal2vulkan::bind::DrawCommands.discards_command_buffer pub discards_command_buffer: bool -field metal2vulkan::bind::DrawCommands.draw pub draw: vk::DrawCommand -field metal2vulkan::bind::DrawCommands.extents pub extents: Vec -field metal2vulkan::bind::DrawCommands.index_overrun pub index_overrun: Option -field metal2vulkan::bind::DrawCommands.indirect_needs_arguments pub indirect_needs_arguments: bool -field metal2vulkan::bind::DrawCommands.mesh_arguments pub mesh_arguments: Option -field metal2vulkan::bind::DrawCommands.object_fold pub object_fold: Option -field metal2vulkan::bind::DrawCommands.push_constants pub push_constants: Vec -field metal2vulkan::bind::DrawCommands.push_holes pub push_holes: Vec -field metal2vulkan::bind::DrawCommands.root_tables pub root_tables: Vec<(vk::ShaderStageFlags, RootTable)> -field metal2vulkan::bind::DrawCommands.specialization pub specialization: Option -field metal2vulkan::bind::DrawCommands.uses pub uses: Vec -field metal2vulkan::bind::DrawCommands.vertex_strides pub vertex_strides: Vec<(u32, u32)> -field metal2vulkan::bind::FunctionTablesShape.bytes_class pub bytes_class: u8 -field metal2vulkan::bind::FunctionTablesShape.class pub class: u8 -field metal2vulkan::bind::ImageViewDesc.aspect pub aspect: vk::ImageAspectFlags -field metal2vulkan::bind::ImageViewDesc.components pub components: vk::ComponentMapping -field metal2vulkan::bind::ImageViewDesc.format pub format: vk::Format -field metal2vulkan::bind::ImageViewDesc.layout pub layout: vk::ImageLayout -field metal2vulkan::bind::ImageViewDesc.level pub level: Option -field metal2vulkan::bind::ImageViewDesc.shader_swizzle pub shader_swizzle: bool -field metal2vulkan::bind::ImageViewDesc.view_type pub view_type: vk::ImageViewType -field metal2vulkan::bind::ImageblockSize.height pub height: u32 -field metal2vulkan::bind::ImageblockSize.width pub width: u32 field metal2vulkan::bind::IndexBufferRef.length pub length: u64 field metal2vulkan::bind::IndexBufferRef.token pub token: u32 -field metal2vulkan::bind::IndirectRef.offset pub offset: u64 -field metal2vulkan::bind::IndirectRef.token pub token: u32 -field metal2vulkan::bind::MeshArguments.form pub form: MeshArgumentsForm -field metal2vulkan::bind::MeshArguments.push_constants pub push_constants: [u8; 8] -field metal2vulkan::bind::MeshArguments.source pub source: IndirectRef -field metal2vulkan::bind::MeshArguments.source_range pub source_range: BufferRange -field metal2vulkan::bind::MeshGridLimits.axes pub axes: [u32; 3] -field metal2vulkan::bind::MeshGridLimits.total pub total: u32 -field metal2vulkan::bind::ObjectFold.discarded pub discarded: bool -field metal2vulkan::bind::ObjectFold.dispatch pub dispatch: [u32; 3] -field metal2vulkan::bind::ObjectFold.past pub past: bool -field metal2vulkan::bind::ObjectFold.pieces pub pieces: u32 -field metal2vulkan::bind::ObjectFold.record pub record: [u32; 8] -field metal2vulkan::bind::PushConstantWrite.bytes pub bytes: Vec -field metal2vulkan::bind::PushConstantWrite.offset pub offset: u32 -field metal2vulkan::bind::PushConstantWrite.stages pub stages: vk::ShaderStageFlags -field metal2vulkan::bind::PushFieldPlacement.field pub field: PushField -field metal2vulkan::bind::PushFieldPlacement.location pub location: FieldLocation -field metal2vulkan::bind::PushFieldPlacement.size pub size: u32 -field metal2vulkan::bind::PushFieldPlacement.stage pub stage: Stage -field metal2vulkan::bind::PushTemplate.fields pub fields: Vec field metal2vulkan::bind::PvrtcDecode.alpha pub alpha: bool field metal2vulkan::bind::PvrtcDecode.srgb pub srgb: bool field metal2vulkan::bind::PvrtcDecode.two_bits pub two_bits: bool @@ -2088,15 +1841,6 @@ field metal2vulkan::bind::RateMapDescriptor.mutability pub mutability: Mutabilit field metal2vulkan::bind::RateMapDescriptor.screen_size pub screen_size: [u32; 2] field metal2vulkan::bind::RateMapLayerDescriptor.horizontal pub horizontal: Vec field metal2vulkan::bind::RateMapLayerDescriptor.vertical pub vertical: Vec -field metal2vulkan::bind::ResidentRange.guest pub guest: u64 -field metal2vulkan::bind::ResidentRange.host pub host: u64 -field metal2vulkan::bind::ResidentRange.length pub length: u64 -field metal2vulkan::bind::ResourceUse.access pub access: AccessSet -field metal2vulkan::bind::ResourceUse.class pub class: AccessClass -field metal2vulkan::bind::ResourceUse.range pub range: Option -field metal2vulkan::bind::ResourceUse.resource pub resource: UseTarget -field metal2vulkan::bind::ResourceUse.stages pub stages: vk::PipelineStageFlags2 -field metal2vulkan::bind::RootTable.bytes pub bytes: Vec field metal2vulkan::bind::SamplerDescriptor.border_color pub border_color: metal::SamplerBorderColor field metal2vulkan::bind::SamplerDescriptor.compare_function pub compare_function: metal::CompareFunction field metal2vulkan::bind::SamplerDescriptor.lod_average pub lod_average: bool @@ -2112,79 +1856,8 @@ field metal2vulkan::bind::SamplerDescriptor.r_address_mode pub r_address_mode: m field metal2vulkan::bind::SamplerDescriptor.reduction_mode pub reduction_mode: metal::SamplerReductionMode field metal2vulkan::bind::SamplerDescriptor.s_address_mode pub s_address_mode: metal::SamplerAddressMode field metal2vulkan::bind::SamplerDescriptor.t_address_mode pub t_address_mode: metal::SamplerAddressMode -field metal2vulkan::bind::SamplerShape.anisotropic pub anisotropic: bool -field metal2vulkan::bind::SamplerShape.compare pub compare: bool -field metal2vulkan::bind::SamplerShape.cubic pub cubic: bool -field metal2vulkan::bind::SamplerShape.linear pub linear: bool -field metal2vulkan::bind::SamplerShape.mirror_clamp_to_edge pub mirror_clamp_to_edge: bool -field metal2vulkan::bind::SamplerShape.opaque_black_border pub opaque_black_border: bool -field metal2vulkan::bind::SamplerShape.reduction pub reduction: metal::SamplerReductionMode -field metal2vulkan::bind::SamplerShape.valid_lod_clamps pub valid_lod_clamps: bool field metal2vulkan::bind::StageInRegion.origin pub origin: [u32; 3] field metal2vulkan::bind::StageInRegion.size pub size: [u32; 3] -field metal2vulkan::bind::StageShape.buffers pub buffers: BTreeMap -field metal2vulkan::bind::StageShape.samplers pub samplers: BTreeMap -field metal2vulkan::bind::StageShape.textures pub textures: BTreeMap -field metal2vulkan::bind::StageShape.threadgroup_lengths pub threadgroup_lengths: BTreeMap -field metal2vulkan::bind::StageTable.acceleration_structures pub acceleration_structures: BTreeMap -field metal2vulkan::bind::StageTable.buffer_ranges pub buffer_ranges: BufferRanges -field metal2vulkan::bind::StageTable.buffers pub buffers: BTreeMap -field metal2vulkan::bind::StageTable.samplers pub samplers: BTreeMap -field metal2vulkan::bind::StageTable.textures pub textures: BTreeMap -field metal2vulkan::bind::StageTable.threadgroup_lengths pub threadgroup_lengths: BTreeMap -field metal2vulkan::bind::StatusReport.cubic_argument_sampler pub cubic_argument_sampler: bool -field metal2vulkan::bind::StatusReport.mesh_grid_discarded pub mesh_grid_discarded: bool -field metal2vulkan::bind::StatusReport.mesh_grid_past_limits pub mesh_grid_past_limits: bool -field metal2vulkan::bind::StatusReport.resident_miss pub resident_miss: bool -field metal2vulkan::bind::StatusReport.resident_misses pub resident_misses: u32 -field metal2vulkan::bind::TessellationFactorBuffer.instance_stride pub instance_stride: u64 -field metal2vulkan::bind::TessellationFactorBuffer.length pub length: u64 -field metal2vulkan::bind::TessellationFactorBuffer.offset pub offset: u64 -field metal2vulkan::bind::TessellationFactors.buffer pub buffer: Option -field metal2vulkan::bind::TessellationFactors.scale pub scale: f32 -field metal2vulkan::bind::TextureFacts.address_modes pub address_modes: metal::sampler::AddressModeMap -field metal2vulkan::bind::TextureFacts.array_length pub array_length: u32 -field metal2vulkan::bind::TextureFacts.mipmap_level_count pub mipmap_level_count: u32 -field metal2vulkan::bind::TextureFacts.parent_base_size pub parent_base_size: [u32; 3] -field metal2vulkan::bind::TextureFacts.parent_relative_level pub parent_relative_level: u32 -field metal2vulkan::bind::TextureFacts.pixel_format pub pixel_format: metal::PixelFormat -field metal2vulkan::bind::TextureFacts.sample_count pub sample_count: u32 -field metal2vulkan::bind::TextureFacts.sparse pub sparse: bool -field metal2vulkan::bind::TextureFacts.swizzle pub swizzle: metal::TextureSwizzleChannels -field metal2vulkan::bind::TextureFacts.texel_rows pub texel_rows: Option -field metal2vulkan::bind::TextureFacts.texture_type pub texture_type: metal::TextureType -field metal2vulkan::bind::TextureFacts.usage pub usage: metal::TextureUsage -field metal2vulkan::bind::TextureFacts.ycbcr_in_place pub ycbcr_in_place: Option -field metal2vulkan::bind::TileThreadgroupArgument.length pub length: u32 -field metal2vulkan::bind::TileThreadgroupArgument.offset pub offset: u32 -field metal2vulkan::bind::TileThreadgroupMemory.arguments pub arguments: BTreeMap -field metal2vulkan::bind::TileThreadgroupMemory.length pub length: u32 -field metal2vulkan::bind::UsedResource.class pub class: ResourceClass -field metal2vulkan::bind::UsedResource.device_address pub device_address: Option -field metal2vulkan::bind::UsedResource.gpu_address pub gpu_address: Option -field metal2vulkan::bind::UsedResource.length pub length: u64 -field metal2vulkan::bind::UsedResource.resource_id pub resource_id: Option -field metal2vulkan::bind::UsedResource.stages pub stages: metal::RenderStages -field metal2vulkan::bind::UsedResource.token pub token: u32 -field metal2vulkan::bind::UsedResource.usage pub usage: metal::ResourceUsage -field metal2vulkan::bind::UsedShape.class pub class: UsedClass -field metal2vulkan::bind::UsedShape.stages pub stages: metal::RenderStages -field metal2vulkan::bind::UsedShape.usage pub usage: metal::ResourceUsage -field metal2vulkan::bind::VertexAmplification.count pub count: u32 -field metal2vulkan::bind::VertexAmplification.one_at_a_time pub one_at_a_time: bool -field metal2vulkan::bind::VertexAmplification.view_mappings pub view_mappings: Vec -field metal2vulkan::bind::VertexBufferBind.binding pub binding: u32 -field metal2vulkan::bind::VertexBufferBind.buffer_index pub buffer_index: u32 -field metal2vulkan::bind::VertexBufferBind.per_bind_stride pub per_bind_stride: bool -field metal2vulkan::bind::ViewMapping.render_target_array_index_offset pub render_target_array_index_offset: u32 -field metal2vulkan::bind::ViewMapping.viewport_array_index_offset pub viewport_array_index_offset: u32 -field metal2vulkan::bind::ViewSetup.base_layer pub base_layer: u32 -field metal2vulkan::bind::ViewSetup.view_mask pub view_mask: u32 -field metal2vulkan::bind::YCbCrCodes.bits pub bits: u32 -field metal2vulkan::bind::YCbCrCodes.bytes pub bytes: u32 -field metal2vulkan::bind::YCbCrCodes.output pub output: YCbCrOutput -field metal2vulkan::bind::YCbCrCodes.packed pub packed: bool -field metal2vulkan::bind::YCbCrCodes.subsampling pub subsampling: ChromaSubsampling field metal2vulkan::bind::indirect_commands::Bindings.pipeline pub pipeline: Option field metal2vulkan::bind::indirect_commands::BufferBinding.address pub address: u64 field metal2vulkan::bind::indirect_commands::BufferBinding.attribute_stride pub attribute_stride: Option @@ -2242,10 +1915,7 @@ field metal2vulkan::cache::VariantKey.srgb_textures pub srgb_textures: BTreeSet< field metal2vulkan::cache::VariantKey.storage_images pub storage_images: BTreeMap field metal2vulkan::cache::VariantKey.swizzled_storage pub swizzled_storage: BTreeSet field metal2vulkan::cache::VariantKey.texel_buffer_parts pub texel_buffer_parts: BTreeMap -field metal2vulkan::cache::VariantKey.texel_rows pub texel_rows: BTreeSet field metal2vulkan::cache::VariantKey.unit_axes pub unit_axes: u8 -field metal2vulkan::cache::VariantKey.ycbcr_in_place pub ycbcr_in_place: BTreeSet -field metal2vulkan::cache::VariantKey.ycbcr_planes_sampled pub ycbcr_planes_sampled: BTreeMap field metal2vulkan::cache::VariantKey.zeroed_colors pub zeroed_colors: BTreeMap field metal2vulkan::device::AllocationLimits.max_buffer_size pub max_buffer_size: u64 field metal2vulkan::device::AllocationLimits.max_memory_allocation_size pub max_memory_allocation_size: u64 @@ -2761,7 +2431,6 @@ field metal2vulkan::pipeline::LoweringInputs.stage_input pub stage_input: Option field metal2vulkan::pipeline::LoweringInputs.storage_images pub storage_images: BTreeMap field metal2vulkan::pipeline::LoweringInputs.swizzled_storage pub swizzled_storage: BTreeSet field metal2vulkan::pipeline::LoweringInputs.texel_buffer_parts pub texel_buffer_parts: BTreeMap -field metal2vulkan::pipeline::LoweringInputs.texel_rows pub texel_rows: BTreeSet field metal2vulkan::pipeline::LoweringInputs.texture_write_rounding pub texture_write_rounding: metal::TextureWriteRoundingMode field metal2vulkan::pipeline::LoweringInputs.threadgroup_size_matches_tile_size pub threadgroup_size_matches_tile_size: bool field metal2vulkan::pipeline::LoweringInputs.tile_attachments pub tile_attachments: Option> @@ -2771,8 +2440,6 @@ field metal2vulkan::pipeline::LoweringInputs.unit_axes pub unit_axes: u8 field metal2vulkan::pipeline::LoweringInputs.vertex_fetch pub vertex_fetch: Option field metal2vulkan::pipeline::LoweringInputs.viewport_index_varying pub viewport_index_varying: bool field metal2vulkan::pipeline::LoweringInputs.word_colors pub word_colors: BTreeMap -field metal2vulkan::pipeline::LoweringInputs.ycbcr_in_place pub ycbcr_in_place: BTreeSet -field metal2vulkan::pipeline::LoweringInputs.ycbcr_planes_sampled pub ycbcr_planes_sampled: BTreeMap field metal2vulkan::pipeline::LoweringInputs.zeroed_colors pub zeroed_colors: BTreeMap field metal2vulkan::pipeline::MeshPipelineDescriptor.alpha_to_coverage pub alpha_to_coverage: bool field metal2vulkan::pipeline::MeshPipelineDescriptor.alpha_to_one pub alpha_to_one: bool @@ -3099,13 +2766,8 @@ fn metal2vulkan-runtime::serve_stage pub fn serve_stage(instance: &Instance, mut fn metal2vulkan::ash_interop::sampler_create_info pub fn sampler_create_info<'a>(desc: &vk::SamplerDesc, reduction: &'a mut ash::vk::SamplerReductionModeCreateInfo<'static>, border: &'a mut ash::vk::SamplerBorderColorComponentMappingCreateInfoEXT<'static>) -> ash::vk::SamplerCreateInfo<'a> fn metal2vulkan::bind::alpha_test_code pub fn alpha_test_code(reference: f32) -> u32 fn metal2vulkan::bind::clamped_depth pub const fn clamped_depth(bits: u32) -> u32 -fn metal2vulkan::bind::fold_object_grid pub fn fold_object_grid(groups: [u32; 3], threads: [u32; 3], task: MeshGridLimits, direct: bool) -> Option -fn metal2vulkan::bind::handle_entry pub fn handle_entry(id: u64, element: u32, flags: u32) -> [u8; HANDLE_ENTRY_BYTES as usize] fn metal2vulkan::bind::indirect_commands::records_address pub const fn records_address(id: u64) -> u64 fn metal2vulkan::bind::indirect_commands::written_flag_offset pub const fn written_flag_offset(capacity: u32, index: u32) -> u64 -fn metal2vulkan::bind::metal_object_grid pub fn metal_object_grid(groups: [u32; 3], threads: [u32; 3], direct: bool) -> Option<([u32; 3], [u32; 3])> -fn metal2vulkan::bind::part_texels pub fn part_texels(limits: &Limits) -> u64 -fn metal2vulkan::bind::sampler_desc pub fn sampler_desc(device: &crate::device::Device, desc: &crate::bind::state::SamplerDescriptor, use_: SamplerUse, opaque_black: OpaqueBlackBorder, image_format: Option) -> Result fn metal2vulkan::device::vk_stage pub fn vk_stage(stage: Stage) -> vk::ShaderStage fn metal2vulkan::metal::format::alpha_in_red pub fn alpha_in_red(pf: PixelFormat, profile: &DeviceProfile) -> bool fn metal2vulkan::metal::format::alpha_in_red_format pub fn alpha_in_red_format(pf: PixelFormat) -> Option @@ -6463,10 +6125,6 @@ method metal2vulkan::CancelToken::new pub fn new() -> CancelToken method metal2vulkan::bind::ArgumentBufferLayout::from_descriptors pub fn from_descriptors(descriptors: &[ArgumentDescriptor]) -> Result method metal2vulkan::bind::ArgumentBufferLayout::id_span pub fn id_span(&self) -> u32 method metal2vulkan::bind::ArgumentDescriptor::new pub fn new(data_type: DataType, index: u32) -> ArgumentDescriptor -method metal2vulkan::bind::ArgumentSampler::new pub fn new(desc: SamplerDescriptor, resource_id: u64) -> ArgumentSampler -method metal2vulkan::bind::ArgumentSamplersShape::entries pub fn entries(&self) -> u64 -method metal2vulkan::bind::ArgumentSamplersShape::least_count pub fn least_count(&self) -> u64 -method metal2vulkan::bind::ArgumentSamplersShape::of pub fn of(samplers: &[ArgumentSampler]) -> ArgumentSamplersShape method metal2vulkan::bind::AstcDecode::block_extent pub fn block_extent(self) -> [u32; 2] method metal2vulkan::bind::AstcDecode::decode pub fn decode(self, texels: AstcTexels, blocks: &[u8], size: [u32; 3]) -> Vec method metal2vulkan::bind::AstcDecode::decode_into pub fn decode_into(self, texels: AstcTexels, blocks: &[u8], [width, height, depth]: [u32; 3], out: &mut [u8]) @@ -6474,20 +6132,6 @@ method metal2vulkan::bind::AstcDecode::form pub fn form(self, texels: AstcTexels method metal2vulkan::bind::AstcDecode::metal_value pub fn metal_value(self, c: [u16; 4]) -> [f32; 4] method metal2vulkan::bind::AstcDecode::of pub fn of(pf: PixelFormat) -> Option method metal2vulkan::bind::AstcDecode::texel_bytes pub fn texel_bytes(self, texels: AstcTexels) -> u32 -method metal2vulkan::bind::BindState::shape pub fn shape(&self) -> BindShape -method metal2vulkan::bind::BindingPlan::content_digest pub fn content_digest(&self) -> Result -method metal2vulkan::bind::BindingPlan::dispatch_variant pub fn dispatch_variant(&self, dispatch: &Dispatch) -> Result -method metal2vulkan::bind::BindingPlan::instantiate_dispatch pub fn instantiate_dispatch(&self, state: &BindState, dispatch: &Dispatch) -> Result -method metal2vulkan::bind::BindingPlan::instantiate_dispatch_into pub fn instantiate_dispatch_into(&self, state: &BindState, dispatch: &Dispatch, commands: &mut DispatchCommands) -> Result<(), BindError> -method metal2vulkan::bind::BindingPlan::instantiate_draw pub fn instantiate_draw(&self, state: &BindState, draw: &DrawCall) -> Result -method metal2vulkan::bind::BindingPlan::instantiate_draw_into pub fn instantiate_draw_into(&self, state: &BindState, draw: &DrawCall, commands: &mut DrawCommands) -> Result<(), BindError> -method metal2vulkan::bind::BindingPlan::specialized_value pub fn specialized_value(&self, key: SpecKey) -> Option -method metal2vulkan::bind::BoundBuffer::shape pub fn shape(&self, ranges: BufferRanges) -> BufferShape -method metal2vulkan::bind::BoundSampler::new pub fn new(desc: SamplerDescriptor) -> BoundSampler -method metal2vulkan::bind::BoundSampler::shape pub fn shape(&self) -> BoundSamplerShape -method metal2vulkan::bind::BoundTexture::shape pub fn shape(&self) -> TextureShape -method metal2vulkan::bind::BufferRanges::length_class pub fn length_class(&self, length: u64) -> u8 -method metal2vulkan::bind::BufferRanges::of pub fn of(limits: &Limits) -> BufferRanges method metal2vulkan::bind::Dispatch::threads_per_group pub fn threads_per_group(&self) -> [u32; 3] method metal2vulkan::bind::EtcDecode::block_bytes pub fn block_bytes(self) -> u32 method metal2vulkan::bind::EtcDecode::block_values pub fn block_values(self, block: &[u8]) -> [[i32; 2]; 16] @@ -6497,19 +6141,7 @@ method metal2vulkan::bind::EtcDecode::eleven_bit pub fn eleven_bit(self) -> bool method metal2vulkan::bind::EtcDecode::metal_value pub fn metal_value(self, c: i32) -> f32 method metal2vulkan::bind::EtcDecode::of pub fn of(pf: PixelFormat) -> Option method metal2vulkan::bind::EtcDecode::texel_bytes pub fn texel_bytes(self, texels: EtcTexels) -> u32 -method metal2vulkan::bind::ExecutionStatus::decode pub fn decode(bytes: &[u8; ExecutionStatus::BYTES]) -> StatusReport -method metal2vulkan::bind::ExecutionStatus::initial pub const fn initial() -> [u8; ExecutionStatus::BYTES] -method metal2vulkan::bind::FunctionTableSnapshot::of pub fn of(sizes: impl IntoIterator) -> Option -method metal2vulkan::bind::FunctionTableSnapshot::offsets pub fn offsets(&self) -> &[u32] -method metal2vulkan::bind::FunctionTablesShape::entries pub fn entries(&self) -> u64 -method metal2vulkan::bind::FunctionTablesShape::least_count pub fn least_count(&self) -> u64 -method metal2vulkan::bind::FunctionTablesShape::may_pass pub fn may_pass(&self, max_storage_buffer_range: u32) -> bool -method metal2vulkan::bind::FunctionTablesShape::of pub fn of(tables: &[ArgumentFunctionTable]) -> FunctionTablesShape -method metal2vulkan::bind::ImageblockSize::new pub fn new(width: u32, height: u32) -> ImageblockSize -method metal2vulkan::bind::IndexBufferRef::fetch_end pub fn fetch_end(&self, index_offset: u64) -> u64 method metal2vulkan::bind::IndexBufferRef::new pub fn new(token: u32, length: u64) -> IndexBufferRef -method metal2vulkan::bind::NeutralResource::for_image pub fn for_image(class: &ImageHandleClass) -> Option -method metal2vulkan::bind::NeutralResource::format pub fn format(&self) -> Option method metal2vulkan::bind::PvrtcDecode::metal_value pub fn metal_value(self, ch: usize, c: u8) -> f32 method metal2vulkan::bind::PvrtcDecode::of pub fn of(pf: PixelFormat) -> Option method metal2vulkan::bind::RasterizationRateMap::is_identity pub fn is_identity(&self) -> bool @@ -6525,24 +6157,6 @@ method metal2vulkan::bind::RateMapLayerDescriptor::new pub fn new(horizontal: Ve method metal2vulkan::bind::SamplerDescriptor::new pub fn new() -> SamplerDescriptor method metal2vulkan::bind::SamplerDescriptor::shape pub fn shape(&self) -> SamplerShape method metal2vulkan::bind::StageInRegion::new pub fn new(origin: [u32; 3], size: [u32; 3]) -> StageInRegion -method metal2vulkan::bind::StageTable::shape pub fn shape(&self) -> StageShape -method metal2vulkan::bind::StatusBits::contains pub const fn contains(self, other: StatusBits) -> bool -method metal2vulkan::bind::StatusWord::byte_offset pub const fn byte_offset(self) -> u32 -method metal2vulkan::bind::StatusWord::index pub const fn index(self) -> u32 -method metal2vulkan::bind::TessellationFactorBuffer::new pub fn new(length: u64, offset: u64, instance_stride: u64) -> TessellationFactorBuffer -method metal2vulkan::bind::TessellationFactors::new pub fn new(buffer: Option, scale: f32) -> TessellationFactors -method metal2vulkan::bind::TexelRows::words pub fn words(&self) -> [u32; Self::WORDS] -method metal2vulkan::bind::TextureFacts::new pub fn new(texture_type: metal::TextureType, pixel_format: metal::PixelFormat) -> Self -method metal2vulkan::bind::TextureFacts::offset_base_axes pub fn offset_base_axes(&self) -> u8 -method metal2vulkan::bind::TextureFacts::shape pub fn shape(&self) -> TextureShape -method metal2vulkan::bind::UsedResource::new pub fn new(class: ResourceClass, token: u32) -> UsedResource -method metal2vulkan::bind::VertexAmplification::layer pub fn layer(&self, a: u32, length: u32, max: u32) -> u32 -method metal2vulkan::bind::VertexAmplification::mapping pub fn mapping(&self, a: u32, max: u32) -> ViewMapping -method metal2vulkan::bind::VertexAmplification::new pub fn new(count: u32, view_mappings: Vec) -> VertexAmplification -method metal2vulkan::bind::YCbCrCodes::of pub fn of(format: crate::metal::format::YCbCrFormat) -> Option -method metal2vulkan::bind::YCbCrInPlace::planes_sampler pub fn planes_sampler(&self) -> Option -method metal2vulkan::bind::YCbCrInPlace::sampler pub fn sampler(&self) -> YCbCrPlanesSampler -method metal2vulkan::bind::YCbCrInPlace::words pub fn words(&self) -> [u32; Self::WORDS] method metal2vulkan::bind::indirect_commands::Action::writes pub fn writes(&self) -> crate::pipeline::CommandWrites method metal2vulkan::bind::indirect_commands::Bindings::buffers pub fn buffers(&self, stage: BufferStage) -> &[Option; BINDING_COUNT] method metal2vulkan::bind::indirect_commands::Bindings::buffers_mut pub fn buffers_mut(&mut self, stage: BufferStage) -> &mut [Option; BINDING_COUNT] @@ -6584,9 +6198,7 @@ method metal2vulkan::bind::indirect_commands::ResolvedBindings::buffers pub fn b method metal2vulkan::cache::PipelineKey::digest pub const fn digest(&self) -> &Hash256 method metal2vulkan::cache::PipelineKey::new pub const fn new(hash: Hash256) -> PipelineKey method metal2vulkan::cache::SpecializationKey::new pub fn new() -> SpecializationKey -method metal2vulkan::cache::VariantKey::covers pub fn covers(&self, settled: &VariantKey) -> bool method metal2vulkan::cache::VariantKey::is_empty pub fn is_empty(&self) -> bool -method metal2vulkan::cache::VariantKey::large_buffer_form pub fn large_buffer_form(&self, dependencies: &[crate::pipeline::RuntimeDependency], shape: &crate::bind::BindShape) -> VariantKey method metal2vulkan::cache::VariantKey::lowering_inputs pub fn lowering_inputs(&self, stage: crate::pipeline::sym::Stage) -> crate::pipeline::LoweringInputs method metal2vulkan::cache::VariantKey::new pub fn new() -> VariantKey method metal2vulkan::device::AllocationLimits::new pub fn new(max_memory_allocation_size: u64, max_buffer_size: u64) -> AllocationLimits @@ -6811,7 +6423,6 @@ method metal2vulkan::pipeline::CommandWrites::union pub const fn union(self, oth method metal2vulkan::pipeline::CommandWrites::writes_kinds pub const fn writes_kinds(self, kinds: u8) -> bool method metal2vulkan::pipeline::ComputePipeline::content_digest pub fn content_digest(&self) -> Hash256 method metal2vulkan::pipeline::ComputePipeline::footprint pub fn footprint(&self) -> u64 -method metal2vulkan::pipeline::ComputePipeline::plan pub fn plan(&self, device: &Device, shape: &BindShape) -> Result method metal2vulkan::pipeline::ComputePipelineDescriptor::lowering_inputs pub fn lowering_inputs(&self) -> LoweringInputs method metal2vulkan::pipeline::ComputePipelineDescriptor::new pub fn new(kernel: StageSource) -> ComputePipelineDescriptor method metal2vulkan::pipeline::ComputePipelineDescriptor::reflection pub fn reflection(&self, budget: &crate::Budget) -> Result @@ -6875,7 +6486,6 @@ method metal2vulkan::pipeline::PrecisionNote::of_math_call pub fn of_math_call(c method metal2vulkan::pipeline::PrivateRenderState::new pub const fn new() -> PrivateRenderState method metal2vulkan::pipeline::RenderPipeline::content_digest pub fn content_digest(&self) -> Hash256 method metal2vulkan::pipeline::RenderPipeline::footprint pub fn footprint(&self) -> u64 -method metal2vulkan::pipeline::RenderPipeline::plan pub fn plan(&self, device: &Device, shape: &BindShape) -> Result method metal2vulkan::pipeline::RenderPipelineDescriptor::fragment_writes_depth_unattached pub fn fragment_writes_depth_unattached(&self, budget: &crate::Budget, entries: &StageEntries) -> Result method metal2vulkan::pipeline::RenderPipelineDescriptor::new pub fn new(vertex: StageSource) -> RenderPipelineDescriptor method metal2vulkan::pipeline::RenderPipelineDescriptor::reflection pub fn reflection(&self, budget: &crate::Budget) -> Result @@ -7242,70 +6852,15 @@ struct metal2vulkan::Budget #[derive(Clone, Debug, Default)] #[non_exhaustive] p struct metal2vulkan::CancelToken #[derive(Clone, Debug, Default)] pub struct CancelToken(Arc) struct metal2vulkan::bind::ArgumentBufferLayout #[derive(Clone, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct ArgumentBufferLayout struct metal2vulkan::bind::ArgumentDescriptor #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct ArgumentDescriptor -struct metal2vulkan::bind::ArgumentFunctionTable #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct ArgumentFunctionTable struct metal2vulkan::bind::ArgumentMember #[derive(Clone, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct ArgumentMember -struct metal2vulkan::bind::ArgumentSampler #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] pub struct ArgumentSampler -struct metal2vulkan::bind::ArgumentSamplersShape #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub struct ArgumentSamplersShape struct metal2vulkan::bind::AstcDecode #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct AstcDecode -struct metal2vulkan::bind::BindShape #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub struct BindShape -struct metal2vulkan::bind::BindState #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, Default, PartialEq)] #[non_exhaustive] pub struct BindState -struct metal2vulkan::bind::BindingPlan #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct BindingPlan -struct metal2vulkan::bind::BoundAccelerationStructure #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct BoundAccelerationStructure -struct metal2vulkan::bind::BoundSampler #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] pub struct BoundSampler -struct metal2vulkan::bind::BoundSamplerShape #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub struct BoundSamplerShape -struct metal2vulkan::bind::BufferExtent #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct BufferExtent -struct metal2vulkan::bind::BufferRange #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct BufferRange -struct metal2vulkan::bind::BufferRanges #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct BufferRanges -struct metal2vulkan::bind::ByteRange #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct ByteRange -struct metal2vulkan::bind::ComputeTemplate #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct ComputeTemplate -struct metal2vulkan::bind::DescriptorBytes #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct DescriptorBytes -struct metal2vulkan::bind::DescriptorRange #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct DescriptorRange -struct metal2vulkan::bind::DescriptorWrite #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct DescriptorWrite -struct metal2vulkan::bind::DispatchCommands #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct DispatchCommands -struct metal2vulkan::bind::DispatchRegion #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct DispatchRegion -struct metal2vulkan::bind::DrawCommands #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct DrawCommands -struct metal2vulkan::bind::ExecutionStatus #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct ExecutionStatus -struct metal2vulkan::bind::FunctionTableSnapshot #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct FunctionTableSnapshot -struct metal2vulkan::bind::FunctionTablesShape #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub struct FunctionTablesShape -struct metal2vulkan::bind::GraphicsTemplate #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct GraphicsTemplate -struct metal2vulkan::bind::ImageViewDesc #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct ImageViewDesc -struct metal2vulkan::bind::ImageblockSize #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub struct ImageblockSize struct metal2vulkan::bind::IndexBufferRef #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct IndexBufferRef -struct metal2vulkan::bind::IndirectRef #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct IndirectRef -struct metal2vulkan::bind::MeshArguments #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct MeshArguments -struct metal2vulkan::bind::MeshGridLimits #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct MeshGridLimits -struct metal2vulkan::bind::ObjectFold #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct ObjectFold -struct metal2vulkan::bind::PushConstantWrite #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct PushConstantWrite -struct metal2vulkan::bind::PushFieldPlacement #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct PushFieldPlacement -struct metal2vulkan::bind::PushTemplate #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct PushTemplate struct metal2vulkan::bind::PvrtcDecode #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct PvrtcDecode struct metal2vulkan::bind::RasterizationRateMap #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct RasterizationRateMap struct metal2vulkan::bind::RateMapDescriptor #[derive(Clone, Debug, PartialEq)] #[non_exhaustive] pub struct RateMapDescriptor struct metal2vulkan::bind::RateMapLayerDescriptor #[derive(Clone, Debug, Default, PartialEq)] #[non_exhaustive] pub struct RateMapLayerDescriptor -struct metal2vulkan::bind::ResidentRange #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct ResidentRange -struct metal2vulkan::bind::ResourceUse #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct ResourceUse -struct metal2vulkan::bind::RootTable #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct RootTable struct metal2vulkan::bind::SamplerDescriptor #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] pub struct SamplerDescriptor -struct metal2vulkan::bind::SamplerShape #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub struct SamplerShape struct metal2vulkan::bind::StageInRegion #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub struct StageInRegion -struct metal2vulkan::bind::StageShape #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub struct StageShape -struct metal2vulkan::bind::StageTable #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, Default, PartialEq)] #[non_exhaustive] pub struct StageTable -struct metal2vulkan::bind::StatusBits #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub struct StatusBits(pub u32) -struct metal2vulkan::bind::StatusReport #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct StatusReport -struct metal2vulkan::bind::TessellationFactorBuffer #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct TessellationFactorBuffer -struct metal2vulkan::bind::TessellationFactors #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] pub struct TessellationFactors -struct metal2vulkan::bind::TexelRows #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] #[non_exhaustive] pub struct TexelRows -struct metal2vulkan::bind::TextureFacts #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct TextureFacts -struct metal2vulkan::bind::TileThreadgroupArgument #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub struct TileThreadgroupArgument -struct metal2vulkan::bind::TileThreadgroupMemory #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub struct TileThreadgroupMemory -struct metal2vulkan::bind::UsedResource #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct UsedResource -struct metal2vulkan::bind::UsedShape #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub struct UsedShape -struct metal2vulkan::bind::VertexAmplification #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub struct VertexAmplification -struct metal2vulkan::bind::VertexBufferBind #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct VertexBufferBind -struct metal2vulkan::bind::ViewMapping #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub struct ViewMapping -struct metal2vulkan::bind::ViewSetup #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct ViewSetup -struct metal2vulkan::bind::YCbCrCodes #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct YCbCrCodes -struct metal2vulkan::bind::YCbCrInPlace #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] #[non_exhaustive] pub struct YCbCrInPlace struct metal2vulkan::bind::YCbCrPlanesSampler #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] #[non_exhaustive] pub struct YCbCrPlanesSampler struct metal2vulkan::bind::indirect_commands::Bindings #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct Bindings struct metal2vulkan::bind::indirect_commands::BufferBinding #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct BufferBinding @@ -7564,14 +7119,11 @@ trait-impl metal2vulkan-runtime::floor::Maintenance8Features impl fe impl vk::Ex trait-impl metal2vulkan-runtime::floor::Maintenance8Features impl fe impl vk::ExtendsPhysicalDeviceFeatures2 unsafe impl vk::ExtendsPhysicalDeviceFeatures2 for Maintenance8Features trait-impl metal2vulkan-runtime::floor::Missing impl fmt::Display impl fmt::Display for Missing trait-impl metal2vulkan::bind::ArgumentLayoutError impl From impl From for ArgumentLayoutError -trait-impl metal2vulkan::bind::DrawCommands impl Default impl Default for DrawCommands trait-impl metal2vulkan::bind::RateMapDescriptor impl Default impl Default for RateMapDescriptor trait-impl metal2vulkan::bind::RateMapError impl fmt::Display impl fmt::Display for RateMapError trait-impl metal2vulkan::bind::RateMapError impl std::error::Error impl std::error::Error for RateMapError trait-impl metal2vulkan::bind::SamplerDescriptor impl Default impl Default for SamplerDescriptor -trait-impl metal2vulkan::bind::TessellationFactors impl Default impl Default for TessellationFactors trait-impl metal2vulkan::bind::UnpinnedCompile impl fmt::Display impl fmt::Display for UnpinnedCompile -trait-impl metal2vulkan::bind::VertexAmplification impl Default impl Default for VertexAmplification trait-impl metal2vulkan::bind::indirect_commands::AddressError impl fmt::Display impl fmt::Display for AddressError trait-impl metal2vulkan::bind::indirect_commands::AddressError impl std::error::Error impl std::error::Error for AddressError trait-impl metal2vulkan::bind::indirect_commands::BindingError impl fmt::Display impl fmt::Display for BindingError @@ -7588,8 +7140,6 @@ trait-impl metal2vulkan::device::DevicePolicy impl Default impl Default for Devi trait-impl metal2vulkan::device::SpirvCapability impl Codec impl Codec for SpirvCapability trait-impl metal2vulkan::device::SpirvCapability impl fmt::Debug impl fmt::Debug for SpirvCapability trait-impl metal2vulkan::error::Attachment impl fmt::Display impl fmt::Display for Attachment -trait-impl metal2vulkan::error::BindError impl fmt::Display impl fmt::Display for BindError -trait-impl metal2vulkan::error::BindError impl std::error::Error impl std::error::Error for BindError trait-impl metal2vulkan::error::DescriptorError impl From impl From for DescriptorError trait-impl metal2vulkan::error::DiagName impl fmt::Debug impl fmt::Debug for DiagName trait-impl metal2vulkan::error::DiagName impl fmt::Display impl fmt::Display for DiagName @@ -8905,14 +8455,12 @@ variant metal2vulkan-runtime::PrecisionNote::ExtrapolatedInterpolation Extrapola variant metal2vulkan-runtime::PrecisionNote::F16FmaDoubleRounding F16FmaDoubleRounding variant metal2vulkan-runtime::PrecisionNote::F16IntConvDoubleRounding F16IntConvDoubleRounding variant metal2vulkan-runtime::PrecisionNote::FastMathRewrites FastMathRewrites -variant metal2vulkan-runtime::PrecisionNote::FloatSampleFilter FloatSampleFilter variant metal2vulkan-runtime::PrecisionNote::Fp8Value Fp8Value variant metal2vulkan-runtime::PrecisionNote::FragmentSimdgroupGrouping FragmentSimdgroupGrouping variant metal2vulkan-runtime::PrecisionNote::FunctionStorageAssumed FunctionStorageAssumed variant metal2vulkan-runtime::PrecisionNote::GradFromBias GradFromBias variant metal2vulkan-runtime::PrecisionNote::HalfOutputFastMathBlend HalfOutputFastMathBlend variant metal2vulkan-runtime::PrecisionNote::HalfOutputPrecision HalfOutputPrecision -variant metal2vulkan-runtime::PrecisionNote::HalfSampleFilter HalfSampleFilter variant metal2vulkan-runtime::PrecisionNote::HalfTexelConversion HalfTexelConversion variant metal2vulkan-runtime::PrecisionNote::LinkedSamplerNumbering LinkedSamplerNumbering variant metal2vulkan-runtime::PrecisionNote::LoopedSampleOutputs LoopedSampleOutputs @@ -9130,15 +8678,6 @@ variant metal2vulkan-runtime::floor::Missing::QueueFamily QueueFamily variant metal2vulkan-runtime::floor::Missing::SetLayout SetLayout { set: u32 } variant metal2vulkan-runtime::floor::Missing::TimeDomain TimeDomain(&'static str) variant metal2vulkan-runtime::floor::Missing::Version Version(u32) -variant metal2vulkan::bind::AccessClass::Attachment Attachment -variant metal2vulkan::bind::AccessClass::Index Index -variant metal2vulkan::bind::AccessClass::Indirect Indirect -variant metal2vulkan::bind::AccessClass::Sampled Sampled -variant metal2vulkan::bind::AccessClass::Storage Storage -variant metal2vulkan::bind::AccessClass::StorageImage StorageImage -variant metal2vulkan::bind::AccessClass::TexelRows TexelRows -variant metal2vulkan::bind::AccessClass::VertexInput VertexInput -variant metal2vulkan::bind::AccessClass::YCbCrPlanes YCbCrPlanes variant metal2vulkan::bind::ArgumentLayoutError::ArrayOfArrays ArrayOfArrays { id: u32 } variant metal2vulkan::bind::ArgumentLayoutError::Compile Compile(Error) variant metal2vulkan::bind::ArgumentLayoutError::ConstantBlockAlignment ConstantBlockAlignment { position: usize } @@ -9161,23 +8700,13 @@ variant metal2vulkan::bind::ArgumentType::VisibleFunctionTable VisibleFunctionTa variant metal2vulkan::bind::AstcTexels::Float Float variant metal2vulkan::bind::AstcTexels::Half Half variant metal2vulkan::bind::AstcTexels::Unorm8 Unorm8 -variant metal2vulkan::bind::BoundBuffer::Buffer Buffer { length: u64, offset: u64, gpu_address: u64, device_address: Option, attribute_stride: Option } -variant metal2vulkan::bind::BoundBuffer::Bytes Bytes { len: u32, attribute_stride: Option } -variant metal2vulkan::bind::BoundTexture::Buffer Buffer { pixel_format: metal::PixelFormat, offset: u64, length: u64, bytes_per_row: u64, resource_id: Option, swizzle: metal::TextureSwizzleChannels, parts: u32 } -variant metal2vulkan::bind::BoundTexture::Texture Texture { facts: TextureFacts, resource_id: Option } -variant metal2vulkan::bind::BufferShape::Buffer Buffer { attribute_stride: Option, device_address: bool, length_class: u8, offset_alignment: u32 } -variant metal2vulkan::bind::BufferShape::Bytes Bytes { attribute_stride: Option } variant metal2vulkan::bind::Dispatch::ThreadgroupRange ThreadgroupRange { groups: [u32; 3], first: [u32; 3], count: [u32; 3], threads_per_group: [u32; 3] } variant metal2vulkan::bind::Dispatch::Threadgroups Threadgroups { groups: [u32; 3], threads_per_group: [u32; 3] } -variant metal2vulkan::bind::Dispatch::ThreadgroupsIndirect ThreadgroupsIndirect { indirect: IndirectRef, threads_per_group: [u32; 3] } variant metal2vulkan::bind::Dispatch::Threads Threads { threads: [u32; 3], threads_per_group: [u32; 3] } variant metal2vulkan::bind::DrawCall::Indexed Indexed { index_type: vk::IndexType, index_buffer: IndexBufferRef, index_count: u32, index_offset: u64, instance_count: u32, base_vertex: i32, base_instance: u32 } -variant metal2vulkan::bind::DrawCall::Indirect Indirect { indirect: IndirectRef, indexed: Option<(vk::IndexType, IndexBufferRef, u64)> } variant metal2vulkan::bind::DrawCall::MeshThreadgroups MeshThreadgroups { groups: [u32; 3], threads_per_object_group: [u32; 3], threads_per_mesh_group: [u32; 3] } -variant metal2vulkan::bind::DrawCall::MeshThreadgroupsIndirect MeshThreadgroupsIndirect { indirect: IndirectRef, threads_per_object_group: [u32; 3], threads_per_mesh_group: [u32; 3] } variant metal2vulkan::bind::DrawCall::MeshThreads MeshThreads { threads: [u32; 3], threads_per_object_group: [u32; 3], threads_per_mesh_group: [u32; 3] } variant metal2vulkan::bind::DrawCall::Patches Patches { control_points: u32, patch_start: u32, patch_count: u32, patch_index: Option<(IndexBufferRef, u64)>, instance_count: u32, base_instance: u32, control_point_index: Option<(IndexBufferRef, u64)> } -variant metal2vulkan::bind::DrawCall::PatchesIndirect PatchesIndirect { control_points: u32, patch_index: Option<(IndexBufferRef, u64)>, indirect: IndirectRef, control_point_index: Option<(IndexBufferRef, u64)> } variant metal2vulkan::bind::DrawCall::Primitives Primitives { vertex_start: u32, vertex_count: u32, instance_count: u32, base_instance: u32 } variant metal2vulkan::bind::EtcDecode::R11Snorm R11Snorm variant metal2vulkan::bind::EtcDecode::R11Unorm R11Unorm @@ -9188,36 +8717,6 @@ variant metal2vulkan::bind::EtcDecode::Rgb8A1 Rgb8A1 variant metal2vulkan::bind::EtcDecode::Rgba8 Rgba8 variant metal2vulkan::bind::EtcTexels::Compact Compact variant metal2vulkan::bind::EtcTexels::Float Float -variant metal2vulkan::bind::FieldLocation::ArgumentTable ArgumentTable { offset: u32 } -variant metal2vulkan::bind::FieldLocation::PushWindow PushWindow { offset: u32 } -variant metal2vulkan::bind::HeapPlacement::Planned Planned -variant metal2vulkan::bind::HeapPlacement::ResourceId ResourceId -variant metal2vulkan::bind::HeapSource::Bound Bound(SlotRef) -variant metal2vulkan::bind::HeapSource::Used Used(u32) -variant metal2vulkan::bind::ImageSource::Neutral Neutral(NeutralResource) -variant metal2vulkan::bind::ImageSource::Texture Texture { slot: SlotRef, view: ImageViewDesc } -variant metal2vulkan::bind::IndexOverrun::Clamped Clamped { past_end: u32 } -variant metal2vulkan::bind::IndirectArgs::Buffer Buffer(IndirectRef) -variant metal2vulkan::bind::IndirectArgs::Replay Replay -variant metal2vulkan::bind::MeshArgumentsForm::FoldedObject FoldedObject -variant metal2vulkan::bind::MeshArgumentsForm::Mesh Mesh -variant metal2vulkan::bind::MeshArgumentsForm::Object Object -variant metal2vulkan::bind::NeutralResource::Image Image { view_type: vk::ImageViewType, sampled_type: SampledType, depth_compare: bool, samples: u32, storage_format: Option } -variant metal2vulkan::bind::NeutralResource::Sampler Sampler { compare: bool } -variant metal2vulkan::bind::NeutralResource::Sink Sink { min_bytes: u32 } -variant metal2vulkan::bind::NeutralResource::TexelBuffer TexelBuffer { format: vk::Format } -variant metal2vulkan::bind::NeutralResource::ZeroBuffer ZeroBuffer { min_bytes: u32 } -variant metal2vulkan::bind::PlanDiagnostic::AstcStorageNeutral AstcStorageNeutral { slot: SlotRef, substituted: NeutralResource } -variant metal2vulkan::bind::PlanDiagnostic::CrossClassHeapNeutral CrossClassHeapNeutral { stage: Stage, class: HandleClass, element: u32, source: HeapSource } -variant metal2vulkan::bind::PlanDiagnostic::CrossClassNeutral CrossClassNeutral { slot: SlotRef, substituted: NeutralResource } -variant metal2vulkan::bind::PlanDiagnostic::IncompatibleBinding IncompatibleBinding { slot: SlotRef, substituted: NeutralResource } -variant metal2vulkan::bind::PlanDiagnostic::IncompatibleHeapEntry IncompatibleHeapEntry { class: HandleClass, element: u32, source: HeapSource, substituted: NeutralResource } -variant metal2vulkan::bind::PushHole::CaptureIndexAddress CaptureIndexAddress { stages: vk::ShaderStageFlags, offset: u32 } -variant metal2vulkan::bind::PushHole::CommandRecordsAddress CommandRecordsAddress { stages: vk::ShaderStageFlags, offset: u32 } -variant metal2vulkan::bind::PushHole::ExecutionStatusAddress ExecutionStatusAddress { stages: vk::ShaderStageFlags, offset: u32 } -variant metal2vulkan::bind::PushHole::MergedDrawAddress MergedDrawAddress { stages: vk::ShaderStageFlags, offset: u32 } -variant metal2vulkan::bind::PushHole::ReplayRegionAddress ReplayRegionAddress { stages: vk::ShaderStageFlags, offset: u32 } -variant metal2vulkan::bind::PushHole::RootTableAddress RootTableAddress { stages: vk::ShaderStageFlags, offset: u32 } variant metal2vulkan::bind::RateMapError::ExtentMismatch ExtentMismatch { layer: usize, axis: usize } variant metal2vulkan::bind::RateMapError::Granularity Granularity { granularity: u32 } variant metal2vulkan::bind::RateMapError::NoSamples NoSamples { layer: usize, axis: usize } @@ -9226,67 +8725,11 @@ variant metal2vulkan::bind::RateMapError::ScreenExtent ScreenExtent { extent: u3 variant metal2vulkan::bind::RateMapError::Tile Tile { tile: usize } variant metal2vulkan::bind::RateMapError::Unpinned Unpinned { reason: UnpinnedCompile } variant metal2vulkan::bind::RateMapError::VerticalAxis VerticalAxis { layer: usize } -variant metal2vulkan::bind::ResourceClass::Buffer Buffer -variant metal2vulkan::bind::ResourceClass::Heap Heap -variant metal2vulkan::bind::ResourceClass::Texture Texture(TextureFacts) -variant metal2vulkan::bind::SamplerSource::Immutable Immutable -variant metal2vulkan::bind::SamplerSource::Neutral Neutral(NeutralResource) -variant metal2vulkan::bind::SamplerSource::Slot Slot { slot: SlotRef, compare: bool, integer: bool, opaque_black: OpaqueBlackBorder } -variant metal2vulkan::bind::StatusWord::ResidentMisses ResidentMisses -variant metal2vulkan::bind::StatusWord::SeqCstFences SeqCstFences -variant metal2vulkan::bind::StatusWord::Status Status -variant metal2vulkan::bind::TextureShape::Buffer Buffer { pixel_format: metal::PixelFormat, swizzle: metal::TextureSwizzleChannels, parts: u32 } -variant metal2vulkan::bind::TextureShape::Texture Texture { texture_type: metal::TextureType, pixel_format: metal::PixelFormat, sample_count: u32, usage: metal::TextureUsage, mipmap_level_count: u32, sparse: bool, swizzle: metal::TextureSwizzleChannels, address_modes: metal::sampler::AddressModeMap, offset_base_axes: u8, ycbcr_in_place: bool, ycbcr_planes_sampler: Option, texel_rows: bool } variant metal2vulkan::bind::UnpinnedCompile::DenseSamples DenseSamples { layer: usize, axis: usize, samples: usize, extent: u32 } variant metal2vulkan::bind::UnpinnedCompile::LayerCount LayerCount { count: usize } variant metal2vulkan::bind::UnpinnedCompile::SampleCount SampleCount { layer: usize, axis: usize, samples: usize, max: usize } variant metal2vulkan::bind::UnpinnedCompile::SampleOutOfRange SampleOutOfRange { layer: usize, axis: usize, index: usize } variant metal2vulkan::bind::UnpinnedCompile::ScreenExtent ScreenExtent { extent: u32 } -variant metal2vulkan::bind::UseTarget::ControlPointIndices ControlPointIndices -variant metal2vulkan::bind::UseTarget::IndexBuffer IndexBuffer -variant metal2vulkan::bind::UseTarget::Indirect Indirect -variant metal2vulkan::bind::UseTarget::PatchIndices PatchIndices -variant metal2vulkan::bind::UseTarget::Slot Slot(SlotRef) -variant metal2vulkan::bind::UseTarget::TessellationFactors TessellationFactors -variant metal2vulkan::bind::UseTarget::TileMap TileMap(SlotRef) -variant metal2vulkan::bind::UseTarget::Used Used(u32) -variant metal2vulkan::bind::UsedClass::Buffer Buffer -variant metal2vulkan::bind::UsedClass::Heap Heap -variant metal2vulkan::bind::UsedClass::Texture Texture(TextureShape) -variant metal2vulkan::bind::WriteSource::AccelerationStructure AccelerationStructure { slot: SlotRef, level: AccelerationStructureLevel } -variant metal2vulkan::bind::WriteSource::ArgumentSampler ArgumentSampler { index: u32, compare: bool, integer: bool } -variant metal2vulkan::bind::WriteSource::ArgumentTable ArgumentTable { stage: Stage, bytes_len: u32 } -variant metal2vulkan::bind::WriteSource::Attachment Attachment { color_index: u32 } -variant metal2vulkan::bind::WriteSource::Buffer Buffer { slot: SlotRef } -variant metal2vulkan::bind::WriteSource::CombinedImageSampler CombinedImageSampler { image: ImageSource, sampler: SamplerSource } -variant metal2vulkan::bind::WriteSource::ConstantBlob ConstantBlob { stage: Stage } -variant metal2vulkan::bind::WriteSource::ControlPointIndices ControlPointIndices -variant metal2vulkan::bind::WriteSource::ExecutionStatus ExecutionStatus -variant metal2vulkan::bind::WriteSource::FunctionTableSnapshot FunctionTableSnapshot -variant metal2vulkan::bind::WriteSource::HandleTable HandleTable { stage: Stage, bytes_len: u32 } -variant metal2vulkan::bind::WriteSource::HeapEntry HeapEntry { class: HandleClass, element: u32, source: HeapSource, view: ImageViewDesc } -variant metal2vulkan::bind::WriteSource::Imageblock Imageblock -variant metal2vulkan::bind::WriteSource::InlineBytes InlineBytes { slot: SlotRef } -variant metal2vulkan::bind::WriteSource::Neutral Neutral(NeutralResource) -variant metal2vulkan::bind::WriteSource::PatchIndices PatchIndices { min_bytes: u32 } -variant metal2vulkan::bind::WriteSource::Sampler Sampler { slot: SlotRef, compare: bool, integer: bool, opaque_black: OpaqueBlackBorder } -variant metal2vulkan::bind::WriteSource::TessellationFactors TessellationFactors -variant metal2vulkan::bind::WriteSource::TexelBuffer TexelBuffer { slot: SlotRef, format: vk::Format, window: Window } -variant metal2vulkan::bind::WriteSource::TexelRows TexelRows { slot: SlotRef, format: vk::Format } -variant metal2vulkan::bind::WriteSource::Texture Texture { slot: SlotRef, view: ImageViewDesc } -variant metal2vulkan::bind::WriteSource::TileAttachment TileAttachment { color_index: u32, format: vk::Format } -variant metal2vulkan::bind::WriteSource::TileMap TileMap { slot: SlotRef } -variant metal2vulkan::bind::WriteSource::TileMemory TileMemory { bytes: u64 } -variant metal2vulkan::bind::WriteSource::YCbCrInPlace YCbCrInPlace { slot: SlotRef } -variant metal2vulkan::bind::WriteSource::YCbCrPlanesImage YCbCrPlanesImage { slot: SlotRef } -variant metal2vulkan::bind::YCbCrMatrix::Bt2020 Bt2020 -variant metal2vulkan::bind::YCbCrMatrix::Bt601 Bt601 -variant metal2vulkan::bind::YCbCrMatrix::Bt709 Bt709 -variant metal2vulkan::bind::YCbCrOutput::Codes Codes -variant metal2vulkan::bind::YCbCrOutput::Converted Converted -variant metal2vulkan::bind::YCbCrOutput::Srgb Srgb -variant metal2vulkan::bind::YCbCrRange::Full Full -variant metal2vulkan::bind::YCbCrRange::Video Video variant metal2vulkan::bind::indirect_commands::Action::DispatchThreadgroups DispatchThreadgroups { grid: [u32; 3], local_size: [u32; 3] } variant metal2vulkan::bind::indirect_commands::Action::DispatchThreads DispatchThreads { grid: [u32; 3], local_size: [u32; 3] } variant metal2vulkan::bind::indirect_commands::Action::DrawIndexedPatches DrawIndexedPatches { control_points: u32, patch_start: u32, patch_count: u32, patch_index_buffer: u64, control_point_index_buffer: u64, instance_count: u32, base_instance: u32, factor_buffer: u64, factor_instance_stride: u32, factor_scale: u32 } @@ -9788,33 +9231,6 @@ variant metal2vulkan::error::AbiError::UnknownStageAttribute UnknownStageAttribu variant metal2vulkan::error::Attachment::Color Color(u32) variant metal2vulkan::error::Attachment::Depth Depth variant metal2vulkan::error::Attachment::Stencil Stencil -variant metal2vulkan::error::BindError::ControlPointIndexRange ControlPointIndexRange { needed: u64, limit: u64 } -variant metal2vulkan::error::BindError::ControlPointIndexing ControlPointIndexing { indexed: bool } -variant metal2vulkan::error::BindError::DescriptorRangeExceeded DescriptorRangeExceeded { slot: SlotRef, needed: u64, limit: u64 } -variant metal2vulkan::error::BindError::HeapTooLarge HeapTooLarge { count: u64, limit: u64 } -variant metal2vulkan::error::BindError::Internal Internal(InternalError) -variant metal2vulkan::error::BindError::InvalidControlPointIndexBuffer InvalidControlPointIndexBuffer { offset: u64 } -variant metal2vulkan::error::BindError::InvalidDescriptor InvalidDescriptor(DescriptorError) -variant metal2vulkan::error::BindError::InvalidDrawKind InvalidDrawKind { patches: bool } -variant metal2vulkan::error::BindError::InvalidImageblockSize InvalidImageblockSize { width: u32, height: u32 } -variant metal2vulkan::error::BindError::InvalidMeshDraw InvalidMeshDraw { mesh: bool } -variant metal2vulkan::error::BindError::InvalidPatchIndexBuffer InvalidPatchIndexBuffer { offset: u64 } -variant metal2vulkan::error::BindError::InvalidRenderArea InvalidRenderArea { width: u32, height: u32 } -variant metal2vulkan::error::BindError::InvalidTessellationFactorScale InvalidTessellationFactorScale { bits: u32 } -variant metal2vulkan::error::BindError::InvalidVertexAmplification InvalidVertexAmplification { count: u32, max: u32, view_mappings: u32 } -variant metal2vulkan::error::BindError::MissingDeviceAddress MissingDeviceAddress { slot: SlotRef } -variant metal2vulkan::error::BindError::MissingGuestAddress MissingGuestAddress { slot: SlotRef } -variant metal2vulkan::error::BindError::MissingPrimitiveType MissingPrimitiveType -variant metal2vulkan::error::BindError::MissingStageInRegion MissingStageInRegion -variant metal2vulkan::error::BindError::MissingThreadgroupMemory MissingThreadgroupMemory { index: u32 } -variant metal2vulkan::error::BindError::NeedsVariant NeedsVariant { variant: Box } -variant metal2vulkan::error::BindError::PatchControlPoints PatchControlPoints { given: u32, expected: u32 } -variant metal2vulkan::error::BindError::PatchIndexRange PatchIndexRange { needed: u64, limit: u64 } -variant metal2vulkan::error::BindError::SlotOutOfRange SlotOutOfRange { slot: SlotRef } -variant metal2vulkan::error::BindError::TessellationFactorRange TessellationFactorRange { needed: u64, limit: u64 } -variant metal2vulkan::error::BindError::TexelBufferTooLarge TexelBufferTooLarge { slot: SlotRef, elements: u64, limit: u64 } -variant metal2vulkan::error::BindError::UnboundVertexBuffer UnboundVertexBuffer { slot: SlotRef } -variant metal2vulkan::error::BindError::Unsupported Unsupported(Unsupported) variant metal2vulkan::error::BitcodeError::BadDataLayout BadDataLayout variant metal2vulkan::error::BitcodeError::BadIdentification BadIdentification variant metal2vulkan::error::BitcodeError::BadMetadata BadMetadata @@ -10338,14 +9754,12 @@ variant metal2vulkan::pipeline::PrecisionNote::ExtrapolatedInterpolation Extrapo variant metal2vulkan::pipeline::PrecisionNote::F16FmaDoubleRounding F16FmaDoubleRounding variant metal2vulkan::pipeline::PrecisionNote::F16IntConvDoubleRounding F16IntConvDoubleRounding variant metal2vulkan::pipeline::PrecisionNote::FastMathRewrites FastMathRewrites -variant metal2vulkan::pipeline::PrecisionNote::FloatSampleFilter FloatSampleFilter variant metal2vulkan::pipeline::PrecisionNote::Fp8Value Fp8Value variant metal2vulkan::pipeline::PrecisionNote::FragmentSimdgroupGrouping FragmentSimdgroupGrouping variant metal2vulkan::pipeline::PrecisionNote::FunctionStorageAssumed FunctionStorageAssumed variant metal2vulkan::pipeline::PrecisionNote::GradFromBias GradFromBias variant metal2vulkan::pipeline::PrecisionNote::HalfOutputFastMathBlend HalfOutputFastMathBlend variant metal2vulkan::pipeline::PrecisionNote::HalfOutputPrecision HalfOutputPrecision -variant metal2vulkan::pipeline::PrecisionNote::HalfSampleFilter HalfSampleFilter variant metal2vulkan::pipeline::PrecisionNote::HalfTexelConversion HalfTexelConversion variant metal2vulkan::pipeline::PrecisionNote::LinkedSamplerNumbering LinkedSamplerNumbering variant metal2vulkan::pipeline::PrecisionNote::LoopedSampleOutputs LoopedSampleOutputs @@ -10422,13 +9836,11 @@ variant metal2vulkan::pipeline::PushField::TessellationFactorAddress Tessellatio variant metal2vulkan::pipeline::PushField::TessellationFactorInstanceStride TessellationFactorInstanceStride variant metal2vulkan::pipeline::PushField::TessellationFactorOffset TessellationFactorOffset variant metal2vulkan::pipeline::PushField::TessellationFactorScale TessellationFactorScale -variant metal2vulkan::pipeline::PushField::TexelRows TexelRows(SlotRef) variant metal2vulkan::pipeline::PushField::TextureIntegerChannels TextureIntegerChannels(SlotRef) variant metal2vulkan::pipeline::PushField::TextureLevels TextureLevels(SlotRef) variant metal2vulkan::pipeline::PushField::VertexBufferStride VertexBufferStride(u32) variant metal2vulkan::pipeline::PushField::VerticesPerPrimitive VerticesPerPrimitive variant metal2vulkan::pipeline::PushField::ViewportCount ViewportCount -variant metal2vulkan::pipeline::PushField::YCbCrInPlace YCbCrInPlace(SlotRef) variant metal2vulkan::pipeline::PushField::ZeroAddress ZeroAddress variant metal2vulkan::pipeline::PushLoc::ArgumentTable ArgumentTable { offset: u32 } variant metal2vulkan::pipeline::PushLoc::Push Push { offset: u32 } @@ -10523,7 +9935,6 @@ variant metal2vulkan::pipeline::RuntimeFact::StorageTextureNumericType StorageTe variant metal2vulkan::pipeline::RuntimeFact::StorageTextureWriteRounding StorageTextureWriteRounding { slot: SlotRef, halves: bool } variant metal2vulkan::pipeline::RuntimeFact::TexelBufferParts TexelBufferParts { slot: SlotRef } variant metal2vulkan::pipeline::RuntimeFact::TexelBufferRange TexelBufferRange { slot: SlotRef } -variant metal2vulkan::pipeline::RuntimeFact::TexelRows TexelRows { slot: SlotRef } variant metal2vulkan::pipeline::RuntimeFact::TextureSwizzle TextureSwizzle { slot: SlotRef } variant metal2vulkan::pipeline::RuntimeFact::ThreadgroupMemoryLength ThreadgroupMemoryLength { index: u32 } variant metal2vulkan::pipeline::RuntimeFact::ThreadsPerThreadgroup ThreadsPerThreadgroup @@ -10536,7 +9947,6 @@ variant metal2vulkan::pipeline::RuntimeFact::UnitAxes UnitAxes { axes: u8, relie variant metal2vulkan::pipeline::RuntimeFact::VertexBufferStride VertexBufferStride { layout: u32 } variant metal2vulkan::pipeline::RuntimeFact::VertexFetch VertexFetch { attr: u32 } variant metal2vulkan::pipeline::RuntimeFact::ViewportCount ViewportCount -variant metal2vulkan::pipeline::RuntimeFact::YCbCrInPlace YCbCrInPlace { slot: SlotRef, samplers: u32, device: bool } variant metal2vulkan::pipeline::RuntimeFact::ZeroedColor ZeroedColor { color: u32, format: crate::metal::PixelFormat } variant metal2vulkan::pipeline::SampledType::Float Float variant metal2vulkan::pipeline::SampledType::Sint Sint @@ -10636,13 +10046,6 @@ variant metal2vulkan::reflection::SlotWritability::Unknown Unknown(SlotWriteGap) variant metal2vulkan::reflection::SlotWriteGap::MemberRole MemberRole variant metal2vulkan::reflection::SlotWriteGap::UnmeasuredPayloadStage UnmeasuredPayloadStage variant metal2vulkan::reflection::SlotWriteGap::UnresolvedIndex UnresolvedIndex -variant metal2vulkan::vk::DrawCommand::Draw Draw { vertex_count: u32, instance_count: u32, first_vertex: u32, first_instance: u32 } -variant metal2vulkan::vk::DrawCommand::DrawIndexed DrawIndexed { index_type: IndexType, index_buffer_offset: u64, index_count: u32, instance_count: u32, first_index: u32, vertex_offset: i32, first_instance: u32 } -variant metal2vulkan::vk::DrawCommand::DrawIndexedIndirect DrawIndexedIndirect { index_type: IndexType, index_buffer_offset: u64, offset: u64, draw_count: u32, stride: u32 } -variant metal2vulkan::vk::DrawCommand::DrawIndirect DrawIndirect { offset: u64, draw_count: u32, stride: u32 } -variant metal2vulkan::vk::DrawCommand::DrawMeshTasks DrawMeshTasks { group_count_x: u32, group_count_y: u32, group_count_z: u32 } -variant metal2vulkan::vk::DrawCommand::DrawMeshTasksIndirect DrawMeshTasksIndirect { offset: u64, draw_count: u32, stride: u32 } -variant metal2vulkan::vk::DrawCommand::DrawMeshTasksIndirectCount DrawMeshTasksIndirectCount { offset: u64, count_offset: u64, max_draw_count: u32, stride: u32 } variant metal2vulkan::vk::NumericFormat::Bool Bool variant metal2vulkan::vk::NumericFormat::Sfixed5 Sfixed5 variant metal2vulkan::vk::NumericFormat::Sfloat Sfloat diff --git a/crates/metal2vulkan/tests/api_surface.rs b/crates/metal2vulkan/tests/api_surface.rs index a9aa4a51d..265437aad 100644 --- a/crates/metal2vulkan/tests/api_surface.rs +++ b/crates/metal2vulkan/tests/api_surface.rs @@ -207,7 +207,6 @@ surface! { enum GenericPointer N; struct InternalError N; enum InternalKind N; - enum BindError N; } "device" => metal2vulkan::device { fn vk_stage; @@ -438,86 +437,11 @@ surface! { enum ArgumentType N; const ARGUMENT_HANDLE_BYTES; enum Dispatch N; - struct DispatchCommands N; - struct DispatchRegion N; - enum IndirectArgs N; enum DrawCall N; - struct DrawCommands N; fn alpha_test_code; - enum IndexOverrun N; - enum HeapSource E; - fn handle_entry; - const HANDLE_ENTRY_BYTES; - struct BufferExtent N; - struct BufferRange N; - struct DescriptorBytes N; - struct DescriptorRange N; struct IndexBufferRef N; - struct IndirectRef N; - struct PushConstantWrite N; - enum PushHole E; - struct ResidentRange N; - struct RootTable N; - enum NeutralResource N; - fn sampler_desc; - enum AccessClass N; - struct BindingPlan N; - struct ByteRange N; - struct ComputeTemplate N; - struct DescriptorWrite N; - enum FieldLocation N; - struct GraphicsTemplate N; - enum ImageSource E; - struct ImageViewDesc N; - enum PlanDiagnostic N; - struct PushFieldPlacement N; - struct PushTemplate N; - struct ResourceUse N; - enum SamplerSource E; - enum UseTarget E; - struct VertexBufferBind N; - struct ViewSetup N; - enum WriteSource N; - struct BindShape N; - struct BindState N; - struct BoundAccelerationStructure N; - enum BoundBuffer N; - struct BoundSampler N; - struct BoundSamplerShape N; - enum BoundTexture N; - struct BufferRanges N; - enum BufferShape N; - enum HeapPlacement N; - enum ResourceClass N; struct SamplerDescriptor N; - struct SamplerShape N; - struct StageShape N; - struct StageTable N; - struct TextureFacts N; - enum TextureShape N; - enum UsedClass N; - struct UsedResource N; - struct UsedShape N; - struct VertexAmplification N; - struct ViewMapping N; - struct ImageblockSize N; struct StageInRegion N; - struct TessellationFactors N; - struct TessellationFactorBuffer N; - struct ArgumentSampler N; - struct ArgumentSamplersShape N; - struct ArgumentFunctionTable N; - struct FunctionTablesShape N; - struct TileThreadgroupMemory N; - struct TileThreadgroupArgument N; - struct ExecutionStatus E; - struct StatusBits E; - struct StatusReport N; - enum StatusWord N; - const DRAW_ARGUMENT_BYTES; - const DRAW_INDEX_ENTRY_BYTES; - const MERGED_REST_FIRST; - struct FunctionTableSnapshot O; struct RasterizationRateMap O; struct RateMapDescriptor N; struct RateMapLayerDescriptor N; @@ -530,23 +454,7 @@ surface! { struct PvrtcDecode N; enum EtcDecode N; enum EtcTexels N; - fn fold_object_grid; - fn metal_object_grid; - struct MeshArguments N; - enum MeshArgumentsForm E; - struct MeshGridLimits N; - struct ObjectFold N; - const METAL_MESH_GRID_AXIS; - const METAL_MESH_GRID_TOTAL; - const METAL_OBJECT_GRID_TOTAL; - struct YCbCrInPlace N; struct YCbCrPlanesSampler N; - struct TexelRows N; - fn part_texels; - struct YCbCrCodes N; - enum YCbCrOutput N; - enum YCbCrRange N; - enum YCbCrMatrix N; mod indirect_commands; } "bind::indirect_commands" => metal2vulkan::bind::indirect_commands { @@ -735,7 +643,6 @@ surface! { fn attribute_fetch; } "vk" => metal2vulkan::vk { - enum DrawCommand E; struct AccessFlags O; struct AccessFlags2 O; struct BlendFactor O; @@ -799,7 +706,6 @@ surface! { // ---- The consumer flow through the public paths (M5 "`CompiledFunction` round trip") ---- -use metal2vulkan::bind::{BindState, BoundBuffer, Dispatch, DrawCall, StageTable}; use metal2vulkan::cache::{Hash256, PipelineArtifact, PipelineKey}; use metal2vulkan::device::{Device, DeviceDescription, DevicePolicy, FloatWidth}; use metal2vulkan::library::{CompiledFunction, Library}; @@ -858,17 +764,6 @@ fn device_under(stem: &str, policy: DevicePolicy) -> Device { Device::from_queries(desc, policy).expect("device") } -/// A buffer bound at `offset` in a `length`-byte allocation. -fn buffer(length: u64, offset: u64) -> BoundBuffer { - BoundBuffer::Buffer { - length, - offset, - gpu_address: 0x1_0000, - device_address: None, - attribute_stride: None, - } -} - /// `f` compiled on `dev`, encoded, and decoded: the decoded function equals the original and /// re-encodes to the same bytes. fn round_tripped( @@ -887,58 +782,6 @@ fn round_tripped( back } -/// A compute pipeline linked from a decoded `CompiledFunction` is the pipeline compiled from the -/// function, it round-trips as an artifact, and plans and dispatches the same. -#[test] -fn compiled_functions_round_trip_through_the_public_api() { - let Some(bc) = fixture("store_const") else { - return; - }; - for stem in ["moltenvk-m3", "runtime-floor"] { - let dev = device(stem); - let f = FunctionDescriptor::new( - Library::from_air(&bc) - .expect("library") - .function("store_const") - .expect("function"), - ); - let from_source = dev - .compile_compute_pipeline( - &ComputePipelineDescriptor::new(StageSource::Function(f.clone())), - &Budget::standard(), - ) - .expect("pipeline from the function"); - let back = round_tripped(&dev, &f, &LoweringInputs::new()); - let d = ComputePipelineDescriptor::new(StageSource::Compiled(back)); - assert_eq!(dev.compute_pipeline_key(&d), from_source.key, "{stem}"); - let linked = dev - .compile_compute_pipeline(&d, &Budget::standard()) - .expect("pipeline from the decoded function"); - assert_eq!(linked, from_source, "{stem}"); - let cached = ComputePipeline::from_bytes_for_key(&linked.to_bytes(), &linked.key, &dev) - .expect("pipeline decode"); - assert_eq!(cached, from_source, "{stem}"); - - let mut table = StageTable::default(); - table.buffers.insert(0, buffer(4096, 256)); - let mut state = BindState::default(); - state.stages.insert(Stage::Kernel, table); - let dispatch = Dispatch::Threads { - threads: [100, 1, 1], - threads_per_group: [32, 1, 1], - }; - let plan = cached.plan(&dev, &state.shape()).expect("plan"); - assert_eq!(plan, from_source.plan(&dev, &state.shape()).expect("plan")); - assert_eq!( - plan.instantiate_dispatch(&state, &dispatch), - from_source - .plan(&dev, &state.shape()) - .expect("plan") - .instantiate_dispatch(&state, &dispatch) - ); - } -} - /// A stage's module statistics: filled by the compile, the same counts the compiled function /// states before linking, kept across an artifact round-trip, and left out of the content digest, /// which already covers the words they describe. @@ -1020,64 +863,6 @@ fn a_stage_states_what_its_module_contains() { ); } -/// The content digests are public: a pipeline's names what it says, not the build that compiled it. -/// Another build of the crate, whose versions differ and so move every cache key, compiles the same -/// content under another `key`; that key and another profile fingerprint leave the digest equal, -/// while one SPIR-V word moves it. A binding plan's digest is its content's: equal for equal plans, -/// moved by one changed value. -#[test] -fn content_digests_name_what_a_pipeline_says_not_its_build() { - let Some(bc) = fixture("store_const") else { - return; - }; - let dev = device("moltenvk-m3"); - let f = FunctionDescriptor::new( - Library::from_air(&bc) - .expect("library") - .function("store_const") - .expect("function"), - ); - let pipeline = dev - .compile_compute_pipeline( - &ComputePipelineDescriptor::new(StageSource::Function(f)), - &Budget::standard(), - ) - .expect("pipeline"); - let digest: Hash256 = pipeline.content_digest(); - let decoded = ComputePipeline::from_bytes(&pipeline.to_bytes(), &dev).expect("decode"); - assert_eq!(decoded.content_digest(), digest); - - let mut other_build = pipeline.clone(); - other_build.key = PipelineKey::new([7; 32]); - other_build.profile = [9; 32]; - assert_eq!(other_build.content_digest(), digest); - - let mut edited = pipeline.clone(); - let mut words = edited.stage.spirv.to_vec(); - let last = words.len() - 1; - words[last] ^= 1; - edited.stage.spirv = words.into(); - assert_ne!(edited.content_digest(), digest); - - // The render pipeline's digest, by the same definition. - let _: fn(&RenderPipeline) -> Hash256 = RenderPipeline::content_digest; - - #[cfg(feature = "serde")] - { - let mut table = StageTable::default(); - table.buffers.insert(0, buffer(4096, 256)); - let mut state = BindState::default(); - state.stages.insert(Stage::Kernel, table); - let plan = pipeline.plan(&dev, &state.shape()).expect("plan"); - let plan_digest = plan.content_digest().expect("plan digest"); - let replanned = other_build.plan(&dev, &state.shape()).expect("plan"); - assert_eq!(replanned.content_digest(), Ok(plan_digest)); - let mut edited = plan.clone(); - edited.compute = None; - assert_ne!(edited.content_digest(), Ok(plan_digest)); - } -} - /// The precision contract is public: a fast `float` division records the device's arithmetic, /// Metal's precise division records the device's division, its denormals and its NaN /// (`NativeDivision`, `DeviceDenormals`, `NativeNanEncoding`), an integer operator has no notes, and @@ -1389,91 +1174,6 @@ fn one_entry_of_a_bare_module_translates_through_the_public_api() { } } -/// A render pipeline linked from decoded vertex and fragment `CompiledFunction`s, each compiled -/// under the inputs `render_pipeline_key` hands out, is the pipeline compiled from the -/// functions, round-trips as an artifact, and plans and draws the same. -#[test] -fn compiled_render_stages_round_trip_through_the_public_api() { - let Some(bc) = fixture("stage_io") else { - return; - }; - let lib = Library::from_air(&bc).expect("library"); - let vertex = FunctionDescriptor::new(lib.function("stage_io_vertex").expect("vertex")); - let fragment = FunctionDescriptor::new(lib.function("stage_io_fragment").expect("fragment")); - let layout = stage_io_layout(); - let descriptor = |v: StageSource, f: StageSource| { - let mut d = RenderPipelineDescriptor::new(v); - d.fragment = Some(f); - d.vertex_descriptor = Some(layout.clone()); - d.color_attachments[0] = Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm)); - d.color_attachments[2] = Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA32Uint)); - d.depth_format = Some(PixelFormat::Depth32Float); - d - }; - for stem in ["moltenvk-m3", "lavapipe"] { - let dev = device(stem); - let from_functions = descriptor( - StageSource::Function(vertex.clone()), - StageSource::Function(fragment.clone()), - ); - let keys = dev - .render_pipeline_key(&from_functions, &Budget::standard()) - .expect("keys"); - let from_source = dev - .compile_render_pipeline(&from_functions, &Budget::standard()) - .expect("pipeline from the functions"); - assert_eq!(keys.pipeline, from_source.key, "{stem}"); - - // Each stage compiles on its own under the inputs its pipeline's keys hand out: a - // vertex function's are the vertex-fetch projection over the attributes it reads, a - // fragment function's on the common path how its `RGBA8Unorm` attachment takes its - // float output where the device does not convert as Metal does, and where its push - // fields start, at the vertex function's push end. - let vertex_inputs = keys.vertex_inputs.clone().expect("vertex inputs"); - assert!(vertex_inputs.vertex_fetch.is_some(), "{stem}"); - let v = round_tripped(&dev, &vertex, &vertex_inputs); - assert_eq!(*v.key(), keys.vertex, "{stem}"); - let mut common = with_color_writes(LoweringInputs::new(), &[(0, UNORM8)]); - common.push_base = v.fragment_push_base(); - assert_eq!(keys.fragment_inputs.as_ref(), Some(&common), "{stem}"); - let f = round_tripped(&dev, &fragment, &common); - assert_eq!(Some(*f.key()), keys.fragment, "{stem}"); - let from_compiled = descriptor(StageSource::Compiled(v), StageSource::Compiled(f)); - let compiled_keys = dev - .render_pipeline_key(&from_compiled, &Budget::standard()) - .expect("keys of the decoded functions"); - assert_eq!(compiled_keys.pipeline, keys.pipeline, "{stem}"); - assert_eq!(compiled_keys.vertex_inputs, None, "{stem}"); - let linked = dev - .compile_render_pipeline(&from_compiled, &Budget::standard()) - .expect("pipeline from the decoded functions"); - assert_eq!(linked, from_source, "{stem}"); - let cached = RenderPipeline::from_bytes_for_key(&linked.to_bytes(), &linked.key, &dev) - .expect("pipeline decode"); - assert_eq!(cached, from_source, "{stem}"); - - let mut table = StageTable::default(); - table.buffers.insert(0, buffer(24 * 64, 48)); - table.buffers.insert(1, buffer(256, 16)); - let mut state = BindState::default(); - state.stages.insert(Stage::Vertex, table); - let draw = DrawCall::Primitives { - vertex_start: 3, - vertex_count: 6, - instance_count: 2, - base_instance: 5, - }; - let plan = cached.plan(&dev, &state.shape()).expect("plan"); - let original = from_source.plan(&dev, &state.shape()).expect("plan"); - assert_eq!(plan, original, "{stem}"); - assert_eq!( - plan.instantiate_draw(&state, &draw), - original.instantiate_draw(&state, &draw), - "{stem}" - ); - } -} - // ---- The source scan ---- fn src_dir() -> PathBuf { @@ -2182,3 +1882,144 @@ fn every_public_entry_is_documented() { missing.join("\n ") ); } + +/// A compute pipeline linked from a decoded `CompiledFunction` is the pipeline compiled from the +/// function, and it round-trips as an artifact. +#[test] +fn compiled_functions_round_trip_through_the_public_api() { + let Some(bc) = fixture("store_const") else { + return; + }; + for stem in ["moltenvk-m3", "runtime-floor"] { + let dev = device(stem); + let f = FunctionDescriptor::new( + Library::from_air(&bc) + .expect("library") + .function("store_const") + .expect("function"), + ); + let from_source = dev + .compile_compute_pipeline( + &ComputePipelineDescriptor::new(StageSource::Function(f.clone())), + &Budget::standard(), + ) + .expect("pipeline from the function"); + let back = round_tripped(&dev, &f, &LoweringInputs::new()); + let d = ComputePipelineDescriptor::new(StageSource::Compiled(back)); + assert_eq!(dev.compute_pipeline_key(&d), from_source.key, "{stem}"); + let linked = dev + .compile_compute_pipeline(&d, &Budget::standard()) + .expect("pipeline from the decoded function"); + assert_eq!(linked, from_source, "{stem}"); + let cached = ComputePipeline::from_bytes_for_key(&linked.to_bytes(), &linked.key, &dev) + .expect("pipeline decode"); + assert_eq!(cached, from_source, "{stem}"); + } +} + +/// The content digests are public: a pipeline's names what it says, not the build that compiled it. +/// Another build of the crate, whose versions differ and so move every cache key, compiles the same +/// content under another `key`; that key and another profile fingerprint leave the digest equal, +/// while one SPIR-V word moves it. +#[test] +fn content_digests_name_what_a_pipeline_says_not_its_build() { + let Some(bc) = fixture("store_const") else { + return; + }; + let dev = device("moltenvk-m3"); + let f = FunctionDescriptor::new( + Library::from_air(&bc) + .expect("library") + .function("store_const") + .expect("function"), + ); + let pipeline = dev + .compile_compute_pipeline( + &ComputePipelineDescriptor::new(StageSource::Function(f)), + &Budget::standard(), + ) + .expect("pipeline"); + let digest: Hash256 = pipeline.content_digest(); + let decoded = ComputePipeline::from_bytes(&pipeline.to_bytes(), &dev).expect("decode"); + assert_eq!(decoded.content_digest(), digest); + + let mut other_build = pipeline.clone(); + other_build.key = PipelineKey::new([7; 32]); + other_build.profile = [9; 32]; + assert_eq!(other_build.content_digest(), digest); + + let mut edited = pipeline.clone(); + let mut words = edited.stage.spirv.to_vec(); + let last = words.len() - 1; + words[last] ^= 1; + edited.stage.spirv = words.into(); + assert_ne!(edited.content_digest(), digest); + + // The render pipeline's digest, by the same definition. + let _: fn(&RenderPipeline) -> Hash256 = RenderPipeline::content_digest; +} + +/// A render pipeline linked from decoded vertex and fragment `CompiledFunction`s, each compiled +/// under the inputs `render_pipeline_key` hands out, is the pipeline compiled from the +/// functions, and round-trips as an artifact. +#[test] +fn compiled_render_stages_round_trip_through_the_public_api() { + let Some(bc) = fixture("stage_io") else { + return; + }; + let lib = Library::from_air(&bc).expect("library"); + let vertex = FunctionDescriptor::new(lib.function("stage_io_vertex").expect("vertex")); + let fragment = FunctionDescriptor::new(lib.function("stage_io_fragment").expect("fragment")); + let layout = stage_io_layout(); + let descriptor = |v: StageSource, f: StageSource| { + let mut d = RenderPipelineDescriptor::new(v); + d.fragment = Some(f); + d.vertex_descriptor = Some(layout.clone()); + d.color_attachments[0] = Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm)); + d.color_attachments[2] = Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA32Uint)); + d.depth_format = Some(PixelFormat::Depth32Float); + d + }; + for stem in ["moltenvk-m3", "lavapipe"] { + let dev = device(stem); + let from_functions = descriptor( + StageSource::Function(vertex.clone()), + StageSource::Function(fragment.clone()), + ); + let keys = dev + .render_pipeline_key(&from_functions, &Budget::standard()) + .expect("keys"); + let from_source = dev + .compile_render_pipeline(&from_functions, &Budget::standard()) + .expect("pipeline from the functions"); + assert_eq!(keys.pipeline, from_source.key, "{stem}"); + + // Each stage compiles on its own under the inputs its pipeline's keys hand out: a + // vertex function's are the vertex-fetch projection over the attributes it reads, a + // fragment function's on the common path how its `RGBA8Unorm` attachment takes its + // float output where the device does not convert as Metal does, and where its push + // fields start, at the vertex function's push end. + let vertex_inputs = keys.vertex_inputs.clone().expect("vertex inputs"); + assert!(vertex_inputs.vertex_fetch.is_some(), "{stem}"); + let v = round_tripped(&dev, &vertex, &vertex_inputs); + assert_eq!(*v.key(), keys.vertex, "{stem}"); + let mut common = with_color_writes(LoweringInputs::new(), &[(0, UNORM8)]); + common.push_base = v.fragment_push_base(); + assert_eq!(keys.fragment_inputs.as_ref(), Some(&common), "{stem}"); + let f = round_tripped(&dev, &fragment, &common); + assert_eq!(Some(*f.key()), keys.fragment, "{stem}"); + let from_compiled = descriptor(StageSource::Compiled(v), StageSource::Compiled(f)); + let compiled_keys = dev + .render_pipeline_key(&from_compiled, &Budget::standard()) + .expect("keys of the decoded functions"); + assert_eq!(compiled_keys.pipeline, keys.pipeline, "{stem}"); + assert_eq!(compiled_keys.vertex_inputs, None, "{stem}"); + let linked = dev + .compile_render_pipeline(&from_compiled, &Budget::standard()) + .expect("pipeline from the decoded functions"); + assert_eq!(linked, from_source, "{stem}"); + let cached = RenderPipeline::from_bytes_for_key(&linked.to_bytes(), &linked.key, &dev) + .expect("pipeline decode"); + assert_eq!(cached, from_source, "{stem}"); + } +} diff --git a/docs/API.md b/docs/API.md index c08b4577a..690a64a53 100644 --- a/docs/API.md +++ b/docs/API.md @@ -24,8 +24,7 @@ differences from Metal. The runtime's own guide is [its README](../crates/metal2 build values with `new`, `Default` or constants, assign fields, and match with a wildcard arm. The exceptions are exhaustive on purpose: keys and Vulkan structs (`SlotRef`, `ResourceSlot`, `ApiVersion`, ...), and the enums a consumer must interpret completely to bind and draw - correctly (`StageSource`, `PushHole`, `HeapSource`, `ImageSource`, `SamplerSource`, - `UseTarget`, `SlotClass`, `VertexStride`, `DrawCommand`, `PrecisionNote`, and Metal's `PrimitiveType`, `IndexType`, `CullMode`, `Winding` + correctly (`StageSource`, `SlotClass`, `VertexStride`, `PrecisionNote`, and Metal's `PrimitiveType`, `IndexType`, `CullMode`, `Winding` and `TextureType`), where a new variant breaks your build on purpose. - **Semver** covers this surface from 0.2.0 (still `0.x`: a breaking change bumps the minor version). @@ -83,16 +82,15 @@ a description whose `maxPushConstantsSize` is below 128 bytes, Vulkan's least an window a stage is lowered for (`Unsupported{PushWindow}`, a `Limit` of `MaxPushConstantsSize`), and an inconsistent description or policy. The push window is the device's `maxPushConstantsSize` up to 256 bytes (`DeviceProfile::push_window`, section 5). A -`Device` is cheap to clone; every compile and plan takes it. +`Device` is cheap to clone; every compile takes it. The guide's examples are quoted from `examples/api_preview.rs`. Its tour device takes -`DevicePolicy::RESIDENT_TABLES`, because its binding plans (sections 5 and 6) are the translator's -binder's, which plans the resident-table domains. A runtime's device takes `DevicePolicy::default()` -and pushes the identity domains' own fields itself: the binder refuses each of them, -`Unsupported{IdentityDomains}` (a texture's or sampler's resource ID in `PushField::SlotGuestBase`, -`PushField::ConstexprSampler`, `PushField::FetchedColor`, `PushField::TessellationFactorAddress`, -the indirect commands' `PushField::IndirectRange`, `IndirectSequence` and `IndirectBase`, and -`ZeroAddress`, `BicubicTexels` and `PrivateArenaAddress`). +`DevicePolicy::default()`, the runtime's policy, which compiles under the identity domains; the +consumer pushes their fields itself (a texture's or sampler's resource ID in +`PushField::SlotGuestBase`, `PushField::ConstexprSampler`, `PushField::FetchedColor`, +`PushField::TessellationFactorAddress`, the indirect commands' `PushField::IndirectRange`, +`IndirectSequence` and `IndirectBase`, and `ZeroAddress`, `BicubicTexels` and +`PrivateArenaAddress`). ### The policy @@ -101,8 +99,8 @@ compile does. `DevicePolicy::default()` is the one constructor: the runtime comp and so do the command line, the compile worker and every validation tool. It holds: - **Bounds on a buffer-slot access at a run-time offset.** Such an access stays inside the range - the binder supplied: the shader checks it on every device, whatever buffer robustness the device - enables. + the consumer supplied: the shader checks it on every device, whatever buffer robustness the + device enables. - **The device's arithmetic.** The device's own maths library, divisions, fused multiply-adds, `float` denormals, rounding order of `dot`/`mix`/`fast::sqrt`, the grouping and fusion of fast-math sums and products (each operation in the AIR's order, its own fast-math flags its @@ -185,15 +183,14 @@ and so do the command line, the compile worker and every validation tool. It hol declares `SpecKey::DeepThreadgroup`, default false: at true its workgroup is one row of the threadgroup's threads, `(sx·sy·sz, 1, 1)`, each thread's position its `LocalInvocationIndex` unflattened in Metal's order, so a threadgroup deeper than a device's - `maxComputeWorkGroupSize[2]` runs; the binder sets it for a region deeper than - `pipeline::DEEP_THREADGROUP` (64) alone, and so does a runtime, so every other pipeline - specializes it away. `MetalDeviceProperties::max_threads_per_threadgroup` is + `maxComputeWorkGroupSize[2]` runs; a runtime sets it for a region deeper than + `pipeline::DEEP_THREADGROUP` (64) alone, so every other pipeline specializes it away. `MetalDeviceProperties::max_threads_per_threadgroup` is the capped `maxComputeWorkGroupInvocations` on every axis. A texture slot's `gpuResourceID` is pushed as its `PushField::SlotGuestBase`, and its texture is the element at the ID's index of set 1's two fixed arrays, the same layout for every pipeline ([RESOURCE-ID.md](RESOURCE-ID.md)); it binds no descriptor of its own and declares no specialization constant. An argument buffer's texture is the element at the index of the `gpuResourceID` its member holds, with no handle table, so a - slot and a member of one class index one array. No binder chooses a variant there: a + slot and a member of one class index one array. No variant is chosen there: a texture reads through the plain form whatever texture its ID names, its `float` or `half` reads take the device's sRGB decode with `PrecisionNote::SrgbTexelDecode`, and no texture is sparse (the consumer refuses a sparse texture). A texture slot sampled through a runtime sampler slot @@ -241,7 +238,7 @@ and so do the command line, the compile worker and every validation tool. It hol supplies `count * slot_bytes` bytes for each dispatch of `count` invocations, and keeps a dispatch's invocations under `2^32`. The memory needs no zeros: Metal's private memory is undefined until the thread writes it. Every precision note is - static there: no constant or binder decides one. So far they lower a kernel that reaches memory + static there: no constant or variant decides one. So far they lower a kernel that reaches memory through its buffer slots and the device addresses it loads (an argument buffer's pointer member, a stored `gpuAddress`) or makes from integers, and reads, writes, sizes or tests for nil its texture slots and its argument buffers' textures, those of an argument buffer a pointer @@ -293,7 +290,7 @@ Loops run as written: no execution bound is translated in. ### What the device answers ```rust -let device = committed_device("moltenvk-m3")?; +let device = runtime_device("moltenvk-m3")?; let enables = device.required_enables(); // ... hex(&device.profile().fingerprint()), @@ -436,8 +433,8 @@ A `ComputePipeline` is immutable plain data: - `requirements`: what the device must have enabled. Do not create the compute `VkPipeline` from `stage` alone: its specialization defaults are -placeholders (a kernel's local size is 1). Create each pipeline from a planned dispatch's -`DispatchRegion` (section 6), with the region's `specialization`, `stage_flags` and +placeholders (a kernel's local size is 1). Create each pipeline with the values its dispatch +gives the specialization constants' keys, and with the stage's `stage_flags` and `required_subgroup_size`. A required subgroup size needs `subgroupSizeControl` and the stage in `requiredSubgroupSizeStages`; full subgroups need `computeFullSubgroups`. A pipeline compiled for one device pins only what that device can take; `DeviceProfile::check` tells whether another @@ -493,9 +490,8 @@ axis is 0 and its `thread_position_in_grid` is its threadgroup's position, parti included. A dispatch of such threadgroups, where its axes are among the masks of `relief`, may run on the kernel's unit-axes variant (`VariantKey::unit_axes`, which `LoweringInputs::unit_axes` compiles): the same kernel with those positions uniform, walked without the predication they -caused, giving the same answers. Its plan -states `UnitAxes { axes, relief: 0 }` and sends a dispatch with more than one thread along one of -its axes back to the variant without them (`BindError::NeedsVariant`). A kernel has at most seven +caused, giving the same answers. Its compile states `UnitAxes { axes, relief: 0 }`, and a +dispatch with more than one thread along one of its axes takes the variant without them. A kernel has at most seven such variants per variant it runs on, one per mask. On the Iris Xe, an authored kernel of four shuffles each way and a simdgroup sum in a loop of 8 to 11 trips, in threadgroups of 8 x 1 x 16, ran 1.14 to 2.16 times the GPU time predicated (its trip count read from `thread_position_in_grid.y`) as with the same @@ -668,8 +664,7 @@ through buffer arguments it reads at any index. threadgroup memory on a profile without it is `Unsupported` with `Feature::ZeroedThreadgroupMemory`. The translator's own `Workgroup` words have none: an emulated SIMD group's exchange scratch and vote word, an object function's mesh grid, a mesh - function's primitive count and staged indices, and those of the binder's own shadow-merge and - index-rewrite kernels. Each is written + function's primitive count and staged indices. Each is written before any read of it, and an object function's payload "is assumed uninitialized at the entry of the object function" (the Metal Shading Language Specification, the `payload` attribute). Metal's documents give threadgroup memory no first contents: `MTLComputeCommandEncoder.h`'s @@ -931,14 +926,14 @@ Where Metal's rules differ from Vulkan's, the pipeline gives Metal's answer: `NotImplemented(PrimitiveId)`: an indexed strip, an indirect indexed draw, indices past their buffer, a vertex function that writes memory in that form, and a mesh pipeline. A draw of Metal's private quads or quad strip, which the consumer lists as two triangles a quad - (`BindState::quad_primitive_ids`), runs the fragment variant that reads `PrimitiveId` shifted + runs the fragment variant that reads `PrimitiveId` shifted right by one (`VariantKey::quad_primitive_ids`), as Metal counts one primitive a quad. A private type's draw whose vertex function writes the varying, or writes memory (Metal runs it once for each vertex of its list, where an indexed draw may run a shared vertex once), runs the - private list form (`VariantKey::private_list`, `BindShape::private_list`; needs device + private list form (`VariantKey::private_list`; needs device addresses): the consumer draws its list without indices from its first index as first vertex, and the vertex function reads each position's index, and Metal's base vertex in the word before - the list, at the list's address (`PushHole::CaptureIndexAddress`), adding them as Metal's vertex + the list, at the list's address (`PushField::CaptureIndexAddress`), adding them as Metal's vertex ID wraps, so each position runs once and the positions count Metal's primitives. - A device draws to at most the lesser of its `maxColorAttachments` and `maxFragmentOutputAttachments` color attachments at once (eight at the runtime's floor), where @@ -959,7 +954,7 @@ Where Metal's rules differ from Vulkan's, the pipeline gives Metal's answer: primitive one patch of its vertices (`PATCH_LIST`, `BandPrimitive::patch_control_points`), a line's without culling under front face `LineBandState::FRONT_FACE` and without depth bias, a triangle's under the draw's cull mode, front face and depth bias, and the band's `[sx, sy, h, f]` - pushed to the evaluation stage at `push_offset` (`BindState::line_band`: Vulkan viewport 0's half + pushed to the evaluation stage at `push_offset` (Vulkan viewport 0's half extent, the half width, and for triangles 1 under a clockwise front face, -1 under a counter-clockwise one). A smooth varying and the clip distances are each endpoint's, a flat or integer varying the first vertex's. It needs `tessellationShader` (`Unsupported{WideLines}` @@ -987,8 +982,8 @@ let pipeline = device.compile_render_pipeline(&descriptor, &Budget::standard())? ``` Its `stages` are a synthesized vertex and tessellation control stage, the function as the -evaluation stage, and the fragment stage. It draws patches only (`DrawCall::Patches` or -`PatchesIndirect`), with the factors from a tessellation factor buffer. The device's tessellator +evaluation stage, and the fragment stage. It draws patches only (`drawPatches:` and its +indirect and indexed forms), with the factors from a tessellation factor buffer. The device's tessellator orders the triangles (`PrecisionNote::TessellationTriangleOrder` where it is not Apple's). A device without `tessellationShader` refuses the function (`Unsupported{Tessellation}`, naming @@ -997,8 +992,8 @@ the feature), and a fragment `[[primitive_id]]` behind it is `NotImplemented(Tes ### Mesh pipelines `Device::compile_mesh_pipeline` compiles a `MeshPipelineDescriptor` (an optional object function, -a mesh function and a fragment function). Its plan draws -mesh draws only (`DrawCall::MeshThreadgroups`, `MeshThreads` and their indirect forms). The +a mesh function and a fragment function). It draws mesh draws only (`drawMeshThreadgroups:`, +`drawMeshThreads:` and their indirect forms). The stages are task and mesh shaders, which need `VK_EXT_mesh_shader` with `meshShader` (and `taskShader` for an object function). A device without them (MoltenVK, older ANV) refuses the pipeline and each of its object and mesh functions (`Unsupported{MeshShading}`, naming what it @@ -1015,46 +1010,26 @@ The mesh lowering is only compiled and validated: no mesh draw it makes has been Metal on a GPU, and the runtime makes no mesh pipeline (its README's known gaps of render pipeline states). What follows is what the lowering emits. -A grid Metal draws nothing for (an axis past `bind::METAL_MESH_GRID_AXIS`, or more than -`bind::METAL_MESH_GRID_TOTAL` threadgroups, measured on the M3 Max) draws nothing in every form: -a direct draw's command is zeroed, an object function's wrapper launches nothing for such a grid, -and an indirect draw reads its counts on the GPU. An indirect draw's -`DrawCommands::mesh_arguments` is the form of a pass to record before the render pass (one -invocation) that writes the draw's counts into the consumer's scratch, which the draw reads in -place of Metal's arguments; the translator builds no module for that pass. +A grid Metal draws nothing for (an axis past 65,535 threadgroups, or more than 1,048,575 of them, +measured on the M3 Max) draws nothing: an object function's wrapper launches nothing for such a +grid. An object grid runs at any count Metal runs, past the task stage's limits too, on a device with device addresses, `shaderInt64`, `multiDrawIndirect` and `drawIndirectCount` (every committed -profile with the extension): the object function is compiled folded, and each draw runs its grid -in pieces within the task limits (`bind::fold_object_grid`), its object stage reading the +profile with the extension): the object function is compiled folded, its object stage reading the threadgroups Metal runs and its grid from a 32-byte region record at its -`PushHole::ReplayRegionAddress`. A direct draw's fold is `DrawCommands::object_fold`, whose bytes -the consumer uploads (the record, and its pieces' commands where `draw` is indirect); an indirect -draw's arguments pass (`MeshArgumentsForm::FoldedObject`) writes the record, the pieces and their -commands, which `draw` (`DrawMeshTasksIndirectCount`) reads. Metal's threads per grid wrap to 32 -bits along each axis, as its builtins report them; a direct draw runs only the threadgroups those -threads fill, rounded up, an indirect one every threadgroup (`bind::metal_object_grid`). The -lowering takes a grid of up to `bind::METAL_OBJECT_GRID_TOTAL` (2^29) threadgroups on every device, -the most Metal's GPU ran within its watchdog's 5 seconds. A larger one, which Metal's GPU discards, draws nothing and -fails its command buffer with Metal's error (the runtime's `CommandBufferError::GpuRecoveryVictim`): -a direct draw says so in `DrawCommands::discards_command_buffer`, and the consumer fails the command -buffer from the draw's encoder on, as Metal does; an indirect draw's arguments pass sets -`StatusBits::MESH_GRID_DISCARDED` in the command buffer's `ExecutionStatus`. Where the device cannot -launch a grid Metal draws, the draw draws nothing and the command buffer fails with the runtime's -own error (`CommandBufferError::MeshGridPastLimits`, not Metal's): an indirect draw's object grid past -the task limits of a device that does not fold object grids, or a mesh grid past the mesh limits, -through `StatusBits::MESH_GRID_PAST_LIMITS`, or a fold of more pieces than -`MeshArguments::OBJECT_PIECES` (only under task limits below Vulkan's required least), its `past`. -A direct object grid past the task limits of a device that does not fold is refused naming the -limit. +`PushField::ReplayRegionAddress`, so a draw runs its grid in pieces within the task limits. Metal's +threads per grid wrap to 32 bits along each axis, as its builtins report them. The lowering takes +a grid of up to 2^29 threadgroups on every device, the most Metal's GPU ran within its watchdog's +5 seconds; Metal's GPU discards a larger one and fails its command buffer with Metal's error. ### Tile pipelines `Device::compile_tile_pipeline` compiles a `TileRenderPipelineDescriptor` (the tile function and the render pass's color attachment formats) into a `ComputePipeline` that stands in for -`dispatchThreadsPerTile:`. Dispatch it as `Dispatch::Threadgroups` over the render area, one -threadgroup per tile, with `BindState::imageblock_size` and `BindState::render_area` set, and bind -each attachment it reaches as a storage image where the plan writes `WriteSource::TileAttachment`. +`dispatchThreadsPerTile:`. Dispatch it as threadgroups over the render area, one threadgroup per +tile, and bind each attachment it reaches as a storage image at its `ResourceKind::TileAttachment` +binding. Its threads are numbered as Metal's tile dispatch numbers them, for every threadgroup of even sides up to 32x32 and the single thread; a threadgroup with an odd side, whose quads Metal leaves partly empty, is refused. A tile function runs on a single-sample pass: a multisample @@ -1062,7 +1037,7 @@ imageblock's operations (its sample count, the colors a pixel holds and their co store to the samples a coverage mask selects) are refused as not implemented (`Feature::Imageblocks`, naming the intrinsic). -## 5. The interface and the plan +## 5. The interface The pipeline states what it binds and how: @@ -1089,9 +1064,8 @@ for dependency in &pipeline.dependencies { 2^64. An access through the slot adds its 32-bit byte offset plus 2^31, modulo 2^32, zero-extended, to that word; a pointer compare, a pulled vertex fetch and an access from the word below it add the 2^31 back to read the address itself, and so does a slot pointer - converted to an integer or stored, which is the slot's address plus its offset. The binder - (`BindingPlan::instantiate_*`) of a device that compiles under the identity domains writes the - word so. A pointer loaded from memory (an argument buffer's pointer member, a `gpuAddress` the + converted to an integer or stored, which is the slot's address plus its offset. A runtime + writes the word so. A pointer loaded from memory (an argument buffer's pointer member, a `gpuAddress` the program stored) and a pointer made from an integer are the device address the word holds, unbiased and used directly, unchecked: there is no root table, no `PushField::RootTableAddress` and no search. A texture's or sampler's `SlotGuestBase` is its `gpuResourceID`, unbiased. A @@ -1118,8 +1092,8 @@ for dependency in &pipeline.dependencies { outside sits in the check's selection and runs nothing; an atomic's answer there is 0. Nil and a slot shorter than one access push a length that every such access past it fails. An access at a constant offset, and an access through a pointer loaded from memory or made from an integer, - is not checked. The binder writes `SlotBounds` from the bound buffer and refuses - `ZeroAddress` (`Unsupported{IdentityDomains}`): the zero range is the runtime's own memory. + is not checked. A runtime writes `SlotBounds` from the bound buffer; `ZeroAddress` is the + runtime's own memory. What the check costs, measured on the runtime against the same build with the check removed (release, no validation layer): in the compute harness's GPU time, `wide_bindings` 34.7% slower on a Radeon 780M (job m3-max-56485), 38.5% on an RTX 3090 (m3-max-56486) and 68% @@ -1138,17 +1112,16 @@ for dependency in &pipeline.dependencies { a storage texel buffer array declared without a format where it writes it, each needing the texel buffer kind's non-uniform indexing and update-after-bind features (a storage one also `shaderStorageImageWriteWithoutFormat`, and where it is read `shaderStorageImageReadWithoutFormat` - or, without it, the formats' own read bits, section 10). A planned heap's members are - textures with images, so only a heap set the consumer keeps for every command (each live - texture at its resource ID) holds texture buffers. Push constants carry the values the - binder writes per command. A stage that writes the command buffer's `ExecutionStatus` (a + or, without it, the formats' own read bits, section 10). A heap set the consumer keeps for + every command holds each live texture at its resource ID, texture buffers among them. Push + constants carry the values the runtime writes per command. A stage that writes the command + buffer's status (a `seq_cst` fence, an argument buffer's cubic sampler) reaches it by device address, a push hole, where the device addresses buffers (`bufferDeviceAddress` and `shaderInt64`), and through a set-0 storage buffer of its own (`SyntheticBinding::ExecutionStatus`) where it does not. That binding counts against the stage's storage-buffer limits: past one, an absent read or a fence is refused (`DescriptorCount`), and a stage that would bind it only to test its argument samplers for a - cubic filter binds nothing, so the plan refuses a cubic sampler listed beside it - (`SamplerBicubicFilter`). + cubic filter binds nothing. - A heap texture sampled through one of several constexpr samplers, the one a sampler handle names at run time (a table of constexpr samplers read at a computed index), samples once through a set-0 array of those samplers (`ResourceKind::SamplerArray`, `BindingSource::SamplerArray`), @@ -1187,8 +1160,8 @@ for dependency in &pipeline.dependencies { (`OpArrayLength`). - `dependencies` lists the bind-time state the pipeline depends on (`RuntimeFact`: threadgroup sizes, sampler coordinate modes, buffer ranges, ...) and how this profile honors each - (`Mechanism`: a specialization constant, a push field, a plan-time check, a variant). The plan - acts on them; you do not have to. + (`Mechanism`: a specialization constant, a push field, a plan-time check, a variant), which a + runtime honors at each draw or dispatch. - The format class of a bound texture is read by the shader as push data, not specialized, so binds that differ only in their textures' formats share one `VkPipeline`. On MoltenVK a slot read with a `half` result also specializes one bit of it: whether the class converts its texels to `half` by @@ -1197,77 +1170,18 @@ for dependency in &pipeline.dependencies { takes two pipelines. Other bound values (a slot's presence, a sampler's word) are specialization constants. A buffer slot's storage view reads at its residual, its range from the buffer's start, so the bytes before a bind offset stay reachable. -- A bound buffer's length enters its shape only as a length class (`bind::length_class`), which a - plan compares with the device's `maxStorageBufferRange` alone (whether every range of the - buffer fits it). Set each table's `buffer_ranges = BufferRanges::of(limits)` and its shape tells - apart only the classes that limit tells apart (`BufferRanges::length_class`: a class rounded up - to the greatest one that fits the same limit), so commands over buffers of many sizes keep one - shape and one plan: on a device whose limit is 4 GiB, every buffer below 4 GiB. The default - tells every class apart. The runtime binds through no stage table; the validation executor sets - it on every table it builds, from its profile's limits. -- A two-plane YCbCr texture whose planes a function may read in place states them in its facts - (`TextureFacts::ycbcr_in_place`, a `YCbCrInPlace` of its planes). A slot whose function only samples it (nearest or linear, no comparison, - anisotropy or `min_lod_clamp`), gathers it or reads its size (`RuntimeFact::YCbCrInPlace`) takes the - pipeline's in-place variant (`VariantKey::ycbcr_in_place`): the slot binds a uniform texel buffer - over the planes' bytes (`WriteSource::YCbCrInPlace`, in `YCbCrInPlace::format`), its push field - (`PushField::YCbCrInPlace`) holds `YCbCrInPlace::words`, and the function converts and filters - the codes as Metal does, exactly (a gather Metal's taps of them). Any other slot, and any texture without the fact, binds the - texture's image of converted texels. Where the consumer also holds the planes as a linear image - of their multi-planar 4:2:0 format over their bytes, which the device's sampler Y′CbCr - conversion reads with Metal's reconstruction, it states so (`YCbCrInPlace::with_planes_image`, - its conversion `YCbCrInPlace::sampler`, a `YCbCrPlanesSampler`). A slot whose every sample the - device's sampler takes (the fact's `device`: no border address mode, no texel offset placed by a - parent's size, no gather; a runtime sampler's word without a border mode) then takes the planes variant - (`VariantKey::ycbcr_planes_sampled`): the slot is a combined image sampler of the image - (`ResourceKind::YCbCrPlanes`, `BindingSource::YCbCrPlanes`, written from - `WriteSource::YCbCrPlanesImage`) whose immutable sampler is `SamplerDesc::ycbcr` of the - conversion. The consumer chains its `VkSamplerYcbcrConversionInfo` into that sampler and makes - the image's view with an identically defined conversion, and sizes a pool for the format's - `combinedImageSamplerDescriptorCount` descriptors at the binding. Each sample is the device's, - at level 0, its conversion and filter of the codes rather than Metal's. -- A 2D texture whose image is a shadow but whose bytes the consumer reads and writes in place - states its rows in its facts (`TextureFacts::texel_rows`, a `TexelRows`: its width, height, the - texels from one row's first to the next's, and its first texel in a texel buffer view of its - bytes; the runtime states one for a shadow over host pages whose image the device refused, not - one its policy asks for). A slot whose function only reads, writes or asks the size of it (no - sample, gather, atomic, read through a sampler, level views, switch at use or residency; - `RuntimeFact::TexelRows`) takes the pipeline's rows variant (`VariantKey::texel_rows`) where - the device views the texture's format as a texel buffer of the slot's kind (uniform where the - slot's declaration only reads, storage otherwise, read and written without a declared format): - the slot binds a texel buffer of the format over the rows' bytes (`WriteSource::TexelRows`, - from the view's first texel through the last row's last; a use of class `AccessClass::TexelRows` - of those bytes), its push field (`PushField::TexelRows`) holds `TexelRows::words`, and the - function addresses texel `(x, y)` at `first + y · row + x`, testing every read and write against - the texture's size itself (a coordinate past the width names the next row's texel in the view): - a read outside is Metal's out-of-bounds texel and a write there is dropped, and a size query - answers the field's size and one level. A texel buffer's texels go through the device's format - conversion as an image's do, so the reads and writes are the image route's, bit for bit (the - runtime's `texel_rows_device` tests compare every `RGBA8Unorm` and `RGBA16Float` code), and no - precision note is recorded. Any other slot, and any texture without the fact, binds the image. -- A texture buffer of more texels than the device's `maxTexelBufferElements` (Metal makes them up - to 2^28 texels on every Mac; one texel buffer view holds 2^27 on ANV and lavapipe and 2^26 on - MoltenVK) is bound through views of its parts. State with its binding the views its texels take - (`BoundTexture::Buffer::parts`: 1 within the limit, which binds one view as before and keeps - the pipeline and its key, else `⌈texels / P⌉` parts of `P` texels). Each part but the last holds - `P = bind::part_texels(limits)` texels, the limit rounded down to a multiple of - `minTexelBufferOffsetAlignment`, so every part starts on that alignment where the texture buffer - does; the last holds the rest. A slot whose function only reads (not through a sampler), writes, - updates by an atomic or asks the width of the texture buffer, on a device that indexes an array - of the slot's kind of texel buffer by a `NonUniform` value (`RuntimeFact::TexelBufferParts`), - takes the pipeline's parts variant (`VariantKey::texel_buffer_parts`) where the shape binds more - than one part there: the slot is an array of the parts' texel buffers, one `WriteSource::TexelBuffer` - per array element, each element's view the bytes of the instance's `DescriptorRange` at that - `element`. The function reads texel `i` as texel `i - k · P` of part `k = min(⌊i / P⌋, parts - 1)`; - a texel past the last lies past the last part's end, so its read is Metal's out-of-bounds texel - and its write is dropped, as through one view, and the width is `(parts - 1) · P` plus the last - part's. Each part is the device's own view in the format one view takes, so a read converts its - texel as that view does, and no precision note is recorded. Still refused with - `BindError::TexelBufferTooLarge`: a slot that reads the texture buffer through a sampler, a device - without `shaderUniformTexelBufferArrayNonUniformIndexing` (or - `shaderStorageTexelBufferArrayNonUniformIndexing` for a slot that writes), and a format whose - block holds several texels; parts past a stage's sampled or storage image descriptors are the - link's descriptor-count refusal. A texture buffer past the limit in an argument buffer is the - heap class's neutral. +- A texture-buffer slot compiled under `LoweringInputs::texel_buffer_parts` (its function only + reads the texture buffer, not through a sampler, writes it, updates it by an atomic or asks its + width, on a device that indexes an array of the slot's kind of texel buffer by a `NonUniform` + value: `RuntimeFact::TexelBufferParts`) is an array of that many texel buffers, each part but + the last of `P` texels, the device's `maxTexelBufferElements` rounded down to a multiple of + `minTexelBufferOffsetAlignment`. The function reads texel `i` as texel `i - k · P` of part + `k = min(⌊i / P⌋, parts - 1)`; a texel past the last lies past the last part's end, so its + read is Metal's out-of-bounds texel and its write is dropped, as through one view, and the + width is `(parts - 1) · P` plus the last part's. Each part is the device's own view in the + format one view takes, so a read converts its texel as that view does, and no precision note + is recorded. The runtime binds a texture buffer as one view and refuses a width past the limit + (`Limit::TextureSize`). - `interface.reaches_command_buffers` and `interface.texture_writing_stages` say, provably, which pipelines may touch an indirect command buffer and which stages may write a texture. `interface.command_writes` (`CommandWrites`) says what its functions may write into the @@ -1292,49 +1206,13 @@ for dependency in &pipeline.dependencies { a resource ID), or an intersection or a call the function cannot see into. A runtime that gives some textures no storage image needs it to find such an access to one. -### Plans +### Binding -Per draw or dispatch, describe what is bound, keyed by Metal slot, as a `BindState`. The binder -never sees your resources, only facts about them: - -```rust -let mut table = StageTable::default(); -table.buffers.insert(0, buffer(4096, 0)); -let facts = TextureFacts::new(TextureType::Type2D, PixelFormat::RGBA8Unorm); -let texture = BoundTexture::Texture { - facts, - resource_id: None, -}; -table.textures.insert(0, texture); -let sampler = BoundSampler::new(SamplerDescriptor::new()); -table.samplers.insert(0, sampler); -let mut state = BindState::default(); -state.stages.insert(Stage::Kernel, table); - -let plan = pipeline.plan(&device, &state.shape())?; -assert!(plan.variant.is_empty(), "this shape needs no other variant"); -``` - -`state.shape()` keeps only what can change a plan (which slots are bound with what kind of -resource, formats, level counts, sampler modes, alignment classes). A plan is a pure function of the -pipeline, the device and the shape: memoize it on `(PipelineKey, BindShape)`. - -The plan holds one `DescriptorWrite` per layout binding element (the resource at a slot, a buffer -the binder synthesizes, or a neutral resource where nothing compatible is bound), the vertex -buffers, and the `ResourceUse`s that drive staging, writeback and barriers. List in the state -every live sampler state and visible-function table the command can reach through argument buffers -(`argument_samplers`, function tables), and the resources it uses (`used_resources`). A consumer -that lists those in token order says so (`used_in_token_order`), and one that points every root -table at a resident set it uploads apart, holding them and the ranges it lists -(`resident_ranges`), says that (`resident_apart`): a command's -instantiation then costs its own bindings and heap members, not every resource the state lists. - -A plan whose `variant` is not empty asks for another variant of the pipeline (a storage texture's -format, a buffer range past the descriptor limit, a vertex buffer that fixed-function input cannot -fetch, ...). A render pipeline compiles under no variant (`Device::compile_render_pipeline`); a -kernel compiles with `plan.variant.lowering_inputs(Stage::Kernel)`, linked as -`StageSource::Compiled`, and is planned for the same shape. A dispatch can -ask too (`plan.dispatch_variant(&dispatch)`, or `BindError::NeedsVariant` from instantiation). +The translator plans no binding and calls no Vulkan to bind. A runtime binds each pipeline from +what it states: its layout's bindings by Metal slot (`ResourceSlot`, set 0 densely in that order +and set 1's heap arrays), the push fields its stages read (`PushField`), its specialization +constants (`SpecKey`), and its `dependencies`. The runtime crate, `metal2vulkan-runtime`, is that +runtime on every device; its README states what it binds, pushes and refuses. Textures follow Metal's texel rules: sparse textures report residency where the device can, `Depth32Float` texels are the device's depth image's (a value it clamps or a denormal it flushes is @@ -1342,8 +1220,7 @@ the device's, `PrecisionNote::DepthDenormals`), a `ulong` texture is an `RG32` u whose two words the function joins and splits (its atomics are refused, `ImageAtomics`), and `half` and sRGB reads give Metal's values or record their bound (an sRGB texel is the device's own decode wherever the device samples its format, -`srgb-texel-decode`). The -rustdoc of `BindState`, `TextureFacts` and `BindingPlan` states each rule. A read's, sample's or +`srgb-texel-decode`). A read's, sample's or gather's `{T, i8}` result (the texel and its residency word) may pass through phis, selects, freezes and member insertions and extractions, Apple's GL code generator's swizzled read among them. A function whose effects depend on a bit of the word other than bit 0 (`resident()`'s), or @@ -1352,87 +1229,26 @@ establishes no other bit. ## 6. At bind time -Instantiate the plan per dispatch or draw: - -```rust -let dispatch = Dispatch::Threads { - threads: [100, 1, 1], - threads_per_group: [32, 1, 1], -}; -let commands = plan.instantiate_dispatch(&state, &dispatch)?; -for region in &commands.regions { -// ... -println!(" descriptor ranges: {:?}", commands.descriptor_ranges); -println!(" push holes: {:?}", commands.push_holes); -``` - -```rust -let plan = pipeline.plan(device, &state.shape())?; -let draw = DrawCall::Primitives { - vertex_start: 0, - vertex_count: 6, - instance_count: 1, - base_instance: 0, -}; -let commands = plan.instantiate_draw(&state, &draw)?; -``` - -A buffer slot read through a storage view of its whole window (a `device` pointer the function -indexes) takes the descriptor range from the start of the bound buffer's space to its end padded -to 16 bytes, whatever its bind offset, which its `SlotBindOffset` push field holds: draws and -dispatches that bind one buffer at other offsets write the same descriptors, and only push data -differs. Where that range would pass the view's `maxStorageBufferRange` or 4 GiB, or the offset -lies at or past the padded end, the range starts at the bind offset aligned down to the -descriptor base alignment. An access that reaches back before the bind offset, inside the buffer, -reads the buffer's bytes there, as Metal's does. - -A slot of a bounded window read at its residual (a storage view's) takes a range its bind offsets -share in the same way: the buffer from 0 to its padded end where that fits the view's maximum -range (`maxStorageBufferRange`; a texel form's is `maxTexelBufferElements` texels) and 4 GiB, -else the block of half that -maximum (rounded down to a power of two) its window starts in, to the maximum past the block's -start. A window of at most half the maximum starting in a block ends inside its block's range; a -longer one, or one at or past the padded end, takes the range from its bind offset, as every -other descriptor-form slot does. So draws that move such a slot's offset along one buffer (a -consumer's staged `setVertexBytes`, a constant reference bound at the next offset of an upload -chunk) write the same descriptor, keep set 0 and push only the slot's `SlotBindOffset`. Each read -inside the window reads the bytes it read before; one outside it, which Metal leaves undefined, -reads the buffer's bytes inside the range. - -`instantiate_draw_into` writes the same commands over a `DrawCommands` you keep, in the storage -its vectors already hold: keep one from draw to draw (`DrawCommands::default()` to start) and the -draws allocate none of it again once it holds as much. `instantiate_dispatch_into` does the same -for a compute dispatch over a `DispatchCommands` you keep (one `instantiate_dispatch` made, to -start): each region's specialization and push bytes, and the argument table's, are written in the -storage the commands before held. - -A plan that reads handles (a texture's or sampler state's resource ID, a visible function table's) -writes heap tables among its descriptor bytes, after the stage tables: its handle tables, sampler -tables and function-table directories. Their bytes grow with the resources the state lists as -used and the textures its slots bind that a handle names, and they depend on nothing else of the -state but its argument samplers, function tables and heap placement. - -A dispatch is one or more regions (a grid that is not whole threadgroups adds edge regions), each -with its group count, specialization and push constants: create one `VkPipeline` per distinct -specialization. The plan of a kernel's partial-threadgroups variant (`VariantKey::partial_threadgroups`, -which `LoweringInputs::partial_threadgroups` compiles) runs such a grid as the threadgroups its -threads fill at the dispatch's threadgroup size instead, the last along an axis Metal's partial -threadgroup, so every remainder takes the same `VkPipeline`; a kernel the variant cannot run -exactly (a tile function, a stage-input region, compute derivatives, emulated simdgroups) is -refused it, `Unsupported{PartialThreadgroups, NotImplemented}`, and keeps the edges. On -the identity domains the variant of a kernel that does not -observe its threadgroup partition (`KernelFacts::partition_oblivious`) runs its grid in tiles -instead (`RuntimeFact::GridTiles`): its plans run a direct dispatch's threads in -`pipeline::grid_tile`'s tiles, one workgroup of `pipeline::GRID_TILE_THREADS` each with the tile -as the region's nominal size (`MultiRegion` 1), the region flagged `NONUNIFORM` where the tile -does not divide the grid, and a range of threadgroups at its own size (`MultiRegion` 0); the -kernel runs the same positions with the same answers: where the region is flagged `NONUNIFORM`, -every invocation compares its position with the region's grid and one past it returns before the -body, a test inside one branch on the flag; an unflagged region runs no such test, so a runtime -flags every region of a grid its workgroups do not divide. At `MultiRegion` 0 a runtime may run a -direct dispatch of the variant in workgroups of a size it picks, flagged where they do not divide -the grid, whose invocations past it return before the body as a tile's do; an indirect dispatch's -region states no grid and is unflagged, and all of its invocations run. +A kernel's dispatch runs as one or more regions, each a group count with its specialization and +push constants, and each distinct specialization is one `VkPipeline`. A kernel's +partial-threadgroups variant (`LoweringInputs::partial_threadgroups`) runs a grid that is not +whole threadgroups as the threadgroups its threads fill at the dispatch's threadgroup size, the +last along an axis Metal's partial threadgroup, so every remainder takes the same `VkPipeline`; a +kernel the variant cannot run exactly (a tile function, a stage-input region, compute +derivatives, emulated simdgroups) is refused it, `Unsupported{PartialThreadgroups, +NotImplemented}`. On the identity domains the variant of a kernel that does not observe its +threadgroup partition (`KernelFacts::partition_oblivious`) runs its grid in tiles instead +(`RuntimeFact::GridTiles`): a direct dispatch's threads run in `pipeline::grid_tile`'s tiles, one +workgroup of `pipeline::GRID_TILE_THREADS` each with the tile as the region's nominal size +(`MultiRegion` 1), the region flagged `NONUNIFORM` where the tile does not divide the grid, and a +range of threadgroups at its own size (`MultiRegion` 0); the kernel runs the same positions with +the same answers: where the region is flagged `NONUNIFORM`, every invocation compares its +position with the region's grid and one past it returns before the body, a test inside one +branch on the flag; an unflagged region runs no such test, so a runtime flags every region of a +grid its workgroups do not divide. At `MultiRegion` 0 a runtime may run a direct dispatch of the +variant in workgroups of a size it picks, flagged where they do not divide the grid, whose +invocations past it return before the body as a tile's do; an indirect dispatch's region states +no grid and is unflagged, and all of its invocations run. `Device::kernel_observes_partition(&kernel, &inputs, &budget, &entries)` answers, before any lowering, what `CompiledFunction::observes_threadgroup_partition` answers for the compile under the same inputs (from the specialized entry `entries` holds, ordered for the device where its @@ -1440,61 +1256,16 @@ profile takes the lockstep order), so a runtime lowers only the variant a creati `CompiledFunction::is_image_only` (`KernelFacts::image_only`) states, from the AIR alone, a kernel that samples, gathers or reads a texture and loads, stores and updates atomically nothing through a `device` pointer (`constant` loads and texture writes allowed), which a runtime may run in -square workgroups. On -that plan a grid of whole threadgroups, of `Threads` or `Threadgroups`, takes the same regions -unflagged (each `MultiRegion` 1, every thread live), so one `VkPipeline` of a threadgroup size runs -all of a kernel's direct dispatches. The runtime lowers a kernel that does not observe its -partition once, as that variant, and runs every direct dispatch of it in its tiles; a kernel that -observes its partition runs every dispatch, a whole grid, threadgroups, an indirect dispatch or -a `dispatchThreads` grid that is not a whole number of threadgroups, on its partial-threadgroups -variant at its own threadgroup size, where the variant takes the dispatch's threadgroup memory -(the variant's predicated walk may add a vote word); an indirect dispatch states no grid in its region and takes -the single-region form, unflagged. A kernel -that steps a stage-in attribute by thread position, or reads `[[grid_origin]]` or `[[grid_size]]`, -needs the encoder's stage-in region: - -```rust -match plan.instantiate_dispatch(&state, &dispatch) { - Err(BindError::MissingStageInRegion) => {} -// ... -state.stage_in_region = Some(StageInRegion::new([0, 0, 0], [64, 1, 1])); -let commands = plan.instantiate_dispatch(&state, &dispatch)?; -``` - -A tessellation pipeline draws patches, with the factors' buffer in the state: - -```rust -let factors = TessellationFactorBuffer::new(4096, 0, 0); -state.tessellation_factors = TessellationFactors::new(Some(factors), 1.0); -let plan = pipeline.plan(device, &state.shape())?; -let draw = DrawCall::Patches { - control_points: 4, - patch_start: 0, - patch_count: 16, - patch_index: None, - instance_count: 1, - base_instance: 0, - control_point_index: None, -}; -let commands = plan.instantiate_draw(&state, &draw)?; -``` - -What you record from `DispatchCommands` or `DrawCommands`: - -- **Descriptors.** Write each of the plan's `descriptors`, binding each buffer descriptor over - exactly its `descriptor_ranges` entry. Upload `descriptor_bytes` (argument and handle tables) and - the resident root tables where present. A handle table maps each resident resource's - `gpuResourceID` to its heap element; a consumer that keeps one heap for every command buffer can - bind one table of every texture ID instead (`bind::handle_entry`), as the runtime does. -- **Push constants.** Write `push_constants`, and fill each of the `push_holes` with the device - address it names: the uploaded root table, the command buffer's `ExecutionStatus` buffer, an - indirect command buffer's records. -- **The dispatch or draw.** Record `regions` or `draw` as given: the binder has already applied - Metal's offsets, bases and clamps. -- **Status.** Per command buffer, keep one `ExecutionStatus` buffer for what translated shaders - report (a resident-set miss, for one), and read it when the command buffer completes. A plan - binds it as `WriteSource::ExecutionStatus` on a device that does not address buffers: bind the - same buffer there, its `ExecutionStatus::BYTES` bytes. +square workgroups. On that variant a grid of whole threadgroups, of `dispatchThreads` or +`dispatchThreadgroups`, takes the same regions unflagged (each `MultiRegion` 1, every thread +live), so one `VkPipeline` of a threadgroup size runs all of a kernel's direct dispatches. The +runtime lowers a kernel that does not observe its partition once, as that variant, and runs every +direct dispatch of it in its tiles; a kernel that observes its partition runs every dispatch, a +whole grid, threadgroups, an indirect dispatch or a `dispatchThreads` grid that is not a whole +number of threadgroups, on its partial-threadgroups variant at its own threadgroup size, where the +variant takes the dispatch's threadgroup memory (the variant's predicated walk may add a vote +word); an indirect dispatch states no grid in its region and takes the single-region form, +unflagged. ### Levels a slot reads @@ -1519,8 +1290,7 @@ The translator replays no records. For a consumer that replays them, a render pi as its replay variant (`VariantKey::replay_bindings`), whose vertex and fragment functions read each command's buffers from slot tables in memory, and as its merged variant (`VariantKey::merged_draws`), whose vertex function finds its command in one merged draw by a -prefix of the commands' first vertices (`bind::DRAW_ARGUMENT_BYTES`, -`bind::DRAW_INDEX_ENTRY_BYTES`, `bind::MERGED_REST_FIRST`) and runs the command's vertex, +prefix of the commands' first vertices and runs the command's vertex, instance and buffers, in the commands' order. A buffer's records start at `bind::indirect_commands::records_address` of its ID, outside every Metal address; records may run past later IDs' starts, and a resident set keeps each records range whole. Storage may hold a written flag per command, @@ -1580,8 +1350,7 @@ assert_eq!(linked, pipeline); the descriptor past the fetch -- its layout agreement, its reflection, and `compute_pipeline_key` -- reads it whole. - A key names an artifact by its inputs and versions; a content digest names it by what it says. - `pipeline.content_digest()` hashes everything but the key and profile, and `plan.content_digest()` - (with `serde`) everything a plan states. A cache of driver objects keyed on the digest survives a + `pipeline.content_digest()` hashes everything but the key and profile. A cache of driver objects keyed on the digest survives a release that bumped `SEMANTICS_VERSION` without changing the output. A digest identifies content; it authenticates nothing. - A compiled function keeps its last relocation beside it, so a sweep of pipeline states over @@ -1602,7 +1371,7 @@ Every failure is typed; match variants, never messages. A refusal says what woul answer: ```rust -let floor = committed_device("runtime-floor")?; +let floor = runtime_device("runtime-floor")?; let min_lod = FunctionDescriptor::new(sampling.function("sample_min_lod")?); match floor.compile_function(&min_lod, &LoweringInputs::new(), &Budget::standard()) { Err(Error::Unsupported(refusal)) => match (&refusal.feature, &refusal.needs) { @@ -1643,12 +1412,9 @@ compiles, as plain Metal's does (section 10, "Function constants"). A storage texture's format (`RuntimeInput::StorageTextureFormat { slot }`) comes from what is bound: `metal::format::storage_image_choice(pixel_format, device.profile())`, placed in a -`VariantKey`'s `storage_images` and compiled as a variant. The plan asks for it itself where the -bound format needs a declared format. +`VariantKey`'s `storage_images` and compiled as a variant. -**What to cache.** `error.retry()` says whether the same request can succeed later. A -`BindError` from `plan` depends only on the pipeline, the device and the shape, so it -memoizes beside the plan; one from instantiation does not. +**What to cache.** `error.retry()` says whether the same request can succeed later. **Where a refusal comes from.** `error.basis()` (a `RefusalBasis`) says where the belief that the input must be refused comes from: a refusal's follows from its `needs` (`Device` for what a @@ -1662,8 +1428,9 @@ runtime's `Error::basis` answers a translation error so. whether subgroup reconvergence after divergence matches Metal's (`Reconvergence::ImplementationDefined` where the profile lacks maximal reconvergence). A note that holds only under some bound values is in `specialized_notes`; -`stage.precision_notes_bound(&plan.specialization, &|key| plan.specialized_value(key))` gives the -notes a plan reaches. Section 9 lists every note. +`stage.precision_notes_bound(&specialization, &|key| bound(key))` gives the notes a pipeline +created under `specialization` reaches where a draw or dispatch binds the values `bound` gives. +Section 9 lists every note. **The runtime's errors** are its own type, `metal2vulkan_runtime::Error`; @@ -2074,11 +1841,6 @@ bound. texel's sample past `±65504`, the infinity where Metal saturates. Recorded outright for every such access, a heap element's and a depth texture's included: the device's `float` texel is its own. -- `metal2vulkan-degrade-half-sample-filter` (precision). `PrecisionNote::HalfSampleFilter`: The - module samples a texture with a `half` result through a filter (linear minification or - magnification, a linear mip filter, anisotropy, or a runtime sampler slot whose bound sampler - filters so) by Vulkan's Y′CbCr model of a 4:2:0 two-plane YCbCr texture's planes read in place, - which blends the codes, not Metal's exact filter of the format, on every device. - `metal2vulkan-degrade-srgb-texel-decode` (precision). `PrecisionNote::SrgbTexelDecode`: The module reads, samples, or gathers a texture with a `half` or `float` result through the device's sRGB decode, or decodes the device's filter of its codes, where the texture may be bound in an 8-bit @@ -2091,10 +1853,6 @@ bound. alias (at a slot, or held by an argument buffer), the module decodes the codes (or the device's filter of them) by the MSL transfer through the device's `Pow`, at every such access on every device. -- `metal2vulkan-degrade-float-sample-filter` (precision). `PrecisionNote::FloatSampleFilter`: The - module samples a texture with a `float` result through a filter by Vulkan's Y′CbCr model of a - 4:2:0 two-plane YCbCr texture's planes read in place, which blends the codes, not Metal's exact - filter of the format, on every device. - `metal2vulkan-degrade-function-storage-assumed` (precision). `PrecisionNote::FunctionStorageAssumed`: A vertex or fragment function keeps more private memory (its `alloca`s, a call stack among them, or constants held as `Private` variables) than the floor, @@ -2559,8 +2317,8 @@ bound. (`BGR10_XR`, `BGRA10_XR`, `R10Unorm_X6`, `RG10Unorm_X12` and the bfloat formats), whose `float` read, sample or gather through an argument buffer the function decodes the same way: such a stage records the note as a specialized note, holding - where a texture its handles can name is one (`SpecKey::HeapRawTextures`, which the binding plan - gives from the textures the command makes resident or binds), so a reading of the module alone + where a texture its handles can name is one (`SpecKey::HeapRawTextures`, which a runtime gives + from the textures the command makes resident or binds), so a reading of the module alone holds it, and so does a command that can name one. - `metal2vulkan-degrade-device-fragment-runs` (precision). `PrecisionNote::DeviceFragmentRuns`: A fragment function that writes memory (`StageInterface::writes_memory`) in a render pipeline of diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 5ce6e4066..7dbffd69c 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -38,8 +38,6 @@ metallib | AIR bitcode band ── relocate ────► the final words of each stage pipeline::relocate = ComputePipeline | RenderPipeline | tile and mesh pipelines - -BindState ── shape ──► BindingPlan (per pipeline and shape) ── instantiate ──► dispatch or draw commands bind ``` `pipeline::compile::compile_stage` runs one function from decode to serialize and keeps only the @@ -83,7 +81,7 @@ rest is `crates/metal2vulkan/src/`. | `library/` | `Library`, `Function`, `CompiledFunction`, `FunctionCompileKey` | | `reflection/` | Metal-shaped reflection of functions and pipelines | | `pipeline/` | Descriptors, compile entry points, link and relocate, `PipelineInterface`, the pipeline layout, vertex input and fixed-function state, runtime facts, precision notes | -| `bind/` | The binder: `BindState` and `BindShape`, `BindingPlan`, per-command instantiation, neutral resources, argument, handle and heap tables, residency, indirect-command replay, and the helper kernels the runtime records. It never calls Vulkan | +| `bind/` | What a runtime computes beside the compile: argument-buffer layouts, the ASTC, ETC and PVRTC decoders, rasterization-rate maps, indirect-command records, Metal's draw and dispatch calls, and the heap classes, status words and device-replay tables the lowering reads. It never calls Vulkan | | `cache/` | `PipelineKey`, `SEMANTICS_VERSION`, the artifact encoding | | `metal/`, `vk/`, `ash_interop/` | Metal's enums and format facts; plain-data Vulkan values; `ash` conversions (feature `ash`) | | `error/` | The typed errors every entry point returns | diff --git a/docs/HOWTO.md b/docs/HOWTO.md index 162d058d0..7543a2bfe 100644 --- a/docs/HOWTO.md +++ b/docs/HOWTO.md @@ -33,10 +33,10 @@ walks the flow in the order a consumer meets it: 2. [A library](API.md#2-a-library): parse a metallib or AIR bitcode. 3. [A compute pipeline](API.md#3-a-compute-pipeline) or [a render pipeline](API.md#4-a-render-pipeline), under a `Budget`. -4. [The interface and the plan](API.md#5-the-interface-and-the-plan): the layout, what each slot - binds, what a dispatch or draw needs. -5. [At bind time](API.md#6-at-bind-time): descriptor writes and push-constant bytes from what is - bound. +4. [The interface](API.md#5-the-interface): the layout, what each slot binds, what a dispatch or + draw needs. +5. [At bind time](API.md#6-at-bind-time): a dispatch's regions, the levels a slot reads, and + indirect command buffers. Every `air.simd_*` operation keeps Metal's 32-lane simdgroup; there is no option to use the driver's subgroup width instead. diff --git a/docs/REFUSALS.md b/docs/REFUSALS.md index db2e972ee..281bf9d86 100644 --- a/docs/REFUSALS.md +++ b/docs/REFUSALS.md @@ -1,6 +1,6 @@ # The refusal surface -Every refusal of something Metal accepts, read from the code: the construction sites of the typed refusals outside tests (`scripts/refusal-surface/refusal_surface.py`, which writes this file; edit its `reach.tsv` and the refusals' own doc comments, never the tables). Section 6 is the runtime's floor: a device below it is refused when the device is made, with every item it lacks named. The sections after it are the runtime's own typed refusals, one for each enum its `Error` carries, every row with its declared basis, which the runtime answers at run time too, by `Error::basis`. Malformed input of no Metal call at all is misuse and is not listed. [`METAL-COVERAGE.md`](METAL-COVERAGE.md) lists the Metal API the runtime has no counterpart for at all. +Every refusal of something Metal accepts, read from the code: the construction sites of the typed refusals outside tests (`scripts/refusal-surface/refusal_surface.py`, which writes this file; edit its `reach.tsv` and the refusals' own doc comments, never the tables). Section 5 is the runtime's floor: a device below it is refused when the device is made, with every item it lacks named. The sections after it are the runtime's own typed refusals, one for each enum its `Error` carries, every row with its declared basis, which the runtime answers at run time too, by `Error::basis`. Malformed input of no Metal call at all is misuse and is not listed. [`METAL-COVERAGE.md`](METAL-COVERAGE.md) lists the Metal API the runtime has no counterpart for at all. Columns: @@ -20,14 +20,13 @@ Columns: - `rare`: public API, but specialized: few apps reach it; - `none`: no public API path: malformed or non-Metal input, Apple-private calls, or a cap no valid program of ordinary size meets; - `?`: not assessed yet. - The floor (section 6) carries no reach mark, as it turns on the device whatever the program, and nor do the runtime's refusals after it, each an argument of a public call. + The floor (section 5) carries no reach mark, as it turns on the device whatever the program, and nor do the runtime's refusals after it, each an argument of a public call. ## Totals | Kind | Variants | With a site | Reach system | Reach app | Reach rare | Reach none | Unassessed | |---|---|---|---|---|---|---|---| -| Translator and front-end refusals | 119 | 119 | 6 | 27 | 66 | 20 | 0 | -| Binder refusals at a device limit | 8 | 8 | 0 | 1 | 6 | 1 | 0 | +| Translator and front-end refusals | 119 | 114 | 6 | 27 | 66 | 20 | 0 | | Translation caps | 14 | 14 | 0 | 0 | 7 | 7 | 0 | | Rate maps the compile layer does not compile | 5 | 5 | 0 | 0 | 4 | 1 | 0 | | The translation deadline | 1 | 1 | 0 | 0 | 0 | 1 | 0 | @@ -40,8 +39,7 @@ Columns: | Kind | `metal-measured` | `metal-documented` | `metal-takes` | `device` | `ours` | `unknown` | `delegated` | `-` | |---|---|---|---|---|---|---|---|---| -| Translator and front-end refusals | 0 | 0 | 0 | 48 | 71 | 0 | 0 | 0 | -| Binder refusals at a device limit | 0 | 0 | 0 | 8 | 0 | 0 | 0 | 0 | +| Translator and front-end refusals | 0 | 0 | 0 | 44 | 70 | 0 | 0 | 5 | | Translation caps | 0 | 0 | 0 | 0 | 14 | 0 | 0 | 0 | | Rate maps the compile layer does not compile | 0 | 0 | 0 | 0 | 5 | 0 | 0 | 0 | | The translation deadline | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | @@ -65,36 +63,36 @@ Columns: | `AgxUnmodeled` | An AGX intrinsic whose semantics are not modeled | every device (not implemented) | `ours` | 1: `crates/metal2vulkan/src/lower/simd/agx.rs (unmodeled)` | `rare`: Apple's own libraries' AGX intrinsics | | `StaticInitializer` | A static initializer that cannot be evaluated | every device (not implemented) | `ours` | 1: `crates/metal2vulkan-air/src/error.rs (from)` | `none`: LLVM initializers AIR does not emit | | `Recursion` | Recursion (one variant) | every device (not implemented) | `ours` | 4: `crates/metal2vulkan-air/src/canon/mod.rs (recursion, 2 sites)`, `crates/metal2vulkan-air/src/canon/recursion.rs (dynamic_alloca)` (+1) | `rare`: recursion through visible functions | -| `DynamicCall` | Indirect calls, function pointers, visible/intersection function tables (one variant) | every device (no Vulkan mechanism); every device (not implemented) | `ours` | 9: `crates/metal2vulkan-air/src/canon/devirt.rs (record)`, `crates/metal2vulkan-air/src/canon/devirt.rs (site)` (+5) | `rare`: function pointers and function tables | +| `DynamicCall` | Indirect calls, function pointers, visible/intersection function tables (one variant) | every device (not implemented) | `ours` | 6: `crates/metal2vulkan-air/src/canon/devirt.rs (record)`, `crates/metal2vulkan-air/src/canon/devirt.rs (site)` (+4) | `rare`: function pointers and function tables | | `InlineAsm` | A call to inline assembly (`asm`) that an entry reaches, other than the empty `asm sideeffect "", ""` decode drops | every device (not implemented) | `ours` | 1: `crates/metal2vulkan-air/src/canon/mod.rs (post_check)` | `none`: inline assembly other than the empty asm("") decode drops, which MSL refuses to compile | | `Linking` | Linkage signatures / stitching / dynamic libraries | every device (not implemented) | `ours` | 3: `crates/metal2vulkan-air/src/canon/link.rs (not_implemented)`, `crates/metal2vulkan-air/src/canon/mod.rs (post_check)` (+1) | `rare`: dynamic libraries and linked functions | | `SimdWidth` | Simdgroup width 32 is not achievable for this usage, stage, and device | devices without a capability the site computes (`subgroup::width_needs(cx.stage, model.stage(cx.stage))`); devices without a capability the site computes (`width_needs(stage, st)`) | `device` | 2: `crates/metal2vulkan/src/device/subgroup.rs (subgroup_tier)`, `crates/metal2vulkan/src/lower/simd/mod.rs (finish)` | `app`: simdgroup functions on a device whose subgroups cannot run 32 wide for the use | -| `LocalSize` | A local size beyond a device limit on this axis (`None` | every device (no Vulkan mechanism) | `device` | 1: `crates/metal2vulkan/src/bind/dispatch.rs (regions)` | `app`: a threadgroup size past a smaller device's limit | +| `LocalSize` | A local size beyond a device limit on this axis (`None` | - | `-` | 0 | `app`: a threadgroup size past a smaller device's limit | | `PartialThreadgroups` | A kernel's partial-threadgroups variant (`LoweringInputs::partial_threadgroups`) that the lowering cannot make | every device (not implemented) | `ours` | 4: `crates/metal2vulkan/src/lower/mesh/mod.rs (plan_partial_groups)`, `crates/metal2vulkan/src/lower/select.rs (finish)` (+2) | `app`: a dispatchThreads grid that is not whole threadgroups, of a kernel whose partial-threadgroups variant cannot be made | | `IrreducibleConvergent` | An irreducible region containing a convergent instruction | every device (no Vulkan mechanism) | `device` | 1: `crates/metal2vulkan/src/structurize/irreducible.rs (refuse_tangled)` | `rare`: irreducible loops around barriers or simd operations | | `ComputeDerivativesWithSimd` | Compute derivatives in a flattened simd tier | every device (no Vulkan mechanism) | `device` | 1: `crates/metal2vulkan/src/lower/dispatch.rs (plan_kernel)` | `rare`: derivatives in a kernel | -| `ComputeDerivatives` | Derivatives outside fragment without compute-derivative support | devices without VkFeature::ComputeDerivativeGroupLinear; every device (no Vulkan mechanism); every device (not implemented) | `ours` | 4: `crates/metal2vulkan/src/bind/dispatch.rs (check_local)`, `crates/metal2vulkan/src/lower/sync/barrier.rs (select_derivative, 3 sites)` | `rare`: derivatives in a kernel | +| `ComputeDerivatives` | Derivatives outside fragment without compute-derivative support | devices without VkFeature::ComputeDerivativeGroupLinear; every device (no Vulkan mechanism); every device (not implemented) | `ours` | 3: `crates/metal2vulkan/src/lower/sync/barrier.rs (select_derivative, 3 sites)` | `rare`: derivatives in a kernel | | `QuadOperations` | Quad operations in a stage without quad support | devices without VkLimit::MinSubgroupSize | `device` | 1: `crates/metal2vulkan/src/device/subgroup.rs (subgroup_tier)` | `app`: quad shuffles in kernels on devices without quad operations there | | `SimdgroupMatrix` | Simdgroup matrix operations | every device (not implemented) | `ours` | 1: `crates/metal2vulkan/src/lower/simd/matrix.rs (not_implemented)` | `rare`: simdgroup matrix kernels | | `SimdgroupMatrix16x16x16` | A 16x16x16 simdgroup matrix product (`air.simdgroup_matrix_16x16x16_[widening_]multiply_accumulate`), in any stage | every device (not implemented) | `ours` | 1: `crates/metal2vulkan/src/lower/simd/matrix.rs (select)` | `rare`: 16x16x16 simdgroup matrix products (Metal: Apple10 GPUs and later) | | `ArgumentBufferPointers` | Argument buffers holding buffer pointers (dynamic roots) | devices without buffer device addresses (`addressed_needs`) | `device` | 1: `crates/metal2vulkan/src/device/metal.rs (unsupported_features)` | `app`: argument buffers holding buffer pointers | -| `ArgumentBufferTextures` | Argument buffers holding textures or samplers (handle domain) | devices without a capability the site computes (`gaps`); devices without a capability the site computes (`missing`); every device (not implemented) | `ours` | 15: `crates/metal2vulkan/src/bind/heap.rs (array)`, `crates/metal2vulkan/src/bind/heap.rs (member_texel_view, 2 sites)` (+8) | `app`: argument buffers holding textures and samplers (bindless) | +| `ArgumentBufferTextures` | Argument buffers holding textures or samplers (handle domain) | devices without a capability the site computes (`gaps`); devices without a capability the site computes (`missing`); every device (not implemented) | `ours` | 13: `crates/metal2vulkan/src/bind/heap.rs (member_texel_view, 2 sites)`, `crates/metal2vulkan/src/bind/heap.rs (member_view, 4 sites)` (+6) | `app`: argument buffers holding textures and samplers (bindless) | | `ArgumentBufferObjects` | Argument-buffer members that are pipeline states, ICBs, function tables, or acceleration structures | every device (not implemented) | `ours` | 4: `crates/metal2vulkan/src/lower/access/icb.rs (select)`, `crates/metal2vulkan/src/lower/access/object.rs (select)` (+2) | `rare`: pipeline states and ICBs in argument buffers | | `DereferenceLoadedPointer` | Dereferencing a pointer loaded from memory or made from an integer | devices short of a Vulkan feature the site names; devices without buffer device addresses (`addressed_needs`); every device (no Vulkan mechanism) | `device` | 4: `crates/metal2vulkan/src/lower/access/dynamic.rs (plan_misses)`, `crates/metal2vulkan/src/lower/access/local.rs (access_ptr)` (+2) | `app`: pointers loaded from argument buffers | | `PointerToInteger` | Storing a pointer or converting it to an integer | devices without buffer device addresses (`addressed_needs`) | `device` | via a helper: 1: `crates/metal2vulkan/src/lower/access/dynamic.rs (require_addresses)` | `rare`: pointer to integer casts | | `PointerCompare` | Comparing pointers with different roots | devices without VkFeature::ShaderInt64 | `device` | via a helper: 1: `crates/metal2vulkan/src/lower/access/copy.rs (addressed)` | `rare`: comparing pointers of different roots | | `HandleAsPointer` | A resource handle used as a byte pointer, or conflicting handle provenance | every device (no Vulkan mechanism); every device (not implemented) | `ours` | 6: `crates/metal2vulkan/src/lower/access/handle.rs (domain_kind)`, `crates/metal2vulkan/src/lower/access/handle.rs (element, 2 sites)` (+3) | `rare`: resource handles used as byte pointers | | `ConstantGlobalEscaping` | A constant global whose address escapes | every device (not implemented) | `ours` | 2: `crates/metal2vulkan/src/memory/plan.rs (blob_nodes)`, `crates/metal2vulkan/src/memory/plan.rs (serialize)` | `rare`: a constant global whose address escapes | -| `ThreadgroupMemorySize` | Threadgroup memory above the device limit | devices short of a device limit the site names; devices without VkLimit::MaxComputeSharedMemorySize; every device (no Vulkan mechanism) | `device` | 3: `crates/metal2vulkan/src/bind/plan/compute.rs (plan)`, `crates/metal2vulkan/src/memory/arena.rs (check)` (+1) | `rare`: threadgroup memory past a smaller device's limit | +| `ThreadgroupMemorySize` | Threadgroup memory above the device limit | devices short of a device limit the site names; every device (no Vulkan mechanism) | `device` | 2: `crates/metal2vulkan/src/memory/arena.rs (check)`, `crates/metal2vulkan/src/memory/plan.rs (too_large)` | `rare`: threadgroup memory past a smaller device's limit | | `ZeroedThreadgroupMemory` | Threadgroup memory that reads zero until the program writes it, on `Device::from_queries`' profile | devices short of a Vulkan feature the site names | `device` | 1: `crates/metal2vulkan/src/lower/access/local.rs (zero_threadgroup)` | `rare`: threadgroup memory on a device without shaderZeroInitializeWorkgroupMemory, which Vulkan 1.3 requires | | `CoherentMemory` | `coherent(device)` accesses (Vulkan memory model) | devices short of a Vulkan feature the site names | `device` | 1: `crates/metal2vulkan/src/lower/sync/memory_model.rs (check)` | `rare`: coherent(device) accesses | | `Int64Atomics` | 64-bit atomics | devices short of a Vulkan feature the site names; devices without buffer device addresses (`addressed_needs`) | `device` | 2: `crates/metal2vulkan/src/lower/access/atomic.rs (select, 2 sites)` | `rare`: 64-bit atomics | | `ImageAtomics` | Image atomics beyond 32-bit integers | every device (not implemented) | `ours` | 1: `crates/metal2vulkan/src/lower/texture/atomic.rs (select)` | `rare`: texture atomics beyond 32-bit integers | | `DescriptorCount` | Too many descriptors of one kind in a stage or pipeline | devices short of a device limit the site names; devices without VkLimit::MaxUniformBufferRange | `device` | 3: `crates/metal2vulkan/src/lower/access/mod.rs (accept_placement)`, `crates/metal2vulkan/src/lower/select.rs (finish)` (+1) | `app`: many textures or buffers in one stage on a smaller device | -| `BufferRange` | A buffer window beyond the descriptor range limits | devices without buffer device addresses (`addressed_needs`); every device (no Vulkan mechanism) | `device` | 6: `crates/metal2vulkan/src/bind/graphics.rs (patch_binding, 3 sites)`, `crates/metal2vulkan/src/bind/instantiate.rs (bind_buffers)` (+2) | `app`: a buffer window past a device's descriptor range | +| `BufferRange` | A buffer window beyond the descriptor range limits | devices without buffer device addresses (`addressed_needs`) | `device` | 2: `crates/metal2vulkan/src/lower/access/function_table.rs (select)`, `crates/metal2vulkan/src/lower/access/mod.rs (place_slots)` | `app`: a buffer window past a device's descriptor range | | `Int64Arithmetic` | 64-bit integer arithmetic | devices without VkFeature::ShaderInt64 | `device` | 2: `crates/metal2vulkan/src/lower/arith/legal.rs (check_scalar)`, `crates/metal2vulkan/src/lower/select.rs (selector_form)` | `rare`: 64-bit integers on a device without shaderInt64 | | `Float64Arithmetic` | 64-bit float arithmetic | devices without VkFeature::ShaderFloat64 | `device` | 2: `crates/metal2vulkan/src/device/metal.rs (unsupported_features)`, `crates/metal2vulkan/src/lower/arith/legal.rs (check_scalar)` | `rare`: doubles (MSL has none outside Apple's own code) | -| `Format` | A pixel or vertex format not supported for the required use | devices without VkFeature::ShaderStorageImageExtendedFormats; devices without a capability the site computes (`alternatives`); devices without a capability the site computes (`missing`); devices without a capability the site computes (`routes`); devices without a format's usage; every device (no Vulkan mechanism); every device (not implemented) | `ours` | 56: `crates/metal2vulkan/src/bind/heap.rs (array)`, `crates/metal2vulkan/src/bind/plan/resources.rs (extended_sampler)` (+31) | `system`: pixel formats a device lacks for a use (CoreVideo's 4:2:x and 10-bit formats among them) | +| `Format` | A pixel or vertex format not supported for the required use | devices without VkFeature::ShaderStorageImageExtendedFormats; devices without a capability the site computes (`alternatives`); devices without a capability the site computes (`missing`); devices without a capability the site computes (`routes`); devices without a format's usage; every device (no Vulkan mechanism); every device (not implemented) | `ours` | 51: `crates/metal2vulkan/src/lower/access/tile.rs (storage_format)`, `crates/metal2vulkan/src/lower/fragment/color.rs (select_param, 5 sites)` (+27) | `system`: pixel formats a device lacks for a use (CoreVideo's 4:2:x and 10-bit formats among them) | | `DivergentImplicitLod` | Divergent implicit-LOD sampling or LOD query through a multi-candidate handle | every device (not implemented) | `ours` | 1: `crates/metal2vulkan/src/lower/sampler/select.rs (tangled)` | `app`: implicit-LOD sampling through a dynamically chosen texture | | `ImplicitLodOutsideFragment` | Implicit-LOD sampling outside fragment | every device (not implemented) | `ours` | 3: `crates/metal2vulkan/src/lower/sampler/constexpr.rs (query_min_level)`, `crates/metal2vulkan/src/lower/sampler/select.rs (query_level_measured)` (+1) | `rare`: implicit-LOD sampling outside fragment functions | | `MinLodClamp` | `min_lod_clamp` without `shaderResourceMinLod` | devices without VkFeature::ShaderResourceMinLod; every device (not implemented) | `ours` | 2: `crates/metal2vulkan/src/lower/sampler/select.rs (min_lod)`, `crates/metal2vulkan/src/lower/sampler/select.rs (select_one)` | `rare`: min_lod_clamp on a device without shaderResourceMinLod | @@ -103,17 +101,17 @@ Columns: | `StorageImageMultisample` | Multisampled storage images | every device (not implemented) | `ours` | 2: `crates/metal2vulkan/src/lower/texture/slot.rs (declare_heap)`, `crates/metal2vulkan/src/lower/texture/slot.rs (declare_slot)` | `rare`: writable multisampled textures | | `StorageTextureInVertexStage` | Storage images in the vertex stage | devices short of a Vulkan feature the site names | `device` | via a helper: 1: `crates/metal2vulkan/src/lower/texture/slot.rs (stage_stores)` | `rare`: writable textures in vertex functions | | `CubeArray` | Cube arrays | devices without VkFeature::ImageCubeArray | `device` | 2: `crates/metal2vulkan/src/lower/sampler/select.rs (select_one)`, `crates/metal2vulkan/src/lower/texture/slot.rs (declare_heap)` | `rare`: cube arrays on a device without imageCubeArray | -| `SamplerAnisotropy` | Sampler anisotropy an argument buffer lists, on a device without `samplerAnisotropy` | devices without VkFeature::SamplerAnisotropy | `device` | 1: `crates/metal2vulkan/src/metal/sampler.rs (check_argument_sampler)` | `app`: anisotropic samplers an argument buffer lists, on a device without samplerAnisotropy | +| `SamplerAnisotropy` | Sampler anisotropy an argument buffer lists, on a device without `samplerAnisotropy` | - | `-` | 0 | `app`: anisotropic samplers an argument buffer lists, on a device without samplerAnisotropy | | `SamplerBorderColor` | Sampler border colors Vulkan cannot express | devices without a capability the site computes (`missing`); devices without a capability the site computes (`need`); devices without a capability the site computes (`vec![need]`); every device (not implemented) | `ours` | 4: `crates/metal2vulkan/src/metal/sampler.rs (border_read, 4 sites)` | `app`: border colors a device cannot express | | `SamplerLodBias` | Sampler LOD bias | devices short of a Vulkan feature the site names; devices without VkLimit::MaxSamplerLodBias; every device (no Vulkan mechanism) | `device` | 3: `crates/metal2vulkan/src/lower/sampler/constexpr.rs (constexpr_desc, 3 sites)` | `app`: constexpr samplers with an LOD bias | | `SamplerCompare` | Sampler compare functions outside what Vulkan allows for the image | devices short of a Vulkan feature the site names | `device` | 1: `crates/metal2vulkan/src/metal/sampler.rs (check_sampler)` | `app`: compare samplers a device cannot apply to the image | | `PixelSamplerCompare` | A constexpr sampler with pixel coordinates and a compare function, which Apple's compiler rejects ("invalid values combination in sampler... | every device (no Vulkan mechanism) | `device` | 1: `crates/metal2vulkan/src/lower/sampler/constexpr.rs (lowered)` | `none`: Apple's compiler rejects it | -| `TexelBuffer` | Texture buffers beyond the device's texel-buffer limits | devices without a format's usage; every device (no Vulkan mechanism) | `device` | 3: `crates/metal2vulkan/src/bind/instantiate.rs (texel_ranges, 2 sites)`, `crates/metal2vulkan/src/bind/plan/resources.rs (plain_texture)` | `app`: texture buffers past a device's texel-buffer limits | +| `TexelBuffer` | Texture buffers beyond the device's texel-buffer limits | - | `-` | 0 | `app`: texture buffers past a device's texel-buffer limits | | `RasterOrderGroups` | Raster order groups without fragment shader interlock | devices without VkFeature::FragmentShaderPixelInterlock; every device (not implemented) | `ours` | 3: `crates/metal2vulkan/src/device/metal.rs (unsupported_features)`, `crates/metal2vulkan/src/lower/fragment/rog.rs (mode, 2 sites)` | `rare`: raster order groups | | `FramebufferFetch` | Framebuffer fetch in a shape not implemented (a write the function would compute over its own read of the attachment), or that needs a feature the... | devices without VkFeature::SampleRateShading; every device (not implemented) | `ours` | 2: `crates/metal2vulkan/src/lower/fragment/fetch.rs (computed_write_refused)`, `crates/metal2vulkan/src/lower/fragment/fetch.rs (plan_sample)` | `system`: programmable blending (framebuffer fetch); macOS 26.6.2's login reaches it (two WindowServer and RenderBox pipelines fetch RGB10A8_2P_XR10 attachments, the consumer's boots) | | `PrimitiveId` | `[[primitive_id]]` in a fragment function | devices without a capability the site computes; every device (not implemented) | `ours` | 2: `crates/metal2vulkan/src/lower/stage_io/plan.rs (finish)`, `crates/metal2vulkan/src/pipeline/link/varyings.rs (check_primitive_id)` | `rare`: primitive_id on a device without geometry or tessellation shaders, in an indexed draw or behind a mesh function | | `PrivatePrimitives` | One of Metal's private primitive types (a line loop, a triangle fan, quads, a quad strip) drawn in the pulled list form... | devices without buffer device addresses (`addressed_needs`); every device (not implemented) | `ours` | via a helper: 1: `crates/metal2vulkan/src/lower/stage_io/plan.rs (indices_feature)` | `rare`: a private primitive type drawn in the pulled list form (a vertex function that writes memory or the primitive_id varying, a vertex start past 2^31) on a device without device addresses | -| `VertexAmplification` | Vertex amplification | devices short of a Vulkan feature the site names; devices without VkFeature::Multiview; devices without VkFeature::MultiviewTessellationShader; devices without VkLimit::MaxMultiviewInstanceIndex; every device (not implemented) | `ours` | 5: `crates/metal2vulkan/src/bind/graphics.rs (multiview_instances)`, `crates/metal2vulkan/src/lower/stage_io/plan.rs (index_store)` (+3) | `rare`: vertex amplification | +| `VertexAmplification` | Vertex amplification | devices short of a Vulkan feature the site names; devices without VkFeature::Multiview; devices without VkFeature::MultiviewTessellationShader; every device (not implemented) | `ours` | 4: `crates/metal2vulkan/src/lower/stage_io/plan.rs (index_store)`, `crates/metal2vulkan/src/lower/tessellation/mod.rs (select_param)` (+2) | `rare`: vertex amplification | | `LayeredRendering` | Layered rendering (`render_target_array_index`, `viewport_array_index`) | devices short of a Vulkan feature the site names; devices without VkFeature::ShaderOutputLayer; devices without VkFeature::ShaderOutputViewportIndex; every device (not implemented) | `ours` | 4: `crates/metal2vulkan/src/lower/mesh/mod.rs (target_index, 2 sites)`, `crates/metal2vulkan/src/lower/stage_io/plan.rs (index_store, 2 sites)` | `rare`: layered rendering on a device without its features | | `ClipDistance` | Clip or cull distances | devices without VkFeature::ShaderClipDistance; devices without VkLimit::MaxClipDistances | `device` | 2: `crates/metal2vulkan/src/lower/mesh/mod.rs (select, 2 sites)` | `rare`: clip distances on a device without them | | `DualSourceBlending` | Dual-source blending | devices without VkFeature::DualSrcBlend; devices without VkLimit::MaxFragmentDualSrcAttachments | `device` | 3: `crates/metal2vulkan/src/metal/state.rs (blend_factor)`, `crates/metal2vulkan/src/pipeline/link/graphics.rs (check_outputs)` (+1) | `rare`: dual-source blending on a device without it | @@ -129,8 +127,8 @@ Columns: | `VertexStepRate` | A vertex buffer layout stepped per instance at a rate above 1, on a profile that fetches every attribute in fixed function (the identity domains,... | devices without a capability the site computes (`needs`) | `device` | 1: `crates/metal2vulkan/src/metal/vertex.rs (divided)` | `app`: instanced vertex layouts stepped at a rate above 1 | | `VertexInputLayout` | A vertex attribute whose layout fixed-function input cannot fetch, on a profile that fetches every attribute in fixed function (the identity... | devices without a capability the site computes (`limit`); every device (not implemented) | `ours` | 4: `crates/metal2vulkan/src/pipeline/link/vertex.rs (resolve, 4 sites)` | `rare`: vertex offsets or strides off their format's alignment, or past a device's limits | | `Tessellation` | Tessellation | devices without VkFeature::TessellationShader; devices without VkLimit::MaxTessellationGenerationLevel; every device (not implemented) | `ours` | 13: `crates/metal2vulkan-air/src/canon/mod.rs (post_check, 2 sites)`, `crates/metal2vulkan/src/lower/stage_io/fetch.rs (select)` (+8) | `rare`: tessellation | -| `MeshShading` | | devices short of a device limit the site names; devices without VkLimit::MaxMeshOutputLayers; devices without VkLimit::MaxTaskPayloadSize; devices without a capability the site computes (`missing`); every device (not implemented) | `ours` | 6: `crates/metal2vulkan/src/bind/graphics.rs (mesh_limit)`, `crates/metal2vulkan/src/bind/graphics.rs (plan)` (+3) | `rare`: mesh pipelines | -| `TileShading` | | devices without VkLimit::MaxStorageBufferRange; every device (not implemented) | `ours` | 4: `crates/metal2vulkan/src/bind/plan/compute.rs (tile_memory)`, `crates/metal2vulkan/src/lower/access/tile.rs (not_implemented)` (+2) | `rare`: tile shaders (Apple GPU families) | +| `MeshShading` | | devices short of a device limit the site names; devices without VkLimit::MaxTaskPayloadSize; devices without a capability the site computes (`missing`); every device (not implemented) | `ours` | 4: `crates/metal2vulkan/src/lower/mesh/mod.rs (check_payload)`, `crates/metal2vulkan/src/lower/mesh/mod.rs (plan_entry, 2 sites)` (+1) | `rare`: mesh pipelines | +| `TileShading` | | every device (not implemented) | `ours` | 3: `crates/metal2vulkan/src/lower/access/tile.rs (not_implemented)`, `crates/metal2vulkan/src/lower/sync/barrier.rs (tile_shading)` (+1) | `rare`: tile shaders (Apple GPU families) | | `Imageblocks` | An imageblock outside the forms implemented | every device (not implemented) | `ours` | 6: `crates/metal2vulkan/src/lower/access/imageblock.rs (imageblocks)`, `crates/metal2vulkan/src/lower/access/mod.rs (select_param)` (+4) | `rare`: imageblocks (Apple GPU families) | | `RayTracing` | | devices without a capability the site computes (`missing`); every device (no Vulkan mechanism); every device (not implemented) | `ours` | 10: `crates/metal2vulkan/src/lower/raytracing/mod.rs (instance_count)`, `crates/metal2vulkan/src/lower/raytracing/mod.rs (intersect, 5 sites)` (+4) | `rare`: ray tracing (out of scope by ruling) | | `Tensors` | | every device (not implemented) | `ours` | 2: `crates/metal2vulkan-air/src/canon/matmul2d/synth.rs (refuse)`, `crates/metal2vulkan/src/lower/select.rs (route_air)` | `rare`: shader tensors | @@ -146,13 +144,13 @@ Columns: | `SubgroupOperations` | Simdgroup operations of a class the stage's subgroups do not support (the stage is not in `subgroupSupportedStages`, or an operation class is... | devices without VkFeature::ShaderQuadControl; devices without VkFeature::ShaderSubgroupExtendedTypes | `device` | 2: `crates/metal2vulkan/src/lower/simd/mod.rs (full_quads)`, `crates/metal2vulkan/src/lower/simd/mod.rs (select_group)` | `app`: simdgroup functions in a stage a device's subgroups do not support | | `DirectCall` | A call to a defined function the inliner cannot take | every device (not implemented) | `ours` | 1: `crates/metal2vulkan-air/src/canon/mod.rs (post_check)` | `rare`: variadic or byval calls the inliner cannot take | | `WideSwitchLiteral` | A switch case literal wider than 32 bits | every device (not implemented) | `ours` | 1: `crates/metal2vulkan/src/structurize/emit.rs (check_tree)` | `rare`: 64-bit switch literals | -| `Lowering` | An instruction, intrinsic, or interface element of a lowering family whose lowering has not landed yet (each family narrows its refusals as it lands) | devices short of a device limit the site names; devices without VkFeature::ShaderDemoteToHelperInvocation; every device (not implemented) | `ours` | 36: `crates/metal2vulkan/src/bind/plan/resources.rs (level_views)`, `crates/metal2vulkan/src/lower/access/handle.rs (domain_kind)` (+33) | `system`: the catch-all of lowering families not landed: any shader can meet one | +| `Lowering` | An instruction, intrinsic, or interface element of a lowering family whose lowering has not landed yet (each family narrows its refusals as it lands) | devices without VkFeature::ShaderDemoteToHelperInvocation; every device (not implemented) | `ours` | 35: `crates/metal2vulkan/src/lower/access/handle.rs (domain_kind)`, `crates/metal2vulkan/src/lower/access/handle.rs (sampler_target)` (+32) | `system`: the catch-all of lowering families not landed: any shader can meet one | | `SamplerAddressMode` | A sampler address mode the device lacks (`MirrorClampToEdge`) | devices without VkFeature::SamplerMirrorClampToEdge; every device (not implemented) | `ours` | 2: `crates/metal2vulkan/src/lower/sampler/constexpr.rs`, `crates/metal2vulkan/src/metal/sampler.rs (check_sampler)` | `app`: mirror-clamp-to-edge on a device without it | | `AlphaToOne` | `alphaToOneEnabled` on a device without Vulkan's `alphaToOne` feature, the exact counterpart... | devices without VkFeature::AlphaToOne | `device` | 1: `crates/metal2vulkan/src/pipeline/link/graphics.rs (graphics_state)` | `rare`: alphaToOneEnabled on a device without alphaToOne | | `StageStoresAndAtomics` | Buffer or image stores or atomics in a vertex or fragment function without the stage's store feature (`vertexPipelineStoresAndAtomics`,... | devices without VkFeature::FragmentStoresAndAtomics | `device` | 1: `crates/metal2vulkan/src/lower/access/tile_memory.rs (written)` | `app`: stores or atomics in vertex or fragment functions on a device without the feature | | `FunctionConstantArgument` | An observed read of a pointer entry argument that a function-constant predicate removes, other than an absent buffer (which reads as null) or an... | every device (not implemented) | `ours` | 1: `crates/metal2vulkan-air/src/canon/interface.rs (absent_values)` | `rare`: a function-constant-removed argument read | -| `SamplerBicubicFilter` | A use of Metal's bicubic filter that no Metal reading establishes | every device (not implemented) | `ours` | 5: `crates/metal2vulkan/src/bind/heap.rs (new)`, `crates/metal2vulkan/src/bind/plan/resources.rs (bicubic_texels)` (+3) | `system`: bicubic filtering forms Metal does not establish; macOS 26.6.2 makes a runtime sampler with MTLSamplerMinMagFilterCubic (the consumer's boots), whose mip-filtered form is refused | -| `GroupCount` | A dispatch whose threadgroup count on `axis` exceeds `maxComputeWorkGroupCount` by more than the binder splits into regions (`None` | every device (no Vulkan mechanism) | `device` | 5: `crates/metal2vulkan/src/bind/dispatch.rs (2 sites)`, `crates/metal2vulkan/src/bind/dispatch.rs (product)` (+2) | `rare`: more threadgroups than a device dispatches, past the binder's split | +| `SamplerBicubicFilter` | A use of Metal's bicubic filter that no Metal reading establishes | every device (not implemented) | `ours` | 2: `crates/metal2vulkan/src/lower/sampler/bicubic.rs (refuse)`, `crates/metal2vulkan/src/lower/sampler/select.rs (bicubic_refused)` | `system`: bicubic filtering forms Metal does not establish; macOS 26.6.2 makes a runtime sampler with MTLSamplerMinMagFilterCubic (the consumer's boots), whose mip-filtered form is refused | +| `GroupCount` | A dispatch whose threadgroup count on `axis` exceeds `maxComputeWorkGroupCount` by more than the binder splits into regions (`None` | - | `-` | 0 | `rare`: more threadgroups than a device dispatches, past the binder's split | | `IntersectionFunctionTable` | A ray intersection through intersection functions | every device (not implemented) | `ours` | 6: `crates/metal2vulkan/src/lower/raytracing/mod.rs (intersect, 2 sites)`, `crates/metal2vulkan/src/lower/raytracing/mod.rs (null_table)` (+3) | `rare`: ray tracing (out of scope by ruling) | | `IndependentBlending` | Color attachments whose write masks or blend states differ, as Metal sets them per attachment, on a device without `independentBlend`, where no... | devices without VkFeature::IndependentBlend | `device` | 1: `crates/metal2vulkan/src/pipeline/link/graphics.rs (uniform_blend)` | `rare`: per-attachment blending on a device without independentBlend | | `RasterSampleCount` | A `rasterSampleCount` outside the device's framebuffer sample counts for the pipeline's attachments (`framebuffer*SampleCounts`), and, for a color... | devices without a capability the site computes | `device` | 1: `crates/metal2vulkan/src/pipeline/graphics.rs (sample_count_properties)` | `app`: a sample count a device lacks for the attachments | @@ -161,33 +159,20 @@ Columns: | `DepthClipClamp` | The render encoder's `MTLDepthClipModeClamp` (`depthClampEnable`) on a device without `depthClamp` | devices short of a Vulkan feature the site names | `device` | via a helper: 1: `crates/metal2vulkan/src/metal/state.rs (depth_clamp_enable)` | `app`: depth clamp on a device without depthClamp | | `DepthBiasClamp` | The render encoder's depth bias clamp, nonzero with a nonzero bias, on a device without `depthBiasClamp` | devices short of a Vulkan feature the site names | `device` | via a helper: 1: `crates/metal2vulkan/src/metal/state.rs (depth_bias)` | `app`: depth bias clamp on a device without depthBiasClamp | | `ConstantAlphaBlendFactor` | `CONSTANT_ALPHA` or `ONE_MINUS_CONSTANT_ALPHA` (Metal's `BlendAlpha` factors) as a color blend factor on a portability-subset device without... | devices without VkFeature::ConstantAlphaColorBlendFactors | `device` | 1: `crates/metal2vulkan/src/metal/state.rs (check_constant_alpha)` | `app`: blend-alpha factors on a portability-subset device without them | -| `SparseTexture` | A sparse texture (`MTLTexture.isSparse`) bound at `slot`, where a function observes the residency of its accesses (`sparse_color::resident()`) and... | devices without VkFeature::ShaderResourceResidency; every device (no Vulkan mechanism); every device (not implemented) | `ours` | via a helper: 2: `crates/metal2vulkan/src/bind/plan/slots.rs (check_sparse_textures, 2 sites)` | `rare`: sparse residency reads | -| `TextureSwizzle` | A texture swizzle whose Metal behavior is not measured | every device (not implemented) | `ours` | 6: `crates/metal2vulkan/src/bind/heap.rs (member_texel_view)`, `crates/metal2vulkan/src/bind/plan/resources.rs (plain_texture)` (+4) | `app`: texture swizzles whose Metal behaviour is unmeasured | +| `SparseTexture` | A sparse texture (`MTLTexture.isSparse`) bound at `slot`, where a function observes the residency of its accesses (`sparse_color::resident()`) and... | - | `-` | 0 | `rare`: sparse residency reads | +| `TextureSwizzle` | A texture swizzle whose Metal behavior is not measured | every device (not implemented) | `ours` | 5: `crates/metal2vulkan/src/bind/heap.rs (member_texel_view)`, `crates/metal2vulkan/src/lower/sampler/select.rs (select_one)` (+3) | `app`: texture swizzles whose Metal behaviour is unmeasured | | `PrivateMemory` | A stage whose private memory (its `thread` variables and arrays, and the constants it holds per thread) takes more Function storage a thread than... | devices without a capability the site computes (`limit`) | `device` | 1: `crates/metal2vulkan/src/lower/access/local.rs (device_arena)` | `rare`: very large per-thread arrays | | `Reflection` | Reflection of an argument whose answer Metal's has not been measured for (`reflection`) | every device (not implemented) | `ours` | 8: `crates/metal2vulkan/src/reflection/derive.rs (gap_at)`, `crates/metal2vulkan/src/reflection/derive.rs (read_attributes)` (+6) | `rare`: reflection of argument kinds Metal's answer is unmeasured for | | `IndirectRenderState` | A `depth_stencil_state` a function reads from an argument buffer or takes as a parameter, the state of an indirect render command, which no record... | every device (not implemented) | `ours` | via a helper: 2: `crates/metal2vulkan/src/lower/access/pointer.rs (unlowered)`, `crates/metal2vulkan/src/lower/select.rs (param_family)` | `rare`: render state set by a kernel on an indirect command | | `GlobalBuiltinInFragment` | A fragment function's read of a Metal 3.1 program-scope built-in variable that Metal does not lower there | every device (not implemented) | `ours` | 1: `crates/metal2vulkan/src/lower/select.rs (route_air)` | `rare`: Metal 3.1 global built-ins in fragment functions | -| `PrivateRenderState` | A private fixed-function property of Metal's pipeline descriptor (Apple SPI, OpenGL on Metal's) set to a value whose effect the translation has... | devices without VkFeature::LogicOp; every device (not implemented) | `ours` | 7: `crates/metal2vulkan/src/bind/heap.rs (array)`, `crates/metal2vulkan/src/bind/plan/resources.rs (write_rounding)` (+5) | `none`: Apple-private pipeline fields of OpenGL on Metal (no public header) | +| `PrivateRenderState` | A private fixed-function property of Metal's pipeline descriptor (Apple SPI, OpenGL on Metal's) set to a value whose effect the translation has... | devices without VkFeature::LogicOp; every device (not implemented) | `ours` | 5: `crates/metal2vulkan/src/lower/sampler/select.rs (clamps_reference)`, `crates/metal2vulkan/src/lower/stage_io/plan.rs (alpha_test_refused)` (+3) | `none`: Apple-private pipeline fields of OpenGL on Metal (no public header) | | `ProgramScopeBinding` | A program-scope buffer binding of MSL 3.2 (macOS 15 and later), `constant T* constant p [[buffer(n)]];` in Apple's `!air.global_bindings` list,... | every device (not implemented) | `ours` | via a helper: 2: `crates/metal2vulkan-air/src/abi/module.rs (decode)`, `crates/metal2vulkan/src/error/mod.rs (from)` | `app`: MSL 3.2 program-scope buffer bindings (macOS 15 and later) | | `GenericPointer` | A generic pointer (MSL 4.1's `addrspace(8)`) that canonicalization cannot make a pointer of one address space, by how it comes to hold a space... | every device (not implemented) | `ours` | 2: `crates/metal2vulkan-air/src/canon/generic.rs (refuse)`, `crates/metal2vulkan-air/src/canon/generic.rs (refused)` | `system`: MSL 4.1 generic pointers held in memory or of two spaces (macOS 27 and later) | | `SeqCstFence` | A sequentially consistent fence (`seq_cst` `atomic_thread_fence`, an LLVM `fence seq_cst`, or a `seq_cst` barrier ordering device memory), whose... | devices short of a Vulkan feature the site names | `device` | 1: `crates/metal2vulkan/src/lower/sync/barrier.rs (require_seq_cst)` | `rare`: a seq_cst fence in a vertex or fragment stage without its stores and atomics | | `PostDepthCoverage` | The coverage after the depth and stencil tests (`[[sample_mask, post_depth_coverage]]`) | every device (not implemented) | `ours` | 1: `crates/metal2vulkan/src/lower/stage_io/plan.rs (param)` | `rare`: the coverage after early depth and stencil tests, on every device | | `WideLines` | Lines at a width other than 1 (Apple's `setLineWidth:`), drawn by the device's own wide lines (`wideLines`) or as bands of triangles through... | devices without VkFeature::TessellationShader; devices without VkLimit::MaxTessellationEvaluationOutputComponents; every device (not implemented) | `ours` | 3: `crates/metal2vulkan/src/pipeline/link/band.rs (plan, 3 sites)` | `none`: a line under the Apple-private setLineWidth: at a width other than 1 drawn as the band, whose pipeline form the translator does not build (a selected slice or viewport, barycentric weights, multiview, synthesized geometry, too many stage outputs) | -## 2. Binder refusals at a device limit (`BindError`) - -| Variant | What it blocks | Where | Basis | Sites | Reach | -|---|---|---|---|---|---| -| `DescriptorRangeExceeded` | A descriptor-form slot's window exceeds the descriptor range limit (Profile F) | at the device's limit | `device` | 1: `crates/metal2vulkan/src/bind/instantiate.rs (bind_buffers)` | `app`: a buffer window past a device's descriptor range | -| `TexelBufferTooLarge` | A texture buffer bound through one texel buffer view exceeds `maxTexelBufferElements` | at the device's limit | `device` | 1: `crates/metal2vulkan/src/bind/instantiate.rs (texel_ranges)` | `rare`: a texture buffer past maxTexelBufferElements its parts do not bind | -| `HeapTooLarge` | The set-1 heap's elements (one per resident texture a handle can name, plus the null element) exceed the pipeline's heap capacity | at the device's limit | `device` | 6: `crates/metal2vulkan/src/bind/heap.rs (directory_bytes)`, `crates/metal2vulkan/src/bind/heap.rs (listed_sampler_tables)` (+2) | `rare`: more resident textures than the pipeline's heap holds (bindless at scale) | -| `TessellationFactorRange` | The tessellation factors a draw reads span more bytes (`needed`) than one storage-buffer descriptor can bind (`limit`, `maxStorageBufferRange`),... | at the device's limit | `device` | 1: `crates/metal2vulkan/src/bind/graphics.rs (patch_binding)` | `rare`: tessellation factors past one storage descriptor | -| `PatchIndexRange` | The patch indices a draw reads span more bytes (`needed`) than one storage-buffer descriptor can bind (`limit`, `maxStorageBufferRange`) | at the device's limit | `device` | 1: `crates/metal2vulkan/src/bind/graphics.rs (patch_binding)` | `rare`: patch indices past one storage descriptor | -| `ControlPointIndexRange` | The control-point indices a draw reads span more bytes (`needed`) than one storage-buffer descriptor can bind (`limit`, `maxStorageBufferRange`) | at the device's limit | `device` | 1: `crates/metal2vulkan/src/bind/graphics.rs (patch_binding)` | `rare`: control-point indices past one storage descriptor | -| `MissingStageInRegion` | The kernel reads the compute encoder's stage-in region (a `[[stage_in]]` attribute stepping by thread position, or `[[grid_origin]]` or... | at the device's limit | `device` | 1: `crates/metal2vulkan/src/bind/dispatch.rs (instantiate)` | `none`: a stage-in region never set, which Metal leaves undefined | -| `MissingDeviceAddress` | A device-address slot received a buffer without a device address | at the device's limit | `device` | 1: `crates/metal2vulkan/src/bind/plan/slots.rs (plan_buffer)` | `rare`: a slot reached through a pointer loaded from memory, bound with inline bytes or on a device without device addresses | - -## 3. Translation caps (`Error::LimitExceeded(Limit)`) +## 2. Translation caps (`Error::LimitExceeded(Limit)`) | Variant | What it blocks | Where | Basis | Sites | Reach | |---|---|---|---|---|---| @@ -206,7 +191,7 @@ Columns: | `PrivateArenaBytes` | Bytes of a function's private arena, whose pointers are `u32` byte offsets | every device (a deterministic cap) | `ours` | 4: `crates/metal2vulkan/src/lower/access/local.rs (device_arena)`, `crates/metal2vulkan/src/lower/access/local.rs (use_arena)` (+1) | `none`: a private arena past 4 GiB | | `CallStackBytes` | Bytes of a kernel's call stack | every device (a deterministic cap) | `ours` | 1: `crates/metal2vulkan-air/src/canon/recursion.rs (metal_stack)` | `rare`: deep visible-function call stacks | -## 4. Rate maps the compile layer does not compile (`UnpinnedCompile`) +## 3. Rate maps the compile layer does not compile (`UnpinnedCompile`) | Variant | What it blocks | Where | Basis | Sites | Reach | |---|---|---|---|---|---| @@ -216,13 +201,13 @@ Columns: | `SampleOutOfRange` | A sample outside `[0, 1]` (or `NaN`) on an axis of two or more samples | every device (this crate's bound: Apple's compile unmeasured or crashing there) | `ours` | 1: `crates/metal2vulkan/src/bind/rate_map.rs (new)` | `rare`: a rate map quality sample outside [0, 1] among others | | `SampleCount` | An axis of more samples, not all equal, than the most measured on a map of its layer count, `max` | every device (this crate's bound: Apple's compile unmeasured or crashing there) | `ours` | 1: `crates/metal2vulkan/src/bind/rate_map.rs (new)` | `rare`: a rate map axis of more distinct samples than measured (9 on one layer, 4 on two) | -## 5. The translation deadline (`Error::Budget`) +## 4. The translation deadline (`Error::Budget`) | Variant | What it blocks | Where | Basis | Sites | Reach | |---|---|---|---|---|---| | `Time` | The attempt's deadline passed | every device (the attempt's deadline, 20 seconds by default) | `ours` | 1: `crates/metal2vulkan-air/src/budget/mod.rs (counted)` | `none`: a translation past its deadline: a defect of ours to fix on any supported input (AGENTS.md: 20 seconds) | -## 6. Devices below the runtime's floor (`floor::BelowFloor`: each `floor::Missing`) +## 5. Devices below the runtime's floor (`floor::BelowFloor`: each `floor::Missing`) | Variant | What it blocks | Where | Basis | Sites | Reach | |---|---|---|---|---|---| @@ -235,7 +220,7 @@ Columns: | `TimeDomain` | A time domain of [`TIME_DOMAINS`] the device does not calibrate (`vkGetPhysicalDeviceCalibrateableTimeDomainsEXT`), as Vulkan names it | devices below the floor, at device creation | `device` | 1: `crates/metal2vulkan-runtime/src/floor.rs (decide)` | `-` | | `SetLayout` | The layout of one of the runtime's descriptor sets, `set` 0 (empty) or 1 (the texture and sampler arrays), which `vkGetDescriptorSetLayoutSupport`... | devices below the floor, at device creation | `device` | 1: `crates/metal2vulkan-runtime/src/arrays.rs (supported)` | `-` | -## 7. The runtime's `Refusal` (`Error::Refused(Refusal)`) +## 6. The runtime's `Refusal` (`Error::Refused(Refusal)`) | Variant | What it blocks | Where | Basis | Sites | Reach | |---|---|---|---|---|---| @@ -324,7 +309,7 @@ Columns: | `VisibilityResultOffset` | A visibility result mode but `Disabled` at an offset that is not a multiple of 8, or whose 8 bytes run past the visibility result buffer | every device (a public call's own check of its arguments) | `metal-documented`: `MTLRenderCommandEncoder.h`: "offset must be a multiple of 8"; Apple's page for `visibilityResultBuffer`: "The GPU stores visibility results as 64-bit integers, so you need to reserve 8 bytes for each visibility result" | 1: `crates/metal2vulkan-runtime/src/render_encoder.rs (set_visibility_result_mode)` | `-` | | `VisibilityResultOffsetTaken` | A visibility result mode but `Disabled` at an offset a mode of the encoder took before, `Disabled` between them or not | every device (a public call's own check of its arguments) | `metal-documented`: Apple's page for `setVisibilityResultMode(_:offset:)`: "You can set a specific offset value only once per render pass"; Metal's validation stops it, "using the same offset (0) in the visibility buffer twice in the same command encoder is not allowed", an Apple M3 Max, macOS 27.0.1, the conformance case `visibility-counting-revisit`, where plain Metal adds the later draws to the result | 1: `crates/metal2vulkan-runtime/src/render_encoder.rs (set_visibility_result_mode)` | `-` | -## 8. The runtime's `Limit` (`Error::Limit(Limit)`) +## 7. The runtime's `Limit` (`Error::Limit(Limit)`) | Variant | What it blocks | Where | Basis | Sites | Reach | |---|---|---|---|---|---| @@ -346,7 +331,7 @@ Columns: | `ExportType` | An export of a handle the device gives, but not in the one form an export takes (`Device::new_exported_block`) | at the device's limit | `device`: its extensions and the buffer's memory requirements | 6: `crates/metal2vulkan-runtime/src/export.rs (new_exported_block)`, `crates/metal2vulkan-runtime/src/import.rs (surface_import)` (+4) | `-` | | `TextureSamples` | A multisample texture of a sample count the device does not make for its format, type and usage | at the device's limit | `device`: the image format query's `sampleCounts` | 1: `crates/metal2vulkan-runtime/src/texture.rs (plan)` | `-` | -## 9. The runtime's `Gap` (`Error::Unsupported(Gap)`) +## 8. The runtime's `Gap` (`Error::Unsupported(Gap)`) | Variant | What it blocks | Where | Basis | Sites | Reach | |---|---|---|---|---|---| @@ -398,36 +383,35 @@ Each refusal's sites, with the function that builds it. - `feature::AgxUnmodeled`: `crates/metal2vulkan/src/lower/simd/agx.rs (unmodeled)` - `feature::StaticInitializer`: `crates/metal2vulkan-air/src/error.rs (from)` - `feature::Recursion`: `crates/metal2vulkan-air/src/canon/mod.rs (recursion, 2 sites)`; `crates/metal2vulkan-air/src/canon/recursion.rs (dynamic_alloca)`; `crates/metal2vulkan-air/src/canon/static_init.rs (run)` -- `feature::DynamicCall`: `crates/metal2vulkan-air/src/canon/devirt.rs (record)`; `crates/metal2vulkan-air/src/canon/devirt.rs (site)`; `crates/metal2vulkan-air/src/canon/devirt.rs (unfolded_decl)`; `crates/metal2vulkan-air/src/canon/mod.rs (post_check)`; `crates/metal2vulkan-air/src/canon/prune.rs (prune_in)`; `crates/metal2vulkan/src/bind/heap.rs (directory_bytes, 3 sites)`; `crates/metal2vulkan/src/lower/select.rs (route_air)` +- `feature::DynamicCall`: `crates/metal2vulkan-air/src/canon/devirt.rs (record)`; `crates/metal2vulkan-air/src/canon/devirt.rs (site)`; `crates/metal2vulkan-air/src/canon/devirt.rs (unfolded_decl)`; `crates/metal2vulkan-air/src/canon/mod.rs (post_check)`; `crates/metal2vulkan-air/src/canon/prune.rs (prune_in)`; `crates/metal2vulkan/src/lower/select.rs (route_air)` - `feature::InlineAsm`: `crates/metal2vulkan-air/src/canon/mod.rs (post_check)` - `feature::Linking`: `crates/metal2vulkan-air/src/canon/link.rs (not_implemented)`; `crates/metal2vulkan-air/src/canon/mod.rs (post_check)`; `crates/metal2vulkan-air/src/canon/mod.rs (specialize_dynamic)` - `feature::SimdWidth`: `crates/metal2vulkan/src/device/subgroup.rs (subgroup_tier)`; `crates/metal2vulkan/src/lower/simd/mod.rs (finish)` -- `feature::LocalSize`: `crates/metal2vulkan/src/bind/dispatch.rs (regions)` - `feature::PartialThreadgroups`: `crates/metal2vulkan/src/lower/mesh/mod.rs (plan_partial_groups)`; `crates/metal2vulkan/src/lower/select.rs (finish)`; `crates/metal2vulkan/src/lower/simd/divergent.rs (barriers)`; `crates/metal2vulkan/src/pipeline/compile.rs (analyze_one)` - `feature::IrreducibleConvergent`: `crates/metal2vulkan/src/structurize/irreducible.rs (refuse_tangled)` - `feature::ComputeDerivativesWithSimd`: `crates/metal2vulkan/src/lower/dispatch.rs (plan_kernel)` -- `feature::ComputeDerivatives`: `crates/metal2vulkan/src/bind/dispatch.rs (check_local)`; `crates/metal2vulkan/src/lower/sync/barrier.rs (select_derivative, 3 sites)` +- `feature::ComputeDerivatives`: `crates/metal2vulkan/src/lower/sync/barrier.rs (select_derivative, 3 sites)` - `feature::QuadOperations`: `crates/metal2vulkan/src/device/subgroup.rs (subgroup_tier)` - `feature::SimdgroupMatrix`: `crates/metal2vulkan/src/lower/simd/matrix.rs (not_implemented)` - `feature::SimdgroupMatrix16x16x16`: `crates/metal2vulkan/src/lower/simd/matrix.rs (select)` - `feature::ArgumentBufferPointers`: `crates/metal2vulkan/src/device/metal.rs (unsupported_features)` -- `feature::ArgumentBufferTextures`: `crates/metal2vulkan/src/bind/heap.rs (array)`; `crates/metal2vulkan/src/bind/heap.rs (member_texel_view, 2 sites)`; `crates/metal2vulkan/src/bind/heap.rs (member_view, 4 sites)`; `crates/metal2vulkan/src/bind/heap.rs (new)`; `crates/metal2vulkan/src/lower/access/handle.rs (select)`; `crates/metal2vulkan/src/lower/sampler/select.rs (select_one)`; `crates/metal2vulkan/src/lower/sampler/select.rs (select_sampling)`; `crates/metal2vulkan/src/lower/texture/atomic.rs (select)`; `crates/metal2vulkan/src/lower/texture/slot.rs (declare_heap, 2 sites)`; `crates/metal2vulkan/src/pipeline/link.rs (heap_set)` +- `feature::ArgumentBufferTextures`: `crates/metal2vulkan/src/bind/heap.rs (member_texel_view, 2 sites)`; `crates/metal2vulkan/src/bind/heap.rs (member_view, 4 sites)`; `crates/metal2vulkan/src/lower/access/handle.rs (select)`; `crates/metal2vulkan/src/lower/sampler/select.rs (select_one)`; `crates/metal2vulkan/src/lower/sampler/select.rs (select_sampling)`; `crates/metal2vulkan/src/lower/texture/atomic.rs (select)`; `crates/metal2vulkan/src/lower/texture/slot.rs (declare_heap, 2 sites)`; `crates/metal2vulkan/src/pipeline/link.rs (heap_set)` - `feature::ArgumentBufferObjects`: `crates/metal2vulkan/src/lower/access/icb.rs (select)`; `crates/metal2vulkan/src/lower/access/object.rs (select)`; `crates/metal2vulkan/src/memory/provenance.rs (access)`; `crates/metal2vulkan/src/memory/provenance.rs (classify)` - `feature::DereferenceLoadedPointer`: `crates/metal2vulkan/src/lower/access/dynamic.rs (plan_misses)`; `crates/metal2vulkan/src/lower/access/local.rs (access_ptr)`; `crates/metal2vulkan/src/lower/access/local.rs (threadgroup_constant_refusal)`; `crates/metal2vulkan/src/memory/plan.rs (analyze)` - `feature::PointerToInteger`: `crates/metal2vulkan/src/lower/access/dynamic.rs (require_addresses)` - `feature::PointerCompare`: `crates/metal2vulkan/src/lower/access/copy.rs (addressed)` - `feature::HandleAsPointer`: `crates/metal2vulkan/src/lower/access/handle.rs (domain_kind)`; `crates/metal2vulkan/src/lower/access/handle.rs (element, 2 sites)`; `crates/metal2vulkan/src/memory/plan.rs (reprs)`; `crates/metal2vulkan/src/memory/provenance.rs (classify)`; `crates/metal2vulkan/src/memory/provenance.rs (seed)` - `feature::ConstantGlobalEscaping`: `crates/metal2vulkan/src/memory/plan.rs (blob_nodes)`; `crates/metal2vulkan/src/memory/plan.rs (serialize)` -- `feature::ThreadgroupMemorySize`: `crates/metal2vulkan/src/bind/plan/compute.rs (plan)`; `crates/metal2vulkan/src/memory/arena.rs (check)`; `crates/metal2vulkan/src/memory/plan.rs (too_large)` +- `feature::ThreadgroupMemorySize`: `crates/metal2vulkan/src/memory/arena.rs (check)`; `crates/metal2vulkan/src/memory/plan.rs (too_large)` - `feature::ZeroedThreadgroupMemory`: `crates/metal2vulkan/src/lower/access/local.rs (zero_threadgroup)` - `feature::CoherentMemory`: `crates/metal2vulkan/src/lower/sync/memory_model.rs (check)` - `feature::Int64Atomics`: `crates/metal2vulkan/src/lower/access/atomic.rs (select, 2 sites)` - `feature::ImageAtomics`: `crates/metal2vulkan/src/lower/texture/atomic.rs (select)` - `feature::DescriptorCount`: `crates/metal2vulkan/src/lower/access/mod.rs (accept_placement)`; `crates/metal2vulkan/src/lower/select.rs (finish)`; `crates/metal2vulkan/src/pipeline/link.rs (limit_error)` -- `feature::BufferRange`: `crates/metal2vulkan/src/bind/graphics.rs (patch_binding, 3 sites)`; `crates/metal2vulkan/src/bind/instantiate.rs (bind_buffers)`; `crates/metal2vulkan/src/lower/access/function_table.rs (select)`; `crates/metal2vulkan/src/lower/access/mod.rs (place_slots)` +- `feature::BufferRange`: `crates/metal2vulkan/src/lower/access/function_table.rs (select)`; `crates/metal2vulkan/src/lower/access/mod.rs (place_slots)` - `feature::Int64Arithmetic`: `crates/metal2vulkan/src/lower/arith/legal.rs (check_scalar)`; `crates/metal2vulkan/src/lower/select.rs (selector_form)` - `feature::Float64Arithmetic`: `crates/metal2vulkan/src/device/metal.rs (unsupported_features)`; `crates/metal2vulkan/src/lower/arith/legal.rs (check_scalar)` -- `feature::Format`: `crates/metal2vulkan/src/bind/heap.rs (array)`; `crates/metal2vulkan/src/bind/plan/resources.rs (extended_sampler)`; `crates/metal2vulkan/src/bind/plan/resources.rs (plain_texture, 2 sites)`; `crates/metal2vulkan/src/bind/plan/resources.rs (require_filter_features)`; `crates/metal2vulkan/src/lower/access/tile.rs (storage_format)`; `crates/metal2vulkan/src/lower/fragment/color.rs (select_param, 5 sites)`; `crates/metal2vulkan/src/lower/sampler/select.rs (select_extended)`; `crates/metal2vulkan/src/lower/sampler/select.rs (texel_in)`; `crates/metal2vulkan/src/lower/stage_io/extended_color.rs (plan, 2 sites)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (entry)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (zeroed_output)`; `crates/metal2vulkan/src/lower/stage_io/word_color.rs (plan)`; `crates/metal2vulkan/src/lower/texture/mod.rs (cross_class)`; `crates/metal2vulkan/src/lower/texture/mod.rs (select)`; `crates/metal2vulkan/src/lower/texture/mod.rs (select_image)`; `crates/metal2vulkan/src/lower/texture/mod.rs (select_read_as, 2 sites)`; `crates/metal2vulkan/src/lower/texture/mod.rs (select_write)`; `crates/metal2vulkan/src/lower/texture/slot.rs (atomic_format, 2 sites)`; `crates/metal2vulkan/src/lower/texture/slot.rs (declare_slot, 2 sites)`; `crates/metal2vulkan/src/lower/texture/slot.rs (storage_format, 5 sites)`; `crates/metal2vulkan/src/lower/texture/slot.rs (ulong_format, 3 sites)`; `crates/metal2vulkan/src/metal/format/mod.rs (candidates)`; `crates/metal2vulkan/src/metal/format/mod.rs (held_storage_choice, 3 sites)`; `crates/metal2vulkan/src/metal/format/mod.rs (storage_choice)`; `crates/metal2vulkan/src/metal/format/mod.rs (vk_format, 2 sites)`; `crates/metal2vulkan/src/metal/vertex.rs (fetch_as, 2 sites)`; `crates/metal2vulkan/src/pipeline/color_writes.rs (rotated_blend_in_shader)`; `crates/metal2vulkan/src/pipeline/link/graphics.rs (extended_write_mask, 2 sites)`; `crates/metal2vulkan/src/pipeline/link/graphics.rs (graphics_state, 3 sites)`; `crates/metal2vulkan/src/pipeline/link/graphics.rs (reads_alpha_to_coverage, 2 sites)`; `crates/metal2vulkan/src/pipeline/link/graphics.rs (textured_fetches)`; `crates/metal2vulkan/src/pipeline/rotated_blend.rs (alpha_in_red_blend)`; `crates/metal2vulkan/src/pipeline/rotated_blend.rs (rotated_blend)` +- `feature::Format`: `crates/metal2vulkan/src/lower/access/tile.rs (storage_format)`; `crates/metal2vulkan/src/lower/fragment/color.rs (select_param, 5 sites)`; `crates/metal2vulkan/src/lower/sampler/select.rs (select_extended)`; `crates/metal2vulkan/src/lower/sampler/select.rs (texel_in)`; `crates/metal2vulkan/src/lower/stage_io/extended_color.rs (plan, 2 sites)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (entry)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (zeroed_output)`; `crates/metal2vulkan/src/lower/stage_io/word_color.rs (plan)`; `crates/metal2vulkan/src/lower/texture/mod.rs (cross_class)`; `crates/metal2vulkan/src/lower/texture/mod.rs (select)`; `crates/metal2vulkan/src/lower/texture/mod.rs (select_image)`; `crates/metal2vulkan/src/lower/texture/mod.rs (select_read_as, 2 sites)`; `crates/metal2vulkan/src/lower/texture/mod.rs (select_write)`; `crates/metal2vulkan/src/lower/texture/slot.rs (atomic_format, 2 sites)`; `crates/metal2vulkan/src/lower/texture/slot.rs (declare_slot, 2 sites)`; `crates/metal2vulkan/src/lower/texture/slot.rs (storage_format, 5 sites)`; `crates/metal2vulkan/src/lower/texture/slot.rs (ulong_format, 3 sites)`; `crates/metal2vulkan/src/metal/format/mod.rs (candidates)`; `crates/metal2vulkan/src/metal/format/mod.rs (held_storage_choice, 3 sites)`; `crates/metal2vulkan/src/metal/format/mod.rs (storage_choice)`; `crates/metal2vulkan/src/metal/format/mod.rs (vk_format, 2 sites)`; `crates/metal2vulkan/src/metal/vertex.rs (fetch_as, 2 sites)`; `crates/metal2vulkan/src/pipeline/color_writes.rs (rotated_blend_in_shader)`; `crates/metal2vulkan/src/pipeline/link/graphics.rs (extended_write_mask, 2 sites)`; `crates/metal2vulkan/src/pipeline/link/graphics.rs (graphics_state, 3 sites)`; `crates/metal2vulkan/src/pipeline/link/graphics.rs (reads_alpha_to_coverage, 2 sites)`; `crates/metal2vulkan/src/pipeline/link/graphics.rs (textured_fetches)`; `crates/metal2vulkan/src/pipeline/rotated_blend.rs (alpha_in_red_blend)`; `crates/metal2vulkan/src/pipeline/rotated_blend.rs (rotated_blend)` - `feature::DivergentImplicitLod`: `crates/metal2vulkan/src/lower/sampler/select.rs (tangled)` - `feature::ImplicitLodOutsideFragment`: `crates/metal2vulkan/src/lower/sampler/constexpr.rs (query_min_level)`; `crates/metal2vulkan/src/lower/sampler/select.rs (query_level_measured)`; `crates/metal2vulkan/src/lower/sampler/select.rs (query_min_level)` - `feature::MinLodClamp`: `crates/metal2vulkan/src/lower/sampler/select.rs (min_lod)`; `crates/metal2vulkan/src/lower/sampler/select.rs (select_one)` @@ -436,17 +420,15 @@ Each refusal's sites, with the function that builds it. - `feature::StorageImageMultisample`: `crates/metal2vulkan/src/lower/texture/slot.rs (declare_heap)`; `crates/metal2vulkan/src/lower/texture/slot.rs (declare_slot)` - `feature::StorageTextureInVertexStage`: `crates/metal2vulkan/src/lower/texture/slot.rs (stage_stores)` - `feature::CubeArray`: `crates/metal2vulkan/src/lower/sampler/select.rs (select_one)`; `crates/metal2vulkan/src/lower/texture/slot.rs (declare_heap)` -- `feature::SamplerAnisotropy`: `crates/metal2vulkan/src/metal/sampler.rs (check_argument_sampler)` - `feature::SamplerBorderColor`: `crates/metal2vulkan/src/metal/sampler.rs (border_read, 4 sites)` - `feature::SamplerLodBias`: `crates/metal2vulkan/src/lower/sampler/constexpr.rs (constexpr_desc, 3 sites)` - `feature::SamplerCompare`: `crates/metal2vulkan/src/metal/sampler.rs (check_sampler)` - `feature::PixelSamplerCompare`: `crates/metal2vulkan/src/lower/sampler/constexpr.rs (lowered)` -- `feature::TexelBuffer`: `crates/metal2vulkan/src/bind/instantiate.rs (texel_ranges, 2 sites)`; `crates/metal2vulkan/src/bind/plan/resources.rs (plain_texture)` - `feature::RasterOrderGroups`: `crates/metal2vulkan/src/device/metal.rs (unsupported_features)`; `crates/metal2vulkan/src/lower/fragment/rog.rs (mode, 2 sites)` - `feature::FramebufferFetch`: `crates/metal2vulkan/src/lower/fragment/fetch.rs (computed_write_refused)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs (plan_sample)` - `feature::PrimitiveId`: `crates/metal2vulkan/src/lower/stage_io/plan.rs (finish)`; `crates/metal2vulkan/src/pipeline/link/varyings.rs (check_primitive_id)` - `feature::PrivatePrimitives`: `crates/metal2vulkan/src/lower/stage_io/plan.rs (indices_feature)` -- `feature::VertexAmplification`: `crates/metal2vulkan/src/bind/graphics.rs (multiview_instances)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (index_store)`; `crates/metal2vulkan/src/lower/tessellation/mod.rs (select_param)`; `crates/metal2vulkan/src/pipeline/link/graphics.rs (vertex_amplification)`; `crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs (control_plan)` +- `feature::VertexAmplification`: `crates/metal2vulkan/src/lower/stage_io/plan.rs (index_store)`; `crates/metal2vulkan/src/lower/tessellation/mod.rs (select_param)`; `crates/metal2vulkan/src/pipeline/link/graphics.rs (vertex_amplification)`; `crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs (control_plan)` - `feature::LayeredRendering`: `crates/metal2vulkan/src/lower/mesh/mod.rs (target_index, 2 sites)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (index_store, 2 sites)` - `feature::ClipDistance`: `crates/metal2vulkan/src/lower/mesh/mod.rs (select, 2 sites)` - `feature::DualSourceBlending`: `crates/metal2vulkan/src/metal/state.rs (blend_factor)`; `crates/metal2vulkan/src/pipeline/link/graphics.rs (check_outputs)`; `crates/metal2vulkan/src/pipeline/rotated_blend.rs (rotated_blend)` @@ -462,8 +444,8 @@ Each refusal's sites, with the function that builds it. - `feature::VertexStepRate`: `crates/metal2vulkan/src/metal/vertex.rs (divided)` - `feature::VertexInputLayout`: `crates/metal2vulkan/src/pipeline/link/vertex.rs (resolve, 4 sites)` - `feature::Tessellation`: `crates/metal2vulkan-air/src/canon/mod.rs (post_check, 2 sites)`; `crates/metal2vulkan/src/lower/stage_io/fetch.rs (select)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (input_builtin)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (param)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (primitive_id_output)`; `crates/metal2vulkan/src/lower/tessellation/mod.rs (not_implemented)`; `crates/metal2vulkan/src/lower/tessellation/mod.rs (plan_entry, 2 sites)`; `crates/metal2vulkan/src/metal/vertex.rs (fetch_as)`; `crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs (check_fragment)`; `crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs (control_plan, 2 sites)` -- `feature::MeshShading`: `crates/metal2vulkan/src/bind/graphics.rs (mesh_limit)`; `crates/metal2vulkan/src/bind/graphics.rs (plan)`; `crates/metal2vulkan/src/lower/mesh/mod.rs (check_payload)`; `crates/metal2vulkan/src/lower/mesh/mod.rs (plan_entry, 2 sites)`; `crates/metal2vulkan/src/memory/plan.rs (reprs)` -- `feature::TileShading`: `crates/metal2vulkan/src/bind/plan/compute.rs (tile_memory)`; `crates/metal2vulkan/src/lower/access/tile.rs (not_implemented)`; `crates/metal2vulkan/src/lower/sync/barrier.rs (tile_shading)`; `crates/metal2vulkan/src/pipeline/compile/api.rs (tile_pipeline)` +- `feature::MeshShading`: `crates/metal2vulkan/src/lower/mesh/mod.rs (check_payload)`; `crates/metal2vulkan/src/lower/mesh/mod.rs (plan_entry, 2 sites)`; `crates/metal2vulkan/src/memory/plan.rs (reprs)` +- `feature::TileShading`: `crates/metal2vulkan/src/lower/access/tile.rs (not_implemented)`; `crates/metal2vulkan/src/lower/sync/barrier.rs (tile_shading)`; `crates/metal2vulkan/src/pipeline/compile/api.rs (tile_pipeline)` - `feature::Imageblocks`: `crates/metal2vulkan/src/lower/access/imageblock.rs (imageblocks)`; `crates/metal2vulkan/src/lower/access/mod.rs (select_param)`; `crates/metal2vulkan/src/lower/fragment/mod.rs (select_param)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (entry)`; `crates/metal2vulkan/src/lower/texture/mod.rs (select)`; `crates/metal2vulkan/src/lower/texture/slice.rs (imageblocks)` - `feature::RayTracing`: `crates/metal2vulkan/src/lower/raytracing/mod.rs (instance_count)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs (intersect, 5 sites)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs (primitive_data_read)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs (select_param)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs (slot_of)`; `crates/metal2vulkan/src/lower/select.rs (route_air)` - `feature::Tensors`: `crates/metal2vulkan-air/src/canon/matmul2d/synth.rs (refuse)`; `crates/metal2vulkan/src/lower/select.rs (route_air)` @@ -479,13 +461,12 @@ Each refusal's sites, with the function that builds it. - `feature::SubgroupOperations`: `crates/metal2vulkan/src/lower/simd/mod.rs (full_quads)`; `crates/metal2vulkan/src/lower/simd/mod.rs (select_group)` - `feature::DirectCall`: `crates/metal2vulkan-air/src/canon/mod.rs (post_check)` - `feature::WideSwitchLiteral`: `crates/metal2vulkan/src/structurize/emit.rs (check_tree)` -- `feature::Lowering`: `crates/metal2vulkan/src/bind/plan/resources.rs (level_views)`; `crates/metal2vulkan/src/lower/access/handle.rs (domain_kind)`; `crates/metal2vulkan/src/lower/access/handle.rs (sampler_target)`; `crates/metal2vulkan/src/lower/access/handle.rs (texture_target)`; `crates/metal2vulkan/src/lower/access/imageblock.rs (operand)`; `crates/metal2vulkan/src/lower/access/mod.rs (not_lowered)`; `crates/metal2vulkan/src/lower/access/pulled.rs (share)`; `crates/metal2vulkan/src/lower/arith/legal.rs (not_lowered)`; `crates/metal2vulkan/src/lower/dispatch.rs (not_lowered)`; `crates/metal2vulkan/src/lower/fragment/discard.rs (not_lowered)`; `crates/metal2vulkan/src/lower/fragment/discard.rs (plan)`; `crates/metal2vulkan/src/lower/fragment/mod.rs (not_lowered)`; `crates/metal2vulkan/src/lower/mesh/mod.rs (not_lowered)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs (not_lowered)`; `crates/metal2vulkan/src/lower/sampler/mod.rs (refuse)`; `crates/metal2vulkan/src/lower/sampler/select.rs (refuse)`; `crates/metal2vulkan/src/lower/select.rs (not_lowered)`; `crates/metal2vulkan/src/lower/select.rs (route_air, 2 sites)`; `crates/metal2vulkan/src/lower/simd/mod.rs (not_lowered)`; `crates/metal2vulkan/src/lower/simd/mod.rs (select_param)`; `crates/metal2vulkan/src/lower/simd/workgroup.rs (check)`; `crates/metal2vulkan/src/lower/stage_io/fetch.rs (not_lowered)`; `crates/metal2vulkan/src/lower/stage_io/mod.rs (not_lowered)`; `crates/metal2vulkan/src/lower/sync/barrier.rs (not_lowered)`; `crates/metal2vulkan/src/lower/sync/memory_model.rs (not_implemented)`; `crates/metal2vulkan/src/lower/sync/memory_model.rs (select)`; `crates/metal2vulkan/src/lower/tessellation/mod.rs (not_lowered)`; `crates/metal2vulkan/src/lower/texture/mod.rs (refuse)`; `crates/metal2vulkan/src/lower/texture/mod.rs (select_through)`; `crates/metal2vulkan/src/lower/texture/mod.rs (select_write)`; `crates/metal2vulkan/src/memory/alloca.rs (not_lowered)`; `crates/metal2vulkan/src/memory/leaf.rs (not_lowered)`; `crates/metal2vulkan/src/memory/plan.rs (not_lowered)`; `crates/metal2vulkan/src/memory/provenance.rs (not_lowered)`; `crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs (patch_fetch_projection)` +- `feature::Lowering`: `crates/metal2vulkan/src/lower/access/handle.rs (domain_kind)`; `crates/metal2vulkan/src/lower/access/handle.rs (sampler_target)`; `crates/metal2vulkan/src/lower/access/handle.rs (texture_target)`; `crates/metal2vulkan/src/lower/access/imageblock.rs (operand)`; `crates/metal2vulkan/src/lower/access/mod.rs (not_lowered)`; `crates/metal2vulkan/src/lower/access/pulled.rs (share)`; `crates/metal2vulkan/src/lower/arith/legal.rs (not_lowered)`; `crates/metal2vulkan/src/lower/dispatch.rs (not_lowered)`; `crates/metal2vulkan/src/lower/fragment/discard.rs (not_lowered)`; `crates/metal2vulkan/src/lower/fragment/discard.rs (plan)`; `crates/metal2vulkan/src/lower/fragment/mod.rs (not_lowered)`; `crates/metal2vulkan/src/lower/mesh/mod.rs (not_lowered)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs (not_lowered)`; `crates/metal2vulkan/src/lower/sampler/mod.rs (refuse)`; `crates/metal2vulkan/src/lower/sampler/select.rs (refuse)`; `crates/metal2vulkan/src/lower/select.rs (not_lowered)`; `crates/metal2vulkan/src/lower/select.rs (route_air, 2 sites)`; `crates/metal2vulkan/src/lower/simd/mod.rs (not_lowered)`; `crates/metal2vulkan/src/lower/simd/mod.rs (select_param)`; `crates/metal2vulkan/src/lower/simd/workgroup.rs (check)`; `crates/metal2vulkan/src/lower/stage_io/fetch.rs (not_lowered)`; `crates/metal2vulkan/src/lower/stage_io/mod.rs (not_lowered)`; `crates/metal2vulkan/src/lower/sync/barrier.rs (not_lowered)`; `crates/metal2vulkan/src/lower/sync/memory_model.rs (not_implemented)`; `crates/metal2vulkan/src/lower/sync/memory_model.rs (select)`; `crates/metal2vulkan/src/lower/tessellation/mod.rs (not_lowered)`; `crates/metal2vulkan/src/lower/texture/mod.rs (refuse)`; `crates/metal2vulkan/src/lower/texture/mod.rs (select_through)`; `crates/metal2vulkan/src/lower/texture/mod.rs (select_write)`; `crates/metal2vulkan/src/memory/alloca.rs (not_lowered)`; `crates/metal2vulkan/src/memory/leaf.rs (not_lowered)`; `crates/metal2vulkan/src/memory/plan.rs (not_lowered)`; `crates/metal2vulkan/src/memory/provenance.rs (not_lowered)`; `crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs (patch_fetch_projection)` - `feature::SamplerAddressMode`: `crates/metal2vulkan/src/lower/sampler/constexpr.rs`; `crates/metal2vulkan/src/metal/sampler.rs (check_sampler)` - `feature::AlphaToOne`: `crates/metal2vulkan/src/pipeline/link/graphics.rs (graphics_state)` - `feature::StageStoresAndAtomics`: `crates/metal2vulkan/src/lower/access/tile_memory.rs (written)` - `feature::FunctionConstantArgument`: `crates/metal2vulkan-air/src/canon/interface.rs (absent_values)` -- `feature::SamplerBicubicFilter`: `crates/metal2vulkan/src/bind/heap.rs (new)`; `crates/metal2vulkan/src/bind/plan/resources.rs (bicubic_texels)`; `crates/metal2vulkan/src/bind/plan/slots.rs (cubic_variant)`; `crates/metal2vulkan/src/lower/sampler/bicubic.rs (refuse)`; `crates/metal2vulkan/src/lower/sampler/select.rs (bicubic_refused)` -- `feature::GroupCount`: `crates/metal2vulkan/src/bind/dispatch.rs (2 sites)`; `crates/metal2vulkan/src/bind/dispatch.rs (product)`; `crates/metal2vulkan/src/bind/dispatch.rs (regions)`; `crates/metal2vulkan/src/bind/graphics.rs (mesh_draw)` +- `feature::SamplerBicubicFilter`: `crates/metal2vulkan/src/lower/sampler/bicubic.rs (refuse)`; `crates/metal2vulkan/src/lower/sampler/select.rs (bicubic_refused)` - `feature::IntersectionFunctionTable`: `crates/metal2vulkan/src/lower/raytracing/mod.rs (intersect, 2 sites)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs (null_table)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs (select_table)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs (table_of)`; `crates/metal2vulkan/src/lower/select.rs (route_air)` - `feature::IndependentBlending`: `crates/metal2vulkan/src/pipeline/link/graphics.rs (uniform_blend)` - `feature::RasterSampleCount`: `crates/metal2vulkan/src/pipeline/graphics.rs (sample_count_properties)` @@ -494,26 +475,17 @@ Each refusal's sites, with the function that builds it. - `feature::DepthClipClamp`: `crates/metal2vulkan/src/metal/state.rs (depth_clamp_enable)` - `feature::DepthBiasClamp`: `crates/metal2vulkan/src/metal/state.rs (depth_bias)` - `feature::ConstantAlphaBlendFactor`: `crates/metal2vulkan/src/metal/state.rs (check_constant_alpha)` -- `feature::SparseTexture`: `crates/metal2vulkan/src/bind/plan/slots.rs (check_sparse_textures, 2 sites)` -- `feature::TextureSwizzle`: `crates/metal2vulkan/src/bind/heap.rs (member_texel_view)`; `crates/metal2vulkan/src/bind/plan/resources.rs (plain_texture)`; `crates/metal2vulkan/src/lower/sampler/select.rs (select_one)`; `crates/metal2vulkan/src/lower/texture/mod.rs (select_read_as)`; `crates/metal2vulkan/src/lower/texture/mod.rs (select_write)`; `crates/metal2vulkan/src/lower/texture/slice.rs (select)` +- `feature::TextureSwizzle`: `crates/metal2vulkan/src/bind/heap.rs (member_texel_view)`; `crates/metal2vulkan/src/lower/sampler/select.rs (select_one)`; `crates/metal2vulkan/src/lower/texture/mod.rs (select_read_as)`; `crates/metal2vulkan/src/lower/texture/mod.rs (select_write)`; `crates/metal2vulkan/src/lower/texture/slice.rs (select)` - `feature::PrivateMemory`: `crates/metal2vulkan/src/lower/access/local.rs (device_arena)` - `feature::Reflection`: `crates/metal2vulkan/src/reflection/derive.rs (gap_at)`; `crates/metal2vulkan/src/reflection/derive.rs (read_attributes)`; `crates/metal2vulkan/src/reflection/derive.rs (specialized_reads)`; `crates/metal2vulkan/src/reflection/function.rs (attribute)`; `crates/metal2vulkan/src/reflection/function.rs (module_constants)`; `crates/metal2vulkan/src/reflection/function.rs (unmeasured)`; `crates/metal2vulkan/src/reflection/linked.rs (function)`; `crates/metal2vulkan/src/reflection/mod.rs (kernel_stage)` - `feature::IndirectRenderState`: `crates/metal2vulkan/src/lower/access/pointer.rs (unlowered)`; `crates/metal2vulkan/src/lower/select.rs (param_family)` - `feature::GlobalBuiltinInFragment`: `crates/metal2vulkan/src/lower/select.rs (route_air)` -- `feature::PrivateRenderState`: `crates/metal2vulkan/src/bind/heap.rs (array)`; `crates/metal2vulkan/src/bind/plan/resources.rs (write_rounding)`; `crates/metal2vulkan/src/lower/sampler/select.rs (clamps_reference)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (alpha_test_refused)`; `crates/metal2vulkan/src/lower/texture/mod.rs (mode_rounded_write)`; `crates/metal2vulkan/src/pipeline/private_state.rs (logic_operation)`; `crates/metal2vulkan/src/pipeline/private_state.rs (refused)` +- `feature::PrivateRenderState`: `crates/metal2vulkan/src/lower/sampler/select.rs (clamps_reference)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (alpha_test_refused)`; `crates/metal2vulkan/src/lower/texture/mod.rs (mode_rounded_write)`; `crates/metal2vulkan/src/pipeline/private_state.rs (logic_operation)`; `crates/metal2vulkan/src/pipeline/private_state.rs (refused)` - `feature::ProgramScopeBinding`: `crates/metal2vulkan-air/src/abi/module.rs (decode)`; `crates/metal2vulkan/src/error/mod.rs (from)` - `feature::GenericPointer`: `crates/metal2vulkan-air/src/canon/generic.rs (refuse)`; `crates/metal2vulkan-air/src/canon/generic.rs (refused)` - `feature::SeqCstFence`: `crates/metal2vulkan/src/lower/sync/barrier.rs (require_seq_cst)` - `feature::PostDepthCoverage`: `crates/metal2vulkan/src/lower/stage_io/plan.rs (param)` - `feature::WideLines`: `crates/metal2vulkan/src/pipeline/link/band.rs (plan, 3 sites)` -- `bind::DescriptorRangeExceeded`: `crates/metal2vulkan/src/bind/instantiate.rs (bind_buffers)` -- `bind::TexelBufferTooLarge`: `crates/metal2vulkan/src/bind/instantiate.rs (texel_ranges)` -- `bind::HeapTooLarge`: `crates/metal2vulkan/src/bind/heap.rs (directory_bytes)`; `crates/metal2vulkan/src/bind/heap.rs (listed_sampler_tables)`; `crates/metal2vulkan/src/bind/heap.rs (new, 3 sites)`; `crates/metal2vulkan/src/bind/heap.rs (placed)` -- `bind::TessellationFactorRange`: `crates/metal2vulkan/src/bind/graphics.rs (patch_binding)` -- `bind::PatchIndexRange`: `crates/metal2vulkan/src/bind/graphics.rs (patch_binding)` -- `bind::ControlPointIndexRange`: `crates/metal2vulkan/src/bind/graphics.rs (patch_binding)` -- `bind::MissingStageInRegion`: `crates/metal2vulkan/src/bind/dispatch.rs (instantiate)` -- `bind::MissingDeviceAddress`: `crates/metal2vulkan/src/bind/plan/slots.rs (plan_buffer)` - `limit::InlinedInstructions`: `crates/metal2vulkan-air/src/canon/inline.rs (inline)`; `crates/metal2vulkan-air/src/canon/inline.rs (u32_of)`; `crates/metal2vulkan-air/src/canon/inline.rs (usize_of)` - `limit::OutputBlocks`: `crates/metal2vulkan/src/structurize/irreducible.rs (round)`; `crates/metal2vulkan/src/structurize/mod.rs (structure_loops)`; `crates/metal2vulkan/src/structurize/structurizer_properties/mod.rs (output_cap_is_checked_before_allocating)`; `crates/metal2vulkan/src/structurize/structurizer_properties/trees.rs (the_output_cap_is_checked_before_emission)` - `limit::IrreducibleDepth`: `crates/metal2vulkan-air/src/graph/loops.rs (compute_in)`; `crates/metal2vulkan/src/structurize/structurizer_properties/mod.rs (check_within_depth)`; `crates/metal2vulkan/src/structurize/structurizer_properties/mod.rs (irreducible_nesting_beyond_the_cap_is_refused, 2 sites)` diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md index f0be1c776..e4e9b4582 100644 --- a/docs/VALIDATION.md +++ b/docs/VALIDATION.md @@ -377,7 +377,7 @@ worker under the 20-second and 500-MiB ceilings, resumable in bounded batches (` | `translation --profile P...` | Each row translated for each committed profile, recorded as a typed outcome class under the current product fingerprint (`--current-fingerprint`, `--retry-failures`, `--hash-file PATH` select rows). It fails when a row breaks a ceiling | | `budgets --profile P...` | The budget gates from recorded rows: no row above 20 s or 500 MiB, no stopped worker, and each row's ledger peak at least 0.7 of its allocator peak | | `specialization --profile P...` | Rows translated under planned function-constant value sets and the pipeline inputs their AIR states, not only with none | -| `authored-compile [--bless \| --bless-additions \| --case ID]` | Every committed authored case compiled, with the requests its executor builds, as the runtime compiles them (a kernel for its dispatch's threadgroup size, a draw with no binding plan's variant), on each profile of `corpus/authored-compile.tsv`; it fails on any changed cell. The table is re-blessed on `development` | +| `authored-compile [--bless \| --bless-additions \| --case ID]` | Every committed authored case compiled, with the requests its executor builds, as the runtime compiles them (a kernel for its dispatch's threadgroup size, a draw with no variant), on each profile of `corpus/authored-compile.tsv`; it fails on any changed cell. The table is re-blessed on `development` | | `bitcode-reader` | The bitcode reader's decode compared with `llvm-dis`, and the intrinsic census | | focused audits (`rasterization-rate-maps`, `sample-rate`, `ulong-textures`, `fragment-varyings`, `linked-functions`, `tile-functions`, `mesh-draws`) | One structural family, selected by current facts, translated in batches | @@ -413,7 +413,7 @@ Other corpus tools: - `corpus-pipeline --device-type cpu|gpu --profile P` is driver acceptance (L4), on lavapipe and the real cards. It compiles each row in a compile worker, then asks the device's driver for its - pipeline. A render row's pipeline is created from the binder layout its artifact carries, with + pipeline. A render row's pipeline is created from the pipeline layout its artifact carries, with nothing drawn. A kernel row is made as a guest's kernel is, through the runtime: its `ComputePipelineState` on the one runtime device the sweep opens for all its kernel rows, and one dispatch of one representative threadgroup (the state's thread execution width of threads) @@ -476,8 +476,8 @@ cargo run -p metal2vulkan-validation --release --bin corpus-vulkan -- \ observation for the environment. `--prepare-only` does the CPU side and stops before a device opens, to screen cases. - **The Vulkan candidate** (`corpus-vulkan`, on Linux) translates the - case through the public API in a killable compile worker, executes exactly what the binder plans, - and compares the observations with Metal's. Every context runs under the validation layer and + case through the public API in a killable compile worker, runs it through the runtime, and + compares the observations with Metal's. Every context runs under the validation layer and enables what the runtime enables of the device: no buffer robustness, and the image robustness the device states. - **Through the runtime.** On Linux, without a profile restriction, every kernel case the engine diff --git a/scripts/api-signatures/signatures.py b/scripts/api-signatures/signatures.py index 0ddccd320..5dda73da5 100644 --- a/scripts/api-signatures/signatures.py +++ b/scripts/api-signatures/signatures.py @@ -793,7 +793,7 @@ CRATES = ["metal2vulkan", "metal2vulkan-air", "metal2vulkan-runtime"] # thousands of removals and fails on its own; the floor is what makes a *blessed* collapse loud as # well, so a table of four items cannot pass quietly. It is a long way under the real counts and # is raised only when a crate's surface grows past it. -FLOORS = {"metal2vulkan": 6000, "metal2vulkan-air": 1800, "metal2vulkan-runtime": 25} +FLOORS = {"metal2vulkan": 5000, "metal2vulkan-air": 1800, "metal2vulkan-runtime": 25} HEADER = """\ # The signature-level public surface of metal2vulkan, metal2vulkan-air and metal2vulkan-runtime: one diff --git a/scripts/refusal-surface/reach.tsv b/scripts/refusal-surface/reach.tsv index a8bed7980..ebbf82ad4 100644 --- a/scripts/refusal-surface/reach.tsv +++ b/scripts/refusal-surface/reach.tsv @@ -118,14 +118,6 @@ feature ViewportDepthRange rare viewport depth outside [0, 1] feature IndirectRenderState rare render state set by a kernel on an indirect command feature GlobalBuiltinInFragment rare Metal 3.1 global built-ins in fragment functions feature (computed) none helpers that build a refusal for a feature their callers name: see the "via a helper" rows -bind DescriptorRangeExceeded app a buffer window past a device's descriptor range -bind TexelBufferTooLarge rare a texture buffer past maxTexelBufferElements its parts do not bind -bind HeapTooLarge rare more resident textures than the pipeline's heap holds (bindless at scale) -bind TessellationFactorRange rare tessellation factors past one storage descriptor -bind PatchIndexRange rare patch indices past one storage descriptor -bind ControlPointIndexRange rare control-point indices past one storage descriptor -bind MissingStageInRegion none a stage-in region never set, which Metal leaves undefined -bind MissingDeviceAddress rare a slot reached through a pointer loaded from memory, bound with inline bytes or on a device without device addresses limit InlinedInstructions rare very large shaders after inlining limit OutputBlocks rare very large control flow limit IrreducibleDepth none deeply nested irreducible loops diff --git a/scripts/refusal-surface/refusal_surface.py b/scripts/refusal-surface/refusal_surface.py index f3e4c867b..22ba878ca 100755 --- a/scripts/refusal-surface/refusal_surface.py +++ b/scripts/refusal-surface/refusal_surface.py @@ -8,7 +8,6 @@ The refusal surface is read from the construction sites of the typed refusals, o `Unsupported { .. }` literals, in the `src` of crates/metal2vulkan-air, crates/metal2vulkan and crates/metal2vulkan-runtime; -- the binder's refusals of valid bind states at a device limit (`BindError`); - the translation caps (`Limit`, `Error::LimitExceeded`); - the rasterization-rate maps the compile layer does not compile (`UnpinnedCompile`); - the translation deadline (`BudgetExceeded`, `Error::Budget`); @@ -80,20 +79,6 @@ CONSTRUCTORS = { "needs_any_of": "AnyOf", } -# Binder refusals of a valid bind state: a device limit or an unestablished reading. The other -# `BindError` variants are Metal's own validation (misuse), or carry an `Unsupported` already -# counted under its feature. -BIND_REFUSALS = [ - "DescriptorRangeExceeded", - "TexelBufferTooLarge", - "HeapTooLarge", - "TessellationFactorRange", - "PatchIndexRange", - "ControlPointIndexRange", - "MissingStageInRegion", - "MissingDeviceAddress", -] - REACH_MARKS = OrderedDict( [ ("system", "a guest's CoreAnimation, CoreImage or VideoToolbox plausibly reaches it"), @@ -224,8 +209,6 @@ def derived_basis(section, kinds, table): if "ours" in bases: return "ours" return bases.pop() if len(bases) == 1 else "" - if section == "bind": - return "device" # A cap, the deadline, and a rate map outside the bounds where Apple's compile was measured # (`UnpinnedCompile`: "the bounds are this crate's, not Metal's"). if section in ("limit", "budget", "ratemap"): @@ -559,10 +542,6 @@ def scan(rt_enums=()): if is_pattern(text, m.start(), m.end()): continue rows[(rt_section(enum), m.group(1))]["sites"].append(site(m.start())) - for m in re.finditer(r"\bBindError::([A-Z][A-Za-z0-9_]*)", text): - if m.group(1) not in BIND_REFUSALS or is_pattern(text, m.start(), m.end()): - continue - rows[("bind", m.group(1))]["sites"].append(site(m.start())) for m in re.finditer(r"\bLimit::([A-Z][A-Za-z0-9_]*)", text): if tree == "rt" or is_pattern(text, m.start(), m.end()): continue @@ -781,7 +760,6 @@ def build(rt_enums): fdocs = OrderedDict(enum_variants(CRATES / "metal2vulkan" / "src" / "error" / "mod.rs", "Feature")) for n, d in enum_variants(CRATES / "metal2vulkan-air" / "src" / "error.rs", "Feature"): fdocs.setdefault(n, d) - bdocs = OrderedDict(enum_variants(CRATES / "metal2vulkan" / "src" / "error" / "mod.rs", "BindError")) ldocs = OrderedDict(enum_variants(CRATES / "metal2vulkan-air" / "src" / "error.rs", "Limit")) rdocs = OrderedDict(enum_variants(CRATES / "metal2vulkan" / "src" / "bind" / "rate_map.rs", "UnpinnedCompile")) tdocs = OrderedDict(enum_variants(CRATES / "metal2vulkan-air" / "src" / "error.rs", "BudgetExceeded")) @@ -800,7 +778,6 @@ def build(rt_enums): basis_faults = [] sections = [ ("feature", fdocs, "Translator and front-end refusals (`Unsupported`: a `Feature` and its `Needs`)"), - ("bind", OrderedDict((n, bdocs.get(n, "")) for n in BIND_REFUSALS), "Binder refusals at a device limit (`BindError`)"), ("limit", ldocs, "Translation caps (`Error::LimitExceeded(Limit)`)"), ( "ratemap", @@ -825,8 +802,8 @@ def build(rt_enums): sites = (r["sites"] if r else []) indirect = (r["indirect"] if r else []) conds = sorted(r["conds"]) if r else [] - if section in ("bind", "limit"): - conds = ["at the device's limit" if section == "bind" else "every device (a deterministic cap)"] + if section == "limit": + conds = ["every device (a deterministic cap)"] elif section == "ratemap": conds = ["every device (this crate's bound: Apple's compile unmeasured or crashing there)"] elif section == "budget": @@ -901,7 +878,7 @@ def render(tables): "Every refusal of something Metal accepts, read from the code: the construction sites of the " "typed refusals outside tests (`scripts/refusal-surface/refusal_surface.py`, which writes this " "file; edit its `reach.tsv` and the refusals' own doc comments, never the tables). " - "Section 6 is the runtime's floor: a " + "Section 5 is the runtime's floor: a " "device below it is refused when the device is made, with every item it lacks named. " "The sections after it are the runtime's own typed refusals, one for each enum its " "`Error` carries, every row with its declared basis, which the runtime answers at run time " @@ -944,7 +921,7 @@ def render(tables): lines.append(f" - `{k}`: {v};") lines.append(" - `?`: not assessed yet.") lines.append( - " The floor (section 6) carries no reach mark, as it turns on the device whatever the " + " The floor (section 5) carries no reach mark, as it turns on the device whatever the " "program, and nor do the runtime's refusals after it, each an argument of a public " "call." )