Translator: the resident core deleted; every device compiles the one form, and the tests run it
Every device now compiles the identity domains, the one form: a kernel's
buffer arguments are bound as storage buffers of set 0 where the device
binds them (DeviceProfile::binds_kernel_buffers) and are reached at their
device addresses elsewhere, as every other stage's are; vertex attributes
are fetched by fixed-function vertex input; textures and samplers are
elements of the identity arrays of set 1, named by their resource IDs.
What the one form does not lower is a typed refusal,
Unsupported{IdentityDomains, NotImplemented} with the IdentityCause the
previous commit names.
Deleted, with everything only they reached:
- the device policy (device/policy.rs) that chose the resident-table
domains, and the resident root table, handle table and their facts;
- the heap raw reads (lower/sampler/heap_raw.rs, lower/texture/heap_raw.rs),
sampler footprints, bind/texel_parts.rs and bind/status.rs;
- the lockstep orders' barrier tiers, which no order key adds now
(OrderKey::of orders nothing).
Tests: 274 tests that only the resident-table policy compiled (development's
DevicePolicy::RESIDENT_TABLES, which only tests built) are deleted, among
them 15 whole files (argument tables, cross-class, device replay, dynamic
roots, two extended-range files, image shapes, mesh barriers, profile F,
separate samplers, sparse unmapped, tile, wide, sweep and the footprint
tests); each deletion's reason is listed with the READY. The others are
ported to what the one form compiles and names today: census names,
push fields, refusals with their causes, and run values. A new interpreter
harness (tests/identity_harness.rs) binds a dispatch's buffers at device
addresses and its textures as identity-array elements. Census naming is
unchanged. The validation tests that read compiled modules (coverage,
companions, the authored compile census, specialization) assert the one
form's present strings. The extended-range levels and volume tests, whose
mip filters development built under the resident tables, become two tests
of the one form's answer, which is development's default policy's: a 2D or
3D sample of an extended-range slot texture is refused, TextureState
(lower::texture::identity_class holds no class for it); a padded form's 3D
sample stays the lowering's NotImplemented(Format). Development's new
thread-local test binds through the one form's harness, and its
handle-web test (every_handle_web_an_instruction_observes_is_refused)
compiles on the default profile.
SEMANTICS_VERSION 2355 and ARTIFACT_FORMAT_VERSION 607 (cached
translations and artifacts change). docs/REFUSALS.md is regenerated and
runtime-sources.sha256 is pinned at this tree.
Verified at the stack's tip, which differs from this commit only by the
five commits after it; the jobs and their results are named in the READY.
This commit is contained in:
1 parent
dec0ca173a
commit
0ce2f39b71
421 files changed
+7661
-46214
No files matched your search
@@ -82,11 +82,10 @@ metal2vulkan kernel.ll kernel.spv --profile device.json --emit-meta kernel.json
|
||||
- `--profile` is required: the crate ships no device description. Any Khronos profiles JSON works;
|
||||
[`crates/metal2vulkan-validation/profiles/`](crates/metal2vulkan-validation/profiles) has
|
||||
examples, from a bare Vulkan 1.2 device to desktop GPUs and MoltenVK. A profile compiles under
|
||||
the runtime's policy (`DevicePolicy::default()`, the identity pointer and handle domains), so a
|
||||
profile without `bufferDeviceAddress` and `shaderInt64` is refused. `--device FILE` takes its
|
||||
place with a device description and policy as JSON (`{"description": ..., "policy": ...}`),
|
||||
which is how a runtime's compile device is reproduced: metal2vulkan-runtime's is the
|
||||
description restricted to the features it enables, under that policy.
|
||||
the identity pointer and handle domains, the only form, so a profile without
|
||||
`bufferDeviceAddress` and `shaderInt64` is refused. `--device FILE` takes its place with a
|
||||
device description as JSON (`{"description": ...}`), which is how a runtime's compile device is
|
||||
reproduced: metal2vulkan-runtime's is the description restricted to the features it enables.
|
||||
- Without `--function` it compiles the library's only kernel or vertex function. A kernel with
|
||||
`--color-format` compiles as a tile pipeline. A post-tessellation vertex function adds
|
||||
`.tesc.spv` and `.tese.spv` modules; on a device without `tessellationShader` it answers
|
||||
@@ -117,13 +116,13 @@ The flow follows Metal's object lifecycle: describe the device, parse a library,
|
||||
pipeline, then plan and instantiate each dispatch or draw.
|
||||
|
||||
```rust,ignore
|
||||
use metal2vulkan::device::{Device, DeviceDescription, DevicePolicy};
|
||||
use metal2vulkan::device::{Device, DeviceDescription};
|
||||
use metal2vulkan::library::Library;
|
||||
use metal2vulkan::pipeline::{ComputePipelineDescriptor, FunctionDescriptor, StageSource};
|
||||
use metal2vulkan::Budget;
|
||||
|
||||
let description = DeviceDescription::from_khronos_json(&profile_json, None)?;
|
||||
let device = Device::from_queries(description, DevicePolicy::default())?;
|
||||
let device = Device::from_queries(description)?;
|
||||
let library = Library::parse(&metallib_bytes)?;
|
||||
let kernel = FunctionDescriptor::new(library.function("my_kernel")?);
|
||||
let descriptor = ComputePipelineDescriptor::new(StageSource::Function(kernel));
|
||||
|
||||
@@ -1403,15 +1403,12 @@ fn the_copy_moves_every_byte_in_whole_threadgroups() {
|
||||
assert_eq!(copy_dispatches(4112), [(0, 1, 256), (4096, 1, 1)]);
|
||||
}
|
||||
|
||||
/// The fixture's two cells kernels on lavapipe's `Device::from_queries` profile. Under the
|
||||
/// resident-table domains both observe their threadgroup partition with
|
||||
/// partial threadgroups through the lockstep order's barriers, which stand past the bounds test,
|
||||
/// so they are SIMD-group barriers, as in the row-indexed kernels the fixture stands for. Under the
|
||||
/// identity domains (the runtime's), whose kernels take no lockstep order, neither observes it,
|
||||
/// plain or with partial threadgroups.
|
||||
/// The fixture's two cells kernels on lavapipe's `Device::from_queries` profile, whose kernels take
|
||||
/// no lockstep order: neither observes its threadgroup partition, plain or with partial
|
||||
/// threadgroups.
|
||||
#[test]
|
||||
fn the_cells_kernels_observe_their_partition_only_under_the_lockstep_order() {
|
||||
use metal2vulkan::device::{Device, DeviceDescription, DevicePolicy};
|
||||
fn the_cells_kernels_observe_no_threadgroup_partition() {
|
||||
use metal2vulkan::device::{Device, DeviceDescription};
|
||||
use metal2vulkan::library::Library;
|
||||
use metal2vulkan::pipeline::{FunctionDescriptor, LoweringInputs, StageEntries};
|
||||
let air = match crate::authored::library_air() {
|
||||
@@ -1423,9 +1420,7 @@ fn the_cells_kernels_observe_their_partition_only_under_the_lockstep_order() {
|
||||
};
|
||||
let json = include_str!("../../metal2vulkan-validation/profiles/lavapipe.json");
|
||||
let description = DeviceDescription::from_khronos_json(json, None).unwrap();
|
||||
let resident =
|
||||
Device::from_queries(description.clone(), DevicePolicy::RESIDENT_TABLES).unwrap();
|
||||
let identity = Device::from_queries(description, DevicePolicy::default()).unwrap();
|
||||
let identity = Device::from_queries(description).unwrap();
|
||||
let library = Library::from_air(&air).unwrap();
|
||||
let budget = metal2vulkan::Budget::standard();
|
||||
let mut partial = LoweringInputs::new();
|
||||
@@ -1437,7 +1432,6 @@ fn the_cells_kernels_observe_their_partition_only_under_the_lockstep_order() {
|
||||
(device.kernel_observes_partition(&function, inputs, &budget, &entries))
|
||||
.unwrap_or_else(|why| panic!("{name}: {why}"))
|
||||
};
|
||||
assert!(observes(&resident, &partial), "{name}: the partial variant");
|
||||
let own = (identity.compile_function(&function, &LoweringInputs::new(), &budget))
|
||||
.unwrap_or_else(|why| panic!("{name}: {why}"));
|
||||
assert!(
|
||||
|
||||
@@ -2380,9 +2380,8 @@ made, with no lock, and never rewritten for layouts.
|
||||
- A texture buffer held as words is read (through a sampler too, and where the function observes
|
||||
its residency), written and asked its width through the words. Its other accesses have no own
|
||||
view to take: the translator refuses, on a device that holds some format as words, a function
|
||||
that reads or writes a texture buffer in another numeric class than its texture's
|
||||
(`LoweringInputs::cross_class`, which the runtime never sets), reads an sRGB texture buffer's
|
||||
codes or writes fewer than four lanes; MSL reaches none of them.
|
||||
that reads an sRGB texture buffer's codes or writes fewer than four lanes; MSL reaches
|
||||
neither.
|
||||
- `replace_region` and `get_bytes` of a texture without named bytes go through the staging region:
|
||||
a copy Metal does not make, counted in `Metrics::bytes_copied`.
|
||||
- A blit copy between textures of a compressed region of whole blocks that ends inside one
|
||||
@@ -4449,10 +4448,15 @@ cache is answered compile-required on both.
|
||||
imageblocks from the Apple4 family, and both its guests, x86-64 and arm64, answer no Apple
|
||||
family;
|
||||
- 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`; the draw's `InstanceCount` or `BaseVertexInstance`; a stage-in stride,
|
||||
`StageInStride`; and the others the translator pushes beside the identity fields): no test
|
||||
yet;
|
||||
encoder value the function reads as F", `F` the `PushField`): a descriptor-form slot's residual
|
||||
bind offset on a device whose kernels do not bind their buffers, `SlotBindOffset`; a bound
|
||||
instance acceleration structure's `InstanceCount`; the draw's `BaseVertexInstance`; a
|
||||
stage-in stride, `StageInStride`; a fragment function's depth clamp range, `DepthClampRange`;
|
||||
a vertex amplification's `AmplificationId`, `AmplificationLayerOffset` and
|
||||
`AmplificationViewportOffset`; the primitive ID's `VerticesPerPrimitive`,
|
||||
`CaptureIndexAddress` and `CaptureLayout`; a merged draw replay's `MergedDrawAddress`; a
|
||||
device-replay dispatch's `ReplayRegionAddress`; 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
|
||||
@@ -4473,7 +4477,10 @@ cache is answered compile-required on both.
|
||||
the word of the sampler's resource ID (docs/API.md, Accepted differences): the translator test
|
||||
`under_the_identity_domains_a_runtime_samplers_query_reads_its_pushed_word`;
|
||||
- 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`): no test yet;
|
||||
or sampler beyond its resource ID (F)", `F` the `RuntimeFact`): a sparse texture's residency,
|
||||
`SparseTexture`; a cube's view shape, `ImageViewShape`; a storage texture's numeric type that
|
||||
nothing in the function states, `StorageTextureNumericType`; and a texture's swizzle,
|
||||
`TextureSwizzle`: no test yet;
|
||||
- the residency of a sparse operation on a texture that is not sparse (the `sparse_color` of
|
||||
`sparse_sample`, `sparse_gather` or `sparse_read`): the golden table holds the refusal
|
||||
(`engine/a2_sparse_status`);
|
||||
@@ -4491,8 +4498,8 @@ cache is answered compile-required on both.
|
||||
`a_bicubic_kernel_reads_each_slots_format_treatment_from_its_pushed_field` asserts the text;
|
||||
- a bicubic sample of an extended-range texture through `address::repeat` with a constant texel
|
||||
offset: the golden table holds the refusal (`engine/xr_bicubic`'s `xrb_repeat_offset`);
|
||||
- an argument buffer's texture of a type the identity arrays hold no element of (a texture
|
||||
buffer's parts, a cube read as an array, level views, a two-plane, extended-range, RGBX or
|
||||
- an argument buffer's texture of a type the identity arrays hold no element of (a cube read as
|
||||
an array, level views, a two-plane, extended-range, RGBX or
|
||||
`ulong` form, or a storage texture with a format), one read through another numeric type than its
|
||||
own or as the raw texels of an extended-range member, a read of one that decodes an
|
||||
extended-range member, and a handle that reads its table entry beyond its element: no test
|
||||
@@ -4501,9 +4508,9 @@ cache is answered compile-required on both.
|
||||
or a sampler argument: the golden table holds the refusal (`engine/kernel_read_through`'s
|
||||
`rt_heap_zero`, `rt_heap_ow` and `rt_heap_arg`);
|
||||
- a sequentially consistent fence (`atomic_thread_fence` of `memory_order_seq_cst` beyond the
|
||||
thread, or a `seq_cst` barrier whose memory scope is the device), which the translator
|
||||
orders through a word the identity domains do not reach ("a sequentially consistent
|
||||
fence"): the translator test
|
||||
thread, or a `seq_cst` barrier whose memory scope is the device), which Vulkan has no order
|
||||
for (its memory model reads `SequentiallyConsistent` as acquire-release) ("a sequentially
|
||||
consistent fence"): the translator test
|
||||
`a_seq_cst_fence_is_refused_naming_its_form_under_the_identity_domains` asserts the text.
|
||||
|
||||
The states-only plays of the 26 kept replay streams on lavapipe, each making every pipeline state
|
||||
|
||||
@@ -30,7 +30,7 @@ use crate::submit_calls::SubmitCalls;
|
||||
use crate::times::{StampPools, Ticks};
|
||||
use crate::visibility::OcclusionPools;
|
||||
use ash::vk;
|
||||
use metal2vulkan::device::{ApiVersion, DeviceDescription, DevicePolicy};
|
||||
use metal2vulkan::device::{ApiVersion, DeviceDescription};
|
||||
use metal2vulkan::metal::{ArgumentBuffersTier, ReadWriteTextureTier};
|
||||
use std::cell::Cell;
|
||||
use std::collections::HashMap;
|
||||
@@ -51,11 +51,11 @@ use std::time::{Duration, Instant};
|
||||
///
|
||||
/// The runtime runs four threads: the block-maker, which makes the pool's allocations ahead of need
|
||||
/// and the runtime's fixed-size internals (the zero source, the parameter ring's blocks and the
|
||||
/// staging region) off every caller's thread, and frees device memory; the submit thread, which runs every scheduled
|
||||
/// handler; the completion thread, which runs every completed handler and listener; and the
|
||||
/// reaper, which frees the semaphores and command pools the others give up, one at a time, so no
|
||||
/// driver free runs on the completion thread. The device is torn down when the last handle is
|
||||
/// dropped: the submit thread submits what is ready and ends what it holds with
|
||||
/// staging region) off every caller's thread, and frees device memory; the submit thread, which
|
||||
/// runs every scheduled handler; the completion thread, which runs every completed handler and
|
||||
/// listener; and the reaper, which frees the semaphores and command pools the others give up, one
|
||||
/// at a time, so no driver free runs on the completion thread. The device is torn down when the
|
||||
/// last handle is dropped: the submit thread submits what is ready and ends what it holds with
|
||||
/// [`CommandBufferError::NotRun`](crate::CommandBufferError::NotRun); the completion thread
|
||||
/// retires the rest as the GPU completes it; the threads are joined; then every allocation is
|
||||
/// freed, after [`BlockMappings::unmap`] for each the consumer mapped, and the
|
||||
@@ -65,8 +65,8 @@ use std::time::{Duration, Instant};
|
||||
/// whose value is reached before the threads end, and every [`BlockMappings`] hook or import
|
||||
/// release the block-maker thread runs, to return: a handler, listener or hook that waits for a
|
||||
/// lock the dropping thread holds never lets the drop return. Where the last handle drops in a
|
||||
/// handler or a listener, the reaper runs the teardown once the handler returns, and the consumer calls
|
||||
/// [`Instance::wait_until_devices_torn_down`](crate::Instance::wait_until_devices_torn_down)
|
||||
/// handler or a listener, the reaper runs the teardown once the handler returns, and the consumer
|
||||
/// calls [`Instance::wait_until_devices_torn_down`](crate::Instance::wait_until_devices_torn_down)
|
||||
/// before it drops its instance or exits. Nothing relies on a static destructor or an `atexit`
|
||||
/// handler: the consumer drops every handle before the process exits, or, where a handle is still
|
||||
/// out, calls [`quiesce`](Device::quiesce) and ends with `_exit`. `exit()` with a live device is
|
||||
@@ -395,7 +395,8 @@ pub(crate) struct Core {
|
||||
pub(crate) constexprs: Mutex<HashMap<(u32, [u64; 2]), Constexpr>>,
|
||||
/// [`Device::minimum_linear_texture_alignment`]'s answers, one per pixel format asked.
|
||||
pub(crate) linear_alignments: Mutex<HashMap<metal2vulkan::metal::PixelFormat, u64>>,
|
||||
/// What a texture buffer's offset and width take ([`Device::minimum_texture_buffer_alignment`]).
|
||||
/// What a texture buffer's offset and width take
|
||||
/// ([`Device::minimum_texture_buffer_alignment`]).
|
||||
pub(crate) texels: crate::texture::TexelLimits,
|
||||
/// The live textures over a buffer in an image of their own (`crate::over`): while there are
|
||||
/// any, the commands track what they write.
|
||||
@@ -552,13 +553,13 @@ impl Device {
|
||||
/// `MTLCreateSystemDefaultDevice`, for the physical device the consumer chose.
|
||||
///
|
||||
/// Checks the floor ([`PhysicalDevice::check`]), then makes one `VkDevice` with the floor's
|
||||
/// features and extensions, each of the optional features and extensions the device has, and each
|
||||
/// of the consumer's extensions ([`DeviceOptions::extensions`]) the device offers with the
|
||||
/// features the consumer needs, and chooses its memory types on it. It takes one queue of the floor's queue
|
||||
/// family for the runtime and, where that family has a second queue, a queue for presenting;
|
||||
/// where it has one, presenting shares the runtime's queue and its lock. It makes one
|
||||
/// allocation of each memory class for blocks, then starts the block-maker thread, the submit
|
||||
/// thread and the completion thread. The block-maker thread's first work, after the call
|
||||
/// features and extensions, each of the optional features and extensions the device has, and
|
||||
/// each of the consumer's extensions ([`DeviceOptions::extensions`]) the device offers with the
|
||||
/// features the consumer needs, and chooses its memory types on it. It takes one queue of the
|
||||
/// floor's queue family for the runtime and, where that family has a second queue, a queue for
|
||||
/// presenting; where it has one, presenting shares the runtime's queue and its lock. It makes
|
||||
/// one allocation of each memory class for blocks, then starts the block-maker thread, the
|
||||
/// submit thread and the completion thread. The block-maker thread's first work, after the call
|
||||
/// returns, is the runtime's fixed-size internals: the zero source (64 KiB), the parameter
|
||||
/// ring's first block (2 MiB) and the staging region (16 MiB). A call that needs one before it
|
||||
/// is made waits for that make, counted in
|
||||
@@ -607,9 +608,8 @@ impl Device {
|
||||
Some(described) => described(description),
|
||||
None => description,
|
||||
};
|
||||
let translator =
|
||||
(metal2vulkan::device::Device::from_queries(description, DevicePolicy::default()))
|
||||
.map_err(Error::translation)?;
|
||||
let translator = (metal2vulkan::device::Device::from_queries(description))
|
||||
.map_err(Error::translation)?;
|
||||
let family = capabilities.queue_family;
|
||||
// SAFETY: as above.
|
||||
let families = unsafe { vk_instance.get_physical_device_queue_family_properties(raw) };
|
||||
@@ -1099,12 +1099,13 @@ impl Device {
|
||||
/// `getDefaultSamplePositions:count:`: where the samples of a pass of `count` samples lie when
|
||||
/// it sets no positions, sample `i` at `i`: Vulkan's standard sample locations, which the
|
||||
/// floor's `standardSampleLocations` makes every pass that sets none rasterize at. At 1, 2, 4
|
||||
/// and 8 samples, the counts [`supports_texture_sample_count`](Device::supports_texture_sample_count)
|
||||
/// can answer, they are Metal's own (an Apple M3 Max, macOS 27.0.1: (0.5, 0.5); (0.75, 0.75),
|
||||
/// (0.25, 0.25); (0.375, 0.125), (0.875, 0.375), (0.125, 0.625), (0.625, 0.875); and an AMD
|
||||
/// Radeon Pro 5300M, macOS 26.7.1, at 8: (0.5625, 0.3125), (0.4375, 0.6875), (0.8125, 0.5625),
|
||||
/// (0.3125, 0.1875), (0.1875, 0.8125), (0.0625, 0.4375), (0.6875, 0.9375), (0.9375, 0.0625)).
|
||||
/// Metal writes the positions into the caller's array; this returns them.
|
||||
/// and 8 samples, the counts
|
||||
/// [`supports_texture_sample_count`](Device::supports_texture_sample_count) can answer, they
|
||||
/// are Metal's own (an Apple M3 Max, macOS 27.0.1: (0.5, 0.5); (0.75, 0.75), (0.25, 0.25);
|
||||
/// (0.375, 0.125), (0.875, 0.375), (0.125, 0.625), (0.625, 0.875); and an AMD Radeon Pro 5300M,
|
||||
/// macOS 26.7.1, at 8: (0.5625, 0.3125), (0.4375, 0.6875), (0.8125, 0.5625), (0.3125, 0.1875),
|
||||
/// (0.1875, 0.8125), (0.0625, 0.4375), (0.6875, 0.9375), (0.9375, 0.0625)). Metal writes the
|
||||
/// positions into the caller's array; this returns them.
|
||||
///
|
||||
/// Err: [`Refusal::DefaultSamplePositions`] for a count the device does not render, where plain
|
||||
/// Metal ends the process.
|
||||
@@ -1181,8 +1182,9 @@ impl Device {
|
||||
/// the runtime for its length. A present in `f` waits only on semaphores whose signal is
|
||||
/// already submitted: the command buffer that presents the image
|
||||
/// ([`CommandBuffer::present_drawable`](crate::CommandBuffer::present_drawable)) is
|
||||
/// scheduled ([`CommandBuffer::wait_until_scheduled`](crate::CommandBuffer::wait_until_scheduled)
|
||||
/// has returned for it, or `f` runs in its scheduled handler).
|
||||
/// scheduled
|
||||
/// ([`CommandBuffer::wait_until_scheduled`](crate::CommandBuffer::wait_until_scheduled) has
|
||||
/// returned for it, or `f` runs in its scheduled handler).
|
||||
pub fn with_present_queue<R>(&self, f: impl FnOnce(vk::Queue) -> R) -> R {
|
||||
let queue = lock(&self.shared.core.queues.present);
|
||||
f(*queue)
|
||||
@@ -1254,11 +1256,12 @@ impl Device {
|
||||
/// Err: [`Limit::BlockLen`](crate::Limit::BlockLen) past the device's largest allocation or
|
||||
/// buffer; [`Limit::BlockIds`](crate::Limit::BlockIds);
|
||||
/// [`Limit::MemoryAllocations`](crate::Limit::MemoryAllocations) where the block takes an
|
||||
/// allocation past the device's count; [`Limit::AllocationNotMapped`](crate::Limit::AllocationNotMapped)
|
||||
/// where the consumer did not map the allocation the take made;
|
||||
/// allocation past the device's count;
|
||||
/// [`Limit::AllocationNotMapped`](crate::Limit::AllocationNotMapped) where the consumer did not
|
||||
/// map the allocation the take made;
|
||||
/// [`Limit::AllocationAddress`](crate::Limit::AllocationAddress) where the device placed the
|
||||
/// allocation the take made off a multiple of 16; [`Error::Vulkan`] where the
|
||||
/// device is out of memory or lost; [`Error::Quiesced`].
|
||||
/// allocation the take made off a multiple of 16; [`Error::Vulkan`] where the device is out of
|
||||
/// memory or lost; [`Error::Quiesced`].
|
||||
pub fn take_block(&self, class: MemoryClass, len: u64) -> Result<Block, Error> {
|
||||
let core = &self.shared.core;
|
||||
if core.closed() {
|
||||
@@ -1271,10 +1274,10 @@ impl Device {
|
||||
}
|
||||
|
||||
/// No Metal counterpart: stops the runtime's threads and its GPU work, for a process that must
|
||||
/// end while a handle of the device is still out. True once the GPU went idle and every thread ended
|
||||
/// within `timeout`; false where the timeout passed first, or the call ran in a handler or a
|
||||
/// listener (the submit thread, which runs the scheduled handlers, and the completion thread,
|
||||
/// which runs the completed handlers and listeners, cannot wait for themselves).
|
||||
/// end while a handle of the device is still out. True once the GPU went idle and every thread
|
||||
/// ended within `timeout`; false where the timeout passed first, or the call ran in a handler
|
||||
/// or a listener (the submit thread, which runs the scheduled handlers, and the completion
|
||||
/// thread, which runs the completed handlers and listeners, cannot wait for themselves).
|
||||
///
|
||||
/// In order, each wait bounded by `timeout`: the submit thread submits what is ready, ends
|
||||
/// every command buffer it holds or has not yet submitted with
|
||||
@@ -1290,8 +1293,9 @@ impl Device {
|
||||
/// it leaves the blob as it was. After it, no runtime thread touches a block,
|
||||
/// unless the call answered false. A thread past the timeout ends alone: the completion
|
||||
/// thread once the GPU completed what was submitted and it retired that, running its
|
||||
/// completed handlers, so what the work held goes then. Such a thread is not joined here; the device's last handle joins
|
||||
/// it, with no deadline, before it destroys anything the thread can reach.
|
||||
/// completed handlers, so what the work held goes then. Such a thread is not joined here; the
|
||||
/// device's last handle joins it, with no deadline, before it destroys anything the thread can
|
||||
/// reach.
|
||||
///
|
||||
/// It frees nothing: every allocation's memory and mapping stays valid until the process ends,
|
||||
/// or until the device's last handle drops, which then frees it without the hook. Later calls
|
||||
@@ -1583,9 +1587,8 @@ fn join(core: &Arc<Core>, threads: Threads) {
|
||||
|
||||
/// The description of `raw` the translator is made of, with what device creation enables of
|
||||
/// `capabilities`: its Vulkan queries alone, so no driver or GPU identity, and no fact measured on
|
||||
/// one, applies. `Device::from_queries` makes the translator of it under the identity domains: a
|
||||
/// buffer argument is the guest's address of the buffer, a push field, and a texture or a sampler
|
||||
/// its resource ID.
|
||||
/// one, applies. `Device::from_queries` makes the translator of it: a buffer argument is the
|
||||
/// guest's address of the buffer, a push field, and a texture or a sampler its resource ID.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
@@ -1896,9 +1899,9 @@ impl Drop for Shared {
|
||||
join(core, left);
|
||||
// The blocks the consumer still holds handles of go back to the pool once the threads
|
||||
// have stopped and the consumer's unmap hook has returned for each allocation
|
||||
// (`halt`), for the core to free; a handle dropped later finds its claim empty. No buffer
|
||||
// of them is left: the consumer's each hold a handle of the device, and the command
|
||||
// buffers that kept one have retired.
|
||||
// (`halt`), for the core to free; a handle dropped later finds its claim empty. No
|
||||
// buffer of them is left: the consumer's each hold a handle of the device, and the
|
||||
// command buffers that kept one have retired.
|
||||
let claims: Vec<Weak<Claim>> = lock(&core.claims).drain().map(|(_, c)| c).collect();
|
||||
let blocks: Vec<Arc<memory::Block>> = (claims.iter())
|
||||
.filter_map(Weak::upgrade)
|
||||
|
||||
@@ -1862,16 +1862,6 @@ pub enum RenderPipelineKind {
|
||||
#[non_exhaustive]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum DrawInputCause {
|
||||
/// A buffer a function reaches through the translator's root table of addresses
|
||||
/// (`PipelineInterface::needs_pointer_translation`), which the runtime does not build: a draw
|
||||
/// pushes each buffer's own device address. Metal's counterpart is a device pointer the
|
||||
/// function reads, which Metal reaches at its `gpuAddress`.
|
||||
PointerTranslation,
|
||||
/// A texture or sampler a function resolves through the translator's handle table
|
||||
/// (`PipelineInterface::needs_handle_translation`), which the runtime does not build: a draw
|
||||
/// pushes each one's resource ID. Metal's counterpart is a texture or sampler the function
|
||||
/// reads, which Metal resolves by its `gpuResourceID`.
|
||||
HandleTranslation,
|
||||
/// A descriptor set of the pipeline's layout that is not the device's: a binding of set 1
|
||||
/// that is not one of the device's texture and sampler arrays, or a binding of another set.
|
||||
/// Metal has no counterpart: it binds every argument by its index.
|
||||
@@ -1932,16 +1922,6 @@ pub enum DrawInputCause {
|
||||
#[non_exhaustive]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum KernelInputKind {
|
||||
/// A buffer the kernel reaches through the translator's root table of addresses
|
||||
/// (`PipelineInterface::needs_pointer_translation`), which the runtime does not build: it
|
||||
/// pushes each buffer's own device address. Metal's counterpart is a device pointer the
|
||||
/// kernel reads, which Metal reaches at its `gpuAddress`.
|
||||
PointerTranslation,
|
||||
/// A texture or sampler the kernel resolves through the translator's handle table
|
||||
/// (`PipelineInterface::needs_handle_translation`), which the runtime does not build: it
|
||||
/// pushes each one's resource ID. Metal's counterpart is a texture or sampler the kernel
|
||||
/// reads, which Metal resolves by its `gpuResourceID`.
|
||||
HandleTranslation,
|
||||
/// A descriptor set of the pipeline's layout that is not the device's: a binding of set 1
|
||||
/// that is not one of the device's texture and sampler arrays, or a binding of another set.
|
||||
/// Metal has no counterpart: it binds every argument by its index.
|
||||
|
||||
@@ -1800,14 +1800,6 @@ pub(crate) fn interface(
|
||||
let subgroups = vk::PipelineShaderStageCreateFlags::REQUIRE_FULL_SUBGROUPS
|
||||
| vk::PipelineShaderStageCreateFlags::ALLOW_VARYING_SUBGROUP_SIZE;
|
||||
let unsupplied = [
|
||||
(
|
||||
translated.needs_pointer_translation,
|
||||
KernelInputKind::PointerTranslation,
|
||||
),
|
||||
(
|
||||
translated.needs_handle_translation,
|
||||
KernelInputKind::HandleTranslation,
|
||||
),
|
||||
(
|
||||
views.is_none()
|
||||
|| !(pipeline.layout.sets.iter())
|
||||
|
||||
@@ -892,8 +892,8 @@ fn constexpr_unstated() -> Error {
|
||||
/// fetching the colours of `arrays` through elements holding 2D array views ([`Draws::arrays`]).
|
||||
///
|
||||
/// Err: [`Gap::RenderPipeline`] of [`RenderPipelineKind::DrawInput`] for a pipeline that reads
|
||||
/// what a draw does not supply, its [`DrawInputCause`] naming what: a function table, a pointer or
|
||||
/// handle translation table, a parameter block longer than a ring chunk, push bytes past the
|
||||
/// what a draw does not supply, its [`DrawInputCause`] naming what: a function 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.
|
||||
fn draws(
|
||||
@@ -902,22 +902,8 @@ fn draws(
|
||||
arrays: u8,
|
||||
) -> Result<(Draws, Numbering), Error> {
|
||||
let translated = &pipeline.interface;
|
||||
let unsupplied = [
|
||||
(
|
||||
translated.needs_pointer_translation,
|
||||
DrawInputCause::PointerTranslation,
|
||||
),
|
||||
(
|
||||
translated.needs_handle_translation,
|
||||
DrawInputCause::HandleTranslation,
|
||||
),
|
||||
(
|
||||
!pipeline.layout.sets.iter().all(of_the_device),
|
||||
DrawInputCause::DescriptorSet,
|
||||
),
|
||||
];
|
||||
if let Some(&(_, cause)) = unsupplied.iter().find(|(reads, _)| *reads) {
|
||||
return Err(draw_input(cause));
|
||||
if !pipeline.layout.sets.iter().all(of_the_device) {
|
||||
return Err(draw_input(DrawInputCause::DescriptorSet));
|
||||
}
|
||||
let table = |stage| match stage {
|
||||
Stage::Vertex => Ok(VERTEX),
|
||||
|
||||
@@ -12,7 +12,7 @@ use crate::floor::{
|
||||
};
|
||||
use ash::vk;
|
||||
use metal2vulkan::device::{
|
||||
Device, DeviceDescription, DevicePolicy, DeviceProfile, EnableSet, VkExtension, VkFeature,
|
||||
Device, DeviceDescription, DeviceProfile, EnableSet, VkExtension, VkFeature,
|
||||
KERNEL_BUFFER_BINDINGS,
|
||||
};
|
||||
use serde_json::Value;
|
||||
@@ -389,7 +389,7 @@ fn read_but_withheld(
|
||||
.map_err(|error| {
|
||||
format!("{name}: the translator's description refuses creation's enables: {error}")
|
||||
})?;
|
||||
let base = Device::from_queries(created.clone(), DevicePolicy::default())
|
||||
let base = Device::from_queries(created.clone())
|
||||
.map_err(|error| format!("{name}: no translator for creation's enables: {error}"))?;
|
||||
let base = facts(base.profile());
|
||||
for &feature in VkFeature::ALL {
|
||||
@@ -405,7 +405,7 @@ fn read_but_withheld(
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let Ok(device) = Device::from_queries(with, DevicePolicy::default()) else {
|
||||
let Ok(device) = Device::from_queries(with) else {
|
||||
continue;
|
||||
};
|
||||
if facts(device.profile()) != base {
|
||||
|
||||
@@ -9,9 +9,8 @@
|
||||
//! `#[cfg(test)]`, and its inline `#[cfg(test)]` modules. A line [`ALLOWED`] lists may hold what
|
||||
//! the scan finds on it, and no other line may: the device type where unified memory is decided,
|
||||
//! the stage cache's key, the translator's `DeviceDescription` and the two readers that fill it,
|
||||
//! the translator's `DevicePolicy`, Vulkan's enums mirrored, the registry of the translator's
|
||||
//! environment variables, the command line's device file, and numbers of a table or a grammar that
|
||||
//! equal a vendor's ID.
|
||||
//! Vulkan's enums mirrored, the registry of the translator's environment variables, the command
|
||||
//! line's device file, and numbers of a table or a grammar that equal a vendor's ID.
|
||||
//!
|
||||
//! A scan cannot see all that rule 2 forbids, and review covers the rest: a policy switch spelled
|
||||
//! as a `bool` field, a constant or a `cfg(feature)` gate reads like any other code, and a `//`
|
||||
@@ -159,12 +158,6 @@ const ALLOWED: &[(&str, &str)] = &[
|
||||
"metal2vulkan/src/device/khronos.rs",
|
||||
"desc.device_type = p.enum_value(\"deviceType\", vk::PhysicalDeviceType::from_name)?;",
|
||||
),
|
||||
// The translator's `DevicePolicy`: its default is the runtime's, and its one other value only
|
||||
// tests build.
|
||||
(
|
||||
"metal2vulkan/src/device/policy.rs",
|
||||
"pub struct DevicePolicy {",
|
||||
),
|
||||
// Vulkan's driver enum, mirrored and converted.
|
||||
(
|
||||
"metal2vulkan/src/vk/generated.rs",
|
||||
|
||||
@@ -129,14 +129,13 @@ mod on_device {
|
||||
for (which, pipeline) in translated {
|
||||
match pipeline {
|
||||
Ok(pipeline) => eprintln!(
|
||||
"{name}: {which}: interface {:?}\nconstants {:?}\ndependencies {:?}\nsets {:?}\nflags {:?} subgroup {:?} blob {}",
|
||||
"{name}: {which}: interface {:?}\nconstants {:?}\ndependencies {:?}\nsets {:?}\nflags {:?} subgroup {:?}",
|
||||
pipeline.interface,
|
||||
pipeline.stage.specialization.constants,
|
||||
pipeline.dependencies,
|
||||
pipeline.layout.sets,
|
||||
pipeline.stage.stage_flags,
|
||||
pipeline.stage.required_subgroup_size,
|
||||
pipeline.stage.constant_blob.is_some(),
|
||||
),
|
||||
Err(refused) => eprintln!("{name}: {which}: refused: {refused}"),
|
||||
}
|
||||
|
||||
@@ -28,9 +28,6 @@ enum Verdict {
|
||||
|
||||
use Verdict::{Applied, Fact, Refused};
|
||||
|
||||
/// The draw's set-0 bindings, which `draws` refuses (`of_the_device`).
|
||||
const SET_0: &str = "a set-0 binding, which draws() refuses";
|
||||
|
||||
const GRAPHICS_STATE: &[(&str, Verdict)] = &[
|
||||
(
|
||||
"topology",
|
||||
@@ -47,7 +44,6 @@ const GRAPHICS_STATE: &[(&str, Verdict)] = &[
|
||||
("alpha_to_one", Applied),
|
||||
("rasterizer_discard", Applied),
|
||||
("dynamic_states", Applied),
|
||||
("input_attachments", Refused(SET_0)),
|
||||
(
|
||||
"max_vertex_amplification_count",
|
||||
Refused("refuse() refuses the descriptor's count other than 1"),
|
||||
@@ -136,18 +132,10 @@ const STAGE_MODULE: &[(&str, Verdict)] = &[
|
||||
),
|
||||
("precision_notes", Applied),
|
||||
("strategies", Fact("a census of the lowering, for coverage")),
|
||||
(
|
||||
"constant_blob",
|
||||
Fact("under the identity domains the module holds its constant data"),
|
||||
),
|
||||
(
|
||||
"rounded_colors",
|
||||
Fact("what the rounding costs, which the module pays"),
|
||||
),
|
||||
(
|
||||
"specialized_notes",
|
||||
Fact("the runtime records every note of precision_notes at creation, these among them"),
|
||||
),
|
||||
("own_pixel_textures", Applied),
|
||||
(
|
||||
"private_bytes",
|
||||
|
||||
@@ -151,7 +151,6 @@ fn main() {
|
||||
"metal2vulkan/src/device/mechanism.rs",
|
||||
"metal2vulkan/src/device/metal.rs",
|
||||
"metal2vulkan/src/device/mod.rs",
|
||||
"metal2vulkan/src/device/policy.rs",
|
||||
"metal2vulkan/src/device/profile.rs",
|
||||
"metal2vulkan/src/device/requirements.rs",
|
||||
"metal2vulkan/src/device/subgroup.rs",
|
||||
|
||||
@@ -1 +1 @@
|
||||
44066e695ea8e4fddb0faea3bc602d1ef37e314cf6716e5d66e14f6715417503
|
||||
7f7dcbcbc4a6b43e2c5fb3e192fbc10f4f1d95fc63eefbaa9ef3e1a5494f3b6f
|
||||
@@ -36,7 +36,7 @@ use crate::worker::compile::{
|
||||
use crate::worker::{Measured, WorkerFailure};
|
||||
use metal2vulkan::device::Independence;
|
||||
use metal2vulkan::device::Requirements;
|
||||
use metal2vulkan::device::{Device, DeviceDescription, DevicePolicy, DeviceProfile, EnableSet};
|
||||
use metal2vulkan::device::{Device, DeviceDescription, DeviceProfile, EnableSet};
|
||||
use metal2vulkan::error::{DescriptorError, Error, RuntimeInput};
|
||||
use metal2vulkan::library::{FunctionConstantValues, Library};
|
||||
use metal2vulkan::pipeline::Stage;
|
||||
@@ -1002,9 +1002,9 @@ pub fn read_at(
|
||||
read
|
||||
}
|
||||
|
||||
/// The profile of an opened description ([`opened_description`]) under the default policy.
|
||||
/// The profile of an opened description ([`opened_description`]).
|
||||
pub fn derived_profile(description: DeviceDescription) -> Result<DeviceProfile, String> {
|
||||
Device::from_queries(description, DevicePolicy::default())
|
||||
Device::from_queries(description)
|
||||
.map(|device| device.profile().clone())
|
||||
.map_err(|error| format!("derive the opened device's profile: {error}"))
|
||||
}
|
||||
@@ -1103,11 +1103,8 @@ mod tests {
|
||||
let Some(bitcode) = fixture("kernel_stage_in.ll") else {
|
||||
return;
|
||||
};
|
||||
let device = Device::from_queries(
|
||||
crate::engine::load_description("moltenvk-m3").unwrap(),
|
||||
DevicePolicy::RESIDENT_TABLES,
|
||||
)
|
||||
.unwrap();
|
||||
let device =
|
||||
Device::from_queries(crate::engine::load_description("moltenvk-m3").unwrap()).unwrap();
|
||||
let undefined = FunctionConstantValues::defaults();
|
||||
let implied = stage_inputs::implied_descriptor(&bitcode, "stage_in_fetch", &undefined)
|
||||
.unwrap()
|
||||
@@ -1466,7 +1463,7 @@ mod tests {
|
||||
] {
|
||||
description.features.remove(&feature);
|
||||
}
|
||||
Device::from_queries(description, DevicePolicy::default()).unwrap()
|
||||
Device::from_queries(description).unwrap()
|
||||
};
|
||||
let compile_on =
|
||||
|device: &Device, entry| compile_row(&bitcode, entry, RowStage::Vertex, device, None);
|
||||
@@ -1672,8 +1669,7 @@ mod tests {
|
||||
/// stage.
|
||||
#[test]
|
||||
fn a_worker_boundary_failure_is_a_stopped_row() {
|
||||
let device =
|
||||
WorkerDevice::new(description("runtime-floor"), DevicePolicy::default()).unwrap();
|
||||
let device = WorkerDevice::new(description("runtime-floor")).unwrap();
|
||||
let worker = CompileWorker::program("/nonexistent/compile-worker");
|
||||
for stage in [RowStage::Kernel, RowStage::Vertex, RowStage::Fragment] {
|
||||
let (row, measured) = compile_row_in_worker(
|
||||
|
||||
@@ -59,7 +59,7 @@ use crate::store::CorpusStore;
|
||||
use crate::translation_audit::CensusKey;
|
||||
use crate::worker::compile::{CompileWorker, NotCompiled, WorkerDevice};
|
||||
use crate::worker::{run_json_within, Measured};
|
||||
use metal2vulkan::device::{DeviceDescription, DevicePolicy};
|
||||
use metal2vulkan::device::DeviceDescription;
|
||||
use rusqlite::{params, Connection};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
@@ -147,11 +147,10 @@ pub struct CensusProfile {
|
||||
}
|
||||
|
||||
impl CensusProfile {
|
||||
/// The committed profile `profile` as the runtime's device describes it, under the default
|
||||
/// policy.
|
||||
/// The committed profile `profile` as the runtime's device describes it.
|
||||
pub fn load(profile: &ProfileStem) -> Result<CensusProfile, String> {
|
||||
let description = crate::engine::runtime_description(&profile.stem)?;
|
||||
let device = WorkerDevice::new(description, DevicePolicy::default())
|
||||
let device = WorkerDevice::new(description)
|
||||
.map_err(|error| format!("{}: {error}", profile.label()))?;
|
||||
let key = profile_key(&CensusKey::engine(
|
||||
&profile.label(),
|
||||
@@ -500,7 +499,7 @@ struct CaseInput<'a> {
|
||||
root: &'a Path,
|
||||
index: &'a Path,
|
||||
case: &'a AuthoredCase,
|
||||
profiles: Vec<(&'a DeviceDescription, &'a DevicePolicy)>,
|
||||
profiles: Vec<&'a DeviceDescription>,
|
||||
}
|
||||
|
||||
/// A case worker's input, as it reads it.
|
||||
@@ -509,7 +508,7 @@ struct CaseInputOwned {
|
||||
root: PathBuf,
|
||||
index: PathBuf,
|
||||
case: AuthoredCase,
|
||||
profiles: Vec<(DeviceDescription, DevicePolicy)>,
|
||||
profiles: Vec<DeviceDescription>,
|
||||
}
|
||||
|
||||
/// A case worker's report: its cells, and how it found the private sources it read.
|
||||
@@ -529,7 +528,7 @@ impl CaseCompiler for CaseWorkers {
|
||||
case,
|
||||
profiles: profiles
|
||||
.iter()
|
||||
.map(|profile| (profile.device.description(), profile.device.policy()))
|
||||
.map(|profile| profile.device.description())
|
||||
.collect(),
|
||||
};
|
||||
let run = run_json_within::<CaseOutput>(
|
||||
@@ -604,8 +603,8 @@ pub fn serve_if_requested() {
|
||||
let devices = input
|
||||
.profiles
|
||||
.into_iter()
|
||||
.map(|(description, policy)| {
|
||||
WorkerDevice::new(description, policy).map_err(|error| error.to_string())
|
||||
.map(|description| {
|
||||
WorkerDevice::new(description).map_err(|error| error.to_string())
|
||||
})
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
let devices = devices.iter().collect::<Vec<_>>();
|
||||
|
||||
@@ -303,11 +303,10 @@ fn run() -> Result<(), String> {
|
||||
}
|
||||
|
||||
/// The compile device of an engine sweep of profile `stem` as the runtime's device describes it
|
||||
/// (`engine::runtime_description`), created under the default policy.
|
||||
/// (`engine::runtime_description`).
|
||||
fn compile_device(stem: &str) -> Result<WorkerDevice, String> {
|
||||
let description = engine::runtime_description(stem)?;
|
||||
WorkerDevice::new(description, metal2vulkan::device::DevicePolicy::default())
|
||||
.map_err(|error| format!("{stem}: {error}"))
|
||||
WorkerDevice::new(description).map_err(|error| format!("{stem}: {error}"))
|
||||
}
|
||||
|
||||
/// What one engine sweep compiles: profile P, and the corpus or the owned fixtures.
|
||||
|
||||
@@ -941,9 +941,6 @@ pub(crate) fn draw_out_of_bounds_run(
|
||||
.iter()
|
||||
.map(|vertex| (vertex.location, vertex.buffer_index)),
|
||||
),
|
||||
resident_roots: pipeline.interface.needs_pointer_translation,
|
||||
handle_table: pipeline.interface.needs_handle_translation,
|
||||
policy: *device.policy(),
|
||||
strategies: &graphics::vertex_module(pipeline)?.strategies,
|
||||
// A render stage reaches its buffers at their addresses or through views checked in
|
||||
// the shader.
|
||||
|
||||
@@ -122,7 +122,6 @@ fn the_runtime_sources_are_the_committed_ones() {
|
||||
("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"),
|
||||
("metal2vulkan/src/lower/arith/aggregate.rs", compile),
|
||||
// The block decode (`bind/block_decode.rs`) and its exact division
|
||||
|
||||
@@ -8,7 +8,7 @@ use crate::check::interface::tests::vertex_buffers_at;
|
||||
use crate::executor_contract::depth_stencil_test;
|
||||
use crate::source::public_sources;
|
||||
use crate::store::CorpusStore;
|
||||
use metal2vulkan::device::{Device, DeviceDescription, DevicePolicy};
|
||||
use metal2vulkan::device::{Device, DeviceDescription};
|
||||
use metal2vulkan::library::FunctionConstantValues;
|
||||
use metal2vulkan_devtools::{fixtures_dir, llvm_assemble, AssembleError};
|
||||
use std::path::Path;
|
||||
@@ -17,7 +17,7 @@ fn device(stem: &str) -> Device {
|
||||
let path = crate::engine::profiles_dir().join(format!("{stem}.json"));
|
||||
let text = std::fs::read_to_string(path).unwrap();
|
||||
let description = DeviceDescription::from_khronos_json(&text, None).unwrap();
|
||||
Device::from_queries(description, DevicePolicy::RESIDENT_TABLES).unwrap()
|
||||
Device::from_queries(description).unwrap()
|
||||
}
|
||||
|
||||
/// The module text a case maps with when its module's stage metadata declares no render target
|
||||
|
||||
@@ -5,17 +5,17 @@ use super::*;
|
||||
use crate::case::ScalarType;
|
||||
use crate::check::admission::NotSupported;
|
||||
use crate::requirement::ToolingRequirement;
|
||||
use metal2vulkan::device::{Device, DeviceDescription, DevicePolicy};
|
||||
use metal2vulkan::device::{Device, DeviceDescription};
|
||||
use metal2vulkan::metal::DataType;
|
||||
use metal2vulkan::pipeline::PrecisionNote;
|
||||
|
||||
mod argument_buffer_members;
|
||||
|
||||
fn device(stem: &str, policy: DevicePolicy) -> Device {
|
||||
fn device(stem: &str) -> Device {
|
||||
let path = crate::engine::profiles_dir().join(format!("{stem}.json"));
|
||||
let text = std::fs::read_to_string(path).unwrap();
|
||||
let description = DeviceDescription::from_khronos_json(&text, None).unwrap();
|
||||
Device::from_queries(description, policy).unwrap()
|
||||
Device::from_queries(description).unwrap()
|
||||
}
|
||||
|
||||
/// A noted verdict is a noted difference unless the C3 reviewed list holds its case under an
|
||||
@@ -923,8 +923,8 @@ fn texture_arrays_bind_each_element_at_its_slot() {
|
||||
|
||||
#[test]
|
||||
fn identity_is_per_profile_and_per_engine_slot() {
|
||||
let a = engine_fingerprint(device("lavapipe", DevicePolicy::RESIDENT_TABLES).profile());
|
||||
let b = engine_fingerprint(device("moltenvk-m3", DevicePolicy::RESIDENT_TABLES).profile());
|
||||
let a = engine_fingerprint(device("lavapipe").profile());
|
||||
let b = engine_fingerprint(device("moltenvk-m3").profile());
|
||||
assert_ne!(a, b);
|
||||
assert_eq!(a.len(), 64);
|
||||
assert_eq!(
|
||||
|
||||
@@ -55,13 +55,13 @@ pub fn compile_kernel(
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use metal2vulkan::device::{DeviceDescription, DevicePolicy};
|
||||
use metal2vulkan::device::DeviceDescription;
|
||||
|
||||
fn device(stem: &str) -> Device {
|
||||
let path = crate::engine::profiles_dir().join(format!("{stem}.json"));
|
||||
let text = std::fs::read_to_string(path).unwrap();
|
||||
let description = DeviceDescription::from_khronos_json(&text, None).unwrap();
|
||||
Device::from_queries(description, DevicePolicy::default()).unwrap()
|
||||
Device::from_queries(description).unwrap()
|
||||
}
|
||||
|
||||
/// A dispatch whose threadgroup has a partial simdgroup runs the kernel's emulated-simdgroups
|
||||
|
||||
@@ -18,11 +18,10 @@ use ash::vk;
|
||||
use metal2vulkan::device::Requirements;
|
||||
use metal2vulkan::pipeline::{PipelineLayout, RenderPipeline, StageModule};
|
||||
|
||||
/// The descriptor-set layouts (with their immutable samplers) and the pipeline layout of one
|
||||
/// The descriptor-set layouts and the pipeline layout of one
|
||||
/// binder `PipelineLayout`, destroyed on every exit path.
|
||||
pub(super) struct LayoutObjects<'a> {
|
||||
device: &'a ash::Device,
|
||||
samplers: Vec<vk::Sampler>,
|
||||
pub(super) set_layouts: Vec<vk::DescriptorSetLayout>,
|
||||
pub(super) pipeline_layout: vk::PipelineLayout,
|
||||
}
|
||||
@@ -38,9 +37,6 @@ impl Drop for LayoutObjects<'_> {
|
||||
for layout in &self.set_layouts {
|
||||
self.device.destroy_descriptor_set_layout(*layout, None);
|
||||
}
|
||||
for sampler in &self.samplers {
|
||||
self.device.destroy_sampler(*sampler, None);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -105,11 +101,8 @@ pub fn opened_worker_device(
|
||||
.clone()
|
||||
.map_err(ExecutorError::Failed)
|
||||
.and_then(|description| {
|
||||
crate::worker::compile::WorkerDevice::new(
|
||||
description,
|
||||
metal2vulkan::device::DevicePolicy::default(),
|
||||
)
|
||||
.map_err(|error| crate::candidate::engine::product_refusal(&error))
|
||||
crate::worker::compile::WorkerDevice::new(description)
|
||||
.map_err(|error| crate::candidate::engine::product_refusal(&error))
|
||||
}))
|
||||
})
|
||||
.map_err(ExecutorError::Failed)?
|
||||
@@ -251,7 +244,7 @@ pub(super) enum LayoutError {
|
||||
}
|
||||
|
||||
impl<'a> LayoutObjects<'a> {
|
||||
/// The descriptor-set layouts (with immutable samplers and binding flags) and the pipeline
|
||||
/// The descriptor-set layouts (with their binding flags) and the pipeline
|
||||
/// layout of `layout`.
|
||||
pub(super) fn create(
|
||||
device: &'a ash::Device,
|
||||
@@ -271,7 +264,6 @@ impl<'a> LayoutObjects<'a> {
|
||||
}
|
||||
let mut objects = LayoutObjects {
|
||||
device,
|
||||
samplers: Vec::new(),
|
||||
set_layouts: Vec::new(),
|
||||
pipeline_layout: vk::PipelineLayout::null(),
|
||||
};
|
||||
@@ -284,40 +276,15 @@ impl<'a> LayoutObjects<'a> {
|
||||
/// the driver refusing an object.
|
||||
fn create_layouts(objects: &mut LayoutObjects<'_>, layout: &PipelineLayout) -> Result<(), String> {
|
||||
for set in &layout.sets {
|
||||
let mut immutable: Vec<Vec<vk::Sampler>> = Vec::with_capacity(set.bindings.len());
|
||||
for binding in &set.bindings {
|
||||
let mut samplers = Vec::new();
|
||||
if let Some(desc) = &binding.immutable_sampler {
|
||||
let mut reduction = vk::SamplerReductionModeCreateInfo::default();
|
||||
let mut border = vk::SamplerBorderColorComponentMappingCreateInfoEXT::default();
|
||||
let info = metal2vulkan::ash_interop::sampler_create_info(
|
||||
desc,
|
||||
&mut reduction,
|
||||
&mut border,
|
||||
);
|
||||
// SAFETY: `info` and its chain are live for the call.
|
||||
let sampler = unsafe { objects.device.create_sampler(&info, None) }
|
||||
.map_err(|error| format!("create immutable sampler: {error}"))?;
|
||||
objects.samplers.push(sampler);
|
||||
samplers = vec![sampler; binding.count as usize];
|
||||
}
|
||||
immutable.push(samplers);
|
||||
}
|
||||
let bindings: Vec<vk::DescriptorSetLayoutBinding<'_>> = set
|
||||
.bindings
|
||||
.iter()
|
||||
.zip(&immutable)
|
||||
.map(|(binding, samplers)| {
|
||||
let info = vk::DescriptorSetLayoutBinding::default()
|
||||
.map(|binding| {
|
||||
vk::DescriptorSetLayoutBinding::default()
|
||||
.binding(binding.binding)
|
||||
.descriptor_type(binding.ty.into())
|
||||
.descriptor_count(binding.count)
|
||||
.stage_flags(binding.stages.into());
|
||||
if samplers.is_empty() {
|
||||
info
|
||||
} else {
|
||||
info.immutable_samplers(samplers)
|
||||
}
|
||||
.stage_flags(binding.stages.into())
|
||||
})
|
||||
.collect();
|
||||
let flags: Vec<vk::DescriptorBindingFlags> =
|
||||
|
||||
@@ -3,7 +3,7 @@ use crate::acceptance::{derived_profile, opened_description};
|
||||
use crate::coverage::ROBUSTNESS_FEATURES;
|
||||
use crate::engine::{committed_profiles, load_description};
|
||||
use metal2vulkan::device::ApiVersion;
|
||||
use metal2vulkan::device::{Device, DevicePolicy};
|
||||
use metal2vulkan::device::Device;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// What a committed profile states that the engine's vocabulary cannot carry, by the names the
|
||||
@@ -418,7 +418,7 @@ fn the_list_enables_what_the_runtime_enables_of_the_description() {
|
||||
assert_eq!(set, crate::engine::runtime_enables(&description), "{stem}");
|
||||
let opened = opened_description(description.clone(), &set)
|
||||
.unwrap_or_else(|error| panic!("{stem}: {error}"));
|
||||
let profile = Device::from_queries(opened, DevicePolicy::default())
|
||||
let profile = Device::from_queries(opened)
|
||||
.unwrap_or_else(|error| panic!("{stem}: {error}"))
|
||||
.profile()
|
||||
.clone();
|
||||
@@ -617,8 +617,7 @@ fn the_list_enables_no_buffer_robustness_and_keeps_the_texel_buffers_update_afte
|
||||
}
|
||||
let opened = opened_description(description.clone(), &set)
|
||||
.unwrap_or_else(|error| panic!("{stem}: {error}"));
|
||||
Device::from_queries(opened, DevicePolicy::default())
|
||||
.unwrap_or_else(|error| panic!("{stem}: {error}"));
|
||||
Device::from_queries(opened).unwrap_or_else(|error| panic!("{stem}: {error}"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -972,8 +971,7 @@ fn a_restricted_context_enables_what_the_runtime_enables_at_its_profiles_version
|
||||
assert_eq!(set, crate::engine::runtime_enables(&description), "{stem}");
|
||||
let opened = opened_description(description.clone(), &set)
|
||||
.unwrap_or_else(|error| panic!("{stem}: {error}"));
|
||||
Device::from_queries(opened, DevicePolicy::default())
|
||||
.unwrap_or_else(|error| panic!("{stem}: {error}"));
|
||||
Device::from_queries(opened).unwrap_or_else(|error| panic!("{stem}: {error}"));
|
||||
for structure in enables.linked.iter().filter(|s| s.core_at(version)) {
|
||||
assert!(
|
||||
structure
|
||||
|
||||
@@ -2,9 +2,8 @@
|
||||
//! ([`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
|
||||
//! input as an input attachment of its color attachment with the by-region self-dependency the
|
||||
//! contract names, and the depth/stencil attachment), the vertex input (static strides, and zero
|
||||
//! ([`create_render_pass`]: every color attachment at its Metal index, and the depth/stencil
|
||||
//! attachment), the vertex input (static strides, and zero
|
||||
//! for a stride the pipeline makes dynamic state; instance divisors through the divisor state),
|
||||
//! the multisample, blend and dynamic states. The caller supplies what the artifact leaves to the
|
||||
//! consumer: each stage's specialization, the draw's topology within the compiled class with the
|
||||
@@ -129,48 +128,33 @@ pub(super) fn has_depth(format: vk::Format) -> bool {
|
||||
}
|
||||
|
||||
/// The render pass of `graphics`: one subpass writing every color attachment at its Metal index
|
||||
/// (`VK_ATTACHMENT_UNUSED` for an absent one), in `COLOR_ATTACHMENT_OPTIMAL` (`GENERAL` for an
|
||||
/// attachment a framebuffer-fetch input also reads, as the input attachment of the same index,
|
||||
/// with the by-region self-dependency of [`FETCH_SELF_DEPENDENCY`]), then the depth/stencil
|
||||
/// attachment ([`depth_stencil_format`]) in `DEPTH_STENCIL_ATTACHMENT_OPTIMAL`. Every attachment
|
||||
/// is loaded before and stored after the subpass. The framebuffer's views are the present color
|
||||
/// attachments in index order, then the depth/stencil one.
|
||||
/// (`VK_ATTACHMENT_UNUSED` for an absent one), in `COLOR_ATTACHMENT_OPTIMAL`, then the
|
||||
/// depth/stencil attachment ([`depth_stencil_format`]) in `DEPTH_STENCIL_ATTACHMENT_OPTIMAL`. Every
|
||||
/// attachment is loaded before and stored after the subpass. The framebuffer's views are the
|
||||
/// present color attachments in index order, then the depth/stencil one.
|
||||
pub(super) fn create_render_pass(
|
||||
device: &ash::Device,
|
||||
graphics: &GraphicsState,
|
||||
) -> Result<vk::RenderPass, GraphicsError> {
|
||||
let samples: vk::SampleCountFlags = graphics.rasterization_samples.into();
|
||||
let fetched = |index: u32| {
|
||||
graphics
|
||||
.input_attachments
|
||||
.iter()
|
||||
.any(|input| input.color_index == index)
|
||||
};
|
||||
let mut attachments = Vec::new();
|
||||
let mut colors = Vec::new();
|
||||
let mut numbers = Vec::new();
|
||||
for (index, state) in graphics.color_attachments.iter().enumerate() {
|
||||
for state in &graphics.color_attachments {
|
||||
let Some(state) = state else {
|
||||
colors.push(
|
||||
vk::AttachmentReference::default()
|
||||
.attachment(vk::ATTACHMENT_UNUSED)
|
||||
.layout(vk::ImageLayout::UNDEFINED),
|
||||
);
|
||||
numbers.push(None);
|
||||
continue;
|
||||
};
|
||||
let layout = if fetched(index as u32) {
|
||||
vk::ImageLayout::GENERAL
|
||||
} else {
|
||||
vk::ImageLayout::COLOR_ATTACHMENT_OPTIMAL
|
||||
};
|
||||
let layout = vk::ImageLayout::COLOR_ATTACHMENT_OPTIMAL;
|
||||
let number = attachments.len() as u32;
|
||||
colors.push(
|
||||
vk::AttachmentReference::default()
|
||||
.attachment(number)
|
||||
.layout(layout),
|
||||
);
|
||||
numbers.push(Some((number, layout)));
|
||||
attachments.push(
|
||||
vk::AttachmentDescription::default()
|
||||
.format(state.format.into())
|
||||
@@ -183,31 +167,6 @@ pub(super) fn create_render_pass(
|
||||
.final_layout(layout),
|
||||
);
|
||||
}
|
||||
let mut inputs = Vec::new();
|
||||
for input in &graphics.input_attachments {
|
||||
let at = input.input_attachment_index as usize;
|
||||
if inputs.len() <= at {
|
||||
inputs.resize(
|
||||
at + 1,
|
||||
vk::AttachmentReference::default()
|
||||
.attachment(vk::ATTACHMENT_UNUSED)
|
||||
.layout(vk::ImageLayout::UNDEFINED),
|
||||
);
|
||||
}
|
||||
let (number, layout) = numbers
|
||||
.get(input.color_index as usize)
|
||||
.copied()
|
||||
.flatten()
|
||||
.ok_or_else(|| {
|
||||
GraphicsError::Unmodelled(format!(
|
||||
"framebuffer-fetch input {} has no color attachment",
|
||||
input.color_index
|
||||
))
|
||||
})?;
|
||||
inputs[at] = vk::AttachmentReference::default()
|
||||
.attachment(number)
|
||||
.layout(layout);
|
||||
}
|
||||
let depth_stencil = depth_stencil_format(graphics)?.map(|format| {
|
||||
let number = attachments.len() as u32;
|
||||
let (depth_op, stencil_op) = (
|
||||
@@ -245,52 +204,19 @@ pub(super) fn create_render_pass(
|
||||
});
|
||||
let mut subpass = vk::SubpassDescription::default()
|
||||
.pipeline_bind_point(vk::PipelineBindPoint::GRAPHICS)
|
||||
.color_attachments(&colors)
|
||||
.input_attachments(&inputs);
|
||||
.color_attachments(&colors);
|
||||
if let Some(reference) = depth_stencil.as_ref() {
|
||||
subpass = subpass.depth_stencil_attachment(reference);
|
||||
}
|
||||
let subpasses = [subpass];
|
||||
// Framebuffer fetch reads the attachment the same subpass writes: the contract's by-region
|
||||
// self-dependency.
|
||||
let scopes = FETCH_SELF_DEPENDENCY;
|
||||
let dependencies = [vk::SubpassDependency::default()
|
||||
.src_subpass(0)
|
||||
.dst_subpass(0)
|
||||
.src_stage_mask(scopes.0)
|
||||
.dst_stage_mask(scopes.0)
|
||||
.src_access_mask(scopes.1)
|
||||
.dst_access_mask(scopes.2)
|
||||
.dependency_flags(vk::DependencyFlags::BY_REGION)];
|
||||
let mut info = vk::RenderPassCreateInfo::default()
|
||||
let info = vk::RenderPassCreateInfo::default()
|
||||
.attachments(&attachments)
|
||||
.subpasses(&subpasses);
|
||||
if !graphics.input_attachments.is_empty() {
|
||||
info = info.dependencies(&dependencies);
|
||||
}
|
||||
// SAFETY: `info` and every array it points at are live for the call.
|
||||
unsafe { device.create_render_pass(&info, None) }
|
||||
.map_err(|error| GraphicsError::Refused(format!("create render pass: {error}")))
|
||||
}
|
||||
|
||||
/// The stages and the source and destination accesses of the self-dependency of a subpass whose
|
||||
/// colors a framebuffer-fetch input reads ([`create_render_pass`]), by region: from the color
|
||||
/// writes to the input attachment reads (a fetch after an earlier draw's writes, or the load
|
||||
/// operations'), and from the fragment shader's reads to the color reads and writes (a write
|
||||
/// after an earlier draw's fetch).
|
||||
pub(super) const FETCH_SELF_DEPENDENCY: (vk::PipelineStageFlags, vk::AccessFlags, vk::AccessFlags) = (
|
||||
vk::PipelineStageFlags::from_raw(
|
||||
vk::PipelineStageFlags::FRAGMENT_SHADER.as_raw()
|
||||
| vk::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT.as_raw(),
|
||||
),
|
||||
vk::AccessFlags::COLOR_ATTACHMENT_WRITE,
|
||||
vk::AccessFlags::from_raw(
|
||||
vk::AccessFlags::INPUT_ATTACHMENT_READ.as_raw()
|
||||
| vk::AccessFlags::COLOR_ATTACHMENT_READ.as_raw()
|
||||
| vk::AccessFlags::COLOR_ATTACHMENT_WRITE.as_raw(),
|
||||
),
|
||||
);
|
||||
|
||||
/// One stage's specialization: its map entries and packed data.
|
||||
pub(super) type Specialization = (Vec<vk::SpecializationMapEntry>, Vec<u8>);
|
||||
|
||||
|
||||
@@ -402,13 +402,10 @@ fn a_restricted_context_runs_only_on_a_device_that_has_and_reports_its_profile()
|
||||
assert_eq!(check(&native, &tools, &queried), Ok(translated.clone()));
|
||||
// A profile is every driver's: the profile on lavapipe's identity and on SwiftShader's is one.
|
||||
let profile_of = |description: &DeviceDescription| {
|
||||
metal2vulkan::device::Device::from_queries(
|
||||
description.clone(),
|
||||
metal2vulkan::device::DevicePolicy::default(),
|
||||
)
|
||||
.expect("device")
|
||||
.profile()
|
||||
.fingerprint()
|
||||
metal2vulkan::device::Device::from_queries(description.clone())
|
||||
.expect("device")
|
||||
.profile()
|
||||
.fingerprint()
|
||||
};
|
||||
let mut swiftshader_native = native.clone();
|
||||
swiftshader_native.driver_id = Some(vk::DriverId::GOOGLE_SWIFTSHADER);
|
||||
|
||||
@@ -76,9 +76,6 @@ pub(super) fn contained(
|
||||
stage: lowered.stage(),
|
||||
slots: lowered.slots(),
|
||||
attributes: &attributes,
|
||||
resident_roots: lowered.reads_resident_roots(),
|
||||
handle_table: lowered.resolves_handles(),
|
||||
policy: *translator.policy(),
|
||||
strategies: lowered.strategies(),
|
||||
robust_views: (lowered.requirements().features)
|
||||
.contains(&metal2vulkan::device::VkFeature::PipelineRobustness),
|
||||
|
||||
@@ -867,8 +867,9 @@ fn an_integer_observation_takes_its_sign_from_the_target() {
|
||||
}
|
||||
|
||||
/// Every companion links with the stage it completes in one engine render pipeline: by user
|
||||
/// key, at the types the two sides state. Under the resident-table domains, which compile the
|
||||
/// mesh and object stages the identity domains refuse.
|
||||
/// key, at the types the two sides state. The mesh companions' pipelines (the launch observer's
|
||||
/// mesh function under its object function, and the payload object under its mesh function) are
|
||||
/// refused: the one form compiles no object or mesh stage.
|
||||
#[test]
|
||||
fn generated_companions_link_with_their_cases_in_the_engine() {
|
||||
use metal2vulkan::library::Library;
|
||||
@@ -885,7 +886,6 @@ fn generated_companions_link_with_their_cases_in_the_engine() {
|
||||
};
|
||||
let device = metal2vulkan::device::Device::from_queries(
|
||||
crate::engine::load_description("lavapipe").unwrap(),
|
||||
metal2vulkan::device::DevicePolicy::RESIDENT_TABLES,
|
||||
)
|
||||
.unwrap();
|
||||
let function = |bitcode: &[u8], entry: &str| {
|
||||
@@ -990,11 +990,7 @@ fn generated_companions_link_with_their_cases_in_the_engine() {
|
||||
descriptor.color_attachments[0] = Some(metal2vulkan::pipeline::ColorAttachmentDescriptor::new(
|
||||
metal2vulkan::metal::PixelFormat::RGBA32Uint,
|
||||
));
|
||||
let linked = device
|
||||
.compile_mesh_pipeline(&descriptor, &metal2vulkan::Budget::standard())
|
||||
.unwrap();
|
||||
// The object, mesh and fragment stages.
|
||||
assert!(linked.stages.len() >= 3, "{}", linked.stages.len());
|
||||
refused_mesh(device.compile_mesh_pipeline(&descriptor, &metal2vulkan::Budget::standard()));
|
||||
|
||||
// The payload object under the mesh function that reads its payload, and that mesh
|
||||
// function's fragment partner.
|
||||
@@ -1018,10 +1014,22 @@ fn generated_companions_link_with_their_cases_in_the_engine() {
|
||||
metal2vulkan::metal::PixelFormat::RGBA32Uint,
|
||||
));
|
||||
}
|
||||
let linked = device
|
||||
.compile_mesh_pipeline(&descriptor, &metal2vulkan::Budget::standard())
|
||||
.unwrap();
|
||||
assert!(linked.stages.len() >= 3, "{}", linked.stages.len());
|
||||
refused_mesh(device.compile_mesh_pipeline(&descriptor, &metal2vulkan::Budget::standard()));
|
||||
}
|
||||
|
||||
/// The one form's refusal of a mesh pipeline: its object and mesh stages are a stage other than a
|
||||
/// kernel, vertex or fragment function (`IdentityCause::ObjectOrMeshStage`).
|
||||
fn refused_mesh<T>(r: Result<T, metal2vulkan::error::Error>) {
|
||||
use metal2vulkan::error::{Cause, Error, IdentityCause};
|
||||
match r {
|
||||
Err(Error::Unsupported(u)) => assert_eq!(
|
||||
u.cause,
|
||||
Some(Cause::Identity(IdentityCause::ObjectOrMeshStage)),
|
||||
"{u}"
|
||||
),
|
||||
Err(e) => panic!("the mesh pipeline: {e}"),
|
||||
Ok(_) => panic!("the mesh pipeline compiled"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The typed spelling is what the Metal oracle loads: `metal-as` assembles it, `metal-opt`
|
||||
|
||||
@@ -227,15 +227,15 @@ fn the_tier_table_derives_a_robustness_off_leg_from_each_profile() {
|
||||
assert_eq!(robustness_off(&none), None);
|
||||
}
|
||||
|
||||
/// A compile records the containment it compiled under, from its profile and its own module:
|
||||
/// both legs of one copy census the same strategy names under the one buffer encoding, checked
|
||||
/// (the shader checks every descriptor view); a kernel that declares no image has none; a texture
|
||||
/// write's image encoding follows the leg's image robustness, and a device that writes a storage
|
||||
/// image only through its declared format (`runtime-floor` without
|
||||
/// `shaderStorageImageWriteWithoutFormat`, below the runtime's floor) needs the texture's format
|
||||
/// first; and a kernel that turns an integer into a pointer (a dynamic root) reaches that memory by
|
||||
/// device address under names of its own, checked in the shader in both legs, as its descriptor
|
||||
/// accesses are.
|
||||
/// A compile records the containment it compiled under, from its profile and its own module.
|
||||
/// lavapipe binds no kernel buffer (`DeviceProfile::binds_kernel_buffers`), so both legs of one
|
||||
/// copy reach both buffers at their device addresses, census the same names and declare no buffer
|
||||
/// variable (`buffers:unused`); a kernel that declares no image has none; a texture write's image
|
||||
/// encoding follows the leg's image robustness, and a device that writes a storage image only
|
||||
/// through its declared format (`runtime-floor` without `shaderStorageImageWriteWithoutFormat`,
|
||||
/// below the runtime's floor) refuses the write, naming the format it lacks; and a kernel that
|
||||
/// turns an integer into a pointer (a dynamic root) reaches that memory by device address under
|
||||
/// names of its own, beside its own accesses at their device addresses.
|
||||
#[test]
|
||||
fn a_compile_records_the_containment_it_compiled_under() {
|
||||
use metal2vulkan_devtools::{engine_dir, fixtures_dir, llvm_assemble};
|
||||
@@ -264,11 +264,21 @@ fn a_compile_records_the_containment_it_compiled_under() {
|
||||
leg("lavapipe", leg_of),
|
||||
)
|
||||
};
|
||||
for leg_of in [Leg::Stated, Leg::RobustnessOff] {
|
||||
assert!(
|
||||
!leg("lavapipe", leg_of).binds_kernel_buffers(),
|
||||
"{leg_of:?}"
|
||||
);
|
||||
}
|
||||
let (stated, off) = (copy(Leg::Stated), copy(Leg::RobustnessOff));
|
||||
assert!(stated.strategies.contains("access.memcpy.dynamic"));
|
||||
assert!(off.strategies.contains("access.memcpy.dynamic"));
|
||||
assert_eq!(stated.containment, encoding(B::Checked, I::Unused));
|
||||
assert_eq!(off.containment, encoding(B::Checked, I::Unused));
|
||||
assert!(stated
|
||||
.strategies
|
||||
.contains("access.memcpy.dynamic.to_psb.from_psb"));
|
||||
assert!(off
|
||||
.strategies
|
||||
.contains("access.memcpy.dynamic.to_psb.from_psb"));
|
||||
assert_eq!(stated.containment, encoding(B::Unused, I::Unused));
|
||||
assert_eq!(off.containment, encoding(B::Unused, I::Unused));
|
||||
|
||||
let write = |stem: &str, leg_of| {
|
||||
compile(
|
||||
@@ -288,22 +298,20 @@ fn a_compile_records_the_containment_it_compiled_under() {
|
||||
assert!(formatted
|
||||
.features
|
||||
.remove(&VkFeature::ShaderStorageImageWriteWithoutFormat));
|
||||
let formatted = metal2vulkan::device::Device::from_queries(
|
||||
formatted,
|
||||
metal2vulkan::device::DevicePolicy::RESIDENT_TABLES,
|
||||
)
|
||||
.unwrap()
|
||||
.profile()
|
||||
.clone();
|
||||
let formatted = metal2vulkan::device::Device::from_queries(formatted)
|
||||
.unwrap()
|
||||
.profile()
|
||||
.clone();
|
||||
match compile_module(
|
||||
&select_write,
|
||||
"a4_select_write",
|
||||
&CaseInputs::defaults(),
|
||||
&formatted,
|
||||
) {
|
||||
Err(CompileError::Refused(reason)) => assert!(
|
||||
reason.starts_with("needs_input StorageTextureFormat"),
|
||||
"{reason}"
|
||||
Err(CompileError::Refused(reason)) => assert_eq!(
|
||||
reason,
|
||||
"unsupported not_implemented IdentityDomains unsupported: IdentityDomains: \
|
||||
StorageTextureFormat; needs NotImplemented"
|
||||
),
|
||||
other => panic!("a4_select_write without formatless writes: {other:?}"),
|
||||
}
|
||||
@@ -330,14 +338,10 @@ fn a_compile_records_the_containment_it_compiled_under() {
|
||||
assert_eq!(
|
||||
round_trip(leg_of),
|
||||
(
|
||||
encoding(B::Checked, I::Unused),
|
||||
[
|
||||
"access.dynamic.load",
|
||||
"access.load.checked",
|
||||
"access.store.checked"
|
||||
]
|
||||
.map(String::from)
|
||||
.into()
|
||||
encoding(B::Unused, I::Unused),
|
||||
["access.dynamic.load", "access.load.psb", "access.store.psb"]
|
||||
.map(String::from)
|
||||
.into()
|
||||
),
|
||||
"{leg_of:?}"
|
||||
);
|
||||
@@ -414,13 +418,10 @@ fn an_image_encoding_names_what_its_device_is_left() {
|
||||
let mut alone = crate::engine::load_description("runtime-floor").unwrap();
|
||||
assert!(alone.features.remove(&VkFeature::RobustImageAccess2));
|
||||
let derive = |description: DeviceDescription| {
|
||||
metal2vulkan::device::Device::from_queries(
|
||||
description,
|
||||
metal2vulkan::device::DevicePolicy::RESIDENT_TABLES,
|
||||
)
|
||||
.unwrap()
|
||||
.profile()
|
||||
.clone()
|
||||
metal2vulkan::device::Device::from_queries(description)
|
||||
.unwrap()
|
||||
.profile()
|
||||
.clone()
|
||||
};
|
||||
let floor = &table
|
||||
.iter()
|
||||
@@ -472,10 +473,8 @@ fn an_image_encoding_names_what_its_device_is_left() {
|
||||
|
||||
/// A vertex case's row compiles under the vertex descriptor its executors draw it with.
|
||||
/// `vertex_varying_triangle` reads two `float2` attributes and binds no buffer. Under its
|
||||
/// descriptor both legs pull them from a storage buffer checked in the shader, as nothing bounds
|
||||
/// fixed-function input outside the identity domains (VUID-vkCmdDraw-None-02721): the row the
|
||||
/// executed module belongs to. A fixture entry's default inputs (no descriptor) declare no buffer
|
||||
/// on either leg.
|
||||
/// descriptor both legs fetch them by fixed-function vertex input, so the module declares no
|
||||
/// buffer, as under a fixture entry's default inputs (no descriptor).
|
||||
#[test]
|
||||
fn a_vertex_case_compiles_under_its_vertex_descriptor() {
|
||||
use crate::case::{AttributeFormat, AttributeInput};
|
||||
@@ -521,7 +520,7 @@ fn a_vertex_case_compiles_under_its_vertex_descriptor() {
|
||||
for leg_of in [Leg::Stated, Leg::RobustnessOff] {
|
||||
assert_eq!(
|
||||
buffers(&inputs, leg(stem, leg_of)),
|
||||
BufferEncoding::Checked,
|
||||
BufferEncoding::Unused,
|
||||
"{stem} {leg_of:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
@@ -619,11 +618,12 @@ fn target(resource: OutOfBoundsResource, form: ContainmentForm) -> OutOfBoundsTa
|
||||
}
|
||||
|
||||
/// The out-of-bounds fixtures (`engine/ob1_*`) compile each target they declare to the form
|
||||
/// and mechanism of the inventory on lavapipe, MoltenVK, and the runtime's floor, in both legs: a
|
||||
/// descriptor view, a texel buffer and a device address checked in the shader on every leg, the
|
||||
/// arena checked nowhere (no profile checks a threadgroup access), and an image left to the
|
||||
/// device's image robustness where enabled. The form is the compiled structure's: every leg views
|
||||
/// the `constant` buffer as a storage buffer.
|
||||
/// and mechanism of the inventory on lavapipe, MoltenVK, and the runtime's floor, in both legs.
|
||||
/// None of them binds a kernel buffer (`DeviceProfile::binds_kernel_buffers`), so every buffer is
|
||||
/// a device address checked in the shader, an atomic one keeping its atomic form; a texel buffer
|
||||
/// is checked in the shader on every leg, the arena nowhere (no profile checks a threadgroup
|
||||
/// access), and an image is left to the device's image robustness where enabled. The form is the
|
||||
/// compiled structure's: a storage or `constant` buffer is reached at its device address.
|
||||
#[test]
|
||||
fn the_out_of_bounds_fixtures_contain_each_target_as_declared() {
|
||||
use metal2vulkan_devtools::{engine_dir, llvm_assemble};
|
||||
@@ -669,25 +669,23 @@ fn the_out_of_bounds_fixtures_contain_each_target_as_declared() {
|
||||
],
|
||||
),
|
||||
];
|
||||
// The mechanism label of each fixture's targets per (stem, leg).
|
||||
let expected = |fixture: &str, _: &str, leg: Leg| -> &str {
|
||||
// The mechanism label of each fixture's targets per leg.
|
||||
let expected = |fixture: &str, leg: Leg| -> &str {
|
||||
match fixture {
|
||||
"ob1_device_address" => "device-address:shader",
|
||||
"ob1_threadgroup" => "arena:unchecked",
|
||||
"ob1_texture" if leg == Leg::RobustnessOff => "image:shader",
|
||||
"ob1_texture" => "image:robust2",
|
||||
"ob1_texel_buffer" => "texel-buffer:shader",
|
||||
_ => "descriptor-view:shader",
|
||||
_ => "device-address:shader",
|
||||
}
|
||||
};
|
||||
// The form each target is exercised as: the declared one, but a buffer as its compiled slot
|
||||
// reaches it. `ob1_uniform_buffer`'s `constant` buffer is a storage buffer, which each thread
|
||||
// reads at its own index: a read whose address may differ between the lanes takes the slot's
|
||||
// storage view on every device.
|
||||
let form = |fixture: &str, _: &str, _: Leg, declared: ContainmentForm| match fixture {
|
||||
"ob1_uniform_buffer" => F::StorageBuffer,
|
||||
// reaches it, at its device address, where an atomic one stays a buffer atomic.
|
||||
let form = |declared: ContainmentForm| match declared {
|
||||
F::StorageBuffer | F::UniformBuffer => F::DeviceAddress,
|
||||
_ => declared,
|
||||
};
|
||||
let mut wrong = Vec::new();
|
||||
for (fixture, targets) in fixtures {
|
||||
let path = engine_dir().join(format!("{fixture}.ll"));
|
||||
let bitcode = llvm_assemble(&path).unwrap_or_else(|error| panic!("{error:?}"));
|
||||
@@ -698,36 +696,32 @@ fn the_out_of_bounds_fixtures_contain_each_target_as_declared() {
|
||||
for entry in table.iter().filter(|entry| {
|
||||
["lavapipe", "moltenvk-m3", "runtime-floor"].contains(&entry.tier.stem.as_str())
|
||||
}) {
|
||||
let label = entry.tier.label();
|
||||
assert!(!entry.profile.binds_kernel_buffers(), "{label}");
|
||||
let compiled = compile_module(&bitcode, fixture, &inputs, &entry.profile)
|
||||
.unwrap_or_else(|error| panic!("{fixture} on {}: {error:?}", entry.tier.label()));
|
||||
let want = expected(fixture, &entry.tier.stem, entry.tier.leg);
|
||||
.unwrap_or_else(|error| panic!("{fixture} on {label}: {error:?}"));
|
||||
let want = expected(fixture, entry.tier.leg);
|
||||
assert_eq!(compiled.out_of_bounds.len(), targets.len());
|
||||
for (contained, declared) in compiled.out_of_bounds.iter().zip(&targets) {
|
||||
assert_eq!(
|
||||
contained.form,
|
||||
form(fixture, &entry.tier.stem, entry.tier.leg, declared.form),
|
||||
"{fixture} on {}",
|
||||
entry.tier.label()
|
||||
);
|
||||
assert_eq!(
|
||||
contained.mechanism.label(),
|
||||
want,
|
||||
"{fixture} on {}",
|
||||
entry.tier.label()
|
||||
);
|
||||
let got = (contained.form, contained.mechanism.label());
|
||||
if got != (form(declared.form), want.to_string()) {
|
||||
wrong.push(format!("{fixture} on {label}: {got:?}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(wrong.is_empty(), "{wrong:#?}");
|
||||
}
|
||||
|
||||
/// The fixtures of the authorable forms (`engine/ob2_*`) compile each target to its form and an
|
||||
/// in-shader check on every committed profile, in both legs: the buffer a loaded pointer reaches is
|
||||
/// a device address the resident set resolves, the thread-local array a typed object checked per
|
||||
/// array level, and the argument buffer's texture array a handle table. A device without device
|
||||
/// addresses or 64-bit integers refuses the loaded pointer, and one without descriptor indexing the
|
||||
/// argument buffer's textures, with what it lacks; every committed profile has them.
|
||||
/// The fixtures of the authorable forms (`engine/ob2_*`) compile each target to its form on every
|
||||
/// committed profile, in both legs: the buffer a loaded pointer reaches is the device address the
|
||||
/// pointer holds, used as given and checked nowhere, the thread-local array a typed object checked
|
||||
/// per array level, and the argument buffer's texture array its resource ids, each index masked
|
||||
/// onto the descriptor arrays in the shader. A device without device addresses or 64-bit integers
|
||||
/// refuses the loaded pointer, and one without descriptor indexing the argument buffer's textures,
|
||||
/// with what it lacks; every committed profile has them.
|
||||
#[test]
|
||||
fn the_ob2_fixtures_contain_each_target_in_the_shader_on_every_profile() {
|
||||
fn the_ob2_fixtures_contain_each_target_by_its_form_on_every_profile() {
|
||||
use metal2vulkan_devtools::{engine_dir, llvm_assemble};
|
||||
use ContainmentForm as F;
|
||||
use OutOfBoundsResource as R;
|
||||
@@ -742,7 +736,7 @@ fn the_ob2_fixtures_contain_each_target_in_the_shader_on_every_profile() {
|
||||
},
|
||||
F::LoadedPointer,
|
||||
),
|
||||
"device-address:shader",
|
||||
"device-address:unchecked",
|
||||
),
|
||||
(
|
||||
"ob2_sized_array",
|
||||
@@ -758,10 +752,11 @@ fn the_ob2_fixtures_contain_each_target_in_the_shader_on_every_profile() {
|
||||
},
|
||||
F::HandleArrayIndex,
|
||||
),
|
||||
"handle-table:shader",
|
||||
"resource-id:shader",
|
||||
),
|
||||
];
|
||||
let mut refused = BTreeSet::new();
|
||||
let mut wrong = Vec::new();
|
||||
for (fixture, declared, mechanism) in fixtures {
|
||||
let path = engine_dir().join(format!("{fixture}.ll"));
|
||||
let bitcode = llvm_assemble(&path).unwrap_or_else(|error| panic!("{error:?}"));
|
||||
@@ -776,12 +771,10 @@ fn the_ob2_fixtures_contain_each_target_in_the_shader_on_every_profile() {
|
||||
let [contained] = compiled.out_of_bounds.as_slice() else {
|
||||
panic!("{fixture} on {label}: {:?}", compiled.out_of_bounds);
|
||||
};
|
||||
assert_eq!(contained.form, declared.form, "{fixture} on {label}");
|
||||
assert_eq!(
|
||||
contained.mechanism.label(),
|
||||
mechanism,
|
||||
"{fixture} on {label}"
|
||||
);
|
||||
let got = (contained.form, contained.mechanism.label());
|
||||
if got != (declared.form, mechanism.to_string()) {
|
||||
wrong.push(format!("{fixture} on {label}: {got:?}"));
|
||||
}
|
||||
}
|
||||
Err(CompileError::Refused(reason)) => {
|
||||
let lacked = match fixture {
|
||||
@@ -798,6 +791,7 @@ fn the_ob2_fixtures_contain_each_target_in_the_shader_on_every_profile() {
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(wrong.is_empty(), "{wrong:#?}");
|
||||
// Every committed profile has device addresses, 64-bit integers and descriptor indexing.
|
||||
assert!(refused.is_empty(), "{refused:?}");
|
||||
}
|
||||
@@ -903,12 +897,14 @@ fn ob3_case(fixture: &str) -> AuthoredCase {
|
||||
|
||||
/// The fixtures of the authorable forms (`engine/ob3_*`) compile, under the inputs their cases
|
||||
/// imply (a vertex descriptor, a stage-input descriptor), each target to its declared form and the
|
||||
/// mechanism of its fetch on every committed profile, in both legs: a vertex input, a control
|
||||
/// point and a stage input are pulled through a descriptor view checked in the shader (outside
|
||||
/// the identity domains nothing bounds fixed-function input); an index buffer is drawn from a
|
||||
/// zero-padded copy; a top-level texture array's index is clamped in the shader. The profiles without `tessellationShader` refuse the control-point draw,
|
||||
/// a post-tessellation vertex function, and those without vertex stores the vertex draws, which
|
||||
/// write memory, each a typed refusal; a control point compiles on every other profile.
|
||||
/// mechanism of its fetch on every committed profile, in both legs: a vertex input is fetched by
|
||||
/// fixed-function vertex input, which nothing bounds; a control point and a stage input are pulled
|
||||
/// from their buffer's device address, checked in the shader (a source buffer keeps its device
|
||||
/// address on every device); an index buffer is drawn from a zero-padded copy; a top-level texture
|
||||
/// array's index is clamped in the shader. The profiles without `tessellationShader` refuse the
|
||||
/// control-point draw, a post-tessellation vertex function, and those without vertex stores the
|
||||
/// vertex draws, which write memory, each a typed refusal; a control point compiles on every other
|
||||
/// profile.
|
||||
#[test]
|
||||
fn the_ob3_fixtures_contain_each_target_by_its_fetch_on_every_profile() {
|
||||
use metal2vulkan_devtools::{engine_dir, llvm_assemble};
|
||||
@@ -931,6 +927,7 @@ fn the_ob3_fixtures_contain_each_target_by_its_fetch_on_every_profile() {
|
||||
})
|
||||
.collect::<BTreeMap<_, _>>();
|
||||
let mut compiled_rows = 0;
|
||||
let mut wrong = Vec::new();
|
||||
for fixture in [
|
||||
"ob3_vertex_input",
|
||||
"ob3_control_point",
|
||||
@@ -954,9 +951,8 @@ fn the_ob3_fixtures_contain_each_target_by_its_fetch_on_every_profile() {
|
||||
_ => None,
|
||||
};
|
||||
let expected = match fixture {
|
||||
"ob3_vertex_input" | "ob3_control_point" | "ob3_stage_input" => {
|
||||
"descriptor-view:shader"
|
||||
}
|
||||
"ob3_vertex_input" => "vertex-input:unchecked",
|
||||
"ob3_control_point" | "ob3_stage_input" => "device-address:shader",
|
||||
// Every device and leg draws from a zero-padded copy.
|
||||
"ob3_index_buffer" => "index-buffer:padded",
|
||||
_ => "handle-array:shader",
|
||||
@@ -967,12 +963,10 @@ fn the_ob3_fixtures_contain_each_target_by_its_fetch_on_every_profile() {
|
||||
let declared = &case.out_of_bounds.as_ref().unwrap().targets;
|
||||
assert_eq!(compiled.out_of_bounds.len(), declared.len());
|
||||
for (contained, target) in compiled.out_of_bounds.iter().zip(declared) {
|
||||
assert_eq!(contained.form, target.form, "{fixture} on {label}");
|
||||
assert_eq!(
|
||||
contained.mechanism.label(),
|
||||
expected,
|
||||
"{fixture} on {label}"
|
||||
);
|
||||
let got = (contained.form, contained.mechanism.label());
|
||||
if got != (target.form, expected.to_string()) {
|
||||
wrong.push(format!("{fixture} on {label}: {got:?}"));
|
||||
}
|
||||
}
|
||||
compiled_rows += 1;
|
||||
}
|
||||
@@ -988,5 +982,6 @@ fn the_ob3_fixtures_contain_each_target_by_its_fetch_on_every_profile() {
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(wrong.is_empty(), "{wrong:#?}");
|
||||
assert!(compiled_rows > 0);
|
||||
}
|
||||
@@ -11,7 +11,7 @@ use crate::check::loop_free::DecodedModule;
|
||||
use crate::engine::{bounded_detail, Outcome};
|
||||
use crate::executor_contract::out_of_bounds::{self, Mechanism};
|
||||
use crate::literal::LiteralResources;
|
||||
use metal2vulkan::device::{Device, DevicePolicy, DeviceProfile};
|
||||
use metal2vulkan::device::{Device, DeviceProfile};
|
||||
use metal2vulkan::error::Error;
|
||||
use metal2vulkan::library::FunctionConstantValues;
|
||||
use metal2vulkan::pipeline::{EntryDescriptor, EntryRef, LoweringInputs};
|
||||
@@ -65,7 +65,7 @@ pub fn committed_profiles() -> Result<Vec<CommittedProfile>, String> {
|
||||
for stem in crate::engine::committed_profiles()? {
|
||||
let description = crate::engine::load_description(&stem)?;
|
||||
let derive = |description: DeviceDescription| {
|
||||
Device::from_queries(description, DevicePolicy::RESIDENT_TABLES)
|
||||
Device::from_queries(description)
|
||||
.map(|device| device.profile().clone())
|
||||
.map_err(|error| format!("{stem}: {error}"))
|
||||
};
|
||||
@@ -105,10 +105,9 @@ fn is_typed_refusal(outcome: &Outcome) -> bool {
|
||||
}
|
||||
|
||||
/// What a module compiles with: the function constants, and the vertex descriptor a vertex
|
||||
/// case's executors draw it with. A vertex function's fetch projection is one of
|
||||
/// its lowering inputs, decided by the descriptor and the profile (on a leg without buffer
|
||||
/// robustness every attribute is pulled from a checked storage buffer, so the module declares
|
||||
/// one), so a case's row compile takes the descriptor its executed module compiled under.
|
||||
/// case's executors draw it with. A vertex function's fetch projection is one of its lowering
|
||||
/// inputs, decided by the descriptor and the profile, so a case's row compile takes the
|
||||
/// descriptor its executed module compiled under.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct CaseInputs {
|
||||
pub constants: FunctionConstantValues,
|
||||
@@ -261,10 +260,6 @@ pub fn compile_module(
|
||||
stage: function.stage(),
|
||||
slots: function.slots(),
|
||||
attributes: &attributes,
|
||||
resident_roots: function.reads_resident_roots(),
|
||||
handle_table: function.resolves_handles(),
|
||||
// Every committed profile's device takes the resident-table domains (`committed_profiles`).
|
||||
policy: DevicePolicy::RESIDENT_TABLES,
|
||||
strategies: function.strategies(),
|
||||
robust_views: (function.requirements().features)
|
||||
.contains(&metal2vulkan::device::VkFeature::PipelineRobustness),
|
||||
|
||||
@@ -11,8 +11,7 @@
|
||||
|
||||
use crate::l3::L3Failure;
|
||||
use metal2vulkan::device::{
|
||||
ApiVersion, DeviceDescription, DevicePolicy, DeviceProfile, EnableSet, Requirements,
|
||||
VkExtension,
|
||||
ApiVersion, DeviceDescription, DeviceProfile, EnableSet, Requirements, VkExtension,
|
||||
};
|
||||
use metal2vulkan::error::{
|
||||
CanonError, Capability, Error, ErrorClass, Feature, InputError, InputErrorKind, InternalKind,
|
||||
@@ -876,9 +875,10 @@ impl BitcodeError {
|
||||
}
|
||||
|
||||
/// What an engine translation worker reads of an indexed row: its identity (its key,
|
||||
/// [`crate::source::SourceRow::key`]), its entry, and where its bitcode comes from. Every lane that translates indexed rows with the engine in a
|
||||
/// worker sends this (the translation census). A row with retained bitcode carries
|
||||
/// no AIR text, so neither the parent holding it nor the worker input holds the text.
|
||||
/// [`crate::source::SourceRow::key`]), its entry, and where its bitcode comes from. Every lane that
|
||||
/// translates indexed rows with the engine in a worker sends this (the translation census). A row
|
||||
/// with retained bitcode carries no AIR text, so neither the parent holding it nor the worker input
|
||||
/// holds the text.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct RowInput<'a> {
|
||||
pub air_sha256: Cow<'a, str>,
|
||||
@@ -992,11 +992,11 @@ pub fn load_profile(stem: &str) -> Result<DeviceProfile, String> {
|
||||
Ok(load_device(stem)?.profile().clone())
|
||||
}
|
||||
|
||||
/// The engine's `Device` for committed profile `stem` under the default policy (the runtime's),
|
||||
/// made of [`runtime_description`]: what the public compile API compiles against (its profile is
|
||||
/// The engine's `Device` for committed profile `stem` (the runtime's), made of
|
||||
/// [`runtime_description`]: what the public compile API compiles against (its profile is
|
||||
/// [`load_profile`]'s).
|
||||
pub fn load_device(stem: &str) -> Result<metal2vulkan::device::Device, String> {
|
||||
metal2vulkan::device::Device::from_queries(runtime_description(stem)?, DevicePolicy::default())
|
||||
metal2vulkan::device::Device::from_queries(runtime_description(stem)?)
|
||||
.map_err(|error| format!("{stem}: {error}"))
|
||||
}
|
||||
|
||||
@@ -1393,13 +1393,10 @@ mod tests {
|
||||
let mut description = load_description("runtime-floor").unwrap();
|
||||
description.limits.max_color_attachments = 4;
|
||||
description.limits.max_fragment_output_attachments = 4;
|
||||
metal2vulkan::device::Device::from_queries(
|
||||
description,
|
||||
metal2vulkan::device::DevicePolicy::default(),
|
||||
)
|
||||
.unwrap()
|
||||
.profile()
|
||||
.clone()
|
||||
metal2vulkan::device::Device::from_queries(description)
|
||||
.unwrap()
|
||||
.profile()
|
||||
.clone()
|
||||
};
|
||||
let lavapipe = load_profile("lavapipe").unwrap();
|
||||
for (stem, profile, expected) in [
|
||||
|
||||
@@ -8,26 +8,24 @@
|
||||
//! - **The form and mechanism** of each target are what its compiled module does with it, never
|
||||
//! only what the case says ([`containment`]): a buffer is a storage buffer through its
|
||||
//! descriptor, or a device address; a buffer slot the product reaches through a descriptor view
|
||||
//! and a slot reached by its device address are checked in the shader in every leg, except that a kernel whose buffer arguments are bound as storage buffers of set 0
|
||||
//! and a slot reached by its device address are checked in the shader in every leg, except that a
|
||||
//! kernel whose buffer arguments are bound as storage buffers of set 0
|
||||
//! (`ModuleFacts::robust_views`) leaves its views' loads and stores to its pipeline's
|
||||
//! `robustBufferAccess2` and checks only their atomics in the shader; a texel buffer and an image follow the product's texel containment
|
||||
//! (`DeviceProfile::device_reads_texels` and `device_drops_texel_writes`): a texel buffer is
|
||||
//! checked in the shader; an image's reads are left to `robustImageAccess2` and its writes to
|
||||
//! `robustImageAccess` at either level, each otherwise checked in the shader. A buffer reached through a pointer loaded from an argument buffer is a
|
||||
//! device address the resident set resolves, a thread-local array a typed object whose index is
|
||||
//! checked against its length, and an argument buffer's texture array a handle table the loaded
|
||||
//! resource id is looked up in: each checked in the shader in every leg. The threadgroup arena is
|
||||
//! checked nowhere: no profile checks a threadgroup access, and one past the memory is undefined,
|
||||
//! as in Metal (docs/API.md, "Threadgroup memory"), so the candidate does not run a case reaching
|
||||
//! past it ([`Check::Unchecked`]). Under the identity
|
||||
//! domains (`DevicePolicy`) a loaded pointer is the address it holds, which nothing checks, so
|
||||
//! the candidate does not run the case ([`Check::Unchecked`]), and a loaded resource id's index
|
||||
//! is masked onto the descriptor arrays, whose elements no live texture owns are null
|
||||
//! descriptors. An attribute buffer is fetched by fixed-function vertex input, which nothing
|
||||
//! bounds ([`Check::Unchecked`]), or pulled in the shader through the slot its fetch names,
|
||||
//! contained as that slot is ([`Fetch`]); a direct
|
||||
//! indexed draw's index buffer is bounded by `robustBufferAccess2` or the binder's clamp; and a
|
||||
//! top-level texture array's dynamic index is clamped onto its elements in the shader.
|
||||
//! `robustBufferAccess2` and checks only their atomics in the shader; a texel buffer and an image
|
||||
//! follow the product's texel containment (`DeviceProfile::device_reads_texels` and
|
||||
//! `device_drops_texel_writes`): a texel buffer is checked in the shader; an image's reads are
|
||||
//! left to `robustImageAccess2` and its writes to `robustImageAccess` at either level, each
|
||||
//! otherwise checked in the shader. A thread-local array is a typed object whose index is checked
|
||||
//! against its length in the shader in every leg. The threadgroup arena is checked nowhere: no profile checks a threadgroup access, and one past the
|
||||
//! memory is undefined, as in Metal (docs/API.md, "Threadgroup memory"), so the candidate does
|
||||
//! not run a case reaching past it ([`Check::Unchecked`]). A loaded pointer is the address it
|
||||
//! holds, which nothing checks, so the candidate does not run the case ([`Check::Unchecked`]),
|
||||
//! and a loaded resource id's index is masked onto the descriptor arrays, whose elements no live
|
||||
//! texture owns are null descriptors. An attribute buffer is fetched by fixed-function vertex
|
||||
//! input, which nothing bounds ([`Check::Unchecked`]), or pulled in the shader through the slot
|
||||
//! its fetch names, contained as that slot is ([`Fetch`]); a direct indexed draw's index buffer
|
||||
//! is bounded by `robustBufferAccess2` or the binder's clamp; and a top-level texture array's
|
||||
//! dynamic index is clamped onto its elements in the shader.
|
||||
//! - **The read rule** ([`read_rule`]) says what an out-of-bounds read of the target may return:
|
||||
//! zero under an in-shader check and under `robustBufferAccess2` (Vulkan's "Robust Buffer
|
||||
//! Access 2": "reads ... outside of the checked range will return zero values"), anything for
|
||||
@@ -54,7 +52,7 @@ use crate::case::{AuthoredCase, OutputSelection};
|
||||
use crate::coverage::ExecutedCensus;
|
||||
use crate::observation_contract::words::{Judgement, WordFacts};
|
||||
use base64::Engine as _;
|
||||
use metal2vulkan::device::{DevicePolicy, DeviceProfile, HandleDomain, PointerDomain};
|
||||
use metal2vulkan::device::DeviceProfile;
|
||||
use metal2vulkan::library::CompiledFunction;
|
||||
use metal2vulkan::pipeline::VertexInputState;
|
||||
use metal2vulkan::pipeline::{AttributeFetch, StrategyCensus};
|
||||
@@ -83,9 +81,9 @@ pub enum Medium {
|
||||
/// The handle table a texture's resource id, loaded from an argument buffer, is looked up in:
|
||||
/// an id of no resident texture is the null handle.
|
||||
HandleTable,
|
||||
/// The descriptor arrays a texture's resource id, loaded from an argument buffer, indexes
|
||||
/// under the identity handle domain (`HandleDomain::Identity`), its index masked onto the
|
||||
/// arrays' elements: an element no live texture owns is the null descriptor.
|
||||
/// The descriptor arrays a texture's resource id, loaded from an argument buffer, indexes, its
|
||||
/// index masked onto the arrays' elements: an element no live texture owns is the null
|
||||
/// descriptor.
|
||||
ResourceId,
|
||||
/// Vulkan's fixed-function vertex input, fetching a vertex buffer binding (only under buffer
|
||||
/// robustness).
|
||||
@@ -121,10 +119,9 @@ pub enum Check {
|
||||
/// position past where Metal's fetch stops reads index 0.
|
||||
Padded,
|
||||
/// Nothing checks the access: neither the shader nor the device's robustness bounds it (a
|
||||
/// pointer loaded from memory under the identity pointer domain, `PointerDomain::Identity`,
|
||||
/// is the device address it holds, used as given; fixed-function vertex input on a device
|
||||
/// without buffer robustness fetches past its buffer what the device gives; and no profile
|
||||
/// checks a threadgroup access). A run would reach
|
||||
/// pointer loaded from memory is the device address it holds, used as given; fixed-function
|
||||
/// vertex input on a device without buffer robustness fetches past its buffer what the device
|
||||
/// gives; and no profile checks a threadgroup access). A run would reach
|
||||
/// memory no binding gave the case, so the candidate refuses the case before it makes the
|
||||
/// pipeline (`NotSupported::Uncontained`).
|
||||
Unchecked,
|
||||
@@ -336,15 +333,6 @@ pub struct ModuleFacts<'a> {
|
||||
/// How the module (for a render pipeline, the pipeline's vertex input with its module) fetches
|
||||
/// each attribute, by Metal attribute index ([`Fetch`]).
|
||||
pub attributes: &'a BTreeMap<u32, Fetch>,
|
||||
/// The module reads the resident root table: it has a device-address slot or a dynamic root
|
||||
/// (`needs_pointer_translation`).
|
||||
pub resident_roots: bool,
|
||||
/// The module resolves texture or sampler handles through the handle table
|
||||
/// (`needs_handle_translation`).
|
||||
pub handle_table: bool,
|
||||
/// The pointer and handle domains of the device the module was compiled for
|
||||
/// (`Device::policy`).
|
||||
pub policy: DevicePolicy,
|
||||
pub strategies: &'a StrategyCensus,
|
||||
/// The module's storage views are contained by its pipeline's robust buffer access 2, not by
|
||||
/// a check in the shader: a kernel whose buffer arguments are bound as storage buffers of set
|
||||
@@ -396,13 +384,12 @@ mod census {
|
||||
/// buffer, and a `device_address` when it reaches it by its address, except that a
|
||||
/// `buffer_atomic` target (one an AIR atomic accesses, which the case checker establishes) stays
|
||||
/// one in every medium. A buffer an argument buffer points to is a `loaded_pointer` when the
|
||||
/// module loads a pointer and accesses memory through it, which the resident table checks and the
|
||||
/// identity pointer domain leaves unchecked ([`Check::Unchecked`]), thread memory a `sized_array`
|
||||
/// when the module indexes a typed thread-local array at a dynamic index, and an argument buffer's
|
||||
/// texture array a `handle_array_index` when the module looks its handles up in the handle table,
|
||||
/// or, under the identity handle domain, masks their ids onto the descriptor arrays. `Err`
|
||||
/// when the module does not access the target, reaches it in a way validation does not know (thread
|
||||
/// memory in the private arena, whose check is the arena's bounds, not the array's).
|
||||
/// module loads a pointer and accesses memory through it, which nothing checks
|
||||
/// ([`Check::Unchecked`]), thread memory a `sized_array` when the module indexes a typed
|
||||
/// thread-local array at a dynamic index, and an argument buffer's texture array a
|
||||
/// `handle_array_index` when the module masks the ids it loads onto the descriptor arrays. `Err`
|
||||
/// when the module does not access the target, reaches it in a way validation does not know
|
||||
/// (thread memory in the private arena, whose check is the arena's bounds, not the array's).
|
||||
pub fn containment(
|
||||
target: &OutOfBoundsTarget,
|
||||
module: &ModuleFacts<'_>,
|
||||
@@ -486,16 +473,10 @@ pub fn containment(
|
||||
OutOfBoundsResource::ArgumentBufferBuffer { buffer_binding, .. } => {
|
||||
slot(SlotClass::Buffer, buffer_binding)?;
|
||||
let accessed = module.uses(census::DYNAMIC_LOAD) || module.uses(census::DYNAMIC_STORE);
|
||||
// Under the resident table the loaded pointer resolves to the resident allocation
|
||||
// holding it, and each access is checked against that allocation's size in the shader,
|
||||
// in every leg. Under the identity pointer domain it is the device address it holds,
|
||||
// used as given: nothing checks the access.
|
||||
let (resolved, check) = match module.policy.pointer_domain {
|
||||
PointerDomain::ResidentTable => (module.resident_roots, Check::Shader),
|
||||
PointerDomain::Identity => (true, Check::Unchecked),
|
||||
_ => return Err("a pointer domain validation does not know".into()),
|
||||
};
|
||||
if !resolved || !module.uses_family(census::LOAD_POINTER) || !accessed {
|
||||
// The loaded pointer is the device address it holds, used as given: nothing checks the
|
||||
// access.
|
||||
let check = Check::Unchecked;
|
||||
if !module.uses_family(census::LOAD_POINTER) || !accessed {
|
||||
return Err(format!(
|
||||
"the compiled module accesses no memory through a pointer loaded from {}",
|
||||
target.resource.label()
|
||||
@@ -532,14 +513,9 @@ pub fn containment(
|
||||
}
|
||||
OutOfBoundsResource::ArgumentBufferTextureArray { buffer_binding, .. } => {
|
||||
slot(SlotClass::Buffer, buffer_binding)?;
|
||||
// The handle table resolves a loaded id to a resident texture or the null handle; the
|
||||
// identity handle domain masks the id's index onto the descriptor arrays.
|
||||
let (resolved, medium) = match module.policy.handle_domain {
|
||||
HandleDomain::Table => (module.handle_table, Medium::HandleTable),
|
||||
HandleDomain::Identity => (true, Medium::ResourceId),
|
||||
_ => return Err("a handle domain validation does not know".into()),
|
||||
};
|
||||
if !resolved || !module.uses_family(census::HANDLE_LOOKUP) {
|
||||
// A loaded id's index is masked onto the descriptor arrays.
|
||||
let medium = Medium::ResourceId;
|
||||
if !module.uses_family(census::HANDLE_LOOKUP) {
|
||||
return Err(format!(
|
||||
"the compiled module resolves no handle of {}",
|
||||
target.resource.label()
|
||||
|
||||
@@ -695,9 +695,6 @@ fn thread_memory_is_contained_by_the_typed_arrays_check_only() {
|
||||
stage: SymStage::Kernel,
|
||||
slots: &slots,
|
||||
attributes: &BTreeMap::new(),
|
||||
resident_roots: true,
|
||||
handle_table: true,
|
||||
policy: DevicePolicy::RESIDENT_TABLES,
|
||||
strategies: &strategies,
|
||||
robust_views: false,
|
||||
};
|
||||
@@ -778,9 +775,6 @@ fn the_identity_domains_leave_a_loaded_pointer_unchecked_and_mask_a_resource_id(
|
||||
.find(|entry| entry.tier.stem == "lavapipe")
|
||||
.unwrap()
|
||||
.profile;
|
||||
let mut identity = DevicePolicy::default();
|
||||
identity.pointer_domain = PointerDomain::Identity;
|
||||
identity.handle_domain = HandleDomain::Identity;
|
||||
let slots = BTreeMap::from([(
|
||||
SlotRef {
|
||||
stage: SymStage::Kernel,
|
||||
@@ -808,13 +802,10 @@ fn the_identity_domains_leave_a_loaded_pointer_unchecked_and_mask_a_resource_id(
|
||||
.insert(name.into(), StrategyUse::default());
|
||||
}
|
||||
let attributes = BTreeMap::new();
|
||||
let module = |policy| ModuleFacts {
|
||||
let module = || ModuleFacts {
|
||||
stage: SymStage::Kernel,
|
||||
slots: &slots,
|
||||
attributes: &attributes,
|
||||
resident_roots: false,
|
||||
handle_table: false,
|
||||
policy,
|
||||
strategies: &strategies,
|
||||
robust_views: false,
|
||||
};
|
||||
@@ -838,7 +829,7 @@ fn the_identity_domains_leave_a_loaded_pointer_unchecked_and_mask_a_resource_id(
|
||||
},
|
||||
ContainmentForm::HandleArrayIndex,
|
||||
);
|
||||
let loaded = containment(&pointer, &module(identity), profile).unwrap();
|
||||
let loaded = containment(&pointer, &module(), profile).unwrap();
|
||||
assert_eq!(
|
||||
(loaded.form, loaded.mechanism.label(), loaded.written),
|
||||
(
|
||||
@@ -847,7 +838,7 @@ fn the_identity_domains_leave_a_loaded_pointer_unchecked_and_mask_a_resource_id(
|
||||
false
|
||||
)
|
||||
);
|
||||
let masked = containment(&handles, &module(identity), profile).unwrap();
|
||||
let masked = containment(&handles, &module(), profile).unwrap();
|
||||
assert_eq!(
|
||||
(masked.form, masked.mechanism.label()),
|
||||
(
|
||||
@@ -859,18 +850,8 @@ fn the_identity_domains_leave_a_loaded_pointer_unchecked_and_mask_a_resource_id(
|
||||
read_rule(ContainmentForm::HandleArrayIndex, masked.mechanism, false),
|
||||
ReadRule::ResidentTexels
|
||||
);
|
||||
assert!(
|
||||
containment(&pointer, &module(DevicePolicy::RESIDENT_TABLES), profile)
|
||||
.unwrap_err()
|
||||
.contains("no memory through a pointer loaded")
|
||||
);
|
||||
assert!(
|
||||
containment(&handles, &module(DevicePolicy::RESIDENT_TABLES), profile)
|
||||
.unwrap_err()
|
||||
.contains("resolves no handle")
|
||||
);
|
||||
// The unchecked target refuses the run, naming its form; the masked one runs.
|
||||
match out_of_bounds_run(profile, &module(identity), &[pointer, handles.clone()]) {
|
||||
match out_of_bounds_run(profile, &module(), &[pointer, handles.clone()]) {
|
||||
Err(ExecutorError::NotSupported(refused @ NotSupported::Uncontained { .. })) => {
|
||||
assert_eq!(
|
||||
refused.outcome(),
|
||||
@@ -883,7 +864,7 @@ fn the_identity_domains_leave_a_loaded_pointer_unchecked_and_mask_a_resource_id(
|
||||
}
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
let run = out_of_bounds_run(profile, &module(identity), &[handles])
|
||||
let run = out_of_bounds_run(profile, &module(), &[handles])
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(run.targets[0].mechanism, masked.mechanism);
|
||||
@@ -909,9 +890,6 @@ fn a_draws_targets_are_contained_by_their_fetch() {
|
||||
stage,
|
||||
slots: &slots,
|
||||
attributes,
|
||||
resident_roots: false,
|
||||
handle_table: false,
|
||||
policy: DevicePolicy::RESIDENT_TABLES,
|
||||
strategies,
|
||||
robust_views: false,
|
||||
};
|
||||
@@ -1054,17 +1032,11 @@ fn a_bound_kernel_s_storage_view_is_contained_by_robust_buffer_access_2() {
|
||||
)]);
|
||||
let strategies = StrategyCensus::default();
|
||||
let attributes = BTreeMap::new();
|
||||
let mut identity = DevicePolicy::default();
|
||||
identity.pointer_domain = PointerDomain::Identity;
|
||||
identity.handle_domain = HandleDomain::Identity;
|
||||
let contained = |robust_views, form| {
|
||||
let module = ModuleFacts {
|
||||
stage: SymStage::Kernel,
|
||||
slots: &slots,
|
||||
attributes: &attributes,
|
||||
resident_roots: false,
|
||||
handle_table: false,
|
||||
policy: identity,
|
||||
strategies: &strategies,
|
||||
robust_views,
|
||||
};
|
||||
@@ -1111,9 +1083,6 @@ fn threadgroup_memory_is_checked_nowhere_and_its_case_is_refused() {
|
||||
let slots = BTreeMap::new();
|
||||
let attributes = BTreeMap::new();
|
||||
let strategies = StrategyCensus::default();
|
||||
let mut identity = DevicePolicy::default();
|
||||
identity.pointer_domain = PointerDomain::Identity;
|
||||
identity.handle_domain = HandleDomain::Identity;
|
||||
let target = OutOfBoundsTarget {
|
||||
resource: OutOfBoundsResource::ThreadgroupMemory { binding: 0 },
|
||||
form: ContainmentForm::Threadgroup,
|
||||
@@ -1122,15 +1091,12 @@ fn threadgroup_memory_is_checked_nowhere_and_its_case_is_refused() {
|
||||
};
|
||||
for committed in &profiles {
|
||||
let profile = &committed.profile;
|
||||
for policy in [identity, DevicePolicy::RESIDENT_TABLES] {
|
||||
let what = format!("{} under {policy:?}", committed.tier.label());
|
||||
{
|
||||
let what = committed.tier.label().to_string();
|
||||
let module = ModuleFacts {
|
||||
stage: SymStage::Kernel,
|
||||
slots: &slots,
|
||||
attributes: &attributes,
|
||||
resident_roots: false,
|
||||
handle_table: false,
|
||||
policy,
|
||||
strategies: &strategies,
|
||||
robust_views: false,
|
||||
};
|
||||
|
||||
@@ -884,19 +884,14 @@ mod tests {
|
||||
replay_specialized(bitcode, entry, constants, &profile, None, None).attempt
|
||||
}
|
||||
|
||||
/// `description`'s profile under the resident-table domains: the inputs the binder supplies (a
|
||||
/// storage texture's format, a tile function's member formats) are theirs, and the identity
|
||||
/// domains refuse what needs them.
|
||||
fn resident_tables(
|
||||
/// `description`'s profile (`Device::from_queries`).
|
||||
fn profile_of(
|
||||
description: metal2vulkan::device::DeviceDescription,
|
||||
) -> metal2vulkan::device::DeviceProfile {
|
||||
metal2vulkan::device::Device::from_queries(
|
||||
description,
|
||||
metal2vulkan::device::DevicePolicy::RESIDENT_TABLES,
|
||||
)
|
||||
.unwrap()
|
||||
.profile()
|
||||
.clone()
|
||||
metal2vulkan::device::Device::from_queries(description)
|
||||
.unwrap()
|
||||
.profile()
|
||||
.clone()
|
||||
}
|
||||
|
||||
fn row_plan(bitcode: &[u8], entry: &str) -> RowPlan {
|
||||
@@ -976,14 +971,15 @@ mod tests {
|
||||
assert_eq!(result.supplied, vec![Supplied::StageInputDescriptor]);
|
||||
}
|
||||
|
||||
/// A tile function is supplied each implicit imageblock member's format, under the
|
||||
/// resident-table domains ([`resident_tables`]).
|
||||
/// A tile function is supplied each implicit imageblock member's format, and its attempt is
|
||||
/// refused, typed: the one form binds no resource through a descriptor beside a bound kernel's
|
||||
/// storage views (`IdentityCause::Descriptor`).
|
||||
#[test]
|
||||
fn a_tile_function_is_supplied_its_members_formats() {
|
||||
let Some(bitcode) = bitcode(engine_dir().join("k10ts_tile_order.ll")) else {
|
||||
return;
|
||||
};
|
||||
let profile = resident_tables(crate::engine::load_description("moltenvk-m3").unwrap());
|
||||
let profile = profile_of(crate::engine::load_description("moltenvk-m3").unwrap());
|
||||
let result = replay_specialized(
|
||||
&bitcode,
|
||||
"k10ts_tile_order",
|
||||
@@ -1000,7 +996,14 @@ mod tests {
|
||||
}],
|
||||
"{result:?}"
|
||||
);
|
||||
assert_eq!(result.attempt.outcome, Outcome::Translated, "{result:?}");
|
||||
assert_eq!(
|
||||
result.attempt.detail.as_deref(),
|
||||
Some(
|
||||
"unsupported: IdentityDomains (a resource bound through a descriptor): \
|
||||
Descriptor; needs NotImplemented"
|
||||
),
|
||||
"{result:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Every derived input crosses the worker boundary and the index as JSON unchanged.
|
||||
@@ -1071,10 +1074,11 @@ mod tests {
|
||||
}
|
||||
|
||||
/// A storage texture on a profile without formatless storage access (`runtime-floor` without
|
||||
/// `shaderStorageImageWriteWithoutFormat`, below the runtime's floor) is supplied the widest
|
||||
/// format of its texel class, under the resident-table domains ([`resident_tables`]).
|
||||
/// `shaderStorageImageWriteWithoutFormat`, below the runtime's floor) is supplied no format:
|
||||
/// the one form holds formatless storage images alone, and the attempt is refused, typed
|
||||
/// (`IdentityCause::StorageTextureFormat`).
|
||||
#[test]
|
||||
fn a_storage_texture_is_supplied_the_widest_format_of_its_class() {
|
||||
fn a_storage_texture_below_the_floor_is_refused_its_format() {
|
||||
let Some(bitcode) =
|
||||
bitcode(fixtures_dir().join("kernel_write_one_dimensional_textures.ll"))
|
||||
else {
|
||||
@@ -1084,7 +1088,7 @@ mod tests {
|
||||
assert!(description
|
||||
.features
|
||||
.remove(&metal2vulkan::device::VkFeature::ShaderStorageImageWriteWithoutFormat));
|
||||
let profile = resident_tables(description);
|
||||
let profile = profile_of(description);
|
||||
let result = replay_specialized(
|
||||
&bitcode,
|
||||
"kernel_write_one_dimensional_textures",
|
||||
@@ -1094,16 +1098,10 @@ mod tests {
|
||||
None,
|
||||
)
|
||||
.attempt;
|
||||
assert!(
|
||||
result
|
||||
.supplied
|
||||
.iter()
|
||||
.any(|s| matches!(s, Supplied::StorageTextureFormat { .. })),
|
||||
"{result:?}"
|
||||
);
|
||||
assert_ne!(
|
||||
result.attempt.outcome.key(),
|
||||
"StorageTextureFormat",
|
||||
assert!(result.supplied.is_empty(), "{result:?}");
|
||||
assert_eq!(
|
||||
result.attempt.detail.as_deref(),
|
||||
Some("unsupported: IdentityDomains: StorageTextureFormat; needs NotImplemented"),
|
||||
"{result:?}"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -16,8 +16,8 @@
|
||||
//! they link, each a [`RowSource`]: its bitcode, or AIR text (a public row that retains none, a
|
||||
//! generated companion) the child assembles with `llvm-as` under its own deadline; the
|
||||
//! [`PipelineRequest`] (kind, entries, function constants, linked functions); and the device's
|
||||
//! `DeviceDescription` and `DevicePolicy` ([`WorkerDevice`]), from which the child rebuilds the
|
||||
//! parent's `Device`. The parent writes it to the file that becomes the child's stdin.
|
||||
//! `DeviceDescription` ([`WorkerDevice`]), from which the child rebuilds the parent's
|
||||
//! `Device`. The parent writes it to the file that becomes the child's stdin.
|
||||
//! 2. The child ([`serve_if_requested`]) refuses to serve without the counting allocator, sets its
|
||||
//! 500-MiB budget, and compiles through the public API ([`compile_pipeline`]:
|
||||
//! `Device::compile_compute_pipeline` or `Device::compile_render_pipeline`) under a `Budget`
|
||||
@@ -56,7 +56,7 @@ use crate::hash::sha256_bytes;
|
||||
use crate::observation::TRANSLATOR_FINGERPRINT;
|
||||
use crate::ScratchDir;
|
||||
use metal2vulkan::cache::{ArtifactError, PipelineArtifact};
|
||||
use metal2vulkan::device::{Device, DeviceDescription, DevicePolicy};
|
||||
use metal2vulkan::device::{Device, DeviceDescription};
|
||||
use metal2vulkan::error::Error;
|
||||
use metal2vulkan::library::FunctionConstantValues;
|
||||
use metal2vulkan::pipeline::{ComputePipeline, RenderPipeline};
|
||||
@@ -167,25 +167,20 @@ const LIB_TESTS_SERVE: &str = "serve";
|
||||
#[cfg(test)]
|
||||
const LIB_TESTS_STACK: usize = 8 << 20;
|
||||
|
||||
/// The device a worker compiles for: the description and policy the child rebuilds it from, and
|
||||
/// the parent's `Device` built from exactly that pair, against which the artifact is decoded.
|
||||
/// The device a worker compiles for: the description the child rebuilds it from, and the parent's
|
||||
/// `Device` built from exactly that description, against which the artifact is decoded.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct WorkerDevice {
|
||||
description: DeviceDescription,
|
||||
policy: DevicePolicy,
|
||||
device: Device,
|
||||
}
|
||||
|
||||
impl WorkerDevice {
|
||||
/// Derive the `Device` of `description` under `policy` (`Device::from_queries`'s refusals are its own).
|
||||
pub fn new(
|
||||
description: DeviceDescription,
|
||||
policy: DevicePolicy,
|
||||
) -> Result<WorkerDevice, Error> {
|
||||
let device = Device::from_queries(description.clone(), policy)?;
|
||||
/// Derive the `Device` of `description` (`Device::from_queries`'s refusals are its own).
|
||||
pub fn new(description: DeviceDescription) -> Result<WorkerDevice, Error> {
|
||||
let device = Device::from_queries(description.clone())?;
|
||||
Ok(WorkerDevice {
|
||||
description,
|
||||
policy,
|
||||
device,
|
||||
})
|
||||
}
|
||||
@@ -199,11 +194,6 @@ impl WorkerDevice {
|
||||
pub fn description(&self) -> &DeviceDescription {
|
||||
&self.description
|
||||
}
|
||||
|
||||
/// The policy the child rebuilds the `Device` under.
|
||||
pub fn policy(&self) -> &DevicePolicy {
|
||||
&self.policy
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a worker compile built no pipeline.
|
||||
@@ -275,7 +265,6 @@ pub fn compile_render_request(
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
struct CompileInput<'a> {
|
||||
description: DeviceDescription,
|
||||
policy: DevicePolicy,
|
||||
request: PipelineRequest,
|
||||
/// The source of each library the compile takes, in the request's order.
|
||||
libraries: Vec<RowSource<'a>>,
|
||||
@@ -416,7 +405,6 @@ fn compile_input<'a>(
|
||||
) -> CompileInput<'a> {
|
||||
CompileInput {
|
||||
description: device.description.clone(),
|
||||
policy: device.policy,
|
||||
request: request.clone(),
|
||||
libraries: libraries.to_vec(),
|
||||
}
|
||||
@@ -553,7 +541,7 @@ fn serve(
|
||||
}
|
||||
}
|
||||
}
|
||||
let device = match Device::from_queries(decoded.description, decoded.policy) {
|
||||
let device = match Device::from_queries(decoded.description) {
|
||||
Ok(device) => device,
|
||||
Err(error) => return Ok(output(not_compiled(&error), None)),
|
||||
};
|
||||
@@ -623,11 +611,7 @@ mod tests {
|
||||
}
|
||||
|
||||
fn worker_device(stem: &str) -> WorkerDevice {
|
||||
WorkerDevice::new(
|
||||
crate::engine::load_description(stem).unwrap(),
|
||||
DevicePolicy::default(),
|
||||
)
|
||||
.unwrap()
|
||||
WorkerDevice::new(crate::engine::load_description(stem).unwrap()).unwrap()
|
||||
}
|
||||
|
||||
/// The worker's compile of `input` from `started`, with the artifact it wrote.
|
||||
|
||||
@@ -277,7 +277,6 @@ fn the_census_refuses_command_buffer_cases_by_their_requirements() {
|
||||
};
|
||||
let lavapipe = metal2vulkan_validation::worker::compile::WorkerDevice::new(
|
||||
metal2vulkan_validation::engine::load_description("lavapipe").unwrap(),
|
||||
metal2vulkan::device::DevicePolicy::RESIDENT_TABLES,
|
||||
)
|
||||
.unwrap();
|
||||
let (scratch, case) =
|
||||
@@ -297,13 +296,13 @@ fn the_census_refuses_command_buffer_cases_by_their_requirements() {
|
||||
assert_eq!(cells[0].artifact, None, "{cells:?}");
|
||||
}
|
||||
|
||||
/// An object or mesh case, which no candidate draws (`mesh_render_pipeline`), still compiles its
|
||||
/// mesh render pipeline in the census: a run's preparation refuses the committed public mesh and
|
||||
/// object cases by that requirement alone, the census's prepares them, and each one's pipeline,
|
||||
/// its partners' stages with it, compiles in the worker as its one compile. Under the resident-table
|
||||
/// domains: the identity domains refuse every stage but kernel, vertex and fragment.
|
||||
/// An object or mesh case, which no candidate draws (`mesh_render_pipeline`), is still attempted
|
||||
/// in the census: a run's preparation refuses the committed public mesh and object cases by that
|
||||
/// requirement alone, the census's prepares them, and each one's pipeline, its partners' stages
|
||||
/// with it, is the worker's one compile, refused, typed: the one form compiles no stage but
|
||||
/// kernel, vertex and fragment.
|
||||
#[test]
|
||||
fn the_census_compiles_the_mesh_pipelines_no_candidate_draws() {
|
||||
fn the_census_refuses_the_mesh_pipelines_no_candidate_draws() {
|
||||
use metal2vulkan_validation::authored_compile::compile_case;
|
||||
use metal2vulkan_validation::candidate::engine::{case_compile, prepare_case, prepare_compile};
|
||||
use metal2vulkan_validation::check::admission::{
|
||||
@@ -321,7 +320,6 @@ fn the_census_compiles_the_mesh_pipelines_no_candidate_draws() {
|
||||
};
|
||||
let lavapipe = metal2vulkan_validation::worker::compile::WorkerDevice::new(
|
||||
metal2vulkan_validation::engine::load_description("lavapipe").unwrap(),
|
||||
metal2vulkan::device::DevicePolicy::RESIDENT_TABLES,
|
||||
)
|
||||
.unwrap();
|
||||
let device = DeviceType::Cpu;
|
||||
@@ -349,9 +347,12 @@ fn the_census_compiles_the_mesh_pipelines_no_candidate_draws() {
|
||||
case_compile(&prepared).unwrap();
|
||||
let cells = compile_case(scratch.path(), &worker, &case, &[&lavapipe]);
|
||||
assert_eq!(cells.len(), 1, "{name}");
|
||||
// The one form compiles no object or mesh stage: the pipeline is refused, typed.
|
||||
assert_eq!(
|
||||
cells[0].outcome,
|
||||
Ok(CellOutcome::Compiled),
|
||||
Ok(CellOutcome::Refused(
|
||||
"not_supported{unsupported:not_implemented IdentityDomains}".into()
|
||||
)),
|
||||
"{name}: {cells:?}"
|
||||
);
|
||||
assert_eq!(cells[0].compiles, 1, "{name}");
|
||||
@@ -375,7 +376,6 @@ fn the_census_compiles_a_texture_buffer_an_argument_buffer_holds() {
|
||||
};
|
||||
let lavapipe = metal2vulkan_validation::worker::compile::WorkerDevice::new(
|
||||
metal2vulkan_validation::engine::load_description("lavapipe").unwrap(),
|
||||
metal2vulkan::device::DevicePolicy::default(),
|
||||
)
|
||||
.unwrap();
|
||||
let holding = CorpusStore::new(metal2vulkan_validation::source::corpus_root())
|
||||
|
||||
@@ -2,20 +2,17 @@
|
||||
//! compiles engine pipelines for a device serves the worker, and what comes back through the
|
||||
//! pipeline's cache artifact bytes is the pipeline the public API compiles in process. A pipeline
|
||||
//! holding a constant blob crosses it without the worker copying the blob.
|
||||
|
||||
use metal2vulkan::device::DevicePolicy;
|
||||
use metal2vulkan::library::FunctionConstantValues;
|
||||
use metal2vulkan::pipeline::ComputePipeline;
|
||||
use metal2vulkan_devtools::{engine_dir, llvm_assemble, AssembleError};
|
||||
use metal2vulkan_validation::acceptance::{
|
||||
compile_draw_in_worker, compile_pipeline, compile_row_in_worker, retained, row,
|
||||
AcceptancePipeline, PipelineRequest, RequestFunction, RowCompile, RowPipeline, RowStage,
|
||||
};
|
||||
use metal2vulkan_validation::engine::{load_description, RowSource};
|
||||
use metal2vulkan_validation::engine::load_description;
|
||||
use metal2vulkan_validation::worker::compile::{
|
||||
compile_compute, CompileWorker, NotCompiled, WorkerCompile, WorkerDevice,
|
||||
compile_compute, CompileWorker, NotCompiled, WorkerDevice,
|
||||
};
|
||||
use metal2vulkan_validation::worker::{WorkerFailure, DEADLINE, MEMORY_LIMIT_BYTES};
|
||||
use metal2vulkan_validation::worker::{WorkerFailure, DEADLINE};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
fn fixture(name: &str) -> Option<Vec<u8>> {
|
||||
@@ -42,7 +39,7 @@ fn worker(program: &Path) -> CompileWorker {
|
||||
}
|
||||
|
||||
fn device(stem: &str) -> WorkerDevice {
|
||||
WorkerDevice::new(load_description(stem).unwrap(), DevicePolicy::default()).unwrap()
|
||||
WorkerDevice::new(load_description(stem).unwrap()).unwrap()
|
||||
}
|
||||
|
||||
/// Every binary that compiles through the worker serves it (and installs the allocator it
|
||||
@@ -236,114 +233,3 @@ fn a_program_that_does_not_serve_the_worker_is_a_worker_failure() {
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A kernel reading two words of `@g`, a closed constant struct DAG `depth` levels deep
|
||||
/// (`%e1 = { i32, i32 }`, `%e{k} = { %e{k-1}, %e{k-1} }`), all zero: past 14 levels `@g` is in
|
||||
/// the constant blob, `2^(depth+2)` bytes (the product's `tests/constant_blob_footprint.rs`).
|
||||
fn blob_kernel(depth: u32) -> String {
|
||||
let mut types = String::from("%e1 = type { i32, i32 }\n");
|
||||
for k in 2..=depth {
|
||||
types += &format!("%e{k} = type {{ %e{p}, %e{p} }}\n", p = k - 1);
|
||||
}
|
||||
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"
|
||||
|
||||
{types}@g = internal addrspace(2) constant %e{depth} zeroinitializer, align 4
|
||||
|
||||
define void @blob(ptr addrspace(1) %out, i32 %t) {{
|
||||
%v0 = load i32, ptr addrspace(2) @g, align 4
|
||||
%q = getelementptr inbounds i8, ptr addrspace(2) @g, i32 4
|
||||
%v1 = load i32, ptr addrspace(2) %q, align 4
|
||||
%i0 = shl i32 %t, 1
|
||||
%o0 = getelementptr inbounds i32, ptr addrspace(1) %out, i32 %i0
|
||||
store i32 %v0, ptr addrspace(1) %o0, align 4
|
||||
%i1 = add i32 %i0, 1
|
||||
%o1 = getelementptr inbounds i32, ptr addrspace(1) %out, i32 %i1
|
||||
store i32 %v1, ptr addrspace(1) %o1, align 4
|
||||
ret void
|
||||
}}
|
||||
|
||||
!air.kernel = !{{!0}}
|
||||
!0 = !{{ptr @blob, !1, !2}}
|
||||
!1 = !{{}}
|
||||
!2 = !{{!3, !4}}
|
||||
!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_index_in_threadgroup", !"air.arg_type_name", !"uint", !"air.arg_name", !"t"}}
|
||||
"#
|
||||
)
|
||||
}
|
||||
|
||||
/// Compile [`blob_kernel`] `depth` levels deep for `lavapipe` through `corpus-pipeline`'s compile
|
||||
/// worker (the child assembles the text): the compile, and its blob's length, `2^(depth+2)`.
|
||||
/// Under the resident-table domains: the identity domains refuse constant data over 64 KiB.
|
||||
fn compile_blob(depth: u32) -> (WorkerCompile<ComputePipeline>, u64) {
|
||||
let worker = worker(&bin_exe!("corpus-pipeline"));
|
||||
let text = blob_kernel(depth);
|
||||
let compiled = compile_compute(
|
||||
&worker,
|
||||
&WorkerDevice::new(
|
||||
load_description("lavapipe").unwrap(),
|
||||
DevicePolicy::RESIDENT_TABLES,
|
||||
)
|
||||
.unwrap(),
|
||||
&RowSource::Text(text.as_str().into()),
|
||||
"blob",
|
||||
&FunctionConstantValues::defaults(),
|
||||
)
|
||||
.unwrap_or_else(|failure| panic!("{depth} levels: {}", failure.message()));
|
||||
let blob = match &compiled.result {
|
||||
Ok(compiled) => compiled
|
||||
.stage
|
||||
.constant_blob
|
||||
.as_ref()
|
||||
.map_or(0, |blob| blob.len() as u64),
|
||||
Err(refused) => panic!("{depth} levels: {refused:?}"),
|
||||
};
|
||||
assert_eq!(blob, 4 << depth, "{depth} levels");
|
||||
(compiled, blob)
|
||||
}
|
||||
|
||||
/// The worker reports a pipeline holding a constant blob without copying the blob: it writes the
|
||||
/// artifact to the parent's file a chunk at a time, so its process's allocator peak passes its
|
||||
/// compile's by under a quarter of the blob (4 MiB at 20 levels). Encoding the artifact whole and
|
||||
/// then as base64 for the report held over twice the blob beside the pipeline.
|
||||
#[test]
|
||||
fn a_constant_blob_crosses_the_worker_without_a_copy() {
|
||||
if fixture("store_const.ll").is_none() {
|
||||
return;
|
||||
}
|
||||
let (compiled, blob) = compile_blob(20);
|
||||
let process = compiled.measured.allocator_peak_bytes.unwrap();
|
||||
let compile = compiled.allocator_peak.unwrap();
|
||||
eprintln!("20 levels: process peak {process} bytes, compile peak {compile} bytes, blob {blob}");
|
||||
assert!(
|
||||
process < compile + blob / 4,
|
||||
"process peak {process} bytes, compile peak {compile} bytes, blob {blob}"
|
||||
);
|
||||
}
|
||||
|
||||
/// The largest closed constant the ledger admits, 26 levels (a 256-MiB blob), compiles through
|
||||
/// the worker boundary within its ceilings: under 500 MiB, the sampled resident set and the
|
||||
/// allocator's peak alike, and within the 20-second deadline. The ceilings are release-mode
|
||||
/// contracts, so this runs in release, ignored otherwise.
|
||||
#[test]
|
||||
#[ignore = "a release-mode measurement of the worker's ceilings"]
|
||||
fn the_largest_admitted_constant_blob_compiles_within_the_worker_ceilings() {
|
||||
if fixture("store_const.ll").is_none() {
|
||||
return;
|
||||
}
|
||||
let (compiled, blob) = compile_blob(26);
|
||||
let measured = compiled.measured;
|
||||
eprintln!(
|
||||
"26 levels: blob {blob} bytes, {:?}, resident peak {:?} bytes, allocator peak {:?} \
|
||||
bytes, compile peak {:?} bytes",
|
||||
measured.elapsed,
|
||||
measured.peak_resident_bytes,
|
||||
measured.allocator_peak_bytes,
|
||||
compiled.allocator_peak
|
||||
);
|
||||
assert!(measured.elapsed < DEADLINE, "{:?}", measured.elapsed);
|
||||
let peak = measured.peak_bytes().unwrap();
|
||||
assert!(peak < MEMORY_LIMIT_BYTES, "{peak} bytes");
|
||||
}
|
||||
@@ -6,7 +6,6 @@
|
||||
//! it compiles for. No device is opened: the GPU run (Metal and the candidate) is the operator's.
|
||||
|
||||
use base64::Engine as _;
|
||||
use metal2vulkan::device::DevicePolicy;
|
||||
use metal2vulkan_devtools::{engine_dir, llvm_assemble, AssembleError};
|
||||
use metal2vulkan_validation::acceptance::{retained, LinkedLibrary};
|
||||
use metal2vulkan_validation::candidate::engine::{
|
||||
@@ -148,8 +147,7 @@ fn a_case_with_visible_function_references_compiles_linked_through_the_worker()
|
||||
|
||||
let worker = worker();
|
||||
for stem in ["moltenvk-m3", "runtime-floor", "lavapipe"] {
|
||||
let device =
|
||||
WorkerDevice::new(load_description(stem).unwrap(), DevicePolicy::default()).unwrap();
|
||||
let device = WorkerDevice::new(load_description(stem).unwrap()).unwrap();
|
||||
let profile = device.device().profile();
|
||||
let compile = |linked: &[LinkedModule]| {
|
||||
let (request, libraries) = kernel_request(&retained(&caller), linked, &compute);
|
||||
|
||||
@@ -21,7 +21,7 @@ use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
use metal2vulkan::cache::PipelineArtifact;
|
||||
use metal2vulkan::device::{Device, DeviceDescription, DevicePolicy};
|
||||
use metal2vulkan::device::{Device, DeviceDescription};
|
||||
use metal2vulkan::error::{Error, Needs, RuntimeInput};
|
||||
use metal2vulkan::library::{
|
||||
CompiledFunction, FunctionConstantValue, FunctionConstantValues, Library,
|
||||
@@ -69,12 +69,11 @@ fn profile_json(stem: &str) -> Result<String> {
|
||||
)))?)
|
||||
}
|
||||
|
||||
/// The device a runtime compiles for on committed profile `stem`: the default policy, the
|
||||
/// identity domains.
|
||||
/// The device a runtime compiles for on committed profile `stem`.
|
||||
fn runtime_device(stem: &str) -> Result<Device> {
|
||||
let json = profile_json(stem)?;
|
||||
let description = DeviceDescription::from_khronos_json(&json, None)?;
|
||||
let device = Device::from_queries(description, DevicePolicy::default())?;
|
||||
let device = Device::from_queries(description)?;
|
||||
Ok(device)
|
||||
}
|
||||
|
||||
|
||||
@@ -35,9 +35,8 @@ This reference shows exactly the API's frozen surface. A walkthrough with a runn
|
||||
|
||||
# The flow
|
||||
|
||||
1. **A device.** Describe the Vulkan device as created ([`device::DeviceDescription`]) and pick a
|
||||
[`device::DevicePolicy`]; [`device::Device::from_queries`] derives the profile every compile
|
||||
decides by.
|
||||
1. **A device.** Describe the Vulkan device as created ([`device::DeviceDescription`]);
|
||||
[`device::Device::from_queries`] derives the profile every compile decides by.
|
||||
2. **A library.** [`library::Library::parse`] reads a metallib or AIR bitcode;
|
||||
[`library::Library::function`] finds a function, and [`library::Function::reflection`]
|
||||
answers what its arguments bind, in Metal's shape ([`reflection`]).
|
||||
|
||||
@@ -1198,14 +1198,12 @@ fn limits(l: &avk::PhysicalDeviceLimits, p: &PropertyChain, chained: &Properties
|
||||
max_per_stage_descriptor_storage_buffers: l.max_per_stage_descriptor_storage_buffers,
|
||||
max_per_stage_descriptor_sampled_images: l.max_per_stage_descriptor_sampled_images,
|
||||
max_per_stage_descriptor_storage_images: l.max_per_stage_descriptor_storage_images,
|
||||
max_per_stage_descriptor_input_attachments: l.max_per_stage_descriptor_input_attachments,
|
||||
max_per_stage_resources: l.max_per_stage_resources,
|
||||
max_descriptor_set_samplers: l.max_descriptor_set_samplers,
|
||||
max_descriptor_set_uniform_buffers: l.max_descriptor_set_uniform_buffers,
|
||||
max_descriptor_set_storage_buffers: l.max_descriptor_set_storage_buffers,
|
||||
max_descriptor_set_sampled_images: l.max_descriptor_set_sampled_images,
|
||||
max_descriptor_set_storage_images: l.max_descriptor_set_storage_images,
|
||||
max_descriptor_set_input_attachments: l.max_descriptor_set_input_attachments,
|
||||
max_descriptor_set_update_after_bind_samplers: v12
|
||||
.max_descriptor_set_update_after_bind_samplers,
|
||||
max_descriptor_set_update_after_bind_sampled_images: v12
|
||||
|
||||
@@ -17,7 +17,7 @@ use super::query::{
|
||||
use crate::device::description::FormatProperties;
|
||||
use crate::device::profile::Independence;
|
||||
use crate::device::requirements::{ApiVersion, VkExtension, VkFeature};
|
||||
use crate::device::{AllocationLimits, Device, DeviceDescription, DevicePolicy, FormatSupport};
|
||||
use crate::device::{AllocationLimits, Device, DeviceDescription, FormatSupport};
|
||||
use crate::error::{Capability, Error, Feature, Unsupported};
|
||||
use crate::vk;
|
||||
|
||||
@@ -1155,7 +1155,7 @@ fn a_queried_description_derives_a_device() {
|
||||
dev.v11_props.subgroup_supported_stages = avk::ShaderStageFlags::ALL;
|
||||
dev.v11_props.subgroup_supported_operations = avk::SubgroupFeatureFlags::from_raw(0xff);
|
||||
let desc = dev.query().unwrap();
|
||||
Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("queried description derives");
|
||||
Device::from_queries(desc).expect("queried description derives");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -22,8 +22,6 @@
|
||||
//! - [`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::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
@@ -236,32 +234,6 @@ pub(crate) fn raw_held(shape: &TextureShape) -> bool {
|
||||
.is_some()
|
||||
}
|
||||
|
||||
/// The bit of `SpecKey::HeapRawTextures`' value that a texture the stage's handles can name is held
|
||||
/// by its raw texels alone, whose decode the function's `float` read, sample or
|
||||
/// gather takes (`lower::texture::heap_raw`).
|
||||
pub(crate) const HELD: u32 = 1;
|
||||
|
||||
/// The bit of `SpecKey::HeapRawTextures`' value that such a texture is of a form whose sample the
|
||||
/// function filters (`lower::sampler::heap_raw`): every form of `ExtendedRange::HEAP_READ` but a
|
||||
/// bfloat one, whose sample reads the nearest texel under either filter.
|
||||
pub(crate) const FILTERED: u32 = 2;
|
||||
|
||||
/// The bit of `SpecKey::HeapNanFamilies` of a 16-bit float format: its written NaN, a `half`'s or
|
||||
/// a `float`'s, is the device's conversion's.
|
||||
pub(crate) const NAN_SIXTEEN: u32 = 1;
|
||||
|
||||
/// The bit of `SpecKey::HeapNanFamilies` of a 32-bit float format: its written `half` NaN is the
|
||||
/// device's widening's.
|
||||
pub(crate) const NAN_WIDE: u32 = 2;
|
||||
|
||||
/// The bit of `SpecKey::HeapNanFamilies` of a packed small float format (`RG11B10Float`,
|
||||
/// `RGB9E5Float`): its written NaN is the device's conversion's.
|
||||
pub(crate) const NAN_SMALL: u32 = 4;
|
||||
|
||||
/// The bit of `SpecKey::HeapNanFamilies` of a float format of none of those families whose texels
|
||||
/// may hold a NaN: its written NaN is the device's.
|
||||
pub(crate) const NAN_OTHER: u32 = 8;
|
||||
|
||||
/// 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
|
||||
|
||||
@@ -27,7 +27,6 @@ fn class(
|
||||
|
||||
fn shape(ty: TextureType, pf: PixelFormat, samples: u32, usage: TextureUsage) -> TextureShape {
|
||||
TextureShape::Texture {
|
||||
address_modes: crate::metal::sampler::AddressModeMap::IDENTITY,
|
||||
offset_base_axes: 0,
|
||||
texture_type: ty,
|
||||
pixel_format: pf,
|
||||
|
||||
@@ -42,9 +42,7 @@ pub(crate) mod pvrtc_decode;
|
||||
pub(crate) mod rate_map;
|
||||
pub(crate) mod replay;
|
||||
pub(crate) mod state;
|
||||
pub(crate) mod status;
|
||||
pub(crate) mod table;
|
||||
pub(crate) mod texel_parts;
|
||||
pub(crate) mod ycbcr_convert;
|
||||
|
||||
pub use argument_buffer::{
|
||||
@@ -68,5 +66,4 @@ pub use state::{SamplerDescriptor, StageInRegion};
|
||||
#[cfg(test)]
|
||||
pub(crate) use table::FunctionTableWords;
|
||||
pub use table::{function_table_entry_offset, function_table_header};
|
||||
pub(crate) use texel_parts::part_texels;
|
||||
pub(crate) use ycbcr_convert::{YCbCrCodes, YCbCrOutput};
|
||||
@@ -28,9 +28,8 @@ impl TextureFacts {
|
||||
/// The facts of an image texture that can change the variant, specialization or views a slot
|
||||
/// binds it through (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 and its
|
||||
/// [`offset_base_axes`](Self::offset_base_axes). Its array length only changes the view's
|
||||
/// subresource range, which is every layer.
|
||||
/// and pushed level count, its swizzle 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
|
||||
/// `ShaderWrite` at every level, through every write form, as one made with it.
|
||||
@@ -43,7 +42,6 @@ impl TextureFacts {
|
||||
mipmap_level_count: self.mipmap_level_count,
|
||||
sparse: self.sparse,
|
||||
swizzle: self.swizzle,
|
||||
address_modes: self.address_modes,
|
||||
offset_base_axes: self.offset_base_axes(),
|
||||
}
|
||||
}
|
||||
@@ -76,8 +74,6 @@ impl SamplerDescriptor {
|
||||
linear: self.min_filter == metal::SamplerMinMagFilter::Linear
|
||||
|| self.mag_filter == metal::SamplerMinMagFilter::Linear
|
||||
|| self.mip_filter == metal::SamplerMipFilter::Linear,
|
||||
cubic: self.min_filter == metal::SamplerMinMagFilter::Cubic
|
||||
|| self.mag_filter == metal::SamplerMinMagFilter::Cubic,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -105,11 +101,6 @@ pub struct TextureFacts {
|
||||
/// an opaque-black border the device replaces is checked against it.
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
pub swizzle: metal::TextureSwizzleChannels,
|
||||
/// The texture's address-mode map (`metal::sampler::AddressModeMap`, the runtime's
|
||||
/// extension): a slot a constexpr sampler samples takes it through the pipeline variant
|
||||
/// (`VariantKey::address_maps`) where it is not the identity.
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
pub address_modes: metal::sampler::AddressModeMap,
|
||||
/// The level of the texture whose levels a view presents at which the view's first level
|
||||
/// lies (`MTLTexture.parentRelativeLevel`): 0 for a texture that is not a view, and for a
|
||||
/// view that starts at its parent's base level.
|
||||
@@ -137,7 +128,6 @@ impl TextureFacts {
|
||||
mipmap_level_count: 1,
|
||||
sparse: false,
|
||||
swizzle: metal::TextureSwizzleChannels::DEFAULT,
|
||||
address_modes: metal::sampler::AddressModeMap::IDENTITY,
|
||||
parent_relative_level: 0,
|
||||
parent_base_size: [0; 3],
|
||||
}
|
||||
@@ -280,11 +270,6 @@ pub enum TextureShape {
|
||||
/// against it.
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
swizzle: metal::TextureSwizzleChannels,
|
||||
/// The texture's address-mode map ([`TextureFacts::address_modes`]): a slot a constexpr
|
||||
/// sampler samples compiles under it where it is not the identity
|
||||
/// (`VariantKey::address_maps`).
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
address_modes: metal::sampler::AddressModeMap,
|
||||
/// The plane axes on which the base-level size Metal's texel-offset rule reads, a view's
|
||||
/// parent's, is not a power of two where the texture's own is
|
||||
/// ([`TextureFacts::offset_base_axes`]): a slot whose function places an offset by that
|
||||
@@ -325,9 +310,4 @@ pub struct SamplerShape {
|
||||
/// (`metal::sampler::vk_filtering`), which the binder checks where the sampler meets textures
|
||||
/// through separate descriptors.
|
||||
pub linear: bool,
|
||||
/// The min or the mag filter is `Cubic`: Metal samples through the sampler with its bicubic
|
||||
/// filter whatever the level, which a function emulates under its pipeline variant's
|
||||
/// cubic samplers (`VariantKey::cubic_samplers`).
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
pub cubic: bool,
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
//! `ExecutionStatus` buffer layout: word indices and status bits.
|
||||
//!
|
||||
//! 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]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub enum StatusWord {
|
||||
/// Status bits ([`StatusBits`]). Initial 0.
|
||||
Status,
|
||||
/// Resident-miss count. Initial 0.
|
||||
ResidentMisses,
|
||||
/// The word every sequentially consistent fence of the command buffer increments with an
|
||||
/// acquire-release atomic at the fence's scope (`lower::sync::barrier::seq_cst_order`), so
|
||||
/// that the fences of one command buffer are totally ordered, as Metal's are. Its value means
|
||||
/// nothing; the decode does not read it. Initial 0. It is the buffer's last word, after one
|
||||
/// that nothing writes.
|
||||
SeqCstFences,
|
||||
}
|
||||
|
||||
impl StatusWord {
|
||||
/// The word's index in the buffer.
|
||||
pub const fn index(self) -> u32 {
|
||||
match self {
|
||||
StatusWord::Status => 0,
|
||||
StatusWord::ResidentMisses => 1,
|
||||
StatusWord::SeqCstFences => 3,
|
||||
}
|
||||
}
|
||||
|
||||
/// The word's byte offset in the buffer.
|
||||
pub const fn byte_offset(self) -> u32 {
|
||||
self.index() * 4
|
||||
}
|
||||
}
|
||||
|
||||
/// Bits of [`StatusWord::Status`].
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
pub struct StatusBits(pub u32);
|
||||
|
||||
impl StatusBits {
|
||||
/// An access missed the resident set.
|
||||
pub const RESIDENT_MISS: StatusBits = StatusBits(1 << 0);
|
||||
/// A function sampled, gathered, or queried through a sampler an argument buffer holds whose
|
||||
/// min or mag filter is `Cubic`, whose bicubic filter it does not emulate there
|
||||
/// (`RuntimeFact::CubicArgumentSampler`): its result is the device's through a nearest
|
||||
/// placeholder, not Metal's.
|
||||
pub const CUBIC_ARGUMENT_SAMPLER: StatusBits = StatusBits(1 << 3);
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
//! A texture buffer wider than one texel buffer view holds, read and written through several
|
||||
//! views of its bytes, its parts.
|
||||
//!
|
||||
//! **Where.** Metal makes a texture buffer of up to 2^28 texels on every Mac. One texel buffer
|
||||
//! 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
|
||||
//! (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
|
||||
//! each part starts on that alignment where the texture buffer does): `P` texels for every part
|
||||
//! but the last, which holds the rest. Each is a view of the device's own in the format one view
|
||||
//! would take, so a read converts its texel as that view does, the device's conversion
|
||||
//! (Uniform Texel Buffer, Storage Texel Buffer).
|
||||
//!
|
||||
//! **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 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.
|
||||
|
||||
use crate::device::Limits;
|
||||
|
||||
/// The texels of each part but the last of a texture buffer of more texels than one texel buffer
|
||||
/// view holds, which binds through views of its parts (part `k` from texel `k · P`, the last
|
||||
/// holding the rest): the device's `maxTexelBufferElements` rounded down to a multiple of its
|
||||
/// `minTexelBufferOffsetAlignment`, so that a part starts on that alignment wherever the texture
|
||||
/// buffer does (a texel is at least a byte). 0 on a device whose limit is below its alignment,
|
||||
/// which binds no parts.
|
||||
pub fn part_texels(limits: &Limits) -> u64 {
|
||||
let max = u64::from(limits.max_texel_buffer_elements);
|
||||
let alignment = limits.min_texel_buffer_offset_alignment.max(1);
|
||||
max - max % alignment
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn limits(max: u32, alignment: u64) -> Limits {
|
||||
Limits {
|
||||
max_texel_buffer_elements: max,
|
||||
min_texel_buffer_offset_alignment: alignment,
|
||||
..Limits::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// A part holds the limit's texels: 2^27 on lavapipe's limits.
|
||||
#[test]
|
||||
fn parts_hold_the_limit_s_texels_each() {
|
||||
assert_eq!(part_texels(&limits(1 << 27, 16)), 1 << 27);
|
||||
}
|
||||
|
||||
/// A limit off the offset alignment: each part holds the limit rounded down to it, so the next
|
||||
/// starts on it; a limit below the alignment holds no aligned part.
|
||||
#[test]
|
||||
fn parts_start_on_the_offset_alignment() {
|
||||
assert_eq!(part_texels(&limits(1000, 64)), 960);
|
||||
assert_eq!(part_texels(&limits(32, 64)), 0);
|
||||
}
|
||||
}
|
||||
+32
-73
@@ -33,20 +33,20 @@ use crate::metal::format::{ExtendedRange, WordAttachment, WordField};
|
||||
use crate::metal::{CompareFunction, TextureWriteRoundingMode};
|
||||
use crate::pipeline::artifact::{
|
||||
ComputePipeline, ComputePipelineMetalInfo, ModuleStats, PrecisionNote, Reconvergence,
|
||||
RenderPipeline, RuntimeDependency, SpecClause, SpecConstant, SpecTest, SpecializationLayout,
|
||||
SpecializedNote, StageModule, StrategyCensus, StrategyUse,
|
||||
RenderPipeline, RuntimeDependency, SpecConstant, SpecializationLayout, StageModule,
|
||||
StrategyCensus, StrategyUse,
|
||||
};
|
||||
use crate::pipeline::descriptor::TessellationDescriptor;
|
||||
use crate::pipeline::facts::{Mechanism, RuntimeFact};
|
||||
use crate::pipeline::graphics::{
|
||||
BandPrimitive, BlendState, ColorAttachmentState, GraphicsState, InputAttachmentUse,
|
||||
LineBandState, TessellationState,
|
||||
BandPrimitive, BlendState, ColorAttachmentState, GraphicsState, LineBandState,
|
||||
TessellationState,
|
||||
};
|
||||
use crate::pipeline::interface::{
|
||||
AccessSet, BufferForm, BufferKind, BufferSlot, CommandWrites, NumberedSampler, PatchDomain,
|
||||
PipelineInterface, PlacedField, PushLoc, PushPlacement, SamplerArray, SamplerSlot,
|
||||
SlotInterface, StageDescriptor, StageInterface, StageSpec, TessellationStage, TextureAccess,
|
||||
TextureSlot, ThreadgroupArgument, Window,
|
||||
PipelineInterface, PlacedField, PushLoc, PushPlacement, SamplerSlot, SlotInterface,
|
||||
StageDescriptor, StageInterface, StageSpec, TessellationStage, TextureAccess, TextureSlot,
|
||||
ThreadgroupArgument, Window,
|
||||
};
|
||||
use crate::pipeline::layout::{
|
||||
BindingSource, DescriptorBinding, DescriptorSetLayout, PipelineLayout, PushConstantRange,
|
||||
@@ -838,40 +838,30 @@ codec_enum! {
|
||||
StorageFormatClass { NotStorage, Unknown, Format(f0) }
|
||||
HandleClass { Image(f0), Sampler { compare, integer }, FunctionTable }
|
||||
SyntheticBinding {
|
||||
ArgumentTable, ExecutionStatus, RootTable, HandleTable, ConstantBlob, TessellationFactors, Imageblock,
|
||||
SamplerTable,
|
||||
FunctionTableDirectory,
|
||||
PatchIndices,
|
||||
ControlPointIndices,
|
||||
TileMemory,
|
||||
FunctionTableSnapshot,
|
||||
Imageblock, FunctionTableDirectory, TileMemory, FunctionTableSnapshot,
|
||||
}
|
||||
ResourceKind {
|
||||
Buffer, Texture, Sampler, Heap(f0), Synthetic(f0), InputAttachment(f0),
|
||||
CombinedTextureSampler(f0), HeapSampler(f0), AccelerationStructure(f0), TileAttachment(f0),
|
||||
TileMap, SeparateTexture(f0), SeparateSampler(f0),
|
||||
SamplerArray { compare, integer },
|
||||
Buffer, Heap(f0), Synthetic(f0), AccelerationStructure(f0), TileAttachment(f0), TileMap,
|
||||
}
|
||||
AccelerationStructureLevel { Primitive, Instance }
|
||||
SamplerRef { Slot(f0), Constexpr(f0) }
|
||||
SpecKey {
|
||||
LocalSize(f0), FlatLocalSize, MultiRegion, TgLength(f0), Presence(f0), SampleCount,
|
||||
AmplificationCount, ImageblockWidth, ImageblockHeight,
|
||||
RenderAreaWidth, RenderAreaHeight, OutOfBoundsAlpha(f0), BicubicTexels(f0),
|
||||
SparseTexture(f0), SamplerState { slot, fields },
|
||||
TgOffset(f0), TileThreadgroupLength, TileGridWidth, TextureSwizzle(f0),
|
||||
RenderAreaWidth, RenderAreaHeight, OutOfBoundsAlpha(f0), SparseTexture(f0), TgOffset(f0),
|
||||
TileThreadgroupLength, TileGridWidth, TextureSwizzle(f0),
|
||||
ObjectLocalSize(f0), ObjectFlatLocalSize, ObjectMultiRegion, SamplerMinLevel(f0),
|
||||
ConstantLanes(f0), BoundTexelFormat(f0), OffsetBaseAxes(f0), SamplerAnisotropy(f0),
|
||||
NearestPixelSampler(f0), BoundSamplerWord(f0),
|
||||
HeapRawTextures(f0), BorderTexels(f0), HeapNanFamilies(f0), DeepThreadgroup,
|
||||
OffsetBaseAxes(f0), SamplerAnisotropy(f0),
|
||||
NearestPixelSampler(f0),
|
||||
BorderTexels(f0), DeepThreadgroup,
|
||||
WorkgroupSize(f0), TexelBufferWords { stage, handles },
|
||||
}
|
||||
PushField {
|
||||
RootTableAddress, ExecutionStatusAddress, DispatchRegion, BaseVertexInstance,
|
||||
RootTableAddress, DispatchRegion, BaseVertexInstance,
|
||||
SlotBindOffset(f0), SlotGuestBase(f0), VertexBufferStride(f0), StageInRegion,
|
||||
TessellationFactorOffset, TessellationFactorInstanceStride, TessellationFactorScale,
|
||||
TextureLevels(f0), InstanceCount(f0), CommandRecordsAddress, ReplayRegionAddress,
|
||||
IndexCapacity, ViewportCount, RenderTargetArrayLength,
|
||||
TextureLevels(f0), InstanceCount(f0), ReplayRegionAddress,
|
||||
ViewportCount, RenderTargetArrayLength,
|
||||
PatchIndexOffset, PatchIndexBound, ControlPointIndexOffset, StageInStride(f0),
|
||||
AmplificationId, AmplificationLayerOffset, AmplificationViewportOffset,
|
||||
DepthClampRange,
|
||||
@@ -879,7 +869,6 @@ codec_enum! {
|
||||
CaptureIndexAddress,
|
||||
TextureIntegerChannels(f0),
|
||||
BicubicTexels(f0),
|
||||
HalfBlendColor,
|
||||
VerticesPerPrimitive,
|
||||
MergedDrawAddress,
|
||||
AlphaTestReference,
|
||||
@@ -1045,10 +1034,9 @@ codec_enum! {
|
||||
MaxSubgroupSize, MaxPushConstantsSize, MaxPushDescriptors, MaxBoundDescriptorSets,
|
||||
MaxPerStageDescriptorSamplers, MaxPerStageDescriptorUniformBuffers,
|
||||
MaxPerStageDescriptorStorageBuffers, MaxPerStageDescriptorSampledImages,
|
||||
MaxPerStageDescriptorStorageImages, MaxPerStageDescriptorInputAttachments,
|
||||
MaxPerStageResources, MaxDescriptorSetSamplers, MaxDescriptorSetUniformBuffers,
|
||||
MaxPerStageDescriptorStorageImages, MaxPerStageResources, MaxDescriptorSetSamplers, MaxDescriptorSetUniformBuffers,
|
||||
MaxDescriptorSetStorageBuffers, MaxDescriptorSetSampledImages,
|
||||
MaxDescriptorSetStorageImages, MaxDescriptorSetInputAttachments,
|
||||
MaxDescriptorSetStorageImages,
|
||||
MaxDescriptorSetUpdateAfterBindSamplers, MaxDescriptorSetUpdateAfterBindSampledImages,
|
||||
MaxDescriptorSetUpdateAfterBindStorageImages,
|
||||
MaxPerStageDescriptorUpdateAfterBindSamplers,
|
||||
@@ -1107,13 +1095,11 @@ codec_enum! {
|
||||
codec_struct! {
|
||||
CommandWrites { operations, primitive_types, kinds }
|
||||
StageInterface {
|
||||
stage, slots, threadgroup, push, descriptors, spec, needs_pointer_translation,
|
||||
needs_handle_translation, io, tessellation, writes_memory, payload, reaches_command_buffers, command_writes, writes_textures,
|
||||
stage, slots, threadgroup, push, descriptors, spec, io, tessellation, writes_memory, payload, reaches_command_buffers, command_writes, writes_textures,
|
||||
reads_unbound_resources, writes_unbound_resources, unbound_storage_textures,
|
||||
numbered_samplers, own_pixel_textures,
|
||||
private_bytes, sampler_arrays,
|
||||
private_bytes,
|
||||
}
|
||||
SamplerArray { slot, samplers }
|
||||
TessellationStage { domain, control_points }
|
||||
TessellationDescriptor {
|
||||
max_tessellation_factor, partition_mode, factor_format, factor_step_function,
|
||||
@@ -1199,11 +1185,9 @@ codec_enum! {
|
||||
RuntimeFact {
|
||||
ThreadsPerThreadgroup, ThreadgroupMemoryLength { index },
|
||||
LocalSizeConstraint { multiple }, LocalSizeLimits, DispatchGrid, IndirectGroupCount,
|
||||
ResourcePresence { slot }, SampleCount, StorageTextureFormat { slot },
|
||||
SamplerCoordinates { slot }, SamplerReduction { slot }, ImageViewShape { slot },
|
||||
ResourcePresence { slot }, SampleCount, ImageViewShape { slot },
|
||||
VertexFetch { attr }, VertexBufferStride { layout }, BaseVertexInstance,
|
||||
DeviceAddresses { slot }, BufferRangeLimit { slot }, TexelBufferRange { slot },
|
||||
FramebufferFetch { color }, ExecutionStatus, HeapNumericType { class },
|
||||
DeviceAddresses { slot }, FramebufferFetch { color },
|
||||
SimdgroupEmulation { bytes_per_simdgroup, arena }, AmplificationCount,
|
||||
EmulatedSimdgroups,
|
||||
ImageblockSize { cell_bytes },
|
||||
@@ -1212,13 +1196,11 @@ codec_enum! {
|
||||
TileFunction, TileAttachmentFormat { color, format },
|
||||
StorageTextureNumericType { slot },
|
||||
OutOfBoundsAlpha { slot },
|
||||
BicubicTexels { slot },
|
||||
StorageTextureLevels { slot },
|
||||
StorageTextureLevelViews { slot },
|
||||
SparseTexture { slot, sparse_arm, tile_map },
|
||||
AccelerationStructureInstanceCount { slot },
|
||||
PredicationVote, SrgbTexture { slot },
|
||||
ViewportCount,
|
||||
PredicationVote, ViewportCount,
|
||||
AliasedImageblock { data_size },
|
||||
CallStackDepth { depth },
|
||||
OpenClMode,
|
||||
@@ -1226,7 +1208,6 @@ codec_enum! {
|
||||
RowLockstep,
|
||||
FlatGrid,
|
||||
CallThreadgroups,
|
||||
SparseTextureWrites { slot, atomic },
|
||||
TileThreadgroupMemory { index },
|
||||
TextureSwizzle { slot },
|
||||
TileImageblock { data_size, alignment },
|
||||
@@ -1237,19 +1218,8 @@ codec_enum! {
|
||||
DroppedColor { color },
|
||||
DepthClampRange,
|
||||
RotatedWeights,
|
||||
ConstantLanes { slot },
|
||||
FunctionTableRange { addressed },
|
||||
TileThreadgroup { tile_sized },
|
||||
ConstexprSampled { slot, modes },
|
||||
CubicSampler { slot },
|
||||
CubicArgumentSampler { stage },
|
||||
HeapRawSamples { stage, sampler },
|
||||
CrossClassReads { slot },
|
||||
HeapCrossClassNeutral { stage, class, every_member },
|
||||
HeapResidency { stage },
|
||||
HeapStorageReads { stage, class },
|
||||
AnisotropicSampler { slot },
|
||||
StorageTextureIntegerChannels { slot },
|
||||
ObjectThreadgroupArena { static_bytes, payload },
|
||||
MergedDraws,
|
||||
QuadPrimitiveIds,
|
||||
@@ -1258,7 +1228,6 @@ codec_enum! {
|
||||
BorderTexels { slot },
|
||||
RegionViewports,
|
||||
PartialThreadgroups,
|
||||
TexelBufferParts { slot },
|
||||
AddressAlignment { slot, align },
|
||||
GridTiles,
|
||||
PrivateArena { slot_bytes },
|
||||
@@ -1268,7 +1237,7 @@ codec_enum! {
|
||||
Mechanism {
|
||||
Specialization, Variant, PushConstant, DynamicState, DynamicStateOrPushConstant,
|
||||
Builtin, PlanTimeCheck, BinderView, KeyProjection, RegionSelected,
|
||||
SyntheticBinding, RenderPassContract, None, PipelineStateOrPushConstant,
|
||||
RenderPassContract, None, PipelineStateOrPushConstant,
|
||||
PipelineState,
|
||||
}
|
||||
}
|
||||
@@ -1278,8 +1247,8 @@ codec_enum! {
|
||||
codec_struct! {
|
||||
RelocatableModule { words, relocs, requirements }
|
||||
FunctionArtifact {
|
||||
key, module, interface, facts, subgroup, reconvergence, precision, strategies, blob,
|
||||
requirements, variant_bits, profile, kernel, reflection, slot_writes, specialized, stats,
|
||||
key, module, interface, facts, subgroup, reconvergence, precision, strategies,
|
||||
requirements, variant_bits, profile, kernel, reflection, slot_writes, stats,
|
||||
}
|
||||
StageReflection { bindings, attributes }
|
||||
SlotWrite { name, parameter, binding_type, index, count, used, access, writes }
|
||||
@@ -1316,13 +1285,9 @@ codec_struct! {
|
||||
}
|
||||
StageModule {
|
||||
stage, entry_point, spirv, specialization, required_subgroup_size, stage_flags,
|
||||
reconvergence, precision_notes, strategies, constant_blob, rounded_colors,
|
||||
specialized_notes, own_pixel_textures,
|
||||
reconvergence, precision_notes, strategies, rounded_colors, own_pixel_textures,
|
||||
private_bytes, stats,
|
||||
}
|
||||
SpecializedNote { note, when }
|
||||
SpecClause { all }
|
||||
SpecTest { key, mask, bits, equal }
|
||||
SpecializationLayout { constants }
|
||||
SpecConstant { id, key, size, default, unread_bits }
|
||||
RuntimeDependency { fact, mechanism }
|
||||
@@ -1332,7 +1297,7 @@ codec_struct! {
|
||||
metal_max_total_threads_per_threadgroup,
|
||||
}
|
||||
PipelineInterface {
|
||||
slots, threadgroup, needs_pointer_translation, needs_handle_translation, push,
|
||||
slots, threadgroup, push,
|
||||
reaches_command_buffers, command_writes, texture_writing_stages,
|
||||
reads_unbound_resources, writes_unbound_resources, unbound_storage_textures, writes_memory,
|
||||
numbered_samplers, stage_in,
|
||||
@@ -1340,8 +1305,7 @@ codec_struct! {
|
||||
PipelineLayout { sets, push_constants }
|
||||
DescriptorSetLayout { set, bindings, flags }
|
||||
DescriptorBinding {
|
||||
binding, ty, count, stages, source, immutable_sampler, flags, variables,
|
||||
immutable_samplers,
|
||||
binding, ty, count, stages, source, flags, variables,
|
||||
}
|
||||
PushConstantRange { stages, offset, size }
|
||||
VertexInputState { bindings, attributes, pulled }
|
||||
@@ -1350,7 +1314,7 @@ codec_struct! {
|
||||
PulledAttribute { attribute, buffer_index, format, offset, step_function, step_rate, stride }
|
||||
GraphicsState {
|
||||
topology, color_attachments, depth_format, stencil_format, rasterization_samples,
|
||||
alpha_to_coverage, alpha_to_one, rasterizer_discard, dynamic_states, input_attachments,
|
||||
alpha_to_coverage, alpha_to_one, rasterizer_discard, dynamic_states,
|
||||
max_vertex_amplification_count, declares_layer,
|
||||
tessellation, vertex_writes_memory, writes_viewport_index, writes_point_size, writes_depth,
|
||||
reads_barycentric_coord, reads_primitive_id, interpolates_at_sample,
|
||||
@@ -1364,7 +1328,6 @@ codec_struct! {
|
||||
LineBandState { push_offset, primitive }
|
||||
ColorAttachmentState { format, write_mask, blend }
|
||||
BlendState { src_color, dst_color, color_op, src_alpha, dst_alpha, alpha_op }
|
||||
InputAttachmentUse { color_index, input_attachment_index, format_class }
|
||||
}
|
||||
|
||||
codec_enum! {
|
||||
@@ -1450,12 +1413,8 @@ codec_enum! {
|
||||
DeviceHalfDenormals,
|
||||
}
|
||||
BindingSource {
|
||||
Buffer(f0), Texture(f0), Sampler(f0), CombinedTextureSampler { texture, sampler },
|
||||
Synthetic { stage, binding }, Heap(f0), InputAttachment(f0), HeapSampler { stage, sampler },
|
||||
Buffer(f0), Synthetic { stage, binding }, IdentityArray,
|
||||
AccelerationStructure { slot, level }, TileAttachment(f0), TileMap(f0),
|
||||
SeparateTexture { texture, sampler }, SeparateSampler { stage, sampler },
|
||||
SamplerArray { stage, compare, integer },
|
||||
IdentityArray,
|
||||
}
|
||||
VertexStride { Static(f0), PerBind }
|
||||
}
|
||||
|
||||
Vendored
+5
-98
@@ -60,7 +60,7 @@ mod tests;
|
||||
/// unchanged version, and its bless records the version. Independent of the crate's version and of
|
||||
/// [`ARTIFACT_FORMAT_VERSION`]. The commit that bumps it says what changed; this comment keeps no
|
||||
/// history.
|
||||
pub const SEMANTICS_VERSION: u32 = 2354;
|
||||
pub const SEMANTICS_VERSION: u32 = 2355;
|
||||
|
||||
/// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the
|
||||
/// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another
|
||||
@@ -70,7 +70,7 @@ pub const SEMANTICS_VERSION: u32 = 2354;
|
||||
/// re-typed in an encoded type, its `codec` body or its `envelope`. A variant removed while its tag
|
||||
/// stays unused needs no bump: an entry holding it fails to decode, which is a miss. The commit that
|
||||
/// bumps it says what changed; this comment keeps no history.
|
||||
pub const ARTIFACT_FORMAT_VERSION: u32 = 606;
|
||||
pub const ARTIFACT_FORMAT_VERSION: u32 = 607;
|
||||
|
||||
/// 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
|
||||
@@ -131,8 +131,7 @@ impl fmt::Debug for PipelineKey {
|
||||
}
|
||||
|
||||
/// 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
|
||||
/// `StorageTextureFormat` fact maps to `Variant`, 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
|
||||
@@ -144,41 +143,11 @@ impl fmt::Debug for PipelineKey {
|
||||
pub struct VariantKey {
|
||||
#[cfg_attr(feature = "serde", serde(with = "crate::pipeline::serde_pairs"))]
|
||||
pub storage_images: BTreeMap<SlotRef, StorageImageChoice>,
|
||||
pub psb_slots: BTreeSet<SlotRef>,
|
||||
/// 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.
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
pub emulated_simdgroups: bool,
|
||||
/// 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.
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
pub srgb_textures: BTreeSet<SlotRef>,
|
||||
/// 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. 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.
|
||||
#[cfg_attr(
|
||||
feature = "serde",
|
||||
serde(default, with = "crate::pipeline::serde_pairs")
|
||||
)]
|
||||
pub texel_buffer_parts: BTreeMap<SlotRef, u32>,
|
||||
/// 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. 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")
|
||||
)]
|
||||
pub address_maps: BTreeMap<SlotRef, crate::metal::sampler::AddressModeMap>,
|
||||
/// 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
|
||||
@@ -291,15 +260,6 @@ pub struct VariantKey {
|
||||
/// (`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
|
||||
/// `SamplerWord::CUBIC_STATE` (`LoweringInputs::cubic_samplers`): the variant whose function
|
||||
/// 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<SlotRef, u32>,
|
||||
/// The de-indexed form of a pipeline whose vertex function writes the primitive ID's varying
|
||||
/// (`LoweringInputs::primitive_id_indices`): the vertex
|
||||
/// function of an indexed draw of this index type runs the draw's indices as `index count`
|
||||
@@ -321,18 +281,7 @@ pub struct VariantKey {
|
||||
/// 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.
|
||||
#[cfg_attr(
|
||||
feature = "serde",
|
||||
serde(default, with = "crate::pipeline::serde_pairs")
|
||||
)]
|
||||
pub cross_class: BTreeMap<SlotRef, crate::pipeline::sym::SampledType>,
|
||||
/// The runtime sampler slots of a `RuntimeFact::AnisotropicSampler` that the shape binds to a
|
||||
/// sampler whose word states anisotropy (`SamplerWord::ANISOTROPIC`,
|
||||
/// The runtime sampler slots 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.
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
@@ -360,11 +309,7 @@ impl VariantKey {
|
||||
/// Whether nothing needs a variant (the common path).
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.storage_images.is_empty()
|
||||
&& self.psb_slots.is_empty()
|
||||
&& !self.emulated_simdgroups
|
||||
&& self.srgb_textures.is_empty()
|
||||
&& self.texel_buffer_parts.is_empty()
|
||||
&& self.address_maps.is_empty()
|
||||
&& !self.flat_grid
|
||||
&& !self.call_threadgroups
|
||||
&& !self.replay_bindings
|
||||
@@ -381,18 +326,16 @@ impl VariantKey {
|
||||
&& self.line_band.is_none()
|
||||
&& self.swizzled_storage.is_empty()
|
||||
&& !self.addressed_function_tables
|
||||
&& self.cubic_samplers.is_empty()
|
||||
&& self.primitive_id_indices.is_none()
|
||||
&& !self.quad_primitive_ids
|
||||
&& !self.private_list
|
||||
&& self.cross_class.is_empty()
|
||||
&& self.anisotropic_samplers.is_empty()
|
||||
&& self.open_cl_lines.is_empty()
|
||||
&& !self.region_viewports
|
||||
}
|
||||
|
||||
/// The lowering inputs of the function of `stage` under this key: its storage-image choices,
|
||||
/// device-address slots, kept storage views, raw sRGB slots, cubic and anisotropic samplers,
|
||||
/// device-address slots, kept storage views, raw sRGB slots, anisotropic samplers,
|
||||
/// for the kernel the emulated simdgroups, the flat grid, the folded groups, the partial
|
||||
/// threadgroups and the replay's bindings, for the vertex and fragment functions the draws of one amplification each, for
|
||||
/// the fragment function the colors it writes zero to and those it drops, its depth's clamp
|
||||
@@ -414,12 +357,6 @@ impl VariantKey {
|
||||
.filter(|(s, _)| s.stage == stage)
|
||||
.map(|(s, c)| (*s, *c))
|
||||
.collect();
|
||||
out.psb_slots = self
|
||||
.psb_slots
|
||||
.iter()
|
||||
.filter(|s| s.stage == stage)
|
||||
.copied()
|
||||
.collect();
|
||||
out.emulated_simdgroups =
|
||||
self.emulated_simdgroups && stage == crate::pipeline::sym::Stage::Kernel;
|
||||
out.flat_grid = self.flat_grid && stage == crate::pipeline::sym::Stage::Kernel;
|
||||
@@ -446,30 +383,6 @@ impl VariantKey {
|
||||
.filter(|_| stage != crate::pipeline::sym::Stage::Kernel);
|
||||
out.region_viewports =
|
||||
self.region_viewports && stage == crate::pipeline::sym::Stage::Vertex;
|
||||
out.srgb_textures = self
|
||||
.srgb_textures
|
||||
.iter()
|
||||
.filter(|s| s.stage == stage)
|
||||
.copied()
|
||||
.collect();
|
||||
out.texel_buffer_parts = self
|
||||
.texel_buffer_parts
|
||||
.iter()
|
||||
.filter(|(s, _)| s.stage == stage)
|
||||
.map(|(s, parts)| (*s, *parts))
|
||||
.collect();
|
||||
out.address_maps = self
|
||||
.address_maps
|
||||
.iter()
|
||||
.filter(|(s, _)| s.stage == stage)
|
||||
.map(|(s, m)| (*s, *m))
|
||||
.collect();
|
||||
out.cubic_samplers = self
|
||||
.cubic_samplers
|
||||
.iter()
|
||||
.filter(|(s, _)| s.stage == stage)
|
||||
.map(|(s, w)| (*s, *w))
|
||||
.collect();
|
||||
out.anisotropic_samplers = self
|
||||
.anisotropic_samplers
|
||||
.iter()
|
||||
@@ -494,12 +407,6 @@ impl VariantKey {
|
||||
.filter(|s| s.stage == stage)
|
||||
.copied()
|
||||
.collect();
|
||||
out.cross_class = self
|
||||
.cross_class
|
||||
.iter()
|
||||
.filter(|(s, _)| s.stage == stage)
|
||||
.map(|(s, c)| (*s, *c))
|
||||
.collect();
|
||||
if stage == crate::pipeline::sym::Stage::Fragment {
|
||||
out.zeroed_colors = self.zeroed_colors.clone();
|
||||
out.dropped_colors = self.dropped_colors.clone();
|
||||
|
||||
+9
-330
@@ -5,7 +5,7 @@
|
||||
//! `llvm-as` assembles the owned fixtures; a missing tool skips a test visibly.
|
||||
|
||||
use crate::budget::Budget;
|
||||
use crate::device::{Device, DeviceDescription, DevicePolicy};
|
||||
use crate::device::{Device, DeviceDescription};
|
||||
use crate::library::{CompiledFunction, FunctionStage, Library};
|
||||
use crate::metal;
|
||||
use crate::pipeline::artifact::{ComputePipeline, RenderPipeline};
|
||||
@@ -37,14 +37,14 @@ fn fixture(stem: &str) -> Option<Vec<u8>> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Committed profile `stem` as a device with the resident-table domains.
|
||||
/// Committed profile `stem` as a device.
|
||||
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")
|
||||
Device::from_queries(desc).expect("device")
|
||||
}
|
||||
|
||||
/// `store_const` compiled on `dev`, with its compute pipeline.
|
||||
@@ -365,41 +365,6 @@ fn earlier_format_versions_are_stale() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The fact format version 4 added encodes and decodes.
|
||||
#[test]
|
||||
fn the_heap_numeric_type_fact_round_trips() {
|
||||
use crate::pipeline::facts::RuntimeFact;
|
||||
use crate::pipeline::sym::{
|
||||
ImageAccess, ImageDim, ImageHandleClass, SampledType, StorageFormatClass,
|
||||
};
|
||||
let fact = RuntimeFact::HeapNumericType {
|
||||
class: ImageHandleClass {
|
||||
dim: ImageDim::D2,
|
||||
arrayed: true,
|
||||
multisampled: false,
|
||||
sampled_type: SampledType::Float,
|
||||
depth_compare: false,
|
||||
access: ImageAccess::Storage,
|
||||
format: StorageFormatClass::Unknown,
|
||||
},
|
||||
};
|
||||
assert_eq!(decode::<RuntimeFact>(&encode(&fact)), Ok(fact));
|
||||
}
|
||||
|
||||
/// The `AnisotropicSampler` fact encodes and decodes.
|
||||
#[test]
|
||||
fn the_anisotropic_sampler_fact_round_trips() {
|
||||
use crate::pipeline::facts::RuntimeFact;
|
||||
let fact = RuntimeFact::AnisotropicSampler {
|
||||
slot: SlotRef {
|
||||
stage: Stage::Fragment,
|
||||
class: SlotClass::Sampler,
|
||||
index: 3,
|
||||
},
|
||||
};
|
||||
assert_eq!(decode::<RuntimeFact>(&encode(&fact)), Ok(fact));
|
||||
}
|
||||
|
||||
/// The members format version 178 appends encode and decode, and each decodes as itself:
|
||||
/// `VkFeature::Maintenance5` and the three framebuffer `VkLimit`s.
|
||||
#[test]
|
||||
@@ -418,13 +383,10 @@ fn the_version_178_members_round_trip() {
|
||||
|
||||
/// The members format version 179 appends encode and decode, and each decodes as itself:
|
||||
/// `VkFeature::{OcclusionQueryPrecise, DepthBiasControl, FloatRepresentation, DepthBiasExact}`,
|
||||
/// `VkExtension::ExtDepthBiasControl`, and `PushField::IndexCapacity`.
|
||||
/// and `VkExtension::ExtDepthBiasControl`.
|
||||
#[test]
|
||||
fn the_version_179_members_round_trip() {
|
||||
use crate::device::requirements::{VkExtension, VkFeature};
|
||||
use crate::pipeline::sym::PushField;
|
||||
let field = PushField::IndexCapacity;
|
||||
assert_eq!(decode::<PushField>(&encode(&field)), Ok(field));
|
||||
for feature in [
|
||||
VkFeature::OcclusionQueryPrecise,
|
||||
VkFeature::DepthBiasControl,
|
||||
@@ -655,23 +617,6 @@ fn the_version_253_members_round_trip() {
|
||||
assert_eq!(decode::<SpecKey>(&encode(&key)), Ok(key));
|
||||
}
|
||||
|
||||
/// The members format version 267 appends encode and decode as themselves: a sparse texture slot's
|
||||
/// constant lanes, as a specialization and as a fact.
|
||||
#[test]
|
||||
fn the_version_267_members_round_trip() {
|
||||
use crate::pipeline::facts::RuntimeFact;
|
||||
use crate::pipeline::sym::SpecKey;
|
||||
let slot = SlotRef {
|
||||
stage: Stage::Fragment,
|
||||
class: SlotClass::Texture,
|
||||
index: 3,
|
||||
};
|
||||
let key = SpecKey::ConstantLanes(slot);
|
||||
assert_eq!(decode::<SpecKey>(&encode(&key)), Ok(key));
|
||||
let fact = RuntimeFact::ConstantLanes { slot };
|
||||
assert_eq!(decode::<RuntimeFact>(&encode(&fact)), Ok(fact));
|
||||
}
|
||||
|
||||
/// The member format version 374 appends encodes and decodes as itself: the axes on which a texture
|
||||
/// slot's 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.
|
||||
@@ -685,22 +630,6 @@ fn the_version_374_member_round_trips() {
|
||||
};
|
||||
let key = SpecKey::OffsetBaseAxes(slot);
|
||||
assert_eq!(decode::<SpecKey>(&encode(&key)), Ok(key));
|
||||
assert_ne!(encode(&key), encode(&SpecKey::BoundTexelFormat(slot)));
|
||||
}
|
||||
|
||||
/// The member format version 485 appends encodes and decodes as itself: the word of the sampler
|
||||
/// bound at a slot, which a specialized note's test alone reads.
|
||||
#[test]
|
||||
fn the_version_485_member_round_trips() {
|
||||
use crate::pipeline::sym::SpecKey;
|
||||
let slot = SlotRef {
|
||||
stage: Stage::Fragment,
|
||||
class: SlotClass::Sampler,
|
||||
index: 2,
|
||||
};
|
||||
let key = SpecKey::BoundSamplerWord(slot);
|
||||
assert_eq!(decode::<SpecKey>(&encode(&key)), Ok(key));
|
||||
assert_ne!(encode(&key), encode(&SpecKey::NearestPixelSampler(slot)));
|
||||
}
|
||||
|
||||
/// The member format version 535 appends encodes and decodes as itself: a kernel's image-only
|
||||
@@ -741,30 +670,13 @@ fn the_version_602_member_round_trips() {
|
||||
assert_eq!(decode::<PrecisionNote>(&encode(¬e)), Ok(note));
|
||||
}
|
||||
|
||||
/// 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`, `PrecisionNote::HalfTexelConversion` and `SrgbTexelDecode`,
|
||||
/// `HandleClass::Sampler { compare, integer }` and
|
||||
/// `SyntheticBinding::SamplerTable`, each beside the others rather than only on its own side's
|
||||
/// fixtures.
|
||||
/// The precision notes format versions 153, 155 and 161 joined from every side encode and decode
|
||||
/// together in one render pipeline: `PrecisionNote::CubeGradientFootprint`,
|
||||
/// `HalfTexelConversion` and `SrgbTexelDecode`, each beside the others rather than only on its own
|
||||
/// side's fixtures.
|
||||
#[test]
|
||||
fn the_merged_members_round_trip_in_one_render_pipeline() {
|
||||
use crate::pipeline::artifact::{PrecisionNote, RuntimeDependency, SpecConstant};
|
||||
use crate::pipeline::facts::{Mechanism, RuntimeFact};
|
||||
use crate::pipeline::layout::{BindingSource, DescriptorBinding, DescriptorSetLayout};
|
||||
use crate::pipeline::sym::{
|
||||
CombinedSampler, HandleClass, ResourceKind, SamplerRef, SpecKey, SyntheticBinding,
|
||||
};
|
||||
use crate::vk;
|
||||
let texture = SlotRef {
|
||||
stage: Stage::Fragment,
|
||||
class: SlotClass::Texture,
|
||||
index: 3,
|
||||
};
|
||||
let sampler = CombinedSampler::new(SamplerRef::Slot(1), true, false);
|
||||
let kind = ResourceKind::CombinedTextureSampler(sampler);
|
||||
assert_eq!(decode::<ResourceKind>(&encode(&kind)), Ok(kind));
|
||||
use crate::pipeline::artifact::PrecisionNote;
|
||||
let notes = [
|
||||
PrecisionNote::CubeGradientFootprint,
|
||||
PrecisionNote::HalfTexelConversion,
|
||||
@@ -784,82 +696,6 @@ fn the_merged_members_round_trip_in_one_render_pipeline() {
|
||||
.compile_render_pipeline(&d, &Budget::standard())
|
||||
.expect("pipeline");
|
||||
p.stages[0].precision_notes.extend(notes);
|
||||
let id = p.stages[0].specialization.constants.len() as u32;
|
||||
p.stages[0].specialization.constants.push(SpecConstant {
|
||||
id,
|
||||
key: SpecKey::BicubicTexels(texture),
|
||||
size: 4,
|
||||
default: 0,
|
||||
unread_bits: 0,
|
||||
});
|
||||
let set = p.layout.sets.len() as u32;
|
||||
p.layout.sets.push(DescriptorSetLayout {
|
||||
set,
|
||||
bindings: vec![
|
||||
DescriptorBinding {
|
||||
binding: 0,
|
||||
ty: vk::DescriptorType::COMBINED_IMAGE_SAMPLER,
|
||||
count: 1,
|
||||
stages: vk::ShaderStageFlags::FRAGMENT,
|
||||
source: BindingSource::CombinedTextureSampler { texture, sampler },
|
||||
immutable_sampler: None,
|
||||
flags: vk::DescriptorBindingFlags::empty(),
|
||||
variables: 1,
|
||||
immutable_samplers: Vec::new(),
|
||||
},
|
||||
DescriptorBinding {
|
||||
binding: 1,
|
||||
ty: vk::DescriptorType::SAMPLED_IMAGE,
|
||||
count: 1,
|
||||
stages: vk::ShaderStageFlags::FRAGMENT,
|
||||
source: BindingSource::Texture(texture),
|
||||
immutable_sampler: None,
|
||||
flags: vk::DescriptorBindingFlags::empty(),
|
||||
variables: 1,
|
||||
immutable_samplers: Vec::new(),
|
||||
},
|
||||
],
|
||||
flags: vk::DescriptorSetLayoutCreateFlags::empty(),
|
||||
});
|
||||
// An argument buffer's sampler array of a comparison use of an integer texel, and the stage's
|
||||
// sampler table.
|
||||
let argument_samplers = vec![
|
||||
DescriptorBinding {
|
||||
binding: 2,
|
||||
ty: vk::DescriptorType::SAMPLER,
|
||||
count: 16,
|
||||
stages: vk::ShaderStageFlags::FRAGMENT,
|
||||
source: BindingSource::Heap(HandleClass::Sampler {
|
||||
compare: true,
|
||||
integer: true,
|
||||
}),
|
||||
immutable_sampler: None,
|
||||
flags: vk::DescriptorBindingFlags::PARTIALLY_BOUND,
|
||||
variables: 1,
|
||||
immutable_samplers: Vec::new(),
|
||||
},
|
||||
DescriptorBinding {
|
||||
binding: 3,
|
||||
ty: vk::DescriptorType::STORAGE_BUFFER,
|
||||
count: 1,
|
||||
stages: vk::ShaderStageFlags::FRAGMENT,
|
||||
source: BindingSource::Synthetic {
|
||||
stage: Stage::Fragment,
|
||||
binding: SyntheticBinding::SamplerTable,
|
||||
},
|
||||
immutable_sampler: None,
|
||||
flags: vk::DescriptorBindingFlags::empty(),
|
||||
variables: 1,
|
||||
immutable_samplers: Vec::new(),
|
||||
},
|
||||
];
|
||||
if let Some(last) = p.layout.sets.last_mut() {
|
||||
last.bindings.extend(argument_samplers);
|
||||
}
|
||||
p.dependencies.push(RuntimeDependency {
|
||||
fact: RuntimeFact::SrgbTexture { slot: texture },
|
||||
mechanism: Mechanism::Variant,
|
||||
});
|
||||
let bytes = encode(&p);
|
||||
let back = decode::<RenderPipeline>(&bytes).expect("decoded");
|
||||
assert_eq!(back, p);
|
||||
@@ -869,130 +705,6 @@ fn the_merged_members_round_trip_in_one_render_pipeline() {
|
||||
assert!(notes
|
||||
.iter()
|
||||
.all(|n| sealed.stages[0].precision_notes.contains(n)));
|
||||
assert!(sealed.stages[0]
|
||||
.specialization
|
||||
.constants
|
||||
.iter()
|
||||
.any(|c| c.key == SpecKey::BicubicTexels(texture)));
|
||||
let bindings = sealed.layout.sets.last().map(|s| &s.bindings[..]);
|
||||
assert!(matches!(
|
||||
bindings.map(|b| &b[0].source),
|
||||
Some(BindingSource::CombinedTextureSampler { sampler, .. })
|
||||
if sampler.compare
|
||||
));
|
||||
assert_eq!(
|
||||
bindings.map(|b| &b[1].source),
|
||||
Some(&BindingSource::Texture(texture))
|
||||
);
|
||||
assert!(matches!(
|
||||
bindings.map(|b| &b[2].source),
|
||||
Some(BindingSource::Heap(HandleClass::Sampler {
|
||||
compare: true,
|
||||
integer: true
|
||||
}))
|
||||
));
|
||||
assert!(matches!(
|
||||
bindings.map(|b| &b[3].source),
|
||||
Some(BindingSource::Synthetic {
|
||||
binding: SyntheticBinding::SamplerTable,
|
||||
..
|
||||
})
|
||||
));
|
||||
let fact = RuntimeFact::SrgbTexture { slot: texture };
|
||||
assert!(
|
||||
sealed.dependencies.iter().any(|d| d.fact == fact),
|
||||
"{fact:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// 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
|
||||
/// one does. Format version 158's members: a pipeline whose stage takes its combined image samplers
|
||||
/// apart (`smp_runtime_array` on `moltenvk-m3`) round-trips its separate texture and separate
|
||||
/// sampler bindings, and the symbols its relocations name.
|
||||
#[test]
|
||||
fn the_separate_bindings_round_trip() {
|
||||
use crate::pipeline::layout::BindingSource;
|
||||
let dev = device("moltenvk-m3");
|
||||
let Some(bc) = fixture("smp_runtime_array") else {
|
||||
return;
|
||||
};
|
||||
let f = Library::from_air(&bc)
|
||||
.and_then(|lib| lib.function("smp_runtime_array"))
|
||||
.expect("kernel");
|
||||
let d = ComputePipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new(f)));
|
||||
let pipeline = dev
|
||||
.compile_compute_pipeline(&d, &Budget::standard())
|
||||
.expect("pipeline");
|
||||
let sources: Vec<_> = pipeline.layout.sets[0]
|
||||
.bindings
|
||||
.iter()
|
||||
.map(|b| b.source)
|
||||
.collect();
|
||||
assert_eq!(
|
||||
sources
|
||||
.iter()
|
||||
.filter(|s| matches!(s, BindingSource::SeparateTexture { .. }))
|
||||
.count(),
|
||||
32
|
||||
);
|
||||
assert!(sources
|
||||
.iter()
|
||||
.any(|s| matches!(s, BindingSource::SeparateSampler { .. })));
|
||||
let decoded = ComputePipeline::from_bytes(&pipeline.to_bytes(), &dev).expect("decoded");
|
||||
assert_eq!(decoded, pipeline);
|
||||
assert_eq!(
|
||||
decoded.to_bytes(),
|
||||
pipeline.to_bytes(),
|
||||
"the encoding is canonical"
|
||||
);
|
||||
// Within the limit the same kernel keeps its combined bindings, which round-trip alike.
|
||||
let within = device("lavapipe");
|
||||
let pipeline = within
|
||||
.compile_compute_pipeline(&d, &Budget::standard())
|
||||
.expect("pipeline");
|
||||
assert_eq!(
|
||||
pipeline.layout.sets[0]
|
||||
.bindings
|
||||
.iter()
|
||||
.filter(|b| matches!(b.source, BindingSource::CombinedTextureSampler { .. }))
|
||||
.count(),
|
||||
32
|
||||
);
|
||||
let decoded = ComputePipeline::from_bytes(&pipeline.to_bytes(), &within).expect("decoded");
|
||||
assert_eq!(decoded, pipeline);
|
||||
}
|
||||
|
||||
/// A combined binding's symbol and a separate texture's, whose index packs its use above its
|
||||
/// texture slot, round-trip through the codec for every use, at the slots' bounds.
|
||||
#[test]
|
||||
fn combined_and_separate_texture_symbols_round_trip() {
|
||||
use crate::pipeline::sym::{CombinedSampler, ResourceKind, ResourceSlot, SamplerRef};
|
||||
for sampler in [
|
||||
SamplerRef::Slot(3),
|
||||
SamplerRef::Constexpr([u64::MAX >> 1, 7]),
|
||||
] {
|
||||
for rank in 0..4u32 {
|
||||
let c = CombinedSampler::new(sampler, rank & 2 != 0, rank & 1 != 0);
|
||||
for texture in [0, 127, (1 << 28) - 1] {
|
||||
let combined = ResourceSlot {
|
||||
stage: Stage::Fragment,
|
||||
kind: ResourceKind::CombinedTextureSampler(c),
|
||||
index: texture,
|
||||
};
|
||||
let separate =
|
||||
ResourceSlot::separate_texture(Stage::Fragment, texture, c).expect("symbol");
|
||||
for s in [combined, separate] {
|
||||
assert_eq!(decode::<ResourceSlot>(&encode(&s)), Ok(s));
|
||||
}
|
||||
assert_eq!(
|
||||
decode::<ResourceSlot>(&encode(&separate)).map(|s| s.separate_texture_of()),
|
||||
Ok(Some((texture, c)))
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A body that passes the checksum is still decoded strictly (every byte used) and scanned: a
|
||||
@@ -1179,39 +891,6 @@ fn a_chunked_encoding_is_the_encoding() {
|
||||
assert_eq!(decode::<Vec<u8>>(&short), Err(Malformed));
|
||||
}
|
||||
|
||||
/// A pipeline whose constant blob is non-zero and longer than a chunk (196,615 bytes) writes
|
||||
/// exactly `to_bytes`' bytes, also through a writer that takes 7 bytes per call, and they decode
|
||||
/// to the pipeline.
|
||||
#[test]
|
||||
fn a_pipeline_with_a_long_blob_writes_its_bytes() {
|
||||
/// A writer that takes at most 7 bytes per call.
|
||||
struct Short(Vec<u8>);
|
||||
impl std::io::Write for Short {
|
||||
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
|
||||
let n = bytes.len().min(7);
|
||||
self.0.extend_from_slice(&bytes[..n]);
|
||||
Ok(n)
|
||||
}
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
let dev = device("moltenvk-m3");
|
||||
let Some((_, mut p)) = store_const(&dev) else {
|
||||
return;
|
||||
};
|
||||
let blob: std::sync::Arc<[u8]> = (0..3 * CHUNK + 7).map(|i| (i % 251) as u8 + 1).collect();
|
||||
p.stage.constant_blob = Some(blob);
|
||||
let bytes = p.to_bytes();
|
||||
let mut whole = Vec::new();
|
||||
p.write_to(&mut whole).expect("write");
|
||||
assert_eq!(whole, bytes);
|
||||
let mut short = Short(Vec::new());
|
||||
p.write_to(&mut short).expect("write");
|
||||
assert_eq!(short.0, bytes);
|
||||
assert_eq!(ComputePipeline::from_bytes(&bytes, &dev), Ok(p));
|
||||
}
|
||||
|
||||
/// The frame layout is stable: a change fails here and needs an `ARTIFACT_FORMAT_VERSION` bump.
|
||||
#[test]
|
||||
fn the_frame_layout_is_pinned() {
|
||||
|
||||
@@ -180,16 +180,12 @@ impl DeviceProfile {
|
||||
VkLimit::MaxPerStageDescriptorStorageImages => {
|
||||
up(l.max_per_stage_descriptor_storage_images)
|
||||
}
|
||||
VkLimit::MaxPerStageDescriptorInputAttachments => {
|
||||
up(l.max_per_stage_descriptor_input_attachments)
|
||||
}
|
||||
VkLimit::MaxPerStageResources => up(l.max_per_stage_resources),
|
||||
VkLimit::MaxDescriptorSetSamplers => up(l.max_descriptor_set_samplers),
|
||||
VkLimit::MaxDescriptorSetUniformBuffers => up(l.max_descriptor_set_uniform_buffers),
|
||||
VkLimit::MaxDescriptorSetStorageBuffers => up(l.max_descriptor_set_storage_buffers),
|
||||
VkLimit::MaxDescriptorSetSampledImages => up(l.max_descriptor_set_sampled_images),
|
||||
VkLimit::MaxDescriptorSetStorageImages => up(l.max_descriptor_set_storage_images),
|
||||
VkLimit::MaxDescriptorSetInputAttachments => up(l.max_descriptor_set_input_attachments),
|
||||
VkLimit::MaxDescriptorSetUpdateAfterBindSamplers => {
|
||||
up(l.max_descriptor_set_update_after_bind_samplers)
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! `Device::from_queries`: the only producer of a `DeviceProfile`.
|
||||
//!
|
||||
//! The profile is a pure function of the description's Vulkan queries and the policy: no driver or
|
||||
//! GPU identity decides anything. Memory's A/F split is the
|
||||
//! The profile is a pure function of the description's Vulkan queries: no driver or GPU identity
|
||||
//! decides anything. Memory's A/F split is the
|
||||
//! only field that selects a pointer model; every other field selects leaf encodings or feeds the
|
||||
//! requirement check.
|
||||
|
||||
@@ -13,22 +13,21 @@ use crate::device::description::{
|
||||
};
|
||||
use crate::device::function_storage;
|
||||
use crate::device::metal::MetalDeviceProperties;
|
||||
use crate::device::policy::DevicePolicy;
|
||||
use crate::device::profile::{
|
||||
BufferAccess, DescriptorCaps, DeviceProfile, EnabledCaps, FormatTable, FragmentCaps,
|
||||
FunctionStorage, HandleDomain, ImageCaps, Independence, LeafCaps, PointerDomain, ProfileFields,
|
||||
FunctionStorage, ImageCaps, Independence, LeafCaps, ProfileFields,
|
||||
};
|
||||
use crate::device::requirements::{
|
||||
ApiVersion, FloatControl, FloatWidth, FormatUsage, ResolveMode, SubgroupOp, VkExtension,
|
||||
VkFeature, VkLimit, VkProperty,
|
||||
};
|
||||
use crate::device::subgroup::{OpBits, StageSubgroup, SubgroupModel, SubgroupSizes};
|
||||
use crate::error::{Capability, DescriptorError, Error, Feature, Unsupported};
|
||||
use crate::error::{Capability, Error, Feature, Unsupported};
|
||||
use crate::pipeline::sym::Stage;
|
||||
use crate::vk;
|
||||
|
||||
/// A device the core translates for: its profile, the Metal properties the consumer reports to
|
||||
/// the guest, and the policy it was created with. Cheap to clone; `Send + Sync`.
|
||||
/// A device the core translates for: its profile and the Metal properties the consumer reports to
|
||||
/// the guest. Cheap to clone; `Send + Sync`.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Device(Arc<DeviceInner>);
|
||||
|
||||
@@ -38,7 +37,6 @@ struct DeviceInner {
|
||||
/// `profile`'s fingerprint, computed once: every key and artifact check takes it.
|
||||
fingerprint: crate::cache::Hash256,
|
||||
metal: MetalDeviceProperties,
|
||||
policy: DevicePolicy,
|
||||
/// The description's `generated_commands`, which only the device replay reads. No translation
|
||||
/// reads it, so it is not a profile field: two devices that differ only in it share every
|
||||
/// artifact.
|
||||
@@ -49,8 +47,9 @@ struct DeviceInner {
|
||||
}
|
||||
|
||||
impl Device {
|
||||
/// The device its Vulkan queries decide, under `policy`: the profile is a function of what
|
||||
/// the description states the device supports and the consumer enabled, and of the policy.
|
||||
/// The device its Vulkan queries decide: the profile is a function of what the description
|
||||
/// states the device supports and the consumer enabled. A pointer is the device address it
|
||||
/// holds and a texture's or sampler's handle is its `gpuResourceID` (the identity domains).
|
||||
/// The description need not come from a device: one read from a Khronos profiles JSON document
|
||||
/// ([`DeviceDescription::from_khronos_json`]) or built field by field
|
||||
/// ([`DeviceDescription::new`]) makes a device with no `VkDevice` behind it.
|
||||
@@ -62,10 +61,8 @@ impl Device {
|
||||
/// a feature neither its version nor its listed extensions expose, a feature without the
|
||||
/// feature Vulkan requires enabled with it, or `shaderQuadControl` without
|
||||
/// `shaderMaximalReconvergence`, which every device with the one supports (`InvalidDescriptor`,
|
||||
/// the invariants `device::enables` states), a policy that turns containment off while guest isolation
|
||||
/// is on (`InvalidDescriptor`), a policy that takes one identity domain without the other
|
||||
/// (`InvalidDescriptor`), and the identity domains on a device without `bufferDeviceAddress`
|
||||
/// and `shaderInt64` (`Unsupported{IdentityDomains}`).
|
||||
/// the invariants `device::enables` states), and a device without `bufferDeviceAddress` and
|
||||
/// `shaderInt64`, which the identity domains need (`Unsupported{IdentityDomains}`).
|
||||
///
|
||||
/// No identity decides anything: the description's `driver_id`, `driver_version`,
|
||||
/// `vendor_id`, `device_id` and `device_name` are not read. The rasterizer splits clipped
|
||||
@@ -74,7 +71,7 @@ impl Device {
|
||||
/// `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. 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<Device, Error> {
|
||||
pub fn from_queries(desc: DeviceDescription) -> Result<Device, Error> {
|
||||
if desc.api_version < ApiVersion::V1_2 {
|
||||
return Err(Unsupported::needs(
|
||||
Feature::VulkanVersion,
|
||||
@@ -95,14 +92,13 @@ impl Device {
|
||||
.into());
|
||||
}
|
||||
crate::device::enables::check_invariants(&desc)?;
|
||||
identity_domains(&desc, &policy)?;
|
||||
let profile = DeviceProfile::of(derive_fields(&desc, &policy));
|
||||
identity_domains(&desc)?;
|
||||
let profile = DeviceProfile::of(derive_fields(&desc));
|
||||
let metal = MetalDeviceProperties::derive(&profile, &desc.allocation);
|
||||
Ok(Device(Arc::new(DeviceInner {
|
||||
fingerprint: profile.fingerprint(),
|
||||
profile,
|
||||
metal,
|
||||
policy,
|
||||
generated_commands: desc.generated_commands,
|
||||
allocation: desc.allocation,
|
||||
})))
|
||||
@@ -125,11 +121,6 @@ impl Device {
|
||||
&self.0.metal
|
||||
}
|
||||
|
||||
/// The policy the device was created with.
|
||||
pub fn policy(&self) -> &DevicePolicy {
|
||||
&self.0.policy
|
||||
}
|
||||
|
||||
/// `VK_EXT_device_generated_commands` as the description states the consumer enabled it: the
|
||||
/// limits and stages the device replay's generated-commands layout is held to. It is not part
|
||||
/// of [`Device::profile`], so it changes no artifact.
|
||||
@@ -145,27 +136,18 @@ impl Device {
|
||||
}
|
||||
}
|
||||
|
||||
/// The identity domains come as a pair, and need device addresses and 64-bit integers: a
|
||||
/// pointer is a 64-bit device address.
|
||||
fn identity_domains(desc: &DeviceDescription, policy: &DevicePolicy) -> Result<(), Error> {
|
||||
let pointers = policy.pointer_domain == PointerDomain::Identity;
|
||||
let handles = policy.handle_domain == HandleDomain::Identity;
|
||||
if pointers != handles {
|
||||
return Err(Error::InvalidDescriptor(
|
||||
DescriptorError::DeviceDescription {
|
||||
detail: "the identity pointer and handle domains are taken together".into(),
|
||||
},
|
||||
));
|
||||
}
|
||||
/// The identity domains need device addresses and 64-bit integers: a pointer is a 64-bit device
|
||||
/// address.
|
||||
fn identity_domains(desc: &DeviceDescription) -> Result<(), Error> {
|
||||
let needs = [VkFeature::BufferDeviceAddress, VkFeature::ShaderInt64];
|
||||
if pointers && !needs.iter().all(|&f| desc.has(f)) {
|
||||
if !needs.iter().all(|&f| desc.has(f)) {
|
||||
let all = needs.iter().map(|&f| Capability::Feature(f)).collect();
|
||||
return Err(Unsupported::needs_any_of(Feature::IdentityDomains, vec![all]).into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn derive_fields(desc: &DeviceDescription, policy: &DevicePolicy) -> ProfileFields {
|
||||
fn derive_fields(desc: &DeviceDescription) -> ProfileFields {
|
||||
let has = |f: VkFeature| desc.has(f);
|
||||
let ext = |e: VkExtension| desc.extensions.contains(&e);
|
||||
let api = desc.api_version;
|
||||
@@ -258,8 +240,6 @@ fn derive_fields(desc: &DeviceDescription, policy: &DevicePolicy) -> ProfileFiel
|
||||
let (vertex_formats, storage_formats, image_formats) = format_tables(desc);
|
||||
ProfileFields {
|
||||
buffer_access,
|
||||
pointer_domain: policy.pointer_domain,
|
||||
handle_domain: policy.handle_domain,
|
||||
leaf,
|
||||
subgroup: subgroup_model(desc),
|
||||
images,
|
||||
|
||||
@@ -16,9 +16,8 @@ use crate::vk;
|
||||
|
||||
/// One Vulkan physical device as the consumer will create it.
|
||||
///
|
||||
/// With feature `serde` it (and [`DevicePolicy`](crate::device::DevicePolicy)) serializes, so a
|
||||
/// consumer that compiles in a child process can hand the child the pair from which it rebuilds
|
||||
/// the same `Device` (`docs/HOWTO.md` section 5).
|
||||
/// With feature `serde` it serializes, so a consumer that compiles in a child process can hand the
|
||||
/// child the description from which it rebuilds the same `Device` (`docs/HOWTO.md` section 5).
|
||||
#[non_exhaustive]
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
|
||||
@@ -743,15 +743,12 @@ fn limits(p: &Props<'_>, api: ApiVersion, extensions: &BTreeSet<String>) -> Resu
|
||||
max_per_stage_descriptor_storage_buffers: p.u32("maxPerStageDescriptorStorageBuffers")?,
|
||||
max_per_stage_descriptor_sampled_images: p.u32("maxPerStageDescriptorSampledImages")?,
|
||||
max_per_stage_descriptor_storage_images: p.u32("maxPerStageDescriptorStorageImages")?,
|
||||
max_per_stage_descriptor_input_attachments: p
|
||||
.u32("maxPerStageDescriptorInputAttachments")?,
|
||||
max_per_stage_resources: p.u32("maxPerStageResources")?,
|
||||
max_descriptor_set_samplers: p.u32("maxDescriptorSetSamplers")?,
|
||||
max_descriptor_set_uniform_buffers: p.u32("maxDescriptorSetUniformBuffers")?,
|
||||
max_descriptor_set_storage_buffers: p.u32("maxDescriptorSetStorageBuffers")?,
|
||||
max_descriptor_set_sampled_images: p.u32("maxDescriptorSetSampledImages")?,
|
||||
max_descriptor_set_storage_images: p.u32("maxDescriptorSetStorageImages")?,
|
||||
max_descriptor_set_input_attachments: p.u32("maxDescriptorSetInputAttachments")?,
|
||||
max_descriptor_set_update_after_bind_samplers: p
|
||||
.u32("maxDescriptorSetUpdateAfterBindSamplers")?,
|
||||
max_descriptor_set_update_after_bind_sampled_images: p
|
||||
@@ -966,14 +963,12 @@ fn required_limits(version: ApiVersion) -> Vec<(&'static str, Value)> {
|
||||
("maxPerStageDescriptorStorageBuffers", n(4)),
|
||||
("maxPerStageDescriptorSampledImages", n(16)),
|
||||
("maxPerStageDescriptorStorageImages", n(4)),
|
||||
("maxPerStageDescriptorInputAttachments", n(4)),
|
||||
("maxPerStageResources", n(128)),
|
||||
("maxDescriptorSetSamplers", n(96)),
|
||||
("maxDescriptorSetUniformBuffers", n(72)),
|
||||
("maxDescriptorSetStorageBuffers", n(24)),
|
||||
("maxDescriptorSetSampledImages", n(96)),
|
||||
("maxDescriptorSetStorageImages", n(24)),
|
||||
("maxDescriptorSetInputAttachments", n(4)),
|
||||
("maxVertexInputAttributes", n(16)),
|
||||
("maxVertexInputBindings", n(16)),
|
||||
("maxVertexInputAttributeOffset", n(2047)),
|
||||
|
||||
@@ -22,12 +22,7 @@ pub fn mechanism(fact: &RuntimeFact, profile: &DeviceProfile) -> Mechanism {
|
||||
RuntimeFact::ResourcePresence { .. } => Mechanism::Specialization,
|
||||
RuntimeFact::SampleCount => Mechanism::Specialization,
|
||||
// Keyed by a per-slot StorageImageChoice, a separate per-function compile.
|
||||
RuntimeFact::StorageTextureFormat { .. }
|
||||
| RuntimeFact::StorageTextureNumericType { .. } => Mechanism::Variant,
|
||||
// Keyed by the slots bound to an sRGB format's UNORM twin, whose codes the function decodes.
|
||||
RuntimeFact::SrgbTexture { .. } => Mechanism::Variant,
|
||||
RuntimeFact::SamplerCoordinates { .. } => Mechanism::Specialization,
|
||||
RuntimeFact::SamplerReduction { .. } => Mechanism::PlanTimeCheck,
|
||||
RuntimeFact::StorageTextureNumericType { .. } => Mechanism::Variant,
|
||||
RuntimeFact::ImageViewShape { .. } => Mechanism::BinderView,
|
||||
RuntimeFact::VertexFetch { .. } => Mechanism::KeyProjection,
|
||||
RuntimeFact::VertexBufferStride { .. } => {
|
||||
@@ -45,24 +40,7 @@ pub fn mechanism(fact: &RuntimeFact, profile: &DeviceProfile) -> Mechanism {
|
||||
}
|
||||
}
|
||||
RuntimeFact::DeviceAddresses { .. } => Mechanism::PlanTimeCheck,
|
||||
// F: DescriptorRangeExceeded at plan time; A: a variant that makes the slot PSB.
|
||||
RuntimeFact::BufferRangeLimit { .. } => match f.buffer_access {
|
||||
BufferAccess::Addressed => Mechanism::Variant,
|
||||
BufferAccess::Floor => Mechanism::PlanTimeCheck,
|
||||
},
|
||||
RuntimeFact::TexelBufferRange { .. } => Mechanism::PlanTimeCheck,
|
||||
RuntimeFact::FramebufferFetch { .. } => Mechanism::RenderPassContract,
|
||||
// A function that writes the status buffer reaches it at the device address the binder
|
||||
// writes into its push field (`PushField::ExecutionStatusAddress`), or, on a device that
|
||||
// does not address buffers, through the stage's binding of it
|
||||
// (`SyntheticBinding::ExecutionStatus`).
|
||||
RuntimeFact::ExecutionStatus => match f.buffer_access {
|
||||
BufferAccess::Addressed => Mechanism::PushConstant,
|
||||
BufferAccess::Floor => Mechanism::SyntheticBinding,
|
||||
},
|
||||
// The binder writes each heap element from the texture's facts and reports a texture
|
||||
// the class cannot hold.
|
||||
RuntimeFact::HeapNumericType { .. } => Mechanism::BinderView,
|
||||
// The scratch's length is a specialization of the local size; the planner checks each
|
||||
// region's total against the limit.
|
||||
RuntimeFact::SimdgroupEmulation { .. } => Mechanism::PlanTimeCheck,
|
||||
@@ -86,13 +64,8 @@ pub fn mechanism(fact: &RuntimeFact, profile: &DeviceProfile) -> Mechanism {
|
||||
// The binder specializes the alpha from the bound texture's pixel format.
|
||||
RuntimeFact::OutOfBoundsAlpha { .. } => Mechanism::Specialization,
|
||||
RuntimeFact::BorderTexels { .. } => Mechanism::Specialization,
|
||||
// The bound format's treatment is specialized; the planner refuses an unmeasured
|
||||
// format.
|
||||
RuntimeFact::BicubicTexels { .. } => Mechanism::Specialization,
|
||||
// The binder writes the bound texture's level count per draw or dispatch.
|
||||
RuntimeFact::StorageTextureLevels { .. } => Mechanism::PushConstant,
|
||||
// The binder writes the bound texture's integer channel widths.
|
||||
RuntimeFact::StorageTextureIntegerChannels { .. } => Mechanism::PushConstant,
|
||||
// The binder views each level of the bound texture at its element.
|
||||
RuntimeFact::StorageTextureLevelViews { .. } => Mechanism::BinderView,
|
||||
// The bound texture's sparseness selects the sparse form or the tile map where the module
|
||||
@@ -128,10 +101,6 @@ pub fn mechanism(fact: &RuntimeFact, profile: &DeviceProfile) -> Mechanism {
|
||||
// A pipeline compiled under the flat-grid variant; its plans state it.
|
||||
RuntimeFact::FlatGrid => Mechanism::Variant,
|
||||
RuntimeFact::CallThreadgroups => Mechanism::Variant,
|
||||
// A sparse texture's writes are dropped under the slot's `SparseTexture` specialization;
|
||||
// at a slot updated atomically the planner refuses one.
|
||||
RuntimeFact::SparseTextureWrites { atomic: false, .. } => Mechanism::Specialization,
|
||||
RuntimeFact::SparseTextureWrites { atomic: true, .. } => Mechanism::PlanTimeCheck,
|
||||
// The offsets and the tile memory are specialized; the pass binds its tile memory.
|
||||
RuntimeFact::TileThreadgroupMemory { .. } => Mechanism::Specialization,
|
||||
// The binder checks the object function's arena with the encoder's lengths, which it
|
||||
@@ -166,8 +135,6 @@ pub fn mechanism(fact: &RuntimeFact, profile: &DeviceProfile) -> Mechanism {
|
||||
RuntimeFact::StencilBitDraws => Mechanism::PushConstant,
|
||||
// The pipeline's robustness, which the consumer states as it makes it.
|
||||
RuntimeFact::RobustStorageBuffers => Mechanism::PipelineState,
|
||||
// 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.
|
||||
RuntimeFact::AddressAlignment { .. } => Mechanism::PlanTimeCheck,
|
||||
// A separate compile of the pipeline, which a pass with colors the pipeline lacks asks
|
||||
@@ -180,8 +147,6 @@ pub fn mechanism(fact: &RuntimeFact, profile: &DeviceProfile) -> Mechanism {
|
||||
// A separate link of the mesh pipeline's synthesized vertex stage.
|
||||
// The binder's region flags a draw whose last object threadgroup along an axis is partial.
|
||||
RuntimeFact::PartialObjectThreadgroups => Mechanism::RegionSelected,
|
||||
// The binder specializes the lanes from the bound texture's pixel format and swizzle.
|
||||
RuntimeFact::ConstantLanes { .. } => Mechanism::Specialization,
|
||||
// A separate compile that reads the tables' words through their device addresses, which
|
||||
// a shape whose tables may pass `maxStorageBufferRange` asks for; without device
|
||||
// addresses the binder refuses such a table where it binds it.
|
||||
@@ -192,29 +157,5 @@ pub fn mechanism(fact: &RuntimeFact, profile: &DeviceProfile) -> Mechanism {
|
||||
// The binder's regions carry the tile as Metal's threadgroup; the tile pipeline checks its
|
||||
// descriptor's flag.
|
||||
RuntimeFact::TileThreadgroup { .. } => Mechanism::RegionSelected,
|
||||
// Keyed by the slots a constexpr sampler samples whose bound texture's address-mode map
|
||||
// is not the identity.
|
||||
RuntimeFact::ConstexprSampled { .. } => Mechanism::Variant,
|
||||
// Keyed by the slots bound to a cubic sampler, with its state.
|
||||
RuntimeFact::CubicSampler { .. } => Mechanism::Variant,
|
||||
// The planner admits a listed cubic sampler beside the stage's sampler table; the
|
||||
// function marks the `ExecutionStatus` buffer where it reaches one.
|
||||
RuntimeFact::CubicArgumentSampler { .. } => Mechanism::PlanTimeCheck,
|
||||
// The planner refuses a texture a heap holds by its raw texels alone that a plan names
|
||||
// beside the stage; a consumer's own heap announces one.
|
||||
RuntimeFact::HeapRawSamples { .. } => Mechanism::PlanTimeCheck,
|
||||
// Keyed by the slots bound in a format of another numeric class than the declared one,
|
||||
// whose texels the function reads in that class.
|
||||
RuntimeFact::CrossClassReads { .. } => Mechanism::Variant,
|
||||
// The planner reports a member of another numeric class the stage reaches in the class.
|
||||
RuntimeFact::HeapCrossClassNeutral { .. } => Mechanism::PlanTimeCheck,
|
||||
// The planner refuses a sparse texture the stage's handle tables reach.
|
||||
RuntimeFact::HeapResidency { .. } => Mechanism::PlanTimeCheck,
|
||||
// The planner refuses a texture of a dropped or shadowed write the stage reaches in a
|
||||
// storage class it reads.
|
||||
RuntimeFact::HeapStorageReads { .. } => Mechanism::PlanTimeCheck,
|
||||
// Keyed by the slots bound to a sampler whose word states anisotropy, where the
|
||||
// function's samples take Metal's anisotropic filter, emulated.
|
||||
RuntimeFact::AnisotropicSampler { .. } => Mechanism::Variant,
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
//! The device a pipeline is compiled for: what the consumer enabled, and its policy.
|
||||
//! The device a pipeline is compiled for: what the consumer enabled.
|
||||
//!
|
||||
//! A [`DeviceDescription`] states one Vulkan physical device as the consumer creates it: its API
|
||||
//! version, the features and extensions it enables, its limits, subgroup and float-controls
|
||||
@@ -12,18 +12,18 @@
|
||||
//! what is enabled. Translation uses only what the description enables.
|
||||
//!
|
||||
//! [`Device::from_queries`] derives an opaque [`DeviceProfile`] from the description's Vulkan
|
||||
//! queries and a [`DevicePolicy`], the consumer's product choices (the pointer and handle
|
||||
//! domains; the default is the runtime's, the identity domains); no
|
||||
//! driver or GPU identity decides anything, and no `VkDevice` is needed. It refuses a device below Vulkan
|
||||
//! 1.2 and an inconsistent description or policy. A [`Device`] is cheap to clone, and every
|
||||
//! compile and plan takes one:
|
||||
//! queries; no driver or GPU identity decides anything, and no `VkDevice` is needed. A pointer is
|
||||
//! the device address it holds and a texture's or sampler's handle is its `gpuResourceID` (the
|
||||
//! identity domains), so it refuses a device without `bufferDeviceAddress` and `shaderInt64`,
|
||||
//! as it refuses a device below Vulkan 1.2 and an inconsistent description. A [`Device`] is cheap
|
||||
//! to clone, and every compile and plan takes one:
|
||||
//!
|
||||
//! - [`Device::compile_function`], [`Device::compile_compute_pipeline`],
|
||||
//! [`Device::compile_render_pipeline`], and their keys (see [`pipeline`](crate::pipeline));
|
||||
//! - [`Device::required_enables`]: everything an artifact compiled for the device can need
|
||||
//! enabled;
|
||||
//! - [`Device::metal_properties`]: the Metal device properties to report to the guest;
|
||||
//! - [`DeviceProfile::fingerprint`]: a hash over every profile field, policy included, which
|
||||
//! - [`DeviceProfile::fingerprint`]: a hash over every profile field, which
|
||||
//! every cache key includes, so an artifact never serves another device.
|
||||
//!
|
||||
//! A consumer that creates its own `VkDevice` sets each feature of an [`EnableSet`] in the
|
||||
@@ -47,7 +47,6 @@ pub(crate) mod function_storage;
|
||||
pub(crate) mod khronos;
|
||||
pub(crate) mod mechanism;
|
||||
pub(crate) mod metal;
|
||||
pub(crate) mod policy;
|
||||
pub(crate) mod profile;
|
||||
pub(crate) mod requirements;
|
||||
pub(crate) mod subgroup;
|
||||
@@ -61,14 +60,13 @@ pub use enables::{EnableSet, Exposure};
|
||||
// The mechanism derivation: internal; a pipeline states each mechanism in its `dependencies`.
|
||||
pub(crate) use mechanism::mechanism;
|
||||
pub use metal::{MetalDeviceProperties, SimdSupport, StageSimd};
|
||||
pub use policy::DevicePolicy;
|
||||
pub(crate) use profile::whole_point_size;
|
||||
pub use profile::{DeviceProfile, SpirvValidation, IDENTITY_BUFFER_BYTES, KERNEL_BUFFER_BINDINGS};
|
||||
// The vocabulary the device surface reaches: description and policy inputs, and the requirement
|
||||
// The vocabulary the device surface reaches: description inputs, and the requirement
|
||||
// vocabulary of `Requirements`, `Capability`, and `DeviceDescription`.
|
||||
pub use profile::{
|
||||
EnabledCaps, FloatControls, FloatWidthControls, FragmentCaps, HandleDomain, ImageCaps,
|
||||
Independence, Limits, MeshLimits, PointerDomain,
|
||||
EnabledCaps, FloatControls, FloatWidthControls, FragmentCaps, ImageCaps, Independence, Limits,
|
||||
MeshLimits,
|
||||
};
|
||||
// The profile's facts a consumer or a validation tool reads: its descriptor capabilities, its
|
||||
// subgroup model and simdgroup tiers, and the Function storage a thread holds.
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
//! `DevicePolicy`: the consumer's product choices that, together with a `DeviceDescription`,
|
||||
//! decide a `DeviceProfile`.
|
||||
|
||||
use crate::device::profile::{HandleDomain, PointerDomain};
|
||||
|
||||
/// Policy inputs of `Device::from_queries`. Every field can change emitted code, so the profile
|
||||
/// carries it and its fingerprint covers it.
|
||||
///
|
||||
/// [`DevicePolicy::default`] is the one constructor: the runtime compiles under it, and the
|
||||
/// command line, the compile worker, the validation executor and every validation tool take
|
||||
/// their policy from it, so a tool compiles what the runtime does. Nothing in the tree builds
|
||||
/// [`DevicePolicy::RESIDENT_TABLES`] outside tests.
|
||||
#[non_exhaustive]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct DevicePolicy {
|
||||
/// How pointer values resolve to resources: `Identity` with `handle_domain` `Identity` (the
|
||||
/// default), or `ResidentTable` with `Table` (`RESIDENT_TABLES`, which only tests build).
|
||||
pub pointer_domain: PointerDomain,
|
||||
/// How resource handles resolve: `Identity` with `pointer_domain` `Identity` (the default), or
|
||||
/// `Table` with `ResidentTable` (`RESIDENT_TABLES`, which only tests build).
|
||||
pub handle_domain: HandleDomain,
|
||||
}
|
||||
|
||||
impl DevicePolicy {
|
||||
/// A resident table of pointers and a handle table. Nothing in the tree builds it outside
|
||||
/// tests: the runtime, the tools and the validation executor take the default.
|
||||
pub const RESIDENT_TABLES: DevicePolicy = DevicePolicy {
|
||||
pointer_domain: PointerDomain::ResidentTable,
|
||||
handle_domain: HandleDomain::Table,
|
||||
};
|
||||
}
|
||||
|
||||
impl Default for DevicePolicy {
|
||||
/// The identity domains, the runtime's: a pointer is the device address it holds and a
|
||||
/// texture's or sampler's handle is its `gpuResourceID` ([`PointerDomain::Identity`],
|
||||
/// [`HandleDomain::Identity`]). `Device::from_queries` refuses them on a device without
|
||||
/// `bufferDeviceAddress` and `shaderInt64` (`Feature::IdentityDomains`).
|
||||
fn default() -> DevicePolicy {
|
||||
DevicePolicy {
|
||||
pointer_domain: PointerDomain::Identity,
|
||||
handle_domain: HandleDomain::Identity,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
//! `DeviceProfile` and its translation-relevant fields.
|
||||
//!
|
||||
//! `Device::from_queries(desc, policy)` is the only producer of a [`DeviceProfile`]. The profile is the
|
||||
//! normalized projection of a device description plus the policy; lowering selects representations
|
||||
//! from it and nothing else. Derivation lives in `device::derive`, the fingerprint in
|
||||
//! `Device::from_queries(desc)` is the only producer of a [`DeviceProfile`]. The profile is the
|
||||
//! normalized projection of a device description; lowering selects representations from it and
|
||||
//! nothing else. Derivation lives in `device::derive`, the fingerprint in
|
||||
//! [`DeviceProfile::fingerprint`].
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
@@ -144,8 +144,7 @@ impl DeviceProfile {
|
||||
l.max_descriptor_set_update_after_bind_storage_buffers,
|
||||
l.max_per_stage_resources,
|
||||
];
|
||||
f.pointer_domain == PointerDomain::Identity
|
||||
&& f.enabled.features.contains(&VkFeature::PipelineRobustness)
|
||||
f.enabled.features.contains(&VkFeature::PipelineRobustness)
|
||||
&& l.robust_buffer_access2
|
||||
&& l.robust_buffer_access_update_after_bind
|
||||
&& buffers.iter().all(|&limit| limit >= KERNEL_BUFFER_BINDINGS)
|
||||
@@ -315,7 +314,7 @@ impl DeviceProfile {
|
||||
}
|
||||
}
|
||||
|
||||
/// A SHA-256 over **every** field, policy included.
|
||||
/// A SHA-256 over **every** field.
|
||||
///
|
||||
/// The encoding is the derived `Debug` rendering of the profile's fields under a versioned
|
||||
/// domain tag: it is total by construction (a new field is hashed without further code) and
|
||||
@@ -383,13 +382,11 @@ pub const KERNEL_BUFFER_BINDINGS: u32 = 31;
|
||||
/// whose accesses add 32-bit offsets read as signed to its address (`docs/API.md` section 1).
|
||||
pub const IDENTITY_BUFFER_BYTES: u64 = 1 << 31;
|
||||
|
||||
/// Every field of a profile, policy included. The fingerprint hashes all of them.
|
||||
/// Every field of a profile. The fingerprint hashes all of them.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ProfileFields {
|
||||
/// Memory's A/F split.
|
||||
pub buffer_access: BufferAccess,
|
||||
pub pointer_domain: PointerDomain,
|
||||
pub handle_domain: HandleDomain,
|
||||
pub leaf: LeafCaps,
|
||||
pub subgroup: SubgroupModel,
|
||||
pub images: ImageCaps,
|
||||
@@ -483,45 +480,6 @@ pub enum BufferAccess {
|
||||
Floor,
|
||||
}
|
||||
|
||||
/// How pointer values are resolved to resources. A device takes `Identity` only with
|
||||
/// [`HandleDomain::Identity`], and the other two together.
|
||||
#[non_exhaustive]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub enum PointerDomain {
|
||||
/// The sorted resident set of bound arguments and used resources. Nothing in the tree
|
||||
/// builds it outside tests
|
||||
/// ([`DevicePolicy::RESIDENT_TABLES`](crate::device::DevicePolicy::RESIDENT_TABLES)): the
|
||||
/// runtime, the tools and the validation executor take `Identity`.
|
||||
ResidentTable,
|
||||
/// Pointers are device addresses used directly: a `device` or `constant` pointer is the
|
||||
/// 64-bit Vulkan device address of the byte it names, as Metal's `gpuAddress` is, and a
|
||||
/// buffer slot is reached at its own address, pushed, and a pointer loaded from
|
||||
/// memory or made from an integer is the address it holds, used directly. Needs
|
||||
/// `bufferDeviceAddress` and `shaderInt64`. So far it lowers a kernel that reaches memory
|
||||
/// only through its buffer slots and such addresses, and, on `Device::from_queries`' profile,
|
||||
/// a vertex or fragment function that does; any other function is refused as
|
||||
/// [`Feature::IdentityDomains`](crate::error::Feature::IdentityDomains).
|
||||
Identity,
|
||||
}
|
||||
|
||||
/// How resource handles are resolved. A device takes `Identity` only with
|
||||
/// [`PointerDomain::Identity`], and the other two together.
|
||||
#[non_exhaustive]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub enum HandleDomain {
|
||||
/// The handle table plus the set-1 heap. Nothing in the tree builds it outside tests
|
||||
/// ([`DevicePolicy::RESIDENT_TABLES`](crate::device::DevicePolicy::RESIDENT_TABLES)): the
|
||||
/// runtime, the tools and the validation executor take `Identity`.
|
||||
Table,
|
||||
/// A texture's or sampler's handle is its `gpuResourceID`: the low 32 bits index the
|
||||
/// pipeline's descriptor arrays and the high 32 bits are the word of its Metal descriptor
|
||||
/// (`docs/RESOURCE-ID.md`). A texture or sampler use with no form under it is refused as
|
||||
/// [`Feature::IdentityDomains`](crate::error::Feature::IdentityDomains).
|
||||
Identity,
|
||||
}
|
||||
|
||||
/// Leaf arithmetic, storage, and atomic capabilities.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
pub struct LeafCaps {
|
||||
@@ -679,14 +637,12 @@ pub struct Limits {
|
||||
pub max_per_stage_descriptor_storage_buffers: u32,
|
||||
pub max_per_stage_descriptor_sampled_images: u32,
|
||||
pub max_per_stage_descriptor_storage_images: u32,
|
||||
pub max_per_stage_descriptor_input_attachments: u32,
|
||||
pub max_per_stage_resources: u32,
|
||||
pub max_descriptor_set_samplers: u32,
|
||||
pub max_descriptor_set_uniform_buffers: u32,
|
||||
pub max_descriptor_set_storage_buffers: u32,
|
||||
pub max_descriptor_set_sampled_images: u32,
|
||||
pub max_descriptor_set_storage_images: u32,
|
||||
pub max_descriptor_set_input_attachments: u32,
|
||||
pub max_descriptor_set_update_after_bind_samplers: u32,
|
||||
pub max_descriptor_set_update_after_bind_sampled_images: u32,
|
||||
pub max_descriptor_set_update_after_bind_storage_images: u32,
|
||||
|
||||
@@ -686,14 +686,12 @@ pub enum VkLimit {
|
||||
MaxPerStageDescriptorStorageBuffers,
|
||||
MaxPerStageDescriptorSampledImages,
|
||||
MaxPerStageDescriptorStorageImages,
|
||||
MaxPerStageDescriptorInputAttachments,
|
||||
MaxPerStageResources,
|
||||
MaxDescriptorSetSamplers,
|
||||
MaxDescriptorSetUniformBuffers,
|
||||
MaxDescriptorSetStorageBuffers,
|
||||
MaxDescriptorSetSampledImages,
|
||||
MaxDescriptorSetStorageImages,
|
||||
MaxDescriptorSetInputAttachments,
|
||||
MaxDescriptorSetUpdateAfterBindSamplers,
|
||||
MaxDescriptorSetUpdateAfterBindSampledImages,
|
||||
MaxDescriptorSetUpdateAfterBindStorageImages,
|
||||
|
||||
@@ -184,7 +184,7 @@ fn divisor_first_instance_support_follows_exposure() {
|
||||
}
|
||||
|
||||
/// `rgba4OpaqueBlackSwizzled` is read where `VK_KHR_maintenance10` is exposed and is an enabled
|
||||
/// property when true; MoltenVK's capture has no maintenance10, so it is false there.
|
||||
/// property when true (lavapipe's); MoltenVK's capture has no maintenance10, so it is false there.
|
||||
#[test]
|
||||
fn rgba4_opaque_black_swizzled_follows_exposure() {
|
||||
use crate::device::requirements::VkProperty;
|
||||
@@ -199,8 +199,7 @@ fn rgba4_opaque_black_swizzled_follows_exposure() {
|
||||
);
|
||||
let d = DeviceDescription::from_khronos_json(&with, None).unwrap();
|
||||
assert!(d.rgba4_opaque_black_swizzled);
|
||||
let dev = crate::device::Device::from_queries(d, crate::device::DevicePolicy::RESIDENT_TABLES)
|
||||
.unwrap();
|
||||
let dev = crate::device::Device::from_queries(profile("lavapipe")).unwrap();
|
||||
assert!(dev
|
||||
.profile()
|
||||
.fields()
|
||||
@@ -743,45 +742,35 @@ fn required_features_are_cumulative() {
|
||||
assert!(v13.contains(&VkFeature::SubgroupSizeControl));
|
||||
}
|
||||
|
||||
/// With feature `serde`, every committed description and both policies survive a JSON round trip
|
||||
/// unchanged, and the `Device` rebuilt from the decoded pair has the original's profile
|
||||
/// fingerprint, or, where the description cannot take the policy (the identity domains without
|
||||
/// `bufferDeviceAddress` and `shaderInt64`), the same refusal: what an out-of-process compile
|
||||
/// worker needs to compile for the consumer's device (worker recipe step 1).
|
||||
/// With feature `serde`, every committed description survives a JSON round trip unchanged, and the
|
||||
/// `Device` rebuilt from the decoded description has the original's profile fingerprint, or, where
|
||||
/// the description cannot take the identity domains (without `bufferDeviceAddress` and
|
||||
/// `shaderInt64`), the same refusal: what an out-of-process compile worker needs to compile for the
|
||||
/// consumer's device (worker recipe step 1).
|
||||
#[cfg(feature = "serde")]
|
||||
#[test]
|
||||
fn descriptions_and_policies_round_trip_through_serde() {
|
||||
let identity = DevicePolicy {
|
||||
pointer_domain: crate::device::PointerDomain::Identity,
|
||||
handle_domain: crate::device::HandleDomain::Identity,
|
||||
};
|
||||
let policies = [DevicePolicy::RESIDENT_TABLES, identity];
|
||||
fn descriptions_round_trip_through_serde() {
|
||||
for (stem, text) in committed_profiles() {
|
||||
let description = DeviceDescription::from_khronos_json(&text, None).unwrap();
|
||||
let json = serde_json::to_string(&description).unwrap();
|
||||
let decoded: DeviceDescription = serde_json::from_str(&json).unwrap();
|
||||
assert_eq!(decoded, description, "{stem}");
|
||||
for policy in policies {
|
||||
let policy_json = serde_json::to_string(&policy).unwrap();
|
||||
let decoded_policy: DevicePolicy = serde_json::from_str(&policy_json).unwrap();
|
||||
assert_eq!(decoded_policy, policy, "{stem}");
|
||||
let original = Device::from_queries(description.clone(), policy);
|
||||
let rebuilt = Device::from_queries(decoded.clone(), decoded_policy);
|
||||
match (original, rebuilt) {
|
||||
(Ok(original), Ok(rebuilt)) => assert_eq!(
|
||||
rebuilt.profile().fingerprint(),
|
||||
original.profile().fingerprint(),
|
||||
"{stem}"
|
||||
),
|
||||
(Err(original), Err(rebuilt)) => {
|
||||
assert_eq!(rebuilt.to_string(), original.to_string(), "{stem}")
|
||||
}
|
||||
(original, rebuilt) => panic!(
|
||||
"{stem}: the original derives {}, the decoded pair {}",
|
||||
original.is_ok(),
|
||||
rebuilt.is_ok()
|
||||
),
|
||||
let original = Device::from_queries(description.clone());
|
||||
let rebuilt = Device::from_queries(decoded.clone());
|
||||
match (original, rebuilt) {
|
||||
(Ok(original), Ok(rebuilt)) => assert_eq!(
|
||||
rebuilt.profile().fingerprint(),
|
||||
original.profile().fingerprint(),
|
||||
"{stem}"
|
||||
),
|
||||
(Err(original), Err(rebuilt)) => {
|
||||
assert_eq!(rebuilt.to_string(), original.to_string(), "{stem}")
|
||||
}
|
||||
(original, rebuilt) => panic!(
|
||||
"{stem}: the original derives {}, the decoded description {}",
|
||||
original.is_ok(),
|
||||
rebuilt.is_ok()
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -97,10 +97,9 @@ fn recommendations_are_closed_fixed_points_on_every_committed_profile() {
|
||||
.clone()
|
||||
.with_enabled(&rec)
|
||||
.unwrap_or_else(|e| panic!("{stem}: {e}"));
|
||||
let dev = Device::from_queries(restricted, DevicePolicy::RESIDENT_TABLES)
|
||||
.unwrap_or_else(|e| panic!("{stem}: {e}"));
|
||||
let dev = Device::from_queries(restricted).unwrap_or_else(|e| panic!("{stem}: {e}"));
|
||||
assert_eq!(dev.required_enables(), rec, "{stem}");
|
||||
let full = Device::from_queries(desc.clone(), DevicePolicy::RESIDENT_TABLES).unwrap();
|
||||
let full = Device::from_queries(desc.clone()).unwrap();
|
||||
assert_eq!(full.required_enables(), rec, "{stem}");
|
||||
assert_eq!(
|
||||
rec.extensions.contains(&VkExtension::KhrPortabilitySubset),
|
||||
@@ -191,11 +190,7 @@ fn extended_dynamic_state2_is_enabled_below_1_3_and_implied_from_it() {
|
||||
assert!(rec.extensions.contains(&extension), "{extension:?}");
|
||||
assert!(rec.features.contains(&feature), "{feature:?}");
|
||||
}
|
||||
let dev = Device::from_queries(
|
||||
d.clone().with_enabled(&rec).unwrap(),
|
||||
DevicePolicy::RESIDENT_TABLES,
|
||||
)
|
||||
.unwrap();
|
||||
let dev = Device::from_queries(d.clone().with_enabled(&rec).unwrap()).unwrap();
|
||||
let enabled = &dev.profile().fields().enabled;
|
||||
assert!(enabled.features.contains(&VkFeature::ExtendedDynamicState2));
|
||||
assert!(enabled
|
||||
@@ -328,13 +323,13 @@ fn device_new_refuses_a_feature_without_its_companion() {
|
||||
}
|
||||
let mut d = floor_with(&[], &[f]);
|
||||
d.features.remove(&needs);
|
||||
let e = match Device::from_queries(d.clone(), DevicePolicy::RESIDENT_TABLES) {
|
||||
let e = match Device::from_queries(d.clone()) {
|
||||
Err(Error::InvalidDescriptor(DescriptorError::DeviceDescription { detail })) => detail,
|
||||
other => panic!("{other:?}"),
|
||||
};
|
||||
assert!(e.contains(vuid), "{e}");
|
||||
d.features.insert(needs);
|
||||
Device::from_queries(d, DevicePolicy::RESIDENT_TABLES).unwrap();
|
||||
Device::from_queries(d).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -359,7 +354,7 @@ fn device_new_refuses_quad_control_without_maximal_reconvergence() {
|
||||
],
|
||||
&[VkFeature::ShaderQuadControl],
|
||||
);
|
||||
let e = match Device::from_queries(d.clone(), DevicePolicy::RESIDENT_TABLES) {
|
||||
let e = match Device::from_queries(d.clone()) {
|
||||
Err(Error::InvalidDescriptor(DescriptorError::DeviceDescription { detail })) => detail,
|
||||
other => panic!("{other:?}"),
|
||||
};
|
||||
@@ -368,7 +363,7 @@ fn device_new_refuses_quad_control_without_maximal_reconvergence() {
|
||||
"{e}"
|
||||
);
|
||||
d.features.insert(VkFeature::ShaderMaximalReconvergence);
|
||||
let device = Device::from_queries(d, DevicePolicy::RESIDENT_TABLES).unwrap();
|
||||
let device = Device::from_queries(d).unwrap();
|
||||
let model = &device.profile().fields().subgroup;
|
||||
assert!(model.quad_control && model.maximal_reconvergence);
|
||||
}
|
||||
@@ -597,7 +592,7 @@ fn required_enables_follow_version_dependencies_formats_and_flags() {
|
||||
fn device_new_refuses_unexposed_features() {
|
||||
let mut d = profile("runtime-floor");
|
||||
d.features.insert(VkFeature::Maintenance8);
|
||||
let e = match Device::from_queries(d.clone(), DevicePolicy::RESIDENT_TABLES) {
|
||||
let e = match Device::from_queries(d.clone()) {
|
||||
Err(Error::InvalidDescriptor(DescriptorError::DeviceDescription { detail })) => detail,
|
||||
other => panic!("{other:?}"),
|
||||
};
|
||||
@@ -606,7 +601,7 @@ fn device_new_refuses_unexposed_features() {
|
||||
"{e}"
|
||||
);
|
||||
d.extensions.insert(VkExtension::KhrMaintenance8);
|
||||
Device::from_queries(d, DevicePolicy::RESIDENT_TABLES).unwrap();
|
||||
Device::from_queries(d).unwrap();
|
||||
}
|
||||
|
||||
/// The profile's format tables hold only formats the description exposes: a queried description
|
||||
@@ -647,7 +642,7 @@ fn profile_format_tables_hold_only_exposed_formats() {
|
||||
let entry = d.formats.formats[&vk::Format::R8_UNORM];
|
||||
d.formats.formats.insert(vk::Format::A8_UNORM, entry);
|
||||
let a8 = |d: &DeviceDescription| {
|
||||
Device::from_queries(d.clone(), DevicePolicy::RESIDENT_TABLES)
|
||||
Device::from_queries(d.clone())
|
||||
.unwrap()
|
||||
.profile()
|
||||
.supports_format(vk::Format::A8_UNORM, FormatUsage::SampledImage)
|
||||
@@ -676,13 +671,12 @@ fn a_storage_read_without_a_format_is_enabled_by_the_feature_the_version_or_the_
|
||||
reads.spirv_capabilities.insert(SpirvCapability::of(
|
||||
crate::spv::Capability::StorageImageReadWithoutFormat,
|
||||
));
|
||||
let policy = DevicePolicy::RESIDENT_TABLES;
|
||||
let open = |desc: &DeviceDescription| {
|
||||
let enabled = desc.recommended_enables();
|
||||
let opened = desc.clone().with_enabled(&enabled).unwrap();
|
||||
(
|
||||
enabled,
|
||||
Device::from_queries(opened.clone(), policy).unwrap(),
|
||||
Device::from_queries(opened.clone()).unwrap(),
|
||||
opened,
|
||||
)
|
||||
};
|
||||
|
||||
@@ -82,7 +82,7 @@ fn from_queries_derives_one_profile_whatever_the_identity() {
|
||||
other.device_type = Some(id.kind);
|
||||
other.device_name = id.name.to_owned();
|
||||
other.driver_version = id.version;
|
||||
Device::from_queries(other, DevicePolicy::RESIDENT_TABLES)
|
||||
Device::from_queries(other)
|
||||
.ok()
|
||||
.map(|d| d.profile().clone())
|
||||
})
|
||||
@@ -165,26 +165,22 @@ entry:
|
||||
"#;
|
||||
|
||||
/// The push window is the device's `maxPushConstantsSize` up to 256 bytes
|
||||
/// (`DeviceProfile::push_window`), and at least 128, Vulkan's least: the Vulkan 1.2 minimum
|
||||
/// (`validation/profiles/below-floor/vk12-floor`, this test's input alone) derives at its 128,
|
||||
/// with a window of 128, and the same description at 64, which no Vulkan device reports, is
|
||||
/// refused: `Unsupported{PushWindow}`, needing `MaxPushConstantsSize` 128. Every committed
|
||||
/// profile derives, its window its limit up to 256: `runtime-floor` at Vulkan 1.3's least, 128,
|
||||
/// and every profile of a device at 256 (`moltenvk-m3`'s 4,096 included).
|
||||
/// (`DeviceProfile::push_window`), and at least 128, Vulkan's least: `runtime-floor`, at Vulkan
|
||||
/// 1.3's least, 128, derives with a window of 128, and the same description at 64, which no Vulkan
|
||||
/// device reports, is refused: `Unsupported{PushWindow}`, needing `MaxPushConstantsSize` 128.
|
||||
/// Every committed profile derives, its window its limit up to 256: every profile of a device at
|
||||
/// 256 (`moltenvk-m3`'s 4,096 included).
|
||||
#[test]
|
||||
fn the_push_window_is_the_device_s_limit_up_to_256_bytes() {
|
||||
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../metal2vulkan-validation/profiles/below-floor/vk12-floor.json");
|
||||
let text = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
|
||||
let least = DeviceDescription::from_khronos_json(&text, None).expect("parses");
|
||||
let least = profile("runtime-floor");
|
||||
assert_eq!(least.limits.max_push_constants_size, 128);
|
||||
let mut below = least.clone();
|
||||
below.limits.max_push_constants_size = 64;
|
||||
match Device::from_queries(least, DevicePolicy::RESIDENT_TABLES) {
|
||||
match Device::from_queries(least) {
|
||||
Ok(device) => assert_eq!(device.profile().push_window(), 128),
|
||||
Err(e) => panic!("vk12-floor: {e}"),
|
||||
Err(e) => panic!("runtime-floor: {e}"),
|
||||
}
|
||||
match Device::from_queries(below, DevicePolicy::RESIDENT_TABLES) {
|
||||
match Device::from_queries(below) {
|
||||
Err(Error::Unsupported(u)) => {
|
||||
assert_eq!(u.feature, Feature::PushWindow);
|
||||
let limit = Capability::Limit {
|
||||
@@ -199,7 +195,7 @@ fn the_push_window_is_the_device_s_limit_up_to_256_bytes() {
|
||||
for (stem, _) in committed_profiles() {
|
||||
let description = profile(&stem);
|
||||
let limit = description.limits.max_push_constants_size;
|
||||
let device = Device::from_queries(description, DevicePolicy::RESIDENT_TABLES)
|
||||
let device = Device::from_queries(description)
|
||||
.unwrap_or_else(|e| panic!("{stem} is committed but refused: {e}"));
|
||||
let window = device.profile().push_window();
|
||||
assert_eq!(window, limit.min(256), "{stem}");
|
||||
@@ -228,7 +224,7 @@ fn from_queries_records_the_device_denormals_of_a_float_product() {
|
||||
};
|
||||
let mut compiled = 0;
|
||||
for (stem, _) in committed_profiles() {
|
||||
let Ok(device) = Device::from_queries(profile(&stem), DevicePolicy::RESIDENT_TABLES) else {
|
||||
let Ok(device) = Device::from_queries(profile(&stem)) else {
|
||||
continue;
|
||||
};
|
||||
let a = compile(&bc, "mixed_products", device.profile())
|
||||
@@ -288,7 +284,7 @@ fn from_queries_clears_a_narrow_value_by_an_and_on_ga10x() {
|
||||
.count();
|
||||
(ands, extracts)
|
||||
};
|
||||
let queried = Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).unwrap();
|
||||
let queried = Device::from_queries(desc).unwrap();
|
||||
let (ands, extracts) = counts(queried.profile());
|
||||
assert!(ands > 0, "from_queries: no AND");
|
||||
assert_eq!(extracts, 0, "from_queries: an extract");
|
||||
|
||||
@@ -3,10 +3,7 @@
|
||||
use super::profile::device;
|
||||
use crate::device::mechanism::mechanism;
|
||||
use crate::pipeline::facts::{Mechanism, RuntimeFact};
|
||||
use crate::pipeline::sym::{
|
||||
ImageAccess, ImageDim, ImageHandleClass, SampledType, SlotClass, SlotRef, Stage,
|
||||
StorageFormatClass,
|
||||
};
|
||||
use crate::pipeline::sym::{SlotClass, SlotRef, Stage};
|
||||
|
||||
/// One value of every `RuntimeFact` variant.
|
||||
fn every_fact() -> Vec<RuntimeFact> {
|
||||
@@ -24,29 +21,12 @@ fn every_fact() -> Vec<RuntimeFact> {
|
||||
RuntimeFact::IndirectGroupCount,
|
||||
RuntimeFact::ResourcePresence { slot },
|
||||
RuntimeFact::SampleCount,
|
||||
RuntimeFact::StorageTextureFormat { slot },
|
||||
RuntimeFact::SamplerCoordinates { slot },
|
||||
RuntimeFact::SamplerReduction { slot },
|
||||
RuntimeFact::ImageViewShape { slot },
|
||||
RuntimeFact::VertexFetch { attr: 1 },
|
||||
RuntimeFact::VertexBufferStride { layout: 0 },
|
||||
RuntimeFact::BaseVertexInstance,
|
||||
RuntimeFact::DeviceAddresses { slot },
|
||||
RuntimeFact::BufferRangeLimit { slot },
|
||||
RuntimeFact::TexelBufferRange { slot },
|
||||
RuntimeFact::FramebufferFetch { color: 0 },
|
||||
RuntimeFact::ExecutionStatus,
|
||||
RuntimeFact::HeapNumericType {
|
||||
class: ImageHandleClass {
|
||||
dim: ImageDim::D2,
|
||||
arrayed: false,
|
||||
multisampled: false,
|
||||
sampled_type: SampledType::Float,
|
||||
depth_compare: false,
|
||||
access: ImageAccess::Sampled,
|
||||
format: StorageFormatClass::NotStorage,
|
||||
},
|
||||
},
|
||||
RuntimeFact::SimdgroupEmulation {
|
||||
bytes_per_simdgroup: 128,
|
||||
arena: None,
|
||||
@@ -69,7 +49,6 @@ fn every_fact() -> Vec<RuntimeFact> {
|
||||
},
|
||||
RuntimeFact::StorageTextureNumericType { slot },
|
||||
RuntimeFact::OutOfBoundsAlpha { slot },
|
||||
RuntimeFact::BicubicTexels { slot },
|
||||
RuntimeFact::BorderTexels { slot },
|
||||
RuntimeFact::StorageTextureLevels { slot },
|
||||
RuntimeFact::StorageTextureLevelViews { slot },
|
||||
@@ -90,22 +69,15 @@ fn every_fact() -> Vec<RuntimeFact> {
|
||||
},
|
||||
RuntimeFact::AccelerationStructureInstanceCount { slot },
|
||||
RuntimeFact::PredicationVote,
|
||||
RuntimeFact::SrgbTexture { slot },
|
||||
RuntimeFact::ViewportCount,
|
||||
RuntimeFact::AliasedImageblock { data_size: 24 },
|
||||
RuntimeFact::CallStackDepth { depth: 8 },
|
||||
RuntimeFact::OpenClMode,
|
||||
RuntimeFact::OpenClLineTexture { slot },
|
||||
RuntimeFact::RowLockstep,
|
||||
RuntimeFact::TexelBufferParts { slot },
|
||||
RuntimeFact::AddressAlignment { slot, align: 16 },
|
||||
RuntimeFact::FlatGrid,
|
||||
RuntimeFact::CallThreadgroups,
|
||||
RuntimeFact::SparseTextureWrites {
|
||||
slot,
|
||||
atomic: false,
|
||||
},
|
||||
RuntimeFact::SparseTextureWrites { slot, atomic: true },
|
||||
RuntimeFact::TileThreadgroupMemory { index: 1 },
|
||||
RuntimeFact::TextureSwizzle { slot },
|
||||
RuntimeFact::TileImageblock {
|
||||
@@ -132,58 +104,8 @@ fn every_fact() -> Vec<RuntimeFact> {
|
||||
},
|
||||
RuntimeFact::DroppedColor { color: 1 },
|
||||
RuntimeFact::DepthClampRange,
|
||||
RuntimeFact::ConstantLanes { slot },
|
||||
RuntimeFact::FunctionTableRange { addressed: false },
|
||||
RuntimeFact::TileThreadgroup { tile_sized: true },
|
||||
RuntimeFact::ConstexprSampled {
|
||||
slot,
|
||||
modes: [crate::metal::SamplerAddressMode::Repeat; 3],
|
||||
},
|
||||
RuntimeFact::CubicSampler { slot },
|
||||
RuntimeFact::CubicArgumentSampler {
|
||||
stage: Stage::Kernel,
|
||||
},
|
||||
RuntimeFact::StorageTextureIntegerChannels { slot },
|
||||
RuntimeFact::HeapRawSamples {
|
||||
stage: Stage::Fragment,
|
||||
sampler: Some(1),
|
||||
},
|
||||
RuntimeFact::CrossClassReads { slot },
|
||||
RuntimeFact::HeapCrossClassNeutral {
|
||||
stage: Stage::Kernel,
|
||||
class: crate::pipeline::sym::ImageHandleClass {
|
||||
dim: crate::pipeline::sym::ImageDim::D2,
|
||||
arrayed: false,
|
||||
multisampled: false,
|
||||
sampled_type: crate::pipeline::sym::SampledType::Float,
|
||||
depth_compare: false,
|
||||
access: crate::pipeline::sym::ImageAccess::Sampled,
|
||||
format: crate::pipeline::sym::StorageFormatClass::NotStorage,
|
||||
},
|
||||
every_member: true,
|
||||
},
|
||||
RuntimeFact::HeapResidency {
|
||||
stage: Stage::Fragment,
|
||||
},
|
||||
RuntimeFact::HeapStorageReads {
|
||||
stage: Stage::Kernel,
|
||||
class: crate::pipeline::sym::ImageHandleClass {
|
||||
dim: crate::pipeline::sym::ImageDim::D2,
|
||||
arrayed: false,
|
||||
multisampled: false,
|
||||
sampled_type: crate::pipeline::sym::SampledType::Float,
|
||||
depth_compare: false,
|
||||
access: crate::pipeline::sym::ImageAccess::Storage,
|
||||
format: crate::pipeline::sym::StorageFormatClass::Unknown,
|
||||
},
|
||||
},
|
||||
RuntimeFact::AnisotropicSampler {
|
||||
slot: SlotRef {
|
||||
stage: Stage::Fragment,
|
||||
class: SlotClass::Sampler,
|
||||
index: 0,
|
||||
},
|
||||
},
|
||||
RuntimeFact::ObjectThreadgroupArena {
|
||||
static_bytes: 16,
|
||||
payload: Some(64),
|
||||
@@ -210,83 +132,61 @@ fn variant(f: &RuntimeFact) -> usize {
|
||||
RuntimeFact::IndirectGroupCount => 5,
|
||||
RuntimeFact::ResourcePresence { .. } => 6,
|
||||
RuntimeFact::SampleCount => 7,
|
||||
RuntimeFact::StorageTextureFormat { .. } => 8,
|
||||
RuntimeFact::SamplerCoordinates { .. } => 9,
|
||||
RuntimeFact::SamplerReduction { .. } => 10,
|
||||
RuntimeFact::ImageViewShape { .. } => 11,
|
||||
RuntimeFact::VertexFetch { .. } => 12,
|
||||
RuntimeFact::VertexBufferStride { .. } => 13,
|
||||
RuntimeFact::BaseVertexInstance => 14,
|
||||
RuntimeFact::DeviceAddresses { .. } => 15,
|
||||
RuntimeFact::BufferRangeLimit { .. } => 16,
|
||||
RuntimeFact::TexelBufferRange { .. } => 17,
|
||||
RuntimeFact::FramebufferFetch { .. } => 18,
|
||||
RuntimeFact::ExecutionStatus => 19,
|
||||
RuntimeFact::HeapNumericType { .. } => 20,
|
||||
RuntimeFact::SimdgroupEmulation { .. } => 21,
|
||||
RuntimeFact::AmplificationCount => 22,
|
||||
RuntimeFact::EmulatedSimdgroups => 23,
|
||||
RuntimeFact::ImageblockSize { .. } => 24,
|
||||
RuntimeFact::RenderTargetArrayLength { .. } => 25,
|
||||
RuntimeFact::StageInRegion => 26,
|
||||
RuntimeFact::StageInStride { .. } => 27,
|
||||
RuntimeFact::RegionViewports => 28,
|
||||
RuntimeFact::TileFunction => 29,
|
||||
RuntimeFact::TileAttachmentFormat { .. } => 30,
|
||||
RuntimeFact::StorageTextureNumericType { .. } => 31,
|
||||
RuntimeFact::OutOfBoundsAlpha { .. } => 32,
|
||||
RuntimeFact::BicubicTexels { .. } => 33,
|
||||
RuntimeFact::StorageTextureLevels { .. } => 34,
|
||||
RuntimeFact::StorageTextureLevelViews { .. } => 35,
|
||||
RuntimeFact::SparseTexture { .. } => 36,
|
||||
RuntimeFact::AccelerationStructureInstanceCount { .. } => 37,
|
||||
RuntimeFact::PredicationVote => 38,
|
||||
RuntimeFact::HeapStorageReads { .. } => 39,
|
||||
RuntimeFact::SrgbTexture { .. } => 40,
|
||||
RuntimeFact::ViewportCount => 41,
|
||||
RuntimeFact::AliasedImageblock { .. } => 42,
|
||||
RuntimeFact::CallStackDepth { .. } => 43,
|
||||
RuntimeFact::FlatGrid => 44,
|
||||
RuntimeFact::SparseTextureWrites { .. } => 45,
|
||||
RuntimeFact::TileThreadgroupMemory { .. } => 46,
|
||||
RuntimeFact::TextureSwizzle { .. } => 47,
|
||||
RuntimeFact::TileImageblock { .. } => 48,
|
||||
RuntimeFact::AmplificationDraws { .. } => 49,
|
||||
RuntimeFact::FoldedGroups => 51,
|
||||
RuntimeFact::ZeroedColor { .. } => 53,
|
||||
RuntimeFact::DroppedColor { .. } => 54,
|
||||
RuntimeFact::DepthClampRange => 55,
|
||||
RuntimeFact::ConstantLanes { .. } => 56,
|
||||
RuntimeFact::FunctionTableRange { .. } => 57,
|
||||
RuntimeFact::TileThreadgroup { .. } => 59,
|
||||
RuntimeFact::ConstexprSampled { .. } => 60,
|
||||
RuntimeFact::CubicSampler { .. } => 61,
|
||||
RuntimeFact::CubicArgumentSampler { .. } => 62,
|
||||
RuntimeFact::HeapRawSamples { .. } => 66,
|
||||
RuntimeFact::CrossClassReads { .. } => 69,
|
||||
RuntimeFact::HeapCrossClassNeutral { .. } => 72,
|
||||
RuntimeFact::AnisotropicSampler { .. } => 73,
|
||||
RuntimeFact::StorageTextureIntegerChannels { .. } => 74,
|
||||
RuntimeFact::ObjectThreadgroupArena { .. } => 77,
|
||||
RuntimeFact::ReplayBindings => 80,
|
||||
RuntimeFact::MergedDraws => 65,
|
||||
RuntimeFact::QuadPrimitiveIds => 52,
|
||||
RuntimeFact::RotatedWeights => 75,
|
||||
RuntimeFact::PrivateList => 78,
|
||||
RuntimeFact::PartialObjectThreadgroups => 81,
|
||||
RuntimeFact::OpenClMode => 83,
|
||||
RuntimeFact::RowLockstep => 84,
|
||||
RuntimeFact::BorderTexels { .. } => 58,
|
||||
RuntimeFact::HeapResidency { .. } => 76,
|
||||
RuntimeFact::CallThreadgroups => 82,
|
||||
RuntimeFact::PartialThreadgroups => 79,
|
||||
RuntimeFact::TexelBufferParts { .. } => 63,
|
||||
RuntimeFact::OpenClLineTexture { .. } => 67,
|
||||
RuntimeFact::AddressAlignment { .. } => 64,
|
||||
RuntimeFact::GridTiles => 50,
|
||||
RuntimeFact::PrivateArena { .. } => 68,
|
||||
RuntimeFact::StencilBitDraws => 70,
|
||||
RuntimeFact::RobustStorageBuffers => 71,
|
||||
RuntimeFact::ImageViewShape { .. } => 8,
|
||||
RuntimeFact::VertexFetch { .. } => 9,
|
||||
RuntimeFact::VertexBufferStride { .. } => 10,
|
||||
RuntimeFact::BaseVertexInstance => 11,
|
||||
RuntimeFact::DeviceAddresses { .. } => 12,
|
||||
RuntimeFact::FramebufferFetch { .. } => 13,
|
||||
RuntimeFact::SimdgroupEmulation { .. } => 14,
|
||||
RuntimeFact::AmplificationCount => 15,
|
||||
RuntimeFact::EmulatedSimdgroups => 16,
|
||||
RuntimeFact::ImageblockSize { .. } => 17,
|
||||
RuntimeFact::RenderTargetArrayLength { .. } => 18,
|
||||
RuntimeFact::StageInRegion => 19,
|
||||
RuntimeFact::StageInStride { .. } => 20,
|
||||
RuntimeFact::RegionViewports => 21,
|
||||
RuntimeFact::TileFunction => 22,
|
||||
RuntimeFact::TileAttachmentFormat { .. } => 23,
|
||||
RuntimeFact::StorageTextureNumericType { .. } => 24,
|
||||
RuntimeFact::OutOfBoundsAlpha { .. } => 25,
|
||||
RuntimeFact::StorageTextureLevels { .. } => 26,
|
||||
RuntimeFact::StorageTextureLevelViews { .. } => 27,
|
||||
RuntimeFact::SparseTexture { .. } => 28,
|
||||
RuntimeFact::AccelerationStructureInstanceCount { .. } => 29,
|
||||
RuntimeFact::PredicationVote => 30,
|
||||
RuntimeFact::ViewportCount => 31,
|
||||
RuntimeFact::AliasedImageblock { .. } => 32,
|
||||
RuntimeFact::CallStackDepth { .. } => 33,
|
||||
RuntimeFact::FlatGrid => 34,
|
||||
RuntimeFact::TileThreadgroupMemory { .. } => 35,
|
||||
RuntimeFact::TextureSwizzle { .. } => 36,
|
||||
RuntimeFact::TileImageblock { .. } => 37,
|
||||
RuntimeFact::AmplificationDraws { .. } => 38,
|
||||
RuntimeFact::FoldedGroups => 40,
|
||||
RuntimeFact::ZeroedColor { .. } => 42,
|
||||
RuntimeFact::DroppedColor { .. } => 43,
|
||||
RuntimeFact::DepthClampRange => 44,
|
||||
RuntimeFact::FunctionTableRange { .. } => 45,
|
||||
RuntimeFact::TileThreadgroup { .. } => 47,
|
||||
RuntimeFact::ObjectThreadgroupArena { .. } => 55,
|
||||
RuntimeFact::ReplayBindings => 58,
|
||||
RuntimeFact::MergedDraws => 49,
|
||||
RuntimeFact::QuadPrimitiveIds => 41,
|
||||
RuntimeFact::RotatedWeights => 54,
|
||||
RuntimeFact::PrivateList => 56,
|
||||
RuntimeFact::PartialObjectThreadgroups => 59,
|
||||
RuntimeFact::OpenClMode => 61,
|
||||
RuntimeFact::RowLockstep => 62,
|
||||
RuntimeFact::BorderTexels { .. } => 46,
|
||||
RuntimeFact::CallThreadgroups => 60,
|
||||
RuntimeFact::PartialThreadgroups => 57,
|
||||
RuntimeFact::OpenClLineTexture { .. } => 50,
|
||||
RuntimeFact::AddressAlignment { .. } => 48,
|
||||
RuntimeFact::GridTiles => 39,
|
||||
RuntimeFact::PrivateArena { .. } => 51,
|
||||
RuntimeFact::StencilBitDraws => 52,
|
||||
RuntimeFact::RobustStorageBuffers => 53,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -294,7 +194,7 @@ fn variant(f: &RuntimeFact) -> usize {
|
||||
fn mechanism_is_total_over_every_fact_and_profile() {
|
||||
let facts = every_fact();
|
||||
let covered: std::collections::BTreeSet<usize> = facts.iter().map(variant).collect();
|
||||
assert_eq!(covered, (0..85).collect(), "every_fact misses a variant");
|
||||
assert_eq!(covered, (0..63).collect(), "every_fact misses a variant");
|
||||
for (stem, _) in super::committed_profiles() {
|
||||
let dev = device(&stem);
|
||||
let p = dev.profile();
|
||||
@@ -308,26 +208,20 @@ fn mechanism_is_total_over_every_fact_and_profile() {
|
||||
| RuntimeFact::ThreadgroupMemoryLength { .. }
|
||||
| RuntimeFact::ResourcePresence { .. }
|
||||
| RuntimeFact::SampleCount
|
||||
| RuntimeFact::SamplerCoordinates { .. }
|
||||
| RuntimeFact::AmplificationCount
|
||||
| RuntimeFact::ImageblockSize { .. }
|
||||
| RuntimeFact::TileFunction
|
||||
| RuntimeFact::OutOfBoundsAlpha { .. }
|
||||
| RuntimeFact::BicubicTexels { .. }
|
||||
| RuntimeFact::BorderTexels { .. }
|
||||
| RuntimeFact::SparseTexture {
|
||||
sparse_arm: true, ..
|
||||
}
|
||||
| RuntimeFact::SparseTexture { tile_map: true, .. }
|
||||
| RuntimeFact::SparseTextureWrites { atomic: false, .. }
|
||||
| RuntimeFact::TileThreadgroupMemory { .. }
|
||||
| RuntimeFact::TextureSwizzle { .. }
|
||||
| RuntimeFact::ConstantLanes { .. } => Mechanism::Specialization,
|
||||
| RuntimeFact::TextureSwizzle { .. } => Mechanism::Specialization,
|
||||
RuntimeFact::LocalSizeConstraint { .. }
|
||||
| RuntimeFact::LocalSizeLimits
|
||||
| RuntimeFact::SamplerReduction { .. }
|
||||
| RuntimeFact::DeviceAddresses { .. }
|
||||
| RuntimeFact::TexelBufferRange { .. }
|
||||
| RuntimeFact::SimdgroupEmulation { .. }
|
||||
| RuntimeFact::PredicationVote
|
||||
| RuntimeFact::SparseTexture {
|
||||
@@ -335,12 +229,6 @@ fn mechanism_is_total_over_every_fact_and_profile() {
|
||||
tile_map: false,
|
||||
..
|
||||
}
|
||||
| RuntimeFact::SparseTextureWrites { atomic: true, .. }
|
||||
| RuntimeFact::CubicArgumentSampler { .. }
|
||||
| RuntimeFact::HeapRawSamples { .. }
|
||||
| RuntimeFact::HeapCrossClassNeutral { .. }
|
||||
| RuntimeFact::HeapResidency { .. }
|
||||
| RuntimeFact::HeapStorageReads { .. }
|
||||
| RuntimeFact::ObjectThreadgroupArena { .. }
|
||||
| RuntimeFact::AddressAlignment { .. }
|
||||
| RuntimeFact::RowLockstep => Mechanism::PlanTimeCheck,
|
||||
@@ -349,12 +237,9 @@ fn mechanism_is_total_over_every_fact_and_profile() {
|
||||
| RuntimeFact::PartialObjectThreadgroups
|
||||
| RuntimeFact::GridTiles => Mechanism::RegionSelected,
|
||||
RuntimeFact::IndirectGroupCount => Mechanism::None,
|
||||
RuntimeFact::StorageTextureFormat { .. }
|
||||
| RuntimeFact::StorageTextureNumericType { .. }
|
||||
RuntimeFact::StorageTextureNumericType { .. }
|
||||
| RuntimeFact::EmulatedSimdgroups
|
||||
| RuntimeFact::RenderTargetArrayLength { .. }
|
||||
| RuntimeFact::SrgbTexture { .. }
|
||||
| RuntimeFact::CrossClassReads { .. }
|
||||
| RuntimeFact::FlatGrid
|
||||
| RuntimeFact::CallThreadgroups
|
||||
| RuntimeFact::PartialThreadgroups
|
||||
@@ -365,15 +250,11 @@ fn mechanism_is_total_over_every_fact_and_profile() {
|
||||
| RuntimeFact::QuadPrimitiveIds
|
||||
| RuntimeFact::PrivateList
|
||||
| RuntimeFact::RegionViewports
|
||||
| RuntimeFact::TexelBufferParts { .. }
|
||||
| RuntimeFact::OpenClLineTexture { .. }
|
||||
| RuntimeFact::ZeroedColor { .. }
|
||||
| RuntimeFact::DroppedColor { .. }
|
||||
| RuntimeFact::DepthClampRange
|
||||
| RuntimeFact::RotatedWeights
|
||||
| RuntimeFact::ConstexprSampled { .. }
|
||||
| RuntimeFact::CubicSampler { .. }
|
||||
| RuntimeFact::AnisotropicSampler { .. } => Mechanism::Variant,
|
||||
| RuntimeFact::RotatedWeights => Mechanism::Variant,
|
||||
RuntimeFact::ImageViewShape { .. }
|
||||
| RuntimeFact::StorageTextureLevelViews { .. } => Mechanism::BinderView,
|
||||
RuntimeFact::VertexFetch { .. } | RuntimeFact::TileAttachmentFormat { .. } => {
|
||||
@@ -393,24 +274,16 @@ fn mechanism_is_total_over_every_fact_and_profile() {
|
||||
Mechanism::PushConstant
|
||||
}
|
||||
}
|
||||
RuntimeFact::BufferRangeLimit { .. } | RuntimeFact::FunctionTableRange { .. } => {
|
||||
match f.buffer_access {
|
||||
crate::device::profile::BufferAccess::Addressed => Mechanism::Variant,
|
||||
_ => Mechanism::PlanTimeCheck,
|
||||
}
|
||||
}
|
||||
RuntimeFact::FunctionTableRange { .. } => match f.buffer_access {
|
||||
crate::device::profile::BufferAccess::Addressed => Mechanism::Variant,
|
||||
_ => Mechanism::PlanTimeCheck,
|
||||
},
|
||||
RuntimeFact::FramebufferFetch { .. } | RuntimeFact::TileImageblock { .. } => {
|
||||
Mechanism::RenderPassContract
|
||||
}
|
||||
RuntimeFact::ExecutionStatus => match f.buffer_access {
|
||||
crate::device::profile::BufferAccess::Addressed => Mechanism::PushConstant,
|
||||
_ => Mechanism::SyntheticBinding,
|
||||
},
|
||||
RuntimeFact::HeapNumericType { .. } => Mechanism::BinderView,
|
||||
RuntimeFact::StageInRegion
|
||||
| RuntimeFact::StageInStride { .. }
|
||||
| RuntimeFact::StorageTextureLevels { .. }
|
||||
| RuntimeFact::StorageTextureIntegerChannels { .. }
|
||||
| RuntimeFact::AccelerationStructureInstanceCount { .. }
|
||||
| RuntimeFact::ViewportCount
|
||||
| RuntimeFact::PrivateArena { .. }
|
||||
@@ -423,49 +296,3 @@ fn mechanism_is_total_over_every_fact_and_profile() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profile_dependent_rows_differ_where_the_design_says() {
|
||||
let range = RuntimeFact::BufferRangeLimit {
|
||||
slot: SlotRef {
|
||||
stage: Stage::Kernel,
|
||||
class: SlotClass::Buffer,
|
||||
index: 0,
|
||||
},
|
||||
};
|
||||
// Below the runtime's floor: `runtime-floor` as a Vulkan 1.2 context reads it, without device
|
||||
// addresses, 64-bit integers or shader draw parameters.
|
||||
use crate::device::requirements::VkFeature;
|
||||
let mut below = crate::pipeline::testing::description_at_1_2("runtime-floor", false).unwrap();
|
||||
for f in [
|
||||
VkFeature::BufferDeviceAddress,
|
||||
VkFeature::ShaderInt64,
|
||||
VkFeature::ShaderDrawParameters,
|
||||
] {
|
||||
below.features.remove(&f);
|
||||
}
|
||||
let floor =
|
||||
crate::device::Device::from_queries(below, crate::device::DevicePolicy::RESIDENT_TABLES)
|
||||
.unwrap();
|
||||
let addressed = device("nvidia-rtx50-linux");
|
||||
assert_eq!(mechanism(&range, floor.profile()), Mechanism::PlanTimeCheck);
|
||||
assert_eq!(mechanism(&range, addressed.profile()), Mechanism::Variant);
|
||||
let stride = RuntimeFact::VertexBufferStride { layout: 0 };
|
||||
assert_eq!(
|
||||
mechanism(&stride, floor.profile()),
|
||||
Mechanism::PipelineStateOrPushConstant
|
||||
);
|
||||
assert_eq!(
|
||||
mechanism(&stride, addressed.profile()),
|
||||
Mechanism::DynamicStateOrPushConstant
|
||||
);
|
||||
// The device reads GPU-written group counts where Metal wrote them.
|
||||
assert_eq!(
|
||||
mechanism(&RuntimeFact::IndirectGroupCount, floor.profile()),
|
||||
Mechanism::None
|
||||
);
|
||||
assert_eq!(
|
||||
mechanism(&RuntimeFact::BaseVertexInstance, floor.profile()),
|
||||
Mechanism::PushConstant
|
||||
);
|
||||
}
|
||||
@@ -1,25 +1,23 @@
|
||||
//! `Device::from_queries`, profile derivation, the fingerprint, and `requirements ⊆ profile`.
|
||||
|
||||
use super::*;
|
||||
use crate::device::profile::{BufferAccess, HandleDomain, Independence, PointerDomain};
|
||||
use crate::device::profile::{BufferAccess, Independence};
|
||||
use crate::device::requirements::{Requirements, StageCreateFlag, VkLimit, VkProperty};
|
||||
use crate::error::{Capability, Feature, Needs};
|
||||
|
||||
pub(crate) fn device(stem: &str) -> Device {
|
||||
Device::from_queries(profile(stem), DevicePolicy::RESIDENT_TABLES)
|
||||
.expect("committed profile derives")
|
||||
Device::from_queries(profile(stem)).expect("committed profile derives")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_committed_profile_derives() {
|
||||
for (stem, text) in committed_profiles() {
|
||||
let desc = DeviceDescription::from_khronos_json(&text, None).unwrap();
|
||||
let dev = Device::from_queries(desc.clone(), DevicePolicy::RESIDENT_TABLES)
|
||||
.unwrap_or_else(|e| panic!("{stem}: {e}"));
|
||||
let dev = Device::from_queries(desc.clone()).unwrap_or_else(|e| panic!("{stem}: {e}"));
|
||||
let f = dev.profile().fields();
|
||||
assert_eq!(f.api_version, desc.api_version, "{stem}");
|
||||
// Deterministic.
|
||||
let again = Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).unwrap();
|
||||
let again = Device::from_queries(desc).unwrap();
|
||||
assert_eq!(dev.profile(), again.profile(), "{stem}");
|
||||
assert_eq!(dev.profile().fingerprint(), again.profile().fingerprint());
|
||||
// A profile satisfies the requirements of everything it enabled.
|
||||
@@ -56,7 +54,7 @@ fn occlusion_query_precise_follows_each_source() {
|
||||
stated,
|
||||
"{stem}"
|
||||
);
|
||||
let dev = Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).unwrap();
|
||||
let dev = Device::from_queries(desc).unwrap();
|
||||
let enabled = &dev.profile().fields().enabled.features;
|
||||
assert_eq!(
|
||||
enabled.contains(&VkFeature::OcclusionQueryPrecise),
|
||||
@@ -89,7 +87,7 @@ fn depth_bias_control_follows_each_source() {
|
||||
let desc = DeviceDescription::from_khronos_json(&text, None).unwrap();
|
||||
let has_extension = desc.extensions.contains(&VkExtension::ExtDepthBiasControl);
|
||||
assert_eq!(has_extension, stated.is_some(), "{stem}");
|
||||
let dev = Device::from_queries(desc.clone(), DevicePolicy::RESIDENT_TABLES).unwrap();
|
||||
let dev = Device::from_queries(desc.clone()).unwrap();
|
||||
let enabled = &dev.profile().fields().enabled;
|
||||
for (member, feature) in features {
|
||||
let want = stated
|
||||
@@ -139,21 +137,9 @@ fn find_structure(v: &serde_json::Value, name: &str, out: &mut Option<serde_json
|
||||
}
|
||||
}
|
||||
|
||||
/// Every committed profile at or above the runtime's floor reaches its buffers by address.
|
||||
#[test]
|
||||
fn memory_profiles_follow_bda_and_int64() {
|
||||
// Without either, below the runtime's floor, which requires both.
|
||||
for without in [
|
||||
&[VkFeature::BufferDeviceAddress, VkFeature::ShaderInt64][..],
|
||||
&[VkFeature::ShaderInt64],
|
||||
] {
|
||||
let dev =
|
||||
Device::from_queries(floor_without(without), DevicePolicy::RESIDENT_TABLES).unwrap();
|
||||
assert_eq!(
|
||||
dev.profile().fields().buffer_access,
|
||||
BufferAccess::Floor,
|
||||
"{without:?}"
|
||||
);
|
||||
}
|
||||
fn every_committed_profile_reaches_its_buffers_by_address() {
|
||||
for stem in [
|
||||
"runtime-floor",
|
||||
"moltenvk-m3",
|
||||
@@ -171,25 +157,6 @@ fn memory_profiles_follow_bda_and_int64() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A Profile F refusal names what the device lacks of Profile A, never a feature it has: on
|
||||
/// `runtime-floor` without either feature, and without `shaderInt64` alone.
|
||||
#[test]
|
||||
fn addressed_needs_name_only_the_missing_features() {
|
||||
let bda = Capability::Feature(VkFeature::BufferDeviceAddress);
|
||||
let int64 = Capability::Feature(VkFeature::ShaderInt64);
|
||||
let needs = |without: &[VkFeature]| {
|
||||
Device::from_queries(floor_without(without), DevicePolicy::RESIDENT_TABLES)
|
||||
.unwrap()
|
||||
.profile()
|
||||
.addressed_needs()
|
||||
};
|
||||
assert_eq!(
|
||||
needs(&[VkFeature::BufferDeviceAddress, VkFeature::ShaderInt64]),
|
||||
vec![bda, int64.clone()]
|
||||
);
|
||||
assert_eq!(needs(&[VkFeature::ShaderInt64]), vec![int64]);
|
||||
}
|
||||
|
||||
/// `runtime-floor` derives the profile of a device at the runtime's floor: addressed buffers,
|
||||
/// stores and atomics in every stage, and the formats the Vulkan 1.2 Required Format Support
|
||||
/// tables require of it.
|
||||
@@ -243,12 +210,12 @@ fn vertex_layer_and_viewport_outputs_follow_the_features_not_the_extension() {
|
||||
assert!(desc
|
||||
.extensions
|
||||
.contains(&VkExtension::ExtShaderViewportIndexLayer));
|
||||
let full = Device::from_queries(desc.clone(), DevicePolicy::RESIDENT_TABLES).unwrap();
|
||||
let full = Device::from_queries(desc.clone()).unwrap();
|
||||
let f = full.profile().fields();
|
||||
assert!(f.fragment.output_layer && f.fragment.output_viewport_index);
|
||||
assert!(desc.features.remove(&VkFeature::ShaderOutputLayer));
|
||||
assert!(desc.features.remove(&VkFeature::ShaderOutputViewportIndex));
|
||||
let lacking = Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).unwrap();
|
||||
let lacking = Device::from_queries(desc).unwrap();
|
||||
let f = lacking.profile().fields();
|
||||
assert!(!f.fragment.output_layer);
|
||||
assert!(!f.fragment.output_viewport_index);
|
||||
@@ -275,7 +242,7 @@ fn moltenvk_m3_derives_its_stride_and_format_usages() {
|
||||
fn below_1_2_is_refused() {
|
||||
let mut desc = profile("runtime-floor");
|
||||
desc.api_version = ApiVersion { major: 1, minor: 1 };
|
||||
match Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES) {
|
||||
match Device::from_queries(desc) {
|
||||
Err(Error::Unsupported(u)) => {
|
||||
assert_eq!(u.feature, Feature::VulkanVersion);
|
||||
assert_eq!(
|
||||
@@ -287,91 +254,40 @@ fn below_1_2_is_refused() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The identity domains come as a pair (`InvalidDescriptor` for one alone) and need
|
||||
/// `bufferDeviceAddress` and `shaderInt64` (`Unsupported{IdentityDomains}` naming both, on a
|
||||
/// device without `shaderInt64`). What they lower is `tests::engine_identity`'s.
|
||||
/// The identity domains need `bufferDeviceAddress` and `shaderInt64`: a device without either,
|
||||
/// below the runtime's floor, which requires both, is refused at `Device::from_queries`:
|
||||
/// `Unsupported{IdentityDomains}` naming both. What they lower is `tests::engine_identity`'s.
|
||||
#[test]
|
||||
fn the_identity_domains_come_as_a_pair_on_a_device_with_addresses() {
|
||||
let identity = DevicePolicy {
|
||||
pointer_domain: PointerDomain::Identity,
|
||||
handle_domain: HandleDomain::Identity,
|
||||
..DevicePolicy::RESIDENT_TABLES
|
||||
};
|
||||
for half in [
|
||||
DevicePolicy {
|
||||
pointer_domain: PointerDomain::Identity,
|
||||
..DevicePolicy::RESIDENT_TABLES
|
||||
},
|
||||
DevicePolicy {
|
||||
handle_domain: HandleDomain::Identity,
|
||||
..DevicePolicy::RESIDENT_TABLES
|
||||
},
|
||||
fn the_identity_domains_need_addresses_and_64_bit_integers() {
|
||||
let both = [VkFeature::BufferDeviceAddress, VkFeature::ShaderInt64];
|
||||
let both = both.map(Capability::Feature).to_vec();
|
||||
for without in [
|
||||
&[VkFeature::BufferDeviceAddress, VkFeature::ShaderInt64][..],
|
||||
&[VkFeature::BufferDeviceAddress],
|
||||
&[VkFeature::ShaderInt64],
|
||||
] {
|
||||
assert!(
|
||||
matches!(
|
||||
Device::from_queries(profile("lavapipe"), half),
|
||||
Err(Error::InvalidDescriptor(
|
||||
DescriptorError::DeviceDescription { .. }
|
||||
))
|
||||
),
|
||||
"{half:?}"
|
||||
);
|
||||
}
|
||||
// `runtime-floor` without `shaderInt64`: device addresses, no 64-bit integers.
|
||||
match Device::from_queries(floor_without(&[VkFeature::ShaderInt64]), identity) {
|
||||
Err(Error::Unsupported(u)) => {
|
||||
assert_eq!(u.feature, Feature::IdentityDomains);
|
||||
let both = [VkFeature::BufferDeviceAddress, VkFeature::ShaderInt64];
|
||||
let both = both.map(Capability::Feature).to_vec();
|
||||
assert_eq!(u.needs, Needs::AnyOf(vec![both]));
|
||||
match Device::from_queries(floor_without(without)) {
|
||||
Err(Error::Unsupported(u)) => {
|
||||
assert_eq!(u.feature, Feature::IdentityDomains, "{without:?}");
|
||||
assert_eq!(u.needs, Needs::AnyOf(vec![both.clone()]), "{without:?}");
|
||||
}
|
||||
other => panic!("{without:?}: {:?}", other.map(|_| ())),
|
||||
}
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The fingerprint covers the description's fields: a feature or a limit changes it.
|
||||
#[test]
|
||||
fn fingerprint_covers_every_policy_field() {
|
||||
fn fingerprint_covers_the_description() {
|
||||
let desc = profile("lavapipe");
|
||||
let base = DevicePolicy::RESIDENT_TABLES;
|
||||
let fp = |p: DevicePolicy| {
|
||||
Device::from_queries(desc.clone(), p)
|
||||
.unwrap()
|
||||
.profile()
|
||||
.fingerprint()
|
||||
};
|
||||
let reference = fp(base);
|
||||
let mut variants = Vec::new();
|
||||
let identity = DevicePolicy {
|
||||
pointer_domain: PointerDomain::Identity,
|
||||
handle_domain: HandleDomain::Identity,
|
||||
..base
|
||||
};
|
||||
variants.push(("domains", identity));
|
||||
let mut seen = vec![reference];
|
||||
for (name, p) in variants {
|
||||
let h = fp(p);
|
||||
assert!(!seen.contains(&h), "{name} did not change the fingerprint");
|
||||
seen.push(h);
|
||||
}
|
||||
// Description-derived fields are covered too.
|
||||
let fp = |d: DeviceDescription| Device::from_queries(d).unwrap().profile().fingerprint();
|
||||
let reference = fp(desc.clone());
|
||||
let mut fewer = desc.clone();
|
||||
fewer.features.remove(&VkFeature::ShaderInt8);
|
||||
assert_ne!(
|
||||
Device::from_queries(fewer, base)
|
||||
.unwrap()
|
||||
.profile()
|
||||
.fingerprint(),
|
||||
reference
|
||||
);
|
||||
assert_ne!(fp(fewer), reference);
|
||||
let mut limits = desc;
|
||||
limits.limits.max_texel_offset += 1;
|
||||
assert_ne!(
|
||||
Device::from_queries(limits, base)
|
||||
.unwrap()
|
||||
.profile()
|
||||
.fingerprint(),
|
||||
reference
|
||||
);
|
||||
assert_ne!(fp(limits), reference);
|
||||
}
|
||||
|
||||
/// The fingerprint streams the `Debug` rendering into the hash; it must equal the hash of the
|
||||
@@ -449,7 +365,7 @@ fn allocation_sizes_are_no_profile_field() {
|
||||
] {
|
||||
let mut other = desc.clone();
|
||||
other.allocation = AllocationLimits::new(memory, buffer);
|
||||
let dev = Device::from_queries(other, DevicePolicy::RESIDENT_TABLES).unwrap();
|
||||
let dev = Device::from_queries(other).unwrap();
|
||||
assert_eq!(dev.profile(), base.profile(), "{stem}");
|
||||
assert_eq!(
|
||||
dev.profile().fingerprint(),
|
||||
@@ -555,11 +471,7 @@ fn check_reports_the_first_missing_capability() {
|
||||
);
|
||||
// Stage flags need their enabling features, which the floor requires: the floor without
|
||||
// `computeFullSubgroups`, a device below it, names it.
|
||||
let without = Device::from_queries(
|
||||
floor_without(&[VkFeature::ComputeFullSubgroups]),
|
||||
DevicePolicy::RESIDENT_TABLES,
|
||||
)
|
||||
.unwrap();
|
||||
let without = Device::from_queries(floor_without(&[VkFeature::ComputeFullSubgroups])).unwrap();
|
||||
assert_eq!(
|
||||
without.profile().check(&Requirements {
|
||||
stage_flags: [StageCreateFlag::RequireFullSubgroups].into(),
|
||||
@@ -592,7 +504,6 @@ fn device_is_send_sync_and_cheap_to_clone() {
|
||||
fn send_sync<T: Send + Sync + Clone>() {}
|
||||
send_sync::<Device>();
|
||||
send_sync::<DeviceDescription>();
|
||||
send_sync::<DevicePolicy>();
|
||||
}
|
||||
|
||||
/// The storage-without-format usages: per format and per image or buffer from
|
||||
@@ -641,14 +552,14 @@ fn storage_without_format_follows_each_format() {
|
||||
U::StorageTexelBufferReadWithoutFormat,
|
||||
U::StorageTexelBufferWriteWithoutFormat,
|
||||
];
|
||||
let dev = Device::from_queries(desc.clone(), DevicePolicy::RESIDENT_TABLES).unwrap();
|
||||
let dev = Device::from_queries(desc.clone()).unwrap();
|
||||
assert_eq!(usages(&dev, vk::Format::R32_UINT), all);
|
||||
assert_eq!(usages(&dev, vk::Format::B8G8R8A8_UNORM), []);
|
||||
let mut write_only = desc.clone();
|
||||
write_only
|
||||
.features
|
||||
.remove(&VkFeature::ShaderStorageImageReadWithoutFormat);
|
||||
let dev = Device::from_queries(write_only, DevicePolicy::RESIDENT_TABLES).unwrap();
|
||||
let dev = Device::from_queries(write_only).unwrap();
|
||||
assert_eq!(
|
||||
usages(&dev, vk::Format::R32_UINT),
|
||||
[
|
||||
@@ -661,7 +572,7 @@ fn storage_without_format_follows_each_format() {
|
||||
// extension at 1.2 reports them as Vulkan 1.3 does.
|
||||
desc.khr_format_feature_flags2 = true;
|
||||
assert!(desc.has_format_feature_flags2());
|
||||
let dev = Device::from_queries(desc.clone(), DevicePolicy::RESIDENT_TABLES).unwrap();
|
||||
let dev = Device::from_queries(desc.clone()).unwrap();
|
||||
assert_eq!(
|
||||
usages(&dev, vk::Format::R32_UINT),
|
||||
[
|
||||
@@ -677,7 +588,7 @@ fn storage_without_format_follows_each_format() {
|
||||
F::STORAGE_READ_WITHOUT_FORMAT,
|
||||
),
|
||||
);
|
||||
let dev = Device::from_queries(desc.clone(), DevicePolicy::RESIDENT_TABLES).unwrap();
|
||||
let dev = Device::from_queries(desc.clone()).unwrap();
|
||||
assert_eq!(
|
||||
usages(&dev, vk::Format::B8G8R8A8_UNORM),
|
||||
[
|
||||
@@ -688,7 +599,7 @@ fn storage_without_format_follows_each_format() {
|
||||
// The implication needs the feature.
|
||||
desc.features
|
||||
.remove(&VkFeature::ShaderStorageImageReadWithoutFormat);
|
||||
let dev = Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).unwrap();
|
||||
let dev = Device::from_queries(desc).unwrap();
|
||||
assert_eq!(
|
||||
usages(&dev, vk::Format::R32_UINT),
|
||||
[U::StorageImageWriteWithoutFormat]
|
||||
@@ -744,7 +655,7 @@ fn from_queries_half_rounding_follows_the_queries_alone() {
|
||||
let mut controlled = Vec::new();
|
||||
for (stem, text) in committed_profiles() {
|
||||
let desc = DeviceDescription::from_khronos_json(&text, None).unwrap();
|
||||
let device = Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).unwrap();
|
||||
let device = Device::from_queries(desc).unwrap();
|
||||
let p = device.profile();
|
||||
if half_controls(p) {
|
||||
assert_eq!(quantize_form(p), QuantizeForm::Controlled, "{stem}");
|
||||
|
||||
@@ -145,7 +145,7 @@ fn render_features_follow_each_source() {
|
||||
for (stem, text) in committed_profiles() {
|
||||
let json: Value = serde_json::from_str(&text).unwrap();
|
||||
let desc = DeviceDescription::from_khronos_json(&text, None).unwrap();
|
||||
let dev = Device::from_queries(desc.clone(), DevicePolicy::RESIDENT_TABLES).unwrap();
|
||||
let dev = Device::from_queries(desc.clone()).unwrap();
|
||||
let enabled = &dev.profile().fields().enabled;
|
||||
for (structure, member, feature, extension) in FEATURES {
|
||||
let exposed = extension.is_none_or(|e| desc.extensions.contains(&e));
|
||||
@@ -215,7 +215,7 @@ fn render_properties_and_limits_follow_each_source() {
|
||||
for (stem, text) in committed_profiles() {
|
||||
let json: Value = serde_json::from_str(&text).unwrap();
|
||||
let desc = DeviceDescription::from_khronos_json(&text, None).unwrap();
|
||||
let dev = Device::from_queries(desc.clone(), DevicePolicy::RESIDENT_TABLES).unwrap();
|
||||
let dev = Device::from_queries(desc.clone()).unwrap();
|
||||
let properties = &dev.profile().fields().enabled.properties;
|
||||
let depth = stated_flags(&json, "supportedDepthResolveModes");
|
||||
let stencil = stated_flags(&json, "supportedStencilResolveModes");
|
||||
@@ -278,7 +278,7 @@ fn each_stated_color_attachment_sample_count_derives_its_property() {
|
||||
for (stem, text) in committed_profiles() {
|
||||
let json: Value = serde_json::from_str(&text).unwrap();
|
||||
let desc = DeviceDescription::from_khronos_json(&text, None).unwrap();
|
||||
let dev = Device::from_queries(desc.clone(), DevicePolicy::RESIDENT_TABLES).unwrap();
|
||||
let dev = Device::from_queries(desc.clone()).unwrap();
|
||||
let derived: BTreeSet<(vk::Format, u32)> = dev
|
||||
.profile()
|
||||
.fields()
|
||||
|
||||
@@ -796,8 +796,9 @@ pub enum Feature {
|
||||
/// push window a stage is lowered for: a compute stage's dispatch region and buffer addresses,
|
||||
/// a render pipeline's two stages together.
|
||||
PushWindow,
|
||||
/// The identity pointer and handle domains (`PointerDomain::Identity`,
|
||||
/// `HandleDomain::Identity`): on a device without `bufferDeviceAddress` and `shaderInt64`
|
||||
/// The identity pointer and handle domains, where a pointer is the device address it holds and
|
||||
/// a texture's or sampler's handle is its `gpuResourceID`: on a device without
|
||||
/// `bufferDeviceAddress` and `shaderInt64`
|
||||
/// (needing them, with no cause), and, on any device, a compile of a function holding a form
|
||||
/// they do not lower yet ([`Needs::NotImplemented`], the form named by [`IdentityCause`]).
|
||||
IdentityDomains,
|
||||
@@ -970,11 +971,6 @@ pub enum Feature {
|
||||
/// ([`GenericPointer`]). Vulkan's logical addressing has no pointer that may point into either
|
||||
/// of two storage classes.
|
||||
GenericPointer(GenericPointer),
|
||||
/// A sequentially consistent fence (`seq_cst` `atomic_thread_fence`, an LLVM `fence seq_cst`,
|
||||
/// or a `seq_cst` barrier ordering device memory), whose total order with the command
|
||||
/// buffer's other such fences the translation keeps through an atomic of the command buffer's
|
||||
/// `ExecutionStatus` word: in a vertex or fragment stage without its stores and atomics.
|
||||
SeqCstFence,
|
||||
/// The coverage after the depth and stencil tests (`[[sample_mask, post_depth_coverage]]`).
|
||||
/// Vulkan's one form reads `SampleMask` under `VK_EXT_post_depth_coverage`, which no runtime
|
||||
/// enables; no form is built.
|
||||
@@ -1106,8 +1102,9 @@ pub enum IdentityCause {
|
||||
/// minimum level or emulated filter the function specializes, a bicubic filter of a 1D
|
||||
/// texture, or an anisotropic sampler slot whose filter the function emulates.
|
||||
SamplerState,
|
||||
/// A sequentially consistent fence, which orders through the command buffer's execution status
|
||||
/// word the identity domains do not reach.
|
||||
/// A sequentially consistent fence, which Vulkan has no order for: its memory model reads
|
||||
/// `SequentiallyConsistent` as acquire-release, whose fence allows the store buffering Metal's
|
||||
/// fence forbids.
|
||||
SeqCstFence,
|
||||
/// A storage texture access the device takes only with a declared format, whose bound format
|
||||
/// no input names under the identity domains.
|
||||
|
||||
@@ -280,17 +280,6 @@ impl CompiledFunction {
|
||||
pub fn writes_memory(&self) -> bool {
|
||||
self.0.interface.writes_memory
|
||||
}
|
||||
|
||||
/// Whether the function reads the resident root table: it has a device-address slot or a
|
||||
/// dynamic root, so the binder builds the table with an entry for each such slot.
|
||||
pub fn reads_resident_roots(&self) -> bool {
|
||||
self.0.interface.needs_pointer_translation
|
||||
}
|
||||
|
||||
/// Whether the function looks texture or sampler handles up in the handle table.
|
||||
pub fn resolves_handles(&self) -> bool {
|
||||
self.0.interface.needs_handle_translation
|
||||
}
|
||||
}
|
||||
|
||||
/// What one per-function compile retains, with its provenance: the profile it was compiled for and
|
||||
@@ -313,8 +302,6 @@ pub struct FunctionArtifact {
|
||||
/// What the finalize verifier counted of the module: what its linked stage states as
|
||||
/// `StageModule::stats`.
|
||||
pub stats: ModuleStats,
|
||||
/// Constant data the function reads through `WriteSource::ConstantBlob`.
|
||||
pub blob: Option<Arc<[u8]>>,
|
||||
pub requirements: Requirements,
|
||||
/// Specialization and variant bits the function can take.
|
||||
pub variant_bits: u32,
|
||||
@@ -336,9 +323,6 @@ pub struct FunctionArtifact {
|
||||
/// take it away, and a per-slot gap is one undetermined answer among the others
|
||||
/// (`SlotWritability::Unknown`).
|
||||
pub(crate) slot_writes: Vec<crate::reflection::SlotWrite>,
|
||||
/// The notes of `precision` that hold only under some specializations, with their
|
||||
/// conditions: what its linked stage states as `StageModule::specialized_notes`.
|
||||
pub specialized: Vec<crate::pipeline::artifact::SpecializedNote>,
|
||||
}
|
||||
|
||||
/// What a kernel's `ComputePipelineMetalInfo`, and an object or mesh function's checks against its
|
||||
|
||||
@@ -7,39 +7,22 @@
|
||||
//! beside a removed texture table, dropped a kernel's whole body, so no one translation is Metal's.
|
||||
//! The read writes no status: it takes the zero of its result's type (a read's zeros and a
|
||||
//! query's size of 0, which the nil texture, set 1's element 0, answers too) and fetches nothing,
|
||||
//! a write of a removed texture is dropped, and the stage takes no `ExecutionStatus` buffer, push
|
||||
//! field or fact for it.
|
||||
//! and a write of a removed texture is dropped.
|
||||
//!
|
||||
//! A load or atomic of threadgroup memory the constants removed is the same read
|
||||
//! ([`FunctionConstant::AbsentMemory`]), and so is a texture operation on a removed texture or
|
||||
//! sampler that lowering reaches through memory, an aggregate, a table, or a merge
|
||||
//! (`texture::AbsentArgument`).
|
||||
//!
|
||||
//! The module also holds how a stage writes the command buffer's `ExecutionStatus` words, for a
|
||||
//! sequentially consistent fence (`sync::barrier`) and an argument buffer's cubic sampler's mark
|
||||
//! (`sampler::emit`): the stage states [`RuntimeFact::ExecutionStatus`] and reaches the buffer by
|
||||
//! its device address ([`PushField::ExecutionStatusAddress`]) where the device addresses buffers
|
||||
//! (`bufferDeviceAddress` and `shaderInt64`), and through a storage-buffer binding of its own
|
||||
//! (`SyntheticBinding::ExecutionStatus`, [`StatusBinding`]) where it does not, one more storage
|
||||
//! descriptor of the stage.
|
||||
|
||||
use crate::air::intrinsics::{AirIntrinsic, FunctionConstant};
|
||||
use crate::air::ir::{Callee, Inst, InstId, InstKind, Type, Value, ValueId};
|
||||
use crate::bind::status::{StatusBits, StatusWord};
|
||||
use crate::device::profile::BufferAccess;
|
||||
use crate::device::requirements::VkFeature;
|
||||
use crate::error::Error;
|
||||
use crate::lower::emit::EmitCx;
|
||||
use crate::lower::select::SelectCx;
|
||||
use crate::memory::leaf::k32;
|
||||
use crate::memory::roots::k64;
|
||||
use crate::memory::views::{self, View};
|
||||
use crate::pipeline::facts::RuntimeFact;
|
||||
use crate::pipeline::sym::{PushField, ResourceKind, ResourceSlot, Stage, SyntheticBinding};
|
||||
use crate::spirv::builder::{FunctionBuilder, ModuleBuilder};
|
||||
use crate::spirv::builder::FunctionBuilder;
|
||||
use crate::spirv::error::BResult;
|
||||
use crate::spirv::ids::DemoteTy;
|
||||
use crate::spirv::ir::{AtomicOp, BinOp, Constant, Scope, Semantics, Type as SType};
|
||||
use crate::spirv::ir::Constant;
|
||||
|
||||
/// An absent read ([`FunctionConstant::AbsentRead`]): zero.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
@@ -83,105 +66,6 @@ pub fn select(cx: &mut SelectCx<'_>, at: InstId, inst: &Inst) -> Result<Option<A
|
||||
Ok(Some(AbsentRead { result }))
|
||||
}
|
||||
|
||||
/// What the stage lacks to write the command buffer's `ExecutionStatus` words. Each refusal
|
||||
/// names its own feature at its site (`sync::barrier::require_seq_cst`), so the refusal surface
|
||||
/// reads each one's condition (`scripts/refusal-surface`).
|
||||
pub enum StatusShort {
|
||||
/// The stage's stores and atomics, which the device has not enabled.
|
||||
Stores(VkFeature),
|
||||
}
|
||||
|
||||
/// What the stage lacks to write the command buffer's `ExecutionStatus` words, or `None` where
|
||||
/// it can ([`state_status`] then states how it reaches the buffer).
|
||||
pub fn status_short(cx: &SelectCx<'_>) -> Option<StatusShort> {
|
||||
let enabled = &cx.profile.fields().enabled.features;
|
||||
super::dynamic::stage_stores(cx.stage)
|
||||
.find(|f| !enabled.contains(f))
|
||||
.map(StatusShort::Stores)
|
||||
}
|
||||
|
||||
/// Why a stage of a device that does not address buffers binds the command buffer's
|
||||
/// `ExecutionStatus` buffer (`SyntheticBinding::ExecutionStatus`), one more storage descriptor of
|
||||
/// the stage, which counts against its per-stage limits.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub enum StatusBinding {
|
||||
/// Only an argument buffer's sampler's cubic test marks the buffer
|
||||
/// (`sampler::select::cubic_reach`): where the stage's descriptors pass a per-stage limit with
|
||||
/// it, [`finish`] gives it back, and the stage marks nothing, as a fragment stage does (the
|
||||
/// planner refuses a listed cubic sampler beside the stage).
|
||||
CubicMark,
|
||||
/// A sequentially consistent fence writes the buffer: a stage past a per-stage limit with it
|
||||
/// is refused as `DescriptorCount`.
|
||||
Required,
|
||||
}
|
||||
|
||||
/// State how the stage reaches the `ExecutionStatus` buffer, which [`status_short`] found it can
|
||||
/// write, for `need`: its device address where the device addresses buffers, else its binding
|
||||
/// ([`StatusBinding`]), counted once in the stage's descriptors.
|
||||
pub fn state_status(cx: &mut SelectCx<'_>, need: StatusBinding) {
|
||||
cx.facts.insert(RuntimeFact::ExecutionStatus);
|
||||
if cx.profile.fields().buffer_access == BufferAccess::Addressed {
|
||||
cx.push.insert(PushField::ExecutionStatusAddress);
|
||||
return;
|
||||
}
|
||||
let access = &mut cx.families.access;
|
||||
if access.status_binding.is_none() {
|
||||
cx.descriptors.storage_buffers = cx.descriptors.storage_buffers.saturating_add(1);
|
||||
}
|
||||
access.status_binding = access.status_binding.max(Some(need));
|
||||
}
|
||||
|
||||
/// Give back a binding of the `ExecutionStatus` buffer that only the cubic mark holds
|
||||
/// ([`StatusBinding::CubicMark`]) where the stage's descriptors pass a per-stage limit with it:
|
||||
/// the stage then marks nothing, and states no cubic reach, so the planner refuses a listed cubic
|
||||
/// sampler beside it (`SamplerBicubicFilter`), as before the binding. Called once the slots'
|
||||
/// forms are final, before the limits are checked (`lower::select`).
|
||||
///
|
||||
/// The mark is one the stage may need, not one it does: only a cubic sampler that a command
|
||||
/// later lists in the argument buffer needs it, and that sampler then meets the planner's typed
|
||||
/// refusal, so giving the binding back hides nothing. Refusing the stage instead would refuse
|
||||
/// every stage near its limit that samples through an argument buffer, cubic sampler or not.
|
||||
pub fn finish(cx: &mut SelectCx<'_>) {
|
||||
if cx.families.access.status_binding != Some(StatusBinding::CubicMark) {
|
||||
return;
|
||||
}
|
||||
if cx
|
||||
.descriptors
|
||||
.exceeded(&cx.profile.fields().limits)
|
||||
.is_none()
|
||||
{
|
||||
return;
|
||||
}
|
||||
cx.families.access.status_binding = None;
|
||||
cx.descriptors.storage_buffers = cx.descriptors.storage_buffers.saturating_sub(1);
|
||||
cx.families.sampler.cubic_reach = false;
|
||||
cx.facts.remove(&RuntimeFact::ExecutionStatus);
|
||||
cx.facts
|
||||
.remove(&RuntimeFact::CubicArgumentSampler { stage: cx.stage });
|
||||
}
|
||||
|
||||
/// The binding symbol of `stage`'s `ExecutionStatus` buffer.
|
||||
pub fn symbol(stage: Stage) -> ResourceSlot {
|
||||
ResourceSlot {
|
||||
stage,
|
||||
kind: ResourceKind::Synthetic(SyntheticBinding::ExecutionStatus),
|
||||
index: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Declare the stage's `ExecutionStatus` view, a storage word view at its binding symbol, where
|
||||
/// it binds the buffer ([`StatusBinding`]).
|
||||
pub fn declare(
|
||||
mb: &mut ModuleBuilder,
|
||||
stage: Stage,
|
||||
plan: &super::AccessPlan,
|
||||
) -> BResult<Option<View>> {
|
||||
match plan.status_binding {
|
||||
Some(_) => Ok(Some(views::declare_at(mb, symbol(stage))?)),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
/// Emit absent read `s`, whose result is `vid`: define the result as zero.
|
||||
pub fn emit(
|
||||
cx: &mut EmitCx<'_>,
|
||||
@@ -200,54 +84,3 @@ pub fn emit(
|
||||
cx.define(vid, zero);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether the stage can write the command buffer's `ExecutionStatus` word for the cubic mark (the
|
||||
/// stage's stores and atomics), stating how it reaches the buffer where it can
|
||||
/// ([`StatusBinding::CubicMark`]).
|
||||
pub fn status_writable(cx: &mut SelectCx<'_>) -> bool {
|
||||
let writable = status_short(cx).is_none();
|
||||
if writable {
|
||||
state_status(cx, StatusBinding::CubicMark);
|
||||
}
|
||||
writable
|
||||
}
|
||||
|
||||
/// Set `bits` in the command buffer's `ExecutionStatus` word, where the open block runs (a
|
||||
/// relaxed device-scope `OR`); the stage stated how it reaches the buffer ([`status_writable`]).
|
||||
pub fn mark_bits(
|
||||
cx: &mut EmitCx<'_>,
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
bits: StatusBits,
|
||||
) -> BResult<()> {
|
||||
let word = status_word(cx, fb, StatusWord::Status)?;
|
||||
let bit = k32(fb, bits.0)?;
|
||||
fb.atomic(AtomicOp::Or, word, Scope::Device, Semantics::RELAXED, bit)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The place of the command buffer's `ExecutionStatus` word `w` (a `u32`): through the stage's
|
||||
/// binding of the buffer where it has one ([`declare`]), else by the buffer's device address; the
|
||||
/// stage stated which ([`state_status`]).
|
||||
pub fn status_word(
|
||||
cx: &mut EmitCx<'_>,
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
w: StatusWord,
|
||||
) -> BResult<crate::spirv::ids::Value> {
|
||||
if let Some(view) = cx.decl.families.access.status {
|
||||
let word = k32(fb, w.byte_offset() / 4)?;
|
||||
return views::word_ptr(fb, view, word);
|
||||
}
|
||||
let status = cx.push_field(fb, PushField::ExecutionStatusAddress)?;
|
||||
let address = match w.byte_offset() {
|
||||
0 => status,
|
||||
at => {
|
||||
let off = k64(fb, u64::from(at))?;
|
||||
fb.binary(BinOp::IAdd, status, off)?
|
||||
}
|
||||
};
|
||||
let u32_ty = fb.module().ty(SType::Int {
|
||||
width: 32,
|
||||
signed: false,
|
||||
})?;
|
||||
fb.device_place(address, u32_ty)
|
||||
}
|
||||
@@ -20,18 +20,17 @@ use crate::air::ir::{CastOp, Const, Inst, InstId, InstKind, Value, ValueId};
|
||||
use crate::error::{AccessCause, Error};
|
||||
use crate::lower::emit::EmitCx;
|
||||
use crate::lower::select::SelectCx;
|
||||
use crate::memory::blob::{BlobDecl, BlobHome, BlobUse};
|
||||
use crate::memory::blob::{BlobUse, ModuleWords};
|
||||
use crate::memory::contain;
|
||||
use crate::memory::leaf::{self, k32, Leaf, WordMem, WordOps};
|
||||
use crate::memory::leaf::{self, k32, Leaf, WordMem};
|
||||
use crate::memory::plan::{ConstGlobalForm, MemoryPlan};
|
||||
use crate::memory::provenance::{Repr, RootSetId};
|
||||
use crate::memory::views;
|
||||
use crate::spirv::builder::FunctionBuilder;
|
||||
use crate::spirv::error::BResult;
|
||||
use crate::spirv::ids::{DemoteTy, Value as SValue};
|
||||
use crate::spirv::ir::BinOp;
|
||||
|
||||
use super::emit::{index_u32, ViewMem};
|
||||
use super::emit::index_u32;
|
||||
use super::local::LocalPtr;
|
||||
use super::root_sets::SetFacts;
|
||||
use super::{is_ptr_ty, operand, refuse, GepTerms};
|
||||
@@ -143,9 +142,8 @@ pub fn lowered_pointer(cx: &SelectCx<'_>, v: Value) -> Result<Option<DemoteTy>,
|
||||
Ok(Some(DemoteTy::ArenaOffset))
|
||||
}
|
||||
|
||||
/// Record that the function reads the blob, its bytes shared with the memory plan's: under the
|
||||
/// identity domains the module's words, with no descriptor; otherwise bound, the artifact carrying
|
||||
/// its bytes and its storage descriptor counting in the per-stage limits.
|
||||
/// Record that the function reads the blob, its bytes shared with the memory plan's: the module's
|
||||
/// words, with no descriptor.
|
||||
pub fn use_blob(cx: &mut SelectCx<'_>) -> Result<(), Error> {
|
||||
if cx.families.access.blob.is_some() {
|
||||
return Ok(());
|
||||
@@ -154,14 +152,7 @@ pub fn use_blob(cx: &mut SelectCx<'_>) -> Result<(), Error> {
|
||||
Some(b) => Arc::clone(&b.bytes),
|
||||
None => return Err(cx.invariant("a blob pointer without a blob")),
|
||||
};
|
||||
let home = match super::identity(cx.profile) {
|
||||
true => BlobHome::Module,
|
||||
false => BlobHome::Bound,
|
||||
};
|
||||
cx.families.access.blob = Some(BlobUse { bytes, home });
|
||||
if home == BlobHome::Bound {
|
||||
cx.descriptors.storage_buffers = cx.descriptors.storage_buffers.saturating_add(1);
|
||||
}
|
||||
cx.families.access.blob = Some(BlobUse { bytes });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -306,26 +297,16 @@ pub fn load_at(
|
||||
load_decl(fb, decl, leaf, off)
|
||||
}
|
||||
|
||||
/// Load `leaf` at byte offset `off` of the declared blob `decl`, contained: a bound blob's view
|
||||
/// and the module's words alike.
|
||||
/// Load `leaf` at byte offset `off` of the declared blob `words`, contained.
|
||||
pub fn load_decl(
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
decl: BlobDecl,
|
||||
mut words: ModuleWords,
|
||||
leaf: &Leaf,
|
||||
off: SValue,
|
||||
) -> BResult<SValue> {
|
||||
// The blob is read-only: its words are the same on every load, which stay plain.
|
||||
match decl {
|
||||
BlobDecl::Bound(view) => {
|
||||
let mut mem = ViewMem(view, WordOps::default(), views::UnitViews::NONE);
|
||||
let size = views::storage_bytes(fb, view)?;
|
||||
contained(fb, &mut mem, leaf, off, size)
|
||||
}
|
||||
BlobDecl::Module(mut words) => {
|
||||
let size = k32(fb, words.words.saturating_mul(4))?;
|
||||
contained(fb, &mut words, leaf, off, size)
|
||||
}
|
||||
}
|
||||
let size = k32(fb, words.words.saturating_mul(4))?;
|
||||
contained(fb, &mut words, leaf, off, size)
|
||||
}
|
||||
|
||||
/// Load `leaf` at byte offset `off` of `mem`, whose bytes number `size`: the leaf, or zero where
|
||||
|
||||
@@ -773,17 +773,6 @@ pub fn base<'a>(
|
||||
cx: &mut EmitCx<'_>,
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
e: &'a Endpoint,
|
||||
) -> BResult<Base<'a>> {
|
||||
base_live(cx, fb, e, None)
|
||||
}
|
||||
|
||||
/// [`base`] of an intrinsic that accesses memory only when `live` holds (a dynamic length's
|
||||
/// nonzero one): a wide endpoint through root 0 counts a miss only then.
|
||||
fn base_live<'a>(
|
||||
cx: &mut EmitCx<'_>,
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
e: &'a Endpoint,
|
||||
live: Option<SValue>,
|
||||
) -> BResult<Base<'a>> {
|
||||
Ok(match e {
|
||||
Endpoint::Buffer(a) => {
|
||||
@@ -805,7 +794,7 @@ fn base_live<'a>(
|
||||
let p = cx.operand(fb, a.ptr)?;
|
||||
Base::Wide {
|
||||
p,
|
||||
b: dynamic::wide_base(cx, fb, p, a, live)?,
|
||||
b: dynamic::wide_base(cx, fb, p, a)?,
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -1246,7 +1235,7 @@ fn position(
|
||||
(Overlap::Addressed, Base::Buffer { a, fat, .. }) => {
|
||||
dynamic::static_guest_address(cx, fb, &a.targets, fat)
|
||||
}
|
||||
(Overlap::Addressed, Base::Wide { p, .. }) => dynamic::guest_address(cx, fb, p),
|
||||
(Overlap::Addressed, Base::Wide { p, .. }) => Ok(p),
|
||||
_ => Err(cx.fail("a directed memmove between endpoints it cannot compare")),
|
||||
}
|
||||
}
|
||||
@@ -1262,37 +1251,9 @@ pub fn emit<'c>(
|
||||
return Ok(());
|
||||
}
|
||||
let (n, tail) = span(cx, fb, op)?;
|
||||
// A dynamic length may be 0: a wide endpoint then accesses nothing (and counts no miss).
|
||||
let wide = matches!(op.dst, Endpoint::Wide(_))
|
||||
|| matches!(
|
||||
&op.src,
|
||||
Source::Copy {
|
||||
from: Endpoint::Wide(_),
|
||||
..
|
||||
}
|
||||
);
|
||||
let nonzero = |fb: &mut FunctionBuilder<'_>, v: SValue, wide: bool| -> BResult<SValue> {
|
||||
let zero = konst(fb, wide, 0)?;
|
||||
fb.binary(BinOp::INotEqual, v, zero)
|
||||
};
|
||||
let live = match (wide, n, tail) {
|
||||
(true, Count::Value(n), Count::Const(0)) => Some(nonzero(fb, n, false)?),
|
||||
(true, Count::Value(n), Count::Value(t)) => {
|
||||
let bytes = fb.binary(BinOp::IAdd, n, t)?;
|
||||
Some(nonzero(fb, bytes, false)?)
|
||||
}
|
||||
// A `u64` unit count: live when it or the tail is nonzero.
|
||||
(true, Count::Wide(n), Count::Const(0)) => Some(nonzero(fb, n, true)?),
|
||||
(true, Count::Wide(n), Count::Value(t)) => {
|
||||
let units = nonzero(fb, n, true)?;
|
||||
let bytes = nonzero(fb, t, false)?;
|
||||
Some(fb.binary(BinOp::LogicalOr, units, bytes)?)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let dst = base_live(cx, fb, &op.dst, live)?;
|
||||
let dst = base(cx, fb, &op.dst)?;
|
||||
let (from, overlap) = match &op.src {
|
||||
Source::Copy { from, overlap } => (Feed::Base(base_live(cx, fb, from, live)?), *overlap),
|
||||
Source::Copy { from, overlap } => (Feed::Base(base(cx, fb, from)?), *overlap),
|
||||
Source::Fill { value: Some(v), .. } => (Feed::Fill(cx.operand(fb, *v)?), Overlap::Disjoint),
|
||||
Source::Fill { value: None, konst } => {
|
||||
(Feed::Fill(k32(fb, u32::from(*konst))?), Overlap::Disjoint)
|
||||
|
||||
@@ -37,13 +37,9 @@
|
||||
//! **Accesses** through a wide pointer compute from the fields it carries (no switch: every
|
||||
//! candidate, static or resident, is one code path): the leaf's words at `host + (at & ~3)`, and
|
||||
//! the sink's address, read once in the function's first block. Every such access is bounded
|
||||
//! (robustness does not cover device addresses): the normative check `size ≥ n ∧ at ≤ size − n` in `u64`, the access at `select(inb,
|
||||
//! address, sink)`, and a load's value `select(inb, v, 0)`; an out-of-bounds store lands in the
|
||||
//! write-only sink. An access through root 0 (a null pointer or a resident-set miss) is
|
||||
//! counted: word 4 of the `ExecutionStatus` buffer
|
||||
//! (`StatusWord::ResidentMisses`) is incremented and `StatusBits::RESIDENT_MISS` set, both relaxed
|
||||
//! `Device` atomics, the buffer reached by `PushField::ExecutionStatusAddress` (a function with
|
||||
//! device-address slots carries the status by address). Every static slot a wide access may reach
|
||||
//! (robustness does not cover device addresses): the normative check `size ≥ n ∧ at ≤ size − n` in
|
||||
//! `u64`, the access at `select(inb, address, sink)`, and a load's value `select(inb, v, 0)`; an
|
||||
//! out-of-bounds store lands in the write-only sink. Every static slot a wide access may reach
|
||||
//! becomes `BufferForm::Psb` (`access::finish_slots`), so the binder writes its root entry.
|
||||
//!
|
||||
//! **Under the identity domains** there is no root table: a pointer is the device address of the
|
||||
@@ -51,18 +47,19 @@
|
||||
//! A wide pointer there is its address `a` alone, a `u64` (`DemoteTy::Address`): the `at` of a
|
||||
//! miss's fields `(0, a, 0, 0)`, whose Metal address is `at` and whose accesses are at `host + at`,
|
||||
//! with no field but `at` held, extracted or rebuilt (a GEP is the address's own arithmetic). A
|
||||
//! wide buffer parameter is its slot's address (`SlotGuestBase`, the bias added back). No access through a wide pointer is contained
|
||||
//! or counted: a stored address is used as it is, unchecked, and no resident set exists to miss.
|
||||
//! No root table is read and no `RootTableAddress` pushed. An escaping slot root stays static
|
||||
//! there (`memory::plan`), so a converted or stored slot pointer is `access::pointer`'s.
|
||||
//! wide buffer parameter is its slot's address (`SlotGuestBase`, the bias added back). No access
|
||||
//! through a wide pointer is contained or counted: a stored address is used as it is, unchecked,
|
||||
//! and no resident set exists to miss. No root table is read and no `RootTableAddress` pushed. An
|
||||
//! escaping slot root stays static there (`memory::plan`), so a converted or stored slot pointer is
|
||||
//! `access::pointer`'s.
|
||||
//!
|
||||
//! **Compares.** `icmp` of wide pointers, or of a wide pointer and the null constant, compares
|
||||
//! their Metal addresses: `guest + at` of each pointer's root entry, the null root's fields being
|
||||
//! 0 (so a miss `(0, i, 0, 0)` is address `i`, and null is 0). A compare of a wide
|
||||
//! pointer with a static one is `access::pointer`'s.
|
||||
//!
|
||||
//! **Null constants** (`null`, `undef`, `poison`) are the null root: `(0, 0, 0, 0)` as a `select` side
|
||||
//! or a phi's incoming value.
|
||||
//! **Null constants** (`null`, `undef`, `poison`) are the null root: `(0, 0, 0, 0)` as a `select`
|
||||
//! side or a phi's incoming value.
|
||||
//!
|
||||
//! **Coherent accesses** (`air.{load,store}.{device,system}_coherent`) through a wide pointer are
|
||||
//! the wide leaf access with `NonPrivatePointer` and `MakePointerVisible` (a load) or
|
||||
@@ -96,7 +93,6 @@ use crate::air::ir::{
|
||||
AddrSpace, Align, Call, Callee, CastOp, Inst, InstId, InstKind, IntPredicate, Type, Value,
|
||||
ValueId,
|
||||
};
|
||||
use crate::bind::status::{StatusBits, StatusWord};
|
||||
use crate::budget::Meter;
|
||||
use crate::device::profile::BufferAccess;
|
||||
use crate::device::requirements::VkFeature;
|
||||
@@ -107,20 +103,18 @@ use crate::lower::select::SelectCx;
|
||||
use crate::memory::contain;
|
||||
use crate::memory::leaf::{self, k32, Coherence, Leaf, Path, Units, WordOps};
|
||||
use crate::memory::provenance::{Repr, RootSetId};
|
||||
use crate::memory::roots::{self, k64};
|
||||
use crate::pipeline::facts::RuntimeFact;
|
||||
use crate::memory::roots::k64;
|
||||
use crate::pipeline::sym::{PushField, SlotClass, SlotRef, Stage};
|
||||
use crate::spirv::builder::constructs::{ArmEnd, ArmFn};
|
||||
use crate::spirv::builder::FunctionBuilder;
|
||||
use crate::spirv::error::BResult;
|
||||
use crate::spirv::ids::{DemoteTy, TypeId, Value as SValue};
|
||||
use crate::spirv::ir::{AtomicOp, BinOp, ConvOp, Scope, Semantics, Type as SType};
|
||||
use crate::spirv::ir::{BinOp, ConvOp, Type as SType};
|
||||
|
||||
use super::local::{self, Home, LocalAccess};
|
||||
use super::psb::PsbMem;
|
||||
use super::{
|
||||
is_ptr_ty, not_lowered, operand, refuse, slot_root, static_roots, Access, AccessPlan,
|
||||
BufferReach, IndexForm, SideReach, Target, WideGepTerms,
|
||||
is_ptr_ty, not_lowered, operand, refuse, static_roots, Access, AccessPlan, BufferReach,
|
||||
IndexForm, SideReach, Target, WideGepTerms,
|
||||
};
|
||||
|
||||
/// The access family's dynamic-root plan.
|
||||
@@ -131,13 +125,6 @@ pub struct DynamicPlan {
|
||||
pub slots: BTreeSet<usize>,
|
||||
/// Buffer parameters whose value is a wide pointer.
|
||||
pub params: BTreeSet<u32>,
|
||||
/// The function reads the root table for a wide pointer (a search or a wide access).
|
||||
pub used: bool,
|
||||
/// The resident-set searches of the function (a loaded pointer or `inttoptr` each): the
|
||||
/// module defines the search once when there are several ([`roots::define_resolve`]).
|
||||
pub resolves: u32,
|
||||
/// Accesses through root 0 are counted in the `ExecutionStatus` buffer.
|
||||
pub misses: bool,
|
||||
}
|
||||
|
||||
/// A leaf access through a wide pointer.
|
||||
@@ -245,13 +232,6 @@ pub enum Side {
|
||||
Null,
|
||||
}
|
||||
|
||||
/// 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,
|
||||
/// its two conversions and the root's second addition (48).
|
||||
pub const SEARCH_WORDS: u32 = 3 * 44 + 216 + 2 * 96 + 48;
|
||||
/// SPIR-V words of one use of the search: the root table's address and the call.
|
||||
const CALL_WORDS: u32 = 24;
|
||||
/// SPIR-V words of one wide access before its leaf: the pointer's fields, the check, the sink
|
||||
@@ -376,33 +356,12 @@ fn wide_operand(cx: &SelectCx<'_>, v: Value) -> Result<ValueId, Error> {
|
||||
operand(cx, v)
|
||||
}
|
||||
|
||||
/// The function reads the root table for a wide pointer; under the identity domains, which have
|
||||
/// none, nothing is read.
|
||||
fn use_table(cx: &mut SelectCx<'_>) {
|
||||
if super::identity(cx.profile) {
|
||||
return;
|
||||
}
|
||||
cx.families.access.dynamic.used = true;
|
||||
cx.push.insert(PushField::RootTableAddress);
|
||||
}
|
||||
|
||||
/// Plan one resident-set search of a guest address (a loaded pointer, an `inttoptr` operand, an
|
||||
/// encoder's record address): the function reads the root table and searches it once more. Under
|
||||
/// the identity domains the address is the pointer, with no search.
|
||||
fn plan_resolve(cx: &mut SelectCx<'_>) {
|
||||
if super::identity(cx.profile) {
|
||||
return;
|
||||
}
|
||||
use_table(cx);
|
||||
cx.families.access.dynamic.resolves += 1;
|
||||
}
|
||||
|
||||
/// Plan a read of wide pointer `v`'s root entry: its static slots go through the root table, so
|
||||
/// the binder writes their entries. The slots are its root set's (`root_sets::SetFacts`), each
|
||||
/// with a window; a root that is neither null, dynamic, nor an accessed buffer slot (the constant
|
||||
/// blob, an arena, a slot the function never accesses and therefore has no root entry for) is
|
||||
/// refused. A set's slots join the plan's once, at its first such read. Under the identity domains
|
||||
/// the pointer carries its address, and no entry is read ([`use_table`]).
|
||||
/// the pointer carries its address, and no entry is read.
|
||||
pub(super) fn plan_entry(cx: &mut SelectCx<'_>, v: Value) -> Result<ValueId, Error> {
|
||||
require_addresses(cx)?;
|
||||
let roots = wide(cx, v).ok_or_else(|| refuse(AccessCause::PointerForm))?;
|
||||
@@ -421,41 +380,18 @@ pub(super) fn plan_entry(cx: &mut SelectCx<'_>, v: Value) -> Result<ValueId, Err
|
||||
.extend(slots.iter().copied());
|
||||
set.merged = true;
|
||||
}
|
||||
use_table(cx);
|
||||
operand(cx, v)
|
||||
}
|
||||
|
||||
/// Plan a dereference of wide pointer `v` ([`plan_entry`]); under isolation an access through
|
||||
/// root 0 is counted, which needs the stage's store feature for the counter's atomics.
|
||||
/// Plan a dereference of wide pointer `v` ([`plan_entry`]): the pointer is the address it holds,
|
||||
/// used as it is, unchecked and uncounted.
|
||||
pub(super) fn plan_deref(cx: &mut SelectCx<'_>, v: Value) -> Result<ValueId, Error> {
|
||||
plan_entry(cx, v)?;
|
||||
plan_misses(cx)?;
|
||||
operand(cx, v)
|
||||
}
|
||||
|
||||
/// Plan the counting of an access through root 0, which needs the stage's store
|
||||
/// feature for the counter's atomics. The identity domains have no resident set to miss: every
|
||||
/// wide pointer there is root 0, and nothing is counted.
|
||||
fn plan_misses(cx: &mut SelectCx<'_>) -> Result<(), Error> {
|
||||
if !super::identity(cx.profile) {
|
||||
let enabled = &cx.profile.fields().enabled.features;
|
||||
if let Some(f) = stage_stores(cx.stage).find(|f| !enabled.contains(f)) {
|
||||
return Err(Unsupported::needs(
|
||||
Feature::DereferenceLoadedPointer,
|
||||
Capability::Feature(f),
|
||||
)
|
||||
.into());
|
||||
}
|
||||
cx.families.access.dynamic.misses = true;
|
||||
cx.push.insert(PushField::ExecutionStatusAddress);
|
||||
cx.facts.insert(RuntimeFact::ExecutionStatus);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The feature the `ExecutionStatus` counter's atomics, and any other store of the product's
|
||||
/// (a vertex function's capture records), need in `stage` besides what any module needs: stage
|
||||
/// stores and atomics outside compute.
|
||||
/// The feature the product's own stores (a vertex function's capture records) need in `stage`
|
||||
/// besides what any module needs: stage stores and atomics outside compute.
|
||||
pub(crate) fn stage_stores(stage: Stage) -> impl Iterator<Item = VkFeature> {
|
||||
match stage {
|
||||
Stage::Vertex => Some(VkFeature::VertexPipelineStoresAndAtomics),
|
||||
@@ -477,20 +413,7 @@ pub fn lowered_pointer(cx: &SelectCx<'_>, v: Value) -> Result<Option<DemoteTy>,
|
||||
if super::phis::incoming(cx, v)?.is_some_and(|i| i.not_wide) {
|
||||
return Err(refuse(AccessCause::PointerJoin));
|
||||
}
|
||||
Ok(Some(match super::identity(cx.profile) {
|
||||
true => DemoteTy::Address,
|
||||
false => DemoteTy::FatPtr { wide: true },
|
||||
}))
|
||||
}
|
||||
|
||||
/// The SPIR-V type of a wide pointer off the identity domains: `u64vec4(root, at, host, size)`.
|
||||
/// Under them a wide pointer is its device address, a `u64` ([`DemoteTy::Address`]).
|
||||
pub fn wide_type(mb: &mut crate::spirv::builder::ModuleBuilder) -> BResult<TypeId> {
|
||||
let u = mb.ty(SType::Int {
|
||||
width: 64,
|
||||
signed: false,
|
||||
})?;
|
||||
mb.ty(SType::Vector { elem: u, len: 4 })
|
||||
Ok(Some(DemoteTy::Address))
|
||||
}
|
||||
|
||||
/// Whether buffer parameter `b`'s value is a wide pointer.
|
||||
@@ -498,14 +421,12 @@ pub fn is_wide_param(cx: &SelectCx<'_>, b: &ParamBinding) -> bool {
|
||||
wide(cx, Value::Arg(crate::air::ir::ArgIdx::new(b.param))).is_some()
|
||||
}
|
||||
|
||||
/// Plan a buffer parameter whose value is a wide pointer: under the identity domains its slot's
|
||||
/// address is read from its `SlotGuestBase`.
|
||||
/// Plan a buffer parameter whose value is a wide pointer: its slot's address is read from its
|
||||
/// `SlotGuestBase`.
|
||||
pub fn select_param(cx: &mut SelectCx<'_>, b: &ParamBinding) -> Result<(), Error> {
|
||||
require_addresses(cx)?;
|
||||
if super::identity(cx.profile) {
|
||||
let slot = param_slot(cx.entry, b).ok_or_else(|| refuse(AccessCause::Parameter))?;
|
||||
cx.push.insert(PushField::SlotGuestBase(slot));
|
||||
}
|
||||
let slot = param_slot(cx.entry, b).ok_or_else(|| refuse(AccessCause::Parameter))?;
|
||||
cx.push.insert(PushField::SlotGuestBase(slot));
|
||||
cx.families.access.dynamic.params.insert(b.param);
|
||||
Ok(())
|
||||
}
|
||||
@@ -541,51 +462,7 @@ pub fn param_value(
|
||||
let Some(slot) = param_slot(cx.entry, b) else {
|
||||
return Err(cx.fail(format!("parameter {} is no buffer slot", b.param)));
|
||||
};
|
||||
if cx.plan.families.access.identity {
|
||||
return super::pointer::slot_address(cx, fb, slot).map(Some);
|
||||
}
|
||||
let root = k64(fb, u64::from(slot_root(slot.index)))?;
|
||||
let table = cx.push_field(fb, PushField::RootTableAddress)?;
|
||||
let at = roots::entry_field(fb, table, root, roots::BIND_OFFSET)?;
|
||||
let host = roots::entry_field(fb, table, root, roots::HOST)?;
|
||||
let size = roots::entry_field(fb, table, root, roots::SIZE)?;
|
||||
Ok(Some(fat(fb, [root, at, host, size])?))
|
||||
}
|
||||
|
||||
/// The work before the body (the entry hook): at entry, in a block that dominates every block of
|
||||
/// the body (the function's first, or the merge of a merged vertex's search, which
|
||||
/// `stage_io::emit_draw_entry` emits before it, as the slot table it reads is its command's), read
|
||||
/// the sink's address and each wide buffer parameter's root entry once, so no access reads the
|
||||
/// root table again. The table is read-only to the dispatch: the binder writes
|
||||
/// it before submission and no lowering stores to it.
|
||||
pub fn emit_entry(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>) -> BResult<()> {
|
||||
let dynamic = &cx.plan.families.access.dynamic;
|
||||
if !dynamic.used {
|
||||
return Ok(());
|
||||
}
|
||||
let params: Vec<u32> = dynamic.params.iter().copied().collect();
|
||||
if cx.plan.families.access.psb_contained {
|
||||
cx.sink_host(fb)?;
|
||||
}
|
||||
for p in params {
|
||||
let Some(v) = cx
|
||||
.plan
|
||||
.values
|
||||
.id(crate::air::ir::Value::Arg(crate::air::ir::ArgIdx::new(p)))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let x = cx.operand(fb, v)?;
|
||||
cx.hold(v, x);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The sink's address (`host` of the sink's root entry), read in the open block.
|
||||
pub(crate) fn read_sink_host(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>) -> BResult<SValue> {
|
||||
let table = cx.push_field(fb, PushField::RootTableAddress)?;
|
||||
let sink = k64(fb, roots::SINK_ROOT)?;
|
||||
roots::entry_field(fb, table, sink, roots::HOST)
|
||||
super::pointer::slot_address(cx, fb, slot).map(Some)
|
||||
}
|
||||
|
||||
/// The 8-byte leaf of a stored pointer (its guest address, a `u64`).
|
||||
@@ -740,7 +617,6 @@ pub fn select(
|
||||
) {
|
||||
return Err(refuse(AccessCause::PointerInteger));
|
||||
}
|
||||
plan_resolve(cx);
|
||||
DynStrategy::FromInt {
|
||||
of: operand(cx, *v)?,
|
||||
}
|
||||
@@ -754,7 +630,6 @@ pub fn select(
|
||||
} if result_wide => {
|
||||
require_addresses(cx)?;
|
||||
let leaf = pointer_leaf(cx, inst.ty, *align)?;
|
||||
plan_resolve(cx);
|
||||
let source = match cx.memory.repr(*ptr) {
|
||||
Some(Repr::BufPtr { wide: false, .. }) => {
|
||||
Source::Static(static_access(cx, *ptr, leaf, false, m)?)
|
||||
@@ -1066,34 +941,17 @@ fn index_u64(fb: &mut FunctionBuilder<'_>, x: SValue, form: IndexForm) -> BResul
|
||||
}
|
||||
}
|
||||
|
||||
/// The wide pointer `[root, at, host, size]`.
|
||||
fn fat(fb: &mut FunctionBuilder<'_>, parts: [SValue; 4]) -> BResult<SValue> {
|
||||
let ty = wide_type(fb.module())?;
|
||||
fb.composite_construct(ty, &parts)
|
||||
/// The wide pointer of fields `parts` (`[root, at, host, size]`): a pointer has no root entry
|
||||
/// (every field but `at` is 0), so it is the address `at` alone.
|
||||
fn wide_of(parts: [SValue; 4]) -> SValue {
|
||||
parts[1]
|
||||
}
|
||||
|
||||
/// The wide pointer of fields `parts` (`[root, at, host, size]`): under the identity domains, whose
|
||||
/// pointers have no root entry (every field but `at` is 0), the address `at` alone.
|
||||
fn wide_of(cx: &EmitCx<'_>, fb: &mut FunctionBuilder<'_>, parts: [SValue; 4]) -> BResult<SValue> {
|
||||
match cx.plan.families.access.identity {
|
||||
true => Ok(parts[1]),
|
||||
false => fat(fb, parts),
|
||||
}
|
||||
}
|
||||
|
||||
/// The fields of wide pointer value `p`: `[root, at, host, size]`; under the identity domains
|
||||
/// `[0, p, 0, 0]`, the constant zeros folding where they are used ([`add64`]).
|
||||
fn fields(cx: &EmitCx<'_>, fb: &mut FunctionBuilder<'_>, p: SValue) -> BResult<[SValue; 4]> {
|
||||
if cx.plan.families.access.identity {
|
||||
let zero = k64(fb, 0)?;
|
||||
return Ok([zero, p, zero, zero]);
|
||||
}
|
||||
Ok([
|
||||
fb.composite_extract(p, &[0])?,
|
||||
fb.composite_extract(p, &[1])?,
|
||||
fb.composite_extract(p, &[2])?,
|
||||
fb.composite_extract(p, &[3])?,
|
||||
])
|
||||
/// The fields of wide pointer value `p`, the address it holds: `[0, p, 0, 0]`, the constant zeros
|
||||
/// folding where they are used ([`add64`]).
|
||||
fn fields(fb: &mut FunctionBuilder<'_>, p: SValue) -> BResult<[SValue; 4]> {
|
||||
let zero = k64(fb, 0)?;
|
||||
Ok([zero, p, zero, zero])
|
||||
}
|
||||
|
||||
/// `a + b` in `u64`: the other operand where one is the constant 0 (the `host` of an identity
|
||||
@@ -1108,49 +966,6 @@ fn add64(fb: &mut FunctionBuilder<'_>, a: SValue, b: SValue) -> BResult<SValue>
|
||||
fb.binary(BinOp::IAdd, a, b)
|
||||
}
|
||||
|
||||
/// Count an access through root 0 when `live` holds (always without it): `ResidentMisses += 1`,
|
||||
/// `RESIDENT_MISS` set.
|
||||
fn count_miss(
|
||||
cx: &mut EmitCx<'_>,
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
root: SValue,
|
||||
live: Option<SValue>,
|
||||
) -> BResult<()> {
|
||||
let status = cx.push_field(fb, PushField::ExecutionStatusAddress)?;
|
||||
let null = k64(fb, roots::NULL_ROOT)?;
|
||||
let miss = fb.binary(BinOp::IEqual, root, null)?;
|
||||
let miss = match live {
|
||||
Some(l) => fb.binary(BinOp::LogicalAnd, miss, l)?,
|
||||
None => miss,
|
||||
};
|
||||
let then: ArmFn<'_, ()> = Box::new(move |fb, _| {
|
||||
let u32_ = fb.module().ty(SType::Int {
|
||||
width: 32,
|
||||
signed: false,
|
||||
})?;
|
||||
let word = |fb: &mut FunctionBuilder<'_>, w: StatusWord| -> BResult<SValue> {
|
||||
let off = k64(fb, u64::from(w.byte_offset()))?;
|
||||
let a = fb.binary(BinOp::IAdd, status, off)?;
|
||||
fb.device_place(a, u32_)
|
||||
};
|
||||
let count = word(fb, StatusWord::ResidentMisses)?;
|
||||
let one = k32(fb, 1)?;
|
||||
fb.atomic(
|
||||
AtomicOp::IAdd,
|
||||
count,
|
||||
Scope::Device,
|
||||
Semantics::RELAXED,
|
||||
one,
|
||||
)?;
|
||||
let bits = word(fb, StatusWord::Status)?;
|
||||
let bit = k32(fb, StatusBits::RESIDENT_MISS.0)?;
|
||||
fb.atomic(AtomicOp::Or, bits, Scope::Device, Semantics::RELAXED, bit)?;
|
||||
Ok(ArmEnd::FallThrough(Vec::new()))
|
||||
});
|
||||
fb.if_(&mut (), miss, then, None)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The access `a` through its wide pointer: the loaded value, or the stored value's store.
|
||||
pub(super) fn wide_access(
|
||||
cx: &mut EmitCx<'_>,
|
||||
@@ -1159,7 +974,7 @@ pub(super) fn wide_access(
|
||||
stored: Option<SValue>,
|
||||
) -> BResult<Option<SValue>> {
|
||||
let p = cx.operand(fb, a.ptr)?;
|
||||
let b = wide_base(cx, fb, p, a, None)?;
|
||||
let b = wide_base(cx, fb, p, a)?;
|
||||
wide_at(fb, b, None, &a.leaf, stored)
|
||||
}
|
||||
|
||||
@@ -1179,17 +994,15 @@ pub struct WideBase {
|
||||
units: Units,
|
||||
}
|
||||
|
||||
/// Resolve wide pointer value `p` (a `u64vec4`, or an identity `u64`) for the accesses of `a`: with its coherence (a
|
||||
/// `*_coherent` access's, or the function's own) and volatility. Under isolation an access
|
||||
/// through root 0 is counted here, once, when `live` holds (always without it).
|
||||
/// Resolve wide pointer value `p` (a `u64vec4`, or an identity `u64`) for the accesses of `a`: with
|
||||
/// its coherence (a `*_coherent` access's, or the function's own) and volatility.
|
||||
pub(super) fn wide_base(
|
||||
cx: &mut EmitCx<'_>,
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
p: SValue,
|
||||
a: &WideAccess,
|
||||
live: Option<SValue>,
|
||||
) -> BResult<WideBase> {
|
||||
base_with(cx, fb, p, (a.coherence, a.volatile), live)
|
||||
base_with(cx, fb, p, (a.coherence, a.volatile))
|
||||
}
|
||||
|
||||
/// [`wide_base`] with the coherence (`None`: the function's own) and volatility `ops`.
|
||||
@@ -1198,21 +1011,12 @@ fn base_with(
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
p: SValue,
|
||||
ops: (Option<Coherence>, bool),
|
||||
live: Option<SValue>,
|
||||
) -> BResult<WideBase> {
|
||||
let [root, at, host, size] = fields(cx, fb, p)?;
|
||||
if cx.plan.families.access.dynamic.misses {
|
||||
count_miss(cx, fb, root, live)?;
|
||||
}
|
||||
let bounds = if cx.plan.families.access.psb_contained {
|
||||
Some((size, cx.sink_host(fb)?))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let [_, at, host, _] = fields(fb, p)?;
|
||||
Ok(WideBase {
|
||||
host,
|
||||
at,
|
||||
bounds,
|
||||
bounds: None,
|
||||
units: cx.plan.families.access.psb_units,
|
||||
ops: WordOps {
|
||||
coherence: ops
|
||||
@@ -1291,10 +1095,7 @@ pub(super) fn atomic_address(
|
||||
n: u32,
|
||||
) -> BResult<AtomicAddress> {
|
||||
let p = cx.operand(fb, ptr)?;
|
||||
let [root, at, host, size] = fields(cx, fb, p)?;
|
||||
if cx.plan.families.access.dynamic.misses {
|
||||
count_miss(cx, fb, root, None)?;
|
||||
}
|
||||
let [_, at, host, _] = fields(fb, p)?;
|
||||
let word = u64::from(n.max(4));
|
||||
let mask = k64(fb, !(word - 1))?;
|
||||
let aligned = fb.binary(BinOp::BitwiseAnd, at, mask)?;
|
||||
@@ -1310,20 +1111,10 @@ pub(super) fn atomic_address(
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if !cx.plan.families.access.psb_contained {
|
||||
return Ok(AtomicAddress {
|
||||
addr,
|
||||
byte,
|
||||
inb: None,
|
||||
});
|
||||
}
|
||||
let inb = contain::in_bounds(fb, at, size, u64::from(n))?;
|
||||
let sink = cx.sink_host(fb)?;
|
||||
let addr = fb.select(inb, addr, sink)?;
|
||||
Ok(AtomicAddress {
|
||||
addr,
|
||||
byte,
|
||||
inb: Some(inb),
|
||||
inb: None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1364,36 +1155,19 @@ fn wide_side(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, side: Side) -> B
|
||||
Side::Ptr(p) => cx.operand(fb, p),
|
||||
Side::Null => {
|
||||
let zero = k64(fb, 0)?;
|
||||
wide_of(cx, fb, [zero; 4])
|
||||
Ok(wide_of([zero; 4]))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The Metal address of wide pointer `side` ([`guest_address`]; 0 for the null constant).
|
||||
/// The Metal address of wide pointer `side`, the address it holds (0 for the null constant).
|
||||
fn metal_address(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, side: Side) -> BResult<SValue> {
|
||||
let p = match side {
|
||||
Side::Null => return k64(fb, 0),
|
||||
Side::Ptr(p) => cx.operand(fb, p)?,
|
||||
};
|
||||
guest_address(cx, fb, p)
|
||||
}
|
||||
|
||||
/// The Metal (guest) address of wide pointer value `p` (a `u64vec4`): `guest + at` of its root
|
||||
/// entry (the null root's fields are 0, so a miss `[0, i, 0, 0]` is `i`). Under the identity
|
||||
/// domains, which have no root table, it is the pointer itself.
|
||||
pub(super) fn guest_address(
|
||||
cx: &mut EmitCx<'_>,
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
p: SValue,
|
||||
) -> BResult<SValue> {
|
||||
if cx.plan.families.access.identity {
|
||||
return Ok(p);
|
||||
}
|
||||
let root = fb.composite_extract(p, &[0])?;
|
||||
let at = fb.composite_extract(p, &[1])?;
|
||||
let table = cx.push_field(fb, PushField::RootTableAddress)?;
|
||||
let guest = roots::entry_field(fb, table, root, roots::GUEST)?;
|
||||
fb.binary(BinOp::IAdd, guest, at)
|
||||
// A wide pointer is the address it holds.
|
||||
Ok(p)
|
||||
}
|
||||
|
||||
/// The Metal (guest) address of static-root fat pointer `fat` whose candidates are `targets`: for
|
||||
@@ -1455,40 +1229,6 @@ pub(super) fn plan_static_guest(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The wide pointer of guest address `guest` (a `u64`): a call of the module's resident-set
|
||||
/// search ([`roots::define_resolve`]), or the search in place when it is the module's only one.
|
||||
/// Under the identity domains the address is the pointer, with no search.
|
||||
fn resolve(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, guest: SValue) -> BResult<SValue> {
|
||||
if cx.plan.families.access.identity {
|
||||
return Ok(guest);
|
||||
}
|
||||
let table = cx.push_field(fb, PushField::RootTableAddress)?;
|
||||
match cx.decl.families.access.resolve {
|
||||
Some(search) => fb
|
||||
.call(search, &[table, guest])?
|
||||
.ok_or_else(|| cx.fail("a resident-set search without a result")),
|
||||
None => {
|
||||
let r = roots::resolve_wide(fb, table, guest)?;
|
||||
fat(fb, r)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the module defines the resident-set search as a function: a function with more than
|
||||
/// one search calls it, one with a single search emits it in place (a function's frame and call
|
||||
/// would only add words).
|
||||
pub fn defines_search(plan: &DynamicPlan) -> bool {
|
||||
plan.resolves > 1
|
||||
}
|
||||
|
||||
/// The module's routines the dynamic strategies use, charged once to the census: the resident-set
|
||||
/// search, `access.dynamic.resolve`, whether called or in place.
|
||||
pub fn routine_words(plan: &DynamicPlan) -> impl Iterator<Item = (&'static str, u64)> {
|
||||
(plan.resolves > 0)
|
||||
.then_some(("access.dynamic.resolve", u64::from(SEARCH_WORDS)))
|
||||
.into_iter()
|
||||
}
|
||||
|
||||
/// Emit dynamic strategy `s`, defining value `vid`.
|
||||
pub fn emit(
|
||||
cx: &mut EmitCx<'_>,
|
||||
@@ -1499,7 +1239,7 @@ pub fn emit(
|
||||
let r = match s {
|
||||
DynStrategy::Gep { base, konst, terms } => {
|
||||
let p = cx.operand(fb, *base)?;
|
||||
let [root, mut off, host, size] = fields(cx, fb, p)?;
|
||||
let [root, mut off, host, size] = fields(fb, p)?;
|
||||
if *konst != 0 {
|
||||
let c = k64(fb, *konst)?;
|
||||
off = fb.binary(BinOp::IAdd, off, c)?;
|
||||
@@ -1513,7 +1253,7 @@ pub fn emit(
|
||||
}
|
||||
off = fb.binary(BinOp::IAdd, off, x)?;
|
||||
}
|
||||
wide_of(cx, fb, [root, off, host, size])?
|
||||
wide_of([root, off, host, size])
|
||||
}
|
||||
DynStrategy::Copy { of } => cx.operand(fb, *of)?,
|
||||
DynStrategy::Select { c, t, f } => {
|
||||
@@ -1523,8 +1263,8 @@ pub fn emit(
|
||||
fb.select(c, t, f)?
|
||||
}
|
||||
DynStrategy::FromInt { of } => {
|
||||
let x = cx.operand(fb, *of)?;
|
||||
resolve(cx, fb, x)?
|
||||
// The address is the pointer, with no search.
|
||||
cx.operand(fb, *of)?
|
||||
}
|
||||
DynStrategy::LoadPointer(Source::Static(a)) => {
|
||||
let p = cx.operand(fb, a.ptr)?;
|
||||
@@ -1532,19 +1272,19 @@ pub fn emit(
|
||||
let Some(guest) = super::emit::access_at(cx, fb, a, p, m, None)? else {
|
||||
return Err(cx.fail("a pointer load without a value"));
|
||||
};
|
||||
resolve(cx, fb, guest)?
|
||||
guest
|
||||
}
|
||||
DynStrategy::LoadPointer(Source::Wide(a)) => {
|
||||
let Some(guest) = wide_access(cx, fb, a, None)? else {
|
||||
return Err(cx.fail("a pointer load without a value"));
|
||||
};
|
||||
resolve(cx, fb, guest)?
|
||||
guest
|
||||
}
|
||||
DynStrategy::LoadPointer(Source::Arena(a)) => {
|
||||
let Some(guest) = local::emit_access(cx, fb, a, None)? else {
|
||||
return Err(cx.fail("a pointer load without a value"));
|
||||
};
|
||||
resolve(cx, fb, guest)?
|
||||
guest
|
||||
}
|
||||
DynStrategy::StorePointer { to, value } => {
|
||||
let guest = metal_address(cx, fb, *value)?;
|
||||
|
||||
@@ -374,27 +374,20 @@ fn prepare_access(
|
||||
};
|
||||
let lowering = cx.plan.families.access.slots.get(t.slot).copied().flatten();
|
||||
let ops = WordOps::of(crate::lower::sync::memory_model::coherence(cx.plan));
|
||||
if let Some(SlotLowering::Psb { start }) = lowering {
|
||||
// Under the identity domains a slot whose address the binder holds to an alignment is
|
||||
// reached from that address as it is (its biased word), a leaf at an offset proven a
|
||||
// multiple of 8 or 16 accessed at that alignment up to the address's; any other from the
|
||||
// word below each access.
|
||||
if let Some(SlotLowering::Psb { .. }) = lowering {
|
||||
// A slot whose address the binder holds to an alignment is reached from that address as
|
||||
// it is (its biased word), a leaf at an offset proven a multiple of 8 or 16 accessed at
|
||||
// that alignment up to the address's; any other from the word below each access.
|
||||
let aligned = cx.plan.families.access.aligned.get(&t.slot).copied();
|
||||
let a = if cx.plan.families.access.identity {
|
||||
match aligned {
|
||||
Some(held) => {
|
||||
let base = super::pointer::direct_base(cx, fb, choice.slot)?;
|
||||
psb::prepare_direct(base, m, held)
|
||||
}
|
||||
None => {
|
||||
let address = super::pointer::slot_address(cx, fb, choice.slot)?;
|
||||
psb::prepare_at(fb, address, m)?
|
||||
}
|
||||
let a = match aligned {
|
||||
Some(held) => {
|
||||
let base = super::pointer::direct_base(cx, fb, choice.slot)?;
|
||||
psb::prepare_direct(base, m, held)
|
||||
}
|
||||
None => {
|
||||
let address = super::pointer::slot_address(cx, fb, choice.slot)?;
|
||||
psb::prepare_at(fb, address, m)?
|
||||
}
|
||||
} else {
|
||||
let table = cx.push_field(fb, PushField::RootTableAddress)?;
|
||||
let contained = cx.plan.families.access.psb_contained;
|
||||
psb::prepare(fb, table, t.root, m, start, n, contained)?
|
||||
};
|
||||
let units = cx.plan.families.access.psb_units;
|
||||
let read_only = cx.plan.families.access.unwritten.contains(&t.slot);
|
||||
|
||||
@@ -79,16 +79,15 @@ use std::collections::BTreeMap;
|
||||
use crate::air::ir::{AddrSpace, CastOp, Inst, InstId, InstKind, Type, Value, ValueId};
|
||||
use crate::budget::{tree_bytes, Meter};
|
||||
use crate::error::{AccessCause, Error, Feature, LowerFamily, Unsupported};
|
||||
use crate::lower::arith::{legal, Form, Held};
|
||||
use crate::lower::arith::{Form, Held};
|
||||
use crate::lower::emit::EmitCx;
|
||||
use crate::lower::select::{DescriptorCounts, Plan, SelectCx};
|
||||
use crate::lower::select::SelectCx;
|
||||
use crate::memory::handles::{self, Candidate, Domain, DomainKind, NULL_HANDLE};
|
||||
use crate::memory::leaf::{k32, Leaf, Path};
|
||||
use crate::memory::provenance::{HandleClass, OffsetRange, Repr};
|
||||
use crate::pipeline::sym::{ResourceKind, ResourceSlot, SyntheticBinding};
|
||||
use crate::spirv::builder::{FunctionBuilder, ModuleBuilder};
|
||||
use crate::spirv::error::BResult;
|
||||
use crate::spirv::ids::{DemoteTy, FuncId, Value as SValue};
|
||||
use crate::spirv::ids::{DemoteTy, Value as SValue};
|
||||
use crate::spirv::ir::BinOp;
|
||||
|
||||
use super::dynamic::WideAccess;
|
||||
@@ -156,24 +155,24 @@ fn id_type(mb: &mut ModuleBuilder) -> BResult<crate::spirv::ids::TypeId> {
|
||||
mb.ty(SType::Vector { elem: u, len: 2 })
|
||||
}
|
||||
|
||||
/// The representation of an argument buffer's sampler handle under the identity domains: its
|
||||
/// resource ID, a `uvec2` ([`emit_identity_sampler`]).
|
||||
/// The representation of an argument buffer's sampler handle: its resource ID, a `uvec2`
|
||||
/// ([`emit_identity_sampler`]).
|
||||
const IDENTITY_SAMPLER_ID: DemoteTy = DemoteTy::Vector {
|
||||
elem: crate::spirv::ids::ScalarTy::Int { bits: 32 },
|
||||
len: 2,
|
||||
};
|
||||
|
||||
/// Whether handle value `v` is an argument buffer's sampler under the identity domains, held as
|
||||
/// its resource ID ([`IDENTITY_SAMPLER_ID`]).
|
||||
/// Whether handle value `v` is an argument buffer's sampler, held as its resource ID
|
||||
/// ([`IDENTITY_SAMPLER_ID`]).
|
||||
fn identity_sampler(cx: &SelectCx<'_>, v: Value) -> bool {
|
||||
super::identity(cx.profile) && handles::heap_handle(cx.memory, v) == Some(HandleClass::Sampler)
|
||||
handles::heap_handle(cx.memory, v) == Some(HandleClass::Sampler)
|
||||
}
|
||||
|
||||
/// The representation of handle word `v` ([`is_word`]): an argument buffer's sampler's resource
|
||||
/// ID under the identity domains ([`IDENTITY_SAMPLER_ID`]), every other word's handle index.
|
||||
/// ID ([`IDENTITY_SAMPLER_ID`]), every other word's handle index.
|
||||
pub fn word_repr(cx: &SelectCx<'_>, v: Value) -> DemoteTy {
|
||||
match member_word(&cx.families.access, v) {
|
||||
Some(HandleClass::Sampler) if super::identity(cx.profile) => IDENTITY_SAMPLER_ID,
|
||||
Some(HandleClass::Sampler) => IDENTITY_SAMPLER_ID,
|
||||
_ => DemoteTy::HandleIndex,
|
||||
}
|
||||
}
|
||||
@@ -303,8 +302,7 @@ impl HandleStrategy {
|
||||
HandleStrategy::Select { .. } => 6,
|
||||
HandleStrategy::Load(Element::Handle(_)) => 4,
|
||||
HandleStrategy::Load(Element::Dynamic { .. }) => 40,
|
||||
// The id's load, its two words, and the call; the search is the module's routine,
|
||||
// counted once ([`routine_words`]).
|
||||
// The id's load, its two words, and their handle's arithmetic.
|
||||
HandleStrategy::Lookup(a) | HandleStrategy::SamplerLookup(a) => {
|
||||
LOOKUP_CALL_WORDS.saturating_add(a.words())
|
||||
}
|
||||
@@ -1097,8 +1095,10 @@ enum Table {
|
||||
}
|
||||
|
||||
/// The resource-id load of a heap texture or sampler handle through buffer pointer `ptr` (the
|
||||
/// argument buffer's member): two words, contained like any leaf access of the slot. The function
|
||||
/// then reads the handle table or the sampler table (`table`), one more storage descriptor.
|
||||
/// argument buffer's member, a texture's or a sampler's by `table`): two words, contained like any
|
||||
/// leaf access of the slot. A texture's or a sampler's resource ID is its handle: its index is the
|
||||
/// element of the set-1 arrays (`emit_identity_handle`, `emit_identity_sampler`), and no table is
|
||||
/// searched.
|
||||
fn lookup(
|
||||
cx: &mut SelectCx<'_>,
|
||||
ptr: Value,
|
||||
@@ -1147,110 +1147,21 @@ fn lookup(
|
||||
)?)
|
||||
}
|
||||
};
|
||||
// Under the identity domains a texture's or a sampler's resource ID is its handle: its index
|
||||
// is the element of the set-1 arrays (`emit_identity_handle`, `emit_identity_sampler`), and no
|
||||
// table is searched.
|
||||
if super::identity(cx.profile) {
|
||||
return Ok(access);
|
||||
}
|
||||
let ids = if legal::holds_wide(cx.profile) {
|
||||
HandleIds::Words
|
||||
} else {
|
||||
HandleIds::U64
|
||||
};
|
||||
let planned = match table {
|
||||
Table::Handles => &mut cx.families.access.handle_table,
|
||||
Table::Samplers => &mut cx.families.access.sampler_table,
|
||||
};
|
||||
if planned.is_none() {
|
||||
*planned = Some(ids);
|
||||
cx.descriptors = cx.descriptors.plus(&DescriptorCounts {
|
||||
storage_buffers: 1,
|
||||
..DescriptorCounts::default()
|
||||
});
|
||||
}
|
||||
Ok(access)
|
||||
}
|
||||
|
||||
/// The words of a heap handle load besides its id's access: the id's two words and the search's
|
||||
/// call (`OpCompositeExtract` of 5 words each, `OpFunctionCall` of 6).
|
||||
/// The words of a heap handle load besides its id's access: the id's two words and their
|
||||
/// handle's arithmetic (`OpCompositeExtract` of 5 words each, and the rest's).
|
||||
const LOOKUP_CALL_WORDS: u32 = 24;
|
||||
|
||||
/// The words of the handle-table and sampler-table searches a function's heap handle loads call,
|
||||
/// with the census name of the strategy that calls each: counted once per module, not per load.
|
||||
pub fn routine_words(plan: &AccessPlan) -> impl Iterator<Item = (&'static str, u64)> {
|
||||
let form = plan.lookup();
|
||||
let handles = plan.handle_table.map(move |ids| {
|
||||
let words = handles::lookup_routine_words(ids == HandleIds::U64, form);
|
||||
("access.handle.lookup", u64::from(words))
|
||||
});
|
||||
let samplers = plan.sampler_table.map(|ids| {
|
||||
let words = handles::lookup_routine_words(ids == HandleIds::U64, handles::Lookup::Entry);
|
||||
("access.handle.sampler_lookup", u64::from(words))
|
||||
});
|
||||
handles.into_iter().chain(samplers)
|
||||
}
|
||||
|
||||
/// How the handle-table search reads an entry's resource id: as one `u64` on a profile with
|
||||
/// `shaderInt64` (the table declared as an entry array), else as two words.
|
||||
/// How a function-table directory search reads an entry's resource id: as one `u64` on a profile
|
||||
/// with `shaderInt64`, else as two words.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum HandleIds {
|
||||
U64,
|
||||
Words,
|
||||
}
|
||||
|
||||
/// The stage's handle table and the module's search of it.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct HandleTable {
|
||||
/// `fn(lo: u32, hi: u32) -> u32`, the heap handle of a resource id
|
||||
/// ([`handles::define_lookup`]): its element, with the entry's flags the plan's search carries;
|
||||
/// for the sampler table, the index of its entry.
|
||||
pub lookup: FuncId,
|
||||
/// The table, whose entries a sampler handle's uses read ([`handles::entry_field`]).
|
||||
pub table: handles::Table,
|
||||
}
|
||||
|
||||
/// The binding symbol of the handle table of `stage`.
|
||||
pub fn table_symbol(stage: crate::pipeline::sym::Stage) -> ResourceSlot {
|
||||
ResourceSlot {
|
||||
stage,
|
||||
kind: ResourceKind::Synthetic(SyntheticBinding::HandleTable),
|
||||
index: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// The binding symbol of the sampler table of `stage`.
|
||||
pub fn sampler_table_symbol(stage: crate::pipeline::sym::Stage) -> ResourceSlot {
|
||||
ResourceSlot {
|
||||
stage,
|
||||
kind: ResourceKind::Synthetic(SyntheticBinding::SamplerTable),
|
||||
index: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Declare the stage's handle table (an entry array, or a word view on a profile without
|
||||
/// `shaderInt64`) and the module's search of it, when the plan reads it.
|
||||
pub fn declare_table(mb: &mut ModuleBuilder, plan: &Plan) -> BResult<Option<HandleTable>> {
|
||||
let Some(ids) = plan.families.access.handle_table else {
|
||||
return Ok(None);
|
||||
};
|
||||
let table = handles::declare_table(mb, table_symbol(plan.stage), ids == HandleIds::U64)?;
|
||||
let lookup = handles::define_lookup(mb, table, plan.families.access.lookup())?;
|
||||
Ok(Some(HandleTable { lookup, table }))
|
||||
}
|
||||
|
||||
/// Declare the stage's sampler table and the module's search of it in its entry form, when the
|
||||
/// plan reads it.
|
||||
pub fn declare_sampler_table(mb: &mut ModuleBuilder, plan: &Plan) -> BResult<Option<HandleTable>> {
|
||||
let Some(ids) = plan.families.access.sampler_table else {
|
||||
return Ok(None);
|
||||
};
|
||||
let sym = sampler_table_symbol(plan.stage);
|
||||
let table = handles::declare_table(mb, sym, ids == HandleIds::U64)?;
|
||||
let lookup = handles::define_lookup(mb, table, handles::Lookup::Entry)?;
|
||||
Ok(Some(HandleTable { lookup, table }))
|
||||
}
|
||||
|
||||
/// Emit handle strategy `s`, defining value `vid`.
|
||||
pub fn emit(
|
||||
cx: &mut EmitCx<'_>,
|
||||
@@ -1305,7 +1216,6 @@ pub fn emit(
|
||||
fb.binary(BinOp::IAdd, base, delta)?
|
||||
}
|
||||
HandleStrategy::Lookup(a) | HandleStrategy::SamplerLookup(a) => {
|
||||
let identity = cx.plan.families.access.identity;
|
||||
let id = match a.as_ref() {
|
||||
IdLoad::Static(a) => {
|
||||
let p = cx.operand(fb, a.ptr)?;
|
||||
@@ -1317,33 +1227,17 @@ pub fn emit(
|
||||
let Some(id) = id else {
|
||||
return Err(cx.fail("a resource-id load without a value"));
|
||||
};
|
||||
match s {
|
||||
HandleStrategy::SamplerLookup(_) if identity => {
|
||||
return emit_identity_sampler(cx, fb, vid, id);
|
||||
}
|
||||
_ if identity => return emit_identity_handle(cx, fb, vid, id),
|
||||
_ => {}
|
||||
}
|
||||
let table = match s {
|
||||
HandleStrategy::SamplerLookup(_) => cx.decl.families.access.sampler_table,
|
||||
_ => cx.decl.families.access.handle_table,
|
||||
return match s {
|
||||
HandleStrategy::SamplerLookup(_) => emit_identity_sampler(cx, fb, vid, id),
|
||||
_ => emit_identity_handle(cx, fb, vid, id),
|
||||
};
|
||||
let Some(table) = table else {
|
||||
return Err(cx.fail("a handle lookup without its table"));
|
||||
};
|
||||
let lo = fb.composite_extract(id, &[0])?;
|
||||
let hi = fb.composite_extract(id, &[1])?;
|
||||
match fb.call(table.lookup, &[lo, hi])? {
|
||||
Some(element) => element,
|
||||
None => return Err(cx.fail("a handle lookup without a result")),
|
||||
}
|
||||
}
|
||||
};
|
||||
cx.define(vid, r);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Under the identity domains, the handle of a texture whose resource ID `id` (`uvec2`, low word
|
||||
/// The handle of a texture whose resource ID `id` (`uvec2`, low word
|
||||
/// first) an argument buffer holds (`docs/RESOURCE-ID.md`), defining `vid`: the id's index masked
|
||||
/// below the set-1 image arrays' length (`pipeline::link::IDENTITY_TEXTURES`, a power of two), the
|
||||
/// element of those arrays (0, nil, the null descriptor), with the word's missing-alpha bit
|
||||
@@ -1402,7 +1296,7 @@ fn emit_identity_handle(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Under the identity domains, the handle of a sampler whose resource ID `id` (`uvec2`, low word
|
||||
/// The handle of a sampler whose resource ID `id` (`uvec2`, low word
|
||||
/// first) an argument buffer holds (`docs/RESOURCE-ID.md`), defining `vid`: the ID itself, its index
|
||||
/// replaced by 0 (the default sampler) where it is not below the set-1 sampler arrays' length
|
||||
/// (`pipeline::link::IDENTITY_SAMPLERS`), and its word as the program wrote it. The program writes
|
||||
|
||||
@@ -237,12 +237,9 @@ fn needs(cx: &SelectCx<'_>) -> Result<(), Error> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Select the strategy of `inst` under the identity domains: an indirect-command operation's
|
||||
/// writes, or its refusal; `None` for any other instruction, or on another profile.
|
||||
/// Select the strategy of `inst`: an indirect-command operation's writes, or its refusal; `None`
|
||||
/// for any other instruction.
|
||||
pub fn select(cx: &mut SelectCx<'_>, inst: &Inst, m: &mut Meter) -> Result<Option<Command>, Error> {
|
||||
if !super::identity(cx.profile) {
|
||||
return Ok(None);
|
||||
}
|
||||
let InstKind::Call(call) = &inst.kind else {
|
||||
return Ok(None);
|
||||
};
|
||||
@@ -393,8 +390,8 @@ fn emit_address(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, a: &Address)
|
||||
match a {
|
||||
Address::Null => k64(fb, 0),
|
||||
Address::Wide(p) => {
|
||||
let p = cx.operand(fb, *p)?;
|
||||
dynamic::guest_address(cx, fb, p)
|
||||
// A wide pointer is the address it holds.
|
||||
cx.operand(fb, *p)
|
||||
}
|
||||
Address::Static { ptr, targets } => {
|
||||
let fat = cx.operand(fb, *ptr)?;
|
||||
|
||||
@@ -22,14 +22,13 @@
|
||||
//! ([`quad`]): one 16-byte store where each invocation finds their address a multiple of 16 and the
|
||||
//! 16 bytes inside the slot, else the four.
|
||||
//!
|
||||
//! **Slots** ([`finish_slots`]). An accessed slot is a storage view. A storage slot whose range is
|
||||
//! not provably within `maxStorageBufferRange` declares `RuntimeFact::BufferRangeLimit`. On
|
||||
//! Profile A a `BufferRangeLimit` variant (`LowerInputs.psb_slots`) and the per-stage
|
||||
//! descriptor-limit fallback move storage slots to their device addresses (`BufferForm::Psb`, the PSB leaf of `psb`, reached through the root
|
||||
//! table), which declare `RuntimeFact::DeviceAddresses`. The pulled vertex fetch's source buffers
|
||||
//! are slots under the same rules ([`pulled`]): one sharing a read-only buffer argument's Metal
|
||||
//! index is that argument's slot, widened to a `Whole` storage slot; any other is a read-only
|
||||
//! `Whole` storage slot of its own.
|
||||
//! **Slots** ([`finish_slots`]). A kernel's slot that its device binds
|
||||
//! (`DeviceProfile::binds_kernel_buffers`) and that only its own typed accesses reach is a storage
|
||||
//! view of set 0 at its pushed bind offset; every other slot is read at its device address
|
||||
//! (`BufferForm::Psb`, the PSB leaf of `psb`), and declares `RuntimeFact::DeviceAddresses`. The
|
||||
//! pulled vertex fetch's source buffers are slots under the same rules ([`pulled`]): one sharing a
|
||||
//! read-only buffer argument's Metal index is that argument's slot, widened to a `Whole` storage
|
||||
//! slot; any other is a read-only `Whole` storage slot of its own.
|
||||
//!
|
||||
//! **Census names**. A slot's form is decided after its accesses are selected, so a strategy's
|
||||
//! census name reads the finished plan ([`AccessPlan::check`], [`BufferReach`]): an access that
|
||||
@@ -122,12 +121,9 @@ use std::collections::{BTreeMap, BTreeSet};
|
||||
use crate::air::abi::{AbiInt, ParamBinding, ParamRole};
|
||||
use crate::air::ir::{AddrSpace, CastOp, Const, Inst, InstId, InstKind, Type, Value, ValueId};
|
||||
use crate::budget::Meter;
|
||||
use crate::device::profile::{BufferAccess, Limits};
|
||||
use crate::device::requirements::VkLimit;
|
||||
use crate::device::profile::BufferAccess;
|
||||
use crate::device::DeviceProfile;
|
||||
use crate::error::{
|
||||
AccessCause, Capability, Error, Feature, ImageblockCause, LowerFamily, Unsupported,
|
||||
};
|
||||
use crate::error::{AccessCause, Error, Feature, ImageblockCause, LowerFamily, Unsupported};
|
||||
use crate::lower::emit::EmitCx;
|
||||
use crate::lower::select::{DescriptorCounts, FamilyPlans, Plan, SelectCx, SlotChoice};
|
||||
use crate::lower::strategy::FamilyStrategy;
|
||||
@@ -472,12 +468,13 @@ impl AccessPlan {
|
||||
)
|
||||
}
|
||||
|
||||
/// The containment check target `t` takes as emitted (`emit::prepare`): the in-shader check,
|
||||
/// unless it is a device-address slot and containment is off (`psb_contained`).
|
||||
/// The containment check target `t` takes as emitted (`emit::prepare`): none for a
|
||||
/// device-address slot, whose accesses are checked against its pushed length where they may
|
||||
/// reach another offset ([`AccessPlan::variable`]), else the in-shader check.
|
||||
pub fn check(&self, t: &Target) -> Check {
|
||||
match (self.by_address(t), self.psb_contained) {
|
||||
(true, false) => Check::None,
|
||||
_ => Check::InShader,
|
||||
match self.by_address(t) {
|
||||
true => Check::None,
|
||||
false => Check::InShader,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -656,15 +653,13 @@ pub fn lowered_pointer(cx: &SelectCx<'_>, v: Value) -> Result<DemoteTy, Error> {
|
||||
if let Some(e) = phis::incoming(cx, v)?.and_then(|i| phis::fat_refusal(cx, i)) {
|
||||
return Err(e);
|
||||
}
|
||||
Ok(DemoteTy::FatPtr { wide: false })
|
||||
Ok(DemoteTy::FatPtr)
|
||||
}
|
||||
|
||||
/// The SPIR-V type of a pointer representation `ty`: `uvec2` for a narrow fat pointer, `u32`
|
||||
/// for an arena offset or a handle index, `u64vec4` for a wide fat pointer, `u64` for a device
|
||||
/// address, `None` for the others.
|
||||
/// The SPIR-V type of a pointer representation `ty`: `uvec2` for a fat pointer, `u32` for an arena
|
||||
/// offset or a handle index, `u64` for a device address, `None` for the others.
|
||||
pub fn spirv_type(mb: &mut ModuleBuilder, ty: &DemoteTy) -> BResult<Option<TypeId>> {
|
||||
match ty {
|
||||
DemoteTy::FatPtr { wide: true } => Ok(Some(dynamic::wide_type(mb)?)),
|
||||
DemoteTy::Address => Ok(Some(mb.ty(SType::Int {
|
||||
width: 64,
|
||||
signed: false,
|
||||
@@ -673,7 +668,7 @@ pub fn spirv_type(mb: &mut ModuleBuilder, ty: &DemoteTy) -> BResult<Option<TypeI
|
||||
width: 32,
|
||||
signed: false,
|
||||
})?)),
|
||||
DemoteTy::FatPtr { wide: false } => {
|
||||
DemoteTy::FatPtr => {
|
||||
let u = mb.ty(SType::Int {
|
||||
width: 32,
|
||||
signed: false,
|
||||
@@ -700,16 +695,9 @@ pub enum SlotLowering {
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct AccessPlan {
|
||||
pub slots: Vec<Option<SlotLowering>>,
|
||||
/// Device-address accesses are bounds-checked (robust buffer access does not cover them):
|
||||
/// every profile's but the identity domains', whose slots are checked against their pushed
|
||||
/// lengths instead.
|
||||
pub psb_contained: bool,
|
||||
/// The narrow units device-address accesses load and store directly (`psb::narrow_units` of
|
||||
/// the profile): a sub-word store there is one narrow store instead of two word atomics.
|
||||
pub psb_units: Units,
|
||||
/// The function compiles under the identity domains: a device-address slot's address is its
|
||||
/// own field ([`address_field`]).
|
||||
pub identity: bool,
|
||||
/// Under the identity domains with containment on ([`identity_contained`]), the buffer slots
|
||||
/// an access may reach at a byte offset that is not a translation-time constant
|
||||
/// ([`note_variable`]): each reads its `PushField::SlotBounds`, and each of those accesses
|
||||
@@ -768,14 +756,6 @@ pub struct AccessPlan {
|
||||
pub typed_slots: BTreeSet<usize>,
|
||||
/// The pulled vertex fetch's source buffers, by Metal index ([`pulled`]).
|
||||
pub pulled: Vec<pulled::PulledSlot>,
|
||||
/// Some texture handle is loaded from an argument buffer: the function reads the stage's
|
||||
/// handle table ([`handle`]), one more storage descriptor, and its search reads the ids as
|
||||
/// this.
|
||||
pub handle_table: Option<handle::HandleIds>,
|
||||
/// Some sampler handle is loaded from an argument buffer: the function reads the stage's
|
||||
/// sampler table ([`handle`]), one more storage descriptor, and its search reads the ids as
|
||||
/// this.
|
||||
pub sampler_table: Option<handle::HandleIds>,
|
||||
/// Memory-plan slots whose Metal address (`SlotGuestBase`) a pointer compare reads
|
||||
/// ([`mod@pointer`]): a slot no access bounds gets the window `Whole`, so the binder plans it
|
||||
/// and writes the field.
|
||||
@@ -856,10 +836,6 @@ pub struct AccessPlan {
|
||||
/// The relaxed atomic loads an exit of a loop holding them depends on ([`atomic::spin`]): each
|
||||
/// acquires its memory. Planned before any instruction is selected.
|
||||
pub spins: BTreeSet<InstId>,
|
||||
/// The stage binds the command buffer's `ExecutionStatus` buffer
|
||||
/// (`SyntheticBinding::ExecutionStatus`), one more storage descriptor, on a device that does
|
||||
/// not address buffers, and why ([`absent::StatusBinding`]).
|
||||
pub status_binding: Option<absent::StatusBinding>,
|
||||
}
|
||||
|
||||
impl AccessPlan {
|
||||
@@ -900,40 +876,21 @@ pub struct Declared {
|
||||
pub views: Vec<Option<View>>,
|
||||
/// The arenas.
|
||||
pub local: local::LocalDecl,
|
||||
/// The stage's `ArgumentTable`, when the placement spilled fields there.
|
||||
pub table: Option<table::Table>,
|
||||
/// The constant blob's words, when the function reads the blob.
|
||||
pub blob: Option<crate::memory::blob::BlobDecl>,
|
||||
/// The storage view of each pulled source buffer with a descriptor slot of its own, by Metal
|
||||
/// index ([`pulled`]).
|
||||
pub pulled: Vec<(u32, View)>,
|
||||
/// The stage's handle table and its search, when a texture handle is loaded from an
|
||||
/// argument buffer.
|
||||
pub handle_table: Option<handle::HandleTable>,
|
||||
/// The stage's sampler table and its search, when a sampler handle is loaded from an
|
||||
/// argument buffer.
|
||||
pub sampler_table: Option<handle::HandleTable>,
|
||||
pub blob: Option<crate::memory::blob::ModuleWords>,
|
||||
/// The unit views of each accessed slot, by memory-plan slot index.
|
||||
pub units: Vec<views::UnitViews>,
|
||||
/// The module's resident-set search, when a function searches it more than once
|
||||
/// ([`dynamic`]).
|
||||
pub resolve: Option<crate::spirv::ids::FuncId>,
|
||||
/// A tile function's attachment images and render area ([`tile`]).
|
||||
pub tile: tile::TileDecl,
|
||||
/// The stage's function-table directory and search and its snapshot, when a table is read by
|
||||
/// its resource id.
|
||||
pub function_tables: Option<function_table::FunctionTables>,
|
||||
/// The stage's view of the command buffer's `ExecutionStatus` buffer, where it binds the
|
||||
/// buffer ([`absent::declare`]).
|
||||
pub status: Option<View>,
|
||||
}
|
||||
|
||||
/// The module's routines the access family's strategies call, each charged once to the census: the
|
||||
/// handle-table and function-table-directory searches and the resident-set search.
|
||||
/// function-table-directory search.
|
||||
pub fn routine_words(plan: &AccessPlan) -> impl Iterator<Item = (&'static str, u64)> + '_ {
|
||||
handle::routine_words(plan)
|
||||
.chain(function_table::routine_words(plan.function_tables))
|
||||
.chain(dynamic::routine_words(&plan.dynamic))
|
||||
function_table::routine_words(plan.function_tables)
|
||||
}
|
||||
|
||||
/// Plan a used resource parameter (buffer, argument buffer, threadgroup, indirect constant).
|
||||
@@ -1019,40 +976,20 @@ pub fn param_value(
|
||||
fb.module().const_value(c)
|
||||
}
|
||||
|
||||
/// Whether a storage slot's descriptor range is provably within `maxStorageBufferRange`: a
|
||||
/// `Bounded` window's range is at most `round_up(len + align - 1, 16)`, with `align` the descriptor
|
||||
/// base alignment `max(minStorageBufferOffsetAlignment, 16)`.
|
||||
fn storage_range_fits(window: Window, limits: &Limits) -> bool {
|
||||
match window {
|
||||
Window::Bounded { len, .. } => {
|
||||
let align = views::base_alignment(limits.min_storage_buffer_offset_alignment);
|
||||
views::descriptor_range(len, align)
|
||||
.is_some_and(|r| r <= u64::from(limits.max_storage_buffer_range))
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Choose the form of every accessed slot and of every pulled vertex source buffer, and add their
|
||||
/// descriptors to `cx.descriptors`. Returns the form of each accessed slot, by memory-plan slot
|
||||
/// index (`None` for slots the function does not access).
|
||||
///
|
||||
/// A slot is a storage view unless a `BufferRangeLimit` variant (`LowerInputs.psb_slots`)
|
||||
/// moves it to its device address, or, on Profile A, the per-stage descriptor limits are exceeded:
|
||||
/// then the highest-index storage slots move to device addresses, one at a time, until the
|
||||
/// storage-buffer and resource counts fit (a deterministic per-function choice). Every
|
||||
/// device-address slot declares `DeviceAddresses` and reads the root table
|
||||
/// (`PushField::RootTableAddress`) instead of its bind residual.
|
||||
/// A slot is its device address, read from its own `SlotGuestBase`, and declares
|
||||
/// `DeviceAddresses`; a kernel's slot on a device that binds its buffer arguments
|
||||
/// (`DeviceProfile::binds_kernel_buffers`) is its storage view, unless a wide pointer, a typed
|
||||
/// atomic or the stage-in fetch reaches it or the dispatch binds it below its argument's
|
||||
/// alignment.
|
||||
///
|
||||
/// A pulled source buffer ([`pulled`]) shares the accessed slot of its Metal index, widened to a
|
||||
/// `Whole` storage slot that the fetch reads too (a window outside the first 2³² bytes above the
|
||||
/// bind offset is refused), or is a read-only `Whole` storage slot of its own; either takes part
|
||||
/// in the rules above like any storage slot.
|
||||
///
|
||||
/// Each step of the fallback moves one storage view, so the descriptors and push fields of the
|
||||
/// slots' forms are kept in a census the step updates, and the order of the slots it moves is
|
||||
/// sorted once: the fallback takes one pass over the slots, metered, where it recounted every slot
|
||||
/// per slot moved before. The working tables are charged while they run.
|
||||
/// `Whole` slot that the fetch reads too (a window outside the first 2³² bytes above the bind
|
||||
/// offset is refused), or is a read-only `Whole` slot of its own, its device address. The working
|
||||
/// tables are charged while they run.
|
||||
pub fn finish_slots(
|
||||
cx: &mut SelectCx<'_>,
|
||||
m: &mut Meter,
|
||||
@@ -1064,80 +1001,9 @@ pub fn finish_slots(
|
||||
result
|
||||
}
|
||||
|
||||
/// The ledger bytes `place_slots` works in per memory-plan slot: its form and window, and its
|
||||
/// place in the fallback's order.
|
||||
const SLOT_WORK_BYTES: usize = std::mem::size_of::<Option<SlotLowering>>()
|
||||
+ std::mem::size_of::<Option<Window>>()
|
||||
+ std::mem::size_of::<(u32, Moved)>();
|
||||
|
||||
/// The descriptors and push fields of the slots' forms while [`finish_slots`] moves them: the
|
||||
/// storage views, and the push fields with each device-address slot's `SlotBindOffset` replaced by
|
||||
/// the field its address is read from ([`slot_address_field`]). A move updates it in place.
|
||||
struct Census {
|
||||
storage: u32,
|
||||
fields: BTreeSet<PushField>,
|
||||
/// Under the identity domains the spilled fields are a parameter block at a pushed address.
|
||||
identity: bool,
|
||||
/// A device-address slot reads its own address ([`slot_address_field`]).
|
||||
own_addresses: bool,
|
||||
/// The stage's push base and the device's window bytes, which decide where the fields spill.
|
||||
push_window: (u32, u32),
|
||||
}
|
||||
|
||||
impl Census {
|
||||
/// The census of `forms` over the function's push fields `push`; `dynamic` when a wide
|
||||
/// pointer reads the root table.
|
||||
fn new(
|
||||
push: &BTreeSet<PushField>,
|
||||
(dynamic, identity, own_addresses, push_window): (bool, bool, bool, (u32, u32)),
|
||||
forms: impl Iterator<Item = (SlotRef, SlotLowering)>,
|
||||
m: &mut Meter,
|
||||
) -> Result<Census, Error> {
|
||||
let mut c = Census {
|
||||
storage: 0,
|
||||
fields: push.clone(),
|
||||
identity,
|
||||
own_addresses,
|
||||
push_window,
|
||||
};
|
||||
if dynamic {
|
||||
c.fields.insert(PushField::RootTableAddress);
|
||||
}
|
||||
for (slot, l) in forms {
|
||||
m.tick(1)?;
|
||||
match l {
|
||||
SlotLowering::View => c.storage = c.storage.saturating_add(1),
|
||||
SlotLowering::Psb { .. } => {
|
||||
c.fields.remove(&PushField::SlotBindOffset(slot));
|
||||
c.fields.insert(slot_address_field(own_addresses, slot));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(c)
|
||||
}
|
||||
|
||||
/// The slots' descriptors in `stage`: their views, and the `ArgumentTable` when the push fields
|
||||
/// spill.
|
||||
fn counts(&self, stage: crate::pipeline::sym::Stage) -> DescriptorCounts {
|
||||
DescriptorCounts {
|
||||
// Under the identity domains the spilled fields are a parameter block at a pushed
|
||||
// address, no descriptor.
|
||||
uniform_buffers: u32::from(
|
||||
!self.identity && table::spills(stage, self.push_window, &self.fields),
|
||||
),
|
||||
storage_buffers: self.storage,
|
||||
..DescriptorCounts::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// A storage view of `slot` became its device address.
|
||||
fn addressed(&mut self, slot: SlotRef) {
|
||||
self.storage = self.storage.saturating_sub(1);
|
||||
self.fields.remove(&PushField::SlotBindOffset(slot));
|
||||
self.fields
|
||||
.insert(slot_address_field(self.own_addresses, slot));
|
||||
}
|
||||
}
|
||||
/// The ledger bytes `place_slots` works in per memory-plan slot: its form and window.
|
||||
const SLOT_WORK_BYTES: usize =
|
||||
std::mem::size_of::<Option<SlotLowering>>() + std::mem::size_of::<Option<Window>>();
|
||||
|
||||
/// The push field a device-address slot's address is read from: its own ([`address_field`]) where
|
||||
/// `own`, under the identity domains outside a device-replay variant, else the root table, where a
|
||||
@@ -1166,17 +1032,10 @@ fn address_field(slot: SlotRef) -> PushField {
|
||||
/// a 64-bit add of a constant.
|
||||
pub(crate) const SLOT_ADDRESS_BIAS: u64 = 1 << 31;
|
||||
|
||||
/// Whether profile `p` takes the identity domains, where a pointer is a device address used
|
||||
/// directly.
|
||||
pub(crate) fn identity(p: &DeviceProfile) -> bool {
|
||||
p.fields().pointer_domain == crate::device::PointerDomain::Identity
|
||||
}
|
||||
|
||||
/// Whether a function selected in `cx` bounds its slots' device-address accesses under the
|
||||
/// identity domains: the function is no device-replay variant, whose slots' addresses are its
|
||||
/// replayed command's.
|
||||
/// Whether a function selected in `cx` bounds its slots' device-address accesses: the function is
|
||||
/// no device-replay variant, whose slots' addresses are its replayed command's.
|
||||
pub(crate) fn identity_contained(cx: &SelectCx<'_>) -> bool {
|
||||
identity(cx.profile) && !cx.inputs.replay_bindings
|
||||
!cx.inputs.replay_bindings
|
||||
}
|
||||
|
||||
/// An access of buffer slot `slot`, a read where `read`, whose byte offset is a translation-time
|
||||
@@ -1235,12 +1094,6 @@ pub(crate) fn fixed_offset(cx: &SelectCx<'_>, ptr: Value) -> bool {
|
||||
/// [`finish_slots`]'s placement, in its charged working tables.
|
||||
fn place_slots(cx: &mut SelectCx<'_>, m: &mut Meter) -> Result<Vec<Option<SlotChoice>>, Error> {
|
||||
let p = cx.profile;
|
||||
let limits = &p.fields().limits;
|
||||
let addressed = p.fields().buffer_access == BufferAccess::Addressed;
|
||||
let range_variant = || -> Error {
|
||||
// Profile F honors `BufferRangeLimit` at plan time; it has no device address.
|
||||
Unsupported::needs_any_of(Feature::BufferRange, vec![p.addressed_needs()]).into()
|
||||
};
|
||||
let memory = cx.memory;
|
||||
let stage = cx.stage;
|
||||
let sources: Vec<SlotRef> = cx
|
||||
@@ -1254,11 +1107,11 @@ fn place_slots(cx: &mut SelectCx<'_>, m: &mut Meter) -> Result<Vec<Option<SlotCh
|
||||
if replay || cx.inputs.flat_grid || cx.inputs.folded_groups {
|
||||
plan_replay(cx, &sources)?;
|
||||
}
|
||||
let own_addresses = identity(p) && !replay;
|
||||
// Under the identity domains a kernel on a device that binds its buffer arguments reaches
|
||||
// each through its storage view, bound over its buffer and contained by the pipeline's
|
||||
// robustness (`DeviceProfile::binds_kernel_buffers`); a slot a wide pointer, a typed atomic or
|
||||
// the stage-in fetch reaches keeps its device address, as every slot of another stage does.
|
||||
let own_addresses = !replay;
|
||||
// A kernel on a device that binds its buffer arguments reaches each through its storage view,
|
||||
// bound over its buffer and contained by the pipeline's robustness
|
||||
// (`DeviceProfile::binds_kernel_buffers`); a slot a wide pointer, a typed atomic or the
|
||||
// stage-in fetch reaches keeps its device address, as every slot of another stage does.
|
||||
let bound = own_addresses && stage == Stage::Kernel && p.binds_kernel_buffers();
|
||||
let shared_slot = |s: SlotRef| {
|
||||
memory
|
||||
@@ -1289,142 +1142,30 @@ fn place_slots(cx: &mut SelectCx<'_>, m: &mut Meter) -> Result<Vec<Option<SlotCh
|
||||
window
|
||||
};
|
||||
windows.push(Some(window));
|
||||
// A slot a wide pointer may reach is read through its root entry; a slot a typed atomic
|
||||
// reaches needs a typed pointer, which only its device address gives; a replay variant
|
||||
// reads every slot through its root entry, which the replay's preprocess writes from the
|
||||
// replayed command's record.
|
||||
// Under the identity domains every slot is its device address, but a kernel's that its
|
||||
// device binds (`bound`), other than one the dispatch binds at a multiple of 4 below its
|
||||
// argument's alignment (`LoweringInputs::word_bound_buffers`): a view's `uvec4` and
|
||||
// `uvec2` units take the bind offset to be a multiple of that alignment (`memory::leaf`).
|
||||
// Every slot is its device address, but a kernel's that its device binds (`bound`), other
|
||||
// than one the dispatch binds at a multiple of 4 below its argument's alignment
|
||||
// (`LoweringInputs::word_bound_buffers`): a view's `uvec4` and `uvec2` units take the bind
|
||||
// offset to be a multiple of that alignment (`memory::leaf`). A slot a wide pointer may
|
||||
// reach, or a typed atomic, which needs a typed pointer, keeps its device address; a
|
||||
// replay variant reads every slot through its root entry, which the replay's preprocess
|
||||
// writes from the replayed command's record.
|
||||
let binds = bound && !shared && !cx.inputs.word_bound_buffers.contains(&plan.slot);
|
||||
if replay
|
||||
|| (identity(p) && !binds)
|
||||
|| cx.families.access.dynamic.slots.contains(&i)
|
||||
|| cx.families.access.typed_slots.contains(&i)
|
||||
let l = if binds
|
||||
&& !cx.families.access.dynamic.slots.contains(&i)
|
||||
&& !cx.families.access.typed_slots.contains(&i)
|
||||
{
|
||||
lowering.push(Some(psb_lowering(window)?));
|
||||
continue;
|
||||
}
|
||||
let mut l = SlotLowering::View;
|
||||
// A bound slot's descriptor range holds its buffer: the device's range holds the longest
|
||||
// (`DeviceProfile::binds_kernel_buffers`).
|
||||
if !bound && !storage_range_fits(window, limits) {
|
||||
cx.facts
|
||||
.insert(RuntimeFact::BufferRangeLimit { slot: plan.slot });
|
||||
}
|
||||
if cx.inputs.psb_slots.contains(&plan.slot) {
|
||||
if !addressed {
|
||||
return Err(range_variant());
|
||||
}
|
||||
l = psb_lowering(window)?;
|
||||
}
|
||||
SlotLowering::View
|
||||
} else {
|
||||
psb_lowering(window)?
|
||||
};
|
||||
lowering.push(Some(l));
|
||||
}
|
||||
// Source buffers no accessed slot shares: read-only `Whole` storage slots of their own, whose
|
||||
// range is never provably within `maxStorageBufferRange`; a replay variant's are read through
|
||||
// their root entries, as its other slots are, and under the identity domains each is its device
|
||||
// address, as every slot is there.
|
||||
// Source buffers no accessed slot shares: read-only `Whole` slots of their own, each its device
|
||||
// address, as every slot is.
|
||||
let mut own: Vec<(SlotRef, SlotLowering)> = Vec::new();
|
||||
for &s in &sources {
|
||||
if shared_slot(s).is_some() {
|
||||
continue;
|
||||
}
|
||||
if replay || identity(p) {
|
||||
if shared_slot(s).is_none() {
|
||||
own.push((s, psb_lowering(Window::Whole)?));
|
||||
continue;
|
||||
}
|
||||
cx.facts.insert(RuntimeFact::BufferRangeLimit { slot: s });
|
||||
let l = if cx.inputs.psb_slots.contains(&s) {
|
||||
if !addressed {
|
||||
return Err(range_variant());
|
||||
}
|
||||
psb_lowering(Window::Whole)?
|
||||
} else {
|
||||
SlotLowering::View
|
||||
};
|
||||
own.push((s, l));
|
||||
}
|
||||
// The push fields as they will be once the slot forms are final: a device-address slot reads
|
||||
// the root table instead of its residual. The `ArgumentTable` is one more uniform buffer when
|
||||
// they spill (the synthetic bindings count against the limits).
|
||||
let forms = memory
|
||||
.slots
|
||||
.iter()
|
||||
.zip(&lowering)
|
||||
.filter_map(|(plan, l)| l.map(|l| (plan.slot, l)))
|
||||
.chain(own.iter().copied());
|
||||
let mut census = Census::new(
|
||||
&cx.push,
|
||||
(
|
||||
cx.families.access.dynamic.used,
|
||||
identity(p),
|
||||
own_addresses,
|
||||
(crate::lower::push::base(cx), p.push_window()),
|
||||
),
|
||||
forms,
|
||||
m,
|
||||
)?;
|
||||
if addressed {
|
||||
// The storage views the step may move, the highest Metal index first: the accessed slots
|
||||
// (by their chosen windows) in memory-plan order, then the source buffers of their own.
|
||||
// A stable sort read from its end takes the last of equal indices, as the search for the
|
||||
// greatest index per step once did.
|
||||
let storage = SlotLowering::View;
|
||||
let mut order: Vec<(u32, Moved)> = Vec::new();
|
||||
for (i, (plan, (l, w))) in memory
|
||||
.slots
|
||||
.iter()
|
||||
.zip(lowering.iter().zip(&windows))
|
||||
.enumerate()
|
||||
{
|
||||
m.tick(1)?;
|
||||
if let (Some(l), Some(w)) = (l, w) {
|
||||
if *l == storage {
|
||||
order.push((plan.slot.index, Moved::Accessed(i, *w)));
|
||||
}
|
||||
}
|
||||
}
|
||||
for (k, (s, l)) in own.iter().enumerate() {
|
||||
m.tick(1)?;
|
||||
if *l == storage {
|
||||
order.push((s.index, Moved::Own(k)));
|
||||
}
|
||||
}
|
||||
order.sort_by_key(|(index, _)| *index);
|
||||
loop {
|
||||
m.tick(1)?;
|
||||
let total = cx.descriptors.plus(&census.counts(stage));
|
||||
let storage_bound = matches!(
|
||||
total.exceeded(limits),
|
||||
Some((
|
||||
VkLimit::MaxPerStageDescriptorStorageBuffers | VkLimit::MaxPerStageResources,
|
||||
_,
|
||||
_
|
||||
))
|
||||
);
|
||||
if !storage_bound {
|
||||
break;
|
||||
}
|
||||
let Some((_, moved)) = order.pop() else {
|
||||
break;
|
||||
};
|
||||
match moved {
|
||||
Moved::Accessed(i, window) => {
|
||||
let psb = psb_lowering(window)?;
|
||||
if let (Some(l), Some(plan)) = (lowering.get_mut(i), memory.slots.get(i)) {
|
||||
*l = Some(psb);
|
||||
census.addressed(plan.slot);
|
||||
}
|
||||
}
|
||||
Moved::Own(k) => {
|
||||
let psb = psb_lowering(Window::Whole)?;
|
||||
if let Some((s, l)) = own.get_mut(k) {
|
||||
*l = psb;
|
||||
census.addressed(*s);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut slots = Vec::with_capacity(memory.slots.len());
|
||||
@@ -1517,14 +1258,22 @@ fn place_slots(cx: &mut SelectCx<'_>, m: &mut Meter) -> Result<Vec<Option<SlotCh
|
||||
cx.facts.insert(RuntimeFact::RobustStorageBuffers);
|
||||
}
|
||||
place_zero_address(cx, &lowering, &own);
|
||||
let counts = census.counts(stage);
|
||||
cx.descriptors = cx.descriptors.plus(&counts);
|
||||
// A bound kernel's storage views are its only descriptors of this family.
|
||||
let storage = slots
|
||||
.iter()
|
||||
.flatten()
|
||||
.filter(|c| c.form == BufferForm::Descriptor)
|
||||
.count();
|
||||
cx.descriptors = cx.descriptors.plus(&DescriptorCounts {
|
||||
storage_buffers: u32::try_from(storage).unwrap_or(u32::MAX),
|
||||
..DescriptorCounts::default()
|
||||
});
|
||||
let window = (crate::lower::push::base(cx), p.push_window());
|
||||
cx.families.access.argument_table = table::spills(stage, window, &cx.push);
|
||||
// Under the identity domains a function whose fields spill, of any stage, reads them from a
|
||||
// parameter block whose address its window holds first: a render pipeline's stages too, in
|
||||
// their shares of the device's one range (`push::vertex_end`).
|
||||
if cx.families.access.argument_table && identity(p) {
|
||||
// A function whose fields spill, of any stage, reads them from a parameter block whose address
|
||||
// its window holds first: a render pipeline's stages too, in their shares of the device's one
|
||||
// range (`push::vertex_end`).
|
||||
if cx.families.access.argument_table {
|
||||
cx.push.insert(PushField::ArgumentTableAddress);
|
||||
}
|
||||
let mut sourced: Vec<pulled::PulledSlot> = own
|
||||
@@ -1546,11 +1295,7 @@ fn place_slots(cx: &mut SelectCx<'_>, m: &mut Meter) -> Result<Vec<Option<SlotCh
|
||||
cx.families.access.pulled = sourced;
|
||||
cx.families.access.unwritten = unwritten_slots(cx, &lowering, &sources);
|
||||
cx.families.access.slots = lowering;
|
||||
// The root table's bounds; under the identity domains a slot's accesses are checked against
|
||||
// its pushed length instead (`variable`).
|
||||
cx.families.access.psb_contained = !identity(p);
|
||||
cx.families.access.psb_units = psb::narrow_units(p);
|
||||
cx.families.access.identity = identity(p);
|
||||
Ok(slots)
|
||||
}
|
||||
|
||||
@@ -1567,7 +1312,7 @@ fn place_slots(cx: &mut SelectCx<'_>, m: &mut Meter) -> Result<Vec<Option<SlotCh
|
||||
/// ([`AccessPlan::reach`]). 1 for an argument with no alignment or one of 1, which states none;
|
||||
/// `None` for a buffer-table element and an argument buffer.
|
||||
fn address_alignment(cx: &SelectCx<'_>, plan: &SlotPlan) -> Option<u32> {
|
||||
if !identity(cx.profile) || plan.element.is_some() || plan.argument_buffer {
|
||||
if plan.element.is_some() || plan.argument_buffer {
|
||||
return None;
|
||||
}
|
||||
let twos = cx
|
||||
@@ -1607,7 +1352,6 @@ fn unwritten_slots(
|
||||
.any(|&(key, _)| module.symbols().get(key) == Some(BUFFER_NO_ALIAS))
|
||||
})
|
||||
};
|
||||
let identity = identity(cx.profile);
|
||||
cx.memory
|
||||
.slots
|
||||
.iter()
|
||||
@@ -1617,9 +1361,7 @@ fn unwritten_slots(
|
||||
let unwritten = !plan.access.write && !plan.wide.write && unaliased(plan.param);
|
||||
let read_only = match l {
|
||||
Some(SlotLowering::View) => unwritten,
|
||||
Some(SlotLowering::Psb { .. }) if identity => {
|
||||
unwritten || plan.space == AddrSpace::Constant
|
||||
}
|
||||
Some(SlotLowering::Psb { .. }) => unwritten || plan.space == AddrSpace::Constant,
|
||||
_ => false,
|
||||
};
|
||||
read_only
|
||||
@@ -1773,15 +1515,6 @@ pub fn replay_guest_base(
|
||||
fb.convert(crate::spirv::ir::ConvOp::Bitcast, base, uvec2)
|
||||
}
|
||||
|
||||
/// A storage slot the per-stage limit fallback moves to its device address.
|
||||
#[derive(Clone, Copy)]
|
||||
enum Moved {
|
||||
/// Memory-plan slot `.0`, with its chosen window.
|
||||
Accessed(usize, Window),
|
||||
/// The `.0`th source buffer of its own.
|
||||
Own(usize),
|
||||
}
|
||||
|
||||
/// The device-address lowering of a slot with `window`: the window's start fixes how the `u32`
|
||||
/// pointer offset maps back to a 64-bit displacement from the bind offset, which is exact for every
|
||||
/// window of at most 2³² bytes. A `Bounded` window longer than that holds constant offsets the
|
||||
@@ -1794,9 +1527,9 @@ fn psb_lowering(window: Window) -> Result<SlotLowering, Error> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Accept the push placement: every field placed in the `ArgumentTable` is read from the table's
|
||||
/// uniform buffer ([`table`]), whose descriptor [`finish_slots`] counted from the same field set,
|
||||
/// and the table fits `maxUniformBufferRange`.
|
||||
/// Accept the push placement: every field placed in the `ArgumentTable` is read from the parameter
|
||||
/// block at the pushed `ArgumentTableAddress`, which [`finish_slots`] placed from the same field
|
||||
/// set.
|
||||
pub fn accept_placement(cx: &SelectCx<'_>, placement: &PushPlacement) -> Result<(), Error> {
|
||||
let spilled = placement
|
||||
.fields
|
||||
@@ -1807,18 +1540,6 @@ pub fn accept_placement(cx: &SelectCx<'_>, placement: &PushPlacement) -> Result<
|
||||
cx.invariant("the push placement disagrees with the counted ArgumentTable descriptor")
|
||||
);
|
||||
}
|
||||
let range = cx.profile.fields().limits.max_uniform_buffer_range;
|
||||
if placement.argument_table_size > range && !cx.families.access.identity {
|
||||
return Err(Unsupported::needs(
|
||||
Feature::DescriptorCount,
|
||||
Capability::Limit {
|
||||
limit: VkLimit::MaxUniformBufferRange,
|
||||
required: u64::from(placement.argument_table_size),
|
||||
available: u64::from(range),
|
||||
},
|
||||
)
|
||||
.into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1829,25 +1550,19 @@ pub fn table_field(
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
field: PushField,
|
||||
) -> BResult<SValue> {
|
||||
let read = match &cx.decl.families.access.table {
|
||||
Some(t) => table::read(fb, t, field)?,
|
||||
// Under the identity domains the table is the parameter block at the pushed address.
|
||||
None if cx.plan.families.access.identity => {
|
||||
let offset = cx.plan.push.fields.iter().find_map(|f| match f.loc {
|
||||
PushLoc::ArgumentTable { offset } if f.field == field => Some(offset),
|
||||
_ => None,
|
||||
});
|
||||
match offset {
|
||||
Some(offset) => {
|
||||
let block = cx.push_field(fb, PushField::ArgumentTableAddress)?;
|
||||
let mut lines = Vec::new();
|
||||
for line in table::lines(offset, field) {
|
||||
lines.push((line, cx.block_line(fb, block, line)?));
|
||||
}
|
||||
Some(table::field_of_lines(fb, &lines, offset, field)?)
|
||||
}
|
||||
None => None,
|
||||
// The table is the parameter block at the pushed address.
|
||||
let offset = cx.plan.push.fields.iter().find_map(|f| match f.loc {
|
||||
PushLoc::ArgumentTable { offset } if f.field == field => Some(offset),
|
||||
_ => None,
|
||||
});
|
||||
let read = match offset {
|
||||
Some(offset) => {
|
||||
let block = cx.push_field(fb, PushField::ArgumentTableAddress)?;
|
||||
let mut lines = Vec::new();
|
||||
for line in table::lines(offset, field) {
|
||||
lines.push((line, cx.block_line(fb, block, line)?));
|
||||
}
|
||||
Some(table::field_of_lines(fb, &lines, offset, field)?)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
@@ -1867,27 +1582,12 @@ pub fn declare(
|
||||
) -> BResult<Declared> {
|
||||
let mut d = Declared {
|
||||
local: local::declare(mb, plan)?,
|
||||
table: match plan.families.access.identity {
|
||||
true => None,
|
||||
false => table::declare(mb, &plan.push)?,
|
||||
},
|
||||
blob: match &plan.families.access.blob {
|
||||
Some(b) => Some(crate::memory::blob::declare(mb, plan.stage, b)?),
|
||||
Some(b) => Some(crate::memory::blob::declare(mb, b)?),
|
||||
None => None,
|
||||
},
|
||||
pulled: pulled::declare(mb, &plan.families.access)?,
|
||||
handle_table: handle::declare_table(mb, plan)?,
|
||||
sampler_table: handle::declare_sampler_table(mb, plan)?,
|
||||
resolve: match dynamic::defines_search(&plan.families.access.dynamic) {
|
||||
true => {
|
||||
let wide = dynamic::wide_type(mb)?;
|
||||
Some(crate::memory::roots::define_resolve(mb, wide)?)
|
||||
}
|
||||
false => None,
|
||||
},
|
||||
tile: tile::declare(mb, &plan.families.access)?,
|
||||
function_tables: function_table::declare(mb, plan)?,
|
||||
status: absent::declare(mb, plan.stage, &plan.families.access)?,
|
||||
..Declared::default()
|
||||
};
|
||||
for (i, s) in plan.slots.iter().enumerate() {
|
||||
|
||||
@@ -573,10 +573,9 @@ pub fn null_value(fb: &mut FunctionBuilder<'_>, ty: &DemoteTy) -> BResult<Option
|
||||
if *ty == DemoteTy::Address {
|
||||
return super::psb::k64(fb, 0).map(Some);
|
||||
}
|
||||
// A narrow fat pointer `(root, offset)`; a wide one `(root, at, host, size)`.
|
||||
// A fat pointer `(root, offset)`.
|
||||
let (width, len) = match ty {
|
||||
DemoteTy::FatPtr { wide: false } => (32, 2),
|
||||
DemoteTy::FatPtr { wide: true } => (64, 4),
|
||||
DemoteTy::FatPtr => (32, 2),
|
||||
_ => return Ok(None),
|
||||
};
|
||||
let elem = fb.module().ty(SType::Int {
|
||||
@@ -625,7 +624,7 @@ pub fn null_operand(
|
||||
if !null_source(cx, v) {
|
||||
return Ok(None);
|
||||
}
|
||||
null_value(fb, &DemoteTy::FatPtr { wide: false })
|
||||
null_value(fb, &DemoteTy::FatPtr)
|
||||
}
|
||||
|
||||
/// The value phi `phi`'s copy on an incoming edge stores for incoming value `src`: a null
|
||||
@@ -785,10 +784,10 @@ fn guest_base(
|
||||
}
|
||||
|
||||
/// Whether buffer slots' `SlotGuestBase` words are their Metal addresses less
|
||||
/// [`SLOT_ADDRESS_BIAS`](super::SLOT_ADDRESS_BIAS): under the identity domains, where the runtime
|
||||
/// pushes them. A replay variant reads each slot's address itself from its root entry.
|
||||
/// [`SLOT_ADDRESS_BIAS`](super::SLOT_ADDRESS_BIAS), as the runtime pushes them. A replay variant
|
||||
/// reads each slot's address itself from its root entry.
|
||||
fn biased(cx: &EmitCx<'_>) -> bool {
|
||||
cx.plan.families.access.identity && !cx.plan.families.access.replay
|
||||
!cx.plan.families.access.replay
|
||||
}
|
||||
|
||||
/// Buffer slot `slot`'s `SlotGuestBase` word (a `uvec2`, low word first) as a `u64` (needs
|
||||
@@ -907,8 +906,8 @@ fn emit_address(
|
||||
if words {
|
||||
return Err(cx.fail("a wide pointer's address in two words"));
|
||||
}
|
||||
let p = cx.operand(fb, *p)?;
|
||||
Ok(Address::U64(dynamic::guest_address(cx, fb, p)?))
|
||||
// A wide pointer is the address it holds.
|
||||
Ok(Address::U64(cx.operand(fb, *p)?))
|
||||
}
|
||||
Addr::Static(s) => {
|
||||
let fat = cx.operand(fb, s.ptr)?;
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
//! The PSB leaf of a static slot: a slot whose `BufferForm` is `Psb` (a `BufferRangeLimit` variant,
|
||||
//! or Profile A's per-stage descriptor-limit fallback) is reached through the device address of its
|
||||
//! The PSB leaf of a static slot: a slot whose `BufferForm` is `Psb` (every slot but a bound
|
||||
//! kernel's storage view, `access::finish_slots`) is reached through the device address of its
|
||||
//! allocation.
|
||||
//!
|
||||
//! **Root table.** The address comes from the resident root table, at the device address
|
||||
//! `PushField::RootTableAddress`: 32-byte entries `{ host: u64, guest: u64, size: u64, bind_offset:
|
||||
//! u64 }` ([`ROOT_ENTRY_BYTES`]), where entry 1 is the write-only sink (`NeutralResource::Sink`, at
|
||||
//! u64 }`, where entry 1 is the write-only sink (`NeutralResource::Sink`, at
|
||||
//! least 64 bytes) and entry `2 + n` is `[[buffer(n)]]`: `host` the device address of the
|
||||
//! allocation, `size` its padded size, and `bind_offset` the Metal bind offset into it.
|
||||
//!
|
||||
@@ -29,10 +29,10 @@
|
||||
//!
|
||||
//! **Narrow units.** Where the profile has the 8- or 16-bit storage access ([`narrow_units`]), the
|
||||
//! memory also loads and stores 1- and 2-byte units: a `u8` or `u16` place at the unit's device
|
||||
//! address, with the `Aligned` operand of its size, as a descriptor slot's narrow views do. Vulkan's
|
||||
//! `storageBuffer8BitAccess` and `storageBuffer16BitAccess` cover the `PhysicalStorageBuffer`
|
||||
//! storage class as they cover `StorageBuffer`. A sub-word store there is one narrow store; without
|
||||
//! the access it stays the two word atomics ([`PsbMem`]'s `write_bits`).
|
||||
//! address, with the `Aligned` operand of its size, as a descriptor slot's narrow views do.
|
||||
//! Vulkan's `storageBuffer8BitAccess` and `storageBuffer16BitAccess` cover the
|
||||
//! `PhysicalStorageBuffer` storage class as they cover `StorageBuffer`. A sub-word store there is
|
||||
//! one narrow store; without the access it stays the two word atomics ([`PsbMem`]'s `write_bits`).
|
||||
//!
|
||||
//! **Whole words.** A leaf of whole words is one access of up to 16 bytes at the device address of
|
||||
//! its first word (`memory::leaf`'s whole words; [`PsbMem`]'s `whole_place`), not one per word:
|
||||
@@ -55,16 +55,6 @@ use crate::spirv::ir::{
|
||||
AtomicOp, BinOp, ConstBits, Constant, ConvOp, GlslOp, MemAccess, Scope, Semantics, Type, UnOp,
|
||||
};
|
||||
|
||||
/// Bytes of one root-table entry.
|
||||
pub const ROOT_ENTRY_BYTES: u64 = 32;
|
||||
/// The sink's root.
|
||||
pub const SINK_ROOT: u32 = 1;
|
||||
|
||||
/// Byte offsets of the entry fields.
|
||||
const HOST: u64 = 0;
|
||||
const SIZE: u64 = 16;
|
||||
const BIND_OFFSET: u64 = 24;
|
||||
|
||||
fn u64_ty(fb: &mut FunctionBuilder<'_>) -> BResult<TypeId> {
|
||||
fb.module().ty(Type::Int {
|
||||
width: 64,
|
||||
@@ -99,31 +89,6 @@ pub fn k64(fb: &mut FunctionBuilder<'_>, v: u64) -> BResult<Value> {
|
||||
fb.module().const_value(c)
|
||||
}
|
||||
|
||||
/// The `u64` field at byte `field` of root `root`'s entry in the table at `table`.
|
||||
fn entry_field(
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
table: Value,
|
||||
root: u32,
|
||||
field: u64,
|
||||
) -> BResult<Value> {
|
||||
let at = k64(
|
||||
fb,
|
||||
u64::from(root)
|
||||
.saturating_mul(ROOT_ENTRY_BYTES)
|
||||
.saturating_add(field),
|
||||
)?;
|
||||
let addr = fb.binary(BinOp::IAdd, table, at)?;
|
||||
let u64_ = u64_ty(fb)?;
|
||||
let p = fb.device_place(addr, u64_)?;
|
||||
fb.load(
|
||||
p,
|
||||
MemAccess {
|
||||
aligned: Some(8),
|
||||
..MemAccess::default()
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/// `x` (a `u64`) rounded down to a multiple of 4, and its remainder (0 to 3) as a `u32`: the word
|
||||
/// below a byte and the byte's offset in it. A leaf of whole words reads only the word, and the
|
||||
/// remainder's instructions are then removed as dead.
|
||||
@@ -166,44 +131,6 @@ pub struct PsbAccess {
|
||||
pub inb: Option<Value>,
|
||||
}
|
||||
|
||||
/// Prepare an `n`-byte access of root `root` (a static slot whose window starts at `start`) at
|
||||
/// the `u32` displacement `m` from its bind offset, for the table at `table` (a `u64`).
|
||||
pub fn prepare(
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
table: Value,
|
||||
root: u32,
|
||||
m: Value,
|
||||
start: i64,
|
||||
n: u32,
|
||||
contained: bool,
|
||||
) -> BResult<PsbAccess> {
|
||||
let host = entry_field(fb, table, root, HOST)?;
|
||||
let size = entry_field(fb, table, root, SIZE)?;
|
||||
let bind = entry_field(fb, table, root, BIND_OFFSET)?;
|
||||
let disp = displacement(fb, m, start)?;
|
||||
let off = fb.binary(BinOp::IAdd, bind, disp)?;
|
||||
let (aligned, low) = split_word(fb, off)?;
|
||||
let base = fb.binary(BinOp::IAdd, host, aligned)?;
|
||||
if !contained {
|
||||
return Ok(PsbAccess {
|
||||
mem: PsbMem::at(base),
|
||||
off: low,
|
||||
inb: None,
|
||||
});
|
||||
}
|
||||
let inb = crate::memory::contain::in_bounds(fb, off, size, u64::from(n))?;
|
||||
let sink = entry_field(fb, table, SINK_ROOT, HOST)?;
|
||||
let base = fb.select(inb, base, sink)?;
|
||||
let zero = fb.u32_const(0)?;
|
||||
let zero = fb.module().const_value(zero)?;
|
||||
let low = fb.select(inb, low, zero)?;
|
||||
Ok(PsbAccess {
|
||||
mem: PsbMem::at(base),
|
||||
off: low,
|
||||
inb: Some(inb),
|
||||
})
|
||||
}
|
||||
|
||||
/// How a device-address memory reaches its units.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Reach {
|
||||
@@ -213,19 +140,19 @@ enum Reach {
|
||||
/// From the 4-aligned device address below one access of a slot under the identity domains
|
||||
/// ([`prepare_at`]): each unit at that address plus its index times its size, the product in
|
||||
/// 32 bits and zero-extended. A unit lies within 2^31 bytes of that address, the runtime
|
||||
/// making no buffer longer than 2 GiB (`metal2vulkan_runtime::MAX_BUFFER_LENGTH`), so the product is
|
||||
/// exact, and no 64-bit shift or multiply scales an index.
|
||||
/// making no buffer longer than 2 GiB (`metal2vulkan_runtime::MAX_BUFFER_LENGTH`), so the
|
||||
/// product is exact, and no 64-bit shift or multiply scales an index.
|
||||
Below,
|
||||
/// From a slot's own device address under the identity domains ([`prepare_direct`]), held
|
||||
/// as that address less [`SLOT_ADDRESS_BIAS`] (2^31): each unit at that base plus its 32-bit
|
||||
/// byte offset plus 2^31, modulo 2^32, treated as unsigned, then one
|
||||
/// `OpConvertUToPtr` to the unit's block (`NonWritable` for a load of an unwritten slot).
|
||||
/// Every byte of a buffer lies within 2^31 bytes of each bind address in it, the runtime
|
||||
/// making no buffer longer than 2 GiB (`metal2vulkan_runtime::MAX_BUFFER_LENGTH`), so the offset
|
||||
/// read as signed is in `[-2^31, 2^31)`, the biased one is that offset plus 2^31 exactly, and
|
||||
/// the sum is the address plus the offset. A unit index `x + c` with a constant `c` folds
|
||||
/// `c`'s bytes into the bias: `(x + c) * s + 2^31` is `x * s + (c * s + 2^31)` modulo 2^32.
|
||||
/// The base's low word takes that unsigned offset and its high word the carry
|
||||
/// making no buffer longer than 2 GiB (`metal2vulkan_runtime::MAX_BUFFER_LENGTH`), so the
|
||||
/// offset read as signed is in `[-2^31, 2^31)`, the biased one is that offset plus 2^31
|
||||
/// exactly, and the sum is the address plus the offset. A unit index `x + c` with a constant
|
||||
/// `c` folds `c`'s bytes into the bias: `(x + c) * s + 2^31` is `x * s + (c * s + 2^31)` modulo
|
||||
/// 2^32. The base's low word takes that unsigned offset and its high word the carry
|
||||
/// ([`add_slot_offset`]); the base's words are made once where they dominate
|
||||
/// (`pointer::direct_base`). The address holds the binder's alignment
|
||||
/// (`RuntimeFact::AddressAlignment`), the first field.
|
||||
@@ -261,8 +188,8 @@ pub fn prepare_at(fb: &mut FunctionBuilder<'_>, address: Value, m: Value) -> BRe
|
||||
/// (`RuntimeFact::AddressAlignment`): the access is the byte offset `m`, read as signed, from that
|
||||
/// address, as a descriptor view's is `m` from its base ([`Reach::Direct`]). Every byte of a
|
||||
/// buffer lies within 2^31 bytes of each bind address in it, the runtime making no buffer longer
|
||||
/// than 2 GiB (`metal2vulkan_runtime::MAX_BUFFER_LENGTH`), so the offset is exact whatever the slot's
|
||||
/// window. Nothing is rounded. The check, where the access takes one, is `emit::prepare`'s.
|
||||
/// than 2 GiB (`metal2vulkan_runtime::MAX_BUFFER_LENGTH`), so the offset is exact whatever the
|
||||
/// slot's window. Nothing is rounded. The check, where the access takes one, is `emit::prepare`'s.
|
||||
pub fn prepare_direct(base: wide::Pair, m: Value, held: u32) -> PsbAccess {
|
||||
PsbAccess {
|
||||
mem: PsbMem {
|
||||
|
||||
@@ -21,36 +21,28 @@
|
||||
//! through a view or a device address).
|
||||
//! - **Own.** Otherwise the source buffer is a read-only `Whole` slot of its own.
|
||||
//!
|
||||
//! Either way it is a storage slot like any other: a `Whole` range is never provably within
|
||||
//! `maxStorageBufferRange`, so it declares `BufferRangeLimit`; a `BufferRangeLimit` variant
|
||||
//! (`LowerInputs.psb_slots`) or Profile A's per-stage descriptor-limit fallback moves it to its
|
||||
//! device address, and a shared slot takes the device address the argument's wide pointers or typed
|
||||
//! atomics need. A device-replay variant (`LowerInputs.replay_bindings`) reads it, as every other
|
||||
//! slot, through its root entry in the replayed command's slot table. The fetch reads a storage view at the bind residual plus its Metal displacement,
|
||||
//! checked in the shader, and a device address through the slot's root entry (`psb`,
|
||||
//! window start 0), always contained unless containment is off. Under the identity domains every
|
||||
//! source buffer is its device address, which the fetch reads from the slot's own pushed address
|
||||
//! (`SlotGuestBase`) plus its displacement, read as signed, checked against the slot's buffer
|
||||
//! (`SlotBounds`): outside its buffer a fetch reads zero at the zero range (`ZeroAddress`). Reads
|
||||
//! are plain: a vertex function has no barrier a coherence could order them with.
|
||||
//! Either way every source buffer is its device address, which the fetch reads from the slot's own
|
||||
//! pushed address (`SlotGuestBase`) plus its displacement, read as signed, checked against the
|
||||
//! slot's buffer (`SlotBounds`): outside its buffer a fetch reads zero at the zero range
|
||||
//! (`ZeroAddress`). A device-replay variant (`LowerInputs.replay_bindings`) reads its address, as
|
||||
//! every other slot's, from its root entry in the replayed command's slot table. Reads are plain:
|
||||
//! a vertex function has no barrier a coherence could order them with.
|
||||
|
||||
use crate::error::{Error, Feature, LowerFamily, Unsupported};
|
||||
use crate::lower::emit::EmitCx;
|
||||
use crate::lower::stage_io::fetch;
|
||||
use crate::memory::contain;
|
||||
use crate::memory::leaf::{self, k32, Leaf, WordMem};
|
||||
use crate::memory::views::{self, View};
|
||||
use crate::pipeline::interface::{
|
||||
AccessSet, BufferForm, BufferKind, BufferSlot, SlotInterface, Window,
|
||||
};
|
||||
use crate::pipeline::sym::{PushField, SlotRef};
|
||||
use crate::spirv::builder::{FunctionBuilder, ModuleBuilder};
|
||||
use crate::spirv::builder::FunctionBuilder;
|
||||
use crate::spirv::error::{BResult, BuildError, Dangling};
|
||||
use crate::spirv::ids::Value as SValue;
|
||||
use crate::spirv::ir::BinOp;
|
||||
|
||||
use super::psb::{self, PsbMem};
|
||||
use super::{slot_root, AccessPlan, SlotLowering};
|
||||
use super::{AccessPlan, SlotLowering};
|
||||
|
||||
/// How the fetch reaches a pulled source buffer.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
@@ -120,34 +112,13 @@ pub fn slot_interfaces(plan: &AccessPlan) -> impl Iterator<Item = (SlotRef, Slot
|
||||
})
|
||||
}
|
||||
|
||||
/// Declare the storage view of every source buffer with a descriptor slot of its own.
|
||||
pub(super) fn declare(mb: &mut ModuleBuilder, plan: &AccessPlan) -> BResult<Vec<(u32, View)>> {
|
||||
let mut out = Vec::new();
|
||||
for p in &plan.pulled {
|
||||
if let Reach::Own(SlotLowering::View) = p.reach {
|
||||
out.push((p.slot.index, views::declare(mb, p.slot)?));
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The read-only word memory of a source buffer: a storage view, or the words at a device
|
||||
/// address.
|
||||
/// The read-only word memory of a source buffer: the words at its device address.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct SourceMem(Mem);
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum Mem {
|
||||
View(View),
|
||||
Psb(PsbMem),
|
||||
}
|
||||
pub struct SourceMem(pub(crate) PsbMem);
|
||||
|
||||
impl WordMem for SourceMem {
|
||||
fn read(&mut self, fb: &mut FunctionBuilder<'_>, word: SValue) -> BResult<SValue> {
|
||||
match &mut self.0 {
|
||||
Mem::View(v) => views::read_word(fb, *v, word),
|
||||
Mem::Psb(m) => m.read(fb, word),
|
||||
}
|
||||
self.0.read(fb, word)
|
||||
}
|
||||
|
||||
fn write(&mut self, _: &mut FunctionBuilder<'_>, _: SValue, value: SValue) -> BResult<()> {
|
||||
@@ -155,10 +126,7 @@ impl WordMem for SourceMem {
|
||||
}
|
||||
|
||||
fn whole(&self) -> bool {
|
||||
match &self.0 {
|
||||
Mem::View(_) => false,
|
||||
Mem::Psb(m) => m.whole(),
|
||||
}
|
||||
self.0.whole()
|
||||
}
|
||||
|
||||
fn read_whole(
|
||||
@@ -169,10 +137,7 @@ impl WordMem for SourceMem {
|
||||
ty: crate::spirv::ids::TypeId,
|
||||
align: u32,
|
||||
) -> BResult<SValue> {
|
||||
match &mut self.0 {
|
||||
Mem::View(v) => Err(BuildError::Dangling(Dangling::Global(v.global))),
|
||||
Mem::Psb(m) => m.read_whole(fb, off, at, ty, align),
|
||||
}
|
||||
self.0.read_whole(fb, off, at, ty, align)
|
||||
}
|
||||
|
||||
fn write_bits(
|
||||
@@ -206,65 +171,11 @@ impl SourceRead {
|
||||
}
|
||||
}
|
||||
|
||||
/// An `n`-byte read of storage view `view` at the bind residual `residual` plus the Metal
|
||||
/// displacement `m` (wrapping `u32`), checked in the shader: out of bounds it reads at offset 0 (a
|
||||
/// bound range is never empty and is padded to 16 bytes, so the at most 16 bytes of a vertex format
|
||||
/// exist there) and yields zero.
|
||||
pub fn view_read(
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
view: View,
|
||||
residual: SValue,
|
||||
m: SValue,
|
||||
n: u32,
|
||||
) -> BResult<SourceRead> {
|
||||
let off = fb.binary(BinOp::IAdd, residual, m)?;
|
||||
view_read_at(fb, view, off, n)
|
||||
}
|
||||
|
||||
/// [`view_read`] at the view's own byte offset `off`.
|
||||
fn view_read_at(
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
view: View,
|
||||
off: SValue,
|
||||
n: u32,
|
||||
) -> BResult<SourceRead> {
|
||||
let size = views::storage_bytes(fb, view)?;
|
||||
let inb = contain::in_bounds(fb, off, size, u64::from(n))?;
|
||||
let zero = k32(fb, 0)?;
|
||||
let off = fb.select(inb, off, zero)?;
|
||||
Ok(SourceRead {
|
||||
mem: SourceMem(Mem::View(view)),
|
||||
off,
|
||||
inb: Some(inb),
|
||||
})
|
||||
}
|
||||
|
||||
/// An `n`-byte read of `[[buffer(buffer)]]` by device address, at the `u32` Metal displacement `m`
|
||||
/// from its bind offset in a slot whose window starts at `start`, through the root table at
|
||||
/// `table` (a `u64`), contained when `contained` (the PSB leaf, `psb`).
|
||||
pub fn psb_read(
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
table: SValue,
|
||||
buffer: u32,
|
||||
m: SValue,
|
||||
start: i64,
|
||||
n: u32,
|
||||
contained: bool,
|
||||
) -> BResult<SourceRead> {
|
||||
let a = psb::prepare(fb, table, slot_root(buffer), m, start, n, contained)?;
|
||||
Ok(SourceRead {
|
||||
mem: SourceMem(Mem::Psb(a.mem)),
|
||||
off: a.off,
|
||||
inb: a.inb,
|
||||
})
|
||||
}
|
||||
|
||||
/// An `n`-byte read of a source buffer under the identity domains, at the `u32` Metal
|
||||
/// displacement `m` from its bind offset, read as signed: from `address` (a `u64`), the slot's own
|
||||
/// device address, the word below the read and the byte offset in it (`psb::prepare_at`). No
|
||||
/// table is read. Where `check` holds the checked slot and the `ZeroAddress` and `m` is not a
|
||||
/// constant, the read is checked as a load of the slot is (`emit::prepare`, `psb::in_buffer`):
|
||||
/// outside its buffer it reads zero at the zero range.
|
||||
/// An `n`-byte read of a source buffer, at the `u32` Metal displacement `m` from its bind offset,
|
||||
/// read as signed: from `address` (a `u64`), the slot's own device address, the word below the
|
||||
/// read and the byte offset in it (`psb::prepare_at`). Where `check` holds the checked slot and the
|
||||
/// `ZeroAddress` and `m` is not a constant, the read is checked as a load of the slot is
|
||||
/// (`emit::prepare`, `psb::in_buffer`): outside its buffer it reads zero at the zero range.
|
||||
fn address_read(
|
||||
cx: &mut EmitCx<'_>,
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
@@ -282,14 +193,14 @@ fn address_read(
|
||||
_ => a.mem,
|
||||
};
|
||||
Ok(SourceRead {
|
||||
mem: SourceMem(Mem::Psb(mem)),
|
||||
mem: SourceMem(mem),
|
||||
off: a.off,
|
||||
inb: a.inb,
|
||||
})
|
||||
}
|
||||
|
||||
/// Prepare an `n`-byte read of source buffer `buffer` at the `u32` Metal displacement `m` from
|
||||
/// its bind offset, in the form [`super::finish_slots`] chose; a view is checked in the shader.
|
||||
/// its bind offset, at its device address ([`super::finish_slots`]).
|
||||
pub fn prepare(
|
||||
cx: &mut EmitCx<'_>,
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
@@ -297,25 +208,17 @@ pub fn prepare(
|
||||
m: SValue,
|
||||
n: u32,
|
||||
) -> BResult<SourceRead> {
|
||||
match source(cx, fb, buffer)? {
|
||||
Source::View { view, residual } => view_read(fb, view, residual, m, n),
|
||||
Source::Psb {
|
||||
table,
|
||||
start,
|
||||
contained,
|
||||
} => psb_read(fb, table, buffer, m, start, n, contained),
|
||||
Source::Address { address, check } => address_read(cx, fb, address, m, (n, check)),
|
||||
}
|
||||
let Source { address, check } = source(cx, fb, buffer)?;
|
||||
address_read(cx, fb, address, m, (n, check))
|
||||
}
|
||||
|
||||
/// [`prepare`] of a read whose `u32` Metal displacement `m` is Metal's own only where `fits` (a
|
||||
/// bool) holds, the read's `n` bytes then lying in the first `2^32` bytes from the bind offset.
|
||||
/// Where it does not, and in a view where the bind residual plus `m` and its `n` bytes run past
|
||||
/// `2^32` (the view's own offset would wrap), the read lies past the first `2^32` bytes of the
|
||||
/// slot: outside every buffer a command that may read past them is not refused for (the
|
||||
/// runtime's `StageInFetchPast4GiB`), and outside every view's range. It then reads at the bind
|
||||
/// offset and yields zero bytes, Metal's answer for a fetch outside its buffer there, on every
|
||||
/// device, its robustness aside: a wrapped offset could land inside the buffer.
|
||||
/// Where it does not, the read lies past the first `2^32` bytes of the slot: outside every buffer
|
||||
/// a command that may read past them is not refused for (the runtime's `StageInFetchPast4GiB`). It
|
||||
/// then reads at the bind offset and yields zero bytes, Metal's answer for a fetch outside its
|
||||
/// buffer there, on every device, its robustness aside: a wrapped offset could land inside the
|
||||
/// buffer.
|
||||
pub fn prepare_within(
|
||||
cx: &mut EmitCx<'_>,
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
@@ -324,33 +227,10 @@ pub fn prepare_within(
|
||||
fits: SValue,
|
||||
n: u32,
|
||||
) -> BResult<SourceRead> {
|
||||
let (read, fits) = match source(cx, fb, buffer)? {
|
||||
Source::View { view, residual } => {
|
||||
// `residual + m + n <= 2^32`: the sum did not wrap, and its end fits.
|
||||
let off = fb.binary(BinOp::IAdd, residual, m)?;
|
||||
let kept = fb.binary(BinOp::UGreaterThanEqual, off, residual)?;
|
||||
let room = k32(fb, u32::MAX - n.saturating_sub(1))?;
|
||||
let ends = fb.binary(BinOp::ULessThanEqual, off, room)?;
|
||||
let view_fits = fb.binary(BinOp::LogicalAnd, kept, ends)?;
|
||||
let fits = fb.binary(BinOp::LogicalAnd, fits, view_fits)?;
|
||||
let off = fb.select(fits, off, residual)?;
|
||||
(view_read_at(fb, view, off, n)?, fits)
|
||||
}
|
||||
Source::Psb {
|
||||
table,
|
||||
start,
|
||||
contained,
|
||||
} => {
|
||||
let zero = k32(fb, 0)?;
|
||||
let m = fb.select(fits, m, zero)?;
|
||||
(psb_read(fb, table, buffer, m, start, n, contained)?, fits)
|
||||
}
|
||||
Source::Address { address, check } => {
|
||||
let zero = k32(fb, 0)?;
|
||||
let m = fb.select(fits, m, zero)?;
|
||||
(address_read(cx, fb, address, m, (n, check))?, fits)
|
||||
}
|
||||
};
|
||||
let Source { address, check } = source(cx, fb, buffer)?;
|
||||
let zero = k32(fb, 0)?;
|
||||
let m = fb.select(fits, m, zero)?;
|
||||
let read = address_read(cx, fb, address, m, (n, check))?;
|
||||
let inb = match read.inb {
|
||||
Some(inb) => fb.binary(BinOp::LogicalAnd, inb, fits)?,
|
||||
None => fits,
|
||||
@@ -361,76 +241,28 @@ pub fn prepare_within(
|
||||
})
|
||||
}
|
||||
|
||||
/// Where source buffer `buffer` is read, in the form [`super::finish_slots`] chose.
|
||||
enum Source {
|
||||
/// Its storage view, at the bind residual.
|
||||
View { view: View, residual: SValue },
|
||||
/// Its device address, through the root table at `table`, in a slot whose window starts at
|
||||
/// `start`, contained when `contained`.
|
||||
Psb {
|
||||
table: SValue,
|
||||
start: i64,
|
||||
contained: bool,
|
||||
},
|
||||
/// Under the identity domains, its own device address (`SlotGuestBase`, a `u64`), with the
|
||||
/// slot and the `ZeroAddress` where the access plan checks it (`AccessPlan::variable`).
|
||||
Address {
|
||||
address: SValue,
|
||||
check: Option<(SlotRef, SValue)>,
|
||||
},
|
||||
/// Where source buffer `buffer` is read: its own device address (`SlotGuestBase`, a `u64`), with
|
||||
/// the slot and the `ZeroAddress` where the access plan checks it (`AccessPlan::variable`).
|
||||
struct Source {
|
||||
address: SValue,
|
||||
check: Option<(SlotRef, SValue)>,
|
||||
}
|
||||
|
||||
/// The form source buffer `buffer` is read in.
|
||||
fn source(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, buffer: u32) -> BResult<Source> {
|
||||
let access = &cx.plan.families.access;
|
||||
let slot = fetch::slot(cx.plan.stage, buffer);
|
||||
let reach = access
|
||||
.pulled
|
||||
.iter()
|
||||
.find(|p| p.slot == slot)
|
||||
.map(|p| p.reach);
|
||||
// The form is `AccessPlan::source_lowering`'s, which the census reads too.
|
||||
let lowering = access.source_lowering(slot);
|
||||
let identity = access.identity;
|
||||
let checked = access.variable.contains(&slot);
|
||||
let view = match reach {
|
||||
Some(Reach::Shared { slot }) => cx.decl.families.access.views.get(slot).copied().flatten(),
|
||||
Some(Reach::Own(_)) => cx
|
||||
.decl
|
||||
.families
|
||||
.access
|
||||
.pulled
|
||||
.iter()
|
||||
.find(|(b, _)| *b == buffer)
|
||||
.map(|(_, v)| *v),
|
||||
None => return Err(cx.fail(format!("source buffer {slot:?} has no planned slot"))),
|
||||
};
|
||||
match (lowering, view) {
|
||||
(Some(SlotLowering::View), Some(view)) => {
|
||||
let residual = cx.push_field(fb, PushField::SlotBindOffset(slot))?;
|
||||
Ok(Source::View { view, residual })
|
||||
}
|
||||
(Some(SlotLowering::Psb { .. }), _) if identity => {
|
||||
let address = super::pointer::slot_address(cx, fb, slot)?;
|
||||
let check = match checked {
|
||||
true => Some((slot, cx.push_field(fb, PushField::ZeroAddress)?)),
|
||||
false => None,
|
||||
};
|
||||
Ok(Source::Address { address, check })
|
||||
}
|
||||
(Some(SlotLowering::Psb { start }), _) => {
|
||||
let table = cx.push_field(fb, PushField::RootTableAddress)?;
|
||||
let contained = cx.plan.families.access.psb_contained;
|
||||
Ok(Source::Psb {
|
||||
table,
|
||||
start,
|
||||
contained,
|
||||
})
|
||||
}
|
||||
_ => Err(cx.fail(format!(
|
||||
"source buffer {slot:?} is neither a declared storage view nor a device address"
|
||||
))),
|
||||
if !matches!(access.source_lowering(slot), Some(SlotLowering::Psb { .. })) {
|
||||
return Err(cx.fail(format!("source buffer {slot:?} is no device address")));
|
||||
}
|
||||
let checked = access.variable.contains(&slot);
|
||||
let address = super::pointer::slot_address(cx, fb, slot)?;
|
||||
let check = match checked {
|
||||
true => Some((slot, cx.push_field(fb, PushField::ZeroAddress)?)),
|
||||
false => None,
|
||||
};
|
||||
Ok(Source { address, check })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -1,40 +1,20 @@
|
||||
//! The stage's `ArgumentTable` uniform buffer.
|
||||
//! The stage's `ArgumentTable`: the push fields past its window.
|
||||
//!
|
||||
//! Push placement (`lower::push`) puts every field from the first one that does not fit the
|
||||
//! stage's push window into the `ArgumentTable`, the uniform buffer bound at
|
||||
//! `ResourceSlot{stage, Synthetic(ArgumentTable), 0}`, at offsets fixed by the same order. The
|
||||
//! access family declares it as one `Uniform` block whose members are exactly the spilled
|
||||
//! fields, each with the push shape's SPIR-V type at its placed offset (std140: the shapes lay
|
||||
//! out identically under std140 and std430), and [`read`] loads a member exactly as
|
||||
//! `EmitCx::push_field` loads a push member, so a family reading a field never knows where it was
|
||||
//! placed. The table's descriptor counts in the per-stage limits (`access::finish_slots`).
|
||||
//!
|
||||
//! Under the identity domains no uniform buffer is declared: the spilled fields are a parameter
|
||||
//! block in memory at the device address `PushField::ArgumentTableAddress` holds, which the
|
||||
//! window always places. [`read_line`] loads it 16 bytes at a time, each line once where it
|
||||
//! dominates (`EmitCx::block_line`), and [`field_of_lines`] puts each field together from its
|
||||
//! lines' words.
|
||||
//! stage's push window into the `ArgumentTable`, at offsets fixed by the same order: a parameter
|
||||
//! block in memory at the device address `PushField::ArgumentTableAddress` holds, which the window
|
||||
//! always places. No descriptor binds it. [`read_line`] loads it 16 bytes at a time, each line once
|
||||
//! where it dominates (`EmitCx::block_line`), and [`field_of_lines`] puts each field together from
|
||||
//! its lines' words.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use crate::lower::push::{self, FieldShape};
|
||||
use crate::pipeline::interface::{PushLoc, PushPlacement};
|
||||
use crate::pipeline::sym::{PushField, ResourceKind, ResourceSlot, Stage, SyntheticBinding};
|
||||
use crate::pipeline::sym::{PushField, Stage};
|
||||
use crate::spirv::builder::{FunctionBuilder, ModuleBuilder};
|
||||
use crate::spirv::error::{BResult, BuildError, Dangling};
|
||||
use crate::spirv::ids::{GlobalId, TypeId, Value};
|
||||
use crate::spirv::ir::{
|
||||
BinOp, ConstBits, Constant, ConvOp, LayoutRule, MemAccess, MemberLayout, StorageClass,
|
||||
StructLayout, Type,
|
||||
};
|
||||
|
||||
/// A declared `ArgumentTable`.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Table {
|
||||
pub global: GlobalId,
|
||||
/// The spilled fields, in member order.
|
||||
pub fields: Vec<PushField>,
|
||||
}
|
||||
use crate::spirv::ids::{TypeId, Value};
|
||||
use crate::spirv::ir::{BinOp, ConstBits, Constant, ConvOp, MemAccess, Type};
|
||||
|
||||
/// Whether `stage`'s placement of `fields` spills into the `ArgumentTable` (`push::spills`), from
|
||||
/// its push base in a device window of `bytes`.
|
||||
@@ -42,17 +22,8 @@ pub fn spills(stage: Stage, (base, bytes): (u32, u32), fields: &BTreeSet<PushFie
|
||||
push::spills(stage, base, bytes, fields)
|
||||
}
|
||||
|
||||
/// The binding symbol of `stage`'s `ArgumentTable`.
|
||||
pub fn symbol(stage: Stage) -> ResourceSlot {
|
||||
ResourceSlot {
|
||||
stage,
|
||||
kind: ResourceKind::Synthetic(SyntheticBinding::ArgumentTable),
|
||||
index: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// The SPIR-V type of a push field of shape `sh` (the same type the push block gives it).
|
||||
pub fn shape_type(mb: &mut ModuleBuilder, sh: FieldShape) -> BResult<TypeId> {
|
||||
fn shape_type(mb: &mut ModuleBuilder, sh: FieldShape) -> BResult<TypeId> {
|
||||
let u32_ = mb.ty(Type::Int {
|
||||
width: 32,
|
||||
signed: false,
|
||||
@@ -81,44 +52,6 @@ pub fn shape_type(mb: &mut ModuleBuilder, sh: FieldShape) -> BResult<TypeId> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Declare the `ArgumentTable` of `placement`, or `None` when nothing spilled.
|
||||
pub fn declare(mb: &mut ModuleBuilder, placement: &PushPlacement) -> BResult<Option<Table>> {
|
||||
let spilled: Vec<(PushField, u32)> = placement
|
||||
.fields
|
||||
.iter()
|
||||
.filter_map(|f| match f.loc {
|
||||
PushLoc::ArgumentTable { offset } => Some((f.field, offset)),
|
||||
PushLoc::Push { .. } => None,
|
||||
})
|
||||
.collect();
|
||||
if spilled.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut members = Vec::with_capacity(spilled.len());
|
||||
let mut layout = Vec::with_capacity(spilled.len());
|
||||
for (field, offset) in &spilled {
|
||||
members.push(shape_type(mb, push::shape(*field))?);
|
||||
layout.push(MemberLayout {
|
||||
offset: *offset,
|
||||
matrix_stride: None,
|
||||
});
|
||||
}
|
||||
let block = mb.ty(Type::Struct {
|
||||
members: members.into(),
|
||||
layout: Some(StructLayout {
|
||||
rule: LayoutRule::Std140,
|
||||
block: true,
|
||||
non_writable: false,
|
||||
members: layout.into(),
|
||||
}),
|
||||
})?;
|
||||
let global = mb.resource(symbol(placement.stage), StorageClass::Uniform, block)?;
|
||||
Ok(Some(Table {
|
||||
global,
|
||||
fields: spilled.into_iter().map(|(f, _)| f).collect(),
|
||||
}))
|
||||
}
|
||||
|
||||
/// The bytes of the parameter block one load reads: a line of 16 bytes at a multiple of 16. The
|
||||
/// block's address is a multiple of 16 (the runtime's ring places every block so) and its size
|
||||
/// is one (`PushPlacement::argument_table_size`), so every line a field touches lies in the block.
|
||||
@@ -204,22 +137,3 @@ pub fn field_of_lines(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Load `field` from `table` in the open block, or `None` when the table does not hold it.
|
||||
pub fn read(
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
table: &Table,
|
||||
field: PushField,
|
||||
) -> BResult<Option<Value>> {
|
||||
let Some(i) = table.fields.iter().position(|f| *f == field) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let Ok(i) = u32::try_from(i) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let base = fb.module().global_value(table.global)?;
|
||||
let index = fb.u32_const(i)?;
|
||||
let index = fb.module().const_value(index)?;
|
||||
let ptr = fb.access_chain(base, &[index])?;
|
||||
Ok(Some(fb.load(ptr, MemAccess::default())?))
|
||||
}
|
||||
@@ -1013,7 +1013,6 @@ fn image_decl(s: &TileSlot) -> ImageDecl {
|
||||
level_views: None,
|
||||
extended: None,
|
||||
x_channel: false,
|
||||
parts: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -435,7 +435,7 @@ fn pointer_member(
|
||||
}
|
||||
}
|
||||
found
|
||||
.or(valueless.then_some(DemoteTy::FatPtr { wide: false }))
|
||||
.or(valueless.then_some(DemoteTy::FatPtr))
|
||||
.ok_or_else(not_lowered)
|
||||
}
|
||||
|
||||
@@ -615,7 +615,7 @@ fn member_constant(cx: &SelectCx<'_>, c: ConstId, want: &DemoteTy) -> Option<Low
|
||||
/// representation, which must be a pointer's.
|
||||
fn null_member(cx: &SelectCx<'_>, at: InstId, ty: TypeId) -> Result<ArithStrategy, Error> {
|
||||
match cx.lowered_repr(Value::Inst(at), ty)? {
|
||||
d @ (DemoteTy::FatPtr { .. }
|
||||
d @ (DemoteTy::FatPtr
|
||||
| DemoteTy::Address
|
||||
| DemoteTy::HandleIndex
|
||||
| DemoteTy::ArenaOffset) => Ok(ArithStrategy::Null(d)),
|
||||
@@ -766,10 +766,9 @@ pub fn null_value(
|
||||
d: &DemoteTy,
|
||||
) -> BResult<SValue> {
|
||||
match d {
|
||||
DemoteTy::FatPtr { .. }
|
||||
| DemoteTy::Address
|
||||
| DemoteTy::HandleIndex
|
||||
| DemoteTy::ArenaOffset => zero_value(cx, fb, d),
|
||||
DemoteTy::FatPtr | DemoteTy::Address | DemoteTy::HandleIndex | DemoteTy::ArenaOffset => {
|
||||
zero_value(cx, fb, d)
|
||||
}
|
||||
_ => Err(cx.fail("a null pointer in a representation of no pointer")),
|
||||
}
|
||||
}
|
||||
@@ -778,7 +777,7 @@ pub fn null_value(
|
||||
/// arith zero, or a composite of its members' zeros.
|
||||
fn zero_value(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, d: &DemoteTy) -> BResult<SValue> {
|
||||
match d {
|
||||
DemoteTy::FatPtr { .. } | DemoteTy::Address => {
|
||||
DemoteTy::FatPtr | DemoteTy::Address => {
|
||||
match crate::lower::access::pointer::null_value(fb, d)? {
|
||||
Some(x) => Ok(x),
|
||||
None => Err(cx.fail("a null fat pointer without a value")),
|
||||
@@ -790,7 +789,7 @@ fn zero_value(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, d: &DemoteTy) -
|
||||
if parts.iter().any(|p| {
|
||||
matches!(
|
||||
p,
|
||||
DemoteTy::FatPtr { .. }
|
||||
DemoteTy::FatPtr
|
||||
| DemoteTy::Address
|
||||
| DemoteTy::HandleIndex
|
||||
| DemoteTy::ArenaOffset
|
||||
|
||||
@@ -188,44 +188,6 @@ pub fn decode(
|
||||
value_of_codes(fb, form, c, half)
|
||||
}
|
||||
|
||||
/// The tile value of raw texel `raw` of a color attachment of `form` (a framebuffer fetch's
|
||||
/// read, a `float` and a `half` read alike): a `vec4` of `f32`, red first, each lane a `half`
|
||||
/// value. Metal's tile holds no extended-range color code above 1022: a linear form's code and
|
||||
/// `BGRA10_XR_sRGB`'s are clamped to 1022 and decoded ([`decode`]), `BGR10_XR_sRGB`'s and the
|
||||
/// two-plane twin's decoded and then clamped to the linear values of codes 0 and 1022,
|
||||
/// `[-384 / 510, 638 / 510]`; a padded form's every code is decoded as it is (code 1023 is one);
|
||||
/// each lane is the device's narrowing of that value to `half`. Alpha is [`decode`]'s. A padded
|
||||
/// form's fetch reads so on Metal: each loaded code's value rounded to `half`, a `float` input's
|
||||
/// too, an sRGB twin's colour through Metal's table (every code of each padded form on the M3 Max
|
||||
/// under macOS 27.0.1, `probes/padded_fetch.m` of the conformance crate).
|
||||
pub fn tile_value(fb: &mut FunctionBuilder<'_>, form: ExtendedRange, raw: Value) -> BResult<Value> {
|
||||
let c = codes(fb, form, raw)?;
|
||||
if form.padded() {
|
||||
let v = value_of_codes(fb, form, c, false)?;
|
||||
return narrow::round(fb, halves(), v);
|
||||
}
|
||||
let by_code = !form.srgb() || matches!(form, ExtendedRange::Bgra10 { .. });
|
||||
let c = match by_code {
|
||||
true => {
|
||||
let top = per_lane(fb, [1022, 1022, 1022, u32::MAX])?;
|
||||
fb.glsl(GlslOp::UMin, &[c, top])?
|
||||
}
|
||||
false => c,
|
||||
};
|
||||
let v = value_of_codes(fb, form, c, false)?;
|
||||
let v = match by_code {
|
||||
true => v,
|
||||
false => {
|
||||
let lo = (-384.0f64 / 510.0) as f32;
|
||||
let hi = (638.0f64 / 510.0) as f32;
|
||||
let lo = per_lane_f(fb, [lo, lo, lo, f32::NEG_INFINITY])?;
|
||||
let hi = per_lane_f(fb, [hi, hi, hi, f32::INFINITY])?;
|
||||
fb.glsl(GlslOp::FClamp, &[v, lo, hi])?
|
||||
}
|
||||
};
|
||||
narrow::round(fb, halves(), v)
|
||||
}
|
||||
|
||||
/// The `ivec4` type.
|
||||
fn ivec4(fb: &mut FunctionBuilder<'_>) -> BResult<crate::spirv::ids::TypeId> {
|
||||
let i32_ = fb.module().ty(Type::Int {
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
//! (the device's `Pow`, which the interpreter does not model) checked in the module and against
|
||||
//! Metal's tables.
|
||||
|
||||
use super::{decode, encode, tile_value};
|
||||
use super::{decode, encode};
|
||||
use crate::lower::arith::{FloatFmt, Form, Held};
|
||||
use crate::lower::stage_io::extended_color::bfloat_output;
|
||||
use crate::metal::format::extended_srgb::{SRGB_DECODE_STEPS, SRGB_ENCODE_FIRST};
|
||||
@@ -30,8 +30,6 @@ enum Op {
|
||||
DecodeHalf,
|
||||
/// The encode of a `vec4` of `f32` bits.
|
||||
Encode,
|
||||
/// The tile value of a raw texel.
|
||||
Tile,
|
||||
/// A render pass's store of a fragment function's output (`vec4` of `f32` bits, of the
|
||||
/// format, `half` values held as `f32`) to a bfloat attachment of a pipeline at
|
||||
/// `textureWriteRoundingMode` `NearestEven` where the flag is set
|
||||
@@ -117,10 +115,6 @@ fn kernel(form: ExtendedRange, op: Op) -> BResult<TypedModule> {
|
||||
let v = decode(&mut f, form, x, true)?;
|
||||
f.convert(ConvOp::Bitcast, v, uvec4)?
|
||||
}
|
||||
Op::Tile => {
|
||||
let v = tile_value(&mut f, form, x)?;
|
||||
f.convert(ConvOp::Bitcast, v, uvec4)?
|
||||
}
|
||||
Op::Output(nearest_even, fmt) => {
|
||||
let v = f.convert(ConvOp::Bitcast, x, vec4)?;
|
||||
let rounding = match nearest_even {
|
||||
@@ -401,9 +395,6 @@ fn srgb_forms_take_the_transfer_by_the_devices_pow() {
|
||||
if form != ExtendedRange::Rg10X12Srgb {
|
||||
ops.extend([Op::Decode, Op::DecodeHalf]);
|
||||
}
|
||||
if form.srgb() {
|
||||
ops.push(Op::Tile);
|
||||
}
|
||||
for op in ops {
|
||||
let words = module_words(kernel(form, op).expect("kernel"));
|
||||
assert_eq!(pow_and_table(&words), (true, false), "{form:?}");
|
||||
@@ -489,51 +480,6 @@ fn half(h: u16) -> f32 {
|
||||
crate::float16::f16_bits_to_f32(h)
|
||||
}
|
||||
|
||||
/// The tile value of a texel of linear `form` whose codes are `rgba` (a two-plane form's alpha its
|
||||
/// byte), as the module docs of `tile_value` state the rule: a code above 1022 as 1022, each lane
|
||||
/// the device's value narrowed to `half`, nearest even. The `_sRGB` forms' are the device's
|
||||
/// (the interpreter models no `Pow`).
|
||||
pub(crate) fn tile_model(form: ExtendedRange, rgba: [u32; 4]) -> [f32; 4] {
|
||||
assert!(
|
||||
!form.srgb() && !form.padded() && !form.bfloat(),
|
||||
"{form:?}: not a linear form"
|
||||
);
|
||||
let color = |c: u32| color_value(c.min(1022));
|
||||
[
|
||||
color(rgba[0]),
|
||||
color(rgba[1]),
|
||||
color(rgba[2]),
|
||||
alpha_value(form, rgba[3]),
|
||||
]
|
||||
.map(|v| to_half(f64::from(v), false))
|
||||
}
|
||||
|
||||
/// Every code of every channel of the linear forms reads its tile value, whatever the bits Metal
|
||||
/// does not read hold: a code above 1022 as 1022, each lane narrowed to `half`. The ends are the
|
||||
/// blend's source range.
|
||||
#[test]
|
||||
fn every_code_reads_its_tile_value() {
|
||||
for form in LINEAR {
|
||||
let alpha = |c: u32| match form {
|
||||
ExtendedRange::Planes { .. } => c % 256,
|
||||
_ => c,
|
||||
};
|
||||
let codes = |c: u32| [c, 1023 - c, (c * 7) % 1024, alpha(c)];
|
||||
let lanes: Vec<[u32; 4]> = (0..1024u32).map(|c| raw(form, codes(c), c * 13)).collect();
|
||||
let got = run(form, Op::Tile, &lanes);
|
||||
for (c, g) in (0..1024u32).zip(&got) {
|
||||
let want = tile_model(form, codes(c));
|
||||
assert_eq!(*g, want.map(f32::to_bits), "{form:?} code {c}");
|
||||
}
|
||||
// Codes 0, 1022 and 1023: the linear values of codes 0 and 1022, `-384 / 510` and
|
||||
// `638 / 510`, rounded to `half`, nearest even.
|
||||
let (lo, hi) = (-1542.0 / 2048.0, 1281.0 / 1024.0);
|
||||
assert_eq!(f32::from_bits(got[0][0]), lo, "{form:?}");
|
||||
assert_eq!(f32::from_bits(got[0][1]), hi, "{form:?}");
|
||||
assert_eq!(f32::from_bits(got[1][1]), hi, "{form:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A padded 10-bit form reads every 16-bit word as `float(c)` of the code `c` in its top 10 bits
|
||||
/// times the `f32` nearest `1 / 1023` (a `half` result that value narrowed to nearest even), blue
|
||||
/// 0 and alpha 1, whatever the low 6 bits hold (every word; `RG10Unorm_X12_sRGB` reads its codes
|
||||
|
||||
@@ -880,10 +880,9 @@ pub fn spirv_type(mb: &mut ModuleBuilder, d: &DemoteTy) -> BResult<Option<TypeId
|
||||
})?
|
||||
}
|
||||
// A pointer member of a member-wise phi's composite is the access family's.
|
||||
DemoteTy::FatPtr { .. }
|
||||
| DemoteTy::Address
|
||||
| DemoteTy::ArenaOffset
|
||||
| DemoteTy::HandleIndex => return crate::lower::access::spirv_type(mb, d),
|
||||
DemoteTy::FatPtr | DemoteTy::Address | DemoteTy::ArenaOffset | DemoteTy::HandleIndex => {
|
||||
return crate::lower::access::spirv_type(mb, d)
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
|
||||
@@ -12,9 +12,9 @@
|
||||
//! [`DispatchPlan::keys`]): link gives a key one id over the pipeline, and a mesh render pipeline's
|
||||
//! object and mesh threadgroups take separate sizes.
|
||||
//!
|
||||
//! **Deep threadgroups.** A kernel of the `Spec` form declares `SpecKey::DeepThreadgroup` ([`DispatchPlan::deep`]), under
|
||||
//! which its `WorkgroupSize` is `(sn, 1, 1)`, `sn = sx·sy·sz`, and its position in the threadgroup
|
||||
//! `LocalInvocationIndex`
|
||||
//! **Deep threadgroups.** A kernel of the `Spec` form declares `SpecKey::DeepThreadgroup`
|
||||
//! ([`DispatchPlan::deep`]), under which its `WorkgroupSize` is `(sn, 1, 1)`, `sn = sx·sy·sz`, and
|
||||
//! its position in the threadgroup `LocalInvocationIndex`
|
||||
//! unflattened over `(sx, sy, sz)`: Metal allows 1024 threads along `z`, where a device's
|
||||
//! `maxComputeWorkGroupSize[2]` may hold 64, and a threadgroup of at most 1024 threads in one row
|
||||
//! fits every device the profile serves. The linear index keeps its value, `x` fastest either
|
||||
@@ -81,15 +81,14 @@
|
||||
//! as Metal's object grid is (measured: an indirect draw runs every threadgroup and reports the
|
||||
//! grid its wrapped threads fill); it is `NumWorkgroups` wherever no axis wraps.
|
||||
//!
|
||||
//! Under the identity domains ([`DispatchPlan::identity`]) every dispatch states its region,
|
||||
//! and the region's grid selects the grid builtins' form: a dispatch the host knows
|
||||
//! (`dispatchThreads`, `dispatchThreadgroups`, and each piece of a split of either) states Metal's
|
||||
//! `threads_per_grid` in `region[1].xyz`, so the pieces of a split read Metal's whole grid; an
|
||||
//! indirect dispatch states `region[1].xyz = 0` and takes the single-region form, its grid
|
||||
//! `NumWorkgroups · L`, which needs its workgroup size to be Metal's threadgroup size. So one
|
||||
//! pipeline runs every dispatch of a threadgroup size. The base is `region[0].xyz` on every
|
||||
//! dispatch (0 for one that is not split and for an indirect one), and `MultiRegion` says only
|
||||
//! whether `L` is the region's nominal size (1, a region whose threadgroup size is not its
|
||||
//! Every dispatch states its region, and the region's grid selects the grid builtins' form: a
|
||||
//! dispatch the host knows (`dispatchThreads`, `dispatchThreadgroups`, and each piece of a split of
|
||||
//! either) states Metal's `threads_per_grid` in `region[1].xyz`, so the pieces of a split read
|
||||
//! Metal's whole grid; an indirect dispatch states `region[1].xyz = 0` and takes the single-region
|
||||
//! form, its grid `NumWorkgroups · L`, which needs its workgroup size to be Metal's threadgroup
|
||||
//! size. So one pipeline runs every dispatch of a threadgroup size. The base is `region[0].xyz` on
|
||||
//! every dispatch (0 for one that is not split and for an indirect one), and `MultiRegion` says
|
||||
//! only whether `L` is the region's nominal size (1, a region whose threadgroup size is not its
|
||||
//! pipeline's, as the binder's edge regions are) or the pipeline's `(sx, sy, sz)` (0, the
|
||||
//! default): a dispatch at its pipeline's size computes its positions from that size and the base
|
||||
//! alone, and the driver folds the region's decode away when it specializes.
|
||||
@@ -130,7 +129,8 @@
|
||||
//! **Grid tiles** ([`DispatchPlan::grid_edge`], `RuntimeFact::GridTiles`). A kernel that does not
|
||||
//! observe its threadgroup partition reads only `thread_position_in_grid` and `threads_per_grid`,
|
||||
//! so neither Metal's threadgroups nor their partial edges reach it: only the set of positions
|
||||
//! does. Under the identity domains its partial-threadgroups variant runs its grid in tiles. Under `MultiRegion` 1 its workgroup of
|
||||
//! does. Its partial-threadgroups variant runs its grid in tiles. Under `MultiRegion` 1 its
|
||||
//! workgroup of
|
||||
//! [`GRID_TILE_THREADS`] is one tile, whose power-of-two sides the region's nominal size gives
|
||||
//! ([`grid_tile`] picks them from the grid's extents): the invocation's position is the tile's
|
||||
//! origin `(base + WorkgroupId) << s` plus `LocalInvocationIndex` masked and shifted by the sides,
|
||||
@@ -454,21 +454,6 @@ pub struct PlannedParam {
|
||||
pub projection: Projection,
|
||||
}
|
||||
|
||||
/// How a kernel that reads a grid builtin tells a region of a dispatch the host knows
|
||||
/// (`dispatchThreads`, `dispatchThreadgroups`, or a split of either, whose region the
|
||||
/// `DispatchRegion` push field states) from a whole dispatch whose grid the GPU holds (an
|
||||
/// indirect one, whose grid is `NumWorkgroups · L`).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum RegionSelect {
|
||||
/// The `MultiRegion` specialization constant.
|
||||
Spec(ConstId),
|
||||
/// Under the identity domains, the region's grid: `region[1].xyz` is Metal's
|
||||
/// `threads_per_grid` for every dispatch the host knows, and all 0 for an indirect one, so one
|
||||
/// pipeline runs both. The base is the region's on every dispatch, and the `MultiRegion`
|
||||
/// constant says only whether `L` is the region's nominal size.
|
||||
Sized(ConstId),
|
||||
}
|
||||
|
||||
/// How a kernel's Vulkan workgroup size is expressed.
|
||||
#[non_exhaustive]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
@@ -523,23 +508,21 @@ pub struct DispatchPlan {
|
||||
/// threadgroup runs only the threads Metal's partial threadgroup has (the module docs). It
|
||||
/// declares `MultiRegion` and reads the region whatever builtins it reads.
|
||||
pub partial_groups: bool,
|
||||
/// Of `partial_groups`, a kernel that does not observe its threadgroup partition, under the
|
||||
/// identity domains: under `MultiRegion` 1 its
|
||||
/// Of `partial_groups`, a kernel that does not observe its threadgroup partition: under
|
||||
/// `MultiRegion` 1 its
|
||||
/// workgroup is one tile of the grid whose power-of-two sides the region's nominal size gives
|
||||
/// ([`grid_tile`]), and an invocation past the region's grid returns before the body, whatever
|
||||
/// the region's flags; under `MultiRegion` 0 it runs at its pipeline's size (the module docs'
|
||||
/// grid tiles).
|
||||
pub grid_edge: bool,
|
||||
/// Under the identity domains a kernel tells a region from an indirect dispatch by the
|
||||
/// region's grid, and reads its base and `L` as [`RegionSelect::Sized`] says.
|
||||
pub identity: bool,
|
||||
/// The subgroup size the pipeline pins in a flattened tier
|
||||
/// (`SubgroupRequirement::size`): `lin` multiplies the subgroup index by it as a constant and
|
||||
/// never reads `SubgroupSize`. `None` outside the flattened tiers and where the stage pins no
|
||||
/// size, where `lin` reads the builtin.
|
||||
pub pinned_subgroup_size: Option<u32>,
|
||||
/// A kernel of the [`LocalSizeForm::Spec`] form without compute derivatives (whose quads are two-dimensional): it declares
|
||||
/// `SpecKey::DeepThreadgroup`, under which its threadgroup runs as one row (the module docs).
|
||||
/// A kernel of the [`LocalSizeForm::Spec`] form without compute derivatives (whose quads are
|
||||
/// two-dimensional): it declares `SpecKey::DeepThreadgroup`, under which its threadgroup runs
|
||||
/// as one row (the module docs).
|
||||
pub deep: bool,
|
||||
/// A kernel whose private arena lives in device memory (`memory::plan::ArenaLayout::device`):
|
||||
/// each invocation reaches its slot by its index in its dispatch ([`KernelDecl::arena_slot`]).
|
||||
@@ -590,13 +573,11 @@ fn reads_region(b: KernelBuiltin, tile_sized: bool) -> bool {
|
||||
|
||||
/// Whether a kernel's partial-threadgroups variant runs its grid in tiles
|
||||
/// ([`DispatchPlan::grid_edge`]): a kernel that does not observe its threadgroup partition
|
||||
/// (`pipeline::compile::partition`, decided from its AIR) under the identity domains, whose
|
||||
/// regions state their base on every dispatch ([`RegionSelect::Sized`]).
|
||||
/// (`pipeline::compile::partition`, decided from its AIR), whose regions state their base on
|
||||
/// every dispatch (the module docs).
|
||||
fn grid_edge(cx: &SelectCx<'_>) -> bool {
|
||||
use crate::pipeline::compile::partition::{partition, Partition};
|
||||
cx.stage == crate::pipeline::sym::Stage::Kernel
|
||||
&& crate::lower::access::identity(cx.profile)
|
||||
&& partition(cx.entry) == Partition::Oblivious
|
||||
cx.stage == crate::pipeline::sym::Stage::Kernel && partition(cx.entry) == Partition::Oblivious
|
||||
}
|
||||
|
||||
/// Plan the kernel's dispatch under subgroup tier `tier`: the local-size form (flattened in the
|
||||
@@ -728,7 +709,6 @@ pub fn plan_kernel(cx: &mut SelectCx<'_>, tier: Tier) -> Result<DispatchPlan, Er
|
||||
object_grid: !folded_groups && cx.stage == crate::pipeline::sym::Stage::Object,
|
||||
partial_groups,
|
||||
grid_edge,
|
||||
identity: crate::lower::access::identity(cx.profile),
|
||||
pinned_subgroup_size,
|
||||
deep,
|
||||
private_arena: cx.memory.priv_arena.device,
|
||||
@@ -976,8 +956,14 @@ pub struct KernelDecl {
|
||||
workgroup: ConstId,
|
||||
/// `SpecKey::DeepThreadgroup`, where the plan declares it ([`DispatchPlan::deep`]).
|
||||
deep: Option<ConstId>,
|
||||
/// How the kernel tells a region, when it reads a grid builtin.
|
||||
multi_region: Option<RegionSelect>,
|
||||
/// The `MultiRegion` specialization constant, when the kernel reads a grid builtin. A kernel
|
||||
/// tells a region of a dispatch the host knows (`dispatchThreads`, `dispatchThreadgroups`, or
|
||||
/// a split of either, whose region the `DispatchRegion` push field states) from a whole
|
||||
/// dispatch whose grid the GPU holds (an indirect one) by the region's grid: `region[1].xyz`
|
||||
/// is Metal's `threads_per_grid` for every dispatch the host knows, and all 0 for an indirect
|
||||
/// one, so one pipeline runs both. The base is the region's on every dispatch, and the
|
||||
/// constant says only whether `L` is the region's nominal size.
|
||||
multi_region: Option<ConstId>,
|
||||
local_id: Option<GlobalId>,
|
||||
local_index: Option<GlobalId>,
|
||||
workgroup_id: Option<GlobalId>,
|
||||
@@ -1288,19 +1274,15 @@ impl KernelDecl {
|
||||
mb.workgroup_size(sn, one, one)?
|
||||
}
|
||||
};
|
||||
let multi_region = match (dp.multi_region, dp.identity) {
|
||||
(false, _) => None,
|
||||
(true, identity) => {
|
||||
let multi_region = match dp.multi_region {
|
||||
false => None,
|
||||
true => {
|
||||
let b = mb.ty(Type::Bool)?;
|
||||
let mr = mb.spec(
|
||||
Some(mb.spec(
|
||||
keys.multi_region,
|
||||
b,
|
||||
ConstBits(u64::from(defaults.multi_region)),
|
||||
)?;
|
||||
Some(match identity {
|
||||
true => RegionSelect::Sized(mr),
|
||||
false => RegionSelect::Spec(mr),
|
||||
})
|
||||
)?)
|
||||
}
|
||||
};
|
||||
let needs = Needs::of(dp);
|
||||
@@ -1590,11 +1572,11 @@ impl KernelDecl {
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
region: &mut RegionFn<'_>,
|
||||
) -> BResult<Option<(SValue, SValue)>> {
|
||||
let (true, false, Some(sel)) = (self.partial_groups, self.grid_edge, self.multi_region)
|
||||
let (true, false, Some(_)) = (self.partial_groups, self.grid_edge, self.multi_region)
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mr = self.selected(fb, sel, region)?;
|
||||
let mr = self.selected(fb, region)?;
|
||||
let r = region(fb)?;
|
||||
let r1 = fb.composite_extract(r, &[1])?;
|
||||
let flags = fb.composite_extract(r1, &[3])?;
|
||||
@@ -1655,7 +1637,7 @@ impl KernelDecl {
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
region: &mut RegionFn<'_>,
|
||||
) -> BResult<SValue> {
|
||||
let Some(RegionSelect::Sized(sized)) = self.multi_region else {
|
||||
let Some(sized) = self.multi_region else {
|
||||
return Err(dangling_value());
|
||||
};
|
||||
let r = region(fb)?;
|
||||
@@ -1699,7 +1681,7 @@ impl KernelDecl {
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
region: &mut RegionFn<'_>,
|
||||
) -> BResult<SValue> {
|
||||
let Some(RegionSelect::Sized(_)) = self.multi_region else {
|
||||
let Some(_) = self.multi_region else {
|
||||
return Err(dangling_value());
|
||||
};
|
||||
let r = region(fb)?;
|
||||
@@ -1720,7 +1702,7 @@ impl KernelDecl {
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
region: &mut RegionFn<'_>,
|
||||
) -> BResult<SValue> {
|
||||
let Some(RegionSelect::Sized(_)) = self.multi_region else {
|
||||
let Some(_) = self.multi_region else {
|
||||
return Err(dangling_value());
|
||||
};
|
||||
let r = region(fb)?;
|
||||
@@ -1748,8 +1730,8 @@ impl KernelDecl {
|
||||
/// 2 quads (the last 1 where `qh` is odd), within such a row over its blocks 4 quads wide (the
|
||||
/// last narrower), and within a block over its quads row-major: so a full column is `8 · qh`
|
||||
/// quads, its row `2 · cw` for a column `cw` wide, and its block `4 · rh` for a row `rh` high.
|
||||
/// Every divisor is at least 1 for any local size, so the shapes the binder refuses never divide
|
||||
/// by zero.
|
||||
/// Every divisor is at least 1 for any local size, so the shapes the binder refuses never
|
||||
/// divide by zero.
|
||||
fn tile_pos(&self, fb: &mut FunctionBuilder<'_>, lin: SValue) -> BResult<SValue> {
|
||||
let bin = |fb: &mut FunctionBuilder<'_>, op, a, n: u32| -> BResult<SValue> {
|
||||
let n = Self::k(fb, n)?;
|
||||
@@ -1868,8 +1850,8 @@ impl KernelDecl {
|
||||
}
|
||||
|
||||
/// The region base and Metal's nominal threadgroup size `L` under `MultiRegion`, or `(0, (sx,
|
||||
/// sy, sz))` when the kernel reads no grid builtin. Under [`RegionSelect::Sized`] the base is
|
||||
/// the region's whatever `MultiRegion` says, and `L` the region's nominal size only under it,
|
||||
/// sy, sz))` when the kernel reads no grid builtin. The base is the region's whatever
|
||||
/// `MultiRegion` says, and `L` the region's nominal size only under it,
|
||||
/// so a pipeline specialized at 0 reads the base alone.
|
||||
fn region(
|
||||
&self,
|
||||
@@ -1877,7 +1859,7 @@ impl KernelDecl {
|
||||
region: &mut RegionFn<'_>,
|
||||
) -> BResult<(Option<SValue>, SValue)> {
|
||||
let s = self.size3(fb)?;
|
||||
let Some(sel) = self.multi_region else {
|
||||
let Some(sized) = self.multi_region else {
|
||||
return Ok((None, s));
|
||||
};
|
||||
let r = region(fb)?;
|
||||
@@ -1894,20 +1876,9 @@ impl KernelDecl {
|
||||
axes.push(fb.binary(BinOp::IAdd, bits, one)?);
|
||||
}
|
||||
let nominal = fb.composite_construct(self.uvec3, &axes)?;
|
||||
match sel {
|
||||
RegionSelect::Spec(_) => {
|
||||
let mr = self.selected(fb, sel, region)?;
|
||||
let zero = self.splat(fb, 0)?;
|
||||
let base = fb.select(mr, base, zero)?;
|
||||
let l = fb.select(mr, nominal, s)?;
|
||||
Ok((Some(base), l))
|
||||
}
|
||||
RegionSelect::Sized(sized) => {
|
||||
let sized = fb.module().const_value(sized)?;
|
||||
let l = fb.select(sized, nominal, s)?;
|
||||
Ok((Some(base), l))
|
||||
}
|
||||
}
|
||||
let sized = fb.module().const_value(sized)?;
|
||||
let l = fb.select(sized, nominal, s)?;
|
||||
Ok((Some(base), l))
|
||||
}
|
||||
|
||||
/// `threads_per_grid` under `MultiRegion`: `region[1].xyz`.
|
||||
@@ -1916,42 +1887,32 @@ impl KernelDecl {
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
region: &mut RegionFn<'_>,
|
||||
) -> BResult<Option<(SValue, SValue)>> {
|
||||
let Some(sel) = self.multi_region else {
|
||||
let Some(_) = self.multi_region else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mr = self.selected(fb, sel, region)?;
|
||||
let mr = self.selected(fb, region)?;
|
||||
let r = region(fb)?;
|
||||
let r1 = fb.composite_extract(r, &[1])?;
|
||||
Ok(Some((mr, fb.vector_shuffle(r1, r1, &[0, 1, 2])?)))
|
||||
}
|
||||
|
||||
/// Whether the dispatch is a region (a `bool`): `MultiRegion`, or under the identity domains
|
||||
/// whether the region's grid `region[1].xyz` is not all 0.
|
||||
fn selected(
|
||||
&self,
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
sel: RegionSelect,
|
||||
region: &mut RegionFn<'_>,
|
||||
) -> BResult<SValue> {
|
||||
match sel {
|
||||
RegionSelect::Spec(mr) => fb.module().const_value(mr),
|
||||
RegionSelect::Sized(_) => {
|
||||
let r = region(fb)?;
|
||||
let r1 = fb.composite_extract(r, &[1])?;
|
||||
let [x, y, z] = [0, 1, 2].map(|i| fb.composite_extract(r1, &[i]));
|
||||
let xy = fb.binary(BinOp::BitwiseOr, x?, y?)?;
|
||||
let any = fb.binary(BinOp::BitwiseOr, xy, z?)?;
|
||||
let zero = Self::k(fb, 0)?;
|
||||
fb.binary(BinOp::INotEqual, any, zero)
|
||||
}
|
||||
}
|
||||
/// Whether the dispatch is a region (a `bool`): whether the region's grid `region[1].xyz` is
|
||||
/// not all 0.
|
||||
fn selected(&self, fb: &mut FunctionBuilder<'_>, region: &mut RegionFn<'_>) -> BResult<SValue> {
|
||||
let r = region(fb)?;
|
||||
let r1 = fb.composite_extract(r, &[1])?;
|
||||
let [x, y, z] = [0, 1, 2].map(|i| fb.composite_extract(r1, &[i]));
|
||||
let xy = fb.binary(BinOp::BitwiseOr, x?, y?)?;
|
||||
let any = fb.binary(BinOp::BitwiseOr, xy, z?)?;
|
||||
let zero = Self::k(fb, 0)?;
|
||||
fb.binary(BinOp::INotEqual, any, zero)
|
||||
}
|
||||
|
||||
/// A flat grid's thread position in the grid (a `uvec3`) and whether the invocation is inside
|
||||
/// the grid: its index `((wz · ny + wy) · nx + wx) · N + LocalInvocationIndex` over the
|
||||
/// dispatch (`lin` for the call's threadgroups, [`Self::lin`]), with `N = sx·sy·sz`, counted
|
||||
/// over `threads_per_grid` (`region[1].xyz`) `x` fastest. Inside the grid each axis's position is below its size, so it fits its `u32`;
|
||||
/// past it the position is unused.
|
||||
/// over `threads_per_grid` (`region[1].xyz`) `x` fastest. Inside the grid each axis's position
|
||||
/// is below its size, so it fits its `u32`; past it the position is unused.
|
||||
///
|
||||
/// Three arms, each chosen by values uniform over the workgroup, so a workgroup takes one:
|
||||
///
|
||||
|
||||
@@ -5,7 +5,6 @@
|
||||
//! must be indistinguishable from the single dispatch.
|
||||
|
||||
use super::*;
|
||||
use crate::device::DevicePolicy;
|
||||
use crate::pipeline::sym::{ResourceKind, ResourceSlot, Stage};
|
||||
use crate::spirv::interp::{run, Buffer, Config, Order, Resources, SubgroupSize};
|
||||
use crate::spirv::ir::{natural_layout, ExecModel, LayoutRule, StorageClass, TypedModule};
|
||||
@@ -38,7 +37,6 @@ fn plan(form: LocalSizeForm, multi_region: bool) -> DispatchPlan {
|
||||
object_grid: false,
|
||||
partial_groups: false,
|
||||
grid_edge: false,
|
||||
identity: false,
|
||||
pinned_subgroup_size: None,
|
||||
deep: false,
|
||||
private_arena: false,
|
||||
@@ -743,7 +741,7 @@ fn builtin_facts_and_projections() {
|
||||
#[test]
|
||||
fn derivation_modules_are_valid() {
|
||||
for stem in ["moltenvk-m3", "runtime-floor"] {
|
||||
let p = crate::pipeline::testing::profile(stem, DevicePolicy::RESIDENT_TABLES).expect(stem);
|
||||
let p = crate::pipeline::testing::profile(stem).expect(stem);
|
||||
for form in [LocalSizeForm::Spec, LocalSizeForm::Flat] {
|
||||
for mr in [false, true] {
|
||||
assert_valid(module(&plan(form, mr)), &p);
|
||||
@@ -864,8 +862,7 @@ fn the_flat_variant_s_64_bit_division_is_exact() {
|
||||
)
|
||||
.expect("entry");
|
||||
let m = mb.finalize().expect("finalize");
|
||||
let p = crate::pipeline::testing::profile("intel-arl-anv", DevicePolicy::RESIDENT_TABLES)
|
||||
.expect("profile");
|
||||
let p = crate::pipeline::testing::profile("intel-arl-anv").expect("profile");
|
||||
assert_valid(m.clone(), &p);
|
||||
let bytes: Vec<u8> = cases
|
||||
.iter()
|
||||
|
||||
@@ -186,8 +186,7 @@ pub struct EmitCx<'a> {
|
||||
/// The block the entry hooks end in, where the walk of the body starts: it dominates every
|
||||
/// block of the body, so its memo entries outlive the block that emitted them too. It is the
|
||||
/// entry block but where a hook closed a construct there: a dispatch past its grid
|
||||
/// (`dispatch::emit_entry`) returns from an arm, and the hooks after it, the sink's address
|
||||
/// among them (`access::dynamic::emit_entry`), run in its merge.
|
||||
/// (`dispatch::emit_entry`) returns from an arm, and the hooks after it run in its merge.
|
||||
hooks_block: Option<SBlockId>,
|
||||
/// While a workgroup synchronization of a predicated walk is emitted, the calling invocation's
|
||||
/// live flag: a lane that is not live takes part with null operands. `None`: every invocation
|
||||
@@ -244,19 +243,12 @@ enum Invariant {
|
||||
/// A kernel's slot of the runtime's private arena, placed as a pointer to its words
|
||||
/// ([`EmitCx::arena_slot`]), in the function's first block.
|
||||
ArenaSlot,
|
||||
/// The table word of the argument buffer's sampler of a handle, tested for a cubic filter
|
||||
/// (`sampler::emit`'s reach test): an operation through the same handle where an earlier test
|
||||
/// dominates it ran that test on the same sampler, so it needs none of its own.
|
||||
CubicTested(ValueId),
|
||||
/// An indexed capture form's raw index (`stage_io::read_captured_index`), read at entry
|
||||
/// (`stage_io::emit_draw_entry`): the index buffer is read-only to the draw.
|
||||
CapturedIndex,
|
||||
/// The private list form's base vertex (`stage_io::read_listed_base`), read at entry
|
||||
/// (`stage_io::emit_draw_entry`): the list is read-only to the draw.
|
||||
ListedBase,
|
||||
/// The root table's sink address (`access::dynamic::read_sink_host`), read at entry
|
||||
/// (`access::dynamic::emit_entry`): the root table is read-only to the dispatch.
|
||||
SinkHost,
|
||||
/// A checked slot's `PushField::SlotBounds` split ([`EmitCx::slot_bounds`]): its buffer's
|
||||
/// bytes before the bind offset (`false`) or its length (`true`).
|
||||
Bounds(SlotRef, bool),
|
||||
@@ -408,18 +400,6 @@ impl<'a> EmitCx<'a> {
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// Whether the cubic reach test of the argument buffer's sampler of `handle` ran where it
|
||||
/// dominates the open block ([`EmitCx::cubic_tested`] recorded it there).
|
||||
pub(crate) fn cubic_test_dominates(&self, fb: &FunctionBuilder<'_>, handle: ValueId) -> bool {
|
||||
self.recall(fb, Invariant::CubicTested(handle)).is_some()
|
||||
}
|
||||
|
||||
/// Record that the cubic reach test of the argument buffer's sampler of `handle`, which read
|
||||
/// `word`, ran in the open block.
|
||||
pub(crate) fn cubic_tested(&mut self, fb: &FunctionBuilder<'_>, handle: ValueId, word: SValue) {
|
||||
self.remember(fb, Invariant::CubicTested(handle), word);
|
||||
}
|
||||
|
||||
/// The first word of a fragment function's tile memory in the pass's buffer, the tile that
|
||||
/// `tile` places (`access::tile_memory::base`), computed once where it dominates:
|
||||
/// `access::tile_memory::emit_entry` computes it in the function's first block.
|
||||
@@ -517,17 +497,6 @@ impl<'a> EmitCx<'a> {
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// The root table's sink address, read once where it dominates: `access::dynamic::emit_entry`
|
||||
/// reads it in the block the entry hooks end in, so no wide access reads the table for it.
|
||||
pub(crate) fn sink_host(&mut self, fb: &mut FunctionBuilder<'_>) -> BResult<SValue> {
|
||||
if let Some(v) = self.recall(fb, Invariant::SinkHost) {
|
||||
return Ok(v);
|
||||
}
|
||||
let v = access::dynamic::read_sink_host(self, fb)?;
|
||||
self.remember(fb, Invariant::SinkHost, v);
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// The work before the body: load each push field the plan places once, in the function's first
|
||||
/// block, where it dominates every block. Where the body first reads a field never moves its
|
||||
/// load, so a read that canonicalization deletes cannot make the others load it again; a placed
|
||||
@@ -560,15 +529,13 @@ impl<'a> EmitCx<'a> {
|
||||
self.fold_tail(fb)?;
|
||||
}
|
||||
}
|
||||
// Under the identity domains each slot's direct base and Metal address, made here, before
|
||||
// the hooks and the body: every block recalls them, so every application of a function
|
||||
// the body repeats reads them from before it and the applications stay the same code,
|
||||
// which `spirv::roll` writes once. One nothing reads leaves with the other unused values.
|
||||
if plan.families.access.identity {
|
||||
for placed in &plan.push.fields {
|
||||
if let PushField::SlotGuestBase(slot) = placed.field {
|
||||
access::pointer::make_ahead(self, fb, slot)?;
|
||||
}
|
||||
// Each slot's direct base and Metal address, made here, before the hooks and the body:
|
||||
// every block recalls them, so every application of a function the body repeats reads
|
||||
// them from before it and the applications stay the same code, which `spirv::roll` writes
|
||||
// once. One nothing reads leaves with the other unused values.
|
||||
for placed in &plan.push.fields {
|
||||
if let PushField::SlotGuestBase(slot) = placed.field {
|
||||
access::pointer::make_ahead(self, fb, slot)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
@@ -823,7 +790,7 @@ impl<'a> EmitCx<'a> {
|
||||
}
|
||||
|
||||
/// Bind AIR value `v` to `x` for the whole function: `x` was emitted by the entry hook
|
||||
/// (`stage_io::emit_entry`, `access::dynamic::emit_entry`) before the walk, in a block that
|
||||
/// (`stage_io::emit_entry`) before the walk, in a block that
|
||||
/// dominates every block of the body (the function's first, or a merged vertex's search's
|
||||
/// merge, `stage_io::emit_draw_entry`), so opening a block does not forget it.
|
||||
pub fn hold(&mut self, v: ValueId, x: SValue) {
|
||||
@@ -1372,7 +1339,7 @@ impl<'a> Emitter<'a> {
|
||||
impl CodeEmitter for Emitter<'_> {
|
||||
fn var_type(&mut self, ty: &DemoteTy, m: &mut ModuleBuilder) -> BResult<TypeId> {
|
||||
let found = match ty {
|
||||
DemoteTy::FatPtr { .. }
|
||||
DemoteTy::FatPtr
|
||||
| DemoteTy::Address
|
||||
| DemoteTy::ArenaOffset
|
||||
| DemoteTy::HandleIndex => access::spirv_type(m, ty)?,
|
||||
@@ -1672,7 +1639,6 @@ pub fn emit_module(e: &Entry, plan: &Plan, m: &mut Meter) -> Result<Emitted, Err
|
||||
// What the invocation draws (a merged draw's command and its slot tables) before
|
||||
// any hook reads a slot table.
|
||||
.and_then(|()| stage_io::emit_draw_entry(&mut em.cx, &mut fb))
|
||||
.and_then(|()| access::dynamic::emit_entry(&mut em.cx, &mut fb))
|
||||
.and_then(|()| stage_io::emit_entry(&mut em.cx, &mut fb))
|
||||
.and_then(|()| tessellation::emit_entry(&mut em.cx, &mut fb))
|
||||
.and_then(|()| fragment::emit_entry(&mut em.cx, &mut fb))
|
||||
|
||||
@@ -1,18 +1,16 @@
|
||||
//! Framebuffer fetch: `[[color(n)]]` fragment inputs read through input attachments.
|
||||
//! Framebuffer fetch: `[[color(n)]]` fragment inputs read through pushed textures.
|
||||
//!
|
||||
//! Each color index a function reads is one `SubpassData` image, declared as the descriptor
|
||||
//! symbol `ResourceSlot{Fragment, InputAttachment(n), n}` (serialization decorates it
|
||||
//! `InputAttachmentIndex n`, and link lists it in `GraphicsState::input_attachments`). A read is
|
||||
//! `OpImageRead` at offset `(0, 0)`, the calling fragment's own texel, taken to the parameter's
|
||||
//! lanes and brought to its lowered representation like a stage input: the image's sampled type is
|
||||
//! `float` for float colors (a `half` is rounded to its format) and `uint` for integer colors
|
||||
//! (masked to the AIR width). Integer colors of a signed format read the same bits through a `uint`
|
||||
//! image; like the `uint` color outputs, link must check the attachment format's class against the
|
||||
//! declared one.
|
||||
//! No descriptor holds a color a function reads: the function reads it through the element of the
|
||||
//! sampled-texture array the consumer pushes for it (`PushField::FetchedColor`), a view of the
|
||||
//! attachment's own texels of the class [`texture_class`] names. A read is a fetch at level 0 of
|
||||
//! the calling fragment's own pixel, taken to the parameter's lanes and brought to its lowered
|
||||
//! representation like a stage input: the element's sampled type is `float` for float colors (a
|
||||
//! `half` is rounded to its format) and the attachment's integer class for integer colors (masked
|
||||
//! to the AIR width).
|
||||
//!
|
||||
//! **Ordering**: Metal orders a fetch after every earlier fragment of the pixel, of the draw and
|
||||
//! of earlier draws. Vulkan orders an earlier draw's color write before
|
||||
//! a later draw's input attachment read of the subpass by a barrier of the subpass's dependency on
|
||||
//! a later draw's read of the attachment by a barrier of the subpass's dependency on
|
||||
//! itself, by region, which the consumer records between them, but nothing orders the overlapping
|
||||
//! fragments of one draw. The function records `PrecisionNote::UnorderedFetchWithinDraw`. It
|
||||
//! states `RuntimeFact::FramebufferFetch{color}` for every index it reads, so the render pass can
|
||||
@@ -20,8 +18,7 @@
|
||||
//!
|
||||
//! **Per sample**. Metal runs a function that reads a color attachment of a multisampled pass once
|
||||
//! per covered sample, reading its own sample (measured). Compiled for such a pipeline
|
||||
//! (`LoweringInputs::multisampled`), each input attachment is a multisampled `SubpassData` image
|
||||
//! (`MS` 1, as Vulkan requires for an attachment of more than one sample), read at the invocation's
|
||||
//! (`LoweringInputs::multisampled`), each element is a multisampled image, read at the invocation's
|
||||
//! `SampleId` (`fetch::plan_sample`), which runs the function once per covered sample under sample
|
||||
//! shading; the function's color outputs then write only that sample, and a returned sample mask
|
||||
//! and alpha to coverage stay the fixed function's, as at one sample. Link's sample
|
||||
@@ -29,30 +26,22 @@
|
||||
//! compiled for another sample count.
|
||||
//!
|
||||
//! **An extended-range attachment** (`metal::format::ExtendedRange`) holds Metal's raw texels in
|
||||
//! its raw unsigned format: its input attachment is of `uint` texels, and a read decodes the texel
|
||||
//! to Metal's tile value (`arith::extended_range::tile_value`). A read
|
||||
//! of one of Apple's extended-range forms (`BGR10_XR`, `BGRA10_XR`, `RGB10A8_2P_XR10` and their
|
||||
//! `_sRGB` twins) is not implemented, on every device (`Feature::Format`, at the attachment):
|
||||
//! Metal's tile holds such an attachment as `half` through the pass, which the codes an earlier
|
||||
//! draw stored do not keep (`fetch::codes_round_the_tile`); a padded one's is built. The
|
||||
//! interface records the attachment (`StageIo::extended_range_colors`), so link holds a stage
|
||||
//! compiled for it to the pipeline's attachments.
|
||||
//! its raw unsigned format, which the element's view of the attachment's own texels does not
|
||||
//! decode: a read of one is not implemented, on every device (`Feature::Format`, at the
|
||||
//! attachment).
|
||||
//!
|
||||
//! **An 8-bit sRGB attachment** (`RGBA8Unorm_sRGB`, `BGRA8Unorm_sRGB` and the rest) reads through
|
||||
//! its input attachment the device's decode of its bytes, Vulkan's sRGB EOTF within the device's
|
||||
//! its element the device's decode of its bytes, Vulkan's sRGB EOTF within the device's
|
||||
//! precision, where Metal decodes a color byte to its twelve-bit step over 4095. The interface
|
||||
//! records each `float` color it reads so (`StageIo::decoded_fetches`), and a render pipeline whose
|
||||
//! attachment there has such a format records `PrecisionNote::SrgbTexelDecode`
|
||||
//! (`color_writes::pipeline_writes`).
|
||||
//!
|
||||
//! **An `A8Unorm` attachment whose image holds Metal's alpha in red** (`R8_UNORM` on a device
|
||||
//! without `A8_UNORM`, `LoweringInputs::alpha_in_red_colors`) reads `(r, 0, 0, 1)` through its
|
||||
//! input attachment, which the read turns into Metal's `(0, 0, 0, r)` ([`alpha_in_red`]); the
|
||||
//! interface records the color (`StageIo::alpha_in_red_colors`), which link holds the pipeline's
|
||||
//! to. Under the identity domains the read takes the texture's element instead, whose view
|
||||
//! presents Metal's channels (its components `(0, 0, 0, R)`, which a fetch applies too, Vulkan's
|
||||
//! Component Swizzle): that read is Metal's `(0, 0, 0, a)` already, converted by nothing and
|
||||
//! recorded nowhere.
|
||||
//! without `A8_UNORM`, `LoweringInputs::alpha_in_red_colors`) is read through its element, whose
|
||||
//! view presents Metal's channels (its components `(0, 0, 0, R)`, which a fetch applies too,
|
||||
//! Vulkan's Component Swizzle): the read is Metal's `(0, 0, 0, a)` already, converted by nothing
|
||||
//! and recorded nowhere.
|
||||
//!
|
||||
//! A color input in a raster order group is read like any other: the family runs the whole body
|
||||
//! inside the interlock, and the read's ordering against other fragments' color writes is still the
|
||||
@@ -61,32 +50,27 @@
|
||||
//!
|
||||
//! Refused: `bool`, 64-bit, and aggregate colors.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use crate::air::abi::{AbiInt, ParamBinding, ParamRole};
|
||||
|
||||
use crate::air::ir::{ArgIdx, TypeId as AirTypeId, Value};
|
||||
use crate::error::{Attachment, DescriptorError, Error, Feature, MetalAnswer, Unsupported};
|
||||
use crate::lower::arith::legal::{form_on, refuse_int64_interface};
|
||||
use crate::lower::arith::{extended_range, narrow, ops, Form, Held};
|
||||
use crate::lower::arith::{narrow, ops, Form, Held};
|
||||
use crate::lower::emit::EmitCx;
|
||||
use crate::lower::select::SelectCx;
|
||||
use crate::lower::stage_io;
|
||||
use crate::lower::texture::{ImageDecl, TexelClass};
|
||||
use crate::metal::format::ExtendedRange;
|
||||
use crate::pipeline::artifact::PrecisionNote;
|
||||
use crate::pipeline::facts::RuntimeFact;
|
||||
use crate::pipeline::lower_inputs::StorageImageClass;
|
||||
use crate::pipeline::sym::{
|
||||
ImageAccess, ImageDim, ImageHandleClass, PushField, ResourceKind, ResourceSlot, SampledType,
|
||||
Stage, StorageFormatClass,
|
||||
ImageAccess, ImageDim, ImageHandleClass, PushField, SampledType, Stage, StorageFormatClass,
|
||||
};
|
||||
use crate::spirv::builder::{FunctionBuilder, ModuleBuilder};
|
||||
use crate::spirv::builder::FunctionBuilder;
|
||||
use crate::spirv::error::BResult;
|
||||
use crate::spirv::ids::{GlobalId, Value as SValue};
|
||||
use crate::spirv::ids::Value as SValue;
|
||||
use crate::spirv::ir::{
|
||||
Constant, ConvOp, Dim, ImageOperands, ImageType, ImageUsage, MemAccess, StorageClass,
|
||||
TexelMemory, Type as SType,
|
||||
Constant, ConvOp, Dim, ImageOperands, ImageUsage, MemAccess, Type as SType,
|
||||
};
|
||||
|
||||
use super::not_lowered;
|
||||
@@ -96,19 +80,10 @@ use super::not_lowered;
|
||||
pub struct ColorInput {
|
||||
/// The LLVM parameter index.
|
||||
pub param: u32,
|
||||
/// The color attachment index, which is also the input attachment index.
|
||||
/// The color attachment index.
|
||||
pub color: u32,
|
||||
/// The parameter's form: a scalar or 2–4 lane vector of 32-bit held integers or floats.
|
||||
pub form: Form,
|
||||
/// The attachment's extended-range form (`LoweringInputs::extended_range_colors`), whose
|
||||
/// image holds Metal's raw texels: an input attachment of the raw format's `uint`s, which
|
||||
/// the read decodes to Metal's tile value. `None` for a format held directly.
|
||||
pub extended: Option<ExtendedRange>,
|
||||
/// The attachment's image holds Metal's alpha in red (`LoweringInputs::alpha_in_red_colors`,
|
||||
/// `A8Unorm` in `R8_UNORM`) and the read takes its input attachment: a read, `(r, 0, 0, 1)`
|
||||
/// from the image, is Metal's `(0, 0, 0, r)`. False for the identity domains' read through the
|
||||
/// texture's element, whose view presents Metal's channels.
|
||||
pub alpha_red: bool,
|
||||
}
|
||||
|
||||
/// The form of a color value of AIR type `ty`, read or written: a scalar or 2 to 4 lanes of
|
||||
@@ -149,8 +124,7 @@ pub(super) fn select_param(cx: &mut SelectCx<'_>, b: &ParamBinding) -> Result<Co
|
||||
};
|
||||
let form = param_form(cx, b)?;
|
||||
let extended = cx.inputs.extended_range_colors.get(&color).copied();
|
||||
// A word attachment's input reads the word: the input attachment form, whose attachment is the
|
||||
// word itself, decodes none.
|
||||
// A word attachment's element holds the word, which the read decodes none of.
|
||||
if cx.inputs.word_colors.contains_key(&color) {
|
||||
let refused = Unsupported::not_implemented(Feature::Format);
|
||||
return Err(refused.at_attachment(Attachment::Color(color)).into());
|
||||
@@ -173,35 +147,32 @@ pub(super) fn select_param(cx: &mut SelectCx<'_>, b: &ParamBinding) -> Result<Co
|
||||
let refused = Unsupported::not_implemented(Feature::Format);
|
||||
return Err(refused.at_attachment(Attachment::Color(color)).into());
|
||||
}
|
||||
// Under the identity domains no descriptor holds the attachment: the function reads it through
|
||||
// the sampled-texture array's element the consumer pushes for it (`PushField::FetchedColor`),
|
||||
// a view of the attachment's own texels, so an extended-range attachment's view holds no raw
|
||||
// codes to decode there, and an alpha held in red reads as Metal's alpha through the view's
|
||||
// components.
|
||||
let textured = crate::lower::access::identity(cx.profile);
|
||||
let input = ColorInput {
|
||||
param: b.param,
|
||||
color,
|
||||
form,
|
||||
extended: extended.map(|e| e.form),
|
||||
alpha_red: cx.inputs.alpha_in_red_colors.contains(&color) && !textured,
|
||||
};
|
||||
// The read is ordered between draws alone, by the consumer's barriers: overlapping fragments
|
||||
// of one draw are not.
|
||||
cx.precision.insert(PrecisionNote::UnorderedFetchWithinDraw);
|
||||
if textured && extended.is_some() {
|
||||
// No descriptor holds the attachment: the function reads it through the sampled-texture
|
||||
// array's element the consumer pushes for it (`PushField::FetchedColor`), a view of the
|
||||
// attachment's own texels, so an extended-range attachment's view holds no raw codes to
|
||||
// decode there, and an alpha held in red reads as Metal's alpha through the view's
|
||||
// components.
|
||||
if extended.is_some() {
|
||||
let refused = Unsupported::not_implemented(Feature::Format);
|
||||
return Err(refused.at_attachment(Attachment::Color(color)).into());
|
||||
}
|
||||
// The input attachment of an image holding Metal's channels rotated (`ARGB8Unorm` in
|
||||
// The element of an image holding Metal's channels rotated (`ARGB8Unorm` in
|
||||
// `R8G8B8A8_UNORM`) reads them in the image's order: a color input of one is not modelled.
|
||||
// One holding Metal's alpha in red is read as Metal's alpha (`ColorInput::alpha_red`).
|
||||
// One holding Metal's alpha in red is read as Metal's alpha through its view.
|
||||
if cx.inputs.rotated_colors.contains(&color) && !cx.inputs.alpha_in_red_colors.contains(&color)
|
||||
{
|
||||
let refused = Unsupported::not_implemented(Feature::Format);
|
||||
return Err(refused.at_attachment(Attachment::Color(color)).into());
|
||||
}
|
||||
// Two reads of one attachment must agree on its numeric class (one image declaration).
|
||||
// Two reads of one attachment must agree on its numeric class (one element class).
|
||||
let known = &cx.families.fragment.colors;
|
||||
if known
|
||||
.iter()
|
||||
@@ -210,66 +181,25 @@ pub(super) fn select_param(cx: &mut SelectCx<'_>, b: &ParamBinding) -> Result<Co
|
||||
return Err(not_lowered());
|
||||
}
|
||||
if !known.iter().any(|c| c.color == color) {
|
||||
match textured {
|
||||
true => {
|
||||
let class = texture_class(cx, color, form);
|
||||
cx.families.fragment.texture_fetches.insert(color, class);
|
||||
let texels = class.sampled_type;
|
||||
cx.push.insert(PushField::FetchedColor { color, texels });
|
||||
cx.families.fragment.fetch_coord = Some(stage_io::frag_coord(cx));
|
||||
}
|
||||
false => {
|
||||
cx.descriptors.input_attachments =
|
||||
cx.descriptors.input_attachments.saturating_add(1);
|
||||
}
|
||||
}
|
||||
let class = texture_class(cx, color, form);
|
||||
cx.families.fragment.texture_fetches.insert(color, class);
|
||||
let texels = class.sampled_type;
|
||||
cx.push.insert(PushField::FetchedColor { color, texels });
|
||||
cx.families.fragment.fetch_coord = Some(stage_io::frag_coord(cx));
|
||||
cx.facts.insert(RuntimeFact::FramebufferFetch { color });
|
||||
}
|
||||
// An extended-range attachment's input reads its raw texels, decoded to the tile value, a
|
||||
// float (an integer read is Metal's pipeline error). The interface records the attachment,
|
||||
// which link holds the pipeline's to (`color_writes::check`).
|
||||
if let Some(e) = extended {
|
||||
if !form.is_float() {
|
||||
return Err(Error::InvalidDescriptor(DescriptorError::ColorAttachment {
|
||||
index: color,
|
||||
metal: MetalAnswer::NilWithError,
|
||||
}));
|
||||
}
|
||||
cx.families.arith.converts(e.form);
|
||||
cx.families
|
||||
.stage_io
|
||||
.interface
|
||||
.extended_range_colors
|
||||
.insert(color, e);
|
||||
}
|
||||
// A `float` color the device's input attachment decodes, an 8-bit sRGB format's through its
|
||||
// A `float` color the device's view decodes, an 8-bit sRGB format's through its
|
||||
// sRGB EOTF: the interface records the color, whose pipeline notes the decode where the
|
||||
// attachment is such a format (`color_writes::pipeline_writes`).
|
||||
if form.is_float() && extended.is_none() && !input.alpha_red {
|
||||
if form.is_float() {
|
||||
cx.families.stage_io.interface.decoded_fetches.insert(color);
|
||||
}
|
||||
// An attachment whose image holds Metal's alpha in red reads the red as Metal's alpha: a float
|
||||
// (an integer read is Metal's pipeline error). The interface records the attachment, which
|
||||
// link holds the pipeline's to (`color_writes::check`).
|
||||
if input.alpha_red {
|
||||
if !form.is_float() {
|
||||
return Err(Error::InvalidDescriptor(DescriptorError::ColorAttachment {
|
||||
index: color,
|
||||
metal: MetalAnswer::NilWithError,
|
||||
}));
|
||||
}
|
||||
cx.families
|
||||
.stage_io
|
||||
.interface
|
||||
.alpha_in_red_colors
|
||||
.insert(color);
|
||||
}
|
||||
super::fetch::plan_sample(cx)?;
|
||||
Ok(input)
|
||||
}
|
||||
|
||||
/// The set-1 class of the element a color input of `form` reads attachment `color` through under
|
||||
/// the identity domains (`PushField::FetchedColor`): a sampled 2D image, multisampled in a
|
||||
/// The set-1 class of the element a color input of `form` reads attachment `color` through
|
||||
/// (`PushField::FetchedColor`): a sampled 2D image, multisampled in a
|
||||
/// multisampled pipeline, arrayed for a colour of `LoweringInputs::arrayed_fetches` (an element
|
||||
/// holding a 2D array view, which Vulkan reads through an arrayed image alone), of `float` texels
|
||||
/// for a float read and of the attachment's own integer class for an integer one (`int` for a
|
||||
@@ -314,85 +244,18 @@ pub(crate) fn texture_decl(class: ImageHandleClass) -> ImageDecl {
|
||||
level_views: None,
|
||||
extended: None,
|
||||
x_channel: false,
|
||||
parts: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Declare one input attachment per color index the plan reads, multisampled for a per-sample
|
||||
/// function (`multisampled`). A color read through a pushed texture (`textured`) declares nothing
|
||||
/// here.
|
||||
pub(super) fn declare(
|
||||
mb: &mut ModuleBuilder,
|
||||
colors: &[ColorInput],
|
||||
multisampled: bool,
|
||||
textured: &BTreeMap<u32, ImageHandleClass>,
|
||||
) -> BResult<BTreeMap<u32, GlobalId>> {
|
||||
let mut out = BTreeMap::new();
|
||||
for c in colors {
|
||||
// A color read through a pushed texture has no declaration of its own: its class's array
|
||||
// is the texture family's (`texture::declare`).
|
||||
if out.contains_key(&c.color) || textured.contains_key(&c.color) {
|
||||
continue;
|
||||
}
|
||||
// An extended-range attachment's image holds the raw format's `uint` texels.
|
||||
let float = c.form.is_float() && c.extended.is_none();
|
||||
out.insert(c.color, input_attachment(mb, c.color, float, multisampled)?);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The input attachment of color `color`, of `float` texels or (not `float`) `uint` ones,
|
||||
/// multisampled for a per-sample function.
|
||||
fn input_attachment(
|
||||
mb: &mut ModuleBuilder,
|
||||
color: u32,
|
||||
float: bool,
|
||||
multisampled: bool,
|
||||
) -> BResult<GlobalId> {
|
||||
let sampled_type = match float {
|
||||
true => mb.ty(SType::Float { width: 32 })?,
|
||||
false => mb.ty(SType::Int {
|
||||
width: 32,
|
||||
signed: false,
|
||||
})?,
|
||||
};
|
||||
let ty = mb.ty(SType::Image(ImageType {
|
||||
sampled_type,
|
||||
dim: Dim::SubpassData,
|
||||
depth: false,
|
||||
arrayed: false,
|
||||
multisampled,
|
||||
usage: ImageUsage::Storage,
|
||||
format: crate::spv::ImageFormat::Unknown,
|
||||
}))?;
|
||||
let slot = ResourceSlot {
|
||||
stage: Stage::Fragment,
|
||||
kind: ResourceKind::InputAttachment(color),
|
||||
index: color,
|
||||
};
|
||||
mb.resource(slot, StorageClass::UniformConstant, ty)
|
||||
}
|
||||
|
||||
/// The value of color input `c` in its lowered representation, at the invocation's sample for a
|
||||
/// per-sample function: an input attachment's read at each use (the use may sit in a construct
|
||||
/// whose values do not dominate the rest of the block).
|
||||
/// per-sample function: a read at each use (the use may sit in a construct whose values do not
|
||||
/// dominate the rest of the block).
|
||||
pub(super) fn value(
|
||||
cx: &mut EmitCx<'_>,
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
c: ColorInput,
|
||||
) -> BResult<SValue> {
|
||||
let texel = match c.extended {
|
||||
Some(form) => {
|
||||
let texel = input_texel(cx, fb, c.color)?;
|
||||
extended_range::tile_value(fb, form, texel)?
|
||||
}
|
||||
// The image's red, Metal's alpha: `(0, 0, 0, r)`.
|
||||
None if c.alpha_red => {
|
||||
let texel = input_texel(cx, fb, c.color)?;
|
||||
alpha_in_red(fb, texel)?
|
||||
}
|
||||
None => input_texel(cx, fb, c.color)?,
|
||||
};
|
||||
let texel = input_texel(cx, fb, c.color)?;
|
||||
let x = match c.form.lanes {
|
||||
4 => texel,
|
||||
1 => fb.composite_extract(texel, &[0])?,
|
||||
@@ -405,56 +268,31 @@ pub(super) fn value(
|
||||
narrow::round(fb, c.form, x)
|
||||
}
|
||||
|
||||
/// Metal's texel of an `A8Unorm` attachment whose image holds Metal's alpha in red, from the
|
||||
/// image's `texel` (a `vec4`, `(r, 0, 0, 1)`): `(0, 0, 0, r)`, as Metal reads such an attachment
|
||||
/// (probe `a8`'s uses on an M3 Max under macOS 27.0.1: a fetch of the byte 153 is
|
||||
/// `(0, 0, 0, 0.6)`, a scalar or two-lane fetch its leading lanes).
|
||||
pub(super) fn alpha_in_red(fb: &mut FunctionBuilder<'_>, texel: SValue) -> BResult<SValue> {
|
||||
let f32_ = fb.module().ty(SType::Float { width: 32 })?;
|
||||
let vec4 = fb.module().ty(SType::Vector { elem: f32_, len: 4 })?;
|
||||
let zero = fb.module().constant(Constant::Null { ty: vec4 })?;
|
||||
let zero = fb.module().const_value(zero)?;
|
||||
fb.vector_shuffle(zero, texel, &[0, 1, 2, 4])
|
||||
}
|
||||
|
||||
/// The texel of color `color`'s input attachment, as the image reads it: at the calling
|
||||
/// fragment's own texel, at the invocation's sample for a per-sample function.
|
||||
/// The texel of color `color`, as its element reads it: at the calling fragment's own texel, at
|
||||
/// the invocation's sample for a per-sample function.
|
||||
pub(super) fn input_texel(
|
||||
cx: &mut EmitCx<'_>,
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
color: u32,
|
||||
) -> BResult<SValue> {
|
||||
if let Some(class) = cx
|
||||
let Some(class) = cx
|
||||
.plan
|
||||
.families
|
||||
.fragment
|
||||
.texture_fetches
|
||||
.get(&color)
|
||||
.copied()
|
||||
{
|
||||
return pushed_texel(cx, fb, color, class);
|
||||
}
|
||||
let Some(g) = cx.decl.families.fragment.attachments.get(&color).copied() else {
|
||||
return Err(cx.fail(format!("input attachment {color} is not declared")));
|
||||
else {
|
||||
return Err(cx.fail(format!("fetched color {color} is not planned")));
|
||||
};
|
||||
let p = fb.module().global_value(g)?;
|
||||
let img = fb.load(p, MemAccess::default())?;
|
||||
let i32_ = fb.module().ty(SType::Int {
|
||||
width: 32,
|
||||
signed: true,
|
||||
})?;
|
||||
let ivec2 = fb.module().ty(SType::Vector { elem: i32_, len: 2 })?;
|
||||
let origin = fb.module().constant(Constant::Null { ty: ivec2 })?;
|
||||
let origin = fb.module().const_value(origin)?;
|
||||
let ops = super::fetch::operands(cx, fb)?;
|
||||
fb.read(img, origin, &ops, TexelMemory::PRIVATE)
|
||||
pushed_texel(cx, fb, color, class)
|
||||
}
|
||||
|
||||
/// The texel of color `color` read through the sampled-texture array's element the consumer pushes
|
||||
/// for it (`PushField::FetchedColor`), an element of `class`: a fetch at level 0 of the integer
|
||||
/// part of the invocation's `FragCoord`, its own pixel, at layer 0 of an arrayed element, and at
|
||||
/// its `SampleId` for a per-sample function, a signed-integer texel's bits as the `uint`s the
|
||||
/// input attachment form reads. The element is uniform over the draw.
|
||||
/// its `SampleId` for a per-sample function, a signed-integer texel's bits as `uint`s. The element
|
||||
/// is uniform over the draw.
|
||||
fn pushed_texel(
|
||||
cx: &mut EmitCx<'_>,
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
//! Framebuffer fetch: what orders it, and the writes no form computes over the texel it reads.
|
||||
//!
|
||||
//! **Where.** Metal orders a fetch after every earlier fragment of the pixel, across draws. A color
|
||||
//! input reads the attachment's input attachment (`color`), which Vulkan orders so only under
|
||||
//! rasterization-order color attachment access, which no form here takes: the read is ordered
|
||||
//! between draws alone, by the consumer's barrier of the subpass's dependency on itself, and notes
|
||||
//! `PrecisionNote::UnorderedFetchWithinDraw`; under the identity domains it reads the attachment's
|
||||
//! pushed texture at the invocation's pixel instead (`PushField::FetchedColor`, [`pixel`]). The
|
||||
//! input reads the attachment's pushed texture at the invocation's pixel (`color`,
|
||||
//! `PushField::FetchedColor`, [`pixel`]), which nothing orders against the overlapping fragments
|
||||
//! of one draw: the read is ordered between draws alone, by the consumer's barrier of the subpass's
|
||||
//! dependency on itself, and notes `PrecisionNote::UnorderedFetchWithinDraw`. The
|
||||
//! pixel interlock orders no fetch: it serves raster order groups on memory the function itself
|
||||
//! reads and writes (`fragment::rog`).
|
||||
//!
|
||||
@@ -43,7 +42,7 @@ use crate::metal::format::ExtendedRange;
|
||||
use crate::spirv::builder::FunctionBuilder;
|
||||
use crate::spirv::error::BResult;
|
||||
use crate::spirv::ids::Value as SValue;
|
||||
use crate::spirv::ir::{Constant, ConvOp, ImageOperands, MemAccess, Type as SType};
|
||||
use crate::spirv::ir::{Constant, ConvOp, MemAccess, Type as SType};
|
||||
|
||||
/// Whether Metal's tile memory holds an attachment of `form` as `half` through a render pass and
|
||||
/// rounds it to the codes only at the store, where the attachment holds the codes: Apple's
|
||||
@@ -90,22 +89,6 @@ pub(super) fn plan_sample(cx: &mut SelectCx<'_>) -> Result<(), Error> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The image operands of a fetched color's read or write in a multisampled image (an input
|
||||
/// attachment, or a pushed texture's fetch): the invocation's `SampleId` for a per-sample
|
||||
/// function (`FragmentPlan::fetch_sample`), none for one sample.
|
||||
pub(super) fn operands(
|
||||
cx: &mut EmitCx<'_>,
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
) -> BResult<ImageOperands> {
|
||||
let Some(sample) = sample(cx, fb)? else {
|
||||
return Ok(ImageOperands::default());
|
||||
};
|
||||
Ok(ImageOperands {
|
||||
sample: Some(sample),
|
||||
..ImageOperands::default()
|
||||
})
|
||||
}
|
||||
|
||||
/// The invocation's `SampleId`, loaded, for a per-sample function; `None` for one sample.
|
||||
pub(super) fn sample(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>) -> BResult<Option<SValue>> {
|
||||
let Some(object) = cx.plan.families.fragment.fetch_sample else {
|
||||
|
||||
@@ -4,9 +4,10 @@
|
||||
//! `discard::plan` (demote, predication, or a terminator, from the language version, forward
|
||||
//! reachability, and the profile). A predicated site sets the `Private bool discarded` this
|
||||
//! family declares, and [`emit_return`] kills a discarded invocation before `OpReturn`.
|
||||
//! - **Framebuffer fetch** (`[[color(n)]]` inputs): each color index is one input attachment
|
||||
//! (`color`), read at every use. Compiled for a multisampled pipeline, it reads the invocation's
|
||||
//! own sample at `SampleId`, which runs the function once per covered sample, as Metal does.
|
||||
//! - **Framebuffer fetch** (`[[color(n)]]` inputs): each color index is read through the element
|
||||
//! of the sampled-texture array the consumer pushes for it (`color`), at every use. Compiled for
|
||||
//! a multisampled pipeline, it reads the invocation's own sample at `SampleId`, which runs the
|
||||
//! function once per covered sample, as Metal does.
|
||||
//! - **Raster order groups** (`rog`): a function that names a group runs its body as a function
|
||||
//! called from `main` between `Begin/EndInvocationInterlockEXT` ([`wrap_entry`], the
|
||||
//! entry-wrapper hook of `lower::emit`); inside it a discard only records `discarded`, and `main`
|
||||
@@ -289,8 +290,6 @@ pub struct Declared {
|
||||
/// The `HelperInvocation` input the whole-quad exits and helper queries where no discard
|
||||
/// demotes read.
|
||||
pub helper: Option<GlobalId>,
|
||||
/// The input attachment of each color index read.
|
||||
pub attachments: BTreeMap<u32, GlobalId>,
|
||||
/// The `Private u32` holding the sample of the loop's pass over the covered samples.
|
||||
pub loop_sample: Option<GlobalId>,
|
||||
/// The `Private u32` copy of the `SampleMask` input's word, which the entry stores before it
|
||||
@@ -298,8 +297,8 @@ pub struct Declared {
|
||||
pub coverage_copy: Option<GlobalId>,
|
||||
}
|
||||
|
||||
/// Declare the fragment family's module-scope objects and modes: the discard predicate, the
|
||||
/// input attachments, and the interlock mode of a function in a raster order group.
|
||||
/// Declare the fragment family's module-scope objects and modes: the discard predicate and the
|
||||
/// interlock mode of a function in a raster order group.
|
||||
pub fn declare(
|
||||
mb: &mut ModuleBuilder,
|
||||
plan: &Plan,
|
||||
@@ -322,12 +321,6 @@ pub fn declare(
|
||||
let bool_ = mb.ty(SType::Bool)?;
|
||||
d.helper = Some(mb.builtin(crate::spv::BuiltIn::HelperInvocation, IoDir::Input, bool_)?);
|
||||
}
|
||||
d.attachments = color::declare(
|
||||
mb,
|
||||
&fp.colors,
|
||||
fp.fetch_sample.is_some(),
|
||||
&fp.texture_fetches,
|
||||
)?;
|
||||
d.loop_sample = coverage::declare(mb, plan)?;
|
||||
if wraps_body(fp) && sample_mask_input(plan).is_some() {
|
||||
let u32_ = mb.ty(SType::Int {
|
||||
|
||||
@@ -27,20 +27,21 @@
|
||||
//! output alone does not interlock the function, so a function whose groups hold nothing else
|
||||
//! compiles on every device, the ones without an interlock included.
|
||||
//!
|
||||
//! **Color inputs**. A color input reads its input attachment ordered between draws alone, by the
|
||||
//! consumer's barriers (under the identity domains, the attachment's pushed texture; `fetch`). A group on such an input, or on a color output of an attachment the
|
||||
//! function reads, asks for the order of that read, which is the read's own there: it does not
|
||||
//! interlock the function, since the interlock cannot order the attachment's own write, which
|
||||
//! happens after the function, and the read's fragments of one draw stay unordered
|
||||
//! **Color inputs**. A color input reads the attachment's pushed texture (`fetch`) ordered between
|
||||
//! draws alone, by the consumer's barriers. A group on such an input, or on a color output of an
|
||||
//! attachment the function reads, asks for the order of that read, which is the read's own there:
|
||||
//! it does not interlock the function, since the interlock cannot order the attachment's own write,
|
||||
//! which happens after the function, and the read's fragments of one draw stay unordered
|
||||
//! (`PrecisionNote::UnorderedFetchWithinDraw`, which the read records). A group on anything else,
|
||||
//! memory the function reads and writes, still needs the interlock.
|
||||
//!
|
||||
//! **Unused inputs**. A group on a parameter the body never uses, such as an input whose reads the
|
||||
//! function's constants fold away, orders no access, and neither does a member of a layout only
|
||||
//! such a parameter reaches, nor a color output whose attachment only such a color input reads. None
|
||||
//! of them interlocks the function: plain Metal makes and draws such a function where the read is
|
||||
//! dead as where it is live (`metal2vulkan-conformance/probes/dead_ordered_and_unattached_reads.m`,
|
||||
//! an M3 Max under macOS 27.0.1).
|
||||
//! such a parameter reaches, nor a color output whose attachment only such a color input reads.
|
||||
//! None of them interlocks the function: plain Metal makes and draws such a function where the read
|
||||
//! is dead as where it is live
|
||||
//! (`metal2vulkan-conformance/probes/dead_ordered_and_unattached_reads.m`, an M3 Max under macOS
|
||||
//! 27.0.1).
|
||||
//!
|
||||
//! **Mode** ([`mode`]). `PixelInterlockOrderedEXT` where the profile has
|
||||
//! `fragmentShaderPixelInterlock`: it orders every invocation covering the pixel, which covers
|
||||
|
||||
@@ -170,10 +170,8 @@ pub const fn shape(f: PushField) -> FieldShape {
|
||||
match f {
|
||||
PushField::ArgumentTableAddress
|
||||
| PushField::RootTableAddress
|
||||
| PushField::ExecutionStatusAddress
|
||||
| PushField::CaptureIndexAddress
|
||||
| PushField::MergedDrawAddress
|
||||
| PushField::CommandRecordsAddress
|
||||
| PushField::ReplayRegionAddress
|
||||
| PushField::TessellationFactorAddress
|
||||
| PushField::PatchIndexAddress
|
||||
@@ -189,10 +187,6 @@ pub const fn shape(f: PushField) -> FieldShape {
|
||||
PushField::DepthClampRange => FieldShape::UVec2,
|
||||
// The alpha test reference's code.
|
||||
PushField::AlphaTestReference => FieldShape::U32,
|
||||
// The blend color and one minus it, four `f32`s' bits each.
|
||||
// The blend color as the encoder set it, four `f32`s' bits.
|
||||
PushField::HalfBlendColor => FieldShape::UVec4Array(1),
|
||||
// A draw's depth bias: its constant, slope and clamp as `f32`s' bits, and a zero word.
|
||||
// Base vertex, base instance.
|
||||
PushField::BaseVertexInstance => FieldShape::UVec2,
|
||||
// The draw's vertices per primitive, and the stencil bit a draw keeps.
|
||||
@@ -239,9 +233,6 @@ pub const fn shape(f: PushField) -> FieldShape {
|
||||
| PushField::ControlPointIndexOffset => FieldShape::U32,
|
||||
// A band's viewport half extent and half width, four `f32`s.
|
||||
PushField::LineBand => FieldShape::UVec4Array(1),
|
||||
// The whole indices from the bound index offset to the buffer's end, unsaturated:
|
||||
// `firstIndex + indexCount` reaches `2^33`.
|
||||
PushField::IndexCapacity => FieldShape::U64,
|
||||
// The floor's tail word, pushed zero.
|
||||
PushField::TailWord => FieldShape::U32,
|
||||
}
|
||||
@@ -776,8 +767,8 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// The control stage's push range fits below a post-tessellation vertex function's window in
|
||||
/// either form, with every factor step, scale and control-point index type the form takes, so
|
||||
/// The control stage's push range fits below a post-tessellation vertex function's window with
|
||||
/// every factor step, scale and control-point index type its form takes, so
|
||||
/// link places it at 0 beside any pair of functions; a fragment function behind such a vertex
|
||||
/// function that pushes nothing starts past it too, and behind any other at 0.
|
||||
#[test]
|
||||
@@ -792,19 +783,16 @@ mod tests {
|
||||
Step::PerPatchAndPerInstance,
|
||||
];
|
||||
let types = [IndexType::None, IndexType::UInt16, IndexType::UInt32];
|
||||
for addressed in [false, true] {
|
||||
for step in steps {
|
||||
for scale in [false, true] {
|
||||
for index_type in types {
|
||||
if addressed && !address_fits(step, scale, index_type) {
|
||||
continue;
|
||||
}
|
||||
let (bytes, align) =
|
||||
Control::push_bytes(addressed, step, scale, index_type);
|
||||
let case = format!("{addressed} {step:?} {scale} {index_type:?}");
|
||||
assert!(bytes <= TESSELLATION_BASE, "{case}");
|
||||
assert_eq!(TESSELLATION_BASE % align, 0);
|
||||
for step in steps {
|
||||
for scale in [false, true] {
|
||||
for index_type in types {
|
||||
if !address_fits(step, scale, index_type) {
|
||||
continue;
|
||||
}
|
||||
let (bytes, align) = Control::push_bytes(step, scale, index_type);
|
||||
let case = format!("{step:?} {scale} {index_type:?}");
|
||||
assert!(bytes <= TESSELLATION_BASE, "{case}");
|
||||
assert_eq!(TESSELLATION_BASE % align, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -930,7 +918,6 @@ mod tests {
|
||||
let kinds = |stage: Stage, i: u32| {
|
||||
[
|
||||
PushField::RootTableAddress,
|
||||
PushField::ExecutionStatusAddress,
|
||||
PushField::DispatchRegion,
|
||||
PushField::BaseVertexInstance,
|
||||
PushField::SlotBindOffset(slot(stage, i)),
|
||||
@@ -960,82 +947,8 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// `ExecutionStatusAddress` is always in the push block, where its readers find it: the
|
||||
/// resident-miss count, and `spirv::requirements::writes`, which knows the `ExecutionStatus`
|
||||
/// buffer by a load of this member and so needs no `ArgumentTable` path. The kind order (the
|
||||
/// derived `Ord` of `PushField`) puts it after `ArgumentTableAddress` and `RootTableAddress`,
|
||||
/// the only kinds that sort before it, of which a function places one at most (the first is
|
||||
/// the identity domains', the second the table domains'), and placement fills the window as a
|
||||
/// prefix of that order, so the field sits in the first 16 bytes of its stage window whatever
|
||||
/// else the function pushes; every window holds 64. Checked for every stage, with neither
|
||||
/// address and with each, alone and with every later kind at its largest count (every buffer
|
||||
/// slot's residual and guest base, 31 strides), which spills.
|
||||
#[test]
|
||||
fn the_status_address_is_always_placed_in_the_push_block() {
|
||||
for stage in [Stage::Vertex, Stage::Fragment, Stage::Kernel] {
|
||||
let slot = |index| SlotRef {
|
||||
stage,
|
||||
class: SlotClass::Buffer,
|
||||
index,
|
||||
};
|
||||
let kinds = [
|
||||
PushField::ArgumentTableAddress,
|
||||
PushField::RootTableAddress,
|
||||
PushField::ExecutionStatusAddress,
|
||||
PushField::DispatchRegion,
|
||||
PushField::BaseVertexInstance,
|
||||
PushField::SlotBindOffset(slot(0)),
|
||||
PushField::SlotGuestBase(slot(0)),
|
||||
PushField::VertexBufferStride(0),
|
||||
];
|
||||
let before: Vec<PushField> = kinds
|
||||
.into_iter()
|
||||
.filter(|k| *k < PushField::ExecutionStatusAddress)
|
||||
.collect();
|
||||
assert_eq!(
|
||||
before,
|
||||
[PushField::ArgumentTableAddress, PushField::RootTableAddress]
|
||||
);
|
||||
let mut later =
|
||||
BTreeSet::from([PushField::DispatchRegion, PushField::BaseVertexInstance]);
|
||||
for i in 0..31 {
|
||||
later.insert(PushField::SlotBindOffset(slot(i)));
|
||||
later.insert(PushField::SlotGuestBase(slot(i)));
|
||||
later.insert(PushField::VertexBufferStride(i));
|
||||
}
|
||||
let (start, end) = window(stage, 0, LEAST_BYTES);
|
||||
let firsts = [
|
||||
None,
|
||||
Some(PushField::RootTableAddress),
|
||||
Some(PushField::ArgumentTableAddress),
|
||||
];
|
||||
for first in firsts {
|
||||
for rest in [BTreeSet::new(), later.clone()] {
|
||||
let spills = !rest.is_empty();
|
||||
let mut fields = rest;
|
||||
fields.insert(PushField::ExecutionStatusAddress);
|
||||
fields.extend(first);
|
||||
let placement = place(stage, 0, LEAST_BYTES, &fields);
|
||||
let status = placement
|
||||
.fields
|
||||
.iter()
|
||||
.find(|f| f.field == PushField::ExecutionStatusAddress)
|
||||
.expect("placed");
|
||||
let at = start + 8 * u32::from(first.is_some());
|
||||
assert_eq!(
|
||||
status.loc,
|
||||
PushLoc::Push { offset: at },
|
||||
"{stage:?} {first:?}"
|
||||
);
|
||||
assert!(at + status.size <= end);
|
||||
assert_eq!(placement.argument_table_size > 0, spills, "{stage:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A vertex function's index address is a hole the consumer fills, which must be in the push
|
||||
/// block: the placement order puts it right after the two other addresses, so the vertex
|
||||
/// block: the placement order puts it right after the root table's address, so the vertex
|
||||
/// window holds it whatever else the function reads, and its layout follows the window's
|
||||
/// other fields.
|
||||
#[test]
|
||||
@@ -1053,23 +966,20 @@ mod tests {
|
||||
later.insert(PushField::VertexBufferStride(i));
|
||||
}
|
||||
let (start, end) = window(Stage::Vertex, 0, LEAST_BYTES);
|
||||
for (root, status) in [(false, false), (true, false), (false, true), (true, true)] {
|
||||
for root in [false, true] {
|
||||
let mut fields = later.clone();
|
||||
fields.insert(PushField::CaptureIndexAddress);
|
||||
if root {
|
||||
fields.insert(PushField::RootTableAddress);
|
||||
}
|
||||
if status {
|
||||
fields.insert(PushField::ExecutionStatusAddress);
|
||||
}
|
||||
let placement = check_in(Stage::Vertex, 0, LEAST_BYTES, &fields);
|
||||
let at = start + 8 * (u32::from(root) + u32::from(status));
|
||||
let at = start + 8 * u32::from(root);
|
||||
let index = placement
|
||||
.fields
|
||||
.iter()
|
||||
.find(|f| f.field == PushField::CaptureIndexAddress)
|
||||
.expect("placed");
|
||||
assert_eq!(index.loc, PushLoc::Push { offset: at }, "{root} {status}");
|
||||
assert_eq!(index.loc, PushLoc::Push { offset: at }, "{root}");
|
||||
assert!(at + index.size <= end);
|
||||
let layout = placement
|
||||
.fields
|
||||
|
||||
@@ -108,8 +108,7 @@
|
||||
//! **The variant**. A runtime slot's emulation, at every sample it reaches, made a guest's
|
||||
//! fragment function of 337 such samples twice its size (2.35M words from 1.18M, the emulation
|
||||
//! written at each site), whatever samplers its draws bind, and every making of its pipeline hands
|
||||
//! the driver the whole module. Such a sample states
|
||||
//! `RuntimeFact::AnisotropicSampler` for its slot and takes the emulation only under the variant
|
||||
//! the driver the whole module. Such a sample takes the emulation only under the variant
|
||||
//! naming the slot (`LoweringInputs::anisotropic_samplers`), which the binder asks for wherever
|
||||
//! the bound sampler's word states anisotropy; elsewhere it is the plain sample, which is
|
||||
//! Metal's for every word the function is then bound with. Under the variant the sample is the
|
||||
@@ -118,10 +117,9 @@
|
||||
|
||||
use crate::air::abi::{Coordinates, MipFilter};
|
||||
use crate::air::intrinsics::{ImageDim, ImageShape};
|
||||
use crate::budget::Meter;
|
||||
use crate::error::Error;
|
||||
use crate::lower::emit::EmitCx;
|
||||
use crate::lower::select::{NoteOn, NoteTest, SelectCx};
|
||||
use crate::lower::select::SelectCx;
|
||||
use crate::lower::texture::ImageRef;
|
||||
use crate::metal::sampler::{device_anisotropy_by_filters, SamplerUse, SamplerWord};
|
||||
use crate::pipeline::artifact::PrecisionNote;
|
||||
@@ -256,17 +254,15 @@ const MINIFIED_NEAREST: f32 = 0.25;
|
||||
/// device whose own sampler answers the sample, anisotropy included, takes neither: one with
|
||||
/// `samplerAnisotropy`.
|
||||
/// `integer`: the texel class is an integer one (never filtered); `observed`: the function
|
||||
/// reads the sample's residency; `other_class`: the slot's variant binds a texture of another
|
||||
/// class (`LoweringInputs::cross_class`); `swizzled`: the slot swizzles its converted texels
|
||||
/// reads the sample's residency; `swizzled`: the slot swizzles its converted texels
|
||||
/// (`LoweringInputs::swizzled_storage`). `use_` is the sample's binding's use of its sampler,
|
||||
/// which with the sampler decides the device's sampler.
|
||||
pub(super) fn select(
|
||||
cx: &mut SelectCx<'_>,
|
||||
op: &SampleOp,
|
||||
(sampler, image, shape): (Option<SamplerRef>, ImageRef, ImageShape),
|
||||
(integer, observed, other_class, swizzled): (bool, bool, bool, bool),
|
||||
(integer, observed, swizzled): (bool, bool, bool),
|
||||
use_: SamplerUse,
|
||||
m: &mut Meter,
|
||||
) -> Result<Option<Anisotropic>, Error> {
|
||||
// Without `samplerAnisotropy` every Vulkan sampler is isotropic
|
||||
// (`metal::sampler::device_anisotropy`): the emulation goes where it reaches an anisotropic
|
||||
@@ -319,7 +315,6 @@ pub(super) fn select(
|
||||
&& !shape.ms
|
||||
&& !shape.depth
|
||||
&& !observed
|
||||
&& !other_class
|
||||
&& !swizzled
|
||||
&& matches!(image, ImageRef::Slot(_));
|
||||
let note = match reached {
|
||||
@@ -331,34 +326,18 @@ pub(super) fn select(
|
||||
cx.precision.insert(note);
|
||||
}
|
||||
Degree::Slot(n) => {
|
||||
// A reached sample states its slot's fact, and takes the emulation only under the
|
||||
// variant naming the slot, which the binder asks for wherever the bound word states
|
||||
// anisotropy. Elsewhere it is the plain sample, with no emulation in the module:
|
||||
// Metal's sample wherever the word states no anisotropy, the only words a function
|
||||
// compiled without the slot is bound with there.
|
||||
// Under the identity domains no binder chooses the variant.
|
||||
if reached && crate::lower::access::identity(cx.profile) {
|
||||
// A reached sample would take the emulation only under a variant naming the slot,
|
||||
// which no binder of the identity domains chooses.
|
||||
if reached {
|
||||
return Err(crate::error::Unsupported::identity(
|
||||
crate::error::IdentityCause::SamplerState,
|
||||
)
|
||||
.into());
|
||||
}
|
||||
if reached {
|
||||
let slot = super::select::sampler_slot(cx.stage, n);
|
||||
cx.facts
|
||||
.insert(crate::pipeline::facts::RuntimeFact::AnisotropicSampler { slot });
|
||||
if !cx.inputs.anisotropic_samplers.contains(&slot) {
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
if let Some(s) = cx.families.sampler.slots.get_mut(&n) {
|
||||
match reached {
|
||||
true => s.emulated = true,
|
||||
false => s.anisotropy = true,
|
||||
}
|
||||
s.anisotropy = true;
|
||||
}
|
||||
let anisotropic = NoteTest::differ(NoteOn::Sampler(n), SamplerWord::ANISOTROPIC, 0);
|
||||
cx.note_when(note, vec![[anisotropic].into()], m)?;
|
||||
cx.precision.insert(note);
|
||||
}
|
||||
}
|
||||
let images = &cx.profile.fields().images;
|
||||
@@ -370,6 +349,12 @@ pub(super) fn select(
|
||||
}))
|
||||
}
|
||||
|
||||
/// The image facts of combined binding `key`, which no module declares: every sampling reads the
|
||||
/// set-1 arrays (`sampler::IdentitySampling`), so an emulation that needs the binding fails.
|
||||
fn combined_image(cx: &mut EmitCx<'_>, key: super::BindingKey) -> BResult<super::CombinedImage> {
|
||||
Err(cx.fail(format!("combined binding {key:?} is not declared")))
|
||||
}
|
||||
|
||||
/// Sample `s` through Metal's anisotropic filter (the module docs), in its result's form: for a
|
||||
/// runtime sampler slot, where its word states anisotropy, else the plain sample. `grads` are a
|
||||
/// switch-at-use's hoisted gradients (`Lod::Hoisted`).
|
||||
@@ -392,9 +377,7 @@ pub(super) fn sample(
|
||||
let Source::Combined(key) = s.source else {
|
||||
return Err(cx.fail("an anisotropic emulation of a heap element"));
|
||||
};
|
||||
let Some(&(_, image)) = cx.decl.families.sampler.combined.get(&key) else {
|
||||
return Err(cx.fail(format!("combined binding {key:?} is not declared")));
|
||||
};
|
||||
let image = combined_image(cx, key)?;
|
||||
let coord = super::emit::plane_coord(cx, fb, s)?;
|
||||
// A cube's direction with its ties broken as Metal breaks them, whose face Metal reads.
|
||||
let coord = match s.cube {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
//! Metal's anisotropic filter emulated: where a sample takes it, the module's shape, the notes it
|
||||
//! records and the specialization a runtime sampler slot reads; every module validated by
|
||||
//! `spirv-val` under its profile. The interpreter leaves `Exp2` unmodelled (the spacing's 6-bit
|
||||
//! power reads it), so the footprint's values are a device's to check; these are shape tests.
|
||||
//! Metal's anisotropic filter: where a sample takes the device's own filter, the module's shape and
|
||||
//! the notes it records; every module validated by `spirv-val` under its profile. These are shape
|
||||
//! tests.
|
||||
//!
|
||||
//! `llvm-as` assembles the fixtures; without it the tests skip visibly.
|
||||
|
||||
@@ -10,17 +9,10 @@ use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use crate::air::abi::{Filter, MipFilter};
|
||||
use crate::device::profile::DeviceProfile;
|
||||
use crate::device::requirements::VkFeature;
|
||||
use crate::device::{Device, DevicePolicy};
|
||||
use crate::device::Device;
|
||||
use crate::library::FunctionArtifact;
|
||||
use crate::metal::sampler::SamplerWord;
|
||||
use crate::pipeline::artifact::PrecisionNote;
|
||||
use crate::pipeline::facts::RuntimeFact;
|
||||
use crate::pipeline::lower_inputs::LoweringInputs;
|
||||
use crate::pipeline::sym::SpecKey;
|
||||
use crate::pipeline::sym::{SlotClass, SlotRef, Stage};
|
||||
use crate::pipeline::testing::{
|
||||
compile, compile_with, link_and_validate, llvm_assemble, profile, AssembleError,
|
||||
};
|
||||
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";
|
||||
|
||||
@@ -30,9 +22,6 @@ const BASE_WORDS: u64 = 34901797601036873;
|
||||
const OP_IMAGE_SAMPLE_IMPLICIT_LOD: u16 = 87;
|
||||
const OP_IMAGE_SAMPLE_EXPLICIT_LOD: u16 = 88;
|
||||
const OP_IMAGE_QUERY_LEVELS: u16 = 106;
|
||||
/// The taps an emulation's code holds, whatever its degree: tap 0 and the loop's one (one
|
||||
/// explicit-level sample each, the device blending a linear mip filter's two levels).
|
||||
const WRITTEN_TAPS: u32 = 2;
|
||||
|
||||
/// The constexpr sampler words of linear filters, mip filter `mip` and `maxAnisotropy` `aniso`.
|
||||
fn words(mip: MipFilter, aniso: u32) -> u64 {
|
||||
@@ -95,48 +84,19 @@ declare {{ <4 x float>, i8 }} @air.sample_texture_2d.v4f32(ptr addrspace(1), ptr
|
||||
)
|
||||
}
|
||||
|
||||
/// A kernel sampling `texture2d<float>` slot 0 with explicit gradients through runtime sampler
|
||||
/// slot 0, writing the texel to buffer 0.
|
||||
const RUNTIME_KERNEL: &str = r#"define void @k(ptr addrspace(1) %t, ptr addrspace(2) %s, ptr addrspace(1) %o, <2 x i32> %gid) {
|
||||
%x = extractelement <2 x i32> %gid, i64 0
|
||||
%xf = uitofp i32 %x to float
|
||||
%u = fmul float %xf, 1.562500e-02
|
||||
%uv = insertelement <2 x float> <float 0.000000e+00, float 5.000000e-01>, float %u, i64 0
|
||||
%r = call { <4 x float>, i8 } @air.sample_texture_2d_grad.v4f32(ptr addrspace(1) %t, ptr addrspace(2) %s, <2 x float> %uv, <2 x float> <float 2.500000e-01, float 0.000000e+00>, <2 x float> <float 0.000000e+00, float 3.125000e-02>, float 0.000000e+00, i1 true, <2 x i32> zeroinitializer, i32 0)
|
||||
%v = extractvalue { <4 x float>, i8 } %r, 0
|
||||
%p = getelementptr <4 x float>, ptr addrspace(1) %o, i32 %x
|
||||
store <4 x float> %v, ptr addrspace(1) %p, align 16
|
||||
ret void
|
||||
}
|
||||
|
||||
declare { <4 x float>, i8 } @air.sample_texture_2d_grad.v4f32(ptr addrspace(1), ptr addrspace(2), <2 x float>, <2 x float>, <2 x float>, float, i1, <2 x i32>, i32)
|
||||
|
||||
!air.kernel = !{!0}
|
||||
!0 = !{ptr @k, !1, !2}
|
||||
!1 = !{}
|
||||
!2 = !{!3, !4, !5, !6}
|
||||
!3 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.sample", !"air.arg_type_name", !"texture2d<float, sample>", !"air.arg_name", !"t"}
|
||||
!4 = !{i32 1, !"air.sampler", !"air.location_index", i32 0, i32 1, !"air.arg_type_name", !"sampler", !"air.arg_name", !"s"}
|
||||
!5 = !{i32 2, !"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"}
|
||||
!6 = !{i32 3, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint2", !"air.arg_name", !"gid"}
|
||||
"#;
|
||||
|
||||
/// Committed profile `stem` without `samplerAnisotropy`: every Vulkan sampler is isotropic there,
|
||||
/// so Metal's anisotropic filter is emulated (the emulation's home), the profile the emulation's
|
||||
/// shape tests compile under.
|
||||
fn p(stem: &str) -> DeviceProfile {
|
||||
let mut desc = crate::pipeline::testing::description(stem).expect(stem);
|
||||
desc.features.remove(&VkFeature::SamplerAnisotropy);
|
||||
Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES)
|
||||
.expect(stem)
|
||||
.profile()
|
||||
.clone()
|
||||
Device::from_queries(desc).expect(stem).profile().clone()
|
||||
}
|
||||
|
||||
/// Committed profile `stem` as described, `samplerAnisotropy` included: the device's own
|
||||
/// anisotropic filter.
|
||||
fn full(stem: &str) -> DeviceProfile {
|
||||
profile(stem, DevicePolicy::RESIDENT_TABLES).expect(stem)
|
||||
profile(stem).expect(stem)
|
||||
}
|
||||
|
||||
fn ok(bc: &[u8], entry: &str, p: &DeviceProfile) -> std::sync::Arc<FunctionArtifact> {
|
||||
@@ -145,31 +105,6 @@ fn ok(bc: &[u8], entry: &str, p: &DeviceProfile) -> std::sync::Arc<FunctionArtif
|
||||
a
|
||||
}
|
||||
|
||||
/// [`RUNTIME_KERNEL`]'s runtime sampler slot.
|
||||
const SLOT: SlotRef = SlotRef {
|
||||
stage: Stage::Kernel,
|
||||
class: SlotClass::Sampler,
|
||||
index: 0,
|
||||
};
|
||||
|
||||
/// The lowering inputs of the variant naming [`SLOT`] (`LoweringInputs::anisotropic_samplers`).
|
||||
fn variant() -> LoweringInputs {
|
||||
let mut inputs = LoweringInputs::new();
|
||||
inputs.anisotropic_samplers.insert(SLOT);
|
||||
inputs
|
||||
}
|
||||
|
||||
/// [`ok`] of entry `k` under `inputs`.
|
||||
fn ok_with(
|
||||
bc: &[u8],
|
||||
inputs: &LoweringInputs,
|
||||
p: &DeviceProfile,
|
||||
) -> std::sync::Arc<FunctionArtifact> {
|
||||
let a = compile_with(bc, "k", p, inputs).unwrap_or_else(|e| panic!("k: compile: {e}"));
|
||||
link_and_validate(&a, p).unwrap_or_else(|e| panic!("k: L3: {e}"));
|
||||
a
|
||||
}
|
||||
|
||||
/// The count of instructions of opcode `op` in `a`'s module.
|
||||
fn count(a: &FunctionArtifact, op: u16) -> usize {
|
||||
let words = &a.module.words;
|
||||
@@ -202,11 +137,9 @@ fn dont_unroll_loops(a: &FunctionArtifact) -> usize {
|
||||
}
|
||||
|
||||
/// A fragment's implicit-level sample through a constexpr sampler of `maxAnisotropy` 3, 8 and 16
|
||||
/// under a linear mip filter, on devices without `samplerAnisotropy`, is Metal's filter emulated:
|
||||
/// no implicit-level sample, one explicit-level sample a tap, the level count queried, and
|
||||
/// `AnisotropicFilter` recorded. With the feature (MoltenVK's here) the device's sample stays,
|
||||
/// unrecorded. Whatever the degree Metal rounds the anisotropy to (4, 8, 16), the code holds tap 0
|
||||
/// and one loop of the others that asks the driver not to unroll it.
|
||||
/// under a linear mip filter is the device's own sample on a device with `samplerAnisotropy` (the
|
||||
/// runtime's floor requires it; MoltenVK's here): one implicit-level sample, unrecorded. An
|
||||
/// isotropic sampler's is untouched too.
|
||||
#[test]
|
||||
fn a_constexpr_anisotropic_sample_takes_metals_filter() {
|
||||
for aniso in [3, 8, 16] {
|
||||
@@ -214,27 +147,6 @@ fn a_constexpr_anisotropic_sample_takes_metals_filter() {
|
||||
let Some(bc) = assemble(&what, &constexpr_fragment(words(MipFilter::Linear, aniso))) else {
|
||||
return;
|
||||
};
|
||||
for stem in ["lavapipe", "amd-780m-radv", "intel-irisxe-anv"] {
|
||||
let what = format!("{what}, {stem}");
|
||||
let a = ok(&bc, "k", &p(stem));
|
||||
assert_eq!(count(&a, OP_IMAGE_SAMPLE_IMPLICIT_LOD), 0, "{what}");
|
||||
assert_eq!(
|
||||
count(&a, OP_IMAGE_SAMPLE_EXPLICIT_LOD),
|
||||
WRITTEN_TAPS as usize,
|
||||
"{what}"
|
||||
);
|
||||
assert_eq!(dont_unroll_loops(&a), 1, "{what}");
|
||||
assert_eq!(count(&a, OP_IMAGE_QUERY_LEVELS), 1, "{what}");
|
||||
assert!(
|
||||
a.precision.contains(&PrecisionNote::AnisotropicFilter),
|
||||
"{what}"
|
||||
);
|
||||
assert!(
|
||||
!a.precision
|
||||
.contains(&PrecisionNote::DeviceAnisotropicFilter),
|
||||
"{what}"
|
||||
);
|
||||
}
|
||||
let a = ok(&bc, "k", &full("moltenvk-m3"));
|
||||
assert_eq!(
|
||||
count(&a, OP_IMAGE_SAMPLE_IMPLICIT_LOD),
|
||||
@@ -253,72 +165,11 @@ fn a_constexpr_anisotropic_sample_takes_metals_filter() {
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
let a = ok(&bc, "k", &p("lavapipe"));
|
||||
let a = ok(&bc, "k", &full("lavapipe"));
|
||||
assert_eq!(count(&a, OP_IMAGE_SAMPLE_IMPLICIT_LOD), 1, "isotropic");
|
||||
assert!(!a.precision.contains(&PrecisionNote::AnisotropicFilter));
|
||||
}
|
||||
|
||||
/// An explicit-gradient sample through a runtime sampler slot states the slot's
|
||||
/// `AnisotropicSampler` fact. Compiled without the slot named, the function is the plain sample
|
||||
/// alone: no `SamplerAnisotropy` specialization, no taps, no note. Under the variant naming the
|
||||
/// slot it reads the slot's `SamplerAnisotropy` specialization and its word's anisotropy and mip
|
||||
/// filter: the emulation (its taps' explicit-level samples) where the word states anisotropy, the
|
||||
/// plain sample elsewhere, and `AnisotropicFilter` recorded under that word alone; each on a
|
||||
/// device without `samplerAnisotropy`. With the feature (MoltenVK's here) nothing of it is
|
||||
/// compiled, and no fact is stated.
|
||||
#[test]
|
||||
fn a_runtime_slot_takes_metals_filter_where_its_word_states_anisotropy() {
|
||||
let Some(bc) = assemble("runtime", RUNTIME_KERNEL) else {
|
||||
return;
|
||||
};
|
||||
let fact = RuntimeFact::AnisotropicSampler { slot: SLOT };
|
||||
let degree = |a: &FunctionArtifact| {
|
||||
a.interface
|
||||
.read_keys()
|
||||
.into_iter()
|
||||
.any(|k| matches!(k, SpecKey::SamplerAnisotropy(_)))
|
||||
};
|
||||
let noted = |a: &FunctionArtifact| {
|
||||
a.specialized
|
||||
.iter()
|
||||
.any(|n| n.note == PrecisionNote::AnisotropicFilter)
|
||||
};
|
||||
for stem in ["lavapipe", "amd-780m-radv"] {
|
||||
let base = ok(&bc, "k", &p(stem));
|
||||
assert!(base.facts.contains(&fact), "{stem}: {:?}", base.facts);
|
||||
assert!(!degree(&base), "{stem}: {:?}", base.interface.read_keys());
|
||||
assert!(!noted(&base), "{stem}");
|
||||
let plain = count(&base, OP_IMAGE_SAMPLE_EXPLICIT_LOD);
|
||||
let a = ok_with(&bc, &variant(), &p(stem));
|
||||
assert!(a.facts.contains(&fact), "{stem}: {:?}", a.facts);
|
||||
let keys = a.interface.read_keys();
|
||||
assert!(degree(&a), "{stem}: {keys:?}");
|
||||
let fields = keys.into_iter().find_map(|k| match k {
|
||||
SpecKey::SamplerState { fields, .. } => Some(fields),
|
||||
_ => None,
|
||||
});
|
||||
let read = SamplerWord::ANISOTROPIC | SamplerWord::MIP_FILTER;
|
||||
assert!(
|
||||
fields.is_some_and(|f| f & read == read),
|
||||
"{stem}: {fields:?}"
|
||||
);
|
||||
// The variant is the base with the emulation's arm: every sample the base takes, and
|
||||
// one a tap of the emulation's, its taps past the first in a loop the driver is asked
|
||||
// not to unroll.
|
||||
assert!(
|
||||
count(&a, OP_IMAGE_SAMPLE_EXPLICIT_LOD) >= plain + WRITTEN_TAPS as usize,
|
||||
"{stem}: {plain}"
|
||||
);
|
||||
assert_eq!(dont_unroll_loops(&a), 1, "{stem}");
|
||||
assert_eq!(dont_unroll_loops(&base), 0, "{stem}");
|
||||
assert!(a.module.words.len() > base.module.words.len(), "{stem}");
|
||||
assert!(noted(&a), "{stem}");
|
||||
}
|
||||
let a = ok(&bc, "k", &full("moltenvk-m3"));
|
||||
assert!(!degree(&a));
|
||||
assert!(!a.facts.contains(&fact));
|
||||
}
|
||||
|
||||
/// 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.
|
||||
@@ -445,101 +296,6 @@ fn an_anisotropic_sample_out_of_reach_records_the_device_filter() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Committed profile `stem` under `policy`, with `samplerAnisotropy` withheld or not.
|
||||
fn anisotropy_of(stem: &str, policy: DevicePolicy, withheld: bool) -> DeviceProfile {
|
||||
let mut desc = crate::pipeline::testing::description(stem).expect(stem);
|
||||
if withheld {
|
||||
assert!(
|
||||
desc.features.remove(&VkFeature::SamplerAnisotropy),
|
||||
"{stem}"
|
||||
);
|
||||
}
|
||||
Device::from_queries(desc, policy)
|
||||
.expect(stem)
|
||||
.profile()
|
||||
.clone()
|
||||
}
|
||||
|
||||
/// Without `samplerAnisotropy` every Vulkan sampler is isotropic, so Metal's anisotropic filter is
|
||||
/// emulated where its reach takes the sample, and the device's isotropic filter is recorded
|
||||
/// elsewhere. On lavapipe with the feature withheld, a fragment's implicit-level sample through a constexpr sampler of
|
||||
/// `maxAnisotropy` 8 takes the taps (`AnisotropicFilter`), a runtime slot's sample states its
|
||||
/// `AnisotropicSampler` fact and takes the taps under the variant (`AnisotropicFilter` under its
|
||||
/// word), and a cube's implicit-level sample records `DeviceAnisotropicFilter`. With the feature
|
||||
/// the module compiles none of it: the device's own sample, no fact, no note. An isotropic
|
||||
/// sampler's sample is the device's either way.
|
||||
#[test]
|
||||
fn without_sampler_anisotropy_metals_filter_is_emulated() {
|
||||
let Some(constexpr) = assemble(
|
||||
"constexpr",
|
||||
&constexpr_fragment(words(MipFilter::Linear, 8)),
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
let Some(isotropic) = assemble(
|
||||
"isotropic",
|
||||
&constexpr_fragment(words(MipFilter::Linear, 1)),
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
let Some(runtime) = assemble("runtime", RUNTIME_KERNEL) else {
|
||||
return;
|
||||
};
|
||||
let cube = out_of_reach_fragment(
|
||||
words(MipFilter::Linear, 8),
|
||||
"texturecube<float, sample>",
|
||||
CUBE_CALL,
|
||||
CUBE_DECL,
|
||||
);
|
||||
let Some(cube) = assemble("cube", &cube) else {
|
||||
return;
|
||||
};
|
||||
let fact = RuntimeFact::AnisotropicSampler { slot: SLOT };
|
||||
for withheld in [false, true] {
|
||||
let what = format!("samplerAnisotropy withheld {withheld}");
|
||||
let p = anisotropy_of("lavapipe", DevicePolicy::RESIDENT_TABLES, withheld);
|
||||
let device = !withheld;
|
||||
let a = ok(&constexpr, "k", &p);
|
||||
assert_eq!(
|
||||
count(&a, OP_IMAGE_SAMPLE_IMPLICIT_LOD),
|
||||
usize::from(device),
|
||||
"{what}"
|
||||
);
|
||||
assert_eq!(dont_unroll_loops(&a), usize::from(!device), "{what}");
|
||||
assert_eq!(
|
||||
a.precision.contains(&PrecisionNote::AnisotropicFilter),
|
||||
!device,
|
||||
"{what}: {:?}",
|
||||
a.precision
|
||||
);
|
||||
let i = ok(&isotropic, "k", &p);
|
||||
assert_eq!(count(&i, OP_IMAGE_SAMPLE_IMPLICIT_LOD), 1, "{what}");
|
||||
assert!(
|
||||
!i.precision.contains(&PrecisionNote::AnisotropicFilter),
|
||||
"{what}"
|
||||
);
|
||||
let base = ok(&runtime, "k", &p);
|
||||
assert_eq!(base.facts.contains(&fact), !device, "{what}");
|
||||
if !device {
|
||||
let v = ok_with(&runtime, &variant(), &p);
|
||||
assert_eq!(dont_unroll_loops(&v), 1, "{what}");
|
||||
assert!(
|
||||
(v.specialized.iter()).any(|n| n.note == PrecisionNote::AnisotropicFilter),
|
||||
"{what}"
|
||||
);
|
||||
}
|
||||
let c = ok(&cube, "k", &p);
|
||||
assert_eq!(
|
||||
c.precision
|
||||
.contains(&PrecisionNote::DeviceAnisotropicFilter),
|
||||
!device,
|
||||
"{what}: {:?}",
|
||||
c.precision
|
||||
);
|
||||
assert_eq!(dont_unroll_loops(&c), 0, "{what}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A kernel sampling `texturecube<float>` slot 0 with explicit gradients through the constexpr
|
||||
/// sampler of first state word `words`, writing the texel to buffer 0.
|
||||
fn constexpr_cube_kernel(words: u64) -> String {
|
||||
@@ -572,72 +328,36 @@ declare {{ <4 x float>, i8 }} @air.sample_texture_cube_grad.v4f32(ptr addrspace(
|
||||
)
|
||||
}
|
||||
|
||||
/// A cube's explicit gradients through a constexpr sampler of `maxAnisotropy` 8 under a linear
|
||||
/// mip filter take Metal's footprint in the shader on every device without `samplerAnisotropy`:
|
||||
/// Metal's level and taps (no gradient sample, the level count queried, tap 0 and the loop's tap
|
||||
/// of one explicit level each, `AnisotropicFilter` recorded and `CubeGradientFootprint` not).
|
||||
/// Through an isotropic sampler a device without the feature keeps its own gradient sample, at the
|
||||
/// footprint the cube's form hands it. On `moltenvk-m3`, whose sampler is anisotropic, the device's
|
||||
/// gradient sample stays, Vulkan's rule's form, recorded as `CubeGradientFootprint`.
|
||||
/// A cube's explicit gradients through a constexpr sampler of `maxAnisotropy` 8 or 1 under a
|
||||
/// linear mip filter keep the device's own gradient sample on `moltenvk-m3`, whose sampler is
|
||||
/// anisotropic: Vulkan's rule's form, recorded as `CubeGradientFootprint`, with no level query and
|
||||
/// no `AnisotropicFilter`.
|
||||
#[test]
|
||||
fn a_cubes_explicit_gradients_take_metals_level_and_taps() {
|
||||
const GRAD: u32 = 0x4;
|
||||
for (aniso, taps) in [(8, true), (1, false)] {
|
||||
let what = format!("maxAnisotropy {aniso}");
|
||||
for aniso in [8, 1] {
|
||||
let what = format!("maxAnisotropy {aniso}, moltenvk-m3");
|
||||
let Some(bc) = assemble(
|
||||
&what,
|
||||
&constexpr_cube_kernel(words(MipFilter::Linear, aniso)),
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
let explicit = if taps { WRITTEN_TAPS as usize } else { 2 };
|
||||
let mut shader = Vec::new();
|
||||
let mut device = vec![("moltenvk-m3", full("moltenvk-m3"))];
|
||||
for stem in ["lavapipe", "amd-780m-radv", "intel-irisxe-anv"] {
|
||||
match taps {
|
||||
true => shader.push((stem, p(stem))),
|
||||
false => device.push((stem, p(stem))),
|
||||
}
|
||||
}
|
||||
for (stem, profile) in shader {
|
||||
let what = format!("{what}, {stem}");
|
||||
let a = ok(&bc, "k", &profile);
|
||||
assert_eq!(count(&a, OP_IMAGE_SAMPLE_EXPLICIT_LOD), explicit, "{what}");
|
||||
assert_eq!(count(&a, OP_IMAGE_QUERY_LEVELS), 1, "{what}");
|
||||
assert_eq!(dont_unroll_loops(&a), usize::from(taps), "{what}");
|
||||
assert_eq!(
|
||||
a.precision.contains(&PrecisionNote::AnisotropicFilter),
|
||||
taps,
|
||||
"{what}: {:?}",
|
||||
a.precision
|
||||
);
|
||||
for note in [
|
||||
PrecisionNote::CubeGradientFootprint,
|
||||
PrecisionNote::DeviceAnisotropicFilter,
|
||||
] {
|
||||
assert!(!a.precision.contains(¬e), "{what}: {:?}", a.precision);
|
||||
}
|
||||
}
|
||||
for (stem, profile) in device {
|
||||
let what = format!("{what}, {stem}");
|
||||
let a = ok(&bc, "k", &profile);
|
||||
assert_eq!(count(&a, OP_IMAGE_SAMPLE_EXPLICIT_LOD), 1, "{what}");
|
||||
assert_eq!(count(&a, OP_IMAGE_QUERY_LEVELS), 0, "{what}");
|
||||
assert_eq!(gradient_masks(&a), vec![GRAD], "{what}");
|
||||
assert!(
|
||||
!a.precision.contains(&PrecisionNote::AnisotropicFilter),
|
||||
"{what}: {:?}",
|
||||
a.precision
|
||||
);
|
||||
// Vulkan's rule's form, the device's reading.
|
||||
if stem == "moltenvk-m3" {
|
||||
assert!(
|
||||
a.precision.contains(&PrecisionNote::CubeGradientFootprint),
|
||||
"{what}: {:?}",
|
||||
a.precision
|
||||
);
|
||||
}
|
||||
}
|
||||
let a = ok(&bc, "k", &full("moltenvk-m3"));
|
||||
assert_eq!(count(&a, OP_IMAGE_SAMPLE_EXPLICIT_LOD), 1, "{what}");
|
||||
assert_eq!(count(&a, OP_IMAGE_QUERY_LEVELS), 0, "{what}");
|
||||
assert_eq!(gradient_masks(&a), vec![GRAD], "{what}");
|
||||
assert!(
|
||||
!a.precision.contains(&PrecisionNote::AnisotropicFilter),
|
||||
"{what}: {:?}",
|
||||
a.precision
|
||||
);
|
||||
// Vulkan's rule's form, the device's reading.
|
||||
assert!(
|
||||
a.precision.contains(&PrecisionNote::CubeGradientFootprint),
|
||||
"{what}: {:?}",
|
||||
a.precision
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -655,181 +375,3 @@ fn gradient_masks(a: &FunctionArtifact) -> Vec<u32> {
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A fragment function summing `n` implicit-level samples of `texture2d<float>` slot 0 through
|
||||
/// runtime sampler slot 0, each at its position scaled by its own power of two, and where
|
||||
/// `offsets` at its own constant texel offset (`(i + 1, -i)` for the `i`-th).
|
||||
fn sampling_fragment(n: usize, offsets: bool) -> String {
|
||||
let mut body = String::new();
|
||||
let mut acc = "zeroinitializer".to_string();
|
||||
for i in 0..n {
|
||||
let scale = 1.0 / f64::from(1u32 << (4 + i));
|
||||
let offset = match offsets {
|
||||
true => format!("<2 x i32> <i32 {}, i32 {}>", i + 1, -(i as i32)),
|
||||
false => "<2 x i32> zeroinitializer".to_string(),
|
||||
};
|
||||
body.push_str(&format!(
|
||||
" %uv{i} = fmul <2 x float> %xy, <float {scale:e}, float {scale:e}>\n \
|
||||
%r{i} = call {{ <4 x float>, i8 }} @air.sample_texture_2d.v4f32(ptr addrspace(1) %t, \
|
||||
ptr addrspace(2) %s, <2 x float> %uv{i}, i1 true, {offset}, i1 false, \
|
||||
float 0.000000e+00, float 0.000000e+00, i32 0)\n \
|
||||
%v{i} = extractvalue {{ <4 x float>, i8 }} %r{i}, 0\n \
|
||||
%a{i} = fadd <4 x float> {acc}, %v{i}\n"
|
||||
));
|
||||
acc = format!("%a{i}");
|
||||
}
|
||||
format!(
|
||||
r#"define <4 x float> @k(<4 x float> %pos, ptr addrspace(1) %t, ptr addrspace(2) %s) {{
|
||||
%xy = shufflevector <4 x float> %pos, <4 x float> poison, <2 x i32> <i32 0, i32 1>
|
||||
{body} ret <4 x float> {acc}
|
||||
}}
|
||||
|
||||
declare {{ <4 x float>, i8 }} @air.sample_texture_2d.v4f32(ptr addrspace(1), ptr addrspace(2), <2 x float>, i1, <2 x i32>, i1, float, float, i32)
|
||||
|
||||
!air.fragment = !{{!0}}
|
||||
!0 = !{{ptr @k, !1, !3}}
|
||||
!1 = !{{!2}}
|
||||
!2 = !{{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"float4"}}
|
||||
!3 = !{{!4, !5, !6}}
|
||||
!4 = !{{i32 0, !"air.position", !"air.center", !"air.no_perspective", !"air.arg_type_name", !"float4", !"air.arg_name", !"position"}}
|
||||
!5 = !{{i32 1, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.sample", !"air.arg_type_name", !"texture2d<float, sample>", !"air.arg_name", !"t"}}
|
||||
!6 = !{{i32 2, !"air.sampler", !"air.location_index", i32 0, i32 1, !"air.arg_type_name", !"sampler", !"air.arg_name", !"s"}}
|
||||
"#
|
||||
)
|
||||
}
|
||||
|
||||
/// The words a sample's site may spend on the emulation's routine besides the plain sample's:
|
||||
/// the word's test and branch, the call with its arguments, and the sum's conversion.
|
||||
const SITE_CALL_WORDS: usize = 256;
|
||||
|
||||
/// The emulation of a runtime sampler slot's samples is one routine every sample calls
|
||||
/// (`routine::Filter`): under the variant naming the slot, a fragment function of 1, 2 and 4 such
|
||||
/// samples holds one emulation's taps (one explicit-level sample each, past the base's) and its
|
||||
/// one loop, and each sample past the first adds no more than the plain sample's words and a
|
||||
/// call's. Written at every site, each sample added about 2,100 words more than the plain one's.
|
||||
#[test]
|
||||
fn anisotropic_samples_call_one_routine() {
|
||||
let inputs = fragment_variant();
|
||||
for stem in ["lavapipe", "intel-irisxe-anv", "nvidia-rtx5080-laptop"] {
|
||||
let p = p(stem);
|
||||
let mut words = Vec::new();
|
||||
for n in [1usize, 2, 4] {
|
||||
let what = format!("{stem}, {n} samples");
|
||||
let Some(bc) = assemble(&what, &sampling_fragment(n, false)) else {
|
||||
return;
|
||||
};
|
||||
let base = ok(&bc, "k", &p);
|
||||
let a = ok_with(&bc, &inputs, &p);
|
||||
assert_eq!(
|
||||
count(&a, OP_IMAGE_SAMPLE_EXPLICIT_LOD),
|
||||
count(&base, OP_IMAGE_SAMPLE_EXPLICIT_LOD) + WRITTEN_TAPS as usize,
|
||||
"{what}"
|
||||
);
|
||||
assert_eq!(dont_unroll_loops(&a), 1, "{what}");
|
||||
words.push((n, base.module.words.len(), a.module.words.len()));
|
||||
}
|
||||
let (n0, base0, variant0) = words[0];
|
||||
for &(n, base, variant) in &words[1..] {
|
||||
let added = n - n0;
|
||||
assert!(
|
||||
variant - variant0 <= base - base0 + added * SITE_CALL_WORDS,
|
||||
"{stem}: {n} samples: the variant grew {} words from {n0}, the base {}",
|
||||
variant - variant0,
|
||||
base - base0
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The fragment of [`sampling_fragment`]'s runtime sampler slot (`LoweringInputs::anisotropic_samplers`).
|
||||
fn fragment_variant() -> LoweringInputs {
|
||||
let mut inputs = LoweringInputs::new();
|
||||
inputs.anisotropic_samplers.insert(SlotRef {
|
||||
stage: Stage::Fragment,
|
||||
class: SlotClass::Sampler,
|
||||
index: 0,
|
||||
});
|
||||
inputs
|
||||
}
|
||||
|
||||
/// The samples of one binding at different constant texel offsets call one routine where the
|
||||
/// profile admits the `Offset` operand on a sample (`maintenance8` and
|
||||
/// `shaderImageGatherExtended`): the call passes the offset, which the taps' samples take as that
|
||||
/// operand, so a fragment of 1, 2 and 4 samples at their own offsets holds one emulation's taps and
|
||||
/// its one loop, no tap sample takes `ConstOffset`, and each sample past the first adds no more
|
||||
/// than the plain sample's words and a call's. Without the operand (`vk12-floor`) each offset is
|
||||
/// its own routine's `ConstOffset`: a loop per sample.
|
||||
#[test]
|
||||
fn anisotropic_samples_at_every_offset_call_one_routine() {
|
||||
let inputs = fragment_variant();
|
||||
for (stem, passes) in [
|
||||
("lavapipe", true),
|
||||
("intel-irisxe-anv", true),
|
||||
("nvidia-rtx5080-laptop", true),
|
||||
("runtime-floor", false),
|
||||
] {
|
||||
let p = p(stem);
|
||||
let images = &p.fields().images;
|
||||
assert_eq!(
|
||||
images.dynamic_sample_offset && images.gather_extended,
|
||||
passes,
|
||||
"{stem}"
|
||||
);
|
||||
let mut words = Vec::new();
|
||||
for n in [1usize, 2, 4] {
|
||||
let what = format!("{stem}, {n} samples at their offsets");
|
||||
let Some(bc) = assemble(&what, &sampling_fragment(n, true)) else {
|
||||
return;
|
||||
};
|
||||
let base = ok(&bc, "k", &p);
|
||||
let a = ok_with(&bc, &inputs, &p);
|
||||
let routines = if passes { 1 } else { n };
|
||||
assert_eq!(dont_unroll_loops(&a), routines, "{what}");
|
||||
assert_eq!(
|
||||
count(&a, OP_IMAGE_SAMPLE_EXPLICIT_LOD),
|
||||
count(&base, OP_IMAGE_SAMPLE_EXPLICIT_LOD) + routines * WRITTEN_TAPS as usize,
|
||||
"{what}"
|
||||
);
|
||||
let taps = if passes { 0 } else { n * WRITTEN_TAPS as usize };
|
||||
assert_eq!(
|
||||
const_offset_samples(&a),
|
||||
const_offset_samples(&base) + taps,
|
||||
"{what}: the taps' samples take ConstOffset only without the Offset operand"
|
||||
);
|
||||
words.push((n, base.module.words.len(), a.module.words.len()));
|
||||
}
|
||||
if passes {
|
||||
let (n0, base0, variant0) = words[0];
|
||||
for &(n, base, variant) in &words[1..] {
|
||||
let added = n - n0;
|
||||
assert!(
|
||||
variant - variant0 <= base - base0 + added * SITE_CALL_WORDS,
|
||||
"{stem}: {n} samples: the variant grew {} words from {n0}, the base {}",
|
||||
variant - variant0,
|
||||
base - base0
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The `ConstOffset` bit of an image operands mask.
|
||||
const CONST_OFFSET: u32 = 0x8;
|
||||
|
||||
/// The explicit-level samples of `a`'s module that take the `ConstOffset` image operand.
|
||||
fn const_offset_samples(a: &FunctionArtifact) -> usize {
|
||||
let words = &a.module.words;
|
||||
let mut found = 0;
|
||||
let mut i = 5;
|
||||
while i < words.len() {
|
||||
let len = ((words[i] >> 16) as usize).max(1);
|
||||
// The operands' mask follows the result type, result, sampled image and coordinate.
|
||||
found += usize::from(
|
||||
(words[i] & 0xffff) as u16 == OP_IMAGE_SAMPLE_EXPLICIT_LOD
|
||||
&& len > 5
|
||||
&& words[i + 5] & CONST_OFFSET != 0,
|
||||
);
|
||||
i += len;
|
||||
}
|
||||
found
|
||||
}
|
||||
@@ -15,9 +15,8 @@
|
||||
//! `clamp_to_zero` reads the border color too). The level is always the base level (Metal's bicubic
|
||||
//! sampler has no mip filter, so the level, bias, gradients, and fragment derivatives select
|
||||
//! nothing), a 2D array's layer is clamped into the array, and what is done with the sum depends on
|
||||
//! the bound format: the [`SpecKey::BicubicTexels`] specialization of the texture slot (under the
|
||||
//! identity domains the same bits, read at run time from the slot's `PushField::BicubicTexels`)
|
||||
//! selects the bilinear inner 2x2 instead (32-bit float channels), clamps the sum into `[0, 1]` or
|
||||
//! the bound format: the bits the slot's `PushField::BicubicTexels` carries, read at run time,
|
||||
//! select the bilinear inner 2x2 instead (32-bit float channels), clamps the sum into `[0, 1]` or
|
||||
//! `[-1, 1]` (normalized channels), or rounds it to `half` (half and small-float channels). A 1D
|
||||
//! texture is filtered bilinearly over taps `i` and `i + 1` whatever its format, with the same
|
||||
//! fraction.
|
||||
@@ -81,7 +80,6 @@
|
||||
//! on a texture slot is an ordinary gather (measured), through the immutable sampler
|
||||
//! [`constexpr_desc`] makes.
|
||||
//!
|
||||
//! [`SpecKey::BicubicTexels`]: crate::pipeline::sym::SpecKey::BicubicTexels
|
||||
//! [`constexpr_desc`]: super::constexpr_desc
|
||||
|
||||
use crate::air::abi::{AddressMode, BorderColor, Filter, SamplerState};
|
||||
@@ -139,10 +137,6 @@ pub struct Bicubic {
|
||||
pub pixel: bool,
|
||||
/// The constant texel offset Metal applies, per plane axis.
|
||||
pub offset: Option<Vec<i32>>,
|
||||
/// The sample reads an 8-bit sRGB texture's raw codes, its slot in the `SrgbTexture`
|
||||
/// variant: each tap's color lanes become the device's decode of their codes (`srgb_raw_tap`)
|
||||
/// before the sum.
|
||||
pub raw: bool,
|
||||
}
|
||||
|
||||
impl Bicubic {
|
||||
@@ -153,16 +147,15 @@ impl Bicubic {
|
||||
|
||||
/// The census words: the footprint (each axis's position, which a pixel coordinate does not
|
||||
/// take), per tap its addressing and fetch, and the calls of the filter's routines, whose own
|
||||
/// words the module counts once ([`routines::Routine::words`]), and a raw sample's tap
|
||||
/// conversions; for a 2D texture the small level's test and linear sample ([`SMALL_WORDS`], its
|
||||
/// four taps' conversions on a raw sample) and each mirrored axis's pinned footprint
|
||||
/// words the module counts once ([`routines::Routine::words`]); for a 2D texture the small
|
||||
/// level's test and linear sample ([`SMALL_WORDS`]) and each mirrored axis's pinned footprint
|
||||
/// ([`PINNED_WORDS`]), and Metal's offset rule on each axis a constant offset moves
|
||||
/// (`position::OFFSET_RULE_WORDS`).
|
||||
pub(super) fn words(&self) -> u32 {
|
||||
let (base, taps) = if self.linear_only() {
|
||||
(448, 2)
|
||||
let base = if self.linear_only() {
|
||||
448
|
||||
} else {
|
||||
(768 + SMALL_WORDS, 20)
|
||||
768 + SMALL_WORDS
|
||||
};
|
||||
let position = if self.pixel {
|
||||
0
|
||||
@@ -180,14 +173,7 @@ impl Bicubic {
|
||||
.as_deref()
|
||||
.map_or(0, |o| o.iter().filter(|o| **o != 0).count() as u32)
|
||||
* super::position::OFFSET_RULE_WORDS;
|
||||
base + position
|
||||
+ mirrored * PINNED_WORDS
|
||||
+ offset
|
||||
+ if self.raw {
|
||||
taps * crate::lower::texture::SRGB_TAP_WORDS
|
||||
} else {
|
||||
0
|
||||
}
|
||||
base + position + mirrored * PINNED_WORDS + offset
|
||||
}
|
||||
}
|
||||
|
||||
@@ -208,65 +194,6 @@ pub(super) fn state(r: SamplerRef) -> Result<Option<SamplerState>, Error> {
|
||||
Ok((s.min_filter == Filter::Bicubic || s.mag_filter == Filter::Bicubic).then_some(s))
|
||||
}
|
||||
|
||||
/// The state of a runtime sampler whose min or mag filter is Metal's `Cubic`, from its word's
|
||||
/// `SamplerWord::CUBIC_STATE` bits (`LoweringInputs::cubic_samplers`): Metal samples through such
|
||||
/// a sampler as through a constexpr bicubic sampler of the same address modes, border color, and
|
||||
/// coordinates, whatever its other filter and the level (990 runs of 8,192
|
||||
/// lanes, nine formats, every address mode and border color, normalized and pixel coordinates,
|
||||
/// min/mag pairs `(2, 2)`, `(2, 1)`, `(1, 2)`, `(2, 0)` and `(0, 2)`, implicit, explicit and
|
||||
/// gradient levels, bit for bit; through an argument buffer alike). `clamp_to_zero` reads the
|
||||
/// sampler's border color, as a runtime sampler's does. The state is both filters bicubic, without
|
||||
/// a mip filter, isotropic, under the weighted-average reduction: a word that states anything else
|
||||
/// is not measured (a mip filter, anisotropy, another reduction, an unnamed border color, or a
|
||||
/// `MirrorClampToEdge` axis, which no bicubic reading covers), and is refused here by the rule the
|
||||
/// binder refuses it by before it names the variant (`metal::bicubic::runtime_cubic_measured`).
|
||||
pub(super) fn cubic_state(word: u32) -> Result<SamplerState, Error> {
|
||||
use crate::air::abi::{CompareFunction, Coordinates, Half, MipFilter, Reduction};
|
||||
if !crate::metal::bicubic::runtime_cubic_measured(word) {
|
||||
return Err(refuse());
|
||||
}
|
||||
let field = |shift: u32, mask: u32| (word & mask) >> shift;
|
||||
let address = |shift: u32, mask: u32| -> Result<AddressMode, Error> {
|
||||
match SamplerAddressMode::try_from(field(shift, mask)) {
|
||||
Ok(SamplerAddressMode::ClampToEdge) => Ok(AddressMode::ClampToEdge),
|
||||
Ok(SamplerAddressMode::Repeat) => Ok(AddressMode::Repeat),
|
||||
Ok(SamplerAddressMode::MirrorRepeat) => Ok(AddressMode::MirroredRepeat),
|
||||
Ok(SamplerAddressMode::ClampToZero) => Ok(AddressMode::ClampToZero),
|
||||
Ok(SamplerAddressMode::ClampToBorderColor) => Ok(AddressMode::ClampToBorder),
|
||||
_ => Err(refuse()),
|
||||
}
|
||||
};
|
||||
let border_color =
|
||||
match SamplerBorderColor::try_from(field(SamplerWord::BORDER_SHIFT, SamplerWord::BORDER)) {
|
||||
Ok(SamplerBorderColor::TransparentBlack) => BorderColor::TransparentBlack,
|
||||
Ok(SamplerBorderColor::OpaqueBlack) => BorderColor::OpaqueBlack,
|
||||
Ok(SamplerBorderColor::OpaqueWhite) => BorderColor::OpaqueWhite,
|
||||
_ => return Err(refuse()),
|
||||
};
|
||||
let [s_shift, t_shift, r_shift] = SamplerWord::ADDRESS_SHIFT;
|
||||
let [s_mask, t_mask, r_mask] = SamplerWord::ADDRESS;
|
||||
Ok(SamplerState {
|
||||
address_s: address(s_shift, s_mask)?,
|
||||
address_t: address(t_shift, t_mask)?,
|
||||
address_r: address(r_shift, r_mask)?,
|
||||
mag_filter: Filter::Bicubic,
|
||||
min_filter: Filter::Bicubic,
|
||||
mip_filter: MipFilter::None,
|
||||
coordinates: if word & SamplerWord::PIXEL_COORDINATES != 0 {
|
||||
Coordinates::Pixel
|
||||
} else {
|
||||
Coordinates::Normalized
|
||||
},
|
||||
compare: CompareFunction::Never,
|
||||
max_anisotropy: 1,
|
||||
lod_min_clamp: Half(0),
|
||||
lod_max_clamp: Half(0),
|
||||
border_color,
|
||||
reduction: Reduction::WeightedAverage,
|
||||
lod_bias: Half(0),
|
||||
})
|
||||
}
|
||||
|
||||
/// The checks every operation through bicubic sampler `s` passes, on a texture of dimension
|
||||
/// `dim` (`depth`, `integer`: its kind; `heap`: an argument-buffer texture), the operation a
|
||||
/// filtered sample where `sample` (not a gather or an LOD query): what the module docs refuse of
|
||||
@@ -346,7 +273,6 @@ pub(super) fn plan(
|
||||
border: s.border_color,
|
||||
pixel: s.coordinates == crate::air::abi::Coordinates::Pixel,
|
||||
offset,
|
||||
raw: false,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -403,51 +329,26 @@ fn i32_value(fb: &mut FunctionBuilder<'_>, t: &Tys, x: i32) -> BResult<SValue> {
|
||||
value(fb, c)
|
||||
}
|
||||
|
||||
/// Whether bit `bit` of the specialization `spec` is set: `0 < (spec & bit)`, computed in the
|
||||
/// function, since a function reads the bound treatment's word as data
|
||||
/// (`PushField::BicubicTexels`).
|
||||
pub(super) fn flag(
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
t: &Tys,
|
||||
spec: ConstId,
|
||||
bit: u32,
|
||||
) -> BResult<SValue> {
|
||||
let v = value(fb, spec)?;
|
||||
Bits::Value(v).test(fb, t, bit)
|
||||
}
|
||||
|
||||
/// A texture slot's format bits as an emulation reads them: the slot's specialization constant, or,
|
||||
/// in the shared emulation of a switch-at-use (SEMANTICS 1012), the bits of the candidate its
|
||||
/// handle names, which the switch's arms yield.
|
||||
/// A texture slot's format bits as an emulation reads them: the slot's pushed field
|
||||
/// (`PushField::BicubicTexels`), or, in the shared emulation of a switch-at-use (SEMANTICS 1012),
|
||||
/// the bits of the candidate its handle names, which the switch's arms yield.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) enum Bits {
|
||||
Spec(ConstId),
|
||||
Value(SValue),
|
||||
}
|
||||
pub(super) struct Bits(pub(super) SValue);
|
||||
|
||||
impl Bits {
|
||||
/// The bits as a `u32` value.
|
||||
pub(super) fn value(self, fb: &mut FunctionBuilder<'_>) -> BResult<SValue> {
|
||||
match self {
|
||||
Bits::Spec(c) => value(fb, c),
|
||||
Bits::Value(v) => Ok(v),
|
||||
}
|
||||
pub(super) fn value(self) -> SValue {
|
||||
self.0
|
||||
}
|
||||
|
||||
/// Whether any bit of `bit` is set: a specialization constant's [`flag`], or the test of the
|
||||
/// value in the function.
|
||||
/// Whether any bit of `bit` is set: `0 < (bits & bit)`, tested in the function.
|
||||
pub(super) fn test(self, fb: &mut FunctionBuilder<'_>, t: &Tys, bit: u32) -> BResult<SValue> {
|
||||
match self {
|
||||
Bits::Spec(c) => flag(fb, t, c, bit),
|
||||
Bits::Value(v) => {
|
||||
let mask = scalar(fb, t.u32_, u64::from(bit))?;
|
||||
let mask = value(fb, mask)?;
|
||||
let zero = scalar(fb, t.u32_, 0)?;
|
||||
let zero = value(fb, zero)?;
|
||||
let and = fb.binary(BinOp::BitwiseAnd, v, mask)?;
|
||||
fb.binary(BinOp::ULessThan, zero, and)
|
||||
}
|
||||
}
|
||||
let mask = scalar(fb, t.u32_, u64::from(bit))?;
|
||||
let mask = value(fb, mask)?;
|
||||
let zero = scalar(fb, t.u32_, 0)?;
|
||||
let zero = value(fb, zero)?;
|
||||
let and = fb.binary(BinOp::BitwiseAnd, self.0, mask)?;
|
||||
fb.binary(BinOp::ULessThan, zero, and)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -791,7 +692,7 @@ fn word_border_texel(
|
||||
SamplerWord::BORDER_SHIFT,
|
||||
SamplerWord::BORDER >> SamplerWord::BORDER_SHIFT,
|
||||
)?;
|
||||
let all = bits.value(fb)?;
|
||||
let all = bits.value();
|
||||
let low = scalar(fb, t.u32_, 1)?;
|
||||
let low = value(fb, low)?;
|
||||
let one = f32_value(fb, t, 1.0)?;
|
||||
@@ -982,7 +883,7 @@ impl Texels<'_> {
|
||||
}
|
||||
Texels::Extended(tex) => {
|
||||
for site in sites {
|
||||
let v = super::extended::texel(cx, fb, fp, tex, site.as_ref(), false)?;
|
||||
let v = super::extended::texel(fb, fp, tex, site.as_ref(), false)?;
|
||||
out.push(post(cx, fb, v)?);
|
||||
}
|
||||
}
|
||||
@@ -1254,26 +1155,17 @@ pub(super) fn word_field(
|
||||
fb.binary(BinOp::BitwiseAnd, f, m)
|
||||
}
|
||||
|
||||
/// The bound format's treatment of texture slot `texture` under the bicubic filter: the slot's
|
||||
/// `BicubicTexels` specialization, or under the identity domains its push field, which the
|
||||
/// consumer writes from the bound texture, read in the open block.
|
||||
/// The bound format's treatment of texture slot `texture` under the bicubic filter: its push
|
||||
/// field, which the consumer writes from the bound texture, read in the open block.
|
||||
pub(super) fn format_bits(
|
||||
cx: &mut EmitCx<'_>,
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
texture: u32,
|
||||
) -> BResult<Bits> {
|
||||
if let Some(&spec) = cx.decl.families.sampler.bicubic.get(&texture) {
|
||||
return Ok(Bits::Spec(spec));
|
||||
}
|
||||
if !cx.plan.families.access.identity {
|
||||
return Err(cx.fail(format!(
|
||||
"texture slot {texture} has no bicubic specialization"
|
||||
)));
|
||||
}
|
||||
let Some(slot) = cx.plan.families.texture.slots.get(&texture) else {
|
||||
return Err(cx.fail(format!("texture slot {texture} is not planned")));
|
||||
};
|
||||
Ok(Bits::Value(
|
||||
Ok(Bits(
|
||||
cx.push_field(fb, PushField::BicubicTexels(slot.slot))?,
|
||||
))
|
||||
}
|
||||
@@ -1318,7 +1210,7 @@ pub(super) fn emit_shared(
|
||||
let t = Tys::new(fb)?;
|
||||
let span = b.span();
|
||||
let taps = b.taps(span);
|
||||
let bits = Bits::Value(bits);
|
||||
let bits = Bits(bits);
|
||||
let fp = footprint_on(cx, fb, &t, s, (size, image), bits, &taps)?;
|
||||
let x = filter(cx, fb, (&t, &fp, size), b, bits, Texels::Candidates(c))?;
|
||||
narrowed(fb, x, half)
|
||||
@@ -1391,15 +1283,8 @@ pub(super) fn filter(
|
||||
};
|
||||
let kx = *kx;
|
||||
let vertical = axes.next().map(|(k, row)| (*k, row));
|
||||
// A raw sample's taps are the device's decode of their codes.
|
||||
let post = |_: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, v: SValue| {
|
||||
if b.raw {
|
||||
crate::lower::texture::srgb_raw_tap(fb, v)
|
||||
} else {
|
||||
Ok(v)
|
||||
}
|
||||
};
|
||||
let flags = bits.value(fb)?;
|
||||
let post = |_: &mut EmitCx<'_>, _: &mut FunctionBuilder<'_>, v: SValue| Ok(v);
|
||||
let flags = bits.value();
|
||||
let call = |fb: &mut FunctionBuilder<'_>, f, args: &[SValue]| -> BResult<SValue> {
|
||||
fb.call(f, args)?.ok_or_else(missing_routine)
|
||||
};
|
||||
|
||||
@@ -160,32 +160,6 @@ fn address(m: AddressMode) -> SamplerAddressMode {
|
||||
}
|
||||
}
|
||||
|
||||
/// The canonical words of constexpr sampler `words` sampling a texture of address-mode map `map`:
|
||||
/// each address mode the map's (`AddressModeMap::constexpr_mode`), as the binder maps a runtime
|
||||
/// sampler's, so its immutable sampler and every emulation that reads its modes follow the map. A
|
||||
/// mode a constexpr sampler cannot state is `NotImplemented(SamplerAddressMode)`.
|
||||
pub fn mapped_words(
|
||||
words: [u64; 2],
|
||||
map: &crate::metal::sampler::AddressModeMap,
|
||||
) -> Result<[u64; 2], Error> {
|
||||
let s = state_of(words)?;
|
||||
let to = |m: AddressMode| -> Result<AddressMode, Error> {
|
||||
match map.constexpr_mode(address(m)) {
|
||||
Some(mode) if mode == address(m) => Ok(m),
|
||||
Some(SamplerAddressMode::ClampToEdge) => Ok(AddressMode::ClampToEdge),
|
||||
Some(SamplerAddressMode::Repeat) => Ok(AddressMode::Repeat),
|
||||
Some(SamplerAddressMode::MirrorRepeat) => Ok(AddressMode::MirroredRepeat),
|
||||
_ => Err(Unsupported::not_implemented(Feature::SamplerAddressMode).into()),
|
||||
}
|
||||
};
|
||||
Ok(state_words(&SamplerState {
|
||||
address_s: to(s.address_s)?,
|
||||
address_t: to(s.address_t)?,
|
||||
address_r: to(s.address_r)?,
|
||||
..s
|
||||
}))
|
||||
}
|
||||
|
||||
/// The address modes on the `s`, `t` and `r` coordinates that constexpr sampler words `words`
|
||||
/// state, as Metal names them (`address::clamp_to_zero` is `ClampToZero`, a border color's code 0
|
||||
/// `ClampToBorderColor`); `None` for words that state no sampler.
|
||||
@@ -253,12 +227,6 @@ fn descriptor(s: &SamplerState) -> Result<SamplerDescriptor, Error> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the device's unnormalized sampler reads constexpr sampler state `s` in pixel
|
||||
/// coordinates as it is (`metal::sampler::unnormalized_reads` of its descriptor).
|
||||
pub(crate) fn unnormalized_reads(s: &SamplerState) -> Result<bool, Error> {
|
||||
Ok(crate::metal::sampler::unnormalized_reads(&descriptor(s)?))
|
||||
}
|
||||
|
||||
/// The immutable `VkSampler` of constexpr sampler `words` used as `use_` on `profile`. Every
|
||||
/// refusal is a feature check of the constexpr state (bicubic filtering, anisotropy, border colors,
|
||||
/// mirror-clamp, comparison and any LOD bias where the portability subset withholds
|
||||
@@ -310,11 +278,10 @@ pub fn constexpr_desc(
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::air::abi::Half;
|
||||
use crate::device::DevicePolicy;
|
||||
use crate::error::Needs;
|
||||
|
||||
fn profile(stem: &str) -> DeviceProfile {
|
||||
crate::pipeline::testing::profile(stem, DevicePolicy::RESIDENT_TABLES).expect("profile")
|
||||
crate::pipeline::testing::profile(stem).expect("profile")
|
||||
}
|
||||
|
||||
/// The words of the public fixtures' constexpr samplers (bit 63 clear).
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
//! Emission of the sampling strategies.
|
||||
|
||||
use crate::lower::emit::EmitCx;
|
||||
use crate::lower::texture::{
|
||||
heap_element, held_texel, live_or_zero, resident_access, sparse_spec, tile_map, tiled_word,
|
||||
with_word,
|
||||
};
|
||||
use crate::lower::texture::{heap_element, held_texel, live_or_zero, with_word};
|
||||
use crate::spirv::builder::constructs::{ArmEnd, ArmFn, Merged};
|
||||
use crate::spirv::builder::ops::image::ArmedOffset;
|
||||
use crate::spirv::builder::FunctionBuilder;
|
||||
@@ -17,50 +14,15 @@ use crate::spirv::ir::{
|
||||
|
||||
use crate::air::ir::ValueId;
|
||||
use crate::lower::texture::TexelClass;
|
||||
use crate::memory::handles::{entry_field, EntryField};
|
||||
use crate::memory::handles::EntryField;
|
||||
use crate::metal::sampler::{SamplerUse, SamplerWord};
|
||||
use crate::pipeline::sym::{CombinedSampler, SamplerRef};
|
||||
|
||||
use super::{
|
||||
BiasReach, Binding, CombinedImage, CubeFootprint, Hoist, Lod, MinLevel, Offset, Pixel,
|
||||
PixelPosition, SampleOp, Sampling, Source, Unmapped,
|
||||
BiasReach, CombinedImage, CubeFootprint, Hoist, Lod, MinLevel, Offset, Pixel, PixelPosition,
|
||||
SampleOp, Sampling, Source,
|
||||
};
|
||||
|
||||
impl Binding {
|
||||
/// The sampled image of the binding, made in the open block (where it must be consumed): the
|
||||
/// combined image sampler, or `OpSampledImage` of the separate texture and sampler.
|
||||
pub fn sampled_image(self, fb: &mut FunctionBuilder<'_>) -> BResult<SValue> {
|
||||
match self {
|
||||
Binding::Combined(g) => {
|
||||
let ptr = fb.module().global_value(g)?;
|
||||
fb.load(ptr, MemAccess::default())
|
||||
}
|
||||
Binding::Separate { image, sampler } => {
|
||||
let image = fb.module().global_value(image)?;
|
||||
let image = fb.load(image, MemAccess::default())?;
|
||||
let sampler = fb.module().global_value(sampler)?;
|
||||
let sampler = fb.load(sampler, MemAccess::default())?;
|
||||
fb.sampled_image(image, sampler)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The image of the binding: `OpImage` of the combined image sampler, or the separate
|
||||
/// texture.
|
||||
pub fn image(self, fb: &mut FunctionBuilder<'_>) -> BResult<SValue> {
|
||||
match self {
|
||||
Binding::Combined(_) => {
|
||||
let si = self.sampled_image(fb)?;
|
||||
fb.image(si)
|
||||
}
|
||||
Binding::Separate { image, .. } => {
|
||||
let image = fb.module().global_value(image)?;
|
||||
fb.load(image, MemAccess::default())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The lowest exponent [`bias_gradients`] scales by: `2^-150` rounds to zero (or the smallest
|
||||
/// denormal), so every scaled component is at most `2^-149` and the level is below 0.
|
||||
const BIAS_EXPONENT_MIN: f32 = -150.0;
|
||||
@@ -630,19 +592,13 @@ pub(super) fn sampled_image(
|
||||
source: Source,
|
||||
) -> BResult<(SValue, CombinedImage, Option<SValue>)> {
|
||||
match source {
|
||||
Source::Combined(key) if cx.plan.families.access.identity => {
|
||||
Source::Combined(key) => {
|
||||
let (si, image) = identity_sampled_image(cx, fb, key)?;
|
||||
Ok((si, image, None))
|
||||
}
|
||||
Source::Combined(key) => {
|
||||
let Some(&(binding, image)) = cx.decl.families.sampler.combined.get(&key) else {
|
||||
return Err(cx.fail(format!("combined binding {key:?} is not declared")));
|
||||
};
|
||||
Ok((binding.sampled_image(fb)?, image, None))
|
||||
}
|
||||
// Under the identity domains the heap element through the slot's or constexpr sampler's
|
||||
// element of the set-1 sampler array of the use, as a texture slot's sampling reads it.
|
||||
Source::Heap { handle, key } if cx.plan.families.access.identity => {
|
||||
// The heap element through the slot's or constexpr sampler's element of the set-1 sampler
|
||||
// array of the use, as a texture slot's sampling reads it.
|
||||
Source::Heap { handle, key } => {
|
||||
let Some(use_) = cx.plan.families.sampler.heap_identity.get(&key).copied() else {
|
||||
return Err(cx.fail(format!("heap sampler {key:?} has no identity use")));
|
||||
};
|
||||
@@ -656,21 +612,6 @@ pub(super) fn sampled_image(
|
||||
};
|
||||
Ok((si, image, element.live))
|
||||
}
|
||||
Source::Heap { handle, key } => {
|
||||
let Some(g) = cx.decl.families.sampler.heap.get(&key).copied() else {
|
||||
return Err(cx.fail(format!("heap sampler {key:?} is not declared")));
|
||||
};
|
||||
let element = heap_element(cx, fb, key.group, handle)?;
|
||||
let ptr = fb.module().global_value(g)?;
|
||||
let sampler = fb.load(ptr, MemAccess::default())?;
|
||||
let si = fb.sampled_image(element.img, sampler)?;
|
||||
let image = CombinedImage {
|
||||
plane: super::plane_of(element.decl.dim),
|
||||
arrayed: element.decl.arrayed,
|
||||
texel: element.decl.texel,
|
||||
};
|
||||
Ok((si, image, element.live))
|
||||
}
|
||||
Source::HeapSampler {
|
||||
handle,
|
||||
sampler,
|
||||
@@ -694,14 +635,14 @@ pub(super) fn sampled_image(
|
||||
};
|
||||
Ok((si, image, element.live))
|
||||
}
|
||||
// Under the identity domains the heap element through the set-1 sampler array's element
|
||||
// at the pushed index of the candidate the handle names.
|
||||
// The heap element through the set-1 sampler array's element at the pushed index of the
|
||||
// candidate the handle names.
|
||||
Source::HeapArray {
|
||||
handle,
|
||||
sampler,
|
||||
key,
|
||||
..
|
||||
} if cx.plan.families.access.identity => {
|
||||
} => {
|
||||
let Some(use_) = (cx.plan.families.sampler.heap_array_identity)
|
||||
.get(&key)
|
||||
.copied()
|
||||
@@ -726,30 +667,6 @@ pub(super) fn sampled_image(
|
||||
};
|
||||
Ok((si, image, element.live))
|
||||
}
|
||||
Source::HeapArray {
|
||||
handle,
|
||||
sampler,
|
||||
key,
|
||||
..
|
||||
} => {
|
||||
let Some(g) = cx.decl.families.sampler.heap_arrays.get(&key).copied() else {
|
||||
return Err(cx.fail(format!("constexpr sampler array {key:?} is not declared")));
|
||||
};
|
||||
let element = heap_element(cx, fb, key.group, handle)?;
|
||||
// The element the sampler handle names (element 0 where it names none, whose result
|
||||
// `sampling_value` makes zero), which may differ between invocations.
|
||||
let (index, _) = array_element(cx, fb, sampler, key)?;
|
||||
let base = fb.module().global_value(g)?;
|
||||
let p = fb.access_chain_non_uniform(base, index)?;
|
||||
let sampler = fb.load(p, MemAccess::default())?;
|
||||
let si = fb.sampled_image(element.img, sampler)?;
|
||||
let image = CombinedImage {
|
||||
plane: super::plane_of(element.decl.dim),
|
||||
arrayed: element.decl.arrayed,
|
||||
texel: element.decl.texel,
|
||||
};
|
||||
Ok((si, image, element.live))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -822,63 +739,9 @@ fn identity_element(
|
||||
index.ok_or_else(|| cx.fail("a sampler array without samplers"))
|
||||
}
|
||||
|
||||
/// The word (`metal::sampler::SamplerWord`) of the constexpr sampler at the element of sampling
|
||||
/// `s`'s constexpr sampler array its sampler handle names (`Source::HeapArray`):
|
||||
/// `ConstexprArray::words` selected at run time, element 0's where the handle names none (whose
|
||||
/// result the sampling makes zero).
|
||||
pub(super) fn array_word(
|
||||
cx: &mut EmitCx<'_>,
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
s: &Sampling,
|
||||
) -> BResult<SValue> {
|
||||
let Source::HeapArray { sampler, key, .. } = s.source else {
|
||||
return Err(cx.fail("a sampler array's word outside a sampler array"));
|
||||
};
|
||||
let words = usize::try_from(key.array)
|
||||
.ok()
|
||||
.and_then(|a| cx.plan.families.sampler.arrays.get(a))
|
||||
.map(|a| a.words.clone());
|
||||
let Some(words) = words else {
|
||||
return Err(cx.fail(format!("constexpr sampler array {key:?} is not planned")));
|
||||
};
|
||||
let (element, _) = array_element(cx, fb, sampler, key)?;
|
||||
let mut word = None;
|
||||
for (k, w) in (0u32..).zip(words) {
|
||||
let w = fb.u32_const(w)?;
|
||||
let w = fb.module().const_value(w)?;
|
||||
word = Some(match word {
|
||||
None => w,
|
||||
Some(v) => {
|
||||
let k = fb.u32_const(k)?;
|
||||
let k = fb.module().const_value(k)?;
|
||||
let is = fb.binary(BinOp::IEqual, element, k)?;
|
||||
fb.select(is, w, v)?
|
||||
}
|
||||
});
|
||||
}
|
||||
word.ok_or_else(|| cx.fail("a sampler array without samplers"))
|
||||
}
|
||||
|
||||
/// Where a sampling operation observes its residency on a slot with a sparse arm: the slot's
|
||||
/// `SparseTexture` specialization, and the combined binding, whose sampled image each arm makes (a
|
||||
/// sampled image is consumed in the block that makes it).
|
||||
fn sparse_arm(cx: &mut EmitCx<'_>, s: &Sampling) -> BResult<Option<(SValue, Binding)>> {
|
||||
let Source::Combined(key) = s.source else {
|
||||
return Ok(None);
|
||||
};
|
||||
let Some(spec) = sparse_spec(cx, key.texture, s.residency) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let Some(&(binding, _)) = cx.decl.families.sampler.combined.get(&key) else {
|
||||
return Err(cx.fail(format!("combined binding {key:?} is not declared")));
|
||||
};
|
||||
Ok(Some((spec, binding)))
|
||||
}
|
||||
|
||||
/// The value of sampling strategy `s` in the open block; `grads` are the gradients of a rule-2
|
||||
/// sample (`Lod::Hoisted`), computed by its switch-at-use. A heap element's sample is zero for the
|
||||
/// null element. An operation through an argument buffer's sampler then tests the sampler's word
|
||||
/// for a cubic filter where the stage marks it ([`cubic_reach`]).
|
||||
/// null element.
|
||||
pub fn sampling_value(
|
||||
cx: &mut EmitCx<'_>,
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
@@ -889,22 +752,6 @@ pub fn sampling_value(
|
||||
true => swizzled_value(cx, fb, s, grads)?,
|
||||
false => sampled_value(cx, fb, s, grads)?,
|
||||
};
|
||||
// A texture the heap holds by its raw texels alone: Metal's sample or gather of it, after
|
||||
// the device's access, which stays where it was.
|
||||
let value = match &s.heap_raw {
|
||||
Some(raw) => super::heap_raw::emit(cx, fb, s, raw, value)?,
|
||||
None => value,
|
||||
};
|
||||
// A texture of another class: its own result's words handed back as declared.
|
||||
let value = match &s.declared {
|
||||
Some(d) => declared_value(cx, fb, s, d, value)?,
|
||||
None => value,
|
||||
};
|
||||
if let Source::HeapSampler { sampler, .. } = s.source {
|
||||
if cx.plan.families.sampler.cubic_reach {
|
||||
cubic_reach(cx, fb, sampler)?;
|
||||
}
|
||||
}
|
||||
// A sampler handle outside a constexpr sampler array: zero, as the switch's null arm.
|
||||
if let Source::HeapArray { sampler, key, .. } = s.source {
|
||||
let (_, named) = array_element(cx, fb, sampler, key)?;
|
||||
@@ -921,10 +768,8 @@ pub fn sampling_value(
|
||||
/// unswizzled texture's held texel, which its class converts, swizzled by the slot's
|
||||
/// `TextureSwizzle` specialization as plain Metal swizzles a sampled texture's texels; a gather
|
||||
/// of a component made of the unswizzled texture's gathers of each component, the one the
|
||||
/// swizzle names taken (0 or 1 at every tap for its `Zero` or `One`); then the lanes Metal reads
|
||||
/// as constants, which the slot's `ConstantLanes` specialization states through the swizzle
|
||||
/// ([`held_constants`], which the unswizzled accesses skip). A gather's status word is its
|
||||
/// red gather's: each of the four reads the same texels.
|
||||
/// swizzle names taken (0 or 1 at every tap for its `Zero` or `One`). A gather's status word is
|
||||
/// its red gather's: each of the four reads the same texels.
|
||||
fn swizzled_value(
|
||||
cx: &mut EmitCx<'_>,
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
@@ -940,7 +785,7 @@ fn swizzled_value(
|
||||
key.texture
|
||||
)));
|
||||
};
|
||||
let (texel, status, gathered) = match &s.op {
|
||||
let (texel, status) = match &s.op {
|
||||
SampleOp::Gather {
|
||||
component,
|
||||
dref,
|
||||
@@ -966,22 +811,12 @@ fn swizzled_value(
|
||||
return Err(cx.fail("a swizzled gather without four components"));
|
||||
};
|
||||
let x = crate::lower::texture::swizzled_gather(cx, fb, taps, word, *component)?;
|
||||
(x, status, Some(*component))
|
||||
(x, status)
|
||||
}
|
||||
_ => {
|
||||
let value = sampled_value(cx, fb, s, grads)?;
|
||||
let (x, w) = texel_and_word(cx, fb, s, value)?;
|
||||
(
|
||||
crate::lower::texture::swizzled_held(cx, fb, x, word)?,
|
||||
w,
|
||||
None,
|
||||
)
|
||||
}
|
||||
};
|
||||
let texel = match s.unmapped {
|
||||
Unmapped::Device => texel,
|
||||
Unmapped::Constants | Unmapped::Named => {
|
||||
crate::lower::texture::constant_lanes(cx, fb, key.texture, texel, gathered)?
|
||||
(crate::lower::texture::swizzled_held(cx, fb, x, word)?, w)
|
||||
}
|
||||
};
|
||||
with_word(cx, fb, &s.result, texel, status)
|
||||
@@ -1007,67 +842,6 @@ fn texel_and_word(
|
||||
}
|
||||
}
|
||||
|
||||
/// Sampling `s`'s value `value` of its texture's own class (`Sampling::result`, a `{T, i8}` or
|
||||
/// `T` of the native texel `Sampling::texel`) as its declared result `d`: the texel's words
|
||||
/// handed back as the declared type (`texture::reinterpret`), the status word kept.
|
||||
fn declared_value(
|
||||
cx: &mut EmitCx<'_>,
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
s: &Sampling,
|
||||
d: &super::DeclaredResult,
|
||||
value: SValue,
|
||||
) -> BResult<SValue> {
|
||||
let Some(native) = s.texel else {
|
||||
return Err(cx.fail("a declared sampling result without its texel"));
|
||||
};
|
||||
let Some(ty) = crate::lower::arith::spirv_type(fb.module(), &s.result)? else {
|
||||
return Err(cx.fail("a sampling result without a lowered type"));
|
||||
};
|
||||
let (x, word) = match matches!(fb.module().types().get(ty)?, SType::Struct { .. }) {
|
||||
true => (
|
||||
fb.composite_extract(value, &[0])?,
|
||||
Some(fb.composite_extract(value, &[1])?),
|
||||
),
|
||||
false => (value, None),
|
||||
};
|
||||
let x = crate::lower::texture::reinterpret(fb, native, d.conv, x)?;
|
||||
with_word(cx, fb, &d.result, x, word)
|
||||
}
|
||||
|
||||
/// Where the argument buffer's sampler of handle `sampler` is cubic (its table entry's word holds
|
||||
/// `SamplerWord::CUBIC`), set `StatusBits::CUBIC_ARGUMENT_SAMPLER` in the command buffer's
|
||||
/// `ExecutionStatus` word (`RuntimeFact::CubicArgumentSampler`): the operation sampled through
|
||||
/// the Vulkan sampler's nearest placeholder, not Metal's bicubic filter, so its command buffer
|
||||
/// fails. The mark is on that path only: the operation itself, implicit derivatives and all, ran
|
||||
/// before the test, outside the selection. An operation through the same handle after an earlier
|
||||
/// one of its block runs no test of its own: wherever it runs, that test ran on the same sampler
|
||||
/// (16 samples of one handle in a block test once).
|
||||
fn cubic_reach<'c>(
|
||||
cx: &mut EmitCx<'c>,
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
sampler: ValueId,
|
||||
) -> BResult<()> {
|
||||
if cx.cubic_test_dominates(fb, sampler) {
|
||||
return Ok(());
|
||||
}
|
||||
// `CUBIC` is the word's highest bit (`SamplerWord::FIELDS`).
|
||||
let word = heap_sampler_field(cx, fb, sampler, EntryField::Flags)?;
|
||||
let bit = fb.u32_const(SamplerWord::CUBIC)?;
|
||||
let bit = fb.module().const_value(bit)?;
|
||||
let cubic = fb.binary(BinOp::UGreaterThanEqual, word, bit)?;
|
||||
let mark: ArmFn<'_, EmitCx<'c>> = Box::new(|fb, cx| {
|
||||
crate::lower::access::absent::mark_bits(
|
||||
cx,
|
||||
fb,
|
||||
crate::bind::status::StatusBits::CUBIC_ARGUMENT_SAMPLER,
|
||||
)?;
|
||||
Ok(ArmEnd::FallThrough(Vec::new()))
|
||||
});
|
||||
fb.if_(cx, cubic, mark, None)?;
|
||||
cx.cubic_tested(fb, sampler, word);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// [`sampling_value`] before an argument buffer's sampler's cubic test.
|
||||
pub(super) fn sampled_value(
|
||||
cx: &mut EmitCx<'_>,
|
||||
@@ -1085,30 +859,8 @@ pub(super) fn sampled_value(
|
||||
let x = query_level(cx, fb, si, *min)?;
|
||||
return live_or_zero(fb, live, x);
|
||||
}
|
||||
let arm = sparse_arm(cx, s)?;
|
||||
// A tile map answers a pixel sampler's fetch and a sample or gather with Metal's footprint:
|
||||
// selection gives a slot whose observed samples or gathers it does not answer no tile-map arm.
|
||||
let tiled = match s.source {
|
||||
Source::Combined(key) => tile_map(cx, key.texture),
|
||||
Source::Heap { .. } | Source::HeapSampler { .. } | Source::HeapArray { .. } => None,
|
||||
};
|
||||
let fetched = matches!(s.op, SampleOp::PixelFetch { .. });
|
||||
if arm.is_some() && tiled.is_some() && !fetched && s.footprint.is_none() {
|
||||
return Err(cx.fail("a filtered sample's residency on a slot with a tile map"));
|
||||
}
|
||||
// Metal's footprint: the device's plain sample or gather, and the word of exactly the texels
|
||||
// Metal counts, through the slot's sparse arm or tile map.
|
||||
let exact = match (arm, s.footprint, tiled) {
|
||||
(Some((spec, binding)), Some(fp), Some(map)) => Some((spec, binding, fp, map)),
|
||||
(Some(_), Some(_), None) => {
|
||||
return Err(cx.fail("Metal's footprint on a slot without a tile map"))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let arm = if exact.is_some() { None } else { arm };
|
||||
if let SampleOp::PixelFetch { offset } = &s.op {
|
||||
let (x, word) = pixel_fetch(cx, fb, s, si, image, offset.as_ref(), arm)?;
|
||||
let x = unmapped_value(cx, fb, s, x, word)?;
|
||||
let (x, word) = pixel_fetch(cx, fb, s, si, image, offset.as_ref())?;
|
||||
let x = live_or_zero(fb, live, x)?;
|
||||
return texel_value(cx, fb, s, image, x, word);
|
||||
}
|
||||
@@ -1148,26 +900,13 @@ pub(super) fn sampled_value(
|
||||
// bias past the device's limit scales, and from which Metal's footprint of an observed access
|
||||
// follows.
|
||||
let plane = coord;
|
||||
let (coord, layer) = layered(cx, fb, s, coord)?;
|
||||
// The access, from the sampled image `si`; under a sparse arm each arm loads its own.
|
||||
// The access, from the sampled image `si` (loaded in the open block); under a sparse arm each
|
||||
// arm loads its own.
|
||||
let observe = |cx: &mut EmitCx<'_>,
|
||||
let (coord, _) = layered(cx, fb, s, coord)?;
|
||||
// The access, from the sampled image `si` (loaded in the open block).
|
||||
let observe = |_: &mut EmitCx<'_>,
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
si: SValue,
|
||||
access: &dyn Fn(&mut FunctionBuilder<'_>, SValue, bool) -> BResult<SValue>|
|
||||
-> BResult<(SValue, Option<SValue>)> {
|
||||
match arm {
|
||||
Some((spec, binding)) => {
|
||||
let (x, word) = resident_access(cx, fb, spec, |fb, sparse| {
|
||||
let si = binding.sampled_image(fb)?;
|
||||
access(fb, si, sparse)
|
||||
})?;
|
||||
Ok((x, Some(word)))
|
||||
}
|
||||
None => Ok((access(fb, si, false)?, None)),
|
||||
}
|
||||
};
|
||||
-> BResult<(SValue, Option<SValue>)> { Ok((access(fb, si, false)?, None)) };
|
||||
let (texel, word) = match &s.op {
|
||||
SampleOp::Sample {
|
||||
lod,
|
||||
@@ -1259,18 +998,6 @@ pub(super) fn sampled_value(
|
||||
return Err(cx.fail("a fetching sample or level query past its own path"))
|
||||
}
|
||||
};
|
||||
let word = match exact {
|
||||
Some((spec, binding, fp, map)) => {
|
||||
let site = super::footprint::Site {
|
||||
binding,
|
||||
coord: plane,
|
||||
lanes: s.lanes,
|
||||
layer,
|
||||
};
|
||||
Some(super::footprint::word(cx, fb, fp, spec, map, site)?)
|
||||
}
|
||||
None => word,
|
||||
};
|
||||
let texel = live_or_zero(fb, live, texel)?;
|
||||
texel_value(cx, fb, s, image, texel, word)
|
||||
}
|
||||
@@ -1335,8 +1062,8 @@ pub(super) fn plane_and_gradients(
|
||||
}
|
||||
|
||||
/// Whether `s`'s plane coordinate is in pixels: `None` when normalized, `Some(None)` always, and
|
||||
/// `Some(Some(c))` where `bool` `c` says so (a runtime sampler's word, its slot's `SamplerState`
|
||||
/// specialization or its argument buffer table entry's).
|
||||
/// `Some(Some(c))` where `bool` `c` says so (a runtime sampler's word, its slot's pushed resource
|
||||
/// ID's or its argument buffer sampler's).
|
||||
pub(super) fn pixel_coordinates(
|
||||
cx: &mut EmitCx<'_>,
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
@@ -1352,23 +1079,18 @@ pub(super) fn pixel_coordinates(
|
||||
})
|
||||
}
|
||||
|
||||
/// The word of the runtime sampler `pixel` names: a slot's `SamplerState` specialization (masked by
|
||||
/// the fields the function reads), or under the identity domains its pushed resource ID's high
|
||||
/// word, whole; or an argument buffer's sampler table entry's.
|
||||
/// The word of the runtime sampler `pixel` names: a slot's pushed resource ID's high word, whole;
|
||||
/// or an argument buffer's sampler's resource ID's.
|
||||
pub(crate) fn sampler_word(
|
||||
cx: &mut EmitCx<'_>,
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
pixel: Pixel,
|
||||
) -> BResult<SValue> {
|
||||
match pixel {
|
||||
Pixel::Spec(n) if cx.plan.families.access.identity => {
|
||||
Pixel::Spec(n) => {
|
||||
let id = sampler_id(cx, fb, n)?;
|
||||
fb.composite_extract(id, &[1])
|
||||
}
|
||||
Pixel::Spec(n) => match cx.decl.families.sampler.words.get(&n).copied() {
|
||||
Some(w) => Ok(w),
|
||||
None => Err(cx.fail(format!("sampler slot {n} has no state word"))),
|
||||
},
|
||||
Pixel::Heap(handle) => heap_sampler_field(cx, fb, handle, EntryField::Flags),
|
||||
Pixel::None | Pixel::Always => Err(cx.fail("a constexpr sampler's word")),
|
||||
}
|
||||
@@ -1462,19 +1184,12 @@ fn heap_sampler_field(
|
||||
handle: ValueId,
|
||||
field: EntryField,
|
||||
) -> BResult<SValue> {
|
||||
if cx.plan.families.access.identity {
|
||||
let id = cx.operand(fb, handle)?;
|
||||
let word = match field {
|
||||
EntryField::Element => 0,
|
||||
EntryField::Flags => 1,
|
||||
};
|
||||
return fb.composite_extract(id, &[word]);
|
||||
}
|
||||
let Some(table) = cx.decl.families.access.sampler_table else {
|
||||
return Err(cx.fail("an argument buffer's sampler without its sampler table"));
|
||||
let id = cx.operand(fb, handle)?;
|
||||
let word = match field {
|
||||
EntryField::Element => 0,
|
||||
EntryField::Flags => 1,
|
||||
};
|
||||
let k = cx.operand(fb, handle)?;
|
||||
entry_field(fb, table.table, k, field)
|
||||
fb.composite_extract(id, &[word])
|
||||
}
|
||||
|
||||
/// Whether sampler word `word` masked by `mask` is exactly [`SamplerWord::PIXEL_COORDINATES`] (a
|
||||
@@ -1551,20 +1266,14 @@ pub(super) fn centre(
|
||||
}
|
||||
PixelPosition::Texel => Centre::Texel,
|
||||
PixelPosition::TexelBySpec => {
|
||||
let Pixel::Spec(n) = s.pixel else {
|
||||
let Pixel::Spec(_) = s.pixel else {
|
||||
return Err(cx.fail("a specialized texel centre without a runtime sampler slot"));
|
||||
};
|
||||
// Under the identity domains the slot's word says whether it is a nearest pixel
|
||||
// sampler, as an argument buffer's sampler's does.
|
||||
if cx.plan.families.access.identity {
|
||||
let mask = SamplerWord::nearest_pixel(image.texel != TexelClass::Float);
|
||||
let word = sampler_word(cx, fb, s.pixel)?;
|
||||
return Ok(Centre::TexelWhere(word_states(fb, word, mask)?));
|
||||
}
|
||||
match cx.decl.families.sampler.nearest.get(&n).copied() {
|
||||
Some(c) => Centre::TexelWhere(c),
|
||||
None => return Err(cx.fail(format!("sampler slot {n} has no nearest constant"))),
|
||||
}
|
||||
// The slot's word says whether it is a nearest pixel sampler, as an argument buffer's
|
||||
// sampler's does.
|
||||
let mask = SamplerWord::nearest_pixel(image.texel != TexelClass::Float);
|
||||
let word = sampler_word(cx, fb, s.pixel)?;
|
||||
Centre::TexelWhere(word_states(fb, word, mask)?)
|
||||
}
|
||||
PixelPosition::TexelByWord => {
|
||||
let Pixel::Heap(handle) = s.pixel else {
|
||||
@@ -2007,8 +1716,8 @@ fn metal_offset(
|
||||
|
||||
/// Metal's answer to a LOD query outside a fragment function: 0 for the unclamped level (`min`
|
||||
/// `None`), and for the clamped one the sampler's minimum level in sixty-fourths bounded by the
|
||||
/// last level of `si`'s image; under the identity domains a runtime sampler's from its word
|
||||
/// ([`MinLevel::Slot`], [`word_min_level`]).
|
||||
/// last level of `si`'s image; a runtime sampler's from its word ([`MinLevel::Slot`],
|
||||
/// [`word_min_level`]).
|
||||
fn query_level(
|
||||
cx: &mut EmitCx<'_>,
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
@@ -2018,19 +1727,10 @@ fn query_level(
|
||||
let min = match min {
|
||||
None | Some(MinLevel::Const(0)) => return f32_const(fb, 0),
|
||||
Some(MinLevel::Const(v)) => f32_const(fb, (v as f32 / 64.0).to_bits())?,
|
||||
Some(MinLevel::Slot(n)) if cx.plan.families.access.identity => {
|
||||
Some(MinLevel::Slot(n)) => {
|
||||
let word = sampler_word(cx, fb, Pixel::Spec(n))?;
|
||||
word_min_level(fb, word)?
|
||||
}
|
||||
Some(MinLevel::Slot(n)) => {
|
||||
let Some(v) = cx.decl.families.sampler.min_levels.get(&n).copied() else {
|
||||
return Err(cx.fail(format!("sampler slot {n} has no minimum level")));
|
||||
};
|
||||
let f = f32_ty(fb)?;
|
||||
let v = fb.convert(ConvOp::ConvertUToF, v, f)?;
|
||||
let scale = f32_const(fb, (1.0f32 / 64.0).to_bits())?;
|
||||
fb.binary(BinOp::FMul, v, scale)?
|
||||
}
|
||||
};
|
||||
let img = fb.image(si)?;
|
||||
let levels = fb.query(ImageQuery::Levels, img)?;
|
||||
@@ -2124,8 +1824,7 @@ pub(super) fn word_pixel(s: &Sampling) -> Option<Pixel> {
|
||||
|
||||
/// The texel a nearest, clamp-to-edge pixel sampler returns, exactly: `OpImageFetch` of the base
|
||||
/// level at `clamp(floor(coord) + offset, 0, size - 1)`, the layer clamped into the array as
|
||||
/// sampling clamps it. A depth texel is its first component. Under a sparse arm the fetch's status
|
||||
/// word too.
|
||||
/// sampling clamps it. A depth texel is its first component.
|
||||
fn pixel_fetch(
|
||||
cx: &mut EmitCx<'_>,
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
@@ -2133,7 +1832,6 @@ fn pixel_fetch(
|
||||
si: SValue,
|
||||
image: super::CombinedImage,
|
||||
offset: Option<&Offset>,
|
||||
arm: Option<(SValue, Binding)>,
|
||||
) -> BResult<(SValue, Option<SValue>)> {
|
||||
let img = fb.image(si)?;
|
||||
let zero = fb.u32_const(0)?;
|
||||
@@ -2220,43 +1918,7 @@ fn pixel_fetch(
|
||||
lod: Some(zero),
|
||||
..ImageOperands::default()
|
||||
};
|
||||
let fetch = move |fb: &mut FunctionBuilder<'_>, sparse: bool| -> BResult<SValue> {
|
||||
if sparse {
|
||||
fb.sparse_fetch(img, at, &ops)
|
||||
} else {
|
||||
fb.fetch(img, at, &ops)
|
||||
}
|
||||
};
|
||||
let tiled = match s.source {
|
||||
Source::Combined(key) => tile_map(cx, key.texture),
|
||||
_ => None,
|
||||
};
|
||||
let (x, word) = match (arm, tiled) {
|
||||
// A tile map: the plain fetch, and the residency of the fetched texel's tile at level 0.
|
||||
(Some((spec, _)), Some(map)) => {
|
||||
let x = fetch(fb, false)?;
|
||||
let zero = fb.u32_const(0)?;
|
||||
let zero = fb.module().const_value(zero)?;
|
||||
let tx = if lanes == 1 {
|
||||
texel
|
||||
} else {
|
||||
fb.composite_extract(texel, &[0])?
|
||||
};
|
||||
let ty = if lanes >= 2 {
|
||||
fb.composite_extract(texel, &[1])?
|
||||
} else {
|
||||
zero
|
||||
};
|
||||
let slice = layer.unwrap_or(zero);
|
||||
let word = tiled_word(cx, fb, spec, map, [tx, ty, zero], zero, slice)?;
|
||||
(x, Some(word))
|
||||
}
|
||||
(Some((spec, _)), None) => {
|
||||
let (x, word) = resident_access(cx, fb, spec, fetch)?;
|
||||
(x, Some(word))
|
||||
}
|
||||
(None, _) => (fetch(fb, false)?, None),
|
||||
};
|
||||
let (x, word) = (fb.fetch(img, at, &ops)?, None);
|
||||
let x = if s.depth {
|
||||
fb.composite_extract(x, &[0])?
|
||||
} else {
|
||||
@@ -2265,58 +1927,8 @@ fn pixel_fetch(
|
||||
Ok((x, word))
|
||||
}
|
||||
|
||||
/// `x`, the device's four-lane value of pixel fetch `s`, zero where its status word `word` (a
|
||||
/// `u32`) says its texel is unmapped under [`Unmapped::Named`]: Metal reads zero memory there,
|
||||
/// where a block of a sparse image that holds no mapped tile reads the device's value. The lanes
|
||||
/// the format lacks take their constants after the held texel's conversion ([`held_constants`]).
|
||||
fn unmapped_value(
|
||||
cx: &mut EmitCx<'_>,
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
s: &Sampling,
|
||||
x: SValue,
|
||||
word: Option<SValue>,
|
||||
) -> BResult<SValue> {
|
||||
if s.unmapped != Unmapped::Named {
|
||||
return Ok(x);
|
||||
}
|
||||
let Some(word) = word else {
|
||||
return Err(cx.fail("an access that names its texel without its residency"));
|
||||
};
|
||||
let zero = fb.u32_const(0)?;
|
||||
let zero = fb.module().const_value(zero)?;
|
||||
let kept = fb.binary(BinOp::IEqual, word, zero)?;
|
||||
let ty = fb.value_ty(x)?;
|
||||
let null = fb.module().constant(Constant::Null { ty })?;
|
||||
let null = fb.module().const_value(null)?;
|
||||
fb.select(kept, x, null)
|
||||
}
|
||||
|
||||
/// `held`, the held texel of access `s`, with the lanes Metal reads as constants set to them
|
||||
/// where the access takes them ([`Unmapped::Constants`] and [`Unmapped::Named`]): the slot's
|
||||
/// `ConstantLanes` specialization names them, a gather's by its component; a swizzled slot's
|
||||
/// sampling sets them after its swizzle instead ([`swizzled_value`]).
|
||||
pub(super) fn held_constants(
|
||||
cx: &mut EmitCx<'_>,
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
s: &Sampling,
|
||||
held: SValue,
|
||||
) -> BResult<SValue> {
|
||||
let Source::Combined(key) = s.source else {
|
||||
return Ok(held);
|
||||
};
|
||||
// A swizzled slot's sampling sets them after its swizzle ([`swizzled_value`]).
|
||||
if s.unmapped == Unmapped::Device || s.swizzle {
|
||||
return Ok(held);
|
||||
}
|
||||
let gathered = match s.op {
|
||||
SampleOp::Gather { component, .. } => Some(component),
|
||||
_ => None,
|
||||
};
|
||||
crate::lower::texture::constant_lanes(cx, fb, key.texture, held, gathered)
|
||||
}
|
||||
|
||||
/// The sampling result of image texel `texel`: the held texel ([`held_value`]) with the lanes
|
||||
/// Metal reads as constants set ([`held_constants`]), as `{T, i8}` where the result is one, with
|
||||
/// The sampling result of image texel `texel`: the held texel ([`held_value`]), as `{T, i8}`
|
||||
/// where the result is one, with
|
||||
/// status word `word` (the sparse arm's; 0 where none is given, Metal's for a resident access).
|
||||
pub(super) fn texel_value(
|
||||
cx: &mut EmitCx<'_>,
|
||||
@@ -2327,13 +1939,11 @@ pub(super) fn texel_value(
|
||||
word: Option<SValue>,
|
||||
) -> BResult<SValue> {
|
||||
let held = held_value(cx, fb, s, image, texel)?;
|
||||
let held = held_constants(cx, fb, s, held)?;
|
||||
with_word(cx, fb, &s.result, held, word)
|
||||
}
|
||||
|
||||
/// The held texel of sampling `s`'s image texel `texel`: an 8-bit sRGB texel's raw code decoded
|
||||
/// by the device's transfer, else the texel held as the result's type holds it; before the lanes
|
||||
/// Metal reads as constants are set ([`held_constants`]).
|
||||
/// by the device's transfer, else the texel held as the result's type holds it.
|
||||
pub(super) fn held_value(
|
||||
cx: &mut EmitCx<'_>,
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
@@ -2344,15 +1954,6 @@ pub(super) fn held_value(
|
||||
let Some(form) = s.texel else {
|
||||
return Err(cx.fail("a sample without a texel form"));
|
||||
};
|
||||
// An 8-bit sRGB texel's raw code, or the device's filter of the codes, decoded by the
|
||||
// device's transfer: a gather's lanes are one channel's, all alpha or all color.
|
||||
if s.raw {
|
||||
let color = match s.op {
|
||||
SampleOp::Gather { component, .. } => [component != 3; 4],
|
||||
_ => crate::lower::texture::SRGB_TEXEL,
|
||||
};
|
||||
return crate::lower::texture::srgb_texel(fb, form, texel, color);
|
||||
}
|
||||
held_texel(fb, image.texel, form, texel)
|
||||
}
|
||||
|
||||
|
||||
@@ -16,8 +16,8 @@
|
||||
//! `k / 256` ([`filtered`]), a `half` result the device's narrowing of the `f32` value. Metal sums
|
||||
//! the taps' codes exactly on the format's grid (each term of the 2D product weights truncated onto
|
||||
//! `2^-7` of a color lane's steps and `2^-4` of alpha's, the step rounded half up, divided by the
|
||||
//! grid exactly; every lane of 4,096 random 2D footprints per format and result type read so), which
|
||||
//! the device's arithmetic does not reproduce: the sample records
|
||||
//! grid exactly; every lane of 4,096 random 2D footprints per format and result type read so),
|
||||
//! which the device's arithmetic does not reproduce: the sample records
|
||||
//! `PrecisionNote::BicubicFilterArithmetic`, the emulated filters' note.
|
||||
//!
|
||||
//! **The two-plane formats** (an Apple M4 on macOS 27.0.1: every lane of 4,096
|
||||
@@ -26,15 +26,15 @@
|
||||
//! sample's `half` rounded with ties away from zero, as the decode rounds it) and filters as the
|
||||
//! other lanes do, where Metal filters it as an 8-bit unorm code on `1/(16 · 255)`.
|
||||
//!
|
||||
//! **A runtime sampler** reads its slot's `SamplerState` word: the sample is linear where the word
|
||||
//! states linear minification and magnification, else nearest; the taps follow the word's address
|
||||
//! modes, border color, and coordinates, and its level the word's mip filter (below). No check
|
||||
//! refuses a bound word that states anything else but a cubic filter (below): mixed filters sample
|
||||
//! as nearest, where Metal's sample is not measured. That is an open gap, which no consumer meets
|
||||
//! while the runtime makes no texture of these formats.
|
||||
//! **A runtime sampler** reads its pushed resource ID's word (`PushField::SlotGuestBase`): the
|
||||
//! sample is linear where the word states linear minification and magnification, else nearest; the
|
||||
//! taps follow the word's address modes, border color, and coordinates, and its level the word's
|
||||
//! mip filter (below). No check refuses a bound word that states anything else but a cubic filter
|
||||
//! (below): mixed filters sample as nearest, where Metal's sample is not measured. That is an open
|
||||
//! gap, which no consumer meets while the runtime makes no texture of these formats.
|
||||
//!
|
||||
//! **Levels and layers.** A sample reads the level Metal's rule reads (`level`, the rule measured on
|
||||
//! the other formats: the level rounded to `half`, clamped into the sampler's clamp and the
|
||||
//! **Levels and layers.** A sample reads the level Metal's rule reads (`level`, the rule measured
|
||||
//! on the other formats: the level rounded to `half`, clamped into the sampler's clamp and the
|
||||
//! texture's levels): level 0 without a mip filter, the level `L + 1` past half a level under a
|
||||
//! nearest one, and under a linear one levels `L` and `L + 1` of the level clamped in `f32`,
|
||||
//! blended by the device's `FMix` at its `f32` fraction where the second weighs anything, else
|
||||
@@ -50,13 +50,13 @@
|
||||
//! The level is the explicit level or a kernel's bias (level 0 without either); a fragment
|
||||
//! function's implicit level, shifted by its bias, and explicit gradients take Vulkan's level of
|
||||
//! detail, which the shader computes (`log2` of the longer of the coordinate's gradients in texels
|
||||
//! of the base level, on each plane axis), as Metal's level from derivatives is not measured: the sample records
|
||||
//! `PrecisionNote::DeviceSampleLevel` (through a runtime sampler where its word states a mip
|
||||
//! filter). A constexpr sampler's clamp bounds are its `half`s; a runtime sampler's are its `f32`s,
|
||||
//! which its word states for a nearest mip filter (the levels a nearest mip filter reads at them)
|
||||
//! and its slot's `SamplerMinLevel` specialization for a linear one (the minimum on the grid); a
|
||||
//! linear one's maximum is not read (the runtime sampler's open gap above). A linear mip filter is
|
||||
//! built for the `BGR10_XR` and `BGRA10_XR` forms, the padded forms and their twins
|
||||
//! of the base level, on each plane axis), as Metal's level from derivatives is not measured: the
|
||||
//! sample records `PrecisionNote::DeviceSampleLevel` (through a runtime sampler where its word
|
||||
//! states a mip filter). A constexpr sampler's clamp bounds are its `half`s; a runtime sampler's
|
||||
//! are its `f32`s, which its word states for a nearest mip filter (the levels a nearest mip filter
|
||||
//! reads at them) and its slot's `SamplerMinLevel` specialization for a linear one (the minimum on
|
||||
//! the grid); a linear one's maximum is not read (the runtime sampler's open gap above). A linear
|
||||
//! mip filter is built for the `BGR10_XR` and `BGRA10_XR` forms, the padded forms and their twins
|
||||
//! (`ExtendedRange::blends_levels`, below); a bfloat form's is its nearest one, as Metal's; a
|
||||
//! two-plane form's and `RGB10A2Unorm_sRGB`'s (not measured) are refused through a constexpr
|
||||
//! sampler and read the level a nearest mip filter reads through a runtime one (the same open
|
||||
@@ -84,11 +84,11 @@
|
||||
//! (`PrecisionNote::BicubicFilterArithmetic`). The level follows the 2D rules under a nearest
|
||||
//! mip filter. Under a linear one the sample blends its two levels' 3D filters as a 2D sample
|
||||
//! blends its levels' (the device's `FMix` at the clamped level's `f32` fraction), through a
|
||||
//! constexpr sampler and through a runtime one whose word states the filter. Metal's blend of a 3D texture's
|
||||
//! two levels fits no rule tried (the XR mip probe: the closest, 284 of 8,192 samples apart; the
|
||||
//! conformance crate's probe `extended_linear_mip_blends`: Metal's two levels' samples blended so
|
||||
//! lie within 0.033 of its 3D sample, and within 0.031 of its 2D one), so the blend records
|
||||
//! `PrecisionNote::BicubicFilterArithmetic`, as every level blend does. Another
|
||||
//! constexpr sampler and through a runtime one whose word states the filter. Metal's blend of a 3D
|
||||
//! texture's two levels fits no rule tried (the XR mip probe: the closest, 284 of 8,192 samples
|
||||
//! apart; the conformance crate's probe `extended_linear_mip_blends`: Metal's two levels' samples
|
||||
//! blended so lie within 0.033 of its 3D sample, and within 0.031 of its 2D one), so the blend
|
||||
//! records `PrecisionNote::BicubicFilterArithmetic`, as every level blend does. Another
|
||||
//! form's 3D sample (not measured) and a 3D bicubic sample are refused.
|
||||
//!
|
||||
//! **Bicubic samples** (an Apple M3 Max on macOS 26.7, the owned fixture `xr_bicubic`: random codes
|
||||
@@ -114,15 +114,8 @@
|
||||
//! refused.
|
||||
//!
|
||||
//! The bicubic paragraph above is Metal's reading on these formats, except inferences, each the
|
||||
//! other formats' bicubic reading (`bicubic`; for a runtime sampler) carried to
|
||||
//! these formats' decoded taps, which no reading of them covers:
|
||||
//! - a runtime `Cubic` sampler whose other filter is not `Cubic` (the readings' runtime sampler
|
||||
//! had both filters `Cubic`): the other formats' runtime sampler answers as both filters bicubic
|
||||
//! whatever its other filter;
|
||||
//! - a runtime sampler under another address mode than clamp to edge, a border color, or pixel
|
||||
//! coordinates (the readings' runtime sampler clamped to the edge at normalized coordinates):
|
||||
//! the constexpr samplers of those states were read on these formats, and the other formats'
|
||||
//! runtime sampler answers as the constexpr sampler of its state;
|
||||
//! other formats' bicubic reading (`bicubic`) carried to these formats' decoded taps, which no
|
||||
//! reading of them covers:
|
||||
//! - a `half` result under another address mode than clamp to edge (the readings' `half` results
|
||||
//! were all under clamp to edge, constexpr and runtime): rounded as under clamp to edge;
|
||||
//! - a sample at an explicit level, with a bias or with gradients, and a fragment function's
|
||||
@@ -183,7 +176,7 @@ use crate::spirv::builder::constructs::{ArmEnd, ArmFn, Merged};
|
||||
use crate::spirv::builder::{FunctionBuilder, ModuleBuilder};
|
||||
use crate::spirv::error::BResult;
|
||||
use crate::spirv::ids::{DemoteTy, FuncId, TypeId, Value as SValue};
|
||||
use crate::spirv::ir::{BinOp, ConstBits, Constant, ConvOp, GlslOp, ImageQuery};
|
||||
use crate::spirv::ir::{BinOp, Constant, ConvOp, GlslOp, ImageQuery};
|
||||
|
||||
use super::bicubic::{
|
||||
footprint_of_image, missing_routine, scalar, value, Addressing, Bicubic, Bits, Footprint, Tap,
|
||||
@@ -246,8 +239,9 @@ pub enum State {
|
||||
/// Pixel coordinates: the plane coordinate is already in texels.
|
||||
pixel: bool,
|
||||
},
|
||||
/// The runtime sampler in slot `sampler`: its `SamplerState` specialization's word states
|
||||
/// the filter, the address modes, the border color, and the coordinates.
|
||||
/// The runtime sampler in slot `sampler`: the word of its pushed resource ID
|
||||
/// (`PushField::SlotGuestBase`) states the filter, the address modes, the border color, and the
|
||||
/// coordinates.
|
||||
Slot { sampler: u32 },
|
||||
}
|
||||
|
||||
@@ -498,7 +492,7 @@ const BLEND_WORDS: u32 = 24;
|
||||
pub(super) struct Texture {
|
||||
pub img: SValue,
|
||||
pub image: CombinedImage,
|
||||
pub decode: Decode,
|
||||
pub form: ExtendedRange,
|
||||
pub flags: SValue,
|
||||
pub swizzle: Option<SValue>,
|
||||
/// The slot's `SpecKey::OffsetBaseAxes` tests, by which a texel offset is placed
|
||||
@@ -506,23 +500,6 @@ pub(super) struct Texture {
|
||||
pub parent: Option<crate::lower::texture::OffsetBase>,
|
||||
}
|
||||
|
||||
/// 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
|
||||
/// heap's decode routine of each result type (`texture::heap_raw::define`).
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) enum Decode {
|
||||
Form {
|
||||
form: ExtendedRange,
|
||||
},
|
||||
Heap {
|
||||
/// The form's index in `ExtendedRange::HEAP_READ` (a `u32`).
|
||||
form: SValue,
|
||||
/// Whether it is a bfloat form (a `bool`).
|
||||
bfloat: SValue,
|
||||
/// The routine of a `float` result, and of a `half` one where the access rounds to it.
|
||||
routines: (FuncId, Option<FuncId>),
|
||||
},
|
||||
}
|
||||
|
||||
/// Where a sample reads: its plane coordinate (two floats), a 2D array's layer (an integer), the
|
||||
/// constant texel offset Metal applies, per plane axis (a heap element's), or a routine's call's
|
||||
/// value of it (`passed`: an `int` or `ivecN` of `N` plane axes, `bicubic::At::offset`), the level
|
||||
@@ -699,7 +676,7 @@ fn sampled(
|
||||
arrayed: r.layer,
|
||||
texel: decl.texel,
|
||||
},
|
||||
decode: Decode::Form { form: r.form },
|
||||
form: r.form,
|
||||
flags: value(fb, flags)?,
|
||||
swizzle,
|
||||
parent,
|
||||
@@ -1117,7 +1094,7 @@ fn block_taps(
|
||||
base: TapBase::Quantized,
|
||||
level: at.level,
|
||||
};
|
||||
let fp = footprint_of(fb, t, at, tex, Bits::Value(tex.flags), &taps)?;
|
||||
let fp = footprint_of(fb, t, at, tex, Bits(tex.flags), &taps)?;
|
||||
let [(kx, xs), (ky, ys), (kz, zs)] = &fp.axes[..] else {
|
||||
return Err(cx.fail("an extended-range 3D linear sample without three plane axes"));
|
||||
};
|
||||
@@ -1128,7 +1105,7 @@ fn block_taps(
|
||||
for z in [z0, z1] {
|
||||
for y in [y0, y1] {
|
||||
for x in [x0, x1] {
|
||||
out.push(texel(cx, fb, &fp, tex, &[x, y, z], false)?);
|
||||
out.push(texel(fb, &fp, tex, &[x, y, z], false)?);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1161,7 +1138,7 @@ fn quad_taps(
|
||||
base: TapBase::Quantized,
|
||||
level: at.level,
|
||||
};
|
||||
let fp = footprint_of(fb, t, at, tex, Bits::Value(tex.flags), &taps)?;
|
||||
let fp = footprint_of(fb, t, at, tex, Bits(tex.flags), &taps)?;
|
||||
let [(kx, xs), (ky, ys)] = &fp.axes[..] else {
|
||||
return Err(cx.fail("an extended-range linear sample without two plane axes"));
|
||||
};
|
||||
@@ -1171,7 +1148,7 @@ fn quad_taps(
|
||||
let (kx, ky) = (*kx, *ky);
|
||||
let mut out = Vec::with_capacity(6);
|
||||
for site in [[x0, y0], [x1, y0], [x0, y1], [x1, y1]] {
|
||||
out.push(texel(cx, fb, &fp, tex, &site, false)?);
|
||||
out.push(texel(fb, &fp, tex, &site, false)?);
|
||||
}
|
||||
out.push(super::linear::merged(fb, t, kx, [x0, x1])?);
|
||||
out.push(super::linear::merged(fb, t, ky, [y0, y1])?);
|
||||
@@ -1204,7 +1181,7 @@ fn bicubic(
|
||||
) -> BResult<SValue> {
|
||||
let span = cubic.span();
|
||||
let taps = cubic.taps(span);
|
||||
let bits = Bits::Value(tex.flags);
|
||||
let bits = Bits(tex.flags);
|
||||
let fp = footprint_of(fb, t, at, tex, bits, &taps)?;
|
||||
let zero = fb.u32_const(0)?;
|
||||
let zero = value(fb, zero)?;
|
||||
@@ -1263,7 +1240,7 @@ pub(super) fn nearest(
|
||||
base: TapBase::Floor,
|
||||
level: at.level,
|
||||
};
|
||||
let fp = footprint_of(fb, t, at, tex, Bits::Value(tex.flags), &taps)?;
|
||||
let fp = footprint_of(fb, t, at, tex, Bits(tex.flags), &taps)?;
|
||||
// Each plane axis's one tap (a 3D texture's three).
|
||||
let mut site = Vec::with_capacity(fp.axes.len());
|
||||
for (_, taps) in &fp.axes {
|
||||
@@ -1274,23 +1251,13 @@ pub(super) fn nearest(
|
||||
}
|
||||
// A bfloat form's `half` result is its `float` result's toward zero, border texels included,
|
||||
// where its reads and gathers round to nearest even.
|
||||
match (at.half, tex.decode) {
|
||||
(false, _) => texel(cx, fb, &fp, tex, &site, false),
|
||||
(true, Decode::Form { form, .. }) if form.bfloat() => {
|
||||
let v = texel(cx, fb, &fp, tex, &site, false)?;
|
||||
match at.half {
|
||||
false => texel(fb, &fp, tex, &site, false),
|
||||
true if tex.form.bfloat() => {
|
||||
let v = texel(fb, &fp, tex, &site, false)?;
|
||||
crate::lower::arith::extended_range::bfloat_sample_half(fb, v)
|
||||
}
|
||||
(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)?;
|
||||
let v = decoded(cx, fb, tex, raw, false)?;
|
||||
let v = fp.border(fb, v, inside)?;
|
||||
let toward = crate::lower::arith::extended_range::bfloat_sample_half(fb, v)?;
|
||||
let rounded = decoded(cx, fb, tex, raw, true)?;
|
||||
let rounded = fp.border(fb, rounded, inside)?;
|
||||
fb.select(bfloat, toward, rounded)
|
||||
}
|
||||
true => texel(fb, &fp, tex, &site, true),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1315,7 +1282,7 @@ pub(super) fn gathered(
|
||||
base: TapBase::Quantized,
|
||||
level: at.level,
|
||||
};
|
||||
let fp = footprint_of(fb, t, at, tex, Bits::Value(tex.flags), &taps)?;
|
||||
let fp = footprint_of(fb, t, at, tex, Bits(tex.flags), &taps)?;
|
||||
let [(_, xs), (_, ys)] = &fp.axes[..] else {
|
||||
return Err(cx.fail("an extended-range gather without two plane axes"));
|
||||
};
|
||||
@@ -1324,7 +1291,7 @@ pub(super) fn gathered(
|
||||
};
|
||||
let mut lanes = Vec::with_capacity(4);
|
||||
for site in [[x0, y1], [x1, y1], [x1, y0], [x0, y0]] {
|
||||
let v = texel(cx, fb, &fp, tex, &site, at.half)?;
|
||||
let v = texel(fb, &fp, tex, &site, at.half)?;
|
||||
let v = swizzled(fb, tex, v)?;
|
||||
lanes.push(fb.composite_extract(v, &[component])?);
|
||||
}
|
||||
@@ -1335,7 +1302,6 @@ pub(super) fn gathered(
|
||||
/// (`extended_range::decode`, rounded to `half` when `half`), or the border texel where the tap
|
||||
/// lies outside a border axis.
|
||||
pub(super) fn texel(
|
||||
cx: &mut EmitCx<'_>,
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
fp: &Footprint,
|
||||
tex: &Texture,
|
||||
@@ -1343,7 +1309,7 @@ pub(super) fn texel(
|
||||
half: bool,
|
||||
) -> BResult<SValue> {
|
||||
let (raw, inside) = tap(fb, fp, tex, site)?;
|
||||
let v = decoded(cx, fb, tex, raw, half)?;
|
||||
let v = crate::lower::arith::extended_range::decode(fb, tex.form, raw, half)?;
|
||||
fp.border(fb, v, inside)
|
||||
}
|
||||
|
||||
@@ -1359,35 +1325,6 @@ fn tap(
|
||||
Ok((fp.read(fb, tex.img, at)?, inside))
|
||||
}
|
||||
|
||||
/// Raw texel `raw` decoded by `tex`'s form (`extended_range::decode`, rounded to `half` when
|
||||
/// `half`), or by the form its heap handle names, through the heap's routine.
|
||||
fn decoded(
|
||||
cx: &mut EmitCx<'_>,
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
tex: &Texture,
|
||||
raw: SValue,
|
||||
half: bool,
|
||||
) -> BResult<SValue> {
|
||||
match tex.decode {
|
||||
Decode::Form { form } => crate::lower::arith::extended_range::decode(fb, form, raw, half),
|
||||
Decode::Heap { form, routines, .. } => {
|
||||
let routine = match (half, routines) {
|
||||
(false, (f, _)) => f,
|
||||
(true, (_, Some(h))) => h,
|
||||
(true, (_, None)) => return Err(cx.fail("a raw heap sample without its routine")),
|
||||
};
|
||||
let bool_ = fb.module().ty(crate::spirv::ir::Type::Bool)?;
|
||||
let inside = fb.module().constant(Constant::Scalar {
|
||||
ty: bool_,
|
||||
bits: ConstBits(1),
|
||||
})?;
|
||||
let inside = fb.module().const_value(inside)?;
|
||||
fb.call(routine, &[raw, form, inside])?
|
||||
.ok_or_else(missing_routine)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The bits of `form` the exact routine and the border texel read: `EXACT` and `EXTENDED` (a
|
||||
/// padded format's `UNORM` and `RGB10A2Unorm`'s packed field instead), `SRGB` for an `_sRGB` twin,
|
||||
/// its channels (`BGR10_XR` has no alpha), and Metal's border texels through them
|
||||
@@ -1464,7 +1401,7 @@ mod tests {
|
||||
// `RGB10A2Unorm_sRGB` has four channels, and its own packed field.
|
||||
assert_eq!(border(ExtendedRange::Rgb10A2Srgb), four);
|
||||
let field = flags(ExtendedRange::Rgb10A2Srgb)
|
||||
& crate::metal::texel_format::TexelFormat::PACKED_MASK;
|
||||
& 0xF << crate::metal::texel_format::TexelFormat::PACKED;
|
||||
assert_eq!(
|
||||
field,
|
||||
crate::metal::texel_format::PackedTexels::Rgb10A2Srgb
|
||||
|
||||
@@ -28,24 +28,10 @@
|
||||
//! `shaderResourceResidency`), whose slot's tile map answers it; a device with it answers a
|
||||
//! sample's or gather's residency itself (its `OpImageSparse*` word,
|
||||
//! `PrecisionNote::SparseResidency`), and selection asks for no rule there.
|
||||
//!
|
||||
//! [`word`] emits the status word of such an access: the residency of each counted texel at
|
||||
//! level 0, through the slot's tile map, under the slot's `SparseTexture` specialization, and the
|
||||
//! residency of each texel; the sample itself is the device's plain sample.
|
||||
|
||||
use crate::air::abi::SamplerState;
|
||||
use crate::air::abi::{AddressMode, Coordinates, Filter, MipFilter};
|
||||
use crate::air::intrinsics::{ImageDim, ImageShape};
|
||||
use crate::lower::emit::EmitCx;
|
||||
use crate::lower::texture::TileLevel;
|
||||
use crate::memory::views::View;
|
||||
use crate::spirv::builder::constructs::{ArmEnd, ArmFn, Merged};
|
||||
use crate::spirv::builder::FunctionBuilder;
|
||||
use crate::spirv::error::BResult;
|
||||
use crate::spirv::ids::Value as SValue;
|
||||
use crate::spirv::ir::{
|
||||
BinOp, ConstBits, Constant, ConvOp, GlslOp, ImageQuery, Type as SType, UnOp,
|
||||
};
|
||||
|
||||
use super::{Lod, SampleOp};
|
||||
|
||||
@@ -71,10 +57,6 @@ pub struct Footprint {
|
||||
pub border: [bool; 3],
|
||||
}
|
||||
|
||||
/// The largest texel distance the position keeps (`2^22`): any position past it is outside every
|
||||
/// texture, so under clamp addressing it reads the same texels as at the limit.
|
||||
const LIMIT: f32 = 4_194_304.0;
|
||||
|
||||
/// Metal's footprint of `op` on a texture of `shape` through the constexpr sampler `state`, where
|
||||
/// the rule decides it; `None` elsewhere. `integer`: the texture's texels are integers (a sample of
|
||||
/// one is not filtered).
|
||||
@@ -141,308 +123,3 @@ pub fn of(
|
||||
};
|
||||
Some(Footprint { kind, axes, border })
|
||||
}
|
||||
|
||||
/// Whether an axis's `i0 + 1` is in the footprint.
|
||||
#[derive(Clone, Copy)]
|
||||
enum Second {
|
||||
/// Never (a nearest filter).
|
||||
No,
|
||||
/// Always (a gather).
|
||||
Yes,
|
||||
/// Where this `bool` holds (a linear filter: its quantized weight is not 0).
|
||||
If(SValue),
|
||||
}
|
||||
|
||||
/// One axis of the footprint: its texel `i0`, whether `i0 + 1` counts, and the level's size.
|
||||
struct Axis {
|
||||
i0: SValue,
|
||||
second: Second,
|
||||
size: SValue,
|
||||
}
|
||||
|
||||
fn f32_const(fb: &mut FunctionBuilder<'_>, x: f32) -> BResult<SValue> {
|
||||
let f = fb.module().ty(SType::Float { width: 32 })?;
|
||||
let c = fb.module().constant(Constant::Scalar {
|
||||
ty: f,
|
||||
bits: ConstBits(u64::from(x.to_bits())),
|
||||
})?;
|
||||
fb.module().const_value(c)
|
||||
}
|
||||
|
||||
fn i32_const(fb: &mut FunctionBuilder<'_>, x: i32) -> BResult<SValue> {
|
||||
let i = fb.module().ty(SType::Int {
|
||||
width: 32,
|
||||
signed: true,
|
||||
})?;
|
||||
let c = fb.module().constant(Constant::Scalar {
|
||||
ty: i,
|
||||
bits: ConstBits(u64::from(x as u32)),
|
||||
})?;
|
||||
fb.module().const_value(c)
|
||||
}
|
||||
|
||||
fn u32_const(fb: &mut FunctionBuilder<'_>, x: u32) -> BResult<SValue> {
|
||||
let c = fb.u32_const(x)?;
|
||||
fb.module().const_value(c)
|
||||
}
|
||||
|
||||
/// Component `i` of `v`, or `v` itself for a one-lane value.
|
||||
fn lane(fb: &mut FunctionBuilder<'_>, v: SValue, lanes: u8, i: u32) -> BResult<SValue> {
|
||||
if lanes == 1 {
|
||||
Ok(v)
|
||||
} else {
|
||||
fb.composite_extract(v, &[i])
|
||||
}
|
||||
}
|
||||
|
||||
/// One axis's texels from normalized coordinate `u` and the level's size `size` (a `u32`).
|
||||
fn axis(fb: &mut FunctionBuilder<'_>, kind: Kind, u: SValue, size: SValue) -> BResult<Axis> {
|
||||
let i = fb.module().ty(SType::Int {
|
||||
width: 32,
|
||||
signed: true,
|
||||
})?;
|
||||
// Metal's position on a clamping axis: the product rounded with ties away from zero.
|
||||
let (x, _) = super::position::position(fb, u, size, super::bicubic::TapAddress::Edge)?;
|
||||
let (i0, second) = match kind {
|
||||
Kind::Nearest => {
|
||||
let lo = f32_const(fb, -LIMIT)?;
|
||||
let hi = f32_const(fb, LIMIT)?;
|
||||
let fl = fb.glsl(GlslOp::Floor, &[x])?;
|
||||
let fl = fb.glsl(GlslOp::FClamp, &[fl, lo, hi])?;
|
||||
(fb.convert(ConvOp::ConvertFToS, fl, i)?, Second::No)
|
||||
}
|
||||
Kind::Linear | Kind::Gather => {
|
||||
// q = floor(256·X + 1/2) - 128, exactly: 256·X is exact, and its fraction decides
|
||||
// the rounding (ties up).
|
||||
let k = f32_const(fb, 256.0)?;
|
||||
let y = fb.binary_no_contraction(BinOp::FMul, x, k)?;
|
||||
let lo = f32_const(fb, -LIMIT * 256.0)?;
|
||||
let hi = f32_const(fb, LIMIT * 256.0)?;
|
||||
let y = fb.glsl(GlslOp::FClamp, &[y, lo, hi])?;
|
||||
let fy = fb.glsl(GlslOp::Floor, &[y])?;
|
||||
let r = fb.binary_no_contraction(BinOp::FSub, y, fy)?;
|
||||
let half = f32_const(fb, 0.5)?;
|
||||
let up = fb.binary(BinOp::FOrdGreaterThanEqual, r, half)?;
|
||||
let q = fb.convert(ConvOp::ConvertFToS, fy, i)?;
|
||||
let one = i32_const(fb, 1)?;
|
||||
let zero = i32_const(fb, 0)?;
|
||||
let carry = fb.select(up, one, zero)?;
|
||||
let q = fb.binary(BinOp::IAdd, q, carry)?;
|
||||
let k128 = i32_const(fb, 128)?;
|
||||
let q = fb.binary(BinOp::ISub, q, k128)?;
|
||||
let eight = i32_const(fb, 8)?;
|
||||
let i0 = fb.binary(BinOp::ShiftRightArithmetic, q, eight)?;
|
||||
let second = match kind {
|
||||
Kind::Gather => Second::Yes,
|
||||
_ => {
|
||||
let mask = i32_const(fb, 255)?;
|
||||
let frac = fb.binary(BinOp::BitwiseAnd, q, mask)?;
|
||||
Second::If(fb.binary(BinOp::INotEqual, frac, zero)?)
|
||||
}
|
||||
};
|
||||
(i0, second)
|
||||
}
|
||||
};
|
||||
Ok(Axis { i0, second, size })
|
||||
}
|
||||
|
||||
/// Texel `i` (an `i32`) of an axis of size `size`: clamped into the level (a `u32`, the texel
|
||||
/// read), and whether it is inside the level (`None` where the axis clamps to its edge, every
|
||||
/// texel counted). A negative texel is outside: as a `u32` it is at least `2^31`, past any size.
|
||||
fn texel(
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
i: SValue,
|
||||
size: SValue,
|
||||
border: bool,
|
||||
) -> BResult<(SValue, Option<SValue>)> {
|
||||
let u = fb.module().ty(SType::Int {
|
||||
width: 32,
|
||||
signed: false,
|
||||
})?;
|
||||
let zero = i32_const(fb, 0)?;
|
||||
let one = u32_const(fb, 1)?;
|
||||
let last = fb.binary(BinOp::ISub, size, one)?;
|
||||
let low = fb.glsl(GlslOp::SMax, &[i, zero])?;
|
||||
let low = fb.convert(ConvOp::Bitcast, low, u)?;
|
||||
let clamped = fb.glsl(GlslOp::UMin, &[low, last])?;
|
||||
if !border {
|
||||
return Ok((clamped, None));
|
||||
}
|
||||
let raw = fb.convert(ConvOp::Bitcast, i, u)?;
|
||||
Ok((clamped, Some(fb.binary(BinOp::ULessThan, raw, size)?)))
|
||||
}
|
||||
|
||||
/// Where a sample or gather reads: the combined binding, the normalized plane coordinate `coord`
|
||||
/// (`lanes` floats), and the array layer (a `u32`, clamped into the array as sampling clamps it).
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Site {
|
||||
pub binding: super::Binding,
|
||||
pub coord: SValue,
|
||||
pub lanes: u8,
|
||||
pub layer: Option<SValue>,
|
||||
}
|
||||
|
||||
/// The status word of a sample or gather with footprint `fp` at `site`, on a slot whose
|
||||
/// `SparseTexture` specialization is `spec` and whose tile map is `map`: [`counted`]'s where the
|
||||
/// bound texture is sparse, and 0 where it is not.
|
||||
pub fn word(
|
||||
cx: &mut EmitCx<'_>,
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
fp: Footprint,
|
||||
spec: SValue,
|
||||
map: View,
|
||||
site: Site,
|
||||
) -> BResult<SValue> {
|
||||
let sparse: ArmFn<'_, ()> = Box::new(move |fb, _| {
|
||||
let word = counted(fb, fp, map, site)?;
|
||||
Ok(ArmEnd::FallThrough(vec![word]))
|
||||
});
|
||||
let plain: ArmFn<'_, ()> = Box::new(move |fb, _| {
|
||||
let word = u32_const(fb, 0)?;
|
||||
Ok(ArmEnd::FallThrough(vec![word]))
|
||||
});
|
||||
let Merged(merged) = fb.if_(&mut (), spec, sparse, Some(plain))?;
|
||||
match merged[..] {
|
||||
[word] => Ok(word),
|
||||
_ => Err(cx.fail("a footprint arm without its word")),
|
||||
}
|
||||
}
|
||||
|
||||
/// The status word (a `u32`) of a sample or gather of a sparse texture with footprint `fp` at
|
||||
/// `site`: 1 where a texel Metal counts is not resident at level 0, read through tile map `map`,
|
||||
/// else 0. The footprint's texels are each a combination of each axis's texels: bit `a` of a
|
||||
/// combination picks axis `a`'s `i0 + 1` over its `i0`; a nearest filter reads combination 0
|
||||
/// alone, a linear filter and a gather every one.
|
||||
pub fn counted(
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
fp: Footprint,
|
||||
map: View,
|
||||
site: Site,
|
||||
) -> BResult<SValue> {
|
||||
let Site {
|
||||
binding,
|
||||
coord,
|
||||
lanes,
|
||||
layer,
|
||||
} = site;
|
||||
let img = binding.image(fb)?;
|
||||
let zero = u32_const(fb, 0)?;
|
||||
let size = fb.query(ImageQuery::SizeLod(zero), img)?;
|
||||
let size_lanes = fp.axes + u8::from(layer.is_some());
|
||||
let mut axes = Vec::with_capacity(usize::from(fp.axes));
|
||||
for a in 0..u32::from(fp.axes) {
|
||||
let u = lane(fb, coord, lanes, a)?;
|
||||
let n = lane(fb, size, size_lanes, a)?;
|
||||
axes.push(axis(fb, fp.kind, u, n)?);
|
||||
}
|
||||
// The layer, clamped into the array.
|
||||
let slice = match layer {
|
||||
Some(l) => {
|
||||
let layers = fb.composite_extract(size, &[u32::from(fp.axes)])?;
|
||||
let one = u32_const(fb, 1)?;
|
||||
let last = fb.binary(BinOp::ISub, layers, one)?;
|
||||
Some(fb.glsl(GlslOp::UMin, &[l, last])?)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
// Each axis's texels, once: `i0`, and `i0 + 1` where the footprint has it, each clamped into
|
||||
// the level, with whether it counts (its weight is not 0, and it is not the border).
|
||||
let tiles = TileLevel::new(fb, map, zero, slice.unwrap_or(zero))?;
|
||||
let mut picks: Vec<Vec<Pick>> = Vec::with_capacity(axes.len());
|
||||
for (a, ax) in axes.iter().enumerate() {
|
||||
let border = fp.border.get(a).copied().unwrap_or(false);
|
||||
let mut both = Vec::with_capacity(2);
|
||||
let (t, inside) = texel(fb, ax.i0, ax.size, border)?;
|
||||
both.push(pick(fb, &tiles, a, t, inside)?);
|
||||
if !matches!(ax.second, Second::No) {
|
||||
let one = i32_const(fb, 1)?;
|
||||
let i = fb.binary(BinOp::IAdd, ax.i0, one)?;
|
||||
let (t, inside) = texel(fb, i, ax.size, border)?;
|
||||
let counts = match (ax.second, inside) {
|
||||
(Second::If(weighed), Some(inside)) => {
|
||||
Some(fb.binary(BinOp::LogicalAnd, weighed, inside)?)
|
||||
}
|
||||
(Second::If(weighed), None) => Some(weighed),
|
||||
(_, inside) => inside,
|
||||
};
|
||||
both.push(pick(fb, &tiles, a, t, counts)?);
|
||||
}
|
||||
picks.push(both);
|
||||
}
|
||||
// A 2D texture's tiles are in its one z tile.
|
||||
let tz = match picks.len() < 3 {
|
||||
true => Some(tiles.tile(fb, 2, zero)?),
|
||||
false => None,
|
||||
};
|
||||
// Every combination of each axis's texels (bit `a` of `combo` picks axis `a`'s second); a
|
||||
// combination that picks a second an axis lacks is not in the footprint.
|
||||
let mut all: Option<SValue> = None;
|
||||
for combo in 0..(1usize << picks.len()) {
|
||||
let chosen: Option<Vec<Pick>> = picks
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(a, p)| p.get(combo >> a & 1).copied())
|
||||
.collect();
|
||||
let Some(chosen) = chosen else {
|
||||
continue;
|
||||
};
|
||||
let mut counts: Option<SValue> = None;
|
||||
for p in &chosen {
|
||||
if let Some(c) = p.counts {
|
||||
counts = Some(and(fb, counts, c)?);
|
||||
}
|
||||
}
|
||||
let mut at = [tz.unwrap_or(zero); 3];
|
||||
for (slot, p) in at.iter_mut().zip(&chosen) {
|
||||
*slot = p.tile;
|
||||
}
|
||||
let resident = tiles.mapped(fb, at)?;
|
||||
// A texel that does not count is resident as far as the word goes.
|
||||
let ok = match counts {
|
||||
Some(c) => {
|
||||
let not = fb.unary(UnOp::LogicalNot, c)?;
|
||||
fb.binary(BinOp::LogicalOr, not, resident)?
|
||||
}
|
||||
None => resident,
|
||||
};
|
||||
all = Some(and(fb, all, ok)?);
|
||||
}
|
||||
// Combination 0 (every axis's `i0`) is always in the footprint, so `all` is set.
|
||||
let one = u32_const(fb, 1)?;
|
||||
match all {
|
||||
Some(all) => fb.select(all, zero, one),
|
||||
None => Ok(zero),
|
||||
}
|
||||
}
|
||||
|
||||
/// One texel of an axis of the footprint: its tile in the tile map, and whether it counts
|
||||
/// (`None`: always).
|
||||
#[derive(Clone, Copy)]
|
||||
struct Pick {
|
||||
tile: SValue,
|
||||
counts: Option<SValue>,
|
||||
}
|
||||
|
||||
fn pick(
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
tiles: &TileLevel,
|
||||
axis: usize,
|
||||
texel: SValue,
|
||||
counts: Option<SValue>,
|
||||
) -> BResult<Pick> {
|
||||
Ok(Pick {
|
||||
tile: tiles.tile(fb, axis, texel)?,
|
||||
counts,
|
||||
})
|
||||
}
|
||||
|
||||
/// `a ∧ b`, or `b` alone.
|
||||
fn and(fb: &mut FunctionBuilder<'_>, a: Option<SValue>, b: SValue) -> BResult<SValue> {
|
||||
match a {
|
||||
Some(a) => fb.binary(BinOp::LogicalAnd, a, b),
|
||||
None => Ok(b),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -1,641 +0,0 @@
|
||||
//! The footprint word, run on the interpreter. Each kernel reads a normalized coordinate per
|
||||
//! invocation and writes [`counted`]'s word for a sparse image whose texels are unmapped where a
|
||||
//! case left them so. Against Metal's own answers (apple-m3-max-macos26.7: cases 39503d65,
|
||||
//! efe06aaf, 363e39a2, 95ca7dc5, 29f15128, 760fce8c, and fd292944 on 2D textures, 203caac1 on a 3D
|
||||
//! one), and, for a 3D and a 2D-array texture, against the rule applied per axis. Each runs through
|
||||
//! both of a slot's arms: the image's sparse fetches, and a tile map of the same texels over an
|
||||
//! image resident everywhere.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use crate::spv::ImageFormat;
|
||||
|
||||
use super::{counted, Footprint, Kind, Site};
|
||||
use crate::memory::views::View;
|
||||
use crate::pipeline::sym::{CombinedSampler, ResourceKind, ResourceSlot, SamplerRef, Stage};
|
||||
use crate::pipeline::tile_map;
|
||||
use crate::spirv::builder::{FunctionBuilder, ModuleBuilder};
|
||||
use crate::spirv::error::BResult;
|
||||
use crate::spirv::ids::{GlobalId, TypeId, Value};
|
||||
use crate::spirv::interp::{self, Buffer, Config, Image, Resources};
|
||||
use crate::spirv::ir::{
|
||||
natural_layout, ConstBits, Constant, ConvOp, Dim, ExecMode, ExecModel, ImageType, ImageUsage,
|
||||
IoDir, LayoutRule, MemAccess, StorageClass, Type, TypedModule,
|
||||
};
|
||||
|
||||
fn slot(kind: ResourceKind, index: u32) -> ResourceSlot {
|
||||
ResourceSlot {
|
||||
stage: Stage::Kernel,
|
||||
kind,
|
||||
index,
|
||||
}
|
||||
}
|
||||
|
||||
/// Texture 0 through sampler slot 0 (the kernel's sampler state is not used: it only fetches).
|
||||
fn combined() -> ResourceSlot {
|
||||
let sampler = CombinedSampler::new(SamplerRef::Slot(0), false, false);
|
||||
slot(ResourceKind::CombinedTextureSampler(sampler), 0)
|
||||
}
|
||||
|
||||
fn storage_buffer(
|
||||
b: &mut ModuleBuilder,
|
||||
index: u32,
|
||||
elem: TypeId,
|
||||
stride: u32,
|
||||
) -> BResult<GlobalId> {
|
||||
let rta = b.ty(Type::RuntimeArray {
|
||||
elem,
|
||||
stride: Some(stride),
|
||||
})?;
|
||||
let layout = natural_layout(b.types(), LayoutRule::Std430, true, &[rta])?;
|
||||
let block = b.ty(Type::Struct {
|
||||
members: [rta].into(),
|
||||
layout: Some(layout),
|
||||
})?;
|
||||
b.resource(
|
||||
slot(ResourceKind::Buffer, index),
|
||||
StorageClass::StorageBuffer,
|
||||
block,
|
||||
)
|
||||
}
|
||||
|
||||
fn element(f: &mut FunctionBuilder<'_>, g: GlobalId, i: Value) -> BResult<Value> {
|
||||
let u32_ = f.module().ty(Type::Int {
|
||||
width: 32,
|
||||
signed: false,
|
||||
})?;
|
||||
let c = f.module().constant(Constant::Scalar {
|
||||
ty: u32_,
|
||||
bits: ConstBits(0),
|
||||
})?;
|
||||
let zero = f.module().const_value(c)?;
|
||||
let base = f.module().global_value(g)?;
|
||||
f.access_chain(base, &[zero, i])
|
||||
}
|
||||
|
||||
/// Where a kernel reads a texel's residency: a tile map in buffer 2 with tiles of the given texels
|
||||
/// (x, y, z), made from the image's unmapped texels, which must be whole tiles; the image itself is
|
||||
/// then resident everywhere, so only the map can answer.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct Arm([u32; 3]);
|
||||
|
||||
/// A kernel whose invocation `i` reads `vec4` probe `i` of buffer 0 (the coordinate in its first
|
||||
/// `axes` lanes; the layer, as a float, in lane 3 of an array) and writes the word of `fp` at it,
|
||||
/// through buffer 2's tile map, to `uint` element `i` of buffer 1.
|
||||
fn kernel(fp: Footprint, dim: Dim, arrayed: bool) -> BResult<TypedModule> {
|
||||
let mut b = ModuleBuilder::new();
|
||||
let f32_ = b.ty(Type::Float { width: 32 })?;
|
||||
let u32_ = b.ty(Type::Int {
|
||||
width: 32,
|
||||
signed: false,
|
||||
})?;
|
||||
let vec4 = b.ty(Type::Vector { elem: f32_, len: 4 })?;
|
||||
let uvec3 = b.ty(Type::Vector { elem: u32_, len: 3 })?;
|
||||
let image = b.ty(Type::Image(ImageType {
|
||||
sampled_type: f32_,
|
||||
dim,
|
||||
depth: false,
|
||||
arrayed,
|
||||
multisampled: false,
|
||||
usage: ImageUsage::Sampled,
|
||||
format: ImageFormat::Unknown,
|
||||
}))?;
|
||||
let sampled = b.ty(Type::SampledImage { image })?;
|
||||
let texture = b.resource(combined(), StorageClass::UniformConstant, sampled)?;
|
||||
let probes = storage_buffer(&mut b, 0, vec4, 16)?;
|
||||
let words = storage_buffer(&mut b, 1, u32_, 4)?;
|
||||
let map = storage_buffer(&mut b, 2, u32_, 4)?;
|
||||
let map = View {
|
||||
global: map,
|
||||
u32_ty: u32_,
|
||||
};
|
||||
let id = b.builtin(crate::spv::BuiltIn::GlobalInvocationId, IoDir::Input, uvec3)?;
|
||||
let void = b.ty(Type::Void)?;
|
||||
let mut f = b.function(void)?;
|
||||
let gid = f.module().global_value(id)?;
|
||||
let gid = f.load(gid, MemAccess::default())?;
|
||||
let i = f.composite_extract(gid, &[0])?;
|
||||
let at = element(&mut f, probes, i)?;
|
||||
let p = f.load(at, MemAccess::default())?;
|
||||
let lanes = fp.axes;
|
||||
let pick: Vec<u32> = (0..u32::from(lanes)).collect();
|
||||
let coord = f.vector_shuffle(p, p, &pick)?;
|
||||
let layer = if arrayed {
|
||||
let l = f.composite_extract(p, &[3])?;
|
||||
Some(f.convert(ConvOp::ConvertFToU, l, u32_)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let site = Site {
|
||||
binding: crate::lower::sampler::Binding::Combined(texture),
|
||||
coord,
|
||||
lanes,
|
||||
layer,
|
||||
};
|
||||
let word = counted(&mut f, fp, map, site)?;
|
||||
let out = element(&mut f, words, i)?;
|
||||
f.store(out, word, MemAccess::default())?;
|
||||
f.ret(None)?;
|
||||
let main = f.finish()?;
|
||||
b.entry(
|
||||
ExecModel::GLCompute,
|
||||
main,
|
||||
vec![ExecMode::LocalSize { x: 1, y: 1, z: 1 }],
|
||||
)?;
|
||||
b.finalize()
|
||||
}
|
||||
|
||||
/// A sparse image of `extent` and `layers` whose texel `(x, y, z)` of layer `l` is unmapped where
|
||||
/// `unmapped(x, y, z, l)`.
|
||||
fn image(
|
||||
dim: Dim,
|
||||
extent: [u32; 3],
|
||||
layers: u32,
|
||||
unmapped: impl Fn(u32, u32, u32, u32) -> bool,
|
||||
) -> Image {
|
||||
let mut img = Image::new(combined(), extent, layers, 1, 1);
|
||||
let [w, h, d] = extent;
|
||||
let mut set = BTreeSet::new();
|
||||
let mut i = 0usize;
|
||||
for l in 0..layers {
|
||||
for z in 0..d {
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
if unmapped(x, y, z, l) {
|
||||
set.insert(i);
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(i, img.texels.len(), "{dim:?} texel count");
|
||||
img.unmapped = set;
|
||||
img
|
||||
}
|
||||
|
||||
/// The tile map of `img`'s level 0 with tiles of `tile` texels: a tile is mapped where none of its
|
||||
/// texels is unmapped, and a tile only some of whose texels are unmapped is refused.
|
||||
fn tile_map(img: &Image, tile: [u32; 3]) -> Vec<u8> {
|
||||
let [w, h, d] = img.extent;
|
||||
let [tw, th, td] = tile;
|
||||
tile_map::one_level_map(img.extent, img.layers, tile, |l, [tx, ty, tz]| {
|
||||
let (mut texels, mut unmapped) = (0, 0);
|
||||
for z in tz * td..((tz + 1) * td).min(d) {
|
||||
for y in ty * th..((ty + 1) * th).min(h) {
|
||||
for x in tx * tw..((tx + 1) * tw).min(w) {
|
||||
let i = (((l * d + z) * h + y) * w + x) as usize;
|
||||
texels += 1;
|
||||
unmapped += usize::from(img.unmapped.contains(&i));
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
unmapped == 0 || unmapped == texels,
|
||||
"tile ({tx}, {ty}, {tz}) of layer {l} is partly unmapped"
|
||||
);
|
||||
unmapped == 0
|
||||
})
|
||||
}
|
||||
|
||||
/// The words of `fp` at `probes` (each `[u, v, w, layer]`) through `arm`.
|
||||
fn words(
|
||||
fp: Footprint,
|
||||
dim: Dim,
|
||||
arrayed: bool,
|
||||
mut img: Image,
|
||||
probes: &[[f32; 4]],
|
||||
arm: Arm,
|
||||
) -> Vec<u32> {
|
||||
let m = kernel(fp, dim, arrayed).expect("kernel");
|
||||
let bytes: Vec<u8> = probes
|
||||
.iter()
|
||||
.flat_map(|p| p.iter().flat_map(|x| x.to_le_bytes()))
|
||||
.collect();
|
||||
let n = u32::try_from(probes.len()).expect("probe count");
|
||||
let mut buffers = vec![
|
||||
Buffer {
|
||||
slot: Some(slot(ResourceKind::Buffer, 0)),
|
||||
address: None,
|
||||
bytes,
|
||||
},
|
||||
Buffer {
|
||||
slot: Some(slot(ResourceKind::Buffer, 1)),
|
||||
address: None,
|
||||
bytes: vec![0xAB; probes.len() * 4],
|
||||
},
|
||||
];
|
||||
let Arm(tile) = arm;
|
||||
buffers.push(Buffer {
|
||||
slot: Some(slot(ResourceKind::Buffer, 2)),
|
||||
address: None,
|
||||
bytes: tile_map(&img, tile),
|
||||
});
|
||||
img.unmapped.clear();
|
||||
let res = Resources {
|
||||
buffers,
|
||||
..Resources::default()
|
||||
};
|
||||
let cfg = Config {
|
||||
workgroups: [n, 1, 1],
|
||||
..Config::default()
|
||||
};
|
||||
let (out, _) = interp::run_with_images(&m, &cfg, res, vec![img]).expect("run");
|
||||
out.buffers
|
||||
.get(1)
|
||||
.expect("words")
|
||||
.as_chunks::<4>()
|
||||
.0
|
||||
.iter()
|
||||
.map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]]))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn footprint(kind: Kind, axes: u8, border: bool) -> Footprint {
|
||||
Footprint {
|
||||
kind,
|
||||
axes,
|
||||
border: [border; 3],
|
||||
}
|
||||
}
|
||||
|
||||
/// One of Metal's answers: the access, the bits of `u` and `v`, and `resident()`.
|
||||
type Reading = (Kind, u32, u32, bool);
|
||||
|
||||
const L: Kind = Kind::Linear;
|
||||
const N: Kind = Kind::Nearest;
|
||||
const G: Kind = Kind::Gather;
|
||||
|
||||
/// 256x128 r32_float, its left 128x128 mapped (39503d65, 95ca7dc5, 760fce8c, 29f15128; the last
|
||||
/// samples at levels 1 to 3.5 of a one-level texture, which reads level 0).
|
||||
const LEFT_256: &[Reading] = &[
|
||||
(L, 0x3eff0000, 0x3d880000, true),
|
||||
(L, 0x3eff0001, 0x3d880000, true),
|
||||
(L, 0x3eff0002, 0x3d880000, true),
|
||||
(L, 0x3eff0004, 0x3d880000, true),
|
||||
(L, 0x3eff0008, 0x3d880000, true),
|
||||
(L, 0x3eff0010, 0x3d880000, true),
|
||||
(L, 0x3eff0020, 0x3d880000, true),
|
||||
(L, 0x3eff0040, 0x3d880000, true),
|
||||
(L, 0x3eff0080, 0x3d880000, true),
|
||||
(L, 0x3eff00c0, 0x3d880000, true),
|
||||
(L, 0x3eff00ff, 0x3d880000, true),
|
||||
(L, 0x3eff0100, 0x3d880000, false),
|
||||
(L, 0x3eff0101, 0x3d880000, false),
|
||||
(L, 0x3eff0180, 0x3d880000, false),
|
||||
(L, 0x3eff01ff, 0x3d880000, false),
|
||||
(L, 0x3eff0200, 0x3d880000, false),
|
||||
(L, 0x3eff0201, 0x3d880000, false),
|
||||
(L, 0x3eff0300, 0x3d880000, false),
|
||||
(L, 0x3eff0500, 0x3d880000, false),
|
||||
(L, 0x3eff03ff, 0x3d880000, false),
|
||||
(L, 0x3eff0400, 0x3d880000, false),
|
||||
(L, 0x3eff0401, 0x3d880000, false),
|
||||
(L, 0x3eff0600, 0x3d880000, false),
|
||||
(L, 0x3eff0800, 0x3d880000, false),
|
||||
(L, 0x3eff1000, 0x3d880000, false),
|
||||
(L, 0x3eff2000, 0x3d880000, false),
|
||||
(L, 0x3eff8000, 0x3d880000, false),
|
||||
(L, 0x3eff0080, 0x3d880400, true),
|
||||
(L, 0x3eff0101, 0x3d880808, false),
|
||||
(L, 0x3eff0200, 0x3d881000, false),
|
||||
(N, 0x3effffff, 0x3d880000, true),
|
||||
(N, 0x3effffe0, 0x3d880000, true),
|
||||
(N, 0x3effff00, 0x3d880000, true),
|
||||
(N, 0x3efffe00, 0x3d880000, true),
|
||||
(L, 0x3e810000, 0x3f7f0020, true),
|
||||
(L, 0x3e810000, 0x3f7f0101, true),
|
||||
(L, 0x3e810000, 0x3f7f0201, true),
|
||||
(L, 0x3e810000, 0x3b7fe000, true),
|
||||
(L, 0x3e810000, 0x3b7eff00, true),
|
||||
(L, 0x3e810000, 0x3b7dff00, true),
|
||||
// 95ca7dc5: probe 2 is the texel center whose zero-weight neighbour is unmapped.
|
||||
(L, 0x3e800000, 0x3d800000, true),
|
||||
(L, 0x3f000000, 0x3d800000, false),
|
||||
(L, 0x3eff0000, 0x3d880000, true),
|
||||
(L, 0x3efd0000, 0x3d880000, true),
|
||||
(L, 0x3f008000, 0x3d880000, false),
|
||||
(L, 0x3eff8000, 0x3d880000, false),
|
||||
(G, 0x3f000000, 0x3d800000, false),
|
||||
(G, 0x3efe0000, 0x3d800000, true),
|
||||
(G, 0x3f010000, 0x3d800000, false),
|
||||
(N, 0x3eff8000, 0x3d880000, true),
|
||||
(N, 0x3f004000, 0x3d880000, false),
|
||||
(L, 0x00000000, 0x3d800000, true),
|
||||
(L, 0x3f800000, 0x3d800000, false),
|
||||
// 760fce8c.
|
||||
(N, 0x3cb00000, 0x3d700000, true),
|
||||
(N, 0x3f488000, 0x3d700000, false),
|
||||
(N, 0x3eff8000, 0x3d700000, true),
|
||||
(N, 0x3f004000, 0x3d700000, false),
|
||||
(N, 0xbe800000, 0x3ec00000, true),
|
||||
// 29f15128.
|
||||
(L, 0x3cb00000, 0x3d700000, true),
|
||||
(L, 0x3f488000, 0x3d700000, false),
|
||||
(G, 0x3cc00000, 0x3d800000, true),
|
||||
(G, 0x3f490000, 0x3d800000, false),
|
||||
];
|
||||
|
||||
/// 256x128, its right 128x128 mapped (efe06aaf).
|
||||
const RIGHT_256: &[Reading] = &[
|
||||
(L, 0x3f008000, 0x3d880000, true),
|
||||
(L, 0x3f007fff, 0x3d880000, true),
|
||||
(L, 0x3f007ffe, 0x3d880000, true),
|
||||
(L, 0x3f007ffc, 0x3d880000, true),
|
||||
(L, 0x3f007ff8, 0x3d880000, true),
|
||||
(L, 0x3f007ff0, 0x3d880000, true),
|
||||
(L, 0x3f007fe0, 0x3d880000, true),
|
||||
(L, 0x3f007fc0, 0x3d880000, true),
|
||||
(L, 0x3f007fa0, 0x3d880000, true),
|
||||
(L, 0x3f007f80, 0x3d880000, true),
|
||||
(L, 0x3f007f40, 0x3d880000, false),
|
||||
(L, 0x3f007f00, 0x3d880000, false),
|
||||
(L, 0x3f007e80, 0x3d880000, false),
|
||||
(L, 0x3f007d80, 0x3d880000, false),
|
||||
(L, 0x3f007e00, 0x3d880000, false),
|
||||
(L, 0x3f007d00, 0x3d880000, false),
|
||||
(L, 0x3f007c00, 0x3d880000, false),
|
||||
(L, 0x3f007800, 0x3d880000, false),
|
||||
(L, 0x3f007000, 0x3d880000, false),
|
||||
(L, 0x3f004000, 0x3d880000, false),
|
||||
(G, 0x3f008000, 0x3d880000, true),
|
||||
(G, 0x3f007ff0, 0x3d880000, true),
|
||||
(G, 0x3f007f80, 0x3d880000, true),
|
||||
(G, 0x3f007f00, 0x3d880000, false),
|
||||
(N, 0x3effffff, 0x3d880000, false),
|
||||
(N, 0x3effffe0, 0x3d880000, false),
|
||||
(N, 0x3effff00, 0x3d880000, false),
|
||||
(N, 0x3efffe00, 0x3d880000, false),
|
||||
// Beside the right edge: the clamp-to-zero border counts nothing.
|
||||
(L, 0x3f7f8010, 0x3d880000, true),
|
||||
(L, 0x3f7f8080, 0x3d880000, true),
|
||||
(L, 0x3f7f8100, 0x3d880000, true),
|
||||
];
|
||||
|
||||
/// 384x128, x 128..256 mapped (363e39a2: off the sweep, where `u · 384` rounds).
|
||||
const MIDDLE_384: &[Reading] = &[
|
||||
(L, 0x3f2a5560, 0x3d880000, true),
|
||||
(L, 0x3f2a5580, 0x3d880000, true),
|
||||
(L, 0x3f2a55ab, 0x3d880000, false),
|
||||
(L, 0x3f2a55d5, 0x3d880000, false),
|
||||
(L, 0x3f2a5600, 0x3d880000, false),
|
||||
(L, 0x3f2a5601, 0x3d880000, false),
|
||||
(L, 0x3f2a5655, 0x3d880000, false),
|
||||
(L, 0x3f2a56ab, 0x3d880000, false),
|
||||
(L, 0x3eab5540, 0x3d880000, true),
|
||||
(L, 0x3eab5500, 0x3d880000, true),
|
||||
(L, 0x3eab54ab, 0x3d880000, true),
|
||||
(L, 0x3eab54a9, 0x3d880000, false),
|
||||
(L, 0x3eab5455, 0x3d880000, false),
|
||||
(L, 0x3eab5400, 0x3d880000, false),
|
||||
(L, 0x3eab53ff, 0x3d880000, false),
|
||||
(L, 0x3eab5355, 0x3d880000, false),
|
||||
(L, 0x3eab52ab, 0x3d880000, false),
|
||||
(L, 0x3eff0000, 0x3d880000, true),
|
||||
(L, 0x3f2a8e39, 0x3d880000, false),
|
||||
(G, 0x3f2aaaab, 0x3d880000, false),
|
||||
(N, 0x3f2aaaab, 0x3d880000, false),
|
||||
];
|
||||
|
||||
fn check(width: u32, mapped: std::ops::Range<u32>, border: bool, readings: &[Reading]) {
|
||||
check_arm(width, mapped, border, readings, Arm([64, 64, 1]));
|
||||
}
|
||||
|
||||
fn check_arm(
|
||||
width: u32,
|
||||
mapped: std::ops::Range<u32>,
|
||||
border: bool,
|
||||
readings: &[Reading],
|
||||
arm: Arm,
|
||||
) {
|
||||
let mut seen = 0;
|
||||
for kind in [L, N, G] {
|
||||
let probes: Vec<[f32; 4]> = readings
|
||||
.iter()
|
||||
.filter(|r| r.0 == kind)
|
||||
.map(|r| [f32::from_bits(r.1), f32::from_bits(r.2), 0.0, 0.0])
|
||||
.collect();
|
||||
let want: Vec<u32> = readings
|
||||
.iter()
|
||||
.filter(|r| r.0 == kind)
|
||||
.map(|r| u32::from(!r.3))
|
||||
.collect();
|
||||
if probes.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let img = image(Dim::D2, [width, 128, 1], 1, |x, _, _, _| {
|
||||
!mapped.contains(&x)
|
||||
});
|
||||
let got = words(
|
||||
footprint(kind, 2, border),
|
||||
Dim::D2,
|
||||
false,
|
||||
img,
|
||||
&probes,
|
||||
arm,
|
||||
);
|
||||
for (k, (g, w)) in got.iter().zip(&want).enumerate() {
|
||||
assert_eq!(
|
||||
g,
|
||||
w,
|
||||
"{arm:?} {kind:?} at u = {:#010x}, v = {} on {width} texels mapped {mapped:?}",
|
||||
probes[k][0].to_bits(),
|
||||
probes[k][1]
|
||||
);
|
||||
}
|
||||
seen += got.len();
|
||||
}
|
||||
assert_eq!(seen, readings.len());
|
||||
}
|
||||
|
||||
/// Metal's measured words at every probe its cases put beside an unmapped column: the linear
|
||||
/// quantum on either side of the edge (ties up), the gather's same position counting all four
|
||||
/// texels, the nearest filter's unquantized `floor`, the border counting nothing, and the
|
||||
/// position `u · N` rounded to `float` before it is quantized (363e39a2 at 384 texels).
|
||||
#[test]
|
||||
fn the_footprint_word_answers_metal_beside_an_unmapped_column() {
|
||||
check(256, 0..128, true, LEFT_256);
|
||||
check(256, 128..256, true, RIGHT_256);
|
||||
check(384, 128..256, true, MIDDLE_384);
|
||||
}
|
||||
|
||||
/// 256x128, its right 128x128 mapped, so the left edge column is unmapped (fd292944), through
|
||||
/// clamp_to_edge samplers.
|
||||
const EDGE: &[Reading] = &[
|
||||
(N, 0xbf000000, 0x3d880000, false),
|
||||
(N, 0x3fc00000, 0x3d880000, true),
|
||||
(N, 0x3f400000, 0xbf000000, true),
|
||||
(N, 0x3f400000, 0x3fc00000, true),
|
||||
(L, 0xbf000000, 0x3d880000, false),
|
||||
(L, 0x3fc00000, 0x3d880000, true),
|
||||
(L, 0x3f400000, 0xbf000000, true),
|
||||
(L, 0x3f008000, 0x3d880000, true),
|
||||
(L, 0x3f004000, 0x3d880000, false),
|
||||
(L, 0x3b000000, 0x3d880000, false),
|
||||
(L, 0xbb000000, 0x3d880000, false),
|
||||
(G, 0xbf000000, 0x3d880000, false),
|
||||
(G, 0x3fc00000, 0x3d880000, true),
|
||||
(G, 0x3f800000, 0x3d880000, true),
|
||||
];
|
||||
|
||||
/// The same texture through clamp_to_border (opaque white) samplers (fd292944).
|
||||
const BORDER: &[Reading] = &[
|
||||
(N, 0xbf000000, 0x3d880000, true),
|
||||
(N, 0x3b000000, 0x3d880000, false),
|
||||
(N, 0x3fc00000, 0x3d880000, true),
|
||||
(L, 0xbf000000, 0x3d880000, true),
|
||||
(L, 0x3a800000, 0x3d880000, false),
|
||||
(L, 0xba800000, 0x3d880000, false),
|
||||
(L, 0xbb800000, 0x3d880000, true),
|
||||
(L, 0xbb000000, 0x3d880000, true),
|
||||
(G, 0xbf000000, 0x3d880000, true),
|
||||
(G, 0x00000000, 0x3d880000, false),
|
||||
(G, 0x3fc00000, 0x3d880000, true),
|
||||
];
|
||||
|
||||
/// Metal's measured words where the addressing meets an unmapped edge column: a clamp_to_edge
|
||||
/// axis counts the edge texel it clamps to, and a clamp_to_border axis counts no border texel, at
|
||||
/// negative positions and past the far edge alike.
|
||||
#[test]
|
||||
fn the_footprint_word_answers_metal_at_an_unmapped_edge() {
|
||||
check(256, 128..256, false, EDGE);
|
||||
check(256, 128..256, true, BORDER);
|
||||
}
|
||||
|
||||
/// 64x64x32 r32_float 3D, slices z 0..16 mapped (203caac1): the quantum along z.
|
||||
const VOLUME: &[(Kind, [u32; 3], bool)] = &[
|
||||
(N, [0x3db00000, 0x3dd00000, 0x3e700000], true),
|
||||
(N, [0x3db00000, 0x3dd00000, 0x3f240000], false),
|
||||
(N, [0x3db00000, 0x3dd00000, 0x3efffff8], true),
|
||||
(L, [0x3db00000, 0x3dd00000, 0x3f000000], false),
|
||||
(L, [0x3db00000, 0x3dd00000, 0x3ef80000], true),
|
||||
(L, [0x3db00000, 0x3dd00000, 0x3ef80800], false),
|
||||
(L, [0x3db00000, 0x3dd00000, 0x3ef807f8], true),
|
||||
(L, [0x3f000000, 0x3f000000, 0x3e800000], true),
|
||||
(L, [0x3db00000, 0x3dd00000, 0x3c7f0000], true),
|
||||
];
|
||||
|
||||
/// Metal's measured words along a 3D texture's z, beside its unmapped upper slices: the same
|
||||
/// quantum on the third axis (ties up at probe `0x3ef80800`, just below it at `0x3ef807f8`).
|
||||
#[test]
|
||||
fn the_footprint_word_answers_metal_along_a_volumes_depth() {
|
||||
let mut seen = 0;
|
||||
for (arm, kind) in [(Arm([64, 64, 1]), L), (Arm([64, 64, 1]), N)] {
|
||||
let rows: Vec<_> = VOLUME.iter().filter(|r| r.0 == kind).collect();
|
||||
let probes: Vec<[f32; 4]> = rows
|
||||
.iter()
|
||||
.map(|r| {
|
||||
let [u, v, w] = r.1.map(f32::from_bits);
|
||||
[u, v, w, 0.0]
|
||||
})
|
||||
.collect();
|
||||
let img = image(Dim::D3, [64, 64, 32], 1, |_, _, z, _| z >= 16);
|
||||
let got = words(footprint(kind, 3, true), Dim::D3, false, img, &probes, arm);
|
||||
for (r, g) in rows.iter().zip(&got) {
|
||||
assert_eq!(*g, u32::from(!r.2), "{arm:?} {kind:?} at {:#010x?}", r.1);
|
||||
}
|
||||
seen += got.len();
|
||||
}
|
||||
assert_eq!(seen, VOLUME.len());
|
||||
}
|
||||
|
||||
/// The rule on one axis of `n` texels: the texels counted at `u`, and whether each is inside.
|
||||
fn rule(kind: Kind, u: f32, n: u32) -> Vec<i64> {
|
||||
let x = u * n as f32;
|
||||
match kind {
|
||||
Kind::Nearest => vec![x.floor() as i64],
|
||||
_ => {
|
||||
let q = (256.0 * f64::from(x) + 0.5).floor() as i64 - 128;
|
||||
let i0 = q >> 8;
|
||||
if kind == Kind::Gather || q & 255 != 0 {
|
||||
vec![i0, i0 + 1]
|
||||
} else {
|
||||
vec![i0]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A 3D texture's and a 2D array's words follow the rule on every axis: a 16x16x16 texture whose
|
||||
/// texels with `z` 0 or at least 8 are unmapped, and a 16x16 array of 3 layers whose layer 1 has
|
||||
/// those `x` unmapped, sampled at positions sweeping the quantum around each edge, from outside
|
||||
/// the texture's left edge to past its right, with the border on one run and the edge clamp on
|
||||
/// the other.
|
||||
#[test]
|
||||
fn the_footprint_word_applies_the_rule_on_every_axis() {
|
||||
let sweep: Vec<f32> = [-1i32, 0, 1, 2, 127, 128, 129, 255, 256]
|
||||
.iter()
|
||||
.flat_map(|&k| {
|
||||
// Positions `X = c + k / 256` around each edge of the unmapped texels, as normalized
|
||||
// coordinates.
|
||||
[-1.5f32, -0.5, 0.5, 7.5, 15.5].map(|c| (c + k as f32 / 256.0) / 16.0)
|
||||
})
|
||||
.collect();
|
||||
let unmapped = |i: i64| i == 0 || (8..16).contains(&i);
|
||||
let hit = |texels: &[i64], border: bool| {
|
||||
texels
|
||||
.iter()
|
||||
.any(|&i| unmapped(if border { i } else { i.clamp(0, 15) }))
|
||||
};
|
||||
let mut runs = 0;
|
||||
// The tile maps' tiles are whole runs of the unmapped texels: 8x8x1 for the 3D texture's
|
||||
// slices, 1x8x1 for the array's columns.
|
||||
let (volume, array) = (Arm([8, 8, 1]), Arm([1, 8, 1]));
|
||||
for border in [true, false] {
|
||||
for kind in [L, N] {
|
||||
let probes: Vec<[f32; 4]> = sweep.iter().map(|&w| [0.5, 0.25, w, 0.0]).collect();
|
||||
let img = image(Dim::D3, [16, 16, 16], 1, |_, _, z, _| {
|
||||
unmapped(i64::from(z))
|
||||
});
|
||||
let got = words(
|
||||
footprint(kind, 3, border),
|
||||
Dim::D3,
|
||||
false,
|
||||
img,
|
||||
&probes,
|
||||
volume,
|
||||
);
|
||||
for (p, g) in probes.iter().zip(&got) {
|
||||
let want = hit(&rule(kind, p[2], 16), border);
|
||||
assert_eq!(
|
||||
*g,
|
||||
u32::from(want),
|
||||
"{volume:?} 3D {kind:?} border {border} w = {}",
|
||||
p[2]
|
||||
);
|
||||
runs += 1;
|
||||
}
|
||||
}
|
||||
for kind in [L, N, G] {
|
||||
let probes: Vec<[f32; 4]> = sweep
|
||||
.iter()
|
||||
.flat_map(|&u| [0.0f32, 1.0, 2.0, 7.0].map(|l| [u, 0.5, 0.0, l]))
|
||||
.collect();
|
||||
let img = image(Dim::D2, [16, 16, 1], 3, |x, _, _, l| {
|
||||
l == 1 && unmapped(i64::from(x))
|
||||
});
|
||||
let got = words(
|
||||
footprint(kind, 2, border),
|
||||
Dim::D2,
|
||||
true,
|
||||
img,
|
||||
&probes,
|
||||
array,
|
||||
);
|
||||
for (p, g) in probes.iter().zip(&got) {
|
||||
// A layer past the array reads its last layer.
|
||||
let layer = (p[3] as u32).min(2);
|
||||
let want = layer == 1 && hit(&rule(kind, p[0], 16), border);
|
||||
assert_eq!(
|
||||
*g,
|
||||
u32::from(want),
|
||||
"{array:?} array {kind:?} border {border} u = {} layer {}",
|
||||
p[0],
|
||||
p[3]
|
||||
);
|
||||
runs += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(runs > 0);
|
||||
}
|
||||
Loaded 100 of 421 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user