Skip to content

fix(mir-importer): read aggregate constant fields at their layout offsets - #394

Merged
nihalpasham merged 5 commits into
NVIDIA:mainfrom
alejandro-soto-franco:fix/aggregate-constant-field-offsets
Jul 23, 2026
Merged

nihalpasham merged 5 commits into
NVIDIA:mainfrom
alejandro-soto-franco:fix/aggregate-constant-field-offsets

Conversation

@alejandro-soto-franco

@alejandro-soto-franco alejandro-soto-franco commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

Closes #393

Summary

An aggregate constant's bytes are the memory image of its type, so each field starts at the offset rustc's layout gives it. The three walkers that carve those bytes into fields advanced a cursor by each field's size instead, which assumes the fields are packed in declaration order. That holds for neither a type rustc pads nor one it reorders, so every field after the first padded gap was read from the wrong offset, silently.

On the device:

struct Padded { a: u8, b: u64 }
const PADDED: Padded = Padded { a: 200, b: 0x7d25933d707303e5 };

read back as a = 229 (the low byte of b) and b = 0xc87d25933d707303 (b shifted by a byte), with no diagnostic.

Changes

  • translate_tuple_constant and translate_struct_constant read field offsets from rust_ty's layout.
  • build_const_from_bytes takes them from the struct type, which already carries rustc's layout.
  • constant_storage_size reports a struct's rustc size rather than the sum of its field sizes.
  • aggregate_field_offsets moves into translator/layout.rs beside the enum readers, whose module doc asks that every offset derivation live in one place.
  • The array arm gained the bounds check the struct arm already had, replacing an unchecked slice.
  • New padded_constants example, and a table-driven unit test over the storage-size predicate.

Rationale

Two silent miscompiles are fixed here, and the second is worth naming separately. A struct's recorded size is also the element stride in the array arm of build_const_from_bytes, so struct Batch { arr: [Padded; 2] } strode by the 9-byte field sum where the elements sit 16 apart, and every element after the first was read from the wrong offset.

Whether a struct's layout is known is decided by its recorded offsets rather than by its size. translator/types.rs stores empty offsets and a zero size when Ty::layout() fails, so keying on the size alone would also reject a struct that has fields and is genuinely zero bytes wide, such as a PhantomData newtype. Those reach the struct arm because is_zst_type calls a struct zero-sized only when it has no fields at all.

The enum constant path already read offsets from the layout and is unchanged. An enum or an f64 nested inside a struct constant still reports an unsupported aggregate field type; those error rather than miscompile and are left as they were.

Found by the in-tree rustlantis differential fuzzer (crates/fuzzer) on seed 71 of a 0..200 sweep. The fuzzer is unchanged here, so its coverage of padded aggregates stays incidental rather than guaranteed.

Validation

  • cargo check --workspace --all-targets
  • cargo test -p mir-importer (802 passed)
  • cargo test -p cuda-oxide-codegen (117 passed)
  • cargo clippy --workspace -- -D warnings
  • cargo fmt --all -- --check
  • (cd crates/rustc-codegen-cuda && cargo fmt --all -- --check)
  • (cd crates/rustc-codegen-cuda/examples/padded_constants && cargo fmt --all -- --check)
  • (cd crates/rustc-codegen-cuda/examples/padded_constants && cargo clippy --all-targets -- -D warnings)
  • RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --workspace

The example asserts on the device and exits non-zero on mismatch. It is compiled but not executed by CI, since examples-compile.yml runs smoketest.sh --compile-only on a runner with no GPU, so those assertions are a manual check. Run here on an RTX 5060, driver 610.43.03.

The example covers a padded struct, the same shape as a tuple, a nested padded struct, a padded struct with a float field, an array of padded structs, a #[repr(C)] struct, and a descending-alignment struct as a control. It fails on the unfixed compiler.

Note: the two example-scoped gates above were failing on this branch before this revision, on code that predates it. Example crates are excluded from the workspace, so a workspace-level cargo fmt --all does not reach them. Both are fixed here.

