Skip to content

feat(mir): preserve Rust pointer and reference kind - #1062

Closed
uurl wants to merge 5 commits into
NVIDIA:mainfrom
uurl:feat/mir-reference-kind
Closed

uurl wants to merge 5 commits into
NVIDIA:mainfrom
uurl:feat/mir-reference-kind

Conversation

@uurl

@uurl uurl commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Part of #413.

This is a fresh implementation following the design feedback from #1040.

Summary

Preserve the Rust source-level pointer/reference category through MIR import and lowering.

This adds MirPointerKind to distinguish:

  • &T -> SharedRef
  • &mut T -> UniqueRef
  • *const T -> RawConst
  • *mut T -> RawMut
  • compiler-generated/storage pointers -> Erased

The kind is retained by MirPtrType and MirSliceType, propagated through MIR import, and intentionally erased during LLVM lowering.

Motivation

The MIR dialect previously preserved pointer mutability and address space, but not whether a pointer originated from a Rust reference or a raw pointer.

That distinction matters if later passes want to reason about Rust aliasing semantics. In particular, *mut T and &mut T are both writable pointers, but only the latter carries Rust uniqueness semantics.

This change records that distinction without introducing LLVM alias metadata or changing the physical pointer representation.

Transition policy

Pointer-kind changes are restricted according to the semantic operation that produced the value.

Explicit Rust semantic boundaries

Operations whose result type is authoritative in rustc may establish a new concrete pointer kind:

  • Rvalue::Ref
  • Rvalue::AddressOf
  • explicit rustc pointer coercions/casts
  • compiler-recognized operations with a known Rust return type, such as SharedArray::as_ptr, as_mut_ptr, and as_raw_mut_ptr

This allows legitimate transitions such as:

RawMut -> UniqueRef

for a reborrow like:

let r: &mut T = unsafe { &mut *raw };

Generic representation normalization

Generic address-space, storage, projection, and representation normalization may:

Concrete -> same Concrete
Concrete -> Erased

but may not perform:

Erased -> Concrete
Concrete A -> Concrete B

This prevents laundering sequences such as:

SharedRef -> Erased -> UniqueRef

Local storage does not establish new Rust pointer semantics.

SharedArray

SharedArray pointer-producing intrinsics now use their rustc-declared result type instead of producing an Erased generic pointer and relying on later storage normalization.

Therefore:

SharedArray::as_ptr         -> RawConst
SharedArray::as_mut_ptr     -> RawMut
SharedArray::as_raw_mut_ptr -> RawMut

while CUDA address space remains independent from Rust pointer kind.

Lowering

MirPointerKind is semantic-only and is deliberately erased during MIR-to-LLVM conversion.

This PR does not infer or emit:

  • noalias
  • readonly
  • dereferenceable
  • other LLVM alias/provenance metadata

Any future use of Rust aliasing facts should be introduced separately with an audited policy.

Retag also remains a codegen no-op; this change does not attempt to model dynamic Stacked Borrows or Tree Borrows state.

Validation

Validated with:

cargo fmt --all -- --check
cargo clippy --workspace --all-targets -- -D warnings

cargo test -p dialect-mir --all-targets
cargo test -p mir-importer --all-targets
cargo test -p mir-lower --all-targets

cargo oxide build vecadd
cargo oxide build addressof_sharedarray

git diff --check

All checks pass.

The end-to-end vecadd build covers the reborrow case that exposed the overly restrictive transition policy in the previous implementation, while addressof_sharedarray validates pointer-kind propagation through the SharedArray compiler-recognized pointer APIs.

Scope

This PR covers the pointer/reference-kind representation, import, propagation, and lowering portion of #413.

The broader tracking issue should remain open for future provenance and aliasing policy work.

@uurl
uurl force-pushed the feat/mir-reference-kind branch 2 times, most recently from ea576f4 to 1f22538 Compare August 20, 2026 01:12
nihalpasham pushed a commit that referenced this pull request Aug 20, 2026
The docs gate runs `cargo doc` without `--document-private-items`, so it never
renders a private item and never checks the intra-doc links in one. #1014 and
#1042 cleaned `cuda-macros`, `mir-importer/statement.rs` and the codegen
backend's collector; this is one of the four that were left:

    error: unresolved link to `classify_op`
      --> crates/llvm-export/src/export/ops.rs:55

`classify_op` is a `macro_rules!` defined further down the same file, at :138.
A `macro_rules!` macro is in scope only textually after its definition unless
it is exported, so no path resolves from a doc comment above it -- rustdoc says
as much: "`macro_rules` named `classify_op` exists in this crate, but it is not
in scope at this link's location". It becomes a plain code span, and since the
sentence is one step of a four-step contract about this file, it gains "below"
so the reference still points somewhere.

Three of the four remain. One is `make_disjoint_slice_struct` in
`mir-lower/src/convert/ops/aggregate.rs`, which needs only a
`crate::convert::types::` prefix; the other two are `MirFieldAddrOp` and
`MirArrayElementAddrOp` in `mir-importer/src/translator/rvalue.rs`. Both files
are under open pull requests (#1062 and #1064 for the first, #1059 and #1062
for the second), so they are left rather than raced.
`--document-private-items` can join the docs gate once they land.

Verified: `RUSTDOCFLAGS="-D warnings" cargo doc --no-deps
--document-private-items -p llvm-export` reports one unresolved link on `main`
and none with this change. The gate's own invocation passes before and after.
fmt clean.

Comment-only change.

Signed-off-by: Vyncint Ng <[email protected]>
@nihalpasham nihalpasham added soundness-audit Correctness case under active maintainer audit; not cleared for merge yet enhancement New feature or request codegen Device code-generation pipeline (Rust MIR to IR to PTX) IR-lowering Lowering between dialects (dialect-mir to LLVM dialect) labels Aug 20, 2026
@nihalpasham

nihalpasham commented Aug 20, 2026 •

Copy link
Copy Markdown
Collaborator
  • Not a merge call yet. Kinds become part of type identity here and perf(llvm): emit proven Rust reference parameter attrs #1089 builds its noalias emission on top, so this is tagged soundness-audit while I audit the kind policy and the two new trust boundaries myself. The one-way rule itself held up when I attacked it: normalization can preserve or erase a kind but never invent one, and SharedRef -> Erased -> UniqueRef is refused, with a test.

  • Ran the full 216-example corpus; it caught three gaps the unit tests can't see. Fixes are done and validated locally, held back until the audit closes. CI on this head will fail examples-compile on the same three examples, which is the point.

  • Gap 1: intrinsic results can't take their declared kind. DynamicSharedArray::<i8, 128>::get() has no Rust body; the emitter synthesizes the pointer from the shared global, so it's Erased. The local is rustc-typed from the signature, and the ordinary store path refuses the upgrade, as it must:

                 value                          slot
      ┌─────────────────────────┐    ┌─────────────────────────┐
      │ mir.ptr<si8, AS3,       │──► │ mir.ptr<si8, AS3,       │
      │        kind: Erased>    │ st │        kind: RawMut>    │
      └─────────────────────────┘    └─────────────────────────┘
      store_local: Erased -> concrete  REFUSED  -> verifier error
      (mathdx_ffi_test; mcast_barrier_test is the same picture with
       *const u64 in AS7 from map_shared_rank)
    

    The PR's own policy table names intrinsic calls as a kind-establishing boundary (the cuda-device signature declares the result type) but the store epilogue never implemented it. The fix is a store_local_at_rust_boundary used only there: establishes the slot's declared kind, requires identical pointee, refuses projected destinations, so the target type is always a whole rustc-typed local and the laundering path stays closed.

  • Gap 2: the new kind-only cast breaks WGMMA fusion. &mut acc at Rvalue::Ref now emits a cast that lands between the fence and the MMA:

      wgmma_fence
      v' = mir.cast <PtrToPtr> (v)     <- Erased -> UniqueRef, new in this PR
      nvvm.wgmma_mma(v', a, b)            same pointee, same addrspace
      wgmma_commit_group
      wgmma_wait_group<0>
    

    The deferred-accumulator matchers hit an op outside their whitelist and silently declined fusion; wgmma_mma_bf16 then died in lowering. A kind-only retype between thin pointers with the same pointee and address space lowers to nothing, so the region walker and the counted-loop whitelist now look through that one form and nothing wider; an addrspace-changing cast still blocks fusion. Regression test builds this region and asserts the single fused inline-asm statement survives.

  • Gap 3: dead dispatch with a landmine. DisjointSlice::get_thread_local is dispatched in two arms plus a ~200-line emitter, but nothing in cuda-device declares that method. The emitter builds an Erased result and stores it into a rustc-typed destination, which this PR's verification would reject if the path ever woke up. Deleted the dispatch and emitter; the three DST-tail slice reconstructions that legitimately stay Erased now say why.

  • With the fixes: 95 workspace suites, compile-only smoketest 216/216, and GPU execution on vecadd, addressof_sharedarray, mcast_barrier_test, warp_reduce, and mathdx_ffi_test on an RTX 5090. Withholding the soundness verdict until I've finished walking the boundary-cast policy.

uurl and others added 4 commits August 23, 2026 09:11
…nt Erased tail slices

DisjointSlice::get_thread_local is not declared anywhere in cuda-device,
so both dispatch arms and the emitter were unreachable. The emitter also
built its *mut T result through the kind-erased constructor and stored
it into a rustc-typed destination, which the new kind-aware verification
would reject if the path ever became reachable.

The three DST-tail reconstruction sites keep MirSliceType::get on
purpose; comments now state the invariant (projection-internal values
stay Erased until an Rvalue::Ref/AddressOf boundary retypes them).

Signed-off-by: nihalpasham <[email protected]>
Three example kernels exposed two gaps in the kind-preservation
policy this PR documents:

1. Intrinsic results were stored with the normalization-only path, so
   an emitter-internal Erased pointer result could not take the
   destination slot's rustc-declared kind and MirStoreOp verification
   failed (mathdx_ffi_test: *mut i8 in AS3, mcast_barrier_test:
   *const u64 in AS7). A compiler-recognized device operation is one
   of the documented Rust-typed boundaries, so
   emit_store_result_and_goto now stores through
   store_local_at_rust_boundary, which establishes the declared kind
   while still requiring the same pointee shape.

2. The Rvalue::Ref boundary now emits a kind-only mir.cast <PtrToPtr>
   between wgmma_fence and the MMA, which the deferred-accumulator
   region matchers treated as an unsupported op, so fusion silently
   declined and lowering failed (wgmma_mma_bf16). Kind-only retypes
   between thin pointers with the same pointee and address space lower
   to nothing, so both the linear/pipeline walker and the counted-loop
   whitelist now look through them.

Signed-off-by: nihalpasham <[email protected]>
Verify exact Rust and ABI call boundaries, including closure receivers and drop glue, and make pointer-producing casts, projections, aggregates, intrinsics, and storage operations preserve or explicitly establish their authority.

Close aggregate and canonical-function-token laundering paths, preserve raw kinds through NVVM cluster mapping, and run whole-tree producer checks before pointer kinds are erased.

Canonicalize harmless pointer-kind reborrows in deferred WGMMA accumulator matching, with counted-loop, verifier-negative, and real Rust pipeline coverage.

Signed-off-by: nihalpasham <[email protected]>
@nihalpasham
nihalpasham force-pushed the feat/mir-reference-kind branch from 9230009 to f65dacb Compare August 23, 2026 06:26
@nihalpasham

nihalpasham commented Aug 23, 2026 •

Copy link
Copy Markdown
Collaborator

Updated #1062 to signed head 92c30552 with the additional soundness and CI fixes found during the final review.

The enforced boundary is:

generic pointer operation:  kind A -> kind A or Erased
typed Rust/ABI boundary:     Erased -> exact declared kind, with authority
LLVM lowering:               verify once more -> erase kind to `ptr`
  • Rust call boundaries: Fn receives immutable SharedRef; FnMut receives mutable UniqueRef; FnOnce stays by value. Drop glue establishes RawMut only when internal storage crosses into drop_in_place(*mut T).
  • Dialect enforcement: casts, offsets, projections, slices, aggregates, calls, inline PTX, IKET, generated intrinsics, and cluster mapa cannot silently invent or switch concrete kinds. Static/ABI recovery from Erased must trace to an allowed storage producer.
  • WGMMA: accumulator matching follows temporary reborrows to their canonical storage, so repeated calls and counted loops work without weakening type or address-space checks.
  • Example/CI repairs:
    • array_constants: exact promoted bytes, relocations, and alignment-aware deduplication;
    • copy_aggregate_borrow: scalarize only proven read-only compiler storage;
    • closure shims: reborrow typed receivers and adapt only by-value closures;
    • foreign ABI calls: normalize only address-space-only pointer mismatches;
    • promoted &mut [T; 0]: require a direct immutable global, exact empty/no-relocation initializer, exact type, and valid power-of-two alignment;
    • shared/device globals: reject incompatible duplicate declarations and keep static shared storage distinct from dynamic extern shared storage.

Pointer kind remains an auditable source classification, not an optimizer proof. This PR still emits no noalias, readonly, or dereferenceable; those require a separate first-class proof in later work.

Validation on the final tree:

  • affected workspace test suites: pass;
  • cargo clippy --workspace --all-targets -- -D warnings: pass;
  • independent adversarial and final-diff audits: no remaining blocker;
  • GPU-less compile-only smoketest: 216/216 passed, including array_constants, copy_aggregate_borrow, closures, drop glue, MathDx FFI, vectorization, tcgen05, and both WGMMA examples.

Hosted CI needs to run on the new head 92c30552 before merge.

@nihalpasham

Copy link
Copy Markdown
Collaborator

Closing this PR because the pointer-kind model is not sound or complete enough to become a compiler invariant.

  • Pointer kinds are attached after the Rust facts that justify them have already split across many import and lowering paths. Closure receivers, drop glue, intrinsics, projections, storage, and ABI adapters therefore need separate recovery rules.
  • The verifier can validate a label and a local transition, but it cannot prove that the label came from the exact Rust operation or ABI fact that justified it.
  • The repeated example repairs show an architectural problem, not a finite list of missed call sites.

I am replacing this with exact source types saved per MIR operation and one shared, fail-closed pointer-construction policy. LLVM alias and validity attributes will come from a separate proof, not from pointer labels alone.

#413 stays open for that replacement.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

codegen Device code-generation pipeline (Rust MIR to IR to PTX) enhancement New feature or request IR-lowering Lowering between dialects (dialect-mir to LLVM dialect) soundness-audit Correctness case under active maintainer audit; not cleared for merge yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants