Skip to content

JIT: (bug) loop hoisting moves a throwing idiv above a finalizable object allocation #134936

Description

@EgorBo

LICM hoists a / b into the loop preheader, ahead of a new F() that comes before it in the loop body. F is finalizable. When the division throws, the object was never allocated, so its finalizer never runs.

Minimal Repro

using System;
using System.Runtime.CompilerServices;

class F
{
    public static int Count;
    ~F() => Count++;
}

public class Program
{
    public static void Main()
    {
        try
        {
            Test(1, 0, 10);
        }
        catch (DivideByZeroException) { }
        GC.Collect();
        GC.WaitForPendingFinalizers();
        Console.WriteLine(F.Count);
    }

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

Expected

1 (what MinOpts and DOTNET_JitNoHoist=1 print)

Actual

0

Regression?

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

Notes

In HoistVisitor::PostOrderVisit, a helper call that can't be hoisted clears m_canHoistSideEffects only on MutatesHeap, MayRunCctor, or !NoThrow. CORINFO_HELP_NEWFAST passes all three checks, so the flag stays true and the throwing idiv gets hoisted above the allocation. The JIT should also check GTF_CALL_M_ALLOC_SIDE_EFFECTS (or HasSideEffects) here.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-CodeGen-coreclrCLR JIT compiler in src/coreclr/src/jit and related components such as SuperPMI

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions