Files
metal2vulkan/docs/ARCHITECTURE.md
T
Anees Iqbal cdc09276f3 Emit fast-math arithmetic in the AIR's order and let the device group and fuse it
One work packet, landed as 4 commits (c81ea84c14..41bbe0f1c2 on archive/development-linear-2026-10-28), in order:

* Emit fast-math arithmetic in the AIR's order and let the device group and fuse it

What. The translator no longer reproduces Metal's compiler's grouping, pairing and fusion of
fast-math arithmetic. Each float operation is emitted in the AIR's order, decorated by its own
fast-math flags: an operation whose flags hold `contract` and `reassoc` is undecorated, so the
device's compiler may group and fuse it; every other one is `NoContraction` (an undecorated
SPIR-V operation would also allow reassociation, which a `contract`-only operation does not), and
a precise module's operations keep their order. `llvm.fmuladd` keeps its fused route: one AIR
operation, answered by the device's fused instruction.

Deleted: lower/arith/regroup.rs (648 lines), reassoc.rs (1469), contract.rs (585) and
contract/chain.rs (1204); the Folded and Fused strategies, ArithPlan's `contract` and `unrounded`
fields and select.rs's CONTRACTED read bit; output_precision's `plan` (the `unrounded` marking of
half output chains, Metal's choice of where not to round) and the plumbing that existed only for
it: LoweringInputs::half_output_lanes, the public HalfOutputLane, StageIo::half_output_lanes,
color_writes' half_output_lanes check, its cache-key hashing and codec entry; Fma::on (tests
only). Tests engine_reassoc (318), engine_regroup (134), engine_settled_sums (572), three
engine_arith tests, three half-output-lane engine_stage_io tests and the fused_sync lockstep case,
whose premises were Metal's grouping. Fixtures regroup_chain, sum_regroup, sum_regroup_precise,
fmx2_contract_fast, fmx2_contract_precise and unm_contract_chain (.metal, .ll, .air.ll, their
TOOLCHAIN lines and air_input printouts). Validation lanes sum_regroup (308) and settled_sums
(394), and the three authored cases whose expected values were Metal's fusions
(multiply-add-contraction-shapes-under-fast-math, multiply-add-contraction-flags-without-fast-math,
multiply-add-chains-under-fast-math) with their observations.

Kept: the contraction rule itself (AIR semantics); output_precision's notes (half_output_note,
note_half_output, note_extended_range_sources), which state where Metal may differ rather than
reproduce it; the F16 strategy's per-operation rounding.

The note. The existing FastMathRewrites covers it: it is now recorded where an operation's
operand comes from an operation the two operations' flags let a compiler regroup (both `reassoc`)
or fuse (a product into a sum, both `contract`), looking through negation, widening, shuffles and
element moves. No new kind. It moves from the ledger's elsewhere class to a device gap
(docs/FAST-PATHS.md row; tests::fast_paths), joins the conformance replay's NATIVE_NOTES, and the
cases' own declarations of it are gone (depth_texel_reads, half_read_nans, host_page_writes,
mesh_draws, sample_positions, snorm_tile_store, visibility, topology_classes).

New tests. tests::engine_fast_math_order: a fast `((d+c)+b)+a`, its precise twin, fast and
contract-only `a*a+c`, and a fast vector product, on every committed profile: spirv-val, no fused
instruction, one instruction per AIR operation, NoContraction exactly where the flags forbid
contraction, the interpreter's answer in the AIR's order, and the note on every form but the
precise sum. runtime_lane::kept_apart (reworks settled_sums): strict and contract-only mul-adds
store two roundings, a precise sum stores the AIR's order, a fast mul-add stores either rounding,
and the layer reports nothing.

Versions: SEMANTICS_VERSION 1900; ARTIFACT_FORMAT_VERSION 469 (StageIo lost a field).
Docs: FAST-PATHS.md, API.md (catalogue entry and policy), ARCHITECTURE.md (module map),
artifact.rs's FastMathRewrites doc. api_signatures.tsv re-blessed.

Verified (this machine unless named):
- Negative control: on the parent tree both new core tests fail (a fast sum regrouped to
  0x34000000 where the AIR order stores 0, the mul-adds fused, the product paired, no note);
  with the change they pass.
