bc23fe636b998c2e7a2e87bf2ae8d2a29bf3a02a
76
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
bc23fe636b |
Say which view went unrepaired, not which arithmetic computed the offset
Nine of the twelve remaining non-function-pointer corpus rejections are one shape, and its
diagnostic pointed away from it. `index 0 into %22 (TypeStruct %21) is %658 (BitwiseOr %657 %655)`
names the instruction that computed the offset, so the message reads as though the AIR contained an
`or` — it does not; none of these sources contain a single `or`, and the operand is emitter-
synthesized address arithmetic that varies by source (`BitwiseOr` in eight, `SConvert` in the
ninth). A previous session authored three synthetic reductions of that `BitwiseOr` shape and all
three translated cleanly, because the operand was never the trigger.
What the module does say, and did not report: `%22` is a single-member struct over a runtime array
of `TypeInt 32`, and the chain's own result pointee is `TypeInt 8`. That is the whole diagnosis — a
byte view of a word array, arriving as one dynamic index into the raw-word block, which is the shape
the four `rewrite_dynamic_struct_index_*` passes exist to repair and none of them matched. It also
distinguishes the ninth source, whose struct has six members and so is a genuine bad member select,
not a view at all.
So on that shape — and only that shape, since a dynamic index into any other struct really is a bad
member select — the violation now names the element type and the view type. Verified against the
corpus: it reports `TypeInt 8` over `TypeInt 32` on all eight, and stays silent on the ninth.
Behaviour is otherwise unchanged: 2880 corpus sources byte-identical against
|
||
|
|
d862cd11ee |
Key the structurizer's cached analyses on a block revision, not on remembering to invalidate
`forest_loop_merges` caches a `LoopForest` and a selection-merge map across the loop headers it plans, because deriving them once per graph edit instead of once per header is the difference between a bounded translation and a quadratic one. It invalidated that cache by hand: eight separate `collision_cache = None` assignments, one per mutation site, plus a `mutated` flag threaded through the collision branch to drive two more. Every future edit that adds a mutation has to remember to add a ninth, and a missing one is invisible — the stale forest still answers every query, just about the graph as it was. `RewriteBlocks` owns the block list and a revision only it can advance; `AnalysisCache` remembers the revision an analysis came from and re-derives exactly when it no longer matches. The eight assignments and the `mutated` flag are gone, and there is nothing left to forget. `rewrite` advances the revision only when a rewrite commits, which is sound because a decline leaves the list untouched ( |
||
|
|
02c3f9e2a8 |
A declined CFG rewrite must hand back the CFG it was given
The structurizer's `synth_*`/`split_*` primitives all advertise the same contract —
`synth_two_target_dispatch` states it outright: "Apply only after every region/type/dominance
proof succeeds, so a declined dispatch leaves the caller's owned CFG untouched" — and callers
depend on it. `forest_loop_merges` only drops its cached `LoopForest` and selection-merge map when
a primitive reports `Some`; a decline that edited the blocks anyway leaves that cache describing a
graph that no longer exists, and every later header is planned against it.
Six primitives edit before their last proof. Two are reachable, and the new tests reach them:
- `split_two_target_critical_edges` redirects the source terminator to both fresh edge blocks
before it has checked that each dispatch target is a block. When one is not, it bails with the
redirect applied and the edge blocks never inserted — the source ends up naming successors that
are not in the function.
- `synth_multi_exit_merge` composes that split with the dispatch proof, and the split must run
first (the proof needs one unambiguous predecessor per exit). So any dispatch decline — an
uncarried block, a non-dominating live-in, a live-in whose type cannot cross the funnel — returns
`None` with the loop's critical exit edges already split.
The other four (`synth_two_target_dispatch`, `synth_multi_latch_continue`,
`synth_unique_selection_merge_phi_explicit`, `split_phi_overlap`) each stage their proofs correctly
and then leak on one trailing `lower_block_carrier(...)?` — the last of which would abandon phi
rewrites and edge redirects pointing at a merge block it failed to build. I could not author an
input that reaches any of them: they lower a fixed synthetic `br` line, which the codebase treats
as infallible elsewhere (`terminal_exit.rs` `.expect("synthetic conditional carrier is always
parseable")`). They are unreached today, not guaranteed.
That is the shape of the problem: the contract held only where someone had proved every `?` in a
body unreachable-after-the-first-edit. That is not a property a reviewer can check by reading, and
not one the next edit preserves. So `atomic_rewrite` now runs each of the six against a private
copy and commits it only on `Some`. `BodyBlock` keeps its payload behind an `Arc`, so the copy is a
vector of (name, role, pointer) and only blocks the rewrite actually edits are deep-copied — the
copy-on-write `typed_mut` already performs on every edit. A borrowed name counter is deliberately
not rolled back, so names a declined attempt consumed stay consumed and every synthesized name
stays unique across attempts.
Verified: 2880 corpus sources byte-identical against
|
||
|
|
eac559dcb3 |
Build the structurizer's test CFGs from one fixture, not six copies
Six `#[cfg(test)] mod`s under structured_emit each carried a private, byte-equivalent `bb(name, lines)` (reject.rs's took a role, which is bb_role). A file without a test module therefore had to grow a seventh copy before it could grow its first test, and a change to how production populates a block carrier had to be found in six places. One `test_support` module owns both constructors; every test module imports them. |
||
|
|
1b119af370 |
Pin the two unsupported classes that actually turn up
`tests/must_fallback.rs` exists so a refactor cannot quietly turn a clean FALLBACK into SPIR-V that
"succeeds" with garbage, and it covered the classes that were easy to name: raytracing intrinsics,
emask intrinsics, texture atomics, malformed modules. It did not cover either of the two classes
that account for almost every real rejection.
Measured over the 2880-source local corpus sample: 204 sources do not translate, and 191 are one of
two shapes -- a call through a Metal visible function table (136) and an intersection whose custom
intersection functions come from a function buffer (about 55). Both are function pointers, which
Logical SPIR-V does not have, so neither is a lowering waiting to be written; the only way they can
change is by becoming wrong. Each is now an authored kernel in the negative suite, and each was
checked to produce the same diagnostic the corpus sources produce, through the public
`translate_sanitized_native` path rather than a component entry point:
unsupported indirect call through function pointer %fp (Metal visible function table)
unhandled air.* intrinsic: air.intersect.intersection_function_buffer.triangle_data
Both inputs are authored, not extracted: the `HEAD`/`TAIL` template already in that file with one
construct injected, so the rejection is attributable to the construct and to nothing else --
`base_kernel_translates` is the anchor for that. `kernel_with_declarations` is the only new
scaffolding, for the two cases whose callee needs declaring.
The `intersection_function_buffer` tag suffix is a combinatorial family -- the corpus alone has
`instancing`, `triangle_data`, `world_space_data`, `user_data`, `primitive_motion`,
`instance_motion` and `multi_level_instancing` in about twenty combinations. The rejection is on the
`intersection_function_buffer` stem rather than on any one combination, so one of them stands for
all of them and the test says so.
Tests only; no product code changed. Full gate green.
|
||
|
|
4968b0a7dd |
Say which residual CFG limit left a function with no construction
`native emitter: selected CFG function cannot be constructed` was the whole error. A shader that
crosses the state-machine construction's fixed 8192-block ceiling got exactly that, and the ceiling
is not derivable from anything its author can see: finding it means bisecting the shader. It took
one this session -- an 8195-block generated kernel translates at 8192 and fails at 8195, with no
hint that a size boundary was the reason.
The reasons already existed. `rewrite_function` names a residual CFG limit at each of its thirteen
`bail` sites, and every one of them went only to a `METAL2VULKAN_RELOOP_WHY` trace. They now come
back to the caller as `ReloopDecline { function, blocks, reason }`, and the emitter's error carries
them:
native emitter: selected CFG function cannot be constructed; the state-machine construction
declined %1041 with 8195 blocks: too-many-blocks (the state-machine ceiling is 8192 blocks)
`rewrite_function` returns `Result<(), &'static str>` rather than `bool` so that an unnamed decline
cannot be written. Three of its declines were a bare `return false` -- a block with no label, a phi
with no result type, malformed phi operands -- and are now `block-without-label`,
`phi-without-result-type` and `malformed-phi-operands`. The type is the enforcement; a test that
scanned the source for `return false` would have been checking what the compiler already checks.
`relooper_block_ceiling` gives the boundary a name (`MAX_RELOOPER_GROUPS` nested dispatch groups of
`MAX_RELOOPER_BLOCKS` cases) instead of leaving it as a multiplication inside a bail condition, and
`a_function_over_the_state_machine_ceiling_declines_by_name` pins it exactly: a function at the
ceiling does not decline for size, and one block over does, by that name and with that count. It
builds its module directly rather than assembling, so it needs no `spirv-as` -- the size check runs
before any terminator is decoded.
The decline list is bounded to four with a count of the rest, like the contract renderer in
`af3a097`.
Scope of the evidence: no source in the 2880-source local corpus reaches this path, so the message
is verified on the generated 8195-block kernel, not on captured input; output over those 2880 is
byte-identical. Full gate green -- fmt, clippy `-D warnings`, rustdoc `-D warnings`,
`cargo test --release -p metal2vulkan`, `cargo test -p metal2vulkan-validation`, and the debug build.
The nesting structurizer, which declines first, still reports no reason of its own; the error says
only what the state-machine construction knows and claims nothing on its behalf. The 8192-block
ceiling itself is deliberate and unchanged -- large flat dispatch switches have pathological driver
compile behaviour -- so this makes the boundary visible rather than moving it.
|
||
|
|
c43bb11612 |
Record the structurizer's selection splits too, and count the analyses so neither comes back
The selection structurizer re-derived dominance and rebuilt the source CFG after every private merge it spliced in, the same defect fixed one commit ago in the merge-ownership pass. Counted on the slowest source in the local corpus -- a 44-block kernel that took 4.2 seconds -- translation built 19,384 source CFGs, and 9,522 of them, 55% of the total block-visits, came from that one statement. It is now 2.7 seconds, and it is the slowest source in the corpus by wall clock. `unique_selection_merges_with_loop_exit_and_forced_inner` splices a pass-through in front of a shared natural merge, once per header that claims it, and the `!construct_tree_owned` arms then re-derived so the new block would participate in the next header's ownership question. Recording the split answers that exactly, for the reasons `Dominators::record_pass_through` sets out: a pass-through elides out of every path through it, so the blocks that were already there keep their dominators, and the new block's follow from its predecessors. The natural loops were already known to be unchanged -- an acyclic pass-through in front of an existing block adds no back edge -- which is why the old code called `analyze_reusing_natural_loops` rather than `analyze`. The last commit's `PassThroughDominance` is folded into `Dominators` itself. The structurizer's `cur_forest` has to stay a `LoopForest` (the synthesis functions take one), so the recording has to be reachable from there; putting it on the dominator relation gives it to both callers with no signature churn, and `LoopForest::record_pass_through` forwards. The contract that a pass-through is never itself a split target is now a `debug_assert!` that costs nothing until something records. `header_owned_merge_predecessors` replaces two identical copies of the rule for which predecessors a selection header owns. It has a third caller now -- recording a split means naming the edges it carried -- and three copies of that filter would be three things to keep in step. Two regression guards, because the two ways to be quadratic need different instruments: * `src/native/tests/bounded_work.rs` counts source CFG constructions for a kernel whose loop exit is claimed by six selections. 871 as it stands; 2209 with the re-derivation put back; the bound is 1400. The count is exact and machine-independent -- six sizes reproduce to the block over repeated runs -- where the wall time this defect actually costs is neither. The counter is `#[cfg(test)]`, thread-local, and absent from a release library. * `tests/bounded_growth.rs`'s total-allocation bound, added last commit, is what covers the merge-ownership pass; this kernel does not reach that pass, and its peak-memory bound sees neither. Both files now say which defect each number catches. Verified byte-identical over 2880 local corpus sources, and over the generated irreducible chain at 1502, 3002 and 6002 blocks. A fresh timing sweep over the same 2880: 0 over the 20-second ceiling, slowest 2.74s. Full gate green -- fmt, clippy `-D warnings`, rustdoc `-D warnings`, `cargo test --release -p metal2vulkan`, `cargo test -p metal2vulkan-validation`, and the debug build so the new `debug_assert!` and the counter both run. Not claimed fixed: 871 whole-function analyses for a seventeen-block kernel is still far more than that kernel is worth, and the retry ladder, not any one pass, is where the rest of them come from. |
||
|
|
1eec182d2b |
Record each merge split instead of re-deriving the whole function's dominance after it
`privatize_reused_emitted_merge_targets` gives every owned construct its own merge by splitting
edges into a shared merge target. It called `loopforest::analyze(blocks)` once per claim, so a
function with one construct per block paid a whole-function analysis per construct. Measured on a
generated irreducible chain (`tests/bounded_growth.rs` builds the same shape):
blocks before after
1502 2.99s 0.40s
3002 11.53s 1.27s
6002 27.92s 4.87s
The 6002-block case was over the hard 20-second per-attempt ceiling in AGENTS.md. 87% of its
samples were inside that one call; a 750-claim run over 250 distinct targets re-derived dominance
750 times.
Two things were wrong and both are structural.
The pass only ever asks whether one block dominates another -- it never touches a natural loop --
but it asked for the loop forest, which pays for back-edge discovery, a body closure per header,
and a nesting comparison between every pair of loops before it can answer. `graph::block_dominators`
is now the way to ask the narrow question.
And re-deriving after a split is not needed at all. A split inserts one pass-through `S` between
some predecessors of `T` and `T`; every path through `S` is the old path with `S` elided, so
dominance among the blocks that were already there is exactly unchanged, and every path to `S` is a
path to one of its predecessors plus one edge, so a block dominates `S` exactly when it dominates
all of them. `graph::PassThroughDominance` computes the relation once and records each split.
Recorded splits resolve transitively to original blocks, so a pass-through carrying an earlier
pass-through is answered too.
`a_recorded_pass_through_answers_what_a_fresh_analysis_answers` performs two chained splices by
hand and cross-checks every dominance pair against the definitional path oracle already in that
file, so the equivalence is checked rather than argued.
`tests/bounded_growth.rs` gains the guard for this defect class. A peak-memory bound cannot see it:
each dominance table is linear and short-lived, so the high-water mark stays flat however many
times it is rebuilt. Total bytes handed out does see it. Doubling the function multiplied total
allocation by 3.71 before (187 MB -> 694 MB) and by 1.95 after (27 MB -> 54 MB); the bound is 2.6,
between them, the same way the existing peak bound sits between 2.00 and the dominator-set
representation's 3.85.
Verified byte-identical over 2880 local corpus sources and over the generated chain at 752, 1502,
3002 and 6002 blocks. Full gate green: fmt, clippy `-D warnings`, rustdoc `-D warnings`,
`cargo test --release -p metal2vulkan`, `cargo test -p metal2vulkan-validation`, and the debug
build so the new `debug_assert!` runs.
Still superlinear, and not claimed fixed: the per-claim scan over every block remains, now at a
couple of hash lookups each rather than a rebuilt analysis. A 12002-block chain still takes 18.3s
before returning an honest construction FALLBACK.
|
||
|
|
de7a3b7ba2 |
Measure that translation memory grows with the function, not its square
The 500 MiB per-translation budget does not get broken by leaks; it gets broken by an analysis whose representation is quadratic in the block count. One such representation shipped and stayed for a long time, because nothing about it is visible on a small graph and every individual translation it produced was correct. `tests/bounded_growth.rs` installs a counting global allocator, translates a generated kernel at 302 and 602 blocks, and asserts that doubling the function does not much more than double peak translation memory. The ratio is a property of the code rather than the machine: the allocator counts bytes the translation asked for, which is the same number on any host, so this is not a microbenchmark. The generated function is a chain of irreducible pairs. That shape is what reaches the nesting structurizer's reducibility question -- the one that carried the quadratic table -- and it also forces the whole function onto the CFG-construction path instead of the ordinary structured planner, so the analyses under test actually run. Calibrated by running it against the defect: with the dominator-set form put back behind `Graph::dominators`, the two functions measure 4.59 MB and 17.66 MB, a 3.85x growth, and the test fails with that number in the message. With the tree form they measure 2.50 MB and 5.00 MB, exactly 2.00x. The limit is 2.6. |
||
|
|
9d662c9461 |
Classify the rejected graph once, not two or three times
The construct-tree recovery in `emit_function` tries two recognizers in turn, and each opened by calling `structured_reject_reason` on the graph -- which replays the whole planner ladder: privatization prepasses, loop forests, dominators, post-dominators, several `structured_plan` variants. The caller hands both recognizers the same blocks (the arm that rewrites them is also the arm that skips the second recognizer), so that was the same pure function of the same input, computed twice. The straddle recognizer then derived it a third time inside its witness derivation. The comment above the call site already said this "duplicates the very planner work the global ownership tier exists to replace", and the response had been to gate it on block count. That bounds the damage; it does not remove the work. Under 300 blocks it was still paid in full, and 300 blocks is most shaders. Both recognizers now take the classification as an argument, so they cannot re-derive it, and `emit_function` derives it once. Measured, release build, byte-identical output: fc78a004… (73-block fragment) 9.81s -> 4.54s 5c3f91cc… (31-block fragment) 4.53s -> 2.16s 2cc5611e… (31-block fragment) 4.63s -> 2.16s f0592493… (31-block fragment) 4.48s -> 2.13s These were the four slowest sources in a 2880-source corpus sample; the sample is byte-identical end to end (0 of 2880 differ). Two tests pin the sharing rather than the timing. Each recognizer is handed an *admitted* graph plus its own classification and must get past the gate to the witness derivation; handed no classification it must decline. An edit that reached for `structured_reject_reason` inside either one would derive `None` for these graphs and fail both directions. |
||
|
|
07c999ad65 |
Finish the job: the source CFG and the emitted CFG share the one dominator core
Correction to
|
||
|
|
db01510465 |
Leave one dominator computation in the crate, not three
The owned-CFG check, the relooper's loop-header scan, and (as of the previous
commit) the nesting structurizer each ran Cooper-Harvey-Kennedy over reverse
postorder and numbered the result into Euler intervals. Three copies of one
algorithm is how the structurizer ended up with dominator *sets* in the first
place: nobody writing it had a shared implementation to reach for.
Moved the index-based core out of `owned_cfg` into `native::dominators`, which
is now its only home, and pointed the structurizer's shape layer at it through
a label-to-index map it can build in one pass. `owned_cfg` and `rewrites` are a
pure move; the shape layer loses the private copy added in
|
||
|
|
fdece243c0 |
Stop asking one reducibility question with a quadratic dominator table
The nesting structurizer decided reducibility from full dominator *sets*: a `BTreeSet` of every dominating block, per block. That is quadratic in the block count, and generated shaders reach block counts where it dominates the whole translation's memory. On an MPS convolution kernel with a 6301-block function it materialized ~40 million set entries -- peak RSS went 85 MB -> 502 MB inside `Graph::is_reducible` alone, and the module then finished at 535 MB, over the 500 MiB per-translation budget that AGENTS.md makes a correctness contract. Replaced it with the Cooper-Harvey-Kennedy immediate-dominator iteration over reverse postorder, numbered into one pre-order interval per block. Dominance is then two integer comparisons, and the structure is linear in the block count. The reducibility walk itself is untouched; only the question's answer moves. Measured on the 21 corpus sources the audit recorded as memory-limit failures, release build, `/usr/bin/time -l`: the 16 that reach the structurizer drop from 509-546 MB to 86-107 MB peak RSS, and are a little faster (2.6-3.0s vs 3.0-3.4s). The other 5 fall back early and are unchanged. Output is byte-identical on all 21, and on a 640-source corpus sample (0 of 640 differ). Two tests. `the_dominator_tree_agrees_with_the_dominator_sets` keeps the dense fixpoint as a test-only reference and cross-checks every ordered block pair on eight graph shapes, including the irreducible ones the verdict exists for. `the_dominator_structure_stays_linear_in_the_block_count` asserts the structure holds one number per reachable block on an 8001-block graph, which is the property that regressed here: the dense form would report n*(n+1)/2. |
||
|
|
d882fa599b |
Report every contract violation a phase leaves, not just the first
The pass-contract trace stopped at the first owned-construction failure, and in flight that is routinely the least interesting one. Lowering leaves dangling debug `OpName`s behind constantly and repairs them a few phases later, so on the two access-chain repros the trace read "Name references undefined id" for five consecutive phases -- masking, in one of them, an access-chain violation that was already present and never repaired. A reader following the trace blames whichever phase runs after the repair. That is not hypothetical; it cost a previous session a round. Split `owned_module_failure` into a prerequisite stage and a set of independent checks. Section layout and the id-collection scan stay hard stops, because a failure in either leaves the definition table incomplete and every later check would be reading nonsense. Everything after is collected into `owned_module_failures(module, limit)`. The gate calls it with limit 1 and is unchanged; the trace calls it unbounded and prints all of them. On the `particle_compact_data` repro the trace now shows the bad struct index present from "air lowering start" onward -- i.e. introduced by the interface phase -- where before that line said only "Name references undefined id %50". |
||
|
|
af3a097cdc |
Bound the contract renderer, and correct two claims I made earlier
describe_owned_id printed every operand of the defining instruction, so a
wide OpTypeStruct or a phi with many arms would have buried the sentence
the message exists to say. It now shows eight and counts the rest, and has
a test that pins all four renderings including the undefined-id case.
Two corrections to the record, since the commits that made these claims
cannot be amended:
1.
|
||
|
|
ad355fcf49 |
Let the lowering pipeline name the phase that broke a contract
A contract violation is a property of the FINISHED module. Which of the phases in transform_with_options_and_sidecar introduced it is not recorded anywhere, so diagnosing one means bisecting the pipeline by hand -- which is exactly what I was doing when I wrote this. METAL2VULKAN_PASS_CONTRACT=1 now prints the owned-construction verdict after every phase. It is a debugging aid, not a gate: a module part-way through lowering is allowed to violate the contract, since several phases exist to repair what an earlier one left behind. What the trace shows is the shape of the run, and the phase whose verdict first turns bad and never recovers is the one to read. Two things were needed to make it readable rather than noisy: - The verdict merges ctx.new_globals into the module before checking. Phases stage new declarations there and splice them in only at the end, so checking ctx.module alone reported an undefined id for every phase in between and drowned out the real signal. phase_contract_verdict is split out from the printing so both halves of that are unit-tested. - "owned module references an undefined id" now names the referencing instruction and the id: "owned Name references undefined id %50". On the module I was bisecting, that one change turned five phases of noise into a diagnosis -- a stale OpName left pointing at a removed id, cleaned up later, and nothing to do with the failure being chased. |
||
|
|
c2ba4ab9a4 |
Name the value a non-constant struct index actually is
The clause split in
|
||
|
|
a2f4380448 |
Discover BDA storage pointers in the order the module presents them
A sixth instance of the emission-order class fixed in
|
||
|
|
63b0c80d0b |
Say which clause of the access-chain contract failed
"owned InBoundsAccessChain violates its pointer storage, index path, or result-pointee contract" names three possible causes and commits to none. It is the largest single failure class in the corpus audit (~40 of 88 at the last fingerprint), and diagnosing one instance meant disassembling the module by hand to find out which of the three it was. The check was one boolean conjunction, so it had nothing to report. It now evaluates the clauses in the order the contract reads and names the first one that fails, with the offending type rendered as its declaration: base %418 has type %27 (TypeInt 64 0), which is not a pointer type which is the dominant class, and says plainly what it needs: a 64-bit device address used as an access-chain base wants OpConvertUToPtr into PhysicalStorageBuffer, not anything to do with index paths. The verdict is unchanged -- the accept/reject decision is still the same conjunction, and which clause gets named cannot move it. What changed is that the twelve rejections in owned_module_enforces_access_chain_contracts are now paired with the clause each must be rejected FOR. All twelve turn out to trip nine distinct clauses; a blanket "was rejected" assertion would have stayed green if one of them had started tripping an unrelated clause by accident. The triage normalizer collapses digit runs, so the ids in these messages fold away and the audit groups these by reason instead of by one bucket. |
||
|
|
a5e01c3f0e |
Take five more emission decisions off hash-map iteration order
A kernel with an unbound buffer parameter translated to different bytes on
almost every run. Its loads from the absent resource each become a copy of
that type's null, and the nulls were minted by iterating a HashSet of the
load result types -- so three loads of three distinct types came out in one
of six orders. tests/deterministic_output.rs has the reduced kernel, plus a
probe asserting it still reaches that rewrite, so the test cannot quietly
start passing over nothing.
Auditing the rest of the pipeline for the same shape -- a hash collection
whose iteration order decides what gets minted or pushed -- found four more:
native/psb.rs OpTypePointer per memory-view pointee
native/rewrites.rs wrapper struct + pointer + decoration per
candidate pointer type
passes/.../texture_array.rs one access-chain id per bound handle, and
the dead-root list
passes/.../selected_load.rs OpDecorate ArrayStride per pointer type
Each now walks the module's own instruction stream instead, which makes the
order a property of the input. src/emission_order.rs holds that idiom in one
place so the correct spelling is the short one, and says which collection
each kind of question wants: a HashSet is still right for pure membership,
where nothing is ever iterated.
Verified over 900 local-corpus sources: 820 translated, 0 varied across four
in-process translations each. Before these fixes the same sweep found 24
varying inputs in its first 400.
The cross-stage fixture sweep is new and is what made the reduction findable:
determinism has to hold for whatever stage the caller passes, and translating
each fixture at all three reaches paths the declared stage never does -- a
parameter the declared stage binds to a descriptor is an unbound Private
placeholder under another.
|
||
|
|
b2b563d414 |
Stop rebuilding all 262k lines for a one-line edit
There was no slow flag to remove: the release profile was Cargo's default, and that default turns incremental compilation off. With one crate this large, that makes every rebuild a full rebuild. Measured on an idle machine: one-line source edit, rebuild 24.97s -> 1.67s cold build 24.02s -> 23.37s 300 corpus modules x4 translated 46.6s -> 46.2s So the edit-rebuild loop gets ~15x shorter, and neither the cold build nor translation throughput moves. The throughput figure is repeatable to within 0.5s run to run, so the per-translation budget in AGENTS.md is untouched. Profiles only apply from the workspace root, so this changes how the repo builds itself and nothing about how a consumer builds the published crate. |
||
|
|
6c4f33f3ee |
Write down two commit rules that were only ever conventions
Both were being followed by habit and neither was written anywhere, so each new contributor (human or agent) had to rediscover them: - Never amend. An existing commit is history someone may already have read; corrections belong in the next commit, not in a rewrite of the last one. - Every commit is a release candidate. Landing a half-applied refactor or a fix whose test is still to come leaves the tree in a state where the pre-commit gate no longer means what it claims. Large changes get split into independently sound steps, not into a break followed by a repair. |
||
|
|
e73c87d49b |
Stop three emission decisions from following hash-map iteration order
The same AIR translated to different SPIR-V on every run. Not different ids that canonicalization normalizes away -- genuinely different modules: a different prologue order, different constant declarations, different type declarations. Each run was individually correct and passed spirv-val, which is why nothing caught it. It matters because the validation ladder compares a candidate's output by SHA-256, consumers cache translated SPIR-V by content hash, and a bug report is only reproducible if the module that produced it can be produced again. Three sources, all the same shape -- an unordered collection deciding the order something is emitted or minted in: - native emitter (functions.rs): the device-address prologue materializes one address per direct buffer parameter, and that list was built by iterating `raw_offsets`. The position each address lands at fixes which address-table slot the module reads there, so the whole prologue permuted. Order by entry parameter ordinal, which is stable and is the order a reader expects. The rewrite also drops a redundant `contains_key` and, with it, an eager map index that would have panicked on any raw offset that is not a direct parameter. - buffer-address lowering (buffer_addresses.rs): `ctx.const_uint` mints a constant the first time it sees a value, so the order the table's location constants were requested in -- taken from a `HashSet` -- was their declaration order. - nesting structurizer (reloop_nest/emit.rs): `demote_phis` walked `blocks.keys()`, minting a variable and a `TypePointer Function` per demoted phi in hash-map order. Record the function's own block order at indexing time and walk that. tests/deterministic_output.rs pins the contract. Rust seeds every HashMap's hasher differently, including two built in the same process, so translating one input twice in one test is enough to expose an order-following emission decision -- it is strictly stronger than comparing two CLI runs, and it found the second and third sources after the first was already fixed. It covers an authored four-buffer device-address kernel (with a guard that the kernel still lowers to an address table, so the case cannot decay into covering nothing) and every public fixture that translates. Verified: the authored kernel produced 6 distinct hashes in 6 CLI runs before the first fix and 1 after; 12 in-process runs collapsed from 2 distinct modules to 1 after the second. Over 1267 sampled local-corpus sources, 1159 translated and 2 still varied before the third fix; after it, a 240-source sample was fully stable and the two known varying cases were checked individually. cargo test -p metal2vulkan: 1704 lib + 3 determinism + 3 env + 6 fallback, all passing. Workspace clippy -D warnings and all-features Rustdoc: clean. |
||
|
|
9a642e930c |
Hold constructed shapes to validity and to a binary round trip
Executing a construction says it computes the right thing. It does not say a driver would accept it: SPIR-V's structured control flow rules -- a block before every block it dominates, a merge dominated by its header, a construct left only at its own merge or an enclosing loop's continue -- are all things a semantically correct rewrite can still break. spirv-val is what knows them, and until now it only ever saw authored fixtures. Point it at the generated family. The authored shape is invalid on purpose, since that is what selects construction, so only the output is validated. Two fixture corrections were needed first, both of them the fixture's fault rather than the product's: the header claimed SPIR-V 1.6, which is rejected before any content is examined under the Vulkan 1.2 target, and the entry point did not list its Private globals, which SPIR-V 1.4 onward requires whatever the storage class. Also round-trip each constructed module through binary and compare the disassembly. An assembler and a parser that disagree about an instruction's encoding are invisible to both validation and execution of the in-memory module, and a consumer takes the bytes. Verified: 3600 constructed modules over depths 2-7 and 0-3 crossings, every one accepted by spirv-val. The committed guards hold 64 of those plus 48 round trips, which keeps the suite fast -- spirv-val is a subprocess per module. cargo test -p metal2vulkan: 1704 passed. Workspace clippy -D warnings and all-features Rustdoc: clean. |
||
|
|
e33ff25ce2 |
Run the constant-folding optimizer against an executable oracle
constfold is a general optimizer -- constant propagation, conditional-branch folding, unreachable-block removal, trivial-phi collapse, DCE, to a fixpoint -- and its whole correctness argument is that it only removes what cannot execute. Its tests were authored fixtures asserting which instructions survive. That checks the rewrite it performed, not the meaning it was supposed to keep. Give it a subject it cannot argue with. A generated shape seeded from a constant-initialized Private global -- the shape a Metal [[function_constant]] compiles to at its disabled default, and exactly what the optimizer keys on -- has one answer. Author it as a void GLCompute entry point that stores that answer into a Private slot, run it, fold it, and run it again. The entry point is not decoration: sweep_uncalled_functions deletes any function no entry point reaches, so a module without one has nothing left to check after folding. Building it needs the entry-point mode and Private globals now in the builder, and module-scope variables with initializers in the interpreter. Both pass orders are exercised. Folding a constructed CFG and constructing a folded one both happen in the pipeline, and an optimizer that is right on the input shape can be wrong on the shape a structurizer left behind. Verified: 8000 constant-seeded modules over depths 2-6, 0-2 crossings and four seed values, each checked in both orders -- 16000 runs, none disagreeing with the function before folding. The committed sweep holds 128 of those. constant_folding_actually_removes_blocks_from_a_constant_seeded_shape pins that the fold is doing work at all (measured 4131 blocks to 3772; the rest are inside loops whose accumulator is not a constant), so the sweep cannot pass by folding nothing. cargo test -p metal2vulkan: 1702 passed. Workspace clippy -D warnings and all-features Rustdoc: clean. |
||
|
|
706ba952d3 |
Put the phi-demotion swap hazard under the differential sweep
Every generated shape carried one live value, so every join had one OpPhi and the hardest question a phi demotion has to answer never came up: what happens when two phis at the same block read each other. `x = phi(x0, y); y = phi(y0, x)` is a simultaneous assignment. Demoting the pair to memory turns it into two sequential stores, and in the obvious order the first clobbers what the second was about to read. Both structurizers demote phis -- the state machine demotes every value that crosses a block boundary, the nesting demotes phi results specifically -- so both have to get this right, and nothing was asking them. Carry three values through a generated function instead of one. The accumulator still drives every condition and still guarantees termination; the two new ones drive nothing and are swapped with each other on every back edge, which puts the hazard at every loop header in the family. The returned value combines all three asymmetrically, so exchanging any two of them changes the answer. Add the authored minimal case as well, and a test that the family really does carry back edges for the swap to ride on -- measured 105/112 shapes and 262 swapping edges -- so this cannot silently decay into straight-line value flow. Verified: 8000 shapes over depths 2-6 and 0-3 crossings, all three values live across every construct boundary, every one computing what it computed before construction. cargo test -p metal2vulkan: 1700 passed. Workspace clippy -D warnings and all-features Rustdoc: clean. |
||
|
|
47060c4e44 |
Take the differential sweep onto the state machine's own territory
The generated family was reducible by construction, so the nesting structurizer answered most of it and the state-machine constructor was only ever reached through what nesting handed back. That is the constructor of last resort — there is nothing behind it — and it was the least directly exercised. Let a generated shape take an edge into the interior of a region already written. The target keeps its predecessors and gains one that does not go through whatever header used to dominate it, which is exactly irreducibility, and the nesting structurizer declines it by contract. Guard the crossing with the same monotonic `accumulator < bound` test the loops use, never a mask, so it stops being taken once the accumulator passes the bound; a crossing guarded by a mask could close a cycle containing no bounded test and the shape would stop terminating. The cross-edge coin is flipped whether or not crossings are allowed, so a seed names the same underlying shape either way and a failure can be diagnosed against its reducible sibling. Also give the generator a switch region. A SPIR-V switch is not a conditional with more arms — a nested construct may break out to an enclosing switch and not to an enclosing selection — so the two take different paths through the emitter and the family should contain both. Verified: 4500 shapes over depths 2-6 and 1-3 crossings, 2879 of them declined by nesting and so constructed by the state machine; every one computes what it computed before construction. The two committed tests hold 96 of those, with irreducible_shapes_are_declined_by_the_nesting_structurizer pinning that the family really is reaching the state machine (measured 66/96) rather than quietly becoming a second run of the reducible sweep. cargo test -p metal2vulkan: 1698 passed. Workspace clippy -D warnings: clean. |
||
|
|
24f9f04308 |
Name the destination of every staged edge that leaves through a dispatch
The nesting structurizer stages an edge that has to leave more than one construct:
it records its destination in a function-scope flow variable, branches to the
innermost construct's merge, and every dispatch it passes through reads that
variable to decide whether to enter its own continuation or forward one more
level.
`resolve` decided whether to write the variable by asking the frame that owns the
*destination* — but the edge branches to the *innermost* frame's merge. When those
differ, the innermost merge is a dispatch (`classify` marks every frame it
forwards through) and reads the variable that this edge never wrote. Ask the frame
the edge actually leaves through instead.
`while (c) { if (d) { if (e) break; } q(); }` is the smallest case: the `break`
left the flow variable unwritten, so the dispatch at the selection's merge read
whatever the previous iteration had stored and ran `q()` after the break. The
module was valid SPIR-V and properly nested, so neither spirv-val, the
construct-ownership checks, nor the value-flow check in owned_cfg saw anything --
SSA dominance says nothing about what is in memory.
Contain the class as well as the case. reloop_nest::verify runs a
definite-assignment analysis for the flow variable over the emitted blocks and
declines a nesting that can reach a dispatch without having written it; a declined
function falls back to the state machine, which writes its selector on every edge.
Phi slots are deliberately out of scope there: their loads sit behind dispatch
arms the flow variable selects, so a path-insensitive analysis reports intended
routing as an unwritten read.
Add src/native/cfg_testkit, the differential harness that found this:
- build: author a synthetic uint(uint) function from named blocks, with reserved
ids for forward references and reverse-postorder emission, so a CFG shape costs
a few lines instead of a few hundred.
- interp: execute the authored integer subset -- phi, select, function-scope
variables, all four terminators -- with a step limit, so a construction that
loses an exit edge reports instead of hanging.
- shapes: grow reducible-but-unstructured graphs from a seed (sequence /
conditional / switch / loop, perforated with multi-level breaks and continues).
One monotonic accumulator threads the function, which both guarantees every
generated shape terminates and makes a mis-selected phi change the answer.
Verified: over 1500 generated shape/depth combinations, 105 constructions
disagreed with the function they replaced before the fix and 0 after. With the fix
reverted but the verifier in place, adoption falls from 1327/1500 to 956/1500 and
disagreements stay at 0 -- the class degrades to a fallback, not to wrong code.
With both reverted, the two sweep tests and the named regression fail. The
adoption-rate test pins that correctness is not being bought by declining.
cargo test -p metal2vulkan: 1696 passed. Workspace clippy -D warnings and
all-features Rustdoc: clean. cargo test -p metal2vulkan-validation: 172 passed, 1
failed -- combined_depth_stencil_outputs_use_separate_native_attachments, which
needs a Metal toolchain this machine does not have.
|
||
|
|
38d1ae3750 |
Pin both reported bugs with regression tests that fail without their fixes
The two bundles under bugs/ are fixed at HEAD, but neither loss was pinned by a test that fails when the fix is reverted, and bugs/ is gitignored, so the reproducers cannot serve as the guard. Both defects also passed spirv-val, so validation cannot be the guard either. Author the guards from the property each bundle actually lost. fragment-code-size-explosion: the module reached the driver as one OpFunction in state-machine form -- 2286 of 2296 blocks were sibling OpSwitch cases inside a single loop, with 3516 function-scope variables because sibling cases cannot dominate each other -- and vkCreateGraphicsPipelines never returned. Build a reducible-but-unstructured function (one loop over a chain of undeclared-merge diamonds), run it through the real construction path, and assert the emitted shape: a surviving loop construct, dispatch over a minority of blocks, and no variable-per-crossing-value demotion. Held at 16 and at 64 diamonds. compute-multisample-query-reports-one: air.get_num_samples_texture_2d_ms lowered to the literal 1, so a four-sample kernel visited only sample zero. Extend the family to texture2d_ms_array, and add the data-flow guard the opcode-presence assertions cannot make: the queried count must be what bounds the per-sample loop. Verified: with reloop_nest::structure_selected_functions stubbed out, the two shape tests fail reporting 51 cases over 58 blocks and 195 over 202 -- the reported 99%-coverage state machine. With the sample-count lowering forced to the constant, all three multisample tests fail; with the query emitted but its result replaced by the constant at the use, only the new data-flow test fails, which is the case it exists for. cargo test -p metal2vulkan: 1688 passed. Workspace clippy with -D warnings: clean. |
||
|
|
47009b2693 |
Trace when the nesting structurizer adopts a construction
METAL2VULKAN_RELOOP_WHY already reports every decline. Without the matching adopt line there is no way to find which inputs actually reach the nesting path, which is what authoring an execution case for it needs. |
||
|
|
93b8ad217b |
Author a nesting case and refresh MoltenVK evidence at 28580a5
colorize-uint-trace-single-cross is the first authored case whose entry adopts the nesting structurizer rather than the dispatch state machine. CC_ColorizeUIntTrace draws a cross around a trace position read from a uint texture; one thread at gid (0,0) makes the two write loops run exactly three iterations each with no two invocations touching the same texel, so the 4x4 half attachment is exactly determined. Metal and MoltenVK both produce d3db92a3c9b398259340a5b2c82c351ed488aa0b2845dd7895b05ca88a683ba7, which differs from the pre-dispatch fill, so the kernel really wrote. Full MoltenVK sweep at this commit over the 771 cases that already had a candidate observation: 769 byte-exact, 0 differing bytes, 2 translation gaps (d00df2e1 aligned memory-access, d787d24e pointer-pointee). The 14 cases that never had MoltenVK evidence still have none: 7 need Apple's externally-defined tensor-ops library, 3 cannot qualify on this device, and 4 hit translator gaps. |
||
|
|
28580a51f6 |
Read a buffer's one element view, not the first of several
A buffer parameter whose entry body indexes it with a single index and
reads a different type at each index is navigating a record, not a flat
array. body_buf_elem_type returned the first of those views, so the
interface builder wrapped the buffer as { RuntimeArray<that type> } and
every access through another view kept its own result type while the
chain now addressed the wrong element: a float2 load off a chain into a
float4 array.
Return the element type only when the body has exactly one view. With
several, the AIR struct layout is reconstructed instead, which is what
the metadata already describes.
Re-auditing the 107 known translation failures: 88 fail, 19 translate
(was 90/17). Both cross-library cases that reported 'owned Load violates
its pointer-pointee and value-type contract' now translate.
|
||
|
|
b7393a94d6 |
Refresh MoltenVK evidence for the first 453 cases at HEAD
Partial re-run of the authored-case sweep against the current translator (commit |
||
|
|
2722041b06 |
Hold a nesting to the whole construction contract, not just its value flow
Splitting the owned-CFG check leaves a structural half that reads only control flow: construct containment, structured exits, switch merges, back edges, and continue-target ownership. It needs no module-wide type tables, so the nesting structurizer can hold its own output to it before adopting it. Re-auditing the 107 rows the corpus-wide translation census failed on: 17 now translate, and every 'owned switch case exits to a non-structured target' and 'owned edge exits a construct without a structured target' failure is gone -- those functions go back to the state machine instead of shipping a nesting that leaves a construct through an unstructured edge. bugs/fragment-code-size-explosion is unaffected: still 168 loops, 608 dispatch cases, 33 function-scope variables, spirv-val vulkan1.2 PASS. |
||
|
|
e3914e93c7 | Record the sample-count query and CFG nesting changes in the changelog | ||
|
|
0a7f5d93f9 |
Record MoltenVK candidate evidence for the authored corpus
Requalified 25 cases on Metal (local-metal), then ran every case with current Metal evidence through corpus-moltenvk under local-moltenvk: 769 of 783 are byte-exact against their recorded Metal bytes. No case produced differing bytes. The 14 without a row are translation gaps, not mismatches: seven need Apple's externally-defined tensor-ops library (air.init_strided_private_tensor.*), six hit the owned Load/PtrAccessChain pointee contract, and linked-single-unit-sdpa-fwd-new never returns from vkWaitForFences. |
||
|
|
c470af1290 |
Describe the nesting reconstruction step in the architecture guide
The CFG structurization section still described reconstruction as the bounded relooper alone. Record that nesting runs first for reducible functions, what a staged edge is, and why the pass checks its own value flow before adopting a nesting. |
||
|
|
a8f6803ea5 |
Promote a demoted phi at the block where its edges meet
The promotion pass wrote the phi back into the block that loads the slot. Nesting usually puts that block one unconditional hop below the join: a loop's original header becomes the body of a synthesized header, and it is the synthesized header that owns the back edge and so the meeting of the two values. With two predecessors one step up and one step here, the slot did not promote and stayed a function-scope variable -- exactly the loop-carried values whose live ranges span the most blocks. Walk up through single-predecessor blocks that do not write the slot before choosing the phi's block. Every block stepped over is dominated by the one before it, so the phi stays in scope wherever the load was. On the bugs/fragment-code-size-explosion shader this takes function-scope variables from 489 to 33 (3516 before the nesting structurizer) and the module from 196,052 to 192,860 words, with the same 168 loops and 608 dispatch cases. spirv-val vulkan1.2 passes. |
||
|
|
acc37fdcc5 |
Check the nesting structurizer's value flow before adopting it
Nesting keeps ordinary values in registers on the premise that it preserves the original CFG's dominance. It does not always: an edge that has to leave more than one construct is staged through a merge dispatch, so its destination is reached from that merge rather than from the block that left it, and a definition inside the construct can stop reaching a use beyond it. The state machine this pass replaced repaired such functions incidentally, by demoting every crossing value. Two private corpus cases regressed to a translation failure because of that. Verify the emitted function against the same value-flow contract the module is held to -- definitions dominating their uses, and phi incoming pairs matching the block's predecessors and result type -- and put the function back on the state machine when it fails, alongside the existing structural gates. owned_cfg gains the function-scoped entry point for that check, reusing its existing phi and ordinary-use rules rather than restating them. |
||
|
|
a7f9119651 |
Put back the phis the nesting did not actually disturb
A phi has to be demoted while the structure is being derived, because nesting is free to rewrite which block physically branches into a merge. Most merges come through unchanged: each incoming edge still ends in a block that branches straight at the merge, and the merge has no other predecessor. That is exactly an OpPhi, so the slot is folded back and the variable, its stores and its load all disappear. The check runs on the emitted blocks, so it needs no model of how they were produced -- an edge that got a helper block of its own is as good a phi predecessor as the original block. It also looks through a chain of single-predecessor branch-only blocks when hunting for the store, which is what reaches a loop's continue target: the value is written by the latch that branches into it, and each block in such a chain dominates the next, so the value is still available where the phi needs it. Measured on bugs/fragment-code-size-explosion/input-frag.air: function-scope variables 951 -> 489 emitted words 199869 -> 196052 Against the state machine this replaced, that is 3516 -> 489 variables. Verified: spirv-val vulkan1.2 passes on the emitted module; full 1682-test product suite green; fmt, workspace clippy with -D warnings and all-features Rustdoc clean. |
||
|
|
0ac159bd6f |
Nest reducible control flow instead of flattening it to a state machine
The nesting structurizer now expresses everything the fragment shader in
bugs/fragment-code-size-explosion needs, so that module no longer reaches
the driver as one dispatch state machine.
Three things were missing.
Staged exits. SPIR-V lets a block leave the construct it is in and no
further, but `while (c) { if (d) { p(); if (e) break; } q(); }` leaves a
selection and a loop on one edge. Such an edge now records its destination
in one function-scope flow variable and leaves the innermost construct;
each construct it crosses carries a dispatch at its merge that either
enters its own continuation at the named destination or forwards through
that dispatch's merge block, which sits directly inside the next construct
out. An analysis pass decides which constructs need a dispatch, so a
construct no staged edge crosses and with one way out keeps a plain merge
and never touches the variable.
Switch constructs. A divergent terminator declares a selection of its own,
and SPIR-V allows breaking out of a nested construct only to an enclosing
loop or switch -- never to an enclosing selection. The analysis marks the
dispatches this applies to and they are written as OpSwitch.
Dispatch headers and arm entries. A dispatch entered from an enclosing
construct rather than fused into one terminator now gets a header of its
own, which is what gives it a merge block its arms' nested constructs may
break to; and an arm is a shape, not a block, so a loop arm is entered at
its synthesized header rather than at the original block. The latter was
producing a back edge into a loop body that bypassed the header.
Measured on that shader (release, 2.4s, unchanged):
function-scope variables 3516 -> 951
widest OpSwitch 1024 -> 122
total switch cases 2286 -> 608
OpLoopMerge 0 -> 168
emitted words 249063 -> 199869
The count that mattered is the first: the driver's compile went unbounded
promoting thousands of variables back to SSA inside one loop that held the
whole program. There are now 168 real nested loops and no whole-function
dispatch.
Verified: spirv-val vulkan1.2 passes on the emitted module; 12 nesting
tests including a new end-to-end pin for the two-construct break; full
1681-test product suite green; fmt, workspace clippy with -D warnings and
all-features Rustdoc clean.
|
||
|
|
465c76d41e |
Add a nesting structurizer for reducible control flow
The state-machine constructor can express any CFG, and that generality is why it makes every non-entry block a sibling case of one OpSwitch inside one loop. Sibling cases do not dominate each other, so every value crossing a block boundary is register-demoted to a function-scope variable. On a large function that yields one loop containing the whole program plus thousands of variables whose live ranges all span it. The module is valid, and it is also the shape a driver's shader compiler can take unbounded time on: promoting those variables back to SSA inside one enormous loop makes the dominance-frontier work superlinear in (variables x blocks). bugs/fragment-code-size-explosion is a boot that dies inside vkCreateGraphicsPipelines on exactly that module. Reducible control flow does not need it. This adds src/native/reloop_nest: the relooper shape derivation (Simple / Loop / Multiple) as pure, unit-testable graph analysis, and an emitter that writes those shapes as genuinely nested SPIR-V loop and selection constructs. Nesting preserves the original CFG's paths and therefore its dominance, so ordinary SSA values are emitted untouched; only OpPhi -- whose meaning is the predecessor list that nesting rewrites -- is demoted. It is a strict addition. Construction tries the nesting first and keeps its output only when the same structural checks that selected construction in the first place accept it; irreducible graphs and any shape the emitter does not express are declined, and those functions stay on the state machine byte-for-byte. Not yet expressed: a branch that leaves more than one enclosing construct, and loops with several entries. The fragment shader in the bug bundle still declines on the former and is unchanged for now. Verified: 11 new tests (8 shape-derivation, 3 end-to-end through spirv-as/spirv-val) plus the full 1681-test product suite green; fmt, workspace clippy with -D warnings, and all-features Rustdoc clean. |
||
|
|
7154e84d2c |
Lower the per-translation wall-clock ceiling from 30s to 20s
The hard end-to-end ceiling per translation attempt is now 20 seconds, in the corpus-triage worker guard that enforces it and in the AGENTS.md and docs/VALIDATION.md statements of the contract. The 500-MiB memory budget is unchanged. Verified: corpus-triage unit tests (15) pass; fmt clean. |
||
|
|
91a5e83f75 |
Lower AIR texture sample-count queries to OpImageQuerySamples
`air.get_num_samples_texture_2d_ms(texture)` is a property of the bound image, but it lowered unconditionally to the literal 1. A guest kernel that loops `for (s = 0; s < tex.get_num_samples(); ++s)` therefore visited sample zero only and silently dropped every other sample of a 4x MS texture. The emitted module stayed structurally valid, so spirv-val could not catch the semantic substitution. Decide the lowering from the image type instead of from a harness assumption: when the resolved operand is a 2D image with MS=1, emit OpImageQuerySamples on it; when it is single-sample, the constant 1 is the exact sample count rather than a stand-in. A multisample operand with a non-2D Dim is now an honest error, since OpImageQuerySamples is undefined there. Op::ImageQuerySamples was also missing from the ImageQuery capability inference in module_cleanup, which would have produced an invalid module the first time the query was emitted. Verified: bugs/compute-multisample-query-reports-one/repro.sh now reports PASS; two new regression tests pin the MS and single-sample paths; full `cargo test -p metal2vulkan` (1670 tests) green; fmt and workspace clippy with -D warnings clean. |
||
|
|
52c961b4de |
Tighten owned numeric conversion contracts
Split ConversionClass so each width-changing conversion carries its own shape contract instead of sharing IntegerToInteger and FloatToFloat buckets. OpUConvert, OpSConvert, and OpFConvert now require the source and result component widths to differ: a same-width conversion is not a no-op, it is an invalid instruction. OpUConvert additionally requires an unsigned result type, since it names a zero extension or truncation. Reject OpSatConvertSToU and OpSatConvertUToS as a shape class before they reach a numeric contract that does not describe them; the saturating OpenCL conversions require the Kernel capability and have no Vulkan environment. Switch the conversion checks from scalar_type_shape to numeric_type_shape so component width is available alongside opcode and lane count. Cover each rejected and accepted shape with a test that pairs the owned verdict against the independent spirv-val verdict, so the construction-time rule stays a restatement of the Vulkan rule rather than a local invention. Verified: cargo clippy --all-targets (clean). Per request, the cargo doc check and workspace test run were skipped. Claude-Session: https://claude.ai/code/session_015sJUGShcKseDFnk4WvaJU2 |
||
|
|
46957b7dd4 |
Refresh MoltenVK evidence after the upstream parser rebase
Re-execute the seventeen previously mismatching authored cases against the rebased translator, which now carries the upstream float-literal and phi parser fixes. All seventeen match on apple-m3-max-moltenvk. The rows move from translator fingerprint c1ac8568 to 72379a2b, the fingerprint of the current tree, so the recorded semantic evidence matches the shipped translator rather than the pre-rebase build. Verified: cargo build --release; corpus-moltenvk --case-id <id> --metal-environment-id apple-m3-max-macos26.5.2 --environment-id apple-m3-max-moltenvk for each of the seventeen case ids (17 Match, 0 mismatch, all exit 0). Observation shards only; no code changed. Claude-Session: https://claude.ai/code/session_01D1u4vU7Mr5QNWrnnRHC8iS |
||
|
|
08970cacd2 |
Consolidate translation, linkage, and validation work
Squash 147 commits (2026-08-20 through 2026-08-31) into one change on top of the exact-kernel-grid work. Covers native lowering and pointer/layout construction, AIR intrinsic and funnel-shift coverage, BDA address preservation across aggregate calls, CFG structurization, function-constant and visible-function specialization, the 30-second translation ceiling, the authored-case corpus and linkage validation suite, and refreshed byte-exact MoltenVK evidence. The kernel-grid lowering in this tree supersedes the 324-line variant in the parent commit; that file is reduced to its current 139-line form here. Resulting tree is identical to 7174c7b. Prior history remains reachable at tag pre-squash-backup and branch backup/pre-squash-7174c7b. Claude-Session: https://claude.ai/code/session_01D1u4vU7Mr5QNWrnnRHC8iS |
||
|
|
d98eae794b |
fix: float literal and phi parser fixes
Five LLVM IR parser bugs in metal2vulkan that caused shader translation failures on macOS Ventura x86 guests: 1. f0x hex f32 literals (f0x358637BD etc.) not parsed - Added LlValue::Float32Bits(u32) variant - Added parse_float32_hex_literal() in lex.rs 2. Decimal float used as Half type (1.0 for half-typed constant) - Added LlType::Half arm to LlValue::Float dispatch - Converts decimal floats to half via f32_to_f16_bits 3. NaN/Inf special literals (+qnan, -qnan, inf, -inf, snan) not recognized by parse_value() - Added parse_float_special_literal() in lex.rs - Handles: +qnan, -qnan, qnan, snan, -snan, +inf, -inf, inf, nan, -nan - Maps to IEEE 754 f32 bit patterns 4. phi incoming values with typed vector constants not parsed (<4 x float> <float 0x3F800000, ...>) - Added parse_phi_incoming_value() in parse.rs - Tries parse_typed_value before parse_value for phi incomings - Same fix in operand_from_bare() in operands.rs 5. Diagnostic: phi_parse_error field on TirInst - Captures parse_phi error string for debugging Tests: 1,390 pass, 0 fail (3 new regression tests) Verified on macOS 13 Ventura x86 guest: 0 phi errors, 0 m2v refusals, 0 draw skips (was 4 phi errors, 94 refusals, 106 draw skips before fix) |
||
|
|
9ff250502c |
Make exact kernel grids safe by default
Model kernel dispatch geometry as a typed contract shared by lowering, reflection, validation, and the CLI. Cull surplus dispatchThreads invocations using fixed or reflected push-constant grid bounds, make that safe dynamic-grid path the default, and require an explicit whole-workgroup assertion to omit it. Reject unsafe source-barrier kernels before every product emission facade by following the selected AIR entry graph, including quoted LLVM symbols. Exercise the same default contract in authored candidate validation and document the host ABI. Keep corpus audit parent concurrency bounded by feeding isolated translation workers from scratch-backed stdin files instead of creating one feeder thread per row. This removes the scoped-thread exhaustion that aborted late full censuses while retaining child decoding inside the time and memory watchdog. Verified with format checking, warnings-denied workspace clippy and Rustdoc, validation tests at concurrency 16, the unchanged downstream repro, a forced 88,819-row audit completing in one invocation at jobs 16, failure retries, and a zero-read warm pass. |
||
|
|
3ed0c38857 |
Update changelog through descriptor specialization work
Document the AIR layout fixes, descriptor ABI changes, runtime sampler and storage-image specialization, and reflection schema updates added since
|