Skip to content

JIT: Hoist proven non-faulting indirections - #134361

Closed
bbartels wants to merge 4 commits into
dotnet:mainfrom
bbartels:fix/jit-hoist-nonfaulting-indirections
Closed

bbartels wants to merge 4 commits into
dotnet:mainfrom
bbartels:fix/jit-hoist-nonfaulting-indirections

Conversation

@bbartels

@bbartels bbartels commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #134352. Also fixes #134379 (see "Also fixed").

Problem

Since #115626 local assertion prop also runs during morph. An invariant field load inside a loop body is
therefore usually proven non-faulting by an earlier dereference of the same object — typically the loop
test's load of another field — and is marked GTF_IND_NONFAULTING | GTF_ORDER_SIDEEFF instead of
GTF_EXCEPT. Loop hoisting rejects every GTF_ORDER_SIDEEFF node, so .NET 10 stopped hoisting obj.Field
loads that .NET 9 hoisted. Such loops also lost their preheader and with it their alignment.

The simplest shape, for (int j = 0; j < N; j++) sum += V[j]; with N, V fields of this
(FullOpts, x64; [rdi] is this):

; .NET 10 / .NET 11 RC1 — 52 bytes; the array reference is reloaded every iteration
       mov      ecx, dword ptr [rdi+0x18]        ; N
       test     ecx, ecx
       jle      SHORT G_M_IG04
       align    [15 bytes for IG03]
G_M_IG03:
       mov      rdx, qword ptr [rdi+0x08]        ; V, inside the loop
       movsxd   rsi, eax
       vaddsd   xmm0, xmm0, qword ptr [rdx+8*rsi]
       inc      eax
       cmp      eax, ecx
       jl       SHORT G_M_IG03
; with this change — 48 bytes, byte-for-byte the .NET 9 listing
       mov      ecx, dword ptr [rdi+0x18]        ; N
       test     ecx, ecx
       jle      SHORT G_M_IG05
G_M_IG03:
       mov      rdx, qword ptr [rdi+0x08]        ; V, hoisted into the preheader
       align    [11 bytes for IG04]
G_M_IG04:
       movsxd   rdi, eax
       vaddsd   xmm0, xmm0, qword ptr [rdx+8*rdi]
       inc      eax
       cmp      eax, ecx
       jl       SHORT G_M_IG04

The Benchmarks Game spectral-norm program hits this in its Parallel.For inner loop (closure fields v and
n): NativeAOT .NET 9 0.333 s, .NET 11 RC1 0.356 s (see below). Any loop that reads a field of a parameter,
of this, or of a closure inside the body is affected.

Solution

Let the hoister admit such a load when it is a GT_IND of an object-reference local at offset zero or at
the offset of an instance field within the null page, and the address carries no effects of its own
(optIsOrderConstrainedFieldLoad). Executed anywhere, such a load throws NullReferenceException exactly
when the object is null and cannot fault otherwise.

The copy placed in the preheader is turned back into a possibly-faulting load: GTF_IND_NONFAULTING is
cleared, the flags are recomputed (GTF_EXCEPT), and the null-reference exception is added to its value
number unconditionally (a method-table load of an object with a known exact type has a constant value and
can still fault), so nothing downstream depends on the dereference that proved the original. The copy keeps
GTF_ORDER_SIDEEFF so that, when the preheader lies in an enclosing loop, that loop hoists it under the same
rule rather than as an ordinary faulting load (hoisting is inner-first and the inner preheader is often the
outer header).

The load is hoisted only from the loop header, before any side effect (the rule GTF_EXCEPT loads already
have), and only if everything that could throw before it is a null check of the same object
(CanHoistOrderingLoad). Then, when the object is null, the loop's first observable event was already that
NullReferenceException — the proving dereference is before the loop, or in the header before the load —
and when it is not null the copy cannot fault. Because no other kind of exception may precede it, the copy
can never overtake a different exception either. (This is stricter than .NET 9, which hoisted the same loads
above unhoisted invariant bounds checks.)

Not admitted: loads at offsets beyond the null page (morph keeps an explicit NULLCHECK in front of them,
which may legitimately stay in the loop), loads through byrefs or native pointers ("not null" does not make
base + offset addressable), and addresses with ordering effects of their own (byrefs formed after a bounds
check or an unbox null check).

Also fixed

The hoister treated a store to a local as invisible unless the local was address exposed. A local that is
live into a catch/finally/filter is observable too, as the alias analysis in sideeffects.h already
states, and the hoister moved possibly-faulting loads above such stores — a pre-existing wrong-code bug that
reproduces on .NET 6–10 with a plain sum += d.N in a do/while inside a try (#134379). Such
stores are now barriers like address-exposed ones (IsHandlerVisibleLocalStore). This makes hoisting
slightly stricter in methods with EH, which SPMI will show as small size increases there.

Benefits

  • Restores .NET 9 codegen for invariant field loads in loops (the common this.Field / param.Field /
    closure-capture shapes): one load per loop instead of one per iteration, and the loop gets its preheader
    and alignment back.
  • Safe by construction: the preheader copy is an honest faulting load with honest flags and value number;
    the hoisting position is restricted so that no exception can be moved ahead of another or ahead of an
    observable store.
  • Closes a pre-existing wrong-code hole for handler-visible locals.

Benchmarks

All measurements: Linux x64 (AMD EPYC 73F3), .NET 11.0.0-rc.1 runtime and libraries. "Baseline" and "this PR"
are the same checked JIT build of the RC1 tag with and without this change, loaded as alt-JITs (so both
sides pay the same checked-build JIT throughput; steady-state code is what a release JIT emits). NativeAOT
uses the RC1 ILCompiler with its JIT replaced the same way. .NET 9 = 9.0.17 release. Paired A/B processes,
alternating order, medians.

Microbenchmarks (µs per call, 4096 elements)

kernel config baseline this PR change .NET 9
IntFieldSum — for (i < N) s += I[i], throughput-bound FullOpts 2.128 1.499 −29.5% 1.501
Tier1, PGO off 2.096 1.499 −28.5% —
Tier1, PGO on (default) 2.104 1.504 −28.6% 1.508
NativeAOT 2.119 1.509 −28.8% —
IntFieldSumByHand — same loop with the fields copied to locals first (control) all four 1.056–1.065 1.060–1.065 ±0.6% 1.065
FieldSum, FieldCountAbove, ClosureSpectral, GuardedAfterStore, LocalsHoistedByHand (FP, latency-bound) all four −1.2% … +0.8% =
FieldSumScalar JIT configs 4.73–4.79 4.73–4.74 ±1.2% 4.75
NativeAOT 5.331 4.774 −10.4% ¹

The double-precision kernels sit on the dependency chain of the FP accumulator, so removing a load per
iteration does not shorten the critical path; the integer kernel is throughput-bound and shows the full
effect. The fixed loop is now identical to what .NET 9 produced (and a by-hand copy to locals remains faster
in both, because loop cloning only recognises array locals — unrelated to this change).

¹ Code placement, not the hoist: the stock FieldSumScalar has its loop head at mod 64 = 49; relinking the
unchanged stock code 32 bytes further (by editing an unrelated method) gives 4.81 µs. The JIT rows, whose loop
alignment is under JIT control, show the true effect of the hoist for this latency-bound loop: none.

Whole program: Benchmarks Game spectral-norm, n = 5500, 4 cores, 10 interleaved rounds (median wall time)

.NET 9 .NET 11 RC1 baseline this PR hand-hoisted source (RC1)
NativeAOT 0.333 s 0.356 s 0.332 s (−6.7%) 0.329 s
JIT, TieredCompilation=0 0.378 s 0.401 s 0.371 s (−7.5%) —
JIT, tiered + PGO (TC_CallCountingDelayMs=0) 0.399 s ² 0.476 s 0.452 s (−5.0%) —
JIT, tiered + PGO, n = 11000 1.272 s ² 1.384 s 1.318 s (−4.8%) —

The change recovers the whole .NET 9 → 10 regression on this program and lands where hand-hoisting does.
Inner loop (NativeAOT): 30 → 29 instructions, the closure-field load moved out of the loop and the loop head
aligned to 32 bytes:

; RC1: loop head at ...a37 (mod 32 = 23), closure field reloaded every iteration
>> 125a37: mov rdx,QWORD PTR [rdi+0x8]
   125a3b: movsxd r8,eax
   125a3e: vmovups xmm1,XMMWORD PTR [rdx+r8*8]
   ...
   125aa0: jl 125a37

; this PR: load in the preheader, loop head at ...a60 (mod 32 = 0)
   125a5b: mov rdx,QWORD PTR [rdi+0x8]
>> 125a60: movsxd r8,eax
   125a63: vmovups xmm1,XMMWORD PTR [rdx+r8*8]
   ...
   125acc: jl 125a60

² The remaining gap to .NET 9 in the tiered rows is JIT throughput of the checked alt-JIT during tiering,
not codegen: CPU time in the FullOpts rows is 1.188 s (.NET 9) vs 1.148 s (this PR).

Changes

  • optimizer.cpp: optIsObjectFieldAddress, Compiler::optIsOrderConstrainedFieldLoad,
    Compiler::optIsNullCheckOfLocal; HoistVisitor::CanHoistOrderingLoad, RecordMayThrow,
    IsHandlerVisibleLocalStore; IsNodeHoistable admits order-constrained field loads;
    optPerformHoistExpr converts the hoisted copy.
  • compiler.h: the two Compiler method declarations.
  • src/tests/JIT/Regression/JitBlue/Runtime_134352: each loop shape run with a null object — loads after a
    store must not be hoisted above it; competing exceptions (SumMixedExceptions, also nested); zero-trip
    loops; a large-offset field must throw NullReferenceException, not crash (the failure mode of the first
    version of this change). The shapes that need the proving load to stay in the loop use 28 integer
    arguments, which exceeds the integer hoisting budget of every target (28 registers at most, x64 with APX),
    and do/while so that the body is the loop header regardless of size.
  • src/tests/JIT/Regression/JitBlue/Runtime_134379: handler-visible locals observed through catch and
    finally, including the plain pre-existing shape, which fails on the current JIT (the handler sees -1
    instead of 1).
  • src/tests/JIT/opt/Hoisting/HoistNonFaultingFieldLoad (disasm check): field loads outside the loop,
    including the decisive shape where the proving d.Count load stays in the loop (unprofitable to hoist)
    while the dependent d.Scale load leaves; a load preceded by a possible IndexOutOfRangeException on
    another object stays inside. Patterns are ISA-agnostic (hold with EnableAVX=0 and EVEX stress) and anchored
    to the loop; the negative case uses a bounds check, which no optimization pass hoists, so the check also holds
    under JitOptRepeat. Fails on the current JIT, passes with the change (verified with FileCheck against
    JitDisasm output in all four configurations).

Verification

  • Disasm checks: fail on the unpatched JIT, pass with the change (validated with FileCheck against real
    JitDisasm output, checked JIT).
  • The regression test and the probes behind each of its shapes pass with a checked JIT (asserts on) in
    TieredCompilation=0, Tier1 without PGO and Tier1 with PGO; spectral-norm, mandelbrot (output MD5) and
    a 40-workload LINQ sweep produce identical results.
  • NativeAOT: ILC with this JIT on spectral-norm — inner loop 30 → 29 instructions, closure load hoisted, loop
    aligned (listing in the Benchmarks section).
  • clang-format with the JIT style: no changes.
  • Not run: the full JIT test suite and SuperPMI asm diffs / TP — please trigger superpmi-diffs. Expected:
    small size reductions wherever an invariant field load sits in a loop header; small increases (a
    callee-saved register for the hoisted value) in shared-generic iterators; small increases in EH methods
    from the handler-visible-store barrier.

Line counts (vs main)

Category Files + −
Runtime (JIT) compiler.h, optimizer.cpp 243 7
Tests Runtime_134352.{cs,csproj}, Runtime_134379.{cs,csproj}, HoistNonFaultingFieldLoad.{cs,csproj} 569 0
Documentation / Configuration — 0 0

Allow nonvolatile indirections marked as non-faulting with an ordering side effect to participate in loop hoisting while preserving the same side-effect ordering constraints as faulting indirections.

Add disassembly and behavioral coverage for reference and scalar field loads and for null-fault ordering around stores.

Fixes dotnet#134352

Signed-off-by: Benjamin Bartels <[email protected]>
Copilot AI lite review requested due to automatic review settings September 21, 2026 18:40
@dotnet-policy-service dotnet-policy-service Bot added the community-contribution Indicates that the PR has been added by a community member label Sep 21, 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 Sep 21, 2026
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 5 pipeline(s).
11 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.

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.

Copilot review overview

🟢 Approval recommended

No unresolved review issues were identified, and all approval-readiness assessments support approval.

Review effort: Lite
Findings: None

What changed in this PR

Restores JIT loop hoisting for assertion-proven non-faulting indirections while preserving side-effect ordering.

Changes:

  • Enables guarded hoisting for eligible nonvolatile indirections.
  • Preserves ordering constraints around side effects.
  • Adds disassembly and null-fault regression coverage.
File Description
src/​tests/​JIT/​Regression/​JitBlue/​Runtime_134352/​Runtime_134352.csproj Configures isolated execution and disassembly checks.
src/​tests/​JIT/​Regression/​JitBlue/​Runtime_134352/​Runtime_134352.cs Adds hoisting and fault-ordering regression tests.
src/​coreclr/​jit/​optimizer.cpp Updates hoisting eligibility and ordering logic.

@bbartels
bbartels marked this pull request as draft September 21, 2026 18:48
Comment thread src/coreclr/jit/optimizer.cpp Resolved
Apply the replacement jit2.diff exactly, tracking prior exception and handler-visible store ordering and restoring faulting semantics on hoisted field-load copies.

Replace the previous regression coverage with the behavioral and codegen cases supplied in the patch. Linux x64 Release clr.jit build succeeded; no tests were run for this revision.

Signed-off-by: Benjamin Bartels <[email protected]>
Replace the prior implementation with the supplied jit3.diff exactly.
Strengthen SSE/AVX-compatible codegen assertions, unhoisted prerequisite
coverage, exception ordering, zero-trip cases, and handler-visible stores.

Linux x64 Release clr.jit build succeeded for the exact committed source
tree. No tests or disassembly checks were run for this revision.

Signed-off-by: Benjamin Bartels <[email protected]>
Restore the existing helper for hoisted-load exception metadata and remove
the rationale for constant-valued loads already excluded by CSE eligibility.
Preserve fault restoration and all jit3 regression coverage.

Linux x64 Release clr.jit build passed for this source tree. No tests or
disassembly checks were run.

Signed-off-by: Benjamin Bartels <[email protected]>
@bbartels
bbartels marked this pull request as ready for review September 22, 2026 01:10
Copilot AI review requested due to automatic review settings September 22, 2026 01:10

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.

Copilot review overview

🔵 Needs a closer look

JIT optimizer changes are high risk, and the final revision was not tested beyond compilation.

Review effort: Lite
Findings: None

@bbartels

bbartels commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor Author

@EgorBo Feel free to have a look now, i am way out of my depth here, so feel free to close/amend the pr in any way you see fit :)

@bbartels

Copy link
Copy Markdown
Contributor Author
image Some numbers of BCL APIs

@EgorBo

EgorBo commented Sep 22, 2026 •

Copy link
Copy Markdown
Member

i am way out of my depth here

I appreciate the effort, but I'd suggest starting with something simpler for your first JIT contribution. You picked a very complex area that might require refactoring on our end first. While I know AI can feel like it can one-shot anything these days, our experience shows it still requires guidance from us to get things right from both an architectural and correctness standpoint.

PS: I can easily recognize Antropic models by its 10:1 not-very-helpful comments to actual code ratio

@bbartels

bbartels commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor Author

i am way out of my depth here

I appreciate the effort, but I'd suggest starting with something simpler for your first JIT contribution. You picked a very complex area that might require refactoring on our end first. While I know AI can feel like it can one-shot anything these days, our experience shows it still requires guidance from us to get things right from both an architectural and correctness standpoint.

PS: I can easily recognize Antropic models by its 10:1 not-very-helpful comments to actual code ratio

totally, meant for this to primarily be a reference for you to work with, rather than actually getting this in directly! Happy for you to take ownership, close/amend/merge as you please :) Dont have a personal attachment to getting a change in, just out for a better runtime 🎉

PS: And you'd be correct on the model 😆 This was fable-5.1 max (writer) / astra max (reviewer) going 6-7 rounds at each other

@EgorBo EgorBo closed this Oct 16, 2026
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

3 participants