Skip to content

feat(codegen): diagnose locals that survive register promotion - #758

Merged
nihalpasham merged 6 commits into
NVIDIA:mainfrom
uurl:feat/707-local-memory-promotion-diagnostic
Aug 10, 2026
Merged

nihalpasham merged 6 commits into
NVIDIA:mainfrom
uurl:feat/707-local-memory-promotion-diagnostic

Conversation

@uurl

@uurl uurl commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

Closes #707

Summary

Adds an opt-in diagnostic for named Rust locals whose allocations remain stack-backed after LLVM optimization.

The diagnostic runs on the final optimized LLVM IR passed to llc, avoiding reports for allocations that are subsequently removed by mem2reg or SROA.

Implementation

  • Attach source-level provenance to named Rust MIR locals, including the binding name, type, and allocation size.
  • Preserve that provenance through MIR-to-LLVM lowering.
  • Encode the provenance into the exported LLVM SSA name so surviving allocations can be identified after opt.
  • Inspect the optimized LLVM IR immediately before llc.
  • Report surviving tagged allocations in verbose optimized builds.
  • Provide specific diagnostics for dynamic indexing and obvious address escapes, with a conservative fallback when the blocker cannot be identified.
  • Skip the diagnostic for non-optimized and full variable-debug builds, where stack-backed storage may be intentional.

Example:

warning: local `scratch` (`[u32; 4]`, 16 bytes) in `kernel` could not be promoted to registers
  = note: indexed by a non-constant value; the allocation survives LLVM scalar replacement and remains stack-backed
  = help: use constant indexing or a small match/select when the index range is bounded

Testing

Added coverage for:

  • dynamic-indexed locals
  • surviving alloca names with optimizer suffixes
  • pointer/address escapes
  • LLVM lifetime intrinsics
  • untagged compiler-generated allocas
  • successfully promoted locals
  • verbose and non-verbose codegen behavior
  • MIR-to-LLVM provenance preservation

Validated with:

cargo fmt --all -- --check

cargo test \
  -p dialect-mir \
  -p mir-lower \
  -p cuda-oxide-codegen \
  -p mir-importer

cargo clippy \
  -p dialect-mir \
  -p mir-lower \
  -p cuda-oxide-codegen \
  -p mir-importer \
  --all-targets -- -D warnings

cargo clippy --all-targets -- -D warnings

uurl and others added 5 commits August 9, 2026 05:50
…x payload

LLVM uniques colliding value names by appending bare digits: when the
same named local is inlined twice into one kernel, the second alloca is
exported as '<name>1'. Digits are valid hex, so the old
take_while(is_ascii_hexdigit) decode absorbed the uniquing suffix into
the payload: a one-digit suffix made the hex run odd-length and silently
dropped the report, and a two-digit suffix decoded a garbage byte into
the reported type name.

Terminate the hex run with a '_' sentinel at the encode site and key the
decode on it: hex digits up to the first '_', rejecting names that lack
the terminator. '.sroa.N' suffixes keep working ('.' already ended the
hex run), and '<hex>_1' uniquing suffixes now decode to the exact
original payload.

Adds unit tests for the uniquing-collision shape and for unterminated
payloads, and updates the fake-opt integration tools to the
sentinel-terminated name.
…first-class attribute

The provenance rode through both dialects as a tab-separated payload
inside a builtin StringAttr, which the project's pliron rules forbid:
a typed value stored on an op must be a first-class attribute so pliron
can inspect, print, and verify it.

Introduce LocalMemoryProvenanceAttr (#[pliron_attr], typed fields for
local index, byte size, binding name, and type name) in llvm-export's
ops module, following the debug-local-variable precedent for pipeline
metadata that must live on both the mir.alloca and the LLVM alloca:
mir-importer attaches it via llvm_export::ops::set_local_memory_provenance,
mir-lower's copy_local_memory_provenance clones the attribute across the
lowering exactly like copy_debug_local_variable, and dialect-mir no
longer needs any provenance code of its own.

The string encoding now exists only at the textual-export boundary
(encode_local_memory_provenance in the exporter), where smuggling the
payload through the SSA value name is genuinely forced: an external
'opt' binary preserves nothing else on surviving instructions.
Demangle the containing function name via rustc-demangle (dropping the
disambiguating hash): kernel entry points already carry their exported
source name, but a non-inlined device function survives optimization
under its mangled Rust symbol, and 'in `kernel::inner`' reads far
better than the raw v0/legacy symbol. Unmangled names pass through
untouched.

Extend the generic fallback help text to mention that large aggregates
are harder to promote: scalar replacement must split every access into
independent scalars, so oversized locals commonly survive even without
dynamic indexing or escapes.
The compile-only smoketest caught four examples (array_for_loop,
host_closure, map_sum, ref_index_projections) whose device IR stopped
parsing: 'error: multiple definition of local value named
__cuda_oxide_local_x33...'. The real defect is name length, not a
duplicate. rustc's MIR inliner merges callee var_debug_info into the
kernel body, so iterator internals contribute named closure locals
(e.g. try_fold's 'f'), and local_memory_type_name fell through to
format!("{ty:?}") for closure types, producing a recursive DefId dump
over 13 KB long. Hex-encoded into the alloca's SSA name, that exceeds
what LLVM's textual lexer can handle (empirically fine at ~1000 chars,
broken at ~2000, surfacing as the bogus multiple-definition error from
both opt and llc).

Two layers of defense:
- mir-importer spells closure and coroutine environments the way rustc
  diagnostics do ('{closure}', '{coroutine}') and hard-caps the debug
  fallback spelling for any kind without a dedicated arm.
- the exporter caps the pre-hex payload at 256 bytes (truncating on a
  char boundary so the name still decodes as UTF-8), making the textual
  boundary safe against any producer since the attribute itself places
  no bound on field lengths.

Adds unit tests for the encode cap and for decoding a name whose type
spelling was truncated by it. Also records the rustc-demangle entry in
rustc-codegen-cuda's own lockfile, which the previous commit missed.
@nihalpasham nihalpasham added enhancement New feature or request QoL-improvement Quality-of-life improvement; not a correctness fix codegen Device code-generation pipeline (Rust MIR to IR to PTX) llvm-export Textual LLVM/NVVM IR exporter (llvm-export crate) IR-lowering Lowering between dialects (dialect-mir to LLVM dialect) labels Aug 10, 2026
@nihalpasham

Copy link
Copy Markdown
Collaborator

Gist: exceeds what #707 asked for, and the placement is right: the diagnostic reads post-opt IR through the one channel that survives O2, since full variable debug info is only available when we skip opt entirely. ptxas -v tells you local memory exists; this tells you which binding and why.

I pushed five commits:

  • provenance is now a first-class pliron attribute on both allocas instead of a tab-separated StringAttr, with the string encoding surviving only at the textual-export boundary where it is genuinely forced;
  • the hex payload is sentinel-terminated with a collision test so LLVM's name-uniquing suffixes can't garble a report; warning text is demangled and bounded; and
  • the new rustc-demangle dependency is recorded in the license inventory.
  • One review suggestion was dropped with evidence: modern SROA has no aggregate-size threshold, so the help text says something true instead.

Verified with real opt -O2 on this host:

  • dynamically indexed locals warn with the right binding, size, and reason;
  • vecadd and six aggregate-heavy examples build warning-free;
  • compile-only smoketest 191/191; workspace suite green.

Merging.

This closes #707. Related to #708 (ptxas-introduced spills are out of scope here) and #399.

@nihalpasham
nihalpasham merged commit ffe1135 into NVIDIA:main Aug 10, 2026
38 checks passed
@uurl
uurl deleted the feat/707-local-memory-promotion-diagnostic branch August 10, 2026 06:24
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) llvm-export Textual LLVM/NVVM IR exporter (llvm-export crate) QoL-improvement Quality-of-life improvement; not a correctness fix

Projects

None yet

Development

Successfully merging this pull request may close these issues.

No diagnostic when a local falls to local memory because it is dynamically indexed

2 participants