Repository navigation
Address an enum payload in memory, so a payload can be mutated in place - #652
Merged
nihalpasham merged 10 commits intoAug 5, 2026
Merged
Conversation
Mutating an enum payload needs the address of that payload. The importer's address walker had no arm for `Downcast`, which left two paths shut: - `&mut` to a payload was refused outright. The walker returned no address, and `Rvalue::Ref` will not fall back to a value copy for a mutable borrow because writes through the borrow would land in the copy and the original would never change. Refusing was right; the missing address was the defect. - `(x as Variant).field = v` failed as "2-level projection Downcast -> Field not yet implemented for assignment". Both are one gap. `all_field_types` already concatenates the variants in order, so a single flattened index names a (variant, field) pair, and `MirFieldAddrOp` extends to a third pointee kind beside struct and union rather than needing an op of its own. `MirEnumType::flat_field_index` does that translation. Lowering resolves the position through `build_enum_slot_map`, which the enum work already built and which answers the part that makes enums awkward: variants share bytes, so a field either has an LLVM slot of its own or its bytes are held by a differently typed field of another variant. The first case is a slot GEP, the second a byte-offset GEP. Both name the same storage, which is what makes a write land in the enum. The walker records the variant at `Downcast` and consumes it at the `Field` that follows, since the downcast moves no address of its own. It still punts when the pointee does not resolve to an enum payload position, so an unknown shape stays a loud failure rather than addressing the wrong bytes. The assignment arm is then a delegation to the same walk-and-store helper the other 2-level pairs use. This was the designed extension point marked in the walker for NVIDIA#131 and NVIDIA#146, both since closed. Validation, RTX 5060 (sm_120), CUDA 13.3, via the new `enum_payload_addr` example over 2^20 elements, each kernel reading its value back so a write into a copy shows as an unchanged element: - `assign_payload` writes through `(x as Variant).field = v`. - `borrow_payload` hands `&mut` to a `#[device]` helper, so the borrow survives into a call and cannot fold into a direct store. - `shared_bytes` uses two payload variants of different types at one offset, so the no-slot byte-offset path runs. - All four kernels match exactly, from a sentinel-filled buffer. - 3287 workspace tests, clippy --all-targets -D warnings clean. The change buys expressiveness, not speed: in-place mutation against the rebuild-from-a-copy workaround is 0.0113 ms against 0.0105 ms over 20 runs, a ratio of 1.08 on a kernel that is bandwidth-bound either way. The value is that the borrowing form compiles at all.
…cal storage
Enum payload bytes use one CANONICAL storage type that can differ from
the field's semantic type: bools are physically i8 bytes and
shared-memory pointers are stored as generic pointers, with the value
paths (construct/extract) coercing exactly at that boundary. The new
in-place payload address bypassed that boundary: the address escapes,
so the loads and stores made through it happen at other sites typed
with the SEMANTIC type. A semantic i1 store through such an address
leaves the byte's upper seven bits undefined for every i8 reader,
including a niche tag sharing the byte (enum Flag { On(bool), Off }
compiled to 'store i1' into the { i8 } tag byte and could misdispatch
the following match), and a shared-pointer store writes a
representation every other reader interprets, and on modern NVVM
sizes, as a generic pointer.
Coercion cannot be attached at address-formation time precisely
because the address escapes, so the sound choice is to reject the
address with a loud, actionable diagnostic, the same way the slot map
already rejects bool bytes hidden behind unions. Payloads whose
storage equals their semantic type (the common integer/float/generic
pointer cases) are unaffected.
Also harden the slotless byte-offset arm: index field_offsets
directly instead of defaulting a missing entry to offset 0 (the tag),
and reject offsets beyond u32 instead of silently truncating the GEP
index.
Tests: bool and shared-pointer payload addresses now fail to lower
with the canonical-storage diagnostic, and a slotless payload address
GEPs the ORIGINAL enum storage at its exact byte offset with no stack
spill.
…ess walker rustc's MIR validator guarantees a Downcast projection is always followed immediately by a Field projection, and that Field is never applied to an enum place without a preceding Downcast. The walker now enforces both ends of that contract instead of assuming them: - a pending variant that is not consumed by the very next Field punts (no stale variant can leak into a later Field arm, and a chain that ends on a Downcast no longer returns the enum's own address as if it were the variant's payload place); - a Field over an enum pointee with NO pending variant fails loudly: MirFieldAddrOp reads an enum-pointee index as a flattened (variant, field) position, so passing a raw per-variant index through could silently address another variant's payload. Before the enum arm was added to the op's verifier this shape died at verification; this restores an equally loud failure at the only place that can still tell raw and flattened indices apart. Also extend the flat_field_index unit test with the inconsistent metadata edge: when all_field_types is shorter than the variant field counts promise, the final bound check refuses rather than naming a position past the array.
…dress on GPU The shared_bytes kernel mutates Either::Real, whose f32 claims the shared bytes first and therefore owns an LLVM slot, so the no-slot byte-offset addressing arm never actually ran on GPU. Add shared_bytes_no_slot, which mutates Either::Bits in place: Bits shares Real's bytes without a slot of its own, so its address is a byte offset off the original enum storage. The read-back check makes a write that lands in a copy, or at the wrong offset, show up as an unchanged or corrupted element.
…nical enum payloads
Regression against main: a SHARED borrow of a bool enum payload that
survives MIR optimization (enum Flag { On(bool), Off } with
`if let Flag::On(b) = &flag { read_bool(b) }` across a #[device] call
boundary) compiled on main and failed on this branch. Main's address
walker punted at Downcast and Rvalue::Ref fell back to a sound value
copy (alloca of the extracted i1 + call); this branch's walker now
produces the payload address, and the mir-lower canonical-storage gate
rightly rejects it, because a bool payload's storage byte is a
canonical i8 that a raw escaped address cannot honor.
The gate is correct; the walker was volunteering an address nobody can
use. Teach the Downcast/Field arm the distinction: when the borrow is
SHARED and the payload's SEMANTIC type is non-canonical for enum
storage (a bool leaf or a shared-memory pointer leaf, at any
struct/tuple/array nesting depth, mirroring what mir-lower's
enum_payload_storage_type rewrites), return Ok(None) so the existing
value-copy fallback handles the read exactly as main did. Mutable
borrows and assignment stores keep the address path and the loud gate.
Layering: the importer predicate is allowed to be conservative (a
nested enum payload is flagged whenever any of its own payload fields
is, without proving the leaf survives into the nested enum's converted
storage); over-punting only costs a copy for a shared borrow and stays
sound. The mir-lower gate remains the fail-closed authority, so a
predicate miss still errors loudly instead of miscompiling.
Tests:
- enum_payload_addr gains shared_borrow_bool_payload, the repro shape
above, with a variant-dependent expected value per element so a read
of the wrong byte or wrong variant shows up as a mismatch; runs
green on GPU.
- new error_enum_bool_payload_addr fixture keeps the MUTABLE-borrow
bool-payload case failing loudly with the canonical-storage gate
diagnostic (wired into smoketest ERROR_EXAMPLES with an exact
diagnostic check, and into STATUS.md).
- a unit test covers the predicate over bool/shared-pointer leaves,
clean scalars and generic pointers, and nested aggregates.
…me mutation The gate message told the user to "rebuild the enum with the new payload value", which presumes an attempted in-place mutation. The gate can also fire on address shapes reached without any user-visible mutation (it is the fail-closed authority behind the importer's shared-borrow punt, so a conservative-predicate miss lands here too), where that advice is a non sequitur. State the actual contract instead: bool and shared-pointer payloads use canonical storage bytes that loads and stores through a raw, escaped payload address cannot honor; shared reads of such payloads are compiled through a value copy automatically; and in-place mutation of them is not supported. The "canonical storage type" and "in-place mutation of bool or shared-pointer enum payloads is not supported" fragments that the unit tests and the error_enum_bool_payload_addr smoketest verdict match on are unchanged.
…indices on enum pointees The 1-level Field, (Deref, Field) and (Field, Field) assignment fast paths build MirFieldAddrOp with the raw per-variant field index and no check on what the base pointer points to. Valid, validator-checked MIR can never steer an enum place into them (Field on an enum place always follows a Downcast, and every Downcast-bearing assignment routes through the walk-and-store path), so today they are unreachable for enums. But MirFieldAddrOp's verifier now accepts enum pointees and reads the index as a FLATTENED (variant, field) position, so a future importer bug that did reach them would no longer die at verification; it would silently address another variant's payload. Give each fast path the same cheap enum-pointee guard the address walker's Field arm received: downcast the base pointer's pointee and fail loudly if it is an enum. Unit test covers both sides of the guard (struct pointee passes, enum pointee is refused).
…ity split
The canonical-storage gate tests prove the ADDRESS path refuses bool
and shared-pointer payloads; nothing yet proved that payloads whose
storage equals their semantic type keep the address path for reads.
Add the missing half: a shared borrow (immutable pointer types) of an
f32 payload with its own LLVM slot lowers to exactly one GEP based on
the ORIGINAL enum storage ({0, slot} into the enum struct) and one
load of f32 through that GEP result, with zero allocas, so no spill
and no value copy.
Together with the gate tests this checks the full split: canonical
payloads are addressed and read in place, non-canonical payloads are
refused at address formation (and, for shared borrows, are compiled
through the importer's value-copy fallback before ever reaching the
gate).
Collaborator
|
Verified the mechanism at every layer (the importer extension point, the flattened field index, the slot-map lowering) and on hardware:
Pushed on top:
Closes #651. #306 (SetDiscriminant) stays open and is untouched here by design. |
rustc's dead-code lint discounts Slot::Empty => Slot::Empty because that arm is only reachable if the variant already existed, so the per-example clippy CI job failed with variant-never-constructed. The kernel now maps a NaN input to Slot::Empty, which makes the Empty match arms real; finite inputs take the same path as before and the host reference is unchanged. Verified on GPU: exact match, SUCCESS.
nihalpasham
approved these changes
Aug 5, 2026
This was referenced Aug 5, 2026
nihalpasham
pushed a commit
that referenced
this pull request
Aug 6, 2026
* Write a canonical-storage enum payload by rebuilding the enum Enum storage keeps two payload kinds in a converted form: a `bool` occupies a full `i8` byte and a shared-memory pointer is stored generic. A raw payload address cannot carry that conversion, because the address escapes and the loads and stores made through it elsewhere are typed with the semantic type, so #652 refused to hand one out. That left `if let Flag::On(b) = &mut flag { *b = value }` with no lowering. The borrow in that shape does not survive to the importer. Optimisation folds it into `(_flag as On).0 = value`, a store to the payload place, and it is that store which asks for the address. So the write needs no address at all: rebuild the enum around the new payload and store the whole value, which is what a whole-enum assignment already does. `construct_enum` coerces each payload to its canonical storage on the way in, which is the conversion the address could not carry. Valid MIR assigns to a variant's field only when the enum already holds that variant, so rebuilding with the same variant leaves the discriminant where it was. A variant of several fields keeps the others as they stand: each is read back out of the loaded value and passed through unchanged. A borrow that escapes, into a `#[device]` call for instance, reaches no store site and keeps the refusal. The diagnostic now says which of the two it is, and the `error_enum_bool_payload_addr` fixture still fails closed on the escaping shape. Tests: `enum_payload_addr` gains `mutate_bool_payload`, whose match arms differ so a write landing in a copy reports a mismatch rather than passing, and `mutate_multi_field_payload`, where the sibling `f32` of a two-field variant has to survive the rebuild. Both exact over 1048576 elements on an RTX 5060. Dropping the write from the first kernel fails it at element 1, so the check discriminates. * examples(enum_payload_addr): allow dead_code on the unconstructed Pair::Neither variant Neither exists so Pair stays a genuine two-variant enum for the payload-addressing test; the kernel only ever constructs Both. clippy's dead_code lint, denied by -D warnings, was blocking #673.
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.
Mutating an enum payload in place needs the address of that payload, and the importer's address walker had no arm for
Downcast, so a mutable borrow of a payload was refused outright and(x as Variant).field = vfailed as an unimplemented projection pair. This adds the addressing and opens both paths.Closes #651.
The one gap behind two errors
Rvalue::Refrefuses a mutable borrow it cannot address rather than falling back to a value copy, because writes through the borrow would land in the copy and the original place would never change. That refusal is correct; the missing address is the defect. The assignment path failed separately with "2-level projection Downcast -> Field not yet implemented for assignment". One address fixes both.Changes
all_field_typesalready concatenates the variants in order, so one flattened index names a (variant, field) pair andMirFieldAddrOpextends to a third pointee kind beside struct and union:The walker records the variant at
Downcastand consumes it at theFieldthat follows, since the downcast moves no address of its own. Lowering resolves the position throughbuild_enum_slot_map, which already answers the part that makes enums awkward: a payload field either has an LLVM slot of its own, or its bytes are held by a differently typed field of another variant. The first is a slot GEP, the second a byte-offset GEP, and both name the same storage.The assignment path becomes a delegation to the same walk-and-store helper the other 2-level pairs use.
This was the extension point marked in the walker for #131 and #146, both since closed.
Design decisions
Chosen: extend
MirFieldAddrOpto an enum pointee, keyed by the flattened field index. Alternative rejected: a dedicated payload-address operation mirroringmir.enum_payloadin value space. It would need a second attribute for the variant and its own verifier and lowering, to reach storage the flattened index already names.Chosen: the walker still returns no address when the pointee does not resolve to an enum payload position. Alternative rejected: treating a downcast as a zero-offset address unconditionally, which would silently address the wrong bytes for any shape the walker misreads.
Validation
New
enum_payload_addrexample, 2^20 elements on an RTX 5060 (sm_120), CUDA 13.3. Each kernel reads its value back after mutating, from a sentinel-filled buffer, so a write into a copy shows as an unchanged element rather than passing quietly.assign_payload(x as Variant).field = vborrow_payload&mutinto a#[device]helper, so the borrow survives a callshared_bytesrebuild_payloadflat_field_indexalso has a unit test covering a field past its variant's count, a variant with no fields, and an out-of-range variant.The caveat
This buys expressiveness, not speed. Against the rebuild-from-a-copy workaround, in-place mutation measures 0.0113 ms to 0.0105 ms over 20 runs, a ratio of 1.08 on a kernel that is bandwidth-bound either way. The value is that the borrowing form compiles at all, not that it runs faster.
Gates
3287 workspace tests pass,
cargo clippy --workspace --all-targets -- -D warningsclean, four device kernels verified against a host reference.