Anees Iqbal 30c8b4bff8 Shadow a padded texture over a buffer exactly, and cut the shadow's cost
The padded-texture work packet. A texture over a buffer whose image would hold bytes that are not
its texels is drawn through a shadow image with exact copies, since a render pass or a layout
transition may write those bytes. Then the shadow's cost is cut, exactly: no copies for a pass that
reaches no tile, a copy back bounded by the draws' scissors, and cost lines that show each part.

Shadow a texture over a buffer whose image would hold bytes that are not its texels:
A texture over a buffer is a linear (or DRM_FORMAT_MOD_LINEAR) image over the buffer's bytes only
where every byte of the image's subresources is one of its texels: its rows lie one after another
(or it has one), its slices likewise, and its last subresource ends at its texels' last byte or
before. Anything else is the shadow, whose copies address the buffer's texels alone. The Metal
texture over an MTLBuffer (MoltenVK) is exempt: every write through it is Metal's own.

Why: Vulkan lets a render pass's load and store operations "read and write back any memory
locations within the image subresource bound for that attachment" (renderpass.adoc, Load and
Store Operations), and VkSubresourceLayout's size "includes any extra memory that is required
based on rowPitch", so the bytes between padded rows lie inside the subresource. Metal leaves them
as the program writes them. No query promises otherwise, so no image may alias padded rows.
Bytes past every subresource stay allowed: Memory Aliasing bounds the bytes a write through an
image affects to "those overlapped by the image subresources that were written". Measured on
lavapipe (Mesa 26.2.4 llvmpipe, gem10) at the round's base: pitched_surfaces' 657x128/5312
RGBA16Float tile took lavapipe's own linear image (its pitch 660 texels rounded to 64 bytes is
the lane's 5312), and a clear-blend-store pass rewrote 13 padding bytes in 13 rows (row 3 byte
5265 0x7c -> 0x7e: texels 657..659 of its 4-texel blocks read and written back, signaling NaNs
quieted). The reliance predates 1cf79a9617 (own linear images whose pitch equals bytesPerRow,
the dma-buf explicit planes); 1cf79a9617 made it every padded surface on ANV and NVIDIA's wider
pitches.

