Skip to content

codegen: scalarize bounded borrowed aggregate reads in MIR - #650

Merged
nihalpasham merged 7 commits into
NVIDIA:mainfrom
uurl:fix/400-mir-lower-borrowed-copy-aggregates
Aug 5, 2026
Merged

nihalpasham merged 7 commits into
NVIDIA:mainfrom
uurl:fix/400-mir-lower-borrowed-copy-aggregates

Conversation

@uurl

@uurl uurl commented Aug 4, 2026

Copy link
Copy Markdown
Contributor

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:

struct MeshDescriptor {
    lower: [u32; 3],
    upper: [u32; 3],
    periodic: [bool; 3],
    extent: [u32; 3],
}

used through an #[inline(always)] method taking &self:

self.lower[axis]
self.upper[axis]
self.periodic[axis]
self.extent[axis]

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:

  • the aggregate was immutable after initialization;
  • the helper was always-inline;
  • the index was proven to be within a small constant range;
  • every possible element could instead be represented directly in SSA.

This PR implements the optimization in typed dialect-mir and 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:

  1. MIR canonicalization converts eligible pointer-based aggregate reads into value-based extraction operations.
  2. MIR lowering emits a bounded SSA selection when the runtime index has a small proven candidate set.

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:

block argument
  -> mir.store into entry mir.alloca
  -> mir.field_addr
  -> mir.array_element_addr
  -> mir.load

Before mem2reg, the new canonicalization recognizes read-only aggregate slots that:

  • are initialized from a function block argument;
  • have no additional stores;
  • do not escape;
  • are accessed only through supported immutable field and array projections;
  • contain fixed-size array fields;
  • use non-volatile loads.

Eligible pointer-based reads are rewritten into:

mir.extract_field
  -> mir.extract_array_element

The original alloca and initialization store are left for the existing mem2reg pass to remove.

This handles direct by-value aggregate access without introducing any special LLVM-level processing.

2. Canonicalize immutable borrowed-pointer helpers after mem2reg

The original issue also contains an interprocedural shape:

caller aggregate slot
  -> mir.cast <PtrToPtr>
  -> mir.call always-inline helper(&self, index)

Inside the helper, the aggregate is visible only as an immutable pointer argument:

immutable pointer argument
  -> mir.field_addr
  -> mir.array_element_addr
  -> mir.load

The runtime bound may also be split across the call boundary. In the motivating benchmark, the caller computes:

axis = value % 3

while the helper retains the equivalent safety condition:

assert(axis < 3)

A second canonicalization phase therefore runs after mem2reg. It recognizes immutable pointer arguments in always-inline helpers when all of the following are proven:

  • the pointee is a struct containing a fixed-size array field;
  • the pointer and all derived pointers are immutable;
  • the projection chain has no unsupported uses or escapes;
  • the final load is non-volatile;
  • the runtime index is unsigned;
  • the index is bounded either by a constant-divisor remainder or by an exact dominating assert(index < C);
  • C is nonzero;
  • C does not exceed the array length;
  • C does 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:

bounded_index = mir.rem(index, C)
array_value = mir.load(field_pointer)
result = mir.extract_array_element(array_value, bounded_index)

This transformation remains typed and preserves the existing function and call structure. The helper's alwaysinline attribute 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_element previously used the generic dynamic fallback:

alloca array
store array
dynamic GEP
load

The lowering now recognizes an unsigned remainder by a constant:

index = value % C

when:

0 < C <= array length
C <= 16

It emits fixed SSA candidates:

candidate0 = extractvalue array[0]
candidate1 = extractvalue array[1]
...
result = select(index == 0, candidate0,
         select(index == 1, candidate1,
         ...))

This exposes every candidate to LLVM's ordinary scalar replacement and simplification passes.

The original alloca/GEP/load lowering remains unchanged for:

  • unbounded runtime indices;
  • zero divisors;
  • candidate counts larger than the array;
  • candidate counts larger than 16;
  • unsupported index expressions.

Safety and fail-closed behavior

The transformation is intentionally conservative.

The by-value slot canonicalization rejects:

  • additional writes after initialization;
  • multiple or ambiguous initialization stores;
  • volatile loads;
  • mutable derived pointers;
  • pointer escapes;
  • calls through derived pointers;
  • pointer casts, PHIs, selects, or unknown users;
  • unsupported projection chains;
  • non-array fields;
  • zero-length arrays;
  • projections whose dominance cannot be established.

The borrowed-pointer canonicalization additionally rejects:

  • functions without alwaysinline;
  • mutable pointer parameters;
  • volatile pointer reads;
  • missing or non-exact bounds;
  • signed or incompatible bounds;
  • bounds larger than the underlying array;
  • bounds larger than the scalarization limit;
  • ambiguous control-flow predecessors;
  • unsupported uses of field or element pointers.

Any rejected case continues through the existing lowering path.

Regression coverage

The MIR transformation tests cover:

  • bounded remainder indexing;
  • arrays larger than the candidate set;
  • direct unbounded indexing canonicalized for the lowering fallback;
  • candidate sets larger than the scalarization threshold;
  • rejection after an additional store;
  • rejection of volatile loads;
  • immutable pointer access guarded by an exact assertion;
  • rejection of borrowed-pointer access without an exact bound;
  • rejection of non-alwaysinline pointer helpers;
  • rejection of volatile borrowed-pointer reads.

The MIR lowering tests cover:

  • bounded urem extraction remaining entirely in SSA;
  • unbounded extraction retaining the memory fallback;
  • oversized candidate sets retaining the fallback;
  • preservation of recursive element alignment in the fallback path.

A GPU regression example, copy_aggregate_borrow, verifies:

  • correct device execution;
  • transformation of runtime-indexed aggregate fields;
  • absence of .local, ld.local, and st.local in generated PTX.

Validation

The following checks pass:

cargo test -p mir-transforms
cargo test -p mir-lower
cargo test -p cuda-oxide-codegen --all-targets

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

Results:

mir-transforms:
  10 unit tests passed
  5 induction tests passed
  5 loop-info tests passed
  17 unroll tests passed

mir-lower:
  160 unit tests passed
  88 integration tests passed
  7 documentation tests ignored

Clippy:
  no warnings

Generated-code validation

The benchmark compares four variants:

  1. baseline borrowed &self;
  2. transformed borrowed &self;
  3. baseline explicit scalar/value control;
  4. transformed explicit scalar/value control.

Target:

GPU: NVIDIA GeForce RTX 5060 Laptop GPU
Driver: 595.84
Target architecture: sm_120
rustc: 1.96.0-nightly (2026-04-02)
cargo: 1.96.0-nightly (2026-03-30)

PTX local-memory inspection:

baseline_borrowed:       17
prototype_borrowed:       0
baseline_value_control:   0
prototype_value_control:  0

ptxas results for the borrowed kernel:

                        Baseline    Prototype
Registers                    27           22
Stack frame             0 bytes      0 bytes
Spill stores            0 bytes      0 bytes
Spill loads             0 bytes      0 bytes
Barriers                       0            0

The baseline PTX contains local-address-space materialization and local loads/stores. ptxas reports no register-allocation spills; the local memory originates from aggregate materialization required by the previous lowering shape.

Performance

The full benchmark used:

Runs:                  5
Elements:              1,048,576; 4,194,304; 8,388,608
Rounds:                8; 32; 128
Warmup launches:       20
Batches:               20
Launches per batch:    5

Results:

Cells Rounds Baseline &self Prototype &self Baseline control Prototype control Speedup
1,048,576 8 0.359120 ms 0.127056 ms 0.146448 ms 0.146198 ms 2.8265×
1,048,576 32 1.421562 ms 0.486960 ms 0.567152 ms 0.566848 ms 2.9200×
1,048,576 128 6.141347 ms 2.000512 ms 2.417994 ms 2.383488 ms 3.0637×
4,194,304 8 1.540477 ms 0.532186 ms 0.616938 ms 0.618522 ms 2.8822×
4,194,304 32 6.251501 ms 2.044854 ms 2.450070 ms 2.463286 ms 3.0239×
4,194,304 128 23.660291 ms 8.144102 ms 9.865222 ms 9.944806 ms 2.9210×
8,388,608 8 3.161747 ms 1.083338 ms 1.294883 ms 1.268346 ms 2.9026×
8,388,608 32 12.305414 ms 4.043117 ms 5.002851 ms 5.083270 ms 3.0174×
8,388,608 128 46.776451 ms 16.814694 ms 19.737357 ms 19.570099 ms 2.7814×

Aggregate results:

Median prototype speedup over baseline borrowed:     2.9200×
Observed speedup range:                              2.7814×–3.0637×
Median baseline borrowed / baseline control:         2.4906×
Median prototype borrowed / prototype control:       0.8558×
Median prototype-control / baseline-control speedup: 0.9999×

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 &self source-level API.

@nihalpasham nihalpasham added codegen Device code-generation pipeline (Rust MIR to IR to PTX) IR-lowering Lowering between dialects (dialect-mir to LLVM dialect) perf Performance of generated code or of the compiler itself labels Aug 5, 2026
…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.
…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.
@nihalpasham

Copy link
Copy Markdown
Collaborator

This is the typed redo #400 asked for: analyze-then-rewrite passes in mir-transforms (the measurable benefit + fail-closed everywhere).

Verified:

  • copy_aggregate_borrow on RTX 5090: PASS with zero .local operations in the kernel body (the example's code-shape check asserts it), matching the 2.8-3.1x measured win.
  • always-on safety: PTX for gemm_sol, array_for_loop, array_index, and const_aggregate is byte-identical to main, so the passes change nothing they should not touch.
  • cargo test --workspace and clippy green on a fresh rebase onto main.

I pushed commits on top for the one real gap plus hardening:

  • caller-provenance eligibility for the &self pass: it now rewrites a helper only when every call site in the module passes a pointer that provably originates from a compiler-owned stack slot of the exact aggregate type. Kernel-parameter pointers, merged pointers, pointers forwarded through another helper, externally callable exports, and mixed call sites all disqualify the helper, and it keeps the original one-read-at-a-time code. This keeps the rewrite inside Promote Copy aggregate arguments borrowed only by inlined device methods #400's line: no invented reads through borrowed external pointers. Regression tests cover the rejected shapes, the still-accepted by-value shape, and the mixed case.
  • hardening: the candidate cap is one shared constant between mir-transforms and mir-lower, constants wider than 64 bits bail out instead of truncating through APInt::to_u64, and the verbose flag threads through Options instead of an env read inside the pass.

Closes #400.

@nihalpasham
nihalpasham force-pushed the fix/400-mir-lower-borrowed-copy-aggregates branch from 2d7ad32 to 470c11b Compare August 5, 2026 12:09
…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
nihalpasham merged commit 98b7995 into NVIDIA:main Aug 5, 2026
33 checks passed
@uurl
uurl deleted the fix/400-mir-lower-borrowed-copy-aggregates branch August 6, 2026 05:57
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) IR-lowering Lowering between dialects (dialect-mir to LLVM dialect) perf Performance of generated code or of the compiler itself

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Promote Copy aggregate arguments borrowed only by inlined device methods

2 participants