From 96e58e5982a01ec63ebc260c240475d3cd987482 Mon Sep 17 00:00:00 2001 From: Rachel Jarvi Date: Wed, 2 Dec 2026 15:49:31 -0800 Subject: [PATCH] fix narrowing --- src/coreclr/jit/gentree.cpp | 14 ++++++++-- .../JIT/Regression_ro_2/Runtime_138344.cs | 26 +++++++++++++++++++ 2 files changed, 38 insertions(+), 2 deletions(-) create mode 100644 src/tests/JIT/Regression_ro_2/Runtime_138344.cs diff --git a/src/coreclr/jit/gentree.cpp b/src/coreclr/jit/gentree.cpp index 1826e688236a22..b5a489080d6e24 100644 --- a/src/coreclr/jit/gentree.cpp +++ b/src/coreclr/jit/gentree.cpp @@ -17402,10 +17402,20 @@ GenTree* Compiler::gtTryRemoveBoxUpstreamEffects(GenTree* op, BoxRemovalOptions } } + // The copy store implicitly normalizes small-typed values, and morph may + // have already removed an explicit cast from its source. + GenTree* boxedValue = copySrc; + if (varTypeIsSmall(copy) && fgCastNeeded(copySrc, copy->TypeGet()) && + !(copySrc->IsIntegralConst() && + IntegralRange::ForType(copy->TypeGet()).Contains(copySrc->AsIntConCommon()->IntegralValue()))) + { + boxedValue = gtNewCastNode(TYP_INT, copySrc, false, copy->TypeGet()); + } + // If this was a trial removal, we're done. if (options == BR_DONT_REMOVE) { - return copySrc; + return boxedValue; } if (options == BR_DONT_REMOVE_WANT_TYPE_HANDLE) @@ -17472,7 +17482,7 @@ GenTree* Compiler::gtTryRemoveBoxUpstreamEffects(GenTree* op, BoxRemovalOptions } else { - return copySrc; + return boxedValue; } } diff --git a/src/tests/JIT/Regression_ro_2/Runtime_138344.cs b/src/tests/JIT/Regression_ro_2/Runtime_138344.cs new file mode 100644 index 00000000000000..091c67b29b6888 --- /dev/null +++ b/src/tests/JIT/Regression_ro_2/Runtime_138344.cs @@ -0,0 +1,26 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System; +using System.Runtime.CompilerServices; +using Xunit; + +public class Runtime_138344 +{ + private enum E : byte + { + A = 1 + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static Enum Box(int x) => (E)x; + + [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.AggressiveOptimization)] + private static bool Test(int x) => E.A.HasFlag(Box(x)); + + [Fact] + public static void TestEntryPoint() + { + Assert.True(Test(0x101)); + } +}