You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
JIT: (bug) multi-dimensional array receiver local is re-read after index side effects (spurious NullReferenceException) #137638
When the receiver of a[i, j] is an address-exposed local that an index expression modifies (here via Interlocked.Exchange(ref a, null), which is intrinsified to xchg), the MD-array expansion in morph re-reads the local after the index side effect ran, so the new value (null) is used instead of the array evaluated first. Wrong code with FullOpts; MinOpts is correct.
Minimal Repro
usingSystem;usingSystem.Runtime.CompilerServices;usingSystem.Threading;classProgram{[MethodImpl(MethodImplOptions.NoInlining|MethodImplOptions.AggressiveOptimization)]staticintTest(int[,]a){// 'a' is evaluated first (old, non-null array); the index is 0returna[Interlocked.Exchange(refa,null)!=null?0:1,0];}staticvoidMain(){vararr=newint[1,1];arr[0,0]=42;Console.WriteLine(Test(arr));}}
Expected
42
(Also what DOTNET_JITMinOpts=1 and .NET 8 print.)
Actual
Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object.
at Program.Test(Int32[,] a)
a lives at [rsp+0x30] and is reloaded after the xchg for every bound/offset access:
xchg gword ptr [rax],rcx ; a = null ...movrcx, gword ptr [rsp+0x30] ; re-read of 'a' after the xchg => nullsubeax, dword ptr [rcx+0x18] ; NullReferenceException
.NET 8 loads the array reference before the xchg.
Regression?
Yes. 8.0.31 prints 42; 9.0.20, 10.0.12/10.0.15, 11.0.0-rc.2 and main (7bbe3a812f7) throw NullReferenceException (DOTNET_JITMinOpts=1 is correct on all). Likely introduced with the move of MD-array access expansion into morph in .NET 9 (not bisected).
Notes
MorphMDArrayVisitor::PostOrderVisit (morph.cpp) reuses arrObj directly when it is a LCL_VAR instead of copying it to a temp, so all lower-bound/length/data reads of the expansion happen after the index side effects.
The importer doesn't spill a because Interlocked.Exchange is intrinsified (no call) and the comparison is a plain ldnull; cgt.un.
Possible fix: snapshot the receiver into a temp when the local is address-exposed and/or the index operands have side effects.
Activity
dotnet-policy-service commentedon Nov 16, 2026
Tagging subscribers to this area: @JulieLeeMSFT, @jakobbotsch
See info in area-owners.md if you want to be subscribed.
JIT: Don't re-read address-exposed array locals after index side effects
JIT: don't reread array locals modified by Interlocked indices (dotne…