Skip to content

fix(mir-lower): thread target mode into shared-pointer transmutes - #879

Closed
Ayush7614 wants to merge 1 commit into
NVIDIA:mainfrom
Ayush7614:fix/874-transmute-shared-pointer
Closed

Ayush7614 wants to merge 1 commit into
NVIDIA:mainfrom
Ayush7614:fix/874-transmute-shared-pointer

Conversation

@Ayush7614

Copy link
Copy Markdown
Contributor

Summary

mir-lower rejected every Transmute involving a shared-memory pointer
(addrspace(3)) with a target-mode-dependent-width error. The physical width
is target-dependent: legacy NVPTX/PTX uses 64-bit pointers, while modern NVVM
(libNVVM) uses 32-bit p3:32. With no target mode available at this stage,
the previous code bailed out before choosing a size.

This adds shared_address_space_pointer_width to LoweringOptions and uses it
in llvm_type_size_align and scalar_bit_width so the correct width (4 or 8
bytes) is reported for addrspace(3) pointers. The existing transmute paths
then handle shared-pointer casts correctly, and a width-mismatched cast still
fails with a clear size-mismatch error.

cuda-oxide-codegen::lower_to_llvm derives the width from IntrinsicBackend
(LibNvvm -> 32, LlvmNvptx -> 64), so the plumbing reaches the real codegen
path automatically. rustc-codegen-cuda does not construct LoweringOptions
directly, so it needs no source change.

Fixes #874.

Verification

  • crate::mir-lower: cargo test -p mir-lower green (146 integration + 76 lib tests, 0 failed).
  • New/updated tests in crates/mir-lower/src/convert/ops/cast.rs:
    • transmute_involving_shared_pointer_uses_target_dependent_width (both 32- and 64-bit modes).
    • transmute_shared_pointer_to_wrong_width_integer_is_rejected.
  • cargo test -p cuda-oxide-codegen green except for one pre-existing,
    environment-specific failure (ptx::tests::legacy_opt_failure_warns_but_experimental_mode_fails,
    which invokes /bin/false and fails identically on main without this change).

Scope / caveat (partially verified)

The 32-vs-64-bit selection is keyed off IntrinsicBackend::LibNvvm == modern
NVVM (p3:32). This matches the existing data-layout assumptions in
convert/types.rs, but the final PTX/object correctness of shared-pointer
transmutes on real hardware still needs validation in CI with the CUDA toolkit
and a GPU, which is unavailable in this dev environment.

The transmute lowering rejected any cast involving a shared-memory pointer
(addrspace(3)) because its physical width is target-dependent: legacy
NVPTX/PTX uses 64-bit pointers, while modern NVVM (libNVVM) uses 32-bit
p3:32. With no target mode available at this stage, the previous code bailed
out before choosing a size.

Add `shared_address_space_pointer_width` to `LoweringOptions` and use it in
`llvm_type_size_align` and `scalar_bit_width` so the correct width (4 or 8
bytes) is reported for addrspace(3) pointers. The general transmute paths
then handle shared-pointer casts correctly, and a width-mismatched cast still
fails with a clear size-mismatch error. `cuda-oxide-codegen` derives the width
from `IntrinsicBackend` (LibNvvm -> 32, LlvmNvptx -> 64).

Fixes NVIDIA#874.
@nihalpasham

nihalpasham commented Aug 14, 2026 •

Copy link
Copy Markdown
Collaborator

So as I understand it, this implements issue #874's proposed fix. The problem is with that proposal, not with the execution.

The approach isn't right for three independent reasons:

1. The width isn't knowable at the point the PR reads it.

The pipeline decides between the two NVVM dialects only after lowering has already run:

lowering runs ──────► IR rendered ──────► legacy-vs-modern NVVM picked
(the PR needs                             (4-vs-8 is actually
 the width HERE)                           decided HERE)

So the PR guesses from --emit-nvvm-ir (IntrinsicBackend::LibNvvm), and the guess is wrong for a whole class of builds, because the legacy NVVM data layout is 64-bit in every address space; only modern NVVM has p3:32:

build                                    PR's guess   physical truth
default llc path                         8            8       ok
--emit-nvvm-ir, Blackwell (modern)       4            4       ok
--emit-nvvm-ir, pre-Blackwell (legacy)   4            8       WRONG

2. Even with the right width, it's the wrong ruler.

Rust defines transmute legality by rustc's layout, and rustc sizes every nvptx64 pointer at 8 bytes, shared or not:

// valid Rust: rustc checks 8 == 8, so this must compile on every target
let p: *mut u32 = transmute(bits as usize);

// this PR in p3:32 mode: re-measures the shared pointer at 4 bytes,
// rejects with "size mismatch: 8 vs 4"

That rejected round trip is the very thing #874's acceptance criteria ask for on the p3:32 target. Meanwhile the added unit test transmutes i32 <-> ptr(3), a 4-byte pairing rustc can never emit, since Rust sizes that pointer at 8. So the check rejects real code and accepts impossible code.

3. It turns a loud error into silently wrong bytes. This is the disqualifying one.

main's blanket guard was crude but safe. With it removed, an aggregate transmute takes the memory round-trip (store to a stack slot, load back), which captures the pointer's raw addrspace(3) bytes: an offset into the shared window, not an address. The first shared allocation sits at offset 0:

scalar path (already correct on main, genericizes first):
  shared_ptr as usize                      -> 0x7f31_4000_0000   generic address

aggregate path (was a loud error, now compiles):
  transmute::<Wrapper, u64>(Wrapper(ptr))  -> 0x0                raw offset, reads as NULL

Two casts Rust considers identical return different integers, and one of them manufactures null-looking values from valid pointers. This is the hazard emit_ptr_to_int's generic-address invariant exists to prevent.

Two further notes:

  • llvm_type_size_align gets repurposed as a physical-width oracle, but its callers (union storage, global validation, layout-divergence checks) and its sibling get_type_size still assume rustc's 8-byte pointers, so two layout oracles disagree about the same type;
  • the PR body cites a test (transmute_shared_pointer_to_wrong_width_integer_is_rejected) that is not present at the head commit.

The sound fix needs no width at all:

  • keep size checks on rustc layout (pointers are 8 bytes, on every target);
  • bridge shared-pointer scalars through the generic address space:
shared -> int    addrspacecast to generic, then ptrtoint    (the existing emit_ptr_to_int invariant)
int -> shared    inttoptr to generic, then addrspacecast
ptr <-> ptr      one addrspacecast
  • keep aggregates loudly rejected: their memory image is the target-dependent part.

That version is implemented and verified:

  • mir-lower green with four new transmute tests, none branching on backend or dialect mode;
  • a new shared_ptr_transmute example passes on an RTX 5090 through the llc path, the unoptimized path, and the modern-NVVM p3:32 path this PR's heuristic targeted, with no width knowledge at lowering time.

It lands as its own PR shortly; closing this one with already-fixed. Thanks for taking #874 on: the issue's own proposed-fix text is what sent this down the wrong road, and it gets corrected there too.

@nihalpasham nihalpasham added bug Something isn't working IR-lowering Lowering between dialects (dialect-mir to LLVM dialect) already-fixed Resolved on a newer commit or branch; no action needed labels Aug 14, 2026
nihalpasham added a commit that referenced this pull request Aug 14, 2026
…address space (#884)

* fix(mir-lower): lower scalar shared-pointer transmutes through the generic address space

A Transmute touching a shared-memory (addrspace(3)) pointer was rejected
wholesale because the pointer's physical width is target-mode dependent
(64-bit PTX/legacy, 32-bit modern NVVM p3:32) and lowering runs before a
data layout is chosen. The scalar forms never needed the physical width:
Rust transmute legality is defined by rustc layout, where every nvptx64
pointer is 8 bytes, and the codebase's own emit_ptr_to_int invariant
already makes a shared pointer's Rust-visible integer form its 64-bit
GENERIC address, never a raw space-local offset.

Narrow the rejection to the transmutes that would actually observe
physical pointer bytes, and let the scalar arms handle the rest through
the generic-address bridge:

- shared ptr -> integer: addrspacecast to generic, then ptrtoint
  (already handled by the early emit_ptr_to_int return; unchanged)
- integer -> shared ptr: inttoptr to generic, then addrspacecast into
  the shared space (emit_int_to_ptr already implemented this; the
  blanket guard just never let it run)
- ptr <-> ptr across address spaces: direct addrspacecast
- ptr -> non-integer scalar: the intermediate ptrtoint now also goes
  through emit_ptr_to_int, so the invariant holds on every arm

Aggregate transmutes containing shared pointers (including transparent
wrappers, which stay llvm.struct at this stage) remain intentionally
unsupported: their memory round-trip would store the pointer's physical
bytes at an unknowable width and leak raw shared-local offsets into
Rust-visible bytes. The rejection now sits on the memory-round-trip
dispatch points and names the types with an actionable diagnostic.

Behavior is identical under both NVVM dialects and the llc path: no
LoweringOptions changes, no width plumbing.

New GPU example shared_ptr_transmute round-trips a shared pointer
through usize and through a generic pointer alias, then writes and reads
shared memory through the reconstructed pointers; verified on sm_120
through the default llc path, CUDA_OXIDE_NO_OPT=1, and the modern NVVM
path (--emit-nvvm-ir --arch=sm_120, p3:32 datalayout). Unit tests cover
usize -> shared, shared <-> generic, and the aggregate rejection.

Closes #874. Supersedes #879.

* style(shared_ptr_transmute): allow the ptr-cast clippy lint on the four transmute helpers

The as-cast form clippy suggests lowers through the pointer-cast path;
Transmute lowering is the path this example exists to regression-test.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

already-fixed Resolved on a newer commit or branch; no action needed bug Something isn't working IR-lowering Lowering between dialects (dialect-mir to LLVM dialect)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Transmute involving a shared-memory pointer is rejected (target-mode-dependent layout)

2 participants