Skip to content

perf(mir-importer): promote a field-less enum array constant like an integer one - #694

Merged
nihalpasham merged 2 commits into
NVIDIA:mainfrom
vyncint:perf/audit-round3
Aug 8, 2026
Merged

nihalpasham merged 2 commits into
NVIDIA:mainfrom
vyncint:perf/audit-round3

Conversation

@vyncint

@vyncint vyncint commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Closes #692. Follow-up to #684.

Problem

Issue #692 names two defects around field-less enum tables:

  • A const OPS: [Op; 256] (field-less #[repr(u32)] enum) was rebuilt element by element in every thread's local depot, even though it is byte-identical to the [u32; 256] of its discriminants. Measured 49x slower than the equivalent u32 table at 256 entries.
  • The reference spelling const R: &[Op; 256] = &OPS; did not even compile: "invalid input program".
#[repr(u32)] enum Op { Add = 3, Sub = 5, Mul = 7, /* ... */ }
const OPS: [Op; 256] = [ /* ... */ ];
acc += OPS[(h >> 24) as usize & 255] as u32;   // runtime index

Before: 256 x st.local per thread, 1 KiB depot, 309 PTX instructions
        16073 us/launch (A10G), 49x the u32 table
After:  table lives once in the module image, one ld.global.nc per
        lookup, no depot, 70 instructions, 330 us/launch, 1.00x

Fix

  • The bare-array promotion gate becomes a predicate owned by this path (promotable_array_element): primitive scalars, field-less enums, and nested arrays of either, plus a byte-size agreement guard between the dialect's storage layout and rustc's evaluated allocation.
  • The discriminant bytes come from rustc's own constant evaluation, so the values were never in question; the guard establishes that reading an element back is cheap.
  • enum_table_lookup example with paired enum/u32 kernels so the integer row doubles as a control; bit-correct against a host reference.

Maintainer commit on top (1242931)

  • The pointer-to-array constant path now delegates its admission decision to the same promotable_array_element predicate, so const R: &[Op; N] = &OPS compiles and the two paths cannot drift apart. This closes the second defect of Field-less enum array constants are still materialized per thread, and &[Op; N] is rejected outright #692, making the "Closes" above accurate.
  • New enum256_ref_table kernel reading through &[Op; 256] at a runtime index, verified bit-exact; on an RTX 5090 it runs at the bare enum table's exact cost, reading the same deduplicated immutable global.

…integer one

NVIDIA#684 stopped bare array constants being built per thread, but its element gate
admits only primitive scalars and nested arrays of those. A field-less enum array
was left out, even though it holds nothing but discriminants and so is
byte-identical to the `[u32; N]` of its values. It was still materialized into the
per-thread local depot -- one `st.local` per element in every thread, for data the
module image already carries -- and the lookup then read thread-private memory.
There was no way to spell around it either: `&[Op; N]`, the reference form that
works for scalar tables, is rejected outright.

Replace the borrowed `&[T; N]` gate with a predicate of this path's own, which
admits primitive scalars, field-less enums, and nested arrays of either. The byte
image is rustc's evaluated allocation, so the discriminants were never the
question; what the gate has to establish is that reading an element back is
cheap, and for a field-less enum the whole element *is* its discriminant.

Payload-carrying enums, tuples and structs stay out, and not because a byte image
would be wrong. Projecting one field of a tuple element out of a local array
copies the whole array to a fresh stack slot, once per field (NVIDIA#693). Those copies
dominate: promoting a `[(u8, u32); 256]` table leaves its 925 PTX instructions,
4096-byte depot and 878 `st.local` exactly as they were and merely adds a 2 KiB
global. Verified both ways on the A10G before excluding them.

A size guard backs the widening: the copy is sized from the destination's
converted type while the bytes come from rustc, so the two must agree before a
byte image is trusted. `dialect_stored_size` answers from the `total_size` the
storage builders reproduce, and any disagreement falls through to the
element-wise path rather than copying over a differently-sized local.

Measured on an A10G (sm_86, driver 595.71.05), 64 dependent divergent lookups per
thread over 8388608 threads, 50 timed launches after 10 warmup. Every kernel
bit-correct against a host reference in both runs, and each enum table is paired
with a `[u32; N]` table over the same discriminants so the pair isolates the
element type:

  entries  table       before      after    speedup   u32 pair (control)
       16  [Op; N]    1309.4us    361.4us      3.62x    361.4 -> 361.6us
      256  [Op; N]   16073.3us    330.2us     48.68x    327.3 -> 330.0us

An enum table now costs what the integer table of the same values costs, to
within 1% at both sizes, and the controls did not move. PTX for the 256-entry
enum kernel goes from 309 instructions with a 1 KiB depot and 256 `st.local` to
70 with no depot, reading through `ld.global.nc`.

`array_constants`' `verify-code-shape.sh` pinned the enum array's `insertvalue`
chain, so it now asserts the shape that replaced it: the discriminants in the
read-only global's initializer, the copy out of that global, and the same runtime
index and element load. Pinning the whole byte image in one pattern also fixes
their order, which the previous per-discriminant search did not -- a permuted or
truncated table now fails where before it passed. That example's runtime
assertions were unaffected; the values were never in question.

Adds `enum_table_lookup`, which measures both pairs and keeps their agreement
checked.

Closes NVIDIA#692.

Signed-off-by: Vyncint Ng <[email protected]>
@nihalpasham nihalpasham added perf Performance of generated code or of the compiler itself codegen Device code-generation pipeline (Rust MIR to IR to PTX) labels Aug 8, 2026
…e spelling

The bare-array widening left the second defect of NVIDIA#692 open: the pointer
path still checked elements with its own validator, so
`const R: &[Op; N] = &OPS` kept hard-erroring with "invalid input
program" while `OPS[i]` promoted cleanly.

Route both promoted-constant paths through the one element gate.
`validate_ptr_to_array_constant_type` now asks
`promotable_array_element`, which absorbs the zero-length vacuous
admission (`&[]` for any element type) so nothing the pointer path
accepted is lost, and the two boundaries cannot drift apart again. The
pointer path also gains the same byte-size agreement the bare-array
promotion demands, except here disagreement is an input error because
there is no element-wise lowering to fall back to.

A unit test holds the reference form to the bare-array gate: field-less
enum arrays pass, payload-carrying enums stay out, and the promoted
empty-slice admission survives the rerouting. `enum_table_lookup` gains
`enum256_ref_table`, which reads through `const R: &[Op; 256] = &OPS`
against the same host reference. On an RTX 5090 it runs bit-correct at
the bare enum table's exact cost (106.5us per launch, 1.21x the u32
control for both spellings), and the emitted IR shows it reading the
same deduplicated immutable global the bare table copies from.
@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

Copy link
Copy Markdown
Collaborator

Gist: A table of C-style enums is stored as the same bytes as a table of the integers, so it deserves the same treatment #684 gave integer tables: keep it in the module image once instead of having every thread rebuild it in private memory. The PR widens the acceptance check the right way, with its own predicate plus a guard that the compiler's byte layout agrees with rustc's.

I pushed one commit on top:

  • the issue's second part: adding the same table behind a reference (const R: &[Op; N] = &OPS) did not just run slow, it refused to compile.
  • the reference path now uses the same acceptance check as the plain path (one check, both paths, cannot drift), with a unit test and a kernel that reads through the reference at a runtime index.

Verified on an RTX 5090 (sm_120):

  • all 5 kernels bit-correct;
  • the 49x perf problem is gone (1.00x at 16 entries, 1.19x at 256 on this card), and
  • the reference runs at the plain table's exact cost;
  • 927 mir-importer tests green; array_constants code-shape guard PASS; full sweep 188/188.

Closes #692.

Merging.

@nihalpasham
nihalpasham merged commit 83d23ac into NVIDIA:main Aug 8, 2026
36 checks passed
vyncint added a commit to vyncint/cuda-oxide that referenced this pull request Aug 8, 2026
…s address

NVIDIA#694 kept tuple elements out of immutable-global promotion, and said why: while a
tuple field read still copied the whole array to a stack slot, that copy dominated
so completely that promoting the table changed nothing measurable and only added a
global to the module image. I measured it both ways there and it was neutral.

NVIDIA#709 removed that copy. With the read addressing in place, the promotion is what
takes the depot away -- the two only pay off together, which is why neither alone
looked like much. So `promotable_array_element` now admits a tuple whose every
field is itself promotable.

Structs stay out because the element-wise path does not build arrays of them
either, so there would be nothing to fall back to. A payload-carrying enum stays
out because reading one back still round-trips the payload through memory: the
address walker resolves enum payload fields for writes, not for reads.

Since NVIDIA#694, that predicate is also the gate for the pointer-to-array form
(`const R: &[T; N] = &TABLE`, via `validate_ptr_to_array_constant_type`), and its
doc says the two forms must not drift apart. Widening it therefore widens that
form too, which is intended and safe: nothing on that path enumerates fields. The
initializer is rustc's evaluated byte image and the size-agreement check rejects
any layout the dialect reproduces differently, so a tuple element travels it
exactly as a scalar does. Its boundary test asserted the old exclusion; it now
asserts the admission, plus a struct-in-tuple case proving the recursion holds
there as well.

Measured on `tuple_field_lookup`, a 256-entry `(u8, u32)` table read at a
divergent runtime index, comparing this commit against its parent:

  kernel             depot  st.local  ld.global.nc  instrs
  tuple_one_field     2048       512             0     562
              +this      0         0             4      67
  tuple_two_fields    2048       512             0     564
              +this      0         0             4      59
  scalar_control         0         0             4      67   (unchanged)

Each thread's 2 KiB private copy of the table is gone and the reads come from the
read-only data cache instead, which is the shape the scalar table has always had:
`tuple_one_field` now matches `scalar_control` instruction for instruction.
`scalar_control` reads a plain `[u32; N]` over the same index stream and does not
move, so the comparison is controlled rather than two separate builds.

`array_constants`' code-shape guard pinned four tuple tables as `insertvalue`
chains, which this replaces with byte images. Each is now asserted as the
initializer bytes plus the lowered element type, which is strictly stronger: the
reordered `(u8, u32, u64)` table went from four separate slot searches to one
pattern that fixes all three fields at their byte offsets, the padding between
them, and both elements' stride at once. Checked that a swapped field and a
padding byte carrying data are both rejected by it.

Signed-off-by: Vyncint Ng <[email protected]>
nihalpasham pushed a commit that referenced this pull request Aug 10, 2026
…s address (#717)

#694 kept tuple elements out of immutable-global promotion, and said why: while a
tuple field read still copied the whole array to a stack slot, that copy dominated
so completely that promoting the table changed nothing measurable and only added a
global to the module image. I measured it both ways there and it was neutral.

#709 removed that copy. With the read addressing in place, the promotion is what
takes the depot away -- the two only pay off together, which is why neither alone
looked like much. So `promotable_array_element` now admits a tuple whose every
field is itself promotable.

Structs stay out because the element-wise path does not build arrays of them
either, so there would be nothing to fall back to. A payload-carrying enum stays
out because reading one back still round-trips the payload through memory: the
address walker resolves enum payload fields for writes, not for reads.

Since #694, that predicate is also the gate for the pointer-to-array form
(`const R: &[T; N] = &TABLE`, via `validate_ptr_to_array_constant_type`), and its
doc says the two forms must not drift apart. Widening it therefore widens that
form too, which is intended and safe: nothing on that path enumerates fields. The
initializer is rustc's evaluated byte image and the size-agreement check rejects
any layout the dialect reproduces differently, so a tuple element travels it
exactly as a scalar does. Its boundary test asserted the old exclusion; it now
asserts the admission, plus a struct-in-tuple case proving the recursion holds
there as well.

Measured on `tuple_field_lookup`, a 256-entry `(u8, u32)` table read at a
divergent runtime index, comparing this commit against its parent:

  kernel             depot  st.local  ld.global.nc  instrs
  tuple_one_field     2048       512             0     562
              +this      0         0             4      67
  tuple_two_fields    2048       512             0     564
              +this      0         0             4      59
  scalar_control         0         0             4      67   (unchanged)

Each thread's 2 KiB private copy of the table is gone and the reads come from the
read-only data cache instead, which is the shape the scalar table has always had:
`tuple_one_field` now matches `scalar_control` instruction for instruction.
`scalar_control` reads a plain `[u32; N]` over the same index stream and does not
move, so the comparison is controlled rather than two separate builds.

`array_constants`' code-shape guard pinned four tuple tables as `insertvalue`
chains, which this replaces with byte images. Each is now asserted as the
initializer bytes plus the lowered element type, which is strictly stronger: the
reordered `(u8, u32, u64)` table went from four separate slot searches to one
pattern that fixes all three fields at their byte offsets, the padding between
them, and both elements' stride at once. Checked that a swapped field and a
padding byte carrying data are both rejected by it.

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

codegen Device code-generation pipeline (Rust MIR to IR to PTX) perf Performance of generated code or of the compiler itself

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Field-less enum array constants are still materialized per thread, and &[Op; N] is rejected outright

2 participants