Skip to content

perf(mir-lower): type an enum's unclaimed bytes as one integer - #675

Merged
nihalpasham merged 1 commit into
NVIDIA:mainfrom
vyncint:perf/enum-filler-scalar
Aug 6, 2026
Merged

nihalpasham merged 1 commit into
NVIDIA:mainfrom
vyncint:perf/enum-filler-scalar

Conversation

@vyncint

@vyncint vyncint commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

Problem

Option<&[T]> lowers to { ptr, [8 x i8] }. The niche carrier claims the pointer, the slice length falls into an 8-byte filler, and that filler is typed as a byte array — eight separate SSA values.

So every construct, merge and destructure of the payload becomes eight i8 insertvalue/extractvalue pairs and eight phi i8, plus an alloca round trip purely to retype {ptr, i64} into {ptr, [8 x i8]}:

; from vectorization.ll; symbol abridged, chain elided at the ellipses
define { ptr, [8 x i8] } @as_vectors(ptr %v0, i64 %v1) {
  ...
  %v41 = alloca { ptr, [8 x i8] }, align 8
  store { ptr, [8 x i8] } undef, ptr %v41, align 8
  %v42 = getelementptr inbounds i8, ptr %v41, i64 0
  store { ptr, i64 } %v40, ptr %v42, align 8   ; store type != load type
  %v43 = load { ptr, [8 x i8] }, ptr %v41, align 8
  %v45 = extractvalue { ptr, [8 x i8] } %v43, 1, 0
  %v46 = extractvalue { ptr, [8 x i8] } %v43, 1, 1
  ...                                    1, 2 … 1, 6
  %v52 = extractvalue { ptr, [8 x i8] } %v43, 1, 7
  %v81 = phi i8 [ %v45, %bb5 ], ...          ; ×8, at every merge

[8 x i8] occurs 134 times in the NVVM IR of one small example.

The pointer rides through that same aggregate, so InferAddressSpaces can no longer prove it global and the access falls out of the global window into the generic one. In PTX, the width is right and the address space is not:

st.local.v2.b32  [%rd34+8], {%r33, %r29}   ; 32-byte .local depot
ld.local.b64     %rd5,  [%rd34+8]
ld.v2.b64        {%rd54, %rd55}, [%rd53]   ; generic, not .global
st.v2.b64        [%rd56], {%rd54, %rd55}

This is #657. That issue's open question was whether the fix belonged in lowering or in the example's expectation, and it named as_mut_ptr and from_raw_parts as the suspects. It belongs in lowering, and neither suspect is involved — it is the filler type.

Reproduction

cargo oxide run vectorization     # the f32x4_view_copy assertion fails

Fix

Emit one integer for the filler where doing so moves nothing:

  • width 2, 4 or 8 bytes, so the integer is byte-faithful (a multiple of 8 bits, no padding of its own). 16 is deliberately excluded: i128 is legal LLVM but lowers to register pairs on NVPTX, so widening that far trades one win for another cost and wants its own measurement.
  • offset a multiple of the width, so LLVM inserts no gap ahead of the field and every later field keeps its byte offset.
  • width no greater than the enum's alignment, or the struct's natural alignment would rise above rustc's.

Anything else keeps [N x i8] — the 7-byte and 3-byte fillers in the existing tests are untouched.

The filler is a vehicle, not a claim: a payload with no typed slot round-trips through memory as a whole aggregate, and both ends of that round trip are byte-exact, so nothing ever reads the filler field-wise. build_enum_slot_map's existing size and alignment assertions are hard errors rather than debug checks, and they backstop all three conditions.

{ ptr, [8 x i8] } becomes { ptr, i64 }, which makes the store and load types match, so the alloca round trip folds away entirely.

Verification on hardware

NVIDIA A10G (sm_86), 23028 MiB, driver 595.71.05, nvcc 13.2 — cargo oxide run vectorization

The example inspects the PTX it just launched and asserts the shape, so this is the #657 assertion itself, executing:

f32x4       float4           16    16  ld.global.v2.b64       yes
f64x2       double2          16    16  ld.global.v2.b64       yes
f64x4       double4          32    16  ld.global.v2.b64       yes
f64x4_a32   double4_32a      32    32  ld.global.v2.b64       yes
f32x4_view_copy: ld.global.v2.b64 	{%rd42, %rd43}, [%rd41];
f32x4_view_copy: st.global.v2.b64 	[%rd44], {%rd42, %rd43};

✓ SUCCESS: 26 CUDA vector types -- layout, copy, and codegen all correct

--- result ---
exit code  : 0

Before this change the same two lines read !! f32x4_view_copy has no 128-bit ld.global vector op / ... st.global ... and the example exited 1.

The full 185-example suite was also run on this device: 184 pass. The one failure, future_apis, is pre-existing and unrelated — its PTX declares .target sm_100 while the device is sm_86, so the driver rejects the module before a kernel runs (DriverError(218)). I confirmed that by rebuilding this same tree with the change reverted and observing the identical failure, rather than inferring it. Worth its own issue; nothing in filler lowering can set .target.

Measured effect

A flat-buffer f32x4 copy taken through vector::as_vectors, against the equivalent hand-written direct path over the same device allocation (reinterpreted between phases, so neither can win on placement). 128 MiB read + 128 MiB written per launch, 100 timed launches after 20 warmup:

kernel µs before µs after GB/s before GB/s after
copy_view 810.5 552.8 331.2 485.6
copy_direct (control) 552.4 552.5 486.0 485.9
copy_scalar (control) 546.4 546.7 491.3 491.0

The view path goes from 68.2% of the direct path to 99.9% of it — +46.6% bandwidth, 1.47× faster. Both controls move by under 0.06%, which is what makes the copy_view row meaningful. 486 GB/s is ~81% of the A10G's 600 GB/s spec peak, the ordinary achieved fraction for a read-plus-write streaming copy.

Codegen for that kernel:

metric before after
[8 x i8] in NVVM IR 134 0
PTX instructions 149 68
prmt byte permutes 26 0
local-memory accesses 4 0
ptxas stack frame 32 B 0 B
ld/st.global.v* 0 2
generic ld/st.v* 2 0
registers (ptxas) 17 20

Three more registers is the cost of keeping the value in registers instead of a stack frame; ptxas reports zero spill stores and zero spill loads either way, and at 20 registers the kernel still reaches full occupancy on sm_86.

The measurement harness is a small example (view_bandwidth) that I have kept out of this PR to keep the diff to the fix — vectorization already guards the codegen shape as an in-tree regression test. Happy to send it as a follow-up if a standing benchmark is wanted.

Test expectations

Four mir-lower unit tests pinned the old lowered struct type as a golden expectation and are updated. In each, that same test's own size-and-alignment assertion still passes unchanged, which is the invariant that matters: the bytes did not move.

One is worth calling out. In Option<(i64, &T)> the storage becomes {i64, ptr} — the same interned type as its own payload tuple — so nested_pointer_niche_tuple_construct_extract_and_discriminant_lower could no longer separate the payload store from the enum spill by type, and its two type-filtered counts go from 1 to 2. The property that matters (whole-aggregate moves, never field-by-field) stays pinned by the total store/load counts asserted immediately above. If you would rather that test keep its discrimination, I am happy to restructure it to assert that no field-typed store targets the enum.

Upstream gates

All run on the A10G box against this branch, all green:

gate result
cargo fmt --check pass
cargo clippy --all-targets --lib --tests -- -D warnings pass
cargo test -p cuda-host -p cuda-macros -p llvm-export -p dialect-mir -p dialect-nvvm -p mir-lower --lib --tests pass
RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --workspace pass
cargo test --doc --workspace --exclude cuda-bindings pass
scripts/smoketest.sh (all 185 examples) 184 pass, 1 pre-existing failure described above

-p mir-lower is not in the CI unit-test set; I added it because it is the crate this change touches. Its 165 tests pass.

No error* example changed, so STATUS.md and check-error-example-status.sh are not implicated.

Not in scope

The union tail filler and ordinary struct padding have the same shape and would take the same widening, but I have no measurement for either and folding them in would turn a contained diff into a risky one. Happy to follow up.

Closes #657

`Option<&[T]>` lowered to `{ ptr, [8 x i8] }`. The niche carrier claims the
pointer, the slice length falls into an 8-byte filler, and that filler was
typed as a byte array -- eight separate SSA values. Every construct, merge and
destructure of the payload therefore became eight `i8` insertvalue/extractvalue
pairs and eight `phi i8`, plus an `alloca` round trip purely to retype
`{ptr, i64}` into `{ptr, [8 x i8]}`. `[8 x i8]` occurred 134 times in the NVVM
IR of one small example.

The pointer rides through that same aggregate, so `InferAddressSpaces` could no
longer prove it global and the access fell out of the global window into the
generic one. That is NVIDIA#657, whose open question was whether the fix belonged in
lowering or in the example's expectation. It belongs in lowering, and neither
`as_mut_ptr` nor `from_raw_parts` -- the two suspects named there -- is
involved.

Emit one integer for the filler where doing so moves nothing: width 2, 4 or 8
bytes, offset a multiple of the width, width no greater than the enum's
alignment. Anything else keeps `[N x i8]`. The filler is a vehicle rather than
a claim: a payload with no typed slot round-trips through memory as a whole
aggregate, byte-exact at both ends. `build_enum_slot_map`'s existing size and
alignment assertions are hard errors and backstop all three conditions.

Measured on an A10G (sm_86) with a flat-buffer f32x4 copy taken through
`vector::as_vectors`, 128 MiB in and 128 MiB out per launch, 100 timed launches
after 20 warmup:

    copy_view     810.5 us -> 552.8 us    331.2 GB/s -> 485.6 GB/s
    copy_direct   552.4 us -> 552.5 us    (control, unchanged)
    copy_scalar   546.4 us -> 546.7 us    (control, unchanged)

The view path goes from 68.2% of the equivalent hand-written direct path to
99.9% of it. For that kernel the PTX falls from 149 to 68 instructions, the 26
`prmt` byte permutes and all four local-memory accesses disappear, ptxas
reports no stack frame where it previously reported 32 bytes, and the accesses
become `ld/st.global.v2.b64`.

Four unit tests pinned the old struct type as a golden expectation and are
updated. Each one's own size and alignment assertion still passes unchanged,
which is the invariant that matters. In `Option<(i64, &T)>` the storage becomes
`{i64, ptr}` -- the same interned type as its payload tuple -- so a test that
identified the payload store by its type can no longer separate it from the
enum spill; the whole-aggregate property stays pinned by the total store and
load counts asserted just above it.

Closes NVIDIA#657

Signed-off-by: Vyncint Ng <[email protected]>
@nihalpasham nihalpasham added perf Performance of generated code or of the compiler itself IR-lowering Lowering between dialects (dialect-mir to LLVM dialect) labels Aug 6, 2026
@nihalpasham

Copy link
Copy Markdown
Collaborator

The root-cause fix #657 asked for,

Verified end to end on an RTX 5090 (sm_120):

-cargo oxide run vectorization: f32x4_view_copy now emits ld.global.v2.b64 / st.global.v2.b64 and the example prints SUCCESS for all 26 vector types; before this change the same check failed with the access stuck in the generic window.

  • re-derived the layout-neutrality argument independently: the three guard conditions (width in {2,4,8}, width-aligned start offset, width <= enum alignment) are exactly what keeps LLVM's natural layout byte-identical to the old byte array, and the existing size/alignment hard checks turn any residual drift into a compile error, never wrong PTX. {ptr, i64} is literally the shape rustc's own LLVM backend gives Option<&[T]>.
  • cargo test -p mir-lower green.

Closes #657.

Follow-ups:

  • the weakened type-discrimination in the nested-niche test is fine as-is;
  • the restructure you offered is welcome as a follow-up.

@vyncint

vyncint commented Aug 6, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for verifying on the 5090 — good to have the sm_120 end of the range covered, since I could only reach sm_86.

The restructure is up as #678. It is stacked on this branch (both touch the same lines of aggregate.rs), so review only the second commit there; I will rebase it to a single commit once this lands.

The short version: instead of counting tuple-typed accesses, it asserts that no store or load moves a bare i64 or a bare ptr — which is what a decomposing lowering would emit — plus two non-vacuity checks that the whole tuple really is moved. I ran it on both sides of the widening to confirm it is insensitive to the coincidence that broke the counting form:

stores loads
at upstream/main {[8 x i8],ptr}, {i64,ptr}, {[8 x i8],ptr} {[8 x i8],ptr}, {i64,ptr}
with this PR {i64,ptr} ×3 {i64,ptr} ×2

Field-typed count is zero in both; only the tuple-typed counts move.

vyncint added a commit to vyncint/cuda-oxide that referenced this pull request Aug 6, 2026
The comment described the generic-window fallback in the present tense, which
was accurate while NVIDIA#657 was open. NVIDIA#675 fixes it at the root, so on a tree with
that change the check passes and this branch is never taken. Left as-is the
comment would assert, in-tree, a pessimization that no longer happens.

Reword to describe what a *future* failure most likely means rather than what
the compiler currently does, so it stays true whichever order this and NVIDIA#675
land in. The printed message is unchanged: naming the address space rather than
the width is still the right thing to say when the check fires.

Refs NVIDIA#657, NVIDIA#675

Signed-off-by: Vyncint Ng <[email protected]>
@nihalpasham
nihalpasham merged commit 456d534 into NVIDIA:main Aug 6, 2026
34 checks passed
nihalpasham pushed a commit that referenced this pull request Aug 6, 2026
…#669)

* docs(examples): vectorization misdescribes what f32x4_view_copy emits

The failure message says the kernel "has no 128-bit ld.global vector op",
which reads as though the transaction had been split into scalars. SASS on
sm_86 says otherwise:

  f32x4           LDG.E.128 x1, STG.E.128 x1                      (2 ops)
  f32x4_view_copy LD.E.128 x1, ST.E.128 x1, LDL.64 x2, STL.64 x2  (6 ops)

The 128-bit access is there. What is missing is the *global* window: the view
path addresses through the generic one and pays four local-memory accesses,
plus a chain of PRMT byte permutes, on the way.

Message and comment corrected to say that. The check itself is unchanged and
still fails, because the pessimization it detects is real -- only its
description was wrong.

Refs #657

Signed-off-by: Vyncint Ng <[email protected]>

* docs(examples): frame the view-copy message as a regression diagnostic

The comment described the generic-window fallback in the present tense, which
was accurate while #657 was open. #675 fixes it at the root, so on a tree with
that change the check passes and this branch is never taken. Left as-is the
comment would assert, in-tree, a pessimization that no longer happens.

Reword to describe what a *future* failure most likely means rather than what
the compiler currently does, so it stays true whichever order this and #675
land in. The printed message is unchanged: naming the address space rather than
the width is still the right thing to say when the check fires.

Refs #657, #675

Signed-off-by: Vyncint Ng <[email protected]>

---------

Signed-off-by: Vyncint Ng <[email protected]>
vyncint added a commit to vyncint/cuda-oxide that referenced this pull request Aug 6, 2026
The nested-niche test pinned its central property -- that an enum payload
moves as one unit, never field by field -- by counting accesses whose type
equalled the lowered payload tuple. That count is not a property of the
lowering under test. It depends on whether the enum's physical storage type
happens to coincide with the payload's.

For `Option<(i64, &T)>` it now does. The niche carrier claims the pointer at
byte 8, the 8 bytes below it lower to one `i64` filler, and the storage is
therefore `{i64, ptr}` -- the same interned type as the payload tuple. Every
whole-aggregate access carries that type, so the expected counts had to move
from 1 and 1 to 3 and 2, for a reason with nothing to do with what the test
checks. A type filter also stopped being able to tell the payload write from
the enum spill.

Assert the property directly instead. A lowering that decomposed the payload
is recognisable by what it emits: traffic in the tuple's *field* types. So
require that no store or load moves a bare `i64` or a bare `ptr`, and add two
non-vacuity checks that the complete tuple really is moved at least once each
way -- without those, a lowering that emitted no payload traffic at all would
pass.

Measured on both sides of the filler widening, the field-typed count is zero
either way while the tuple-typed counts differ:

    before the widening    stores: {[8 x i8],ptr} {i64,ptr} {[8 x i8],ptr}
                           loads:  {[8 x i8],ptr} {i64,ptr}
    after the widening     stores: {i64,ptr} x3
                           loads:  {i64,ptr} x2

The new assertion holds unchanged across that, which is the point of making
it. Verified by running the test at `upstream/main` with only this change
applied, as well as on top of the widening.

Refs NVIDIA#675

Signed-off-by: Vyncint Ng <[email protected]>
vyncint added a commit to vyncint/cuda-oxide that referenced this pull request Aug 6, 2026
The nested-niche test pinned its central property -- that an enum payload
moves as one unit, never field by field -- by counting accesses whose type
equalled the lowered payload tuple. That count is not a property of the
lowering under test. It depends on whether the enum's physical storage type
happens to coincide with the payload's.

For `Option<(i64, &T)>` it now does. The niche carrier claims the pointer at
byte 8, the 8 bytes below it lower to one `i64` filler, and the storage is
therefore `{i64, ptr}` -- the same interned type as the payload tuple. Every
whole-aggregate access carries that type, so the expected counts had to move
from 1 and 1 to 3 and 2, for a reason with nothing to do with what the test
checks. A type filter also stopped being able to tell the payload write from
the enum spill.

Assert the property directly instead. A lowering that decomposed the payload
is recognisable by what it emits: traffic in the tuple's *field* types. So
require that no store or load moves a bare `i64` or a bare `ptr`, and add two
non-vacuity checks that the complete tuple really is moved at least once each
way -- without those, a lowering that emitted no payload traffic at all would
pass.

Measured on both sides of the filler widening, the field-typed count is zero
either way while the tuple-typed counts differ:

    before the widening    stores: {[8 x i8],ptr} {i64,ptr} {[8 x i8],ptr}
                           loads:  {[8 x i8],ptr} {i64,ptr}
    after the widening     stores: {i64,ptr} x3
                           loads:  {i64,ptr} x2

The new assertion holds unchanged across that, which is the point of making
it. Verified by running the test at `upstream/main` with only this change
applied, as well as on top of the widening.

Refs NVIDIA#675

Signed-off-by: Vyncint Ng <[email protected]>
nihalpasham pushed a commit that referenced this pull request Aug 7, 2026
#680)

The nested-niche test pinned its central property -- that an enum payload
moves as one unit, never field by field -- by counting accesses whose type
equalled the lowered payload tuple. That count is not a property of the
lowering under test. It depends on whether the enum's physical storage type
happens to coincide with the payload's.

For `Option<(i64, &T)>` it now does. The niche carrier claims the pointer at
byte 8, the 8 bytes below it lower to one `i64` filler, and the storage is
therefore `{i64, ptr}` -- the same interned type as the payload tuple. Every
whole-aggregate access carries that type, so the expected counts had to move
from 1 and 1 to 3 and 2, for a reason with nothing to do with what the test
checks. A type filter also stopped being able to tell the payload write from
the enum spill.

Assert the property directly instead. A lowering that decomposed the payload
is recognisable by what it emits: traffic in the tuple's *field* types. So
require that no store or load moves a bare `i64` or a bare `ptr`, and add two
non-vacuity checks that the complete tuple really is moved at least once each
way -- without those, a lowering that emitted no payload traffic at all would
pass.

Measured on both sides of the filler widening, the field-typed count is zero
either way while the tuple-typed counts differ:

    before the widening    stores: {[8 x i8],ptr} {i64,ptr} {[8 x i8],ptr}
                           loads:  {[8 x i8],ptr} {i64,ptr}
    after the widening     stores: {i64,ptr} x3
                           loads:  {i64,ptr} x2

The new assertion holds unchanged across that, which is the point of making
it. Verified by running the test at `upstream/main` with only this change
applied, as well as on top of the widening.

Refs #675

Signed-off-by: Vyncint Ng <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

IR-lowering Lowering between dialects (dialect-mir to LLVM dialect) perf Performance of generated code or of the compiler itself

Projects

None yet

Development

Successfully merging this pull request may close these issues.

vectorization: f32x4_view_copy accesses lower to generic space, not .global

2 participants