diff --git a/src/coreclr/jit/objectalloc.cpp b/src/coreclr/jit/objectalloc.cpp index 4042fd7063fa73..012248266bf701 100644 --- a/src/coreclr/jit/objectalloc.cpp +++ b/src/coreclr/jit/objectalloc.cpp @@ -2203,12 +2203,20 @@ void ObjectAllocator::AnalyzeParentStack(ArrayStack* parentStack, unsi switch (comp->lookupNamedIntrinsic(call->gtCallMethHnd)) { case NI_System_SpanHelpers_ClearWithoutReferences: - case NI_System_SpanHelpers_Fill: case NI_System_SpanHelpers_Memmove: case NI_System_SpanHelpers_SequenceEqual: canLclVarEscapeViaParentStack = false; break; + case NI_System_SpanHelpers_Fill: + // For Fill only the first (byref span) arg does not escape + // + if (tree == call->gtArgs.GetUserArgByIndex(0)->GetNode()) + { + canLclVarEscapeViaParentStack = false; + } + break; + default: break; } diff --git a/src/tests/JIT/opt/ObjectStackAllocation/Runtime_122879.cs b/src/tests/JIT/opt/ObjectStackAllocation/Runtime_122879.cs new file mode 100644 index 00000000000000..6dc40977139db9 --- /dev/null +++ b/src/tests/JIT/opt/ObjectStackAllocation/Runtime_122879.cs @@ -0,0 +1,39 @@ +// 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 Poco(string value) +{ + public string Value { get; } = value; +} + +public class Runtime_122879 +{ + [MethodImpl(MethodImplOptions.NoInlining)] + static void StackTrasher() + { + Guid heavy = Guid.NewGuid(); + heavy.ToString(); + } + + [MethodImpl(MethodImplOptions.AggressiveOptimization | MethodImplOptions.NoInlining)] + static Poco[] Creator() => CreateArray(new Poco("Passed"), 2); + + static T[] CreateArray(T value, int count) + { + var output = new T[count]; + output.AsSpan().Fill(value); + return output; + } + + [Fact] + public static void Test() + { + var result = Creator(); + StackTrasher(); // Removing this line makes it work as expected + Console.WriteLine(result[0].Value); + } +} diff --git a/src/tests/JIT/opt/ObjectStackAllocation/Runtime_122879.csproj b/src/tests/JIT/opt/ObjectStackAllocation/Runtime_122879.csproj new file mode 100644 index 00000000000000..501217e4d86892 --- /dev/null +++ b/src/tests/JIT/opt/ObjectStackAllocation/Runtime_122879.csproj @@ -0,0 +1,9 @@ + + + None + True + + + + +