Skip to content

JIT: (bug) redundant branch opts remove a null check that a non-faulting load depends on (spurious NullReferenceException) #135811

Description

@EgorBo

In FullOpts, optRedundantDominatingBranch removes the dominating obj != null check even though obj.Value in the dominated block was marked non-faulting only because of that check. The load then runs with obj == null and throws a spurious NullReferenceException in valid safe C#.

Minimal Repro

using System;
using System.Runtime.CompilerServices;

class C { public int Value; }

class Program
{
    [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.AggressiveOptimization)]
    static int Test(C obj)
    {
        bool notNull = obj != null;
        if (obj != null)
        {
            if (notNull & (obj.Value > 0))
                return 1;
        }
        return 3;
    }

    static void Main() => Console.WriteLine(Test(null));
}

Expected

3 (obj is null, so obj.Value is never evaluated).

Actual

Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object.
   at Program.Test(C obj)
   at Program.Main()

The outer obj != null branch is gone and cmp dword ptr [rcx+0x08], 0 executes unconditionally.

Regression?

Yes, a regression in .NET 11 (not bisected): 8.0.x, 9.0.x and 10.0.12 print 3; 11.0.0-rc.1 and current main throw.

Notes

  • DOTNET_JitDoRedundantBranchOpts=0 and DOTNET_JITMinOpts=1 both print 3.
  • Morph's non-null assertion prop marks the obj.Value IND as GTF_IND_NONFAULTING (clearing GTF_EXCEPT) because of the obj != null guard. Redundant branch opts then infer that same guard from the AND(notNull, obj.Value > 0) predicate and fold it away.
  • Its side-effect check (BasicBlock::hasSideEffects() -> GTF_SIDE_EFFECT) doesn't see the non-faulting IND (it only carries GTF_ORDER_SIDEEFF | GTF_GLOB_REF). Same pattern as JIT: (bug) x >= 0 && x < (a[x] & int.MaxValue) drops the x >= 0 guard #134202 (fixed in FoldNeverNegativeRangeTest).

Activity

  1. added this to the 12.0.0 milestone on Oct 14, 2026
  2. added
    area-CodeGen-coreclr
    on Oct 14, 2026
  3. dotnet-policy-service commented on Oct 14, 2026

    @dotnet-policy-service
    Contributor

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

  4. self-assigned this
    on Nov 24, 2026
  5. added a commit that references this issue on Nov 25, 2026
    9899e0b
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area-CodeGen-coreclr

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions