Repository navigation
Conversation
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]>
|
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. |
|
Tagging subscribers to this area: @JulieLeeMSFT, @jakobbotsch |
There was a problem hiding this comment.
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. |
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]>
|
@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 :) |
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 |

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_SIDEEFFinstead ofGTF_EXCEPT. Loop hoisting rejects everyGTF_ORDER_SIDEEFFnode, so .NET 10 stopped hoistingobj.Fieldloads 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];withN,Vfields ofthis(FullOpts, x64;
[rdi]isthis):The Benchmarks Game spectral-norm program hits this in its
Parallel.Forinner loop (closure fieldsvandn): 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_INDof an object-reference local at offset zero or atthe offset of an instance field within the null page, and the address carries no effects of its own
(
optIsOrderConstrainedFieldLoad). Executed anywhere, such a load throwsNullReferenceExceptionexactlywhen the object is null and cannot fault otherwise.
The copy placed in the preheader is turned back into a possibly-faulting load:
GTF_IND_NONFAULTINGiscleared, the flags are recomputed (
GTF_EXCEPT), and the null-reference exception is added to its valuenumber 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_SIDEEFFso that, when the preheader lies in an enclosing loop, that loop hoists it under the samerule 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_EXCEPTloads alreadyhave), 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 thatNullReferenceException— 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
NULLCHECKin front of them,which may legitimately stay in the loop), loads through byrefs or native pointers ("not null" does not make
base + offsetaddressable), and addresses with ordering effects of their own (byrefs formed after a boundscheck or an
unboxnull 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 insideeffects.halreadystates, 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.Nin ado/whileinside atry(#134379). Suchstores are now barriers like address-exposed ones (
IsHandlerVisibleLocalStore). This makes hoistingslightly stricter in methods with EH, which SPMI will show as small size increases there.
Benefits
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.
the hoisting position is restricted so that no exception can be moved ahead of another or ahead of an
observable store.
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)
IntFieldSum—for (i < N) s += I[i], throughput-boundIntFieldSumByHand— same loop with the fields copied to locals first (control)FieldSum,FieldCountAbove,ClosureSpectral,GuardedAfterStore,LocalsHoistedByHand(FP, latency-bound)FieldSumScalarThe 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
FieldSumScalarhas its loop head atmod 64 = 49; relinking theunchanged 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)
TieredCompilation=0TC_CallCountingDelayMs=0)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:
² 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;IsNodeHoistableadmits order-constrained field loads;optPerformHoistExprconverts the hoisted copy.compiler.h: the twoCompilermethod declarations.src/tests/JIT/Regression/JitBlue/Runtime_134352: each loop shape run with a null object — loads after astore must not be hoisted above it; competing exceptions (
SumMixedExceptions, also nested); zero-triploops; a large-offset field must throw
NullReferenceException, not crash (the failure mode of the firstversion 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/whileso that the body is the loop header regardless of size.src/tests/JIT/Regression/JitBlue/Runtime_134379: handler-visible locals observed throughcatchandfinally, including the plain pre-existing shape, which fails on the current JIT (the handler sees-1instead of
1).src/tests/JIT/opt/Hoisting/HoistNonFaultingFieldLoad(disasm check): field loads outside the loop,including the decisive shape where the proving
d.Countload stays in the loop (unprofitable to hoist)while the dependent
d.Scaleload leaves; a load preceded by a possibleIndexOutOfRangeExceptiononanother object stays inside. Patterns are ISA-agnostic (hold with
EnableAVX=0and EVEX stress) and anchoredto 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 againstJitDisasmoutput in all four configurations).Verification
JitDisasmoutput, checked JIT).TieredCompilation=0, Tier1 without PGO and Tier1 with PGO; spectral-norm, mandelbrot (output MD5) anda 40-workload LINQ sweep produce identical results.
aligned (listing in the Benchmarks section).
clang-formatwith the JIT style: no changes.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)compiler.h,optimizer.cppRuntime_134352.{cs,csproj},Runtime_134379.{cs,csproj},HoistNonFaultingFieldLoad.{cs,csproj}