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

Improve the performance of ConditionalWeakTable.TryGetValue #80059

Merged
merged 17 commits into from
Jan 5, 2023
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
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
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,17 @@ public static unsafe void PrepareMethod(RuntimeMethodHandle method, RuntimeTypeH
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern int GetHashCode(object? o);

/// <summary>
/// If a hash code has been assigned to the object, it is returned. Otherwise zero is
/// returned.
/// </summary>
/// <remarks>
/// The advantage of this over <see cref="GetHashCode" /> is that it avoids assigning a hash
/// code to the object if it does not already have one.
/// </remarks>
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern int TryGetHashCode(object o);

[MethodImpl(MethodImplOptions.InternalCall)]
public static extern new bool Equals(object? o1, object? o2);

Expand Down
41 changes: 41 additions & 0 deletions src/coreclr/classlibnative/bcltype/objectnative.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,47 @@ FCIMPL1(INT32, ObjectNative::GetHashCode, Object* obj) {
}
FCIMPLEND

FCIMPL1(INT32, ObjectNative::TryGetHashCode, Object* obj) {

CONTRACTL
{
FCALL_CHECK;
}
CONTRACTL_END;

VALIDATEOBJECT(obj);

if (obj == 0)
return 0;

OBJECTREF objRef(obj);

{
DWORD bits = objRef->GetHeader()->GetBits();

if (bits & BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX)
{
if (bits & BIT_SBLK_IS_HASHCODE)
{
// Common case: the object already has a hash code
return bits & MASK_HASHCODE;
}
else
{
// We have a sync block index. There may be a hash code stored within the sync block.
SyncBlock *psb = objRef->PassiveGetSyncBlock();
if (psb != NULL)
{
return psb->GetHashCode();
}
}
}
}

return 0;
}
FCIMPLEND

//
// Compare by ref for normal classes, by value for value types.
//
Expand Down
1 change: 1 addition & 0 deletions src/coreclr/classlibnative/bcltype/objectnative.h
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ class ObjectNative
// If the Class object doesn't exist then you must call the GetClass() method.
static FCDECL1(Object*, GetObjectValue, Object* vThisRef);
static FCDECL1(INT32, GetHashCode, Object* vThisRef);
static FCDECL1(INT32, TryGetHashCode, Object* vThisRef);
static FCDECL2(FC_BOOL_RET, Equals, Object *pThisRef, Object *pCompareRef);
static FCDECL1(Object*, AllocateUninitializedClone, Object* pObjUNSAFE);
static FCDECL1(Object*, GetClass, Object* pThis);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,19 @@ public static unsafe int GetHashCode(object o)
return ObjectHeader.GetHashCode(o);
}

/// <summary>
/// If a hash code has been assigned to the object, it is returned. Otherwise zero is
/// returned.
/// </summary>
/// <remarks>
/// The advantage of this over <see cref="GetHashCode" /> is that it avoids assigning a hash
/// code to the object if it does not already have one.
/// </remarks>
internal static int TryGetHashCode(object o)
{
return ObjectHeader.TryGetHashCode(o);
}

[Obsolete("OffsetToStringData has been deprecated. Use string.GetPinnableReference() instead.")]
public static int OffsetToStringData
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,38 @@ public static unsafe int GetHashCode(object o)
}
}

/// <summary>
/// If a hash code has been assigned to the object, it is returned. Otherwise zero is
/// returned.
/// </summary>
public static unsafe int TryGetHashCode(object o)
{
if (o == null)
return 0;

fixed (MethodTable** ppMethodTable = &o.GetMethodTableRef())
{
int* pHeader = GetHeaderPtr(ppMethodTable);
int bits = *pHeader;
int hashOrIndex = bits & MASK_HASHCODE_INDEX;
if ((bits & BIT_SBLK_IS_HASHCODE) != 0)
{
// Found the hash code in the header
Debug.Assert(hashOrIndex != 0);
return hashOrIndex;
}

if ((bits & BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX) != 0)
{
// Look up the hash code in the SyncTable
return SyncTable.GetHashCode(hashOrIndex);
}

// The hash code has not yet been set.
return 0;
}
}

/// <summary>
/// Assigns a hash code to the object in a thread-safe way.
/// </summary>
Expand Down
1 change: 1 addition & 0 deletions src/coreclr/vm/ecalllist.h
Original file line number Diff line number Diff line change
Expand Up @@ -552,6 +552,7 @@ FCFuncStart(gRuntimeHelpers)
FCFuncElement("GetSpanDataFrom", ArrayNative::GetSpanDataFrom)
FCFuncElement("PrepareDelegate", ReflectionInvocation::PrepareDelegate)
FCFuncElement("GetHashCode", ObjectNative::GetHashCode)
FCFuncElement("TryGetHashCode", ObjectNative::TryGetHashCode)
FCFuncElement("Equals", ObjectNative::Equals)
FCFuncElement("AllocateUninitializedClone", ObjectNative::AllocateUninitializedClone)
FCFuncElement("EnsureSufficientExecutionStack", ReflectionInvocation::EnsureSufficientExecutionStack)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public ConditionalWeakTable()
/// </param>
/// <returns>Returns "true" if key was found, "false" otherwise.</returns>
/// <remarks>
/// The key may get garbaged collected during the TryGetValue operation. If so, TryGetValue
/// The key may get garbage collected during the TryGetValue operation. If so, TryGetValue
/// may at its discretion, return "false" and set "value" to the default (as if the key was not present.)
/// </remarks>
public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value)
Expand Down Expand Up @@ -538,7 +538,23 @@ internal int FindEntry(TKey key, out object? value)
{
Debug.Assert(key != null); // Key already validated as non-null.

int hashCode = RuntimeHelpers.GetHashCode(key) & int.MaxValue;
int hashCode;

#if MONO
hashCode = RuntimeHelpers.GetHashCode(key);
#else
hashCode = RuntimeHelpers.TryGetHashCode(key);

if (hashCode == 0)
AustinWise marked this conversation as resolved.
Show resolved Hide resolved
{
// No hash code has been assigned to the key, so therefore it has not been added
// to any ConditionalWeakTable.
value = null;
return -1;
}
#endif

hashCode &= int.MaxValue;
int bucket = hashCode & (_buckets.Length - 1);
for (int entriesIndex = Volatile.Read(ref _buckets[bucket]); entriesIndex != -1; entriesIndex = _entries[entriesIndex].Next)
{
Expand Down
56 changes: 56 additions & 0 deletions src/tests/Interop/ObjectiveC/ObjectiveCMarshalAPI/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ namespace ObjectiveCMarshalAPI
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ObjectiveC;
using System.Threading;

using Xunit;

Expand Down Expand Up @@ -131,6 +132,39 @@ class DerivedWithFinalizer : Base
[ObjectiveCTrackedTypeAttribute]
class AttributedNoFinalizer { }

class HasNoHashCode : Base
{
}

class HasHashCode : Base
{
public HasHashCode()
{
// this will write a hash code into the object header.
RuntimeHelpers.GetHashCode(this);
}
}

class HasThinLockHeld : Base
{
public HasThinLockHeld()
{
// This will write lock information into the object header.
// An attempt to generate a hash code for this object will cause the lock to be
// upgrade to a thick lock.
Monitor.Enter(this);
}
}

class HasSyncBlock : Base
{
public HasSyncBlock()
{
RuntimeHelpers.GetHashCode(this);
Monitor.Enter(this);
}
}

static void InitializeObjectiveCMarshal()
{
delegate* unmanaged<void> beginEndCallback;
Expand All @@ -156,6 +190,12 @@ static void InitializeObjectiveCMarshal()
return h;
}

[MethodImpl(MethodImplOptions.NoInlining)]
static void AllocUntrackedObject<T>() where T : Base, new()
{
new T();
}

static void Validate_AllocAndFreeAnotherHandle<T>(GCHandle handle) where T : Base, new()
{
var obj = (T)handle.Target;
Expand Down Expand Up @@ -191,6 +231,14 @@ static unsafe void Validate_ReferenceTracking_Scenario()
ObjectiveCMarshal.CreateReferenceTrackingHandle(new AttributedNoFinalizer(), out _);
});

// Ensure objects who have no tagged memory allocated are handled when they enter the
// finalization queue. The NativeAOT implementation looks up objects in a hash table,
// so we exercise the various ways a hash code can be stored.
AllocUntrackedObject<HasNoHashCode>();
AllocUntrackedObject<HasHashCode>();
AllocUntrackedObject<HasThinLockHeld>();
AllocUntrackedObject<HasSyncBlock>();

// Provide the minimum number of times the reference callback should run.
// See IsRefCb() in NativeObjCMarshalTests.cpp for usage logic.
const uint callbackCount = 3;
Expand Down Expand Up @@ -285,6 +333,14 @@ class Scenario
// Do not call this method from Main as it depends on a previous test for set up.
static void _Validate_ExceptionPropagation()
{
// Not yet implemented for NativeAOT.
AustinWise marked this conversation as resolved.
Show resolved Hide resolved
// https://github.com/dotnet/runtime/issues/77472
if (TestLibrary.Utilities.IsNativeAot)
{
Console.WriteLine($"Skipping {nameof(_Validate_ExceptionPropagation)}, NYI");
return;
}

Console.WriteLine($"Running {nameof(_Validate_ExceptionPropagation)}");

var delThrowInt = new ThrowExceptionDelegate(DEL_ThrowIntException);
Expand Down