- cargo check, clippy --workspace --all-targets --all-features -D warnings, plain and with
  --cfg m2v_gpu; rustdoc -D warnings; refusal_surface --check; conformance and metal coverage
  current.
- Core tests: engine_fast_math_order, engine_arith, arith::tests, engine_stage_io,
  engine_simd*, engine_native_*, engine_metal_math, engine_fetch_*blend, engine_bicubic,
  engine_rotated_weights, engine_extended_range, engine_float_call_notes, color_write,
  api_tests, compile tests, fast_paths: 469 + 83 passed.
- The engine inventory bless (not committed) compiled every public fixture on all 19 profiles:
  43593 ok cells, each through spirv-val; only the deleted fixtures' 28 rows went.
- Conformance replay on lavapipe (linux-gate arm64): exit 0, the 723 rows are exactly
  known-gaps.tsv's, 0 unlisted.
- Validation lanes on lavapipe (linux-gate arm64, --cfg m2v_cpu_icd): kept_apart and the lanes
  that assert notice sets (blits, degrade_notices, gpu_times, half_slice_nans, heap_metal_sizes,
  heap_textures, provoking, provoking_mesh, sparse_textures, ycbcr_passes): 93 passed. llvmpipe
  kept all 4096 fast mul-adds as written and all 4096 fast sums in the AIR's order.
- kept_apart on MoltenVK (Apple M3 Max, --cfg m2v_gpu, under maclock): passed; the device's
  compiler fused 2370 of 4096 fast mul-adds and kept all 4096 fast sums in the AIR's order.
- Release CLI before and after, back to back, on the deleted and most affected fixtures over
  moltenvk-m3, gate-lavapipe, nvidia-rtx5080-laptop and intel-irisxe-anv: wall within noise
  (about 8 ms of process start, +-3 ms on a loaded host). Words: hfb_filter_bank 148284 ->
  162420 on moltenvk-m3 (half chains feeding a half output now round at each operation as the
  AIR says: +1408 OpFConvert, +1408 NoContraction; 289 OpFmaKHR became a multiply and an add),
  unm_contract_chain 33666 -> 35167, fmx2_contract_fast 18557 -> 18908, the rest within +-200.

Not in this commit: the golden tables (6028 cells move in 347 subjects, 5707 of them under an
unchanged key, 28 subjects go with the fixtures) and the engine inventory (28 rows go, none
moves) are re-blessed on development; corpus/authored-compile.tsv keeps three lines for the
deleted cases until its re-bless.

* Read 16-bit operands directly and hold half chains at float without float16

What. Two forms of `half` arithmetic that were neither the device's native one nor the fast one:

- Where a profile takes the device's 16-bit `+ - *` and `fma` (moltenvk-m3 on the measured fact,
  RADV and ANV under the 16-bit float controls), every `half` is held widened in an `f32`, so each
  16-bit operation narrowed both operands and widened its result: three conversions an operation,
  the next operation narrowing what the last had just widened. `FunctionBuilder::convert` now
  answers a narrowing of a value it widened from a 16-bit float with that float (exact), and a
  narrowing of a plain constant whose lanes are zeros, infinities or normal halves with the 16-bit
  constant; the widenings nothing else reads leave with the dead code. A rounding's own pair (a
  narrowing widened back) is never taken apart, so `narrow::rounds_by_conversion`, which decides
  `NativeHalfConversion` and the controlled modes, still sees every rounding. A chain of 16-bit
  operations is now 16-bit instructions on 16-bit values, converted only where a value enters or
  leaves it.
- Without `shaderFloat16` (vk12-floor, SwiftShader, Pascal) the module emulates `half` arithmetic
  in `float`, rounding each result by the device's quantize. New `DevicePolicy::half_chains`:
  `HalfChainPolicy::AtExits` (the default, the fast form) holds a `half` `+ - *` whose flags hold
  `contract` and `reassoc` and whose result only such operations read at `float` precision
  (`lower::arith::half_chain`), so a chain rounds where a value leaves it, one quantize per exit;
  `HalfChainPolicy::EachOperation`, which `exact_answers()` selects, rounds every operation. The
  profile carries it, so its fingerprint covers it. Recorded as `FastMathRewrites` (its doc and
  API.md's catalogue entry extended); a FAST-PATHS.md fast-default row; API.md's policy list.

The forms by profile (unchanged, for the record): moltenvk-m3 takes the measured 16-bit
arithmetic; RADV and ANV the controlled one; NVIDIA (the conversion pair folded,
`HalfConversionPairFolded`) and lavapipe (no `DenormPreserve` for 16 bits) have `shaderFloat16`
but compute `half` in `float` and round by the device's conversion pair, which this commit leaves
as it is; the profiles without `shaderFloat16` quantize.

Tests: tests::engine_fast_math_order::half_operations_read_their_16_bit_operands_directly (no
narrowing of a widened half or a constant on any profile, the rounded chain stored, some profile
takes 16-bit arithmetic) and ::half_chains_without_float16_round_at_their_exits_by_default (one
quantize against two, the held and rounded answers, both policies on every profile, distinct
fingerprints); runtime_lane::kept_apart::half_chains_without_float16_round_at_their_exits on the
device. Updated, as the conversions they counted are gone (the half agent's files, minimal):
lower::arith::tests::narrow::half_arithmetic_on_the_device_is_one_16_bit_instruction (at most two
operand narrowings), tests::engine_arith::half_rounding_follows_the_operation (the chain's
conversion count), tests::engine_arith::a_measured_half_sum_requires_the_arithmetic_fact_alone (a
kernel whose halves only the 16-bit `fma` reads widens nothing, so needs no measured widening).

Versions: SEMANTICS_VERSION 1901. ARTIFACT_FORMAT_VERSION unchanged (no encoded type changed).
api_signatures.tsv re-blessed (the enum and the field).

Words, release CLI, every module spirv-val'd (before = development 7b5cf8328d, then 622b388830,
then this commit):
- moltenvk-m3: hfb_filter_bank 148284, 162420, 140672; grd_half_many_samples 99039, 99330, 96710;
  nan_half_fast 10042, 10057, 9961.
- nvidia-rtx5080-laptop: hfb 147962, 155474, 155474; grd 110944, 111163, 111163; nan 9888, 9882,
  9882.
- gate-lavapipe: hfb 148530, 155470, 155470; grd 111018, 111163, 111163; nan 9888, 9882, 9882.
- vk12-floor: hfb 124826, 131766, 121270; grd 84482, 84627, 82019; nan 9838, 9832, 9808
  (EachOperation reproduces 622b388830's: 131766, 84627, 9832).

Verified:
- Negative controls: with the narrowing fold off, the 16-bit test fails (amd-780m-hawkpoint-radv
  narrows a widened half); with the plan off, the chain test fails (two quantizes on
  lunarg-desktop-baseline-2023). Both pass with them on.
- Core tests on this Mac: 1133 passed (arith, engine_arith, engine_native*, engine_stage_io,
  engine_fetch*, engine_simd*, spirv::*, device::*, cache::*, compile tests, api_tests,
  air_input, fast_paths, engine_fast_math_order, api_signatures, api_surface); conformance
  filtered tests 26 passed; clippy --workspace --all-targets --all-features -D warnings, plain and
  with --cfg m2v_gpu; rustdoc -D warnings; refusal_surface --check.
- The engine inventory bless (not committed) over every public fixture on all 19 profiles: only
  the deleted fixtures' 28 rows go, every other cell as before (spirv-val on each `ok`).
- runtime_lane::kept_apart on SwiftShader (linux-gate arm64, --icd swiftshader): the `fast` chain
  4096 of 4096 held under AtExits and 4096 rounded under EachOperation, the strict chain rounded
  under both; on lavapipe (whose compiler drops the undecorated conversion pairs: the `fast` chain
  4096 held under both, the strict one rounded) and on MoltenVK (Apple M3 Max, under maclock:
  every chain rounded at each sum, the 16-bit arithmetic) both tests pass.
- Lavapipe (linux-gate arm64): the conformance replay exits 0, its 763 rows exactly
  known-gaps.tsv's, 0 unlisted, the verdicts as at 622b388830; runtime_lane kept_apart,
  native_maths, half_* and degrade_notices: 28 passed. MoltenVK: the half_* lanes and
  native_maths' half rounding pass; native_maths_answers_within_its_recorded_bounds fails on
  NativeDivision (`divide::precise` records it everywhere; code this commit does not touch).

Not in this commit: the golden tables (with 622b388830, 7652 cells move in 672 subjects; 28
subjects go) and the engine inventory (28 rows go) are re-blessed on development.

* Number ARTIFACT_FORMAT_VERSION 470, after development's 469

What. development's own commit took 469 for its encoding change while this branch's first commit
took 469 for StageIo losing half_output_lanes; the rebase merged the two equal lines silently, so
two layouts shared one value. 470 keeps an artifact of either from decoding as the other.

Verified: cargo check -p metal2vulkan --all-features --all-targets on the rebased tree.

* Re-pin the runtime sources at the landing tip

The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-10-28 17:24:22 +02:00

175 lines
13 KiB
Markdown

# Architecture
How the translator turns AIR into Vulkan pipelines: the stages, the rules that hold across them,
and where each piece lives. The consumer's view of the same flow is [API.md](API.md).
## The pipeline
```text
metallib | AIR bitcode
── parse ───────► Library: the container's functions air::container, library
── decode ──────► a typed AIR module and its ABI air::{bitstream, bitcode, ir, intrinsics, abi}
── specialize ──► one inlined entry: function constants baked, air::canon
constants propagated, linked functions resolved,
pointee types erased
── analyze ─────► MemoryPlan: provenance, one representation memory
per value, slot windows
── select ──────► Plan: a strategy per instruction and interface lower::select, lower::strategy
element, push-constant placement, requirements,
the output-size estimate (checked here)
── structurize ─► a structured tree over the AIR CFG structurize
── emit ────────► a typed SPIR-V module through the builder structurize::emit, lower::*, spirv::builder
── tidy ────────► single-store promotion, dead values removed, structurize::promote, spirv::{dead, roll}
repeated regions of large entries rolled into loops
── verify ──────► the full verifier; requirements within the profile spirv::verify, spirv::requirements
── serialize ───► SPIR-V 1.5 words with typed relocations spirv::serialize
= CompiledFunction, keyed by FunctionCompileKey (the caller may cache it)
── link ────────► bindings, Locations, spec ids, the pipeline pipeline::link
layout, pipeline-wide limits, the generated pipeline::link::geometry
geometry stages (barycentric weights read as
varyings, a selected slice or viewport stored
from the first vertex)
── relocate ────► the final words of each stage pipeline::relocate
= ComputePipeline | RenderPipeline | tile and mesh pipelines
BindState ── shape ──► BindingPlan (per pipeline and shape) ── instantiate ──► dispatch or draw commands bind
```
`pipeline::compile::compile_stage` runs one function from decode to serialize and keeps only the
relocatable module and plain metadata; the decoded AIR, the plan and the typed module are dropped
before it returns. It runs under `catch_unwind`, so a panic in the core becomes
`Error::Internal`, never an unwind into the caller.
Three rules hold across the arrows:
- **Each stage maps valid typed input to valid typed output.** No stage produces a form a later
stage repairs, and nothing parses SPIR-V words to decide what to emit.
- **Nothing after `select` changes which instructions a function contains**, except the tidy
passes, which preserve meaning. Link and relocate write only literal numbers (descriptor set and
binding, `Location`, `SpecId`) into slots the serializer reserved, so one compiled function is
reused by every pipeline it links into.
- **One representation per feature and device, chosen before emission.** `select` decides every
strategy from the AIR and the device profile. There are no retries, no candidate modules and no
validator in the loop. A family that cannot lower an input refuses it.
The library runs no external tool: it reads bitcode with its own reader and verifies with its own
verifier. The command line adds `llvm-as` for `.ll` input and `spirv-val` as an independent check.
## Where each piece lives
The AIR front end is its own crate, `metal2vulkan-air` (`crates/metal2vulkan-air/src/`). The
translator names it `air`, with its `graph` and `budget` modules at the translator's root. The
rest is `crates/metal2vulkan/src/`.
| Module | Role |
|---|---|
| `air` (`metal2vulkan-air`) | The container (metallib, bitcode wrapper, raw module), the bitstream and bitcode readers, the typed IR, the `air.*` and `llvm.*` intrinsic families, the metadata ABI (`AirAbi`), and canonicalization (`canon`: inlining, function constants, SCCP, devirtualization, linking, pruning, pointee erasure, and the speculation of the short branch arms Metal's backend runs in every lane). Canonicalization also writes the formats the binder and runtime read: the visible-function table's words and the rasterization-rate map's parameter data |
| `graph` | The shared RPO, dominator tree, loop forest and SCC |
| `budget` | `Budget`, `CancelToken`, and the per-attempt `Meter`: deadline, cancellation, work units, the byte ledger and every structural cap |
| `memory/` | Pointer provenance, the `MemoryPlan`, leaf access emitters, arenas, root and handle lookups, word composition, atomics |
| `lower/` | `select` (routing every instruction, intrinsic and parameter into the `Plan`), `strategy`, `push` (push-constant placement), `estimate` (output size), `specialized` (bound-texture values read as push data), and one module per family: `arith` (each float operation in the AIR's order, decorated by its own fast-math flags, so the device's compiler groups and fuses only what they allow; `half_chain`, a fast-math `half` chain held at `float` precision between its roundings where the device has no 16-bit floats), `access`, `texture`, `sampler`, `simd`, `sync`, `fragment`, `stage_io`, `dispatch`, `tessellation`, `mesh`, `raytracing` |
| `structurize/` | The structurizer over the AIR CFG, the emit walk that drives the families, and single-store promotion |
| `spirv/` | The typed SPIR-V IR and interners, the module and function builders, dead-value removal, the roll pass, the verifier, requirement derivation and the serializer. `spirv::interp` is a CPU interpreter used only by tests |
| `spv.rs` | The SPIR-V grammar's opcodes and enumerants the translator names, generated from Khronos's grammar (`scripts/regen-spirv-grammar/`) |
| `spirv_binary/` | A reader of SPIR-V's binary form over the grammar's instruction table, used only by tests |
| `device/` | `DeviceDescription` (from a Khronos profile, or from `ash`), `DevicePolicy`, and the derived `DeviceProfile` every decision reads |
| `library/` | `Library`, `Function`, `CompiledFunction`, `FunctionCompileKey` |
| `reflection/` | Metal-shaped reflection of functions and pipelines |
| `pipeline/` | Descriptors, compile entry points, link and relocate, `PipelineInterface`, the pipeline layout, vertex input and fixed-function state, runtime facts, precision notes |
| `bind/` | The binder: `BindState` and `BindShape`, `BindingPlan`, per-command instantiation, neutral resources, argument, handle and heap tables, residency, indirect-command replay, and the helper kernels the runtime records. It never calls Vulkan |
| `cache/` | `PipelineKey`, `SEMANTICS_VERSION`, the artifact encoding |
| `metal/`, `vk/`, `ash_interop/` | Metal's enums and format facts; plain-data Vulkan values; `ash` conversions (feature `ash`) |
| `error/` | The typed errors every entry point returns |
| `main.rs` | The command line (feature `cli`) |
The translator core (`lower`, `memory`, `spirv`, `spv`, `structurize`) and every submodule of a
public module are crate-private; no feature or cfg exposes them. The runtime
(`crates/metal2vulkan-runtime`), validation and devtools use the public API only. A test that
needs an internal item is one of the crate's own tests (`src/tests/`).
## Decisions come from structure and the device
- **The device profile.** `Device::new` derives one `DeviceProfile` from the description and the
policy. Every device-dependent choice (subgroup tier, buffer views, storage widths, robustness,
push-constant room, limits, measured driver deviations) reads it, and its fingerprint is part of
every cache key.
- **The device's native forms.** The maths, the grouping and fusion of fast-math arithmetic, NaN
bits, minimum and maximum, `half` rounding and blends, the sampler and the texel and color
conversions are the device's own on every device,
each difference from Metal recorded as a precision note; on MoltenVK on Apple's GPUs most are
Metal's own. The policy's accuracy switches are the runtime's ([FAST-PATHS.md](FAST-PATHS.md)).
- **Structure, not names.** Families decide from IR types, address spaces, the metadata ABI and the
`air.*` and `llvm.*` intrinsic contract. No branch keys on a function, type or variable name.
- **Typed refusals.** An input the device cannot run exactly is `Error::Unsupported`, naming the
Metal feature and what would make it translatable. A missing pipeline input (a function-constant
value, a stage-input or vertex descriptor, a storage texture's format) is `Error::NeedsInput`,
asked for and never guessed. A deterministic cap is `Error::LimitExceeded`. Only a deadline
(`Error::Budget`) or a cancellation (`Error::Cancelled`) is transient.
- **Recorded differences.** Where the output gives a near-equivalent of Metal's answer, the stage
records a `PrecisionNote`, and `Reconvergence::ImplementationDefined` where the profile lacks
maximal reconvergence.
## Validity by construction
- **The builder makes invalid modules hard to write.** Typed constructors check operand and
result types; storage-class rules hold by construction; `if_`, `switch_` and `loop_` are the only
construct openers, each closed by its scope, so constructs nest correctly.
- **Types are interned with their layout**, so a type is unique and its explicit layout is part of
its key.
- **Capabilities and extensions are derived** from what the module contains, never written by a
lowering, and must lie within the profile (else `Error::Internal`, kind
`RequirementsExceedProfile`).
- **The serializer** writes the logical layout and numbers result ids densely in order, so equal
modules give equal words. Nothing nondeterministic (such as hash-map order) reaches the output.
- **The verifier always runs**, in release builds too, before any word leaves the crate:
ownership, SSA dominance, structured control flow and canonical loops, convergent instructions,
atomic pointers, an acyclic call graph, stage rules, the recorded interface and requirements, and
the profile's rules. A violation is `Error::Internal` (kind `Verify`): a translator bug, never an
input error.
## Structurization
The structurizer reads the CFG through a view: blocks are opaque units and terminators are shapes.
1. Prune unreachable blocks and fold trivial branches.
2. Make an irreducible graph reducible with a multi-entry dispatch; refuse an irreducible region
that holds a convergent instruction, and nesting or output past the structural limits.
3. Find the loop nest.
4. Demote every block-crossing value and phi to a `Function` variable.
5. Canonicalize loops: back edges become `continue`, exits a `break` through one exit dispatch per
loop.
6. Place every acyclic region on the dominator tree, innermost loop first.
7. Let tail jumps fall out and route the rest through one pending variable.
8. Emit the tree through the builder, each block lowered by the plan's strategies.
9. Promote single-store variables back to values where dominance allows.
The output size is checked against `Limit::OutputBlocks` before anything is emitted.
## Bounded work
Every compile takes a `Budget`: a wall deadline, a `CancelToken`, a deterministic work-unit cap and
a byte ledger. The `Meter` is threaded through every loop that scales with the input: it ticks work
units and charges each input-sized container before reserving it, so a refusal comes before the
allocation and the same input refuses the same way on every host. The crate keeps no global cache
and memoizes nothing; the caller caches compiled functions, pipelines and plans under the public
keys. A consumer that needs a hard memory ceiling or crash isolation compiles in a child process
([HOWTO.md](HOWTO.md#5-bound-a-compile)).
## Checks
Match the evidence to the claim; [VALIDATION.md](VALIDATION.md) has the full ladder.
| Check | Catches |
|---|---|
| clippy with warnings denied | warnings and common defects |
| unit and integration tests | construction and lowering regressions |
| the always-on verifier, and `spirv-val` in tests and the command line | invalid modules |
| interpreter tests (`spirv::interp`) | wrong compute lowering, out-of-bounds access, non-termination |
| the fixture inventory (`tests/public_fixture_expectations_engine.tsv`) | a fixture that stops compiling or starts refusing on a committed profile |
| golden output hashes (`src/tests/golden_hashes.rs`) | unintended output changes |
| authored cases run on Metal and Vulkan | answers that differ from Metal's |
| bounded release-mode corpus translation | time, memory and coverage over real AIR |
A valid module is necessary, not sufficient. A change that only silences the verifier or
`spirv-val` is unsound; unknown semantics stay refusals.