From ad35f3ab42337a422ea453579cbf117e8257fce7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Petryka?= Date: Thu, 29 Feb 2024 23:18:48 +0100 Subject: [PATCH 1/2] Optimize casts from constant byrefs --- src/coreclr/jit/morph.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/coreclr/jit/morph.cpp b/src/coreclr/jit/morph.cpp index 81394493fa8b09..64a2f469e8c8b7 100644 --- a/src/coreclr/jit/morph.cpp +++ b/src/coreclr/jit/morph.cpp @@ -561,6 +561,13 @@ GenTree* Compiler::fgMorphExpandCast(GenTreeCast* tree) // we fix this by copying the GC pointer to a non-gc pointer temp. noway_assert(!varTypeIsGC(dstType) && "How can we have a cast to a GCRef here?"); + // we can just change the type for constant addresses + if (oper->IsCnsIntOrI()) + { + oper->gtType = TYP_I_IMPL; + return fgMorphTree(gtNewCastNode(TYP_I_IMPL, oper, false, dstType)); + } + // We generate an assignment to an int and then do the cast from an int. With this we avoid // the gc problem and we allow casts to bytes, longs, etc... unsigned lclNum = lvaGrabTemp(true DEBUGARG("Cast away GC")); From e52a42b771a81470058558206080de0ce277cfc4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Petryka?= Date: Sat, 2 Mar 2024 18:09:44 +0100 Subject: [PATCH 2/2] Retype BYREF constants instead of folding a new cast --- src/coreclr/jit/morph.cpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/coreclr/jit/morph.cpp b/src/coreclr/jit/morph.cpp index 64a2f469e8c8b7..7a3c99d10474a7 100644 --- a/src/coreclr/jit/morph.cpp +++ b/src/coreclr/jit/morph.cpp @@ -561,11 +561,12 @@ GenTree* Compiler::fgMorphExpandCast(GenTreeCast* tree) // we fix this by copying the GC pointer to a non-gc pointer temp. noway_assert(!varTypeIsGC(dstType) && "How can we have a cast to a GCRef here?"); - // we can just change the type for constant addresses - if (oper->IsCnsIntOrI()) + // we can just retype byref constants + if (oper->IsCnsIntOrI() && oper->TypeIs(TYP_BYREF) && varTypeIsI(dstType)) { - oper->gtType = TYP_I_IMPL; - return fgMorphTree(gtNewCastNode(TYP_I_IMPL, oper, false, dstType)); + assert(srcType == TYP_BYREF); + oper->gtType = dstType; + return fgMorphTree(oper); } // We generate an assignment to an int and then do the cast from an int. With this we avoid