Skip to content

perf(mir-importer): address a tuple field in place instead of copying its array - #715

Closed
vyncint wants to merge 1 commit into
NVIDIA:mainfrom
vyncint:perf/array-element-field-projection
Closed

vyncint wants to merge 1 commit into
NVIDIA:mainfrom
vyncint:perf/array-element-field-projection

Conversation

@vyncint

@vyncint vyncint commented Aug 8, 2026

Copy link
Copy Markdown
Contributor

Closes #693.

Summary

PAIRS[i].1 — one field of a tuple array element — loaded the whole array as
a value and projected into it, so every such read first spilled the entire table
into a fresh per-thread stack slot. A second field read spilled it again.

The reason was narrow, and place_read_fallbacks recorded it:

tuple field reads, because mir.field_addr currently verifies struct pointees
only while value-space mir.extract_field supports tuples.

A tuple carries the same layout facts a struct does — declaration order, memory
order, per-field offsets, total size — and StructLayoutInfo::of_tuple already
existed to hand them over. So:

  • mir.field_addr accepts a tuple pointee;
  • convert_field_addr builds its slot map through that same StructLayoutInfo,
    so the field's LLVM slot comes out of the walk that built the type — which is
    what keeps a reordered tuple like (u8, u32, u64) addressing correctly;
  • the read classifier lets a tuple field read walk to its address.

Measured

A10G, from the evidence logs' nvidia-smi block:

name, compute_cap, driver_version
NVIDIA A10G, 8.6, 595.71.05

1048576 threads x 64 divergent lookups into a 256-entry (u8, u32) table, 10
timed launches after 3 warmup. Every kernel bit-correct against a host reference
in both runs.

Before (.gpu-evidence/20260808T000635Z.log) / after
(.gpu-evidence/20260808T000907Z.log):

kernel reads before after speedup
tuple_one_field PAIRS[i].1 1 127 170 us 479 670 us 2.35x
tuple_two_fields let (a,b)=PAIRS[i] 2 139 199 us 485 414 us 4.41x
scalar_control CODES[i] 46.3 us 46.3 us 1.00x

scalar_control reads a plain [u32; N] table over the same index stream and
came back bit-identical at 46.3 us in both runs, so this is a controlled
comparison rather than two unrelated timings.

PTX:

kernel before after
tuple_one_field 567 instrs, 2048 B depot, 512 st.local 565, 2048, 512
tuple_two_fields 1084 instrs, 4096 B depot, 1024 st.local 567, 2048, 512
scalar_control 70, 0, 0 70, 0, 0

Two things improve, which is why tuple_one_field moves at an essentially
unchanged instruction count: tuple_two_fields drops from two whole-array spills
to one, and both kernels now read only the field they want per loop iteration
instead of loading the whole element and extracting.

What is deliberately left

The table's own materialization: the constant is still built element by element
into the one remaining slot. That is the other half, and it is not independent —
#694 excludes tuple elements from immutable-global promotion because this copy
dominated
, which I measured there (promoting alone changed nothing).

With both in place the depot goes entirely: the same two kernels compile to 42
and 44 PTX instructions with no local memory at all
, reading through
ld.global.nc. I verified that composition locally before deciding to split it.
It belongs on top of #694 rather than here, since it edits that PR's gate and
would need several array_constants code-shape assertions rewritten in the same
change.

Over-aligned tuples stay on the value path

A zero-sized field can carry repr(align(N)), raising the ABI alignment above
anything the LLVM storage type expresses — (Align32, u8) lowers to
{ i8, [31 x i8] }, naturally align-1. The address path states no alignment on
its final load, so lowering falls back to the field's natural alignment and
quietly under-states the ABI.

