Skip to content

codegen: scalarize borrowed fields of by-value Copy aggregates - #638

Closed
uurl wants to merge 2 commits into
NVIDIA:mainfrom
uurl:fix/400-copy-aggregate-borrows
Closed

uurl wants to merge 2 commits into
NVIDIA:mainfrom
uurl:fix/400-copy-aggregate-borrows

Conversation

@uurl

@uurl uurl commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

Related to #400

Summary

This PR extends the post-inline LLVM IR scalarizer to promote small runtime-indexed fields borrowed from by-value Copy aggregates.

It fixes the retained-local-memory pattern described in #400, where an aggregate is materialized in an alloca only because an inlined read-only method takes &self.

Dependency: This PR is stacked on #636. Please review and merge #636 first.
The diff against main currently includes the base PR and should collapse after #636 lands.

Implementation

The scalarizer now recognizes eligible aggregate allocas that are:

  • created in the function entry block;
  • initialized before use;
  • read-only after initialization;
  • accessed through tracked GEP chains;
  • not escaped through calls, stores, casts, PHIs, selects, or other unsupported operations.

It supports two initialization forms:

  1. one full aggregate store;
  2. scalar stores at constant non-overlapping byte offsets, including the form emitted by LLVM 22 after the first default<O2> pipeline.

For scalarized aggregate initialization, the pass reconstructs contiguous scalar fields from their stored byte offsets.

Dynamic field loads are rewritten into:

  • constant-address candidate GEPs;
  • candidate loads;
  • pointer comparisons;
  • a value select chain.

A subsequent default<O2> pass removes the dead dynamic pointer arithmetic and allows SROA to eliminate the aggregate allocation.

Safety constraints

The aggregate transformation is intentionally conservative.

It rejects:

  • volatile or atomic loads and stores;
  • overlapping initialization stores;
  • stores outside the entry block;
  • writes through derived pointers;
  • pointer escapes;
  • pointer-valued elements;
  • unsupported or dynamic initialization offsets;
  • external-pointer loads;
  • dynamic indices without a proven unsigned upper bound.

The current range proof recognizes constant-divisor urem expressions and requires the resulting upper bound to fit within the discovered field length.

The small-array-iterators and copy-aggregate-borrows modes are kept independent so enabling one transformation does not implicitly enable the other.

Regression coverage

New unit coverage includes:

  • full aggregate initialization;
  • LLVM 22 scalarized aggregate initialization;
  • aggregate element-pointer GEP forms;
  • bounded runtime indexing;
  • rejection of unbounded indices;
  • rejection of overlapping stores;
  • rejection of post-initialization writes;
  • rejection of pointer escapes;
  • rejection of initialization outside the entry block;
  • rejection of volatile aggregate loads;
  • rejection of external dynamic pointer loads;
  • isolation between scalarization modes.

A new copy_aggregate_borrow GPU example verifies:

  • correct execution on the device;
  • scalarization of both runtime-indexed fields;
  • absence of .local, ld.local, and st.local in the kernel PTX.

Validation

cargo fmt --all
cargo clippy -p cuda-oxide-codegen --all-targets -- -D warnings
cargo test -p cuda-oxide-codegen --all-targets

Results:

162 unit tests passed
16 compile-to-PTX tests passed
concurrent compilation test passed
6 libdevice-linking tests passed
spine PTX test passed
4 target-provenance tests passed

GPU regression for #400:

small-array scalarization: replaced 2 dynamic load(s)
copy_aggregate_borrow: PASS
copy_aggregate_borrow PTX shape: PASS

Regression for the existing small-array iterator path:

array_iterator_adapters: PASS
array_iterator_adapters PTX shape: PASS

@uurl uurl changed the title codegen: scalarize borrowed fields of by-value copy aggregates codegen: scalarize borrowed fields of by-value Copy aggregates Aug 2, 2026
@nihalpasham nihalpasham added perf Performance of generated code or of the compiler itself codegen Device code-generation pipeline (Rust MIR to IR to PTX) on-hold Paused: valid but deferred until a prerequisite decision or dependency resolves labels Aug 3, 2026
@nihalpasham

Copy link
Copy Markdown
Collaborator

Thanks for the PR.

I'm putting this on hold along with #636. This one is stacked on top of it (the diff includes all of #636), so that conversation gates this PR either way. Notes specific to this one below.

What this PR is about:

A copyable struct passed to a kernel by value gets forced into local memory just because a read-only method takes &self:

#[kernel]
fn k(mesh: Mesh, level: usize, ...) {   // mesh arrives by value, in registers
    let n = mesh.count(level);          // count() takes &self
}

// &self needs an address, so the compiler spills the argument:
//   .local .b8 depot[24]     <- stack slot created just for the borrow
//   st.local x6              <- copy the already-in-registers arg into it
//   ld.local                 <- runtime-indexed read of a small field

The struct was already in registers; the borrow alone puts it in memory. #400 saw a 56-byte local frame drop to zero by switching &self to self, which is not a workaround we want to teach anyone.

What we'd need before we go further:

Findings from the review:

  • Credit first: the aggregate analysis is careful and fail-closed. Entry-block-only initialization, escape/volatile/atomic/overlap rejection, and selection by pointer equality rather than value substitution. I found no miscompile in the new code.
  • The blocker is the layer it lives in: this grows the textual opt-output rewriter from ~1,150 to ~2,250 lines. Everything I said on Scalarize small local arrays used by iterator adapters #636 about that layer applies unchanged here.
  • Because it's stacked, this branch also carries Scalarize small local arrays used by iterator adapters #636's issues as-is, including the phi provenance bug in the shared array path.

What I'd recommend instead, if the measurement pans out:

  • Same direction as Scalarize small local arrays used by iterator adapters #636: extend the existing mir-lower scalarizer, this time to recognize the borrow-of-by-value-aggregate shape, and emit its select chains over loads at fixed field offsets. One note that makes this case different from Scalarize small local arrays used by iterator adapters #636: the field values here are runtime kernel arguments, not constants, so the .const-space idea doesn't apply; the scalarizer extension is the whole path.
  • Your eligibility rules (write-once, read-only-after, no escapes, bounded index) are the right conditions and would carry straight over into that version.

@nihalpasham nihalpasham added the optional-opts Opt-in optimization passes for the oxide-owned opt registry (off by default) label Aug 3, 2026
@uurl

uurl commented Aug 4, 2026

Copy link
Copy Markdown
Contributor Author

I repeated the benchmark with device code generated natively for the RTX 5060's sm_120 target.

Both modules contain:

.version 8.7
.target sm_120

The comparison used:

  • baseline: 345d912d68147d674ba8ab961cf4cf9b271ab8a8;
  • prototype: 2876838aa4d96ef9a006bb35c4ab49b5af49d5b8;
  • GPU: NVIDIA GeForce RTX 5060 Laptop GPU;
  • driver: 595.84;
  • Rust nightly 2026-04-03 / LLVM 22;
  • PTX target: sm_120;
  • 1M, 4M, and 8M cells;
  • 8, 32, and 128 topology rounds per thread;
  • 20 warm-up launches;
  • 20 batches of 5 measured launches;
  • 5 independent runs;
  • rotating execution order;
  • CUDA-event timing;
  • output validation outside the measured interval.

The workload passes a 56-byte structured-grid descriptor to the kernel by value. The borrowed variant queries runtime-selected fields through an inlined &self helper. The scalar control performs equivalent explicit scalar selection without runtime aggregate indexing.

The native sm_120 code-shape checks were:

baseline_borrowed:         17 local-memory PTX matches
prototype_borrowed:         0
baseline_value_control:     0
prototype_value_control:    0

The prototype reported four replaced dynamic loads.

Across the full measurement matrix:

median prototype speedup: 2.8911x
observed range:           2.7709x–2.9924x

The median baseline borrowed time divided by baseline scalar-control time was 2.4819x.

To isolate the effect of the additional optimization pipeline, the scalar control was compiled through both revisions. Its median prototype-over-baseline speedup was 1.0000x, indicating that the extra optimization pipeline alone does not explain the borrowed-kernel improvement.

Native sm_120 ptxas results were:

baseline borrowed:  27 registers
prototype borrowed: 25 registers
baseline control:   23 registers
prototype control:  23 registers

All kernels reported zero stack frame and zero allocator spill loads/stores. The local-memory operations in the baseline PTX come from explicit aggregate materialization rather than register-allocation spills.

The same benchmark previously produced a 2.8812x median speedup when emitting sm_80 PTX and relying on driver JIT. The native sm_120 result reproduces the effect at 2.8911x.

This provides a measurable benefit for the optimization opportunity. I will not extend the textual rewriter further; the next implementation step is a focused typed transformation in mir-lower, preserving the conservative eligibility rules from the prototype.

@nihalpasham

Copy link
Copy Markdown
Collaborator

Closing the prototype now that the question it existed to answer is answered:

And again, thanks for this :)

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) on-hold Paused: valid but deferred until a prerequisite decision or dependency resolves optional-opts Opt-in optimization passes for the oxide-owned opt registry (off by default) perf Performance of generated code or of the compiler itself

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants