Skip to content

JIT: (bug) loop hoisting moves a throwing expression above a store to an EH-live local #134938

Closed

Description

@EgorBo

LICM hoists a / b into the loop preheader, ahead of state = i + 1 in the loop body. state is live into the catch handler, so when the division throws, the handler sees the old value.

Minimal Repro

using System;
using System.Runtime.CompilerServices;

public class Program
{
    public static void Main()
    {
        Console.WriteLine(Test(10, 0, 5));
    }

    [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.AggressiveOptimization)]
    static int Test(int a, int b, int n)
    {
        int state = 0;
        int sum = 0;
        try
        {
            int i = 0;
            do
            {
                state = i + 1;
                sum += a / b;
                i++;
            } while (i < n);
        }
        catch (DivideByZeroException)
        {
            return state;
        }
        return sum;
    }
}

Expected

1 (what DOTNET_JitNoHoist=1 prints)

Actual

0

Regression?

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

Notes

HoistVisitor::PostOrderVisit treats a local store as globally visible only when the local is address-exposed. That's wrong for EH-live locals (lvLiveInOutOfHndlr), because a handler can observe the store when a later instruction throws. m_canHoistSideEffects stays true, and the GTF_EXCEPT division is hoisted above the store.

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. MihuBot commented on Sep 30, 2026

    @MihuBot

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

  5. jakobbotsch commented on Sep 30, 2026

    @jakobbotsch
    Member

    Duplicate of #134379 ?

  6. added a commit that references this issue on Oct 16, 2026
    d1cf7ba
  7. locked and limited conversation to collaborators on Nov 16, 2026
  8. self-assigned this
    on Nov 17, 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