array_constants' own guard caught exactly this, which is how the case was found:
it rejects any align 1 operation in the over-aligned kernel, and my first cut
introduced load i8, ptr %v15, align 1. That load is sound on its own — a u8
needs no alignment — but the guard is right that the address path cannot restate
what the ABI recorded, so such tuples keep the value path, which moves the whole
aggregate at its recorded alignment. Making the address path carry alignment
would be the better fix and is a separate piece of work.

Validation

Local, all clean:

cargo fmt --check
cargo clippy --all-targets --lib --tests -- -D warnings
cargo test -p mir-lower -p llvm-export -p dialect-mir -p dialect-nvvm \
           -p mir-importer -p cuda-oxide-codegen --lib --tests    # 18 suites ok
bash crates/rustc-codegen-cuda/examples/array_constants/verify-code-shape.sh

On the A10G — scoped smoketest 15/15, 0 fail (.gpu-evidence/20260808T001138Z.log),
covering every example that reads through tuple/array projections plus controls:

[ 1/15] array_constants     PASS   [ 6/15] index_field_assign        PASS   [11/15] tuple_constant_provenance PASS
[ 2/15] array_index         PASS   [ 7/15] place_read_fallbacks      PASS   [12/15] tuple_field_lookup        PASS
[ 3/15] cast_tests          PASS   [ 8/15] ref_index_projections     PASS   [13/15] uninit_const              PASS
[ 4/15] const_aggregate     PASS   [ 9/15] tma_copy       PASS (skipped)    [14/15] vecadd                    PASS
[ 5/15] enum_array_match    PASS   [10/15] tuple_array_provenance    PASS   [15/15] vectorization             PASS

I scoped rather than swept, to the examples that project through tuples and
arrays plus controls. Happy to run the full 188 if you would rather see it.

Not verified: SASS. nvdisasm is not on the image I used, so the
instruction-level evidence here is PTX only.

Notes

place_read_fallbacks documented tuple field reads as a fallback, which they no
longer are. Its entry now names over-alignment as what keeps a tuple on the value
path; the kernel and its runtime check are unchanged, and it still covers the
cases that genuinely do fall back (enum payload reads, ZSTs).

tuple_field_lookup is sized deliberately small — 1 Mi threads, 10 iterations.
Before this change a single launch of the tuple kernels took over a second, so a
larger benchmark would have made the smoketest sit on it.

… its array

Reading one field of a tuple array element -- `PAIRS[i].1` -- loaded the *whole
array* as a value and projected into it, so every such read first spilled the
entire table into a fresh per-thread stack slot. A second field read spilled it
again. The reason was narrow and recorded in `place_read_fallbacks`:
`mir.field_addr` verified struct pointees only, so the classifier sent every
tuple field read to the value path.

A tuple carries the same layout facts a struct does -- declaration order, memory
order, per-field offsets, total size -- and `StructLayoutInfo::of_tuple` already
existed to hand them over. So `mir.field_addr` now accepts a tuple pointee,
`convert_field_addr` builds its slot map through that same path, and the
classifier lets a tuple field read walk to its address. The field's LLVM slot
comes out of the same walk that built the type, which is what keeps a reordered
tuple like `(u8, u32, u64)` addressing correctly.

An over-aligned tuple stays on the value path. A zero-sized field can carry
`repr(align(N))`, which raises the ABI alignment above anything the LLVM storage
type expresses -- `(Align32, u8)` lowers to `{ i8, [31 x i8] }`, naturally
align-1 -- and the address path states no alignment on its final load, so
lowering would fall back to the field's natural alignment and quietly under-state
it. `array_constants`' own guard catches exactly that, which is how the case was
found.

Measured on an A10G (sm_86, driver 595.71.05), 1048576 threads x 64 divergent
lookups into a 256-entry `(u8, u32)` table, 10 timed launches after 3 warmup.
Every kernel bit-correct against a host reference in both runs:

  kernel              reads                  before        after   speedup
  tuple_one_field     PAIRS[i].1          1127170us     479670us     2.35x
  tuple_two_fields    let (a,b)=PAIRS[i]  2139199us     485414us     4.41x
  scalar_control      CODES[i]                46.3us       46.3us     1.00x

`scalar_control` reads a plain `[u32; N]` table over the same index stream and
came back bit-identical at 46.3us in both runs, so the pair is a controlled
comparison rather than two separate timings.

Two things improve. `tuple_two_fields` goes from two whole-array spills to one
(4096-byte depot to 2048, 1084 PTX instructions to 567), and both kernels now
read only the field they want per iteration instead of the whole element, which
is what moves `tuple_one_field` at unchanged instruction count.

What remains is the table's own materialization: the constant is still built
element by element into that one remaining slot. NVIDIA#694 excludes tuple elements
from immutable-global promotion precisely because this copy dominated, so with
both in place the depot goes entirely -- the same kernels compile to 42 and 44
instructions with no local memory at all. That widening belongs on top of NVIDIA#694
rather than here.

Adds `tuple_field_lookup`, which measures both shapes against the scalar control.
`place_read_fallbacks` documented tuple field reads as a fallback, which they no
longer are; its entry now names over-alignment as what keeps a tuple on the value
path, and its runtime check is unchanged.

Closes NVIDIA#693.

Signed-off-by: Vyncint Ng <[email protected]>
@nihalpasham nihalpasham added perf Performance of generated code or of the compiler itself bug Something isn't working codegen Device code-generation pipeline (Rust MIR to IR to PTX) IR-lowering Lowering between dialects (dialect-mir to LLVM dialect) labels Aug 8, 2026
@vyncint

vyncint commented Aug 8, 2026

Copy link
Copy Markdown
Contributor Author

Ran the full sweep this PR's body offered, on the combined stack (#694 + #715 +
#717 merged onto one branch, since the later ones build on the earlier).

190 / 190 pass, 0 fail, 1218s, A10G (sm_86, driver 595.71.05) —
.gpu-evidence/20260808T080039Z.log:

===== SMOKETEST SUMMARY =====
Pass:    190 / 190
Fail:    0 / 190
Elapsed: 1218s

190 rather than 188 because the stack adds enum_table_lookup and
tuple_field_lookup. Every example this work touches passes:

[  3/190] array_constants          ... PASS
[ 29/190] const_table_lookup       ... PASS
[ 63/190] enum_table_lookup        ... PASS
[131/190] place_read_fallbacks     ... PASS
[175/190] tuple_array_provenance   ... PASS
[177/190] tuple_field_lookup       ... PASS

So the "scoped rather than swept, happy to run the full 188" caveat in the body
is now discharged — no need to take that on trust.