How: linear_plan's padding() and texels_alone(), used by alias_image (before any image is made),
aliases() (now given the subresource's size), host_alias_unbound (the own linear image's fit and
the pitched image's), the dma-buf alias (before the pages' source is asked, counted as a
fallback; its plane's size checked for textures over buffers, not heaps') and the rebind (the
alias kind keeps the texels' layout). Importer::makes_modifier_images, a duplicate of
makes_dma_buf_images, is folded into it. RUNTIME_VERSION 1188.

Tests: the aliases unit test covers padded rows, slices apart, a one-row pitch, a subresource
past the texels and a whole-array report. pitched_surfaces checks the pages after every step
(now naming the changed bytes outside the texels), asserts padded rows are never aliased off
MoltenVK, adds a load-blend-DontCare step, packed layouts of 510 and 126 rows and of 200, and a
fragment function's writes over six layouts (shader read/write usage). no_copy_textures asserts
padded rows shadow off MoltenVK (it asserted ANV's pitched image); dma_buf_imports' 60-texel case
now shadows. Docs: API.md (the extension paragraph and the shadowed-texture entry),
ShadowedTexture's rustdoc, HOWTO.md section 6, Texture::vk_image, dma_buf.rs, and a known-gap
entry in FAST-PATHS.md with ANV's cost (making the browser tile ~135 us as a shadow vs ~41 us
as a pitched image, 1cf79a9617's numbers).

Verified on lavapipe (gem10, release, --cfg m2v_cpu_icd, LP_NUM_THREADS=1): runtime_lane's
pitched_surfaces, no_copy_textures, buffer_texture_blits, dma_buf_imports, linear_attachments,
buffer_textures, buffer_texture_order, buffer_texture_renders, dont_care_stores,
kept_buffer_bytes, rotated_textures, and tests::linear_plan / degradation: 137 of 140 passed;
a_half_float_tile passes (it failed at the base), every padded layout is shadowed, 300x200/1200
is a pitched image. The three failures: the runtime-sources pin (written here), and the two
packed odd-height layouts, 658x126/5264 (rows 126..127 past the texture rewritten) and
1308x510/5232 (SIGSEGV, rows 510..511 written past the mapping): a lavapipe defect of explicit
DRM_FORMAT_MOD_LINEAR planes, handled in the next part. GPU lanes (ANV, RADV, NVIDIA,
MoltenVK) not run yet.

Make no explicit-plane modifier image of an odd height where lavapipe renders rows past it:
RuntimeDriverDefect::ExplicitPlaneRowsPastHeight: a DRM_FORMAT_MOD_LINEAR image whose one plane
the caller lays out (VkImageDrmFormatModifierExplicitCreateInfoEXT) is rendered in blocks of 4
rows, its rows past its height up to a multiple of 4 written past its subresource and past its
memory requirements. On a driver with the defect (lavapipe, MESA_LLVMPIPE, every release until a
probe finds one clean) neither host_pitched_image nor the dma-buf image (textures over buffers
and heaps' textures alike) is made of a height that is no multiple of 4: the texture takes its
shadow, announced as shadowed-texture with the defect named. The trigger is structural (the
image's height); the driver's own linear images are untouched, as they report the rounded rows
in their subresource (the previous part's texels_alone then shadows them).

Why: a write past an image's own memory is a spec violation no query reveals. Measured on lavapipe
(Mesa 26.2.4, llvmpipe LLVM 23.1.1 256 bits, gem10, release, LP_NUM_THREADS=1) at the previous
commit, pitched_surfaces' packed odd-height layouts, each a pitched image (pitched host images 1):
658x126/5264 RGBA16Float, a load-blend-store pass rewrote 21 bytes of rows 126..127 past the
texture (signaling NaNs quieted); 1308x510/5232 BGRA8Unorm, the same pass wrote rows 510..511 past
the no-copy buffer's mapping and the process took SIGSEGV. lavapipe 26.0.8 is unprobed.

How: Device::explicit_plane_rows (dma_buf.rs), asked by host_pitched_image and
dma_buf_image_unbound after their format checks. The registry entry and its test, the variant's
rustdoc, ShadowedTexture's rustdoc and API.md's shadowed-texture entry. No refusal is added, so
docs/REFUSALS.md has no row for it (refusal_surface.py --check passes); the api_surface table
names the enum, not its variants. RUNTIME_VERSION 1189.

Verified: see the landing run (lavapipe, the pitched_surfaces odd-height layouts shadowed and
passing).

Record that an image over host-pointer pages keeps its bytes past its first move only by drivers:
A known gap in docs/FAST-PATHS.md, and a lane check that turns a driver that drops the bytes into
a visible failure. No behaviour changes (no RUNTIME_VERSION bump): whether every texture over
pointer-imported pages becomes a shadow is the owner's call.

The gap: an image of host allocations must start UNDEFINED (VUID-VkImageCreateInfo-pNext-01443),
and a transition from UNDEFINED "will cause the contents of the image's memory to be undefined"
(resources.adoc, VkImageLayout). Memory imported from a host pointer "shares ownership of the
memory between the host and the Vulkan implementation", with host access synchronized as for any
memory (memory.adoc, VkImportMemoryHostPointerInfoEXT), so the external-memory acquire from
VK_QUEUE_FAMILY_EXTERNAL/FOREIGN is not blessed for it. sync2's ignored-layout barrier keeps
contents but leaves the image UNDEFINED, invalid to use as GENERAL. Paths that rely on the drivers:
host_linear_image, host_pitched_image, and metal_alias_image (VkImportMetalTextureInfoEXT says
nothing of contents). Spec-backed: dma-buf images, acquired from VK_QUEUE_FAMILY_FOREIGN_EXT in
GENERAL (the external memory chapter's ownership transfer and its note that the UNDEFINED initial
layout is a placeholder), and the runtime's own linear images, made PREINITIALIZED.

The check: pitched_surfaces::a_texture_s_first_use_reads_the_bytes_it_was_made_over makes a
texture over each layout and reads it first through its image (a fragment function's read)
before anything else touches the pages: the read must be the pages' texels and the pages
unchanged.

Verified: see the landing run (lavapipe).

Expect a shadow wherever no linear image holds a texture's texels alone:
The runtime aliases a texture over an ordinary buffer with a linear image only
where the image's subresource holds the texture's texels and nothing else
(linear_plan::texels_alone): no padding between rows, the driver's row pitch
Metal's, and no subresource bytes past the last texel. The lanes' expectation
helper, buffer_texture_blits::linear_rows_differ, compared only the driver's
row pitch, so on lavapipe, whose linear 64x2 RGBA8Uint at a 256-byte pitch
reports a 1024-byte subresource (its height rounded up to 4 rows) while the
texels end at 512, resource_ids expected no shadow and failed with "announced
past []: [ShadowedTexture, UnnamedShadowedTexture]".

The helper now applies the same rule: rows with bytes between them, a
subresource offset other than 0, a row pitch other than the buffer's, or a
subresource size past (height - 1) * row + width * texel. It takes the texel
size, which every caller knows. The callers' expectations move the same way:
resource_ids' 64-texel rows (the size rule), buffer_texture_blits' 4x4
textures at 32-byte rows and the IOSurface planes at 9, 20 and 40 bytes, and
view_reinterpretation's rows 16 bytes past their texels (the padding rule,
which shadows them on every device).

Verified on gem10's lavapipe (Mesa 26.2.4, --cfg m2v_cpu_icd,
LP_NUM_THREADS=1, release): the focused filter over pitched_surfaces,
no_copy_textures, buffer_texture_blits, dma_buf_imports, linear_attachments,
buffer_textures, buffer_texture_order, buffer_texture_renders,
dont_care_stores, kept_buffer_bytes, rotated_textures, resource_ids,
view_reinterpretation and the runtime's linear_plan, degradation and
driver_defects tests: 186 of 187 pass, resource_ids'
a_buffer_under_a_texture_goes_at_its_release_whatever_keeps_the_image among
them; the one failure is the runtime-sources pin, which moves with this work (below).
Test-only: no runtime source changes.

Name the layout transitions as what may write a padded texture's padding:
A texture over a buffer whose rows (or slices) lie with bytes between them
is a shadow off MoltenVK, since an image over those rows would hold the
bytes between them in its subresource. The shadowed-texture notice gave one
reason for every such texture: Vulkan lets a render pass's load and store
operations write those bytes back. That cannot apply to a texture without
RenderTarget usage, which never becomes an attachment, and ms01's A/B saw
read-only padded textures shadowed under that reason.

For such a texture the basis is the layout-transition rule (the
Synchronization chapter's Image Layout Transitions): "Image layout
transitions may perform read and write accesses on all memory bound to the
image subresource range", and "If the old layout is
VK_IMAGE_LAYOUT_UNDEFINED, the contents of that range may be discarded".
Every image takes one transition before any use: its first move into
GENERAL, from UNDEFINED for imports (VUID-VkImageCreateInfo-pNext-01443)
or PREINITIALIZED for ordinary buffers. No descriptor or copy takes an image
in either layout, and host image copy's transition is a transition too. So
no transition-free path exists for a read-only linear image, and the shadow
stays. After the first move every runtime image rests in GENERAL, so no
later barrier transitions it; copies and shader accesses touch texels alone
(the Memory Model: "A memory operation must not affect memory at a memory
location not within its set of memory locations").

linear_plan::padding now takes whether the texture renders (RenderTarget
usage). Its reason names the layout transitions, its first move among them,
and for a render target also the render pass's load and store operations.
The doc comment quotes both texts. The ShadowedTexture rustdoc, docs/API.md's
catalogue entry, docs/HOWTO.md, docs/FAST-PATHS.md's known gap, and the
dma_buf.rs and linear_plan.rs module docs say the same.

Tests:
- tests::linear_plan::a_padded_texture_s_shadow_names_what_may_write_its_padding
  checks both reasons' exact text.
- The lane test pitched_surfaces::a_padded_texture_s_shadow_names_what_may_write_its_padding
  makes the browser's 1307x512/5248 tile over an ordinary buffer, which
  shadows on every device, MoltenVK included. It runs a fresh device per
  usage (ShaderRead; RenderTarget | ShaderRead) and checks the
  shadowed-texture notice's reason.

RUNTIME_VERSION 1190 (fleet/round's 1189 + 1). The runtime-sources pin is
recomputed at this tree.

Verified on gem10's lavapipe (Mesa 26.2.4, llvmpipe LLVM 23.1.1,
--cfg m2v_cpu_icd, LP_NUM_THREADS=1, release). The focused filter
(pitched_surfaces, no_copy_textures, buffer_texture_blits, dma_buf_imports,
linear_attachments, buffer_textures, buffer_texture_order,
buffer_texture_renders, dont_care_stores, kept_buffer_bytes,
rotated_textures, resource_ids, view_reinterpretation, and the runtime's
linear_plan, degradation and driver_defects tests) ran 189 tests. 188
passed, both new tests among them, printing:
- ShaderRead: "its rows lie 5248 bytes apart, 5228 bytes of texels each: an
  image over them holds the bytes between them, which Vulkan lets its layout
  transitions read and write, its first move from the layout it is made in
  among them"
- RenderTarget: "... which Vulkan lets its layout transitions read and
  write, and a render pass's load and store operations write back"
The one failure was the runtime-sources pin before this commit set it
(860ca881...). Clippy with all features (no cfg) is clean.

Take the surface texture cost frame apart, per part and per texture:
surface_texture_costs measures a browser-like frame: five surface textures
over new no-copy buffers, each loaded and stored by a pass that draws
nothing, then each blitted into a private texture. On ANV, ms01 measured
commit-to-completion rising by about 2.8 ms a frame where four of them
became shadows. That number alone cannot say where the time goes: the
shadows' copies in and back, their making and release, or work beside them.
It also cannot say why the packed 1024x512/4096 tile, which stays the
driver's own linear image in both forms, took longer to make.

The new ignored measurement surface_texture_cost_parts (run by name, release,
as the others) runs the frame over anonymous pages in parts:
- Empty: the textures made and released around an empty command buffer.
- PassesStored: Load/Store passes, i.e. a shadow's copy in and copy back.
- PassesNotStored: Load/DontCare passes, a copy in only.
- PassesDrawn: Load passes that blend a rectangle and store, as a browser's
  passes draw.
- Blits: the blits alone, which read a texture over a buffer as its bytes.
- Both: the original frame.

It runs over every layout, then over the packed layouts alone, so no shadow
is made beside them. Per set and part it prints (SURFTEX-PART): the forms;
each texture's making median and p90; the frame's release, encoding,
commit-to-completion and process CPU time; and the per-frame work counts.
frame() takes the part, and surface_texture_costs passes Part::Both, so its
own output is unchanged.

Test-only. It compiles at fleet/base as well (it names nothing newer), so the
same measurement runs on the earlier form. Checked with clippy --cfg m2v_gpu,
all targets and features, -D warnings, on gem10.

Copy no shadow in or back for an attachment a pass that reaches no tile loads:
A texture over a buffer whose image would hold bytes that are not its texels
is a shadow: an image of its own that encoders copy the texels into before
use and back after a write. A render pass copied its shadowed color
attachment in before the pass and back after it whenever it loaded and
stored it, even where the pass reached no tile: no draw call, or draw calls
that draw nothing (clear_reach::PassReach::Nothing). Such a pass changes no
texel:
- Metal loads and stores only the tiles a draw reaches (PassReach's EVs).
- Vulkan's load and store write back what they read: "Load operations only
  update values within the defined render area", and store operations
  alike.
So the copies moved a texture's every texel twice for nothing. On ANV,
surface_texture_costs' frame (whose passes draw nothing) paid that for four
padded surfaces since they became shadows.

attachment_shadows now takes no use of such an attachment: a color
attachment of a pass that reaches no tile, that loads it (Load, also a
DontCare load the pass loads), stores it Store or DontCare, resolves
nothing, and has no stand-in or planes, where the shadow is a plain image of
a buffer's bytes (ShadowTarget::Image, writes kept). No copy in, nothing
dirty, no copy back. Rotated, converted and image shadows keep their copies.
The pass still renders into the shadow image, whose attachment uses order it
as before. Every later use copies in again, since the shadow was never marked
current.

New public counter WorkCounts::shadow_copies: copies between a shadowed
texture's truth and its shadow that encoders planned (in, back, keep and
merge). It is counted where EncoderCore plans them and at each of the three
end-of-encoder finishes.

Lane test pitched_surfaces::a_pass_that_draws_nothing_copies_no_shadow: the
browser's 1307x512/5248 tile over an ordinary buffer (a shadow on every
device). Load/Store and Load/DontCare passes that draw nothing plan 0 copies
and leave every byte of the buffer. A pass that blends a rectangle plans 2
(in and back). Without this change, the expected counts for the two empty
passes are 2 and 1.

This shrinks surface_texture_costs' frame, whose passes draw nothing, not a
browser's, whose passes draw. surface_texture_cost_parts' PassesDrawn part
measures that apart.

RUNTIME_VERSION and the runtime-sources pin move with this work (below).

Verified on gem10's lavapipe (Mesa 26.2.4, --cfg m2v_cpu_icd,
LP_NUM_THREADS=1, release): the earlier focused filter plus the runtime's
shadow tests ran 200 tests, 199 passed, the new test among them. The one
failure was the pin. clippy -D warnings, all targets and features, is clean
with no cfg and with --cfg m2v_gpu.

Copy back only the texels inside a pass's draws' scissors:
A shadowed texture's copy back after a render pass moved every texel from
the shadow image to the buffer. On ANV that write-back is the shadow's cost:
ms01's surface_texture_cost_parts put a stored shadow at about 0.8 ms of
commit-to-completion a frame (1307x512 BGRA8). A pass that loads a color
attachment changes no texel outside its draws' scissors:
- "Samples with coordinates outside the scissor rectangle at the
  corresponding ViewportIndex will have their coverage set to 0" (the
  Fragment Operations chapter's Scissor Test).
- "Load operations only update values within the defined render area" and
  "Store operations only update values within the defined render area" (the
  Render Pass chapter), writing back what they read.
- Each Vulkan scissor is Metal's rectangle clipped to the pixels its viewport
  overlaps (render_state.rs's implicit scissor), so Metal's draw writes no
  pixel past it either.
The image's other texels are what the last copy in left, which the buffer
still holds, and a write of the bytes another way leaves the image stale, so
they need no copy back.

How:
- ShadowUse gains an area: where a command writes through the texture, where
  it bounds that. render.rs passes the bounds of the pass's DrawnArea (its
  draws' Vulkan scissors) for a pass whose draws reach tiles, unless a reach
  clear runs before the pass, together with which color attachments the
  encoder set to Load, read before the DontCare loads and reach clears change
  any. attachment_shadows gives that area to a loaded color attachment with
  no resolve, stand-in or planes that is the whole of a one-level, one-slice
  texture.
- join and ShadowSync::after keep the rectangle bounding the writes since
  the last copy back, or none where one does not bound them. copy_back puts
  it on the ShadowCopy.
- record() cuts the one region of a ShadowTarget::Image without staging to
  it, by part_of: the buffer offset moved to the rectangle's first texel at
  the region's row length, clamped to the image. ShadowTarget::Image now
  carries its texel size (none for a heap's depth or stencil shadow, which
  takes no area).
- Copies in still move every texel.

New public counter WorkCounts::shadow_texels_copied_back: the texels copies
back of buffers' textures' images move.

Tests:
- tests::shadow::a_copy_back_covers_only_where_the_commands_wrote: areas
  through ShadowSync and join.
- tests::shadow::a_part_of_a_region_starts_at_its_first_texel: the region
  arithmetic, clamping, empty parts and tight rows.
- Lane pitched_surfaces::a_pass_copies_back_only_the_texels_its_scissors_reach:
  the browser's 1307x512/5248 tile over an ordinary buffer (a shadow on every
  device), blended under a 300x200 scissor, moves 60000 texels back. The
  buffer then holds a private texture's blend inside the scissor and every
  other byte as it was. Unscissored, the pass moves all 669184.

docs/FAST-PATHS.md's known gaps record the race the bound leaves: Metal
stores only the 32x32 tiles a primitive touches (reims-vgpu's padding probe,
M3 Max, macOS 27.0.1). A concurrent CPU write to an undrawn texel in an
untouched tile inside the scissors can be undone here, where Metal keeps it.
No copy reaches the bytes between rows.

The batch's version commit moves RUNTIME_VERSION; the runtime-sources pin follows it.

Verified on gem10's lavapipe (Mesa 26.2.4, --cfg m2v_cpu_icd,
LP_NUM_THREADS=1, release). The shadow lanes (the previous part's list,
plus scissors and capture_reach where they exist) and the runtime's shadow,
shadow_stencil, linear_plan, degradation and driver_defects tests ran 319
tests, and 318 passed, the three new ones among them. The one failure was
the runtime-sources pin. clippy -D warnings, all targets and features,
--cfg m2v_gpu, is clean.

Measure a scissored drawn pass and a shadow's copies alone:
Two additions to the surface texture cost measurements, both ignored and
run by name in release builds.

surface_texture_cost_parts gains PassesScissored: the drawn pass (Load, a
rectangle blended over the left half, Store) under a scissor of the left
half, as a browser's pass redrawing a damaged part of a tile draws. With the
previous part, its shadows copy back only the scissored half.
PassesDrawn's default scissor covers the whole tile, so its copy back moves
every texel.

shadow_copy_costs times each copy alone in its own command buffer, committed
and waited for, on the browser's 1307x512 BGRA8 tile at 5248-byte rows:
- a private texture made as a shadow is (render target and shader read) into
  a no-copy buffer over anonymous pages: a copy back's way;
- the pages into the texture: a copy in's way;
- the texture into a private buffer and into a Shared buffer;
- a private buffer into the pages, and back.
It prints SURFTEX-COPY lines with commit-to-completion medians and p90s.
These tell the image's tiling (detiling) from the pages' memory (writes into
imported host memory) as the cause of ANV's copy back.

Test-only. clippy -D warnings with --cfg m2v_gpu, all targets and features,
is clean on gem10.

Print a frame's shadow copies and the texels its copies back move in the surface cost lines:
What: the surface texture cost lines' per-frame work counts (SURFTEX-COST, SURFTEX-PART) now
end with the shadow copies the encoders planned and the texels their copies back moved, both
per frame.

Why: a change to how a shadow's image is made or copied must leave the copies and the texels
they move as they were; the cost lines then show it beside the times, in the same run.

Verified: test-only; built and run with the measurements on Linux hosts in the next steps
(no build on the Mac).

Wrap the surface texture costs' SURFTEX-QUERY sentence at 100 columns:
The commit that added a frame's shadow copies to the cost lines left the module doc's
SURFTEX-QUERY sentence on one 154-column line; the tree wraps doc comments at 100. Doc only.

Verified: awk finds no line of the file over 100 columns but the ignored-tests sentence (110),
which predates that commit; cargo fmt --all leaves the tree unchanged.

Versions: RUNTIME_VERSION 1202 -> 1203. RUNTIME_VERSION moves: padded textures over buffers are
drawn through shadows, and the shadows' copies change.
crates/metal2vulkan-validation/runtime-sources.sha256 holds
52d6ce1648b67055d046e043e6d1cd126e0a8315d04a922261df93ad0a25f734, the hash of this tree's runtime
inputs (runtime-pin.py, which reproduces build.rs's). Version numbers quoted above are the values
the work's branch built with. Each part's Verified lines name the tree it ran at.
2026-10-14 20:17:38 +03:00
2026-07-22 13:15:24 +03:00

metal2vulkan

License: GPL-2.0-or-later OR LGPL-3.0-or-later

metal2vulkan runs Metal shaders and Metal programs on Vulkan. It reads Metal AIR (a metallib, or AIR bitcode) and compiles it into Vulkan pipelines, and it offers the Metal API itself on top of a Vulkan device.

Alpha. The API, the command line, the pipeline JSON and the emitted SPIR-V may change during the 0.x series. Version your cached outputs.

The crates

Crate Directory What it is
metal2vulkan crates/metal2vulkan The translator. A Metal-shaped API (device, library, pipeline descriptors, binding plans) that compiles compute, render, tessellation, tile and mesh pipelines for a described Vulkan device: SPIR-V per stage, one pipeline layout, fixed-function state, and per-draw descriptor writes and push constants. The cli feature builds the metal2vulkan command.
metal2vulkan-runtime crates/metal2vulkan-runtime The Metal API on Vulkan: devices, command queues and buffers, encoders, buffers, textures, heaps, pipeline states and events, run on a Vulkan device through ash. It uses only the translator's public API.
metal2vulkan-air crates/metal2vulkan-air The AIR front end: the metallib container, the bitcode reader, a typed IR, AIR's metadata ABI, intrinsics and canonicalization. For tools that read AIR without translating it.
metal2vulkan-validation crates/metal2vulkan-validation Not published. Authored cases run on Metal and on Vulkan and compared, and bounded audits over a private corpus.
metal2vulkan-devtools crates/metal2vulkan-devtools Not published. The external-tool runner and fixture assemblers the tests share.

The three published crates share one version and are released together; metal2vulkan pins metal2vulkan-air exactly.

What the translator promises:

  • Typed refusals. Input the device cannot run exactly fails with an error that names the Metal feature and what would make it work. It never returns a module that computes something else.
  • Recorded differences. Where a pipeline gives a near-equivalent of Metal's answer, its artifact records a precision note, and the runtime announces it once with a stable code.
  • Fast by default. Off Apple's GPUs, choices that trade exactness for speed take the device's native form; each has an opt-in exact switch (docs/FAST-PATHS.md).
  • Bounded work. Every compile runs under a deadline, a cancellation token and deterministic work and memory caps.

Install

0.2.0 is not on crates.io yet (crates.io has 0.1.0, an unrelated earlier design). Depend on a git revision:

[dependencies]
metal2vulkan = { git = "https://github.com/steelbrain/metal2vulkan", rev = "<sha>" }
# For the Metal API on Vulkan:
metal2vulkan-runtime = { git = "https://github.com/steelbrain/metal2vulkan", rev = "<sha>" }

Features of metal2vulkan, none needed by the library:

  • serde: serialization of the API's plain-data values.
  • ash: conversions to and from ash::vk, and DeviceDescription::query, which reads a physical device.
  • cli: the metal2vulkan command (enables serde).

Requirements: Rust 1.98 or newer. The libraries run no external tool. The runtime opens the Vulkan loader at run time and needs a Vulkan 1.2 device.

Command line

cargo install --git https://github.com/steelbrain/metal2vulkan metal2vulkan --features cli

The command compiles one pipeline of a metallib, an AIR bitcode module or an LLVM text module (.ll) for the device a Khronos profiles JSON describes, and writes its SPIR-V:

# A kernel: one module.
metal2vulkan library.metallib kernel.spv --profile device.json --function my_kernel

# A render pipeline: one module per stage (pipeline.vert.spv, pipeline.frag.spv).
metal2vulkan shaders.air pipeline.spv --profile device.json \
  --function vertex_main --fragment fragment_main --vertex-descriptor vertex.json \
  --color-format 0:BGRA8Unorm --depth-format Depth32Float

# The pipeline's layout, interface, dependencies and stages as JSON.
metal2vulkan kernel.ll kernel.spv --profile device.json --emit-meta kernel.json
  • --profile is required: the crate ships no device description. Any Khronos profiles JSON works; crates/metal2vulkan-validation/profiles/ has examples, from a bare Vulkan 1.2 device to desktop GPUs and MoltenVK.
  • Without --function it compiles the library's only kernel or vertex function. A kernel with --color-format compiles as a tile pipeline. A post-tessellation vertex function adds .tesc.spv and .tese.spv modules.
  • A compile that needs a pipeline input fails naming it and the option that supplies it: --constant ID:TYPE:VALUE for a function constant, --stage-input FILE or --vertex-descriptor FILE for a stage-input or vertex descriptor (as JSON).
  • A .ll input is assembled with llvm-as (LLVM 21 or newer). Each module written is checked with spirv-val when it is found, under the environments the library states for the device; --no-spirv-val skips it. Both tools come from PATH, or from METAL2VULKAN_LLVM_AS and METAL2VULKAN_SPIRV_VAL.
  • Success prints a line with PASS and exits 0. Failure prints metal2vulkan: FALLBACK (<why>), writes nothing, and exits 2; a failure after the inputs are read also writes a repro bundle under $TMPDIR/metal2vulkan-repros (or METAL2VULKAN_REPRO_DIR).
  • metal2vulkan --help lists every option.

Library

The flow follows Metal's object lifecycle: describe the device, parse a library, compile a pipeline, then plan and instantiate each dispatch or draw.

use metal2vulkan::device::{Device, DeviceDescription, DevicePolicy};
use metal2vulkan::library::Library;
use metal2vulkan::pipeline::{ComputePipelineDescriptor, FunctionDescriptor, StageSource};
use metal2vulkan::Budget;

let description = DeviceDescription::from_khronos_json(&profile_json, None)?;
let device = Device::new(description, DevicePolicy::default())?;
let library = Library::parse(&metallib_bytes)?;
let kernel = FunctionDescriptor::new(library.function("my_kernel")?);
let descriptor = ComputePipelineDescriptor::new(StageSource::Function(kernel));
let pipeline = device.compile_compute_pipeline(&descriptor, &Budget::standard())?;
// pipeline.stage.spirv, pipeline.layout, pipeline.interface: create the Vulkan objects from these,
// then pipeline.plan(...) and plan.instantiate_dispatch(...) per dispatch.

docs/API.md walks the whole flow on a runnable example, examples/api_preview.rs:

cargo run -p metal2vulkan --example api_preview   # needs llvm-as on PATH

For the runtime, start at its README.

Documentation

Document Read it when
docs/API.md You use the translator's API: devices, libraries, pipelines, binding, caching, errors; and the runtime's degrade notices
Runtime README You use the Metal API on Vulkan
docs/HOWTO.md You integrate: tools, caching, failures, isolation, the runtime's shader cache
docs/RUNTIME-PORTING.md You port Metal calls (Objective-C or metal-rs) to the runtime
docs/FAST-PATHS.md You need every speed-for-accuracy default and its exact switch
docs/METAL-COVERAGE.md You ask whether a Metal API item is covered
docs/REFUSALS.md You ask what Metal accepts that the code refuses
docs/ARCHITECTURE.md You change the translator
docs/VALIDATION.md You check behavior against Metal
CONTRIBUTING.md You build and test the repository

The rustdoc of each crate (cargo doc --workspace --all-features --open) documents every public item; each runtime item names its Metal counterpart.

Shaders in this repository

The repository ships no third-party shaders. Tests use synthetic fixtures written for it. Passing spirv-val shows a module is valid, not that it computes what Metal computes; that claim needs the authored validation cases (docs/VALIDATION.md).

License

metal2vulkan is dual-licensed: you can redistribute it and/or modify it under the terms of either of these licenses, at your choice (LICENSE):

As an SPDX expression: GPL-2.0-or-later OR LGPL-3.0-or-later. Each published crate carries the notice and the three texts.

Metal is a trademark of Apple Inc. metal2vulkan is an independent project and is not affiliated with, sponsored by, or endorsed by Apple Inc.

S
Description
No description provided
Readme
1.7 GiB
0 Stars 1 Watchers 0 Forks
Languages
Rust 61.3%
LLVM 31.7%
Metal 3%
Objective-C 2.2%
Python 1.2%
Other 0.5%