Skip to content

fix(codegen): compile step_by by translating Pat types and rebuilding niched Option aggregates - #64

Merged
nihalpasham merged 8 commits into
NVIDIA:mainfrom
g-ampo:fix/issue-21-step-by-codegen
May 18, 2026
Merged

nihalpasham merged 8 commits into
NVIDIA:mainfrom
g-ampo:fix/issue-21-step-by-codegen

Conversation

@g-ampo

@g-ampo g-ampo commented May 15, 2026

Copy link
Copy Markdown
Contributor

Fixes #21.

for i in (a..b).step_by(s) compiles and runs after this. Verified on a real GPU: the step_by kernel and an equivalent while-loop kernel produce identical sums for all 32 threads and match host-computed expected values.

Issue

Two compiler gaps, exposed by StepBy::next after MIR inlining:

  1. TyKind::Pat was unsupported in the importer. core encodes NonZeroUsize as Pat<usize, 1..=usize::MAX>, so importer bailed before reaching lowering.
  2. After teaching the importer about Pat, mir-lower emitted bitcast i64 to { i8, { { i64 } } } for rustc's Transmute usize -> Option<NonZeroUsize>. rustc treats that Option as a niche-optimised 8-byte scalar (0 = None, non-zero = Some(x)); MirEnumType lowers it to the un-niched aggregate. A bitcast across the scalar/aggregate boundary is invalid LLVM and showed up as invalid cast opcode from llc.

Fix

  • mir-importer/.../types.rs: lower RigidTy::Pat(base, _) as the base type, with an in-source note on the layout assumption.
  • mir-importer/.../rvalue.rs: when a Transmute targets a niche-optimised enum, attach the niche encoding (niche_start, niche_variant_idx, untagged_variant_idx) as attributes on the cast op, read straight from ty.layout().
  • mir-lower/.../cast.rs: for scalar -> struct casts, rebuild the un-niched aggregate explicitly using those attributes: icmp eq val, niche_start -> select for the discriminant, plus a nested insertvalue that lands the payload at the deepest scalar slot of the variant struct. if the importer did not classify the destination as niched, we error out rather than fall through to an invalid bitcast.
  • dialect-llvm/.../export.rs: emit SelectOp in the LLVM IR exporter. The op was registered but unprinted, so the new lowering needed it.
  • examples/step_by/: positive regression with the step_by kernel and a while-loop control.

The discriminant computation is driven by the niche encoding rustc hands us, so this is not limited to niche_value = 0: any single-niche enum that fits in a scalar (Option<NonZeroT>, Option<&T>, Option<NonNull<T>>, Option<Box<T>>, Option<bool>, Option<char>, ...) takes the same path.

g-ampo and others added 8 commits May 18, 2026 15:50
Sibling regression for issue NVIDIA#21. step_by exercises the integer-source
form of the niched-enum Transmute (Option<NonZeroUsize> -> { i8, {{i64}} });
this kernel exercises the pointer-source form (Option<&T> -> { i8, { ptr } })
via an explicit mem::transmute::<*const u32, Option<&u32>>.

Currently fails at IR construction time with a pliron verifier error:

    Value being inserted / extracted does not match the type of the
    indexed aggregate
    v248 = llvm.insert_value v247[0], v215 : llvm.struct
        <{ builtin.integer i8, llvm.ptr addrspace(0) }>

because the existing src_is_ptr && dst_is_struct branch in
emit_pointer_cast was written for fat-pointer construction (field 0 = ptr)
and assumes the destination's field 0 is pointer-typed. For a niched enum
field 0 is the i8 discriminant, so the insertvalue is type-invalid.

Committed before the fix so the regression is recorded; subsequent
commits in this branch make the example pass.
Replaces the string-keyed `niche_start` / `niche_variant_idx` /
`untagged_variant_idx` IntegerAttrs that PR NVIDIA#64 attached to MirCastOp
via raw `attributes.0.insert` calls with a typed pliron attribute.

* `NicheEncodingAttr { niche_start: u64, niche_variant_idx: u32,
  untagged_variant_idx: u32 }` declared with #[pliron_attr], registered
  in the dialect, and listed in `MirCastOp`'s `attributes = (...)` slot
  so pliron generates `get_attr_niche_encoding` /
  `set_attr_niche_encoding` accessors.
* MirCastOp::verify rejects `niche_encoding` on any non-Transmute cast,
  pinning the contract in one place.
* `niche_start` stored as `u64` rather than the i64 PR NVIDIA#64 used: niched
  scalars are at most 64 bits wide, so we lose no information and stop
  spuriously rejecting niches with the top bit set.

This is the pliron-shaped fix for nit NVIDIA#2 in the PR review thread: no
more cross-crate string contract, no "keep in sync with cast.rs"
comment, one typed accessor per side.
Drops the hand-rolled `set_niche_transmute_attrs` helper and its three
private string constants (`NICHE_START_ATTR`, `NICHE_VARIANT_IDX_ATTR`,
`UNTAGGED_VARIANT_IDX_ATTR`) in favour of pliron's macro-generated
`cast_op.set_attr_niche_encoding(ctx, NicheEncodingAttr { ... })`.

Carries `niche_start` as `u64` to match the new attribute. Rejects
niches with bit patterns wider than 64 bits up front with a clear
"not supported" error instead of silently truncating to i64.
…ct->scalar

Three layered fixes on top of PR NVIDIA#64's cast lowering.

1. Niche path runs first in emit_pointer_cast (was a late else-if):
   if the importer attached a `niche_encoding` attribute and the
   destination is a struct, take the niche reconstruction branch
   regardless of source type. This stops `Option<&T>` /
   `Option<NonNull<T>>` / `Option<Box<T>>` Transmutes from being
   miscompiled by the older `src_is_ptr && dst_is_struct` arm, which
   was written for fat-pointer construction and would put the source
   pointer into field 0 (the discriminant slot in a niched enum).

2. emit_scalar_to_niched_enum now accepts pointer-scalar sources, not
   just integer scalars. The discriminant comparison is built in the
   source's own type (icmp eq ptr %src, inttoptr i64 niche_start),
   which folds to `null` for the niche_start == 0 case rustc emits
   today. Reads the niche encoding through the new typed getter
   `MirCastOp::get_attr_niche_encoding`; the old string-keyed
   `read_niche_info` helper is gone.

3. emit_struct_to_scalar gains a size guard. The previous version did
   alloca + store + load with no check that the destination scalar
   width matched the deepest scalar inside the source aggregate; a
   mismatch would silently truncate or pull padding bytes. We now
   walk the single-field newtype chain (capped at MAX_NEWTYPE_DEPTH),
   compare widths, and bail loudly with a "size mismatch" diagnostic
   if they differ or if the aggregate is not a single-scalar wrapper.

Also: replaced the magic `path.len() > 8` cap in `deep_scalar_index_path`
with the named `MAX_NEWTYPE_DEPTH` const and reordered its checks so
the width-equivalent shortcut runs in the same iteration as the
pointer-equality check.

Doc table at the top of the file updated to reflect the new dispatch
order.

