Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JIT: Fold string fields in structs stored in static readonly fields #80431

Merged
merged 23 commits into from
Mar 11, 2023
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions src/coreclr/jit/valuenum.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5426,6 +5426,41 @@ void Compiler::fgValueNumberFieldLoad(GenTree* loadTree, GenTree* baseAddr, Fiel
{
noway_assert(fieldSeq != nullptr);

// Check if the load represents a frozen gc object located in a struct which is stored in a static readonly field,
// e.g.:
//
// struct MyStruct { string Name; }
// static readonly MyStruct MyStr = new() { Name = "Hey!" };
//
// string GetName() => MyStr.Name; // <- loadTree
//
if ((baseAddr == nullptr) && loadTree->TypeIs(TYP_REF) &&
// it should be a static field
(fieldSeq->GetKind() == FieldSeq::FieldKind::SimpleStatic))
{
uint8_t buffer[TARGET_POINTER_SIZE] = {0};
if (((UINT)offset < INT_MAX) &&
info.compCompHnd->getReadonlyStaticFieldValue(fieldSeq->GetFieldHandle(), buffer, TARGET_POINTER_SIZE,
(int)offset))
{
// In case of 64bit jit emitting 32bit codegen this handle will be 64bit
// value holding 32bit handle with upper half zeroed (hence, "= NULL").
// It's done to match the current crossgen/ILC behavior.
ssize_t objHandle = 0;
memcpy(&objHandle, buffer, TARGET_POINTER_SIZE);
if (objHandle == 0)
{
loadTree->gtVNPair.SetBoth(vnStore->VNForNull());
}
else
{
loadTree->gtVNPair.SetBoth(vnStore->VNForHandle(objHandle, GTF_ICON_OBJ_HDL));
setMethodHasFrozenObjects();
}
return;
}
}

// Two cases:
//
// 1) Instance field / "complex" static: heap[field][baseAddr][offset + load size].
Expand Down
56 changes: 54 additions & 2 deletions src/coreclr/vm/jitinterface.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -11688,8 +11688,60 @@ bool CEEInfo::getReadonlyStaticFieldValue(CORINFO_FIELD_HANDLE fieldHnd, uint8_t

if (size >= (UINT)bufferSize && valueOffset >= 0 && (UINT)valueOffset <= size - (UINT)bufferSize)
{
memcpy(buffer, (uint8_t*)baseAddr + valueOffset, bufferSize);
result = true;
// For structs containing GC pointers we want to make sure those GC pointers belong to FOH
// so we expect valueOffset to be a real field offset (same for bufferSize)
if (!field->IsRVA() && field->GetFieldType() == ELEMENT_TYPE_VALUETYPE)
{
PTR_MethodTable structType = field->GetFieldTypeHandleThrowing().AsMethodTable();
if (structType->ContainsPointers())
{
ApproxFieldDescIterator fieldIterator(structType, ApproxFieldDescIterator::INSTANCE_FIELDS);
for (FieldDesc* subField = fieldIterator.Next(); subField != NULL; subField = fieldIterator.Next())
{
// TODO: If subField is also a struct we might want to inspect its fields too
if (subField->GetOffset() == (DWORD)valueOffset && subField->GetSize() == (UINT)bufferSize &&
EgorBo marked this conversation as resolved.
Show resolved Hide resolved
subField->IsObjRef())
{
GCX_COOP();

// Read field's value
Object* subFieldValue = nullptr;
memcpy(&subFieldValue, (uint8_t*)baseAddr + valueOffset, bufferSize);

if (subFieldValue == nullptr)
{
// Report null
memset(buffer, 0, bufferSize);
result = true;
}
else if (GCHeapUtilities::GetGCHeap()->IsInFrozenSegment(subFieldValue))
EgorBo marked this conversation as resolved.
Show resolved Hide resolved
{
CORINFO_OBJECT_HANDLE handle = getJitHandleForObject(
ObjectToOBJECTREF(subFieldValue), /*knownFrozen*/ true);

// GC handle is either from FOH or null
memcpy(buffer, &handle, bufferSize);
result = true;
}

// We're done with this struct
EgorBo marked this conversation as resolved.
Show resolved Hide resolved
break;
}
}
}
else
{
// No gc pointers in the struct
EgorBo marked this conversation as resolved.
Show resolved Hide resolved
memcpy(buffer, (uint8_t*)baseAddr + valueOffset, bufferSize);
result = true;
}
}
else
{
// Primitive or RVA
memcpy(buffer, (uint8_t*)baseAddr + valueOffset, bufferSize);
result = true;
}
}
}
}
Expand Down
71 changes: 71 additions & 0 deletions src/tests/JIT/opt/ValueNumbering/StaticReadonlyStructWithGC.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
// 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 System.Threading;

class StaticReadonlyStructWithGC
{
static int Main()
{
// Pre-initialize host type
RuntimeHelpers.RunClassConstructor(typeof(StaticReadonlyStructWithGC).TypeHandle);

if (!Test1()) throw new Exception("Test1 failed");
if (!Test2()) throw new Exception("Test2 failed");
if (!Test3()) throw new Exception("Test3 failed");
if (!Test4()) throw new Exception("Test4 failed");
if (!Test5()) throw new Exception("Test5 failed");
if (!Test6()) throw new Exception("Test6 failed");
if (!Test7()) throw new Exception("Test7 failed");
if (!Test8()) throw new Exception("Test8 failed");
if (!Test9()) throw new Exception("Test9 failed");
return 100;
}

static readonly MyStruct MyStructFld = new()
{
A = "A",
B = 111111.ToString(), // non-literal
C = new MyStruct2 { A = "AA" },
D = typeof(int),
E = () => 42,
F = new MyStruct3 { A = typeof(double), B = typeof(string) },
G = new int[0],
H = null
};

[MethodImpl(MethodImplOptions.NoInlining)] static bool Test1() => MyStructFld.A == "A";
[MethodImpl(MethodImplOptions.NoInlining)] static bool Test2() => MyStructFld.B == "111111";
[MethodImpl(MethodImplOptions.NoInlining)] static bool Test3() => MyStructFld.C.A == "AA";
[MethodImpl(MethodImplOptions.NoInlining)] static bool Test4() => MyStructFld.D == typeof(int);
[MethodImpl(MethodImplOptions.NoInlining)] static bool Test5() => MyStructFld.E() == 42;
[MethodImpl(MethodImplOptions.NoInlining)] static bool Test6() => MyStructFld.F.A == typeof(double);
[MethodImpl(MethodImplOptions.NoInlining)] static bool Test7() => MyStructFld.F.B == typeof(string);
[MethodImpl(MethodImplOptions.NoInlining)] static bool Test8() => MyStructFld.G.Length == 0;
[MethodImpl(MethodImplOptions.NoInlining)] static bool Test9() => MyStructFld.H == null;

struct MyStruct
{
public string A;
public string B;
public MyStruct2 C;
public Type D;
public Func<int> E;
public MyStruct3 F;
public int[] G;
public object H;
}

struct MyStruct2
{
public string A;
}

struct MyStruct3
{
public Type A;
public Type B;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<Optimize>True</Optimize>
</PropertyGroup>
<ItemGroup>
<Compile Include="$(MSBuildProjectName).cs" />
</ItemGroup>
</Project>