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
This commit is contained in:
1 parent
d98eae794b
commit
08970cacd2
478 files changed
+70879
-25282
No files matched your search
@@ -78,10 +78,10 @@ jobs:
|
||||
run: cargo doc --workspace --all-features --no-deps
|
||||
|
||||
- name: Test metal2vulkan
|
||||
run: cargo test -p metal2vulkan -- --test-threads=1
|
||||
run: cargo test -p metal2vulkan
|
||||
|
||||
- name: Test validation suite
|
||||
run: cargo test -p metal2vulkan-validation -- --test-threads=1
|
||||
run: cargo test -p metal2vulkan-validation
|
||||
|
||||
# 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
|
||||
|
||||
@@ -38,7 +38,7 @@ This tree is **not** the paravirtual GPU monorepo. Do not reintroduce monorepo p
|
||||
| `validation/` | Authored-case validation tooling (not published to crates.io) |
|
||||
| `docs/` | Architecture and consumer guides |
|
||||
| `scripts/` | Dev utilities (`mtlb-extract`, SPIR-V grammar regeneration) |
|
||||
| `.github/workflows/ci.yml` | Format, warnings-denied clippy/Rustdoc, and serial tests on `ubuntu-26.04` + `macos-26`; public Vulkan qualification on Linux |
|
||||
| `.github/workflows/ci.yml` | Format, warnings-denied clippy/Rustdoc, and parallel tests on `ubuntu-26.04` + `macos-26`; public Vulkan qualification on Linux |
|
||||
|
||||
Crown-jewel code lives under `src/native/`, `src/passes/`, and `src/reflect/`. Prefer structural
|
||||
fixes over one-off workarounds.
|
||||
@@ -135,13 +135,18 @@ fixes over one-off workarounds.
|
||||
and fixed before the affected work is done. A timeout is a safety rail, not an acceptable way
|
||||
to classify supported input. Do not meet the ceiling by skipping required validation, reducing
|
||||
semantic coverage, or converting an input that was supported before into a premature fallback.
|
||||
- **512 MiB is the hard memory budget per translation attempt.** Enforce it at the worker
|
||||
- **500 MiB is the hard memory budget per translation attempt.** Enforce it at the worker
|
||||
boundary, covering peak translation-attributable live allocations and resident growth. Kill
|
||||
the complete worker process group on a time or memory breach and clean up its scratch files.
|
||||
Do not raise either budget without explicit user approval.
|
||||
This explicit 500-MiB ceiling supersedes the former 300/350-MiB escalation contract. Do not raise
|
||||
it again unless a new explicit user instruction supersedes this rule; no automatic increase
|
||||
remains available.
|
||||
- **Keep total resource use bounded.** Parallelize only independent rows or phases, cap worker and
|
||||
queue counts, and account for the aggregate worst case (`workers * 512 MiB`). No optimization
|
||||
queue counts, and account for the aggregate worst case (`workers * 500 MiB`). No optimization
|
||||
may introduce unbounded threads, processes, queues, caches, retained IR, or candidate modules.
|
||||
- **Use host parallelism for corpus runs.** Corpus tooling defaults `jobs` to the host's available
|
||||
logical CPU count (the equivalent of `nproc`). Use that default for full-corpus work; pass an
|
||||
explicit `--jobs N` only when the user requests an override.
|
||||
- **Remove work instead of hiding it.** Prefer shard-local incremental indexing, parsing only the
|
||||
selected or changed source, caching immutable analysis, reusing still-valid CFG facts, skipping
|
||||
equivalent retry states, and releasing failed candidates promptly. Never reuse analysis across
|
||||
@@ -156,7 +161,7 @@ fixes over one-off workarounds.
|
||||
slowest row and the scope measured. Debug-build timing does not verify the ceiling.
|
||||
- When a slow or memory-heavy failure class is found, add a deterministic regression check for
|
||||
the underlying redundant-work or boundedness property. Avoid machine-fragile microbenchmarks;
|
||||
keep the 30-second and 512-MiB worker guards as hard integration backstops.
|
||||
keep the 30-second and 500-MiB worker guards as hard integration backstops.
|
||||
- **Do not normalize known breaches.** An observed over-budget translation is an active correctness
|
||||
bug, not acceptable technical debt or a reason to weaken the workload. Profile where its time
|
||||
and memory go, remove redundant or global work structurally, and remeasure the same input under
|
||||
@@ -196,14 +201,14 @@ shards under `validation/corpus/cases/`, and dependency-exact observation shards
|
||||
|
||||
## Build, test, CI
|
||||
|
||||
Always run Rust tests **serially**:
|
||||
Run Rust tests with Cargo's default available parallelism (the logical CPU count):
|
||||
|
||||
```sh
|
||||
cargo fmt --all
|
||||
cargo clippy --workspace --all-targets -- -D warnings
|
||||
RUSTDOCFLAGS='-D warnings' cargo doc --workspace --all-features --no-deps
|
||||
cargo test -p metal2vulkan -- --test-threads=1
|
||||
cargo test -p metal2vulkan-validation -- --test-threads=1
|
||||
cargo test -p metal2vulkan
|
||||
cargo test -p metal2vulkan-validation
|
||||
```
|
||||
|
||||
- **MSRV:** see `rust-version` in `Cargo.toml` (currently 1.87).
|
||||
@@ -219,6 +224,13 @@ When diagnosing a hang, prefer reading full `cargo test` output over piping thro
|
||||
|
||||
## Code style
|
||||
|
||||
- **No empty-placeholder ownership tricks.** Do not use `std::mem::take`, `mem::replace` with an
|
||||
empty/default sentinel, `swap` with an empty value, or an equivalent helper to move IR, modules,
|
||||
functions, blocks, instructions, or analysis collections out of a borrowed owner. Express the
|
||||
real ownership contract instead: consume and return the owned value, borrow the existing
|
||||
allocation, or redesign the transformation around an explicit result. When touching an existing
|
||||
occurrence, remove it structurally rather than copying the pattern.
|
||||
|
||||
- **Format before every commit.** Run `cargo fmt --all` (repo `rustfmt.toml`) on the whole
|
||||
workspace so the diff you commit already matches what CI’s `fmt --check` expects. If a change
|
||||
is pure formatting, keep it in its own commit when mixed with logic would obscure the review.
|
||||
@@ -250,6 +262,6 @@ When diagnosing a hang, prefer reading full `cargo test` output over piping thro
|
||||
when fmt, clippy, and applicable Rustdoc checks are clean.
|
||||
|
||||
**Done** = it works under the checks above, claims match evidence, fmt/clippy/Rustdoc are green,
|
||||
measured translations in the touched scope stay within 30 seconds and 512 MiB, relevant capability
|
||||
measured translations in the touched scope stay within 30 seconds and 500 MiB, relevant capability
|
||||
audits remain closed without stale evidence or unrelated source reads, and the tree stays
|
||||
publishable as a general AIR→SPIR-V translator.
|
||||
+350
-18
@@ -9,12 +9,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
### Added
|
||||
|
||||
- Bounded translation censuses now consume exact authored visible-function-table populations inside
|
||||
the isolated worker, using hash-local case lookup and the same checked linkage mapping as Vulkan
|
||||
candidate execution; only rows with no authored population remain linkage-required.
|
||||
- Public `specialize_function_constants_zero` helper for baking discovered Metal function
|
||||
constants to their zero/default values, including branch pruning and removal of now-dead entry
|
||||
interface globals.
|
||||
- Public byte-exact function-constant specialization, reflection-only AIR inspection, authored
|
||||
linked-function/table specialization, and vertex-observer generation APIs.
|
||||
- Reflection schema v29: consumer metadata now covers decoded static samplers, texture shape and
|
||||
- AIR-level scalar/vector function-constant translation APIs that specialize stable
|
||||
`air.fc_initializer` globals before metadata, resource-interface, and CFG construction.
|
||||
- Reflection schema v30: consumer metadata now covers decoded static samplers, texture shape and
|
||||
access, argument-buffer resources, kernel stage inputs, tessellation, imageblocks, exact function-
|
||||
constant ABI types, buffer extent/access classification, and conservative final-module static and
|
||||
invocation-strided buffer footprints, plus runtime sampler/storage-image specialization and the
|
||||
@@ -24,15 +29,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
existing layout as the explicit default.
|
||||
- Runtime pipeline-state specialization by Metal resource index for dynamically bound samplers and
|
||||
writable storage images, including embedded argument-buffer textures, exact reflected sampler and
|
||||
image-format state, and host storage-image feature checks.
|
||||
- A typed kernel dispatch-grid ABI that safely defaults every kernel to a per-dispatch push-constant
|
||||
grid, with fixed and explicitly proven whole-workgroup forms reflected for consumers and exposed
|
||||
through matching CLI options.
|
||||
image-format state (including two-channel `Rg32Float`), and host storage-image feature checks.
|
||||
- A typed exact-thread dispatch ABI that decomposes Metal boundary workgroups into at most eight
|
||||
Vulkan regions, with specialized local sizes, logical grid bases, public planning helpers, and
|
||||
fixed, dynamic, and explicitly proven whole-workgroup forms.
|
||||
- A task-oriented translation and reflection integration guide plus a compiled serde reflection
|
||||
example.
|
||||
- Additional stage-interface support for fragment `[[point_coord]]`, `[[primitive_id]]`, and
|
||||
`[[sample_id]]`, flat varyings, framebuffer-fetch color inputs, vertex builtins, and fragment
|
||||
outputs with nonzero render-target locations.
|
||||
- Additional stage-interface support for fragment `[[point_coord]]`, `[[primitive_id]]`,
|
||||
`[[sample_id]]`, and `[[render_target_array_index]]`, flat varyings, framebuffer-fetch color
|
||||
inputs, vertex builtins, and fragment outputs with nonzero render-target locations.
|
||||
- Broader native translation support for texture arrays, storage-image arrays, texture
|
||||
gather/sample/read/write variants, half/integer render-target formats, scalar 64-bit integer
|
||||
arithmetic, and Workgroup memory patterns used by shared-memory reductions.
|
||||
@@ -44,13 +49,98 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
transpose operands and 32-lane tile ownership.
|
||||
- Authored validation contracts and executable Metal/Vulkan cases for tessellation, depth/stencil
|
||||
attachments, framebuffer fetch, multisample and buffer textures, narrow vertex attributes,
|
||||
vertex side effects, function constants, argument buffers, imageblocks, and ray intersections.
|
||||
vertex side effects, function constants, argument buffers, imageblocks, ray intersections, and
|
||||
exact empty observations for entries with no reflected writable output, including rejection of
|
||||
vertex positions and varyings as observable outputs.
|
||||
- Byte-exact Metal/MoltenVK evidence now covers every public synthetic AIR fixture, including vector
|
||||
function-constant lanes, barrier-bearing boundary workgroups, narrow vertex attributes, combined
|
||||
depth/stencil, and custom and implicit imageblocks, plus indexed local identities for
|
||||
unconditional word stores, signed min/max initialization, grid-indexed byte clears, and exact
|
||||
grid-index sequence generation, parameter-free scalar and vector fragment returns (including a
|
||||
sparse color-location-2 target and scalar half targets), and constant-zero vertex positions
|
||||
observed through their exact non-rasterizing framebuffer result, plus two-channel float fragment
|
||||
targets, fragment position-depth extraction, and a pixel-coordinate sampled vertical convolution
|
||||
with explicit sampler state, weights, bounds, and bias. Constant scalar/vector fragment evidence
|
||||
now also covers half, float, and uint targets, while dual-output fragment clears qualify both
|
||||
attachments independently for half4 and float4 formats. Authored Vulkan draws now mirror Metal's
|
||||
default clockwise front-face winding, with byte-exact coverage for `[[front_facing]]`, primitive
|
||||
IDs, generated float/half fragment varyings across additional independently indexed AIR
|
||||
identities, scalar float-to-half varying conversion, and constant outputs whose unused stage
|
||||
inputs include viewport indices. Additional authored vertex evidence observes generated
|
||||
ushort-ID positions and independently captures passthrough position and float2 varying outputs;
|
||||
fragment evidence also covers flat uint varyings, scalar depth expansion, and independently
|
||||
selected sparse color attachments. Exact vertex observation now additionally covers forced-zero
|
||||
clip-space depth, paired position/float2 passthrough outputs, and deterministic position results
|
||||
beside explicitly undefined return members; fragment coverage includes alpha-to-half4 conversion,
|
||||
aggregate flat-uint returns, and viewport-bearing varying passthrough.
|
||||
The indexed evidence set additionally covers float2/float3 clip-position expansion, paired
|
||||
float2 vertex varyings, scalar and vector float-to-half fragment conversion, flat-boolean color
|
||||
selection, fog-alpha multiplication, empty texture kernels that preserve their selected bytes,
|
||||
and a rasterization-disabled vertex side-effect store.
|
||||
A complete indexed texture-copy family now has byte-exact coverage for flat and array-layer
|
||||
half-texture reads, including explicit function-constant specialization of the flat alternative.
|
||||
The complete indexed `backgroundFragment` family now has fresh byte-exact Metal/MoltenVK evidence
|
||||
for constant and sampled outputs, including two function-constant-selected gradient textures.
|
||||
The complete eight-identity `Clear::clear_fragment{,2,3,4}` suite now has byte-exact evidence for
|
||||
constant-buffer float-to-half conversion and aggregate output mapping through four render targets.
|
||||
Attachmentless fragment draws now execute on Metal with explicit render-pass dimensions, without
|
||||
synthesizing an observable attachment. The two-identity `Clear::clear_depth_stencil_fragment`
|
||||
family has exact empty-output Metal/MoltenVK evidence for its structural void-return contract.
|
||||
The complete four-identity `Clear::clear_vertex{,_mrt}` family has exact Metal/MoltenVK position
|
||||
observations for float2 vertex attributes expanded with buffer-supplied clip-space depth.
|
||||
The complete six-identity `FullscreenFragment{DepthStencil,Overlay,Texture}` suite has exact
|
||||
Metal/MoltenVK evidence for static-sampler half-texture reads, including red-lane replication,
|
||||
uniform-color multiplication, and RGB widening to RGBA32Float outputs.
|
||||
The complete six-identity `ARMesh::{mesh_depth_fragment,ar_mesh_shadow_fragment,ar_mesh_fragment}`
|
||||
suite has exact Metal/MoltenVK evidence for literal depth, edge-weighted shadow colors, and the
|
||||
full 2D/cube sampled-texture lighting path.
|
||||
A complete indexed tracking-area family now covers layered textures, fixed texture arrays, and
|
||||
function-constant-selected alternatives through eight-SIMD-group shared-memory reductions with
|
||||
barrier-synchronized exact uint output. Complete indexed vertex families now also cover
|
||||
vertex-ID-generated fullscreen positions across plain, viewport-indexed,
|
||||
render-target-layer-indexed, and single-view amplification interfaces.
|
||||
- A sharded validation workflow with dependency-exact observations, an incremental SQLite source
|
||||
index, focused hash/shard selection, explicit full reclassification, capability audits, native
|
||||
Metal and Vulkan/MoltenVK A/B execution, and optional OpenRouter-authored case proposals.
|
||||
|
||||
### Changed
|
||||
|
||||
- Vulkan 1.2 is now the mandatory translation and validation baseline; newer Vulkan features may
|
||||
only be exposed as optional performance paths with faithful Vulkan 1.2 fallbacks.
|
||||
- Structured CFG plans now finalize loop-continue selection ownership before their completeness,
|
||||
ordering, and ownership checks; typed emission no longer runs detached continue, selection-arm,
|
||||
bypass, or reused-merge normalization after plan admission.
|
||||
- Nested loop planning now materializes inner multi-exit dispatches before recomputing enclosing
|
||||
loop ownership, so newly synthesized exits are validly owned without a construct-tree retry.
|
||||
- A nested natural loop that exits into its enclosing selection's sibling is now owned by a typed
|
||||
regional dispatcher before emission. Bounded scalar-only CFG rejects can use the same ownership
|
||||
contract across the whole function, while pointer state still declines rather than being guessed;
|
||||
terminal switches retain real dominated reconvergences and conflicting phi ownership rejects
|
||||
before instruction emission.
|
||||
- Loop-local switches that target an enclosing loop role now lower to branch ladders before plan
|
||||
admission, preventing source-dominance false positives from emitting invalid case constructs.
|
||||
- Imageblock scratch layout inference now follows reachable internal calls, preserving complete
|
||||
cells when a helper byte-addresses a nonzero field instead of relying on an inlining retry.
|
||||
- Integer-width phi legalization now happens while pointer-phi transformations construct their
|
||||
replacement index phis; retained modules are no longer rescanned or repaired after emission or
|
||||
scalar-i64 lowering.
|
||||
- Vulkan validation uploads every sampled-only literal through a staging buffer into an
|
||||
optimal-tiled image, so cube and other sampled shapes do not depend on optional linear-image
|
||||
support for their exact create flags.
|
||||
- Authored output qualification now requires the shared checker to map the selection to a reflected
|
||||
shader write, then accepts deterministic byte-identical transformations instead of requiring
|
||||
every byte to differ from its initial value.
|
||||
- The Metal validation executor now derives render-pipeline input topology from each authored draw
|
||||
and constructs matching array attachments and active-layer render passes for layered rendering.
|
||||
- Generated Vulkan fragment companions preserve their authored layer-zero contract through the
|
||||
core first-layer rule, without requiring the optional Vulkan 1.2 `shaderOutputLayer` feature.
|
||||
- Authored Vulkan execution now applies function constants before AIR translation, so nondefault
|
||||
values faithfully retain selected resources and CFG arms instead of trying to restore structure
|
||||
after default-valued SPIR-V emission.
|
||||
- Exact Metal `dispatchThreads` kernels no longer round up and cull surplus lanes. The default
|
||||
contract now preserves partial-workgroup barriers by dispatching true boundary workgroup sizes;
|
||||
consumers must follow the reflected region plan and 48-byte dispatch payload.
|
||||
|
||||
- Native emitter wrapper APIs under `tools` now use `emit_vulkan_spirv*` names that match their
|
||||
implementation.
|
||||
- The CLI accepts `--raster-samples` for AIR sample-count queries and derives a default `.vk.spv`
|
||||
@@ -60,17 +150,193 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
- Buffer, pointer, control-flow, and access-chain lowering handles more structural cases, reducing
|
||||
fallbacks and invalid SPIR-V for shaders that use dynamic indices, pointer selects, aggregate
|
||||
copies, raw subword loads/stores, and local pointer tables.
|
||||
- Opaque Metal buffers used through multiple scalar element types now retain each typed view as a
|
||||
descriptor alias at the same binding, while genuine array element-zero accesses gain their block
|
||||
descent and vector-stride pointers retain their vector pointee during interface construction;
|
||||
these preserve exact byte strides without late load/store pointer repairs.
|
||||
- Exact byte-address provenance now composes through resource-wrapper collapse to the final buffer
|
||||
descriptor, so raw 32-bit vector loads are constructed from their word lanes before validation.
|
||||
- Exact raw-word replay now derives synthesized access-chain pointer types from the concrete root's
|
||||
storage class, eliminating detached final access-chain storage-class repairs.
|
||||
- Finalized typed CFG construction now recognizes a phi as an SSA identity only when its block has
|
||||
one actual predecessor and every incoming pair names that predecessor with the same structural
|
||||
value. All identities, including pointers, are substituted before SPIR-V IDs and representation
|
||||
sidecars are constructed. This eliminates the detached phi collapse and its access-chain and
|
||||
sampled-image type repairs.
|
||||
- Buffer-interface discovery now follows transparent pointer aliases, includes pointer-arithmetic
|
||||
chains as typed element views, and gives mixed numeric scalar/vector views descriptor aliases at
|
||||
the same binding. Each logical pointer is therefore valid by construction instead of being
|
||||
retyped away from its byte loads during interface specialization.
|
||||
- Null-derived access chains are neutralized once in the main access transform; redundant
|
||||
whole-module cleanup passes after native pointer rewrites have been removed.
|
||||
- Exact raw-byte access is replayed at the descriptor-reconstruction boundary, eliminating the
|
||||
detached post-native replay and releasing source-only layout type graphs before final cleanup.
|
||||
- Nondominating-value demotion now explicitly preserves the CFG successor contract, eliminating
|
||||
redundant whole-CFG repair passes after register spills.
|
||||
- Pointer-phi legalization and mixed-storage value lowering now explicitly preserve CFG successors,
|
||||
so late structured-CFG repair runs only for an actual edge-producing loop split.
|
||||
- Multi-entry loop splitting now owns its cloned region, header phis, redirected entry, and selection
|
||||
exit as one transaction, eliminating its detached whole-CFG repair pass.
|
||||
- Multi-exit funnels, deep shared-arm refunnelling, and multi-entry loop splitting now preserve SSA
|
||||
dominance at their typed construction boundaries, eliminating the final emitted-module
|
||||
nondominating-value demotion pass.
|
||||
- Construct-tree planning now assigns unreachable merge declarations for fully terminal selections
|
||||
alongside every other header, eliminating the late missing-terminal-header completion sweep.
|
||||
- Dominated-region cloning now carries nested selection ownership through its structural rename map,
|
||||
so enclosing-route selections are materialized locally instead of dropped and rediscovered by a
|
||||
final missing-selection sweep.
|
||||
- Construct-tree selection construction now preserves the local live-arm ownership of direct
|
||||
terminal guards through generic merge normalization, eliminating its repeated enclosing-escape
|
||||
and terminal-live repair sweeps.
|
||||
- Ordinary selection construction now derives nested exits from the complete immutable source
|
||||
ownership map and materializes their private enclosing boundaries innermost-first, eliminating
|
||||
the late enclosing-region escape repair fixed point.
|
||||
- Construct-tree selection construction now retains complete merge ownership through enclosing
|
||||
synthesis, eliminating its three post-construction nondominance, pass-through promotion, and
|
||||
bypass-refunneling repair stages from the product path.
|
||||
- Construct-tree source ownership now includes nested terminal selections in its initial
|
||||
innermost-first header census, eliminating late post-synthesis terminal-convergence completion.
|
||||
- Direct terminal ownership now consumes the complete proved linear tail before selection analysis,
|
||||
eliminating post-construction direct-guard refunneling from the product path.
|
||||
- Selection construction now privatizes shared terminal returns when each merge owner is created,
|
||||
eliminating the later whole-owner terminal-return fixed-point sweeps.
|
||||
- Innermost-first terminal-tail ownership now closes enclosing parents directly, removing the late
|
||||
parent/nested merge-composition pass from production.
|
||||
- Switch merge construction now collapses proved terminal case tails when each switch owner is
|
||||
recorded, removing the late all-switch terminal finalization sweep from production.
|
||||
- Loop-free terminal guards whose live convergence enters a later loop now defer a return shared
|
||||
with that loop's exit to the terminal owner, which privatizes both boundaries instead of admitting
|
||||
overlapping merge ownership.
|
||||
- Loop-exit switch lowering now includes loop headers and multi-exit loops, producing a conditional
|
||||
ladder before planning so one block never needs both loop and selection merge ownership.
|
||||
- Switch construction now privatizes intermediate continuations shared by a subset of cases even
|
||||
when the eventual switch merge is dominated, including loop-local suffixes whose clone does not
|
||||
cross a loop header, latch, exit, or nested-loop boundary.
|
||||
- Construct-tree ownership now runs by default after an ordinary source-CFG planning rejection,
|
||||
while forward SSA allocation is scoped only to functions using that reordered plan. This removes
|
||||
a redundant emit, finish, validation, and source reparse from structurally owned large functions.
|
||||
- Switch-tail ownership now preserves SPIR-V's legal fallthrough into the immediately following case,
|
||||
and shared-region cloning declines edges whose redirected predecessor crosses a natural-loop
|
||||
boundary, preventing non-adjacent case entries and non-dominating loop-exit values by construction.
|
||||
- Enclosing selection owners now finish only their indexed dependent routes when the owner is
|
||||
recorded, removing the late whole-CFG enclosing-route materialization fixed point.
|
||||
- Indexed translations retain natural emitted-loop ownership through the typed edge-producing
|
||||
transforms, allowing the detached stale-loop reclassification adapter to leave production.
|
||||
- Translation audits now finish the 16-worker ordinary lane before starting the bounded costly-row
|
||||
lane, including sub-megabyte CFGs whose serialized AIR reaches 256 KiB. The costly lane is capped
|
||||
at two workers, with ≤384-KiB, 370-block/400-call CFGs isolated on one sublane while unrelated
|
||||
large and device-address/function-table rows continue on the other, so sustained concurrency does
|
||||
not consume the per-attempt 20-second budget. Cached outcomes now fingerprint the audit harness
|
||||
as well as the product translator.
|
||||
- Translation audits can now resume a per-fingerprint retry-tier census in the disposable SQLite
|
||||
index, measure exact hash-file selections, and report the complete adoption histogram without
|
||||
reopening warm source shards.
|
||||
- Resumable translation selection now materializes the historical-failure priority set once per
|
||||
uncursored batch instead of probing the complete audit history once for every indexed source.
|
||||
- Function-constant-wrapped visible and intersection tables now retain their shared authored-linkage
|
||||
roles, and validation traces visible-table handles through internal helper parameters. A full
|
||||
`--reclassify-all` authoring census now reads every indexed source under the current analyzer ABI;
|
||||
the ordinary warm pass remains a zero-source-read incremental check. Translation workers classify
|
||||
these structurally proven authored-linkage dependencies before spawning the product/tool cascade.
|
||||
- Direct AIR visible-function references now resolve automatically through an incremental
|
||||
same-library symbol index when the retained definition is unique, including transitive linked
|
||||
references; exact module byte locations keep warm and targeted lookups shard-local, while missing
|
||||
or ambiguous definitions remain explicit authored inputs. Translation audits can resumably replay
|
||||
historical linkage rows with `--retry-linkage`.
|
||||
- Authored visible and intersection table slots now accept exact functions from separately
|
||||
harvested Metal libraries, matching the linked-functions API instead of imposing a false
|
||||
same-metallib provenance rule; exact module hashes, symbol definitions, and globally unique linked
|
||||
names remain mandatory.
|
||||
- Partial zero-initialization of typed aggregates now lowers recursively into null stores for fully
|
||||
covered prefix subobjects, and final SPIR-V construction dependency-orders late synthesized
|
||||
module-scope types before existing users. Linked declaration/body pairs also select the bodied
|
||||
definition consistently during emitted-helper inlining, removing the associated empty-callee
|
||||
panic.
|
||||
- Same-width scalar-array/vector reinterpret loads now rebuild the vector lane-by-lane with scalar
|
||||
bitcasts, preserving logical pointer types instead of requiring the all-buffer raw retry.
|
||||
- Function-constant buffer alternatives that share one binding and mix scalar families through a
|
||||
recurrent pointer carrier now choose byte-addressed storage plus typed construct-tree planning
|
||||
during primary construction, instead of relying on the all-buffer raw and relooper retry cascade.
|
||||
- Function-constant pruning now owns branch folding, reachability, phi, and loop-merge closure, which
|
||||
removes the final finish-time whole-module structured-CFG repair adapter.
|
||||
- Primary construction now checks owned selection entry/exit, loop back-edge declarations,
|
||||
conditional merge declarations, and dominator serialization after function-constant CFG pruning,
|
||||
choosing bounded relooper form for only the affected functions before the first assembly while
|
||||
preserving unrelated functions and the hard downstream-driver state-machine cap. Relooper switch
|
||||
lowering now preserves both 32-bit and 64-bit selector literals.
|
||||
- Function-constant pruning and entry-interface rebuilding now also own specialized Workgroup
|
||||
aggregate-stride access lowering instead of invoking a detached pointer repair afterward.
|
||||
- The inline, SROA, and raw-access retry lowers dynamic typed accesses before constructing its
|
||||
relooper module, eliminating its post-relooper access-chain repair adapter.
|
||||
- Helper inlining now completes address-preserving zero-offset aggregate descent once at its
|
||||
self-contained entry-closure boundary, eliminating the emitter's detached whole-module repair scan.
|
||||
- Resource-select lowering assigns each duplicated `OpSampledImage` its branch image's exact type at
|
||||
construction, eliminating its final whole-module sampled-image type repair scan.
|
||||
- Pointer-phi lowering now assigns synthesized incoming values directly to their predecessor edges,
|
||||
eliminating the final post-emission access-chain relocation and phi-order repair scan.
|
||||
- Finalized typed CFG construction now redirects external entries around loop continue constructs,
|
||||
moves their exact phi values onto loop-header edges, and restores dominator serialization before
|
||||
emission, eliminating the corresponding numeric SPIR-V repair fixpoint.
|
||||
- Emitted loop, selection, and switch merges that are reachable from outside their owning construct
|
||||
now get phi-aware private boundaries in the finalized typed CFG, eliminating the matching
|
||||
post-emission dominance repair.
|
||||
- Instruction-local control flow is now materialized as real blocks inside the native emitter; when
|
||||
it splits a loop header, a dedicated source header retains the loop phis and ownership while any
|
||||
nested selection receives a private merge, eliminating the post-emission stale-loop downgrade.
|
||||
- Finalized typed CFG construction now owns every loop header required by indexed inputs, eliminating
|
||||
both post-emission unmarked-loop synthesis and product-wide dominator-order normalization;
|
||||
structural loop tests define membership by dominated CFG predecessor edges rather than
|
||||
serialization order. Instruction-local control flow now carries each source block's real emitted
|
||||
exit into successor phis, eliminating final numeric-SPIR-V phi reconciliation and the product CFG
|
||||
repair module altogether.
|
||||
- Selection boundaries that collide with a loop continue are now resolved in the finalized typed
|
||||
CFG, including enclosing selections, direct break/continue branches, and phi-carrying in-loop
|
||||
reconvergence; inner construct merges are likewise privatized in the typed plan, and emitted
|
||||
helper inlining now preserves the enclosing continue while giving its nested selection a private
|
||||
pass-through, eliminating both matching post-emission repairs.
|
||||
- Structured emission now retains merge markers immediately before their terminators throughout
|
||||
lowering, eliminating the permissive pass that reordered already-malformed merge blocks.
|
||||
- Direct-arm cloning and external loop-entry rewrites now preserve their newly established
|
||||
dominator order at the owning structural boundary.
|
||||
- Loop plans now resolve emission-empty continue pass-through chains from the finalized typed CFG
|
||||
before emitting `OpLoopMerge`, eliminating the corresponding post-emission label repair.
|
||||
- Finalized emission plans now give nested constructs phi-aware private merge targets while
|
||||
preserving loop-header backedges, eliminating the retained-SPIR-V shared-merge ownership pass.
|
||||
- Finalized typed CFG emission now funnels selection/switch bypass edges through their declared
|
||||
phi-aware pass-through merges, eliminating that retained-SPIR-V product repair.
|
||||
- Finalized typed CFG emission now clones shared direct arms only for headers with declared merges,
|
||||
then routes each clone through the merge with exact phi synthesis, eliminating the numeric-label
|
||||
shared-arm product repair.
|
||||
- AIR `target datalayout` vector alignment and exact `air.struct_type_info` member offsets now flow
|
||||
through the primary emitter, aggregate byte walkers, reflection, and every retry tier instead of
|
||||
being reconstructed from generic SPIR-V layout assumptions.
|
||||
- The default descriptor ABI now uses checked, non-overlapping bands for buffers, sampled textures,
|
||||
samplers, color inputs, imageblocks, storage textures, and translator-owned resources. Final
|
||||
modules reject descriptors outside their selected class range or set.
|
||||
- Structured control-flow retries are bounded more tightly, improving behavior on large shaders and
|
||||
avoiding unnecessary fallback to slower emission paths.
|
||||
- Corpus translation and classification use bounded parallel workers, a 30-second per-item
|
||||
watchdog, a 512 MiB per-item memory ceiling, size-aware scheduling, and incremental index/cache
|
||||
reuse. Warm audits avoid reopening unchanged source shards; forced audits remain explicit.
|
||||
- Structured control-flow retries are bounded more tightly and reuse exact ordinary-planner
|
||||
rejection facts across the primary and construct-tree attempts, improving behavior on large
|
||||
shaders without reusing an accepting plan across retry semantics.
|
||||
- Corpus translation and classification use bounded parallel workers, a 20-second per-item
|
||||
watchdog, a 500 MiB per-item memory ceiling, source-size and structural-cost-aware scheduling, and
|
||||
incremental index/cache reuse. Watchdog cleanup polls its own child instead of installing a
|
||||
process-global signal handler, and worker panics remain hash-attributed retryable failures instead
|
||||
of aborting a resumable census. Warm audits avoid reopening unchanged source shards; forced audits
|
||||
remain explicit.
|
||||
- Large-module translation now streams function bodies into typed blocks, borrows unchanged
|
||||
normalization input, shares immutable block carriers, interns repeated instruction opcodes, and
|
||||
keeps mutually exclusive instruction and phi facts in one canonical representation. Resolved
|
||||
instructions derive def/use edges from those operands instead of allocating parallel name lists, and
|
||||
the emitter no longer clones every typed operand into a result-keyed table. Async-copy lowering
|
||||
streams into one bounded-growth buffer, skips dead declarations, and lets owned callers release
|
||||
superseded source text before typed parsing. Together these changes substantially reduce the
|
||||
measured largest local rows without changing their translated classification or skipping SPIR-V
|
||||
validation.
|
||||
- Function-variable hoisting and integer-width normalization now preserve each block's instruction
|
||||
allocation, moving only matched variables and snapshotting only the instruction being rewritten.
|
||||
This removes full-block clones from universal large-module paths while preserving emitted order.
|
||||
- Integer conversions now select their opcode from the actual emitted SPIR-V storage types. Legalized
|
||||
widths such as LLVM `i24` are masked at their producer, signed extensions restore the logical sign
|
||||
bit, and equal-width signed vertex inputs use bitcasts, eliminating the late width-convert repair.
|
||||
- Validation capability checks, authored schema validation, backend execution gates, and cache
|
||||
identities now share one typed contract so a clean audit cannot hide a later executor rejection.
|
||||
- Corpus capability audits now use the product's canonical AIR-call inventory and report every
|
||||
@@ -79,7 +345,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
- Full AIR-intrinsic reclassification now updates every cached source in bounded keyset batches,
|
||||
independent of `--limit`, without reopening source shards; matrix capability recognition and
|
||||
lowering share one exact ABI parser.
|
||||
- Reflection documentation now describes the complete schema v29 descriptor, argument-buffer,
|
||||
- Translation census results now flow through a worker-count-bounded queue. A checkpoint failure
|
||||
cancels unclaimed rows and drains only in-flight results instead of allowing workers to retain an
|
||||
unbounded completed-row backlog while the scoped parent unwinds.
|
||||
- Reflection documentation now describes the complete schema v30 descriptor, argument-buffer,
|
||||
runtime specialization, stage-interface, and conservative buffer-staging contracts.
|
||||
|
||||
### Removed
|
||||
@@ -89,9 +358,52 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
commands.
|
||||
- Removed obsolete emitter naming and compatibility terminology; the product and tooling describe
|
||||
only the native AIR-to-SPIR-V pipeline.
|
||||
- Removed the universal post-validation StorageBuffer/Workgroup pointer-phi rewrite, successful-
|
||||
module constant-branch reparse, and scalar-i64 module wrapper; same-root pointer merges and literal
|
||||
dead arms are now resolved on the typed source graph before emission.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Opaque buffer sources copied into local aggregates are now inferred as byte-addressed even when
|
||||
the destination is not another buffer parameter. AIR aggregate metadata whose explicit member
|
||||
offsets overlap Vulkan's naturally aligned block extents also selects the faithful byte view.
|
||||
- Large CFGs now attempt their structurally valid primary emission before any retry. Missing switch
|
||||
merges and phi/predecessor mismatches route by their typed CFG failure class to the whole-CFG
|
||||
constructor, replacing the former block-count-triggered raw/relooper and construct-tree pre-route.
|
||||
- Runtime device pointers now select the Vulkan 1.2 buffer-device-address model from typed AIR
|
||||
producer/use structure during primary emission. Opaque resource handles remain in the logical
|
||||
resource domain, and the redundant validation-triggered plain-BDA retries have been removed.
|
||||
- Packed 32-bit reads through Private vector-backed helper views are now completed inside the
|
||||
memory-lowering transaction, so finalization no longer needs a repeated post-pass legalization.
|
||||
- Interface binding now materializes direct loads selected between descriptor-backed and Private
|
||||
placeholder arms in the value domain, eliminating the corresponding module-wide finalizer repair.
|
||||
- Descriptor-backed pointer-select closures, including dynamically indexed local pointer tables,
|
||||
are now constructed in the Logical value domain on the primary path instead of relying on
|
||||
validation-triggered value-select or physical-address repairs.
|
||||
- Same-root pointer phis and selects now merge their integer access-chain indices and rematerialize
|
||||
one pointer for every storage class. Typed forward-select facts cover loop backedges whose
|
||||
advancing arm is a later chain of GEPs, so these recurrences need neither pointer SSA nor
|
||||
`VariablePointersStorageBuffer`.
|
||||
- Scalar and vector function-constant initializer expressions are folded on the owned typed CFG
|
||||
before merge planning. Literal edges are pruned independently, surviving phi predecessor sets are
|
||||
rebuilt, and single-predecessor phis are substituted without letting an unrelated opaque aggregate
|
||||
phi suppress safe pruning. AGX execution-mask lowering now keeps loop ownership on the original
|
||||
backedge target and gives the lowered exit test a private structured merge.
|
||||
- Function-constant-gated texture inputs with real Metal locations now retain their own descriptor
|
||||
and exact image shape even when their predicate defaults false, so later SPIR-V specialization
|
||||
cannot sample or write an unrelated texture. Only the `-1` location sentinel remains absent.
|
||||
Arrayed texture writes take their operand shape from the stable AIR intrinsic symbol even after
|
||||
the image handle passes through a local carrier.
|
||||
- Scalar StorageBuffer remodeling now replays exact source GEP byte offsets as one stride-checked
|
||||
runtime-array index, preserving aggregate row/lane addresses after metadata collapses the
|
||||
descriptor element type.
|
||||
- Unsupported image-texel value shapes now bypass buffer/CFG retry tiers that preserve the rejected
|
||||
SSA value, returning an honest fallback within the translation budget instead of repeatedly
|
||||
emitting the same large module.
|
||||
- Added structural lowering for one-dimensional linear pixel sampling, logical pointer aliases,
|
||||
little-endian byte-aggregate/integer reinterpretation, and the packed signed-i8 AGX3 16x16x16
|
||||
matrix-MAC ABI. The matrix adapter validates its complete fixed descriptor contract and reuses
|
||||
the common distributed 32-lane matrix implementation.
|
||||
- Unsupported Metal visible function references now fail fast with an explicit fallback instead of
|
||||
being treated as ordinary functions.
|
||||
- Multiple `OpReturnValue` sites are rewritten consistently to stage outputs, and undefined
|
||||
@@ -118,6 +430,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
phis use ordinary access chains instead of invalid `OpPtrAccessChain` pointer-stride forms.
|
||||
- Fixed function-constant-gated fragment outputs so the default-zero AIR predicate model does not
|
||||
advertise mutually exclusive render-target formats at the same Vulkan location.
|
||||
- Fixed static-initializer evaluation so a specialized integer vector is retained as a typed vector
|
||||
and only a genuinely scalar value can enter the scalar global-fold map.
|
||||
- Fixed fragment `[[sample_id]]` lowering to use `BuiltIn SampleId` with the required
|
||||
`SampleRateShading` capability, and lowered AIR `texture2d_ms` reads to MS `OpTypeImage` fetches
|
||||
with a `Sample` operand instead of treating the sample id as a mip LOD.
|
||||
@@ -140,9 +454,27 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
capability checks in executable and metadata-only reflection paths.
|
||||
- Vulkan validation now binds every compatible reflected sampled/storage texture alias to the same
|
||||
allocation and validates texture-array and argument-buffer alternatives as complete sets.
|
||||
- Exact Metal `dispatchThreads` grids now use one typed fixed or per-dispatch push-constant source
|
||||
for both `[[threads_per_grid]]` and a structured surplus-invocation cull. Partial grids with source
|
||||
control barriers fail honestly instead of emitting an unsafe divergent return.
|
||||
- Exact Metal `dispatchThreads` grids share one typed region payload across every logical grid
|
||||
builtin, including synthesized stage-input indexing and reflected buffer footprints.
|
||||
- Module, function, block, instruction, and analysis transformations now express ownership by
|
||||
consuming values, returning replacements, mutating existing allocations transactionally, or
|
||||
appending directly. Fallible late SPIR-V repairs return their module explicitly, so no path can
|
||||
leave caller-visible state replaced by an empty/default ownership placeholder. ID-deleting native
|
||||
rewrite adapters now remove debug and annotation records only for the exact result IDs deleted by
|
||||
their own transaction, eliminating detached product cleanup sweeps without masking unrelated
|
||||
invalid metadata.
|
||||
- Removed the late module-wide integer arithmetic width repair; packed scalar-slot addressing now
|
||||
scales dynamic indices in their declared integer type, so 64-bit access-chain indices remain
|
||||
valid and value-preserving without after-the-fact truncation.
|
||||
- Deep shared-arm refunneling now gives every synthesized value phi an explicit incoming on every
|
||||
join predecessor, using an unobservable `undef` only on edges whose route branches to the other
|
||||
target.
|
||||
Value-domain pointer lowering likewise proves post-merge indices and its complete planned value-phi
|
||||
graph satisfy every predecessor dominance edge before commit. These construction contracts remove
|
||||
the duplicate post-primary non-dominating-value demotion scan.
|
||||
- Cross-binding pointer-phi lowering now runs before the whole-function relooper size gate. The
|
||||
bounded in-memory address rewrite does not depend on CFG re-emission and remains available to large
|
||||
functions whose refunnelled value flow produces a complete cross-binding phi.
|
||||
- Reduced worst-case translation time and memory growth by caching retry verdicts, pruning dead CFG
|
||||
before source re-emission, using linear CFG ordering and candidate scans, bounding generated CFG
|
||||
growth, and applying resource limits from worker startup.
|
||||
|
||||
+5
-5
@@ -47,17 +47,17 @@ cargo clippy --workspace --all-targets -- -D warnings
|
||||
# public Rustdoc, including feature-gated APIs (CI denies warnings)
|
||||
RUSTDOCFLAGS='-D warnings' cargo doc --workspace --all-features --no-deps
|
||||
|
||||
# unit + integration tests (serial)
|
||||
cargo test -p metal2vulkan -- --test-threads=1
|
||||
# unit + integration tests (Cargo defaults to the available logical CPU count)
|
||||
cargo test -p metal2vulkan
|
||||
|
||||
# optional validation package
|
||||
cargo test -p metal2vulkan-validation -- --test-threads=1
|
||||
cargo test -p metal2vulkan-validation
|
||||
```
|
||||
|
||||
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 -- --test-threads=1
|
||||
PATH=/opt/homebrew/opt/llvm/bin:$PATH cargo test -p metal2vulkan
|
||||
```
|
||||
|
||||
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 -- --test-threads=1
|
||||
cargo test -p metal2vulkan
|
||||
|
||||
# before/after a byte-stable refactor
|
||||
cp target/release/metal2vulkan ./m2v-old
|
||||
|
||||
@@ -6,15 +6,15 @@
|
||||
> series. The project is suitable for experimentation and integration pilots, but consumers should
|
||||
> version their cached outputs and expect upgrades to require integration work.
|
||||
|
||||
`metal2vulkan` translates **Metal AIR**—LLVM bitcode or sanitized LLVM IR—into Vulkan 1.3 SPIR-V
|
||||
`metal2vulkan` translates **Metal AIR**—LLVM bitcode or sanitized LLVM IR—into Vulkan 1.2 SPIR-V
|
||||
with a native Rust emitter and retained-SPIR-V passes.
|
||||
|
||||
## What it provides
|
||||
|
||||
- Vertex, post-tessellation vertex, fragment, compute-kernel, and generated passthrough interfaces
|
||||
- A Rust library and an `in → out.spv` command-line interface
|
||||
- Validation-gated retry tiers: unsupported inputs fail visibly instead of returning known-invalid
|
||||
SPIR-V
|
||||
- Structurally selected construction with one final validation pass; unsupported inputs fail
|
||||
visibly instead of returning known-invalid SPIR-V
|
||||
- Consumer reflection for descriptors, stage interfaces, function constants, argument buffers, and
|
||||
conservative buffer byte footprints
|
||||
- An optional unpublished validation workspace for authored semantic cases, GPU evidence, and exact
|
||||
@@ -80,10 +80,11 @@ Accepted values are `1`, `2`, `4`, `8`, `16`, `32`, and `64`. Library callers se
|
||||
`TransformOptions::raster_sample_count`; translation fails visibly when the query is present and
|
||||
the value is unknown.
|
||||
|
||||
Vulkan dispatches whole workgroups, so every kernel uses a per-dispatch exact thread-grid contract
|
||||
by default. Before each dispatch, write three tightly packed `u32` dimensions at push-constant
|
||||
offset 0: the requested thread count for Metal `dispatchThreads`, or `groupCount * localSize` for
|
||||
Metal `dispatchThreadgroups`. The shader culls rounded-up invocations outside that grid.
|
||||
Metal `dispatchThreads` can make boundary workgroups smaller. Exact-thread kernels therefore expose
|
||||
specializable local sizes and a reflected `KernelDispatch::plan`: create a compute pipeline for
|
||||
each distinct region `local_size`, specializing `KERNEL_LOCAL_SIZE_SPEC_IDS`, then dispatch every
|
||||
region with its 48-byte logical-grid payload. This produces at most eight rectangular dispatches,
|
||||
with no surplus invocations and uniform workgroup barriers.
|
||||
|
||||
For a fixed grid, the CLI can instead bake the exact bounds into a pipeline variant:
|
||||
|
||||
@@ -91,12 +92,11 @@ For a fixed grid, the CLI can instead bake the exact bounds into a pipeline vari
|
||||
metal2vulkan kernel.air kernel.spv --local 8,8,1 --threads-per-grid 57,9,1
|
||||
```
|
||||
|
||||
`--threads-per-grid-push-constant OFFSET` moves the default dynamic grid to another byte offset.
|
||||
`--threads-per-grid-push-constant OFFSET` moves the default dynamic dispatch payload.
|
||||
Library callers select an override with `TransformOptions::kernel_dispatch`; reflected translation
|
||||
returns the effective contract in `ShaderReflection::kernel_dispatch`. Callers that can prove every
|
||||
launch covers complete workgroups may explicitly select `KernelDispatch::Workgroups` or pass
|
||||
`--whole-workgroups` to omit the guard. Kernels with source workgroup barriers require that explicit
|
||||
proof until partial-workgroup barrier execution can be modeled without divergent early returns.
|
||||
`--whole-workgroups` to retain a single fixed-local-size dispatch.
|
||||
|
||||
## Library
|
||||
|
||||
|
||||
+148
-175
@@ -1,213 +1,186 @@
|
||||
# metal2vulkan architecture
|
||||
|
||||
A map of the AIR→SPIR-V translator: the primary pipeline, the failure-triggered retry cascade, and
|
||||
how the pieces fit together. This document describes **structure**. Regression coverage for this
|
||||
public tree is the unit/integration suite plus optional local A/B and oracle tooling.
|
||||
This document maps the AIR→SPIR-V product pipeline. The central construction contract is simple:
|
||||
representation selection happens from AIR and owned-module facts, then one serialized module is
|
||||
validated. Validator output is a verdict, never a code-generation input.
|
||||
|
||||
## The pipeline
|
||||
## Pipeline
|
||||
|
||||
The crate emits `OpCapability Shader` / `Logical GLSL450` SPIR-V directly from sanitized AIR LLVM
|
||||
IR, structured by construction where the CFG admits it.
|
||||
|
||||
```
|
||||
.air|.ll
|
||||
└─ tools::air_to_sanitized_ll llvm-dis (if .air) + sanitize → textual LLVM IR
|
||||
└─ lower_async_copy_if_enabled shared pre-emit AIR rewrites
|
||||
└─ meta::parse_air_{frag,vert,kern} stage interface metadata (bindings, attributes)
|
||||
└─ native emit (tools::emit_vulkan_spirv → native::emit_vulkan_spirv)
|
||||
parse (native/parse.rs, lex.rs) → LlModule
|
||||
typed IR (native/tir/, native/ir/)
|
||||
structured-by-construction emit (native/emitter/**, native/cfg/**)
|
||||
└─ structured_plan admits → Op*Merge; else unrepaired emit + relooper on retry
|
||||
└─ retained SpirvModule + EmitSidecar
|
||||
└─ stage/resource/lowering passes (passes/**)
|
||||
└─ finish_module id canonicalization, portability normalization
|
||||
└─ assemble → SPIR-V words
|
||||
└─ spirv-val (vulkan1.3) validation/adoption gate; not part of the bytes
|
||||
└─ reflect final buffer footprints reflected entry points only; read-only over adopted bytes
|
||||
```text
|
||||
.air | sanitized .ll
|
||||
└─ llvm-dis when needed + AIR sanitization
|
||||
└─ shared pre-parse AIR lowering
|
||||
└─ stage metadata and target-layout parsing
|
||||
└─ typed LLVM/AIR parse
|
||||
└─ primary structured CFG and typed interface emission
|
||||
└─ owned SpirvModule + EmitSidecar
|
||||
└─ stage, resource, memory, and interface passes
|
||||
└─ owned-module construction
|
||||
├─ close pointer/value and opaque-image representations
|
||||
├─ prune statically unreachable CFG
|
||||
├─ construct selected CFG functions with the bounded relooper
|
||||
├─ check load/store/select and Logical-pointer type invariants
|
||||
└─ check descriptor ABI invariants
|
||||
└─ if an owned invariant rejects the primary representation:
|
||||
construct one structurally selected alternate representation
|
||||
└─ canonical assembly
|
||||
└─ spirv-val --target-env vulkan1.2
|
||||
└─ optional read-only reflection over the returned bytes
|
||||
```
|
||||
|
||||
`translate_native_no_retry` is this path up to (but not including) spirv-val and the retry cascade.
|
||||
It is the pure primary emit used when you want “what the emitter produced first,” without rescue
|
||||
tiers.
|
||||
There is no production loop from `spirv-val` back into emission or rewriting. A validation failure
|
||||
is returned as `Err` / CLI `FALLBACK`. The product does not parse the failed output and does not use
|
||||
validator wording to select another representation.
|
||||
|
||||
Sanitization preserves the source `target datalayout`. The layout module parses its LLVM
|
||||
`v<size>:<abi>` entries and carries the typed vector-alignment rules in `EmitSidecar` through
|
||||
the primary and every retry. Exact successfully mapped `air.struct_type_info` member offsets take
|
||||
precedence; otherwise all decoration and byte-address walkers share the same natural member cursor,
|
||||
including LLVM allocation-size advancement for three-lane vectors. Retry diagnostics report exact
|
||||
metadata layouts that map explicitly and metadata shapes that could not be mapped.
|
||||
`translate_native_no_retry` retains its compatibility name. It constructs the primary
|
||||
representation up to, but not including, external validation and does not select an alternate when
|
||||
an owned invariant rejects that representation. `translate_native_primary_validated` validates
|
||||
that same primary-only construction. Ordinary `translate*` entry points may select an alternate
|
||||
before validation from the structural facts described below.
|
||||
|
||||
Kernel interface lowering owns one typed dispatch-grid contract. Whole-workgroup dispatch derives
|
||||
`[[threads_per_grid]]` from `NumWorkgroups * LocalSize`; exact Metal `dispatchThreads` uses either a
|
||||
fixed grid or, by default, a reflected three-`u32` push-constant grid at offset zero. That same value drives a structured entry
|
||||
cull for rounded-up Vulkan invocations, including kernels that do not declare the attribute. A
|
||||
partial grid with a source control barrier falls back rather than emitting an early return that
|
||||
would violate Vulkan barrier participation.
|
||||
## Typed ownership
|
||||
|
||||
### Text vs typed IR
|
||||
The production body path is parse once → typed IR → owned SPIR-V module:
|
||||
|
||||
The production body path is **parse once → typed IR → emit**. There is no mid-pipeline
|
||||
`Vec<String>` function body:
|
||||
- LLVM text is consumed by `native/parse.rs`, `native/lex.rs`, and the AIR metadata parser.
|
||||
- Instruction semantics are carried by typed `TirInst` / `TirBlock` fields. Unsupported opcodes
|
||||
fail visibly instead of being recovered from textual spellings.
|
||||
- CFG construction mutates typed `BodyBlock` carriers. Loop, selection, and terminal roles are
|
||||
structural tags rather than name-based decisions.
|
||||
- The native emitter and all retained passes share the crate-owned `SpirvModule`. Successful
|
||||
product construction does not serialize and reparse between passes.
|
||||
- Within each chosen representation, raw buffer scope is fixed from typed AIR before function
|
||||
emission, including incompatible multi-root pointer merges and integer atomics whose source
|
||||
pointee cannot be addressed as an `i32` Logical pointer. A function is emitted once; emitter
|
||||
errors never rerun it with a broader buffer model.
|
||||
- `EmitSidecar` carries typed facts that do not belong in SPIR-V instructions, including AIR
|
||||
layouts, buffer-address words, pointer-field stores, and CFG ownership rejections. Passes remap
|
||||
those facts when IDs change.
|
||||
|
||||
- LLVM-IR text is read in the parser (`parse.rs` / `lex.rs`) and in `meta/` for AIR metadata.
|
||||
- Instruction and terminator **semantics** are carried on typed `TirInst` / `TirBlock` fields
|
||||
(`operands`, `call`, `phi_incoming`, etc.). The emitter walks those carriers
|
||||
(`emit_body_inst`); unmigrated opcodes fail visibly rather than re-lexing text.
|
||||
- The CFG structurizer (`cfg/**`) mutates typed block carriers (`BodyBlock.typed`), not string
|
||||
lines. Roles such as loop-merge / terminal-exit are typed tags on `BodyBlock`, not name-decoded
|
||||
decisions in production control flow.
|
||||
- Four pre-emit rewrites still run as **text→text** on the sanitized AIR string before parse:
|
||||
`async_copy`, `vec_scalar_merge`, `sroa`, and `inline` (including the `inline_sroa*` retry
|
||||
variants). They are intentional pre-parse passes, not mid-pipeline body text.
|
||||
Four source transforms intentionally operate before typed parsing: async-copy lowering,
|
||||
vector/scalar pointer-merge lowering, SROA, and internal-helper inlining. Alternate representations
|
||||
receive the same already-lowered source, so they do not observe a different program.
|
||||
|
||||
### Reflection
|
||||
## Validity by construction
|
||||
|
||||
Each translation decodes AIR metadata once into a `StageMeta` shared by emission, passes,
|
||||
reflection, and retry re-emissions. After a reflected translation adopts its final validating
|
||||
module, a read-only analyzer derives conservative buffer byte footprints from those exact bytes.
|
||||
Public `translate_*_reflected` entry points return `(Vec<u8>, reflect::ShaderReflection)` with
|
||||
**bytes identical** to the non-reflected call.
|
||||
`finish_module` is the common owned-module boundary for primary and alternate emission. It performs
|
||||
the following work before assembly:
|
||||
|
||||
The default descriptor ABI ranges (buffers `0..32`, sampled textures `32..160`, samplers
|
||||
`160..192`, colors `192..200`, and storage textures `480..608`, set 0) live in
|
||||
`reflect` and are consumed by the resource pass so decorated bindings and reported reflection share
|
||||
one checked contract. A final module audit rejects descriptor classes outside their bands. Start
|
||||
with the integration [how-to](HOWTO.md); the complete schema and ABI contract is in
|
||||
[`REFLECTION.md`](REFLECTION.md).
|
||||
1. Run interface, resource, access, workgroup, stage-input, stage-output, finalization, and module
|
||||
cleanup passes.
|
||||
2. Close cross-binding pointer operations in the value domain where their load/store closure is
|
||||
representable.
|
||||
3. Retype Workgroup atomic storage and construct opaque-image selects using the consumers' image
|
||||
types.
|
||||
4. Lower remaining representable cross-binding pointer closures to the address domain.
|
||||
5. Canonicalize IDs while remapping the sidecar.
|
||||
6. On the primary representation, remove invalid value chains made unreachable by static CFG
|
||||
pruning.
|
||||
7. Reconstruct only CFG functions selected by source ownership or final owned-CFG facts.
|
||||
8. On the selected raw-relooper representation, carry address-domain selection into final resource
|
||||
construction, then rebuild the selected CFG and canonicalize the completed graph.
|
||||
9. Reject malformed result-type IDs and core type-declaration graphs before any instruction can
|
||||
treat an arbitrary defined ID as a type.
|
||||
10. Reject owned arithmetic, comparison, shift, numeric-bitcast, bit-count, Boolean reduction,
|
||||
float-classification, vector-algebra, derivative, copy, select, phi, load, and store type
|
||||
disagreement; atomic pointer-pointee, result, value, comparator, scope, and memory-semantics type
|
||||
disagreement; unknown GLSL.std.450 opcodes and extended-instruction arity or type-shape
|
||||
disagreement; sampled-image result, image, and sampler type disagreement; image-query result,
|
||||
dimension, array, multisample, sampled/storage mode, LOD, and coordinate disagreement; derivatives
|
||||
and implicit-LOD queries reachable outside a Fragment call tree; texel fetch/read/write image mode,
|
||||
component, coordinate, result, texel, LOD, and sample disagreement; sampled-image operation result,
|
||||
coordinate, component, LOD, constant-offset, and stage disagreement; image-texel-pointer result,
|
||||
image, coordinate, sample, and atomic-format disagreement; barrier scope, memory-semantics, and
|
||||
execution-model disagreement; subgroup vote, ballot, shuffle, arithmetic, scope, index,
|
||||
group-operation, and cluster-size disagreement; access-chain base/result storage, integer index,
|
||||
structure-member, and result-pointee disagreement; invalid branch and switch
|
||||
controls; inconsistent function signatures, calls, parameters, and returns; inconsistent
|
||||
composite constituents, index paths, dynamic vector operations, and shuffle lanes; invalid
|
||||
structure-member indices; non-32-bit Vulkan 1.2 bit-field/count/reverse bases; and Logical pointer
|
||||
nulls, cross-root selects, or pointer-valued variables.
|
||||
11. Reject descriptor bindings outside the configured ABI.
|
||||
12. Assemble once.
|
||||
|
||||
### Retained module seam
|
||||
The owned checks are deliberately narrower than a second SPIR-V validator. They enforce invariant
|
||||
classes the translator itself has enough information to guarantee and use failures as construction
|
||||
facts while the source and module are still owned. `spirv-val` remains the independent final
|
||||
backstop for the complete Vulkan SPIR-V contract.
|
||||
|
||||
The native emitter and the typed passes share one crate-owned `SpirvModule`. Emission returns an
|
||||
internal `EmittedSpirv` (module + `EmitSidecar`); `finish_module` hands both into the pass
|
||||
context. The validating-primary path assembles once after passes complete.
|
||||
### Representation selection
|
||||
|
||||
`SpirvModule` owns section layout, load/assemble, result-id allocation, and instruction/block
|
||||
nodes. Retries may re-enter from bytes, but they parse back into the same module type. There is no production dependency on an external SPIR-V builder; optional validation
|
||||
helpers may use `rspirv` as an offline oracle only.
|
||||
Alternate construction is selected before validation:
|
||||
|
||||
Related ownership:
|
||||
|
||||
| Area | Location |
|
||||
| Owned fact | Constructed representation |
|
||||
|---|---|
|
||||
| Layout rules (AIR / SPIR-V / tight / padded) | crate `layout` module |
|
||||
| Value/type queries on retained SPIR-V | `passes/value_queries.rs` |
|
||||
| Access-chain / subword / Workgroup / Private | `passes/access/` |
|
||||
| Structured-CFG repairs after AIR-call phase | `passes/cfg_repair/` |
|
||||
| AIR/LLVM intrinsic lowering | `passes/air_calls/` (+ `images/`) |
|
||||
| Workgroup interface + zero-init | `passes/workgroup/` |
|
||||
| Resource discovery, bindings, rewrites | `passes/resources/` |
|
||||
| Stage inputs / outputs | `passes/stage_input/`, `passes/stage_output/` |
|
||||
| Finalize, GC, caps, type singletons | `passes/finalize.rs`, `module_cleanup.rs`, `type_singletons.rs` |
|
||||
| Source CFG ownership rejection or final owned-CFG construction failure | raw-buffer relooper feed |
|
||||
| Internal helper directly consumes a pointer-select result | consuming-helper inline + bounded CFG construction |
|
||||
|
||||
The emit sidecar carries Word-id-keyed facts (buffer-address words, local-pointer field stores,
|
||||
static/dynamic field loads, AIR struct offsets). Producers append; inlining and resource rewrites
|
||||
remap them. There is no cross-seam `OpName` marker protocol for facts.
|
||||
If the selected alternate cannot be constructed, translation fails honestly. The implementation
|
||||
does not serialize multiple candidates and ask the validator which one to adopt.
|
||||
Malformed declarations, load/store/select/access typing, ordinary value typing, environment
|
||||
contracts, function contracts, and value-composite contracts are non-repairable validity failures.
|
||||
They cannot select an alternate representation merely because they are discovered at the same
|
||||
owned-module boundary as CFG facts. Raw buffer scope is chosen from typed AIR before emission.
|
||||
|
||||
Metal vertex entries carrying `air.patch` metadata finalize as Vulkan tessellation-evaluation
|
||||
entries. The interface pass maps `position_in_patch` to `TessCoord`, `patch_id` to `PrimitiveId`,
|
||||
per-patch arguments to `Patch` inputs, and metadata-described control-point accessors to indexed
|
||||
loads from control-point input arrays. The AIR patch domain and control-point count, never a shader
|
||||
name, determine the execution modes and array extents.
|
||||
Validator-message classifiers and byte-level repair adapters are deliberately absent. Diagnostics
|
||||
inspect AIR or an owned module directly; validator text is only returned to the caller.
|
||||
|
||||
### Inlining
|
||||
|
||||
Helpers are inlined on the producer side where structural rules allow (one-block and multi-block
|
||||
leaf helpers, constructor CFGs). Typed SSA, pointee/raw-buffer facts, and sidecar IDs move with
|
||||
the splice. Residual indirect/bodiless/conflicting cases stay as calls. Dead-function pruning and
|
||||
chained-access composition remain in their post-inline cleanup phase; `passes/emitted_inline/` is
|
||||
the producer-side inliner.
|
||||
|
||||
### Structurizer
|
||||
|
||||
Emission is structured-by-construction when possible:
|
||||
## CFG structurization
|
||||
|
||||
1. `native::cfg` builds a loop/selection forest from the AIR CFG.
|
||||
2. `structured_plan` decides whether that forest is expressible as Vulkan structured control flow.
|
||||
3. **Admit** → emitter walks the plan (`OpLoopMerge` / `OpSelectionMerge`), then
|
||||
`repair_pre_phi_incoming_materializations` relocates illegal in-phi-block access chains.
|
||||
4. **Reject** → function emits with inferred merges unrepaired; the retry cascade’s **relooper**
|
||||
(`native/relooper.rs`) strips merges and rebuilds structured CFG. The relooper is the sole
|
||||
general structuring fallback.
|
||||
2. `structured_plan` admits forests expressible as Vulkan structured control flow.
|
||||
3. Admitted functions emit `OpLoopMerge` / `OpSelectionMerge`; phi incoming materializations belong
|
||||
to predecessor edges and are inserted before their merge/terminator instructions.
|
||||
4. Rejected bounded CFGs use typed construct-tree ownership, regional dispatch, or a whole-CFG
|
||||
dispatcher where their scalar state is representable.
|
||||
5. Source ownership rejections are recorded in the sidecar. After interface lowering and static CFG
|
||||
pruning, the owned module also checks conditional/switch merge ownership and dominance
|
||||
backedges. Only affected functions are rebuilt by the bounded relooper before assembly.
|
||||
|
||||
Between reject and relooper, a few specialized constructions may still admit a shape
|
||||
(`structured_plan_divergent_exit`, construct-tree own-arm retry for a narrow class). Adoption of
|
||||
retry-produced modules is always **spirv-val gated**.
|
||||
The whole-function state-machine representation has a hard block ceiling because a module can be
|
||||
SPIR-V-valid yet pathological for a driver compiler. Exceeding that construction ceiling remains a
|
||||
visible failure; validation success is not used to waive it.
|
||||
|
||||
Diagnose admit/reject reasons with `METAL2VULKAN_WHY=1` on a local translate of the module under
|
||||
study.
|
||||
Diagnose planner admission with `METAL2VULKAN_WHY=1`. Diagnostic environment variables may report
|
||||
facts, but product representation selection is not environment-gated.
|
||||
|
||||
## Retry cascade
|
||||
## Layout and interfaces
|
||||
|
||||
When the primary emit fails validation (or the emitter returns an error), translation walks a fixed
|
||||
ladder of retry **tiers**. Mechanisms live in `retry.rs`; routing lives in
|
||||
`translate_sanitized_with_meta` as a match on `native::classify_{validation,emit}_error`.
|
||||
Sanitization preserves `target datalayout`. Vector ABI alignment, allocation-size advancement, and
|
||||
successfully mapped `air.struct_type_info` offsets flow through the sidecar and are shared by
|
||||
decorations and byte-address walkers.
|
||||
|
||||
Three invariants:
|
||||
The default descriptor ABI ranges are owned by `reflect`: buffers `0..32`, sampled textures
|
||||
`32..160`, samplers `160..192`, colors `192..200`, and storage textures `480..608`, all in set 0.
|
||||
Resource lowering and reflection consume the same checked contract. See [REFLECTION.md](REFLECTION.md).
|
||||
|
||||
1. **Adopt only if the candidate validates.** A module that already passed spirv-val never enters
|
||||
the cascade; a non-validating retry result is discarded.
|
||||
2. **Tier order is load-bearing.** Example: value-select before PhysicalStorageBuffer (device-address)
|
||||
lowering, because some drivers cannot pipeline BDA modules as compute; inline+SROA before relooper
|
||||
where that ordering has been proven safer. Do not reorder tiers casually.
|
||||
3. **Validator success is not a driver-cost proof.** The whole-function switch/state-machine
|
||||
relooper has a hard 1,024-block ceiling. Larger flattened modules can validate quickly while
|
||||
taking real drivers many minutes to compile or crashing their compiler, so they return
|
||||
`FALLBACK` until a regional structurizer can preserve most of the CFG and SSA.
|
||||
Kernel interface lowering also owns the dispatch-grid contract. Whole-workgroup dispatch derives
|
||||
`threads_per_grid` from `NumWorkgroups * LocalSize`; exact dispatch uses a fixed or dynamic grid and
|
||||
partitions partial workgroups without divergent early returns around barriers.
|
||||
|
||||
Classification of validator/emitter text into `ValidationClass` / `EmitErrorClass` is confined to
|
||||
`native` (`classify_validation_error` / `classify_emit_error`). The cascade then routes by class:
|
||||
Metal vertex entries with `air.patch` metadata become tessellation-evaluation entries. Patch domain,
|
||||
control-point count, interface roles, and array extents come from AIR structure and metadata, never
|
||||
shader names.
|
||||
|
||||
| Class | Typical tier order (census labels under `METAL2VULKAN_TIER_CENSUS`) |
|
||||
|---|---|
|
||||
| PointerTyping | `fc_promote_logical` → raw → prune → subword pack → raw+relooper → `fc_promote_psb` |
|
||||
| CfgStructurization | relooper → prune+relooper → raw+relooper |
|
||||
| LogicalPointerPhi | phi-index legalization → prune |
|
||||
| CrossBindingPointerMerge | value-select → PSB → raw+PSB → prune |
|
||||
| Other (validation) | prune → raw+relooper → value-select |
|
||||
| Emit PointerTyping / Other | raw / BDA / PSB / inline-SROA combinations |
|
||||
## Reflection
|
||||
|
||||
CFG shapes that the structurizer rejects now fail **validation** (unrepaired merges), not a separate
|
||||
CFG emit-error arm. Emit-error routing is essentially `{PointerTyping, Other}`.
|
||||
|
||||
### Primary-path rewrites
|
||||
|
||||
Before the cascade, several validation-gated rewrites run on the primary path itself
|
||||
(`apply_primary_emit_rewrites` and related helpers in `lib.rs`). Each is a no-op on modules that do
|
||||
not carry its shape. Examples: cross-binding value-domain lowering, logical-pointer-phi
|
||||
legalization, multi-entry loop split, and reject-triggered structured-plan admission handlers.
|
||||
These run unconditionally on the product path; `src/env_vars.rs` is for diagnostics, tool overrides,
|
||||
and default-off measurement substrates only—not product feature gates.
|
||||
Reflected translation shares one parsed `StageMeta` with emission and passes. After the sole module
|
||||
has validated, read-only analysis derives conservative buffer footprints from the returned bytes.
|
||||
The reflected and non-reflected entry points return identical SPIR-V bytes for identical options.
|
||||
|
||||
## Verification
|
||||
|
||||
Match the check to the change. The full developer playbook (harvest → author cases → exact A/B →
|
||||
targeted GPU evidence) lives in **[`VALIDATION.md`](VALIDATION.md)**.
|
||||
Match evidence to the claim. The complete developer ladder is in [VALIDATION.md](VALIDATION.md).
|
||||
|
||||
| Check | Command / tool | Catches |
|
||||
|---|---|---|
|
||||
| Lint | `cargo clippy` | style / obvious bugs |
|
||||
| Unit + integration | `cargo test -- --test-threads=1` | translator regressions |
|
||||
| Byte A/B | validation `corpus-ab` | exact old/new translator drift without a GPU |
|
||||
| Authored cases | `validation/corpus/cases/` | literal semantic inputs and output selection |
|
||||
| Exact observations | `validation/corpus/observations/` | dependency-complete current experiment slots |
|
||||
| Private corpus (optional) | `validation/corpus/local/sources/` | aligned sanitized AIR source shards |
|
||||
| Metal qualification (optional) | validation `corpus-metal` | literal case execution and golden bytes |
|
||||
| Candidate execution (optional) | `corpus-moltenvk` / `corpus-vulkan` | candidate bytes vs exact Metal observation |
|
||||
| Check | Catches |
|
||||
|---|---|
|
||||
| `cargo clippy --workspace --all-targets -- -D warnings` | warnings and common defects |
|
||||
| serial product and validation tests | construction and tooling regressions |
|
||||
| primary-validity tests | violations escaping owned construction |
|
||||
| byte A/B | unintended output drift |
|
||||
| authored Metal/Vulkan execution | semantic disagreement beyond SPIR-V validity |
|
||||
| bounded release-mode corpus translation | time, memory, and unsupported-shape coverage |
|
||||
|
||||
Always rebuild the translator binary before measuring. Default CI is synthetic-only; private
|
||||
metallib harvest is gitignored under `validation/corpus/local/` (see that README). GPU validation
|
||||
never affects product translation paths and never infers an execution plan from AIR.
|
||||
|
||||
## Hard-won constraints
|
||||
|
||||
- **spirv-val validity ≠ end-to-end correctness.** Retyping a load/store carrier only to silence the
|
||||
validator is unsound if it changes meaning.
|
||||
- **Post-hoc repair was deleted for a reason.** Remaining “repair” is narrow and structural (e.g.
|
||||
phi-incoming materialization relocation), not a large merge-rewrite roster. Broad repair deletion
|
||||
is byte-changing and needs execution evidence, not only a reject census of zero.
|
||||
- **No name-keyed translation.** Decide from IR structure, types, storage classes, and the AIR
|
||||
metadata ABI—not from shader/function names observed in particular workloads. Stable `air.*` /
|
||||
`llvm.*` ABI symbols are the allowed exception.
|
||||
- **Admission is reject-triggered and spirv-val gated.** Do not invent structured exits from
|
||||
dominance alone as a primary admission path.
|
||||
`spirv-val` validity is necessary but not sufficient for semantic correctness. A type rewrite that
|
||||
only silences the validator is unsound. Construction decisions must follow IR types, storage
|
||||
classes, CFG ownership, and stable AIR/LLVM ABI structure; unknown semantics remain `FALLBACK`.
|
||||
+28
-20
@@ -10,8 +10,8 @@ Product translation uses two external executables:
|
||||
|
||||
- `llvm-dis` converts AIR bitcode to LLVM IR. It is not needed when the input is already textual
|
||||
`.ll`.
|
||||
- `spirv-val` validates every candidate under the Vulkan 1.3 environment. A retry candidate is
|
||||
adopted only after it validates.
|
||||
- `spirv-val` validates the single constructed output under the Vulkan 1.2 environment. Its verdict
|
||||
cannot trigger a repair or select another representation.
|
||||
|
||||
Put both tools on `PATH`, or set an absolute per-tool override:
|
||||
|
||||
@@ -55,9 +55,9 @@ These options affect pipeline- or dispatch-dependent lowering:
|
||||
| `--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` | Bake one exact Metal `dispatchThreads` grid into a pipeline variant |
|
||||
| `--threads-per-grid-push-constant OFFSET` | Move the default per-dispatch exact grid from push-constant offset 0 to `OFFSET` |
|
||||
| `--whole-workgroups` | Assert every kernel launch covers complete workgroups and omit the default grid guard |
|
||||
| `--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.
|
||||
Do not use either option as a workaround for an unrelated translation failure.
|
||||
@@ -177,7 +177,7 @@ their resources are unrelated, and use the returned effective layout rather than
|
||||
|
||||
Successful reflected translation attaches `footprint` to descriptor-backed `Buffer`,
|
||||
`KernelStageInput`, and `AccelerationStructureShadow` resources. It describes accesses in the final
|
||||
SPIR-V module selected by the retry cascade.
|
||||
constructed SPIR-V module returned by translation.
|
||||
|
||||
Apply this decision in order:
|
||||
|
||||
@@ -224,15 +224,22 @@ footprint soundness gate. Treat `access: null` conservatively as read-write.
|
||||
`depth_qualifier`.
|
||||
- Kernel stages use `local_size`. `imageblock_layouts` and threadgroup bindings describe Workgroup
|
||||
storage rather than descriptors.
|
||||
- For kernels, obey `kernel_dispatch`. The safe default is `ThreadsPushConstant` at offset 0:
|
||||
declare a compute-stage range of `KERNEL_GRID_PUSH_CONSTANT_SIZE` bytes and write three tightly
|
||||
packed `u32` dimensions before every `vkCmdDispatch`. For Metal `dispatchThreads`, write its exact
|
||||
requested thread count; for `dispatchThreadgroups`, write `groupCount * local_size`. The shader
|
||||
uses that same value for both `[[threads_per_grid]]` and surplus-invocation culling.
|
||||
`ThreadsFixed` bakes a grid into a pipeline variant. `Workgroups` needs no extra state but is an
|
||||
explicit proof that partial threadgroups will never reach the kernel.
|
||||
- Use `function_constants` to discover exact indices and Metal ABI type encodings. Specialize IR
|
||||
with `specialize_function_constant_bytes` when exact scalar or vector payloads are required.
|
||||
- For kernels, obey `kernel_dispatch`. For `ThreadsDynamic` and `ThreadsFixed`, call
|
||||
`KernelDispatch::plan`, create one pipeline per distinct region `local_size` using
|
||||
`KERNEL_LOCAL_SIZE_SPEC_IDS`, and issue every returned region. Before each dispatch, write
|
||||
`KernelDispatchPlan::push_constants` into the reflected
|
||||
`KERNEL_DISPATCH_PUSH_CONSTANT_SIZE` range. Its four `u32[3]` fields are the logical thread grid,
|
||||
thread base, threadgroup base, and logical threadgroup grid. `Workgroups` is the only single
|
||||
fixed-local-size path and asserts that every workgroup is complete.
|
||||
- Use `function_constants` to discover exact indices and Metal ABI type encodings. When exact scalar
|
||||
or vector payloads are supplied, translate sanitized AIR with
|
||||
`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
|
||||
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.
|
||||
|
||||
## 7. Cache outputs safely
|
||||
|
||||
@@ -253,7 +260,7 @@ has no final-module footprint and is not a substitute for reflected translation
|
||||
The Rust API returns `Err(String)`. The CLI prints `FALLBACK`, exits nonzero, and writes a self-
|
||||
contained repro bundle under `$TMPDIR/metal2vulkan-repros` unless `METAL2VULKAN_REPRO_DIR` overrides
|
||||
the base directory. Unsupported input must remain a fallback; do not continue with partial metadata
|
||||
or a rejected retry candidate.
|
||||
or a construction that returned an error.
|
||||
|
||||
For local diagnosis:
|
||||
|
||||
@@ -262,16 +269,17 @@ METAL2VULKAN_RETRY_DEBUG=1 metal2vulkan input.air output.spv
|
||||
METAL2VULKAN_WHY=1 metal2vulkan input.air output.spv
|
||||
```
|
||||
|
||||
The first command shows retry-tier attempts. The second reports structured-CFG admission decisions.
|
||||
These diagnostics do not authorize a different product translation path.
|
||||
The first command traces construction phases (the environment-variable name is retained for
|
||||
compatibility). The second reports structured-CFG admission decisions. These diagnostics do not
|
||||
authorize a different product translation path.
|
||||
|
||||
## 9. Verify the integration
|
||||
|
||||
At minimum:
|
||||
|
||||
```sh
|
||||
spirv-val --target-env vulkan1.3 output.spv
|
||||
cargo test -p metal2vulkan -- --test-threads=1
|
||||
spirv-val --target-env vulkan1.2 output.spv
|
||||
cargo test -p metal2vulkan
|
||||
```
|
||||
|
||||
`spirv-val` checks structural validity, not Metal equivalence. For a semantic claim, follow the
|
||||
|
||||
+26
-18
@@ -4,7 +4,9 @@ When metal2vulkan translates Metal AIR or sanitized LLVM IR, it has two authorit
|
||||
consumer information:
|
||||
|
||||
- AIR metadata plus the translator's shared descriptor ABI define resources and stage interfaces.
|
||||
- Read-only analysis of the final adopted SPIR-V defines conservative buffer byte footprints.
|
||||
- Read-only analysis of the final constructed SPIR-V module defines conservative buffer byte
|
||||
footprints. It consumes the same owned module that supplies the returned bytes; it does not parse
|
||||
serialized output back into a second module.
|
||||
|
||||
Both are exposed as [`ShaderReflection`](../src/reflect/mod.rs), so a host does not need to reparse
|
||||
AIR or build a second general-purpose SPIR-V reflection path. Reflection remains **byte-neutral**:
|
||||
@@ -41,6 +43,7 @@ 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 |
|
||||
| `reflect_sanitized_specialized` | You need metadata for exact function-constant values that can select resources or outputs; buffer footprints remain absent |
|
||||
| `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
|
||||
@@ -174,8 +177,8 @@ Top-level fields:
|
||||
| `render_targets` | Fragment color attachments (member index + location + type name) |
|
||||
| `depth_members` / `stencil_members` | Fragment return members tagged depth/stencil |
|
||||
| `depth_qualifier` | Fragment depth comparison contract (`Any`, `Less`, or `Greater`) |
|
||||
| `local_size` | Kernel GLCompute local size `[x,y,z]` when known |
|
||||
| `kernel_dispatch` | Kernel grid source: whole workgroups, fixed exact threads, or the reflected per-dispatch push-constant offset |
|
||||
| `local_size` | Nominal Metal kernel local size `[x,y,z]`; exact-thread regions specialize boundary dimensions |
|
||||
| `kernel_dispatch` | Whole-workgroup launch or the fixed/dynamic exact-thread region-planning contract |
|
||||
| `vertex_builtins` | Whether vertex uses `VertexIndex` / `InstanceIndex` / writes `Position` |
|
||||
| `tessellation` | Post-tessellation patch domain, control-point count, locations, and synthesized system-value carriers |
|
||||
| `imageblock_layouts` | Kernel `[[imageblock]]` tiles (param index + AIR struct layout; no descriptor) |
|
||||
@@ -242,11 +245,11 @@ classification is retained.
|
||||
|
||||
### Buffer byte footprints
|
||||
|
||||
Successful reflected translation derives each supported descriptor-backed buffer's `footprint` from the
|
||||
**final adopted SPIR-V module**. This is intentionally later than AIR metadata reflection: if the
|
||||
validator selects a raw-buffer, pointer-value, or CFG retry tier, the footprint describes the bytes
|
||||
that tier actually executes. Metadata-only `reflect_sanitized` leaves `footprint: null` because no
|
||||
executable module exists to audit.
|
||||
Successful reflected translation derives each supported descriptor-backed buffer's `footprint`
|
||||
from the **final constructed SPIR-V module**. This is intentionally later than AIR metadata
|
||||
reflection: if owned structural facts select a raw-buffer, pointer-value, or CFG representation,
|
||||
the footprint describes the bytes that representation actually executes. Metadata-only
|
||||
`reflect_sanitized` leaves `footprint: null` because no executable module exists to audit.
|
||||
|
||||
Footprints are populated for `Buffer`, `KernelStageInput`, and `AccelerationStructureShadow` when
|
||||
they have a descriptor. Other resource kinds leave the field null.
|
||||
@@ -399,14 +402,17 @@ choice. Create the image view and descriptor from the same runtime state used fo
|
||||
8. For vertex: bind attributes from `vertex_attributes` and respect `vertex_builtins`.
|
||||
9. For fragment: attach color targets from `render_targets`; attach the reflected depth/stencil
|
||||
aspects and derive depth comparison from `depth_qualifier`.
|
||||
10. For kernels: set local size from `local_size` and obey `kernel_dispatch`. The default
|
||||
`ThreadsPushConstant` grid begins at `DEFAULT_KERNEL_GRID_PUSH_CONSTANT_OFFSET` and occupies
|
||||
`KERNEL_GRID_PUSH_CONSTANT_SIZE` bytes: write three tightly packed `u32` dimensions before each
|
||||
dispatch. Supply the exact thread count for `dispatchThreads`, or `groupCount * local_size` for
|
||||
`dispatchThreadgroups`. `Workgroups` appears only when the caller explicitly proves every launch
|
||||
is complete. Specialize
|
||||
function constants if the host supplies values. Use `specialize_function_constant_bytes` for
|
||||
exact scalar/vector payloads; the `u64`-only helper cannot carry vectors wider than eight bytes.
|
||||
10. For kernels: obey `kernel_dispatch`. `ThreadsDynamic` and `ThreadsFixed` require
|
||||
`KernelDispatch::plan`. Create a pipeline for each distinct region `local_size`, specializing
|
||||
the three `KERNEL_LOCAL_SIZE_SPEC_IDS`; write the region's
|
||||
`KernelDispatchPlan::push_constants` payload into the reflected
|
||||
`KERNEL_DISPATCH_PUSH_CONSTANT_SIZE` range; then dispatch its `group_count`. Execute every
|
||||
returned region. `Workgroups` is the only single-pipeline path and appears only when the caller
|
||||
explicitly proves every launch is complete. When the host supplies function constants, use
|
||||
`translate_sanitized_native_specialized_with_options` so exact scalar/vector payloads are baked
|
||||
before metadata, resource-interface, and CFG construction. Post-SPIR-V specialization cannot
|
||||
restore a resource or branch already removed under the default value. Specialized reflection
|
||||
exposes true-gated resources and omits false-gated resources from the descriptor contract.
|
||||
|
||||
## Related APIs
|
||||
|
||||
@@ -415,8 +421,10 @@ choice. Create the image view and descriptor from the same runtime state used fo
|
||||
| `metal2vulkan::reflect` | Public facade (`ShaderReflection`, ABI constants) |
|
||||
| `metal2vulkan::meta` | Lower-level AIR metadata parsers (`FragMeta` / `VertMeta` / `KernMeta`) |
|
||||
| `metal2vulkan::passes::Stage` | Stage enum for translate |
|
||||
| `metal2vulkan::specialize_function_constants` | Specialize FC values on sanitized IR (when needed) |
|
||||
| `metal2vulkan::specialize_function_constant_bytes` | Specialize exact-width scalar/vector FC payloads |
|
||||
| `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::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
|
||||
0/32/160/192/200/224/480, and a synthetic range beginning at 640; configurable layouts are covered
|
||||
|
||||
+101
-44
@@ -7,20 +7,20 @@ Choose the smallest route that proves the claim being made:
|
||||
|
||||
| Goal | Required starting point |
|
||||
|---|---|
|
||||
| Ordinary code change | Format, clippy, and serial product/validation tests |
|
||||
| Ordinary code change | Format, clippy, and parallel product/validation tests |
|
||||
| Behavior-preserving translator refactor | Ordinary gate plus exact old/new `corpus-ab` over the structurally affected selection |
|
||||
| Intentional shader behavior change | Synthetic regression, reviewed byte drift, and affected authored Metal/candidate evidence |
|
||||
| Corpus-wide support or performance claim | Resumable indexed `corpus-triage` audit with its completion/read/time summaries |
|
||||
|
||||
## Ordinary gate
|
||||
|
||||
Always run Rust tests serially:
|
||||
Run Rust tests with Cargo's default available parallelism:
|
||||
|
||||
```sh
|
||||
cargo fmt --all
|
||||
cargo clippy --workspace --all-targets -- -D warnings
|
||||
cargo test -p metal2vulkan -- --test-threads=1
|
||||
cargo test -p metal2vulkan-validation -- --test-threads=1
|
||||
cargo test -p metal2vulkan
|
||||
cargo test -p metal2vulkan-validation
|
||||
```
|
||||
|
||||
CI uses owned synthetic fixtures. Private AIR and machine-specific GPU execution are optional.
|
||||
@@ -80,38 +80,69 @@ cargo run -p metal2vulkan-validation --release --bin corpus-triage -- \
|
||||
--audit authoring-capabilities --limit 100000
|
||||
```
|
||||
|
||||
After changing only the product's AIR-intrinsic recognition/lowering contract, add
|
||||
`--reclassify-all`. It recomputes the product disposition for every current analyzer row directly
|
||||
from the cached exact `air_calls` inventory. The operation ignores the ordinary `--limit`, uses
|
||||
bounded keyset batches, and opens zero AIR source shards. Changes to source-derived structural
|
||||
analysis instead require an analyzer ABI bump; the ordinary incremental audit then reads and caches
|
||||
each row once under the new ABI.
|
||||
After changing the product or source-derived structural contract, bump the analyzer ABI and add
|
||||
`--reclassify-all`. It deliberately selects every indexed identity up to `--limit`, reopens the
|
||||
indexed source slices, and replaces their facts under the new contract. This is the cold closure
|
||||
proof; follow it with the ordinary command above, which must select no rows and open/read zero source
|
||||
shards once the index is warm.
|
||||
|
||||
The summary exposes classified and remaining counts plus exact shard bytes read, so both an
|
||||
incomplete support claim and an accidental corpus rescan are visible. Classification defaults to
|
||||
all logical CPU cores. Only one parsed source may wait outside the workers (individual rows can be
|
||||
tens of MiB), result channels are bounded, and cache writes are committed in fixed-size batches, so
|
||||
a full recomputation does not retain the corpus in memory; use `--jobs N` to lower the aggregate
|
||||
working set.
|
||||
the host's available logical CPU count (the equivalent of `nproc`). Only one parsed source may wait
|
||||
outside the workers (individual rows can be tens of MiB), result channels are bounded, and cache
|
||||
writes are committed in fixed-size batches, so a full recomputation does not retain the corpus in
|
||||
memory.
|
||||
|
||||
### Run the bounded translation census
|
||||
|
||||
The translation census is resumable and uses the same indexed source locations. Discovery skips any
|
||||
hash that has already translated (or has been classified as requiring authored linkage), while
|
||||
`--current-fingerprint` performs a fresh regression sweep after product changes. A validation-harness
|
||||
fix can re-run only failures recorded for the current product with `--retry-failures`:
|
||||
`--current-fingerprint` performs a fresh regression sweep after product or translation-audit harness
|
||||
changes. Its cache fingerprint covers both contracts. `--retry-failures` re-runs only failures
|
||||
recorded for that exact fingerprint. `--retry-linkage` resumably revisits every row that an older
|
||||
fingerprint classified as requiring linkage but the current fingerprint has not attempted.
|
||||
Uncursored batches still prioritize historical failures, but materialize that compact priority set
|
||||
once rather than probing the complete audit history independently for every indexed identity;
|
||||
cursor pages use strict hash order and skip the priority work entirely.
|
||||
|
||||
Rows whose exact AIR flow proves that an observed visible-table operation depends on table contents
|
||||
are classified as `authored_linkage_required` before spawning translation tools. Dead lookups remain
|
||||
ordinary translation work, while unsupported pointer escapes remain failures; the shortcut applies
|
||||
only when the shared structural audit proves authored linkage is the sole missing semantic input.
|
||||
Direct `!air.visible_function_references` are different: their metadata already names the logical
|
||||
symbol. The audit resolves that symbol recursively when exactly one retained module from the same
|
||||
library defines it, using the disposable SQLite `(library, symbol)` index and the module's exact
|
||||
JSONL byte range. When parent-library resolution is missing or ambiguous, an exact authored case
|
||||
may instead name cross-library reference modules and their recursive dependency closure. Function
|
||||
tables likewise require exact authored slot population. For either authored linkage form, the
|
||||
isolated worker reads only that identity's hash-derived case shard, checks every case against the
|
||||
source row it already owns, translates with the exact linked modules, slots, and function
|
||||
constants, and validates every resulting module. The row is `translated` only when all of its
|
||||
authored cases succeed; a row with no complete authored population remains
|
||||
`authored_linkage_required`.
|
||||
|
||||
`--tier-census` is retained as compatibility telemetry. Product translation now reports `default`
|
||||
for any successfully constructed module and `fallback` for a construction error; representation
|
||||
selection is deliberately not exposed as validator-gated tier adoption. The disposable index can
|
||||
resume this measurement without rescanning warm source shards. Inputs that structurally require
|
||||
authored linkage remain `authored_linkage_required`.
|
||||
|
||||
For a targeted regression set, `--hash-file PATH` reads the lowercase SHA-256 in the first
|
||||
whitespace-delimited field of each non-empty line. It audits exactly those identities through their
|
||||
indexed byte ranges, so a saved structural manifest never requires a shard or corpus rescan.
|
||||
indexed byte ranges, so a saved structural manifest never requires a shard or corpus rescan. Combine
|
||||
it with `--tier-census` to persist the compatibility construction result for exactly that set.
|
||||
|
||||
Translation workers default to all available logical CPU cores. Each row is decoded from its indexed
|
||||
shard slice and translated in an independent child with the per-translation limits below; use
|
||||
`--jobs N` to reduce aggregate memory pressure. The summary reports source-read time separately from
|
||||
Translation workers default to the host's available logical CPU count (the equivalent of `nproc`).
|
||||
An explicit `--jobs N` is an operator override, not part of the normal full-corpus command. Each row
|
||||
is decoded from its indexed shard slice and translated in an independent child with the
|
||||
per-translation limits below. The summary reports source-read time separately from
|
||||
translate/validate time so serial decode overhead stays visible. To prevent CPU contention from
|
||||
turning into false wall-time failures, at most four AIR sources of 1 MiB or larger run concurrently;
|
||||
the remaining workers consume the small-source lane, and large-lane workers steal small work after
|
||||
their lane drains.
|
||||
turning into false wall-time failures, all requested workers finish sources below 256 KiB first,
|
||||
then at most two workers translate the costly 256-KiB-and-larger lane. Structurally costly
|
||||
device-address/function-table rows join that bounded lane regardless of serialized size. Inputs no
|
||||
larger than 384 KiB with at least 370 source blocks and 400 call instructions use a dedicated
|
||||
single-worker sublane, so their attempts cannot consume one another's wall-time budget while
|
||||
unrelated costly rows continue on the other worker.
|
||||
|
||||
```sh
|
||||
cargo run --release -p metal2vulkan-validation --bin corpus-triage -- \
|
||||
@@ -119,23 +150,28 @@ cargo run --release -p metal2vulkan-validation --bin corpus-triage -- \
|
||||
cargo run --release -p metal2vulkan-validation --bin corpus-triage -- \
|
||||
--audit translation --retry-failures --limit 500 --summary-only
|
||||
cargo run --release -p metal2vulkan-validation --bin corpus-triage -- \
|
||||
--audit translation --hash-file imageblock-sources.txt --summary-only
|
||||
--audit translation --tier-census --limit 500 --summary-only
|
||||
cargo run --release -p metal2vulkan-validation --bin corpus-triage -- \
|
||||
--audit translation --hash-file imageblock-sources.txt --tier-census --summary-only
|
||||
```
|
||||
|
||||
The 500-row checkpoint is the measured default for the current 88,819-row corpus: unlike a
|
||||
The 500-row checkpoint is the measured default for the current 88,820-row corpus: unlike a
|
||||
1,000-row checkpoint containing several of its largest modules, it retained comfortable margin
|
||||
under the repository's 30-second workflow ceiling while still persisting every ten completions.
|
||||
Jobs default to the host's available logical cores; increasing that value beyond the available
|
||||
cores can starve individual workers and create false timeouts.
|
||||
Jobs default to the host's available logical cores (`nproc`). Explicitly increasing that value
|
||||
beyond the available cores can starve individual workers and create false timeouts.
|
||||
|
||||
The translation audit supplies the validation graphics executor's single-sample pipeline contract
|
||||
when lowering `air.get_num_samples.i32`; authored candidate execution uses that same value. This is
|
||||
not a product default: general callers provide their exact raster sample count through
|
||||
`TransformOptions` or the CLI.
|
||||
|
||||
Each translation runs in a killable child with a 30-second / 512-MiB ceiling. The parent owns the
|
||||
Each translation runs in a killable child with a 30-second / 500-MiB ceiling. The parent owns the
|
||||
child's scratch subtree, so success, failure, timeout, and memory termination all have the same
|
||||
deterministic cleanup path; a killed child never strands a PID-named directory.
|
||||
deterministic cleanup path; a killed child never strands a PID-named directory. Completed results
|
||||
cross a queue bounded by the requested worker count. If a ten-row SQLite checkpoint fails, the
|
||||
parent cancels unclaimed work and drains only the in-flight bounded queue before reporting the
|
||||
database error.
|
||||
|
||||
### Run focused structural audits
|
||||
|
||||
@@ -150,12 +186,14 @@ cargo run -p metal2vulkan-validation --bin corpus-triage -- \
|
||||
--audit visible-function-tables --after LAST_SHA256 --limit 200 --summary-only
|
||||
```
|
||||
|
||||
The audit distinguishes direct/cast calls, internal-helper parameter threading, authored slot
|
||||
nullness checks, and unsupported pointer escapes. Dynamic dispatchers contain only linked functions
|
||||
whose LLVM signature matches the call site, allowing one authored table to hold heterogeneous
|
||||
visible-function types. AIR's exact `ptrtoint` / truncate / compare-with-`1` opaque-intersection
|
||||
sentinel probe is folded to false for authored visible tables, whose slots are strictly linked
|
||||
functions or null; other pointer-integer observations remain unsupported.
|
||||
The audit distinguishes direct/cast calls, table-handle and callback-pointer threading through
|
||||
internal helper parameters, authored slot nullness checks, and unsupported pointer escapes.
|
||||
Function-constant-wrapped table parameters retain the same authored-linkage role. Dynamic
|
||||
dispatchers contain only linked functions whose LLVM signature matches the call site, allowing one
|
||||
authored table to hold heterogeneous visible-function types. AIR's exact `ptrtoint` / truncate /
|
||||
compare-with-`1` opaque-intersection sentinel probe is folded to false for authored visible tables,
|
||||
whose slots are strictly linked functions or null; other pointer-integer observations remain
|
||||
unsupported.
|
||||
|
||||
Ray-intersection families use the same indexed cursor workflow:
|
||||
|
||||
@@ -172,7 +210,7 @@ translation cannot drift into separate whole-symbol allowlists.
|
||||
|
||||
Focused audits select cached structural facts, not unsupported-requirement rows. A feature therefore
|
||||
remains auditable after it becomes fully supported. Device-address captures use the same cursor and
|
||||
the same killable 30-second / 512-MiB translation worker as the full census:
|
||||
the same killable 30-second / 500-MiB translation worker as the full census:
|
||||
|
||||
```sh
|
||||
cargo run --release -p metal2vulkan-validation --bin corpus-triage -- \
|
||||
@@ -188,7 +226,10 @@ Authored fragment cases are executable, not review-only: `render_targets`, `dept
|
||||
`any`/`less`/`greater` qualifier, while stencil outputs use the native fragment stencil-export
|
||||
contract. Each runner derives the same fullscreen vertex inputs from the
|
||||
fragment AIR interface, and the candidate dependency hash covers both generated vertex SPIR-V and
|
||||
translated fragment SPIR-V.
|
||||
translated fragment SPIR-V. Render-target formats retain their exact channel width across both
|
||||
executors, including scalar `R32Float`, two-channel `Rg32Float`, and four-channel `Rgba32Float`.
|
||||
Authored Vulkan draws use clockwise front faces, matching a Metal render encoder's default winding;
|
||||
this keeps `[[front_facing]]` values comparable without rewriting the shader builtin.
|
||||
|
||||
Custom fragment `[[imageblock_data]]` is authored separately as `fragment_imageblock`: one
|
||||
tightly-packed plane per accessed AIR user semantic, with an explicit `half`, `half4`, `uchar4`, or
|
||||
@@ -313,10 +354,17 @@ cargo run -p metal2vulkan-validation --release --bin corpus-metal -- \
|
||||
--case-id CASE --environment-id METAL_ENV
|
||||
```
|
||||
|
||||
Qualification executes the literal manifest three times. The selected bytes must be identical on
|
||||
all runs and must differ from the exact initial poison bytes throughout the selected region. The
|
||||
accepted row records case/AIR/input/output hashes, output bytes, environment identity, and exact
|
||||
oracle ABI.
|
||||
Qualification first requires the shared checker to prove that the selected output maps to a
|
||||
shader-writable reflected resource, then executes the literal manifest three times. The selected
|
||||
bytes must be identical on all runs; byte-identical in-place transformations remain valid evidence
|
||||
because their write contract is established structurally rather than inferred from changed poison
|
||||
bytes. The accepted row records case/AIR/input/output hashes, output bytes, environment identity,
|
||||
and exact oracle ABI.
|
||||
|
||||
An authored `output` with `kind: "none"` records the exact empty byte sequence after normal GPU
|
||||
execution. The shared checker accepts it only when product reflection exposes no writable buffer,
|
||||
image, attachment, depth/stencil aspect, imageblock member, vertex position, or vertex varying; it
|
||||
cannot be used to ignore an observable shader result.
|
||||
|
||||
Candidates require a matching Metal slot and run independently:
|
||||
|
||||
@@ -338,9 +386,11 @@ reference under `visible_function_references` names the logical symbol from AIR'
|
||||
dependencies may come from a separate explicitly harvested Metal library, matching Metal's linked
|
||||
functions API. The Vulkan path recursively closes their dependency metadata, replaces every
|
||||
`.MTL_VISIBLE_FN_REF` stub with a direct call, and rejects an unresolved symbol. The checker also
|
||||
resolves each authored table slot from the hash-derived private library-module shard and proves
|
||||
same-metallib provenance before either runner starts. Metal receives all referenced `MTLFunction`
|
||||
handles through one `MTLLinkedFunctions` descriptor and creates native function tables. Intersection
|
||||
resolves each authored table slot from the hash-derived private library-module shard and proves that
|
||||
the exact module defines the exact authored symbol before either runner starts. Table entries may
|
||||
come from a separate explicitly harvested Metal library, matching `MTLLinkedFunctions`' object-based
|
||||
linking contract. Metal receives all referenced `MTLFunction` handles through one descriptor and
|
||||
creates native function tables. Intersection
|
||||
entries may instead author Metal's explicit opaque-triangle sentinel and its sorted signature
|
||||
flags; that entry uses the dedicated native opaque-triangle API and needs no library module.
|
||||
Vulkan translation specializes visible-table calls to the exact linked AIR definitions; constant
|
||||
@@ -362,6 +412,13 @@ support and writes that address into the reflected owner field; the BDA lowering
|
||||
the identical logical resource. `argument_buffer_buffer` output selection observes writable nested
|
||||
buffers directly.
|
||||
|
||||
A top-level AIR `array_ref<void>` is authored under `device_buffer_arrays`. `binding` is the
|
||||
literal AIR/Metal base buffer index, `length` is the address-table extent, and each sorted sparse
|
||||
element owns ordinary input/output literal bytes; undeclared slots are null. Metal flattens the
|
||||
elements onto consecutive native buffer indices. Vulkan binds an address-table buffer at the base,
|
||||
allocates every element separately with device-address support, and writes their addresses into the
|
||||
matching slots. `device_buffer_array_element` output selection observes one writable element.
|
||||
|
||||
Every function table declares `size` separately from `entries`. The size is the native table
|
||||
capacity; omitted indices are authored null slots, so `entries: []` honestly represents an all-null
|
||||
table without inventing a linked function. Entry indices must be unique, sorted, and smaller than
|
||||
|
||||
@@ -45,6 +45,7 @@ echo "# running rspirv-autogen..."
|
||||
|
||||
echo "# adapting outputs into metal2vulkan..."
|
||||
python3 - "$CACHE_DIR/rspirv" "$CRATE_DIR" "$HEADERS_REF" <<'PY'
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
@@ -137,6 +138,139 @@ gram = gram.replace(
|
||||
"pub static INSTRUCTION_TABLE: InstructionTable =",
|
||||
)
|
||||
write_out("src/spirv_binary/grammar_generated.rs", gram)
|
||||
|
||||
core_grammar = json.loads(
|
||||
(
|
||||
r
|
||||
/ "autogen/external/SPIRV-Headers/include/spirv/unified1/spirv.core.grammar.json"
|
||||
).read_text()
|
||||
)
|
||||
enumerant_requirement_groups = []
|
||||
operand_arms = []
|
||||
for kind in core_grammar["operand_kinds"]:
|
||||
category = kind.get("category")
|
||||
if category not in ("BitEnum", "ValueEnum"):
|
||||
continue
|
||||
kind_name = kind["kind"]
|
||||
value = "value.bits()" if category == "BitEnum" else "*value as u32"
|
||||
kind_requirements = []
|
||||
seen_values = set()
|
||||
for enumerant in kind["enumerants"]:
|
||||
raw_value = enumerant["value"]
|
||||
numeric_value = (
|
||||
int(raw_value, 0) if isinstance(raw_value, str) else raw_value
|
||||
)
|
||||
if numeric_value in seen_values:
|
||||
continue
|
||||
seen_values.add(numeric_value)
|
||||
capabilities = enumerant.get("capabilities", [])
|
||||
extensions = enumerant.get("extensions", [])
|
||||
version = enumerant.get("version")
|
||||
if not capabilities and not extensions and version in (None, "None", "1.0"):
|
||||
continue
|
||||
kind_requirements.append(
|
||||
(kind_name, numeric_value, capabilities, extensions, version)
|
||||
)
|
||||
group_index = len(enumerant_requirement_groups)
|
||||
enumerant_requirement_groups.append(kind_requirements)
|
||||
operand_arms.append(
|
||||
f" Operand::{kind_name}(value) => EnumerantRequirements::new("
|
||||
f"ENUMERANT_REQUIREMENTS_{group_index}, {value}, "
|
||||
f"{str(category == 'BitEnum').lower()}),"
|
||||
)
|
||||
|
||||
requirements = [
|
||||
"#[derive(Clone, Copy, Debug)]",
|
||||
"pub(crate) struct EnumerantRequirement {",
|
||||
" pub(super) value: u32,",
|
||||
" pub(crate) capabilities: &'static [spirv::Capability],",
|
||||
" pub(crate) extensions: &'static [&'static str],",
|
||||
" pub(crate) min_core_version: Option<(u8, u8)>,",
|
||||
"}",
|
||||
"",
|
||||
"pub(super) struct EnumerantRequirements {",
|
||||
" remaining: &'static [EnumerantRequirement],",
|
||||
" value: u32,",
|
||||
" bit_enum: bool,",
|
||||
"}",
|
||||
"",
|
||||
"impl EnumerantRequirements {",
|
||||
" fn new(",
|
||||
" remaining: &'static [EnumerantRequirement],",
|
||||
" value: u32,",
|
||||
" bit_enum: bool,",
|
||||
" ) -> Self {",
|
||||
" Self { remaining, value, bit_enum }",
|
||||
" }",
|
||||
"}",
|
||||
"",
|
||||
"impl Iterator for EnumerantRequirements {",
|
||||
" type Item = &'static EnumerantRequirement;",
|
||||
"",
|
||||
" fn next(&mut self) -> Option<Self::Item> {",
|
||||
" while let Some((requirement, remaining)) = self.remaining.split_first() {",
|
||||
" self.remaining = remaining;",
|
||||
" let matches = if self.bit_enum {",
|
||||
" if requirement.value == 0 {",
|
||||
" self.value == 0",
|
||||
" } else {",
|
||||
" self.value & requirement.value == requirement.value",
|
||||
" }",
|
||||
" } else {",
|
||||
" self.value == requirement.value",
|
||||
" };",
|
||||
" if matches {",
|
||||
" return Some(requirement);",
|
||||
" }",
|
||||
" }",
|
||||
" None",
|
||||
" }",
|
||||
"}",
|
||||
"",
|
||||
]
|
||||
for group_index, group in enumerate(enumerant_requirement_groups):
|
||||
requirements.append(
|
||||
f"static ENUMERANT_REQUIREMENTS_{group_index}: &[EnumerantRequirement] = &["
|
||||
)
|
||||
for kind, value, capabilities, extensions, version in group:
|
||||
caps = ", ".join(f"spirv::Capability::{capability}" for capability in capabilities)
|
||||
exts = ", ".join(f'\"{extension}\"' for extension in extensions)
|
||||
core_version = (
|
||||
f"Some(({version[0]}, {version[2]}))"
|
||||
if version not in (None, "None")
|
||||
else "None"
|
||||
)
|
||||
requirements.extend(
|
||||
[
|
||||
" EnumerantRequirement {",
|
||||
f" value: {value},",
|
||||
f" capabilities: &[{caps}],",
|
||||
f" extensions: &[{exts}],",
|
||||
f" min_core_version: {core_version},",
|
||||
" },",
|
||||
]
|
||||
)
|
||||
requirements.extend([
|
||||
"];",
|
||||
"",
|
||||
])
|
||||
requirements.extend(
|
||||
[
|
||||
"pub(super) fn operand_declaration_requirements_generated(",
|
||||
" operand: &Operand,",
|
||||
") -> EnumerantRequirements {",
|
||||
" match operand {",
|
||||
*operand_arms,
|
||||
" _ => EnumerantRequirements::new(&[], 0, false),",
|
||||
" }",
|
||||
"}",
|
||||
"",
|
||||
]
|
||||
)
|
||||
write_out(
|
||||
"src/spirv_binary/enumerant_requirements_generated.rs",
|
||||
"\n".join(requirements),
|
||||
)
|
||||
print("done")
|
||||
PY
|
||||
|
||||
|
||||
+166
-226
@@ -6,7 +6,7 @@
|
||||
//! same inventory, so a newly harvested `air.*` family cannot disappear behind an unrelated clean
|
||||
//! authored-resource audit.
|
||||
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// Where the product intentionally handles an AIR intrinsic family.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
@@ -37,6 +37,52 @@ pub(crate) struct Matrix16Intrinsic {
|
||||
pub integer: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub(crate) struct Matrix8Intrinsic {
|
||||
pub result: Matrix16Element,
|
||||
pub lhs: Matrix16Element,
|
||||
pub rhs: Matrix16Element,
|
||||
pub accumulator: Matrix16Element,
|
||||
}
|
||||
|
||||
/// Parse the complete stable 8x8 matrix multiply-accumulate ABI grammar.
|
||||
pub(crate) fn matrix8_intrinsic(name: &str) -> Option<Matrix8Intrinsic> {
|
||||
let fields: Vec<_> = name.split('.').collect();
|
||||
if fields.len() != 6
|
||||
|| fields[0] != "air"
|
||||
|| fields[1] != "simdgroup_matrix_8x8_multiply_accumulate"
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let result = matrix8_result_element(fields[2])?;
|
||||
Some(Matrix8Intrinsic {
|
||||
result,
|
||||
lhs: matrix8_float_element(fields[3])?,
|
||||
rhs: matrix8_float_element(fields[4])?,
|
||||
accumulator: matrix8_float_element(fields[5])?,
|
||||
})
|
||||
}
|
||||
|
||||
fn matrix8_result_element(token: &str) -> Option<Matrix16Element> {
|
||||
Some(match token {
|
||||
"v64f32" => Matrix16Element::F32,
|
||||
"v64f16" => Matrix16Element::F16,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
fn matrix8_float_element(token: &str) -> Option<Matrix16Element> {
|
||||
Some(match token {
|
||||
"v64f32" => Matrix16Element::F32,
|
||||
"v64f16" => Matrix16Element::F16,
|
||||
"v64bf16" => Matrix16Element::Bf16,
|
||||
"v64f8e4m3" => Matrix16Element::F8E4M3,
|
||||
"v64f8e4m3fn" => Matrix16Element::F8E4M3Fn,
|
||||
"v64f8e5m2" => Matrix16Element::F8E5M2,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Parse the complete stable 16x16x16 matrix ABI grammar shared by inventory and lowering.
|
||||
pub(crate) fn matrix16_intrinsic(name: &str) -> Option<Matrix16Intrinsic> {
|
||||
let fields: Vec<_> = name.split('.').collect();
|
||||
@@ -107,129 +153,6 @@ pub fn air_call_counts(ll: &str) -> BTreeMap<String, usize> {
|
||||
calls
|
||||
}
|
||||
|
||||
/// Whether the selected entry's direct source call graph reaches one of the exact AIR ABI symbols.
|
||||
///
|
||||
/// This intentionally parses only definition boundaries and direct callee symbols. It is the
|
||||
/// bounded pre-emission dual of the typed emitter graph: ordinary dead helpers are excluded, while
|
||||
/// module static initializers are roots because the emitter injects them into the entry. Indirect
|
||||
/// calls remain unsupported elsewhere and cannot silently prove a barrier-free graph here.
|
||||
pub(crate) fn entry_reaches_air_call(ll: &str, entry_name: Option<&str>, targets: &[&str]) -> bool {
|
||||
// Most kernels have no barrier symbol at all. Keep their preflight allocation-free: besides
|
||||
// avoiding needless work, this matters to the worker's peak-RSS contract for very large IR.
|
||||
// A textual hit is only a reason to build the exact graph below, never evidence by itself.
|
||||
if !targets
|
||||
.iter()
|
||||
.any(|target| llvm_global_symbol_spelling_may_occur(ll, target))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct FunctionCalls {
|
||||
callees: Vec<String>,
|
||||
reaches_target_directly: bool,
|
||||
}
|
||||
|
||||
let mut functions = HashMap::<String, FunctionCalls>::new();
|
||||
let mut current = None::<(String, FunctionCalls)>;
|
||||
let mut first_function = None;
|
||||
for line in ll.lines() {
|
||||
let trimmed = strip_llvm_comment(line).trim();
|
||||
if current.is_none() && trimmed.starts_with("define ") {
|
||||
let Some(name) = global_symbol_after_at(trimmed) else {
|
||||
continue;
|
||||
};
|
||||
first_function.get_or_insert_with(|| name.clone());
|
||||
current = Some((name, FunctionCalls::default()));
|
||||
continue;
|
||||
}
|
||||
let Some((_, calls)) = current.as_mut() else {
|
||||
continue;
|
||||
};
|
||||
if trimmed == "}" {
|
||||
let (name, calls) = current.take().expect("current function");
|
||||
functions.insert(name, calls);
|
||||
continue;
|
||||
}
|
||||
for callee in direct_callees(trimmed) {
|
||||
if targets.contains(&callee.as_str()) {
|
||||
calls.reaches_target_directly = true;
|
||||
}
|
||||
calls.callees.push(callee);
|
||||
}
|
||||
}
|
||||
|
||||
let Some(entry_name) = entry_name.map(str::to_string).or(first_function) else {
|
||||
return false;
|
||||
};
|
||||
let mut pending = vec![entry_name.clone()];
|
||||
let mut reachable = HashSet::from([entry_name]);
|
||||
for name in functions.keys() {
|
||||
if name.starts_with("_GLOBAL__sub_I") && reachable.insert(name.clone()) {
|
||||
pending.push(name.clone());
|
||||
}
|
||||
}
|
||||
while let Some(name) = pending.pop() {
|
||||
let Some(calls) = functions.get(&name) else {
|
||||
continue;
|
||||
};
|
||||
if calls.reaches_target_directly {
|
||||
return true;
|
||||
}
|
||||
for callee in &calls.callees {
|
||||
if functions.contains_key(callee) && reachable.insert(callee.clone()) {
|
||||
pending.push(callee.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Allocation-free prefilter for an LLVM global symbol in plain or quoted/hex-escaped spelling.
|
||||
/// False positives are harmless because the exact function graph remains authoritative; false
|
||||
/// negatives would skip that graph and are therefore forbidden.
|
||||
fn llvm_global_symbol_spelling_may_occur(ll: &str, target: &str) -> bool {
|
||||
if ll.contains(target) {
|
||||
return true;
|
||||
}
|
||||
ll.match_indices("@\"")
|
||||
.any(|(offset, _)| quoted_symbol_matches(&ll[offset + 2..], target.as_bytes()))
|
||||
}
|
||||
|
||||
fn quoted_symbol_matches(mut quoted: &str, target: &[u8]) -> bool {
|
||||
for expected in target {
|
||||
let bytes = quoted.as_bytes();
|
||||
let Some(&first) = bytes.first() else {
|
||||
return false;
|
||||
};
|
||||
let (actual, consumed) = if first == b'\\' {
|
||||
let (Some(&hi), Some(&lo)) = (bytes.get(1), bytes.get(2)) else {
|
||||
return false;
|
||||
};
|
||||
let (Some(hi), Some(lo)) = (hex_nibble(hi), hex_nibble(lo)) else {
|
||||
return false;
|
||||
};
|
||||
((hi << 4) | lo, 3)
|
||||
} else {
|
||||
(first, 1)
|
||||
};
|
||||
if actual != *expected {
|
||||
return false;
|
||||
}
|
||||
quoted = "ed[consumed..];
|
||||
}
|
||||
quoted.starts_with('"')
|
||||
}
|
||||
|
||||
const fn hex_nibble(byte: u8) -> Option<u8> {
|
||||
match byte {
|
||||
b'0'..=b'9' => Some(byte - b'0'),
|
||||
b'a'..=b'f' => Some(byte - b'a' + 10),
|
||||
b'A'..=b'F' => Some(byte - b'A' + 10),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn direct_callees(line: &str) -> Vec<String> {
|
||||
if ![
|
||||
"call ", "call\t", "invoke ", "invoke\t", "callbr ", "callbr\t",
|
||||
@@ -409,6 +332,43 @@ fn any_prefix(name: &str, prefixes: &[&str]) -> bool {
|
||||
prefixes.iter().any(|prefix| name.starts_with(prefix))
|
||||
}
|
||||
|
||||
/// Stable AIR ABI families whose operands or results are opaque Metal image handles. These values
|
||||
/// cannot be represented as generic LLVM pointer state without losing the image descriptor identity
|
||||
/// required by SPIR-V image operations.
|
||||
pub(crate) fn air_image_intrinsic(name: &str) -> bool {
|
||||
matches!(
|
||||
name,
|
||||
"air.calculate_unclamped_lod_texture_2d" | "air.calculate_clamped_lod_texture_2d"
|
||||
) || any_prefix(
|
||||
name,
|
||||
&[
|
||||
"air.fence_texture",
|
||||
"air.sample_texture",
|
||||
"air.sample_depth",
|
||||
"air.sample_compare_depth",
|
||||
"air.gather_texture",
|
||||
"air.gather_depth",
|
||||
"air.read_texture",
|
||||
"air.read_depth",
|
||||
"air.write_texture",
|
||||
"air.atomic_fetch_max_explicit_texture_",
|
||||
"air.write_imageblock_slice_to_texture",
|
||||
"air.get_width_texture",
|
||||
"air.get_height_texture",
|
||||
"air.get_depth_texture",
|
||||
"air.get_array_size_texture",
|
||||
"air.get_width_depth",
|
||||
"air.get_height_depth",
|
||||
"air.get_depth_depth",
|
||||
"air.get_num_mip_levels_texture",
|
||||
"air.get_num_mip_levels_depth",
|
||||
"air.get_num_samples_texture",
|
||||
"air.is_null_texture",
|
||||
"air.get_null_texture",
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn is_command_encoder_helper(name: &str) -> bool {
|
||||
matches!(
|
||||
name,
|
||||
@@ -445,6 +405,10 @@ pub fn air_intrinsic_disposition(name: &str) -> Option<AirIntrinsicDisposition>
|
||||
return Some(LoweredOrStaticLinkage);
|
||||
}
|
||||
|
||||
if name == "air.get_descriptor_size_tensor" {
|
||||
return Some(Lowered);
|
||||
}
|
||||
|
||||
if any_prefix(
|
||||
name,
|
||||
&[
|
||||
@@ -458,9 +422,7 @@ pub fn air_intrinsic_disposition(name: &str) -> Option<AirIntrinsicDisposition>
|
||||
| "air.get_function_pointer_visible_function_table"
|
||||
| "air.is_null_visible_function_table"
|
||||
// Inline tensor descriptors are opaque Apple ABI objects consumed by externally-defined
|
||||
// tensor-ops helpers. They must be supplied in the same exact authored linkage unit;
|
||||
// lowering only these calls would invent a layout the linked consumer does not share.
|
||||
| "air.get_descriptor_size_tensor"
|
||||
// tensor-ops helpers. They must be supplied in the same exact authored linkage unit.
|
||||
| "air.get_extent_private_tensor.i32"
|
||||
| "air.init_strided_private_tensor.i32.global"
|
||||
| "air.init_strided_private_tensor.i32.local"
|
||||
@@ -522,61 +484,41 @@ pub fn air_intrinsic_disposition(name: &str) -> Option<AirIntrinsicDisposition>
|
||||
| "air.get_instance_count_instance_acceleration_structure"
|
||||
| "air.get_primitive_acceleration_structure_instance_acceleration_structure"
|
||||
| "air.get_data_pointer_instance_acceleration_structure"
|
||||
| "air.calculate_unclamped_lod_texture_2d"
|
||||
| "air.calculate_clamped_lod_texture_2d"
|
||||
| "air.imageblock_data"
|
||||
| "air.rhadd.u.i16"
|
||||
) {
|
||||
return Some(Lowered);
|
||||
}
|
||||
|
||||
if any_prefix(
|
||||
name,
|
||||
&[
|
||||
"air.load.device_coherent.",
|
||||
"air.load.system_coherent.",
|
||||
"air.store.device_coherent.",
|
||||
"air.store.system_coherent.",
|
||||
"air.fence_texture",
|
||||
"air.sample_texture",
|
||||
"air.sample_depth",
|
||||
"air.sample_compare_depth",
|
||||
"air.gather_texture",
|
||||
"air.gather_depth",
|
||||
"air.read_texture",
|
||||
"air.read_depth",
|
||||
"air.write_texture",
|
||||
"air.atomic_fetch_max_explicit_texture_",
|
||||
"air.write_imageblock_slice_to_texture",
|
||||
"air.load.implicit_imageblock.",
|
||||
"air.store.implicit_imageblock.",
|
||||
"air.discard_fragment",
|
||||
"air.get_width_texture",
|
||||
"air.get_height_texture",
|
||||
"air.get_depth_texture",
|
||||
"air.get_array_size_texture",
|
||||
"air.get_width_depth",
|
||||
"air.get_height_depth",
|
||||
"air.get_depth_depth",
|
||||
"air.get_num_mip_levels_texture",
|
||||
"air.get_num_mip_levels_depth",
|
||||
"air.get_num_samples_texture",
|
||||
"air.is_null_texture",
|
||||
"air.get_null_texture",
|
||||
"air.map_screen_to_physical_coordinates.",
|
||||
"air.map_physical_to_screen_coordinates.",
|
||||
"air.simdgroup_matrix_8x8_load.",
|
||||
"air.simdgroup_matrix_8x8_store.",
|
||||
"air.simdgroup_matrix_8x8_init_diag.",
|
||||
"air.simdgroup_matrix_8x8_multiply_accumulate.",
|
||||
"air.simdgroup_async_copy_2d.",
|
||||
"air.get_null_simdgroup_event",
|
||||
"air.is_null_simdgroup_event",
|
||||
"air.wait_simdgroup_events",
|
||||
"air.function_constant_predicate",
|
||||
"air.normalize_function_constant_predicate.",
|
||||
],
|
||||
) {
|
||||
if air_image_intrinsic(name)
|
||||
|| any_prefix(
|
||||
name,
|
||||
&[
|
||||
"air.load.device_coherent.",
|
||||
"air.load.system_coherent.",
|
||||
"air.store.device_coherent.",
|
||||
"air.store.system_coherent.",
|
||||
"air.load.implicit_imageblock.",
|
||||
"air.store.implicit_imageblock.",
|
||||
"air.discard_fragment",
|
||||
"air.map_screen_to_physical_coordinates.",
|
||||
"air.map_physical_to_screen_coordinates.",
|
||||
"air.simdgroup_matrix_8x8_load.",
|
||||
"air.simdgroup_matrix_8x8_store.",
|
||||
"air.simdgroup_matrix_8x8_init_diag.",
|
||||
"air.simdgroup_async_copy_2d.",
|
||||
"air.get_null_simdgroup_event",
|
||||
"air.is_null_simdgroup_event",
|
||||
"air.wait_simdgroup_events",
|
||||
"air.function_constant_predicate",
|
||||
"air.normalize_function_constant_predicate.",
|
||||
],
|
||||
)
|
||||
{
|
||||
return Some(Lowered);
|
||||
}
|
||||
|
||||
if matrix8_intrinsic(name).is_some() {
|
||||
return Some(Lowered);
|
||||
}
|
||||
|
||||
@@ -740,6 +682,10 @@ mod tests {
|
||||
);
|
||||
assert_eq!(air_intrinsic_disposition("air.anything.v4i1"), None);
|
||||
assert_eq!(air_intrinsic_disposition("air.tensor_future.i32"), None);
|
||||
assert_eq!(
|
||||
air_intrinsic_disposition("air.get_descriptor_size_tensor"),
|
||||
Some(AirIntrinsicDisposition::Lowered)
|
||||
);
|
||||
assert_eq!(
|
||||
air_intrinsic_disposition("air.init_strided_private_tensor.i32.local"),
|
||||
Some(AirIntrinsicDisposition::StaticLinkage)
|
||||
@@ -751,6 +697,17 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_handle_families_are_classified_by_the_shared_abi_predicate() {
|
||||
assert!(air_image_intrinsic("air.write_texture_2d.i16.v4f32"));
|
||||
assert!(air_image_intrinsic("air.sample_compare_depth_2d.f32"));
|
||||
assert!(air_image_intrinsic(
|
||||
"air.calculate_unclamped_lod_texture_2d"
|
||||
));
|
||||
assert!(!air_image_intrinsic("air.texture_future"));
|
||||
assert!(!air_image_intrinsic("air.atomic.global.add.u.i32"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linkage_is_distinct_from_direct_lowering() {
|
||||
assert_eq!(
|
||||
@@ -795,6 +752,39 @@ mod tests {
|
||||
.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matrix8_recognition_requires_the_complete_known_abi_shape() {
|
||||
let bfloat = "air.simdgroup_matrix_8x8_multiply_accumulate.v64f32.v64bf16.v64bf16.v64f32";
|
||||
assert_eq!(
|
||||
matrix8_intrinsic(bfloat),
|
||||
Some(Matrix8Intrinsic {
|
||||
result: Matrix16Element::F32,
|
||||
lhs: Matrix16Element::Bf16,
|
||||
rhs: Matrix16Element::Bf16,
|
||||
accumulator: Matrix16Element::F32,
|
||||
})
|
||||
);
|
||||
let float8 =
|
||||
"air.simdgroup_matrix_8x8_multiply_accumulate.v64f32.v64f8e5m2.v64f8e5m2.v64f32";
|
||||
assert_eq!(
|
||||
matrix8_intrinsic(float8),
|
||||
Some(Matrix8Intrinsic {
|
||||
result: Matrix16Element::F32,
|
||||
lhs: Matrix16Element::F8E5M2,
|
||||
rhs: Matrix16Element::F8E5M2,
|
||||
accumulator: Matrix16Element::F32,
|
||||
})
|
||||
);
|
||||
assert!(matrix8_intrinsic(
|
||||
"air.simdgroup_matrix_8x8_multiply_accumulate.v64f32.v64future.v64f16.v64f32"
|
||||
)
|
||||
.is_none());
|
||||
assert!(matrix8_intrinsic(
|
||||
"air.simdgroup_matrix_8x8_multiply_accumulate.v64future.v64f16.v64f16.v64f32"
|
||||
)
|
||||
.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn call_inventory_ignores_non_callees_and_counts_all_call_forms() {
|
||||
let ll = "define void @main() {\nentry:\n %a = call i32 @air.abs.s.i32(i32 -1)\n %b = tail call i32 @air.future_tensor.i32(i32 1)\n %c = musttail\tcall i32 @air.future_tensor.i32(i32 2)\n %d = invoke i32 @\"air.quoted_future.i32\"(i32 3) to label %ok unwind label %err\n callbr void @air.branch_future() to label %ok [label %err]\n call void @ordinary(ptr @air.declaration_only.i32) ; @air.comment_only\n ret void\n}\ndefine void @compact() { %x = call i32 @air.compact_future(i32 0) ret void }\ndeclare i32 @air.declaration_only.i32(i32)";
|
||||
@@ -818,54 +808,4 @@ mod tests {
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entry_call_graph_excludes_dead_helpers_and_includes_static_initializers() {
|
||||
let ll = r#"
|
||||
define void @entry() {
|
||||
call void @live_helper()
|
||||
ret void
|
||||
}
|
||||
define internal void @live_helper() {
|
||||
ret void
|
||||
}
|
||||
define internal void @dead_helper() {
|
||||
call void @air.wg.barrier(i32 0, i32 1)
|
||||
ret void
|
||||
}
|
||||
define internal void @"_GLOBAL__sub_I.quoted"() {
|
||||
call void @"air.simdgroup.barrier"(i32 0, i32 1)
|
||||
ret void
|
||||
}
|
||||
"#;
|
||||
assert!(!entry_reaches_air_call(
|
||||
ll,
|
||||
Some("entry"),
|
||||
&["air.wg.barrier"]
|
||||
));
|
||||
assert!(entry_reaches_air_call(
|
||||
ll,
|
||||
Some("entry"),
|
||||
&["air.simdgroup.barrier"]
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entry_call_graph_follows_reachable_quoted_helpers() {
|
||||
let ll = r#"
|
||||
define void @entry() {
|
||||
call void @"helper\2Ebarrier"()
|
||||
ret void
|
||||
}
|
||||
define internal void @"helper.barrier"() {
|
||||
call void @"air\2Ewg\2Ebarrier"(i32 0, i32 1)
|
||||
ret void
|
||||
}
|
||||
"#;
|
||||
assert!(entry_reaches_air_call(
|
||||
ll,
|
||||
Some("entry"),
|
||||
&["air.wg.barrier"]
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
//! Pre-validation construction alternatives selected from owned CFG and type facts.
|
||||
//!
|
||||
//! The primary representation is finished and structurally checked while it remains an owned
|
||||
//! module. When those checks prove that representation cannot satisfy the source contract, this
|
||||
//! context constructs the raw-buffer or raw-CFG representation. Only the single finished result is
|
||||
//! serialized and validated; validator output never selects another representation.
|
||||
|
||||
use crate::{
|
||||
finish_module, meta, passes, stage_buffer_layouts, tools, FinishConstruction,
|
||||
FinishFailureKind, FinishedModule,
|
||||
};
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
|
||||
/// Shared source, metadata, and option context for pre-validation representation construction.
|
||||
pub(crate) struct ConstructionCtx<'a> {
|
||||
pub(crate) san_ll: &'a str,
|
||||
pub(crate) stage: passes::Stage,
|
||||
pub(crate) frag: Option<&'a meta::FragMeta>,
|
||||
pub(crate) vert: Option<&'a meta::VertMeta>,
|
||||
pub(crate) kern: Option<&'a meta::KernMeta>,
|
||||
pub(crate) entry_name: Option<&'a str>,
|
||||
pub(crate) tmp: &'a Path,
|
||||
pub(crate) options: passes::TransformOptions,
|
||||
pub(crate) air_data_layout: Option<crate::layout::AirDataLayout>,
|
||||
ordinary_plan_rejections: std::cell::RefCell<std::collections::HashSet<String>>,
|
||||
ownership_plan_rejections: std::cell::RefCell<std::collections::HashSet<String>>,
|
||||
post_lowering_cfg_construction: std::cell::Cell<bool>,
|
||||
primary_cfg_construction_failure: std::cell::Cell<bool>,
|
||||
primary_raw_buffer_construction_failure: std::cell::Cell<bool>,
|
||||
}
|
||||
|
||||
impl<'a> ConstructionCtx<'a> {
|
||||
fn buffer_layouts(&self) -> Option<&'a HashMap<u32, meta::AirType>> {
|
||||
stage_buffer_layouts(self.stage, self.frag, self.vert, self.kern)
|
||||
}
|
||||
|
||||
/// Build the construction context shared by primary and structurally selected representations.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn new(
|
||||
san_ll: &'a str,
|
||||
stage: passes::Stage,
|
||||
frag: Option<&'a meta::FragMeta>,
|
||||
vert: Option<&'a meta::VertMeta>,
|
||||
kern: Option<&'a meta::KernMeta>,
|
||||
entry_name: Option<&'a str>,
|
||||
tmp: &'a Path,
|
||||
options: passes::TransformOptions,
|
||||
air_data_layout: Option<crate::layout::AirDataLayout>,
|
||||
) -> Self {
|
||||
ConstructionCtx {
|
||||
san_ll,
|
||||
stage,
|
||||
frag,
|
||||
vert,
|
||||
kern,
|
||||
entry_name,
|
||||
tmp,
|
||||
options,
|
||||
air_data_layout,
|
||||
ordinary_plan_rejections: std::cell::RefCell::new(Default::default()),
|
||||
ownership_plan_rejections: std::cell::RefCell::new(Default::default()),
|
||||
post_lowering_cfg_construction: std::cell::Cell::new(false),
|
||||
primary_cfg_construction_failure: std::cell::Cell::new(false),
|
||||
primary_raw_buffer_construction_failure: std::cell::Cell::new(false),
|
||||
}
|
||||
}
|
||||
|
||||
/// Run the shared owned-module construction tail over a freshly emitted representation.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn finish(
|
||||
&self,
|
||||
emitted: crate::emit_sidecar::EmittedSpirv,
|
||||
) -> Result<Vec<u8>, String> {
|
||||
self.finish_carrier(emitted).map(|finished| finished.bytes)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn finish_carrier(
|
||||
&self,
|
||||
emitted: crate::emit_sidecar::EmittedSpirv,
|
||||
) -> Result<FinishedModule, String> {
|
||||
self.finish_carrier_with_construction(emitted, FinishConstruction::Plain)
|
||||
}
|
||||
|
||||
fn finish_carrier_with_construction(
|
||||
&self,
|
||||
emitted: crate::emit_sidecar::EmittedSpirv,
|
||||
construction: FinishConstruction,
|
||||
) -> Result<FinishedModule, String> {
|
||||
finish_module(
|
||||
emitted,
|
||||
self.stage,
|
||||
self.frag,
|
||||
self.vert,
|
||||
self.kern,
|
||||
self.entry_name,
|
||||
self.air_data_layout.as_ref(),
|
||||
self.options,
|
||||
construction,
|
||||
)
|
||||
.map_err(|failure| failure.error)
|
||||
}
|
||||
|
||||
pub(crate) fn finish_primary_carrier(
|
||||
&self,
|
||||
emitted: crate::emit_sidecar::EmittedSpirv,
|
||||
) -> Result<FinishedModule, String> {
|
||||
finish_module(
|
||||
emitted,
|
||||
self.stage,
|
||||
self.frag,
|
||||
self.vert,
|
||||
self.kern,
|
||||
self.entry_name,
|
||||
self.air_data_layout.as_ref(),
|
||||
self.options,
|
||||
FinishConstruction::Primary,
|
||||
)
|
||||
.map_err(|failure| {
|
||||
match failure.kind {
|
||||
FinishFailureKind::CfgConstruction => {
|
||||
self.primary_cfg_construction_failure.set(true);
|
||||
}
|
||||
FinishFailureKind::RawBufferConstruction => {
|
||||
self.primary_raw_buffer_construction_failure.set(true);
|
||||
}
|
||||
FinishFailureKind::Other => {}
|
||||
}
|
||||
failure.error
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn remember_ordinary_plan_rejections(
|
||||
&self,
|
||||
emitted: &crate::emit_sidecar::EmittedSpirv,
|
||||
) {
|
||||
self.ordinary_plan_rejections.borrow_mut().extend(
|
||||
emitted
|
||||
.sidecar
|
||||
.ordinary_plan_rejected_functions
|
||||
.iter()
|
||||
.cloned(),
|
||||
);
|
||||
self.ownership_plan_rejections.borrow_mut().extend(
|
||||
emitted
|
||||
.sidecar
|
||||
.ownership_plan_rejected_functions
|
||||
.iter()
|
||||
.cloned(),
|
||||
);
|
||||
self.post_lowering_cfg_construction.set(
|
||||
self.post_lowering_cfg_construction.get()
|
||||
|| !emitted
|
||||
.sidecar
|
||||
.post_lowering_cfg_construction_functions
|
||||
.is_empty(),
|
||||
);
|
||||
}
|
||||
|
||||
pub(crate) fn remember_ordinary_plan_rejection_set(
|
||||
&self,
|
||||
rejected: &std::collections::HashSet<String>,
|
||||
) {
|
||||
self.ordinary_plan_rejections
|
||||
.borrow_mut()
|
||||
.extend(rejected.iter().cloned());
|
||||
}
|
||||
|
||||
pub(crate) fn has_cfg_plan_rejections(&self) -> bool {
|
||||
!self.ordinary_plan_rejections.borrow().is_empty()
|
||||
|| !self.ownership_plan_rejections.borrow().is_empty()
|
||||
|| self.post_lowering_cfg_construction.get()
|
||||
|| self.primary_cfg_construction_failure.get()
|
||||
}
|
||||
|
||||
pub(crate) fn needs_raw_construction(&self) -> bool {
|
||||
self.has_cfg_plan_rejections() || self.primary_raw_buffer_construction_failure.get()
|
||||
}
|
||||
|
||||
/// Build the selected raw-buffer representation. CFG ownership failures additionally select
|
||||
/// the bounded relooper feed; a pure buffer-type failure keeps the ordinary CFG representation.
|
||||
pub(crate) fn construct_raw(&self) -> Result<FinishedModule, String> {
|
||||
if self.has_cfg_plan_rejections() {
|
||||
return self.construct_raw_relooper();
|
||||
}
|
||||
let ordinary_rejections = self.ordinary_plan_rejections.borrow();
|
||||
let ownership_rejections = self.ownership_plan_rejections.borrow();
|
||||
let mut emitted = tools::emit_vulkan_spirv_all_buffers_raw_with_sidecar(
|
||||
self.san_ll,
|
||||
self.tmp,
|
||||
self.kern,
|
||||
self.entry_name,
|
||||
self.buffer_layouts(),
|
||||
&ordinary_rejections,
|
||||
&ownership_rejections,
|
||||
)?;
|
||||
// The all-raw representation can still contain a source pointer phi/select spanning
|
||||
// distinct buffer descriptors even when its CFG needed no reconstruction. Tell final
|
||||
// interface construction up front to own that closure in the address domain.
|
||||
emitted.sidecar.construct_cross_binding_addresses = true;
|
||||
self.finish_carrier_with_construction(emitted, FinishConstruction::Primary)
|
||||
}
|
||||
|
||||
/// Build the raw-buffer CFG representation selected by a source ownership rejection. The raw
|
||||
/// feed remains an owned module through final CFG and address-domain construction, its owned
|
||||
/// checks, canonicalization, and its sole assembly. No intermediate representation is sealed,
|
||||
/// and no validator result selects a rewrite.
|
||||
pub(crate) fn construct_raw_relooper(&self) -> Result<FinishedModule, String> {
|
||||
let mut emitted = tools::emit_vulkan_spirv_all_buffers_raw_relooper_feed_with_sidecar(
|
||||
self.san_ll,
|
||||
self.tmp,
|
||||
self.kern,
|
||||
self.entry_name,
|
||||
self.buffer_layouts(),
|
||||
)?;
|
||||
emitted.sidecar.construct_cross_binding_addresses = true;
|
||||
self.finish_carrier_with_construction(emitted, FinishConstruction::RawRelooper)
|
||||
}
|
||||
|
||||
pub(crate) fn remember_ownership_plan_rejection_set(
|
||||
&self,
|
||||
rejected: &std::collections::HashSet<String>,
|
||||
) {
|
||||
self.ownership_plan_rejections
|
||||
.borrow_mut()
|
||||
.extend(rejected.iter().cloned());
|
||||
}
|
||||
}
|
||||
+133
-13
@@ -4,10 +4,27 @@
|
||||
//! every consumer runs before final id canonicalization.
|
||||
|
||||
use spirv::Word;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub(crate) struct EmitSidecar {
|
||||
/// The emitter intentionally modeled every device/constant buffer through the raw byte/word
|
||||
/// representation. Interface construction uses this typed fact to preserve that representation's
|
||||
/// established closure ordering rather than applying the default typed-buffer fallback early.
|
||||
pub(crate) all_device_buffers_raw: bool,
|
||||
/// Final interface construction must represent any remaining cross-binding StorageBuffer
|
||||
/// closure in the address domain. Both all-raw constructors set this before passes begin so the
|
||||
/// resource phase owns the complete descriptor-pointer graph.
|
||||
pub(crate) construct_cross_binding_addresses: bool,
|
||||
/// Functions whose exact source CFG was rejected by the ordinary ownership planner. Same-CFG
|
||||
/// representation retries reuse this immutable result before trying construct-tree ownership.
|
||||
pub(crate) ordinary_plan_rejected_functions: HashSet<String>,
|
||||
/// Functions whose exact source CFG was rejected by the complete source-ownership ladder.
|
||||
/// Same-CFG representation retries can proceed directly to the bounded fallback constructor.
|
||||
pub(crate) ownership_plan_rejected_functions: HashSet<String>,
|
||||
/// Surviving functions whose final owned instruction graph contains a conditional or switch
|
||||
/// header without an adjacent merge declaration after source ownership planning and lowering.
|
||||
pub(crate) post_lowering_cfg_construction_functions: HashSet<String>,
|
||||
/// Parsed source vector ABI rules, threaded through every retry candidate into final layout.
|
||||
pub(crate) air_data_layout: Option<crate::layout::AirDataLayout>,
|
||||
/// Emitted `OpTypeStruct` id -> exact AIR member offsets, including backend padding members.
|
||||
@@ -15,6 +32,10 @@ pub(crate) struct EmitSidecar {
|
||||
/// One outcome for every entry buffer carrying `air.struct_type_info`. This keeps an exact AIR
|
||||
/// layout that could not be associated with the emitted type graph from disappearing silently.
|
||||
pub(crate) air_struct_layout_mappings: Vec<AirStructLayoutMapping>,
|
||||
/// Entry buffer ordinals whose AIR aggregate layout replaced a non-aggregate source pointee.
|
||||
/// Their native raw-word access paths are flat element indices and must be routed through member
|
||||
/// 0 of the existing `{ RuntimeArray<uint> }` interface block.
|
||||
pub(crate) flat_raw_buffer_params: HashSet<u32>,
|
||||
pub(crate) buffer_address_words: Vec<BufferAddressWord>,
|
||||
/// Exact constant byte address of a GEP result relative to one buffer root. This preserves the
|
||||
/// source aggregate layout across the native-emitter → remodeled-interface seam, where an
|
||||
@@ -37,12 +58,23 @@ pub(crate) struct EmitSidecar {
|
||||
pub(crate) local_pointer_field_stores: Vec<LocalPointerFieldStore>,
|
||||
pub(crate) local_pointer_field_loads: Vec<LocalPointerFieldLoad>,
|
||||
pub(crate) local_pointer_dynamic_field_loads: Vec<LocalPointerDynamicFieldLoad>,
|
||||
/// Exact logical pointer carried by an integer payload slot in a by-value AIR aggregate. The
|
||||
/// 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>,
|
||||
}
|
||||
|
||||
#[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>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct AirStructLayoutMapping {
|
||||
pub(crate) param_index: u32,
|
||||
@@ -61,12 +93,6 @@ pub(crate) enum AirStructLayoutMappingStatus {
|
||||
NonIncreasingOffsets,
|
||||
}
|
||||
|
||||
impl AirStructLayoutMappingStatus {
|
||||
pub(crate) const fn is_mapped(self) -> bool {
|
||||
matches!(self, Self::MappedNatural | Self::MappedExplicit)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct BufferAddressWord {
|
||||
pub(crate) id: Word,
|
||||
@@ -128,7 +154,59 @@ pub(crate) struct LocalPointerDynamicFieldLoad {
|
||||
pub(crate) suffix: Vec<u32>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct AggregatePointerValue {
|
||||
pub(crate) aggregate: Word,
|
||||
pub(crate) source: Word,
|
||||
pub(crate) indices: Vec<u32>,
|
||||
}
|
||||
|
||||
impl EmitSidecar {
|
||||
/// Every SPIR-V id referenced by a typed fact crossing the emitter-to-passes seam.
|
||||
pub(crate) fn referenced_ids(&self) -> HashSet<Word> {
|
||||
let mut ids = self
|
||||
.buffer_address_words
|
||||
.iter()
|
||||
.map(|fact| fact.id)
|
||||
.collect::<HashSet<_>>();
|
||||
for fact in &self.buffer_access_offsets {
|
||||
ids.extend([fact.id, fact.root]);
|
||||
}
|
||||
for fact in &self.buffer_access_affine_offsets {
|
||||
ids.extend([fact.id, fact.root]);
|
||||
ids.extend(fact.terms.iter().map(|(index, _)| *index));
|
||||
}
|
||||
for fact in &self.buffer_pointer_field_loads {
|
||||
ids.extend([fact.id, fact.root]);
|
||||
}
|
||||
for fact in &self.buffer_pointer_dynamic_field_loads {
|
||||
ids.extend([fact.id, fact.root, fact.index]);
|
||||
}
|
||||
for fact in &self.local_pointer_field_stores {
|
||||
ids.extend([fact.id, fact.source, fact.root]);
|
||||
}
|
||||
for fact in &self.local_pointer_field_loads {
|
||||
ids.extend([fact.id, fact.root]);
|
||||
}
|
||||
for fact in &self.local_pointer_dynamic_field_loads {
|
||||
ids.extend([fact.id, fact.root, fact.index]);
|
||||
}
|
||||
for fact in &self.aggregate_pointer_values {
|
||||
ids.extend([fact.aggregate, fact.source]);
|
||||
}
|
||||
ids.extend(self.agx2_cluster_numbers.iter().copied());
|
||||
ids.extend(self.air_struct_offsets.keys().copied());
|
||||
ids.extend(
|
||||
self.air_struct_layout_mappings
|
||||
.iter()
|
||||
.filter_map(|mapping| mapping.struct_ty),
|
||||
);
|
||||
for (&root, &source_ty) in &self.buffer_root_source_types {
|
||||
ids.extend([root, source_ty]);
|
||||
}
|
||||
ids
|
||||
}
|
||||
|
||||
/// Apply a whole-module value-id substitution to every typed fact.
|
||||
///
|
||||
/// Typed helper inlining emits cloned bodies against opaque parameter ids, then replaces those
|
||||
@@ -177,6 +255,10 @@ impl EmitSidecar {
|
||||
replace(&mut fact.root);
|
||||
replace(&mut fact.index);
|
||||
}
|
||||
for fact in &mut self.aggregate_pointer_values {
|
||||
replace(&mut fact.aggregate);
|
||||
replace(&mut fact.source);
|
||||
}
|
||||
for id in &mut self.agx2_cluster_numbers {
|
||||
replace(id);
|
||||
}
|
||||
@@ -185,13 +267,15 @@ impl EmitSidecar {
|
||||
replace(struct_ty);
|
||||
}
|
||||
}
|
||||
self.air_struct_offsets = std::mem::take(&mut self.air_struct_offsets)
|
||||
.into_iter()
|
||||
.map(|(id, offsets)| (remap.get(&id).copied().unwrap_or(id), offsets))
|
||||
self.air_struct_offsets = self
|
||||
.air_struct_offsets
|
||||
.iter()
|
||||
.map(|(&id, offsets)| (remap.get(&id).copied().unwrap_or(id), offsets.clone()))
|
||||
.collect();
|
||||
self.buffer_root_source_types = std::mem::take(&mut self.buffer_root_source_types)
|
||||
.into_iter()
|
||||
.map(|(root, source_ty)| {
|
||||
self.buffer_root_source_types = self
|
||||
.buffer_root_source_types
|
||||
.iter()
|
||||
.map(|(&root, &source_ty)| {
|
||||
(
|
||||
remap.get(&root).copied().unwrap_or(root),
|
||||
remap.get(&source_ty).copied().unwrap_or(source_ty),
|
||||
@@ -298,6 +382,18 @@ impl EmitSidecar {
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
self.local_pointer_dynamic_field_loads.extend(clones);
|
||||
let clones = self
|
||||
.aggregate_pointer_values
|
||||
.iter()
|
||||
.filter_map(|fact| {
|
||||
Some(AggregatePointerValue {
|
||||
aggregate: remap.get(&fact.aggregate).copied()?,
|
||||
source: remap.get(&fact.source).copied().unwrap_or(fact.source),
|
||||
indices: fact.indices.clone(),
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
self.aggregate_pointer_values.extend(clones);
|
||||
let clones = self
|
||||
.agx2_cluster_numbers
|
||||
.iter()
|
||||
@@ -338,6 +434,9 @@ mod tests {
|
||||
#[test]
|
||||
fn inlining_clones_load_facts_and_remaps_store_sources() {
|
||||
let mut sidecar = EmitSidecar {
|
||||
ordinary_plan_rejected_functions: HashSet::new(),
|
||||
ownership_plan_rejected_functions: HashSet::new(),
|
||||
post_lowering_cfg_construction_functions: HashSet::new(),
|
||||
buffer_access_offsets: vec![BufferAccessOffset {
|
||||
id: 82,
|
||||
root: 92,
|
||||
@@ -496,6 +595,11 @@ mod tests {
|
||||
#[test]
|
||||
fn whole_module_substitution_remaps_every_sidecar_id_field() {
|
||||
let mut sidecar = EmitSidecar {
|
||||
all_device_buffers_raw: false,
|
||||
construct_cross_binding_addresses: false,
|
||||
ordinary_plan_rejected_functions: HashSet::new(),
|
||||
ownership_plan_rejected_functions: HashSet::new(),
|
||||
post_lowering_cfg_construction_functions: HashSet::new(),
|
||||
air_data_layout: None,
|
||||
air_struct_offsets: HashMap::from([(5, vec![0, 16])]),
|
||||
air_struct_layout_mappings: vec![AirStructLayoutMapping {
|
||||
@@ -503,6 +607,7 @@ mod tests {
|
||||
struct_ty: Some(5),
|
||||
status: AirStructLayoutMappingStatus::MappedNatural,
|
||||
}],
|
||||
flat_raw_buffer_params: HashSet::from([2]),
|
||||
buffer_address_words: vec![BufferAddressWord {
|
||||
id: 10,
|
||||
param_index: 2,
|
||||
@@ -549,6 +654,11 @@ mod tests {
|
||||
index: 42,
|
||||
suffix: vec![6],
|
||||
}],
|
||||
aggregate_pointer_values: vec![AggregatePointerValue {
|
||||
aggregate: 43,
|
||||
source: 44,
|
||||
indices: vec![1, 0],
|
||||
}],
|
||||
agx2_cluster_numbers: vec![50],
|
||||
};
|
||||
let remap = HashMap::from([
|
||||
@@ -573,11 +683,21 @@ mod tests {
|
||||
(40, 140),
|
||||
(41, 141),
|
||||
(42, 142),
|
||||
(43, 143),
|
||||
(44, 144),
|
||||
(5, 105),
|
||||
(50, 150),
|
||||
]);
|
||||
|
||||
sidecar.remap_ids(&remap);
|
||||
assert_eq!(
|
||||
sidecar.aggregate_pointer_values,
|
||||
vec![AggregatePointerValue {
|
||||
aggregate: 143,
|
||||
source: 144,
|
||||
indices: vec![1, 0],
|
||||
}]
|
||||
);
|
||||
assert_eq!(
|
||||
sidecar.buffer_root_source_types,
|
||||
HashMap::from([(118, 119)])
|
||||
|
||||
+4
-3
@@ -37,7 +37,7 @@ pub const REGISTRY: &[EnvVar] = &[
|
||||
EnvVar {
|
||||
name: "METAL2VULKAN_RELOOPER_MAX_BLOCKS",
|
||||
default: "1024",
|
||||
effect: "requested relooper block-count cap (hard maximum: 1024)",
|
||||
effect: "requested relooper cases per dispatch group (hard maximum: 1024)",
|
||||
},
|
||||
// paths
|
||||
EnvVar {
|
||||
@@ -200,8 +200,9 @@ pub fn val_par() -> usize {
|
||||
.unwrap_or(3)
|
||||
}
|
||||
|
||||
/// Requested relooper block-count cap. The native relooper applies its hard product safety maximum
|
||||
/// after reading this value, so the override can lower the cap but cannot raise it above 1024.
|
||||
/// Requested case count per relooper dispatch group. The native relooper applies its hard product
|
||||
/// safety maximum after reading this value, so the override can lower the group size but cannot
|
||||
/// raise it above 1024.
|
||||
pub fn relooper_max_blocks(fallback: usize) -> usize {
|
||||
std::env::var("METAL2VULKAN_RELOOPER_MAX_BLOCKS")
|
||||
.ok()
|
||||
|
||||
@@ -0,0 +1,304 @@
|
||||
//! AIR-level Metal function-constant specialization.
|
||||
//!
|
||||
//! Function constants can control resource presence and CFG shape before SPIR-V exists. Baking the
|
||||
//! exact authored values into the stable `air.fc_initializer` globals before metadata parsing and
|
||||
//! native emission lets the ordinary static-initializer analysis construct only the selected AIR
|
||||
//! program. This is the valid-by-construction path for values that cannot be restored after a
|
||||
//! default-valued branch or resource has already been removed.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
pub(crate) fn specialize_air_function_constants<'a>(
|
||||
air_ll: &'a str,
|
||||
values: &[(u32, Vec<u8>)],
|
||||
) -> Result<Cow<'a, str>, String> {
|
||||
if values.is_empty() {
|
||||
return Ok(Cow::Borrowed(air_ll));
|
||||
}
|
||||
|
||||
let mut requested = BTreeMap::<u32, &[u8]>::new();
|
||||
for (index, bytes) in values {
|
||||
if requested.insert(*index, bytes).is_some() {
|
||||
return Err(format!(
|
||||
"AIR function-constant specialization contains duplicate index {index}"
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
let constants = crate::meta::parse_function_constants(air_ll)
|
||||
.into_iter()
|
||||
.map(|constant| (constant.index, constant))
|
||||
.collect::<BTreeMap<_, _>>();
|
||||
let missing = requested
|
||||
.keys()
|
||||
.filter(|index| !constants.contains_key(index))
|
||||
.copied()
|
||||
.collect::<Vec<_>>();
|
||||
if !missing.is_empty() {
|
||||
return Err(format!(
|
||||
"AIR function-constant specialization found no air.fc_initializer for index(es) {missing:?}"
|
||||
));
|
||||
}
|
||||
|
||||
let literals = requested
|
||||
.iter()
|
||||
.map(|(index, bytes)| {
|
||||
let constant = &constants[index];
|
||||
llvm_typed_literal(&constant.type_name, &constant.abi_type_encoding, bytes)
|
||||
.map(|literal| (*index, (constant.type_name.as_str(), literal)))
|
||||
.map_err(|error| format!("function constant {index}: {error}"))
|
||||
})
|
||||
.collect::<Result<BTreeMap<_, _>, _>>()?;
|
||||
|
||||
let mut replaced = BTreeSet::new();
|
||||
let mut output = String::with_capacity(air_ll.len());
|
||||
for line in air_ll.split_inclusive('\n') {
|
||||
if line.trim_start().starts_with("declare ") {
|
||||
output.push_str(line);
|
||||
continue;
|
||||
}
|
||||
if line.contains("@air.is_function_constant_defined(") {
|
||||
let Some(index) = crate::fc_specialize::fc_init_index(line) else {
|
||||
return Err(
|
||||
"air.is_function_constant_defined has no MTL_FC_INIT operand".to_string(),
|
||||
);
|
||||
};
|
||||
if requested.contains_key(&index) {
|
||||
let (result, _) = line.split_once(" = ").ok_or_else(|| {
|
||||
format!(
|
||||
"function constant {index}: malformed air.is_function_constant_defined call"
|
||||
)
|
||||
})?;
|
||||
output.push_str(result);
|
||||
output.push_str(" = icmp eq i1 true, true");
|
||||
if line.ends_with('\n') {
|
||||
output.push('\n');
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let declaration = line.trim_start();
|
||||
if !declaration.starts_with('@') || !declaration.contains(" = ") {
|
||||
output.push_str(line);
|
||||
continue;
|
||||
}
|
||||
let Some(index) = crate::fc_specialize::fc_init_index(line) else {
|
||||
output.push_str(line);
|
||||
continue;
|
||||
};
|
||||
let Some((type_name, literal)) = literals.get(&index) else {
|
||||
output.push_str(line);
|
||||
continue;
|
||||
};
|
||||
if !line.contains("air.fc_initializer") {
|
||||
return Err(format!(
|
||||
"function constant {index}: MTL_FC_INIT global is not in the air.fc_initializer section"
|
||||
));
|
||||
}
|
||||
let constant_needle = format!(" constant {type_name} undef");
|
||||
let global_needle = format!(" global {type_name} undef");
|
||||
let replacement = if line.contains(&constant_needle) {
|
||||
Some((constant_needle, format!(" constant {literal}")))
|
||||
} else if line.contains(&global_needle) {
|
||||
Some((global_needle, format!(" global {literal}")))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let Some((needle, replacement)) = replacement else {
|
||||
return Err(format!(
|
||||
"function constant {index}: air.fc_initializer is not an undef {type_name} global"
|
||||
));
|
||||
};
|
||||
output.push_str(&line.replacen(&needle, &replacement, 1));
|
||||
replaced.insert(index);
|
||||
}
|
||||
|
||||
let missing = requested
|
||||
.keys()
|
||||
.filter(|index| !replaced.contains(index))
|
||||
.copied()
|
||||
.collect::<Vec<_>>();
|
||||
if !missing.is_empty() {
|
||||
return Err(format!(
|
||||
"AIR function-constant specialization did not replace index(es) {missing:?}"
|
||||
));
|
||||
}
|
||||
Ok(Cow::Owned(
|
||||
crate::meta::specialize_function_constant_metadata(&output),
|
||||
))
|
||||
}
|
||||
|
||||
fn llvm_typed_literal(
|
||||
type_name: &str,
|
||||
abi_type_encoding: &str,
|
||||
bytes: &[u8],
|
||||
) -> Result<String, String> {
|
||||
let bool_abi = abi_type_encoding == "b"
|
||||
|| abi_type_encoding
|
||||
.rsplit_once('_')
|
||||
.is_some_and(|(_, scalar)| scalar == "b");
|
||||
if let Some(inner) = type_name
|
||||
.strip_prefix('<')
|
||||
.and_then(|value| value.strip_suffix('>'))
|
||||
{
|
||||
let (lanes, scalar) = inner
|
||||
.split_once(" x ")
|
||||
.ok_or_else(|| format!("unsupported vector type `{type_name}`"))?;
|
||||
let lanes = lanes
|
||||
.parse::<usize>()
|
||||
.map_err(|error| format!("invalid vector lane count in `{type_name}`: {error}"))?;
|
||||
if !(1..=4).contains(&lanes) {
|
||||
return Err(format!("unsupported vector lane count {lanes}"));
|
||||
}
|
||||
let scalar_size = scalar_byte_size(scalar)?;
|
||||
let required = scalar_size
|
||||
.checked_mul(lanes)
|
||||
.ok_or_else(|| "function-constant payload size overflow".to_string())?;
|
||||
if bytes.len() != required {
|
||||
return Err(format!(
|
||||
"payload has {} bytes, {type_name} requires {required}",
|
||||
bytes.len()
|
||||
));
|
||||
}
|
||||
let elements = bytes
|
||||
.chunks_exact(scalar_size)
|
||||
.map(|lane| {
|
||||
scalar_literal(scalar, lane, bool_abi).map(|literal| format!("{scalar} {literal}"))
|
||||
})
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
return Ok(format!("{type_name} <{}>", elements.join(", ")));
|
||||
}
|
||||
|
||||
let required = scalar_byte_size(type_name)?;
|
||||
if bytes.len() != required {
|
||||
return Err(format!(
|
||||
"payload has {} bytes, {type_name} requires {required}",
|
||||
bytes.len()
|
||||
));
|
||||
}
|
||||
scalar_literal(type_name, bytes, bool_abi).map(|literal| format!("{type_name} {literal}"))
|
||||
}
|
||||
|
||||
fn scalar_byte_size(type_name: &str) -> Result<usize, String> {
|
||||
match type_name {
|
||||
"i1" | "i8" => Ok(1),
|
||||
"i16" | "half" | "bfloat" => Ok(2),
|
||||
"i32" | "float" => Ok(4),
|
||||
"i64" | "double" => Ok(8),
|
||||
_ => Err(format!("unsupported function-constant type `{type_name}`")),
|
||||
}
|
||||
}
|
||||
|
||||
fn scalar_literal(type_name: &str, bytes: &[u8], bool_abi: bool) -> Result<String, String> {
|
||||
let unsigned = || {
|
||||
let mut word = [0u8; 8];
|
||||
word[..bytes.len()].copy_from_slice(bytes);
|
||||
u64::from_le_bytes(word)
|
||||
};
|
||||
match type_name {
|
||||
"i1" => match bytes[0] {
|
||||
0 => Ok("0".into()),
|
||||
1 => Ok("1".into()),
|
||||
value => Err(format!("boolean payload must be 0 or 1, got {value}")),
|
||||
},
|
||||
"i8" | "i16" | "i32" | "i64" if bool_abi => match unsigned() {
|
||||
0 => Ok("0".into()),
|
||||
1 => Ok("1".into()),
|
||||
value => Err(format!("boolean payload must be 0 or 1, got {value}")),
|
||||
},
|
||||
"i8" | "i16" | "i32" | "i64" => Ok(unsigned().to_string()),
|
||||
"half" => Ok(format!("0xH{:04X}", unsigned())),
|
||||
"bfloat" => Ok(format!("0xR{:04X}", unsigned())),
|
||||
"float" => {
|
||||
let bits = u32::from_le_bytes(bytes.try_into().expect("four-byte payload checked"));
|
||||
let widened = f64::from(f32::from_bits(bits));
|
||||
let roundtrip = (widened as f32).to_bits();
|
||||
if roundtrip != bits {
|
||||
return Err(format!(
|
||||
"float payload 0x{bits:08x} cannot be represented exactly as an LLVM hexadecimal literal"
|
||||
));
|
||||
}
|
||||
Ok(format!("0x{:016X}", widened.to_bits()))
|
||||
}
|
||||
"double" => Ok(format!("0x{:016X}", unsigned())),
|
||||
_ => Err(format!("unsupported function-constant type `{type_name}`")),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn specializes_scalar_and_vector_initializer_globals() {
|
||||
let ll = r#"@enabled.MTL_FC_INIT_0_b = internal addrspace(2) externally_initialized constant i8 undef, section "air.fc_initializer", align 1
|
||||
@lanes.MTL_FC_INIT_3_Dv2_j = internal addrspace(2) externally_initialized constant <2 x i32> undef, section "air.fc_initializer", align 8
|
||||
define void @init() {
|
||||
%defined = call i1 @air.is_function_constant_defined(ptr addrspace(2) @enabled.MTL_FC_INIT_0_b)
|
||||
ret void
|
||||
}
|
||||
"#;
|
||||
let specialized = specialize_air_function_constants(
|
||||
ll,
|
||||
&[
|
||||
(0, vec![1]),
|
||||
(3, [7u32.to_le_bytes(), 11u32.to_le_bytes()].concat()),
|
||||
],
|
||||
)
|
||||
.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"));
|
||||
|
||||
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"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn specialized_predicates_select_metadata_roles_in_both_directions() {
|
||||
let ll = r#"@state.MTL_FC_INIT_0_b = internal addrspace(2) externally_initialized constant i8 undef, section "air.fc_initializer", align 1
|
||||
@enabled = internal addrspace(2) global i8 0, align 1
|
||||
@disabled = internal addrspace(2) global i8 0, align 1
|
||||
define internal void @_GLOBAL__sub_I_metadata() section "air.static_init" {
|
||||
%state = load i8, ptr addrspace(2) @state.MTL_FC_INIT_0_b
|
||||
%inverse = xor i8 %state, 1
|
||||
store i8 %state, ptr addrspace(2) @enabled
|
||||
store i8 %inverse, ptr addrspace(2) @disabled
|
||||
ret void
|
||||
}
|
||||
!0 = !{i32 0, !"air.function_constant", !2, !"air.buffer", !"air.location_index", i32 3}
|
||||
!1 = !{i32 1, !"air.function_constant", !3, !"air.texture", !"air.location_index", i32 4}
|
||||
!2 = !{ptr addrspace(2) @enabled, !"bool", !"enabled"}
|
||||
!3 = !{ptr addrspace(2) @disabled, !"bool", !"disabled"}
|
||||
"#;
|
||||
|
||||
let specialized = specialize_air_function_constants(ll, &[(0, vec![1])])
|
||||
.expect("specialize metadata predicates");
|
||||
assert!(
|
||||
specialized.contains("!0 = !{i32 0, !\"air.buffer\", !\"air.location_index\", i32 3}")
|
||||
);
|
||||
assert!(specialized
|
||||
.contains("!1 = !{i32 1, !\"air.function_constant_disabled\", !3, !\"air.texture\""));
|
||||
assert!(!specialized.contains("!0 = !{i32 0, !\"air.function_constant\""));
|
||||
let vertex = format!(
|
||||
"{specialized}!air.vertex = !{{!4}}\n!4 = !{{ptr @main, !5, !6}}\n!5 = !{{!1}}\n!6 = !{{}}\n"
|
||||
);
|
||||
assert_eq!(
|
||||
crate::meta::parse_air_vertex_meta(&vertex)
|
||||
.and_then(|meta| meta.output_role_of(0).cloned()),
|
||||
Some(crate::meta::VertOutRole::FunctionConstantDisabled)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_unknown_and_malformed_values() {
|
||||
let ll = r#"@enabled.MTL_FC_INIT_0_b = internal addrspace(2) externally_initialized constant i8 undef, section "air.fc_initializer", align 1
|
||||
"#;
|
||||
assert!(specialize_air_function_constants(ll, &[(9, vec![1])]).is_err());
|
||||
assert!(specialize_air_function_constants(ll, &[(0, vec![2])]).is_err());
|
||||
assert!(specialize_air_function_constants(ll, &[(0, vec![1, 0])]).is_err());
|
||||
}
|
||||
}
|
||||
+20
-19
@@ -297,7 +297,7 @@ fn materialize_zero_fc_initializers(module: &mut crate::spirv_module::Module) ->
|
||||
.collect();
|
||||
let mut rebuilt = Vec::with_capacity(module.types_global_values.len() + new_consts.len());
|
||||
let mut emitted = std::collections::HashSet::new();
|
||||
for mut inst in module.types_global_values.drain(..) {
|
||||
for mut inst in module.types_global_values.clone() {
|
||||
if inst.class.opcode == Op::Variable {
|
||||
if let Some((consts, initializer)) =
|
||||
inst.result_id.as_ref().and_then(|id| var_to_consts.get(id))
|
||||
@@ -385,9 +385,9 @@ pub fn specialize_function_constants_zero(spv: &[u8]) -> Result<Vec<u8>, String>
|
||||
let materialized = materialize_zero_fc_initializers(&mut module);
|
||||
let definedness = specialize_fc_definedness(&mut module, &defined_indices);
|
||||
if !materialized && !definedness {
|
||||
if prune_static_fc_branches_and_drop_interface(&mut module) {
|
||||
crate::passes::repair_specialized_workgroup_ptr_access_chains(&mut module);
|
||||
return Ok(module
|
||||
let (specialized, pruned) = prune_static_fc_branches_and_rebuild_interface(module);
|
||||
if pruned {
|
||||
return Ok(specialized
|
||||
.assemble()
|
||||
.iter()
|
||||
.flat_map(|w| w.to_le_bytes())
|
||||
@@ -395,8 +395,7 @@ pub fn specialize_function_constants_zero(spv: &[u8]) -> Result<Vec<u8>, String>
|
||||
}
|
||||
return Ok(spv.to_vec());
|
||||
}
|
||||
prune_static_fc_branches_and_drop_interface(&mut module);
|
||||
crate::passes::repair_specialized_workgroup_ptr_access_chains(&mut module);
|
||||
(module, _) = prune_static_fc_branches_and_rebuild_interface(module);
|
||||
Ok(module
|
||||
.assemble()
|
||||
.iter()
|
||||
@@ -642,7 +641,7 @@ fn specialize_function_constant_bytes_impl(
|
||||
// variable's initializer to the constant as we go.
|
||||
let mut rebuilt: Vec<Instruction> = Vec::with_capacity(module.types_global_values.len() + 1);
|
||||
let mut emitted: std::collections::HashSet<u32> = std::collections::HashSet::new();
|
||||
for mut inst in module.types_global_values.drain(..) {
|
||||
for mut inst in module.types_global_values.clone() {
|
||||
if inst.class.opcode == Op::Variable {
|
||||
if let Some((consts, initializer)) =
|
||||
inst.result_id.as_ref().and_then(|v| var_to_consts.get(v))
|
||||
@@ -676,11 +675,10 @@ fn specialize_function_constant_bytes_impl(
|
||||
// mutually-exclusive FC-gated resources honest: a Metal function may present a texture2d and a
|
||||
// texture2d_array at the same `[[texture(N)]]` slot under different FC predicates, but Vulkan
|
||||
// cannot bind two image view types to one descriptor in one specialized module. The pruning pass
|
||||
// is structural and already used by native retry tiers; this helper is opt-in because it only runs
|
||||
// for explicit harness/user-provided FC values.
|
||||
prune_static_fc_branches_and_drop_interface(&mut module);
|
||||
// is structural; this helper is opt-in because it only runs for explicit harness/user-provided
|
||||
// FC values.
|
||||
(module, _) = prune_static_fc_branches_and_rebuild_interface(module);
|
||||
rewrite_thread_local_scalar_byte_subslot_stores(&mut module);
|
||||
crate::passes::repair_specialized_workgroup_ptr_access_chains(&mut module);
|
||||
|
||||
Ok(module
|
||||
.assemble()
|
||||
@@ -689,17 +687,20 @@ fn specialize_function_constant_bytes_impl(
|
||||
.collect())
|
||||
}
|
||||
|
||||
fn prune_static_fc_branches_and_drop_interface(module: &mut crate::spirv_module::Module) -> bool {
|
||||
fn prune_static_fc_branches_and_rebuild_interface(
|
||||
mut module: crate::spirv_module::Module,
|
||||
) -> (crate::spirv_module::Module, bool) {
|
||||
if module.entry_points.is_empty() {
|
||||
return false;
|
||||
return (module, false);
|
||||
}
|
||||
let before_prune = module.clone();
|
||||
if crate::native::prune_constant_branches_module(module).is_err() {
|
||||
return false;
|
||||
if crate::native::prune_constant_branches_module(&mut module).is_err() {
|
||||
return (module, false);
|
||||
}
|
||||
restore_loop_merges_removed_by_fc_prune(&before_prune, module);
|
||||
drop_unreferenced_entry_interface_globals(module);
|
||||
true
|
||||
restore_loop_merges_removed_by_fc_prune(&before_prune, &mut module);
|
||||
drop_unreferenced_entry_interface_globals(&mut module);
|
||||
module = crate::passes::lower_specialized_workgroup_ptr_access_chains(module);
|
||||
(module, true)
|
||||
}
|
||||
|
||||
fn rewrite_thread_local_scalar_byte_subslot_stores(
|
||||
@@ -968,7 +969,7 @@ fn rewrite_thread_local_scalar_byte_subslot_stores(
|
||||
let mut changed = false;
|
||||
for (fi, function) in module.functions.iter_mut().enumerate() {
|
||||
for (bi, block) in function.blocks.iter_mut().enumerate() {
|
||||
let old = std::mem::take(&mut block.instructions);
|
||||
let old = block.instructions.clone();
|
||||
let mut out = Vec::with_capacity(old.len() + 16);
|
||||
for (ii, inst) in old.into_iter().enumerate() {
|
||||
if chain_sites.contains(&(fi, bi, ii)) {
|
||||
|
||||
+558
-984
File diff suppressed because it is too large.
Load diff
+129
-13
@@ -538,8 +538,14 @@ pub fn specialize_visible_function_references(
|
||||
)?;
|
||||
append_dependency_module(&mut output, &rewritten);
|
||||
}
|
||||
|
||||
Ok(output)
|
||||
let direct_functions = used
|
||||
.into_iter()
|
||||
.map(llvm_global)
|
||||
.collect::<Result<HashSet<_>, _>>()?;
|
||||
Ok(crate::native::inline_direct_function_pointer_consumers(
|
||||
&output,
|
||||
&direct_functions,
|
||||
))
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
@@ -548,6 +554,20 @@ struct AirVisibleFunctionReference {
|
||||
symbol: String,
|
||||
}
|
||||
|
||||
/// Return the logical callback symbols named by AIR's direct visible-function-reference metadata.
|
||||
///
|
||||
/// The order follows the metadata, with repeated mappings of the same stub reported once. This is
|
||||
/// the structural key a linker needs to resolve retained dependency modules before translating to
|
||||
/// Logical SPIR-V.
|
||||
pub fn visible_function_reference_symbols(module: &str) -> Result<Vec<String>, String> {
|
||||
air_visible_function_references(module).map(|references| {
|
||||
references
|
||||
.into_iter()
|
||||
.map(|reference| reference.symbol)
|
||||
.collect()
|
||||
})
|
||||
}
|
||||
|
||||
fn rewrite_visible_reference_stubs<'a>(
|
||||
module: &str,
|
||||
authored: &HashMap<&str, &'a LinkedFunctionReference>,
|
||||
@@ -678,27 +698,52 @@ fn decode_llvm_string(encoded: &str) -> Result<String, String> {
|
||||
String::from_utf8(decoded).map_err(|_| format!("non-UTF-8 LLVM symbol in {encoded:?}"))
|
||||
}
|
||||
|
||||
/// Resolve visible-function-table lookups and append their exact dependency modules.
|
||||
/// Trace entry visible-function-table parameters through direct calls to internal helpers.
|
||||
///
|
||||
/// Literal slots become direct calls. Dynamic slots become a direct call to a generated switch
|
||||
/// dispatcher containing one arm per authored table entry. Calls not derived from an authored table
|
||||
/// are left for the native emitter's ordinary indirect-call error.
|
||||
pub fn specialize_visible_function_tables(
|
||||
/// This exposes the exact table-flow contract used by [`specialize_visible_function_tables`] so
|
||||
/// validation and authoring tools can decide whether a helper-local lookup has an authored entry
|
||||
/// root without maintaining a second LLVM call-flow parser. A helper parameter reached from two
|
||||
/// distinct table roots is rejected just as it is during specialization.
|
||||
pub fn trace_visible_function_table_parameters(
|
||||
entry_ll: &str,
|
||||
entry_name: &str,
|
||||
linkage: &LinkedFunctionLinkage,
|
||||
) -> Result<String, String> {
|
||||
if linkage.visible_tables.is_empty() {
|
||||
return Ok(entry_ll.to_string());
|
||||
parameter_indices: &[u32],
|
||||
) -> Result<HashMap<String, HashSet<String>>, String> {
|
||||
let tables = parameter_indices
|
||||
.iter()
|
||||
.map(|parameter_index| LinkedFunctionTable {
|
||||
parameter_index: *parameter_index,
|
||||
size: 1,
|
||||
entries: Vec::new(),
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let (signatures, flow) = visible_table_flow(entry_ll, entry_name, &tables)?;
|
||||
let mut values = HashMap::<String, HashSet<String>>::new();
|
||||
for ((function, ordinal), _) in flow.table_parameters {
|
||||
let parameter = signatures
|
||||
.get(&function)
|
||||
.and_then(|signature| signature.parameters.get(ordinal))
|
||||
.ok_or_else(|| format!("missing parameter {ordinal} of {function}"))?;
|
||||
values
|
||||
.entry(function)
|
||||
.or_default()
|
||||
.insert(parameter.clone());
|
||||
}
|
||||
validate_linkage(linkage)?;
|
||||
Ok(values)
|
||||
}
|
||||
|
||||
fn visible_table_flow<'a>(
|
||||
entry_ll: &str,
|
||||
entry_name: &str,
|
||||
tables: &'a [LinkedFunctionTable],
|
||||
) -> Result<(HashMap<String, FunctionSignature>, LinkedFlow<'a>), String> {
|
||||
let signatures = function_signatures(entry_ll)?;
|
||||
let entry_global = llvm_global(entry_name)?;
|
||||
let entry_signature = signatures.get(&entry_global).ok_or_else(|| {
|
||||
format!("linked function-table entry function {entry_name:?} is not defined")
|
||||
})?;
|
||||
let mut flow = LinkedFlow::default();
|
||||
for table in &linkage.visible_tables {
|
||||
for table in tables {
|
||||
let parameter = entry_signature
|
||||
.parameters
|
||||
.get(table.parameter_index as usize)
|
||||
@@ -726,6 +771,24 @@ pub fn specialize_visible_function_tables(
|
||||
}
|
||||
}
|
||||
propagate_linked_flow(entry_ll, &signatures, &mut flow)?;
|
||||
Ok((signatures, flow))
|
||||
}
|
||||
|
||||
/// Resolve visible-function-table lookups and append their exact dependency modules.
|
||||
///
|
||||
/// Literal slots become direct calls. Dynamic slots become a direct call to a generated switch
|
||||
/// dispatcher containing one arm per authored table entry. Calls not derived from an authored table
|
||||
/// are left for the native emitter's ordinary indirect-call error.
|
||||
pub fn specialize_visible_function_tables(
|
||||
entry_ll: &str,
|
||||
entry_name: &str,
|
||||
linkage: &LinkedFunctionLinkage,
|
||||
) -> Result<String, String> {
|
||||
if linkage.visible_tables.is_empty() {
|
||||
return Ok(entry_ll.to_string());
|
||||
}
|
||||
validate_linkage(linkage)?;
|
||||
let (signatures, flow) = visible_table_flow(entry_ll, entry_name, &linkage.visible_tables)?;
|
||||
|
||||
struct Dispatcher<'a> {
|
||||
name: String,
|
||||
@@ -1906,6 +1969,37 @@ declare i32 @base.MTL_VISIBLE_FN_REF(i32) section "air.externally_defined"
|
||||
assert!(!specialized.contains("!air.visible_function_references"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_visible_reference_specializes_internal_function_pointer_consumer() {
|
||||
let entry = r#"define i32 @main(i32 %value) {
|
||||
entry:
|
||||
%result = call i32 @apply(ptr @linked.MTL_VISIBLE_FN_REF, i32 %value)
|
||||
ret i32 %result
|
||||
}
|
||||
define internal i32 @apply(ptr %function, i32 %value) {
|
||||
entry:
|
||||
%result = call i32 %function(i32 %value)
|
||||
ret i32 %result
|
||||
}
|
||||
declare i32 @linked.MTL_VISIBLE_FN_REF(i32) section "air.externally_defined"
|
||||
!air.visible_function_references = !{!0}
|
||||
!0 = !{!"air.visible_function_reference", ptr @linked.MTL_VISIBLE_FN_REF, !"linked"}
|
||||
"#;
|
||||
let linkage = LinkedFunctionLinkage {
|
||||
visible_references: vec![LinkedFunctionReference {
|
||||
symbol: "linked".into(),
|
||||
module_ll: "define i32 @linked(i32 %value) { ret i32 %value }\n".into(),
|
||||
}],
|
||||
visible_tables: vec![],
|
||||
intersection_tables: vec![],
|
||||
};
|
||||
|
||||
let specialized = specialize_visible_function_references(entry, &linkage).unwrap();
|
||||
assert!(specialized.contains("call i32 @linked(i32 %value)"));
|
||||
assert!(!specialized.contains("call i32 %function"));
|
||||
assert!(!specialized.contains("call i32 @apply(ptr @linked"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_visible_reference_requires_an_exact_authored_symbol() {
|
||||
let entry = r#"define void @main() { ret void }
|
||||
@@ -2379,6 +2473,8 @@ entry:
|
||||
}],
|
||||
intersection_tables: vec![],
|
||||
};
|
||||
let traced = trace_visible_function_table_parameters(entry, "main", &[1]).unwrap();
|
||||
assert_eq!(traced["@main"], HashSet::from(["%table".to_string()]));
|
||||
let specialized = specialize_visible_function_tables(entry, "main", &linked).unwrap();
|
||||
assert!(specialized.contains("call i32 @invoke(ptr %typed, i32 41, i32 %slot)"));
|
||||
assert!(specialized.contains(
|
||||
@@ -2390,6 +2486,26 @@ entry:
|
||||
assert!(!specialized.contains("call i32 %callback("));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn table_parameter_trace_uses_the_specializers_internal_call_flow() {
|
||||
let entry = r#"
|
||||
define void @main(ptr addrspace(1) %table) {
|
||||
entry:
|
||||
%value = call i32 @invoke(ptr addrspace(1) %table)
|
||||
ret void
|
||||
}
|
||||
define internal i32 @invoke(ptr addrspace(1) %functions) {
|
||||
entry:
|
||||
%fp = call ptr @air.get_function_pointer_visible_function_table(ptr addrspace(1) %functions, i32 0)
|
||||
%value = call i32 %fp()
|
||||
ret i32 %value
|
||||
}
|
||||
"#;
|
||||
let traced = trace_visible_function_table_parameters(entry, "main", &[0]).unwrap();
|
||||
assert_eq!(traced["@main"], HashSet::from(["%table".to_string()]));
|
||||
assert_eq!(traced["@invoke"], HashSet::from(["%functions".to_string()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linked_translation_emits_the_direct_function_and_no_table_descriptor() {
|
||||
let entry = format!(
|
||||
|
||||
+7
-15
@@ -1,6 +1,6 @@
|
||||
//! metal2vulkan CLI — AIR/LLVM-IR to validated Vulkan SPIR-V.
|
||||
//! Usage: metal2vulkan <in.air|.ll> <out.spv> [--stage auto|vertex|fragment|passthrough|kernel]
|
||||
//! Prints a line containing `PASS` on success (spirv-val vulkan1.3 clean), nonzero exit + `FALLBACK`
|
||||
//! Prints a line containing `PASS` on success (spirv-val vulkan1.2 clean), nonzero exit + `FALLBACK`
|
||||
//! on any failure.
|
||||
|
||||
use metal2vulkan::passes::{Stage, TransformOptions};
|
||||
@@ -63,13 +63,13 @@ options:
|
||||
--raster-samples 1|2|4|8|16|32|64
|
||||
exact graphics-pipeline sample count for AIR sample-count queries
|
||||
--local X,Y,Z
|
||||
Vulkan/Metal kernel threadgroup size (default: 64,1,1)
|
||||
nominal Metal kernel threadgroup size (default: 64,1,1)
|
||||
--threads-per-grid X,Y,Z
|
||||
bake one exact Metal dispatchThreads grid and cull rounded-up Vulkan invocations
|
||||
reflect one fixed Metal dispatchThreads grid for exact boundary decomposition
|
||||
--threads-per-grid-push-constant OFFSET
|
||||
read the exact grid from three u32 push constants at OFFSET, OFFSET+4, OFFSET+8
|
||||
place the dynamic 48-byte dispatch-region payload at OFFSET
|
||||
--whole-workgroups
|
||||
assert every dispatch covers complete workgroups and omit the default grid guard
|
||||
assert every dispatch covers complete workgroups and use one fixed-local-size pipeline
|
||||
-h, --help
|
||||
show this help
|
||||
"#
|
||||
@@ -132,7 +132,7 @@ options:
|
||||
.unwrap_or_else(|| {
|
||||
fail("--threads-per-grid-push-constant requires a byte offset")
|
||||
});
|
||||
let dispatch = KernelDispatch::ThreadsPushConstant { offset };
|
||||
let dispatch = KernelDispatch::ThreadsDynamic { offset };
|
||||
if let Err(error) = dispatch.validate() {
|
||||
fail(&error);
|
||||
}
|
||||
@@ -241,15 +241,7 @@ options:
|
||||
fail_with_repro("write failed", &repro, Some(&e.to_string()), &tmp);
|
||||
}
|
||||
|
||||
match tools::spirv_val(&out) {
|
||||
Ok(()) => {
|
||||
println!("metal2vulkan: wrote {out}; spirv-val vulkan1.3: PASS");
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("{e}");
|
||||
fail_with_repro("spirv-val failed", &repro, Some(&e), &tmp);
|
||||
}
|
||||
}
|
||||
println!("metal2vulkan: wrote {out}; spirv-val vulkan1.2: PASS");
|
||||
|
||||
if let Some(meta_path) = &emit_meta {
|
||||
match reflection.as_ref() {
|
||||
|
||||
+279
-45
@@ -39,14 +39,31 @@ fn parse_global_name(s: &str) -> Option<String> {
|
||||
enum StaticValue {
|
||||
Bool(bool),
|
||||
Int(u64),
|
||||
Vec4([u64; 4]),
|
||||
Vector(Vec<u64>),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) enum StaticIntValue {
|
||||
Scalar(u32),
|
||||
Vector(Vec<u32>),
|
||||
}
|
||||
|
||||
/// Best-effort evaluator for AIR static initializers that materialize default function-constant
|
||||
/// integer globals. Unknown expressions are ignored so dynamic metadata falls back to its immediate
|
||||
/// location index rather than guessing.
|
||||
pub(super) fn static_init_int_global_values(ll: &str) -> HashMap<String, u32> {
|
||||
let mut globals = parse_integer_global_initializers(ll);
|
||||
static_init_global_values(ll)
|
||||
.into_iter()
|
||||
.filter_map(|(global, value)| match value {
|
||||
StaticValue::Bool(value) => Some((global, u32::from(value))),
|
||||
StaticValue::Int(value) => Some((global, value as u32)),
|
||||
StaticValue::Vector(_) => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn static_init_global_values(ll: &str) -> HashMap<String, StaticValue> {
|
||||
let mut globals = parse_static_global_initializers(ll);
|
||||
let mut unknown_stores = HashSet::new();
|
||||
let mut env: HashMap<String, StaticValue> = HashMap::new();
|
||||
let mut in_static_init = false;
|
||||
@@ -75,10 +92,15 @@ pub(super) fn static_init_int_global_values(ll: &str) -> HashMap<String, u32> {
|
||||
let Some(global) = parse_global_name(ptr) else {
|
||||
continue;
|
||||
};
|
||||
if let Some(value) = eval_int_operand(value, &env, &globals) {
|
||||
let value = value as u32;
|
||||
if let Some(value) = eval_value_token(value_token(value), &env, &globals) {
|
||||
unknown_stores.remove(&global);
|
||||
globals.insert(global, value);
|
||||
globals.insert(
|
||||
global,
|
||||
match value {
|
||||
StaticValue::Int(value) => StaticValue::Int(value & u64::from(u32::MAX)),
|
||||
value => value,
|
||||
},
|
||||
);
|
||||
} else {
|
||||
globals.remove(&global);
|
||||
unknown_stores.insert(global);
|
||||
@@ -97,18 +119,17 @@ pub(super) fn static_init_int_global_values(ll: &str) -> HashMap<String, u32> {
|
||||
}
|
||||
}
|
||||
|
||||
globals.retain(|global, _| !unknown_stores.contains(global));
|
||||
globals
|
||||
.into_iter()
|
||||
.filter(|(global, _)| !unknown_stores.contains(global))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Integer mirrors derived from an AIR function-constant initializer and only read afterward. This
|
||||
/// Integer scalar/vector mirrors derived from an AIR function-constant initializer and only read
|
||||
/// afterward. This
|
||||
/// is the product-safe subset of the metadata evaluator above: ordinary constructor state is left
|
||||
/// intact, and any non-load use outside a constructor may mutate or escape the cell, so it is
|
||||
/// excluded.
|
||||
pub(crate) fn static_init_foldable_int_global_values(ll: &str) -> HashMap<String, u32> {
|
||||
let mut values = static_init_int_global_values(ll);
|
||||
pub(crate) fn static_init_foldable_global_values(ll: &str) -> HashMap<String, StaticIntValue> {
|
||||
let mut values = static_init_global_values(ll);
|
||||
let mut derived_globals = ll
|
||||
.lines()
|
||||
.filter_map(|raw| {
|
||||
@@ -118,6 +139,7 @@ pub(crate) fn static_init_foldable_int_global_values(ll: &str) -> HashMap<String
|
||||
.flatten()
|
||||
})
|
||||
.collect::<HashSet<_>>();
|
||||
let initializer_globals = derived_globals.clone();
|
||||
let mut derived_locals = HashSet::<String>::new();
|
||||
let mut in_constructor = false;
|
||||
for raw in ll.lines() {
|
||||
@@ -188,7 +210,24 @@ pub(crate) fn static_init_foldable_int_global_values(ll: &str) -> HashMap<String
|
||||
parse_global_name(load).as_ref() == Some(global)
|
||||
});
|
||||
}
|
||||
// Keep the ABI initializer cells and their loads in generic SPIR-V so the public post-emit
|
||||
// specialization helper can still override direct function-constant uses. Only constructor-
|
||||
// derived immutable mirrors are folded under the generic translation's zero/default model;
|
||||
// structure-changing nonzero values use the AIR-level specialization API.
|
||||
values.retain(|global, _| !initializer_globals.contains(global));
|
||||
values
|
||||
.into_iter()
|
||||
.map(|(global, value)| {
|
||||
let value = match value {
|
||||
StaticValue::Bool(value) => StaticIntValue::Scalar(u32::from(value)),
|
||||
StaticValue::Int(value) => StaticIntValue::Scalar(value as u32),
|
||||
StaticValue::Vector(values) => {
|
||||
StaticIntValue::Vector(values.into_iter().map(|value| value as u32).collect())
|
||||
}
|
||||
};
|
||||
(global, value)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn references_symbol(text: &str, symbol: &str) -> bool {
|
||||
@@ -200,7 +239,7 @@ fn references_symbol(text: &str, symbol: &str) -> bool {
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_integer_global_initializers(ll: &str) -> HashMap<String, u32> {
|
||||
fn parse_static_global_initializers(ll: &str) -> HashMap<String, StaticValue> {
|
||||
let mut globals = HashMap::new();
|
||||
for raw in ll.lines() {
|
||||
let line = raw.split(';').next().unwrap_or(raw).trim();
|
||||
@@ -218,55 +257,121 @@ fn parse_integer_global_initializers(ll: &str) -> HashMap<String, u32> {
|
||||
globals
|
||||
}
|
||||
|
||||
fn integer_initializer(rest: &str) -> Option<u32> {
|
||||
fn integer_initializer(rest: &str) -> Option<StaticValue> {
|
||||
let typed_init = rest
|
||||
.split_once(" global ")
|
||||
.map(|(_, init)| init)
|
||||
.or_else(|| rest.split_once(" constant ").map(|(_, init)| init))?;
|
||||
let tokens = typed_init.split_whitespace().collect::<Vec<_>>();
|
||||
let ty_pos = tokens
|
||||
.iter()
|
||||
.position(|tok| matches!(*tok, "i8" | "i16" | "i32"))?;
|
||||
let value = tokens.get(ty_pos + 1)?.trim_end_matches(',');
|
||||
if value == "undef" && rest.contains("air.fc_initializer") {
|
||||
return Some(0);
|
||||
if typed_init.starts_with('<') {
|
||||
let type_end = typed_init.find('>')?;
|
||||
let vector_ty = &typed_init[1..type_end];
|
||||
let (lanes, element_ty) = vector_ty.split_once(" x ")?;
|
||||
let lanes = lanes.parse::<usize>().ok()?;
|
||||
let width = element_ty.strip_prefix('i')?.parse::<u32>().ok()?;
|
||||
if width == 0 || width > 32 {
|
||||
return None;
|
||||
}
|
||||
let vector = typed_init[type_end + 1..].trim_start();
|
||||
let vector = if vector.starts_with('<') {
|
||||
&vector[..=vector.find('>')?]
|
||||
} else {
|
||||
vector.split(',').next().unwrap_or(vector).trim()
|
||||
};
|
||||
if vector == "undef" || vector == "zeroinitializer" {
|
||||
return rest
|
||||
.contains("air.fc_initializer")
|
||||
.then(|| StaticValue::Vector(vec![0; lanes]));
|
||||
}
|
||||
let values = vector.strip_prefix('<')?.strip_suffix('>')?;
|
||||
let mask = if width == 32 {
|
||||
u64::from(u32::MAX)
|
||||
} else {
|
||||
(1_u64 << width) - 1
|
||||
};
|
||||
let values = values
|
||||
.split(',')
|
||||
.map(|lane| {
|
||||
let (ty, value) = lane.trim().split_once(' ')?;
|
||||
(ty == element_ty)
|
||||
.then(|| {
|
||||
value
|
||||
.parse::<u64>()
|
||||
.or_else(|_| value.parse::<i64>().map(|value| value as u64))
|
||||
.ok()
|
||||
})
|
||||
.flatten()
|
||||
.map(|value| value & mask)
|
||||
})
|
||||
.collect::<Option<Vec<_>>>()?;
|
||||
return (values.len() == lanes).then_some(StaticValue::Vector(values));
|
||||
}
|
||||
value.parse::<u32>().ok()
|
||||
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) {
|
||||
return None;
|
||||
}
|
||||
let mask = (1_u64 << width) - 1;
|
||||
let value = tokens.next()?.trim_end_matches(',');
|
||||
if value == "undef" && rest.contains("air.fc_initializer") {
|
||||
return Some(StaticValue::Int(0));
|
||||
}
|
||||
value
|
||||
.parse::<u64>()
|
||||
.or_else(|_| value.parse::<i64>().map(|value| value as u64))
|
||||
.ok()
|
||||
.map(|value| StaticValue::Int(value & mask))
|
||||
}
|
||||
|
||||
fn eval_static_rhs(
|
||||
rhs: &str,
|
||||
env: &HashMap<String, StaticValue>,
|
||||
globals: &HashMap<String, u32>,
|
||||
globals: &HashMap<String, StaticValue>,
|
||||
) -> Option<StaticValue> {
|
||||
if rhs.contains("@air.is_function_constant_defined(") {
|
||||
return Some(StaticValue::Bool(false));
|
||||
}
|
||||
if rhs.starts_with("load <4 x i32>") {
|
||||
return Some(StaticValue::Vec4([0; 4]));
|
||||
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)?;
|
||||
return Some(StaticValue::Int(u64::from(value != 0)));
|
||||
}
|
||||
if rhs.starts_with("load i") {
|
||||
if rhs.starts_with("load ") {
|
||||
let global = parse_global_name(rhs)?;
|
||||
return globals
|
||||
.get(&global)
|
||||
.map(|value| StaticValue::Int(*value as u64));
|
||||
return globals.get(&global).cloned();
|
||||
}
|
||||
if let Some(rest) = rhs.strip_prefix("extractelement ") {
|
||||
let parts = rest.split(',').collect::<Vec<_>>();
|
||||
let vector = eval_value_token(parts.first()?.split_whitespace().last()?, env, globals)?;
|
||||
let idx = eval_int_operand(parts.get(1)?, env, globals)? as usize;
|
||||
let StaticValue::Vec4(values) = vector else {
|
||||
let StaticValue::Vector(values) = vector else {
|
||||
return None;
|
||||
};
|
||||
return values.get(idx).copied().map(StaticValue::Int);
|
||||
}
|
||||
if let Some(rest) = rhs.strip_prefix("lshr ") {
|
||||
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))
|
||||
})
|
||||
{
|
||||
let (lhs, rhs) = eval_binary_int(rest, env, globals)?;
|
||||
return Some(StaticValue::Int(lhs >> rhs));
|
||||
}
|
||||
if let Some(rest) = rhs.strip_prefix("and ") {
|
||||
let (lhs, rhs) = eval_binary_int(rest, env, globals)?;
|
||||
return Some(StaticValue::Int(lhs & rhs));
|
||||
let (width, mask) = integer_result_width_and_mask(rest)?;
|
||||
let lhs = lhs & 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),
|
||||
"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,
|
||||
_ => unreachable!("matched integer opcode"),
|
||||
};
|
||||
return Some(StaticValue::Int(value & mask));
|
||||
}
|
||||
if let Some(rest) = rhs.strip_prefix("icmp ") {
|
||||
let mut fields = rest.splitn(2, ' ');
|
||||
@@ -313,7 +418,7 @@ fn eval_static_rhs(
|
||||
fn eval_binary_int(
|
||||
rest: &str,
|
||||
env: &HashMap<String, StaticValue>,
|
||||
globals: &HashMap<String, u32>,
|
||||
globals: &HashMap<String, StaticValue>,
|
||||
) -> Option<(u64, u64)> {
|
||||
let parts = rest.split(',').collect::<Vec<_>>();
|
||||
Some((
|
||||
@@ -322,34 +427,45 @@ fn eval_binary_int(
|
||||
))
|
||||
}
|
||||
|
||||
fn integer_result_width_and_mask(text: &str) -> Option<(u32, u64)> {
|
||||
let width = text
|
||||
.split(|c: char| c.is_whitespace() || c == ',')
|
||||
.find_map(|token| token.strip_prefix('i')?.parse::<u32>().ok())?;
|
||||
match width {
|
||||
1..=63 => Some((width, (1_u64 << width) - 1)),
|
||||
64 => Some((width, u64::MAX)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn eval_int_operand(
|
||||
text: &str,
|
||||
env: &HashMap<String, StaticValue>,
|
||||
globals: &HashMap<String, u32>,
|
||||
globals: &HashMap<String, StaticValue>,
|
||||
) -> Option<u64> {
|
||||
match eval_value_token(value_token(text), env, globals)? {
|
||||
StaticValue::Bool(value) => Some(u64::from(value)),
|
||||
StaticValue::Int(value) => Some(value),
|
||||
StaticValue::Vec4(_) => None,
|
||||
StaticValue::Vector(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn eval_bool_operand(
|
||||
text: &str,
|
||||
env: &HashMap<String, StaticValue>,
|
||||
globals: &HashMap<String, u32>,
|
||||
globals: &HashMap<String, StaticValue>,
|
||||
) -> Option<bool> {
|
||||
match eval_value_token(value_token(text), env, globals)? {
|
||||
StaticValue::Bool(value) => Some(value),
|
||||
StaticValue::Int(value) => Some(value != 0),
|
||||
StaticValue::Vec4(_) => None,
|
||||
StaticValue::Vector(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn eval_value_token(
|
||||
token: &str,
|
||||
env: &HashMap<String, StaticValue>,
|
||||
globals: &HashMap<String, u32>,
|
||||
globals: &HashMap<String, StaticValue>,
|
||||
) -> Option<StaticValue> {
|
||||
let token = token.trim().trim_end_matches(',');
|
||||
if token == "true" {
|
||||
@@ -362,11 +478,13 @@ fn eval_value_token(
|
||||
return env.get(token).cloned();
|
||||
}
|
||||
if token.starts_with('@') {
|
||||
return globals
|
||||
.get(token)
|
||||
.map(|value| StaticValue::Int(*value as u64));
|
||||
return globals.get(token).cloned();
|
||||
}
|
||||
token.parse::<u64>().ok().map(StaticValue::Int)
|
||||
token
|
||||
.parse::<u64>()
|
||||
.or_else(|_| token.parse::<i64>().map(|value| value as u64))
|
||||
.ok()
|
||||
.map(StaticValue::Int)
|
||||
}
|
||||
|
||||
fn value_token(text: &str) -> &str {
|
||||
@@ -375,3 +493,119 @@ fn value_token(text: &str) -> &str {
|
||||
.unwrap_or_else(|| text.trim())
|
||||
.trim_end_matches(',')
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn vector_initializer_is_not_misclassified_as_a_scalar() {
|
||||
let ll = r#"
|
||||
@fc.MTL_FC_INIT_3_Dv4_j = internal addrspace(2) externally_initialized constant <4 x i32> <i32 1, i32 2, i32 3, i32 4>, section "air.fc_initializer", align 16
|
||||
@mirror = internal addrspace(2) global i32 undef, align 4
|
||||
|
||||
define internal void @_GLOBAL__sub_I_vector_fc() {
|
||||
entry:
|
||||
%value = load <4 x i32>, ptr addrspace(2) @fc.MTL_FC_INIT_3_Dv4_j
|
||||
%lane = extractelement <4 x i32> %value, i64 2
|
||||
store i32 %lane, ptr addrspace(2) @mirror
|
||||
ret void
|
||||
}
|
||||
|
||||
define i32 @use() {
|
||||
entry:
|
||||
%value = load i32, ptr addrspace(2) @mirror
|
||||
ret i32 %value
|
||||
}
|
||||
"#;
|
||||
|
||||
let values = static_init_int_global_values(ll);
|
||||
assert_eq!(values.get("@mirror"), Some(&3));
|
||||
assert!(!values.contains_key("@fc.MTL_FC_INIT_3_Dv4_j"));
|
||||
let foldable = static_init_foldable_global_values(ll);
|
||||
assert!(matches!(
|
||||
foldable.get("@mirror"),
|
||||
Some(StaticIntValue::Scalar(3))
|
||||
));
|
||||
assert!(!foldable.contains_key("@fc.MTL_FC_INIT_3_Dv4_j"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn signed_masked_function_constant_initializer_is_foldable() {
|
||||
let ll = r#"
|
||||
@fc.MTL_FC_INIT_2_t = internal addrspace(2) externally_initialized constant i16 undef, section "air.fc_initializer", align 2
|
||||
@rounded = internal addrspace(2) global i16 undef, align 2
|
||||
@negative = internal addrspace(2) global i16 -1, align 2
|
||||
|
||||
define internal void @_GLOBAL__sub_I_fc() {
|
||||
entry:
|
||||
%value = load i16, ptr addrspace(2) @fc.MTL_FC_INIT_2_t
|
||||
%biased = add i16 %value, 15
|
||||
%masked = and i16 %biased, -16
|
||||
store i16 %masked, ptr addrspace(2) @rounded
|
||||
ret void
|
||||
}
|
||||
|
||||
define i16 @use() {
|
||||
entry:
|
||||
%value = load i16, ptr addrspace(2) @rounded
|
||||
ret i16 %value
|
||||
}
|
||||
"#;
|
||||
|
||||
let values = static_init_foldable_global_values(ll);
|
||||
assert!(matches!(
|
||||
values.get("@rounded"),
|
||||
Some(StaticIntValue::Scalar(0))
|
||||
));
|
||||
assert_eq!(
|
||||
static_init_int_global_values(ll).get("@negative"),
|
||||
Some(&65535)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn out_of_width_shift_is_not_folded() {
|
||||
let ll = r#"
|
||||
@fc.MTL_FC_INIT_2_t = internal addrspace(2) externally_initialized constant i16 undef, section "air.fc_initializer", align 2
|
||||
@shifted = internal addrspace(2) global i16 undef, align 2
|
||||
|
||||
define internal void @_GLOBAL__sub_I_fc() {
|
||||
entry:
|
||||
%value = load i16, ptr addrspace(2) @fc.MTL_FC_INIT_2_t
|
||||
%value.shifted = shl i16 %value, 16
|
||||
store i16 %value.shifted, ptr addrspace(2) @shifted
|
||||
ret void
|
||||
}
|
||||
|
||||
define i16 @use() {
|
||||
entry:
|
||||
%value = load i16, ptr addrspace(2) @shifted
|
||||
ret i16 %value
|
||||
}
|
||||
"#;
|
||||
|
||||
assert!(!static_init_foldable_global_values(ll).contains_key("@shifted"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn function_constant_predicate_normalization_preserves_an_enabled_default() {
|
||||
let ll = r#"
|
||||
@fc.MTL_FC_INIT_1_b = internal addrspace(2) externally_initialized constant i8 1, section "air.fc_initializer", align 1
|
||||
@predicate = internal addrspace(2) global i8 0, align 1
|
||||
|
||||
define internal void @_GLOBAL__sub_I_fc() {
|
||||
entry:
|
||||
%value = load i8, ptr addrspace(2) @fc.MTL_FC_INIT_1_b
|
||||
%normalized = tail call i8 @air.normalize_function_constant_predicate.i8(i8 %value)
|
||||
store i8 %normalized, ptr addrspace(2) @predicate
|
||||
ret void
|
||||
}
|
||||
"#;
|
||||
|
||||
assert_eq!(
|
||||
static_init_int_global_values(ll).get("@predicate"),
|
||||
Some(&1)
|
||||
);
|
||||
}
|
||||
}
|
||||
+186
-98
@@ -13,8 +13,8 @@ mod types;
|
||||
use embedded::{body_uses_texture_intrinsic, detect_embedded_arguments, detect_embedded_textures};
|
||||
pub use embedded::{embedded_synthetic_texture_index, EmbeddedArgument, EmbeddedTexture};
|
||||
pub use function_constants::{parse_function_constants, FunctionConstant};
|
||||
pub(crate) use globals::static_init_foldable_int_global_values;
|
||||
use globals::{location_index_with_static, static_init_int_global_values};
|
||||
pub(crate) use globals::{static_init_foldable_global_values, StaticIntValue};
|
||||
pub use intersections::{
|
||||
AirIntersectionFamily, AirIntersectionInstancing, AirIntersectionResultField,
|
||||
};
|
||||
@@ -25,6 +25,13 @@ pub use textures::{
|
||||
use types::{parse_struct_info, struct_info_ref, tokenize, Tok};
|
||||
pub use types::{primitive_air_type_from_name, AirMember, AirScalar, AirType};
|
||||
|
||||
/// Whether stable AIR argument metadata describes a runtime array of device-buffer addresses.
|
||||
pub fn is_device_buffer_array_type_name(name: &str) -> bool {
|
||||
name.chars()
|
||||
.filter(|character| !character.is_whitespace())
|
||||
.eq("array_ref<void>".chars())
|
||||
}
|
||||
|
||||
/// Role of a single fragment-shader entry parameter, keyed by its parameter index.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum FragRole {
|
||||
@@ -40,6 +47,8 @@ pub enum FragRole {
|
||||
SampleId,
|
||||
/// `[[viewport_array_index]]` -> Input BuiltIn ViewportIndex (32-bit uint).
|
||||
ViewportArrayIndex,
|
||||
/// `[[render_target_array_index]]` -> Input BuiltIn Layer (32-bit uint).
|
||||
RenderTargetArrayIndex,
|
||||
/// `[[stage_in]]` interpolated input -> Input var at Location N (N = order among fragment_inputs).
|
||||
Varying(u32),
|
||||
/// `[[texture(n)]]` -> UniformConstant sampled image.
|
||||
@@ -438,8 +447,8 @@ pub enum KernRole {
|
||||
/// Scalar params receive component .x; vector params receive the full v3uint.
|
||||
ThreadgroupsPerGrid,
|
||||
/// `[[threads_per_grid]]` (`uint` or `uint3`) -> the selected kernel dispatch grid. Whole-
|
||||
/// workgroup dispatches derive it as NumWorkgroups * LocalSize; exact-thread dispatches share
|
||||
/// their fixed or push-constant bounds with invocation culling.
|
||||
/// workgroup dispatches derive it as NumWorkgroups * LocalSize; exact-thread dispatches read
|
||||
/// the complete logical grid from the region payload.
|
||||
ThreadsPerGrid,
|
||||
/// `[[threadgroup_position_in_grid]]` (`uint` or `uint3`) -> WorkgroupId.
|
||||
/// Scalar params receive component .x; vector params receive the full v3uint.
|
||||
@@ -473,6 +482,9 @@ pub enum KernRole {
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct KernMeta {
|
||||
pub roles: Vec<(u32, KernRole)>,
|
||||
/// Function-constant-wrapped buffer parameter index -> Metal buffer location. Multiple mutually
|
||||
/// exclusive typed alternatives may intentionally share one location.
|
||||
pub function_constant_buffer_locations: HashMap<u32, u32>,
|
||||
/// `param_idx -> reconstructed struct layout` for buffer args (see `FragMeta::buffer_layouts`).
|
||||
pub buffer_layouts: HashMap<u32, AirType>,
|
||||
/// `param_idx -> reconstructed air.imageblock_data layout` for imageblock args.
|
||||
@@ -625,6 +637,7 @@ fn parse_air_kernel_meta_with_nodes(
|
||||
let in_ref = *refs.get(1)?;
|
||||
|
||||
let mut roles = vec![];
|
||||
let mut function_constant_buffer_locations = HashMap::new();
|
||||
let mut buffer_layouts = HashMap::new();
|
||||
let mut imageblock_layouts = HashMap::new();
|
||||
let mut buffer_address_spaces = HashMap::new();
|
||||
@@ -645,9 +658,17 @@ fn parse_air_kernel_meta_with_nodes(
|
||||
let Some(idx) = first_i32(node) else { continue };
|
||||
let layout = struct_info_ref(node).and_then(|sref| parse_struct_info(nodes, sref, 0));
|
||||
let strs = role_strings(node);
|
||||
let Some(first) = fc_promoted_role(&strs, promote_fc_buffers) else {
|
||||
if strs.first().map(String::as_str) == Some("function_constant")
|
||||
&& primary_role(&strs) == Some("buffer")
|
||||
{
|
||||
function_constant_buffer_locations.insert(idx, resource_location(node, idx));
|
||||
}
|
||||
let Some(mut first) = fc_promoted_role(&strs, promote_fc_buffers) else {
|
||||
continue;
|
||||
};
|
||||
if primary_role(&strs) == Some("texture") && resource_location(node, idx) == u32::MAX {
|
||||
first = "function_constant";
|
||||
}
|
||||
let role = match first {
|
||||
"buffer" | "indirect_buffer" => {
|
||||
if first == "indirect_buffer" {
|
||||
@@ -681,7 +702,7 @@ fn parse_air_kernel_meta_with_nodes(
|
||||
if let Some(access) = declared_buffer_access(node) {
|
||||
buffer_accesses.insert(idx, access);
|
||||
}
|
||||
KernRole::Buffer(resource_location(node, idx))
|
||||
KernRole::Buffer(buffer_location_index(node, idx, &static_int_globals))
|
||||
}
|
||||
"texture" => {
|
||||
if let Some(name) = arg_type_name(node) {
|
||||
@@ -755,6 +776,7 @@ fn parse_air_kernel_meta_with_nodes(
|
||||
let implicit_imageblock_attachments = detect_implicit_imageblock_attachments(ll)?;
|
||||
Some(KernMeta {
|
||||
roles,
|
||||
function_constant_buffer_locations,
|
||||
buffer_layouts,
|
||||
imageblock_layouts,
|
||||
implicit_imageblock_attachments,
|
||||
@@ -1125,6 +1147,24 @@ fn location_index(body: &str, fallback: u32) -> u32 {
|
||||
i32_after_marker(body, "air.location_index").unwrap_or(fallback)
|
||||
}
|
||||
|
||||
fn buffer_location_index(
|
||||
body: &str,
|
||||
fallback: u32,
|
||||
static_int_globals: &HashMap<String, u32>,
|
||||
) -> u32 {
|
||||
if arg_type_name(body)
|
||||
.as_deref()
|
||||
.is_some_and(is_device_buffer_array_type_name)
|
||||
{
|
||||
// Metal flattens `array_ref<void>` into consecutive buffer-table arguments beginning at
|
||||
// the literal metadata location. Its static initializer computes the array extent/next
|
||||
// free slot, not a replacement binding for element zero.
|
||||
location_index(body, fallback)
|
||||
} else {
|
||||
location_index_with_static(body, fallback, static_int_globals)
|
||||
}
|
||||
}
|
||||
|
||||
fn render_target_location(
|
||||
body: &str,
|
||||
fallback: u32,
|
||||
@@ -1194,7 +1234,7 @@ fn function_constant_gate_global(body: &str, nodes: &HashMap<u32, String>) -> Op
|
||||
})
|
||||
}
|
||||
|
||||
fn output_metadata_enabled_by_default(
|
||||
fn metadata_enabled_by_default(
|
||||
body: &str,
|
||||
nodes: &HashMap<u32, String>,
|
||||
static_int_globals: &HashMap<String, u32>,
|
||||
@@ -1208,11 +1248,50 @@ fn output_metadata_enabled_by_default(
|
||||
.unwrap_or(true)
|
||||
}
|
||||
|
||||
/// Specialize metadata-only `air.function_constant` wrappers from statically evaluated AIR
|
||||
/// predicates. A true predicate exposes the wrapped role as unconditional. A false predicate is
|
||||
/// marked disabled so interface construction cannot retain an unreachable descriptor or output.
|
||||
/// Unknown predicates keep the wrapper and the ordinary unspecialized projection.
|
||||
pub(crate) fn specialize_function_constant_metadata(ll: &str) -> String {
|
||||
let nodes = collect_nodes(ll);
|
||||
let static_int_globals = static_init_int_global_values(ll);
|
||||
let marker = "!\"air.function_constant\"";
|
||||
let mut output = String::with_capacity(ll.len());
|
||||
|
||||
for line in ll.split_inclusive('\n') {
|
||||
let value = function_constant_gate_global(line, &nodes)
|
||||
.and_then(|global| static_int_globals.get(&global).copied());
|
||||
match value {
|
||||
Some(0) => {
|
||||
output.push_str(&line.replacen(marker, "!\"air.function_constant_disabled\"", 1))
|
||||
}
|
||||
Some(_) => {
|
||||
let rewritten = line.find(marker).and_then(|start| {
|
||||
let after_marker = &line[start + marker.len()..];
|
||||
let next_role = after_marker.find("!\"air.")?;
|
||||
Some(format!("{}{}", &line[..start], &after_marker[next_role..]))
|
||||
});
|
||||
if let Some(rewritten) = rewritten {
|
||||
output.push_str(&rewritten);
|
||||
} else {
|
||||
output.push_str(line);
|
||||
}
|
||||
}
|
||||
None => output.push_str(line),
|
||||
}
|
||||
}
|
||||
output
|
||||
}
|
||||
|
||||
/// Like `primary_role`, but only looks past the `air.function_constant` wrapper when the wrapped
|
||||
/// resource is a TEXTURE, IMAGEBLOCK, or BUFFER (the latter only when `promote_buffers` is set).
|
||||
/// resource is a TEXTURE, IMAGEBLOCK, FUNCTION TABLE, or BUFFER (the latter only when
|
||||
/// `promote_buffers` is set).
|
||||
/// An imageblock has no descriptor binding to promote; recognizing its stable ABI marker merely keeps
|
||||
/// its metadata-described cell type available to the native emitter. Promoting a wrapped texture is
|
||||
/// additive (it gains its own sampled/storage image binding). Promoting a wrapped BUFFER binds it as a
|
||||
/// its metadata-described cell type available to the native emitter. A wrapped texture with a real
|
||||
/// location remains a descriptor even when its predicate defaults false: SPIR-V specialization may
|
||||
/// enable the resource-using arm, and substituting another texture or erasing the binding would be
|
||||
/// semantically wrong. A `-1` location remains absent until AIR specialization assigns a binding.
|
||||
/// Promoting a wrapped BUFFER binds it as a
|
||||
/// REAL StorageBuffer instead of the "possibly-absent → Private zero placeholder" default; on the
|
||||
/// DEFAULT path this regresses byte-conformant goldens (a genuinely-absent fc buffer must stay Private,
|
||||
/// and the conditionally-present binding emits an invalid `ArrayStride`-decorated array-of-Block), so
|
||||
@@ -1227,6 +1306,8 @@ fn fc_promoted_role(strs: &[String], promote_buffers: bool) -> Option<&str> {
|
||||
return Some(match primary_role(strs) {
|
||||
Some("texture") => "texture",
|
||||
Some("imageblock") => "imageblock",
|
||||
Some("visible_function_table") => "visible_function_table",
|
||||
Some("intersection_function_table") => "intersection_function_table",
|
||||
Some("buffer") if promote_buffers => "buffer",
|
||||
_ => first,
|
||||
});
|
||||
@@ -1460,7 +1541,7 @@ fn parse_air_fragment_meta_with_nodes(
|
||||
let roles = role_strings(node);
|
||||
let is_render_target = primary_role(&roles) == Some("render_target");
|
||||
(is_render_target
|
||||
&& output_metadata_enabled_by_default(node, nodes, &static_int_globals))
|
||||
&& metadata_enabled_by_default(node, nodes, &static_int_globals))
|
||||
.then(|| {
|
||||
(
|
||||
i as u32,
|
||||
@@ -1481,9 +1562,8 @@ fn parse_air_fragment_meta_with_nodes(
|
||||
let node = nodes.get(&r)?;
|
||||
let roles = role_strings(node);
|
||||
let is_depth = primary_role(&roles) == Some("depth");
|
||||
(is_depth
|
||||
&& output_metadata_enabled_by_default(node, nodes, &static_int_globals))
|
||||
.then_some(i as u32)
|
||||
(is_depth && metadata_enabled_by_default(node, nodes, &static_int_globals))
|
||||
.then_some(i as u32)
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
@@ -1512,9 +1592,8 @@ fn parse_air_fragment_meta_with_nodes(
|
||||
let node = nodes.get(&r)?;
|
||||
let roles = role_strings(node);
|
||||
let is_stencil = primary_role(&roles) == Some("stencil");
|
||||
(is_stencil
|
||||
&& output_metadata_enabled_by_default(node, nodes, &static_int_globals))
|
||||
.then_some(i as u32)
|
||||
(is_stencil && metadata_enabled_by_default(node, nodes, &static_int_globals))
|
||||
.then_some(i as u32)
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
@@ -1535,7 +1614,7 @@ fn parse_air_fragment_meta_with_nodes(
|
||||
let roles = role_strings(node);
|
||||
let is_render_target = primary_role(&roles) == Some("render_target");
|
||||
if is_render_target
|
||||
&& output_metadata_enabled_by_default(node, nodes, &static_int_globals)
|
||||
&& metadata_enabled_by_default(node, nodes, &static_int_globals)
|
||||
{
|
||||
arg_type_name(node).map(|name| (i as u32, name))
|
||||
} else {
|
||||
@@ -1579,90 +1658,92 @@ fn parse_air_fragment_meta_with_nodes(
|
||||
let Some(role_str) = primary_role(&strs) else {
|
||||
continue;
|
||||
};
|
||||
let role =
|
||||
match role_str {
|
||||
"position" => FragRole::Position,
|
||||
"point_coord" => FragRole::PointCoord,
|
||||
"front_facing" => FragRole::FrontFacing,
|
||||
"primitive_id" => FragRole::PrimitiveId,
|
||||
"sample_id" => FragRole::SampleId,
|
||||
"viewport_array_index" => FragRole::ViewportArrayIndex,
|
||||
"fragment_input" => {
|
||||
let l = varying_loc;
|
||||
varying_loc += 1;
|
||||
if let Some(name) = arg_type_name(node) {
|
||||
varying_types.insert(l, name);
|
||||
}
|
||||
if let Some(name) = arg_name(node) {
|
||||
varying_names.insert(l, name);
|
||||
}
|
||||
if let Some(semantic) = string_after_marker(node, "air.fragment_input") {
|
||||
varying_user_semantics.insert(l, semantic);
|
||||
}
|
||||
if strs.iter().any(|s| s == "flat") {
|
||||
flat_varyings.insert(l);
|
||||
}
|
||||
FragRole::Varying(l)
|
||||
let role = match role_str {
|
||||
"position" => FragRole::Position,
|
||||
"point_coord" => FragRole::PointCoord,
|
||||
"front_facing" => FragRole::FrontFacing,
|
||||
"primitive_id" => FragRole::PrimitiveId,
|
||||
"sample_id" => FragRole::SampleId,
|
||||
"viewport_array_index" => FragRole::ViewportArrayIndex,
|
||||
"render_target_array_index" => FragRole::RenderTargetArrayIndex,
|
||||
"fragment_input" => {
|
||||
let l = varying_loc;
|
||||
varying_loc += 1;
|
||||
if let Some(name) = arg_type_name(node) {
|
||||
varying_types.insert(l, name);
|
||||
}
|
||||
"texture" => {
|
||||
if let Some(name) = arg_type_name(node) {
|
||||
texture_type_names.insert(idx, name);
|
||||
}
|
||||
FragRole::Texture(location_index_with_static(node, idx, &static_int_globals))
|
||||
if let Some(name) = arg_name(node) {
|
||||
varying_names.insert(l, name);
|
||||
}
|
||||
"sampler" => {
|
||||
FragRole::Sampler(location_index_with_static(node, idx, &static_int_globals))
|
||||
if let Some(semantic) = string_after_marker(node, "air.fragment_input") {
|
||||
varying_user_semantics.insert(l, semantic);
|
||||
}
|
||||
"visible_function_table" => FragRole::VisibleFunctionTable(
|
||||
location_index_with_static(node, idx, &static_int_globals),
|
||||
),
|
||||
"intersection_function_table" => FragRole::IntersectionFunctionTable(
|
||||
location_index_with_static(node, idx, &static_int_globals),
|
||||
),
|
||||
"buffer" | "indirect_buffer" => {
|
||||
if role_str == "indirect_buffer" {
|
||||
if let Some(sref) = struct_info_ref(node) {
|
||||
indirect_buffer_struct_refs.push((
|
||||
idx,
|
||||
location_index_with_static(node, idx, &static_int_globals),
|
||||
sref,
|
||||
));
|
||||
}
|
||||
}
|
||||
// Populate address space / declared size ONLY when the IR actually carries them
|
||||
// (no invented default), so reflection never reports a guessed value.
|
||||
if let Some(space) =
|
||||
address_space(node).or_else(|| param_address_spaces.get(&idx).copied())
|
||||
{
|
||||
buffer_address_spaces.insert(idx, space);
|
||||
}
|
||||
if let Some(size) = i32_after_marker(node, "air.arg_type_size")
|
||||
.or_else(|| i32_after_marker(node, "air.buffer_size"))
|
||||
{
|
||||
buffer_type_sizes.insert(idx, size);
|
||||
}
|
||||
if let Some(size) = i32_after_marker(node, "air.buffer_size") {
|
||||
buffer_object_sizes.insert(idx, size);
|
||||
}
|
||||
if let Some(name) = arg_type_name(node) {
|
||||
buffer_type_names.insert(idx, name);
|
||||
}
|
||||
if let Some(access) = declared_buffer_access(node) {
|
||||
buffer_accesses.insert(idx, access);
|
||||
}
|
||||
FragRole::Buffer(location_index_with_static(node, idx, &static_int_globals))
|
||||
if strs.iter().any(|s| s == "flat") {
|
||||
flat_varyings.insert(l);
|
||||
}
|
||||
// an air.render_target in the INPUT list = framebuffer fetch ([[color(n)]]).
|
||||
"render_target" => {
|
||||
let location = render_target_location(node, idx, &static_int_globals);
|
||||
if let Some(name) = arg_type_name(node) {
|
||||
color_input_type_names.insert(location, name);
|
||||
}
|
||||
FragRole::ColorInput(location)
|
||||
FragRole::Varying(l)
|
||||
}
|
||||
"texture" if location_index_with_static(node, idx, &static_int_globals) != u32::MAX => {
|
||||
if let Some(name) = arg_type_name(node) {
|
||||
texture_type_names.insert(idx, name);
|
||||
}
|
||||
"imageblock_data" => FragRole::ImageblockData,
|
||||
_ => FragRole::Other,
|
||||
};
|
||||
FragRole::Texture(location_index_with_static(node, idx, &static_int_globals))
|
||||
}
|
||||
"sampler" => {
|
||||
FragRole::Sampler(location_index_with_static(node, idx, &static_int_globals))
|
||||
}
|
||||
"visible_function_table" => FragRole::VisibleFunctionTable(location_index_with_static(
|
||||
node,
|
||||
idx,
|
||||
&static_int_globals,
|
||||
)),
|
||||
"intersection_function_table" => FragRole::IntersectionFunctionTable(
|
||||
location_index_with_static(node, idx, &static_int_globals),
|
||||
),
|
||||
"buffer" | "indirect_buffer" => {
|
||||
if role_str == "indirect_buffer" {
|
||||
if let Some(sref) = struct_info_ref(node) {
|
||||
indirect_buffer_struct_refs.push((
|
||||
idx,
|
||||
location_index_with_static(node, idx, &static_int_globals),
|
||||
sref,
|
||||
));
|
||||
}
|
||||
}
|
||||
// Populate address space / declared size ONLY when the IR actually carries them
|
||||
// (no invented default), so reflection never reports a guessed value.
|
||||
if let Some(space) =
|
||||
address_space(node).or_else(|| param_address_spaces.get(&idx).copied())
|
||||
{
|
||||
buffer_address_spaces.insert(idx, space);
|
||||
}
|
||||
if let Some(size) = i32_after_marker(node, "air.arg_type_size")
|
||||
.or_else(|| i32_after_marker(node, "air.buffer_size"))
|
||||
{
|
||||
buffer_type_sizes.insert(idx, size);
|
||||
}
|
||||
if let Some(size) = i32_after_marker(node, "air.buffer_size") {
|
||||
buffer_object_sizes.insert(idx, size);
|
||||
}
|
||||
if let Some(name) = arg_type_name(node) {
|
||||
buffer_type_names.insert(idx, name);
|
||||
}
|
||||
if let Some(access) = declared_buffer_access(node) {
|
||||
buffer_accesses.insert(idx, access);
|
||||
}
|
||||
FragRole::Buffer(buffer_location_index(node, idx, &static_int_globals))
|
||||
}
|
||||
// an air.render_target in the INPUT list = framebuffer fetch ([[color(n)]]).
|
||||
"render_target" => {
|
||||
let location = render_target_location(node, idx, &static_int_globals);
|
||||
if let Some(name) = arg_type_name(node) {
|
||||
color_input_type_names.insert(location, name);
|
||||
}
|
||||
FragRole::ColorInput(location)
|
||||
}
|
||||
"imageblock_data" => FragRole::ImageblockData,
|
||||
_ => FragRole::Other,
|
||||
};
|
||||
roles.push((idx, role));
|
||||
}
|
||||
let top_level_texture_locations = roles
|
||||
@@ -1758,7 +1839,9 @@ fn parse_air_vertex_meta_with_nodes(
|
||||
continue;
|
||||
};
|
||||
let role = match first {
|
||||
"function_constant" => VertOutRole::FunctionConstantDisabled,
|
||||
"function_constant" | "function_constant_disabled" => {
|
||||
VertOutRole::FunctionConstantDisabled
|
||||
}
|
||||
"position" => VertOutRole::Position,
|
||||
"point_size" => VertOutRole::PointSize,
|
||||
"clip_distance" => VertOutRole::ClipDistance,
|
||||
@@ -1817,6 +1900,11 @@ fn parse_air_vertex_meta_with_nodes(
|
||||
let Some(mut first) = fc_promoted_role(&strs, false) else {
|
||||
continue;
|
||||
};
|
||||
if primary_role(&strs) == Some("texture")
|
||||
&& location_index_with_static(node, idx, &static_int_globals) == u32::MAX
|
||||
{
|
||||
first = "function_constant";
|
||||
}
|
||||
if primary_role(&strs) == Some("patch_input") {
|
||||
first = "patch_input";
|
||||
}
|
||||
@@ -1862,7 +1950,7 @@ fn parse_air_vertex_meta_with_nodes(
|
||||
if let Some(access) = declared_buffer_access(node) {
|
||||
buffer_accesses.insert(idx, access);
|
||||
}
|
||||
VertRole::Buffer(location_index_with_static(node, idx, &static_int_globals))
|
||||
VertRole::Buffer(buffer_location_index(node, idx, &static_int_globals))
|
||||
}
|
||||
"texture" => {
|
||||
if let Some(name) = arg_type_name(node) {
|
||||
|
||||
+96
-1
@@ -43,10 +43,25 @@ fn fragment_flat_varying_metadata() {
|
||||
assert!(m.varying_is_flat(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fragment_render_target_array_index_role() {
|
||||
let ll = r#"
|
||||
!air.fragment = !{!0}
|
||||
!0 = !{ptr @F, !1, !3}
|
||||
!1 = !{!2}
|
||||
!2 = !{!"air.render_target", i32 0, i32 0}
|
||||
!3 = !{!4}
|
||||
!4 = !{i32 0, !"air.render_target_array_index", !"air.arg_type_name", !"ushort", !"air.arg_name", !"layer"}
|
||||
"#;
|
||||
let meta = parse_air_fragment_meta(ll).unwrap();
|
||||
assert_eq!(meta.role_of(0), Some(&FragRole::RenderTargetArrayIndex));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fragment_function_constant_location_uses_static_init_default() {
|
||||
let ll = r#"
|
||||
@_ZL32__metal_implicit_attr_int_expr_1.78 = internal addrspace(2) global i32 0, align 4
|
||||
@__metal_implicit_fc_pred_1.80 = internal addrspace(2) global i8 1, align 1
|
||||
@_ZN2RB6Shader8Constant13_shader_stateE.MTL_FC_INIT_0_Dv4_j = internal unnamed_addr addrspace(2) externally_initialized constant <4 x i32> undef, section "air.fc_initializer", align 16
|
||||
|
||||
define internal void @_GLOBAL__sub_I_shader_filter_distance.metal() section "air.static_init" {
|
||||
@@ -73,10 +88,11 @@ entry:
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kernel_function_constant_resource_locations_use_static_defaults() {
|
||||
fn kernel_function_constant_texture_with_valid_location_is_bound_when_disabled_by_default() {
|
||||
let ll = r#"
|
||||
@texture_location = internal addrspace(2) global i32 40, align 4
|
||||
@sampler_location = internal addrspace(2) global i32 15, align 4
|
||||
@texture_enabled = internal addrspace(2) global i8 0, align 1
|
||||
|
||||
define void @K(ptr addrspace(1) %texture, ptr addrspace(2) %sampler) {
|
||||
ret void
|
||||
@@ -95,6 +111,65 @@ define void @K(ptr addrspace(1) %texture, ptr addrspace(2) %sampler) {
|
||||
assert_eq!(meta.role_of(1), Some(&KernRole::Sampler(15)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn function_constant_texture_with_absent_location_is_not_bound() {
|
||||
let ll = r#"
|
||||
@texture_location = internal addrspace(2) global i32 -1, align 4
|
||||
@texture_enabled = internal addrspace(2) global i8 0, align 1
|
||||
|
||||
define void @K(ptr addrspace(1) %texture) {
|
||||
ret void
|
||||
}
|
||||
|
||||
!air.kernel = !{!0}
|
||||
!0 = !{ptr @K, !1, !2}
|
||||
!1 = !{}
|
||||
!2 = !{!3}
|
||||
!3 = !{i32 0, !"air.function_constant", !4, !"air.texture", !"air.location_index", ptr addrspace(2) @texture_location, i32 1, !"air.sample", !"air.arg_type_name", !"texture2d<float, sample>"}
|
||||
!4 = !{ptr addrspace(2) @texture_enabled, !"bool", !"texture_enabled"}
|
||||
"#;
|
||||
|
||||
let meta = parse_air_kernel_meta(ll).expect("kernel metadata");
|
||||
assert_eq!(meta.role_of(0), Some(&KernRole::Other));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kernel_function_constant_buffer_locations_preserve_shared_bindings() {
|
||||
let ll = r#"
|
||||
!air.kernel = !{!0}
|
||||
!0 = !{ptr @K, !1, !2}
|
||||
!1 = !{}
|
||||
!2 = !{!3, !4, !5}
|
||||
!3 = !{i32 0, !"air.function_constant", !6, !"air.buffer", !"air.location_index", i32 29}
|
||||
!4 = !{i32 1, !"air.function_constant", !7, !"air.buffer", !"air.location_index", i32 29}
|
||||
!5 = !{i32 2, !"air.buffer", !"air.location_index", i32 30}
|
||||
!6 = !{ptr addrspace(2) @float_enabled, !"bool", !"float_enabled"}
|
||||
!7 = !{ptr addrspace(2) @half_enabled, !"bool", !"half_enabled"}
|
||||
"#;
|
||||
|
||||
let meta = parse_air_kernel_meta(ll).expect("kernel metadata");
|
||||
assert_eq!(
|
||||
meta.function_constant_buffer_locations,
|
||||
HashMap::from([(0, 29), (1, 29)])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn device_buffer_array_uses_literal_base_instead_of_static_next_location() {
|
||||
let ll = r#"
|
||||
@next_buffer = internal addrspace(2) global i32 1, align 4
|
||||
|
||||
!air.kernel = !{!0}
|
||||
!0 = !{ptr @K, !1, !2}
|
||||
!1 = !{}
|
||||
!2 = !{!3}
|
||||
!3 = !{i32 0, !"air.buffer", !"air.location_index", i32 0, ptr addrspace(2) @next_buffer, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_name", !"array_ref<void>", !"air.arg_name", !"buffers"}
|
||||
"#;
|
||||
let meta = parse_air_kernel_meta(ll).expect("kernel metadata");
|
||||
assert_eq!(meta.role_of(0), Some(&KernRole::Buffer(0)));
|
||||
assert_eq!(meta.buffer_type_name(0), Some("array_ref<void>"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fragment_function_constant_render_target_disabled_by_default() {
|
||||
let ll = r#"
|
||||
@@ -273,6 +348,26 @@ fn vertex_builtin_roles() {
|
||||
assert_eq!(m.output_role_of(2), Some(&VertOutRole::ClipDistance));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn function_constant_wrapped_function_tables_keep_their_linkage_roles() {
|
||||
let ll = r#"
|
||||
!air.vertex = !{!0}
|
||||
!0 = !{ptr @main, !1, !2}
|
||||
!1 = !{}
|
||||
!2 = !{!3, !4}
|
||||
!3 = !{i32 0, !"air.function_constant", !5, !"air.visible_function_table", !"air.location_index", i32 7, i32 1, !"air.read"}
|
||||
!4 = !{i32 1, !"air.function_constant", !6, !"air.intersection_function_table", !"air.location_index", i32 8, i32 1, !"air.read"}
|
||||
!5 = !{ptr addrspace(2) @visible_enabled, !"bool", !"visible_enabled"}
|
||||
!6 = !{ptr addrspace(2) @intersection_enabled, !"bool", !"intersection_enabled"}
|
||||
"#;
|
||||
let meta = parse_air_vertex_meta(ll).unwrap();
|
||||
assert_eq!(meta.role_of(0), Some(&VertRole::VisibleFunctionTable(7)));
|
||||
assert_eq!(
|
||||
meta.role_of(1),
|
||||
Some(&VertRole::IntersectionFunctionTable(8))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vertex_patch_contract_preserves_domain_control_points_and_system_locations() {
|
||||
let ll = r#"
|
||||
|
||||
@@ -83,6 +83,7 @@ pub enum TextureFormat {
|
||||
R16f,
|
||||
R16ui,
|
||||
Rg16f,
|
||||
Rg32f,
|
||||
R32f,
|
||||
R32i,
|
||||
R32ui,
|
||||
@@ -104,6 +105,7 @@ impl TextureFormat {
|
||||
TextureFormat::R16f => ImageFormat::R16f,
|
||||
TextureFormat::R16ui => ImageFormat::R16ui,
|
||||
TextureFormat::Rg16f => ImageFormat::Rg16f,
|
||||
TextureFormat::Rg32f => ImageFormat::Rg32f,
|
||||
TextureFormat::R32f => ImageFormat::R32f,
|
||||
TextureFormat::R32i => ImageFormat::R32i,
|
||||
TextureFormat::R32ui => ImageFormat::R32ui,
|
||||
|
||||
+108
-25
@@ -20,6 +20,8 @@
|
||||
//! 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 _;
|
||||
|
||||
/// The 12-operand `air.simdgroup_async_copy_2d` call, decoded from its argument list.
|
||||
struct AsyncCopyCall {
|
||||
/// element size in bytes (operand 0): 4 → i32/float, 2 → i16/half.
|
||||
@@ -35,15 +37,28 @@ struct AsyncCopyCall {
|
||||
}
|
||||
|
||||
/// Rewrite every `air.simdgroup_async_copy_2d` / `air.get_null_simdgroup_event` /
|
||||
/// `air.is_null_simdgroup_event` / `air.wait_simdgroup_events` in `san_ll`. Returns the text unchanged
|
||||
/// when the module does not call the async-copy intrinsic (the common case).
|
||||
pub(crate) fn lower_simdgroup_async_copy(san_ll: &str) -> String {
|
||||
if !san_ll.contains("air.simdgroup_async_copy_2d") {
|
||||
return san_ll.to_string();
|
||||
/// `air.is_null_simdgroup_event` / `air.wait_simdgroup_events` in `san_ll`. Borrows the original text
|
||||
/// when the module does not call the async-copy intrinsic (the common case), so large modules do not
|
||||
/// retain a byte-identical full-source copy beside the typed parser.
|
||||
pub(crate) fn lower_simdgroup_async_copy(san_ll: &str) -> std::borrow::Cow<'_, str> {
|
||||
// The shared product prologue lowers calls before the emitter. It intentionally leaves the
|
||||
// now-dead intrinsic declaration in the module, so retry/emit entry points can see the symbol
|
||||
// without there being any work left to do. Test for an actual call line: treating a declaration
|
||||
// as work would clone and rejoin every line of a large already-lowered module on each emit tier.
|
||||
let has_copy_call = san_ll.lines().any(|line| {
|
||||
let trimmed = line.trim_start();
|
||||
trimmed.contains("air.simdgroup_async_copy_2d") && trimmed.contains("call")
|
||||
});
|
||||
if !has_copy_call {
|
||||
return std::borrow::Cow::Borrowed(san_ll);
|
||||
}
|
||||
|
||||
let mut elem_sizes: std::collections::BTreeSet<u32> = std::collections::BTreeSet::new();
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
// A lowered call expands one long intrinsic line into eight short ordinary-LLVM lines. Reserve
|
||||
// bounded growth once so a large module does not cross its original capacity by a few bytes and
|
||||
// make `String` retain an abandoned doubled buffer immediately before the typed parse peak.
|
||||
let rewrite_capacity = san_ll.len().saturating_add(san_ll.len() / 4);
|
||||
let mut out = LineBuffer::with_capacity(rewrite_capacity);
|
||||
let mut fresh = fresh_counter(san_ll);
|
||||
|
||||
for line in san_ll.lines() {
|
||||
@@ -58,7 +73,7 @@ pub(crate) fn lower_simdgroup_async_copy(san_ll: &str) -> String {
|
||||
}
|
||||
None => {
|
||||
// Unrecognized shape — leave it (the emitter will still error, no regression).
|
||||
out.push(line.to_string());
|
||||
out.push(line);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
@@ -67,7 +82,7 @@ pub(crate) fn lower_simdgroup_async_copy(san_ll: &str) -> String {
|
||||
// The event is always valid (the copy completed synchronously): is_null = false.
|
||||
if let Some(res) = call_result_id(trimmed) {
|
||||
let indent = &line[..line.len() - trimmed.len()];
|
||||
out.push(format!("{indent}{res} = icmp ne i64 0, 0"));
|
||||
out.push_fmt(format_args!("{indent}{res} = icmp ne i64 0, 0"));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
@@ -76,73 +91,119 @@ pub(crate) fn lower_simdgroup_async_copy(san_ll: &str) -> String {
|
||||
// carrier because event structs store it, while eliminating the now-unsupported call.
|
||||
if let Some(res) = call_result_id(trimmed) {
|
||||
let indent = &line[..line.len() - trimmed.len()];
|
||||
out.push(format!("{indent}{res} = inttoptr i64 0 to ptr"));
|
||||
out.push_fmt(format_args!("{indent}{res} = inttoptr i64 0 to ptr"));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if trimmed.contains("air.wait_simdgroup_events") && trimmed.contains("call") {
|
||||
// The copy is already complete in every thread; publish the threadgroup tile with a barrier.
|
||||
let indent = &line[..line.len() - trimmed.len()];
|
||||
out.push(format!("{indent}call void @air.wg.barrier(i32 2, i32 1)"));
|
||||
out.push_fmt(format_args!(
|
||||
"{indent}call void @air.wg.barrier(i32 2, i32 1)"
|
||||
));
|
||||
continue;
|
||||
}
|
||||
out.push(line.to_string());
|
||||
out.push(line);
|
||||
}
|
||||
|
||||
let mut result = out.join("\n");
|
||||
if san_ll.ends_with('\n') {
|
||||
result.push('\n');
|
||||
out.text.push('\n');
|
||||
}
|
||||
// Append the synthesized copy helpers (one per element size) and the barrier declaration if the
|
||||
// module did not already declare it.
|
||||
for &elem in &elem_sizes {
|
||||
result.push_str(&helper_definition(elem));
|
||||
out.text.push_str(&helper_definition(elem));
|
||||
}
|
||||
if !san_ll.contains("declare void @air.wg.barrier") {
|
||||
result.push_str("\ndeclare void @air.wg.barrier(i32, i32)\n");
|
||||
out.text
|
||||
.push_str("\ndeclare void @air.wg.barrier(i32, i32)\n");
|
||||
}
|
||||
std::borrow::Cow::Owned(out.text)
|
||||
}
|
||||
|
||||
/// Owned counterpart used when the caller can relinquish the source buffer. Once rewriting creates
|
||||
/// a replacement, returning it drops the superseded input before typed parsing begins; a no-op
|
||||
/// preserves and returns the original allocation unchanged.
|
||||
pub(crate) fn lower_simdgroup_async_copy_owned(san_ll: String) -> String {
|
||||
match lower_simdgroup_async_copy(&san_ll) {
|
||||
std::borrow::Cow::Borrowed(_) => san_ll,
|
||||
std::borrow::Cow::Owned(lowered) => lowered,
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// 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 Vec<String>, indent: &str, call: &AsyncCopyCall, fresh: &mut u64) {
|
||||
fn emit_copy_call(out: &mut LineBuffer, indent: &str, call: &AsyncCopyCall, fresh: &mut u64) {
|
||||
let mut id = || {
|
||||
let v = format!("%__ac{}", *fresh);
|
||||
*fresh += 1;
|
||||
v
|
||||
};
|
||||
let (dw, dh, sw, sh, ox, oy) = (id(), id(), id(), id(), id(), id());
|
||||
out.push(format!(
|
||||
out.push_fmt(format_args!(
|
||||
"{indent}{dw} = extractelement <2 x i64> {}, i64 0",
|
||||
call.dst_dims
|
||||
));
|
||||
out.push(format!(
|
||||
out.push_fmt(format_args!(
|
||||
"{indent}{dh} = extractelement <2 x i64> {}, i64 1",
|
||||
call.dst_dims
|
||||
));
|
||||
out.push(format!(
|
||||
out.push_fmt(format_args!(
|
||||
"{indent}{sw} = extractelement <2 x i64> {}, i64 0",
|
||||
call.src_dims
|
||||
));
|
||||
out.push(format!(
|
||||
out.push_fmt(format_args!(
|
||||
"{indent}{sh} = extractelement <2 x i64> {}, i64 1",
|
||||
call.src_dims
|
||||
));
|
||||
out.push(format!(
|
||||
out.push_fmt(format_args!(
|
||||
"{indent}{ox} = extractelement <2 x i64> {}, i64 0",
|
||||
call.offset
|
||||
));
|
||||
out.push(format!(
|
||||
out.push_fmt(format_args!(
|
||||
"{indent}{oy} = extractelement <2 x i64> {}, i64 1",
|
||||
call.offset
|
||||
));
|
||||
out.push(format!(
|
||||
out.push_fmt(format_args!(
|
||||
"{indent}call void @__metal2vulkan_sac2d_e{}(ptr addrspace(3) {}, i64 {}, i64 {dw}, i64 {dh}, ptr addrspace(1) {}, i64 {}, i64 {sw}, i64 {sh}, i64 {ox}, i64 {oy})",
|
||||
call.elem, call.dst, call.dst_epr, call.src, call.src_epr
|
||||
));
|
||||
// A non-null dummy for the event value the intrinsic returned.
|
||||
out.push(format!("{indent}{} = inttoptr i64 1 to ptr", call.result));
|
||||
out.push_fmt(format_args!(
|
||||
"{indent}{} = inttoptr i64 1 to ptr",
|
||||
call.result
|
||||
));
|
||||
}
|
||||
|
||||
/// The copy-loop helper for a given element size (bytes). Copies `dst_dims` (dw×dh) elements from
|
||||
@@ -288,6 +349,28 @@ fn fresh_counter(_san_ll: &str) -> u64 {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::lower_simdgroup_async_copy;
|
||||
use std::borrow::Cow;
|
||||
|
||||
#[test]
|
||||
fn no_async_copy_borrows_the_original_module() {
|
||||
let ll = "define void @k() {\nentry:\n ret void\n}\n";
|
||||
assert!(matches!(
|
||||
lower_simdgroup_async_copy(ll),
|
||||
Cow::Borrowed(value) if std::ptr::eq(value, ll)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dead_async_copy_declaration_borrows_the_already_lowered_module() {
|
||||
let ll = concat!(
|
||||
"define void @k() {\nentry:\n ret void\n}\n",
|
||||
"declare ptr @air.simdgroup_async_copy_2d.p3i8.p1i8(i64)\n",
|
||||
);
|
||||
assert!(matches!(
|
||||
lower_simdgroup_async_copy(ll),
|
||||
Cow::Borrowed(value) if std::ptr::eq(value, ll)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_null_event_lowers_with_the_async_copy_family() {
|
||||
|
||||
@@ -1,618 +0,0 @@
|
||||
//! Whole-buffer scalar-arm reconciliation for a cross-binding pointer merge.
|
||||
//!
|
||||
//! An FC-multiplexed kernel (e.g. the MPS Winograd weight transform) accesses a device buffer at
|
||||
//! CONFLICTING element types across its function-constant-dead template variants (a `device float*`
|
||||
//! view in the live variant, `half*`/`bfloat*`/`uchar*` views in the dead ones). The emitter cannot
|
||||
//! pick one pointee, so it models the buffer as a raw `{ RuntimeArray<uchar> }` block and forms the
|
||||
//! whole-buffer base as an `OpAccessChain %_ptr_StorageBuffer_uchar %buf %uint_0 %uint_0` (byte 0).
|
||||
//! After the FC dead arms are pruned, that byte-0 base is the FALLBACK arm of `OpSelect`/`OpPhi`
|
||||
//! merges whose result type is `%_ptr_StorageBuffer_float` and whose loads are `OpLoad %float` — so
|
||||
//! spirv-val rejects the merge: *"Expected both objects to be of Result Type"* (the float arm vs the
|
||||
//! uchar arm).
|
||||
//!
|
||||
//! This pass reconciles the mismatch: a StorageBuffer variable whose block is `{ RuntimeArray<E> }`,
|
||||
//! used ONLY through byte-0 whole-buffer base chains `[buf, 0, 0]` that feed ONLY pointer merges of a
|
||||
//! single DIFFERENT scalar pointee `T`, is retyped so its block is `{ RuntimeArray<T> }` and its base
|
||||
//! chains yield `%_ptr_StorageBuffer_T`. Byte-EXACT by construction: only element 0 (offset 0) is ever
|
||||
//! accessed, and `E`-element-0 and `T`-element-0 both start at byte 0. After this, the merge arms
|
||||
//! share the pointee type `T`; the remaining wall is that the two arms point into DISTINCT bindings —
|
||||
//! a cross-binding merge the PSB pass ([`super::psb`]) then lowers to PhysicalStorageBuffer64.
|
||||
//!
|
||||
//! Applied only in `lib.rs`'s adopt-if-VALIDATES `fc_promote_psb` retry (feeding PSB), so floor-safe
|
||||
//! by construction. Decides purely from IR structure (storage class, block shape, the byte-0 base
|
||||
//! chain, the uniform merge pointee) — never a shader name. New types are synthesized fresh; no
|
||||
//! existing (possibly-shared) `RuntimeArray`/struct/pointer type is mutated in place.
|
||||
|
||||
use crate::spirv_module::Instruction;
|
||||
use crate::spirv_module::Module;
|
||||
use crate::spirv_module::Operand;
|
||||
use spirv::{Decoration, Op, StorageClass, Word};
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// A buffer to retype: its variable, byte-0 base chains, target scalar pointee `T`, and `T`'s size in
|
||||
/// bytes (precomputed during discovery so the rewrite stage needs no type lookups).
|
||||
struct Retype {
|
||||
var: Word,
|
||||
base_chains: Vec<Word>,
|
||||
target: Word, // pointee scalar T
|
||||
target_bytes: u32,
|
||||
}
|
||||
|
||||
/// The two synthesized pointer types a plan's rewrite installs: the struct pointer for the variable
|
||||
/// and the `T` pointer for its byte-0 base chains.
|
||||
struct PlanTypes {
|
||||
ptr_struct: Word,
|
||||
ptr_t: Word,
|
||||
}
|
||||
|
||||
/// Reconcile whole-buffer scalar fallback arms as described above. Returns true if any buffer was
|
||||
/// retyped. Three stages: discover the retype plans (pure), then for each plan synthesize its fresh
|
||||
/// types and repoint the module.
|
||||
pub(super) fn reconcile_whole_buffer_scalar_arms(module: &mut Module) -> bool {
|
||||
let plans = discover_reconcile_plans(module);
|
||||
if plans.is_empty() {
|
||||
return false;
|
||||
}
|
||||
|
||||
let mut next_id = module.header.as_ref().map(|h| h.bound).unwrap_or(1);
|
||||
for plan in &plans {
|
||||
let types = synthesize_plan_types(module, plan, &mut next_id);
|
||||
repoint_plan(module, plan, &types);
|
||||
}
|
||||
|
||||
// The new struct/pointer types are appended at the END of `types_global_values`, but the repointed
|
||||
// `OpVariable`s appear earlier — an illegal forward type reference. A module-scope type/constant
|
||||
// never depends on an `OpVariable`, so stably moving every `OpVariable` to the end (relative order
|
||||
// preserved) guarantees each variable's (pointer) type precedes it, with no other ordering change.
|
||||
module
|
||||
.types_global_values
|
||||
.sort_by_key(|i| i.class.opcode == Op::Variable);
|
||||
|
||||
if let Some(h) = module.header.as_mut() {
|
||||
h.bound = next_id;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Discovery + validation (pure): every StorageBuffer variable safe to retype and the scalar pointee
|
||||
/// to retype it to, per the structural criteria in the module doc. No mutation.
|
||||
fn discover_reconcile_plans(module: &Module) -> Vec<Retype> {
|
||||
let type_defs: HashMap<Word, Instruction> = module
|
||||
.types_global_values
|
||||
.iter()
|
||||
.filter_map(|i| i.result_id.map(|id| (id, i.clone())))
|
||||
.collect();
|
||||
|
||||
// (storage class, pointee) of a pointer type.
|
||||
let ptr_info = |ty: Word| -> Option<(StorageClass, Word)> {
|
||||
let inst = type_defs.get(&ty)?;
|
||||
if inst.class.opcode != Op::TypePointer {
|
||||
return None;
|
||||
}
|
||||
match (inst.operands.first()?, inst.operands.get(1)?) {
|
||||
(Operand::StorageClass(s), Operand::IdRef(p)) => Some((*s, *p)),
|
||||
_ => None,
|
||||
}
|
||||
};
|
||||
// The single runtimearray-element type of a `{ RuntimeArray<E> }` struct pointee, else None.
|
||||
let single_runtime_array_elem = |struct_ty: Word| -> Option<Word> {
|
||||
let s = type_defs.get(&struct_ty)?;
|
||||
if s.class.opcode != Op::TypeStruct || s.operands.len() != 1 {
|
||||
return None;
|
||||
}
|
||||
let Operand::IdRef(member) = s.operands.first()? else {
|
||||
return None;
|
||||
};
|
||||
let ra = type_defs.get(member)?;
|
||||
if ra.class.opcode != Op::TypeRuntimeArray {
|
||||
return None;
|
||||
}
|
||||
match ra.operands.first()? {
|
||||
Operand::IdRef(elem) => Some(*elem),
|
||||
_ => None,
|
||||
}
|
||||
};
|
||||
let is_scalar = |ty: Word| -> bool {
|
||||
type_defs
|
||||
.get(&ty)
|
||||
.is_some_and(|i| matches!(i.class.opcode, Op::TypeInt | Op::TypeFloat))
|
||||
};
|
||||
let scalar_bytes = |ty: Word| -> Option<u32> {
|
||||
match type_defs.get(&ty)?.operands.first()? {
|
||||
Operand::LiteralBit32(bits) => Some(bits / 8),
|
||||
_ => None,
|
||||
}
|
||||
};
|
||||
|
||||
// Constant-zero uint ids (for the byte-0 base chain `[buf, 0, 0]`).
|
||||
let zero_consts: std::collections::HashSet<Word> = module
|
||||
.types_global_values
|
||||
.iter()
|
||||
.filter(|i| i.class.opcode == Op::Constant)
|
||||
.filter_map(|i| match i.operands.first()? {
|
||||
Operand::LiteralBit32(0) => i.result_id,
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Result-type of every merge (OpSelect/OpPhi) result id, and the merge's pointee if a pointer.
|
||||
// Also: for each value id used as a merge arm, the merge result pointee (for uniformity check).
|
||||
let mut merge_arm_pointee: HashMap<Word, Vec<Word>> = HashMap::new();
|
||||
for f in &module.functions {
|
||||
for b in &f.blocks {
|
||||
for inst in &b.instructions {
|
||||
if !matches!(inst.class.opcode, Op::Select | Op::Phi) {
|
||||
continue;
|
||||
}
|
||||
let Some(rt) = inst.result_type else { continue };
|
||||
let Some((_, pointee)) = ptr_info(rt) else {
|
||||
continue;
|
||||
};
|
||||
// Operand ids that are pointer arms: for Select they are operands 1,2; for Phi the
|
||||
// even-indexed operands (value, parent, value, parent, …). Record the merge pointee
|
||||
// against each arm id.
|
||||
match inst.class.opcode {
|
||||
Op::Select => {
|
||||
for op in inst.operands.iter().skip(1) {
|
||||
if let Operand::IdRef(a) = op {
|
||||
merge_arm_pointee.entry(*a).or_default().push(pointee);
|
||||
}
|
||||
}
|
||||
}
|
||||
Op::Phi => {
|
||||
for (k, op) in inst.operands.iter().enumerate() {
|
||||
if k % 2 == 0 {
|
||||
if let Operand::IdRef(a) = op {
|
||||
merge_arm_pointee.entry(*a).or_default().push(pointee);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Every operand USE of a value id across all function bodies (to prove a base chain is used ONLY as
|
||||
// a merge arm, and a buffer var ONLY as byte-0 base chains).
|
||||
let mut all_uses: HashMap<Word, usize> = HashMap::new();
|
||||
let mut base_chains_of: HashMap<Word, Vec<Word>> = HashMap::new(); // buffer var -> its base chain ids
|
||||
for f in &module.functions {
|
||||
for b in &f.blocks {
|
||||
for inst in &b.instructions {
|
||||
for op in &inst.operands {
|
||||
if let Operand::IdRef(id) = op {
|
||||
*all_uses.entry(*id).or_default() += 1;
|
||||
}
|
||||
}
|
||||
if matches!(inst.class.opcode, Op::AccessChain | Op::InBoundsAccessChain) {
|
||||
// base chain shape: [buf, zero, zero]
|
||||
if inst.operands.len() == 3 {
|
||||
if let (
|
||||
Some(Operand::IdRef(buf)),
|
||||
Some(Operand::IdRef(i0)),
|
||||
Some(Operand::IdRef(i1)),
|
||||
) = (
|
||||
inst.operands.first(),
|
||||
inst.operands.get(1),
|
||||
inst.operands.get(2),
|
||||
) {
|
||||
if zero_consts.contains(i0) && zero_consts.contains(i1) {
|
||||
if let Some(rid) = inst.result_id {
|
||||
base_chains_of.entry(*buf).or_default().push(rid);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Candidate buffers: module-scope StorageBuffer variables with a `{ RuntimeArray<scalar E> }`
|
||||
// pointee, whose EVERY function-body use is a byte-0 base chain, and whose base chains feed ONLY
|
||||
// pointer merges of a single scalar pointee T != E.
|
||||
let mut plans: Vec<Retype> = vec![];
|
||||
for inst in &module.types_global_values {
|
||||
if inst.class.opcode != Op::Variable {
|
||||
continue;
|
||||
}
|
||||
let Some(var) = inst.result_id else { continue };
|
||||
let Some(var_ty) = inst.result_type else {
|
||||
continue;
|
||||
};
|
||||
let Some((StorageClass::StorageBuffer, struct_ty)) = ptr_info(var_ty) else {
|
||||
continue;
|
||||
};
|
||||
let Some(elem) = single_runtime_array_elem(struct_ty) else {
|
||||
continue;
|
||||
};
|
||||
if !is_scalar(elem) {
|
||||
continue;
|
||||
}
|
||||
let Some(base_chains) = base_chains_of.get(&var) else {
|
||||
continue;
|
||||
};
|
||||
if base_chains.is_empty() {
|
||||
continue;
|
||||
}
|
||||
// Every function-body use of the var must be one of its byte-0 base chains (one operand use per
|
||||
// chain access-chain instruction).
|
||||
let var_uses = *all_uses.get(&var).unwrap_or(&0);
|
||||
if var_uses != base_chains.len() {
|
||||
continue;
|
||||
}
|
||||
// Every base chain must be used ONLY as merge arms, and all those merges must share ONE scalar
|
||||
// pointee T != E.
|
||||
let mut target: Option<Word> = None;
|
||||
let mut ok = true;
|
||||
for &bc in base_chains {
|
||||
let uses = *all_uses.get(&bc).unwrap_or(&0);
|
||||
let Some(pointees) = merge_arm_pointee.get(&bc) else {
|
||||
ok = false;
|
||||
break;
|
||||
};
|
||||
// chain used somewhere other than as a merge arm → bail
|
||||
if uses != pointees.len() {
|
||||
ok = false;
|
||||
break;
|
||||
}
|
||||
for &p in pointees {
|
||||
if p == elem || !is_scalar(p) {
|
||||
ok = false;
|
||||
break;
|
||||
}
|
||||
match target {
|
||||
None => target = Some(p),
|
||||
Some(t) if t == p => {}
|
||||
Some(_) => {
|
||||
ok = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if !ok {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let (Some(target), true) = (target, ok) else {
|
||||
continue;
|
||||
};
|
||||
// Both E and T must be sized scalars (they are, checked is_scalar) and the base chain's declared
|
||||
// result pointee must be E (sanity).
|
||||
if scalar_bytes(target).is_none() || scalar_bytes(elem).is_none() {
|
||||
continue;
|
||||
}
|
||||
plans.push(Retype {
|
||||
var,
|
||||
base_chains: base_chains.clone(),
|
||||
target,
|
||||
// `scalar_bytes(target)` is Some here (checked just above); precompute the stride so the
|
||||
// rewrite stage carries no type lookups.
|
||||
target_bytes: scalar_bytes(target).unwrap(),
|
||||
});
|
||||
}
|
||||
|
||||
plans
|
||||
}
|
||||
|
||||
/// Find an existing `%_ptr_StorageBuffer_<pointee>` type, if the module already declares one.
|
||||
fn find_storage_buffer_ptr(module: &Module, pointee: Word) -> Option<Word> {
|
||||
module.types_global_values.iter().find_map(|i| {
|
||||
if i.class.opcode == Op::TypePointer
|
||||
&& i.operands.first() == Some(&Operand::StorageClass(StorageClass::StorageBuffer))
|
||||
&& i.operands.get(1) == Some(&Operand::IdRef(pointee))
|
||||
{
|
||||
i.result_id
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Type synthesis (mutating): append the `RuntimeArray<T>` (reused iff it already carries the matching
|
||||
/// ArrayStride), the fresh `{ RuntimeArray<T> }` Block struct, and the two pointer types this plan
|
||||
/// installs. `next_id` threads the module's fresh-id counter across plans.
|
||||
fn synthesize_plan_types(module: &mut Module, plan: &Retype, next_id: &mut u32) -> PlanTypes {
|
||||
let t = plan.target;
|
||||
let stride = plan.target_bytes;
|
||||
let mut fresh = || {
|
||||
let id = *next_id;
|
||||
*next_id += 1;
|
||||
id
|
||||
};
|
||||
|
||||
// RuntimeArray<T> with ArrayStride = size(T). Reuse an existing one iff it already carries the
|
||||
// matching ArrayStride; else synthesize fresh (never mutate a possibly-shared existing RA).
|
||||
let ra_id = module
|
||||
.types_global_values
|
||||
.iter()
|
||||
.find_map(|i| {
|
||||
if i.class.opcode == Op::TypeRuntimeArray
|
||||
&& i.operands.first() == Some(&Operand::IdRef(t))
|
||||
{
|
||||
let rid = i.result_id?;
|
||||
let has_stride = module.annotations.iter().any(|a| {
|
||||
a.class.opcode == Op::Decorate
|
||||
&& a.operands.first() == Some(&Operand::IdRef(rid))
|
||||
&& a.operands.get(1) == Some(&Operand::Decoration(Decoration::ArrayStride))
|
||||
&& a.operands.get(2) == Some(&Operand::LiteralBit32(stride))
|
||||
});
|
||||
if has_stride {
|
||||
Some(rid)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.unwrap_or_else(|| {
|
||||
let id = fresh();
|
||||
module.types_global_values.push(Instruction::new(
|
||||
Op::TypeRuntimeArray,
|
||||
None,
|
||||
Some(id),
|
||||
vec![Operand::IdRef(t)],
|
||||
));
|
||||
module.annotations.push(Instruction::new(
|
||||
Op::Decorate,
|
||||
None,
|
||||
None,
|
||||
vec![
|
||||
Operand::IdRef(id),
|
||||
Operand::Decoration(Decoration::ArrayStride),
|
||||
Operand::LiteralBit32(stride),
|
||||
],
|
||||
));
|
||||
id
|
||||
});
|
||||
|
||||
// Fresh `{ RuntimeArray<T> }` Block struct (member 0 at Offset 0).
|
||||
let struct_id = fresh();
|
||||
module.types_global_values.push(Instruction::new(
|
||||
Op::TypeStruct,
|
||||
None,
|
||||
Some(struct_id),
|
||||
vec![Operand::IdRef(ra_id)],
|
||||
));
|
||||
module.annotations.push(Instruction::new(
|
||||
Op::MemberDecorate,
|
||||
None,
|
||||
None,
|
||||
vec![
|
||||
Operand::IdRef(struct_id),
|
||||
Operand::LiteralBit32(0),
|
||||
Operand::Decoration(Decoration::Offset),
|
||||
Operand::LiteralBit32(0),
|
||||
],
|
||||
));
|
||||
module.annotations.push(Instruction::new(
|
||||
Op::Decorate,
|
||||
None,
|
||||
None,
|
||||
vec![
|
||||
Operand::IdRef(struct_id),
|
||||
Operand::Decoration(Decoration::Block),
|
||||
],
|
||||
));
|
||||
|
||||
// Pointer to the new struct (for the variable), and pointer to T (for the base chains).
|
||||
let ptr_struct = fresh();
|
||||
module.types_global_values.push(Instruction::new(
|
||||
Op::TypePointer,
|
||||
None,
|
||||
Some(ptr_struct),
|
||||
vec![
|
||||
Operand::StorageClass(StorageClass::StorageBuffer),
|
||||
Operand::IdRef(struct_id),
|
||||
],
|
||||
));
|
||||
let ptr_t = find_storage_buffer_ptr(module, t).unwrap_or_else(|| {
|
||||
let id = fresh();
|
||||
module.types_global_values.push(Instruction::new(
|
||||
Op::TypePointer,
|
||||
None,
|
||||
Some(id),
|
||||
vec![
|
||||
Operand::StorageClass(StorageClass::StorageBuffer),
|
||||
Operand::IdRef(t),
|
||||
],
|
||||
));
|
||||
id
|
||||
});
|
||||
|
||||
PlanTypes { ptr_struct, ptr_t }
|
||||
}
|
||||
|
||||
/// Rewrite (mutating): repoint the buffer variable to the new struct pointer and each byte-0 base
|
||||
/// chain to the new `T` pointer.
|
||||
fn repoint_plan(module: &mut Module, plan: &Retype, types: &PlanTypes) {
|
||||
for inst in &mut module.types_global_values {
|
||||
if inst.result_id == Some(plan.var) {
|
||||
inst.result_type = Some(types.ptr_struct);
|
||||
}
|
||||
}
|
||||
for f in &mut module.functions {
|
||||
for b in &mut f.blocks {
|
||||
for inst in &mut b.instructions {
|
||||
if let Some(rid) = inst.result_id {
|
||||
if plan.base_chains.contains(&rid) {
|
||||
inst.result_type = Some(types.ptr_t);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::spirv_module::{Block, Function, ModuleHeader};
|
||||
|
||||
fn ti(op: Op, rt: Option<Word>, rid: Option<Word>, ops: Vec<Operand>) -> Instruction {
|
||||
Instruction::new(op, rt, rid, ops)
|
||||
}
|
||||
|
||||
/// A StorageBuffer buffer whose block is `{ RuntimeArray<uchar> }`, used only through a byte-0
|
||||
/// whole-buffer base chain that feeds an `OpSelect` of pointee `float`, is retyped to a
|
||||
/// `{ RuntimeArray<float> }` block with a `float*` base chain — the merge arms then share `float*`.
|
||||
#[test]
|
||||
fn reconciles_byte0_uchar_arm_to_float_merge_pointee() {
|
||||
// ids: 1 uint, 2 float, 3 uchar, 4 uint_0, 5 ra_uchar, 6 struct_v, 7 ptr_sb_struct_v,
|
||||
// 8 ra_float, 9 struct_w, 10 ptr_sb_struct_w, 11 ptr_sb_uchar, 12 ptr_sb_float, 13 bool,
|
||||
// 14 true, 15 V, 16 W, 20 base_v, 21 elem_w, 22 sel, 23 val
|
||||
let mut m = Module::new();
|
||||
m.header = Some(ModuleHeader::new(30));
|
||||
let sb = || Operand::StorageClass(StorageClass::StorageBuffer);
|
||||
m.types_global_values = vec![
|
||||
ti(
|
||||
Op::TypeInt,
|
||||
None,
|
||||
Some(1),
|
||||
vec![Operand::LiteralBit32(32), Operand::LiteralBit32(0)],
|
||||
),
|
||||
ti(
|
||||
Op::TypeFloat,
|
||||
None,
|
||||
Some(2),
|
||||
vec![Operand::LiteralBit32(32)],
|
||||
),
|
||||
ti(
|
||||
Op::TypeInt,
|
||||
None,
|
||||
Some(3),
|
||||
vec![Operand::LiteralBit32(8), Operand::LiteralBit32(0)],
|
||||
),
|
||||
ti(
|
||||
Op::Constant,
|
||||
Some(1),
|
||||
Some(4),
|
||||
vec![Operand::LiteralBit32(0)],
|
||||
),
|
||||
ti(Op::TypeRuntimeArray, None, Some(5), vec![Operand::IdRef(3)]),
|
||||
ti(Op::TypeStruct, None, Some(6), vec![Operand::IdRef(5)]),
|
||||
ti(
|
||||
Op::TypePointer,
|
||||
None,
|
||||
Some(7),
|
||||
vec![sb(), Operand::IdRef(6)],
|
||||
),
|
||||
ti(Op::TypeRuntimeArray, None, Some(8), vec![Operand::IdRef(2)]),
|
||||
ti(Op::TypeStruct, None, Some(9), vec![Operand::IdRef(8)]),
|
||||
ti(
|
||||
Op::TypePointer,
|
||||
None,
|
||||
Some(10),
|
||||
vec![sb(), Operand::IdRef(9)],
|
||||
),
|
||||
ti(
|
||||
Op::TypePointer,
|
||||
None,
|
||||
Some(11),
|
||||
vec![sb(), Operand::IdRef(3)],
|
||||
),
|
||||
ti(
|
||||
Op::TypePointer,
|
||||
None,
|
||||
Some(12),
|
||||
vec![sb(), Operand::IdRef(2)],
|
||||
),
|
||||
ti(Op::TypeBool, None, Some(13), vec![]),
|
||||
ti(Op::ConstantTrue, Some(13), Some(14), vec![]),
|
||||
ti(Op::Variable, Some(7), Some(15), vec![sb()]),
|
||||
ti(Op::Variable, Some(10), Some(16), vec![sb()]),
|
||||
];
|
||||
// ArrayStride 4 on the existing float runtimearray, so reconcile reuses it.
|
||||
m.annotations = vec![ti(
|
||||
Op::Decorate,
|
||||
None,
|
||||
None,
|
||||
vec![
|
||||
Operand::IdRef(8),
|
||||
Operand::Decoration(Decoration::ArrayStride),
|
||||
Operand::LiteralBit32(4),
|
||||
],
|
||||
)];
|
||||
let mut block = Block::new();
|
||||
block.label = Some(ti(Op::Label, None, Some(19), vec![]));
|
||||
block.instructions = vec![
|
||||
ti(
|
||||
Op::AccessChain,
|
||||
Some(11),
|
||||
Some(20),
|
||||
vec![Operand::IdRef(15), Operand::IdRef(4), Operand::IdRef(4)],
|
||||
),
|
||||
ti(
|
||||
Op::AccessChain,
|
||||
Some(12),
|
||||
Some(21),
|
||||
vec![Operand::IdRef(16), Operand::IdRef(4), Operand::IdRef(4)],
|
||||
),
|
||||
ti(
|
||||
Op::Select,
|
||||
Some(12),
|
||||
Some(22),
|
||||
vec![Operand::IdRef(14), Operand::IdRef(21), Operand::IdRef(20)],
|
||||
),
|
||||
ti(Op::Load, Some(2), Some(23), vec![Operand::IdRef(22)]),
|
||||
ti(Op::Return, None, None, vec![]),
|
||||
];
|
||||
let mut f = Function::new();
|
||||
f.blocks = vec![block];
|
||||
m.functions = vec![f];
|
||||
|
||||
assert!(reconcile_whole_buffer_scalar_arms(&mut m));
|
||||
|
||||
// V (%15) now points at a struct whose single runtimearray element is float (%2).
|
||||
let var_ty = m
|
||||
.types_global_values
|
||||
.iter()
|
||||
.find(|i| i.result_id == Some(15))
|
||||
.and_then(|i| i.result_type)
|
||||
.expect("V typed");
|
||||
let elem = single_runtime_array_elem_in(&m, ptr_pointee_in(&m, var_ty).expect("ptr"))
|
||||
.expect("runtime array");
|
||||
assert_eq!(elem, 2, "V block runtimearray must be retyped to float");
|
||||
// The base chain (%20) now yields `float*` (%12), matching the merge's `float*` arm.
|
||||
let base_ty = m.functions[0].blocks[0]
|
||||
.instructions
|
||||
.iter()
|
||||
.find(|i| i.result_id == Some(20))
|
||||
.and_then(|i| i.result_type)
|
||||
.expect("base chain typed");
|
||||
assert_eq!(base_ty, 12, "byte-0 base chain must be retyped to float*");
|
||||
}
|
||||
|
||||
fn ptr_pointee_in(m: &Module, ty: Word) -> Option<Word> {
|
||||
m.types_global_values.iter().find_map(|i| {
|
||||
if i.result_id == Some(ty) && i.class.opcode == Op::TypePointer {
|
||||
match i.operands.get(1) {
|
||||
Some(Operand::IdRef(p)) => Some(*p),
|
||||
_ => None,
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
}
|
||||
fn single_runtime_array_elem_in(m: &Module, struct_ty: Word) -> Option<Word> {
|
||||
let s = m
|
||||
.types_global_values
|
||||
.iter()
|
||||
.find(|i| i.result_id == Some(struct_ty))?;
|
||||
let Operand::IdRef(member) = s.operands.first()? else {
|
||||
return None;
|
||||
};
|
||||
let ra = m
|
||||
.types_global_values
|
||||
.iter()
|
||||
.find(|i| i.result_id == Some(*member))?;
|
||||
match ra.operands.first()? {
|
||||
Operand::IdRef(elem) => Some(*elem),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
+311
-43
@@ -13,8 +13,9 @@ const SWITCH_BLOCK_PREFIX: &str = "%metal2vulkan_switch_";
|
||||
/// string, so it lives here once and is shared.
|
||||
pub(in crate::native) const SWITCH_BYPASS_PREFIX: &str = "%metal2vulkan_switch_bypass_";
|
||||
|
||||
pub(in crate::native) fn split_body_blocks(
|
||||
lines: &[String],
|
||||
#[cfg(test)]
|
||||
pub(in crate::native) fn split_body_blocks<S: AsRef<str>>(
|
||||
lines: &[S],
|
||||
entry_name: String,
|
||||
named_types: &HashMap<String, LlType>,
|
||||
) -> Vec<BodyBlock> {
|
||||
@@ -26,6 +27,7 @@ pub(in crate::native) fn split_body_blocks(
|
||||
let mut cur_name = entry_name;
|
||||
let mut cur_lines: Vec<String> = Vec::new();
|
||||
for line in lines {
|
||||
let line = line.as_ref();
|
||||
let trimmed = strip_comment(line).trim();
|
||||
if trimmed.is_empty() {
|
||||
continue;
|
||||
@@ -44,7 +46,7 @@ pub(in crate::native) fn split_body_blocks(
|
||||
cur_name = format!("%{label}");
|
||||
cur_lines = Vec::new();
|
||||
} else {
|
||||
cur_lines.push(line.clone());
|
||||
cur_lines.push(line.to_string());
|
||||
}
|
||||
}
|
||||
let typed =
|
||||
@@ -57,6 +59,63 @@ pub(in crate::native) fn split_body_blocks(
|
||||
blocks
|
||||
}
|
||||
|
||||
/// Split a source function body directly from the module's borrowed line index. Only the current
|
||||
/// basic block is staged, and ordinary instruction lines remain borrowed; a multiline `switch` is
|
||||
/// the sole owned text because its cases must be joined for the terminator parser. This is the
|
||||
/// bounded-memory production parse path for large generated modules.
|
||||
pub(in crate::native) fn split_source_body_blocks(
|
||||
lines: &[&str],
|
||||
entry_name: String,
|
||||
named_types: &HashMap<String, LlType>,
|
||||
) -> Result<Vec<BodyBlock>, String> {
|
||||
use std::borrow::Cow;
|
||||
|
||||
let mut blocks = Vec::new();
|
||||
let mut cur_name = entry_name;
|
||||
let mut cur_lines: Vec<Cow<'_, str>> = Vec::new();
|
||||
let mut index = 0;
|
||||
while index < lines.len() {
|
||||
let raw = lines[index];
|
||||
let trimmed = strip_comment(raw).trim();
|
||||
if trimmed.is_empty() {
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
if let Some(label) = trimmed.strip_suffix(':') {
|
||||
if !cur_lines.is_empty() || !blocks.is_empty() {
|
||||
let typed =
|
||||
crate::native::tir::lower_block_carrier(&cur_name, &cur_lines, named_types)
|
||||
.map(Into::into);
|
||||
blocks.push(BodyBlock {
|
||||
name: cur_name,
|
||||
role: BlockRole::Normal,
|
||||
typed,
|
||||
});
|
||||
}
|
||||
cur_name = format!("%{label}");
|
||||
cur_lines.clear();
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
if trimmed.starts_with("switch ") {
|
||||
let (switch, next) = crate::native::parse::collect_switch(lines, index)?;
|
||||
cur_lines.push(Cow::Owned(switch));
|
||||
index = next;
|
||||
continue;
|
||||
}
|
||||
cur_lines.push(Cow::Borrowed(raw));
|
||||
index += 1;
|
||||
}
|
||||
let typed =
|
||||
crate::native::tir::lower_block_carrier(&cur_name, &cur_lines, named_types).map(Into::into);
|
||||
blocks.push(BodyBlock {
|
||||
name: cur_name,
|
||||
role: BlockRole::Normal,
|
||||
typed,
|
||||
});
|
||||
Ok(blocks)
|
||||
}
|
||||
|
||||
/// Build a synthesized [`BodyBlock`] with its `typed` carrier populated from its own `lines`. For the
|
||||
/// scaffolding blocks the structurizer synthesizes (`br`/`ret`/`phi` over primitive, vector, or pointer
|
||||
/// SSA values), the module named-type table is not needed — those never carry an `extractvalue` into a
|
||||
@@ -411,6 +470,33 @@ pub(in crate::native) fn infer_branch_merges(
|
||||
merges
|
||||
}
|
||||
|
||||
/// Index pair-keyed conditional merge ownership by the header that emits it.
|
||||
///
|
||||
/// Heuristic inference historically retained only `(true_arm, false_arm) -> merge`, even though
|
||||
/// emission and later ownership checks operate on headers. Build that second projection explicitly
|
||||
/// at the inference boundary. Existing header-specific claims win, and loop headers are excluded
|
||||
/// because they emit `OpLoopMerge` rather than `OpSelectionMerge`.
|
||||
pub(in crate::native) fn index_branch_merges_by_header(
|
||||
blocks: &[BodyBlock],
|
||||
loop_merges: &HashMap<String, LoopMergeInfo>,
|
||||
branch_merges: &HashMap<(String, String), String>,
|
||||
branch_merges_by_header: &mut HashMap<String, String>,
|
||||
) {
|
||||
for block in blocks {
|
||||
if loop_merges.contains_key(&block.name)
|
||||
|| branch_merges_by_header.contains_key(&block.name)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let Some((on_true, on_false)) = conditional_branch_targets(block) else {
|
||||
continue;
|
||||
};
|
||||
if let Some(merge) = branch_merges.get(&(on_true, on_false)) {
|
||||
branch_merges_by_header.insert(block.name.clone(), merge.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// True when `label` names a synthesized switch-bypass block, read from the block's typed
|
||||
/// [`BlockRole::SwitchBypass`] tag rather than decoding the `SWITCH_BYPASS_PREFIX` on the name.
|
||||
/// Byte-identical to the retired name match: a block carries `SwitchBypass` iff its name has that
|
||||
@@ -771,6 +857,52 @@ pub(in crate::native) fn infer_loop_merges(blocks: &[BodyBlock]) -> HashMap<Stri
|
||||
merges
|
||||
}
|
||||
|
||||
/// Resolve an emission-empty pass-through named as a loop continue before `OpLoopMerge` is emitted.
|
||||
///
|
||||
/// Structurization can preserve an intermediate edge block while selecting the block after it as
|
||||
/// the real back-edge carrier. The finalized typed CFG owns both facts, so collapse the complete
|
||||
/// emission-empty/unconditional chain in the loop plan rather than repairing numeric SPIR-V labels
|
||||
/// later. Ignored LLVM lifetime/debug markers are semantically empty and emit no instruction, so
|
||||
/// they do not turn an otherwise empty edge block into a continue target.
|
||||
#[cfg(test)]
|
||||
pub(in crate::native) fn normalize_loop_continue_targets(
|
||||
blocks: &[BodyBlock],
|
||||
loop_merges: &mut HashMap<String, LoopMergeInfo>,
|
||||
) {
|
||||
let by_name = blocks
|
||||
.iter()
|
||||
.map(|block| (block.name.as_str(), block))
|
||||
.collect::<HashMap<_, _>>();
|
||||
for (header, info) in loop_merges {
|
||||
let mut seen = HashSet::new();
|
||||
while info.continue_target != *header
|
||||
&& info.continue_target != info.merge
|
||||
&& seen.insert(info.continue_target.clone())
|
||||
{
|
||||
let Some(block) = by_name.get(info.continue_target.as_str()) else {
|
||||
break;
|
||||
};
|
||||
let Some(typed) = block.typed.as_ref() else {
|
||||
break;
|
||||
};
|
||||
if !typed.insts.iter().all(|inst| {
|
||||
inst.void_call_line()
|
||||
.as_deref()
|
||||
.is_some_and(crate::native::parse::is_ignored_call_line)
|
||||
}) {
|
||||
break;
|
||||
}
|
||||
let crate::native::tir::TirTerminator::Br(target) = &typed.terminator else {
|
||||
break;
|
||||
};
|
||||
if target == header || target == &info.merge {
|
||||
break;
|
||||
}
|
||||
info.continue_target = target.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn natural_loop_nodes(
|
||||
header: &str,
|
||||
back_preds: &[String],
|
||||
@@ -896,6 +1028,17 @@ pub(in crate::native) fn infer_switch_merges(blocks: &[BodyBlock]) -> HashMap<St
|
||||
merges
|
||||
}
|
||||
|
||||
/// True when a source switch's default target is also its inferred common merge. Such a block cannot
|
||||
/// be both a case header and the selection merge in structured SPIR-V; emission must use the existing
|
||||
/// comparison-ladder construction for that switch.
|
||||
pub(in crate::native) fn switch_default_is_inferred_merge(blocks: &[BodyBlock]) -> bool {
|
||||
let merges = infer_switch_merges(blocks);
|
||||
blocks.iter().any(|block| {
|
||||
switch_of(block)
|
||||
.is_some_and(|switch| merges.get(&block.name) == Some(&switch.default_label))
|
||||
})
|
||||
}
|
||||
|
||||
/// 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
|
||||
@@ -1171,7 +1314,7 @@ fn funnel_one_shared_branch_dispatch(
|
||||
};
|
||||
let mut rewrites = Vec::new();
|
||||
for inst in &target_typed.insts {
|
||||
let Some((ty, incoming)) = &inst.phi_incoming else {
|
||||
let Some((ty, incoming)) = &inst.phi_incoming() else {
|
||||
continue;
|
||||
};
|
||||
let from_left = incoming
|
||||
@@ -1362,7 +1505,7 @@ pub(in crate::native) fn refunnel_one_deep_shared_arm(
|
||||
let entry_set = entries.iter().map(String::as_str).collect::<HashSet<_>>();
|
||||
let mut rewrites = Vec::new();
|
||||
for inst in &target_typed.insts {
|
||||
let Some((ty, incoming)) = &inst.phi_incoming else {
|
||||
let Some((ty, incoming)) = &inst.phi_incoming() else {
|
||||
continue;
|
||||
};
|
||||
let selected = incoming
|
||||
@@ -1378,9 +1521,21 @@ pub(in crate::native) fn refunnel_one_deep_shared_arm(
|
||||
let result = inst.result.as_ref()?;
|
||||
let phi_name = format!("{join_name}.phi.{join_phi_index}");
|
||||
join_phi_index += 1;
|
||||
let join_incoming = selected
|
||||
// The join has every shared and bypass predecessor regardless of which target
|
||||
// owns this value. Cover the other route with `undef`: the route phi branches
|
||||
// away from this value's target on those edges, so the placeholder is never
|
||||
// observed, while the phi remains structurally complete by construction.
|
||||
let join_incoming = all_entries
|
||||
.iter()
|
||||
.map(|(value, pred)| ((*value).clone(), pred.clone()))
|
||||
.map(|(pred, _)| {
|
||||
let value = selected
|
||||
.iter()
|
||||
.find_map(|(value, selected_pred)| {
|
||||
(selected_pred == pred).then(|| (*value).clone())
|
||||
})
|
||||
.unwrap_or(LlValue::Undef);
|
||||
(value, pred.clone())
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
join_typed.push_value_phi(&phi_name, ty, &join_incoming);
|
||||
let mut replacement = Vec::with_capacity(incoming.len() + 1 - selected.len());
|
||||
@@ -1436,8 +1591,8 @@ pub(in crate::native) fn lower_unstructured_switches(blocks: &[BodyBlock]) -> Ve
|
||||
/// Lower every switch that directly exits an enclosing natural loop while another arm remains in that
|
||||
/// loop. SPIR-V cannot use a loop-breaking target as an `OpSwitch` case construct; a branch ladder
|
||||
/// makes each equality test an ordinary selection, where the loop-exit arm is a legal structured exit.
|
||||
/// This is used only by the reject-triggered loop-exit structurizer tier; the default lowering keeps
|
||||
/// its existing byte behavior.
|
||||
/// Planning applies this before admitting the source graph so the selected block ownership is valid
|
||||
/// by construction rather than repaired after SPIR-V emission.
|
||||
pub(in crate::native) fn lower_loop_exit_switches(blocks: &[BodyBlock]) -> Vec<BodyBlock> {
|
||||
lower_switches(blocks, true)
|
||||
}
|
||||
@@ -1459,28 +1614,33 @@ fn lower_switches(blocks: &[BodyBlock], force_loop_exit_ladders: bool) -> Vec<Bo
|
||||
let mut phi_rewrites: HashMap<String, HashMap<String, Vec<String>>> = HashMap::new();
|
||||
let mut synthetic_index = 0usize;
|
||||
|
||||
for block in blocks {
|
||||
for block in normalized {
|
||||
// SPIR-V switch case constructs cannot converge at a shared intermediate block when another
|
||||
// case can bypass it. A branch ladder lets ordinary branch merge inference model that shape.
|
||||
// Source the block's switch from the typed carrier (`switch: switch_emit(term)`, populated for
|
||||
// every production switch block).
|
||||
let Some(switch) = switch_of(block) else {
|
||||
lowered.push(block.clone());
|
||||
let Some(switch) = switch_of(&block) else {
|
||||
lowered.push(block);
|
||||
continue;
|
||||
};
|
||||
let needs_ladder = loop_exit_ladders.contains(&block.name)
|
||||
|| !switch_merges.contains_key(&block.name)
|
||||
// A selection merge cannot simultaneously serve as the switch's default case header:
|
||||
// every explicit case that reconverges there would enter another case construct. The
|
||||
// comparison ladder gives each route an ordinary selection and leaves the common block
|
||||
// solely in its merge role.
|
||||
|| switch_merges.get(&block.name) == Some(&switch.default_label)
|
||||
|| switch_case_order_requires_ladder(&block.name, &switch, &switch_merges, &successors);
|
||||
if !needs_ladder {
|
||||
lowered.push(block.clone());
|
||||
lowered.push(block);
|
||||
continue;
|
||||
}
|
||||
let Some(selector_ty) = text_type(&switch.selector.ty) else {
|
||||
lowered.push(block.clone());
|
||||
lowered.push(block);
|
||||
continue;
|
||||
};
|
||||
let Some(selector_value) = text_value(&switch.selector.value) else {
|
||||
lowered.push(block.clone());
|
||||
lowered.push(block);
|
||||
continue;
|
||||
};
|
||||
let cases = switch
|
||||
@@ -1598,20 +1758,22 @@ fn lower_switches(blocks: &[BodyBlock], force_loop_exit_ladders: bool) -> Vec<Bo
|
||||
lowered
|
||||
}
|
||||
|
||||
/// Return switches in a natural-loop body that branch directly to that loop's sole exit while at least
|
||||
/// one other arm stays in the body. Such a `switch` is source-valid, but its exiting case cannot be a
|
||||
/// SPIR-V case construct; [`lower_loop_exit_switches`] lowers it to ordinary conditional branches.
|
||||
/// Return switches in a natural loop that branch directly to any loop exit while at least one other
|
||||
/// arm stays in the body. This includes the loop header itself: lowering its switch leaves the
|
||||
/// first comparison on the loop header under `OpLoopMerge`, while subsequent comparisons become
|
||||
/// ordinary selection blocks. Such a `switch` is source-valid, but its exiting case cannot be a SPIR-V
|
||||
/// case construct; [`lower_loop_exit_switches`] lowers it to ordinary conditional branches.
|
||||
fn loop_exit_switch_headers(blocks: &[BodyBlock]) -> HashSet<String> {
|
||||
let forest = analyze(blocks);
|
||||
let mut headers = HashSet::new();
|
||||
for loop_info in &forest.loops {
|
||||
let [merge] = loop_info.exits.as_slice() else {
|
||||
if loop_info.exits.is_empty() {
|
||||
continue;
|
||||
};
|
||||
}
|
||||
let exits = loop_info.exits.iter().collect::<HashSet<_>>();
|
||||
let body: HashSet<&str> = loop_info.body.iter().map(String::as_str).collect();
|
||||
for block in blocks {
|
||||
if block.name == loop_info.header
|
||||
|| !body.contains(block.name.as_str())
|
||||
if (block.name != loop_info.header && !body.contains(block.name.as_str()))
|
||||
|| !block.typed.as_ref().is_some_and(|t| {
|
||||
matches!(
|
||||
t.terminator,
|
||||
@@ -1622,7 +1784,7 @@ fn loop_exit_switch_headers(blocks: &[BodyBlock]) -> HashSet<String> {
|
||||
continue;
|
||||
}
|
||||
let successors = block_successors(block);
|
||||
if successors.iter().any(|target| target == merge)
|
||||
if successors.iter().any(|target| exits.contains(target))
|
||||
&& successors
|
||||
.iter()
|
||||
.any(|target| body.contains(target.as_str()))
|
||||
@@ -1917,7 +2079,7 @@ fn rewrite_switch_bypass_merge(
|
||||
}
|
||||
let mut additions: HashMap<String, Vec<(LlValue, String)>> = HashMap::new();
|
||||
for merge_phi in merge_phis {
|
||||
let Some((_, incoming)) = &merge_phi.phi_incoming else {
|
||||
let Some((_, incoming)) = &merge_phi.phi_incoming() else {
|
||||
return false;
|
||||
};
|
||||
let Some((inner_value, _)) = incoming.iter().find(|(_, pred)| pred == intermediate)
|
||||
@@ -1990,33 +2152,34 @@ fn rewrite_switch_bypass_merge(
|
||||
}
|
||||
// Drop the bypass incomings from the merge carrier's phis (the same `!bypass_set` filter): a merge
|
||||
// phi that had a bypass incoming is non-aggregate (the plan loop bailed otherwise), so
|
||||
// `rebuild_phi_incomings` reproduces the same incoming set / operands / uses a re-lower of the
|
||||
// `rebuild_phi_incomings` reproduces the same canonical incoming set and derived uses a re-lower of the
|
||||
// bypass-dropped line would.
|
||||
if let Some(t) = blocks[merge_idx].typed_mut() {
|
||||
t.rebuild_phi_incomings(|pred| !bypass_set.contains(pred));
|
||||
}
|
||||
|
||||
let mut rebuilt = Vec::with_capacity(blocks.len() + insert_after.len());
|
||||
for block in blocks.drain(..) {
|
||||
let synthetic = insert_after.get(&block.name).cloned();
|
||||
rebuilt.push(block);
|
||||
if let Some(synthetic) = synthetic {
|
||||
let lines = vec![format!("br label {intermediate}")];
|
||||
// Purely synthetic single-`br` bypass block — lower its carrier directly (empty named-types
|
||||
// is exact for a `br`).
|
||||
let typed =
|
||||
crate::native::tir::lower_block_carrier(&synthetic, &lines, &HashMap::new())
|
||||
.map(Into::into);
|
||||
rebuilt.push(BodyBlock {
|
||||
// Insert from the end so original indices remain stable and the existing block allocation stays
|
||||
// owned by its caller throughout the transformation.
|
||||
for block_idx in (0..blocks.len()).rev() {
|
||||
let Some(synthetic) = insert_after.get(&blocks[block_idx].name).cloned() else {
|
||||
continue;
|
||||
};
|
||||
let lines = vec![format!("br label {intermediate}")];
|
||||
// Purely synthetic single-`br` bypass block — lower its carrier directly (empty named-types
|
||||
// is exact for a `br`).
|
||||
let typed = crate::native::tir::lower_block_carrier(&synthetic, &lines, &HashMap::new())
|
||||
.map(Into::into);
|
||||
blocks.insert(
|
||||
block_idx + 1,
|
||||
BodyBlock {
|
||||
name: synthetic,
|
||||
// A `%metal2vulkan_switch_bypass_*` block — the one SwitchBypass synthesis site;
|
||||
// `infer_branch_merges` reads this role instead of decoding the bypass-prefixed name.
|
||||
role: BlockRole::SwitchBypass,
|
||||
typed,
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
*blocks = rebuilt;
|
||||
true
|
||||
}
|
||||
|
||||
@@ -2109,6 +2272,62 @@ mod tests {
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loop_plan_resolves_emission_empty_continue_chain_before_emission() {
|
||||
let blocks = vec![
|
||||
block("%header", "br label %body"),
|
||||
block("%body", "br label %pass0"),
|
||||
synthetic_block(
|
||||
"%pass0".to_string(),
|
||||
vec![
|
||||
"call void @llvm.lifetime.start.p0(i64 4, ptr null)".to_string(),
|
||||
"br label %pass1".to_string(),
|
||||
],
|
||||
BlockRole::Normal,
|
||||
),
|
||||
block("%pass1", "br label %header"),
|
||||
block("%merge", "ret void"),
|
||||
];
|
||||
let mut loop_merges = HashMap::from([(
|
||||
"%header".to_string(),
|
||||
LoopMergeInfo {
|
||||
merge: "%merge".to_string(),
|
||||
continue_target: "%pass0".to_string(),
|
||||
},
|
||||
)]);
|
||||
|
||||
normalize_loop_continue_targets(&blocks, &mut loop_merges);
|
||||
|
||||
assert_eq!(loop_merges["%header"].continue_target, "%pass1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pair_keyed_branch_merges_are_indexed_only_for_unclaimed_selection_headers() {
|
||||
let blocks = vec![
|
||||
block("%first", "br i1 %c0, label %yes, label %no"),
|
||||
block("%second", "br i1 %c1, label %yes, label %no"),
|
||||
block("%loop", "br i1 %c2, label %yes, label %no"),
|
||||
];
|
||||
let branch_merges = HashMap::from([(
|
||||
("%yes".to_string(), "%no".to_string()),
|
||||
"%shared".to_string(),
|
||||
)]);
|
||||
let loop_merges = HashMap::from([(
|
||||
"%loop".to_string(),
|
||||
LoopMergeInfo {
|
||||
merge: "%exit".to_string(),
|
||||
continue_target: "%continue".to_string(),
|
||||
},
|
||||
)]);
|
||||
let mut by_header = HashMap::from([("%second".to_string(), "%specific".to_string())]);
|
||||
|
||||
index_branch_merges_by_header(&blocks, &loop_merges, &branch_merges, &mut by_header);
|
||||
|
||||
assert_eq!(by_header["%first"], "%shared");
|
||||
assert_eq!(by_header["%second"], "%specific");
|
||||
assert!(!by_header.contains_key("%loop"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn implicit_entry_block_name_uses_next_numeric_value() {
|
||||
let function = LlFunction {
|
||||
@@ -2218,6 +2437,28 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn switch_whose_default_is_its_merge_lowers_to_branch_ladder() {
|
||||
let blocks = vec![
|
||||
block(
|
||||
"%switch",
|
||||
"switch i32 %tag, label %merge [ i32 0, label %a i32 1, label %b i32 2, label %c ]",
|
||||
),
|
||||
block("%a", "br label %merge"),
|
||||
block("%b", "br label %merge"),
|
||||
block("%c", "br label %merge"),
|
||||
block("%merge", "ret void"),
|
||||
];
|
||||
assert_eq!(
|
||||
infer_switch_merges(&blocks).get("%switch"),
|
||||
Some(&"%merge".to_string())
|
||||
);
|
||||
|
||||
let lowered = lower_unstructured_switches(&blocks);
|
||||
assert!(lowered.iter().all(|block| switch_of(block).is_none()));
|
||||
assert!(lowered.len() > blocks.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_switch_merge_accepts_only_local_common_reconvergence() {
|
||||
let blocks = vec![
|
||||
@@ -2324,7 +2565,7 @@ mod tests {
|
||||
|
||||
let taken = out.iter().find(|block| block.name == "%taken").unwrap();
|
||||
let incoming = &taken.typed.as_ref().unwrap().insts[0]
|
||||
.phi_incoming
|
||||
.phi_incoming()
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.1;
|
||||
@@ -2353,8 +2594,22 @@ mod tests {
|
||||
),
|
||||
block("%via_shared", "br label %shared"),
|
||||
block("%bypass", "br label %merge"),
|
||||
block("%shared", "br label %merge"),
|
||||
block("%merge", "ret void"),
|
||||
synthetic_block(
|
||||
"%shared".to_string(),
|
||||
vec![
|
||||
"%shared_value = phi i32 [ 1, %header ], [ 2, %via_shared ]".to_string(),
|
||||
"br label %merge".to_string(),
|
||||
],
|
||||
BlockRole::Normal,
|
||||
),
|
||||
synthetic_block(
|
||||
"%merge".to_string(),
|
||||
vec![
|
||||
"%merge_value = phi i32 [ 3, %bypass ], [ %shared_value, %shared ]".to_string(),
|
||||
"ret void".to_string(),
|
||||
],
|
||||
BlockRole::Normal,
|
||||
),
|
||||
];
|
||||
let out = refunnel_one_deep_shared_arm(&blocks, &mut 0).unwrap();
|
||||
let join = out
|
||||
@@ -2369,6 +2624,19 @@ mod tests {
|
||||
let block = out.iter().find(|block| block.name == predecessor).unwrap();
|
||||
assert!(block_successors(block).contains(&join.name));
|
||||
}
|
||||
let join_phis = join
|
||||
.typed
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.insts
|
||||
.iter()
|
||||
.filter_map(|instruction| instruction.phi_incoming().as_ref())
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(join_phis.len(), 3, "route plus both forwarded values");
|
||||
assert!(join_phis.iter().all(|(_, incoming)| incoming.len() == 3));
|
||||
assert!(join_phis.iter().skip(1).all(|(_, incoming)| incoming
|
||||
.iter()
|
||||
.any(|(value, _)| matches!(value, LlValue::Undef))));
|
||||
assert_eq!(out.len(), blocks.len() + 1);
|
||||
}
|
||||
|
||||
|
||||
@@ -14,9 +14,9 @@ pub(in crate::native) fn privatize_cross_arm_edge(blocks: &[BodyBlock]) -> Vec<B
|
||||
let mut counter = 1_000_000usize;
|
||||
// Round + growth caps: bound the cost. Each round re-runs `analyze` (dominator recompute, super-
|
||||
// linear in blocks) and clones up to `MAX_REGION_BLOCKS`, and this driver is re-invoked by
|
||||
// `structured_plan` per retry tier, so an unbounded loop on a big function grinds the cascade. Real
|
||||
// `structured_plan` per construction attempt, so an unbounded loop on a big function is costly. Real
|
||||
// cross-arm-edge functions converge in 1-3 rounds (the largest landed win needs <=3); a function that
|
||||
// has not converged in `EDGE_ROUNDS` was not going to structure cleanly and falls to repair, exactly
|
||||
// has not converged in `EDGE_ROUNDS` was not going to structure cleanly and falls to the relooper retry, exactly
|
||||
// as before this attempt existed. `structured_emit::CROSS_ARM_EDGE_MAX_BLOCKS` already gates the whole
|
||||
// attempt to modest functions, so `cap` is a secondary belt.
|
||||
const EDGE_ROUNDS: usize = 8;
|
||||
@@ -37,8 +37,8 @@ pub(in crate::native) fn privatize_cross_arm_edge(blocks: &[BodyBlock]) -> Vec<B
|
||||
}
|
||||
|
||||
/// Privatize the TRIVIAL-pass-through cross-arm sub-case as a default-path pre-pass for
|
||||
/// [`crate::native::cfg::structured_emit::structured_plan`] (distinct from [`clone_cross_arm_shared`], the gated
|
||||
/// failure-retry that does full-closure tail duplication).
|
||||
/// [`crate::native::cfg::structured_emit::structured_plan`] (distinct from the legacy full-tail
|
||||
/// full-tail form that performs full-closure tail duplication).
|
||||
///
|
||||
/// The dominant cross-arm shape (`selection:cross-arm-shared`, the frontier's largest reject class) is
|
||||
/// a header `H` whose arm targets a block `A` shared with an ENCLOSING construct's arm, so `H` does not
|
||||
@@ -63,10 +63,28 @@ pub(in crate::native) fn privatize_cross_arm_edge(blocks: &[BodyBlock]) -> Vec<B
|
||||
/// returns the (possibly unchanged) block list. When no trivial cross-arm exists it returns a clone of
|
||||
/// the input verbatim (same length), which the caller uses to skip the redundant retry.
|
||||
pub(in crate::native) fn privatize_trivial_cross_arm(blocks: &[BodyBlock]) -> Vec<BodyBlock> {
|
||||
privatize_trivial_cross_arm_for_headers(blocks, None)
|
||||
}
|
||||
|
||||
/// Apply the trivial cross-arm clone only to headers whose finalized emission plans declare a
|
||||
/// selection merge. This lets the emitter reuse the same typed clone after merge inference without
|
||||
/// transforming a conditional that still has no structurally owned merge.
|
||||
#[cfg(test)]
|
||||
pub(in crate::native) fn privatize_trivial_cross_arm_for_emitted_headers(
|
||||
blocks: &[BodyBlock],
|
||||
headers: &HashSet<String>,
|
||||
) -> Vec<BodyBlock> {
|
||||
privatize_trivial_cross_arm_for_headers(blocks, Some(headers))
|
||||
}
|
||||
|
||||
fn privatize_trivial_cross_arm_for_headers(
|
||||
blocks: &[BodyBlock],
|
||||
headers: Option<&HashSet<String>>,
|
||||
) -> Vec<BodyBlock> {
|
||||
let mut cur: Vec<BodyBlock> = blocks.to_vec();
|
||||
let mut counter = 0usize;
|
||||
for _ in 0..MAX_ROUNDS {
|
||||
let Some((header, arm)) = find_trivial_cross_arm(&cur) else {
|
||||
let Some((header, arm)) = find_trivial_cross_arm_for_headers(&cur, headers) else {
|
||||
break;
|
||||
};
|
||||
let Some(next) = privatize_trivial(&cur, &header, &arm, &mut counter) else {
|
||||
@@ -81,7 +99,15 @@ pub(in crate::native) fn privatize_trivial_cross_arm(blocks: &[BodyBlock]) -> Ve
|
||||
/// single unconditional `br label %S` with no phi and no SSA definition — safe to clone verbatim (no
|
||||
/// rename, the clone defines nothing). Reuses the same merge / enclosing-break / loop-header
|
||||
/// exclusions as [`find_cross_arm`].
|
||||
#[cfg(test)]
|
||||
pub(in crate::native) fn find_trivial_cross_arm(blocks: &[BodyBlock]) -> Option<(String, String)> {
|
||||
find_trivial_cross_arm_for_headers(blocks, None)
|
||||
}
|
||||
|
||||
fn find_trivial_cross_arm_for_headers(
|
||||
blocks: &[BodyBlock],
|
||||
eligible_headers: Option<&HashSet<String>>,
|
||||
) -> Option<(String, String)> {
|
||||
let forest = analyze(blocks);
|
||||
let pidom = post_idom(blocks);
|
||||
let loop_headers: HashSet<&str> = forest.loops.iter().map(|l| l.header.as_str()).collect();
|
||||
@@ -93,6 +119,9 @@ pub(in crate::native) fn find_trivial_cross_arm(blocks: &[BodyBlock]) -> Option<
|
||||
let by_name: HashMap<&str, &BodyBlock> = blocks.iter().map(|b| (b.name.as_str(), b)).collect();
|
||||
let names: HashSet<&str> = blocks.iter().map(|b| b.name.as_str()).collect();
|
||||
for b in blocks {
|
||||
if eligible_headers.is_some_and(|headers| !headers.contains(&b.name)) {
|
||||
continue;
|
||||
}
|
||||
if loop_headers.contains(b.name.as_str()) {
|
||||
continue;
|
||||
}
|
||||
@@ -181,7 +210,7 @@ pub(in crate::native) fn arm_defs_safe_to_clone(
|
||||
let mentions = b.typed.as_ref().is_some_and(|t| {
|
||||
t.insts
|
||||
.iter()
|
||||
.any(|i| !i.is_phi() && i.uses.iter().any(|u| defs.contains(u)))
|
||||
.any(|i| !i.is_phi() && i.uses_any(|use_name| defs.contains(use_name)))
|
||||
|| terminator_mentions(&t.terminator)
|
||||
.iter()
|
||||
.any(|u| defs.contains(u))
|
||||
@@ -244,6 +273,9 @@ pub(in crate::native) fn privatize_trivial(
|
||||
|
||||
let by_name: HashMap<&str, &BodyBlock> = blocks.iter().map(|b| (b.name.as_str(), b)).collect();
|
||||
let arm_block = by_name.get(arm)?;
|
||||
if cloned_labels_overlap_ssa_values(blocks, &HashSet::from([arm.to_string()])) {
|
||||
return None;
|
||||
}
|
||||
// The single successor `S` — the shared reconvergence, kept as the merge.
|
||||
let succ = block_successors(arm_block);
|
||||
let s = succ.first()?.clone();
|
||||
|
||||
@@ -2,35 +2,6 @@
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Try to make `blocks` structurable by privatizing cross-arm shared regions via single-entry tail
|
||||
/// duplication. Applies up to [`MAX_ROUNDS`] privatizations (re-detecting each round). Returns the
|
||||
/// transformed block list IFF at least one clone was applied; otherwise `None` (no cleanly-cloneable
|
||||
/// cross-arm region was found). The caller decides whether to adopt it (it adopts only when
|
||||
/// [`crate::native::cfg::structured_emit::structured_plan`] then admits the result — floor-safe).
|
||||
pub(in crate::native) fn clone_cross_arm_shared(blocks: &[BodyBlock]) -> Option<Vec<BodyBlock>> {
|
||||
let mut cur: Vec<BodyBlock> = blocks.to_vec();
|
||||
let mut changed = false;
|
||||
let mut counter = 0usize;
|
||||
for _ in 0..MAX_ROUNDS {
|
||||
if crate::native::cfg::structured_emit::structured_plan(&cur).is_some() {
|
||||
break;
|
||||
}
|
||||
let Some((header, arm)) = find_cross_arm(&cur) else {
|
||||
break;
|
||||
};
|
||||
let Some(next) = privatize_region(&cur, &header, &arm, &mut counter) else {
|
||||
break;
|
||||
};
|
||||
cur = next;
|
||||
changed = true;
|
||||
}
|
||||
if changed {
|
||||
Some(cur)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Predecessor map: block name -> the blocks that branch to it.
|
||||
pub(in crate::native) fn predecessors(blocks: &[BodyBlock]) -> HashMap<String, Vec<String>> {
|
||||
let mut preds: HashMap<String, Vec<String>> = HashMap::new();
|
||||
|
||||
@@ -72,10 +72,13 @@ pub(in crate::native) fn find_deep_shared_continuations(
|
||||
}
|
||||
|
||||
/// Find a switch-case tail that is shared with another case. Each returned `case_root` is a direct
|
||||
/// target of a non-loop switch; `continuation` is reached from its dominated region but is not itself
|
||||
/// case-root-dominated, so another case still enters it. A non-case continuation is eligible only when
|
||||
/// the natural merge is externally reachable; a direct case-root continuation is eligible regardless,
|
||||
/// because entering another case is forbidden by SPIR-V's case-construct rules.
|
||||
/// target of a switch; `continuation` is reached from its dominated region but is not itself
|
||||
/// case-root-dominated, so another case still enters it. The natural merge itself is excluded, but an
|
||||
/// intermediate continuation is illegal even when the eventual merge is switch-dominated: SPIR-V does
|
||||
/// not permit one case construct to enter a block shared with another case. For a switch inside a natural
|
||||
/// loop, the cloneable region and its boundaries must remain in exactly the switch's loop nest and may
|
||||
/// not contain a loop header or latch. This permits ordinary loop-local case suffixes without cloning a
|
||||
/// break, continue, or nested-loop construct.
|
||||
pub(in crate::native) fn find_switch_case_shared_continuations(
|
||||
blocks: &[BodyBlock],
|
||||
) -> Vec<(String, String)> {
|
||||
@@ -83,10 +86,15 @@ pub(in crate::native) fn find_switch_case_shared_continuations(
|
||||
let selection = selection_merges(blocks, &forest);
|
||||
let names: HashSet<&str> = blocks.iter().map(|b| b.name.as_str()).collect();
|
||||
let loop_headers: HashSet<&str> = forest.loops.iter().map(|l| l.header.as_str()).collect();
|
||||
let loop_nodes: HashSet<&str> = forest
|
||||
let loop_latches: HashSet<&str> = forest
|
||||
.loops
|
||||
.iter()
|
||||
.flat_map(|l| l.body.iter().map(String::as_str))
|
||||
.flat_map(|l| l.latches.iter().map(String::as_str))
|
||||
.collect();
|
||||
let loop_exits: HashSet<&str> = forest
|
||||
.loops
|
||||
.iter()
|
||||
.flat_map(|l| l.exits.iter().map(String::as_str))
|
||||
.collect();
|
||||
|
||||
let depth = |name: &str| {
|
||||
@@ -102,7 +110,6 @@ pub(in crate::native) fn find_switch_case_shared_continuations(
|
||||
.iter()
|
||||
.filter(|b| {
|
||||
!loop_headers.contains(b.name.as_str())
|
||||
&& !loop_nodes.contains(b.name.as_str())
|
||||
// Switch-terminating detection via the carrier (`is_switch_block`, carrier-first with a
|
||||
// line fallback) instead of re-lexing `.lines.last()` — byte-identical by construction.
|
||||
&& crate::native::cfg::structured_emit::is_switch_block(b)
|
||||
@@ -117,9 +124,27 @@ pub(in crate::native) fn find_switch_case_shared_continuations(
|
||||
let Some(natural) = selection.get(&switch.name) else {
|
||||
continue;
|
||||
};
|
||||
// SPIR-V explicitly permits one case construct to fall through to the immediately following
|
||||
// literal case target. Privatizing that target would replace the legal edge with a cloned
|
||||
// prefix whose boundary can enter a later, non-adjacent case. Preserve the ordered fallthrough
|
||||
// here; genuinely shared or non-adjacent case entries remain privatization candidates.
|
||||
let adjacent_cases = match &switch.typed.as_ref().expect("typed switch").terminator {
|
||||
crate::native::tir::TirTerminator::Switch { cases, .. } => {
|
||||
let mut ordered = Vec::new();
|
||||
let mut unique = HashSet::new();
|
||||
for (_, target) in cases {
|
||||
if unique.insert(target.as_str()) {
|
||||
ordered.push(target.as_str());
|
||||
}
|
||||
}
|
||||
ordered
|
||||
.windows(2)
|
||||
.map(|pair| (pair[0], pair[1]))
|
||||
.collect::<HashSet<_>>()
|
||||
}
|
||||
_ => unreachable!("switch filter guarantees a switch terminator"),
|
||||
};
|
||||
let roots = block_successors(switch);
|
||||
let root_set: HashSet<&str> = roots.iter().map(String::as_str).collect();
|
||||
let merge_is_external = !forest.dominates(&switch.name, natural);
|
||||
let reaches_natural = reverse_reachable(blocks, natural, &names);
|
||||
for case_root in &roots {
|
||||
if case_root == natural
|
||||
@@ -133,11 +158,27 @@ pub(in crate::native) fn find_switch_case_shared_continuations(
|
||||
continue;
|
||||
}
|
||||
for continuation in block_successors(block) {
|
||||
let is_legal_adjacent_fallthrough = adjacent_cases
|
||||
.contains(&(case_root.as_str(), continuation.as_str()))
|
||||
&& matches!(
|
||||
block.typed.as_ref().map(|typed| &typed.terminator),
|
||||
Some(crate::native::tir::TirTerminator::Br(target))
|
||||
if target == &continuation
|
||||
);
|
||||
if continuation == *natural
|
||||
|| is_legal_adjacent_fallthrough
|
||||
|| !names.contains(continuation.as_str())
|
||||
|| forest.dominates(case_root, &continuation)
|
||||
|| !reaches_natural.contains(&continuation)
|
||||
|| (!merge_is_external && !root_set.contains(continuation.as_str()))
|
||||
|| !shared_clone_is_loop_local(
|
||||
blocks,
|
||||
&forest,
|
||||
case_root,
|
||||
&continuation,
|
||||
&loop_headers,
|
||||
&loop_latches,
|
||||
&loop_exits,
|
||||
)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
@@ -152,6 +193,75 @@ pub(in crate::native) fn find_switch_case_shared_continuations(
|
||||
found
|
||||
}
|
||||
|
||||
pub(in crate::native) fn shared_clone_is_loop_local(
|
||||
blocks: &[BodyBlock],
|
||||
forest: &crate::native::cfg::loopforest::LoopForest,
|
||||
owner: &str,
|
||||
continuation: &str,
|
||||
loop_headers: &HashSet<&str>,
|
||||
loop_latches: &HashSet<&str>,
|
||||
loop_exits: &HashSet<&str>,
|
||||
) -> bool {
|
||||
let membership = |name: &str| {
|
||||
forest
|
||||
.loops
|
||||
.iter()
|
||||
.filter(|natural_loop| natural_loop.body.iter().any(|node| node == name))
|
||||
.map(|natural_loop| natural_loop.header.as_str())
|
||||
.collect::<HashSet<_>>()
|
||||
};
|
||||
let owner_membership = membership(owner);
|
||||
if membership(continuation) != owner_membership {
|
||||
return false;
|
||||
}
|
||||
// The clone redirects owner-dominated predecessors of `continuation`. A predecessor in a deeper
|
||||
// loop cannot be moved onto a clone outside that loop: values selected on that exit edge would
|
||||
// become merely control-dependent after loop-merge routing and cease to dominate the clone.
|
||||
if blocks.iter().any(|block| {
|
||||
forest.dominates(owner, &block.name)
|
||||
&& block_successors(block)
|
||||
.iter()
|
||||
.any(|successor| successor == continuation)
|
||||
&& membership(&block.name) != owner_membership
|
||||
}) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let names: HashSet<&str> = blocks.iter().map(|block| block.name.as_str()).collect();
|
||||
let mut region = HashSet::new();
|
||||
let mut stack = vec![continuation.to_string()];
|
||||
while let Some(name) = stack.pop() {
|
||||
if !region.insert(name.clone()) {
|
||||
continue;
|
||||
}
|
||||
if membership(&name) != owner_membership
|
||||
|| loop_headers.contains(name.as_str())
|
||||
|| loop_latches.contains(name.as_str())
|
||||
|| loop_exits.contains(name.as_str())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let Some(block) = blocks.iter().find(|block| block.name == name) else {
|
||||
continue;
|
||||
};
|
||||
for successor in block_successors(block) {
|
||||
if !names.contains(successor.as_str()) {
|
||||
continue;
|
||||
}
|
||||
if forest.dominates(continuation, &successor) {
|
||||
stack.push(successor);
|
||||
} else if membership(&successor) != owner_membership
|
||||
|| loop_headers.contains(successor.as_str())
|
||||
|| loop_latches.contains(successor.as_str())
|
||||
|| loop_exits.contains(successor.as_str())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// The blocks that can reach `target`, including `target`, computed on the finite in-function CFG.
|
||||
pub(in crate::native) fn reverse_reachable(
|
||||
blocks: &[BodyBlock],
|
||||
@@ -188,6 +298,16 @@ pub(in crate::native) fn reverse_reachable(
|
||||
pub(in crate::native) fn find_cross_arm_edge(blocks: &[BodyBlock]) -> Option<(String, String)> {
|
||||
let forest = analyze(blocks);
|
||||
let loop_headers: HashSet<&str> = forest.loops.iter().map(|l| l.header.as_str()).collect();
|
||||
let loop_latches: HashSet<&str> = forest
|
||||
.loops
|
||||
.iter()
|
||||
.flat_map(|natural_loop| natural_loop.latches.iter().map(String::as_str))
|
||||
.collect();
|
||||
let loop_exits: HashSet<&str> = forest
|
||||
.loops
|
||||
.iter()
|
||||
.flat_map(|natural_loop| natural_loop.exits.iter().map(String::as_str))
|
||||
.collect();
|
||||
let names: HashSet<&str> = blocks.iter().map(|b| b.name.as_str()).collect();
|
||||
// Selection headers -> their two arm targets (skip loop headers — their conditional is the loop exit
|
||||
// test, and a break/continue is a legal exit, not a cross-arm jump).
|
||||
@@ -226,7 +346,17 @@ pub(in crate::native) fn find_cross_arm_edge(blocks: &[BodyBlock]) -> Option<(St
|
||||
None
|
||||
};
|
||||
if let Some(sib) = sibling {
|
||||
if forest.dominates(sib, &s) {
|
||||
if forest.dominates(sib, &s)
|
||||
&& shared_clone_is_loop_local(
|
||||
blocks,
|
||||
&forest,
|
||||
child,
|
||||
&s,
|
||||
&loop_headers,
|
||||
&loop_latches,
|
||||
&loop_exits,
|
||||
)
|
||||
{
|
||||
return Some((child.to_string(), s));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,14 +12,9 @@
|
||||
//! Because `R` is the FULL forward closure of `A`, every use of a value defined inside `R` is itself
|
||||
//! inside `R` (uses are reachable from their def) — so the clone needs **no exit-phi synthesis**: each
|
||||
//! copy is self-contained. The transform fires only when `R` is **single-entry** (every block in
|
||||
//! `R\{A}` has all its predecessors inside `R`); otherwise a deeper block is shared too and a single
|
||||
//! clone would just move the sharing (the cascade the prior session proved necessary — left to a
|
||||
//! future increment).
|
||||
//!
|
||||
//! It is NOT wired into the default emission path. It is reached only via the failure-triggered
|
||||
//! `inline_sroa_raw_cfg_restructure` retry tier (adopt-if-validates, mirroring the R4 raw retry), so a
|
||||
//! banked/passing case — which `structured_plan` admits on the default path — never reaches it and the
|
||||
//! floor is byte-identical by construction.
|
||||
//! `R\{A}` has all its predecessors inside `R`); otherwise the broader region and construct-tree
|
||||
//! builders own the shape. These transformations are selected from CFG ownership facts before the
|
||||
//! module is serialized.
|
||||
|
||||
use super::blocks::{block_successors, conditional_branch_targets};
|
||||
use super::loopforest::{analyze, post_idom, selection_merges};
|
||||
@@ -394,6 +389,21 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clone_declines_label_that_is_also_an_ssa_operand() {
|
||||
let blocks = vec![
|
||||
blk(
|
||||
"%entry",
|
||||
&["%value = add i32 %shared, 1", "br label %shared"],
|
||||
),
|
||||
blk("%shared", &["ret void"]),
|
||||
];
|
||||
assert!(cloned_labels_overlap_ssa_values(
|
||||
&blocks,
|
||||
&HashSet::from(["%shared".to_string()])
|
||||
));
|
||||
}
|
||||
|
||||
/// A shared arm whose def is used in a BODY computation past the arm (`%d` in `%merge`'s
|
||||
/// `mul`, not a phi incoming) is still EXCLUDED: the split removes the arm's domination of the
|
||||
/// successor, so the body use is undefined on the clone edge (broken SSA — the `000ca89f`
|
||||
@@ -734,6 +744,123 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// Adjacent literal cases are the one case-to-case edge SPIR-V permits. Cloning the middle case
|
||||
/// would leave its private prefix entering the third case non-adjacently, converting a valid
|
||||
/// compact fallthrough chain into an invalid construct.
|
||||
#[test]
|
||||
fn privatize_switch_case_continuations_preserves_adjacent_case_chain() {
|
||||
let blocks = vec![
|
||||
blk("entry", &["br label %sw"]),
|
||||
blk(
|
||||
"sw",
|
||||
&["switch i32 %x, label %merge [ i32 3, label %a i32 2, label %b i32 1, label %c ]"],
|
||||
),
|
||||
blk("a", &["br label %b"]),
|
||||
blk("b", &["br label %c"]),
|
||||
blk("c", &["br label %merge"]),
|
||||
blk("merge", &["ret void"]),
|
||||
];
|
||||
assert!(find_switch_case_shared_continuations(&blocks).is_empty());
|
||||
let out = privatize_switch_case_continuations(&blocks);
|
||||
assert_eq!(out.len(), blocks.len());
|
||||
assert!(out
|
||||
.iter()
|
||||
.zip(&blocks)
|
||||
.all(|(actual, expected)| actual.name == expected.name
|
||||
&& actual.lines() == expected.lines()));
|
||||
assert!(
|
||||
super::super::structured_emit::structured_plan(&out).is_some(),
|
||||
"the legal compact switch remains directly structurable"
|
||||
);
|
||||
}
|
||||
|
||||
/// Adjacency only licenses an unconditional case fallthrough. A conditional edge into the next
|
||||
/// case is still an illegal side entry and must be privatized even when the case labels are
|
||||
/// consecutive in the switch instruction.
|
||||
#[test]
|
||||
fn privatize_switch_case_continuations_rewrites_conditional_adjacent_entry() {
|
||||
let blocks = vec![
|
||||
blk("entry", &["br label %sw"]),
|
||||
blk(
|
||||
"sw",
|
||||
&["switch i32 %x, label %merge [ i32 2, label %a i32 1, label %b ]"],
|
||||
),
|
||||
blk("a", &["br i1 %take, label %b, label %tail"]),
|
||||
blk("tail", &["br label %merge"]),
|
||||
blk("b", &["br label %merge"]),
|
||||
blk("merge", &["ret void"]),
|
||||
];
|
||||
assert_eq!(
|
||||
find_switch_case_shared_continuations(&blocks),
|
||||
vec![("%a".into(), "%b".into())]
|
||||
);
|
||||
let out = privatize_switch_case_continuations(&blocks);
|
||||
let a = out.iter().find(|block| block.name == "%a").unwrap();
|
||||
assert!(!block_successors(a).iter().any(|target| target == "%b"));
|
||||
assert!(
|
||||
super::super::structured_emit::structured_plan(&out).is_some(),
|
||||
"the conditional side entry is privatized before planning"
|
||||
);
|
||||
}
|
||||
|
||||
/// A shared continuation outside a loop cannot receive a clone entered from a predecessor inside
|
||||
/// that loop. Structured loop-exit routing later passes through the loop merge, so an edge-local
|
||||
/// value would no longer dominate uses specialized into the clone.
|
||||
#[test]
|
||||
fn shared_clone_rejects_cross_loop_redirected_predecessor() {
|
||||
let blocks = vec![
|
||||
blk("entry", &["br label %outer"]),
|
||||
blk("outer", &["br i1 %direct, label %shared, label %head"]),
|
||||
blk(
|
||||
"head",
|
||||
&[
|
||||
"%i = phi i32 [ 0, %outer ], [ %next, %body ]",
|
||||
"br label %body",
|
||||
],
|
||||
),
|
||||
blk(
|
||||
"body",
|
||||
&[
|
||||
"%edge = add i32 %i, 1",
|
||||
"%next = add i32 %i, 1",
|
||||
"br i1 %leave, label %shared, label %head",
|
||||
],
|
||||
),
|
||||
blk(
|
||||
"shared",
|
||||
&[
|
||||
"%value = phi i32 [ 0, %outer ], [ %edge, %body ]",
|
||||
"ret void",
|
||||
],
|
||||
),
|
||||
];
|
||||
let forest = analyze(&blocks);
|
||||
let loop_headers = forest
|
||||
.loops
|
||||
.iter()
|
||||
.map(|natural_loop| natural_loop.header.as_str())
|
||||
.collect::<HashSet<_>>();
|
||||
let loop_latches = forest
|
||||
.loops
|
||||
.iter()
|
||||
.flat_map(|natural_loop| natural_loop.latches.iter().map(String::as_str))
|
||||
.collect::<HashSet<_>>();
|
||||
let loop_exits = forest
|
||||
.loops
|
||||
.iter()
|
||||
.flat_map(|natural_loop| natural_loop.exits.iter().map(String::as_str))
|
||||
.collect::<HashSet<_>>();
|
||||
assert!(!shared_clone_is_loop_local(
|
||||
&blocks,
|
||||
&forest,
|
||||
"%outer",
|
||||
"%shared",
|
||||
&loop_headers,
|
||||
&loop_latches,
|
||||
&loop_exits,
|
||||
));
|
||||
}
|
||||
|
||||
/// A case can also enter the switch's DEFAULT CASE through a conditional tail. The switch merge is
|
||||
/// ordinarily dominated in this shape, so generic tail sharing is left alone; the continuation is
|
||||
/// still a direct case root, though, and SPIR-V forbids one case construct from entering another.
|
||||
@@ -769,11 +896,77 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// A switch inside a natural loop is deliberately outside the case-tail transform: its shared
|
||||
/// continuation can be a loop break/continue boundary, which needs a real multi-level-break model
|
||||
/// rather than tail duplication.
|
||||
/// A switch-dominated merge does not make an earlier subset reconvergence legal. Cases `%a` and
|
||||
/// `%b` share `%shared`, while the default and `%c` bypass it and meet them only at `%merge`.
|
||||
/// `%shared` must therefore be private to each entering case even though `%merge` is dominated by
|
||||
/// the switch.
|
||||
#[test]
|
||||
fn privatize_switch_case_continuations_skips_loop_contained_switch() {
|
||||
fn privatize_switch_case_continuations_splits_subset_before_dominated_merge() {
|
||||
let blocks = vec![
|
||||
blk("entry", &["br label %sw"]),
|
||||
blk(
|
||||
"sw",
|
||||
&["switch i32 %x, label %default [ i32 0, label %a i32 1, label %b i32 2, label %c ]"],
|
||||
),
|
||||
blk("a", &["br label %shared"]),
|
||||
blk("b", &["br label %shared"]),
|
||||
blk("c", &["br label %merge"]),
|
||||
blk("default", &["br label %merge"]),
|
||||
blk("shared", &["br label %merge"]),
|
||||
blk("merge", &["ret void"]),
|
||||
];
|
||||
assert!(
|
||||
find_switch_case_shared_continuations(&blocks)
|
||||
.contains(&("%a".to_string(), "%shared".to_string())),
|
||||
"the intermediate subset reconvergence is not the switch merge"
|
||||
);
|
||||
let out = privatize_switch_case_continuations(&blocks);
|
||||
assert!(out.len() > blocks.len(), "the shared suffix is privatized");
|
||||
assert_eq!(out.iter().filter(|b| b.name == "%merge").count(), 1);
|
||||
assert!(
|
||||
super::super::structured_emit::structured_plan(&out).is_some(),
|
||||
"the split subset remains structurable"
|
||||
);
|
||||
}
|
||||
|
||||
/// A switch inside a natural loop may privatize an ordinary shared suffix when the cloned region
|
||||
/// and its boundary remain inside that loop. The separate latch keeps the clone away from the
|
||||
/// continue construct.
|
||||
#[test]
|
||||
fn privatize_switch_case_continuations_clones_loop_local_tail() {
|
||||
let blocks = vec![
|
||||
blk("entry", &["br label %loop"]),
|
||||
blk("loop", &["br i1 %run, label %sw, label %join"]),
|
||||
blk(
|
||||
"sw",
|
||||
&["switch i32 %x, label %join [ i32 0, label %a i32 1, label %b ]"],
|
||||
),
|
||||
blk("a", &["br label %shared"]),
|
||||
blk("b", &["br label %shared"]),
|
||||
blk("shared", &["br label %join"]),
|
||||
blk("join", &["br label %latch"]),
|
||||
blk("latch", &["br i1 %again, label %loop, label %exit"]),
|
||||
blk("exit", &["ret void"]),
|
||||
];
|
||||
assert!(
|
||||
find_switch_case_shared_continuations(&blocks)
|
||||
.contains(&("%a".to_string(), "%shared".to_string())),
|
||||
"a loop-local shared case suffix is eligible"
|
||||
);
|
||||
let out = privatize_switch_case_continuations(&blocks);
|
||||
assert!(out.len() > blocks.len(), "the shared suffix is privatized");
|
||||
assert_eq!(out.iter().filter(|b| b.name == "%join").count(), 1);
|
||||
assert_eq!(out.iter().filter(|b| b.name == "%latch").count(), 1);
|
||||
assert!(
|
||||
super::super::structured_emit::structured_plan(&out).is_some(),
|
||||
"the loop and privatized switch remain structurable"
|
||||
);
|
||||
}
|
||||
|
||||
/// A shared case tail that is itself the loop latch remains outside the case-tail transform: it
|
||||
/// is a continue boundary, which needs loop-aware ownership rather than tail duplication.
|
||||
#[test]
|
||||
fn privatize_switch_case_continuations_skips_loop_latch() {
|
||||
let blocks = vec![
|
||||
blk("entry", &["br label %loop"]),
|
||||
blk("loop", &["br i1 %again, label %sw, label %exit"]),
|
||||
@@ -789,7 +982,42 @@ mod tests {
|
||||
assert_eq!(
|
||||
privatize_switch_case_continuations(&blocks).len(),
|
||||
blocks.len(),
|
||||
"loop-contained switch is left to the loop-aware structurizer"
|
||||
"a shared loop latch is left to the loop-aware structurizer"
|
||||
);
|
||||
}
|
||||
|
||||
/// A block may be in the same outer loop as a switch while also serving as a nested loop's exit.
|
||||
/// Exact loop-membership equality alone does not make that structural merge cloneable.
|
||||
#[test]
|
||||
fn privatize_switch_case_continuations_skips_nested_loop_exit() {
|
||||
let blocks = vec![
|
||||
blk("entry", &["br label %outer"]),
|
||||
blk("outer", &["br i1 %run, label %sw, label %exit"]),
|
||||
blk(
|
||||
"sw",
|
||||
&["switch i32 %x, label %join [ i32 0, label %a i32 1, label %b i32 2, label %inner ]"],
|
||||
),
|
||||
blk("a", &["br label %shared"]),
|
||||
blk("b", &["br label %shared"]),
|
||||
blk(
|
||||
"inner",
|
||||
&["br i1 %inner_again, label %inner_body, label %shared"],
|
||||
),
|
||||
blk("inner_body", &["br label %inner"]),
|
||||
blk("shared", &["br label %join"]),
|
||||
blk("join", &["br label %outer_latch"]),
|
||||
blk("outer_latch", &["br label %outer"]),
|
||||
blk("exit", &["ret void"]),
|
||||
];
|
||||
assert!(
|
||||
!find_switch_case_shared_continuations(&blocks)
|
||||
.contains(&("%a".to_string(), "%shared".to_string())),
|
||||
"a nested loop exit is retained as that loop's structural merge"
|
||||
);
|
||||
assert_eq!(
|
||||
privatize_switch_case_continuations(&blocks).len(),
|
||||
blocks.len(),
|
||||
"the nested loop exit is not cloned as a case suffix"
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -8,63 +8,17 @@ use crate::native::tir::RetTerm;
|
||||
/// the base label, its collision-avoidance variants, and the merged-return phi value cannot drift apart.
|
||||
pub(in crate::native) const URET_PREFIX: &str = "%metal2vulkan.uret";
|
||||
|
||||
/// Lower every `unreachable` terminator to a `ret` (transform #1.5 of the cross-arm cascade, applied
|
||||
/// before [`unify_returns`]). An arm ending in `unreachable` never reconverges with its sibling, so
|
||||
/// the enclosing selection has no natural merge (`cond-no-natural`) even after return unification.
|
||||
/// Executing `unreachable` is UB, so replacing it with a function return is a legal refinement; the
|
||||
/// return's type/shape is copied from the function's first real `ret` (`ret void`, or `ret T undef`).
|
||||
/// Returns `None` when there is no `unreachable` or no `ret` to model the replacement on.
|
||||
pub(in crate::native) fn lower_unreachable_to_ret(blocks: &[BodyBlock]) -> Option<Vec<BodyBlock>> {
|
||||
// Model the replacement `ret` on the function's first real `ret`, read from the typed carrier (the
|
||||
// dual of scanning the trailing `ret` LINE). `Unrenderable` — a value `ret` whose type does not
|
||||
// render injectively (e.g. an anonymous struct return) — declines the transform, mirroring the line
|
||||
// path's `?`-bail on an un-splittable `ret`; a non-`ret` terminator is skipped.
|
||||
let mut model: Option<String> = None;
|
||||
for b in blocks {
|
||||
let Some(t) = &b.typed else { continue };
|
||||
match t.ret_term() {
|
||||
RetTerm::Void => {
|
||||
model = Some("ret void".to_string());
|
||||
break;
|
||||
}
|
||||
RetTerm::Value { ty, .. } => {
|
||||
model = Some(format!("ret {ty} undef"));
|
||||
break;
|
||||
}
|
||||
RetTerm::Unrenderable => return None,
|
||||
RetTerm::NotRet => {}
|
||||
}
|
||||
}
|
||||
let model = model?;
|
||||
let mut hit = false;
|
||||
let mut out = blocks.to_vec();
|
||||
for b in out.iter_mut() {
|
||||
// Detect an `unreachable` terminator from the carrier (the sole substrate).
|
||||
let is_unreachable = b.typed.as_ref().is_some_and(|t| {
|
||||
matches!(t.terminator, crate::native::tir::TirTerminator::Unreachable)
|
||||
});
|
||||
if is_unreachable {
|
||||
// Rewrite the `unreachable` -> `ret` terminator on the carrier.
|
||||
if let Some(t) = &mut b.typed {
|
||||
let t = std::sync::Arc::make_mut(t);
|
||||
t.set_terminator_line(&model);
|
||||
}
|
||||
hit = true;
|
||||
}
|
||||
}
|
||||
hit.then_some(out)
|
||||
}
|
||||
|
||||
/// Single-exit transform (transform #2 of the cross-arm cascade): route every `ret` through one
|
||||
/// Single-exit transform: route every `ret` through one
|
||||
/// synthesized exit block, so a divergent selection (arms that `ret` rather than reconverge) gains a
|
||||
/// natural merge — the common exit — instead of rejecting `selection:cond-no-natural`. Returns the
|
||||
/// rewritten blocks, or `None` if there are fewer than two `ret` blocks (nothing to unify) or the
|
||||
/// returns are not uniformly typed.
|
||||
/// returns are not uniformly typed. This helper is retained for focused transformation tests;
|
||||
/// production divergent-exit construction also includes unreachable exits.
|
||||
///
|
||||
/// For a void function the exit block is `ret void`; for a value-returning function it is a phi over
|
||||
/// the returned values (`%uret.v = phi T [v_i, %b_i]...`) followed by `ret T %uret.v`. Each original
|
||||
/// `ret` block's terminator becomes `br label %exit`. Floor-safe: invoked only behind the
|
||||
/// `inline_sroa_raw_cfg_restructure` retry, adopted only if `structured_plan` then admits.
|
||||
/// `ret` block's terminator becomes `br label %exit`.
|
||||
#[cfg(test)]
|
||||
pub(in crate::native) fn unify_returns(blocks: &[BodyBlock]) -> Option<Vec<BodyBlock>> {
|
||||
unify_return_like_exits(blocks, false)
|
||||
}
|
||||
@@ -199,6 +153,36 @@ pub(in crate::native) fn fresh(orig: &str, id: usize) -> String {
|
||||
format!("%xa{id}_{stripped}")
|
||||
}
|
||||
|
||||
/// 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
|
||||
/// can then preserve the two identities instead of accidentally renaming an external value use.
|
||||
pub(in crate::native) fn cloned_labels_overlap_ssa_values(
|
||||
blocks: &[BodyBlock],
|
||||
labels: &HashSet<String>,
|
||||
) -> bool {
|
||||
for block in blocks {
|
||||
let Some(carrier) = block.typed.as_ref() else {
|
||||
return true;
|
||||
};
|
||||
for instruction in &carrier.insts {
|
||||
if instruction
|
||||
.result
|
||||
.as_ref()
|
||||
.is_some_and(|result| labels.contains(result))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
let mut overlaps = false;
|
||||
instruction.visit_uses(|name| overlaps |= labels.contains(name));
|
||||
if overlaps {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// The SSA value a line defines (`%x = ...`), including the `%`, or `None` for a non-defining line.
|
||||
#[cfg(test)]
|
||||
pub(in crate::native) fn line_def(line: &str) -> Option<String> {
|
||||
|
||||
@@ -35,6 +35,14 @@ pub(in crate::native) struct DominatedRegionCloneWitness {
|
||||
pub first_empty_phi_block: Option<String>,
|
||||
}
|
||||
|
||||
/// Result of a dominated-region clone for callers that also own structural metadata keyed by block
|
||||
/// label. `renamed` contains every cloned block and SSA definition; labels absent from the map remain
|
||||
/// shared boundaries in `blocks`.
|
||||
pub(in crate::native) struct DominatedRegionClone {
|
||||
pub blocks: Vec<BodyBlock>,
|
||||
pub renamed: HashMap<String, String>,
|
||||
}
|
||||
|
||||
pub(in crate::native) fn dominated_region_clone_witness(
|
||||
blocks: &[BodyBlock],
|
||||
header: &str,
|
||||
@@ -138,7 +146,7 @@ pub(in crate::native) fn dominated_region_clone_witness(
|
||||
break;
|
||||
};
|
||||
if src_carrier.insts.iter().any(|inst| {
|
||||
inst.phi_incoming.as_ref().is_some_and(|(_, incoming)| {
|
||||
inst.phi_incoming().as_ref().is_some_and(|(_, incoming)| {
|
||||
!incoming.is_empty() && !incoming.iter().any(|(_, p)| keep(p))
|
||||
})
|
||||
}) {
|
||||
@@ -199,6 +207,7 @@ pub(in crate::native) struct RegionCrossArmFixpointWitness {
|
||||
/// Privatize the forward-closed region rooted at `arm` for `header`'s in-construct entries. Returns
|
||||
/// the new block list, or `None` if the region is not cleanly single-entry / loop-free-entry /
|
||||
/// within budget.
|
||||
#[cfg(test)]
|
||||
pub(in crate::native) fn privatize_region(
|
||||
blocks: &[BodyBlock],
|
||||
header: &str,
|
||||
@@ -266,6 +275,9 @@ pub(in crate::native) fn privatize_region(
|
||||
if !keeps_original {
|
||||
return None;
|
||||
}
|
||||
if cloned_labels_overlap_ssa_values(blocks, ®ion) {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Build the rename map: every block label in R + every SSA value defined in R gets a fresh name.
|
||||
let id = *counter;
|
||||
@@ -332,7 +344,7 @@ pub(in crate::native) fn privatize_region(
|
||||
return None;
|
||||
};
|
||||
for inst in &src_carrier.insts {
|
||||
if let Some((_, incoming)) = &inst.phi_incoming {
|
||||
if let Some((_, incoming)) = &inst.phi_incoming() {
|
||||
if !incoming.is_empty() && !incoming.iter().any(|(_, p)| keep(p)) {
|
||||
return None;
|
||||
}
|
||||
@@ -372,12 +384,12 @@ pub(in crate::native) fn privatize_region(
|
||||
/// (the boundary has a non-region predecessor). Mirroring the boundary phis therefore closes SSA.
|
||||
/// Returns `None` if the region is over budget, `arm` sits in an in-region cycle, or there is no
|
||||
/// dominated predecessor to redirect (or none to keep) — the same guards as [`privatize_region`].
|
||||
pub(in crate::native) fn privatize_dominated_region(
|
||||
pub(in crate::native) fn privatize_dominated_region_with_renames(
|
||||
blocks: &[BodyBlock],
|
||||
header: &str,
|
||||
arm: &str,
|
||||
counter: &mut usize,
|
||||
) -> Option<Vec<BodyBlock>> {
|
||||
) -> Option<DominatedRegionClone> {
|
||||
let forest = analyze(blocks);
|
||||
let preds = predecessors(blocks);
|
||||
let by_name: HashMap<&str, &BodyBlock> = blocks.iter().map(|b| (b.name.as_str(), b)).collect();
|
||||
@@ -454,6 +466,9 @@ pub(in crate::native) fn privatize_dominated_region(
|
||||
if !keeps_original {
|
||||
return None;
|
||||
}
|
||||
if cloned_labels_overlap_ssa_values(blocks, ®ion) {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Rename every region label + every SSA value defined in the region into a fresh clone namespace.
|
||||
let id = *counter;
|
||||
@@ -521,7 +536,7 @@ pub(in crate::native) fn privatize_dominated_region(
|
||||
return None;
|
||||
};
|
||||
for inst in &src_carrier.insts {
|
||||
if let Some((_, incoming)) = &inst.phi_incoming {
|
||||
if let Some((_, incoming)) = &inst.phi_incoming() {
|
||||
if !incoming.is_empty() && !incoming.iter().any(|(_, p)| keep(p)) {
|
||||
return None;
|
||||
}
|
||||
@@ -537,7 +552,20 @@ pub(in crate::native) fn privatize_dominated_region(
|
||||
typed: Some(c.into()),
|
||||
});
|
||||
}
|
||||
Some(out)
|
||||
Some(DominatedRegionClone {
|
||||
blocks: out,
|
||||
renamed: rename,
|
||||
})
|
||||
}
|
||||
|
||||
pub(in crate::native) fn privatize_dominated_region(
|
||||
blocks: &[BodyBlock],
|
||||
header: &str,
|
||||
arm: &str,
|
||||
counter: &mut usize,
|
||||
) -> Option<Vec<BodyBlock>> {
|
||||
privatize_dominated_region_with_renames(blocks, header, arm, counter)
|
||||
.map(|cloned| cloned.blocks)
|
||||
}
|
||||
|
||||
/// Append, to a boundary block's phi, a mirrored incoming for every existing incoming whose
|
||||
@@ -790,7 +818,7 @@ pub(in crate::native) fn privatize_shared_phi_exit_predecessors(
|
||||
cur
|
||||
}
|
||||
|
||||
/// Privatize a tail shared by two or more cases of a loop-free switch.
|
||||
/// Privatize a tail shared by two or more cases of a switch.
|
||||
///
|
||||
/// SPIR-V case constructs cannot enter a tail belonging to another case construct. A source switch can
|
||||
/// express that compactly by letting cases fall into shared suffixes (`case 3 -> tail1`, `case 2 ->
|
||||
@@ -803,8 +831,9 @@ pub(in crate::native) fn privatize_shared_phi_exit_predecessors(
|
||||
/// case retains the original.
|
||||
///
|
||||
/// It uses the same [`privatize_dominated_region`] SSA and boundary guards as conditional deep-tail
|
||||
/// privatization. Loop switches, direct merge exits, and large CFGs decline rather than inventing a
|
||||
/// multi-level break representation.
|
||||
/// privatization. Loop-contained tails are eligible only when the finder proves that the cloned region
|
||||
/// stays within one loop nest and avoids loop headers and latches. Direct merge exits and large CFGs
|
||||
/// decline rather than inventing a multi-level break representation.
|
||||
pub(in crate::native) fn privatize_switch_case_continuations(
|
||||
blocks: &[BodyBlock],
|
||||
) -> Vec<BodyBlock> {
|
||||
|
||||
@@ -1,18 +1,25 @@
|
||||
//! Compact dominance over an emitted SPIR-V function CFG.
|
||||
//!
|
||||
//! Shared by late native rewrites and the emitter's phi-materialization repair. The immediate-
|
||||
//! dominator tree uses O(V + E) storage and answers dominance with DFS intervals; the former
|
||||
//! Shared by late native rewrites. The immediate-dominator tree uses O(V + E) storage and answers
|
||||
//! dominance with DFS intervals; the former
|
||||
//! `label -> HashSet<all dominators>` representation was O(V²) and drove large translations far
|
||||
//! beyond their resident-memory budget even after those temporary sets were freed.
|
||||
|
||||
#[cfg(test)]
|
||||
use crate::spirv_module::{Function, Module, Operand};
|
||||
#[cfg(test)]
|
||||
use spirv::Op;
|
||||
use spirv::Word;
|
||||
use std::collections::HashMap;
|
||||
#[cfg(test)]
|
||||
use std::collections::HashSet;
|
||||
|
||||
pub(in crate::native) struct EmittedDominators {
|
||||
index: HashMap<Word, usize>,
|
||||
#[cfg(test)]
|
||||
immediate_dominator: Vec<Option<usize>>,
|
||||
preorder: Vec<usize>,
|
||||
postorder: Vec<usize>,
|
||||
depth: Vec<usize>,
|
||||
}
|
||||
|
||||
impl EmittedDominators {
|
||||
@@ -100,19 +107,16 @@ impl EmittedDominators {
|
||||
}
|
||||
let mut preorder = vec![usize::MAX; labels.len()];
|
||||
let mut postorder = vec![usize::MAX; labels.len()];
|
||||
let mut depth = vec![0; labels.len()];
|
||||
if let Some(&entry) = rpo.first() {
|
||||
let mut clock = 0usize;
|
||||
let mut stack = vec![(entry, 0usize)];
|
||||
preorder[entry] = clock;
|
||||
depth[entry] = 1;
|
||||
clock += 1;
|
||||
while let Some((node, next)) = stack.last_mut() {
|
||||
if *next < children[*node].len() {
|
||||
let child = children[*node][*next];
|
||||
*next += 1;
|
||||
preorder[child] = clock;
|
||||
depth[child] = depth[*node] + 1;
|
||||
clock += 1;
|
||||
stack.push((child, 0));
|
||||
} else {
|
||||
@@ -123,9 +127,10 @@ impl EmittedDominators {
|
||||
}
|
||||
Self {
|
||||
index,
|
||||
#[cfg(test)]
|
||||
immediate_dominator: idom,
|
||||
preorder,
|
||||
postorder,
|
||||
depth,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -139,11 +144,376 @@ impl EmittedDominators {
|
||||
&& self.preorder[node] < self.postorder[dominator]
|
||||
}
|
||||
|
||||
pub(in crate::native) fn depth(&self, label: Word) -> usize {
|
||||
self.index.get(&label).map_or(0, |index| self.depth[*index])
|
||||
/// Whether every reachable block's immediate dominator precedes it in serialized block order.
|
||||
#[cfg(test)]
|
||||
fn serialization_respects_dominance(&self) -> bool {
|
||||
self.immediate_dominator
|
||||
.iter()
|
||||
.enumerate()
|
||||
.all(|(node, dominator)| dominator.is_none_or(|dominator| dominator <= node))
|
||||
}
|
||||
}
|
||||
|
||||
/// Return functions whose constructed CFG violates a structural invariant: either an edge exits an
|
||||
/// inner selection anywhere other than a structured target, a dominance back-edge targets a block
|
||||
/// without an `OpLoopMerge`, a merge declaration is absent or displaced from its terminator,
|
||||
/// serialized blocks precede their dominators, or a function-local SSA definition does not dominate
|
||||
/// its use. A branch to an enclosing loop's merge/continue target and a continue-construct back edge
|
||||
/// to that loop's header are the structured loop-exit/continue exceptions.
|
||||
///
|
||||
/// Constant-CFG pruning can expose this shape after the source structurizer has already assigned
|
||||
/// merge ownership. This test-only checker guards the invariants that construction must establish
|
||||
/// before serialization.
|
||||
#[cfg(test)]
|
||||
fn functions_violating_constructed_cfg(module: &Module) -> HashSet<Word> {
|
||||
module
|
||||
.functions
|
||||
.iter()
|
||||
.filter(|function| {
|
||||
function_has_invalid_selection_exit(function)
|
||||
|| function_has_unmarked_back_edge(function)
|
||||
|| function_has_unmarked_selection(function)
|
||||
|| function_has_displaced_merge(function)
|
||||
|| function_has_late_dominator(function)
|
||||
|| function_has_non_dominating_value_use(function)
|
||||
})
|
||||
.filter_map(|function| function.def.as_ref()?.result_id)
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn function_has_unmarked_selection(function: &Function) -> bool {
|
||||
function.blocks.iter().any(|block| {
|
||||
let Some((terminator, prefix)) = block.instructions.split_last() else {
|
||||
return false;
|
||||
};
|
||||
if !matches!(terminator.class.opcode, Op::BranchConditional | Op::Switch) {
|
||||
return false;
|
||||
}
|
||||
!prefix.last().is_some_and(|instruction| {
|
||||
matches!(instruction.class.opcode, Op::SelectionMerge | Op::LoopMerge)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn function_has_displaced_merge(function: &Function) -> bool {
|
||||
function.blocks.iter().any(|block| {
|
||||
let Some((terminator, prefix)) = block.instructions.split_last() else {
|
||||
return false;
|
||||
};
|
||||
prefix
|
||||
.iter()
|
||||
.enumerate()
|
||||
.find(|(_, instruction)| {
|
||||
matches!(instruction.class.opcode, Op::SelectionMerge | Op::LoopMerge)
|
||||
})
|
||||
.is_some_and(|(merge_index, merge)| {
|
||||
merge_index + 1 != prefix.len()
|
||||
|| match merge.class.opcode {
|
||||
Op::SelectionMerge => {
|
||||
!matches!(terminator.class.opcode, Op::BranchConditional | Op::Switch)
|
||||
}
|
||||
Op::LoopMerge => {
|
||||
!matches!(terminator.class.opcode, Op::Branch | Op::BranchConditional)
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn function_has_late_dominator(function: &Function) -> bool {
|
||||
let labels = function
|
||||
.blocks
|
||||
.iter()
|
||||
.filter_map(|block| block.label.as_ref()?.result_id)
|
||||
.collect::<Vec<_>>();
|
||||
let Some(&entry) = labels.first() else {
|
||||
return false;
|
||||
};
|
||||
let successors = super::graph::spirv_block_successors_by_label(&function.blocks);
|
||||
let dominators = EmittedDominators::new(entry, &labels, &successors);
|
||||
!dominators.serialization_respects_dominance()
|
||||
}
|
||||
|
||||
/// Whether a function-local SSA definition fails to dominate an ordinary use or a phi's incoming
|
||||
/// predecessor edge. Module-scope ids, function parameters, labels, and types are deliberately
|
||||
/// absent from `definitions`; their availability follows different SPIR-V rules.
|
||||
#[cfg(test)]
|
||||
fn function_has_non_dominating_value_use(function: &Function) -> bool {
|
||||
let labels = function
|
||||
.blocks
|
||||
.iter()
|
||||
.filter_map(|block| block.label.as_ref()?.result_id)
|
||||
.collect::<Vec<_>>();
|
||||
let Some(&entry) = labels.first() else {
|
||||
return false;
|
||||
};
|
||||
let successors = super::graph::spirv_block_successors_by_label(&function.blocks);
|
||||
let dominators = EmittedDominators::new(entry, &labels, &successors);
|
||||
let definitions = function
|
||||
.blocks
|
||||
.iter()
|
||||
.enumerate()
|
||||
.flat_map(|(block_index, block)| {
|
||||
block.instructions.iter().enumerate().filter_map(
|
||||
move |(instruction_index, instruction)| {
|
||||
Some((instruction.result_id?, (block_index, instruction_index)))
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect::<HashMap<_, _>>();
|
||||
let label_indices = labels
|
||||
.iter()
|
||||
.copied()
|
||||
.enumerate()
|
||||
.map(|(index, label)| (label, index))
|
||||
.collect::<HashMap<_, _>>();
|
||||
|
||||
for (use_block, block) in function.blocks.iter().enumerate() {
|
||||
for (use_instruction, instruction) in block.instructions.iter().enumerate() {
|
||||
if instruction.class.opcode == Op::Phi {
|
||||
for pair in instruction.operands.chunks_exact(2) {
|
||||
let (Operand::IdRef(value), Operand::IdRef(predecessor)) = (&pair[0], &pair[1])
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let (Some(&(definition_block, _)), Some(&predecessor_block)) =
|
||||
(definitions.get(value), label_indices.get(predecessor))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if definition_block != predecessor_block
|
||||
&& !dominators.dominates(labels[definition_block], *predecessor)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
for operand in &instruction.operands {
|
||||
let Operand::IdRef(value) = operand else {
|
||||
continue;
|
||||
};
|
||||
let Some(&(definition_block, definition_instruction)) = definitions.get(value)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let dominates = if definition_block == use_block {
|
||||
definition_instruction < use_instruction
|
||||
} else {
|
||||
dominators.dominates(labels[definition_block], labels[use_block])
|
||||
};
|
||||
if !dominates {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn function_has_unmarked_back_edge(function: &Function) -> bool {
|
||||
let labels = function
|
||||
.blocks
|
||||
.iter()
|
||||
.filter_map(|block| block.label.as_ref()?.result_id)
|
||||
.collect::<Vec<_>>();
|
||||
let Some(&entry) = labels.first() else {
|
||||
return false;
|
||||
};
|
||||
let successors = super::graph::spirv_block_successors_by_label(&function.blocks);
|
||||
let dominators = EmittedDominators::new(entry, &labels, &successors);
|
||||
let loop_headers = function
|
||||
.blocks
|
||||
.iter()
|
||||
.filter(|block| {
|
||||
block
|
||||
.instructions
|
||||
.iter()
|
||||
.any(|instruction| instruction.class.opcode == Op::LoopMerge)
|
||||
})
|
||||
.filter_map(|block| block.label.as_ref()?.result_id)
|
||||
.collect::<HashSet<_>>();
|
||||
for (source, targets) in &successors {
|
||||
for target in targets {
|
||||
if dominators.dominates(*target, *source) && !loop_headers.contains(target) {
|
||||
if crate::env_vars::reloop_why() {
|
||||
eprintln!(
|
||||
"UNMARKED-BACKEDGE function={:?} source={source} target={target}",
|
||||
function
|
||||
.def
|
||||
.as_ref()
|
||||
.and_then(|definition| definition.result_id)
|
||||
);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn function_has_invalid_selection_exit(function: &Function) -> bool {
|
||||
let labels = function
|
||||
.blocks
|
||||
.iter()
|
||||
.filter_map(|block| block.label.as_ref()?.result_id)
|
||||
.collect::<Vec<_>>();
|
||||
let Some(&entry) = labels.first() else {
|
||||
return false;
|
||||
};
|
||||
let successors = super::graph::spirv_block_successors_by_label(&function.blocks);
|
||||
let dominators = EmittedDominators::new(entry, &labels, &successors);
|
||||
let terminal_targets = function
|
||||
.blocks
|
||||
.iter()
|
||||
.filter(|block| {
|
||||
block.instructions.last().is_some_and(|terminator| {
|
||||
matches!(
|
||||
terminator.class.opcode,
|
||||
Op::Return | Op::ReturnValue | Op::Unreachable
|
||||
)
|
||||
})
|
||||
})
|
||||
.filter_map(|block| block.label.as_ref()?.result_id)
|
||||
.collect::<HashSet<_>>();
|
||||
let loop_constructs = function
|
||||
.blocks
|
||||
.iter()
|
||||
.filter_map(|block| {
|
||||
let header = block.label.as_ref()?.result_id?;
|
||||
let merge = block
|
||||
.instructions
|
||||
.iter()
|
||||
.find(|instruction| instruction.class.opcode == Op::LoopMerge)?;
|
||||
let (Some(Operand::IdRef(merge)), Some(Operand::IdRef(continue_target))) =
|
||||
(merge.operands.first(), merge.operands.get(1))
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
Some((header, *merge, *continue_target))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
for block in &function.blocks {
|
||||
let Some(header) = block.label.as_ref().and_then(|label| label.result_id) else {
|
||||
continue;
|
||||
};
|
||||
let Some(merge) = block
|
||||
.instructions
|
||||
.iter()
|
||||
.find(|instruction| instruction.class.opcode == Op::SelectionMerge)
|
||||
.and_then(|instruction| instruction.operands.first())
|
||||
.and_then(|operand| match operand {
|
||||
Operand::IdRef(merge) => Some(*merge),
|
||||
_ => None,
|
||||
})
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let enclosing_loop_targets = loop_constructs
|
||||
.iter()
|
||||
.filter(|(loop_header, loop_merge, _)| {
|
||||
dominators.dominates(*loop_header, header)
|
||||
&& !dominators.dominates(*loop_merge, header)
|
||||
})
|
||||
.flat_map(|(_, loop_merge, continue_target)| [*loop_merge, *continue_target])
|
||||
.collect::<HashSet<_>>();
|
||||
let members = labels
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|label| {
|
||||
dominators.dominates(header, *label) && !dominators.dominates(merge, *label)
|
||||
})
|
||||
.collect::<HashSet<_>>();
|
||||
for (source, targets) in &successors {
|
||||
if members.contains(source) {
|
||||
continue;
|
||||
}
|
||||
if let Some(target) = targets
|
||||
.iter()
|
||||
.find(|target| **target != header && members.contains(target))
|
||||
{
|
||||
if crate::env_vars::reloop_why() {
|
||||
eprintln!(
|
||||
"NONHEADER-CONSTRUCT-ENTRY function={:?} header={header} merge={merge} source={source} target={target}",
|
||||
function.def.as_ref().and_then(|definition| definition.result_id)
|
||||
);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
for member in members {
|
||||
for target in successors.get(&member).into_iter().flatten() {
|
||||
let stays_in_selection =
|
||||
dominators.dominates(header, *target) && !dominators.dominates(merge, *target);
|
||||
// A loop's continue target may also be its back-edge block. A selection containing
|
||||
// that block legally exits by taking the back edge to the enclosing loop header.
|
||||
// Do not send an already structured module through the relooper merely because the
|
||||
// edge targets the header rather than the continue target: require the source to be
|
||||
// dominated by that exact loop's continue target, so an ordinary selection arm
|
||||
// cannot bypass the continue construct.
|
||||
let is_enclosing_loop_back_edge =
|
||||
loop_constructs
|
||||
.iter()
|
||||
.any(|(loop_header, loop_merge, continue_target)| {
|
||||
*target == *loop_header
|
||||
&& dominators.dominates(*loop_header, header)
|
||||
&& !dominators.dominates(*loop_merge, header)
|
||||
&& dominators.dominates(*continue_target, member)
|
||||
});
|
||||
let is_structured_exit = *target == merge
|
||||
|| enclosing_loop_targets.contains(target)
|
||||
|| is_enclosing_loop_back_edge
|
||||
|| terminal_targets.contains(target);
|
||||
if !stays_in_selection && !is_structured_exit {
|
||||
if crate::env_vars::reloop_why() {
|
||||
let target_block = function.blocks.iter().find(|block| {
|
||||
block.label.as_ref().and_then(|label| label.result_id) == Some(*target)
|
||||
});
|
||||
let claims = function
|
||||
.blocks
|
||||
.iter()
|
||||
.filter_map(|block| {
|
||||
let claim_header = block.label.as_ref()?.result_id?;
|
||||
let claim = block.instructions.iter().find(|instruction| {
|
||||
matches!(
|
||||
instruction.class.opcode,
|
||||
Op::SelectionMerge | Op::LoopMerge
|
||||
) && instruction
|
||||
.operands
|
||||
.iter()
|
||||
.any(|operand| operand == &Operand::IdRef(*target))
|
||||
})?;
|
||||
Some((
|
||||
claim.class.opcode,
|
||||
claim_header,
|
||||
dominators.dominates(claim_header, header),
|
||||
dominators.dominates(*target, header),
|
||||
))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
eprintln!(
|
||||
"STRUCTURED-EXIT function={:?} header={header} merge={merge} header_dominates_merge={} member={member} target={target} target_ops={:?} claims={claims:?}",
|
||||
function.def.as_ref().and_then(|definition| definition.result_id),
|
||||
dominators.dominates(header, merge),
|
||||
target_block.map(|block| block.instructions.iter().map(|instruction| instruction.class.opcode).collect::<Vec<_>>())
|
||||
);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn intersect(
|
||||
mut left: usize,
|
||||
mut right: usize,
|
||||
@@ -160,3 +530,419 @@ fn intersect(
|
||||
}
|
||||
left
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::spirv_module::{Block, Instruction};
|
||||
|
||||
fn instruction(opcode: Op, result_id: Option<Word>, operands: Vec<Operand>) -> Instruction {
|
||||
Instruction::new(opcode, None, result_id, operands)
|
||||
}
|
||||
|
||||
fn block(label: Word, instructions: Vec<Instruction>) -> Block {
|
||||
Block {
|
||||
label: Some(instruction(Op::Label, Some(label), vec![])),
|
||||
instructions,
|
||||
}
|
||||
}
|
||||
|
||||
fn branch(target: Word) -> Instruction {
|
||||
instruction(Op::Branch, None, vec![Operand::IdRef(target)])
|
||||
}
|
||||
|
||||
fn conditional(if_true: Word, if_false: Word) -> Instruction {
|
||||
instruction(
|
||||
Op::BranchConditional,
|
||||
None,
|
||||
vec![
|
||||
Operand::IdRef(99),
|
||||
Operand::IdRef(if_true),
|
||||
Operand::IdRef(if_false),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
fn selection(merge: Word) -> Instruction {
|
||||
instruction(
|
||||
Op::SelectionMerge,
|
||||
None,
|
||||
vec![
|
||||
Operand::IdRef(merge),
|
||||
Operand::SelectionControl(spirv::SelectionControl::NONE),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
fn test_module(blocks: Vec<Block>) -> Module {
|
||||
let mut module = Module::default();
|
||||
module.functions.push(Function {
|
||||
def: Some(instruction(Op::Function, Some(100), vec![])),
|
||||
blocks,
|
||||
..Function::default()
|
||||
});
|
||||
module
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detects_inner_selection_arm_exiting_to_outer_selection_merge() {
|
||||
let module = test_module(vec![
|
||||
block(1, vec![selection(8), conditional(2, 7)]),
|
||||
block(2, vec![selection(6), conditional(3, 6)]),
|
||||
block(3, vec![branch(8)]),
|
||||
block(6, vec![branch(8)]),
|
||||
block(7, vec![branch(8)]),
|
||||
block(8, vec![branch(9)]),
|
||||
block(9, vec![instruction(Op::Return, None, vec![])]),
|
||||
]);
|
||||
assert_eq!(
|
||||
functions_violating_constructed_cfg(&module),
|
||||
HashSet::from([100])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepts_nested_selection_exiting_through_its_own_merge() {
|
||||
let module = test_module(vec![
|
||||
block(1, vec![selection(8), conditional(2, 7)]),
|
||||
block(2, vec![selection(6), conditional(3, 6)]),
|
||||
block(3, vec![branch(6)]),
|
||||
block(6, vec![branch(8)]),
|
||||
block(7, vec![branch(8)]),
|
||||
block(8, vec![instruction(Op::Return, None, vec![])]),
|
||||
]);
|
||||
assert!(functions_violating_constructed_cfg(&module).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepts_inner_selection_break_to_enclosing_loop_merge() {
|
||||
let module = test_module(vec![
|
||||
block(1, vec![branch(2)]),
|
||||
block(
|
||||
2,
|
||||
vec![
|
||||
instruction(
|
||||
Op::LoopMerge,
|
||||
None,
|
||||
vec![
|
||||
Operand::IdRef(9),
|
||||
Operand::IdRef(8),
|
||||
Operand::LoopControl(spirv::LoopControl::NONE),
|
||||
],
|
||||
),
|
||||
branch(3),
|
||||
],
|
||||
),
|
||||
block(3, vec![selection(6), conditional(4, 6)]),
|
||||
block(4, vec![branch(9)]),
|
||||
block(6, vec![branch(8)]),
|
||||
block(8, vec![branch(2)]),
|
||||
block(9, vec![instruction(Op::Return, None, vec![])]),
|
||||
]);
|
||||
assert!(functions_violating_constructed_cfg(&module).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepts_selection_back_edge_from_enclosing_loop_continue_target() {
|
||||
let module = test_module(vec![
|
||||
block(1, vec![branch(2)]),
|
||||
block(
|
||||
2,
|
||||
vec![
|
||||
instruction(
|
||||
Op::LoopMerge,
|
||||
None,
|
||||
vec![
|
||||
Operand::IdRef(9),
|
||||
Operand::IdRef(8),
|
||||
Operand::LoopControl(spirv::LoopControl::NONE),
|
||||
],
|
||||
),
|
||||
branch(3),
|
||||
],
|
||||
),
|
||||
block(3, vec![selection(7), conditional(7, 8)]),
|
||||
block(7, vec![branch(9)]),
|
||||
block(8, vec![branch(2)]),
|
||||
block(9, vec![instruction(Op::Return, None, vec![])]),
|
||||
]);
|
||||
assert!(functions_violating_constructed_cfg(&module).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detects_selection_arm_bypassing_enclosing_loop_continue_target() {
|
||||
let module = test_module(vec![
|
||||
block(1, vec![branch(2)]),
|
||||
block(
|
||||
2,
|
||||
vec![
|
||||
instruction(
|
||||
Op::LoopMerge,
|
||||
None,
|
||||
vec![
|
||||
Operand::IdRef(9),
|
||||
Operand::IdRef(8),
|
||||
Operand::LoopControl(spirv::LoopControl::NONE),
|
||||
],
|
||||
),
|
||||
branch(3),
|
||||
],
|
||||
),
|
||||
block(3, vec![selection(7), conditional(4, 7)]),
|
||||
block(4, vec![branch(2)]),
|
||||
block(7, vec![branch(8)]),
|
||||
block(8, vec![branch(2)]),
|
||||
block(9, vec![instruction(Op::Return, None, vec![])]),
|
||||
]);
|
||||
assert_eq!(
|
||||
functions_violating_constructed_cfg(&module),
|
||||
HashSet::from([100])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detects_non_dominating_ordinary_value_use() {
|
||||
let module = test_module(vec![
|
||||
block(1, vec![selection(4), conditional(2, 3)]),
|
||||
block(
|
||||
2,
|
||||
vec![
|
||||
instruction(
|
||||
Op::IAdd,
|
||||
Some(50),
|
||||
vec![Operand::IdRef(90), Operand::IdRef(91)],
|
||||
),
|
||||
branch(4),
|
||||
],
|
||||
),
|
||||
block(3, vec![branch(4)]),
|
||||
block(
|
||||
4,
|
||||
vec![
|
||||
instruction(
|
||||
Op::IAdd,
|
||||
Some(51),
|
||||
vec![Operand::IdRef(50), Operand::IdRef(91)],
|
||||
),
|
||||
instruction(Op::Return, None, vec![]),
|
||||
],
|
||||
),
|
||||
]);
|
||||
assert_eq!(
|
||||
functions_violating_constructed_cfg(&module),
|
||||
HashSet::from([100])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepts_phi_values_defined_on_their_incoming_edges() {
|
||||
let module = test_module(vec![
|
||||
block(1, vec![selection(4), conditional(2, 3)]),
|
||||
block(
|
||||
2,
|
||||
vec![
|
||||
instruction(
|
||||
Op::IAdd,
|
||||
Some(50),
|
||||
vec![Operand::IdRef(90), Operand::IdRef(91)],
|
||||
),
|
||||
branch(4),
|
||||
],
|
||||
),
|
||||
block(
|
||||
3,
|
||||
vec![
|
||||
instruction(
|
||||
Op::IAdd,
|
||||
Some(51),
|
||||
vec![Operand::IdRef(90), Operand::IdRef(91)],
|
||||
),
|
||||
branch(4),
|
||||
],
|
||||
),
|
||||
block(
|
||||
4,
|
||||
vec![
|
||||
instruction(
|
||||
Op::Phi,
|
||||
Some(52),
|
||||
vec![
|
||||
Operand::IdRef(50),
|
||||
Operand::IdRef(2),
|
||||
Operand::IdRef(51),
|
||||
Operand::IdRef(3),
|
||||
],
|
||||
),
|
||||
instruction(Op::Return, None, vec![]),
|
||||
],
|
||||
),
|
||||
]);
|
||||
assert!(functions_violating_constructed_cfg(&module).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detects_phi_value_not_dominating_its_incoming_edge() {
|
||||
let module = test_module(vec![
|
||||
block(1, vec![selection(4), conditional(2, 3)]),
|
||||
block(
|
||||
2,
|
||||
vec![
|
||||
instruction(
|
||||
Op::IAdd,
|
||||
Some(50),
|
||||
vec![Operand::IdRef(90), Operand::IdRef(91)],
|
||||
),
|
||||
branch(4),
|
||||
],
|
||||
),
|
||||
block(3, vec![branch(4)]),
|
||||
block(
|
||||
4,
|
||||
vec![
|
||||
instruction(
|
||||
Op::Phi,
|
||||
Some(52),
|
||||
vec![
|
||||
Operand::IdRef(50),
|
||||
Operand::IdRef(2),
|
||||
Operand::IdRef(50),
|
||||
Operand::IdRef(3),
|
||||
],
|
||||
),
|
||||
instruction(Op::Return, None, vec![]),
|
||||
],
|
||||
),
|
||||
]);
|
||||
assert_eq!(
|
||||
functions_violating_constructed_cfg(&module),
|
||||
HashSet::from([100])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepts_selection_arm_exiting_to_shared_terminal_block() {
|
||||
let module = test_module(vec![
|
||||
block(1, vec![selection(8), conditional(2, 7)]),
|
||||
block(2, vec![selection(6), conditional(3, 6)]),
|
||||
block(3, vec![branch(9)]),
|
||||
block(6, vec![branch(8)]),
|
||||
block(7, vec![branch(9)]),
|
||||
block(8, vec![instruction(Op::Return, None, vec![])]),
|
||||
block(9, vec![instruction(Op::Return, None, vec![])]),
|
||||
]);
|
||||
assert!(functions_violating_constructed_cfg(&module).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detects_post_merge_reentry_into_selection_terminal() {
|
||||
let module = test_module(vec![
|
||||
block(1, vec![selection(6), conditional(3, 6)]),
|
||||
block(3, vec![branch(9)]),
|
||||
block(6, vec![branch(7)]),
|
||||
block(7, vec![branch(9)]),
|
||||
block(9, vec![instruction(Op::Return, None, vec![])]),
|
||||
]);
|
||||
assert_eq!(
|
||||
functions_violating_constructed_cfg(&module),
|
||||
HashSet::from([100])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detects_back_edge_to_header_without_loop_merge() {
|
||||
let module = test_module(vec![
|
||||
block(1, vec![branch(2)]),
|
||||
block(2, vec![conditional(3, 4)]),
|
||||
block(3, vec![branch(2)]),
|
||||
block(4, vec![instruction(Op::Return, None, vec![])]),
|
||||
]);
|
||||
assert_eq!(
|
||||
functions_violating_constructed_cfg(&module),
|
||||
HashSet::from([100])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepts_back_edge_to_declared_loop_header() {
|
||||
let module = test_module(vec![
|
||||
block(1, vec![branch(2)]),
|
||||
block(
|
||||
2,
|
||||
vec![
|
||||
instruction(
|
||||
Op::LoopMerge,
|
||||
None,
|
||||
vec![
|
||||
Operand::IdRef(4),
|
||||
Operand::IdRef(3),
|
||||
Operand::LoopControl(spirv::LoopControl::NONE),
|
||||
],
|
||||
),
|
||||
conditional(3, 4),
|
||||
],
|
||||
),
|
||||
block(3, vec![branch(2)]),
|
||||
block(4, vec![instruction(Op::Return, None, vec![])]),
|
||||
]);
|
||||
assert!(functions_violating_constructed_cfg(&module).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detects_block_serialized_before_its_dominator() {
|
||||
let module = test_module(vec![
|
||||
block(1, vec![branch(2)]),
|
||||
block(3, vec![instruction(Op::Return, None, vec![])]),
|
||||
block(2, vec![branch(3)]),
|
||||
]);
|
||||
assert_eq!(
|
||||
functions_violating_constructed_cfg(&module),
|
||||
HashSet::from([100])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detects_conditional_without_merge_declaration() {
|
||||
let module = test_module(vec![
|
||||
block(1, vec![conditional(2, 3)]),
|
||||
block(2, vec![instruction(Op::Return, None, vec![])]),
|
||||
block(3, vec![instruction(Op::Return, None, vec![])]),
|
||||
]);
|
||||
assert_eq!(
|
||||
functions_violating_constructed_cfg(&module),
|
||||
HashSet::from([100])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detects_loop_merge_displaced_from_its_terminator() {
|
||||
let module = test_module(vec![
|
||||
block(1, vec![branch(2)]),
|
||||
block(
|
||||
2,
|
||||
vec![
|
||||
instruction(
|
||||
Op::LoopMerge,
|
||||
None,
|
||||
vec![
|
||||
Operand::IdRef(4),
|
||||
Operand::IdRef(3),
|
||||
Operand::LoopControl(spirv::LoopControl::NONE),
|
||||
],
|
||||
),
|
||||
instruction(
|
||||
Op::IAdd,
|
||||
Some(50),
|
||||
vec![Operand::IdRef(90), Operand::IdRef(91)],
|
||||
),
|
||||
branch(3),
|
||||
],
|
||||
),
|
||||
block(3, vec![branch(2)]),
|
||||
block(4, vec![instruction(Op::Return, None, vec![])]),
|
||||
]);
|
||||
assert_eq!(
|
||||
functions_violating_constructed_cfg(&module),
|
||||
HashSet::from([100])
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -374,23 +374,6 @@ pub(in crate::native) fn spirv_block_successors_by_label(
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Invert a Word-keyed successor map into predecessors, deduping duplicate (target, pred) edges.
|
||||
pub(in crate::native) fn spirv_predecessor_ids_by_label(
|
||||
successors: &HashMap<Word, Vec<Word>>,
|
||||
) -> HashMap<Word, Vec<Word>> {
|
||||
let mut predecessors: HashMap<Word, Vec<Word>> = HashMap::new();
|
||||
let mut seen: HashSet<(Word, Word)> = HashSet::new();
|
||||
for (pred, targets) in successors {
|
||||
for target in targets {
|
||||
if !seen.insert((*target, *pred)) {
|
||||
continue;
|
||||
}
|
||||
predecessors.entry(*target).or_default().push(*pred);
|
||||
}
|
||||
}
|
||||
predecessors
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -1,715 +0,0 @@
|
||||
//! Post-emit multi-entry-loop split on an EMITTED SPIR-V module: node-split a loop whose header is
|
||||
//! entered from two different selections' arms, so each entry gets its own single-entry loop.
|
||||
//!
|
||||
//! The structurizer-by-construction can ADMIT (its self-checks do not catch it) a function whose
|
||||
//! emitted CFG has a loop header `R` reached by a forward edge from BOTH an inner selection's arm and
|
||||
//! an enclosing selection's arm — a MULTI-ENTRY (irreducible) loop. SPIR-V structured control flow
|
||||
//! requires each loop to be single-entry (the header dominates the whole loop), so spirv-val rejects
|
||||
//! it, surfacing as *"block X exits the selection headed by Y, but not via a structured exit"* (the
|
||||
//! inner arm's block escapes its selection into the shared loop). The mlx-steel `steel_attention`
|
||||
//! kernel family is the canonical case: `if a { …; if b { work } else { →L } } else { →L }` where `L`
|
||||
//! is a loop — the inner `else` and the outer `else` both enter `L`.
|
||||
//!
|
||||
//! The fix duplicates `L`'s loop region for the INNER arm's entry (the "broken" one — whose enclosing
|
||||
//! selection's merge is NOT the loop's own exit, so its arm cannot reconverge at that merge), routing
|
||||
//! the clone's exit to that selection's merge. The other entry keeps the original loop. Each loop is
|
||||
//! then single-entry and each selection's arms reconverge at its own merge. This is exactly the
|
||||
//! node-splitting the relooper retry already applies to these functions; doing it surgically on the
|
||||
//! structured CFG makes its PRIMARY output valid instead of shipping only via the relooper retry.
|
||||
//!
|
||||
//! Applies ONLY when the whole loop region has NO SSA value used past its single exit boundary (the
|
||||
//! `steel_attention` loops only store to Workgroup memory), so the clone is self-contained and needs no
|
||||
//! exit-phi synthesis. Floor-safe by construction: a single-entry (valid) loop has < 2 forward header
|
||||
//! predecessors so the scan finds nothing and the module is byte-identical; a matched region that is
|
||||
//! not cleanly cloneable (multiple exits, escaping SSA, a boundary phi over region values) is left in
|
||||
//! place (that function stays on the floor, no regression). Decides purely from IR structure (loop
|
||||
//! merges, block edges, dominance), never a shader name.
|
||||
|
||||
use super::graph::{spirv_block_successors_by_label, spirv_predecessor_ids_by_label};
|
||||
use super::EmittedDominators;
|
||||
use crate::spirv_module::Module;
|
||||
use crate::spirv_module::Operand;
|
||||
use crate::spirv_module::{Block, Function, Instruction};
|
||||
use spirv::{Op, Word};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
/// Cap on cloned region size so a pathological loop cannot blow up emission.
|
||||
const MAX_REGION_BLOCKS: usize = 96;
|
||||
|
||||
/// Split every multi-entry loop whose extra entries are broken selection arms. Returns true if any
|
||||
/// clone was applied.
|
||||
pub(in crate::native) fn split_multientry_loop_selection_exits(module: &mut Module) -> bool {
|
||||
let mut next_id = module.header.as_ref().map(|h| h.bound).unwrap_or(0);
|
||||
let mut fresh = || {
|
||||
let id = next_id;
|
||||
next_id += 1;
|
||||
id
|
||||
};
|
||||
let mut any = false;
|
||||
for function in &mut module.functions {
|
||||
any |= split_in_function(function, &mut fresh);
|
||||
}
|
||||
if any {
|
||||
if let Some(header) = module.header.as_mut() {
|
||||
header.bound = next_id;
|
||||
}
|
||||
}
|
||||
any
|
||||
}
|
||||
|
||||
/// A planned clone: the loop entry (`arm`) to privatize, the region blocks (labels, in a stable order),
|
||||
/// the loop's single exit boundary (`mo`), and the selection merge (`ms`) the clone must reconverge at.
|
||||
struct Plan {
|
||||
arm: Word,
|
||||
region: Vec<Word>,
|
||||
mo: Word,
|
||||
ms: Word,
|
||||
}
|
||||
|
||||
fn split_in_function(function: &mut Function, fresh: &mut impl FnMut() -> Word) -> bool {
|
||||
let Some(entry) = function
|
||||
.blocks
|
||||
.first()
|
||||
.and_then(|b| b.label.as_ref()?.result_id)
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
let labels: Vec<Word> = function
|
||||
.blocks
|
||||
.iter()
|
||||
.filter_map(|b| b.label.as_ref()?.result_id)
|
||||
.collect();
|
||||
let label_set: HashSet<Word> = labels.iter().copied().collect();
|
||||
let successors = spirv_block_successors_by_label(&function.blocks);
|
||||
let preds = spirv_predecessor_ids_by_label(&successors);
|
||||
let dominators = EmittedDominators::new(entry, &labels, &successors);
|
||||
let dominates = |a: Word, b: Word| dominators.dominates(a, b);
|
||||
let depth = |n: Word| dominators.depth(n);
|
||||
|
||||
// Loop headers (block with OpLoopMerge) → its merge block.
|
||||
let mut loop_merge: HashMap<Word, Word> = HashMap::new();
|
||||
// Selection headers (block with OpSelectionMerge whose terminator is a conditional branch, not a
|
||||
// switch) → its merge block.
|
||||
let mut sel_merge: Vec<(Word, Word)> = Vec::new();
|
||||
for block in &function.blocks {
|
||||
let Some(h) = block.label.as_ref().and_then(|l| l.result_id) else {
|
||||
continue;
|
||||
};
|
||||
let is_switch = block
|
||||
.instructions
|
||||
.last()
|
||||
.is_some_and(|i| i.class.opcode == Op::Switch);
|
||||
for inst in &block.instructions {
|
||||
match inst.class.opcode {
|
||||
Op::LoopMerge => {
|
||||
if let Some(Operand::IdRef(m)) = inst.operands.first() {
|
||||
loop_merge.insert(h, *m);
|
||||
}
|
||||
}
|
||||
Op::SelectionMerge if !is_switch => {
|
||||
if let Some(Operand::IdRef(m)) = inst.operands.first() {
|
||||
sel_merge.push((h, *m));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
if loop_merge.is_empty() {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Innermost enclosing selection (header, merge) of a block P: the deepest selection header that
|
||||
// dominates P without its merge dominating P.
|
||||
let innermost_sel = |p: Word| -> Option<(Word, Word)> {
|
||||
sel_merge
|
||||
.iter()
|
||||
.filter(|(h, m)| *h != p && dominates(*h, p) && !dominates(*m, p))
|
||||
.max_by_key(|(h, _)| depth(*h))
|
||||
.copied()
|
||||
};
|
||||
|
||||
// value id -> region membership is per-loop; collect ALL result ids once for the escaping-SSA check.
|
||||
let mut plans: Vec<Plan> = Vec::new();
|
||||
for (&r, &rm) in &loop_merge {
|
||||
// Forward predecessors of the header: preds NOT dominated by the header (a dominated pred is a
|
||||
// back-edge / in-loop latch).
|
||||
let fwd: Vec<Word> = preds
|
||||
.get(&r)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.copied()
|
||||
.filter(|&p| !dominates(r, p))
|
||||
.collect();
|
||||
if fwd.len() < 2 {
|
||||
continue; // single-entry loop — valid, nothing to split
|
||||
}
|
||||
// Region = the loop construct + its merge: blocks the header dominates, excluding anything the
|
||||
// merge dominates (post-loop tail), plus the merge itself.
|
||||
let region: Vec<Word> = labels
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|&b| dominates(r, b) && (b == rm || !dominates(rm, b)))
|
||||
.collect();
|
||||
if region.len() > MAX_REGION_BLOCKS {
|
||||
continue;
|
||||
}
|
||||
let region_set: HashSet<Word> = region.iter().copied().collect();
|
||||
// Single exit boundary: exactly one block outside the region that the region branches to.
|
||||
let mut boundary: HashSet<Word> = HashSet::new();
|
||||
for &b in ®ion {
|
||||
for &s in successors.get(&b).into_iter().flatten() {
|
||||
if !region_set.contains(&s) {
|
||||
boundary.insert(s);
|
||||
}
|
||||
}
|
||||
}
|
||||
if boundary.len() != 1 {
|
||||
continue;
|
||||
}
|
||||
let mo = *boundary.iter().next().unwrap();
|
||||
|
||||
// No SSA value defined in the region may be used outside it (else the clone would need exit-phi
|
||||
// synthesis); and the boundary block must have no OpPhi reading a region predecessor.
|
||||
if region_escapes(function, ®ion_set, mo) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Partition forward entries: an entry is BROKEN (needs its own loop copy) when its innermost
|
||||
// enclosing selection's merge is not the loop's own exit `mo` and is outside the region — its
|
||||
// arm cannot reconverge at that merge because it dives into the shared loop instead. An entry
|
||||
// whose enclosing selection merges at `mo` (or has none) is already well-formed; it keeps the
|
||||
// original loop.
|
||||
let mut to_clone: Vec<(Word, Word)> = Vec::new(); // (arm, ms)
|
||||
let mut keepers = 0usize;
|
||||
for &p in &fwd {
|
||||
match innermost_sel(p) {
|
||||
Some((_hs, ms)) if ms != mo && !region_set.contains(&ms) => {
|
||||
to_clone.push((p, ms));
|
||||
}
|
||||
_ => keepers += 1,
|
||||
}
|
||||
}
|
||||
// Need at least one keeper (retains the original loop) and at least one broken arm to fix.
|
||||
if keepers == 0 || to_clone.is_empty() {
|
||||
continue;
|
||||
}
|
||||
for (arm, ms) in to_clone {
|
||||
plans.push(Plan {
|
||||
arm,
|
||||
region: region.clone(),
|
||||
mo,
|
||||
ms,
|
||||
});
|
||||
}
|
||||
}
|
||||
if plans.is_empty() {
|
||||
return false;
|
||||
}
|
||||
|
||||
let _ = label_set;
|
||||
let mut any = false;
|
||||
for plan in plans {
|
||||
if apply_plan(function, &plan, fresh) {
|
||||
any = true;
|
||||
}
|
||||
}
|
||||
any
|
||||
}
|
||||
|
||||
/// Map each block's label id to its current index in `function.blocks` (recomputed per plan, since a
|
||||
/// prior plan's clone insertion shifts indices).
|
||||
fn index_of(function: &Function) -> HashMap<Word, usize> {
|
||||
function
|
||||
.blocks
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, b)| b.label.as_ref()?.result_id.map(|l| (l, i)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// True if any SSA value defined in `region` is referenced from a block outside the region, or the
|
||||
/// exit boundary block `mo` has an OpPhi with an incoming edge from a region block (which would need a
|
||||
/// mirrored incoming for the clone). Either makes the self-contained clone unsound — bail.
|
||||
fn region_escapes(function: &Function, region: &HashSet<Word>, mo: Word) -> bool {
|
||||
let mut region_defs: HashSet<Word> = HashSet::new();
|
||||
for block in &function.blocks {
|
||||
let Some(l) = block.label.as_ref().and_then(|i| i.result_id) else {
|
||||
continue;
|
||||
};
|
||||
if !region.contains(&l) {
|
||||
continue;
|
||||
}
|
||||
for inst in &block.instructions {
|
||||
if let Some(rid) = inst.result_id {
|
||||
region_defs.insert(rid);
|
||||
}
|
||||
}
|
||||
}
|
||||
for block in &function.blocks {
|
||||
let l = block.label.as_ref().and_then(|i| i.result_id);
|
||||
let in_region = l.is_some_and(|l| region.contains(&l));
|
||||
if in_region {
|
||||
continue;
|
||||
}
|
||||
// A use of a region-defined value in an out-of-region block escapes.
|
||||
for inst in &block.instructions {
|
||||
for op in &inst.operands {
|
||||
if let Operand::IdRef(v) = op {
|
||||
if region_defs.contains(v) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Boundary phi over a region predecessor?
|
||||
if let Some(block) = function
|
||||
.blocks
|
||||
.iter()
|
||||
.find(|b| b.label.as_ref().and_then(|i| i.result_id) == Some(mo))
|
||||
{
|
||||
for inst in &block.instructions {
|
||||
if inst.class.opcode != Op::Phi {
|
||||
continue;
|
||||
}
|
||||
let mut pos = 1;
|
||||
while pos < inst.operands.len() {
|
||||
if let Operand::IdRef(pred) = inst.operands[pos] {
|
||||
if region.contains(&pred) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
pos += 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Clone `plan.region` for the `plan.arm` entry: fresh ids throughout, the cloned header's phi keeps
|
||||
/// only the arm + cloned back-edge incomings, the original header's phi drops the arm incoming, the arm
|
||||
/// is redirected to the clone header, and the clone's exit is routed to `plan.ms`.
|
||||
fn apply_plan(function: &mut Function, plan: &Plan, fresh: &mut impl FnMut() -> Word) -> bool {
|
||||
let idx_of = index_of(function);
|
||||
let region_set: HashSet<Word> = plan.region.iter().copied().collect();
|
||||
// Re-derive the loop header: the region block carrying the OpLoopMerge.
|
||||
let Some(header) = plan.region.iter().copied().find(|&b| {
|
||||
function.blocks[idx_of[&b]]
|
||||
.instructions
|
||||
.iter()
|
||||
.any(|i| i.class.opcode == Op::LoopMerge)
|
||||
}) else {
|
||||
return false;
|
||||
};
|
||||
|
||||
// Rename map: every region label + every value defined in the region → a fresh id.
|
||||
let mut rename: HashMap<Word, Word> = HashMap::new();
|
||||
for &b in &plan.region {
|
||||
rename.insert(b, fresh());
|
||||
for inst in &function.blocks[idx_of[&b]].instructions {
|
||||
if let Some(rid) = inst.result_id {
|
||||
rename.insert(rid, fresh());
|
||||
}
|
||||
}
|
||||
}
|
||||
let remap = |w: Word| -> Word { rename.get(&w).copied().unwrap_or(w) };
|
||||
|
||||
// Materialize the cloned blocks.
|
||||
let mut cloned: Vec<Block> = Vec::with_capacity(plan.region.len());
|
||||
for &b in &plan.region {
|
||||
let src = &function.blocks[idx_of[&b]];
|
||||
let mut out = Block::new();
|
||||
out.label = Some(Instruction::new(Op::Label, None, Some(remap(b)), vec![]));
|
||||
for inst in &src.instructions {
|
||||
let mut ni = inst.clone();
|
||||
if let Some(rid) = ni.result_id {
|
||||
ni.result_id = Some(remap(rid));
|
||||
}
|
||||
if b == header && inst.class.opcode == Op::Phi {
|
||||
// Cloned header phi: keep only the arm incoming + cloned back-edge incomings.
|
||||
ni.operands = clone_header_phi(&inst.operands, plan.arm, ®ion_set, &remap);
|
||||
} else {
|
||||
for op in ni.operands.iter_mut() {
|
||||
if let Operand::IdRef(v) = op {
|
||||
*op = Operand::IdRef(remap(*v));
|
||||
}
|
||||
}
|
||||
}
|
||||
out.instructions.push(ni);
|
||||
}
|
||||
// Route the cloned exit (the block that branched to `mo`, outside the region so un-renamed) to
|
||||
// the broken selection's merge `ms` instead.
|
||||
redirect_terminator(&mut out, plan.mo, plan.ms);
|
||||
cloned.push(out);
|
||||
}
|
||||
|
||||
// Original header phi: drop the arm incoming (it now flows into the clone).
|
||||
for inst in function.blocks[idx_of[&header]].instructions.iter_mut() {
|
||||
if inst.class.opcode == Op::Phi {
|
||||
inst.operands = drop_phi_incoming(&inst.operands, plan.arm);
|
||||
}
|
||||
}
|
||||
// Redirect the arm's terminator: arm -> header becomes arm -> header_clone.
|
||||
redirect_terminator(
|
||||
&mut function.blocks[idx_of[&plan.arm]],
|
||||
header,
|
||||
remap(header),
|
||||
);
|
||||
|
||||
// Splice the cloned blocks in right after the arm block, so they sit inside the arm's region.
|
||||
let insert_at = idx_of[&plan.arm] + 1;
|
||||
for (k, b) in cloned.into_iter().enumerate() {
|
||||
function.blocks.insert(insert_at + k, b);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Rebuild a header phi's operands for the CLONE: keep the `[val, arm]` incoming as-is (the arm still
|
||||
/// branches here, into the clone), keep back-edge incomings (pred in region) with both val and pred
|
||||
/// remapped, and drop every other incoming (the sibling forward entries that keep the original loop).
|
||||
fn clone_header_phi(
|
||||
operands: &[Operand],
|
||||
arm: Word,
|
||||
region: &HashSet<Word>,
|
||||
remap: &impl Fn(Word) -> Word,
|
||||
) -> Vec<Operand> {
|
||||
let mut out = Vec::new();
|
||||
let mut pos = 0;
|
||||
while pos + 1 < operands.len() {
|
||||
if let (Operand::IdRef(v), Operand::IdRef(pred)) = (&operands[pos], &operands[pos + 1]) {
|
||||
if *pred == arm {
|
||||
out.push(Operand::IdRef(*v));
|
||||
out.push(Operand::IdRef(*pred));
|
||||
} else if region.contains(pred) {
|
||||
out.push(Operand::IdRef(remap(*v)));
|
||||
out.push(Operand::IdRef(remap(*pred)));
|
||||
}
|
||||
}
|
||||
pos += 2;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Rebuild a phi's operands dropping the incoming whose predecessor is `pred_to_drop`.
|
||||
fn drop_phi_incoming(operands: &[Operand], pred_to_drop: Word) -> Vec<Operand> {
|
||||
let mut out = Vec::new();
|
||||
let mut pos = 0;
|
||||
while pos + 1 < operands.len() {
|
||||
if let (Operand::IdRef(_), Operand::IdRef(pred)) = (&operands[pos], &operands[pos + 1]) {
|
||||
if *pred != pred_to_drop {
|
||||
out.push(operands[pos].clone());
|
||||
out.push(operands[pos + 1].clone());
|
||||
}
|
||||
}
|
||||
pos += 2;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Replace every `IdRef(from)` in a block's TERMINATOR (last instruction) with `IdRef(to)`.
|
||||
fn redirect_terminator(block: &mut Block, from: Word, to: Word) {
|
||||
if let Some(term) = block.instructions.last_mut() {
|
||||
for op in term.operands.iter_mut() {
|
||||
if *op == Operand::IdRef(from) {
|
||||
*op = Operand::IdRef(to);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::spirv_module::ModuleHeader;
|
||||
use spirv::LoopControl;
|
||||
|
||||
fn i(op: Op, ty: Option<Word>, res: Option<Word>, ops: Vec<Operand>) -> Instruction {
|
||||
Instruction::new(op, ty, res, ops)
|
||||
}
|
||||
fn b(label: Word, instrs: Vec<Instruction>) -> Block {
|
||||
Block {
|
||||
label: Some(i(Op::Label, None, Some(label), vec![])),
|
||||
instructions: instrs,
|
||||
}
|
||||
}
|
||||
fn r(w: Word) -> Operand {
|
||||
Operand::IdRef(w)
|
||||
}
|
||||
fn base_types() -> Vec<Instruction> {
|
||||
vec![
|
||||
i(Op::TypeBool, None, Some(1), vec![]),
|
||||
i(
|
||||
Op::TypeInt,
|
||||
None,
|
||||
Some(2),
|
||||
vec![Operand::LiteralBit32(32), Operand::LiteralBit32(0)],
|
||||
),
|
||||
i(
|
||||
Op::Constant,
|
||||
Some(2),
|
||||
Some(3),
|
||||
vec![Operand::LiteralBit32(0)],
|
||||
),
|
||||
]
|
||||
}
|
||||
fn term_targets(block: &Block) -> Vec<Word> {
|
||||
block
|
||||
.instructions
|
||||
.last()
|
||||
.map(|t| {
|
||||
t.operands
|
||||
.iter()
|
||||
.filter_map(|o| match o {
|
||||
Operand::IdRef(w) => Some(*w),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
fn find_block(f: &Function, label: Word) -> &Block {
|
||||
f.blocks
|
||||
.iter()
|
||||
.find(|b| b.label.as_ref().and_then(|l| l.result_id) == Some(label))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// The `steel_attention` shape: outer selection H0(100, merge 109) then→inner selection H1(101,
|
||||
/// merge 105) else→106; H1's else(104) AND H0's else(106) both enter loop header 107 (a MULTI-ENTRY
|
||||
/// loop). The split clones the loop for the 104 entry and routes the clone's exit to H1's merge 105.
|
||||
fn attention_module() -> Module {
|
||||
let mut m = Module::new();
|
||||
m.header = Some(ModuleHeader::new(300));
|
||||
m.types_global_values = base_types();
|
||||
let entry = b(
|
||||
100,
|
||||
vec![
|
||||
i(Op::Undef, Some(1), Some(200), vec![]),
|
||||
i(Op::Undef, Some(1), Some(201), vec![]),
|
||||
i(Op::Undef, Some(1), Some(202), vec![]),
|
||||
i(
|
||||
Op::SelectionMerge,
|
||||
None,
|
||||
None,
|
||||
vec![
|
||||
r(109),
|
||||
Operand::SelectionControl(spirv::SelectionControl::NONE),
|
||||
],
|
||||
),
|
||||
i(
|
||||
Op::BranchConditional,
|
||||
None,
|
||||
None,
|
||||
vec![r(200), r(101), r(106)],
|
||||
),
|
||||
],
|
||||
);
|
||||
let inner_h = b(
|
||||
101,
|
||||
vec![
|
||||
i(
|
||||
Op::SelectionMerge,
|
||||
None,
|
||||
None,
|
||||
vec![
|
||||
r(105),
|
||||
Operand::SelectionControl(spirv::SelectionControl::NONE),
|
||||
],
|
||||
),
|
||||
i(
|
||||
Op::BranchConditional,
|
||||
None,
|
||||
None,
|
||||
vec![r(201), r(102), r(104)],
|
||||
),
|
||||
],
|
||||
);
|
||||
let inner_then = b(102, vec![i(Op::Branch, None, None, vec![r(105)])]);
|
||||
let inner_else = b(104, vec![i(Op::Branch, None, None, vec![r(107)])]);
|
||||
let inner_merge = b(105, vec![i(Op::Branch, None, None, vec![r(109)])]);
|
||||
let outer_else = b(106, vec![i(Op::Branch, None, None, vec![r(107)])]);
|
||||
let loop_h = b(
|
||||
107,
|
||||
vec![
|
||||
i(
|
||||
Op::Phi,
|
||||
Some(2),
|
||||
Some(203),
|
||||
vec![r(3), r(104), r(3), r(106), r(204), r(110)],
|
||||
),
|
||||
i(Op::IAdd, Some(2), Some(204), vec![r(203), r(3)]),
|
||||
i(
|
||||
Op::LoopMerge,
|
||||
None,
|
||||
None,
|
||||
vec![r(108), r(110), Operand::LoopControl(LoopControl::NONE)],
|
||||
),
|
||||
i(
|
||||
Op::BranchConditional,
|
||||
None,
|
||||
None,
|
||||
vec![r(202), r(108), r(110)],
|
||||
),
|
||||
],
|
||||
);
|
||||
let latch = b(110, vec![i(Op::Branch, None, None, vec![r(107)])]);
|
||||
let loop_merge = b(108, vec![i(Op::Branch, None, None, vec![r(109)])]);
|
||||
let outer_merge = b(109, vec![i(Op::Return, None, None, vec![])]);
|
||||
let mut f = Function::new();
|
||||
f.blocks = vec![
|
||||
entry,
|
||||
inner_h,
|
||||
inner_then,
|
||||
inner_else,
|
||||
inner_merge,
|
||||
outer_else,
|
||||
loop_h,
|
||||
latch,
|
||||
loop_merge,
|
||||
outer_merge,
|
||||
];
|
||||
m.functions = vec![f];
|
||||
m
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn splits_multientry_loop_shared_by_two_selection_arms() {
|
||||
let mut m = attention_module();
|
||||
assert!(split_multientry_loop_selection_exits(&mut m));
|
||||
let f = &m.functions[0];
|
||||
// Three region blocks (107,110,108) were cloned.
|
||||
assert_eq!(f.blocks.len(), 13);
|
||||
// The original loop header 107 now has a single forward entry: its phi dropped the 104 incoming
|
||||
// (which now flows into the clone), keeping 106 and the 110 back-edge.
|
||||
let phi = find_block(f, 107)
|
||||
.instructions
|
||||
.iter()
|
||||
.find(|x| x.class.opcode == Op::Phi)
|
||||
.unwrap();
|
||||
let preds: Vec<Word> = phi
|
||||
.operands
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(k, o)| match o {
|
||||
Operand::IdRef(w) if k % 2 == 1 => Some(*w),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(
|
||||
preds,
|
||||
vec![106, 110],
|
||||
"original header keeps only 106 + back-edge"
|
||||
);
|
||||
// Arm 104 no longer branches to 107 (it targets the clone header instead).
|
||||
assert!(!term_targets(find_block(f, 104)).contains(&107));
|
||||
// H1's merge 105 now reconverges BOTH arms: the then-arm 102 (original) and the cloned
|
||||
// loop-merge (the 104 arm's private loop exit). The original loop-merge 108 still -> 109.
|
||||
let to_105 = f
|
||||
.blocks
|
||||
.iter()
|
||||
.filter(|b| term_targets(b).contains(&105))
|
||||
.count();
|
||||
assert_eq!(to_105, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn noop_on_single_entry_loop() {
|
||||
let mut m = Module::new();
|
||||
m.header = Some(ModuleHeader::new(200));
|
||||
m.types_global_values = base_types();
|
||||
let entry = b(100, vec![i(Op::Branch, None, None, vec![r(101)])]);
|
||||
let loop_h = b(
|
||||
101,
|
||||
vec![
|
||||
i(
|
||||
Op::Phi,
|
||||
Some(2),
|
||||
Some(120),
|
||||
vec![r(3), r(100), r(3), r(102)],
|
||||
),
|
||||
i(
|
||||
Op::LoopMerge,
|
||||
None,
|
||||
None,
|
||||
vec![r(103), r(102), Operand::LoopControl(LoopControl::NONE)],
|
||||
),
|
||||
i(
|
||||
Op::BranchConditional,
|
||||
None,
|
||||
None,
|
||||
vec![r(120), r(103), r(102)],
|
||||
),
|
||||
],
|
||||
);
|
||||
let latch = b(102, vec![i(Op::Branch, None, None, vec![r(101)])]);
|
||||
let merge = b(103, vec![i(Op::Return, None, None, vec![])]);
|
||||
let mut f = Function::new();
|
||||
f.blocks = vec![entry, loop_h, latch, merge];
|
||||
m.functions = vec![f];
|
||||
assert!(!split_multientry_loop_selection_exits(&mut m));
|
||||
assert_eq!(m.functions[0].blocks.len(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn noop_when_selection_merge_is_the_loop_header() {
|
||||
// A VALID shape: both arms of a selection reconverge AT the loop header (Ms == loop header,
|
||||
// which is inside the loop region) — must NOT be split (the region-contains-ms guard).
|
||||
let mut m = Module::new();
|
||||
m.header = Some(ModuleHeader::new(200));
|
||||
m.types_global_values = base_types();
|
||||
let entry = b(
|
||||
100,
|
||||
vec![
|
||||
i(Op::Undef, Some(1), Some(200), vec![]),
|
||||
i(
|
||||
Op::SelectionMerge,
|
||||
None,
|
||||
None,
|
||||
vec![
|
||||
r(101),
|
||||
Operand::SelectionControl(spirv::SelectionControl::NONE),
|
||||
],
|
||||
),
|
||||
i(
|
||||
Op::BranchConditional,
|
||||
None,
|
||||
None,
|
||||
vec![r(200), r(104), r(105)],
|
||||
),
|
||||
],
|
||||
);
|
||||
let arm_a = b(104, vec![i(Op::Branch, None, None, vec![r(101)])]);
|
||||
let arm_b = b(105, vec![i(Op::Branch, None, None, vec![r(101)])]);
|
||||
let loop_h = b(
|
||||
101,
|
||||
vec![
|
||||
i(
|
||||
Op::Phi,
|
||||
Some(2),
|
||||
Some(120),
|
||||
vec![r(3), r(104), r(3), r(105), r(3), r(102)],
|
||||
),
|
||||
i(
|
||||
Op::LoopMerge,
|
||||
None,
|
||||
None,
|
||||
vec![r(103), r(102), Operand::LoopControl(LoopControl::NONE)],
|
||||
),
|
||||
i(
|
||||
Op::BranchConditional,
|
||||
None,
|
||||
None,
|
||||
vec![r(120), r(103), r(102)],
|
||||
),
|
||||
],
|
||||
);
|
||||
let latch = b(102, vec![i(Op::Branch, None, None, vec![r(101)])]);
|
||||
let merge = b(103, vec![i(Op::Return, None, None, vec![])]);
|
||||
let mut f = Function::new();
|
||||
f.blocks = vec![entry, arm_a, arm_b, loop_h, latch, merge];
|
||||
m.functions = vec![f];
|
||||
assert!(!split_multientry_loop_selection_exits(&mut m));
|
||||
assert_eq!(m.functions[0].blocks.len(), 6);
|
||||
}
|
||||
}
|
||||
+24
-32
@@ -1,29 +1,14 @@
|
||||
// Dominator/loop-forest analysis backing the structured-by-construction path (`structured_plan`,
|
||||
// the DEFAULT structurizer in `emitter::functions::emit_function`; a function it rejects emits its
|
||||
// inferred merges unrepaired and ships via the relooper retry — the post-hoc repair roster that used
|
||||
// to be the fallback was deleted at W4).
|
||||
// Dominator/loop-forest analysis backing the structured-by-construction path (`structured_plan`).
|
||||
// A rejected local plan is recorded as an owned construction fact so the module can select its raw
|
||||
// CFG representation before serialization.
|
||||
// Low-level source-CFG graph primitives (successor/predecessor adjacency + CHK
|
||||
// dominator tree) shared by the loop-forest and structurizer analyses.
|
||||
pub(in crate::native) mod graph;
|
||||
pub(super) mod loopforest;
|
||||
// Cross-arm node-splitting (single-entry tail duplication) for the structured path. Not on the
|
||||
// default path; invoked behind the failure-triggered `inline_sroa_raw_cfg_restructure` retry
|
||||
// (adopt-if-validates) and the `historical cfg-clone probes` probe, so the floor is
|
||||
// byte-identical by construction.
|
||||
// Cross-arm node-splitting (single-entry tail duplication) used while constructing structured CFGs.
|
||||
pub(super) mod clone_crossarm;
|
||||
mod repair;
|
||||
// Compact immediate-dominator analysis over the emitted CFG, shared by late rewrites and emitter
|
||||
// phi-materialization repair.
|
||||
// Compact immediate-dominator analysis over the emitted CFG, shared by late rewrites.
|
||||
mod exit_check;
|
||||
// Loop-closed-SSA repair on the emitted module: register-demote a value whose def block no longer
|
||||
// dominates a use (the `synth_multi_exit_merge` funnel gap), so the PRIMARY structured emit validates
|
||||
// instead of shipping only via the relooper retry. Self-gating / floor-safe (no violation => no-op).
|
||||
mod ssa_demote;
|
||||
// Post-emit multi-entry-loop split: node-split a loop whose header is entered from two different
|
||||
// selections' arms (the irreducible shape `structured_plan` over-admits), so the PRIMARY structured
|
||||
// emit validates instead of shipping only via the relooper retry. Self-gating / floor-safe (a valid
|
||||
// loop is single-entry => no-op).
|
||||
mod loop_split;
|
||||
// Forest-driven emission consumer: loop-merge computation + merge==continue overlap split for
|
||||
// `structured_plan`, the live default structurization path.
|
||||
pub(super) mod structured_emit;
|
||||
@@ -31,27 +16,34 @@ pub(super) mod structured_emit;
|
||||
mod blocks;
|
||||
pub(super) mod structured_order;
|
||||
|
||||
pub(super) use clone_crossarm::{
|
||||
clone_cross_arm_shared, lower_unreachable_to_ret, privatize_region_cross_arm, rename_tokens,
|
||||
unify_returns,
|
||||
};
|
||||
pub(super) use clone_crossarm::rename_tokens;
|
||||
pub(in crate::native) use exit_check::EmittedDominators;
|
||||
pub(super) use loop_split::split_multientry_loop_selection_exits;
|
||||
pub(super) use ssa_demote::demote_nondominating_values;
|
||||
pub(super) use structured_emit::{
|
||||
cond_other_witness_lines, cond_phi_shared_witness_lines, construct_tree_gate_witness_lines,
|
||||
construct_tree_reject_reason, renest_cond_phi_shared_own_arm, renest_straddle_loop_merge,
|
||||
restructure_straddle_loop_merges, straddle_witness_lines, structured_plan,
|
||||
structured_plan_construct_tree, structured_reject_reason, CROSS_ARM_EDGE_MAX_BLOCKS,
|
||||
construct_tree_reject_reason, exceeds_local_structured_plan_budget,
|
||||
privatize_reused_emitted_merge_targets, renest_cond_phi_shared_own_arm,
|
||||
renest_loop_exit_sibling, renest_straddle_loop_merge, renest_whole_cfg_dispatch,
|
||||
requires_loop_exit_sibling_dispatch, requires_shared_loop_entry_ownership,
|
||||
straddle_witness_lines, structured_plan, structured_plan_construct_tree,
|
||||
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,
|
||||
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,
|
||||
lower_unstructured_switches, refunnel_one_deep_shared_arm, split_body_blocks,
|
||||
lower_unstructured_switches, refunnel_one_deep_shared_arm, split_source_body_blocks,
|
||||
switch_default_is_inferred_merge,
|
||||
};
|
||||
pub(super) use repair::{block_index_by_label, id_ref_operand};
|
||||
#[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;
|
||||
};
|
||||
Some(*id)
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(super) struct LoopMergeInfo {
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
use crate::spirv_module::Block;
|
||||
use crate::spirv_module::Operand;
|
||||
use spirv::Word;
|
||||
|
||||
pub(in crate::native) fn block_index_by_label(blocks: &[Block], label_id: Word) -> Option<usize> {
|
||||
blocks
|
||||
.iter()
|
||||
.position(|block| block.label.as_ref().and_then(|label| label.result_id) == Some(label_id))
|
||||
}
|
||||
|
||||
pub(in crate::native) fn id_ref_operand(operand: &Operand) -> Option<Word> {
|
||||
let Operand::IdRef(id) = operand else {
|
||||
return None;
|
||||
};
|
||||
Some(*id)
|
||||
}
|
||||
@@ -1,591 +0,0 @@
|
||||
//! Loop-closed-SSA repair on an EMITTED SPIR-V module: register-demote a value whose defining block
|
||||
//! no longer dominates a use.
|
||||
//!
|
||||
//! The structurizer-by-construction reorders/restructures blocks to satisfy the structured-CFG rules.
|
||||
//! A `MultipleExits` loop is funnelled through a synthesized dispatch merge (`synth_multi_exit_merge`),
|
||||
//! and a loop-body value consumed after the loop (the classic loop-closed-SSA / LCSSA shape) can end up
|
||||
//! referenced RAW in a post-loop block that the restructured CFG reaches by a path skipping the
|
||||
//! defining block — so the def no longer dominates the use and spirv-val rejects: *"ID X defined in
|
||||
//! block B does not dominate its use in block U"*. The AIR was strict SSA (the def dominated the use
|
||||
//! through a proper LCSSA phi), and the emitted CFG is semantics-equivalent to the AIR — whenever
|
||||
//! control reaches the use with that value live, the defining block ran first — so spilling the value
|
||||
//! to a function-scope `OpVariable` (stored right after its definition, loaded before each
|
||||
//! non-dominated use) preserves semantics while making the module structurally valid. This is exactly
|
||||
//! the register-demotion the relooper retry already applies to these functions (via its big-switch
|
||||
//! form); doing it SURGICALLY on the structured CFG keeps the structured emit and makes its PRIMARY
|
||||
//! output valid, instead of shipping only via the relooper retry.
|
||||
//!
|
||||
//! Floor-safe by construction: a module that already validates has every def dominating its uses, so
|
||||
//! the violation scan finds nothing and the module is returned byte-identical. Only a value whose type
|
||||
//! is spillable to Function memory (not a pointer under Logical addressing, not an opaque
|
||||
//! image/sampler) is demoted; any other non-dominating value is left in place (that function stays on
|
||||
//! the floor, no regression). Decides purely from IR structure (block edges, dominance, value
|
||||
//! def/use), never a shader name.
|
||||
|
||||
use super::graph::spirv_block_successors_by_label;
|
||||
use super::EmittedDominators;
|
||||
use crate::spirv_module::Operand;
|
||||
use crate::spirv_module::{Function, Instruction, Module};
|
||||
use spirv::{Op, StorageClass, Word};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
/// Register-demote every value in `module` whose defining block does not dominate one of its uses.
|
||||
/// Returns true if any value was demoted.
|
||||
pub(in crate::native) fn demote_nondominating_values(module: &mut Module) -> bool {
|
||||
// Type kinds we can back with a Function `OpVariable` (a concrete data type). A pointer (illegal to
|
||||
// store under Logical addressing) or an opaque handle (image/sampler) is NOT spillable.
|
||||
let type_kind: HashMap<Word, Op> = module
|
||||
.types_global_values
|
||||
.iter()
|
||||
.filter_map(|i| i.result_id.map(|id| (id, i.class.opcode)))
|
||||
.collect();
|
||||
let spillable = |ty: Word| -> bool {
|
||||
matches!(
|
||||
type_kind.get(&ty),
|
||||
Some(
|
||||
Op::TypeInt
|
||||
| Op::TypeFloat
|
||||
| Op::TypeBool
|
||||
| Op::TypeVector
|
||||
| Op::TypeMatrix
|
||||
| Op::TypeArray
|
||||
| Op::TypeStruct
|
||||
)
|
||||
)
|
||||
};
|
||||
// Existing Function pointer types by pointee, so a demotion reuses one rather than emitting a
|
||||
// duplicate (SPIR-V forbids two identical OpTypePointer).
|
||||
let mut fn_ptr_type: HashMap<Word, Word> = HashMap::new();
|
||||
for i in &module.types_global_values {
|
||||
if i.class.opcode == Op::TypePointer {
|
||||
if let (
|
||||
Some(rid),
|
||||
Some(Operand::StorageClass(StorageClass::Function)),
|
||||
Some(Operand::IdRef(pointee)),
|
||||
) = (i.result_id, i.operands.first(), i.operands.get(1))
|
||||
{
|
||||
fn_ptr_type.entry(*pointee).or_insert(rid);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut next_id = module.header.as_ref().map(|h| h.bound).unwrap_or(0);
|
||||
let mut fresh = || {
|
||||
let id = next_id;
|
||||
next_id += 1;
|
||||
id
|
||||
};
|
||||
|
||||
let mut new_ptr_types: Vec<Instruction> = Vec::new();
|
||||
let mut any = false;
|
||||
for function in &mut module.functions {
|
||||
any |= demote_in_function(
|
||||
function,
|
||||
&spillable,
|
||||
&mut fn_ptr_type,
|
||||
&mut new_ptr_types,
|
||||
&mut fresh,
|
||||
);
|
||||
}
|
||||
|
||||
if any {
|
||||
// Splice any freshly-created Function pointer types into the global type section (order among
|
||||
// type defs is not load-bearing; id-canonicalization re-sorts afterward).
|
||||
module.types_global_values.extend(new_ptr_types);
|
||||
if let Some(header) = module.header.as_mut() {
|
||||
header.bound = next_id;
|
||||
}
|
||||
}
|
||||
any
|
||||
}
|
||||
|
||||
/// A single value to demote: its result id, its (value) type, and the block index of its definition.
|
||||
struct Target {
|
||||
value: Word,
|
||||
ty: Word,
|
||||
def_block: usize,
|
||||
/// Blocks in which a load must be materialized (a non-dominated non-phi use lives here, or an
|
||||
/// incoming phi edge from here carries the value).
|
||||
load_blocks: Vec<usize>,
|
||||
}
|
||||
|
||||
fn demote_in_function(
|
||||
function: &mut Function,
|
||||
spillable: &impl Fn(Word) -> bool,
|
||||
fn_ptr_type: &mut HashMap<Word, Word>,
|
||||
new_ptr_types: &mut Vec<Instruction>,
|
||||
fresh: &mut impl FnMut() -> Word,
|
||||
) -> bool {
|
||||
if function.blocks.len() < 2 {
|
||||
return false;
|
||||
}
|
||||
let Some(entry) = function
|
||||
.blocks
|
||||
.first()
|
||||
.and_then(|b| b.label.as_ref()?.result_id)
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
// block index -> label id, label id -> block index, and the reachable label list.
|
||||
let idx_to_label: Vec<Option<Word>> = function
|
||||
.blocks
|
||||
.iter()
|
||||
.map(|b| b.label.as_ref().and_then(|l| l.result_id))
|
||||
.collect();
|
||||
let mut label_to_idx: HashMap<Word, usize> = HashMap::new();
|
||||
let mut labels: Vec<Word> = Vec::new();
|
||||
for (bi, l) in idx_to_label.iter().enumerate() {
|
||||
if let Some(rid) = l {
|
||||
label_to_idx.insert(*rid, bi);
|
||||
labels.push(*rid);
|
||||
}
|
||||
}
|
||||
let successors = spirv_block_successors_by_label(&function.blocks);
|
||||
let dominators = EmittedDominators::new(entry, &labels, &successors);
|
||||
// A block whose dominators were not computed (unreachable) dominates nothing reachable and is
|
||||
// dominated by nothing — treat as non-dominating so its dead uses are left alone.
|
||||
let dominates = |a_label: Word, b_label: Word| dominators.dominates(a_label, b_label);
|
||||
|
||||
// value id -> (def block index, result type), for every value defined in the function body.
|
||||
let mut def_block: HashMap<Word, usize> = HashMap::new();
|
||||
let mut value_type: HashMap<Word, Word> = HashMap::new();
|
||||
for (bi, block) in function.blocks.iter().enumerate() {
|
||||
for inst in &block.instructions {
|
||||
if let Some(rid) = inst.result_id {
|
||||
def_block.insert(rid, bi);
|
||||
if let Some(rty) = inst.result_type {
|
||||
value_type.insert(rid, rty);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Plan phase (immutable scan): collect each value whose def block does not dominate a use, together
|
||||
// with the set of blocks that must load it.
|
||||
let mut targets: HashMap<Word, HashSet<usize>> = HashMap::new();
|
||||
for (bi, block) in function.blocks.iter().enumerate() {
|
||||
let this_label = idx_to_label[bi];
|
||||
for inst in &block.instructions {
|
||||
if inst.class.opcode == Op::Phi {
|
||||
// Operands are [v0, b0, v1, b1, ...]: value v_i flows in on the edge from predecessor
|
||||
// b_i, so v_i must dominate b_i (the predecessor's terminator), NOT the phi's block.
|
||||
let mut pos = 0;
|
||||
while pos + 1 < inst.operands.len() {
|
||||
if let (Operand::IdRef(v), Operand::IdRef(pred)) =
|
||||
(&inst.operands[pos], &inst.operands[pos + 1])
|
||||
{
|
||||
if let Some(&db) = def_block.get(v) {
|
||||
if let (Some(db_label), Some(&pred_idx)) =
|
||||
(idx_to_label[db], label_to_idx.get(pred))
|
||||
{
|
||||
if !dominates(db_label, *pred) {
|
||||
targets.entry(*v).or_default().insert(pred_idx);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
pos += 2;
|
||||
}
|
||||
} else {
|
||||
// A non-phi instruction's operands must be dominated by this block.
|
||||
let Some(this) = this_label else { continue };
|
||||
for op in &inst.operands {
|
||||
if let Operand::IdRef(v) = op {
|
||||
if let Some(&db) = def_block.get(v) {
|
||||
if let Some(db_label) = idx_to_label[db] {
|
||||
if !dominates(db_label, this) {
|
||||
targets.entry(*v).or_default().insert(bi);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if targets.is_empty() {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Keep only spillable targets; a non-spillable non-dominating value (a pointer / opaque) is left in
|
||||
// place — the function simply stays invalid (relooper retry still rescues it), no regression.
|
||||
let mut plans: Vec<Target> = Vec::new();
|
||||
for (value, load_blocks) in targets {
|
||||
let Some(&ty) = value_type.get(&value) else {
|
||||
continue;
|
||||
};
|
||||
if !spillable(ty) {
|
||||
continue;
|
||||
}
|
||||
let Some(&def_b) = def_block.get(&value) else {
|
||||
continue;
|
||||
};
|
||||
let mut load_blocks: Vec<usize> = load_blocks.into_iter().collect();
|
||||
load_blocks.sort_unstable();
|
||||
plans.push(Target {
|
||||
value,
|
||||
ty,
|
||||
def_block: def_b,
|
||||
load_blocks,
|
||||
});
|
||||
}
|
||||
if plans.is_empty() {
|
||||
return false;
|
||||
}
|
||||
// Deterministic order (id ascending) so the pass is reproducible independent of HashMap iteration.
|
||||
plans.sort_by_key(|t| t.value);
|
||||
|
||||
// Apply phase. Materialize a Function OpVariable per demoted value, store after its def, and load
|
||||
// (once per block) before each non-dominated use, repointing those uses to the load.
|
||||
for plan in &plans {
|
||||
let ptr_ty = *fn_ptr_type.entry(plan.ty).or_insert_with(|| {
|
||||
let id = fresh();
|
||||
new_ptr_types.push(Instruction::new(
|
||||
Op::TypePointer,
|
||||
None,
|
||||
Some(id),
|
||||
vec![
|
||||
Operand::StorageClass(StorageClass::Function),
|
||||
Operand::IdRef(plan.ty),
|
||||
],
|
||||
));
|
||||
id
|
||||
});
|
||||
let var_id = fresh();
|
||||
|
||||
// 1) OpVariable at the top of the entry block (all Function variables must lead the first
|
||||
// block). Insert after any existing leading variables so they stay contiguous.
|
||||
{
|
||||
let entry_block = &mut function.blocks[0];
|
||||
let after_vars = entry_block
|
||||
.instructions
|
||||
.iter()
|
||||
.position(|i| i.class.opcode != Op::Variable)
|
||||
.unwrap_or(0);
|
||||
entry_block.instructions.insert(
|
||||
after_vars,
|
||||
Instruction::new(
|
||||
Op::Variable,
|
||||
Some(ptr_ty),
|
||||
Some(var_id),
|
||||
vec![Operand::StorageClass(StorageClass::Function)],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// 2) OpStore right after the definition (but after any leading phis, and before a trailing
|
||||
// structured-merge instruction).
|
||||
{
|
||||
let block = &mut function.blocks[plan.def_block];
|
||||
let def_idx = block
|
||||
.instructions
|
||||
.iter()
|
||||
.position(|i| i.result_id == Some(plan.value))
|
||||
.expect("def instruction present");
|
||||
let first_non_phi = block
|
||||
.instructions
|
||||
.iter()
|
||||
.position(|i| i.class.opcode != Op::Phi)
|
||||
.unwrap_or(block.instructions.len());
|
||||
let mut at = (def_idx + 1).max(first_non_phi);
|
||||
let n = block.instructions.len();
|
||||
// Keep a trailing OpSelectionMerge/OpLoopMerge adjacent to its branch terminator.
|
||||
let safe_max = if n >= 2
|
||||
&& matches!(
|
||||
block.instructions[n - 2].class.opcode,
|
||||
Op::SelectionMerge | Op::LoopMerge
|
||||
) {
|
||||
n - 2
|
||||
} else {
|
||||
n - 1
|
||||
};
|
||||
at = at.min(safe_max);
|
||||
block.instructions.insert(
|
||||
at,
|
||||
Instruction::new(
|
||||
Op::Store,
|
||||
None,
|
||||
None,
|
||||
vec![Operand::IdRef(var_id), Operand::IdRef(plan.value)],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// 3) One OpLoad at the top of each load block (after its phis), repointing that block's uses.
|
||||
for &lb in &plan.load_blocks {
|
||||
let load_id = fresh();
|
||||
let lb_label = idx_to_label[lb];
|
||||
{
|
||||
let block = &mut function.blocks[lb];
|
||||
let after_phis = block
|
||||
.instructions
|
||||
.iter()
|
||||
.position(|i| i.class.opcode != Op::Phi && i.class.opcode != Op::Variable)
|
||||
.unwrap_or(0);
|
||||
block.instructions.insert(
|
||||
after_phis,
|
||||
Instruction::new(
|
||||
Op::Load,
|
||||
Some(plan.ty),
|
||||
Some(load_id),
|
||||
vec![Operand::IdRef(var_id)],
|
||||
),
|
||||
);
|
||||
// Repoint non-phi uses of `value` in THIS block to the load (it precedes them). Never
|
||||
// touch the store we just inserted (its value operand must stay the original def), and
|
||||
// never the load itself.
|
||||
for inst in block.instructions.iter_mut() {
|
||||
if inst.class.opcode == Op::Phi
|
||||
|| inst.class.opcode == Op::Variable
|
||||
|| inst.result_id == Some(load_id)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if inst.class.opcode == Op::Store
|
||||
&& inst.operands.first() == Some(&Operand::IdRef(var_id))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
for op in inst.operands.iter_mut() {
|
||||
if *op == Operand::IdRef(plan.value) {
|
||||
*op = Operand::IdRef(load_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Repoint phi operands ANYWHERE whose predecessor label is this block: the load in this
|
||||
// predecessor dominates the outgoing edge, so the phi may read it.
|
||||
if let Some(lb_label) = lb_label {
|
||||
for other in function.blocks.iter_mut() {
|
||||
for inst in other.instructions.iter_mut() {
|
||||
if inst.class.opcode != Op::Phi {
|
||||
continue;
|
||||
}
|
||||
let mut pos = 0;
|
||||
while pos + 1 < inst.operands.len() {
|
||||
if inst.operands[pos] == Operand::IdRef(plan.value)
|
||||
&& inst.operands[pos + 1] == Operand::IdRef(lb_label)
|
||||
{
|
||||
inst.operands[pos] = Operand::IdRef(load_id);
|
||||
}
|
||||
pos += 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::spirv_module::{Block, ModuleHeader};
|
||||
|
||||
fn inst(op: Op, ty: Option<Word>, res: Option<Word>, ops: Vec<Operand>) -> Instruction {
|
||||
Instruction::new(op, ty, res, ops)
|
||||
}
|
||||
fn block(label: Word, instrs: Vec<Instruction>) -> Block {
|
||||
Block {
|
||||
label: Some(inst(Op::Label, None, Some(label), vec![])),
|
||||
instructions: instrs,
|
||||
}
|
||||
}
|
||||
|
||||
// A value defined in a loop BODY (block 12) and used after the loop at the merge (block 14) — the
|
||||
// loop header can early-exit straight to 14, so 12 does not dominate 14. The value is
|
||||
// register-demoted: an OpVariable in the entry, an OpStore after the def, an OpLoad at the merge,
|
||||
// and the post-loop use is repointed to the load.
|
||||
#[test]
|
||||
fn demotes_loop_body_value_used_after_early_exit_loop() {
|
||||
// types: bool=1 float=2 (Function-float pointer type is synthesized by the pass)
|
||||
let mut m = Module::new();
|
||||
m.header = Some(ModuleHeader::new(60));
|
||||
m.types_global_values = vec![
|
||||
inst(Op::TypeBool, None, Some(1), vec![]),
|
||||
inst(
|
||||
Op::TypeFloat,
|
||||
None,
|
||||
Some(2),
|
||||
vec![Operand::LiteralBit32(32)],
|
||||
),
|
||||
];
|
||||
// entry 10 -> header 11
|
||||
let entry = block(
|
||||
10,
|
||||
vec![inst(Op::Branch, None, None, vec![Operand::IdRef(11)])],
|
||||
);
|
||||
// header 11: cond = undef; loopmerge 14 13; branchconditional cond -> body 12 / merge 14
|
||||
let header = block(
|
||||
11,
|
||||
vec![
|
||||
inst(Op::Undef, Some(1), Some(20), vec![]),
|
||||
inst(
|
||||
Op::LoopMerge,
|
||||
None,
|
||||
None,
|
||||
vec![
|
||||
Operand::IdRef(14),
|
||||
Operand::IdRef(13),
|
||||
Operand::LoopControl(spirv::LoopControl::NONE),
|
||||
],
|
||||
),
|
||||
inst(
|
||||
Op::BranchConditional,
|
||||
None,
|
||||
None,
|
||||
vec![Operand::IdRef(20), Operand::IdRef(12), Operand::IdRef(14)],
|
||||
),
|
||||
],
|
||||
);
|
||||
// body 12: %30 = fadd float (the loop-body value); branch to latch 13
|
||||
let body = block(
|
||||
12,
|
||||
vec![
|
||||
inst(
|
||||
Op::FAdd,
|
||||
Some(2),
|
||||
Some(30),
|
||||
vec![Operand::IdRef(2), Operand::IdRef(2)],
|
||||
),
|
||||
inst(Op::Branch, None, None, vec![Operand::IdRef(13)]),
|
||||
],
|
||||
);
|
||||
// latch 13 -> header 11 (back edge)
|
||||
let latch = block(
|
||||
13,
|
||||
vec![inst(Op::Branch, None, None, vec![Operand::IdRef(11)])],
|
||||
);
|
||||
// merge 14: %40 = fsub float %30 %30 (uses the loop-body value); return
|
||||
let merge = block(
|
||||
14,
|
||||
vec![
|
||||
inst(
|
||||
Op::FSub,
|
||||
Some(2),
|
||||
Some(40),
|
||||
vec![Operand::IdRef(30), Operand::IdRef(30)],
|
||||
),
|
||||
inst(Op::Return, None, None, vec![]),
|
||||
],
|
||||
);
|
||||
let mut func = Function::new();
|
||||
func.blocks = vec![entry, header, body, latch, merge];
|
||||
m.functions = vec![func];
|
||||
|
||||
assert!(demote_nondominating_values(&mut m));
|
||||
|
||||
// A Function pointer-to-float type was synthesized.
|
||||
let ptr_ty = m
|
||||
.types_global_values
|
||||
.iter()
|
||||
.find(|i| {
|
||||
i.class.opcode == Op::TypePointer
|
||||
&& i.operands.first() == Some(&Operand::StorageClass(StorageClass::Function))
|
||||
&& i.operands.get(1) == Some(&Operand::IdRef(2))
|
||||
})
|
||||
.and_then(|i| i.result_id)
|
||||
.expect("Function float pointer type synthesized");
|
||||
|
||||
let f = &m.functions[0];
|
||||
// Entry block holds the demotion OpVariable of that pointer type.
|
||||
let var = f.blocks[0]
|
||||
.instructions
|
||||
.iter()
|
||||
.find(|i| i.class.opcode == Op::Variable)
|
||||
.expect("OpVariable in entry");
|
||||
assert_eq!(var.result_type, Some(ptr_ty));
|
||||
let var_id = var.result_id.unwrap();
|
||||
|
||||
// The body (block index 2) stores the value after its def, before the terminator.
|
||||
let body = &f.blocks[2];
|
||||
let store_pos = body
|
||||
.instructions
|
||||
.iter()
|
||||
.position(|i| {
|
||||
i.class.opcode == Op::Store
|
||||
&& i.operands == vec![Operand::IdRef(var_id), Operand::IdRef(30)]
|
||||
})
|
||||
.expect("store of the loop-body value after its def");
|
||||
let def_pos = body
|
||||
.instructions
|
||||
.iter()
|
||||
.position(|i| i.result_id == Some(30))
|
||||
.unwrap();
|
||||
assert!(store_pos > def_pos);
|
||||
assert_eq!(body.instructions.last().unwrap().class.opcode, Op::Branch);
|
||||
|
||||
// The merge (block index 4) loads from the var and the fsub now reads the load, not %30.
|
||||
let merge = &f.blocks[4];
|
||||
let load = merge
|
||||
.instructions
|
||||
.iter()
|
||||
.find(|i| i.class.opcode == Op::Load && i.operands == vec![Operand::IdRef(var_id)])
|
||||
.expect("load at the merge");
|
||||
let load_id = load.result_id.unwrap();
|
||||
let fsub = merge
|
||||
.instructions
|
||||
.iter()
|
||||
.find(|i| i.class.opcode == Op::FSub)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
fsub.operands,
|
||||
vec![Operand::IdRef(load_id), Operand::IdRef(load_id)]
|
||||
);
|
||||
}
|
||||
|
||||
// A module whose every def already dominates its uses is returned byte-identical — the floor-safety
|
||||
// property (no violation => no-op).
|
||||
#[test]
|
||||
fn valid_module_is_untouched() {
|
||||
let mut m = Module::new();
|
||||
m.header = Some(ModuleHeader::new(30));
|
||||
m.types_global_values = vec![inst(
|
||||
Op::TypeFloat,
|
||||
None,
|
||||
Some(2),
|
||||
vec![Operand::LiteralBit32(32)],
|
||||
)];
|
||||
// entry defines %10, single successor uses it (entry dominates all).
|
||||
let entry = block(
|
||||
1,
|
||||
vec![
|
||||
inst(
|
||||
Op::FAdd,
|
||||
Some(2),
|
||||
Some(10),
|
||||
vec![Operand::IdRef(2), Operand::IdRef(2)],
|
||||
),
|
||||
inst(Op::Branch, None, None, vec![Operand::IdRef(2)]),
|
||||
],
|
||||
);
|
||||
let tail = block(
|
||||
2,
|
||||
vec![
|
||||
inst(
|
||||
Op::FSub,
|
||||
Some(2),
|
||||
Some(11),
|
||||
vec![Operand::IdRef(10), Operand::IdRef(10)],
|
||||
),
|
||||
inst(Op::Return, None, None, vec![]),
|
||||
],
|
||||
);
|
||||
let mut func = Function::new();
|
||||
func.blocks = vec![entry, tail];
|
||||
m.functions = vec![func];
|
||||
let before = m.clone();
|
||||
|
||||
assert!(!demote_nondominating_values(&mut m));
|
||||
assert_eq!(
|
||||
m.functions[0].blocks.len(),
|
||||
before.functions[0].blocks.len()
|
||||
);
|
||||
assert_eq!(
|
||||
m.functions[0].blocks[1].instructions[0].operands,
|
||||
vec![Operand::IdRef(10), Operand::IdRef(10)]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,17 +1,148 @@
|
||||
//! Bounded ownership and edge-route analysis for the reject-only construct-tree re-nester.
|
||||
//!
|
||||
//! This module does not participate in production admission yet. It converts an explicit parent-first
|
||||
//! construct claim graph into one owner per original block and one finite ancestor route per original
|
||||
//! edge; its `renest` child materializes the bounded typed regional construct used by the R1 fixture
|
||||
//! proof. R2+ derives these claims from one live reject class at a time.
|
||||
//! It converts an explicit parent-first construct claim graph into one owner per original block and
|
||||
//! one finite ancestor route per original edge. Its `renest` child materializes typed regional and
|
||||
//! whole-CFG dispatcher constructs before emission; production derives claims structurally from the
|
||||
//! current source CFG rather than matching workload identities.
|
||||
|
||||
use super::{synthetic_block, BlockRole, BodyBlock};
|
||||
use std::collections::HashSet;
|
||||
use super::{
|
||||
analyze, block_successors, conditional_branch_targets, synthetic_block, BlockRole, BodyBlock,
|
||||
StructuredPlan, CROSS_ARM_EDGE_MAX_BLOCKS,
|
||||
};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
pub(in crate::native) mod renest;
|
||||
|
||||
const ROUTE_PREFIX: &str = "%metal2vulkan.ctroute.";
|
||||
|
||||
/// Whether a selection arm owns a natural loop that exits directly into the selection's sibling
|
||||
/// arm. SPIR-V cannot represent that edge in place: leaving the loop does not license entry into a
|
||||
/// sibling selection construct. A typed dispatcher must therefore own this shape even when a local
|
||||
/// merge assignment happens to pass the source planner's cheaper checks.
|
||||
pub(in crate::native) fn requires_loop_exit_sibling_dispatch(blocks: &[BodyBlock]) -> bool {
|
||||
let forest = analyze(blocks);
|
||||
let by_name = blocks
|
||||
.iter()
|
||||
.map(|block| (block.name.as_str(), block))
|
||||
.collect::<HashMap<_, _>>();
|
||||
blocks.iter().any(|header| {
|
||||
let Some((left, right)) = conditional_branch_targets(header) else {
|
||||
return false;
|
||||
};
|
||||
let requires_dispatch =
|
||||
[(&left, &right), (&right, &left)]
|
||||
.into_iter()
|
||||
.any(|(loop_entry, sibling)| {
|
||||
forest.loops.iter().any(|natural_loop| {
|
||||
natural_loop.body.iter().any(|block| block == loop_entry)
|
||||
&& !natural_loop.body.iter().any(|block| block == &header.name)
|
||||
&& !natural_loop.body.iter().any(|block| block == sibling)
|
||||
&& natural_loop.exits.iter().any(|exit| {
|
||||
let mut current = exit.clone();
|
||||
let mut seen = HashSet::new();
|
||||
loop {
|
||||
if ¤t == sibling {
|
||||
break true;
|
||||
}
|
||||
if !seen.insert(current.clone())
|
||||
|| natural_loop.body.iter().any(|block| block == ¤t)
|
||||
{
|
||||
break false;
|
||||
}
|
||||
let Some(block) = by_name.get(current.as_str()) else {
|
||||
break false;
|
||||
};
|
||||
let successors = block_successors(block);
|
||||
let [next] = successors.as_slice() else {
|
||||
break false;
|
||||
};
|
||||
current = next.clone();
|
||||
}
|
||||
})
|
||||
})
|
||||
});
|
||||
requires_dispatch
|
||||
})
|
||||
}
|
||||
|
||||
/// Derive the complete ownership tree used by the whole-CFG dispatcher and materialize it before
|
||||
/// emission. Every original block is owned by one switch arm under one dispatcher loop; every source
|
||||
/// edge therefore has one finite arm-to-arm route, including backedges and multi-level exits. The
|
||||
/// typed materializer carries phi and cross-block state explicitly. Pointer state remains a pointer
|
||||
/// `phi`, allowing the typed emitter's use-pointee propagation to assign one legal SPIR-V pointer type
|
||||
/// without converting control flow into a pointer `select`.
|
||||
///
|
||||
/// This is reject-only and bounded to the same modest CFG domain as the local cross-arm machinery.
|
||||
/// Larger graphs continue to use the separately bounded path until their state representation can be
|
||||
/// made sparse without retaining `blocks * live_values` incoming pairs.
|
||||
pub(in crate::native) fn renest_whole_cfg_dispatch(
|
||||
blocks: &[BodyBlock],
|
||||
) -> Result<StructuredPlan, String> {
|
||||
if blocks.is_empty() {
|
||||
return Err("construct-tree:whole-cfg-empty".to_string());
|
||||
}
|
||||
if blocks.len() > CROSS_ARM_EDGE_MAX_BLOCKS {
|
||||
return Err(format!(
|
||||
"construct-tree:whole-cfg-block-limit blocks={} limit={CROSS_ARM_EDGE_MAX_BLOCKS}",
|
||||
blocks.len()
|
||||
));
|
||||
}
|
||||
|
||||
let mut nodes = vec![
|
||||
ConstructNode {
|
||||
name: "whole-cfg-root".to_string(),
|
||||
parent: None,
|
||||
kind: ConstructKind::Root,
|
||||
},
|
||||
ConstructNode {
|
||||
name: "whole-cfg-loop".to_string(),
|
||||
parent: Some(0),
|
||||
kind: ConstructKind::Loop,
|
||||
},
|
||||
ConstructNode {
|
||||
name: "whole-cfg-switch".to_string(),
|
||||
parent: Some(1),
|
||||
kind: ConstructKind::Switch,
|
||||
},
|
||||
];
|
||||
let mut claimed = Vec::with_capacity(blocks.len());
|
||||
for (index, block) in blocks.iter().enumerate() {
|
||||
let arm = nodes.len();
|
||||
nodes.push(ConstructNode {
|
||||
name: format!("whole-cfg-arm-{index}"),
|
||||
parent: Some(2),
|
||||
kind: ConstructKind::Arm,
|
||||
});
|
||||
claimed.push(ClaimedBlock {
|
||||
name: block.name.clone(),
|
||||
claims: vec![arm],
|
||||
});
|
||||
}
|
||||
|
||||
let by_name = blocks
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, block)| (block.name.as_str(), index))
|
||||
.collect::<HashMap<_, _>>();
|
||||
let mut edges = Vec::new();
|
||||
let mut seen = HashSet::new();
|
||||
for (from, block) in blocks.iter().enumerate() {
|
||||
for target in block_successors(block) {
|
||||
let Some(&to) = by_name.get(target.as_str()) else {
|
||||
return Err(format!(
|
||||
"construct-tree:whole-cfg-unknown-successor from={} to={target}",
|
||||
block.name
|
||||
));
|
||||
};
|
||||
if seen.insert((from, to)) {
|
||||
edges.push(OriginalEdge { from, to });
|
||||
}
|
||||
}
|
||||
}
|
||||
let plan = plan_construct_tree(&nodes, &claimed, &edges)?;
|
||||
renest::renest_construct_tree(blocks, &plan)
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub(in crate::native) enum ConstructKind {
|
||||
Root,
|
||||
@@ -331,6 +462,7 @@ pub(in crate::native) fn materialize_construct_routes(
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::native::ir::{LlType, LlValue, TypedValue};
|
||||
use crate::native::tir;
|
||||
use std::collections::HashMap;
|
||||
|
||||
@@ -368,6 +500,95 @@ mod tests {
|
||||
]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whole_cfg_dispatch_owns_loop_exit_into_selection_sibling() {
|
||||
let blocks = vec![
|
||||
bb("%entry", &["br label %outer"]),
|
||||
bb("%outer", &["br i1 %direct, label %sibling, label %loop"]),
|
||||
bb(
|
||||
"%loop",
|
||||
&[
|
||||
"%i = phi i32 [ 0, %outer ], [ %next, %body ]",
|
||||
"br label %body",
|
||||
],
|
||||
),
|
||||
bb(
|
||||
"%body",
|
||||
&[
|
||||
"%next = add i32 %i, 1",
|
||||
"br i1 %leave, label %sibling, label %loop",
|
||||
],
|
||||
),
|
||||
bb(
|
||||
"%sibling",
|
||||
&[
|
||||
"%value = phi i32 [ 7, %outer ], [ %next, %body ]",
|
||||
"ret void",
|
||||
],
|
||||
),
|
||||
];
|
||||
assert!(requires_loop_exit_sibling_dispatch(&blocks));
|
||||
let plan = renest_whole_cfg_dispatch(&blocks).expect("whole-CFG ownership plan");
|
||||
assert!(plan
|
||||
.blocks
|
||||
.iter()
|
||||
.any(|block| block.name == "%metal2vulkan.ct.dispatch"));
|
||||
assert!(plan
|
||||
.blocks
|
||||
.iter()
|
||||
.any(|block| block.name == "%metal2vulkan.ct.header"));
|
||||
assert!(super::super::structured_plan_construct_tree(&plan.blocks).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whole_cfg_dispatch_carries_nonvoid_returns_through_typed_state() {
|
||||
let blocks = vec![
|
||||
bb("%entry", &["br i1 %condition, label %left, label %right"]),
|
||||
bb(
|
||||
"%left",
|
||||
&["%left.value = add i32 6, 1", "ret i32 %left.value"],
|
||||
),
|
||||
bb("%right", &["ret i32 9"]),
|
||||
];
|
||||
|
||||
let plan = renest_whole_cfg_dispatch(&blocks).expect("whole-CFG ownership plan");
|
||||
let header = plan
|
||||
.blocks
|
||||
.iter()
|
||||
.find(|block| block.name == "%metal2vulkan.ct.header")
|
||||
.and_then(|block| block.typed.as_ref())
|
||||
.expect("typed dispatcher header");
|
||||
let merge = plan
|
||||
.blocks
|
||||
.iter()
|
||||
.find(|block| block.name == "%metal2vulkan.ct.merge")
|
||||
.and_then(|block| block.typed.as_ref())
|
||||
.expect("typed dispatcher merge");
|
||||
let exit = plan
|
||||
.blocks
|
||||
.iter()
|
||||
.find(|block| block.name == "%metal2vulkan.ct.exit")
|
||||
.and_then(|block| block.typed.as_ref())
|
||||
.expect("typed dispatcher exit");
|
||||
|
||||
assert!(header
|
||||
.insts
|
||||
.iter()
|
||||
.any(|inst| inst.result.as_deref() == Some("%metal2vulkan.ct.return")));
|
||||
assert!(merge
|
||||
.insts
|
||||
.iter()
|
||||
.any(|inst| inst.result.as_deref() == Some("%metal2vulkan.ct.nextreturn")));
|
||||
assert!(matches!(
|
||||
&exit.ret,
|
||||
tir::RetEmit::Value(TypedValue {
|
||||
ty: LlType::Int(32),
|
||||
value: LlValue::Local(value),
|
||||
}) if value == "%metal2vulkan.ct.return"
|
||||
));
|
||||
assert!(super::super::structured_plan_construct_tree(&plan.blocks).is_some());
|
||||
}
|
||||
|
||||
fn linear_claims() -> Vec<ClaimedBlock> {
|
||||
vec![
|
||||
ClaimedBlock {
|
||||
@@ -533,7 +754,7 @@ mod tests {
|
||||
.insts
|
||||
.iter()
|
||||
.find(|inst| inst.result.as_deref() == Some("%value"))
|
||||
.and_then(|inst| inst.phi_incoming.as_ref())
|
||||
.and_then(|inst| inst.phi_incoming().as_ref())
|
||||
.map(|(_, incoming)| incoming)
|
||||
.unwrap();
|
||||
assert_eq!(phi[0].1, format!("{ROUTE_PREFIX}2.0"));
|
||||
@@ -612,8 +833,10 @@ mod tests {
|
||||
.iter()
|
||||
.find(|inst| inst.result.as_deref() == Some("%y"))
|
||||
.unwrap();
|
||||
let mut y_uses = Vec::new();
|
||||
y.visit_uses(|name| y_uses.push(name.to_string()));
|
||||
assert_eq!(
|
||||
y.uses,
|
||||
y_uses,
|
||||
vec!["%metal2vulkan.ct.vslot.0".to_string()],
|
||||
"later cases read the current state slot, not the out-of-scope source SSA name"
|
||||
);
|
||||
@@ -644,7 +867,7 @@ mod tests {
|
||||
.insts
|
||||
.iter()
|
||||
.find(|inst| inst.result.as_deref() == Some("%metal2vulkan.ct.nextvslot.0"))
|
||||
.and_then(|inst| inst.phi_incoming.as_ref())
|
||||
.and_then(|inst| inst.phi_incoming().as_ref())
|
||||
.map(|(_, incoming)| incoming)
|
||||
.unwrap();
|
||||
assert!(
|
||||
@@ -657,7 +880,35 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn r1_renester_keeps_cross_case_pointer_values_rejected() {
|
||||
fn r1_renester_carries_cross_case_pointer_values_as_typed_phis() {
|
||||
let nodes = deep_single_owner_nodes();
|
||||
let blocks = vec![
|
||||
bb("%entry", &["br label %def"]),
|
||||
bb("%def", &["%p = freeze ptr null", "br label %use"]),
|
||||
bb("%use", &["%v = load i32, ptr %p, align 4", "ret void"]),
|
||||
];
|
||||
let edges = vec![
|
||||
OriginalEdge { from: 0, to: 1 },
|
||||
OriginalEdge { from: 1, to: 2 },
|
||||
];
|
||||
let plan = plan_construct_tree(&nodes, &linear_claims(), &edges).unwrap();
|
||||
let out = renest::materialize_construct_tree_roles(&blocks, &plan).unwrap();
|
||||
let header = out
|
||||
.iter()
|
||||
.find(|block| block.name == "%metal2vulkan.ct.header")
|
||||
.and_then(|block| block.typed.as_ref())
|
||||
.expect("typed dispatcher header");
|
||||
let pointer_slot = header
|
||||
.insts
|
||||
.iter()
|
||||
.find(|inst| inst.result.as_deref() == Some("%metal2vulkan.ct.vslot.0"))
|
||||
.expect("pointer state slot");
|
||||
assert_eq!(pointer_slot.result_ty, Some(LlType::Ptr(0)));
|
||||
assert!(super::super::structured_plan_construct_tree(&out).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn r1_renester_keeps_function_variables_out_of_pointer_state() {
|
||||
let nodes = deep_single_owner_nodes();
|
||||
let blocks = vec![
|
||||
bb("%entry", &["br label %def"]),
|
||||
@@ -669,10 +920,262 @@ mod tests {
|
||||
OriginalEdge { from: 1, to: 2 },
|
||||
];
|
||||
let plan = plan_construct_tree(&nodes, &linear_claims(), &edges).unwrap();
|
||||
let out = renest::materialize_construct_tree_roles(&blocks, &plan).unwrap();
|
||||
let header = out
|
||||
.iter()
|
||||
.find(|block| block.name == "%metal2vulkan.ct.header")
|
||||
.and_then(|block| block.typed.as_ref())
|
||||
.expect("typed dispatcher header");
|
||||
|
||||
assert!(!header.insts.iter().any(|inst| {
|
||||
inst.result
|
||||
.as_deref()
|
||||
.is_some_and(|result| result.starts_with("%metal2vulkan.ct.vslot."))
|
||||
}));
|
||||
let use_block = out
|
||||
.iter()
|
||||
.find(|block| block.name == "%use")
|
||||
.and_then(|block| block.typed.as_ref())
|
||||
.expect("typed use block");
|
||||
assert!(use_block.insts.iter().any(|inst| {
|
||||
inst.operands.iter().any(|operand| {
|
||||
matches!(operand, tir::TirOperand::Value { name, ty: LlType::Ptr(0) } if name == "%p")
|
||||
})
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn r1_renester_hoists_function_pointer_derivations_out_of_state() {
|
||||
let nodes = deep_single_owner_nodes();
|
||||
let blocks = vec![
|
||||
bb("%entry", &["br label %def"]),
|
||||
bb(
|
||||
"%def",
|
||||
&[
|
||||
"%p = alloca [2 x i32], align 4",
|
||||
"%alias = bitcast ptr %p to ptr",
|
||||
"%field = getelementptr [2 x i32], ptr %alias, i64 0, i64 1",
|
||||
"%device.field = getelementptr i32, ptr addrspace(1) %device, i64 %index",
|
||||
"br label %use",
|
||||
],
|
||||
),
|
||||
bb(
|
||||
"%use",
|
||||
&[
|
||||
"%v = load i32, ptr %field, align 4",
|
||||
"%w = load i32, ptr addrspace(1) %device.field, align 4",
|
||||
"ret void",
|
||||
],
|
||||
),
|
||||
];
|
||||
let edges = vec![
|
||||
OriginalEdge { from: 0, to: 1 },
|
||||
OriginalEdge { from: 1, to: 2 },
|
||||
];
|
||||
let plan = plan_construct_tree(&nodes, &linear_claims(), &edges).unwrap();
|
||||
let out = renest::materialize_construct_tree_roles(&blocks, &plan).unwrap();
|
||||
let preheader = out
|
||||
.iter()
|
||||
.find(|block| block.name == "%metal2vulkan.ct.pre")
|
||||
.and_then(|block| block.typed.as_ref())
|
||||
.expect("typed dispatcher preheader");
|
||||
let preheader_results = preheader
|
||||
.insts
|
||||
.iter()
|
||||
.filter_map(|inst| inst.result.as_deref())
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
preheader_results,
|
||||
["%p", "%alias", "%field", "%device.field"]
|
||||
);
|
||||
|
||||
let header = out
|
||||
.iter()
|
||||
.find(|block| block.name == "%metal2vulkan.ct.header")
|
||||
.and_then(|block| block.typed.as_ref())
|
||||
.expect("typed dispatcher header");
|
||||
assert!(!header.insts.iter().any(|inst| {
|
||||
inst.result
|
||||
.as_deref()
|
||||
.is_some_and(|result| result.starts_with("%metal2vulkan.ct.vslot."))
|
||||
}));
|
||||
assert_eq!(
|
||||
out.iter()
|
||||
.filter_map(|block| block.typed.as_ref())
|
||||
.flat_map(|block| &block.insts)
|
||||
.filter(|inst| inst.result.as_deref() == Some("%alias"))
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
out.iter()
|
||||
.filter_map(|block| block.typed.as_ref())
|
||||
.flat_map(|block| &block.insts)
|
||||
.filter(|inst| inst.result.as_deref() == Some("%field"))
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
assert!(super::super::structured_plan_construct_tree(&out).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn r1_renester_carries_dynamic_function_pointer_indices() {
|
||||
let nodes = deep_single_owner_nodes();
|
||||
let blocks = vec![
|
||||
bb("%entry", &["br label %def"]),
|
||||
bb(
|
||||
"%def",
|
||||
&[
|
||||
"%p = alloca [4 x i32], align 4",
|
||||
"%index = add i64 %argument, 1",
|
||||
"%field = getelementptr [4 x i32], ptr %p, i64 0, i64 %index",
|
||||
"%same = load i32, ptr %field, align 4",
|
||||
"br label %use",
|
||||
],
|
||||
),
|
||||
bb(
|
||||
"%use",
|
||||
&["store i32 %same, ptr %field, align 4", "ret void"],
|
||||
),
|
||||
];
|
||||
let edges = vec![
|
||||
OriginalEdge { from: 0, to: 1 },
|
||||
OriginalEdge { from: 1, to: 2 },
|
||||
];
|
||||
let plan = plan_construct_tree(&nodes, &linear_claims(), &edges).unwrap();
|
||||
let out = renest::materialize_construct_tree_roles(&blocks, &plan).unwrap();
|
||||
let header = out
|
||||
.iter()
|
||||
.find(|block| block.name == "%metal2vulkan.ct.header")
|
||||
.and_then(|block| block.typed.as_ref())
|
||||
.expect("typed dispatcher header");
|
||||
assert!(header.insts.iter().any(|inst| {
|
||||
inst.result.as_deref() == Some("%metal2vulkan.ct.vslot.0")
|
||||
&& inst.result_ty == Some(LlType::Int(64))
|
||||
}));
|
||||
assert!(header.insts.iter().any(|inst| {
|
||||
inst.result.as_deref() == Some("%metal2vulkan.ct.ptr.0")
|
||||
&& inst.opcode == "getelementptr"
|
||||
}));
|
||||
assert!(!header
|
||||
.insts
|
||||
.iter()
|
||||
.any(|inst| { inst.result_ty == Some(LlType::Ptr(0)) && inst.opcode == "phi" }));
|
||||
|
||||
let defining_case = out
|
||||
.iter()
|
||||
.find(|block| block.name == "%def")
|
||||
.and_then(|block| block.typed.as_ref())
|
||||
.expect("typed defining case");
|
||||
assert!(defining_case
|
||||
.insts
|
||||
.iter()
|
||||
.any(|inst| inst.result.as_deref() == Some("%field")));
|
||||
let later_case = out
|
||||
.iter()
|
||||
.find(|block| block.name == "%use")
|
||||
.and_then(|block| block.typed.as_ref())
|
||||
.expect("typed later case");
|
||||
assert!(later_case.insts.iter().any(|inst| {
|
||||
inst.operands.iter().any(|operand| {
|
||||
matches!(operand, tir::TirOperand::Value { name, ty: LlType::Ptr(0) }
|
||||
if name == "%metal2vulkan.ct.ptr.0")
|
||||
})
|
||||
}));
|
||||
assert!(super::super::structured_plan_construct_tree(&out).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn r1_renester_rejects_opaque_images_as_generic_pointer_state() {
|
||||
let nodes = deep_single_owner_nodes();
|
||||
let blocks = vec![
|
||||
bb("%entry", &["br label %def"]),
|
||||
bb("%def", &["%table = freeze ptr null", "br label %use"]),
|
||||
bb(
|
||||
"%use",
|
||||
&[
|
||||
"%image = load ptr addrspace(1), ptr %table",
|
||||
"call void @air.write_texture_2d(ptr addrspace(1) %image)",
|
||||
"ret void",
|
||||
],
|
||||
),
|
||||
];
|
||||
let edges = vec![
|
||||
OriginalEdge { from: 0, to: 1 },
|
||||
OriginalEdge { from: 1, to: 2 },
|
||||
];
|
||||
let plan = plan_construct_tree(&nodes, &linear_claims(), &edges).unwrap();
|
||||
|
||||
let error = renest::materialize_construct_tree_roles(&blocks, &plan).unwrap_err();
|
||||
assert_eq!(
|
||||
error,
|
||||
"construct-tree:cross-case-pointer-value owner=%def value=%p"
|
||||
"construct-tree:cross-case-opaque-image owner=%def value=%table"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn r1_renester_rejects_opaque_image_phis_as_generic_pointer_state() {
|
||||
let nodes = deep_single_owner_nodes();
|
||||
let blocks = vec![
|
||||
bb("%entry", &["br label %def"]),
|
||||
bb(
|
||||
"%def",
|
||||
&[
|
||||
"%image = phi ptr addrspace(1) [ null, %entry ]",
|
||||
"br label %use",
|
||||
],
|
||||
),
|
||||
bb(
|
||||
"%use",
|
||||
&[
|
||||
"call void @air.write_texture_2d(ptr addrspace(1) %image)",
|
||||
"ret void",
|
||||
],
|
||||
),
|
||||
];
|
||||
let edges = vec![
|
||||
OriginalEdge { from: 0, to: 1 },
|
||||
OriginalEdge { from: 1, to: 2 },
|
||||
];
|
||||
let plan = plan_construct_tree(&nodes, &linear_claims(), &edges).unwrap();
|
||||
|
||||
let error = renest::materialize_construct_tree_roles(&blocks, &plan).unwrap_err();
|
||||
assert_eq!(
|
||||
error,
|
||||
"construct-tree:cross-case-opaque-image owner=%def value=%image"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn r1_renester_rejects_unresolved_cross_case_composites() {
|
||||
let nodes = deep_single_owner_nodes();
|
||||
let blocks = vec![
|
||||
bb("%entry", &["br label %def"]),
|
||||
bb(
|
||||
"%def",
|
||||
&[
|
||||
"%aggregate = insertvalue %\"wrapper\" undef, i32 7, 0",
|
||||
"br label %use",
|
||||
],
|
||||
),
|
||||
bb(
|
||||
"%use",
|
||||
&[
|
||||
"%value = extractvalue %\"wrapper\" %aggregate, 0",
|
||||
"ret void",
|
||||
],
|
||||
),
|
||||
];
|
||||
let edges = vec![
|
||||
OriginalEdge { from: 0, to: 1 },
|
||||
OriginalEdge { from: 1, to: 2 },
|
||||
];
|
||||
let plan = plan_construct_tree(&nodes, &linear_claims(), &edges).unwrap();
|
||||
|
||||
let error = renest::materialize_construct_tree_roles(&blocks, &plan).unwrap_err();
|
||||
assert_eq!(
|
||||
error,
|
||||
"construct-tree:cross-case-unresolved-composite owner=%def value=%aggregate"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Whole-region structured role materialization for the R1 fixture gate.
|
||||
//! Whole-region structured role materialization for typed source CFGs.
|
||||
//!
|
||||
//! The immutable ownership plan is lowered once to a regional dispatcher construct: one loop owns
|
||||
//! one switch, every original body is one switch case, and original edges select the next case.
|
||||
@@ -24,9 +24,12 @@ const PC: &str = "%metal2vulkan.ct.pc";
|
||||
const NEXT_PC: &str = "%metal2vulkan.ct.nextpc";
|
||||
const DONE: &str = "%metal2vulkan.ct.done";
|
||||
const ROUTE: &str = "%metal2vulkan.ct.route";
|
||||
const RETURN_VALUE: &str = "%metal2vulkan.ct.return";
|
||||
const NEXT_RETURN_VALUE: &str = "%metal2vulkan.ct.nextreturn";
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct PhiSlot {
|
||||
original: String,
|
||||
ty: LlType,
|
||||
host: usize,
|
||||
incoming: HashMap<usize, LlValue>,
|
||||
@@ -43,6 +46,158 @@ struct ValueSlot {
|
||||
next: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct HeaderPointerDerivation {
|
||||
owner: usize,
|
||||
original: String,
|
||||
header: String,
|
||||
inst: tir::TirInst,
|
||||
scalar_dependencies: Vec<String>,
|
||||
}
|
||||
|
||||
fn cross_case_state_type(ty: &LlType) -> bool {
|
||||
match ty {
|
||||
LlType::Named(_) => false,
|
||||
LlType::Vector(element, _) | LlType::Array(element, _) => {
|
||||
pointer_free_composite_component(element)
|
||||
}
|
||||
LlType::Struct(fields) => fields.iter().all(pointer_free_composite_component),
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
fn pointer_free_composite_component(ty: &LlType) -> bool {
|
||||
match ty {
|
||||
LlType::Ptr(_) | LlType::Named(_) => false,
|
||||
LlType::Vector(element, _) | LlType::Array(element, _) => {
|
||||
pointer_free_composite_component(element)
|
||||
}
|
||||
LlType::Struct(fields) => fields.iter().all(pointer_free_composite_component),
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
fn opaque_image_dependencies(blocks: &[BodyBlock]) -> HashSet<String> {
|
||||
let mut values = HashSet::new();
|
||||
for block in blocks.iter().filter_map(|block| block.typed.as_ref()) {
|
||||
for inst in &block.insts {
|
||||
let Some(call) = inst.call().as_ref() else {
|
||||
continue;
|
||||
};
|
||||
if !crate::air_intrinsics::air_image_intrinsic(&call.callee) {
|
||||
continue;
|
||||
}
|
||||
for argument in &call.args {
|
||||
if matches!(argument.ty, LlType::Ptr(_)) {
|
||||
if let LlValue::Local(name) = &argument.value {
|
||||
values.insert(name.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut changed = true;
|
||||
while changed {
|
||||
changed = false;
|
||||
for block in blocks.iter().filter_map(|block| block.typed.as_ref()) {
|
||||
for inst in &block.insts {
|
||||
let Some(result) = &inst.result else {
|
||||
continue;
|
||||
};
|
||||
if !values.contains(result) || !matches!(inst.result_ty, Some(LlType::Ptr(_))) {
|
||||
continue;
|
||||
}
|
||||
for operand in &inst.operands {
|
||||
if let tir::TirOperand::Value {
|
||||
name,
|
||||
ty: LlType::Ptr(_),
|
||||
} = operand
|
||||
{
|
||||
changed |= values.insert(name.clone());
|
||||
}
|
||||
}
|
||||
if let Some(phi_values) = inst.phi_values() {
|
||||
for value in phi_values {
|
||||
if let LlValue::Local(name) = value {
|
||||
changed |= values.insert(name.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
values
|
||||
}
|
||||
|
||||
fn dominating_pointer_derivations(
|
||||
blocks: &[BodyBlock],
|
||||
function_variables: &HashSet<String>,
|
||||
defined_values: &HashSet<String>,
|
||||
) -> (HashSet<String>, Vec<tir::TirInst>) {
|
||||
let mut names = HashSet::new();
|
||||
let mut instructions = Vec::new();
|
||||
loop {
|
||||
let mut added = false;
|
||||
for block in blocks.iter().filter_map(|block| block.typed.as_ref()) {
|
||||
for inst in &block.insts {
|
||||
let Some(result) = &inst.result else {
|
||||
continue;
|
||||
};
|
||||
if names.contains(result)
|
||||
|| !matches!(inst.result_ty, Some(LlType::Ptr(_)))
|
||||
|| !matches!(
|
||||
inst.opcode,
|
||||
tir::TirOpcode::Bitcast
|
||||
| tir::TirOpcode::AddrSpaceCast
|
||||
| tir::TirOpcode::GetElementPtr
|
||||
)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut rooted = match inst.opcode {
|
||||
tir::TirOpcode::GetElementPtr => inst.gep().as_ref().is_some_and(|gep| {
|
||||
matches!(
|
||||
&gep.base.value,
|
||||
LlValue::Local(name) if !defined_values.contains(name)
|
||||
)
|
||||
}),
|
||||
tir::TirOpcode::Bitcast | tir::TirOpcode::AddrSpaceCast => {
|
||||
inst.operands.iter().any(|operand| {
|
||||
matches!(
|
||||
operand,
|
||||
tir::TirOperand::Value {
|
||||
name,
|
||||
ty: LlType::Ptr(_)
|
||||
} if !defined_values.contains(name)
|
||||
)
|
||||
})
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
let mut operands_dominate = true;
|
||||
inst.visit_uses(|name| {
|
||||
if function_variables.contains(name) || names.contains(name) {
|
||||
rooted = true;
|
||||
} else if defined_values.contains(name) {
|
||||
operands_dominate = false;
|
||||
}
|
||||
});
|
||||
if rooted && operands_dominate {
|
||||
names.insert(result.clone());
|
||||
instructions.push(inst.clone());
|
||||
added = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if !added {
|
||||
break;
|
||||
}
|
||||
}
|
||||
(names, instructions)
|
||||
}
|
||||
|
||||
fn passthrough(name: &str, target: &str) -> BodyBlock {
|
||||
synthetic_block(
|
||||
name.to_string(),
|
||||
@@ -212,7 +367,10 @@ pub(in crate::native) fn materialize_construct_tree_roles(
|
||||
.iter()
|
||||
.map(|route| ((route.edge.from, route.edge.to), route))
|
||||
.collect();
|
||||
let opaque_image_dependencies = opaque_image_dependencies(blocks);
|
||||
|
||||
let mut return_ty = None;
|
||||
let mut saw_void_return = false;
|
||||
let mut successors = Vec::with_capacity(blocks.len());
|
||||
for (source, block) in blocks.iter().enumerate() {
|
||||
let carrier = block
|
||||
@@ -230,11 +388,42 @@ pub(in crate::native) fn materialize_construct_tree_roles(
|
||||
block.name
|
||||
));
|
||||
}
|
||||
if matches!(carrier.terminator, tir::TirTerminator::Ret(Some(_))) {
|
||||
return Err(format!(
|
||||
"construct-tree:nonvoid-return block={}",
|
||||
block.name
|
||||
));
|
||||
match &carrier.ret {
|
||||
tir::RetEmit::Value(value) => {
|
||||
if matches!(value.ty, LlType::Ptr(_)) {
|
||||
return Err(format!(
|
||||
"construct-tree:pointer-return block={}",
|
||||
block.name
|
||||
));
|
||||
}
|
||||
if saw_void_return
|
||||
|| return_ty
|
||||
.as_ref()
|
||||
.is_some_and(|existing| existing != &value.ty)
|
||||
{
|
||||
return Err(format!(
|
||||
"construct-tree:mixed-return-type block={}",
|
||||
block.name
|
||||
));
|
||||
}
|
||||
return_ty = Some(value.ty.clone());
|
||||
}
|
||||
tir::RetEmit::Void => {
|
||||
if return_ty.is_some() {
|
||||
return Err(format!(
|
||||
"construct-tree:mixed-return-type block={}",
|
||||
block.name
|
||||
));
|
||||
}
|
||||
saw_void_return = true;
|
||||
}
|
||||
tir::RetEmit::FromText if matches!(carrier.terminator, tir::TirTerminator::Ret(_)) => {
|
||||
return Err(format!(
|
||||
"construct-tree:untyped-return block={}",
|
||||
block.name
|
||||
));
|
||||
}
|
||||
tir::RetEmit::FromText => {}
|
||||
}
|
||||
let mut block_successors = Vec::new();
|
||||
for target in carrier.terminator.successors() {
|
||||
@@ -275,7 +464,7 @@ pub(in crate::native) fn materialize_construct_tree_roles(
|
||||
for (host, block) in blocks.iter().enumerate() {
|
||||
let carrier = block.typed.as_ref().expect("checked above");
|
||||
for inst in &carrier.insts {
|
||||
let Some((ty, incoming)) = &inst.phi_incoming else {
|
||||
let Some((ty, incoming)) = &inst.phi_incoming() else {
|
||||
continue;
|
||||
};
|
||||
let result = inst
|
||||
@@ -308,6 +497,7 @@ pub(in crate::native) fn materialize_construct_tree_roles(
|
||||
}
|
||||
}
|
||||
slots.push(PhiSlot {
|
||||
original: result.clone(),
|
||||
ty: ty.clone(),
|
||||
host,
|
||||
incoming: routed,
|
||||
@@ -316,6 +506,14 @@ pub(in crate::native) fn materialize_construct_tree_roles(
|
||||
});
|
||||
}
|
||||
}
|
||||
for slot in &slots {
|
||||
if matches!(slot.ty, LlType::Ptr(_)) && opaque_image_dependencies.contains(&slot.original) {
|
||||
return Err(format!(
|
||||
"construct-tree:cross-case-opaque-image owner={} value={}",
|
||||
blocks[slot.host].name, slot.original
|
||||
));
|
||||
}
|
||||
}
|
||||
for slot in &mut slots {
|
||||
for value in slot.incoming.values_mut() {
|
||||
*value = renamed_value(value, &rename);
|
||||
@@ -323,14 +521,23 @@ pub(in crate::native) fn materialize_construct_tree_roles(
|
||||
}
|
||||
|
||||
// Non-phi values crossing between original cases are carried explicitly through typed state slots.
|
||||
// Pointer values remain excluded: a raw `ptr` slot would discard provenance/pointee information that
|
||||
// the later pointer path still depends on.
|
||||
// A pointer slot remains a pointer phi rather than becoming a value select. The TIR pointee
|
||||
// propagation sees that phi together with all of its uses and assigns one concrete pointee to the
|
||||
// complete network before SPIR-V emission.
|
||||
let mut def_block = HashMap::new();
|
||||
let mut defined_values = HashSet::new();
|
||||
let mut function_variables = HashSet::new();
|
||||
for (index, block) in blocks.iter().enumerate() {
|
||||
for inst in &block.typed.as_ref().expect("checked above").insts {
|
||||
if let Some(result) = &inst.result {
|
||||
defined_values.insert(result.clone());
|
||||
}
|
||||
if !inst.is_phi() {
|
||||
if let Some(result) = &inst.result {
|
||||
def_block.insert(result.clone(), (index, inst.result_ty.clone()));
|
||||
if inst.opcode == "alloca" {
|
||||
function_variables.insert(result.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -342,14 +549,14 @@ pub(in crate::native) fn materialize_construct_tree_roles(
|
||||
if inst.is_phi() {
|
||||
continue;
|
||||
}
|
||||
for name in &inst.uses {
|
||||
inst.visit_uses(|name| {
|
||||
if def_block
|
||||
.get(name.as_str())
|
||||
.get(name)
|
||||
.is_some_and(|(owner, _)| *owner != index)
|
||||
{
|
||||
cross_values.insert(name.clone());
|
||||
cross_values.insert(name.to_string());
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
for name in terminator_value_uses(&carrier.terminator) {
|
||||
if def_block
|
||||
@@ -375,6 +582,79 @@ pub(in crate::native) fn materialize_construct_tree_roles(
|
||||
}
|
||||
}
|
||||
}
|
||||
// The SPIR-V emitter declares every LLVM `alloca` as a function-scope variable in the entry
|
||||
// block. It therefore already dominates every dispatcher case and is not loop-carried SSA state.
|
||||
// Pure pointer derivations whose complete local dependency chain reaches such a variable or a
|
||||
// function parameter can likewise execute once in the dispatcher preheader. Keeping these values
|
||||
// in state would invent pointer merges for addresses which already dominate the whole region.
|
||||
let (dominating_pointer_derivations, pointer_preheader_instructions) =
|
||||
dominating_pointer_derivations(blocks, &function_variables, &defined_values);
|
||||
cross_values.retain(|name| {
|
||||
!function_variables.contains(name) && !dominating_pointer_derivations.contains(name)
|
||||
});
|
||||
|
||||
// A Function pointer derived from a dominating root and dynamic scalar indices is represented by
|
||||
// carrying those indices, not the pointer. The defining case keeps its original GEP for immediate
|
||||
// uses; the dispatcher header reconstructs a distinct pointer from the previous iteration's scalar
|
||||
// state for uses in later cases. This preserves pointer identity without requiring a Function
|
||||
// pointer phi, which SPIR-V cannot express.
|
||||
let mut header_pointer_derivations = Vec::new();
|
||||
for (owner, block) in blocks.iter().enumerate() {
|
||||
for inst in &block.typed.as_ref().expect("checked above").insts {
|
||||
let Some(original) = &inst.result else {
|
||||
continue;
|
||||
};
|
||||
if !cross_values.contains(original) || inst.result_ty != Some(LlType::Ptr(0)) {
|
||||
continue;
|
||||
}
|
||||
let Some(gep) = inst.gep().as_ref() else {
|
||||
continue;
|
||||
};
|
||||
let LlValue::Local(base) = &gep.base.value else {
|
||||
continue;
|
||||
};
|
||||
if defined_values.contains(base)
|
||||
&& !function_variables.contains(base)
|
||||
&& !dominating_pointer_derivations.contains(base)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut scalar_dependencies = Vec::new();
|
||||
let mut representable = true;
|
||||
for index in &gep.indices {
|
||||
let LlValue::Local(name) = &index.value else {
|
||||
continue;
|
||||
};
|
||||
if rename.contains_key(name) || !defined_values.contains(name) {
|
||||
continue;
|
||||
}
|
||||
let Some((_, Some(ty))) = def_block.get(name) else {
|
||||
representable = false;
|
||||
break;
|
||||
};
|
||||
if matches!(ty, LlType::Ptr(_)) || !cross_case_state_type(ty) {
|
||||
representable = false;
|
||||
break;
|
||||
}
|
||||
scalar_dependencies.push(name.clone());
|
||||
}
|
||||
if !representable || scalar_dependencies.is_empty() {
|
||||
continue;
|
||||
}
|
||||
for dependency in &scalar_dependencies {
|
||||
cross_values.insert(dependency.clone());
|
||||
}
|
||||
cross_values.remove(original);
|
||||
header_pointer_derivations.push(HeaderPointerDerivation {
|
||||
owner,
|
||||
original: original.clone(),
|
||||
header: format!("{PREFIX}ptr.{}", header_pointer_derivations.len()),
|
||||
inst: inst.clone(),
|
||||
scalar_dependencies,
|
||||
});
|
||||
}
|
||||
}
|
||||
let mut value_slots = Vec::new();
|
||||
for original in cross_values {
|
||||
let Some((owner, ty)) = def_block.get(&original) else {
|
||||
@@ -386,9 +666,15 @@ pub(in crate::native) fn materialize_construct_tree_roles(
|
||||
blocks[*owner].name
|
||||
));
|
||||
};
|
||||
if matches!(ty, LlType::Ptr(_)) {
|
||||
if !cross_case_state_type(ty) {
|
||||
return Err(format!(
|
||||
"construct-tree:cross-case-pointer-value owner={} value={original}",
|
||||
"construct-tree:cross-case-unresolved-composite owner={} value={original}",
|
||||
blocks[*owner].name
|
||||
));
|
||||
}
|
||||
if matches!(ty, LlType::Ptr(_)) && opaque_image_dependencies.contains(&original) {
|
||||
return Err(format!(
|
||||
"construct-tree:cross-case-opaque-image owner={} value={original}",
|
||||
blocks[*owner].name
|
||||
));
|
||||
}
|
||||
@@ -412,7 +698,21 @@ pub(in crate::native) fn materialize_construct_tree_roles(
|
||||
}
|
||||
|
||||
let done_state = blocks.len() as u64;
|
||||
let mut out = vec![passthrough(PRE, HEADER)];
|
||||
let mut preheader = passthrough(PRE, HEADER);
|
||||
let preheader_carrier =
|
||||
std::sync::Arc::make_mut(preheader.typed.as_mut().expect("typed preheader"));
|
||||
preheader_carrier.insts.extend(
|
||||
blocks
|
||||
.iter()
|
||||
.filter_map(|block| block.typed.as_ref())
|
||||
.flat_map(|block| &block.insts)
|
||||
.filter(|inst| inst.opcode == "alloca")
|
||||
.cloned(),
|
||||
);
|
||||
preheader_carrier
|
||||
.insts
|
||||
.extend(pointer_preheader_instructions);
|
||||
let mut out = vec![preheader];
|
||||
let mut header_phis = vec![(
|
||||
PC.to_string(),
|
||||
LlType::Int(32),
|
||||
@@ -441,12 +741,40 @@ pub(in crate::native) fn materialize_construct_tree_roles(
|
||||
],
|
||||
));
|
||||
}
|
||||
out.push(carrier_with_phis(
|
||||
HEADER,
|
||||
TEST,
|
||||
&header_phis,
|
||||
BlockRole::Normal,
|
||||
)?);
|
||||
if let Some(return_ty) = &return_ty {
|
||||
header_phis.push((
|
||||
RETURN_VALUE.to_string(),
|
||||
return_ty.clone(),
|
||||
vec![
|
||||
(LlValue::Undef, PRE.to_string()),
|
||||
(
|
||||
LlValue::Local(NEXT_RETURN_VALUE.to_string()),
|
||||
CONTINUE.to_string(),
|
||||
),
|
||||
],
|
||||
));
|
||||
}
|
||||
let mut header = carrier_with_phis(HEADER, TEST, &header_phis, BlockRole::Normal)?;
|
||||
if !header_pointer_derivations.is_empty() {
|
||||
let carrier = std::sync::Arc::make_mut(header.typed.as_mut().expect("typed header"));
|
||||
carrier.insts.extend(
|
||||
header_pointer_derivations
|
||||
.iter()
|
||||
.map(|derivation| derivation.inst.clone()),
|
||||
);
|
||||
let mut header_rename = rename.clone();
|
||||
for derivation in &header_pointer_derivations {
|
||||
header_rename.insert(derivation.original.clone(), derivation.header.clone());
|
||||
for dependency in &derivation.scalar_dependencies {
|
||||
let slot = value_slot_by_name
|
||||
.get(dependency.as_str())
|
||||
.expect("dynamic pointer scalar has a value slot");
|
||||
header_rename.insert(dependency.clone(), slot.current.clone());
|
||||
}
|
||||
}
|
||||
carrier.rename(&header_rename);
|
||||
}
|
||||
out.push(header);
|
||||
out.push(synthetic_block(
|
||||
TEST.to_string(),
|
||||
vec![
|
||||
@@ -478,20 +806,27 @@ pub(in crate::native) fn materialize_construct_tree_roles(
|
||||
.iter()
|
||||
.map(|_| Vec::with_capacity(blocks.len()))
|
||||
.collect::<Vec<_>>();
|
||||
let mut return_update_incoming = return_ty.as_ref().map(|_| Vec::with_capacity(blocks.len()));
|
||||
for (case_index, original) in blocks.iter().enumerate() {
|
||||
let mut case = original.clone();
|
||||
let carrier = std::sync::Arc::make_mut(case.typed.as_mut().expect("checked above"));
|
||||
carrier.rename(&rename);
|
||||
carrier.insts.retain(|inst| {
|
||||
!inst.result.as_ref().is_some_and(|result| {
|
||||
function_variables.contains(result)
|
||||
|| dominating_pointer_derivations.contains(result)
|
||||
})
|
||||
});
|
||||
// Most cross-case values are irrelevant to any one case. Building the full value-slot map
|
||||
// for every block made this bounded transform allocate O(cases * slots) cloned names and
|
||||
// types before it touched a single operand. Restrict the substitution map to actual uses in
|
||||
// this carrier; the deep typed substitution below remains the sole mutation primitive.
|
||||
let mut used_names = carrier
|
||||
.insts
|
||||
.iter()
|
||||
.filter(|inst| !inst.is_phi())
|
||||
.flat_map(|inst| inst.uses.iter().cloned())
|
||||
.collect::<HashSet<_>>();
|
||||
let mut used_names = HashSet::new();
|
||||
for inst in carrier.insts.iter().filter(|inst| !inst.is_phi()) {
|
||||
inst.visit_uses(|name| {
|
||||
used_names.insert(name.to_string());
|
||||
});
|
||||
}
|
||||
used_names.extend(terminator_value_uses(&carrier.terminator));
|
||||
let mut substitutions = HashMap::new();
|
||||
for name in used_names {
|
||||
@@ -509,8 +844,23 @@ pub(in crate::native) fn materialize_construct_tree_roles(
|
||||
},
|
||||
);
|
||||
}
|
||||
for derivation in &header_pointer_derivations {
|
||||
if derivation.owner != case_index {
|
||||
substitutions.insert(
|
||||
derivation.original.clone(),
|
||||
TypedValue {
|
||||
ty: LlType::Ptr(0),
|
||||
value: LlValue::Local(derivation.header.clone()),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
carrier.substitute_values(&substitutions);
|
||||
carrier.insts.retain(|inst| !inst.is_phi());
|
||||
let case_return = match &carrier.ret {
|
||||
tir::RetEmit::Value(value) => Some(value.value.clone()),
|
||||
tir::RetEmit::Void | tir::RetEmit::FromText => None,
|
||||
};
|
||||
let targets = &successors[case_index];
|
||||
let join = format!("{PREFIX}casejoin.{case_index}");
|
||||
let mut route_tails = Vec::with_capacity(targets.len());
|
||||
@@ -626,6 +976,12 @@ pub(in crate::native) fn materialize_construct_tree_roles(
|
||||
for (incoming, value) in value_update_incoming.iter_mut().zip(case_value_updates) {
|
||||
incoming.push((value, join.clone()));
|
||||
}
|
||||
if let Some(incoming) = return_update_incoming.as_mut() {
|
||||
incoming.push((
|
||||
case_return.unwrap_or_else(|| LlValue::Local(RETURN_VALUE.to_string())),
|
||||
join,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
out.push(passthrough(INVALID, MERGE));
|
||||
@@ -666,6 +1022,19 @@ pub(in crate::native) fn materialize_construct_tree_roles(
|
||||
.collect(),
|
||||
));
|
||||
}
|
||||
if let Some(incoming) = return_update_incoming {
|
||||
merge_phis.push((
|
||||
NEXT_RETURN_VALUE.to_string(),
|
||||
return_ty.clone().expect("return updates require a type"),
|
||||
incoming
|
||||
.into_iter()
|
||||
.chain(std::iter::once((
|
||||
LlValue::Local(RETURN_VALUE.to_string()),
|
||||
INVALID.to_string(),
|
||||
)))
|
||||
.collect(),
|
||||
));
|
||||
}
|
||||
out.push(carrier_with_phis(
|
||||
MERGE,
|
||||
CONTINUE,
|
||||
@@ -673,9 +1042,16 @@ pub(in crate::native) fn materialize_construct_tree_roles(
|
||||
BlockRole::LMerge,
|
||||
)?);
|
||||
out.push(passthrough(CONTINUE, HEADER));
|
||||
let exit = if let Some(return_ty) = &return_ty {
|
||||
let return_ty = crate::native::render::render_type(return_ty)
|
||||
.ok_or_else(|| "construct-tree:unrenderable-return-type".to_string())?;
|
||||
format!("ret {return_ty} {RETURN_VALUE}")
|
||||
} else {
|
||||
"ret void".to_string()
|
||||
};
|
||||
out.push(synthetic_block(
|
||||
EXIT.to_string(),
|
||||
vec!["ret void".to_string()],
|
||||
vec![exit],
|
||||
BlockRole::Normal,
|
||||
));
|
||||
|
||||
@@ -702,7 +1078,7 @@ pub(in crate::native) fn materialize_construct_tree_roles(
|
||||
.iter()
|
||||
.filter_map(|block| block.typed.as_ref())
|
||||
.flat_map(|block| &block.insts)
|
||||
.filter_map(|inst| inst.phi_incoming.as_ref())
|
||||
.filter_map(|inst| inst.phi_incoming().as_ref())
|
||||
.map(|(_, incoming)| incoming.len())
|
||||
.sum::<usize>();
|
||||
eprintln!(
|
||||
@@ -712,21 +1088,27 @@ pub(in crate::native) fn materialize_construct_tree_roles(
|
||||
value_slots.len()
|
||||
);
|
||||
}
|
||||
if super::super::structured_plan(&out).is_none() {
|
||||
let reason =
|
||||
super::super::structured_reject_reason(&out).unwrap_or_else(|| "unknown".to_string());
|
||||
if finalized_construct_tree_plan(&out).is_none() {
|
||||
let reason = super::super::construct_tree_reject_reason(&out)
|
||||
.unwrap_or_else(|| "unknown".to_string());
|
||||
return Err(format!("construct-tree:role-plan-reject reason={reason}"));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Materialize the bounded construct tree and return the ordinary planner's finalized result. Kept as
|
||||
/// the direct R1 proof API; production wiring can consume the returned maps without re-planning.
|
||||
fn finalized_construct_tree_plan(blocks: &[BodyBlock]) -> Option<super::super::StructuredPlan> {
|
||||
super::super::structured_plan(blocks)
|
||||
.or_else(|| super::super::structured_plan_construct_tree(blocks))
|
||||
}
|
||||
|
||||
/// Materialize the bounded construct tree and return its finalized ownership-aware planner result.
|
||||
/// Kept as the direct R1 proof API; production wiring can consume the returned maps without
|
||||
/// re-planning.
|
||||
pub(in crate::native) fn renest_construct_tree(
|
||||
blocks: &[BodyBlock],
|
||||
plan: &ConstructTreePlan,
|
||||
) -> Result<super::super::StructuredPlan, String> {
|
||||
let out = materialize_construct_tree_roles(blocks, plan)?;
|
||||
super::super::structured_plan(&out)
|
||||
finalized_construct_tree_plan(&out)
|
||||
.ok_or_else(|| "construct-tree:role-plan-nondeterministic".to_string())
|
||||
}
|
||||
@@ -212,7 +212,7 @@ fn llvm_fixture_shell(block_count: usize) -> String {
|
||||
params.push(format!("i32 %ct.switch{index}"));
|
||||
}
|
||||
format!(
|
||||
"target triple = \"spirv-unknown-vulkan1.3\"\n\
|
||||
"target triple = \"spirv-unknown-vulkan1.2\"\n\
|
||||
define void @construct_tree_fixture({}) {{\n\
|
||||
entry:\n\
|
||||
ret void\n\
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+1422
-307
File diff suppressed because it is too large.
Load diff
@@ -30,18 +30,30 @@ pub(in crate::native) fn split_multi_exit_critical_edges(
|
||||
exits: &[String],
|
||||
counter: &mut usize,
|
||||
) -> Option<Vec<(String, usize)>> {
|
||||
if exits.len() != 2 {
|
||||
return None;
|
||||
}
|
||||
let body: HashSet<&str> = forest
|
||||
let body = forest
|
||||
.loop_for_header(header)?
|
||||
.body
|
||||
.iter()
|
||||
.map(String::as_str)
|
||||
.collect();
|
||||
.cloned()
|
||||
.collect::<HashSet<_>>();
|
||||
split_two_target_critical_edges(blocks, &body, exits, counter)
|
||||
}
|
||||
|
||||
/// Split a region predecessor that branches to both dispatch targets, preserving destination phis.
|
||||
/// The returned edge blocks become the unambiguous predecessor/target pairs consumed by
|
||||
/// [`synth_two_target_dispatch`].
|
||||
pub(in crate::native) fn split_two_target_critical_edges(
|
||||
blocks: &mut Vec<BodyBlock>,
|
||||
region: &HashSet<String>,
|
||||
exits: &[String],
|
||||
counter: &mut usize,
|
||||
) -> Option<Vec<(String, usize)>> {
|
||||
if exits.len() != 2 {
|
||||
return None;
|
||||
}
|
||||
let mut splits: Vec<(String, Vec<usize>)> = Vec::new();
|
||||
|
||||
for block in blocks.iter().filter(|b| body.contains(b.name.as_str())) {
|
||||
for block in blocks.iter().filter(|block| region.contains(&block.name)) {
|
||||
let successors = block_successors(block);
|
||||
let hit: Vec<usize> = exits
|
||||
.iter()
|
||||
@@ -153,11 +165,143 @@ pub(in crate::native) fn synth_multi_exit_merge(
|
||||
return None;
|
||||
}
|
||||
|
||||
synth_two_target_dispatch(blocks, exits, &preds, counter)
|
||||
}
|
||||
|
||||
/// Funnel a proved set of predecessor edges to two structural role targets through one typed
|
||||
/// dispatch block. The caller owns region discovery; this primitive owns the edge and SSA contract.
|
||||
pub(in crate::native) fn synth_two_target_dispatch(
|
||||
blocks: &mut Vec<BodyBlock>,
|
||||
exits: &[String],
|
||||
preds: &[(String, usize)],
|
||||
counter: &mut usize,
|
||||
) -> Option<String> {
|
||||
if exits.len() != 2 || preds.is_empty() || preds.iter().any(|(_, exit)| *exit >= exits.len()) {
|
||||
return None;
|
||||
}
|
||||
let merge = format!("{SPLIT_PREFIX}{counter}");
|
||||
*counter += 1;
|
||||
let sel = format!("{EXIT_SEL_PREFIX}{counter}");
|
||||
*counter += 1;
|
||||
|
||||
// Redirecting several exits through one dispatch merge changes SSA dominance even though the
|
||||
// selected runtime path is unchanged. A value defined on one exit path used to dominate that
|
||||
// exit directly; after funneling, the other exit paths also reach the dispatch block and make the
|
||||
// original definition non-dominating. Carry each such ordinary live-in through a typed phi in the
|
||||
// dispatch (`undef` on paths selected for the other exit), then rewrite only the dominated target
|
||||
// region's non-phi consumers. Destination phis retain their separate edge-specific funnel below.
|
||||
let forest = analyze(blocks);
|
||||
let mut definitions = HashMap::new();
|
||||
for block in blocks.iter() {
|
||||
let carrier = block.typed.as_ref()?;
|
||||
for instruction in &carrier.insts {
|
||||
if let (Some(result), Some(ty)) = (&instruction.result, &instruction.result_ty) {
|
||||
definitions.insert(result.clone(), (block.name.clone(), ty.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut dispatch_live_phis: Vec<(
|
||||
String,
|
||||
crate::native::ir::LlType,
|
||||
Vec<(crate::native::ir::LlValue, String)>,
|
||||
)> = Vec::new();
|
||||
let mut region_substitutions = Vec::new();
|
||||
for (exit_index, exit) in exits.iter().enumerate() {
|
||||
let region = blocks
|
||||
.iter()
|
||||
.filter(|block| forest.dominates(exit, &block.name))
|
||||
.map(|block| block.name.clone())
|
||||
.collect::<HashSet<_>>();
|
||||
let mut used = Vec::new();
|
||||
let mut used_set = HashSet::new();
|
||||
for block in blocks.iter().filter(|block| region.contains(&block.name)) {
|
||||
let carrier = block.typed.as_ref()?;
|
||||
for instruction in carrier
|
||||
.insts
|
||||
.iter()
|
||||
.filter(|instruction| !instruction.is_phi())
|
||||
{
|
||||
instruction.visit_uses(|name| {
|
||||
if used_set.insert(name.to_string()) {
|
||||
used.push(name.to_string());
|
||||
}
|
||||
});
|
||||
}
|
||||
let terminator_use = match &carrier.terminator {
|
||||
crate::native::tir::TirTerminator::Br(_)
|
||||
| crate::native::tir::TirTerminator::Ret(None)
|
||||
| crate::native::tir::TirTerminator::Unreachable => None,
|
||||
crate::native::tir::TirTerminator::BrCond { cond, .. }
|
||||
| crate::native::tir::TirTerminator::Switch { selector: cond, .. }
|
||||
| crate::native::tir::TirTerminator::Ret(Some(cond)) => Some(cond),
|
||||
};
|
||||
if let Some(name) = terminator_use {
|
||||
if used_set.insert(name.clone()) {
|
||||
used.push(name.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut substitutions = HashMap::new();
|
||||
for value in used {
|
||||
let Some((definition_block, ty)) = definitions.get(&value) else {
|
||||
continue;
|
||||
};
|
||||
if region.contains(definition_block) {
|
||||
continue;
|
||||
}
|
||||
if preds
|
||||
.iter()
|
||||
.all(|(predecessor, _)| forest.dominates(definition_block, predecessor))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if !preds
|
||||
.iter()
|
||||
.filter(|(_, target)| *target == exit_index)
|
||||
.all(|(predecessor, _)| forest.dominates(definition_block, predecessor))
|
||||
|| !dispatch_live_value_type(ty)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let carried = format!("%metal2vulkan.exitlive.{counter}");
|
||||
*counter += 1;
|
||||
let incoming = preds
|
||||
.iter()
|
||||
.map(|(predecessor, target)| {
|
||||
let incoming = if *target == exit_index {
|
||||
crate::native::ir::LlValue::Local(value.clone())
|
||||
} else {
|
||||
crate::native::ir::LlValue::Undef
|
||||
};
|
||||
(incoming, predecessor.clone())
|
||||
})
|
||||
.collect();
|
||||
substitutions.insert(
|
||||
value,
|
||||
crate::native::ir::TypedValue {
|
||||
ty: ty.clone(),
|
||||
value: crate::native::ir::LlValue::Local(carried.clone()),
|
||||
},
|
||||
);
|
||||
dispatch_live_phis.push((carried, ty.clone(), incoming));
|
||||
}
|
||||
region_substitutions.push((region, substitutions));
|
||||
}
|
||||
// Apply only after every region/type/dominance proof succeeds, so a declined dispatch leaves the
|
||||
// caller's owned CFG untouched.
|
||||
for (region, substitutions) in region_substitutions {
|
||||
for block in blocks
|
||||
.iter_mut()
|
||||
.filter(|block| region.contains(&block.name))
|
||||
{
|
||||
block
|
||||
.typed_mut()
|
||||
.expect("dispatch live-in analysis checked every carrier")
|
||||
.substitute_non_phi_values(&substitutions);
|
||||
}
|
||||
}
|
||||
|
||||
// Redirect every in-loop exit edge directly to the merge.
|
||||
for b in blocks.iter_mut() {
|
||||
if let Some((_, idx)) = preds.iter().find(|(n, _)| n == &b.name) {
|
||||
@@ -211,7 +355,7 @@ pub(in crate::native) fn synth_multi_exit_merge(
|
||||
if let Some(t) = &blocks[exit_idx].typed {
|
||||
for inst in &t.insts {
|
||||
let (Some(dst), Some((cty, inc))) =
|
||||
(inst.result.clone(), inst.phi_incoming.clone())
|
||||
(inst.result.clone(), inst.phi_incoming().clone())
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
@@ -280,6 +424,9 @@ pub(in crate::native) fn synth_multi_exit_merge(
|
||||
for (mname, ty, merged_typed) in &typed_value_phis {
|
||||
blk.push_value_phi(mname, ty, merged_typed);
|
||||
}
|
||||
for (name, ty, incoming) in &dispatch_live_phis {
|
||||
blk.push_value_phi(name, ty, incoming);
|
||||
}
|
||||
blk.push_value_phi(&sel, &crate::native::ir::LlType::Int(1), &selector_typed);
|
||||
let merge_block = BodyBlock {
|
||||
name: merge.clone(),
|
||||
@@ -296,6 +443,16 @@ pub(in crate::native) fn synth_multi_exit_merge(
|
||||
Some(merge)
|
||||
}
|
||||
|
||||
fn dispatch_live_value_type(ty: &crate::native::ir::LlType) -> bool {
|
||||
use crate::native::ir::LlType;
|
||||
match ty {
|
||||
LlType::Void | LlType::Ptr(_) | LlType::Named(_) => false,
|
||||
LlType::Vector(element, _) | LlType::Array(element, _) => dispatch_live_value_type(element),
|
||||
LlType::Struct(fields) => fields.iter().all(dispatch_live_value_type),
|
||||
LlType::Bool | LlType::Float | LlType::Half | LlType::BFloat | LlType::Int(_) => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Unify a loop's multiple back-edges (latches) into ONE synthesized latch so the loop can carry a
|
||||
/// valid single `OpLoopMerge` continue target (`Restructure::MultipleLatches`). SPIR-V names exactly
|
||||
/// one continue target, so a loop whose header has several back-edge predecessors must funnel them
|
||||
@@ -348,7 +505,7 @@ pub(in crate::native) fn synth_multi_latch_continue(
|
||||
let mut header_typed_merges: Vec<(String, TypedIncomings)> = Vec::new();
|
||||
if let Some(t) = &blocks[hidx].typed {
|
||||
for inst in &t.insts {
|
||||
let (Some(dst), Some((cty, inc))) = (inst.result.clone(), inst.phi_incoming.clone())
|
||||
let (Some(dst), Some((cty, inc))) = (inst.result.clone(), inst.phi_incoming().clone())
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
|
||||
@@ -441,18 +441,14 @@ fn regional_candidate(witness: Witness) -> Result<Vec<BodyBlock>, String> {
|
||||
.copied()
|
||||
.filter(|index| source_forest.dominates(&blocks[work].name, &blocks[*index].name))
|
||||
.collect();
|
||||
let work_uses: HashSet<String> = work_nodes
|
||||
.iter()
|
||||
.flat_map(|index| {
|
||||
blocks[*index]
|
||||
.typed
|
||||
.as_ref()
|
||||
.expect("carrier")
|
||||
.insts
|
||||
.iter()
|
||||
.flat_map(|inst| inst.uses.clone())
|
||||
})
|
||||
.collect();
|
||||
let mut work_uses = HashSet::new();
|
||||
for index in &work_nodes {
|
||||
for inst in &blocks[*index].typed.as_ref().expect("carrier").insts {
|
||||
inst.visit_uses(|name| {
|
||||
work_uses.insert(name.to_string());
|
||||
});
|
||||
}
|
||||
}
|
||||
for inst in &header_carrier.insts {
|
||||
let (Some(result), Some(ty)) = (&inst.result, &inst.result_ty) else {
|
||||
continue;
|
||||
@@ -536,8 +532,8 @@ fn regional_candidate(witness: Witness) -> Result<Vec<BodyBlock>, String> {
|
||||
.filter_map(|inst| {
|
||||
Some((
|
||||
inst.result.clone()?,
|
||||
inst.phi_incoming.as_ref()?.0.clone(),
|
||||
inst.phi_incoming.as_ref()?.1.clone(),
|
||||
inst.phi_incoming().as_ref()?.0.clone(),
|
||||
inst.phi_incoming().as_ref()?.1.clone(),
|
||||
))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
@@ -13,7 +13,7 @@ use super::*;
|
||||
/// private, `M`-dominated merge (inserted afterward by [`unique_selection_merges`]) while outer edges
|
||||
/// keep flowing through the untouched original exit. A non-cloneable region (multiple reconvergence
|
||||
/// boundaries, an in-region back-edge, or oversize) leaves the graph unchanged — the plan then honestly
|
||||
/// rejects and falls to repair, so this is floor-safe.
|
||||
/// rejects and falls to the relooper retry, so this is floor-safe.
|
||||
pub(in crate::native) fn privatize_dispatch_shared_exits(
|
||||
blocks: &mut Vec<BodyBlock>,
|
||||
dispatch: &str,
|
||||
@@ -86,7 +86,7 @@ pub(in crate::native) fn split_phi_overlap(
|
||||
let mut exit_rewrites: Vec<(String, TypedIncomings)> = Vec::new();
|
||||
if let Some(t) = &blocks[exit_idx].typed {
|
||||
for inst in &t.insts {
|
||||
let (Some(dst), Some((ty, inc))) = (inst.result.clone(), inst.phi_incoming.clone())
|
||||
let (Some(dst), Some((ty, inc))) = (inst.result.clone(), inst.phi_incoming().clone())
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Byte-neutral responsibility split of the former monolith; see the parent module.
|
||||
|
||||
use super::*;
|
||||
use crate::native::cfg::loopforest::post_idom;
|
||||
|
||||
/// Synthesized pass-through merge-block name prefix (kept distinct from any AIR label).
|
||||
pub(in crate::native) const SPLIT_PREFIX: &str = "%metal2vulkan.lmerge.";
|
||||
@@ -58,8 +59,8 @@ pub(in crate::native) fn role_for_name(name: &str) -> BlockRole {
|
||||
}
|
||||
|
||||
/// Full structured plan for a function: forest-augmented, structured-ordered blocks plus the
|
||||
/// loop/branch/switch merge maps consumed by emission. The retained-module cleanup remains part of
|
||||
/// the production pipeline after this primary by-construction plan.
|
||||
/// loop/branch/switch merge maps consumed by emission. Instruction-local emission preserves this
|
||||
/// source CFG's edge identities through its real emitted block exits.
|
||||
pub(in crate::native) struct StructuredPlan {
|
||||
pub(in crate::native) blocks: Vec<BodyBlock>,
|
||||
pub(in crate::native) loop_merges: HashMap<String, LoopMergeInfo>,
|
||||
@@ -74,7 +75,7 @@ pub(in crate::native) struct StructuredPlan {
|
||||
/// loop merges + merge==continue split), `unique_selection_merges` (module 2: per-construct selection
|
||||
/// merges), and `structured_order` (module 1: dominator-tree, merge-last ordering). When `Some`, every
|
||||
/// loop and every conditional/switch header has a unique merge, so the emitter emits a complete
|
||||
/// structured CFG; the kept post-hoc repair then normalizes rather than repairs.
|
||||
/// structured CFG without a retained-module control-flow rewrite.
|
||||
/// Block-count ceiling for the cross-arm-EDGE machinery (self-check 3 + the 9th-attempt clone). A pure
|
||||
/// PERFORMANCE bound for cross-arm cloning and its repeated planner invocations. The final
|
||||
/// cross-arm correctness check itself is never size-gated: a large function must reject an invalid
|
||||
@@ -85,7 +86,7 @@ pub(in crate::native) const CROSS_ARM_EDGE_MAX_BLOCKS: usize = 300;
|
||||
/// Reject-only loop-exit selection planning is intentionally bounded to modest CFGs. It walks a
|
||||
/// candidate's complete in-loop region to prove that every path either reaches the candidate or exits
|
||||
/// through an enclosing loop role; the bound keeps that proof from becoming a quadratic retry cost on
|
||||
/// giant descriptor-index functions. A skipped graph follows the existing repair path unchanged.
|
||||
/// giant descriptor-index functions. A skipped graph follows the existing relooper retry path.
|
||||
pub(in crate::native) const LOOP_EXIT_SELECTION_MAX_BLOCKS: usize = 300;
|
||||
|
||||
/// Merge-preserving region-cross-arm planning is also bounded to modest CFGs in the default ladder.
|
||||
@@ -106,16 +107,31 @@ pub(in crate::native) const SHARED_CONTINUATION_LADDER_MAX_BLOCKS: usize = 300;
|
||||
/// Selection-merge synthesis can turn compact straight-line decision trees into hundreds of
|
||||
/// `%metal2vulkan.lmerge.sel*` pass-through blocks. Keep a fixed allowance for modest CFGs and a
|
||||
/// one-block-per-source-block allowance for generated CFGs: a large function can legitimately need
|
||||
/// more than 300 private selection merges, while superlinear growth still indicates a runaway retry.
|
||||
/// more than 300 private selection merges, while superlinear growth still indicates runaway construction.
|
||||
pub(in crate::native) const SELECTION_SYNTH_GROWTH_MAX_BLOCKS: usize = 300;
|
||||
|
||||
/// Hard ceiling for the source-CFG structured planner. The ordinary reject path emits inferred merges
|
||||
/// and lets the retry cascade's relooper tiers rebuild control flow; on massive functions, proving that
|
||||
/// the structured planner cannot help can cost minutes before reaching that same path. This bound is
|
||||
/// deliberately far above the targeted retry caps so normal and moderately large CFGs still get the
|
||||
/// full ladder.
|
||||
/// Hard ceiling for the source-CFG structured planner. A rejection selects raw-CFG construction;
|
||||
/// on massive functions, proving that the local planner cannot help can cost minutes before reaching
|
||||
/// that representation. This bound remains far above the local construction caps.
|
||||
pub(in crate::native) const STRUCTURED_PLAN_MAX_BLOCKS: usize = 3000;
|
||||
|
||||
/// Bound repeated local-planner work by graph shape, not only by block count. The attempt ladder
|
||||
/// recomputes ownership for each branching header; dense generated CFGs below the block ceiling can
|
||||
/// otherwise exceed the end-to-end translation budget before reaching the linear whole-CFG owner.
|
||||
const LOCAL_STRUCTURED_PLAN_WORK_BUDGET: usize = 4096;
|
||||
const LOCAL_STRUCTURED_PLAN_MAX_BLOCKS: usize = 128;
|
||||
|
||||
pub(in crate::native) fn exceeds_local_structured_plan_budget(blocks: &[BodyBlock]) -> bool {
|
||||
if blocks.len() > LOCAL_STRUCTURED_PLAN_MAX_BLOCKS {
|
||||
return true;
|
||||
}
|
||||
let branching = blocks
|
||||
.iter()
|
||||
.filter(|block| block_successors(block).len() > 1)
|
||||
.count();
|
||||
blocks.len().saturating_mul(branching.max(1)) > LOCAL_STRUCTURED_PLAN_WORK_BUDGET
|
||||
}
|
||||
|
||||
/// Whether a structural retry actually changed its source CFG. `BodyBlock` deliberately does not need
|
||||
/// a public `PartialEq`; the planner only needs this local name/carrier comparison to distinguish a
|
||||
/// forced lowering that preserves block count (for example an empty switch) from a true no-op. The
|
||||
@@ -131,6 +147,65 @@ pub(in crate::native) fn blocks_changed(before: &[BodyBlock], after: &[BodyBlock
|
||||
.any(|(left, right)| left.name != right.name || block_body_changed(left, right))
|
||||
}
|
||||
|
||||
/// Whether a natural loop is entered from both inside and outside a still-open nested selection.
|
||||
/// Such a selection cannot reconverge before the loop: one arm enters the shared loop while another
|
||||
/// path that the selection does not own enters the same header. The loop region therefore needs
|
||||
/// whole-CFG ownership construction before merge assignment; assigning a private selection merge on
|
||||
/// the unowned shared loop produces a live path that bypasses that merge.
|
||||
pub(in crate::native) fn requires_shared_loop_entry_ownership(blocks: &[BodyBlock]) -> bool {
|
||||
let forest = analyze(blocks);
|
||||
let post_idoms = post_idom(blocks);
|
||||
let mut predecessors = HashMap::<String, Vec<&str>>::new();
|
||||
for block in blocks {
|
||||
for successor in block_successors(block) {
|
||||
predecessors
|
||||
.entry(successor)
|
||||
.or_default()
|
||||
.push(block.name.as_str());
|
||||
}
|
||||
}
|
||||
for loop_info in &forest.loops {
|
||||
let loop_body = loop_info
|
||||
.body
|
||||
.iter()
|
||||
.map(String::as_str)
|
||||
.collect::<HashSet<_>>();
|
||||
let forward_predecessors = predecessors
|
||||
.get(loop_info.header.as_str())
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.copied()
|
||||
.filter(|predecessor| !loop_body.contains(predecessor))
|
||||
.collect::<Vec<_>>();
|
||||
if forward_predecessors.len() < 2 {
|
||||
continue;
|
||||
}
|
||||
for header in blocks {
|
||||
if conditional_branch_targets(header).is_none() {
|
||||
continue;
|
||||
}
|
||||
let Some(natural_merge) = post_idoms.get(&header.name) else {
|
||||
continue;
|
||||
};
|
||||
let owned = forward_predecessors
|
||||
.iter()
|
||||
.filter(|predecessor| forest.dominates(&header.name, predecessor))
|
||||
.copied()
|
||||
.collect::<Vec<_>>();
|
||||
if owned.is_empty() || owned.len() == forward_predecessors.len() {
|
||||
continue;
|
||||
}
|
||||
if owned
|
||||
.iter()
|
||||
.any(|predecessor| !forest.dominates(natural_merge, predecessor))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn block_body_changed(left: &BodyBlock, right: &BodyBlock) -> bool {
|
||||
match (&left.typed, &right.typed) {
|
||||
(Some(l), Some(r)) => format!("{l:?}") != format!("{r:?}"),
|
||||
@@ -153,10 +228,10 @@ pub(in crate::native) fn structured_plan(blocks: &[BodyBlock]) -> Option<Structu
|
||||
let deep_shared = privatize_shared_continuations_for_ladder(blocks);
|
||||
if deep_shared.len() != blocks.len() {
|
||||
if let Some(plan) = structured_plan_ladder(&deep_shared, false) {
|
||||
return Some(plan);
|
||||
return finalize_loop_role_switches(plan);
|
||||
}
|
||||
if let Some(plan) = structured_plan_ladder(&deep_shared, true) {
|
||||
return Some(plan);
|
||||
return finalize_loop_role_switches(plan);
|
||||
}
|
||||
}
|
||||
// The helper returns an owned no-op clone when no ladder repair applies. Do not retain that
|
||||
@@ -175,18 +250,18 @@ pub(in crate::native) fn structured_plan(blocks: &[BodyBlock]) -> Option<Structu
|
||||
// residual latch. The second pass is byte-neutral for admitting functions (never reached) and its only
|
||||
// new admissions are functions that today fall through to the fallback.
|
||||
if blocks.len() > TERMINAL_EXIT_SELECTION_MAX_BLOCKS {
|
||||
// Large generated CFGs go directly to the whole-CFG construct-tree/relooper fallback.
|
||||
// Large generated CFGs go directly to the whole-CFG construct-tree planner in the emitter.
|
||||
// Even one speculative source-CFG candidate can coexist with the fallback's ownership graph
|
||||
// long enough to exceed the per-translation live-memory budget. The global path is the only
|
||||
// tier capable of resolving compound straddle/cross-arm ownership anyway, so a preliminary
|
||||
// planner capable of resolving compound straddle/cross-arm ownership anyway, so a preliminary
|
||||
// local candidate adds cost without broadening support.
|
||||
return None;
|
||||
} else {
|
||||
if let Some(plan) = structured_plan_ladder(blocks, false) {
|
||||
return Some(plan);
|
||||
return finalize_loop_role_switches(plan);
|
||||
}
|
||||
if let Some(plan) = structured_plan_ladder(blocks, true) {
|
||||
return Some(plan);
|
||||
return finalize_loop_role_switches(plan);
|
||||
}
|
||||
}
|
||||
// Reject-only shared-merge separation: when divergent return-like exits are the structural reason
|
||||
@@ -195,11 +270,44 @@ pub(in crate::native) fn structured_plan(blocks: &[BodyBlock]) -> Option<Structu
|
||||
// structurable; a function that merely contains multiple returns but still rejects is untouched.
|
||||
// An already-admitted function never reaches this construction.
|
||||
if let Some(plan) = structured_plan_divergent_exit(blocks) {
|
||||
return Some(plan);
|
||||
return finalize_loop_role_switches(plan);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// A source-valid switch may branch directly to an enclosing loop's continue/merge role while
|
||||
/// another arm remains in the loop. Source dominance can admit that graph, but SPIR-V case
|
||||
/// constructs cannot borrow an enclosing loop-role block. Inspect the completed ownership map
|
||||
/// cheaply and pay for loop analysis/lowering only when a switch actually targets one of its roles.
|
||||
fn finalize_loop_role_switches(plan: StructuredPlan) -> Option<StructuredPlan> {
|
||||
if plan.blocks.len() > LOOP_EXIT_SELECTION_MAX_BLOCKS {
|
||||
return Some(plan);
|
||||
}
|
||||
let loop_roles = plan
|
||||
.loop_merges
|
||||
.values()
|
||||
.flat_map(|info| [&info.merge, &info.continue_target])
|
||||
.collect::<HashSet<_>>();
|
||||
let targets_loop_role = plan.blocks.iter().any(|block| {
|
||||
block.typed.as_ref().is_some_and(|typed| {
|
||||
matches!(
|
||||
typed.terminator,
|
||||
crate::native::tir::TirTerminator::Switch { .. }
|
||||
) && block_successors(block)
|
||||
.iter()
|
||||
.any(|target| loop_roles.contains(target))
|
||||
})
|
||||
});
|
||||
if !targets_loop_role {
|
||||
return Some(plan);
|
||||
}
|
||||
let lowered_switches = super::blocks::lower_loop_exit_switches(&plan.blocks);
|
||||
if !blocks_changed(&plan.blocks, &lowered_switches) {
|
||||
return Some(plan);
|
||||
}
|
||||
structured_plan(&lowered_switches)
|
||||
}
|
||||
|
||||
/// Final reject-only construction for divergent function exits. Return unification creates the common
|
||||
/// post-dominator. If that phi-carrying exit is still shared with enclosing paths, clone only its
|
||||
/// immediate shared predecessors for the nested entries; the ordinary ladder can then synthesize each
|
||||
@@ -309,7 +417,7 @@ pub(in crate::native) fn structured_plan_ladder(
|
||||
// cross-arm attempts could NOT structure reach here, so this is byte-identical for every currently-
|
||||
// admitting function; it rescues the dominant `cond-phi-shared/loop-role/merge-inloop` class (07 and
|
||||
// the 107-fn bucket) by giving a loop a distinct merge when an IN-LOOP selection shares it. Floor-safe:
|
||||
// the retry cascade adopts the resulting plan only if it independently spirv-val-passes.
|
||||
// the resulting plan is admitted only after the planner's structural self-check.
|
||||
if let Some(plan) = structured_plan_inner4(blocks, true, false, false, allow_bare_exit) {
|
||||
return Some(plan);
|
||||
}
|
||||
@@ -349,7 +457,7 @@ pub(in crate::native) fn structured_plan_ladder(
|
||||
// whose case-construct dominance the source-CFG self-check cannot verify (source-CFG dominance ≠
|
||||
// emitted structural dominance — dead-end #6) can emit invalid SPIR-V that the retry path would
|
||||
// otherwise handle validly (`Switch header does not structurally dominate its case construct`,
|
||||
// banked `02/387ebaa9` family). Leave only genuine multi-level-break switches to the repair path:
|
||||
// banked `02/387ebaa9` family). Leave only genuine multi-level-break switches to the relooper retry:
|
||||
// the M1b default (`switch_gate_excludes`) excludes just an in-loop switch with a loop-exiting arm;
|
||||
// a loop-free switch (or an in-loop switch whose arms all stay in the loop) is safe to admit.
|
||||
if switch_gate_excludes(blocks) {
|
||||
@@ -368,8 +476,8 @@ pub(in crate::native) fn structured_plan_ladder(
|
||||
// fixing the reject at its SOURCE (unlike LOOP_BREAK_PROTECT, which kept the break edge into the
|
||||
// claimed loop merge and over-admitted into `branches to the selection construct` invalidity;
|
||||
// dead-end #19). Reached ONLY after all four prior attempts reject, so every currently-admitting
|
||||
// function stays byte-identical; floor-safe since the retry cascade adopts the plan only if it
|
||||
// independently spirv-val-passes.
|
||||
// function stays byte-identical; the resulting plan is admitted only after its structural
|
||||
// self-check.
|
||||
if let Some(plan) = structured_plan_inner4(blocks, true, true, false, allow_bare_exit) {
|
||||
return Some(plan);
|
||||
}
|
||||
@@ -463,7 +571,7 @@ pub(in crate::native) fn structured_plan_ladder(
|
||||
// guard AND (for the `590c6cf2` shape) the region-cross-arm pre-pass privatizes the enclosing
|
||||
// selection, so the clone is retried across the same pre-pass combos the ladder uses. The plan
|
||||
// self-checks inside `structured_plan_inner4` still gate admission; the switch guard keeps the
|
||||
// dead-end #6 multi-level-break switches on the repair path.
|
||||
// dead-end #6 multi-level-break switches on the relooper retry path.
|
||||
if !switch_gate_excludes(blocks) {
|
||||
for &(bl, cv, br) in &[
|
||||
(blocks, force_converge, false),
|
||||
@@ -490,7 +598,7 @@ pub(in crate::native) fn structured_plan_ladder(
|
||||
// destraddled graph re-runs the inner ladder (base -> converge -> converge+break-aware). Reached
|
||||
// ONLY after every prior attempt rejects, so a currently-admitting function stays byte-identical; the
|
||||
// plan self-checks (including the cross-arm-edge self-check itself) still gate admission of the
|
||||
// cloned graph, so an unfixable residue rejects honestly and falls to repair.
|
||||
// cloned graph, so an unfixable residue rejects honestly and falls to the relooper retry.
|
||||
if blocks.len() <= CROSS_ARM_EDGE_MAX_BLOCKS {
|
||||
let cloned = super::clone_crossarm::privatize_cross_arm_edge(blocks);
|
||||
if cloned.len() != blocks.len() && cloned.len() <= CROSS_ARM_EDGE_MAX_BLOCKS {
|
||||
|
||||
@@ -34,9 +34,27 @@ pub(in crate::native) fn plan_self_check_reason(
|
||||
// not (the header sits between CH and CM). If the loop's own merge ML is then dominated by CM — it
|
||||
// lands at/after the construct's merge — the construct boundaries invert: CM branches back into the
|
||||
// loop's merge, and the structured emitter produces "branches to / exits the selection construct,
|
||||
// but not via the header" rejects (a previously observed module shape). The kept repair path structures
|
||||
// but not via the header" rejects (a previously observed module shape). The relooper retry structures
|
||||
// these correctly, so reject and fall back rather than emit invalid SPIR-V.
|
||||
let plan_forest = analyze(ordered);
|
||||
// Every dominance back-edge must target a header that the emitted plan owns as a loop. A
|
||||
// construct-tree rewrite can preserve a source back-edge while losing that ownership; emitting
|
||||
// it as an ordinary branch produces a SPIR-V back-edge to a non-loop header.
|
||||
for block in ordered {
|
||||
for successor in block_successors(block) {
|
||||
if plan_forest.dominates(&successor, &block.name)
|
||||
&& !loop_merges.contains_key(&successor)
|
||||
{
|
||||
if crate::env_vars::spi_why() {
|
||||
eprintln!(
|
||||
"[spi-why] backedge-target-unowned block={} -> {}",
|
||||
block.name, successor,
|
||||
);
|
||||
}
|
||||
return Some("loop:backedge-target-unowned");
|
||||
}
|
||||
}
|
||||
}
|
||||
for l in &plan_forest.loops {
|
||||
let Some(info) = loop_merges.get(&l.header) else {
|
||||
continue;
|
||||
@@ -69,8 +87,8 @@ pub(in crate::native) fn plan_self_check_reason(
|
||||
// loop) MUST be dominated by the header — i.e. private to that arm. When an arm jumps to a block
|
||||
// reached from OUTSIDE the construct too, the shared block is not dominated by any one header and
|
||||
// lands after that header's merge in emission order, so the header "exits the selection ... but not
|
||||
// via a structured exit". Structured SPIR-V needs the shared block CLONED per level, which the kept
|
||||
// repair path does; reject and fall back. Two shapes hit this:
|
||||
// via a structured exit". Structured SPIR-V needs the shared block CLONED per level; reject so the
|
||||
// whole-CFG retry can rebuild it. Two shapes hit this:
|
||||
// - conditionals: a short-circuit `a || b || c` ladder funnels every condition's taken-arm into
|
||||
// one shared block (a previously observed module shape).
|
||||
// - switches: a `switch` case/default target is a SIBLING arm of an enclosing selection (banked
|
||||
@@ -93,11 +111,54 @@ pub(in crate::native) fn plan_self_check_reason(
|
||||
let is_enclosing_break = |b: &str, a: &str| -> bool {
|
||||
plan_forest.loops.iter().any(|l| {
|
||||
l.body.iter().any(|n| n == b)
|
||||
&& loop_merges
|
||||
.get(&l.header)
|
||||
.is_some_and(|i| i.merge == a || i.continue_target == a)
|
||||
&& (l.header == a
|
||||
|| loop_merges
|
||||
.get(&l.header)
|
||||
.is_some_and(|i| i.merge == a || i.continue_target == a))
|
||||
})
|
||||
};
|
||||
|
||||
// A child selection merge remains inside every enclosing selection until it reaches each
|
||||
// enclosing selection's own merge. An inner merge may not jump directly to a more distant
|
||||
// selection merge: SPIR-V does not treat that as a structured break. Other internal edges retain
|
||||
// the established construct-tree bare-loop-role handling.
|
||||
let selection_merges = header_merge
|
||||
.values()
|
||||
.map(String::as_str)
|
||||
.collect::<HashSet<_>>();
|
||||
for block in ordered {
|
||||
if !selection_merges.contains(block.name.as_str()) {
|
||||
continue;
|
||||
}
|
||||
for successor in block_successors(block) {
|
||||
let mut owner = Some(block.name.as_str());
|
||||
while let Some(header) = owner {
|
||||
let Some(merge) = header_merge.get(header) else {
|
||||
owner = plan_forest.idom(header);
|
||||
continue;
|
||||
};
|
||||
if plan_loop_headers.contains(header) || plan_forest.dominates(merge, &block.name) {
|
||||
owner = plan_forest.idom(header);
|
||||
continue;
|
||||
}
|
||||
let remains_inside = plan_forest.dominates(header, &successor)
|
||||
&& !plan_forest.dominates(merge, &successor);
|
||||
if successor != *merge
|
||||
&& !remains_inside
|
||||
&& !is_enclosing_break(&block.name, &successor)
|
||||
{
|
||||
if crate::env_vars::spi_why() {
|
||||
eprintln!(
|
||||
"[spi-why] nested-exit-bypass header={} merge={} block={} -> {}",
|
||||
header, merge, block.name, successor,
|
||||
);
|
||||
}
|
||||
return Some("selection:nested-exit-bypass");
|
||||
}
|
||||
owner = plan_forest.idom(header);
|
||||
}
|
||||
}
|
||||
}
|
||||
for b in ordered {
|
||||
if plan_loop_headers.contains(b.name.as_str()) {
|
||||
continue;
|
||||
@@ -109,7 +170,7 @@ pub(in crate::native) fn plan_self_check_reason(
|
||||
// merge-assignment picked a block shared with an ENCLOSING construct's arm — so an outer branch
|
||||
// reaches it directly without passing through this header — the header does not dominate it and
|
||||
// the selection/switch "exits the selection ... but not via a structured exit" (banked
|
||||
// `e848bc87`/`72cbab44`). The repair path re-nests these; reject and fall back.
|
||||
// `e848bc87`/`72cbab44`). The whole-CFG retry re-nests these; reject and fall back.
|
||||
let unreachable_terminal_merge = ordered
|
||||
.iter()
|
||||
.find(|block| block.name == *m)
|
||||
@@ -209,6 +270,7 @@ pub(in crate::native) fn plan_self_check_reason(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
@@ -1224,7 +1286,7 @@ pub(in crate::native) fn reject_reason_inner(blocks: &[BodyBlock]) -> Option<Str
|
||||
// All merge-synthesis gates passed (every header has a unique merge) — `structured_plan` would now
|
||||
// reach its two plan self-checks. Rebuild the same header→merge map + structured order and run them
|
||||
// via the shared helper, so a function rejected ONLY by a self-check is reported here too (else it
|
||||
// mis-reports as ADMIT while emission falls back to the repair path).
|
||||
// mis-reports as ADMIT while emission falls back to the relooper retry).
|
||||
let mut header_merge: HashMap<String, String> = HashMap::new();
|
||||
for (h, info) in &loop_merges {
|
||||
header_merge.insert(h.clone(), info.merge.clone());
|
||||
@@ -1310,6 +1372,61 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plan_self_check_rejects_child_merge_bypassing_parent_selection_merge() {
|
||||
let blocks = vec![
|
||||
bb(
|
||||
"%outer",
|
||||
BlockRole::Normal,
|
||||
&["br i1 %a, label %nested, label %live"],
|
||||
),
|
||||
bb(
|
||||
"%nested",
|
||||
BlockRole::Normal,
|
||||
&["br i1 %b, label %inner, label %nested_merge"],
|
||||
),
|
||||
bb(
|
||||
"%inner",
|
||||
BlockRole::Normal,
|
||||
&["br i1 %c, label %work, label %nested_merge"],
|
||||
),
|
||||
bb("%work", BlockRole::Normal, &["br label %inner_merge"]),
|
||||
bb("%inner_merge", BlockRole::LMerge, &["br label %done"]),
|
||||
bb("%nested_merge", BlockRole::LMerge, &["br label %live"]),
|
||||
bb("%live", BlockRole::Normal, &["br label %done"]),
|
||||
bb("%done", BlockRole::Normal, &["ret void"]),
|
||||
];
|
||||
let header_merges = HashMap::from([
|
||||
("%outer".to_string(), "%done".to_string()),
|
||||
("%nested".to_string(), "%nested_merge".to_string()),
|
||||
("%inner".to_string(), "%inner_merge".to_string()),
|
||||
]);
|
||||
|
||||
assert_eq!(
|
||||
plan_self_check_reason(&blocks, &header_merges, &HashMap::new()),
|
||||
Some("selection:nested-exit-bypass")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plan_self_check_rejects_backedge_without_loop_header_ownership() {
|
||||
let blocks = vec![
|
||||
bb("%entry", BlockRole::Normal, &["br label %header"]),
|
||||
bb(
|
||||
"%header",
|
||||
BlockRole::Normal,
|
||||
&["br i1 %condition, label %body, label %exit"],
|
||||
),
|
||||
bb("%body", BlockRole::Normal, &["br label %header"]),
|
||||
bb("%exit", BlockRole::Normal, &["ret void"]),
|
||||
];
|
||||
|
||||
assert_eq!(
|
||||
plan_self_check_reason(&blocks, &HashMap::new(), &HashMap::new()),
|
||||
Some("loop:backedge-target-unowned")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cond_other_target_role_reports_synthetic_loop_routes() {
|
||||
let blocks = vec![
|
||||
|
||||
@@ -190,15 +190,23 @@ pub(in crate::native) fn refine_nested_terminal_selection_merges(
|
||||
.collect::<Vec<_>>();
|
||||
enclosing.sort_by_key(|(loop_info, _)| loop_info.body.len());
|
||||
if enclosing.is_empty() {
|
||||
// A loop-free guard can return through the same block used as a later loop's exit. The
|
||||
// convergence candidate on its live arm is real, but recording it directly leaves the
|
||||
// shared return inside two structural owners. The terminal planner owns the required
|
||||
// edge split: it first gives the loop a private return, then gives this guard a private
|
||||
// merge. Decline here so that ownership-producing path runs instead of admitting an
|
||||
// unmodified graph that spirv-val rejects as re-entering a selection construct.
|
||||
if let Some(candidate) = terminal_exit_convergence(blocks, forest, &header) {
|
||||
selection_merges.insert(header.clone(), candidate.clone());
|
||||
if crate::env_vars::spi_why() {
|
||||
eprintln!(
|
||||
"[spi-why] terminal-convergence header={} merge={}",
|
||||
header, candidate,
|
||||
);
|
||||
if !terminal_arm_enters_loop_with_shared_exit(blocks, forest, &header, &candidate) {
|
||||
selection_merges.insert(header.clone(), candidate.clone());
|
||||
if crate::env_vars::spi_why() {
|
||||
eprintln!(
|
||||
"[spi-why] terminal-convergence header={} merge={}",
|
||||
header, candidate,
|
||||
);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
for (loop_info, info) in enclosing {
|
||||
@@ -273,6 +281,53 @@ pub(in crate::native) fn refine_nested_terminal_selection_merges(
|
||||
}
|
||||
}
|
||||
|
||||
fn terminal_arm_enters_loop_with_shared_exit(
|
||||
blocks: &[BodyBlock],
|
||||
forest: &LoopForest,
|
||||
header: &str,
|
||||
live_convergence: &str,
|
||||
) -> bool {
|
||||
let Some((left, right)) = blocks
|
||||
.iter()
|
||||
.find(|block| block.name == header)
|
||||
.and_then(conditional_branch_targets)
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
[left, right].into_iter().any(|arm| {
|
||||
terminal_exit_arm(blocks, forest, header, &arm).is_some_and(|terminal| {
|
||||
forest.loops.iter().any(|loop_info| {
|
||||
loop_info
|
||||
.exits
|
||||
.iter()
|
||||
.any(|exit| exit == &terminal.return_block)
|
||||
&& block_reaches(blocks, live_convergence, &loop_info.header)
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn block_reaches(blocks: &[BodyBlock], start: &str, target: &str) -> bool {
|
||||
let by_name = blocks
|
||||
.iter()
|
||||
.map(|block| (block.name.as_str(), block))
|
||||
.collect::<HashMap<_, _>>();
|
||||
let mut seen = HashSet::new();
|
||||
let mut pending = vec![start.to_string()];
|
||||
while let Some(current) = pending.pop() {
|
||||
if current == target {
|
||||
return true;
|
||||
}
|
||||
if !seen.insert(current.clone()) {
|
||||
continue;
|
||||
}
|
||||
if let Some(block) = by_name.get(current.as_str()) {
|
||||
pending.extend(block_successors(block));
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Re-run terminal convergence after construct-tree edge splits have exposed an enclosing
|
||||
/// continuation that was not provable in the source CFG.
|
||||
///
|
||||
@@ -284,6 +339,7 @@ pub(in crate::native) fn refine_nested_terminal_selection_merges(
|
||||
/// absent and therefore falls back rather than weakening structured-CFG ownership. A header that
|
||||
/// already had a source-time natural merge is also excluded: failure to synthesize that merge is a
|
||||
/// collision-repair problem, not evidence that it became a terminal selection.
|
||||
#[cfg(test)]
|
||||
pub(in crate::native) fn complete_construct_tree_terminal_convergences(
|
||||
blocks: &[BodyBlock],
|
||||
loop_merges: &HashMap<String, LoopMergeInfo>,
|
||||
@@ -652,7 +708,7 @@ pub(in crate::native) fn synth_unique_selection_merge_phi_explicit(
|
||||
let mut nat_rewrites: Vec<(String, TypedIncomings)> = Vec::new();
|
||||
if let Some(t) = &blocks[nat_idx].typed {
|
||||
for inst in &t.insts {
|
||||
let (Some(dst), Some((ty, inc))) = (inst.result.clone(), inst.phi_incoming.clone())
|
||||
let (Some(dst), Some((ty, inc))) = (inst.result.clone(), inst.phi_incoming().clone())
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
@@ -953,7 +1009,7 @@ pub(in crate::native) fn split_loop_header_selection(
|
||||
/// header (its merge resolved by [`unique_selection_merges`]' switch path). Phi incomings in the
|
||||
/// case/default targets that named the header as predecessor are rewired to the new block. Returns the
|
||||
/// new block's name, or `None` if the header is not this shape — any switch target being the loop's
|
||||
/// merge/continue/header is a structured break/continue switch, left to the kept repair path (and still
|
||||
/// merge/continue/header is a structured break/continue switch, left to the relooper retry (and still
|
||||
/// rejected by `structured_plan`'s loop-header-switch gate, which now fires only on that residue).
|
||||
pub(in crate::native) fn split_loop_header_switch(
|
||||
blocks: &mut Vec<BodyBlock>,
|
||||
@@ -1144,12 +1200,13 @@ pub(in crate::native) fn bare_natural_loop_exit_branch(
|
||||
}
|
||||
|
||||
/// Return the first target outside `b`'s dominated region that is still inside an enclosing
|
||||
/// construct-tree selection region. The caller uses this as a continuation split point: the nested
|
||||
/// branch remains a structured selection by merging at a private pass-through before that shared
|
||||
/// continuation, instead of emitting a bare conditional.
|
||||
/// selection region. The caller uses this as a continuation split point: the nested branch remains
|
||||
/// a structured selection by merging at a private pass-through before that shared continuation,
|
||||
/// instead of emitting a bare conditional.
|
||||
pub(in crate::native) fn enclosing_selection_region_exit_target(
|
||||
blocks: &[BodyBlock],
|
||||
forest: &LoopForest,
|
||||
loop_merges: &HashMap<String, LoopMergeInfo>,
|
||||
selection_merges: &HashMap<String, String>,
|
||||
b: &str,
|
||||
t: &str,
|
||||
@@ -1169,6 +1226,7 @@ pub(in crate::native) fn enclosing_selection_region_exit_target(
|
||||
if let Some(exit) = first_enclosing_selection_region_exit(
|
||||
blocks,
|
||||
forest,
|
||||
loop_merges,
|
||||
selection_merges,
|
||||
b,
|
||||
target,
|
||||
@@ -1183,6 +1241,7 @@ pub(in crate::native) fn enclosing_selection_region_exit_target(
|
||||
fn first_enclosing_selection_region_exit(
|
||||
blocks: &[BodyBlock],
|
||||
forest: &LoopForest,
|
||||
loop_merges: &HashMap<String, LoopMergeInfo>,
|
||||
selection_merges: &HashMap<String, String>,
|
||||
b: &str,
|
||||
target: &str,
|
||||
@@ -1209,6 +1268,9 @@ fn first_enclosing_selection_region_exit(
|
||||
if merge.is_some_and(|merge| successor == merge) {
|
||||
continue;
|
||||
}
|
||||
if legal_enclosing_loop_exit(forest, loop_merges, &node, &successor) {
|
||||
continue;
|
||||
}
|
||||
if forest.dominates(b, &successor) {
|
||||
stack.push(successor);
|
||||
} else if exits_to_enclosing_selection_region(
|
||||
@@ -1226,6 +1288,117 @@ fn first_enclosing_selection_region_exit(
|
||||
None
|
||||
}
|
||||
|
||||
fn legal_enclosing_loop_exit(
|
||||
forest: &LoopForest,
|
||||
loop_merges: &HashMap<String, LoopMergeInfo>,
|
||||
source: &str,
|
||||
target: &str,
|
||||
) -> bool {
|
||||
forest.loops.iter().any(|loop_info| {
|
||||
let encloses =
|
||||
loop_info.header == source || loop_info.body.iter().any(|name| name == source);
|
||||
encloses
|
||||
&& (loop_info.header == target
|
||||
|| loop_merges
|
||||
.get(&loop_info.header)
|
||||
.is_some_and(|info| info.merge == target || info.continue_target == target))
|
||||
})
|
||||
}
|
||||
|
||||
/// Identify the one exact enclosing boundary crossed by an ordinary selection's owned source
|
||||
/// region. Unlike the construct-tree sibling-region query, this declines loop-role branches,
|
||||
/// conditional latches, terminal declarations, and regions with multiple distinct escapes. The
|
||||
/// ordinary planner can therefore materialize the returned boundary while processing the header,
|
||||
/// without revisiting or mutating already-constructed selections afterward.
|
||||
pub(in crate::native) fn ordinary_selection_enclosing_boundary_target(
|
||||
blocks: &[BodyBlock],
|
||||
forest: &LoopForest,
|
||||
loop_merges: &HashMap<String, LoopMergeInfo>,
|
||||
source_selection_merges: &HashMap<String, String>,
|
||||
header: &str,
|
||||
merge: &str,
|
||||
) -> Option<String> {
|
||||
let by_name = blocks
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, block)| (block.name.clone(), index))
|
||||
.collect::<HashMap<_, _>>();
|
||||
let header_block = &blocks[*by_name.get(header)?];
|
||||
let (true_target, false_target) = conditional_branch_targets(header_block)?;
|
||||
if bare_loop_exit_branch_with_passthroughs(
|
||||
blocks,
|
||||
forest,
|
||||
loop_merges,
|
||||
header,
|
||||
&true_target,
|
||||
&false_target,
|
||||
) {
|
||||
return None;
|
||||
}
|
||||
let header_successors = block_successors(header_block);
|
||||
if forest.loops.iter().any(|loop_info| {
|
||||
loop_info.latches.iter().any(|latch| latch == header)
|
||||
&& header_successors
|
||||
.iter()
|
||||
.any(|successor| successor == &loop_info.header)
|
||||
}) {
|
||||
return None;
|
||||
}
|
||||
if by_name
|
||||
.get(merge)
|
||||
.map(|index| &blocks[*index])
|
||||
.is_some_and(is_bare_unreachable)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut seen = HashSet::new();
|
||||
let mut stack = header_successors
|
||||
.into_iter()
|
||||
.filter(|target| target != merge)
|
||||
.collect::<Vec<_>>();
|
||||
let mut boundary = None;
|
||||
while let Some(node) = stack.pop() {
|
||||
if node == merge || !seen.insert(node.clone()) {
|
||||
continue;
|
||||
}
|
||||
let Some(block) = by_name.get(node.as_str()).map(|index| &blocks[*index]) else {
|
||||
continue;
|
||||
};
|
||||
if !forest.dominates(header, &node) {
|
||||
continue;
|
||||
}
|
||||
for successor in block_successors(block) {
|
||||
if successor == merge
|
||||
|| legal_enclosing_loop_exit(forest, loop_merges, &node, &successor)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if forest.dominates(header, &successor) {
|
||||
stack.push(successor);
|
||||
continue;
|
||||
}
|
||||
if exits_to_enclosing_selection_region(
|
||||
blocks,
|
||||
forest,
|
||||
source_selection_merges,
|
||||
&by_name,
|
||||
&node,
|
||||
&successor,
|
||||
) {
|
||||
if boundary
|
||||
.as_ref()
|
||||
.is_some_and(|current: &String| current != &successor)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
boundary = Some(successor);
|
||||
}
|
||||
}
|
||||
}
|
||||
boundary
|
||||
}
|
||||
|
||||
fn dominated_region_exits(
|
||||
blocks: &[BodyBlock],
|
||||
forest: &LoopForest,
|
||||
@@ -1242,22 +1415,76 @@ fn dominated_region_exits(
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// After all innermost-first merge splits, repair any selection whose current region still exits to
|
||||
/// an enclosing selection merge before reaching the selection's own declared merge.
|
||||
/// Source owners whose construction can expose a nested selection with both arms routing into it.
|
||||
///
|
||||
/// The first-pass `enclosing_selection_region_exit_target` runs while header merges are still being
|
||||
/// assigned, so it cannot see private enclosing merges synthesized later in the same pass. Re-run the
|
||||
/// check on the final header->merge map: if an in-region block escapes to an enclosing selection's
|
||||
/// recorded merge/region, split that escape target and make the fresh pass-through this header's
|
||||
/// merge. Loop break/continue exits stay untouched.
|
||||
pub(in crate::native) fn repair_enclosing_selection_region_escapes(
|
||||
/// The ownership builder runs innermost-first, so the nested header is already registered when one
|
||||
/// of these enclosing owners is produced. Indexing that dependency on the immutable source CFG lets
|
||||
/// the enclosing producer finish only the routes it can unlock instead of revisiting the whole CFG
|
||||
/// after construction.
|
||||
#[derive(Default)]
|
||||
pub(in crate::native) struct PureEnclosingSelectionOwners {
|
||||
dependents_by_owner: HashMap<String, HashSet<String>>,
|
||||
}
|
||||
|
||||
pub(in crate::native) fn pure_enclosing_selection_owners(
|
||||
blocks: &[BodyBlock],
|
||||
forest: &LoopForest,
|
||||
source_selection_merges: &HashMap<String, String>,
|
||||
) -> PureEnclosingSelectionOwners {
|
||||
let by_name = blocks
|
||||
.iter()
|
||||
.map(|block| (block.name.as_str(), block))
|
||||
.collect::<HashMap<_, _>>();
|
||||
let mut dependents_by_owner: HashMap<String, HashSet<String>> = HashMap::new();
|
||||
for (header, merge) in source_selection_merges {
|
||||
let Some((left, right)) = by_name
|
||||
.get(header.as_str())
|
||||
.and_then(|block| conditional_branch_targets(block))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if (left == *merge) == (right == *merge) {
|
||||
continue;
|
||||
}
|
||||
let mut current = header.as_str();
|
||||
while let Some(parent) = forest.idom(current) {
|
||||
if source_selection_merges.contains_key(parent) {
|
||||
dependents_by_owner
|
||||
.entry(parent.to_string())
|
||||
.or_default()
|
||||
.insert(header.clone());
|
||||
}
|
||||
current = parent;
|
||||
}
|
||||
}
|
||||
PureEnclosingSelectionOwners {
|
||||
dependents_by_owner,
|
||||
}
|
||||
}
|
||||
|
||||
/// Materialize selections exposed by construction of one indexed enclosing owner.
|
||||
///
|
||||
/// Unique-merge synthesis can produce `H -> { shared, M -> outer-merge }`, where an enclosing sibling
|
||||
/// also enters `shared`. Treating H as a bare routing branch loses real conditional ownership and
|
||||
/// forces a later whole-CFG completeness sweep to rediscover H. When the indexed enclosing owner is
|
||||
/// registered, clone the shared arm for H,
|
||||
/// transfer every nested header's merge assignment through the clone's structural rename map, and
|
||||
/// refunnel H-owned predecessors into one private merge. Processing innermost-first means a later
|
||||
/// enclosing clone carries already-complete nested ownership with it.
|
||||
pub(in crate::native) fn materialize_pure_enclosing_selection_routes_for_owner(
|
||||
blocks: &mut Vec<BodyBlock>,
|
||||
loop_merges: &HashMap<String, LoopMergeInfo>,
|
||||
header_merges: &mut HashMap<String, String>,
|
||||
indexed_owners: &PureEnclosingSelectionOwners,
|
||||
owner: &str,
|
||||
counter: &mut usize,
|
||||
) -> bool {
|
||||
let mut any_repaired = false;
|
||||
let mut attempted = HashSet::<(String, String)>::new();
|
||||
let Some(dependents) = indexed_owners.dependents_by_owner.get(owner) else {
|
||||
return false;
|
||||
};
|
||||
let mut dependents = dependents.clone();
|
||||
let mut changed = false;
|
||||
let mut declined = HashSet::new();
|
||||
loop {
|
||||
let forest = analyze(blocks);
|
||||
let by_name = blocks
|
||||
@@ -1268,366 +1495,184 @@ pub(in crate::native) fn repair_enclosing_selection_region_escapes(
|
||||
let mut headers = header_merges
|
||||
.iter()
|
||||
.filter_map(|(header, merge)| {
|
||||
let block = &blocks[*by_name.get(header.as_str())?];
|
||||
dependents.contains(header).then_some(())?;
|
||||
(!declined.contains(header)).then_some(())?;
|
||||
let block = &blocks[*by_name.get(header)?];
|
||||
conditional_branch_targets(block)?;
|
||||
Some((header.clone(), merge.clone()))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
// The CFG can contain hundreds of nested selection headers. Cache the idom-chain depth once
|
||||
// per header; `sort_by_key` would recompute it for every comparison.
|
||||
headers.sort_by_cached_key(|(header, _)| {
|
||||
std::cmp::Reverse(depth_from_forest(&forest, header))
|
||||
});
|
||||
|
||||
let mut repaired = false;
|
||||
for (header, merge) in headers {
|
||||
if let Some((true_target, false_target)) =
|
||||
conditional_branch_targets(&blocks[by_name[&header]])
|
||||
{
|
||||
if bare_loop_exit_branch_with_passthroughs(
|
||||
blocks,
|
||||
&forest,
|
||||
loop_merges,
|
||||
&header,
|
||||
&true_target,
|
||||
&false_target,
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
// A conditional natural-loop latch is the loop's own back-edge/exit dispatch, not an
|
||||
// ordinary nested selection. Its non-backedge arm may enter an enclosing selection
|
||||
// merge, but wrapping that edge in a fresh selection merge would make the wrapper an
|
||||
// illegal loop exit (the edge must leave through the loop's declared merge).
|
||||
let header_successors = block_successors(&blocks[by_name[&header]]);
|
||||
if forest.loops.iter().any(|loop_info| {
|
||||
loop_info.latches.iter().any(|latch| latch == &header)
|
||||
&& header_successors
|
||||
.iter()
|
||||
.any(|successor| successor == &loop_info.header)
|
||||
}) {
|
||||
continue;
|
||||
}
|
||||
// A fully terminal selection deliberately owns a disconnected unreachable merge: every
|
||||
// real arm exits via return/unreachable, so there is no ordinary reconvergence to repair.
|
||||
// Replacing that marker with one terminal arm would pull the shared return into the
|
||||
// construct and make unrelated return predecessors illegal external entries.
|
||||
if by_name
|
||||
.get(&merge)
|
||||
.map(|index| &blocks[*index])
|
||||
.is_some_and(is_bare_unreachable)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let Some(exit_target) = selection_region_enclosing_escape_target(
|
||||
blocks,
|
||||
&forest,
|
||||
loop_merges,
|
||||
header_merges,
|
||||
&by_name,
|
||||
&header,
|
||||
&merge,
|
||||
) else {
|
||||
continue;
|
||||
};
|
||||
if crate::env_vars::spi_why() {
|
||||
eprintln!(
|
||||
"[spi-why] final-escape header={} merge={} target={}",
|
||||
header, merge, exit_target,
|
||||
);
|
||||
}
|
||||
if !attempted.insert((header.clone(), exit_target.clone())) {
|
||||
continue;
|
||||
}
|
||||
let synth = if block_has_phi(blocks, &exit_target) {
|
||||
synth_unique_selection_merge_phi(blocks, &forest, &header, &exit_target, counter)
|
||||
} else {
|
||||
synth_unique_selection_merge(blocks, &forest, &header, &exit_target, counter)
|
||||
};
|
||||
if let Some(private_merge) = synth {
|
||||
header_merges.insert(header, private_merge);
|
||||
any_repaired = true;
|
||||
repaired = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if !repaired {
|
||||
break;
|
||||
}
|
||||
}
|
||||
any_repaired
|
||||
}
|
||||
|
||||
/// Replace a terminal marker when one arm actually reaches an enclosing selection merge.
|
||||
///
|
||||
/// Late return privatization can leave `H -> { terminal, live }` with H still mapped to the private
|
||||
/// return while the live arm exits to an enclosing construct's merge. Funnel H-owned incoming edges
|
||||
/// to that unique enclosing merge through a private phi-aware merge. Restricting the search to
|
||||
/// terminal-marked headers and already-declared enclosing merges avoids the broad whole-plan frontier
|
||||
/// churn of the general escape repair.
|
||||
pub(in crate::native) fn repair_terminal_selection_live_escapes(
|
||||
blocks: &mut Vec<BodyBlock>,
|
||||
loop_merges: &HashMap<String, LoopMergeInfo>,
|
||||
header_merges: &mut HashMap<String, String>,
|
||||
counter: &mut usize,
|
||||
) -> bool {
|
||||
let mut changed = false;
|
||||
let mut attempted = HashSet::<(String, String)>::new();
|
||||
loop {
|
||||
let forest = analyze(blocks);
|
||||
let by_name = blocks
|
||||
.iter()
|
||||
.map(|block| (block.name.as_str(), block))
|
||||
.collect::<HashMap<_, _>>();
|
||||
let reaches_terminal = |start: &str| {
|
||||
let mut current = start.to_string();
|
||||
let mut seen = HashSet::new();
|
||||
while seen.insert(current.clone()) {
|
||||
let Some(block) = by_name.get(current.as_str()) else {
|
||||
return false;
|
||||
};
|
||||
if is_bare_unreachable(block)
|
||||
|| block.role == BlockRole::TerminalExitReturn
|
||||
&& block_ends_in_void_return(blocks, ¤t)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
if block.role != BlockRole::LMerge {
|
||||
return false;
|
||||
}
|
||||
let successors = block_successors(block);
|
||||
let [successor] = successors.as_slice() else {
|
||||
return false;
|
||||
};
|
||||
current = successor.clone();
|
||||
}
|
||||
false
|
||||
};
|
||||
let mut headers = header_merges
|
||||
.iter()
|
||||
.filter(|(_, merge)| reaches_terminal(merge))
|
||||
.map(|(header, merge)| {
|
||||
(
|
||||
Some((
|
||||
header.clone(),
|
||||
merge.clone(),
|
||||
depth_from_forest(&forest, header),
|
||||
)
|
||||
))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
headers.sort_by(|left, right| right.2.cmp(&left.2).then(left.0.cmp(&right.0)));
|
||||
|
||||
let mut repaired = false;
|
||||
for (header, current_merge, _) in headers {
|
||||
let enclosing_merges = header_merges
|
||||
.iter()
|
||||
.filter(|(owner, merge)| {
|
||||
owner.as_str() != header
|
||||
&& merge.as_str() != current_merge
|
||||
&& forest.dominates(owner, &header)
|
||||
})
|
||||
.map(|(_, merge)| merge.clone())
|
||||
.collect::<HashSet<_>>();
|
||||
if enclosing_merges.is_empty() {
|
||||
let mut candidate = None;
|
||||
for (header, merge, _) in headers {
|
||||
let block = &blocks[by_name[&header]];
|
||||
let Some((left, right)) = conditional_branch_targets(block) else {
|
||||
continue;
|
||||
}
|
||||
let mut exits = HashSet::new();
|
||||
for block in blocks
|
||||
.iter()
|
||||
.filter(|block| forest.dominates(&header, &block.name))
|
||||
{
|
||||
for successor in block_successors(block) {
|
||||
if successor != current_merge
|
||||
&& !forest.dominates(&header, &successor)
|
||||
&& enclosing_merges.contains(&successor)
|
||||
&& !legal_enclosing_loop_exit(&forest, loop_merges, &block.name, &successor)
|
||||
{
|
||||
exits.insert(successor);
|
||||
}
|
||||
}
|
||||
}
|
||||
if exits.len() != 1 {
|
||||
continue;
|
||||
}
|
||||
let exit_target = exits.into_iter().next().expect("one exit was checked");
|
||||
if !attempted.insert((header.clone(), exit_target.clone())) {
|
||||
continue;
|
||||
}
|
||||
let private = if block_has_phi(blocks, &exit_target) {
|
||||
synth_unique_selection_merge_phi(blocks, &forest, &header, &exit_target, counter)
|
||||
} else {
|
||||
synth_unique_selection_merge(blocks, &forest, &header, &exit_target, counter)
|
||||
};
|
||||
if let Some(private) = private {
|
||||
if crate::env_vars::spi_why() {
|
||||
eprintln!(
|
||||
"[spi-why] terminal-live-refunnel header={} old_merge={} target={} merge={}",
|
||||
header, current_merge, exit_target, private,
|
||||
);
|
||||
}
|
||||
header_merges.insert(header, private);
|
||||
changed = true;
|
||||
repaired = true;
|
||||
let other = match (left == merge, right == merge) {
|
||||
(true, false) => right,
|
||||
(false, true) => left,
|
||||
_ => continue,
|
||||
};
|
||||
let Some(merge_block) = by_name.get(&merge).map(|index| &blocks[*index]) else {
|
||||
continue;
|
||||
};
|
||||
let merge_successors = block_successors(merge_block);
|
||||
let [merge_successor] = merge_successors.as_slice() else {
|
||||
continue;
|
||||
};
|
||||
let merge_routes_out = !forest.dominates(&header, merge_successor)
|
||||
&& exits_to_enclosing_selection_region(
|
||||
blocks,
|
||||
&forest,
|
||||
header_merges,
|
||||
&by_name,
|
||||
&header,
|
||||
merge_successor,
|
||||
);
|
||||
let other_routes_out = !forest.dominates(&header, &other)
|
||||
&& exits_to_enclosing_selection_region(
|
||||
blocks,
|
||||
&forest,
|
||||
header_merges,
|
||||
&by_name,
|
||||
&header,
|
||||
&other,
|
||||
);
|
||||
if merge_routes_out && other_routes_out {
|
||||
candidate = Some((header, other));
|
||||
break;
|
||||
}
|
||||
}
|
||||
if !repaired {
|
||||
let Some((header, other)) = candidate else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
changed
|
||||
}
|
||||
};
|
||||
|
||||
/// Remove a selection assignment from a conditional that owns no region of its own and only routes
|
||||
/// between exits of an enclosing selection.
|
||||
///
|
||||
/// Unique-merge synthesis can leave `H -> { shared, M -> outer-merge }`, where `shared` is entered by
|
||||
/// an enclosing sibling and `M` is H's phi-carrying private pass-through. Declaring `M` as H's merge
|
||||
/// makes the `shared` arm illegally escape H's construct. The conditional is instead a bare routing
|
||||
/// branch inside the enclosing construct: both arms leave H immediately, while `M` remains in place to
|
||||
/// preserve its edge phis. This is the selection analogue of a bare loop break/continue branch.
|
||||
pub(in crate::native) fn drop_pure_enclosing_selection_routes(
|
||||
blocks: &[BodyBlock],
|
||||
header_merges: &mut HashMap<String, String>,
|
||||
) -> bool {
|
||||
let forest = analyze(blocks);
|
||||
let by_name = blocks
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, block)| (block.name.clone(), index))
|
||||
.collect::<HashMap<_, _>>();
|
||||
let mut headers = header_merges
|
||||
.iter()
|
||||
.filter_map(|(header, merge)| {
|
||||
let block = &blocks[*by_name.get(header)?];
|
||||
conditional_branch_targets(block)?;
|
||||
Some((
|
||||
header.clone(),
|
||||
merge.clone(),
|
||||
depth_from_forest(&forest, header),
|
||||
))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
headers.sort_by(|left, right| right.2.cmp(&left.2).then(left.0.cmp(&right.0)));
|
||||
|
||||
let mut removed = false;
|
||||
for (header, merge, _) in headers {
|
||||
let Some(block) = by_name.get(&header).map(|index| &blocks[*index]) else {
|
||||
continue;
|
||||
};
|
||||
let Some((left, right)) = conditional_branch_targets(block) else {
|
||||
continue;
|
||||
};
|
||||
let other = match (left == merge, right == merge) {
|
||||
(true, false) => right,
|
||||
(false, true) => left,
|
||||
_ => continue,
|
||||
};
|
||||
let Some(merge_block) = by_name.get(&merge).map(|index| &blocks[*index]) else {
|
||||
continue;
|
||||
};
|
||||
let merge_successors = block_successors(merge_block);
|
||||
let [merge_successor] = merge_successors.as_slice() else {
|
||||
continue;
|
||||
};
|
||||
let merge_routes_out = !forest.dominates(&header, merge_successor)
|
||||
&& exits_to_enclosing_selection_region(
|
||||
let mut next_counter = *counter;
|
||||
let Some(cloned) =
|
||||
crate::native::cfg::clone_crossarm::privatize_dominated_region_with_renames(
|
||||
blocks,
|
||||
&forest,
|
||||
header_merges,
|
||||
&by_name,
|
||||
&header,
|
||||
merge_successor,
|
||||
);
|
||||
let other_routes_out = !forest.dominates(&header, &other)
|
||||
&& exits_to_enclosing_selection_region(
|
||||
blocks,
|
||||
&forest,
|
||||
header_merges,
|
||||
&by_name,
|
||||
&header,
|
||||
&other,
|
||||
);
|
||||
if merge_routes_out && other_routes_out {
|
||||
header_merges.remove(&header);
|
||||
removed = true;
|
||||
}
|
||||
}
|
||||
removed
|
||||
}
|
||||
|
||||
fn selection_region_enclosing_escape_target(
|
||||
blocks: &[BodyBlock],
|
||||
forest: &LoopForest,
|
||||
loop_merges: &HashMap<String, LoopMergeInfo>,
|
||||
header_merges: &HashMap<String, String>,
|
||||
by_name: &HashMap<String, usize>,
|
||||
header: &str,
|
||||
merge: &str,
|
||||
) -> Option<String> {
|
||||
let header_block = &blocks[*by_name.get(header)?];
|
||||
let mut seen = HashSet::new();
|
||||
let mut stack = block_successors(header_block)
|
||||
.into_iter()
|
||||
.filter(|target| target != merge)
|
||||
.collect::<Vec<_>>();
|
||||
let mut exit_target = None;
|
||||
while let Some(node) = stack.pop() {
|
||||
if node == merge || !seen.insert(node.clone()) {
|
||||
continue;
|
||||
}
|
||||
let Some(block) = by_name.get(node.as_str()).map(|index| &blocks[*index]) else {
|
||||
&mut next_counter,
|
||||
)
|
||||
else {
|
||||
declined.insert(header);
|
||||
continue;
|
||||
};
|
||||
if !forest.dominates(header, &node) {
|
||||
continue;
|
||||
}
|
||||
for successor in block_successors(block) {
|
||||
if successor == merge {
|
||||
continue;
|
||||
}
|
||||
if legal_enclosing_loop_exit(forest, loop_merges, &node, &successor) {
|
||||
continue;
|
||||
}
|
||||
if forest.dominates(header, &successor) {
|
||||
stack.push(successor);
|
||||
continue;
|
||||
}
|
||||
if exits_to_enclosing_selection_region(
|
||||
blocks,
|
||||
forest,
|
||||
header_merges,
|
||||
by_name,
|
||||
&node,
|
||||
&successor,
|
||||
) {
|
||||
if exit_target
|
||||
.as_ref()
|
||||
.is_some_and(|target: &String| target != &successor)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
exit_target = Some(successor);
|
||||
}
|
||||
}
|
||||
}
|
||||
exit_target
|
||||
}
|
||||
let mut next_blocks = cloned.blocks;
|
||||
let cloned_merges = header_merges
|
||||
.iter()
|
||||
.filter_map(|(owner, merge)| {
|
||||
Some((
|
||||
owner.clone(),
|
||||
cloned.renamed.get(owner)?.clone(),
|
||||
cloned
|
||||
.renamed
|
||||
.get(merge)
|
||||
.cloned()
|
||||
.unwrap_or_else(|| merge.clone()),
|
||||
))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
fn legal_enclosing_loop_exit(
|
||||
forest: &LoopForest,
|
||||
loop_merges: &HashMap<String, LoopMergeInfo>,
|
||||
source: &str,
|
||||
target: &str,
|
||||
) -> bool {
|
||||
forest.loops.iter().any(|loop_info| {
|
||||
let encloses =
|
||||
loop_info.header == source || loop_info.body.iter().any(|name| name == source);
|
||||
encloses
|
||||
&& (loop_info.header == target
|
||||
|| loop_merges
|
||||
.get(&loop_info.header)
|
||||
.is_some_and(|info| info.merge == target || info.continue_target == target))
|
||||
})
|
||||
let next_forest = analyze(&next_blocks);
|
||||
let Some(natural) = selection_merges(&next_blocks, &next_forest).remove(&header) else {
|
||||
declined.insert(header);
|
||||
continue;
|
||||
};
|
||||
let claims = header_merges
|
||||
.iter()
|
||||
.filter(|(owner, _)| owner.as_str() != header)
|
||||
.map(|(_, merge)| merge.clone())
|
||||
.chain(cloned_merges.iter().map(|(_, _, merge)| merge.clone()))
|
||||
.collect::<HashSet<_>>();
|
||||
let loop_roles = loop_role_targets_with_passthroughs(&next_blocks, loop_merges);
|
||||
let private = if next_forest.dominates(&header, &natural)
|
||||
&& !claims.contains(&natural)
|
||||
&& !loop_roles.contains(&natural)
|
||||
{
|
||||
Some(natural)
|
||||
} else if block_has_phi(&next_blocks, &natural) {
|
||||
synth_unique_selection_merge_phi(
|
||||
&mut next_blocks,
|
||||
&next_forest,
|
||||
&header,
|
||||
&natural,
|
||||
&mut next_counter,
|
||||
)
|
||||
} else {
|
||||
synth_unique_selection_merge(
|
||||
&mut next_blocks,
|
||||
&next_forest,
|
||||
&header,
|
||||
&natural,
|
||||
&mut next_counter,
|
||||
)
|
||||
};
|
||||
let Some(private) = private else {
|
||||
declined.insert(header);
|
||||
continue;
|
||||
};
|
||||
*blocks = next_blocks;
|
||||
for (_, cloned_owner, _) in &cloned_merges {
|
||||
dependents.insert(cloned_owner.clone());
|
||||
}
|
||||
let mut new_owners = cloned_merges
|
||||
.into_iter()
|
||||
.map(|(_, owner, merge)| (owner, merge))
|
||||
.collect::<Vec<_>>();
|
||||
new_owners.push((header.clone(), private.clone()));
|
||||
let next_forest = analyze(blocks);
|
||||
header_merges.extend(new_owners.iter().cloned());
|
||||
let terminal_links = terminal_parent_links(blocks, &next_forest);
|
||||
let mut composition_owners = new_owners
|
||||
.iter()
|
||||
.map(|(owner, _)| owner.clone())
|
||||
.collect::<Vec<_>>();
|
||||
composition_owners.sort_by(|left, right| {
|
||||
depth_from_forest(&next_forest, right)
|
||||
.cmp(&depth_from_forest(&next_forest, left))
|
||||
.then(left.cmp(right))
|
||||
});
|
||||
for owner in composition_owners {
|
||||
let completed = complete_terminal_parent_ownership(
|
||||
blocks,
|
||||
header_merges,
|
||||
&terminal_links,
|
||||
&owner,
|
||||
&mut next_counter,
|
||||
);
|
||||
for completed_owner in completed {
|
||||
if let Some(completed_dependents) =
|
||||
indexed_owners.dependents_by_owner.get(&completed_owner)
|
||||
{
|
||||
dependents.extend(completed_dependents.iter().cloned());
|
||||
}
|
||||
if blocks
|
||||
.iter()
|
||||
.find(|block| block.name == completed_owner)
|
||||
.is_some_and(is_switch_block)
|
||||
{
|
||||
finalize_fully_terminal_switch(
|
||||
blocks,
|
||||
header_merges,
|
||||
&completed_owner,
|
||||
&mut next_counter,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
*counter = next_counter;
|
||||
declined.clear();
|
||||
changed = true;
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
fn depth_from_forest(forest: &LoopForest, name: &str) -> usize {
|
||||
@@ -1787,8 +1832,80 @@ pub(in crate::native) fn bare_exit_escape_reason(
|
||||
if loop_ok || sel_break || case_ok || enclosing_selection_region_ok {
|
||||
continue;
|
||||
}
|
||||
if crate::env_vars::exit_why() {
|
||||
eprintln!(
|
||||
"[exit-why] source={} target={} selection-merge={:?} enclosing-loops={:?}",
|
||||
b.name,
|
||||
s,
|
||||
header_merge.get(&b.name),
|
||||
forest
|
||||
.loops
|
||||
.iter()
|
||||
.filter(|natural_loop| {
|
||||
natural_loop.header == b.name
|
||||
|| natural_loop.body.iter().any(|node| node == &b.name)
|
||||
})
|
||||
.map(|natural_loop| (
|
||||
&natural_loop.header,
|
||||
loop_merges.get(&natural_loop.header)
|
||||
))
|
||||
.collect::<Vec<_>>(),
|
||||
);
|
||||
}
|
||||
return Some("bare-exit:unstructured-escape");
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Reject an edge that begins inside a declared SPIR-V loop construct but bypasses that loop's
|
||||
/// merge/continue/header. Natural-loop SCC membership is insufficient here: a header-dominated,
|
||||
/// exit-only arm remains part of the structured loop even though it cannot reach a backedge.
|
||||
pub(in crate::native) fn dominance_loop_exit_escape_reason(
|
||||
blocks: &[BodyBlock],
|
||||
loop_merges: &HashMap<String, LoopMergeInfo>,
|
||||
) -> Option<&'static str> {
|
||||
let forest = analyze(blocks);
|
||||
let names = blocks
|
||||
.iter()
|
||||
.map(|block| block.name.as_str())
|
||||
.collect::<HashSet<_>>();
|
||||
for block in blocks {
|
||||
for successor in block_successors(block) {
|
||||
if successor == block.name || !names.contains(successor.as_str()) {
|
||||
continue;
|
||||
}
|
||||
for natural_loop in &forest.loops {
|
||||
let Some(info) = loop_merges.get(&natural_loop.header) else {
|
||||
continue;
|
||||
};
|
||||
let source_inside = natural_loop.header == block.name
|
||||
|| (forest.dominates(&natural_loop.header, &block.name)
|
||||
&& !forest.dominates(&info.merge, &block.name));
|
||||
if !source_inside {
|
||||
continue;
|
||||
}
|
||||
let target_inside = forest.dominates(&natural_loop.header, &successor)
|
||||
&& !forest.dominates(&info.merge, &successor);
|
||||
let target_is_role = natural_loop.header == successor
|
||||
|| info.merge == successor
|
||||
|| info.continue_target == successor;
|
||||
if target_inside || target_is_role {
|
||||
continue;
|
||||
}
|
||||
if crate::env_vars::exit_why() {
|
||||
eprintln!(
|
||||
"[exit-why] source={} target={} loop={} merge={} continue={}",
|
||||
block.name,
|
||||
successor,
|
||||
natural_loop.header,
|
||||
info.merge,
|
||||
info.continue_target,
|
||||
);
|
||||
}
|
||||
return Some("loop-exit:dominance-owned-bypass");
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
@@ -87,15 +87,15 @@ pub(in crate::native) fn structured_plan_inner6(
|
||||
pub(in crate::native) fn structured_plan_construct_tree(
|
||||
blocks: &[BodyBlock],
|
||||
) -> Option<StructuredPlan> {
|
||||
// Prefer the immutable whole-CFG ownership proof. It can close ordinary, loop-exit, and terminal
|
||||
// switch constructs without duplicating their regions. Direct cross-arm privatization is a last
|
||||
// resort: on generated CFGs it can clone several nested copies before discovering that the raw
|
||||
// tree already owned the route, multiplying both planner work and live carrier memory.
|
||||
// Prefer the immutable whole-CFG ownership proof when it already captures the graph without
|
||||
// loop-exit convergence. Besides avoiding needless synthetic roles, this keeps an outer
|
||||
// selection from being stretched across a loop that has entries in both of its arms.
|
||||
if let Some(plan) =
|
||||
structured_plan_inner7(blocks, false, false, false, true, false, false, true)
|
||||
{
|
||||
return Some(plan);
|
||||
}
|
||||
|
||||
for (converge_inloop, break_aware) in [(true, false), (true, true), (false, false)] {
|
||||
if let Some(plan) = structured_plan_inner7(
|
||||
blocks,
|
||||
@@ -378,7 +378,7 @@ pub(in crate::native) fn structured_plan_inner8(
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let (sblocks, mut branch, mut branch_merges_by_header, switch) = if construct_tree_owned {
|
||||
let (mut sblocks, mut branch, mut branch_merges_by_header, switch) = if construct_tree_owned {
|
||||
unique_selection_merges_with_construct_tree_ownership(
|
||||
&lblocks,
|
||||
&loop_merges,
|
||||
@@ -395,6 +395,29 @@ pub(in crate::native) fn structured_plan_inner8(
|
||||
&terminal_merges,
|
||||
)
|
||||
};
|
||||
if !construct_tree_owned {
|
||||
index_branch_merges_by_header(
|
||||
&sblocks,
|
||||
&loop_merges,
|
||||
&branch,
|
||||
&mut branch_merges_by_header,
|
||||
);
|
||||
}
|
||||
normalize_continue_selection_merge_targets(
|
||||
&mut sblocks,
|
||||
&loop_merges,
|
||||
&mut branch_merges_by_header,
|
||||
);
|
||||
if !construct_tree_owned {
|
||||
branch = sblocks
|
||||
.iter()
|
||||
.filter_map(|block| {
|
||||
let (true_target, false_target) = conditional_branch_targets(block)?;
|
||||
let merge = branch_merges_by_header.get(&block.name)?;
|
||||
Some(((true_target, false_target), merge.clone()))
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
if selection_synth_growth_exceeds_ladder_cap(lblocks.len(), sblocks.len()) {
|
||||
spi_reject!(format!(
|
||||
"selection-synth-growth nblk={} from={}",
|
||||
@@ -430,7 +453,7 @@ pub(in crate::native) fn structured_plan_inner8(
|
||||
// (in `forest_loop_merges`) already lifts the GENUINE in-loop case — every switch target an
|
||||
// in-loop block — into a fresh successor, so what reaches here is the residue whose switch
|
||||
// targets the loop's merge/continue (a `while`-style switch exit test, banked a private capture shard
|
||||
// `423ff479`); that residue has no split yet, so reject and fall back to the repair path.
|
||||
// `423ff479`); that residue has no split yet, so reject and fall back to the relooper retry.
|
||||
if is_switch {
|
||||
spi_reject!(format!("loop-header-switch header={}", b.name));
|
||||
return None;
|
||||
@@ -611,26 +634,61 @@ pub(in crate::native) fn structured_plan_inner8(
|
||||
// When a bare-loop-exit skip fired, re-verify that NO block escapes its construct to a non-merge,
|
||||
// non-role block (the residual unstructured exit self-checks 2/3 conservatively skip, unmasked by
|
||||
// the skip). Scoped to skip-affected functions so the primary emit stays byte-identical.
|
||||
if construct_tree_owned {
|
||||
if let Some(reason) = dominance_loop_exit_escape_reason(&ordered, &loop_merges) {
|
||||
spi_reject!(format!("self-check {reason}"));
|
||||
return None;
|
||||
}
|
||||
}
|
||||
if (skipped_bare_exit || loop_exit_selection) && !construct_tree_owned {
|
||||
if let Some(reason) = bare_exit_escape_reason(&ordered, &header_merge, &loop_merges) {
|
||||
spi_reject!(format!("self-check {reason}"));
|
||||
return None;
|
||||
}
|
||||
}
|
||||
if let Some(reason) = conflicting_phi_predecessor_reason(&ordered) {
|
||||
spi_reject!(format!("self-check {reason}"));
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(StructuredPlan {
|
||||
blocks: ordered,
|
||||
loop_merges,
|
||||
branch_merges: branch,
|
||||
branch_merges_by_header: if construct_tree_owned {
|
||||
branch_merges_by_header
|
||||
} else {
|
||||
HashMap::new()
|
||||
},
|
||||
branch_merges_by_header,
|
||||
switch_merges: switch,
|
||||
})
|
||||
}
|
||||
|
||||
/// Reject conflicting incoming values after every edge split and merge synthesis. Repeated
|
||||
/// byte-identical pairs canonicalize to one SPIR-V operand, but one predecessor cannot select two
|
||||
/// different values.
|
||||
fn conflicting_phi_predecessor_reason(blocks: &[BodyBlock]) -> Option<String> {
|
||||
for block in blocks {
|
||||
let Some(carrier) = &block.typed else {
|
||||
continue;
|
||||
};
|
||||
for inst in &carrier.insts {
|
||||
let Some((_, incoming)) = inst.phi_incoming() else {
|
||||
continue;
|
||||
};
|
||||
let mut value_by_predecessor = HashMap::new();
|
||||
for (value, predecessor) in incoming {
|
||||
if value_by_predecessor
|
||||
.insert(predecessor.as_str(), value)
|
||||
.is_some_and(|existing| existing != value)
|
||||
{
|
||||
return Some(format!(
|
||||
"phi-conflicting-predecessor block={} pred={predecessor}",
|
||||
block.name
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Restructure straddling loop merges into an admissible shape — the `selection:straddle-loop-merge`
|
||||
/// reject class (`05/MPSRNNBreakUpToOutputVecs`: two enclosing early-return guards whose false arm is
|
||||
/// the OpReturn block that also serves as the inner loop's exit merge, so the loop merge lands at/after
|
||||
@@ -641,9 +699,8 @@ pub(in crate::native) fn structured_plan_inner8(
|
||||
/// straddle was split, else `None`.
|
||||
///
|
||||
/// Pure structural transform (adds pass-through blocks, redirects in-loop exit edges, preserves the
|
||||
/// shared merge's phis via [`split_phi_overlap`]). Used ONLY by the `cfg_restructure` retry emit
|
||||
/// (adopt-if-validates at the caller), never the default path — so it is floor-safe by construction: a
|
||||
/// case that emits + validates on the default path never reaches it.
|
||||
/// shared merge's phis via [`split_phi_overlap`]). It is one reject-only planner alternative and is
|
||||
/// admitted through the same structural self-check as the ordinary plan.
|
||||
pub(in crate::native) fn restructure_straddle_loop_merges(
|
||||
blocks: &[BodyBlock],
|
||||
) -> Option<Vec<BodyBlock>> {
|
||||
@@ -1300,7 +1357,7 @@ fn straddle_closure_stats(
|
||||
continue;
|
||||
};
|
||||
for inst in &carrier.insts {
|
||||
if let Some((_, incoming)) = &inst.phi_incoming {
|
||||
if let Some((_, incoming)) = &inst.phi_incoming() {
|
||||
for (value, predecessor) in incoming {
|
||||
if !closure.contains(predecessor) {
|
||||
continue;
|
||||
@@ -1332,11 +1389,11 @@ fn straddle_closure_stats(
|
||||
}
|
||||
continue;
|
||||
}
|
||||
for used in &inst.uses {
|
||||
inst.visit_uses(|used| {
|
||||
if def_ty.contains_key(used) {
|
||||
nonphi_escapes.push((used.clone(), block.name.clone()));
|
||||
nonphi_escapes.push((used.to_string(), block.name.clone()));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
for used in terminator_uses(carrier) {
|
||||
if def_ty.contains_key(&used) {
|
||||
@@ -1518,6 +1575,33 @@ pub(in crate::native) fn find_synthesized_cross_arm_shared(
|
||||
})
|
||||
};
|
||||
let raw: HashSet<&str> = blocks.iter().map(|b| b.name.as_str()).collect();
|
||||
let raw_forest = analyze(blocks);
|
||||
let raw_loop_headers = raw_forest
|
||||
.loops
|
||||
.iter()
|
||||
.map(|natural_loop| natural_loop.header.as_str())
|
||||
.collect::<HashSet<_>>();
|
||||
let raw_loop_latches = raw_forest
|
||||
.loops
|
||||
.iter()
|
||||
.flat_map(|natural_loop| natural_loop.latches.iter().map(String::as_str))
|
||||
.collect::<HashSet<_>>();
|
||||
let raw_loop_exits = raw_forest
|
||||
.loops
|
||||
.iter()
|
||||
.flat_map(|natural_loop| natural_loop.exits.iter().map(String::as_str))
|
||||
.collect::<HashSet<_>>();
|
||||
let clone_is_loop_local = |owner: &str, continuation: &str| {
|
||||
super::clone_crossarm::shared_clone_is_loop_local(
|
||||
blocks,
|
||||
&raw_forest,
|
||||
owner,
|
||||
continuation,
|
||||
&raw_loop_headers,
|
||||
&raw_loop_latches,
|
||||
&raw_loop_exits,
|
||||
)
|
||||
};
|
||||
for b in &sblocks {
|
||||
if loop_headers.contains(b.name.as_str()) {
|
||||
continue;
|
||||
@@ -1532,6 +1616,7 @@ pub(in crate::native) fn find_synthesized_cross_arm_shared(
|
||||
if !forest.dominates(&b.name, &a)
|
||||
&& raw.contains(b.name.as_str())
|
||||
&& raw.contains(a.as_str())
|
||||
&& clone_is_loop_local(&b.name, &a)
|
||||
{
|
||||
return Some((b.name.clone(), a));
|
||||
}
|
||||
@@ -1574,6 +1659,7 @@ pub(in crate::native) fn find_synthesized_cross_arm_shared(
|
||||
if forest.dominates(t1, &s)
|
||||
&& raw.contains(child)
|
||||
&& raw.contains(s.as_str())
|
||||
&& clone_is_loop_local(child, &s)
|
||||
{
|
||||
return Some((child.to_string(), s));
|
||||
}
|
||||
@@ -1711,4 +1797,19 @@ mod tests {
|
||||
.exit_phi_sample
|
||||
.contains(&"%after:%x<-%lmerge:%v".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn final_phi_contract_rejects_conflicting_predecessor_values() {
|
||||
let blocks = vec![
|
||||
bb("%entry", &["br label %merge"]),
|
||||
bb(
|
||||
"%merge",
|
||||
&["%v = phi i32 [ 1, %entry ], [ 2, %entry ]", "ret void"],
|
||||
),
|
||||
];
|
||||
assert_eq!(
|
||||
conflicting_phi_predecessor_reason(&blocks).as_deref(),
|
||||
Some("phi-conflicting-predecessor block=%merge pred=%entry")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,13 @@
|
||||
//! Reject-only regional wrapper for bounded `selection:straddle-loop-merge` residue.
|
||||
//! Reject-only regional wrapper for bounded selection/loop ownership conflicts.
|
||||
//!
|
||||
//! The existing straddle split gives the nested loop its own merge, but the live R2 representatives
|
||||
//! still expose a second ownership conflict after that local split. This module derives the smaller
|
||||
//! source region measured by `straddle-witness-list`: one external entry into the straddled owner,
|
||||
//! two external exits, all escaping values carried only by exit-target phis, and no pointer payloads.
|
||||
//! It materializes that region as a local PC-dispatch loop and rewrites the two external exits through
|
||||
//! typed payload gateways. This is diagnostic-only until the live representative follow-on
|
||||
//! ownership blockers admit; any future production adoption must remain whole-module `spirv-val`
|
||||
//! gated.
|
||||
//! typed payload gateways. The same materializer owns a complete selection arm when a nested loop
|
||||
//! exits into that selection's sibling. Both paths preserve typed scalar state and decline pointer
|
||||
//! state whose provenance cannot be represented faithfully.
|
||||
|
||||
use super::*;
|
||||
use crate::native::ir::{LlType, LlValue, TypedValue};
|
||||
@@ -232,6 +232,180 @@ fn derive_witness(blocks: &[BodyBlock]) -> Option<Witness> {
|
||||
None
|
||||
}
|
||||
|
||||
fn derive_loop_exit_sibling_witness(blocks: &[BodyBlock]) -> Option<Witness> {
|
||||
let forest = analyze(blocks);
|
||||
let post_idom = super::super::loopforest::post_idom(blocks);
|
||||
let by_name = blocks
|
||||
.iter()
|
||||
.map(|block| (block.name.as_str(), block))
|
||||
.collect::<HashMap<_, _>>();
|
||||
let post_chain = |start: &str| {
|
||||
let mut chain = vec![start.to_string()];
|
||||
let mut current = start;
|
||||
while let Some(next) = post_idom.get(current) {
|
||||
if chain.contains(next) {
|
||||
break;
|
||||
}
|
||||
chain.push(next.clone());
|
||||
current = next;
|
||||
}
|
||||
chain
|
||||
};
|
||||
for owner in blocks {
|
||||
let Some((left, right)) = conditional_branch_targets(owner) else {
|
||||
continue;
|
||||
};
|
||||
let Some(owner_merge) = post_idom.get(&owner.name) else {
|
||||
continue;
|
||||
};
|
||||
for (loop_entry, sibling) in [(&left, &right), (&right, &left)] {
|
||||
for natural_loop in &forest.loops {
|
||||
let exit_chains = natural_loop
|
||||
.exits
|
||||
.iter()
|
||||
.map(|exit| post_chain(exit))
|
||||
.collect::<Vec<_>>();
|
||||
let Some(loop_merge) = exit_chains.first().and_then(|first| {
|
||||
first
|
||||
.iter()
|
||||
.find(|candidate| {
|
||||
exit_chains.iter().all(|chain| chain.contains(*candidate))
|
||||
})
|
||||
.cloned()
|
||||
}) else {
|
||||
continue;
|
||||
};
|
||||
if !natural_loop.body.iter().any(|block| block == loop_entry)
|
||||
|| natural_loop.body.iter().any(|block| block == &owner.name)
|
||||
|| natural_loop.body.iter().any(|block| block == sibling)
|
||||
|| !forest.dominates(&owner.name, &natural_loop.header)
|
||||
|| !forest.dominates(&loop_merge, owner_merge)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let exits_to_sibling = natural_loop.exits.iter().any(|exit| {
|
||||
let mut current = exit.clone();
|
||||
let mut seen = HashSet::new();
|
||||
loop {
|
||||
if ¤t == sibling {
|
||||
break true;
|
||||
}
|
||||
if !seen.insert(current.clone())
|
||||
|| natural_loop.body.iter().any(|block| block == ¤t)
|
||||
{
|
||||
break false;
|
||||
}
|
||||
let Some(block) = by_name.get(current.as_str()) else {
|
||||
break false;
|
||||
};
|
||||
let successors = block_successors(block);
|
||||
let [next] = successors.as_slice() else {
|
||||
break false;
|
||||
};
|
||||
current = next.clone();
|
||||
}
|
||||
});
|
||||
if !exits_to_sibling {
|
||||
continue;
|
||||
}
|
||||
if let Some(witness) =
|
||||
build_selection_arm_witness(blocks, &forest, &owner.name, owner_merge)
|
||||
{
|
||||
return Some(witness);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn build_selection_arm_witness(
|
||||
blocks: &[BodyBlock],
|
||||
forest: &LoopForest,
|
||||
owner: &str,
|
||||
owner_merge: &str,
|
||||
) -> Option<Witness> {
|
||||
let names = blocks
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, block)| (block.name.as_str(), index))
|
||||
.collect::<HashMap<_, _>>();
|
||||
let name_set = blocks
|
||||
.iter()
|
||||
.map(|block| block.name.as_str())
|
||||
.collect::<HashSet<_>>();
|
||||
let mut predecessors: HashMap<String, Vec<String>> = HashMap::new();
|
||||
for block in blocks {
|
||||
for successor in block_successors(block) {
|
||||
if name_set.contains(successor.as_str()) {
|
||||
predecessors
|
||||
.entry(successor)
|
||||
.or_default()
|
||||
.push(block.name.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut reaches_merge = HashSet::new();
|
||||
let mut stack = vec![owner_merge.to_string()];
|
||||
while let Some(node) = stack.pop() {
|
||||
if !reaches_merge.insert(node.clone()) {
|
||||
continue;
|
||||
}
|
||||
if let Some(incoming) = predecessors.get(&node) {
|
||||
stack.extend(incoming.iter().cloned());
|
||||
}
|
||||
}
|
||||
let closure = blocks
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(index, block)| {
|
||||
(block.name != owner_merge
|
||||
&& forest.dominates(owner, &block.name)
|
||||
&& reaches_merge.contains(&block.name))
|
||||
.then_some(index)
|
||||
})
|
||||
.collect::<HashSet<_>>();
|
||||
if closure.is_empty() || closure.len() > MAX_REGION_BLOCKS {
|
||||
return None;
|
||||
}
|
||||
let mut entries = Vec::new();
|
||||
let mut exits = Vec::new();
|
||||
for (source, block) in blocks.iter().enumerate() {
|
||||
for successor in block_successors(block) {
|
||||
let target = *names.get(successor.as_str())?;
|
||||
match (closure.contains(&source), closure.contains(&target)) {
|
||||
(false, true) => entries.push((source, target)),
|
||||
(true, false) => exits.push((source, target)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
entries.sort_unstable();
|
||||
entries.dedup();
|
||||
exits.sort_unstable();
|
||||
exits.dedup();
|
||||
if entries.len() != 1 || exits.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut ordered = closure.iter().copied().collect::<Vec<_>>();
|
||||
ordered.sort_unstable();
|
||||
let local_of = ordered
|
||||
.iter()
|
||||
.copied()
|
||||
.enumerate()
|
||||
.map(|(local, global)| (global, local))
|
||||
.collect::<HashMap<_, _>>();
|
||||
Some(Witness {
|
||||
blocks: blocks.to_vec(),
|
||||
closure,
|
||||
ordered,
|
||||
local_of,
|
||||
entry_from: entries[0].0,
|
||||
entry_to: entries[0].1,
|
||||
exits,
|
||||
})
|
||||
}
|
||||
|
||||
fn derive_witness_in_mode(
|
||||
blocks: &[BodyBlock],
|
||||
converge_inloop: bool,
|
||||
@@ -395,7 +569,10 @@ fn build_witness(
|
||||
})
|
||||
}
|
||||
|
||||
fn regional_candidate(witness: Witness) -> Result<Vec<BodyBlock>, String> {
|
||||
fn regional_candidate(
|
||||
witness: Witness,
|
||||
require_exit_payload: bool,
|
||||
) -> Result<Vec<BodyBlock>, String> {
|
||||
let Witness {
|
||||
mut blocks,
|
||||
closure,
|
||||
@@ -474,7 +651,7 @@ fn regional_candidate(witness: Witness) -> Result<Vec<BodyBlock>, String> {
|
||||
for (host_local, &global) in ordered.iter().enumerate() {
|
||||
let carrier = blocks[global].typed.as_ref().expect("checked above");
|
||||
for inst in &carrier.insts {
|
||||
let Some((ty, incoming)) = &inst.phi_incoming else {
|
||||
let Some((ty, incoming)) = &inst.phi_incoming() else {
|
||||
continue;
|
||||
};
|
||||
let result = inst.result.as_ref().ok_or_else(|| {
|
||||
@@ -544,7 +721,7 @@ fn regional_candidate(witness: Witness) -> Result<Vec<BodyBlock>, String> {
|
||||
&exit_by_pair,
|
||||
&def_block,
|
||||
)?;
|
||||
if exit_payload_slots.is_empty() {
|
||||
if require_exit_payload && exit_payload_slots.is_empty() {
|
||||
return Err("construct-tree:straddle-no-exit-payload".to_string());
|
||||
}
|
||||
|
||||
@@ -555,14 +732,14 @@ fn regional_candidate(witness: Witness) -> Result<Vec<BodyBlock>, String> {
|
||||
if inst.is_phi() {
|
||||
continue;
|
||||
}
|
||||
for name in &inst.uses {
|
||||
inst.visit_uses(|name| {
|
||||
if def_block
|
||||
.get(name.as_str())
|
||||
.get(name)
|
||||
.is_some_and(|(owner, _)| *owner != local)
|
||||
{
|
||||
cross_values.insert(name.clone());
|
||||
cross_values.insert(name.to_string());
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
for name in terminator_uses(carrier) {
|
||||
if def_block
|
||||
@@ -1015,7 +1192,10 @@ fn regional_candidate(witness: Witness) -> Result<Vec<BodyBlock>, String> {
|
||||
"switch i32 {EXIT_ID}, label {} [ {switch_targets} ]",
|
||||
exit_gateway[external_exit_indices[0]]
|
||||
)],
|
||||
BlockRole::ConstructTreeRoute,
|
||||
// This is a real selection header whose routes reconverge in the outside CFG. Marking
|
||||
// the header itself as a route makes construct-tree merge synthesis treat that
|
||||
// reconvergence as an enclosing escape and invent an unreachable merge instead.
|
||||
BlockRole::Normal,
|
||||
));
|
||||
}
|
||||
for exit_index in external_exit_indices {
|
||||
@@ -1079,7 +1259,7 @@ fn collect_exit_payload_slots(
|
||||
continue;
|
||||
};
|
||||
for inst in &carrier.insts {
|
||||
if let Some((ty, incoming)) = &inst.phi_incoming {
|
||||
if let Some((ty, incoming)) = &inst.phi_incoming() {
|
||||
let result = inst.result.clone().ok_or_else(|| {
|
||||
format!(
|
||||
"construct-tree:straddle-exit-phi-without-result block={}",
|
||||
@@ -1126,13 +1306,17 @@ fn collect_exit_payload_slots(
|
||||
}
|
||||
continue;
|
||||
}
|
||||
for used in &inst.uses {
|
||||
if def_block.contains_key(used) {
|
||||
return Err(format!(
|
||||
"construct-tree:straddle-nonphi-escape block={} value={used}",
|
||||
block.name
|
||||
));
|
||||
let mut escaping = None;
|
||||
inst.visit_uses(|used| {
|
||||
if escaping.is_none() && def_block.contains_key(used) {
|
||||
escaping = Some(used.to_string());
|
||||
}
|
||||
});
|
||||
if let Some(used) = escaping {
|
||||
return Err(format!(
|
||||
"construct-tree:straddle-nonphi-escape block={} value={used}",
|
||||
block.name
|
||||
));
|
||||
}
|
||||
}
|
||||
for used in terminator_uses(carrier) {
|
||||
@@ -1148,7 +1332,7 @@ fn collect_exit_payload_slots(
|
||||
for (source, target) in exits {
|
||||
if !blocks[*target].typed.as_ref().is_some_and(|carrier| {
|
||||
carrier.insts.iter().any(|inst| {
|
||||
inst.phi_incoming.as_ref().is_some_and(|(_, incoming)| {
|
||||
inst.phi_incoming().as_ref().is_some_and(|(_, incoming)| {
|
||||
incoming
|
||||
.iter()
|
||||
.any(|(_, predecessor)| names.get(predecessor) == Some(source))
|
||||
@@ -1220,7 +1404,7 @@ fn rewrite_entry_and_exit_phis(
|
||||
)
|
||||
})?;
|
||||
let incoming = inst
|
||||
.phi_incoming
|
||||
.phi_incoming()
|
||||
.as_ref()
|
||||
.map(|(_, incoming)| incoming.clone())
|
||||
.ok_or_else(|| {
|
||||
@@ -1263,6 +1447,24 @@ pub(in crate::native) fn renest_straddle_loop_merge(
|
||||
regional_candidate(
|
||||
derive_witness(blocks)
|
||||
.ok_or_else(|| "construct-tree:straddle-witness-decline".to_string())?,
|
||||
true,
|
||||
)
|
||||
.map(Some)
|
||||
}
|
||||
|
||||
/// Re-nest a selection arm whose natural loop exits through a linear tail into the selection's
|
||||
/// sibling arm. The regional wrapper owns only the conflicted selection/loop closure, carries its
|
||||
/// scalar exit payloads through typed gateways, and leaves all outside pointer SSA in place.
|
||||
pub(in crate::native) fn renest_loop_exit_sibling(
|
||||
blocks: &[BodyBlock],
|
||||
) -> Result<Option<Vec<BodyBlock>>, String> {
|
||||
if !requires_loop_exit_sibling_dispatch(blocks) {
|
||||
return Ok(None);
|
||||
}
|
||||
regional_candidate(
|
||||
derive_loop_exit_sibling_witness(blocks)
|
||||
.ok_or_else(|| "construct-tree:loop-exit-sibling-witness-decline".to_string())?,
|
||||
false,
|
||||
)
|
||||
.map(Some)
|
||||
}
|
||||
@@ -1331,7 +1533,7 @@ mod tests {
|
||||
.clone();
|
||||
let witness = build_witness(&source, &forest, &loop_body, "%lmerge", "%owner", "%out0")
|
||||
.expect("bounded straddle witness");
|
||||
let candidate = regional_candidate(witness).expect("regional wrapper");
|
||||
let candidate = regional_candidate(witness, true).expect("regional wrapper");
|
||||
assert!(candidate.iter().any(|block| block.name == PRE));
|
||||
assert!(candidate.iter().any(|block| block.name == EXIT));
|
||||
for original in ["%owner", "%loop", "%body", "%lmerge"] {
|
||||
@@ -1355,7 +1557,7 @@ mod tests {
|
||||
.insts
|
||||
.iter()
|
||||
.find(|inst| inst.result.as_deref() == Some("%x"))
|
||||
.and_then(|inst| inst.phi_incoming.as_ref())
|
||||
.and_then(|inst| inst.phi_incoming().as_ref())
|
||||
.map(|(_, incoming)| incoming.clone())
|
||||
.expect("rewritten out0 phi");
|
||||
assert!(
|
||||
@@ -1384,7 +1586,7 @@ mod tests {
|
||||
.find(|block| block.name == MERGE)
|
||||
.expect("wrapper merge");
|
||||
for inst in &merge.typed.as_ref().expect("carrier").insts {
|
||||
let Some((_, incoming)) = &inst.phi_incoming else {
|
||||
let Some((_, incoming)) = &inst.phi_incoming() else {
|
||||
continue;
|
||||
};
|
||||
for (_, predecessor) in incoming {
|
||||
@@ -1395,4 +1597,50 @@ mod tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loop_exit_sibling_wrapper_owns_the_complete_selection_tail() {
|
||||
let source = vec![
|
||||
bb("%entry", &["br label %owner"]),
|
||||
bb("%owner", &["br i1 %direct, label %sibling, label %loop"]),
|
||||
bb(
|
||||
"%loop",
|
||||
&[
|
||||
"%i = phi i32 [ 0, %owner ], [ %next, %loop_tail ]",
|
||||
"br label %body",
|
||||
],
|
||||
),
|
||||
bb(
|
||||
"%body",
|
||||
&[
|
||||
"%next = add i32 %i, 1",
|
||||
"br i1 %leave, label %sibling, label %loop_tail",
|
||||
],
|
||||
),
|
||||
bb("%loop_tail", &["br i1 %again, label %loop, label %tail"]),
|
||||
bb(
|
||||
"%sibling",
|
||||
&[
|
||||
"%value = phi i32 [ 7, %owner ], [ %next, %body ]",
|
||||
"br label %post",
|
||||
],
|
||||
),
|
||||
bb("%tail", &["br label %post"]),
|
||||
bb("%post", &["br label %merge"]),
|
||||
bb("%merge", &["ret void"]),
|
||||
];
|
||||
assert!(requires_loop_exit_sibling_dispatch(&source));
|
||||
let candidate = renest_loop_exit_sibling(&source)
|
||||
.expect("regional ownership construction")
|
||||
.expect("loop-exit sibling witness");
|
||||
assert!(candidate.iter().any(|block| block.name == PRE));
|
||||
assert!(candidate.iter().any(|block| block.name == "%post"));
|
||||
assert!(candidate.iter().any(|block| block.name == "%merge"));
|
||||
structured_plan_construct_tree(&candidate).unwrap_or_else(|| {
|
||||
panic!(
|
||||
"regional loop-exit sibling candidate should structure, reason={:?}",
|
||||
structured_reject_reason(&candidate)
|
||||
)
|
||||
});
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -2,7 +2,7 @@
|
||||
//!
|
||||
//! Primary CFG emission is structured by construction. Block ordering, single-predecessor cleanup,
|
||||
//! and merge placement are coupled, so the planner produces a complete plan rather than incrementally
|
||||
//! bypassing individual retained-module repairs. This begins with emitting blocks in a structured
|
||||
//! avoiding retained-module control-flow rewrites. This begins with emitting blocks in a structured
|
||||
//! order.
|
||||
//!
|
||||
//! This module is that ordering. SPIR-V's structured CFG requires every block to appear after its
|
||||
|
||||
@@ -124,17 +124,25 @@ pub(in crate::native) fn compute_global_consts(
|
||||
let mut store_count: HashMap<Word, usize> = HashMap::new();
|
||||
// (function index, block index, instruction index, value operand id)
|
||||
let mut single_store: HashMap<Word, (usize, usize, usize, Word)> = HashMap::new();
|
||||
let mut load_functions: HashMap<Word, HashSet<usize>> = HashMap::new();
|
||||
for (fi, f) in module.functions.iter().enumerate() {
|
||||
for (bi, blk) in f.blocks.iter().enumerate() {
|
||||
for (ii, inst) in blk.instructions.iter().enumerate() {
|
||||
if inst.class.opcode != Op::Store {
|
||||
continue;
|
||||
}
|
||||
if let Some(g) = direct_global(inst, &global_vars) {
|
||||
*store_count.entry(g).or_default() += 1;
|
||||
if let Some(Operand::IdRef(v)) = inst.operands.get(1) {
|
||||
single_store.insert(g, (fi, bi, ii, *v));
|
||||
match inst.class.opcode {
|
||||
Op::Store => {
|
||||
if let Some(g) = direct_global(inst, &global_vars) {
|
||||
*store_count.entry(g).or_default() += 1;
|
||||
if let Some(Operand::IdRef(v)) = inst.operands.get(1) {
|
||||
single_store.insert(g, (fi, bi, ii, *v));
|
||||
}
|
||||
}
|
||||
}
|
||||
Op::Load => {
|
||||
if let Some(g) = direct_global(inst, &global_vars) {
|
||||
load_functions.entry(g).or_default().insert(fi);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -154,7 +162,7 @@ pub(in crate::native) fn compute_global_consts(
|
||||
|
||||
// (b) single-store forwarding fixpoint.
|
||||
loop {
|
||||
let mut changed = false;
|
||||
let mut candidates = Vec::new();
|
||||
for (&g, &(fi, bi, ii, vid)) in &single_store {
|
||||
if gc.contains_key(&g) || store_count.get(&g).copied().unwrap_or(0) != 1 {
|
||||
continue;
|
||||
@@ -175,18 +183,40 @@ pub(in crate::native) fn compute_global_consts(
|
||||
// The store's dominance only covers loads in its OWN function; if any other function
|
||||
// loads `g`, the forwarded constant is not guaranteed there. (Post-inline this is a
|
||||
// single function, but guard it so the rule stays sound for multi-function modules.)
|
||||
let loaded_elsewhere = module.functions.iter().enumerate().any(|(other, of)| {
|
||||
other != fi
|
||||
&& of.blocks.iter().flat_map(|b| &b.instructions).any(|i| {
|
||||
i.class.opcode == Op::Load && direct_global(i, &global_vars) == Some(g)
|
||||
})
|
||||
});
|
||||
let loaded_elsewhere = load_functions
|
||||
.get(&g)
|
||||
.is_some_and(|functions| functions.iter().any(|&other| other != fi));
|
||||
if loaded_elsewhere {
|
||||
continue;
|
||||
}
|
||||
// Evaluate the stored value with the constants known so far.
|
||||
let vals = forward_eval(f, consts, &gc, widths, &HashMap::new(), vec_globals);
|
||||
if let Some(c) = vals.get(&vid) {
|
||||
candidates.push((g, fi, vid));
|
||||
}
|
||||
if candidates.is_empty() {
|
||||
break;
|
||||
}
|
||||
let function_indices = candidates
|
||||
.iter()
|
||||
.map(|(_, fi, _)| *fi)
|
||||
.collect::<HashSet<_>>();
|
||||
let evaluations = function_indices
|
||||
.into_iter()
|
||||
.map(|fi| {
|
||||
(
|
||||
fi,
|
||||
forward_eval(
|
||||
&module.functions[fi],
|
||||
consts,
|
||||
&gc,
|
||||
widths,
|
||||
&HashMap::new(),
|
||||
vec_globals,
|
||||
),
|
||||
)
|
||||
})
|
||||
.collect::<HashMap<_, _>>();
|
||||
let mut changed = false;
|
||||
for (g, fi, vid) in candidates {
|
||||
if let Some(c) = evaluations.get(&fi).and_then(|values| values.get(&vid)) {
|
||||
gc.insert(g, *c);
|
||||
changed = true;
|
||||
}
|
||||
|
||||
@@ -16,9 +16,9 @@
|
||||
//! on NOTHING workload-specific: the only seed is "a scalar-int/bool global that is never stored and
|
||||
//! has a constant initializer" plus "a scalar global stored exactly once (in the entry block, with no
|
||||
//! preceding load) by a constant value" — both of which are the function-constant machinery the
|
||||
//! emitter produced, identified structurally. Run as a failure-triggered, adopt-if-VALIDATES retry,
|
||||
//! so it is floor-safe: a module that validates on the default path never reaches it, and a
|
||||
//! non-validating pruned result is discarded.
|
||||
//! emitter produced, identified structurally. Primary construction folds the constant-controlled
|
||||
//! CFG without global DCE; raw-CFG construction retains the full DCE form for values that require
|
||||
//! it. Neither representation depends on validator wording to decide which CFG is executable.
|
||||
|
||||
mod prune;
|
||||
pub(in crate::native) use prune::*;
|
||||
@@ -150,8 +150,25 @@ mod tests {
|
||||
let mut func = Function::new();
|
||||
func.blocks = vec![entry, then_b, else_b, merge_b];
|
||||
m.functions = vec![func];
|
||||
m.debug_names = vec![
|
||||
inst(
|
||||
Op::Name,
|
||||
None,
|
||||
None,
|
||||
vec![
|
||||
Operand::IdRef(35),
|
||||
Operand::LiteralString("dead-arm".into()),
|
||||
],
|
||||
),
|
||||
inst(
|
||||
Op::Name,
|
||||
None,
|
||||
None,
|
||||
vec![Operand::IdRef(39), Operand::LiteralString("unowned".into())],
|
||||
),
|
||||
];
|
||||
|
||||
assert!(prune_constant_branches(&mut m), "expected a fold");
|
||||
crate::native::rewrites::prune_constant_branches_module(&mut m).expect("expected a fold");
|
||||
let labels: Vec<Word> = m.functions[0]
|
||||
.blocks
|
||||
.iter()
|
||||
@@ -165,6 +182,8 @@ mod tests {
|
||||
labels.contains(&34),
|
||||
"taken then-arm (%34) should survive: {labels:?}"
|
||||
);
|
||||
assert_eq!(m.debug_names.len(), 1);
|
||||
assert_eq!(m.debug_names[0].operands[0], Operand::IdRef(39));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -10,15 +10,20 @@ use std::collections::HashSet;
|
||||
/// Entry: fold statically-constant branches and DCE the resulting dead code, to a fixpoint.
|
||||
/// Returns `true` if anything changed.
|
||||
pub(in crate::native) fn prune_constant_branches(module: &mut Module) -> bool {
|
||||
prune_constant_branches_preserving(module, &HashSet::new())
|
||||
prune_constant_branches_impl(module, &HashSet::new(), true)
|
||||
}
|
||||
|
||||
/// Constant-branch pruning with additional module-global roots supplied by a typed sidecar. This is
|
||||
/// used only while a primary module is still in memory: the roots replace the liveness formerly
|
||||
/// supplied accidentally by debug `OpName` marker instructions.
|
||||
pub(in crate::native) fn prune_constant_branches_preserving(
|
||||
/// Fold constant-controlled CFG without sweeping unrelated unused values. This is the primary
|
||||
/// construction form: it may run for every module without turning the failure-recovery DCE into a
|
||||
/// byte-changing whole-module optimization.
|
||||
pub(in crate::native) fn prune_constant_cfg(module: &mut Module) -> bool {
|
||||
prune_constant_branches_impl(module, &HashSet::new(), false)
|
||||
}
|
||||
|
||||
fn prune_constant_branches_impl(
|
||||
module: &mut Module,
|
||||
preserved_global_ids: &HashSet<Word>,
|
||||
sweep_dead_values: bool,
|
||||
) -> bool {
|
||||
let scalar_int_types = scalar_int_bool_types(module);
|
||||
let consts = module_scalar_constants(module, &scalar_int_types);
|
||||
@@ -32,6 +37,7 @@ pub(in crate::native) fn prune_constant_branches_preserving(
|
||||
}
|
||||
|
||||
let mut any = false;
|
||||
let mut cfg_was_pruned = false;
|
||||
// Module-level fixpoint: each pass may expose new constant conditions (a collapsed single-pred
|
||||
// phi whose arms are equal, a freshly-dead block) for the next.
|
||||
loop {
|
||||
@@ -60,17 +66,32 @@ pub(in crate::native) fn prune_constant_branches_preserving(
|
||||
for (g, v) in guards {
|
||||
vals.entry(g).or_insert(v);
|
||||
}
|
||||
changed |= fold_branches(&mut module.functions[fi], &vals);
|
||||
changed |= prune_unreachable(&mut module.functions[fi]);
|
||||
changed |= collapse_trivial_phis(&mut module.functions[fi]);
|
||||
if sweep_dead_values {
|
||||
changed |= fold_branches(&mut module.functions[fi], &vals);
|
||||
changed |= prune_unreachable(&mut module.functions[fi]);
|
||||
changed |= collapse_trivial_phis(&mut module.functions[fi]);
|
||||
} else {
|
||||
let folded = fold_branches(&mut module.functions[fi], &vals);
|
||||
let pruned = prune_unreachable(&mut module.functions[fi]);
|
||||
let collapsed =
|
||||
(folded || pruned) && collapse_trivial_phis(&mut module.functions[fi]);
|
||||
changed |= folded || pruned || collapsed;
|
||||
if folded || pruned {
|
||||
cfg_was_pruned = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
// DCE is module-wide (uses cross blocks/functions); run once per outer iteration.
|
||||
changed |= dce_preserving(module, preserved_global_ids);
|
||||
if sweep_dead_values {
|
||||
changed |= dce_preserving(module, preserved_global_ids);
|
||||
}
|
||||
// Once branch folding removes every call to an unhandled-intrinsic function (igemm /
|
||||
// load.with.emask / ... — emitted as a BODYLESS OpFunction declaration), that declaration is
|
||||
// dead: a non-imported function with no basic blocks is invalid SPIR-V, so it must be swept
|
||||
// or the pruned module never validates. Fold-then-sweep, once per outer iteration.
|
||||
changed |= sweep_uncalled_functions(module);
|
||||
if sweep_dead_values || cfg_was_pruned {
|
||||
changed |= sweep_uncalled_functions(module);
|
||||
}
|
||||
any |= changed;
|
||||
if !changed {
|
||||
break;
|
||||
|
||||
@@ -195,16 +195,36 @@ pub(in crate::native) fn prune_unreachable(f: &mut crate::spirv_module::Function
|
||||
removed || phi_fixed || merge_fixed
|
||||
}
|
||||
|
||||
/// Replace single-incoming phis with their value (substituting uses module-wide).
|
||||
/// 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.
|
||||
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 {
|
||||
let Some(parent) = block_id(block) else {
|
||||
continue;
|
||||
};
|
||||
if let Some(terminator) = block.instructions.last() {
|
||||
for successor in successors(terminator) {
|
||||
predecessors.entry(successor).or_default().insert(parent);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut repl: HashMap<Word, Word> = HashMap::new();
|
||||
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(v))) =
|
||||
(inst.result_id, inst.operands.first())
|
||||
if let (Some(rid), Some(Operand::IdRef(value)), Some(Operand::IdRef(parent))) =
|
||||
(inst.result_id, inst.operands.first(), inst.operands.get(1))
|
||||
{
|
||||
repl.insert(rid, *v);
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -400,7 +420,7 @@ pub(in crate::native) fn dce_preserving(
|
||||
}
|
||||
|
||||
// Transitive closure: a live pure result keeps its operands live.
|
||||
let mut live: HashSet<Word> = HashSet::new();
|
||||
let mut live = HashSet::new();
|
||||
while let Some(id) = work.pop() {
|
||||
if !live.insert(id) {
|
||||
continue;
|
||||
@@ -454,8 +474,16 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn single_incoming_phi_substitutes_its_concrete_value() {
|
||||
let mut entry = Block::new();
|
||||
entry.label = Some(Instruction::new(Op::Label, None, Some(7), vec![]));
|
||||
entry.instructions = vec![Instruction::new(
|
||||
Op::Branch,
|
||||
None,
|
||||
None,
|
||||
vec![Operand::IdRef(8)],
|
||||
)];
|
||||
let mut block = Block::new();
|
||||
block.label = Some(Instruction::new(Op::Label, None, Some(7), vec![]));
|
||||
block.label = Some(Instruction::new(Op::Label, None, Some(8), vec![]));
|
||||
block.instructions = vec![
|
||||
// The deliberately stale result type models an interface-refined image value still
|
||||
// wrapped in the pointer carrier recorded before CFG edge splitting.
|
||||
@@ -473,12 +501,12 @@ mod tests {
|
||||
),
|
||||
];
|
||||
let mut function = Function::new();
|
||||
function.blocks.push(block);
|
||||
function.blocks = vec![entry, block];
|
||||
|
||||
assert!(collapse_trivial_phis(&mut function));
|
||||
assert_eq!(function.blocks[0].instructions.len(), 1);
|
||||
assert_eq!(function.blocks[1].instructions.len(), 1);
|
||||
assert_eq!(
|
||||
function.blocks[0].instructions[0].operands.first(),
|
||||
function.blocks[1].instructions[0].operands.first(),
|
||||
Some(&Operand::IdRef(5))
|
||||
);
|
||||
}
|
||||
|
||||
@@ -301,11 +301,11 @@ fn accumulate_tir_soundness(
|
||||
}
|
||||
for tb in &tir.blocks {
|
||||
for inst in &tb.insts {
|
||||
for u in &inst.uses {
|
||||
if !defined.contains(u.as_str()) {
|
||||
inst.visit_uses(|u| {
|
||||
if !defined.contains(u) {
|
||||
stats.dangling_uses += 1;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
// Resolved-operand coverage + typed-graph soundness: every `Value` operand's use-site type must
|
||||
@@ -375,8 +375,8 @@ fn accumulate_tir_soundness(
|
||||
/// operands, so its `Value` operands and synthetic-phi incomings reference the SSA universe emission
|
||||
/// actually sees. Built and validated alongside the string path; NOT yet consumed by emission (the
|
||||
/// byte gate guards consumption). Mirrors `emit_function`'s pre-loop exactly: split → lower
|
||||
/// unstructured switches → `structured_plan` (and on a structurizer reject, validate the lowered blocks
|
||||
/// the fallback merge-repair path would walk).
|
||||
/// unstructured switches → `structured_plan` (and on a structurizer reject, validate the lowered
|
||||
/// blocks retained for raw-CFG construction).
|
||||
pub fn tir_structured_self_check(san_ll: &str) -> Result<TirCheckStats, String> {
|
||||
let parsed = LlModule::parse(san_ll)?;
|
||||
let mut stats = TirCheckStats::default();
|
||||
|
||||
+766
-224
File diff suppressed because it is too large.
Load diff
@@ -440,6 +440,16 @@ impl Emitter {
|
||||
.collect::<Vec<_>>();
|
||||
let mut ids = Vec::with_capacity(args.len() + nullness_args.len());
|
||||
for (index, arg, (param_name, param_ty)) in args {
|
||||
if let Some(id) = self.data_buffer_array_call_arg_id(
|
||||
&call.callee,
|
||||
¶m_name,
|
||||
¶m_ty,
|
||||
&arg,
|
||||
instructions,
|
||||
)? {
|
||||
ids.push(id);
|
||||
continue;
|
||||
}
|
||||
if let Some(id) = self.raw_workgroup_call_arg_id(
|
||||
&call.callee,
|
||||
index,
|
||||
@@ -480,6 +490,43 @@ impl Emitter {
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
fn data_buffer_array_call_arg_id(
|
||||
&mut self,
|
||||
callee: &str,
|
||||
param_name: &str,
|
||||
param_ty: &LlType,
|
||||
arg: &TypedValue,
|
||||
instructions: &mut Vec<Instruction>,
|
||||
) -> Result<Option<Word>, String> {
|
||||
if !self.bda_device_pointers
|
||||
|| !matches!(self.resolve_type(param_ty)?, LlType::Ptr(0))
|
||||
|| !self
|
||||
.ir
|
||||
.metadata_data_buffer_params
|
||||
.contains(&(callee.to_string(), param_name.to_string()))
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
let LlValue::Local(arg_name) = &arg.value else {
|
||||
return Ok(None);
|
||||
};
|
||||
if let Some(address) = self.bda_direct_addresses.get(arg_name).copied() {
|
||||
return Ok(Some(address));
|
||||
}
|
||||
if !self.data_buffer_params.contains(arg_name)
|
||||
|| !self.direct_param_indices.contains_key(arg_name)
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
let (low, high) = self.emit_direct_buffer_address_payload(arg_name, instructions)?;
|
||||
let address = self.combine_pointer_payload_words(low, high, instructions)?;
|
||||
self.pointer_payload_words
|
||||
.insert(arg_name.to_string(), (low, high));
|
||||
self.bda_direct_addresses
|
||||
.insert(arg_name.to_string(), address);
|
||||
Ok(Some(address))
|
||||
}
|
||||
|
||||
fn pointer_call_arg_nullness_id(&mut self, value: &LlValue) -> Result<Word, String> {
|
||||
match value {
|
||||
LlValue::Zero => self.const_bool(true),
|
||||
@@ -734,26 +781,44 @@ impl Emitter {
|
||||
if arg_addrspace != 3 {
|
||||
return Ok(None);
|
||||
}
|
||||
let storage = self.pointer_storage_for(&arg.value, arg_addrspace)?;
|
||||
let raw = match &arg.value {
|
||||
LlValue::Local(arg_name) => self.raw_offsets.get(arg_name).cloned(),
|
||||
_ => None,
|
||||
};
|
||||
let storage = if let Some(raw) = &raw {
|
||||
self.raw_access_storage(raw)?
|
||||
} else {
|
||||
self.pointer_storage_for(&arg.value, arg_addrspace)?
|
||||
};
|
||||
if storage != StorageClass::Workgroup {
|
||||
return Ok(None);
|
||||
}
|
||||
let raw_ty = raw_workgroup_array_type();
|
||||
let arg_id = self.value_id_in(&arg.value, &arg.ty, instructions)?;
|
||||
if self
|
||||
.pointer_pointee_for_value(&arg.value)?
|
||||
.is_some_and(|pointee| types_compatible(&pointee, &raw_ty))
|
||||
{
|
||||
return Ok(Some(arg_id));
|
||||
if let Some(raw) = &raw {
|
||||
let root_id = self.raw_root_value_id(raw)?;
|
||||
if self
|
||||
.pointer_pointees
|
||||
.get(&raw.root)
|
||||
.is_some_and(|pointee| types_compatible(pointee, &raw_ty))
|
||||
{
|
||||
return Ok(Some(root_id));
|
||||
}
|
||||
} else {
|
||||
let arg_id = self.value_id_in(&arg.value, &arg.ty, instructions)?;
|
||||
if self
|
||||
.pointer_pointee_for_value(&arg.value)?
|
||||
.is_some_and(|pointee| types_compatible(&pointee, &raw_ty))
|
||||
{
|
||||
return Ok(Some(arg_id));
|
||||
}
|
||||
}
|
||||
// Reinterpreting the typed Workgroup argument pointer to the raw word-array view would require
|
||||
// an `OpBitcast` on a logical pointer — illegal under Logical addressing (the module emits no
|
||||
// VariablePointers/PhysicalStorageBuffer for Workgroup). Such a bitcast is never part of a valid
|
||||
// module, so rather than emit it (a guaranteed spirv-val reject), surface a pointer-typing emit
|
||||
// error that routes to the failure-triggered raw retry (`is_pointer_typing_emit_error` ->
|
||||
// all-buffers-raw-with-workgroup), which models the whole callee buffer raw without a pointer
|
||||
// bitcast. Floor-safe: a banked module never contains this illegal bitcast, so it never reaches
|
||||
// here; a module that did was already failing.
|
||||
// module, so rather than emit it (a guaranteed spirv-val reject), surface a pointer-typing
|
||||
// error. Production raw construction reparses the typed AIR and uses its exact connected-param
|
||||
// raw facts; it does not broaden every Workgroup parameter after this error. A module that
|
||||
// reaches this point therefore fails honestly instead of materializing the illegal bitcast.
|
||||
Err(format!(
|
||||
"native emitter: cannot reinterpret workgroup pointer arg {param_name} to raw word view \
|
||||
without a logical-pointer bitcast (callee {callee})"
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -18,6 +18,112 @@ impl Emitter {
|
||||
}
|
||||
};
|
||||
let parsed_source_ty = self.resolve_type(&gep.source_ty)?;
|
||||
if let LlValue::Local(base_name) = &gep.base.value {
|
||||
if self.pointer_phi_values.contains(base_name)
|
||||
&& !self.raw_offsets.contains_key(base_name)
|
||||
{
|
||||
if let Some(incoming) = self.tir_phi_incomings.get(base_name).cloned() {
|
||||
let base_ty = self.resolve_type(&gep.base.ty)?;
|
||||
self.reserve_bda_address_phi(base_name, &incoming, &base_ty)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
let network_base_pointee = match &gep.base.value {
|
||||
LlValue::Local(base) => self.network_pointees.get(base),
|
||||
_ => None,
|
||||
};
|
||||
let base_pointee = if let Some(pointee) = network_base_pointee {
|
||||
Some(self.resolve_type(pointee)?)
|
||||
} else {
|
||||
self.pointer_pointee_for_value(&gep.base.value)?
|
||||
.as_ref()
|
||||
.map(|ty| self.resolve_type(ty))
|
||||
.transpose()?
|
||||
};
|
||||
if self.null_rooted_pointer_values.contains(name)
|
||||
&& matches!(&gep.base.value, LlValue::Local(base) if self.null_rooted_pointer_values.contains(base))
|
||||
{
|
||||
let storage = self.pointer_storage_for(&gep.base.value, addrspace)?;
|
||||
let pointee = self
|
||||
.network_pointees
|
||||
.get(name)
|
||||
.cloned()
|
||||
.unwrap_or(gep_pointee(&parsed_source_ty, &gep.indices)?);
|
||||
let result_type = self.ptr_type_id(storage, &pointee)?;
|
||||
let result = self.result_id(name, &LlType::Ptr(addrspace))?;
|
||||
self.module.types_global_values.push(Self::inst(
|
||||
Op::Undef,
|
||||
Some(result_type),
|
||||
Some(result),
|
||||
vec![],
|
||||
));
|
||||
self.pointer_storage.insert(name.to_string(), storage);
|
||||
self.pointer_pointees.insert(name.to_string(), pointee);
|
||||
return Ok(Some(result));
|
||||
}
|
||||
// A byte GEP into Workgroup struct padding has no representation in Logical SPIR-V: an
|
||||
// `OpPtrAccessChain %uchar*` cannot reinterpret a `%struct*`. Keep that address symbolic
|
||||
// instead of constructing an instruction which a later pass must delete. Its only supported
|
||||
// consumer is a zero store or memset, which proves the complete written range remains padding
|
||||
// before discarding the unobservable write. Any other consumer fails visibly when it asks for
|
||||
// an id.
|
||||
if parsed_source_ty == LlType::Int(8) && gep.indices.len() == 1 {
|
||||
if let Some(relative) = const_index_i64(&gep.indices[0]) {
|
||||
let deferred = match &gep.base.value {
|
||||
LlValue::Local(base_name) => self
|
||||
.workgroup_padding_byte_pointers
|
||||
.get(base_name)
|
||||
.cloned()
|
||||
.map(|base| {
|
||||
let byte_offset = i128::from(base.byte_offset) + i128::from(relative);
|
||||
(base.struct_ty, byte_offset)
|
||||
}),
|
||||
_ => None,
|
||||
};
|
||||
let direct = if deferred.is_none()
|
||||
&& self.pointer_storage_for(&gep.base.value, addrspace).ok()
|
||||
== Some(StorageClass::Workgroup)
|
||||
&& matches!(base_pointee, Some(LlType::Struct(_)))
|
||||
{
|
||||
Some((
|
||||
base_pointee.clone().expect("matched struct pointee"),
|
||||
i128::from(relative),
|
||||
))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some((struct_ty, byte_offset)) = deferred.or(direct) {
|
||||
let byte_offset = u64::try_from(byte_offset).map_err(|_| {
|
||||
"native emitter: Workgroup padding byte GEP has a negative offset"
|
||||
.to_string()
|
||||
})?;
|
||||
if self.struct_range_is_padding(&struct_ty, byte_offset, 1)? {
|
||||
self.pointer_storage
|
||||
.insert(name.to_string(), StorageClass::Workgroup);
|
||||
self.pointer_pointees
|
||||
.insert(name.to_string(), LlType::Int(8));
|
||||
self.workgroup_padding_byte_pointers.insert(
|
||||
name.to_string(),
|
||||
WorkgroupPaddingBytePointer {
|
||||
struct_ty,
|
||||
byte_offset,
|
||||
},
|
||||
);
|
||||
return Ok(None);
|
||||
}
|
||||
if matches!(
|
||||
&gep.base.value,
|
||||
LlValue::Local(base_name)
|
||||
if self.workgroup_padding_byte_pointers.contains_key(base_name)
|
||||
) {
|
||||
return Err(
|
||||
"native emitter: byte GEP escapes a symbolic Workgroup padding range"
|
||||
.to_string(),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if let LlValue::Local(base_name) = &gep.base.value {
|
||||
if let Some(raw_base) = self.raw_offsets.get(base_name).cloned() {
|
||||
let base_storage = self.pointer_storage_for(&gep.base.value, addrspace)?;
|
||||
@@ -39,20 +145,53 @@ impl Emitter {
|
||||
self.materialize_reserved_raw_word_index(name, &raw, instructions)?;
|
||||
}
|
||||
}
|
||||
if raw.device_addr_base.is_some() {
|
||||
self.materialize_reserved_bda_address(name, &raw, instructions)?;
|
||||
}
|
||||
self.raw_offsets.insert(name.to_string(), raw);
|
||||
if !matches!(pointee, LlType::Ptr(_)) {
|
||||
self.define_unmodeled_pointer_value(name, addrspace, &pointee)?;
|
||||
if let Some(raw) =
|
||||
self.raw_offsets.get(name).cloned().filter(|raw| {
|
||||
self.bda_device_pointers && raw.device_addr_base.is_some()
|
||||
})
|
||||
{
|
||||
let result = self.result_id(name, &LlType::Ptr(addrspace))?;
|
||||
let address = self.materialize_device_address(&raw, instructions)?;
|
||||
let pointer_type =
|
||||
self.ptr_type_id(StorageClass::PhysicalStorageBuffer, &pointee)?;
|
||||
instructions.push(Self::inst(
|
||||
Op::ConvertUToPtr,
|
||||
Some(pointer_type),
|
||||
Some(result),
|
||||
vec![Operand::IdRef(address)],
|
||||
));
|
||||
self.pointer_storage
|
||||
.insert(name.to_string(), StorageClass::PhysicalStorageBuffer);
|
||||
self.pointer_pointees
|
||||
.insert(name.to_string(), pointee.clone());
|
||||
self.used_device_address = true;
|
||||
} else {
|
||||
self.define_unmodeled_pointer_value(name, addrspace, &pointee)?;
|
||||
}
|
||||
}
|
||||
return Ok(self.values.get(name).map(|(id, _)| *id));
|
||||
}
|
||||
if self.unmodeled_pointers.contains(base_name) {
|
||||
let pointee = gep_pointee(&parsed_source_ty, &gep.indices)?;
|
||||
if matches!(pointee, LlType::Ptr(_)) {
|
||||
self.define_unmodeled_byte_pointer_value(name, addrspace)?;
|
||||
} else {
|
||||
self.define_unmodeled_pointer_value(name, addrspace, &pointee)?;
|
||||
let recoverable_field_base = self.values.get(base_name).is_some_and(|(id, _)| {
|
||||
self.emit_sidecar
|
||||
.local_pointer_field_loads
|
||||
.iter()
|
||||
.any(|fact| fact.id == *id)
|
||||
});
|
||||
if !recoverable_field_base {
|
||||
let pointee = gep_pointee(&parsed_source_ty, &gep.indices)?;
|
||||
if matches!(pointee, LlType::Ptr(_)) {
|
||||
self.define_unmodeled_byte_pointer_value(name, addrspace)?;
|
||||
} else {
|
||||
self.define_unmodeled_pointer_value(name, addrspace, &pointee)?;
|
||||
}
|
||||
return Ok(self.values.get(name).map(|(id, _)| *id));
|
||||
}
|
||||
return Ok(self.values.get(name).map(|(id, _)| *id));
|
||||
}
|
||||
if let Some(selected) = self.selected_pointers.get(base_name).cloned() {
|
||||
if self.emit_selected_pointer_gep(
|
||||
@@ -65,6 +204,17 @@ impl Emitter {
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
if let Some(tree) = self.selected_access_trees.get(base_name).cloned() {
|
||||
if self.emit_selected_access_tree_gep(
|
||||
name,
|
||||
&tree,
|
||||
&parsed_source_ty,
|
||||
&gep.indices,
|
||||
instructions,
|
||||
)? {
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
if let Some(selected) = self.selected_load_pointers.get(base_name).cloned() {
|
||||
if self.emit_selected_load_pointer_gep(
|
||||
name,
|
||||
@@ -91,11 +241,6 @@ impl Emitter {
|
||||
}
|
||||
let parsed_base = self.value_id_in(&gep.base.value, &gep.base.ty, instructions)?;
|
||||
let base_storage = self.pointer_storage_for(&gep.base.value, addrspace)?;
|
||||
let base_pointee = self
|
||||
.pointer_pointee_for_value(&gep.base.value)?
|
||||
.as_ref()
|
||||
.map(|ty| self.resolve_type(ty))
|
||||
.transpose()?;
|
||||
let base_points_to_aggregate = base_pointee
|
||||
.as_ref()
|
||||
.is_some_and(|ty| matches!(ty, LlType::Array(_, _) | LlType::Struct(_)));
|
||||
@@ -599,16 +744,17 @@ impl Emitter {
|
||||
for idx in &access_indices {
|
||||
ops.push(Operand::IdRef(self.value_id(&idx.value, &idx.ty)?));
|
||||
}
|
||||
instructions.push(Self::inst(
|
||||
if use_ptr_access_chain {
|
||||
Op::PtrAccessChain
|
||||
} else {
|
||||
Op::InBoundsAccessChain
|
||||
},
|
||||
Some(ptr_type),
|
||||
Some(result),
|
||||
ops,
|
||||
));
|
||||
// A zero-offset LLVM GEP can lower to no SPIR-V indices after its logical root index is
|
||||
// removed. Every SPIR-V access-chain grammar requires at least one index/element operand,
|
||||
// so preserve that identity explicitly instead of serializing a truncated access chain.
|
||||
let opcode = if access_indices.is_empty() {
|
||||
Op::CopyObject
|
||||
} else if use_ptr_access_chain {
|
||||
Op::PtrAccessChain
|
||||
} else {
|
||||
Op::InBoundsAccessChain
|
||||
};
|
||||
instructions.push(Self::inst(opcode, Some(ptr_type), Some(result), ops));
|
||||
self.pointer_storage
|
||||
.insert(name.to_string(), access_storage);
|
||||
self.pointer_pointees
|
||||
@@ -748,6 +894,7 @@ impl Emitter {
|
||||
self.pointer_storage.insert(name.to_string(), base_storage);
|
||||
self.pointer_pointees
|
||||
.insert(name.to_string(), LlType::Int(8));
|
||||
self.byte_view_pointers.insert(name.to_string());
|
||||
if !self.pointer_phi_values.is_empty() {
|
||||
let is_null = self.const_bool(false)?;
|
||||
self.record_pointer_nullness(name.to_string(), is_null);
|
||||
|
||||
@@ -344,7 +344,7 @@ impl Emitter {
|
||||
return Ok(false);
|
||||
};
|
||||
let dst_pointee = function_storage_local_type(&self.resolve_type(&dst_pointee)?);
|
||||
if !matches!(&dst_pointee, LlType::Struct(_)) {
|
||||
if !matches!(&dst_pointee, LlType::Struct(_) | LlType::Array(_, _)) {
|
||||
return Ok(false);
|
||||
}
|
||||
let LlType::Ptr(dst_addrspace) = self.resolve_type(&dst.ty)? else {
|
||||
@@ -480,7 +480,11 @@ impl Emitter {
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
leaf @ (LlType::Int(32) | LlType::Float | LlType::Vector(_, _)) => {
|
||||
leaf @ (LlType::Int(8 | 16 | 32)
|
||||
| LlType::Half
|
||||
| LlType::BFloat
|
||||
| LlType::Float
|
||||
| LlType::Vector(_, _)) => {
|
||||
let Some(value) =
|
||||
self.emit_raw_word_as_typed_memcpy_field(src, base_offset, &leaf, out)?
|
||||
else {
|
||||
@@ -519,10 +523,20 @@ impl Emitter {
|
||||
field: &LlType,
|
||||
instructions: &mut Vec<Instruction>,
|
||||
) -> Result<Option<Word>, String> {
|
||||
if !offset.is_multiple_of(4) {
|
||||
if !offset.is_multiple_of(4)
|
||||
&& !matches!(
|
||||
self.resolve_type(field)?,
|
||||
LlType::Int(8 | 16) | LlType::Half | LlType::BFloat
|
||||
)
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
match self.resolve_type(field)? {
|
||||
scalar @ (LlType::Int(8 | 16) | LlType::Half | LlType::BFloat) => {
|
||||
let value = self.fresh();
|
||||
self.emit_raw_scalar_load(value, &scalar, src, offset, None, instructions)?;
|
||||
Ok(Some(value))
|
||||
}
|
||||
LlType::Int(32) | LlType::Float => {
|
||||
let (field_size, _) = self.raw_type_size_align(field)?;
|
||||
if field_size != 4 {
|
||||
@@ -648,46 +662,29 @@ impl Emitter {
|
||||
let storage_pointee = function_storage_local_type(&pointee);
|
||||
let (size, _) = self.raw_type_size_align(&storage_pointee)?;
|
||||
if len < size {
|
||||
// Partial zero-memset: clearing the first `len` bytes of a LARGER object. When the pointee
|
||||
// is an array and `len` is a whole number of leading elements, clear those elements with one
|
||||
// `OpStore null` each (the byte range [0,len) maps to element indices [0, len/elem_size)) —
|
||||
// a typed lowering that stays valid under Logical addressing, where the alternative (a
|
||||
// generic call to the byte `llvm.memset` declaration whose pointer param is `uchar`) is an
|
||||
// invalid-SPIR-V dead end. A sub-element or struct-spanning partial memset has no clean typed
|
||||
// form, so it still falls through.
|
||||
if let LlType::Array(elem, _) = self.resolve_type(&storage_pointee)? {
|
||||
let elem_ty = self.resolve_type(&elem)?;
|
||||
let (elem_size, _) = self.raw_type_size_align(&elem_ty)?;
|
||||
if elem_size > 0 && len % elem_size == 0 {
|
||||
let LlType::Ptr(addrspace) = self.resolve_type(&call.args[0].ty)? else {
|
||||
return Ok(false);
|
||||
};
|
||||
let storage = self.pointer_storage_for(&call.args[0].value, addrspace)?;
|
||||
let elem_ptr_ty = self.ptr_type_id(storage, &elem_ty)?;
|
||||
let base = self.value_id(&call.args[0].value, &call.args[0].ty)?;
|
||||
let zero = self.const_null(&elem_ty)?;
|
||||
for i in 0..(len / elem_size) {
|
||||
let index = self.const_uint(u32::try_from(i).map_err(|_| {
|
||||
format!("native emitter: memset element index {i} exceeds u32")
|
||||
})?)?;
|
||||
let elem_ptr = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
Op::InBoundsAccessChain,
|
||||
Some(elem_ptr_ty),
|
||||
Some(elem_ptr),
|
||||
vec![Operand::IdRef(base), Operand::IdRef(index)],
|
||||
));
|
||||
instructions.push(Self::inst(
|
||||
Op::Store,
|
||||
None,
|
||||
None,
|
||||
vec![Operand::IdRef(elem_ptr), Operand::IdRef(zero)],
|
||||
));
|
||||
}
|
||||
return Ok(true);
|
||||
}
|
||||
// Logical SPIR-V cannot call LLVM's byte-pointer declaration with a differently typed
|
||||
// aggregate pointer. Lower a prefix clear through the real aggregate layout: fully
|
||||
// covered subobjects receive typed null stores, partial aggregates recurse, and padding
|
||||
// needs no store. A prefix cutting through a scalar remains an honest unsupported emit.
|
||||
let LlType::Ptr(addrspace) = self.resolve_type(&call.args[0].ty)? else {
|
||||
return Ok(false);
|
||||
};
|
||||
let storage = self.pointer_storage_for(&call.args[0].value, addrspace)?;
|
||||
let base = self.value_id(&call.args[0].value, &call.args[0].ty)?;
|
||||
if self.emit_typed_zero_prefix(
|
||||
base,
|
||||
storage,
|
||||
&storage_pointee,
|
||||
0,
|
||||
len,
|
||||
&mut Vec::new(),
|
||||
instructions,
|
||||
)? {
|
||||
return Ok(true);
|
||||
}
|
||||
return Ok(false);
|
||||
return Err(format!(
|
||||
"native emitter: partial zero memset cuts through a scalar subobject of {storage_pointee:?}"
|
||||
));
|
||||
}
|
||||
let ptr = self.value_id(&call.args[0].value, &call.args[0].ty)?;
|
||||
let zero = self.const_null(&storage_pointee)?;
|
||||
@@ -700,6 +697,109 @@ impl Emitter {
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn emit_typed_zero_prefix(
|
||||
&mut self,
|
||||
base: Word,
|
||||
storage: StorageClass,
|
||||
ty: &LlType,
|
||||
offset: u64,
|
||||
end: u64,
|
||||
indices: &mut Vec<Word>,
|
||||
instructions: &mut Vec<Instruction>,
|
||||
) -> Result<bool, String> {
|
||||
let ty = function_storage_local_type(&self.resolve_type(ty)?);
|
||||
let (size, _) = self.raw_type_size_align(&ty)?;
|
||||
if size == 0 || offset >= end {
|
||||
return Ok(true);
|
||||
}
|
||||
if offset
|
||||
.checked_add(size)
|
||||
.is_some_and(|object_end| object_end <= end)
|
||||
{
|
||||
let pointer = if indices.is_empty() {
|
||||
base
|
||||
} else {
|
||||
let pointer_type = self.ptr_type_id(storage, &ty)?;
|
||||
let pointer = self.fresh();
|
||||
let mut operands = Vec::with_capacity(indices.len() + 1);
|
||||
operands.push(Operand::IdRef(base));
|
||||
operands.extend(indices.iter().copied().map(Operand::IdRef));
|
||||
instructions.push(Self::inst(
|
||||
Op::InBoundsAccessChain,
|
||||
Some(pointer_type),
|
||||
Some(pointer),
|
||||
operands,
|
||||
));
|
||||
pointer
|
||||
};
|
||||
let zero = self.const_null(&ty)?;
|
||||
instructions.push(Self::inst(
|
||||
Op::Store,
|
||||
None,
|
||||
None,
|
||||
vec![Operand::IdRef(pointer), Operand::IdRef(zero)],
|
||||
));
|
||||
return Ok(true);
|
||||
}
|
||||
match ty {
|
||||
LlType::Struct(fields) => {
|
||||
for index in 0..fields.len() {
|
||||
let (member_offset, field) = self.raw_struct_member(&fields, index as u64)?;
|
||||
let index = self.const_uint(index as u32)?;
|
||||
indices.push(index);
|
||||
let supported = self.emit_typed_zero_prefix(
|
||||
base,
|
||||
storage,
|
||||
&field,
|
||||
offset.checked_add(member_offset).ok_or_else(|| {
|
||||
"native emitter: partial memset struct offset overflows u64".to_string()
|
||||
})?,
|
||||
end,
|
||||
indices,
|
||||
instructions,
|
||||
)?;
|
||||
indices.pop();
|
||||
if !supported {
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
LlType::Array(elem, count) | LlType::Vector(elem, count) => {
|
||||
let elem = function_storage_local_type(&self.resolve_type(&elem)?);
|
||||
let (elem_size, elem_align) = self.raw_type_size_align(&elem)?;
|
||||
let stride = round_up_u64(elem_size, elem_align);
|
||||
for index in 0..count {
|
||||
let index_id = self.const_uint(index)?;
|
||||
indices.push(index_id);
|
||||
let element_offset = u64::from(index)
|
||||
.checked_mul(stride)
|
||||
.and_then(|relative| offset.checked_add(relative))
|
||||
.ok_or_else(|| {
|
||||
"native emitter: partial memset aggregate offset overflows u64"
|
||||
.to_string()
|
||||
})?;
|
||||
let supported = self.emit_typed_zero_prefix(
|
||||
base,
|
||||
storage,
|
||||
&elem,
|
||||
element_offset,
|
||||
end,
|
||||
indices,
|
||||
instructions,
|
||||
)?;
|
||||
indices.pop();
|
||||
if !supported {
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
_ => Ok(false),
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::native::emitter) fn emit_raw_zero_memset(
|
||||
&mut self,
|
||||
raw: &RawBufferOffset,
|
||||
@@ -730,6 +830,17 @@ impl Emitter {
|
||||
len: u64,
|
||||
instructions: &mut Vec<Instruction>,
|
||||
) -> Result<bool, String> {
|
||||
if let LlValue::Local(name) = &dst.value {
|
||||
if let Some(padding) = self.workgroup_padding_byte_pointers.get(name).cloned() {
|
||||
if self.struct_range_is_padding(&padding.struct_ty, padding.byte_offset, len)? {
|
||||
return Ok(true);
|
||||
}
|
||||
return Err(format!(
|
||||
"native emitter: zero memset from Workgroup struct padding offset {} spans non-padding bytes",
|
||||
padding.byte_offset
|
||||
));
|
||||
}
|
||||
}
|
||||
let Some(pointee) = self.pointer_pointee_for_value(&dst.value)? else {
|
||||
return Ok(false);
|
||||
};
|
||||
@@ -774,6 +885,37 @@ impl Emitter {
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub(in crate::native::emitter) fn struct_range_is_padding(
|
||||
&self,
|
||||
struct_ty: &LlType,
|
||||
byte_offset: u64,
|
||||
len: u64,
|
||||
) -> Result<bool, String> {
|
||||
let LlType::Struct(fields) = self.resolve_type(struct_ty)? else {
|
||||
return Ok(false);
|
||||
};
|
||||
let end = byte_offset.checked_add(len).ok_or_else(|| {
|
||||
"native emitter: Workgroup padding byte range overflows u64".to_string()
|
||||
})?;
|
||||
let (struct_size, _) = self.raw_type_size_align(struct_ty)?;
|
||||
if len == 0 || end > struct_size {
|
||||
return Ok(false);
|
||||
}
|
||||
let mut member_offset = 0u64;
|
||||
for field in &fields {
|
||||
let (field_size, field_align) = self.raw_type_size_align(field)?;
|
||||
member_offset = round_up_u64(member_offset, field_align);
|
||||
let member_end = member_offset.checked_add(field_size).ok_or_else(|| {
|
||||
"native emitter: Workgroup struct member range overflows u64".to_string()
|
||||
})?;
|
||||
if byte_offset < member_end && end > member_offset {
|
||||
return Ok(false);
|
||||
}
|
||||
member_offset = member_end;
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub(in crate::native::emitter) fn emit_typed_memcpy(
|
||||
&mut self,
|
||||
call: &LlCall,
|
||||
@@ -852,6 +994,37 @@ impl Emitter {
|
||||
return Ok(true);
|
||||
}
|
||||
|
||||
// LLVM may pass an array object directly as the destination of an exact one-element
|
||||
// memcpy. Opaque pointers erase the source-level array-to-first-element decay, but SPIR-V
|
||||
// retains the aggregate pointee and therefore needs that access chain constructed
|
||||
// explicitly. Limit this to one complete source object; a longer byte range would require
|
||||
// source extent information that the erased pointer does not provide.
|
||||
if let LlType::Array(dst_element, count) = &dst_pointee {
|
||||
if *count > 0 && len == copy_size && types_compatible(dst_element, &src_pointee) {
|
||||
let dst = self.value_id(&call.args[0].value, &call.args[0].ty)?;
|
||||
let dst_element = function_storage_local_type(dst_element);
|
||||
let dst_ptr_ty = self.ptr_type_id(dst_storage, &dst_element)?;
|
||||
let dst_element_ptr = self.fresh();
|
||||
let zero = self.const_uint(0)?;
|
||||
instructions.push(Self::inst(
|
||||
Op::InBoundsAccessChain,
|
||||
Some(dst_ptr_ty),
|
||||
Some(dst_element_ptr),
|
||||
vec![Operand::IdRef(dst), Operand::IdRef(zero)],
|
||||
));
|
||||
return self.emit_aggregate_memcpy(
|
||||
dst_element_ptr,
|
||||
src,
|
||||
dst_storage,
|
||||
src_storage,
|
||||
&dst_element,
|
||||
&src_pointee,
|
||||
len,
|
||||
instructions,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// A named AIR wrapper can contain the exact aggregate copied into a bare local array
|
||||
// (`metal::matrix<T>` -> its `[N x vector<T>]` storage). Descend through the source's
|
||||
// offset-zero field just as the symmetric destination-wrapper path below does. The helper's
|
||||
@@ -1077,9 +1250,20 @@ impl Emitter {
|
||||
}
|
||||
let src_field = function_storage_local_type(&src_field);
|
||||
let dst_pointee = function_storage_local_type(dst_pointee);
|
||||
if !types_compatible(&dst_pointee, &src_field) {
|
||||
return Ok(false);
|
||||
}
|
||||
// A memcpy starting at an array object and spanning one element addresses element zero.
|
||||
// Opaque LLVM pointers erase that decay: `%dst = alloca [N x T]` is passed directly while
|
||||
// the source is a wrapper struct whose first field is `T`. Construct the element-zero
|
||||
// pointer explicitly instead of leaving a residual byte-pointer memcpy call whose declared
|
||||
// SPIR-V parameter cannot match the aggregate pointer value.
|
||||
let (dst_copy_pointee, decay_destination_array) = match &dst_pointee {
|
||||
LlType::Array(element, count)
|
||||
if *count > 0 && types_compatible(element, &src_field) =>
|
||||
{
|
||||
(function_storage_local_type(element), true)
|
||||
}
|
||||
_ if types_compatible(&dst_pointee, &src_field) => (dst_pointee.clone(), false),
|
||||
_ => return Ok(false),
|
||||
};
|
||||
let (field_size, _) = self.raw_type_size_align(&src_field)?;
|
||||
if len > field_size {
|
||||
return Ok(false);
|
||||
@@ -1093,11 +1277,22 @@ impl Emitter {
|
||||
};
|
||||
let dst_storage = self.pointer_storage_for(&dst_arg.value, dst_addrspace)?;
|
||||
let src_storage = self.pointer_storage_for(&src_arg.value, src_addrspace)?;
|
||||
let dst = self.value_id(&dst_arg.value, &dst_arg.ty)?;
|
||||
let mut dst = self.value_id(&dst_arg.value, &dst_arg.ty)?;
|
||||
let src = self.value_id(&src_arg.value, &src_arg.ty)?;
|
||||
let zero = self.const_uint(0)?;
|
||||
if decay_destination_array {
|
||||
let dst_ptr_ty = self.ptr_type_id(dst_storage, &dst_copy_pointee)?;
|
||||
let dst_element = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
Op::InBoundsAccessChain,
|
||||
Some(dst_ptr_ty),
|
||||
Some(dst_element),
|
||||
vec![Operand::IdRef(dst), Operand::IdRef(zero)],
|
||||
));
|
||||
dst = dst_element;
|
||||
}
|
||||
let src_ptr_ty = self.ptr_type_id(src_storage, &src_field)?;
|
||||
let src_field_ptr = self.fresh();
|
||||
let zero = self.const_uint(0)?;
|
||||
instructions.push(Self::inst(
|
||||
Op::InBoundsAccessChain,
|
||||
Some(src_ptr_ty),
|
||||
@@ -1109,7 +1304,7 @@ impl Emitter {
|
||||
src_field_ptr,
|
||||
dst_storage,
|
||||
src_storage,
|
||||
&dst_pointee,
|
||||
&dst_copy_pointee,
|
||||
&src_field,
|
||||
len,
|
||||
instructions,
|
||||
|
||||
@@ -3,6 +3,86 @@
|
||||
use super::*;
|
||||
|
||||
impl Emitter {
|
||||
pub(in crate::native::emitter) fn emit_aggregate_prefix_pointer_reinterpret_load(
|
||||
&mut self,
|
||||
result_name: &str,
|
||||
pointee: &LlType,
|
||||
result_ty: &LlType,
|
||||
ptr_value: &TypedValue,
|
||||
ptr: Word,
|
||||
instructions: &mut Vec<Instruction>,
|
||||
) -> Result<bool, String> {
|
||||
if !self.bda_device_pointers || !matches!(result_ty, LlType::Ptr(_)) {
|
||||
return Ok(false);
|
||||
}
|
||||
let storage = match self.resolve_type(&ptr_value.ty)? {
|
||||
LlType::Ptr(addrspace) => self.pointer_storage_for(&ptr_value.value, addrspace)?,
|
||||
other => {
|
||||
return Err(format!(
|
||||
"native emitter: load pointer is not a pointer: {other:?}"
|
||||
))
|
||||
}
|
||||
};
|
||||
let (address, payload_words) = if let Some((field_ty, access_path)) =
|
||||
first_aggregate_leaf(pointee, &|ty| *ty == LlType::Int(64), false)
|
||||
{
|
||||
let field_ptr_ty = self.ptr_type_id(storage, &field_ty)?;
|
||||
let field_ptr = self.fresh();
|
||||
let mut operands = vec![Operand::IdRef(ptr)];
|
||||
for index in access_path {
|
||||
operands.push(Operand::IdRef(self.const_uint(index)?));
|
||||
}
|
||||
instructions.push(Self::inst(
|
||||
Op::InBoundsAccessChain,
|
||||
Some(field_ptr_ty),
|
||||
Some(field_ptr),
|
||||
operands,
|
||||
));
|
||||
let field_type = self.type_id(&field_ty)?;
|
||||
let address = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
Op::Load,
|
||||
Some(field_type),
|
||||
Some(address),
|
||||
vec![Operand::IdRef(field_ptr)],
|
||||
));
|
||||
(address, None)
|
||||
} else {
|
||||
let Some(fields) = self.leading_i32_scalar_accesses(pointee, 8)? else {
|
||||
return Ok(false);
|
||||
};
|
||||
if fields.len() != 2 {
|
||||
return Ok(false);
|
||||
}
|
||||
let mut words = fields.into_iter().map(|(access_path, field_ty)| {
|
||||
self.emit_i32_scalar_field_load(ptr, storage, &access_path, &field_ty, instructions)
|
||||
});
|
||||
let low = words.next().transpose()?.expect("two leading words");
|
||||
let high = words.next().transpose()?.expect("two leading words");
|
||||
(
|
||||
self.combine_pointer_payload_words(low, high, instructions)?,
|
||||
Some((low, high)),
|
||||
)
|
||||
};
|
||||
self.emit_device_address_nullness(result_name, address, instructions)?;
|
||||
let LlType::Ptr(addrspace) = result_ty else {
|
||||
unreachable!()
|
||||
};
|
||||
let mut raw = RawBufferOffset::root(format!(".bda_{address}"), *addrspace);
|
||||
raw.device_addr_base = Some(address);
|
||||
self.raw_offsets.insert(result_name.to_string(), raw);
|
||||
if let Some(payload_words) = payload_words {
|
||||
self.pointer_payload_words
|
||||
.insert(result_name.to_string(), payload_words);
|
||||
}
|
||||
self.pointer_storage
|
||||
.insert(result_name.to_string(), StorageClass::PhysicalStorageBuffer);
|
||||
self.pointer_pointees
|
||||
.insert(result_name.to_string(), LlType::Int(8));
|
||||
self.used_device_address = true;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub(in crate::native::emitter) fn emit_i32_pair_struct_to_i64_load(
|
||||
&mut self,
|
||||
result: Word,
|
||||
@@ -156,7 +236,28 @@ impl Emitter {
|
||||
};
|
||||
|
||||
let ptr_id = self.value_id(&ptr.value, &ptr.ty)?;
|
||||
let object_id = self.value_id(&object.value, &object.ty)?;
|
||||
if self.bda_device_pointers && *pointee == LlType::Int(64) {
|
||||
if let LlValue::Local(object_name) = &object.value {
|
||||
if let Some(address) = self.bda_direct_addresses.get(object_name).copied() {
|
||||
self.emit_sidecar.local_pointer_field_stores.push(
|
||||
crate::emit_sidecar::LocalPointerFieldStore {
|
||||
id: address,
|
||||
source: address,
|
||||
root: key.root,
|
||||
indices: key.indices.clone(),
|
||||
},
|
||||
);
|
||||
instructions.push(Self::inst(
|
||||
Op::Store,
|
||||
None,
|
||||
None,
|
||||
vec![Operand::IdRef(ptr_id), Operand::IdRef(address)],
|
||||
));
|
||||
self.local_pointer_fields.insert(key, object.clone());
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
let zero_ty = self.type_id(&LlType::Int(64))?;
|
||||
let zero = self.fresh();
|
||||
self.module.types_global_values.push(Self::inst(
|
||||
@@ -165,10 +266,19 @@ impl Emitter {
|
||||
Some(zero),
|
||||
vec![],
|
||||
));
|
||||
// Local pointer fields use an integer payload plus the typed sidecar carrier. A literal
|
||||
// null/undef has no pointer payload to preserve: its exact stored representation is this
|
||||
// integer zero. Do not construct a Private/Function OpConstantNull merely to name the
|
||||
// sidecar source; such logical pointer constants are not legal Vulkan SPIR-V.
|
||||
let source = if matches!(object.value, LlValue::Zero | LlValue::Undef) {
|
||||
zero
|
||||
} else {
|
||||
self.value_id(&object.value, &object.ty)?
|
||||
};
|
||||
self.emit_sidecar.local_pointer_field_stores.push(
|
||||
crate::emit_sidecar::LocalPointerFieldStore {
|
||||
id: zero,
|
||||
source: object_id,
|
||||
source,
|
||||
root: key.root,
|
||||
indices: key.indices.clone(),
|
||||
},
|
||||
@@ -201,6 +311,33 @@ 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)
|
||||
{
|
||||
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;
|
||||
return Ok(true);
|
||||
}
|
||||
self.emit_pointer_from_local_field_key(result_name, result, result_ty, &key, instructions)?;
|
||||
Ok(true)
|
||||
}
|
||||
@@ -218,12 +355,30 @@ impl Emitter {
|
||||
"native emitter: local pointer field loaded as non-pointer {result_ty:?}"
|
||||
));
|
||||
};
|
||||
let stored = (!self
|
||||
.ir
|
||||
.preinlined_helper_pointer_loads
|
||||
.contains(result_name))
|
||||
.then(|| self.local_pointer_fields.get(key).cloned())
|
||||
.flatten();
|
||||
let stored = self
|
||||
.local_pointer_fields
|
||||
.get(key)
|
||||
.cloned()
|
||||
.filter(|stored| {
|
||||
if !self
|
||||
.ir
|
||||
.preinlined_helper_pointer_loads
|
||||
.contains(result_name)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
match &stored.value {
|
||||
LlValue::Local(source_name) => {
|
||||
self.bda_direct_addresses.contains_key(source_name)
|
||||
|| self.raw_offsets.get(source_name).is_some_and(|raw| {
|
||||
raw.device_addr_base.is_some()
|
||||
|| self.bda_direct_addresses.contains_key(&raw.root)
|
||||
})
|
||||
|| self.bda_phi_value_is_addressable(&stored.value)
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
});
|
||||
let Some(stored) = stored else {
|
||||
self.emit_unmodeled_byte_pointer_copy(result_name, result, *addrspace, instructions)?;
|
||||
self.emit_sidecar.local_pointer_field_loads.push(
|
||||
@@ -235,39 +390,110 @@ impl Emitter {
|
||||
);
|
||||
return Ok(());
|
||||
};
|
||||
self.pointer_forward_values
|
||||
.insert(result_name.to_string(), stored.clone());
|
||||
|
||||
if matches!(stored.value, LlValue::Zero | LlValue::Undef) {
|
||||
let storage = self.pointer_storage_for(&stored.value, *addrspace)?;
|
||||
let pointee = self
|
||||
.pointer_pointee_for_value(&stored.value)?
|
||||
.unwrap_or(LlType::Int(8));
|
||||
let result_type = self.ptr_type_id(storage, &pointee)?;
|
||||
self.module.types_global_values.push(Self::inst(
|
||||
Op::Undef,
|
||||
Some(result_type),
|
||||
Some(result),
|
||||
vec![],
|
||||
));
|
||||
self.pointer_storage
|
||||
.insert(result_name.to_string(), storage);
|
||||
self.pointer_pointees
|
||||
.insert(result_name.to_string(), pointee);
|
||||
let is_null = self.const_bool(true)?;
|
||||
self.record_pointer_nullness(result_name.to_string(), is_null);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if let LlValue::Local(source_name) = &stored.value {
|
||||
if self.pointer_phi_values.contains(source_name)
|
||||
&& !self.raw_offsets.contains_key(source_name)
|
||||
{
|
||||
if let Some(incoming) = self.tir_phi_incomings.get(source_name).cloned() {
|
||||
let source_ty = self.resolve_type(&stored.ty)?;
|
||||
self.reserve_bda_address_phi(source_name, &incoming, &source_ty)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let storage = self.pointer_storage_for(&stored.value, *addrspace)?;
|
||||
let pointee = self
|
||||
.pointer_pointee_for_value(&stored.value)?
|
||||
.unwrap_or(LlType::Int(8));
|
||||
let result_type = self.ptr_type_id(storage, &pointee)?;
|
||||
let source = self.value_id_in(&stored.value, &stored.ty, instructions)?;
|
||||
let address = if self.bda_device_pointers {
|
||||
match &stored.value {
|
||||
LlValue::Local(source_name) => self
|
||||
.bda_direct_addresses
|
||||
.get(source_name)
|
||||
.copied()
|
||||
.or_else(|| {
|
||||
self.raw_offsets.get(source_name).and_then(|raw| {
|
||||
raw.device_addr_base
|
||||
.or_else(|| self.bda_direct_addresses.get(&raw.root).copied())
|
||||
})
|
||||
}),
|
||||
_ => None,
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let (result_type, source) = if let Some(address) = address {
|
||||
self.bda_direct_addresses
|
||||
.insert(result_name.to_string(), result);
|
||||
let mut raw = RawBufferOffset::root(format!(".bda_{result}"), *addrspace);
|
||||
raw.device_addr_base = Some(result);
|
||||
self.raw_offsets.insert(result_name.to_string(), raw);
|
||||
(self.type_id(&LlType::Int(64))?, address)
|
||||
} else {
|
||||
(
|
||||
self.ptr_type_id(storage, &pointee)?,
|
||||
self.value_id_in(&stored.value, &stored.ty, instructions)?,
|
||||
)
|
||||
};
|
||||
instructions.push(Self::inst(
|
||||
Op::CopyObject,
|
||||
Some(result_type),
|
||||
Some(result),
|
||||
vec![Operand::IdRef(source)],
|
||||
));
|
||||
// This is only a pointer-typed copy until interface binding gives an opaque AIR resource
|
||||
// parameter its final SPIR-V image/sampler type. Preserve the field identity even on the
|
||||
// emitter's fast path so `recover_inlined_local_pointer_fields` can replace the copy with
|
||||
// its stored source before that retyping. Without this fact, binding a texture held in a
|
||||
// private aggregate rewrites only the operand to an OpTypeImage and leaves an invalid
|
||||
// pointer-typed OpCopyObject behind.
|
||||
self.emit_sidecar.local_pointer_field_loads.push(
|
||||
crate::emit_sidecar::LocalPointerFieldLoad {
|
||||
id: result,
|
||||
root: key.root,
|
||||
indices: key.indices.clone(),
|
||||
// A logical pointer copy can still be an opaque AIR resource handle whose final image or
|
||||
// sampler type is assigned during interface binding. Preserve that field identity so the
|
||||
// recovery pass can forward its stored source before retyping. A physical-address copy is
|
||||
// already the final 64-bit representation; marking it as a logical field load would make
|
||||
// recovery replace the address with the original pointer-typed SSA id.
|
||||
if address.is_none() {
|
||||
self.emit_sidecar.local_pointer_field_loads.push(
|
||||
crate::emit_sidecar::LocalPointerFieldLoad {
|
||||
id: result,
|
||||
root: key.root,
|
||||
indices: key.indices.clone(),
|
||||
},
|
||||
);
|
||||
}
|
||||
self.pointer_storage.insert(
|
||||
result_name.to_string(),
|
||||
if address.is_some() {
|
||||
StorageClass::PhysicalStorageBuffer
|
||||
} else {
|
||||
storage
|
||||
},
|
||||
);
|
||||
self.pointer_storage
|
||||
.insert(result_name.to_string(), storage);
|
||||
self.pointer_pointees
|
||||
.insert(result_name.to_string(), pointee);
|
||||
if let LlValue::Local(source_name) = &stored.value {
|
||||
if let Some(raw) = self.raw_offsets.get(source_name).cloned() {
|
||||
self.raw_offsets.insert(result_name.to_string(), raw);
|
||||
if address.is_none() {
|
||||
if let Some(raw) = self.raw_offsets.get(source_name).cloned() {
|
||||
self.raw_offsets.insert(result_name.to_string(), raw);
|
||||
}
|
||||
}
|
||||
if let Some(nullness) = self.pointer_nullness.get(source_name).copied() {
|
||||
self.record_pointer_nullness(result_name.to_string(), nullness);
|
||||
@@ -845,8 +1071,13 @@ impl Emitter {
|
||||
ptr: Word,
|
||||
instructions: &mut Vec<Instruction>,
|
||||
) -> Result<bool, String> {
|
||||
let LlType::Array(elem, len) = pointee else {
|
||||
return Ok(false);
|
||||
let (elem, len) = match pointee {
|
||||
LlType::Array(elem, len) => (elem, len),
|
||||
// SPIR-V's native vector width stops at four lanes. Wider LLVM byte vectors are emitted
|
||||
// as fixed arrays, so dereferencing one through an opaque-pointer alias requires the
|
||||
// same byte-wise value reconstruction as an LLVM array.
|
||||
LlType::Vector(elem, len) if *len > 4 => (elem, len),
|
||||
_ => return Ok(false),
|
||||
};
|
||||
if elem.as_ref() != &LlType::Int(8) {
|
||||
return Ok(false);
|
||||
@@ -945,6 +1176,131 @@ impl Emitter {
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Reconstruct an integer load whose LLVM GEP selects one byte inside a fixed byte-array leaf
|
||||
/// of Function/Private aggregate storage. Logical SPIR-V cannot widen that leaf pointer or walk
|
||||
/// to its sibling bytes with `OpPtrAccessChain`; replay the aggregate path once per byte and
|
||||
/// pack the loads little-endian instead.
|
||||
pub(in crate::native::emitter) fn emit_trailing_byte_array_integer_load(
|
||||
&mut self,
|
||||
result: Word,
|
||||
result_ty: &LlType,
|
||||
ptr_value: &TypedValue,
|
||||
instructions: &mut Vec<Instruction>,
|
||||
) -> Result<bool, String> {
|
||||
let LlValue::Local(pointer_name) = &ptr_value.value else {
|
||||
return Ok(false);
|
||||
};
|
||||
let Some(provenance) = self.gep_provenance.get(pointer_name).cloned() else {
|
||||
return Ok(false);
|
||||
};
|
||||
let storage = self.pointer_storage_for(&ptr_value.value, provenance.addrspace)?;
|
||||
if !matches!(storage, StorageClass::Function | StorageClass::Private) {
|
||||
return Ok(false);
|
||||
}
|
||||
let LlType::Int(bits) = self.resolve_type(result_ty)? else {
|
||||
return Ok(false);
|
||||
};
|
||||
if bits == 0 || bits % 8 != 0 || provenance.indices.len() < 2 {
|
||||
return Ok(false);
|
||||
}
|
||||
let byte_count = bits / 8;
|
||||
let Some(first_byte) = const_index(provenance.indices.last()) else {
|
||||
return Ok(false);
|
||||
};
|
||||
let parent = self.resolve_type(&gep_pointee(
|
||||
&provenance.source_ty,
|
||||
&provenance.indices[..provenance.indices.len() - 1],
|
||||
)?)?;
|
||||
let LlType::Array(element, length) = parent else {
|
||||
return Ok(false);
|
||||
};
|
||||
if self.resolve_type(&element)? != LlType::Int(8)
|
||||
|| first_byte
|
||||
.checked_add(byte_count)
|
||||
.is_none_or(|end| end > length)
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
let byte_ty = self.type_id(&LlType::Int(8))?;
|
||||
let byte_ptr_ty = self.ptr_type_id(storage, &LlType::Int(8))?;
|
||||
let result_ty_id = self.type_id(result_ty)?;
|
||||
let mut acc = None;
|
||||
for byte in 0..byte_count {
|
||||
let mut indices = provenance.indices.clone();
|
||||
let last = indices.last_mut().expect("checked non-empty index path");
|
||||
last.value = LlValue::Int(u64::from(first_byte + byte));
|
||||
let mut operands = vec![Operand::IdRef(provenance.root)];
|
||||
for index in gep_spirv_indices(&indices)? {
|
||||
operands.push(Operand::IdRef(self.value_id(&index.value, &index.ty)?));
|
||||
}
|
||||
let byte_ptr = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
Op::InBoundsAccessChain,
|
||||
Some(byte_ptr_ty),
|
||||
Some(byte_ptr),
|
||||
operands,
|
||||
));
|
||||
let loaded = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
Op::Load,
|
||||
Some(byte_ty),
|
||||
Some(loaded),
|
||||
vec![Operand::IdRef(byte_ptr)],
|
||||
));
|
||||
let widened = if bits == 8 {
|
||||
loaded
|
||||
} else {
|
||||
let widened = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
Op::UConvert,
|
||||
Some(result_ty_id),
|
||||
Some(widened),
|
||||
vec![Operand::IdRef(loaded)],
|
||||
));
|
||||
widened
|
||||
};
|
||||
let term = if byte == 0 {
|
||||
widened
|
||||
} else {
|
||||
let shifted = self.fresh();
|
||||
let shift = self.const_signed_int(bits, i64::from(byte * 8))?;
|
||||
instructions.push(Self::inst(
|
||||
Op::ShiftLeftLogical,
|
||||
Some(result_ty_id),
|
||||
Some(shifted),
|
||||
vec![Operand::IdRef(widened), Operand::IdRef(shift)],
|
||||
));
|
||||
shifted
|
||||
};
|
||||
acc = Some(if let Some(previous) = acc {
|
||||
let combined = if byte + 1 == byte_count {
|
||||
result
|
||||
} else {
|
||||
self.fresh()
|
||||
};
|
||||
instructions.push(Self::inst(
|
||||
Op::BitwiseOr,
|
||||
Some(result_ty_id),
|
||||
Some(combined),
|
||||
vec![Operand::IdRef(previous), Operand::IdRef(term)],
|
||||
));
|
||||
combined
|
||||
} else {
|
||||
term
|
||||
});
|
||||
}
|
||||
if acc != Some(result) {
|
||||
instructions.push(Self::inst(
|
||||
Op::CopyObject,
|
||||
Some(result_ty_id),
|
||||
Some(result),
|
||||
vec![Operand::IdRef(acc.expect("positive byte count"))],
|
||||
));
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub(in crate::native::emitter) fn local_pointer_field_key(
|
||||
&self,
|
||||
ptr: &TypedValue,
|
||||
@@ -952,9 +1308,6 @@ impl Emitter {
|
||||
let LlValue::Local(name) = &ptr.value else {
|
||||
return Ok(None);
|
||||
};
|
||||
let Some(provenance) = self.gep_provenance.get(name) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let LlType::Ptr(addrspace) = self.resolve_type(&ptr.ty)? else {
|
||||
return Err(format!(
|
||||
"native emitter: local pointer field key for non-pointer {:?}",
|
||||
@@ -965,6 +1318,24 @@ impl Emitter {
|
||||
if !matches!(storage, StorageClass::Function | StorageClass::Private) {
|
||||
return Ok(None);
|
||||
}
|
||||
let Some(provenance) = self.gep_provenance.get(name) else {
|
||||
// A direct `alloca ptr` is itself the complete local pointer field. Its pointee was
|
||||
// stored as an i64 payload by `function_storage_local_type`, but the typed pointer fact
|
||||
// remains in `pointer_pointees`; use the allocation id as an empty-path field root so
|
||||
// pointer stores and later loads share the same address-domain record.
|
||||
if storage == StorageClass::Function
|
||||
&& self
|
||||
.pointer_pointees
|
||||
.get(name)
|
||||
.is_some_and(local_pointer_field_pointee)
|
||||
{
|
||||
return Ok(self.values.get(name).map(|(root, _)| LocalPointerField {
|
||||
root: *root,
|
||||
indices: Vec::new(),
|
||||
}));
|
||||
}
|
||||
return Ok(None);
|
||||
};
|
||||
let Some(mut indices) = provenance
|
||||
.indices
|
||||
.iter()
|
||||
|
||||
@@ -778,7 +778,7 @@ impl Emitter {
|
||||
Ok(types_compatible(
|
||||
&gep_pointee(&provenance.source_ty, &provenance.indices)?,
|
||||
elem,
|
||||
))
|
||||
) && self.gep_provenance_strides_contiguous(ptr, elem)?)
|
||||
}
|
||||
|
||||
pub(in crate::native::emitter) fn emit_gep_provenance_lane_ptr(
|
||||
|
||||
@@ -67,13 +67,29 @@ impl Emitter {
|
||||
else {
|
||||
return Ok(false);
|
||||
};
|
||||
if array_len != vector_len || !types_compatible(array_elem, vector_elem) {
|
||||
if array_len != vector_len
|
||||
|| !is_scalar_storage_type(array_elem)
|
||||
|| !is_scalar_storage_type(vector_elem)
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
let elements_are_compatible = types_compatible(array_elem, vector_elem);
|
||||
if !elements_are_compatible {
|
||||
let (Some(array_elem_bits), Some(vector_elem_bits)) =
|
||||
(bitcast_width(array_elem), bitcast_width(vector_elem))
|
||||
else {
|
||||
return Ok(false);
|
||||
};
|
||||
if array_elem_bits != vector_elem_bits {
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
|
||||
// LLVM permits a vector load through an opaque pointer whose allocation is an equivalent
|
||||
// fixed scalar array. Logical SPIR-V cannot bitcast the pointer or the aggregate value, so
|
||||
// load the array and rebuild the vector lane-for-lane.
|
||||
// load the array and rebuild the vector lane-for-lane. When the scalar interpretations
|
||||
// differ, reinterpret each same-width lane rather than changing the pointer's storage
|
||||
// model or attempting an illegal aggregate bitcast.
|
||||
let array_type = self.type_id(pointee)?;
|
||||
let loaded = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
@@ -82,16 +98,30 @@ impl Emitter {
|
||||
Some(loaded),
|
||||
vec![Operand::IdRef(ptr)],
|
||||
));
|
||||
let elem_type = self.type_id(vector_elem)?;
|
||||
let array_elem_type = self.type_id(array_elem)?;
|
||||
let vector_elem_type = self.type_id(vector_elem)?;
|
||||
let elements_need_bitcast = !elements_are_compatible && array_elem_type != vector_elem_type;
|
||||
let mut lanes = Vec::with_capacity(*vector_len as usize);
|
||||
for lane in 0..*vector_len {
|
||||
let value = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
Op::CompositeExtract,
|
||||
Some(elem_type),
|
||||
Some(array_elem_type),
|
||||
Some(value),
|
||||
vec![Operand::IdRef(loaded), Operand::LiteralBit32(lane)],
|
||||
));
|
||||
let value = if elements_need_bitcast {
|
||||
let reinterpreted = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
Op::Bitcast,
|
||||
Some(vector_elem_type),
|
||||
Some(reinterpreted),
|
||||
vec![Operand::IdRef(value)],
|
||||
));
|
||||
reinterpreted
|
||||
} else {
|
||||
value
|
||||
};
|
||||
lanes.push(Operand::IdRef(value));
|
||||
}
|
||||
let vector_type = self.type_id(result_ty)?;
|
||||
|
||||
@@ -35,7 +35,7 @@ impl Emitter {
|
||||
let false_label = f.trim();
|
||||
if let Some(loop_merge) = self.current_loop_merge() {
|
||||
self.emit_loop_merge(&loop_merge, instructions)?;
|
||||
} else if !self.current_branch_is_loop_continue(true_label, false_label) {
|
||||
} else {
|
||||
let header_merge = self
|
||||
.current_block
|
||||
.as_ref()
|
||||
@@ -109,7 +109,7 @@ impl Emitter {
|
||||
// `value_id_in` the text path ran). `FromText` (the ret operand did not `parse_typed_value`
|
||||
// at build) is a fail-visible error — the emission substrate `terminator_text` is retired, and
|
||||
// this fallback is measured dead broadly (0 / 16942 frontier + 0 / 15,336 banked), so a
|
||||
// hit routes to the retry cascade, which re-parses the sanitized AIR from scratch.
|
||||
// hit is returned as an unsupported typed-carrier error.
|
||||
TirTerminator::Ret(v) => match ret {
|
||||
RetEmit::Void => {
|
||||
instructions.push(Self::inst(Op::Return, None, None, vec![]));
|
||||
@@ -133,7 +133,7 @@ impl Emitter {
|
||||
// `switch` emits entirely from the typed `LlSwitch` carrier (built via the byte-identical
|
||||
// text-path `parse_switch`). `None` (the operands did not strict-parse at build) is a
|
||||
// fail-visible error for the same retired-substrate reason as `ret` above — measured dead
|
||||
// broadly, routes to the retry cascade.
|
||||
// broadly.
|
||||
TirTerminator::Switch {
|
||||
selector, default, ..
|
||||
} => match switch {
|
||||
@@ -151,19 +151,6 @@ impl Emitter {
|
||||
self.loop_merges.get(block).cloned()
|
||||
}
|
||||
|
||||
fn current_branch_is_loop_continue(&self, true_label: &str, false_label: &str) -> bool {
|
||||
let Some(block) = self.current_block.as_ref() else {
|
||||
return false;
|
||||
};
|
||||
self.loop_merges
|
||||
.get(true_label)
|
||||
.is_some_and(|info| info.merge == false_label && info.continue_target == *block)
|
||||
|| self
|
||||
.loop_merges
|
||||
.get(false_label)
|
||||
.is_some_and(|info| info.merge == true_label && info.continue_target == *block)
|
||||
}
|
||||
|
||||
pub(in crate::native::emitter) fn emit_loop_merge(
|
||||
&mut self,
|
||||
loop_merge: &LoopMergeInfo,
|
||||
|
||||
@@ -1,144 +0,0 @@
|
||||
//! Byte-neutral responsibility split of the former monolith; see the parent module.
|
||||
|
||||
use super::*;
|
||||
|
||||
pub(in crate::native::emitter) fn emitted_block_dominators(
|
||||
blocks: &[Block],
|
||||
) -> crate::native::cfg::EmittedDominators {
|
||||
let labels = blocks
|
||||
.iter()
|
||||
.filter_map(|block| block.label.as_ref()?.result_id)
|
||||
.collect::<Vec<_>>();
|
||||
let entry = labels.first().copied().unwrap_or_default();
|
||||
let successors = blocks
|
||||
.iter()
|
||||
.filter_map(|block| {
|
||||
Some((
|
||||
block.label.as_ref()?.result_id?,
|
||||
cloned_block_successors(block),
|
||||
))
|
||||
})
|
||||
.collect::<HashMap<_, _>>();
|
||||
crate::native::cfg::EmittedDominators::new(entry, &labels, &successors)
|
||||
}
|
||||
|
||||
pub(in crate::native::emitter) fn block_value_defs(blocks: &[Block]) -> HashMap<Word, Word> {
|
||||
let mut defs = HashMap::new();
|
||||
for block in blocks {
|
||||
let Some(label) = block.label.as_ref().and_then(|label| label.result_id) else {
|
||||
continue;
|
||||
};
|
||||
for inst in &block.instructions {
|
||||
if let Some(result) = inst.result_id {
|
||||
defs.insert(result, label);
|
||||
}
|
||||
}
|
||||
}
|
||||
defs
|
||||
}
|
||||
|
||||
pub(in crate::native::emitter) fn has_non_leading_phi(block: &Block) -> bool {
|
||||
let mut saw_non_phi = false;
|
||||
for inst in &block.instructions {
|
||||
if inst.class.opcode == Op::Phi {
|
||||
if saw_non_phi {
|
||||
return true;
|
||||
}
|
||||
} else {
|
||||
saw_non_phi = true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
pub(in crate::native::emitter) fn is_phi_incoming_materialization(inst: &Instruction) -> bool {
|
||||
matches!(
|
||||
inst.class.opcode,
|
||||
Op::AccessChain | Op::InBoundsAccessChain | Op::PtrAccessChain
|
||||
) && inst.result_id.is_some()
|
||||
}
|
||||
|
||||
pub(in crate::native::emitter) fn unique_phi_incoming_predecessor_for_value(
|
||||
blocks: &[Block],
|
||||
target_label: Word,
|
||||
value_id: Word,
|
||||
) -> Option<Word> {
|
||||
let mut incoming_pred = None;
|
||||
for block in blocks {
|
||||
let label = block.label.as_ref().and_then(|label| label.result_id);
|
||||
for inst in &block.instructions {
|
||||
for operand in &inst.operands {
|
||||
if id_ref_operand(operand) != Some(value_id) {
|
||||
continue;
|
||||
}
|
||||
let is_target_phi_incoming = label == Some(target_label)
|
||||
&& inst.class.opcode == Op::Phi
|
||||
&& inst.operands.chunks(2).any(|pair| {
|
||||
matches!(
|
||||
pair,
|
||||
[Operand::IdRef(value), Operand::IdRef(_)] if *value == value_id
|
||||
)
|
||||
});
|
||||
if !is_target_phi_incoming {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
if label != Some(target_label) || inst.class.opcode != Op::Phi {
|
||||
continue;
|
||||
}
|
||||
for pair in inst.operands.chunks(2) {
|
||||
let [Operand::IdRef(value), Operand::IdRef(pred)] = pair else {
|
||||
continue;
|
||||
};
|
||||
if *value != value_id {
|
||||
continue;
|
||||
}
|
||||
match incoming_pred {
|
||||
Some(existing) if existing != *pred => return None,
|
||||
Some(_) => {}
|
||||
None => incoming_pred = Some(*pred),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
incoming_pred
|
||||
}
|
||||
|
||||
pub(in crate::native::emitter) fn materialization_operands_dominate_pred(
|
||||
inst: &Instruction,
|
||||
result: Word,
|
||||
target_label: Word,
|
||||
pred: Word,
|
||||
defs: &HashMap<Word, Word>,
|
||||
dominators: &crate::native::cfg::EmittedDominators,
|
||||
) -> bool {
|
||||
for operand in &inst.operands {
|
||||
let Some(id) = id_ref_operand(operand) else {
|
||||
continue;
|
||||
};
|
||||
if id == result {
|
||||
continue;
|
||||
}
|
||||
let Some(def_label) = defs.get(&id).copied() else {
|
||||
continue;
|
||||
};
|
||||
if def_label == target_label || !dominators.dominates(def_label, pred) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
pub(in crate::native::emitter) fn terminator_insert_index(block: &Block) -> usize {
|
||||
let term_idx = block.instructions.len().saturating_sub(1);
|
||||
if term_idx > 0
|
||||
&& matches!(
|
||||
block.instructions[term_idx - 1].class.opcode,
|
||||
Op::SelectionMerge | Op::LoopMerge
|
||||
)
|
||||
{
|
||||
term_idx - 1
|
||||
} else {
|
||||
term_idx
|
||||
}
|
||||
}
|
||||
@@ -1,102 +0,0 @@
|
||||
//! Post-emit pre-phi materialization fixup — the sole survivor of the W4 repair-roster deletion.
|
||||
//!
|
||||
//! The ~4,800-line post-hoc CFG repair roster (the 4x fixpoint + `repair_*`/`split_*`/`clone_*`
|
||||
//! surgery) was deleted at W4 (2026-07-16): `METAL2VULKAN_NO_REPAIR` proved the retry cascade ships
|
||||
//! the full regression set spirv-val-valid without it. What remains here is the ONE fixup that runs on the
|
||||
//! STRUCTURED (admitted) path, not on reject repair: relocating a pointer-phi's incoming access-chain
|
||||
//! materialization out of the phi's own block. It is CFG-structure-agnostic (moves a single
|
||||
//! materialization to its unique phi-incoming predecessor edge under dominance guards; never reorders
|
||||
//! blocks or rewrites merges), so it is independent of the deleted roster.
|
||||
|
||||
use super::*;
|
||||
|
||||
impl Emitter {
|
||||
pub(in crate::native) fn repair_pre_phi_incoming_materializations(
|
||||
&mut self,
|
||||
blocks: &mut [Block],
|
||||
) {
|
||||
// Relocating an instruction changes its defining block but never changes the CFG. Build the
|
||||
// compact dominator tree once; only the much smaller value-definition map must be refreshed
|
||||
// after a move. The former full dominator-set map was O(V^2) and rebuilt for every relocated
|
||||
// materialization, leaving hundreds of MiB of allocator high-water pages on large functions.
|
||||
let dominators = emitted_block_dominators(blocks);
|
||||
loop {
|
||||
let defs = block_value_defs(blocks);
|
||||
let mut moved = false;
|
||||
'scan: for target_idx in 0..blocks.len() {
|
||||
let Some(target_label) = blocks[target_idx]
|
||||
.label
|
||||
.as_ref()
|
||||
.and_then(|label| label.result_id)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if !has_non_leading_phi(&blocks[target_idx]) {
|
||||
continue;
|
||||
}
|
||||
for inst_idx in 0..blocks[target_idx].instructions.len() {
|
||||
let inst = &blocks[target_idx].instructions[inst_idx];
|
||||
if !is_phi_incoming_materialization(inst)
|
||||
|| !blocks[target_idx]
|
||||
.instructions
|
||||
.iter()
|
||||
.skip(inst_idx + 1)
|
||||
.any(|inst| inst.class.opcode == Op::Phi)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let Some(result) = inst.result_id else {
|
||||
continue;
|
||||
};
|
||||
let Some(pred) =
|
||||
unique_phi_incoming_predecessor_for_value(blocks, target_label, result)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if pred == target_label
|
||||
|| !materialization_operands_dominate_pred(
|
||||
inst,
|
||||
result,
|
||||
target_label,
|
||||
pred,
|
||||
&defs,
|
||||
&dominators,
|
||||
)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let Some(pred_idx) = block_index_by_label(blocks, pred) else {
|
||||
continue;
|
||||
};
|
||||
let inst = blocks[target_idx].instructions.remove(inst_idx);
|
||||
let insert_idx = terminator_insert_index(&blocks[pred_idx]);
|
||||
blocks[pred_idx].instructions.insert(insert_idx, inst);
|
||||
moved = true;
|
||||
break 'scan;
|
||||
}
|
||||
}
|
||||
if !moved {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// A non-phi instruction can remain between phis even when it is not itself a phi incoming
|
||||
// materialization (for example, index arithmetic rematerialized for an earlier pointer phi in
|
||||
// the same block). Every OpPhi semantically executes at block entry and its operands come from
|
||||
// predecessor edges, so stable-partitioning the residual phis ahead of ordinary instructions is
|
||||
// the canonical SPIR-V order. Materializations that actually feed a phi were relocated by the
|
||||
// dominance-checked loop above first; any unsupported same-block dependency remains invalid and
|
||||
// is still rejected by the caller's module-level validation gate.
|
||||
for block in blocks {
|
||||
if !has_non_leading_phi(block) {
|
||||
continue;
|
||||
}
|
||||
let instructions = std::mem::take(&mut block.instructions);
|
||||
let (mut phis, rest): (Vec<_>, Vec<_>) = instructions
|
||||
.into_iter()
|
||||
.partition(|inst| inst.class.opcode == Op::Phi);
|
||||
phis.extend(rest);
|
||||
block.instructions = phis;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,6 @@
|
||||
use super::*;
|
||||
use crate::native::cfg::graph::spirv_block_successors as cloned_block_successors;
|
||||
|
||||
mod loop_continue;
|
||||
mod merge_helpers;
|
||||
mod merges;
|
||||
pub(in crate::native::emitter) use merge_helpers::*;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
|
||||
+2458
-207
File diff suppressed because it is too large.
Load diff
@@ -70,6 +70,22 @@ fn raw_rule_errors_on_uncovered_types() {
|
||||
assert!(e.raw_type_size_align(&LlType::Void).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn workgroup_struct_padding_ranges_exclude_members_and_allocation_escape() {
|
||||
let e = emitter();
|
||||
let padded = LlType::Struct(vec![LlType::Int(32), LlType::Int(8)]);
|
||||
|
||||
assert!(e
|
||||
.struct_range_is_padding(&padded, 5, 3)
|
||||
.expect("tail-padding range"));
|
||||
assert!(!e
|
||||
.struct_range_is_padding(&padded, 4, 1)
|
||||
.expect("member range"));
|
||||
assert!(!e
|
||||
.struct_range_is_padding(&padded, 5, 4)
|
||||
.expect("range beyond allocation"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raw_rule_uses_source_vector_abi_alignment() {
|
||||
let ir = LlModule::parse(concat!(
|
||||
|
||||
@@ -119,6 +119,30 @@ impl Emitter {
|
||||
Ok(addr)
|
||||
}
|
||||
|
||||
pub(in crate::native::emitter) fn materialize_reserved_bda_address(
|
||||
&mut self,
|
||||
name: &str,
|
||||
raw: &RawBufferOffset,
|
||||
instructions: &mut Vec<Instruction>,
|
||||
) -> Result<(), String> {
|
||||
let address_name = bda_address_name(name);
|
||||
let Some((reserved, _)) = self.values.get(&address_name).cloned() else {
|
||||
return Ok(());
|
||||
};
|
||||
let address = self.materialize_device_address(raw, instructions)?;
|
||||
if address != reserved {
|
||||
let address_ty = self.type_id(&LlType::Int(64))?;
|
||||
instructions.push(Self::inst(
|
||||
Op::CopyObject,
|
||||
Some(address_ty),
|
||||
Some(reserved),
|
||||
vec![Operand::IdRef(address)],
|
||||
));
|
||||
}
|
||||
self.bda_address_values.insert(reserved);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The `Aligned` memory-operand value for a PhysicalStorageBuffer load/store of `ty`: the component
|
||||
/// (scalar) size in bytes, a power of two (`VUID-StandaloneSpirv-PhysicalStorageBuffer64-06314`
|
||||
/// requires the operand to be a power of two and present).
|
||||
|
||||
@@ -140,6 +140,17 @@ impl Emitter {
|
||||
pointee: &LlType,
|
||||
) -> Result<(), String> {
|
||||
let result = self.result_id(name, &LlType::Ptr(addrspace))?;
|
||||
if crate::env_vars::spi_why() {
|
||||
self.module.debug_names.push(Self::inst(
|
||||
Op::Name,
|
||||
None,
|
||||
None,
|
||||
vec![
|
||||
Operand::IdRef(result),
|
||||
Operand::LiteralString(format!("unmodeled pointer {name}")),
|
||||
],
|
||||
));
|
||||
}
|
||||
self.emit_private_zero_pointer_value_at(
|
||||
result,
|
||||
pointee,
|
||||
@@ -163,6 +174,17 @@ impl Emitter {
|
||||
addrspace: u32,
|
||||
) -> Result<(), String> {
|
||||
let result = self.result_id(name, &LlType::Ptr(addrspace))?;
|
||||
if crate::env_vars::spi_why() {
|
||||
self.module.debug_names.push(Self::inst(
|
||||
Op::Name,
|
||||
None,
|
||||
None,
|
||||
vec![
|
||||
Operand::IdRef(result),
|
||||
Operand::LiteralString(format!("unmodeled byte pointer {name}")),
|
||||
],
|
||||
));
|
||||
}
|
||||
self.emit_private_zero_pointer_value_at(
|
||||
result,
|
||||
&LlType::Int(8),
|
||||
|
||||
@@ -83,15 +83,18 @@ impl Emitter {
|
||||
word_index: Word,
|
||||
instructions: &mut Vec<Instruction>,
|
||||
) -> Result<Word, String> {
|
||||
let ptr = self.emit_raw_word_pointer_at_index(raw, word_index, instructions)?;
|
||||
let (ptr, storage) =
|
||||
self.emit_raw_word_pointer_at_index_with_storage(raw, word_index, instructions)?;
|
||||
let word_ty = self.type_id(&LlType::Int(32))?;
|
||||
let word = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
Op::Load,
|
||||
Some(word_ty),
|
||||
Some(word),
|
||||
vec![Operand::IdRef(ptr)],
|
||||
));
|
||||
let mut operands = vec![Operand::IdRef(ptr)];
|
||||
if storage == StorageClass::PhysicalStorageBuffer {
|
||||
operands.extend([
|
||||
Operand::MemoryAccess(spirv::MemoryAccess::ALIGNED),
|
||||
Operand::LiteralBit32(4),
|
||||
]);
|
||||
}
|
||||
instructions.push(Self::inst(Op::Load, Some(word_ty), Some(word), operands));
|
||||
Ok(word)
|
||||
}
|
||||
|
||||
@@ -127,11 +130,6 @@ impl Emitter {
|
||||
let storage = self.raw_access_storage(raw)?;
|
||||
let ptr_ty = self.ptr_type_id(storage, &LlType::Int(32))?;
|
||||
if let Some(base_address) = raw.device_addr_base {
|
||||
if storage != StorageClass::PhysicalStorageBuffer {
|
||||
return Err(format!(
|
||||
"native emitter: device-address raw word uses non-physical storage {storage:?}"
|
||||
));
|
||||
}
|
||||
let i64_ty = self.type_id(&LlType::Int(64))?;
|
||||
let index64 = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
@@ -198,6 +196,9 @@ impl Emitter {
|
||||
&self,
|
||||
raw: &RawBufferOffset,
|
||||
) -> Result<StorageClass, String> {
|
||||
if raw.device_addr_base.is_some() {
|
||||
return Ok(StorageClass::PhysicalStorageBuffer);
|
||||
}
|
||||
self.pointer_storage
|
||||
.get(&raw.root)
|
||||
.copied()
|
||||
@@ -239,13 +240,16 @@ impl Emitter {
|
||||
value: Word,
|
||||
instructions: &mut Vec<Instruction>,
|
||||
) -> Result<(), String> {
|
||||
let ptr = self.emit_raw_word_pointer_at_index(raw, word_index, instructions)?;
|
||||
instructions.push(Self::inst(
|
||||
Op::Store,
|
||||
None,
|
||||
None,
|
||||
vec![Operand::IdRef(ptr), Operand::IdRef(value)],
|
||||
));
|
||||
let (ptr, storage) =
|
||||
self.emit_raw_word_pointer_at_index_with_storage(raw, word_index, instructions)?;
|
||||
let mut operands = vec![Operand::IdRef(ptr), Operand::IdRef(value)];
|
||||
if storage == StorageClass::PhysicalStorageBuffer {
|
||||
operands.extend([
|
||||
Operand::MemoryAccess(spirv::MemoryAccess::ALIGNED),
|
||||
Operand::LiteralBit32(4),
|
||||
]);
|
||||
}
|
||||
instructions.push(Self::inst(Op::Store, None, None, operands));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
+1656
-292
File diff suppressed because it is too large.
Load diff
@@ -159,6 +159,52 @@ impl Emitter {
|
||||
"native emitter: {op:?} currently supports scalar/vector integer types, got {result_ty:?}"
|
||||
));
|
||||
}
|
||||
// Vulkan vectors have at most four components. AIR retains wider LLVM integer vectors,
|
||||
// which `type_id` represents as arrays; scalarize their elementwise operation instead of
|
||||
// applying an integer opcode to an aggregate result type.
|
||||
if let LlType::Vector(element, lanes) = &result_ty {
|
||||
if *lanes > 4 {
|
||||
let element_ty = self.resolve_type(element)?;
|
||||
let element_type = self.type_id(&element_ty)?;
|
||||
let result_type = self.type_id(&result_ty)?;
|
||||
let result = self.result_id(&name, &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 mut values = Vec::with_capacity(*lanes as usize);
|
||||
for lane in 0..*lanes {
|
||||
let left = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
Op::CompositeExtract,
|
||||
Some(element_type),
|
||||
Some(left),
|
||||
vec![Operand::IdRef(lhs_id), Operand::LiteralBit32(lane)],
|
||||
));
|
||||
let right = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
Op::CompositeExtract,
|
||||
Some(element_type),
|
||||
Some(right),
|
||||
vec![Operand::IdRef(rhs_id), Operand::LiteralBit32(lane)],
|
||||
));
|
||||
let value = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
op,
|
||||
Some(element_type),
|
||||
Some(value),
|
||||
vec![Operand::IdRef(left), Operand::IdRef(right)],
|
||||
));
|
||||
values.push(Operand::IdRef(value));
|
||||
}
|
||||
instructions.push(Self::inst(
|
||||
Op::CompositeConstruct,
|
||||
Some(result_type),
|
||||
Some(result),
|
||||
values,
|
||||
));
|
||||
self.record_int_alignment(&name, &result_ty, int_alignment);
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
let result_type = self.type_id(&result_ty)?;
|
||||
let result = self.result_id(&name, &result_ty)?;
|
||||
let lhs_id = self.value_id_in(&lhs.value, &lhs.ty, instructions)?;
|
||||
|
||||
@@ -3,6 +3,127 @@
|
||||
use super::*;
|
||||
|
||||
impl Emitter {
|
||||
pub(in crate::native::emitter) fn emit_i8_array_integer_bitcast(
|
||||
&mut self,
|
||||
src: Word,
|
||||
src_ty: &LlType,
|
||||
dst_ty: &LlType,
|
||||
result: Word,
|
||||
instructions: &mut Vec<Instruction>,
|
||||
) -> Result<bool, String> {
|
||||
match (src_ty, dst_ty) {
|
||||
(LlType::Array(elem, lanes) | LlType::Vector(elem, lanes), LlType::Int(bits))
|
||||
if **elem == LlType::Int(8)
|
||||
&& *lanes > 0
|
||||
&& lanes.checked_mul(8) == Some(*bits)
|
||||
&& *bits <= 64
|
||||
&& (matches!(src_ty, LlType::Array(_, _)) || *lanes > 4) =>
|
||||
{
|
||||
let byte_ty = self.type_id(&LlType::Int(8))?;
|
||||
let integer_ty = self.type_id(dst_ty)?;
|
||||
let mut packed = None;
|
||||
for lane in 0..*lanes {
|
||||
let byte = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
Op::CompositeExtract,
|
||||
Some(byte_ty),
|
||||
Some(byte),
|
||||
vec![Operand::IdRef(src), Operand::LiteralBit32(lane)],
|
||||
));
|
||||
let widened = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
Op::UConvert,
|
||||
Some(integer_ty),
|
||||
Some(widened),
|
||||
vec![Operand::IdRef(byte)],
|
||||
));
|
||||
let shifted = if lane == 0 {
|
||||
widened
|
||||
} else {
|
||||
let shift = self.const_int(*bits, u64::from(lane) * 8)?;
|
||||
let shifted = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
Op::ShiftLeftLogical,
|
||||
Some(integer_ty),
|
||||
Some(shifted),
|
||||
vec![Operand::IdRef(widened), Operand::IdRef(shift)],
|
||||
));
|
||||
shifted
|
||||
};
|
||||
packed = Some(match packed {
|
||||
None => shifted,
|
||||
Some(low) => {
|
||||
let combined = if lane + 1 == *lanes {
|
||||
result
|
||||
} else {
|
||||
self.fresh()
|
||||
};
|
||||
instructions.push(Self::inst(
|
||||
Op::BitwiseOr,
|
||||
Some(integer_ty),
|
||||
Some(combined),
|
||||
vec![Operand::IdRef(low), Operand::IdRef(shifted)],
|
||||
));
|
||||
combined
|
||||
}
|
||||
});
|
||||
}
|
||||
if *lanes == 1 {
|
||||
instructions.push(Self::inst(
|
||||
Op::CopyObject,
|
||||
Some(integer_ty),
|
||||
Some(result),
|
||||
vec![Operand::IdRef(packed.expect("non-empty byte array"))],
|
||||
));
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
(LlType::Int(bits), LlType::Array(elem, lanes) | LlType::Vector(elem, lanes))
|
||||
if **elem == LlType::Int(8)
|
||||
&& *lanes > 0
|
||||
&& lanes.checked_mul(8) == Some(*bits)
|
||||
&& *bits <= 64
|
||||
&& (matches!(dst_ty, LlType::Array(_, _)) || *lanes > 4) =>
|
||||
{
|
||||
let integer_ty = self.type_id(src_ty)?;
|
||||
let byte_ty = self.type_id(&LlType::Int(8))?;
|
||||
let array_ty = self.type_id(dst_ty)?;
|
||||
let mut bytes = Vec::with_capacity(*lanes as usize);
|
||||
for lane in 0..*lanes {
|
||||
let shifted = if lane == 0 {
|
||||
src
|
||||
} else {
|
||||
let shift = self.const_int(*bits, u64::from(lane) * 8)?;
|
||||
let shifted = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
Op::ShiftRightLogical,
|
||||
Some(integer_ty),
|
||||
Some(shifted),
|
||||
vec![Operand::IdRef(src), Operand::IdRef(shift)],
|
||||
));
|
||||
shifted
|
||||
};
|
||||
let byte = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
Op::UConvert,
|
||||
Some(byte_ty),
|
||||
Some(byte),
|
||||
vec![Operand::IdRef(shifted)],
|
||||
));
|
||||
bytes.push(Operand::IdRef(byte));
|
||||
}
|
||||
instructions.push(Self::inst(
|
||||
Op::CompositeConstruct,
|
||||
Some(array_ty),
|
||||
Some(result),
|
||||
bytes,
|
||||
));
|
||||
Ok(true)
|
||||
}
|
||||
_ => Ok(false),
|
||||
}
|
||||
}
|
||||
|
||||
/// The operand-resolved core of the int-convert handler — the M-A4 graph walk drives it from
|
||||
/// `TirInst.operands[0]` (source) + `TirInst.result_ty` (dest), see `emit_binary_float_op_resolved`.
|
||||
pub(in crate::native::emitter) fn emit_int_convert_resolved(
|
||||
@@ -53,40 +174,80 @@ impl Emitter {
|
||||
));
|
||||
}
|
||||
let result_type = self.type_id(&dst_ty)?;
|
||||
let source_type = self.type_id(&src_ty)?;
|
||||
let result = self.result_id(&name, &dst_ty)?;
|
||||
let src_id = self.value_id_in(&src.value, &src.ty, instructions)?;
|
||||
// A nonstandard integer lives in the next legal unsigned container with only its logical
|
||||
// low bits significant. Before `sext`, restore the logical sign bit across that container;
|
||||
// otherwise an i24 value whose bit 23 is set would be interpreted as a positive i32.
|
||||
let converted_src = if op == Op::SConvert {
|
||||
if let Some(bits) = nonstandard_scalar_int_bits(&src_ty) {
|
||||
let legal = spirv_int_width(bits)?;
|
||||
let shift = self.const_int(legal, u64::from(legal - bits))?;
|
||||
let shifted = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
Op::ShiftLeftLogical,
|
||||
Some(source_type),
|
||||
Some(shifted),
|
||||
vec![Operand::IdRef(src_id), Operand::IdRef(shift)],
|
||||
));
|
||||
let extended = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
Op::ShiftRightArithmetic,
|
||||
Some(source_type),
|
||||
Some(extended),
|
||||
vec![Operand::IdRef(shifted), Operand::IdRef(shift)],
|
||||
));
|
||||
extended
|
||||
} else {
|
||||
src_id
|
||||
}
|
||||
} else {
|
||||
src_id
|
||||
};
|
||||
// Nonstandard dest widths (`trunc i16 to i2`) emit as the legal container type (i8) via
|
||||
// `type_id`. A bare `OpUConvert` to i8 keeps the low *8* bits, but LLVM `i2` only has the
|
||||
// low 2 — mask so a subsequent `switch i2` with cases `i2 -1/-2/1` (encoded as 3/2/1)
|
||||
// matches. Unsigned convert (zext/trunc) only; signed narrow/widen of nonstandard widths
|
||||
// is a residual (not seen on the SkyLight reduction kernels).
|
||||
// matches. Signed destinations use the same canonical low-bit representation after their
|
||||
// source has been sign-extended above.
|
||||
let dst_resolved = self.resolve_type(&dst_ty)?;
|
||||
if let Some(bits) = nonstandard_scalar_int_bits(&dst_resolved) {
|
||||
if op == Op::UConvert {
|
||||
let tmp = self.fresh();
|
||||
let legal = spirv_int_width(bits)?;
|
||||
let mask = self.const_int(legal, (1u64 << bits) - 1)?;
|
||||
let masked_source = if source_type == result_type {
|
||||
converted_src
|
||||
} else {
|
||||
let converted = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
op,
|
||||
Some(result_type),
|
||||
Some(tmp),
|
||||
vec![Operand::IdRef(src_id)],
|
||||
Some(converted),
|
||||
vec![Operand::IdRef(converted_src)],
|
||||
));
|
||||
let legal = spirv_int_width(bits)?;
|
||||
let mask = self.const_int(legal, (1u64 << bits) - 1)?;
|
||||
instructions.push(Self::inst(
|
||||
Op::BitwiseAnd,
|
||||
Some(result_type),
|
||||
Some(result),
|
||||
vec![Operand::IdRef(tmp), Operand::IdRef(mask)],
|
||||
));
|
||||
self.record_int_alignment(&name, &dst_ty, self.int_value_alignment(&src.value));
|
||||
return Ok(());
|
||||
}
|
||||
converted
|
||||
};
|
||||
instructions.push(Self::inst(
|
||||
Op::BitwiseAnd,
|
||||
Some(result_type),
|
||||
Some(result),
|
||||
vec![Operand::IdRef(masked_source), Operand::IdRef(mask)],
|
||||
));
|
||||
self.record_int_alignment(&name, &dst_ty, self.int_value_alignment(&src.value));
|
||||
return Ok(());
|
||||
}
|
||||
// Choose from the emitted storage types, not the logical LLVM widths. Nonstandard integers
|
||||
// such as i24 share a legal i32 container with their i32 source/destination; SPIR-V forbids
|
||||
// OpUConvert/OpSConvert when those actual types are identical.
|
||||
let emitted_op = if source_type == result_type {
|
||||
Op::CopyObject
|
||||
} else {
|
||||
op
|
||||
};
|
||||
instructions.push(Self::inst(
|
||||
op,
|
||||
emitted_op,
|
||||
Some(result_type),
|
||||
Some(result),
|
||||
vec![Operand::IdRef(src_id)],
|
||||
vec![Operand::IdRef(converted_src)],
|
||||
));
|
||||
self.record_int_alignment(&name, &dst_ty, self.int_value_alignment(&src.value));
|
||||
Ok(())
|
||||
@@ -127,10 +288,15 @@ impl Emitter {
|
||||
));
|
||||
}
|
||||
let result_type = self.type_id(&dst_ty)?;
|
||||
let source_type = self.type_id(&src_ty)?;
|
||||
let result = self.result_id(&name, &dst_ty)?;
|
||||
let src_id = self.value_id_in(&src.value, &src.ty, instructions)?;
|
||||
instructions.push(Self::inst(
|
||||
Op::FConvert,
|
||||
if source_type == result_type {
|
||||
Op::CopyObject
|
||||
} else {
|
||||
Op::FConvert
|
||||
},
|
||||
Some(result_type),
|
||||
Some(result),
|
||||
vec![Operand::IdRef(src_id)],
|
||||
|
||||
@@ -57,6 +57,9 @@ impl Emitter {
|
||||
if let Some(selected) = self.selected_pointers.get(src_name).cloned() {
|
||||
self.selected_pointers.insert(name.to_string(), selected);
|
||||
}
|
||||
if let Some(tree) = self.selected_access_trees.get(src_name).cloned() {
|
||||
self.selected_access_trees.insert(name.to_string(), tree);
|
||||
}
|
||||
if let Some(selected) = self.selected_load_pointers.get(src_name).cloned() {
|
||||
self.selected_load_pointers
|
||||
.insert(name.to_string(), selected);
|
||||
@@ -64,6 +67,9 @@ impl Emitter {
|
||||
if self.unmodeled_pointers.contains(src_name) {
|
||||
self.unmodeled_pointers.insert(name.to_string());
|
||||
}
|
||||
if self.byte_view_pointers.contains(src_name) {
|
||||
self.byte_view_pointers.insert(name.to_string());
|
||||
}
|
||||
if self.param_values.contains(src_name) {
|
||||
self.param_values.insert(name.to_string());
|
||||
}
|
||||
|
||||
@@ -3,6 +3,43 @@
|
||||
use super::*;
|
||||
|
||||
impl Emitter {
|
||||
pub(in crate::native::emitter) fn emit_llvm_ctpop_call(
|
||||
&mut self,
|
||||
call: &LlCall,
|
||||
name: &str,
|
||||
instructions: &mut Vec<Instruction>,
|
||||
) -> Result<bool, String> {
|
||||
if !call.callee.starts_with("llvm.ctpop.") {
|
||||
return Ok(false);
|
||||
}
|
||||
let [value] = call.args.as_slice() else {
|
||||
return Err(format!(
|
||||
"native emitter: {} expects one operand",
|
||||
call.callee
|
||||
));
|
||||
};
|
||||
let result_ty = self.resolve_type(&call.ret)?;
|
||||
let value_ty = self.resolve_type(&value.ty)?;
|
||||
if !is_integer_type(&result_ty) || value_ty != result_ty {
|
||||
return Err(format!(
|
||||
"native emitter: {} operand/result type mismatch {value_ty:?}, {result_ty:?}",
|
||||
call.callee
|
||||
));
|
||||
}
|
||||
|
||||
let result_type = self.type_id(&result_ty)?;
|
||||
let value = self.value_id_in(&value.value, &value.ty, instructions)?;
|
||||
let result = self.result_id(name, &result_ty)?;
|
||||
instructions.push(Self::inst(
|
||||
Op::BitCount,
|
||||
Some(result_type),
|
||||
Some(result),
|
||||
vec![Operand::IdRef(value)],
|
||||
));
|
||||
self.record_int_alignment(name, &result_ty, 1);
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub(in crate::native::emitter) fn emit_llvm_int_minmax_call(
|
||||
&mut self,
|
||||
call: &LlCall,
|
||||
@@ -356,40 +393,48 @@ impl Emitter {
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub(in crate::native::emitter) fn emit_llvm_fshl_i32_call(
|
||||
pub(in crate::native::emitter) fn emit_llvm_fshl_call(
|
||||
&mut self,
|
||||
call: &LlCall,
|
||||
name: &str,
|
||||
instructions: &mut Vec<Instruction>,
|
||||
) -> Result<bool, String> {
|
||||
if call.callee != "llvm.fshl.i32" {
|
||||
let Some(bits) = call
|
||||
.callee
|
||||
.strip_prefix("llvm.fshl.i")
|
||||
.and_then(|suffix| suffix.parse::<u32>().ok())
|
||||
.filter(|bits| matches!(bits, 8 | 16 | 32 | 64))
|
||||
else {
|
||||
return Ok(false);
|
||||
}
|
||||
};
|
||||
if call.args.len() != 3 {
|
||||
return Err("native emitter: llvm.fshl.i32 expects three operands".to_string());
|
||||
return Err(format!(
|
||||
"native emitter: llvm.fshl.i{bits} expects three operands"
|
||||
));
|
||||
}
|
||||
let result_ty = self.resolve_type(&call.ret)?;
|
||||
if result_ty != LlType::Int(32) {
|
||||
let int_ty = LlType::Int(bits);
|
||||
if result_ty != int_ty {
|
||||
return Err(format!(
|
||||
"native emitter: llvm.fshl.i32 returned {result_ty:?}"
|
||||
"native emitter: llvm.fshl.i{bits} returned {result_ty:?}"
|
||||
));
|
||||
}
|
||||
for arg in &call.args {
|
||||
let arg_ty = self.resolve_type(&arg.ty)?;
|
||||
if arg_ty != LlType::Int(32) {
|
||||
if arg_ty != int_ty {
|
||||
return Err(format!(
|
||||
"native emitter: llvm.fshl.i32 operand is {arg_ty:?}"
|
||||
"native emitter: llvm.fshl.i{bits} operand is {arg_ty:?}"
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
let uint = self.type_id(&LlType::Int(32))?;
|
||||
let uint = self.type_id(&int_ty)?;
|
||||
let bool_ty = self.type_id(&LlType::Bool)?;
|
||||
let result = self.result_id(name, &result_ty)?;
|
||||
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 shift = self.value_id_in(&call.args[2].value, &call.args[2].ty, instructions)?;
|
||||
let mask = self.const_uint(31)?;
|
||||
let mask = self.const_int(bits, u64::from(bits - 1))?;
|
||||
let normalized_shift = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
Op::BitwiseAnd,
|
||||
@@ -406,7 +451,7 @@ impl Emitter {
|
||||
vec![Operand::IdRef(lhs), Operand::IdRef(normalized_shift)],
|
||||
));
|
||||
|
||||
let width = self.const_uint(32)?;
|
||||
let width = self.const_int(bits, u64::from(bits))?;
|
||||
let inverse_unmasked = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
Op::ISub,
|
||||
@@ -429,7 +474,7 @@ impl Emitter {
|
||||
Some(right_raw),
|
||||
vec![Operand::IdRef(rhs), Operand::IdRef(inverse_shift)],
|
||||
));
|
||||
let zero = self.const_uint(0)?;
|
||||
let zero = self.const_int(bits, 0)?;
|
||||
let is_zero_shift = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
Op::IEqual,
|
||||
|
||||
@@ -3,25 +3,9 @@
|
||||
use super::*;
|
||||
|
||||
impl Emitter {
|
||||
/// The instruction's operands as typed values resolved by the typed SSA IR (`tir`), or `None` if the
|
||||
/// graph did not resolve every operand (the caller then falls back to string parsing). This is the
|
||||
/// single entry point for R3 graph-driven emission: an opcode is "migrated" once its emitter reads
|
||||
/// its operands from here instead of re-lexing the instruction text.
|
||||
pub(in crate::native::emitter) fn tir_typed_operands(
|
||||
&self,
|
||||
name: &str,
|
||||
) -> Option<Vec<TypedValue>> {
|
||||
self.tir_operands
|
||||
.get(name)?
|
||||
.iter()
|
||||
.map(crate::native::tir::TirOperand::as_typed_value)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The typed operands of a `TirInst` read STRAIGHT off the instruction (not via the `tir_operands`
|
||||
/// side-table keyed by result name), or `None` if any operand is `Unresolved`. This is the M-A4
|
||||
/// graph-walk operand source — byte-identical to `tir_typed_operands(name)` for a result-bearing
|
||||
/// instruction, since `emit_function` populates that map from this same `inst.operands`.
|
||||
/// The typed operands of a `TirInst` read straight off the instruction, or `None` if any operand is
|
||||
/// `Unresolved`. This direct carrier is the sole M-A4 graph-walk operand source; emission does not
|
||||
/// retain a parallel result-keyed clone.
|
||||
pub(in crate::native::emitter) fn tir_inst_typed_operands(
|
||||
&self,
|
||||
inst: &crate::native::tir::TirInst,
|
||||
@@ -32,34 +16,6 @@ impl Emitter {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The phi's incoming `(value, predecessor-label)` pairs, with the VALUES sourced from the typed
|
||||
/// graph. `phi` carries an SSA result, so its value operands live in `tir_operands` (one per
|
||||
/// incoming, in source order — `resolve_phi_operands` keeps the first field of each `[ val, pred ]`
|
||||
/// chunk and drops the predecessor label). The predecessor LABELS are control-flow edges that exist
|
||||
/// only in the instruction text, so they always come from `parsed`. When the graph resolved exactly
|
||||
/// one operand per incoming, each parsed value is replaced by the graph's; on any count mismatch or
|
||||
/// unresolved operand the parsed values stand (and the `METAL2VULKAN_TIR_ONLY` gate fires). tir's phi
|
||||
/// operands are proven sound broadly — including the synthetic `%metal2vulkan.lmerge.*` merge phis the
|
||||
/// structurizer adds — so this is byte-identical to parsing; it routes the value sourcing through
|
||||
/// the typed graph rather than the parsed text.
|
||||
pub(in crate::native::emitter) fn phi_incoming_values(
|
||||
&self,
|
||||
name: &str,
|
||||
parsed: Vec<(LlValue, String)>,
|
||||
) -> Vec<(LlValue, String)> {
|
||||
if let Some(operands) = self.tir_typed_operands(name) {
|
||||
if operands.len() == parsed.len() {
|
||||
return operands
|
||||
.into_iter()
|
||||
.zip(parsed)
|
||||
.map(|(op, (_, label))| (op.value, label))
|
||||
.collect();
|
||||
}
|
||||
}
|
||||
Self::tir_only_gate(name, "phi");
|
||||
parsed
|
||||
}
|
||||
|
||||
/// Overlay typed-graph `operands` onto a direct call's parsed argument values, returning whether it
|
||||
/// applied. The callee and return type are NOT operands (the graph does not lower them), so the
|
||||
/// caller keeps them from the instruction text; only the value arguments are sourced from the
|
||||
@@ -80,30 +36,21 @@ impl Emitter {
|
||||
true
|
||||
}
|
||||
|
||||
/// Source a result-bearing direct call's argument values from the typed graph (keyed by the SSA
|
||||
/// result `name`, as the straight-line ops are), falling back to the parsed args on any count
|
||||
/// mismatch or unresolved operand. Byte-identical to parsing by tir's call-operand soundness.
|
||||
pub(in crate::native::emitter) fn apply_tir_call_args(&self, name: &str, call: &mut LlCall) {
|
||||
match self.tir_typed_operands(name) {
|
||||
Some(ops) if Self::overlay_call_args(&mut call.args, &ops) => {}
|
||||
_ => Self::tir_only_gate(name, "call"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Source a result-LESS (void) direct call's argument values STRAIGHT off the `TirInst.operands` in the
|
||||
/// graph walk (a void call has no SSA result, so it cannot be keyed in `tir_operands`). Byte-identical
|
||||
/// to parsing by tir's call-operand soundness: the same `overlay_call_args` runs on the same operands.
|
||||
/// Source a direct call's argument values straight off `TirInst.operands` in the graph walk.
|
||||
/// Byte-identical to parsing by tir's call-operand soundness: the same `overlay_call_args` runs on
|
||||
/// the same operands for result-bearing and result-less calls.
|
||||
/// Falls back to the parsed args on any count mismatch or unresolved operand (the `METAL2VULKAN_TIR_ONLY`
|
||||
/// gate fires). The former text-walk analogue (`apply_tir_void_call_args`, popping a per-block
|
||||
/// `tir_call_queue`) is retired — the text-walk fallback just uses the parsed args.
|
||||
pub(in crate::native::emitter) fn apply_tir_inst_void_call_args(
|
||||
pub(in crate::native::emitter) fn apply_tir_inst_call_args(
|
||||
&self,
|
||||
inst: &crate::native::tir::TirInst,
|
||||
diagnostic_name: &str,
|
||||
call: &mut LlCall,
|
||||
) {
|
||||
match self.tir_inst_typed_operands(inst) {
|
||||
Some(ops) if Self::overlay_call_args(&mut call.args, &ops) => {}
|
||||
_ => Self::tir_only_gate("void", "call"),
|
||||
_ => Self::tir_only_gate(diagnostic_name, "call"),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,10 +4,10 @@
|
||||
//! merge-participant sets (`pointer_phi_values`, `pointer_phi_incoming_values`, `selected_pointers`)
|
||||
//! are flat membership sets, NOT a grouping. That is the wall behind the three M-B1 blockers and the
|
||||
//! unsound M-A2(a)/(b) read-side flags: a pointee typed differently at two def sites of ONE
|
||||
//! phi/select network (e.g. `05/b00a8a8d`'s `%144`, a loop-carried device pointer whose incomings
|
||||
//! deref as `<4 x float>` on one arm and scalar `float` on the other) errors `pointer merge pointee
|
||||
//! mismatch Float vs Vector(Float,4)`, and no read-side override can fix it because SPIR-V logical
|
||||
//! addressing forbids `OpBitcast` between pointer types.
|
||||
//! phi/select network (for example, a loop-carried device pointer whose incomings dereference as
|
||||
//! `<4 x float>` on one arm and scalar `float` on the other) errors with a pointer-merge pointee
|
||||
//! mismatch, and no read-side override can fix it because SPIR-V logical addressing forbids
|
||||
//! `OpBitcast` between pointer types.
|
||||
//!
|
||||
//! The sound fix (plan §M-A2, ~line 325) must first BUILD the network — the transitive closure over
|
||||
//! phi result ↔ incoming and select result ↔ arm edges — then census each component's deref
|
||||
@@ -23,12 +23,14 @@
|
||||
//! - [`NetworkClass::Unclassified`] — mixed with a non-scalar-family relationship (structs, nested
|
||||
//! pointers): not a widening candidate.
|
||||
//!
|
||||
//! Analysis-only: this module reads the IR and the emitter's recorded pointees; it changes no bytes.
|
||||
//! The analysis is read-only. The emitter consumes its structural classifications when choosing the
|
||||
//! representation of pointer networks.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap};
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
|
||||
|
||||
use crate::native::cfg::BodyBlock;
|
||||
use crate::native::ir::{LlType, LlValue};
|
||||
use crate::native::tir::TirOperand;
|
||||
|
||||
/// How a pointer network's per-def-site deref granularities relate — decides whether recording one
|
||||
/// finest pointee uniformly across the component is sound.
|
||||
@@ -172,7 +174,7 @@ fn pointer_edges_from_carrier(
|
||||
continue;
|
||||
};
|
||||
if inst.opcode == "phi" {
|
||||
if let Some((ty, incomings)) = &inst.phi_incoming {
|
||||
if let Some((ty, incomings)) = &inst.phi_incoming() {
|
||||
if matches!(ty, LlType::Ptr(_)) {
|
||||
for (value, _pred) in incomings {
|
||||
if let LlValue::Local(inc) = value {
|
||||
@@ -197,20 +199,118 @@ fn pointer_edges_from_carrier(
|
||||
} else if inst.opcode == "bitcast" {
|
||||
// A `bitcast ptr %src to ptr` is a pointer-identity alias (a no-op in opaque-pointer LLVM):
|
||||
// result and source are the same pointer, so they belong to one network. Load-bearing for
|
||||
// the access census — 05's scalar `float` arm reaches its phi through
|
||||
// `%142 = bitcast (%141 = gep float …)`; without this edge `%141`'s Float access is invisible
|
||||
// and the whole-vs-part network masquerades as Uniform.
|
||||
if let Some((src, dst)) = inst.bitcast.as_deref() {
|
||||
// the access census: a scalar `float` arm can reach its phi through a pointer bitcast;
|
||||
// without this edge the scalar access is invisible and a whole-vs-part network can
|
||||
// masquerade as Uniform.
|
||||
if let Some((src, dst)) = inst.bitcast() {
|
||||
if matches!(src.ty, LlType::Ptr(_)) && dst.trim_start().starts_with("ptr") {
|
||||
if let LlValue::Local(local) = &src.value {
|
||||
edges.push((name.clone(), local.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if inst.opcode == "freeze" && matches!(inst.result_ty, Some(LlType::Ptr(_))) {
|
||||
if let Some(TirOperand::Value {
|
||||
name: local,
|
||||
ty: LlType::Ptr(_),
|
||||
}) = inst.operands.first()
|
||||
{
|
||||
edges.push((name.clone(), local.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Pointer components whose only roots are `null`/`undef` and whose remaining producers are
|
||||
/// transparent pointer aliases or GEPs rooted back in the same component. These arise after literal
|
||||
/// specialization removes the concrete arm of a pointer induction. Retaining its separately-carried
|
||||
/// nullness is sufficient while the pointer payload may be represented by a correctly typed `OpUndef`.
|
||||
/// Source blocks may still contain consumers on paths discarded by the selected CFG and cleanup
|
||||
/// construction; the final product module retains only the separately represented nullness.
|
||||
pub(in crate::native) fn null_rooted_pointer_networks(blocks: &[BodyBlock]) -> Vec<Vec<String>> {
|
||||
let definitions = blocks
|
||||
.iter()
|
||||
.filter_map(|block| block.typed.as_ref())
|
||||
.flat_map(|block| &block.insts)
|
||||
.filter_map(|inst| inst.result.as_ref().map(|result| (result.as_str(), inst)))
|
||||
.collect::<HashMap<_, _>>();
|
||||
let mut result = Vec::new();
|
||||
for members in build_null_rooted_components(blocks) {
|
||||
let member_set = members.iter().map(String::as_str).collect::<HashSet<_>>();
|
||||
let mut saw_nullish = false;
|
||||
let valid = members.iter().all(|name| {
|
||||
let Some(inst) = definitions.get(name.as_str()) else {
|
||||
return false;
|
||||
};
|
||||
let pointer_value = |value: &LlValue, saw_nullish: &mut bool| match value {
|
||||
LlValue::Local(local) => member_set.contains(local.as_str()),
|
||||
LlValue::Zero | LlValue::Undef => {
|
||||
*saw_nullish = true;
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
match inst.opcode.as_str() {
|
||||
"phi" => inst.phi_values().is_some_and(|values| {
|
||||
values
|
||||
.into_iter()
|
||||
.all(|value| pointer_value(value, &mut saw_nullish))
|
||||
}),
|
||||
"select" => inst.select_arms().as_ref().is_some_and(|arms| {
|
||||
pointer_value(&arms.0.value, &mut saw_nullish)
|
||||
&& pointer_value(&arms.1.value, &mut saw_nullish)
|
||||
}),
|
||||
"bitcast" | "freeze" => inst
|
||||
.operands
|
||||
.first()
|
||||
.and_then(TirOperand::as_typed_value)
|
||||
.is_some_and(|value| pointer_value(&value.value, &mut saw_nullish)),
|
||||
"getelementptr" => inst
|
||||
.gep()
|
||||
.as_deref()
|
||||
.is_some_and(|gep| pointer_value(&gep.base.value, &mut saw_nullish)),
|
||||
_ => false,
|
||||
}
|
||||
});
|
||||
if valid && saw_nullish {
|
||||
result.push(members);
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Components for null-root closure include GEP result↔base edges in addition to the ordinary
|
||||
/// phi/select/transparent-alias graph. A GEP is itself an allowed producer in this classification;
|
||||
/// omitting its edge can split one recurrence into two apparent components and hide the concrete root
|
||||
/// (or make an otherwise closed component appear to reference an external producer).
|
||||
fn build_null_rooted_components(blocks: &[BodyBlock]) -> Vec<Vec<String>> {
|
||||
let mut edges = pointer_edges(blocks);
|
||||
for block in blocks {
|
||||
let Some(carrier) = &block.typed else {
|
||||
continue;
|
||||
};
|
||||
for inst in &carrier.insts {
|
||||
let (Some(result), Some(gep)) = (&inst.result, inst.gep().as_deref()) else {
|
||||
continue;
|
||||
};
|
||||
if let LlValue::Local(base) = &gep.base.value {
|
||||
edges.push((result.clone(), base.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
build_components_from_edges(edges)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(in crate::native) fn null_rooted_pointer_network_members(
|
||||
blocks: &[BodyBlock],
|
||||
) -> HashSet<String> {
|
||||
null_rooted_pointer_networks(blocks)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether a typed operand is `ptr`-typed (the dual of the line scan's arm `starts_with("ptr")`).
|
||||
fn is_ptr_operand(op: &crate::native::tir::TirOperand) -> bool {
|
||||
op.as_typed_value()
|
||||
@@ -220,7 +320,10 @@ fn is_ptr_operand(op: &crate::native::tir::TirOperand) -> bool {
|
||||
/// Group the pointer SSA names of `blocks` into connected components over the phi/select edges.
|
||||
/// Shared by every census; each returned member list is sorted and deduped.
|
||||
fn build_components(blocks: &[BodyBlock]) -> Vec<Vec<String>> {
|
||||
let edges = pointer_edges(blocks);
|
||||
build_components_from_edges(pointer_edges(blocks))
|
||||
}
|
||||
|
||||
fn build_components_from_edges(edges: Vec<(String, String)>) -> Vec<Vec<String>> {
|
||||
let mut uf = UnionFind::default();
|
||||
let mut nodes: BTreeSet<String> = BTreeSet::new();
|
||||
for (a, b) in &edges {
|
||||
@@ -293,6 +396,155 @@ pub(in crate::native) fn analyze_networks_by_access(blocks: &[BodyBlock]) -> Vec
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Buffer parameters whose pointer-merge component genuinely reinterprets storage between distinct
|
||||
/// scalar families. Logical SPIR-V cannot assign one pointee to such a component. Trace every member
|
||||
/// back through typed pointer identities, GEPs, selects, and phis. This primary-construction path is
|
||||
/// needed when the merged carrier crosses a phi and either still contains the function-constant
|
||||
/// select or has one surviving root after function-constant pruning. A select-only component can
|
||||
/// keep using its existing value-domain lowering. The concrete roots must be function-constant
|
||||
/// buffer alternatives at one Metal location, and a pruned single root must have another metadata
|
||||
/// alternative at that location. This gives the roots one descriptor identity despite their
|
||||
/// different source pointees. When every concrete leaf satisfies that contract, return all exact
|
||||
/// roots for byte-address modeling. An unknown producer rejects the complete component, preventing
|
||||
/// partial or mismatched pointer representations.
|
||||
pub(in crate::native) fn reinterpret_mix_buffer_params(
|
||||
blocks: &[BodyBlock],
|
||||
buffer_params: &BTreeMap<String, u32>,
|
||||
) -> BTreeSet<String> {
|
||||
let mut sources = HashMap::<String, Vec<LlValue>>::new();
|
||||
let mut phi_results = HashSet::new();
|
||||
let mut select_results = HashSet::new();
|
||||
for block in blocks {
|
||||
let Some(carrier) = &block.typed else {
|
||||
continue;
|
||||
};
|
||||
for inst in &carrier.insts {
|
||||
let (Some(result), Some(LlType::Ptr(_))) = (&inst.result, &inst.result_ty) else {
|
||||
continue;
|
||||
};
|
||||
let values = if let Some(gep) = inst.gep().as_deref() {
|
||||
vec![gep.base.value.clone()]
|
||||
} else if let Some((source, _)) = inst.bitcast() {
|
||||
vec![source.value]
|
||||
} else if let Some((_, incoming)) = inst.phi_incoming().as_ref() {
|
||||
phi_results.insert(result.clone());
|
||||
incoming.iter().map(|(value, _)| value.clone()).collect()
|
||||
} else if let Some((true_value, false_value)) = inst.select_arms().as_deref() {
|
||||
select_results.insert(result.clone());
|
||||
vec![true_value.value.clone(), false_value.value.clone()]
|
||||
} else if matches!(inst.opcode.as_str(), "addrspacecast" | "freeze") {
|
||||
inst.operands
|
||||
.first()
|
||||
.and_then(|operand| operand.as_typed_value())
|
||||
.map(|value| vec![value.value])
|
||||
.unwrap_or_default()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
if !values.is_empty() {
|
||||
sources.insert(result.clone(), values);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn roots_for(
|
||||
name: &str,
|
||||
buffer_params: &BTreeMap<String, u32>,
|
||||
sources: &HashMap<String, Vec<LlValue>>,
|
||||
select_results: &HashSet<String>,
|
||||
visiting: &mut HashSet<String>,
|
||||
members: &mut BTreeSet<String>,
|
||||
saw_select: &mut bool,
|
||||
) -> Option<BTreeSet<String>> {
|
||||
members.insert(name.to_string());
|
||||
*saw_select |= select_results.contains(name);
|
||||
if buffer_params.contains_key(name) {
|
||||
return Some(BTreeSet::from([name.to_string()]));
|
||||
}
|
||||
if !visiting.insert(name.to_string()) {
|
||||
return Some(BTreeSet::new());
|
||||
}
|
||||
let result = sources.get(name).and_then(|values| {
|
||||
let mut roots = BTreeSet::new();
|
||||
for value in values {
|
||||
match value {
|
||||
LlValue::Local(source) => {
|
||||
roots.extend(roots_for(
|
||||
source,
|
||||
buffer_params,
|
||||
sources,
|
||||
select_results,
|
||||
visiting,
|
||||
members,
|
||||
saw_select,
|
||||
)?);
|
||||
}
|
||||
LlValue::Zero | LlValue::Undef => {}
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
Some(roots)
|
||||
});
|
||||
visiting.remove(name);
|
||||
result
|
||||
}
|
||||
|
||||
let mut selected = BTreeSet::new();
|
||||
let access = access_pointees(blocks);
|
||||
for phi in &phi_results {
|
||||
let mut members = BTreeSet::new();
|
||||
let mut saw_select = false;
|
||||
let Some(roots) = roots_for(
|
||||
phi,
|
||||
buffer_params,
|
||||
&sources,
|
||||
&select_results,
|
||||
&mut HashSet::new(),
|
||||
&mut members,
|
||||
&mut saw_select,
|
||||
) else {
|
||||
continue;
|
||||
};
|
||||
let mut pointees = Vec::new();
|
||||
for pointee in members
|
||||
.iter()
|
||||
.filter_map(|member| access.get(member))
|
||||
.flatten()
|
||||
{
|
||||
if !pointees.contains(pointee) {
|
||||
pointees.push(pointee.clone());
|
||||
}
|
||||
}
|
||||
let root_locations = roots
|
||||
.iter()
|
||||
.filter_map(|root| buffer_params.get(root))
|
||||
.copied()
|
||||
.collect::<BTreeSet<_>>();
|
||||
let one_shared_location = root_locations.len() == 1;
|
||||
let metadata_alternatives = root_locations.first().map_or(0, |location| {
|
||||
buffer_params
|
||||
.values()
|
||||
.filter(|candidate| *candidate == location)
|
||||
.count()
|
||||
});
|
||||
let recurrent_phi_carrier = members
|
||||
.iter()
|
||||
.filter(|member| phi_results.contains(*member))
|
||||
.take(2)
|
||||
.count()
|
||||
>= 2;
|
||||
let function_constant_shape = (saw_select && roots.len() >= 2)
|
||||
|| (roots.len() == 1 && metadata_alternatives >= 2 && recurrent_phi_carrier);
|
||||
if function_constant_shape
|
||||
&& one_shared_location
|
||||
&& matches!(classify(&pointees), NetworkClass::ReinterpretMix)
|
||||
{
|
||||
selected.extend(roots);
|
||||
}
|
||||
}
|
||||
selected
|
||||
}
|
||||
|
||||
/// Collect, per pointer SSA name, the distinct element types it is dereferenced or stepped at across the
|
||||
/// function body: a `load T`/`store T` derefs the pointer at `T`; a `getelementptr T, ptr %base, …`
|
||||
/// steps `%base` at `T` (element stride) and defines a result whose pointee is `gep_pointee(T, idx)`.
|
||||
@@ -312,7 +564,7 @@ fn access_pointees(blocks: &[BodyBlock]) -> HashMap<String, Vec<LlType>> {
|
||||
for block in blocks {
|
||||
// Typed walk (the sole substrate): `load`/`store` carry the deref type on `result_ty` / the
|
||||
// value operand and the pointer on `operands`, and `getelementptr` carries the full `parse_gep`
|
||||
// result on `inst.gep`.
|
||||
// result on `inst.gep()`.
|
||||
if let Some(carrier) = &block.typed {
|
||||
{
|
||||
for inst in &carrier.insts {
|
||||
@@ -331,7 +583,7 @@ fn access_pointees(blocks: &[BodyBlock]) -> HashMap<String, Vec<LlType>> {
|
||||
record(&ptr, val.ty);
|
||||
}
|
||||
} else if inst.opcode == "getelementptr" {
|
||||
if let Some(gep) = &inst.gep {
|
||||
if let Some(gep) = &inst.gep() {
|
||||
if let LlValue::Local(base) = &gep.base.value {
|
||||
record(base, gep.source_ty.clone());
|
||||
}
|
||||
@@ -357,6 +609,181 @@ fn local_operand(op: &crate::native::tir::TirOperand) -> Option<String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Buffer roots whose typed load spans beyond a struct member. Logical SPIR-V access chains preserve
|
||||
/// member boundaries, so a wider load cannot be constructed by incrementing that member index as if
|
||||
/// it were an array stride. Select byte-addressed storage before emission for exactly those roots.
|
||||
pub(in crate::native) fn cross_member_widening_load_roots(
|
||||
blocks: &[BodyBlock],
|
||||
buffer_params: &HashSet<String>,
|
||||
named_types: &HashMap<String, LlType>,
|
||||
) -> BTreeSet<String> {
|
||||
use crate::native::emitter::helpers::{bitcast_width, gep_parent_before_last, gep_pointee};
|
||||
|
||||
let mut sources = HashMap::<String, Vec<String>>::new();
|
||||
let mut cross_member_gep_pointee_bits = HashMap::<String, u32>::new();
|
||||
let mut loads = Vec::<(String, LlType)>::new();
|
||||
fn resolve_type(
|
||||
ty: &LlType,
|
||||
named_types: &HashMap<String, LlType>,
|
||||
visiting: &mut HashSet<String>,
|
||||
) -> Option<LlType> {
|
||||
match ty {
|
||||
LlType::Named(name) => {
|
||||
if !visiting.insert(name.clone()) {
|
||||
return None;
|
||||
}
|
||||
let resolved = resolve_type(named_types.get(name)?, named_types, visiting);
|
||||
visiting.remove(name);
|
||||
resolved
|
||||
}
|
||||
LlType::Vector(elem, 1) => resolve_type(elem, named_types, visiting),
|
||||
LlType::Vector(elem, lanes) => Some(LlType::Vector(
|
||||
Box::new(resolve_type(elem, named_types, visiting)?),
|
||||
*lanes,
|
||||
)),
|
||||
LlType::Array(elem, len) => Some(LlType::Array(
|
||||
Box::new(resolve_type(elem, named_types, visiting)?),
|
||||
*len,
|
||||
)),
|
||||
LlType::Struct(fields) => fields
|
||||
.iter()
|
||||
.map(|field| resolve_type(field, named_types, visiting))
|
||||
.collect::<Option<Vec<_>>>()
|
||||
.map(LlType::Struct),
|
||||
LlType::Int(1) => Some(LlType::Bool),
|
||||
other => Some(other.clone()),
|
||||
}
|
||||
}
|
||||
for block in blocks {
|
||||
let Some(carrier) = &block.typed else {
|
||||
continue;
|
||||
};
|
||||
for inst in &carrier.insts {
|
||||
if inst.opcode == "load" {
|
||||
if let (Some(result_ty), Some(pointer)) = (
|
||||
inst.result_ty.clone(),
|
||||
inst.operands.first().and_then(local_operand),
|
||||
) {
|
||||
loads.push((pointer, result_ty));
|
||||
}
|
||||
}
|
||||
let Some(result) = &inst.result else {
|
||||
continue;
|
||||
};
|
||||
let operands = if let Some(gep) = inst.gep().as_deref() {
|
||||
let source_ty = resolve_type(&gep.source_ty, named_types, &mut HashSet::new());
|
||||
if matches!(
|
||||
source_ty
|
||||
.as_ref()
|
||||
.and_then(|source_ty| { gep_parent_before_last(source_ty, &gep.indices) }),
|
||||
Some(LlType::Struct(_))
|
||||
) {
|
||||
if let Some(bits) = source_ty
|
||||
.as_ref()
|
||||
.and_then(|source_ty| gep_pointee(source_ty, &gep.indices).ok())
|
||||
.and_then(|ty| bitcast_width(&ty))
|
||||
{
|
||||
cross_member_gep_pointee_bits.insert(result.clone(), bits);
|
||||
}
|
||||
}
|
||||
match &gep.base.value {
|
||||
LlValue::Local(base) => vec![base.clone()],
|
||||
_ => Vec::new(),
|
||||
}
|
||||
} else if let Some((source, _)) = inst.bitcast() {
|
||||
match source.value {
|
||||
LlValue::Local(source) => vec![source],
|
||||
_ => Vec::new(),
|
||||
}
|
||||
} else if let Some((_, incoming)) = inst.phi_incoming().as_ref() {
|
||||
incoming
|
||||
.iter()
|
||||
.filter_map(|(value, _)| match value {
|
||||
LlValue::Local(source) => Some(source.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
} else if let Some((true_value, false_value)) = inst.select_arms().as_deref() {
|
||||
[true_value, false_value]
|
||||
.into_iter()
|
||||
.filter_map(|value| match &value.value {
|
||||
LlValue::Local(source) => Some(source.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
} else if matches!(inst.opcode.as_str(), "addrspacecast" | "freeze") {
|
||||
inst.operands
|
||||
.first()
|
||||
.and_then(local_operand)
|
||||
.into_iter()
|
||||
.collect()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
if !operands.is_empty() {
|
||||
sources.insert(result.clone(), operands);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_roots(
|
||||
name: &str,
|
||||
sources: &HashMap<String, Vec<String>>,
|
||||
buffer_params: &HashSet<String>,
|
||||
visiting: &mut HashSet<String>,
|
||||
roots: &mut BTreeSet<String>,
|
||||
) {
|
||||
if buffer_params.contains(name) {
|
||||
roots.insert(name.to_string());
|
||||
return;
|
||||
}
|
||||
if !visiting.insert(name.to_string()) {
|
||||
return;
|
||||
}
|
||||
if let Some(parents) = sources.get(name) {
|
||||
for parent in parents {
|
||||
collect_roots(parent, sources, buffer_params, visiting, roots);
|
||||
}
|
||||
}
|
||||
visiting.remove(name);
|
||||
}
|
||||
|
||||
let mut roots = BTreeSet::new();
|
||||
for (pointer, load_ty) in loads {
|
||||
let Some(load_bits) = bitcast_width(&load_ty) else {
|
||||
continue;
|
||||
};
|
||||
let mut stack = vec![pointer.clone()];
|
||||
let mut seen = HashSet::new();
|
||||
let mut crosses = false;
|
||||
while let Some(name) = stack.pop() {
|
||||
if !seen.insert(name.clone()) {
|
||||
continue;
|
||||
}
|
||||
if cross_member_gep_pointee_bits
|
||||
.get(&name)
|
||||
.is_some_and(|pointee_bits| load_bits > *pointee_bits)
|
||||
{
|
||||
crosses = true;
|
||||
break;
|
||||
}
|
||||
if let Some(parents) = sources.get(&name) {
|
||||
stack.extend(parents.iter().cloned());
|
||||
}
|
||||
}
|
||||
if crosses {
|
||||
collect_roots(
|
||||
&pointer,
|
||||
&sources,
|
||||
buffer_params,
|
||||
&mut HashSet::new(),
|
||||
&mut roots,
|
||||
);
|
||||
}
|
||||
}
|
||||
roots
|
||||
}
|
||||
|
||||
/// Pointer names that are stepped as an ARRAY of a bare primitive scalar — a
|
||||
/// `getelementptr <scalar>, ptr %base, <index>` whose element type is a primitive scalar (not an
|
||||
/// aggregate) and whose single index is non-zero or dynamic. Such a `%base` implicitly addresses an
|
||||
@@ -390,10 +817,10 @@ pub(in crate::native) fn array_indexed_scalar_bases(blocks: &[BodyBlock]) -> BTr
|
||||
};
|
||||
for block in blocks {
|
||||
// Typed walk (the sole substrate): the carrier holds each GEP's full `parse_gep` result on
|
||||
// `inst.gep`.
|
||||
// `inst.gep()`.
|
||||
if let Some(carrier) = &block.typed {
|
||||
for inst in &carrier.insts {
|
||||
if let Some(gep) = &inst.gep {
|
||||
if let Some(gep) = &inst.gep() {
|
||||
consider(gep);
|
||||
}
|
||||
}
|
||||
@@ -472,6 +899,152 @@ mod tests {
|
||||
assert_eq!(c, NetworkClass::Unclassified);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recognizes_closed_null_rooted_pointer_recurrence() {
|
||||
let blocks = [block(&[
|
||||
"%cursor = phi ptr addrspace(2) [ null, %entry ], [ %next, %loop ]",
|
||||
"%next = getelementptr float, ptr addrspace(2) %cursor, i64 %stride",
|
||||
])];
|
||||
|
||||
assert_eq!(
|
||||
null_rooted_pointer_network_members(&blocks),
|
||||
HashSet::from(["%cursor".to_string(), "%next".to_string()])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gep_edges_close_half_whole_part_null_recurrence() {
|
||||
let blocks = [block(&[
|
||||
"%cursor = phi ptr addrspace(2) [ null, %entry ], [ %next, %loop ]",
|
||||
"%wide_next = getelementptr <4 x half>, ptr addrspace(2) %cursor, i64 %index",
|
||||
"%next = bitcast ptr addrspace(2) %wide_next to ptr addrspace(2)",
|
||||
"%wide = load <4 x half>, ptr addrspace(2) %next",
|
||||
"%narrow = load half, ptr addrspace(2) %cursor",
|
||||
])];
|
||||
let null_members = null_rooted_pointer_network_members(&blocks);
|
||||
let network = analyze_networks_by_access(&blocks)
|
||||
.into_iter()
|
||||
.find(|network| network.members.iter().any(|member| member == "%cursor"))
|
||||
.expect("pointer network");
|
||||
|
||||
assert_eq!(network.class, NetworkClass::WholeVsPart(LlType::Half));
|
||||
assert!(
|
||||
network
|
||||
.members
|
||||
.iter()
|
||||
.all(|member| null_members.contains(member)),
|
||||
"the access network must be one closed null-rooted component"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn concrete_pointer_root_disqualifies_null_rooted_recurrence() {
|
||||
let blocks = [block(&[
|
||||
"%cursor = phi ptr addrspace(2) [ %base, %entry ], [ %next, %loop ]",
|
||||
"%next = getelementptr float, ptr addrspace(2) %cursor, i64 %stride",
|
||||
])];
|
||||
|
||||
assert!(null_rooted_pointer_network_members(&blocks).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reinterpret_mix_select_marks_only_its_traced_buffer_roots() {
|
||||
let blocks = [block(&[
|
||||
"%fp = getelementptr float, ptr addrspace(2) %floats, i64 0",
|
||||
"%hp = getelementptr half, ptr addrspace(2) %halves, i64 0",
|
||||
"%fv = bitcast ptr addrspace(2) %fp to ptr addrspace(2)",
|
||||
"%hv = bitcast ptr addrspace(2) %hp to ptr addrspace(2)",
|
||||
"%picked = select i1 %condition, ptr addrspace(2) %hv, ptr addrspace(2) %fv",
|
||||
"%vector = getelementptr <4 x float>, ptr addrspace(2) %picked, i64 1",
|
||||
"%merged = phi ptr addrspace(2) [ %vector, %left ], [ %picked, %right ]",
|
||||
"%value = load <4 x float>, ptr addrspace(2) %merged",
|
||||
])];
|
||||
let eligible = BTreeMap::from([
|
||||
("%floats".to_string(), 29),
|
||||
("%halves".to_string(), 29),
|
||||
("%unrelated".to_string(), 30),
|
||||
]);
|
||||
|
||||
assert_eq!(
|
||||
reinterpret_mix_buffer_params(&blocks, &eligible),
|
||||
BTreeSet::from(["%floats".to_string(), "%halves".to_string()])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reinterpret_mix_select_without_pointer_phi_keeps_value_domain_lowering() {
|
||||
let blocks = [block(&[
|
||||
"%fp = getelementptr float, ptr addrspace(2) %storage, i64 0",
|
||||
"%hp = getelementptr half, ptr addrspace(2) %storage, i64 0",
|
||||
"%picked = select i1 %condition, ptr addrspace(2) %hp, ptr addrspace(2) %fp",
|
||||
"%value = load <4 x float>, ptr addrspace(2) %picked",
|
||||
])];
|
||||
let eligible = BTreeMap::from([("%storage".to_string(), 1)]);
|
||||
|
||||
assert!(reinterpret_mix_buffer_params(&blocks, &eligible).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reinterpret_mix_after_function_constant_pruning_marks_the_surviving_root() {
|
||||
let blocks = [block(&[
|
||||
"%hp = getelementptr half, ptr addrspace(2) %halves, i64 0",
|
||||
"%view = bitcast ptr addrspace(2) %hp to ptr addrspace(2)",
|
||||
"%vector = getelementptr <4 x float>, ptr addrspace(2) %view, i64 1",
|
||||
"%merged = phi ptr addrspace(2) [ %vector, %left ], [ %view, %right ]",
|
||||
"%next = getelementptr <4 x float>, ptr addrspace(2) %merged, i64 1",
|
||||
"%recurred = phi ptr addrspace(2) [ %next, %body ], [ %merged, %entry ]",
|
||||
"%value = load <4 x float>, ptr addrspace(2) %recurred",
|
||||
])];
|
||||
let eligible = BTreeMap::from([("%floats".to_string(), 29), ("%halves".to_string(), 29)]);
|
||||
|
||||
assert_eq!(
|
||||
reinterpret_mix_buffer_params(&blocks, &eligible),
|
||||
BTreeSet::from(["%halves".to_string()])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_phi_after_function_constant_pruning_is_not_raw_modeled() {
|
||||
let blocks = [block(&[
|
||||
"%hp = getelementptr half, ptr addrspace(2) %halves, i64 0",
|
||||
"%view = bitcast ptr addrspace(2) %hp to ptr addrspace(2)",
|
||||
"%vector = getelementptr <4 x float>, ptr addrspace(2) %view, i64 1",
|
||||
"%merged = phi ptr addrspace(2) [ %vector, %left ], [ %view, %right ]",
|
||||
"%value = load <4 x float>, ptr addrspace(2) %merged",
|
||||
])];
|
||||
let eligible = BTreeMap::from([("%floats".to_string(), 29), ("%halves".to_string(), 29)]);
|
||||
|
||||
assert!(reinterpret_mix_buffer_params(&blocks, &eligible).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reinterpret_mix_with_different_buffer_locations_is_not_raw_modeled() {
|
||||
let blocks = [block(&[
|
||||
"%fp = getelementptr float, ptr addrspace(2) %floats, i64 0",
|
||||
"%hp = getelementptr half, ptr addrspace(2) %halves, i64 0",
|
||||
"%picked = select i1 %condition, ptr addrspace(2) %hp, ptr addrspace(2) %fp",
|
||||
"%merged = phi ptr addrspace(2) [ %picked, %left ], [ %fp, %right ]",
|
||||
"%value = load <4 x float>, ptr addrspace(2) %merged",
|
||||
])];
|
||||
let eligible = BTreeMap::from([("%floats".to_string(), 28), ("%halves".to_string(), 29)]);
|
||||
|
||||
assert!(reinterpret_mix_buffer_params(&blocks, &eligible).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reinterpret_mix_with_unknown_pointer_producer_marks_no_partial_roots() {
|
||||
let blocks = [block(&[
|
||||
"%fp = getelementptr float, ptr addrspace(2) %floats, i64 0",
|
||||
"%opaque = call ptr addrspace(2) @pointer_source()",
|
||||
"%picked = select i1 %condition, ptr addrspace(2) %opaque, ptr addrspace(2) %fp",
|
||||
"%merged = phi ptr addrspace(2) [ %picked, %left ], [ %fp, %right ]",
|
||||
"%value = load <4 x i32>, ptr addrspace(2) %merged",
|
||||
])];
|
||||
let eligible = BTreeMap::from([("%floats".to_string(), 1)]);
|
||||
|
||||
assert!(reinterpret_mix_buffer_params(&blocks, &eligible).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_pointee_is_uniform() {
|
||||
assert_eq!(classify(&[LlType::Float]), NetworkClass::Uniform);
|
||||
@@ -561,6 +1134,34 @@ mod tests {
|
||||
assert_eq!(net.pointees, vec![LlType::Float]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cross_member_widening_load_selects_byte_addressed_root() {
|
||||
let blocks = [block(&[
|
||||
"%field = getelementptr %Payload, ptr addrspace(2) %buffer, i64 0, i32 1",
|
||||
"%alias = bitcast ptr addrspace(2) %field to ptr addrspace(2)",
|
||||
"%value = load <3 x float>, ptr addrspace(2) %alias",
|
||||
])];
|
||||
let params = HashSet::from(["%buffer".to_string()]);
|
||||
let named_types = HashMap::from([(
|
||||
"%Payload".to_string(),
|
||||
LlType::Struct(vec![LlType::Int(32), LlType::Float, LlType::Int(32)]),
|
||||
)]);
|
||||
assert_eq!(
|
||||
cross_member_widening_load_roots(&blocks, ¶ms, &named_types),
|
||||
BTreeSet::from(["%buffer".to_string()])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn array_element_widening_load_keeps_structured_root() {
|
||||
let blocks = [block(&[
|
||||
"%element = getelementptr [4 x float], ptr addrspace(2) %buffer, i64 0, i64 1",
|
||||
"%value = load <3 x float>, ptr addrspace(2) %element",
|
||||
])];
|
||||
let params = HashSet::from(["%buffer".to_string()]);
|
||||
assert!(cross_member_widening_load_roots(&blocks, ¶ms, &HashMap::new()).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn groups_select_arms_into_one_network() {
|
||||
let blocks = [block(&[
|
||||
|
||||
@@ -93,14 +93,18 @@ impl Emitter {
|
||||
if base_ptr_ty == want_ptr_type {
|
||||
return true;
|
||||
}
|
||||
// SPIR-V ground truth: if the base pointer's pointee is already a scalar type, any
|
||||
// multi-index structured chain over-indexes — flatten regardless of TypePointer id
|
||||
// equality (interning can leave distinct Words for the same shape in edge cases).
|
||||
if let Some(pointee_ty) = self.type_pointer_pointee_id(base_ptr_ty) {
|
||||
if self.spirv_type_is_scalar(pointee_ty) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
// An `OpPtrAccessChain` strides the base pointee; it cannot reinterpret that pointee.
|
||||
// Once the emitted Word type is available it is authoritative: flatten only when the
|
||||
// base and requested pointer types name the same scalar pointee. A byte pointer and a
|
||||
// wider integer pointer are both scalar, but treating them as interchangeable produces
|
||||
// a structurally invalid result type.
|
||||
return matches!(
|
||||
(
|
||||
self.type_pointer_pointee_id(base_ptr_ty),
|
||||
self.type_pointer_pointee_id(want_ptr_type)
|
||||
),
|
||||
(Some(base_pointee), Some(want_pointee)) if base_pointee == want_pointee
|
||||
);
|
||||
}
|
||||
if let Some(bp) = base_pointee {
|
||||
if let Ok(bp) = self.resolve_type(bp) {
|
||||
@@ -133,19 +137,6 @@ impl Emitter {
|
||||
None
|
||||
}
|
||||
|
||||
/// Whether a SPIR-V type id is a scalar (float/int/bool), not a composite.
|
||||
pub(in crate::native::emitter) fn spirv_type_is_scalar(&self, ty: Word) -> bool {
|
||||
for inst in &self.module.types_global_values {
|
||||
if inst.result_id == Some(ty) {
|
||||
return matches!(
|
||||
inst.class.opcode,
|
||||
Op::TypeFloat | Op::TypeInt | Op::TypeBool
|
||||
);
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Fold structured GEP `indices` through `source_ty` into a single offset in units of `scalar`.
|
||||
/// Returns `None` when the layout cannot be linearized (dynamic struct index, size mismatch,
|
||||
/// non-divisible stride) so the caller can leave the chain alone rather than miscompile.
|
||||
|
||||
@@ -63,6 +63,7 @@ fn pointer_arithmetic_access_chain_op_for_storage(
|
||||
if scalar_pointee
|
||||
&& ptr_access_chain_allowed_storage(storage)
|
||||
&& !base_is_indexed_container
|
||||
&& !indices.is_empty()
|
||||
&& indices.first().and_then(|idx| const_index(Some(idx))) != Some(0)
|
||||
{
|
||||
Op::PtrAccessChain
|
||||
@@ -71,6 +72,30 @@ fn pointer_arithmetic_access_chain_op_for_storage(
|
||||
}
|
||||
}
|
||||
|
||||
fn structural_pointer_index(
|
||||
position: usize,
|
||||
selected_ty: &mut LlType,
|
||||
index: &TypedValue,
|
||||
first_index_is_pointer_arithmetic: bool,
|
||||
) -> Option<bool> {
|
||||
if position == 0 && first_index_is_pointer_arithmetic {
|
||||
return Some(false);
|
||||
}
|
||||
if position == 0 && const_index(Some(index)) == Some(0) {
|
||||
return Some(true);
|
||||
}
|
||||
if let LlType::Struct(fields) = selected_ty {
|
||||
let member = const_index(Some(index))? as usize;
|
||||
*selected_ty = fields.get(member)?.clone();
|
||||
return Some(true);
|
||||
}
|
||||
*selected_ty = match selected_ty.clone() {
|
||||
LlType::Array(element, _) | LlType::Vector(element, _) => *element,
|
||||
other => other,
|
||||
};
|
||||
Some(false)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod pointee_upgrade_tests {
|
||||
//! Coverage for the M-A2 pointee-upgrade shape predicates (`is_scalar_pointee`,
|
||||
@@ -78,8 +103,11 @@ mod pointee_upgrade_tests {
|
||||
//! default-off byte→real / whole-vs-part / reinterpret flags upgrade a pointer's pointee; getting
|
||||
//! the shape test wrong would silently mis-upgrade (or fail to upgrade) at the `pointer_pointee_for_value`
|
||||
//! seam. Pure functions on already-resolved `LlType`s, so no emitter state is needed.
|
||||
use super::{is_scalar_pointee, reinterp_compatible, scalar_bit_width, whole_part_widens};
|
||||
use crate::native::ir::LlType;
|
||||
use super::{
|
||||
is_scalar_pointee, reinterp_compatible, scalar_bit_width, structural_pointer_index,
|
||||
whole_part_widens,
|
||||
};
|
||||
use crate::native::ir::{LlType, LlValue, TypedValue};
|
||||
|
||||
fn vec(elem: LlType, n: u32) -> LlType {
|
||||
LlType::Vector(Box::new(elem), n)
|
||||
@@ -88,6 +116,56 @@ mod pointee_upgrade_tests {
|
||||
LlType::Array(Box::new(elem), n)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn struct_pointer_indices_remain_literals() {
|
||||
let mut selected = LlType::Struct(vec![arr(LlType::Float, 4)]);
|
||||
let zero = TypedValue {
|
||||
ty: LlType::Int(32),
|
||||
value: LlValue::Int(0),
|
||||
};
|
||||
assert_eq!(
|
||||
structural_pointer_index(0, &mut selected, &zero, false),
|
||||
Some(true)
|
||||
);
|
||||
assert_eq!(
|
||||
structural_pointer_index(1, &mut selected, &zero, false),
|
||||
Some(true)
|
||||
);
|
||||
assert_eq!(selected, arr(LlType::Float, 4));
|
||||
|
||||
let dynamic = TypedValue {
|
||||
ty: LlType::Int(64),
|
||||
value: LlValue::Local("%index".into()),
|
||||
};
|
||||
assert_eq!(
|
||||
structural_pointer_index(2, &mut selected, &dynamic, false),
|
||||
Some(false)
|
||||
);
|
||||
assert_eq!(selected, LlType::Float);
|
||||
|
||||
let mut structure = LlType::Struct(vec![LlType::Float]);
|
||||
assert_eq!(
|
||||
structural_pointer_index(1, &mut structure, &dynamic, false),
|
||||
None
|
||||
);
|
||||
|
||||
let member_one = TypedValue {
|
||||
ty: LlType::Int(32),
|
||||
value: LlValue::Int(1),
|
||||
};
|
||||
let mut normalized_structure = LlType::Struct(vec![LlType::Int(32), LlType::Float]);
|
||||
assert_eq!(
|
||||
structural_pointer_index(0, &mut normalized_structure, &member_one, false),
|
||||
Some(true)
|
||||
);
|
||||
assert_eq!(normalized_structure, LlType::Float);
|
||||
let mut normalized_structure = LlType::Struct(vec![LlType::Float]);
|
||||
assert_eq!(
|
||||
structural_pointer_index(0, &mut normalized_structure, &dynamic, false),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalars_are_scalar_composites_are_not() {
|
||||
for s in [
|
||||
|
||||
@@ -6,7 +6,7 @@ use super::*;
|
||||
impl Emitter {
|
||||
/// The operand-resolved core of the `phi` handler. Driven from the parsed (unresolved) phi type + the
|
||||
/// `(value, predecessor-label)` pairs — either re-parsed by the text entry above or carried typed on
|
||||
/// `TirInst.phi_incoming`. Byte-identical either way: same `parse_phi` output, and the incoming VALUES
|
||||
/// `TirInst.phi_incoming()`. Byte-identical either way: same `parse_phi` output, and the incoming VALUES
|
||||
/// are then overlaid from the typed graph (`phi_incoming_values`), labels kept from the pairs.
|
||||
pub(in crate::native::emitter) fn emit_phi_resolved(
|
||||
&mut self,
|
||||
@@ -16,9 +16,18 @@ impl Emitter {
|
||||
instructions: &mut Vec<Instruction>,
|
||||
) -> Result<(), String> {
|
||||
let result_ty = self.resolve_type(phi_ty)?;
|
||||
// R3: source the incoming VALUES from the typed graph (labels stay from the parsed pairs).
|
||||
// Byte-identical to the parsed values by tir's phi-operand soundness; falls back on any mismatch.
|
||||
let incoming = self.phi_incoming_values(&name, parsed_incoming);
|
||||
// The typed instruction's canonical phi carrier supplies both values and labels directly.
|
||||
let incoming = if matches!(result_ty, LlType::Ptr(_)) {
|
||||
parsed_incoming
|
||||
.into_iter()
|
||||
.map(|(value, label)| (self.forwarded_pointer_value(&value), label))
|
||||
.collect()
|
||||
} else {
|
||||
parsed_incoming
|
||||
};
|
||||
if self.emit_selected_access_tree_phi(&name, &incoming, &result_ty, instructions)? {
|
||||
return Ok(());
|
||||
}
|
||||
if self.emit_bda_address_phi(&name, &incoming, &result_ty, instructions)? {
|
||||
return Ok(());
|
||||
}
|
||||
@@ -28,37 +37,190 @@ impl Emitter {
|
||||
if self.emit_unmodeled_pointer_phi(&name, &incoming, &result_ty, instructions)? {
|
||||
return Ok(());
|
||||
}
|
||||
let pointer_meta = self.pointer_merge_meta(
|
||||
let mut pointer_meta = self.pointer_merge_meta(
|
||||
&incoming.iter().map(|(value, _)| value).collect::<Vec<_>>(),
|
||||
&result_ty,
|
||||
)?;
|
||||
if self.null_rooted_pointer_values.contains(&name) {
|
||||
if let Some(meta) = pointer_meta.as_mut() {
|
||||
if meta.pointee.is_none() {
|
||||
let direct = self
|
||||
.tir_use_pointees
|
||||
.get(&name)
|
||||
.map(|pointee| self.resolve_type(pointee))
|
||||
.transpose()?;
|
||||
let peers = self
|
||||
.null_rooted_pointer_peers
|
||||
.get(&name)
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
let mut recurrence_pointees = Vec::new();
|
||||
for peer in peers {
|
||||
let Some(gep) = self.forward_geps.get(&peer).cloned() else {
|
||||
continue;
|
||||
};
|
||||
let source_ty = self.resolve_type(&gep.source_ty)?;
|
||||
let pointee = gep_pointee(&source_ty, &gep.indices)?;
|
||||
if !recurrence_pointees.contains(&pointee) {
|
||||
recurrence_pointees.push(pointee);
|
||||
}
|
||||
}
|
||||
meta.pointee = match (direct, recurrence_pointees.as_slice()) {
|
||||
(Some(direct), []) => Some(direct),
|
||||
(Some(direct), [recurrence]) if direct == *recurrence => Some(direct),
|
||||
(None, [recurrence]) => Some(recurrence.clone()),
|
||||
(None, []) => Some(LlType::Int(8)),
|
||||
_ => {
|
||||
return Err(format!(
|
||||
"native emitter: null-rooted pointer component has conflicting pointee contracts {recurrence_pointees:?}"
|
||||
));
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
let int_alignment = matches!(result_ty, LlType::Int(_))
|
||||
.then(|| self.merged_int_alignment(incoming.iter().map(|(value, _)| value.clone())));
|
||||
let pointer_provenance =
|
||||
self.emit_pointer_phi_provenance(&name, &incoming, instructions)?;
|
||||
let pointer_provenance = if self.null_rooted_pointer_values.contains(&name) {
|
||||
None
|
||||
} else {
|
||||
self.emit_pointer_phi_provenance(&name, &incoming, instructions)?
|
||||
};
|
||||
self.emit_pointer_nullness_phi(&name, &incoming, &result_ty, instructions)?;
|
||||
if self.null_rooted_pointer_values.contains(&name) {
|
||||
let Some(meta) = pointer_meta.as_ref() else {
|
||||
return Err(
|
||||
"native emitter: null-rooted pointer phi has no storage contract".into(),
|
||||
);
|
||||
};
|
||||
let Some(pointee) = meta.pointee.as_ref() else {
|
||||
return Err(
|
||||
"native emitter: null-rooted pointer phi has no pointee contract".into(),
|
||||
);
|
||||
};
|
||||
let result_type = self.ptr_type_id(meta.storage, pointee)?;
|
||||
let result = self.result_id(&name, &result_ty)?;
|
||||
self.module.types_global_values.push(Self::inst(
|
||||
Op::Undef,
|
||||
Some(result_type),
|
||||
Some(result),
|
||||
vec![],
|
||||
));
|
||||
self.record_pointer_meta(name, meta.clone());
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(meta) = pointer_meta.as_ref().filter(|meta| {
|
||||
pointer_provenance.is_none()
|
||||
&& matches!(meta.storage, StorageClass::Private | StorageClass::Function)
|
||||
}) {
|
||||
let Some((first, _)) = incoming.first() else {
|
||||
return Err(format!(
|
||||
"native emitter: pointer phi {name} has no incoming values"
|
||||
));
|
||||
};
|
||||
if incoming.iter().all(|(value, _)| value == first) {
|
||||
let result = match first {
|
||||
LlValue::Zero | LlValue::Undef => {
|
||||
let pointee = meta.pointee.as_ref().ok_or_else(|| {
|
||||
format!(
|
||||
"native emitter: collapsed pointer phi {name} has no pointee contract"
|
||||
)
|
||||
})?;
|
||||
let result_type = self.ptr_type_id(meta.storage, pointee)?;
|
||||
let result = self.fresh();
|
||||
self.module.types_global_values.push(Self::inst(
|
||||
Op::Undef,
|
||||
Some(result_type),
|
||||
Some(result),
|
||||
vec![],
|
||||
));
|
||||
result
|
||||
}
|
||||
_ => self.value_id(first, &result_ty)?,
|
||||
};
|
||||
self.values
|
||||
.insert(name.clone(), (result, result_ty.clone()));
|
||||
self.record_pointer_meta(name, meta.clone());
|
||||
return Ok(());
|
||||
}
|
||||
return Err(format!(
|
||||
"native emitter: {:?} pointer phi {name} has differing structural sources",
|
||||
meta.storage
|
||||
));
|
||||
}
|
||||
if let (
|
||||
Some(
|
||||
meta @ PointerMeta {
|
||||
storage,
|
||||
pointee: Some(pointee),
|
||||
},
|
||||
),
|
||||
Some(provenance),
|
||||
) = (pointer_meta.as_ref(), pointer_provenance.as_ref())
|
||||
{
|
||||
// A same-root pointer merge is an index merge in every storage class. Emit the index
|
||||
// phis above and rematerialize one pointer after the leading-phi region. StorageBuffer
|
||||
// and Workgroup used to fall through to a legal pointer OpPhi and rely on the universal
|
||||
// post-validation portability rewrite to discover this same provenance again. Keeping
|
||||
// the source provenance here makes the emitted module portable by construction and
|
||||
// avoids declaring VariablePointersStorageBuffer for an operation that needs no pointer
|
||||
// SSA merge.
|
||||
let result_type = self.ptr_type_id(*storage, pointee)?;
|
||||
let result = self.result_id(&name, &result_ty)?;
|
||||
let op = pointer_arithmetic_access_chain_op_for_storage(
|
||||
*storage,
|
||||
provenance.root_is_indexed_container,
|
||||
pointee,
|
||||
&provenance.indices,
|
||||
);
|
||||
let mut operands = vec![Operand::IdRef(provenance.root)];
|
||||
for index in gep_spirv_indices(&provenance.indices)? {
|
||||
operands.push(Operand::IdRef(self.value_id(&index.value, &index.ty)?));
|
||||
}
|
||||
self.phi_result_instructions.push(Self::inst(
|
||||
op,
|
||||
Some(result_type),
|
||||
Some(result),
|
||||
operands,
|
||||
));
|
||||
self.record_pointer_meta(name.clone(), meta.clone());
|
||||
self.gep_provenance.insert(name.clone(), provenance.clone());
|
||||
return Ok(());
|
||||
}
|
||||
if matches!(
|
||||
pointer_meta,
|
||||
Some(PointerMeta {
|
||||
storage: StorageClass::Function,
|
||||
..
|
||||
})
|
||||
) {
|
||||
return Err(format!(
|
||||
"native emitter: Function pointer phi {name} has no exact index-domain representation from {incoming:?}"
|
||||
));
|
||||
}
|
||||
let result_type = self.pointer_aware_type_id(&result_ty, pointer_meta.as_ref())?;
|
||||
let result = self.result_id(&name, &result_ty)?;
|
||||
let mut ops = Vec::new();
|
||||
let mut seen_incoming: HashMap<Word, Word> = HashMap::new();
|
||||
for (value, label) in incoming {
|
||||
let mut edge_instructions = Vec::new();
|
||||
let value_id = if let Some(meta) = pointer_meta.as_ref() {
|
||||
self.pointer_phi_value_id(
|
||||
&value,
|
||||
&result_ty,
|
||||
meta,
|
||||
pointer_provenance.as_ref(),
|
||||
instructions,
|
||||
&mut edge_instructions,
|
||||
)?
|
||||
} else {
|
||||
self.phi_value_id(&value, &result_ty, instructions)?
|
||||
self.phi_value_id(&value, &result_ty, &mut edge_instructions)?
|
||||
};
|
||||
let label_id = self.label_id(&label)?;
|
||||
self.record_phi_edge_instructions(label_id, edge_instructions);
|
||||
if let Some(existing) = seen_incoming.insert(label_id, value_id) {
|
||||
if existing != value_id {
|
||||
return Err(format!(
|
||||
"native emitter: phi has multiple values from predecessor {}",
|
||||
label
|
||||
"native emitter: phi {name} has multiple values from predecessor {label}"
|
||||
));
|
||||
}
|
||||
continue;
|
||||
@@ -79,6 +241,219 @@ impl Emitter {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn forwarded_pointer_value(&self, value: &LlValue) -> LlValue {
|
||||
let mut value = value.clone();
|
||||
let mut visited = HashSet::new();
|
||||
while let LlValue::Local(name) = &value {
|
||||
if !visited.insert(name.clone()) {
|
||||
break;
|
||||
}
|
||||
let Some(source) = self.pointer_forward_values.get(name) else {
|
||||
break;
|
||||
};
|
||||
value = source.value.clone();
|
||||
}
|
||||
value
|
||||
}
|
||||
|
||||
fn emit_selected_access_tree_phi(
|
||||
&mut self,
|
||||
name: &str,
|
||||
incoming: &[(LlValue, String)],
|
||||
result_ty: &LlType,
|
||||
instructions: &mut Vec<Instruction>,
|
||||
) -> Result<bool, String> {
|
||||
let LlType::Ptr(_) = result_ty else {
|
||||
return Ok(false);
|
||||
};
|
||||
let pointee = self
|
||||
.tir_use_pointees
|
||||
.get(name)
|
||||
.cloned()
|
||||
.or_else(|| self.pointer_pointees.get(name).cloned());
|
||||
let Some(pointee) = pointee else {
|
||||
return Ok(false);
|
||||
};
|
||||
let mut trees = Vec::with_capacity(incoming.len());
|
||||
for (value, label) in incoming {
|
||||
let LlValue::Local(local) = value else {
|
||||
return Ok(false);
|
||||
};
|
||||
let tree = if let Some(tree) = self.selected_access_trees.get(local).cloned() {
|
||||
if !types_compatible(&self.resolve_type(&tree.pointee)?, &pointee) {
|
||||
return Ok(false);
|
||||
}
|
||||
tree
|
||||
} else if let Some(selected) = self.selected_pointers.get(local).cloned() {
|
||||
self.build_selected_access_tree(
|
||||
&selected,
|
||||
&pointee,
|
||||
&[],
|
||||
&mut HashSet::new(),
|
||||
instructions,
|
||||
)?
|
||||
} else {
|
||||
return Ok(false);
|
||||
};
|
||||
trees.push((tree, self.label_id(label)?));
|
||||
}
|
||||
let Some(tree) = self.merge_selected_access_tree_phi(&trees, instructions)? else {
|
||||
return Ok(false);
|
||||
};
|
||||
self.pointer_pointees
|
||||
.insert(name.to_string(), tree.pointee.clone());
|
||||
self.selected_access_trees.insert(name.to_string(), tree);
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn merge_selected_access_tree_phi(
|
||||
&mut self,
|
||||
trees: &[(SelectedAccessTree, Word)],
|
||||
instructions: &mut Vec<Instruction>,
|
||||
) -> Result<Option<SelectedAccessTree>, String> {
|
||||
let Some((first, _)) = trees.first() else {
|
||||
return Ok(None);
|
||||
};
|
||||
if trees
|
||||
.iter()
|
||||
.any(|(tree, _)| !types_compatible(&tree.pointee, &first.pointee))
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
let cond = self.merge_selected_phi_ids(
|
||||
trees.iter().map(|(tree, label)| (tree.cond, *label)),
|
||||
&LlType::Bool,
|
||||
instructions,
|
||||
)?;
|
||||
let true_arms = trees
|
||||
.iter()
|
||||
.map(|(tree, label)| (&tree.true_arm, *label))
|
||||
.collect::<Vec<_>>();
|
||||
let false_arms = trees
|
||||
.iter()
|
||||
.map(|(tree, label)| (&tree.false_arm, *label))
|
||||
.collect::<Vec<_>>();
|
||||
let Some(true_arm) =
|
||||
self.merge_selected_access_arm_phi(&true_arms, &first.pointee, instructions)?
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
let Some(false_arm) =
|
||||
self.merge_selected_access_arm_phi(&false_arms, &first.pointee, instructions)?
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
Ok(Some(SelectedAccessTree {
|
||||
cond,
|
||||
true_arm,
|
||||
false_arm,
|
||||
pointee: first.pointee.clone(),
|
||||
}))
|
||||
}
|
||||
|
||||
fn merge_selected_access_arm_phi(
|
||||
&mut self,
|
||||
arms: &[(&SelectedAccessArm, Word)],
|
||||
pointee: &LlType,
|
||||
instructions: &mut Vec<Instruction>,
|
||||
) -> Result<Option<SelectedAccessArm>, String> {
|
||||
let Some((first, _)) = arms.first() else {
|
||||
return Ok(None);
|
||||
};
|
||||
match first {
|
||||
SelectedAccessArm::Typed { storage, .. }
|
||||
if arms.iter().all(|(arm, _)| {
|
||||
matches!(arm, SelectedAccessArm::Typed { storage: arm_storage, .. } if arm_storage == storage)
|
||||
}) =>
|
||||
{
|
||||
let ptr_type = self.ptr_type_id(*storage, pointee)?;
|
||||
let ids = arms.iter().map(|(arm, label)| {
|
||||
let SelectedAccessArm::Typed { ptr, .. } = arm else {
|
||||
unreachable!("shape checked above");
|
||||
};
|
||||
(*ptr, *label)
|
||||
});
|
||||
let ptr = self.merge_selected_phi_ids_with_type(ids, ptr_type, instructions);
|
||||
Ok(Some(SelectedAccessArm::Typed {
|
||||
ptr,
|
||||
storage: *storage,
|
||||
}))
|
||||
}
|
||||
SelectedAccessArm::Nested(_) if arms.iter().all(|(arm, _)| {
|
||||
matches!(arm, SelectedAccessArm::Nested(_))
|
||||
}) => {
|
||||
let nested = arms
|
||||
.iter()
|
||||
.map(|(arm, label)| {
|
||||
let SelectedAccessArm::Nested(tree) = arm else {
|
||||
unreachable!("shape checked above");
|
||||
};
|
||||
((**tree).clone(), *label)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
Ok(self
|
||||
.merge_selected_access_tree_phi(&nested, instructions)?
|
||||
.map(|tree| SelectedAccessArm::Nested(Box::new(tree))))
|
||||
}
|
||||
SelectedAccessArm::Null
|
||||
if arms
|
||||
.iter()
|
||||
.all(|(arm, _)| matches!(arm, SelectedAccessArm::Null)) =>
|
||||
{
|
||||
Ok(Some(SelectedAccessArm::Null))
|
||||
}
|
||||
_ => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
fn merge_selected_phi_ids(
|
||||
&mut self,
|
||||
ids: impl Iterator<Item = (Word, Word)>,
|
||||
ty: &LlType,
|
||||
instructions: &mut Vec<Instruction>,
|
||||
) -> Result<Word, String> {
|
||||
let result_type = self.type_id(ty)?;
|
||||
Ok(self.merge_selected_phi_ids_with_type(ids, result_type, instructions))
|
||||
}
|
||||
|
||||
fn merge_selected_phi_ids_with_type(
|
||||
&mut self,
|
||||
ids: impl Iterator<Item = (Word, Word)>,
|
||||
result_type: Word,
|
||||
instructions: &mut Vec<Instruction>,
|
||||
) -> Word {
|
||||
let ids = ids.collect::<Vec<_>>();
|
||||
if ids.iter().all(|(id, _)| *id == ids[0].0) {
|
||||
return ids[0].0;
|
||||
}
|
||||
let result = self.fresh();
|
||||
let operands = ids
|
||||
.into_iter()
|
||||
.flat_map(|(id, label)| [Operand::IdRef(id), Operand::IdRef(label)])
|
||||
.collect();
|
||||
instructions.push(Self::inst(
|
||||
Op::Phi,
|
||||
Some(result_type),
|
||||
Some(result),
|
||||
operands,
|
||||
));
|
||||
result
|
||||
}
|
||||
|
||||
pub(in crate::native) fn record_phi_edge_instructions(
|
||||
&mut self,
|
||||
predecessor: Word,
|
||||
instructions: Vec<Instruction>,
|
||||
) {
|
||||
if instructions.is_empty() {
|
||||
return;
|
||||
}
|
||||
self.phi_edge_instructions
|
||||
.entry(predecessor)
|
||||
.or_default()
|
||||
.extend(instructions);
|
||||
}
|
||||
|
||||
pub(in crate::native::emitter) fn pointer_phi_value_id(
|
||||
&mut self,
|
||||
value: &LlValue,
|
||||
@@ -137,6 +512,12 @@ impl Emitter {
|
||||
}
|
||||
let ptr_ty = self.ptr_type_id(meta.storage, pointee)?;
|
||||
let result = self.fresh();
|
||||
let op = pointer_arithmetic_access_chain_op_for_storage(
|
||||
meta.storage,
|
||||
provenance.root_is_indexed_container,
|
||||
pointee,
|
||||
&provenance.indices,
|
||||
);
|
||||
let mut ops = vec![Operand::IdRef(provenance.root)];
|
||||
let mut indices = gep_spirv_indices(&provenance.indices)?;
|
||||
if indices.is_empty() && !provenance.indices.is_empty() {
|
||||
@@ -145,17 +526,12 @@ impl Emitter {
|
||||
for idx in indices {
|
||||
ops.push(Operand::IdRef(self.value_id(&idx.value, &idx.ty)?));
|
||||
}
|
||||
instructions.push(Self::inst(
|
||||
Op::InBoundsAccessChain,
|
||||
Some(ptr_ty),
|
||||
Some(result),
|
||||
ops,
|
||||
));
|
||||
instructions.push(Self::inst(op, Some(ptr_ty), Some(result), ops));
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// The predicate-and-operand-resolved core of the `fcmp` handler — the M-A4 graph walk drives it from
|
||||
/// `TirInst.cmp_predicate` (mapped through `fcmp_predicate`) + `TirInst.operands`, byte-identical to
|
||||
/// `TirInst.cmp_predicate()` (mapped through `fcmp_predicate`) + `TirInst.operands`, byte-identical to
|
||||
/// the text path (which sources the same predicate token + operands from the tir carrier).
|
||||
pub(in crate::native::emitter) fn emit_fcmp_resolved(
|
||||
&mut self,
|
||||
@@ -242,10 +618,10 @@ impl Emitter {
|
||||
|
||||
/// The POINTER core of `emit_icmp`: emit a pointer equality/inequality (direct-param constant fold,
|
||||
/// provenance compare, payload-word compare, or null compare) given the resolved predicate + typed
|
||||
/// operands. Split out so the M-A4 graph walk drives it straight from `TirInst.cmp_predicate` +
|
||||
/// operands. Split out so the M-A4 graph walk drives it straight from `TirInst.cmp_predicate()` +
|
||||
/// `TirInst.operands` (the pointer form was the last opcode still falling through to the text
|
||||
/// substrate). `rest` is the operand TEXT, needed ONLY for the two unsupported-form error diagnostics
|
||||
/// (which BC fingerprints); the graph walk passes it from the diagnostics-only `TirInst.icmp_rest`
|
||||
/// (which BC fingerprints); the graph walk passes it from the diagnostics-only `TirInst.icmp_rest()`
|
||||
/// carrier (byte-identical to the text path's `rest`), so no `inst.text` re-lex.
|
||||
pub(in crate::native::emitter) fn emit_icmp_ptr_resolved(
|
||||
&mut self,
|
||||
@@ -382,9 +758,9 @@ impl Emitter {
|
||||
|
||||
/// The NON-pointer core of `emit_icmp`: emit a scalar/vector integer compare given its resolved
|
||||
/// predicate `Op`, typed operands, and (already-resolved) operand type. Extracted so the M-A4 graph
|
||||
/// walk can drive it straight from `TirInst.cmp_predicate` + `TirInst.operands` for the common
|
||||
/// walk can drive it straight from `TirInst.cmp_predicate()` + `TirInst.operands` for the common
|
||||
/// (non-pointer) case — byte-identical to the text path. The POINTER icmp forms are driven the same way
|
||||
/// via `emit_icmp_ptr_resolved`, with the operand `rest` supplied from the `TirInst.icmp_rest` carrier
|
||||
/// via `emit_icmp_ptr_resolved`, with the operand `rest` supplied from the `TirInst.icmp_rest()` carrier
|
||||
/// for their error diagnostics.
|
||||
pub(in crate::native::emitter) fn emit_icmp_int_resolved(
|
||||
&mut self,
|
||||
@@ -429,20 +805,31 @@ impl Emitter {
|
||||
) else {
|
||||
return Ok(false);
|
||||
};
|
||||
if lhs_raw.root != rhs_raw.root
|
||||
|| lhs_raw.addrspace != rhs_raw.addrspace
|
||||
|| lhs_raw.device_addr_base != rhs_raw.device_addr_base
|
||||
|| lhs_raw.unmodelable
|
||||
|| rhs_raw.unmodelable
|
||||
{
|
||||
if lhs_raw.unmodelable || rhs_raw.unmodelable {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
let result_ty = LlType::Bool;
|
||||
let result_type = self.type_id(&result_ty)?;
|
||||
let equal = self.fresh();
|
||||
let lhs_index = self.emit_raw_byte_index(&lhs_raw, 0, instructions)?;
|
||||
let rhs_index = self.emit_raw_byte_index(&rhs_raw, 0, instructions)?;
|
||||
let (lhs_index, rhs_index) = match (
|
||||
lhs_raw.device_addr_base.is_some(),
|
||||
rhs_raw.device_addr_base.is_some(),
|
||||
) {
|
||||
(true, true) => (
|
||||
self.materialize_device_address(&lhs_raw, instructions)?,
|
||||
self.materialize_device_address(&rhs_raw, instructions)?,
|
||||
),
|
||||
(false, false)
|
||||
if lhs_raw.root == rhs_raw.root && lhs_raw.addrspace == rhs_raw.addrspace =>
|
||||
{
|
||||
(
|
||||
self.emit_raw_byte_index(&lhs_raw, 0, instructions)?,
|
||||
self.emit_raw_byte_index(&rhs_raw, 0, instructions)?,
|
||||
)
|
||||
}
|
||||
_ => return Ok(false),
|
||||
};
|
||||
instructions.push(Self::inst(
|
||||
Op::IEqual,
|
||||
Some(result_type),
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
use super::*;
|
||||
|
||||
impl Emitter {
|
||||
/// Lower an addrspace(1) pointer phi as a phi of 64-bit byte addresses when every arm has an
|
||||
/// Lower a buffer-addressable pointer phi as a phi of 64-bit byte addresses when every arm has an
|
||||
/// exact address-domain representation: either a direct Metal buffer root supplied by the
|
||||
/// reflected address sidecar, or an `inttoptr`/BDA raw value. This is the structural shape used
|
||||
/// by device-address hierarchies: the root arm starts at a bound acceleration-structure buffer
|
||||
@@ -15,25 +15,18 @@ impl Emitter {
|
||||
result_ty: &LlType,
|
||||
instructions: &mut Vec<Instruction>,
|
||||
) -> Result<bool, String> {
|
||||
if !self.bda_device_pointers || *result_ty != LlType::Ptr(1) {
|
||||
let Some(result) = self.reserve_bda_address_phi(name, incoming, result_ty)? else {
|
||||
return Ok(false);
|
||||
}
|
||||
if !incoming
|
||||
.iter()
|
||||
.all(|(value, _)| self.bda_phi_value_is_addressable(value))
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
};
|
||||
let address_ty = LlType::Int(64);
|
||||
let result_type = self.type_id(&address_ty)?;
|
||||
let result_name = bda_address_name(name);
|
||||
let result = self.result_id(&result_name, &address_ty)?;
|
||||
let mut ops = Vec::new();
|
||||
let mut seen_incoming: HashMap<Word, Word> = HashMap::new();
|
||||
for (value, label) in incoming {
|
||||
let value_id = self.bda_phi_address_id(value)?;
|
||||
let label_id = self.label_id(label)?;
|
||||
let mut edge_instructions = Vec::new();
|
||||
let value_id = self.bda_phi_address_id(value, &mut edge_instructions)?;
|
||||
self.record_phi_edge_instructions(label_id, edge_instructions);
|
||||
if let Some(existing) = seen_incoming.insert(label_id, value_id) {
|
||||
if existing != value_id {
|
||||
return Err(format!(
|
||||
@@ -48,21 +41,58 @@ impl Emitter {
|
||||
instructions.push(Self::inst(Op::Phi, Some(result_type), Some(result), ops));
|
||||
self.emit_pointer_nullness_phi(name, incoming, result_ty, instructions)?;
|
||||
self.used_device_address = true;
|
||||
let mut raw = RawBufferOffset::root(format!(".bda_phi_{name}"), 1);
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub(in crate::native::emitter) fn reserve_bda_address_phi(
|
||||
&mut self,
|
||||
name: &str,
|
||||
incoming: &[(LlValue, String)],
|
||||
result_ty: &LlType,
|
||||
) -> Result<Option<Word>, String> {
|
||||
let LlType::Ptr(addrspace @ 0..=2) = result_ty else {
|
||||
return Ok(None);
|
||||
};
|
||||
if !self.bda_device_pointers
|
||||
|| !incoming
|
||||
.iter()
|
||||
.all(|(value, _)| self.bda_phi_value_is_addressable(value))
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let result = self.result_id(&bda_address_name(name), &LlType::Int(64))?;
|
||||
if let Some((logical_result, _)) = self.values.get(name).cloned() {
|
||||
self.phi_result_instructions
|
||||
.retain(|instruction| instruction.result_id != Some(logical_result));
|
||||
self.emit_sidecar
|
||||
.remap_ids(&HashMap::from([(logical_result, result)]));
|
||||
}
|
||||
let mut raw = RawBufferOffset::root(format!(".bda_phi_{name}"), *addrspace);
|
||||
raw.device_addr_base = Some(result);
|
||||
self.raw_offsets.insert(name.to_string(), raw);
|
||||
self.pointer_storage
|
||||
.insert(name.to_string(), StorageClass::PhysicalStorageBuffer);
|
||||
self.pointer_pointees
|
||||
.insert(name.to_string(), LlType::Int(8));
|
||||
Ok(true)
|
||||
self.gep_provenance.remove(name);
|
||||
Ok(Some(result))
|
||||
}
|
||||
|
||||
fn bda_phi_value_is_addressable(&self, value: &LlValue) -> bool {
|
||||
pub(in crate::native::emitter) fn bda_phi_value_is_addressable(&self, value: &LlValue) -> bool {
|
||||
self.bda_phi_value_is_addressable_inner(value, &mut HashSet::new())
|
||||
}
|
||||
|
||||
fn bda_phi_value_is_addressable_inner(
|
||||
&self,
|
||||
value: &LlValue,
|
||||
visiting: &mut HashSet<String>,
|
||||
) -> bool {
|
||||
match value {
|
||||
LlValue::Zero => true,
|
||||
LlValue::Zero | LlValue::Undef => true,
|
||||
LlValue::Local(name) => {
|
||||
self.bda_inttoptr_sources.contains_key(name)
|
||||
if self.bda_inttoptr_sources.contains_key(name)
|
||||
|| self.bda_forward_addresses.contains(name)
|
||||
|| self.bda_direct_addresses.contains_key(name)
|
||||
|| self.raw_offsets.get(name).is_some_and(|raw| {
|
||||
raw.const_off == 0
|
||||
@@ -70,14 +100,38 @@ impl Emitter {
|
||||
&& (raw.device_addr_base.is_some()
|
||||
|| self.bda_direct_addresses.contains_key(&raw.root))
|
||||
})
|
||||
{
|
||||
return true;
|
||||
}
|
||||
let Some(incoming) = self.tir_phi_incomings.get(name) else {
|
||||
return false;
|
||||
};
|
||||
// Pointer state introduced by construct-tree is a mutually recursive phi network:
|
||||
// the header reads the next-state phi and the next-state phi retains the header on
|
||||
// edges that do not update it. A revisit proves only that this edge stays within the
|
||||
// network; concrete leaves still have to be direct addresses, inttoptr values, zero,
|
||||
// or undef. This is the greatest fixed point over that finite typed network.
|
||||
if !visiting.insert(name.clone()) {
|
||||
return true;
|
||||
}
|
||||
let addressable = incoming
|
||||
.iter()
|
||||
.all(|(value, _)| self.bda_phi_value_is_addressable_inner(value, visiting));
|
||||
visiting.remove(name);
|
||||
addressable
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn bda_phi_address_id(&mut self, value: &LlValue) -> Result<Word, String> {
|
||||
fn bda_phi_address_id(
|
||||
&mut self,
|
||||
value: &LlValue,
|
||||
instructions: &mut Vec<Instruction>,
|
||||
) -> Result<Word, String> {
|
||||
match value {
|
||||
LlValue::Zero => self.const_signed_int(64, 0),
|
||||
LlValue::Undef => self.undef_id(&LlType::Int(64)),
|
||||
LlValue::Local(name) => {
|
||||
if let Some(address) = self.bda_direct_addresses.get(name).copied() {
|
||||
return Ok(address);
|
||||
@@ -92,9 +146,123 @@ impl Emitter {
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(raw) = self
|
||||
.raw_offsets
|
||||
.get(name)
|
||||
.filter(|raw| raw.device_addr_base.is_some())
|
||||
.cloned()
|
||||
{
|
||||
let address = self.materialize_device_address(&raw, instructions)?;
|
||||
self.bda_address_values.insert(address);
|
||||
return Ok(address);
|
||||
}
|
||||
if self.bda_address_loads.contains(name) {
|
||||
let result_ty = self.tir_result_types.get(name).cloned().ok_or_else(|| {
|
||||
format!("native emitter: BDA pointer load {name} has no result type")
|
||||
})?;
|
||||
let address = self.result_id(name, &result_ty)?;
|
||||
self.bda_address_values.insert(address);
|
||||
return Ok(address);
|
||||
}
|
||||
if let Some(source) = self.bda_forward_sources.get(name).cloned() {
|
||||
return self.bda_phi_address_id(&source.value, instructions);
|
||||
}
|
||||
if let (Some((true_value, false_value)), Some(condition)) = (
|
||||
self.forward_pointer_selects.get(name).cloned(),
|
||||
self.forward_pointer_select_conditions.get(name).cloned(),
|
||||
) {
|
||||
let true_address = self.bda_phi_address_id(&true_value.value, instructions)?;
|
||||
let false_address =
|
||||
self.bda_phi_address_id(&false_value.value, instructions)?;
|
||||
let condition =
|
||||
self.value_id_in(&condition.value, &condition.ty, instructions)?;
|
||||
let address_type = self.type_id(&LlType::Int(64))?;
|
||||
let address = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
Op::Select,
|
||||
Some(address_type),
|
||||
Some(address),
|
||||
vec![
|
||||
Operand::IdRef(condition),
|
||||
Operand::IdRef(true_address),
|
||||
Operand::IdRef(false_address),
|
||||
],
|
||||
));
|
||||
self.bda_address_values.insert(address);
|
||||
self.bda_direct_addresses.insert(name.clone(), address);
|
||||
return Ok(address);
|
||||
}
|
||||
if let Some(gep) = self.forward_geps.get(name).cloned() {
|
||||
let root = match &gep.base.value {
|
||||
LlValue::Local(base_name) => base_name.clone(),
|
||||
LlValue::Zero | LlValue::Undef => format!(".bda_forward_gep_{name}"),
|
||||
other => {
|
||||
return Err(if crate::env_vars::retry_debug() {
|
||||
format!(
|
||||
"native emitter: forward BDA GEP {name} has an unsupported base {other:?} in {gep:?}"
|
||||
)
|
||||
} else {
|
||||
"native emitter: forward BDA GEP has an unsupported base"
|
||||
.to_string()
|
||||
});
|
||||
}
|
||||
};
|
||||
let base_address = self.bda_phi_address_id(&gep.base.value, instructions)?;
|
||||
let LlType::Ptr(addrspace) = self.resolve_type(&gep.base.ty)? else {
|
||||
return Err(
|
||||
"native emitter: forward BDA GEP base is not a pointer".to_string()
|
||||
);
|
||||
};
|
||||
let source_type = self.resolve_type(&gep.source_ty)?;
|
||||
let mut raw = RawBufferOffset::root(root, addrspace);
|
||||
raw.device_addr_base = Some(base_address);
|
||||
let raw = self.apply_raw_gep(raw, &source_type, &gep.indices)?;
|
||||
if !raw.unmodelable {
|
||||
let address = self.materialize_device_address(&raw, instructions)?;
|
||||
self.bda_address_values.insert(address);
|
||||
return Ok(address);
|
||||
}
|
||||
}
|
||||
if let Some((pointer, LlType::Ptr(_))) = self.values.get(name).cloned() {
|
||||
if self.pointer_storage.get(name) == Some(&StorageClass::PhysicalStorageBuffer)
|
||||
{
|
||||
let address_type = self.type_id(&LlType::Int(64))?;
|
||||
let address = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
Op::ConvertPtrToU,
|
||||
Some(address_type),
|
||||
Some(address),
|
||||
vec![Operand::IdRef(pointer)],
|
||||
));
|
||||
self.bda_address_values.insert(address);
|
||||
return Ok(address);
|
||||
}
|
||||
}
|
||||
if let Some(source) = self.bda_inttoptr_sources.get(name).cloned() {
|
||||
return self.phi_value_id(&source.value, &source.ty, &mut Vec::new());
|
||||
}
|
||||
// A construct-tree header may reference its next-state phi before that block is
|
||||
// emitted. Reserve the typed phi's address result now; its OpPhi definition is
|
||||
// emitted at the ordinary block position and SPIR-V permits this forward edge use.
|
||||
if let (Some(incoming), Some(result_ty)) = (
|
||||
self.tir_phi_incomings.get(name).cloned(),
|
||||
self.tir_result_types.get(name).cloned(),
|
||||
) {
|
||||
if self
|
||||
.reserve_bda_address_phi(name, &incoming, &result_ty)?
|
||||
.is_some()
|
||||
{
|
||||
return self
|
||||
.raw_offsets
|
||||
.get(name)
|
||||
.and_then(|raw| raw.device_addr_base)
|
||||
.ok_or_else(|| {
|
||||
format!(
|
||||
"native emitter: reserved BDA pointer {name} has no address result"
|
||||
)
|
||||
});
|
||||
}
|
||||
}
|
||||
Err(format!(
|
||||
"native emitter: pointer {name} has no exact BDA address representation"
|
||||
))
|
||||
@@ -138,7 +306,7 @@ impl Emitter {
|
||||
};
|
||||
if saw_meta && merged.storage != meta.storage {
|
||||
return Err(format!(
|
||||
"native emitter: pointer merge storage mismatch {:?} vs {:?} at {value:?}",
|
||||
"native emitter: pointer merge storage mismatch {:?} vs {:?} at {value:?} across {values:?}",
|
||||
merged.storage, meta.storage
|
||||
));
|
||||
}
|
||||
@@ -148,7 +316,7 @@ impl Emitter {
|
||||
match &merged.pointee {
|
||||
Some(existing) if existing != &pointee => {
|
||||
return Err(format!(
|
||||
"native emitter: pointer merge pointee mismatch {existing:?} vs {pointee:?}"
|
||||
"native emitter: pointer merge pointee mismatch {existing:?} vs {pointee:?} across {values:?}"
|
||||
));
|
||||
}
|
||||
None => merged.pointee = Some(pointee),
|
||||
@@ -258,7 +426,7 @@ impl Emitter {
|
||||
// fallback the emitter doc names as debt, without touching the raw-addressing path.
|
||||
//
|
||||
// Also EXCLUDE any pointer that carries a byte (`i8`) view in its uses
|
||||
// (`tir_byte_view_pointers`): a pointer dereferenced BOTH as a byte cursor
|
||||
// (`byte_view_pointers`): a pointer dereferenced BOTH as a byte cursor
|
||||
// (`getelementptr i8` → `uchar`-result `OpPtrAccessChain`) AND as a wider type. Its
|
||||
// carrier resolves to the wider type, but the byte cursor still expects a
|
||||
// `uchar`-pointee base, so upgrading the pointee strands it and emits globally-invalid
|
||||
@@ -269,7 +437,7 @@ impl Emitter {
|
||||
if *pointee == LlType::Int(8)
|
||||
&& !self.raw_offsets.contains_key(name)
|
||||
&& !self.unmodeled_pointers.contains(name)
|
||||
&& !self.tir_byte_view_pointers.contains(name)
|
||||
&& !self.byte_view_pointers.contains(name)
|
||||
{
|
||||
if let Some(carrier) = self.tir_use_pointees.get(name) {
|
||||
let carrier = self.resolve_type(carrier)?;
|
||||
@@ -299,7 +467,7 @@ impl Emitter {
|
||||
&& is_scalar_pointee(pointee)
|
||||
&& !self.raw_offsets.contains_key(name)
|
||||
&& !self.unmodeled_pointers.contains(name)
|
||||
&& !self.tir_byte_view_pointers.contains(name)
|
||||
&& !self.byte_view_pointers.contains(name)
|
||||
&& !self.pointer_in_pointer_merge(name)
|
||||
{
|
||||
if let Some(carrier) = self.tir_use_pointees.get(name) {
|
||||
@@ -327,7 +495,7 @@ impl Emitter {
|
||||
&& is_scalar_pointee(pointee)
|
||||
&& !self.raw_offsets.contains_key(name)
|
||||
&& !self.unmodeled_pointers.contains(name)
|
||||
&& !self.tir_byte_view_pointers.contains(name)
|
||||
&& !self.byte_view_pointers.contains(name)
|
||||
&& !self.pointer_in_pointer_merge(name)
|
||||
{
|
||||
if let Some(carrier) = self.tir_use_pointees.get(name) {
|
||||
@@ -392,6 +560,9 @@ impl Emitter {
|
||||
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()
|
||||
})
|
||||
}
|
||||
|
||||
@@ -457,7 +628,9 @@ impl Emitter {
|
||||
let result_type = self.type_id(&index_ty)?;
|
||||
let mut ops = Vec::new();
|
||||
let mut seen_incoming: HashMap<Word, Word> = HashMap::new();
|
||||
let mut pending_edges = Vec::new();
|
||||
for (value, label) in incoming {
|
||||
let mut edge_instructions = Vec::new();
|
||||
let value_id = match value {
|
||||
LlValue::Local(incoming_name) => {
|
||||
if let Some(raw) = self.raw_offsets.get(incoming_name).cloned() {
|
||||
@@ -476,9 +649,9 @@ impl Emitter {
|
||||
if self.values.contains_key(&incoming_index_name) {
|
||||
self.value_id(&LlValue::Local(incoming_index_name), &LlType::Int(32))?
|
||||
} else if word_indexed && raw.dyn_terms.is_empty() {
|
||||
self.emit_raw_word_index(&raw, 0, instructions)?
|
||||
self.emit_raw_word_index(&raw, 0, &mut edge_instructions)?
|
||||
} else if !word_indexed {
|
||||
self.emit_raw_byte_index(&raw, 0, instructions)?
|
||||
self.emit_raw_byte_index(&raw, 0, &mut edge_instructions)?
|
||||
} else {
|
||||
return Ok(false);
|
||||
}
|
||||
@@ -492,13 +665,14 @@ impl Emitter {
|
||||
raw_byte_index_name(incoming_name)
|
||||
}),
|
||||
&index_ty,
|
||||
instructions,
|
||||
&mut edge_instructions,
|
||||
)?
|
||||
}
|
||||
}
|
||||
_ => return Ok(false),
|
||||
};
|
||||
let label_id = self.label_id(label)?;
|
||||
pending_edges.push((label_id, edge_instructions));
|
||||
if let Some(existing) = seen_incoming.insert(label_id, value_id) {
|
||||
if existing != value_id {
|
||||
return Err(format!(
|
||||
@@ -510,6 +684,9 @@ impl Emitter {
|
||||
ops.push(Operand::IdRef(value_id));
|
||||
ops.push(Operand::IdRef(label_id));
|
||||
}
|
||||
for (predecessor, edge_instructions) in pending_edges {
|
||||
self.record_phi_edge_instructions(predecessor, edge_instructions);
|
||||
}
|
||||
instructions.push(Self::inst(Op::Phi, Some(result_type), Some(result), ops));
|
||||
self.pointer_storage
|
||||
.insert(name.to_string(), llvm_pointer_storage(*addrspace)?);
|
||||
@@ -548,9 +725,7 @@ impl Emitter {
|
||||
};
|
||||
let has_unmodeled = incoming.iter().any(|(value, _)| match value {
|
||||
LlValue::Local(name) => {
|
||||
self.unmodeled_pointers.contains(name)
|
||||
|| (self.pointer_phi_values.contains(name) && !self.values.contains_key(name))
|
||||
|| self.forward_gep_base_is_unmodeled(name)
|
||||
self.unmodeled_pointers.contains(name) || self.forward_gep_base_is_unmodeled(name)
|
||||
}
|
||||
_ => false,
|
||||
});
|
||||
@@ -609,55 +784,239 @@ impl Emitter {
|
||||
let Some(template) = self.pointer_phi_template_provenance(name, incoming)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
if template.indices.len() != 1 {
|
||||
return Ok(None);
|
||||
}
|
||||
let index_ty = template.indices[0].ty.clone();
|
||||
let index_name = pointer_index_name(name);
|
||||
let result = self.result_id(&index_name, &index_ty)?;
|
||||
let result_type = self.type_id(&index_ty)?;
|
||||
let mut ops = Vec::new();
|
||||
let mut seen_incoming: HashMap<Word, Word> = HashMap::new();
|
||||
for (value, label) in incoming {
|
||||
let first_index_is_pointer_arithmetic = template.indices.len() == 1
|
||||
&& incoming.iter().any(|(value, _)| {
|
||||
let LlValue::Local(incoming_name) = value else {
|
||||
return false;
|
||||
};
|
||||
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 forward_index_ty = (template.indices.len() == 1).then(|| &template.indices[0].ty);
|
||||
let mut provenances = vec![None; incoming.len()];
|
||||
// Resolve already-defined arms before creating any forward reservation. Such an arm cannot
|
||||
// acquire new provenance later in block order, so a failure here rejects this representation
|
||||
// without leaving a speculative index id for another pointer merge to consume.
|
||||
for (position, (value, _)) in incoming.iter().enumerate() {
|
||||
let LlValue::Local(value_name) = value else {
|
||||
continue;
|
||||
};
|
||||
if !self.values.contains_key(value_name) {
|
||||
continue;
|
||||
}
|
||||
let Some(provenance) =
|
||||
self.provenance_for_pointer_value(value, Some(&template), Some(&index_ty))?
|
||||
self.provenance_for_pointer_value(value, Some(&template), forward_index_ty)?
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
if !compatible_pointer_provenance(&template, &provenance)
|
||||
|| provenance.indices.len() != 1
|
||||
|| provenance
|
||||
.indices
|
||||
.iter()
|
||||
.zip(&template.indices)
|
||||
.any(|(index, template_index)| index.ty != template_index.ty)
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
let index = &provenance.indices[0];
|
||||
let value_id = self.phi_value_id(&index.value, &index.ty, instructions)?;
|
||||
let label_id = self.label_id(label)?;
|
||||
if let Some(existing) = seen_incoming.insert(label_id, value_id) {
|
||||
if existing != value_id {
|
||||
return Err(format!(
|
||||
"native emitter: pointer index phi has multiple values from predecessor {label}"
|
||||
));
|
||||
provenances[position] = Some(provenance);
|
||||
}
|
||||
let prior_provenance = self.gep_provenance.get(name).cloned();
|
||||
let index_names = if template.indices.len() == 1 {
|
||||
vec![pointer_index_name(name)]
|
||||
} else {
|
||||
(0..template.indices.len())
|
||||
.map(|position| format!("{}.{position}", pointer_index_name(name)))
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
let prior_index_values = index_names
|
||||
.iter()
|
||||
.map(|index_name| (index_name.clone(), self.values.get(index_name).cloned()))
|
||||
.collect::<Vec<_>>();
|
||||
// Reserve the phi's index carrier before resolving a forward GEP/select backedge. Those
|
||||
// definitions are emitted later, but their structural provenance is expressed relative to
|
||||
// this index result; without the reservation they appear ungrounded and the emitter falls
|
||||
// through to an illegal Function/Private pointer OpPhi.
|
||||
if self
|
||||
.reserve_pointer_provenance_from_template(
|
||||
name,
|
||||
&template,
|
||||
first_index_is_pointer_arithmetic,
|
||||
)?
|
||||
.is_none()
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
let mut resolved_provenances = Vec::with_capacity(incoming.len());
|
||||
for ((value, label), preflight) in incoming.iter().zip(provenances) {
|
||||
let provenance = if let Some(provenance) = preflight {
|
||||
provenance
|
||||
} else if let Some(provenance) =
|
||||
self.provenance_for_pointer_value(value, Some(&template), forward_index_ty)?
|
||||
{
|
||||
provenance
|
||||
} else {
|
||||
self.restore_pointer_phi_reservation(name, prior_provenance, &prior_index_values);
|
||||
return Ok(None);
|
||||
};
|
||||
if !compatible_pointer_provenance(&template, &provenance)
|
||||
|| provenance
|
||||
.indices
|
||||
.iter()
|
||||
.zip(&template.indices)
|
||||
.any(|(index, template_index)| index.ty != template_index.ty)
|
||||
{
|
||||
self.restore_pointer_phi_reservation(name, prior_provenance, &prior_index_values);
|
||||
return Ok(None);
|
||||
}
|
||||
resolved_provenances.push((provenance, label));
|
||||
}
|
||||
let mut merged_indices = Vec::with_capacity(template.indices.len());
|
||||
let mut selected_ty = template.source_ty.clone();
|
||||
for (position, template_index) in template.indices.iter().enumerate() {
|
||||
let Some(structural_literal) = structural_pointer_index(
|
||||
position,
|
||||
&mut selected_ty,
|
||||
template_index,
|
||||
first_index_is_pointer_arithmetic,
|
||||
) else {
|
||||
self.restore_pointer_phi_reservation(name, prior_provenance, &prior_index_values);
|
||||
return Ok(None);
|
||||
};
|
||||
if structural_literal {
|
||||
if resolved_provenances.iter().any(|(provenance, _)| {
|
||||
provenance.indices[position].value != template_index.value
|
||||
}) {
|
||||
self.restore_pointer_phi_reservation(
|
||||
name,
|
||||
prior_provenance,
|
||||
&prior_index_values,
|
||||
);
|
||||
return Ok(None);
|
||||
}
|
||||
merged_indices.push(template_index.clone());
|
||||
continue;
|
||||
}
|
||||
ops.push(Operand::IdRef(value_id));
|
||||
ops.push(Operand::IdRef(label_id));
|
||||
let index_name = if template.indices.len() == 1 {
|
||||
pointer_index_name(name)
|
||||
} else {
|
||||
format!("{}.{position}", pointer_index_name(name))
|
||||
};
|
||||
if resolved_provenances
|
||||
.iter()
|
||||
.all(|(provenance, _)| provenance.indices[position].value == template_index.value)
|
||||
&& !self.values.contains_key(&index_name)
|
||||
{
|
||||
merged_indices.push(template_index.clone());
|
||||
continue;
|
||||
}
|
||||
let result = self.result_id(&index_name, &template_index.ty)?;
|
||||
let result_type = self.type_id(&template_index.ty)?;
|
||||
let mut ops = Vec::new();
|
||||
let mut seen_incoming: HashMap<Word, Word> = HashMap::new();
|
||||
let mut pending_edges = Vec::new();
|
||||
for (provenance, label) in &resolved_provenances {
|
||||
let index = &provenance.indices[position];
|
||||
let mut edge_instructions = Vec::new();
|
||||
let value_id =
|
||||
self.phi_value_id(&index.value, &index.ty, &mut edge_instructions)?;
|
||||
let label_id = self.label_id(label)?;
|
||||
pending_edges.push((label_id, edge_instructions));
|
||||
if let Some(existing) = seen_incoming.insert(label_id, value_id) {
|
||||
if existing != value_id {
|
||||
return Err(format!(
|
||||
"native emitter: pointer index phi has multiple values from predecessor {label}"
|
||||
));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
ops.push(Operand::IdRef(value_id));
|
||||
ops.push(Operand::IdRef(label_id));
|
||||
}
|
||||
for (predecessor, edge_instructions) in pending_edges {
|
||||
self.record_phi_edge_instructions(predecessor, edge_instructions);
|
||||
}
|
||||
instructions.push(Self::inst(Op::Phi, Some(result_type), Some(result), ops));
|
||||
merged_indices.push(TypedValue {
|
||||
ty: template_index.ty.clone(),
|
||||
value: LlValue::Local(index_name),
|
||||
});
|
||||
}
|
||||
instructions.push(Self::inst(Op::Phi, Some(result_type), Some(result), ops));
|
||||
Ok(Some(GepProvenance {
|
||||
root: template.root,
|
||||
addrspace: template.addrspace,
|
||||
source_ty: template.source_ty,
|
||||
indices: vec![TypedValue {
|
||||
ty: index_ty,
|
||||
value: LlValue::Local(index_name),
|
||||
}],
|
||||
indices: merged_indices,
|
||||
root_indices: None,
|
||||
root_is_indexed_container: template.root_is_indexed_container,
|
||||
}))
|
||||
}
|
||||
|
||||
fn restore_pointer_phi_reservation(
|
||||
&mut self,
|
||||
name: &str,
|
||||
prior_provenance: Option<GepProvenance>,
|
||||
prior_index_values: &[(String, Option<(Word, LlType)>)],
|
||||
) {
|
||||
if let Some(provenance) = prior_provenance {
|
||||
self.gep_provenance.insert(name.to_string(), provenance);
|
||||
} else {
|
||||
self.gep_provenance.remove(name);
|
||||
}
|
||||
for (index_name, prior_value) in prior_index_values {
|
||||
if let Some(value) = prior_value {
|
||||
self.values.insert(index_name.clone(), value.clone());
|
||||
} else {
|
||||
self.values.remove(index_name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn bda_address_name(name: &str) -> String {
|
||||
format!("{name}.metal2vulkan.bda_address")
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn incompatible_defined_phi_arm_does_not_leave_reserved_index() {
|
||||
let ir = LlModule::parse("define void @k() {\nentry:\n ret void\n}\n")
|
||||
.expect("minimal module parses");
|
||||
let mut emitter = Emitter::new(ir);
|
||||
let pointer_ty = LlType::Ptr(1);
|
||||
emitter
|
||||
.values
|
||||
.insert("%modeled".into(), (10, pointer_ty.clone()));
|
||||
emitter.values.insert("%unmodeled".into(), (11, pointer_ty));
|
||||
emitter.gep_provenance.insert(
|
||||
"%modeled".into(),
|
||||
GepProvenance {
|
||||
root: 12,
|
||||
addrspace: 1,
|
||||
source_ty: LlType::Int(16),
|
||||
indices: vec![TypedValue {
|
||||
ty: LlType::Int(64),
|
||||
value: LlValue::Int(0),
|
||||
}],
|
||||
root_indices: None,
|
||||
root_is_indexed_container: false,
|
||||
},
|
||||
);
|
||||
|
||||
let result = emitter
|
||||
.emit_pointer_phi_provenance(
|
||||
"%merged",
|
||||
&[
|
||||
(LlValue::Local("%modeled".into()), "left".into()),
|
||||
(LlValue::Local("%unmodeled".into()), "right".into()),
|
||||
],
|
||||
&mut Vec::new(),
|
||||
)
|
||||
.expect("unsupported provenance declines cleanly");
|
||||
|
||||
assert!(result.is_none());
|
||||
assert!(!emitter.values.contains_key(&pointer_index_name("%merged")));
|
||||
assert!(!emitter.gep_provenance.contains_key("%merged"));
|
||||
}
|
||||
}
|
||||
@@ -129,7 +129,84 @@ impl Emitter {
|
||||
}
|
||||
return Ok(Some(template));
|
||||
}
|
||||
self.pointer_phi_forward_template_provenance(name, incoming)
|
||||
if let Some(template) = self.pointer_phi_forward_template_provenance(name, incoming)? {
|
||||
return Ok(Some(template));
|
||||
}
|
||||
let mut visited = HashSet::new();
|
||||
let values = incoming
|
||||
.iter()
|
||||
.map(|(value, _)| value.clone())
|
||||
.collect::<Vec<_>>();
|
||||
if let Some(template) = self.pointer_network_forward_template(&values, &mut visited)? {
|
||||
return Ok(Some(template));
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// Find a concrete forward GEP behind a cycle of construct-tree pointer state phis/selects.
|
||||
/// Such a network may be encountered before its one concrete arm is emitted; the GEP's typed
|
||||
/// carrier still supplies an exact root, source type, and index vector for index-domain lowering.
|
||||
fn pointer_network_forward_template(
|
||||
&mut self,
|
||||
values: &[LlValue],
|
||||
visited: &mut HashSet<String>,
|
||||
) -> Result<Option<GepProvenance>, String> {
|
||||
for value in values {
|
||||
let LlValue::Local(name) = value else {
|
||||
continue;
|
||||
};
|
||||
// This is a reachability search for any concrete GEP template. Once one value's complete
|
||||
// forward subgraph has been searched without finding a template, revisiting it through a
|
||||
// reconvergent phi arm cannot produce a different answer. Retaining the mark bounds the
|
||||
// search by the number of pointer values instead of the number of paths through the graph.
|
||||
if !visited.insert(name.clone()) {
|
||||
continue;
|
||||
}
|
||||
let found = if let Some(provenance) = self.gep_provenance.get(name).cloned() {
|
||||
Some(provenance)
|
||||
} else if let Some(gep) = self.forward_geps.get(name).cloned() {
|
||||
self.forward_gep_template_provenance(&gep)?
|
||||
} else if let Some(incoming) = self.tir_phi_incomings.get(name).cloned() {
|
||||
let values = incoming
|
||||
.into_iter()
|
||||
.map(|(value, _)| value)
|
||||
.collect::<Vec<_>>();
|
||||
self.pointer_network_forward_template(&values, visited)?
|
||||
} else if let Some((true_value, false_value)) =
|
||||
self.forward_pointer_selects.get(name).cloned()
|
||||
{
|
||||
self.pointer_network_forward_template(
|
||||
&[true_value.value, false_value.value],
|
||||
visited,
|
||||
)?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if found.is_some() {
|
||||
return Ok(found);
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn forward_gep_template_provenance(
|
||||
&mut self,
|
||||
gep: &LlGep,
|
||||
) -> Result<Option<GepProvenance>, String> {
|
||||
let LlType::Ptr(addrspace) = self.resolve_type(&gep.base.ty)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let Some(root) = self.forward_phi_root_id(&gep.base.value, &gep.base.ty)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
Ok(Some(GepProvenance {
|
||||
root,
|
||||
addrspace,
|
||||
source_ty: self.resolve_type(&gep.source_ty)?,
|
||||
indices: gep.indices.clone(),
|
||||
root_indices: None,
|
||||
root_is_indexed_container: self.is_indexed_container_root(root, None),
|
||||
}))
|
||||
}
|
||||
|
||||
pub(in crate::native::emitter) fn pointer_phi_forward_template_provenance(
|
||||
@@ -137,14 +214,21 @@ impl Emitter {
|
||||
name: &str,
|
||||
incoming: &[(LlValue, String)],
|
||||
) -> Result<Option<GepProvenance>, String> {
|
||||
let Some(gep) = incoming.iter().find_map(|(value, _)| {
|
||||
let direct_gep = incoming.iter().find_map(|(value, _)| {
|
||||
let LlValue::Local(incoming_name) = value else {
|
||||
return None;
|
||||
};
|
||||
let gep = self.forward_geps.get(incoming_name)?;
|
||||
matches!(&gep.base.value, LlValue::Local(base_name) if base_name == name)
|
||||
.then(|| gep.clone())
|
||||
}) else {
|
||||
});
|
||||
let select_gep = incoming.iter().find_map(|(value, _)| {
|
||||
let LlValue::Local(incoming_name) = value else {
|
||||
return None;
|
||||
};
|
||||
self.forward_select_recurrence_gep(incoming_name, name)
|
||||
});
|
||||
let Some(gep) = direct_gep.or(select_gep) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let LlValue::Local(base_name) = &gep.base.value else {
|
||||
@@ -163,7 +247,9 @@ impl Emitter {
|
||||
LlValue::Local(incoming_name) => {
|
||||
self.forward_geps.get(incoming_name).is_some_and(|gep| {
|
||||
matches!(&gep.base.value, LlValue::Local(base_name) if base_name == name)
|
||||
})
|
||||
}) || self
|
||||
.forward_select_recurrence_gep(incoming_name, name)
|
||||
.is_some()
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
@@ -189,6 +275,51 @@ impl Emitter {
|
||||
}))
|
||||
}
|
||||
|
||||
/// Return the first GEP in a forward-defined chain whose base is the loop phi. The chain is
|
||||
/// source-structural: every link must be a typed GEP and cycles or unrelated pointer producers
|
||||
/// decline. Only the root link defines the index domain used to construct the phi; ordinary GEP
|
||||
/// emission composes each later link into that reserved index in source order.
|
||||
fn forward_gep_chain_rooted_at(&self, value: &str, root: &str) -> Option<LlGep> {
|
||||
let mut current = value;
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
loop {
|
||||
if !seen.insert(current) {
|
||||
return None;
|
||||
}
|
||||
let gep = self.forward_geps.get(current)?;
|
||||
let LlValue::Local(base) = &gep.base.value else {
|
||||
return None;
|
||||
};
|
||||
if base == root {
|
||||
return Some(gep.clone());
|
||||
}
|
||||
current = base;
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::native::emitter) fn forward_select_recurrence_gep(
|
||||
&self,
|
||||
select: &str,
|
||||
phi: &str,
|
||||
) -> Option<LlGep> {
|
||||
let (true_value, false_value) = self.forward_pointer_selects.get(select)?;
|
||||
let (self_arm, advanced_arm) = if matches!(&true_value.value, LlValue::Local(name) if name == phi)
|
||||
{
|
||||
(true_value, false_value)
|
||||
} else if matches!(&false_value.value, LlValue::Local(name) if name == phi) {
|
||||
(false_value, true_value)
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
if !matches!(&self_arm.ty, LlType::Ptr(_)) {
|
||||
return None;
|
||||
}
|
||||
let LlValue::Local(advanced_name) = &advanced_arm.value else {
|
||||
return None;
|
||||
};
|
||||
self.forward_gep_chain_rooted_at(advanced_name, phi)
|
||||
}
|
||||
|
||||
fn forward_phi_root_id(
|
||||
&mut self,
|
||||
value: &LlValue,
|
||||
@@ -233,6 +364,20 @@ impl Emitter {
|
||||
}
|
||||
}
|
||||
let (Some(template), Some(index_ty)) = (template, index_ty) else {
|
||||
if let Some(template) = template {
|
||||
if self.tir_phi_incomings.contains_key(name) {
|
||||
return self
|
||||
.reserve_pointer_provenance_from_template(name, template, false);
|
||||
}
|
||||
if let Some(gep) = self.forward_geps.get(name).cloned() {
|
||||
let provenance = self.forward_gep_template_provenance(&gep)?;
|
||||
if provenance.as_ref().is_some_and(|provenance| {
|
||||
compatible_pointer_provenance(template, provenance)
|
||||
}) {
|
||||
return Ok(provenance);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(provenance) = self.gep_provenance.get(name).cloned() {
|
||||
return Ok(Some(provenance));
|
||||
}
|
||||
@@ -264,6 +409,11 @@ impl Emitter {
|
||||
{
|
||||
return Ok(Some(provenance));
|
||||
}
|
||||
if let Some(provenance) =
|
||||
self.forward_select_pointer_provenance(name, template, index_ty)?
|
||||
{
|
||||
return Ok(Some(provenance));
|
||||
}
|
||||
// The reserved-index promise below is fulfilled only by a LATER defining GEP of
|
||||
// `name` (the `materialize_reserved_pointer_index` call sites). A name that already
|
||||
// has a value id is already defined — a param or an emitted pointer — so no future
|
||||
@@ -288,10 +438,83 @@ impl Emitter {
|
||||
self.gep_provenance.insert(name.clone(), provenance.clone());
|
||||
Ok(Some(provenance))
|
||||
}
|
||||
LlValue::Undef => {
|
||||
let Some(mut provenance) = template.cloned() else {
|
||||
return Ok(None);
|
||||
};
|
||||
// An undefined pointer arm shares the concrete arm's structural path, but it does
|
||||
// not carry that arm's dynamic indices. Copying those SSA values into the undefined
|
||||
// arm can move a branch-local index across the merge without a phi, violating
|
||||
// dominance. Preserve only literal struct/array selectors and make every dynamic
|
||||
// index explicitly undefined so merge construction emits the required index phis.
|
||||
let mut selected_ty = provenance.source_ty.clone();
|
||||
for (position, index) in provenance.indices.iter_mut().enumerate() {
|
||||
let structural =
|
||||
structural_pointer_index(position, &mut selected_ty, index, false)
|
||||
.ok_or_else(|| {
|
||||
"native emitter: undefined pointer provenance has an invalid structural path"
|
||||
.to_string()
|
||||
})?;
|
||||
if !structural {
|
||||
index.value = LlValue::Undef;
|
||||
}
|
||||
}
|
||||
Ok(Some(provenance))
|
||||
}
|
||||
_ => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::native::emitter) fn reserve_pointer_provenance_from_template(
|
||||
&mut self,
|
||||
name: &str,
|
||||
template: &GepProvenance,
|
||||
first_index_is_pointer_arithmetic: bool,
|
||||
) -> Result<Option<GepProvenance>, String> {
|
||||
let mut indices = Vec::with_capacity(template.indices.len());
|
||||
let mut selected_ty = template.source_ty.clone();
|
||||
for (position, template_index) in template.indices.iter().enumerate() {
|
||||
// LLVM's leading zero indexes the pointee object itself and is omitted when constructing
|
||||
// the SPIR-V access chain. A later index into a struct is also part of SPIR-V's TYPE path
|
||||
// and must remain a literal member number. Turning either into a phi result would create
|
||||
// a dynamic struct index, which cannot describe an OpAccessChain. Array/vector indices
|
||||
// remain state values and may vary across incoming edges.
|
||||
let Some(structural_literal) = structural_pointer_index(
|
||||
position,
|
||||
&mut selected_ty,
|
||||
template_index,
|
||||
first_index_is_pointer_arithmetic,
|
||||
) else {
|
||||
return Ok(None);
|
||||
};
|
||||
if structural_literal {
|
||||
indices.push(template_index.clone());
|
||||
continue;
|
||||
}
|
||||
let index_name = if template.indices.len() == 1 {
|
||||
pointer_index_name(name)
|
||||
} else {
|
||||
format!("{}.{position}", pointer_index_name(name))
|
||||
};
|
||||
self.result_id(&index_name, &template_index.ty)?;
|
||||
indices.push(TypedValue {
|
||||
ty: template_index.ty.clone(),
|
||||
value: LlValue::Local(index_name),
|
||||
});
|
||||
}
|
||||
let provenance = GepProvenance {
|
||||
root: template.root,
|
||||
addrspace: template.addrspace,
|
||||
source_ty: template.source_ty.clone(),
|
||||
indices,
|
||||
root_indices: None,
|
||||
root_is_indexed_container: template.root_is_indexed_container,
|
||||
};
|
||||
self.gep_provenance
|
||||
.insert(name.to_string(), provenance.clone());
|
||||
Ok(Some(provenance))
|
||||
}
|
||||
|
||||
pub(in crate::native::emitter) fn forward_gep_pointer_provenance(
|
||||
&mut self,
|
||||
name: &str,
|
||||
@@ -333,6 +556,58 @@ impl Emitter {
|
||||
Ok(Some(provenance))
|
||||
}
|
||||
|
||||
fn forward_select_pointer_provenance(
|
||||
&mut self,
|
||||
name: &str,
|
||||
template: &GepProvenance,
|
||||
index_ty: &LlType,
|
||||
) -> Result<Option<GepProvenance>, String> {
|
||||
let Some((true_value, false_value)) = self.forward_pointer_selects.get(name).cloned()
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
let phi_name = [&true_value, &false_value].into_iter().find_map(|value| {
|
||||
let LlValue::Local(phi_name) = &value.value else {
|
||||
return None;
|
||||
};
|
||||
(self.tir_phi_incomings.contains_key(phi_name)
|
||||
&& self.forward_select_recurrence_gep(name, phi_name).is_some())
|
||||
.then_some(phi_name.clone())
|
||||
});
|
||||
let Some(phi_name) = phi_name else {
|
||||
return Ok(None);
|
||||
};
|
||||
let Some(gep) = self.forward_select_recurrence_gep(name, &phi_name) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let LlType::Ptr(addrspace) = self.resolve_type(&gep.base.ty)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let source_ty = self.resolve_type(&gep.source_ty)?;
|
||||
if addrspace != template.addrspace
|
||||
|| source_ty != template.source_ty
|
||||
|| gep.indices.len() != 1
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
let index_name = pointer_index_name(name);
|
||||
self.result_id(&index_name, index_ty)?;
|
||||
let provenance = GepProvenance {
|
||||
root: template.root,
|
||||
addrspace: template.addrspace,
|
||||
source_ty: template.source_ty.clone(),
|
||||
indices: vec![TypedValue {
|
||||
ty: index_ty.clone(),
|
||||
value: LlValue::Local(index_name),
|
||||
}],
|
||||
root_indices: None,
|
||||
root_is_indexed_container: template.root_is_indexed_container,
|
||||
};
|
||||
self.gep_provenance
|
||||
.insert(name.to_string(), provenance.clone());
|
||||
Ok(Some(provenance))
|
||||
}
|
||||
|
||||
pub(in crate::native::emitter) fn materialize_reserved_pointer_index(
|
||||
&mut self,
|
||||
name: &str,
|
||||
@@ -371,26 +646,7 @@ impl Emitter {
|
||||
let Some(template) = self.pointer_phi_template_provenance(name, &incoming)? else {
|
||||
return Ok(());
|
||||
};
|
||||
if template.indices.len() != 1 {
|
||||
return Ok(());
|
||||
}
|
||||
let index_ty = template.indices[0].ty.clone();
|
||||
let index_name = pointer_index_name(name);
|
||||
self.result_id(&index_name, &index_ty)?;
|
||||
self.gep_provenance.insert(
|
||||
name.to_string(),
|
||||
GepProvenance {
|
||||
root: template.root,
|
||||
addrspace: template.addrspace,
|
||||
source_ty: template.source_ty,
|
||||
indices: vec![TypedValue {
|
||||
ty: index_ty,
|
||||
value: LlValue::Local(index_name),
|
||||
}],
|
||||
root_indices: None,
|
||||
root_is_indexed_container: template.root_is_indexed_container,
|
||||
},
|
||||
);
|
||||
self.reserve_pointer_provenance_from_template(name, &template, false)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -547,27 +803,62 @@ impl Emitter {
|
||||
root: Word,
|
||||
storage: Option<StorageClass>,
|
||||
) -> bool {
|
||||
self.global_values.iter().any(|(name, (id, ty))| {
|
||||
let matches_storage = match (storage, ty) {
|
||||
(Some(storage), LlType::Ptr(addrspace)) => {
|
||||
llvm_pointer_storage(*addrspace) == Ok(storage)
|
||||
let emitted_global_is_indexed_container = self
|
||||
.module
|
||||
.types_global_values
|
||||
.iter()
|
||||
.find(|inst| inst.class.opcode == Op::Variable && inst.result_id == Some(root))
|
||||
.and_then(|variable| variable.result_type)
|
||||
.and_then(|pointer_type| {
|
||||
self.module.types_global_values.iter().find(|inst| {
|
||||
inst.class.opcode == Op::TypePointer && inst.result_id == Some(pointer_type)
|
||||
})
|
||||
})
|
||||
.and_then(|pointer_type| {
|
||||
let matches_storage = storage.is_none_or(|storage| {
|
||||
pointer_type.operands.first() == Some(&Operand::StorageClass(storage))
|
||||
});
|
||||
match matches_storage.then(|| pointer_type.operands.get(1))?? {
|
||||
Operand::IdRef(pointee) => Some(*pointee),
|
||||
_ => None,
|
||||
}
|
||||
(Some(_), _) => false,
|
||||
(None, _) => true,
|
||||
};
|
||||
*id == root
|
||||
&& matches_storage
|
||||
&& self.pointer_pointees.get(name).is_some_and(|pointee| {
|
||||
matches!(pointee, LlType::Array(_, _) | LlType::Struct(_))
|
||||
})
|
||||
}) || self.values.iter().any(|(name, (id, _))| {
|
||||
*id == root
|
||||
&& storage
|
||||
.map(|storage| self.pointer_storage.get(name) == Some(&storage))
|
||||
.unwrap_or(true)
|
||||
&& self.pointer_pointees.get(name).is_some_and(|pointee| {
|
||||
matches!(pointee, LlType::Array(_, _) | LlType::Struct(_))
|
||||
})
|
||||
})
|
||||
})
|
||||
.and_then(|pointee| {
|
||||
self.module
|
||||
.types_global_values
|
||||
.iter()
|
||||
.find(|inst| inst.result_id == Some(pointee))
|
||||
})
|
||||
.is_some_and(|pointee| {
|
||||
matches!(
|
||||
pointee.class.opcode,
|
||||
Op::TypeArray | Op::TypeRuntimeArray | Op::TypeStruct
|
||||
)
|
||||
});
|
||||
|
||||
emitted_global_is_indexed_container
|
||||
|| self.global_values.iter().any(|(name, (id, ty))| {
|
||||
let matches_storage = match (storage, ty) {
|
||||
(Some(storage), LlType::Ptr(addrspace)) => {
|
||||
llvm_pointer_storage(*addrspace) == Ok(storage)
|
||||
}
|
||||
(Some(_), _) => false,
|
||||
(None, _) => true,
|
||||
};
|
||||
*id == root
|
||||
&& matches_storage
|
||||
&& self.pointer_pointees.get(name).is_some_and(|pointee| {
|
||||
matches!(pointee, LlType::Array(_, _) | LlType::Struct(_))
|
||||
})
|
||||
})
|
||||
|| self.values.iter().any(|(name, (id, _))| {
|
||||
*id == root
|
||||
&& storage
|
||||
.map(|storage| self.pointer_storage.get(name) == Some(&storage))
|
||||
.unwrap_or(true)
|
||||
&& self.pointer_pointees.get(name).is_some_and(|pointee| {
|
||||
matches!(pointee, LlType::Array(_, _) | LlType::Struct(_))
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,9 @@
|
||||
use super::*;
|
||||
|
||||
impl Emitter {
|
||||
/// Replay a direct pointer selection in the value domain. Either arm may be an exact raw or
|
||||
/// PhysicalStorageBuffer address: `emit_selected_direct_load_arm_value` lowers that arm through
|
||||
/// its address model while an ordinary logical arm remains rooted in its own storage class.
|
||||
pub(in crate::native::emitter) fn emit_selected_pointer_direct_load(
|
||||
&mut self,
|
||||
result: Word,
|
||||
@@ -74,6 +77,24 @@ impl Emitter {
|
||||
instructions: &mut Vec<Instruction>,
|
||||
) -> Result<Word, String> {
|
||||
if let LlValue::Local(name) = value {
|
||||
// A null-rooted GEP/phi network denotes no memory object. Loading it is undefined in the
|
||||
// source program, but an OpUndef POINTER is not a legal SPIR-V memory operand. When this
|
||||
// network is one arm of value-domain pointer selection, materialize the arm's undefined
|
||||
// VALUE directly; the selected concrete arm still performs its exact load.
|
||||
if self.null_rooted_pointer_values.contains(name) {
|
||||
return self.undef_id(load_ty);
|
||||
}
|
||||
if let Some(selected) = self.selected_pointers.get(name).cloned() {
|
||||
let loaded = self.fresh();
|
||||
self.emit_selected_pointer_direct_load(
|
||||
loaded,
|
||||
load_ty,
|
||||
&selected,
|
||||
access_align,
|
||||
instructions,
|
||||
)?;
|
||||
return Ok(loaded);
|
||||
}
|
||||
if let Some(raw) = self.raw_offsets.get(name).cloned() {
|
||||
let loaded = self.fresh();
|
||||
self.emit_raw_load(loaded, load_ty, &raw, access_align, instructions)?;
|
||||
@@ -258,6 +279,271 @@ impl Emitter {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(in crate::native::emitter) fn emit_selected_access_tree_load(
|
||||
&mut self,
|
||||
result: Word,
|
||||
result_ty: &LlType,
|
||||
tree: &SelectedAccessTree,
|
||||
access_align: Option<u64>,
|
||||
instructions: &mut Vec<Instruction>,
|
||||
) -> Result<(), String> {
|
||||
let result_ty = self.resolve_type(result_ty)?;
|
||||
let value = self.emit_selected_access_tree_load_value(
|
||||
tree,
|
||||
&result_ty,
|
||||
access_align,
|
||||
instructions,
|
||||
)?;
|
||||
if value != result {
|
||||
instructions.push(Self::inst(
|
||||
Op::CopyObject,
|
||||
Some(self.type_id(&result_ty)?),
|
||||
Some(result),
|
||||
vec![Operand::IdRef(value)],
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn emit_selected_access_tree_load_value(
|
||||
&mut self,
|
||||
tree: &SelectedAccessTree,
|
||||
result_ty: &LlType,
|
||||
access_align: Option<u64>,
|
||||
instructions: &mut Vec<Instruction>,
|
||||
) -> Result<Word, String> {
|
||||
if !types_compatible(&self.resolve_type(&tree.pointee)?, result_ty) {
|
||||
return Err(format!(
|
||||
"native emitter: selected access tree load type mismatch {:?} vs {result_ty:?}",
|
||||
tree.pointee
|
||||
));
|
||||
}
|
||||
let true_value = self.emit_selected_access_arm_load_value(
|
||||
&tree.true_arm,
|
||||
result_ty,
|
||||
access_align,
|
||||
instructions,
|
||||
)?;
|
||||
let false_value = self.emit_selected_access_arm_load_value(
|
||||
&tree.false_arm,
|
||||
result_ty,
|
||||
access_align,
|
||||
instructions,
|
||||
)?;
|
||||
let value = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
Op::Select,
|
||||
Some(self.type_id(result_ty)?),
|
||||
Some(value),
|
||||
vec![
|
||||
Operand::IdRef(tree.cond),
|
||||
Operand::IdRef(true_value),
|
||||
Operand::IdRef(false_value),
|
||||
],
|
||||
));
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn emit_selected_access_arm_load_value(
|
||||
&mut self,
|
||||
arm: &SelectedAccessArm,
|
||||
result_ty: &LlType,
|
||||
access_align: Option<u64>,
|
||||
instructions: &mut Vec<Instruction>,
|
||||
) -> Result<Word, String> {
|
||||
match arm {
|
||||
SelectedAccessArm::Typed { ptr, .. } => {
|
||||
let value = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
Op::Load,
|
||||
Some(self.type_id(result_ty)?),
|
||||
Some(value),
|
||||
vec![Operand::IdRef(*ptr)],
|
||||
));
|
||||
Ok(value)
|
||||
}
|
||||
SelectedAccessArm::Raw(raw) => {
|
||||
let value = self.fresh();
|
||||
self.emit_raw_load(value, result_ty, raw, access_align, instructions)?;
|
||||
Ok(value)
|
||||
}
|
||||
SelectedAccessArm::Nested(nested) => self.emit_selected_access_tree_load_value(
|
||||
nested,
|
||||
result_ty,
|
||||
access_align,
|
||||
instructions,
|
||||
),
|
||||
SelectedAccessArm::Null => self.const_null(result_ty),
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::native::emitter) fn emit_selected_access_tree_store(
|
||||
&mut self,
|
||||
object_ty: &LlType,
|
||||
object: Word,
|
||||
tree: &SelectedAccessTree,
|
||||
access_align: Option<u64>,
|
||||
instructions: &mut Vec<Instruction>,
|
||||
) -> Result<(), String> {
|
||||
let object_ty = self.resolve_type(object_ty)?;
|
||||
if !types_compatible(&self.resolve_type(&tree.pointee)?, &object_ty) {
|
||||
return Err(format!(
|
||||
"native emitter: selected access tree store type mismatch {:?} vs {object_ty:?}",
|
||||
tree.pointee
|
||||
));
|
||||
}
|
||||
self.emit_selected_access_tree_store_with_parent(
|
||||
&object_ty,
|
||||
object,
|
||||
tree,
|
||||
None,
|
||||
access_align,
|
||||
instructions,
|
||||
)
|
||||
}
|
||||
|
||||
fn emit_selected_access_tree_store_with_parent(
|
||||
&mut self,
|
||||
object_ty: &LlType,
|
||||
object: Word,
|
||||
tree: &SelectedAccessTree,
|
||||
parent_condition: Option<Word>,
|
||||
access_align: Option<u64>,
|
||||
instructions: &mut Vec<Instruction>,
|
||||
) -> Result<(), String> {
|
||||
let true_condition =
|
||||
self.selected_access_branch_condition(parent_condition, tree.cond, true, instructions)?;
|
||||
let false_condition = self.selected_access_branch_condition(
|
||||
parent_condition,
|
||||
tree.cond,
|
||||
false,
|
||||
instructions,
|
||||
)?;
|
||||
self.emit_selected_access_arm_store(
|
||||
object_ty,
|
||||
object,
|
||||
&tree.true_arm,
|
||||
true_condition,
|
||||
access_align,
|
||||
instructions,
|
||||
)?;
|
||||
self.emit_selected_access_arm_store(
|
||||
object_ty,
|
||||
object,
|
||||
&tree.false_arm,
|
||||
false_condition,
|
||||
access_align,
|
||||
instructions,
|
||||
)
|
||||
}
|
||||
|
||||
fn selected_access_branch_condition(
|
||||
&mut self,
|
||||
parent: Option<Word>,
|
||||
condition: Word,
|
||||
true_branch: bool,
|
||||
instructions: &mut Vec<Instruction>,
|
||||
) -> Result<Word, String> {
|
||||
let bool_ty = self.type_id(&LlType::Bool)?;
|
||||
let branch = if true_branch {
|
||||
condition
|
||||
} else {
|
||||
let negated = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
Op::LogicalNot,
|
||||
Some(bool_ty),
|
||||
Some(negated),
|
||||
vec![Operand::IdRef(condition)],
|
||||
));
|
||||
negated
|
||||
};
|
||||
let Some(parent) = parent else {
|
||||
return Ok(branch);
|
||||
};
|
||||
let combined = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
Op::LogicalAnd,
|
||||
Some(bool_ty),
|
||||
Some(combined),
|
||||
vec![Operand::IdRef(parent), Operand::IdRef(branch)],
|
||||
));
|
||||
Ok(combined)
|
||||
}
|
||||
|
||||
fn emit_selected_access_arm_store(
|
||||
&mut self,
|
||||
object_ty: &LlType,
|
||||
object: Word,
|
||||
arm: &SelectedAccessArm,
|
||||
condition: Word,
|
||||
access_align: Option<u64>,
|
||||
instructions: &mut Vec<Instruction>,
|
||||
) -> Result<(), String> {
|
||||
match arm {
|
||||
SelectedAccessArm::Nested(nested) => self.emit_selected_access_tree_store_with_parent(
|
||||
object_ty,
|
||||
object,
|
||||
nested,
|
||||
Some(condition),
|
||||
access_align,
|
||||
instructions,
|
||||
),
|
||||
SelectedAccessArm::Typed { ptr, storage } => {
|
||||
if !matches!(
|
||||
storage,
|
||||
StorageClass::StorageBuffer | StorageClass::UniformConstant
|
||||
) {
|
||||
return Err(format!(
|
||||
"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(())
|
||||
}
|
||||
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)
|
||||
}
|
||||
SelectedAccessArm::Null => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::native::emitter) fn materialize_selected_pointer_value(
|
||||
&mut self,
|
||||
name: &str,
|
||||
@@ -305,40 +591,6 @@ impl Emitter {
|
||||
instructions: &mut Vec<Instruction>,
|
||||
) -> Result<(), String> {
|
||||
let result_ty = self.resolve_type(result_ty)?;
|
||||
if selected.load_typed {
|
||||
// The arms are already-typed pointers; load each with the load's value type and select.
|
||||
let (Some(true_ptr), Some(false_ptr)) = (selected.true_ptr, selected.false_ptr) else {
|
||||
return Err(
|
||||
"native emitter: load-typed selected pointer missing an arm".to_string()
|
||||
);
|
||||
};
|
||||
let result_type = self.type_id(&result_ty)?;
|
||||
let true_value = self.fresh();
|
||||
let false_value = self.fresh();
|
||||
instructions.push(Self::inst(
|
||||
Op::Load,
|
||||
Some(result_type),
|
||||
Some(true_value),
|
||||
vec![Operand::IdRef(true_ptr)],
|
||||
));
|
||||
instructions.push(Self::inst(
|
||||
Op::Load,
|
||||
Some(result_type),
|
||||
Some(false_value),
|
||||
vec![Operand::IdRef(false_ptr)],
|
||||
));
|
||||
instructions.push(Self::inst(
|
||||
Op::Select,
|
||||
Some(result_type),
|
||||
Some(result),
|
||||
vec![
|
||||
Operand::IdRef(selected.cond),
|
||||
Operand::IdRef(true_value),
|
||||
Operand::IdRef(false_value),
|
||||
],
|
||||
));
|
||||
return Ok(());
|
||||
}
|
||||
let pointee = self.resolve_type(&selected.pointee)?;
|
||||
let reinterpret_raw = pointee == LlType::Int(8) && pointee != result_ty;
|
||||
if reinterpret_raw {
|
||||
|
||||
@@ -23,12 +23,29 @@ impl Emitter {
|
||||
));
|
||||
}
|
||||
let cond_id = self.value_id_in(&cond.value, &cond.ty, instructions)?;
|
||||
// Try the raw pointer-select path BEFORE the logical merge-meta, so a buffer marked raw by the
|
||||
// pointer-merge-failure retry (emit_function_with_raw_retry) is not pre-empted by
|
||||
// pointer_merge_meta's pointee-mismatch error on the aggregate-vs-element arms. For a non-raw
|
||||
// buffer emit_raw_pointer_select_index returns false (no raw offsets), so banked selects fall
|
||||
// through to the unchanged logical path below.
|
||||
// Try the raw pointer-select path BEFORE the logical merge-meta. Typed AIR analysis marks an
|
||||
// incompatible multi-root merge raw before emission, so pointer_merge_meta must not pre-empt
|
||||
// that representation with its pointee-mismatch error. For a non-raw buffer
|
||||
// emit_raw_pointer_select_index returns false (no raw offsets), so compatible selects fall
|
||||
// through to the logical path below.
|
||||
if let LlType::Ptr(_) = result_ty {
|
||||
let arm_is_deferred = |value: &LlValue| {
|
||||
matches!(value, LlValue::Local(local)
|
||||
if self.selected_pointers.contains_key(local)
|
||||
|| self.selected_access_trees.contains_key(local))
|
||||
};
|
||||
if arm_is_deferred(&true_value.value) || arm_is_deferred(&false_value.value) {
|
||||
self.selected_pointers.insert(
|
||||
name.clone(),
|
||||
SelectedPointer {
|
||||
cond: cond_id,
|
||||
true_value: true_value.value.clone(),
|
||||
false_value: false_value.value.clone(),
|
||||
ty: result_ty.clone(),
|
||||
},
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
if self.emit_raw_pointer_select_index(
|
||||
&name,
|
||||
&result_ty,
|
||||
@@ -48,9 +65,19 @@ impl Emitter {
|
||||
)? {
|
||||
return Ok(());
|
||||
}
|
||||
if self.record_incompatible_pointee_load_select(
|
||||
&name,
|
||||
&result_ty,
|
||||
&true_value.value,
|
||||
&false_value.value,
|
||||
cond_id,
|
||||
)? {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
let pointer_meta =
|
||||
self.pointer_merge_meta(&[&true_value.value, &false_value.value], &result_ty)?;
|
||||
let mut pointer_provenance = None;
|
||||
if let LlType::Ptr(addrspace) = result_ty {
|
||||
if let Some(meta) = pointer_meta.as_ref() {
|
||||
let arm_storage_mismatch = |emitter: &Self,
|
||||
@@ -91,14 +118,13 @@ impl Emitter {
|
||||
)? {
|
||||
return Ok(());
|
||||
}
|
||||
if self.record_deferred_load_typed_pointer_select(
|
||||
if self.record_deferred_buffer_pointer_select(
|
||||
&name,
|
||||
&result_ty,
|
||||
&true_value.value,
|
||||
&false_value.value,
|
||||
addrspace,
|
||||
cond_id,
|
||||
pointer_meta.as_ref(),
|
||||
instructions,
|
||||
)? {
|
||||
return Ok(());
|
||||
}
|
||||
@@ -111,14 +137,15 @@ impl Emitter {
|
||||
)
|
||||
});
|
||||
if !can_select_pointer {
|
||||
if let Some(provenance) = self.emit_pointer_select_provenance(
|
||||
pointer_provenance = self.emit_pointer_select_provenance(
|
||||
&name,
|
||||
&result_ty,
|
||||
&true_value.value,
|
||||
&false_value.value,
|
||||
cond_id,
|
||||
instructions,
|
||||
)? {
|
||||
)?;
|
||||
if let Some(provenance) = pointer_provenance.clone() {
|
||||
self.gep_provenance.insert(name.clone(), provenance);
|
||||
if let Some(meta) = pointer_meta {
|
||||
self.record_pointer_meta(name.clone(), meta);
|
||||
@@ -144,6 +171,45 @@ impl Emitter {
|
||||
)? {
|
||||
return Ok(());
|
||||
}
|
||||
pointer_provenance = self.emit_pointer_select_provenance(
|
||||
&name,
|
||||
&result_ty,
|
||||
&true_value.value,
|
||||
&false_value.value,
|
||||
cond_id,
|
||||
instructions,
|
||||
)?;
|
||||
if let (
|
||||
Some(
|
||||
meta @ PointerMeta {
|
||||
storage,
|
||||
pointee: Some(pointee),
|
||||
},
|
||||
),
|
||||
Some(provenance),
|
||||
) = (pointer_meta.as_ref(), pointer_provenance.as_ref())
|
||||
{
|
||||
// A select between pointers with one complete root/index provenance is an integer
|
||||
// select followed by one rematerialized pointer, regardless of storage class. The
|
||||
// provenance helper emitted the index select above; constructing the pointer here
|
||||
// keeps pointer SSA out of both ordinary diamonds and select-fed loop recurrences.
|
||||
let result_type = self.ptr_type_id(*storage, pointee)?;
|
||||
let result = self.result_id(&name, &result_ty)?;
|
||||
let op = pointer_arithmetic_access_chain_op_for_storage(
|
||||
*storage,
|
||||
provenance.root_is_indexed_container,
|
||||
pointee,
|
||||
&provenance.indices,
|
||||
);
|
||||
let mut operands = vec![Operand::IdRef(provenance.root)];
|
||||
for index in gep_spirv_indices(&provenance.indices)? {
|
||||
operands.push(Operand::IdRef(self.value_id(&index.value, &index.ty)?));
|
||||
}
|
||||
instructions.push(Self::inst(op, Some(result_type), Some(result), operands));
|
||||
self.record_pointer_meta(name.clone(), meta.clone());
|
||||
self.gep_provenance.insert(name, provenance.clone());
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
let result_type = self.pointer_aware_type_id(&result_ty, pointer_meta.as_ref())?;
|
||||
let result = self.result_id(&name, &result_ty)?;
|
||||
@@ -157,14 +223,6 @@ impl Emitter {
|
||||
} else {
|
||||
self.value_id_in(&false_value.value, &false_value.ty, instructions)?
|
||||
};
|
||||
let pointer_provenance = self.emit_pointer_select_provenance(
|
||||
&name,
|
||||
&result_ty,
|
||||
&true_value.value,
|
||||
&false_value.value,
|
||||
cond_id,
|
||||
instructions,
|
||||
)?;
|
||||
instructions.push(Self::inst(
|
||||
Op::Select,
|
||||
Some(result_type),
|
||||
@@ -234,6 +292,7 @@ impl Emitter {
|
||||
StorageClass::Private
|
||||
| StorageClass::UniformConstant
|
||||
| StorageClass::StorageBuffer
|
||||
| StorageClass::PhysicalStorageBuffer
|
||||
| StorageClass::Workgroup
|
||||
)
|
||||
};
|
||||
@@ -269,6 +328,67 @@ impl Emitter {
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Defer a direct-load-only pointer select whose opaque-pointer arms acquired incompatible
|
||||
/// provisional pointees. LLVM permits that merge because the pointer type carries only an address
|
||||
/// space; SPIR-V does not. Loading each concrete arm with the use-implied type and selecting those
|
||||
/// values preserves the source operation without constructing an invalid pointer cast or select.
|
||||
fn record_incompatible_pointee_load_select(
|
||||
&mut self,
|
||||
name: &str,
|
||||
result_ty: &LlType,
|
||||
true_value: &LlValue,
|
||||
false_value: &LlValue,
|
||||
cond_id: Word,
|
||||
) -> Result<bool, String> {
|
||||
let LlType::Ptr(addrspace) = result_ty else {
|
||||
return Ok(false);
|
||||
};
|
||||
if !self.tir_direct_load_pointers.contains(name)
|
||||
|| matches!(true_value, LlValue::Zero | LlValue::Undef)
|
||||
|| matches!(false_value, LlValue::Zero | LlValue::Undef)
|
||||
|| self.pointer_phi_incoming_values.contains(name)
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
let Some(true_pointee) = self.pointer_pointee_for_value(true_value)? else {
|
||||
return Ok(false);
|
||||
};
|
||||
let Some(false_pointee) = self.pointer_pointee_for_value(false_value)? else {
|
||||
return Ok(false);
|
||||
};
|
||||
if types_compatible(
|
||||
&self.resolve_type(&true_pointee)?,
|
||||
&self.resolve_type(&false_pointee)?,
|
||||
) {
|
||||
return Ok(false);
|
||||
}
|
||||
let value_readable = |storage| {
|
||||
matches!(
|
||||
storage,
|
||||
StorageClass::Private
|
||||
| StorageClass::UniformConstant
|
||||
| StorageClass::StorageBuffer
|
||||
| StorageClass::PhysicalStorageBuffer
|
||||
| StorageClass::Workgroup
|
||||
)
|
||||
};
|
||||
if !value_readable(self.pointer_storage_for(true_value, *addrspace)?)
|
||||
|| !value_readable(self.pointer_storage_for(false_value, *addrspace)?)
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
self.selected_pointers.insert(
|
||||
name.to_string(),
|
||||
SelectedPointer {
|
||||
cond: cond_id,
|
||||
true_value: true_value.clone(),
|
||||
false_value: false_value.clone(),
|
||||
ty: result_ty.clone(),
|
||||
},
|
||||
);
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub(in crate::native::emitter) fn pointer_select_arm_id(
|
||||
&mut self,
|
||||
value: &LlValue,
|
||||
@@ -422,9 +542,11 @@ impl Emitter {
|
||||
}
|
||||
|
||||
/// A `null`/`undef` pointer constant typed to the storage class + pointee a pointer merge resolved,
|
||||
/// not the generic default `value_id_in` would emit. A merge's `null`/`undef` arm must carry the
|
||||
/// merge result's SPIR-V pointer type, or the `OpSelect`/`OpPhi` operand types mismatch the result
|
||||
/// type (the cross-storage `_ptr_UniformConstant_uchar` vs `_ptr_StorageBuffer_*` validation reject).
|
||||
/// not the generic default `value_id_in` would emit. SPIR-V Logical pointer merges admit a null
|
||||
/// pointer arm but not an `OpUndef` pointer arm, so source `undef` is refined to the same typed
|
||||
/// null representation. A merge's nullish arm must carry the merge result's SPIR-V pointer type,
|
||||
/// or the `OpSelect`/`OpPhi` operand types mismatch the result type (the cross-storage
|
||||
/// `_ptr_UniformConstant_uchar` vs `_ptr_StorageBuffer_*` validation reject).
|
||||
/// Returns `None` for any other value, so the caller emits it the normal way.
|
||||
pub(in crate::native::emitter) fn typed_null_or_undef_pointer_id(
|
||||
&mut self,
|
||||
@@ -433,8 +555,7 @@ impl Emitter {
|
||||
pointee: &LlType,
|
||||
) -> Result<Option<Word>, String> {
|
||||
let op = match value {
|
||||
LlValue::Zero => Op::ConstantNull,
|
||||
LlValue::Undef => Op::Undef,
|
||||
LlValue::Zero | LlValue::Undef => Op::ConstantNull,
|
||||
_ => return Ok(None),
|
||||
};
|
||||
let ptr_type = self.ptr_type_id(storage, pointee)?;
|
||||
@@ -537,21 +658,18 @@ impl Emitter {
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// A `select` between two pointers whose common pointee could not be modeled — typically a
|
||||
/// select between pointers into *distinct* buffers (e.g. a tensor `select` op routed through a
|
||||
/// `get_buffer_ptr` helper). A direct pointer `OpSelect` would be illegal in Logical SPIR-V
|
||||
/// ("variable pointers must point into the same structure") and crashes the driver. Instead
|
||||
/// materialize both arm pointers now and defer: the consuming load/store loads each arm with its
|
||||
/// own value type and selects the loaded values. Returns true when it took over the select.
|
||||
pub(in crate::native::emitter) fn record_deferred_load_typed_pointer_select(
|
||||
/// Preserve a `select` between distinct buffer pointers as source structure. A direct pointer
|
||||
/// `OpSelect` would be illegal in Logical SPIR-V, while materializing its arms before a memory
|
||||
/// consumer establishes their pointee can freeze a provisional byte type. GEP/load/store
|
||||
/// lowering instead walks these operands and constructs each concrete leaf at its required type.
|
||||
pub(in crate::native::emitter) fn record_deferred_buffer_pointer_select(
|
||||
&mut self,
|
||||
name: &str,
|
||||
result_ty: &LlType,
|
||||
true_value: &LlValue,
|
||||
false_value: &LlValue,
|
||||
addrspace: u32,
|
||||
cond_id: Word,
|
||||
pointer_meta: Option<&PointerMeta>,
|
||||
instructions: &mut Vec<Instruction>,
|
||||
) -> Result<bool, String> {
|
||||
// Engage only for a buffer-storage pointer select whose common pointee is unknown: that is
|
||||
// the shape that would otherwise emit an illegal cross-buffer `OpSelect`. A known pointee
|
||||
@@ -586,25 +704,15 @@ impl Emitter {
|
||||
// Deferred load-typed pointers are not modeled across phi edges; let other paths run.
|
||||
return Ok(false);
|
||||
}
|
||||
let ptr_ty = LlType::Ptr(addrspace);
|
||||
let true_ptr = self.value_id_in(true_value, &ptr_ty, instructions)?;
|
||||
let false_ptr = self.value_id_in(false_value, &ptr_ty, instructions)?;
|
||||
let storage = llvm_pointer_storage(addrspace)?;
|
||||
self.selected_load_pointers.insert(
|
||||
self.selected_pointers.insert(
|
||||
name.to_string(),
|
||||
SelectedLoadPointer {
|
||||
SelectedPointer {
|
||||
cond: cond_id,
|
||||
true_ptr: Some(true_ptr),
|
||||
false_ptr: Some(false_ptr),
|
||||
true_storage: storage,
|
||||
false_storage: storage,
|
||||
pointee: LlType::Void,
|
||||
true_raw: None,
|
||||
false_raw: None,
|
||||
load_typed: true,
|
||||
true_value: true_value.clone(),
|
||||
false_value: false_value.clone(),
|
||||
ty: result_ty.clone(),
|
||||
},
|
||||
);
|
||||
self.pointer_storage.insert(name.to_string(), storage);
|
||||
let is_null = self.const_bool(false)?;
|
||||
self.record_pointer_nullness(name.to_string(), is_null);
|
||||
Ok(true)
|
||||
|
||||
@@ -14,6 +14,22 @@ impl Emitter {
|
||||
let LlType::Ptr(addrspace) = self.resolve_type(&selected.ty)? else {
|
||||
return Ok(false);
|
||||
};
|
||||
let pointee = gep_pointee(source_ty, indices)?;
|
||||
if self.selected_value_has_access_tree(&selected.true_value)
|
||||
|| self.selected_value_has_access_tree(&selected.false_value)
|
||||
{
|
||||
let tree = self.build_selected_access_tree(
|
||||
selected,
|
||||
source_ty,
|
||||
indices,
|
||||
&mut HashSet::new(),
|
||||
instructions,
|
||||
)?;
|
||||
self.selected_access_trees.insert(name.to_string(), tree);
|
||||
self.pointer_pointees
|
||||
.insert(name.to_string(), pointee.clone());
|
||||
return Ok(true);
|
||||
}
|
||||
let true_is_null = matches!(selected.true_value, LlValue::Zero);
|
||||
let false_is_null = matches!(selected.false_value, LlValue::Zero);
|
||||
let true_storage = (!true_is_null)
|
||||
@@ -25,7 +41,6 @@ impl Emitter {
|
||||
let Some(storage) = true_storage.or(false_storage) else {
|
||||
return Ok(false);
|
||||
};
|
||||
let pointee = gep_pointee(source_ty, indices)?;
|
||||
if let (Some(true_storage), Some(false_storage)) = (true_storage, false_storage) {
|
||||
if true_storage != false_storage {
|
||||
let raw_arm = |emitter: &Self, value: &LlValue| match value {
|
||||
@@ -79,7 +94,6 @@ impl Emitter {
|
||||
pointee: pointee.clone(),
|
||||
true_raw,
|
||||
false_raw,
|
||||
load_typed: false,
|
||||
},
|
||||
);
|
||||
self.pointer_pointees.insert(name.to_string(), pointee);
|
||||
@@ -173,7 +187,6 @@ impl Emitter {
|
||||
pointee: pointee.clone(),
|
||||
true_raw,
|
||||
false_raw,
|
||||
load_typed: false,
|
||||
},
|
||||
);
|
||||
self.pointer_storage.insert(name.to_string(), storage);
|
||||
@@ -185,6 +198,195 @@ impl Emitter {
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn selected_value_has_access_tree(&self, value: &LlValue) -> bool {
|
||||
matches!(value, LlValue::Local(name) if self.selected_pointers.contains_key(name) || self.selected_access_trees.contains_key(name))
|
||||
}
|
||||
|
||||
pub(in crate::native::emitter) fn build_selected_access_tree(
|
||||
&mut self,
|
||||
selected: &SelectedPointer,
|
||||
source_ty: &LlType,
|
||||
indices: &[TypedValue],
|
||||
visiting: &mut HashSet<String>,
|
||||
instructions: &mut Vec<Instruction>,
|
||||
) -> Result<SelectedAccessTree, String> {
|
||||
let LlType::Ptr(addrspace) = self.resolve_type(&selected.ty)? else {
|
||||
return Err("native emitter: selected access tree source is not a pointer".to_string());
|
||||
};
|
||||
let pointee = gep_pointee(source_ty, indices)?;
|
||||
let shape = SelectedGepShape {
|
||||
source_ty,
|
||||
pointee: &pointee,
|
||||
indices,
|
||||
};
|
||||
let true_arm = self.build_selected_access_arm(
|
||||
&selected.true_value,
|
||||
&selected.ty,
|
||||
addrspace,
|
||||
&shape,
|
||||
visiting,
|
||||
instructions,
|
||||
)?;
|
||||
let false_arm = self.build_selected_access_arm(
|
||||
&selected.false_value,
|
||||
&selected.ty,
|
||||
addrspace,
|
||||
&shape,
|
||||
visiting,
|
||||
instructions,
|
||||
)?;
|
||||
Ok(SelectedAccessTree {
|
||||
cond: selected.cond,
|
||||
true_arm,
|
||||
false_arm,
|
||||
pointee,
|
||||
})
|
||||
}
|
||||
|
||||
fn build_selected_access_arm(
|
||||
&mut self,
|
||||
value: &LlValue,
|
||||
pointer_ty: &LlType,
|
||||
addrspace: u32,
|
||||
shape: &SelectedGepShape<'_>,
|
||||
visiting: &mut HashSet<String>,
|
||||
instructions: &mut Vec<Instruction>,
|
||||
) -> Result<SelectedAccessArm, String> {
|
||||
if matches!(value, LlValue::Zero) {
|
||||
return Ok(SelectedAccessArm::Null);
|
||||
}
|
||||
if let LlValue::Local(name) = value {
|
||||
if let Some(nested) = self.selected_pointers.get(name).cloned() {
|
||||
if !visiting.insert(name.clone()) {
|
||||
return Err("native emitter: cyclic selected access tree".to_string());
|
||||
}
|
||||
let tree = self.build_selected_access_tree(
|
||||
&nested,
|
||||
shape.source_ty,
|
||||
shape.indices,
|
||||
visiting,
|
||||
instructions,
|
||||
)?;
|
||||
visiting.remove(name);
|
||||
return Ok(SelectedAccessArm::Nested(Box::new(tree)));
|
||||
}
|
||||
if let Some(tree) = self.selected_access_trees.get(name).cloned() {
|
||||
let tree = self.apply_selected_access_tree_gep(
|
||||
&tree,
|
||||
shape.source_ty,
|
||||
shape.indices,
|
||||
instructions,
|
||||
)?;
|
||||
return Ok(SelectedAccessArm::Nested(Box::new(tree)));
|
||||
}
|
||||
if let Some(raw) = self.raw_offsets.get(name).cloned() {
|
||||
return Ok(SelectedAccessArm::Raw(self.apply_raw_gep(
|
||||
raw,
|
||||
shape.source_ty,
|
||||
shape.indices,
|
||||
)?));
|
||||
}
|
||||
}
|
||||
let storage = self.pointer_storage_for(value, addrspace)?;
|
||||
let ptr_type = self.ptr_type_id(storage, shape.pointee)?;
|
||||
let ptr = self.emit_selected_pointer_access_chain(
|
||||
ptr_type,
|
||||
value,
|
||||
pointer_ty,
|
||||
shape.source_ty,
|
||||
shape.pointee,
|
||||
storage,
|
||||
shape.indices,
|
||||
instructions,
|
||||
)?;
|
||||
Ok(SelectedAccessArm::Typed { ptr, storage })
|
||||
}
|
||||
|
||||
pub(in crate::native::emitter) fn emit_selected_access_tree_gep(
|
||||
&mut self,
|
||||
name: &str,
|
||||
tree: &SelectedAccessTree,
|
||||
source_ty: &LlType,
|
||||
indices: &[TypedValue],
|
||||
instructions: &mut Vec<Instruction>,
|
||||
) -> Result<bool, String> {
|
||||
if !types_compatible(&self.resolve_type(&tree.pointee)?, source_ty) {
|
||||
return Ok(false);
|
||||
}
|
||||
let tree = self.apply_selected_access_tree_gep(tree, source_ty, indices, instructions)?;
|
||||
self.pointer_pointees
|
||||
.insert(name.to_string(), tree.pointee.clone());
|
||||
self.selected_access_trees.insert(name.to_string(), tree);
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn apply_selected_access_tree_gep(
|
||||
&mut self,
|
||||
tree: &SelectedAccessTree,
|
||||
source_ty: &LlType,
|
||||
indices: &[TypedValue],
|
||||
instructions: &mut Vec<Instruction>,
|
||||
) -> Result<SelectedAccessTree, String> {
|
||||
let pointee = gep_pointee(source_ty, indices)?;
|
||||
let true_arm = self.apply_selected_access_arm_gep(
|
||||
&tree.true_arm,
|
||||
source_ty,
|
||||
&pointee,
|
||||
indices,
|
||||
instructions,
|
||||
)?;
|
||||
let false_arm = self.apply_selected_access_arm_gep(
|
||||
&tree.false_arm,
|
||||
source_ty,
|
||||
&pointee,
|
||||
indices,
|
||||
instructions,
|
||||
)?;
|
||||
Ok(SelectedAccessTree {
|
||||
cond: tree.cond,
|
||||
true_arm,
|
||||
false_arm,
|
||||
pointee,
|
||||
})
|
||||
}
|
||||
|
||||
fn apply_selected_access_arm_gep(
|
||||
&mut self,
|
||||
arm: &SelectedAccessArm,
|
||||
source_ty: &LlType,
|
||||
pointee: &LlType,
|
||||
indices: &[TypedValue],
|
||||
instructions: &mut Vec<Instruction>,
|
||||
) -> Result<SelectedAccessArm, String> {
|
||||
match arm {
|
||||
SelectedAccessArm::Typed { ptr, storage } => {
|
||||
let ptr_type = self.ptr_type_id(*storage, pointee)?;
|
||||
let ptr = self.emit_selected_pointer_access_chain_from_id(
|
||||
ptr_type,
|
||||
*ptr,
|
||||
*storage,
|
||||
source_ty,
|
||||
pointee,
|
||||
indices,
|
||||
instructions,
|
||||
)?;
|
||||
Ok(SelectedAccessArm::Typed {
|
||||
ptr,
|
||||
storage: *storage,
|
||||
})
|
||||
}
|
||||
SelectedAccessArm::Raw(raw) => Ok(SelectedAccessArm::Raw(self.apply_raw_gep(
|
||||
raw.clone(),
|
||||
source_ty,
|
||||
indices,
|
||||
)?)),
|
||||
SelectedAccessArm::Nested(nested) => Ok(SelectedAccessArm::Nested(Box::new(
|
||||
self.apply_selected_access_tree_gep(nested, source_ty, indices, instructions)?,
|
||||
))),
|
||||
SelectedAccessArm::Null => Ok(SelectedAccessArm::Null),
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::native::emitter) fn emit_selected_load_pointer_gep(
|
||||
&mut self,
|
||||
name: &str,
|
||||
@@ -259,7 +461,6 @@ impl Emitter {
|
||||
pointee: pointee.clone(),
|
||||
true_raw,
|
||||
false_raw,
|
||||
load_typed: false,
|
||||
},
|
||||
);
|
||||
if selected.true_storage == selected.false_storage {
|
||||
@@ -490,9 +691,13 @@ impl Emitter {
|
||||
return Ok(result);
|
||||
}
|
||||
}
|
||||
let spirv_indices = gep_spirv_indices(indices)?;
|
||||
if spirv_indices.is_empty() {
|
||||
return Ok(base);
|
||||
}
|
||||
let op = pointer_arithmetic_access_chain_op_for_storage(storage, false, pointee, indices);
|
||||
let mut ops = vec![Operand::IdRef(base)];
|
||||
for idx in gep_spirv_indices(indices)? {
|
||||
for idx in spirv_indices {
|
||||
ops.push(Operand::IdRef(self.value_id(&idx.value, &idx.ty)?));
|
||||
}
|
||||
let result = self.fresh();
|
||||
@@ -584,9 +789,13 @@ impl Emitter {
|
||||
// Structured path: use pointer-arithmetic opcode selection so a non-zero leading index on a
|
||||
// StorageBuffer aggregate arm becomes OpPtrAccessChain (element stride), matching the
|
||||
// scalar-arm flatten's relative offset semantics.
|
||||
let spirv_indices = gep_spirv_indices(indices)?;
|
||||
if spirv_indices.is_empty() {
|
||||
return Ok(base);
|
||||
}
|
||||
let op = pointer_arithmetic_access_chain_op_for_storage(storage, false, pointee, indices);
|
||||
let mut ops = vec![Operand::IdRef(base)];
|
||||
for idx in gep_spirv_indices(indices)? {
|
||||
for idx in spirv_indices {
|
||||
ops.push(Operand::IdRef(self.value_id(&idx.value, &idx.ty)?));
|
||||
}
|
||||
let result = self.fresh();
|
||||
|
||||
+166
-36
@@ -15,19 +15,34 @@ impl Emitter {
|
||||
/// preserved by `resolve_type` for value-level masking/const encoding; this only normalizes the
|
||||
/// type-id key/build basis.
|
||||
fn storage_type(ty: &LlType) -> LlType {
|
||||
Self::storage_type_at_depth(ty, false)
|
||||
}
|
||||
|
||||
fn storage_type_at_depth(ty: &LlType, nested: bool) -> LlType {
|
||||
match ty {
|
||||
// Logical SPIR-V cannot allocate a Function variable whose pointee recursively contains
|
||||
// a logical pointer. AIR nevertheless uses by-value aggregates as temporary pointer
|
||||
// carriers. The emitter retains those exact pointers in `aggregate_pointer_values`; the
|
||||
// serialized aggregate therefore owns only a fixed-width payload slot for each nested
|
||||
// pointer. A top-level pointer remains a real SPIR-V pointer.
|
||||
LlType::Ptr(_) if nested => LlType::Int(64),
|
||||
LlType::BFloat => LlType::Int(16),
|
||||
LlType::Int(bits) => match spirv_int_width(*bits) {
|
||||
Ok(legal) if legal != *bits => LlType::Int(legal),
|
||||
_ => ty.clone(),
|
||||
},
|
||||
LlType::Vector(elem, lanes) => {
|
||||
LlType::Vector(Box::new(Self::storage_type(elem)), *lanes)
|
||||
LlType::Vector(Box::new(Self::storage_type_at_depth(elem, true)), *lanes)
|
||||
}
|
||||
LlType::Array(elem, len) => LlType::Array(Box::new(Self::storage_type(elem)), *len),
|
||||
LlType::Struct(fields) => {
|
||||
LlType::Struct(fields.iter().map(Self::storage_type).collect())
|
||||
LlType::Array(elem, len) => {
|
||||
LlType::Array(Box::new(Self::storage_type_at_depth(elem, true)), *len)
|
||||
}
|
||||
LlType::Struct(fields) => LlType::Struct(
|
||||
fields
|
||||
.iter()
|
||||
.map(|field| Self::storage_type_at_depth(field, true))
|
||||
.collect(),
|
||||
),
|
||||
other => other.clone(),
|
||||
}
|
||||
}
|
||||
@@ -207,6 +222,9 @@ impl Emitter {
|
||||
return Ok(*id);
|
||||
}
|
||||
let pointee_id = self.type_id(&pointee)?;
|
||||
if storage == StorageClass::PhysicalStorageBuffer {
|
||||
self.ensure_physical_storage_layout(&pointee, pointee_id, true)?;
|
||||
}
|
||||
let id = self.fresh();
|
||||
self.module.types_global_values.push(Self::inst(
|
||||
Op::TypePointer,
|
||||
@@ -218,6 +236,91 @@ impl Emitter {
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
fn ensure_physical_storage_layout(
|
||||
&mut self,
|
||||
ty: &LlType,
|
||||
type_id: Word,
|
||||
root: bool,
|
||||
) -> Result<(), String> {
|
||||
let ty = Self::storage_type(&self.resolve_type(ty)?);
|
||||
let has_decoration = |annotations: &[Instruction], target, decoration| {
|
||||
annotations.iter().any(|instruction| {
|
||||
instruction.class.opcode == Op::Decorate
|
||||
&& instruction.operands.first() == Some(&Operand::IdRef(target))
|
||||
&& instruction.operands.get(1) == Some(&Operand::Decoration(decoration))
|
||||
})
|
||||
};
|
||||
match &ty {
|
||||
LlType::Struct(fields) => {
|
||||
if root
|
||||
&& !has_decoration(&self.module.annotations, type_id, spirv::Decoration::Block)
|
||||
{
|
||||
self.module.annotations.push(Self::inst(
|
||||
Op::Decorate,
|
||||
None,
|
||||
None,
|
||||
vec![
|
||||
Operand::IdRef(type_id),
|
||||
Operand::Decoration(spirv::Decoration::Block),
|
||||
],
|
||||
));
|
||||
}
|
||||
let mut offset = 0u64;
|
||||
for (member, field) in fields.iter().enumerate() {
|
||||
let (size, align) = self.raw_type_size_align(field)?;
|
||||
offset = offset.div_ceil(align) * align;
|
||||
let already_decorated = self.module.annotations.iter().any(|instruction| {
|
||||
instruction.class.opcode == Op::MemberDecorate
|
||||
&& instruction.operands.first() == Some(&Operand::IdRef(type_id))
|
||||
&& instruction.operands.get(1)
|
||||
== Some(&Operand::LiteralBit32(member as u32))
|
||||
&& instruction.operands.get(2)
|
||||
== Some(&Operand::Decoration(spirv::Decoration::Offset))
|
||||
});
|
||||
if !already_decorated {
|
||||
self.module.annotations.push(Self::inst(
|
||||
Op::MemberDecorate,
|
||||
None,
|
||||
None,
|
||||
vec![
|
||||
Operand::IdRef(type_id),
|
||||
Operand::LiteralBit32(member as u32),
|
||||
Operand::Decoration(spirv::Decoration::Offset),
|
||||
Operand::LiteralBit32(offset as u32),
|
||||
],
|
||||
));
|
||||
}
|
||||
let field_id = self.type_id(field)?;
|
||||
self.ensure_physical_storage_layout(field, field_id, false)?;
|
||||
offset += size;
|
||||
}
|
||||
}
|
||||
LlType::Array(element, _) | LlType::Vector(element, 5..) => {
|
||||
let (stride, _) = self.raw_type_size_align(element)?;
|
||||
if !has_decoration(
|
||||
&self.module.annotations,
|
||||
type_id,
|
||||
spirv::Decoration::ArrayStride,
|
||||
) {
|
||||
self.module.annotations.push(Self::inst(
|
||||
Op::Decorate,
|
||||
None,
|
||||
None,
|
||||
vec![
|
||||
Operand::IdRef(type_id),
|
||||
Operand::Decoration(spirv::Decoration::ArrayStride),
|
||||
Operand::LiteralBit32(stride as u32),
|
||||
],
|
||||
));
|
||||
}
|
||||
let element_id = self.type_id(element)?;
|
||||
self.ensure_physical_storage_layout(element, element_id, false)?;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn const_uint(&mut self, value: u32) -> Result<Word, String> {
|
||||
if let Some(id) = self.interner.uint_constants.get(&value) {
|
||||
return Ok(*id);
|
||||
@@ -322,15 +425,33 @@ impl Emitter {
|
||||
pub(super) fn value_id(&mut self, value: &LlValue, ty: &LlType) -> Result<Word, String> {
|
||||
match value {
|
||||
LlValue::Local(name) => {
|
||||
if self.pointer_phi_values.contains(name)
|
||||
&& matches!(self.resolve_type(ty)?, LlType::Ptr(_))
|
||||
{
|
||||
if let Some(address) = self.raw_offsets.get(name).and_then(|raw| {
|
||||
(raw.const_off == 0 && raw.dyn_terms.is_empty())
|
||||
.then_some(raw.device_addr_base)
|
||||
.flatten()
|
||||
}) {
|
||||
return Ok(address);
|
||||
}
|
||||
}
|
||||
let (id, have_ty) = if let Some((id, have_ty)) = self.values.get(name).cloned() {
|
||||
(id, have_ty)
|
||||
} else if self.construct_tree {
|
||||
// The construct-tree retry can route a loop latch before the header phi it
|
||||
// back-edges to. That is still a dominance-valid SSA use, and `OpPhi` already
|
||||
// allocates ids for future incoming values via `phi_value_id`; mirror that behavior
|
||||
// for non-phi uses, but only inside this reject-triggered retry tier. The finished
|
||||
// module remains adopted only after `spirv-val`, so an actually non-dominating use
|
||||
// still falls through.
|
||||
} else if self.construct_tree_active
|
||||
|| self.relooper_feed
|
||||
|| self
|
||||
.tir_result_types
|
||||
.get(name)
|
||||
.is_some_and(|ty| !matches!(ty, LlType::Ptr(_)))
|
||||
{
|
||||
// CFG construction can serialize a cloned predecessor after a block that uses
|
||||
// one of its scalar results; construct-tree and relooper plans can do the same
|
||||
// for source-order latches. Those are dominance-valid SSA uses even when their
|
||||
// definition block is serialized later. `OpPhi` already allocates ids for future
|
||||
// incoming values via `phi_value_id`; mirror that behavior for typed scalar uses.
|
||||
// Pointer values retain their dedicated provenance reservation below. An actually
|
||||
// non-dominating scalar use still fails the owned CFG check or final validation.
|
||||
let Some(have_ty) = self.tir_result_types.get(name).cloned() else {
|
||||
return Err(format!("native emitter: unknown SSA value {name}"));
|
||||
};
|
||||
@@ -354,31 +475,40 @@ impl Emitter {
|
||||
));
|
||||
}
|
||||
if let LlType::Ptr(addrspace) = have {
|
||||
self.reserve_pointer_phi_provenance(name)?;
|
||||
let merge_meta = self
|
||||
.tir_phi_incomings
|
||||
.get(name)
|
||||
.cloned()
|
||||
.map(|incoming| {
|
||||
self.pointer_merge_meta(
|
||||
&incoming.iter().map(|(value, _)| value).collect::<Vec<_>>(),
|
||||
&have_ty,
|
||||
)
|
||||
})
|
||||
.transpose()?
|
||||
.flatten();
|
||||
self.pointer_storage
|
||||
.entry(name.clone())
|
||||
.or_insert(match &merge_meta {
|
||||
Some(meta) => meta.storage,
|
||||
None => llvm_pointer_storage(addrspace)?,
|
||||
});
|
||||
if !self.pointer_pointees.contains_key(name) {
|
||||
if let Some(pointee) = merge_meta
|
||||
.and_then(|meta| meta.pointee)
|
||||
.or_else(|| self.tir_use_pointees.get(name).cloned())
|
||||
{
|
||||
self.pointer_pointees.insert(name.clone(), pointee);
|
||||
let phi_incoming = self.tir_phi_incomings.get(name).cloned();
|
||||
let reserved_bda = match phi_incoming.as_ref() {
|
||||
Some(incoming) => self
|
||||
.reserve_bda_address_phi(name, incoming, &have_ty)?
|
||||
.is_some(),
|
||||
None => false,
|
||||
};
|
||||
if !reserved_bda {
|
||||
self.reserve_pointer_phi_provenance(name)?;
|
||||
let merge_meta = phi_incoming
|
||||
.map(|incoming| {
|
||||
self.pointer_merge_meta(
|
||||
&incoming
|
||||
.iter()
|
||||
.map(|(value, _)| value)
|
||||
.collect::<Vec<_>>(),
|
||||
&have_ty,
|
||||
)
|
||||
})
|
||||
.transpose()?
|
||||
.flatten();
|
||||
self.pointer_storage
|
||||
.entry(name.clone())
|
||||
.or_insert(match &merge_meta {
|
||||
Some(meta) => meta.storage,
|
||||
None => llvm_pointer_storage(addrspace)?,
|
||||
});
|
||||
if !self.pointer_pointees.contains_key(name) {
|
||||
if let Some(pointee) = merge_meta
|
||||
.and_then(|meta| meta.pointee)
|
||||
.or_else(|| self.tir_use_pointees.get(name).cloned())
|
||||
{
|
||||
self.pointer_pointees.insert(name.clone(), pointee);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,306 +0,0 @@
|
||||
//! Retry-routing error classifiers: pure substring predicates over SPIRV-Tools / native-emitter
|
||||
//! message text that decide which failure-recovery retry a translate error routes to, plus the
|
||||
//! aggregate [`ValidationClass`]/[`EmitErrorClass`] enums `lib.rs`'s cascade matches on. Keeping the
|
||||
//! validator-text matching in this one adapter means a SPIRV-Tools message change touches one place.
|
||||
//! Unit coverage lives in `error_classifier_tests`.
|
||||
|
||||
use crate::spirv_module::{Module, Operand};
|
||||
use spirv::{Op, Word};
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// A systematic shared-merge failure this large is outside the bounded CFG recovery envelope. The
|
||||
/// threshold deliberately excludes isolated/local structurizer mistakes, which still receive the
|
||||
/// complete retry ladder.
|
||||
const SYSTEMATIC_REUSED_MERGE_TARGETS: usize = 8;
|
||||
|
||||
pub(crate) fn systematic_reused_merges_beyond_relooper(module: &Module) -> Option<(usize, usize)> {
|
||||
module.functions.iter().find_map(|function| {
|
||||
if function.blocks.len() <= super::CFG_EMIT_RELOOPER_MAX_BLOCKS {
|
||||
return None;
|
||||
}
|
||||
let mut claims = HashMap::<Word, usize>::new();
|
||||
for instruction in function.blocks.iter().flat_map(|block| &block.instructions) {
|
||||
if !matches!(instruction.class.opcode, Op::SelectionMerge | Op::LoopMerge) {
|
||||
continue;
|
||||
}
|
||||
if let Some(Operand::IdRef(merge)) = instruction.operands.first() {
|
||||
*claims.entry(*merge).or_default() += 1;
|
||||
}
|
||||
}
|
||||
let reused = claims.values().filter(|&&count| count > 1).count();
|
||||
(reused >= SYSTEMATIC_REUSED_MERGE_TARGETS).then_some((function.blocks.len(), reused))
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod systematic_merge_tests {
|
||||
use super::*;
|
||||
use crate::spirv_module::{Block, Function, Instruction};
|
||||
|
||||
fn module_with_reused_merges(blocks: usize, reused_targets: usize) -> Module {
|
||||
let mut function = Function::new();
|
||||
function.blocks.resize_with(blocks, Block::new);
|
||||
for target in 0..reused_targets {
|
||||
for claim in 0..2 {
|
||||
function.blocks[target * 2 + claim]
|
||||
.instructions
|
||||
.push(Instruction::new(
|
||||
Op::SelectionMerge,
|
||||
None,
|
||||
None,
|
||||
vec![Operand::IdRef(target as Word + 1)],
|
||||
));
|
||||
}
|
||||
}
|
||||
let mut module = Module::new();
|
||||
module.functions.push(function);
|
||||
module
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn systematic_merge_fast_fallback_requires_both_size_and_repetition() {
|
||||
assert!(
|
||||
systematic_reused_merges_beyond_relooper(&module_with_reused_merges(
|
||||
super::super::CFG_EMIT_RELOOPER_MAX_BLOCKS,
|
||||
SYSTEMATIC_REUSED_MERGE_TARGETS,
|
||||
))
|
||||
.is_none()
|
||||
);
|
||||
assert!(
|
||||
systematic_reused_merges_beyond_relooper(&module_with_reused_merges(
|
||||
super::super::CFG_EMIT_RELOOPER_MAX_BLOCKS + 1,
|
||||
SYSTEMATIC_REUSED_MERGE_TARGETS - 1,
|
||||
))
|
||||
.is_none()
|
||||
);
|
||||
assert_eq!(
|
||||
systematic_reused_merges_beyond_relooper(&module_with_reused_merges(
|
||||
super::super::CFG_EMIT_RELOOPER_MAX_BLOCKS + 1,
|
||||
SYSTEMATIC_REUSED_MERGE_TARGETS,
|
||||
)),
|
||||
Some((
|
||||
super::super::CFG_EMIT_RELOOPER_MAX_BLOCKS + 1,
|
||||
SYSTEMATIC_REUSED_MERGE_TARGETS,
|
||||
))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a spirv-val error message is one of the buffer pointer-typing failures the raw byte-offset
|
||||
/// path repairs (the pointer-merge frontier class). Anything else — a CFG/back-edge error, a missing
|
||||
/// capability, or a spirv-val spawn failure — returns false so the ground-truth retry is skipped.
|
||||
pub fn is_pointer_typing_validation_error(err: &str) -> bool {
|
||||
err.contains("does not match Pointer")
|
||||
|| err.contains("does not match Object")
|
||||
|| err.contains("does not match the type that results from indexing into the Composite")
|
||||
|| err.contains("reached non-composite")
|
||||
|| err.contains("OpInBoundsAccessChain cannot find index")
|
||||
// Anchored: the real spirv-val message is "... does not match the type used to index ..."
|
||||
// (an access-chain index-type mismatch). The bare "to index" substring also matched
|
||||
// unrelated wordings ("prior to indexing", "failed to index"); "used to index" pins the
|
||||
// access-chain family without the spurious catches. (M-C3 classifier hardening.)
|
||||
|| err.contains("used to index")
|
||||
}
|
||||
|
||||
/// Whether a native-emitter ERROR (the default typed emission returned `Err` *before* any spirv-val
|
||||
/// runs) is a buffer/pointer-typing gap the raw byte-offset model can express: a reinterpret-load
|
||||
/// width mismatch (a buffer's declared pointee width differs from the load's result width, so the
|
||||
/// typed access chain cannot be formed) or a missing pointer storage class. The ground-truth raw retry
|
||||
/// uses this to also recover from an outright emit failure — not only a spirv-val rejection of a
|
||||
/// produced module — by re-emitting with buffers modeled raw and adopting that only if it independently
|
||||
/// validates. Floor-safe: a banked case emits and validates on the default path, so it never reaches
|
||||
/// the retry; an emit failure was already a hard FALLBACK, so the raw attempt can only add a win.
|
||||
pub fn is_pointer_typing_emit_error(err: &str) -> bool {
|
||||
err.contains("bit width mismatch")
|
||||
|| err.contains("missing pointer storage")
|
||||
|| err.contains("cannot reinterpret load")
|
||||
// A typed Workgroup argument pointer that the default path can only reinterpret to the raw
|
||||
// word view via an illegal logical-pointer `OpBitcast`. The all-buffers-raw-with-workgroup
|
||||
// retry models the callee buffer raw and passes the argument without a bitcast, so this routes
|
||||
// to that retry instead of emitting (and shipping) the rejected module.
|
||||
|| err.contains("cannot reinterpret workgroup pointer")
|
||||
// The other illegal logical-pointer `OpBitcast` reinterpret sites the default path used to ship
|
||||
// a rejected module from: a cross-address-space pointer reinterpret, and a byte (i8) pointer
|
||||
// reinterpreted to a wider load type. Both are inexpressible under Logical addressing without a
|
||||
// pointer bitcast, so they route to the raw byte/word-offset retry instead.
|
||||
|| err.contains("cannot reinterpret pointer")
|
||||
|| err.contains("cannot reinterpret load of byte pointer")
|
||||
// A store THROUGH a direct pointer select whose arms can point into distinct buffers — illegal
|
||||
// as a pointer `OpSelect`+store under Logical addressing. Routes to the all-buffers-raw retry,
|
||||
// which lowers the select + store as byte-offset operations on the raw backings.
|
||||
|| err.contains("cannot store through reinterpreted pointer select")
|
||||
}
|
||||
|
||||
/// Whether emission reached a deferred cross-storage pointer select at an opaque consumer (most
|
||||
/// commonly an internal-helper argument). Logical SPIR-V cannot materialize one pointer value for
|
||||
/// arms in different storage classes; the typed helper-inlining tier preserves the deferred carrier
|
||||
/// across the former parameter boundary and replays its loads in the value domain.
|
||||
pub fn is_deferred_pointer_materialization_emit_error(err: &str) -> bool {
|
||||
err.contains("selected pointer") && err.contains("missing metadata")
|
||||
}
|
||||
|
||||
pub fn deferred_pointer_materialization_name(err: &str) -> Option<String> {
|
||||
let rest = err.split_once("selected pointer ")?.1;
|
||||
let name = rest.split_once(" missing metadata")?.0;
|
||||
if name.is_empty() {
|
||||
return None;
|
||||
}
|
||||
// CFG cross-arm cloning names a cloned SSA value `%xa<fresh-id>_<source-name>`. Retry input is
|
||||
// the pre-structurization AIR text, so carry the structural source suffix back across that
|
||||
// boundary. Ordinary names pass through unchanged.
|
||||
let source = name
|
||||
.strip_prefix("%xa")
|
||||
.and_then(|rest| rest.split_once('_'))
|
||||
.filter(|(id, _)| !id.is_empty() && id.bytes().all(|byte| byte.is_ascii_digit()))
|
||||
.map_or(name.to_string(), |(_, source)| format!("%{source}"));
|
||||
Some(source)
|
||||
}
|
||||
|
||||
/// Whether a native-emitter error came from the typed straight-line body dispatcher after it failed
|
||||
/// to find a migrated lowering/carrier for one instruction. CFG-only retry feeds cannot repair this
|
||||
/// class: they change structured merge handling around already-emitted blocks, but this error occurs
|
||||
/// before the block body is complete.
|
||||
pub fn is_graph_walk_unmigrated_emit_error(err: &str) -> bool {
|
||||
err.contains("reason=graph_walk_unmigrated_opcode")
|
||||
}
|
||||
|
||||
/// Whether a spirv-val rejection of a produced module (`branches to the selection construct`,
|
||||
/// `back-edge`, `header block`, `does not dominate`, …) is a control-flow structurization failure the
|
||||
/// relooper retry tiers can restructure. Used by [`classify_validation_error`] to route a rejected
|
||||
/// module to the `CfgStructurization` cascade; a false positive only wastes a retry that is discarded
|
||||
/// unless it independently validates. Anything pointer/parser/intrinsic-shaped returns false so the
|
||||
/// cfg retry stays off that path. The needle set is spirv-val phrasings only: retired emit-error
|
||||
/// `cost budget` / `clone budget` needles were deleted at cleanup-plan S2 (the repair roster that
|
||||
/// produced them died at W4, and [`classify_emit_error`] no longer consults this predicate).
|
||||
pub fn is_cfg_structurization_error(err: &str) -> bool {
|
||||
let m = err.to_ascii_lowercase();
|
||||
let has = |needle: &str| m.contains(needle);
|
||||
has("structured cfg")
|
||||
|| has("back-edge")
|
||||
|| has("back edge")
|
||||
|| has("loop header")
|
||||
|| has("loop construct")
|
||||
|| has("selection construct")
|
||||
|| has("merge block")
|
||||
|| has("header block")
|
||||
|| has("continue target")
|
||||
|| has("structured exit")
|
||||
|| has("structurally dominate")
|
||||
|| has("does not dominate")
|
||||
// "Block N appears in the binary before its dominator M": a pure block-ORDERING violation in
|
||||
// the structurizer's output — the relooper rebuilds every block into one switch in a
|
||||
// dominance-valid order, so it can repair this. Adopt-if-validates keeps it floor-safe.
|
||||
|| has("before its dominator")
|
||||
|| has("must be structured")
|
||||
|| has("case construct")
|
||||
// Structured-order / unrepaired merge emission can leave a use before its def in the
|
||||
// serialized block stream. spirv-val reports "ID N has not been defined" — the same class of
|
||||
// CFG emission failure the relooper / raw→relooper cascade rebuilds. Without this needle the
|
||||
// message falls through to Other and primary-validated never adopts the production rescue.
|
||||
|| has("has not been defined")
|
||||
}
|
||||
|
||||
/// Whether a spirv-val error is the illegal-logical-pointer-`OpPhi` rejection the M4 phi-the-index
|
||||
/// rewrite (`rewrite_logical_pointer_phis_retry_module`) targets: a pointer `OpPhi`/`OpSelect` in
|
||||
/// a storage class `VariablePointers` cannot cover (Private/UniformConstant/Function). Used by
|
||||
/// `lib.rs`'s retry to route a rejected module to the rewrite; a false positive only wastes a retry
|
||||
/// that is discarded unless the rewrite independently validates.
|
||||
pub fn is_logical_pointer_phi_error(err: &str) -> bool {
|
||||
err.contains("may only have a logical pointer operand")
|
||||
}
|
||||
|
||||
/// Whether a spirv-val error is the cross-binding pointer-merge rejection the W1 PhysicalStorageBuffer64
|
||||
/// rewrite ([`crate::native::rewrite_cross_binding_pointer_merges_bytes`]) targets: an
|
||||
/// `OpSelect`/`OpPhi` over pointers
|
||||
/// from DISTINCT descriptor bindings, illegal under Logical addressing ("Variable pointers must point
|
||||
/// into the same structure"). Used by `lib.rs`'s retry to route a rejected module to the PSB rewrite; a
|
||||
/// false positive only wastes a retry that is discarded unless the rewrite independently validates.
|
||||
pub fn is_cross_binding_pointer_merge_error(err: &str) -> bool {
|
||||
err.contains("Variable pointers must point into the same structure")
|
||||
}
|
||||
|
||||
/// Whether a spirv-val rejection is the dynamic-structure-index rule ("Index into a structure must be
|
||||
/// an OpConstant"): an access chain indexed a struct member with a runtime value, illegal in
|
||||
/// structured SPIR-V. Classifies as [`ValidationClass::Other`] (no dedicated tier), but `lib.rs`'s
|
||||
/// `primary_dynamic_struct_index_inline_sroa_relooper` rewrite refines within `Other` on exactly this
|
||||
/// message. Kept here so validator-text matching lives only in this adapter (cleanup-plan S1).
|
||||
pub fn is_dynamic_struct_index_error(err: &str) -> bool {
|
||||
err.contains("into a structure must be an OpConstant")
|
||||
}
|
||||
|
||||
/// Whether a spirv-val rejection is the illegal-logical-pointer-operand rule ("Instruction may not
|
||||
/// have a logical pointer operand"): an instruction other than an allowed pointer op took a logical
|
||||
/// pointer where the storage class forbids it. Classifies as [`ValidationClass::Other`], but `lib.rs`'s
|
||||
/// `primary_logical_pointer_inline_sroa_raw` rewrite refines within `Other` on exactly this message.
|
||||
/// Distinct from [`is_logical_pointer_phi_error`] (the `OpPhi`-specific rule). Kept here so
|
||||
/// validator-text matching lives only in this adapter (cleanup-plan S1).
|
||||
pub fn is_logical_pointer_operand_error(err: &str) -> bool {
|
||||
err.contains("Instruction may not have a logical pointer operand")
|
||||
}
|
||||
|
||||
/// Structural class of a spirv-val rejection of an *emitted* module, used to route the
|
||||
/// failure-triggered retry cascade in `lib.rs`. This is the single classifier over the substring
|
||||
/// matchers above (§2.2 fact 5 in the refactor plan): a SPIRV-Tools message change now touches one
|
||||
/// place. The precedence here is load-bearing — it MUST equal the order of `lib.rs`'s
|
||||
/// `Err(e) if is_*(e)` guard chain (pointer-typing, then cfg, then logical-pointer-phi, then
|
||||
/// cross-binding), so that `match classify_validation_error(e)` fires exactly the arm the guard chain
|
||||
/// did for an error that matches more than one family (spirv-val reports one error per module, but the
|
||||
/// families are not provably disjoint).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ValidationClass {
|
||||
/// Buffer/pointer mistyping the raw byte-offset path repairs — [`is_pointer_typing_validation_error`].
|
||||
PointerTyping,
|
||||
/// Structured-CFG nesting/dominance violation — [`is_cfg_structurization_error`].
|
||||
CfgStructurization,
|
||||
/// Illegal logical-pointer `OpPhi` — [`is_logical_pointer_phi_error`].
|
||||
LogicalPointerPhi,
|
||||
/// `OpSelect`/`OpPhi` over pointers from distinct bindings — [`is_cross_binding_pointer_merge_error`].
|
||||
CrossBindingPointerMerge,
|
||||
/// None of the retry-routable families (keep the default bytes).
|
||||
Other,
|
||||
}
|
||||
|
||||
/// Classify a spirv-val rejection into its [`ValidationClass`]. Equivalent, arm-for-arm, to the
|
||||
/// ordered `Err(e) if is_*(e)` guard chain it replaces.
|
||||
pub fn classify_validation_error(err: &str) -> ValidationClass {
|
||||
if is_pointer_typing_validation_error(err) {
|
||||
ValidationClass::PointerTyping
|
||||
} else if is_cfg_structurization_error(err) {
|
||||
ValidationClass::CfgStructurization
|
||||
} else if is_logical_pointer_phi_error(err) {
|
||||
ValidationClass::LogicalPointerPhi
|
||||
} else if is_cross_binding_pointer_merge_error(err) {
|
||||
ValidationClass::CrossBindingPointerMerge
|
||||
} else {
|
||||
ValidationClass::Other
|
||||
}
|
||||
}
|
||||
|
||||
/// Structural class of a native-emitter `Err` returned *before* any spirv-val runs, used to route the
|
||||
/// emit-failure retry cascade in `lib.rs`. Only the pointer-typing gap has a dedicated raw-byte
|
||||
/// recovery arm; everything else (including any residual CFG-shaped emit gap) routes to the BDA/raw
|
||||
/// last-resort cascade. (The dedicated cfg-emit-error arm was removed with the W4 repair-roster
|
||||
/// deletion: the roster's repair fixpoint was the sole producer of a cfg-class emit *error*, so no
|
||||
/// emit path returns one anymore — a reject function now emits complete unrepaired bytes that fail
|
||||
/// *validation*, routing through the validation-side cfg cascade instead.)
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum EmitErrorClass {
|
||||
/// Deferred cross-storage pointer consumed across a helper boundary.
|
||||
DeferredPointerMaterialization,
|
||||
/// Buffer/pointer-typing gap the raw byte model can express — [`is_pointer_typing_emit_error`].
|
||||
PointerTyping,
|
||||
/// Any other emit failure.
|
||||
Other,
|
||||
}
|
||||
|
||||
/// Classify a native-emitter emit `Err` into its [`EmitErrorClass`]. Equivalent, arm-for-arm, to the
|
||||
/// ordered `Err(emit_err) if is_*(emit_err)` guard chain it replaces.
|
||||
pub fn classify_emit_error(err: &str) -> EmitErrorClass {
|
||||
if is_deferred_pointer_materialization_emit_error(err) {
|
||||
EmitErrorClass::DeferredPointerMaterialization
|
||||
} else if is_pointer_typing_emit_error(err) {
|
||||
EmitErrorClass::PointerTyping
|
||||
} else {
|
||||
EmitErrorClass::Other
|
||||
}
|
||||
}
|
||||
@@ -1,258 +0,0 @@
|
||||
//! Unit coverage for the retry-routing error classifiers in the parent module (§6 gap-list:
|
||||
//! `native/mod.rs` error classifiers had zero isolated tests). These pure substring predicates decide
|
||||
//! which failure-recovery retry a translate error routes to, keyed on SPIRV-Tools / native-emitter
|
||||
//! message text — so a message-wording change silently mis-routes (or drops) a retry. The tests pin:
|
||||
//! * each predicate on a representative real message (positive) and an unrelated one (negative),
|
||||
//! * the aggregate `classify_*` routing, and
|
||||
//! * the LOAD-BEARING precedence: `classify_validation_error` must resolve a message matching more
|
||||
//! than one family to the same arm the ordered `is_*` guard chain in `lib.rs` fires first.
|
||||
|
||||
use super::{
|
||||
classify_emit_error, classify_validation_error, is_cfg_structurization_error,
|
||||
is_cross_binding_pointer_merge_error, is_dynamic_struct_index_error,
|
||||
is_logical_pointer_operand_error, is_logical_pointer_phi_error, is_pointer_typing_emit_error,
|
||||
is_pointer_typing_validation_error, EmitErrorClass, ValidationClass,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn other_class_refinement_predicates_match_their_exact_messages() {
|
||||
// Both refine within ValidationClass::Other for the two primary-emit rewrites in lib.rs; they
|
||||
// live here so validator-text matching stays in one adapter (S1).
|
||||
assert!(is_dynamic_struct_index_error(
|
||||
"Index into a structure must be an OpConstant"
|
||||
));
|
||||
assert_eq!(
|
||||
classify_validation_error("Index into a structure must be an OpConstant"),
|
||||
ValidationClass::Other
|
||||
);
|
||||
assert!(!is_dynamic_struct_index_error(
|
||||
"OpPhi may only have a logical pointer operand"
|
||||
));
|
||||
|
||||
assert!(is_logical_pointer_operand_error(
|
||||
"Instruction may not have a logical pointer operand"
|
||||
));
|
||||
assert_eq!(
|
||||
classify_validation_error("Instruction may not have a logical pointer operand"),
|
||||
ValidationClass::Other
|
||||
);
|
||||
// Distinct from the OpPhi-specific logical-pointer rule.
|
||||
assert!(!is_logical_pointer_operand_error(
|
||||
"OpPhi may only have a logical pointer operand"
|
||||
));
|
||||
assert!(!is_logical_pointer_phi_error(
|
||||
"Instruction may not have a logical pointer operand"
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pointer_typing_validation_matches_access_chain_messages() {
|
||||
assert!(is_pointer_typing_validation_error(
|
||||
"OpInBoundsAccessChain cannot find index 3"
|
||||
));
|
||||
assert!(is_pointer_typing_validation_error(
|
||||
"Result Type does not match Pointer type"
|
||||
));
|
||||
assert!(is_pointer_typing_validation_error(
|
||||
"Index 2 is out of bounds: reached non-composite type"
|
||||
));
|
||||
// Anchored access-chain index-type mismatch: the real message keys on "used to index".
|
||||
assert!(is_pointer_typing_validation_error(
|
||||
"Result Type does not match the type used to index into the composite"
|
||||
));
|
||||
assert!(is_pointer_typing_validation_error(
|
||||
"The Object type (OpTypePointer) does not match the type that results from indexing into the Composite (OpTypePointer)."
|
||||
));
|
||||
assert!(!is_pointer_typing_validation_error(
|
||||
"some unrelated parser failure"
|
||||
));
|
||||
// M-C3: the anchored "used to index" no longer catches spurious "to index" wordings that the
|
||||
// bare substring did — those must fall through to `Other`, not misroute to the raw retry.
|
||||
assert!(!is_pointer_typing_validation_error(
|
||||
"diagnostic emitted prior to indexing the resource table"
|
||||
));
|
||||
assert!(!is_pointer_typing_validation_error(
|
||||
"the pass failed to index the descriptor set"
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cfg_structurization_is_case_insensitive_over_its_family() {
|
||||
assert!(is_cfg_structurization_error(
|
||||
"Structured CFG rejected: unstructured back-edge"
|
||||
));
|
||||
assert!(is_cfg_structurization_error(
|
||||
"Block 5 has a back-edge to a non-header block"
|
||||
));
|
||||
// The classifier lowercases first, so an upper-case SPIRV-Tools phrasing still routes.
|
||||
assert!(is_cfg_structurization_error(
|
||||
"Block 5 appears in the binary before its dominator 3"
|
||||
));
|
||||
assert!(is_cfg_structurization_error("BACK-EDGE detected"));
|
||||
// The naive-fallback message the repair path emits for a function that REJECTS `structured_plan`
|
||||
// (an S15 reject class) and falls back to `infer_*`+repair — two headers ending up sharing a
|
||||
// post-dominator merge block. Captured fresh 2026-07-08 from all three M-B1 repair-unique blockers
|
||||
// (05/b00a8a8d, 06/389737b0, 07/777b9bb4), which each produce it verbatim under `NO_REPAIR=1`. It
|
||||
// MUST route to CfgStructurization so the cfg restructure retry tier is what gets a shot at these.
|
||||
assert!(is_cfg_structurization_error(
|
||||
"Block '699[%699]' is already a merge block for another header"
|
||||
));
|
||||
assert!(!is_cfg_structurization_error("bit width mismatch"));
|
||||
}
|
||||
|
||||
/// M-C3 classifier hardening — the captured spirv-val cfg-message set.
|
||||
///
|
||||
/// The nine message FAMILIES below are every distinct structured-CFG rejection SPIRV-Tools actually
|
||||
/// emits for the frontier private capture set, captured 2026-07-08 by running
|
||||
/// `METAL2VULKAN_RETRY_DEBUG=1 historical validation tooling and de-duplicating the
|
||||
/// `[retry-debug] default module failed cfg-class spirv-val:` lines (ids elided). Each MUST route to
|
||||
/// `CfgStructurization` so the cfg-restructure / relooper retry tiers are what get a shot at it — a
|
||||
/// message that fell through to `Other` (or was captured by a higher-precedence pointer family) would
|
||||
/// silently drop the cfg-specific recovery. Pinning them here means a future needle edit (or a
|
||||
/// SPIRV-Tools wording change) that breaks routing fails a unit test instead of a execution gate.
|
||||
///
|
||||
/// KEY FINDING (why the 17 needles are broad substrings, NOT anchored full phrases): a single needle
|
||||
/// legitimately catches MULTIPLE distinct real phrasings, so anchoring to any one of them would lose
|
||||
/// the others. `"merge block"` catches both `"... does not structurally dominate the merge block ..."`
|
||||
/// (an admitted-module dominance reject) AND `"... is already a merge block for another header"` (the
|
||||
/// naive-fallback the repair path emits for an S15-rejected function — the M-B1 blocker message above);
|
||||
/// `"case construct"` catches the `"Multiple case constructs ..."`, `"Case construct that targets ..."`,
|
||||
/// and invalid-branch phrasings. The breadth is load-bearing, so M-C3's "replace broad substrings with
|
||||
/// anchored patterns" is verified UNNECESSARY for these needles — every one that fires here catches a
|
||||
/// real cfg message, and every real cfg message is caught. The `"used to index"` anchoring (in
|
||||
/// `is_pointer_typing_validation_error`) remains the correct fix for the ONE needle that had a genuine
|
||||
/// spurious-substring problem.
|
||||
#[test]
|
||||
fn cfg_structurization_routes_captured_spirv_val_messages() {
|
||||
for msg in [
|
||||
"Block '4122[%4122]' appears in the binary before its dominator '4540[%4540]'",
|
||||
"block <ID> '600[%600]' exits the selection headed by <ID> '583[%583]', \
|
||||
but not via a structured exit",
|
||||
"block <ID> 4953 branches to the loop construct, but not to the loop header <ID> 4929",
|
||||
"block <ID> 2640 branches to the selection construct, \
|
||||
but not to the selection header <ID> 1849",
|
||||
"Case construct that targets '193[%193]' has invalid branch to block '226[%226]' \
|
||||
(not another case construct, corresponding merge, outer loop merge or outer loop continue)",
|
||||
"Multiple case constructs have branches to the case construct that targets '501[%501]'",
|
||||
"ID '1234[%1234]' defined in block '10[%10]' does not dominate its use in block '20[%20]'",
|
||||
"Selection must be structured",
|
||||
"The selection construct with the selection header '742[%742]' \
|
||||
does not structurally dominate the merge block '3760[%3760]'",
|
||||
] {
|
||||
assert_eq!(
|
||||
classify_validation_error(msg),
|
||||
ValidationClass::CfgStructurization,
|
||||
"captured spirv-val cfg message must route to CfgStructurization: {msg}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn logical_pointer_phi_and_cross_binding_match_their_exact_messages() {
|
||||
assert!(is_logical_pointer_phi_error(
|
||||
"OpPhi may only have a logical pointer operand"
|
||||
));
|
||||
assert!(!is_logical_pointer_phi_error(
|
||||
"Variable pointers must point into the same structure"
|
||||
));
|
||||
assert!(is_cross_binding_pointer_merge_error(
|
||||
"Variable pointers must point into the same structure or array"
|
||||
));
|
||||
assert!(!is_cross_binding_pointer_merge_error(
|
||||
"OpPhi may only have a logical pointer operand"
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pointer_typing_emit_matches_reinterpret_and_storage_gaps() {
|
||||
assert!(is_pointer_typing_emit_error("load bit width mismatch"));
|
||||
assert!(is_pointer_typing_emit_error(
|
||||
"missing pointer storage class"
|
||||
));
|
||||
assert!(is_pointer_typing_emit_error(
|
||||
"cannot reinterpret load of byte pointer"
|
||||
));
|
||||
assert!(is_pointer_typing_emit_error(
|
||||
"cannot reinterpret workgroup pointer"
|
||||
));
|
||||
assert!(!is_pointer_typing_emit_error(
|
||||
"Structured CFG rejected: unstructured back-edge"
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classify_validation_routes_each_family() {
|
||||
assert_eq!(
|
||||
classify_validation_error("OpInBoundsAccessChain cannot find index 0"),
|
||||
ValidationClass::PointerTyping
|
||||
);
|
||||
assert_eq!(
|
||||
classify_validation_error("loop header block 4 does not dominate its merge"),
|
||||
ValidationClass::CfgStructurization
|
||||
);
|
||||
assert_eq!(
|
||||
classify_validation_error("ID '4994[%4994]' has not been defined"),
|
||||
ValidationClass::CfgStructurization
|
||||
);
|
||||
assert_eq!(
|
||||
classify_validation_error("OpPhi may only have a logical pointer operand"),
|
||||
ValidationClass::LogicalPointerPhi
|
||||
);
|
||||
assert_eq!(
|
||||
classify_validation_error("Variable pointers must point into the same structure"),
|
||||
ValidationClass::CrossBindingPointerMerge
|
||||
);
|
||||
assert_eq!(
|
||||
classify_validation_error("unrelated intrinsic lowering failure"),
|
||||
ValidationClass::Other
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classify_validation_precedence_is_pointer_typing_before_cfg() {
|
||||
// A message that trips BOTH the pointer-typing family ("does not match Pointer") and the cfg
|
||||
// family ("back-edge") must resolve to PointerTyping — the first arm of the guard chain.
|
||||
let both = "Result does not match Pointer type at a back-edge";
|
||||
assert!(is_pointer_typing_validation_error(both));
|
||||
assert!(is_cfg_structurization_error(both));
|
||||
assert_eq!(
|
||||
classify_validation_error(both),
|
||||
ValidationClass::PointerTyping
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classify_validation_precedence_phi_before_cross_binding() {
|
||||
// Logical-pointer-phi outranks cross-binding when a message matches both.
|
||||
let both = "OpPhi may only have a logical pointer operand; \
|
||||
Variable pointers must point into the same structure";
|
||||
assert!(is_logical_pointer_phi_error(both));
|
||||
assert!(is_cross_binding_pointer_merge_error(both));
|
||||
assert_eq!(
|
||||
classify_validation_error(both),
|
||||
ValidationClass::LogicalPointerPhi
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classify_emit_routes_pointer_typing_then_other() {
|
||||
assert_eq!(
|
||||
classify_emit_error("load bit width mismatch"),
|
||||
EmitErrorClass::PointerTyping
|
||||
);
|
||||
// The dedicated cfg-emit-error arm was removed with the W4 repair-roster deletion (no emit path
|
||||
// returns a cfg-class emit error anymore); a residual cfg-shaped emit gap now routes to Other.
|
||||
assert_eq!(
|
||||
classify_emit_error("native emitter: structured cfg rejected"),
|
||||
EmitErrorClass::Other
|
||||
);
|
||||
assert_eq!(
|
||||
classify_emit_error("out of registers"),
|
||||
EmitErrorClass::Other
|
||||
);
|
||||
// A message in both emit families still resolves to PointerTyping (checked first).
|
||||
let both = "missing pointer storage in a structured cfg block";
|
||||
assert!(is_pointer_typing_emit_error(both));
|
||||
assert!(is_cfg_structurization_error(both));
|
||||
assert_eq!(classify_emit_error(both), EmitErrorClass::PointerTyping);
|
||||
}
|
||||
+296
-44
@@ -20,8 +20,61 @@
|
||||
use super::lex::split_top_level;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
/// Inline only internal helper callsites that carry an exact linked function symbol as an
|
||||
/// argument. Substituting the helper parameter turns its indirect `%function(...)` call into an
|
||||
/// ordinary direct `@function(...)` call before Logical-SPIR-V construction, without attempting to
|
||||
/// represent a first-class function pointer.
|
||||
pub(super) fn inline_direct_function_pointer_consumers(
|
||||
san_ll: &str,
|
||||
direct_functions: &HashSet<String>,
|
||||
) -> String {
|
||||
let mut source = san_ll.to_string();
|
||||
loop {
|
||||
let Some(items) = parse_items(&source) else {
|
||||
return source;
|
||||
};
|
||||
let internal = items
|
||||
.iter()
|
||||
.filter_map(|item| {
|
||||
let Item::Func(function) = item else {
|
||||
return None;
|
||||
};
|
||||
let signature = parse_def_header(&function.header)?;
|
||||
signature.internal.then_some(signature.name)
|
||||
})
|
||||
.collect::<HashSet<_>>();
|
||||
let selected = items.iter().find_map(|item| {
|
||||
let Item::Func(function) = item else {
|
||||
return None;
|
||||
};
|
||||
function.body.iter().find_map(|line| {
|
||||
let call = parse_call(line)?;
|
||||
if !internal.contains(&call.callee) {
|
||||
return None;
|
||||
}
|
||||
call.args
|
||||
.iter()
|
||||
.find(|argument| direct_functions.contains(*argument))
|
||||
.map(|argument| (call.callee.clone(), argument.clone()))
|
||||
})
|
||||
});
|
||||
let Some((consumer, function)) = selected else {
|
||||
return source;
|
||||
};
|
||||
let targets = HashSet::from([consumer]);
|
||||
let Some(inlined) = try_inline(&source, Some((&targets, &function, None))) else {
|
||||
return source;
|
||||
};
|
||||
if inlined == source {
|
||||
return source;
|
||||
}
|
||||
source = inlined;
|
||||
}
|
||||
}
|
||||
|
||||
/// Inline every eligible direct call to a module-local `internal` helper, transitively, to a
|
||||
/// fixpoint. Returns the module text unchanged when nothing is eligible or any difficulty is hit.
|
||||
#[cfg(test)]
|
||||
pub(super) fn inline_nonrecursive_internal_calls(san_ll: &str) -> String {
|
||||
match try_inline(san_ll, None) {
|
||||
Some(out) => out,
|
||||
@@ -29,19 +82,37 @@ pub(super) fn inline_nonrecursive_internal_calls(san_ll: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// Inline only internal helpers that directly consume the result of a pointer `select`. This is the
|
||||
/// bounded repair for a deferred cross-storage pointer reaching a call boundary: it removes exactly
|
||||
/// that opaque consumer so ordinary selected-pointer load/store replay can operate inside the cloned
|
||||
/// helper body, without expanding the rest of a large module's internal call graph.
|
||||
pub(super) fn inline_pointer_select_consumer(
|
||||
pub(super) struct PointerConsumerInlining {
|
||||
pub(super) source: String,
|
||||
pub(super) requires_relooper: bool,
|
||||
}
|
||||
|
||||
/// Inline internal helpers that directly consume pointer-select results before emission. A
|
||||
/// deferred select has no standalone Logical-SPIR-V pointer value when its arms name distinct
|
||||
/// buffers; moving its consumer into the caller lets loads/stores replay the select in value space.
|
||||
/// The returned construction fact selects the bounded whole-CFG path whenever inlining changed the
|
||||
/// source, before either emitter attempts to construct a module.
|
||||
pub(super) fn inline_pointer_select_consumers(
|
||||
san_ll: &str,
|
||||
entry_name: Option<&str>,
|
||||
selected_pointer: &str,
|
||||
) -> String {
|
||||
) -> PointerConsumerInlining {
|
||||
let Some(items) = parse_items(san_ll) else {
|
||||
return san_ll.to_string();
|
||||
return PointerConsumerInlining {
|
||||
source: san_ll.to_string(),
|
||||
requires_relooper: false,
|
||||
};
|
||||
};
|
||||
let mut targets = HashSet::new();
|
||||
let eligible_callees = items
|
||||
.iter()
|
||||
.filter_map(|item| {
|
||||
let Item::Func(function) = item else {
|
||||
return None;
|
||||
};
|
||||
let signature = parse_def_header(&function.header)?;
|
||||
signature.internal.then_some(signature.name)
|
||||
})
|
||||
.collect::<HashSet<_>>();
|
||||
let mut selected_consumers = Vec::new();
|
||||
for item in &items {
|
||||
let Item::Func(function) = item else {
|
||||
continue;
|
||||
@@ -54,22 +125,49 @@ pub(super) fn inline_pointer_select_consumer(
|
||||
continue;
|
||||
}
|
||||
}
|
||||
for call in function.body.iter().filter_map(|line| parse_call(line)) {
|
||||
if call
|
||||
.args
|
||||
.iter()
|
||||
.any(|argument| argument == selected_pointer)
|
||||
{
|
||||
targets.insert(call.callee);
|
||||
let pointer_selects = function
|
||||
.body
|
||||
.iter()
|
||||
.filter_map(|line| {
|
||||
let (true_value, false_value) =
|
||||
crate::native::tir::resolve_select_arms(line, "select")?;
|
||||
(matches!(true_value.ty, crate::native::ir::LlType::Ptr(_))
|
||||
&& matches!(false_value.ty, crate::native::ir::LlType::Ptr(_)))
|
||||
.then(|| crate::native::tir::result_name(line))
|
||||
.flatten()
|
||||
})
|
||||
.collect::<HashSet<_>>();
|
||||
for call in function
|
||||
.body
|
||||
.iter()
|
||||
.filter_map(|line| parse_call(line))
|
||||
.filter(|call| eligible_callees.contains(&call.callee))
|
||||
{
|
||||
for argument in call.args {
|
||||
if pointer_selects.contains(&argument)
|
||||
&& !selected_consumers.contains(&(argument.clone(), call.callee.clone()))
|
||||
{
|
||||
selected_consumers.push((argument, call.callee.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if targets.is_empty() {
|
||||
return san_ll.to_string();
|
||||
let mut source = san_ll.to_string();
|
||||
let mut changed = false;
|
||||
for (selected, consumer) in selected_consumers {
|
||||
let targets = HashSet::from([consumer]);
|
||||
if let Some(inlined) = try_inline(&source, Some((&targets, selected.as_str(), entry_name)))
|
||||
{
|
||||
changed |= inlined != source;
|
||||
source = inlined;
|
||||
}
|
||||
}
|
||||
match try_inline(san_ll, Some((&targets, selected_pointer))) {
|
||||
Some(out) => out,
|
||||
None => san_ll.to_string(),
|
||||
PointerConsumerInlining {
|
||||
source,
|
||||
// Inlining may splice a multi-block helper or enlarge an already complex entry. Select the
|
||||
// bounded whole-CFG constructor from that source fact instead of attempting ordinary
|
||||
// emission and waiting for an opaque pointer materialization error.
|
||||
requires_relooper: changed,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -106,13 +204,18 @@ struct DefSig {
|
||||
fn parse_items(san_ll: &str) -> Option<Vec<Item>> {
|
||||
let lines: Vec<&str> = san_ll.lines().collect();
|
||||
let mut items: Vec<Item> = Vec::new();
|
||||
let mut raw: Vec<String> = Vec::new();
|
||||
let mut raw_start = 0;
|
||||
let mut i = 0;
|
||||
while i < lines.len() {
|
||||
let line = lines[i];
|
||||
if line.starts_with("define") && line.trim_end().ends_with('{') {
|
||||
if !raw.is_empty() {
|
||||
items.push(Item::Raw(std::mem::take(&mut raw)));
|
||||
if raw_start != i {
|
||||
items.push(Item::Raw(
|
||||
lines[raw_start..i]
|
||||
.iter()
|
||||
.map(|line| (*line).to_string())
|
||||
.collect(),
|
||||
));
|
||||
}
|
||||
let start = i + 1;
|
||||
let mut j = start;
|
||||
@@ -127,13 +230,18 @@ fn parse_items(san_ll: &str) -> Option<Vec<Item>> {
|
||||
body: lines[start..j].iter().map(|s| s.to_string()).collect(),
|
||||
}));
|
||||
i = j + 1;
|
||||
raw_start = i;
|
||||
} else {
|
||||
raw.push(line.to_string());
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
if !raw.is_empty() {
|
||||
items.push(Item::Raw(raw));
|
||||
if raw_start != lines.len() {
|
||||
items.push(Item::Raw(
|
||||
lines[raw_start..]
|
||||
.iter()
|
||||
.map(|line| (*line).to_string())
|
||||
.collect(),
|
||||
));
|
||||
}
|
||||
Some(items)
|
||||
}
|
||||
@@ -652,7 +760,10 @@ fn preceded_by_label_keyword(out: &str) -> bool {
|
||||
|
||||
/// The whole pass, in the fallible `Option` domain so any bail returns `None` and the caller keeps
|
||||
/// the input verbatim.
|
||||
fn try_inline(san_ll: &str, targets: Option<(&HashSet<String>, &str)>) -> Option<String> {
|
||||
fn try_inline(
|
||||
san_ll: &str,
|
||||
targets: Option<(&HashSet<String>, &str, Option<&str>)>,
|
||||
) -> Option<String> {
|
||||
let items = parse_items(san_ll)?;
|
||||
|
||||
// Collect the internal-function table: name -> (signature, body). Only `define internal`.
|
||||
@@ -663,7 +774,7 @@ fn try_inline(san_ll: &str, targets: Option<(&HashSet<String>, &str)>) -> Option
|
||||
has_any_func = true;
|
||||
let sig = parse_def_header(&f.header)?;
|
||||
if sig.internal
|
||||
&& targets.is_none_or(|(targets, _selected)| targets.contains(&sig.name))
|
||||
&& targets.is_none_or(|(targets, _selected, _entry)| targets.contains(&sig.name))
|
||||
{
|
||||
// Every param must name a value for us to substitute; reject varargs/unnamed.
|
||||
if sig.params.iter().any(|p| p.is_empty()) {
|
||||
@@ -708,18 +819,25 @@ fn try_inline(san_ll: &str, targets: Option<(&HashSet<String>, &str)>) -> Option
|
||||
|
||||
// Rewrite each function body to a fixpoint. A shared counter gives every inlined site a unique
|
||||
// `.inl<K>` prefix across the whole module.
|
||||
let mut counter: usize = 0;
|
||||
let mut counter = next_inline_ordinal(san_ll);
|
||||
let mut out_items: Vec<Item> = Vec::with_capacity(items.len());
|
||||
for it in items {
|
||||
match it {
|
||||
Item::Raw(r) => out_items.push(Item::Raw(r)),
|
||||
Item::Func(f) => {
|
||||
let new_body = inline_body_to_fixpoint(
|
||||
f.body,
|
||||
&internal,
|
||||
&mut counter,
|
||||
targets.map(|(_, selected)| selected),
|
||||
)?;
|
||||
let selected_pointer = targets.and_then(|(_, selected, entry_name)| {
|
||||
let signature = parse_def_header(&f.header)?;
|
||||
entry_name
|
||||
.is_none_or(|entry_name| {
|
||||
signature.name.trim_start_matches('@') == entry_name
|
||||
})
|
||||
.then_some(selected)
|
||||
});
|
||||
let new_body = if targets.is_some() && selected_pointer.is_none() {
|
||||
f.body
|
||||
} else {
|
||||
inline_body_to_fixpoint(f.body, &internal, &mut counter, selected_pointer)?
|
||||
};
|
||||
out_items.push(Item::Func(FuncBlock {
|
||||
header: f.header,
|
||||
body: new_body,
|
||||
@@ -738,6 +856,33 @@ fn try_inline(san_ll: &str, targets: Option<(&HashSet<String>, &str)>) -> Option
|
||||
Some(render(&out_items, san_ll.ends_with('\n')))
|
||||
}
|
||||
|
||||
/// Return an ordinal above every existing `.inl<N>.` namespace in the input. Pointer-consumer
|
||||
/// normalization may invoke the inliner more than once on the progressively rewritten module; a
|
||||
/// per-invocation zero counter would then duplicate SSA values and block labels from an earlier
|
||||
/// invocation.
|
||||
fn next_inline_ordinal(source: &str) -> usize {
|
||||
let bytes = source.as_bytes();
|
||||
let mut next = 0usize;
|
||||
let mut cursor = 0usize;
|
||||
while let Some(relative) = source[cursor..].find(".inl") {
|
||||
let start = cursor + relative + 4;
|
||||
let mut end = start;
|
||||
while end < bytes.len() && bytes[end].is_ascii_digit() {
|
||||
end += 1;
|
||||
}
|
||||
if end > start && bytes.get(end) == Some(&b'.') {
|
||||
if let Ok(ordinal) = source[start..end].parse::<usize>() {
|
||||
next = next.max(ordinal.saturating_add(1));
|
||||
}
|
||||
}
|
||||
cursor = start;
|
||||
if cursor >= source.len() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
next
|
||||
}
|
||||
|
||||
/// Mark-and-sweep the `define internal` functions: roots are the non-internal functions and every
|
||||
/// module-scope `Raw` item; an internal function is live if its `@name` token appears in any live
|
||||
/// item, iterated to a fixpoint (so a helper kept alive only by another live helper survives). This
|
||||
@@ -918,7 +1063,7 @@ fn inline_body_to_fixpoint(
|
||||
let Some(idx) = find_inlinable_call(&body, internal, selected_pointer) else {
|
||||
return Some(body);
|
||||
};
|
||||
body = inline_one(body, idx, internal, counter)?;
|
||||
body = inline_one(body, idx, internal, counter, selected_pointer.is_some())?;
|
||||
budget -= 1;
|
||||
if budget == 0 {
|
||||
return None;
|
||||
@@ -951,12 +1096,16 @@ fn inline_one(
|
||||
idx: usize,
|
||||
internal: &HashMap<String, (DefSig, Vec<String>)>,
|
||||
counter: &mut usize,
|
||||
preserve_caller_cfg: bool,
|
||||
) -> Option<Vec<String>> {
|
||||
let call = parse_call(&body[idx])?;
|
||||
let (sig, callee_body) = internal.get(&call.callee)?;
|
||||
if sig.params.len() != call.args.len() {
|
||||
return None; // arity mismatch (varargs etc.) — refuse
|
||||
}
|
||||
if preserve_caller_cfg && is_single_block_leaf(callee_body) {
|
||||
return inline_single_block_leaf(body, idx, &call, sig, callee_body, counter);
|
||||
}
|
||||
|
||||
let k = *counter;
|
||||
*counter += 1;
|
||||
@@ -1009,8 +1158,19 @@ fn inline_one(
|
||||
let mut returns: Vec<(String, String)> = Vec::new();
|
||||
// The current source block label as we walk callee lines. The entry block is `entry_label`.
|
||||
let mut cur_block = entry_label.clone();
|
||||
// Emit the entry label line first so the entry block is addressable.
|
||||
renamed.push(format!("{entry_label}:"));
|
||||
// An explicitly labeled source entry is renamed to `entry_label` by `label_map`. Only synthesize
|
||||
// the label for an implicit entry; emitting both would create an empty block followed by a
|
||||
// duplicate label, which is not a valid CFG.
|
||||
let has_explicit_entry = callee_body
|
||||
.iter()
|
||||
.find(|line| {
|
||||
let line = line.trim();
|
||||
!line.is_empty() && !line.starts_with(';')
|
||||
})
|
||||
.is_some_and(|line| block_label_id(line).is_some());
|
||||
if !has_explicit_entry {
|
||||
renamed.push(format!("{entry_label}:"));
|
||||
}
|
||||
for line in callee_body {
|
||||
// Track block boundaries: a block-start label line updates cur_block.
|
||||
if let Some(bare) = block_label_id(line) {
|
||||
@@ -1123,6 +1283,78 @@ fn inline_one(
|
||||
Some(new_body)
|
||||
}
|
||||
|
||||
/// Inline a one-block helper without splitting the caller block. This is the selected-pointer
|
||||
/// consumer path: preserving the caller CFG is part of its construction contract.
|
||||
fn inline_single_block_leaf(
|
||||
body: Vec<String>,
|
||||
idx: usize,
|
||||
call: &CallSite,
|
||||
sig: &DefSig,
|
||||
callee_body: &[String],
|
||||
counter: &mut usize,
|
||||
) -> Option<Vec<String>> {
|
||||
let prefix = format!(".inl{}", *counter);
|
||||
*counter += 1;
|
||||
let (local_values, _) = collect_callee_locals(callee_body)?;
|
||||
let mut value_map = HashMap::new();
|
||||
for (parameter, argument) in sig.params.iter().zip(&call.args) {
|
||||
value_map.insert(parameter.clone(), argument.clone());
|
||||
}
|
||||
for value in local_values {
|
||||
value_map.insert(value.clone(), format!("%{prefix}.{}", &value[1..]));
|
||||
}
|
||||
for (parameter, argument) in sig.params.iter().zip(&call.args) {
|
||||
value_map.insert(parameter.clone(), argument.clone());
|
||||
}
|
||||
|
||||
let mut replacement = Vec::new();
|
||||
let mut returned = None;
|
||||
for line in callee_body {
|
||||
if block_label_id(line).is_some() {
|
||||
continue;
|
||||
}
|
||||
if let Some(ret) = parse_ret(line) {
|
||||
returned = Some(match ret {
|
||||
RetKind::Value(_, value) => substitute_value_token(&value, &value_map),
|
||||
RetKind::Void => String::new(),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
replacement.push(rename_line(line, &value_map, &HashMap::new()));
|
||||
}
|
||||
let returned = returned?;
|
||||
let mut after = body[idx + 1..].to_vec();
|
||||
if let Some(result) = &call.result {
|
||||
if returned.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let result_map = HashMap::from([(result.clone(), returned)]);
|
||||
for line in &mut after {
|
||||
*line = rename_line(line, &result_map, &HashMap::new());
|
||||
}
|
||||
}
|
||||
let mut new_body = Vec::with_capacity(body.len() + replacement.len());
|
||||
new_body.extend_from_slice(&body[..idx]);
|
||||
new_body.extend(replacement);
|
||||
new_body.extend(after);
|
||||
Some(new_body)
|
||||
}
|
||||
|
||||
fn is_single_block_leaf(body: &[String]) -> bool {
|
||||
body.iter()
|
||||
.filter(|line| block_label_id(line).is_some())
|
||||
.count()
|
||||
<= 1
|
||||
&& body.iter().filter(|line| parse_ret(line).is_some()).count() == 1
|
||||
&& !body.iter().any(|line| {
|
||||
let line = line.trim_start();
|
||||
line.starts_with("br ")
|
||||
|| line.starts_with("switch ")
|
||||
|| line.starts_with("indirectbr ")
|
||||
|| line.starts_with("unreachable")
|
||||
})
|
||||
}
|
||||
|
||||
/// The `%name` value or literal token substituted through `value_map` (for `ret` operands, which are
|
||||
/// value positions only).
|
||||
fn substitute_value_token(tok: &str, value_map: &HashMap<String, String>) -> String {
|
||||
@@ -1324,6 +1556,13 @@ fn is_phi_line(line: &str) -> bool {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn repeated_inlining_starts_after_existing_namespace() {
|
||||
let source = "%x.inl2.value = add i32 1, 2\n.inl17.block:\n ret void\n";
|
||||
assert_eq!(next_inline_ordinal(source), 18);
|
||||
assert_eq!(next_inline_ordinal("define void @f() { ret void }\n"), 0);
|
||||
}
|
||||
|
||||
// 7. Token-rename edge case: renaming %1 must not touch %10 or %11.
|
||||
#[test]
|
||||
fn rename_is_token_accurate() {
|
||||
@@ -1734,7 +1973,7 @@ merge:
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pointer_select_consumer_inline_is_bounded_to_the_consuming_helper() {
|
||||
fn pointer_select_consumer_inline_is_structurally_planned() {
|
||||
let src = r#"
|
||||
@fallback = internal addrspace(2) global i32 0
|
||||
@fc_default = internal addrspace(2) global i8 0
|
||||
@@ -1761,15 +2000,26 @@ entry:
|
||||
ret i32 %sum
|
||||
}
|
||||
|
||||
define internal i32 @consume_leaf(ptr addrspace(2) %pointer) {
|
||||
entry:
|
||||
%value = load i32, ptr addrspace(2) %pointer
|
||||
ret i32 %value
|
||||
}
|
||||
|
||||
define i32 @main(ptr addrspace(2) %runtime, i1 %choose) {
|
||||
entry:
|
||||
%selected = select i1 %choose, ptr addrspace(2) %runtime, ptr addrspace(2) @fallback
|
||||
%first = select i1 %choose, ptr addrspace(2) %runtime, ptr addrspace(2) @fallback
|
||||
%selected = select i1 %choose, ptr addrspace(2) @fallback, ptr addrspace(2) %first
|
||||
%leaf = call i32 @consume_leaf(ptr addrspace(2) %selected)
|
||||
%consumed = call i32 @consume(ptr addrspace(2) %selected, i1 %choose)
|
||||
%other = call i32 @unrelated(i32 %consumed)
|
||||
%sum = add i32 %leaf, %consumed
|
||||
%other = call i32 @unrelated(i32 %sum)
|
||||
ret i32 %other
|
||||
}
|
||||
"#;
|
||||
let out = inline_pointer_select_consumer(src, Some("main"), "%selected");
|
||||
let plan = inline_pointer_select_consumers(src, Some("main"));
|
||||
let out = &plan.source;
|
||||
assert!(plan.requires_relooper);
|
||||
assert!(!out.contains("call i32 @consume"), "{out}");
|
||||
assert!(out.contains("call i32 @unrelated"), "{out}");
|
||||
assert!(out.contains("define internal i32 @unrelated"), "{out}");
|
||||
@@ -1777,6 +2027,8 @@ entry:
|
||||
out.contains("define internal void @_GLOBAL__sub_I_defaults"),
|
||||
"implicit constructor root was swept:\n{out}"
|
||||
);
|
||||
assert!(out.contains(".inl0.left:"), "{out}");
|
||||
assert!(out.contains(".left:"), "{out}");
|
||||
|
||||
assert!(!out.contains("call i32 @consume_leaf"), "{out}");
|
||||
}
|
||||
}
|
||||
@@ -19,9 +19,9 @@ impl LlModule {
|
||||
while changed {
|
||||
changed = false;
|
||||
for inst in f.carrier_insts() {
|
||||
if let Some((res, base)) = &inst.identity_ptr_bitcast {
|
||||
if let Some((res, base)) = inst.identity_ptr_bitcast() {
|
||||
if let Some(root) = roots.get(base).cloned() {
|
||||
if roots.insert(res.clone(), root).is_none() {
|
||||
if roots.insert(res.to_string(), root).is_none() {
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
@@ -31,7 +31,7 @@ impl LlModule {
|
||||
let Some(res) = &inst.result else {
|
||||
continue;
|
||||
};
|
||||
if let Some(gep) = &inst.gep {
|
||||
if let Some(gep) = &inst.gep() {
|
||||
let LlValue::Local(base) = &gep.base.value else {
|
||||
continue;
|
||||
};
|
||||
@@ -48,7 +48,7 @@ impl LlModule {
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Some(incoming) = &inst.phi_incoming_values {
|
||||
if let Some(incoming) = inst.phi_values() {
|
||||
let mut root: Option<String> = None;
|
||||
for value in incoming {
|
||||
let LlValue::Local(name) = value else {
|
||||
@@ -138,7 +138,7 @@ impl LlModule {
|
||||
// `alloca_ty` is `resolve_alloca_ty` — the exact `parse_type(parts[0])` on the post-`alloca`
|
||||
// comma-split the reader ran, computed only for `opcode == "alloca"`, so a `Some` here is
|
||||
// precisely the reader's parsed alloca type. The result name is the reader's LHS.
|
||||
let (Some(name), Some(ty)) = (&inst.result, &inst.alloca_ty) else {
|
||||
let (Some(name), Some(ty)) = (&inst.result, &inst.alloca_ty()) else {
|
||||
continue;
|
||||
};
|
||||
allocas.insert(name.clone(), ty.clone());
|
||||
|
||||
@@ -24,6 +24,11 @@ impl LlModule {
|
||||
let Some(layout) = kern.layout_of(idx as u32) else {
|
||||
continue;
|
||||
};
|
||||
let key = (entry.name.clone(), name.clone());
|
||||
if self.air_metadata_requires_byte_view(layout) {
|
||||
self.raw_buffer_params.insert(key);
|
||||
continue;
|
||||
}
|
||||
let Some(declared_size) = kern.buffer_type_size(idx as u32) else {
|
||||
continue;
|
||||
};
|
||||
@@ -34,7 +39,6 @@ impl LlModule {
|
||||
if size != u64::from(declared_size) {
|
||||
continue;
|
||||
}
|
||||
let key = (entry.name.clone(), name.clone());
|
||||
if !self.ptr_pointees.contains_key(&key) {
|
||||
self.ptr_pointees.insert(key.clone(), pointee);
|
||||
self.metadata_pointee_sizes
|
||||
|
||||
+430
-25
@@ -1,5 +1,5 @@
|
||||
use super::parse::{
|
||||
is_ignored_intrinsic, parse_declaration, parse_function, parse_global, parse_type,
|
||||
is_ignored_intrinsic, parse_declaration, parse_function_header, parse_global, parse_type,
|
||||
strip_comment,
|
||||
};
|
||||
use crate::meta::{self, AirScalar, AirType, KernRole};
|
||||
@@ -39,7 +39,7 @@ pub(super) enum LlTypeCapability {
|
||||
Int64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(super) struct TypedValue {
|
||||
pub(super) ty: LlType,
|
||||
pub(super) value: LlValue,
|
||||
@@ -70,7 +70,39 @@ pub(super) enum LlValue {
|
||||
Undef,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
impl PartialEq for LlValue {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
match (self, other) {
|
||||
(Self::Local(a), Self::Local(b)) | (Self::Global(a), Self::Global(b)) => a == b,
|
||||
(Self::Bool(a), Self::Bool(b)) => a == b,
|
||||
(Self::Int(a), Self::Int(b)) | (Self::Hex(a), Self::Hex(b)) => a == b,
|
||||
(Self::SignedInt(a), Self::SignedInt(b)) => a == b,
|
||||
(Self::Float(a), Self::Float(b)) => a.to_bits() == b.to_bits(),
|
||||
(Self::HalfBits(a), Self::HalfBits(b)) | (Self::BFloatBits(a), Self::BFloatBits(b)) => {
|
||||
a == b
|
||||
}
|
||||
(Self::Vector(a), Self::Vector(b))
|
||||
| (Self::Array(a), Self::Array(b))
|
||||
| (Self::Struct(a), Self::Struct(b)) => a == b,
|
||||
(Self::Splat(a), Self::Splat(b)) => a == b,
|
||||
(Self::Gep(a), Self::Gep(b)) => a == b,
|
||||
(
|
||||
Self::IntToPtr {
|
||||
source: a_source,
|
||||
destination: a_destination,
|
||||
},
|
||||
Self::IntToPtr {
|
||||
source: b_source,
|
||||
destination: b_destination,
|
||||
},
|
||||
) => a_source == b_source && a_destination == b_destination,
|
||||
(Self::Zero, Self::Zero) | (Self::Undef, Self::Undef) => true,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(super) struct LlGep {
|
||||
pub(super) inbounds: bool,
|
||||
pub(super) source_ty: LlType,
|
||||
@@ -137,7 +169,7 @@ pub(super) struct LlModule {
|
||||
pub(super) declarations: Vec<LlDeclaration>,
|
||||
pub(super) globals: Vec<LlGlobal>,
|
||||
/// Proven immutable integer values materialized by AIR static initializers.
|
||||
static_init_int_globals: HashMap<String, u32>,
|
||||
static_init_globals: HashMap<String, meta::StaticIntValue>,
|
||||
/// Stage entry selected by the caller's parsed AIR metadata. `None` preserves the downstream
|
||||
/// transform's historical fallback to the first bodied function.
|
||||
pub(super) entry_name: Option<String>,
|
||||
@@ -176,7 +208,48 @@ pub(super) struct LlModule {
|
||||
/// Entry params declared `air.buffer` in the kernel metadata (any element type): DATA pointers,
|
||||
/// as opposed to `air.texture`/sampler args that also arrive as `ptr addrspace(1)` params.
|
||||
pub(super) metadata_data_buffer_params: HashSet<(String, String)>,
|
||||
/// Primitive pointee declared by AIR entry-buffer metadata, retained independently from the
|
||||
/// use-inferred logical pointer type. Representation planning needs this source contract when a
|
||||
/// helper reinterprets a float buffer through an integer atomic view.
|
||||
pub(super) metadata_primitive_buffer_pointees: HashMap<(String, String), LlType>,
|
||||
/// Entry function-constant buffer parameters keyed to their shared Metal buffer location.
|
||||
pub(super) metadata_fc_buffer_locations: HashMap<(String, String), u32>,
|
||||
pub(super) raw_buffer_params: HashSet<(String, String)>,
|
||||
/// Buffer parameters whose raw representation was selected because one call-connected object
|
||||
/// has storage-incompatible views. Interface construction must retain that representation
|
||||
/// instead of reconstructing one endpoint's typed view.
|
||||
pub(super) call_connected_raw_params: HashSet<(String, String)>,
|
||||
/// Raw parameters connected through an address-preserving call edge to another function
|
||||
/// parameter. Workgroup memory in this set can share one raw entry allocation; a raw helper fed
|
||||
/// from a typed global cannot and retains its concrete vector-backed lowering.
|
||||
pub(super) param_connected_raw_params: HashSet<(String, String)>,
|
||||
}
|
||||
|
||||
fn infer_metadata_fc_buffer_locations(
|
||||
kern: Option<&meta::KernMeta>,
|
||||
entry_name: Option<&str>,
|
||||
functions: &[LlFunction],
|
||||
) -> HashMap<(String, String), u32> {
|
||||
let Some(kern) = kern else {
|
||||
return HashMap::new();
|
||||
};
|
||||
let Some(entry_name) = entry_name else {
|
||||
return HashMap::new();
|
||||
};
|
||||
let Some(entry) = functions
|
||||
.iter()
|
||||
.find(|function| function.name == entry_name)
|
||||
else {
|
||||
return HashMap::new();
|
||||
};
|
||||
kern.function_constant_buffer_locations
|
||||
.iter()
|
||||
.filter_map(|(index, location)| {
|
||||
let (name, ty) = entry.params.get(*index as usize)?;
|
||||
matches!(ty, LlType::Ptr(1 | 2))
|
||||
.then(|| ((entry.name.clone(), name.clone()), *location))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
@@ -201,9 +274,9 @@ fn pointer_param_alias_roots(f: &LlFunction) -> HashMap<String, String> {
|
||||
while changed {
|
||||
changed = false;
|
||||
for inst in f.carrier_insts() {
|
||||
if let Some((res, base)) = &inst.identity_ptr_bitcast {
|
||||
if let Some((res, base)) = inst.identity_ptr_bitcast() {
|
||||
if let Some(root) = roots.get(base).cloned() {
|
||||
if roots.insert(res.clone(), root).is_none() {
|
||||
if roots.insert(res.to_string(), root).is_none() {
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
@@ -213,7 +286,7 @@ fn pointer_param_alias_roots(f: &LlFunction) -> HashMap<String, String> {
|
||||
let Some(res) = &inst.result else {
|
||||
continue;
|
||||
};
|
||||
if let Some(gep) = &inst.gep {
|
||||
if let Some(gep) = &inst.gep() {
|
||||
let LlValue::Local(base) = &gep.base.value else {
|
||||
continue;
|
||||
};
|
||||
@@ -241,15 +314,15 @@ fn pointer_param_alias_roots(f: &LlFunction) -> HashMap<String, String> {
|
||||
}
|
||||
Some(root)
|
||||
};
|
||||
if let Some(incoming) = &inst.phi_incoming_values {
|
||||
if let Some(root) = common_root(incoming.iter().collect()) {
|
||||
if let Some(incoming) = inst.phi_values() {
|
||||
if let Some(root) = common_root(incoming.collect()) {
|
||||
if roots.insert(res.clone(), root).is_none() {
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if let Some((true_value, false_value)) = inst.select_arms.as_deref() {
|
||||
if let Some((true_value, false_value)) = inst.select_arms().as_deref() {
|
||||
if !matches!(true_value.ty, LlType::Ptr(_))
|
||||
|| !matches!(false_value.ty, LlType::Ptr(_))
|
||||
{
|
||||
@@ -284,17 +357,17 @@ fn cross_buffer_pointer_phi_gep_sources(f: &LlFunction) -> HashMap<String, HashS
|
||||
while changed {
|
||||
changed = false;
|
||||
for inst in f.carrier_insts() {
|
||||
if let Some((res, base)) = &inst.identity_ptr_bitcast {
|
||||
if let Some((res, base)) = inst.identity_ptr_bitcast() {
|
||||
let Some(base_roots) = roots.get(base).cloned() else {
|
||||
continue;
|
||||
};
|
||||
let base_has_phi = contains_phi.get(base).copied().unwrap_or(false);
|
||||
let result_roots = roots.entry(res.clone()).or_default();
|
||||
let result_roots = roots.entry(res.to_string()).or_default();
|
||||
let old_len = result_roots.len();
|
||||
result_roots.extend(base_roots);
|
||||
changed |= result_roots.len() != old_len;
|
||||
if base_has_phi && !contains_phi.get(res).copied().unwrap_or(false) {
|
||||
contains_phi.insert(res.clone(), true);
|
||||
contains_phi.insert(res.to_string(), true);
|
||||
changed = true;
|
||||
}
|
||||
continue;
|
||||
@@ -303,7 +376,7 @@ fn cross_buffer_pointer_phi_gep_sources(f: &LlFunction) -> HashMap<String, HashS
|
||||
let Some(res) = &inst.result else {
|
||||
continue;
|
||||
};
|
||||
if let Some(gep) = &inst.gep {
|
||||
if let Some(gep) = &inst.gep() {
|
||||
let LlValue::Local(base) = &gep.base.value else {
|
||||
continue;
|
||||
};
|
||||
@@ -323,7 +396,7 @@ fn cross_buffer_pointer_phi_gep_sources(f: &LlFunction) -> HashMap<String, HashS
|
||||
continue;
|
||||
}
|
||||
|
||||
let (merge_roots, result_has_phi) = if let Some(incoming) = &inst.phi_incoming_values {
|
||||
let (merge_roots, result_has_phi) = if let Some(incoming) = inst.phi_values() {
|
||||
let mut merged = HashSet::new();
|
||||
let mut complete = true;
|
||||
for value in incoming {
|
||||
@@ -338,7 +411,7 @@ fn cross_buffer_pointer_phi_gep_sources(f: &LlFunction) -> HashMap<String, HashS
|
||||
merged.extend(value_roots.iter().cloned());
|
||||
}
|
||||
(complete.then_some(merged), true)
|
||||
} else if let Some((true_value, false_value)) = inst.select_arms.as_deref() {
|
||||
} else if let Some((true_value, false_value)) = inst.select_arms().as_deref() {
|
||||
if !matches!(true_value.ty, LlType::Ptr(_))
|
||||
|| !matches!(false_value.ty, LlType::Ptr(_))
|
||||
{
|
||||
@@ -382,7 +455,7 @@ fn cross_buffer_pointer_phi_gep_sources(f: &LlFunction) -> HashMap<String, HashS
|
||||
|
||||
let mut sources: HashMap<String, HashSet<LlType>> = HashMap::new();
|
||||
for inst in f.carrier_insts() {
|
||||
let Some(gep) = &inst.gep else {
|
||||
let Some(gep) = &inst.gep() else {
|
||||
continue;
|
||||
};
|
||||
let LlValue::Local(base) = &gep.base.value else {
|
||||
@@ -469,13 +542,52 @@ fn infer_metadata_data_buffer_params(
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
if matches!(ty, LlType::Ptr(1 | 2)) {
|
||||
let device_buffer_array = matches!(ty, LlType::Ptr(0))
|
||||
&& kern
|
||||
.buffer_type_name(idx as u32)
|
||||
.is_some_and(meta::is_device_buffer_array_type_name);
|
||||
if matches!(ty, LlType::Ptr(1 | 2)) || device_buffer_array {
|
||||
out.insert((entry.name.clone(), name.clone()));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn infer_metadata_primitive_buffer_pointees(
|
||||
kern: Option<&meta::KernMeta>,
|
||||
entry_name: Option<&str>,
|
||||
functions: &[LlFunction],
|
||||
) -> HashMap<(String, String), LlType> {
|
||||
let mut out = HashMap::new();
|
||||
let (Some(kern), Some(entry_name)) = (kern, entry_name) else {
|
||||
return out;
|
||||
};
|
||||
let Some(entry) = functions
|
||||
.iter()
|
||||
.find(|function| function.name == entry_name)
|
||||
else {
|
||||
return out;
|
||||
};
|
||||
for (index, (name, ty)) in entry.params.iter().enumerate() {
|
||||
if !matches!(ty, LlType::Ptr(1..=3))
|
||||
|| !matches!(kern.role_of(index as u32), Some(KernRole::Buffer(_)))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let Some(layout) = kern
|
||||
.buffer_type_name(index as u32)
|
||||
.and_then(meta::primitive_air_type_from_name)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
out.insert(
|
||||
(entry.name.clone(), name.clone()),
|
||||
ll_type_from_air_type(&layout),
|
||||
);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn infer_cross_coordinate_imageblock(
|
||||
functions: &[LlFunction],
|
||||
entry_functions: &HashSet<String>,
|
||||
@@ -486,7 +598,7 @@ fn infer_cross_coordinate_imageblock(
|
||||
{
|
||||
let mut coordinates = HashSet::new();
|
||||
for inst in function.carrier_insts() {
|
||||
let Some(call) = &inst.alias_call else {
|
||||
let Some(call) = inst.alias_call() else {
|
||||
continue;
|
||||
};
|
||||
if call.callee != "air.imageblock_data" {
|
||||
@@ -520,9 +632,30 @@ fn infer_imageblock_nonzero_byte_field(
|
||||
functions: &[LlFunction],
|
||||
entry_functions: &HashSet<String>,
|
||||
) -> bool {
|
||||
let function_by_name = functions
|
||||
.iter()
|
||||
.map(|function| (function.name.as_str(), function))
|
||||
.collect::<HashMap<_, _>>();
|
||||
let mut reachable = entry_functions.clone();
|
||||
let mut pending = entry_functions.iter().cloned().collect::<Vec<_>>();
|
||||
while let Some(name) = pending.pop() {
|
||||
let Some(function) = function_by_name.get(name.as_str()) else {
|
||||
continue;
|
||||
};
|
||||
for call in function
|
||||
.carrier_insts()
|
||||
.filter_map(|inst| inst.call().as_deref())
|
||||
{
|
||||
if function_by_name.contains_key(call.callee.as_str())
|
||||
&& reachable.insert(call.callee.clone())
|
||||
{
|
||||
pending.push(call.callee.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
for function in functions
|
||||
.iter()
|
||||
.filter(|function| entry_functions.contains(&function.name))
|
||||
.filter(|function| reachable.contains(&function.name))
|
||||
{
|
||||
let mut roots = HashSet::new();
|
||||
let mut changed = true;
|
||||
@@ -540,22 +673,21 @@ fn infer_imageblock_nonzero_byte_field(
|
||||
// `alias_call` on a result-bearing line comes only from the value-call rhs path (the
|
||||
// void fallback needs a `= `-less line), so this is the reader's `strip_call_prefix(rhs)`.
|
||||
if inst
|
||||
.alias_call
|
||||
.as_ref()
|
||||
.alias_call()
|
||||
.is_some_and(|call| call.callee == "air.imageblock_data")
|
||||
{
|
||||
changed |= roots.insert(result.clone());
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Some((alias, base)) = &inst.identity_ptr_bitcast {
|
||||
if let Some((alias, base)) = inst.identity_ptr_bitcast() {
|
||||
if roots.contains(base) {
|
||||
changed |= roots.insert(alias.clone());
|
||||
changed |= roots.insert(alias.to_string());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
let Some(gep) = &inst.gep else {
|
||||
let Some(gep) = &inst.gep() else {
|
||||
continue;
|
||||
};
|
||||
let LlValue::Local(base) = &gep.base.value else {
|
||||
@@ -580,6 +712,49 @@ fn infer_imageblock_nonzero_byte_field(
|
||||
false
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod imageblock_reachability_tests {
|
||||
use super::*;
|
||||
|
||||
fn module(entry_calls_helper: bool) -> LlModule {
|
||||
let call = if entry_calls_helper {
|
||||
" call void @helper()\n"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
LlModule::parse(&format!(
|
||||
r#"define void @entry() {{
|
||||
entry:
|
||||
{call} ret void
|
||||
}}
|
||||
define internal void @helper() {{
|
||||
entry:
|
||||
%data = call ptr addrspace(4) @air.imageblock_data(<2 x i16> zeroinitializer, i32 0, i16 0)
|
||||
%field = getelementptr i8, ptr addrspace(4) %data, i64 16
|
||||
ret void
|
||||
}}
|
||||
declare ptr addrspace(4) @air.imageblock_data(<2 x i16>, i32, i16)
|
||||
"#
|
||||
))
|
||||
.expect("module parses")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reachable_helper_nonzero_byte_field_requires_complete_imageblock_cell() {
|
||||
let reachable = module(true);
|
||||
assert!(infer_imageblock_nonzero_byte_field(
|
||||
&reachable.functions,
|
||||
&HashSet::from(["entry".to_string()])
|
||||
));
|
||||
|
||||
let unreachable = module(false);
|
||||
assert!(!infer_imageblock_nonzero_byte_field(
|
||||
&unreachable.functions,
|
||||
&HashSet::from(["entry".to_string()])
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
fn infer_apv_imageblock_dimensions(ll: &str) -> Option<[u32; 2]> {
|
||||
let root = ll.lines().find_map(|line| {
|
||||
let rest = line
|
||||
@@ -862,6 +1037,64 @@ mod layout_abi_tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn air_metadata_incompatible_with_vulkan_block_layout_requires_a_byte_view() {
|
||||
let m = module();
|
||||
let overlapping = AirType::Struct(vec![
|
||||
AirMember {
|
||||
offset: 0,
|
||||
ty: AirType::Array {
|
||||
elem: Box::new(AirType::Scalar(AirScalar::UInt)),
|
||||
len: 8,
|
||||
},
|
||||
},
|
||||
AirMember {
|
||||
offset: 16,
|
||||
ty: AirType::Array {
|
||||
elem: Box::new(AirType::Scalar(AirScalar::UInt)),
|
||||
len: 8,
|
||||
},
|
||||
},
|
||||
]);
|
||||
assert!(m.air_metadata_requires_byte_view(&overlapping));
|
||||
|
||||
let stride_overlap = 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),
|
||||
},
|
||||
])),
|
||||
len: 2,
|
||||
},
|
||||
},
|
||||
AirMember {
|
||||
offset: 28,
|
||||
ty: AirType::Scalar(AirScalar::UInt),
|
||||
},
|
||||
]);
|
||||
assert!(m.air_metadata_requires_byte_view(&stride_overlap));
|
||||
|
||||
let adjacent = AirType::Struct(vec![
|
||||
AirMember {
|
||||
offset: 0,
|
||||
ty: AirType::Scalar(AirScalar::UInt),
|
||||
},
|
||||
AirMember {
|
||||
offset: 4,
|
||||
ty: AirType::Scalar(AirScalar::UInt),
|
||||
},
|
||||
]);
|
||||
assert!(!m.air_metadata_requires_byte_view(&adjacent));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn differential_calculators_agree_on_scalars_and_scalar_aggregates() {
|
||||
// Where the layout rules MUST agree, S4's oracle unification must keep them equal.
|
||||
@@ -1005,6 +1238,41 @@ mod raw_buffer_inference_tests {
|
||||
assert!(params(air).contains(&("k".to_string(), "%buf".to_string())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pointer_value_store_marks_destination_param_raw() {
|
||||
let air = concat!(
|
||||
"define void @k(ptr addrspace(1) %out, ptr addrspace(1) %source) {\n",
|
||||
"entry:\n",
|
||||
" store ptr addrspace(1) %source, ptr addrspace(1) %out, align 8\n",
|
||||
" ret void\n",
|
||||
"}\n",
|
||||
);
|
||||
assert!(params(air).contains(&("k".to_string(), "%out".to_string())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_select_gep_infers_every_pointer_param_pointee() {
|
||||
let air = concat!(
|
||||
"define void @k(ptr addrspace(1) %a, ptr addrspace(1) %b, ptr addrspace(1) %c, i1 %x, i1 %y) {\n",
|
||||
"entry:\n",
|
||||
" %inner = select i1 %x, ptr addrspace(1) %a, ptr addrspace(1) %b\n",
|
||||
" %outer = select i1 %y, ptr addrspace(1) %inner, ptr addrspace(1) %c\n",
|
||||
" %element = getelementptr half, ptr addrspace(1) %outer, i64 0\n",
|
||||
" %value = load half, ptr addrspace(1) %element\n",
|
||||
" ret void\n",
|
||||
"}\n",
|
||||
);
|
||||
let module = LlModule::parse(air).expect("fixture parses");
|
||||
for param in ["%a", "%b", "%c"] {
|
||||
assert_eq!(
|
||||
module
|
||||
.ptr_pointees
|
||||
.get(&("k".to_string(), param.to_string())),
|
||||
Some(&LlType::Half)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_typed_load_leaves_param_typed() {
|
||||
// A param read only ever as one consistent scalar type has a valid typed view — NOT raw.
|
||||
@@ -1018,6 +1286,55 @@ mod raw_buffer_inference_tests {
|
||||
assert!(!params(air).contains(&("k".to_string(), "%buf".to_string())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opaque_memcpy_source_into_local_aggregate_is_raw() {
|
||||
let air = concat!(
|
||||
"%S = type { <4 x float> }\n",
|
||||
"define void @k(ptr addrspace(2) %src) {\n",
|
||||
"entry:\n",
|
||||
" %dst = alloca %S\n",
|
||||
" %field = getelementptr %S, ptr %dst, i64 0, i32 0\n",
|
||||
" %source = bitcast ptr addrspace(2) %src to ptr addrspace(2)\n",
|
||||
" call void @llvm.memcpy.p0.p2.i64(ptr %field, ptr addrspace(2) %source, i64 16, i1 false)\n",
|
||||
" ret void\n",
|
||||
"}\n",
|
||||
"declare void @llvm.memcpy.p0.p2.i64(ptr, ptr addrspace(2), i64, i1)\n",
|
||||
);
|
||||
assert!(params(air).contains(&("k".to_string(), "%src".to_string())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_memcpy_source_into_local_aggregate_stays_typed() {
|
||||
let air = concat!(
|
||||
"%S = type { <4 x float> }\n",
|
||||
"define void @k(ptr addrspace(2) %src) {\n",
|
||||
"entry:\n",
|
||||
" %dst = alloca %S\n",
|
||||
" %field = getelementptr %S, ptr %dst, i64 0, i32 0\n",
|
||||
" %source = getelementptr <4 x float>, ptr addrspace(2) %src, i64 0\n",
|
||||
" call void @llvm.memcpy.p0.p2.i64(ptr %field, ptr addrspace(2) %source, i64 16, i1 false)\n",
|
||||
" ret void\n",
|
||||
"}\n",
|
||||
"declare void @llvm.memcpy.p0.p2.i64(ptr, ptr addrspace(2), i64, i1)\n",
|
||||
);
|
||||
assert!(!params(air).contains(&("k".to_string(), "%src".to_string())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opaque_memcpy_destination_does_not_imply_local_aggregate_storage() {
|
||||
let air = concat!(
|
||||
"define void @k(ptr addrspace(2) %src) {\n",
|
||||
"entry:\n",
|
||||
" %dst = call ptr @destination()\n",
|
||||
" call void @llvm.memcpy.p0.p2.i64(ptr %dst, ptr addrspace(2) %src, i64 16, i1 false)\n",
|
||||
" ret void\n",
|
||||
"}\n",
|
||||
"declare ptr @destination()\n",
|
||||
"declare void @llvm.memcpy.p0.p2.i64(ptr, ptr addrspace(2), i64, i1)\n",
|
||||
);
|
||||
assert!(!params(air).contains(&("k".to_string(), "%src".to_string())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_pointer_param_is_never_raw() {
|
||||
// Only addrspace pointer params are candidates; a by-value scalar param cannot be a buffer.
|
||||
@@ -1051,11 +1368,82 @@ mod raw_buffer_inference_tests {
|
||||
" ret void\n",
|
||||
"}\n",
|
||||
);
|
||||
let module = LlModule::parse(air).expect("fixture parses");
|
||||
let entry = ("entry".to_string(), "%buf".to_string());
|
||||
let helper = ("helper".to_string(), "%p".to_string());
|
||||
assert!(module.raw_buffer_params.contains(&entry));
|
||||
assert!(module.raw_buffer_params.contains(&helper));
|
||||
assert!(module.call_connected_raw_params.contains(&entry));
|
||||
assert!(module.call_connected_raw_params.contains(&helper));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn incompatible_call_connected_aggregate_views_select_raw_buffers() {
|
||||
// One buffer object is a packed-byte view in the entry and an array-of-float view in its
|
||||
// helper. Each function has only one local source type, but the call edge proves that a
|
||||
// single typed SPIR-V pointee cannot represent both views.
|
||||
let air = concat!(
|
||||
"define void @entry(ptr addrspace(1) %buf) {\n",
|
||||
"entry:\n",
|
||||
" %alias = getelementptr [3 x i8], ptr addrspace(1) %buf, i64 0, i64 0\n",
|
||||
" call void @helper(ptr addrspace(1) %alias)\n",
|
||||
" ret void\n",
|
||||
"}\n",
|
||||
"define void @helper(ptr addrspace(1) %p) {\n",
|
||||
"entry:\n",
|
||||
" %field = getelementptr [3 x float], ptr addrspace(1) %p, i64 0, i64 1\n",
|
||||
" %value = load float, ptr addrspace(1) %field\n",
|
||||
" ret void\n",
|
||||
"}\n",
|
||||
);
|
||||
let raw = params(air);
|
||||
assert!(raw.contains(&("entry".to_string(), "%buf".to_string())));
|
||||
assert!(raw.contains(&("helper".to_string(), "%p".to_string())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn call_connected_workgroup_reinterpretation_selects_raw_words() {
|
||||
let air = concat!(
|
||||
"define void @entry(ptr addrspace(3) %scratch) {\n",
|
||||
"entry:\n",
|
||||
" %local = getelementptr float, ptr addrspace(3) %scratch, i64 0\n",
|
||||
" store float 0.000000e+00, ptr addrspace(3) %local\n",
|
||||
" call void @write_uint(ptr addrspace(3) %scratch)\n",
|
||||
" call void @write_float(ptr addrspace(3) %scratch)\n",
|
||||
" ret void\n",
|
||||
"}\n",
|
||||
"define void @write_uint(ptr addrspace(3) %p) {\n",
|
||||
"entry:\n",
|
||||
" %slot = getelementptr i32, ptr addrspace(3) %p, i64 0\n",
|
||||
" store i32 1, ptr addrspace(3) %slot\n",
|
||||
" ret void\n",
|
||||
"}\n",
|
||||
"define void @write_float(ptr addrspace(3) %p) {\n",
|
||||
"entry:\n",
|
||||
" %slot = getelementptr float, ptr addrspace(3) %p, i64 0\n",
|
||||
" store float 1.000000e+00, ptr addrspace(3) %slot\n",
|
||||
" ret void\n",
|
||||
"}\n",
|
||||
"define void @unrelated(ptr addrspace(3) %typed) {\n",
|
||||
"entry:\n",
|
||||
" store float 2.000000e+00, ptr addrspace(3) %typed\n",
|
||||
" ret void\n",
|
||||
"}\n",
|
||||
);
|
||||
let module = LlModule::parse(air).expect("fixture parses");
|
||||
for key in [
|
||||
("entry".to_string(), "%scratch".to_string()),
|
||||
("write_uint".to_string(), "%p".to_string()),
|
||||
("write_float".to_string(), "%p".to_string()),
|
||||
] {
|
||||
assert!(module.raw_buffer_params.contains(&key));
|
||||
assert!(module.call_connected_raw_params.contains(&key));
|
||||
}
|
||||
assert!(!module
|
||||
.raw_buffer_params
|
||||
.contains(&("unrelated".to_string(), "%typed".to_string())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn helper_raw_mark_reaches_entry_through_byte_gep_alias() {
|
||||
// The reverse direction matters too: helper-local byte reinterpretation must make the entry
|
||||
@@ -1170,6 +1558,23 @@ mod pointee_inference_tests {
|
||||
assert!(parsed(air).ptr_pointees.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_store_value_becomes_pointer_param_pointee() {
|
||||
let air = concat!(
|
||||
"define void @k(ptr addrspace(1) %out, float %value) {\n",
|
||||
"entry:\n",
|
||||
" store float %value, ptr addrspace(1) %out, align 4\n",
|
||||
" ret void\n",
|
||||
"}\n",
|
||||
);
|
||||
assert_eq!(
|
||||
parsed(air)
|
||||
.ptr_pointees
|
||||
.get(&("k".to_string(), "%out".to_string())),
|
||||
Some(&LlType::Float)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn primitive_metadata_seeds_cross_buffer_phi_roots_without_direct_geps() {
|
||||
// The only float GEP is below a phi joining distinct buffers, so the single-root GEP pass
|
||||
|
||||
@@ -80,7 +80,7 @@ fn eligible_ordinary_helper(
|
||||
instruction.opcode == "alloca"
|
||||
|| (is_call_opcode(&instruction.opcode)
|
||||
&& instruction
|
||||
.call
|
||||
.call()
|
||||
.as_ref()
|
||||
.is_none_or(|call| bodied_functions.contains(&call.callee)))
|
||||
})
|
||||
@@ -134,7 +134,7 @@ fn reachable_functions(
|
||||
continue;
|
||||
};
|
||||
for instruction in function.carrier_insts() {
|
||||
let Some(call) = instruction.call.as_ref() else {
|
||||
let Some(call) = instruction.call().as_ref() else {
|
||||
continue;
|
||||
};
|
||||
if !is_residual_intrinsic(&call.callee)
|
||||
@@ -300,7 +300,7 @@ fn function_type_capabilities(
|
||||
TirOperand::Unresolved => {}
|
||||
}
|
||||
}
|
||||
if let Some(call) = &instruction.call {
|
||||
if let Some(call) = &instruction.call() {
|
||||
collect_type_capabilities(&call.ret, aliases, &mut visiting, &mut capabilities);
|
||||
for argument in &call.args {
|
||||
collect_type_capabilities(
|
||||
@@ -317,7 +317,7 @@ fn function_type_capabilities(
|
||||
);
|
||||
}
|
||||
}
|
||||
if let Some(gep) = &instruction.gep {
|
||||
if let Some(gep) = &instruction.gep() {
|
||||
collect_type_capabilities(
|
||||
&gep.source_ty,
|
||||
aliases,
|
||||
@@ -401,7 +401,7 @@ impl LlModule {
|
||||
for function in &self.functions {
|
||||
for instruction in function.carrier_insts() {
|
||||
if let (Some(result), Some(allocated)) =
|
||||
(&instruction.result, &instruction.alloca_ty)
|
||||
(&instruction.result, &instruction.alloca_ty())
|
||||
{
|
||||
source_value_pointees
|
||||
.insert((function.name.clone(), result.clone()), allocated.clone());
|
||||
@@ -434,7 +434,7 @@ impl LlModule {
|
||||
if !is_call_opcode(&instruction.opcode) {
|
||||
return None;
|
||||
}
|
||||
let call = instruction.call.as_ref()?;
|
||||
let call = instruction.call().as_ref()?;
|
||||
let helper = helpers.get(&call.callee)?.clone();
|
||||
if call.args.len() != helper.params.len() {
|
||||
return None;
|
||||
@@ -590,7 +590,7 @@ impl LlModule {
|
||||
}
|
||||
|
||||
let inserted = typed.insts.len();
|
||||
let replacement = typed.insts.drain(..);
|
||||
let replacement = typed.insts.clone();
|
||||
self.functions[function_index].blocks[block_index]
|
||||
.typed_mut()
|
||||
.expect("call site came from a typed block")
|
||||
|
||||
@@ -16,7 +16,7 @@ fn function<'a>(module: &'a LlModule, name: &str) -> &'a LlFunction {
|
||||
fn call_names(function: &LlFunction) -> Vec<&str> {
|
||||
function
|
||||
.carrier_insts()
|
||||
.filter_map(|instruction| instruction.call.as_ref())
|
||||
.filter_map(|instruction| instruction.call().as_ref())
|
||||
.map(|call| call.callee.as_str())
|
||||
.collect()
|
||||
}
|
||||
@@ -82,7 +82,7 @@ declare float @air.sqrt(float)
|
||||
.carrier_insts()
|
||||
.find(|instruction| {
|
||||
instruction
|
||||
.call
|
||||
.call()
|
||||
.as_ref()
|
||||
.is_some_and(|call| call.callee == "air.sqrt")
|
||||
})
|
||||
|
||||
+58
-40
@@ -47,29 +47,48 @@ impl LlModule {
|
||||
let ray_lowered = crate::native::ray_intersection::lower_callback_free_triangle_queries(ll);
|
||||
let ll = ray_lowered.as_deref().unwrap_or(ll);
|
||||
let mut types = HashMap::new();
|
||||
let lines: Vec<&str> = ll.lines().collect();
|
||||
let mut functions = Vec::new();
|
||||
// Each function's raw body lines, parallel to `functions`, held only until the carriers are
|
||||
// lowered below; `LlFunction` itself has no `Vec<String>` body (T5 — text is read once, here).
|
||||
let mut function_bodies: Vec<Vec<String>> = Vec::new();
|
||||
let mut declarations = Vec::new();
|
||||
let mut globals = Vec::new();
|
||||
let mut i = 0;
|
||||
while i < lines.len() {
|
||||
let line = strip_comment(lines[i]).trim();
|
||||
// Named types may appear after a function that uses them. Collect the compact type table in
|
||||
// a first pass, then lower each function body directly into its typed carrier in a streaming
|
||||
// second pass. Only the current function's borrowed body lines are indexed; a generated module
|
||||
// never retains a whole-module line table beside all of its typed carriers.
|
||||
for raw_line in ll.lines() {
|
||||
let line = strip_comment(raw_line).trim();
|
||||
if line.starts_with('%') && line.contains(" = type ") {
|
||||
let (name, body) = line
|
||||
.split_once(" = type ")
|
||||
.ok_or_else(|| format!("native emitter: malformed type alias: {line}"))?;
|
||||
types.insert(name.trim().to_string(), parse_type(body.trim())?);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
let mut functions = Vec::new();
|
||||
let mut declarations = Vec::new();
|
||||
let mut globals = Vec::new();
|
||||
let mut lines = ll.lines();
|
||||
while let Some(raw_line) = lines.next() {
|
||||
let line = strip_comment(raw_line).trim();
|
||||
if line.starts_with('%') && line.contains(" = type ") {
|
||||
continue;
|
||||
}
|
||||
if line.starts_with("define ") {
|
||||
let (func, body, next) = parse_function(&lines, i)?;
|
||||
let mut func = parse_function_header(line)?;
|
||||
let mut body = Vec::new();
|
||||
let mut terminated = false;
|
||||
for body_line in lines.by_ref() {
|
||||
if strip_comment(body_line).trim() == "}" {
|
||||
terminated = true;
|
||||
break;
|
||||
}
|
||||
body.push(body_line);
|
||||
}
|
||||
if !terminated {
|
||||
return Err(format!(
|
||||
"native emitter: unterminated function {}",
|
||||
func.name
|
||||
));
|
||||
}
|
||||
let entry = crate::native::cfg::implicit_entry_block_name(&func);
|
||||
func.blocks = crate::native::cfg::split_source_body_blocks(&body, entry, &types)?;
|
||||
functions.push(func);
|
||||
function_bodies.push(body);
|
||||
i = next;
|
||||
continue;
|
||||
}
|
||||
if line.starts_with("declare ") {
|
||||
@@ -77,44 +96,21 @@ impl LlModule {
|
||||
if !is_ignored_intrinsic(&decl.name) {
|
||||
declarations.push(decl);
|
||||
}
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if is_ignored_global(line) {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if line.starts_with('@') && (line.contains(" constant ") || line.contains(" global ")) {
|
||||
globals.push(parse_global(line)?);
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
if functions.is_empty() {
|
||||
return Err("native emitter: no function definitions found".into());
|
||||
}
|
||||
// Parse-once typed IR: lower every function's blocks to carriers now that the module type
|
||||
// table is complete, BEFORE any inference reads a body. This is the SAME `split_body_blocks`
|
||||
// call the emitter runs per function (same immutable `body`, same module `types`); the
|
||||
// carriers do not depend on any inference output, so hoisting the population to the top of
|
||||
// `parse_inner` is byte-neutral. Every body reader — the free-function imageblock scans
|
||||
// below, the parse-time pointee/raw-buffer inferences, the CFG diagnostics, and the emitter's
|
||||
// global-reinterpret scans — reads `f.blocks` (the F-track / T5): `LlFunction.body` is deleted
|
||||
// and the LLVM-IR text is read exactly once (here, at parse).
|
||||
let block_lists: Vec<Vec<crate::native::cfg::BodyBlock>> = functions
|
||||
.iter()
|
||||
.zip(&function_bodies)
|
||||
.map(|(f, body)| {
|
||||
let entry = crate::native::cfg::implicit_entry_block_name(f);
|
||||
crate::native::cfg::split_body_blocks(body, entry, &types)
|
||||
})
|
||||
.collect();
|
||||
for (f, blocks) in functions.iter_mut().zip(block_lists) {
|
||||
f.blocks = blocks;
|
||||
}
|
||||
drop(function_bodies);
|
||||
drop(lines);
|
||||
// Every body reader below consumes the typed carriers. Each borrowed function-body index was
|
||||
// released immediately after that function was lowered.
|
||||
let entry_functions = entry_name
|
||||
.map(|name| HashSet::from([name.to_string()]))
|
||||
.unwrap_or_else(|| infer_entry_functions(ll));
|
||||
@@ -122,6 +118,10 @@ impl LlModule {
|
||||
infer_metadata_byte_buffer_params(kern, entry_name, &functions);
|
||||
let metadata_data_buffer_params =
|
||||
infer_metadata_data_buffer_params(kern, entry_name, &functions);
|
||||
let metadata_primitive_buffer_pointees =
|
||||
infer_metadata_primitive_buffer_pointees(kern, entry_name, &functions);
|
||||
let metadata_fc_buffer_locations =
|
||||
infer_metadata_fc_buffer_locations(kern, entry_name, &functions);
|
||||
let imageblock_dimensions = infer_apv_imageblock_dimensions(ll);
|
||||
let cross_coordinate_imageblock =
|
||||
infer_cross_coordinate_imageblock(&functions, &entry_functions);
|
||||
@@ -159,7 +159,7 @@ impl LlModule {
|
||||
functions,
|
||||
declarations,
|
||||
globals,
|
||||
static_init_int_globals: meta::static_init_foldable_int_global_values(ll),
|
||||
static_init_globals: meta::static_init_foldable_global_values(ll),
|
||||
entry_name: entry_name.map(str::to_string),
|
||||
preinlined_static_initializers: HashSet::new(),
|
||||
preinlined_helper_pointer_loads: HashSet::new(),
|
||||
@@ -175,7 +175,11 @@ impl LlModule {
|
||||
metadata_pointee_sizes: HashMap::new(),
|
||||
metadata_byte_buffer_params,
|
||||
metadata_data_buffer_params,
|
||||
metadata_primitive_buffer_pointees,
|
||||
metadata_fc_buffer_locations,
|
||||
raw_buffer_params: HashSet::new(),
|
||||
call_connected_raw_params: HashSet::new(),
|
||||
param_connected_raw_params: HashSet::new(),
|
||||
};
|
||||
module.infer_metadata_buffer_pointees(kern, entry_name);
|
||||
module.infer_pointer_pointees();
|
||||
@@ -184,7 +188,9 @@ impl LlModule {
|
||||
}
|
||||
module.infer_local_alloca_pointees();
|
||||
module.infer_raw_buffer_params();
|
||||
module.infer_call_connected_raw_buffer_params();
|
||||
module.propagate_raw_buffer_params();
|
||||
module.propagate_data_buffer_params();
|
||||
Ok(module)
|
||||
}
|
||||
}
|
||||
@@ -231,6 +237,18 @@ entry:
|
||||
threaded.metadata_data_buffer_params,
|
||||
reparsed.metadata_data_buffer_params
|
||||
);
|
||||
assert_eq!(
|
||||
threaded.metadata_primitive_buffer_pointees,
|
||||
reparsed.metadata_primitive_buffer_pointees
|
||||
);
|
||||
assert_eq!(
|
||||
threaded.call_connected_raw_params,
|
||||
reparsed.call_connected_raw_params
|
||||
);
|
||||
assert_eq!(
|
||||
threaded.param_connected_raw_params,
|
||||
reparsed.param_connected_raw_params
|
||||
);
|
||||
assert_eq!(
|
||||
threaded.imageblock_data_pointee,
|
||||
reparsed.imageblock_data_pointee
|
||||
|
||||
Loaded 100 of 478 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user