Skip to content

feat: field-faithful multi-payload enum layout; admit enums at the kernel ABI - #160

Merged
nihalpasham merged 8 commits into
mainfrom
feat/enum-field-faithful-layout
Jun 11, 2026
Merged

nihalpasham merged 8 commits into
mainfrom
feat/enum-field-faithful-layout

Conversation

@nihalpasham

Copy link
Copy Markdown
Collaborator

What

Multi-payload enums now lower with rustc's exact byte layout, so enum data can cross the host/device boundary in both directions. The "not yet field-faithful" divergence guard is gone; what remains is a narrower check that closes a latent unsoundness (details below).

#[repr(u32)] enum E { A(u32), B(f32), C }      rustc: 8 bytes, payloads overlap at byte 4

Before:  device struct { i32, i32, i32 }  (12 bytes, payloads side by side)
         -> kernels taking E behind a ptr/slice REJECTED at the ABI boundary
After:   device struct { i32, i32 }       (8 bytes, byte-identical to rustc)
         -> &[E] / DisjointSlice<E> kernel params just work

How

Four commits, each independently green:

  1. Metadata (dialect-mir, mir-importer): MirEnumType records where the tag and every payload field live (byte positions from rustc's layout). The offset lookups move into a shared translator::layout module so type import and constant decoding cannot drift.
  2. Representation (mir-lower): build_enum_slot_map builds the LLVM struct and the indices into it in one walk (the issue kernel silently reads the wrong struct field on the GPU (reordered/padded repr(Rust) struct) #128 build_struct_slot_map pattern). Fields whose bytes collide with a different-typed field of another variant keep their byte position but no struct slot; they are read/written through an alignment-stamped stack spill plus a byte-precise pointer (no bitcast). Identical (position, type) payloads share one slot, so common shapes like Result<i32, u32> stay pure SSA. All five index consumers (type conversion, construct, discriminant read, payload read, three-way compare) switched atomically. The old guard deliberately stayed active through this commit as a bisect point.
  3. Guard flip: enum_memory_divergence deleted; the ABI walk narrows to find_unmodeled_enum_in_abi, which rejects only enums whose layout we deliberately do not record: niche-encoded shapes (Option<&T>) and degenerate multi-variant Singles (Result<T, Infallible>). This closes a pre-existing hole: such enums used to pass the old size-comparison guard while host and device disagreed on every byte (the host stores no tag at all; the device adds a synthetic one). New unit test pins the rejection; kernel_param_rejects_layout_divergent_enum flips into kernel_param_accepts_multi_payload_enum.
  4. Docs: all enum-related comments rewritten in plain language with byte diagrams, readable with basic Rust knowledge.

Evidence

  • New example enum_abi_multi_payload proves both ABI directions on hardware: the host writes an E { A(u32) = 7, B(f32) = 9, C = 4096 } buffer (overlapping payloads, sparse discriminants), a kernel matches and decodes it (B's payload through the memory path), and a second kernel constructs all three variants back through DisjointSlice<E> for host verification. Passes on sm_120.
  • Prove-it-bites: at the stage-1 commit the same example is rejected with the old "not yet field-faithful" fatal; after stage 3 it builds and passes.
  • New unit tests: payload slot sharing; tag NOT at byte 0 ({A(u64), B(u64)} with the tag at byte 8 lowers to { i64, i8, [7 x i8] } with both payloads sharing slot 0); niched-enum kernel-param rejection.
  • Full GPU smoketest on sm_120: 75/76, the single failure being the documented pre-existing cluster Test 2 (cluster sync) baseline failure. All five enum-pinning examples (enum_array_match, repr_u32_enum_stride, option_ref_transmute, option_ref_unwrap_or, ord_cmp) execute correctly.
  • 76/76 compile-only; all dialect-mir / mir-importer / mir-lower tests green; clippy clean.

Notes

  • The user-visible behavior change: niched enums reachable from kernel params are now rejected with an explanatory error suggesting an explicit discriminant repr. Previously they compiled and silently miscompiled.
  • Known follow-ups: hoist the lowering-introduced spill allocas to the function entry block (matters only under CUDA_OXIDE_NO_OPT=1; opt -O2 SROA removes them today), and modelling niched layouts themselves so Option<&T> can cross the boundary too.
  • SetDiscriminant stays rejected at import; under this model it becomes a plain tag store, an enabled follow-up.

Additive metadata, stage 1 of the field-faithful enum layout work. No
lowering behavior changes; no consumer reads the new fields yet.

- MirEnumType gains `tag_offset` (the tag is usually at byte 0, but
  rustc may place it after payload bytes) and `all_field_offsets`
  (flattened parallel to `all_field_types`; variants OVERLAP in rustc's
  layout, so offsets from different variants may coincide). EnumVariant
  gains `field_offsets` + `new_with_offsets`. The verifier requires one
  offset per field when `total_size > 0` and offsets within the object
  (`==` allowed for ZST fields, which rustc may place at the end).
- The importer fills both from rustc layout in the Direct-tag arm.
  Niched / single-variant / empty arms pass zeros: the deliberately
  un-niched model is unchanged.
- The byte-offset lookups move out of rvalue.rs into a shared
  `translator::layout` module (enum_variant_field_offsets, plus the tag
  offset lookup factored out of read_enum_tag_value), so constant
  decoding and type import cannot drift on how an offset is derived.

Verified: dialect-mir/mir-importer/mir-lower tests green; clippy clean;
all five enum-pinning examples build; MIR dump shows E { A(u32), B(u32),
C } carrying offsets [4, 4], total_size 8, and niched Option keeping the
empty-offsets total_size=0 model.
Stage 2 of the field-faithful enum layout work: Direct-tag enums now
lower to an LLVM struct whose every field sits at its exact rustc byte
offset and whose allocation size equals rustc's, so host and device
agree byte-for-byte. The kernel-ABI divergence guard deliberately stays
in place this commit (its concat-size computation is independent of the
converter); it narrows in the next stage.

- build_enum_slot_map (the issue-#128 build_struct_slot_map pattern:
  type and indices from one walk). The tag claims a typed slot at its
  rustc offset first; payload fields claim typed slots in ascending
  offset order, SHARING a slot on identical (offset, converted type)
  (so `enum E { A(u32), B(u32) }` keeps both payloads in one i32 slot,
  pure SSA); colliding or unaligned fields are filler-resident behind
  explicit [N x i8] filler; gaps and the tail get explicit filler. A
  natural size that cannot reproduce rustc's is a hard error. The
  total_size == 0 model (niched / single-variant, deliberately
  un-niched) keeps the concatenated struct verbatim.
- All five index consumers switch to the map in this one commit:
  convert_enum_to_llvm, convert_construct_enum (filler-resident fields
  are written through an abi_align-stamped stack spill at their rustc
  offsets), convert_get_discriminant (tag_slot, not literal 0),
  convert_enum_payload (extractvalue, or spill + byte-GEP + typed load
  for filler-resident fields; undef for ZSTs), convert_three_way_cmp.
- struct_over_align generalizes to aggregate_over_align: enum allocas/
  loads/stores are stamped with rustc's ABI alignment, since a
  filler-heavy struct like { i8, [7 x i8] } has natural alignment 1
  while rustc demands 8.
- Spill allocas are emitted at the use site like
  convert_extract_array_element; entry-block hoisting is a noted
  follow-up for the CUDA_OXIDE_NO_OPT=1 path.

Verified: 39/39 mir-lower tests (incl. new slot-sharing and
tag-not-at-zero tests; the ABI guard rejection test still passes);
75/75 examples compile; enum_array_match IR is [4 x { i32, i32 }] with
shared payload slots (was 12-byte concat); all five enum-pinning
examples plus vecadd/struct_field_layout/tuple_return execute correctly
on sm_120.
Stage 3 of the field-faithful enum layout work: with the slot map
making every Direct-tag enum byte-identical to rustc's layout, the
divergence guard's premise is gone. enum_memory_divergence (which
recomputed the old concatenated layout) is deleted, and the ABI walk
narrows into find_unmodeled_enum_in_abi.

The narrowed walk flags `total_size == 0` enums with more than one
variant: niche-encoded shapes (Option<&T>) and degenerate
multi-syntactic-variant Singles (Result<T, Infallible>), whose
deliberately un-niched device model carries a synthetic tag that does
not exist in rustc's layout. This CLOSES a pre-existing hole: such an
enum reachable from a kernel param used to sail past the old
size-comparison guard (early return on total_size == 0) with host and
device disagreeing on every byte. The new error suggests an explicit
discriminant repr at the boundary.

Tests: kernel_param_rejects_layout_divergent_enum flips into
kernel_param_accepts_multi_payload_enum; new
kernel_param_rejects_niched_enum pins the closed hole; "divergent"
helpers renamed to multi_payload.

New example enum_abi_multi_payload proves both ABI directions on
hardware: the host writes a #[repr(u32)] enum buffer whose payloads
overlap (A(u32) / B(f32) both at byte 4, sparse discriminants 7/9/4096),
a kernel matches and decodes it (B's payload via the filler-resident
memory path), and a second kernel constructs all three variants back
through DisjointSlice<E> for host-side verification.

Verified: all dialect-mir/mir-importer/mir-lower tests green; 76/76
examples compile; enum_abi_multi_payload passes on sm_120 (both
directions); prove-it-bites: at the stage-1 commit the same example is
rejected with the old "not yet field-faithful" ABI fatal.
Stage 4 of the field-faithful enum layout work, plus a readability pass
over the comments the earlier stages introduced. Target reader: someone
with a little Rust knowledge. Concepts are now explained where they are
used (variants share bytes because only one is alive; a niche hides the
tag inside the payload, e.g. null means None for a never-null &T), with
small byte diagrams where they help. Invented shorthand
("memory-faithful", "filler-resident") is gone or explained at first
use.

Also sweeps the references that stage 2/3 made stale: the MirEnumType
doc no longer describes the concatenated model as THE model, the
mir-lower module header shows the byte-faithful struct with a worked
example, and both READMEs' mir.enum rows/format examples match the new
representation.

The kernel-boundary error message is rewritten in the same plain style
(its test assertions updated to match). No code behavior changes; all
tests green.
@nihalpasham nihalpasham added enhancement New feature or request safety Memory safety, soundness, or undefined behavior codegen Device code-generation pipeline (Rust MIR to IR to PTX) IR-lowering Lowering between dialects (dialect-mir to LLVM dialect) labels Jun 11, 2026
…ntly

Nothing in the hardware demands a different layout; the difference is a
scoped deferral. With a real tag, discriminant read/construct are
one-field loads and stores, which is all our enum ops know how to be.
A niche has no tag: the variant must be computed from the payload
(null check, byte-range check, rustc's get_discr arithmetic), and that
decode/encode logic has not been ported yet. Until it is, the device
keeps a synthetic tag, private to the device, with the kernel-boundary
check keeping it away from host bytes. Porting the niche logic retires
both the difference and the check.
@nihalpasham

Copy link
Copy Markdown
Collaborator Author

Since this whole thing is about matching device and host enum layouts, where niche-encoded enums (e.g. Option<&T>) store no tag in rustc's layout; the variant is computed from the payload (null means None).

And our construct ops only know the load-a-tag / store-a-tag shape, which is why we model these enums with an explicit variant-count tag, and mir-lower rebuilds the aggregate from NicheEncodingAttr (emit_scalar_to_niched_enum).

Question: which enums does rustc apply this optimization to and why? Can we not have the same exceptions in our pipeline?

cargo fmt over the enum-layout files, and the module doc's reference to
pub(crate) build_enum_slot_map becomes plain code text (public docs may
not link private items under the doc gate).
@nihalpasham
nihalpasham merged commit 71b6974 into main Jun 11, 2026
24 checks passed
@nihalpasham
nihalpasham deleted the feat/enum-field-faithful-layout branch June 12, 2026 10:19
meefs pushed a commit to meefs/cuda-oxide that referenced this pull request Sep 30, 2026
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) enhancement New feature or request IR-lowering Lowering between dialects (dialect-mir to LLVM dialect) safety Memory safety, soundness, or undefined behavior

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant