Skip to content

JIT: (bug) Loop hoisting moves a throwing division above a bounds check, so the wrong exception is raised #133585

Closed

Description

@EgorBo

Repro

using System;
using System.Runtime.CompilerServices;

internal static class Program
{
    [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.AggressiveOptimization)]
    private static int Test(int[] arr, int idx, int a, int b, int n)
    {
        int r = 0;
        for (int i = 0; i < n; i++)
        {
            r += arr[idx];
            r += a / b;
        }
        return r;
    }

    private static void Main()
    {
        try
        {
            Console.WriteLine(Test(new int[1], 5, 1, 0, 5));
        }
        catch (Exception e)
        {
            Console.WriteLine(e.GetType().Name);
        }
    }
}

arr has length 1 and idx is 5, so the very first statement of the first iteration must fault
before a / b is ever evaluated.

Expected

IndexOutOfRangeException

Actual

DivideByZeroException

Also reproduces on the Release runner with no environment variables set at all.
DOTNET_JitDoLoopHoisting=0 and DOTNET_JITMinOpts=1 both print the correct
IndexOutOfRangeException.

The invariant arr[idx] bounds check is not hoistable, but because it is loop-invariant it does
not close loop hoisting's exception-ordering barrier, so the invariant a / b is hoisted into the
preheader and executes ahead of it.

Platform

Windows x64, .NET 11 (dotnet/runtime main @ a0b86b1, Checked and Release builds). No special
env vars or CPU features required.

Activity

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

    @MihuBot

    I'm a bot. Here is a possible related and/or duplicate issue (I may be wrong):

  5. self-assigned this
    on Sep 10, 2026
  6. EgorBo commented on Sep 18, 2026

    @EgorBo
    MemberAuthor

    Affected SDK versions:

    • 9.0.318
    • 10.0.401
    • 11.0.100-rc.2.26467.112
  7. added a commit that references this issue on Sep 24, 2026
    88f9632
  8. locked and limited conversation to collaborators on Oct 25, 2026
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