Verified locally:
* step_by example: PASS (integer-source niche, regressionn from PR NVIDIA#64).
* option_ref_transmute example: PASS (pointer-source niche, the gap
  this commit closes).
* vecadd, sharedmem, cast_tests, hashmap: PASS (smoke test).
@nihalpasham
nihalpasham force-pushed the fix/issue-21-step-by-codegen branch from ed0fd9a to 8909b30 Compare May 18, 2026 12:16

@nihalpasham nihalpasham left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the PR. It needed some additions, which I've layered on top of your branch

The importants ones:

  • Pointer-source niche transmutes: Your fix handled the integer-source case (Option<NonZeroUsize> -> aggregate) but missed the pointer-source case (Option<&T>, Option<NonNull<T>>, Option<Box<T>>). I added a sibling example (option_ref_transmute) that reproduced the bug as a pliron verifier error, reordered the dispatch in emit_pointer_cast so the niche reconstruction runs first whenever the importer attached a niche encoding, regardless of whether the source is an integer or a pointer. The helper now also accepts pointer sources directly (icmp eq ptr %src, inttoptr i64 niche_start).

  • Typed NicheEncodingAttr instead of string-keyed attributes: The three loose IntegerAttr entries (niche_start, niche_variant_idx, untagged_variant_idx) glued together by a "keep in sync" string contract between importer and lowering are replaced with a proper #[pliron_attr] struct declared in dialect-mir, wired onto MirCastOp via its attributes = (...) slot. Both sides now use the macro-generated get_attr_niche_encoding / set_attr_niche_encoding. You can check how cast_kind did this before. Removed the cross-crate string contract, the hand-rolled read_niche_info / set_niche_transmute_attrs helpers, and the "keep in sync" comment.

  • Size guard on struct -> scalar: The reverse direction (emit_struct_to_scalar) was doing an unchecked alloca + store + load, which would silently truncate or pull padding bytes on any size mismatch. It now walks the single-field newtype chain, compares widths, and errors loudly with a "size mismatch" diagnostic if they differ. Same loud-failure as the scalar -> struct direction.

Also just some nits that were addressed in this PR

  • niche_start is now carried as u64 instead of i64, so we drop the bogus overflow rejection on niches with the top bit set.
  • The magic path.len() > 8 cap in deep_scalar_index_path is now a named MAX_NEWTYPE_DEPTH = 8 constant with a comment explaining the choice.
  • read_niche_info is a one-liner now, it just forwards to the typed getter.
  • MirCastOp::verify rejects niche_encoding on non-Transmute casts, so the contract is enforced in one place.

@nihalpasham nihalpasham added bug Something isn't working miscompile Produces incorrect PTX/IR (wrong generated code) codegen Device code-generation pipeline (Rust MIR to IR to PTX) labels May 18, 2026
@nihalpasham
nihalpasham merged commit 7505c7a into NVIDIA:main May 18, 2026
@g-ampo
g-ampo deleted the fix/issue-21-step-by-codegen branch May 18, 2026 15:05
shaneholloman pushed a commit to shaneholloman/cuda-oxide that referenced this pull request Jun 10, 2026
Under -O, MIR const-folds the None arm of
`Option<&u32>::unwrap_or(&77)` into an Operand::Constant of type
`&u32`: a ConstantKind::Allocated whose data bytes are a pointer-sized
placeholder and whose provenance entry names the allocation holding the
literal 77.

The pointer-constant arm of translate_operand only followed that
provenance when the pointee was a MirStructType (arrays take a separate
path). Every other pointee fell through to the raw-pointer path, which
parses the placeholder bytes as an address and emits
MirConstantOp(0) + inttoptr, i.e. a null pointer. The subsequent
dereference became `load i32, ptr null`: an illegal memory access
(CUDA error 700) at runtime, and under opt -O2 the UB even deletes the
out[1] store outright.

Fix: after the existing struct branch, follow the provenance for ALL
remaining pointee types. Resolve the entry via GlobalAlloc
(GlobalAlloc::Memory directly, GlobalAlloc::Static via
eval_initializer), honor the byte offset that the pointer's own data
bytes encode into the target allocation, materialize the pointee
through the existing shared constant-from-bytes path
(translate_constant_value_from_bytes: integer / f16 / f32 / f64 /
enum / ZST / nested pointer), and take its address with MirRefOp
exactly like the struct branch. mem2reg/lowering turn the MirRefOp
into alloca + store + address, which is sound because promoted
constants are immutable.

The raw-pointer fallthrough now only handles constants WITHOUT
provenance (true null / int-to-ptr values). Provenance pointing at a
non-memory allocation (e.g. a function) is a hard translation error
instead of a silent null, matching the array path's existing behavior.

Evidence on the issue repro (compile-only, --arch sm_90):

  before:  %v14 = inttoptr i64 0 to ptr
           %v15 = load i32, ptr %v14, align 4
  after:   %v14 = alloca i32, align 4
           store i32 77, ptr %v14, align 4
           %v15 = load i32, ptr %v14, align 4

and post-opt the kernel stores [5, 77] as expected.

Issue: NVIDIA#132 (const-operand half; the niche-optimized aggregate half
was issue NVIDIA#64).
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

bug Something isn't working codegen Device code-generation pipeline (Rust MIR to IR to PTX) miscompile Produces incorrect PTX/IR (wrong generated code)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

PTX Codegen Failure: StepBy struct lowering (invalid cast opcode) exposed by missing Pat type translation

2 participants