One correction while I am here, in case it matters to review: partway through this
work I quoted a figure of a 64-byte depot / 6 st.local for array_constants.
That came from a stale backend. Forcing a clean rebuild gives 96 bytes and 12
st.local
(from 128 and 24 on main). No number in any PR body was affected —
those all come from box runs that touch crates/*/src/lib.rs first, and I
re-verified under a clean rebuild that tuple_field_lookup is still 70/70/62
instructions with no depot and that array_constants' code-shape guard passes.

Also worth knowing when weighing these: across the 16 pre-existing examples that
could plausibly change, only two actually do — array_constants (depot 128 → 96,
st.local 24 → 12) and tuple_array_provenance (64 → 32). The large speedups are
real but land on lookup-table shapes the current corpus barely exercises, which is
why the two new examples exist.

nihalpasham added a commit to alejandro-soto-franco/cuda-rust that referenced this pull request Aug 8, 2026
The field_addr tuple read path ends in a mir.load that states the
loaded field's natural alignment only. A tuple whose ABI alignment
comes from a zero-byte repr(align(N)) field, such as (Align32, u8),
therefore emitted an align-1 load in the unoptimized LLVM, tripping
the array_constants code-shape guard that keeps over-aligned reads
off that shape.

Gate the read classifier: a tuple field read falls back to the value
path when the tuple carries a field that owns zero bytes while its
recorded ABI alignment exceeds 1. Detection compares byte sizes, not
element counts, recursing through arrays at any nesting depth so a
zero-byte [Align32; 2] cannot slip through on its element count of 2.
Ordinary tuples keep the address path. Gate shape from PR NVIDIA#715
(vyncint), with the byte-size gap closed.
@nihalpasham

Copy link
Copy Markdown
Collaborator

Gist: This is the right fix, but #709 fixed the same gap at the same three compiler layers, was filed first, and came with tests at both stages, so it is the one merging. Closing this as already-fixed

Two notes that matter:

@nihalpasham nihalpasham closed this Aug 8, 2026
@nihalpasham nihalpasham added the already-fixed Resolved on a newer commit or branch; no action needed label Aug 8, 2026
nihalpasham added a commit that referenced this pull request Aug 8, 2026
* perf(mir): address tuple field reads instead of copying the whole array

`mir.field_addr` verified only struct, union and enum pointees, so a
field projection on a tuple array element (`let (a, b) = TABLE[i]`)
fell back to the value path: the whole array materialized as one
first-class-aggregate value, once per field projected. Extend the
verifier, the mir-importer read-path classifier and the mir-lower GEP
lowering to accept tuple pointees, reusing the same StructLayoutInfo
memory-order slot map the struct path already proves correct.

Closes #693.

Signed-off-by: Alejandro Soto Franco <[email protected]>

* test(mir): cover tuple-field writes unlocked by the field_addr tuple pointee

The mir.field_addr verifier extension for tuple pointees also unlocks
tuple-field WRITES (arr[i].1 = x, t.0 = x) and &mut tuple-field borrows:
statement.rs and the unified address walker already emit MirFieldAddrOp
for those shapes unconditionally, so only the verifier stood in the way,
and nothing tested the write side.

- dialect-mir ops_test: verify a mir.field_addr on a reordered (u8, u32)
  tuple pointee used as a mir.store destination, plus a negative case
  storing the wrong field type through it.
- const_tuple_table_lookup example: new tuple_field_store kernel that
  copies tuple-array elements locally, writes .1 through a runtime index
  with a thread-unique value, writes .0 through a &mut borrow, and
  checks bit-exact against a host reference. The rustc-reordered
  (u8, u32) element locks the memory-slot vs declaration-index
  distinction for stores as the read kernel already does for loads.

Validated: cargo fmt --all; cargo clippy -p dialect-mir -p mir-importer
-p mir-lower -- -D warnings; cargo test -p dialect-mir -p mir-lower;
cargo oxide run const_tuple_table_lookup on an RTX 5090 (all three
kernels exact match, SUCCESS marker printed).

* fix(mir): keep over-aligned-ZST tuples on the value read path

The field_addr tuple read path ends in a mir.load that states the
loaded field's natural alignment only. A tuple whose ABI alignment
comes from a zero-byte repr(align(N)) field, such as (Align32, u8),
therefore emitted an align-1 load in the unoptimized LLVM, tripping
the array_constants code-shape guard that keeps over-aligned reads
off that shape.

Gate the read classifier: a tuple field read falls back to the value
path when the tuple carries a field that owns zero bytes while its
recorded ABI alignment exceeds 1. Detection compares byte sizes, not
element counts, recursing through arrays at any nesting depth so a
zero-byte [Align32; 2] cannot slip through on its element count of 2.
Ordinary tuples keep the address path. Gate shape from PR #715
(vyncint), with the byte-size gap closed.

---------

Signed-off-by: Alejandro Soto Franco <[email protected]>
Co-authored-by: nihalpasham <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

already-fixed Resolved on a newer commit or branch; no action needed bug Something isn't working codegen Device code-generation pipeline (Rust MIR to IR to PTX) 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.

Projecting a field of a tuple array element copies the whole array, once per field

2 participants