Files
metal2vulkan/docs/API.md
T
Anees Iqbal a7320ad3f9 Conformance: no case declares a notice the runtime never announces
The runtime's side announces only the codes of the precision notes its states, textures and
sampler states carry (Degradation::from_precision_note). 66 Degradation kinds had no precision
note behind them: they were the deleted runtime's notices. A case that named one declared a
notice nothing can announce, and a value it loosened by one stayed loosened on no run.

What goes:
- every declaration of those 66 kinds, in 70 case files and the native-note set (six of its
  members were among them: float-tininess-after-rounding, unorm-depth-rounding,
  signed-depth-test, ycbcr-filter-not-exact, device-line-ties, device-subpixel-snap);
- the value tolerances justified by one: astc's and etc's compact-twin bounds
  (decoded-texel-precision), visibility's Boolean words (device-boolean-visibility),
  rotated-planes' unreached rotation-4 bands (rotated-load-tiles), sample-fills' wide depth
  digest (drawn-depth-copy), texture-fills' 32-bit float depth digests and fresh-contents'
  Depth32Float fresh site (restricted-depth-upload, fresh-pattern-zeroed);
- the replay helpers staged_records_notice, interlocked_split_notice and
  set_past_layout_notice, and every call of them;
- the 66 variants, their ALL entries and their codes;
- what only they used: the mesh pass notice list, the sparse notice lists, the GPU-time list,
  the buffer-blits and sparse-mappings rows' notices fields, buffer-target-clears' kept_image,
  buffer-texture-blits' copies_shared_bytes and its two tests, render-draw-forms'
  bounds-pass helpers, rotated-planes' band_is_reached and surface::stored_at,
  rotated-targets' reads_destination_alpha_in_color, visibility's boolean_words, and the
  module prose that described those notices.

The one backed kind whose name was not its note's, ImplementationDefinedReconvergence, is now
DeviceReconvergence with the code metal2vulkan-degrade-device-reconvergence, the note's kebab
name, and docs/API.md section 9 gains its entry. shared-in-system-memory stays for the next
commit. The tests that used a deleted kind as a stand-in use a backed one. Every case keeps
its shared-in-system-memory declaration; tests that count a case's declarations count what is
left. pass_start_reads no longer cites the deleted cost::the_creation_prediction.
docs/CONFORMANCE-COVERAGE.md is regenerated.

A case whose values the deleted tolerances held is now compared exactly; whether the runtime
differs there shows on the venues' replays.

Verified: cargo fmt --all. The gate runs once over this and the following commits.
2026-11-20 09:13:39 -08:00

381 KiB
Raw Blame History

The API

metal2vulkan compiles Metal AIR into Vulkan pipelines through an API shaped like Metal's object lifecycle. You hand it Metal-shaped inputs (a device description, a library, pipeline descriptors, what a draw or dispatch binds) and get back plain data to create and record Vulkan objects with: SPIR-V per stage, one pipeline layout, fixed-function state, and per-draw descriptor writes and push-constant bytes. You never parse AIR, never patch SPIR-V, never derive binding numbers from Metal indices, and never classify errors by message text.

This guide walks the flow on the repository's own fixtures. Every rust block is quoted from examples/api_preview.rs, which the test suite runs (tests/api_preview_example.rs fails when a block here stops matching it). Sections 9 and 10 also cover the runtime crate (metal2vulkan-runtime): the precision notes it carries and its deliberate differences from Metal. The runtime's own guide is its README.

Stability

  • No feature needed. Feature ash adds conversions to ash::vk and DeviceDescription::query; serde serializes the plain-data values; cli builds the command.
  • Frozen names, additive changes. The surface is the items at the roots of error, device, library, reflection, pipeline, bind, cache, metal (with metal::{format, sampler, state, vertex}), vk and ash_interop, plus Budget and CancelToken at the crate root. tests/api_surface.rs pins every name. Structs and enums are #[non_exhaustive] or opaque, so build values with new, Default or constants, assign fields, and match with a wildcard arm. The exceptions are exhaustive on purpose: keys and Vulkan structs (SlotRef, ResourceSlot, ApiVersion, ...), and the enums a consumer must interpret completely to bind and draw correctly (StageSource, PushHole, HeapSource, ImageSource, SamplerSource, UseTarget, SlotClass, StorageAttachmentView, VertexStride, TileMapping, CopySource, DrawCommand, PrecisionNote, and Metal's PrimitiveType, IndexType, CullMode, Winding and TextureType), where a new variant breaks your build on purpose.
  • Semver covers this surface from 0.2.0 (still 0.x: a breaking change bumps the minor version).
  • Not API: anything the reference does not show. Hidden items, every submodule of library, pipeline, bind and device (write pipeline::SlotRef, never pipeline::sym::SlotRef), and the translator core are private.
  • The AIR front end (container, bitcode reader, typed IR, metadata ABI, intrinsics, canonicalization) is the metal2vulkan-air crate, pinned exactly. The input and budget errors this crate re-exports are that crate's types.

scripts/api-docs renders the reference of exactly this surface (add --open to open it); it fails when a page links to a hidden or internal item.

Run the tour

PATH=/opt/homebrew/opt/llvm/bin:$PATH cargo run -p metal2vulkan --example api_preview

No GPU is involved. The fixtures are committed as LLVM text, so the example assembles them with llvm-as first; the API itself reads bitcode only.

1. A device

A DeviceDescription states the Vulkan physical device as you create it: API version, enabled features and extensions, limits, subgroup and float-controls properties, format support and the driver's identity. Three ways to get one:

  • DeviceDescription::from_khronos_json(json, profile_name) reads a Khronos profiles JSON. The tour uses the committed profiles under crates/metal2vulkan-validation/profiles/, from a bare Vulkan 1.2 device to desktop GPUs and MoltenVK.
  • unsafe DeviceDescription::query(&instance, physical_device, instance_api_version) (feature ash) reads a physical device. That is what it supports: enable at least description.recommended_enables(&policy) at vkCreateDevice, then pass with_enabled(&enabled) so the description states what is enabled. with_enabled refuses a set that breaks one of Vulkan's co-enable rules, naming its VUID. VkFeature::exposure() and VkExtension::requires(version) say where each feature lives at the device's version, to chain the create info.
  • Build one field by field.
let description = DeviceDescription::from_khronos_json(&json, None)?;
let device = Device::from_queries(description, DevicePolicy::default())?;

Device::from_queries needs no Vulkan device: it derives the profile from the description's queries alone, reading no vendor, device or driver identity. It refuses a device below Vulkan 1.2 and an inconsistent description or policy. A Device is cheap to clone; every compile and plan takes it.

The policy

DevicePolicy holds your product choices; together with the description they decide everything a compile does. DevicePolicy::default() is DevicePolicy::UNTRUSTED:

  • Containment and isolation on. Every access stays inside the resources the binder supplied, and guest shaders cannot reach each other's resources. Where the device enables robustBufferAccess, buffer accesses and vertex input are left to it. (MoltenVK advertises the feature without implementing it; there such accesses are not contained, as on native Metal.)
  • The device's arithmetic. The device's own maths library, divisions, fused multiply-adds, float denormals, rounding order of dot/mix/fast::sqrt, the grouping and fusion of fast-math sums and products (each operation in the AIR's order, its own fast-math flags its decoration), NaN bits, and the operand of fmin, fmax, min3, max3, clamp and saturate, on every device and with no exact form. Each records a precision note with its bound, on every device.
  • The device's native forms. The device's own sampler (its filter, footprint, level, anisotropy, texel conversion and comparison, a two-plane YCbCr texture's filter among them), with no switch: the device's answer is the contract, recorded as PrecisionNote::DeviceSampling with its measured bound. The device's own half rounding and its blend of a half color have no switch either: each records its note.
  • The resident-table and handle-table domains (PointerDomain::ResidentTable, HandleDomain::Table, the default). The identity domains (PointerDomain::Identity with HandleDomain::Identity, taken together) are the new runtime's form: pointers are device addresses used directly and a texture's or sampler's handle is its gpuResourceID (RESOURCE-ID.md). They need bufferDeviceAddress and shaderInt64. Under them a buffer slot is reached at its own device address (gpuAddress plus the bind offset), pushed less 2^31 as PushField::SlotGuestBase (section 5), with no root table and no descriptor. The constant blob (the program-scope constants whose address merges, escapes or is compared, or that are read through another type than their own) is the module's own there: a Private array of its words, zero-padded to 16 bytes, which every load is checked against, and no stage carries a constant_blob. A blob past 64 KiB is refused (Unsupported{IdentityDomains}, naming the constant data's size). With containment on, an access of the slot whose byte offset is not a translation-time constant is checked against the slot's buffer (PushField::SlotBounds), from the buffer's start to its end, as Metal's domain is the buffer: an offset before the bind offset reads and writes the buffer's bytes there. Outside the buffer, a load reads zero and a store or atomic does nothing (section 5). An access at a constant offset is not checked. A slot whose argument states an alignment of at least 4 (air.arg_type_align_size) is reached from that address as it is: each access is at the pushed word plus its 32-bit byte offset plus 2^31, modulo 2^32, zero-extended, which is the address plus the offset read as signed, exact as the new runtime makes no buffer longer than 2 GiB (MAX_BUFFER_LENGTH); a constant part of the offset joins the 2^31 in one constant. An access of 8 or 16 bytes at an offset proven a multiple of its size is one uvec2 or uvec4. The function states RuntimeFact::AddressAlignment with that alignment (at most 16), and the new runtime refuses a dispatch whose bound address is not a multiple of it, as Metal's API validation refuses the bind offset (an accepted difference, section 10). A slot whose argument states an alignment below 4, or none, is reached the same way where each of its accesses is one 1- or 2-byte unit no wider than that alignment (an i8 access of a uchar buffer, an i16 one of a ushort buffer) on a device with that width's storage access. Any other slot is reached from the word below each access, its offset sign-extended, so an access before the bind offset reaches below the bind address as Metal's does. Fields past a function's push window go to a parameter block in memory, read at the device address PushField::ArgumentTableAddress, which the window always holds. The function reads the block 16 bytes at a time at multiples of 16 (its size, argument_table_size, is a multiple of 16) and never writes it, so the consumer places it at a multiple of 16 and leaves it unchanged while the command reads it. A kernel's window is 256 bytes, as the runtime's floor requires that much maxPushConstantsSize: a dispatch region and 24 buffer addresses below its tail. A render pipeline's two functions share one 256-byte range: the vertex function's window is [0, 248), and the fragment function's runs from the vertex function's end to 256. A vertex function is lowered without knowing its fragment function, so it leaves the last 8 bytes, where a fragment function whose fields spill always pushes its block's address; that costs only a vertex function whose own fields pass 248 bytes, which spills where it would have filled them. The fields only a checked access reads (PushField::ZeroAddress and each PushField::SlotBounds) come last in the order, so they are the first to move to the block. Each function's push ends with its tail, 24 bytes or more above its other pushed fields: its highest PushField::SlotBounds or PushField::ZeroAddress, moved there, or where it pushes neither, the zero word PushField::TailWord at PushPlacement::tail_word, with which its push_range ends; a function that pushes one field of 8 bytes or fewer has none. A driver that uploads a stage's push bytes up to the highest one the stage reads then holds every load it widens from the other fields. The function returns at its start where its tail holds what the consumer never pushes there (a tail word other than zero, bounds whose two words are both all ones, a zero-range address of all ones), so the consumer pushes the tail word zero with the other fields; the bytes of the hole are not read. A kernel that reads a grid builtin reads PushField::DispatchRegion on every dispatch: a dispatch the host knows states Metal's grid and its piece's first threadgroup there, and an indirect dispatch a zero grid, whose kernel takes NumWorkgroups times its workgroup size. It reads its first threadgroup from every region (0 where the dispatch is not split, and for an indirect one) and declares MultiRegion, default 0: at 0 Metal's threadgroup size is the pipeline's workgroup size; at 1 it is the region's, for a region whose workgroup size is not Metal's (an edge region). A kernel whose workgroup is its threadgroup (one outside the flattened SIMD-group tiers, without compute derivatives) also declares SpecKey::DeepThreadgroup, default false: at true its workgroup is one row of the threadgroup's threads, (sx·sy·sz, 1, 1), each thread's position its LocalInvocationIndex unflattened in Metal's order, so a threadgroup deeper than a device's maxComputeWorkGroupSize[2] runs; the binder sets it for a region deeper than pipeline::DEEP_THREADGROUP (64) alone, and so does a runtime, so every other pipeline specializes it away. MetalDeviceProperties::max_threads_per_threadgroup is the capped maxComputeWorkGroupInvocations on every axis. A texture slot's gpuResourceID is pushed as its PushField::SlotGuestBase, and its texture is the element at the ID's index of set 1's two fixed arrays, the same layout for every pipeline (RESOURCE-ID.md); it binds no descriptor of its own and declares no specialization constant. An argument buffer's texture is the element at the index of the gpuResourceID its member holds, with no handle table, so a slot and a member of one class index one array. No binder chooses a variant there: a texture reads through the plain form whatever texture its ID names, its float or half reads take the device's sRGB decode with PrecisionNote::SrgbTexelDecode, and no texture is sparse (the consumer refuses a sparse texture). A texture slot sampled through a runtime sampler slot samples set 1's element of the sampler arrays at the index of the sampler's pushed gpuResourceID, joined to the texture's element by OpSampledImage, and reads the sampler's word from that ID. One sampled through a constexpr sampler samples the element at the index the consumer pushes for it (PushField::ConstexprSampler), where the consumer places the device sampler CombinedSampler::constexpr_sampler describes, normalized: the shader scales a pixel sampler's coordinate. An integer write to a storage slot without a format saturates to the channel widths the consumer pushes (PushField::TextureIntegerChannels). A sample of a 2D texture slot through a bicubic constexpr sampler at normalized coordinates reads how Metal's bicubic filter treats the bound texture's texels (its inner taps, its clamp and its border texels) from the word the consumer pushes for that slot (PushField::BicubicTexels: metal::format::bicubic_texels_word of the bound texture's format and swizzle, metal::format::BICUBIC_TEXELS_UNBOUND for a slot bound to nothing), the bits the default domains specialize SpecKey::BicubicTexels to. bicubic_texels_word has no word for a compressed, YUV, stencil, integer, extended-range or 8-bit sRGB format, so such a texture has no bicubic sample there (the new runtime refuses the dispatch, Gap::BicubicTexels). Its arithmetic is noted PrecisionNote::BicubicFilterArithmetic, as on the default domains. A fragment function under the pipeline's private alpha test (PrivateRenderState::alpha_test_enabled, a compare function other than Never or Always) compares its color 0's alpha with the code the consumer pushes (PushField::AlphaTestReference): bind::alpha_test_code of the encoder's setAlphaTestReferenceValue:, 1 until the encoder sets it. It is Metal's 8-bit unorm code of the reference (a NaN taken as 0, clamped to [0, 1], the exact product with 255 rounded to nearest), the form the function converts its alpha to, so a consumer that pushes it compares as Metal does. A fragment function's read of a color attachment (framebuffer fetch, section 4) on a device with neither ordered form takes no input attachment: it reads, at the integer part of its position (its own sample where the pass is multisampled), level 0, the sampled-texture array's element at the index the consumer pushes for that attachment (PushField::FetchedColor { color, texels }, texels the read's numeric class), and a read-only signed-integer attachment joins signed_color_attachments. Every precision note is static there: no constant or binder decides one. So far they lower a kernel that reaches memory through its buffer slots and the device addresses it loads (an argument buffer's pointer member, a stored gpuAddress) or makes from integers, and reads, writes, sizes or tests for nil its texture slots and its argument buffers' textures, those of an argument buffer a pointer member reaches included, and samples its texture slots through its runtime sampler slots and its constexpr samplers. Any other function is refused as Unsupported{IdentityDomains}, whose symbol names the first such form the function holds: one that samples through an argument buffer's sampler or an array of samplers or samples an argument buffer's texture, emulates a sampler's anisotropy, samples a 1D texture or at pixel coordinates through a bicubic filter, uses a texture buffer, a slot's levels or swizzle, a two-plane, extended-range or sRGB-twin form, reads an argument buffer's texture through another numeric type or as raw texels, or uses any other state of a texture or sampler beyond its ID. An argument buffer's texture reads the element at its ID's index masked to its low 16 bits, so a bad ID reads an element of the arrays (RESOURCE-ID.md); the change that first lowers an argument buffer's sampler masks its index the same way.
  • The model's linear sample of planes read in place (YCbCrInPlacePolicy::Model, the default; changes emitted code). On an integrated GPU or a CPU device a function that only samples, gathers or sizes a YCBCR8_420_2P or YCBCR10_420_2P texture reads its planes' codes in place through a uniform texel buffer, which no sampler of the device reads, so the shader filters and converts them. A linear sample that addresses no border is Vulkan's Y′CbCr model of the codes, as the device's own conversion with a linear chroma filter computes it: four luma codes and four chroma pairs blended bilinearly, then the range and matrix in float, clamped into [0, 1] (eight fetches), recorded HalfSampleFilter or FloatSampleFilter and announced ycbcr-filter-not-exact. ycbcr_in_place_reads = YCbCrInPlacePolicy::Exact, which exact_answers() selects, converts each of Metal's four taps and sums them on the grid 2048, exactly (twenty fetches). A nearest sample, a border mode and a gather are Metal's under either value.
  • half chains held at float precision without shaderFloat16 (HalfChainPolicy::AtExits, the default; changes emitted code). A device without 16-bit floats has no half arithmetic, so a module computes each half + - * in float and rounds it by the device's quantize. An operation whose flags hold contract and reassoc and whose result only such operations read is left unrounded: the chain rounds where a value leaves it, one quantize per exit instead of one per operation, recorded FastMathRewrites. half_chains = HalfChainPolicy::EachOperation, which exact_answers() selects, rounds every operation. A device with shaderFloat16 computes half alike under either value.
  • Batches of a queue ordered by their ends (BatchOrderPolicy::Ends, the runtime's choice; no pipeline differs). On ANV, RADV and NVIDIA's driver, each measured to start no kernel submission of a VkQueue before the one before it completed, each batch of command buffers ends with a barrier ordering its work before every later command of its VkQueue: a batch that depends on an earlier one there begins with no barrier of its own, and a command buffer's GPU start is taken once the work before it completed, which is when such a driver starts it. Nothing is announced: on those drivers the work's order, its results and its GPU times are the same under either value. batch_order = BatchOrderPolicy::Exact, which exact_answers() selects, orders each batch after the earlier ones of its queue only by its work's dependencies on theirs, as Metal does (an M3 Max starts an independent command buffer committed behind running work while that work runs), and takes a command buffer's GPU start as its work begins. Every other driver takes that form under either value.
  • A render encoder's calls lowered inside each call (RenderLoweringPolicy::AtCall, the default, which exact_answers() selects too; the runtime's choice, no pipeline differs): each call works out and records its commands before it returns, and returns every refusal. render_lowering = RenderLoweringPolicy::Worker logs each call and lowers it later, in order, before the command buffer's submission: in batches of 32 calls on the device's lowering thread while the program goes on. A program that runs 16 batches ahead of that thread waits for it in its next call, and one 4 encoders' ends ahead in its next end_encoding. end_encoding hands the encoder's end to that thread too and returns; the next call that follows the end in its command buffer (another encoder, an event or semaphore command, commit_failed, refusal, used_resources, ended_encoders, failed_pipeline, dropped_draw) lowers on the program's thread what the thread has not, and a rebind or detach of host pages and Device::work_counts lower every encoder's first. commit makes its checks at the call (committed already, an encoder open, one abandoned) and returns, its status Committed, its own work left to run once the end is lowered, on the thread that lowers it; while such a commit waits, every later commit of the device waits behind it, so the device's scheduler still takes commits in their order across its queues. A wait for the command buffer lowers on the waiting thread what that thread has not. A refusal only the commit's own work finds (an executed indirect command's recording, the commit's uploads) fails the command buffer, nothing of it run, with CallRefused of commit at index 0 where no call of it was refused before: it commits again with nothing made for its commands, so it completes, in its queue's order, its completed handlers run and its waits return, as every committed command buffer of Metal's does. An end that checks the depth/stencil attachment's store actions or store action options (one Unknown, options set, or any store action or resolve target set by a call) is lowered inside end_encoding, which returns its refusal. The call still makes Metal's checks of its arguments and of the encoder's state, and returns their refusals: the argument tables' and state setters', the objects' devices, the pipeline state's against the pass, and a draw's kind, arguments and settings. It copies the bytes it was lent and holds the objects it names. A call those checks do not cover is lowered inside the call, as under AtCall: store actions, resolve targets, visibility result modes, threadgroup memory lengths, fences, patch and mesh draws, a draw while a visible-function table or a vertex buffer of more than 4 GiB past its offset is bound, and any call while a buffer of the device is detached. From a pipeline state that fetches the pass's colors, reads its tile memory, uses an imageblock, draws patches or meshes, or renders a color in another format than its attachment's; a tile dispatch; an execution of indirect render commands; a memory barrier; and a draw that gives the pass its hidden depth and stencil, every later call of the encoder is lowered inside the call, and so is every call of a pass the device draws in color groups. A refusal only the lowering finds (a runtime gap of the draw's variant or instance, out of memory, a Vulkan error) fails the command buffer instead: CommandBufferError::CallRefused names the call (EncoderCall: its Metal selector and its index among the encoder's calls; the end is endEncoding, the index after the encoder's last call), CommandBuffer::refusal returns the error the call would have returned, and that encoder and every one after it in the command buffer run nothing. Notices a logged call's lowering announces name the call (DegradeNotice::call) and may reach the message sink on the lowering thread, and DeviceOptions::lowering_refuses turns the kinds it lists into such refusals (section 9).
  • A pipeline still being made: a creation waits a bound, a command buffer until made (PipelineWaitPolicy::Bounded, the default; the runtime's choice, no pipeline differs). A render or compute state's creation hands the driver's making of its predicted pipeline to the runtime's pool and waits for it DevicePolicy::pipeline_creation_wait at most. A committed command buffer waits for its draws' and dispatches' (a compute encoder's, a render pass's tile dispatches, an execution's replayed draws, whose pipelines the commit hands to the pool) pipelines still being made until they are made, however long that takes, and records them then: each renders and writes what Metal's does, its command buffer completing later, as on a slower GPU. commit waits for none of them but a pass that executes render commands the CPU writes, until its commit plus DevicePolicy::pipeline_commit_wait at most, for its pipelines and for those its executions' replay begins itself, which it leaves to the command buffer's host step past that; the step records the pass once they are made. No other program call blocks for a making but those that wait for the GPU (a wait for the command buffer's completion or scheduling, an event it signals, a new command buffer of a queue whose most are all uncompleted); a host step that meets a making of its own waits for it on its step's thread. No draw or dispatch is dropped for its making's time. Meanwhile it holds back only its own queue's later command buffers: one of another queue committed after it goes first, even where the two touch one tracked resource that one of them writes, and the waiting one runs after it, as an x86 Mac's GPU may take a later commit of another queue first (metal2vulkan-conformance's probes/cross_queue_surface_order.m: a Radeon Pro 5300M and a UHD 630 under macOS 26.7.1; an M3 Max kept commit order); a fence the two share keeps commit order, and so does a command buffer of a queue made for copies (Device::new_command_queue_for_copies, a runtime extension that promises it), which waits behind the waiting one where the two conflict. Both bounds are 4.5 s by default. What one call waits for the driver's makings: a state's creation, its creation wait at most; a commit, until its own deadline at most (it records there what it can, an execution of render commands the CPU writes among them; every other recording runs on the runtime's scheduler thread, which no call waits for). A creation waits on no command buffer's deadline and a commit on no creation's, so a host step that creates a state and commits a command buffer waits their sum at most, 9 s by default, under a guest's 10 s FIFO check, where a driver's cold compile took 11.6 s (MoltenVK with a cold Metal compiler service). Made until made under this value too, in the call that makes them: a draw that records nothing, a draw in a pass of custom sample positions, and one recorded again into another instance of its pass (each in the draw's call or an execution's replay), a device replay's draws (in its commit), and a making that failed, made again by its command's recording. pipeline_waits = PipelineWaitPolicy::Exact, which exact_answers() selects, makes the predicted pipeline before the creation returns, as Metal compiles there, and waits for every draw's and dispatch's until made.
  • A wide line the device's own (WideLinePolicy::Device, the default; the runtime's choice, no pipeline's code differs). A line Apple's setLineWidth: widens, and a triangle's edge in fill mode Lines, is drawn by the device's own lines wherever it draws the width (wideLines, inside lineWidthRange), announced device-wide-lines: no device's lines are taken as Metal's parallelogram, a driver's parallelograms included (their ends are the driver's). wide_lines = WideLinePolicy::Exact, which exact_answers() selects, draws those as the pipeline's band variant instead (section 4), on a device with tessellationShader. Every other width other than 1 is the band under either value, and what neither draws the device's lines at the nearest width they draw, announced lines-at-nearest-width (the runtime's README, line widths).
  • A compressed extended-range texture's blits keep the bytes (ExtendedRangeBlitPolicy::Kept, the default; the runtime's choice, no pipeline differs). Metal's GPU blit into, out of or between BGRA10_XR or BGRA10_XR_sRGB textures it keeps losslessly compressed (allowGPUOptimizedContents, 16 texels or more a side, neither ShaderWrite nor PixelFormatView usage) writes each texel's canonical encoding, each 16-bit field's low six bits cleared and the alpha code clamped to [384, 894], and its fill clears the low six bits alone; the device's copy keeps the bytes, the same value, announced extended-range-bits-kept. extended_range_blits = ExtendedRangeBlitPolicy::Canonical, which exact_answers() selects, writes Metal's encoding: a compute dispatch after each such blit rewrites the texels it wrote (an image's through a scratch copy, a buffer's or a texture over a buffer's in place), and a fill's texel is encoded before it is written. A blit out of one into a buffer whose words the device cannot bind (an offset or pitch off 4 bytes, past maxStorageBufferRange), or into a texture over a buffer whose rows share bytes, keeps the bytes under either value, announced.
  • Command queues share VkQueues where the GPU idles between them (QueueSharingPolicy::Adaptive, the default; the runtime's choice, no pipeline differs). On a device whose own self-check finds its GPU idle when consecutive work comes from another VkQueue (the runtime's check, run once per driver, release and runtime on a thread of its own and its verdict kept in the shader cache's directory as the in-place check's is; NVIDIA's driver on the RTX 5080 Laptop GPU idles about 50 us at each such switch), a command queue that makes a command buffer while it holds no other uncompleted one moves onto the busy VkQueue of its family whose oldest batch has run under 0.5 ms, so short command buffers of several queues run with no switch between them. A queue one of whose command buffers ran on the GPU for over 2 ms, by its own timestamps, is long: no queue joins its VkQueue, and it moves once more, at its next such make, to an idle VkQueue of its own. So a queue waits behind another's long command buffer once per queue that goes long, about that command buffer's length: the first long command buffer of a queue that shared holds the command buffers committed behind it there for its whole length, announced queue-sharing at the device's first join (section 9). A queue made with Device::new_command_queue_unshared never moves, and no queue joins its VkQueue: the form for a queue whose command buffers must never wait behind another's (a compositor's beside an application's; on the RTX 5080 Laptop GPU none of its completions took over 10 ms in any run, where a shared one's had one stall of 30 ms beside 30 ms command buffers). Presenting queues, and a queue that lent its VkQueue (CommandQueue::with_vk_queue), never move. Before the check answers, and on a device whose check finds no idling or that has no two VkQueues of one family (MoltenVK, RADV, lavapipe), each queue keeps the VkQueue it took at its creation. So does a device whose command buffers write no GPU timestamps it reads (DeviceOptions::gpu_times_from_host, or a driver whose timestamps wait for every queue's), counted WorkCounts::queue_sharing_untimed: a queue is known long only by its command buffers' timestamps. queue_sharing = QueueSharingPolicy::PerQueue, which exact_answers() selects, keeps each command queue on that VkQueue everywhere and runs no check. Under either value a queue takes, as it is made, the VkQueue the fewest live command queues hold, of those no unshared queue holds, in turn among equals, so queues share one only while more are live than VkQueues, however many came and went before (WorkCounts::command_queues_live_most); an unshared queue takes one no command queue holds where one is free (WorkCounts::unshared_queues_sharing_a_vk_queue counts one that found none).
  • Other queues' work is held back from an unshared queue's VkQueue (UnsharedIsolationPolicy::Bounded, the default; the runtime's choice, no pipeline differs). Where a queue made with Device::new_command_queue_unshared shares its VkQueue with other command queues (a device with one graphics queue: RADV, ANV, lavapipe), another queue's batch is submitted there only while less than 2 ms of the other queues' expected GPU work is in flight on it; else the scheduler holds it, in its place in the order, until enough completes. A batch's expected work is its command queue's: the host's view of how long its recent batches ran, raised at once by a longer one and halved toward a shorter one; while a batch of a command queue with no run seen yet is in flight, no other goes until it completes. The next batch goes in before the one ahead ends, so the GPU is not left idle between them where the scheduler's thread runs in time, and the unshared queue's command buffer waits behind about one batch of theirs: the whole of one, however long, as a submission runs to its end. A scheduler pass that finds a held batch let go and the unshared queue's command buffer ready together (a pass the host ran late) sends the unshared one first, and a batch whose room comes during a pass waits while the unshared queue's commit, posted before that, is not yet taken in by a pass, or is taken in and waits only for its host step, its submission checks or a signal already submitted to land (WorkCounts::heads_held_for_unshared_commits); commits posted after its room came never hold it, nor one that waits for anything else. The 2 ms holds while an unshared queue there committed a command buffer within the last 50 ms, so a compositor drawing 20 frames a second or more (a 24-frame video's, a 30-frame game's) keeps it; while none has, the budget is 16 ms: an application keeping less queued beside a quiet compositor is not held, and the compositor's first command buffer after its quiet stretch waits behind at most about 16 ms of the other queues' expected work and one batch, the 2 ms applying from that commit on (WorkCounts::heads_let_go_unshared_idle counts the heads the 16 ms let go where 2 ms would hold them). Beside an application keeping three 30 ms command buffers in flight, a compositor's median wait fell from 75 to 17.5 ms on the Iris Xe and from 71-84 to 18 ms on the Radeon 780M, with no throughput lost on a quiet host; under the host's CPU load the GPU idles more (docs/FAST-PATHS.md has the numbers). Counted: WorkCounts::heads_held_for_unshared_isolation. unshared_isolation = UnsharedIsolationPolicy::Off submits every ready batch at once, so the unshared queue's command buffers wait behind every batch submitted before them there.
  • Command queues take turns on a VkQueue they share (QueueTurnPolicy::Fair, the default; the runtime's choice, no pipeline differs). On a VkQueue two or more command queues hold (a device with one graphics queue: RADV, ANV, lavapipe), a batch of a queue not made unshared is submitted there only while less than 2 ms of its own queue's expected GPU work is in flight on it, or 16 ms while no other command queue submitted there within the last 50 ms; else the scheduler holds it, in its place in the order, and a later commit of another queue that shares nothing with it goes first. Each batch of a queue in flight counts the queue's expected run now (as above), so a run longer than its recent ones prices the rest of a burst at once; a queue with no run seen yet keeps one batch in flight until it completes. So a command buffer another queue commits after one queue's burst of command buffers waits behind about 16 ms of it and one batch, then about 2 ms and one batch while it keeps submitting, not the whole burst; a batch already submitted still runs to its end. An unshared queue's batches are never held for their turn. Counted: WorkCounts::heads_held_for_queue_turns, heads_let_go_turn_idle, scheduler_at_commit_left_turns. queue_turns = QueueTurnPolicy::CommitOrder submits every ready batch at once, in commit order, so a later commit of another queue waits behind every batch submitted before it there (docs/FAST-PATHS.md has the trade).
  • An attachment loaded DontCare and not stored, cleared where its driver clears it no slower (UnstoredDontCarePolicy::Driver, the default; the runtime's choice, no pipeline differs). Metal's draws read zero (a colour) or the pass's clear value (depth, stencil) of such an attachment wherever they read it (an M3 Max, macOS 27.0.1: a framebuffer fetch and a stencil test, in passes split and whole). In a pass whose draws reach a tile the runtime clears it over the render area on a driver measured to run that clear no slower than its DONT_CARE load (DriverFact::UnstoredClearNoSlower: MoltenVK on the M3 Max, RADV on the Radeon 780M), and leaves it to the driver's DONT_CARE elsewhere, announced dont-care-unstored-load: lavapipe's draws then read its earlier texels. unstored_dont_care_loads = UnstoredDontCarePolicy::Cleared, which exact_answers() selects, clears it on every device. Separate depth and stencil textures take the same answer, each aspect apart, in the scratch image the pass renders them through. An image the runtime makes to stand for an attachment there (that scratch image, a stand-in, a backing) starts at zero on such a driver, never as its memory lies. A memoryless one is not covered.

Loops run as written: no execution bound is translated in.

What the device answers

let device = committed_device("moltenvk-m3")?;
let enables = device.required_enables();
// ...
hex(&device.profile().fingerprint()),
// ...
println!("  Metal properties: {:?}", device.metal_properties());
  • required_enables(): everything an artifact compiled for this device can need enabled.
  • metal_properties(): the answers to the guest's device queries (thread execution width, threadgroup limits, argument-buffer and read-write texture tiers, ...).
  • profile().fingerprint(): a hash of every profile field, the policy included. Every cache key includes it, so an artifact never serves another device. Facts that follow the machine's memory (DeviceDescription::allocation: maxMemoryAllocationSize, maxBufferSize) are not profile fields, so two machines that differ only there share artifacts.
  • profile().spirv_validation(): the spirv-val environments and relaxations every module for the device is valid under. The command line runs exactly these.
  • The profile's facts: enabled(), limits(), images(), fragment(), descriptors(), the driver workarounds and measured deviations it takes (workarounds(), driver_deviations()), its subgroups() model and simd_tier(...), how it contains an out-of-bounds access (containment(), checks_buffers_in_shader(), checks_atomics_in_shader()), and the Function storage a thread holds (function_storage(): FunctionStorage::Measured bytes for a measured device, or FunctionStorage::Assumed with the 16 KiB floor, past which a vertex or fragment function runs with FunctionStorageAssumed up to 192 KiB and any other stage is refused).
  • neutral_kinds(): the neutral resources plans bind where nothing compatible is bound. Create each once, up front.

Measured driver behavior

Where Vulkan leaves an answer to the driver and a driver's answer is Metal's, the profile relies on it only where that driver was measured to give it, keyed on the description's driver identity (driver_id, vendor_id, and device_id where one GPU differs from another; MoltenVK's device_id is the macOS release and the Apple GPU family, so the M3 Max and the M4 share one under macOS 27), never on its driver_version and never on a claim of the description itself. A row holds at every release of its driver. A GPU that reports more than one device_id is read by the one it was measured under (DeviceDescription::canonical_device_id): the Radeon 780M of Hawk Point (0x1900) as Phoenix's (0x15bf). These are DriverDeviations (simdgroups that run in lockstep, Metal's own float functions, sampler and canonical NaNs, color writes, ...), measured on MoltenVK on Apple's M3 Max and M4, with a few per-GPU facts measured elsewhere. A driver or GPU that was not measured takes the route each deviation's docs name for it: the device's own answer, recorded as a precision note, or, where the answer decides a capability, its emulation or a refusal.

Metal semantics the translation keeps on every device, beyond Vulkan's: Metal's 32-lane simdgroups (and, under the resident-table domains alone, the order Apple's lockstep gives a simdgroup's threadgroup and device accesses within a barrier interval). fneg and fabs are the device's OpFNegate and FAbs, so a NaN's payload and a denormal are the device's (native-nan-encoding, device-denormals). A NaN's bits, the operand fmin, fmax, min3, max3, clamp and saturate pick beside a NaN or between two zeros, a half read from its bits, which is the device's widening on every device (a NaN's bits, and a denormal on a device that may flush 16-bit ones), and a half rounded from a value below the smallest normal half on a device without shaderFloat16 (its OpQuantizeToF16's zero) are the device's, each recorded as a precision note.

What the runtime enables for itself outside the vocabulary enters no enable set, compile profile or fingerprint: among it the extensions of its dma-buf fallback for no-copy memory whose pointer the device refuses (HostMemory::with_dma_buf), VK_EXT_external_memory_dma_buf with VK_KHR_external_memory_fd, and VK_EXT_image_drm_format_modifier with VK_EXT_queue_family_foreign beside them, wherever a device lists them, and VK_EXT_pageable_device_local_memory with VK_EXT_memory_priority, where a device lists both and has pageableDeviceLocalMemory: its driver may then move device-local memory to host-local memory to make room rather than fail an allocation, every allocation at the default priority; and VK_EXT_zero_initialize_device_memory, where a device the runtime made lists it, has zeroInitializeDeviceMemory and copies textures on the host: its blocks of images are then allocated zero-initialized, as many as without it, and a Shared or Managed texture's image that copies on the host and lies in bytes no resource used starts in the driver's zeros, with no write of the host's (WorkCounts::images_started_zeroed).

A texture over host pages is one over a no-copy buffer's (imported by their pointer or as dma-bufs), or over a host-visible buffer of the runtime's own longer than 32 MiB where the device imports host pointers and the memory class's best type for the buffer takes such an import: that buffer lies in fresh anonymous pages imported by their pointer, zero as mapped, so that nothing writes its zeros (WorkCounts::fresh_page_buffers_made). A class whose best memory type takes no such import -- a discrete card's write-combined class, whose best type for the buffer is a device-local host-visible one -- is placed as ever and its bytes set to zero on the host; the buffer reads zero either way, which is all a program sees.

An image bound to imported memory starts in VK_IMAGE_LAYOUT_UNDEFINED (VUID-VkImageCreateInfo-pNext-01443), and its first move, like any layout transition, may read and write every byte bound to it, where Metal keeps every CPU write to bytes a command buffer does not write; a render pass's load and store operations may too, for an image it renders. Under the default HostPageTexturePolicy::InPlace the runtime relies on the driver there, checked: a texture over host pages whose declared usage samples, reads, renders into it or writes it through a shader (ShaderWrite or ShaderAtomic, of texels of 1, 2, 4, 8 or 16 bytes) is a linear image aliasing the pages (one over dma-buf pages a DRM_FORMAT_MOD_LINEAR image acquired from VK_QUEUE_FAMILY_FOREIGN_EXT: where the buffer lies in one import dedicated to nothing and the driver takes such an image there, its plane at offset 0, bound at the texels' offset in that import and asking the buffer's source nothing, WorkCounts::dma_buf_images_in_import; else over a dma-buf of its own pages, its plane at the texels' offset in their first page, or, where the driver lays such a plane out at another offset, at offset 0 of an image bound at the texels' offset, WorkCounts::dma_buf_images_at_offset) wherever the device makes such an image and its own check passed for that kind of pages and each of its accesses (WorkCounts::host_textures_in_place, dma_buf_textures_in_place, fresh_page_textures_in_place, and host_textures_in_place_written for one a shader writes), on a discrete GPU as on any other. An image over a dma-buf of its own pages is kept with its import as its texture goes, for the next texture over the same pages of the same plan, offset and pitches, which takes it asking the source nothing (WorkCounts::dma_buf_images_taken, docs/HOWTO.md). A texture that renders takes the feedback loop usage where the device makes the image with it, and the storage usage too where the check passed for a shader's writes of texels of its width over that kind of pages (with it a shader writes the texels in place, as one declared to), so a draw that reads it after a render-target barrier reads it through a snapshot (WorkCounts::feedback_loop_alias_images); without the storage usage such a draw splits its pass. The check makes such images of every texel size, small and 3840x2160, over each kind of pages while a CPU thread writes beside their texels, and passes a kind only where every first move kept every byte; for a texture that renders it checks images made with RenderTarget usage apart, through their first move, their moves into the feedback loop layout and back, and a render pass that clears and stores them, while the CPU writes the bytes between their rows and after them; and for one a shader writes, images made with ShaderWrite usage, whose every texel a kernel stores through an unsigned-integer view of 4, 8 or 16-byte texels while the CPU writes the bytes beside them (a program's atomics are among no round), and apart from those, images of 1- and 2-byte texels stored through R8_UINT and R16_UINT views, rows of which end inside a 4-byte word: a driver may store a narrow texel through a wider access, so 1- and 2-byte texels take verdicts of their own, and a byte their rounds changed keeps no wider texel's texture a shadow (a device without shaderStorageImageExtendedFormats leaves them unchecked). Each verdict is given apart for texels that share a line of the device's memory (nonCoherentAtomSize bytes) with bytes beside them and for texels that share none (their first byte, their end and, with bytes between rows, each row's start and end on a line): a device that writes back a texel's line whole puts an older value back over a CPU write in the first alone, as the Iris Xe's clear and store and draws do, so its render targets and written textures whose rows end on a line, a 3840x2160 BGRA8Unorm surface's among them, take the image in place where the others keep the shadow. A kernel's writes of a texture over a buffer's rows (no IOSurface plane's) whose rows, each to its pitch, start and end on a line, its buffer holding the last row to its pitch, may change the rows' padding (section 10, Kernels): the same rounds give a second verdict for such textures, which a round that changed only bytes of its rows' padding passes, so the Iris Xe's written textures over a buffer take the image in place whatever their rows' ends. A texture that renders over host pages whose renders failed for its row ends is a shadow, whatever its rows' padding. The check's copies of a texture's texels into a buffer's rows over each kind of host pages (a blit, as a shadow's copy back writes them, while the CPU writes the bytes between the rows and after them) decide no texture's placement: where they, or a kernel's writes of such texels, changed a byte for rows that end inside a line, or have not answered, a shadow's copy back into that kind of pages is spliced and its merge goes on the host, so the CPU's writes beside its texels stay (section 9, shadowed-texture). Where that kind's copies kept every byte or were not checked, a kind of host pages whose copies changed a byte for those row ends, its reads of them passing, decides it, but only where the check's pages of both lay in memory of a type of the same property flags (VkMemoryPropertyFlags, as the driver reports them: host-cached or not, coherent or not): a copy's line write-back belongs to the GPU's store path into memory of that type, which a kind's rounds see only as often as the CPU's writes race it, and one measured through memory of other flags says nothing of this memory. On the Iris Xe, a buffer copy, a copy of texels into a buffer's rows, a kernel's stores and a pass's clear, store and draws into host memory each write back the whole 64-byte line that holds a row's last bytes (its nonCoherentAtomSize; docs/FAST-PATHS.md, Known gaps), so its render targets over rows that end inside a line are shadows whose copies back are spliced. A byte beside the texels changed under the GPU's stores (a render round's clear, store or draw, or a kernel's stores) in one kind of pages, whose reads of those row ends passed, fails that access and row ends for every kind: the line written back belongs to the GPU's store path, which every kind's images share, while a kind whose pages the CPU maps uncached (ANV maps the dma-buf kind's so) sees it in fewer rounds. Reads, and verdicts a kind could not check, carry to no other kind. So the verdicts are given together once every kind is checked. It runs on a thread of its own, which the first such texture starts; a texture made before its kind of pages and access has its verdict is a shadow, made without waiting for the check (WorkCounts::host_texture_shadows_check_pending), and moves in place, with no copy, at a quiet commit once its kind's verdicts pass (WorkCounts::host_textures_moved_in_place; docs/HOWTO.md says which commits). It runs once per driver and driver version: its verdicts are kept in the shader cache's directory, named by the driver and the check's own version, not the runtime's (a device without one checks once per process), and recalled as the next device is made (WorkCounts::in_place_checks_run, _passed, _failed, _unchecked, _recalled): those it measured, passed or failed, and those it could not check for a cause that lasts for the driver (the device lacks an extension, a feature, an import, a format or an image of the shape). A class it could not check for a cause that may pass (pages or memory not made, an import refused, its writer thread not started, a move or the stores that failed; its reason noted) is checked again by the next device. Such a texture's commands read and write the texels in the memory the buffer's commands read, so a CPU write reaches them as it reaches the buffer's.

Every other texture over host pages is a shadow (shadowed-texture, the notice naming why): under HostPageTexturePolicy::Shadow (DevicePolicy::exact_answers); one a shader writes of texels of a width the check's kernel stores none of (none of 1, 2, 4, 8 and 16 bytes); one made before the check for an access of its answered, or where it failed or made no image; and one no image in place serves (its format or usage the device makes no linear image of, the bytes' pitch, placement or memory, or over dma-buf pages no dma-buf of the texture's own pages, or, where the driver lays a plane at the texels' offset in their page out at another offset, no image of a plane at offset 0 that binds at that offset of an import of the pages: one that requires a dedicated allocation, as RADV's does, or whose memory's alignment does not divide the offset). WorkCounts::host_texture_shadows_* counts each reason apart (the texel width, _store_width), and of them all those whose usage renders into them (_render_target) and those a shader writes (_shader_write). A shadow is an optimal image of the runtime's own memory, whose texels the encoders copy in from the pages before a use and back (merged back: only the bytes the commands changed) after a write; no image is bound to the pages, and Texture::vk_image gives None for it. A shadow whose image the device refused for its format, features or limits, the bytes' pitch or placement, or the dma-buf import (not one the policy, a check or a write's width asks for) still has its bytes in place: a 2D texture of one level, slice and sample, of an uncompressed format and no swizzle, whose rows start on a texel and lie a whole number of texels apart within a buffer that has no read twin, binds its rows as a texel buffer of the buffer's bytes (the pages, or the buffer's copy of them) at a slot whose function only reads, writes or asks its size (section 5, TextureFacts::texel_rows), and those commands copy nothing into or out of the shadow (WorkCounts::texel_rows_textures, texel_rows_bound); a slot that samples it reads the shadow. Such a texture's shadow (not one made before its pages' verdicts, nor one over a heap's buffer) is made at the first reach of its image, not with the texture: a slot that binds the image, a use_resource of it, a render pass's attachment, an execution of commands that inherits its binding, a view, its VkImage handed out (WorkCounts::shadows_left_unmade, shadows_made_at_use). One only ever bound through its rows, or read and written by the CPU and blits, which reach its bytes, makes none, and its resource ID reads the neutral texture until its shadow is made, as a texture that no command named holds nothing a read through its ID could see. Over a buffer with a read twin, a slot that only reads the texture binds the texture's read twin where it has one in place, and the shadow otherwise. A texture in place renders and is written beyond its declared usage, as plain Metal allows, through its usage shadow and an attachment stand-in, whose copies touch its texels alone. Buffer::texture_placement and Buffer::texture_placement_with_iosurface_plane answer, for the arguments of new_texture and new_texture_with_iosurface_plane, where the texture lies if made then (TexturePlacement): in place; Pending, a shadow made before its verdict that moves in place where the verdict passes; a shadow and why (TextureShadowReason: the policy, the texel width, the check's failed or unchecked verdict with its access and row ends, a refusal, a tiled texture's levels, texels past the buffer's length, a device copy, and over the device's own memory rows with bytes between them the buffer does not declare unobserved, of a texture that renders or of a buffer other writers than the device's ordered commands reach, BytesBetweenRows); no host pages (an image aliasing the buffer's memory: the device's linear image where it lays one out as Metal does, else a DRM_FORMAT_MOD_LINEAR image at Metal's pitch where the device's check passed for its pooled memory; a texture over that memory that takes neither answers its shadow's cause); or a shape no image in place takes; Buffer::tiled_texture_placement answers it for new_tiled_texture's. The making's own route answers it (texture/route.rs), after every check the making runs before it makes anything, so the same arguments are refused with the same errors. Where the route is the image in place, the query asks first what the device answers without an image: rows that share bytes, and the format, feature and limit queries the image steps run before vkCreateImage, for every plan the making would try. Where those refuse every plan, that refusal is the answer and no image is made. Otherwise the query runs the image's making up to the bind (texture/in_place_image.rs): it makes the driver's linear image, and the DRM_FORMAT_MOD_LINEAR one where the driver lays the first out at another pitch, checks their requirements against the bytes' place and memory type, and releases them unbound, so a pitch, an image, a placement or rows the device refuses answer Shadow(Refused(..)), the shadow the texture then is. That is one or two VkImages where the declared plan is made in place, and a pair more for each wider plan the making tries first where it is refused; nothing is bound or submitted. Only the bind shows the rest: over pages imported as dma-bufs, the caller's source's dma-buf and the driver's import of it; and memory or a lost device, which fail the making. A pending verdict starts the check, as a texture's making does. Device::settle_in_place_checks starts the check and says when the verdicts are known (a zero timeout waits for nothing). They become known once per VkDevice: a GPU recovery's new one reads them from the record as it is made, or checks again where the lost one's check left none. Device::host_pages_texture_placement answers the same question for a texture new_texture_with_iosurface_plane would make over a no-copy buffer of host pages not made yet (start and length, imported by pointer or as dma-bufs), by the same steps up to the import: where those decide (the shape and the call's refusals, the policy, the texel width, the verdicts for texels laid out from start, texels past length, rows that share bytes, and the device's format, feature and limit queries), its answer is the one texture_placement_with_iosurface_plane gives once the buffer is made; where only an image or the import decides, InPlace. It makes no buffer, import or image. Buffer::new_tiled_texture (Metal's private newTiledTextureWithDescriptor:offset:bytesPerRow:) makes what new_texture makes, and a 2D texture of more than one level, which is a copy of the buffer's rows at the offset and pitch, taken at its first use, as on an x86 Mac (an AMD Radeon Pro 5300M and an Intel UHD Graphics 630 under macOS 26.7.1). Over any buffer such a texture is one image of its own holding every level (shadowed-texture, naming the levels; TextureShadowReason::Mipmapped). The first command of an encoder that uses any of its levels after its making, or after Texture::did_modify_data (Metal's private didModifyData) or a replace_region of its first level, takes the copy before that command: the bytes into its first level, then every later level made from the first as generate_mipmaps makes them for the format: the device's blit chain or the compute filter (device-filtered-mipmaps), or an integer format's texel picks. The copy is taken as that command is encoded and runs in its command buffer's order on the GPU, so it reads the bytes as they are when the command buffer runs. A rebind that encodes the encoder again before its command buffer's first submission (Buffer::rebind_bytes_no_copy) takes the copy in the encoding again where the first encoding took it, its work recorded on the GPU alone (a render pass that executes indirect commands the GPU writes) among it, and a did_modify_data made since is left to the next use encoded. A take whose encoder runs nothing, its command buffer having failed before it ran (committed as failed, a submission that fails, a host step that fails or a vkQueueSubmit the driver refuses) or dropped without a commit, is given back: the next use takes the copy. Work a host step records again after the commit (an execution of indirect commands the CPU wrote since) takes the copy where the commit's recording took it. Between takes no write of the bytes reaches a level, and nothing the GPU writes into a level reaches the bytes or the other levels. get_bytes and replace_region of the first level read and write the buffer's bytes, as the Macs' do, and of a later level the image (an accepted difference, section 10). While the buffer's bytes are detached (detach_backing) it keeps its own image, every level read and written by its commands as before and the later levels by its CPU calls; their calls on the first level are refused meanwhile (NotImplemented(DetachedTexelAccess)), as a one-level texture's are. A format generate_mipmaps leaves as it is or refuses has its first level copied and its later levels left as they are (docs/FAST-PATHS.md, known gaps). A texture of one level is new_texture's, in place where that is. On a discrete GPU (no unified memory), a Managed no-copy buffer is two copies, as Metal keeps a Managed resource on a Mac with a discrete GPU (HostBacking::DeviceCopy): the GPU's own in device-local memory, which every command reads and writes, at the buffer's gpu_address, and the caller's pages, which contents answers. The pages reach the GPU's copy as the buffer is made and at a rebind (whole), each before any command of a command buffer committed after the call, and a did_modify_range's range at the next commit of a command buffer that uses the buffer (its encoders' uses or use_resource name it, or a command reaches memory no use names), before any command of that command buffer, on its queue after the command buffers before it there: the copy in of a later range never lands under an earlier command buffer still to read the buffer. A commit of a command buffer that uses none of the buffer leaves the range for the next that does. By default (DevicePolicy::managed_copy_in = ManagedCopyInPolicy::AtSubmission) the GPU copies the range from the pages' import as that command buffer's submission runs, with no copy on the CPU: a CPU write of the range after the commit, before the GPU runs the command buffer, may be read, as on an Intel UHD Graphics 630 (one copy, macOS 26.7.1), where an AMD Radeon Pro 5300M (two copies) read the bytes at the commit. ManagedCopyInPolicy::AtCommit, which exact_answers() selects, takes the 5300M's answer: the commit copies each range on the CPU into staging buffers of host-cached system memory, a cost of the range's bytes, and a write after it reaches no command buffer committed before it, however late the GPU reaches it (docs/FAST-PATHS.md). Pages no import of their own maps are staged so at the commit under either, but where a guest RAM's chunk imports hold them all (HostRam): there the default copies them by the GPU from those imports, as from an import of their own (WorkCounts::managed_bytes_copied_in_from_ram). Under the default, a range of at most 16 KiB whose start and length are whole words is not copied: the submission reads it from the host copy as it is recorded and writes it in its command stream (vkCmdUpdateBuffer, WorkCounts::managed_ranges_inlined). On a device that orders its batches by their ends (RADV, NVIDIA's driver, ANV), a batch whose first work is such uploads alone records no barrier of its own before them: the end of the batch before it on its VkQueue already orders every earlier command ahead of them (WorkCounts::managed_uploads_unbarriered). The barrier after them makes them visible to the stages and access types the batch's own commands use those buffers in, not to every later command, where the batch's uses of each are known: the batch's end orders every later batch (WorkCounts::managed_upload_barriers_narrowed). A CPU write that no did_modify_range names is not seen by the GPU. A blit encoder's synchronize_resource copies the GPU's copy out to the pages in its command buffer's order, which the CPU sees once the command buffer completed: the bytes the GPU's tracked writes reached since the buffer's last copy out, in the GPU's order across command buffers and queues, the range whole where those are not known (an untracked buffer, an exported one or one whose VkBuffer was handed out, its first synchronize, a command buffer that may write memory no use names, WorkCounts::managed_synchronizes_whole). Every other byte of the pages already holds what the GPU's copy holds, so a byte the CPU wrote that the GPU did not keeps the CPU's value. The copies run from an import of the pages where the device makes one (never a copy of them), or from the chunk imports of a guest RAM that hold them, else through staging buffers the runtime frees once their work completed, at most 256 MiB staged ahead (WorkCounts::managed_*). A texture over the buffer's bytes is over the GPU's copy and follows it, its replace_region copying in and its synchronize_resource or synchronize_texture copying out. Over pages the process maps read-only, the GPU's writes are dropped: nothing is copied out, and the pages are copied in again at the completion of each command buffer that used the buffer. A detach keeps the GPU's copy. A detached no-copy buffer's contents, of either kind (and a detached no-copy heap's buffers'), answers the caller's pointer of the pages it lay in last, as Metal's does, until a rebind gives it new ones; the runtime reads and writes nothing through it meanwhile. Where device-local memory has no room for the GPU's copy, the buffer lies in its pages as a Shared one does (device-memory-overflow). A Shared no-copy buffer, and every no-copy buffer on a device with unified memory, lies in the caller's pages, which the GPU of a discrete device reads across the bus, as a discrete Mac's GPU reads them. A Managed texture over a no-copy buffer's bytes that lie in its pages there (not an IOSurface plane's) that only samples or reads, whose policy takes the image in place, over memory that carries a log of its writes (HostMemory::with_dirty_pages), tracked, one slice laid out as one copy, is instead a device copy (WorkCounts::device_copy_textures, whatever the check answered): the GPU's copy of the two a Managed resource is on a Mac with a discrete GPU, a shadow whose copies in take only the bands of rows the log reports changed (dirty_copies_in_gated and kin). Its notice is not announced: it holds the bytes wherever a command reads it. A Shared texture and an IOSurface's are the pages' alone there too, in place where the check passed, which the GPU reads across the bus as a discrete Mac's GPU reads them. A texture placed in a heap over dma-buf pages is an image over a dma-buf of its own pages, which its first submission acquires from VK_QUEUE_FAMILY_FOREIGN_EXT; a linear image over a buffer of the runtime's own memory starts VK_IMAGE_LAYOUT_PREINITIALIZED, and its move from there keeps its bytes. FAST-PATHS.md's costs and known gaps state what this costs and differs from Metal in.

MTLResourceOptions bit 20 (0x100000, ResourceOptions::BIT_20) is an option no Metal header names, whose meaning Metal does not state; programs pass it with a buffer's options (0x100010 for a Managed no-copy buffer). ResourceOptions::from_raw takes it, and nothing in the runtime reads it. Measured on an M3 Max under macOS 27.0.1 and an AMD Radeon Pro 5300M under macOS 26.7.1, plain and under API validation (crates/metal2vulkan-conformance/probes/resource_option_bit20.m), the runtime following both halves:

  • a buffer of a length, of bytes or over the caller's pages (newBufferWithBytesNoCopy:), of every storage mode, is made with it and reports its options without it; so are a heap and a heap's buffer (the M3 Max; Metal's API validation stops the heap's buffer, "unknown bits 0x100000"). The runtime makes each as without it;
  • a texture descriptor with it ends Metal's process (its suballocator asserts, "Different MTLResourceOptions used for the same heap index"): the runtime refuses it (Invalid, Problem::UndefinedValue), as it refuses bit 24 there.

2. A library

Library::parse takes a metallib, a bitcode wrapper or a raw AIR module; Library::from_air takes the last two. LLVM text is not an input: assemble .ll with llvm-as first. Listing functions decodes nothing.

let sampling = Library::from_air(&fixture_bitcode("sampling")?)?;
for info in sampling.functions() {
    println!("library: {} ({:?})", info.name, info.stage);
}
  • library.function(name) finds a function like newFunctionWithName:; a missing name is Error::InvalidDescriptor(EntryNotFound).

  • A metallib function's info.air_hash is the SHA-256 of its bitcode, its content key. In every library but a Core Image kernel library it is the function's HASH tag, checked against the bitcode: a mismatch is InvalidInput(Container(HashMismatch)), though Metal checks no HASH and loads such a library. A Core Image kernel library (file type 1, metallib -cikernel) lists its kernels as extern functions (FunctionStage::Extern, no stage) over one module, and Apple's toolchain writes them a HASH that, for some modules, is not that module's SHA-256 (what it digests is not known); Core Image's own libraries are such. Its HASH is read as 32 bytes and kept as read, and air_hash is the module's SHA-256, computed. The conformance crate's probes/metallib_function_hashes.m measures what Metal answers for both kinds of library.

  • function.reflection(&budget) answers as reflectionForFunctionWithName: does: the function's arguments in declaration order with their types, access, indices and use, in Metal's shape (module reflection). It is None for a metallib function whose library carries no reflection, where Metal answers nil. An argument whose Metal answer was not measured is Unsupported(Feature::Reflection).

  • A pipeline descriptor's reflection(&budget) answers what the reflection: out-parameter of Metal's creation call does.

  • A pipeline descriptor's slot_writes(&budget) answers, per stage, what the function may store through the object bound at each slot its arguments bind (SlotWrites, one SlotWrite per binding). SlotWrite::may_write(slots, binding_type, index) answers for one slot: SlotWritability::Never where the declaration is read-only (a constant or const device buffer, a texture declared access::read or access::sample, a sampler, a function table, an acceleration structure, an imageblock, a mesh function's payload) and for a slot no argument binds, Maybe where it is write-only or read-write, and Unknown(SlotWriteGap) for a slot that one argument alone leaves undetermined.

    The values are the ones reflection gives as Binding::access, worked out without the type description a reflection must also give. That is why a state that compiles always answers here, while its reflection is refused where Metal's answer for one argument's type was not measured, and why uncertainty stays on the slot it belongs to instead of refusing the state: a caller asking whether a read-only buffer may sit at a slot gets an answer per slot, and an undetermined slot reads as neither writable nor read-only.

  • function.argument_buffer_layout(index, &constants, &budget) gives the layout of the argument buffer the function takes at a buffer index, as newArgumentEncoderWithBufferIndex: encodes it: its length, alignment, and each argument's offset and type by [[id(n)]]. ArgumentBufferLayout::from_descriptors and from_buffer_binding give the layouts of Metal's other two encoder constructors. Each argument is 8 bytes: a buffer's address plus offset, or a resource ID.

  • function.properties(&budget) answers what MTLFunction states about the function.

One entry of a bare module

A tool that holds bitcode and an entry name, not a library, compiles through the profile:

let bitcode = fixture_bitcode("sampling")?;
let entry = EntryDescriptor::new(&bitcode, EntryRef::Name("sample_level"));
let profile = device.profile();
let (compiled, report) = profile.compile_entry(&entry, &LoweringInputs::new(), &budget);
let alone = profile.link_standalone(&compiled?)?;

link_standalone links the function with no partner stage. The report says what the compile cost against its budget, whether it succeeded or not.

3. A compute pipeline

Descriptors mirror Metal's. Each stage is a StageSource: a FunctionDescriptor to compile (a function, its constant values, the functions it links) or a CompiledFunction to link as it is. Every compile takes a Budget:

let cancel = CancelToken::new();
let mut budget = Budget::standard();
budget.cancel = Some(cancel.clone());
let kernel = FunctionDescriptor::new(sampling.function("sample_level")?);
let descriptor = ComputePipelineDescriptor::new(StageSource::Function(kernel));
let pipeline = device.compile_compute_pipeline(&descriptor, &budget)?;

Budget::standard() is a 20-second deadline. cancel.cancel() from any thread ends the attempt at its next poll point with Error::Cancelled; a passed deadline is Error::Budget. Both are transient. Deterministic caps (work units, a memory ledger, structural limits) apply whatever the budget, and exceeding one is Error::LimitExceeded, permanent for that input.

A ComputePipeline is immutable plain data:

  • stage: a StageModule (SPIR-V 1.5 words valid for the device, the entry point, specialization constants, a required subgroup size and stage flags, precision notes, private_bytes, the private memory a thread keeps, as StageInterface::private_bytes states it too, and stats, what the module contains);
  • layout: the pipeline layout, dense and complete; create it as it is;
  • interface, dependencies: what it binds and what bind-time state it depends on (section 5);
  • metal_info: answers to Metal's per-pipeline queries (maxTotalThreadsPerThreadgroup, ...);
  • requirements: what the device must have enabled.

Do not create the compute VkPipeline from stage alone: its specialization defaults are placeholders (a kernel's local size is 1). Create each pipeline from a planned dispatch's DispatchRegion (section 6), with the region's specialization, stage_flags and required_subgroup_size. A required subgroup size needs subgroupSizeControl and the stage in requiredSubgroupSizeStages; full subgroups need computeFullSubgroups. A pipeline compiled for one device pins only what that device can take; DeviceProfile::check tells whether another device can.

A kernel whose simdgroups run on 32-lane subgroups pins a required size of 32 with full subgroups. On a device whose compiler chooses a kernel's SIMD width between a minSubgroupSize below 32 and a maxSubgroupSize of 32 (ANV), that pin compiles the kernel in the device's widest mode, where each lane's value takes four times the registers of the narrowest one. A kernel whose entry, inlined, holds more than 256 AIR instructions and whose values are estimated to hold more than 36 32-bit words at once (live intervals over the body in layout order, a value read in a loop held to the loop's end) takes the emulated simdgroup tier there instead: each simdgroup is 32 consecutive threads, its operations and lockstep barriers go through workgroup memory and workgroup barriers, and its module pins no subgroup size, so the driver chooses the width. Both forms are exact. The runtime counts such kernels (WorkCounts::widest_pin_kernels_emulated). A kernel the emulated tier refuses (a 64-bit exchange, or a scratch that does not fit beside its threadgroup memory) keeps the pin.

The bounds come from an authored kernel measured on an Iris Xe (RPL-P, ANV): S steps, each a branch on one of K live float accumulators whose arm stores a device word and loads the next (a lockstep pair in divergent flow, so a subgroup barrier there), with P 1 the arm's accesses going through a pointer it loads from memory (a resident-set search a step), then every accumulator updated. Pressure, not size, separates the cases. The driver's compile time (vkCreateComputePipelines) and the GPU time of a dispatch of 12,288 threads, pinned and emulated, one run each (compile times varied up to twice between runs):

P K S AIR instructions estimated words compile ms, pinned emulated GPU ms, pinned emulated
0 16 128 7,850 24 589 559 0.129 0.159
1 4 32 874 34 783 766 0.010 0.018
0 32 64 7,050 40 6,652 282 1.061 0.107
1 16 16 1,042 46 971 300 0.070 0.015
1 16 64 4,066 46 11,987 2,585 0.319 0.074
0 48 8 1,362 56 458 38 0.168 0.021
1 48 32 5,186 78 25,799 1,277 1.985 0.081

At 34 estimated words or fewer the two compile alike and the pinned kernel runs as fast or faster; from 40 the pinned compile took 1.6 to 24 times the emulated one and its GPU time 1.5 to 25 times. At or below 256 instructions every pinned compile measured took at most 102 ms. Answers were the same bits on both tiers. The estimate costs time linear in the body: 5 ms of a 3.4 s release translation of a 162,914-instruction kernel.

On the emulated tier, a simdgroup operation or barrier in a block whose control flow differs between threads is walked predicated: each thread carries a live flag, the threads that do not run the block take part in its exchanges as inactive lanes, and a loop that holds one votes on its exit. A kernel whose threads' positions alone make such a block differ, along some axes (thread_position_in_threadgroup or thread_position_in_grid, read by lane), states RuntimeFact::UnitAxes { axes: 0, relief }: relief holds, at bit m - 1, each mask m of axes (bit 0 x, bit 1 y, bit 2 z) under which fewer of those blocks differ once the positions along them are taken as uniform. In a threadgroup of one thread along an axis, Metal's threads_per_threadgroup is 1 there, so every thread's thread_position_in_threadgroup on that axis is 0 and its thread_position_in_grid is its threadgroup's position, partial threadgroups included. BindingPlan::unit_axes_variant(&dispatch) offers a dispatch of such threadgroups, where its axes are among the masks of relief, the kernel's unit-axes variant (VariantKey::unit_axes, which LoweringInputs::unit_axes compiles): the same kernel with those positions uniform, walked without the predication they caused, giving the same answers. Its plan states UnitAxes { axes, relief: 0 } and sends a dispatch with more than one thread along one of its axes back to the variant without them (BindError::NeedsVariant). A kernel has at most seven such variants per variant it runs on, one per mask. metal2vulkan-runtime begins the variant on its pipeline pool at the first dispatch it is offered to, and runs that dispatch and the next ones on the plain variant until the variant's translation and its regions' VkPipelines are made, so no dispatch waits for it (WorkCounts::unit_axes_variants_begun, unit_axes_meanwhile, unit_axes_dispatches). On the Iris Xe, an authored kernel of four shuffles each way and a simdgroup sum in a loop of 8 to 11 trips, in threadgroups of 8 x 1 x 16, ran 1.14 to 2.16 times the GPU time predicated (its trip count read from thread_position_in_grid.y) as with the same trip counts read from threadgroup_position_in_grid.y, over four sizes from 46 to 126 estimated words (one run each), with the same bits.

What the module contains

Every stage states the size and shape of its module, counted by the verifier that runs on every translation, in every build: stage.stats, a ModuleStats. A function compiled on its own states the same counts as module_stats(), before it is linked. Reading them is how a caller watches the size of what it hands a driver, and what in it grew.

let stats = pipeline.stage.stats;
println!(
    "{} blocks, {} instructions",
    stats.blocks, stats.instructions
);
assert!(stats.reachable_blocks <= stats.blocks);
  • blocks and instructions are the module's size: a larger module costs more to compile on the drivers measured. Canonicalization inlines every direct call before the module is emitted, so they count the whole program, not one function.
  • functions -- the entry point and the functions left beside it -- says how far blocks stands for that program. A driver inlines before it charges, so a module of few functions is one whose blocks are the program's, while a module that calls a many-block function from many sites holds a program far larger than its own blocks; the two read alike in blocks alone. Lowering emits such functions itself: the handle-table search (unrolled branch-free steps) and the root-table search (a loop), each emitted once and called at every access.
  • Compare one module against the next of the same shader, not one shader against another. Measured cost per block differed several-fold between a synthetic module and a real workload, so a per-block figure taken from one shader predicts nothing for the next; instructions is the second number for that reason.
  • constructs (selection, switch and loop headers) and loops say whose blocks those are. Translation adds blocks of its own -- inlining, and the structurizer's layout of control flow as SPIR-V requires -- and the input has blocks of its own. The structurizer makes no loop the input does not have, so a blocks that has risen while loops holds still is translation's work or a changed shape of the same control flow, not new control flow in the shader.
  • reachable_blocks is a bound, not a lever. It is never above blocks, and below it by the merge blocks SPIR-V requires a construct to declare that no path reaches -- both arms of a conditional inside a loop leaving the construct, say -- which the module terminates with OpUnreachable. The difference is blocks the driver still reads and no invocation runs.
  • The AIR side of the comparison is yours, through metal2vulkan-air. For the counts the input itself holds, before inlining, decode it and count the blocks of each function's body (metal2vulkan_air::decode, then each ir::Function's body); for the ones canonicalization produced, walk the entry DeviceProfile::specialized_entry gives, which is that AIR specialized and canonicalized. A decoded function's ir::InstKind::Call sites give each callee's call count, which is what turns its own blocks into the program inlining will make of it.
  • inert says the module holds no loop and that no instruction of it writes memory other than an invocation's own and its workgroup's (Function, Private and Workgroup storage), writes an image, or emits or drops an output of its stage. Every invocation of such a module ends and leaves nothing behind, so a dispatch of an inert kernel computes nothing anyone can read: metal2vulkan-runtime records no Vulkan dispatch of it. The command buffer still uses what the dispatch binds, as Metal's does: a Managed buffer's ranges named by did_modify_range are copied in by that command buffer, not by the next one that reads them. An instruction the check does not classify as reading or computing alone (an interlock, a ray query) makes a module not inert.

The counts are of the module spirv holds: the verifier counts the module it checked, and serialization and relocation assign link numbers without adding or removing an instruction. They are part of the encoded artifact, so a cache hit states them too, and they are left out of content_digest, which already covers the words they describe.

A kernel with [[stage_in]]

A kernel's [[stage_in]] attributes are fetched in the shader, as Metal does. The compile asks for the stage-input descriptor it needs, and you supply it:

match device.compile_compute_pipeline(&descriptor, budget) {
    Err(Error::NeedsInput(RuntimeInput::StageInputDescriptor { attribute })) => {
        let mut stage_input = StageInputDescriptor::new();
        let fetch = StageInputAttributeDescriptor::new(AttributeFormat::Float, 0, 1);
        stage_input.attributes.insert(attribute, fetch);
        let mut layout = StageInputLayoutDescriptor::new(Some(4));
        layout.step_function = StepFunction::ThreadPositionInGridX;
        stage_input.layouts.insert(1, layout);
        descriptor.stage_input = Some(stage_input);
    }
// ...
let mut inputs = LoweringInputs::new();
inputs.stage_input = descriptor.stage_input.clone();
let compiled = device.compile_function(&kernel, &inputs, budget)?;

A fresh StageInputLayoutDescriptor steps per vertex at rate 1, as a fresh Metal layout does. A layout stride of None is MTLBufferLayoutStrideDynamic: the stride comes from the encoder.

A kernel that takes a patch control-point input (air.patch_control_point_input, the input of a post-tessellation vertex function) is refused, InvalidInput(Abi(UnknownKey)) at that argument and key. Metal's compiler writes that input for no kernel, and Metal makes no compute pipeline of a kernel that takes one: on an M3 Max under macOS 27.0.1 it makes the library and the function, then fails the pipeline with "Internal compiler error." under every compute step function. A kernel reads vertices by index through [[stage_in]] under a stage-input descriptor (one element per thread), or through buffer arguments it reads at any index.

Other compute features

  • Visible functions and recursion. Linked visible functions, function tables and intersection function tables compile; recursion through visible functions runs on a stack of frames sized by max_call_stack_depth. A call that finds the stack full returns zero.
  • Linked functions: names and constants. A visible-function reference resolves to the linked function whose LinkedFunction::name it names: its specialized name where it was made with one (with_specialized_name, Metal's MTLFunctionDescriptor.specializedName), else its library function's own; its body is still that library function's. A linked function whose module declares function constants is specialized with its own values before it is linked, its module's static initializer run over them. A function made specialized (LinkedFunction::specialized: with constant values, or by newFunctionWithDescriptor: with or without them) reads a constant it was given no value for as an entry's undefined constants read (section 10, "Function constants"). One made unspecialized (newFunctionWithName:) that reaches one of its module's constants refuses the pipeline at a call that survives specialization, DescriptorError::LinkedFunction with LinkProblem::UnresolvedConstant { index }, guarded by is_function_constant_defined or not, as Metal fails the creation ("cannot lower module with unresolved function constants"); one that reaches none links. The specialized name and the specialization are part of the compile key. A reference resolves against functions and private_functions (LinkedList::resolves_references), never against binary_functions, whose functions only a visible-function table calls: a reference only a binary function names is NeedsInput(LinkedFunction), as Metal fails the creation ("unresolved visible function reference"). Two different functions of one name, one in functions and one in binary_functions, are two functions a table holds, each with its handle, and the reference calls the one of functions, as Metal links them.
  • Linked functions: types. A reference resolves to the linked function of its name whatever the definition's type is, and Metal makes every such pipeline (the probe linked_function_signatures.m, an M3 Max under macOS 27.0.1). The call passes its arguments by position: one past the definition's last parameter is dropped, and a parameter past the reference's last argument reads zero. An argument of another plain-value type (an integer or floating-point scalar or vector, a bool as one bit) passes its bits: all of them at the same width, its low bits to a narrower parameter, its bits with zeros above to a wider one. The result passes back the same way; a definition returning nothing returns zero, and a reference returning nothing drops the result. A struct a [[visible]] function takes by value reaches it as its fields, so a reference passing the fields one by one is passing it. A pointer for a value or a value for a pointer, a pointer of another address space, and an aggregate of another type refuse the pipeline at a call that survives specialization, Unsupported with Feature::Linking (section 10, "Linked functions").
  • Stitched functions. A function Metal's stitcher made (newLibraryWithStitchedDescriptor:) links like any other visible function, in functions or in privateFunctions: hand the stitched library's bytes to Library::from_metallib, and link its function. Each stitched function is a module of its own whose !air.signature describes the graph it was made from; the module's own code, the graph's nodes inlined, is what is linked. The translator makes no stitched library itself. A module whose linkage signature has no reading (a linked-constants signature on a module that still declares function constants) refuses the pipeline at a call that survives specialization, Unsupported with Feature::Linking.
  • Threadgroup memory. No threadgroup memory access is contained: a load or store, atomic, memory intrinsic, pointer cell or imageblock access of a threadgroup arena, and a typed threadgroup object's index, run as the program states them, and one past the memory is undefined, as in Metal. A kernel whose every threadgroup access is a whole, aligned float (a scalar or a vector of two to four), with no atomic, memory intrinsic, imageblock or pointer kept in it, and whose SIMD groups are not emulated, holds its threadgroup memory as a Workgroup array of float: each access is one typed load or store a lane, with no branch and no bitcast, at the word offset / 4 and the words after it. The array is the memory's own words (the static part and the specialized [[threadgroup(n)]] lengths), at least four: the memory Metal allocates, so its threadgroup memory is Metal's static length and lengths, and a length filling the limit runs. The strategy census names its accesses access.threadgroup.load.floats and access.threadgroup.store.floats. Every other kernel holds u32 words.
  • Threadgroup memory before the program writes it. A function's threadgroup memory reads zero until the program writes it: the Workgroup variables that hold it, its threadgroup arena (declared threadgroup variables, [[threadgroup(n)]] arguments and an explicit imageblock) and its typed threadgroup objects, have a null initializer, in every threadgroup of every dispatch. That needs shaderZeroInitializeWorkgroupMemory, which Vulkan 1.3 requires; a function that uses threadgroup memory on a profile without it is Unsupported with Feature::ZeroedThreadgroupMemory. The translator's own Workgroup words have none: an emulated SIMD group's exchange scratch and vote word, an object function's mesh grid, a mesh function's primitive count and staged indices, an emulated object or mesh function's payload, and those of the binder's own scan, shadow-merge and index-rewrite kernels. Each is written before any read of it, and an object function's payload "is assumed uninitialized at the entry of the object function" (the Metal Shading Language Specification, the payload attribute). Metal's documents give threadgroup memory no first contents: MTLComputeCommandEncoder.h's setThreadgroupMemoryLength:atIndex: reads "Set the threadgroup memory byte length at the binding point specified by the index. This applies to all compute kernels.", Apple's page for it "Configures the size of a block of threadgroup memory." and points to the specification's section 4.4, which says "Threadgroup variables in a kernel, mesh, or object function only exist for the lifetime of the threadgroup that executes the kernel." and nothing of what they hold first. An Apple M3 Max under macOS 27.0.1 reads zero there, a declared array and a [[threadgroup(n)]] argument alike, in the later threadgroups of a dispatch of 2048 threadgroups of 16 KiB each, many more than its cores hold at once, and in a second dispatch (the conformance case compute-threadgroup-memory-reads-zero); recorded programs read entries of it they have not written.
  • Binary functions, required threadgroup sizes, buffer mutability. Whether a binary function was compiled to a binary (LinkedFunction::precompiled), required threadgroup sizes and buffer mutability change no translation and are in no compile key; the runtime checks them as Metal does.
  • Dynamic libraries. DynamicLibrary::new(library, &budget) checks a dynamic metallib as Metal's newDynamicLibrary: does; pipelines link its exported functions.
  • OpenCL C kernels. Metal compiles OpenCL C (newLibraryWithSource with the compile options' sourceLanguage 1, which the GL renderer's compute path uses), naming each kernel __entry_<name>, and its AIR has shapes MSL's does not:
    • A helper left out of line that passes its parameter on as an intrinsic's immediate operand: OpenCL C's barrier(flags) passes its flags to air.wg.barrier, and mem_fence(flags) computes air.atomic.fence's flags from them with llvm.bitreverse.i2. Each inlined copy reads its own call site's constants, folded through the integer arithmetic between them. An immediate that is still not a constant after that is InvalidInput(Intrinsic(ImmediateNotConstant)) at the call. llvm.ctpop, llvm.bitreverse, llvm.bswap and the scalar llvm.umin, llvm.umax, llvm.smin and llvm.smax are folded over constants, on a width no SPIR-V type has (i2) too; an integer llvm.* operation on such a width that is not folded is refused (Lowering(Arith)).
    • An argument passed by value (a kernel's scalar, vector or struct parameter, air.constant): the entry reads it from a constant-space pointer at its location, so it is a read-only constant buffer holding its own bytes, bound with set_bytes or a buffer at an offset. The reflection lists it as such a buffer of its own data type, size and alignment, a struct as Struct with its members, as the M3 Max answers: float k is Float, 4 bytes aligned to 4, and struct { float a; int b; } is Struct, 8 bytes aligned to 4.
    • A required work-group size (reqd_work_group_size(x, y, z), air.work_group_size) caps the pipeline's max_total_threads_per_threadgroup at x * y * z threads, as the M3 Max answers (64 for (64, 1, 1)). A dispatch in smaller threadgroups runs, as it does there.
    • OpenCL mode. Metal makes a pipeline of such a kernel only with ComputePipelineDescriptor::open_cl_mode_enabled (openCLModeEnabled, Apple SPI), and the crate compiles the kernel as Metal links it then (LoweringInputs::open_cl_mode, part of the key). Three hidden buffers come before the kernel's own: __global_offset_and_num_dims at index 0, four uints the dispatcher fills with the dispatch's global offset in each of its dimensions and its dimension count, __printf_buffer at 1 and __image_order_data_type_table at 2. Each argument the kernel binds at a buffer index sits 3 past its own; threadgroup memory (__local), textures and samplers keep theirs. The reflection lists the kernel's arguments at those indices, then the three buffers (read-only uint 4 bytes, read-write char 1 byte, read-only uint 4 bytes), each used, as the M3 Max answers. OpenCL C's work-item functions read the dispatch: get_global_id(d) is the thread's position in the grid plus the offset in d, get_global_offset(d) and get_work_dim() read buffer 0, get_local_id, get_group_id, get_local_size, get_global_size and get_num_groups are the built-ins of those names, and a dimension the kernel reads from its data selects among the three. A dimension past 2 answers OpenCL's 0 for an id or an offset and 1 for a size or a count. A compiled kernel serves only a pipeline of the mode it was compiled in (RuntimeFact::OpenClMode, InvalidDescriptor(OpenClMode) otherwise). Without the mode Metal refuses the pipeline ("Internal compiler error"); the crate compiles the AIR as Metal AIR, its buffers at their own indices, and refuses a read of get_global_offset or get_work_dim (Unsupported with Lowering(Dispatch)).
    • Images in OpenCL mode. get_image_channel_order(image) and get_image_channel_data_type(image) (air.get_channel_order_texture_<kind> and air.get_channel_data_type_texture_<kind>, Query::ChannelOrder and Query::ChannelDataType) read the third hidden buffer as it holds them: word 2t + 1 for the order and word 2t for the data type of the image at texture index t, as an M3 Max (macOS 27.0.1) and a Radeon Pro 5300M (macOS 26.7.1) answer. Metal refuses the queries of a buffer or a depth image, and the crate decodes none (UnknownIntrinsic); without the mode it refuses each query (Unsupported with Lowering(Texture)). Apple's OpenCL binds a 2D texture of height 1 for an image1d_t, which the AIR declares texture1d, and a 2D array texture of height 1 for an image1d_array_t (texture1d_array). In the mode the kernel's slot is that texture's type (TextureType::Type2D, Type2DArray), and each read, sample and write of the image, get_image_width and get_image_array_size is the 2D texture's at row 0 (a sampled coordinate at the row's centre), as both Macs answer. A real 1D texture bound for an image1d_t, or a 1D array texture for an image1d_array_t, which Apple's OpenCL never binds, takes the kernel's variant that declares that slot as the 1D texture (RuntimeFact::OpenClLineTexture, VariantKey::open_cl_lines): each read, sample and size query answers the 1D texture's values, of the layer an array access names, as a Radeon Pro 5300M (macOS 26.7.1) answers (an Intel UHD Graphics 630 reads layer 0 of the array, an M3 Max texel 0 at every coordinate). Apple's OpenCL binds an image of most channel orders as a swizzled view (on an M3 Max, macOS 27.0.1, with CL_UNORM_INT8: CL_R, CL_RG, CL_A, CL_RA and CL_INTENSITY as R8Unorm or RG8Unorm views, CL_BGRA, CL_ARGB and CL_RGB as RGBA8Unorm views). A read (with a sampler or without) answers the swizzled texel, a write stores it with the swizzle undone (each channel from the first lane whose source it is), and a query answers the view's size and the hidden buffer's words, which no swizzle reaches, as plain Metal answers for the same view; the order is never applied twice. A storage slot the kernel only queries binds the texture's view with no swizzle. The reflection states each image argument as the texture bound for it, an image1d_t TextureType::Type2D and an image1d_array_t Type2DArray, of data type DataType::None (the AIR names its component unknown) whatever the kernel reads it as, as an M3 Max (macOS 27.0.1) answers for 1D, 1D array, 2D and 3D images read as float, int, uint and half, written, only queried and unused.
    • OpenCL C's native_<function> and half_<function> of float types (air.native_<stem>.<type> and air.half_<stem>.<type>, for cos, exp, exp10, exp2, log, log10, log2, powr, rsqrt, sin, sqrt and tan, scalar and of every vector width) are the function's fast form, as fast::<function> is (Precision::Fast). OpenCL C leaves their precision to the implementation, and Metal's devices differ: native_powr(100, 0.5) is 0x1.400002p+3 on the M3 Max and 0x1.4p+3 on the Radeon Pro 5300M.
    • OpenCL C's vector data functions (vload<n>, vstore<n>, vload_half[<n>], vloada_half<n>, vstore_half[<n>][_<rounding>] and vstorea_half<n>[_<rounding>], which the compiler spells air.vload[a][_half].<space>.<type> and air.vstore[a][_half].<space>[.<rounding>].<type>, VectorData) read and write n elements at p + offset * n (offset * 4 for vloada_half3 and vstorea_half3), each at its own element's alignment, in every address space and of every element type the compiler spells. vload3 of a uint pointer one element past a buffer's start reads the three words that follow, as the M3 Max, a Radeon Pro 5300M and a UHD Graphics 630 (macOS 26.7.1) do. vstorea_half3 writes three halves of each four, as the M3 Max and the UHD Graphics 630 do (the Radeon Pro 5300M's writes the fourth too). The half forms widen each half read to float and narrow each lane stored to half; a store's rounding is an accepted difference (section 10, Conversions).

4. A render pipeline

let mut vertex_descriptor = VertexDescriptor::new();
let layout = VertexBufferLayoutDescriptor::new(Some(24));
vertex_descriptor.layouts.insert(0, layout);
// ...
let mut descriptor = RenderPipelineDescriptor::new(StageSource::Function(vertex));
descriptor.fragment = Some(StageSource::Function(fragment));
descriptor.vertex_descriptor = Some(vertex_descriptor);
let color = ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm);
descriptor.color_attachments[0] = Some(color);
// ...
let pipeline = device.compile_render_pipeline(&descriptor, &Budget::standard())?;

A RenderPipeline holds:

  • stages: vertex, then fragment when rasterization is enabled, with three geometry stages before the fragment stage when the fragment function reads [[barycentric_coord]] on a device without fragmentShaderBarycentric, or the vertex function selects its slice or viewport on a device without the output (below). A VkPipeline takes the stages RenderPipeline::runs_stage(at, topology) says its topology runs;
  • layout: one pipeline layout for every stage;
  • vertex_input: Vulkan bindings and attributes. An attribute Vulkan cannot fetch as described is pulled in the shader instead, and so is every attribute on a device without robustBufferAccess (unless containment is off). A FloatRGB9E5 attribute is pulled on every device: no device must fetch the shared-exponent format as vertex input, and its decode is exact, so the shader's is the answer a conformant fetch gives. Under the identity domains nothing is pulled, as the pulled fetch reads through a descriptor: every attribute is fetched in fixed function, with or without buffer robustness (a fetch outside its buffer reads what the device gives), an unnormalized signed-integer format into a variable declared int, the constant step at vertex rate on a binding of stride 0 (no divisor); an attribute fixed-function input cannot take is refused, Unsupported{VertexStepRate} (a per-instance rate above 1, naming the missing vertexAttributeInstanceRateDivisor or the maxVertexAttribDivisor it passes; a device that lacks only supportsNonZeroFirstInstance takes the divisor, and the consumer refuses each draw through it at a base instance other than 0), Unsupported{Format} (a format the device cannot fetch as VERTEX_BUFFER, and FloatRGB9E5) or Unsupported{VertexInputLayout} (an offset or stride off the format's alignment or past the device's limits, more attributes or layouts than its limits, or the constant step's stride of 0 under the portability subset);
  • graphics: the fixed-function state (topology, attachment formats and blend states, sample count, dynamic states, input attachments, ...). Build VkPipelineColorBlendStateCreateInfo::pAttachments from graphics.color_blend_attachments().

Where Metal's rules differ from Vulkan's, the pipeline gives Metal's answer:

  • A color attachment no fragment output names keeps its texels (an empty write mask).
  • What Metal refuses, the link refuses as InvalidDescriptor(ColorAttachment): an output with fewer components than its attachment's channels, a blend that reads the second output without the first, alpha to coverage over an integer attachment 0. Function-constant values that put two outputs at one attachment are InvalidDescriptor(DuplicateColorOutput), and values that put two arguments of one argument table (buffer, threadgroup memory, texture or sampler) on overlapping slots are InvalidDescriptor(OverlappingArgument), naming the later argument, of any stage: Metal refuses both when it makes the function.
  • ColorAttachment's metal is how plain Metal answers the pipeline (measured on an Apple M3 Max under macOS 27.0.1): MetalAnswer::NilWithError, nil and an NSError (code 3), for an output or color input of another numeric class than its attachment, an output with fewer components, a blend of the second source without both outputs, and a color input or tile imageblock member of an attachment without a format; MetalAnswer::EndsProcess, Metal's descriptor validation asserting, for a blend into a bfloat attachment and for alpha to coverage over an integer attachment 0. A layer that answers as Metal does ends the process only for the second.
  • On a device without independentBlend, attachments the function does not write copy the blend state of those it does; where those differ the pipeline is refused, naming the feature.
  • A packed 16-bit attachment (A1BGR5Unorm, ABGR4Unorm, BGRA4Unorm) of a format the device samples but does not render (the RTX 5080) renders through an R16_UINT view of its texture (metal::format::WordAttachment, LoweringInputs::word_colors): the fragment function writes the word Metal stores and graphics gives the attachment that format; a pass clears it to the word of Metal's clear. Exact, for a write unblended (or blended one and zero); under a mask of some of its channels the function merges the word into the texel in the interlocked storage form (a GraphicsState::storage_attachments entry of R16_UINT) where the device orders fetch through the pixel interlock. Blended otherwise, there too the function computes Metal's blend of a half4 or float4 output over the word it reads, within one code of Metal's (PrecisionNote::DeviceColorConversion: the attachment holds codes where Metal's tile holds a clear's or an earlier blend's result in the pass as a half, and under fast math Metal sums a few states otherwise; docs/FAST-PATHS.md). A blend of the second source, and a blend or partial mask on a device without the interlock, is refused as the device lacking the format; a blend of an output of fewer lanes is NotImplemented; a color input of one is read in the interlocked storage form, the word decoded to each channel's code over its maximum code rounded to half, nearest even, which is Metal's value (measured on an Apple M3 Max under macOS 27.0.1 for a float4 and a half4 input, every code of each 4-bit channel).
  • An 8-bit sRGB attachment of one or two channels (R8Unorm_sRGB, RG8Unorm_sRGB) the device does not render (the RTX 5080: it renders neither R8_SRGB nor R8G8_SRGB, and holds the latter in its UNORM twin) renders through an R8_UINT or R16_UINT view of its texture the same way: the fragment function writes the bytes of the device's sRGB encode (DevicePackConversion), a pass clears it to the bytes of Metal's clear, and a partial mask merges the word in the interlock, or over the attachment's input attachment on a device that orders fetch through rasterization-order input attachments (lavapipe; RuntimeFact::WordInputMerge). A blend of one other than one and zero is refused as the device lacking the format; a color input of one is NotImplemented(Format).
  • An RGB9E5Float attachment the device does not render (the RTX 5080) renders through an R32_UINT view of its texture: the fragment function writes Metal's word of a float output (each channel clamped to [0, 65408], a NaN 0, the exponent of the largest, every mantissa truncated), and a pass clears it to the word of Metal's clear. Exact. A half output to one is NotImplemented(Format) (Metal rounds the float the half was converted from, half up); a blend, or a mask of some of its channels, is refused as the device lacking the format; a color input of one is NotImplemented(Format).
  • A multisampled texture of one of these formats, on a device that samples the format but renders it at no count (the RTX 5080), is held in its word's format (R8_UINT, R16_UINT or R32_UINT) wherever the device renders that format at the texture's count: its samples are the words Metal stores, read through the format's own view as Metal reads them, and copied bitwise. Its resolve is the crate-owned one, a pass after the pass that reads the stored words (shader-resolve): Metal's for RGB9E5Float (each channel's mean of the samples' values, rounded to the nearest half, then encoded with its mantissas rounded half up) and an 8-bit sRGB format, every pixel; for a packed 16-bit format each field's mean of the samples' codes, a tie rounded down (a one-bit field's up), within one code of Metal's, which averages its tile's finer values (word-resolve). A device whose word's format renders one sample at that count refuses the texture (TextureSampleCount).
  • A fragment function that reads a color attachment (framebuffer fetch) reads it in an ordered form wherever the device has one. On a device with neither ordered form it reads the attachment as an input attachment without rasterization-order access (GraphicsState::rasterization_order_attachment_access false), and the consumer records a barrier of the subpass's dependency on itself, by region, before each draw that reads input attachments after an earlier draw of the subpass, or its load operations, wrote a color, and before each draw that writes a color after an earlier one read them: a fetch reads what every earlier draw stored, Metal's answer, but the overlapping fragments of one draw are not ordered, which the fragment stage records (PrecisionNote::UnorderedFetchWithinDraw; the runtime does all of this itself). Under the identity domains the read is the pushed texture of section 1 instead, at the fragment's own pixel, with the same note: the consumer reads the attachment's texture there and orders each fetching draw after the earlier draws of its pass. Linking refuses an attachment the read cannot take: none attached, or one of another numeric class than the read's (InvalidDescriptor at the color attachment), or one of a rotated, Y'CbCr or extended-range format (Unsupported{Format}). A raster order group on such a color input, or on a color output of an attachment the function reads, orders that read alone there and takes no interlock; a group on anything else still needs the pixel interlock (Unsupported{RasterOrderGroups}). The ordered forms are rasterization-order attachment access, or the interlocked storage form, which binds the attachment as a storage image viewed in StorageAttachmentUse::view_format(): its own format, an 8-bit sRGB format's unsigned-integer view, or, where the device declares a BGRA-order format neither typed nor without a format, its RGBA-order twin (the shader exchanges red and blue). A [[stencil]] output uses VK_EXT_shader_stencil_export.
  • [[barycentric_coord]] reads BaryCoordKHR or BaryCoordNoPerspKHR, whose vertex order is Vulkan's first-vertex order and Metal's for every primitive type. A float3 read takes the first two weights and computes the third as 1 - (x + y) in float, as Metal does, not the device's own third lane. On a device without fragmentShaderBarycentric the weights are a varying instead: the pipeline carries a generated geometry stage for each topology class (points, lines, triangles, in that order), which writes (1, 0), (0, 1) and (0, 0) at the primitive's vertices in their order and passes the vertex function's outputs, clip distances, point size and the primitive ID through, and a draw runs its class's. A centroid or sample qualifier reads the pixel center's weights, as Metal does. That needs geometryShader; without it, or for what a geometry stage cannot carry (tessellation, mesh pipelines, a vertex function's own layer or viewport index, amplification without multiviewGeometryShader, a written point size in a point draw without shaderTessellationAndGeometryPointSize, more varyings than the geometry limits), the pipeline is refused, naming what it needs. Measured on the Iris Xe (ANV), such a pipeline takes about 2.6 ms longer to create, and a geometry stage's presence costs about 15% of fill rate.
  • A primitive renders into the slice and through the viewport its first vertex selects, the range check applying to that vertex's index, and its fragments read the first vertex's indices as written, where Vulkan asks every vertex of a primitive to write the same Layer and ViewportIndex. A vertex function stores an index to its builtin only where it writes the same at every vertex of a primitive, decided from its structure (computed from constants, constant memory, the instance, the amplification and per-instance attributes, as StageIo::uniform_outputs lists), or on MoltenVK, which hands the builtins to Metal (DriverDeviation::MetalFirstVertexIndices). Otherwise, and on a device without shaderOutputLayer or shaderOutputViewportIndex, the vertex function stores the index it selects to a flat varying and the same generated geometry stages (one set serving the weights, the primitive ID and the indices) store Layer or ViewportIndex from the primitive's first vertex at every vertex they emit; where it stores one index so, it stores the other so too. The variant for a pass of one layer selects no slice and carries no stage. A device without multiViewport draws through one viewport, so there the vertex function stores no viewport index at all; a draw that selects among more than one viewport there is refused at the draw, Unsupported(LayeredRendering) needing multiViewport. Without geometryShader either, a vertex function that selects its slice is refused needing either feature (its pass of one layer still runs), and so is one that selects its viewport on a device with multiViewport; one whose index differs among a primitive's vertices is refused needing geometryShader. The stages cannot serve a post-tessellation vertex function or an emulated mesh function, nor sit beside a vertex function that writes the builtins itself (a device with the outputs but without fragmentShaderBarycentric): those are refused as not implemented. A fragment function that reads an index no stage writes, on a device that can declare neither builtin, reads 0, Metal's value with no vertex write.
  • [[primitive_id]] counts the draw's primitives in each instance from 0; vertex start, base vertex and base instance do not move it. A fragment stage declares PrimitiveId through geometryShader or tessellationShader. Without both it reads a flat varying the vertex function writes (IoRole::PrimitiveId, PushField::VerticesPerPrimitive); an indirect draw's arguments are then read on the CPU only without shaderDrawParameters. An indexed draw runs de-indexed (VariantKey::primitive_id_indices: needs device addresses, shades every index). NotImplemented(PrimitiveId): an indexed strip, an indirect indexed draw, indices past their buffer, a vertex function that writes memory in that form, and a mesh pipeline. A draw of Metal's private quads or quad strip, which the consumer lists as two triangles a quad (BindState::quad_primitive_ids), runs the fragment variant that reads PrimitiveId shifted right by one (VariantKey::quad_primitive_ids), as Metal counts one primitive a quad. A private type's draw whose vertex function writes the varying, or writes memory (Metal runs it once for each vertex of its list, where an indexed draw may run a shared vertex once), runs the private list form (VariantKey::private_list, BindShape::private_list; needs device addresses): the consumer draws its list without indices from its first index as first vertex, and the vertex function reads each position's index, and Metal's base vertex in the word before the list, at the list's address (PushHole::CaptureIndexAddress), adding them as Metal's vertex ID wraps, so each position runs once and the positions count Metal's primitives. Behind an emulated post-tessellation vertex function the varying carries the patch's position in its draw (tessellation, below).
  • A device draws to at most the lesser of its maxColorAttachments and maxFragmentOutputAttachments color attachments at once (four at Vulkan's floor), where Metal takes eight. A pipeline whose attachments with a pixel format number more draws them in groups of that many, in the order of their indices: variant VariantKey::color_group of the pipeline draws one group, its fragment function writing that group's attachments alone at locations 0.. and its graphics holding them alone (graphics.color_group, a ColorGroup; ColorGroup::of(present, width, group) names a group, and ColorGroup::width_on(profile) is a device's group width). A pipeline whose attachments number no more but reach an index at or past the count (color(0) and color(5) on a device of four) takes one group, renumbered. Every group's variant has the same vertex module; where there is more than one group, their fragment stages' FragDepth, SampleMask and FragStencilRefEXT are decorated Invariant and record PrecisionNote::ColorAttachmentGroups. What each group's draw would run again or read from another group is the pipeline's limit refusal (InterfaceComponents at MaxColorAttachments): a vertex or fragment function that writes memory, alpha to coverage, a tessellation pipeline, a [[color(n)]] input of another group that the specialized function reads (one whose read its function constants fold away reads nothing and is not refused), imageblocks, and a raster order group on a color output or on a parameter the specialized function uses (one on a parameter it never uses orders nothing and is not refused). Mesh and tile pipelines take no groups. The runtime draws such a pass group by group, each group's colors in a pass of its own over a twin of the depth and stencil (the runtime's render/color_groups.rs; what it refuses there is RuntimeGap::ColorAttachmentGroups).
  • A pipeline's band variant (VariantKey::line_band, of a BandPrimitive) draws each line, or each edge of a triangle in fill mode Lines, as the parallelogram Metal draws for a line under Apple's setLineWidth: at a width the device's own lines do not draw (the runtime chooses where: its README's line widths). Link adds two stages after the vertex stage (pipeline::link::band): a tessellation control stage that passes the primitive's vertices through, and an evaluation stage that places each vertex of a quad patch at an endpoint, moved across the segment along its minor axis by half the width in framebuffer pixels. A line's patch is two triangles over its parallelogram, front-facing under LineBandState::FRONT_FACE; a triangle's is the fans of the quad domain's degenerate inner ring over its three edges' parallelograms, which face as the triangle does under the draw's front face (a zero-area triangle faces back). graphics.line_band (LineBandState) states the draw's contract: each primitive one patch of its vertices (PATCH_LIST, BandPrimitive::patch_control_points), a line's without culling under front face LineBandState::FRONT_FACE and without depth bias, a triangle's under the draw's cull mode, front face and depth bias, and the band's [sx, sy, h, f] pushed to the evaluation stage at push_offset (BindState::line_band: Vulkan viewport 0's half extent, the half width, and for triangles 1 under a clockwise front face, -1 under a counter-clockwise one). A smooth varying and the clip distances are each endpoint's, a flat or integer varying the first vertex's. It needs tessellationShader (Unsupported{WideLines} needing it); a post-tessellation vertex function, a vertex function that writes a layer or viewport index, synthesized geometry stages, a fragment function that reads barycentric weights and multiview are not implemented.
  • graphics also states what the runtime needs to record draws correctly: whether the fragment function reads flat inputs, barycentrics or its position's depth, whether the vertex function writes memory or a layer or viewport index, and which colors the function may write.
  • On a device with VK_KHR_portability_subset (MoltenVK), each of the subset's missing features is checked against what the pipeline uses.

metal::state maps the encoder-side Metal state a pipeline does not own (cull mode, winding, depth/stencil state, ...) to Vulkan values.

Tessellation

A post-tessellation vertex function makes a tessellation pipeline:

let vertex = FunctionDescriptor::new(library.function("tess_quad_buffer")?);
let mut descriptor = RenderPipelineDescriptor::new(StageSource::Function(vertex));
descriptor.tessellation = Some(TessellationDescriptor::default());
let pipeline = device.compile_render_pipeline(&descriptor, &Budget::standard())?;

Its stages are a synthesized vertex and tessellation control stage, the function as the evaluation stage, and the fragment stage. It draws patches only (DrawCall::Patches or PatchesIndirect), with the factors from a tessellation factor buffer. The device's tessellator orders the triangles (PrecisionNote::TessellationTriangleOrder where it is not Apple's).

On a device without tessellationShader the pipeline is an emulation with no tessellation stage: the function is its vertex stage (TRIANGLE_LIST), and graphics.emulated_tessellation states the tessellation state it bakes in. Each patch draw's DrawCommands::tessellation_dispatch is a compute scan (bind::tessellation_scan_module, one workgroup) to record before the render pass, and chunk draws of up to 2^30 triangles that replace draw; TessellationDispatch states the contract (buffers, order, barriers). The scan binds four storage buffers; the vertex function binds two to four beside its own, counted against maxPerStageDescriptorStorageBuffers (DescriptorCount past it). A fragment [[primitive_id]] reads the patch's position in the draw from the primitive ID's varying (NotImplemented(Tessellation) behind tessellation stages), and an indirect patch draw's [[base_instance]] is read on the GPU.

Mesh pipelines

Device::compile_mesh_pipeline compiles a MeshPipelineDescriptor (an optional object function, a mesh function and a fragment function), and compile_mesh_variant its variants. Its plan draws mesh draws only (DrawCall::MeshThreadgroups, MeshThreads and their indirect forms). With VK_EXT_mesh_shader the stages are task and mesh shaders. Without it (MoltenVK, older ANV) the pipeline is an exact emulation: the object and mesh functions run as compute stages that write the mesh's vertices and primitives as records into buffers, and a synthesized vertex stage draws those records; the plan says which dispatches and draw to record.

A grid Metal draws nothing for (an axis past bind::METAL_MESH_GRID_AXIS, or more than bind::METAL_MESH_GRID_TOTAL threadgroups, measured on the M3 Max) draws nothing in every form: a direct draw's command is zeroed, an object function's wrapper launches nothing for such a grid, and an indirect draw reads its counts on the GPU. With the extension, an indirect draw's DrawCommands::mesh_arguments is a pass to record before the render pass (bind::mesh_arguments_module, one invocation): it writes the draw's counts into the consumer's scratch (MeshArguments::scratch_bytes), which the draw reads in place of Metal's arguments.

An object grid runs at any count Metal runs, past the task stage's limits too, on a device with device addresses, shaderInt64, multiDrawIndirect and drawIndirectCount (every committed profile with the extension): the object function is compiled folded, and each draw runs its grid in pieces within the task limits (bind::fold_object_grid), its object stage reading the threadgroups Metal runs and its grid from a 32-byte region record at its PushHole::ReplayRegionAddress. A direct draw's fold is DrawCommands::object_fold, whose bytes the consumer uploads (the record, and its pieces' commands where draw is indirect); an indirect draw's arguments pass (MeshArgumentsForm::FoldedObject) writes the record, the pieces and their commands, which draw (DrawMeshTasksIndirectCount) reads. Metal's threads per grid wrap to 32 bits along each axis, as its builtins report them; a direct draw runs only the threadgroups those threads fill, rounded up, an indirect one every threadgroup (bind::metal_object_grid). Every device runs a grid of up to bind::METAL_OBJECT_GRID_TOTAL (2^29) threadgroups, the most Metal's GPU ran within its watchdog's 5 seconds. A larger one, which Metal's GPU discards, draws nothing and fails its command buffer with Metal's error (the runtime's CommandBufferError::GpuRecoveryVictim): a direct draw says so in DrawCommands::discards_command_buffer, and the consumer fails the command buffer from the draw's encoder on, as Metal does; an indirect draw's arguments pass sets StatusBits::MESH_GRID_DISCARDED in the command buffer's ExecutionStatus. Where the device cannot launch a grid Metal draws, the draw draws nothing and the command buffer fails with the runtime's own error (CommandBufferError::MeshGridPastLimits, not Metal's): an indirect draw's object grid past the task limits of a device that does not fold object grids, or a mesh grid past the mesh limits, through StatusBits::MESH_GRID_PAST_LIMITS, or a fold of more pieces than MeshArguments::OBJECT_PIECES (only under task limits below Vulkan's required least), its past. A direct object grid past the task limits of a device that does not fold is refused naming the limit.

Without the extension, an indirect draw with an object function first dispatches an object arguments pass (MeshDispatch::object_arguments, bind::mesh_object_arguments_module, one invocation over the scan's bindings): it reads Metal's arguments, reserves the object threadgroups' slots in the command buffer's records pool, and writes the object function's VkDispatchIndirectCommand into the work buffer (MeshDispatch::OBJECT_DISPATCH_OFFSET). A grid Metal's GPU discards sets StatusBits::MESH_GRID_DISCARDED; one past the device's compute limits sets MESH_GRID_PAST_LIMITS; slots the rest of the pool cannot hold set MESH_RECORDS_OVERFLOW. Each draws nothing. A grid whose threads per grid wrap along an axis runs every threadgroup, and the object function reports the wrapped grid as Metal's: an unfolded object function's threadgroups_per_grid is the threadgroups its wrapped threads fill.

Tile pipelines

Device::compile_tile_pipeline compiles a TileRenderPipelineDescriptor (the tile function and the render pass's color attachment formats) into a ComputePipeline that stands in for dispatchThreadsPerTile:. Dispatch it as Dispatch::Threadgroups over the render area, one threadgroup per tile, with BindState::imageblock_size and BindState::render_area set, and bind each attachment it reaches as a storage image where the plan writes WriteSource::TileAttachment. Its threads are numbered as Metal's tile dispatch numbers them, for every threadgroup of even sides up to 32x32 and the single thread; a threadgroup with an odd side, whose quads Metal leaves partly empty, is refused. A tile function runs on a single-sample pass: a multisample imageblock's operations (its sample count, the colors a pixel holds and their coverage masks, a store to the samples a coverage mask selects) are refused as not implemented (Feature::Imageblocks, naming the intrinsic).

5. The interface and the plan

The pipeline states what it binds and how:

for (slot, interface) in &pipeline.interface.slots {
    println!("  slot {slot:?}: {interface:?}");
}
for set in &pipeline.layout.sets {
    for binding in &set.bindings {
// ...
for dependency in &pipeline.dependencies {
    let (fact, mechanism) = (dependency.fact, dependency.mechanism);
    println!("  depends on {fact:?} via {mechanism:?}");
}
  • interface.slots holds every statically used Metal slot (SlotRef: stage, table, index): how the shader accesses it, and for a buffer the byte window it can touch. A buffer slot's kind says whether Metal binds a buffer, a visible-function table or an intersection function table there.
  • Under the identity domains (section 1) a buffer slot's PushField::SlotGuestBase is its address, the bound buffer's gpuAddress plus the bind offset (or the address of its setBytes copy, or of the consumer's nil buffer where nothing is bound), less 2^31, modulo 2^64. An access through the slot adds its 32-bit byte offset plus 2^31, modulo 2^32, zero-extended, to that word; a pointer compare, a pulled vertex fetch and an access from the word below it add the 2^31 back to read the address itself, and so does a slot pointer converted to an integer or stored, which is the slot's address plus its offset. The binder (BindingPlan::instantiate_*) of a device that compiles under the identity domains writes the word so. A pointer loaded from memory (an argument buffer's pointer member, a gpuAddress the program stored) and a pointer made from an integer are the device address the word holds, unbiased and used directly, unchecked: there is no root table, no PushField::RootTableAddress and no search. A texture's or sampler's SlotGuestBase is its gpuResourceID, unbiased.
  • Under the identity domains with containment on, a buffer slot that an access may reach at a byte offset that is not a translation-time constant (an index the memory plan does not prove one value, a looping memcpy or memset, a pulled fetch) also reads PushField::SlotBounds: a uvec2, the bound buffer's bytes before the bind offset (the bind offset), then the buffer's length; 0 and the length of its setBytes copy; 0 and 0 where nothing is bound. Each such access whose offset the module does not hold as a constant is checked against the buffer: for an n-byte access at its 32-bit byte offset m from the bind offset, read as signed, the normative check (len >= n) && (m + before <= len - n) in u32. The domain is the bound buffer, as Metal's is and as a storage view of a whole window's is (from the buffer's start): an offset before the bind offset is inside where the buffer holds it, and one before the buffer's start wraps to at least 2^31, outside. The module computes it as m + before < limit, the slot's limit for n-byte accesses len - min(len, n - 1) (0 for a slot shorter than one access), made once per slot and size in the function's first block: one add and one compare per access. A load outside reads each of its units at PushField::ZeroAddress, a u64 the consumer pushes: the address of 16 bytes of zeros, a multiple of 16, that nothing writes. That is one select of each unit's address, with no select of the value and no branch, and the load touches nothing of the slot. A store or an atomic outside sits in the check's selection and runs nothing; an atomic's answer there is 0. Nil and a slot shorter than one access push a length that every such access past it fails. An access at a constant offset, and an access through a pointer loaded from memory or made from an integer, is not checked. The binder writes SlotBounds from the bound buffer and refuses ZeroAddress (Unsupported{IdentityDomains}): the zero range is the new runtime's own memory. What the check costs, measured on the new runtime against the same build with the check removed (release, no validation layer): in the compute harness's GPU time, wide_bindings 34.7% slower on a Radeon 780M (job m3-max-56485), 38.5% on an RTX 3090 (m3-max-56486) and 68% on an Iris Xe (m3-max-56546); bind_2000 17.9%, 32.1% and 11.3%; constant_managed and constant_private 8.0% and 8.3% on the 780M, 22.2% and 25.8% on the 3090, level on the Iris Xe; row_cells level on the 780M and the 3090, 9.5% on the Iris Xe. A recorded replay stream's GPU time a frame, its players built from 653014c278 (the same jobs): 3.3% more on the 780M over 438 frames (one round), level on the 3090 over 464 frames, and 5.5% more on the Iris Xe over 200 frames (m3-max-56641). Making two recorded sessions' render pipelines cold takes 3.5% and 3.8% more driver time on two RTX 3090s with the check than without it (players built from 84b4f52e4b, jobs m3-max-58076 and m3-max-58098).
  • The layout numbers set 0 densely, in ResourceSlot order. Set 1 holds the heap arrays (the resources reached through argument buffers and resource IDs); pipeline::heap_sampler_capacity is the most elements a set-1 sampler array has on a profile. A texture buffer reached so is an element of a texel-buffer class: a uniform texel buffer array where the function only reads it, a storage texel buffer array declared without a format where it writes it, each needing the texel buffer kind's non-uniform indexing and update-after-bind features (a storage one also shaderStorageImageWriteWithoutFormat, and where it is read shaderStorageImageReadWithoutFormat or, without it, the formats' own read bits, section 10). bind::heap_element answers HeapElement::TexelBuffer for a texture buffer such a class holds, the format of its texel buffer view; a planned heap's members are textures with images, so only a heap set the consumer keeps for every command (each live texture at its resource ID) holds texture buffers. Push constants carry the values the binder writes per command. A stage that writes the command buffer's ExecutionStatus (a seq_cst fence, an argument buffer's cubic sampler) reaches it by device address, a push hole, where the device addresses buffers (bufferDeviceAddress and shaderInt64), and through a set-0 storage buffer of its own (SyntheticBinding::ExecutionStatus) where it does not. That binding counts against the stage's storage-buffer limits: past one, an absent read or a fence is refused (DescriptorCount), and a stage that would bind it only to test its argument samplers for a cubic filter binds nothing, so the plan refuses a cubic sampler listed beside it (SamplerBicubicFilter).
  • A heap texture sampled through one of several constexpr samplers, the one a sampler handle names at run time (a table of constexpr samplers read at a computed index), samples once through a set-0 array of those samplers (ResourceKind::SamplerArray, BindingSource::SamplerArray), at the element the handle names. The binding's immutable_samplers holds each element's sampler, count of them, each made as a heap texture sampled through that sampler alone bakes it; it takes no descriptor write, and a pushed set 0 pushes them. StageInterface::sampler_arrays lists each array's constexpr samplers by its slot. The module takes this form where the candidates' handles are consecutive, each candidate's sampling is the same but for its sampler, and the device indexes a sampler array by a value that may differ between invocations (shaderSampledImageArrayNonUniformIndexing, which heap textures already need); otherwise it switches over the candidates, one sampling per candidate.
  • Each binding's variables is the most variables one stage's entry point uses at it (those its OpEntryPoint lists): a function that reaches a buffer through several types uses a variable of each type at the buffer's binding. A set-0 uniform or storage buffer binding may be created as its dynamic type (VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, ..._STORAGE_BUFFER_DYNAMIC), its descriptor written at offset 0 and its range's offset bound as the dynamic offset: the module reads the same bytes, and commands that differ only in offsets can bind one set. The runtime does so for each such binding of one descriptor and one variable that no stage the pipeline adds reads, in binding order within maxDescriptorSetUniformBuffersDynamic and maxDescriptorSetStorageBuffersDynamic, where it does not push set 0; the rest stay of their own types. Keep a binding of several variables static on MoltenVK 1.4.1: its SPIRV-Cross writes Metal that does not compile for a dynamic buffer an entry point uses through more than one variable.
  • A buffer slot's uniform view is a Uniform block (DescriptorView::UniformWords, or UniformVec4 without uniformBufferStandardLayout), but on a profile that takes DriverWorkaround::ExternalUniformReadsSkipACache (measured: DeviceDescription::measured; on the Iris Xe RPL-P under ANV the runtime's view check finds it) a slot with an indexed read whose window is Bounded and at most 4 KiB long takes a uniform texel buffer instead; a slot read at constant offsets alone keeps its Uniform block, whose words a driver may load ahead into registers as it cannot a texel fetch (DescriptorView::UniformTexel: a UniformConstant image of Dim Buffer, Sampled 1, u32 texels, read with OpImageFetch), its binding VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER. Write a view of the planned range in R32G32B32A32_UINT, from the range's buffer, offset and length, each command's own (the runtime makes one for each descriptor write and holds it until the command buffer completed); the buffer needs the uniform texel buffer usage. The range starts at a multiple of max(minTexelBufferOffsetAlignment, 16), holds a multiple of 16 bytes and at most maxTexelBufferElements texels, and the slot's use class is AccessClass::Sampled (VK_ACCESS_2_SHADER_SAMPLED_READ_BIT). Its words are those a uniform buffer of the range would read. On that driver a uniform buffer read of memory the device marks external (imported host memory, a dma-buf) misses a cache that a uniform texel buffer read keeps: a kernel's uniform buffer reads of a window over imported memory took 2.0 to 2.5 times their time over device memory (5.2 to 5.5 times where each invocation read its own word), its texel reads 0.98 to 1.04 times. A window of up to 4 KiB read through a texel buffer was no slower than through a uniform buffer of device memory in any pattern measured; longer windows keep the uniform buffer, whose reads over imported memory stay slower there (docs/FAST-PATHS.md, known gaps).
  • On MoltenVK, push set 0 (a push descriptor set layout) for a pipeline whose fragment stage writes a storage buffer of set 0 inside its interlock (an interlock execution mode, and a StorageBuffer variable of set 0 not decorated NonWritable): binding through Metal argument buffers, MoltenVK packs a bound set 0 into one argument buffer, and Metal leaves such a buffer out of its raster order group where the function also reads another buffer of that argument buffer, so overlapping fragments of a draw read it unordered (measured on an M3 Max with 1.4.2). A pushed set's buffers are discrete arguments, which Metal orders. MoltenVK's pushed sets do not hold their buffers' sizes, so bind set 0 there for a pipeline a stage of which reads a buffer's length (OpArrayLength); the runtime does both, and announces such a bound set 0 (metal2vulkan-degrade-interlocked-buffer-order).
  • dependencies lists the bind-time state the pipeline depends on (RuntimeFact: threadgroup sizes, sampler coordinate modes, buffer ranges, ...) and how this profile honors each (Mechanism: a specialization constant, a push field, a plan-time check, a variant). The plan acts on them; you do not have to.
  • The format class of a bound texture is read by the shader as push data, not specialized, so binds that differ only in their textures' formats share one VkPipeline. On MoltenVK a slot read with a half result also specializes one bit of it: whether the class converts its texels to half by rounding to nearest even alone (every class but those with 32-bit float channels, 16-bit normalized ones and YCbCr fields on the grid 8192), so a slot bound to both kinds of format takes two pipelines. Other bound values (a slot's presence, a sampler's word, whether a uniform buffer's descriptor range starts at its bind offset) are specialization constants. The last lets a driver load the constants ahead of the shader: inline bytes take that form, and so does a buffer bound at a multiple of max(minUniformBufferOffsetAlignment, 16) at a slot whose table tells that alignment apart (state.view_base_alignment = BindState::view_base_alignment_of(limits), and the slot's bit in its table's at_bind_views; interface.uniform_view_buffers(stage) lists the slots that can take it). A buffer bound at any other offset, or at a slot left out, takes the other form, a pipeline of its own: leave out a slot bound at offsets that move, so that its draws keep one shape and one pipeline (the runtime leaves out each slot of a state once it finds one bound at an offset the alignment does not divide). A consumer that draws and dispatches every key with its uniform views at their residuals (each uniform view's RangeAtBindOffset at 0, as the runtime does on every device whose driver is not measured to load such reads ahead of the shader) says so with state.uniform_views_at_residual = true: its uniform views then bind ranges their bind offsets share (below), as a bounded storage view's do. On a profile that takes DriverWorkaround::PushReadsLengthenThreadPayload (ANV on the Iris Xe RPL-P, where a light kernel that reads a pushed word was measured at about 2.2 times the time of one that reads none) a storage view declares the key too, and takes the form that reads no residual only at bind offset 0 of a slot whose table tells offset 0 apart (the slot's bit in its table's zero_offset_views; interface.storage_view_buffers(stage) lists the slots that can take it), its class then bind::ZERO_OFFSET_CLASS: leave out a slot bound at another offset, as the runtime does, so that the bytes before a bind offset stay reachable through the range from the buffer's start and its dispatches keep one shape. A storage view's slot bound to nothing takes the value a bind at offset 0 gives it, so a plan of nothing bound (a creation's prediction) names the key of a command that binds its storage views at offset 0, the commonest bind. The runtime keeps that key and makes it at a state's creation together with its general form (every view read at its residual), which a command binding a storage view at another offset takes at once while its own key is made, so neither is a second pipeline made at a first command. It reads the profile's uniform views at their residuals: there a kernel of three storage views at offset 0 and inline bytes ran in 161.8 us a dispatch with the bytes' uniform view read at its bind offset, and in 142.8 us with it read at its residual. Elsewhere no storage view declares the key, and zero_offset_views changes nothing.
  • A bound buffer's length enters its shape only as a length class (bind::length_class), which a plan compares with the device's maxUniformBufferRange and maxStorageBufferRange alone (whether every range of the buffer fits each). Set each table's buffer_ranges = BufferRanges::of(limits) and its shape tells apart only the classes those limits tell apart (BufferRanges::length_class: a class rounded up to the greatest one that fits the same limits), so commands over buffers of many sizes keep one shape and one plan: on a device whose two limits are both 4 GiB, every buffer below 4 GiB. The default tells every class apart. The runtime sets them on every table it reads.
  • A two-plane YCbCr texture whose planes a function may read in place states them in its facts (TextureFacts::ycbcr_in_place, a YCbCrInPlace of its planes; the runtime states one on a device whose memory is the host's, DeviceProfile::reads_ycbcr_planes_in_place: an integrated GPU or a CPU device). A slot whose function only samples it (nearest or linear, no comparison, anisotropy or min_lod_clamp), gathers it or reads its size (RuntimeFact::YCbCrInPlace) takes the pipeline's in-place variant (VariantKey::ycbcr_in_place): the slot binds a uniform texel buffer over the planes' bytes (WriteSource::YCbCrInPlace, in YCbCrInPlace::format), its push field (PushField::YCbCrInPlace) holds YCbCrInPlace::words, and the function converts and filters the codes as Metal does, exactly (a gather Metal's taps of them). Any other slot, and any texture without the fact, binds the texture's image of converted texels. Where the consumer also holds the planes as a linear image of their multi-planar 4:2:0 format over their bytes, which the device's sampler Y′CbCr conversion reads with Metal's reconstruction, it states so (YCbCrInPlace::with_planes_image, its conversion YCbCrInPlace::sampler, a YCbCrPlanesSampler). A slot whose every sample the device's sampler takes (the fact's device: no border address mode, no texel offset placed by a parent's size, no gather; a runtime sampler's word without a border mode) then takes the planes variant (VariantKey::ycbcr_planes_sampled): the slot is a combined image sampler of the image (ResourceKind::YCbCrPlanes, BindingSource::YCbCrPlanes, written from WriteSource::YCbCrPlanesImage) whose immutable sampler is SamplerDesc::ycbcr of the conversion. The consumer chains its VkSamplerYcbcrConversionInfo into that sampler and makes the image's view with an identically defined conversion, and sizes a pool for the format's combinedImageSamplerDescriptorCount descriptors at the binding. Each sample is the device's, at level 0, its conversion and filter of the codes rather than Metal's.
  • A 2D texture whose image is a shadow but whose bytes the consumer reads and writes in place states its rows in its facts (TextureFacts::texel_rows, a TexelRows: its width, height, the texels from one row's first to the next's, and its first texel in a texel buffer view of its bytes; the runtime states one for a shadow over host pages whose image the device refused, not one its policy asks for). A slot whose function only reads, writes or asks the size of it (no sample, gather, atomic, read through a sampler, level views, switch at use or residency; RuntimeFact::TexelRows) takes the pipeline's rows variant (VariantKey::texel_rows) where the device views the texture's format as a texel buffer of the slot's kind (uniform where the slot's declaration only reads, storage otherwise, read and written without a declared format): the slot binds a texel buffer of the format over the rows' bytes (WriteSource::TexelRows, from the view's first texel through the last row's last; a use of class AccessClass::TexelRows of those bytes), its push field (PushField::TexelRows) holds TexelRows::words, and the function addresses texel (x, y) at first + y · row + x, testing every read and write against the texture's size itself (a coordinate past the width names the next row's texel in the view): a read outside is Metal's out-of-bounds texel and a write there is dropped, and a size query answers the field's size and one level. A texel buffer's texels go through the device's format conversion as an image's do, so the reads and writes are the image route's, bit for bit (the runtime's texel_rows_device tests compare every RGBA8Unorm and RGBA16Float code), and no precision note is recorded. Any other slot, and any texture without the fact, binds the image.
  • A texture buffer of more texels than the device's maxTexelBufferElements (Metal makes them up to 2^28 texels on every Mac; one texel buffer view holds 2^27 on ANV and lavapipe and 2^26 on MoltenVK) is bound through views of its parts. State with its binding the views its texels take (BoundTexture::Buffer::parts, bind::texel_buffer_parts(limits, texels): 1 within the limit, which binds one view as before and keeps the pipeline and its key). Each part but the last holds bind::part_texels(limits) texels, the limit rounded down to a multiple of minTexelBufferOffsetAlignment, so every part starts on that alignment where the texture buffer does; the last holds the rest. A slot whose function only reads (not through a sampler), writes, updates by an atomic or asks the width of the texture buffer, on a device that indexes an array of the slot's kind of texel buffer by a NonUniform value (RuntimeFact::TexelBufferParts), takes the pipeline's parts variant (VariantKey::texel_buffer_parts) where the shape binds more than one part there: the slot is an array of the parts' texel buffers, one WriteSource::TexelBuffer per array element, each element's view the bytes of the instance's DescriptorRange at that element. The function reads texel i as texel i - k · P of part k = min(⌊i / P⌋, parts - 1); a texel past the last lies past the last part's end, so its read is Metal's out-of-bounds texel and its write is dropped, as through one view, and the width is (parts - 1) · P plus the last part's. Each part is the device's own view in the format one view takes, so a read converts its texel as that view does, and no precision note is recorded. Still refused with BindError::TexelBufferTooLarge: a slot that reads the texture buffer through a sampler, a device without shaderUniformTexelBufferArrayNonUniformIndexing (or shaderStorageTexelBufferArrayNonUniformIndexing for a slot that writes), and a format whose block holds several texels; parts past a stage's sampled or storage image descriptors are the link's descriptor-count refusal. A texture buffer past the limit in an argument buffer is the heap class's neutral (metal2vulkan-degrade-unnamed-texture-unviewable).
  • interface.reaches_command_buffers and interface.texture_writing_stages say, provably, which pipelines may touch an indirect command buffer and which stages may write a texture. interface.command_writes (CommandWrites) says what its functions may write into the records they reach: the indirect-command operations they may call, and the primitive types their draws may pass (a draw's constant type, or all five where it is not a constant). A clear bit is proven.
  • interface.writes_memory says, provably, whether a pipeline's functions write memory another invocation or a later command can read: a store to a buffer or through a device address, a texture write, or an atomic update. A compute pipeline without it has no effect a program can observe, so a runtime may run nothing for its dispatches.
  • interface.reads_unbound_resources and interface.writes_unbound_resources say, provably, whether a pipeline's functions may read or write a resource through anything but their bound slots: through a pointer or texture they load from memory or make from an integer (an argument buffer's resources, an address stored in a buffer, a resource ID), an indirect command buffer, ray tracing, or a call the function cannot see into. Metal requires such resources to be declared with useResource or useHeap. With each slot's access, they are what a compute encoder needs to place a barrier only on a hazard.
  • interface.unbound_storage_textures says, provably, whether a pipeline's functions may reach a texture through its storage image through anything but their bound slots: a texture write or atomic, or a read the operation does not declare access::sample or access::read, through a texture they load from memory or make from an integer (an argument buffer's texture, a resource ID), or an intersection or a call the function cannot see into. A runtime that gives some textures no storage image needs it to find such an access to one.

Plans

Per draw or dispatch, describe what is bound, keyed by Metal slot, as a BindState. The binder never sees your resources, only facts about them:

let mut table = StageTable::default();
table.buffers.insert(0, buffer(4096, 0));
let facts = TextureFacts::new(TextureType::Type2D, PixelFormat::RGBA8Unorm);
let texture = BoundTexture::Texture {
    facts,
    resource_id: None,
};
table.textures.insert(0, texture);
let sampler = BoundSampler::new(SamplerDescriptor::new());
table.samplers.insert(0, sampler);
let mut state = BindState::default();
state.stages.insert(Stage::Kernel, table);

let plan = pipeline.plan(&device, &state.shape())?;
assert!(plan.variant.is_empty(), "this shape needs no other variant");

state.shape() keeps only what can change a plan (which slots are bound with what kind of resource, formats, level counts, sampler modes, alignment classes). A plan is a pure function of the pipeline, the device and the shape: memoize it on (PipelineKey, BindShape). A consumer that keeps the shapes it planned can find a state's among them without making it: state.has_shape(&shape) answers state.shape() == shape, compared in place, and state.position_of_shape(&shapes) finds it among many, making the shape of the resources the state lists at most once.

The plan holds one DescriptorWrite per layout binding element (the resource at a slot, a buffer the binder synthesizes, or a neutral resource where nothing compatible is bound), the vertex buffers, and the ResourceUses that drive staging, writeback and barriers. List in the state every live sampler state and visible-function table the command can reach through argument buffers (argument_samplers, function tables), and the resources it uses (used_resources). A consumer that lists those in token order says so (used_in_token_order), and one that points every root table at a resident set it uploads apart, holding them and the ranges it lists (resident_ranges), says that (resident_apart, with ResidentSet and RootTable::resident_fields): a command's instantiation then costs its own bindings and heap members, not every resource the state lists. A consumer whose ranges change a few at a time keeps them in parts (ResidentPart), makes again only the parts that changed, and joins them (ResidentSet::of_parts) into the set ResidentSet::new makes of all their ranges, entry for entry, without sorting or coalescing the unchanged parts again.

A plan whose variant is not empty asks for another variant of the pipeline (a storage texture's format, a buffer range past the descriptor limit, a vertex buffer that fixed-function input cannot fetch, ...). Compile it and plan it for the same shape: device.compile_render_variant(&descriptor, &plan.variant, &budget) for a render pipeline, or compile the kernel with plan.variant.lowering_inputs(Stage::Kernel) and link it as StageSource::Compiled. A dispatch can ask too (plan.dispatch_variant(&dispatch), or BindError::NeedsVariant from instantiation).

Textures follow Metal's texel rules: sparse textures report residency where the device can, Depth32Float texels are the device's depth image's (a value it clamps or a denormal it flushes is announced, restricted-depth-upload, depth-denormals), ulong textures and their atomics use 64-bit images where the device has them, and half and sRGB reads give Metal's values or record their bound (an sRGB texel is the device's own decode wherever the device samples its format, srgb-texel-decode). The rustdoc of BindState, TextureFacts and BindingPlan states each rule. A read's, sample's or gather's {T, i8} result (the texel and its residency word) may pass through phis, selects, freezes and member insertions and extractions, Apple's GL code generator's swizzled read among them. A function whose effects depend on a bit of the word other than bit 0 (resident()'s), or that stores, passes or returns a value holding the word, is refused (Lowering(Texture)): Metal establishes no other bit.

6. At bind time

Instantiate the plan per dispatch or draw:

let dispatch = Dispatch::Threads {
    threads: [100, 1, 1],
    threads_per_group: [32, 1, 1],
};
let commands = plan.instantiate_dispatch(&state, &dispatch)?;
for region in &commands.regions {
// ...
println!("  descriptor ranges: {:?}", commands.descriptor_ranges);
println!("  push holes: {:?}", commands.push_holes);
let plan = pipeline.plan(device, &state.shape())?;
let draw = DrawCall::Primitives {
    vertex_start: 0,
    vertex_count: 6,
    instance_count: 1,
    base_instance: 0,
};
let commands = plan.instantiate_draw(&state, &draw)?;

A buffer slot read through a storage view of its whole window (a device pointer the function indexes) takes the descriptor range from the start of the bound buffer's space to its end padded to 16 bytes, whatever its bind offset, which its SlotBindOffset push field holds: draws and dispatches that bind one buffer at other offsets write the same descriptors, and only push data differs. Where that range would pass the view's maxStorageBufferRange or 4 GiB, or the offset lies at or past the padded end, the range starts at the bind offset aligned down to the descriptor base alignment. An access that reaches back before the bind offset, inside the buffer, reads the buffer's bytes there, as Metal's does.

A slot of a bounded window read at its residual -- a storage view's always, a uniform view's where the state says uniform_views_at_residual -- takes a range its bind offsets share in the same way: the buffer from 0 to its padded end where that fits the view's maximum range (a uniform view's is maxUniformBufferRange capped at 64 KiB, its texel form's maxTexelBufferElements texels) and 4 GiB, else the block of half that maximum (rounded down to a power of two) its window starts in, to the maximum past the block's start. A window of at most half the maximum starting in a block ends inside its block's range; a longer one, or one at or past the padded end, takes the range from its bind offset, as every other descriptor-form slot does. So draws that move such a slot's offset along one buffer (a consumer's staged setVertexBytes, a constant reference bound at the next offset of an upload chunk) write the same descriptor, keep set 0 and push only the slot's SlotBindOffset. Each read inside the window reads the bytes it read before; one outside it, which Metal leaves undefined, reads the buffer's bytes inside the range.

instantiate_draw_into writes the same commands over a DrawCommands you keep, in the storage its vectors already hold: keep one from draw to draw (DrawCommands::default() to start) and the draws allocate none of it again once it holds as much. instantiate_dispatch_into does the same for a compute dispatch over a DispatchCommands you keep (one instantiate_dispatch made, to start): each region's specialization and push bytes, and the argument table's, are written in the storage the commands before held.

dispatch_reads says which slot classes' bound values, past their shape, a compute plan's instantiate_dispatch may read: buffer slots always; texture slots only where the plan binds a texture buffer's range as a texel-buffer view, pushes a texture's in-place planes, or names the texture bound at a slot in a handle table; sampler slots never. The commands of a dispatch are those of a later dispatch of the same plan whose state has the same shape and differs only at slots of a class it answers false for: two textures of one shape bound in turn, for one. Every other value of the state may be read.

rebind_draw_slots_into writes again only what some buffer, texture and sampler slots decide, over the commands of the same draw of a state of the same shape that differed only in what those slots bind: the buffers' descriptor ranges, the push fields that read them and their vertex buffers' offsets. A texture or sampler slot decides none of the commands; its descriptor is yours to write again. It answers Ok(false) where the plan reads one of them some other way (a device address, an argument or root table, a vertex binding of a per-bind stride, a texture buffer's texel range, a YCbCr texture's planes, a mesh, patch or de-indexed draw) or a uniform view a written slot may alias; then instantiate the draw whole.

What a plan alone decides of such a rebind, for a list of slots, slot_rebinds works out once: each changed buffer slot's place among the descriptor ranges, the push fields that read the slots and where they lie, and the vertex buffers they bind (None where rebind_draw_slots_into answers Ok(false) whatever the state). rebind_draw_slots_with then rebinds those slots by them, looking at the state and the commands alone, with the answers and commands rebind_draw_slots_into gives: keep the SlotRebinds beside the commands for draws that change the same slots of the same plan. slot_rebinds_into makes them again in a SlotRebinds you keep (its default holds none), for other slots or another plan, in place of what it held: its lists keep their room, so making them again allocates nothing where they had room; SlotRebinds::slots names the slots they were made for.

redraw_apart_into writes again only what a draw's arguments decide, over the commands instantiate_draw_apart_into wrote for another draw of the same state that differed from it only in them (whether it reads indices, its index type and index buffer, its vertex or index counts and starts, its index offset, its instance count, base vertex and base instance), both direct draws: the Vulkan draw, its index overrun, the BaseVertexInstance push fields and the draw's own index buffer use. It answers Ok(false) where the plan reads the arguments some other way (an argument or root table, a mesh, patch or de-indexed draw, a vertices-per-primitive push field of a draw with indices and one without), where a fixed-function vertex buffer's fetch window, which the extents hold, moves with them (another vertex range of a draw without indices, another instance range of a per-instance buffer), or where the two draws are no such pair; then instantiate the draw whole. An index offset that moves rebinds the index buffer there: the draw command's index_buffer_offset is the new offset.

A plan that reads handles (a texture's or sampler state's resource ID, a visible function table's) writes heap tables among its descriptor bytes, after the stage tables: its handle tables, sampler tables and function-table directories. Their bytes grow with the resources the state lists as used and the textures its slots bind that a handle names, and they depend on nothing else of the state but its argument samplers, function tables and heap placement. heap_tables_into writes them alone, and instantiate_draw_apart_into writes every other command of a draw, its descriptor bytes the stage tables alone. Keep a state's heap tables while those inputs hold (the used resources, the textures at the plan's heap_slots, the argument samplers, the function tables and the placement), and instantiate each draw apart: draws that rebind only buffers then cost what they bind, not what the state made resident. heap_elements is the same kind of function of the same inputs and the heap's capacity.

A dispatch is one or more regions (a grid that is not whole threadgroups adds edge regions), each with its group count, specialization and push constants: create one VkPipeline per distinct specialization. The plan of a kernel's partial-threadgroups variant (VariantKey::partial_threadgroups, which LoweringInputs::partial_threadgroups compiles) runs such a grid as the threadgroups its threads fill at the dispatch's threadgroup size instead, the last along an axis Metal's partial threadgroup, so every remainder takes the same VkPipeline; a kernel the variant cannot run exactly (a tile function, a stage-input region, compute derivatives, emulated simdgroups) is refused it, Unsupported{GpuEncodedIndirectCommands, NotImplemented}, and keeps the edges. On the identity domains the variant of a kernel that does not observe its threadgroup partition (KernelFacts::partition_oblivious) runs its grid in tiles instead (RuntimeFact::GridTiles): its plans run a direct dispatch's threads in pipeline::grid_tile's tiles, one workgroup of pipeline::GRID_TILE_THREADS each with the tile as the region's nominal size (MultiRegion 1), the region flagged NONUNIFORM where the tile does not divide the grid, and a range of threadgroups at its own size (MultiRegion 0); the kernel runs the same positions with the same answers: where the region is flagged NONUNIFORM, every invocation compares its position with the region's grid and one past it returns before the body, a test inside one branch on the flag; an unflagged region runs no such test, so a runtime flags every region of a grid its workgroups do not divide. At MultiRegion 0 a runtime may run a direct dispatch of the variant in workgroups of a size it picks, flagged where they do not divide the grid, whose invocations past it return before the body as a tile's do; an indirect dispatch's region states no grid and is unflagged, and all of its invocations run. Device::kernel_observes_partition(&kernel, &inputs, &budget, &entries) answers, before any lowering, what CompiledFunction::observes_threadgroup_partition answers for the compile under the same inputs (from the specialized entry entries holds, ordered for the device where its profile takes the lockstep order), so a runtime lowers only the variant a creation needs. CompiledFunction::is_image_only (KernelFacts::image_only) states, from the AIR alone, a kernel that samples, gathers or reads a texture and loads, stores and updates atomically nothing through a device pointer (constant loads and texture writes allowed), which a runtime may run in square workgroups. On that plan a grid of whole threadgroups, of Threads or Threadgroups, takes the same regions unflagged (each MultiRegion 1, every thread live), so one VkPipeline of a threadgroup size runs all of a kernel's direct dispatches. metal2vulkan-runtime runs a kernel's whole grids there where its module holds 65,536 SPIR-V words or more and its ragged grids run there too: it observes its threadgroup partition (CompiledFunction::observes_threadgroup_partition), and for a one-row grid in threadgroups of one row otherwise than through its simdgroups alone (observes_partition_through_simdgroups_alone, whose such grids run flat). That is one driver compile of the module instead of two: on a guest's run on an RX 7900 XTX, the plain pipeline's compile of a kernel of 2,415,531 words was 26.9 s of a 39.8 s warm pass. Measured once on that GPU (RADV) over four straight-line kernels, the variant ran their whole grids at 0.997 to 1.020 times the plain pipeline's GPU time. Smaller kernels keep the plain pipeline for whole grids. A kernel that steps a stage-in attribute by thread position, or reads [[grid_origin]] or [[grid_size]], needs the encoder's stage-in region:

match plan.instantiate_dispatch(&state, &dispatch) {
    Err(BindError::MissingStageInRegion) => {}
// ...
state.stage_in_region = Some(StageInRegion::new([0, 0, 0], [64, 1, 1]));
let commands = plan.instantiate_dispatch(&state, &dispatch)?;

A tessellation pipeline draws patches, with the factors' buffer in the state:

let factors = TessellationFactorBuffer::new(4096, 0, 0);
state.tessellation_factors = TessellationFactors::new(Some(factors), 1.0);
let plan = pipeline.plan(device, &state.shape())?;
let draw = DrawCall::Patches {
    control_points: 4,
    patch_start: 0,
    patch_count: 16,
    patch_index: None,
    instance_count: 1,
    base_instance: 0,
    control_point_index: None,
};
let commands = plan.instantiate_draw(&state, &draw)?;

What you record from DispatchCommands or DrawCommands:

  • Descriptors. Write each of the plan's descriptors, binding each buffer descriptor over exactly its descriptor_ranges entry. Upload descriptor_bytes (argument and handle tables) and the resident root tables where present. A handle table maps each resident resource's gpuResourceID to its heap element; a consumer that keeps one heap for every command buffer can bind one table of every texture ID instead (bind::handle_entry, bind::heap_element, bind::handle_entry_flags), as the runtime does.
  • Push constants. Write push_constants, and fill each of the push_holes with the device address it names: the uploaded root table, the command buffer's ExecutionStatus buffer, an indirect command buffer's records. A snapshot variant's PushHole::SnapshotPhase is a word, not an address (below).
  • The dispatch or draw. Record regions or draw as given: the binder has already applied Metal's offsets, bases and clamps.
  • Status. Per command buffer, keep one ExecutionStatus buffer for what translated shaders report (a resident-set miss, for one), and read it when the command buffer completes. A plan binds it as WriteSource::ExecutionStatus on a device that does not address buffers: bind the same buffer there, its ExecutionStatus::BYTES bytes.

Snapshot reads

A draw that reads, at its fragments' own pixels, a texture its own subpass renders can read it through a snapshot instead of a copy taken before the render pass instance. The interface lists the fragment slots that allow it (StageInterface::snapshot_textures, StageModule:: snapshot_textures): own-pixel slots whose texels reach no derivative, sample, quad or subgroup operation, branch, integer divisor, dynamic vector index or store outside the invocation, directly or through a call, in a function that writes no memory. A selection on a texel is allowed where its arms leave through its merge alone and hold no derivative, implicit-level sample or level-of-detail query, quad or subgroup operation, loop or undefined operand, nor call a function that does; what its arms leave behind (its merge's phis, the variables they store to) is judged as the texel is. It says why it leaves out each other own-pixel slot (snapshot_refusals: each slot with every SnapshotRefusal that holds for it). Name the slots in BindState::snapshot_textures; the plan keeps those its pipeline can read so and states them in variant.snapshot_textures, each with the form its snapshot holds texels in (SnapshotForm::of the slot's bound view and declared type: the texel's codes for an 8- or 16-bit normalized, half-float or integer format of the slot's class, which a read decodes as Metal reads the format, and the fetched lanes' bits for any other), compiled like any other variant. It keeps none on a device without fragmentShaderPixelInterlock, fragmentStoresAndAtomics, attachmentFeedbackLoopLayout or extendedDynamicState3ColorWriteMask, for a pipeline of more than one sample, a depth or stencil attachment, attachments in the storage form, input attachments, an imageblock, tile memory, a shader-side stencil or tests, tessellation or mesh stages, or a function that writes memory, and for an amplified or layered draw. Serve every other read as before.

A pipeline of that variant states GraphicsState::snapshot_reads: create it with VK_PIPELINE_CREATE_COLOR_ATTACHMENT_FEEDBACK_LOOP_BIT_EXT; its dynamic_states hold VK_DYNAMIC_STATE_COLOR_WRITE_MASK_EXT, and its requirements attachmentFeedbackLoopLayout and extendedDynamicState3ColorWriteMask. Bind the slot's own texture in the attachment's feedback-loop layout, and at WriteSource::SnapshotTexels a storage image of the slot's form's SnapshotForm::format (R8G8B8A8_UINT, R16G16B16A16_UINT or R32G32B32A32_UINT) covering the render area, in GENERAL layout. Record each draw twice in its subpass: first with every color write mask 0 and PushHole::SnapshotPhase set to 1, each fragment copying its texel into the snapshot and running nothing else; then with the pipeline's own masks and the phase 0 (the plan's bytes), each fragment reading the snapshot. A by-region pipeline barrier before the first draw makes the attachment's earlier writes visible to the copy, and one between the two makes the copy visible to the reads and orders it before the second draw's color writes. Each step rests on a sentence of the Vulkan specification: the feedback loop's per-pixel barrier, the color write mask leaving memory unmodified, the invariance of fragment generation under write masks (Rule 2, Corollary 1), and the ordered pixel interlock. One draw alone cannot be exact: nothing orders a fragment shader's read of a texel before the same draw's color write of it.

Where the attachment's image lacks feedback-loop usage (NVIDIA's drivers make no linear image with it), the two draws can run in two render pass instances instead, after the instance before them ends. Record the first in a render pass instance of its own over the framebuffer of the instance that follows, of a render pass compatible with that instance's that loads every attachment and stores none (VK_ATTACHMENT_STORE_OP_NONE, core in Vulkan 1.3 and brought below it by VK_KHR_load_store_op_none or VK_EXT_load_store_op_none), every color in GENERAL and the slot's texture bound in GENERAL, between pipeline barriers from everything before and to everything after; then begin the next instance and record the second draw first in it, with no barrier between the draws. Neither instance enables a feedback loop, and neither needs one: the first writes no color, by its masks or by its load and store operations (VUID-vkCmdDraw-None-10795, VUID-vkCmdDraw-None-12338), and the second's fetch of the texture never runs. The same pipeline serves both, as render pass compatibility ignores load and store operations and layouts. The runtime takes this form for such a read after a memory barrier inside the instance (WorkCounts::reading_draws_snapshotted_leading), where it would otherwise split the instance and copy the texture, and where it weighs cheaper than the split by the scissors' area or, on a device with precise occlusion queries, by the pixels the draw covered in its last measured pass, even over a buffer's bytes: its first draw reads the texture at every pixel the draw covers.

A draw whose pipeline writes no channel of the color it reads so needs no snapshot: the runtime creates its pipeline (the variant without snapshots) with the feedback-loop flag, binds the slot's own texture in the attachment's feedback-loop layout, and records a by-region barrier before the draw, from the color writes to the fragment shader's reads, and one after it, from those reads to the color output (section 10 says what it then reads).

Levels a slot reads

Each texture slot of a stage states the levels of its bound view its reads reach, counted from the view's first level (StageModule::level_reads, one LevelReads a slot): whether some read may reach any level (any: a level the function computes, a level-count query used beyond the containment of a constant level, a level-of-detail query, a sample through no sampler or with a minimum level of detail, a storage access, or a use the analysis does not follow), the highest constant level a fetch, size query or gather names (named) and the lowest whose texels a fetch or gather reads (lowest_read), and its samples by the sampler each reads through (sampled, with the highest and the lowest constant level of detail). A sample's level is its sampler's to bound: ask LevelReads::highest_level with SampledLevels::level of the sampler you bind (SamplerLevels::of its vk::SamplerDesc, and SamplerLevels::finite_texels of the view's format), and LevelReads::lowest_level with SampledLevels::lowest. A view of the same first level and more levels than the highest answer reads what the whole view reads, and no read reaches a level below the lowest answer. The runtime counts with it which levels a draw reads of a texture its own render pass instance renders, and reads in place those that no attachment of the instance renders.

Indirect command buffers

An indirect command buffer's commands are records in ordinary buffer storage (bind::indirect_commands): one format whatever the descriptor, written by the CPU or by a kernel. The binder replays records into dispatches and draws: on the host, or on the device through a preprocessing kernel (replay_preprocess), and through VK_EXT_device_generated_commands where the device has it (replay_preprocess_generated). Draws of primitives under the encoder's pipeline replay on the device through draw_replay_preprocess: one indirect draw per command and primitive type the execution names, the pipeline compiled as its replay variant (VariantKey::replay_bindings), whose vertex and fragment functions read each command's buffers from the slot tables the preprocess writes. The variant pulls every layout fixed-function vertex input would fetch (draw_replay_vertex_layouts, named in the shape's far_vertex_buffers: the pulled-vertex-buffer variant, no buffer bound there), so each attribute reads its command's buffer at the command's own vertex and instance; a layout whose stride is set per bind keeps an execution off the device (DrawReplayRule::VertexAttributes), since each command binds its own stride. Draws of one list type or points whose fragment function reads no buffer and no [[primitive_id]] may instead merge into one draw (DrawReplay::merged): two merge passes (draw_merge_module) write each command's first vertex in the merged draw, and the vertex function, compiled as its merged variant (VariantKey::merged_draws), finds its command by that prefix and runs the command's vertex, instance and buffers, in the commands' order. A kernel that encodes commands writes the records that start at bind::indirect_commands::records_address of the buffer's ID, outside every Metal address, and finds them only at their start: records may run past later IDs' starts, and a resident set (bind::ResidentSet) keeps each records range whole. Each of the kernel's writes of a command's record also stores 1 at the command's written flag, a u32 a command past the records (bind::indirect_commands::written_flag_offset), where the storage holds them; storage that ends at its records takes none. A consumer whose own writes of the records set the flags too resets a run of commands with icb_reset_module, which writes only the flagged records and clears their flags.

7. Caching

The crate keeps no cache; keys and encodings let you keep one across processes. Keys are SHA-256 hashes of the inputs, cache::SEMANTICS_VERSION and the profile fingerprint, known before compiling (device.compute_pipeline_key(&descriptor), render_pipeline_key(&descriptor, &budget), tile_pipeline_key, function_compile_key):

let bytes = pipeline.to_bytes();
let cached = ComputePipeline::from_bytes_for_key(&bytes, &pipeline.key, &device)?;
assert_eq!(cached, pipeline);

A decode checks the format and semantics versions, the key, the profile fingerprint and a checksum. Every ArtifactError is a cache miss: compile again and replace the entry.

Functions cache on their own, so pipelines that share a function share its compile, and a pipeline links a cached function without decoding it again:

let kernel = FunctionDescriptor::new(sampling.function("sample_level")?);
let inputs = LoweringInputs::new();
let key = device.function_compile_key(&kernel, &inputs);
let compiled = device.compile_function(&kernel, &inputs, &budget)?;
let bytes = compiled.to_bytes();
let function = CompiledFunction::from_bytes_for_key(&bytes, &key, &device)?;
let descriptor = ComputePipelineDescriptor::new(StageSource::Compiled(function));
let linked = device.compile_compute_pipeline(&descriptor, &budget)?;
assert_eq!(linked, pipeline);
  • A compiled function states before linking what its stage will: stage(), requirements() (check it against another profile with DeviceProfile::check), precision_notes() (the pipeline's stage adds those of its own state: a fragment stage's attachment writes, a vertex stage's formats its fixed-function vertex input converts), reconvergence(), required_subgroup_size(), requires_full_subgroups(), module_stats() (section 3) and writes_memory() (stores or atomics, which a render pipeline drawn in more than one color group refuses). compile_function_with_report also returns a CompileReport of what the compile cost.
  • A render pipeline's stages compile under inputs that a decode of its functions learns. render_pipeline_key returns RenderPipelineKeys: each stage's function key, and the inputs to compile a missing stage under. So does a compute pipeline's kernel: kernel_inputs_read(&kernel, &inputs, &budget, &entries) narrows the stage-input descriptor to the attributes its entry reads, and the kernel keys and compiles under those, so states that differ only in an attribute it never reads share one compiled function. What a creation reads of the descriptor past the fetch -- its layout agreement, its reflection, and compute_pipeline_key -- reads it whole.
  • A key names an artifact by its inputs and versions; a content digest names it by what it says. pipeline.content_digest() hashes everything but the key and profile, and plan.content_digest() (with serde) everything a plan states. A cache of driver objects keyed on the digest survives a release that bumped SEMANTICS_VERSION without changing the output. A digest identifies content; it authenticates nothing.
  • A caller that names a stage's module by its words need not hash them twice. A compiled function keeps its last relocation beside it, so a sweep of pipeline states over one function pair takes the same Arc<[u32]> on every creation; compiled.relocated_words_digest(&stage.spirv, derive) gives the digest derive produced over those very words, or None where they are not the function's last relocation -- a miss costs no call of derive at all, so it is safe to ask first in a creation's hot path. The digest a caller gets is always one its own derive made, so nothing it names by the digest moves.
  • A memo that holds pipelines in memory and bounds itself by bytes can weigh one it never encoded. pipeline.footprint() is the bytes a RenderPipeline or a ComputePipeline keeps live -- every word of every stage, each stage's constant blob and notes, and its own storage -- so a pipeline kept without to_bytes() is weighed by what it costs rather than by the zero length of an encoding that was not made.
  • Versions move independently: the crate's (the API), SEMANTICS_VERSION (the output), ARTIFACT_FORMAT_VERSION (the encoding) and RUNTIME_VERSION (what the runtime does with an unchanged artifact). SOURCE_DIGEST names the sources a build was compiled from, for caches kept across builds.

8. Refusals, requested inputs, and precision

Every failure is typed; match variants, never messages. A refusal says what would change the answer:

let floor = committed_device("vk12-floor")?;
let min_lod = FunctionDescriptor::new(sampling.function("sample_min_lod")?);
match floor.compile_function(&min_lod, &LoweringInputs::new(), &Budget::standard()) {
    Err(Error::Unsupported(refusal)) => match (&refusal.feature, &refusal.needs) {
        (feature, Needs::AnyOf(alternatives)) => {
            println!("refused {feature:?}: needs any of {alternatives:?}");
        }
        (feature, needs) => println!("refused {feature:?}: {needs:?}"),
    },

Error has these variants:

Variant Means Retry
Unsupported The device cannot run this exactly. feature names the Metal feature, needs what would change it No
NeedsInput The compile needs a pipeline input you did not supply After supplying it
InvalidInput The AIR or container is malformed No
InvalidDescriptor The descriptor is invalid as Metal would refuse it, or names a missing entry No
LimitExceeded A deterministic cap (work units, ledger bytes, output size, structural limits) No
Budget The deadline passed Later
Cancelled The CancelToken was triggered Later
Internal A translator bug (a panic, a verifier failure) No; report it

Needs says what a refusal needs:

  • AnyOf: alternative sets of device capabilities; a device that enables every capability of one set compiles it.
  • NotImplemented: a gap of this version. NotRepresentable: no Vulkan mechanism exists.
  • DriverDefect: a defect the device's driver is measured to have. RuntimeDriverDefect: one in a command the runtime records.
  • StageBound: a stage that the device's plan writes heavier than the translator hands any driver (the heaviest measured to compile within host-sized memory); symbol names its entry weight and the bound. A device whose plan writes it lighter compiles it.
  • MetalGpuFamily: a Metal GPU family the device does not claim, where Metal itself refuses the input without it.

location and symbol are diagnostics only. A render pipeline's refusal of one attachment's state names it (location.attachment()). REFUSALS.md lists every refusal in the code, with its device condition.

A compile that needs an input asks for it (Error::NeedsInput) instead of guessing: a storage texture's format, a linked function, a kernel's stage-input descriptor. Supply it and compile again. A function-constant value is no such input: a constant the request leaves undefined compiles, as plain Metal's does (section 10, "Function constants").

A storage texture's format (RuntimeInput::StorageTextureFormat { slot }) comes from what is bound: metal::format::storage_image_choice(pixel_format, device.profile()), placed in a VariantKey's storage_images and compiled as a variant. The plan asks for it itself where the bound format needs a declared format.

What to cache. error.retry() says whether the same request can succeed later, and error.is_permanent_for() which key may memoize the failure (the input, the input on this device, or never). A BindError from plan depends only on the pipeline, the device and the shape, so it memoizes beside the plan; one from instantiation does not.

Precision. Where an output gives a near-equivalent of Metal's answer, its stage lists it in precision_notes (a PrecisionNote, each documenting its bound), and reconvergence says whether subgroup reconvergence after divergence matches Metal's (Reconvergence::ImplementationDefined where the profile lacks maximal reconvergence). A note that holds only under some bound values is in specialized_notes; stage.precision_notes_bound(&plan.specialization, &|key| plan.specialized_value(key)) gives the notes a plan reaches. Section 9 lists every note.

The runtime's errors are its own type, metal2vulkan_runtime::Error; REFUSALS.md lists its refusals with their basis, and its README states each known gap.

9. Degrade notices

Where an answer may differ from Metal's, the operation carries a precision note (metal2vulkan::pipeline::PrecisionNote), fixed per operation and never decided at run time: by the translated module, the pixel format, the descriptor or the state, on every device. metal2vulkan-runtime gives them through these items:

  • ComputePipelineState::precision_notes and RenderPipelineState::precision_notes: the translator's notes of the state's modules, with SwizzledOpaqueBlackBorder where a function samples through a constexpr sampler whose address mode reads an opaque-black border;
  • Texture::precision_note: CompressedTexelDecode where the texture's own pixel format is block-compressed;
  • SamplerState::precision_note: SwizzledOpaqueBlackBorder where an address mode reads an opaque-black border;
  • DepthStencilState::precision_note: DepthDenormals where the state tests or writes depth;
  • RenderPassDescriptor::precision_note: DeviceRoundedResolve where a color attachment resolves;
  • BlitCommandEncoder::GENERATE_MIPMAPS_NOTE (DeviceFilteredMipmaps, of generate_mipmaps) and RenderCommandEncoder::DEPTH_BIAS_NOTE (DeviceDepthBias, of a draw of triangles under a depth bias).

A note is never fatal: the work runs on every device. The runtime prints and sends no note; a consumer reads them through these items. The translator's own API gives a stage's notes (section 8).

Each entry below is named by a code, metal2vulkan-degrade- and the note's name in kebab case (PrecisionNote::NativeFma is metal2vulkan-degrade-native-fma), with its category, and says what makes an operation carry the note and what may differ. Each PrecisionNote's rustdoc states its bound.

  • metal2vulkan-degrade-device-rounded-resolve (precision). DeviceRoundedResolve: A multisample color resolve averages through Vulkan's AVERAGE mode, which leaves the rounding of the average (and the sRGB encoding) to the device, on a device not measured to round as Metal does: any color attachment but an extended-range one and one resolving into its format's sRGB twin (each resolved after the pass), one a fetching pass's sample planes hold as it ends included (the planes merged back first). Never, whatever the format, on a device whose resolve is measured to round as Metal does (DriverFact::ColorResolveAverageIsMetals: MoltenVK's resolve is Metal's own). Also, on every device, a resolve into an 8-bit UNORM attachment's sRGB twin where the device has the sRGB format: the crate-owned resolve decodes the samples and encodes their average by the device's own sRGB conversions, where Metal's resolve takes its own 12-bit tables (with correctly rounded conversions, 1,758 of the 65,536 pairs of codes at 2 samples land one code from Metal's; MoltenVK 1.4.2 on the M3 Max: 696 of 262,144 channels at 2 samples, one code below; lavapipe, Mesa 26.0.8: 57,865 of 524,288 at 4, within one code). Measured against Metal's rules at 2 and 4 samples on RADV (Mesa 26.0.8, the Radeon 780M and the RX 7900 XTX), ANV (Mesa 26.2.4, the Iris Xe), NVIDIA (615.71, the RTX 5080 Laptop GPU) and lavapipe (Mesa 26.2.4, at 4 samples): every unorm, snorm and packed 16-bit unorm channel within one code of Metal's, an sRGB channel within two (NVIDIA's at 4 samples; one elsewhere). Each rounds an 8-bit unorm tie down (RADV and ANV: 32512 of R8Unorm's 65536 pairs of samples one code below at 2 samples); an sRGB or packed channel lands above Metal's code in some texels and below in others. A float channel's average differs in its last bits, counted and not bounded (RADV: 8565 of R32Float's 65536 channels at 2 samples). Cost: a resolved channel can differ from Metal's by one code (an sRGB channel by two) where the average lies near a rounding boundary, a float channel in its last bits, and wholly where a sample is a NaN or an infinity: Metal's resolve counts a half or small-float NaN as 0 and a half infinity as 65536 of its sign, and makes any 32-bit float NaN 0x7fc00000, where the device's average may keep them. On metal2vulkan-runtime it is the static note PrecisionNote::DeviceRoundedResolve of a render pass that resolves a color attachment (RenderPassDescriptor::precision_note), by Vulkan's AVERAGE in the pass's own rendering, on every device: an extended-range, bfloat or YCbCr attachment's resolve is Gap::RenderPass of RenderPassKind::Resolve, and an integer one is Refusal::ResolveFormat.
  • metal2vulkan-degrade-device-filtered-mipmaps (precision). DeviceFilteredMipmaps: generate_mipmaps of a filtered format (an integer format's texels are picked as plain Metal picks them), the static note BlitCommandEncoder::GENERATE_MIPMAPS_NOTE on every device: each level is the device's linear filter of the one above at the scaled texel centres, its blit chain (vkCmdBlitImage with VK_FILTER_LINEAR); a format the device's blits cannot filter is Gap::MipmapFilter. The device's filter is not Apple's datapath, whose answers also differ between Apple's GPUs (an M3 Max's and an M4's by up to a unit in the last place). No bound against Metal's answer is measured. Cost: a channel can differ from Metal's where the filtered value lies near a rounding boundary, and wholly where a box averages infinities, NaNs or a float format's extremes.
  • metal2vulkan-degrade-capped-lod-bias (precision). CappedLodBias: A sampler state whose lodBias the GPU of the Mac the device presents adds to every sample's level (MacClass::IntelOrAmd), where the device's samplers cannot add it as it is (metal::sampler::DeviceLodBias): past the device's maxSamplerLodBias (an infinity included), a NaN, or a bias other than 0 where the device's portability subset withholds samplerMipLodBias (MoltenVK). Cost: its samples add the device's limit of the bias's sign where the bias is past it, and no bias where the device withholds it or the bias is NaN: a sample whose level with what the device adds has not reached the last level the sampler reads (a positive bias) or level 0 (a negative one) reads another level than Metal's, which adds the whole bias and then clamps the level into the texture's levels; what Metal samples for a NaN bias is not measured. The translator states the same difference as the sampler state's static note, PrecisionNote::CappedLodBias (DeviceLodBias::note), which no pipeline stage records.
  • metal2vulkan-degrade-device-reconvergence (precision). DeviceReconvergence: A stage holds a tangled instruction (a simdgroup or quad operation, or a barrier whose lanes depend on reconvergence) on a device without maximal reconvergence (shaderMaximalReconvergence): after divergent control flow the device decides which lanes run it together, where Metal's lanes reconverge maximally, so such an operation may see other lanes active than Metal's. Under subgroup-uniform control flow (shaderSubgroupUniformControlFlow) the lanes reconverge where control flow is uniform. Static per stage: recorded for any tangled instruction in the entry.
  • metal2vulkan-degrade-snorm-minimum-kept (precision). SnormMinimumKept: A draw in a render pass that loads a single-sampled color attachment of a signed normalized format (R8Snorm, RG8Snorm, RGBA8Snorm, R16Snorm, RG16Snorm, RGBA16Snorm) and does not discard it at the store. Cost: the texels the pass's draws do not write keep their bytes; Metal's pass rewrites a channel's minimum code (-128, or -32768 for 16 bits) as the code above it (-127, -32767) in each tile a draw reaches: a texel whose bytes no Metal write left (uploaded or copied bytes) keeps a code Metal's pass would change. Not on a driver whose pass stores the codes as Metal's (DriverFact::TileStoreIsMetals: MoltenVK on Apple's GPUs, whose pass is a Metal pass). On a device Device::from_queries made (metal2vulkan-runtime's) it is the static note PrecisionNote::SnormMinimumKept of every render pipeline that draws into such an attachment, whatever its passes load, on its fragment stage (its vertex stage where it has none).
  • metal2vulkan-degrade-shared-exponent-kept (precision). SharedExponentKept: A draw in a render pass that loads a single-sampled RGB9E5Float color attachment and does not discard it at the store. Cost: the texels the pass's draws do not write keep their words; Metal's pass normalizes a word whose largest mantissa is below 256 (its exponent above 0) in each tile a draw reaches: a texel whose bytes no Metal write left (uploaded or copied words) keeps a word Metal would change, of the same value. Not on a driver whose pass stores the words as Metal's (DriverFact::TileStoreIsMetals). On a device Device::from_queries made (metal2vulkan-runtime's) it is the static note PrecisionNote::SharedExponentKept of every render pipeline that draws into such an attachment, whatever its passes load, on its fragment stage (its vertex stage where it has none).
  • metal2vulkan-degrade-compressed-texel-decode (precision). CompressedTexelDecode: The static note of every texture or view whose own pixel format is block-compressed (BC1 to BC7, and the ASTC, ETC2 and EAC formats where the device makes them; Texture::precision_note), on every device. The texture's image is its own image of that format, which the device samples through its own decode: no BC texture keeps a decoded twin. The bounds are the largest differences from Metal's texels measured on random blocks of every format; a driver not named is unmeasured. Validation derives no tolerance from them; the conformance suite's BC1 to BC5 decode cases hold each texel to its family's largest bound on any driver (an sRGB form's to the sRGB decode's largest step over 4/255), and its ASTC cases each linear (_LDR) texel to 1/2048, plus both values' rounding to float, justified by the note alone. Cost: a read, sample or gather of its texels answers the device's decode of its blocks (an sRGB form's code through the device's sRGB decode), where Metal interpolates with 6-bit weights: a BC1 to BC3 channel up to 4/255 off Metal's on NVIDIA (615.71.09, the RTX 3090 and RTX 5080 Laptop GPU; BC3's alpha 6/255), 3/255 on lavapipe, 1/255 on ANV; a BC4 or BC5 channel up to 7.4/255 (signed 0.065) on NVIDIA, 1.3/255 (signed 0.013) on ANV, 2.4/255 (signed 0.022) on lavapipe, and on RADV (Mesa 26.2.4, the Radeon 780M) a signed texel with an endpoint of -128 up to 1.7/255; a BC7 channel a float ulp on lavapipe; its blocks' bytes, copies and sizes are Metal's. An ASTC LDR channel is up to 1/2048 off Metal's on ANV (Mesa 26.2.6, the Iris Xe of Raptor Lake-P), over the fourteen footprints. Measured on more drivers: NVIDIA's 620.70.06 (the RTX 2080) a BC1 to BC3 channel 3/255 (BC3's alpha 6/255) and a BC4 or BC5 channel 7.33/255 (signed 0.064); ANV (the Iris Xe of Raptor Lake-P) and Intel's Windows driver (the UHD 630) BC3's alpha 2/255 and a BC4 or BC5 channel 1.4/255 (signed 0.0134), a BC4 or BC5 texel within 0.0001 of the specification's exact decode there, so what moves is Metal's 6-bit weights.
  • metal2vulkan-degrade-depth-denormals (precision). DepthDenormals: A write that may store a denormal in the 32-bit float depth of a depth image (a pass's clear to one, a blit's copy into a Depth32Float or Depth32Float_Stencil8 texture's depth, a replace_region whose bytes hold one), on a device whose driver stores one a write on the GPU gives it as a zero (no DriverFact::DepthImageKeepsDenormals: RADV, ANV; a host copy keeps it) or whose depth test compares one otherwise than Metal's (no DriverFact::DepthTestKeepsDenormals: every driver measured but MoltenVK on an Apple M4). Cost: a denormal depth may read, sample and copy out as a zero, or the depth test may compare it as zero (a positive one) or below zero (a negative one), where Metal keeps it and compares a positive one above zero and a negative one not below it. On metal2vulkan-runtime it is the static note PrecisionNote::DepthDenormals of every depth-stencil state that tests or writes depth (DepthStencilState::precision_note), on every device, with no driver fact.
  • metal2vulkan-degrade-f16-fma-double-rounding (precision). PrecisionNote::F16FmaDoubleRounding: Widened half fma rounds twice.
  • metal2vulkan-degrade-f16-int-conv-double-rounding (precision). PrecisionNote::F16IntConvDoubleRounding: Widened half-integer conversions round twice.
  • metal2vulkan-degrade-grad-from-bias (precision). PrecisionNote::GradFromBias: Bias sampling emulated with gradients may pick another level and another anisotropic footprint than Metal's: derivatives hoisted out of a per-fragment texture choice, which scale by 2^B through every sampler, and, on a device that does not sample through Metal's own sampler, a bias whose sum with the sampler's own may lie beyond the device's maxSamplerLodBias, which Vulkan clamps, or that an anisotropic sampler applies to its footprint's minor axis alone. On a device without maintenance8, a fragment's implicit-level sample with a dynamic texel offset samples with its derivatives too, taken before the switch over the offset's values (docs/FAST-PATHS.md).
  • metal2vulkan-degrade-device-transcendentals (precision). PrecisionNote::DeviceTranscendentals: Transcendentals answer within Apple's stated bound, not Metal's bits: the device's own functions where they are Metal's (MoltenVK), and the device's precision for a call no other note bounds. Apple states no answer at a NaN operand under fast math, and where the device's compiler takes one math mode for the whole entry (MoltenVK) a precise function of a fast-math entry answers by its fast form, so a NaN operand may answer a number (precise::sin and precise::cos of a NaN answer 0 on the Apple M3 Max through MoltenVK 1.4.2, where Metal answers the NaN).
  • metal2vulkan-degrade-reduction-order (precision). PrecisionNote::ReductionOrder: Float reductions use the device's association order.
  • metal2vulkan-degrade-device-denormals (precision). PrecisionNote::DeviceDenormals: float denormals follow the device: Metal reads an f32 denormal operand of its float arithmetic, comparisons, and functions as the zero of its sign and flushes a denormal result to one, where a Vulkan device keeps or flushes them by its own float controls (this translation declares no DenormFlushToZero). Recorded where the module leaves an operation's denormals to a device not measured to read them as Metal does: + - *, the comparisons, fma, dot, sqrt, rsqrt, trunc, rint and ldexp on float (by the device's products) but on a device that takes the measured DriverDeviation::MetalFloatDenormals, and those on such a device too in an entry that declares the 16-bit float controls where its driver is measured to keep them there (DriverWorkaround::FloatDenormalsKeptUnderHalfControls: NVIDIA's on the RTX 3090 and the RTX 5080 Laptop GPU, whose module then requires no VkProperty::MetalFloatDenormals); fneg, fabs, floor and ceil on float but on a device that takes the measured DriverDeviation::MetalUnaryDenormals (MoltenVK on the Apple M3 Max's macOS 27 identity, whose module then requires VkProperty::MetalUnaryDenormals); and on every device the divisions and the remainder, the device's maths functions (fast::fmod's fused multiply-add, sign and fract among them), mix by FMix, fast::sqrt by Sqrt, dot of vectors of other than two to four lanes, whose chunks' products the device sums where Metal flushes each one below 2^-126, and a conversion to or from double, where Metal's reading is not measured. The operations that read a denormal on its bits answer Metal on every device: copysign and atan2; and so do the functions the device answers as Metal's own. Where the minimum and maximum functions and saturate are the device's NMin, NMax and NClamp, their pick of a denormal is NativeMinMax's. Off MoltenVK the device's multiply and fused multiply-add, and ldexp on float by that multiply, round a result whose exact value is below 2^-126 up to 2^-126, which Metal flushes. A nearest pixel-coordinate sample at its texel's centre floor(x) + 0.5, and a pixel fetch at floor(x) + k under an offset, records it for that floor: Metal's sampler reads a negative subnormal x as texel -1, where MoltenVK's floor reads it as the zero of its sign, texel 0 (an Apple M3 Max). An address mode that reads texel -1 as texel 0 (clamp to edge, mirror clamp to edge, mirrored repeat) answers alike, so the sample records it only where its s or t mode is repeat, clamp to zero or clamp to the border: through a constexpr sampler of such a mode; through a runtime sampler slot only under a pipeline made for a nearest pixel state (SpecKey::NearestPixelSampler), never under a normalized one, and there where the bound state is of such a mode (SpecKey::BoundSamplerWord); through an argument buffer's sampler argument-pixel-sampler-scaling records it instead. A pixel fetch under an offset records it outright.
  • metal2vulkan-degrade-pixel-sampler-scaling (precision). PrecisionNote::PixelSamplerScaling: A pixel-coordinate sampler's coordinate reaches the device's normalized sampler divided by the texture's level-0 size in the shader, and the device reads its texels and weights from that coordinate in its own arithmetic: within a few units in the last place of the edge of a linear filter's pair of texels, a gather's block or one of the filter's sub-texel steps it may read the neighbouring pair, block or step, where Metal's sampler reads the coordinate as given. Recorded for a linear sample, a gather and a level query through a constexpr pixel sampler of an array, a 3D texture or a texture whose residency the function observes, and through a runtime sampler slot (where the bound state reads pixel coordinates, and for a sample or comparison where it is not a nearest one of one isotropic level). Measured: the device's normalized sampler's answer within one f32 ulp of the quotient on MoltenVK and at the quotient on lavapipe; a linear downscale by 8 within 1/255 of Metal's on MoltenVK and 2/255 on lavapipe. Under the identity domains it is also recorded for a linear sample and a gather through any constexpr pixel sampler, whose device sampler the consumer makes normalized. Nothing is recorded where Metal's texel or footprint follows from the coordinate itself: elsewhere a constexpr pixel sampler's sample or gather of a 1D or 2D texture that is no array hands the coordinate, moved by its offset, to the device's unnormalized sampler; a nearest sample elsewhere hands the device its texel's centre, where the device reads exactly Metal's texel; and a nearest constexpr sampler clamped to the edge fetches its texel.
  • metal2vulkan-degrade-device-arithmetic (precision). PrecisionNote::DeviceArithmetic: Float division, remainder, square root, fused multiply-add, and dot products use Vulkan's precision bounds (e.g. 2.5 ULP division, a possibly unfused Fma) rather than correct rounding.
  • metal2vulkan-degrade-device-signed-zero-inf-nan (precision). PrecisionNote::DeviceSignedZeroInfNan: Float operations LLVM requires to keep signed zeros, infinities, and NaNs run without SignedZeroInfNanPreserve, which the device does not support at their width. Without the mode the device may answer such a zero with either sign.
  • metal2vulkan-degrade-device-ray-intersection (precision). PrecisionNote::DeviceRayIntersection: A ray intersection traversed by the device's ray query.
  • metal2vulkan-degrade-fast-math-rewrites (precision). PrecisionNote::FastMathRewrites: Float arithmetic whose AIR lets a compiler rewrite it with a neighbouring operation: an addition or subtraction and the multiply feeding it both carry LLVM's contract, two chained additions, subtractions, or multiplies both carry reassoc, or an llvm.fmuladd (fused or not, as the implementation chooses). The module states each operation in the AIR's order with its own flags: one carrying both contract and reassoc is the device's compiler's to group and fuse, any other is kept apart (NoContraction); Metal's compiler groups and fuses by its own choice. On a device without shaderFloat16, a chain of such half additions, subtractions and products is held at float precision between the roundings where its values leave it (HalfChainPolicy::AtExits, the default; HalfChainPolicy::EachOperation rounds each). On MoltenVK a half addition, subtraction or product carrying both flags is the 16-bit instruction left undecorated, whose conversions Metal's fast compile folds away: the float result, unrounded. Cost: a sum of mixed signs grouped otherwise, or a multiply-add fused on one side alone, differs from Metal's by any amount relative to the result; a held half chain, or a MoltenVK half operation left to the compiler, by the roundings it skips, a value inside it past half's range staying finite.
  • metal2vulkan-degrade-tessellation-winding (precision). PrecisionNote::TessellationWinding: A tessellation pipeline's vertex order: Metal's clockwise output winding is declared VertexOrderCcw and its counter-clockwise one VertexOrderCw, as MoltenVK maps them under Vulkan's default upper-left domain origin. Measured for both windings against Metal's bytes (recorded on an Apple M3 Max) by a consumer's device test, tessellation_states_tessellate_as_metals, on RADV (Radeon 780M, RX 7900 XTX), NVIDIA Turing and MoltenVK; other drivers are not measured.
  • metal2vulkan-degrade-tessellation-factor-edge-cases (precision). PrecisionNote::TessellationFactorEdgeCases: A tessellation pipeline's factors at the edges of Metal's stated rules: a subnormal edge factor is positive and does not cull (its level is the range's lower end), where a flush to zero would cull the patch; and a NaN inside factor's level is the range's lower end.
  • metal2vulkan-degrade-tessellation-factor-scale (precision). PrecisionNote::TessellationFactorScale: A tessellation pipeline with tessellationFactorScaleEnabled multiplies each factor by the encoder's scale rounded to half, exactly in float, after the cull.
  • metal2vulkan-degrade-tessellation-factor-instance (precision). PrecisionNote::TessellationFactorInstance: A tessellation pipeline whose factor step function is per instance reads instance i's factors at i · instanceStride, i counting the draw's base instance as [[instance_id]] does.
  • metal2vulkan-degrade-tessellation-fractional-spacing (precision). PrecisionNote::TessellationFractionalSpacing: A tessellation pipeline of a fractional partition (fractionalOdd, fractionalEven) drawn through the device's tessellation stages: Vulkan leaves where a fractional spacing places its vertices to the implementation (its two shorter segments' length need only fall monotonically with the rounded level less the level, and their place on the edge is the implementation's), where Metal's tessellator places them by its own rule. Measured equal to Metal's, at factors within the device's range, by a consumer's device tests on RADV (Radeon 780M, RX 7900 XTX), NVIDIA Turing, ANV (Intel Iris Xe) and MoltenVK; other drivers, lavapipe among them, and factors past the range are not measured. A device without tessellationShader draws Metal's tessellator through the emulation and records none.
  • metal2vulkan-degrade-tessellation-triangle-order (precision). PrecisionNote::TessellationTriangleOrder: A tessellation pipeline drawn through the device's tessellation stages (a device with tessellationShader) whose tessellator is not Apple's (every driver but MoltenVK on an Apple GPU, DriverWorkaround::TessellatorNotMetals): the device's tessellator orders each patch's triangles, picks each one's first corner, and joins the patch's rings where Vulkan leaves that to the implementation. The domain points are Metal's; a flat varying, a value interpolated across another triangulation, and the order a patch's triangles blend in may differ.
  • metal2vulkan-degrade-unmeasured-group-speculation (precision). PrecisionNote::UnmeasuredGroupSpeculation: A function holds a branch whose arms hold a quad or simdgroup operation that answers over every lane of the branch's block when Metal's backend speculates the arms (a quad shuffle, broadcast or vote, a simdgroup shuffle, simd_is_first), where no measurement says whether Metal speculates them: an arm of an instruction, size or shape no probe covers. The branch keeps the AIR's lanes, so that operation may answer over the lanes that take the arm where Metal's answers over the block's. A branch Metal was measured to speculate is speculated, and one it was measured to keep is kept, with no note.
  • metal2vulkan-degrade-not-mipmapped-anisotropic-filter (precision). PrecisionNote::NotMipmappedAnisotropicFilter: A sample at an implicit level or with gradients through a constexpr sampler with anisotropy, no mip filter and different minification and magnification filters, on a device that samples through Metal's own sampler (MoltenVK on Apple's GPU): no level clamp the device's sampler takes reads Metal's NotMipmapped footprint at maxAnisotropy 2 to 16, so the sample filters another anisotropic footprint than Metal's.
  • metal2vulkan-degrade-device-sample-level (precision). PrecisionNote::DeviceSampleLevel: An extended-range texture's (BGR10_XR, BGRA10_XR and their sRGB twins) fragment sample at an implicit level, or with explicit gradients, on every device: its texels are read in the shader, at Vulkan's level of detail computed there and Metal's level rule, where a constexpr sampler states a mip filter or a runtime sampler's word does. The device takes the level of detail by Vulkan's rules, whose scale factor may be approximated; Metal's level of detail from derivatives is not measured. The sample may read another level or filter than Metal's near a boundary.
  • metal2vulkan-degrade-unmeasured-fetch-blend (precision). PrecisionNote::UnmeasuredFetchBlend: A fragment function reads a color attachment the pipeline blends, on a device that orders framebuffer fetch only through the pixel interlock (MoltenVK, RADV, ANV), of a format whose Metal blend arithmetic is not built: a format whose channels read as floats but a 16-bit float, a 32-bit float, an sRGB and an extended-range one (a 16-bit normalized, 8-bit signed normalized, 10-bit, packed float or A8Unorm format, among others), an 8-bit unorm one written by an output of fewer than four lanes, a 32-bit float one (R32Float, RG32Float, RGBA32Float) written by an output of fewer than four lanes, by a module without fast math, or under a blend state the one sweep that measured that family does not fit: a color or alpha arithmetic of more than a lone term, a lone fused multiply-add, or a minimum or maximum, outside the states measured word for word. A one-channel attachment's SourceColor over DestinationColor is such a state, and so is a blend color's difference, which a 16-bit float attachment's blend fits and a 32-bit float one's does not; a lone term that reads the blend color, OneMinusBlendColor over Zero among them, is fitted and takes the exact form. Also a 16-bit float or 8-bit unorm one under a blend of the second source or beside a second (index 1) output. No Vulkan blend applies to the storage write, so the shader computes the pipeline's blend in float: each factor, product and sum rounded to nearest even, the source and the blend color clamped first to a normalized format's range (a NaN to its low end), an output's missing lane zero, and the result stored through the device's conversion. Metal's blend arithmetic for these formats is not measured, so the bound is not known. A factor of the second source reads the function's second output, clamped as the source. An 8-bit sRGB attachment (R8Unorm_sRGB, RG8Unorm_sRGB, RGBA8Unorm_sRGB, BGRA8Unorm_sRGB) under a blend of the second source, a one- or two-channel one under a lerp, each in a module compiled with fast math, and one written by an output of fewer than four lanes, record it too: the shader computes Metal's 8-bit unorm blend's rounded forms over the decoded texel, in the output's type (a missing lane zero), and stores the result by the device's sRGB encode (DevicePackConversion), Metal's blend without fast math at four lanes; under fast math Metal regroups the blend, unmeasured.
  • metal2vulkan-degrade-unordered-fetch-within-draw (precision). PrecisionNote::UnorderedFetchWithinDraw: A fragment function reads a color attachment (framebuffer fetch) on a device with neither rasterization-order color attachment access nor fragmentShaderPixelInterlock (Honeykrisp on Apple's M2 Pro; RADV on the RX 550). It reads the attachment as an input attachment, and the runtime records a barrier of the draws' subpass's dependency on itself, by region, before each draw that reads input attachments after an earlier draw of its render pass instance, or its load operations, wrote a color, and before each draw that writes a color after an earlier one read them (WorkCounts::fetch_draw_barriers): a fetch reads what every earlier draw stored at its pixel, Metal's answer. Under the identity domains it reads the attachment's texture at its own pixel instead (PushField::FetchedColor), and the consumer orders each fetching draw after the earlier draws of its pass by a barrier between them (the new runtime's Metrics::attachment_loop_reads, or its copies into the attachment's shadow on a device without the attachment feedback loop). Vulkan orders nothing between the overlapping fragments of one draw there, where Metal orders them in primitive order: a fragment that covers a pixel an earlier fragment of its own draw covered may read the texel from before that fragment's write. Exact for a draw whose primitives do not overlap at a pixel; otherwise each such pixel holds the result of some order of the draw's fragments there. A raster order group on the color input, or on a color output of an attachment the function reads, takes the same form.
  • metal2vulkan-degrade-fp8-value (precision). PrecisionNote::Fp8Value: An 8-bit float converts to an integer from the format's documented value with Metal's saturating float-to-integer rule, where Metal's device here answers otherwise: Metal on Apple M3 compiles these reads but extends the carrier byte as an integer, the same for every format, so the result is unverified on Metal.
  • metal2vulkan-degrade-multisample-position (precision). PrecisionNote::MultisamplePosition: A fragment function of a render pipeline that rasterizes more than one sample reads a value Metal reads at the pixel center in every invocation and Vulkan evaluates at an implementation-defined position within the fragment: [[position]]'s z or w (the interpolated depth and 1/w, whose position Vulkan does not state), a center-sampled varying on a device without its pixel form (interpolation functions whose InterpolateAtOffset reads from the pixel center: "an implementation-defined position within the fragment area being shaded"), a centroid varying or an interpolant read through interpolate_at_centroid (anywhere in the fragment's covered area, where Metal, measured on Apple M3 Max, moves it to the lowest covered sample's location only under partial coverage), an interpolant read through interpolate_at_center as a center varying, [[point_coord]] ("the fragment center, or the location of a sample"), or [[barycentric_coord]] (its builtin). A function that runs per sample under sample shading reads all but the center varying where Vulkan evaluates them for its sample, where Metal reads every one as the pixel's in each sample's run (Apple M3 Max at 4x, measured). Each is evaluated at a point of the pixel, so it differs from Metal's by at most its change over half the pixel's diagonal, and a centroid varying by at most its change across the pixel's covered area; exact where the device evaluates a read where Metal does.
  • metal2vulkan-degrade-rasterization-rate-map (precision). PrecisionNote::RasterizationRateMap: A render pass drawn by regions over a rasterization-rate map that is not the identity: its regions' lines are this crate's tiles' exact lines, where Apple's are its fixed-point ones, so a fragment's evaluated point lies within a bounded distance of Metal's.
  • metal2vulkan-degrade-bicubic-filter-arithmetic (precision). PrecisionNote::BicubicFilterArithmetic: a filter emulated by fetches (Metal's bicubic filter on every format, and an extended-range texture's linear, 3D and linear-mip-filter samples) sums its taps in the device's arithmetic: the Catmull-Rom weights computed in f32 from the fraction, the taps summed by the device's multiply and add, a bilinear, trilinear or level blend by its FMix at the f32 fractions, and a half result the device's narrowing. The footprint, addressing, filter choice, level and clamps are Metal's. Metal's fixed-point weights, exact grid sums, float accumulators and sixty-fourth level fractions are not reproduced: a lane may differ by a few grid steps (1/4080 at 8 bits), by up to 2.1e-3 on an extended-range sRGB texture's bicubic sample, and by up to 1/64 of the two levels' difference under a linear mip filter. Measured for the bicubic filter by the conformance case bicubic-texel-classes (Metal on an Apple M3 Max, macOS 27.0.1): Metal's results lie on the format's grid, a sixteenth of a code for RGBA8Unorm, R8Unorm and RGBA8Snorm, a whole code for RGBA16Unorm and an exact half for RGBA16Float, and at the six RGBA16Float samples whose sum lies exactly halfway between two halves Metal rounds away from zero. Ours is the unrounded f32 sum; R32Float's samples compare exactly. The largest difference per format, float and half results together, over lavapipe, the M3 on KosmicKrisp and on MoltenVK, a Radeon 780M, an RTX 3090 and an Iris Xe: RGBA8Unorm 2.44e-4, R8Unorm 1.53e-4, RGBA8Snorm 4.88e-4, RGBA16Float 3.74e-4, RGBA16Unorm 2.16e-4 on lavapipe, KosmicKrisp and the 3090 and 7.8e-6 elsewhere (lavapipe's half results keep their f32 values). Through a runtime sampler slot it holds only where the bound sampler filters (a linear minification or magnification filter, anisotropy, a cubic filter or a linear mip filter): a nearest sampler's sample is the decoded texel at Metal's position. Through an argument buffer it holds only where the command can name a texture held by its raw texels in a form the function filters (BGR10_XR, BGRA10_XR, the padded forms; not a bfloat one).
  • metal2vulkan-degrade-sparse-residency (precision). PrecisionNote::SparseResidency: A stage samples or gathers a texture whose residency it observes (sparse_color::resident()) through the slot's sparse form, which the module has where the profile enables shaderResourceResidency: the word is the device's OpImageSparse* residency, whose footprint may count a texel of zero weight Metal does not, and an unmapped texel's lanes the device's non-resident value. Where the device has no residency of its own, the slot's tile map answers Metal's footprint rule exactly, unrecorded.
  • metal2vulkan-degrade-device-nan-encoding (precision). PrecisionNote::DeviceNanEncoding: A float NaN result's bit pattern follows the device: Metal answers the canonical 0x7fc00000 for the NaN results of its float arithmetic and functions, and Vulkan states no encoding, so a device may answer another sign or payload (llvmpipe: 0xffc00000). Also a blend a fragment function computes into a 16-bit float attachment through the pixel interlock: a NaN of the blend is the device's arithmetic's, which the storage image's store converts, where Metal stores every NaN of the blend as 0x7e00. A texture write records it where the stored NaN is the device's: a constant texel none of whose lanes is a NaN records nothing, and a half or float write through an argument buffer holds only where the command can name a texture of a format family whose stored NaN is the device's (for a half write on MoltenVK on the Apple M3 Max, a 16-bit float one; a 32-bit float or RG11B10Float one stores Metal's; for a float write, a 16-bit float or RG11B10Float one). So does a fragment function's color output where the device's conversion stores its NaN, but one every return of which holds such a constant records nothing. Exempt: a half texel's write to a 32-bit float storage image on a profile that takes DriverDeviation::MetalNanMoves (the image stores the widened float's bits, Metal's 0x7fc00000; the module requires VkProperty::MetalNanMoves), and a float or half texel's write to a packed small float one (RG11B10Float) on a profile that takes DriverDeviation::MetalSmallFloatNans: MoltenVK on Apple's GPUs of the Apple M3 Max's macOS 27 identity, measured byte for byte against plain Metal over every half and 33,792 float words, 16,446 NaNs among them, and lavapipe, whose stores of 32,766 float NaNs and every half NaN are Metal's canonical field NaN (the module requires VkProperty::MetalSmallFloatNans); and a half read, sample or gather of a texture slot bound to a 32-bit float or packed small float format (RG11B10Float, RGB9E5Float) on a profile that takes DriverDeviation::MetalHalfConversion, the same identity, whose half of such a texel is Metal's, its NaN 0x7e00 (the module requires VkProperty::MetalHalfConversion).
  • metal2vulkan-degrade-restricted-depth-range (precision). PrecisionNote::RestrictedDepthRange: The device compares a depth texture's texels on a device without VK_EXT_depth_range_unrestricted enabled (MoltenVK on the M3 Max, ANV on the Iris Xe, RADV), where Vulkan gives a depth image no value outside [0, 1], whatever its driver is measured to keep: an upload into a 32-bit float depth is refused (Gap::FloatDepthUpload), and a render write is clamped to the viewport's depth range. A comparison of a texel Metal holds outside [0, 1] can differ; one within it is exact.
  • metal2vulkan-degrade-cube-gradient-footprint (precision). PrecisionNote::CubeGradientFootprint: An explicit-gradient sample of a cube texture takes Metal's footprint in a form a Vulkan device reads alike, but for what is not reproduced. Cost: off MoltenVK the sample takes the device's logarithm of Metal's footprint and, if anisotropic, the device's taps, so a level or blend near a boundary can differ from Metal's. Where the shader takes Metal's level and taps itself (PrecisionNote::AnisotropicFilter) this note is not recorded. On a MoltenVK release or GPU whose cube-gradient route is not measured the sample takes Vulkan's rule's form, the device's reading of it. Through MoltenVK's vertex and fragment stages under macOS 27, an isotropic sample is Metal's, but an anisotropic sample on a cube's +Y or -Y face loses the gradients' z component to SPIRV-Cross's spvGradientCube, so its ellipse lies on the face's diagonal (docs/FAST-PATHS.md's known gaps). A kernel's samples through MoltenVK are Metal's own, with no note.
  • metal2vulkan-degrade-half-texel-conversion (precision). PrecisionNote::HalfTexelConversion: The module reads, gathers, or samples a texture with a half result, the device's float texel rounded to nearest even on every device: within one half ulp of Metal's, but a 32-bit float texel's sample past ±65504, the infinity where Metal saturates. On MoltenVK, whose float texel is Metal's, where the command binds a texture of a class whose Metal half differs from it (a 32-bit float texel's sample, but where the profile takes DriverDeviation::MetalHalfConversion, measured on the Apple M3 Max to answer Metal's half of every float word; a 16-bit normalized texel; a format not measured) and a two-plane YCbCr texture on the grid 8192 at a slot sampled through a runtime sampler (a sample of one texel is the device's rounding of its step: toward zero on MoltenVK 1.4.2 over the Apple M3 Max, within one half ulp of Metal's ties-away rounding, measured over 8,409 channels; unmeasured on other Apple GPUs); a heap element or a depth texture wherever it is accessed.
  • metal2vulkan-degrade-half-sample-filter (precision). PrecisionNote::HalfSampleFilter: The module samples a texture with a half result through a filter (linear minification or magnification, a linear mip filter, anisotropy, or a runtime sampler slot whose bound sampler filters so) that Metal's own sampler (MoltenVK) answers otherwise than Metal filters the format bound there: a two-plane YCbCr texture's, at a slot or held by an argument buffer; or, on any device, a linear sample by Vulkan's Y′CbCr model of a 4:2:0 texture's planes read in place (YCbCrInPlacePolicy::Model).
  • metal2vulkan-degrade-srgb-texel-decode (precision). PrecisionNote::SrgbTexelDecode: The module reads, samples, or gathers a texture with a half or float result through the device's sRGB decode, or decodes the device's filter of its codes, where the texture may be bound in an 8-bit sRGB format. The device's decode is the only form wherever it samples the format (an 8-bit sRGB format, or the sRGB form of a BC, PVRTC, ETC2, EAC or ASTC format, through the texture's or its decoded twin's sRGB view), so it holds where a command binds such a texture, at an argument buffer's texture access, and for a render pipeline that reads an sRGB color attachment as an input attachment; never on MoltenVK, whose decode is Metal's own. Where the device holds the format as its UNORM twin, or a storage texture holds it through its UNORM alias (at a slot, or held by an argument buffer), the module decodes the codes (or the device's filter of them) by the MSL transfer through the device's Pow, at every such access on every device.
  • metal2vulkan-degrade-float-sample-filter (precision). PrecisionNote::FloatSampleFilter: The module samples a texture with a float result through a filter that Metal's own sampler (MoltenVK) answers otherwise than Metal filters the format bound there: a two-plane YCbCr texture's, at a slot or held by an argument buffer; or, on any device, a linear sample by Vulkan's Y′CbCr model of a 4:2:0 texture's planes read in place (YCbCrInPlacePolicy::Model).
  • metal2vulkan-degrade-function-storage-assumed (precision). PrecisionNote::FunctionStorageAssumed: A vertex or fragment function keeps more private memory (its allocas, a call stack among them, or constants held as Private variables) than the floor, 16 KiB a thread, on a device whose Function storage was not measured, up to the 192 KiB a thread Metal was measured to hold (device::function_storage). The risk is the driver's: past what it holds it can answer wrongly or hang the GPU with no error.
  • metal2vulkan-degrade-quads-counted-before-discard (precision). PrecisionNote::QuadsCountedBeforeDiscard: A fragment function runs a non-quad simdgroup operation (a reduction, scan, ballot, broadcast, shuffle, vote, or simdgroup matrix) before a discard on a path to it, in a shape where Metal's placement of it is not known.
  • metal2vulkan-degrade-view-base-texel-offset (precision). PrecisionNote::ViewBaseTexelOffset: The module places a texel offset on an axis that may repeat or mirror as Metal does in an access of an argument buffer's texture: in an emulated raw sample (heap_raw) or a bicubic filter's footprint.
  • metal2vulkan-degrade-device-color-conversion (precision). PrecisionNote::DeviceColorConversion: A fragment function writes a float to a color channel whose conversion the device makes where it is not measured to make Metal's: a normalized, sRGB or small float channel on a device other than MoltenVK on an Apple GPU not measured to convert that kind as Metal does, an attachment that blends with factors other than one and zero (ChannelWrite::Device), the alpha of attachment 0 under alpha-to-coverage, a format whose conversion Metal was not measured with (the packed 16-bit unorm formats, A8Unorm, the packed floats). Near a tie between two codes the device may store the other one: the RTX 5080 Laptop GPU (NVIDIA 615.71.09) stores 0.5 in an 8-bit unorm channel as 0x7f, and the lower code of every input up to two f32 steps above a tie, where Metal stores 0x80 and rounds the exact product to nearest, a tie up; ANV, RADV and lavapipe round the f32 product with ties to even. Also a float texel a function writes to a storage texture that may hold a normalized or half-float format, or ARGB8Unorm, on a device not measured to store Metal's codes (or a 1-bit alpha, on one measured to store every other normalized channel's); an integer texel written into a storage texture of the float class that may hold a half-float or small-float format, which Metal rounds to nearest even and the device's store as it rounds a float (toward zero on every measured driver, one unit in the last place, a finite value past 65504 stored as 65504); and a fragment function's float blend into a 16-bit float attachment through the pixel interlock on a device not measured to round a half store as Metal does, and a blend into an 8-bit unorm attachment through the pixel interlock, whose result the storage image's store converts to its code, or into an ARGB8Unorm attachment over its input attachment where no Vulkan blend state on its rotated image gives Metal's (a destination alpha in a color factor, say), whose result the attachment's write converts; and a render pipeline's private logic operation that the fragment function computes on a device without logicOp into an 8- or 16-bit unorm or snorm attachment, which converts the output to the codes it operates on by the device's float product rounded to nearest even where Metal rounds the exact product (the two differ only near a half-code tie). The recorded bound past one code, measured on lavapipe against plain Metal on an Apple M3 Max: a blend into an 8-bit unorm attachment (RGBA8Unorm, ARGB8Unorm) within 2 codes of Metal's; a fragment function that fetches an 8-bit sRGB attachment and writes it again, within 2 codes once a later draw reads an earlier one's code (with srgb-texel-decode); a blend into an 8-bit sRGB attachment, within 4 codes; a blend into a 4-sample A1BGR5Unorm attachment the device renders itself (Mesa 26.2.4), within 2 codes, over a sample whose fill it stored a code from Metal's. RADV (Mesa 26.2.6 on the Radeon 780M) blends into an RGB9E5Float attachment it renders itself a source whose channels and alpha are halves rounded toward zero, a value past 65504 as 65504, where Metal blends the floats (Vulkan asks a blend for no more precision and range than the attachment's): at 2 and 4 samples, 30 of 96 blended samples are not Metal's, up to 33 units of the larger value's last mantissa bit apart where the source passes 65504, and 7 where the half's alpha weighs a destination far larger than the source. Another device is not bounded past one code (an NVIDIA RTX 5080 Laptop GPU's blend into an 8-bit sRGB attachment stored up to 11 codes from Metal's).
  • metal2vulkan-degrade-device-interpolation (precision). PrecisionNote::DeviceInterpolation: A fragment function reads a varying the device interpolates (center_perspective, centroid, sample or no_perspective, not flat) on a device not measured to interpolate as Metal does (DriverDeviation::MetalInterpolation, which MoltenVK takes: Metal interpolates there). Vulkan states no precision for interpolation, and RADV, ANV, lavapipe and NVIDIA's driver each round most interpolated lanes otherwise than Metal, up to about 1.5e-4 apart (3e-4 on lavapipe) on the probes. RADV's read of a perspective input at a sample or an offset is further off, and records extrapolated-interpolation.
  • metal2vulkan-degrade-device-interpolation-offset (precision). PrecisionNote::DeviceInterpolationOffset: A fragment function reads an interpolant through interpolate_at_offset, which Metal evaluates at the offset as given from the pixel's upper-left corner, at any distance and on no grid (an Apple M3 Max, macOS 27.0.1: 0.999 read at 0.999, 1e9 extrapolated, a NaN or infinite offset NaN). The device reads at the offset moved to its origin (the pixel center; 7/16 on MoltenVK) and clamped to its [minInterpolationOffset, maxInterpolationOffset], which Vulkan requires, a NaN to the minimum, and rounds it to its subPixelInterpolationOffsetBits (at least sixteenths): within the range the read lies within half a step of Metal's, past it at the range's nearer end. On MoltenVK Metal reads the offset itself, so within the range ([-1/16, 15/16] from the corner on the M3 Max) the read is Metal's.
  • metal2vulkan-degrade-extrapolated-interpolation (precision). PrecisionNote::ExtrapolatedInterpolation: A fragment function reads a perspective input at a sample or an offset (interpolate_at_sample, interpolate_at_offset, or a sample-qualified varying a function looping over its covered samples reads at each pass's sample) on RADV (DriverWorkaround::PerspectiveReadsExtrapolated), whose driver answers such a read with the value at the pixel center extrapolated along the quad's coarse derivatives, where Metal interpolates in perspective at the location itself. The answer is first-order, off by the value's curvature across the distance, which grows with the triangle's spread of clip w: on a triangle of w 1, 2 and 4 over a 6x6 target, up to about 1.0 in a lane whose vertices hand 3, -2 and 0.5 (the Radeon 780M, Mesa 26.2.6). A no-perspective input is exact there and records nothing. It is the device's own interpolation, which Vulkan states no precision for.
  • metal2vulkan-degrade-quads-split-by-clipping (precision). PrecisionNote::QuadsSplitByClipping: A fragment function runs a quad or simdgroup operation on a device that shades a triangle it clips as several triangles (DriverWorkaround::ClippedTrianglesSplitPixelFragments): a quad a seam between the pieces crosses runs once per piece, each run with the other piece's pixels as helper invocations, so the operation counts or combines fewer active lanes than Metal's, whose quad holds all four.
  • metal2vulkan-degrade-vertex-simdgroup-grouping (precision). PrecisionNote::VertexSimdgroupGrouping: A vertex function runs a simdgroup or quad operation on a device whose vertex stage takes no required subgroup size and whose driver is measured to group vertices otherwise than Apple's GPUs (DriverWorkaround::VertexGroupingNotApples: ANV, 8 vertices a subgroup, interleaved): the operation runs over the device's group of vertices, so a sum, a ballot or a shuffle combines other vertices than on an Apple GPU, whose simdgroup holds 32 consecutive vertices.
  • metal2vulkan-degrade-fragment-simdgroup-grouping (precision). PrecisionNote::FragmentSimdgroupGrouping: A fragment function runs a simdgroup operation (a reduction, scan, vote, ballot, shuffle, broadcast or AGX multiply-add) or reads its [[thread_index_in_simdgroup]], or discards, asks quad_is_helper_thread or simd_is_helper_thread and runs a quad operation, on a device whose fragment subgroups are not Metal's simdgroups (the profile does not take DriverDeviation::MetalFragmentSimdgroups). A simdgroup operation runs over the pixels the device's rasterizer packs into a subgroup, so a sum, a ballot or a shuffle combines other pixels than on an Apple GPU, whose packing is measured, and the lane is the pixel's place in the device's subgroup, or in its aligned 32 lanes where the subgroup holds 64 or 128 (each such run of 32 lanes is one simdgroup, as [[threads_per_simdgroup]]'s 32 says). An Apple GPU also shades some quads of a function that discards as several partial quads from the function's start, each run holding the quad's other covered pixels as helpers, where the device shades them as one quad: a ballot of the helper query names covered pixels as helpers on the M3 Max (3 of the 16 quads of an 8x8 target, 2 to 4 of the 12 of a 7x5 one, under the full-screen triangle with every third pixel discarded) and none on the device. A device whose fragment subgroup holds fewer than two quads combines the one quad's pixels alone, so a reduction ahead of a discard_fragment counts no quad the discard drops, where an Apple GPU's simdgroup counts the dropped quads of its 8x4 pixel block; the device states one fragment subgroup size, so no required size widens it, and no exact form exists there.
  • metal2vulkan-degrade-blended-write-rounding (precision). PrecisionNote::BlendedWriteRounding: A fragment function writes a float to a half-float color channel of a render pipeline under TextureWriteRoundingMode::NearestEven that blends with factors other than one and zero (ChannelWrite::BlendedNearestEven): Metal rounds the blend's result to nearest even, and the device's blend converts it by its own rounding (MoltenVK's toward zero), so a blended value off the half grid may store the neighbouring half; under a constant factor Metal's result is neither rule's on 2,376 of 580,508 RGBA16Float channels near the half denormals.
  • metal2vulkan-degrade-coverage-reads-rounded-alpha (precision). PrecisionNote::CoverageReadsRoundedAlpha: A render pipeline covers by alpha (alphaToCoverageEnabled) under TextureWriteRoundingMode::NearestEven, and its fragment function writes a float alpha to a half-float attachment 0 that stores it as written: Metal stores the alpha rounded to the nearest-even half and reads the coverage from the alpha before rounding, which no device separates, so the function rounds the alpha and the coverage reads the rounded one. The stored alpha is Metal's; a fragment whose alpha lies within half a half step of a coverage threshold may cover one sample more or fewer (2 of 16,384 alphas on an Apple M3 Max). Which samples an alpha covers is the device's own (device-alpha-coverage).
  • metal2vulkan-degrade-device-alpha-coverage (precision). PrecisionNote::DeviceAlphaCoverage: A render pipeline covers by alpha (alphaToCoverageEnabled, over a four-component float first output at attachment 0) on a device not measured to cover as Metal does (DriverDeviation::MetalAlphaCoverage, which MoltenVK takes on the Apple M3 Max's macOS 27 identity: Metal covers there). The device converts the alpha to its coverage mask by its own algorithm, which Vulkan does not specify ("It is intended that the number of 1's in this value be proportional to the alpha value", and "The algorithm may be different at different framebuffer coordinates"). Metal, measured over 639 alphas a sample count on an Apple M3 Max under macOS 27.0.1, covers a pixel at one sample above an alpha of 1/2, and at two and four samples ceil(alpha * n - t) samples, t a 2x2 ordered dither of the pixel's window coordinates (1/8, 5/8; 7/8, 3/8), either count within an f32 ulp of a threshold. Recorded bound, pixel by pixel against Metal's reading: on lavapipe (Mesa 26.0.8, arm64) every pixel covers floor(alpha * n) or ceil(alpha * n) samples, so within one sample of Metal's and Metal's where alpha * n is an integer; at one sample, where lavapipe dithers too, a whole fragment is stored or dropped where its alpha lies between its own threshold and 1/2 (2,560 of the sweep's 10,224 pixels); at four samples a pixel is one sample apart only within an f32 ulp of a threshold (96 of 10,224). An NVIDIA RTX 5080 Laptop GPU stores a fragment of alpha 1/2 at one sample, where Metal drops it; every other device and count is unmeasured.
  • metal2vulkan-degrade-rotated-blend-rounding (precision). PrecisionNote::RotatedBlendRounding: A fragment function writes an attachment held with its channels rotated (ARGB8Unorm) whose blend is none of the measured forms (RotatedBlendForm::Unmeasured), or the premultiplied form through a first output that is not 32-bit float: Apple's blend computes a factor pair apart in its color and alpha arithmetic, and the rotation moves Metal's blue into the image's alpha and Metal's alpha into its red, so a channel may store one code apart from Metal's.
  • metal2vulkan-degrade-linked-sampler-numbering (precision). PrecisionNote::LinkedSamplerNumbering: The sampler resource IDs a pipeline state takes for the constexpr samplers of the visible functions its stage links may be other than Metal's: two or more linked functions bring constexpr samplers, which Metal numbers in an order the pipeline's inputs do not decide; or a function a table can hold that linking did not import could not be planned, so its samplers are not known; or a dynamic library's symbol, a binary function or a function-pointer group's function brings them, whose numbering is not measured.
  • metal2vulkan-degrade-computed-sample-depth (precision). PrecisionNote::ComputedSampleDepth: A fragment function runs its draw's depth test itself at more than one sample on a device whose FragCoord.z is the pixel centre's there (VkProperty::CenterFragCoordDepth), and computes each sample's depth from its vertex function's window depth read at the sample, plus FragCoord.z less that depth read at the centre, which carries the depth bias.
  • metal2vulkan-degrade-argument-pixel-sampler-scaling (precision). PrecisionNote::ArgumentPixelSamplerScaling: A sample, gather or comparison through an argument buffer's sampler whose word the specialized module cannot read may hand the device a pixel coordinate scaled by the texture's size, where the sampler states pixel coordinates, with pixel-sampler-scaling's bound. A sample through a state of nearest filters, one level and no anisotropy hands the device its texel's centre instead, where the device reads exactly Metal's texel but at a negative subnormal coordinate, whose floor is the device's (device-denormals' reading, which this note records for such a sampler).
  • metal2vulkan-degrade-half-output-precision (precision). PrecisionNote::HalfOutputPrecision: A fragment function returns a half color output (a scalar or vector of AIR's half) to an attachment the pipeline has, and either its module is compiled without fast math (air.compile.fast_math_disable) and that attachment blends, factors one and zero included, with some channel written (StageIo::half_blend_colors, which the pipeline's stage reads), or its module names no math mode (under fast math the pipeline's stage records PrecisionNote::HalfOutputFastMathBlend instead).
  • metal2vulkan-degrade-extended-range-blend-source (precision). PrecisionNote::ExtendedRangeBlendSource: A fragment function's half color output (a scalar or vector of AIR's half) is blended into an extended-range attachment (BGR10_XR, BGRA10_XR, RGB10A8_2P_XR10, or an _sRGB twin) or a padded 10-bit one (R10Unorm_X6, RG10Unorm_X12, their _sRGB twins, RGB10A2Unorm_sRGB), whose raw codes no device's blend unit reads, so the function blends in the shader in the device's arithmetic: S·Fs op D·Fd in float, in the blend equation's order, the source, second source and blend color clamped to the format's range first (a padded format's not clamped, as Metal clamps none there). The device's compiler may contract a product into its sum and may regroup the blend: MoltenVK on the M3 Max and NVIDIA's driver on an RTX 5080 compute a second source's blend S·F + D·(1 - F) as D + F·(S - D). Metal's compiler rounds each step to half, so a blended channel may store another code than Metal's: within two codes on a linear format and within six on an sRGB twin near zero, where its transfer is steepest, in the conformance suite's extended-range and padded blend cases; and where the device's compiler regroups a padded format's blend, an infinite second source stores the end code its sign picks where Metal's sum is NaN, stored as code 0.
  • metal2vulkan-degrade-discard-drops-simdgroup-stores (precision). PrecisionNote::DiscardDropsSimdgroupStores: A fragment function meets the store-dropping defect of DriverWorkaround::DiscardDropsSimdgroupStores (MoltenVK on an Apple GPU: Apple's compiler drops the texture writes of every live thread of a simdgroup holding a discarded thread, where the function discards, then writes storage, samples, and calls SPIRV-Cross's optnone arithmetic helpers), and a discard site that would discard at once cannot wait until after the writes: a store, atomic, image write or non-quad subgroup operation follows it, which a predicated discard does not yet guard (lower::fragment::discard).
  • metal2vulkan-degrade-helper-branch-drops-simdgroup-stores (precision). PrecisionNote::HelperBranchDropsSimdgroupStores: A fragment function meets the store-dropping defect of DriverWorkaround::DiscardDropsSimdgroupStores without a discard: SPIRV-Cross writes an operation of the module as an optnone call (a sum, difference or product decorated NoContraction, among others) where only helper invocations (the quad helpers past a primitive's edges, or demoted invocations) may run it before a storage write, and keeping them out would not be exact (spirv::helper_branches): a derivative or subgroup operation reads what they compute there or after, an arm leaves its selection otherwise than at its merge, the call is in a loop whose helper invocations may iterate alone, or it is in no branch at all but SPIRV-Cross writes it in one (a ?: arm, the right side of a && or ||, or a selection's arm, where its value is read once); and no identity shuffle of the call's result can follow it, which keeps the writes where the module places one: the device has no fragment-stage subgroup shuffle, or the result is a 64-bit or bool lane, or an 8- or 16-bit one without shaderSubgroupExtendedTypes.
  • metal2vulkan-degrade-extended-range-float-blend-source (precision). PrecisionNote::ExtendedRangeFloatBlendSource: PrecisionNote::ExtendedRangeBlendSource for a float color output (a scalar or vector of AIR's float): blended into an extended-range or padded 10-bit attachment in the shader in the device's arithmetic, which the device's compiler may contract and regroup, where Metal's compiler rounds the output and each step of the blend to half; a blended channel within ExtendedRangeBlendSource's bound of Metal's.
  • metal2vulkan-degrade-anisotropic-filter (precision). PrecisionNote::AnisotropicFilter: The module samples a texture through an anisotropic sampler with Metal's anisotropic filter emulated by the device's samples at explicit levels (lower::sampler::anisotropic), on a device without samplerAnisotropy, every Vulkan sampler being isotropic there, each tap the device's isotropic filter: a sample without comparison of a 2D texture or 2D array at the fragment's implicit level or with explicit gradients, or of a cube or cube array with explicit gradients, through a constexpr sampler of maxAnisotropy above 1, or through a runtime sampler slot whose word states anisotropy (under that word alone). A device with the feature samples with its own anisotropic filter. The footprint's logarithms and powers are the device's Log2 and Exp2, its level and spacing unrounded, and a linear mip filter's two levels the device's own blend at the fractional level, where Metal takes a piecewise-linear log2, 256ths and 4096ths. Cost: a cube's taps step across its face by Metal's face gradients, and a tap past the face's edge reads the next face as the device projects it, which Metal's own is not measured against.
  • metal2vulkan-degrade-device-anisotropic-filter (precision). PrecisionNote::DeviceAnisotropicFilter: The module samples a texture through a sampler whose anisotropy is known where Metal's anisotropic filter is not emulated (PrecisionNote::AnisotropicFilter's reach), on a device without samplerAnisotropy, which filters it isotropically: a cube, a 3D texture, a comparison, a sample whose residency the function observes, or a texture of another class than its declared one, at an implicit level or with explicit gradients, through a constexpr sampler of maxAnisotropy above 1 or a runtime sampler slot whose word states anisotropy (under that word alone). An argument buffer's anisotropic sampler, which the function cannot record, is refused there (SamplerAnisotropy).
  • metal2vulkan-degrade-device-point-size (precision). PrecisionNote::DevicePointSize: A vertex function writes [[point_size]], or a mesh function that outputs points set_point_size, on a device whose pointSizeRange ends below Metal's largest point, 511 pixels (Limits::max_point_size: 255 on ANV, 256 on lavapipe). A line or triangle mesh's size draws nothing, and its function records no note. The render pipeline state carries the note whatever primitive a draw of it takes; a draw of lines or triangles of it is Metal's exactly.
  • metal2vulkan-degrade-clipped-coverage-split (precision). PrecisionNote::ClippedCoverageSplit: A fragment function compiled for a multisampled pipeline reads [[sample_mask]] on a device whose rasterizer is not Apple's (DriverWorkaround::ClippedCoverageNotMetals): Apple's GPU draws a triangle that extends past the viewport as pieces whose shared edges cross pixels, and such a pixel's fragments can run once per piece, each reading that piece's coverage, where the device hands the pixel's fragment its coverage by the whole primitive (lavapipe by its own pieces).
  • metal2vulkan-degrade-looped-sample-outputs (precision). PrecisionNote::LoopedSampleOutputs: A fragment function that reads [[sample_mask]], runs once per covered sample on Metal and writes an output runs once per pixel in a multisampled pipeline, its body once per covered sample, on a device that does not run it per sample itself (MoltenVK on Apple's GPU runs a memory writer per sample itself, as written). The samples Metal writes are written, but each with the last pass's outputs, where Metal writes each sample's from that sample's run: equal where every pass computes the same outputs. Vulkan hands an invocation under sample shading only its own sample's bit of the coverage.
  • metal2vulkan-degrade-half-output-fast-math-blend (precision). PrecisionNote::HalfOutputFastMathBlend: A fragment function of a module compiled with fast math (air.compile.fast_math_enable) returns a half color output to an attachment the pipeline has that stores some channel (its write mask names one of its format's channels; StageIo::half_fast_colors, which the pipeline's stage reads, or the interlocked storage form's write), where PrecisionNote::HalfOutputPrecision's conditions hold; or computes the blend of a 16-bit float attachment it fetches in the interlocked storage form (no Vulkan blend applies to a storage write) where Metal's compiler may fold the output's own arithmetic into that blend or regroup a sum of it: within 2 half units in the last place of Metal's at the operands' magnitude, 16 at the stored value's under cancellation. Where the output is opaque to the blend and its form fits every measured state, the function's blend is Metal's and records nothing; so does the blend of a fetched 8-bit unorm attachment it computes there (every factor, operation, write mask and blend color it builds), which Metal reads the output into clamped, folding none of it (the storage image's store of its result is the device's conversion, DeviceColorConversion). Every device receives the output widened to float.
  • metal2vulkan-degrade-device-sampling (precision). PrecisionNote::DeviceSampling: Native device sampling: the module hands a sample, gather, comparison or level query to the device's own sampler on a device whose sampler is not Metal's (the module requires VkProperty::DeviceSampling), its level clamp the descriptor's as given (a lodMinClamp past level 15, past every texture's last level, handed as 15, which reads the same level; Metal holds it on a 1/64 grid, and its nearest mip filter reads the lower level at a clamp halfway between two, where the device may read the upper) and a subnormal coordinate the device's to read (Metal reads a normalized one as a zero before addressing, and a negative pixel one as texel -1). That includes a linear sample of a two-plane YCbCr texture, whose texels hold Metal's reads exactly: the device's filter of them lands within 1.183 codes (1/255) of Metal's sum on the format's grid, so a draw binding such a texture makes no pipeline of its own.
  • metal2vulkan-degrade-native-transcendentals (precision). PrecisionNote::NativeTranscendentals: Native device maths: the module computes a float or half math-library function by the device's own GLSL.std.450 instruction (exp, log, pow, sinh, cosh and tanh among them; a composition of the device's Exp2 and Log2 only for exp10 and log10, which no instruction is) where Metal's function is not the device's own; fast::sqrt the device's Sqrt, and a half sqrt its 16-bit Sqrt where the module computes half in 16 bits under the 16-bit float controls; the fast sin, cos, tan, sinh, cosh, tanh and atanh the device's instructions, not MSL's fast-math formulas (fast::sin of 1e7 is the device's sine, where Metal answers +0; fast::tanh(45) is 1, where Metal answers NaN); fabs, sign and fract the device's FAbs, FSign and Fract, their special operands the instruction's (Metal's sign of a NaN, a zero and an f32 denormal is +0, its fract of an infinity +0); a half function's signed zeros and NaN signs its float instruction's (half sin(-0) is -0, where Metal answers +0), and on every device a half fmod's zero remainder its float remainder's (half fmod(-2, 0.5) is -0, where Metal answers +0); pow, powr and atan2 C99's special values by the device's comparisons around its instruction (pow(x, 1) the device's Pow, where Metal answers x; an f32 denormal operand as the device reads it); and round C99's from the device's Trunc on every device (round(-0.3) is -0, where Metal answers +0).
  • metal2vulkan-degrade-native-division (precision). PrecisionNote::NativeDivision: Native device maths: a precise float or half division, or Metal's fast division or reciprocal, is the device's OpFDiv where the device's division is not Metal's own: within Vulkan's 2.5 ulp, where Metal's precise division is correctly rounded. A half one is the float quotient rounded to half, or, where the module computes half in 16 bits under the 16-bit float controls, the device's 16-bit OpFDiv: within 2.5 half ulp, its divisor scaled by a power of two into [2^-14, 2^14].
  • metal2vulkan-degrade-native-fma (precision). PrecisionNote::NativeFma: Native device maths: a float fused multiply-add on a device without OpFmaKHR, or a half one where the device's 16-bit Fma is not measured to be Metal's and the device has no 16-bit OpFmaKHR under the 16-bit float controls, is the device's GLSL.std.450 Fma (on the half operands held in float, its result rounded to half), where Metal's rounds once. On a device Device::from_queries made that computes half in 16 bits under the 16-bit float controls, a half one is the device's 16-bit Fma on the half operands. Recorded bound: a half result held in float within one half ulp of Metal's; a float one, and a 16-bit one, within half an ulp of the product plus half an ulp of the result, in its own format.
  • metal2vulkan-degrade-device-texel-conversion (precision). PrecisionNote::DeviceTexelConversion: Native device sampling (a texel conversion): the module hands a read, sample or gather with a float result the device's own conversion of the texel's codes, off Apple's GPUs (VkProperty::MetalSampler keeps Metal's value). Recorded bound, of a texel read from one texel of one level: an 8-, 10- or 16-bit normalized code within one f32 ulp of Metal's c / (2^b - 1) where measured (lavapipe multiplies by the reciprocal: some 8-bit codes one ulp high; some 10-bit BGR10A2Unorm, a 16-bit and 512 Depth16Unorm codes one ulp low), and a 10-bit code within 0.015 of a code where the device widens it by replicating its bits to 16, (c << 6 | c >> 4) / 65535 (NVIDIA's RTX 5080 Laptop GPU); a 4-, 5- or 6-bit channel of a packed format within one f32 ulp where the device converts it by the reciprocal (lavapipe: some ABGR4Unorm codes one ulp high), and within 0.18 of a code where it widens a 5- or 6-bit channel by replicating its bits (ANV, NVIDIA; a 4-bit channel's replication is exact); a half-float or small-float texel's NaN in the device's encoding, where Metal answers 0x7fc00000; a 32-bit float texel's NaN in a gather in the device's encoding, and its denormal in a gather a zero of its sign, where Metal hands back the texel's bits (NVIDIA's 615.71.09 on the RTX 5080 Laptop GPU gathers every NaN as 0x7fffffff and every denormal as a zero); a 32-bit float texel's NaN in a nearest sample in the device's encoding, and its denormal there a zero of its sign on a device that flushes it there (ANV's Mesa 26.2.6 on the Iris Xe samples every NaN as 0xffc00000 and every denormal as a zero of its sign, and reads and gathers both as stored; RADV's Mesa 26.2.6 on the RX 7900 XTX and the Radeon 780M samples a denormal as a zero and gathers it as stored); every other class Metal's value.
  • metal2vulkan-degrade-device-vertex-conversion (precision). PrecisionNote::DeviceVertexConversion: Native vertex input (a conversion): a render pipeline's vertex descriptor gives a normalized format (UCharNormalized through Short4Normalized of either sign, UChar4Normalized_BGRA, Int1010102Normalized, UInt1010102Normalized) to an attribute that fixed-function vertex input fetches, so the attribute is the device's UNORM or SNORM conversion of its codes, where Metal's fetch answers the code over its maximum correctly rounded (an Int1010102Normalized 10-bit field times float(1/511)): within one f32 ulp where measured (lavapipe reads some 8-bit unsigned codes one ulp high), but lavapipe's per-instance fetch, which reads the most negative code of an 8- or 16-bit signed format unclamped (-128/127, -32768/32767) where Metal reads -1. Recorded on the pipeline's vertex stage on every device but one whose profile takes DriverDeviation::MetalNormalizedVertexFetch (MoltenVK on the Apple M3 Max's macOS 27 identity), where only a 16-bit format read as half records it; one module serves every format the device fetches. A normalized attribute the shader pulls from its buffer instead (an offset, stride or step fixed-function input cannot fetch, a kernel's [[stage_in]] attribute) is the module's product of the code and its maximum's reciprocal, rounded once, the signed one clamped to -1: within one f32 ulp of Metal's quotient (some 8-bit unsigned codes one ulp high, some signed, 10-bit and 16-bit codes one ulp toward zero; 0, the maximum and -1 exact). The function records it on every device, read as float for every normalized format but Int1010102Normalized (Metal's own product), and read as half for a 16-bit format (one half ulp at four codes).
  • metal2vulkan-degrade-native-half-conversion (precision). PrecisionNote::NativeHalfConversion: Native half rounding (a conversion): the module rounds a half result it computes in float (a half operation's, a function's, a conversion from float's, a texel's) by the device's conversion of the float to 16 bits and its widening, on a device with shaderFloat16 whose float controls do not make that conversion Metal's half(float) (RoundingModeRTE, DenormPreserve and SignedZeroInfNanPreserve for 16 bits: ANV and RADV round through the conversion under them, exactly, with no note): NVIDIA, whose driver folds the conversion's round trip even under those controls (DriverWorkaround::HalfConversionPairFolded), MoltenVK, lavapipe, and any device without them. NVIDIA's pipelines compute under those controls all the same: a half +, -, *, / and sqrt there are the device's 16-bit instructions, whose results take no such rounding. Also recorded under those controls on RADV where the half is the result of a float addition, subtraction, multiply or fused multiply-add: its compiler fuses the operation into the conversion and rounds the exact result once (DriverWorkaround::HalfConversionFusedWithArithmetic), one half ulp from Metal's where the float result lies on a half midpoint. On a device Device::from_queries made, which reads no driver identity, every device with those controls takes the pair (NVIDIA's included), and every pipeline that rounds through it records the note, a static note of the rounding: a driver's compiler may fold the pair or fuse the operation so. Also recorded where a half read from its bits is the device's widening, or a half encoded to its bits (where they are not the bits it was read from) is the device's narrowing, and that conversion is neither under those controls nor measured to be Metal's: the conversion on lavapipe, and GLSL.std.450 UnpackHalf2x16 and PackHalf2x16 on every device without shaderFloat16. A half denormal may read or encode as the zero of its sign. Exempt: on a profile that takes DriverDeviation::MetalHalfConversion, MoltenVK on Apple's GPUs of the Apple M3 Max's macOS 27 identity, a module whose every half rounded through the conversion converts a float the function holds (an AIR fptrunc or air.convert from float) or a texel's value records no note for that rounding and requires VkProperty::MetalHalfConversion: measured word for word against plain Metal, with and without fast math, over 1,173,760 floats loaded, summed, multiplied, divided and fused, an integer's quotient, and every texel of ten formats read, sampled and gathered as half. A texel's value includes one the module decodes itself (an extended-range or bfloat code) and a heap read's merge of its fetched texel and its decode routine's; where Metal's half texel is not that rounding of the value the access records half-texel-conversion (outright for an argument buffer's texture) or device-pack-conversion (a decoded texel). A half operation or function computed in float and rounded keeps the note (Metal's half tanh answers 7 of the 65,536 halfs otherwise).
  • metal2vulkan-degrade-native-half-quantize (precision). PrecisionNote::NativeHalfQuantize: Native half rounding (a quantize): the module rounds a half result it computes in float (a half operation's, a function's, a conversion from float's, a texel's) by the device's OpQuantizeToF16 alone, on every device without shaderFloat16, its quantize measured or not: a value below the smallest normal half may round to a zero where Metal answers the half denormal (or 2^-14, from just below it). An integer's half rounds exactly instead.
  • metal2vulkan-degrade-native-nan-encoding (precision). PrecisionNote::NativeNanEncoding: Native device maths: a float or half operation's NaN result is the device's, its sign and payload unselected, where Metal answers a NaN the device is not measured to answer (every NaN but Metal's canonical one on a device measured to answer that, MoltenVK on an Apple GPU): a float fneg and fabs, which keep a NaN operand's payload on Metal, a half fract, which returns it, and a precise float pow of a NaN base to the exponent one, which returns the base, among them. A float ldexp, which the module computes on the bits, returns a NaN operand itself as Metal does, on every device, and records nothing. Also recorded wherever a half is read from its bits, on every device, since the read is the device's widening (its conversion with shaderFloat16, UnpackHalf2x16 without): a NaN's bits the device's, where Metal widens every half NaN to 0x7fc00000 and moves one it does not widen with its bits. And wherever a half is encoded to its bits (a store, a reinterpretation, a texel's bits) where they are not the bits it was read from (a half moved unchanged from its read keeps them, through a struct's member too), on every device, since the encode is the device's narrowing (its conversion with shaderFloat16, PackHalf2x16 without): a NaN's bits the device's, where Metal keeps a half NaN's sign and payload. Exempt: on a profile that takes DriverDeviation::MetalNanMoves, MoltenVK on Apple's GPUs of the Apple M3 Max's macOS 27 identity, whose widening, narrowing, float fneg and fabs and half fabs were measured to answer Metal's bits (every half widened, moved through a select, a phi of a half and of a half2, a later block and fabs, and 98,368 float words negated and taken the magnitude of, on Metal and on the runtime), a float fneg or fabs, a half's widening to float, a half fabs, and a module's reads and encodes of a half's bits record no note and require VkProperty::MetalNanMoves. The exemption stops where the module carries a widened half out of the registers before narrowing it (a store to a stage output or a variable other than a function's float one, a call, a return, a group or atomic operation, an image operation but a texture write of it, whose store the write's own PrecisionNote::DeviceNanEncoding accounts for), reads its widened bits (a bitcast but to store them to memory, frexp, modf, ldexp), holds a float NaN constant other than 0x7fc00000, or merges a select of a widened half against a value it does not hold widened with another widened half at a phi or in a function's float variable, member by member where a struct, an array or a vector carries them (Metal's compiler answers 2045 of the 2046 half NaNs of that merge 0x7e00, measured on the M3 Max): such a module records the note there too. A half fneg records it on every device.
  • metal2vulkan-degrade-native-min-max (precision). PrecisionNote::NativeMinMax: Native device maths: Metal's fmin, fmax, min3, max3, clamp or saturate (its clamp(x, +0, 1)) on float or half is the device's GLSL.std.450 NMin, NMax or NClamp, on a device not measured to answer Metal's operand; and median3 on every device, min(max(c, min(a, b)), max(a, b)) of the device's NMin and NMax, whose pick of two NaNs and of an f32 denormal is the device's. The result is one of the operands, Metal's but at three ties (of two NaNs a NaN of the device's bits, where Metal answers the second operand's; of +0 and -0 either zero; an f32 denormal beside a zero or a denormal compared by its value, where Metal compares it as a zero and answers the second) and one undefined answer: fast::median3 of two NaN first operands and a number answers the number, as precise median3 does on Metal, where Metal's fast form answers the second NaN. MSL leaves a NaN operand under fast math undefined (section 8.1).
  • metal2vulkan-degrade-native-dot (precision). PrecisionNote::NativeDot: Native device maths: Metal's dot on float and half is the device's OpDot (a half one summed in float and rounded once to half, or the device's 16-bit OpDot where the module computes half in 16 bits under the 16-bit float controls), not Metal's fused chain of its products, on every device but for a float one where the device's functions are Metal's own (MoltenVK).
  • metal2vulkan-degrade-native-mix (precision). PrecisionNote::NativeMix: Native device maths: Metal's mix(x, y, t) on float and half is the device's FMix (a half one computed in float and rounded once to half, or the device's 16-bit FMix where the module computes half in 16 bits under the 16-bit float controls), not Metal's fma(t, y, fma(-t, x, x)), on every device but for a float one where the device's functions are Metal's own (MoltenVK).
  • metal2vulkan-degrade-native-logic-operation (precision). PrecisionNote::NativeLogicOperation: A render pipeline's private logic operation (other than copy and no-op) is drawn by the device's logicOp into an RGB10A2Unorm, BGR10A2Unorm or signed normalized attachment the fragment function writes, with a channel its write mask keeps. Vulkan's operation takes the fragment's value converted to the channel's own code and the stored code as it is, and stores its result as it is; Metal widens a 10-bit (or 2-bit) code and the fragment's to 16-bit codes, operates, and narrows the result to the channel's code, rounded to nearest, and reads a signed channel's lowest code (0x80, or 0x8000) as the code above it and stores a result of the lowest code as the code above (probe logic_operation on an Apple M3 Max, macOS 27.0.1). So a channel may store another code than Metal's (lavapipe's xor into RGB10A2Unorm stored green 938 where Metal's rule gives 937, and its xor of 0xe0 over an RGBA8Snorm channel's 0x80 stored 0x60 where Metal's gives 0x61), by a distance the note does not bound: the result follows the codes' bits. The device's logicOp is its native form there, and no other form is built for it; a device without logicOp computes Metal's rule in the fragment function and records none. A signed channel the draw does not write (outside the write mask, or every channel under no-op) keeps its lowest code where any draw's unwritten texel does (snorm-minimum-kept).
  • metal2vulkan-degrade-native-float8 (precision). PrecisionNote::NativeFloat8: A tensor's 8-bit float element (MTLTensorDataTypeFloat8E4M3 or Float8E5M2, which a matmul2d product reads) widens through the device's own 8-bit float on a device with shaderFloat8 (SPV_EXT_float8's Float8E4M3EXT or Float8E5M2EXT, OCP's encodings), the only form there: an e4m3 code 0x7F or 0xFF reads as a NaN, where Metal reads 480 and -480 (measured on the M3 Max), and an e5m2 NaN's bits are the device's, where Metal reads 0x7FC00000. Every other code reads Metal's value. A device without shaderFloat8 decodes the fields with integers, as Metal reads them, and records none. An air.convert from f8e4m3fn or f8e5m2 and a simdgroup-matrix cell of those formats widen through the same type there and record none: their formats are OCP's own, and Metal on Apple M3 does not compile them.
  • metal2vulkan-degrade-device-depth-bias (precision). PrecisionNote::DeviceDepthBias: A draw of triangles under a depth bias (setDepthBias:slopeScale:clamp: with a bias or a slope scale other than 0) on metal2vulkan-runtime, whose render encoder carries it as a static note (RenderCommandEncoder::DEPTH_BIAS_NOTE): the biased depth is the device's. Vulkan biases by m × slopeScale + r × depthBias, where the maximum depth slope m is the device's (exact, or the larger of the two derivatives' magnitudes) and the unit r is 2^(e - n) of the primitive's largest depth exponent for a float depth attachment and the device's for a fixed-point one (at most 2 × 2^-n). Apple's documentation states neither the slope measure nor the unit. A draw of lines is not biased, as Metal biases triangles alone.
  • metal2vulkan-degrade-swizzled-opaque-black-border (precision). PrecisionNote::SwizzledOpaqueBlackBorder: A sampler that reads its border (ClampToZero or ClampToBorderColor on an axis, both of which read the sampler's colour) with an opaque-black border colour. A sampler state carries it as a static note (SamplerState::precision_note), decided by its descriptor alone on every device; a compute or render pipeline whose function samples through such a constexpr sampler carries it among its notes (precision_notes), decided by the sampler's own constants. Sampled through a view whose Vulkan component mapping is not the identity (the texture's swizzle, or the mapping its pixel format takes), its border texel is the device's answer on a device without borderColorSwizzleFromImage (VK_EXT_border_color_swizzle): Vulkan leaves it undefined unless the sampler names the view's mapping, which a sampler that meets every view cannot, and the NVIDIA driver reads (0, 0, 0, 1), where Metal reads the border colour in the format's channels through the swizzle. A device with the feature reads Metal's texel.
  • metal2vulkan-degrade-device-pack-conversion (precision). PrecisionNote::DevicePackConversion: Native device maths (a conversion): air.pack or air.unpack of a normalized format is the device's: GLSL.std.450's Pack/Unpack Unorm4x8, Snorm4x8, Unorm2x16 and Snorm2x16, their definition by the device's NClamp, multiply, RoundEven and reciprocal for rgb10a2 and rgb565, and the MSL transfer functions by the device's Pow for unorm4x8_srgb's colour. Metal rounds the exact product and divides correctly rounded (unorm565 in float: the product rounded to float first, and the code times the float nearest the reciprocal, as the definition does), answers code 0 for a NaN channel, and takes an sRGB colour through its twelve-bit table; a packed code is within one of Metal's, an unpacked value within 2.5 ulp, a decoded sRGB colour within half a twelve-bit step (1 / 8190) of Metal's step beyond its Pow's bound. Also a write of an 8-bit sRGB storage texture held through its UNORM alias (at a slot, or held by an argument buffer), which encodes by unorm4x8_srgb's pack. Not recorded for a float conversion of the four named formats on MoltenVK, Metal's own there. Exempt: on a profile that takes DriverDeviation::MetalPackConversions, MoltenVK on Apple's GPUs of the Apple M3 Max's macOS 27 identity, the forms measured to answer Metal's at every code and every half (on Metal and on the runtime) record no note and require VkProperty::MetalPackConversions: unorm565 in float, and in half unorm4x8, snorm4x8, unorm10a2 and unorm565 both ways and unorm2x16 and snorm2x16 packed. The sRGB format, unorm10a2 in float (9,163 of 131,072 unpacked words and 1,257 of 3,083,776 packed floats differ), snorm10a2, and the half unpacks of unorm2x16 and snorm2x16 (Metal's single rounding, 8 lanes differ) stay noted there. The same conversions serve an implicit imageblock access of a normalized attachment (a half load rounding the unpacked float once more), a fragment function's read and write of an 8-bit sRGB attachment in the interlocked storage form or through its word view, and a snapshot read's decode of a normalized code (c times the f32 nearest 1 / D), noted alike. So does every conversion of an extended-range, padded 10-bit or bfloat texel (BGR10_XR, BGRA10_XR, RGB10A8_2P_XR10, R10Unorm_X6, RG10Unorm_X12, their sRGB twins, RGB10A2Unorm_sRGB, R16Bfloat, RG16Bfloat, RGBA16Bfloat), which no Vulkan format holds: a read is float(c - 384) (a padded code c) times the f32 nearest 1 / 510 (1 / 1023), a write RoundEven of the clamped value's f32 product plus 384, an sRGB twin's colour the MSL transfer by the device's Pow on the magnitude, a half result the device's narrowing, a bfloat code's NaN as it is (a write's kept a NaN by its quiet bit). Metal divides correctly rounded, rounds the exact product, rounds a half with ties away from zero, converts the sRGB twins through its own tables, makes a bfloat NaN 0x7fc00000 or 0x7fc0, and rounds a bfloat sample's half toward zero: a linear value within one f32 ulp, a code within one (R10Unorm_X6_sRGB's and RGB10A2Unorm_sRGB's colour within two below 0.0031308, where Metal rounds the value to 2^-13 before its table, a step there spanning 1.6 codes), an sRGB twin's decoded value within half a 2^-13 step of Metal's table (R10Unorm_X6_sRGB's and RGB10A2Unorm_sRGB's colour 1.64 steps) beyond the Pow's bound, a half result within one half ulp. A texture a heap holds by its raw texels alone (BGR10_XR, BGRA10_XR, R10Unorm_X6, RG10Unorm_X12 and the bfloat formats: bind::heap_raw_form), whose float read, sample or gather through an argument buffer the function decodes the same way: such a stage records the note as a specialized note, holding where a texture its handles can name is one (SpecKey::HeapRawTextures, which the binding plan gives from the textures the command makes resident or binds), so a reading of the module alone holds it, and so does a command that can name one.
  • metal2vulkan-degrade-color-attachment-groups (precision). PrecisionNote::ColorAttachmentGroups: A render pipeline whose color attachments the device draws in more than one group (more than the lesser of its maxColorAttachments and maxFragmentOutputAttachments, four on a device at Vulkan's floor): each draw runs once per group, each group's variant writing its own attachments over its own copy of the depth and stencil the pass loads. Every variant's vertex stage is the same module, Position invariant, and every fragment variant's FragDepth, SampleMask and FragStencilRefEXT are decorated Invariant; Vulkan promises no more across pipelines of other fragment modules and attachments. Groups past the first may differ at discard or depth edges if the driver compiles the variants differently.

10. Accepted differences

Where the runtime answers otherwise than Metal on purpose, and nothing is slower or approximate for it (so no degrade notice says so), the difference is listed here. Most are answers Metal leaves undefined or ends the process for, and answers the runtime adds beyond Metal's API. The rustdoc of each item named states the rule in full.

Draws and index buffers

  • An indexed draw past its index buffer draws. Metal's API validation stops it; the runtime draws as Metal does without validation: a partial last index reads up to the length rounded up to 4 bytes, and every later position draws index 0 plus the base vertex.
  • An indexed draw from an index offset at or past the length draws index 0 plus the base vertex at each position, where Metal reads whatever memory follows (zeroed-index-fetch).
  • An object grid of more than 2^29 threadgroups fails its command buffer by its count, at once (GpuRecoveryVictim, Metal's code 1). Metal's GPU runs it for its watchdog's 5 seconds, then discards the command buffer from the draw's encoder on, and a command buffer of the queue committed while it ran. The runtime fails by the count Metal's GPU ran within the watchdog with an object function that does next to nothing (2^29 in 4.98 s, bind::METAL_OBJECT_GRID_TOTAL): a grid of up to 2^29 runs whatever its function costs, where Metal discards a slow one; the queue's other command buffers run. A direct draw fails from its encoder on, as Metal's; an indirect one, whose count only its arguments pass reads, draws nothing and fails the command buffer while the rest of its encoder and the encoders after it run.
  • A mesh grid of 1,048,577 to 2,097,151 threadgroups draws nothing, direct, indirect or set by an object threadgroup. Metal on the M3 Max draws whole up to 1,048,575 and nothing at exactly 2^20 or from 2^21 on, and between them is erratic (17 by 61,681 and 65,535 by 24 drew, 1025 by 1025 and 33 by 32,768 did not); the runtime answers there as at 2^20 (bind::METAL_MESH_GRID_TOTAL).
  • A draw's VkPipeline is made while the draw goes on. A draw whose pipeline is not made yet returns once encoded; the pipeline is made on the device's pool of at most four threads, and the command buffer's work waits for it in queue order.
  • A draw can take its key's general form while its own pipeline is made. A state's creation makes its predicted key and, where it differs, that key's general form, the two together: each specialization constant with an arm that serves every binding exactly at that arm. Every constant buffer slot read through a uniform view is read at the slot's residual (RangeAtBindOffset 0), which reads the same bytes at every bind offset: the binder writes the slot's descriptor range and residual from the bind offset alone, and the residual is 0 wherever the range starts at the bind offset (a bind state that says uniform_views_at_residual, whose keys read every uniform view at its residual, binds a range its bind offsets share instead, the residual the rest). A slot bound to nothing is read at its residual too (0), so a draw that leaves such slots unbound takes the creation's pipeline itself. On MoltenVK a texture slot a function converts to half has its UnmeasuredTexels, which no instruction reads, at 0 (a class whose half conversion is not measured, BC4 to BC7 and the linear ASTC formats among them, takes 1), and its PlainHalfTexels at 1, as a slot bound to nothing takes: the plain arm, which Metal's compiler can fold into the image instruction and which every plain class takes (every class but a YCbCr field on the grid 8192, which takes the class routine, PlainHalfTexels 0, and makes its own pipeline at its draw, as any key the creation did not predict). Where the predicted key is not its own general form (a storage view read at the bind offset, on a profile whose storage views declare the key, where a storage view bound to nothing is predicted as bound at offset 0), the creation makes both, so that neither a draw binding its storage views at offset 0 nor one taking the general form makes anything at its first use. A draw whose own pipeline (which reads such a buffer slot at the bind offset alone, or names an unmeasured class) is not made, and whose key's general form's is, draws with that one at once; its own is made on the pool behind the makings something waits for, and later draws take it. So a draw binding a texture of an unmeasured class waits for no compile of its own, and runs the instructions its own key runs. Only GPU time moves for the draws before their own lands (WorkCounts::residual_form_draws, residual_form_makings): on ANV the residual form's reads are loads where the other form's are pushed constants. On MoltenVK every key reads its buffer slots at their residual (the two forms measured alike there), so a draw's bind offsets choose no pipeline there, and a creation makes one pipeline. A constant with no arm that serves every binding stays a pipeline per value, made at the first draw of it: the half conversion's arm (PlainHalfTexels, above), a sampler's state (SamplerState, each sampler word a sampling emulation of its own), whether a pixel sampler is a nearest one (NearestPixelSampler, whose sample reads its texel's centre) and how the bicubic filter treats the bound format's texels (BicubicTexels).
  • A dispatch's VkPipeline is made while the dispatch goes on, the same way: one pipeline per threadgroup size and edge region, made on the pool. A compute state whose descriptor states requiredThreadsPerThreadgroup -- the threadgroup every dispatch of the state must have -- makes one at its creation: its predicted region's, at that size, each uniform view read at its residual; a dispatch of that region takes it, as does one whose key differs only in reading a view at its bind offset alone while its own is made (WorkCounts::creation_dispatch_pipelines_made, creation_dispatch_pipelines_drawn). A state whose descriptor requires no threadgroup size makes none at its creation: the size is the dispatch's own call and nothing in the request answers it, and a pipeline guessed from the state instead was taken by no dispatch at all over the whole conformance suite (141 made, 0 taken, against the render-side prediction's 764 of 794 in the same run). A tile dispatch's pipeline is made on the pool too, its pass recorded once it is made, the making ranked from the dispatch as one a committed command buffer waits for (WorkCounts::tile_pipelines_pooled); a failed making fails the command buffer, as a draw's does, FailedPipeline naming the dispatch by its order among the encoder's tile dispatch calls.

Binary archives and dynamic libraries

  • A binary archive serializes after its file is deleted. Device::new_binary_archive reads the file whole, so BinaryArchive::serialize_to_url writes what was loaded; Metal's fails there.
  • An archive's file is a path. BinaryArchiveDescriptor::url and serialize_to_url take a file path, not a URL.
  • A dynamic library's file is its metallib. DynamicLibrary::serialize_to_url writes the bytes the library was made from, without a slice of GPU code; the runtime loads either form.
  • Only a regular file is read. A pipeline creation's install name, a Device::new_dynamic_library_with_url path or a binary archive's path that names a FIFO, a device or a directory is not opened for reading: the install name loads nothing, and the other two are InvalidFile. A file is read once, no further than its length when opened. Metal's answer for such paths is not measured.
  • A device can be made to open no dynamic library's file. Under DeviceOptions::load_no_dynamic_library_file (and RawDevice's), a creation links only the libraries its function descriptors give, an install name libraries.loaded lacks fails a creation whose import survives specialization (Compile(NeedsInput(DynamicLibrary))) where Metal would read the file, and new_dynamic_library_with_url is refused (DynamicLibraryError::NoFileLoading). Off by default.

Resource IDs and identifiers

  • A gone holder's texture ID reads the neutral texture. A function reading a texture ID from an argument buffer reaches the texture holding the ID as the command buffer runs; once the holder is gone, the ID reads the neutral texture, where Metal's read is undefined.
  • A read_write argument-buffer texture of a format outside Metal's read-write tiers reads zero where the device cannot read its storage view without a format. On a device without shaderStorageImageReadWithoutFormat that reads storage without a format by the formats' own STORAGE_READ_WITHOUT_FORMAT bits (Vulkan 1.3 or VK_KHR_format_feature_flags2: ANV before Gfx12.5, the Iris Xe), the heap's storage arrays hold such a texture for its writes, which store as before, and a read through its handle reads the null element, as a nil texture's read does (memory::handles::FLAG_STORAGE_UNREADABLE). Metal defines a read_write texture's read only for its read-write tier formats (MTLReadWriteTextureTier): a function that reads a storage class one of them is held in through a view the device cannot read so is refused (Unsupported{ArgumentBufferTextures} naming the view format's bit). Which formats this reaches is in docs/FAST-PATHS.md's device gaps.
  • Two live textures with one ID: a function reads the holder, the texture placed there last.
  • An indirect command buffer's ID is Metal's small integer, from 1, the lowest free, in the indirect command buffers' own space; it stays held while committed work that runs or makes the buffer resident has not completed.
  • Resource IDs are numbered as Metal numbers them: textures', sampler states', pipeline states' and indirect command buffers' IDs follow Metal's allocator, around reservations (Device::reserve_resource_ids) too. IDs that end Metal's process, or whose reservation Metal never returns from, are refused.
  • The device counts the sampler IDs it holds (Device::sampler_ids_live, Device::sampler_id_pool_size), runtime extensions for a consumer that models Metal's sampler heap.
  • maxArgumentBufferSamplerCount is the device's set-1 sampler array less its neutral (DeviceProperties::max_argument_buffer_sampler_count): one fewer than the smaller of the array's elements (pipeline::heap_sampler_capacity: at most the handle table's 65536 entries and the update-after-bind sampler limits) and maxSamplerAllocationCount. Metal answers 500000 on an M3 Max; MoltenVK there answers 65535. It counts every live sampler state, with or without supportArgumentBuffers. A state past it reads the neutral sampler through an argument buffer (unlisted-argument-sampler).
  • A texture can take no resource ID (IdPlacement::Outside), for a consumer's helper textures and its textures over its own images (Device::new_texture_with_vk_image), such as swapchain images.
  • An indirect command buffer placed at an ID (IndirectCommandBufferDescriptor::placement, Apple's private setResourceIndex:) takes it as Metal does; an index of 16384 or more is refused.
  • A pipeline state placed before any pipeline ID is made (PipelineOptions::placement) is made, where Metal ended the process; an index of 16384 or more is refused.
  • An indirect command names its pipeline state without holding it. As in Metal, releasing a state gives its ID back while a command names it; a CPU-encoded command still runs what the state ran, and a GPU-written record runs the ID's holder, or nothing (released-command-state).
  • Unique identifiers (ComputePipelineState::unique_identifier, RenderPipelineState::unique_identifier, IndirectCommandBuffer::unique_identifier) are nonzero and unique among live objects, laid out by Metal's rule where it was measured (plain-state-unique-identifier, unmeasured-unique-identifier where it differs). IndirectCommandBuffer::identifier_unmeasured (no Metal counterpart) answers, without announcing, whether a buffer's identifier is one that notice names.

Indirect command buffers

  • A command's setters in one call (IndirectRenderCommand::set_each, IndirectComputeCommand::set_each, no Metal counterpart): an IndirectRenderSet or IndirectComputeSet names one setter call, its fields the setter's arguments, and each does what that setter does, refusals included. The first refused stops the rest and answers its place among them with the setter's error; the calls before it stay made and those after it are not taken, as one setter call at a time would leave the command. IndirectCommandBuffer::set_render_command and set_compute_command (no Metal counterpart: indirectRenderCommandAtIndex: or indirectComputeCommandAtIndex:, then the setters) take the command's index with the sets, with no command handle; the refusals of the index (past the size) and of the kind (a compute command of a render buffer) answer at place 0, before any setter. A setter's write that adds nothing to what the records may hold, on a buffer the GPU may not have written, takes no lock: a buffer slot, a draw, dispatch or barrier the CPU's writes added already, and a pipeline state the command names already, which is not held either. Each command's first set of a state, and every set after a device recovery carried the buffer, takes the lock and checks the state. Records in the runtime's own pages, as they are on a device that imports host pointers, are the pages a recovery's carry keeps, so such a write needs nothing more; in pooled memory, which the carry moves, the carry waits for such a write under way, and one begun during the carry takes the lock: an atomic add a write.
  • A command's read-back answers Metal's private getters: command_type, the buffer addresses and attribute strides, as Metal's get* getters answer them. IndirectComputeCommand and IndirectRenderCommand read one field of their record alone (command_type, has_barrier, dispatch or draw, one buffer slot, pipeline_unique_identifier, and the rest), as IndirectCommandBuffer::commands reads it, without decoding the whole command. Where Metal's getters answer other than what the command runs, the read-back answers as they do: a render command's draw of primitive type 7, 8 or 9 reads as one of points (0), and command_type of an indexed draw of type 9 reads as none; commands keeps the type the command draws.
  • Whether the GPU may have written the records (IndirectCommandBuffer::gpu_written, no Metal counterpart) turns true at the first route that may write them: the call that completes, in one command buffer, a write residency of the buffer and a pipeline state whose functions may call an indirect-command operation on commands of the buffer's kind (indirect_command_writes not empty and its kinds naming render commands for a buffer of draws, compute commands for one of dispatches, read from their AIR) set in any of its encoders, before or after, or an execution of commands whose records may name such a state (the commit asks again of what the records name then); a kernel that encodes dispatches alone neither marks nor adds to a buffer of draws beside it; a later write that first leaves such a state in the records of a buffer the command buffer executed; a blit's copy or reset into it. From then on an execution runs the records as they stand once the work before it completed. A buffer made resident for writing alongside functions that call no such operation stays unmarked, and its executions run the CPU's records as a buffer made resident for reading does (WorkCounts::indirect_write_residencies_unmarked counts each such commit's buffers). What the records may hold (IndirectCommandBuffer::command_writes) takes what each such state, and each state such an execution's records may name, may write, in whichever encoder of the command buffer it was set: Metal on an M3 Max runs what a kernel wrote with the buffer resident for writing only in an encoder before the kernel's or after it, as it does with the buffer resident in the kernel's own. A buffer no encoder of the command buffer made resident for writing is outside Metal's contract for a function's write: its executions run the CPU's records, where Metal on an M3 Max ran a compute execution's commands as the kernel wrote them (and a render execution's as the CPU did).
  • What an execution runs, where its records are read (CommandBuffer::add_executed_commands_handler, no Metal counterpart): a handler is called each time the runtime reads an execution's records, at commit, in a host step, or not at all for an execution the GPU alone runs.
  • An execution's commands order by their records' barriers alone, in either kind of encoder, as Metal states for MTLIndirectComputeCommand's concurrentDispatchThreadgroups: "Compute commands encoded into an indirect command buffer don't automatically serialize access to resources with other commands in the indirect command buffer. Use barriers to serialize access to resources within a range of commands. See setBarrier()." and "When you execute the commands in an indirect command buffer, the dispatchType property of the compute command encoder determines whether the compute command encoder adds additional barriers. If dispatchType is serial, the compute command encoder adds a barrier before and after the range of commands. If dispatchType is concurrent, then the compute command encoder does nothing, and you are responsible for synchronizing access to resources." The runtime runs a command after the earlier ones of the range where its record sets a barrier, and adds a barrier before and after the range in either kind of encoder. Where the GPU alone runs the execution and a route that wrote the records may set a barrier (IndirectCommandBuffer::command_writes), every command runs after the one before it.
  • Render commands the GPU may write run on the GPU alone where the commit can tell from what the records may hold (IndirectCommandBuffer::command_writes) that every command is a draw of one primitive type under the encoder's pipeline state, which the buffer inherits, and whose vertex function fetches no attribute of a layout whose stride is set per bind (each command binds its own buffers, which the GPU form fetches each attribute from in the shader): one indirect draw per command, in order, from what a preprocess wrote; and where the commands draw points, lines or triangles, the state's vertex function writes no memory and its fragment function reads no [[primitive_id]], one merged draw for the whole range, in the commands' order, whatever its count (WorkCounts::merged_draw_commands), which indexed draws among the commands need. Where the buffer inherits the encoder's buffers, every command draws with the encoder's vertex and fragment buffers as they stood at the call, each at its offset then (set*BufferOffset before the call included) and inline bytes included, as the host step binds them; a visible-function table the encoder binds where the functions read a buffer takes the host step. Otherwise, and where what the records may hold grew by the time the pass's batch is ready to submit, a host step records the pass.
  • A checked execution states what its check looks for (execute_commands_in_buffer_checked's and execute_commands_in_buffer_indirect_checked's IndirectCommandCheckNeeds, no Metal counterpart): draws of points, and commands under states that may encode indirect commands. The check is called with each command the runtime records, before it records any, wherever it reads the records: at commit for the CPU's records, in a host step for records the GPU may have written. Where what the records may hold rules out every kind the check names (IndirectCommandCheckNeeds::ALL names both; a record of no draw and no dispatch runs nothing), the check has nothing to see, is not called, and the execution may run on the GPU alone, render and compute alike; where that grows by the time the batch is ready, a host step records it and calls the check.
  • Command predication (encode_start_if, encode_start_else, encode_end_if and the while and do-while loops) runs Metal's blocks and loops on every device, with or without buffer device addresses, its unbalanced records answering NO and dropping their ranges, and its live blocks left open where a unit ends failing the command buffer as Metal's GPU recovery does (PredicationOpenAtUnitEnd). Loops nest to any depth and run as many passes as Metal's. A loop is laid down as 64 copies (16 inside another loop, fewer where they would lay down more than 16384 steps and gated dispatches, or more than 16 pieces of work a host step records after the GPU's work before it, an indirect dispatch's or an execution's, each a round trip to the host in every run whether its pass runs or not, and at least one); where it runs past them, a check submits its copies again, from where it stopped, until it ends, each time a round trip to the host, holding the batches after it on its queue (and those on other queues that use what the loop uses), and nothing encoded before the loop runs again. A loop without bound runs on, as Metal's does, after the program let go of its queue and device too, until the process ends or the device is lost. A loop running again stops, as Metal's does, at the GPU's recovery from a fault or a hang of another queue's command buffer (primitive type 9, or one a program commits as failed with Metal's code of either, 3 or 2; one behind the loop on its own queue waits for it, a known gap in docs/FAST-PATHS.md): a fault's fails its command buffer as a victim (GpuRecoveryVictim), a hang's ends it with no error, and nothing after the loop runs. Work inside a loop the runtime records apart (an indirect dispatch or an indirect command buffer's execution a host step records) is recorded again in each such run, after another round trip to the host where its first recording waited for the work before it. A condition word past its buffer reads as Metal reads it (the heap's bytes, or zero), and as zero where Metal reads memory unrelated to the buffer (predication-word-past-buffer). An unbalanced record that is its unit's first drops the unit's dispatches before it as Metal's does: what the unit's encoders recorded before it is never submitted.
  • A GPU-written indirect command naming a placed ID runs that ID's live holder, the state made last; once it is released, nothing.
  • An indirect render command keeps a draw's values to 32 bits, as Metal's records keep most of them; a value that cannot fit is refused.
  • An indexed patch command reads its control-point indices as Metal's did, with its pipeline's control points and index type; an index past its buffer reads 0.
  • An indirect render command's index and factor buffers must be resident: an execution resolves them against the resources the encoder made resident, as its kernel buffers.
  • A kernel's patch command scales its factors by the scale its draw_patches passes, as Metal does.
  • A render execution records its pass at commit, from the records as they stand then, as Metal's does.
  • A command's refusal is one typed error wherever it is recorded: the CPU's records are checked as commit records them, and commit returns what a command refuses; but for a buffer the command buffer made resident for writing, as a route met after the commit may still write the records before they run (another queue's command buffer the work waits for through an event, whose writes Metal runs), the host step records them once the work that wrote them completed, and the command buffer fails at that batch's submission only where they are still refused (WorkCounts::commit_refusals_held).
  • A render execution's range read from a buffer is read before its pass (execute_commands_in_buffer_indirect).
  • An indirect command's buffer outside the resident resources misses: its Metal address resolves against the buffers and heaps the encoder made resident; outside them the slot reads zero, drops writes, and the execution report counts a resident-set miss. Metal leaves the access undefined.
  • Indirect commands the GPU may write run in the large-buffer form: buffer slots at device addresses with in-shader bounds checks (VariantKey::large_buffer_form), so no buffer a command binds needs another compile. Inside a slot's window every access is the CPU form's; outside it, two contained answers differ, neither defined by Metal.
  • A blit copy between indirect command buffers of different descriptors copies the commands; a record the destination's descriptor does not allow runs nothing.
  • Render states an indirect command buffer leaves to its commands are the encoder's on a device that does not claim Apple10.
  • A function that sets a render state on a render command is not made (a kernel's render_command::set_cull_mode and its kin): the pipeline state is refused, as Metal refuses it without Apple10.
  • An indirect command buffer's allocatedSize is Metal's (its layout in 16-KiB pages), not the runtime's records' footprint.

Blits

  • Multisampled blit copies between depth or stencil and colour formats copy each sample's bytes as plain Metal does (its validation stops them), through VK_KHR_maintenance8 or sample-rate draws. A 16-bit depth crosses as its codes, exact where the driver keeps every code (DriverFact::FragmentDepthKeepsDepth16Codes: lavapipe's measured releases, and MoltenVK 1.4.2 on the Apple M3 Max) and refused where it is not measured to. A copy into a 32-bit float depth on a driver not measured to store fragment depths unchanged is drawn and announced (drawn-depth-copy).
  • A blit copy of 24-bit depth between textures of different formats is refused: Apple's reference GPUs make no Depth24Unorm_Stencil8 texture, so there is no Metal answer to match.
  • A blit copy out of a texture whose rows overlap in the buffer writes them in turn, the later row's bytes standing: a bytesPerRow below the row, as MTLPixelFormatGetInfoForDevice describes a one-plane YCbCr format's row, places each row at y x bytesPerRow, as Metal's blit does. Metal writes such rows in no one order: on the Apple M3 Max under macOS 27.0.1, of 300 shapes of 12 formats copied out at half the row, about a fifth left the later rows' bytes standing, a fifth every even row's and the rest neither order's, and 15 answered otherwise in another process (probes/short_row_blits.m). The runtime's answer is one of those, the same every time. Depth and stencil textures, textures over a buffer and two-plane extended-range textures (a level a multiple of 4 wide, not 3D) copy the same way, both ways: on the same GPU, 32 x 8 Depth16Unorm, Stencil8, both aspects of Depth32Float_Stencil8, an RGBA8Unorm texture over a buffer and RGB10A8_2P_XR10 at half the row, half plus a texel and the row less 16 bytes read each row whole from y x bytesPerRow into the texture, and wrote the rows there out of it in no one order, the even rows' bytes standing or neither order's, varying from run to run (probes/short_row_kinds.m, three runs); the runtime's answer is the later row's there too. A multisampled texture's copy out at such a pitch stays refused (Copy(BytesPerRow)): where Metal places its rows there is not measured. That probe's every copy between a buffer and a multisampled texture, at the packed row too, ended its process in Metal's blit (SIGABRT) because each case ran in a child that forked and had not exec'd, where Metal's compiler, which makes a multisampled blit's program, aborts. Spawned, the same copies return at every usage, storage mode and call tried, and nine of the multisampled layouts the runtime copies lie where it places them (probes/multisample_buffer_copies.m).

Render passes

  • A texture over a buffer that a pass stores DontCare keeps the buffer's bytes, in every texel, with or without memory barriers between the pass's draws, and under DontCareColorPolicy::Kept a texture's own image keeps its earlier texels: Metal's answer, but that the first pass in a process to overflow Apple's tiler (some 2 to 4 million triangle-tile entries) leaves the rendered texels in every texel, which no call can predict or detect. The runtime does not model the overflow, but where it hands the attachment to Metal's own DontCare (MoltenVK), which decides it. A pass that renders such a texture in place, as the default policy renders a texture's own image, otherwise announces dont-care-store.

  • The runtime's DontCare store writes what the pass rendered (metal2vulkan-runtime's render encoder stores a DontCare attachment as it stores a Store one, its README's render passes). Apple's page for MTLStoreAction.dontCare: "The GPU has permission to discard the rendered contents of the attachment at the end of the render pass, replacing them with arbitrary data." and "Some GPUs may still store the contents back to the texture, but you can't rely on that behavior. You need to assume that GPU discarded the texture's contents." MTLRenderPass.h states only that it is the default store action. An Apple M3 Max on macOS 27.0.1 leaves the texels of a texture over a buffer as they were before a clearing pass; the new runtime stores the clear there. The bytes of the buffer outside the texels keep what they held on both.

  • Two mesh draws of one pass with no barrier between them run in order. Where a later draw's object or mesh function reads a buffer an earlier draw wrote, and no memoryBarrier stands between them, Metal orders nothing: on an M3 Max (macOS 27.0.1) the reader read the host's words in 30 runs of 30, through an indirect command buffer's two commands. The runtime's emulation of mesh draws (MoltenVK, ANV on the Iris Xe) records the reader's dispatches after the writer's, so the reader reads the writer's words every run. Nothing is slower or approximate for the order, so no notice says so, and every field the pass does determine is Metal's: the conformance case mesh-commands-unordered-draws compares those exactly and keeps Metal's own texels beside them, for the next macOS to be read against.

  • A barrier over the render targets orders what it names, as a Mac2 GPU's does. The Metal Feature Set Tables give MTLBarrierScopeRenderTargets to Mac2 GPUs, not to Apple GPUs, and an M3 Max (macOS 27.0.1) orders nothing with it: a draw after one that samples its own pass's color attachment's texture reads the texels from before the pass, whatever the pass's load action or draws wrote before the barrier. The runtime orders the draws after such a barrier, or one over the texture, after the fragment stage, behind the draws before it and, where it comes before the pass's first draw, behind the pass's load actions: that draw reads what the draws before the barrier wrote, or the clear (the runtime's fence.rs and texture/attached_reads.rs). A draw that reads the clear before any draw of the pass reads its copy cleared to the clear in the pass's first instance, where the copy can be so (WorkCounts::attachment_read_clears), else an instance after one of the clear alone. With no barrier a draw reads at its own pixel what the draws before it wrote where the runtime takes no copy for it; else, before any draw of a pass that clears the color, the clear where its copy can be cleared to it, and otherwise the texels from before the pass, the M3 Max's answer (below). The conformance cases pass-start-barrier-* keep the M3 Max's texels and take the Mac2 answer as the one other, and their rows that read at their own pixels with no barrier the clear (below).

  • A draw that reads its own pass's color attachment at its own pixels reads what the draws before it wrote, with no barrier too, where the runtime takes no copy for it. Metal defines no answer here, and the Macs disagree. On an M3 Max (macOS 27.0.1) such a draw read the texels from before the pass at every pixel, in a pass that clears too. On an AMD Radeon Pro 5300M and an Intel UHD Graphics 630 (macOS 26.7.1) it read the earlier draw's texels at 98.6% and 99.99% of the pixels, and at all of them after a barrier over the render targets; the rest read the load's or the clear's texels. The runtime gives the x86 Macs' answer where that costs no copy, and the M3 Max's where the copy is the cheaper form, so a reader can see either, each one a Mac's:

    • where the device enabled attachmentFeedbackLoopLayout and its passes fetch no color as an input attachment (it has fragmentShaderPixelInterlock and not rasterizationOrderColorAttachmentAccess), a draw whose fragment function reads the texture at the fragment's own pixel alone, and that writes no channel of the color, reads the attachment itself, behind a barrier inside the pass, and sees the load and every earlier draw of the pass (WorkCounts::reading_draws_in_place);
    • a draw that writes the color it reads reads it through a snapshot where the device takes the snapshot route (section "Snapshot reads") and the snapshot costs no more than the copy, and sees the same: always for a color that renders a texture over a buffer's bytes, as a surface's does, and for a private texture by the area rule, which takes the snapshot through large scissors alone (WorkCounts::reading_draws_snapshotted). On a Radeon 780M a compositor's frame of six such readers over surfaces took 3.41 ms of GPU time against 4.07 with the copies;
    • a draw before any draw of a pass that clears the color reads a copy cleared to the clear, where the copy can be so (Texture::cleared_copy: a whole single-sampled 2D texture of one level and slice that one color renders in place; WorkCounts::attachment_read_clears): what both x86 Macs read at such a draw's pixels, as the load and no draw before it wrote only the clear there, the answer x86 macOS guests are written against, and a clear of the copy costs less than a copy of the texture;
    • every other such draw reads a copy taken before the pass, the M3 Max's answer: a private texture's reader through small scissors, and every reader on lavapipe (which has rasterization-order access) or on a device without the interlock, such as the Radeon RX 550 (the runtime's render/snapshot.rs, texture/attached_reads.rs).

A command buffer committed as failed (CommandBuffer::commit_failed)

  • A failure inside a group of encoders recorded together whose unit of command predication laid a loop or left work out fails the whole group. The runtime records a compute or blit encoder into the VkCommandBuffer of the compute, blit or render encoder before it where nothing needs a boundary between them: a compute encoder's dispatch type that of the group's compute encoders, the same batch (no event wait or signal between them), no work left for later in the earlier one, nor a write into an ASTC texture or a write of a new texture whole before any read, no command predication yet, the encoder trail off (DeviceOptions::encoder_trail) and protection options 0 (WorkCounts::encoders_folded counts each). It records a render encoder there too where it logs its calls (the device has a buffer over host pages), its pass is of one color group, over no rasterization-rate map, with no depth attachment the device holds between passes, and records at the encoder's end (its draws in a secondary command buffer); one whose first instance records inline begins such a group but joins none. On a device whose driver's image uses miss a write through a buffer over their memory recorded before them in the same VkCommandBuffer (DriverFact::ImageUsesMissBufferWritesInOneCommandBuffer: NVIDIA's 620.70.06 on the RTX 3090), a command that uses an image over bytes written before it in its VkCommandBuffer goes on in a new one, a grouped encoder's in its own (WorkCounts::command_buffers_split_at_aliases); a grouped render encoder's pass goes on in a new one before it where the pass or one of its draws uses such an image, and a render encoder that could continue the render pass instance the render encoder before it left open (WorkCounts::render_passes_continued) begins its own in its own VkCommandBuffer instead where an image its pass uses lies over bytes the group's encoders wrote. An encoder that updates a fence stays in its group: every command of a later member orders after the writes the update covers, whether or not its encoder waits for the fence, which orders more than Metal does, through the narrowest barrier that covers a fence: from those writes' stages to the command's own stages' storage, sampled and transfer accesses and its bound resources' accesses (WorkCounts::fold_fence_barriers); WorkCounts::folds_refused_kind and its kin count the encoders that joined no group by reason. A failure that fails some of such a group's encoders and not the others (a FailedEncoders::From(n) whose n lies inside it, a FailedEncoders::Set that names some of them, a fault or a recording failure at one) splits it at the commit: the encoders that run are recorded again from their logs, each into VkCommandBuffers of its own, so exactly the encoders the failure names run nothing, as on Metal; so does an unbalanced record that leaves out the work of its unit's encoders from one past the group's first (a blit encoder ends a unit of command predication). Where a running compute encoder of the group lies in a unit of command predication that a later encoder of the command buffer made lay a loop (ComputeCommandEncoder::encode_start_while, encode_start_do_while) or leave work out (an unbalanced record), it cannot be recorded again outside its blocks, and such a failure fails the whole group instead, where Metal runs the group's encoders before n and those the set leaves out. So does a group one of whose calls answers otherwise when recorded again. A command buffer with a submission check (CommandBuffer::set_submission_check) has the encoders whose commands such a group's shared VkCommandBuffer holds recorded again apart at the commit where they lie in more than one of Metal's submissions, so a check fails its own submission's encoders alone; where they cannot be recorded again so, a check that fails one of those submissions fails each of them, where Metal runs the others.

GPU hangs and faults (a draw of private primitive type 9, DrawPrimitiveType::Nine)

  • A hang reads Scheduled 5.06 ms after its commit and completes no sooner than 27.5 ms after that and the GPU reached it, and its queue runs nothing of what it schedules meanwhile: one of Metal's two outcomes. On an M3 Max (macOS 27.0.1, 33 hangs) Metal's hang read Scheduled 0.68 to 13.2 ms in and completed about 27.6 ms after; the queue's later command buffers' work mostly ran on the GPU during the hang where it read Scheduled within 2 ms (17 of 18), and mostly did not where later (56 of 62 ran nothing or in part). Either way they read Scheduled from the hang's on, as they are committed or their event waits are met, and complete with the hang, its signals firing, as the runtime's do (0.04 to 1.5 ms after it on MoltenVK, Metal's 0.01 to 0.03 ms).
  • A page fault or a victim of the GPU's recovery runs nothing from its encoder on, and completes no sooner than 6.86 ms after it read Scheduled and the GPU reached the encoder, its event signals firing, the encoders before it run, and its queue's command buffers committed meanwhile reading Scheduled as they are committed, and running: Metal's steady state. On an M3 Max (macOS 27.0.1, 164 command buffers: type-9 draws and executions of indirect commands under a state that cannot inherit) Metal completed it 6.86 to 10.3 ms after Scheduled, and whether the encoders after the faulted one ran was a race the GPU's state decides: lost to its recovery where the GPU ran just before (127 of 142), run where it was idle before (the first fault after 3 s idle), and run in part in some shapes (an encoder after an event signal, a command buffer committed right after). The runtime does not model the GPU's idle state.
  • A fault that later failing encoders follow fails with the fault's error, in their time: it reads Scheduled no sooner than 6.86 ms after the GPU reached the fault, and completes no sooner than 6.86 ms after that for each later fault, then 27.5 ms for a hang, past which nothing adds; its queue's command buffers committed meanwhile run nothing where a hang follows the fault, as during a hang. On an M3 Max (macOS 27.0.1, 88 command buffers) Metal's read Scheduled 14.3 to 21.0 ms after its commit, once the GPU recovered from the fault, and completed 25.8 to 29.1 ms after that where a hang followed the fault. One that hangs first fails as the hang alone does (30 of 30), the GPU never reaching the fault.
  • A queue's second caused GPU error revokes it, as Metal's does, and only an event wait held across the revocation is answered unmeasured. Measured on the M3 Max (macOS 27.0.1, about sixty command buffers): page faults and hangs (CommandBufferError::PageFault, GpuHang) count against their queue, victims of the GPU's recovery (GpuRecoveryVictim) do not; from the completion of the queue's second counted command buffer, every one committed on that queue fails at its commit with CommandBufferError::AccessRevoked (MTLCommandBufferErrorAccessRevoked, 4), running nothing and firing none of its event signals, for good (two seconds on too), while one committed before it runs; the device's other queues, new ones too, run on. The runtime counts the faults and hangs it makes Metal's answer for (primitive type 9, an execution of indirect commands under a state it cannot inherit) and those a program commits as failed in their place (commit_failed with Metal's code 3 or 2, CommandBufferError::Injected), not the ones the driver relays, and decides at the commit: a command buffer committed before the revocation runs whatever its event waits, a predicated loop's runs again included (on the M3 Max a loop committed before the revocation ran all its passes after it, with no error).

The Mac a device presents

  • A device answers as the class of Mac it presents. An Apple silicon Mac's GPU keeps textures losslessly compressed; a Mac's Intel or AMD GPU keeps none. A device presents the class DeviceOptions::mac_class declares (MacClass), by default its GPU's: an Apple silicon Mac on an Apple GPU (vendor 0x106b, MoltenVK on Apple silicon), a Mac with an Intel or AMD GPU on every other GPU, an integrated one of unified memory included (an Intel UHD 630 Mac reports unified memory and keeps no texture compressed). DeviceProperties::lossless_compression states it. On a device that presents a Mac with an Intel or AMD GPU (lossless_compression false), the runtime answers as that Mac:

    • a new Private texture reads zero, filled at its first use (WorkCounts::private_textures_zero_filled counts each; no fill where that use, a pass that loads it Clear and stores it or a blit into its whole extent, writes every texel before any command reads one, WorkCounts::private_textures_overwritten_unfilled), where an Apple silicon Mac's reads zero or the compressed texture's fixed pattern, so fresh-pattern-zeroed is never announced. Such a Mac's holds what its memory held. Measured on Macs with an AMD Radeon Pro 5300M and an Intel UHD 630 (the consumer's probes): new Private textures read zero; a mipmapped RGBA16Float one made right after a cleared one of its descriptor was released read the cleared colour in every level on both; a Depth32Float one never read the released clear. That colour is the same process's. A consumer that serves several processes from one device would show one process another's texels that way, which macOS never does, so the runtime gives the zeros those Macs read where their memory held nothing, which Metal's undefined contents allow.
    • a GPU blit or fill through any texture keeps its bytes, with no extended-range-bits-kept, device-nan-encoding or shared-exponent-kept note for it and no rewrite under ExtendedRangeBlitPolicy::Canonical, and a clear of any texture takes the route of Metal's uncompressed one, through half, so a half NaN clear keeps no sign and an extended-range or bfloat clear rounds as through half. Expected, not measured on such a Mac.
    • a Clear load in a pass of one layer without a draw call clears the attachment's whole level and slice past the render area, whatever its texture. The Macs disagree there (the consumer's probe tileclear2, jobs m3-max-12736 and m3-max-12737): an AMD Radeon Pro 5300M clears the whole level or slice at every format, shape and allowGPUOptimizedContents; an Intel UHD 630 anything from the render area alone (a level past the first, a slice past the first, 4x multisampled) to the whole texture (plain 4-, 8- and 16-byte color formats). Metal guarantees nothing past the render area, and the runtime gives the 5300M's answer.
    • a sampler state's lodBias is added to every sample's level, an explicit level's, a gradient's and an implicit one's alike, the sum clamped into the texture's levels, as an AMD Radeon Pro 5300M and an Intel UHD 630 sample it (the consumer's probe): the state's binds hand the device its bias as mipLodBias (SamplerUse::lod_bias), which Vulkan adds to an explicit level too. A bias past the device's maxSamplerLodBias adds that limit, and a NaN, or any bias where the device's portability subset withholds samplerMipLodBias (MoltenVK), none, announced (capped-lod-bias, the state's PrecisionNote::CappedLodBias). A device that presents an Apple silicon Mac samples every level as with no bias, as an Apple M3 Max (Apple9) does.
    • maxThreadgroupMemoryLength (DeviceProperties::max_threadgroup_memory_length) is the device's maxComputeSharedMemorySize up to 65536 bytes, which an AMD Radeon Pro 5300M and an Intel UHD 630 answer (the consumer's probes), where a device that presents an Apple silicon Mac answers up to 32768, an Apple M3 Max's: RADV's 65536 bytes answer 65536, ANV's and NVIDIA's 49152 answer 49152. A dispatch takes threadgroup memory up to the device's own limit whatever the class, so every length answered runs.

    Metal leaves a new texture's contents undefined, and zero and a released texture's texels are both what such a Mac reads, so this trades no accuracy and no DevicePolicy switch fills the texture. A device that presents an Apple silicon Mac (lossless_compression true) answers as one, on any GPU: the runtime writes the pattern and the zeros of a new Private texture, a pattern no clear or copy writes exactly reading zero (fresh-pattern-zeroed), and a Clear load in a pass of one layer without a draw call clears a texture Metal keeps compressed over its whole level and slice past the render area and any other texture over the render area rounded up to 32x32 tiles clipped to the level, as a pass with a draw call clears every texture, and no other level or slice (our probes on the M3 Max under macOS 27.0.1: every color format, depth and stencil format, sample count, level, slice and usage measured, and a texture over a buffer; the consumer's tileclear2, jobs m3-max-12716 and m3-max-12735, alike). In such a pass the runtime clears the attachment before the pass, by a render pass of that attachment alone, and the pass loads it over Metal's render area, so a DontCare or Load attachment beside it keeps its texels past that area as Metal keeps them. Under a declared class other than the GPU's, the blit encodings and NaN signs above are the runtime's own handling, except that MoltenVK's copies of an image Metal compresses on an Apple GPU still write the canonical RG11B10Float and RGB9E5Float encodings (RuntimeDriverDefect::CompressedImageCopiesRewriteTexels). Expected, not measured, beyond the new textures' contents.

Heaps and memory

  • A heap texture answers Metal's size and alignment where the device's image fits them, else the device's (Device::heap_texture_size_and_align, DevicePolicy::heap_answers). Under the default HeapAnswerPolicy::Device, a texture whose image binds into the heap's memory (a multisample one too) and needs more than Metal's answer answers the larger of the two and lies in that image: no image is put in its place and no shadow holds it. The alignment it takes is the device's (on an RX 7900 XTX, 256 KiB for a 4-sample render target past 128 texels a side), at most a heap's memory's own, 256 KiB, past which no image binds there, and at most 4 KiB or its own size; where its image asks more, its image that a 4 KiB alignment holds (host-transfer usage, else linear) takes its place. A Shared texture's answer also holds the linear image a heap over host pages binds. Under HeapAnswerPolicy::Metal (in exact_answers), the answer is Metal's: an image that fits it takes the place of one that does not, else a shadow of the heap's bytes holds the texture there, and only a texture neither holds answers the device's (heap-texture-larger-than-metal). Metal's measured answers (4:2:2, one-plane YCbCr, two-plane extended-range, X32_Stencil8, BlockWritesOnly) hold under either value. A placement heap's newTextureWithDescriptor:offset: is held to Metal's own alignment, not that answer, for a texture whose image lies in memory of its own (a shadow of the heap's bytes, a multisample texture's samples in Metal's tiles): no image binds to the heap's memory there, so every offset Metal makes the texture at makes it here, and such a texture is held to no alignment bound of the heap's memory base either, whatever alignment it answers. A texture an image of does bind into that memory is refused NotImplemented(HeapTextureAlignment) where its answer passes the base (256 KiB, the largest image alignment measured).
  • A heap's texture answers the size that placed it (Texture::allocated_size, Metal's allocatedSize): the size query's answer for its descriptor, a view's its texture's, as Metal answers; None for a texture outside a heap, whose Metal answer the runtime does not model.
  • The runtime's heap texture size and alignment are the device's own (metal2vulkan-runtime's Device::heap_texture_size_and_align, its README's heaps): the device's own image requirements, not Metal's, the size rounded up to and the alignment raised to the device's bufferImageGranularity, so a buffer placed by the same answers never shares a granularity page with the texture. The answers differ by device, so the consumer places by this device's. The conformance suite does not compare the two numbers with Metal's on the new runtime; it holds each answer to three steps: (1) the alignment is a power of two; (2) a Private descriptor's texture is made at offset align in a heap of align + size bytes; (3) there, level 0's first slice written from a buffer reads back unchanged. A Shared, Managed or Memoryless descriptor is held to step 1 alone, as the new runtime places heap textures in Private blocks only. A descriptor whose bytes the new runtime does not move (depth and stencil both, multisample, Depth32Float) is held to steps 1 and 2.
  • A no-copy buffer's keep-alive waits for the buffers bound inside its import (KeepAlive, a runtime extension with no Metal counterpart). A no-copy buffer made over part of a live one's bytes, or over the same bytes as memory of another class, is bound inside the live one's import rather than importing the pages again: one live import of a page at a time, as VK_EXT_external_memory_host leaves a host allocation imported twice into one device undefined (issue 6 of the extension). It holds that import until it goes, so the first buffer's keep-alive, which keeps the pages that import maps, is dropped once the import is freed: after both buffers' releases, never before. Given with a keep-alive, the first buffer's deallocator still runs at its release, as Metal's; given none, it waits for the free, announced as host-deallocator-delayed. Counted: WorkCounts::host_releases_held_inside, each release so held, beside host_keep_alives_kept (held now) and ObjectChurn::buffers_bound_in_import. A program that unmaps the first buffer's pages as its keep-alive drops unmaps them after the later buffer's release too, never before.
  • Metal's own heap answer, for bookkeeping (Device::metal_heap_texture_size_and_align, no Metal counterpart): what plain Metal answers, for a consumer that lays out a guest's heap.
  • Where Metal's answer is not its image's, every device answers Metal's, for the few formats the runtime holds in an image of another layout.
  • A multisample texture answers at least Metal's size and alignment.
  • Metal's answer by usage: Metal's size depends on whether it compresses the texture, which follows its usage bits and shape; the bookkeeping answer follows the measured rule.
  • Apple's private texture usage bits are kept in TextureUsage (NO_CONCURRENT_ACCESS, VIDEO, BLOCK_WRITES_ONLY).
  • max_buffer_length takes the largest device-local heap for Metal's working set (DeviceProperties::max_buffer_length, Metal's maxBufferLength). Metal answers three quarters of recommendedMaxWorkingSetSize, to 16 KiB, on the Radeon Pro 5300M and the M3 Max (measured), and Vulkan has no working-set query, so the runtime answers the smaller of the compile layer's length and three quarters of the largest DEVICE_LOCAL heap, to 16 KiB: about 12 GiB on a 16 GiB card, where the device's own maxBufferSize is 2^40. A longer buffer is nil, as Metal's is.
  • A heap larger than the device's maxBufferSize is refused: a heap's buffers live in one VkBuffer over the heap's allocation.
  • A Shared heap's textures are linear images where the device's optimal images take no host-visible memory.
  • A sparse texture on a device without shader residency holds all its texels' memory.
  • A sparse mapping update of a slice past the texture's own maps nothing. Metal's API validation refuses such an update; plain Metal takes it, charges its heap's usedSize one page a tile of the region (clipped to the level's tiles), and binds that page at an address its own page layout derives: on an Apple M3 Max under macOS 27.0.1 a 16 by 16 texel block of slice 0's mapped tile (0, 0) then read Metal's unwritten pattern. The runtime charges the heap the same pages, given back on an unmap of each tile (ResourceStateCommandEncoder:: update_texture_mapping), and leaves every texel as it was: Vulkan binds nothing past an image's layers (VUID-VkSparseImageMemoryBindInfo-subresource-01723), and which texels Metal's page reaches is not derivable from what was measured.
  • A sparse tile a move rebound reads all its texels, compressed or not. Under Metal's default allowGPUOptimizedContents, Metal may keep a sparse texture losslessly compressed, and a tile moveTextureMappingsFromTexture:… rebound into one can then read its moved texels in only part of the tile: on an Apple M3 Max under macOS 27.0.1 a ShaderRead R32Float tile held them in 128 of its 4,096 texels (the first 4 by 2 of each 16 by 16 block) and 0 in the rest. With allowGPUOptimizedContents off, ShaderWrite or PixelFormatView usage, Metal's moved tile read all 4,096. The runtime's moved tile holds all of its texels under every descriptor; it does not reproduce the loss.
  • A heap's buffer and texture over the same bytes alias them, in the device's layout, not Apple's tiled or compressed one.
  • A tiled texture's replace_region of a later level reaches the GPU (Buffer::new_tiled_texture, more than one level; Texture::replace_region): it writes the texture's image, which its commands read until the next take of its copy makes that level again. Two x86 Macs (an AMD Radeon Pro 5300M and an Intel UHD Graphics 630 under macOS 26.7.1) never showed such a write to the GPU; what their getBytes reads of a later level is not measured. The runtime's get_bytes there reads the image. The first level is Metal's on both calls: the buffer's bytes.
  • A heap's one-plane YCbCr texture whose rows share bytes keeps the earlier row's bytes there. Metal's blits lay a one-plane YCbCr texture's rows of 16 bytes or more that are not a multiple of 16 the row rounded down to 16 bytes apart, so consecutive rows share the row's last row % 16 bytes, and so does the runtime, each row read whole from its own offset. Metal's blits leave the shared bytes from no one row: on the Apple M3 Max under macOS 27.0.1 (probes/one_plane_ycbcr_heap_rows.m), the even rows' at 10 x 3, 12 x 3, 20 x 3 and 13 x 7, the later row's at 33 x 3 and the earlier row's at 100 x 30. The runtime's GPU writes leave the earlier row's, one of those, the same every time.
  • A texture over a buffer keeps its texels past what the buffer's memory holds in a tail of its own. Plain Metal makes a 2D texture, an array or a texture buffer over a buffer whose texels run past its length, up to where the buffer's allocation ends, counted from the buffer's start (nil past it): its allocatedSize (its length rounded up to 16 KiB), a heap's buffer's heap's size, a no-copy buffer's pages (its pointer's offset in its 16 KiB page plus its length, rounded up to 16 KiB). A 2D texture and a texture buffer count to their last texel, an array to its slices' end, each slice rounded up to 128 bytes (BufferTextureProblem::PastAllocation; an Apple M3 Max under macOS 27.0.1, each kind and form bisected). The runtime makes more than the M3 Max in two cases, as an AMD Radeon Pro 5300M and an Intel UHD 630 under macOS 26.7.1 do (each end measured made, to 16 MiB): a buffer under 16 KiB takes a texture however far past its length, where the M3 Max answers nil past 131072 bytes of a buffer of its own, past its pages of a no-copy buffer and past its heap's size of a heap's buffer; and an array whose last texel lies inside the length is made whatever its slices' end. Where the buffer's memory holds the texels, the texture lies there as one inside the length does, as Metal's does: a buffer of 16 KiB or more that the device makes (new_buffer, new_buffer_with_bytes, new_buffer_with_descriptor but for an exportable one) holds its allocation, its VkBuffer its length rounded up to 16 KiB, zero when made; and a heap's buffer reaches to its heap's end, its texels past its length the heap's bytes there, another resource's where one lies there, as on Metal. The buffer itself still ends at its length: a blit of its bytes past it is refused, as Metal's validation refuses it. Past a no-copy buffer's length (its pages past it are the caller's), past a wrapped VkBuffer's or an exportable buffer's, past a buffer's under 16 KiB, and past a heap's end, the texture is a copy: a 2D texture or an array is a shadow image whose copies in and back go through its tail (shadowed-texture), and a texture buffer's functions view its tail, which copies in and back too (staged-texture-buffer); its texels the buffer's memory holds are the buffer's bytes on every path. Metal's texels past the length are the memory after the buffer's: on an Apple M3 Max under macOS 27.0.1 (probes/texels_past_buffer_length.m, probes/texture_buffer_past_length.m) a kernel's read() and sample(), a blit and getBytes read the next allocation's bytes there, and a kernel's write(), a blit and replaceRegion write them, changing that allocation; past a 20000-byte buffer's length, inside its allocation, they read zero. On both, what one path writes there every path reads, and the texels inside the length are the buffer's bytes. The runtime's texels past what the buffer's memory holds lie in the texture's tail (Buffer::new_texture): zero when made, read and written alike by its functions, blits and CPU calls, and no other allocation's bytes; two textures over one buffer past it keep a tail each. A colour texture over a plane of an IOSurface with planes keeps its texels past the surface in a tail of its own too, announced (metal2vulkan-degrade-surface-texels-tail), where Metal lays them in no one place; the plane shapes that keep no tail (a two-plane YCbCr, two-plane extended-range, 4:2:2, depth, stencil, BC or rotated texture) stay NotImplemented(TexelsPastBufferLength) there.
  • A 2D array of several slices over an IOSurface plane keeps its slices past the first in a tail of its own. Over a plane of a surface with planes Metal makes a 2D array of any slices. On an Apple M3 Max under macOS 27.0.1 (probes/surface_texture_envelope.m) its first slice lies over the plane on every path, and its second in no one place: its blits and getBytes read it at the plane's offset, over the first slice, its kernels one image on, and its blits' and replaceRegion's writes of it land at the plane's offset, over the first. The runtime's first slice is the plane's bytes, as Metal's is; its slices past the first lie in the texture's tail, zero when made, read and written alike by every path, and reach no byte of the surface, announced (metal2vulkan-degrade-surface-texels-tail). A colour array over a plane whose offset and bytesPerRow are multiples of 16 is made so; one off 16, or of another format, stays NotImplemented(SurfacePlaneShape).
  • A mipmapped, 3D or multisample texture over an IOSurface plane lies in memory of its own. Over a plane of a surface with planes Metal makes a 2D texture of several levels, a 3D texture and a 2D multisample one. On an Apple M3 Max under macOS 27.0.1 (probes/surface_texture_envelope.m) it lays their texels out in no one place, their first level and slice among them: its blits and kernels read other bytes than its blits, replaceRegion and getBytes write and read there. The runtime's such texture of a colour format lies in memory of its own, zero when made in every storage mode, read and written alike by every path, and reaches no byte of the surface, announced (metal2vulkan-degrade-surface-texels-apart): no level or slice of it is the plane's, as the M3 Max's are not. The x86 Macs under macOS 26.7.1 (an AMD Radeon Pro 5300M and an Intel UHD 630) keep the first level and slice over the plane, and the runtime does not. Such a texture of another format stays NotImplemented(SurfacePlaneShape), and a Memoryless one NotImplemented(MemorylessSurfacePlane).
  • A BC1 or BC4 texture over an IOSurface plane at an offset off 16 reads and writes the plane from its offset on the CPU too. The Apple M3 Max answers nil for a BC texture over a surface, so the x86 Macs' Metal under macOS 26.7.1 is the reference (probes/surface_texture_envelope.m, bgraat8.bc1 and bgrarow264.bc1). Over a plane at offset 8 or at 264 bytes a row, an AMD Radeon Pro 5300M's and an Intel UHD 630's blits and samples take block row j at the plane's offset + j × bytesPerRow, unrounded, and so do the 5300M's getBytes at both and the UHD 630's getBytes and replaceRegion at 264 bytes a row; at offset 8 the UHD 630's getBytes and replaceRegion take the plane from byte 0, and the 5300M's replaceRegion writes other bytes than the texture's past its first row of blocks at both. The runtime's BC1 or BC4 texture there lies at the plane's own offset and pitch on every path, its CPU calls among them. BC4 was not measured off 16; it takes BC1's 8-byte block rows. A BC texture of 16-byte blocks off 16 stays NotImplemented(SurfacePlaneShape).
  • A BC1 or BC4 texture over an IOSurface plane whose rows of blocks are wider than the plane's keeps each row to the plane's row, its blocks past it zero on every path. The x86 Macs under macOS 26.7.1 make a BC1 64x64 texture over a 420v surface's luma plane of 64 bytes a row (probes/surface_texture_envelope.m, 420v.p0.bc1.64x64; the M3 Max answers nil): an AMD Radeon Pro 5300M's and an Intel UHD 630's blits read each row of blocks' first bytesPerRow bytes at the plane's offset + j × bytesPerRow and its other blocks as zeros, and write only those first bytes. The UHD 630's samples of the other blocks decode other memory, the 5300M's replaceRegion writes other bytes past the texture's and ends the process, and the UHD 630's getBytes and replaceRegion take whole rows of blocks bytesPerRow apart from the surface's first byte. The runtime's such texture over a plane at an offset and bytesPerRow that are multiples of 16 lies as the GPUs' blits lay it on every path, its CPU calls among them: its blocks past the plane's row read zero (samples too) and take no write. BC4 was not measured; it takes BC1's 8-byte blocks. One of 16-byte blocks so wide, or over a plane off 16, stays NotImplemented(SurfacePlaneShape).
  • A cube or cube array over an IOSurface plane lies face after face on the CPU too. Plain Metal asserts on one on an Apple M3 Max under macOS 27.0.1; the x86 Macs under macOS 26.7.1 make it (probes/surface_texture_envelope.m, bgra1x2.cube.16, bgra1x2.cubearray.16, bgra1x2.cubearray.8.a2 and 420v.p0.cube.8): an AMD Radeon Pro 5300M's and an Intel UHD 630's blits and kernels take face k (every cube's six, one cube after another) at the plane's offset
    • k × its rows × bytesPerRow inside the plane, and read other bytes or zeros for a face past the plane's rows, where their blits write nothing. The 5300M's getBytes and replaceRegion take every face at the first's bytes, and the UHD 630's take the faces one image apart from the surface's first byte. The runtime's colour cube over a plane at an offset and bytesPerRow that are multiples of 16 lies so on every path, its CPU calls among them; a face past the plane's rows but inside the surface is the surface's bytes there, as every texture's rows past its plane are (the call gives no plane height), and a face past the surface lies in the texture's tail, zero when made, announced (metal2vulkan-degrade-surface-texels-tail). One of another format, off 16 or of several levels stays NotImplemented(SurfacePlaneShape).
  • The runtime's Managed copies read the consumer's bytes when the GPU reaches them (metal2vulkan-runtime's Buffer::did_modify_range and Texture::upload_region). On a device whose Shared memory is not device-local, a Managed buffer's changed range is one device copy from the consumer's bytes into the buffer's device copy, and on every device a Managed texture's uploaded region is one device copy from its named bytes into its image, at the head of the next submission, ahead of every command buffer committed after the call on every queue. The copy reads the bytes as they are when the GPU runs it, so a write the consumer makes after the call and before then may be seen. Metal leaves it undefined: an Apple M3 and an Intel UHD 630 take the bytes when the GPU reads them, an AMD Radeon Pro 5300M at the commit.

Function constants

  • A function constant the request leaves undefined reads as zero. A value computed from it alone is its type's zero (an and, or or mul with a constant that decides it is that constant), and a branch or select on one takes its false way; a value it meets with one the run computes is computed with that zero. As Metal's, is_function_constant_defined is false for it and an argument gated on it, negated or not, is absent. Metal makes the same pipeline of a specialized function (made with constant values, none among them too, or by newFunctionWithDescriptor:), and its reads of the constant vary from read to read: on an M3 Max under macOS 27.0.1 it read u + 3 as 0, u * 7 + 1 as 1, u == 0 ? 111 : 222 as 222 and b ? 5 : 6 as 5. The compile is the same for a function made by newFunctionWithName:, which Metal makes no pipeline state of where its function declares a constant: its creation ends the process at every stage ("function ko cannot be used to build a pipeline state. Use newFunctionWithName:constantValues:... to get the specialized function"), whether the constant is required, read only where is_function_constant_defined says, or only gates an argument. FunctionDescriptor::needs_specialization answers it (FunctionDescriptor::specialized and the function's function_constants_dictionary), and the runtime refuses such a state as Metal does (Invalid with Problem::UnspecializedFunction). A linked function keeps its own rule (section 3, "Linked functions: names and constants").
  • A fast-math float operation of a NaN function constant and a value the run computes stores that NaN. An fadd, fsub, fmul or fdiv that carries nnan (Metal's default fast math) and whose operand is a function constant bound to a NaN is poison in the AIR once the constants are bound, so any value is a correct answer for it. The translation answers the NaN operand, its bits unchanged, as it does for the same operation without fast math, where that NaN is Metal's answer. Metal answers a NaN for a fragment function's output of it on an Apple M3 Max, an AMD Radeon Pro 5300M and an Intel UHD Graphics 630 under macOS 27.0.1. On the M3 Max a kernel's store of it writes nothing, float and half alike, and the memory keeps what it held, while the same kernel's store of the run value is written (the fixture sfold_fast_poison, case 2d9a7e3091e1f9d9, job m3-max-12877; the case stays out of the corpus, whose comparisons are exact). The runtime on MoltenVK writes the NaN there.
  • A linked function's constant without a value reads as zero too, where the function was made specialized (section 3, "Linked functions: names and constants"). Metal makes that pipeline, and its read is undefined: a kernel storing x * scale + 1 of such a function stored nothing on an M3 Max under macOS 27.0.1.
  • A program-scope constant that the function constants make a division by zero reads as an undefined constant reads. A static initializer's scalar integer division or remainder by zero (udiv, sdiv, urem, srem) has a result the AIR leaves undefined, and so does everything computed from it: the translation reads it as zero, and a branch or select on it takes its false way, as for a constant the request leaves undefined. Metal makes that pipeline on an M3 Max under macOS 27.0.1 and stores nothing of the quotient, nor of a value chosen by it; where a loop's trip count is computed from it, the kernel stores nothing at all (the probe static_init_division.m). A vector division with a zero lane is still Unsupported{StaticInitializer}.

Linked functions

  • A reference of another type reads zero or its arguments' bits where Metal's read is undefined (section 3, "Linked functions: types"). A parameter the reference passes nothing for reads zero, as Metal's read zero on an M3 Max under macOS 27.0.1 and on a Radeon Pro 5300M and a UHD Graphics 630 under macOS 26.7.1. An argument of another width passes its low bits to a narrower parameter, as the 5300M did for a float passed to a half, where the M3 Max and the UHD 630 left the parameter undefined (a kernel storing a value computed from it stored nothing); it passes its bits with zeros above to a wider parameter, and a result of another width or one a definition returning nothing gives passes the same way or reads zero, where the M3 Max stored nothing.
  • A reference passing a pointer for a value or a value for a pointer, a pointer of another address space, or an aggregate of another type is refused (Unsupported, Feature::Linking), where Metal makes the pipeline: on the M3 Max each such read was undefined (the kernel stored nothing); on the 5300M a value for a pointer read the pointer's low 32 bits and a constant pointer for a device one read through it.

Conversions

  • air.convert with a rounding (.rte, .rtz, .rtp, .rtn) and .sat after its types is honored in a compute pipeline of OpenCL mode and is the conversion its types name elsewhere. Apple's OpenCL compiler spells these on every convert_<type>[_sat][_<mode>].

    In OpenCL mode (ComputePipelineDescriptor::open_cl_mode_enabled) Metal honors them. Measured over OpenCL C of our own, one work-item per operand (probe jobs m3-max-15651 on a Radeon Pro 5300M and m3-max-15652 on a UHD Graphics 630, both macOS 26.7.1):

    Form, OpenCL mode Radeon Pro 5300M UHD Graphics 630 Runtime
    integer of 8 to 64 bits to float, .rtz, .rtp, .rtn rounded as named rounded as named rounded as named
    float to an integer of 8 to 64 bits, .rte, .rtp, .rtn rounded as named, then clamped where .sat as the 5300M, but a uint of 2^31 or more is 0x7fffffff and a uchar with .sat above 127 is 127 rounded as named, then saturated (the 5300M's answer)
    integer to integer, .sat clamped to the destination's range clamped to the destination's range clamped to the destination's range
    a half side, any suffix no pipeline no pipeline the conversion its types name

    An integer to float by .rte, a float to an integer by .rtz, and an integer to an integer with a rounding and no .sat are the conversion their types name on both, as on the runtime. Neither creates a pipeline of OpenCL mode for a conversion with a half side (its library compiles), so no Metal answer exists for one, and the runtime makes the pipeline. The device has no directed conversion (Vulkan's integer-to-float conversion rounds in a direction of its own, its float-to-integer one truncates), so the runtime builds each exactly: a float is rounded to an integral value (RoundEven, Ceil, Floor) before the conversion, and the device's conversion of an integer to float moves one unit in the last place where it lies on the wrong side of the integer.

    Outside OpenCL mode Metal's compilers do not answer them alike. Measured over the owned fixture kernel_convert_rounding_modes's edge values, one kernel per form (probe jobs m3-max-14380 on a Radeon Pro 5300M and m3-max-14381 on a UHD Graphics 630, both macOS 26.7.1; m3-max-14382 on the M3 Max, macOS 27.0.1), the runtime differs from a Mac in three places:

    Form M3 Max Radeon Pro 5300M UHD Graphics 630 Runtime
    float to integer, .rte rounds to nearest even truncates no pipeline truncates
    float to half, .rtz, .rtp, .rtn .rtz as named; no pipeline for the others nearest even as named nearest even
    float to integer, .sat an unsigned destination keeps a negative's wrapped bits; a long of an infinity is 0, past its range wraps an 8-bit destination is not clamped; a long is clamped to int's range no pipeline clamps, as its conversion without the suffix

    Everywhere else every Mac that creates the pipeline answers the conversion without the suffix, which is no difference: an integer to float or half by any rounding is rounded to nearest even (the M3 Max creates no pipeline for a directed one), an integer to an integer with .sat wraps (the M3 Max creates none), and a float to an integer by .rtp or .rtn truncates on the 5300M (the others create none). The M3 Max's compiler service exits on the forms it does not compile, where the runtime compiles them all.

  • vstore_half and vstorea_half with a rounding (_rtz, _rtp, _rtn) store each lane as the device converts a float to half, to nearest even. Measured over 32 values among them ties, overflows past the largest half, subnormals and zeros, with the vstore_half4 forms alike (probe jobs m3-max-15563 on the M3 Max, macOS 27.0.1; m3-max-15564 on a Radeon Pro 5300M and m3-max-15584 on a UHD Graphics 630, macOS 26.7.1):

    Form M3 Max Radeon Pro 5300M UHD Graphics 630 Runtime
    vstore_half_rtz, _rtp, _rtn (70000.0 by _rtz) as named (0x7bff) nearest even (0x7c00) nearest even (0x7c00) nearest even (0x7c00)
  • A float past an integer's range converts to the integer's nearest bound, a long of an infinity too, where Metal's is 0. MSL states two answers of a conversion from a floating-point type to an integer (MSL 8.6): it rounds toward zero, and a NaN converts to 0. Metal's compiler spells every such conversion of MSL as an air.convert call (measured over int, uint, static_cast and two-lane vector forms of float and half, in a kernel and in fragment functions, with fast math on and off: probe job m3-max-55309, Metal compiler 32023.922), which the runtime converts so, and which takes a value past the destination's range to its nearest bound. Metal on the M3 Max (macOS 27.0.1) answers the same at every width from char to ulong, from float and from half, but converts either infinity to a long as 0, where ulong of +inf is its maximum (conformance case nan-to-integer-conversions). A plain LLVM fptosi or fptoui, which Metal's compiler does not emit, is Vulkan's OpConvertFToS or OpConvertFToU, whose result for a NaN or a value its integer cannot hold SPIR-V leaves undefined: the device's own.

Inline assembly

  • An empty asm volatile("") is no compiler barrier. It is the one inline assembly MSL accepts (a template, an operand or a clobber is an "illegal asm statement"), and it assembles to no instruction: the translator drops its call, asm sideeffect "", "" of type void (), with no notice. In Metal it acts on the compiler alone: no memory access moves across it, and a loop that holds it is kept. Only a racy spin loop over plain (non-atomic) memory can tell the difference, and MSL's memory model leaves that loop undefined; a loop with a visible effect runs every iteration either way. Any other inline assembly, which only hand-written AIR can hold, is refused where an entry reaches it (Feature::InlineAsm).

Kernels

  • A kernel's writes of a texture over a buffer may change its rows' padding (each row's bytes after its last texel to its pitch, the last row's included), where the texture is an image in place over host pages whose rows, each to its pitch, start and end on a line of the device's memory (nonCoherentAtomSize), its buffer holding the last row to its pitch, and the device's check found its kernel's storage writes changing no byte but of such padding (the check report's buffer writes verdicts). Metal leaves those bytes to the GPU, and the rule follows the x86 Macs' envelope. Measured over 100 rounds of each operation, the CPU writing the padding while the GPU ran, BGRA8Unorm textures of 3662x64 and 61x64 over a buffer (14848 and 256-byte pitches) and over an IOSurface (14656 and 256): an Intel UHD Graphics 630 (macOS 26.7.1) wrote older values back over the CPU's writes to the padding of the textures over a buffer under a kernel's writes (10,197 and 28,162 bytes, 304 and 307 of them in the last row), and over the IOSurfaces and under a pass's clear and store or a draw kept every byte; an M3 Max (macOS 27.0.1, arm64 and x86_64) kept every byte under each; a Radeon Pro 5300M (macOS 26.7.1), its rows read once each operation completed, with no CPU write meanwhile, kept every byte under each. A render target's rows, an IOSurface plane's, and the bytes past the last row's pitch or between slices keep every byte (crates/metal2vulkan-conformance/probes/row_padding_writes.m).
  • A buffer argument a kernel only reads is read-only memory to the device where the AIR declares the argument unaliased (the air-buffer-no-alias attribute, which the AIR of Metal's current compiler carries on every buffer argument) and no store, atomic, volatile or coherent access of the kernel reaches it, through the argument or through a pointer its address may come back as: its views are decorated NonWritable, and under the identity domains (the new runtime) its device-address loads go through NonWritable places. Under the identity domains a constant buffer argument is read-only memory too, whether or not the AIR declares it unaliased: Metal's constant address space is read-only. A dispatch that binds memory to such an argument and to an argument the kernel writes may read those bytes as they were before its own writes, where the device reads read-only memory through another path (RADV reads a uniform address of it with a scalar load). The attribute states that no other argument reaches that memory.
  • A dispatch that reaches a buffer bound off its argument's alignment is refused (the alignment the kernel's AIR states for the argument, air.arg_type_align_size, at most 16; RuntimeFact::AddressAlignment): the new runtime refuses the dispatch (Refusal::BufferOffsetAlignment) where the bound address, the buffer's gpuAddress plus the offset, is not a multiple of it, before anything is recorded, as Metal's API validation refuses such a bind offset ("must be a multiple of 4 but was set to 2" for a uint * argument). Without validation an Apple M3 Max (macOS 27.0.1) runs it, reaching each element at its address rounded down to the smaller of the element's alignment and 4, for loads, stores and pointers stored in a buffer alike (crates/metal2vulkan-conformance/probes/misaligned_buffer_binds.m).
  • An imageblock's length rounds its cell as an M4 does (ComputePipelineState::imageblock_memory_length_for_dimensions), never less than what a dispatch counts against the device's threadgroup memory.
  • A recursive call past the call stack yields zero: the stack holds what Metal's byte model holds for the pipeline's max_call_stack_depth; a call that finds it full returns zero, where Metal's answer is corrupt.
  • The threads of a SIMD-group run in no order between barriers under the identity domains (the new runtime), where an Apple GPU runs them in lockstep: the Metal Shading Language orders their memory accesses only through barriers and atomics, and calls two of them that conflict between barriers a data race.
  • A simdgroup barrier in divergent code waits for its tangle, as SPIR-V defines it. The Metal Shading Language requires every thread of the SIMD-group to execute a simdgroup_barrier that any of them executes in a conditional or a loop iteration, so Metal defines no answer there.
  • A state whose descriptor requires a threadgroup size answers that size's threads as its maxTotalThreadsPerThreadgroup, lowered only to the device's own limit (ComputePipelineState::max_total_threads_per_threadgroup, and a tile state's RenderPipelineState::max_total_threads_per_threadgroup). A compute state compiled by Metal for the first time answers the same (M3 Max, macOS 27.0.1, each state of a source compiled once: 1 for 1x1x1, 21 for 7x3x1, 128 for 8x8x2, 1024 for 32x32x1). The runtime differs in two ways:
    • A tile state answers the size's threads and runs a dispatch of its size. Metal's tile state rounds the threads down to a multiple of 4 (0 for 1x1, 2x1 and 3x1, 8 for 3x3, 20 for 7x3), and its dispatch of a size that is not a multiple of 4 runs no thread, with the command buffer completed and no error.
    • Each state answers its own size. Metal hands a state of a function it has already compiled under another size the earlier state's limit, in the same process or a later one. An 8x8 tile state then answered 16 after a 4x4 one, and its 8x8 dispatch ran no thread. A compute state of the same MTLFunction answered 16 after a 4x4x1 state, with an 8x8x1 size and with none, where the runtime's answers 64 and the compiled limit. A compute state whose size has more threads than its kernel's own [[max_total_threads_per_threadgroup(n)]] is refused every time (RequiredThreadsProblem::OverKernelMax), as Metal's first compile of the kernel refuses it; Metal makes it once the kernel compiled under another descriptor, answering the kernel's maximum (128 by 1 by 1 beside 64, compute_pipeline_limits.m).
  • A reset compute pipeline descriptor is a fresh one, every field at its default: ComputePipelineDescriptor::new stands for reset, as MTLComputePipeline.h documents it ("Restore all compute pipeline descriptor properties to their default values", and of maxTotalThreadsPerThreadgroup, "If it is not set, returns zero"). Metal's reset on the M3 Max (macOS 27.0.1) restores every other field and keeps three as the program set them: threadGroupSizeIsMultipleOfThreadExecutionWidth, maxTotalThreadsPerThreadgroup and requiredThreadsPerThreadgroup (true, 96 and 8 by 6 by 2 in compute-descriptor-reset, where the runtime answers false, 0 and 0 by 0 by 0). The tile and mesh render pipeline descriptors' resets restore every field on the same machine.
  • An OpenCL work-item read of a dimension past 2 answers OpenCL's value in a pipeline of OpenCL mode: 0 for get_global_id, get_local_id, get_group_id and get_global_offset, 1 for get_local_size, get_global_size and get_num_groups, as OpenCL C defines them. The M3 Max (macOS 27.0.1) leaves unwritten the store of get_global_id(3) + get_local_size(4) + get_global_size(5), where the runtime stores 2.

Mesh render pipelines

  • A mesh state without an object function answers 0 for its object stage (RenderPipelineState::max_total_threads_per_object_threadgroup and object_thread_execution_width), where an M3 Max under macOS 27.0.1 answers 3 and 32.
  • A mesh draw is not held to its state's thread maxima, mesh-grid maximum or required threadgroup sizes. The state answers them as an M3 Max does (RenderPipelineState::max_total_threads_per_mesh_threadgroup, max_total_threadgroups_per_mesh_grid, required_threads_per_object_threadgroup and the rest), and its creation refuses what Metal refuses of them (MeshPipelineProblem); a draw of other threadgroup sizes within the device's limits runs, and so does an object function's mesh grid past the state's maximum (within Metal's 2^20 above).
  • A mesh state under a required threadgroup size or a function's own maximum answers as Metal's first compile of its functions, every time. Its thread maxima are the least of the descriptor's, the function's, the required size's threads and 1024, and a required size of other threads than its stage's maximum is refused in either stage. An M3 Max under macOS 27.0.1 answers these from what its compiler compiled before, which it keeps across processes keyed on the function's AIR: a first compile refused a required size of 32 under a maximum of 64 in either stage, and made it once the same function had compiled under that maximum and a required size of 64; after a compile under a required object size of 32 by 2, a plain state of the same functions answered an object maximum of 64, where a first compile answers 1024 (mesh_pipeline_limits.m).

Queues and command buffers

  • The runtime schedules a command buffer once its submit thread is free (metal2vulkan-runtime's CommandBuffer::status, add_scheduled_handler and wait_until_scheduled). Apple defines MTLCommandBufferStatusScheduled as "All dependencies have been resolved and the command buffer has been scheduled for execution", and promises no time between the two. Every queue's command buffers go to the device's one VkQueue, which takes one vkQueueSubmit2 call at a time, all made by the device's one submit thread, and the new runtime schedules each command buffer there once that thread's earlier calls have returned, whichever queue they were for (the runtime's README, the known gaps of queues). So a command buffer whose wait an earlier submission's signal meets stays Committed, its scheduled handlers not run, for as long as that submission's driver call lasts, where an Apple M3 Max had scheduled it while the signalling command buffer still ran.
  • A command buffer that waits for a shared event's value is Scheduled as it is submitted (metal2vulkan-runtime's CommandBufferStatus::Scheduled, Device::new_shared_event), its scheduled handlers run, while the GPU still waits for the value, as for an MTLEvent's value. Apple's MTLCommandBuffer.h describes MTLCommandBufferStatusScheduled as "All dependencies have been resolved and the command buffer has been scheduled for execution" (lines 47-48), and encodeWaitForEvent:value: as a command that "pauses execution of this command buffer until the specified event reaches a given value" (lines 405-406): execution pauses after scheduling. An Apple M3 Max with macOS 27.0.1 holds a command buffer that waits for an MTLSharedEvent's value not yet reached at Committed, with no scheduled handler run, and its queue's next command buffer with it, until the value lands, and holds none for an MTLEvent (the conformance case event-wait-behind-a-running-signal). No documented Metal states that hold, so the runtime keeps none. The GPU's order and when each command buffer completes are the same either way; what moves is when the program's threads and handlers see Scheduled.

Process exit

  • On Linux, an exit while the driver still runs the runtime's work past the exit's wait for it ends the process at once with the exit's status and one line on standard error. The exit waits for that work (the runtime's calls in the driver, a CPU device's commands) for at most 2 s, and at most 60 s while a pipeline's making is in progress in the driver; once it ended the exit handlers registered before the runtime's run, as Metal's exit runs them. Past those bounds they do not run (a terminal's restore, say), where Metal's exit runs them. Once the wait passed half its bound, one line on standard error names where the runtime's work still in progress began. A device's teardown that the exit finds in progress (its last reference let go on another thread) leaves the device to the process's end at its next step, so the exit waits for that step alone.
  • An exit while a pipeline's making is in progress can run the driver's compiler's destructors beside it where the making runs on the program's own thread, or where the compiler registered them in the last 2 ms before the exit, where Metal compiles in another process. A making on the runtime's own threads is waited for (above), and while one is in progress the runtime registers its exit handler again every 2 ms (at most 16384 times in a process), so the destructors the compiler registered before that run after the wait. One such exit, with a program's making thread left running, ended a consumer's process with SIGSEGV inside NVIDIA's SPIR-V compiler (libnvidia-glvkspirv.so, RTX 5080). A program that ends its making threads before it exits leaves only the 2 ms window.
  • A pipeline's making that an exit handler begins answers that the process is exiting (WaitWouldDeadlock of DeadlockCause::Exiting) where the program made a pipeline after it registered that handler, where Metal's exit makes it. The runtime registers its exit handler again after each making, and the exit runs it before the program's handler, after the destructors the driver's compiler registered at that making: that run ends the makings and waits for those in progress, and leaves the rest of the runtime running, so the handler's other work is submitted and completes, as Metal's exit runs it. A making its work needs that had not begun answers the same.
  • An exit handler's calls keep none of the runtime's state for their thread: exit destroys the exiting thread's thread-locals before it runs the handlers (macOS, the GNU C library). There a pipeline's making takes no turn of the process's making budget, the driver's messages a making is measured to report reach the device's message sink rather than being withheld, and a notice of a kind the device's options refuse while lowering is announced, and refuses no call, where the handler's own thread lowers it.
  • On a CPU device (lavapipe, SwiftShader), an exit handler the program registered before a later pipeline making finds the process exiting: its waits answer WaitWouldDeadlock of DeadlockCause::Exiting and the work it commits stays pending, where Metal's exit runs it. A CPU device's queues compile as they run their work, on the process's own threads, and the driver's compiler's destructors registered at that making run before the handler, so the runtime's exit handler run there closes the runtime, as it does for a device's registration. On lavapipe a queue's compile beside the exit's destructors ended the process in free()'s heap checks in 5 of 300 exits while a host step waited.
  • On NVIDIA's proprietary driver, an exit with a device live can fault in the driver's own exit handler with no making in progress, where Metal's exit is clean: the handler tears the driver's SPIR-V compiler down while a worker thread of the driver's still runs in it (a null dereference at 0x18 in libnvidia-glvkspirv.so, the fault above), on an RTX 3090 (620.70.06) in 6 of 80 exits right after the device's check of textures over host pages ended, and none three seconds after it. A device dropped before the exit leaves none (FAST-PATHS, known gaps).

Two-plane YCbCr textures

  • A view of an _sRGB twin as a 2D array reads its luma codes, as its converted format's view does, where Metal's reads change from run to run.

Padded 10-bit textures (R10Unorm_X6, RG10Unorm_X12 and their _sRGB twins)

  • A texture of one in memory of its own round-trips its words at every extent. Metal makes such a texture from every creator, newSharedTextureWithDescriptor: among them in the Private storage that is the only storage any shareable texture is made in, and the runtime makes it from each. Metal's own replaceRegion: and getBytes: on it are exact only while it keeps the texture linear, and are silent no-ops where it picks its compressed layout instead (allocatedSize 128 bytes or more beyond the tight linear size: on an M3 Max under macOS 27.0.1, 16x16 and 64x64 under ShaderRead alone, where getBytes: left its destination untouched and a shader read 0 at every texel after a replaceRegion:; exact at every height to 8 at widths to 1024, and at 16x16 once the usage included ShaderWrite). A blit either way moves the texels in both layouts. Which extents Metal compresses is an undocumented, per-chip choice, so the runtime moves the caller's bytes at every extent rather than predict it.

Textures held for copies alone (metal::format::copies_only)

  • A texture of one round-trips its bytes at every extent. Plain Metal's replaceRegion: and getBytes: on a 16x16 Shared texture of R12Unorm_X4, R12Unorm_X4_PQ, RG12Unorm_X8, R10Unorm_X6_PQ, R10Unorm_X6_HLG, R12Unorm_X4_HLG or RGB10A2Unorm_HLG under ShaderRead alone leave their destinations untouched, a fresh read's and a written texture's alike (an M3 Max under macOS 27.0.1, metal2vulkan-conformance's format-footprints-padded-wide-channels), as Metal's copies of a padded 10-bit texture it keeps compressed do (above). The runtime moves the caller's bytes at every extent, as it does for those.

Rasterization-rate maps

  • A map of no layers refuses its coordinate maps, and a mutable map not yet reset its physical-to-screen map, where Metal ends the process. So does the screen-to-physical map of a map whose screen width or height is 0, which plain Metal compiles and whose physical-to-screen map it answers (an M3 Max under macOS 27.0.1: a SIGSEGV at the first such call on 0 by 64, 64 by 0 and 0 by 0 alike).
  • A screen past 16384 pixels a side is refused, where Apple's compile crashes or returns a corrupt size.
  • A parameter-data copy Metal makes unsafely is refused: into a Private buffer, or past the buffer's length.
  • A physical size past the map's layers has width 0, but after a reset to fewer layers, which keeps the earlier layers' widths, as Metal does. Past layer 1 Metal reads the map's other fields and the memory after them (an M3 Max: at layer 2 the vertical extent, at 3 and 4 the screen's sides), and a layer near the top of the range ends the process.
  • A mutable map's pass stops at the physical size, where Metal rasterizes past the screen edge (an M3 Max: a 64-pixel half-rate map's pass to 49 by 49 pixels); announced with rasterization-rate-map.
  • A pass whose map is reset to another screen after it took the map keeps the screen it took, as Metal's does (an M3 Max: over a reset to the identity, it shades to the new screen's 32-pixel tiles where the new screen spans one tile fewer, else the whole screen taken); over a map reset to one that is not the identity, which no probe measured, it draws by the map as reset within the screen taken, announced with rasterization-rate-map.
  • A rate-mapped pass's clear covers its attachments, where Metal's covers the physical size rounded up to 32-pixel tiles and leaves the attachments' other pixels as they were (an M3 Max: a 16-pixel identity map's pass into a 64-pixel attachment cleared 32 by 32 pixels).
  • A rate-mapped pass draws region by region, and refuses a cutting scissor. Where the device enables multiDraw, multiViewport, shaderOutputViewportIndex and shaderDrawParameters, a direct draw of a vertex pipeline records as many regions as the least of its maxViewports and one below its maxMultiDrawCount in one vkCmdDrawMultiEXT or vkCmdDrawMultiIndexedEXT, its vertex function's variant storing ViewportIndex as DrawIndex (BindState::region_viewports, VariantKey::region_viewports): the same pixels in fewer commands. A region whose scissor, cut to the guest's viewport and the render area, holds no pixel is not recorded. At a host step, under RateMapRegionPolicy::FanOut (the default) on a device that enables geometryShader, shaderClipDistance and vertexPipelineStoresAndAtomics, an executed command's draw of triangles is drawn once instead where a probe finds that none of its triangles crosses w = 0 or touches more regions than the fan-out's copies: its variant's geometry stage emits a copy of each triangle for each region it touches (VariantKey::region_fan_out), a pixel centre within a rounding error of an edge possibly covered otherwise (docs/FAST-PATHS.md). A draw the probe flags, a list of triangles of one instance whose pipeline reads no [[primitive_id]] and writes no memory, is drawn in parts in its place: its runs of blocks of 64 triangles that hold a triangle the probe flagged region by region, cut to the first and the last flagged one, runs fewer than 170 triangles apart joined and at most four a draw, the triangles before, between and after them fanned out (WorkCounts::rate_map_parted_draws, the runs rate_map_region_runs, their triangles rate_map_parted_region_triangles and of those the ones the probe flagged rate_map_flagged_triangles), each run only into the regions its blocks' triangles reach by the probe's bounds, a triangle crossing w = 0 by its part where w is positive (rate_map_run_region_draws the regions the runs are drawn into, rate_map_runs_every_region the runs drawn into every one, rate_map_straddling_triangles the flagged triangles crossing w = 0); another flagged draw is drawn region by region. A direct draw to fan out, or a flagged draw's part, whose triangles lie in few regions is drawn through its region-copy variant (below) into the boxes of the regions they reach by the probe's bounds instead, where those regions' draws hold no more work than its triangles' geometry stage (WorkCounts::rate_map_boxed_draws): the same pixels, without the geometry stage. On such a device every draw of the pass the fan-out's variant takes and does not fan out (the encoder's own, those the probe flags or does not probe, the boxed ones) is drawn region by region through its region-copy variant where the device also enables shaderOutputViewportIndex and shaderDrawParameters, whose vertex function puts each vertex in its region by the instructions that put a fanned-out copy's and stores 0 as ViewportIndex, over boxes of regions (a run's the boxes its bounds reach), a region a recording or as many of a box as a direct draw's multi-draw takes, each through one viewport over the render area and its box's scissor, four clip distances keeping each copy to its region (WorkCounts::rate_map_region_copy_draws, the recordings rate_map_region_copy_recordings, their vertices times instances times regions rate_map_whole_copy_vertex_regions into the whole table, of the encoder's own draws rate_map_own_copy_vertex_regions, and rate_map_run_vertex_regions in runs; the fanned-out draws' rate_map_fanned_vertices, and rate_map_fanned_box_vertex_regions those times the regions their blocks' bounds reach, and rate_map_fanned_vertices_boxed_16, _64 and _256 those of boxes of at most that many; a pass whose sample positions put a sample on a pixel's edge records a box a column or a row at a time), so the pass's routes rasterize a vertex at one position and a depth Equal test across them holds where both pipelines compute the position alike; a draw the variant does not take is drawn through each region's viewport (docs/FAST-PATHS.md, known gaps). The probe costs the host step submissions it waits for before the pass, which run each probed draw's vertex function and geometry stage once and shade nothing: its parts, of at least 32 commands and at most 8 a probe, each submitted once the host recorded it, so the GPU runs one while the host records the next, and one wait after the last (WorkCounts::rate_map_probes, rate_map_probe_parts, rate_map_probe_gpu_nanos, the host's wait rate_map_probe_wait_nanos); a fanned-out draw runs its vertex function once where region by region it runs once per region (rate_mapped_pass.rs, Fan-out).
  • A pass over a map of a zero screen extent is refused, RegionError::RegionExtent on that axis: the layer has no physical pixel there, so no attachment of the map's physical size can be made, and what Metal rasterizes in such a pass is not measured.

Command queues

  • A write whose queue holds nothing back is seen by another queue's command buffer committed after it (metal2vulkan-runtime). A writer whose queue has fewer than three submissions in flight is submitted at once, ahead of every command buffer committed after it on any queue, so a later reader on another queue reads the write, on every device and every run: all 1024 words in the conformance case fence-none-tracked-behind-one, whose writer's queue has one busy command buffer in flight. That is the order Apple describes for a tracked resource: the framework prevents subsequent commands from running until write operations finish. Metal's 0 words there is measured, not documented: on an M3 Max with macOS 27.0.1, the copy on the other queue ran before the fill and read none of it in 5 runs of 5 (job m3-max-52432), and behind three busy command buffers likewise (job m3-max-52415); Metal's tracking ordered the copy only against work it had already submitted. The runtime's README states what was measured (crates/metal2vulkan-runtime/README.md, "Queues, command buffers and events").