Skip to content

[wasm] Reuse Locals in Regalloc - #138249

Draft
adamperlin wants to merge 14 commits into
dotnet:mainfrom
adamperlin:adamperlin/wasm-regalloc-reuse-locals
Draft

adamperlin wants to merge 14 commits into
dotnet:mainfrom
adamperlin:adamperlin/wasm-regalloc-reuse-locals

Conversation

@adamperlin

@adamperlin adamperlin commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Opening as a draft since I'm not sure this is in its final form. This PR updates the Wasm register allocator strategy to allow for reuse in declared locals. The handling of ABI locals/params/SP/FP remain the same for now; SP and FP are shared if possible, and parameters/param reg targets retain their ABI homes. It's only the extra locals declared in-method which are eligible for reuse.

General Approach

The general approach is a simple greedy allocation strategy that looks like LSRA at a high-level.

  1. Linearize the CFG (done already by fgWasmControlFlow)
  2. Number the LIR trees and assign live intervals to each interval candidate in the selected block order (BuildIntervals)
    a. The intervals are conservative and contiguous, from first to last use of a tracked local. We don't do any interval splitting or account for lifetime holes.
  3. Assign registers greedily based on which registers are free for the duration of a particular interval (AssignIntervals). If at any point all existing "registers" (locals) are busy, simply allocate a new one. In this way, we should end up with the minimal number of locals we need to ensure each conservative interval has its own non-interfering Wasm local.

Results

Diffs
Overall : -789,246 bytes
TP:

  • Minopts: +0.67% to +1.01%
  • FullOpts: +0.95% to +2.13%

Memory Usage: +1.05% to +3.39%

System.Private.CoreLib

Metric Main base JIT Diff JIT Base + wasm-opt
Functions with bodies 36,845 36,809 36, 845
Total declared locals 261,621 112,226 39,912
Minimum locals per method 0 0 0
Maximum locals per method 599 44 24
Total Size 25,144,897 bytes 25,121,821 bytes -

The diff output has 149,395 fewer locals overall (57.10%). Wasm-opt does even better though, with a further 64.4% reduction. One factor is likely that wasm-opt allows for re-using parameter local slots as well.

Havit

Metric Baseline (0ef12455bdf9) Locals-reuse (58469a4ab42) Change
Mobile cold startup 5,564 ms 5,429 ms -2.4%
Desktop walkthrough 5.61 s 5.53 s -1.4%
Compressed cold download 8.717 MB 8.400 MB -3.6%
App publish time 121.79 s 104.69 s -14.0%

@adamperlin
adamperlin requested a balanced review from Copilot November 25, 2026 00:09
@github-actions github-actions Bot added the area-CodeGen-coreclr CLR JIT compiler in src/coreclr/src/jit and related components such as SuperPMI label Nov 25, 2026
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 6 pipeline(s).
9 pipeline(s) were filtered out due to trigger conditions.
There may be pipelines that require an authorized user to comment /azp run to run.

@adamperlin adamperlin added the arch-wasm WebAssembly architecture label Nov 25, 2026
@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Tagging subscribers to this area: @JulieLeeMSFT, @jakobbotsch
See info in area-owners.md if you want to be subscribed.

@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Tagging subscribers to 'arch-wasm': @lewing, @pavelsavara
See info in area-owners.md if you want to be subscribed.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Wasm live-interval allocation and per-funclet register coalescing require target execution or differential validation plus local-count and performance evidence, none of which was available in this static review.

No open issues 🎉

What changed in this PR

This PR adds lifetime-based local reuse to the CoreCLR WebAssembly register allocator, aiming to reduce the number of declared WebAssembly locals.

Changes:

  • Builds per-funclet live intervals and reuses same-type locals across non-overlapping intervals.
  • Adds relative register indices and resolves them after allocation, while retaining dedicated parameter and frame-pointer homes.
  • Adds directed tests covering interval boundaries, loops, exceptions, contained operations, and stack frames.
File Description
src/​tests/​JIT/​Directed/​WasmRegalloc/​WasmRegalloc.csproj Defines the optimized, priority-1 test project.
src/​tests/​JIT/​Directed/​WasmRegalloc/​WasmRegalloc.cs Adds directed coverage for local reuse and retained homes.
src/​tests/​JIT/​Directed/​Directed_1.csproj Includes the new tests in the merged runner.
src/​coreclr/​jit/​registeropswasm.h Declares relative-register encoding and resolution helpers.
src/​coreclr/​jit/​registeropswasm.cpp Implements relative indices and register-offset resolution.
src/​coreclr/​jit/​regallocwasm.h Defines live intervals and physical-register allocation helpers.
src/​coreclr/​jit/​regallocwasm.cpp Builds intervals, reuses locals, and resolves per-funclet assignments.
src/​coreclr/​jit/​priorityqueue.h Adds a size accessor for tracking active intervals.

