Repository navigation
Description
I hit this building a struct inside a kernel and reading a field back — the value came back wrong, with no error at all. On other structs the same thing fails loudly instead, in a few different shapes depending on version:
# LLVM module verification:
Value being inserted / extracted does not match the type of the indexed aggregate
# or (v0.2.0):
Lowering failed: IntToInt: source is not an integer
# or (v0.1.0):
Compilation error: invalid input program
So it's the same underlying bug showing up as either a wrong value (scary) or a confusing build error. It doesn't need generics or a custom trait — the kernel just has to build a repr(Rust) struct whose fields rustc reorders/pads.
Reproduce
The trigger is a repr(Rust) struct whose fields rustc reorders, with a multi-word align-4 enum field that forces interior [N x i8] padding. To also hit the silent identity-fallback path, put the generic struct in a sibling crate so its MirStructType is reconstructed across the crate boundary at monomorphization.
arena_core (a small no_std crate):
#![no_std]
#[derive(Copy, Clone)]
pub enum Layout { Aos, Soa, AoSoA(u32) } // payload variant -> align-4, multi-word enum
pub trait CellStore {
fn bump(&self, n: u32) -> u32;
fn store(&self, idx: u32, val: u32);
}
// declaration order: store, cap, stride, layout. rustc reorders in memory
// (fat-pointer store first, then u32s, then the enum) -> decl index != LLVM
// field index, and the lowered struct gets [N x i8] padding after the enum.
pub struct ScratchArena<S: CellStore> { store: S, cap: u32, stride: u32, layout: Layout }
impl<S: CellStore> ScratchArena<S> {
pub fn new(store: S, cap: u32, stride: u32, layout: Layout) -> Self {
Self { store, cap, stride, layout }
}
pub fn alloc(&self) -> Option<u32> {
let s = self.store.bump(1);
if s >= self.cap { None } else { Some(s) }
}
pub fn write(&self, slot: u32, field: u32, val: u32) {
let i = match self.layout { // reads layout, cap, stride, store off &self
Layout::Soa => field.wrapping_mul(self.cap).wrapping_add(slot),
_ => slot.wrapping_mul(self.stride).wrapping_add(field),
};
self.store.store(i, val);
}
}
#[inline(never)] // keep the receiver a pointer-to-struct across the crate boundary
pub fn alloc_and_fill<S: CellStore>(a: &ScratchArena<S>) {
if let Some(slot) = a.alloc() {
a.write(slot, 0, slot);
a.write(slot, 1, slot.wrapping_mul(10));
}
}The kernel supplies a CellStore backed by a device buffer + atomic cursor, builds the arena, and drives it through the &self methods:
#[kernel]
pub fn fill(cursor: &[u32], data: &[u32], params: &[u32]) {
let cur = unsafe { &*(cursor.as_ptr() as *const DeviceAtomicU32) };
let store = DeviceStore { cursor: cur, data }; // impl CellStore: bump = atomic fetch_add, store = raw write
let arena = ScratchArena::new(store, params[0] /*cap*/, params[1] /*stride*/, Layout::Soa);
alloc_and_fill(&arena); // every field access here goes through the mis-mapped index
}Under Layout::Soa, slot s's two fields should land at data[s] and data[cap + s]. Pre-fix the build fails LLVM verification — an insert_value whose index lands on the struct's [N x i8] padding field; post-fix all cap slots verify. (The padding-unaware index defect shows even single-crate; the silent identity fallback additionally needs the cross-crate generic above.)
What I found digging in
Root cause (mir-lower / aggregate.rs)
convert/ops/aggregate.rs maps a declaration-order field index to the LLVM-struct field index in four places, and each diverges from the struct the type converter actually builds (build_struct_with_explicit_padding):
convert_extract_field— when the operand'sMirStructTypeisn't in the type-history, it falls back to a silent identity mapping (llvm_index = decl_index). On a reordered struct that extracts a different field. This is the dangerous, silent path.convert_insert_field— same silent identity fallback.convert_field_addr— honours reorder but not the[N x i8]padding, so the GEP index is off by the pad count.convert_construct_struct— builds the padded LLVM struct but inserts fields counting only real fields, ignoring pad slots → off-by-pad indices.
cast.rs (the IntToInt message) and the importer are fine — they just forward the wrong operand they were handed.
What worked for me: one padding/reorder-aware llvm_field_index helper that all four sites go through, and replacing the silent identity fallback with recover-or-error (only allowing identity for an already-lowered LLVM struct, whose order is final — slices/fat pointers — otherwise erroring instead of guessing). That last part is in the same spirit as #27 (no silent miscompiles).
Related
- a kernel which accepts a reference to an application struct seems to cause illegal memory access #29 (kernel taking
&AppStruct→ illegal memory access) — this might actually be the same root cause surfacing at runtime; worth re-testing a kernel which accepts a reference to an application struct seems to cause illegal memory access #29's repro against the fix before claiming it. - MIR importer lowers explicit repr enum discriminants with the wrong width #118/fix(mir-importer): honour explicit repr integer widths for enums #119 (enum discriminant width) and Rvalue::Ref lowering can drop runtime Index projections #120/fix(mir-importer): preserve runtime Index projections in Rvalue::Ref #121 (dropped Index projection) are the same family — "layout/projection metadata goes stale" — but different sites; not duplicates.
- match xs[i] over an array of an enum fails to import (Downcast on non-ADT type: Array) #131 (my other issue, enum-in-array match) is the same family in the importer's type-narrowing.
Suggested labels: miscompile, codegen, safety.
I've got the fix + this repro on a fork (DCO-signed) and can open a PR. (Heads-up for PR time: I still owe a cargo fmt pass and want to add a hardware-free unit test for the index helper.)
Activity
[-]Device codegen mis-indexes reordered / padded `repr(Rust)` struct fields[/-][+]kernel silently reads the wrong struct field on the GPU (reordered/padded repr(Rust) struct)[/+]feat(dialect-mir): carry rustc total_size/abi_align on MirEnumType
fix(mir-lower): single source of truth for struct field -> LLVM slot …
test(mir-lower): unit-test the struct slot map + add issue NVIDIA#128 …
feat(mir-lower): byte-faithful enum lowering via an enum slot map
fix: support CUmemLocation layout across CUDA 13.0–13.2 (NVIDIA#128)