Skip to content

JIT: (bug) loop hoisting reorders exceptions when an earlier throwing candidate is rejected as unprofitable #134937

Closed

Description

@EgorBo

LICM hoists a / b into the preheader but leaves the earlier arr.Length null check in the loop, because hoisting it isn't profitable. The program then throws DivideByZeroException instead of NullReferenceException.

Minimal Repro

using System;
using System.Runtime.CompilerServices;

public class Program
{
    public static void Main()
    {
        try
        {
            Test(null, 1, 0, 2, 10);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.GetType().Name);
        }
    }

    [MethodImpl(MethodImplOptions.NoInlining)]
    static void Consume(int x) { }

    [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.AggressiveOptimization)]
    static int Test(int[] arr, int a, int b, int c, int n)
    {
        int sum = 0;
        for (int i = 0; i < n; i++)
        {
            sum += arr.Length;
            sum += a / b + c;
            Consume(sum + i);
        }
        return sum;
    }
}

Expected

NullReferenceException (what MinOpts prints)

Actual

DivideByZeroException

Regression?

No. .NET 8, 9, 10, 11 RC2, and main all print DivideByZeroException.

Notes

HoistVisitor::PostOrderVisit marks ARR_LENGTH(arr) as hoistable, so m_canHoistSideEffects stays true. optHoistCandidate then rejects that candidate as unprofitable ("tree cost too low"). The next tree, a / b + c, isn't blocked by the GTF_EXCEPT ordering check and is hoisted above the null check that stays in the loop. A throwing candidate that is rejected should act as an exception-ordering barrier.

Activity

  1. added this to the 12.0.0 milestone on Sep 30, 2026
  2. added
    area-CodeGen-coreclr
    on Sep 30, 2026
  3. dotnet-policy-service commented on Sep 30, 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. jakobbotsch commented on Sep 30, 2026

    @jakobbotsch
    Member

    Is this different from #133585 ? (That one was already fixed, so probably?)

  5. self-assigned this
    on Nov 6, 2026
  6. added a commit that references this issue on Nov 12, 2026
    68b16fb
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