Review effort: Balanced

@adamperlin

adamperlin commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor Author

I think the locals reduction is a really good improvement, but it is not close to the wasm-opt numbers in terms of total locals. From a copilot analysis, it looks like the reuse of parameter local slots does account for a large portion of the gap with wasm-opt. Parameter slot re-use seems like it might be worth implementing, though I think there are some edge cases to be careful about.

The memory usage diff also seems a little high, and I think the tpdiff for minopts is higher than it needs to be since we are currently still building intervals even in minopts, which we should probably disable.

@adamperlin
adamperlin force-pushed the adamperlin/wasm-regalloc-reuse-locals branch from 3f15a2c to 4bfd047 Compare November 26, 2026 06:15
@AndyAyersMS

Copy link
Copy Markdown
Member

From a quick skim:

  • TP cost seems high, can you look more closely at where it comes from?
  • We should add Wasm locals as a jit metric so we can see this more easily in SPMI summaries. Can just be total locals or can be total per type. Maybe do this as a prerequisite?
  • Make sure the predicate used by the priority queue gives a total order, seems like multiple intervals could end at the same spot and we'd need some secondary criteria there.
  • Disable for minopts seems reasonable. Also we should be able to opt out via a config setting (easier bug isolation).
  • LSRA usually has a model for "holes" in the lifetimes. Allowing this might lead to a given local being stored in multiple Wasm locals. Not sure if it's worth the trouble.

@adamperlin

Copy link
Copy Markdown
Contributor Author

From a quick skim:

  • TP cost seems high, can you look more closely at where it comes from?

Yes, definitely. One suspect is the handling for multiply used nodes; we are currently re-walking the whole block to look for a consuming user in those cases, and it seems like we could maybe do this without extra searching.

  • We should add Wasm locals as a jit metric so we can see this more easily in SPMI summaries. Can just be total locals or can be total per type. Maybe do this as a prerequisite?

That's a good idea. I made a separate PR to do that here: #138560

  • Make sure the predicate used by the priority queue gives a total order, seems like multiple intervals could end at the same spot and we'd need some secondary criteria there.

I'll address this. Are you thinking we should have a total order for predictability / reproducibility?

  • Disable for minopts seems reasonable. Also we should be able to opt out via a config setting (easier bug isolation).

Would the config setting just apply the minopts policy to fullopts?

  • LSRA usually has a model for "holes" in the lifetimes. Allowing this might lead to a given local being stored in multiple Wasm locals. Not sure if it's worth the trouble.

I'm not sure on this one either; allowing a given local to be stored at multiple wasm locals at different points would definitely complicate our current model a bit. After doing a bit of experimenting with AI with a modified version of wasm-opt, I actually think our biggest gap is that the current approach doesn't allow for param local reuse, so I think I might want to prioritize addressing that?

…tBlockSequence

using the WasmDfs produced dfs tree to perform a loop-aware RPO traversal.
Blocks are partitioned per funclet during the traversal, resulting in relative LaRPO for each funclet.
Null out empty intervals in funclets;
Improve interval dump;
…mporarily disable allocation for temporary registers
…e whether

a local created by the allocator has its indexBase added. Resolve IndexBase's and
map created locals to their resolved indices. Assert that the isRelative bit
doesn't survive on any tracked locals once they are assigned physRegs.

Also, jit-format and rename some of the reg map structure temps.
… in one place;

Merge all reg assignments in funclets which do not exist in the root funclet into the root's
assignments to match existing policy
We could have a case where an interval's end is set to the last node position of a block
due to its liveOut set, but the last position in said block contains a dead store followed
by a BBJ_ALWAYS back edge. The dead store interferes then interferes with the liveOut local. Fix this
by extending the endpoints of the liveOut set to pos + 1. This could push some locals' endpoints into an
adjacent block where the locals are not already live, but that is ok because, assuming the liveOut was the "last use",
the locals' intervals will still be expired before any interval starting at the first node in the block.
@adamperlin
adamperlin force-pushed the adamperlin/wasm-regalloc-reuse-locals branch from 7721534 to 5cf45f1 Compare December 3, 2026 00:44

This branch has not been deployed

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

Labels

arch-wasm WebAssembly architecture area-CodeGen-coreclr CLR JIT compiler in src/coreclr/src/jit and related components such as SuperPMI

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants