Repository navigation
codegen: scalarize bounded borrowed aggregate reads in MIR - #650
Merged
nihalpasham merged 7 commits intoAug 5, 2026
Merged
Conversation
Signed-off-by: Raul Estrada <[email protected]>
…de divisors Define MAX_SCALARIZED_CANDIDATES once in dialect-mir next to mir.extract_array_element so the mir-transforms canonicalization and the mir-lower bounded-urem fast path gate on one constant and cannot desync silently. Also guard the lowering's divisor extraction against constants wider than 64 bits: pliron's APInt::to_u64 truncates, so a 128-bit divisor could be misread as a small in-range candidate count. Bail out on width > 64.
… borrowed reads The post-mem2reg phase runs before inlining and used to check only helper-local facts, so it rewrote a single dynamic element load into a whole-array-field load through any immutable &self pointer, including pointers backed by global, shared, or external memory. Issue NVIDIA#400 (and the NVIDIA#398 precedent) requires such pointers to keep exactly one dynamic memory access. Gate the rewrite on a module-level caller-provenance analysis: every mir.call of the helper must pass a pointer traceable, through pointer-identity casts (mir.cast PtrToPtr reborrows), to a caller-local mir.alloca of exactly the helper's aggregate type. Kernel pointer parameters, phi/select merges, pointers forwarded from another helper's parameter, shared or global allocations, helpers without a single visible call site, and externally callable device exports (whose call sites this module cannot see) all disable the rewrite for the helper. Also route the verbose progress notes through the threaded MirPreparation/BackendOptions contract instead of reading CUDA_OXIDE_VERBOSE inside the pass, consume the shared MAX_SCALARIZED_CANDIDATES cap from dialect-mir, and guard the bound extraction against constants wider than 64 bits (APInt::to_u64 truncates). Regression tests cover the owned-slot shape (still rewritten), a forwarded pointer parameter, mixed call sites, a helper without call sites, and a device-export helper (all left untouched with their single dynamic load intact).
clippy's too-many-arguments lint rejects the eight-parameter caller builders, so the shared type handles now travel in a CallerTypes value.
…ymbols dependency in the lockfile
…asses The MirPreparation::verbose doc said the preparation passes never read the environment, but loop unrolling in the same stage still checks CUDA_OXIDE_VERBOSE directly. Scope the claim to the scalarization passes, which are the ones threading this flag.
Collaborator
|
This is the typed redo #400 asked for: analyze-then-rewrite passes in mir-transforms (the measurable benefit + fail-closed everywhere). Verified:
I pushed commits on top for the one real gap plus hardening:
Closes #400. |
nihalpasham
force-pushed
the
fix/400-mir-lower-borrowed-copy-aggregates
branch
from
August 5, 2026 12:09
2d7ad32 to
470c11b
Compare
…ates Two gates run wider than the root workspace check: the docs job builds rustdoc with -D warnings, and the fmt job re-checks this crate as a path dependency of the rustc-codegen-cuda workspace. Rustdoc rejected two intra-doc links from public pass docs to private helpers (analyze_alloca, all_call_sites_pass_owned_aggregate); they are plain code spans now. The fmt pass wanted the add_helper_call test call wrapped.
nihalpasham
approved these changes
Aug 5, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #400.
Supersedes #638.
Summary
This PR removes unnecessary local-memory materialization when a small aggregate is passed by value, borrowed through an immutable reference, and indexed at runtime with a statically proven small bound.
The motivating case is an aggregate such as:
used through an
#[inline(always)]method taking&self:Before this change, the by-value aggregate was materialized into local memory so that the helper could receive a pointer. Runtime indexing then survived as dynamic local-memory loads even though:
This PR implements the optimization in typed
dialect-mirand MIR-to-LLVM lowering rather than rewriting textual LLVM IR.Background
The original prototype in #638 performed post-inline textual LLVM IR rewriting. It demonstrated that the optimization was valuable, but the implementation operated outside the typed compiler pipeline.
The final implementation moves the transformation into two typed stages:
Unsupported or unproven cases retain the existing memory-based lowering.
Implementation
1. Canonicalize by-value aggregate argument slots
Rust MIR models locals using stack slots. A by-value aggregate argument therefore initially has the following shape:
Before
mem2reg, the new canonicalization recognizes read-only aggregate slots that:Eligible pointer-based reads are rewritten into:
The original alloca and initialization store are left for the existing
mem2regpass to remove.This handles direct by-value aggregate access without introducing any special LLVM-level processing.
2. Canonicalize immutable borrowed-pointer helpers after
mem2regThe original issue also contains an interprocedural shape:
Inside the helper, the aggregate is visible only as an immutable pointer argument:
The runtime bound may also be split across the call boundary. In the motivating benchmark, the caller computes:
while the helper retains the equivalent safety condition:
A second canonicalization phase therefore runs after
mem2reg. It recognizes immutable pointer arguments in always-inline helpers when all of the following are proven:assert(index < C);Cis nonzero;Cdoes not exceed the array length;Cdoes not exceed the scalarization limit.The pointer-based load is replaced with a value load of the array field followed by
mir.extract_array_element.For an assertion-proven index, the pass materializes a bounded remainder before extraction so that the lowering stage receives an explicit candidate count:
This transformation remains typed and preserves the existing function and call structure. The helper's
alwaysinlineattribute is propagated to LLVM, allowing the normal LLVM optimization pipeline to inline the helper and eliminate the remaining aggregate materialization.3. Lower bounded dynamic array extraction in SSA
mir.extract_array_elementpreviously used the generic dynamic fallback:The lowering now recognizes an unsigned remainder by a constant:
when:
It emits fixed SSA candidates:
This exposes every candidate to LLVM's ordinary scalar replacement and simplification passes.
The original alloca/GEP/load lowering remains unchanged for:
Safety and fail-closed behavior
The transformation is intentionally conservative.
The by-value slot canonicalization rejects:
The borrowed-pointer canonicalization additionally rejects:
alwaysinline;Any rejected case continues through the existing lowering path.
Regression coverage
The MIR transformation tests cover:
alwaysinlinepointer helpers;The MIR lowering tests cover:
uremextraction remaining entirely in SSA;A GPU regression example,
copy_aggregate_borrow, verifies:.local,ld.local, andst.localin generated PTX.Validation
The following checks pass:
Results:
Generated-code validation
The benchmark compares four variants:
&self;&self;Target:
PTX local-memory inspection:
ptxasresults for the borrowed kernel:The baseline PTX contains local-address-space materialization and local loads/stores.
ptxasreports no register-allocation spills; the local memory originates from aggregate materialization required by the previous lowering shape.Performance
The full benchmark used:
Results:
&self&selfAggregate results:
The prototype-control result remaining at approximately
1.0×shows that the performance improvement is isolated to the borrowed-aggregate transformation rather than a general change to the compilation pipeline.The transformed borrowed kernel reaches or exceeds the explicit scalar control in this benchmark while preserving the original
&selfsource-level API.