@alejandro-soto-franco
alejandro-soto-franco force-pushed the fix/aggregate-constant-field-offsets branch from b787e13 to f5fb360 Compare July 20, 2026 17:09
@nihalpasham nihalpasham added 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) miscompile Produces incorrect PTX/IR (wrong generated code) on-hold Paused: valid but deferred until a prerequisite decision or dependency resolves tests Adds or improves test coverage and removed on-hold Paused: valid but deferred until a prerequisite decision or dependency resolves labels Jul 22, 2026
alejandro-soto-franco and others added 2 commits July 23, 2026 17:30
…sets

An aggregate constant's bytes are the memory image of its type, so each field
starts at the offset rustc's layout gives it. The three walkers that carve those
bytes into fields instead advanced a cursor by each field's size, which assumes
the fields are packed in declaration order. That holds for neither a type rustc
pads nor one it reorders, and every field after the first padded gap was then
read from the wrong offset.

The values were wrong, silently. On the device

    struct Padded { a: u8, b: u64 }
    const PADDED: Padded = Padded { a: 200, b: 0x7d25933d707303e5 };

read back as `a = 229` (the low byte of `b`) and `b = 0xc87d25933d707303`
(`b` shifted by a byte), with no diagnostic. `(u8, u64)` and every other
ascending-alignment tuple went the same way; reversing the fields hid it,
since descending alignment needs no padding.

Take each field's offset from the layout instead:

- `translate_tuple_constant` and `translate_struct_constant` now read the
  offsets from `rust_ty`'s layout. `translate_struct_constant` had them
  available all along: its `_rust_ty` parameter was marked "Reserved for
  future layout computation".
- `build_const_from_bytes`, which handles nested aggregates, takes them from
  the struct type, which already carries rustc's layout.
- `constant_storage_size` reports a struct's rustc size rather than the sum of
  its field sizes, which under-reported every padded struct and so handed a
  short slice to the nested path.

That size is also the element stride in the array arm of
`build_const_from_bytes`, so `struct Batch { arr: [Padded; 2] }` strode by the
9-byte field sum where the elements sit 16 apart, and every element after the
first was read from the wrong offset. That second silent miscompile goes with
the first.

Whether a struct's layout is known is decided by its recorded offsets rather
than by its size. `translator/types.rs` stores empty offsets and a zero size
when `Ty::layout()` fails, so a zero size on its own would also reject a struct
that has fields and is genuinely zero bytes wide, such as a `PhantomData`
newtype. Those reach the struct arm because `is_zst_type` calls a struct
zero-sized only when it has no fields at all. `struct_storage_size` is a pure
predicate over that decision, table-tested across the padded, zero-sized,
field-less and layout-missing cases.

The enum constant path already did this, and is unchanged. An enum or an `f64`
nested inside a struct constant still reports an unsupported aggregate field
type; those error rather than miscompile, and are left as they were.

`aggregate_field_offsets` now sits in `translator/layout.rs` beside the enum
readers, whose module doc asks that every offset derivation live in one place
so the consumers cannot drift. The array arm gained the same bounds check the
struct arm carries, in place of an unchecked slice.

Found by the in-tree rustlantis differential fuzzer (`crates/fuzzer`), on seed
71 of a 0..200 sweep: CPU and GPU traces of the same program disagreed. That
sweep is now clean. The fuzzer is unchanged here, so its coverage of padded
aggregates stays incidental rather than guaranteed.

The `padded_constants` example covers a padded struct, the same shape as a
tuple, a nested padded struct, a padded struct with a float field, an array of
padded structs, a `#[repr(C)]` struct, and a descending-alignment struct as a
control. It fails on the unfixed compiler. CI compiles the example but does not
execute it, since `examples-compile.yml` runs `smoketest.sh --compile-only` on a
runner with no GPU, so the device-side assertions are a manual check.

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

translate_struct_constant followed the first provenance entry whenever
one existed, assuming the by-ref shape stable_mir uses for promoted
constants like &(8..16). Two defects hid in that guess. A by-value
struct constant with a pointer field had its own bytes silently
replaced by the first pointee's bytes before field decoding. And the
new layout query ran on constant.ty(), which at the promoted-reference
call site is the reference type, whose Primitive field shape the
layout helper rejects, so every promoted &struct constant stopped
compiling.

Decide by the constant's Rust type instead: Ref/RawPtr means follow the
indirection and query layout on the pointee; an aggregate type means
the allocation is the struct's own memory image. Pointer relocations in
the struct data itself are rejected with a diagnostic on both paths,
in the same style as the existing tuple, array, and enum guards: the
stored bytes of a relocation are an offset into the target allocation,
not an address, and the per-field decoders carry no provenance map to
resolve them.

Also report the bounds-check failure in build_const_from_bytes without
re-adding the offsets unchecked in the message.
@nihalpasham
nihalpasham force-pushed the fix/aggregate-constant-field-offsets branch from f5fb360 to 998afa1 Compare July 23, 2026 12:01
@nihalpasham

Copy link
Copy Markdown
Collaborator

Thanks for the PR

I layered maintainer commits on top:

  • Dropped the tuple hunk in favor of fix(mir-importer): lower tuple array constants with rustc layout #383's stricter version (it cross-validates offsets against dialect metadata), so this PR is now purely the struct half. Neither PR subsumed the other; together they cover both aggregate kinds.
  • translate_struct_constant now decides by-ref indirection by the constant's Rust type instead of by "has provenance". That fixes a regression in the original revision (every promoted &struct constant, the &(8..16) shape, hit the layout helper's Primitive rejection and stopped compiling) and closes a pre-existing silent miscompile (a by-value struct constant with a pointer field had its own bytes replaced by the pointee's). Pointer relocations in struct data are now rejected loudly, matching the tuple, array, and enum guards, with an error example pinning the diagnostic in the smoketest error lane.
  • The example gained the previously dead repr(C) trailing-field read and two promoted-&Range fields, so both decode paths (direct and by-ref) are pinned on hardware.
  • The final diff surfaced two remaining silent-wrong by-ref shapes, now also rejected loudly: a reference-to-struct constant pointing at a non-zero interior offset, and a promoted pointee that itself contains pointer relocations.

Validated: 810 importer tests, the full workspace suite, padded_constants (21 fields, 63 threads) on an RTX 5090, and the error lane. Closes #393.

…railing field

Add error_struct_constant_provenance (registered in the smoketest error
lane) so a struct constant holding a reference fails loudly instead of
decoding relocation bytes as an address. Wire the previously dead
take_repr_c(_, 2) arm into padded_constants so the #[repr(C)] trailing
field after interior padding is read on the device, and record the
struct-constant layout rules in the supported-features appendix.
…by-ref constant paths

Two remaining silent-wrong shapes in by-ref constant decoding now fail
loudly. A reference-to-struct constant whose pointer stores a non-zero
offset into its target allocation was decoded from byte zero, reading
every field from the wrong base; the offset is now read the same way
the scalar pointer path reads it, and interior references are rejected.
And on the promoted-constant materializer path, a pointee that itself
contains pointer relocations had those placeholder bytes decoded as
addresses; the target allocation's provenance is now checked before any
byte decoding, matching the struct, tuple, array, and enum guards.
Plain promoted literals like &77 and pointer-free aggregates behind a
reference are unaffected.
The compile_to_ptx fake-tool tests intermittently failed toolchain
resolution with 'llc --version did not run successfully'. A test that
forks concurrently can duplicate the script's briefly-open write fd
into its child, and until that child execs, running the fresh script
fails with ETXTBSY. Probe each staged tool until it executes so no
toolchain-resolution assert can observe the window. This pre-existing
flake hit both local runs and this PR's CI, so the fix rides along.
@nihalpasham
nihalpasham force-pushed the fix/aggregate-constant-field-offsets branch from 998afa1 to 56eb8ec Compare July 23, 2026 12:19
@nihalpasham
nihalpasham merged commit 124595d into NVIDIA:main Jul 23, 2026
33 checks passed
@alejandro-soto-franco
alejandro-soto-franco deleted the fix/aggregate-constant-field-offsets branch September 9, 2026 17:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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) miscompile Produces incorrect PTX/IR (wrong generated code) tests Adds or improves test coverage

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Aggregate constants with padding are silently miscompiled: fields are read at packed offsets

2 participants