Skip to content

Preserve Rust reference kind and exclusivity through MIR import and lowering #413

Closed

Description

@nihalpasham

Summary

cuda-oxide currently represents Rust references and raw pointers identically once their pointee type, source mutability, and address space match:

&mut T   -> mir.ptr<T, mutable: true, ...>
*mut T   -> mir.ptr<T, mutable: true, ...>

&T       -> mir.ptr<T, mutable: false, ...>
*const T -> mir.ptr<T, mutable: false, ...>

Both RigidTy::Ref and RigidTy::RawPtr use the same pointer translation. MirPtrType records the pointee, a mutability bit, and the address space, but not whether the value originated as a raw pointer, shared reference, or unique reference.

The mutability bit cannot by itself mean “exclusive”: Rust permits aliasing *mut T pointers, while &mut T carries unique-borrow requirements. MIR Retag statements are also currently skipped, and MIR-to-LLVM pointer conversion retains only the address space.

Current impact

We do not currently have a demonstrated miscompile from this information loss.

The LLVM exporter intentionally does not emit Rust-derived noalias, readonly, dereferenceable, or related pointer attributes. Current lowering also does not use MirPtrType::is_mutable as proof of exclusivity. LLVM therefore handles these pointers conservatively today.

Dropping exclusivity information is not itself incorrect for valid programs while every downstream pass remains conservative. The gap becomes actionable if we later:

  • emit noalias or other Rust-derived LLVM attributes;
  • introduce alias-aware optimizations;
  • verify reference use in the MIR dialect;
  • rely on ordinary Rust reference rules when lowering GPU-specific APIs.

Motivating example from PR #350

PR #350 contains this shared-memory access:

static mut TILE: SharedArray<[f32; N], 1> = SharedArray::UNINIT;

let i = thread::index_1d().get();

if i < N {
    unsafe { TILE[0][i] = input[i] };
}

In simple terms, the fully monomorphized MIR first performs the outer mutable indexing:

let row: &mut [f32; N] =
    IndexMut::index_mut(&mut TILE, 0);

row[i] = input[i];

Every GPU thread requests mutable access to outer index 0, producing overlapping &mut [f32; N] references. Each thread then selects a different inner element i, so the final physical stores do not overlap.

This distinction matters because SharedArray::index_mut requires that no other thread concurrently access the same index. Under that documented contract, the outer access to index 0 is the relevant operation even though the final inner stores are disjoint.

The example runs correctly today, and Compute Sanitizer racecheck reports no hardware race, because the lowered code performs disjoint stores and does not retain Rust reference exclusivity. That makes it a useful concrete example of the semantic information currently lost.

PR #350 did not create this gap. Its shared-to-generic address-space unsizing fix is independent and merely exposed a clear example.

Desired outcome

Preserve enough information in the MIR dialect to distinguish at least:

raw const pointer
raw mutable pointer
shared reference
mutable/unique reference

We do not necessarily need to implement the complete Rust aliasing model or make Retag a runtime operation. We should first define which reference guarantees the MIR dialect promises to retain and where they may be intentionally erased.

At minimum:

  • Document that MirPtrType::is_mutable is not proof of uniqueness.
  • Do not derive noalias or equivalent assumptions from is_mutable.
  • Decide how reference kind is propagated through projections, reborrows, casts, slices, and calls.
  • Decide how GPU-specific abstractions such as SharedArray interact with ordinary Rust reference rules.
  • Audit Retag handling and document whether any of its information is needed in the compiler representation.
  • Resolve this design before introducing Rust-derived alias metadata or alias-based optimizations.

Acceptance criteria

  • The intended reference/provenance model of the MIR dialect is documented.
  • Tests show how &mut T and *mut T are represented and which guarantees survive lowering.
  • No pass treats pointer mutability as proof of uniqueness.
  • The SharedArray<[T; N], 1> example above has a documented interpretation.
  • Any future noalias or related LLVM metadata is based on preserved, auditable reference information.

Related

  • #34 identifies the same general boundary for mutable kernel parameters and notes that noalias is not currently emitted.
  • #151 demonstrates how invalid reference usage becomes visible when readonly or noalias metadata is introduced.

Activity

  1. added
    safety
    codegen
    IR-lowering
    tracking
    on Jul 20, 2026
  2. vyncint commented on Aug 11, 2026

    @vyncint
    Contributor

    Measured the prize, since the issue says the gap "becomes actionable if we later emit noalias or other Rust-derived LLVM attributes" but not what it is worth. On an A10G (sm_86, driver 595.71.05), it is worth a lot more than I expected, and the blocked pattern is an ordinary one.

    The pattern that pays for the missing information

    A field-wise copy — the way you would naturally write it:

    #[repr(C, align(16))]
    struct Quad16 { a: f32, b: f32, c: f32, d: f32 }
    
    #[kernel]
    pub fn copy(src: &[Quad16], mut dst: DisjointSlice<Quad16>) {
        let idx = thread::index_1d();
        let i = idx.get();
        if let Some(o) = dst.get_mut(idx) {
            o.a = src[i].a;
            o.b = src[i].b;
            o.c = src[i].c;
            o.d = src[i].d;
        }
    }

    emits four narrow loads and four narrow stores, even though the element promises 16-byte alignment and #746/#777/#795 stamp that alignment onto the addresses. The loads cannot be grouped, because moving the load of .b above the store to o.a needs a proof that dst does not overlap src, and there is none.

    Hand-patching the IR isolates it

    Same module, same opt -O2 and llc -mcpu=sm_86, one edit — noalias on the two pointer parameters and nothing else:

    loads stores
    as cuda-oxide emits 4 x ld.global.b32 4 x st.global.b32
    + noalias by hand 1 x ld.global.nc.v4.b32 1 x st.global.v4.b32

    Two wins from the one attribute: 128-bit vectorization, and the read-only .nc path, which LLVM will only take when it can prove nothing writes the memory during the kernel.

    What it costs today

    Restructuring the source to let s = src[i]; before the four field stores lets the loads group, which reaches ld.global.v4 (but never .nc — zero occurrences anywhere in the module). That workaround is a clean A/B for the vectorization half, 1M threads, 30 timed launches after 5 warmup:

    kernel shape us/launch
    streaming copy, interleaved 4+4 narrow 94.5
    streaming copy, grouped 1+1 v4 71.1 1.33x
    cache-resident copy, interleaved 4+4 narrow 1313.1
    cache-resident copy, grouped 1+1 v4 268.4 4.89x

    Streaming gains least because the same bytes still reach memory; the cache-resident kernel is bound by access issue, which is where collapsing eight instructions into two shows up. noalias should beat the grouped column too, since it adds .nc on top, though I have not timed that half — producing it needs the attribute this issue is about.

    Not proposing a patch

    I am not sending one, because the summary here is right about why: &mut T and *mut T both arrive as mir.ptr<T, mutable: true>, so there is nothing to key noalias off that would not also mark a legally-aliasing raw pointer. Emitting it from the current type information would be unsound rather than merely optimistic. Filing this as evidence for sizing the reference-kind work, not as a request to shortcut it.

    Two smaller notes from the same probing session, in case they are useful:

    • The alignment machinery already reaches 128 bits: a grouped access on a repr(C, align(16)) element gives one ld.global.v4.b32 / st.global.v4.b32, so no separate v4 work is needed.
    • A natural-alignment (align 4) control stays at four narrow accesses in every variant, as it must.
  3. uurl commented on Aug 20, 2026

    @uurl
    Contributor

    I reworked the transition policy around one distinction: semantic establishment vs. representation normalization.

    Proposed policy:

    Context Source Destination Policy
    Rvalue::Ref any valid pointer provenance SharedRef / UniqueRef Trust rustc result type
    Rvalue::AddressOf any valid pointer provenance RawConst / RawMut Trust rustc result type
    Explicit rustc pointer coercion/cast concrete concrete Trust the MIR operation/result type
    Compiler-recognized operation with a typed Rust result any valid carrier declared concrete kind Trust the rustc-declared result type
    Projection / address-space normalization concrete same concrete Preserve
    Generic normalization concrete Erased Allow forgetting
    Generic normalization Erased concrete Reject
    Generic normalization concrete A concrete B Reject
    Local storage Erased concrete Reject
    Local storage concrete A concrete B Reject

    The key rule is that a concrete pointer/reference kind can only be established at a Rust-typed semantic boundary.

    This prevents laundering such as:

    SharedRef -> Erased -> UniqueRef
    

    while still allowing legitimate reborrows such as:

    RawMut -> UniqueRef
    

    at Rvalue::Ref, where rustc's declared result type is authoritative.

    For compiler-recognized APIs such as SharedArray::as_ptr, as_mut_ptr, and as_raw_mut_ptr, the intrinsic expansion now uses the rustc-declared result type directly instead of relying on local storage to recover kind.

    The implementation is in #1062.

    MirPointerKind remains semantic-only during lowering and does not introduce noalias, readonly, or other Rust-derived LLVM alias metadata. Retag remains a codegen no-op.

  4. added this to the cuda oxide v0.3.0 milestone on Oct 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    IR-loweringcodegenmaintainer-ownedsafetytracking

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions