Repository navigation
feat: field-faithful multi-payload enum layout; admit enums at the kernel ABI - #160
Merged
Merged
Conversation
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.
…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.
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 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).
meefs
pushed a commit
to meefs/cuda-oxide
that referenced
this pull request
Sep 30, 2026
Co-authored-by: Melih Elibol <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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).
How
Four commits, each independently green:
dialect-mir,mir-importer):MirEnumTyperecords where the tag and every payload field live (byte positions from rustc's layout). The offset lookups move into a sharedtranslator::layoutmodule so type import and constant decoding cannot drift.mir-lower):build_enum_slot_mapbuilds 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) #128build_struct_slot_mappattern). 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 (nobitcast). Identical (position, type) payloads share one slot, so common shapes likeResult<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.enum_memory_divergencedeleted; the ABI walk narrows tofind_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_enumflips intokernel_param_accepts_multi_payload_enum.Evidence
enum_abi_multi_payloadproves both ABI directions on hardware: the host writes anE { 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 throughDisjointSlice<E>for host verification. Passes on sm_120.{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.clusterTest 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.Notes
CUDA_OXIDE_NO_OPT=1;opt -O2SROA removes them today), and modelling niched layouts themselves soOption<&T>can cross the boundary too.SetDiscriminantstays rejected at import; under this model it becomes a plain tag store, an enabled follow-up.