Skip to content

JIT: Consider cheaper callee-saved evictions for call-crossing locals - #137509

Open
NinoFloris wants to merge 8 commits into
dotnet:mainfrom
NinoFloris:jit/lsra-spill-selection
Open

NinoFloris wants to merge 8 commits into
dotnet:mainfrom
NinoFloris:jit/lsra-spill-selection

Conversation

@NinoFloris

@NinoFloris NinoFloris commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

A free caller-saved register may only defer a spill until the next call. When no free register covers the remaining range and suitable callee-saved registers are occupied, compare their spill costs with the incoming reference's weight. If eviction is cheaper, let the normal spill-selection heuristics choose among those registers.

CI results, aggregated across collections. PerfScore is the geomean over all paired compilations; lower is better in every column.

Platform TP Code size PerfScore (geomean)
Linux x64 −0.112% −5,775,825 B −0.253%
Windows x64 −0.073% −5,152,153 B −0.117%
Linux arm64 −0.002% −1,788,024 B −0.067%
Windows arm64 −0.003% −1,545,288 B −0.063%
macOS arm64 −0.001% −1,039,404 B −0.057%
Linux arm +0.313% −2,490,516 B −0.131%
Windows x86 −0.047% −4,266,322 B −0.281%
Wasm −0.001% 0 B 0.000%

Missing replay captures are excluded. Windows x86 has 104,234 misses with the changed JIT versus 220 with the baseline. In an earlier local reproduction, all 901 newly missing benchmark contexts requested register-specific write-barrier helpers absent from the captures: changing the allocated register changes which helper codegen requests. The table includes only successfully paired compilations; the full CI missing set has not been individually checked.

@dotnet-policy-service dotnet-policy-service Bot added the community-contribution Indicates that the PR has been added by a community member label Nov 13, 2026
@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 13, 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.

@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.

@NinoFloris
NinoFloris force-pushed the jit/lsra-spill-selection branch from 06290c9 to 1899aee Compare November 13, 2026 18:16
A free caller-saved register may only defer a spill until the next call. When no free register covers the remaining range and suitable callee-saved registers are occupied, compare their spill costs with the incoming reference's weight. If eviction is cheaper, let the normal spill-selection heuristics choose among those registers.
@NinoFloris
NinoFloris force-pushed the jit/lsra-spill-selection branch from 1899aee to db2bd23 Compare November 13, 2026 18:30
@NinoFloris
NinoFloris marked this pull request as ready for review November 13, 2026 19:51
@NinoFloris

Copy link
Copy Markdown
Contributor Author

@AndyAyersMS ptal, very nice wins.

@AndyAyersMS

Copy link
Copy Markdown
Member

@AndyAyersMS ptal, very nice wins.

Yes, this looks quite nice indeed.

Looping in @jakobbotsch who is more familiar with linear scan.

@AndyAyersMS

Copy link
Copy Markdown
Member

@jakobbotsch what do you think?

fyi @dotnet/jit-contrib some impressive improvements here.

@jakobbotsch

Copy link
Copy Markdown
Member

Improvements indeed look very impressive and it makes sense to me.

It is a long-standing issue that we always prefer free registers even in cases where freeing up another register may be better. It was tracked by #6824 (not sure why that was closed; we never fixed that). Carol's idea for this is in #8019 -- that approach may allow the existing occupant to be allocated to a different free register instead of having to be spilled.
Still, this PR seems simple enough and like an improvement over the current state of things.

Comment thread src/coreclr/jit/lsra.cpp Resolved

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.

🟡 Changes recommended

The eviction probe can crash on ARM32 by dereferencing an unassigned register half, and the lifetime-coverage check can cause unnecessary callee-saved spills.

2 open issues
What changed in this PR

Updates CoreCLR’s linear-scan register allocator to consider cheaper callee-saved evictions when a free register cannot cover a call-crossing local’s remaining lifetime.

Changes:

  • Extracts shared spill-candidate eligibility and cost calculation into spillCandidateCost.
  • Adds an eviction check that compares costs, then delegates register choice to the existing spill-selection heuristics.

Review was based on source inspection; builds, tests, and benchmarks were not run.

File Description
src/​coreclr/​jit/​lsra.h Declares the shared spill-candidate cost helper.
src/​coreclr/​jit/​lsra.cpp Implements the helper and adds cost-based callee-saved eviction selection.

Review effort: Balanced

Comment thread src/coreclr/jit/lsra.cpp Resolved
Comment thread src/coreclr/jit/lsra.cpp Resolved
@NinoFloris

Copy link
Copy Markdown
Contributor Author

Carol's idea for this is in #8019 -- that approach may allow the existing occupant to be allocated to a different free register instead of having to be spilled.
Still, this PR seems simple enough and like an improvement over the current state of things.

I'm glad to see this was considered at some point.

I could see how a reservation approach might avoid costs this local opt cannot see, but making the right choices across a wider range is harder. I tried a revocable reservation scheme just now and didn’t get any better results. That doesn’t necessarily rule it out, but making it behave well seems to need a lot more infrastructure.

Move the cheaper-eviction decision into try_FREE and dispatch subsequent heuristics accordingly. Share the fixed-reference endpoint adjustment with the coverage check, and check each occupied ARM32 register half's own next reference before admitting a pair.
Rename FREE and its helper, statistics and dump label to reflect the eviction alternative. Preserve the score value and ordering code A.
@NinoFloris
NinoFloris requested review from jakobbotsch and a balanced review from Copilot November 18, 2026 15:56

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

Cross-platform register-allocation and spill-eligibility changes lack runtime validation, and 103,586 reported x86 changed-JIT misses were only partially investigated, leaving a coverage gap requiring maintainer review.

No open issues 🎉

2 resolved since last review

Review effort: Balanced

Restore the Release call-site guard around FREE_OR_CHEAPER_SPILL. With no free candidates the helper immediately returns, so dispatch directly to the spill heuristics.

@tannergooding tannergooding left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Changes look correct to me

Comment thread src/coreclr/jit/lsra.cpp Resolved
Comment thread src/coreclr/jit/lsra.cpp Resolved
Comment thread src/coreclr/jit/lsra.cpp Resolved
Comment thread src/coreclr/jit/lsra.cpp Resolved
Comment thread src/coreclr/jit/lsra.h Resolved
Use the existing call-crossing preferences and spill weights for tree temporaries as well as locals. Simplify register-mask iteration and keep the coverage query free of allocation-event logging.
Leave the minimum-cost selection to try_SPILL_COST and document why reordered DEBUG heuristics need their own free-candidate checks.
Restore the spill selector ordering lost during helper extraction. An active consecutive-register use can be the last reference under lifetime-extension stress, so reject it before querying whether its next reference requires a register.
Comment thread src/coreclr/jit/lsra.cpp Resolved

@jakobbotsch jakobbotsch left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This looks good to me, thanks!

Have you looked at some of the regressions that are both size and perfscore regressions to understand what is causing them?

I am fine with taking this as is, but it would be good to characterize regressions.

@NinoFloris

Copy link
Copy Markdown
Contributor Author

Have you looked at some of the regressions that are both size and perfscore regressions to understand what is causing them?

Yes, some of these are from removing the isLocalVar condition, I wrote a bit about this earlier on #137509 (comment)

TL;DR
Most of the PerfScore loss in the CI collections comes from cases where the same spilled local now reloads at many sites. In GetKeyValuePair, startposition has four counted references, but evicting it introduces 46 static reload sites. I tried to account for this in spill selection, but none of those attempts improved on the current situation overall.

Astra and Fable combined size and PS regression categorization:

The biggest pattern was one displaced local getting reloaded at many sites. In the CI examples, 374 of 1,058 distinct regressing method/target cases had at least six added reload sites for one stack slot. Those cases accounted for 78% of the summed PerfScore increase seen in CI. In a separate full ARM64 libraries PMI replay, 886 of 5,214 changed contexts regressed on both metrics, while the collection saved about 109 KB overall.

1. A local with few counted references can still need reloads on many edges.

System.Data.Common.DbConnectionOptions:GetKeyValuePair on Linux ARM64 went from 1,528 to 1,784 bytes, PerfScore 558.86 to 689.61. length (weight 600) takes x25 from startposition (weight 400). startposition has four counted references, but the resulting code has 46 static reload sites across the parser’s branches. Here’s one after GetIsWhiteSpace:

  blr  x2                       // GetIsWhiteSpace
- cbnz w0, G_M9981_IG21
+ ldr  w1, [fp, #0x1C]          // reload startposition
+ cbnz w0, G_M9981_IG26

This regression also happens with the isLocalVar gate in place.

Other examples include Roslyn’s CommonReferenceManager.ReuseAssemblySymbols (one CSE temp reloaded at 14 added sites, including inside loops; +296 bytes and about +8,509 PerfScore on ARM64), System.Number.TryParseNumber<Utf8Char>, and V8.Crypto.BigInteger:am3, where the displaced list reference is reloaded on a loop backedge.

2. Removing the isLocalVar gate lets a short-lived temp displace a local from a callee-saved register.

Comparing the local-only and unrestricted versions directly. In Microsoft.CodeAnalysis.CSharp.Binder:EnumerateAllExtensionMembersInSingleBinder on Windows x64, a multiply temp gets a weight of 3,200 (4x the block weight) and displaces arity, weighted at 2,100, from rbx. The temp itself dies before the call; it inherits the callee-save preference through related intervals. One consequence is this spill and reload:

+ mov  dword ptr [rbp+0x28], ebx    ; spill arity
  mov  r9d, ebx
  cmp  dword ptr [rcx], ecx
  call [<unknown method>]
  cmp  byte ptr [rbp-0x40], 0
+ mov  ebx, dword ptr [rbp+0x28]    ; reload arity

That takes the method from 1,396 to 1,428 bytes, PerfScore 1,610.29 to 1,695.79. On Linux x64, arity was already on the stack and the same change avoids a different spill: 1,537 to 1,504 bytes, PerfScore 1,696.75 to 1,679.75. These numbers are from the local gate comparison. Removing the gate was still beneficial overall.

System.Collections.Generic.GrowableArray1[byte]:BinarySearch[byte]` is another example. Main and the local-only variant emit identical instructions. Without the gate, the midpoint calculation takes ebp instead of the free eax, displacing the byref result argument. The loop body scores the same, but saving the byref on entry and reloading it on exit takes the method from 162 to 173 bytes, PerfScore 93.00 to 94.75.

3. Larger stack displacements can amplify the byte cost.

Microsoft.Diagnostics.Tracing.Parsers.AspNet.AspNetTraceEventParser:EnumerateTemplates on Windows x64 went from 9,399 to 9,851 bytes, PerfScore 800.12 to 823.75. Both versions have exactly 1,630 instructions. The frame grows from 88 to 584 bytes, and repeated register moves become longer stack loads:

- mov  rdx, r13
+ mov  rdx, gword ptr [rsp+0x218]
  call CORINFO_HELP_ASSIGN_REF

Larger displacements also contribute to growth in ApplicationServerTraceEventParser.EnumerateTemplates and System.Xml.XmlTextReaderImpl:ParseAttributeValueSlowAsync. Those methods also gain instructions.

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

area-CodeGen-coreclr CLR JIT compiler in src/coreclr/src/jit and related components such as SuperPMI community-contribution Indicates that the PR has been added by a community member

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants