Squash 680 commits of translator, validation, and corpus work

Rolls up everything since 9e0e99a4 into a single commit:

- src/native, src/passes, src/reflect, src/meta: AIR intrinsic lowering,
  access-chain and pointer handling, constant/composite dedup, storage
  and descriptor-slot fixes, function-constant folding.
- validation/: Metal and MoltenVK oracles, triage, observation contract,
  and the case runner.
- validation/corpus and fixtures: new authored cases and re-recorded
  candidate observations at the shipping fingerprint.
- tests/: module-level oracles for reflection, NonWritable, gated
  varyings/system values/descriptor slots, loop budget, and fallback.
This commit is contained in:
Anees Iqbal committed 2026-09-06 23:58:13 +03:00
1 parent 9e0e99a41d
commit 43c46ac8a2
772 files changed
+69927 -10031

No files matched your search

+6 -4
View File
@@ -68,9 +68,11 @@ jobs:
- name: Format
run: cargo fmt --all -- --check
# clippy --all-targets typechecks the workspace; no separate cargo build step.
# clippy --all-targets --all-features typechecks the workspace INCLUDING the
# `serde` cfg the shipped CLI is built with; without it, code and tests behind
# `#[cfg(feature = "serde")]` are never compiled by any gate.
- name: Clippy (warnings denied)
run: cargo clippy --workspace --all-targets -- -D warnings
run: cargo clippy --workspace --all-targets --all-features -- -D warnings
- name: Build public documentation (warnings denied)
env:
@@ -78,10 +80,10 @@ jobs:
run: cargo doc --workspace --all-features --no-deps
- name: Test metal2vulkan
run: cargo test -p metal2vulkan
run: cargo test -p metal2vulkan --all-features
- name: Test validation suite
run: cargo test -p metal2vulkan-validation
run: cargo test -p metal2vulkan-validation --all-features
# Machine-specific semantic qualification remains explicit. Linux CI has lavapipe, so it can
# execute the owned public cases against their exact committed Metal observations without a
+12 -4
View File
@@ -176,6 +176,12 @@ fixes over one-off workarounds.
`process::exit` on FALLBACK. Do not reintroduce long-lived dumps under fixed `/tmp/...` paths.
- FALLBACK **repro bundles** under `$TMPDIR/metal2vulkan-repros` (or `METAL2VULKAN_REPRO_DIR`) are
intentional and may be kept for debugging.
- **`pgrep` / `ps | grep`:** the only permitted spelling brackets the first character of the
pattern — `pgrep -f '[c]orpus-refresh'`, `pgrep -f '[c]argo test --release'`. Unbracketed, `-f`
tests the whole command line and the pattern appears verbatim in the argv of the shell running
the `pgrep`, so it matches itself and the target always looks alive: you end up waiting on your
own wait loop, which then returns only on its timeout. A long, specific pattern is *more* likely
to self-match, not less. Bracket unconditionally.
### What not to commit
@@ -205,10 +211,10 @@ Run Rust tests with Cargo's default available parallelism (the logical CPU count
```sh
cargo fmt --all
cargo clippy --workspace --all-targets -- -D warnings
cargo clippy --workspace --all-targets --all-features -- -D warnings
RUSTDOCFLAGS='-D warnings' cargo doc --workspace --all-features --no-deps
cargo test -p metal2vulkan
cargo test -p metal2vulkan-validation
cargo test -p metal2vulkan --all-features
cargo test -p metal2vulkan-validation --all-features
```
- **MSRV:** see `rust-version` in `Cargo.toml` (currently 1.87).
@@ -216,7 +222,9 @@ cargo test -p metal2vulkan-validation
`-D warnings`. Treat any new rustc or clippy warning as a bug you must fix before committing —
do not leave `#[allow(...)]` noise to paper over real issues, and do not ask reviewers (or a
later CI run) to clean up after you.
- **Features:** `serde` enables `ShaderReflection` JSON and CLI `--emit-meta`.
- **Features:** `serde` enables `ShaderReflection` JSON and CLI `--emit-meta`. Every gate above
passes `--all-features`, because the released CLI is built with `serde` and code behind
`#[cfg(feature = "serde")]` is otherwise compiled by nothing.
- CI runners: **`ubuntu-26.04`** and **`macos-26`** (not `*-latest`).
When diagnosing a hang, prefer reading full `cargo test` output over piping through `head`/`grep`
+530
View File
@@ -9,6 +9,516 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
- A texture argument the pipeline variant does not provide is no longer answered by the module's
only same-shaped live texture. `recovered_image_for_private_operand` exists for a handle the
lowering lost track of -- a helper stored a texture in a Function aggregate and field replay
missed it -- and it accepts a Private placeholder when exactly one image binding has the shape the
intrinsic's own symbol names. A texture the variant leaves out arrives as the SAME placeholder, so
wherever the live binding happened to match, the recovery stood it in: the shader read a texture it
never named, and its store landed on one the pipeline did bind. The two are now told apart at the
one point that knows which is which -- the parameter binding -- by naming the demotion
`VariantAbsentTexture` instead of dropping it into `Other`, and recording the placeholder variable
it creates.
**Both spellings of "this variant leaves the argument out" had to be named, and only one of them
was.** `air.function_constant` beside a gate the module's own static initializers drive to zero is
what an unspecialized module carries; once a VALUE is supplied,
`specialize_function_constant_metadata` rewrites that same node to
`air.function_constant_disabled`, after which the wrapped role is unreadable by design and the
demotion never runs. Every authored case with function constants is translated from the second
spelling, so fixing only the first left the case path exactly as it was.
**Measured reach over the 14,579 corpus sources: 0 modules change SPIR-V and none changes status.**
The refusal is asked 3,451 times across 290 of them and never changes the answer -- 324 modules do
build 2,985 absent-texture placeholders, so that is a real measurement and not a vacuous one; in
every corpus case the recovery was already declining on candidate count, dominance or shape. On
the specialized path it is a fix and not hardening, and the authored case that ships with it is
the evidence: `read-and-write-a-texture-the-pipeline-does-not-provide` returns all `-1` before this
change and matches Metal after it.
- The Vulkan executor enables `VK_KHR_maintenance5` where the device has it, so a point-topology
pipeline built from a `vertex void` Metal function is legal. Three cases in the store draw points
with a rasterization-disabled vertex function, which has no position output at all, let alone a
`[[point_size]]`; without `maintenance5`,
`VUID-VkGraphicsPipelineCreateInfo-topology-08773` makes a `POINT_LIST` pipeline demand that the
last vertex-processing stage write `PointSize`. Two of the three violated it, and a result recorded
from an invalid pipeline is not entitled to be trusted whatever it happens to be. `maintenance5` is
the guarantee those cases actually need: it DEFINES the unwritten `PointSize` as 1.0 instead of
leaving it undefined.
Substituting a topology that demands nothing is not an alternative, and that was measured rather
than assumed: under `TRIANGLE_LIST` both rasterization-disabled point cases flip to Mismatch,
because a one-vertex draw assembles no triangle and the vertex shader never runs. The existing
`rasterization_disabled_vertex_executes_narrow_attributes_without_a_companion` fails on the same
substitution, so the topology is load-bearing and already guarded in-repo.
`VK_KHR_maintenance5` requires `VK_KHR_dynamic_rendering` in the same enabled list
(`VUID-vkCreateDevice-ppEnabledExtensionNames-01387`), so both are asked for or neither is;
nothing here begins a dynamic-rendering pass. This closes the last messages the Vulkan validation
layer reported over the store: **1010 before this session's executor work, 4 after it, 0 now.**
- `drop_unrequired_capabilities` now also decides the `VariablePointers` pair, recomputed from the
finished module. The pipeline computes the variable-pointer requirement once and reapplies that
SNAPSHOT after later passes run, so a pass that deleted the last pointer merge left the capability
behind -- the same stale-declaration shape the `NonWritable` decoration is placed last to avoid.
These two cannot join the grammar allowlist beside `ImageQuery` and the rest, because what asks
for them is a POINTER-TYPED `OpPhi`/`OpSelect`/`OpPtrAccessChain` and the SPIR-V grammar attaches
nothing to those opcodes; they get their own predicate instead.
**Measured reach over the 14,579 corpus sources: 1 module changes SPIR-V, none changes status.**
That is hardening, not a fix anyone was waiting for -- and it is worth stating why it is so small.
The strip-one-capability oracle was previously run over the 332 *distinct capability sets* in the
corpus, which is not a sweep of the corpus: whether a declared capability is needed is a fact about
a module's instructions, not about the set it declares, so two modules with identical sets can
differ on every member. Run properly over all 14,579 sources it reports **7** modules, and six of
those are `VariablePointersStorageBuffer` declared beside `VariablePointers`, which implies it --
redundant, not a demand. The seventh is this one. The oracle is now closed.
- A storage image the module never writes is decorated `NonWritable`, which is the other half of
the VUID the storage-buffer decoration closed. `VUID-RuntimeSpirv-NonWritable-06340`/`-06341`
covers "storage image, storage texel buffer, storage tensor, and storage buffer", and it is
per-variable: one undecorated descriptor keeps `fragmentStoresAndAtomics` /
`vertexPipelineStoresAndAtomics` demanded for the whole module. So decorating only the buffers
left the demand standing wherever a storage image was declared beside them.
**340 of the 14,579 corpus sources change SPIR-V**, carrying 513 image decorations. Of the 2655
graphics-stage modules that declare a storage buffer or storage image, 264 still demanded the
feature; **164 of them now stop**, and none starts. No status and no reflection changed.
The image proof is shorter than the buffer one and deliberately not the same walk, because an
image is not reached the same way. There is no device address to a `UniformConstant` variable, so
no addressing-model gate is needed. Gating on Logical anyway, as the buffer half must, would have
excluded the corpus's 387 `PhysicalStorageBuffer64` modules from consideration; **measured, 4 of
the 340 modules that gain a decoration are among them**, so that is what the ungated rule is
worth here -- 4 modules, not 387. Follow the variable, the image objects loaded from it, and the
objects copied from those; disqualify on `OpImageWrite`, on `OpImageTexelPointer` (which takes the
variable and exists to feed an atomic), or on **any operand slot the rule list has no entry for**.
An array of images is not a root: its pointee is `OpTypeArray`, so it is never decorated.
`spirv-val` accepts `NonWritable` on a storage-image variable and does not check it against
`OpImageWrite`, so a wrong answer here is silent all the way to the device -- the same hole the
buffer half found, measured again for images. `tests/nonwritable_covers_the_module.rs` performs the
check it does not, now for images as well as buffers: an independent disassembly walk that roots
every image object at the variable it was loaded from. A sweep of that shape found 0 violations
across all 13,318 modules that translate. Both new tests are red without the decoration.
Both halves now live in `src/reflect/nonwritable.rs` and share one derivation of "what descriptor
is this variable" with the footprint walk, rather than reading `module.annotations` a second time.
- Four more capabilities are declared only for the construct that needs them. Each was a rule keyed
on something coarser than the thing the capability enables, and `OpCapability` is a demand: the
consumer must enable the device feature behind it before the module is legal to load.
**283 of the 14,579 corpus sources change SPIR-V; none changes status or reflection.**
- `GroupNonUniformArithmetic` was pushed for an arithmetic group *opcode*. The capability belongs
to the group *operation*: `Reduce`/`InclusiveScan`/`ExclusiveScan` take it, `ClusteredReduce`
takes `GroupNonUniformClustered` instead. Every `air.simd_*` whole-simdgroup reduction emits the
clustered form, so 244 modules demanded arithmetic subgroup support they use none of. Two
existing tests had asserted the old answer, one of them checking the substring `Reduce`, which
`ClusteredReduce` contains.
- `VariablePointers` was pushed for a pointer merge in any storage class but `StorageBuffer`. A
`PhysicalStorageBuffer` pointer is an address; merging one is what `PhysicalStorageBufferAddresses`
is for and neither variable-pointers capability governs it. 30 modules demanded the strictly
stronger `variablePointers` feature for merging only addresses.
- `Sampled1D` and `SampledBuffer` were pushed for an image of that dimensionality. `Dim 1D` is
enabled by either `Sampled1D` or `Image1D`, and the type's `Sampled` operand — 2 means storage —
says which one describes it. The storage arm read that operand and the sampled arm did not, so a
`texture1d<..., access::write>` claimed both. 9 modules.
These come from the same oracle as the `Geometry` fix above: strip one declared capability,
reassemble, and ask `spirv-val` whether the module still validates.
`tests/declared_capabilities_are_needed.rs` runs that oracle over every public fixture, and adds
the three checks `spirv-val` cannot make — it enforces an opcode's capability disjunction but not
the group operation's, the `Dim` enumerant's pair, or `ClipDistance` at all. The new fixture
`kernel_write_one_dimensional_textures` is the carrier for the image half and the first authored
device evidence for `air.write_texture_1d.u.v4i32` and `air.write_texture_buffer_1d.u.v4i32` — the
latter appears in no corpus source, so no corpus host could ever have covered it.
- A module no longer declares `Capability Geometry`, which no Metal-backed Vulkan implementation can
grant. Declaring a SPIR-V capability is a demand on the consumer — Vulkan requires the device
feature behind it before the `VkShaderModule` is legal — and `Geometry` demands `geometryShader`,
which Metal has no stage for at all. Nothing in the source language can produce a geometry shader,
so the demand only ever arrived by accident, and it did: `PrimitiveId` is enabled by ANY of
`Geometry`, `Tessellation`, `RayTracingKHR` or `MeshShadingEXT`, and the translator picked
`Geometry` from that disjunction unconditionally. **236 of the 14,579 corpus sources carried it;
226 were tessellation-evaluation entries that already declared `Tessellation`**, so the
requirement was satisfied before the demand was added and the demand bought exactly nothing. The
remaining 10 are fragment entries reading `[[primitive_id]]`, where one disjunct does have to be
declared; neither names a fragment shader, so the choice is between a disjunct every Metal-backed
implementation supports and one none of them does. **236 modules change SPIR-V, 10 of them by
gaining `Tessellation`; no source changes status and no reflection changes.** The Vulkan
validation layer reported this over the case store as
`VUID-VkShaderModuleCreateInfo-pCode-08740`. `tests/no_module_needs_a_geometry_stage.rs` sweeps
every public fixture for the invariant; the two arms of the rule are pinned by name in
`native::tests::interface` (a fragment entry, which must add `Tessellation`) and
`native::tests::intrinsics` (a tessellation-evaluation entry, which must add nothing).
- A buffer's reflected `access` is now what the module does, not that ORed onto what AIR declared,
wherever the walk that answers the question is provably complete. `widen_access` has always
refused to narrow, on the sound grounds that a store through a device address it cannot attribute
would be missed — but that risk has a boundary, and the boundary was already being computed for
the footprint. Under Logical addressing, with no pointer rooted at the descriptor escaping into an
operand slot the walk does not model, there is nowhere else for an access to come from. That is
the same proof under which the module now decorates the descriptor `NonWritable`, and reporting
the wider answer beside that decoration made one function state two incompatible facts: the module
told the driver the buffer is read-only while reflection told the consumer to upload it, barrier
it, and read it back. AIR's `air.read_write` on a buffer whose body only stores to it describes
the parameter, not the program. **Measured reach over the 14,579-source corpus: 2258 buffer
bindings in 1727 modules change access — 1846 `ReadWrite`→`WriteOnly`, 388 `ReadWrite`→`ReadOnly`,
21 `WriteOnly`→`Unused`, 3 `ReadOnly`→`Unused`.** No SPIR-V, no other reflected field, and no
status changes; all 1209 device cases re-record byte-identical. `REFLECTION_VERSION` is 55.
`tests/reflection_access_covers_the_module.rs` gains the direction it could not check before —
its contradicted-access kernel stores through an `air.read` buffer it never loads, and that buffer
is now `WriteOnly` rather than the declaration's read ORed onto the module's write — and
`tests/nonwritable_covers_the_module.rs` pins the two derivations to each other: a binding the
module decorates `NonWritable` may never reflect an access that includes writes.
- A storage buffer the module provably never writes is now decorated `NonWritable`. Vulkan reads the
absence of that decoration as a demand rather than as silence: a graphics-stage module declaring an
undecorated storage buffer requires its consumer to enable `fragmentStoresAndAtomics` or
`vertexPipelineStoresAndAtomics` whether or not any store exists
(`VUID-RuntimeSpirv-NonWritable-06340` and `-06341`). Running the candidate Vulkan executor under
`VK_LAYER_KHRONOS_validation` over all 1209 qualified corpus cases reported those two VUIDs 302
times; `grep -rn NonWritable src/` returned nothing, because the decoration had never been emitted
at all. Read-only buffers were therefore asking every consumer for a device feature the shader does
not use, and on a device without it the pipeline is simply unavailable.
**11,193 of 14,579 corpus sources change bytes** (8617 kernel, 1474 fragment, 869 vertex, 233
tessellation-evaluation). Of the 2608 graphics-stage modules that declare a storage buffer, **2558
now decorate every one of them** and drop the feature demand entirely; 18 are decorated in part and
32 not at all, and those keep the demand because the VUID is per-variable. 6199 of 6364
graphics-stage storage buffers are decorated. No source changed status and no reflection changed.
The proof is the access walk reflection already runs to widen a declared access
(`reflect::footprint`), not a second one: "did any instruction write through this descriptor" is one
fact about the module. Three conditions make that walk's silence a proof rather than an absence of
evidence -- Logical addressing, no observed write, and no pointer rooted at the descriptor reaching
an operand slot the walk does not model. The third was already computed and folded into
`has_unbounded_access`; it is now reported separately as `Analysis::escaped`. 291 candidate
descriptors are refused on the second or third condition. AIR's declared `air.read` is *not* the
signal and cannot be: the corpus contains buffers declared read-only that the body stores through,
and `tests/nonwritable_covers_the_module.rs` pins that case by name. That file is also the check
`spirv-val` does not perform -- measured here, `spirv-val` accepts an `OpStore` straight through a
`NonWritable` variable, so a wrong decoration is silent all the way to the device. It walks the
disassembly independently of the translator's own analysis, over every public fixture; an
independent sweep of the same shape found 0 violations across all 13,318 modules that translate.
- `air.simd_all`, `air.simd_any` and `air.simd_ballot.i64` now answer for Metal's 32-lane
simdgroup instead of the whole physical subgroup. Every other member of the family already did:
`air.simd_is_first`, `air.simd_broadcast_first` and the clustered `air.simd_{sum,min,max}`
reductions all read `SubgroupLocalInvocationId` and partition on it, and corpus source
`c3441ab4` emitted both models in one function -- an `OpGroupNonUniformFMax ... ClusteredReduce
%uint_32` four hundred instructions above an `OpGroupNonUniformAny` over the physical subgroup.
On a driver wider than 32 lanes the votes answered for lanes outside the caller's simdgroup, and
the ballot's bits were indexed by subgroup lane rather than by `simd_lane_id`. All three were
also the only members of the family emitted natively rather than as pass lowerings, so this
closes a native/pass split as well. The vote now reads the caller's own 32-lane ballot word
(`any` = non-zero, `all` = equal to the same partition's ballot of `true`), and the ballot is
that word zero-extended; the shared word selection is `subgroup_partition_ballot_word`, which
`air.quad_active_threads_mask` had open-coded. **Hardening on this hardware:** Apple's subgroup
is exactly 32, so the answers are unchanged here, and the new authored fixture
`kernel_simd_vote_and_ballot` confirms byte-identical device output for all five symbols. Four
of 14,579 modules change bytes; two more change only type-declaration order. No status and no
reflection changed, and the changed modules stop demanding `GroupNonUniformVote`.
- `air.simd_broadcast` and `air.simd_shuffle` now resolve their lane operand inside the CALLER's
Metal simdgroup instead of treating it as an absolute subgroup lane. Every other member of the
family already did -- `simd_shuffle_up`, `_down`, `_rotate_down`, `_and_fill_*` and the
`simd_broadcast_first` arm immediately above these two all read `SubgroupLocalInvocationId` and
rebase onto `lane & !31` -- so this was one fact derived two ways in one function. On a driver
whose subgroup is wider than 32, lane 40 asking for simd-local 3 read absolute lane 3, which
belongs to a different simdgroup. Both now go through one shared `metal_simd_absolute_lane_u32`,
which also masks the index so `base + index` cannot name an id past the end of the subgroup.
**Hardening, not a fix on any runtime here:** Apple's subgroup is exactly 32, so the rebase is a
no-op on this hardware, and the two authored cases added on one of the changed modules confirm
byte-identical device output. Ten of 14,579 modules change bytes; no status and no reflection
changed. The mask is a defined refinement, not a Metal match -- measured on an M3 Max,
`simd_shuffle(v, lane + 32)` returns lane `lane & !3`, so Metal has no out-of-range answer to
reproduce.
- `air.dispatch_threads_per_threadgroup` no longer reports the executing threadgroup size. It was
decoded as `KernRole::ThreadsPerThreadgroup` on the stated ground that "`vkCmdDispatch` issues
whole workgroups only, so under Vulkan the two denote the same value". That premise is false for
this translator, because `KernelDispatchPlan` emulates Metal's `dispatchThreads:` by giving each
region its own specialized `LocalSize` -- so a tail region's threadgroup genuinely is shorter, and
aliasing the roles made the requested size shrink with it. A Metal probe settles what the two
attributes answer: for a ten-thread grid in groups of four, the last threadgroup reports
`threads_per_threadgroup == 2` and `dispatch_threads_per_threadgroup == 4`. The requested size is
now its own `KernRole::DispatchThreadsPerThreadgroup`, emitted as plain constants from
`TransformOptions::kernel_local_size` -- the same value a caller decomposes the plan from, so it
is fixed at translation time even where the grid is not, and deliberately not routed through the
region spec constants. Two corpus modules change bytes; no status and no reflection changed.
`exact_thread_regions_report_the_requested_threadgroup_size_unchanged` runs both facts through all
four regions of a 10x3 grid in 4x2 threadgroups on the device and fails without the split.
- Recovering an inlined helper's local pointer field no longer forwards a source that has stopped
being an opaque handle. The pass replaces a handle-typed load with the value that was stored into
the same root/member slot, and it only filtered the load side. A device buffer parameter is
pointer-typed when its store is recorded but a `ulong` address by the second replay, so the
replacement handed every consumer a 64-bit integer where a handle belonged; an access chain rooted
on it can descend nothing, and the native emitter refused sixteen corpus modules with
`base %N has type TypeInt 64, which is not a pointer type`. The pass now declines only when the
source is not one of the handle shapes the load side already accepts. Two narrower-looking
variants are both wrong: requiring the two types to be *equal* trades four recoveries for eight
regressions, because a pointer source legitimately changes pointer type across the boundary, and
requiring only that a pointer load keep a pointer source breaks the case the second replay exists
for -- an entry texture parameter is a loaded image id by then, and declining it folds a real
`OpImageQuerySize` to zero with no status, reflection or byte-count signal at all. Four modules
translate that did not (`4115808d`, `c159cd71`, `de9eb706`, `f0673eb9`), no module regressed, no
reflection changed, and no other module's bytes move. The remaining twelve of the sixteen are
refused earlier, for an atomic on a non-atomic storage class, which the forwarding was masking.
- `metal2vulkan` now rejects an unrecognized option instead of using it as the output path. Both
positionals fell through a catch-all arm, so `metal2vulkan in.ll -o out.spv` wrote a file named
`-o` into the working directory and never wrote `out.spv` -- and said `wrote -o` while doing it. A
misspelled `--stag vertex` failed the same way. A leading dash is now always a flag, and an
unknown one is an error naming the positional form.
- The synthetic index an argument-buffer-embedded texture binds at is now derived from the entry's
parameter order rather than from the order the AIR metadata list names its `air.indirect_buffer`
nodes. `embedded_synthetic_texture_index` fixes where the synthetic indices start and the walk
hands out `K`, `K+1`, ... in list order, so a consumer binding by that index has to reach the same
order the translator did -- and reversing the argument list of one corpus kernel moved the same
embedded texture from `Binding 32` (sampled) to `Binding 480` (storage). Sixteen kernels were
order-dependent this way under the metamorphic sweep. Parameter index orders them because it is
unique per argument; the Metal `[[buffer(N)]]` slot is not, since mutually exclusive
function-constant alternatives share one. The order now belongs to `ArgumentBuffers`, whose only
constructor sorts, and the three walkers take that type and nothing else, so a fourth caller
cannot pass an unsorted list. Every AIR argument list in the local corpus is already in parameter
order, so the status A/B and the reflection diff over all 14579 sources are both zero changes.
- The AIR static-initializer evaluator reads 64-bit function constants, and a store keeps its own
operand width. `ulong` is a Metal function-constant type -- 47 of the local corpus's
`air.fc_initializer` globals are `i64` -- and the initializer reader accepted only 8, 16 and 32
bits, so every predicate derived from one stayed unknown and each caller read that as "not enabled
by default". Separately, every stored integer was narrowed to 32 bits regardless of the store's
type, which discards exactly the half an `lshr i64 %bits, 63` predicate reads; `trunc ... to i32`
had the same shape, masking only `i8` and `i16` destinations. Unresolved function-constant gates
in a 1823-source sample fall from 37 to 28, in 9 modules to 7, with five declarations moving from
"unknown, therefore treated as absent" to enabled. Status A/B and reflection diff over all 14579
local corpus sources: zero changes either way -- the wrong values were being read into decisions
that happened to land the same way, and the reason to fix them is that nothing guarantees the next
one will.
- The AIR static-initializer evaluator folds the ordered `icmp` predicates (`ugt`, `uge`, `ult`,
`ule`, `sgt`, `sge`, `slt`, `sle`), the integer opcodes it was missing (`sub`, `udiv`, `urem`,
`sdiv`, `srem`, `ashr`) and the `llvm.umax`/`umin`/`smax`/`smin` intrinsics. It read only `eq` and
`ne`, leaving 648 of the 10938 `icmp`s in the local corpus's static initializers unevaluated --
and an unevaluated function-constant predicate reads as "not enabled by default", which every
caller spends as a fact. Two corpus fragment shaders reported and emitted **no color attachment at
all**: their only `air.render_target` sat behind
`%15 = add nsw i32 %14, -3` / `%16 = icmp ult i32 %15, 2` / `xor i8 %17, 1`, a predicate that is
TRUE under the all-constants-zero variant. Both now declare `Location 0` in the module and in
reflection.
Signedness is the part worth stating: the evaluator carries every integer as a masked `u64`, so
`-1` compares GREATER than `1` unless the sign is recovered from the OPERAND's width, which is
what the shader above depends on. A division by zero stays unknown rather than folding, as an
over-wide shift already did. Status A/B over all 14579 local corpus sources: zero changes; the
reflection diff moves exactly six modules -- two gaining the color attachment above, four kernels
whose buffer footprint tightens because a newly folded constant changed which accesses are
reachable.
- A kernel's synthetic `[[stage_in]]` buffer slots are now allocated in PARAMETER-INDEX order rather
than in the order the AIR argument list names its nodes. Both `stage_input`'s lowering and
reflection read this one allocation, so a producer that emitted the same kernel with its argument
nodes reordered would have handed a consumer different slots for the same shader -- an ABI that
depends on a metadata layout nothing else reads. All 14397 kernel, fragment and vertex argument
lists in the local corpus are already in parameter-index order, so ordering them changes no
output; the status A/B over 14579 sources is zero changes. The set of roles a synthetic slot must
avoid is now `KernRole::buffer_table_slot`, an exhaustive match rather than a list with a
`_ => None` tail: a role added later that names a buffer-table index has to answer it, instead of
silently getting a stage input allocated on top of it.
- A texture the pipeline variant does not declare no longer takes a live texture's descriptor slot.
Metal compiles `[[texture(fc_expr)]]` into a RUNNING SUM over the arguments the pipeline enables,
emitted as a global the module's `air.static_init` constructor computes; the sum is a given
argument's Metal slot only while that argument is one the variant enables. For an argument whose
own `air.function_constant` gate the module's initializers drive to zero, the same global holds
wherever the sum stopped -- which is a LIVE argument's slot. Reading it anyway put 17 differently
shaped sampled textures on `Binding 38` of one corpus fragment shader, and a
`texture2d<float, write>` beside a 128-element `array_ref` on `Binding 480` of a kernel.
Reflection asked a consumer to bind two different textures to one Metal index -- no descriptor-set
layout describes that -- and the store the shader aimed at the argument that is not there landed on
the texture the pipeline did bind. 338 of 14579 local corpus sources emitted a module with two
resources on one descriptor slot; the fix takes that to 92, all of which are either Metal's own
mutually exclusive alternatives sharing a slot they STATE as a literal, or a module whose
all-constants-zero variant is degenerate for a reason of its own.
The rule keys on how the slot is spelled, not on the gate. `[[texture(0), function_constant(a)]]`
beside `[[texture(0), function_constant(!a)]]` is Metal's way of declaring mutually exclusive typed
alternatives; the slot is written down rather than summed, so it stays that argument's slot and the
binding is kept. All 4851 ptr-spelled `air.location_index` operands in the local corpus are globals
the static initializer writes; none is a constant global.
Dropping those descriptors made three texture lowerings answer a resource that is no longer there,
so the absent-resource contract now covers the whole texture-operation surface rather than only the
reading half:
- A `air.write_texture` whose image operand is an absent resource stores NOWHERE, the way
`lower_null_texture_result` already reads zero for one, under the same
`unsurfaced_embedded_resources` guard. The alternative is not "store somewhere harmless" but
"overwrite the texture the pipeline did bind".
- Recovering a Private placeholder onto "the module's only image binding" now also requires that
image to have the shape the AIR intrinsic's own stable symbol states. Exactly one candidate is
not evidence on its own, because an absent argument stands beside the live binding as a
differently shaped alternative of it. The three near-identical recovery helpers
(`single_storage_image_for_private_write`, `single_sampled_image_for_private_read`,
`single_image_for_private_query`) are now one `recovered_image_for_private_operand`, so the rule
is stated once, and one `intrinsic_texture_shape` parses the shape for it, for the write ABI and
for `air.get_null_texture_*`.
- A texture operand is absent whether it is the Private placeholder or the `OpConstantNull` that
placeholder holds, which is what resolving a load through it reaches. Recognizing only the first
left an `air.get_array_size_texture_2d_array` on the second to take the default non-arrayed 2D
shape and refuse.
Status A/B over all 14579 local corpus sources: **zero** changes.
`tests/gated_texture_descriptor_slots.rs` pins each of the four parts from both sides, including
the literal-slot control that scopes the rule.
- A texture an argument buffer holds inside a nested struct is no longer treated as an absent
texture. Metal lets an argument-buffer member be a user struct that itself holds a texture,
sampler or buffer; AIR spells that with an `air.struct_type_info` PREFIX naming the wrapper's own
member list, and the member's `air.indirect_argument` suffix is then an `i32` where a flat member
carries the node ref describing the resource. The embedded-argument walk reads only the flat form,
so the wrapped texture never became an embedded descriptor: the member decoded as opaque storage,
the handle load produced a Private placeholder, and the sample took the path that answers ZERO for
a resource the pipeline does not provide. That answer is right for a `[[function_constant]]`-gated
texture whose constant is off and wrong here -- the result was a fragment shader that samples
black, in a module that passes `spirv-val`, reports a consistent reflection, and gives a consumer
nothing to notice. The decode now reports each such resource, and a texture operand the resource
binding could not recover refuses in a module that declares one rather than answering zero. 52 of
14579 local corpus sources declare the shape; the status A/B moves exactly 12 of them from OK to an
honest FALLBACK and changes nothing else.
Surfacing them properly instead of refusing needs the argument-index rule for a nested member,
which the corpus does not settle: three modules spell the outer `i32` as 0, 1 and 201 beside nested
`air.location_index` values of 0, 10 and 0. `tests/argument_buffer_wrapped_resource.rs` pins the
flat form still binding, the decode naming what it cannot surface, and both the sampled and written
wrapped forms refusing.
- A `[[function_constant]]`-gated `air.stage_in` is the vertex stream it declares. The kernel decode
collapsed a gated stage-in attribute back to the wrapper, so the parameter lowered to `OpUndef`:
a skinning kernel that reads `position` always and `normal` behind a `needNormal` constant read
nothing at all for the normal, in a module that validates and whose reflection agrees with it.
120 gated `air.stage_in` arguments in 52 of 14579 local corpus sources; 12 of the 2880-source
sample gain 24 `KernelStageInput` bindings AND the same 24 descriptors in the emitted module.
Status A/B over all 14579 sources: zero changes.
`FC_PROMOTED_RESOURCE_ROLES` now states the rule for belonging to it: **promoting a role has to
change the emitted module, not only reflection.** The standing justification for keeping a gated
descriptor is that the resource-using arm may be enabled later, but an argument whose uses fold
away leaves an unreferenced variable that `module_cleanup` removes, and reflection then asks a
consumer to create and bind a descriptor no instruction touches. Measured that way,
`air.indirect_buffer` -- the other role the fragment decode promotes and the kernel and vertex
decodes do not -- gains 225 reflected bindings across 28 modules and **zero** module bindings, so
it stays out, with the measurement recorded next to the list. `texture`, `sampler` and `imageblock`
are already wrapper-neutral corpus-wide. `tests/gated_stage_inputs.rs` now translates one
declaration with and without the wrapper in all three stages and requires the two modules to be
identical. `REFLECTION_VERSION` is now 45.
- A `[[function_constant]]`-gated `air.vertex_input` is the vertex attribute it declares. The wrapper
says WHEN a parameter is live, not whether it exists: Metal reports the attribute, the application
binds a vertex buffer for it, and a pipeline created with the constant enabled reads it. The
fragment decode has always read a wrapped role straight through the marker, so the mirror-image
`air.fragment_input` was always the varying it declares; the vertex decode read its roles through a
resource-promotion list that named no stage-input role, so the argument became no `Input` variable
at all -- it lowered to `OpUndef`, and reflection omitted the attribute. Nothing reports that: the
module validates, and reflection agrees with the module about the wrong answer. 573 gated
`air.vertex_input` arguments in 89 of 14579 local corpus sources, every one with a real
`air.location_index` and none colliding with another attribute in its own module. Over the
2880-source sample: 15 modules change, 59 `Input` `Location`s and 59 `vertex_attributes` gained and
none lost, `vertex_attributes` the only reflected key that differs anywhere, and one vertex shader
goes from reporting no attributes at all to reporting its eight. Status A/B over all 14579 sources:
zero changes.
The vertex entry-parameter decode now states the roles it reads past the wrapper as one promotion
set, instead of patching the resource classifier's answer afterwards at the call site -- which is
how `patch_input` came to be corrected there while `vertex_input` was not corrected at all. The one
remaining call-site adjustment, a wrapped texture whose `air.location_index` is still unassigned, is
a demotion the promotion set cannot express and is documented as such.
`tests/gated_stage_inputs.rs` translates one declaration with and without the wrapper, in both
stages, and requires the two modules to be identical. `REFLECTION_VERSION` is now 44.
- A varying AIR declares reaches the module even when the shader never writes it. `stage_output`
skipped the store for an output whose value is statically `OpUndef` -- nothing useful to write, so
nothing written -- which left the Output variable unreferenced, and `module_cleanup`'s
unreferenced-global rule then removed the variable, its `Location` decoration and its entry-point
interface entry together. That rule is right for a descriptor, whose `Binding` a consumer would
otherwise have to satisfy for nothing, and wrong for a stage output, which is one half of a
linkage contract: the fragment shader compiled from the same Metal varying struct declares the
matching Input, and Vulkan requires every consumed input to have a producing output at that
`Location`. AIR declares the member because Metal declares it; that the shader leaves it undefined
makes its VALUE undefined, not its existence. Fragment outputs deliberately keep the old rule --
an attachment is memory, and one nothing writes is better left unwritten than written with garbage.
Over the 2880-source sample: 30 modules change (27 vertex, 3 tessellation evaluation), 87 Output
`Location`s gained and none lost, no Input change and no reflected field change at all; the
reflection-declares-a-varying-the-module-does-not oracle goes from 30 modules to 0. Status A/B over
all 14579 sources: zero changes. `tests/vertex_output_declared_locations.rs` pins both halves of
the rule, including the fragment attachment that stays unwritten.
- A `[[function_constant]]`-gated `air.vertex_output` member keeps the varying slot it declares. A
vertex return struct and the fragment parameter list it feeds are one Metal declaration compiled
twice, and Vulkan links the two by `Location`, which this translator assigns positionally from the
AIR interface list -- so the numbering rule has to be a pure function of that list and identical in
both stages. It was not: the fragment decode reads a wrapped role straight through the
`air.function_constant` marker and numbered the gated member, while the vertex output decode read
its roles through a promotion list that named no output role at all and dropped it, numbering every
member behind it one slot lower. Both modules validate, both report the same varyings by name, and
the pipeline links -- the fragment simply reads a different interpolant than the vertex wrote, for
every varying declared after a gated one. 507 gated `air.vertex_output` members in 156 of 14579
local corpus sources, 106 of them with an ungated member behind the gated one, which is the shape
that shifts; 1240 gated `air.fragment_input` parameters in 292 sources on the other side. A
reflection A/B over the 2880-source sample finds 30 modules differing and the `varyings` key is the
only one that differs in any of them: 22 have a location that now names a different varying (the
shift), and 8 declared every varying under a function constant and so reported none at all. Status
A/B over all 14579 sources: zero changes.
A gated BUILTIN return member still needs the module's own initializer to turn it on, which is the
distinction the fragment decode draws with `FRAGMENT_SYSTEM_VALUE_ROLES` and for the same reason:
nothing writes a builtin whose predicate is off, and declaring `Layer` or `ViewportIndex` anyway
puts a device capability in the module for a value nothing produces. Four vertex sources declare
TWO gated `air.point_size` members under mutually exclusive predicates, and promoting both emits
two `PointSize` builtins in one entry point, which is invalid.
Structurally, the vertex output roles are now one table, `VERTEX_OUTPUT_ROLES`, that is BOTH the
set an `air.function_constant` wrapper is resolved against and the mapping the decode applies -- a
role cannot be lowered without being read past the wrapper, or read past the wrapper without being
lowered. Those were two spellings of one fact and they disagreed. `gated_role` is now the one place
a wrapper is resolved, shared with the resource classifier.
`tests/gated_varying_locations.rs` translates one gated varying struct as a vertex and as a
fragment and compares the emitted `Location` decorations, which is the property that was broken and
which neither module can fail on its own. `REFLECTION_VERSION` is now 43.
- A `[[function_constant]]`-gated `sampler` argument is a descriptor in every stage, not only in
fragments. Metal declares a gated `texture2d` and the gated `sampler` it is sampled through
together, and the fragment decode reads a wrapped argument's role straight through the
`air.function_constant` marker, so it always bound both. The kernel and vertex decodes read theirs
through a promoted-role classifier whose list named `texture`, `imageblock` and the function
tables but not `sampler` -- so the same two lines of AIR produced a texture descriptor and no
sampler descriptor, the sampler parameter never became one, and the sample fell through to the
translator's own nearest/clamp default. 63 gated sampler arguments across 21 of 14579 local corpus
sources; 9 of them, in 6 modules, are kernel or vertex. Status A/B over all 14579: exactly one
module goes FALLBACK -> OK -- the one whose sample actually reached the substitution, which the
previous entry now refuses -- and it reports its sampler at the Metal slot AIR declared. Four of
the remaining five already translated and gain exactly the 7 `Sampler` bindings that were missing,
with nothing removed and no other reflected field changed; the sixth still fails on a Metal visible
function table. A reflection A/B over the 2880-source sample finds one module gaining one
`Sampler` binding and no other content difference at all -- every remaining diff is the version
field itself. The promotion list is now one named `FC_PROMOTED_RESOURCE_ROLES` rather than one
match arm per role -- separate arms are what let `sampler` go missing next to `texture` --
and `tests/gated_system_values.rs` translates one gated texture+sampler declaration in all three
stages, which is the property that was broken. `REFLECTION_VERSION` is now 42.
- A sampler operand the translator could not resolve to a sampler is refused instead of being
answered with the translator's own default. `valid_sampler_value` ended with "if it is still
pointer-shaped, load the synthesized nearest/clamp sampler". That is correct for exactly one
operand -- `air.get_read_sampler()`, which AIR declares stateless and whose consumer ignores the
sampler -- and wrong for every other one, because a pointer-shaped sampler operand is a state the
shader chose that an earlier pass failed to carry. The commonest form is a runtime `select`
between two `__air_sampler_state` globals: the emitter has no SPIR-V pointer value for it and
leaves a private placeholder, so both states are gone by the time the sample lowers and the module
went on to validate, bind and reflect as though the shader had asked for nearest/clamp. Which ids
`air.get_read_sampler()` produced is now recorded before AIR-call lowering rewrites them
(`Ctx::read_sampler_values`), since after the rewrite the two forms are indistinguishable by type.
Status A/B over all 14579 local corpus sources: 9 modules move from a silently substituted sampler
to a clean FALLBACK, and nothing else changes. `tests/must_fallback.rs` pins the selected form
from both sides, and a cube read through `air.get_read_sampler()` -- the one operand the default
may still answer -- is pinned in `src/native/tests/textures.rs`.
- Reflected translation no longer asks a consumer to create a `VkSampler` at a binding the module
does not declare. `StaticSampler` is a descriptor translation invents -- nothing in Metal's API
puts one there, so the only reason a consumer creates it is that this reflection asked. Reflection
@@ -234,8 +744,28 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
bound no longer demands a texture descriptor it never reads. The rule is stated once, over the
set of synthesized placeholders, rather than per variable.
### Removed
- `TransformOptions::simd_cluster32` and the `--simd-cluster32` CLI flag. The option could not be
observed: `options_for_air` force-enabled it for any module whose text contained `@air.simd_`,
and every arm it gated is reached only from an `air.simd_*` lowering, so a caller who passed
`false` silently got clustering anyway and a caller who passed `true` changed nothing. The
32-lane partition is now unconditional, which is what the shuffle half of the family already
did -- `metal_simd_absolute_lane_u32` never consulted the flag. Removing it deletes the string
sniff, five unreachable whole-subgroup arms, and one test that asserted a state that cannot
occur; `air.simd_is_first` and `air.simd_broadcast_first` now take their partition base from the
shared `metal_simd_lane_local_u32` / `metal_simd_lane_base_u32` helpers instead of open-coding
it a third time. Measured: 0 of 14,579 corpus modules change a byte.
### Added
- `translate_sanitized_native_specialized_reflected_with_options` and
`translate_sanitized_native_linked_specialized_reflected_with_options`: the function-constant
specialized and linked translation entry points now have reflected forms, so a caller that binds
the module can have the reflection OF that module. `reflect_sanitized_specialized` constructs no
module and therefore answers the AIR type name for the facts only a finished module knows, which
is what its doc comment has always said; before this the specialized paths left no other choice.
- Reflection schema v36: an argument-buffer member that holds a resource handle is reported at the
eight bytes it occupies instead of as the type it points at. Metal spells such a member with its
pointee's name -- `char` for a `device char *`, `float4x3` for a `device float4x3 *`, a
+6 -6
View File
@@ -41,23 +41,23 @@ standalone crate.
# format
cargo fmt --all
# clippy (CI denies warnings)
cargo clippy --workspace --all-targets -- -D warnings
# clippy (CI denies warnings); --all-features also covers the `serde` cfg the CLI ships with
cargo clippy --workspace --all-targets --all-features -- -D warnings
# public Rustdoc, including feature-gated APIs (CI denies warnings)
RUSTDOCFLAGS='-D warnings' cargo doc --workspace --all-features --no-deps
# unit + integration tests (Cargo defaults to the available logical CPU count)
cargo test -p metal2vulkan
cargo test -p metal2vulkan --all-features
# optional validation package
cargo test -p metal2vulkan-validation
cargo test -p metal2vulkan-validation --all-features
```
External tools used by some paths: `llvm-dis`, `spirv-val` (and friends). On macOS with Homebrew:
```sh
PATH=/opt/homebrew/opt/llvm/bin:$PATH cargo test -p metal2vulkan
PATH=/opt/homebrew/opt/llvm/bin:$PATH cargo test -p metal2vulkan --all-features
```
GPU-free byte A/B is provided by `corpus-ab` in the validation crate.
@@ -93,7 +93,7 @@ Quick anchors:
```sh
# always
cargo test -p metal2vulkan
cargo test -p metal2vulkan --all-features
# before/after a byte-stable refactor
cp target/release/metal2vulkan ./m2v-old
+7 -4
View File
@@ -53,13 +53,13 @@ These options affect pipeline- or dispatch-dependent lowering:
| Option | Supply it when |
|---|---|
| `--raster-samples 1|2|4|8|16|32|64` | Fragment AIR calls `air.get_num_samples.i32`; use the exact graphics-pipeline sample count |
| `--simd-cluster32` | A caller explicitly needs Metal's 32-lane simdgroup reduction partition on a wider Vulkan subgroup |
| `--local X,Y,Z` | Kernel dispatches use a threadgroup size other than the default `64,1,1` |
| `--threads-per-grid X,Y,Z` | Reflect one fixed Metal `dispatchThreads` grid for region planning |
| `--threads-per-grid-push-constant OFFSET` | Move the default 48-byte dispatch-region payload from offset 0 to `OFFSET` |
| `--whole-workgroups` | Assert every kernel launch covers complete workgroups and use one fixed-local-size pipeline |
The translator automatically preserves the 32-lane contract for recognized `air.simd_*` modules.
Every `air.simd_*` lowering keeps Metal's 32-lane simdgroup contract unconditionally; there is no
option for it, because there is no correct module that wants the driver's subgroup width instead.
Do not use either option as a workaround for an unrelated translation failure.
## 3. Translate from Rust
@@ -236,7 +236,10 @@ footprint soundness gate. Treat `access: null` conservatively as read-write.
`translate_sanitized_native_specialized_with_options`; specialization must precede metadata,
resource-interface, and CFG construction. Metadata-only tooling must pass those same payloads to
`reflect_sanitized_specialized`; reflecting the default AIR can omit a resource selected by a
non-default value. Exact predicates also remove false-gated resources from the specialized
non-default value. A consumer that BINDS the specialized module should take its reflection from
`translate_sanitized_native_specialized_reflected_with_options` instead: `reflect_sanitized*`
constructs no module, so the image type behind a texture binding stays at the AIR type name, and a
`texturecube` that is only ever texel-read is bound as a 2D array image. Exact predicates also remove false-gated resources from the specialized
interface, so consumers bind the selected contract rather than the unspecialized union. A
generated fullscreen companion must use `translate_passthrough_specialized` with the same
payloads so its vertex outputs match the selected fragment inputs.
@@ -279,7 +282,7 @@ At minimum:
```sh
spirv-val --target-env vulkan1.2 output.spv
cargo test -p metal2vulkan
cargo test -p metal2vulkan --all-features
```
`spirv-val` checks structural validity, not Metal equivalence. For a semantic claim, follow the
+39 -2
View File
@@ -43,7 +43,8 @@ Other entry points:
| `translate_reflected` / `translate_reflected_with_options` | Path to `.air` or `.ll` + stage |
| `translate_sanitized_native_reflected` | You already have sanitized LLVM IR text and `TransformOptions` |
| `reflect_sanitized` | You need metadata for link-time tooling even when executable translation is not yet possible; buffer footprints remain absent, and the `BufferAddressTable` binding is predicted rather than read off a module (it can be reported for a module that declares none, or missed for one that does) |
| `reflect_sanitized_specialized` | You need metadata for exact function-constant values that can select resources or outputs; buffer footprints remain absent |
| `translate_sanitized_native_specialized_reflected_with_options` / `..._linked_specialized_reflected_with_options` | You are BINDING a function-constant-specialized (and possibly linked) module and need the reflection of that exact module |
| `reflect_sanitized_specialized` | You need metadata for exact function-constant values that can select resources or outputs; buffer footprints remain absent, and the texture shape, `BufferAddressTable` binding, and synthesized placeholder descriptors are the same AIR-text approximations `reflect_sanitized` documents above |
| `ShaderReflection::from_{fragment,vertex,kernel}` | You already have `meta::{Frag,Vert,Kern}Meta`; IR-derived fields and buffer footprints remain absent |
Path-based optional transforms use `translate_reflected_with_options`. The sanitized reflected
@@ -72,7 +73,7 @@ metal2vulkan = { version = "0.1", features = ["serde"] }
```
`ShaderReflection` and its nested types derive `Serialize`/`Deserialize` under that feature. The
current `REFLECTION_VERSION` is `39`. Serialized Rust enums use serde's externally tagged default:
current `REFLECTION_VERSION` is `49`. Serialized Rust enums use serde's externally tagged default:
unit variants are strings (for example `"Unbounded"`), while data variants are objects (for example
`{ "Object": { "bytes": 288 } }`). Optional fields serialize as `null`.
@@ -286,6 +287,15 @@ other rooted dereference the affine schema cannot prove. When true, consumers mu
caller-provided window; the other entries remain useful diagnostics but do not authorize narrowing.
When false, the union of the static and bounded strided ranges is a conservative staging footprint.
A reflected descriptor the finished module never declares is a special case, because there is no
variable to walk. Whether its absence proves anything is a property of the module's ADDRESSING
MODEL, not of what AIR declared about the buffer: under `Logical` addressing every access reaches
memory through a declared variable, so a binding with no variable executes zero bytes and its
footprint is bounded and empty. A module that lowered any pointer to a device address carries
`PhysicalStorageBuffer64`, and there a `PhysicalStorageBuffer` access can reach a buffer that has no
descriptor, so the footprint stays unbounded. `access` is unaffected either way — it is the declared
classification widened by what the module was seen doing, and there is nothing to widen it with.
Pointer-select/phi alternatives are analyzed structurally across every descriptor arm. To preserve
the per-translation memory bound, an adversarial expression with more than 4096 address alternatives
is compressed to one unbounded result per affected binding rather than allowed to grow
@@ -390,6 +400,28 @@ Successful reflected translation records the applied states in
`None` for `Unknown`; the corresponding binding's `texture_shape.storage_format` reports the same
choice. Create the image view and descriptor from the same runtime state used for translation.
### Nil texture bindings are resolved at translation time
Metal decides whether a texture slot is nil when the encoder binds, and `air.is_null_texture_*`
observes that decision at run time. A Logical SPIR-V module has no equivalent query: a descriptor
either exists in the module or it does not, and nothing in the shader can ask the host what it
bound. Translation therefore answers the predicate from the module it is building.
A texture argument that translation surfaces as a descriptor answers `false`. The predicate answers
`true` only for a handle translation itself synthesized (`air.get_null_texture_*`, reported as
`SynthesizedNullTexture`) or for an argument the module does not surface at all — for example a
function-constant-gated argument the selected variant disables. Reads through an absent handle fold
to zero and writes through one are dropped, matching Metal's contract for an unbound resource.
**Consequence for the consumer:** a translated module COMMITS to "this slot is bound". Binding nil to
that Metal index at run time does not take the shader's nil branch; the shader reads whatever the
descriptor holds. If a pipeline can leave the slot nil, that is a second pipeline configuration and
needs its own translation, in the same way a different runtime sampler or storage-image format does.
Measured over the 14,579-source local corpus: 583 sources name `air.is_null_texture_*`, and 581 of
them contain no `air.get_null_texture_*` handle at all — so for those the predicate is entirely a
question about host binding, and translation answers it as "bound".
## Typical consumer flow
1. Call `translate_reflected` (or a serde-enabled CLI with `--emit-meta`).
@@ -434,6 +466,8 @@ choice. Create the image view and descriptor from the same runtime state used fo
| `metal2vulkan::reflect_sanitized_specialized` | Reflect the same function-constant-specialized AIR resource contract used by translation |
| `metal2vulkan::translate_sanitized_native_specialized_with_options` | Translate exact-width scalar/vector FC payloads before structural lowering |
| `metal2vulkan::translate_sanitized_native_linked_specialized_with_options` | Apply the same AIR-level specialization after authored linkage resolution |
| `metal2vulkan::translate_sanitized_native_specialized_reflected_with_options` | Translate FC payloads AND get the reflection of the module you are about to bind |
| `metal2vulkan::translate_sanitized_native_linked_specialized_reflected_with_options` | The same, after authored linkage resolution |
| `metal2vulkan::specialize_function_constant_bytes` | Repoint FC initializers only in an already emitted module that retained the complete specialized structure |
Unit coverage for binding numbers lives in `src/reflect/tests.rs` (the default ABI uses set 0, bases
@@ -446,3 +480,6 @@ separately).
descriptor/type/value graph required for conservative buffer footprints.
- Not a substitute for `spirv-val` or runtime pipeline creation.
- Not populated for passthrough vertex generation (`translate_passthrough`).
- Not a description of run-time binding choices. `air.is_null_texture_*` is resolved when the module
is built, not when the encoder binds — see *Nil texture bindings are resolved at translation
time*.
+28 -2
View File
@@ -19,8 +19,8 @@ Run Rust tests with Cargo's default available parallelism:
```sh
cargo fmt --all
cargo clippy --workspace --all-targets -- -D warnings
cargo test -p metal2vulkan
cargo test -p metal2vulkan-validation
cargo test -p metal2vulkan --all-features
cargo test -p metal2vulkan-validation --all-features
```
CI uses owned synthetic fixtures. Private AIR and machine-specific GPU execution are optional.
@@ -37,6 +37,14 @@ cargo run -p metal2vulkan-validation --bin corpus-index
cargo run -p metal2vulkan-validation --bin corpus-next -- --limit 1
```
`corpus-next --coverage` orders the same case-less sources by what authoring one would add rather
than by hash: each row's `reach` is the total number of case-less sources that call the `air.*`
symbols this source would be the first cased source to call, and `calls` is how many distinct
symbols it calls at all, which breaks ties toward the cheapest row to author. Coverage is
source-level -- a symbol counts as covered once any source with a case calls it -- so `reach` is an
upper bound on what one case closes, not a promise. The query reads only `sources`, `cases`, and
the cached `triage_analysis` histogram; it opens no source shard.
Ordinary `corpus-index` runs are incremental: unchanged multi-gigabyte AIR source shards are not
opened. Use `corpus-index -- --rebuild` only for explicit recovery; `--check` verifies a cloned,
incrementally synchronized snapshot without performing a second full rebuild. Upgrading a legacy
@@ -313,6 +321,24 @@ cargo run -p metal2vulkan-validation --bin corpus-case-check -- \
--delete-air AIR_SHA256 --delete-name CASE_NAME
```
### Re-check the installed store against the current product
An authored case is evidence about the bytes this translator emits **today**. A product change that
moves a descriptor slot or starts requiring a resource turns that evidence into a manifest the
checker no longer accepts, with its Metal and candidate observations still committed beside it.
`corpus-index --check` does not see this: it verifies the index against the shards, not the shards
against the product.
```sh
cargo run --release -p metal2vulkan-validation --bin corpus-case-check -- --recheck-all
```
It re-runs the shared checker over every installed case, names each one it now rejects with the
checker's own reasons, and exits non-zero if any are stale. It needs the private AIR sources, so it
is a developer command rather than a CI gate. Run it after any change to reflection, to the
descriptor ABI, or to the authored schema — a full-corpus translation A/B measures status and bytes
and will not tell you the store went stale.
## Contract 1: emitter stability
Preserve the old translator binary, build the new one, and use the smallest useful explicit
+33
View File
@@ -0,0 +1,33 @@
// SCRATCH: translate one AIR source with explicit function-constant values and write the SPIR-V.
fn main() {
let args: Vec<String> = std::env::args().collect();
let src = std::fs::read_to_string(&args[1]).expect("read");
let out = std::path::PathBuf::from(&args[2]);
let mut values = Vec::new();
for spec in args[3..].iter() {
let (i, v) = spec.split_once('=').expect("index=hexbytes");
let bytes: Vec<u8> = v
.as_bytes()
.chunks(2)
.map(|c| u8::from_str_radix(std::str::from_utf8(c).unwrap(), 16).unwrap())
.collect();
values.push((i.parse::<u32>().unwrap(), bytes));
}
let tmp = std::env::temp_dir().join(format!("fcspec-{}", std::process::id()));
std::fs::create_dir_all(&tmp).ok();
let options = metal2vulkan::passes::TransformOptions::default();
match metal2vulkan::translate_sanitized_native_specialized_reflected_with_options(
&src,
metal2vulkan::passes::Stage::Kernel,
&tmp,
options,
&values,
) {
Ok((spv, _)) => {
std::fs::write(&out, &spv).expect("write");
println!("OK {} bytes", spv.len());
}
Err(e) => println!("ERR {e}"),
}
std::fs::remove_dir_all(&tmp).ok();
}
+78
View File
@@ -0,0 +1,78 @@
//! Apply the pre-submission loop budget to an emitted SPIR-V module and validate the result.
//!
//! Verification aid for the guard that keeps a dropped loop bound from wedging the GPU:
//!
//! ```text
//! metal2vulkan case.ll case.spv
//! cargo run --example loop_budget -- case.spv [budget]
//! ```
//!
//! Exits non-zero if the instrumented module fails `spirv-val`, which is the property that matters:
//! a guard that produces invalid SPIR-V would turn every loopy case into a pipeline-creation error.
use std::path::Path;
fn main() {
let mut args = std::env::args().skip(1);
let Some(input) = args.next() else {
eprintln!("usage: loop_budget <in.spv> [budget]");
std::process::exit(2);
};
let budget = match args.next() {
Some(text) => match text.parse::<u32>() {
Ok(budget) => budget,
Err(error) => {
eprintln!("budget {text:?}: {error}");
std::process::exit(2);
}
},
None => metal2vulkan::DEFAULT_LOOP_BUDGET,
};
let spv = match std::fs::read(&input) {
Ok(bytes) => bytes,
Err(error) => {
eprintln!("read {input}: {error}");
std::process::exit(1);
}
};
let scratch = std::env::temp_dir();
if let Err(error) = metal2vulkan::tools::spirv_val_bytes(&spv, Path::new(&scratch)) {
eprintln!("input module does not validate before instrumentation: {error}");
std::process::exit(1);
}
let (bounded, report) = match metal2vulkan::instrument_spirv_loop_budget(&spv, budget) {
Ok(result) => result,
Err(error) => {
eprintln!("instrument {input}: {error}");
std::process::exit(1);
}
};
println!(
"{input}: {} loops bounded in place, {} via early return, {} non-iterating, {} -> {} bytes",
report.loops_bounded_in_place,
report.loops_bounded_via_early_return,
report.loops_skipped,
spv.len(),
bounded.len()
);
match metal2vulkan::tools::spirv_val_bytes(&bounded, Path::new(&scratch)) {
Ok(()) => println!("{input}: instrumented module PASSES spirv-val"),
Err(error) => {
eprintln!("{input}: instrumented module FAILS spirv-val: {error}");
let dump = format!("{input}.bounded.spv");
let _ = std::fs::write(&dump, &bounded);
eprintln!("wrote {dump} for inspection");
std::process::exit(1);
}
}
if !report.had_loops() && bounded != spv {
eprintln!("{input}: loop-free module was modified; the guard must be a no-op here");
std::process::exit(1);
}
}
+10 -1
View File
@@ -499,7 +499,6 @@ pub fn air_intrinsic_disposition(name: &str) -> Option<AirIntrinsicDisposition>
| "air.get_primitive_acceleration_structure_instance_acceleration_structure"
| "air.get_data_pointer_instance_acceleration_structure"
| "air.imageblock_data"
| "air.rhadd.u.i16"
) {
return Some(Lowered);
}
@@ -562,9 +561,19 @@ pub fn air_intrinsic_disposition(name: &str) -> Option<AirIntrinsicDisposition>
"air.ctz",
"air.clz",
"air.mul_hi.u",
"air.mul_hi.s",
"air.mad_hi.u",
"air.mad_hi.s",
"air.mad_sat.s",
"air.mad_sat.u",
"air.add_sat.u",
"air.add_sat.s",
"air.sub_sat.u",
"air.sub_sat.s",
"air.hadd.u",
"air.hadd.s",
"air.rhadd.u",
"air.rhadd.s",
"air.convert",
"air.dfdx",
"air.fast_dfdx",
@@ -6,13 +6,15 @@
//! It works on dense block indices, `0` being the entry, because every caller already has (or can
//! cheaply build) that shape: the owned-CFG check indexes blocks positionally, the relooper indexes
//! them positionally, and the nesting structurizer maps its labels through a table it builds anyway.
//! Keeping one implementation is the point. The obvious alternative -- a dominator *set* per block --
//! Keeping one implementation is the point, which is also why this sits at the crate root rather
//! than inside `native`: the passes layer must not depend on `native`, and a second copy over there
//! would be exactly the duplication this module exists to prevent. The obvious alternative -- a dominator *set* per block --
//! is quadratic in the block count, and generated shaders reach block counts where that alone costs
//! hundreds of megabytes; the structurizer shipped that form once and it cost more memory than the
//! whole rest of the translation.
/// The reverse adjacency of a dense successor table.
pub(in crate::native) fn build_predecessors(successors: &[Vec<usize>]) -> Vec<Vec<usize>> {
pub(crate) fn build_predecessors(successors: &[Vec<usize>]) -> Vec<Vec<usize>> {
let mut predecessors = vec![Vec::new(); successors.len()];
for (source, targets) in successors.iter().enumerate() {
for target in targets {
@@ -26,7 +28,7 @@ pub(in crate::native) fn build_predecessors(successors: &[Vec<usize>]) -> Vec<Ve
///
/// Returns `(reachable, intervals, idom)`, each indexed by block. `reachable` is what a depth-first
/// walk from block `0` reaches; `intervals` and `idom` are `None` for everything it does not.
pub(in crate::native) fn dominance(
pub(crate) fn dominance(
successors: &[Vec<usize>],
predecessors: &[Vec<usize>],
) -> (Vec<bool>, Vec<Option<(usize, usize)>>, Vec<Option<usize>>) {
@@ -131,7 +133,7 @@ fn intersect(
///
/// Reflexive, and false for either block being unreachable -- an unreachable block dominates
/// nothing and is dominated by nothing.
pub(in crate::native) fn dominates_interval(
pub(crate) fn dominates_interval(
dominance: &[Option<(usize, usize)>],
dominator: usize,
node: usize,
+45 -18
View File
@@ -62,17 +62,43 @@ pub(crate) struct EmitSidecar {
/// aggregate and path survive emitted helper inlining; interface binding remaps `source` to the
/// concrete descriptor value before resource-wrapper collapse resolves matching extracts.
pub(crate) aggregate_pointer_values: Vec<AggregatePointerValue>,
/// Result ids emitted as typed sentinels for the stable `llvm.agx2.cluster.num` ABI intrinsic.
/// The final interface pass replaces each sentinel with the AGX2 physical-cluster number derived
/// from Vulkan `LocalInvocationId` and the caller-supplied kernel local size.
pub(crate) agx2_cluster_numbers: Vec<Word>,
/// The Workgroup array variable staging an explicit imageblock whose AIR carries
/// `air.alias_implicit_imageblock`. The alias says its cells ARE render-target texels, and the
/// emitter cannot reach the descriptor-backed planes that represent those; `aliased_imageblock`
/// fills every cell from them on entry and writes it back on return.
pub(crate) aliased_imageblock_staging: Option<Word>,
}
#[derive(Debug)]
pub(crate) struct EmissionFailure {
pub(crate) error: String,
pub(crate) ordinary_plan_rejected_functions: HashSet<String>,
pub(crate) ownership_plan_rejected_functions: HashSet<String>,
/// Boxed so that every emission `Result` in the crate stays one pointer wide in its error arm.
pub(crate) rejected: Box<EmissionRejections>,
}
/// The owned emitter facts a failed emission hands to representation selection. Each names a shape
/// the attempt proved this source cannot take, and a retry chooses its next representation from
/// them rather than from the error text.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct EmissionRejections {
pub(crate) ordinary_plan_functions: HashSet<String>,
pub(crate) ownership_plan_functions: HashSet<String>,
/// `(callee, caller-local argument name)` for every helper call the emitter refused because a
/// descriptor-relative byte cursor cannot cross a SPIR-V function boundary. Logical addressing
/// forbids handing the callee a derived pointer, and the cursor lives in emitter state rather
/// than in any SSA value, so the only representation that keeps the callee's accesses on the
/// buffer is one with no boundary: the AIR-text retry inlines exactly these call sites.
pub(crate) cursor_call_sites: HashSet<(String, String)>,
}
impl EmissionFailure {
/// A failure raised before or beside emission, with no owned emitter facts to carry.
pub(crate) fn from_error(error: String) -> Self {
EmissionFailure {
error,
rejected: Box::default(),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -94,9 +120,15 @@ pub(crate) enum AirStructLayoutMappingStatus {
/// is the raw byte/word view a buffer takes when its accesses are byte-addressed, and it is not
/// a disagreement with the metadata -- there is nothing to disagree with. Keeping it apart from
/// [`AirStructLayoutMappingStatus::EmittedShapeMismatch`] matters because the two ask for
/// different work: over 2880 corpus sources 1681 of 1805 unmapped parameters are this, and the
/// 124 that remain are the ones where two structural descriptions actually differ.
/// different work: over the 14579 corpus sources 8044 of 8473 unmapped parameters are this, and
/// the 378 shape mismatches are the residue worth reading.
EmittedIsUntypedBuffer,
/// The emitted parameter has members, and walking them against the declared member list did not
/// line up. Not every one of these is a layout disagreement: when a buffer keeps the source
/// struct verbatim, that type spells its padding out as `[N x i8]` members AIR never names and
/// may nest an array AIR describes flat (`[8 x [8 x [8 x T]]]` against `T[512]`), so the walk
/// stops even though every declared offset is present in the emitted decorations. Read the
/// member offsets before treating one as a bug.
EmittedShapeMismatch,
NonIncreasingOffsets,
}
@@ -202,7 +234,7 @@ impl EmitSidecar {
for fact in &self.aggregate_pointer_values {
ids.extend([fact.aggregate, fact.source]);
}
ids.extend(self.agx2_cluster_numbers.iter().copied());
ids.extend(self.aliased_imageblock_staging);
ids.extend(self.air_struct_offsets.keys().copied());
ids.extend(
self.air_struct_layout_mappings
@@ -267,7 +299,7 @@ impl EmitSidecar {
replace(&mut fact.aggregate);
replace(&mut fact.source);
}
for id in &mut self.agx2_cluster_numbers {
if let Some(id) = &mut self.aliased_imageblock_staging {
replace(id);
}
for mapping in &mut self.air_struct_layout_mappings {
@@ -402,12 +434,6 @@ impl EmitSidecar {
})
.collect::<Vec<_>>();
self.aggregate_pointer_values.extend(clones);
let clones = self
.agx2_cluster_numbers
.iter()
.filter_map(|id| remap.get(id).copied())
.collect::<Vec<_>>();
self.agx2_cluster_numbers.extend(clones);
}
pub(crate) fn remap_local_pointer_field_store_sources(&mut self, remap: &HashMap<Word, Word>) {
@@ -667,7 +693,7 @@ mod tests {
source: 44,
indices: vec![1, 0],
}],
agx2_cluster_numbers: vec![50],
aliased_imageblock_staging: Some(51),
};
let remap = HashMap::from([
(10, 110),
@@ -695,6 +721,7 @@ mod tests {
(44, 144),
(5, 105),
(50, 150),
(51, 151),
]);
sidecar.remap_ids(&remap);
@@ -736,6 +763,6 @@ mod tests {
assert_eq!(sidecar.local_pointer_dynamic_field_loads[0].id, 140);
assert_eq!(sidecar.local_pointer_dynamic_field_loads[0].root, 141);
assert_eq!(sidecar.local_pointer_dynamic_field_loads[0].index, 142);
assert_eq!(sidecar.agx2_cluster_numbers, vec![150]);
assert_eq!(sidecar.aliased_imageblock_staging, Some(151));
}
}
+382
View File
@@ -0,0 +1,382 @@
//! Whether a finished module can still do what its AIR said it does.
//!
//! Every lowering decision that removes work is safe only while something the dispatch can observe
//! survives it. Metal's `[[function_constant]]` folding is the one that can remove all of it: AIR
//! declares no default for a function constant, so `meta::globals` reads its `undef`
//! `air.fc_initializer` as zero, and a shader that dispatches on the constant's VALUE — rather than
//! on `air.is_function_constant_defined`, which AIR does answer — can have every arm fall away. The
//! result validates, reflects, and writes nothing.
//!
//! Metal imageblocks are the second way it happens, and the cause is ours rather than the shader's:
//! an imageblock is tile memory that Metal's render pass resolves into its attachments, Vulkan has
//! no such step, and this translator therefore stages imageblock cells in per-invocation `Private`
//! or per-threadgroup `Workgroup` memory. A kernel that reads back what it staged and then writes a
//! texture is fine; a Metal tile CLEAR kernel, whose only write is the imageblock, becomes a module
//! that validates, reflects no resource at all, and clears nothing.
//!
//! The predicates here are the halves of noticing both: what the AIR plainly does — through either
//! path — and what the emitted module still can.
use crate::spirv_module::Module;
use crate::spirv_operand::Operand;
use spirv::{Op, StorageClass, Word};
use std::collections::HashMap;
/// Every `air.*` marker that names a write into memory the dispatch's caller owns, other than the
/// device atomics (see [`declares_a_device_atomic_write`], which has to exclude one operation).
///
/// A store through an `addrspace(1)` pointer is the spelling this used to know, and an AIR that
/// writes only through an INTRINSIC has no such line -- which is how three corpus kernels whose
/// every write is an `air.atomic.global.*` got past the pair of predicates below. Censused over all
/// 14579 local corpus sources by `@air.*` symbol, these are the write-side families that exist:
///
/// - `air.write_texture_{1d,1d_array,2d,2d_array,3d,cube,buffer_1d}` — one prefix covers them all.
/// - `air.write_imageblock_slice_to_texture_2d{,_array}`, 160 sources. NOT covered by the prefix
/// above: the substring is `write_imageblock_slice_to_texture`.
/// - `air.atomic_fetch_max_explicit_texture_2d`, 2 sources — a texture atomic, so an image write.
/// - `air.store.device_coherent` (19) and `air.store.system_coherent.volatile` (4).
/// - `air.atomic.global.{add,store,cmpxchg.weak,max,min,xchg,or,sub,xor,and}`.
///
/// Deliberately left out: `air.atomic.local.*` and `air.store.implicit_imageblock` write memory
/// that dies with the dispatch or the tile, which is what
/// [`module_has_an_observable_effect`] and [`air_declares_an_imageblock_write`] answer for;
/// `air.simdgroup_async_copy_2d` and `air.simdgroup_matrix_8x8_store` take a pointer whose address
/// space the AIR spells out at the call, so the `addrspace(1)` arm already sees the device cases.
const AIR_OBSERVABLE_WRITE_MARKERS: &[&str] = &[
"@air.write_texture",
"@air.write_imageblock_slice_to_texture",
"@air.atomic_fetch_",
"@air.store.device_coherent",
"@air.store.system_coherent",
// The `llvm.*` half of the same contract. `llvm.agx3.*.with.emask.global.*` is the AGX masked
// device store (37 sources; the `.local` sibling is threadgroup and stays out), and LLVM's
// memory intrinsics mangle their DESTINATION address space first, so `p1` is the device one --
// `llvm.memcpy.p0.p1` reads a device buffer into an alloca and must not count.
"@llvm.agx3.store.with.emask.global",
"@llvm.memcpy.p1.",
"@llvm.memset.p1.",
];
/// Whether the AIR plainly writes something a dispatch can observe: a device-write intrinsic, or a
/// store through a device (`addrspace(1)`) pointer.
///
/// Deliberately textual and deliberately generous — it only decides whether the finished module is
/// worth asking about, and [`module_has_an_observable_effect`] is what actually decides.
pub(crate) fn air_declares_an_observable_write(air_ll: &str) -> bool {
air_ll.lines().any(|line| {
let line = line.trim_start();
// A `declare` names a symbol; only a call performs it. AIR declares every intrinsic it
// references and some it no longer calls, so reading the declarations would report a
// module that dropped its last write as one that still has one.
if line.starts_with("declare ") {
return false;
}
if line.starts_with("store ") && line.contains("ptr addrspace(1)") {
return true;
}
AIR_OBSERVABLE_WRITE_MARKERS
.iter()
.any(|marker| line.contains(marker))
|| calls_a_device_atomic_write(line)
})
}
/// Whether the line performs a device atomic that leaves a new value behind.
///
/// `air.atomic.global.load` does not, and the prefix alone would count a kernel that only reads a
/// device counter as one that writes — refusing a shader that really is a no-op in Metal too. This
/// is the same distinction [`is_atomic_read_modify_write`] draws on the emitted side.
fn calls_a_device_atomic_write(line: &str) -> bool {
const MARKER: &str = "@air.atomic.global.";
line.match_indices(MARKER)
.any(|(start, _)| !line[start + MARKER.len()..].starts_with("load"))
}
/// Whether the AIR writes an imageblock cell: a store through the imageblock address space.
///
/// `addrspace(4)` is that space. Measured over all 14579 local corpus sources: 729 stores through
/// it in 143 sources, and every one of those 143 declares an `air.imageblock` entry parameter --
/// no source stores there without one. Textual and generous for the same reason as
/// [`air_declares_an_observable_write`]: it only decides whether the finished module is worth
/// asking about.
///
/// Separate from [`air_declares_an_observable_write`] because a caller observes the two through
/// different machinery. A device store lands in memory the dispatch's caller already owns; an
/// imageblock cell is tile memory that Metal's render pass RESOLVES into its attachments when the
/// tile completes, and there is no such step to lower.
pub(crate) fn air_declares_an_imageblock_write(air_ll: &str) -> bool {
air_ll.lines().any(|line| {
let line = line.trim_start();
if line.starts_with("declare ") {
return false;
}
(line.starts_with("store ") && line.contains("ptr addrspace(4)"))
// LLVM's memory intrinsics mangle their destination address space first.
|| line.contains("@llvm.memcpy.p4.")
|| line.contains("@llvm.memset.p4.")
})
}
/// Whether the module contains any instruction that can affect memory the DISPATCH'S CALLER can
/// observe -- which is the question [`air_declares_an_observable_write`] asked, so it is the
/// question this has to answer.
///
/// Every opcode that writes through a pointer answers to one rule: the write counts unless the
/// pointer's storage class dies with the dispatch. `Function` and `Private` are per-invocation and
/// `Workgroup` is per-threadgroup. Staging a value in an alloca or in threadgroup memory is how
/// ordinary code gets work done, so counting either would report an emptied module as live -- and a
/// folded shader that keeps its threadgroup scratch and loses every buffer write is exactly the
/// shape that happens: 17 corpus sources reached here with no store outside those three classes,
/// and the largest of them writes 157 textures in its AIR.
///
/// The rule is one rule deliberately. Applying it to stores and exempting atomics and
/// `OpCopyMemory` is the asymmetry that let those 17 through in the first place: a threadgroup
/// counter is no more visible to a caller than a threadgroup store. No corpus source depends on
/// either arm today -- none has a local-storage atomic or copy as its only surviving effect -- so
/// this costs nothing and closes the same hole in the arms where it has not been dug yet.
///
/// `OpImageWrite` is the exception, and only because it takes an image rather than a pointer: an
/// image operand is a descriptor or a placeholder for one, never `Function`/`Private`/`Workgroup`.
pub(crate) fn module_has_an_observable_effect(module: &Module) -> bool {
let mut pointer_storage: HashMap<Word, StorageClass> = HashMap::new();
for instruction in module.types_global_values.iter() {
if instruction.class.opcode != Op::TypePointer {
continue;
}
if let (Some(id), Some(Operand::StorageClass(storage))) =
(instruction.result_id, instruction.operands.first())
{
pointer_storage.insert(id, *storage);
}
}
let mut value_storage: HashMap<Word, StorageClass> = HashMap::new();
for instruction in module.all_inst_iter() {
if let (Some(id), Some(result_type)) = (instruction.result_id, instruction.result_type) {
if let Some(storage) = pointer_storage.get(&result_type) {
value_storage.insert(id, *storage);
}
}
}
module.all_inst_iter().any(|instruction| {
let opcode = instruction.class.opcode;
if opcode == Op::ImageWrite {
return true;
}
if !matches!(opcode, Op::Store | Op::CopyMemory | Op::AtomicStore)
&& !is_atomic_read_modify_write(opcode)
{
return false;
}
// Every one of those opcodes names the pointer it writes through first (`OpCopyMemory`
// names the TARGET first and the source second, which is the one that matters here).
let Some(Operand::IdRef(pointer)) = instruction.operands.first() else {
// A write whose pointer this cannot read is not evidence that nothing survived.
return true;
};
!matches!(
value_storage.get(pointer),
Some(StorageClass::Function | StorageClass::Private | StorageClass::Workgroup)
)
})
}
// What is left after this check, re-measured over all 14579 corpus sources by disassembling every
// translating module and asking this predicate of it directly. 68 of the 13231 that translate have
// no caller-observable effect, and every one of them is accounted for:
//
// - 42 kernels whose AIR entry is literally `ret void`. They really do nothing; every argument is
// `air.arg_unused`.
// - 20 FRAGMENT entries. A fragment's result is an `Output` variable, not a store, so this
// predicate says "no" about all of them and means nothing by it -- which is why
// `air_declares_an_observable_write` gates the question and no fragment reaches it.
// - 2 `fence_wait` kernels whose only call is `air.atomic.fence`. Nothing to write.
// - the 4 `MatrixMultiplyNNA11_M*` below.
//
// So the four ARE the whole residue now, but they were not when that was first written: the
// AIR-side predicate knew two spellings of a write, and 24 more modules -- 16 imageblock-only tile
// kernels, 3 whose every write was a device atomic, 5 whose every write was
// `llvm.agx3.store.with.emask.global` -- were passing it by never being asked.
//
// Four modules -- `MatrixMultiplyNNA11_M1..M4` -- still translate to something that cannot write.
// They carry no function constants at all, so the arm above never names them; the pair of
// predicates WOULD refuse them if the function-constant precondition in
// `reject_function_constant_erased_effects` were dropped, and that widening was tried and not
// taken. It costs exactly those 4 and moves nothing else in the corpus, but it also refuses every
// stage-MISMATCHED translation whose write cannot bind, which halves the sweep in
// tests/live_module_scope_variables.rs -- 55 fixture/stage pairs and 123 module-scope globals down
// to 31 and 53. Four modules out of 14579 did not look worth that.
//
// What is actually wrong with the four, so the next person does not re-derive it: the entry
// advances two device buffer parameters by a DYNAMIC byte offset and passes the cursors to one of
// eight `internal fastcc` helpers chosen by a runtime switch. `raw_call_arg_id`
// (`native/emitter/body/calls.rs`) declines to propagate the caller's buffer root through a
// parameter whose offset carries dynamic terms and returns `Ok(None)`; the helper parameter then
// stays a Private zero placeholder and every raw store through it lands there. M1 emits 154
// `OpStore`, 132 of which target an `OpCopyObject %_ptr_Private_uint`, and declares one
// StorageBuffer variable for the three buffers its own reflection reports.
//
// Three independent sweeps agree those four are the whole non-function-constant residue: AIR
// device-writes with no StorageBuffer store in the module; reflection reporting `Unused` for a
// buffer an AIR dataflow shows dereferenced; and `OpStore` into a Private pointer placeholder.
//
// A trap in that third sweep, which faked a 121-module class out of an 8-module one: the
// `air.static_init` constructor is INLINED into the entry, so restricting the scan to the entry
// body does not exclude it, and its stores go into module-scope `Private` globals. Tell them apart
// by `OpName` -- the AIR globals the constructor mirrors carry one, the zero variable synthesised
// for a possibly-absent parameter does not.
//
// Turning that `Ok(None)` into an `Err` is NOT the fix: 72 of the 14579 reach that arm and 68 are
// unharmed by the decline. A twenty-line reduction of the shape -- one helper, one dynamic byte
// cursor, one store -- lowers correctly and keeps its `OpStore`, so the trigger is something the
// four have that the reduction does not.
/// The atomic opcodes that leave a new value behind. `OpAtomicLoad` does not, and counting it once
/// cost a whole invented failure class.
fn is_atomic_read_modify_write(opcode: Op) -> bool {
matches!(
opcode,
Op::AtomicExchange
| Op::AtomicCompareExchange
| Op::AtomicCompareExchangeWeak
| Op::AtomicIIncrement
| Op::AtomicIDecrement
| Op::AtomicIAdd
| Op::AtomicISub
| Op::AtomicSMin
| Op::AtomicUMin
| Op::AtomicSMax
| Op::AtomicUMax
| Op::AtomicAnd
| Op::AtomicOr
| Op::AtomicXor
| Op::AtomicFAddEXT
| Op::AtomicFMinEXT
| Op::AtomicFMaxEXT
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_device_store_is_an_observable_write() {
assert!(air_declares_an_observable_write(
" store i32 %v, ptr addrspace(1) %p, align 4\n"
));
assert!(air_declares_an_observable_write(
" tail call void @air.write_texture_2d.v4f32(ptr addrspace(1) %t)\n"
));
}
/// A write spelled only as an intrinsic has no `store ... addrspace(1)` line, and three corpus
/// kernels whose every write is a device atomic reached the emitted-side check with the AIR-side
/// one answering "this module never claimed to write".
#[test]
fn a_device_write_spelled_as_an_intrinsic_is_an_observable_write() {
for call in [
" %r = call i32 @air.atomic.global.add.u.i32(ptr addrspace(1) %p, i32 1)\n",
" call void @air.atomic.global.store.u.i32(ptr addrspace(1) %p, i32 1)\n",
" %r = call i32 @air.atomic.global.max.s.i32(ptr addrspace(1) %p, i32 1)\n",
" call void @air.write_imageblock_slice_to_texture_2d.i16.f16(ptr addrspace(1) %t)\n",
" call void @air.store.device_coherent.i32(ptr addrspace(1) %p, i32 1)\n",
" call void @air.store.system_coherent.volatile.i32(ptr addrspace(1) %p, i32 1)\n",
" %r = call i32 @air.atomic_fetch_max_explicit_texture_2d.u.i32(ptr addrspace(1) %t)\n",
] {
assert!(
air_declares_an_observable_write(call),
"{call} names a write the dispatch's caller owns"
);
}
}
/// The `llvm.*` half of the same contract, and the address-space mangling that decides it.
#[test]
fn an_llvm_intrinsic_write_is_read_from_its_destination_address_space() {
assert!(air_declares_an_observable_write(
" tail call void @llvm.agx3.store.with.emask.global.v4i8(ptr addrspace(1) %p, \
<4 x i8> %v, i16 15, i16 15, i16 1)\n"
));
assert!(air_declares_an_observable_write(
" call void @llvm.memcpy.p1.p0.i64(ptr addrspace(1) %dst, ptr %src, i64 16, i1 false)\n"
));
assert!(air_declares_an_observable_write(
" call void @llvm.memset.p1.i64(ptr addrspace(1) %dst, i8 0, i64 16, i1 false)\n"
));
// Destination first: copying a device buffer INTO an alloca is a read.
assert!(!air_declares_an_observable_write(
" call void @llvm.memcpy.p0.p1.i64(ptr %dst, ptr addrspace(1) %src, i64 16, i1 false)\n"
));
// The threadgroup sibling of the AGX store dies with the dispatch.
assert!(!air_declares_an_observable_write(
" tail call void @llvm.agx3.store.with.emask.local.v4i8(ptr addrspace(3) %p, \
<4 x i8> %v, i16 15, i16 15, i16 1)\n"
));
// And an imageblock destination is the other predicate's question.
assert!(!air_declares_an_observable_write(
" call void @llvm.memset.p4.i64(ptr addrspace(4) %dst, i8 0, i64 8, i1 false)\n"
));
assert!(air_declares_an_imageblock_write(
" call void @llvm.memset.p4.i64(ptr addrspace(4) %dst, i8 0, i64 8, i1 false)\n"
));
}
/// The one device atomic that leaves no value behind. Counting it would refuse a kernel that
/// only reads a device counter -- which really is a no-op in Metal too.
#[test]
fn a_device_atomic_load_is_not_an_observable_write() {
assert!(!air_declares_an_observable_write(
" %r = call i32 @air.atomic.global.load.u.i32(ptr addrspace(1) %p)\n"
));
// ... and it must not mask a real one beside it.
assert!(air_declares_an_observable_write(
" %r = call i32 @air.atomic.global.load.u.i32(ptr addrspace(1) %p)\n \
%s = call i32 @air.atomic.global.add.u.i32(ptr addrspace(1) %p, i32 1)\n"
));
}
/// Threadgroup atomics and implicit-imageblock stores are deliberately not on the list: they
/// write memory that dies with the dispatch or the tile.
#[test]
fn a_local_atomic_is_not_an_observable_write() {
assert!(!air_declares_an_observable_write(
" %r = call i32 @air.atomic.local.add.u.i32(ptr addrspace(3) %p, i32 1)\n"
));
assert!(!air_declares_an_observable_write(
" call void @air.store.implicit_imageblock.v4f16(ptr addrspace(4) %p)\n"
));
}
#[test]
fn an_imageblock_store_is_recognised_by_its_address_space() {
assert!(air_declares_an_imageblock_write(
" store <4 x half> zeroinitializer, ptr addrspace(4) %5, align 8\n"
));
// The imageblock address space is not one of the observable ones, and vice versa: the two
// predicates answer different questions and must not collapse into each other.
assert!(!air_declares_an_observable_write(
" store <4 x half> zeroinitializer, ptr addrspace(4) %5, align 8\n"
));
assert!(!air_declares_an_imageblock_write(
" store i32 %v, ptr addrspace(1) %p, align 4\n"
));
// A load through an imageblock pointer is not a write.
assert!(!air_declares_an_imageblock_write(
" %v = load <4 x half>, ptr addrspace(4) %p, align 8\n"
));
}
#[test]
fn a_threadgroup_or_stack_store_is_not_an_observable_write() {
assert!(!air_declares_an_observable_write(
" store i32 %v, ptr addrspace(3) %p, align 4\n"
));
assert!(!air_declares_an_observable_write(
" store i32 %v, ptr %alloca, align 4\n"
));
// A load through a device pointer is not a write.
assert!(!air_declares_an_observable_write(
" %v = load i32, ptr addrspace(1) %p, align 4\n"
));
}
}
+14
View File
@@ -50,6 +50,11 @@ pub const REGISTRY: &[EnvVar] = &[
default: "unset",
effect: "path to dump a failing retry or corpus-audit SPIR-V module (debug)",
},
EnvVar {
name: "METAL2VULKAN_PHASE_DUMP",
default: "unset",
effect: "path prefix for a per-phase SPIR-V dump of the lowering pipeline (debug)",
},
EnvVar {
name: "METAL2VULKAN_<TOOL>",
default: "PATH search",
@@ -226,6 +231,15 @@ pub fn retry_dump() -> Option<OsString> {
std::env::var_os("METAL2VULKAN_RETRY_DUMP")
}
/// Path prefix for a per-phase SPIR-V dump, the companion of [`pass_contract`].
///
/// `pass_contract` names the phase that broke a contract; this writes the module that phase started
/// from, as `<prefix>-<NN>-<phase>.spv`, so the offending instruction can be read with `spirv-dis`
/// instead of inferred from the verdict string.
pub fn phase_dump() -> Option<OsString> {
std::env::var_os("METAL2VULKAN_PHASE_DUMP")
}
/// Optional path override for an external tool `cmd` (`llvm-dis`, `spirv-val`, …), read from
/// `METAL2VULKAN_<CMD>` (uppercased, `-`→`_`). A dynamic family — one var per tool the pipeline
/// shells out to — documented in `REGISTRY` as a single `METAL2VULKAN_<TOOL>` family row rather than
+9 -3
View File
@@ -71,7 +71,13 @@ pub(crate) fn specialize_air_function_constants<'a>(
)
})?;
output.push_str(result);
output.push_str(" = icmp eq i1 true, true");
// A supplied constant IS defined, so this call becomes an `i1` that is always
// true. Spell that with INTEGER operands: everything downstream models the AIR
// Metal actually emits, and no corpus source compares `i1` values, so
// `int_compare_result_type` refuses `icmp ... i1` outright. Metal's implicit
// function-constant predicate initializer parks this value in a global the entry
// never reads, so nothing folds the comparison away before the emitter sees it.
output.push_str(" = icmp eq i32 0, 0");
if line.ends_with('\n') {
output.push('\n');
}
@@ -249,12 +255,12 @@ define void @init() {
.expect("specialize");
assert!(specialized.contains("constant i8 1, section"));
assert!(specialized.contains("constant <2 x i32> <i32 7, i32 11>, section"));
assert!(specialized.contains("%defined = icmp eq i1 true, true"));
assert!(specialized.contains("%defined = icmp eq i32 0, 0"));
let supplied_zero = specialize_air_function_constants(ll, &[(0, vec![0])])
.expect("specialize a defined false value");
assert!(supplied_zero.contains("constant i8 0, section"));
assert!(supplied_zero.contains("%defined = icmp eq i1 true, true"));
assert!(supplied_zero.contains("%defined = icmp eq i32 0, 0"));
}
#[test]
+31 -20
View File
@@ -53,6 +53,36 @@ pub(crate) fn f32_to_f16_bits(value: f32) -> u16 {
sign | encoded.min(0x7c00) as u16
}
/// The exact `f32` value of a binary16 bit pattern.
///
/// Every finite `half` is exactly representable as an `f32`, so this is a widening with no
/// rounding of its own; the infinities and NaNs widen to their `f32` counterparts.
pub(crate) fn f16_bits_to_f32(bits: u16) -> f32 {
let negative = bits & 0x8000 != 0;
let exponent = ((bits >> 10) & 0x1f) as u32;
let significand = (bits & 0x03ff) as u32;
let magnitude = if exponent == 0 {
// Subnormal: significand * 2^-24, exact in `f32`.
(significand as f32) * (2.0f32).powi(-24)
} else if exponent == 0x1f {
// The all-ones exponent is not a binade. Widening it arithmetically lands on 65536, which
// is a plausible-looking number and the wrong one; and 65536 encodes back to this same
// pattern, so a round-trip test cannot tell the difference.
if significand == 0 {
f32::INFINITY
} else {
f32::from_bits(0x7f80_0000 | (significand << 13))
}
} else {
f32::from_bits(((exponent + 112) << 23) | (significand << 13))
};
if negative {
-magnitude
} else {
magnitude
}
}
/// `value >> shift`, rounded to nearest with ties going to the even result.
fn round_shift_right_ties_even(value: u32, shift: u32) -> u32 {
let truncated = value >> shift;
@@ -63,26 +93,7 @@ fn round_shift_right_ties_even(value: u32, shift: u32) -> u32 {
#[cfg(test)]
mod tests {
use super::f32_to_f16_bits;
/// The exact `f32` value of a binary16 bit pattern. Every finite `half` is exactly
/// representable as an `f32`, so this is a widening with no rounding of its own.
fn f16_bits_to_f32(bits: u16) -> f32 {
let negative = bits & 0x8000 != 0;
let exponent = ((bits >> 10) & 0x1f) as u32;
let significand = (bits & 0x03ff) as u32;
let magnitude = if exponent == 0 {
// Subnormal: significand * 2^-24, exact in `f32`.
(significand as f32) * (2.0f32).powi(-24)
} else {
f32::from_bits(((exponent + 112) << 23) | (significand << 13))
};
if negative {
-magnitude
} else {
magnitude
}
}
use super::{f16_bits_to_f32, f32_to_f16_bits};
/// Every finite `half`, widened and encoded again, must come back unchanged.
///
+44 -18
View File
@@ -102,6 +102,24 @@ pub(super) fn scalar_storage_size(
/// The "Native" rule: tight packing, alignment = element alignment (a vec3 is 12/4 — no vector-size
/// growth). Was `LlModule::type_storage_size_align`.
///
/// **Do not unify this with the Memcpy rule.** It disagrees with `memcpy_size_align` on every type
/// containing a vector — measured over the corpus, 2086 of 14579 sources ask it something the two
/// rules answer differently, e.g. `%struct.ASVCameraUniforms` 500/4 here against 512/16 there. It
/// has exactly two callers, and at BOTH the smaller, less-aligned answer is the CONSERVATIVE one:
///
/// * `raw_buffer::infer_call_connected_raw_buffer_params` compares a caller's and a callee's pointee
/// layouts and forces the raw byte view when they differ. Two structs the Memcpy rule rounds up
/// to the same 128/16 can differ here (96/8 against 120/8) — swapping the rule would DROP the
/// raw forcing on 343 call edges across 30 sources.
/// * `raw_buffer::memcpy_source_implies_raw_bytes` asks whether a `memcpy` length covers the whole
/// object. A smaller size makes "covers it" true more often, which again forces the raw view;
/// swapping the rule would drop it in 3 sources (a 72-byte copy of an object this rule sizes at
/// 68 and the Memcpy rule at 80).
///
/// Both callers only ever DECIDE with the answer, never address with it, so a conservative
/// under-estimate costs typed access chains and nothing else. See `layout_abi_tests` in
/// `native::ir` for the pinned divergence.
pub(super) fn native_size_align(
ty: &LlType,
resolve: &impl Fn(&LlType) -> LlType,
@@ -139,7 +157,8 @@ pub(super) fn native_size_align(
}
/// The "Memcpy" rule: LLVM allocation layout for a `memcpy`, using the source vector ABI alignment
/// (or LLVM's power-of-two default) and aligning arrays to at least four bytes. Was
/// (or LLVM's power-of-two default). An array's alignment is its element's, as in the Native and
/// Raw rules -- the vector arm is the only place this rule diverges from them. Was
/// `LlModule::native_memcpy_type_size_align`.
pub(super) fn memcpy_size_align(
ty: &LlType,
@@ -168,10 +187,7 @@ pub(super) fn memcpy_size_align(
}
LlType::Array(elem, len) => {
let (elem_size, elem_align) = memcpy_size_align(&elem, resolve, data_layout)?;
Some((
round_up_u64(elem_size, elem_align) * len as u64,
elem_align.max(4),
))
Some((round_up_u64(elem_size, elem_align) * len as u64, elem_align))
}
LlType::Struct(fields) => {
let mut offset = 0u64;
@@ -189,8 +205,9 @@ pub(super) fn memcpy_size_align(
}
/// The "Raw" rule (emitter): LLVM allocation sizes using the source vector ABI alignment (or LLVM's
/// power-of-two default), with arrays floored to four-byte alignment. It differs from the optional
/// calculators above in two other ways:
/// power-of-two default). An array's alignment is its element's, which is what decides where the
/// explicit `[N x i8]` pads Metal writes into a packed struct put every member behind them. It
/// differs from the optional calculators above in two other ways:
/// * `resolve` is FALLIBLE — a `Named` type the module can't expand is an error, not a fallthrough.
/// * uncovered types (odd-width ints, `Void`) are an `Err`, not `None` — the Raw rule only accepts
/// the standard scalar widths it knows how to lay out.
@@ -224,7 +241,7 @@ pub(super) fn raw_size_align(
LlType::Array(elem, len) => {
let (elem_size, elem_align) = raw_size_align(&elem, resolve, data_layout)?;
let stride = round_up_u64(elem_size, elem_align);
Ok((stride * len as u64, elem_align.max(4)))
Ok((stride * len as u64, elem_align))
}
LlType::Struct(fields) => {
let mut off = 0;
@@ -270,14 +287,15 @@ pub(super) fn air_metadata_size_align(
///
/// This is the quantity comparable to `air.arg_type_size`, which is the argument's `sizeof` and so
/// always at least as large. [`air_metadata_size_align`] answers a different question -- the stride
/// a pointee type needs -- and rounds accordingly, which makes it unusable as a bound: over 2880
/// corpus sources it exceeds the declared argument size for 96 buffers whose layout is correct.
/// a pointee type needs -- and rounds to the aggregate's alignment, which makes it unusable as a
/// bound: over the 14579 corpus sources it still exceeds the declared argument size for 2 buffers
/// whose layout is correct. (It was 462 while arrays were floored to four-byte alignment.)
///
/// An array strides by its element's *declared* size, not a recomputed one, because that is what
/// AIR states: a member tuple carries the per-element size beside the array length, and the
/// corpus bears it out exactly (`i32 8192, i32 2, i32 4096, !"half"` -- 4096 halves at stride two
/// starting where the previous 4096 ended). Recomputing it inflates a `packed_half3` element from
/// six bytes to eight, since [`memcpy_size_align`] floors array alignment at four.
/// starting where the previous 4096 ended). Recomputing it would re-derive a stride AIR already
/// spelled out, and AIR's is the ABI.
///
/// Overlap is normal here and needs no special case: AIR describes unions by giving two members
/// the same offset, so the reach is a maximum rather than a sum.
@@ -398,7 +416,14 @@ pub(crate) fn spirv_size_align(
Op::TypeStruct => {
let mut cursor = 0u32;
let mut end = 0u32;
let mut max_align = 4u32;
// No alignment floor. A struct's alignment is the largest alignment among its members
// and nothing more -- `{ short a[5]; uchar b[7]; }` is 17 bytes of members aligned to 2,
// so it is 18 bytes, and Metal says so in `air.arg_type_size` and in its own `sizeof`.
// Starting this at 4 made it 20, and that number became the buffer's `ArrayStride`, so
// every element but the zeroth was addressed two bytes per record too far along. The
// same floor was in `raw_size_align` (removed by `9993cca8`) and in `memcpy_size_align`
// (removed by `1c2d724d`); this was the third copy of one rule.
let mut max_align = 1u32;
let explicit_offsets = rule.struct_offsets(ty);
for (index, operand) in def.operands.iter().enumerate() {
let Operand::IdRef(member) = operand else {
@@ -478,14 +503,15 @@ pub(crate) fn round_up_u32(value: u32, align: u32) -> u32 {
mod tests {
use super::*;
/// The two rules `air_metadata_extent` states that `air_metadata_size_align` does not: an array
/// strides by its element's tight size, and overlapping members reach rather than accumulate.
/// The rule `air_metadata_extent` states that `air_metadata_size_align` does not: overlapping
/// members reach rather than accumulate. Array stride is no longer a divergence -- both take
/// the element's own alignment.
#[test]
fn air_metadata_extent_strides_arrays_tightly_and_takes_the_furthest_reach() {
use crate::meta::{AirMember, AirScalar};
// `packed_half3[3]` is 18 bytes. The stride rule that floors array alignment at four --
// what `air_metadata_size_align` applies -- would report 24 and put the argument over.
// `packed_half3[3]` is 18 bytes, and both rules say so. Flooring array alignment at four
// reported 24 and put the argument over its own declared size.
let packed = AirType::Array {
elem: Box::new(AirType::PackedVec {
scalar: AirScalar::Half,
@@ -496,7 +522,7 @@ mod tests {
assert_eq!(air_metadata_extent(&packed), Some(18));
assert_eq!(
air_metadata_size_align(&packed, &|ty| ty.clone(), None),
Some((24, 4)),
Some((18, 2)),
);
// AIR spells a union by giving two members one offset. The struct reaches as far as its
+193 -24
View File
@@ -20,8 +20,10 @@ pub mod air_intrinsics;
pub(crate) mod air_static_init;
pub mod as_shadow;
mod construction;
mod dominators;
mod emission_order;
mod emit_sidecar;
mod emitted_effects;
pub mod env_vars;
mod fc_air_specialize;
mod fc_specialize;
@@ -109,10 +111,10 @@ pub fn translate_sanitized_native(
/// Apply the shared pre-emit AIR lowering before any representation derives stage metadata or emits
/// from the module. Alternate constructions re-emit the supplied text directly, so using the
/// original intrinsic-bearing text would make the representations observe different programs.
/// Floor-safe: `lower_simdgroup_async_copy` is a no-op unless the module calls
/// `air.simdgroup_async_copy_2d` (such modules fail the emitter outright otherwise).
fn lower_async_copy_if_enabled(san_ll: &str) -> Cow<'_, str> {
native::lower_simdgroup_async_copy(san_ll)
/// Floor-safe: each member is a no-op unless the module names what it lowers, and both shapes are
/// ones the emitter otherwise mistranslates or rejects outright.
fn lower_air_text_if_enabled(san_ll: &str) -> Cow<'_, str> {
native::lower_air_text(san_ll)
}
fn reject_unsupported_metal_linked_functions(san_ll: &str) -> Result<(), String> {
@@ -127,6 +129,79 @@ fn reject_unsupported_metal_linked_functions(san_ll: &str) -> Result<(), String>
Ok(())
}
/// Refuse a module whose every observable write was removed by folding a function constant the
/// caller supplied no value for.
///
/// AIR states no default for a `[[function_constant]]`: its `air.fc_initializer` global is
/// `externally_initialized … undef`, and `meta::globals` reads that as zero so an off-by-default
/// region folds away before it can hold something Logical SPIR-V cannot express. That folding is
/// load-bearing and stays — disabling it costs 106 of the 14579 local corpus sources and still
/// leaves 53 of the 55 modules this check names with no image write. But the zero it reads is a
/// value AIR never gave, and when it is what removed every last write, the module we would hand a
/// caller cannot write the texture its AIR writes. Refuse instead of reporting success: 55 sources,
/// 28 of which regain an image write as soon as any value is substituted for their constants.
///
/// Values supplied through [`fc_air_specialize::specialize_air_function_constants`] rewrite the
/// initializer they are given, so a specialized module has nothing left for this to fire on and a
/// caller who asked for the empty variant still gets it.
fn reject_function_constant_erased_effects(san_ll: &str, module: &Module) -> Result<(), String> {
if !emitted_effects::air_declares_an_observable_write(san_ll) {
return Ok(());
}
if emitted_effects::module_has_an_observable_effect(module) {
return Ok(());
}
let unsupplied = meta::function_constants_without_a_supplied_value(san_ll);
if unsupplied.is_empty() {
return Ok(());
}
let named = unsupplied
.iter()
.take(4)
.map(|constant| format!("{} (index {})", constant.name, constant.index))
.collect::<Vec<_>>()
.join(", ");
Err(format!(
"the entry writes a texture or a device buffer, but no write survived folding {} function \
constant(s) the caller supplied no value for -- {named}. AIR declares no default for a \
function constant, so the zero folded in its place is a value the shader never asked for; \
emitting the module would silently do nothing where Metal writes",
unsupplied.len(),
))
}
/// Refuse a module whose every write went into an imageblock this translator has no tile model for.
///
/// A Metal imageblock is threadgroup tile memory that the render pass resolves into its attachments
/// when the tile completes. Vulkan has no resolve step and this translator has no attachment to
/// resolve into, so `native::emitter::body::calls` stages imageblock cells in per-invocation
/// `Private` (or per-threadgroup `Workgroup`) memory. 143 of the 14579 local corpus sources store
/// into an imageblock; 66 of them go on to write a texture or a device buffer, and for those this
/// says nothing. For 16 the staging array IS the program -- Metal's tile CLEAR kernels and the
/// `xdr::*_block` converters -- and the module validates, reflects no resource at all, and a
/// consumer that dispatches it clears nothing. (The remaining 61 are refused for other reasons.)
///
/// Stated on its own cause rather than folded into
/// [`reject_function_constant_erased_effects`]: that one names function-constant folding as the
/// thing that removed the writes, and needs an unsupplied constant to be honest about it. Ten of
/// these sixteen declare no function constant at all, and for the other six the constants are not
/// what emptied the module.
fn reject_imageblock_only_effects(san_ll: &str, module: &Module) -> Result<(), String> {
if !emitted_effects::air_declares_an_imageblock_write(san_ll) {
return Ok(());
}
if emitted_effects::module_has_an_observable_effect(module) {
return Ok(());
}
Err(
"the entry's only write is into an imageblock, which this translator stages in \
per-invocation or per-threadgroup memory because Vulkan has no tile-resolve step; \
emitting the module would hand a caller a dispatch that writes nothing where Metal \
resolves the tile into its attachments"
.to_string(),
)
}
fn options_for_air(
san_ll: &str,
mut options: passes::TransformOptions,
@@ -143,12 +218,6 @@ fn options_for_air(
if san_ll.contains("air.compile.denorms_disable") {
options.denorm_flush_to_zero_f32 = true;
}
// AIR's simdgroup ABI is 32 lanes. Vulkan implementations may expose wider native subgroups
// (MoltenVK commonly exposes 64), so subgroup reductions/scans must retain 32-lane partitions
// instead of silently adopting the driver's width.
if san_ll.contains("@air.simd_") {
options.simd_cluster32 = true;
}
Ok(options)
}
@@ -395,6 +464,32 @@ pub fn translate_sanitized_native_specialized_with_options(
)
}
/// [`translate_sanitized_native_specialized_with_options`] plus the reflection facade.
///
/// A caller that binds the resulting module needs the reflection OF that module, not one built from
/// the AIR alone: [`reflect_sanitized`] constructs no module, so the facts only the finished module
/// can answer -- the image type behind a texture binding, the address table, synthesized
/// placeholder descriptors -- stay at their AIR-text approximation there. See
/// [`translate_reflected`].
pub fn translate_sanitized_native_specialized_reflected_with_options(
san_ll: &str,
stage: passes::Stage,
tmp: &Path,
options: passes::TransformOptions,
function_constants: &[(u32, Vec<u8>)],
) -> Result<(Vec<u8>, reflect::ShaderReflection), String> {
let datalayout = layout::AirDataLayout::from_ir(san_ll)?;
let specialized =
fc_air_specialize::specialize_air_function_constants(san_ll, function_constants)?;
translate_sanitized_native_reflected_with_layout(
specialized.as_ref(),
stage,
tmp,
options,
datalayout,
)
}
/// Translate an owned sanitized AIR module while allowing superseded preprocessing input to be
/// released before typed parsing. This is byte- and error-equivalent to
/// [`translate_sanitized_native_with_options`], but lowers peak memory for large modules that need a
@@ -406,7 +501,7 @@ pub fn translate_sanitized_native_owned_with_options(
options: passes::TransformOptions,
) -> Result<Vec<u8>, String> {
let datalayout = layout::AirDataLayout::from_ir(&san_ll)?;
let lowered = native::lower_simdgroup_async_copy_owned(san_ll);
let lowered = native::lower_air_text_owned(san_ll);
translate_sanitized_native_pre_lowered_with_layout(&lowered, stage, tmp, options, datalayout)
}
@@ -417,14 +512,15 @@ fn translate_sanitized_native_with_options_and_layout(
options: passes::TransformOptions,
datalayout: Option<layout::AirDataLayout>,
) -> Result<Vec<u8>, String> {
// Lower `air.simdgroup_async_copy_2d` (+ its event/wait pair) to an explicit strided tile copy
// before metadata parsing or emission, so the primary and alternate representations see the
// same ordinary LLVM. The rewrite is a no-op unless the module calls the intrinsic, which the
// emitter otherwise rejects. See `native::async_copy` and its structural regression tests.
// Lower `air.simdgroup_async_copy_2d` (+ its event/wait pair) to an explicit strided tile copy,
// and a dynamic-length `llvm.memcpy` to a byte loop, before metadata parsing or emission, so the
// primary and alternate representations see the same ordinary LLVM. Each rewrite is a no-op
// unless the module contains what it lowers. See `native::async_copy` and
// `native::dynamic_memcpy` and their structural regression tests.
if env_vars::retry_debug() {
eprintln!("[retry-debug] translate: AIR pre-lowering start");
}
let lowered = lower_async_copy_if_enabled(san_ll);
let lowered = lower_air_text_if_enabled(san_ll);
let san_ll = lowered.as_ref();
if env_vars::retry_debug() {
eprintln!("[retry-debug] translate: AIR pre-lowering complete");
@@ -527,6 +623,27 @@ pub fn translate_sanitized_native_linked_specialized_with_options(
)
}
/// [`translate_sanitized_native_linked_specialized_with_options`] plus the reflection facade. See
/// [`translate_sanitized_native_specialized_reflected_with_options`] for why a caller that binds the
/// module wants this reflection rather than [`reflect_sanitized_specialized`]'s.
pub fn translate_sanitized_native_linked_specialized_reflected_with_options(
san_ll: &str,
stage: passes::Stage,
tmp: &Path,
options: passes::TransformOptions,
linkage: &linked_functions::LinkedFunctionLinkage,
function_constants: &[(u32, Vec<u8>)],
) -> Result<(Vec<u8>, reflect::ShaderReflection), String> {
let specialized = specialize_linked_module(san_ll, stage, linkage)?;
translate_sanitized_native_specialized_reflected_with_options(
&specialized,
stage,
tmp,
options,
function_constants,
)
}
/// Like [`translate`] but also returns the [`reflect::ShaderReflection`] needed to integrate the
/// resulting module.
///
@@ -596,7 +713,7 @@ pub fn reflect_sanitized(
stage: passes::Stage,
options: passes::TransformOptions,
) -> Result<reflect::ShaderReflection, String> {
let lowered = lower_async_copy_if_enabled(san_ll);
let lowered = lower_air_text_if_enabled(san_ll);
let san_ll = lowered.as_ref();
let stage_meta = parse_stage_meta(san_ll, stage);
let options = options_for_air(san_ll, options)?;
@@ -660,7 +777,7 @@ fn translate_sanitized_native_reflected_with_layout(
options: passes::TransformOptions,
datalayout: Option<layout::AirDataLayout>,
) -> Result<(Vec<u8>, reflect::ShaderReflection), String> {
let lowered = lower_async_copy_if_enabled(san_ll);
let lowered = lower_air_text_if_enabled(san_ll);
let san_ll = lowered.as_ref();
reject_unsupported_metal_linked_functions(san_ll)?;
let stage_meta = parse_stage_meta(san_ll, stage);
@@ -718,7 +835,7 @@ fn translate_sanitized_native_reflected_with_layout(
pub fn translate_native_no_retry(san_ll: &str, stage: passes::Stage) -> Result<Vec<u8>, String> {
// Mirror the pre-spirv-val prologue of `translate_sanitized_native_with_options` exactly so BC
// measures the bytes production would actually validate: async-copy lowering, then stage meta.
let lowered = lower_async_copy_if_enabled(san_ll);
let lowered = lower_air_text_if_enabled(san_ll);
reject_unsupported_metal_linked_functions(&lowered)?;
let stage_meta = parse_stage_meta(&lowered, stage);
translate_native_no_retry_with_meta(
@@ -801,7 +918,7 @@ pub fn translate_native_primary_validated(
stage: passes::Stage,
tmp: &Path,
) -> Result<Vec<u8>, String> {
let lowered = lower_async_copy_if_enabled(san_ll);
let lowered = lower_air_text_if_enabled(san_ll);
let san_ll = lowered.as_ref();
reject_unsupported_metal_linked_functions(san_ll)?;
let stage_meta = parse_stage_meta(san_ll, stage);
@@ -1036,6 +1153,21 @@ fn finish_module(
// intermediate module.
passes::canonicalize_ids(&mut out);
}
// CFG construction can delete the only instruction that needed a capability -- an
// `OpDemoteToHelperInvocation` in a block the structurizer proves unreachable is the measured
// case. Every earlier cleanup ran on a module that still had it, so the capability survives a
// liveness snapshot taken before this boundary; this is the first point at which the module is
// the one that ships. See `drop_unrequired_capabilities`.
passes::drop_unreferenced_scalar_types(&mut out);
passes::drop_unused_scalar_width_capabilities(&mut out);
passes::drop_unrequired_capabilities(&mut out);
// Vulkan reads an undecorated storage buffer as a demand: a graphics-stage module that declares
// one requires `fragmentStoresAndAtomics` / `vertexPipelineStoresAndAtomics` from every consumer
// whether or not a store exists. State the buffers this module provably never writes. This runs
// last because the answer is about the module that ships -- every instruction-deleting step
// above can remove the only store through a descriptor, and a decoration attached before them
// would describe a module that no longer exists.
reflect::decorate_unwritten_descriptors(&mut out);
if let Some(failure) = native::owned_module_failure(&out) {
if let Some(path) = env_vars::retry_dump() {
let _ = std::fs::write(path, assemble_finished_module(&out));
@@ -1067,7 +1199,7 @@ pub fn translate_raw_tiers_probe(
stage: passes::Stage,
tmp: &Path,
) -> Vec<Result<Vec<u8>, String>> {
let lowered = lower_async_copy_if_enabled(san_ll);
let lowered = lower_air_text_if_enabled(san_ll);
let san_ll = lowered.as_ref();
if let Err(error) = reject_unsupported_metal_linked_functions(san_ll) {
return vec![Err(error.clone()), Err(error)];
@@ -1139,7 +1271,7 @@ pub fn translate_bda_probe(
stage: passes::Stage,
tmp: &Path,
) -> Result<Vec<u8>, String> {
let lowered = lower_async_copy_if_enabled(san_ll);
let lowered = lower_air_text_if_enabled(san_ll);
let san_ll = lowered.as_ref();
reject_unsupported_metal_linked_functions(san_ll)?;
let stage_meta = parse_stage_meta(san_ll, stage);
@@ -1235,8 +1367,8 @@ fn translate_sanitized_with_meta_prevalidated_carrier(
rc.finish_primary_carrier(emitted)
}
Err(failure) => {
rc.remember_ordinary_plan_rejection_set(&failure.ordinary_plan_rejected_functions);
rc.remember_ownership_plan_rejection_set(&failure.ownership_plan_rejected_functions);
rc.remember_ordinary_plan_rejection_set(&failure.rejected.ordinary_plan_functions);
rc.remember_ownership_plan_rejection_set(&failure.rejected.ownership_plan_functions);
Err(failure.error)
}
};
@@ -1261,6 +1393,8 @@ fn translate_sanitized_with_meta_prevalidated_carrier(
let _ = std::fs::write(path, &constructed.bytes);
}
tools::spirv_val_bytes(&constructed.bytes, tmp)?;
reject_function_constant_erased_effects(san_ll, &constructed.module)?;
reject_imageblock_only_effects(san_ll, &constructed.module)?;
if retry_debug_on {
eprintln!("[retry-debug] constructed module validated in-translate");
}
@@ -1293,6 +1427,41 @@ pub fn canonicalize_spirv_bytes(spv: &[u8]) -> Result<Vec<u8>, String> {
.collect())
}
pub use passes::loop_budget::{LoopBudgetReport, DEFAULT_LOOP_BUDGET};
/// Bound every loop in an emitted SPIR-V byte stream to `budget` iterations per entry.
///
/// A committed GPU command buffer cannot be cancelled, so an unbounded loop in translated SPIR-V
/// pins the GPU until reboot and, on macOS, starves WindowServer into a watchdog kill. Callers that
/// dispatch translated modules to a real device must run this first; the returned report says
/// whether the module had loops at all, so a budget-exceeded run can be reported as such rather
/// than mistaken for a byte mismatch.
pub fn instrument_spirv_loop_budget(
spv: &[u8],
budget: u32,
) -> Result<(Vec<u8>, LoopBudgetReport), String> {
let mut module = load_owned_module(spv).map_err(|e| format!("SPIR-V load: {e:?}"))?;
let report = passes::loop_budget::instrument_loop_budget(&mut module, budget);
let bytes: Vec<u8> = module
.assemble()
.iter()
.flat_map(|w| w.to_le_bytes())
.collect();
// Reusing a loop's own exit edge cannot disturb the CFG, so only the guard-block fallback needs
// checking. Validating here rather than at the call site means no caller can dispatch a module
// this pass broke: an invalid module becomes a failed case, never a wedged GPU.
if report.needs_revalidation() {
tools::spirv_val_bytes(&bytes, &std::env::temp_dir()).map_err(|error| {
format!(
"loop budget rewrote {} loop header(s) to return on exhaustion and the result does \
not validate, so the module is not safe to dispatch: {error}",
report.loops_bounded_via_early_return
)
})?;
}
Ok((bytes, report))
}
/// Disassemble SPIR-V bytes to spvasm text (for golden fixtures / debugging).
pub fn disassemble(spv: &[u8]) -> Result<String, String> {
let m = load_owned_module(spv).map_err(|e| format!("SPIR-V load: {e:?}"))?;
+29 -10
View File
@@ -38,8 +38,8 @@ fn main() {
// --stage vertex" mis-mappings when translating captured guest AIR.
let mut stage = "auto".to_string();
let mut emit_meta: Option<String> = None;
let mut simd_cluster32 = false;
let mut raster_sample_count = None;
let mut vertex_amplification_count = 1;
let mut kernel_local_size = [64, 1, 1];
let mut kernel_dispatch = None;
let mut translation_options = Vec::new();
@@ -58,10 +58,10 @@ options:
shader stage (default: auto from AIR metadata; compute aliases kernel)
--emit-meta out.json
write ShaderReflection JSON (requires the serde feature; not passthrough)
--simd-cluster32
request 32-lane clustered subgroup reductions
--raster-samples 1|2|4|8|16|32|64
exact graphics-pipeline sample count for AIR sample-count queries
--vertex-amplification-count N
vertex amplification count the render pass encodes (default: 1, Metal's own default)
--local X,Y,Z
nominal Metal kernel threadgroup size (default: 64,1,1)
--threads-per-grid X,Y,Z
@@ -87,12 +87,6 @@ options:
emit_meta = args.get(i + 1).cloned();
i += 2;
}
// M-D2: cluster simd reductions to Metal's 32-lane simdgroup (see TransformOptions).
"--simd-cluster32" => {
simd_cluster32 = true;
translation_options.push("--simd-cluster32".to_string());
i += 1;
}
"--raster-samples" => {
raster_sample_count = args.get(i + 1).and_then(|value| value.parse().ok());
if !matches!(raster_sample_count, Some(1 | 2 | 4 | 8 | 16 | 32 | 64)) {
@@ -101,6 +95,17 @@ options:
translation_options.extend(["--raster-samples".to_string(), args[i + 1].clone()]);
i += 2;
}
"--vertex-amplification-count" => {
match args.get(i + 1).and_then(|value| value.parse::<u32>().ok()) {
Some(count) if count >= 1 => vertex_amplification_count = count,
_ => fail("--vertex-amplification-count requires a count of 1 or more"),
}
translation_options.extend([
"--vertex-amplification-count".to_string(),
args[i + 1].clone(),
]);
i += 2;
}
"--local" => {
kernel_local_size = args
.get(i + 1)
@@ -155,6 +160,20 @@ options:
"--entry" => {
i += 2;
}
// A leading dash is always a flag here, and an unknown one is a mistake rather than a
// path. Falling through to the positional list made `-o out.spv` write a file named
// `-o` in the working directory and silently never write `out.spv` -- the tool even
// printed "wrote -o". A misspelled `--stag vertex` failed the same way. There are
// exactly two positionals and neither can begin with a dash.
other if other.starts_with('-') && other.len() > 1 => {
fail(&format!(
concat!(
"unrecognized option `{}`; the input and output are positional ",
"(`metal2vulkan <in.air|.ll> <out.spv>`), and --help lists every option"
),
other
));
}
_ => {
pos.push(args[i].clone());
i += 1;
@@ -187,8 +206,8 @@ options:
let options = TransformOptions {
kernel_local_size,
kernel_dispatch,
simd_cluster32,
raster_sample_count,
vertex_amplification_count,
..TransformOptions::default()
};
let want_meta = emit_meta.is_some();
+601 -96
View File
@@ -1,9 +1,40 @@
use super::types::{struct_member_starts_at, tokenize, Tok};
use super::types::{member_tuples, tokenize};
use super::{arg_type_name, role_strings, texture_shape_from_name, BufferAccess, TextureFormat};
use crate::passes::ImageComp;
use spirv::Dim;
use std::collections::HashMap;
/// The `air.indirect_buffer` arguments of one entry, in the order the synthetic embedded-texture
/// index counts them: `(parameter index, Metal `[[buffer(N)]]` slot, `air.struct_type_info` node)`
/// per argument buffer, ordered by PARAMETER INDEX.
///
/// The order is part of an ABI, not a detail. [`embedded_synthetic_texture_index`] fixes where the
/// synthetic indices start and [`detect_embedded_textures`] hands out `K`, `K+1`, ... by walking
/// this list, so a consumer that binds by synthetic index has to reach the same order the
/// translator did. Walking the AIR metadata list in the order it happens to name its argument
/// nodes made that order a property of the metadata layout: reversing the list of one corpus kernel
/// moves the same embedded texture from `Binding 32` to `Binding 480` and from Sampled to Storage.
///
/// Ordered by PARAMETER index rather than by Metal buffer index, because the latter is not a total
/// order -- mutually exclusive function-constant alternatives share one `[[buffer(N)]]` -- while an
/// entry's parameter index is unique by construction.
///
/// The type exists so the order cannot be skipped: the walkers below take this and nothing else,
/// and [`ArgumentBuffers::new`] is the only way to make one.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(super) struct ArgumentBuffers(Vec<(u32, u32, u32)>);
impl ArgumentBuffers {
pub(super) fn new(mut declared: Vec<(u32, u32, u32)>) -> Self {
declared.sort_by_key(|(param_index, _, _)| *param_index);
Self(declared)
}
fn iter(&self) -> impl Iterator<Item = (u32, u32, u32)> + '_ {
self.0.iter().copied()
}
}
/// A texture that lives inside an `air.indirect_buffer` argument buffer, marked
/// `air.indirect_argument` → `air.texture` in the buffer's `air.struct_type_info`, and used by the
/// shader body through an AIR texture intrinsic.
@@ -83,42 +114,30 @@ pub(super) fn body_uses_texture_intrinsic(ll: &str) -> bool {
/// `air.indirect_argument` whose nested node is an `air.texture`. Each such texture is
/// surfaced as an `EmbeddedTexture` with a synthetic index K, K+1, … (K from
/// [`embedded_synthetic_texture_index`]) so the translator and harness agree on the binding without
/// a name key. Plain 2D and 2D-array float/int textures share this structural contract.
/// a name key. Every texture shape [`texture_shape_from_name`] reads shares this contract; see
/// [`expressible_embedded_texture`] for what is left out.
pub(super) fn detect_embedded_textures(
nodes: &HashMap<u32, String>,
indirect_buffer_struct_refs: &[(u32, u32, u32)],
argument_buffers: &ArgumentBuffers,
top_level_texture_locations: &[u32],
) -> Vec<EmbeddedTexture> {
let mut out = vec![];
let mut next_k = embedded_synthetic_texture_index(top_level_texture_locations);
for &(buffer_param_index, buffer_index, sref) in indirect_buffer_struct_refs {
for (field_ordinal, field_offset, tex_node_ref) in embedded_argument_members(nodes, sref) {
let Some(tex_node) = nodes.get(&tex_node_ref) else {
for (buffer_param_index, buffer_index, sref) in argument_buffers.iter() {
for member in embedded_argument_members(nodes, sref) {
let Some(tex_node) = nodes.get(&member.node_ref) else {
continue;
};
let strs = role_strings(tex_node);
// Structural gate: the nested node must be an `air.texture` with an access class the
// read/write lowerings can express.
if !strs.iter().any(|s| s == "texture")
|| !strs
.iter()
.any(|s| matches!(s.as_str(), "sample" | "read" | "write" | "read_write"))
{
let Some(shape) = expressible_embedded_texture(&member, tex_node) else {
continue;
}
let name = arg_type_name(tex_node).unwrap_or_default();
let shape = texture_shape_from_name(&name);
let dim = shape.dimension.to_spirv_dim();
if dim != Dim::Dim2D {
continue;
}
};
out.push(EmbeddedTexture {
buffer_param_index,
buffer_index,
field_offset,
field_ordinal,
argument_index: super::location_index(tex_node, field_ordinal),
dim,
field_offset: member.field_offset,
field_ordinal: member.field_ordinal,
argument_index: member.argument_index(tex_node),
dim: shape.dimension.to_spirv_dim(),
arrayed: shape.arrayed,
comp: shape.component.to_image_comp(),
storage_format: shape.storage_format,
@@ -131,93 +150,315 @@ pub(super) fn detect_embedded_textures(
out
}
/// The texture shape of an `air.indirect_argument` member the embedded lowering can materialize a
/// descriptor for, or `None` for any other member.
///
/// One predicate, so [`detect_embedded_textures`] and [`unsurfaced_embedded_resources`] cannot
/// disagree about which handles are surfaced: whatever this refuses stays a refusal reason.
///
/// The shape is derived by [`texture_shape_from_name`], the same reading the top-level texture
/// arguments get, and every dimension it names is materialized -- `register_embedded_textures`
/// builds the image from `dim`/`arrayed`/`comp` without caring which. An earlier 2D-only gate here
/// silently dropped the embedded `texturecube`, `texturecube_array`, `texture1d` and `texture3d`
/// members of 97 corpus sources; 10 of those reached a sample and answered black.
fn expressible_embedded_texture(
member: &ArgumentMember,
node: &str,
) -> Option<super::TextureShape> {
// A wrapper declared as an ARRAY of structs repeats its members once per element, at offsets
// and argument ids this walk does not enumerate. Surfacing element 0 alone would bind one
// descriptor and leave the rest reading black.
if member.in_array_wrapper {
return None;
}
let strs = role_strings(node);
// Structural gate: the node must be an `air.texture` with an access class the read/write
// lowerings can express.
if !strs.iter().any(|s| s == "texture")
|| !strs
.iter()
.any(|s| matches!(s.as_str(), "sample" | "read" | "write" | "read_write"))
{
return None;
}
let mut shape = texture_shape_from_name(&arg_type_name(node).unwrap_or_default());
// A descriptor-array member has TWO spellings and only one of them is in the type name.
// `metal::array<texture2d<half, sample>, 2>` names the array, and `texture_shape_from_name`
// reads the length out of it. A C array -- `texture2d<float, sample> slices[32]` -- names the
// ELEMENT type, and states the length only in the member tuple's `array_len` slot; the node's
// own `air.location_index` count operand stays `1` for it, unlike the top-level spelling
// (see the corpus fact that count and `array<..., N>` always agree -- that holds outside an
// argument buffer, not inside one). Reading the name alone surfaced one descriptor and let a
// runtime index sample element 0 for every value of the index.
if shape.array_length.is_none() && member.array_len != 0 {
shape.array_ref = true;
shape.array_length = Some(member.array_len);
}
Some(shape)
}
pub(super) fn detect_embedded_arguments(
nodes: &HashMap<u32, String>,
indirect_buffer_struct_refs: &[(u32, u32, u32)],
argument_buffers: &ArgumentBuffers,
) -> Vec<EmbeddedArgument> {
indirect_buffer_struct_refs
argument_buffers
.iter()
.flat_map(|&(buffer_param_index, buffer_index, sref)| {
.flat_map(|(buffer_param_index, buffer_index, sref)| {
embedded_argument_members(nodes, sref)
.into_iter()
.filter_map(move |(field_ordinal, field_offset, node_ref)| {
let node = nodes.get(&node_ref)?;
let is_buffer = role_strings(node).iter().any(|role| role == "buffer");
Some(EmbeddedArgument {
buffer_param_index,
buffer_index,
field_ordinal,
field_offset,
argument_index: super::location_index(node, field_ordinal),
resource_buffer_index: is_buffer
.then(|| super::location_index(node, field_ordinal)),
resource_address_space: is_buffer
.then(|| super::address_space(node))
.flatten(),
resource_declared_size: is_buffer
.then(|| super::i32_after_marker(node, "air.arg_type_size"))
.flatten(),
resource_access: is_buffer
.then(|| super::declared_buffer_access(node))
.flatten(),
// Flat members only. A wrapped `air.buffer` is a device address a consumer has to
// write into the owning argument buffer, and nothing binds one yet, so it stays a
// refusal reason in `unsurfaced_embedded_resources` rather than a silent descriptor.
.filter(|member| member.depth == 0)
.flat_map(move |member| {
let node = nodes.get(&member.node_ref);
let is_buffer = node
.is_some_and(|node| role_strings(node).iter().any(|role| role == "buffer"));
// A C-array member -- `device half4* bufs[2]` -- declares ONE handle per
// element, at consecutive argument ids and consecutive 8-byte slots, and states
// its length only in the member tuple. A consumer given the first element alone
// leaves every later slot of the argument buffer unwritten, so a runtime index
// into the member reads a device address nothing ever populated. Only the
// handle roles repeat this way: `air.indirect_constant` is stored INLINE, so its
// array is one span of data rather than N resources.
let elements = match node {
// A texture array is already counted ONCE, by
// `EmbeddedTexture::array_length`, and every consumer derives its elements
// from that. Repeating them here would be a second derivation of one fact
// for no reader, and 512 entries wide in the corpus's largest atlas.
Some(node) if expressible_embedded_texture(&member, node).is_some() => 1,
Some(node) if member.repeats_a_handle(node) => member.array_len,
_ => 1,
};
(0..elements).filter_map(move |element| {
let node = node?;
let argument_index = member.argument_index(node).checked_add(element)?;
Some(EmbeddedArgument {
buffer_param_index,
buffer_index,
field_ordinal: member.field_ordinal,
field_offset: member
.field_offset
.checked_add(element.checked_mul(HANDLE_BYTES)?)?,
argument_index,
resource_buffer_index: is_buffer.then_some(argument_index),
resource_address_space: is_buffer
.then(|| super::address_space(node))
.flatten(),
resource_declared_size: is_buffer
.then(|| super::i32_after_marker(node, "air.arg_type_size"))
.flatten(),
resource_access: is_buffer
.then(|| super::declared_buffer_access(node))
.flatten(),
})
})
})
})
.collect()
}
/// Yield `(field_offset, nested_node_ref)` for every `air.indirect_argument` member of an
/// `air.struct_type_info` node. Each member of a struct-type-info node is a 5-tuple
/// `i32 offset, i32 size, i32 array_len, !"type", !"name"`, optionally PREFIXED by
/// `!"air.indirect_argument", !N` — a SUFFIX that trails the member's `name` string (e.g.
/// `i32 0, i32 8, i32 0, !"texture2d<...>", !"texture", !"air.indirect_argument", !22`), mirroring the
/// tuple layout `parse_struct_info` walks. We recover the member `offset` and the `!N` of the
/// `air.indirect_argument` suffix that belongs to THAT member, so the caller can classify the nested
/// node. (Nested `air.struct_type_info` members are walked but never carry a top-level embedded
/// texture, so their suffix is ignored.)
fn embedded_argument_members(nodes: &HashMap<u32, String>, sref: u32) -> Vec<(u32, u32, u32)> {
let Some(body) = nodes.get(&sref) else {
return vec![];
};
let toks = tokenize(body);
/// The AIR roles that name a resource an argument buffer references by HANDLE, rather than a value
/// it stores inline. `air.indirect_constant` is the one role that means "stored inline".
const EMBEDDED_RESOURCE_ROLES: &[&str] = &[
"buffer",
"command_buffer",
"compute_pipeline_state",
"indirect_buffer",
"intersection_function_table",
"primitive_acceleration_structure",
"render_pipeline_state",
"sampler",
"texture",
"visible_function_table",
];
/// Resource handles an argument buffer declares that [`detect_embedded_textures`] cannot
/// materialize a descriptor for, each named so a refusal can say what was missed.
///
/// Metal lets an argument-buffer member be a user struct that itself holds a texture, sampler or
/// buffer -- `struct texture2d_wrapper { texture2d<half> t; };` as one member. A wrapped texture is
/// surfaced like a flat one, at the argument id [`ArgumentMember::argument_index`] derives; anything
/// else wrapped -- a buffer, a sampler, a function table, or any member of a wrapper declared as an
/// ARRAY of structs -- has no descriptor. Nor does a flat `air.texture` whose access class the
/// read/write lowerings cannot express.
///
/// Such a member decodes as opaque storage, the handle load yields a Private placeholder, and every
/// texture operation on it takes the "resource is absent" path and folds to zero. That path is
/// right for a resource AIR says is absent and wrong for one it declares, so a module carrying one
/// of these refuses rather than sampling black.
///
/// A flat `air.buffer`, `air.sampler` or function-table handle is NOT named here: those have their
/// own representation as an [`EmbeddedArgument`], and the ones that lack a descriptor lack it for
/// reasons this list is not the diagnosis of.
pub(super) fn unsurfaced_embedded_resources(
nodes: &HashMap<u32, String>,
argument_buffers: &ArgumentBuffers,
) -> Vec<String> {
let mut out = vec![];
let mut i = 0;
let mut field_ordinal = 0u32;
while i < toks.len() {
// Optional nested-struct prefix (`!"air.struct_type_info", !N`).
if let (Some(Tok::Str(s)), Some(Tok::Ref(_))) = (toks.get(i), toks.get(i + 1)) {
if s == "air.struct_type_info" {
i += 2;
for (buffer_param_index, _, sref) in argument_buffers.iter() {
for member in embedded_argument_members(nodes, sref) {
let Some(node) = nodes.get(&member.node_ref) else {
continue;
};
if expressible_embedded_texture(&member, node).is_some() {
continue;
}
let Some(role) = role_strings(node)
.into_iter()
.find(|role| EMBEDDED_RESOURCE_ROLES.contains(&role.as_str()))
else {
continue;
};
let offset = member.field_offset;
match (member.depth, role.as_str()) {
(0, "texture") => out.push(format!(
"argument buffer parameter {buffer_param_index} holds an air.texture at byte \
offset {offset} the embedded lowering cannot express ({})",
arg_type_name(node).unwrap_or_else(|| "unnamed".to_string())
)),
(0, _) => {}
(_, _) => out.push(format!(
"argument buffer parameter {buffer_param_index} holds an air.{role} at byte \
offset {offset} inside a nested struct member"
)),
}
}
// Member tuple: offset, size, array_len, type-name (name string follows).
let offset = match (
toks.get(i),
toks.get(i + 1),
toks.get(i + 2),
toks.get(i + 3),
) {
(Some(Tok::Int(off)), Some(Tok::Int(_)), Some(Tok::Int(_)), Some(Tok::Str(_))) => *off,
_ => break,
};
i += 5; // 3 ints + type + name
// Trailing tokens up to the next member: an `!"air.indirect_argument", !N` SUFFIX here binds
// node `!N` to THIS member (its `offset`). Use `struct_member_starts_at` (which does NOT treat
// the `air.indirect_argument` marker as a member start) as the stop test, so the suffix is
// scanned rather than skipped; the scan ends at the next real member tuple.
while i < toks.len() && !struct_member_starts_at(&toks, i) {
if let (Some(Tok::Str(s)), Some(Tok::Ref(x))) = (toks.get(i), toks.get(i + 1)) {
if s == "air.indirect_argument" {
out.push((field_ordinal, offset, *x));
}
}
i += 1;
}
field_ordinal += 1;
}
out
}
/// One `air.indirect_argument` resource member of an argument buffer, flattened out of the nested
/// `air.struct_type_info` wrappers Metal allows around it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct ArgumentMember {
/// Member ordinal of the OUTERMOST struct member that reaches this handle -- the first index of
/// the LLVM GEP that loads it. Members of one wrapper share it; `field_offset` separates them.
field_ordinal: u32,
/// Byte offset of the handle from the start of the argument buffer.
field_offset: u32,
/// The `air.<role>` node describing the resource.
node_ref: u32,
/// Sum of the `air.indirect_argument` ids of the enclosing wrappers; zero for a flat member. A
/// wrapped member's own `air.location_index` is RELATIVE to it, so the Metal argument-encoder id
/// is `argument_base + air.location_index`.
argument_base: u32,
/// How many `air.struct_type_info` wrappers enclose this handle. Zero for a flat member.
depth: u32,
/// Whether any enclosing wrapper is declared as an ARRAY of structs. Such a wrapper repeats its
/// members once per element, and this walk names element 0 only.
in_array_wrapper: bool,
/// The member's OWN declared C-array length (`texture2d<float> slices[32]`), or zero when it is
/// a single handle. This is a third, independent statement of a descriptor-array length -- see
/// [`expressible_embedded_texture`] for why the type name cannot answer it.
array_len: u32,
}
impl ArgumentMember {
/// The Metal `[[id(n)]]` this resource occupies in its argument buffer.
///
/// Proved against the Metal front end, which refuses
/// `struct Inner { texture2d<half> x [[id(3)]]; }` at `[[id(7)]]` beside a sibling at
/// `[[id(10)]]` with "attribute 'id' set location to 10, but minimum is 11": 7 + 3 is taken, so
/// the ids ADD down the nesting path.
fn argument_index(&self, node: &str) -> u32 {
self.argument_base
.saturating_add(super::location_index(node, self.field_ordinal))
}
/// True when this member is a C array of RESOURCE HANDLES, each of which is its own argument id
/// and its own [`HANDLE_BYTES`] slot. An `air.indirect_constant` array is stored inline and is
/// one span of data, not N resources, so it is not one of these.
fn repeats_a_handle(&self, node: &str) -> bool {
self.array_len > 1
&& role_strings(node)
.iter()
.any(|role| EMBEDDED_RESOURCE_ROLES.contains(&role.as_str()))
}
}
/// The size of one opaque resource handle in an argument buffer. Every consumer of an embedded
/// resource -- the Metal argument encoder, the Vulkan descriptor writer and `corpus-case-check` --
/// already derives an element from `field_offset` by this stride, so it is stated once here.
const HANDLE_BYTES: u32 = 8;
/// Metal's own argument-buffer nesting limit is far below this; the cap only stops a malformed node
/// graph whose `air.struct_type_info` reaches itself from recursing forever.
const MAX_ARGUMENT_NESTING: u32 = 8;
/// Yield every `air.indirect_argument` resource member of an `air.struct_type_info` node, descending
/// into the nested wrappers Metal allows around one.
///
/// The member grammar itself is [`member_tuples`]; this walk only decides what each tuple means.
/// A tuple whose `air.indirect_argument` suffix is a bare `i32` beside a nested member list is a
/// wrapper, and that `i32` is the wrapper's own argument id (see [`ArgumentMember::argument_index`]).
fn embedded_argument_members(nodes: &HashMap<u32, String>, sref: u32) -> Vec<ArgumentMember> {
let mut out = vec![];
collect_argument_members(nodes, sref, Nesting::default(), &mut out);
out
}
/// What the enclosing `air.struct_type_info` wrappers contribute to every member inside them.
/// `Nesting::default()` is the argument buffer's own member list.
#[derive(Clone, Copy, Debug, Default)]
struct Nesting {
field_ordinal: u32,
field_offset: u32,
argument_base: u32,
depth: u32,
in_array_wrapper: bool,
}
fn collect_argument_members(
nodes: &HashMap<u32, String>,
sref: u32,
enclosing: Nesting,
out: &mut Vec<ArgumentMember>,
) {
if enclosing.depth > MAX_ARGUMENT_NESTING {
return;
}
let Some(body) = nodes.get(&sref) else {
return;
};
for (field_ordinal, member) in member_tuples(&tokenize(body)).into_iter().enumerate() {
// A wrapper's members keep the OUTERMOST ordinal, which is the GEP index that reaches them,
// so a flat member's ordinal is exactly what it was before nesting was walked at all.
let outer_ordinal = if enclosing.depth == 0 {
field_ordinal as u32
} else {
enclosing.field_ordinal
};
match (member.nested, member.argument_wrapper_id) {
(Some(wrapper), Some(id)) => collect_argument_members(
nodes,
wrapper,
Nesting {
field_ordinal: outer_ordinal,
field_offset: enclosing.field_offset + member.offset,
argument_base: enclosing.argument_base + id,
depth: enclosing.depth + 1,
in_array_wrapper: enclosing.in_array_wrapper || member.array_len != 0,
},
out,
),
_ => {
if let Some(node_ref) = member.argument_node {
out.push(ArgumentMember {
field_ordinal: outer_ordinal,
field_offset: enclosing.field_offset + member.offset,
node_ref,
argument_base: enclosing.argument_base,
depth: enclosing.depth,
in_array_wrapper: enclosing.in_array_wrapper,
array_len: member.array_len,
});
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -252,7 +493,8 @@ mod tests {
r#"i32 1, !"air.texture", !"air.location_index", i32 1, i32 1, !"air.write", !"air.arg_type_name", !"texture2d<float, write>""#.to_string(),
);
let textures = detect_embedded_textures(&nodes, &[(4, 0, 10)], &[]);
let textures =
detect_embedded_textures(&nodes, &ArgumentBuffers::new(vec![(4, 0, 10)]), &[]);
assert_eq!(textures.len(), 2);
assert_eq!(textures[0].buffer_param_index, 4);
assert_eq!(textures[0].field_offset, 0);
@@ -280,7 +522,8 @@ mod tests {
r#"i32 0, !"air.texture", !"air.location_index", i32 4, i32 2, !"air.sample", !"air.arg_type_name", !"array<depth2d_array<float, sample>, 2>""#.to_string(),
);
let textures = detect_embedded_textures(&nodes, &[(1, 16, 10)], &[]);
let textures =
detect_embedded_textures(&nodes, &ArgumentBuffers::new(vec![(1, 16, 10)]), &[]);
assert_eq!(textures.len(), 1);
assert_eq!(textures[0].argument_index, 4);
assert_eq!(textures[0].array_length, Some(2));
@@ -288,6 +531,73 @@ mod tests {
assert_eq!(textures[0].storage_format, None);
}
#[test]
fn embedded_c_array_member_takes_its_length_from_the_member_tuple() {
// `texture2d<float, sample> slices[32]` inside an argument buffer: the type name is the
// ELEMENT type and the node's count operand stays 1, so only the tuple's `array_len` slot
// says 32. Reading the name alone surfaced one descriptor and let a runtime index sample
// element 0.
let mut nodes = HashMap::new();
nodes.insert(
10,
r#"i32 0, i32 8, i32 32, !"texture2d<float, sample>", !"slices", !"air.indirect_argument", !20"#.to_string(),
);
nodes.insert(
20,
r#"i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.sample", !"air.arg_type_name", !"texture2d<float, sample>", !"air.arg_name", !"slices""#.to_string(),
);
let textures =
detect_embedded_textures(&nodes, &ArgumentBuffers::new(vec![(5, 1, 10)]), &[]);
assert_eq!(textures.len(), 1);
assert_eq!(textures[0].array_length, Some(32));
assert_eq!(textures[0].argument_index, 0);
assert!(!textures[0].arrayed);
// Expressible, so it is not also reported as a resource with no descriptor.
assert!(
unsurfaced_embedded_resources(&nodes, &ArgumentBuffers::new(vec![(5, 1, 10)]))
.is_empty()
);
}
#[test]
fn a_c_array_of_buffer_handles_surfaces_one_resource_per_element() {
// `device half4* bufs[2] [[id(12)]]` -- two device addresses, at consecutive argument ids
// and consecutive 8-byte slots. Surfacing only the first left the second slot of the
// argument buffer unwritten, so a runtime index into the member read an address nothing
// ever populated.
let mut nodes = HashMap::new();
nodes.insert(
10,
r#"i32 0, i32 8, i32 2, !"half4", !"bufs", !"air.indirect_argument", !20, i32 16, i32 4, i32 4, !"uint", !"counts", !"air.indirect_argument", !21"#.to_string(),
);
nodes.insert(
20,
r#"i32 0, !"air.buffer", !"air.location_index", i32 12, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 8, !"air.arg_type_name", !"half4", !"air.arg_name", !"bufs""#.to_string(),
);
// An inline `uint counts[4]` is one span of DATA, not four resources.
nodes.insert(
21,
r#"i32 1, !"air.indirect_constant", !"air.location_index", i32 14, i32 1, !"air.arg_type_name", !"uint", !"air.arg_name", !"counts""#.to_string(),
);
let arguments = detect_embedded_arguments(&nodes, &ArgumentBuffers::new(vec![(0, 3, 10)]));
let coordinates = arguments
.iter()
.map(|argument| {
(
argument.field_offset,
argument.argument_index,
argument.resource_buffer_index,
)
})
.collect::<Vec<_>>();
assert_eq!(
coordinates,
vec![(0, 12, Some(12)), (8, 13, Some(13)), (16, 14, None)]
);
}
#[test]
fn embedded_argument_detection_classifies_only_nested_buffers_as_device_resources() {
let mut nodes = HashMap::new();
@@ -304,7 +614,7 @@ mod tests {
r#"i32 1, !"air.buffer", !"air.location_index", i32 7, i32 1, !"air.address_space", i32 1"#.to_string(),
);
let arguments = detect_embedded_arguments(&nodes, &[(3, 5, 10)]);
let arguments = detect_embedded_arguments(&nodes, &ArgumentBuffers::new(vec![(3, 5, 10)]));
assert_eq!(arguments.len(), 2);
assert_eq!(arguments[0].resource_buffer_index, None);
assert_eq!(arguments[1].buffer_param_index, 3);
@@ -314,4 +624,199 @@ mod tests {
assert_eq!(arguments[1].resource_buffer_index, Some(7));
assert_eq!(arguments[1].resource_address_space, Some(1));
}
/// A wrapper's members carry an `air.location_index` RELATIVE to the wrapper's own id, so the
/// Metal `[[id(n)]]` adds down the nesting path -- 30 + 0 + 2 for a handle two wrappers deep.
#[test]
fn a_wrapped_texture_binds_at_the_summed_argument_id() {
let nodes = HashMap::from([
(
10_u32,
r#"!"air.struct_type_info", !11, i32 64, i32 8, i32 0, !"deep", !"d", !"air.indirect_argument", i32 30, i32 72, i32 8, i32 0, !"texture2d<float, sample>", !"flat", !"air.indirect_argument", !14"#.to_string(),
),
(
11_u32,
r#"!"air.struct_type_info", !12, i32 0, i32 8, i32 0, !"inner", !"mid", !"air.indirect_argument", i32 0"#.to_string(),
),
(
12_u32,
r#"i32 8, i32 8, i32 0, !"texture2d<float, sample>", !"y", !"air.indirect_argument", !13"#.to_string(),
),
(
13_u32,
r#"i32 0, !"air.texture", !"air.location_index", i32 2, i32 1, !"air.sample", !"air.arg_type_name", !"texture2d<float, sample>""#.to_string(),
),
(
14_u32,
r#"i32 1, !"air.texture", !"air.location_index", i32 40, i32 1, !"air.sample", !"air.arg_type_name", !"texture2d<float, sample>""#.to_string(),
),
]);
let textures =
detect_embedded_textures(&nodes, &ArgumentBuffers::new(vec![(0, 0, 10)]), &[]);
assert_eq!(
textures
.iter()
.map(|t| (t.field_ordinal, t.field_offset, t.argument_index))
.collect::<Vec<_>>(),
// The nested handle keeps the OUTER ordinal 0 (the first GEP index that reaches it) and
// an ABSOLUTE byte offset 64 + 0 + 8; the flat sibling is untouched by the descent.
vec![(0, 72, 32), (1, 72, 40)],
);
}
/// A wrapper declared as an ARRAY of structs repeats its members once per element, at offsets
/// and argument ids this walk does not enumerate. Binding element 0 alone would leave the rest
/// reading black, so every member under it stays a refusal reason instead.
#[test]
fn an_arrayed_wrapper_is_refused_rather_than_bound_at_element_zero() {
let nodes = HashMap::from([
(
10_u32,
r#"!"air.struct_type_info", !11, i32 0, i32 48, i32 9, !"MaterialProperty", !"slot", !"air.indirect_argument", i32 0"#.to_string(),
),
(
11_u32,
r#"i32 0, i32 8, i32 0, !"texture2d<float, sample>", !"tex", !"air.indirect_argument", !12"#.to_string(),
),
(
12_u32,
r#"i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.sample", !"air.arg_type_name", !"texture2d<float, sample>""#.to_string(),
),
]);
let buffers = ArgumentBuffers::new(vec![(0, 0, 10)]);
assert_eq!(detect_embedded_textures(&nodes, &buffers, &[]), vec![]);
assert_eq!(
unsurfaced_embedded_resources(&nodes, &buffers),
vec![
"argument buffer parameter 0 holds an air.texture at byte offset 0 inside a nested \
struct member"
.to_string()
],
);
}
/// A wrapped `air.buffer` is a device address a consumer has to write into the owning argument
/// buffer, and nothing binds one, so it is named as unsurfaced rather than becoming a silent
/// `EmbeddedArgument` beside the flat members.
#[test]
fn a_wrapped_buffer_is_named_unsurfaced_and_is_not_an_embedded_argument() {
let nodes = HashMap::from([
(
10_u32,
r#"!"air.struct_type_info", !11, i32 16, i32 8, i32 0, !"wrapper", !"w", !"air.indirect_argument", i32 4, i32 24, i32 8, i32 0, !"float", !"values", !"air.indirect_argument", !13"#.to_string(),
),
(
11_u32,
r#"i32 0, i32 8, i32 0, !"float", !"inner", !"air.indirect_argument", !12"#.to_string(),
),
(
12_u32,
r#"i32 0, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.address_space", i32 1"#.to_string(),
),
(
13_u32,
r#"i32 1, !"air.buffer", !"air.location_index", i32 7, i32 1, !"air.address_space", i32 1"#.to_string(),
),
]);
let buffers = ArgumentBuffers::new(vec![(0, 0, 10)]);
assert_eq!(
detect_embedded_arguments(&nodes, &buffers)
.iter()
.map(|argument| (argument.field_offset, argument.resource_buffer_index))
.collect::<Vec<_>>(),
vec![(24, Some(7))],
);
assert_eq!(
unsurfaced_embedded_resources(&nodes, &buffers),
vec![
"argument buffer parameter 0 holds an air.buffer at byte offset 16 inside a nested \
struct member"
.to_string()
],
);
}
/// A nested struct with no `air.indirect_argument` suffix is an inline value, not a wrapped
/// resource: the walk steps over it without disturbing the ordinals of the members around it.
#[test]
fn an_inline_nested_struct_does_not_shift_its_siblings() {
let nodes = HashMap::from([
(
10_u32,
r#"i32 0, i32 4, i32 0, !"uint", !"count", !"air.indirect_argument", !11, !"air.struct_type_info", !12, i32 8, i32 16, i32 0, !"Params", !"params", i32 24, i32 8, i32 0, !"texture2d<float, sample>", !"tex", !"air.indirect_argument", !13"#.to_string(),
),
(
11_u32,
r#"i32 0, !"air.indirect_constant", !"air.location_index", i32 0, i32 1"#.to_string(),
),
(
12_u32,
r#"i32 0, i32 16, i32 0, !"float4", !"a""#.to_string(),
),
(
13_u32,
r#"i32 2, !"air.texture", !"air.location_index", i32 5, i32 1, !"air.sample", !"air.arg_type_name", !"texture2d<float, sample>""#.to_string(),
),
]);
let buffers = ArgumentBuffers::new(vec![(0, 0, 10)]);
assert!(unsurfaced_embedded_resources(&nodes, &buffers).is_empty());
let textures = detect_embedded_textures(&nodes, &buffers, &[]);
assert_eq!(textures.len(), 1);
assert_eq!(textures[0].field_ordinal, 2);
assert_eq!(textures[0].field_offset, 24);
assert_eq!(textures[0].argument_index, 5);
}
/// The synthetic embedded-texture index is a function of the entry's SIGNATURE, not of the order
/// the AIR metadata list names its argument-buffer nodes.
///
/// The walk hands out `K`, `K+1`, ... in list order, and a consumer binds by that index, so
/// listing the same two argument buffers the other way round used to move each embedded texture
/// onto the other one's descriptor -- in one corpus kernel, from `Binding 32` (sampled) to
/// `Binding 480` (storage). Parameter index orders them because it is unique per argument;
/// the Metal `[[buffer(N)]]` slot is not, since mutually exclusive function-constant
/// alternatives share one.
#[test]
fn the_synthetic_texture_index_does_not_depend_on_the_argument_list_order() {
let nodes = HashMap::from([
(
10_u32,
r#"i32 0, i32 8, i32 0, !"texture2d<float, sample>", !"first", !"air.indirect_argument", !12"#
.to_string(),
),
(
11_u32,
r#"i32 0, i32 8, i32 0, !"texture2d<float, write>", !"second", !"air.indirect_argument", !13"#
.to_string(),
),
(
12_u32,
r#"i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.sample", !"air.arg_type_name", !"texture2d<float, sample>", !"air.arg_name", !"first""#
.to_string(),
),
(
13_u32,
r#"i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.write", !"air.arg_type_name", !"texture2d<float, write>", !"air.arg_name", !"second""#
.to_string(),
),
]);
// Parameter 0 binds `[[buffer(7)]]`, parameter 1 binds `[[buffer(2)]]`, so list order,
// parameter order and Metal-slot order are three different orders.
let declared = vec![(0_u32, 7_u32, 10_u32), (1, 2, 11)];
let forward =
detect_embedded_textures(&nodes, &ArgumentBuffers::new(declared.clone()), &[]);
let reversed = detect_embedded_textures(
&nodes,
&ArgumentBuffers::new(declared.into_iter().rev().collect()),
&[],
);
assert_eq!(forward, reversed);
assert_eq!(
forward
.iter()
.map(|texture| (texture.buffer_param_index, texture.synthetic_texture_index))
.collect::<Vec<_>>(),
vec![(0, 0), (1, 1)],
);
}
}
+41 -7
View File
@@ -23,6 +23,22 @@ pub struct FunctionConstant {
/// Keys ONLY on that documented marker, never on a shader-specific name. Returns one entry per
/// distinct index, sorted, so a consumer can discover the module's spec-ids without scanning SPIR-V.
pub fn parse_function_constants(ll: &str) -> Vec<FunctionConstant> {
declared_function_constants(ll, |_| true)
}
/// The module's function constants the caller supplied no value for.
///
/// [`crate::fc_air_specialize::specialize_air_function_constants`] rewrites the `undef` initializer
/// of every index it is handed into that index's literal, and nothing else writes one, so an
/// initializer still reading `undef` is exactly "no value reached this constant". AIR states no
/// default for it either — see the type comment above — so anything downstream that needs a value
/// here is inventing one.
pub(crate) fn function_constants_without_a_supplied_value(ll: &str) -> Vec<FunctionConstant> {
declared_function_constants(ll, declares_no_value)
}
/// One entry per distinct index whose declaration's initializer satisfies `keep`, sorted by index.
fn declared_function_constants(ll: &str, keep: impl Fn(&str) -> bool) -> Vec<FunctionConstant> {
let mut out: Vec<FunctionConstant> = Vec::new();
for line in ll.lines() {
let t = line.trim_start();
@@ -47,10 +63,14 @@ pub fn parse_function_constants(ll: &str) -> Vec<FunctionConstant> {
if out.iter().any(|f| f.index == index) {
continue;
}
let declared = fc_global_decl_type_and_initializer(&t[eq + 3..]);
if !keep(declared.as_ref().map_or("", |(_, initializer)| initializer)) {
continue;
}
out.push(FunctionConstant {
index,
name: base.to_string(),
type_name: fc_global_decl_type(&t[eq + 3..]).unwrap_or_default(),
type_name: declared.map(|(type_name, _)| type_name).unwrap_or_default(),
abi_type_encoding,
});
}
@@ -58,18 +78,32 @@ pub fn parse_function_constants(ll: &str) -> Vec<FunctionConstant> {
out
}
/// Whether a declaration's initializer is LLVM's `undef` rather than a value. Matched as a whole
/// token so an identifier that merely starts with those letters cannot be read as one.
fn declares_no_value(initializer: &str) -> bool {
initializer
.strip_prefix("undef")
.is_some_and(|rest| !rest.starts_with(|c: char| c.is_alphanumeric() || c == '_'))
}
/// The declared LLVM type of a `constant`/`global` definition body (the token after the
/// `constant`/`global` keyword): a balanced `<...>` vector/array or the first scalar token.
fn fc_global_decl_type(decl: &str) -> Option<String> {
/// `constant`/`global` keyword) and the initializer that follows it: a balanced `<...>`
/// vector/array or the first scalar token, then the rest.
///
/// One reader for both, so the type scan and the "did the caller supply a value" scan cannot
/// disagree about where the type ends.
fn fc_global_decl_type_and_initializer(decl: &str) -> Option<(String, &str)> {
let after = decl
.split(" constant ")
.nth(1)
.or_else(|| decl.split(" global ").nth(1))?;
let s = after.trim_start();
if let Some(rest) = s.strip_prefix('<') {
let (type_name, rest) = if let Some(rest) = s.strip_prefix('<') {
let end = rest.find('>')?;
Some(format!("<{}>", &rest[..end]))
(format!("<{}>", &rest[..end]), &rest[end + 1..])
} else {
s.split_whitespace().next().map(str::to_string)
}
let token = s.split_whitespace().next()?;
(token.to_string(), &s[token.len()..])
};
Some((type_name, rest.trim_start()))
}
+268 -32
View File
@@ -83,13 +83,18 @@ fn static_init_global_values(ll: &str) -> HashMap<String, StaticValue> {
let Some(global) = parse_global_name(ptr) else {
continue;
};
if let Some(value) = eval_value_token(value_token(value), &env, &globals) {
if let Some(evaluated) = eval_value_token(value_token(value), &env, &globals) {
unknown_stores.remove(&global);
// Narrow to the STORE's own operand type. A fixed 32-bit mask clipped every
// `store i64` to its low half, which is how a 64-bit function constant's high bits
// -- the bit an `lshr i64 %x, 63` predicate reads -- were lost.
let mask = integer_result_width_and_mask(value)
.map_or(u64::from(u32::MAX), |(_, mask)| mask);
globals.insert(
global,
match value {
StaticValue::Int(value) => StaticValue::Int(value & u64::from(u32::MAX)),
value => value,
match evaluated {
StaticValue::Int(evaluated) => StaticValue::Int(evaluated & mask),
evaluated => evaluated,
},
);
} else {
@@ -299,10 +304,13 @@ fn integer_initializer(rest: &str) -> Option<StaticValue> {
let mut tokens = typed_init.split_whitespace();
let ty = tokens.next()?;
let width = ty.strip_prefix('i')?.parse::<u32>().ok()?;
if !matches!(width, 8 | 16 | 32) {
// The scalar widths a Metal function constant is declared at. 47 of the local corpus's
// `air.fc_initializer` globals are `i64` (`ulong`), and leaving them unseeded left every
// predicate derived from one unevaluated.
if !matches!(width, 8 | 16 | 32 | 64) {
return None;
}
let mask = (1_u64 << width) - 1;
let (_, mask) = integer_result_width_and_mask(ty)?;
let value = tokens.next()?.trim_end_matches(',');
if value == "undef" && rest.contains("air.fc_initializer") {
return Some(StaticValue::Int(0));
@@ -314,6 +322,21 @@ fn integer_initializer(rest: &str) -> Option<StaticValue> {
.map(|value| StaticValue::Int(value & mask))
}
/// The integer binary opcodes the static-initializer evaluator folds. Every one is matched with the
/// separating space, so no entry can be read out of the start of another and the order here carries
/// no meaning.
const INTEGER_BINARY_OPCODES: &[&str] = &[
"add", "sub", "mul", "and", "or", "xor", "udiv", "urem", "sdiv", "srem", "shl", "lshr", "ashr",
];
/// `value` read as a SIGNED integer of `width` bits. The evaluator carries every integer as a
/// masked `u64`, so a signed comparison, division or arithmetic shift has to recover the sign bit
/// from the operand's own width rather than from bit 63 of the carrier.
fn signed_of(value: u64, width: u32) -> i64 {
let shift = 64 - width.min(64);
((value << shift) as i64) >> shift
}
fn eval_static_rhs(
rhs: &str,
env: &HashMap<String, StaticValue>,
@@ -322,6 +345,28 @@ fn eval_static_rhs(
if rhs.contains("@air.is_function_constant_defined(") {
return Some(StaticValue::Bool(false));
}
// `llvm.umax`/`umin`/`smax`/`smin` are how the front end spells a clamped function-constant
// expression, and 106 of them appear in the local corpus's static initializers.
if let Some((name, rest)) = ["umax", "umin", "smax", "smin"]
.into_iter()
.find_map(|name| {
rhs.split_once(&format!("@llvm.{name}."))
.map(|(_, rest)| (name, rest))
})
{
let arguments = rest.split_once('(')?.1.rsplit_once(')')?.0;
let (lhs, rhs) = eval_binary_int(arguments, env, globals)?;
let (width, mask) = integer_result_width_and_mask(arguments)?;
let (lhs, rhs) = (lhs & mask, rhs & mask);
let value = match name {
"umax" => lhs.max(rhs),
"umin" => lhs.min(rhs),
"smax" => signed_of(lhs, width).max(signed_of(rhs, width)) as u64,
"smin" => signed_of(lhs, width).min(signed_of(rhs, width)) as u64,
_ => unreachable!("matched min/max intrinsic"),
};
return Some(StaticValue::Int(value & mask));
}
if rhs.contains("@air.normalize_function_constant_predicate.") {
let arguments = rhs.split_once('(')?.1.rsplit_once(')')?.0;
let value = eval_int_operand(arguments, env, globals)?;
@@ -340,37 +385,57 @@ fn eval_static_rhs(
};
return values.get(idx).copied().map(StaticValue::Int);
}
if let Some((opcode, rest)) = ["add", "mul", "and", "or", "xor", "shl", "lshr"]
.into_iter()
.find_map(|opcode| {
rhs.strip_prefix(opcode)
.and_then(|rest| rest.strip_prefix(' '))
.map(|rest| (opcode, rest))
})
{
if let Some((opcode, rest)) = INTEGER_BINARY_OPCODES.iter().find_map(|opcode| {
rhs.strip_prefix(opcode)
.and_then(|rest| rest.strip_prefix(' '))
.map(|rest| (*opcode, rest))
}) {
let (lhs, rhs) = eval_binary_int(rest, env, globals)?;
let (width, mask) = integer_result_width_and_mask(rest)?;
let lhs = lhs & mask;
let (lhs, rhs) = (lhs & mask, rhs & mask);
let value = match opcode {
"add" => lhs.wrapping_add(rhs & mask),
"mul" => lhs.wrapping_mul(rhs & mask),
"and" => lhs & (rhs & mask),
"or" => lhs | (rhs & mask),
"xor" => lhs ^ (rhs & mask),
"add" => lhs.wrapping_add(rhs),
"sub" => lhs.wrapping_sub(rhs),
"mul" => lhs.wrapping_mul(rhs),
"and" => lhs & rhs,
"or" => lhs | rhs,
"xor" => lhs ^ rhs,
"udiv" => lhs.checked_div(rhs)?,
"urem" => lhs.checked_rem(rhs)?,
"sdiv" => signed_of(lhs, width).checked_div(signed_of(rhs, width))? as u64,
"srem" => signed_of(lhs, width).checked_rem(signed_of(rhs, width))? as u64,
"shl" if rhs < u64::from(width) => lhs.checked_shl(rhs.try_into().ok()?)?,
"lshr" if rhs < u64::from(width) => lhs.checked_shr(rhs.try_into().ok()?)?,
"shl" | "lshr" => return None,
// Arithmetic shift right is the one shift that reads the operand as SIGNED, so the
// sign bit has to be recovered from the operand width before shifting rather than from
// the 64-bit carrier the value is stored in.
"ashr" if rhs < u64::from(width) => (signed_of(lhs, width) >> rhs.min(63)) as u64,
"shl" | "lshr" | "ashr" => return None,
_ => unreachable!("matched integer opcode"),
};
return Some(StaticValue::Int(value & mask));
}
if let Some(rest) = rhs.strip_prefix("icmp ") {
let mut fields = rest.splitn(2, ' ');
let pred = fields.next()?;
let (lhs, rhs) = eval_binary_int(fields.next()?, env, globals)?;
let value = match pred {
let (predicate, operands) = rest.split_once(' ')?;
let (lhs, rhs) = eval_binary_int(operands, env, globals)?;
// The comparison is on the OPERAND type's width: a signed predicate reads the same bits as
// a negative number, and an unsigned one must not see carrier bits above the operand.
// Reading only `eq`/`ne` left every ordered comparison unevaluated -- 648 of the 10938
// `icmp`s in the local corpus's static initializers -- and an unevaluated predicate is
// reported as "not enabled by default", which is a GUESS the callers spend as a fact.
let (width, mask) = integer_result_width_and_mask(operands)?;
let (lhs, rhs) = (lhs & mask, rhs & mask);
let value = match predicate {
"eq" => lhs == rhs,
"ne" => lhs != rhs,
"ugt" => lhs > rhs,
"uge" => lhs >= rhs,
"ult" => lhs < rhs,
"ule" => lhs <= rhs,
"sgt" => signed_of(lhs, width) > signed_of(rhs, width),
"sge" => signed_of(lhs, width) >= signed_of(rhs, width),
"slt" => signed_of(lhs, width) < signed_of(rhs, width),
"sle" => signed_of(lhs, width) <= signed_of(rhs, width),
_ => return None,
};
return Some(StaticValue::Bool(value));
@@ -386,13 +451,11 @@ fn eval_static_rhs(
.or_else(|| rhs.strip_prefix("zext "))
{
let (value, to_ty) = rest.split_once(" to ")?;
let mut int = eval_int_operand(value, env, globals)?;
if to_ty.trim_start().starts_with("i8") {
int &= 0xff;
} else if to_ty.trim_start().starts_with("i16") {
int &= 0xffff;
}
return Some(StaticValue::Int(int));
let int = eval_int_operand(value, env, globals)?;
// Narrow to the DESTINATION width, whatever it is. Masking only `i8` and `i16` let a
// `trunc i64 ... to i32` keep the high half it exists to discard.
let (_, mask) = integer_result_width_and_mask(to_ty)?;
return Some(StaticValue::Int(int & mask));
}
if rhs.contains("function_constant_predicate") {
let open = rhs.rfind('(')?;
@@ -599,4 +662,177 @@ entry:
Some(&1)
);
}
/// Every `icmp` predicate and integer opcode the local corpus's static initializers contain.
///
/// An expression the evaluator cannot fold leaves its global unknown, and an unknown
/// function-constant predicate is reported as "not enabled by default" -- a guess the stage
/// decodes spend as a fact, dropping outputs and system values. Reading only `eq` and `ne` left
/// 648 ordered comparisons unevaluated. The signed cases are the ones worth stating: the
/// evaluator carries every integer as a masked `u64`, so `-1` compares GREATER than `1` unless
/// the sign is recovered from the operand's own width.
#[test]
fn every_static_initializer_integer_expression_folds() {
for (expression, expected) in [
("%a = add i16 %one, 15", 16),
("%a = sub i16 %one, 15", 0xfff2),
("%a = mul i16 %one, 15", 15),
("%a = udiv i16 %seven, 2", 3),
("%a = urem i16 %seven, 2", 1),
("%a = sdiv i16 %minus_one, 1", 0xffff),
("%a = srem i16 %seven, 2", 1),
("%a = and i16 %seven, 2", 2),
("%a = or i16 %one, 2", 3),
("%a = xor i16 %one, 3", 2),
("%a = shl i16 %one, 3", 8),
("%a = lshr i16 %minus_one, 12", 0xf),
// `ashr` reads the operand as signed: -1 stays -1 however far it is shifted.
("%a = ashr i16 %minus_one, 12", 0xffff),
("%a = icmp ugt i16 %seven, 2", 1),
("%a = icmp uge i16 %seven, 7", 1),
("%a = icmp ult i16 %seven, 2", 0),
("%a = icmp ule i16 %seven, 7", 1),
// -1 is the LARGEST i16 unsigned and the SMALLEST signed.
("%a = icmp ugt i16 %minus_one, 7", 1),
("%a = icmp sgt i16 %minus_one, 7", 0),
("%a = icmp slt i16 %minus_one, 7", 1),
("%a = icmp sge i16 %minus_one, %minus_one", 1),
("%a = icmp sle i16 %minus_one, 7", 1),
("%a = icmp eq i16 %seven, 7", 1),
("%a = icmp ne i16 %seven, 7", 0),
("%a = tail call i16 @llvm.umax.i16(i16 %seven, i16 2)", 7),
("%a = tail call i16 @llvm.umin.i16(i16 %seven, i16 2)", 2),
(
"%a = tail call i16 @llvm.umax.i16(i16 %minus_one, i16 2)",
0xffff,
),
(
"%a = tail call i16 @llvm.smax.i16(i16 %minus_one, i16 2)",
2,
),
(
"%a = tail call i16 @llvm.smin.i16(i16 %minus_one, i16 2)",
0xffff,
),
] {
let ll = format!(
r#"
@one = internal addrspace(2) global i16 1, align 2
@seven = internal addrspace(2) global i16 7, align 2
@minus_one = internal addrspace(2) global i16 -1, align 2
@folded = internal addrspace(2) global i16 undef, align 2
define internal void @_GLOBAL__sub_I_fold() section "air.static_init" {{
entry:
%one = load i16, ptr addrspace(2) @one
%seven = load i16, ptr addrspace(2) @seven
%minus_one = load i16, ptr addrspace(2) @minus_one
{expression}
store i16 %a, ptr addrspace(2) @folded
ret void
}}
"#
);
assert_eq!(
static_init_int_global_values(&ll).get("@folded"),
Some(&expected),
"{expression}"
);
}
}
/// A division by zero must stay UNKNOWN rather than fold to a value the shader would never see,
/// the way [`out_of_width_shift_is_not_folded`] already requires of an over-wide shift.
#[test]
fn an_undefined_division_does_not_fold() {
for expression in [
"%a = udiv i16 %seven, 0",
"%a = urem i16 %seven, 0",
"%a = sdiv i16 %seven, 0",
"%a = srem i16 %seven, 0",
] {
let ll = format!(
r#"
@seven = internal addrspace(2) global i16 7, align 2
@folded = internal addrspace(2) global i16 undef, align 2
define internal void @_GLOBAL__sub_I_fold() section "air.static_init" {{
entry:
%seven = load i16, ptr addrspace(2) @seven
{expression}
store i16 %a, ptr addrspace(2) @folded
ret void
}}
"#
);
assert_eq!(
static_init_int_global_values(&ll).get("@folded"),
None,
"{expression}"
);
}
}
/// A 64-bit function constant is a function constant. `ulong` is a Metal function-constant type
/// -- 47 of the local corpus's `air.fc_initializer` globals are `i64` -- and the initializer
/// reader accepted only 8, 16 and 32 bits, so every predicate derived from one stayed unknown
/// and every caller read that as "not enabled by default".
#[test]
fn a_64_bit_function_constant_initializer_is_seeded() {
let ll = r#"
@bits.MTL_FC_INIT_1_m = internal addrspace(2) externally_initialized constant i64 undef, section "air.fc_initializer", align 8
@mirror = internal addrspace(2) global i64 undef, align 8
@enabled = internal addrspace(2) global i8 undef, align 1
define internal void @_GLOBAL__sub_I_wide() section "air.static_init" {
entry:
%value = load i64, ptr addrspace(2) @bits.MTL_FC_INIT_1_m
store i64 %value, ptr addrspace(2) @mirror
%high = lshr i64 %value, 63
%narrow = trunc i64 %high to i8
store i8 %narrow, ptr addrspace(2) @enabled
ret void
}
"#;
let values = static_init_int_global_values(ll);
assert_eq!(values.get("@mirror"), Some(&0));
assert_eq!(values.get("@enabled"), Some(&0));
}
/// A store carries its OWN operand width. Narrowing every stored integer to 32 bits dropped the
/// high half of a `store i64`, so a predicate reading a bit above 31 out of the stored mirror --
/// `lshr i64 %x, 63`, the shape two corpus kernels use -- read zero whatever the constant said.
#[test]
fn a_stored_64_bit_value_keeps_its_high_half() {
let ll = r#"
@bits = internal addrspace(2) global i64 1311768467463790320, align 8
@mirror = internal addrspace(2) global i64 undef, align 8
@high = internal addrspace(2) global i32 undef, align 4
@low = internal addrspace(2) global i32 undef, align 4
@residue = internal addrspace(2) global i64 undef, align 8
define internal void @_GLOBAL__sub_I_wide() section "air.static_init" {
entry:
%value = load i64, ptr addrspace(2) @bits
store i64 %value, ptr addrspace(2) @mirror
%stored = load i64, ptr addrspace(2) @mirror
%shifted = lshr i64 %stored, 32
%top = trunc i64 %shifted to i32
store i32 %top, ptr addrspace(2) @high
%bottom = trunc i64 %stored to i32
store i32 %bottom, ptr addrspace(2) @low
%widened = zext i32 %bottom to i64
%residue = lshr i64 %widened, 32
store i64 %residue, ptr addrspace(2) @residue
ret void
}
"#;
let values = static_init_int_global_values(ll);
assert_eq!(values.get("@high"), Some(&0x1234_5678));
assert_eq!(values.get("@low"), Some(&0x9abc_def0));
// `trunc ... to i32` discards the half it exists to discard. Masking only `i8` and `i16`
// left the high half on the value, and only the next STORE happened to hide it -- widening
// the truncated value again brings it back.
assert_eq!(values.get("@residue"), Some(&0));
}
}
+974 -235
View File
File diff suppressed because it is too large. Load diff
+950 -24
View File
File diff suppressed because it is too large. Load diff
+33 -18
View File
@@ -98,6 +98,7 @@ pub enum TextureFormat {
Rgba8ui,
Rgba16ui,
Rgba8i,
Rgba16i,
}
impl TextureFormat {
@@ -120,13 +121,14 @@ impl TextureFormat {
TextureFormat::Rgba8ui => ImageFormat::Rgba8ui,
TextureFormat::Rgba16ui => ImageFormat::Rgba16ui,
TextureFormat::Rgba8i => ImageFormat::Rgba8i,
TextureFormat::Rgba16i => ImageFormat::Rgba16i,
}
}
/// Every format this ABI can name. [`TextureFormat::from_spirv_format`] inverts
/// [`TextureFormat::to_spirv_format`] by searching this list, so a new variant belongs here as
/// well as in that match.
pub const ALL: [Self; 16] = [
pub const ALL: [Self; 17] = [
TextureFormat::R8,
TextureFormat::Rgba8,
TextureFormat::R16f,
@@ -143,6 +145,7 @@ impl TextureFormat {
TextureFormat::Rgba8ui,
TextureFormat::Rgba16ui,
TextureFormat::Rgba8i,
TextureFormat::Rgba16i,
];
/// The format a decorated storage image carries, or `None` for `ImageFormat::Unknown` and for
@@ -223,10 +226,14 @@ impl TextureShape {
}
}
/// Decode a Metal texture argument/type name into its [`TextureShape`]. The dimensionality/arrayed
/// classification is substring-order-sensitive (`1d_array` before `1d`, `cube_array` before `cube`)
/// and matches what the interface pass uses to construct the emitted image type, including its
/// multisample operand.
/// Decode a Metal texture argument/type name into its [`TextureShape`]. Matches what the interface
/// pass uses to construct the emitted image type, including its multisample operand.
///
/// "Arrayed" is read ONCE, off the `_array` suffix, rather than from a per-dimension substring per
/// arrayed spelling. The enumerated form had to name every combination and it missed one:
/// `texture2d_ms_array` does not contain the substring `2d_array`, so it reflected as a plain
/// multisample 2D texture while the emitted `OpTypeImage` was arrayed -- two derivations of one
/// fact, disagreeing. `depth2d_ms_array` had the same hole.
pub fn texture_shape_from_name(name: &str) -> TextureShape {
let (writable, array_ref) = texture_access_from_name(name);
let array_length = texture_handle_array(name).flatten();
@@ -242,23 +249,20 @@ pub fn texture_shape_from_name(name: &str) -> TextureShape {
.split_once('<')
.map(|(h, _)| h)
.unwrap_or(shape_name);
let (dimension, arrayed) = if head.contains("texture_buffer") {
(TextureDimension::Buffer, false)
} else if head.contains("1d_array") {
(TextureDimension::D1, true)
let dimension = if head.contains("texture_buffer") {
TextureDimension::Buffer
} else if head.contains("1d") {
(TextureDimension::D1, false)
TextureDimension::D1
} else if head.contains("3d") {
(TextureDimension::D3, false)
} else if head.contains("cube_array") {
(TextureDimension::Cube, true)
TextureDimension::D3
} else if head.contains("cube") {
(TextureDimension::Cube, false)
} else if head.contains("2d_array") {
(TextureDimension::D2, true)
TextureDimension::Cube
} else {
(TextureDimension::D2, false)
TextureDimension::D2
};
// `texture_buffer` is the one name that cannot be arrayed, and it does not end in `_array`
// either, so the suffix answers every spelling on its own.
let arrayed = head.ends_with("_array");
let multisampled = head.contains("_ms");
let component = texture_component_from_name(shape_name);
let storage_format = if writable {
@@ -325,7 +329,18 @@ fn storage_format_from_name(name: &str, component: TextureComponent) -> TextureF
TextureFormat::Rgba8ui
}
}
TextureComponent::Sint => TextureFormat::Rgba8i,
TextureComponent::Sint => {
// The signed default has to widen for `<short` exactly as the unsigned one does for
// `<ushort` just above. Without this branch a `texture2d<short, write>` was decorated
// `Rgba8i`, an 8-bit storage image for a 16-bit texture, so every component a shader
// wrote was truncated to the signed byte range; 5 of the 14579 local corpus sources
// reach it.
if name.contains("<short") {
TextureFormat::Rgba16i
} else {
TextureFormat::Rgba8i
}
}
}
}
+129 -56
View File
@@ -145,25 +145,46 @@ pub(super) fn tokenize(body: &str) -> Vec<Tok> {
out
}
/// Parse an `air.struct_type_info` node into an `AirType::Struct`. Each member is a 5-tuple
/// `i32 offset, i32 size, i32 array_len, !"type", !"name"`, optionally PREFIXED by
/// `!"air.struct_type_info", !N` when the member is itself a nested struct (then recurse into `!N`)
/// and optionally SUFFIXED by `!"air.indirect_argument", !N` naming the argument-buffer entry the
/// member holds (see [`member_holds_resource_handle`]).
pub(super) fn parse_struct_info(
nodes: &HashMap<u32, String>,
id: u32,
depth: u32,
) -> Option<AirType> {
if depth > 16 {
return None;
/// One member of an `air.struct_type_info` node, exactly as AIR spells it.
///
/// AIR writes a member as a 5-tuple `i32 offset, i32 size, i32 array_len, !"type", !"name"`,
/// optionally PREFIXED by `!"air.struct_type_info", !N` naming the member's OWN member list, and
/// optionally SUFFIXED by `!"air.indirect_argument"` plus one operand: a node ref `!N` for a
/// resource handle, or a bare `i32` for an argument-buffer wrapper carrying its own argument id.
pub(super) struct MemberTuple {
pub(super) offset: u32,
/// Per-element declared size. For an array member this is the ELEMENT size, not the total.
pub(super) size: u32,
/// Zero for a scalar member; otherwise the number of elements.
pub(super) array_len: u32,
pub(super) tyname: String,
/// The `!"air.struct_type_info", !N` prefix: this member's own member list.
pub(super) nested: Option<u32>,
/// The `!"air.indirect_argument", !N` suffix: the argument-buffer entry this member holds.
pub(super) argument_node: Option<u32>,
/// The `!"air.indirect_argument", i32 N` suffix: this wrapper's own argument-id base.
pub(super) argument_wrapper_id: Option<u32>,
}
impl MemberTuple {
/// How many bytes the member occupies by AIR's own account, from its declared per-element size
/// and array length. This is what AIR states, not a recomputation from the type name, so it is
/// the quantity two members are compared on to decide whether they overlap.
pub(super) fn declared_extent(&self) -> u64 {
u64::from(self.size) * u64::from(self.array_len.max(1))
}
let body = nodes.get(&id)?;
let toks = tokenize(body);
let mut members = vec![];
}
/// Walk one `air.struct_type_info` node body into its member tuples.
///
/// The single decoder for AIR's member-tuple grammar: [`parse_struct_info`] reads it as a layout
/// and `embedded::collect_argument_members` reads it as a resource list, and they used to walk it
/// separately. `struct_member_starts_at` does NOT treat a suffix as a member start, so scanning to
/// the next member start reads the suffix that belongs to THIS member.
pub(super) fn member_tuples(toks: &[Tok]) -> Vec<MemberTuple> {
let mut out = vec![];
let mut i = 0;
while i < toks.len() {
// Optional nested-struct prefix.
let mut nested = None;
if let (Some(Tok::Str(s)), Some(Tok::Ref(x))) = (toks.get(i), toks.get(i + 1)) {
if s == "air.struct_type_info" {
@@ -171,7 +192,6 @@ pub(super) fn parse_struct_info(
i += 2;
}
}
// Member tuple: offset, size, array_len, type-name (name string follows, ignored).
let (offset, size, array_len, tyname) = match (
toks.get(i),
toks.get(i + 1),
@@ -187,46 +207,79 @@ pub(super) fn parse_struct_info(
_ => break,
};
i += 5; // 3 ints + type + name
// Trailing tokens up to the next member tuple. `!"air.indirect_argument", !N` here binds
// node `!N` to THIS member; `embedded::embedded_argument_members` walks the same suffix to
// surface the resources an argument buffer carries.
let mut argument_node = None;
while i < toks.len() && !struct_member_starts_at(&toks, i) {
if let (Some(Tok::Str(s)), Some(Tok::Ref(x))) = (toks.get(i), toks.get(i + 1)) {
if s == "air.indirect_argument" {
let mut argument_wrapper_id = None;
while i < toks.len() && !struct_member_starts_at(toks, i) {
match (toks.get(i), toks.get(i + 1)) {
(Some(Tok::Str(s)), Some(Tok::Ref(x))) if s == "air.indirect_argument" => {
argument_node = Some(*x);
}
(Some(Tok::Str(s)), Some(Tok::Int(id))) if s == "air.indirect_argument" => {
argument_wrapper_id = Some(*id);
}
_ => {}
}
i += 1;
}
let mut mt = match nested {
Some(x) => {
let nested_ty = parse_struct_info(nodes, x, depth + 1)?;
if nested_offsets_are_strict(&nested_ty) {
nested_ty
} else {
storage_air_type_for_size(size)
out.push(MemberTuple {
offset,
size,
array_len,
tyname,
nested,
argument_node,
argument_wrapper_id,
});
}
out
}
/// Parse an `air.struct_type_info` node into an `AirType::Struct`, one member per
/// [`MemberTuple`], or `None` when the node does not describe storage member-by-member.
///
/// `None` is not a parse failure; it is the answer that AIR's member list cannot be read as a
/// layout, and every caller already has the fact that outranks it -- the enclosing member's
/// declared size, or `air.arg_type_size` for a whole argument. See
/// [`members_are_disjoint`] for the shapes that produce it.
pub(super) fn parse_struct_info(
nodes: &HashMap<u32, String>,
id: u32,
depth: u32,
) -> Option<AirType> {
if depth > 16 {
return None;
}
let body = nodes.get(&id)?;
let tuples = member_tuples(&tokenize(body));
if tuples.is_empty() || !members_are_disjoint(&tuples) {
return None;
}
let members = tuples
.into_iter()
.map(|tuple| {
let mut ty = match tuple.nested {
// A nested node that does not describe storage leaves the member exactly as well
// described as before: AIR stated its size right here in the tuple.
Some(x) => parse_struct_info(nodes, x, depth + 1)
.unwrap_or_else(|| storage_air_type_for_size(tuple.size)),
None if member_holds_resource_handle(nodes, tuple.argument_node) => {
storage_air_type_for_size(tuple.size)
}
}
None if member_holds_resource_handle(nodes, argument_node) => {
storage_air_type_for_size(size)
}
None => member_air_type(&tyname, size),
};
if array_len > 0 {
mt = AirType::Array {
elem: Box::new(mt),
len: array_len,
None => member_air_type(&tuple.tyname, tuple.size),
};
}
members.push(AirMember { offset, ty: mt });
}
if members.is_empty() {
None
} else {
Some(AirType::Struct(members))
}
if tuple.array_len > 0 {
ty = AirType::Array {
elem: Box::new(ty),
len: tuple.array_len,
};
}
AirMember {
offset: tuple.offset,
ty,
}
})
.collect();
Some(AirType::Struct(members))
}
/// True when a member's `air.indirect_argument` node describes a resource the argument buffer
@@ -272,13 +325,33 @@ pub(super) fn struct_member_starts_at(toks: &[Tok], mut i: usize) -> bool {
)
}
fn nested_offsets_are_strict(ty: &AirType) -> bool {
match ty {
AirType::Struct(members) => members
.windows(2)
.all(|pair| pair[1].offset > pair[0].offset),
_ => true,
}
/// Whether a node's members each own their bytes outright.
///
/// AIR states two shapes with overlapping members, and neither is usable as a layout:
///
/// - A **union** gives every member the SAME offset -- `half2 maskCoord` and `half vectorOpacity`
/// both at 0 are two readings of one four-byte run.
/// - A **bitfield** gives each field the offset of the byte its run starts in beside the size of
/// the whole underlying storage unit -- `uint pixel_x` at 0, `uint pixel_y` at 1, `uint matid`
/// at 3, each four bytes wide, is three views of one four-byte word, not a struct reaching to
/// byte seven.
///
/// What settles both is who consumes this layout: [`crate::passes`] builds a SPIR-V struct type
/// from it, and a `Block` cannot decorate two members onto the same bytes. An overlapping member
/// list therefore does not become an overlapping struct -- it makes the emitter give up on the
/// WHOLE buffer and address it as raw words, losing every typed access chain in it, not just the
/// overlapping member. Refusing the node here costs far less: the caller always has the size AIR
/// declared for this member, or `air.arg_type_size` for a whole argument.
///
/// So overlap is the test, at any offset and by any amount. Accepting unions was measured: it
/// re-typed 379 corpus sources and cost `87c1f8ca` its `PKMetalStrokeVertex` access chains,
/// widening a `writeonly` buffer to `ReadWrite`. Requiring a strictly increasing offset instead --
/// which is what this used to do, for nested nodes only -- misses the bitfield, whose offsets do
/// increase strictly while its members still overlap, on 4 corpus sources.
fn members_are_disjoint(tuples: &[MemberTuple]) -> bool {
tuples.windows(2).all(|pair| {
u64::from(pair[0].offset) + pair[0].declared_extent() <= u64::from(pair[1].offset)
})
}
/// Render `size` opaque bytes as a concrete AIR leaf, for the places that must hand a real
+96
View File
@@ -0,0 +1,96 @@
//! Line and operand primitives shared by the pre-emit AIR-text lowerings.
//!
//! Those passes rewrite a call site before [`super::LlModule::parse`] ever sees it, so they work on
//! the raw text and need the same two things: a buffer that joins lines without a trailing blank,
//! and an argument splitter that respects LLVM's nested `<...>` / `(...)` type and constant syntax.
use std::fmt::Write as _;
pub(super) struct LineBuffer {
pub(super) text: String,
has_line: bool,
}
impl LineBuffer {
pub(super) fn with_capacity(capacity: usize) -> Self {
Self {
text: String::with_capacity(capacity),
has_line: false,
}
}
fn begin_line(&mut self) {
if self.has_line {
self.text.push('\n');
}
self.has_line = true;
}
pub(super) fn push(&mut self, line: &str) {
self.begin_line();
self.text.push_str(line);
}
pub(super) fn push_fmt(&mut self, line: std::fmt::Arguments<'_>) {
self.begin_line();
let _ = self.text.write_fmt(line);
}
}
/// Split a call argument list on TOP-LEVEL commas, respecting `<...>` / `(...)` / `[...]` / `{...}`
/// nesting — a constant vector operand `<2 x i64> <i64 8, i64 32>` contains an inner comma that must
/// NOT split the argument, and neither does the `addrspace(1)` in a pointer operand's type.
pub(super) fn split_args(s: &str) -> Vec<String> {
let mut out = Vec::new();
let mut depth = 0i32;
let mut cur = String::new();
for ch in s.chars() {
match ch {
'<' | '(' | '[' | '{' => {
depth += 1;
cur.push(ch);
}
'>' | ')' | ']' | '}' => {
depth -= 1;
cur.push(ch);
}
',' if depth == 0 => {
out.push(cur.trim().to_string());
cur.clear();
}
_ => cur.push(ch),
}
}
if !cur.trim().is_empty() {
out.push(cur.trim().to_string());
}
out
}
/// The last whitespace token of an operand — its value, past the type and any
/// `noundef`/`readonly`/`align N`/`captures(none)` attributes between them.
pub(super) fn last_token(arg: &str) -> &str {
arg.trim().rsplit(' ').next().unwrap_or("")
}
/// The argument list of a call line: the text between the LAST balanced top-level paren group's
/// delimiters. `find('(')` alone would land inside the callee's `addrspace(3)`-style type parens,
/// and `rfind(')')` alone would run past the `#N` attribute group and `!noalias` metadata that
/// follow the call.
pub(super) fn call_arguments(line: &str) -> Option<&str> {
let open = line.find('(')?;
let mut depth = 0i32;
for (offset, ch) in line[open..].char_indices() {
match ch {
'(' => depth += 1,
')' => {
depth -= 1;
if depth == 0 {
return Some(&line[open + 1..open + offset]);
}
}
_ => {}
}
}
None
}
+3 -70
View File
@@ -20,7 +20,7 @@
//! on a module that CALLS `air.simdgroup_async_copy_2d` — a module the emitter rejects outright today
//! (`unhandled air.* intrinsic`), so nothing that emits today is altered.
use std::fmt::Write as _;
use super::air_text::{split_args, LineBuffer};
/// The 12-operand `air.simdgroup_async_copy_2d` call, decoded from its argument list.
struct AsyncCopyCall {
@@ -131,37 +131,6 @@ pub(crate) fn lower_simdgroup_async_copy_owned(san_ll: String) -> String {
}
}
struct LineBuffer {
text: String,
has_line: bool,
}
impl LineBuffer {
fn with_capacity(capacity: usize) -> Self {
Self {
text: String::with_capacity(capacity),
has_line: false,
}
}
fn begin_line(&mut self) {
if self.has_line {
self.text.push('\n');
}
self.has_line = true;
}
fn push(&mut self, line: &str) {
self.begin_line();
self.text.push_str(line);
}
fn push_fmt(&mut self, line: std::fmt::Arguments<'_>) {
self.begin_line();
let _ = self.text.write_fmt(line);
}
}
/// Emit the extractelements + helper call replacing one async-copy call. `%result` is kept as a dummy
/// non-null pointer so downstream `store ptr %result` / event plumbing stays well-typed.
fn emit_copy_call(out: &mut LineBuffer, indent: &str, call: &AsyncCopyCall, fresh: &mut u64) {
@@ -269,13 +238,7 @@ fn parse_async_copy(line: &str) -> Option<AsyncCopyCall> {
if !result.starts_with('%') {
return None;
}
// The argument list is delimited by the call's OUTER parens. `rfind(')')` is the closing paren
// (the `#N` attribute group and `!noalias` metadata follow it), and `find('(')` skips the callee's
// `addrspace(3)`-style type parens because it lands on the first `(` — which is inside a type; use
// the LAST balanced top-level paren group instead.
let open = line.find('(')?;
let args_str = &line[open + 1..line.rfind(')')?];
let args = split_args(args_str);
let args = split_args(super::air_text::call_arguments(line)?);
if args.len() != 12 {
return None;
}
@@ -293,36 +256,6 @@ fn parse_async_copy(line: &str) -> Option<AsyncCopyCall> {
})
}
/// Split a call argument list on TOP-LEVEL commas, respecting `<...>` / `(...)` / `[...]` / `{...}`
/// nesting — a constant vector operand `<2 x i64> <i64 8, i64 32>` contains an inner comma that must
/// NOT split the argument.
fn split_args(s: &str) -> Vec<String> {
let mut out = Vec::new();
let mut depth = 0i32;
let mut cur = String::new();
for ch in s.chars() {
match ch {
'<' | '(' | '[' | '{' => {
depth += 1;
cur.push(ch);
}
'>' | ')' | ']' | '}' => {
depth -= 1;
cur.push(ch);
}
',' if depth == 0 => {
out.push(cur.trim().to_string());
cur.clear();
}
_ => cur.push(ch),
}
}
if !cur.trim().is_empty() {
out.push(cur.trim().to_string());
}
out
}
/// The VALUE of a `<type> <value>` LLVM operand. A `<2 x i64>` vector operand's value is everything
/// after that type token (a `%reg`, a `<i64 8, i64 32>` constant, or a `splat (i64 32)` constant); a
/// scalar / pointer operand's value is its last whitespace token (past any `noundef`/`readonly`/
@@ -332,7 +265,7 @@ fn operand_value(arg: &str) -> String {
if let Some(rest) = a.strip_prefix("<2 x i64>") {
return rest.trim().to_string();
}
a.rsplit(' ').next().unwrap_or("").to_string()
super::air_text::last_token(a).to_string()
}
/// The `%id` result of a `%id = call ...` line, if any.
+18
View File
@@ -1039,6 +1039,24 @@ pub(in crate::native) fn switch_default_is_inferred_merge(blocks: &[BodyBlock])
})
}
/// Switch-merge inference for a CFG the structured planner declined, keyed on the cost driver the
/// complete inference actually has: block count. `infer_switch_merges` scans every later block as a
/// merge candidate and proves reconvergence per switch arm, so its cost grows with the graph, not
/// with why the planner stopped. The planner is skipped for two different reasons — a graph over
/// `CROSS_ARM_EDGE_MAX_BLOCKS`, and a graph whose *branching density* exceeds the local ownership
/// work budget — and only the first makes the complete inference expensive. A dense but small CFG
/// keeps it: downgrading there costs the switch its merge and sends the whole module to raw-buffer
/// construction, without saving work the planner skip was protecting.
pub(in crate::native) fn infer_switch_merges_bounded(
blocks: &[BodyBlock],
) -> HashMap<String, String> {
if blocks.len() > crate::native::cfg::CROSS_ARM_EDGE_MAX_BLOCKS {
infer_direct_switch_merges(blocks)
} else {
infer_switch_merges(blocks)
}
}
/// Infer only switches whose live targets are the merge itself or branch directly to one common
/// merge. This linear-time subset is used when a rejected function is too large for the complete
/// structured planner and the transitive-closure switch heuristic. It never guesses through an
+31
View File
@@ -91,6 +91,37 @@ mod tests {
}
}
#[test]
fn clone_source_name_inverts_fresh() {
for original in [
"%1",
"%cont",
"%metal2vulkan.helper.5.3.param.1",
"%xa7_already_a_clone",
] {
for id in [
0usize,
7,
DEEP_SHARED_COUNTER_START,
SWITCH_CASE_COUNTER_START,
] {
assert_eq!(
clone_source_name(&fresh(original, id)).as_deref(),
Some(original),
"fresh({original}, {id}) does not invert"
);
}
}
// A name the clone never minted is not a clone, whatever it starts with.
for ordinary in ["%1", "%xa_1", "%xax7_1", "%xa7", "%metal2vulkan.uret", "%x"] {
assert_eq!(
clone_source_name(ordinary),
None,
"{ordinary} is not a clone"
);
}
}
#[test]
fn rename_is_boundary_aware() {
let mut map = HashMap::new();
@@ -153,6 +153,19 @@ pub(in crate::native) fn fresh(orig: &str, id: usize) -> String {
format!("%xa{id}_{stripped}")
}
/// The name [`fresh`] was given, for a name it produced.
///
/// Cloning renames every value it duplicates, and the emitter carries several facts about a value
/// keyed by NAME -- which buffer parameter is addressed as raw words, above all. Those facts are
/// derived before the CFG is structured, so nothing re-keys them onto the clone and the clone
/// silently has none. Rather than thread a rename map out of three call sites and up through the
/// planner, ask the name: this is the exact inverse of `fresh`, held by
/// `clone_source_name_inverts_fresh`.
pub(in crate::native) fn clone_source_name(cloned: &str) -> Option<String> {
let (id, original) = cloned.strip_prefix("%xa")?.split_once('_')?;
(!id.is_empty() && id.bytes().all(|byte| byte.is_ascii_digit())).then(|| format!("%{original}"))
}
/// LLVM's textual block labels and SSA values can carry the same spelling in AIR. A whole-token
/// rename map cannot distinguish those namespaces, so a clone must decline when one of its labels
/// is also used or defined as an SSA value anywhere in the function. Another structurization path
+3 -4
View File
@@ -46,11 +46,10 @@ impl EmittedDominators {
}
}
}
let predecessors = crate::native::dominators::build_predecessors(&successors);
let predecessors = crate::dominators::build_predecessors(&successors);
// Underscore-prefixed because the parent links are only read by the serialization-order
// check, which is test-only; the intervals are what production queries.
let (_, intervals, _parents) =
crate::native::dominators::dominance(&successors, &predecessors);
let (_, intervals, _parents) = crate::dominators::dominance(&successors, &predecessors);
Self {
index,
#[cfg(test)]
@@ -64,7 +63,7 @@ impl EmittedDominators {
else {
return false;
};
crate::native::dominators::dominates_interval(&self.intervals, dominator, node)
crate::dominators::dominates_interval(&self.intervals, dominator, node)
}
/// Whether every reachable block's immediate dominator precedes it in serialized block order.
+3 -62
View File
@@ -11,9 +11,6 @@
use super::blocks::block_successors;
use super::BodyBlock;
use crate::spirv_module::Block;
use crate::spirv_module::Operand;
use spirv::{Op, Word};
use std::collections::{HashMap, HashSet};
// How many source CFGs this thread has built, for the redundant-work regression checks.
@@ -179,8 +176,8 @@ pub(super) fn named_dominators<'a>(
.collect()
})
.collect();
let predecessors = crate::native::dominators::build_predecessors(&dense);
let (_, intervals, parents) = crate::native::dominators::dominance(&dense, &predecessors);
let predecessors = crate::dominators::build_predecessors(&dense);
let (_, intervals, parents) = crate::dominators::dominance(&dense, &predecessors);
let named_idom = parents
.iter()
.enumerate()
@@ -328,63 +325,7 @@ pub(super) fn reachable_from(
// layer; the passes-side copies stay separate because the passes layer must not depend on `native`
// (that dependency would invert ownership). Behaviour is identical to the copies they replace.
/// Successor block labels of one owned `Block`, read from its terminator. Branch/BranchConditional
/// arms in operand order; switch default + case targets sorted and deduped. Non-terminating or
/// unstructured-terminator blocks yield no successors.
pub(in crate::native) fn spirv_block_successors(block: &Block) -> Vec<Word> {
fn id_ref(operand: &Operand) -> Option<Word> {
match operand {
Operand::IdRef(id) => Some(*id),
_ => None,
}
}
let Some(inst) = block.instructions.last() else {
return Vec::new();
};
match inst.class.opcode {
Op::Branch => inst.operands.first().and_then(id_ref).into_iter().collect(),
Op::BranchConditional => inst
.operands
.iter()
.skip(1)
.take(2)
.filter_map(id_ref)
.collect(),
Op::Switch => {
let mut out = Vec::new();
if let Some(default) = inst.operands.get(1).and_then(id_ref) {
out.push(default);
}
let mut idx = 3;
while idx < inst.operands.len() {
if let Some(target) = inst.operands.get(idx).and_then(id_ref) {
out.push(target);
}
idx += 2;
}
out.sort_unstable();
out.dedup();
out
}
_ => Vec::new(),
}
}
/// Forward-edge adjacency of an owned SPIR-V function body keyed by block label id
/// (via [`spirv_block_successors`]). Blocks without a label id are skipped.
pub(in crate::native) fn spirv_block_successors_by_label(
blocks: &[Block],
) -> HashMap<Word, Vec<Word>> {
blocks
.iter()
.filter_map(|block| {
Some((
block.label.as_ref()?.result_id?,
spirv_block_successors(block),
))
})
.collect()
}
pub(in crate::native) use crate::spirv_module::block_successors_by_label as spirv_block_successors_by_label;
#[cfg(test)]
mod tests {
+8 -3
View File
@@ -18,6 +18,11 @@ pub(super) mod structured_order;
pub(super) use clone_crossarm::rename_tokens;
pub(in crate::native) use exit_check::EmittedDominators;
/// Whether the source CFG has no natural loop at all.
pub(super) fn loop_forest_is_empty(blocks: &[BodyBlock]) -> bool {
loopforest::analyze(blocks).loops.is_empty()
}
pub(super) use structured_emit::{
cond_other_witness_lines, cond_phi_shared_witness_lines, construct_tree_gate_witness_lines,
construct_tree_reject_reason, exceeds_local_structured_plan_budget,
@@ -28,16 +33,16 @@ pub(super) use structured_emit::{
structured_reject_reason, CROSS_ARM_EDGE_MAX_BLOCKS,
};
#[cfg(test)]
pub(super) use blocks::split_body_blocks;
pub(super) use blocks::{
funnel_shared_branch_dispatches, implicit_entry_block_name, index_branch_merges_by_header,
infer_bounded_branch_merges_by_header, infer_branch_merges, infer_direct_branch_merges,
infer_direct_switch_merges, infer_loop_merges, infer_switch_merges,
infer_loop_merges, infer_switch_merges, infer_switch_merges_bounded,
lower_unstructured_switches, refunnel_one_deep_shared_arm, split_source_body_blocks,
switch_default_is_inferred_merge,
};
#[cfg(test)]
pub(super) use blocks::{infer_direct_switch_merges, split_body_blocks};
#[cfg(test)]
pub(super) fn id_ref_operand(operand: &crate::spirv_module::Operand) -> Option<spirv::Word> {
let crate::spirv_module::Operand::IdRef(id) = operand else {
return None;
@@ -6,8 +6,9 @@
//! current source CFG rather than matching workload identities.
use super::{
analyze, block_successors, conditional_branch_targets, synthetic_block, BlockRole, BodyBlock,
StructuredPlan, CROSS_ARM_EDGE_MAX_BLOCKS,
analyze, block_successors, collect_value_locals, conditional_branch_targets, passthrough,
route_passthrough, substitute_cross_slot_value, synthetic_block, BlockRole, BodyBlock,
StructuredPlan, ValueSlot, CROSS_ARM_EDGE_MAX_BLOCKS,
};
use std::collections::{HashMap, HashSet};
@@ -37,15 +37,6 @@ struct PhiSlot {
next: String,
}
#[derive(Clone, Debug)]
struct ValueSlot {
ty: LlType,
owner: usize,
original: String,
current: String,
next: String,
}
#[derive(Clone, Debug)]
struct HeaderPointerDerivation {
owner: usize,
@@ -198,22 +189,6 @@ fn dominating_pointer_derivations(
(names, instructions)
}
fn passthrough(name: &str, target: &str) -> BodyBlock {
synthetic_block(
name.to_string(),
vec![format!("br label {target}")],
BlockRole::Normal,
)
}
fn route_passthrough(name: &str, target: &str) -> BodyBlock {
synthetic_block(
name.to_string(),
vec![format!("br label {target}")],
BlockRole::ConstructTreeRoute,
)
}
fn carrier_with_phis(
name: &str,
target: &str,
@@ -237,81 +212,6 @@ fn renamed_value(value: &LlValue, map: &HashMap<String, String>) -> LlValue {
tir::renamed_llvalue(value, map)
}
fn collect_value_locals(value: &LlValue, out: &mut Vec<String>) {
match value {
LlValue::Local(name) => out.push(name.clone()),
LlValue::Vector(values) | LlValue::Array(values) | LlValue::Struct(values) => {
for value in values {
collect_value_locals(&value.value, out);
}
}
LlValue::Splat(value) => collect_value_locals(&value.value, out),
LlValue::Gep(gep) => {
collect_value_locals(&gep.base.value, out);
for index in &gep.indices {
collect_value_locals(&index.value, out);
}
}
LlValue::IntToPtr { source, .. } => collect_value_locals(&source.value, out),
LlValue::Global(_)
| LlValue::Bool(_)
| LlValue::Int(_)
| LlValue::SignedInt(_)
| LlValue::Hex(_)
| LlValue::Float(_)
| LlValue::Float32Bits(_)
| LlValue::HalfBits(_)
| LlValue::BFloatBits(_)
| LlValue::Zero
| LlValue::Undef => {}
}
}
fn substitute_cross_slot_value(
value: &mut LlValue,
value_slots: &HashMap<&str, &ValueSlot>,
source: usize,
) {
match value {
LlValue::Local(name) => {
let Some(slot) = value_slots.get(name.as_str()) else {
return;
};
if slot.owner != source {
*value = LlValue::Local(slot.current.clone());
}
}
LlValue::Vector(values) | LlValue::Array(values) | LlValue::Struct(values) => {
for value in values {
substitute_cross_slot_value(&mut value.value, value_slots, source);
}
}
LlValue::Splat(value) => {
substitute_cross_slot_value(&mut value.value, value_slots, source);
}
LlValue::Gep(gep) => {
substitute_cross_slot_value(&mut gep.base.value, value_slots, source);
for index in &mut gep.indices {
substitute_cross_slot_value(&mut index.value, value_slots, source);
}
}
LlValue::IntToPtr {
source: operand, ..
} => substitute_cross_slot_value(&mut operand.value, value_slots, source),
LlValue::Global(_)
| LlValue::Bool(_)
| LlValue::Int(_)
| LlValue::SignedInt(_)
| LlValue::Hex(_)
| LlValue::Float(_)
| LlValue::Float32Bits(_)
| LlValue::HalfBits(_)
| LlValue::BFloatBits(_)
| LlValue::Zero
| LlValue::Undef => {}
}
}
fn terminator_value_uses(terminator: &tir::TirTerminator) -> Vec<String> {
match terminator {
tir::TirTerminator::Br(_)
@@ -0,0 +1,132 @@
//! State-slot and gateway-block primitives shared by the three dispatch materializers.
//!
//! `straddle_region`, `own_arm` and `construct_tree::renest` each build the same thing: a set of
//! typed state slots carried across a synthesized dispatch, and the pass-through / phi-carrying
//! gateway blocks that route between them. Each used to carry its own byte-identical copy of the
//! slot record and of the four `LlValue` walkers over it, so a new `LlValue` variant had to be
//! taught to all of them or one materializer would silently drop it. They are one definition here.
use super::*;
use crate::native::ir::{LlType, LlValue};
use crate::native::tir;
use std::collections::HashMap;
#[derive(Clone, Debug)]
pub(in crate::native) struct ValueSlot {
pub(in crate::native) ty: LlType,
pub(in crate::native) owner: usize,
pub(in crate::native) original: String,
pub(in crate::native) current: String,
pub(in crate::native) next: String,
}
pub(in crate::native) fn typed_state_type(ty: &LlType) -> bool {
match ty {
LlType::Void | LlType::Ptr(_) | LlType::Named(_) => false,
LlType::Vector(element, _) | LlType::Array(element, _) => typed_state_type(element),
LlType::Struct(fields) => fields.iter().all(typed_state_type),
LlType::Bool | LlType::Float | LlType::Half | LlType::BFloat | LlType::Int(_) => true,
}
}
pub(in crate::native) fn passthrough(name: &str, target: &str) -> BodyBlock {
synthetic_block(
name.to_string(),
vec![format!("br label {target}")],
BlockRole::Normal,
)
}
pub(in crate::native) fn route_passthrough(name: &str, target: &str) -> BodyBlock {
synthetic_block(
name.to_string(),
vec![format!("br label {target}")],
BlockRole::ConstructTreeRoute,
)
}
pub(in crate::native) fn collect_value_locals(value: &LlValue, out: &mut Vec<String>) {
match value {
LlValue::Local(name) => out.push(name.clone()),
LlValue::Vector(values) | LlValue::Array(values) | LlValue::Struct(values) => {
for value in values {
collect_value_locals(&value.value, out);
}
}
LlValue::Splat(value) => collect_value_locals(&value.value, out),
LlValue::Gep(gep) => {
collect_value_locals(&gep.base.value, out);
for index in &gep.indices {
collect_value_locals(&index.value, out);
}
}
LlValue::IntToPtr { source, .. } => collect_value_locals(&source.value, out),
LlValue::Global(_)
| LlValue::Bool(_)
| LlValue::Int(_)
| LlValue::SignedInt(_)
| LlValue::Hex(_)
| LlValue::Float(_)
| LlValue::Float32Bits(_)
| LlValue::HalfBits(_)
| LlValue::BFloatBits(_)
| LlValue::Zero
| LlValue::Undef => {}
}
}
pub(in crate::native) fn substitute_cross_slot_value(
value: &mut LlValue,
value_slots: &HashMap<&str, &ValueSlot>,
source: usize,
) {
match value {
LlValue::Local(name) => {
let Some(slot) = value_slots.get(name.as_str()) else {
return;
};
if slot.owner != source {
*value = LlValue::Local(slot.current.clone());
}
}
LlValue::Vector(values) | LlValue::Array(values) | LlValue::Struct(values) => {
for value in values {
substitute_cross_slot_value(&mut value.value, value_slots, source);
}
}
LlValue::Splat(value) => {
substitute_cross_slot_value(&mut value.value, value_slots, source);
}
LlValue::Gep(gep) => {
substitute_cross_slot_value(&mut gep.base.value, value_slots, source);
for index in &mut gep.indices {
substitute_cross_slot_value(&mut index.value, value_slots, source);
}
}
LlValue::IntToPtr {
source: operand, ..
} => substitute_cross_slot_value(&mut operand.value, value_slots, source),
LlValue::Global(_)
| LlValue::Bool(_)
| LlValue::Int(_)
| LlValue::SignedInt(_)
| LlValue::Hex(_)
| LlValue::Float(_)
| LlValue::Float32Bits(_)
| LlValue::HalfBits(_)
| LlValue::BFloatBits(_)
| LlValue::Zero
| LlValue::Undef => {}
}
}
pub(in crate::native) fn terminator_uses(carrier: &tir::TirBlock) -> Vec<String> {
match &carrier.terminator {
tir::TirTerminator::Br(_)
| tir::TirTerminator::Ret(None)
| tir::TirTerminator::Unreachable => Vec::new(),
tir::TirTerminator::BrCond { cond, .. }
| tir::TirTerminator::Switch { selector: cond, .. }
| tir::TirTerminator::Ret(Some(cond)) => vec![cond.clone()],
}
}
+2
View File
@@ -55,6 +55,8 @@ mod selection_merge;
pub(in crate::native) use selection_merge::*;
mod multi_exit;
pub(in crate::native) use multi_exit::*;
mod dispatch_state;
pub(in crate::native) use dispatch_state::*;
mod phi_util;
pub(in crate::native) use phi_util::*;
mod rewrite;
-17
View File
@@ -38,23 +38,6 @@ struct Witness {
local_of: HashMap<usize, usize>,
}
fn typed_state_type(ty: &LlType) -> bool {
match ty {
LlType::Void | LlType::Ptr(_) | LlType::Named(_) => false,
LlType::Vector(element, _) | LlType::Array(element, _) => typed_state_type(element),
LlType::Struct(fields) => fields.iter().all(typed_state_type),
LlType::Bool | LlType::Float | LlType::Half | LlType::BFloat | LlType::Int(_) => true,
}
}
fn passthrough(name: &str, target: &str) -> BodyBlock {
synthetic_block(
name.to_string(),
vec![format!("br label {target}")],
BlockRole::Normal,
)
}
fn carrier_with_phis(
name: &str,
target: &str,
@@ -1469,17 +1469,6 @@ fn collect_llvalue_locals(value: &crate::native::ir::LlValue, out: &mut Vec<Stri
}
}
fn terminator_uses(carrier: &crate::native::tir::TirBlock) -> Vec<String> {
match &carrier.terminator {
crate::native::tir::TirTerminator::Br(_)
| crate::native::tir::TirTerminator::Ret(None)
| crate::native::tir::TirTerminator::Unreachable => Vec::new(),
crate::native::tir::TirTerminator::BrCond { cond, .. }
| crate::native::tir::TirTerminator::Switch { selector: cond, .. }
| crate::native::tir::TirTerminator::Ret(Some(cond)) => vec![cond.clone()],
}
}
fn multilevel_break_switch_witnesses(blocks: &[BodyBlock]) -> Vec<String> {
let forest = analyze(blocks);
let mut out = Vec::new();
@@ -53,15 +53,6 @@ struct PhiSlot {
next: String,
}
#[derive(Clone, Debug)]
struct ValueSlot {
ty: LlType,
owner: usize,
original: String,
current: String,
next: String,
}
#[derive(Clone, Debug)]
struct ExitPayloadSlot {
ty: LlType,
@@ -90,31 +81,6 @@ struct CaseUpdate {
exit_payload_slots: Vec<LlValue>,
}
fn typed_state_type(ty: &LlType) -> bool {
match ty {
LlType::Void | LlType::Ptr(_) | LlType::Named(_) => false,
LlType::Vector(element, _) | LlType::Array(element, _) => typed_state_type(element),
LlType::Struct(fields) => fields.iter().all(typed_state_type),
LlType::Bool | LlType::Float | LlType::Half | LlType::BFloat | LlType::Int(_) => true,
}
}
fn passthrough(name: &str, target: &str) -> BodyBlock {
synthetic_block(
name.to_string(),
vec![format!("br label {target}")],
BlockRole::Normal,
)
}
fn route_passthrough(name: &str, target: &str) -> BodyBlock {
synthetic_block(
name.to_string(),
vec![format!("br label {target}")],
BlockRole::ConstructTreeRoute,
)
}
fn carrier_with_phis(
name: &str,
target: &str,
@@ -134,92 +100,6 @@ fn carrier_with_phis(
})
}
fn collect_value_locals(value: &LlValue, out: &mut Vec<String>) {
match value {
LlValue::Local(name) => out.push(name.clone()),
LlValue::Vector(values) | LlValue::Array(values) | LlValue::Struct(values) => {
for value in values {
collect_value_locals(&value.value, out);
}
}
LlValue::Splat(value) => collect_value_locals(&value.value, out),
LlValue::Gep(gep) => {
collect_value_locals(&gep.base.value, out);
for index in &gep.indices {
collect_value_locals(&index.value, out);
}
}
LlValue::IntToPtr { source, .. } => collect_value_locals(&source.value, out),
LlValue::Global(_)
| LlValue::Bool(_)
| LlValue::Int(_)
| LlValue::SignedInt(_)
| LlValue::Hex(_)
| LlValue::Float(_)
| LlValue::Float32Bits(_)
| LlValue::HalfBits(_)
| LlValue::BFloatBits(_)
| LlValue::Zero
| LlValue::Undef => {}
}
}
fn substitute_cross_slot_value(
value: &mut LlValue,
value_slots: &HashMap<&str, &ValueSlot>,
source: usize,
) {
match value {
LlValue::Local(name) => {
let Some(slot) = value_slots.get(name.as_str()) else {
return;
};
if slot.owner != source {
*value = LlValue::Local(slot.current.clone());
}
}
LlValue::Vector(values) | LlValue::Array(values) | LlValue::Struct(values) => {
for value in values {
substitute_cross_slot_value(&mut value.value, value_slots, source);
}
}
LlValue::Splat(value) => {
substitute_cross_slot_value(&mut value.value, value_slots, source);
}
LlValue::Gep(gep) => {
substitute_cross_slot_value(&mut gep.base.value, value_slots, source);
for index in &mut gep.indices {
substitute_cross_slot_value(&mut index.value, value_slots, source);
}
}
LlValue::IntToPtr {
source: operand, ..
} => substitute_cross_slot_value(&mut operand.value, value_slots, source),
LlValue::Global(_)
| LlValue::Bool(_)
| LlValue::Int(_)
| LlValue::SignedInt(_)
| LlValue::Hex(_)
| LlValue::Float(_)
| LlValue::Float32Bits(_)
| LlValue::HalfBits(_)
| LlValue::BFloatBits(_)
| LlValue::Zero
| LlValue::Undef => {}
}
}
fn terminator_uses(carrier: &tir::TirBlock) -> Vec<String> {
match &carrier.terminator {
tir::TirTerminator::Br(_)
| tir::TirTerminator::Ret(None)
| tir::TirTerminator::Unreachable => Vec::new(),
tir::TirTerminator::BrCond { cond, .. }
| tir::TirTerminator::Switch { selector: cond, .. }
| tir::TirTerminator::Ret(Some(cond)) => vec![cond.clone()],
}
}
fn derive_witness(blocks: &[BodyBlock], reject_reason: Option<&str>) -> Option<Witness> {
if reject_reason != Some("selection:straddle-loop-merge") {
return None;
+19
View File
@@ -359,6 +359,25 @@ impl CfgBuilder {
));
}
/// Declare the current block the header of a selection construct merging at `merge`.
///
/// Call it immediately before the divergent terminator, which is where SPIR-V requires the
/// `OpSelectionMerge` to sit. Authoring an explicit merge is what lets a shape be *owned* and
/// still badly nested — an arm leaving the construct through a block that is not the merge —
/// which is a distinct failure from having no owner at all.
pub(in crate::native) fn selection_merge(&mut self, merge: &str) {
let merge = self.label(merge);
self.push(Instruction::new(
Op::SelectionMerge,
None,
None,
vec![
Operand::IdRef(merge),
Operand::SelectionControl(spirv::SelectionControl::NONE),
],
));
}
pub(in crate::native) fn branch_conditional(
&mut self,
condition: Word,
+67
View File
@@ -528,6 +528,73 @@ fn constructed_shapes_survive_a_binary_round_trip_unchanged() {
}
}
/// A function whose entry selection is OWNED and badly nested, the shape helper inlining leaves
/// behind.
///
/// The helper's `if (c) return;` was structured with the early arm terminating the function, so the
/// selection's merge is legitimately its other arm. Inlining rewrites that `OpReturn` into a branch
/// to the caller's continuation, and the arm now leaves the construct through a block that is not
/// the merge — while the `OpSelectionMerge` that named the merge stays exactly where it was.
fn early_return_inlined_past_its_merge() -> crate::spirv_module::Module {
let mut builder = CfgBuilder::new(1);
let one = builder.constant(1);
let seven = builder.constant(7);
let hundred = builder.constant(100);
builder.block("entry");
let argument = builder.parameter(0);
let low_bit = builder.bitwise_and(argument, one);
let taken = builder.equal(low_bit, one);
builder.selection_merge("body");
builder.branch_conditional(taken, "early", "body");
// The inlined early return: a branch to the continuation instead of `OpReturn`.
builder.block("early");
builder.branch("exit");
builder.block("body");
let computed = builder.add(argument, hundred);
builder.branch("exit");
builder.block("exit");
let result = builder.phi(&[(seven, "early"), (computed, "body")]);
builder.return_value(result);
builder.finish()
}
/// Selecting functions for reconstruction on a MISSING owner alone cannot see a construct that is
/// owned and badly nested, so this module used to reach the owned gate broken — and a whole shader
/// then fell to the raw-buffer rebuild, which retypes every storage buffer as words.
#[test]
fn a_selection_arm_that_leaves_its_construct_is_reconstructed() {
let module = early_return_inlined_past_its_merge();
let before = construction_error(&module).expect("the authored nesting is badly nested");
assert!(
before.contains("enters a construct outside its header"),
"{before}"
);
let constructed = assert_construction_preserves_semantics(module, ARGUMENTS);
assert_eq!(
construction_error(&constructed),
None,
"construction left the function badly nested"
);
}
/// The owned-contract verdict a control-flow rewrite is answerable for, asked of the authored
/// function directly. The module-wide gate reports section-layout prerequisites first — an authored
/// bare function declares no capability — and those are not what construction owns.
fn construction_error(module: &crate::spirv_module::Module) -> Option<String> {
let value_types = module
.all_inst_iter()
.filter_map(|instruction| Some((instruction.result_id?, instruction.result_type?)))
.collect::<std::collections::HashMap<_, _>>();
module.functions.iter().find_map(|function| {
crate::native::owned_cfg::owned_function_construction_error(function, &value_types)
})
}
fn assemble(module: &crate::spirv_module::Module) -> Vec<u8> {
module
.assemble()
+50 -8
View File
@@ -70,15 +70,19 @@ pub(in crate::native) fn value_int_widths(module: &Module) -> HashMap<Word, u32>
}
}
}
// Module-scope constants are values with an integer type as much as instruction results are,
// and a fold over a comparison of two of them needs their width to know where the sign bit is.
let mut out: HashMap<Word, u32> = HashMap::new();
for f in &module.functions {
for b in &f.blocks {
for inst in &b.instructions {
if let (Some(rid), Some(t)) = (inst.result_id, inst.result_type) {
if let Some(w) = type_width.get(&t) {
out.insert(rid, *w);
}
}
for inst in module.types_global_values.iter().chain(
module
.functions
.iter()
.flat_map(|f| f.blocks.iter())
.flat_map(|b| b.instructions.iter()),
) {
if let (Some(rid), Some(t)) = (inst.result_id, inst.result_type) {
if let Some(w) = type_width.get(&t) {
out.insert(rid, *w);
}
}
}
@@ -426,3 +430,41 @@ pub(in crate::native) fn numworkgroups_vars(module: &Module) -> HashSet<Word> {
})
.collect()
}
/// Every value id whose type is a vector of booleans -- the ids that may appear as an `OpSelect`
/// condition selecting PER LANE. The scalar constant lattice cannot describe one, so a caller that
/// reads a condition out of it must exclude these.
pub(in crate::native) fn bool_vector_valued_ids(module: &Module) -> HashSet<Word> {
let bool_types: HashSet<Word> = module
.types_global_values
.iter()
.filter(|inst| inst.class.opcode == Op::TypeBool)
.filter_map(|inst| inst.result_id)
.collect();
let bool_vectors: HashSet<Word> = module
.types_global_values
.iter()
.filter(|inst| inst.class.opcode == Op::TypeVector)
.filter(|inst| match inst.operands.first() {
Some(Operand::IdRef(element)) => bool_types.contains(element),
_ => false,
})
.filter_map(|inst| inst.result_id)
.collect();
module
.types_global_values
.iter()
.chain(
module
.functions
.iter()
.flat_map(|function| function.blocks.iter())
.flat_map(|block| block.instructions.iter()),
)
.filter(|inst| {
inst.result_type
.is_some_and(|ty| bool_vectors.contains(&ty))
})
.filter_map(|inst| inst.result_id)
.collect()
}
+31 -4
View File
@@ -142,23 +142,50 @@ pub(in crate::native) fn forward_eval(
Op::ULessThan => ucmp_fold(
get(&lat, inst.operands.first()),
get(&lat, inst.operands.get(1)),
UCmp::Lt,
Cmp::Lt,
),
Op::UGreaterThan => ucmp_fold(
get(&lat, inst.operands.first()),
get(&lat, inst.operands.get(1)),
UCmp::Gt,
Cmp::Gt,
),
Op::ULessThanEqual => ucmp_fold(
get(&lat, inst.operands.first()),
get(&lat, inst.operands.get(1)),
UCmp::Le,
Cmp::Le,
),
Op::UGreaterThanEqual => ucmp_fold(
get(&lat, inst.operands.first()),
get(&lat, inst.operands.get(1)),
UCmp::Ge,
Cmp::Ge,
),
// The signed twins of the four unsigned comparisons above. Leaving them out
// left `OpSGreaterThan %uint_0 %uint_0` -- a comparison of one constant with
// itself -- opaque, and with it every branch and select it fed.
Op::SLessThan
| Op::SGreaterThan
| Op::SLessThanEqual
| Op::SGreaterThanEqual => {
let operand_width =
inst.operands
.iter()
.take(2)
.find_map(|operand| match operand {
Operand::IdRef(id) => widths.get(id).copied(),
_ => None,
});
scmp_fold(
get(&lat, inst.operands.first()),
get(&lat, inst.operands.get(1)),
operand_width,
match inst.class.opcode {
Op::SLessThan => Cmp::Lt,
Op::SGreaterThan => Cmp::Gt,
Op::SLessThanEqual => Cmp::Le,
_ => Cmp::Ge,
},
)
}
Op::LogicalNot => match get(&lat, inst.operands.first()) {
Some(Lat::Const(a)) => Some(Lat::Const((a == 0) as i128)),
Some(Lat::Bottom) => Some(Lat::Bottom),
+212
View File
@@ -37,6 +37,7 @@ mod tests {
use crate::spirv_module::Operand;
use crate::spirv_module::{Block, Function, Instruction, Module, ModuleHeader};
use spirv::{Op, StorageClass, Word};
use std::collections::HashMap;
fn inst(op: Op, ty: Option<Word>, res: Option<Word>, ops: Vec<Operand>) -> Instruction {
Instruction::new(op, ty, res, ops)
@@ -186,6 +187,217 @@ mod tests {
assert_eq!(m.debug_names[0].operands[0], Operand::IdRef(39));
}
// The corpus shape this fold exists for: an `MTL_FC_DEFINED` gate lowers to
// `OpSelect %bool %runtime %true %true`, whose two arms are the SAME constant. The condition is
// a runtime value, so the SCCP lattice can say nothing about it -- but the select's result is
// `true` on either edge, which makes the branch below it static and its else-arm dead. Without
// the collapse the select is opaque, the branch survives and the whole gated arm ships.
#[test]
fn collapses_an_identical_arm_select_and_prunes_the_arm_it_gates() {
// ids: uint=1 bool=2 ptrPrivUint=3 | uint_0=10 true=11 null=12 | runtime_global=20
// labels: entry=30 taken=34 dead=35 merge=36
let mut m = Module::new();
m.header = Some(ModuleHeader::new(40));
m.types_global_values = vec![
inst(
Op::TypeInt,
None,
Some(1),
vec![Operand::LiteralBit32(32), Operand::LiteralBit32(0)],
),
inst(Op::TypeBool, None, Some(2), vec![]),
inst(
Op::TypePointer,
None,
Some(3),
vec![
Operand::StorageClass(StorageClass::Private),
Operand::IdRef(1),
],
),
inst(
Op::Constant,
Some(1),
Some(10),
vec![Operand::LiteralBit32(0)],
),
inst(Op::ConstantTrue, Some(2), Some(11), vec![]),
inst(Op::ConstantNull, Some(1), Some(12), vec![]),
inst(
Op::Variable,
Some(3),
Some(20),
vec![
Operand::StorageClass(StorageClass::Private),
Operand::IdRef(12),
],
),
];
let mut function = Function::new();
function.parameters = vec![inst(Op::FunctionParameter, Some(1), Some(21), vec![])];
function.blocks = vec![
Block {
label: Some(inst(Op::Label, None, Some(30), vec![])),
instructions: vec![
// %31 is a runtime bool: the lattice cannot fold it.
inst(
Op::INotEqual,
Some(2),
Some(31),
vec![Operand::IdRef(21), Operand::IdRef(10)],
),
inst(
Op::Select,
Some(2),
Some(32),
vec![Operand::IdRef(31), Operand::IdRef(11), Operand::IdRef(11)],
),
inst(Op::SelectionMerge, None, None, vec![Operand::IdRef(36)]),
inst(
Op::BranchConditional,
None,
None,
vec![Operand::IdRef(32), Operand::IdRef(34), Operand::IdRef(35)],
),
],
},
Block {
label: Some(inst(Op::Label, None, Some(34), vec![])),
instructions: vec![inst(Op::Branch, None, None, vec![Operand::IdRef(36)])],
},
Block {
label: Some(inst(Op::Label, None, Some(35), vec![])),
instructions: vec![inst(Op::Branch, None, None, vec![Operand::IdRef(36)])],
},
Block {
label: Some(inst(Op::Label, None, Some(36), vec![])),
instructions: vec![inst(Op::Return, None, None, vec![])],
},
];
m.functions.push(function);
crate::native::rewrites::prune_constant_branches_module(&mut m).expect("expected a fold");
let labels: Vec<Word> = m.functions[0]
.blocks
.iter()
.filter_map(|b| b.label.as_ref().and_then(|l| l.result_id))
.collect();
assert!(
!labels.contains(&35),
"the arm the collapsed select gated is dead: {labels:?}"
);
assert!(labels.contains(&34), "the taken arm survives: {labels:?}");
assert!(
!m.functions[0]
.blocks
.iter()
.flat_map(|b| b.instructions.iter())
.any(|i| i.class.opcode == Op::Select),
"the identical-arm select itself is gone"
);
}
/// A bool-VECTOR condition selects per lane, so a scalar lattice entry for it proves nothing.
/// `bool_vector_valued_ids` is what keeps those out; the same select with a scalar condition of
/// the same lattice value must still fold, or the guard is just a disabled rule.
#[test]
fn collapse_constant_selects_refuses_a_per_lane_condition() {
// ids: uint=1 bool=2 v2uint=3 v2bool=4 | uint_7=10
let mut m = Module::new();
m.header = Some(ModuleHeader::new(40));
m.types_global_values = vec![
inst(
Op::TypeInt,
None,
Some(1),
vec![Operand::LiteralBit32(32), Operand::LiteralBit32(0)],
),
inst(Op::TypeBool, None, Some(2), vec![]),
inst(
Op::TypeVector,
None,
Some(3),
vec![Operand::IdRef(1), Operand::LiteralBit32(2)],
),
inst(
Op::TypeVector,
None,
Some(4),
vec![Operand::IdRef(2), Operand::LiteralBit32(2)],
),
inst(
Op::Constant,
Some(1),
Some(10),
vec![Operand::LiteralBit32(7)],
),
];
let select = |result: Word, ty: Word, cond: Word, a: Word, b: Word| {
inst(
Op::Select,
Some(ty),
Some(result),
vec![Operand::IdRef(cond), Operand::IdRef(a), Operand::IdRef(b)],
)
};
let mut function = Function::new();
function.parameters = vec![
inst(Op::FunctionParameter, Some(3), Some(20), vec![]),
inst(Op::FunctionParameter, Some(3), Some(21), vec![]),
inst(Op::FunctionParameter, Some(1), Some(22), vec![]),
inst(Op::FunctionParameter, Some(1), Some(23), vec![]),
];
function.blocks = vec![Block {
label: Some(inst(Op::Label, None, Some(30), vec![])),
instructions: vec![
// %31 : v2bool, %32 : bool -- both carry lattice value 1 below.
inst(
Op::INotEqual,
Some(4),
Some(31),
vec![Operand::IdRef(20), Operand::IdRef(21)],
),
inst(
Op::INotEqual,
Some(2),
Some(32),
vec![Operand::IdRef(22), Operand::IdRef(23)],
),
select(33, 3, 31, 20, 21),
select(34, 1, 32, 22, 23),
inst(Op::Return, None, None, vec![]),
],
}];
m.functions.push(function);
let vals: HashMap<Word, i128> = [(31, 1), (32, 1)].into_iter().collect();
let lane_conditions = bool_vector_valued_ids(&m);
assert!(
lane_conditions.contains(&31) && !lane_conditions.contains(&32),
"only the v2bool comparison is a per-lane condition"
);
assert!(collapse_constant_selects(
&mut m.functions[0],
&vals,
&lane_conditions
));
let body = &m.functions[0].blocks[0].instructions;
assert!(
body.iter().any(|i| i.result_id == Some(33)),
"the per-lane select survives"
);
assert!(
!body.iter().any(|i| i.result_id == Some(34)),
"the scalar-condition select folds to its true arm"
);
assert_eq!(
body.last().expect("a terminator").class.opcode,
Op::Return,
"the terminator is untouched"
);
}
#[test]
fn keeps_loop_exit_gated_by_loop_carried_phi() {
// A loop induction phi has one constant entry arm and one backedge defined by the loop body.
+124 -11
View File
@@ -179,7 +179,7 @@ pub(in crate::native) fn nonzero_self_minus_one_guards(
/// Unsigned comparison kind for [`ucmp_fold`].
#[derive(Clone, Copy)]
pub(in crate::native) enum UCmp {
pub(in crate::native) enum Cmp {
Lt,
Gt,
Le,
@@ -191,13 +191,13 @@ pub(in crate::native) enum UCmp {
/// of the other (even Bottom): `x < 0` and `0 > x` are always false; `0 <= x` and `x >= 0` are always
/// true. Values are interpreted unsigned (widths <= 64; the lattice stores width-masked non-negative
/// integers).
pub(in crate::native) fn ucmp_fold(x: Option<Lat>, y: Option<Lat>, kind: UCmp) -> Option<Lat> {
pub(in crate::native) fn ucmp_fold(x: Option<Lat>, y: Option<Lat>, kind: Cmp) -> Option<Lat> {
let is_zero = |v: Option<Lat>| matches!(v, Some(Lat::Const(0)));
match kind {
UCmp::Lt if is_zero(y) => return Some(Lat::Const(0)), // x < 0 = false
UCmp::Gt if is_zero(x) => return Some(Lat::Const(0)), // 0 > y = false
UCmp::Le if is_zero(x) => return Some(Lat::Const(1)), // 0 <= y = true
UCmp::Ge if is_zero(y) => return Some(Lat::Const(1)), // x >= 0 = true
Cmp::Lt if is_zero(y) => return Some(Lat::Const(0)), // x < 0 = false
Cmp::Gt if is_zero(x) => return Some(Lat::Const(0)), // 0 > y = false
Cmp::Le if is_zero(x) => return Some(Lat::Const(1)), // 0 <= y = true
Cmp::Ge if is_zero(y) => return Some(Lat::Const(1)), // x >= 0 = true
_ => {}
}
match (x, y) {
@@ -205,10 +205,10 @@ pub(in crate::native) fn ucmp_fold(x: Option<Lat>, y: Option<Lat>, kind: UCmp) -
(Some(Lat::Const(a)), Some(Lat::Const(b))) => {
let (a, b) = (a as u128, b as u128);
let r = match kind {
UCmp::Lt => a < b,
UCmp::Gt => a > b,
UCmp::Le => a <= b,
UCmp::Ge => a >= b,
Cmp::Lt => a < b,
Cmp::Gt => a > b,
Cmp::Le => a <= b,
Cmp::Ge => a >= b,
};
Some(Lat::Const(r as i128))
}
@@ -216,9 +216,43 @@ pub(in crate::native) fn ucmp_fold(x: Option<Lat>, y: Option<Lat>, kind: UCmp) -
}
}
/// Fold a SIGNED integer comparison over lattice operands. The lattice stores an integer in its
/// type's UNSIGNED representation -- `module_scalar_constants` zero-extends the literal and
/// `IAdd`/`IMul`/`ISub` mask back to the width -- so `-1 : i32` is held as `0xFFFFFFFF` and the bits
/// must be sign-extended from `width` before they mean anything signed. That is why this cannot
/// share `ucmp_fold`'s body, and why an unknown or implausible width refuses to fold rather than
/// guessing 128 and reading every negative operand as a large positive one.
///
/// There is no zero-operand shortcut here. `x >= 0` is a tautology for UNSIGNED `x` only; signed,
/// both `x >= 0` and `x < 0` depend on the value, so a one-constant operand proves nothing.
pub(in crate::native) fn scmp_fold(
x: Option<Lat>,
y: Option<Lat>,
width: Option<u32>,
kind: Cmp,
) -> Option<Lat> {
match (x, y) {
(Some(Lat::Bottom), _) | (_, Some(Lat::Bottom)) => Some(Lat::Bottom),
(Some(Lat::Const(a)), Some(Lat::Const(b))) => {
let width = width.filter(|w| (1..=128).contains(w))?;
let shift = 128 - width;
let sign_extend = |v: i128| (v << shift) >> shift;
let (a, b) = (sign_extend(a), sign_extend(b));
let result = match kind {
Cmp::Lt => a < b,
Cmp::Gt => a > b,
Cmp::Le => a <= b,
Cmp::Ge => a >= b,
};
Some(Lat::Const(result as i128))
}
_ => None,
}
}
/// A value in the constant lattice. Absent-from-the-map = TOP (optimistically undefined). This is
/// the classic SCCP lattice: TOP -> Const -> Bottom, monotone downward, so the fixpoint terminates.
#[derive(Clone, Copy, PartialEq, Eq)]
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(in crate::native) enum Lat {
Const(i128),
Bottom,
@@ -234,3 +268,82 @@ pub(in crate::native) fn meet(a: Option<Lat>, b: Option<Lat>) -> Option<Lat> {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
/// The lattice holds an integer in its type's UNSIGNED representation, so the WIDTH decides
/// what a signed comparison means: `0 < 65534` is true read as 32-bit and false read as 16-bit,
/// where 65534 is -2. Getting this wrong would fold a real branch to the opposite arm, so the
/// width is not optional -- an absent or implausible one refuses instead of guessing.
#[test]
fn signed_comparison_reads_the_operands_at_their_own_width() {
let c = |v: i128| Some(Lat::Const(v));
assert_eq!(
scmp_fold(c(0), c(65534), Some(32), Cmp::Lt),
Some(Lat::Const(1)),
"at 32 bits 65534 is 65534"
);
assert_eq!(
scmp_fold(c(0), c(65534), Some(16), Cmp::Lt),
Some(Lat::Const(0)),
"at 16 bits 65534 is -2"
);
assert_eq!(
scmp_fold(c(0), c(65534), Some(16), Cmp::Gt),
Some(Lat::Const(1)),
"and 0 > -2"
);
// 0xFFFFFFFF is -1 at 32 bits and 4294967295 at 64.
assert_eq!(
scmp_fold(c(0xFFFF_FFFF), c(0), Some(32), Cmp::Lt),
Some(Lat::Const(1))
);
assert_eq!(
scmp_fold(c(0xFFFF_FFFF), c(0), Some(64), Cmp::Lt),
Some(Lat::Const(0))
);
// The signed minimum compares below everything else at its width.
assert_eq!(
scmp_fold(c(0x8000_0000), c(0x7FFF_FFFF), Some(32), Cmp::Lt),
Some(Lat::Const(1))
);
assert_eq!(
scmp_fold(c(7), c(7), Some(32), Cmp::Le),
Some(Lat::Const(1))
);
assert_eq!(
scmp_fold(c(7), c(7), Some(32), Cmp::Ge),
Some(Lat::Const(1))
);
}
/// Unlike `ucmp_fold` there is no zero shortcut: `x >= 0` is a tautology only for an UNSIGNED
/// `x`. A lattice value that is still TOP or a width the caller could not determine both leave
/// the comparison unresolved rather than assuming one.
#[test]
fn signed_comparison_refuses_what_it_cannot_prove() {
let c = |v: i128| Some(Lat::Const(v));
assert_eq!(
scmp_fold(None, c(0), Some(32), Cmp::Ge),
None,
"x >= 0 is not a signed tautology"
);
assert_eq!(scmp_fold(c(0), None, Some(32), Cmp::Lt), None);
assert_eq!(
scmp_fold(c(0), c(1), None, Cmp::Lt),
None,
"an unknown width refuses"
);
assert_eq!(scmp_fold(c(0), c(1), Some(0), Cmp::Lt), None);
assert_eq!(scmp_fold(c(0), c(1), Some(129), Cmp::Lt), None);
assert_eq!(
scmp_fold(Some(Lat::Bottom), c(1), Some(32), Cmp::Lt),
Some(Lat::Bottom),
"a poisoned operand poisons the result"
);
// The unsigned twin DOES have the zero shortcut, and keeps it.
assert_eq!(ucmp_fold(None, c(0), Cmp::Ge), Some(Lat::Const(1)));
}
}
+3
View File
@@ -26,6 +26,7 @@ fn prune_constant_branches_impl(
sweep_dead_values: bool,
) -> bool {
let scalar_int_types = scalar_int_bool_types(module);
let lane_conditions = bool_vector_valued_ids(module);
let consts = module_scalar_constants(module, &scalar_int_types);
let widths = value_int_widths(module);
let composites = module_composite_constants(module, &scalar_int_types, &consts);
@@ -66,6 +67,8 @@ fn prune_constant_branches_impl(
for (g, v) in guards {
vals.entry(g).or_insert(v);
}
changed |=
collapse_constant_selects(&mut module.functions[fi], &vals, &lane_conditions);
if sweep_dead_values {
changed |= fold_branches(&mut module.functions[fi], &vals);
changed |= prune_unreachable(&mut module.functions[fi]);
+165 -20
View File
@@ -195,10 +195,16 @@ pub(in crate::native) fn prune_unreachable(f: &mut crate::spirv_module::Function
removed || phi_fixed || merge_fixed
}
/// Replace a single-incoming phi only when its listed parent is the block's sole actual CFG
/// predecessor, then substitute its value throughout the function. A phi with a stale partial arm
/// list is not an SSA identity: replacing it could expose the listed value along another incoming
/// edge that its definition does not dominate.
/// Replace a phi that has only one possible outcome -- every incoming value is the same id -- with
/// that value, then substitute it throughout the function. The single-incoming phi is the one-arm
/// instance of this, not a separate rule.
///
/// The listed parents must be EXACTLY the block's actual CFG predecessors. A phi with a stale
/// partial arm list is not an SSA identity: replacing it could expose the listed value along an
/// incoming edge that its definition does not dominate. When the lists do agree, the value
/// dominates the end of every predecessor, so it dominates the phi's own block and every use the
/// phi had. A phi that names ITSELF as an incoming value is excluded -- collapsing it to its own
/// result id would delete the only definition of that id.
pub(in crate::native) fn collapse_trivial_phis(f: &mut crate::spirv_module::Function) -> bool {
let mut predecessors: HashMap<Word, HashSet<Word>> = HashMap::new();
for block in &f.blocks {
@@ -215,16 +221,27 @@ pub(in crate::native) fn collapse_trivial_phis(f: &mut crate::spirv_module::Func
for b in &f.blocks {
let Some(block) = block_id(b) else { continue };
for inst in &b.instructions {
if inst.class.opcode == Op::Phi && inst.operands.len() == 2 {
if let (Some(rid), Some(Operand::IdRef(value)), Some(Operand::IdRef(parent))) =
(inst.result_id, inst.operands.first(), inst.operands.get(1))
{
let is_only_predecessor = predecessors
.get(&block)
.is_some_and(|actual| actual.len() == 1 && actual.contains(parent));
if is_only_predecessor {
repl.insert(rid, *value);
}
if inst.class.opcode != Op::Phi
|| inst.operands.is_empty()
|| !inst.operands.len().is_multiple_of(2)
{
continue;
}
let Some(rid) = inst.result_id else { continue };
let mut only_value: Option<Word> = None;
let mut parents: HashSet<Word> = HashSet::new();
let identity = inst.operands.chunks_exact(2).all(|pair| {
let (Some(Operand::IdRef(value)), Some(Operand::IdRef(parent))) =
(pair.first(), pair.get(1))
else {
return false;
};
parents.insert(*parent);
*value != rid && *only_value.get_or_insert(*value) == *value
});
if let (true, Some(value)) = (identity, only_value) {
if predecessors.get(&block) == Some(&parents) {
repl.insert(rid, value);
}
}
}
@@ -232,7 +249,15 @@ pub(in crate::native) fn collapse_trivial_phis(f: &mut crate::spirv_module::Func
if repl.is_empty() {
return false;
}
// Resolve chains (a phi whose value is itself a collapsed phi).
drop_and_substitute(f, &repl);
true
}
/// Delete every instruction whose result is a key of `repl` and rewrite every remaining reference
/// to it as the value it collapsed to, following chains so a value that itself collapsed resolves
/// to its final replacement. Shared by the phi and the select collapse: both reduce a merge with
/// one possible outcome to that outcome, and the bookkeeping afterwards is the same.
fn drop_and_substitute(f: &mut crate::spirv_module::Function, repl: &HashMap<Word, Word>) {
let resolve = |mut x: Word| -> Word {
let mut guard = 0;
while let Some(&n) = repl.get(&x) {
@@ -244,13 +269,10 @@ pub(in crate::native) fn collapse_trivial_phis(f: &mut crate::spirv_module::Func
}
x
};
// Drop the collapsed phis.
for b in &mut f.blocks {
b.instructions.retain(|i| {
!(i.class.opcode == Op::Phi && i.result_id.is_some_and(|r| repl.contains_key(&r)))
});
b.instructions
.retain(|i| !i.result_id.is_some_and(|r| repl.contains_key(&r)));
}
// Substitute uses everywhere in this function.
for b in &mut f.blocks {
for inst in &mut b.instructions {
for op in &mut inst.operands {
@@ -262,6 +284,59 @@ pub(in crate::native) fn collapse_trivial_phis(f: &mut crate::spirv_module::Func
}
}
}
}
/// Replace an `OpSelect` that has only one possible outcome with that outcome: either its two arms
/// are the same id, or `vals` proves its condition constant. This is the value-side twin of
/// `fold_branches` (which does the same for `OpBranchConditional`) and of `collapse_trivial_phis`
/// (which does the same for a merge in phi form). Unlike the phi there is no dominance side
/// condition to check: both arms of a select must already dominate the select itself, so the
/// surviving arm dominates every use the select had.
pub(in crate::native) fn collapse_constant_selects(
f: &mut crate::spirv_module::Function,
vals: &HashMap<Word, i128>,
lane_conditions: &HashSet<Word>,
) -> bool {
let mut repl: HashMap<Word, Word> = HashMap::new();
for b in &f.blocks {
for inst in &b.instructions {
if inst.class.opcode != Op::Select {
continue;
}
let (
Some(rid),
Some(Operand::IdRef(cond)),
Some(Operand::IdRef(a)),
Some(Operand::IdRef(b)),
) = (
inst.result_id,
inst.operands.first(),
inst.operands.get(1),
inst.operands.get(2),
)
else {
continue;
};
if a == b {
repl.insert(rid, *a);
continue;
}
// A vector condition selects per lane, and `vals` is a SCALAR lattice: an entry for
// a vector id (a `Bitcast` of a scalar constant can put one there) says nothing about
// the individual lanes. `fold_branches` never meets this because a branch condition is
// always a scalar bool; a select's need not be, so it is checked.
if lane_conditions.contains(cond) {
continue;
}
if let Some(c) = vals.get(cond) {
repl.insert(rid, if *c != 0 { *a } else { *b });
}
}
}
if repl.is_empty() {
return false;
}
drop_and_substitute(f, &repl);
true
}
@@ -511,6 +586,76 @@ mod tests {
);
}
/// A phi is an identity when every incoming edge carries the SAME value, not only when there is
/// one edge. Three predecessors all handing over `%5` make the phi `%5`. The two refusals are
/// the safety of that: a parent list that does not name every real predecessor is not an SSA
/// identity (the value need not dominate the unlisted edge), and a phi that names its own result
/// would lose the only definition of that id.
#[test]
fn phi_collapses_when_every_edge_carries_one_value() {
let label = |id: Word| Some(Instruction::new(Op::Label, None, Some(id), vec![]));
let branch =
|target: Word| Instruction::new(Op::Branch, None, None, vec![Operand::IdRef(target)]);
let phi = |result: Word, arms: &[(Word, Word)]| {
Instruction::new(
Op::Phi,
Some(2),
Some(result),
arms.iter()
.flat_map(|(value, parent)| [Operand::IdRef(*value), Operand::IdRef(*parent)])
.collect(),
)
};
// Three predecessors (7, 8, 9) all branch to the join block 10.
let join = |body: Vec<Instruction>| {
let mut function = Function::new();
let mut blocks = Vec::new();
for id in [7, 8, 9] {
let mut block = Block::new();
block.label = label(id);
block.instructions = vec![branch(10)];
blocks.push(block);
}
let mut merge = Block::new();
merge.label = label(10);
merge.instructions = body;
blocks.push(merge);
function.blocks = blocks;
function
};
let mut all_three = join(vec![
phi(11, &[(5, 7), (5, 8), (5, 9)]),
Instruction::new(Op::CopyObject, Some(2), Some(12), vec![Operand::IdRef(11)]),
]);
assert!(collapse_trivial_phis(&mut all_three));
let body = &all_three.blocks[3].instructions;
assert_eq!(body.len(), 1, "the phi is gone");
assert_eq!(
body[0].operands.first(),
Some(&Operand::IdRef(5)),
"its use reads the one incoming value"
);
// Block 9 is a real predecessor the arm list does not name.
let mut partial = join(vec![phi(11, &[(5, 7), (5, 8)])]);
assert!(
!collapse_trivial_phis(&mut partial),
"a partial parent list is not an SSA identity"
);
// Every arm carries the phi's own result.
let mut circular = join(vec![phi(11, &[(11, 7), (11, 8), (11, 9)])]);
assert!(
!collapse_trivial_phis(&mut circular),
"a self-referential phi keeps its definition"
);
// Two distinct incoming values are a real merge.
let mut real = join(vec![phi(11, &[(5, 7), (5, 8), (6, 9)])]);
assert!(!collapse_trivial_phis(&mut real), "a real merge survives");
}
#[test]
fn dce_keeps_only_typed_sidecar_rooted_dead_global() {
let ulong = 1;
+315
View File
@@ -0,0 +1,315 @@
//! Pre-emit AIR lowering for a `llvm.memcpy` whose LENGTH is not a compile-time constant.
//!
//! The emitter copies a constant-length `llvm.memcpy` by unrolling it into that many word or byte
//! accesses (`emitter::body::memcpy_memset`), which needs the count in hand. A dynamic length has
//! no unrolling, and until this pass the call fell through every arm: in a module the emitter
//! otherwise accepted, the copy was silently DROPPED and the bytes it should have written kept
//! their previous value; in the rest it surfaced as an internal-contract failure against a bodiless
//! `llvm.memcpy` declaration. Both are measured — `fastGPUMemcpyKernel` copies its `len % 16` tail
//! this way, and before this pass the authored case
//! `a-byte-copy-whose-tail-is-shorter-than-its-vector` disagreed with Metal on exactly those bytes.
//!
//! The lowering is a byte loop, which is what a dynamic length admits: nothing about the count is
//! known, so neither alignment nor a wider step can be assumed. `llvm.memcpy` requires its operands
//! not to overlap, so ascending order needs no argument.
//!
//! The loop is spliced into the CALLER's block rather than called as a helper. A device-buffer
//! pointer does not survive a SPIR-V function boundary here — routed through a helper parameter it
//! arrives as a Private placeholder and the copy lands in scratch memory, which is the same silent
//! loss in a new costume. Splicing keeps both pointers on the raw-cursor path the surrounding code
//! already uses. That costs one restriction: the containing block must be LABELLED, because the
//! split renames it for any successor phi, and an implicit entry block has no name to rewrite. All
//! ten dynamic-length copies in the corpus are in labelled blocks; an entry-block one is left
//! exactly as it is today.
//!
//! Like [`super::async_copy`], this runs on the sanitized AIR TEXT before
//! [`super::ir::LlModule::parse`], and is a no-op — borrowing its input — unless a call with a
//! non-constant length is actually present.
use super::air_text::{call_arguments, last_token, split_args, LineBuffer};
use std::borrow::Cow;
use std::collections::HashMap;
/// One `llvm.memcpy` call with a dynamic length, decoded from its argument list.
struct DynamicMemcpy {
dst_ty: String,
src_ty: String,
len_ty: String,
dst: String,
src: String,
len: String,
}
/// Rewrite every dynamic-length `llvm.memcpy` in `san_ll` into an in-place byte-copy loop.
pub(crate) fn lower_dynamic_length_memcpy(san_ll: &str) -> Cow<'_, str> {
let splits = plan_splits(san_ll);
if splits.is_empty() {
return Cow::Borrowed(san_ll);
}
let mut out = LineBuffer::with_capacity(san_ll.len().saturating_add(san_ll.len() / 8));
let mut label: Option<String> = None;
let mut next = 0usize;
for line in san_ll.lines() {
if let Some(block) = block_label(line) {
label = Some(block.to_string());
out.push(line);
continue;
}
let trimmed = line.trim_start();
let Some(call) = parse_dynamic_memcpy(trimmed) else {
out.push(&rewrite_phi_predecessors(line, &splits));
continue;
};
let Some(predecessor) = label.clone() else {
// An implicit entry block has no name for a successor phi to be re-pointed at.
out.push(line);
continue;
};
let indent = &line[..line.len() - trimmed.len()];
emit_copy_loop(&mut out, indent, &call, &predecessor, next);
label = Some(format!("__dmc_done{next}"));
next += 1;
}
if san_ll.ends_with('\n') {
out.text.push('\n');
}
Cow::Owned(out.text)
}
/// Owned counterpart: once rewriting has produced a replacement, returning it drops the superseded
/// input before typed parsing begins, and a no-op returns the original allocation unchanged.
pub(crate) fn lower_dynamic_length_memcpy_owned(san_ll: String) -> String {
match lower_dynamic_length_memcpy(&san_ll) {
Cow::Borrowed(_) => san_ll,
Cow::Owned(lowered) => lowered,
}
}
/// The label each split block ENDS at after rewriting, keyed by its original label. A phi in a
/// successor names the predecessor block, and after a split the branch it names comes from the
/// loop's exit block instead. Computed up front because a phi can precede its predecessor in the
/// text; empty when the module has no dynamic-length copy to split on.
fn plan_splits(san_ll: &str) -> HashMap<String, String> {
let mut splits = HashMap::new();
let mut label: Option<&str> = None;
let mut original: Option<String> = None;
let mut next = 0usize;
for line in san_ll.lines() {
if let Some(block) = block_label(line) {
label = Some(block);
original = None;
continue;
}
if parse_dynamic_memcpy(line.trim_start()).is_none() {
continue;
}
let Some(block) = label else { continue };
let start = original.get_or_insert_with(|| block.to_string()).clone();
splits.insert(start, format!("__dmc_done{next}"));
next += 1;
}
splits
}
/// The label a basic-block header line declares, if it is one.
fn block_label(line: &str) -> Option<&str> {
if line.starts_with(char::is_whitespace) {
return None;
}
let name = line.split(':').next()?;
(!name.is_empty()
&& name
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '$'))
&& line[name.len()..].starts_with(':'))
.then_some(name)
}
/// Re-point a phi's incoming block at the loop exit that now terminates the split predecessor.
/// Only phi lines are touched: a `br`/`switch` still targets the block's unchanged START.
fn rewrite_phi_predecessors(line: &str, splits: &HashMap<String, String>) -> String {
if !line.contains(" phi ") {
return line.to_string();
}
let mut rewritten = line.to_string();
for (from, to) in splits {
rewritten = rewritten.replace(&format!(", %{from} ]"), &format!(", %{to} ]"));
}
rewritten
}
/// Emit the byte loop replacing one call, leaving the emitter positioned in `__dmc_done{n}` so the
/// rest of the original block follows it.
fn emit_copy_loop(
out: &mut LineBuffer,
indent: &str,
call: &DynamicMemcpy,
predecessor: &str,
n: usize,
) {
let (dst_ty, src_ty, len_ty) = (&call.dst_ty, &call.src_ty, &call.len_ty);
let (dst, src, len) = (&call.dst, &call.src, &call.len);
out.push_fmt(format_args!("{indent}br label %__dmc_head{n}"));
out.push_fmt(format_args!("__dmc_head{n}:"));
out.push_fmt(format_args!(
"{indent}%__dmc_i{n} = phi {len_ty} [ 0, %{predecessor} ], [ %__dmc_next{n}, %__dmc_body{n} ]"
));
// `llvm.memcpy` takes an unsigned byte count.
out.push_fmt(format_args!(
"{indent}%__dmc_more{n} = icmp ult {len_ty} %__dmc_i{n}, {len}"
));
out.push_fmt(format_args!(
"{indent}br i1 %__dmc_more{n}, label %__dmc_body{n}, label %__dmc_done{n}"
));
out.push_fmt(format_args!("__dmc_body{n}:"));
out.push_fmt(format_args!(
"{indent}%__dmc_src{n} = getelementptr i8, {src_ty} {src}, {len_ty} %__dmc_i{n}"
));
out.push_fmt(format_args!(
"{indent}%__dmc_byte{n} = load i8, {src_ty} %__dmc_src{n}, align 1"
));
out.push_fmt(format_args!(
"{indent}%__dmc_dst{n} = getelementptr i8, {dst_ty} {dst}, {len_ty} %__dmc_i{n}"
));
out.push_fmt(format_args!(
"{indent}store i8 %__dmc_byte{n}, {dst_ty} %__dmc_dst{n}, align 1"
));
out.push_fmt(format_args!(
"{indent}%__dmc_next{n} = add {len_ty} %__dmc_i{n}, 1"
));
out.push_fmt(format_args!("{indent}br label %__dmc_head{n}"));
out.push_fmt(format_args!("__dmc_done{n}:"));
}
/// Decode `call void @llvm.memcpy.<dst>.<src>.<len>(<dst>, <src>, <len>, i1 <volatile>)`, returning
/// `None` for anything this pass must not touch: a declaration, a constant length (the emitter
/// unrolls those), or a volatile copy, whose ordering a plain loop does not promise.
fn parse_dynamic_memcpy(line: &str) -> Option<DynamicMemcpy> {
if !line.contains("call") || line.starts_with("declare") {
return None;
}
let suffix = line.split("@llvm.memcpy.").nth(1)?;
let mut spaces = suffix.split('(').next()?.split('.');
let dst_ty = pointer_type(spaces.next()?)?;
let src_ty = pointer_type(spaces.next()?)?;
let len_ty = spaces.next()?.to_string();
if !len_ty.starts_with('i') || len_ty[1..].parse::<u32>().is_err() {
return None;
}
let args = split_args(call_arguments(line)?);
if args.len() != 4 || last_token(&args[3]) != "false" {
return None;
}
let len = last_token(&args[2]).to_string();
if !len.starts_with('%') {
return None;
}
Some(DynamicMemcpy {
dst_ty,
src_ty,
len_ty,
dst: last_token(&args[0]).to_string(),
src: last_token(&args[1]).to_string(),
len,
})
}
/// The LLVM spelling of the `pN` address-space token in the intrinsic's name.
fn pointer_type(space: &str) -> Option<String> {
match space.strip_prefix('p')?.parse::<u32>().ok()? {
0 => Some("ptr".to_string()),
n => Some(format!("ptr addrspace({n})")),
}
}
#[cfg(test)]
mod tests {
use super::lower_dynamic_length_memcpy;
use std::borrow::Cow;
fn module(body: &str) -> String {
format!("define void @k() {{\nentry:\n br label %19\n19:\n{body} br label %24\n24:\n ret void\n}}\n")
}
const DYNAMIC: &str = " tail call void @llvm.memcpy.p1.p1.i64(ptr addrspace(1) align 1 %21, \
ptr addrspace(1) align 1 %22, i64 %23, i1 false) #2, !alias.scope !30\n";
#[test]
fn a_constant_length_copy_is_left_for_the_emitter_to_unroll() {
let ll = module(
" tail call void @llvm.memcpy.p1.p1.i64(ptr addrspace(1) %a, ptr addrspace(1) %b, \
i64 48, i1 false)\n",
);
assert!(matches!(
lower_dynamic_length_memcpy(&ll),
Cow::Borrowed(value) if std::ptr::eq(value, ll.as_str())
));
}
#[test]
fn a_volatile_copy_is_not_rewritten_into_a_plain_loop() {
let ll = module(&DYNAMIC.replace("i1 false", "i1 true"));
assert!(matches!(
lower_dynamic_length_memcpy(&ll),
Cow::Borrowed(value) if std::ptr::eq(value, ll.as_str())
));
}
#[test]
fn a_lone_declaration_is_not_a_call() {
let ll =
"declare void @llvm.memcpy.p1.p1.i64(ptr addrspace(1), ptr addrspace(1), i64, i1)\n";
assert!(matches!(
lower_dynamic_length_memcpy(ll),
Cow::Borrowed(value) if std::ptr::eq(value, ll)
));
}
#[test]
fn a_dynamic_length_copy_becomes_a_byte_loop_in_the_calling_block() {
let ll = module(DYNAMIC);
let lowered = lower_dynamic_length_memcpy(&ll);
assert!(!lowered.contains("@llvm.memcpy.p1.p1.i64(ptr"), "{lowered}");
// The loop is spliced in place: it must NOT become a call, whose parameters would strip the
// pointers of their device-buffer provenance.
assert!(!lowered.contains("call void @__"), "{lowered}");
assert!(
lowered.contains("%__dmc_i0 = phi i64 [ 0, %19 ], [ %__dmc_next0, %__dmc_body0 ]"),
"{lowered}"
);
assert!(lowered.contains("icmp ult i64 %__dmc_i0, %23"), "{lowered}");
assert!(
lowered.contains("%__dmc_src0 = getelementptr i8, ptr addrspace(1) %22, i64 %__dmc_i0"),
"{lowered}"
);
assert!(
lowered.contains("store i8 %__dmc_byte0, ptr addrspace(1) %__dmc_dst0, align 1"),
"{lowered}"
);
assert!(lowered.contains("__dmc_done0:"), "{lowered}");
}
#[test]
fn a_successor_phi_follows_the_split_block_to_its_loop_exit() {
let ll = format!(
"define void @k() {{\nentry:\n br label %19\n19:\n{DYNAMIC} br label %24\n24:\n \
%26 = phi i32 [ 0, %entry ], [ 1, %19 ]\n ret void\n}}\n"
);
let lowered = lower_dynamic_length_memcpy(&ll);
assert!(
lowered.contains("%26 = phi i32 [ 0, %entry ], [ 1, %__dmc_done0 ]"),
"{lowered}"
);
// The unconditional branch still targets the block's unchanged START.
assert!(lowered.contains(" br label %19\n"), "{lowered}");
}
#[test]
fn an_implicit_entry_block_is_left_alone() {
let ll = format!("define void @k() {{\n{DYNAMIC} ret void\n}}\n");
assert!(matches!(
lower_dynamic_length_memcpy(&ll),
Cow::Borrowed(value) if std::ptr::eq(value, ll.as_str())
));
}
}
+87 -25
View File
@@ -89,17 +89,14 @@ fn emit_vulkan_spirv_inner(
entry_name: Option<&str>,
buffer_layouts: Option<&HashMap<u32, meta::AirType>>,
) -> Result<crate::emit_sidecar::EmittedSpirv, crate::emit_sidecar::EmissionFailure> {
// Lower `air.simdgroup_async_copy_2d` (+ its event/wait pair) to an explicit strided tile copy
// before parse. Alternate constructions see this lowering because the production entry applies
// it before re-emission. This
// entry's copy is retained for direct callers; already-lowered text is a no-op guard. See
// `async_copy` and its structural regression tests. Floor-safe: only fires on async-copy modules,
// which fail the emitter outright otherwise.
// Apply the shared pre-emit AIR-text lowering before parse. Alternate constructions see it
// because the production entry applies it before re-emission; this entry's copy is retained for
// direct callers, and already-lowered text is a no-op guard. See `super::lower_air_text`.
let retry_debug = crate::env_vars::retry_debug();
if retry_debug {
eprintln!("[retry-debug] native emit: AIR normalizations start");
}
let san_ll = async_copy::lower_simdgroup_async_copy(san_ll);
let san_ll = super::lower_air_text(san_ll);
// Scalarize any scalar/vector pointer-merge before parse (floor-safe: a no-op unless the module
// carries a `<N x T>*`/`T*` merge the emitter rejects outright). See `vec_scalar_merge`.
let san_ll = vec_scalar_merge::lower_vector_scalar_pointer_merge(&san_ll);
@@ -111,16 +108,88 @@ fn emit_vulkan_spirv_inner(
if retry_debug {
eprintln!("[retry-debug] native emit: AIR normalizations complete; typed parse start");
}
// A descriptor-relative byte cursor lives in emitter state, not in an SSA value, and Logical
// addressing forbids handing the callee the derived pointer instead. The one representation
// that keeps the callee's accesses on the buffer is the one with no call boundary: splice the
// refused helper calls into their callers in the AIR text and emit that source instead.
//
// Emission raises the first refusal it reaches and stops, so one pass names one call site.
// Splicing it and re-emitting names the next, and each pass removes at least one call from an
// acyclic internal call graph, so the loop converges; only a module that already failed enters
// it, and the bound keeps the failure path from re-emitting without end.
let mut source = san_ll;
let mut spliced_calls = 0usize;
let mut first_failure = None;
for _ in 0..MAX_CURSOR_CALL_SPLICES {
let failure = match emit_lowered_air_text(
&source,
primitive_phi_metadata,
kern,
entry_name,
buffer_layouts,
// Splicing a multi-block helper into its caller enlarges the entry CFG exactly as the
// pointer-consumer inliner does; select the bounded whole-CFG constructor from that
// fact.
pointer_consumers.requires_relooper || spliced_calls > 0,
) {
Ok(emitted) => return Ok(emitted),
Err(failure) => failure,
};
let Some(spliced) = (if failure.rejected.cursor_call_sites.is_empty() {
None
} else {
inline::inline_cursor_call_sites(&source, &failure.rejected.cursor_call_sites)
}) else {
// The first refusal is the fact worth reporting: it names the seam. A later error is a
// property of a source shape the module never had, so it only annotates that one.
return Err(match first_failure {
None => failure,
Some(error) => crate::emit_sidecar::EmissionFailure {
error: format!(
"{error}; with {spliced_calls} refused call(s) spliced: {}",
failure.error
),
rejected: failure.rejected,
},
});
};
spliced_calls += failure.rejected.cursor_call_sites.len();
first_failure.get_or_insert(failure.error);
if retry_debug {
eprintln!(
"[retry-debug] native emit: retrying with {spliced_calls} cursor call site(s) spliced"
);
}
source = spliced;
}
Err(crate::emit_sidecar::EmissionFailure::from_error(format!(
"native emitter: more than {MAX_CURSOR_CALL_SPLICES} helper calls carry a \
descriptor-relative byte cursor that cannot cross the call"
)))
}
/// How many refused helper calls one module may have spliced before the retry gives up. Measured
/// over the 14579-source corpus: the deepest module needs 20, and no module reaches this bound.
const MAX_CURSOR_CALL_SPLICES: usize = 32;
/// Emit one already-lowered AIR module. Every text normalization has run; this is the parse,
/// representation-selection, and emission tail that a retry over rewritten text repeats verbatim.
fn emit_lowered_air_text(
san_ll: &str,
primitive_phi_metadata: bool,
kern: Option<&meta::KernMeta>,
entry_name: Option<&str>,
buffer_layouts: Option<&HashMap<u32, meta::AirType>>,
requires_relooper: bool,
) -> Result<crate::emit_sidecar::EmittedSpirv, crate::emit_sidecar::EmissionFailure> {
let retry_debug = crate::env_vars::retry_debug();
let san_ll = san_ll.to_string();
let mut parsed = if primitive_phi_metadata {
LlModule::parse_with_primitive_phi_metadata_and_stage_meta(&san_ll, kern, entry_name)
} else {
LlModule::parse_with_stage_meta(&san_ll, kern, entry_name)
}
.map_err(|error| crate::emit_sidecar::EmissionFailure {
error,
ordinary_plan_rejected_functions: HashSet::new(),
ownership_plan_rejected_functions: HashSet::new(),
})?;
.map_err(crate::emit_sidecar::EmissionFailure::from_error)?;
let requires_device_addresses = requires_device_address_model(&parsed);
if retry_debug {
eprintln!(
@@ -176,11 +245,9 @@ fn emit_vulkan_spirv_inner(
.filter_map(|inst| inst.value_call_error().as_deref())
.find(|error| error.contains("unsupported indirect call through function pointer"))
{
return Err(crate::emit_sidecar::EmissionFailure {
error: error.to_string(),
ordinary_plan_rejected_functions: HashSet::new(),
ownership_plan_rejected_functions: HashSet::new(),
});
return Err(crate::emit_sidecar::EmissionFailure::from_error(
error.to_string(),
));
}
}
if requires_device_addresses {
@@ -193,7 +260,7 @@ fn emit_vulkan_spirv_inner(
if requires_device_addresses {
emitter = emitter.with_bda_device_pointers();
}
if pointer_consumers.requires_relooper {
if requires_relooper {
emitter = emitter.with_relooper_feed();
}
let mut emitted = finalize_emission_outcome(emitter, buffer_layouts, &san_ll)?;
@@ -759,13 +826,8 @@ fn finalize_emission_outcome(
buffer_layouts: Option<&HashMap<u32, meta::AirType>>,
san_ll: &str,
) -> Result<crate::emit_sidecar::EmittedSpirv, crate::emit_sidecar::EmissionFailure> {
let air_data_layout = crate::layout::AirDataLayout::from_ir(san_ll).map_err(|error| {
crate::emit_sidecar::EmissionFailure {
error,
ordinary_plan_rejected_functions: HashSet::new(),
ownership_plan_rejected_functions: HashSet::new(),
}
})?;
let air_data_layout = crate::layout::AirDataLayout::from_ir(san_ll)
.map_err(crate::emit_sidecar::EmissionFailure::from_error)?;
let (mut module, sidecar) =
emitter.emit_with_sidecar(buffer_layouts, air_data_layout.as_ref())?;
add_native_module_capabilities(&mut module);
+15 -35
View File
@@ -438,45 +438,25 @@ fn matrix_type_matches(
array_len == cols && vector_type_matches(defs, vec_ty, scalar, rows)
}
fn array_type(defs: &HashMap<Word, Instruction>, ty: Word) -> Option<(Word, u32)> {
let def = defs.get(&ty)?;
if def.class.opcode != Op::TypeArray {
return None;
}
let elem = match def.operands.first()? {
Operand::IdRef(elem) => *elem,
_ => return None,
};
let len_const = match def.operands.get(1)? {
Operand::IdRef(len_const) => *len_const,
_ => return None,
};
let len = defs
.get(&len_const)
.and_then(|constant| match constant.operands.first() {
Some(Operand::LiteralBit32(len)) => Some(*len),
_ => None,
})?;
Some((elem, len))
}
use crate::spirv_module::array_type;
fn type_int_width(defs: &HashMap<Word, Instruction>, ty: Word) -> Option<u32> {
let def = defs.get(&ty)?;
(def.class.opcode == Op::TypeInt).then(|| match def.operands.first() {
Some(Operand::LiteralBit32(width)) => *width,
_ => 32,
})
}
use crate::spirv_module::type_int_width;
fn type_float_width(defs: &HashMap<Word, Instruction>, ty: Word) -> Option<u32> {
let def = defs.get(&ty)?;
(def.class.opcode == Op::TypeFloat).then(|| match def.operands.first() {
Some(Operand::LiteralBit32(width)) => *width,
_ => 32,
})
}
use crate::spirv_module::type_float_width;
/// Whether an emitted member AIR does not describe is the backend's own padding.
///
/// The Metal front end spells a hole between two members as bytes: `[N x i8]` for a run, and a
/// BARE `i8` for a single byte, which is what a `char` followed by a two-byte member produces
/// (`re::BreakthroughPlanarInstanceData` declares `char cullMode` at 180 and
/// `ushort clippingOffset` at 182, and LLVM emits `float, i8, i8, i16`). Recognising only the
/// array spelling made the single byte look like a member AIR forgot to declare, which discarded
/// the whole struct's declared offsets. Padding is only ever consulted after the member fails to
/// match the AIR member at the cursor, so a genuine one-byte member is matched as itself first.
fn is_backend_padding_array(defs: &HashMap<Word, Instruction>, ty: Word) -> bool {
if type_int_width(defs, ty) == Some(8) {
return true;
}
let Some((elem, _len)) = array_type(defs, ty) else {
return false;
};
+265 -14
View File
@@ -183,15 +183,46 @@ impl Emitter {
// A cross-coordinate AIR imageblock is shared tile memory. APV supplies an explicit extent;
// ordinary compute AIR supplies its row stride through `[[threads_per_threadgroup]]`. Both
// forms allocate one complete metadata-typed cell per coordinate.
//
// Both forms also linearise `y * width + x`, which needs every coordinate to land inside one
// row of that width. An entry that stages a `k`x`k` block per thread has an imageblock `k`
// times wider than the threadgroup extent, and linearising it by that extent would land two
// cells one row apart on the same index -- one thread silently reading and writing
// another's staging. `imageblock_cell_scale` reads `k` off the coordinate; the stride and
// the cell count are multiplied by it below. `None` is an entry whose coordinates are not a
// linear function of a thread position at all, so no width bounds them, which stays refused.
if !self.ir.aliased_imageblock_planes.is_empty() && self.ir.imageblock_cell_scale != Some(1)
{
// One aliased cell is one render-target texel, so a thread that stages a `k`x`k` block
// owns `k * k` texels and the entry prologue would have to fill all of them. No corpus
// source does that, and staging the block without filling it reads scratch where the
// attachments should be -- the exact silence the alias marker exists to prevent.
return Err(format!(
"native emitter: an imageblock aliased onto the implicit imageblock stages {:?} cells per thread; only one cell per thread, which is one render-target texel, has a modelled correspondence to an attachment",
self.ir.imageblock_cell_scale
));
}
let cell_scale = self.ir.imageblock_cell_scale.ok_or_else(|| {
"native emitter: an imageblock cell coordinate is not a linear function of a thread \
position, so the tile has no row stride that keeps every coordinate inside it and two \
of its cells would share one linearised index"
.to_string()
})?;
let (cell_count, width_id) = if let Some([width, height]) = self.ir.imageblock_dimensions {
// An APV extent is the whole tile already, scale included.
let cell_count = width
.checked_mul(height)
.ok_or_else(|| "native emitter: imageblock cell count overflows".to_string())?;
(cell_count, self.const_uint(width)?)
} else {
// No stated extent, so the tile is bounded by the threadgroup memory it may occupy
// rather than by a cell count: how many cells that is depends on how wide one is, and
// on how many of them each thread owns.
let cell_bytes = self.imageblock_cell_allocation_size(&pointee)?;
let width = self.emit_imageblock_threadgroup_width(instructions)?;
(
crate::native::imageblock::CELL_CAPACITY,
self.emit_imageblock_threadgroup_width(instructions)?,
crate::native::imageblock::cell_capacity(cell_bytes, cell_scale),
self.emit_scaled_imageblock_width(width, cell_scale, instructions)?,
)
};
let array = LlType::Array(Box::new(pointee.clone()), cell_count);
@@ -209,6 +240,9 @@ impl Emitter {
self.imageblock_data_scratch = Some((storage, pointee.clone()));
storage
};
if !self.ir.aliased_imageblock_planes.is_empty() {
self.emit_sidecar.aliased_imageblock_staging = Some(storage);
}
let coordinate = call
.args
@@ -302,18 +336,82 @@ impl Emitter {
Ok(true)
}
/// The threadgroup-memory footprint of one imageblock cell, in bytes.
///
/// The cell is the metadata-typed imageblock struct the tile array is an array of, so its
/// allocation size -- its natural size rounded to its own alignment, which is what an
/// `OpTypeArray` of it strides by -- is what divides the tile budget into cells.
fn imageblock_cell_allocation_size(&mut self, pointee: &LlType) -> Result<u32, String> {
let cell_ty = self.type_id(pointee)?;
let defs = self
.module
.types_global_values
.iter()
.filter_map(|instruction| instruction.result_id.map(|id| (id, instruction.clone())))
.collect::<HashMap<_, _>>();
let (size, align) = crate::layout::spirv_size_align(
cell_ty,
&defs,
crate::layout::SpirvLayout::natural(self.air_data_layout.as_ref()),
);
Ok(crate::layout::round_up_u32(size, align.max(1)))
}
/// Widen a threadgroup row stride into the imageblock's, which is `scale` times it in each axis.
///
/// At the usual `scale` of 1 the tile IS the threadgroup and the stride is returned untouched,
/// so an entry that stages one cell per thread emits exactly what it emitted before.
fn emit_scaled_imageblock_width(
&mut self,
width: Word,
scale: u32,
instructions: &mut Vec<Instruction>,
) -> Result<Word, String> {
if scale == 1 {
return Ok(width);
}
let uint_ty = self.type_id(&LlType::Int(32))?;
let scale_id = self.const_uint(scale)?;
let scaled = self.fresh();
instructions.push(Self::inst(
Op::IMul,
Some(uint_ty),
Some(scaled),
vec![Operand::IdRef(width), Operand::IdRef(scale_id)],
));
Ok(scaled)
}
pub(in crate::native::emitter) fn emit_imageblock_threadgroup_width(
&mut self,
instructions: &mut Vec<Instruction>,
) -> Result<Word, String> {
let param_name = self
.ir
.imageblock_threads_per_threadgroup_param
.clone()
.ok_or_else(|| {
"native emitter: cross-coordinate imageblock has no threads_per_threadgroup parameter"
.to_string()
})?;
let Some(param_name) = self.ir.imageblock_threads_per_threadgroup_param.clone() else {
// No `[[threads_per_threadgroup]]` parameter to read the stride from. The tile width is
// still a known fact, just not one this layer holds: ask `air.get_imageblock_width`,
// which the pass answers from `TransformOptions::kernel_local_size`. The IR declares
// that intrinsic for exactly this case (`IMAGEBLOCK_WIDTH_INTRINSIC`), so a module that
// reaches here without the declaration is one this emitter must still refuse.
let callee = *self
.function_ids
.get(crate::native::ir::IMAGEBLOCK_WIDTH_INTRINSIC)
.ok_or_else(|| {
"native emitter: a cross-coordinate imageblock has no row stride; the entry \
declares neither an APV imageblock extent nor a `[[threads_per_threadgroup]]` \
parameter, and emitting the module would resolve every tile coordinate to one \
per-invocation slot"
.to_string()
})?;
let uint_ty = self.type_id(&LlType::Int(32))?;
let width = self.fresh();
instructions.push(Self::inst(
Op::FunctionCall,
Some(uint_ty),
Some(width),
vec![Operand::IdRef(callee)],
));
return Ok(width);
};
let (param_id, param_ty) = self.values.get(&param_name).cloned().ok_or_else(|| {
format!(
"native emitter: imageblock threads_per_threadgroup value {param_name} is unavailable"
@@ -474,6 +572,7 @@ impl Emitter {
}
if let Some(id) = self.raw_device_call_arg_id(
&call.callee,
index,
&param_name,
&param_ty,
&arg,
@@ -482,6 +581,35 @@ impl Emitter {
ids.push(id);
continue;
}
// A descriptor-backed pointer whose byte cursor could not be carried onto the
// parameter above has a `Private` zero placeholder as its ordinary SSA value: the real
// root and offset live in `raw_offsets`, which is emitter state, not a SPIR-V value.
// Handing that placeholder to the callee is not an approximation, it is a silent loss --
// the emitted-graph inliner substitutes it faithfully and every load and store the
// callee makes through the parameter lands in scratch. Refuse instead; a pointer the
// emitter genuinely cannot address at all has no `raw_offsets` entry and is unaffected.
if let (LlValue::Local(arg_name), LlType::Ptr(_)) =
(&arg.value, self.resolve_type(&param_ty)?)
{
if self.unmodeled_pointers.contains(arg_name)
&& self
.raw_offsets
.get(arg_name)
.is_some_and(|raw| !raw.unmodelable)
&& self.ir.param_is_dereferenced(&call.callee, &param_name)
{
// Record the site before refusing: with no boundary there is no cursor to
// carry, and the AIR-text retry inlines exactly this call to remove it.
self.cursor_call_sites
.insert((call.callee.clone(), arg_name.clone()));
return Err(format!(
"native emitter: helper @{} parameter {param_name} is passed a \
descriptor-backed pointer whose byte cursor cannot cross the call; the \
callee would read and write scratch where Metal reaches the buffer",
call.callee
));
}
}
ids.push(self.value_id_in(&arg.value, &arg.ty, instructions)?);
}
for value in &nullness_args {
@@ -682,6 +810,7 @@ impl Emitter {
pub(in crate::native::emitter) fn raw_device_call_arg_id(
&mut self,
callee: &str,
param_index: usize,
param_name: &str,
param_ty: &LlType,
arg: &TypedValue,
@@ -697,8 +826,17 @@ impl Emitter {
let LlType::Ptr(param_addrspace) = self.resolve_type(param_ty)? else {
return Ok(None);
};
if param_addrspace != 1 {
return Ok(None); // device buffers only; the workgroup case is handled separately
if !matches!(param_addrspace, 1 | 2) {
return Ok(None); // descriptor-backed buffers only; workgroup is handled separately
}
// Metal's `constant` space (`addrspace(2)`) is descriptor-backed exactly like `device`, so
// a member pointer into a uniform struct has the same Private placeholder VALUE and the
// same need to reach the helper as a cursor on the real root. It differs in one way that
// matters here: the SAME helper is routinely called with several members of one struct,
// and only one cursor per parameter can be recorded. Admit only the shape where a second,
// conflicting cursor cannot exist.
if param_addrspace == 2 && !self.constant_call_cursor_cannot_conflict(callee, param_index) {
return Ok(None);
}
let LlValue::Local(arg_name) = &arg.value else {
return Ok(None);
@@ -718,7 +856,7 @@ impl Emitter {
.materialize_device_address(&address_raw, instructions)
.map(Some);
}
if raw.addrspace != 1
if !matches!(raw.addrspace, 1 | 2)
|| !raw.dyn_terms.is_empty()
|| raw.unmodelable
|| raw.device_addr_base.is_some()
@@ -726,7 +864,7 @@ impl Emitter {
return Ok(None);
}
let root = raw.root.clone();
if !self.param_values.contains(&root) || !self.raw_buffer_params.contains(&root) {
if !self.param_values.contains(&root) || !self.is_raw_buffer_param(&root) {
return Ok(None);
}
let key = (callee.to_string(), param_name.to_string());
@@ -747,6 +885,30 @@ impl Emitter {
Ok(Some(id))
}
/// Whether the cursor recorded for a `constant`-space helper parameter cannot be contradicted
/// by a second call site.
///
/// Metal's `constant` space carries whole uniform STRUCTS, and a helper that takes one member
/// of a struct is routinely called again with a DIFFERENT member of the same struct: over the
/// corpus, 33 sources call a constant helper parameter at two different byte cursors, where
/// only one cursor can be recorded. Only the first call site's cursor would survive, and the
/// second would read at the wrong offset, so admit only the shape where that cannot happen.
///
/// One call site is the easy case. Beyond that, all the call sites have to be in ONE caller --
/// a local name means nothing across functions -- and each of them has to name the parameter's
/// argument the same way: the same local, or the same all-constant `getelementptr` off the same
/// base. Identical chains address identical bytes, which is stronger than comparing the offsets
/// and does not re-derive the AIR layout to find out.
fn constant_call_cursor_cannot_conflict(&mut self, callee: &str, param_index: usize) -> bool {
if self.agreeing_constant_call_cursors.is_none() {
self.agreeing_constant_call_cursors = Some(agreeing_constant_call_cursors(&self.ir));
}
self.agreeing_constant_call_cursors
.as_ref()
.expect("just set")
.contains(&(callee.to_string(), param_index))
}
pub(in crate::native::emitter) fn raw_workgroup_call_arg_id(
&mut self,
callee: &str,
@@ -889,3 +1051,92 @@ fn decayed_global_call_arg_indices(
_ => None,
}
}
/// For each `(callee, parameter index)`, whether every call site in the module names that argument
/// the same byte. See [`Emitter::constant_call_cursor_cannot_conflict`] for why this is the gate.
///
/// A callee called once qualifies on every parameter. Otherwise the call sites must share one
/// caller function, and each parameter is judged on its own: the arguments must all reduce to the
/// same key, where a local's key is its own name unless it is defined by an all-constant
/// `getelementptr`, in which case it is that chain. An argument that is not a local disqualifies
/// the parameter, because only a local can carry a `raw_offsets` cursor at all.
fn agreeing_constant_call_cursors(ir: &LlModule) -> HashSet<(String, usize)> {
let mut sites: HashMap<&str, Vec<(&str, &LlCall)>> = HashMap::new();
for function in &ir.functions {
for instruction in function.carrier_insts() {
if let Some(call) = instruction.alias_call() {
sites
.entry(call.callee.as_str())
.or_default()
.push((function.name.as_str(), call));
}
}
}
let mut agreeing = HashSet::new();
for (callee, calls) in sites {
let arity = calls
.iter()
.map(|(_, call)| call.args.len())
.max()
.unwrap_or(0);
if calls.len() == 1 {
agreeing.extend((0..arity).map(|index| (callee.to_string(), index)));
continue;
}
let (first_caller, _) = calls[0];
if calls.iter().any(|(caller, _)| *caller != first_caller) {
continue;
}
let Some(caller) = ir.functions.iter().find(|f| f.name == first_caller) else {
continue;
};
let mut definitions: HashMap<&str, &LlGep> = HashMap::new();
for instruction in caller.carrier_insts() {
if let (Some(result), Some(gep)) = (&instruction.result, instruction.gep().as_deref()) {
definitions.insert(result.as_str(), gep);
}
}
for index in 0..arity {
let mut keys = calls.iter().map(|(_, call)| {
call.args.get(index).and_then(|arg| match &arg.value {
LlValue::Local(name) => Some(constant_cursor_key(name, &definitions)),
_ => None,
})
});
let Some(Some(first)) = keys.next() else {
continue;
};
if keys.all(|key| key.as_ref() == Some(&first)) {
agreeing.insert((callee.to_string(), index));
}
}
}
agreeing
}
/// The bytes a pointer local names, as a comparable key: the chain if it is an all-constant
/// `getelementptr`, and the local's own name otherwise. Two equal keys address equal bytes.
fn constant_cursor_key(name: &str, definitions: &HashMap<&str, &LlGep>) -> String {
let Some(gep) = definitions.get(name) else {
return name.to_string();
};
let LlValue::Local(base) = &gep.base.value else {
return name.to_string();
};
if !gep.indices.iter().all(|index| {
matches!(
index.value,
LlValue::Int(_) | LlValue::Hex(_) | LlValue::SignedInt(_) | LlValue::Zero
)
}) {
return name.to_string();
}
format!(
"gep {base} {:?} {:?}",
gep.source_ty,
gep.indices
.iter()
.map(|index| &index.value)
.collect::<Vec<_>>()
)
}
+176 -353
View File
@@ -49,25 +49,15 @@ impl Emitter {
self.emit_binary_int_op_resolved(op, lhs, rhs, name, instructions)
}
BinaryKind::Float => {
if inst.fast_math()
&& self.try_emit_partitioned_fast_sum(
if let Some(mode) = inst.float_math_mode() {
return self.emit_float_op_granting(
op,
&lhs,
&name,
lhs,
rhs,
name,
mode,
instructions,
)?
{
return Ok(());
}
if inst.fast_math()
&& self.try_emit_grouped_fast_sum(
op,
&lhs,
&name,
instructions,
)?
{
return Ok(());
);
}
if inst.fast_math()
&& self.try_emit_fast_fma(
@@ -539,193 +529,6 @@ impl Emitter {
Ok(true)
}
fn try_emit_grouped_fast_sum(
&mut self,
op: Op,
lhs: &TypedValue,
name: &str,
instructions: &mut Vec<Instruction>,
) -> Result<bool, String> {
if op != Op::FAdd {
return Ok(false);
}
let Some((positive, negative, materialize_leading_pair)) =
self.fast_grouped_sums.get(name).cloned()
else {
return Ok(false);
};
let result_ty = self.resolve_type(&lhs.ty)?;
if !is_float_type(&result_ty) || bfloat_lanes(&result_ty).is_some() {
return Ok(false);
}
let result_type = self.type_id(&result_ty)?;
let mut emit_group = |terms: Vec<(TypedValue, bool)>,
materialize_leading_pair: bool,
this: &mut Self|
-> Result<Word, String> {
let mut terms = terms.into_iter();
let (first, negate) = terms.next().ok_or("empty grouped fast sum")?;
let mut sum = this.value_id_in(&first.value, &first.ty, instructions)?;
if matches!(&first.value, LlValue::Local(name) if this.fast_grouped_sum_boundaries.contains(name))
{
sum = this.materialize_float_bits(sum, &result_ty, instructions)?;
}
if negate {
let negated = this.fresh();
instructions.push(Self::inst(
Op::FNegate,
Some(result_type),
Some(negated),
vec![Operand::IdRef(sum)],
));
sum = negated;
}
for (index, (term, negate)) in terms.enumerate() {
let mut rhs = this.value_id_in(&term.value, &term.ty, instructions)?;
if matches!(&term.value, LlValue::Local(name) if this.fast_grouped_sum_boundaries.contains(name))
{
rhs = this.materialize_float_bits(rhs, &result_ty, instructions)?;
}
if negate {
let negated = this.fresh();
instructions.push(Self::inst(
Op::FNegate,
Some(result_type),
Some(negated),
vec![Operand::IdRef(rhs)],
));
rhs = negated;
}
let next = this.fresh();
instructions.push(Self::inst(
Op::FAdd,
Some(result_type),
Some(next),
vec![Operand::IdRef(sum), Operand::IdRef(rhs)],
));
sum = next;
if materialize_leading_pair && index == 0 {
sum = this.materialize_float_bits(sum, &result_ty, instructions)?;
}
}
Ok(sum)
};
let positive = emit_group(positive, materialize_leading_pair, self)?;
let negative = emit_group(negative, false, self)?;
let positive = self.materialize_float_bits(positive, &result_ty, instructions)?;
let negative = self.materialize_float_bits(negative, &result_ty, instructions)?;
let result = self.result_id(name, &result_ty)?;
instructions.push(Self::inst(
Op::FAdd,
Some(result_type),
Some(result),
vec![Operand::IdRef(positive), Operand::IdRef(negative)],
));
Ok(true)
}
fn try_emit_partitioned_fast_sum(
&mut self,
op: Op,
lhs: &TypedValue,
name: &str,
instructions: &mut Vec<Instruction>,
) -> Result<bool, String> {
if op != Op::FAdd {
return Ok(false);
}
let Some(groups) = self.fast_partitioned_sums.get(name).cloned() else {
return Ok(false);
};
let result_ty = self.resolve_type(&lhs.ty)?;
if !is_float_type(&result_ty) || bfloat_lanes(&result_ty).is_some() {
return Ok(false);
}
let result_type = self.type_id(&result_ty)?;
let mut group_values = Vec::with_capacity(groups.len());
for group in groups {
let mut terms = group.into_iter();
let first = terms.next().ok_or("empty partitioned fast sum")?;
let mut sum = self.value_id_in(&first.value, &first.ty, instructions)?;
for term in terms {
let rhs = self.value_id_in(&term.value, &term.ty, instructions)?;
let next = self.fresh();
instructions.push(Self::inst(
Op::FAdd,
Some(result_type),
Some(next),
vec![Operand::IdRef(sum), Operand::IdRef(rhs)],
));
sum = self.materialize_float_bits(next, &result_ty, instructions)?;
}
group_values.push(self.materialize_float_bits(sum, &result_ty, instructions)?);
}
let mut groups = group_values.into_iter();
let mut sum = groups.next().ok_or("empty partitioned fast sum")?;
for rhs in groups {
let next = self.fresh();
instructions.push(Self::inst(
Op::FAdd,
Some(result_type),
Some(next),
vec![Operand::IdRef(sum), Operand::IdRef(rhs)],
));
sum = next;
}
let result = self.result_id(name, &result_ty)?;
instructions.push(Self::inst(
Op::CopyObject,
Some(result_type),
Some(result),
vec![Operand::IdRef(sum)],
));
Ok(true)
}
fn materialize_float_bits(
&mut self,
value: Word,
ty: &LlType,
instructions: &mut Vec<Instruction>,
) -> Result<Word, String> {
let bits_ty = match ty {
LlType::Float => LlType::Int(32),
LlType::Half => LlType::Int(16),
_ => return Ok(value),
};
let bits_type = self.type_id(&bits_ty)?;
let bits = self.fresh();
instructions.push(Self::inst(
Op::Bitcast,
Some(bits_type),
Some(bits),
vec![Operand::IdRef(value)],
));
let reversed = self.fresh();
instructions.push(Self::inst(
Op::BitReverse,
Some(bits_type),
Some(reversed),
vec![Operand::IdRef(bits)],
));
let restored_bits = self.fresh();
instructions.push(Self::inst(
Op::BitReverse,
Some(bits_type),
Some(restored_bits),
vec![Operand::IdRef(reversed)],
));
let result_type = self.type_id(ty)?;
let restored = self.fresh();
instructions.push(Self::inst(
Op::Bitcast,
Some(result_type),
Some(restored),
vec![Operand::IdRef(restored_bits)],
));
Ok(restored)
}
fn bind_inline_parameter(
&mut self,
name: &str,
@@ -783,7 +586,7 @@ impl Emitter {
.cloned()
.filter(|raw| {
!raw.unmodelable
&& ((self.raw_buffer_params.contains(name) && raw.addrspace == 1)
&& ((self.is_raw_buffer_param(name) && matches!(raw.addrspace, 1 | 2))
|| (self.bda_device_pointers && raw.device_addr_base.is_some()))
})
.or_else(|| {
@@ -897,15 +700,15 @@ impl Emitter {
if let Some(nullness) = nullness {
self.record_pointer_nullness(name.to_string(), nullness);
}
if let Some(mut raw) = inline_raw.filter(|raw| {
self.raw_buffer_params.contains(name) || raw.device_addr_base.is_some()
}) {
if let Some(mut raw) = inline_raw
.filter(|raw| self.is_raw_buffer_param(name) || raw.device_addr_base.is_some())
{
raw.root = name.to_string();
self.raw_offsets.insert(name.to_string(), raw);
if let Some(storage) = inline_raw_storage {
self.pointer_storage.insert(name.to_string(), storage);
}
} else if self.raw_buffer_params.contains(name) {
} else if self.is_raw_buffer_param(name) {
self.raw_offsets.insert(
name.to_string(),
RawBufferOffset::root(name.to_string(), addrspace),
@@ -1605,6 +1408,38 @@ impl Emitter {
self.pointer_pointees.insert(name, LlType::Int(8));
return Ok(());
}
// An integer that is a bound buffer's address plus a byte offset names a byte inside that
// buffer, and the round trip through `ptrtoint`/`inttoptr` is the only place its address was
// ever needed. Hand the pointer the offset rather than a placeholder: without this the
// pointer is unmodelled and every load through it reads zero, silently.
if let LlValue::Local(src_name) = &src.value {
if let Some(base) = self.symbolic_buffer_addresses.get(src_name).cloned() {
if base.addrspace == addrspace {
// The raw word path indexes its root in WORDS: it emits `AccessChain(root, 0,
// word)` typed `ptr uint`, which is only well typed when the root was declared
// with `raw_buffer_block_type()`. A root the AIR metadata typed instead keeps
// its own element type, and the same chain would be read back as a BYTE index
// by `plan_raw_word_pointer_rewrite` and divided by four a second time. Refuse
// rather than answer the wrong word.
if !self.root_is_word_addressable(&base.root) {
return Err(format!(
"native emitter: buffer address round trip through `{name}` on the \
untyped byte root `{}`",
base.root
));
}
let storage = self.raw_access_storage(&base)?;
// The placeholder still has to exist: it is this name's SSA value, and anything
// that consumes the pointer itself rather than accessing through it needs one.
// The raw entry installed after it is the ADDRESSING, and every emitter function
// that reads both sets reads `raw_offsets` first.
self.define_unmodeled_pointer_value(&name, addrspace, &LlType::Int(8))?;
self.raw_offsets.insert(name.clone(), base);
self.pointer_storage.insert(name.clone(), storage);
return Ok(());
}
}
}
// Logical SPIR-V cannot materialize an integer as an address. Preserve a valid SSA pointer so
// function-constant-dead command-buffer paths translate without claiming active GPU-address
// semantics.
@@ -1746,9 +1581,15 @@ impl Emitter {
));
}
}
if let LlValue::Local(src_name) = &src.value {
if let Some(base) = self.symbolic_buffer_address_for_pointer(src_name) {
self.symbolic_buffer_addresses.insert(name.clone(), base);
}
}
let _ = self.value_id(&src.value, &src.ty)?;
// Logical SPIR-V has no portable pointer address value. Keep GPU-address arithmetic paths
// structurally valid without claiming physical pointer semantics.
// structurally valid without claiming physical pointer semantics. The ADDRESS this stands
// for is recorded above, so a round trip back to a pointer does not lose the buffer.
let zero = self.const_null(&dst_ty)?;
let result = self.result_id(&name, &dst_ty)?;
instructions.push(Self::inst(
@@ -1906,8 +1747,21 @@ impl Emitter {
if self.emit_vector_root_store(&ptr, &object, instructions)? {
return Ok(());
}
if matches!(&ptr.value, LlValue::Local(name) if self.unmodeled_pointers.contains(name)) {
return Ok(());
// An unmodeled pointer is a Private zero placeholder: it stands for an address the emitter
// could not model, and it addresses nothing. Dropping a store through one used to return
// `Ok(())`, which reports success for a module that has silently lost the write --
// `native_generic_callback_table_cursor_keeps_its_store` is a twenty-line AIR fixture whose
// emitted module contains no `OpStore` at all. Refuse instead, so the retry tiers get a
// chance at a representation and an unrepresentable module FALLBACKs rather than lying.
//
// Costs nothing: no source among the 14579 in the corpus reaches this line, and none even
// contains the shape that leads here (a device pointer loaded through a generic `ptr`).
if let LlValue::Local(name) = &ptr.value {
if self.unmodeled_pointers.contains(name) {
return Err(format!(
"native emitter: store through {name}, an unmodeled pointer placeholder that addresses nothing; the write would be lost"
));
}
}
if let Some(pointee) = self.pointer_pointee_for_value(&ptr.value)? {
let pointee = self.resolve_type(&pointee)?;
@@ -1944,117 +1798,14 @@ impl Emitter {
}
}
}
if !types_compatible(&pointee, &object_ty)
&& self.emit_i64_to_i32_pair_struct_store(&object, &ptr, &pointee, instructions)?
{
return Ok(());
}
if !types_compatible(&pointee, &object_ty)
&& self.emit_aggregate_prefix_integer_reinterpret_store(
&object,
&ptr,
&object_ty,
&pointee,
instructions,
)?
{
return Ok(());
}
if !types_compatible(&pointee, &object_ty)
&& self.emit_first_vector_aggregate_reinterpret_store(
&object,
&ptr,
&object_ty,
&pointee,
instructions,
)?
{
return Ok(());
}
if !types_compatible(&pointee, &object_ty)
&& self.emit_first_scalar_aggregate_reinterpret_store(
&object,
&ptr,
&object_ty,
&pointee,
instructions,
)?
{
return Ok(());
}
if !types_compatible(&pointee, &object_ty)
&& self.emit_zero_scalar_to_aggregate_store(
&object,
&ptr,
&object_ty,
&pointee,
instructions,
)?
{
return Ok(());
}
if !types_compatible(&pointee, &object_ty)
&& self.emit_vector_as_scalar_array_store(&object, &ptr, &pointee, instructions)?
{
return Ok(());
}
if !types_compatible(&pointee, &object_ty)
&& self.emit_vector_to_scalar_stores(&object, &ptr, &pointee, instructions)?
{
return Ok(());
}
if !types_compatible(&pointee, &object_ty)
&& self.emit_workgroup_vector_chunk_stores(
&object,
&ptr,
&object_ty,
&pointee,
instructions,
)?
{
return Ok(());
}
if !types_compatible(&pointee, &object_ty)
&& self.emit_widening_vector_store(&object, &ptr, &pointee, instructions)?
{
return Ok(());
}
if !types_compatible(&pointee, &object_ty)
&& self.emit_narrowing_vector_store(&object, &ptr, &pointee, instructions)?
{
return Ok(());
}
if !types_compatible(&pointee, &object_ty)
&& self.emit_same_width_scalar_store(
&object,
&ptr,
&object_ty,
&pointee,
instructions,
)?
{
return Ok(());
}
if !types_compatible(&pointee, &object_ty)
&& self.emit_scalar_narrowing_store(
&object,
&ptr,
&object_ty,
&pointee,
instructions,
)?
{
return Ok(());
}
if !types_compatible(&pointee, &object_ty)
&& self.emit_same_width_vector_reinterpret_store(
&object,
&ptr,
&object_ty,
&pointee,
instructions,
)?
{
if self.emit_mismatched_store(
&object,
&ptr,
&object_ty,
&pointee,
align,
instructions,
)? {
return Ok(());
}
}
@@ -2151,10 +1902,10 @@ impl Emitter {
if self.emit_llvm_usub_sat_call(&call, &name, instructions)? {
return Ok(());
}
if self.emit_air_unsigned_sat_call(&call, &name, instructions)? {
if self.emit_air_saturating_add_sub_call(&call, &name, instructions)? {
return Ok(());
}
if self.emit_air_unsigned_rhadd_call(&call, &name, instructions)? {
if self.emit_air_halving_add_call(&call, &name, instructions)? {
return Ok(());
}
if self.emit_llvm_int_minmax_call(&call, &name, instructions)? {
@@ -2195,6 +1946,27 @@ impl Emitter {
/// source typed value + destination-type TEXT. Driven straight off the `TirInst.bitcast()` carrier
/// by the graph walk. The pointer
/// copy-prop side-tables are keyed on `src.value`'s local name, so this needs no `inst.text`.
/// Carry the structural facts a same-address-space pointer `bitcast` aliases, for the arms of
/// [`Self::emit_bitcast_resolved`] whose side table already says what the pointer IS. Storage
/// class, nullness and pointee are properties of the address, and the address is unchanged by
/// an identity bitcast; `param_values` records that the alias is still a parameter's own
/// pointer. Written once because a missing propagation here is invisible until some later
/// consumer of the alias asks the question the dropped fact answered.
fn alias_pointer_facts(&mut self, src_name: &str, name: &str) {
if let Some(storage) = self.pointer_storage.get(src_name).copied() {
self.pointer_storage.insert(name.to_string(), storage);
}
if let Some(is_null) = self.pointer_nullness.get(src_name).copied() {
self.record_pointer_nullness(name.to_string(), is_null);
}
if let Some(pointee) = self.pointer_pointees.get(src_name).cloned() {
self.pointer_pointees.insert(name.to_string(), pointee);
}
if self.param_values.contains(src_name) {
self.param_values.insert(name.to_string());
}
}
pub(in crate::native::emitter) fn emit_bitcast_resolved(
&mut self,
src: TypedValue,
@@ -2226,30 +1998,23 @@ impl Emitter {
}
if let Some(selected) = self.selected_load_pointers.get(src_name).cloned() {
self.selected_load_pointers.insert(name.clone(), selected);
if let Some(storage) = self.pointer_storage.get(src_name).copied() {
self.pointer_storage.insert(name.clone(), storage);
}
if let Some(is_null) = self.pointer_nullness.get(src_name).copied() {
self.record_pointer_nullness(name.clone(), is_null);
}
if let Some(pointee) = self.pointer_pointees.get(src_name).cloned() {
self.pointer_pointees.insert(name.clone(), pointee);
}
if self.param_values.contains(src_name) {
self.param_values.insert(name.clone());
}
self.alias_pointer_facts(src_name, &name);
return Ok(());
}
// The plain pointer merge, the fourth side table an alias has to carry. Without this
// arm the alias falls through to `value_id(%sel)` and dies with "unknown SSA value":
// a merge is deferred into `selected_pointers` and never materialized as a plain
// SPIR-V pointer, exactly as the store path at `emit_selected_pointer_direct_store`
// records. This is the result-side twin of 72d95483, which taught the merge-ARM walk
// to follow the same `bitcast ptr %p to ptr` the frontend spells a device-pointer
// cast with.
if let Some(selected) = self.selected_pointers.get(src_name).cloned() {
self.selected_pointers.insert(name.clone(), selected);
self.alias_pointer_facts(src_name, &name);
return Ok(());
}
if let Some(raw) = self.raw_offsets.get(src_name).cloned() {
if let Some(storage) = self.pointer_storage.get(src_name).copied() {
self.pointer_storage.insert(name.clone(), storage);
}
if let Some(is_null) = self.pointer_nullness.get(src_name).copied() {
self.record_pointer_nullness(name.clone(), is_null);
}
if let Some(pointee) = self.pointer_pointees.get(src_name).cloned() {
self.pointer_pointees.insert(name.clone(), pointee);
}
self.alias_pointer_facts(src_name, &name);
if !self.pointer_phi_values.is_empty() {
self.materialize_raw_byte_index(&name, &raw, true, instructions)?;
if self.raw_pointer_word_aligned(&raw) {
@@ -2276,9 +2041,6 @@ impl Emitter {
}
};
self.define_unmodeled_byte_pointer_value(&name, addrspace)?;
if self.param_values.contains(src_name) {
self.param_values.insert(name.clone());
}
return Ok(());
}
}
@@ -2363,9 +2125,63 @@ impl Emitter {
without a logical-pointer bitcast"
));
}
// Vulkan vectors carry at most four components, so `type_id` gives a wider LLVM vector
// an `OpTypeArray` -- and `OpBitcast` does not accept an aggregate operand or result.
// Reinterpret one lane at a time and rebuild the array, the same scalarization the
// elementwise integer ops already apply at this width.
(LlType::Vector(src_elem, src_lanes), LlType::Vector(dst_elem, dst_lanes))
if *src_lanes > 4 && src_lanes == dst_lanes =>
{
let src_elem_ty = self.resolve_type(src_elem)?;
let dst_elem_ty = self.resolve_type(dst_elem)?;
let src_elem_type = self.type_id(&src_elem_ty)?;
let dst_elem_type = self.type_id(&dst_elem_ty)?;
let lanes = *src_lanes;
let result_type = self.type_id(&dst_ty)?;
let result = self.result_id(&name, &dst_ty)?;
if src_elem_type == dst_elem_type {
// Distinct AIR element types can share one storage type (bfloat and i16 do),
// and then the whole array is already the destination value. `OpCopyObject`
// accepts an aggregate, so name the no-op as the copy it is.
instructions.push(Self::inst(
Op::CopyObject,
Some(result_type),
Some(result),
vec![Operand::IdRef(src_id)],
));
result
} else {
let mut values = Vec::with_capacity(lanes as usize);
for lane in 0..lanes {
let component = self.fresh();
instructions.push(Self::inst(
Op::CompositeExtract,
Some(src_elem_type),
Some(component),
vec![Operand::IdRef(src_id), Operand::LiteralBit32(lane)],
));
let cast = self.fresh();
instructions.push(Self::inst(
Op::Bitcast,
Some(dst_elem_type),
Some(cast),
vec![Operand::IdRef(component)],
));
values.push(Operand::IdRef(cast));
}
instructions.push(Self::inst(
Op::CompositeConstruct,
Some(result_type),
Some(result),
values,
));
result
}
}
_ => {
// Distinct AIR types can share one storage type (notably bfloat and i16). SPIR-V
// forbids OpBitcast when the constructed source and result types are identical.
// Distinct AIR types can share one storage type (notably bfloat and i16). An
// OpBitcast whose source and result types are identical is valid SPIR-V but says
// nothing -- name the no-op as the copy it is.
let source_type = self.type_id(&src_ty)?;
let result_type = self.type_id(&dst_ty)?;
let result = self.result_id(&name, &dst_ty)?;
@@ -2473,7 +2289,14 @@ impl Emitter {
// intentionally left undefined — a device pointer is only ever used AS a pointer
// (GEP/store/deref), all routed through `raw_offsets`, never as a plain value.
if self.bda_device_pointers && !self.opaque_resource_pointers.contains(&name) {
if let LlType::Ptr(1) = result_ty {
// `constant` (`addrspace(2)`) is a read-only DEVICE allocation, not a separate
// physical space: a `constant T*` stored in a buffer is the same 64-bit GPU
// address a `device T*` is. Reading only `addrspace(1)` here left every
// constant-space nested pointer on the `Private` placeholder, and every load
// through it folded to zero -- `scn_osd_synchronize_coarse_positions` indexed
// its output array with `0 * 3` where Metal indexes it with the value it just
// read, so all four sources of that family wrote element 0 from every thread.
if let LlType::Ptr(1 | 2) = result_ty {
let addr = self.result_id(&bda_address_name(&name), &LlType::Int(64))?;
self.emit_raw_load(addr, &LlType::Int(64), &raw, load.align, instructions)?;
self.bda_address_values.insert(addr);
@@ -2802,7 +2625,7 @@ impl Emitter {
)? {
return Ok(());
}
if self.emit_scalar_to_wider_vector_load(
if self.emit_scalar_slots_to_wider_load(
result,
&pointee,
&result_ty,
+1 -1
View File
@@ -725,7 +725,7 @@ impl Emitter {
&& base_storage == StorageClass::Workgroup
&& indices.len() >= 2
&& !matches!(&gep.base.value,
LlValue::Local(base_name) if self.raw_buffer_params.contains(base_name));
LlValue::Local(base_name) if self.is_raw_buffer_param(base_name));
let logical_indices = entry_metadata_indices.as_ref().unwrap_or(&indices);
let access_indices = if use_ptr_access_chain {
logical_indices.clone()
+378 -20
View File
@@ -55,11 +55,29 @@ impl Emitter {
if let Some(dst) = dst_raw {
let dst_align = call.arg_aligns.first().copied().flatten();
return self.emit_typed_to_raw_memcpy(
// A destination with no SPIR-V pointer value of its own has exactly one alternative to
// this decomposition: `emit_typed_memcpy` copies the whole object into the `Private`
// placeholder that stands in for it, which writes the buffer nothing at all. Let the
// decomposition leave the source layout's inter-member padding alone rather than
// decline, since `llvm.memcpy` of an aggregate leaves those bytes undefined anyway --
// the surrounding shader writes the same struct member by member and never writes them.
let leave_source_padding = self.unmodeled_pointers.contains(dst_name);
if self.emit_typed_to_raw_memcpy(
&dst,
dst_align,
&call.args[1],
len,
leave_source_padding,
instructions,
)? {
return Ok(true);
}
return self.emit_raw_byte_run_memcpy(
&dst,
dst_align,
&call.args[1],
len,
true,
instructions,
);
}
@@ -95,17 +113,169 @@ impl Emitter {
}
return Ok(true);
}
return self.emit_raw_to_typed_struct_memcpy(&call.args[0], &src, len, instructions);
if self.emit_raw_to_typed_struct_memcpy(&call.args[0], &src, len, instructions)? {
return Ok(true);
}
let dst_align = call.arg_aligns.first().copied().flatten();
return self.emit_raw_byte_run_memcpy(
&src,
dst_align,
&call.args[0],
len,
false,
instructions,
);
}
Ok(false)
}
/// Copy a run of BYTES between a raw byte cursor and a typed pointer that names one `i8`
/// element of a longer local object -- `memcpy(&blob[0], &buffer_field, n)`, where the local is
/// an `[n x i8]` staging alloca. Both whole-object decompositions see only the single byte the
/// typed pointer names and decline, and the call then reached `drop_unmodeled_memcpy`, which
/// discarded it: a copy of a real descriptor-backed buffer that simply did not happen.
///
/// A byte at a time would be correct and unaffordable -- a subword store into a device buffer is
/// an atomic read-modify-write loop. Group four consecutive `i8` lanes into one word instead, so
/// the raw side keeps its plain word access. That needs the length to be a whole number of words
/// and the cursor to be word-aligned; anything else declines, exactly as before.
fn emit_raw_byte_run_memcpy(
&mut self,
raw: &RawBufferOffset,
raw_align: Option<u64>,
typed: &TypedValue,
len: u64,
raw_is_destination: bool,
instructions: &mut Vec<Instruction>,
) -> Result<bool, String> {
if !len.is_multiple_of(4) || !self.raw_pointer_word_aligned(raw) {
return Ok(false);
}
staged_emit(instructions, |instructions| {
let Some((element, count)) = self.gep_element_run(typed, len)? else {
return Ok(false);
};
if self.resolve_type(&element)? != LlType::Int(8) || u64::from(count) != len {
return Ok(false);
}
let uint_ty = self.type_id(&LlType::Int(32))?;
let byte_ty = self.type_id(&LlType::Int(8))?;
for word in 0..(len / 4) {
let mut lane_ptrs = Vec::with_capacity(4);
for lane in 0..4 {
let index = u32::try_from(word * 4 + lane).map_err(|_| {
"native emitter: byte-run memcpy lane index overflows".to_string()
})?;
let Some(ptr) =
self.emit_gep_provenance_lane_ptr(typed, &element, index, instructions)?
else {
return Ok(false);
};
lane_ptrs.push(ptr);
}
if raw_is_destination {
let mut assembled = None;
for (lane, ptr) in lane_ptrs.into_iter().enumerate() {
let byte = self.fresh();
instructions.push(Self::inst(
Op::Load,
Some(byte_ty),
Some(byte),
vec![Operand::IdRef(ptr)],
));
let widened = self.fresh();
instructions.push(Self::inst(
Op::UConvert,
Some(uint_ty),
Some(widened),
vec![Operand::IdRef(byte)],
));
let placed = if lane == 0 {
widened
} else {
let shift = self.const_uint(lane as u32 * 8)?;
let shifted = self.fresh();
instructions.push(Self::inst(
Op::ShiftLeftLogical,
Some(uint_ty),
Some(shifted),
vec![Operand::IdRef(widened), Operand::IdRef(shift)],
));
shifted
};
assembled = Some(match assembled {
None => placed,
Some(previous) => {
let merged = self.fresh();
instructions.push(Self::inst(
Op::BitwiseOr,
Some(uint_ty),
Some(merged),
vec![Operand::IdRef(previous), Operand::IdRef(placed)],
));
merged
}
});
}
let Some(assembled) = assembled else {
return Ok(false);
};
self.emit_raw_word_store_for_access(
raw,
word * 4,
assembled,
raw_align,
instructions,
)?;
} else {
let value = self.emit_raw_word_load(raw, word * 4, instructions)?;
for (lane, ptr) in lane_ptrs.into_iter().enumerate() {
let placed = if lane == 0 {
value
} else {
let shift = self.const_uint(lane as u32 * 8)?;
let shifted = self.fresh();
instructions.push(Self::inst(
Op::ShiftRightLogical,
Some(uint_ty),
Some(shifted),
vec![Operand::IdRef(value), Operand::IdRef(shift)],
));
shifted
};
let narrowed = self.fresh();
instructions.push(Self::inst(
Op::UConvert,
Some(byte_ty),
Some(narrowed),
vec![Operand::IdRef(placed)],
));
instructions.push(Self::inst(
Op::Store,
None,
None,
vec![Operand::IdRef(ptr), Operand::IdRef(narrowed)],
));
}
}
}
Ok(true)
})
}
/// Store a typed aggregate through a raw byte cursor, one 32-bit word per leaf.
///
/// `leave_source_padding` admits a word set that does not cover every word of `len`. The walk
/// visits every leaf of the source type at its own layout offset, so a gap is inter-member
/// padding and never data; leaving those destination bytes unchanged is one of the undefined
/// values `llvm.memcpy` of an aggregate may leave there.
pub(in crate::native::emitter) fn emit_typed_to_raw_memcpy(
&mut self,
dst: &RawBufferOffset,
dst_align: Option<u64>,
src: &TypedValue,
len: u64,
leave_source_padding: bool,
instructions: &mut Vec<Instruction>,
) -> Result<bool, String> {
staged_emit(instructions, |instructions| {
@@ -139,25 +309,78 @@ impl Emitter {
return Ok(false);
}
words.sort_by_key(|(offset, _)| *offset);
let expected_words = (len / 4) as usize;
if words.len() != expected_words {
let Some(words_with_padding) =
self.typed_memcpy_words_with_raw_padding(src, len, words)?
else {
return Ok(false);
};
words = words_with_padding;
if words.len() != (len / 4) as usize {
match self.typed_memcpy_words_with_raw_padding(src, len, words.clone())? {
Some(words_with_padding) => words = words_with_padding,
None if leave_source_padding => {}
None => return Ok(false),
}
}
for (index, (offset, word)) in words.into_iter().enumerate() {
if offset != (index as u64) * 4 {
let mut previous = None;
for (offset, word) in words {
if !offset.is_multiple_of(4)
|| offset + 4 > len
|| previous.is_some_and(|previous| previous >= offset)
{
return Ok(false);
}
previous = Some(offset);
self.emit_raw_word_store_for_access(dst, offset, word, dst_align, instructions)?;
}
Ok(true)
})
}
/// Copy a `memcpy` that spans MORE than the object either pointer names: `memcpy(&a[0], &b[k],
/// n * sizeof(T))` names one element on each side and copies `n`. The whole-object path below is
/// short by `n - 1` elements and says nothing about it — a 296-byte copy through two `i8` element
/// pointers came out as a single-byte `OpCopyMemory`. Walk the run through both pointers' own GEP
/// provenance, the same element-striding primitive [`Self::emit_element_run_zero_memset`] uses.
///
/// Returns `false` — and `emit_typed_memcpy` then declines the call entirely, which hands it to
/// `drop_unmodeled_memcpy` and the retry tiers — when either side has no element-striding
/// provenance, when the two element types disagree, when the length does not divide evenly, or
/// when the element is a pointer. Declining is the point: the four corpus modules whose source
/// pointer is an unmodelled `Private` placeholder reach `drop_unmodeled_memcpy`, which is where
/// they belonged, instead of copying one byte out of a variable that addresses nothing.
fn emit_element_run_memcpy(
&mut self,
dst: &TypedValue,
src: &TypedValue,
len: u64,
instructions: &mut Vec<Instruction>,
) -> Result<bool, String> {
let Some((dst_element, count)) = self.gep_element_run(dst, len)? else {
return Ok(false);
};
let Some((src_element, src_count)) = self.gep_element_run(src, len)? else {
return Ok(false);
};
if count != src_count || !types_compatible(&dst_element, &src_element) {
return Ok(false);
}
let LlType::Ptr(dst_addrspace) = self.resolve_type(&dst.ty)? else {
return Ok(false);
};
let dst_storage = self.pointer_storage_for(&dst.value, dst_addrspace)?;
let mut staged = Vec::new();
for lane in 0..count {
let Some(dst_ptr) =
self.emit_gep_provenance_lane_ptr(dst, &dst_element, lane, &mut staged)?
else {
return Ok(false);
};
let Some(src_ptr) =
self.emit_gep_provenance_lane_ptr(src, &src_element, lane, &mut staged)?
else {
return Ok(false);
};
self.emit_copy_memory(dst_ptr, src_ptr, dst_storage, &dst_element, &mut staged)?;
}
instructions.extend(staged);
Ok(true)
}
pub(in crate::native::emitter) fn typed_memcpy_words_with_raw_padding(
&self,
src: &TypedValue,
@@ -632,6 +855,58 @@ impl Emitter {
Ok(Some((provenance.root, provenance.addrspace, base)))
}
/// The type a pointer's own `getelementptr` chain names, when it has one. Distinct from
/// [`Self::pointer_pointee_for_value`]'s Function-storage view, which rewrites device pointers to
/// `Int(64)`; an access chain built from this provenance is typed by THIS type.
fn gep_provenance_element_type(&self, ptr: &TypedValue) -> Result<Option<LlType>, String> {
let LlValue::Local(name) = &ptr.value else {
return Ok(None);
};
let Some(provenance) = self.gep_provenance.get(name) else {
return Ok(None);
};
if provenance.indices.is_empty() {
return Ok(None);
}
Ok(Some(gep_pointee(
&provenance.source_ty,
&provenance.indices,
)?))
}
/// The element RUN a byte length addresses through `ptr`: the element type and how many of them
/// `len` covers, or `None` when the pointer does not address a contiguous run of them.
///
/// The element type comes from the pointer's own `getelementptr` chain, not from
/// [`Self::pointer_pointee_for_value`]'s Function-storage view, because the striding primitive
/// ([`Self::emit_gep_provenance_lane_ptr`]) types its access chain from the GEP. A `ptr` element is
/// refused for exactly that reason: a `[N x ptr addrspace(1)]` local declares `Int(64)` slots while
/// its GEP names `Ptr`, so a chain built from the GEP cannot address the array the local is.
fn gep_element_run(
&mut self,
ptr: &TypedValue,
len: u64,
) -> Result<Option<(LlType, u32)>, String> {
let Some(element) = self.gep_provenance_element_type(ptr)? else {
return Ok(None);
};
let element = self.resolve_type(&element)?;
if matches!(element, LlType::Ptr(_)) {
return Ok(None);
}
let (element_size, _) = self.raw_type_size_align(&element)?;
if element_size == 0 || !len.is_multiple_of(element_size) {
return Ok(None);
}
let Ok(count) = u32::try_from(len / element_size) else {
return Ok(None);
};
if !self.can_emit_gep_provenance_lane_ptrs(ptr, &element)? {
return Ok(None);
}
Ok(Some((element, count)))
}
pub(in crate::native::emitter) fn emit_zero_memset(
&mut self,
call: &LlCall,
@@ -690,6 +965,9 @@ impl Emitter {
"native emitter: partial zero memset cuts through a scalar subobject of {storage_pointee:?}"
));
}
if len > size && self.emit_element_run_zero_memset(&call.args[0], len, instructions)? {
return Ok(true);
}
let ptr = self.value_id(&call.args[0].value, &call.args[0].ty)?;
let zero = self.const_null(&storage_pointee)?;
instructions.push(Self::inst(
@@ -701,6 +979,47 @@ impl Emitter {
Ok(true)
}
/// Clear a `memset` that spans MORE than its pointee object: `memset(&a[k], 0, n * sizeof(T))`
/// names one element and clears `n` of them, and the single null store below is short by `n - 1`
/// elements. Walk the run through the destination's own GEP provenance instead — the same
/// element-striding primitive the vector loads use, which keeps `Function`/`Private` roots on
/// `OpInBoundsAccessChain` where `OpPtrAccessChain` is illegal.
///
/// Returns `false` (the caller keeps its single store) when the run does not divide evenly into
/// elements, when the pointer's last index does not stride a contiguous array/vector element —
/// striding a struct member would walk into a differently typed neighbour — or when the element is
/// a pointer. That last one is the `[N x ptr addrspace(1)]` device-pointer table: the local
/// declares `Int(64)` slots, the GEP names `Ptr`, and the striding primitive types its chain from
/// the GEP, so it cannot address the array the local actually is. Zeroing a device pointer is the
/// separate unmodelled-placeholder problem and is left exactly as it was.
fn emit_element_run_zero_memset(
&mut self,
dst: &TypedValue,
len: u64,
instructions: &mut Vec<Instruction>,
) -> Result<bool, String> {
let Some((element, count)) = self.gep_element_run(dst, len)? else {
return Ok(false);
};
let zero = self.const_null(&element)?;
let mut staged = Vec::new();
for lane in 0..count {
let Some(pointer) =
self.emit_gep_provenance_lane_ptr(dst, &element, lane, &mut staged)?
else {
return Ok(false);
};
staged.push(Self::inst(
Op::Store,
None,
None,
vec![Operand::IdRef(pointer), Operand::IdRef(zero)],
));
}
instructions.extend(staged);
Ok(true)
}
#[allow(clippy::too_many_arguments)]
fn emit_typed_zero_prefix(
&mut self,
@@ -952,6 +1271,16 @@ impl Emitter {
let src_pointee = self.resolve_type(&src_pointee)?;
let copy_pointee = function_storage_local_type(&src_pointee);
let (copy_size, _) = self.raw_type_size_align(&copy_pointee)?;
if len > copy_size {
// The copy outruns the object its pointer names, so copying that object is short by
// `len / copy_size - 1` elements. See `emit_element_run_zero_memset`.
return self.emit_element_run_memcpy(
&call.args[0],
&call.args[1],
len,
instructions,
);
}
if len < copy_size {
if !types_compatible(&dst_pointee, &src_pointee) {
return self.emit_prefix_source_struct_memcpy(
@@ -1004,7 +1333,7 @@ impl Emitter {
src_storage,
)? {
let dst = self.value_id(&call.args[0].value, &call.args[0].ty)?;
self.emit_copy_memory(dst, src, instructions);
self.emit_copy_memory(dst, src, dst_storage, &dst_pointee, instructions)?;
return Ok(true);
}
@@ -1173,18 +1502,47 @@ impl Emitter {
Ok(true)
}
/// Copy one whole object from `src` to `dst`.
///
/// `OpCopyMemory` is the natural spelling and is what this emits everywhere it can. It cannot be
/// used when the DESTINATION is an interface-backed block: SPIRV-Cross's write analysis does not
/// count an `OpCopyMemory` as a write, so a `StorageBuffer` written only that way is rendered
/// `const device _N&` in MSL, the assignment into it does not compile, and MoltenVK answers
/// `create compute pipeline: Initialization of an object has failed`. `spirv-val` is happy with
/// the module either way, which is why this survived. An `OpLoad` plus an `OpStore` is the same
/// copy and SPIRV-Cross does count that.
pub(in crate::native::emitter) fn emit_copy_memory(
&self,
&mut self,
dst: Word,
src: Word,
dst_storage: StorageClass,
pointee: &LlType,
instructions: &mut Vec<Instruction>,
) {
) -> Result<(), String> {
if !is_interface_backed_copy_storage(dst_storage) {
instructions.push(Self::inst(
Op::CopyMemory,
None,
None,
vec![Operand::IdRef(dst), Operand::IdRef(src)],
));
return Ok(());
}
let object_ty = self.type_id(&function_storage_local_type(pointee))?;
let object = self.fresh();
instructions.push(Self::inst(
Op::CopyMemory,
None,
None,
vec![Operand::IdRef(dst), Operand::IdRef(src)],
Op::Load,
Some(object_ty),
Some(object),
vec![Operand::IdRef(src)],
));
instructions.push(Self::inst(
Op::Store,
None,
None,
vec![Operand::IdRef(dst), Operand::IdRef(object)],
));
Ok(())
}
pub(in crate::native::emitter) fn emit_aggregate_memcpy(
@@ -1202,7 +1560,7 @@ impl Emitter {
return Ok(true);
}
if self.can_emit_whole_copy_memory(dst_pointee, src_pointee, dst_storage, src_storage)? {
self.emit_copy_memory(dst, src, instructions);
self.emit_copy_memory(dst, src, dst_storage, dst_pointee, instructions)?;
return Ok(true);
}
+49 -24
View File
@@ -311,37 +311,62 @@ impl Emitter {
let Some(key) = self.local_pointer_field_key(ptr)? else {
return Ok(false);
};
if self.bda_device_pointers
&& matches!(result_ty, LlType::Ptr(1))
&& self.bda_forward_addresses.contains(result_name)
{
if self.bda_forwards_local_pointer_field(result_name, result_ty) {
let pointer = self.value_id_in(&ptr.value, &ptr.ty, instructions)?;
let address_type = self.type_id(&LlType::Int(64))?;
let address = self.result_id(&bda_address_name(result_name), &LlType::Int(64))?;
instructions.push(Self::inst(
Op::Load,
Some(address_type),
Some(address),
vec![Operand::IdRef(pointer)],
));
self.bda_address_values.insert(address);
self.bda_direct_addresses
.insert(result_name.to_string(), address);
let mut raw = RawBufferOffset::root(format!(".bda_{address}"), 1);
raw.device_addr_base = Some(address);
self.raw_offsets.insert(result_name.to_string(), raw);
self.pointer_storage
.insert(result_name.to_string(), StorageClass::PhysicalStorageBuffer);
self.pointer_pointees
.insert(result_name.to_string(), LlType::Int(8));
self.emit_device_address_nullness(result_name, address, instructions)?;
self.used_device_address = true;
self.emit_bda_address_from_field(result_name, pointer, instructions)?;
return Ok(true);
}
self.emit_pointer_from_local_field_key(result_name, result, result_ty, &key, instructions)?;
Ok(true)
}
/// True when a pointer read out of a LOCAL aggregate field is a device address this module
/// forwards, i.e. the field holds an `i64` payload that is really a `device` pointer. Both
/// spellings of the field access have to ask the same question: LLVM writes the zero-offset
/// member either as a GEP or as a bare `bitcast`, and only the GEP arrives with the field's own
/// `i64` pointee attached.
pub(in crate::native::emitter) fn bda_forwards_local_pointer_field(
&self,
result_name: &str,
result_ty: &LlType,
) -> bool {
self.bda_device_pointers
&& matches!(result_ty, LlType::Ptr(1))
&& self.bda_forward_addresses.contains(result_name)
}
/// Read the 64-bit device address a local aggregate field holds and register the result as an
/// address-rooted pointer. `field_pointer` must already point AT the field (an `i64` payload),
/// not at the aggregate containing it.
pub(in crate::native::emitter) fn emit_bda_address_from_field(
&mut self,
result_name: &str,
field_pointer: Word,
instructions: &mut Vec<Instruction>,
) -> Result<(), String> {
let address_type = self.type_id(&LlType::Int(64))?;
let address = self.result_id(&bda_address_name(result_name), &LlType::Int(64))?;
instructions.push(Self::inst(
Op::Load,
Some(address_type),
Some(address),
vec![Operand::IdRef(field_pointer)],
));
self.bda_address_values.insert(address);
self.bda_direct_addresses
.insert(result_name.to_string(), address);
let mut raw = RawBufferOffset::root(format!(".bda_{address}"), 1);
raw.device_addr_base = Some(address);
self.raw_offsets.insert(result_name.to_string(), raw);
self.pointer_storage
.insert(result_name.to_string(), StorageClass::PhysicalStorageBuffer);
self.pointer_pointees
.insert(result_name.to_string(), LlType::Int(8));
self.emit_device_address_nullness(result_name, address, instructions)?;
self.used_device_address = true;
Ok(())
}
pub(in crate::native::emitter) fn emit_pointer_from_local_field_key(
&mut self,
result_name: &str,
+92 -25
View File
@@ -179,10 +179,28 @@ impl Emitter {
return Ok(false);
};
let elem = self.resolve_type(elem)?;
if !types_compatible(pointee, &elem) || *lanes == 0 {
if *lanes == 0 {
return Ok(false);
}
if *lanes > 1 && !self.can_emit_gep_provenance_lane_ptrs(ptr_value, &elem)? {
// The lanes are addressed as SLOTS of the pointee type, and each slot is reinterpreted into
// the result's element type. When the two agree the reinterpret is the identity; when they
// are incompatible but equal in width it is one `OpBitcast` per lane. That is exactly the
// set `emit_vector_to_scalar_stores` accepts in the other direction, and the two must accept
// the same set or a module cannot read back the vector it just wrote lane by lane.
let slot_ty = if types_compatible(pointee, &elem) {
elem.clone()
} else {
let (Some(elem_bits), Some(pointee_bits)) =
(bitcast_width(&elem), bitcast_width(pointee))
else {
return Ok(false);
};
if elem_bits != pointee_bits {
return Ok(false);
}
pointee.clone()
};
if *lanes > 1 && !self.can_emit_gep_provenance_lane_ptrs(ptr_value, &slot_ty)? {
return self.emit_scalar_pointer_vector_load(
result,
&elem,
@@ -198,7 +216,7 @@ impl Emitter {
let lane_ptr = if lane == 0 {
ptr
} else {
self.emit_gep_provenance_lane_ptr(ptr_value, &elem, lane, instructions)?
self.emit_gep_provenance_lane_ptr(ptr_value, &slot_ty, lane, instructions)?
.ok_or_else(|| {
"native emitter: scalar-to-vector load lost pointer provenance".to_string()
})?
@@ -207,15 +225,29 @@ impl Emitter {
}
let elem_type = self.type_id(&elem)?;
let slot_type = self.type_id(&slot_ty)?;
let lanes_need_bitcast = slot_type != elem_type;
let mut lane_ids = Vec::with_capacity(*lanes as usize);
for lane_ptr in lane_ptrs {
let lane_id = self.fresh();
instructions.push(Self::inst(
Op::Load,
Some(elem_type),
Some(slot_type),
Some(lane_id),
vec![Operand::IdRef(lane_ptr)],
));
let lane_id = if lanes_need_bitcast {
let reinterpreted = self.fresh();
instructions.push(Self::inst(
Op::Bitcast,
Some(elem_type),
Some(reinterpreted),
vec![Operand::IdRef(lane_id)],
));
reinterpreted
} else {
lane_id
};
lane_ids.push(Operand::IdRef(lane_id));
}
@@ -313,8 +345,8 @@ impl Emitter {
Ok(true)
}
/// Reinterpret-load a WIDER VECTOR result from a narrower SCALAR pointee by reading the contiguous
/// scalar slots that span the result's bytes and bit-reinterpreting them. The dominant case is an
/// Reinterpret-load a WIDER result from a narrower SCALAR pointee by reading the contiguous scalar
/// slots that span the result's bytes and bit-reinterpreting them. The dominant case is an
/// `OpLoad %v4float` (128 bits) through a `half` element pointer into a `device half*` runtime array
/// (an MPS half-buffer read as a float vector): 8 contiguous halfs are the 4 floats' bytes. For each
/// result lane this packs `slots_per_elem = result_elem_bits / pointee_bits` consecutive pointee
@@ -323,6 +355,12 @@ impl Emitter {
/// it to the result vector. Packing into a `uint` vector (never an N-wide pointee vector) keeps the
/// component count in {2,3,4} — no `Vector16` capability is needed.
///
/// A SCALAR result is the one-lane case of the same assembly and takes the same path: the single
/// accumulator is the result, with no `OpCompositeConstruct` around it. It is reached where a byte
/// pointer cannot be re-typed and `emit_scalar_load_from_byte_pointer` has already declined —
/// notably on a Private byte view, where per-byte `OpPtrAccessChain` is illegal but a
/// gep-provenance sibling pointer is not.
///
/// Byte-EXACT on a little-endian target (the assembled bits are the bytes the load reads at the
/// chain address). Byte-SAFE by construction: only fires when the gep provenance strides a
/// contiguous element (a single leading pointer-stride index, or a multi-index chain whose last
@@ -330,7 +368,7 @@ impl Emitter {
/// differently-typed member). Floor-SAFE by construction: only REACHED on a width mismatch a valid
/// module never has, and returns false unless the provenance proves contiguity, so a banked module
/// is provably untouched.
pub(in crate::native::emitter) fn emit_scalar_to_wider_vector_load(
pub(in crate::native::emitter) fn emit_scalar_slots_to_wider_load(
&mut self,
result: Word,
pointee: &LlType,
@@ -342,24 +380,27 @@ impl Emitter {
if matches!(pointee, LlType::Vector(..)) {
return Ok(false);
}
let LlType::Vector(result_elem, lanes) = result_ty else {
return Ok(false);
let (result_elem, lanes) = match result_ty {
LlType::Vector(elem, lanes) => (self.resolve_type(elem)?, *lanes),
LlType::Float | LlType::Half | LlType::BFloat | LlType::Int(_) => {
(result_ty.clone(), 1)
}
_ => return Ok(false),
};
let result_elem = self.resolve_type(result_elem)?;
let (Some(pointee_bits), Some(result_elem_bits)) =
(bitcast_width(pointee), bitcast_width(&result_elem))
else {
return Ok(false);
};
if pointee_bits == 0
|| *lanes == 0
|| lanes == 0
|| result_elem_bits <= pointee_bits
|| result_elem_bits % pointee_bits != 0
{
return Ok(false);
}
let slots_per_elem = result_elem_bits / pointee_bits;
let total_slots = slots_per_elem * *lanes;
let total_slots = slots_per_elem * lanes;
// Byte-safety gate: the sibling slots must be a contiguous array/vector stride, and the
// provenance must be able to form per-slot sibling pointers.
if !self.gep_provenance_strides_contiguous(ptr_value, pointee)?
@@ -410,8 +451,8 @@ impl Emitter {
}
// Pack `slots_per_elem` consecutive slots, little-endian, into each result element's uint.
let mut elem_uints = Vec::with_capacity(*lanes as usize);
for lane in 0..*lanes {
let mut elem_uints = Vec::with_capacity(lanes as usize);
for lane in 0..lanes {
let mut acc: Option<Word> = None;
for j in 0..slots_per_elem {
let slot_uint = slot_uints[(lane * slots_per_elem + j) as usize];
@@ -462,24 +503,50 @@ impl Emitter {
})?));
}
// Build the uint vector, then bitcast to the result vector type if it isn't already uint.
let uint_vec_ty = LlType::Vector(Box::new(elem_uint.clone()), *lanes);
// Assemble the accumulators into the result: a vector result composes its lanes first, a
// scalar result IS its single accumulator. Either way a bitcast follows unless the result is
// already the unsigned integer the lanes were packed into.
let bitcast_needed = !types_compatible(&result_elem, &elem_uint);
let uint_vec_type = self.type_id(&uint_vec_ty)?;
let uint_vec = if bitcast_needed { self.fresh() } else { result };
instructions.push(Self::inst(
Op::CompositeConstruct,
Some(uint_vec_type),
Some(uint_vec),
elem_uints,
));
let packed = match result_ty {
LlType::Vector(..) => {
let uint_vec_type =
self.type_id(&LlType::Vector(Box::new(elem_uint.clone()), lanes))?;
let uint_vec = if bitcast_needed { self.fresh() } else { result };
instructions.push(Self::inst(
Op::CompositeConstruct,
Some(uint_vec_type),
Some(uint_vec),
elem_uints,
));
uint_vec
}
_ => {
let Operand::IdRef(acc) = elem_uints[0] else {
return Ok(false);
};
if bitcast_needed {
acc
} else {
// The accumulator already has the result type, but `result` still needs a
// defining instruction.
let result_type = self.type_id(result_ty)?;
instructions.push(Self::inst(
Op::CopyObject,
Some(result_type),
Some(result),
vec![Operand::IdRef(acc)],
));
result
}
}
};
if bitcast_needed {
let result_type = self.type_id(result_ty)?;
instructions.push(Self::inst(
Op::Bitcast,
Some(result_type),
Some(result),
vec![Operand::IdRef(uint_vec)],
vec![Operand::IdRef(packed)],
));
}
Ok(true)
+253 -68
View File
@@ -16,15 +16,35 @@ impl Emitter {
else {
return Ok(false);
};
if vector_len != array_len || !types_compatible(vector_elem, array_elem) {
if vector_len != array_len {
return Ok(false);
}
let elements_are_compatible = types_compatible(vector_elem, array_elem);
if !elements_are_compatible {
// Same lane count, different scalar interpretation: reinterpret each lane, exactly as
// `emit_scalar_array_as_vector_load` does in the other direction. Only an equal-width
// scalar pair qualifies -- a lane bitcast is a pure bit reinterpret, so the stored bytes
// are the object's own.
if !is_scalar_storage_type(vector_elem) || !is_scalar_storage_type(array_elem) {
return Ok(false);
}
let (Some(vector_elem_bits), Some(array_elem_bits)) =
(bitcast_width(vector_elem), bitcast_width(array_elem))
else {
return Ok(false);
};
if vector_elem_bits != array_elem_bits {
return Ok(false);
}
}
// LLVM permits a vector store through an opaque pointer whose allocation is an equivalent
// fixed scalar array. Rebuild the array value lane-for-lane so the SPIR-V store's object
// type exactly matches its pointer pointee.
let object_id = self.value_id_in(&object.value, &object.ty, instructions)?;
let elem_type = self.type_id(vector_elem)?;
let array_elem_type = self.type_id(array_elem)?;
let elements_need_bitcast = !elements_are_compatible && elem_type != array_elem_type;
let mut elements = Vec::with_capacity(*vector_len as usize);
for lane in 0..*vector_len {
let value = self.fresh();
@@ -34,6 +54,18 @@ impl Emitter {
Some(value),
vec![Operand::IdRef(object_id), Operand::LiteralBit32(lane)],
));
let value = if elements_need_bitcast {
let reinterpreted = self.fresh();
instructions.push(Self::inst(
Op::Bitcast,
Some(array_elem_type),
Some(reinterpreted),
vec![Operand::IdRef(value)],
));
reinterpreted
} else {
value
};
elements.push(Operand::IdRef(value));
}
let array_type = self.type_id(pointee)?;
@@ -463,7 +495,22 @@ impl Emitter {
Ok(true)
}
pub(in crate::native::emitter) fn emit_same_width_scalar_store(
/// Reinterpret an `OpStore` whose object and declared pointee are INCOMPATIBLE but equal in total
/// bit width: `OpBitcast` the object to the pointee type and store. Byte-identical on any target
/// (an equal-width bitcast is a pure bit reinterpret), and shape-agnostic — scalar→scalar,
/// scalar→vector, vector→vector and vector→scalar all take the same two instructions, because
/// `bitcast_width` multiplies a vector through and both types arrive resolved.
///
/// Shape-agnostic ON PURPOSE: this is the exact mirror of the equal-width reinterpret LOAD in
/// `emit_load_resolved`, which accepts ANY pointee/result pair of equal bit width and emits
/// `OpLoad` of the pointee plus `OpBitcast` to the result. A store arm that took only some of
/// those shapes would refuse to write back what the load arm happily read: `*(device ushort2*)&buf[i]`
/// reads as `load <2 x i16>` from a `uint` pointee, but `store <2 x i16>` into it used to fall
/// through to a plain `OpStore` and fail the owned-module pointee/value contract.
///
/// Floor-safe by construction: only fires when the types are INCOMPATIBLE but equal in width — a
/// valid module's stores match their pointee, so it never reaches here.
pub(in crate::native::emitter) fn emit_same_width_reinterpret_store(
&mut self,
object: &TypedValue,
ptr: &TypedValue,
@@ -471,19 +518,16 @@ impl Emitter {
pointee: &LlType,
instructions: &mut Vec<Instruction>,
) -> Result<bool, String> {
if matches!(object_ty, LlType::Vector(_, _)) {
return Ok(false);
}
let (Some(object_bits), Some(pointee_bits)) =
(bitcast_width(object_ty), bitcast_width(pointee))
else {
return Ok(false);
};
if object_bits != pointee_bits {
if object_bits == 0 || object_bits != pointee_bits {
return Ok(false);
}
let ptr_id = self.value_id(&ptr.value, &ptr.ty)?;
let ptr_id = self.value_id_in(&ptr.value, &ptr.ty, instructions)?;
let object_id = self.value_id_in(&object.value, &object.ty, instructions)?;
let pointee_ty = self.type_id(pointee)?;
let stored = self.fresh();
@@ -535,7 +579,7 @@ impl Emitter {
return Ok(false);
};
// Strict narrowing only: a wider object would write past the slot (a sibling the access-chain
// rewrite owns); same-width is `emit_same_width_scalar_store` above.
// rewrite owns); same-width is `emit_same_width_reinterpret_store` above.
if object_bits == 0 || pointee_bits == 0 || object_bits >= pointee_bits {
return Ok(false);
}
@@ -646,6 +690,160 @@ impl Emitter {
Ok(true)
}
/// An MSL `union` lowers to a ONE-MEMBER LLVM struct -- `union { ulong u; float f; }` is
/// `%union.Slot = type { i64 }` -- so `s.f = x` arrives as a store whose object is a narrower,
/// differently typed scalar and whose declared pointee is that struct. Every width-based rule
/// above declines (`bitcast_width` has no answer for a struct) and the store falls through to a
/// plain `OpStore` that fails the owned pointee/value contract.
///
/// Every union member starts at byte offset 0, and a `Function`/`Private` struct carries no
/// explicit `Offset` decoration, so member 0 of a SINGLE-member struct is the slot's own address.
/// Descend to it and re-enter the store handler on the leaf: the whole chain above -- scalar
/// narrowing, same-width reinterpret, the vector rules -- then applies unchanged, so one descent
/// covers every member type a union can name rather than one rule's worth.
///
/// Runs LAST, after every aggregate rule has declined, so no module that already stores through a
/// one-member struct by some other route changes. Floor-safe: the only alternative at this point
/// is the mismatched plain `OpStore` the contract already refuses.
/// The mismatched-store chain: thirteen rules, each one way a `store` whose object type does not
/// match its pointer's declared pointee is still a byte-faithful write of the object's own bytes.
/// Order is load-bearing -- every rule sees only what the rules above it declined -- and so is the
/// precondition, which is the CHAIN's and not any rule's: neither `pointee` nor `object_ty`
/// changes as the chain runs, so the thirteen copies of `!types_compatible(&pointee, &object_ty)`
/// the dispatch used to spell out were one test asked thirteen times. A rule that returns
/// `Ok(false)` has emitted nothing -- the ones that speculate wrap themselves in `staged_emit` --
/// so declining is free.
///
/// `Ok(false)` means no rule claimed the store and the caller falls through to a plain `OpStore`,
/// which the owned pointee/value contract then refuses, so the module retries at a lower tier
/// rather than silently writing the wrong bytes.
pub(in crate::native::emitter) fn emit_mismatched_store(
&mut self,
object: &TypedValue,
ptr: &TypedValue,
object_ty: &LlType,
pointee: &LlType,
align: Option<u64>,
instructions: &mut Vec<Instruction>,
) -> Result<bool, String> {
if types_compatible(pointee, object_ty) {
return Ok(false);
}
Ok(
self.emit_i64_to_i32_pair_struct_store(object, ptr, pointee, instructions)?
|| self.emit_aggregate_prefix_integer_reinterpret_store(
object,
ptr,
object_ty,
pointee,
instructions,
)?
|| self.emit_first_vector_aggregate_reinterpret_store(
object,
ptr,
object_ty,
pointee,
instructions,
)?
|| self.emit_first_scalar_aggregate_reinterpret_store(
object,
ptr,
object_ty,
pointee,
instructions,
)?
|| self.emit_zero_scalar_to_aggregate_store(
object,
ptr,
object_ty,
pointee,
instructions,
)?
|| self.emit_vector_as_scalar_array_store(object, ptr, pointee, instructions)?
|| self.emit_vector_to_scalar_stores(object, ptr, pointee, instructions)?
|| self.emit_workgroup_vector_chunk_stores(
object,
ptr,
object_ty,
pointee,
instructions,
)?
|| self.emit_widening_vector_store(object, ptr, pointee, instructions)?
|| self.emit_narrowing_vector_store(object, ptr, pointee, instructions)?
|| self.emit_same_width_reinterpret_store(
object,
ptr,
object_ty,
pointee,
instructions,
)?
|| self.emit_scalar_narrowing_store(
object,
ptr,
object_ty,
pointee,
instructions,
)?
|| self.emit_single_member_struct_store(
object,
ptr,
pointee,
align,
instructions,
)?,
)
}
pub(in crate::native::emitter) fn emit_single_member_struct_store(
&mut self,
object: &TypedValue,
ptr: &TypedValue,
pointee: &LlType,
align: Option<u64>,
instructions: &mut Vec<Instruction>,
) -> Result<bool, String> {
let LlType::Struct(fields) = pointee else {
return Ok(false);
};
let [field] = fields.as_slice() else {
return Ok(false);
};
let leaf_pointee = self.resolve_type(field)?;
let storage = match self.resolve_type(&ptr.ty)? {
LlType::Ptr(addrspace) => self.pointer_storage_for(&ptr.value, addrspace)?,
_ => return Ok(false),
};
let ptr_id = self.value_id_in(&ptr.value, &ptr.ty, instructions)?;
let leaf_ptr_type = self.ptr_type_id(storage, &leaf_pointee)?;
let index = self.const_uint(0)?;
let leaf = self.fresh();
instructions.push(Self::inst(
Op::InBoundsAccessChain,
Some(leaf_ptr_type),
Some(leaf),
vec![Operand::IdRef(ptr_id), Operand::IdRef(index)],
));
// Name the leaf so the re-entered handler can resolve it like any other local pointer. The
// name is minted from the leaf's own id, so it is unique within the function and nothing else
// ever refers to it -- the access chain dominates its single use, the store two lines below.
let name = format!("metal2vulkan.union.member.{leaf}");
self.values.insert(name.clone(), (leaf, ptr.ty.clone()));
self.pointer_pointees.insert(name.clone(), leaf_pointee);
self.pointer_storage.insert(name.clone(), storage);
self.emit_store_resolved(
object.clone(),
TypedValue {
ty: ptr.ty.clone(),
value: LlValue::Local(name),
},
align,
instructions,
)?;
Ok(true)
}
pub(in crate::native::emitter) fn emit_zero_scalar_to_aggregate_store(
&mut self,
object: &TypedValue,
@@ -754,51 +952,6 @@ impl Emitter {
Ok(true)
}
/// Reinterpret a vector `OpStore` whose object is a SAME-TOTAL-WIDTH vector of a different type than
/// the declared pointee (e.g. `store <2 x float>` through a `<4 x half>` pointer — 8 bytes either
/// way): `OpBitcast` the object to the pointee vector and store. Byte-identical on any target (an
/// equal-size vector bitcast is a pure bit reinterpret). Floor-safe by construction: only fires on a
/// vector→vector store whose types are INCOMPATIBLE but equal in total width — a valid module's
/// stores match their pointee, so it never reaches here.
pub(in crate::native::emitter) fn emit_same_width_vector_reinterpret_store(
&mut self,
object: &TypedValue,
ptr: &TypedValue,
object_ty: &LlType,
pointee: &LlType,
instructions: &mut Vec<Instruction>,
) -> Result<bool, String> {
if !matches!(object_ty, LlType::Vector(..)) || !matches!(pointee, LlType::Vector(..)) {
return Ok(false);
}
let (Some(ow), Some(pw)) = (
self.vector_total_bits(object_ty),
self.vector_total_bits(pointee),
) else {
return Ok(false);
};
if ow == 0 || ow != pw {
return Ok(false);
}
let object_id = self.value_id_in(&object.value, &object.ty, instructions)?;
let ptr_id = self.value_id_in(&ptr.value, &ptr.ty, instructions)?;
let pointee_ty = self.type_id(pointee)?;
let cast = self.fresh();
instructions.push(Self::inst(
Op::Bitcast,
Some(pointee_ty),
Some(cast),
vec![Operand::IdRef(object_id)],
));
instructions.push(Self::inst(
Op::Store,
None,
None,
vec![Operand::IdRef(ptr_id), Operand::IdRef(cast)],
));
Ok(true)
}
/// Total bit width of a vector type (`elem_bits * lanes`), or `None` if `ty` is not a vector of a
/// bitcastable scalar. Used to decide whether two distinct vector types are a byte-identical
/// `OpBitcast` reinterpret (equal total width).
@@ -891,6 +1044,31 @@ impl Emitter {
})
}
/// `OpInBoundsAccessChain` down a constant member path to one field of an aggregate the emitter
/// holds a pointer to.
fn emit_aggregate_field_pointer(
&mut self,
storage: StorageClass,
field_ty: &LlType,
ptr: Word,
access_path: &[u32],
instructions: &mut Vec<Instruction>,
) -> Result<Word, String> {
let field_ptr_ty = self.ptr_type_id(storage, field_ty)?;
let field_ptr = self.fresh();
let mut ops = vec![Operand::IdRef(ptr)];
for idx in access_path {
ops.push(Operand::IdRef(self.const_uint(*idx)?));
}
instructions.push(Self::inst(
Op::InBoundsAccessChain,
Some(field_ptr_ty),
Some(field_ptr),
ops,
));
Ok(field_ptr)
}
pub(in crate::native::emitter) fn emit_first_pointer_aggregate_reinterpret_load(
&mut self,
result_name: &str,
@@ -919,6 +1097,24 @@ impl Emitter {
))
}
};
// The zero-offset member spelled as `bitcast ptr %p to ptr` rather than as a GEP arrives
// here with the AGGREGATE as its pointee, so it never reached the device-address branch in
// `emit_pointer_from_local_field_load` -- that branch keys off a field pointee. Descend to
// the field first and ask the same question, or a device address read through the bitcast
// spelling becomes a Private placeholder that no later pass can repair: the store recorded
// its source as a 64-bit address, and forwarding an integer into a pointer load is exactly
// what `recover_inlined_local_pointer_fields` declines to do.
if self.bda_forwards_local_pointer_field(result_name, result_ty) {
let field_ptr = self.emit_aggregate_field_pointer(
storage,
&LlType::Int(64),
ptr,
&access_path,
instructions,
)?;
self.emit_bda_address_from_field(result_name, field_ptr, instructions)?;
return Ok(true);
}
let key = LocalPointerField {
root: ptr,
indices: access_path.clone(),
@@ -936,18 +1132,8 @@ impl Emitter {
)?;
return Ok(true);
}
let field_ptr_ty = self.ptr_type_id(storage, &field_ty)?;
let field_ptr = self.fresh();
let mut ops = vec![Operand::IdRef(ptr)];
for idx in access_path {
ops.push(Operand::IdRef(self.const_uint(idx)?));
}
instructions.push(Self::inst(
Op::InBoundsAccessChain,
Some(field_ptr_ty),
Some(field_ptr),
ops,
));
let field_ptr =
self.emit_aggregate_field_pointer(storage, &field_ty, ptr, &access_path, instructions)?;
let result_type = self.type_id(result_ty)?;
instructions.push(Self::inst(
@@ -988,9 +1174,8 @@ impl Emitter {
let bitcast = !direct
&& matches!(
(&vector_ty, result_ty),
(LlType::Vector(_, n), LlType::Vector(_, m))
if n == m
&& bitcast_width(&vector_ty).is_some()
(LlType::Vector(..), LlType::Vector(..))
if bitcast_width(&vector_ty).is_some()
&& bitcast_width(&vector_ty) == bitcast_width(result_ty)
);
if !direct && !bitcast {
+12 -3
View File
@@ -696,9 +696,18 @@ impl Emitter {
// <4 x i16> array) each rewrite the other's word from their stale copy, losing writes that
// Metal's 4-byte store keeps. Emit two 16-bit component stores through component access
// chains instead wherever the storage class allows a 16-bit pointer without extra
// capabilities (Workgroup/Function/Private). StorageBuffer keeps the vector RMW: a 16-bit
// StorageBuffer pointer needs StorageBuffer16BitAccess, which the executors do not enable;
// the same inter-thread race is still possible there and needs that capability to fix.
// capabilities (Workgroup/Function/Private). StorageBuffer keeps the vector RMW, and the
// same inter-thread race is possible there in principle.
//
// The reason that used to be given for the StorageBuffer arm -- "a 16-bit StorageBuffer
// pointer needs StorageBuffer16BitAccess, which the executors do not enable" -- is FALSE:
// `validation/src/candidate.rs` enables `storage_buffer16_bit_access` and its 8-bit and
// uniform-and-storage siblings whenever the device reports them, and 276 corpus modules
// already use a narrow StorageBuffer pointer with no capability declared, spirv-val
// accepting and MoltenVK running them. What actually justifies leaving the arm alone is
// that it is DEAD: an `eprintln` on this branch, swept over all 14579 sources, fires on
// ZERO of them. Every vector word store the corpus reaches is Workgroup/Function/Private
// and takes the component-store path above. Measure it again before rewriting it.
if matches!(
pointer.storage,
StorageClass::Workgroup | StorageClass::Function | StorageClass::Private
+19 -365
View File
@@ -3,14 +3,6 @@ use crate::native::cfg::BodyBlock;
use crate::native::tir::{TirFunction, TirOpcode, TirOperand, TirTerminator};
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum FastSumLeaf {
Addend,
Positive,
Negative,
Difference,
}
fn ordinary_cfg_shape_key(blocks: &[BodyBlock]) -> String {
// `structured_plan` rejection is a control-flow property. Keep value opcodes out of this key so
// type-specialized helper bodies with the same block graph share the rejection fact; each body
@@ -53,47 +45,6 @@ fn ordinary_cfg_shape_key(blocks: &[BodyBlock]) -> String {
key
}
fn sixteen_leaf_cancellation_order(shape: &[FastSumLeaf]) -> Option<&'static [usize; 16]> {
use FastSumLeaf::{Addend as A, Difference as D, Negative as N, Positive as P};
match shape {
[P, P, A, P, N, N, N, N, N, D, N, D, P, D, D, A] => {
Some(&[13, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 0, 14, 15])
}
[A, P, P, N, N, N, N, D, N, D, N, D, P, D, P, D] => {
Some(&[12, 1, 2, 3, 0, 5, 6, 7, 8, 9, 10, 11, 4, 13, 14, 15])
}
[P, P, A, N, N, N, P, P, N, D, N, D, N, D, D, A] => {
Some(&[0, 15, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 1])
}
[A, P, N, N, N, P, P, D, N, D, N, D, N, D, P, D] => {
Some(&[0, 12, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 1, 13, 14, 15])
}
[P, N, A, N, P, P, N, N, P, D, P, D, N, D, D, A] => {
Some(&[3, 15, 2, 0, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 1])
}
[A, N, N, P, P, N, N, D, P, D, P, D, N, D, N, D] => {
Some(&[14, 1, 2, 0, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 3, 15])
}
[P, N, A, N, P, N, P, P, N, D, P, D, N, D, D, A] => {
Some(&[3, 1, 2, 0, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])
}
[A, N, N, P, N, P, P, D, N, D, P, D, N, D, N, D] => {
Some(&[1, 0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])
}
[A, N, N, P, N, P, P, N, D, P, D, N, D, N, D, D] => {
Some(&[1, 0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])
}
[P, N, A, P, N, P, N, N, P, D, N, D, P, D, D, A] => {
Some(&[0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 1])
}
[A, N, P, N, P, N, N, D, P, D, N, D, P, D, N, D] => {
Some(&[0, 12, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 1, 13, 14, 15])
}
_ => None,
}
}
fn bda_forward_address_values(
tir: &TirFunction,
seeds: &HashSet<String>,
@@ -407,9 +358,6 @@ impl Emitter {
pub(super) fn emit_function(&mut self, f: &LlFunction) -> Result<(), String> {
self.values.clear();
self.fast_float_products.clear();
self.fast_grouped_sums.clear();
self.fast_partitioned_sums.clear();
self.fast_grouped_sum_boundaries.clear();
self.fast_contract_adds.clear();
self.fast_uncontracted_sums.clear();
self.construct_tree_active = false;
@@ -478,6 +426,7 @@ impl Emitter {
self.param_values.clear();
self.inline_parameter_substitutions.clear();
self.raw_offsets.clear();
self.symbolic_buffer_addresses.clear();
self.int_alignments.clear();
self.unmodeled_pointers.clear();
for global in &self.ir.globals.clone() {
@@ -673,7 +622,7 @@ impl Emitter {
&& self
.concrete_vector_workgroup_raw_param_pointee(&f.name, param_index, name)
.is_some();
if self.raw_buffer_params.contains(name) {
if self.is_raw_buffer_param(name) {
let pointee = if addrspace == 3 {
self.concrete_vector_workgroup_raw_param_pointee(&f.name, param_index, name)
.unwrap_or_else(raw_workgroup_array_type)
@@ -695,7 +644,7 @@ impl Emitter {
{
self.pointer_pointees.insert(name.clone(), pointee);
}
if self.raw_buffer_params.contains(name) && !concrete_workgroup_raw_param {
if self.is_raw_buffer_param(name) && !concrete_workgroup_raw_param {
let mut raw = self
.raw_call_param_offsets
.get(&(f.name.clone(), name.clone()))
@@ -1079,10 +1028,21 @@ impl Emitter {
// local: it exists only to preserve typed instructions and source edges until that
// selected constructor runs, so cloning/refunneling it here would duplicate the
// over-budget ownership work without changing the chosen representation.
self.branch_merges_by_header = infer_bounded_branch_merges_by_header(&body_blocks);
self.branch_merges.clear();
self.loop_merges.clear();
self.switch_merges = infer_direct_switch_merges(&body_blocks);
if body_blocks.len() > crate::native::cfg::CROSS_ARM_EDGE_MAX_BLOCKS {
self.branch_merges_by_header =
infer_bounded_branch_merges_by_header(&body_blocks);
self.branch_merges.clear();
self.loop_merges.clear();
} else if crate::native::cfg::loop_forest_is_empty(&body_blocks) {
self.branch_merges = infer_branch_merges(&body_blocks);
self.loop_merges.clear();
} else {
self.branch_merges_by_header =
infer_bounded_branch_merges_by_header(&body_blocks);
self.branch_merges.clear();
self.loop_merges.clear();
}
self.switch_merges = infer_switch_merges_bounded(&body_blocks);
} else if body_blocks.len() > crate::native::cfg::CROSS_ARM_EDGE_MAX_BLOCKS {
// The ordinary and construct-tree planners have both rejected this large CFG. Building
// heuristic branch/loop transitive-closure maps here can exceed the memory budget before
@@ -1120,7 +1080,7 @@ impl Emitter {
infer_bounded_branch_merges_by_header(&body_blocks);
self.branch_merges.clear();
self.loop_merges.clear();
self.switch_merges = infer_direct_switch_merges(&body_blocks);
self.switch_merges = infer_switch_merges_bounded(&body_blocks);
}
} else {
self.branch_merges = infer_branch_merges(&body_blocks);
@@ -1213,312 +1173,6 @@ impl Emitter {
Some((result.clone(), (local(&lhs.value), local(&rhs.value))))
})
.collect::<HashMap<_, _>>();
let fast_add_values = tir
.blocks
.iter()
.flat_map(|block| &block.insts)
.filter(|inst| inst.fast_math() && inst.opcode == "fadd")
.filter_map(|inst| {
let result = inst.result.as_ref()?;
let operands = self.tir_inst_typed_operands(inst)?;
let [lhs, rhs] = operands.as_slice() else {
return None;
};
Some((result.clone(), (lhs.clone(), rhs.clone())))
})
.collect::<HashMap<_, _>>();
let fast_sum_values = tir
.blocks
.iter()
.flat_map(|block| &block.insts)
.filter(|inst| inst.fast_math() && matches!(inst.opcode.as_str(), "fadd" | "fsub"))
.filter_map(|inst| {
let result = inst.result.as_ref()?;
let operands = self.tir_inst_typed_operands(inst)?;
let [lhs, rhs] = operands.as_slice() else {
return None;
};
Some((
result.clone(),
(inst.opcode == "fsub", lhs.clone(), rhs.clone()),
))
})
.collect::<HashMap<_, _>>();
let nested_fast_adds = fast_sum_values
.values()
.flat_map(|(_, lhs, rhs)| [lhs, rhs])
.filter_map(|value| match &value.value {
LlValue::Local(name) if fast_add_values.contains_key(name) => {
Some(name.clone())
}
_ => None,
})
.collect::<HashSet<_>>();
let mut stored_fast_adds = HashSet::new();
for inst in tir
.blocks
.iter()
.flat_map(|block| &block.insts)
.filter(|inst| inst.opcode == "store")
{
inst.visit_uses(|name| {
if fast_add_values.contains_key(name) {
stored_fast_adds.insert(name.to_string());
}
});
}
fn collect_fast_sum_terms(
value: &TypedValue,
negate: bool,
sums: &HashMap<String, (bool, TypedValue, TypedValue)>,
visiting: &mut HashSet<String>,
terms: &mut Vec<(TypedValue, bool)>,
) -> bool {
let LlValue::Local(name) = &value.value else {
terms.push((value.clone(), negate));
return true;
};
let Some((subtract, lhs, rhs)) = sums.get(name) else {
terms.push((value.clone(), negate));
return true;
};
if *subtract {
terms.push((value.clone(), negate));
return true;
}
if !visiting.insert(name.clone()) {
return false;
}
let valid = collect_fast_sum_terms(lhs, negate, sums, visiting, terms)
&& collect_fast_sum_terms(rhs, negate ^ subtract, sums, visiting, terms);
visiting.remove(name);
valid
}
fn literal_is_negative(value: &TypedValue) -> Option<bool> {
match (&value.ty, &value.value) {
(LlType::Float, LlValue::Float(value)) => Some(value.is_sign_negative()),
(LlType::Float, LlValue::Hex(bits)) => Some(bits >> 63 != 0),
(LlType::Half, LlValue::HalfBits(bits)) => Some(bits >> 15 != 0),
(LlType::BFloat, LlValue::BFloatBits(bits)) => Some(bits >> 15 != 0),
(_, LlValue::SignedInt(value)) => Some(*value < 0),
(_, LlValue::Int(_) | LlValue::Zero) => Some(false),
_ => None,
}
}
let leaf_shape = |term: &TypedValue, negate: bool| {
let LlValue::Local(name) = &term.value else {
return Some(FastSumLeaf::Addend);
};
let Some((lhs, rhs)) = fast_products.get(name) else {
return Some(FastSumLeaf::Addend);
};
if [lhs, rhs].into_iter().any(|operand| {
matches!(&operand.value, LlValue::Local(name) if fast_sum_values.get(name).is_some_and(|(subtract, _, _)| *subtract))
}) {
return Some(FastSumLeaf::Difference);
}
let coefficient_negative =
[lhs, rhs].into_iter().find_map(literal_is_negative)? ^ negate;
Some(if coefficient_negative {
FastSumLeaf::Negative
} else {
FastSumLeaf::Positive
})
};
for (root, (lhs, rhs)) in &fast_add_values {
if nested_fast_adds.contains(root) {
continue;
}
let mut terms = Vec::new();
let mut visiting = HashSet::new();
if !collect_fast_sum_terms(lhs, false, &fast_sum_values, &mut visiting, &mut terms)
|| !collect_fast_sum_terms(
rhs,
false,
&fast_sum_values,
&mut visiting,
&mut terms,
)
|| !(5..10).contains(&terms.len())
{
continue;
}
let shape = terms
.iter()
.map(|(term, negate)| leaf_shape(term, *negate))
.collect::<Option<Vec<_>>>();
let stored_source_tree = stored_fast_adds.contains(root)
&& shape.as_deref().is_some_and(|shape| {
shape.len() == 7
&& shape
.iter()
.filter(|leaf| matches!(leaf, FastSumLeaf::Addend))
.count()
== 1
&& shape
.iter()
.filter(|leaf| matches!(leaf, FastSumLeaf::Difference))
.count()
== 2
});
if stored_source_tree {
continue;
}
let mut positive = Vec::new();
let mut negative = Vec::new();
let mut supported = true;
for (term, negate) in terms {
let product = match &term.value {
LlValue::Local(name) => fast_products.get(name),
_ => None,
};
let sign = if let Some((a, b)) = product {
let literals = [a, b]
.into_iter()
.filter_map(literal_is_negative)
.collect::<Vec<_>>();
if literals.len() != 1 {
supported = false;
break;
}
negate ^ literals[0]
} else {
negate
};
if sign {
negative.push((term, negate));
} else {
positive.push((term, negate));
}
}
let mut moved_accumulator = false;
if let Some(position) = positive.iter().position(|(term, _)| match &term.value {
LlValue::Local(name) => {
!fast_products.contains_key(name) && !fast_sum_values.contains_key(name)
}
_ => true,
}) {
if position > 1 {
let accumulator = positive.remove(position);
positive.insert(1, accumulator);
moved_accumulator = true;
}
}
if supported && positive.len() >= 2 && negative.len() >= 2 {
for (term, _) in positive.iter().chain(&negative) {
let LlValue::Local(name) = &term.value else {
continue;
};
if fast_sum_values
.get(name)
.is_some_and(|(subtract, _, _)| *subtract)
{
self.fast_grouped_sum_boundaries.insert(name.clone());
}
}
self.fast_grouped_sums
.insert(root.clone(), (positive, negative, moved_accumulator));
}
}
for (root, (lhs, rhs)) in &fast_add_values {
if nested_fast_adds.contains(root) {
continue;
}
let mut terms = Vec::new();
let mut visiting = HashSet::new();
if !collect_fast_sum_terms(lhs, false, &fast_sum_values, &mut visiting, &mut terms)
|| !collect_fast_sum_terms(
rhs,
false,
&fast_sum_values,
&mut visiting,
&mut terms,
)
|| !matches!(terms.len(), 10 | 16)
{
continue;
}
if terms.len() == 16 {
let Some(shape) = terms
.iter()
.map(|(term, negate)| leaf_shape(term, *negate))
.collect::<Option<Vec<_>>>()
else {
continue;
};
let Some(order) = sixteen_leaf_cancellation_order(&shape) else {
continue;
};
let ordered = order
.iter()
.map(|index| terms[*index].0.clone())
.collect::<Vec<_>>();
self.fast_partitioned_sums
.insert(root.clone(), vec![ordered]);
continue;
}
let signs = terms
.iter()
.map(|(term, negate)| {
let LlValue::Local(name) = &term.value else {
return None;
};
let (lhs, rhs) = fast_products.get(name)?;
[lhs, rhs]
.into_iter()
.find_map(literal_is_negative)
.map(|negative| negative ^ negate)
})
.collect::<Vec<_>>();
let difference_products = terms
.iter()
.map(|(term, _)| {
let LlValue::Local(name) = &term.value else {
return false;
};
fast_products.get(name).is_some_and(|(lhs, rhs)| {
[lhs, rhs].into_iter().any(|operand| {
matches!(&operand.value, LlValue::Local(name) if fast_sum_values.get(name).is_some_and(|(subtract, _, _)| *subtract))
})
})
})
.collect::<Vec<_>>();
let accumulator_real_tree = difference_products.as_slice()
== [
false, false, false, false, false, false, true, false, true, true,
];
// Preserve the partitions selected by each typed cancellation topology. These
// predicates use only leaf operation kind and coefficient sign: direct products,
// products of source differences, and product differences retain distinct rounding
// boundaries independently of symbols and exact coefficient values.
let partitions: &[usize] = match signs.as_slice() {
[Some(false), Some(false), _, Some(true), ..] => &[2, 6],
[Some(false), Some(true), _, Some(true), ..] => &[1, 4],
[None, Some(true), Some(true), Some(false), ..] if accumulator_real_tree => {
&[2]
}
[None, Some(false), Some(true), Some(true), ..] if accumulator_real_tree => {
&[3]
}
_ => continue,
};
let mut groups = Vec::with_capacity(partitions.len() + 1);
let mut start = 0;
for end in partitions
.iter()
.copied()
.chain(std::iter::once(terms.len()))
{
groups.push(
terms[start..end]
.iter()
.map(|(term, _)| term.clone())
.collect(),
);
start = end;
}
self.fast_partitioned_sums.insert(root.clone(), groups);
}
const EXPLICIT_FMA_CHAIN_MIN_TERMS: usize = 10;
for result in fast_add_operands.keys() {
let mut chain = Vec::new();
+5
View File
@@ -353,6 +353,11 @@ pub(super) fn raw_buffer_block_type() -> LlType {
LlType::Struct(vec![LlType::Array(Box::new(LlType::Int(32)), 0)])
}
/// The word array a `[[threadgroup]]` parameter gets when its accesses reinterpret between element
/// types, so no AIR layout describes it. AIR carries no length -- Metal binds one at encode time --
/// so 2048 words is a guess, and `passes::stage_input` replaces it with `length / 4` words when the
/// caller named a byte length for that Metal index. Keep the element `Int(32)`: the body's access
/// chains are typed against it and only the bound is the caller's to move.
pub(super) fn raw_workgroup_array_type() -> LlType {
LlType::Array(Box::new(LlType::Int(32)), 2048)
}
+17 -4
View File
@@ -4,8 +4,8 @@
//! `Emitter` (module context / `resolve_type`) rather than an `LlModule`:
//!
//! - `Emitter::raw_type_size_align` → the "Raw" `LayoutRule` (LLVM vector allocation size and
//! source ABI alignment, arrays floor align at 4; a `Result` that ERRORS — not `None` — on
//! odd-width ints / `Void`).
//! source ABI alignment, arrays taking their element's alignment; a `Result` that ERRORS — not
//! `None` — on odd-width ints / `Void`).
//! - `bitcast_width` / `Emitter::vector_total_bits` → the bit-width helpers used to decide when
//! two types are a byte-identical `OpBitcast` reinterpret. These are NOT size/align calculators
//! (they return bit counts, not `(size, align)`), so they are pinned here but are not folded
@@ -29,7 +29,7 @@ fn vec(elem: LlType, lanes: u32) -> LlType {
}
#[test]
fn raw_rule_pads_vec3_and_floors_array_align() {
fn raw_rule_pads_vec3_and_keeps_element_array_align() {
// "Raw" (`raw_type_size_align`): same padded shape as the Memcpy rule (vec3 = 16/16), a
// `Result` return, and explicit standard-width int buckets.
let e = emitter();
@@ -48,8 +48,10 @@ fn raw_rule_pads_vec3_and_floors_array_align() {
assert_eq!(raw(&vec(LlType::Float, 2)), (8, 8));
assert_eq!(raw(&vec(LlType::Float, 3)), (16, 16));
assert_eq!(raw(&vec(LlType::Float, 4)), (16, 16));
// array of scalars floors align at 4; array of vec3 strides at the padded 16
// an array takes its ELEMENT's alignment: a byte array stays byte-aligned, and array of vec3
// strides at the padded 16
assert_eq!(raw(&LlType::Array(Box::new(LlType::Float), 3)), (12, 4));
assert_eq!(raw(&LlType::Array(Box::new(LlType::Int(8)), 11)), (11, 1));
assert_eq!(
raw(&LlType::Array(Box::new(vec(LlType::Float, 3)), 2)),
(32, 16)
@@ -59,6 +61,17 @@ fn raw_rule_pads_vec3_and_floors_array_align() {
raw(&LlType::Struct(vec![LlType::Int(8), LlType::Float])),
(8, 4)
);
// Metal's packed spelling: `<{ i8, [3 x i8], i32 }>` writes its padding out as a byte array, so
// the i32 behind it lands at 4. A four-byte floor on the pad would push it to 8 and grow the
// struct to 12.
assert_eq!(
raw(&LlType::Struct(vec![
LlType::Int(8),
LlType::Array(Box::new(LlType::Int(8)), 3),
LlType::Int(32),
])),
(8, 4)
);
}
#[test]
+105
View File
@@ -168,6 +168,111 @@ impl Emitter {
Ok(())
}
/// The buffer-relative byte offset an integer `ptrtoint` of `name` stands for, if `name` is a
/// pointer whose addressing this emitter knows.
///
/// A pointer already carrying a raw offset contributes that offset; any other modelled pointer
/// is its own root at offset zero. A pointer rooted at a runtime DEVICE address is excluded --
/// that address is a real value the physical model already materializes, and folding it into a
/// buffer-relative offset would claim the wrong base.
pub(in crate::native::emitter) fn symbolic_buffer_address_for_pointer(
&self,
name: &str,
) -> Option<RawBufferOffset> {
if let Some(raw) = self.raw_offsets.get(name) {
return (raw.device_addr_base.is_none() && !raw.unmodelable).then(|| raw.clone());
}
if self.unmodeled_pointers.contains(name) {
return None;
}
let storage = self.pointer_storage.get(name).copied()?;
if matches!(
storage,
StorageClass::Private | StorageClass::PhysicalStorageBuffer
) {
return None;
}
let ty = self
.values
.get(name)
.or_else(|| self.global_values.get(name))
.map(|(_, ty)| ty.clone())?;
let LlType::Ptr(addrspace) = self.resolve_type(&ty).ok()? else {
return None;
};
Some(RawBufferOffset::root(name.to_string(), addrspace))
}
/// Whether `name` is a buffer parameter this function addresses as raw words -- including one
/// the CFG structurizer CLONED.
///
/// `raw_buffer_params` is keyed by name and is derived before the CFG is structured, so a value
/// that tail duplication renamed (`cfg::clone_crossarm::fresh`) is absent from it. When the
/// renamed value is an inlined helper's buffer parameter, that absence drops its byte cursor
/// and every load through it folds to `OpConstantNull`. Follow the rename back instead; clones
/// nest, so the walk repeats.
pub(in crate::native::emitter) fn is_raw_buffer_param(&self, name: &str) -> bool {
let mut name = name.to_string();
loop {
if self.raw_buffer_params.contains(&name) {
return true;
}
match crate::native::cfg::clone_crossarm::clone_source_name(&name) {
Some(source) => name = source,
None => return false,
}
}
}
/// Whether a raw root may be indexed in WORDS.
///
/// The raw word path emits `AccessChain(root, 0, word_index)` typed `ptr uint`, which is well
/// typed only against a root declared with [`raw_buffer_block_type`] -- and that declaration
/// needs a pointee to derive from. A root whose pointee this emitter never learned is declared
/// as a bare `uchar` pointer instead, its descriptor block becomes a BYTE array, and
/// `passes::resources::rewrites::plan_raw_word_pointer_rewrite` then reads the same chain's
/// index as a byte index and divides it by four a second time. The two units cannot be told
/// apart after the fact, so the word chain must not be emitted at all.
pub(in crate::native::emitter) fn root_is_word_addressable(&self, root: &str) -> bool {
self.pointer_pointees
.get(root)
.is_some_and(|pointee| !matches!(self.resolve_type(pointee), Ok(LlType::Int(8))))
}
/// Carry a symbolic buffer address across `add`: exactly one side must be the address, and the
/// other is the byte offset -- a constant folds into `const_off`, anything else becomes a
/// dynamic term of stride one. Two symbolic sides are the sum of two addresses, which names no
/// byte in either buffer, so nothing is recorded.
pub(in crate::native::emitter) fn extend_symbolic_buffer_address(
&mut self,
name: &str,
lhs: &TypedValue,
rhs: &TypedValue,
) {
let symbolic = |value: &LlValue| match value {
LlValue::Local(local) => self.symbolic_buffer_addresses.get(local).cloned(),
_ => None,
};
let (mut base, offset) = match (symbolic(&lhs.value), symbolic(&rhs.value)) {
(Some(base), None) => (base, rhs.clone()),
(None, Some(base)) => (base, lhs.clone()),
_ => return,
};
match offset.value {
LlValue::Int(value) | LlValue::Hex(value) => {
let Ok(value) = i64::try_from(value) else {
return;
};
base.const_off += value;
}
LlValue::SignedInt(value) => base.const_off += value,
LlValue::Zero => {}
_ => base.dyn_terms.push((offset, 1)),
}
self.symbolic_buffer_addresses
.insert(name.to_string(), base);
}
pub(in crate::native::emitter) fn define_unmodeled_byte_pointer_value(
&mut self,
name: &str,
+151 -58
View File
@@ -1,7 +1,7 @@
use super::cfg::{
funnel_shared_branch_dispatches, index_branch_merges_by_header,
infer_bounded_branch_merges_by_header, infer_branch_merges, infer_direct_branch_merges,
infer_direct_switch_merges, infer_loop_merges, infer_switch_merges,
infer_loop_merges, infer_switch_merges, infer_switch_merges_bounded,
lower_unstructured_switches, privatize_reused_emitted_merge_targets,
refunnel_one_deep_shared_arm, LoopMergeInfo,
};
@@ -60,12 +60,6 @@ pub(super) struct Emitter {
/// lets emission express that contraction explicitly as GLSL.std.450 `Fma`, independent of a
/// downstream SPIR-V consumer's optimizer choices.
fast_float_products: HashMap<String, (TypedValue, TypedValue)>,
fast_grouped_sums: HashMap<String, (Vec<(TypedValue, bool)>, Vec<(TypedValue, bool)>, bool)>,
/// Fast sum trees whose direct-product/difference-product topology requires explicit evaluation
/// partitions. Without these boundaries, an MSL round trip flattens the source AIR tree and
/// changes cancellation residuals even though both forms permit reassociation.
fast_partitioned_sums: HashMap<String, Vec<Vec<TypedValue>>>,
fast_grouped_sum_boundaries: HashSet<String>,
/// Fast add results belonging to a long multiply-accumulate chain. Short source chains already
/// retain AIR's contraction behavior through ordinary MSL expression lowering; explicit `Fma`
/// is reserved for chains long enough that downstream expression materialization loses it.
@@ -200,10 +194,26 @@ pub(super) struct Emitter {
/// `(callee, parameter)`. The emitted-helper inliner can then keep a non-zero caller GEP rooted
/// in the real StorageBuffer instead of the ordinary Private placeholder value.
raw_call_param_offsets: HashMap<(String, String), RawBufferOffset>,
/// `(callee, caller-local argument name)` for every helper call refused because its
/// descriptor-relative byte cursor cannot cross the call. See `EmissionFailure`.
cursor_call_sites: HashSet<(String, String)>,
/// Cached `(callee, parameter index)` pairs whose call sites cannot disagree about the byte
/// a `constant`-space cursor names. See `Emitter::constant_call_cursor_cannot_conflict`.
agreeing_constant_call_cursors: Option<HashSet<(String, usize)>>,
/// Current function's entry params declared `air.buffer` in kernel metadata (data pointers,
/// never textures/samplers). Rebuilt per emit_function from `ir.metadata_data_buffer_params`.
data_buffer_params: HashSet<String>,
raw_offsets: HashMap<String, RawBufferOffset>,
/// Integer SSA values that are the ADDRESS of a descriptor-bound buffer plus a byte offset.
///
/// `ptrtoint` a bound pointer, add to it, `inttoptr` it back: the round trip names a byte inside
/// the buffer it started in, and the address itself is never observed. Logical SPIR-V has no
/// pointer address, so the integer stays the zero
/// [`Self::emit_ptrtoint_resolved`](Emitter::emit_ptrtoint_resolved) already emits -- what is
/// carried here is which buffer and how far in, exactly as `raw_offsets` carries it for a
/// pointer, so the `inttoptr` can hand its result a real offset instead of a placeholder whose
/// loads read zero.
symbolic_buffer_addresses: HashMap<String, RawBufferOffset>,
int_alignments: HashMap<String, u64>,
unmodeled_pointers: HashSet<String>,
/// AIR occasionally embeds a numeric Workgroup address directly in an atomic operand. Logical
@@ -570,9 +580,6 @@ impl Emitter {
glsl_ext: None,
values: HashMap::new(),
fast_float_products: HashMap::new(),
fast_grouped_sums: HashMap::new(),
fast_partitioned_sums: HashMap::new(),
fast_grouped_sum_boundaries: HashSet::new(),
fast_contract_adds: HashSet::new(),
fast_uncontracted_sums: HashSet::new(),
global_values: HashMap::new(),
@@ -625,8 +632,11 @@ impl Emitter {
inline_parameter_substitutions: Vec::new(),
raw_buffer_params: HashSet::new(),
raw_call_param_offsets: HashMap::new(),
cursor_call_sites: HashSet::new(),
agreeing_constant_call_cursors: None,
data_buffer_params: HashSet::new(),
raw_offsets: HashMap::new(),
symbolic_buffer_addresses: HashMap::new(),
int_alignments: HashMap::new(),
unmodeled_pointers: HashSet::new(),
workgroup_i32_addresses: HashMap::new(),
@@ -1095,6 +1105,23 @@ impl Emitter {
}
}
/// The owned facts every emitter failure carries. A retry selects its next representation from
/// these, so raising a failure anywhere in emission must not drop them.
fn emission_failure(&self, error: String) -> crate::emit_sidecar::EmissionFailure {
crate::emit_sidecar::EmissionFailure {
error,
rejected: Box::new(self.emission_rejections()),
}
}
fn emission_rejections(&self) -> crate::emit_sidecar::EmissionRejections {
crate::emit_sidecar::EmissionRejections {
ordinary_plan_functions: self.emit_sidecar.ordinary_plan_rejected_functions.clone(),
ownership_plan_functions: self.emit_sidecar.ownership_plan_rejected_functions.clone(),
cursor_call_sites: self.cursor_call_sites.clone(),
}
}
pub(super) fn emit_with_sidecar(
mut self,
buffer_layouts: Option<&HashMap<u32, crate::meta::AirType>>,
@@ -1115,36 +1142,124 @@ impl Emitter {
this.emit_sidecar.air_data_layout = air_data_layout;
if this.used_device_address {
if let Err(error) = this.lower_bda_null_aggregate_pointers() {
return Err(crate::emit_sidecar::EmissionFailure {
error,
ordinary_plan_rejected_functions: this
.emit_sidecar
.ordinary_plan_rejected_functions
.clone(),
ownership_plan_rejected_functions: this
.emit_sidecar
.ownership_plan_rejected_functions
.clone(),
});
return Err(this.emission_failure(error));
}
if let Err(error) = this.lower_bda_address_operations_module() {
return Err(crate::emit_sidecar::EmissionFailure {
error,
ordinary_plan_rejected_functions: this
.emit_sidecar
.ordinary_plan_rejected_functions
.clone(),
ownership_plan_rejected_functions: this
.emit_sidecar
.ownership_plan_rejected_functions
.clone(),
});
return Err(this.emission_failure(error));
}
this.switch_to_physical_storage_buffer64();
}
this.align_physical_memory_accesses();
Ok((this.module, this.emit_sidecar))
}
/// Attach the `Aligned` memory operand to every load and store through a
/// `PhysicalStorageBuffer` pointer that does not already carry one.
///
/// Vulkan requires it, and `owned_cfg`'s memory-access contract refuses the module without it.
/// Every site that BUILDS a physical access attaches it itself, so this is a no-op for them --
/// measured, 0 of 14579 corpus sources change. What it is for is a physical pointer that
/// reaches an ORDINARY load or store: a `select` between two device addresses hands the
/// generic access path a physical pointer it did not construct, and the alternative to
/// legalizing it here is to decline the whole representation and read zero instead.
///
/// The alignment is the pointee's natural one, the same rule
/// [`Self::device_addr_align`](Emitter::device_addr_align) applies to a device-address leaf.
fn align_physical_memory_accesses(&mut self) {
fn scalar_alignment(types: &HashMap<Word, &Instruction>, id: Word) -> u32 {
let Some(inst) = types.get(&id) else {
return 4;
};
match inst.class.opcode {
Op::TypeInt | Op::TypeFloat => match inst.operands.first() {
Some(Operand::LiteralBit32(bits)) => (bits / 8).clamp(1, 8),
_ => 4,
},
Op::TypeVector | Op::TypeMatrix | Op::TypeArray => match inst.operands.first() {
Some(Operand::IdRef(element)) => scalar_alignment(types, *element),
_ => 4,
},
Op::TypePointer => 8,
_ => 4,
}
}
let types: HashMap<Word, &Instruction> = self
.module
.types_global_values
.iter()
.filter_map(|inst| inst.result_id.map(|id| (id, inst)))
.collect();
let physical_pointer_alignment: HashMap<Word, u32> = self
.module
.types_global_values
.iter()
.filter(|inst| inst.class.opcode == Op::TypePointer)
.filter(|inst| {
matches!(
inst.operands.first(),
Some(Operand::StorageClass(StorageClass::PhysicalStorageBuffer))
)
})
.filter_map(|inst| {
let id = inst.result_id?;
let Some(Operand::IdRef(pointee)) = inst.operands.get(1) else {
return None;
};
Some((id, scalar_alignment(&types, *pointee)))
})
.collect();
if physical_pointer_alignment.is_empty() {
return;
}
let mut pointer_alignment: HashMap<Word, u32> = HashMap::new();
for function in &self.module.functions {
for parameter in &function.parameters {
if let (Some(result), Some(ty)) = (parameter.result_id, parameter.result_type) {
if let Some(align) = physical_pointer_alignment.get(&ty) {
pointer_alignment.insert(result, *align);
}
}
}
for instruction in function.blocks.iter().flat_map(|block| &block.instructions) {
if let (Some(result), Some(ty)) = (instruction.result_id, instruction.result_type) {
if let Some(align) = physical_pointer_alignment.get(&ty) {
pointer_alignment.insert(result, *align);
}
}
}
}
for instruction in self
.module
.functions
.iter_mut()
.flat_map(|function| function.blocks.iter_mut())
.flat_map(|block| block.instructions.iter_mut())
{
// <pointer> for a load; <pointer> <object> for a store.
let operands_before_access = match instruction.class.opcode {
Op::Load => 1,
Op::Store => 2,
_ => continue,
};
if instruction.operands.len() != operands_before_access {
continue;
}
let Some(Operand::IdRef(pointer)) = instruction.operands.first() else {
continue;
};
let Some(alignment) = pointer_alignment.get(pointer).copied() else {
continue;
};
instruction
.operands
.push(Operand::MemoryAccess(MemoryAccess::ALIGNED));
instruction.operands.push(Operand::LiteralBit32(alignment));
}
}
fn lower_bda_address_operations_module(&mut self) -> Result<(), String> {
loop {
let loads_changed = self.lower_bda_integer_pointer_loads_module()?;
@@ -2673,17 +2788,7 @@ impl Emitter {
match $expression {
Ok(value) => value,
Err(error) => {
return Err(crate::emit_sidecar::EmissionFailure {
error,
ordinary_plan_rejected_functions: self
.emit_sidecar
.ordinary_plan_rejected_functions
.clone(),
ownership_plan_rejected_functions: self
.emit_sidecar
.ownership_plan_rejected_functions
.clone(),
});
return Err(self.emission_failure(error));
}
}
};
@@ -2762,10 +2867,7 @@ impl Emitter {
// Match the SPIR-V version LLVM's Vulkan backend emitted for this pipeline.
header.set_version(1, 4);
self.module.header = Some(header);
let ordinary_plan_rejected_functions =
self.emit_sidecar.ordinary_plan_rejected_functions.clone();
let ownership_plan_rejected_functions =
self.emit_sidecar.ownership_plan_rejected_functions.clone();
let rejected = Box::new(self.emission_rejections());
let module = self.module;
let emit_sidecar = self.emit_sidecar;
let inlined = crate::passes::inline_all_emitted_helpers(
@@ -2776,11 +2878,7 @@ impl Emitter {
(self.module, self.emit_sidecar) = match inlined {
Ok(inlined) => inlined,
Err(error) => {
return Err(crate::emit_sidecar::EmissionFailure {
error,
ordinary_plan_rejected_functions,
ownership_plan_rejected_functions,
});
return Err(crate::emit_sidecar::EmissionFailure { error, rejected });
}
};
self.rewrite_private_scalar_offset_access_chains();
@@ -3190,12 +3288,7 @@ fn aggregate_pointer_leaf_paths(
paths
}
fn ptr_access_chain_allowed_storage(storage: StorageClass) -> bool {
matches!(
storage,
StorageClass::Workgroup | StorageClass::StorageBuffer | StorageClass::PhysicalStorageBuffer
)
}
use crate::spirv_module::ptr_access_chain_allowed_storage;
fn result_type_of_id(defs: &HashMap<Word, Instruction>, id: Word) -> Option<Word> {
defs.get(&id).and_then(|inst| inst.result_type)
+85 -218
View File
@@ -9,35 +9,21 @@ impl Emitter {
instructions: &mut Vec<Instruction>,
) -> Result<bool, String> {
match call.callee.as_str() {
"air.simdgroup.barrier" => {
"air.wg.barrier" | "air.simdgroup.barrier" => {
if call.args.len() != 2 {
return Err(
"native emitter: air.simdgroup.barrier expects 2 operands".to_string()
);
return Err(format!(
"native emitter: {} expects 2 operands",
call.callee
));
}
let scope = self.const_uint(Scope::Subgroup as u32)?;
// The execution scope is the second operand, not the intrinsic name. The two
// intrinsics differ only in the scope Apple's `threadgroup_barrier` and
// `simdgroup_barrier` happen to pass, and AIR spells a threadgroup-wide barrier
// through the simdgroup intrinsic often enough to matter.
let execution = air_barrier_execution_scope(call)?;
let scope = self.const_uint(execution as u32)?;
let memory_scope =
self.const_uint(air_barrier_memory_scope(call, Scope::Subgroup) as u32)?;
let semantics = self.const_uint(air_barrier_memory_semantics(call).bits())?;
instructions.push(Self::inst(
Op::ControlBarrier,
None,
None,
vec![
Operand::IdScope(scope),
Operand::IdScope(memory_scope),
Operand::IdMemorySemantics(semantics),
],
));
Ok(true)
}
"air.wg.barrier" => {
if call.args.len() != 2 {
return Err("native emitter: air.wg.barrier expects 2 operands".to_string());
}
let scope = self.const_uint(Scope::Workgroup as u32)?;
let memory_scope =
self.const_uint(air_barrier_memory_scope(call, Scope::Workgroup) as u32)?;
self.const_uint(air_barrier_memory_scope(call, execution) as u32)?;
let semantics = self.const_uint(air_barrier_memory_semantics(call).bits())?;
instructions.push(Self::inst(
Op::ControlBarrier,
@@ -55,19 +41,13 @@ impl Emitter {
if call.args.len() != 3 {
return Err("native emitter: air.atomic.fence expects 3 operands".to_string());
}
let scope_kind = match air_i32_literal(&call.args[2].value) {
Some(1) => Scope::Workgroup,
_ => Scope::Device,
};
let semantics_kind = if scope_kind == Scope::Workgroup {
MemorySemantics::ACQUIRE_RELEASE | MemorySemantics::WORKGROUP_MEMORY
} else {
MemorySemantics::ACQUIRE_RELEASE
| MemorySemantics::UNIFORM_MEMORY
| MemorySemantics::CROSS_WORKGROUP_MEMORY
};
// Which memory a fence covers is its FIRST operand, exactly as it is for the two
// barriers above; the third names the scope over which that memory is ordered.
// Deriving the memory classes from the scope instead answered `mem_threadgroup`
// with device semantics and no `WORKGROUP_MEMORY` at all.
let scope_kind = air_fence_memory_scope(call);
let scope = self.const_uint(scope_kind as u32)?;
let semantics = self.const_uint(semantics_kind.bits())?;
let semantics = self.const_uint(air_barrier_memory_semantics(call).bits())?;
instructions.push(Self::inst(
Op::MemoryBarrier,
None,
@@ -165,9 +145,19 @@ impl Emitter {
instructions: &mut Vec<Instruction>,
) -> Result<bool, String> {
match call.callee.as_str() {
// AGX2 numbers threadgroup lanes in physical 16-wide cluster rows. Preserve a typed
// sentinel here because the native emitter deliberately does not know Vulkan dispatch
// geometry; the interface pass replaces it using LocalInvocationId + LocalSize.
// `llvm.agx2.cluster.num` names the PHYSICAL GPU cluster the threadgroup landed on,
// not any position within it. Device-measured on an M3 Max (`xcrun metal -x ir` over a
// hand-written AIR probe, since MSL has no spelling for the intrinsic): the value is
// identical for every thread of a threadgroup, and over 32768 threadgroups it took every
// value in 0..=36 with no dependence on the thread's coordinates. Vulkan exposes no
// physical cluster, and nothing about the invocation could reproduce one — a per-thread
// answer would make a predicate the hardware guarantees uniform diverge inside a
// threadgroup, which is worse than any single answer. Zero is the answer given, and it
// is one the device itself gives: it says this threadgroup ran on cluster 0, which is a
// legal execution of a value the hardware picks nondeterministically. The corpus uses it
// only as `icmp ult %n, 10` guarding a per-cluster slot claimed by an atomic cmpxchg,
// so the effect is that every threadgroup contends for slot 0 and one wins, as it would
// on a device with a single cluster.
"llvm.agx2.cluster.num" => {
if !call.args.is_empty() {
return Err(format!(
@@ -191,7 +181,6 @@ impl Emitter {
Some(result),
vec![Operand::IdRef(zero)],
));
self.emit_sidecar.agx2_cluster_numbers.push(result);
Ok(true)
}
// `air.is_null_texture_<dim>(%tex)` asks whether a texture handle is the null texture.
@@ -362,181 +351,6 @@ impl Emitter {
));
Ok(true)
}
"air.simd_any" | "air.simd_all" => {
if call.args.len() != 1 {
return Err(format!("native emitter: {} expects 1 operand", call.callee));
}
let result_ty = self.resolve_type(&call.ret)?;
if !is_bool_type(&result_ty) {
return Err(format!(
"native emitter: {} returned {result_ty:?}",
call.callee
));
}
let value_ty = self.resolve_type(&call.args[0].ty)?;
if !is_bool_type(&value_ty) {
return Err(format!(
"native emitter: {} value is {value_ty:?}",
call.callee
));
}
let result_type = self.type_id(&result_ty)?;
let result = self.result_id(name, &result_ty)?;
let value =
self.value_id_in(&call.args[0].value, &call.args[0].ty, instructions)?;
let scope = self.const_uint(Scope::Subgroup as u32)?;
let op = if call.callee == "air.simd_any" {
Op::GroupNonUniformAny
} else {
Op::GroupNonUniformAll
};
instructions.push(Self::inst(
op,
Some(result_type),
Some(result),
vec![Operand::IdScope(scope), Operand::IdRef(value)],
));
Ok(true)
}
"air.simd_ballot.i64" => {
if call.args.len() != 1 {
return Err("native emitter: air.simd_ballot.i64 expects 1 operand".to_string());
}
let result_ty = self.resolve_type(&call.ret)?;
if result_ty != LlType::Int(64) {
return Err(format!(
"native emitter: air.simd_ballot.i64 returned {result_ty:?}"
));
}
let predicate_ty = self.resolve_type(&call.args[0].ty)?;
if !is_bool_type(&predicate_ty) {
return Err(format!(
"native emitter: air.simd_ballot.i64 predicate is {predicate_ty:?}"
));
}
let uint = self.type_id(&LlType::Int(32))?;
let ulong = self.type_id(&LlType::Int(64))?;
let ballot_ty = LlType::Vector(Box::new(LlType::Int(32)), 4);
let ballot_type = self.type_id(&ballot_ty)?;
let result = self.result_id(name, &result_ty)?;
let predicate =
self.value_id_in(&call.args[0].value, &call.args[0].ty, instructions)?;
let scope = self.const_uint(Scope::Subgroup as u32)?;
let ballot = self.fresh();
instructions.push(Self::inst(
Op::GroupNonUniformBallot,
Some(ballot_type),
Some(ballot),
vec![Operand::IdScope(scope), Operand::IdRef(predicate)],
));
let lo32 = self.fresh();
instructions.push(Self::inst(
Op::CompositeExtract,
Some(uint),
Some(lo32),
vec![Operand::IdRef(ballot), Operand::LiteralBit32(0)],
));
let hi32 = self.fresh();
instructions.push(Self::inst(
Op::CompositeExtract,
Some(uint),
Some(hi32),
vec![Operand::IdRef(ballot), Operand::LiteralBit32(1)],
));
let lo64 = self.fresh();
instructions.push(Self::inst(
Op::UConvert,
Some(ulong),
Some(lo64),
vec![Operand::IdRef(lo32)],
));
let hi64 = self.fresh();
instructions.push(Self::inst(
Op::UConvert,
Some(ulong),
Some(hi64),
vec![Operand::IdRef(hi32)],
));
let shift = self.const_int(64, 32)?;
let shifted_hi = self.fresh();
instructions.push(Self::inst(
Op::ShiftLeftLogical,
Some(ulong),
Some(shifted_hi),
vec![Operand::IdRef(hi64), Operand::IdRef(shift)],
));
instructions.push(Self::inst(
Op::BitwiseOr,
Some(ulong),
Some(result),
vec![Operand::IdRef(shifted_hi), Operand::IdRef(lo64)],
));
Ok(true)
}
"air.simd_shuffle.u.i32" | "air.simd_shuffle.s.i32" => {
if call.args.len() != 2 {
return Err(format!(
"native emitter: {} expects 2 operands",
call.callee
));
}
let result_ty = self.resolve_type(&call.ret)?;
if result_ty != LlType::Int(32) {
return Err(format!(
"native emitter: {} returned {result_ty:?}",
call.callee
));
}
let value_ty = self.resolve_type(&call.args[0].ty)?;
if value_ty != LlType::Int(32) {
return Err(format!(
"native emitter: {} value is {value_ty:?}",
call.callee
));
}
let lane_ty = self.resolve_type(&call.args[1].ty)?;
if !matches!(lane_ty, LlType::Int(_)) {
return Err(format!(
"native emitter: {} lane is {lane_ty:?}",
call.callee
));
}
let result_type = self.type_id(&result_ty)?;
let result = self.result_id(name, &result_ty)?;
let value =
self.value_id_in(&call.args[0].value, &call.args[0].ty, instructions)?;
let lane = self.value_id_in(&call.args[1].value, &call.args[1].ty, instructions)?;
let uint = self.type_id(&LlType::Int(32))?;
let invocation = if lane_ty == LlType::Int(32) {
lane
} else {
let converted = self.fresh();
instructions.push(Self::inst(
Op::UConvert,
Some(uint),
Some(converted),
vec![Operand::IdRef(lane)],
));
converted
};
let scope = self.const_uint(Scope::Subgroup as u32)?;
instructions.push(Self::inst(
Op::GroupNonUniformShuffle,
Some(result_type),
Some(result),
vec![
Operand::IdScope(scope),
Operand::IdRef(value),
Operand::IdRef(invocation),
],
));
Ok(true)
}
"air.atomic.local.load.i32" | "air.atomic.global.load.i32" => {
if call.args.len() != 4 {
return Err(format!(
@@ -802,6 +616,12 @@ impl Emitter {
}
}
/// Which memories a barrier synchronizes, from AIR's `mem_flags` word.
///
/// `metal_compute`'s enum, confirmed one setter per probe kernel: `mem_device` is 1,
/// `mem_threadgroup` 2, `mem_texture` 4, `mem_threadgroup_imageblock` 8. An imageblock is
/// threadgroup memory -- the shared-cell lowering puts it in `Workgroup` storage -- so bit 3
/// names the same semantic bit as bit 1 rather than a new one.
fn air_barrier_memory_semantics(call: &LlCall) -> MemorySemantics {
let flags = call
.args
@@ -812,7 +632,7 @@ fn air_barrier_memory_semantics(call: &LlCall) -> MemorySemantics {
if flags & 1 != 0 {
semantics |= MemorySemantics::UNIFORM_MEMORY | MemorySemantics::CROSS_WORKGROUP_MEMORY;
}
if flags & 2 != 0 {
if flags & (2 | 8) != 0 {
semantics |= MemorySemantics::WORKGROUP_MEMORY;
}
if flags & 4 != 0 {
@@ -824,6 +644,53 @@ fn air_barrier_memory_semantics(call: &LlCall) -> MemorySemantics {
semantics
}
/// The execution scope AIR states in a barrier's second operand: 1 threadgroup, 4 simdgroup.
///
/// Both barrier intrinsics carry it and both take both values. Apple's `threadgroup_barrier`
/// compiles to `air.wg.barrier(flags, 1)` and `simdgroup_barrier` to
/// `air.simdgroup.barrier(flags, 4)`, but AIR also spells a threadgroup-wide execution barrier
/// through the simdgroup intrinsic: 42 such calls across 13 corpus sources. Reading the scope off
/// the callee name instead of the operand made those synchronize one simdgroup where Metal
/// synchronizes the whole threadgroup.
///
/// Only 1 and 4 appear in the corpus and only those two are documented by the headers, so any
/// other value fails visibly rather than picking a scope for it.
fn air_barrier_execution_scope(call: &LlCall) -> Result<Scope, String> {
match call.args.get(1).and_then(|arg| air_i32_literal(&arg.value)) {
Some(1) => Ok(Scope::Workgroup),
Some(4) => Ok(Scope::Subgroup),
Some(other) => Err(format!(
"native emitter: {} states execution scope {other}, which is neither AIR's threadgroup \
(1) nor its simdgroup (4)",
call.callee
)),
None => Err(format!(
"native emitter: {} has no constant execution scope operand",
call.callee
)),
}
}
/// The scope AIR states in `air.atomic.fence`'s third operand.
///
/// `atomic_thread_fence(flags, order, scope)` lowers to `air.atomic.fence(int(flags), int(order),
/// int(scope))`, and `thread_scope` is `thread_scope_thread` 0, `thread_scope_threadgroup` 1,
/// `thread_scope_device` 2 and `thread_scope_simdgroup` 4 — read one enumerator at a time out of
/// the Metal front end, not out of the enum's declaration order, which does not match the values.
///
/// Corpus fences state only 2 and a legacy 3, the OpenCL-derived all-devices scope this Metal has
/// dropped; both are Device, which is the widest scope a Vulkan shader can name. Anything else
/// unrecognised is Device too: a wider fence orders strictly more than a narrower one, so guessing
/// wide cannot lose an ordering the shader asked for.
fn air_fence_memory_scope(call: &LlCall) -> Scope {
match call.args.get(2).and_then(|arg| air_i32_literal(&arg.value)) {
Some(0) => Scope::Invocation,
Some(1) => Scope::Workgroup,
Some(4) => Scope::Subgroup,
_ => Scope::Device,
}
}
fn air_barrier_memory_scope(call: &LlCall, default_scope: Scope) -> Scope {
let flags = call
.args
+27 -3
View File
@@ -3,15 +3,26 @@
use super::*;
impl Emitter {
/// The scope an atomic on `ptr_arg` is performed over: the storage class of the pointer
/// [`Self::atomic_i32_pointer_id`] will emit for the SAME argument.
///
/// The two must test `raw_offsets` and `unmodeled_pointers` in the SAME order, because a
/// placeholder name is in BOTH sets -- an unmodelled pointer carries its real addressing in
/// `raw_offsets` and only falls back to a Workgroup slot when it has no such entry. Testing
/// `unmodeled_pointers` first here while the pointer side tests `raw_offsets` first answered
/// `Workgroup` for 32 atomics in 8 corpus modules whose emitted pointer is
/// `PhysicalStorageBuffer`: a device-address atomic scoped to one threadgroup, which is not
/// atomic against any other threadgroup, and whose semantics named `WorkgroupMemory` for a
/// device-memory access.
pub(in crate::native::emitter) fn atomic_i32_scope_for_arg(
&self,
ptr_arg: &TypedValue,
) -> Result<Scope, String> {
let storage = if let LlValue::Local(name) = &ptr_arg.value {
if self.unmodeled_pointers.contains(name) {
StorageClass::Workgroup
} else if let Some(raw) = self.raw_offsets.get(name) {
if let Some(raw) = self.raw_offsets.get(name) {
self.raw_access_storage(raw)?
} else if self.unmodeled_pointers.contains(name) {
StorageClass::Workgroup
} else {
let LlType::Ptr(addrspace) = self.resolve_type(&ptr_arg.ty)? else {
return Err(format!(
@@ -219,6 +230,19 @@ impl Emitter {
Ok(result)
}
/// The atomic slot for a pointer that has no addressing at all -- neither a raw offset nor a
/// modelled pointee. Both callers reach `raw_offsets` first, so this is the placeholder with
/// nothing behind it, and the atomic it carries writes into a threadgroup word nothing reads.
///
/// **Measured dead: 0 of the 706 corpus sources that name any `air.atomic.*` reach either this
/// or [`Self::unmodeled_atomic_f32_pointer`].** Deleting them looks like an easy win and is
/// not: without them an f32 atomic on a placeholder falls through to the Private placeholder
/// ID itself and the pointer-storage-class check refuses the module. What reaches them is
/// UNDERSPECIFIED AIR, not anything the Metal frontend emits -- `device atomic_float*` carries
/// `air.struct_type_info` and `air.arg_type_name "metal::_atomic"`, and with those the buffer
/// is modelled as an array of its own struct and the atomic lands on the real slot. Drop the
/// struct info, as a hand-written fixture easily does, and the buffer collapses to a word view
/// the float GEP cannot be typed through. Keep these as the floor for that input.
pub(in crate::native::emitter) fn unmodeled_atomic_i32_pointer(
&mut self,
) -> Result<Word, String> {
+99
View File
@@ -127,6 +127,12 @@ impl Emitter {
instructions: &mut Vec<Instruction>,
) -> Result<(), String> {
let result_ty = self.resolve_type(&lhs.ty)?;
if op == Op::IAdd {
// Adding to a bound buffer's address moves within that buffer. Carry the base forward so
// an `inttoptr` at the end of the chain still knows which buffer it is in; the integer
// result itself is emitted exactly as before.
self.extend_symbolic_buffer_address(&name, &lhs, &rhs);
}
let int_alignment = match op {
Op::IAdd | Op::ISub => add_int_alignment(
self.int_value_alignment(&lhs.value),
@@ -318,3 +324,96 @@ impl Emitter {
Ok(())
}
}
impl Emitter {
/// Emit a float binary op and return the ids of every arithmetic result it produced.
///
/// One LLVM instruction can expand into several: a wider-than-four vector scalarizes into one op
/// per lane, and a bf16 operand widens to `float` around an inner op. All of them descend from
/// the same source instruction and carry the same fast-math permissions, so a caller that has to
/// state a withheld permission states it about all of them.
fn emit_float_op_collecting_results(
&mut self,
op: Op,
lhs: TypedValue,
rhs: TypedValue,
name: String,
instructions: &mut Vec<Instruction>,
) -> Result<Vec<Word>, String> {
let emitted_before = instructions.len();
self.emit_binary_float_op_resolved(op, lhs, rhs, name, instructions)?;
Ok(instructions[emitted_before..]
.iter()
.filter(|instruction| {
matches!(
instruction.class.opcode,
Op::FMul | Op::FAdd | Op::FSub | Op::FDiv | Op::FNegate
)
})
.filter_map(|instruction| instruction.result_id)
.collect())
}
/// A float arithmetic instruction that withholds at least one fast-math permission, emitted with
/// every arithmetic result it produces decorated `FPFastMathMode` carrying exactly the
/// permissions LLVM granted.
///
/// Metal decides its float relaxations from the module's math mode and the expression's
/// `precise`-ness; SPIR-V has no equivalent module state, so an undecorated `OpFMul` is an open
/// invitation and MoltenVK -- whose own fast-math default is on -- takes it. Measured twice:
/// decorating the pair in `StyleEngineCoefficients::filterStep` moves its four lanes off the
/// fused answer onto the separately rounded one, and decorating the division in
/// `MinMaxReduction_float2` moves its five-texel average off the multiply-by-rounded-reciprocal
/// answer onto the correctly rounded quotient.
///
/// `FPFastMathMode` rather than `NoContraction` for all four opcodes, because `NoContraction`
/// can only say one of the seven things a flag run says. It forbids fusion and leaves
/// reassociation permitted, and 437 corpus sources carry a three-term association chain no
/// instruction of which permits regrouping. `SPV_KHR_float_controls2` is the only
/// per-instruction spelling for the rest, so a module with such an instruction requires it.
///
/// `AllowTransform` is never set. It is the umbrella permission over reassociation, contraction
/// and the reciprocal, and setting it would grant a fusion of the three that no LLVM flag asked
/// for; withholding it is the conservative reading of a flag run that already withheld
/// something.
pub(in crate::native::emitter) fn emit_float_op_granting(
&mut self,
op: Op,
lhs: TypedValue,
rhs: TypedValue,
name: String,
mode: crate::native::tir::FloatMathMode,
instructions: &mut Vec<Instruction>,
) -> Result<(), String> {
let results = self.emit_float_op_collecting_results(op, lhs, rhs, name, instructions)?;
if results.is_empty() {
return Ok(());
}
let granted = [
(mode.not_nan, spirv::FPFastMathMode::NOT_NAN),
(mode.not_inf, spirv::FPFastMathMode::NOT_INF),
(mode.signed_zero_insignificant, spirv::FPFastMathMode::NSZ),
(mode.allow_reciprocal, spirv::FPFastMathMode::ALLOW_RECIP),
(mode.allow_contract, spirv::FPFastMathMode::ALLOW_CONTRACT),
(mode.allow_reassociate, spirv::FPFastMathMode::ALLOW_REASSOC),
]
.into_iter()
.filter(|(permitted, _)| *permitted)
.fold(spirv::FPFastMathMode::NONE, |mask, (_, bit)| mask | bit);
self.require_capability(Capability::FloatControls2);
self.require_extension("SPV_KHR_float_controls2");
for result in results {
self.module.annotations.push(Self::inst(
Op::Decorate,
None,
None,
vec![
Operand::IdRef(result),
Operand::Decoration(spirv::Decoration::FPFastMathMode),
Operand::FPFastMathMode(granted),
],
));
}
Ok(())
}
}
+192 -104
View File
@@ -230,46 +230,42 @@ impl Emitter {
Ok(true)
}
pub(in crate::native::emitter) fn emit_air_unsigned_sat_call(
/// `air.{add,sub}_sat.{s,u}.<ty>(a, b)`: the sum or difference clamped to the operand type's
/// own range rather than wrapped.
///
/// Unsigned carries are self-announcing — the wrapped sum compares below an operand exactly
/// when it carried, and the wrapped difference borrowed exactly when `a < b` — so one
/// `ULessThan` picks between the wrapped value and the single range end.
///
/// Signed has two ends, and which one it saturates to is the sign of `a`: `a >> (W-1)` is
/// all-zeros or all-ones, and XOR with `INT_MAX` turns those into `INT_MAX` and `INT_MIN`.
/// Overflow is a sign disagreement the wrapped result cannot hide: for `a + b` both operands
/// disagree with it, for `a - b` the operands disagree with each other and `a` disagrees with
/// the result. Device-measured against Metal's `addsat`/`subsat` over a 256-row `i32` edge
/// grid, and both forms are width- and lane-generic, so `<3 x i8>` and `i16` take the same
/// path as `i32`.
pub(in crate::native::emitter) fn emit_air_saturating_add_sub_call(
&mut self,
call: &LlCall,
name: &str,
instructions: &mut Vec<Instruction>,
) -> Result<bool, String> {
let is_add = call.callee.starts_with("air.add_sat.u.");
let is_sub = call.callee.starts_with("air.sub_sat.u.");
if !is_add && !is_sub {
const MEMBERS: [(&str, bool, bool); 4] = [
("air.add_sat.u.", true, false),
("air.add_sat.s.", true, true),
("air.sub_sat.u.", false, false),
("air.sub_sat.s.", false, true),
];
let Some(&(_, is_add, signed)) = MEMBERS
.iter()
.find(|(prefix, _, _)| call.callee.starts_with(prefix))
else {
return Ok(false);
}
if call.args.len() != 2 {
return Err(format!(
"native emitter: {} expects two operands",
call.callee
));
}
let result_ty = self.resolve_type(&call.ret)?;
if !is_integer_type(&result_ty) {
return Err(format!(
"native emitter: {} expects integer result, got {result_ty:?}",
call.callee
));
}
let lhs = &call.args[0];
let rhs = &call.args[1];
let lhs_ty = self.resolve_type(&lhs.ty)?;
let rhs_ty = self.resolve_type(&rhs.ty)?;
if lhs_ty != result_ty || rhs_ty != result_ty {
return Err(format!(
"native emitter: {} operand/result type mismatch {lhs_ty:?}, {rhs_ty:?}, {result_ty:?}",
call.callee
));
}
let cmp_ty = int_compare_result_type(&result_ty)?;
let cmp_ty_id = self.type_id(&cmp_ty)?;
};
let (result_ty, width, lhs_id, rhs_id) = self.int_binary_operands(call, instructions, 2)?;
let cmp_ty_id = self.type_id(&int_compare_result_type(&result_ty)?)?;
let result_ty_id = self.type_id(&result_ty)?;
let lhs_id = self.value_id_in(&lhs.value, &lhs.ty, instructions)?;
let rhs_id = self.value_id_in(&rhs.value, &rhs.ty, instructions)?;
let raw = self.fresh();
instructions.push(Self::inst(
if is_add { Op::IAdd } else { Op::ISub },
@@ -277,29 +273,92 @@ impl Emitter {
Some(raw),
vec![Operand::IdRef(lhs_id), Operand::IdRef(rhs_id)],
));
let saturated = self.fresh();
instructions.push(Self::inst(
Op::ULessThan,
Some(cmp_ty_id),
Some(saturated),
if is_add {
vec![Operand::IdRef(raw), Operand::IdRef(lhs_id)]
let (overflowed, limit) = if signed {
// `(a ^ raw) & (b ^ raw)` for add, `(a ^ b) & (a ^ raw)` for sub; negative iff the
// true result left the range.
let (left, right) = if is_add {
((lhs_id, raw), (rhs_id, raw))
} else {
vec![Operand::IdRef(lhs_id), Operand::IdRef(rhs_id)]
},
));
let limit = if is_add {
self.int_constant_like(&result_ty, -1)?
((lhs_id, rhs_id), (lhs_id, raw))
};
let disagree_left = self.fresh();
instructions.push(Self::inst(
Op::BitwiseXor,
Some(result_ty_id),
Some(disagree_left),
vec![Operand::IdRef(left.0), Operand::IdRef(left.1)],
));
let disagree_right = self.fresh();
instructions.push(Self::inst(
Op::BitwiseXor,
Some(result_ty_id),
Some(disagree_right),
vec![Operand::IdRef(right.0), Operand::IdRef(right.1)],
));
let both = self.fresh();
instructions.push(Self::inst(
Op::BitwiseAnd,
Some(result_ty_id),
Some(both),
vec![
Operand::IdRef(disagree_left),
Operand::IdRef(disagree_right),
],
));
let zero = self.const_null(&result_ty)?;
let overflowed = self.fresh();
instructions.push(Self::inst(
Op::SLessThan,
Some(cmp_ty_id),
Some(overflowed),
vec![Operand::IdRef(both), Operand::IdRef(zero)],
));
// `(a >> (W-1)) ^ INT_MAX` is `INT_MIN` when `a` is negative and `INT_MAX` otherwise.
let sign_bits = self.fresh();
let shift = self.int_constant_like(&result_ty, i64::from(width - 1))?;
instructions.push(Self::inst(
Op::ShiftRightArithmetic,
Some(result_ty_id),
Some(sign_bits),
vec![Operand::IdRef(lhs_id), Operand::IdRef(shift)],
));
let int_max = self.int_constant_like(&result_ty, i64::MAX >> (64 - width))?;
let limit = self.fresh();
instructions.push(Self::inst(
Op::BitwiseXor,
Some(result_ty_id),
Some(limit),
vec![Operand::IdRef(sign_bits), Operand::IdRef(int_max)],
));
(overflowed, limit)
} else {
self.const_null(&result_ty)?
let overflowed = self.fresh();
instructions.push(Self::inst(
Op::ULessThan,
Some(cmp_ty_id),
Some(overflowed),
if is_add {
vec![Operand::IdRef(raw), Operand::IdRef(lhs_id)]
} else {
vec![Operand::IdRef(lhs_id), Operand::IdRef(rhs_id)]
},
));
let limit = if is_add {
self.int_constant_like(&result_ty, -1)?
} else {
self.const_null(&result_ty)?
};
(overflowed, limit)
};
let result = self.result_id(name, &result_ty)?;
instructions.push(Self::inst(
Op::Select,
Some(result_ty_id),
Some(result),
vec![
Operand::IdRef(saturated),
Operand::IdRef(overflowed),
Operand::IdRef(limit),
Operand::IdRef(raw),
],
@@ -308,25 +367,103 @@ impl Emitter {
Ok(true)
}
pub(in crate::native::emitter) fn emit_air_unsigned_rhadd_call(
/// `air.{h,rhadd}.{s,u}.<ty>(a, b)`: the average of two integers, computed so the intermediate
/// sum cannot overflow the operand width.
///
/// `hadd(a, b) = (a & b) + ((a ^ b) >> 1)` and `rhadd(a, b) = (a | b) - ((a ^ b) >> 1)`: the
/// common bits carry their full weight and the differing bits carry half, so nothing ever
/// leaves the operand type and no widening is needed at any width. The shift is arithmetic for
/// the signed families, which is exactly Metal's rounding: `hadd` truncates toward -inf and
/// `rhadd` rounds the half up, both device-measured over a 256-row `i32` edge grid.
pub(in crate::native::emitter) fn emit_air_halving_add_call(
&mut self,
call: &LlCall,
name: &str,
instructions: &mut Vec<Instruction>,
) -> Result<bool, String> {
if call.callee != "air.rhadd.u.i16" {
const MEMBERS: [(&str, bool, bool); 4] = [
("air.hadd.u.", false, false),
("air.hadd.s.", false, true),
("air.rhadd.u.", true, false),
("air.rhadd.s.", true, true),
];
let Some(&(_, rounded, signed)) = MEMBERS
.iter()
.find(|(prefix, _, _)| call.callee.starts_with(prefix))
else {
return Ok(false);
}
if call.args.len() != 2 {
};
let (result_ty, _, lhs_id, rhs_id) = self.int_binary_operands(call, instructions, 2)?;
let result_ty_id = self.type_id(&result_ty)?;
let common = self.fresh();
instructions.push(Self::inst(
if rounded {
Op::BitwiseOr
} else {
Op::BitwiseAnd
},
Some(result_ty_id),
Some(common),
vec![Operand::IdRef(lhs_id), Operand::IdRef(rhs_id)],
));
let differing = self.fresh();
instructions.push(Self::inst(
Op::BitwiseXor,
Some(result_ty_id),
Some(differing),
vec![Operand::IdRef(lhs_id), Operand::IdRef(rhs_id)],
));
let half = self.fresh();
let one = self.int_constant_like(&result_ty, 1)?;
instructions.push(Self::inst(
if signed {
Op::ShiftRightArithmetic
} else {
Op::ShiftRightLogical
},
Some(result_ty_id),
Some(half),
vec![Operand::IdRef(differing), Operand::IdRef(one)],
));
let result = self.result_id(name, &result_ty)?;
instructions.push(Self::inst(
if rounded { Op::ISub } else { Op::IAdd },
Some(result_ty_id),
Some(result),
vec![Operand::IdRef(common), Operand::IdRef(half)],
));
self.record_int_alignment(name, &result_ty, 1);
Ok(true)
}
/// Resolves the operands of an integer AIR intrinsic that requires every operand and the
/// result to share one integer scalar/vector type, returning that type, its component width
/// and the operand ids.
fn int_binary_operands(
&mut self,
call: &LlCall,
instructions: &mut Vec<Instruction>,
arity: usize,
) -> Result<(LlType, u32, Word, Word), String> {
if call.args.len() != arity {
return Err(format!(
"native emitter: {} expects two operands",
"native emitter: {} expects {arity} operands",
call.callee
));
}
let result_ty = self.resolve_type(&call.ret)?;
if result_ty != LlType::Int(16) {
let width = match &result_ty {
LlType::Int(bits) => *bits,
LlType::Vector(elem, _) => match elem.as_ref() {
LlType::Int(bits) => *bits,
_ => 0,
},
_ => 0,
};
if width == 0 {
return Err(format!(
"native emitter: {} returned {result_ty:?}",
"native emitter: {} expects integer result, got {result_ty:?}",
call.callee
));
}
@@ -339,58 +476,9 @@ impl Emitter {
));
}
}
let ushort = self.type_id(&result_ty)?;
let uint = self.type_id(&LlType::Int(32))?;
let lhs = self.value_id_in(&call.args[0].value, &call.args[0].ty, instructions)?;
let rhs = self.value_id_in(&call.args[1].value, &call.args[1].ty, instructions)?;
let lhs32 = self.fresh();
instructions.push(Self::inst(
Op::UConvert,
Some(uint),
Some(lhs32),
vec![Operand::IdRef(lhs)],
));
let rhs32 = self.fresh();
instructions.push(Self::inst(
Op::UConvert,
Some(uint),
Some(rhs32),
vec![Operand::IdRef(rhs)],
));
let one = self.const_uint(1)?;
let sum = self.fresh();
instructions.push(Self::inst(
Op::IAdd,
Some(uint),
Some(sum),
vec![Operand::IdRef(lhs32), Operand::IdRef(rhs32)],
));
let rounded = self.fresh();
instructions.push(Self::inst(
Op::IAdd,
Some(uint),
Some(rounded),
vec![Operand::IdRef(sum), Operand::IdRef(one)],
));
let shift = self.const_uint(1)?;
let half = self.fresh();
instructions.push(Self::inst(
Op::ShiftRightLogical,
Some(uint),
Some(half),
vec![Operand::IdRef(rounded), Operand::IdRef(shift)],
));
let result = self.result_id(name, &result_ty)?;
instructions.push(Self::inst(
Op::UConvert,
Some(ushort),
Some(result),
vec![Operand::IdRef(half)],
));
self.record_int_alignment(name, &result_ty, 1);
Ok(true)
Ok((result_ty, width, lhs, rhs))
}
pub(in crate::native::emitter) fn emit_llvm_fshl_call(
+3 -1
View File
@@ -470,7 +470,9 @@ impl Emitter {
// A `null`/`undef` incoming must carry the phi's resolved pointer type (storage + pointee), the
// same the select path already does — otherwise it is emitted with the generic default type and
// mismatches the phi result (the cross-storage `_ptr_UniformConstant_uchar` validation reject).
if let Some(id) = self.typed_null_or_undef_pointer_id(value, meta.storage, pointee)? {
if let Some(id) =
self.typed_null_or_undef_pointer_id(value, meta.storage, pointee, instructions)?
{
return Ok(id);
}
let Some(template) = result_provenance else {
+106 -22
View File
@@ -157,6 +157,24 @@ impl Emitter {
return Ok(address);
}
if self.bda_address_loads.contains(name) {
// The load has not been lowered yet -- this arm is a forward reference from a
// loop header -- so the id to reserve is the one `emit_load_resolved`'s
// device-address branch will DEFINE: `bda_address_name(name)`, into which it
// loads the eight address bytes. It deliberately leaves the pointer's own
// result id undefined, so reserving `name` produced an `OpIAdd %ulong` over an
// id nothing ever gave a value.
//
// Once the load HAS been lowered, `values[name]` is what its own lowering
// decided this value is, and this branch must not second-guess it: a
// `ptr addrspace(1)` load is also how an opaque texture handle comes out of an
// argument buffer, and that one is a descriptor with no address at all. A load
// that did lower as a device address never reaches here -- `raw_offsets[name]`
// carries its `device_addr_base` and the branches above return it.
if !self.values.contains_key(name) {
let address = self.result_id(&bda_address_name(name), &LlType::Int(64))?;
self.bda_address_values.insert(address);
return Ok(address);
}
let result_ty = self.tir_result_types.get(name).cloned().ok_or_else(|| {
format!("native emitter: BDA pointer load {name} has no result type")
})?;
@@ -537,8 +555,8 @@ impl Emitter {
}
/// Whether a pointer phi is a fully-RAW single-root induction: every arm is either a pointer
/// already raw-modeled under the template's root (same root + addrspace, modelable) or the
/// loop-carried step — a forward GEP whose base is the phi itself. Such a phi is exactly the
/// already raw-modeled under the template's root (same root + addrspace, modelable) or a
/// loop-carried step of the phi itself (`raw_induction_arm`). Such a phi is exactly the
/// shape `emit_raw_pointer_phi` models (a byte/word index phi over one raw root), and the ONLY
/// shape where the `network_pointees` defer must not steal the claim: the typed merge path has
/// no way to express the network pointee against the root's raw block declaration.
@@ -548,22 +566,69 @@ impl Emitter {
incoming: &[(LlValue, String)],
template: &RawBufferOffset,
) -> bool {
incoming.iter().all(|(value, _)| {
let LlValue::Local(incoming_name) = value else {
return false;
};
if let Some(raw) = self.raw_offsets.get(incoming_name) {
return raw.root == template.root
&& raw.addrspace == template.addrspace
&& !raw.unmodelable;
}
self.forward_geps
.get(incoming_name)
.is_some_and(|gep| matches!(&gep.base.value, LlValue::Local(base) if base == name))
|| self
.forward_select_recurrence_gep(incoming_name, name)
.is_some()
})
let mut proving = HashSet::from([name.to_string()]);
incoming
.iter()
.all(|(value, _)| self.raw_induction_arm(name, value, template, &mut proving))
}
/// Whether one arm of a raw induction phi is a step of the SAME cursor.
///
/// The simple shape is a self-recursive phi whose backedge is a forward GEP off itself. A
/// pointer walked by a NESTED loop is a CYCLE of phis instead: the outer header's carried
/// pointer is advanced by the inner loop, so its backedge arm is a GEP off the INNER header's
/// phi, whose own entry arm is the outer phi (a third phi in the latch closes the cycle when
/// the inner loop is also conditional). No arm of either phi is a GEP off that phi, so the
/// one-phi test left the whole cycle on `Private` placeholders. Every value in such a cycle
/// addresses the same root, and the typed merge path cannot express any of them -- their arms
/// materialize against the root's raw `{ [0 x i32] }` declaration -- so walking the cycle and
/// admitting all of them together is the only representation that keeps the accesses on the
/// buffer.
///
/// A name already being proved counts as proved: that is the cycle closing, and the arms that
/// reach it are checked on their own way round.
///
/// Measured over the corpus against the one-phi test: 24 of 14,579 sources change, 4 of them
/// ERROR -> OK (a phi merging a placeholder with a real `StorageBuffer` pointer has no common
/// type, so those did not merely read zero, they failed to construct), 20 emit more
/// `StorageBuffer` access chains in place of null-folded loads, and none regress.
fn raw_induction_arm(
&self,
phi: &str,
value: &LlValue,
template: &RawBufferOffset,
proving: &mut HashSet<String>,
) -> bool {
if matches!(value, LlValue::Zero) {
return true;
}
let LlValue::Local(incoming_name) = value else {
return false;
};
if let Some(raw) = self.raw_offsets.get(incoming_name) {
return raw.root == template.root
&& raw.addrspace == template.addrspace
&& !raw.unmodelable;
}
if !proving.insert(incoming_name.clone()) {
return true;
}
if let Some(gep) = self.forward_geps.get(incoming_name) {
return self.raw_induction_arm(phi, &gep.base.value, template, proving);
}
if self
.forward_select_recurrence_gep(incoming_name, phi)
.is_some()
{
return true;
}
self.tir_phi_incomings
.get(incoming_name)
.is_some_and(|incoming| {
incoming
.iter()
.all(|(value, _)| self.raw_induction_arm(phi, value, template, proving))
})
}
pub(in crate::native::emitter) fn emit_raw_pointer_phi(
@@ -603,6 +668,9 @@ impl Emitter {
}
let all_incoming_raw = incoming.iter().all(|(value, _)| match value {
LlValue::Local(name) => self.raw_offsets.contains_key(name),
// A `null` arm is the root at offset 0 (see the arm loop below), which is raw and
// word-aligned by construction.
LlValue::Zero => true,
_ => false,
});
// A raw phi can use word indices only when EVERY arm is word-aligned. Choosing the
@@ -612,10 +680,11 @@ impl Emitter {
// only at a later access whose alignment proves it legal.
let word_indexed = all_incoming_raw
&& incoming.iter().all(|(value, _)| {
matches!(value, LlValue::Local(name) if self
.raw_offsets
.get(name)
.is_some_and(|raw| self.raw_pointer_word_aligned(raw)))
matches!(value, LlValue::Zero)
|| matches!(value, LlValue::Local(name) if self
.raw_offsets
.get(name)
.is_some_and(|raw| self.raw_pointer_word_aligned(raw)))
});
let index_ty = LlType::Int(32);
@@ -669,6 +738,15 @@ impl Emitter {
)?
}
}
// A `null` arm is the loop-entry or unused-variant edge of a pointer the shader
// only dereferences on the OTHER edges: dereferencing null is undefined, so the
// index it contributes is unobservable and 0 is the representable choice. The
// nullness phi below keeps `p == null` answerable, which is what the shader
// actually asks. Refusing the arm instead collapsed the whole phi -- and every
// pointer downstream of it -- to a `Private` zero placeholder, so the loads on
// the LIVE edges answered zero too. Measured over the corpus: 40 sources change
// and the placeholder-load residue falls 79 -> 38, the single largest class of it.
LlValue::Zero => self.const_uint(0)?,
_ => return Ok(false),
};
let label_id = self.label_id(label)?;
@@ -688,6 +766,12 @@ impl Emitter {
self.record_phi_edge_instructions(predecessor, edge_instructions);
}
instructions.push(Self::inst(Op::Phi, Some(result_type), Some(result), ops));
if incoming
.iter()
.any(|(value, _)| matches!(value, LlValue::Zero))
{
self.emit_pointer_nullness_phi(name, incoming, result_ty, instructions)?;
}
self.pointer_storage
.insert(name.to_string(), llvm_pointer_storage(*addrspace)?);
self.pointer_pointees
+115 -123
View File
@@ -179,6 +179,81 @@ impl Emitter {
))
}
/// Emit `body` guarded by `condition`, as a structured `if` spliced into the instruction stream.
///
/// The selected-pointer stores below need this because a pointer `OpSelect`-then-store is illegal
/// under Logical addressing when the arms are distinct bindings, and the branch-free alternative
/// is not equivalent. That alternative loaded each arm, selected the new value against the old one
/// under the arm's condition, and stored the result back into EVERY arm. Storing a value back is
/// still a write: when two invocations reach the same byte of one buffer through DIFFERENT
/// selections, the one that did not select it overwrites the other's result with the pre-store
/// value. Apple's store is a single indirect store through the selected pointer and has no such
/// write, so the branch-free form is a data race the source does not have -- measured on the
/// device as a nondeterministic answer, three distinct outputs in four runs.
///
/// A guarded store has no write to un-write. The emitter's block list is a flat instruction
/// stream split at `OpLabel` (`emit_raw_store`'s bounds guard uses the same idiom), so this is a
/// well-formed selection construct even though CFG structurization has already run.
fn emit_guarded(
&mut self,
condition: Word,
instructions: &mut Vec<Instruction>,
body: impl FnOnce(&mut Self, &mut Vec<Instruction>) -> Result<(), String>,
) -> Result<(), String> {
let body_label = self.fresh();
let merge_label = self.fresh();
instructions.push(Self::inst(
Op::SelectionMerge,
None,
None,
vec![
Operand::IdRef(merge_label),
Operand::SelectionControl(SelectionControl::NONE),
],
));
instructions.push(Self::inst(
Op::BranchConditional,
None,
None,
vec![
Operand::IdRef(condition),
Operand::IdRef(body_label),
Operand::IdRef(merge_label),
],
));
instructions.push(Self::inst(Op::Label, None, Some(body_label), vec![]));
body(self, instructions)?;
instructions.push(Self::inst(
Op::Branch,
None,
None,
vec![Operand::IdRef(merge_label)],
));
instructions.push(Self::inst(Op::Label, None, Some(merge_label), vec![]));
Ok(())
}
/// `condition` when `when_true`, else its negation. The arm-selected predicate for a store guard.
fn store_arm_condition(
&mut self,
condition: Word,
when_true: bool,
instructions: &mut Vec<Instruction>,
) -> Result<Word, String> {
if when_true {
return Ok(condition);
}
let bool_ty = self.type_id(&LlType::Bool)?;
let negated = self.fresh();
instructions.push(Self::inst(
Op::LogicalNot,
Some(bool_ty),
Some(negated),
vec![Operand::IdRef(condition)],
));
Ok(negated)
}
/// Store `object` THROUGH a direct pointer select (`selected_pointers`), the write-side analog of
/// [`emit_selected_pointer_direct_load`]. A pointer `OpSelect`-then-store is illegal under Logical
/// addressing when the arms can point into distinct buffers, and there is no value-level "store to
@@ -235,46 +310,25 @@ impl Emitter {
"native emitter: selected store type mismatch {pointee:?} vs {object_ty:?}"
));
}
let object_type = self.type_id(&object_ty)?;
// The SELECTED arm receives the new value; the other arm is written back unchanged. `cond` true
// selects the true arm, so the true arm stores `select(cond, object, old)` and the false arm
// stores `select(cond, old, object)`.
for (value, take_object_when_true) in
// Only the SELECTED arm is written, each store under its own guard. `cond` true selects the
// true arm. See [`Self::emit_guarded`] for why writing both arms is not an option.
for (value, selected_when_true) in
[(&selected.true_value, true), (&selected.false_value, false)]
{
if matches!(value, LlValue::Zero) {
continue; // a null arm is UB to store through in the source; skip it.
}
let ptr = self.value_id(value, &selected.ty)?;
let old = self.fresh();
instructions.push(Self::inst(
Op::Load,
Some(object_type),
Some(old),
vec![Operand::IdRef(ptr)],
));
let merged = self.fresh();
let (t, f) = if take_object_when_true {
(object_id, old)
} else {
(old, object_id)
};
instructions.push(Self::inst(
Op::Select,
Some(object_type),
Some(merged),
vec![
Operand::IdRef(selected.cond),
Operand::IdRef(t),
Operand::IdRef(f),
],
));
instructions.push(Self::inst(
Op::Store,
None,
None,
vec![Operand::IdRef(ptr), Operand::IdRef(merged)],
));
let arm = self.store_arm_condition(selected.cond, selected_when_true, instructions)?;
self.emit_guarded(arm, instructions, |_, instructions| {
instructions.push(Self::inst(
Op::Store,
None,
None,
vec![Operand::IdRef(ptr), Operand::IdRef(object_id)],
));
Ok(())
})?;
}
Ok(())
}
@@ -497,48 +551,23 @@ impl Emitter {
"native emitter: selected access store has unsupported storage {storage:?}"
));
}
let object_type = self.type_id(object_ty)?;
let old = self.fresh();
instructions.push(Self::inst(
Op::Load,
Some(object_type),
Some(old),
vec![Operand::IdRef(*ptr)],
));
let value = self.fresh();
instructions.push(Self::inst(
Op::Select,
Some(object_type),
Some(value),
vec![
Operand::IdRef(condition),
Operand::IdRef(object),
Operand::IdRef(old),
],
));
instructions.push(Self::inst(
Op::Store,
None,
None,
vec![Operand::IdRef(*ptr), Operand::IdRef(value)],
));
Ok(())
let ptr = *ptr;
self.emit_guarded(condition, instructions, |_, instructions| {
instructions.push(Self::inst(
Op::Store,
None,
None,
vec![Operand::IdRef(ptr), Operand::IdRef(object)],
));
Ok(())
})
}
SelectedAccessArm::Raw(raw) => {
let old = self.fresh();
self.emit_raw_load(old, object_ty, raw, access_align, instructions)?;
let value = self.fresh();
instructions.push(Self::inst(
Op::Select,
Some(self.type_id(object_ty)?),
Some(value),
vec![
Operand::IdRef(condition),
Operand::IdRef(object),
Operand::IdRef(old),
],
));
self.emit_raw_store(object_ty, value, raw, access_align, instructions)
let raw = raw.clone();
let object_ty = object_ty.clone();
self.emit_guarded(condition, instructions, move |emitter, instructions| {
emitter.emit_raw_store(&object_ty, object, &raw, access_align, instructions)
})
}
SelectedAccessArm::Null => Ok(()),
}
@@ -697,55 +726,18 @@ impl Emitter {
let false_ptr = selected.false_ptr.ok_or_else(|| {
"native emitter: selected pointer store missing false arm".to_string()
})?;
let object_type = self.type_id(&object_ty)?;
let true_old = self.fresh();
instructions.push(Self::inst(
Op::Load,
Some(object_type),
Some(true_old),
vec![Operand::IdRef(true_ptr)],
));
let false_old = self.fresh();
instructions.push(Self::inst(
Op::Load,
Some(object_type),
Some(false_old),
vec![Operand::IdRef(false_ptr)],
));
let true_value = self.fresh();
instructions.push(Self::inst(
Op::Select,
Some(object_type),
Some(true_value),
vec![
Operand::IdRef(selected.cond),
Operand::IdRef(object),
Operand::IdRef(true_old),
],
));
let false_value = self.fresh();
instructions.push(Self::inst(
Op::Select,
Some(object_type),
Some(false_value),
vec![
Operand::IdRef(selected.cond),
Operand::IdRef(false_old),
Operand::IdRef(object),
],
));
instructions.push(Self::inst(
Op::Store,
None,
None,
vec![Operand::IdRef(true_ptr), Operand::IdRef(true_value)],
));
instructions.push(Self::inst(
Op::Store,
None,
None,
vec![Operand::IdRef(false_ptr), Operand::IdRef(false_value)],
));
for (ptr, selected_when_true) in [(true_ptr, true), (false_ptr, false)] {
let arm = self.store_arm_condition(selected.cond, selected_when_true, instructions)?;
self.emit_guarded(arm, instructions, |_, instructions| {
instructions.push(Self::inst(
Op::Store,
None,
None,
vec![Operand::IdRef(ptr), Operand::IdRef(object)],
));
Ok(())
})?;
}
Ok(())
}
+44 -8
View File
@@ -134,6 +134,7 @@ impl Emitter {
StorageClass::StorageBuffer
| StorageClass::UniformConstant
| StorageClass::Workgroup
| StorageClass::PhysicalStorageBuffer
)
});
if !can_select_pointer {
@@ -234,6 +235,24 @@ impl Emitter {
],
));
if let Some(meta) = pointer_meta {
// A pointer select with one null arm is null exactly when that arm is taken, and a
// later `icmp eq ptr, null` reads the answer out of `pointer_nullness`. Every OTHER
// route out of this function records it; this tail did not, because before physical
// pointers became selectable nothing with a null arm reached it -- the arms landed in
// an unmodelled placeholder, which records nullness on the way past. Two arms that are
// both null or both concrete carry no answer, and `selected_pointer_nullness_id`
// returns None for them, so nothing is recorded and nothing changes.
let selected = SelectedPointer {
ty: result_ty.clone(),
cond: cond_id,
true_value: true_value.value.clone(),
false_value: false_value.value.clone(),
};
if !self.pointer_nullness.contains_key(&name) {
if let Some(is_null) = self.selected_pointer_nullness_id(&selected, instructions)? {
self.record_pointer_nullness(name.clone(), is_null);
}
}
self.record_pointer_meta(name.clone(), meta);
}
if let Some(provenance) = pointer_provenance {
@@ -399,7 +418,7 @@ impl Emitter {
let Some(pointee) = meta.pointee.as_ref() else {
return self.value_id_in(value, ty, instructions);
};
match self.typed_null_or_undef_pointer_id(value, meta.storage, pointee)? {
match self.typed_null_or_undef_pointer_id(value, meta.storage, pointee, instructions)? {
Some(id) => Ok(id),
None => self.value_id_in(value, ty, instructions),
}
@@ -553,16 +572,33 @@ impl Emitter {
value: &LlValue,
storage: StorageClass,
pointee: &LlType,
instructions: &mut Vec<Instruction>,
) -> Result<Option<Word>, String> {
let op = match value {
LlValue::Zero | LlValue::Undef => Op::ConstantNull,
_ => return Ok(None),
};
if !matches!(value, LlValue::Zero | LlValue::Undef) {
return Ok(None);
}
let ptr_type = self.ptr_type_id(storage, pointee)?;
let id = self.fresh();
self.module
.types_global_values
.push(Self::inst(op, Some(ptr_type), Some(id), vec![]));
if storage == StorageClass::PhysicalStorageBuffer {
// A physical pointer has no null CONSTANT -- spirv-val: "OpConstantNull Result Type
// cannot have a null value" for a PhysicalStorageBuffer pointer. Its null is the
// address zero, which is an instruction, so it belongs in the body rather than the
// module's constant section.
let zero = self.const_signed_int(64, 0)?;
instructions.push(Self::inst(
Op::ConvertUToPtr,
Some(ptr_type),
Some(id),
vec![Operand::IdRef(zero)],
));
return Ok(Some(id));
}
self.module.types_global_values.push(Self::inst(
Op::ConstantNull,
Some(ptr_type),
Some(id),
vec![],
));
Ok(Some(id))
}
+19 -12
View File
@@ -550,21 +550,11 @@ impl Emitter {
},
LlValue::Int(value) => match self.resolve_type(ty)? {
LlType::Int(bits) => self.const_int(bits, *value),
LlType::Float if *value == 0 => self.const_float32(0.0),
LlType::Half if *value == 0 => self.const_float16_bits(0),
LlType::BFloat if *value == 0 => self.const_int(16, 0),
other => Err(format!(
"native emitter: integer literal {value} used as non-int type {other:?}"
)),
other => self.int_literal_bits_as_float(*value, &other),
},
LlValue::SignedInt(value) => match self.resolve_type(ty)? {
LlType::Int(bits) => self.const_signed_int(bits, *value),
LlType::Float if *value == 0 => self.const_float32(0.0),
LlType::Half if *value == 0 => self.const_float16_bits(0),
LlType::BFloat if *value == 0 => self.const_int(16, 0),
other => Err(format!(
"native emitter: integer literal {value} used as non-int type {other:?}"
)),
other => self.int_literal_bits_as_float(*value as u64, &other),
},
LlValue::Hex(bits) => match self.resolve_type(ty)? {
LlType::Int(width) => self.const_int(width, *bits),
@@ -1052,6 +1042,23 @@ impl Emitter {
}
}
/// Materializes an integer literal that lands in a floating-point slot.
///
/// AIR reaches this shape by punning a pointer: a function-constant initializer declares
/// `global i16`, the static initializer stores the supplied integer into it, and the entry
/// point spells `load half` from the same global. LLVM reads that as a reinterpretation of
/// the stored bytes, not as a numeric conversion, so the literal carries a bit pattern.
fn int_literal_bits_as_float(&mut self, value: u64, ty: &LlType) -> Result<Word, String> {
match ty {
LlType::Float => self.const_float32_bits(value as u32),
LlType::Half => self.const_float16_bits(value as u16),
LlType::BFloat => self.const_int(16, value & 0xffff),
other => Err(format!(
"native emitter: integer literal {value} used as non-int type {other:?}"
)),
}
}
pub(super) fn const_float32(&mut self, value: f32) -> Result<Word, String> {
self.const_float32_bits(value.to_bits())
}
+32 -5
View File
@@ -1,8 +1,35 @@
//! AIR imageblock execution-model constants.
/// Maximum number of coordinate-addressable imageblock cells in the current compute contract.
/// The most threads a threadgroup can have, which is how many cells a tile has per cell scale.
///
/// This matches the translator's existing 512-element threadgroup-memory interface contract and
/// covers every supported `kernel_local_size` shape. Cross-coordinate imageblock lowering allocates
/// one metadata-typed cell per slot and uses the decoded `threads_per_threadgroup.x` as row stride.
pub(super) const CELL_CAPACITY: u32 = 512;
/// A threadgroup holds at most 1024 threads on every Apple GPU -- `maxTotalThreadsPerThreadgroup`.
/// An entry that stages one cell per thread therefore cannot address a 1025th cell, and one that
/// stages a `k`x`k` block per thread (`imageblock_cell_scale`) cannot address past `k * k` times
/// that.
const MAX_THREADS_PER_THREADGROUP: u32 = 1024;
/// The threadgroup-memory budget those cells may occupy.
///
/// Vulkan guarantees `maxComputeSharedMemorySize >= 16384`, so this is the largest tile allocation
/// that is portable to every conformant device. A cell wide enough that 1024 of them would not fit
/// gets however many do.
const TILE_BYTE_BUDGET: u32 = 16384;
/// How many coordinate-addressable cells the shared-tile lowering allocates for a `cell_bytes`-wide
/// cell in a tile that is `cell_scale` cells per thread in each axis.
///
/// This used to be a flat 512, a number that answered neither question: it is below the thread count
/// a tile can have, so it refused five corpus modules whose 8-byte cells name a 32x32 block, and it
/// is stated in cells, so what it costs in threadgroup memory depended on a cell width it never
/// looked at. Both bounds here are external facts about the two APIs rather than a chosen size.
///
/// A cell is never zero bytes in practice; treat a degenerate one as a single byte rather than
/// dividing by zero, and always leave room for the one cell the smallest tile has. A scale wide
/// enough to overflow the thread bound is one the byte budget would have cut long before, so
/// saturate rather than refuse here.
pub(super) fn cell_capacity(cell_bytes: u32, cell_scale: u32) -> u32 {
MAX_THREADS_PER_THREADGROUP
.saturating_mul(cell_scale.saturating_mul(cell_scale))
.min(TILE_BYTE_BUDGET / cell_bytes.max(1))
.max(1)
}
+28
View File
@@ -171,6 +171,34 @@ pub(super) fn inline_pointer_select_consumers(
}
}
/// Splice the named helper calls into their callers so no descriptor-relative byte cursor has to
/// cross a SPIR-V function boundary. Each site is `(callee, the caller-local name of the argument
/// that carries the cursor)`; the argument name selects the exact call, so a helper called with a
/// plain buffer root elsewhere keeps that call site and its body.
///
/// Returns `None` when nothing could be spliced -- a caller uses this only after an emission that
/// already failed, so leaving the source alone simply preserves that failure.
pub(super) fn inline_cursor_call_sites(
san_ll: &str,
sites: &HashSet<(String, String)>,
) -> Option<String> {
let mut ordered = sites.iter().collect::<Vec<_>>();
ordered.sort();
let mut source = san_ll.to_string();
let mut changed = false;
for (callee, argument) in ordered {
// The typed IR names a callee bare; every name in the AIR text keeps its `@` sigil.
let targets = HashSet::from([format!("@{}", callee.trim_start_matches('@'))]);
// No caller filter: the cursor may be built in a helper rather than the entry, and an
// argument name that also occurs in an unrelated caller only inlines one more call.
if let Some(inlined) = try_inline(&source, Some((&targets, argument.as_str(), None))) {
changed |= inlined != source;
source = inlined;
}
}
changed.then_some(source)
}
// ---------------------------------------------------------------------------------------------
// Module model
// ---------------------------------------------------------------------------------------------
+280 -12
View File
@@ -151,6 +151,12 @@ impl LlFunction {
}
}
/// The AIR intrinsic that answers the imageblock (= threadgroup) tile width. Declared into the IR
/// when a cross-coordinate imageblock has no stride of its own, and lowered in the pass layer by
/// `lower_get_imageblock_extent`, which is the only place that holds
/// `TransformOptions::kernel_local_size`.
pub(super) const IMAGEBLOCK_WIDTH_INTRINSIC: &str = "air.get_imageblock_width";
#[derive(Clone, Debug)]
pub(super) struct LlDeclaration {
pub(super) name: String,
@@ -202,6 +208,14 @@ pub(super) struct LlModule {
/// AIR entry parameter carrying `[[threads_per_threadgroup]]`, used as the row stride for a
/// shared imageblock whose dimensions are supplied by the dispatch rather than APV metadata.
pub(super) imageblock_threads_per_threadgroup_param: Option<String>,
/// How many imageblock cells wide the tile is per thread in each axis: `1` when every
/// `air.imageblock_data` coordinate names the calling thread's own cell, `k` when the entry
/// stages a `k`x`k` block per thread, and `None` when the entry has no one such factor and the
/// shared-cell lowering cannot linearise it. See [`infer_imageblock_cell_scale`].
pub(super) imageblock_cell_scale: Option<u32>,
/// The render-target planes an `air.alias_implicit_imageblock` explicit imageblock's members
/// alias, in member order. Empty for the ordinary tile-local imageblock.
pub(super) aliased_imageblock_planes: Vec<meta::AliasedImageblockPlane>,
metadata_pointee_params: HashSet<(String, String)>,
/// For each metadata-seeded pointee param, the buffer element's declared `air.arg_type_size`
/// (the authoritative byte extent, offset-aware over any union/bitfield tail). Used to let a
@@ -593,6 +607,215 @@ fn infer_metadata_primitive_buffer_pointees(
out
}
/// Whether the entry copies a whole imageblock block to a texture.
///
/// `air.write_imageblock_slice_to_texture_*` hands the texture a WxH block of cells starting at the
/// one its pointer names -- the Metal `imageblock_slice` carries the pointer, a size and a validity
/// flag, and nothing else, so the pointer IS the block origin. Per-invocation `Private` staging has
/// exactly one cell, so a module that makes this call cannot be staging per invocation: the cells
/// the call reads past the first belong to other threads, and in the corpus the call is routinely
/// made by one gated thread on behalf of the whole threadgroup. Naming the call is therefore a
/// direct statement that the imageblock is threadgroup memory, independent of whether the module
/// happens to address a second coordinate.
fn calls_imageblock_slice_write(
functions: &[LlFunction],
entry_functions: &HashSet<String>,
) -> bool {
functions
.iter()
.filter(|function| entry_functions.contains(&function.name))
.flat_map(|function| function.carrier_insts())
.filter_map(|inst| inst.alias_call())
.any(|call| {
call.callee
.starts_with("air.write_imageblock_slice_to_texture")
})
}
/// How many imageblock cells wide the tile is per thread, or `None` when this entry has no such
/// factor and the shared-cell lowering must refuse it.
///
/// The shared-cell lowering linearises the tile `y * width + x` with `width` the threadgroup extent
/// (`emit_imageblock_threadgroup_width`), which is the imageblock's extent only when each thread
/// owns one cell. A kernel that stages a 2x2 output block per thread addresses `2 * tid + {0,1}^2`,
/// so its imageblock is twice as wide in each axis -- `rwppCopyImage` states as much, passing an
/// explicit slice-write region of `2 * [[threads_per_threadgroup]]`. That factor is not a caller
/// fact: the module carries it, both as the multiply on the coordinate and as the region operand.
/// So read it off the coordinate and hand it to the emitter, which multiplies the row stride and
/// the cell count by it.
///
/// **The factor is a linear coefficient in the thread position, and the tile is as wide as the
/// LARGEST one.** `tid + (1, 0)` is a neighbour read, which is what tile memory is for, and adding
/// a constant does not widen anything -- coefficient 1. `2 * tid` says the tile has twice as many
/// columns as there are threads -- coefficient 2. A wholly constant coordinate has coefficient 0.
/// Coefficients may differ within one entry and routinely do: `rwppCopyImage` stages its 2x2 block
/// at `2 * tid | {0,1}^2` and then names the block origin as plain `tid` under a gate that proves
/// the position zero. Taking the maximum is not a compromise -- a coordinate with coefficient `j`
/// spans `[0, j * threads)`, which is inside `[0, k * threads)` for every `j <= k`, so linearising
/// every coordinate by the widest one is exactly right for all of them. It is UNDER-stating the
/// width that collides two cells, which is why `add` sums its operands' coefficients rather than
/// taking their maximum.
fn infer_imageblock_cell_scale(
functions: &[LlFunction],
entry_functions: &HashSet<String>,
) -> Option<u32> {
let mut scale = 0;
for function in functions
.iter()
.filter(|function| entry_functions.contains(&function.name))
{
let defs = function
.carrier_insts()
.filter_map(|inst| inst.result.as_deref().map(|result| (result, inst)))
.collect::<HashMap<_, _>>();
for coordinate in function
.carrier_insts()
.filter_map(|inst| inst.alias_call())
.filter(|call| call.callee == "air.imageblock_data")
.filter_map(|call| call.args.first().map(|arg| arg.value.clone()))
{
let coordinate_scale = match coordinate {
LlValue::Local(name) => tile_coordinate_scale(&defs, &name, 16)?,
// A literal coordinate names one fixed cell and widens nothing.
_ => 0,
};
scale = scale.max(coordinate_scale);
}
}
// Every coordinate constant: one cell per thread is as true as it ever was.
Some(scale.max(1))
}
/// The coefficient of the thread position in `name`, or `None` when it is not a linear function of
/// one.
///
/// `0` means the value does not depend on a thread position at all. A name this function cannot see
/// a definition for is a parameter or a global -- a thread position, coefficient 1. Multiplying by a
/// constant multiplies the coefficient and adding two values adds theirs, which is what makes
/// `2 * tid + 1` come out as 2 rather than as 2 and 1 separately.
///
/// Everything else -- `x >> n`, `x & m`, `x % m` -- is not linear, but each of them is bounded above
/// by `x`, so a coordinate built that way out of an UNSCALED position still lands inside the tile
/// and keeps the coefficient it had. Applied to a scaled one the bound says nothing about which cell
/// it names, so that combination is refused rather than guessed.
fn tile_coordinate_scale(
defs: &HashMap<&str, &crate::native::tir::TirInst>,
name: &str,
depth: u32,
) -> Option<u32> {
if depth == 0 {
return None;
}
// Not defined in this function: a parameter or a global, which is a thread position itself.
let Some(inst) = defs.get(name) else {
return Some(1);
};
// A value no thread position reaches is an offset, however it is computed. Asking this before
// recursing is also what keeps a loop-carried offset from spinning: the `{0,1}^2` corner of a
// per-thread block arrives through a phi that names its own increment, which no depth-limited
// linear walk terminates on, and which contributes nothing to the width either way.
if !reaches_thread_position(defs, name, &mut HashSet::new()) {
return Some(0);
}
use crate::native::tir::TirOpcode;
let operand_scale = |operand: &crate::native::tir::TirOperand| match operand {
crate::native::tir::TirOperand::Value { name, .. } => {
tile_coordinate_scale(defs, name, depth - 1)
}
crate::native::tir::TirOperand::Const { .. } => Some(0),
crate::native::tir::TirOperand::Unresolved => None,
};
match inst.opcode {
TirOpcode::Shl | TirOpcode::Mul => {
let [lhs, rhs] = inst.operands.as_slice() else {
return None;
};
// Exactly one side constant, or the product is not a scale of a position.
let (value, factor) = match (constant_uniform_int(lhs), constant_uniform_int(rhs)) {
(None, Some(factor)) => (lhs, factor),
(Some(factor), None) if inst.opcode == TirOpcode::Mul => (rhs, factor),
_ => return None,
};
let factor = if inst.opcode == TirOpcode::Shl {
1u32.checked_shl(u32::try_from(factor).ok()?)?
} else {
u32::try_from(factor).ok()?
};
operand_scale(value)?.checked_mul(factor)
}
TirOpcode::Add | TirOpcode::Or | TirOpcode::Sub => {
let [lhs, rhs] = inst.operands.as_slice() else {
return None;
};
operand_scale(lhs)?.checked_add(operand_scale(rhs)?)
}
_ => {
// Not linear, so it may only narrow a position that was never scaled.
let mut scale = Some(0);
inst.visit_uses(|use_name| {
scale = match (scale, tile_coordinate_scale(defs, use_name, depth - 1)) {
(Some(0), Some(1)) | (Some(1), Some(1)) => Some(1),
(Some(0), Some(0)) => Some(0),
_ => None,
};
});
scale
}
}
}
/// Whether any thread position reaches `name`.
///
/// A name with no definition in this entry is a parameter or a global, and the entry's imageblock
/// coordinates are built out of its `[[thread_position_*]]` parameters, so an undefined name is the
/// thread position. Everything else is reachability, with a visited set so a loop-carried value that
/// names its own increment terminates.
fn reaches_thread_position<'a>(
defs: &HashMap<&'a str, &'a crate::native::tir::TirInst>,
name: &'a str,
visited: &mut HashSet<&'a str>,
) -> bool {
if !visited.insert(name) {
return false;
}
let Some(inst) = defs.get(name) else {
return true;
};
let mut reaches = false;
inst.visit_uses(|use_name| {
// `visit_uses` hands out borrows of the instruction's own strings; the definition map keys
// are borrows of the same arena, so look each one up to recover the longer lifetime.
if let Some((interned, _)) = defs.get_key_value(use_name) {
reaches |= reaches_thread_position(defs, interned, visited);
} else {
reaches = true;
}
});
reaches
}
/// A constant integer operand, or the element of a constant splat/uniform vector one.
fn constant_uniform_int(operand: &crate::native::tir::TirOperand) -> Option<u64> {
let crate::native::tir::TirOperand::Const { value, .. } = operand else {
return None;
};
fn scalar(value: &LlValue) -> Option<u64> {
match value {
LlValue::Int(value) | LlValue::Hex(value) => Some(*value),
LlValue::SignedInt(value) => u64::try_from(*value).ok(),
LlValue::Zero => Some(0),
LlValue::Splat(element) => scalar(&element.value),
LlValue::Vector(elements) => {
let mut lanes = elements.iter().map(|element| scalar(&element.value));
let first = lanes.next()??;
lanes.all(|lane| lane == Some(first)).then_some(first)
}
_ => None,
}
}
scalar(value)
}
fn infer_cross_coordinate_imageblock(
functions: &[LlFunction],
entry_functions: &HashSet<String>,
@@ -986,11 +1209,24 @@ mod layout_abi_tests {
m.native_memcpy_type_size_align(&LlType::Array(Box::new(vec(LlType::Float, 3)), 2)),
Some((32, 16))
);
// array of scalars floors align at 4
// an array takes its element's alignment, not a four-byte floor: `packed_half3` is the
// six bytes AIR declares, and a byte pad stays where the packed struct put it.
assert_eq!(
m.native_memcpy_type_size_align(&LlType::Array(Box::new(LlType::Float), 3)),
Some((12, 4))
);
assert_eq!(
m.native_memcpy_type_size_align(&LlType::Array(Box::new(LlType::Half), 3)),
Some((6, 2))
);
assert_eq!(
m.native_memcpy_type_size_align(&LlType::Struct(vec![
LlType::Int(8),
LlType::Array(Box::new(LlType::Int(8)), 3),
LlType::Int(32),
])),
Some((8, 4))
);
}
#[test]
@@ -1066,20 +1302,34 @@ mod layout_abi_tests {
]);
assert!(m.air_metadata_requires_byte_view(&overlapping));
let stride_overlap = AirType::Struct(vec![
// `{ ushort @0, uchar @12 }` is 13 bytes of members aligned to 2, so it is 14 and an array
// of two is 28. MEASURED against the Metal front end rather than assumed: a kernel over
// `struct Inner { ushort a; uchar pad[10]; uchar b; }` reports `sizeof` 14, `alignof` 2,
// `&arr[1] - &arr[0]` 14, and for `struct Outer { Inner arr[2]; uint c; }` an `offsetof(c)`
// of 28 and a `sizeof` of 32.
//
// So 28 is where the next member goes and there is nothing to overlap. This fixture used to
// put the `uint` at 28 and assert a byte view WAS required, which was true only because a
// four-byte alignment floor rounded the inner struct to 16 and the array to 32 -- the same
// floor `ffdde3cc` removed from the emitted addresses. A fabricated overlap costs a whole
// buffer its typed access chains, so both directions are pinned here.
let inner = || {
AirType::Struct(vec![
AirMember {
offset: 0,
ty: AirType::Scalar(AirScalar::UShort),
},
AirMember {
offset: 12,
ty: AirType::Scalar(AirScalar::UChar),
},
])
};
let stride_adjacent = AirType::Struct(vec![
AirMember {
offset: 0,
ty: AirType::Array {
elem: Box::new(AirType::Struct(vec![
AirMember {
offset: 0,
ty: AirType::Scalar(AirScalar::UShort),
},
AirMember {
offset: 12,
ty: AirType::Scalar(AirScalar::UChar),
},
])),
elem: Box::new(inner()),
len: 2,
},
},
@@ -1088,6 +1338,23 @@ mod layout_abi_tests {
ty: AirType::Scalar(AirScalar::UInt),
},
]);
assert!(!m.air_metadata_requires_byte_view(&stride_adjacent));
// The genuine version of the same shape: the `uint` starts at 20, inside the array's real
// extent of [0, 28), so the members really do overlap and the byte view really is required.
let stride_overlap = AirType::Struct(vec![
AirMember {
offset: 0,
ty: AirType::Array {
elem: Box::new(inner()),
len: 2,
},
},
AirMember {
offset: 20,
ty: AirType::Scalar(AirScalar::UInt),
},
]);
assert!(m.air_metadata_requires_byte_view(&stride_overlap));
let adjacent = AirType::Struct(vec![
@@ -1117,6 +1384,7 @@ mod layout_abi_tests {
LlType::Float,
LlType::Ptr(1),
LlType::Array(Box::new(LlType::Float), 3),
LlType::Array(Box::new(LlType::Half), 3),
LlType::Struct(vec![LlType::Int(8), LlType::Float]),
LlType::Struct(vec![LlType::Float, LlType::Float, LlType::Int(32)]),
];
+55 -2
View File
@@ -57,6 +57,14 @@ impl LlModule {
let (name, body) = line
.split_once(" = type ")
.ok_or_else(|| format!("native emitter: malformed type alias: {line}"))?;
// `%struct._texture_2d_t = type opaque` declares a name whose body LLVM itself
// does not know -- Metal's texture and sampler handles. Leaving it out of the
// table is what keeps it opaque here too: a pointer to it still parses (the
// pointee is dropped), and anything that reaches for the body gets an honest
// "unknown named type" instead of a body we invented.
if body.trim() == "opaque" {
continue;
}
types.insert(name.trim().to_string(), parse_type(body.trim())?);
}
}
@@ -138,8 +146,51 @@ impl LlModule {
.and_then(|function| function.params.get(index))
.map(|(name, _)| name.clone())
});
let imageblock_shared_cells =
cross_coordinate_imageblock && imageblock_threads_per_threadgroup_param.is_some();
// Whether the tile is shared is a property of the AIR, not of the stride the emitter can
// reach for. Conjoining the `[[threads_per_threadgroup]]` parameter here answered "is this
// imageblock shared?" with "can I linearize it?", and a kernel that addresses a second
// coordinate without that parameter fell through to per-invocation Private staging, where
// every coordinate resolves to the same private slot. `emit_imageblock_threadgroup_width`
// already refuses the missing stride; let it.
// An `air.alias_implicit_imageblock` explicit imageblock is not tile-local scratch at all:
// its storage IS the implicit imageblock, so each cell is one render-target texel and the
// tile is shared with whatever rasterized into it. Per-invocation staging, where every
// coordinate resolves to one Private slot, cannot represent that however few coordinates
// the entry happens to name -- so an aliased block takes the shared-cell path
// unconditionally, and `aliased_imageblock` fills its cells from the planes and writes
// them back.
let aliased_imageblock_planes = kern
.and_then(|meta| {
meta.aliased_implicit_imageblock_params
.first()
.and_then(|param| meta.aliased_implicit_imageblock_planes.get(param))
})
.cloned()
.unwrap_or_default();
let imageblock_shared_cells = cross_coordinate_imageblock
|| !aliased_imageblock_planes.is_empty()
|| calls_imageblock_slice_write(&functions, &entry_functions);
let imageblock_cell_scale = infer_imageblock_cell_scale(&functions, &entry_functions);
// A shared tile is linearised `y * width + x`, and nothing in AIR states that width: it is
// the threadgroup extent, a dispatch-time fact. A kernel that takes
// `[[threads_per_threadgroup]]` hands it to us directly; one that does not used to leave
// the emitter with no stride at all. But the pass layer already answers
// `air.get_imageblock_width` with `TransformOptions::kernel_local_size` -- the same number,
// from the one place that knows it. Declare that intrinsic so the emitter can ask the
// question instead of inventing a second derivation of the tile extent.
if imageblock_shared_cells
&& imageblock_dimensions.is_none()
&& imageblock_threads_per_threadgroup_param.is_none()
&& !declarations
.iter()
.any(|declaration| declaration.name == IMAGEBLOCK_WIDTH_INTRINSIC)
{
declarations.push(LlDeclaration {
name: IMAGEBLOCK_WIDTH_INTRINSIC.to_string(),
ret: LlType::Int(32),
params: Vec::new(),
});
}
// Private imageblock scratch normally keeps only its first metadata member, because a
// single-coordinate slice never addresses another field. A byte GEP rooted at
// `air.imageblock_data` proves that this module does address a later field, though; retain
@@ -170,7 +221,9 @@ impl LlModule {
imageblock_data_pointee,
imageblock_dimensions,
imageblock_shared_cells,
aliased_imageblock_planes,
imageblock_threads_per_threadgroup_param,
imageblock_cell_scale,
metadata_pointee_params: HashSet::new(),
metadata_pointee_sizes: HashMap::new(),
metadata_byte_buffer_params,
+200 -51
View File
@@ -25,7 +25,16 @@ impl LlModule {
.map(|(param, _ty)| param.clone())
.collect::<HashSet<_>>();
let mut pointer_select_arms: HashMap<String, Vec<String>> = HashMap::new();
// A `bitcast ptr %p to ptr` denotes the same address, so a select arm spelled as one is
// the arm's base for every purpose the walk below has. Without this the walk stops at
// the alias and the underlying parameter never receives the merged GEP's element type,
// leaving the two arms of one merge typed at different widths.
let mut pointer_identity_aliases: HashMap<String, String> = HashMap::new();
for inst in f.carrier_insts() {
if let Some((result, base)) = inst.identity_ptr_bitcast() {
pointer_identity_aliases.insert(result.to_string(), base.to_string());
continue;
}
let Some(result) = &inst.result else {
continue;
};
@@ -46,11 +55,42 @@ impl LlModule {
.insert(result.clone(), vec![true_name.clone(), false_name.clone()]);
}
// The parameters a MERGE denotes: every arm that is one, descending through nested
// merges and through the identity bitcasts an arm may be spelled as. Deliberately not
// applied to a pointer that is itself an alias -- following a bitcast as a general
// GEP-base rule retypes buffers whose byte view is intentional, and regresses 13 of
// the 14,579 corpus sources. Through a merge the arms have to agree, so it is safe.
let merge_arm_params = |arms: &[String]| -> Vec<String> {
let mut pending = arms.to_vec();
let mut visited = HashSet::new();
let mut roots = Vec::new();
while let Some(arm) = pending.pop() {
if !visited.insert(arm.clone()) {
continue;
}
if params.contains(&arm) {
roots.push(arm);
} else if let Some(nested) = pointer_select_arms.get(&arm) {
pending.extend(nested.iter().cloned());
} else if let Some(base) = pointer_identity_aliases.get(&arm) {
pending.push(base.clone());
}
}
roots
};
for inst in f.carrier_insts() {
if let Some(gep) = &inst.gep() {
if let LlValue::Local(name) = &gep.base.value {
let mut voters = Vec::new();
if params.contains(name) {
let key = (f.name.clone(), name.clone());
voters.push(name.clone());
}
if let Some(arms) = pointer_select_arms.get(name) {
voters.extend(merge_arm_params(arms));
}
for voter in voters {
let key = (f.name.clone(), voter);
if self.gep_source_should_override(&key, &gep.source_ty) {
self.metadata_pointee_params.remove(&key);
self.ptr_pointees.insert(key, gep.source_ty.clone());
@@ -60,28 +100,6 @@ impl LlModule {
.or_insert_with(|| gep.source_ty.clone());
}
}
if let Some(arms) = pointer_select_arms.get(name) {
let mut pending = arms.clone();
let mut visited = HashSet::new();
while let Some(arm) = pending.pop() {
if !visited.insert(arm.clone()) {
continue;
}
if params.contains(&arm) {
let key = (f.name.clone(), arm);
if self.gep_source_should_override(&key, &gep.source_ty) {
self.metadata_pointee_params.remove(&key);
self.ptr_pointees.insert(key, gep.source_ty.clone());
} else {
self.ptr_pointees
.entry(key)
.or_insert_with(|| gep.source_ty.clone());
}
} else if let Some(nested) = pointer_select_arms.get(&arm) {
pending.extend(nested.iter().cloned());
}
}
}
}
continue;
}
@@ -135,6 +153,25 @@ impl LlModule {
}
}
// `air.simdgroup_matrix_8x8_{load,store}` dereferences its pointer operand as
// a row-major block of the MATRIX ELEMENT type -- the mangled suffix says so
// twice (`...load.v64f32.p1f32`) and the SSA types agree. It is the only
// dereference some buffers have: `simdgroup_load(m, buf, 8)` against a bare
// `device const float *` parameter never GEPs, so without this the parameter
// keeps the raw word view and `lower_simdgroup_matrix_8x8_load` refuses it for
// an integer pointee where the matrix element is a float. The same load spelled
// `&buf[i]` types itself on the way and always worked. Dispatching on the stable
// `air.simdgroup_matrix_*` intrinsic name is the AIR/LLVM-ABI exception the
// project allows, the same one the atomic pointee inference takes.
if let Some((element, pointers)) = simdgroup_matrix_block_element(inst) {
let element = self.resolve_known_type(&element);
for pointer in pointers {
if let Some(root) = roots.get(&pointer).cloned() {
sources.entry(root).or_default().insert(element.clone());
}
}
}
let Some(res) = &inst.result else {
continue;
};
@@ -317,15 +354,32 @@ impl LlModule {
metadata_size == candidate_size
}
/// Recover a buffer parameter's pointee from the alloca'd pointer table Metal entry points
/// park their buffers in. A parameter whose only direct use is `store %param, %slot` carries
/// no type evidence of its own; the evidence is at the load site, and getting it back means
/// deciding which stored parameter a given load names.
///
/// A slot is keyed by the alloca that roots it plus the chain of `(source type, indices)`
/// steps that reach it, so two different `getelementptr` instructions addressing the same
/// field agree -- which is the usual shape, since the store and the load are written
/// separately. A step whose index is not a constant makes the slot statically unknown, and
/// then a load through it may name any parameter stored anywhere in that table, so the type
/// goes to all of them; that union is sound only because the alternative is silence.
///
/// Keying by the store instruction's SSA name instead sends every constant-slot load into
/// that union as well, and four differently-typed buffers come out sharing one pointee -- the
/// emitter then types every descriptor after whichever buffer the loads happened to name.
pub(in crate::native) fn infer_local_pointer_table_param_pointees(
&self,
f: &LlFunction,
pointer_params: &HashSet<String>,
) -> HashMap<String, HashSet<LlType>> {
let mut table_roots: HashMap<String, String> = HashMap::new();
type Path = Vec<(LlType, Vec<u64>)>;
type Slot = (String, Path);
// `None` marks a pointer into the table whose slot a non-constant index made unknown.
let mut table_slots: HashMap<String, (String, Option<Path>)> = HashMap::new();
let mut slot_params: HashMap<Slot, HashSet<String>> = HashMap::new();
let mut table_params: HashMap<String, HashSet<String>> = HashMap::new();
let mut field_params: HashMap<String, HashSet<String>> = HashMap::new();
let mut loaded_tables: HashMap<String, String> = HashMap::new();
let mut loaded_params: HashMap<String, HashSet<String>> = HashMap::new();
let mut sources: HashMap<String, HashSet<LlType>> = HashMap::new();
@@ -333,13 +387,13 @@ impl LlModule {
if let Some(res) = &inst.result {
if let Some(ty) = &inst.alloca_ty() {
if self.type_contains_pointer(ty) {
table_roots.insert(res.clone(), res.clone());
table_slots.insert(res.clone(), (res.clone(), Some(Vec::new())));
}
continue;
}
if let Some((bres, base)) = inst.identity_ptr_bitcast() {
if let Some(root) = table_roots.get(base).cloned() {
table_roots.insert(bres.to_string(), root);
if let Some(slot) = table_slots.get(base).cloned() {
table_slots.insert(bres.to_string(), slot);
}
continue;
}
@@ -347,8 +401,20 @@ impl LlModule {
let LlValue::Local(base) = &gep.base.value else {
continue;
};
if let Some(root) = table_roots.get(base).cloned() {
table_roots.insert(res.clone(), root);
if let Some((root, path)) = table_slots.get(base).cloned() {
let indices = gep
.indices
.iter()
.map(typed_value_u64)
.collect::<Option<Vec<_>>>();
let path = match (path, indices) {
(Some(mut path), Some(indices)) => {
path.push((self.resolve_known_type(&gep.source_ty), indices));
Some(path)
}
_ => None,
};
table_slots.insert(res.clone(), (root, path));
} else if let Some(params) = loaded_params.get(base) {
for param in params {
sources
@@ -356,15 +422,6 @@ impl LlModule {
.or_default()
.insert(self.resolve_known_type(&gep.source_ty));
}
} else if let Some(root) = loaded_tables.get(base) {
if let Some(params) = table_params.get(root) {
for param in params {
sources
.entry(param.clone())
.or_default()
.insert(self.resolve_known_type(&gep.source_ty));
}
}
}
continue;
}
@@ -375,10 +432,15 @@ impl LlModule {
let LlValue::Local(ptr_name) = &load.ptr.value else {
continue;
};
if let Some(params) = field_params.get(ptr_name).cloned() {
loaded_params.insert(res.clone(), params);
} else if let Some(root) = table_roots.get(ptr_name).cloned() {
loaded_tables.insert(res.clone(), root);
let Some((root, path)) = table_slots.get(ptr_name) else {
continue;
};
let params = match path {
Some(path) => slot_params.get(&(root.clone(), path.clone())),
None => table_params.get(root),
};
if let Some(params) = params {
loaded_params.insert(res.clone(), params.clone());
}
}
continue;
@@ -396,13 +458,16 @@ impl LlModule {
let LlValue::Local(ptr_name) = &ptr.value else {
continue;
};
if let Some(root) = table_roots.get(ptr_name) {
table_params
.entry(root.clone())
.or_default()
.insert(param.clone());
field_params
.entry(ptr_name.clone())
let Some((root, path)) = table_slots.get(ptr_name).cloned() else {
continue;
};
table_params
.entry(root.clone())
.or_default()
.insert(param.clone());
if let Some(path) = path {
slot_params
.entry((root, path))
.or_default()
.insert(param.clone());
}
@@ -412,10 +477,94 @@ impl LlModule {
}
}
/// `(matrix element type, pointer operand names)` for an `air.simdgroup_matrix_8x8_{load,store}`
/// call, or `None` for anything else. The matrix is a 64-lane composite of one element type: read
/// it off the call's result for the value-returning `load`, or off the first non-pointer argument
/// for the void `store`, whose matrix operand precedes both its pointer and its three `<2 x i64>`
/// descriptor vectors.
fn simdgroup_matrix_block_element(
inst: &crate::native::tir::TirInst,
) -> Option<(LlType, Vec<String>)> {
let call = inst.call();
let call = call.as_deref()?;
if !(call.callee.starts_with("air.simdgroup_matrix_8x8_load.")
|| call.callee.starts_with("air.simdgroup_matrix_8x8_store."))
{
return None;
}
let composite = match &inst.result_ty {
Some(ty) => ty.clone(),
None => call
.args
.iter()
.find(|arg| !matches!(arg.ty, LlType::Ptr(_)))?
.ty
.clone(),
};
let LlType::Vector(element, 64) = composite else {
return None;
};
let pointers = call
.args
.iter()
.filter_map(|arg| match (&arg.ty, &arg.value) {
(LlType::Ptr(_), LlValue::Local(name)) => Some(name.clone()),
_ => None,
})
.collect::<Vec<_>>();
(!pointers.is_empty()).then_some((*element, pointers))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_pointer_table_slot_types_only_the_parameter_stored_in_it() {
// Metal entry points park every buffer pointer in one alloca'd table and the callees read
// them back out, so a parameter whose only direct use is that store has no type evidence
// of its own. The store and the load address the slot with separate `getelementptr`
// instructions, so matching them by SSA name never fires; the whole-table fallback then
// hands the one type seen through any load to every parameter in the table. Here only
// `%first` is ever loaded, and `%second` must come away with nothing rather than with
// `%first`'s pointee.
let ll = r#"
%Holder = type { ptr addrspace(2), ptr addrspace(2) }
%Payload = type { [2 x <4 x float>] }
define void @k(ptr addrspace(2) %first, ptr addrspace(2) %second) {
entry:
%holder = alloca %Holder, align 8
%store0 = getelementptr inbounds %Holder, ptr %holder, i64 0, i32 0
store ptr addrspace(2) %first, ptr %store0, align 8
%store1 = getelementptr inbounds %Holder, ptr %holder, i64 0, i32 1
store ptr addrspace(2) %second, ptr %store1, align 8
%load0 = getelementptr inbounds %Holder, ptr %holder, i64 0, i32 0
%loaded = load ptr addrspace(2), ptr %load0, align 8
%element = getelementptr inbounds %Payload, ptr addrspace(2) %loaded, i64 0, i32 0, i64 1
%value = load <4 x float>, ptr addrspace(2) %element, align 16
ret void
}
"#;
let module = LlModule::parse(ll).expect("parse pointer table");
let payload = LlType::Struct(vec![LlType::Array(
Box::new(LlType::Vector(Box::new(LlType::Float), 4)),
2,
)]);
assert_eq!(
module
.ptr_pointees
.get(&("k".to_string(), "%first".to_string())),
Some(&payload)
);
assert_eq!(
module
.ptr_pointees
.get(&("k".to_string(), "%second".to_string())),
None
);
}
#[test]
fn local_pointer_field_access_replaces_equal_size_metadata_placeholder() {
let ll = r#"
+107 -1
View File
@@ -544,7 +544,13 @@ impl LlModule {
}
AirType::Struct(members) => {
let mut ranges = Vec::with_capacity(members.len());
let mut max_align = 4;
// No alignment floor, for the same reason as `spirv_size_align` (`ffdde3cc`): a
// struct's alignment is the largest alignment among its members. Here the number is
// not an address, it is the extent each member is rounded up to before the overlap
// test below -- so a floor inflates a nested member's end past the start of the next
// one and FABRICATES a union, and a fabricated union costs the whole buffer its
// typed access chains and puts it on the raw word view.
let mut max_align = 1;
let mut nested_overlap = false;
for member in members {
let (size, align, overlaps) =
@@ -731,6 +737,106 @@ impl LlModule {
}
}
/// Whether `function` reads or writes memory through its parameter `param`.
///
/// The emitter can hand a callee a `Private` zero placeholder for a pointer whose real
/// addressing it holds only in its own raw-cursor state. That is harmless when the callee never
/// touches the pointer, and a silent loss of every access when it does, so the refusal that
/// guards it needs this exact question rather than "is a placeholder passed".
///
/// Conservative in the safe direction: an alias path this does not model (a pointer that
/// escapes through a select, a phi, or a struct field) answers `false`, which keeps today's
/// behaviour rather than refusing a module on a guess. Pointer arguments handed on to another
/// bodied helper are followed, so a dereference one call deeper still counts.
pub(in crate::native) fn param_is_dereferenced(&self, function: &str, param: &str) -> bool {
let mut seen = HashSet::new();
self.param_is_dereferenced_seen(function, param, &mut seen)
}
fn param_is_dereferenced_seen(
&self,
function: &str,
param: &str,
seen: &mut HashSet<(String, String)>,
) -> bool {
if !seen.insert((function.to_string(), param.to_string())) {
return false;
}
let Some(f) = self.functions.iter().find(|f| f.name == function) else {
return false;
};
let mut aliases: HashSet<String> = HashSet::from([param.to_string()]);
let mut changed = true;
while changed {
changed = false;
for inst in f.carrier_insts() {
let Some(result) = inst.result.as_ref() else {
continue;
};
if aliases.contains(result) {
continue;
}
let derived = inst
.gep()
.as_deref()
.and_then(|gep| match &gep.base.value {
LlValue::Local(base) => Some(base.clone()),
_ => None,
})
.or_else(|| {
inst.identity_ptr_bitcast()
.map(|(_, base)| base.to_string())
})
.is_some_and(|base| aliases.contains(&base));
if derived {
aliases.insert(result.clone());
changed = true;
}
}
}
let names =
|value: &LlValue| matches!(value, LlValue::Local(name) if aliases.contains(name));
f.carrier_insts().any(|inst| {
if inst
.load()
.as_deref()
.is_some_and(|load| names(&load.ptr.value))
{
return true;
}
if inst
.store()
.as_deref()
.is_some_and(|(_, pointer)| names(&pointer.value))
{
return true;
}
let Some(call) = inst.call().as_deref() else {
return false;
};
let passed = call
.args
.iter()
.enumerate()
.filter(|(_, arg)| names(&arg.value))
.map(|(index, _)| index)
.collect::<Vec<_>>();
if passed.is_empty() {
return false;
}
// An `air.*`/`llvm.*` intrinsic taking the pointer is a memory access by definition;
// there is no body to walk and every such symbol that takes a pointer dereferences it.
let Some(callee) = self.functions.iter().find(|f| f.name == call.callee) else {
return true;
};
passed.into_iter().any(|index| {
callee.params.get(index).is_some_and(|(name, _)| {
self.param_is_dereferenced_seen(&callee.name.clone(), &name.clone(), seen)
})
})
})
}
pub(in crate::native) fn type_contains_pointer(&self, ty: &LlType) -> bool {
match ty {
LlType::Ptr(_) => true,
+29 -4
View File
@@ -4,6 +4,7 @@
//! function, typed parameters, and an aggregate/vector return. Retained-SPIR-V interface and
//! lowering passes consume that module.
mod air_text;
mod async_copy;
mod cfg;
// Differential test support for the control-flow constructors (test builds only).
@@ -12,7 +13,7 @@ mod cfg_testkit;
mod constfold;
// Read-only typed-SSA soundness / carrier-comparison / reject-census diagnostics (no emission path).
mod diagnostics;
mod dominators;
mod dynamic_memcpy;
mod emitter;
// Emitter entry points for the primary and structurally selected alternate representations.
mod emit_tiers;
@@ -42,7 +43,28 @@ mod tir;
use crate::spirv_module::Instruction;
use crate::spirv_module::Module;
use crate::spirv_module::Operand;
pub(crate) use async_copy::{lower_simdgroup_async_copy, lower_simdgroup_async_copy_owned};
/// The shared pre-emit AIR-text lowering: every representation that derives stage metadata or
/// emits from a module must observe the SAME program, so the passes that rewrite AIR text before
/// [`ir::LlModule::parse`] are composed here rather than chained at each call site. Both members
/// borrow their input when they find nothing to do, so an ordinary module allocates nothing.
pub(crate) fn lower_air_text(san_ll: &str) -> std::borrow::Cow<'_, str> {
match async_copy::lower_simdgroup_async_copy(san_ll) {
std::borrow::Cow::Borrowed(borrowed) => {
dynamic_memcpy::lower_dynamic_length_memcpy(borrowed)
}
std::borrow::Cow::Owned(owned) => {
std::borrow::Cow::Owned(dynamic_memcpy::lower_dynamic_length_memcpy_owned(owned))
}
}
}
/// Owned counterpart of [`lower_air_text`], for callers that can relinquish the source buffer so a
/// rewrite drops the superseded text before typed parsing begins.
pub(crate) fn lower_air_text_owned(san_ll: String) -> String {
dynamic_memcpy::lower_dynamic_length_memcpy_owned(async_copy::lower_simdgroup_async_copy_owned(
san_ll,
))
}
pub use diagnostics::{
cond_other_witness_report, irreducible_region_report, param_pointee_check,
straddle_region_report, straddle_witness_report, structured_reject_loop_classes,
@@ -75,7 +97,9 @@ pub(crate) fn inline_direct_function_pointer_consumers(
inline::inline_direct_function_pointer_consumers(san_ll, direct_functions)
}
pub(crate) use owned_cfg::{owned_module_failure, owned_module_failures, OwnedModuleFailure};
pub(crate) use owned_cfg::{
owned_module_failure, owned_module_failures, scalar_width_capability, OwnedModuleFailure,
};
pub(crate) use parse::{
parse_return_type as parse_llvm_return_type, parse_type_prefix as parse_llvm_type_prefix,
};
@@ -98,6 +122,7 @@ use spirv::{Capability, Op, StorageClass, Word};
use std::collections::{HashMap, HashSet};
fn add_native_module_capabilities(module: &mut Module) {
crate::spirv_variable_ptr::lower_storage_buffer_pointer_phis(module);
crate::spirv_variable_ptr::lower_zero_base_storage_buffer_ptr_access_chains(module);
let (has_storage_buffer_pointer_merge, has_other_pointer_merge) =
crate::spirv_variable_ptr::variable_pointer_requirement(module);
@@ -160,7 +185,7 @@ pub(crate) fn requires_device_address_model_for_source(
kern: Option<&crate::meta::KernMeta>,
entry: Option<&str>,
) -> bool {
let san_ll = async_copy::lower_simdgroup_async_copy(san_ll);
let san_ll = lower_air_text(san_ll);
let san_ll = vec_scalar_merge::lower_vector_scalar_pointer_merge(&san_ll);
let san_ll = inline::inline_pointer_select_consumers(&san_ll, entry).source;
ir::LlModule::parse_with_stage_meta(&san_ll, kern, entry)
+326 -90
View File
@@ -5,7 +5,7 @@
//! later rewrite cannot serialize a module that relies on `spirv-val` to discover broken ownership
//! or typing.
use super::dominators::{build_predecessors, dominance, dominates_interval};
use crate::dominators::{build_predecessors, dominance, dominates_interval};
use crate::spirv_module::{is_block_terminator, Function, Instruction, Operand};
use spirv::{Op, Word};
use std::collections::{HashMap, HashSet};
@@ -163,6 +163,17 @@ impl OwnedCfg {
})
}
/// The label id of a block, for a verdict that has to point a reader at a disassembly.
///
/// `labels` is label -> index because every other caller asks that way; a verdict asks the
/// other way exactly twice, so it searches rather than the struct carrying a second map.
fn block_label(&self, block: usize) -> String {
self.labels
.iter()
.find_map(|(label, index)| (*index == block).then_some(format!("%{label}")))
.unwrap_or_else(|| format!("block {block}"))
}
fn dominates(&self, dominator: usize, node: usize) -> bool {
dominates_interval(&self.dominance, dominator, node)
}
@@ -561,14 +572,26 @@ impl OwnedCfg {
};
if definition.block == block {
if definition.instruction >= instruction_index {
return Err(
"native emitter: owned SSA value is used before its definition".to_string(),
);
return Err(format!(
"native emitter: owned SSA value is used before its definition: {:?}{} \
reads %{id}, which block {} defines below it",
instruction.class.opcode,
describe_result(instruction),
self.block_label(block)
));
}
} else if self.flow_reachable[block] && !self.flow_dominates(definition.block, block) {
return Err(
"native emitter: owned SSA definition does not dominate its use".to_string(),
);
// Name the value, the consumer, and both blocks. The phase that breaks dominance is
// typically several phases upstream of the one that reports it, and without the id
// the only way to find it is to bisect the pipeline by hand.
return Err(format!(
"native emitter: owned SSA definition does not dominate its use: {:?}{} in \
block {} reads %{id}, which is defined in block {}",
instruction.class.opcode,
describe_result(instruction),
self.block_label(block),
self.block_label(definition.block)
));
}
}
Ok(())
@@ -1765,16 +1788,27 @@ fn owned_function_call_contract_error(
"native emitter: owned OpFunctionCall disagrees with its function type".to_string(),
);
}
for (argument, parameter_type) in arguments.iter().zip(parameter_types) {
for (position, (argument, parameter_type)) in arguments.iter().zip(parameter_types).enumerate()
{
let (Operand::IdRef(argument), Operand::IdRef(parameter_type)) = (argument, parameter_type)
else {
return Err("native emitter: owned OpFunctionCall has malformed operands".to_string());
};
if value_types.get(argument) != Some(parameter_type) {
return Err(
"native emitter: owned OpFunctionCall argument type disagrees with its function type"
.to_string(),
);
// Name the argument and both types, the same shape the same-type and access-chain
// contracts use. The opcode alone does not say which of a helper's arguments is wrong.
let described = match value_types.get(argument) {
Some(argument_type) => format!(
"%{argument}, of type {}",
describe_owned_id(*argument_type, definitions)
),
None => format!("%{argument}, which has no value type"),
};
return Err(format!(
"native emitter: owned OpFunctionCall argument type disagrees with its function \
type: argument {position} is {described}, but the parameter type is {}",
describe_owned_id(*parameter_type, definitions)
));
}
}
Ok(())
@@ -2147,7 +2181,7 @@ fn glsl_ext_inst_contract(number: u32) -> Option<GlslExtInstContract> {
arity: 2,
width_16_or_32: true,
}),
Glsl::FMin | Glsl::FMax => Some(FloatSame {
Glsl::FMin | Glsl::FMax | Glsl::NMin | Glsl::NMax => Some(FloatSame {
arity: 2,
width_16_or_32: false,
}),
@@ -2523,8 +2557,49 @@ fn owned_memory_type_error(
_ => return None,
};
if !valid {
// Name the pointer, what it points at, and the value type that disagrees. The opcode alone
// does not say which of a module's thousands of loads is wrong, and this verdict is the one
// the retry cascade reports when raw construction also fails -- the same reasoning as the
// same-type-class verdict above, rendered through the same `describe_owned_id`.
let describe_operand = |index: usize| match instruction.operands.get(index) {
Some(Operand::IdRef(id)) => match value_types.get(id) {
Some(ty) => format!("%{id}, of type {}", describe_owned_id(*ty, definitions)),
None => format!("%{id}, which has no value type"),
},
Some(operand) => format!("{operand:?}, which is not a value"),
None => "nothing -- the operand is missing".to_string(),
};
let describe_pointee = |index: usize| match pointer_pointee(index) {
Some(pointee) => describe_owned_id(pointee, definitions),
None => "no pointee -- it is not a pointer".to_string(),
};
let detail = match instruction.class.opcode {
Op::Load => format!(
"pointer {}, points at {}, but the result type is {}",
describe_operand(0),
describe_pointee(0),
match instruction.result_type {
Some(result_type) => describe_owned_id(result_type, definitions),
None => "absent".to_string(),
}
),
Op::Store => format!(
"pointer {}, points at {}, but the stored value is {}",
describe_operand(0),
describe_pointee(0),
describe_operand(1)
),
_ => format!(
"the target {}, points at {}, and the source {}, points at {}",
describe_operand(0),
describe_pointee(0),
describe_operand(1),
describe_pointee(1)
),
};
return Some(format!(
"native emitter: owned {:?} violates its pointer-pointee and value-type contract",
"native emitter: owned {:?} violates its pointer-pointee and value-type contract: \
{detail}",
instruction.class.opcode
));
}
@@ -2767,17 +2842,24 @@ fn owned_pointer_construction_error(
| Op::AtomicFAddEXT
| Op::AtomicFMinEXT
| Op::AtomicFMaxEXT => {
if matches!(
operand_type(0).and_then(|ty| pointer_type_shape(ty, definitions)),
Some((
spirv::StorageClass::Private | spirv::StorageClass::Function,
_
))
) {
return Some(
"native emitter: owned atomic pointer has a non-atomic storage class"
.to_string(),
);
if let Some((
storage @ (spirv::StorageClass::Private | spirv::StorageClass::Function),
_,
)) = operand_type(0).and_then(|ty| pointer_type_shape(ty, definitions))
{
// Name the pointer and the class it is in. Both classes reach here for different
// reasons -- a `Private` one is usually an unmodelled placeholder that leaked into
// an atomic, a `Function` one an alloca the atomic lowering did not promote -- and
// the shared wording cannot be told apart without the operand.
let pointer = match instruction.operands.first() {
Some(Operand::IdRef(pointer)) => describe_owned_id(*pointer, definitions),
_ => "an operand that is not a value".to_string(),
};
return Some(format!(
"native emitter: owned {:?} pointer {pointer} has the non-atomic storage \
class {storage:?}",
instruction.class.opcode
));
}
}
Op::ConstantNull if logical => {
@@ -2834,6 +2916,15 @@ struct OwnedAccessChainFailure {
/// kinds that do not survive as a short literal are dropped rather than debug-printed, so the
/// rendering stays one line, and a long operand list is elided: a wide `OpTypeStruct` or a phi with
/// many arms would otherwise bury the sentence the message is trying to say.
/// ` %N` when an instruction has a result id, and nothing when it does not, so a verdict can name
/// the consumer without a second sentence for the store/branch case.
fn describe_result(instruction: &Instruction) -> String {
instruction
.result_id
.map(|result| format!(" %{result}"))
.unwrap_or_default()
}
fn describe_owned_id(id: Word, definitions: &HashMap<Word, &Instruction>) -> String {
/// Enough operands to recognize a type or an instruction by, and few enough to read.
const SHOWN_OPERANDS: usize = 8;
@@ -3395,6 +3486,23 @@ fn owned_sample_operation_error(
)
})
};
// `Grad` supplies the explicit derivatives Metal's `gradient2d(dPdx, dPdy)` carries: one float
// vector per spatial axis of the image, with the array layer excluded on both.
let grad_valid = |dx: Word, dy: Word| {
let shape = |value: Word| {
value_types
.get(&value)
.and_then(|ty| numeric_type_shape(*ty, definitions))
};
matches!(
(spatial_lanes, shape(dx), shape(dy)),
(
Some(spatial_lanes),
Some((Op::TypeFloat, 32, dx_lanes)),
Some((Op::TypeFloat, 32, dy_lanes)),
) if dx_lanes == spatial_lanes && dy_lanes == spatial_lanes
)
};
let tail = if instruction.class.opcode == Op::ImageGather {
instruction.operands.get(3..)
} else {
@@ -3408,6 +3516,19 @@ fn owned_sample_operation_error(
[Operand::ImageOperands(spirv::ImageOperands::CONST_OFFSET), Operand::IdRef(offset)],
),
) => offset_valid(*offset),
// `Bias` is Metal's `sample(..., bias(b))`: one scalar float shifting the level the
// derivatives give, so it rides the implicit-LOD instruction the way `Lod` rides the
// explicit one. SPIR-V accepts it nowhere else.
(
Op::ImageSampleImplicitLod,
Some([Operand::ImageOperands(spirv::ImageOperands::BIAS), Operand::IdRef(bias)]),
) => lod_valid(*bias),
(
Op::ImageSampleImplicitLod,
Some([Operand::ImageOperands(mask), Operand::IdRef(bias), Operand::IdRef(offset)]),
) if *mask == (spirv::ImageOperands::BIAS | spirv::ImageOperands::CONST_OFFSET) => {
lod_valid(*bias) && offset_valid(*offset)
}
(
Op::ImageSampleExplicitLod,
Some([Operand::ImageOperands(spirv::ImageOperands::LOD), Operand::IdRef(lod)]),
@@ -3418,6 +3539,20 @@ fn owned_sample_operation_error(
) if *mask == (spirv::ImageOperands::LOD | spirv::ImageOperands::CONST_OFFSET) => {
lod_valid(*lod) && offset_valid(*offset)
}
(
Op::ImageSampleExplicitLod,
Some(
[Operand::ImageOperands(spirv::ImageOperands::GRAD), Operand::IdRef(dx), Operand::IdRef(dy)],
),
) => grad_valid(*dx, *dy),
(
Op::ImageSampleExplicitLod,
Some(
[Operand::ImageOperands(mask), Operand::IdRef(dx), Operand::IdRef(dy), Operand::IdRef(offset)],
),
) if *mask == (spirv::ImageOperands::GRAD | spirv::ImageOperands::CONST_OFFSET) => {
grad_valid(*dx, *dy) && offset_valid(*offset)
}
_ => false,
};
let operation_valid = image.is_some_and(|image| {
@@ -3714,14 +3849,30 @@ fn owned_value_instruction_error(
let Some(result_type) = instruction.result_type else {
return Ok(());
};
if instruction
if let Some((position, operand)) = instruction
.operands
.iter()
.any(|operand| operand_type(operand) != Some(result_type))
.enumerate()
.find(|(_, operand)| operand_type(operand) != Some(result_type))
{
// Name the operand that disagrees and both types. A module that reaches this check has
// hundreds of same-class instructions and the opcode alone does not say which one to
// look at; `describe_owned_id` renders the same shape the access-chain contract uses.
let described = match operand {
Operand::IdRef(value) => match value_types.get(value) {
Some(operand_type) => format!(
"%{value}, of type {}",
describe_owned_id(*operand_type, definitions)
),
None => format!("%{value}, which has no value type"),
},
operand => format!("{operand:?}, which is not a value"),
};
return Err(format!(
"native emitter: owned {:?} operands do not match its result type",
instruction.class.opcode
"native emitter: owned {:?} operands do not match its result type: operand \
{position} is {described}, but the result type is {}",
instruction.class.opcode,
describe_owned_id(result_type, definitions)
));
}
let scalar_opcode = scalar_type_shape(result_type, definitions).map(|(opcode, _)| opcode);
@@ -3889,10 +4040,15 @@ fn owned_value_instruction_error(
if !is_pointer(source_type) && !is_pointer(result_type) {
let source_shape = numeric_type_shape(source_type, definitions);
let result_shape = numeric_type_shape(result_type, definitions);
// An `OpBitcast` whose source and result types are the SAME id is a no-op, not an
// error: `spirv-val --target-env vulkan1.2` accepts it. Distinct AIR types share one
// SPIR-V storage type here -- `BFloat` interns as `Int(16)`, and an illegal integer
// width interns as its legal container (`storage_type` in `emitter/types.rs`) -- so a
// `bitcast <4 x bfloat> to <4 x i16>` reaches this check with one id on both sides.
// Only a NUMERIC shape is accepted, so a struct/array source and result still fail
// below on their absent shape.
let valid = match (source_shape, result_shape) {
(Some((_, source_width, source_lanes)), Some((_, result_width, result_lanes)))
if source_type != result_type =>
{
(Some((_, source_width, source_lanes)), Some((_, result_width, result_lanes))) => {
if source_lanes == result_lanes {
source_width == result_width
} else {
@@ -4110,6 +4266,11 @@ fn owned_value_instruction_error(
.to_string(),
);
}
// A pointer-typed result is not exempt from "both objects match Result Type" -- it is
// checked by `owned_pointer_construction_error`, which applies the same predicate and then
// goes on to the cross-root rule Logical addressing adds on top of it. Repeating it here
// only preempts that arm's more specific verdict with this one's generic wording; measured
// 0 of 14,579 corpus sources and 0 of 136 public fixtures change status either way.
let result_is_pointer = definitions
.get(&result_type)
.is_some_and(|definition| definition.class.opcode == Op::TypePointer);
@@ -4124,6 +4285,24 @@ fn owned_value_instruction_error(
Ok(())
}
/// The capability a scalar type of `width` bits demands, or `None` when the width is the one every
/// Vulkan implementation has. `Op::TypeInt`/`Op::TypeFloat` only.
///
/// One table, read in both directions: the owned-module check below refuses a module that declares
/// such a type without the capability, and `passes::drop_unused_scalar_width_capabilities` drops
/// the capability from a module that declares no such type. Two derivations of one fact is how a
/// declared-but-unused `Int8` survived in 656 of the 14,579 corpus sources, so there is one.
pub(crate) fn scalar_width_capability(opcode: Op, width: u32) -> Option<spirv::Capability> {
match (opcode, width) {
(Op::TypeInt, 8) => Some(spirv::Capability::Int8),
(Op::TypeInt, 16) => Some(spirv::Capability::Int16),
(Op::TypeInt, 64) => Some(spirv::Capability::Int64),
(Op::TypeFloat, 16) => Some(spirv::Capability::Float16),
(Op::TypeFloat, 64) => Some(spirv::Capability::Float64),
_ => None,
}
}
fn vector_type_shape(ty: Word, definitions: &HashMap<Word, &Instruction>) -> Option<(Word, u32)> {
let definition = definitions.get(&ty)?;
let [Operand::IdRef(component), Operand::LiteralBit32(count)] = definition.operands.as_slice()
@@ -4931,6 +5110,16 @@ fn owned_module_environment_error(module: &crate::spirv_module::Module) -> Resul
continue;
}
if requirement.extensions.is_empty() {
// An enumerant the grammar gates on CAPABILITIES ALONE -- no core version, no
// extension of its own -- is available exactly when one of them is declared,
// which the check above already settled. The extension that introduced the
// capability is required by the capability, not by this operand. Every
// `FPFastMathMode` bit past `AllowContract` is spelled that way, and demanding
// a core version of them refused 25 corpus modules whose float instructions
// withhold a relaxation the SPIR-V 1.4 core grammar has no word for.
if !requirement.capabilities.is_empty() {
continue;
}
return Err(format!(
"native emitter: owned {:?} operand is unavailable in SPIR-V {}.{}",
instruction.class.opcode, version.0, version.1
@@ -4957,35 +5146,34 @@ fn owned_module_environment_error(module: &crate::spirv_module::Module) -> Resul
{
return Err("native emitter: owned OpTypeInt has invalid signedness".to_string());
}
let width = match (instruction.class.opcode, instruction.operands.as_slice()) {
(Op::TypeInt, [Operand::LiteralBit32(width), Operand::LiteralBit32(_)])
| (Op::TypeFloat, [Operand::LiteralBit32(width)]) => Some(*width),
(Op::TypeInt, _) => {
return Err(
"native emitter: owned OpTypeInt has an unsupported scalar width".to_string(),
);
}
(Op::TypeFloat, _) => {
return Err(
"native emitter: owned OpTypeFloat has an unsupported scalar width".to_string(),
);
}
_ => None,
};
if let Some(width) = width {
if !matches!(
(instruction.class.opcode, width),
(Op::TypeInt, 8 | 16 | 32 | 64) | (Op::TypeFloat, 16 | 32 | 64)
) {
return Err(format!(
"native emitter: owned {:?} has an unsupported scalar width",
instruction.class.opcode
));
}
}
let required_scalar_capability =
match (instruction.class.opcode, instruction.operands.as_slice()) {
(Op::TypeInt, [Operand::LiteralBit32(8), Operand::LiteralBit32(_)]) => {
Some(spirv::Capability::Int8)
}
(Op::TypeInt, [Operand::LiteralBit32(16), Operand::LiteralBit32(_)]) => {
Some(spirv::Capability::Int16)
}
(Op::TypeInt, [Operand::LiteralBit32(32), Operand::LiteralBit32(_)]) => None,
(Op::TypeInt, [Operand::LiteralBit32(64), Operand::LiteralBit32(_)]) => {
Some(spirv::Capability::Int64)
}
(Op::TypeInt, _) => {
return Err(
"native emitter: owned OpTypeInt has an unsupported scalar width"
.to_string(),
);
}
(Op::TypeFloat, [Operand::LiteralBit32(16)]) => Some(spirv::Capability::Float16),
(Op::TypeFloat, [Operand::LiteralBit32(32)]) => None,
(Op::TypeFloat, [Operand::LiteralBit32(64)]) => Some(spirv::Capability::Float64),
(Op::TypeFloat, _) => {
return Err(
"native emitter: owned OpTypeFloat has an unsupported scalar width"
.to_string(),
);
}
_ => None,
};
width.and_then(|width| scalar_width_capability(instruction.class.opcode, width));
if required_scalar_capability.is_some_and(|capability| !capabilities.contains(&capability))
{
return Err(format!(
@@ -6865,6 +7053,17 @@ mod tests {
));
assert!(owned_module_failure(&valid_bitcast).is_none());
// Identity bitcast: `Some(16)` is `vec2<int32>` and id 21 is an Undef of that same type.
// `bitcast <4 x bfloat> to <4 x i16>` arrives in exactly this shape because BFloat interns
// as its Int(16) storage, and `spirv-val --target-env vulkan1.2` accepts it.
let identity_bitcast = module_with_composite_instruction(Instruction::new(
Op::Bitcast,
Some(16),
Some(40),
vec![Operand::IdRef(21)],
));
assert!(owned_module_failure(&identity_bitcast).is_none());
let valid_shift = module_with_composite_instruction(Instruction::new(
Op::ShiftLeftLogical,
Some(16),
@@ -8107,31 +8306,42 @@ mod tests {
#[test]
fn owned_module_enforces_memory_type_contracts() {
let expected = |opcode| {
format!(
"native emitter: owned {opcode:?} violates its pointer-pointee and value-type contract"
)
};
for instruction in [
Instruction::new(Op::Load, Some(15), Some(40), vec![Operand::IdRef(33)]),
Instruction::new(
Op::Store,
None,
None,
vec![Operand::IdRef(33), Operand::IdRef(36)],
// Each verdict names the pointer, what it points at, and the value type that disagrees.
// A module reaching this check has thousands of loads and the opcode alone does not say
// which one to look at -- and this is the verdict the retry cascade reports when raw
// construction fails too, so it is often the only thing a reader gets.
for (instruction, expected) in [
(
Instruction::new(Op::Load, Some(15), Some(40), vec![Operand::IdRef(33)]),
"native emitter: owned Load violates its pointer-pointee and value-type contract: \
pointer %33, of type %14 (TypePointer Function %12), points at %12 \
(TypeInt 32 0), but the result type is %15 (TypeFloat 32)",
),
Instruction::new(
Op::CopyMemory,
None,
None,
vec![Operand::IdRef(33), Operand::IdRef(35)],
(
Instruction::new(
Op::Store,
None,
None,
vec![Operand::IdRef(33), Operand::IdRef(36)],
),
"native emitter: owned Store violates its pointer-pointee and value-type contract: \
pointer %33, of type %14 (TypePointer Function %12), points at %12 \
(TypeInt 32 0), but the stored value is %36, of type %15 (TypeFloat 32)",
),
(
Instruction::new(
Op::CopyMemory,
None,
None,
vec![Operand::IdRef(33), Operand::IdRef(35)],
),
"native emitter: owned CopyMemory violates its pointer-pointee and value-type \
contract: the target %33, of type %14 (TypePointer Function %12), points at \
%12 (TypeInt 32 0), and the source %35, of type %16 (TypePointer Function %15), \
points at %15 (TypeFloat 32)",
),
] {
let opcode = instruction.class.opcode;
assert_owned_type_construction(
&module_with_memory_instruction(instruction),
&expected(opcode),
);
assert_owned_type_construction(&module_with_memory_instruction(instruction), expected);
}
assert_owned_type_construction(
&module_with_memory_instruction(Instruction::new(
@@ -8194,7 +8404,10 @@ mod tests {
));
assert_owned_type_construction(
&invalid,
"native emitter: owned CopyMemory violates its pointer-pointee and value-type contract",
"native emitter: owned CopyMemory violates its pointer-pointee and value-type \
contract: the target %33, of type %14 (TypePointer Function %12), points at \
%12 (TypeInt 32 0), and the source %35, of type %16 (TypePointer Function %15), \
points at %15 (TypeFloat 32)",
);
assert_owned_type_construction(
&invalid_alignment,
@@ -8353,7 +8566,8 @@ mod tests {
));
assert_owned_type_construction(
&atomic,
"native emitter: owned atomic pointer has a non-atomic storage class",
"native emitter: owned AtomicLoad pointer %33 (Variable Function) has the \
non-atomic storage class Function",
);
let pointer_select = |left, right| {
@@ -8895,8 +9109,20 @@ mod tests {
);
}
/// The owned derivative check is the ONLY thing that rejects this module.
///
/// Every sibling in this family names a rule `spirv-val` also enforces, so the owned check is a
/// faster diagnosis of a failure the validator would catch anyway. This one is not. Before
/// SPIR-V 1.6 and `SPV_KHR_compute_shader_derivatives` a derivative instruction is valid only
/// under the Fragment execution model, and a Vulkan 1.2 target has neither -- but measured
/// against SPIRV-Tools v2026.3, `spirv-val` accepts `OpFwidth` reachable from a `GLCompute`
/// entry point under every target environment from `vulkan1.0` through `vulkan1.3`. The
/// assertion here is therefore the opposite of its siblings': it pins the validator's silence,
/// so that the day the gap closes this test says so rather than the owned check quietly becoming
/// redundant. What the owned check rejects is covered by
/// `owned_module_rejects_derivatives_from_non_fragment_call_trees` above.
#[test]
fn owned_derivative_execution_model_check_matches_vulkan_validation() {
fn owned_derivative_execution_model_check_is_not_backed_by_vulkan_validation() {
let module = module_with_composite_instruction(Instruction::new(
Op::Fwidth,
Some(15),
@@ -8919,8 +9145,10 @@ mod tests {
let validation = crate::tools::spirv_val_bytes(&bytes, &tmp);
let _ = std::fs::remove_dir(&tmp);
assert!(
validation.is_err(),
"spirv-val must reject a derivative reachable from GLCompute"
validation.is_ok(),
"spirv-val now rejects a derivative reachable from GLCompute, so the owned check has a \
second line of defence behind it; say so here rather than leaving this note stale: \
{validation:?}"
);
}
@@ -10030,7 +10258,9 @@ mod tests {
assert_eq!(
owned_module_cfg_error(&wrong_argument).as_deref(),
Some(
"native emitter: owned OpFunctionCall argument type disagrees with its function type"
"native emitter: owned OpFunctionCall argument type disagrees with its function \
type: argument 0 is %13, of type %12 (TypeInt 32 0), but the parameter type is \
%9 (TypeBool)"
)
);
@@ -10278,7 +10508,10 @@ mod tests {
assert_eq!(
owned_module_cfg_error(&module).as_deref(),
Some("native emitter: owned SSA definition does not dominate its use")
Some(
"native emitter: owned SSA definition does not dominate its use: CopyObject %23 \
in block %4 reads %22, which is defined in block %2"
)
);
}
@@ -10291,7 +10524,10 @@ mod tests {
assert_eq!(
owned_module_cfg_error(&module).as_deref(),
Some("native emitter: owned SSA value is used before its definition")
Some(
"native emitter: owned SSA value is used before its definition: CopyObject %23 \
reads %22, which block %1 defines below it"
)
);
}
+122 -3
View File
@@ -895,7 +895,16 @@ pub(super) fn parse_identity_ptr_bitcast(line: &str) -> Option<(String, String)>
return None;
}
let src_ty = src[..src.len() - base.len()].trim();
if src_ty != dst {
// Compare the PARSED types, not their text. A pointer's pointee is not part of this
// translator's pointer model -- `LlType::Ptr` carries only the address space -- so
// `bitcast i32 addrspace(1)* %p to i8 addrspace(1)*`, which is how the Metal frontend spells
// a reinterpreting cast in LLVM's pre-opaque syntax, is the same address identity that
// `bitcast ptr addrspace(1) %p to ptr addrspace(1)` is. Reading it as a non-identity kept the
// pointee-typed spelling off the byte-view path and gave the following GEP the BASE's element
// stride instead of its own. Text equality still stands in for a type neither side parses.
let identical =
src_ty == dst || matches!((parse_type(src_ty), parse_type(dst)), (Ok(a), Ok(b)) if a == b);
if !identical {
return None;
}
Some((res, base.to_string()))
@@ -962,8 +971,17 @@ pub(super) fn parse_type(s: &str) -> Result<LlType, String> {
}
}
if let Some(name) = s.strip_prefix('%') {
if name.starts_with('"') && name.ends_with('"') {
return Ok(LlType::Named(format!("%{name}")));
// LLVM escapes inside a quoted identifier as `\xx`, never `\"`, so the first closing
// quote ends the name. Requiring it to end the whole string is what stops the name from
// swallowing a trailing parameter attribute that is quoted too -- a parameter spelled
// `%"struct.metal::_atomic" addrspace(1)* nocapture "air-buffer-no-alias"` was read as
// one named type running from the first quote to the last.
if let Some(inner) = name
.strip_prefix('"')
.and_then(|rest| rest.strip_suffix('"'))
.filter(|inner| !inner.contains('"'))
{
return Ok(LlType::Named(format!("%\"{inner}\"")));
}
if !name.is_empty()
&& name
@@ -1000,9 +1018,31 @@ pub(super) fn parse_type(s: &str) -> Result<LlType, String> {
let (len, elem) = split_vector_type(inner)?;
return Ok(LlType::Array(Box::new(parse_type(elem)?), len));
}
// LLVM's pre-opaque pointer spelling, which is what `xcrun metal -S -emit-llvm` still emits:
// `T*` and `T addrspace(N)*`. It carries the same information as `ptr`/`ptr addrspace(N)`
// plus a pointee our pointer model does not keep, so parse the pointee for validation only.
// Parsing it is what keeps the trailing `*` from being dropped by a caller that backtracks
// over type prefixes, which would silently hand back the pointee as if it were the type.
if let Some(pointee) = s.strip_suffix('*') {
let (pointee, space) = split_trailing_addrspace(pointee.trim_end())?;
parse_type(pointee)?;
return Ok(LlType::Ptr(space));
}
Err(format!("native emitter: unsupported type `{s}`"))
}
/// Split a typed pointer's ` addrspace(N)` suffix off its pointee, defaulting to address space 0.
fn split_trailing_addrspace(s: &str) -> Result<(&str, u32), String> {
let Some(open) = s.strip_suffix(')').and_then(|s| s.rfind(" addrspace(")) else {
return Ok((s, 0));
};
let digits = &s[open + " addrspace(".len()..s.len() - 1];
let space = digits
.parse()
.map_err(|e| format!("native emitter: bad addrspace in `{s}*`: {e}"))?;
Ok((&s[..open], space))
}
fn strip_leading_fast_math_flags(mut s: &str) -> &str {
loop {
let toks = split_top_level_whitespace(s);
@@ -1148,6 +1188,46 @@ mod parse_tests {
assert!(parse_type("ptr addrspace(x)").is_err()); // non-numeric
}
#[test]
fn parse_type_typed_pointers() {
// LLVM's pre-opaque spelling carries the address space on the pointee, and the pointee
// itself is dropped -- both spellings of one pointer have to land on the same type.
assert_eq!(parse_type("i32*").unwrap(), LlType::Ptr(0));
assert_eq!(parse_type("i32 addrspace(1)*").unwrap(), LlType::Ptr(1));
assert_eq!(parse_type("float addrspace(2)*").unwrap(), LlType::Ptr(2));
assert_eq!(
parse_type("<4 x float> addrspace(1)*").unwrap(),
LlType::Ptr(1)
);
assert_eq!(
parse_type("%struct.Foo addrspace(3)*").unwrap(),
LlType::Ptr(3)
);
assert_eq!(parse_type("i32 addrspace(1)**").unwrap(), LlType::Ptr(0));
// A pointee that is not a type is still a parse failure, so a stray `*` cannot pass.
assert!(parse_type("notatype*").is_err());
assert!(parse_type("i32 addrspace(x)*").is_err());
}
#[test]
fn parse_type_prefix_keeps_the_typed_pointer_star() {
// The prefix scan tries the longest candidate first, so before `parse_type` understood
// `i32 addrspace(1)*` it fell through to `i32` and handed back the POINTEE as the type.
assert_eq!(
parse_type_prefix(r#"i32 addrspace(1)* nocapture readonly "air-buffer-no-alias""#)
.unwrap(),
LlType::Ptr(1)
);
let (params, _) = parse_params(r#"i32 addrspace(1)* nocapture %0, i32 %1"#).unwrap();
assert_eq!(
params,
vec![
("%0".to_string(), LlType::Ptr(1)),
("%1".to_string(), LlType::Int(32)),
]
);
}
#[test]
fn parse_quoted_function_and_call_names() {
let lines = [
@@ -1165,6 +1245,45 @@ mod parse_tests {
assert_eq!(call.callee, "helper::quoted");
}
#[test]
fn identity_ptr_bitcast_sees_through_the_pointee_typed_spelling() {
// `LlType::Ptr` carries only the address space, so a pointer bitcast within one address
// space is an address identity however its pointee is spelled. Comparing the type TEXT
// said no to the reinterpreting spelling the Metal frontend emits.
assert_eq!(
parse_identity_ptr_bitcast("%4 = bitcast i32 addrspace(1)* %0 to i8 addrspace(1)*"),
Some(("%4".to_string(), "%0".to_string()))
);
assert_eq!(
parse_identity_ptr_bitcast("%4 = bitcast ptr addrspace(1) %0 to ptr addrspace(1)"),
Some(("%4".to_string(), "%0".to_string()))
);
// Across address spaces, and between non-pointers, it is not an identity.
assert_eq!(
parse_identity_ptr_bitcast("%4 = bitcast i32 addrspace(1)* %0 to i8 addrspace(3)*"),
None
);
assert_eq!(
parse_identity_ptr_bitcast("%4 = bitcast i32 %0 to float"),
None
);
}
#[test]
fn parse_type_quoted_name_stops_at_its_own_closing_quote() {
// A parameter attribute is quoted too, so a name that ran to the LAST quote in the string
// swallowed the whole tail and produced a `Named` nothing could resolve. It has to stop at
// the first closing quote and leave the rest to the prefix scan.
assert!(parse_type(r#"%"struct.metal::_atomic" nocapture "air-buffer-no-alias""#).is_err());
assert_eq!(
parse_type_prefix(
r#"%"struct.metal::_atomic" addrspace(1)* nocapture "air-buffer-no-alias""#
)
.unwrap(),
LlType::Ptr(1)
);
}
#[test]
fn parse_type_named_and_quoted() {
assert_eq!(
+648 -29
View File
@@ -801,6 +801,16 @@ fn rewrite_cross_binding_pointer_merges_inner(
}
})
}
/// The module's existing declaration of `OpTypePointer <storage> <pointee>`, if any.
fn find_ptr_ty(module: &Module, storage: StorageClass, pointee: Word) -> Option<Word> {
module.types_global_values.iter().find_map(|i| {
(i.class.opcode == Op::TypePointer
&& i.operands.first() == Some(&Operand::StorageClass(storage))
&& i.operands.get(1) == Some(&Operand::IdRef(pointee)))
.then_some(i.result_id)
.flatten()
})
}
let uint_ty = match find_int_ty(module, 32) {
Some(id) => id,
None => {
@@ -1136,16 +1146,26 @@ fn rewrite_cross_binding_pointer_merges_inner(
Operand::IdRef(addr_struct),
],
));
let ptr_sb_u64 = fresh();
module.types_global_values.push(Instruction::new(
Op::TypePointer,
None,
Some(ptr_sb_u64),
vec![
Operand::StorageClass(StorageClass::StorageBuffer),
Operand::IdRef(ulong_ty),
],
));
// SPIR-V 2.8 uniques non-aggregate types by opcode and operands: unlike the aggregates above,
// a second `OpTypePointer StorageBuffer %ulong` is invalid even though `spirv-val` accepts it.
// The address table's element pointer is exactly the shape a `device ulong*` buffer parameter
// already declares, so reuse the module's when it has one.
let ptr_sb_u64 = match find_ptr_ty(module, StorageClass::StorageBuffer, ulong_ty) {
Some(id) => id,
None => {
let id = fresh();
module.types_global_values.push(Instruction::new(
Op::TypePointer,
None,
Some(id),
vec![
Operand::StorageClass(StorageClass::StorageBuffer),
Operand::IdRef(ulong_ty),
],
));
id
}
};
let addr_var = fresh();
module.types_global_values.push(Instruction::new(
Op::Variable,
@@ -1366,30 +1386,53 @@ fn rewrite_cross_binding_pointer_merges_inner(
}
}
// Flat-element post-merge chain: an OpAccessChain/OpInBoundsAccessChain that applies a
// SINGLE DYNAMIC index straight to a merged whole-buffer pointer (`%merged %idx`, no
// constant member-0 selector) — the shape a scalar element walk over a cross-binding
// select cascade produces (e.g. b00a8a8d's 28-way output-buffer scatter). Indexing a
// struct member dynamically is illegal, so the simple retype below cannot fix it.
// Lower it like the array-element leaf: take the merged pointer's device address
// (ConvertPtrToU), reinterpret as the element pointer (ConvertUToPtr to the
// ArrayStride-decorated physical element type), and OpPtrAccessChain by the same index
// (`base + idx*stride`, byte-identical). The valid `%merged %uint_0 %i` post-merge chains
// the cleared whole-buffer cases carry have a CONSTANT first index, so they never match
// and fall through to the plain retype.
// SINGLE index straight to a merged whole-buffer pointer (`%merged %idx`) — the shape
// a scalar element walk over a cross-binding select cascade produces (e.g. b00a8a8d's
// 28-way output-buffer scatter). The simple retype below cannot fix it in two cases,
// and both are here: indexing a struct member DYNAMICALLY is illegal, and indexing a
// merged pointer whose pointee is a SCALAR is illegal whatever the index is, because
// there is nothing to descend into. Lower it like the array-element leaf: take the
// merged pointer's device address (ConvertPtrToU), reinterpret as the element pointer
// (ConvertUToPtr to the ArrayStride-decorated physical element type), and
// OpPtrAccessChain by the same index (`base + idx*stride`, byte-identical).
//
// A `%merged %uint_0` whose merged pointee IS a composite stays with the plain retype:
// there the constant is a member selector and descending is what it means. The
// `%merged %uint_0 %i` post-merge chains the cleared whole-buffer cases carry have two
// indices and never reach here at all.
if let Some(r) = rid {
if matches!(inst.class.opcode, Op::AccessChain | Op::InBoundsAccessChain) {
let base = match inst.operands.first() {
Some(Operand::IdRef(b)) => Some(*b),
_ => None,
};
let single_dyn_index = (inst.operands.len() == 2)
let merged_pointee_is_composite = base
.and_then(|base| retype.get(&base).or_else(|| value_type.get(&base)))
.and_then(|ty| ptr_info(*ty))
.and_then(|(_, pointee)| type_defs.get(&pointee))
.is_some_and(|pointee| {
matches!(
pointee.class.opcode,
Op::TypeStruct
| Op::TypeArray
| Op::TypeRuntimeArray
| Op::TypeVector
| Op::TypeMatrix
)
});
let single_index = (inst.operands.len() == 2)
.then(|| match inst.operands[1] {
Operand::IdRef(idx) if !const_ids.contains(&idx) => Some(idx),
Operand::IdRef(idx)
if !const_ids.contains(&idx)
|| !merged_pointee_is_composite =>
{
Some(idx)
}
_ => None,
})
.flatten();
if let (Some(base), Some(idx), Some(&elem_ptr)) =
(base, single_dyn_index, retype.get(&r))
(base, single_index, retype.get(&r))
{
if closure.contains(&base) {
let addr = fresh();
@@ -1481,13 +1524,46 @@ fn rewrite_cross_binding_pointer_merges_inner(
.and_then(|ty| ptr_info(*ty))
.map(|(_, pointee)| pointee);
if closure.contains(&pointer) && pointer_pointee != Some(accessed_type) {
// Take the address of the BASE and add the byte offset, rather than the
// address of the byte access chain, whenever the pointer is one.
//
// `OpConvertPtrToU` of an `OpPtrAccessChain` is valid SPIR-V and
// `spirv-val` accepts it, but SPIRV-Cross's MSL backend renders the access
// chain as an LVALUE there -- `reinterpret_cast<ulong>(_p[i])`, which is a
// cast from `uchar`, and does not compile. It renders the base pointer
// itself correctly. A `uchar` element is one byte, so adding the index to
// the base address names the same byte the chain did.
let byte_step = byte_element_step(
pointer,
&all_value_defs,
&value_type,
&all_value_types,
&type_defs,
ulong_ty,
);
let address = fresh();
new_insts.push(Instruction::new(
Op::ConvertPtrToU,
Some(ulong_ty),
Some(address),
vec![Operand::IdRef(pointer)],
));
if let Some((base, index)) = byte_step {
let base_address = fresh();
new_insts.push(Instruction::new(
Op::ConvertPtrToU,
Some(ulong_ty),
Some(base_address),
vec![Operand::IdRef(base)],
));
new_insts.push(Instruction::new(
Op::IAdd,
Some(ulong_ty),
Some(address),
vec![Operand::IdRef(base_address), Operand::IdRef(index)],
));
} else {
new_insts.push(Instruction::new(
Op::ConvertPtrToU,
Some(ulong_ty),
Some(address),
vec![Operand::IdRef(pointer)],
));
}
let typed_pointer = fresh();
new_insts.push(Instruction::new(
Op::ConvertUToPtr,
@@ -1573,6 +1649,51 @@ fn rewrite_cross_binding_pointer_merges_inner(
Some(addr_var)
}
/// The `(base, byte index)` of a byte-element `OpPtrAccessChain`, when taking the base's address
/// and adding the index names the same byte the chain does.
///
/// `OpConvertPtrToU` of an access chain is valid SPIR-V and `spirv-val` accepts it, but SPIRV-Cross
/// renders the chain as an LVALUE there -- `reinterpret_cast<ulong>(_p[i])`, a cast from `uchar` --
/// and the MSL does not compile, so MoltenVK refuses the pipeline. It renders the base pointer
/// itself correctly. A `uchar` element is one byte, so `base + index` is the same address.
///
/// Restricted to a byte element and a 64-bit index: any other stride would need a multiply, and any
/// other index width a conversion, and neither is justified by anything measured here.
fn byte_element_step(
pointer: Word,
value_defs: &HashMap<Word, Instruction>,
value_type: &HashMap<Word, Word>,
all_value_types: &HashMap<Word, Word>,
type_defs: &HashMap<Word, Instruction>,
ulong_ty: Word,
) -> Option<(Word, Word)> {
let def = value_defs.get(&pointer)?;
if !matches!(
def.class.opcode,
Op::PtrAccessChain | Op::InBoundsPtrAccessChain
) {
return None;
}
let [Operand::IdRef(base), Operand::IdRef(index)] = def.operands.as_slice() else {
return None;
};
if all_value_types.get(index).copied() != Some(ulong_ty) {
return None;
}
let base_pointee = match type_defs.get(value_type.get(base)?)?.operands.as_slice() {
[Operand::StorageClass(_), Operand::IdRef(pointee)] => *pointee,
_ => return None,
};
let pointee = type_defs.get(&base_pointee)?;
if pointee.class.opcode != Op::TypeInt {
return None;
}
match pointee.operands.first()? {
Operand::LiteralBit32(8) => Some((*base, *index)),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -1582,6 +1703,504 @@ mod tests {
Instruction::new(op, ty, res, ops)
}
#[test]
fn a_byte_element_step_is_recognized_and_a_wider_one_is_not() {
// `%chain = OpPtrAccessChain %ptr_uchar %base %index` with a 64-bit index: taking the
// BASE's address and adding the index names the same byte, and unlike the address of the
// chain it is something SPIRV-Cross can spell in MSL.
let uchar = 1;
let ulong = 2;
let uint = 3;
let ptr_uchar = 4;
let ptr_ushort = 5;
let ushort = 6;
let type_defs = HashMap::from([
(
uchar,
inst(
Op::TypeInt,
None,
Some(uchar),
vec![Operand::LiteralBit32(8), Operand::LiteralBit32(0)],
),
),
(
ushort,
inst(
Op::TypeInt,
None,
Some(ushort),
vec![Operand::LiteralBit32(16), Operand::LiteralBit32(0)],
),
),
(
ptr_uchar,
inst(
Op::TypePointer,
None,
Some(ptr_uchar),
vec![
Operand::StorageClass(StorageClass::PhysicalStorageBuffer),
Operand::IdRef(uchar),
],
),
),
(
ptr_ushort,
inst(
Op::TypePointer,
None,
Some(ptr_ushort),
vec![
Operand::StorageClass(StorageClass::PhysicalStorageBuffer),
Operand::IdRef(ushort),
],
),
),
]);
let (base, index, chain) = (10, 11, 12);
let chain_inst = inst(
Op::PtrAccessChain,
Some(ptr_uchar),
Some(chain),
vec![Operand::IdRef(base), Operand::IdRef(index)],
);
let value_defs = HashMap::from([(chain, chain_inst.clone())]);
let value_type = HashMap::from([(base, ptr_uchar), (chain, ptr_uchar)]);
let all_value_types = HashMap::from([(index, ulong)]);
assert_eq!(
byte_element_step(
chain,
&value_defs,
&value_type,
&all_value_types,
&type_defs,
ulong,
),
Some((base, index))
);
// A 16-bit element is a stride this rewrite would have to multiply by, and a 32-bit index
// is a width it would have to convert. Neither is recognized.
let wide_type = HashMap::from([(base, ptr_ushort), (chain, ptr_uchar)]);
assert_eq!(
byte_element_step(
chain,
&value_defs,
&wide_type,
&all_value_types,
&type_defs,
ulong,
),
None
);
let narrow_index = HashMap::from([(index, uint)]);
assert_eq!(
byte_element_step(
chain,
&value_defs,
&value_type,
&narrow_index,
&type_defs,
ulong,
),
None
);
// Anything that is not a pointer access chain keeps the plain conversion.
let load = HashMap::from([(
chain,
inst(
Op::Load,
Some(ptr_uchar),
Some(chain),
vec![Operand::IdRef(base)],
),
)]);
assert_eq!(
byte_element_step(
chain,
&load,
&value_type,
&all_value_types,
&type_defs,
ulong,
),
None
);
}
// A byte-element `OpPtrAccessChain` reached by a load of a WIDER type is the shape that made
// SPIRV-Cross emit `reinterpret_cast<ulong>(_p[i])` -- a cast from `uchar`, which `xcrun metal`
// rejects. The address the rewrite converts must be the BASE's, with the byte index added.
#[test]
fn a_byte_chain_address_is_taken_from_the_base_and_offset() {
// ids: uchar=1 rtarr=2 struct=3 ptrSbStruct=4 ptrSbUchar=5 bool=6 uint=7 ulong=8 |
// uint_0=10 true=12 ulong_4=13 | bufA=20 bufB=21 | block=30 chainA=31 chainB=32
// select=33 byteChain=34 load=35
let mut module = Module::new();
module.header = Some(ModuleHeader::new(40));
module.memory_model = Some(inst(
Op::MemoryModel,
None,
None,
vec![
Operand::AddressingModel(spirv::AddressingModel::Logical),
Operand::MemoryModel(MemoryModel::GLSL450),
],
));
module.types_global_values = vec![
inst(
Op::TypeInt,
None,
Some(1),
vec![Operand::LiteralBit32(8), Operand::LiteralBit32(0)],
),
inst(Op::TypeRuntimeArray, None, Some(2), vec![Operand::IdRef(1)]),
inst(Op::TypeStruct, None, Some(3), vec![Operand::IdRef(2)]),
inst(
Op::TypePointer,
None,
Some(4),
vec![
Operand::StorageClass(StorageClass::StorageBuffer),
Operand::IdRef(3),
],
),
inst(
Op::TypePointer,
None,
Some(5),
vec![
Operand::StorageClass(StorageClass::StorageBuffer),
Operand::IdRef(1),
],
),
inst(Op::TypeBool, None, Some(6), vec![]),
inst(
Op::TypeInt,
None,
Some(7),
vec![Operand::LiteralBit32(32), Operand::LiteralBit32(0)],
),
inst(
Op::TypeInt,
None,
Some(8),
vec![Operand::LiteralBit32(64), Operand::LiteralBit32(0)],
),
inst(
Op::Constant,
Some(7),
Some(10),
vec![Operand::LiteralBit32(0)],
),
inst(Op::ConstantTrue, Some(6), Some(12), vec![]),
inst(
Op::Constant,
Some(8),
Some(13),
vec![Operand::LiteralBit32(4), Operand::LiteralBit32(0)],
),
inst(
Op::Variable,
Some(4),
Some(20),
vec![Operand::StorageClass(StorageClass::StorageBuffer)],
),
inst(
Op::Variable,
Some(4),
Some(21),
vec![Operand::StorageClass(StorageClass::StorageBuffer)],
),
];
module.annotations = vec![
inst(
Op::Decorate,
None,
None,
vec![
Operand::IdRef(2),
Operand::Decoration(Decoration::ArrayStride),
Operand::LiteralBit32(1),
],
),
inst(
Op::Decorate,
None,
None,
vec![Operand::IdRef(3), Operand::Decoration(Decoration::Block)],
),
inst(
Op::MemberDecorate,
None,
None,
vec![
Operand::IdRef(3),
Operand::LiteralBit32(0),
Operand::Decoration(Decoration::Offset),
Operand::LiteralBit32(0),
],
),
inst(
Op::Decorate,
None,
None,
vec![
Operand::IdRef(20),
Operand::Decoration(Decoration::Binding),
Operand::LiteralBit32(0),
],
),
inst(
Op::Decorate,
None,
None,
vec![
Operand::IdRef(21),
Operand::Decoration(Decoration::Binding),
Operand::LiteralBit32(1),
],
),
];
let mut block = Block::new();
block.label = Some(inst(Op::Label, None, Some(30), vec![]));
block.instructions = vec![
inst(
Op::AccessChain,
Some(5),
Some(31),
vec![Operand::IdRef(20), Operand::IdRef(10), Operand::IdRef(10)],
),
inst(
Op::AccessChain,
Some(5),
Some(32),
vec![Operand::IdRef(21), Operand::IdRef(10), Operand::IdRef(10)],
),
inst(
Op::Select,
Some(5),
Some(33),
vec![Operand::IdRef(12), Operand::IdRef(31), Operand::IdRef(32)],
),
inst(
Op::PtrAccessChain,
Some(5),
Some(34),
vec![Operand::IdRef(33), Operand::IdRef(13)],
),
// A 32-bit load through the byte pointer: the pointee and the accessed type differ, so
// the rewrite must materialize the address itself.
inst(Op::Load, Some(7), Some(35), vec![Operand::IdRef(34)]),
inst(Op::Return, None, None, vec![]),
];
let mut function = Function::new();
function.blocks = vec![block];
module.functions = vec![function];
assert!(rewrite_cross_binding_pointer_merges(&mut module));
let instructions = &module.functions[0].blocks[0].instructions;
// The chain itself is never the operand of a `OpConvertPtrToU`; the base is, and the byte
// index is added to it.
let converted = instructions
.iter()
.filter(|instruction| instruction.class.opcode == Op::ConvertPtrToU)
.map(|instruction| instruction.operands.clone())
.collect::<Vec<_>>();
assert!(!converted.is_empty(), "no address was materialized");
assert!(
!converted.contains(&vec![Operand::IdRef(34)]),
"the byte access chain is still converted directly: {converted:?}"
);
let base_address = instructions
.iter()
.find(|instruction| {
instruction.class.opcode == Op::ConvertPtrToU
&& instruction.operands == [Operand::IdRef(33)]
})
.and_then(|instruction| instruction.result_id)
.expect("the select's address");
assert!(
instructions.iter().any(|instruction| {
instruction.class.opcode == Op::IAdd
&& instruction.operands == [Operand::IdRef(base_address), Operand::IdRef(13)]
}),
"the byte index is not added to the base address"
);
}
// SPIR-V 2.8 uniques non-aggregate types, so the address table's `OpTypePointer StorageBuffer
// %ulong` may not be a second declaration of one the module already has. `spirv-val` accepts the
// duplicate, so only this assertion catches it.
#[test]
fn the_address_table_reuses_the_modules_storage_buffer_ulong_pointer() {
// ids: ulong=1 rtarr=2 struct=3 ptrSbStruct=4 ptrSbUlong=5 bool=6 uint=7 |
// uint_0=10 true=12 | bufA=20 bufB=21 | block=30 chainA=31 chainB=32 select=33 load=35
let mut module = Module::new();
module.header = Some(ModuleHeader::new(40));
module.memory_model = Some(inst(
Op::MemoryModel,
None,
None,
vec![
Operand::AddressingModel(spirv::AddressingModel::Logical),
Operand::MemoryModel(MemoryModel::GLSL450),
],
));
module.types_global_values = vec![
inst(
Op::TypeInt,
None,
Some(1),
vec![Operand::LiteralBit32(64), Operand::LiteralBit32(0)],
),
inst(Op::TypeRuntimeArray, None, Some(2), vec![Operand::IdRef(1)]),
inst(Op::TypeStruct, None, Some(3), vec![Operand::IdRef(2)]),
inst(
Op::TypePointer,
None,
Some(4),
vec![
Operand::StorageClass(StorageClass::StorageBuffer),
Operand::IdRef(3),
],
),
inst(
Op::TypePointer,
None,
Some(5),
vec![
Operand::StorageClass(StorageClass::StorageBuffer),
Operand::IdRef(1),
],
),
inst(Op::TypeBool, None, Some(6), vec![]),
inst(
Op::TypeInt,
None,
Some(7),
vec![Operand::LiteralBit32(32), Operand::LiteralBit32(0)],
),
inst(
Op::Constant,
Some(7),
Some(10),
vec![Operand::LiteralBit32(0)],
),
inst(Op::ConstantTrue, Some(6), Some(12), vec![]),
inst(
Op::Variable,
Some(4),
Some(20),
vec![Operand::StorageClass(StorageClass::StorageBuffer)],
),
inst(
Op::Variable,
Some(4),
Some(21),
vec![Operand::StorageClass(StorageClass::StorageBuffer)],
),
];
module.annotations = vec![
inst(
Op::Decorate,
None,
None,
vec![
Operand::IdRef(2),
Operand::Decoration(Decoration::ArrayStride),
Operand::LiteralBit32(8),
],
),
inst(
Op::Decorate,
None,
None,
vec![Operand::IdRef(3), Operand::Decoration(Decoration::Block)],
),
inst(
Op::MemberDecorate,
None,
None,
vec![
Operand::IdRef(3),
Operand::LiteralBit32(0),
Operand::Decoration(Decoration::Offset),
Operand::LiteralBit32(0),
],
),
inst(
Op::Decorate,
None,
None,
vec![
Operand::IdRef(20),
Operand::Decoration(Decoration::Binding),
Operand::LiteralBit32(0),
],
),
inst(
Op::Decorate,
None,
None,
vec![
Operand::IdRef(21),
Operand::Decoration(Decoration::Binding),
Operand::LiteralBit32(1),
],
),
];
let mut block = Block::new();
block.label = Some(inst(Op::Label, None, Some(30), vec![]));
block.instructions = vec![
inst(
Op::AccessChain,
Some(5),
Some(31),
vec![Operand::IdRef(20), Operand::IdRef(10), Operand::IdRef(10)],
),
inst(
Op::AccessChain,
Some(5),
Some(32),
vec![Operand::IdRef(21), Operand::IdRef(10), Operand::IdRef(10)],
),
inst(
Op::Select,
Some(5),
Some(33),
vec![Operand::IdRef(12), Operand::IdRef(31), Operand::IdRef(32)],
),
inst(Op::Load, Some(1), Some(35), vec![Operand::IdRef(33)]),
inst(Op::Return, None, None, vec![]),
];
let mut function = Function::new();
function.blocks = vec![block];
module.functions = vec![function];
assert!(rewrite_cross_binding_pointer_merges(&mut module));
let declarations = module
.types_global_values
.iter()
.filter(|instruction| {
instruction.class.opcode == Op::TypePointer
&& instruction.operands
== [
Operand::StorageClass(StorageClass::StorageBuffer),
Operand::IdRef(1),
]
})
.filter_map(|instruction| instruction.result_id)
.collect::<Vec<_>>();
assert_eq!(
declarations,
vec![5],
"the address table declared its own StorageBuffer ulong pointer"
);
}
#[test]
fn physical_vector_stride_prefers_explicit_layout_and_rejects_conflicts() {
let mut module = Module::new();
+199 -7
View File
@@ -13,13 +13,19 @@
//! // before (illegal): p = select(c, &bufB[i], &bufA[i]); v = load(p)
//! // after (legal): vA = load(&bufA[i]); vB = load(&bufB[i]); v = select(c, vB, vA)
//! ```
//! It is byte-exact by construction: the SELECTED value is the exact load Apple performs; the
//! non-selected loads are discarded (device-buffer over-reads on Metal do not fault). For an ordinary
//! store through the merge, it uses the emitter's established branch-free read/modify/write form: each
//! candidate arm is loaded, the selected arm receives the new value, and the other is stored back
//! unchanged. This keeps the operation in Logical StorageBuffer value space without introducing a new
//! control-flow block after CFG structurization. Opaque pointer uses, atomics, and pointer phis still
//! make the pass BAIL so PSB handles those shapes as today.
//! The LOAD rewrite is byte-exact by construction: the SELECTED value is the exact load Apple
//! performs, and the non-selected loads are discarded (device-buffer over-reads on Metal do not
//! fault).
//!
//! The STORE rewrite is a branch-free read/modify/write: each candidate arm is loaded, the selected
//! arm receives the new value, and the other is stored back unchanged. That is byte-exact for ONE
//! invocation and NOT equivalent to Apple's store in general -- storing a value back is still a
//! write, so an invocation that did not select an arm overwrites, with the pre-store value, the
//! result of an invocation that did. The emitter hit exactly this and now guards each arm's store
//! instead (`emitter::pointers::raw_select`); this pass runs after CFG structurization on a block
//! list it cannot split, so it has no guard to emit and instead DECLINES whenever the arm an
//! invocation stores into can differ between invocations. Opaque pointer uses, atomics, and pointer
//! phis still make the pass BAIL so PSB handles those shapes as today.
//!
//! Decides purely from IR structure (storage class, access-chain roots, the cross-binding property,
//! and replayable consumer class) — never a shader name. Interface binding invokes it when concrete
@@ -785,6 +791,98 @@ fn rewrite_scalar_ptr_byte_loads(module: &mut Module) -> bool {
/// Rewrite the cross-binding pointer-merge sub-graph(s) of `module` into the value domain (plain
/// Logical `StorageBuffer`). Returns true if any rewrite was applied. Three stages: discover the
/// lowerable closure, replay each closure load into the value domain (synthesis), then install it.
/// Ids whose value can differ between the invocations of one dispatch: everything reachable forward
/// from an `Input` variable. A load is varying when its POINTER is varying — the memory it reads is
/// the same for every invocation, but the address is not.
///
/// Data-flow only, and that is sufficient here: a pointer merge that is a control-flow `OpPhi`
/// already makes discovery bail, so the arm an invocation stores into is decided by `OpSelect`
/// conditions and nothing else.
fn invocation_varying_ids(module: &Module) -> HashSet<Word> {
let mut varying: HashSet<Word> = module
.types_global_values
.iter()
.filter(|inst| {
inst.class.opcode == Op::Variable
&& matches!(
inst.operands.first(),
Some(Operand::StorageClass(StorageClass::Input))
)
})
.filter_map(|inst| inst.result_id)
.collect();
// Block order is not a dominance order for `OpPhi`, so iterate to a fixpoint. Every round
// strictly grows the set, so this terminates in at most one round per value.
loop {
let mut changed = false;
for function in &module.functions {
for block in &function.blocks {
for inst in &block.instructions {
let Some(result) = inst.result_id else {
continue;
};
if varying.contains(&result) {
continue;
}
if inst
.operands
.iter()
.any(|op| matches!(op, Operand::IdRef(id) if varying.contains(id)))
{
varying.insert(result);
changed = true;
}
}
}
}
if !changed {
return varying;
}
}
}
/// Whether the arm a store through `ptr` lands in can differ between invocations — the condition
/// under which the branch-free read/modify/write store described in the module doc is a data race.
fn store_arm_varies_by_invocation(
ptr: Word,
value_def: &HashMap<Word, Instruction>,
var_storage: &HashMap<Word, StorageClass>,
varying: &HashSet<Word>,
) -> bool {
let mut seen: HashSet<Word> = HashSet::new();
let mut work = vec![ptr];
while let Some(id) = work.pop() {
if !seen.insert(id) || var_storage.contains_key(&id) {
continue;
}
let Some(def) = value_def.get(&id) else {
continue;
};
match def.class.opcode {
Op::Select => {
let Some(Operand::IdRef(condition)) = def.operands.first() else {
return true;
};
if varying.contains(condition) {
return true;
}
work.extend(def.operands.iter().skip(1).filter_map(|op| match op {
Operand::IdRef(arm) => Some(*arm),
_ => None,
}));
}
Op::Phi => return true,
Op::AccessChain | Op::InBoundsAccessChain | Op::PtrAccessChain | Op::CopyObject => {
if let Some(Operand::IdRef(base)) = def.operands.first() {
work.push(*base);
}
}
_ => {}
}
}
false
}
pub(super) fn rewrite_cross_binding_pointer_merges_to_values(module: &mut Module) -> bool {
let Some(Discovery {
type_defs,
@@ -1726,6 +1824,17 @@ pub(super) fn rewrite_cross_binding_pointer_merges_to_values(module: &mut Module
}
}
}
if !stores.is_empty() {
let varying = invocation_varying_ids(module);
if stores.iter().any(|(_, _, _, ptr, _, _)| {
store_arm_varies_by_invocation(*ptr, &value_def, &var_storage, &varying)
}) {
// Declining leaves the whole closure for PSB's device-address lowering. That costs
// a compute pipeline MoltenVK can create, and it is still the right trade against a
// store that races: measured over all 14,579 corpus sources, no module reaches this.
return false;
}
}
for ptr in loads
.iter()
.map(|(_, ptr, _)| ptr)
@@ -2746,6 +2855,89 @@ mod tests {
);
}
/// Give the two-buffer fixture the same store, but choose the arm from a per-invocation
/// builtin instead of a constant. The branch-free read/modify/write writes BOTH arms, so an
/// invocation that took the other arm would overwrite this one's result with the value it read
/// before the store. The pass has no guard to emit here, so it must decline and leave the whole
/// closure to PSB.
#[test]
fn store_through_a_merge_the_invocation_chooses_is_declined() {
let mut m = build_two_buffer_select();
m.types_global_values.push(inst(
Op::Constant,
Some(4),
Some(44),
vec![Operand::LiteralBit32(0)],
));
// %45 = ptr Input uint, %46 = the builtin, %47 = its load, %48 = the derived condition.
m.types_global_values.push(inst(
Op::TypePointer,
None,
Some(45),
vec![
Operand::StorageClass(StorageClass::Input),
Operand::IdRef(3),
],
));
m.types_global_values.push(inst(
Op::Variable,
Some(45),
Some(46),
vec![Operand::StorageClass(StorageClass::Input)],
));
let block = &mut m.functions[0].blocks[0];
block.instructions.retain(|i| i.result_id != Some(43));
block.instructions.insert(
0,
inst(Op::Load, Some(3), Some(47), vec![Operand::IdRef(46)]),
);
block.instructions.insert(
1,
inst(
Op::IEqual,
Some(9),
Some(48),
vec![Operand::IdRef(47), Operand::IdRef(10)],
),
);
for instruction in block.instructions.iter_mut() {
if instruction.result_id == Some(42) {
instruction.operands[0] = Operand::IdRef(48);
}
}
let ret_pos = block
.instructions
.iter()
.position(|i| i.class.opcode == Op::Return)
.unwrap();
block.instructions.insert(
ret_pos,
inst(
Op::Store,
None,
None,
vec![Operand::IdRef(42), Operand::IdRef(44)],
),
);
let before = m.clone();
assert!(
!rewrite_cross_binding_pointer_merges_to_values(&mut m),
"a store whose arm the invocation chooses must not be replayed in the value domain"
);
assert_eq!(
m.functions[0].blocks[0].instructions.len(),
before.functions[0].blocks[0].instructions.len(),
"declining must leave the module untouched"
);
assert!(
m.functions[0].blocks[0]
.instructions
.iter()
.any(|inst| inst.result_id == Some(42)),
"the pointer select survives for PSB to lower"
);
}
#[test]
fn store_through_merge_lowers_to_value_domain_rmw() {
let mut m = build_two_buffer_select();
+133 -6
View File
@@ -617,7 +617,7 @@ pub(crate) fn all_air_intersection_calls_are_lowerable(ll: &str) -> bool {
}
const TRIANGLE_QUERY_HELPER: &str = r#"
define internal { i32, float, i32, i32, i64, <2 x float>, i1 } @metal2vulkan.intersect.callback_free.triangle_data(<3 x float> %origin, <3 x float> %direction, float %min_distance, float %max_distance, ptr addrspace(1) %acceleration_structure, ptr addrspace(1) %table, ptr %payload, i64 %payload_stride, i32 %a8, i32 %a9, i32 %a10, i32 %a11, i32 %a12, i32 %a13, i32 %a14, i32 %a15, i32 %a16, i1 %a17) {
define internal { i32, float, i32, i32, i64, <2 x float>, i1 } @metal2vulkan.intersect.callback_free.triangle_data(<3 x float> %origin, <3 x float> %direction, float %min_distance, float %max_distance, ptr addrspace(1) %acceleration_structure, ptr addrspace(1) %table, ptr %payload, i64 %payload_stride, i32 %front_facing_winding, i32 %triangle_cull_mode, i32 %a10, i32 %a11, i32 %a12, i32 %a13, i32 %a14, i32 %a15, i32 %a16, i1 %a17) {
entry:
%triangle_count = load i32, ptr addrspace(1) %acceleration_structure, align 4
%ox = extractelement <3 x float> %origin, i32 0
@@ -735,8 +735,29 @@ body:
%valid1 = and i1 %valid0, %v_nonnegative
%valid2 = and i1 %valid1, %uv_in_triangle
%valid3 = and i1 %valid2, %after_min
%valid = and i1 %valid3, %before_best
%front = fcmp ogt float %det, 0.000000e+00
%valid4 = and i1 %valid3, %before_best
%det_positive = fcmp ogt float %det, 0.000000e+00
%det_negative = fcmp olt float %det, 0.000000e+00
; Metal's `winding` says which sign of the Moller-Trumbore determinant is the front face: 0 is
; clockwise, which is the default `intersection_params` holds, and 1 is counterclockwise, which
; swaps the two. It has to be read before anything that names a face -- the cull mode below and
; the front-facing result field are the same question asked twice.
%counterclockwise = icmp eq i32 %front_facing_winding, 1
%clockwise = icmp ne i32 %front_facing_winding, 1
%front_cw = and i1 %clockwise, %det_positive
%front_ccw = and i1 %counterclockwise, %det_negative
%front = or i1 %front_cw, %front_ccw
%back_cw = and i1 %clockwise, %det_negative
%back_ccw = and i1 %counterclockwise, %det_positive
%back = or i1 %back_cw, %back_ccw
; Metal's `triangle_cull_mode`: 0 none, 1 front, 2 back. Each mode only removes hits, so keeping
; one means the mode either is not that mode or names the face this hit is not on.
%not_cull_front = icmp ne i32 %triangle_cull_mode, 1
%not_cull_back = icmp ne i32 %triangle_cull_mode, 2
%keep_front = or i1 %not_cull_front, %back
%keep_back = or i1 %not_cull_back, %front
%kept = and i1 %keep_front, %keep_back
%valid = and i1 %valid4, %kept
%selected_distance = select i1 %valid, float %distance, float %best_distance
%selected_primitive = select i1 %valid, i32 %index, i32 %best_primitive
%selected_u = select i1 %valid, float %u, float %best_u
@@ -782,7 +803,7 @@ entry:
ret { i32, float, i32, i32, i64, <2 x float>, i1 } %full
}
define internal { i32, float, i32, i32, i64, i32, i32, <2 x float>, i1 } @metal2vulkan.intersect.callback_free.instancing.triangle_data(<3 x float> %origin, <3 x float> %direction, float %min_distance, float %max_distance, ptr addrspace(1) %acceleration_structure, i32 %instance_mask, ptr addrspace(1) %table, ptr %payload, i64 %payload_stride, i32 %a9, i32 %a10, i32 %a11, i32 %a12, i32 %a13, i32 %a14, i32 %a15, i32 %a16, i32 %a17, i1 %a18, i1 %a19) {
define internal { i32, float, i32, i32, i64, i32, i32, <2 x float>, i1 } @metal2vulkan.intersect.callback_free.instancing.triangle_data(<3 x float> %origin, <3 x float> %direction, float %min_distance, float %max_distance, ptr addrspace(1) %acceleration_structure, i32 %instance_mask, ptr addrspace(1) %table, ptr %payload, i64 %payload_stride, i32 %front_facing_winding, i32 %triangle_cull_mode, i32 %a11, i32 %a12, i32 %a13, i32 %a14, i32 %a15, i32 %a16, i32 %a17, i1 %a18, i1 %a19) {
entry:
%instance_count = load i32, ptr addrspace(1) %acceleration_structure, align 4
%has_instance = icmp ne i32 %instance_count, 0
@@ -827,10 +848,31 @@ entry:
%valid3 = and i1 %valid2, %v_nonnegative
%valid4 = and i1 %valid3, %uv_in_triangle
%valid5 = and i1 %valid4, %after_min
%valid = and i1 %valid5, %before_max
%valid6 = and i1 %valid5, %before_max
%det_positive = fcmp ogt float %det, 0.000000e+00
%det_negative = fcmp olt float %det, 0.000000e+00
; Metal's `winding` says which sign of the Moller-Trumbore determinant is the front face: 0 is
; clockwise, which is the default `intersection_params` holds, and 1 is counterclockwise, which
; swaps the two. It has to be read before anything that names a face -- the cull mode below and
; the front-facing result field are the same question asked twice.
%counterclockwise = icmp eq i32 %front_facing_winding, 1
%clockwise = icmp ne i32 %front_facing_winding, 1
%front_cw = and i1 %clockwise, %det_positive
%front_ccw = and i1 %counterclockwise, %det_negative
%front = or i1 %front_cw, %front_ccw
%back_cw = and i1 %clockwise, %det_negative
%back_ccw = and i1 %counterclockwise, %det_positive
%back = or i1 %back_cw, %back_ccw
; Metal's `triangle_cull_mode`: 0 none, 1 front, 2 back. Each mode only removes hits, so keeping
; one means the mode either is not that mode or names the face this hit is not on.
%not_cull_front = icmp ne i32 %triangle_cull_mode, 1
%not_cull_back = icmp ne i32 %triangle_cull_mode, 2
%keep_front = or i1 %not_cull_front, %back
%keep_back = or i1 %not_cull_back, %front
%kept = and i1 %keep_front, %keep_back
%valid = and i1 %valid6, %kept
%intersection_type = select i1 %valid, i32 1, i32 0
%selected_distance = select i1 %valid, float %distance, float %max_distance
%front = fcmp ogt float %det, 0.000000e+00
%selected_front = and i1 %valid, %front
%selected_u = select i1 %valid, float %u, float 0.000000e+00
%selected_v = select i1 %valid, float %v, float 0.000000e+00
@@ -925,6 +967,91 @@ mod tests {
assert!(all_air_intersection_calls_are_lowerable(ll));
}
#[test]
fn triangle_facing_reads_the_winding_and_the_cull_mode_air_passes_beside_it() {
// AIR's operand order is Apple's: `winding, triangle_cull_mode, geometry_cull_mode,
// opacity_cull_mode, forced_opacity, geometry_type, ...`, so the two this lowering reads sit
// immediately after the payload stride. Reading one slot over silently turns a cull mode
// into a geometry cull mode and a winding into a cull mode, and every family that adds an
// operand -- motion time, instance mask -- adds it before that block, never inside it.
let plain = "%hit = call { i32, float, i32, i32, ptr addrspace(1), <2 x float>, i1 } \
@air.intersect.triangle_data(<3 x float> zeroinitializer, <3 x float> zeroinitializer, float 0.0, \
float 1.0, ptr addrspace(1) %as, ptr addrspace(1) %table, ptr null, i64 0, i32 1, i32 2, i32 0, \
i32 0, i32 0, i32 3, i32 -1, i32 -1, i32 0, i1 false)\n";
let motion = "%hit = call { i32, float, i32, i32, ptr addrspace(1), <2 x float>, i1 } \
@air.intersect.triangle_data.primitive_motion(<3 x float> zeroinitializer, <3 x float> \
zeroinitializer, float 0.0, float 1.0, ptr addrspace(1) %as, float 0.0, ptr addrspace(1) %table, \
ptr null, i64 0, i32 1, i32 2, i32 0, i32 0, i32 0, i32 3, i32 -1, i32 -1, i32 0, i1 false)\n";
let instanced = "%hit = call { i32, float, i32, i32, ptr addrspace(1), i32, i32, \
<2 x float>, i1 } @air.intersect.instancing.triangle_data(<3 x float> zeroinitializer, \
<3 x float> zeroinitializer, float 0.0, float 1.0, ptr addrspace(1) %as, i32 255, \
ptr addrspace(1) %table, ptr null, i64 0, i32 1, i32 2, i32 0, i32 0, i32 0, i32 3, i32 -1, \
i32 -1, i32 0, i1 false, i1 false)\n";
// Everything after the payload stride, by name, or `None` when the line has no stride.
let tail = |line: &str| {
line.split_once("i64 %payload_stride, ").map(|(_, rest)| {
rest.trim_end_matches([')', ' ', '{'])
.split(", ")
.filter_map(|operand| operand.split_whitespace().last().map(str::to_string))
.collect::<Vec<_>>()
})
};
for source in [plain, motion, instanced] {
let lowered = lower_callback_free_triangle_queries(source).expect("lowered");
let mut cores = 0usize;
let mut wrappers = 0usize;
let mut definition: Option<Vec<String>> = None;
for line in lowered.lines() {
let trimmed = line.trim_start();
if line.starts_with("define internal") {
definition = tail(line);
if line.contains("callback_free.triangle_data(")
|| line.contains("callback_free.instancing.triangle_data(")
{
cores += 1;
let names = definition.clone().expect("a core takes a payload stride");
assert_eq!(
&names[..2],
["%front_facing_winding", "%triangle_cull_mode"],
"the two operands AIR puts after the payload stride are the winding \
and the cull mode: {line}"
);
}
continue;
}
// A wrapper adds its extra operand before the trailing block, so it must hand that
// block on unshifted: its call's tail is its own parameter tail, name for name.
if trimmed.starts_with("%full = call")
&& trimmed.contains("@metal2vulkan.intersect.callback_free")
{
wrappers += 1;
assert_eq!(
tail(line),
definition,
"a wrapper must forward the trailing operand block unshifted: {line}"
);
}
}
assert!(cores >= 1, "no triangle core was emitted: {lowered}");
assert!(wrappers >= 1, "no wrapper was emitted: {lowered}");
// The front face is whichever determinant sign the winding names, so facing can no
// longer be a bare comparison against zero: the cull mode and the front-facing result
// field are the same question, and both need the winding asked first.
assert!(
!lowered.contains("%front = fcmp ogt float %det"),
"facing must follow the winding: {lowered}"
);
assert!(
lowered.contains("%front = or i1 %front_cw, %front_ccw"),
"facing must follow the winding: {lowered}"
);
assert!(
lowered.contains("%kept = and i1 %keep_front, %keep_back"),
"a culled hit must not reach the result: {lowered}"
);
}
}
#[test]
fn single_level_instancing_uses_the_authored_identity_instance_shadow() {
let ll = "%hit = call { i32, float, i32, i32, ptr addrspace(1), i32, i32, <2 x float>, i1 } @air.intersect.instancing.triangle_data(<3 x float> zeroinitializer, <3 x float> zeroinitializer, float 0.0, float 1.0, ptr addrspace(1) %as, i32 255, ptr addrspace(1) %table, ptr null, i64 0, i32 0, i32 0, i32 0, i32 0, i32 0, i32 0, i32 -1, i32 -1, i32 0, i1 false, i1 false)\n%instance = extractvalue { i32, float, i32, i32, ptr addrspace(1), i32, i32, <2 x float>, i1 } %hit, 6\n";
+3 -3
View File
@@ -154,8 +154,8 @@ impl Graph {
.filter_map(|target| index.get(target).map(|target| swap(*target)))
.collect();
}
let predecessors = crate::native::dominators::build_predecessors(&successors);
let (_, intervals, _) = crate::native::dominators::dominance(&successors, &predecessors);
let predecessors = crate::dominators::build_predecessors(&successors);
let (_, intervals, _) = crate::dominators::dominance(&successors, &predecessors);
Dominators {
block: index
.into_iter()
@@ -188,7 +188,7 @@ impl Dominators {
else {
return false;
};
crate::native::dominators::dominates_interval(&self.intervals, ancestor, node)
crate::dominators::dominates_interval(&self.intervals, ancestor, node)
}
/// How many blocks the tree numbers, which is what the linear bound is about.
+123 -5
View File
@@ -972,6 +972,30 @@ pub(crate) fn construct_cfg_functions_module(
.then_some(function.def.as_ref().and_then(|def| def.result_id))
.flatten()
}));
// The two proxies above name a MISSING owner (a conditional with no merge, a back edge with no
// loop). A construct can also be owned and still badly nested, and that is what helper inlining
// produces: the callee's `OpReturn` becomes a branch to the caller's continuation, so a
// selection arm that used to terminate the function now leaves the construct through a block
// that is not its merge. Ask the owned contract itself which functions a control-flow rewrite is
// answerable for, instead of enumerating the ways one can be broken -- the same question, in the
// same words, that the module-wide gate asks a few steps later.
let value_types = module
.all_inst_iter()
.filter_map(|instruction| Some((instruction.result_id?, instruction.result_type?)))
.collect::<HashMap<_, _>>();
selected.extend(module.functions.iter().filter_map(|function| {
crate::native::owned_cfg::owned_function_construction_error(function, &value_types)?;
function.def.as_ref().and_then(|def| def.result_id)
}));
// A function that is already structured needs no construction, and neither construction offers
// one for it, so leaving it in `selected` turns "nothing to do" into "no construction was
// available" -- which the caller reads as a module-level failure.
selected.retain(|id| {
!module.functions.iter().any(|function| {
function.def.as_ref().and_then(|def| def.result_id) == Some(*id)
&& function_is_already_structured(function)
})
});
if selected.is_empty() {
return Ok(());
}
@@ -1127,6 +1151,31 @@ pub(crate) fn unowned_selection_header_labels(
.collect()
}
/// Whether a function is one block ending without a successor, and so is already structured.
///
/// Such a function has no selection to merge and no loop to close. Neither the nesting structurizer
/// nor the state-machine construction can change it, and neither needs to.
///
/// It still reaches selection, because `construction_names` is decided by typed source planning --
/// before helper inlining and constant folding run. By the time construction happens, a named
/// function can have collapsed to its entry block. The state-machine construction then declines it,
/// correctly and by name (`too-few-blocks`), and with nothing else selected the caller reports that
/// no construction was available. That is a module-level failure, and the recovery is to rebuild
/// EVERY buffer in the module as raw bytes: 79 of the 14579 corpus sources lose their typed buffer
/// representation this way, for a function that was already fine.
fn function_is_already_structured(function: &crate::spirv_module::Function) -> bool {
let [block] = function.blocks.as_slice() else {
return false;
};
!matches!(
block
.instructions
.last()
.map(|instruction| instruction.class.opcode),
Some(Op::Branch | Op::BranchConditional | Op::Switch)
)
}
pub(crate) fn function_has_unowned_backedge(function: &crate::spirv_module::Function) -> bool {
let labels = function
.blocks
@@ -1185,7 +1234,7 @@ pub(crate) fn function_has_unowned_backedge(function: &crate::spirv_module::Func
predecessors[successor].push(block);
}
}
let (reachable, dominance, _) = super::dominators::dominance(&successors, &predecessors);
let (reachable, dominance, _) = crate::dominators::dominance(&successors, &predecessors);
let loop_headers = function
.blocks
.iter()
@@ -1506,7 +1555,8 @@ mod tests {
Some(21),
vec![Operand::IdRef(4), Operand::IdRef(6)],
),
"native emitter: owned IAdd operands do not match its result type",
"native emitter: owned IAdd operands do not match its result type: operand 1 is \
%6, of type %2 (TypeFloat 32), but the result type is %1 (TypeInt 32 0)",
),
(
inst(
@@ -1533,11 +1583,13 @@ mod tests {
Some(21),
vec![Operand::IdRef(7), Operand::IdRef(4)],
),
"native emitter: owned LogicalAnd operands do not match its result type",
"native emitter: owned LogicalAnd operands do not match its result type: \
operand 1 is %4, of type %1 (TypeInt 32 0), but the result type is %3 (TypeBool)",
),
(
inst(Op::CopyObject, Some(1), Some(21), vec![Operand::IdRef(6)]),
"native emitter: owned CopyObject operands do not match its result type",
"native emitter: owned CopyObject operands do not match its result type: \
operand 0 is %6, of type %2 (TypeFloat 32), but the result type is %1 (TypeInt 32 0)",
),
(
inst(
@@ -1623,7 +1675,10 @@ mod tests {
assert_eq!(
owned_invalid_error(&module).as_deref(),
Some("native emitter: owned IAdd operands do not match its result type")
Some(
"native emitter: owned IAdd operands do not match its result type: operand 0 is \
%4, of type %1 (TypeInt 32 0), but the result type is %2 (TypeFloat 32)"
)
);
let bytes = module
.assemble()
@@ -1929,6 +1984,69 @@ mod tests {
assert_eq!(module.functions[0].blocks.len(), 2);
}
/// Typed source planning names the functions to construct before helper inlining and constant
/// folding run, so a named function can be one block by the time construction happens. Neither
/// construction changes such a function and neither needs to, but reporting that as "no
/// construction was available" makes the caller rebuild every buffer in the module as raw
/// bytes. 79 of the 14579 corpus sources took that recovery for a function already fine.
#[test]
fn a_named_function_folded_to_one_returning_block_needs_no_construction() {
let mut module = Module::new();
module.header = Some(ModuleHeader::new(20));
let mut function = Function::new();
function.def = Some(inst(Op::Function, None, Some(15), vec![]));
function.blocks = vec![Block {
label: Some(inst(Op::Label, None, Some(16), vec![])),
instructions: vec![inst(Op::Return, None, None, vec![])],
}];
module.functions.push(function);
module.debug_names.push(inst(
Op::Name,
None,
None,
vec![
Operand::IdRef(15),
Operand::LiteralString("folded_helper".to_string()),
],
));
construct_cfg_functions_module(&mut module, &HashSet::from(["folded_helper".to_string()]))
.expect("a single returning block is already structured");
assert_eq!(module.functions[0].blocks.len(), 1);
}
/// The exception: one block can still branch to ITSELF, which is a loop with no structured
/// merge. That one is not already structured and must stay selected.
#[test]
fn a_named_function_whose_one_block_branches_to_itself_stays_selected() {
let mut module = Module::new();
module.header = Some(ModuleHeader::new(20));
let mut function = Function::new();
function.def = Some(inst(Op::Function, None, Some(15), vec![]));
function.blocks = vec![Block {
label: Some(inst(Op::Label, None, Some(16), vec![])),
instructions: vec![inst(Op::Branch, None, None, vec![Operand::IdRef(16)])],
}];
module.functions.push(function);
module.debug_names.push(inst(
Op::Name,
None,
None,
vec![
Operand::IdRef(15),
Operand::LiteralString("self_loop".to_string()),
],
));
let error =
construct_cfg_functions_module(&mut module, &HashSet::from(["self_loop".to_string()]))
.expect_err("a self-branching block is not already structured");
assert!(
error.contains("cannot be constructed"),
"expected the selection to survive to the decline, got {error}"
);
}
#[test]
fn unowned_conditional_selects_construction_without_validation() {
let mut module = Module::new();
File diff suppressed because it is too large. Load diff
+185 -4
View File
@@ -1,7 +1,9 @@
#![allow(unused_imports)]
use super::super::cfg::{
id_ref_operand, infer_branch_merges, infer_loop_merges, infer_switch_merges,
lower_unstructured_switches, split_body_blocks, BodyBlock,
exceeds_local_structured_plan_budget, id_ref_operand, infer_branch_merges,
infer_direct_switch_merges, infer_loop_merges, infer_switch_merges,
infer_switch_merges_bounded, loop_forest_is_empty, lower_unstructured_switches,
split_body_blocks, BodyBlock, CROSS_ARM_EDGE_MAX_BLOCKS,
};
use super::super::emit_vulkan_spirv;
use super::super::emitter::Emitter;
@@ -263,11 +265,11 @@ b:
failure.error
);
assert_eq!(
failure.ordinary_plan_rejected_functions,
failure.rejected.ordinary_plan_functions,
HashSet::from(["k".to_string()])
);
assert_eq!(
failure.ownership_plan_rejected_functions,
failure.rejected.ownership_plan_functions,
HashSet::from(["k".to_string()])
);
}
@@ -5088,3 +5090,182 @@ entry:
);
tools::spirv_val_bytes(&out, &tmp).expect("spirv-val");
}
/// A CFG the local structured planner declines for *branching density* still gets the complete
/// switch-merge inference. `exceeds_local_structured_plan_budget` bounds repeated per-header
/// ownership planning, which is not what `infer_switch_merges` costs — that cost is the candidate
/// scan, and it is bounded by block count. Downgrading to the direct-edge subset here leaves the
/// switch without a merge and sends the whole module to raw-buffer construction, so the bound has to
/// be the block count both fallbacks already agree on.
#[test]
fn dense_small_cfg_keeps_complete_switch_merge_inference() {
let mut ll = String::from(
"define void @dense(i1 %c, i32 %sel) {\n\
entry:\n\
\x20 switch i32 %sel, label %d [\n\
\x20 i32 0, label %a\n\
\x20 i32 1, label %b\n\
\x20 ]\n\
a:\n\
\x20 br label %a2\n\
a2:\n\
\x20 br label %merge\n\
b:\n\
\x20 br label %b2\n\
b2:\n\
\x20 br label %merge\n\
d:\n\
\x20 br label %merge\n\
merge:\n\
\x20 br label %n0\n",
);
// 45 diamonds: 99 blocks (under the 128-block ceiling) with 45 branching headers, so the
// block-count term admits the graph and only the density term rejects it.
const DIAMONDS: usize = 45;
for i in 0..DIAMONDS {
ll.push_str(&format!(
"n{i}:\n br i1 %c, label %t{i}, label %n{next}\nt{i}:\n br label %n{next}\n",
next = i + 1
));
}
ll.push_str(&format!("n{DIAMONDS}:\n ret void\n}}\n"));
let blocks = super::super::ir::LlModule::parse(&ll)
.expect("parse")
.functions
.into_iter()
.find(|function| function.name == "dense")
.expect("dense function")
.blocks;
assert!(
exceeds_local_structured_plan_budget(&blocks),
"the density term must be what declines this graph: {} blocks",
blocks.len()
);
assert!(blocks.len() <= CROSS_ARM_EDGE_MAX_BLOCKS);
assert_eq!(
infer_direct_switch_merges(&blocks).get("%entry"),
None,
"arms reconverge through an intermediate block, so the direct subset proves nothing",
);
assert_eq!(
infer_switch_merges_bounded(&blocks).get("%entry"),
Some(&"%merge".to_string()),
);
}
/// Above `CROSS_ARM_EDGE_MAX_BLOCKS` the bounded inference is still the linear direct subset: that
/// is the bound the complete candidate scan actually costs against.
#[test]
fn oversized_cfg_keeps_the_direct_switch_merge_subset() {
let mut ll = String::from(
"define void @wide(i32 %sel) {\n\
entry:\n\
\x20 switch i32 %sel, label %d [\n\
\x20 i32 0, label %a\n\
\x20 i32 1, label %b\n\
\x20 ]\n\
a:\n\
\x20 br label %a2\n\
a2:\n\
\x20 br label %merge\n\
b:\n\
\x20 br label %b2\n\
b2:\n\
\x20 br label %merge\n\
d:\n\
\x20 br label %merge\n\
merge:\n\
\x20 br label %p0\n",
);
let pad = CROSS_ARM_EDGE_MAX_BLOCKS + 1;
for i in 0..pad {
ll.push_str(&format!("p{i}:\n br label %p{next}\n", next = i + 1));
}
ll.push_str(&format!("p{pad}:\n ret void\n}}\n"));
let blocks = super::super::ir::LlModule::parse(&ll)
.expect("parse")
.functions
.into_iter()
.find(|function| function.name == "wide")
.expect("wide function")
.blocks;
assert!(blocks.len() > CROSS_ARM_EDGE_MAX_BLOCKS);
assert_eq!(
infer_switch_merges_bounded(&blocks),
infer_direct_switch_merges(&blocks),
);
assert_eq!(infer_switch_merges_bounded(&blocks).get("%entry"), None);
}
/// Build a CFG that only the *density* term of `exceeds_local_structured_plan_budget` declines: one
/// conditional whose arms reconverge two hops apart, then `DIAMONDS` two-way diamonds. `back_edge`
/// closes the chain into a natural loop without changing the block count.
#[cfg(test)]
fn dense_diamond_chain(back_edge: bool) -> Vec<BodyBlock> {
const DIAMONDS: usize = 45;
let mut ll = String::from(
"define void @dense(i1 %c) {\n\
entry:\n\
\x20 br i1 %c, label %a, label %b\n\
a:\n\
\x20 br label %a2\n\
a2:\n\
\x20 br label %join\n\
b:\n\
\x20 br label %b2\n\
b2:\n\
\x20 br label %join\n\
join:\n\
\x20 br label %n0\n",
);
for i in 0..DIAMONDS {
ll.push_str(&format!(
"n{i}:\n br i1 %c, label %t{i}, label %n{next}\nt{i}:\n br label %n{next}\n",
next = i + 1
));
}
ll.push_str(&if back_edge {
format!("n{DIAMONDS}:\n br i1 %c, label %n0, label %exit\nexit:\n ret void\n}}\n")
} else {
format!("n{DIAMONDS}:\n ret void\n}}\n")
});
super::super::ir::LlModule::parse(&ll)
.expect("parse")
.functions
.into_iter()
.find(|function| function.name == "dense")
.expect("dense function")
.blocks
}
/// A loop-free CFG the local planner declined for branching density still gets the complete
/// branch-merge inference. Like the switch case above, `infer_branch_merges` costs the candidate
/// scan, not the per-header ownership planning the budget was bounding.
#[test]
fn loop_free_dense_cfg_keeps_complete_branch_merge_inference() {
let blocks = dense_diamond_chain(false);
assert!(exceeds_local_structured_plan_budget(&blocks));
assert!(blocks.len() <= CROSS_ARM_EDGE_MAX_BLOCKS);
assert!(loop_forest_is_empty(&blocks));
assert_eq!(
infer_branch_merges(&blocks).get(&("%a".to_string(), "%b".to_string())),
Some(&"%join".to_string()),
"arms reconverge two hops apart, so only the complete inference proves the merge",
);
}
/// The same CFG with one back edge keeps the bounded header subset. The skip path clears
/// `loop_merges` because the block order was never structurized, so handing the emitter selection
/// merges for a CFG that also has loop constructs describes only half the construct tree -- measured
/// as two modules that stopped translating at all until this gate was added.
#[test]
fn a_loop_in_a_dense_cfg_declines_the_complete_branch_merge_inference() {
let blocks = dense_diamond_chain(true);
assert!(exceeds_local_structured_plan_budget(&blocks));
assert!(blocks.len() <= CROSS_ARM_EDGE_MAX_BLOCKS);
assert!(!loop_forest_is_empty(&blocks));
}
+536 -3
View File
@@ -348,6 +348,50 @@ attributes #0 = { nounwind }
}
}
/// `StencilRefReplacingEXT` is to `FragStencilRefEXT` what `DepthReplacing` is to `FragDepth`: the
/// declaration that this shader replaces the value. spirv-val does not demand it -- all 6 corpus
/// sources that write the builtin passed without it -- so the pair below is asserted against
/// glslang, which emits exactly this capability, extension and mode for `gl_FragStencilRefARB`.
#[test]
fn native_fragment_stencil_return_declares_the_replacing_execution_mode() {
let ll = r#"
source_filename = "synth_stencil"
target datalayout = "e-p:64:64:64"
target triple = "air64-apple-macosx14.0.0"
define <{ i32 }> @synth_stencil(<4 x float> %position) local_unnamed_addr #0 {
%z = extractelement <4 x float> %position, i64 2
%i = bitcast float %z to i32
%2 = insertvalue <{ i32 }> undef, i32 %i, 0
ret <{ i32 }> %2
}
attributes #0 = { nounwind }
!air.fragment = !{!0}
!0 = !{ptr @synth_stencil, !1, !3}
!1 = !{!2}
!2 = !{!"air.stencil", !"air.arg_type_name", !"uint", !"air.arg_name", !"stencil"}
!3 = !{!4}
!4 = !{i32 0, !"air.position", !"air.center", !"air.arg_type_name", !"float4", !"air.arg_name", !"position"}
"#;
let tmp = std::env::temp_dir().join(format!(
"metal2vulkan_native_stencil_{}",
std::process::id()
));
let _ = std::fs::create_dir_all(&tmp);
let out = crate::translate_sanitized_native(ll, Stage::Fragment, &tmp).expect("translate");
let asm = disassemble(&out).expect("disassemble transformed");
let _ = std::fs::remove_dir_all(&tmp);
assert!(asm.contains("BuiltIn FragStencilRefEXT"), "{asm}");
assert!(asm.contains("OpCapability StencilExportEXT"), "{asm}");
assert!(
asm.contains(r#"OpExtension "SPV_EXT_shader_stencil_export""#),
"{asm}"
);
assert!(asm.contains("StencilRefReplacingEXT"), "{asm}");
}
#[test]
fn native_vertex_viewport_array_index_declares_vulkan_capability() {
let ll = r#"
@@ -588,6 +632,240 @@ attributes #0 = { nounwind }
}
}
/// Metal vertex amplification and Vulkan multiview are one feature: the draw is rasterized into
/// several views and the shader is told which one it is running for. Every stage that reads
/// `[[amplification_id]]` must therefore reach `BuiltIn ViewIndex` -- a plain vertex entry as much
/// as a fragment one -- **once the caller says the pass has more than one view**.
///
/// At the default count of one there is no view to be told about: the amplification id is zero at
/// every vertex by definition, so the constant is the exact answer rather than the zero-binding
/// fallthrough this test was originally written against. Both halves are asserted here because they
/// are the same claim from two sides -- the constant must not appear when a second view exists, and
/// the builtin must not appear when only one does, since a `ViewIndex` input beside a `Layer`
/// output is MSL that Metal refuses to compile.
#[test]
fn amplification_id_reaches_the_view_index_builtin_in_every_stage_that_declares_it() {
let vertex = r#"
source_filename = "synth_vertex_amplification_id"
target datalayout = "e-p:64:64:64"
target triple = "air64-apple-macosx14.0.0"
define <4 x float> @vert(i16 %amp) local_unnamed_addr #0 {
%wide = zext i16 %amp to i32
%f = uitofp i32 %wide to float
%v = insertelement <4 x float> zeroinitializer, float %f, i64 0
ret <4 x float> %v
}
attributes #0 = { nounwind }
!air.vertex = !{!0}
!0 = !{ptr @vert, !1, !3}
!1 = !{!2}
!2 = !{i32 0, !"air.position", !"air.arg_type_name", !"float4", !"air.arg_name", !"pos"}
!3 = !{!4}
!4 = !{i32 0, !"air.amplification_id", !"air.arg_type_name", !"ushort", !"air.arg_name", !"amp"}
"#;
let fragment = r#"
source_filename = "synth_fragment_amplification_id"
target datalayout = "e-p:64:64:64"
target triple = "air64-apple-macosx14.0.0"
define i16 @frag(i16 %amp) local_unnamed_addr #0 {
ret i16 %amp
}
attributes #0 = { nounwind }
!air.fragment = !{!0}
!0 = !{ptr @frag, !1, !3}
!1 = !{!2}
!2 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"ushort", !"air.arg_name", !"color"}
!3 = !{!4}
!4 = !{i32 0, !"air.amplification_id", !"air.arg_type_name", !"ushort", !"air.arg_name", !"amp"}
"#;
let tmp = std::env::temp_dir().join(format!(
"metal2vulkan_amplification_id_{}",
std::process::id()
));
let _ = std::fs::create_dir_all(&tmp);
for (stage, ll) in [(Stage::Vertex, vertex), (Stage::Fragment, fragment)] {
// One view: no multiview interface at all, and the parameter reads the constant zero.
let single = crate::translate_sanitized_native(ll, stage, &tmp)
.unwrap_or_else(|e| panic!("translate {stage:?}: {e}"));
let single_asm = disassemble(&single).expect("disassemble single-view");
assert!(
!single_asm.contains("BuiltIn ViewIndex"),
"{stage:?} declares ViewIndex for a single-view pass: {single_asm}"
);
assert!(
!single_asm.contains("OpCapability MultiView"),
"{stage:?} declares MultiView for a single-view pass: {single_asm}"
);
tools::spirv_val_bytes(&single, &tmp).expect("spirv-val single-view");
let options = crate::passes::TransformOptions {
vertex_amplification_count: 2,
..crate::passes::TransformOptions::default()
};
let out = crate::translate_sanitized_native_with_options(ll, stage, &tmp, options)
.unwrap_or_else(|e| panic!("translate {stage:?}: {e}"));
let module = load_bytes(&out).expect("parse transformed");
let view_var = module
.annotations
.iter()
.find_map(|inst| match inst.operands.as_slice() {
[
Operand::IdRef(var),
Operand::Decoration(Decoration::BuiltIn),
Operand::BuiltIn(BuiltIn::ViewIndex),
] => Some(*var),
_ => None,
})
.unwrap_or_else(|| panic!("{stage:?} declares no ViewIndex builtin"));
// The value the body reads is the builtin, not a constant: a zero binding is exactly the
// bug, and it leaves no Input variable behind at all.
assert!(
module
.functions
.iter()
.flat_map(|function| &function.blocks)
.flat_map(|block| &block.instructions)
.any(|inst| inst.class.opcode == Op::Load
&& inst.operands.first() == Some(&Operand::IdRef(view_var))),
"{stage:?} declares ViewIndex but never loads it"
);
let asm = disassemble(&out).expect("disassemble transformed");
assert!(asm.contains("OpCapability MultiView"), "{stage:?}: {asm}");
// Only a fragment Input needs the interpolation decoration an integer cannot do without.
assert_eq!(
matches!(stage, Stage::Fragment),
module.annotations.iter().any(|inst| {
inst.class.opcode == Op::Decorate
&& inst.operands.first() == Some(&Operand::IdRef(view_var))
&& inst.operands.get(1) == Some(&Operand::Decoration(Decoration::Flat))
}),
"{stage:?}: {asm}"
);
tools::spirv_val_bytes(&out, &tmp).expect("spirv-val");
}
let _ = std::fs::remove_dir_all(&tmp);
}
/// `[[amplification_count]]` is a number the render encoder chose, and Vulkan has no builtin to
/// read it back from -- so the caller states it and the parameter binds that constant.
///
/// Before this it had no binding arm at all. It was in `VERTEX_INPUT_ROLES`, so the unmodelled-role
/// refusal stayed quiet, and the parameter fell off the end of the chain to the zero binding: 126
/// corpus vertex modules read an amplification count of zero, which is a count Metal never returns
/// because the encoder's minimum is one. A count is not a view index, so unlike
/// `[[amplification_id]]` this one never becomes a builtin at any count.
#[test]
fn amplification_count_binds_the_count_the_caller_states() {
let ll = r#"
source_filename = "synth_vertex_amplification_count"
target datalayout = "e-p:64:64:64"
target triple = "air64-apple-macosx14.0.0"
define <4 x float> @vert(i16 %count) local_unnamed_addr #0 {
%wide = zext i16 %count to i32
%f = uitofp i32 %wide to float
%v = insertelement <4 x float> zeroinitializer, float %f, i64 0
ret <4 x float> %v
}
attributes #0 = { nounwind }
!air.vertex = !{!0}
!0 = !{ptr @vert, !1, !3}
!1 = !{!2}
!2 = !{i32 0, !"air.position", !"air.arg_type_name", !"float4", !"air.arg_name", !"pos"}
!3 = !{!4}
!4 = !{i32 0, !"air.amplification_count", !"air.arg_type_name", !"ushort", !"air.arg_name", !"count"}
"#;
let tmp = std::env::temp_dir().join(format!(
"metal2vulkan_amplification_count_{}",
std::process::id()
));
let _ = std::fs::create_dir_all(&tmp);
for count in [1u32, 2, 4] {
let options = crate::passes::TransformOptions {
vertex_amplification_count: count,
..crate::passes::TransformOptions::default()
};
let out = crate::translate_sanitized_native_with_options(ll, Stage::Vertex, &tmp, options)
.unwrap_or_else(|e| panic!("translate at count {count}: {e}"));
let asm = disassemble(&out).expect("disassemble transformed");
assert!(
!asm.contains("BuiltIn ViewIndex"),
"a count is not a view index, at count {count}: {asm}"
);
assert!(
asm.lines().any(|line| line.contains("= OpConstant ")
&& line.split_whitespace().last() == Some(&count.to_string())),
"count {count} is not the constant the parameter reads: {asm}"
);
tools::spirv_val_bytes(&out, &tmp).expect("spirv-val");
}
let _ = std::fs::remove_dir_all(&tmp);
}
/// The same count answers a fragment, because it is a property of the draw and not of the stage.
///
/// `FragRole` modelled `[[amplification_id]]` but had no `[[amplification_count]]` variant at all,
/// so a fragment declaring it decoded to `FragRole::Other` and the module was refused as carrying a
/// role with no lowering -- while the binding arm in the stage-input pass was already stage-agnostic
/// and would have answered it. 4 of the 14579 local corpus sources declare the role on a fragment;
/// the 2 that read it were refused, and this closes both.
#[test]
fn fragment_amplification_count_binds_the_same_count_the_vertex_stage_does() {
let ll = r#"
source_filename = "synth_fragment_amplification_count"
target datalayout = "e-p:64:64:64"
target triple = "air64-apple-macosx14.0.0"
define i32 @frag(i16 %count) local_unnamed_addr #0 {
%wide = zext i16 %count to i32
ret i32 %wide
}
attributes #0 = { nounwind }
!air.fragment = !{!0}
!0 = !{ptr @frag, !1, !3}
!1 = !{!2}
!2 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"uint"}
!3 = !{!4}
!4 = !{i32 0, !"air.amplification_count", !"air.arg_type_name", !"ushort", !"air.arg_name", !"count"}
"#;
let tmp = std::env::temp_dir().join(format!(
"metal2vulkan_frag_amplification_count_{}",
std::process::id()
));
let _ = std::fs::create_dir_all(&tmp);
for count in [1u32, 2, 4] {
let options = crate::passes::TransformOptions {
vertex_amplification_count: count,
..crate::passes::TransformOptions::default()
};
let out =
crate::translate_sanitized_native_with_options(ll, Stage::Fragment, &tmp, options)
.unwrap_or_else(|e| panic!("translate at count {count}: {e}"));
let asm = disassemble(&out).expect("disassemble transformed");
assert!(
!asm.contains("BuiltIn ViewIndex"),
"a count is not a view index, at count {count}: {asm}"
);
assert!(
asm.lines().any(|line| line.contains("= OpConstant ")
&& line.split_whitespace().last() == Some(&count.to_string())),
"count {count} is not the constant the parameter reads: {asm}"
);
tools::spirv_val_bytes(&out, &tmp).expect("spirv-val");
}
let _ = std::fs::remove_dir_all(&tmp);
}
#[test]
fn native_fragment_render_target_array_index_uses_builtin_layer_input() {
let ll = r#"
@@ -923,6 +1201,12 @@ attributes #0 = { nounwind }
assert!(asm.contains("BuiltIn PrimitiveId"), "{asm}");
assert!(asm.contains("OpEntryPoint Fragment"), "{asm}");
assert!(asm.contains("OpLoad"), "{asm}");
// `PrimitiveId` is enabled by any of `Geometry`, `Tessellation`, `RayTracingKHR` or
// `MeshShadingEXT`. Declaring a capability is asking a consumer to enable the feature behind
// it, and Metal has no geometry stage at all, so `geometryShader` is the one disjunct no
// Metal-backed implementation can grant. See `passes::module_cleanup`.
assert!(asm.contains("OpCapability Tessellation"), "{asm}");
assert!(!asm.contains("OpCapability Geometry"), "{asm}");
assert!(
!asm.lines()
.any(|line| line.contains("OpUndef") && line.contains("%1")),
@@ -1895,8 +2179,109 @@ target triple = "spirv-unknown-vulkan1.2"
}
}
/// Every member of the AIR execution-group family lowers, for BOTH group widths and under the
/// `dispatch_` spelling.
///
/// Metal's quadgroup is four threads and its simdgroup thirty-two, and each of the family's facts is
/// one derivation over that width. Written per group, `air.quadgroups_per_threadgroup` was the
/// member nobody had copied the derivation for -- a kernel declaring it was rejected outright, and a
/// gated one read a zero where the hardware had a count. The two widths must therefore appear here
/// together, so a member cannot be added for one and forgotten for the other.
#[test]
fn native_kernel_map_screen_to_physical_1x1_map_lowers_to_zero() {
fn native_kernel_execution_group_family_lowers_for_both_widths() {
let ll = r#"
target triple = "spirv-unknown-vulkan1.2"
define void @main(i32 %quad_lane, i32 %quad_group, i32 %quads, i32 %lane, i32 %simd_group, i32 %simds, i32 %simd_width) {
entry:
%a = add i32 %quad_lane, %quad_group
%b = add i32 %a, %quads
%c = add i32 %b, %lane
%d = add i32 %c, %simd_group
%e = add i32 %d, %simds
%f = add i32 %e, %simd_width
%ok = icmp uge i32 %f, 0
ret void
}
!air.kernel = !{!0}
!0 = !{ptr @main, !1, !2}
!1 = !{}
!2 = !{!3, !4, !5, !6, !7, !8, !9}
!3 = !{i32 0, !"air.thread_index_in_quadgroup", !"air.arg_type_name", !"uint", !"air.arg_name", !"quad_lane"}
!4 = !{i32 1, !"air.quadgroup_index_in_threadgroup", !"air.arg_type_name", !"uint", !"air.arg_name", !"quad_group"}
!5 = !{i32 2, !"air.quadgroups_per_threadgroup", !"air.arg_type_name", !"uint", !"air.arg_name", !"quads"}
!6 = !{i32 3, !"air.thread_index_in_simdgroup", !"air.arg_type_name", !"uint", !"air.arg_name", !"lane"}
!7 = !{i32 4, !"air.simdgroup_index_in_threadgroup", !"air.arg_type_name", !"uint", !"air.arg_name", !"simd_group"}
!8 = !{i32 5, !"air.dispatch_simdgroups_per_threadgroup", !"air.arg_type_name", !"uint", !"air.arg_name", !"simds"}
!9 = !{i32 6, !"air.threads_per_simdgroup", !"air.arg_type_name", !"uint", !"air.arg_name", !"simd_width"}
"#;
let module = load_bytes(emit_vulkan_spirv(ll).expect("native emit")).expect("load native spv");
let out = passes::transform(
module,
Stage::Kernel,
None,
None,
meta::parse_air_kernel_meta(ll).as_ref(),
meta::entry_name(ll, "kernel").as_deref(),
)
.expect("interface transform")
.assemble()
.iter()
.flat_map(|w| w.to_le_bytes())
.collect::<Vec<_>>();
let asm = disassemble(&out).expect("disassemble transformed");
// No parameter may fall through to the zero/undef binding: that is the silent read this family
// exists to avoid.
assert!(!asm.contains("OpUndef"), "{asm}");
// A lane index is the threadgroup index masked to the group width, a group index is that index
// divided by it, and a group count rounds the local size up by it -- all exact, because every
// width is a power of two. Both widths must appear for each, or one group is unlowered.
let mut constants = std::collections::HashMap::new();
for line in asm.lines().map(str::trim) {
let Some((id, rest)) = line.split_once(" = Op") else {
continue;
};
let Some(last) = rest.split_whitespace().last() else {
continue;
};
// A divisor is emitted through the pass that keeps a specialized local size from dividing by
// zero, so it reaches OpUDiv as `OpSelect %cond %1 %width`. The width is the false arm.
let value = if rest.starts_with("Constant ") {
last.parse::<u32>().ok()
} else if rest.starts_with("Select ") {
constants.get(last).copied()
} else {
None
};
if let Some(value) = value {
constants.insert(id.to_string(), value);
}
}
let operand_values = |op: &str| {
asm.lines()
.filter(|line| line.contains(&format!(" = {op} ")))
.filter_map(|line| constants.get(line.split_whitespace().last()?).copied())
.collect::<std::collections::BTreeSet<_>>()
};
assert_eq!(
operand_values("OpBitwiseAnd"),
[3, 31].into_iter().collect(),
"a lane index is masked to its own group's width\n{asm}"
);
assert_eq!(
operand_values("OpShiftRightLogical"),
[2, 5].into_iter().collect(),
"a group index divides by its own group's width\n{asm}"
);
assert_eq!(
operand_values("OpUDiv"),
[4, 32].into_iter().collect(),
"a group count divides by its own group's width\n{asm}"
);
}
#[test]
fn native_kernel_map_screen_to_physical_uniform_map_is_the_identity() {
let ll = r#"
target triple = "spirv-unknown-vulkan1.2"
@@ -1927,8 +2312,10 @@ declare <2 x float> @air.map_screen_to_physical_coordinates.v2f32.p2i8.i32(<2 x
let _ = std::fs::create_dir_all(&tmp);
let spv = crate::translate_sanitized_native(ll, Stage::Kernel, &tmp).expect("translate");
let asm = disassemble(&spv).expect("disassemble");
assert!(asm.contains("OpCompositeConstruct"), "{asm}");
assert!(!asm.contains("OpCopyObject"), "{asm}");
// A uniform rate-1.0 map makes the physical grid the screen grid, so the screen coordinate
// passes through unchanged - the same direction its inverse already answered. Metal agrees on
// device; see `lower_map_screen_to_physical`.
assert!(asm.contains("OpCopyObject"), "{asm}");
assert!(!asm.contains("OpFunctionCall"), "{asm}");
assert!(!asm.contains("map_screen_to_physical"), "{asm}");
if std::process::Command::new("spirv-val")
@@ -2130,3 +2517,149 @@ entry:
tools::spirv_val_bytes(&spv, &tmp).expect("spirv-val");
}
}
/// A fragment entry gets the execution-group facts that do not need a threadgroup, and is refused
/// the two that do.
///
/// Metal's simdgroup is the same thirty-two threads in a fragment shader as in a kernel, and this
/// translator states a lane's index inside it off `SubgroupLocalInvocationId` -- a builtin with no
/// workgroup in it. The family was nevertheless listed for the kernel alone, so 9 of the 14579 local
/// corpus sources were refused for declaring `[[thread_index_in_simdgroup]]` at a stage that could
/// have answered it. Which simdgroup inside the threadgroup, and how many the threadgroup holds,
/// stay refused: a fragment has no threadgroup, and a zero would be an invented answer.
#[test]
fn native_fragment_answers_the_group_facts_and_refuses_the_threadgroup_ones() {
let entry = |role: &str, arg: &str| {
format!(
r#"
source_filename = "synth_fragment_execution_group"
target datalayout = "e-p:64:64:64"
target triple = "air64-apple-macosx14.0.0"
define i32 @frag(i32 %{arg}) local_unnamed_addr #0 {{
entry:
%next = add i32 %{arg}, 1
ret i32 %next
}}
attributes #0 = {{ nounwind }}
!air.fragment = !{{!0}}
!0 = !{{ptr @frag, !1, !3}}
!1 = !{{!2}}
!2 = !{{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"uint"}}
!3 = !{{!4}}
!4 = !{{i32 0, !"{role}", !"air.arg_type_name", !"uint", !"air.arg_name", !"{arg}"}}
"#
)
};
let tmp = std::env::temp_dir().join(format!(
"metal2vulkan_fragment_execution_group_{}",
std::process::id()
));
let _ = std::fs::create_dir_all(&tmp);
let spv = crate::translate_sanitized_native(
&entry("air.thread_index_in_simdgroup", "lane"),
Stage::Fragment,
&tmp,
)
.expect("a fragment lane index lowers");
let asm = disassemble(&spv).expect("disassemble");
assert!(asm.contains("OpEntryPoint Fragment"), "{asm}");
assert!(asm.contains("BuiltIn SubgroupLocalInvocationId"), "{asm}");
// An integer fragment input cannot be interpolated, so the lane variable must be Flat.
assert!(asm.contains("Flat"), "{asm}");
assert!(asm.contains("OpBitwiseAnd"), "{asm}");
assert!(!asm.contains("BuiltIn LocalInvocationIndex"), "{asm}");
let spv = crate::translate_sanitized_native(
&entry("air.threads_per_simdgroup", "width"),
Stage::Fragment,
&tmp,
)
.expect("a fragment group width lowers");
let asm = disassemble(&spv).expect("disassemble");
assert!(
asm.lines()
.any(|line| line.contains("OpConstant ") && line.trim_end().ends_with(" 32")),
"the group's width is its width at any stage\n{asm}"
);
for (role, arg) in [
("air.simdgroup_index_in_threadgroup", "group"),
("air.simdgroups_per_threadgroup", "groups"),
] {
let err = crate::translate_sanitized_native(&entry(role, arg), Stage::Fragment, &tmp)
.expect_err("a fragment has no threadgroup to count groups in");
assert!(
err.to_string().contains(role),
"the refusal names the role it could not answer: {err}"
);
}
let _ = std::fs::remove_dir_all(&tmp);
}
/// An unmodelled entry-parameter role is refused for the value the shader would read, so a
/// parameter nothing reads is not refused.
///
/// The refusal exists because binding a zero for a role the emitter cannot answer gives the body a
/// value the hardware would have supplied, in a module that validates and reflects as though nothing
/// were missing. Its premise is that the zero reaches an instruction. Metal states the same fact on
/// the declaration as `air.arg_unused`, but the emitted module's own use list is the exact form of
/// it: the local corpus declares a role with no lowering on a parameter no instruction mentions, and
/// refusing those reported a missing value where there is no reader.
///
/// The role here is `air.render_target_array_index` on a *kernel* entry, which is the only shape
/// left in the 14579 local corpus that still refuses this way (4 sources). It used to be
/// `air.amplification_count` on a fragment, but that role is modelled now: the count is a property
/// of the draw, so the constant the vertex stage binds answers a fragment too.
#[test]
fn native_an_unmodelled_role_on_an_unread_parameter_is_not_refused() {
const READS_IT: &str = " %read = zext i32 %eye to i64\n store i64 %read, ptr addrspace(1) %out, align 8\n ret void";
let entry = |body: &str| {
format!(
r#"
source_filename = "synth_unread_unmodelled_role"
target datalayout = "e-p:64:64:64"
target triple = "air64-apple-macosx14.0.0"
define void @kern(ptr addrspace(1) %out, i32 %eye) local_unnamed_addr #0 {{
entry:
{body}
}}
attributes #0 = {{ nounwind }}
!air.kernel = !{{!0}}
!0 = !{{ptr @kern, !1, !2}}
!1 = !{{}}
!2 = !{{!3, !4}}
!3 = !{{i32 0, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 8, !"air.arg_type_align_size", i32 8, !"air.arg_type_name", !"ulong", !"air.arg_name", !"out"}}
!4 = !{{i32 1, !"air.render_target_array_index", !"air.arg_type_name", !"uint", !"air.arg_name", !"eye"}}
"#
)
};
let tmp = std::env::temp_dir().join(format!(
"metal2vulkan_unread_unmodelled_role_{}",
std::process::id()
));
let _ = std::fs::create_dir_all(&tmp);
let spv = crate::translate_sanitized_native(
&entry(" store i64 7, ptr addrspace(1) %out, align 8\n ret void"),
Stage::Kernel,
&tmp,
)
.expect("a role nothing reads supplies no value to refuse");
let asm = disassemble(&spv).expect("disassemble");
assert!(asm.contains("OpEntryPoint GLCompute"), "{asm}");
let err = crate::translate_sanitized_native(&entry(READS_IT), Stage::Kernel, &tmp)
.expect_err("the same role, read, is a value the emitter would answer with a zero");
assert!(
err.to_string().contains("air.render_target_array_index"),
"the refusal names the role whose value is missing: {err}"
);
let _ = std::fs::remove_dir_all(&tmp);
}
File diff suppressed because it is too large. Load diff
+270
View File
@@ -597,6 +597,62 @@ declare i1 @air.is_function_constant_defined(ptr addrspace(2))
}
}
#[test]
fn a_supplied_function_constant_reaches_the_implicit_predicate_initializer() {
// The shape 41 corpus sources spell: Metal answers `[[function_constant]]` definedness once in
// `air.static_init`, widens the `i1` to `i8`, normalizes it, and parks it in an implicit
// predicate global the entry never reads. Nothing folds that chain away, so the definedness
// value the AIR specializer substitutes has to be an expression the native emitter models --
// and `icmp` on `i1` is not one: no corpus source spells it and `int_compare_result_type`
// refuses it. Substituting one made every module of this shape fail to translate the moment a
// caller supplied the constant, which is the only way a caller ever runs them.
let ll = r#"
target triple = "spirv-unknown-vulkan1.2"
@__metal_implicit_fc_pred_0 = internal addrspace(2) global i8 0, align 1
@_Z8CLIPPING.MTL_FC_INIT_1_b = internal addrspace(2) externally_initialized constant i8 undef, section "air.fc_initializer", align 1
define internal void @_GLOBAL__sub_I_fc() section "air.static_init" {
entry:
%defined = tail call i1 @air.is_function_constant_defined(ptr addrspace(2) @_Z8CLIPPING.MTL_FC_INIT_1_b)
%widened = zext i1 %defined to i8
%normalized = tail call i8 @air.normalize_function_constant_predicate.i8(i8 %widened)
store i8 %normalized, ptr addrspace(2) @__metal_implicit_fc_pred_0
ret void
}
define i32 @frag() {
entry:
ret i32 7
}
!air.fragment = !{!0}
!0 = !{ptr @frag, !1, !2}
!1 = !{!3}
!2 = !{}
!3 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"int"}
declare i1 @air.is_function_constant_defined(ptr addrspace(2))
declare i8 @air.normalize_function_constant_predicate.i8(i8)
"#;
let tmp = std::env::temp_dir().join(format!(
"metal2vulkan_native_fc_implicit_predicate_{}",
std::process::id()
));
let _ = std::fs::create_dir_all(&tmp);
let specialized = crate::translate_sanitized_native_specialized_with_options(
ll,
Stage::Fragment,
&tmp,
passes::TransformOptions::default(),
&[(1, vec![1])],
)
.expect("a supplied function constant must not break the implicit predicate initializer");
tools::spirv_val_bytes(&specialized, &tmp).expect("spirv-val");
// The substituted definedness must still read as "defined", not as the unsupplied default.
let asm = disassemble(&specialized).expect("disassemble specialized");
assert!(!asm.contains("OpFunctionCall"), "{asm}");
}
#[test]
fn air_level_function_constant_specialization_selects_cfg_before_emission() {
let ll = r#"
@@ -852,6 +908,137 @@ declare void @llvm.memset.p0.i64(ptr, i8, i64, i1)
}
}
#[test]
fn native_zero_memset_past_its_pointee_clears_the_whole_element_run() {
// `memset(&buf[2], 0, 24)` names ONE float and clears six. The destination's pointee is `float`,
// so a single `OpStore null` through it is short by five elements and nothing downstream notices.
// The run is walked through the destination's own GEP provenance instead.
let ll = r#"
target triple = "spirv-unknown-vulkan1.2"
define void @main() {
entry:
%buf = alloca [8 x float], align 4
%tail = getelementptr inbounds [8 x float], ptr %buf, i64 0, i64 2
call void @llvm.memset.p0.i64(ptr %tail, i8 0, i64 24, i1 false)
ret void
}
declare void @llvm.memset.p0.i64(ptr, i8, i64, i1)
"#;
let tmp = std::env::temp_dir().join(format!(
"metal2vulkan_native_memset_run_{}",
std::process::id()
));
let _ = std::fs::create_dir_all(&tmp);
let module = load_bytes(emit_vulkan_spirv(ll).expect("native emit")).expect("load native spv");
let out = passes::transform(module, Stage::Kernel, None, None, None, Some("main"))
.expect("interface transform")
.assemble()
.iter()
.flat_map(|word| word.to_le_bytes())
.collect::<Vec<_>>();
let asm = disassemble(&out).expect("disassemble transformed");
assert_eq!(asm.matches("OpStore").count(), 6, "{asm}");
assert!(!asm.contains("OpFunctionCall"), "{asm}");
assert!(!asm.contains("llvm.memset"), "{asm}");
if std::process::Command::new("spirv-val")
.arg("--version")
.output()
.is_ok()
{
tools::spirv_val_bytes(&out, &tmp).expect("spirv-val");
}
}
#[test]
fn native_memcpy_past_its_pointee_copies_the_whole_element_run() {
// `memcpy(&a[0], &b[0], 12)` through two `i8` element pointers names ONE byte on each side and
// copies twelve. Copying the pointee alone is an `OpCopyMemory` of a single byte, which is valid
// SPIR-V and silently drops eleven.
let ll = r#"
target triple = "spirv-unknown-vulkan1.2"
define void @main() {
entry:
%dst = alloca [12 x i8], align 4
%src = alloca [12 x i8], align 4
%d = getelementptr inbounds [12 x i8], ptr %dst, i64 0, i64 0
%s = getelementptr inbounds [12 x i8], ptr %src, i64 0, i64 0
call void @llvm.memcpy.p0.p0.i64(ptr %d, ptr %s, i64 12, i1 false)
ret void
}
declare void @llvm.memcpy.p0.p0.i64(ptr, ptr, i64, i1)
"#;
let tmp = std::env::temp_dir().join(format!(
"metal2vulkan_native_memcpy_run_{}",
std::process::id()
));
let _ = std::fs::create_dir_all(&tmp);
let module = load_bytes(emit_vulkan_spirv(ll).expect("native emit")).expect("load native spv");
let out = passes::transform(module, Stage::Kernel, None, None, None, Some("main"))
.expect("interface transform")
.assemble()
.iter()
.flat_map(|word| word.to_le_bytes())
.collect::<Vec<_>>();
let asm = disassemble(&out).expect("disassemble transformed");
assert_eq!(asm.matches("OpCopyMemory").count(), 12, "{asm}");
assert!(!asm.contains("llvm.memcpy"), "{asm}");
if std::process::Command::new("spirv-val")
.arg("--version")
.output()
.is_ok()
{
tools::spirv_val_bytes(&out, &tmp).expect("spirv-val");
}
}
#[test]
fn native_zero_memset_of_a_device_pointer_table_keeps_its_single_store() {
// The deliberate hole in the run clear above. A `[N x ptr addrspace(1)]` local is emitted with
// `Int(64)` slots while its `getelementptr` still names `ptr`, and the element-striding primitive
// types its access chain from the GEP -- so it cannot address the array this local actually is.
// Zeroing a device pointer is the separate unmodelled-placeholder problem; the run clear declines
// and the pre-existing single store stands, rather than the module failing to translate.
let ll = r#"
target triple = "spirv-unknown-vulkan1.2"
define void @main() {
entry:
%table = alloca [4 x ptr addrspace(1)], align 8
%tail = getelementptr inbounds [4 x ptr addrspace(1)], ptr %table, i64 0, i64 1
call void @llvm.memset.p0.i64(ptr %tail, i8 0, i64 24, i1 false)
ret void
}
declare void @llvm.memset.p0.i64(ptr, i8, i64, i1)
"#;
let tmp = std::env::temp_dir().join(format!(
"metal2vulkan_native_memset_ptr_table_{}",
std::process::id()
));
let _ = std::fs::create_dir_all(&tmp);
let module = load_bytes(emit_vulkan_spirv(ll).expect("native emit")).expect("load native spv");
let out = passes::transform(module, Stage::Kernel, None, None, None, Some("main"))
.expect("interface transform")
.assemble()
.iter()
.flat_map(|word| word.to_le_bytes())
.collect::<Vec<_>>();
let asm = disassemble(&out).expect("disassemble transformed");
assert_eq!(asm.matches("OpStore").count(), 1, "{asm}");
assert!(!asm.contains("llvm.memset"), "{asm}");
if std::process::Command::new("spirv-val")
.arg("--version")
.output()
.is_ok()
{
tools::spirv_val_bytes(&out, &tmp).expect("spirv-val");
}
}
#[test]
fn native_partial_zero_memset_of_struct_clears_complete_prefix_fields() {
let ll = r#"
@@ -1181,3 +1368,86 @@ fn native_parser_accepts_byte_string_constant_array() {
.collect::<Vec<_>>();
assert_eq!(bytes, [3, 6, 11, 16, 23, 32, 41, 64]);
}
#[test]
fn a_function_constant_loaded_at_a_narrower_float_type_carries_its_bits() {
// Metal declares a constant `ushort` or `uint`, parks the supplied integer in a global of that
// integer type, and then spells `load half` or `load float` from the same global. LLVM reads a
// load through a pointer at a different scalar type as a reinterpretation of the stored bytes,
// so the caller's integer is a floating-point bit pattern rather than a count. The emitter used
// to accept an integer literal in a float slot only when it was zero -- the one value at which
// both readings agree -- and refused every other, so every module of this shape failed the
// moment a caller supplied a non-zero value. `sparserendering_localContrast`
// (`2507aea3c7ebac05`) is the smallest corpus source that spells it.
let ll = r#"
target triple = "spirv-unknown-vulkan1.2"
@bias = internal unnamed_addr addrspace(2) global i16 undef, align 2
@bias.MTL_FC_INIT_0_t = internal unnamed_addr addrspace(2) externally_initialized constant i16 undef, section "air.fc_initializer", align 2
@scale = internal unnamed_addr addrspace(2) global i32 undef, align 4
@scale.MTL_FC_INIT_1_t = internal unnamed_addr addrspace(2) externally_initialized constant i32 undef, section "air.fc_initializer", align 4
define internal void @_GLOBAL__sub_I_fc() section "air.static_init" {
entry:
%0 = load i16, ptr addrspace(2) @bias.MTL_FC_INIT_0_t, align 2
store i16 %0, ptr addrspace(2) @bias, align 2
%1 = load i32, ptr addrspace(2) @scale.MTL_FC_INIT_1_t, align 4
store i32 %1, ptr addrspace(2) @scale, align 4
ret void
}
define float @frag() {
entry:
%bias = load half, ptr addrspace(2) @bias, align 2
%scale = load float, ptr addrspace(2) @scale, align 4
%widened = fpext half %bias to float
%sum = fadd float %widened, %scale
ret float %sum
}
!air.fragment = !{!0}
!air.function_constants = !{!4, !5}
!0 = !{ptr @frag, !1, !2}
!1 = !{!3}
!2 = !{}
!3 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"float"}
!4 = !{ptr addrspace(2) @bias.MTL_FC_INIT_0_t, !"ushort", !"bias", i32 0, i1 true}
!5 = !{ptr addrspace(2) @scale.MTL_FC_INIT_1_t, !"uint", !"scale", i32 1, i1 true}
"#;
let tmp = std::env::temp_dir().join(format!(
"metal2vulkan_native_fc_float_bits_{}",
std::process::id()
));
let _ = std::fs::create_dir_all(&tmp);
// 0xbc00 is -1.0 as binary16 -- a value no unsigned numeric reading of a `ushort` can produce.
// 0x40400000 is 3.0 as binary32; read as a number it is 1077936128.
let specialized = crate::translate_sanitized_native_specialized_with_options(
ll,
Stage::Fragment,
&tmp,
passes::TransformOptions::default(),
&[(0, vec![0x00, 0xbc]), (1, vec![0x00, 0x00, 0x40, 0x40])],
)
.expect("a function constant loaded at half must reinterpret its bits");
tools::spirv_val_bytes(&specialized, &tmp).expect("spirv-val");
let asm = disassemble(&specialized).expect("disassemble specialized");
// The 32-bit constant must land on 3.0, and the 16-bit one must reach the widening as a
// floating-point literal rather than as the integer the caller spelled. The half value itself
// is checked end to end instead: three authored cases on `2507aea3c7ebac05` supply 0x3400,
// 0xb800 and 0xc000 and match Metal's own execution byte for byte.
assert!(
asm.lines()
.any(|line| line.contains("OpConstant") && line.trim_end().ends_with(" 3")),
"the supplied uint bits must reinterpret to 3.0: {asm}"
);
let widened = asm
.lines()
.find_map(|line| line.split("OpFConvert").nth(1))
.and_then(|rest| rest.split_whitespace().nth(1))
.expect("the half load must be widened to the render target type")
.to_string();
assert!(
asm.lines()
.any(|line| line.starts_with(&format!("{widened} = OpConstant "))),
"the supplied ushort bits must reach the widening as a half literal: {asm}"
);
}
+1742 -128
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+638 -25
View File
@@ -116,8 +116,12 @@ declare float @llvm.minnum.f32(float, float)
.flat_map(|w| w.to_le_bytes())
.collect::<Vec<_>>();
let asm = disassemble(&out).expect("disassemble transformed");
assert!(asm.lines().any(|line| line.contains(" FMax ")), "{asm}");
assert!(asm.lines().any(|line| line.contains(" FMin ")), "{asm}");
// `llvm.maxnum`/`llvm.minnum` are IEEE-754 maxNum/minNum: a NaN operand loses to a non-NaN one.
// That is `NMax`/`NMin`, not `FMax`/`FMin`, whose NaN result SPIR-V leaves undefined.
assert!(asm.lines().any(|line| line.contains(" NMax ")), "{asm}");
assert!(asm.lines().any(|line| line.contains(" NMin ")), "{asm}");
assert!(!asm.contains(" FMax "), "{asm}");
assert!(!asm.contains(" FMin "), "{asm}");
assert!(!asm.contains("OpFunctionCall"), "{asm}");
assert!(!asm.contains("llvm.maxnum"), "{asm}");
assert!(!asm.contains("llvm.minnum"), "{asm}");
@@ -238,21 +242,54 @@ declare <3 x i8> @air.sub_sat.u.v3i8(<3 x i8>, <3 x i8>)
}
#[test]
fn native_air_unsigned_i16_rhadd_widens_before_rounding() {
fn native_air_signed_saturating_add_sub_clamp_to_the_end_the_first_operand_names() {
let ll = r#"
target triple = "spirv-unknown-vulkan1.2"
define i16 @rhadd(i16 %a, i16 %b) {
define <3 x i8> @sat_vec(<3 x i8> %a, <3 x i8> %b) {
entry:
%avg = call i16 @air.rhadd.u.i16(i16 %a, i16 %b)
ret i16 %avg
%sum = call <3 x i8> @air.add_sat.s.v3i8(<3 x i8> %a, <3 x i8> %b)
%diff = call <3 x i8> @air.sub_sat.s.v3i8(<3 x i8> %sum, <3 x i8> %b)
ret <3 x i8> %diff
}
declare <3 x i8> @air.add_sat.s.v3i8(<3 x i8>, <3 x i8>)
declare <3 x i8> @air.sub_sat.s.v3i8(<3 x i8>, <3 x i8>)
"#;
let asm = disassemble(&emit_vulkan_spirv(ll).expect("native emit")).expect("disassemble");
// The clamp end is `(a >> 7) ^ INT_MAX`, so an arithmetic shift over the FIRST operand and a
// signed overflow test are what separate this from the unsigned form's single `OpULessThan`.
assert!(asm.contains("OpShiftRightArithmetic"), "{asm}");
assert!(asm.contains("OpSLessThan"), "{asm}");
assert!(asm.contains("OpSelect"), "{asm}");
assert!(!asm.contains("OpULessThan"), "{asm}");
assert!(!asm.contains("OpFunctionCall"), "{asm}");
}
#[test]
fn native_air_halving_add_rounds_in_place_at_every_width() {
let ll = r#"
target triple = "spirv-unknown-vulkan1.2"
define i32 @avg(i16 %a, i16 %b, i32 %c, i32 %d) {
entry:
%rounded = call i16 @air.rhadd.u.i16(i16 %a, i16 %b)
%truncated = call i32 @air.hadd.s.i32(i32 %c, i32 %d)
%widened = zext i16 %rounded to i32
%sum = add i32 %widened, %truncated
ret i32 %sum
}
declare i16 @air.rhadd.u.i16(i16, i16)
declare i32 @air.hadd.s.i32(i32, i32)
"#;
let asm = disassemble(&emit_vulkan_spirv(ll).expect("native emit")).expect("disassemble");
assert!(asm.contains("OpUConvert"), "{asm}");
assert!(asm.contains("OpIAdd"), "{asm}");
// `(a|b) - ((a^b)>>1)` and `(a&b) + ((a^b)>>1)` never leave the operand width, so the only
// `OpUConvert` in the module is the caller's own `zext`.
assert!(asm.contains("OpBitwiseOr"), "{asm}");
assert!(asm.contains("OpBitwiseAnd"), "{asm}");
assert!(asm.contains("OpBitwiseXor"), "{asm}");
assert!(asm.contains("OpShiftRightLogical"), "{asm}");
assert!(asm.contains("OpShiftRightArithmetic"), "{asm}");
assert_eq!(asm.matches("OpUConvert").count(), 1, "{asm}");
assert!(!asm.contains("OpFunctionCall"), "{asm}");
assert!(!asm.contains("air.rhadd.u.i16"), "{asm}");
}
@@ -310,6 +347,238 @@ declare i32 @air.pack.unorm4x8.v4f16(<4 x half>)
}
}
#[test]
fn native_simdgroup_matrix_load_types_a_bare_buffer_parameter() {
// `simdgroup_load(m, buf, 8)` against a bare `device const float *` parameter never GEPs the
// pointer, so nothing else in the module says what it points at and it kept the raw word view
// every untyped device buffer starts with. `lower_simdgroup_matrix_8x8_load` then refused it for
// an integer pointee where the matrix element is a float. The intrinsic itself pins the pointee:
// a simdgroup matrix is a 64-lane composite of one element and the pointer is the base of a
// row-major block of THAT element. The same load spelled `&buf[i]` always worked.
let ll = r#"
target triple = "spirv-unknown-vulkan1.2"
define void @k(ptr addrspace(1) %in, ptr addrspace(1) %out) {
entry:
%m = tail call <64 x float> @air.simdgroup_matrix_8x8_load.v64f32.p1f32(ptr addrspace(1) %in, <2 x i64> <i64 8, i64 8>, <2 x i64> <i64 1, i64 8>, <2 x i64> zeroinitializer)
tail call void @air.simdgroup_matrix_8x8_store.v64f32.p1f32(<64 x float> %m, ptr addrspace(1) %out, <2 x i64> <i64 8, i64 8>, <2 x i64> <i64 1, i64 8>, <2 x i64> zeroinitializer)
ret void
}
declare <64 x float> @air.simdgroup_matrix_8x8_load.v64f32.p1f32(ptr addrspace(1), <2 x i64>, <2 x i64>, <2 x i64>)
declare void @air.simdgroup_matrix_8x8_store.v64f32.p1f32(<64 x float>, ptr addrspace(1), <2 x i64>, <2 x i64>, <2 x i64>)
!air.kernel = !{!0}
!0 = !{ptr @k, !1, !2}
!1 = !{}
!2 = !{!3, !4}
!3 = !{i32 0, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"float", !"air.arg_name", !"in"}
!4 = !{i32 1, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.write", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"float", !"air.arg_name", !"out"}
"#;
let tmp = std::env::temp_dir().join(format!("metal2vulkan_sgm_bare_{}", std::process::id()));
let _ = std::fs::create_dir_all(&tmp);
let spv = crate::translate_sanitized_native(ll, Stage::Kernel, &tmp).expect("translate");
let asm = disassemble(&spv).expect("disassemble");
// 64 gathered loads and 64 scattered stores, all at float.
assert_eq!(asm.matches("OpLoad").count(), 64, "{asm}");
assert_eq!(asm.matches("OpStore").count(), 64, "{asm}");
if std::process::Command::new("spirv-val")
.arg("--version")
.output()
.is_ok()
{
tools::spirv_val_bytes(&spv, &tmp).expect("spirv-val");
}
let _ = std::fs::remove_dir_all(tmp);
}
#[test]
fn native_simdgroup_matrix_all_half_mac_accumulates_without_an_identity_fconvert() {
// The MAC accumulates at f32 whenever the result or any operand is wider than f16. An ALL-half
// one accumulates at half, and the operand widening is then the IDENTITY -- but it was emitted
// unconditionally, and `OpFConvert` requires the two widths to differ, so the owned module
// rejected its own output with "FConvert source and result shapes are inconsistent". No
// all-half `simdgroup_multiply_accumulate` could translate at all.
let ll = r#"
target triple = "spirv-unknown-vulkan1.2"
define void @k(ptr addrspace(1) %in, ptr addrspace(1) %out) {
entry:
%a = tail call <64 x half> @air.simdgroup_matrix_8x8_load.v64f16.p1f16(ptr addrspace(1) %in, <2 x i64> <i64 8, i64 8>, <2 x i64> <i64 1, i64 8>, <2 x i64> zeroinitializer)
%r = tail call <64 x half> @air.simdgroup_matrix_8x8_multiply_accumulate.v64f16.v64f16.v64f16.v64f16(<64 x half> %a, <64 x half> %a, <64 x half> %a)
tail call void @air.simdgroup_matrix_8x8_store.v64f16.p1f16(<64 x half> %r, ptr addrspace(1) %out, <2 x i64> <i64 8, i64 8>, <2 x i64> <i64 1, i64 8>, <2 x i64> zeroinitializer)
ret void
}
declare <64 x half> @air.simdgroup_matrix_8x8_load.v64f16.p1f16(ptr addrspace(1), <2 x i64>, <2 x i64>, <2 x i64>)
declare <64 x half> @air.simdgroup_matrix_8x8_multiply_accumulate.v64f16.v64f16.v64f16.v64f16(<64 x half>, <64 x half>, <64 x half>)
declare void @air.simdgroup_matrix_8x8_store.v64f16.p1f16(<64 x half>, ptr addrspace(1), <2 x i64>, <2 x i64>, <2 x i64>)
!air.kernel = !{!0}
!0 = !{ptr @k, !1, !2}
!1 = !{}
!2 = !{!3, !4}
!3 = !{i32 0, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 1, !"air.arg_type_size", i32 2, !"air.arg_type_align_size", i32 2, !"air.arg_type_name", !"half", !"air.arg_name", !"in"}
!4 = !{i32 1, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.write", !"air.address_space", i32 1, !"air.arg_type_size", i32 2, !"air.arg_type_align_size", i32 2, !"air.arg_type_name", !"half", !"air.arg_name", !"out"}
"#;
let tmp = std::env::temp_dir().join(format!("metal2vulkan_sgm_half_{}", std::process::id()));
let _ = std::fs::create_dir_all(&tmp);
let spv = crate::translate_sanitized_native(ll, Stage::Kernel, &tmp).expect("translate");
let asm = disassemble(&spv).expect("disassemble");
// The arithmetic stays at half throughout: 8 products and 8 sums per lane, and no widening.
assert_eq!(asm.matches("OpFMul").count(), 512, "{asm}");
assert_eq!(asm.matches("OpFAdd").count(), 512, "{asm}");
assert_eq!(asm.matches("OpFConvert").count(), 0, "{asm}");
if std::process::Command::new("spirv-val")
.arg("--version")
.output()
.is_ok()
{
tools::spirv_val_bytes(&spv, &tmp).expect("spirv-val");
}
let _ = std::fs::remove_dir_all(tmp);
}
#[test]
fn native_air_convert_wide_int_to_bfloat_rounds_the_f32_hop_to_odd() {
// bf16 keeps 8 significant bits and f32 keeps 24, so a wide integer taken to bf16 through an
// f32 intermediate rounds TWICE: an integer just past a bf16 midpoint can round back onto that
// midpoint in f32 and then be sent the other way by ties-to-even. Metal converts in one step --
// `bfloat(33685505u)` is 0x4C01 on device, 0x4C00 through a plain f32 hop -- so the intermediate
// is rounded to odd first. That needs the truncating round trip back to the integer (to learn
// whether the f32 hop was exact and which way it went) and the significand's low bit set.
let with_source = |ty: &str, size: i32| {
format!(
r#"
target triple = "spirv-unknown-vulkan1.2"
define void @k(ptr addrspace(1) %in, ptr addrspace(1) %out) {{
entry:
%v = load {ty}, ptr addrspace(1) %in, align 4
%bf = tail call bfloat @air.convert.f.bf16.s.{ty}({ty} %v)
store bfloat %bf, ptr addrspace(1) %out, align 2
ret void
}}
declare bfloat @air.convert.f.bf16.s.{ty}({ty})
!air.kernel = !{{!0}}
!0 = !{{ptr @k, !1, !2}}
!1 = !{{}}
!2 = !{{!3, !4}}
!3 = !{{i32 0, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 1, !"air.arg_type_size", i32 {size}, !"air.arg_type_align_size", i32 {size}, !"air.arg_type_name", !"int*", !"air.arg_name", !"in"}}
!4 = !{{i32 1, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.write", !"air.address_space", i32 1, !"air.arg_type_size", i32 2, !"air.arg_type_align_size", i32 2, !"air.arg_type_name", !"bfloat*", !"air.arg_name", !"out"}}
"#
)
};
let tmp = std::env::temp_dir().join(format!("metal2vulkan_bf16_rto_{}", std::process::id()));
let _ = std::fs::create_dir_all(&tmp);
let wide = crate::translate_sanitized_native(&with_source("i32", 4), Stage::Kernel, &tmp)
.expect("translate i32 source");
let asm = disassemble(&wide).expect("disassemble i32 source");
// The clamp that keeps the round trip inside the integer range, the round trip itself, and the
// step-down + set-low-bit that names the odd member of the bracketing pair.
assert!(asm.contains("FMin"), "{asm}");
assert!(asm.contains("OpConvertFToS"), "{asm}");
assert!(asm.contains("OpBitwiseOr"), "{asm}");
assert!(asm.contains("OpSelect"), "{asm}");
// A source narrower than the f32 significand cannot round twice, so it keeps the plain hop:
// no round trip back to the integer at all.
let narrow = crate::translate_sanitized_native(&with_source("i16", 2), Stage::Kernel, &tmp)
.expect("translate i16 source");
let asm = disassemble(&narrow).expect("disassemble i16 source");
assert!(asm.contains("OpConvertSToF"), "{asm}");
assert!(!asm.contains("OpConvertFToS"), "{asm}");
if std::process::Command::new("spirv-val")
.arg("--version")
.output()
.is_ok()
{
tools::spirv_val_bytes(&wide, &tmp).expect("spirv-val");
tools::spirv_val_bytes(&narrow, &tmp).expect("spirv-val");
}
}
#[test]
fn native_wide_vector_convert_and_bitcast_run_one_lane_at_a_time() {
// Vulkan has no vector wider than four components, so a wider AIR vector is typed as an
// `OpTypeArray` -- and neither a conversion nor an `OpBitcast` accepts an aggregate. Both must
// decompose to per-lane work. `air.convert` used to carry a SECOND kind-to-opcode table for the
// wide arm, which disagreed with the narrow one about bfloat: bf16's SPIR-V type is
// `OpTypeInt 16`, so an `f`->`f` convert into it picked `OpFConvert` on an integer result and
// was rejected outright. The wide arm now re-spells the name without its `v<N>` prefixes and
// defers to the same lowering the narrow path uses.
let with_source = |lanes: u32, elem: &str, air_elem: &str, cast: &str, bits: &str| {
let size = lanes * 2;
format!(
r#"
target triple = "spirv-unknown-vulkan1.2"
define void @k(ptr addrspace(1) %in, ptr addrspace(1) %out) {{
entry:
%v = load <{lanes} x half>, ptr addrspace(1) %in, align 16
%c = tail call <{lanes} x {elem}> @air.convert.f.v{lanes}{air_elem}.f.v{lanes}f16(<{lanes} x half> %v)
%b = bitcast <{lanes} x {elem}> %c to <{lanes} x {cast}>
%lane = extractelement <{lanes} x {cast}> %b, i64 2
store {cast} %lane, ptr addrspace(1) %out, align 4
ret void
}}
declare <{lanes} x {elem}> @air.convert.f.v{lanes}{air_elem}.f.v{lanes}f16(<{lanes} x half>)
!air.kernel = !{{!0}}
!0 = !{{ptr @k, !1, !2}}
!1 = !{{}}
!2 = !{{!3, !4}}
!3 = !{{i32 0, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 1, !"air.arg_type_size", i32 {size}, !"air.arg_type_align_size", i32 {size}, !"air.arg_type_name", !"half*", !"air.arg_name", !"in"}}
!4 = !{{i32 1, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.write", !"air.address_space", i32 1, !"air.arg_type_size", i32 {bits}, !"air.arg_type_align_size", i32 {bits}, !"air.arg_type_name", !"uint*", !"air.arg_name", !"out"}}
"#
)
};
let tmp = std::env::temp_dir().join(format!("metal2vulkan_wide_lane_{}", std::process::id()));
let _ = std::fs::create_dir_all(&tmp);
// Eight lanes into bfloat: the conversion has to take the bf16 route (widen to f32, round the
// f32 bits to nearest-even, keep the top 16) at every lane, not a single `OpFConvert`.
let source = with_source(8, "bfloat", "bf16", "i16", "2");
let wide = crate::translate_sanitized_native(&source, Stage::Kernel, &tmp)
.expect("translate wide half->bfloat");
let asm = disassemble(&wide).expect("disassemble wide half->bfloat");
assert!(asm.contains("OpTypeArray"), "{asm}");
assert!(asm.contains("OpCompositeConstruct"), "{asm}");
// Per lane: widen the half to f32, then take the f32 bits to bf16 with a ties-to-even carry
// and a shift down to the top 16. Eight widenings, not one `OpFConvert` over the array.
assert_eq!(asm.matches("OpFConvert").count(), 8, "{asm}");
assert!(asm.contains("OpShiftRightLogical"), "{asm}");
// The `bitcast <8 x bfloat> to <8 x i16>` costs nothing: bfloat is already modelled as i16, so
// the two arrays are the same SPIR-V type and the array copies whole, in one `OpCopyObject`.
assert_eq!(asm.matches("OpCopyObject").count(), 1, "{asm}");
// Sixteen lanes into float: the conversion is an ordinary widening, and the bitcast that
// follows it is the part that cannot be one instruction over an array.
let source = with_source(16, "float", "f32", "i32", "4");
let bits = crate::translate_sanitized_native(&source, Stage::Kernel, &tmp)
.expect("translate wide half->float");
let asm = disassemble(&bits).expect("disassemble wide half->float");
assert_eq!(asm.matches("OpFConvert").count(), 16, "{asm}");
// Three arrays are built lane by lane: the loaded `<16 x half>`, the conversion's result and
// the bitcast's. Neither the conversion nor the bitcast may name an array operand, which is
// what the `spirv-val` run below is really checking.
assert_eq!(asm.matches("OpCompositeConstruct").count(), 3, "{asm}");
if std::process::Command::new("spirv-val")
.arg("--version")
.output()
.is_ok()
{
tools::spirv_val_bytes(&wide, &tmp).expect("spirv-val wide half->bfloat");
tools::spirv_val_bytes(&bits, &tmp).expect("spirv-val wide half->float");
}
}
#[test]
fn native_air_convert_bfloat_widens_and_narrows_through_f32() {
// bf16 has no SPIR-V type, so a bfloat value is modeled as its `OpTypeInt 16` bit pattern. An
@@ -362,8 +631,19 @@ declare bfloat @air.convert.f.bf16.f.f32(float)
}
}
/// A float-to-integer convert is bare at EVERY destination width -- no clamp, at any of them.
///
/// SPIR-V leaves an out-of-range or NaN input undefined, so what a shader gets is Metal's answer,
/// and Metal's cast SATURATES at every width and sends NaN to zero (device-measured on an Apple M3
/// Max / macOS 26.5.2; the case `float-to-integer-saturates-at-every-width` carries all 72 rows).
/// SPIRV-Cross renders `OpConvertFToU`/`OpConvertFToS` as exactly that MSL cast, so the bare
/// convert reproduces the contract and the clamp that used to wrap the narrow widths only broke
/// it: `clamp(NaN, lo, hi)` is `lo` on Metal, so a signed narrow destination answered -32768 or
/// -128 where Metal answers 0; and the clamp edges are spelled in the SOURCE float type, which at
/// half cannot hold a 16-bit destination's maximum, so `short(half(40000))` came back 32752
/// instead of 32767.
#[test]
fn native_air_float_to_narrow_int_convert_clamps_before_convert() {
fn native_air_float_to_int_convert_is_bare_at_every_width() {
let ll = r#"
target triple = "spirv-unknown-vulkan1.2"
@@ -371,17 +651,25 @@ define void @k(ptr addrspace(1) %out_u8, ptr addrspace(1) %out_i16, ptr addrspac
entry:
%x = load float, ptr addrspace(1) %in_f, align 4
%v = load <2 x float>, ptr addrspace(1) %in_vf, align 8
%h = fptrunc float %x to half
%u8 = tail call i8 @air.convert.u.i8.f.f32(float %x)
%i16 = tail call i16 @air.convert.s.i16.f.f32(float %x)
%vu8 = tail call <2 x i8> @air.convert.u.v2i8.f.v2f32(<2 x float> %v)
%hi16 = tail call i16 @air.convert.s.i16.f.f16(half %h)
%i32 = tail call i32 @air.convert.u.i32.f.f32(float %x)
%sum = add i16 %i16, %hi16
%narrow = trunc i32 %i32 to i16
%all = add i16 %sum, %narrow
store i8 %u8, ptr addrspace(1) %out_u8, align 1
store i16 %i16, ptr addrspace(1) %out_i16, align 2
store i16 %all, ptr addrspace(1) %out_i16, align 2
store <2 x i8> %vu8, ptr addrspace(1) %out_vu8, align 2
ret void
}
declare i8 @air.convert.u.i8.f.f32(float)
declare i16 @air.convert.s.i16.f.f32(float)
declare i16 @air.convert.s.i16.f.f16(half)
declare i32 @air.convert.u.i32.f.f32(float)
declare <2 x i8> @air.convert.u.v2i8.f.v2f32(<2 x float>)
!air.kernel = !{!0}
@@ -401,9 +689,12 @@ declare <2 x i8> @air.convert.u.v2i8.f.v2f32(<2 x float>)
let _ = std::fs::create_dir_all(&tmp);
let spv = crate::translate_sanitized_native(ll, Stage::Kernel, &tmp).expect("translate");
let asm = disassemble(&spv).expect("disassemble");
assert_eq!(asm.matches(" FClamp ").count(), 3, "{asm}");
assert!(asm.contains("OpConvertFToU"), "{asm}");
assert!(asm.contains("OpConvertFToS"), "{asm}");
// Five converts -- u8, s16, vector u8, s16 from a HALF source, and u32 -- and not one clamp
// between them. The half source is the shape whose bound could not be spelled at all.
assert!(!asm.contains(" FClamp "), "{asm}");
assert!(!asm.contains(" NClamp "), "{asm}");
assert_eq!(asm.matches("OpConvertFToU").count(), 3, "{asm}");
assert_eq!(asm.matches("OpConvertFToS").count(), 2, "{asm}");
assert!(!asm.contains("OpFunctionCall"), "{asm}");
if std::process::Command::new("spirv-val")
.arg("--version")
@@ -1130,6 +1421,12 @@ entry:
store i32 %w, ptr addrspace(1) %out, align 4
ret void
}
!air.kernel = !{!0}
!0 = !{ptr @k, !1, !2}
!1 = !{}
!2 = !{!3}
!3 = !{i32 0, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_name", !"uint*", !"air.arg_name", !"out"}
"#;
let tmp = std::env::temp_dir().join(format!(
"metal2vulkan_native_union_byte_store_{}",
@@ -1198,6 +1495,57 @@ entry:
assert!(!asm.contains("does not match Object"), "{asm}");
}
#[test]
fn native_single_member_struct_store_descends_to_the_union_member() {
// The same reinterpret as above, but stored straight AT the union rather than through a
// `getelementptr` to member 0: an MSL union is a one-member LLVM struct, so the declared pointee
// is `%union.U`, no width-based rule has an answer for it, and the store used to fall through to
// a plain `OpStore` the pointee/value contract refuses. Member 0 of a single-member struct is the
// slot's own address, so the emitter descends to it and the read-modify-write applies unchanged.
let ll = r#"
target triple = "spirv-unknown-vulkan1.2"
%union.U = type { i64 }
define void @float_into_union(float %f) {
entry:
%scratch = alloca %union.U, align 8
store float %f, ptr %scratch, align 4
ret void
}
"#;
let asm = disassemble(&emit_vulkan_spirv(ll).expect("native emit")).expect("disassemble");
assert!(asm.contains("AccessChain"), "{asm}");
assert!(asm.contains("OpShiftRightLogical"), "{asm}");
assert!(asm.contains("OpShiftLeftLogical"), "{asm}");
assert!(asm.contains("OpBitwiseOr"), "{asm}");
assert!(asm.contains("OpUConvert"), "{asm}");
assert!(!asm.contains("does not match Object"), "{asm}");
}
#[test]
fn native_single_member_struct_store_reaches_the_vector_rules_too() {
// The descent happens once, at the store dispatch, so every rule below it applies to the union
// member -- not just the scalar narrowing one. A `uint2` member of the same eight-byte union is a
// SAME-WIDTH reinterpret of the `i64` slot, which is a different rule and a different lowering
// (a plain `OpBitcast`, no read-modify-write, because the store covers every byte of the slot).
let ll = r#"
target triple = "spirv-unknown-vulkan1.2"
%union.U = type { i64 }
define void @vector_into_union(<2 x i32> %v) {
entry:
%scratch = alloca %union.U, align 8
store <2 x i32> %v, ptr %scratch, align 8
ret void
}
"#;
let asm = disassemble(&emit_vulkan_spirv(ll).expect("native emit")).expect("disassemble");
assert!(asm.contains("AccessChain"), "{asm}");
assert!(asm.contains("OpBitcast"), "{asm}");
assert!(!asm.contains("OpShiftRightLogical"), "{asm}");
assert!(!asm.contains("does not match Object"), "{asm}");
}
#[test]
fn native_fast_float_arithmetic_and_store_lower() {
let ll = r#"
@@ -1828,8 +2176,14 @@ declare <3 x float> @air.fast_log2.v3f32(<3 x float>)
}
}
/// `air.mix` is a bare `FMix` -- no endpoint guard around it.
///
/// The guard that used to be here selected `x` when `t == 0` and `y` when `t == 1`. For a finite
/// pair that changes nothing, because `x * (1 - a) + y * a` is already exactly `x` at 0 and exactly
/// `y` at 1; for a non-finite pair it made us disagree with Metal, which answers NaN for
/// `mix(inf, 5, 1)` where the guard answered 5. See `mix-an-infinite-endpoint-into-a-nan`.
#[test]
fn native_air_mix_preserves_exact_vector_endpoints() {
fn native_air_mix_is_a_bare_blend_with_no_endpoint_guard() {
let ll = r#"
target triple = "spirv-unknown-vulkan1.2"
define void @main(float %t) {
@@ -1866,8 +2220,8 @@ declare <4 x float> @air.mix.v4f32(<4 x float>, <4 x float>, <4 x float>)
.collect::<Vec<_>>();
let asm = disassemble(&out).expect("disassemble transformed");
assert!(asm.contains(" FMix "), "{asm}");
assert!(asm.matches("OpFOrdEqual").count() >= 2, "{asm}");
assert!(asm.matches("OpSelect").count() >= 2, "{asm}");
assert_eq!(asm.matches("OpFOrdEqual").count(), 0, "{asm}");
assert_eq!(asm.matches("OpSelect").count(), 0, "{asm}");
assert!(!asm.contains("OpFunctionCall"), "{asm}");
if std::process::Command::new("spirv-val")
.arg("--version")
@@ -1946,9 +2300,12 @@ declare <4 x float> @air.fast_powr.v4f32(<4 x float>, <4 x float>)
assert!(asm.contains(" Asinh "), "{asm}");
assert!(asm.contains(" Acosh "), "{asm}");
assert!(asm.contains(" Atanh "), "{asm}");
assert!(asm.contains(" Log "), "{asm}");
// `air.fast_log10` is `log2(x) * log10(2)`, not `log(x) / ln(10)`: the natural-log form
// disagrees with Metal on 1995 of a 2011-argument device sweep, this one on none of them.
assert!(asm.contains(" Log2 "), "{asm}");
assert!(!asm.contains(" Log "), "{asm}");
assert!(asm.contains(" Pow "), "{asm}");
assert!(asm.contains("OpFDiv"), "{asm}");
assert!(asm.contains("OpFMul"), "{asm}");
assert!(!asm.contains("OpFunctionCall"), "{asm}");
if std::process::Command::new("spirv-val")
.arg("--version")
@@ -1959,8 +2316,189 @@ declare <4 x float> @air.fast_powr.v4f32(<4 x float>, <4 x float>)
}
}
/// A half `log10` multiplies at FLOAT width, and a half `exp10` does not widen at all.
///
/// `log10` is composed as `log2(x) * log10(2)`. Rounding that intermediate to half does not
/// reproduce Metal: evaluated entirely in half it disagrees with Metal's `log10(half)` on 8081 of
/// the 63488 finite halves, and evaluated in float and rounded once it agrees on all 63488
/// (device-measured, Apple M3 Max / macOS 26.5.2). `exp10` needs no such promotion -- half-width
/// `powr(10, x)` is bit-identical to Metal's `exp10(half)` on all 63488.
///
/// The vector `exp10` is here because the composition used to be scalar-only and FALLBACK on a
/// vector; that refusal had no reason behind it.
#[test]
fn native_half_pow_uses_abs_base() {
fn native_half_log10_multiplies_at_float_width() {
let ll = r#"
target triple = "spirv-unknown-vulkan1.2"
define void @main() {
entry:
%l = tail call fast half @air.log10.f16(half 0xH5640)
%e = tail call fast half @air.exp10.f16(half 0xH4000)
%sum = fadd fast half %l, %e
%wide = fpext half %sum to float
%v0 = insertelement <2 x float> poison, float 2.500000e-01, i32 0
%v1 = insertelement <2 x float> %v0, float 7.500000e-01, i32 1
%t = tail call fast <2 x float> @air.fast_exp10.v2f32(<2 x float> %v1)
%lane = extractelement <2 x float> %t, i32 0
%all = fadd fast float %wide, %lane
%sink = fcmp oge float %all, 0.000000e+00
ret void
}
declare half @air.log10.f16(half)
declare half @air.exp10.f16(half)
declare <2 x float> @air.fast_exp10.v2f32(<2 x float>)
"#;
let tmp = std::env::temp_dir().join(format!(
"metal2vulkan_half_log10_float_width_{}",
std::process::id()
));
let _ = std::fs::create_dir_all(&tmp);
let module = load_bytes(emit_vulkan_spirv(ll).expect("native emit")).expect("load native spv");
let out = passes::transform(module, Stage::Kernel, None, None, None, Some("main"))
.expect("interface transform")
.assemble()
.iter()
.flat_map(|w| w.to_le_bytes())
.collect::<Vec<_>>();
let asm = disassemble(&out).expect("disassemble transformed");
let scalar_ty = |width: &str| {
asm.lines()
.find(|line| line.contains(&format!("OpTypeFloat {width}")))
.and_then(|line| line.split('=').next())
.map(str::trim)
.unwrap_or_else(|| panic!("a {width}-bit float type: {asm}"))
.to_string()
};
let float_ty = scalar_ty("32");
let half_ty = scalar_ty("16");
let result_ty = |line: &str, op: &str| {
line.split(op)
.nth(1)
.and_then(|rest| rest.split_whitespace().next())
.expect("result type")
.to_string()
};
let ext_widths = |op: &str| {
asm.lines()
.filter(|line| line.contains(op))
.map(|line| result_ty(line, "OpExtInst"))
.collect::<Vec<_>>()
};
// The natural log is not involved at any width.
assert!(!asm.contains(" Log "), "{asm}");
assert_eq!(ext_widths(" Log2 "), vec![float_ty.clone()], "{asm}");
// `exp10` stays at half: a `Pow` at half width, no promotion. The vector `exp10` lowers to a
// second `Pow` instead of falling back.
let pow_widths = ext_widths(" Pow ");
assert_eq!(pow_widths.len(), 2, "{asm}");
assert!(pow_widths.contains(&half_ty), "{asm}");
// No multiply in the composition happens at half width.
let half_muls = asm
.lines()
.filter(|line| line.contains("OpFMul"))
.filter(|line| result_ty(line, "OpFMul") == half_ty)
.count();
assert_eq!(half_muls, 0, "{asm}");
// Two converts for the widened half log10, one for the fpext the fixture writes; the half
// exp10 and the float-vector exp10 add none.
assert_eq!(asm.matches("OpFConvert").count(), 3, "{asm}");
assert!(!asm.contains("OpFunctionCall"), "{asm}");
if std::process::Command::new("spirv-val")
.arg("--version")
.output()
.is_ok()
{
tools::spirv_val_bytes(&out, &tmp).expect("spirv-val");
}
}
/// A half `Tanh`/`Atan2` is computed at float width, and a float one is not widened.
///
/// SPIRV-Cross -- what MoltenVK runs our modules through -- chooses Metal's `fast::` variant for a
/// HALF `Tanh`/`Atan2` and its `precise::` variant for the float one. `fast::tanh(44)` is 0 and
/// `fast::tanh(50)` is NaN where Metal's own `tanh(half)` is 1.0, so a half ext-inst names a
/// different function than the AIR call did.
#[test]
fn native_half_tanh_and_atan2_are_computed_at_float_width() {
let ll = r#"
target triple = "spirv-unknown-vulkan1.2"
define void @main() {
entry:
%h = tail call fast half @air.tanh.f16(half 0xH5180)
%a = tail call fast half @air.atan2.f16(half 0xH3C00, half 0xH4000)
%g = tail call fast half @air.fast_atan2.f16(half 0xH3C00, half 0xH4000)
%f = tail call fast float @air.tanh.f32(float 4.400000e+01)
%sum = fadd fast half %h, %a
%sum2 = fadd fast half %sum, %g
%wide = fpext half %sum2 to float
%all = fadd fast float %wide, %f
%sink = fcmp oge float %all, 0.000000e+00
ret void
}
declare half @air.tanh.f16(half)
declare half @air.atan2.f16(half, half)
declare half @air.fast_atan2.f16(half, half)
declare float @air.tanh.f32(float)
"#;
let tmp = std::env::temp_dir().join(format!(
"metal2vulkan_half_tanh_float_width_{}",
std::process::id()
));
let _ = std::fs::create_dir_all(&tmp);
let module = load_bytes(emit_vulkan_spirv(ll).expect("native emit")).expect("load native spv");
let out = passes::transform(module, Stage::Kernel, None, None, None, Some("main"))
.expect("interface transform")
.assemble()
.iter()
.flat_map(|w| w.to_le_bytes())
.collect::<Vec<_>>();
let asm = disassemble(&out).expect("disassemble transformed");
let float_ty = asm
.lines()
.find(|line| line.contains("OpTypeFloat 32"))
.and_then(|line| line.split('=').next())
.map(str::trim)
.expect("a 32-bit float type")
.to_string();
let ext_inst_result_ty = |line: &str| {
line.split("OpExtInst")
.nth(1)
.and_then(|rest| rest.split_whitespace().next())
.expect("ext-inst result type")
.to_string()
};
let widths = |op: &str| {
asm.lines()
.filter(|line| line.contains(op))
.map(ext_inst_result_ty)
.collect::<Vec<_>>()
};
assert_eq!(widths(" Tanh "), vec![float_ty.clone(); 2], "{asm}");
// Two atan2 calls: the precise one widens, and `air.fast_atan2` is asking for exactly the
// `fast::` variant the half width already reaches, so it must NOT.
let atan2 = widths(" Atan2 ");
assert_eq!(atan2.len(), 2, "{asm}");
assert!(atan2.contains(&float_ty), "precise atan2 widens: {asm}");
assert!(
atan2.iter().any(|ty| *ty != float_ty),
"air.fast_atan2.f16 must stay at half width: {asm}"
);
// Three converts for the widened half atan2 (two in, one out), two for the half tanh, and one
// for the fpext the fixture writes. The fast atan2 and the float tanh add none.
assert_eq!(asm.matches("OpFConvert").count(), 6, "{asm}");
if std::process::Command::new("spirv-val")
.arg("--version")
.output()
.is_ok()
{
tools::spirv_val_bytes(&out, &tmp).expect("spirv-val");
}
}
#[test]
fn native_half_pow_signs_the_magnitude_by_exponent_parity() {
let ll = r#"
target triple = "spirv-unknown-vulkan1.2"
define void @main() {
@@ -1991,8 +2529,18 @@ declare <3 x half> @air.pow.v3f16(<3 x half>, <3 x half>)
.flat_map(|w| w.to_le_bytes())
.collect::<Vec<_>>();
let asm = disassemble(&out).expect("disassemble transformed");
// GLSL Pow only takes the magnitude; the base's sign comes back only when the exponent is an
// odd integer, and a non-integer exponent leaves the domain entirely.
assert!(asm.contains(" FAbs "), "{asm}");
assert!(asm.contains(" Pow "), "{asm}");
assert!(asm.contains(" Trunc "), "{asm}");
assert!(asm.contains("OpFNegate"), "{asm}");
assert!(asm.contains("OpFOrdNotEqual"), "{asm}");
assert!(asm.contains("OpFOrdLessThan"), "{asm}");
assert!(
asm.contains("NaN"),
"the out-of-domain arm needs a NaN constant: {asm}"
);
assert!(!asm.contains("OpFunctionCall"), "{asm}");
if std::process::Command::new("spirv-val")
.arg("--version")
@@ -2034,7 +2582,11 @@ declare <4 x float> @air.fast_round.v4f32(<4 x float>)
.flat_map(|w| w.to_le_bytes())
.collect::<Vec<_>>();
let asm = disassemble(&out).expect("disassemble transformed");
assert!(asm.contains(" Round "), "{asm}");
// Lanes 2 and 3 are the ties 2.5 and -2.5, which Metal rounds to 3.0 and -3.0. GLSL Round
// picks the tie direction itself, so the lowering is the explicit trunc/remainder form.
assert!(!asm.contains(" Round "), "{asm}");
assert!(asm.contains(" Trunc "), "{asm}");
assert_eq!(asm.matches("OpSelect").count(), 2, "{asm}");
assert!(!asm.contains("OpFunctionCall"), "{asm}");
if std::process::Command::new("spirv-val")
.arg("--version")
@@ -2088,21 +2640,21 @@ declare <4 x float> @air.fast_rint.v4f32(<4 x float>)
}
#[test]
fn native_round_half_vector_round_trips_through_float() {
fn native_rint_half_vector_round_trips_through_float() {
let ll = r#"
target triple = "spirv-unknown-vulkan1.2"
define void @main(<2 x half> %v) {
entry:
%rounded = tail call fast <2 x half> @air.round.v2f16(<2 x half> %v)
%rounded = tail call fast <2 x half> @air.rint.v2f16(<2 x half> %v)
%lane = extractelement <2 x half> %rounded, i32 0
%sink = fcmp oge half %lane, 0xH0000
ret void
}
declare <2 x half> @air.round.v2f16(<2 x half>)
declare <2 x half> @air.rint.v2f16(<2 x half>)
"#;
let tmp = std::env::temp_dir().join(format!(
"metal2vulkan_native_round_half_vector_{}",
"metal2vulkan_native_rint_half_vector_{}",
std::process::id()
));
let _ = std::fs::create_dir_all(&tmp);
@@ -2115,7 +2667,7 @@ declare <2 x half> @air.round.v2f16(<2 x half>)
.collect::<Vec<_>>();
let asm = disassemble(&out).expect("disassemble transformed");
assert!(asm.contains("OpFConvert"), "{asm}");
assert!(asm.contains(" Round "), "{asm}");
assert!(asm.contains(" RoundEven "), "{asm}");
if std::process::Command::new("spirv-val")
.arg("--version")
.output()
@@ -2585,3 +3137,64 @@ merge:
Err(e) => panic!("emit failed: {}", e),
}
}
#[test]
fn native_typed_and_opaque_pointer_spellings_translate_identically() {
// `xcrun metal -S -emit-llvm` still emits LLVM's pre-opaque pointer spelling, so an AIR
// module straight out of the Metal frontend reads `i32 addrspace(1)* %0` where the corpus
// reads `ptr addrspace(1) %0`. The two spell one pointer and have to translate to one
// module. Before the type parser knew the trailing `*`, every prefix scan backtracked past
// it and handed back the POINTEE -- so the buffer parameter came out as `Int(32)` and the
// first GEP off it died with "getelementptr base is not a pointer".
const METADATA: &str = r#"
!air.kernel = !{!0}
!1 = !{}
!2 = !{!3, !4, !5}
!3 = !{i32 0, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"a"}
!4 = !{i32 1, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"o"}
!5 = !{i32 2, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"g"}
"#;
let typed = format!(
r#"
source_filename = "case.metal"
define void @tp(i32 addrspace(1)* nocapture readonly %0, i32 addrspace(1)* nocapture %1, i32 %2) {{
%4 = zext i32 %2 to i64
%5 = getelementptr inbounds i32, i32 addrspace(1)* %0, i64 %4
%6 = load i32, i32 addrspace(1)* %5, align 4
%7 = add i32 %6, 7
%8 = getelementptr inbounds i32, i32 addrspace(1)* %1, i64 %4
store i32 %7, i32 addrspace(1)* %8, align 4
ret void
}}
!0 = !{{void (i32 addrspace(1)*, i32 addrspace(1)*, i32)* @tp, !1, !2}}
{METADATA}"#
);
let opaque = format!(
r#"
source_filename = "case.metal"
define void @tp(ptr addrspace(1) readonly captures(none) %0, ptr addrspace(1) captures(none) %1, i32 %2) {{
%4 = zext i32 %2 to i64
%5 = getelementptr inbounds i32, ptr addrspace(1) %0, i64 %4
%6 = load i32, ptr addrspace(1) %5, align 4
%7 = add i32 %6, 7
%8 = getelementptr inbounds i32, ptr addrspace(1) %1, i64 %4
store i32 %7, ptr addrspace(1) %8, align 4
ret void
}}
!0 = !{{ptr @tp, !1, !2}}
{METADATA}"#
);
let tmp = std::env::temp_dir().join(format!(
"metal2vulkan_native_typed_pointer_spelling_{}",
std::process::id()
));
let _ = std::fs::create_dir_all(&tmp);
let from_typed =
crate::translate_sanitized_native(&typed, Stage::Kernel, &tmp).expect("typed pointers");
let from_opaque =
crate::translate_sanitized_native(&opaque, Stage::Kernel, &tmp).expect("opaque pointers");
assert_eq!(from_typed, from_opaque);
}
+36
View File
@@ -473,6 +473,12 @@ pub(in crate::native) fn push_inst_line(
.unwrap_or("")
.to_string();
let fast_math = rhs_of(line).split_whitespace().nth(1) == Some("fast");
// LLVM spells each fast-math permission three ways: the aggregate `fast`, the individual
// keyword, or not at all. Metal honours the distinction -- a module compiled
// `air.compile.fast_math_disable`, and any `precise` expression inside one that is not, carries
// neither keyword. SPIR-V has no per-module math mode, so a withheld permission has to travel
// on the instruction; see `emit_body_inst`.
let float_math_mode = granted_float_relaxations(rhs_of(line));
let alloca_ty = if opcode == "alloca" {
resolve_alloca_ty(line)
} else {
@@ -604,7 +610,37 @@ pub(in crate::native) fn push_inst_line(
opcode: TirOpcode::new(opcode),
data: Box::new(TirInstDetails {
fast_math,
float_math_mode,
payload: data,
}),
});
}
/// The fast-math permissions a float arithmetic instruction's flag run GRANTS, or `None` when it
/// grants everything and an undecorated SPIR-V instruction already says so.
///
/// An LLVM flag run is a whitelist and a SPIR-V `FPFastMathMode` is a whitelist, so this is one
/// translation rather than a per-permission question. Reading it as "does it withhold fusion" and
/// "does it withhold the reciprocal" -- two booleans for two of the seven permissions -- left
/// reassociation unstated on 437 corpus sources whose association chains Metal will not regroup.
///
/// The flag run is the whitespace-separated tokens between the mnemonic and the type: `fmul fast
/// float` grants everything, `fmul afn arcp ninf nnan nsz float` grants four of the seven, and a
/// bare `fsub float` grants none. A vector type stops the scan on its own (`<4` is not
/// all-lowercase), which is what keeps the type's words out of the flag run.
fn granted_float_relaxations(rhs: &str) -> Option<FloatMathMode> {
let mut tokens = rhs.split_whitespace();
if !matches!(tokens.next(), Some("fmul" | "fadd" | "fsub" | "fdiv")) {
return None;
}
let flags = tokens
.take_while(|token| token.chars().all(|c| c.is_ascii_lowercase()))
.collect::<Vec<_>>();
// The aggregate `fast` grants everything, which is what an undecorated SPIR-V instruction
// already permits. Say nothing rather than spell it out.
if flags.contains(&"fast") {
return None;
}
let granted = FloatMathMode::from_llvm_flags(&flags);
(!granted.grants_every_rewrite()).then_some(granted)
}
+64
View File
@@ -847,11 +847,66 @@ enum TirInstData {
Select(Option<Box<(TypedValue, TypedValue)>>),
}
/// The fast-math permissions one float arithmetic instruction grants, as the set of LLVM flag
/// keywords it carries. This is a whitelist, exactly like SPIR-V's `FPFastMathMode`, so the two
/// translate one-for-one; see [`TirInst::float_math_mode`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(in crate::native) struct FloatMathMode {
/// `nnan` -- the operands and result are assumed not to be NaN.
pub(in crate::native) not_nan: bool,
/// `ninf` -- the operands and result are assumed not to be an infinity.
pub(in crate::native) not_inf: bool,
/// `nsz` -- the sign of a zero result carries no information.
pub(in crate::native) signed_zero_insignificant: bool,
/// `arcp` -- a division may become a multiply by an approximate reciprocal.
pub(in crate::native) allow_reciprocal: bool,
/// `contract` -- a multiply feeding an add may be fused into one rounding.
pub(in crate::native) allow_contract: bool,
/// `reassoc` -- an association chain may be regrouped.
pub(in crate::native) allow_reassociate: bool,
}
impl FloatMathMode {
/// The permissions an LLVM flag run grants. `afn` (approximate library functions) has no
/// `FPFastMathMode` bit and is therefore not represented: it says nothing about the arithmetic
/// operators this mode decorates.
fn from_llvm_flags(flags: &[&str]) -> Self {
let has = |keyword: &str| flags.contains(&keyword);
Self {
not_nan: has("nnan"),
not_inf: has("ninf"),
signed_zero_insignificant: has("nsz"),
allow_reciprocal: has("arcp"),
allow_contract: has("contract"),
allow_reassociate: has("reassoc"),
}
}
/// True when this mode withholds nothing that changes the arithmetic, so leaving the emitted
/// instruction undecorated says everything the flag run says that matters.
///
/// Three of the six permissions rewrite an expression: fusing a multiply into an add,
/// regrouping an association chain, and turning a division into a multiply by a reciprocal.
/// The other three -- `nnan`, `ninf`, `nsz` -- only license folding an expression LLVM already
/// had the same licence to fold, so a withheld one is observable only where LLVM KEPT such an
/// expression. Censused over all 14579 corpus sources: **3 instructions in 3 sources**, all
/// `fsub float 0.0, %x`, whose only exposure is the sign of a zero, and no shader anywhere in
/// the corpus asks an `fcmp uno`/`ord` question. Decorating for them would put
/// `SPV_KHR_float_controls2` on every module that spells a flag run at all.
fn grants_every_rewrite(self) -> bool {
self.allow_contract && self.allow_reassociate && self.allow_reciprocal
}
}
#[derive(Clone, Debug)]
struct TirInstDetails {
/// LLVM's aggregate `fast` floating-point flag on this instruction. Keeping it in the existing
/// opcode-detail allocation avoids enlarging every instruction carrier.
fast_math: bool,
/// The fast-math permissions a float `fmul`/`fadd`/`fsub`/`fdiv` GRANTS, when it does not grant
/// all of them. `None` on every other instruction and on one marked `fast`, which is the
/// permissive answer and matches how a synthesized instruction is emitted.
float_math_mode: Option<FloatMathMode>,
payload: TirInstData,
}
@@ -867,6 +922,14 @@ impl TirInst {
self.data.fast_math
}
/// The fast-math permissions this float arithmetic instruction grants, when it withholds any.
///
/// SPIR-V has no per-module math mode, so a withheld permission has to travel on the emitted
/// instruction as an `FPFastMathMode` decoration; see `emit_body_inst`.
pub(in crate::native) fn float_math_mode(&self) -> Option<FloatMathMode> {
self.data.float_math_mode
}
/// Visit the instruction's def/use edges without retaining a second copy of resolved operand values.
/// Parsed phis derive local names from `(value, predecessor)` pairs; other resolved instructions use
/// their typed operands. Unresolved shapes use the lossless scan captured at lowering. The borrowed
@@ -1183,6 +1246,7 @@ impl TirInst {
opcode: TirOpcode::Metal2VulkanInlineParameter,
data: Box::new(TirInstDetails {
fast_math: false,
float_math_mode: None,
payload: TirInstData::Plain,
}),
}
+15 -1
View File
@@ -683,6 +683,18 @@ pub(in crate::native) fn first_type_after_op(rhs: &str) -> Option<LlType> {
/// token (a type may be multi-token like `<4 x float>`). Scanning — rather than requiring the type at
/// a fixed offset — tolerates the variable run of leading non-type tokens: fast-math flags, and the
/// `fcmp`/`icmp` predicate (`olt`/`eq`/...) that sits between the opcode and the operand type.
///
/// The inner scan is SHORTEST window first, and that is not neutral: every LLVM type has a
/// parseable proper prefix, so `phi ptr addrspace(2) [ .. ]` resolves to `Ptr(0)`, not `Ptr(2)`.
/// `parse_type_prefix` (used for parameters) scans longest-first and does not have this shape.
/// Correcting the order here was MEASURED over all 14,579 corpus sources and is not an improvement:
/// four modules gain an unbounded `reserve_pointer_phi_provenance` recursion (a stack-overflow
/// abort, not a refusal), and once that is broken the one module whose bytes change loses its typed
/// `runtimearray<float>` buffer views for raw `runtimearray<uint>` ones. Every other source is
/// byte-identical, because `types_compatible(Ptr(0), Ptr(2))` is false and every `value_id` caller
/// for a pointer phi is spelled `if let Ok(id)` and takes its fallback — the fallback is what
/// lowers pointer phis, and it is the better lowering. Do not "fix" the order on its own; the work
/// it would unblock is a pointer-phi provenance route that measures worse than what runs today.
pub(in crate::native) fn first_type_after(rhs: &str, start: usize) -> Option<LlType> {
let toks: Vec<&str> = rhs.split_whitespace().collect();
for begin in start..toks.len() {
@@ -697,7 +709,9 @@ pub(in crate::native) fn first_type_after(rhs: &str, start: usize) -> Option<LlT
None
}
/// The first parseable type token at the start of `s` (for a select arm `<ty> <v>`).
/// The first parseable type token at the start of `s` (for a select arm `<ty> <v>`). Shortest window
/// first, with the same `Ptr(0)`-for-`ptr addrspace(N)` consequence and the same measurement behind
/// it as [`first_type_after`].
pub(in crate::native) fn first_type_token(s: &str) -> Option<LlType> {
let toks: Vec<&str> = s.split_whitespace().collect();
for end in 1..=toks.len() {
+1
View File
@@ -73,6 +73,7 @@ impl TirBlock {
// The lighter incoming-values view is filled by `recompute_phi_uses` below.
data: Box::new(TirInstDetails {
fast_math: false,
float_math_mode: None,
payload: TirInstData::Phi {
parse_error: None,
incoming: Some((ty.clone(), incomings.to_vec())),
Loaded 100 of 772 files, more files were not shown because too many files have changed in this diff. Show more