diff --git a/src/coreclr/clrfeatures.cmake b/src/coreclr/clrfeatures.cmake index c1f79cb5912fd8..10752d02bab93a 100644 --- a/src/coreclr/clrfeatures.cmake +++ b/src/coreclr/clrfeatures.cmake @@ -191,7 +191,3 @@ endif() # but that would be more expensive. set(FEATURE_CORECLR_FLUSH_INSTRUCTION_CACHE_TO_PROTECT_STUB_READS 1) -if (CLR_CMAKE_HOST_UNIX AND CLR_CMAKE_HOST_ARCH_AMD64) - # Allow 16 byte compare-exchange (cmpxchg16b) - add_compile_options($<${FEATURE_CORECLR_CACHED_INTERFACE_DISPATCH}:-mcx16>) -endif() diff --git a/src/coreclr/inc/jithelpers.h b/src/coreclr/inc/jithelpers.h index 6d7caaa5643983..937b5415978b1f 100644 --- a/src/coreclr/inc/jithelpers.h +++ b/src/coreclr/inc/jithelpers.h @@ -355,10 +355,20 @@ JITHELPER(CORINFO_HELP_GVMLOOKUP_FOR_SLOT, NULL, METHOD__NIL) #ifdef FEATURE_RESOLVE_HELPER_DISPATCH +#if defined(FEATURE_CACHED_INTERFACE_DISPATCH) + // Set to RhpInterfaceDispatch when cached interface dispatch is used + DYNAMICJITHELPER(CORINFO_HELP_INTERFACEDISPATCH_FOR_SLOT, JIT_InterfaceDispatchForSlot, METHOD__NIL) +#else JITHELPER(CORINFO_HELP_INTERFACEDISPATCH_FOR_SLOT, JIT_InterfaceDispatchForSlot, METHOD__NIL) +#endif JITHELPER(CORINFO_HELP_INTERFACELOOKUP_FOR_SLOT, JIT_InterfaceLookupForSlot, METHOD__NIL) +#else +#if defined(FEATURE_CACHED_INTERFACE_DISPATCH) && !defined(TARGET_WASM) + // Set to RhpInterfaceDispatch when cached interface dispatch is used + DYNAMICJITHELPER(CORINFO_HELP_INTERFACEDISPATCH_FOR_SLOT, NULL, METHOD__NIL) #else JITHELPER(CORINFO_HELP_INTERFACEDISPATCH_FOR_SLOT, NULL, METHOD__NIL) +#endif JITHELPER(CORINFO_HELP_INTERFACELOOKUP_FOR_SLOT, NULL, METHOD__NIL) #endif diff --git a/src/coreclr/inc/readytorun.h b/src/coreclr/inc/readytorun.h index 073ead514389e5..c750c943d363d4 100644 --- a/src/coreclr/inc/readytorun.h +++ b/src/coreclr/inc/readytorun.h @@ -20,7 +20,7 @@ // If you update this, ensure you run `git grep MINIMUM_READYTORUN_MAJOR_VERSION` // and handle pending work. #define READYTORUN_MAJOR_VERSION 34 -#define READYTORUN_MINOR_VERSION 0x0001 +#define READYTORUN_MINOR_VERSION 0x0002 #define MINIMUM_READYTORUN_MAJOR_VERSION 34 @@ -90,6 +90,9 @@ // only the return address, and the runtime preserves the callee-saved registers around the // funclets that it calls // R2R Version 34.1 adds AuxiliaryModuleMetadata sections +// R2R Version 34.2 adds READYTORUN_HELPER_InterfaceDispatch. Images compiled with cached interface dispatch support +// call it with the dispatch cell instead of calling through the cell, and lay out their dispatch +// cells as { MethodTable, Code, Token }. struct READYTORUN_CORE_HEADER { @@ -539,6 +542,9 @@ enum ReadyToRunHelper READYTORUN_HELPER_InitInstClass = 0x117, READYTORUN_HELPER_R2RToInterpreter = 0x118, READYTORUN_HELPER_WasmProfSamplepoint = 0x119, + + // Interface dispatch through a cached interface dispatch cell passed in the VSD parameter register + READYTORUN_HELPER_InterfaceDispatch = 0x11A, }; #include "readytoruninstructionset.h" diff --git a/src/coreclr/jit/lower.cpp b/src/coreclr/jit/lower.cpp index a4e1ebd7570a19..5c5784e8af24dd 100644 --- a/src/coreclr/jit/lower.cpp +++ b/src/coreclr/jit/lower.cpp @@ -7560,14 +7560,22 @@ GenTree* Lowering::LowerVirtualStubCall(GenTreeCall* call) } CORINFO_CONST_LOOKUP helperLookup = m_compiler->compGetHelperFtn(CORINFO_HELP_INTERFACEDISPATCH_FOR_SLOT); - assert(helperLookup.accessType == IAT_VALUE); - call->gtCallType = CT_USER_FUNC; - call->gtCallMethHnd = nullptr; - call->gtDirectCallAddress = helperLookup.addr; + call->gtCallType = CT_USER_FUNC; + call->gtCallMethHnd = Compiler::eeFindHelper(CORINFO_HELP_INTERFACEDISPATCH_FOR_SLOT); call->gtFlags &= ~GTF_CALL_VIRT_STUB; call->gtCallMoreFlags &= ~GTF_CALL_M_VIRTSTUB_REL_INDIRECT; - return nullptr; + if (helperLookup.accessType == IAT_VALUE) + { + call->gtDirectCallAddress = helperLookup.addr; + return nullptr; + } + + // The helper is called through an indirection cell (e.g. ReadyToRun). The cell register + // holds the dispatch cell, so the helper address is loaded from its cell explicitly. + assert(helperLookup.accessType == IAT_PVALUE); + GenTree* helperCellAddr = AddrGen(helperLookup.addr); + return m_compiler->gtNewIndir(TYP_I_IMPL, helperCellAddr, GTF_IND_NONFAULTING); } // An x86 JIT which uses full stub dispatch must generate only diff --git a/src/coreclr/minipal/minipal.h b/src/coreclr/minipal/minipal.h index 45d47439ab171c..3e0d26cbef1ae5 100644 --- a/src/coreclr/minipal/minipal.h +++ b/src/coreclr/minipal/minipal.h @@ -330,17 +330,4 @@ class VMToOSInterface static void AlignedFree(void* memblock); }; -#if defined(HOST_64BIT) && defined(FEATURE_CACHED_INTERFACE_DISPATCH) -EXTERN_C uint8_t _InterlockedCompareExchange128(int64_t volatile *, int64_t, int64_t, int64_t *); - -#if defined(HOST_WINDOWS) -#pragma intrinsic(_InterlockedCompareExchange128) -#endif - -FORCEINLINE uint8_t PalInterlockedCompareExchange128(_Inout_ int64_t volatile *pDst, int64_t iValueHigh, int64_t iValueLow, int64_t *pComparandAndResult) -{ - return _InterlockedCompareExchange128(pDst, iValueHigh, iValueLow, pComparandAndResult); -} -#endif // defined(HOST_64BIT) && defined(FEATURE_CACHED_INTERFACE_DISPATCH) - #endif // CORECLR_MINIPAL_H diff --git a/src/coreclr/nativeaot/BuildIntegration/Microsoft.NETCore.Native.Unix.targets b/src/coreclr/nativeaot/BuildIntegration/Microsoft.NETCore.Native.Unix.targets index 9eb5d14a7d9bb6..6dd255ebf2e172 100644 --- a/src/coreclr/nativeaot/BuildIntegration/Microsoft.NETCore.Native.Unix.targets +++ b/src/coreclr/nativeaot/BuildIntegration/Microsoft.NETCore.Native.Unix.targets @@ -250,8 +250,6 @@ The .NET Foundation licenses this file to you under the MIT license. - - diff --git a/src/coreclr/nativeaot/Runtime/inc/ModuleHeaders.h b/src/coreclr/nativeaot/Runtime/inc/ModuleHeaders.h index d09fff9a7db1c8..2d49bc2d14feb2 100644 --- a/src/coreclr/nativeaot/Runtime/inc/ModuleHeaders.h +++ b/src/coreclr/nativeaot/Runtime/inc/ModuleHeaders.h @@ -12,7 +12,7 @@ struct ReadyToRunHeaderConstants static const uint32_t Signature = 0x00525452; // 'RTR' static const uint32_t CurrentMajorVersion = 34; - static const uint32_t CurrentMinorVersion = 1; + static const uint32_t CurrentMinorVersion = 2; }; struct ReadyToRunHeader diff --git a/src/coreclr/nativeaot/Runtime/unix/PalInline.h b/src/coreclr/nativeaot/Runtime/unix/PalInline.h index 85a9de7f2ea592..c44e65a5fbe493 100644 --- a/src/coreclr/nativeaot/Runtime/unix/PalInline.h +++ b/src/coreclr/nativeaot/Runtime/unix/PalInline.h @@ -94,29 +94,6 @@ FORCEINLINE int64_t PalInterlockedCompareExchange64(_Inout_ int64_t volatile *pD return result; } -#if defined(HOST_64BIT) -FORCEINLINE uint8_t PalInterlockedCompareExchange128(_Inout_ int64_t volatile *pDst, int64_t iValueHigh, int64_t iValueLow, int64_t *pComparandAndResult) -{ - __int128_t iComparand = ((__int128_t)pComparandAndResult[1] << 64) + (uint64_t)pComparandAndResult[0]; - - // TODO-LOONGARCH64: the 128-bit CAS is supported starting from the 3A6000 CPU (ISA1.1). - // When running on older hardware that doesn't support native CAS-128, the system falls back - // to a mutex-based approach via libatomic, which is not suitable for runtime requirements. - // - // TODO-RISCV64: double-check if libatomic's emulated CAS-128 works as expected once AOT applications are - // functional on linux-riscv64: https://github.com/dotnet/runtime/issues/106223. - // CAS-128 is natively supported starting with the Zacas extension in Linux 6.8; however, hardware support - // for RVA23 profile is not available at the time of writing. - // - // See https://github.com/dotnet/runtime/issues/109276. - - __int128_t iResult = __sync_val_compare_and_swap((__int128_t volatile*)pDst, iComparand, ((__int128_t)iValueHigh << 64) + (uint64_t)iValueLow); - PalInterlockedOperationBarrier(); - pComparandAndResult[0] = (int64_t)iResult; pComparandAndResult[1] = (int64_t)(iResult >> 64); - return iComparand == iResult; -} -#endif // HOST_64BIT - #ifdef HOST_64BIT #define PalInterlockedExchangePointer(_pDst, _pValue) \ diff --git a/src/coreclr/nativeaot/Runtime/windows/PalInline.h b/src/coreclr/nativeaot/Runtime/windows/PalInline.h index 7bbc969b72c921..703d83d460450b 100644 --- a/src/coreclr/nativeaot/Runtime/windows/PalInline.h +++ b/src/coreclr/nativeaot/Runtime/windows/PalInline.h @@ -94,15 +94,6 @@ FORCEINLINE int64_t PalInterlockedIncrement64(_Inout_ int64_t volatile *pDst) } #endif // HOST_X86 -#if defined(HOST_AMD64) || defined(HOST_ARM64) -EXTERN_C uint8_t _InterlockedCompareExchange128(int64_t volatile *, int64_t, int64_t, int64_t *); -#pragma intrinsic(_InterlockedCompareExchange128) -FORCEINLINE uint8_t PalInterlockedCompareExchange128(_Inout_ int64_t volatile *pDst, int64_t iValueHigh, int64_t iValueLow, int64_t *pComparandAndResult) -{ - return _InterlockedCompareExchange128(pDst, iValueHigh, iValueLow, pComparandAndResult); -} -#endif // HOST_AMD64 - #ifdef HOST_64BIT EXTERN_C void * _InterlockedExchangePointer(void * volatile *, void *); diff --git a/src/coreclr/pal/inc/pal.h b/src/coreclr/pal/inc/pal.h index dbfb6303426164..b54693317e0e8d 100644 --- a/src/coreclr/pal/inc/pal.h +++ b/src/coreclr/pal/inc/pal.h @@ -2450,27 +2450,6 @@ Define_InterlockMethod( ((PVOID)(UINT_PTR)InterlockedCompareExchange((PLONG)(UINT_PTR)(Destination), (LONG)(UINT_PTR)(ExChange), (LONG)(UINT_PTR)(Comperand))) #endif -#if defined(HOST_64BIT) && defined(FEATURE_CACHED_INTERFACE_DISPATCH) -FORCEINLINE uint8_t _InterlockedCompareExchange128(int64_t volatile *pDst, int64_t iValueHigh, int64_t iValueLow, int64_t *pComparandAndResult) -{ - __int128_t iComparand = ((__int128_t)pComparandAndResult[1] << 64) + (uint64_t)pComparandAndResult[0]; - // TODO-LOONGARCH64: the 128-bit CAS is supported starting from the 3A6000 CPU (ISA1.1). - // When running on older hardware that doesn't support native CAS-128, the system falls back - // to a mutex-based approach via libatomic, which is not suitable for runtime requirements. - // - // TODO-RISCV64: double-check if libatomic's emulated CAS-128 works as expected once AOT applications are - // functional on linux-riscv64: https://github.com/dotnet/runtime/issues/106223. - // CAS-128 is natively supported starting with the Zacas extension in Linux 6.8; however, hardware support - // for RVA23 profile is not available at the time of writing. - // - // See https://github.com/dotnet/runtime/issues/109276. - __int128_t iResult = __sync_val_compare_and_swap((__int128_t volatile*)pDst, iComparand, ((__int128_t)iValueHigh << 64) + (uint64_t)iValueLow); - PAL_InterlockedOperationBarrier(); - pComparandAndResult[0] = (int64_t)iResult; pComparandAndResult[1] = (int64_t)(iResult >> 64); - return iComparand == iResult; -} -#endif - /*++ Function: MemoryBarrier diff --git a/src/coreclr/runtime/CachedInterfaceDispatch.cpp b/src/coreclr/runtime/CachedInterfaceDispatch.cpp index 2fffb69ab55204..29d52e93fcf97b 100644 --- a/src/coreclr/runtime/CachedInterfaceDispatch.cpp +++ b/src/coreclr/runtime/CachedInterfaceDispatch.cpp @@ -7,483 +7,366 @@ // // ============================================================================ #include "common.h" -#include #ifdef FEATURE_CACHED_INTERFACE_DISPATCH #include "CachedInterfaceDispatchPal.h" #include "CachedInterfaceDispatch.h" -// We always allocate cache sizes with a power of 2 number of entries. We have a maximum size we support, -// defined below. -#define CID_MAX_CACHE_SIZE_LOG2 6 -#define CID_MAX_CACHE_SIZE (1 << CID_MAX_CACHE_SIZE_LOG2) +// This is a port of the insertion side of GenericCache (see GenericCache.cs). The lookup side is +// implemented by the RhpInterfaceDispatch helpers, so the hashing and the probing sequence must not diverge. -//#define FEATURE_CID_STATS 1 +#ifdef _DEBUG +// use smaller numbers to hit resizing/preempting logic in debug +static const uint32_t DISPATCH_CACHE_INITIAL_SIZE = 8; +static const uint32_t DISPATCH_CACHE_MAX_SIZE = 512; +#else +static const uint32_t DISPATCH_CACHE_INITIAL_SIZE = 128; +static const uint32_t DISPATCH_CACHE_MAX_SIZE = 128 * 1024; +#endif -#ifdef FEATURE_CID_STATS +static const int VERSION_NUM_SIZE = 29; +static const uint32_t VERSION_NUM_MASK = (1 << VERSION_NUM_SIZE) - 1; +static const int BUCKET_SIZE = 8; +static const uint32_t SENTINEL_TABLE_SIZE = 2; -// Some counters used for debugging and profiling the algorithms. -extern "C" -{ - uint32_t CID_g_cLoadVirtFunc = 0; - uint32_t CID_g_cCacheMisses = 0; - uint32_t CID_g_cCacheSizeOverflows = 0; - uint32_t CID_g_cCacheOutOfMemory = 0; - uint32_t CID_g_cCacheReallocates = 0; - uint32_t CID_g_cCacheAllocates = 0; - uint32_t CID_g_cCacheDiscards = 0; - uint32_t CID_g_cInterfaceDispatches = 0; - uint32_t CID_g_cbMemoryAllocated = 0; - uint32_t CID_g_rgAllocatesBySize[CID_MAX_CACHE_SIZE_LOG2 + 1] = { 0 }; -}; - -#define CID_COUNTER_INC(_counter_name) CID_g_c##_counter_name++ +static DispatchCacheTable * volatile g_pDispatchCacheTable; +void * g_pDispatchCache = (void*)&g_pDispatchCacheTable; -#else +// A trivial 2-element table that never contains anything. It is installed when the cache is flushed. +static DispatchCacheTable * g_pDispatchCacheSentinelTable; +static uint32_t g_dispatchCacheLastFlushSize = DISPATCH_CACHE_INITIAL_SIZE; -#define CID_COUNTER_INC(_counter_name) +// Tables that were replaced and may still be read by the dispatch helpers. They are freed at the next GC, +// linked through m_unused. +static DispatchCacheTable * volatile g_pDiscardedDispatchCacheTables; -#endif // FEATURE_CID_STATS +static uint8_t & HashShift(DispatchCacheTable * pTable) +{ + return reinterpret_cast(&pTable->m_entries[0].m_version)[0]; +} -// Helper function for updating two adjacent pointers (which are aligned on a double pointer-sized boundary) -// atomically. -// -// This is used to update interface dispatch cache entries and also the stub/cache pair in -// interface dispatch indirection cells. The cases have slightly different semantics: cache entry updates -// (fFailOnNonNull == true) require that the existing values in the location are both NULL whereas indirection -// cell updates have no such restriction. In both cases we'll try the update once; on failure we'll return the -// new value of the second pointer and on success we'll the old value of the second pointer. -// -// This suits the semantics of both callers. For indirection cell updates the caller needs to know the address -// of the cache that can now be scheduled for release and the cache pointer is the second one in the pair. For -// cache entry updates the caller only needs a success/failure indication: on success the return value will be -// NULL and on failure non-NULL. -static void * UpdatePointerPairAtomically(void * pPairLocation, - void * pFirstPointer, - void * pSecondPointer, - bool fFailOnNonNull) +static uint8_t & VictimCounter(DispatchCacheTable * pTable) { -#if defined(HOST_64BIT) - // The same comments apply to the AMD64 version. The CompareExchange looks a little different since the - // API was refactored in terms of int64_t to avoid creating a 128-bit integer type. + return reinterpret_cast(&pTable->m_entries[0].m_version)[1]; +} - int64_t rgComparand[2] = { 0 , 0 }; - if (!fFailOnNonNull) - { - rgComparand[0] = *(int64_t volatile *)pPairLocation; - rgComparand[1] = *((int64_t volatile *)pPairLocation + 1); - } +static uint32_t TableMask(DispatchCacheTable * pTable) +{ + // element 0 is used for embedded aux data + return pTable->m_length - 2; +} - uint8_t bResult = PalInterlockedCompareExchange128((int64_t*)pPairLocation, (int64_t)pSecondPointer, (int64_t)pFirstPointer, rgComparand); - if (bResult == 1) - { - // Success, return old value of second pointer (rgComparand is updated by - // PalInterlockedCompareExchange128 with the old pointer values in this case). - return (void*)rgComparand[1]; - } +static DispatchCacheEntry * Element(DispatchCacheTable * pTable, uint32_t index) +{ + // element 0 is used for embedded aux data, skip it + return &pTable->m_entries[index + 1]; +} - // Failure, return the new second pointer value. - return pSecondPointer; +static uint32_t CacheElementCount(DispatchCacheTable * pTable) +{ + return pTable->m_length - 1; +} + +static bool IsSentinel(DispatchCacheTable * pTable) +{ + return pTable->m_length == SENTINEL_TABLE_SIZE + 1; +} + +static int32_t GetDispatchCacheHashCode(TADDR pCell, TADDR pInstanceType) +{ + // pointers will likely match and cancel out in the upper bits + // we will rotate context by 16 bit to keep more varying bits in the hash + const int bits = sizeof(TADDR) * 8; + TADDR value = ((pCell << 16) | (pCell >> (bits - 16))) ^ pInstanceType; +#ifdef TARGET_64BIT + return (int32_t)(uint32_t)value ^ (int32_t)(uint32_t)(value >> 32); #else - // Stuff the two pointers into a 64-bit value as the proposed new value for the CompareExchange64 below. - int64_t iNewValue = (int64_t)((uint64_t)(uintptr_t)pFirstPointer | ((uint64_t)(uintptr_t)pSecondPointer << 32)); + return (int32_t)value; +#endif +} - // Read the old value in the location. If fFailOnNonNull is set we just assume this was zero and we'll - // fail below if that's not the case. - int64_t iOldValue = fFailOnNonNull ? 0 : *(int64_t volatile *)pPairLocation; +static uint32_t HashToBucket(DispatchCacheTable * pTable, int32_t hash) +{ + uint8_t hashShift = HashShift(pTable); +#ifdef TARGET_64BIT + return (uint32_t)(((uint64_t)(int64_t)hash * 11400714819323198485ull) >> hashShift); +#else + return (uint32_t)(((uint32_t)hash * 2654435769u) >> hashShift); +#endif +} - int64_t iUpdatedOldValue = PalInterlockedCompareExchange64((int64_t*)pPairLocation, iNewValue, iOldValue); - if (iUpdatedOldValue == iOldValue) +static DispatchCacheTable * CreateDispatchCacheTable(uint32_t size) +{ + CONTRACTL { - // Successful update. Return the previous value of the second pointer. For cache entry updates - // (fFailOnNonNull == true) this is guaranteed to be NULL in this case and the result being being - // NULL in the success case is all the caller cares about. For indirection cell updates the second - // pointer represents the old cache and the caller needs this data so they can schedule the cache - // for deletion once it becomes safe to do so. - return (void*)(uint32_t)(iOldValue >> 32); + NOTHROW; + GC_NOTRIGGER; } + CONTRACTL_END; + + // size must be a power of two + _ASSERTE((size > 1) && ((size & (size - 1)) == 0)); + + size_t cbTable = offsetof(DispatchCacheTable, m_entries) + (size + 1) * sizeof(DispatchCacheEntry); + DispatchCacheTable * pTable = (DispatchCacheTable*)new (nothrow) BYTE[cbTable]; + if (pTable == NULL) + return NULL; + + memset(pTable, 0, cbTable); + pTable->m_length = size + 1; - // The update failed due to a racing update to the same location. Return the new value of the second - // pointer (either a new cache that lost the race or a non-NULL pointer in the cache entry update case). - return pSecondPointer; -#endif // HOST_64BIT + // Fibonacci hash reduces the value into desired range by shifting right by the number of leading zeroes in 'size-1' + uint8_t log2Size = 0; + while ((1u << log2Size) < size) + log2Size++; + HashShift(pTable) = (uint8_t)(sizeof(TADDR) * 8 - log2Size); + + return pTable; } -// Helper method for updating an interface dispatch cache entry atomically. See comments by the usage of -// this method for the details of why we need this. If a racing update is detected false is returned and the -// update abandoned. This is necessary since it's not safe to update a valid cache entry (one with a non-NULL -// m_pInstanceType field) outside of a GC. -static bool UpdateCacheEntryAtomically(InterfaceDispatchCacheEntry *pEntry, - MethodTable * pInstanceType, - void * pTargetCode) +static void DiscardDispatchCacheTable(DispatchCacheTable * pTable) { - static_assert(sizeof(InterfaceDispatchCacheEntry) == (sizeof(void*) * 2)); - static_assert(offsetof(InterfaceDispatchCacheEntry, m_pInstanceType) < offsetof(InterfaceDispatchCacheEntry, m_pTargetCode)); + LIMITED_METHOD_CONTRACT; + + if (IsSentinel(pTable)) + return; - return UpdatePointerPairAtomically(pEntry, pInstanceType, pTargetCode, true) == NULL; + DispatchCacheTable * pHead; + do + { + pHead = g_pDiscardedDispatchCacheTables; + pTable->m_unused = (TADDR)pHead; + } + while (InterlockedCompareExchangeT(&g_pDiscardedDispatchCacheTables, pTable, pHead) != pHead); } -// Helper method for updating an interface dispatch indirection cell's stub and cache pointer atomically. -// Returns the value of the cache pointer that is not referenced by the cell after this operation. This can be -// NULL on the initial cell update, the value of the old cache pointer or the value of the new cache pointer -// supplied (in the case where another thread raced with us for the update and won). In any case, if the -// returned pointer is non-NULL it represents a cache that should be scheduled for release. -static InterfaceDispatchCache * UpdateCellStubAndCache(InterfaceDispatchCell * pCell, - PCODE pStub, - uintptr_t newCacheValue) +static void ReplaceDispatchCacheTable(DispatchCacheTable * pOldTable, DispatchCacheTable * pNewTable) { - static_assert(offsetof(InterfaceDispatchCell, m_pStub) == 0); - static_assert(offsetof(InterfaceDispatchCell, m_pCache) == sizeof(void*)); + LIMITED_METHOD_CONTRACT; - uintptr_t oldCacheValue = (uintptr_t)UpdatePointerPairAtomically(pCell, (void*)pStub, (void*)newCacheValue, false); - - if (InterfaceDispatchCell::IsCache(oldCacheValue)) + if (InterlockedCompareExchangeT(&g_pDispatchCacheTable, pNewTable, pOldTable) == pOldTable) { - return (InterfaceDispatchCache *)oldCacheValue; + DiscardDispatchCacheTable(pOldTable); } - else + else if (pNewTable != g_pDispatchCacheSentinelTable) { - return nullptr; + // Another thread replaced the table first. The new table was never published. + delete[] (BYTE*)pNewTable; } } -// -// Cache allocation logic. -// -// We use the existing AllocHeap mechanism as our base allocator for cache blocks. This is because it can -// provide the required 16-byte alignment with no padding or heap header costs. The downside is that there is -// no deallocation support (which would be hard to implement without implementing a cache block compaction -// scheme, which is certainly possible but not necessarily needed at this point). -// -// Instead, much like the original VSD algorithm, we keep discarded cache blocks and use them to satisfy new -// allocation requests before falling back on AllocHeap. -// -// We can't re-use discarded cache blocks immediately since there may be code that is still using them. -// Instead we link them into a global list and then at the next GC (when no code can hold a reference to these -// any more) we can place them on one of several free lists based on their size. -// - -#ifndef INTERFACE_DISPATCH_CACHE_HAS_CELL_BACKPOINTER +static bool MaybeReplaceCacheWithLarger(DispatchCacheTable * pOldTable, uint32_t size) +{ + LIMITED_METHOD_CONTRACT; -// Head of the list of discarded cache blocks that can't be re-used just yet. -InterfaceDispatchCache * g_pDiscardedCacheList; // m_pCell is not used and we can link the discarded blocks themselves + DispatchCacheTable * pNewTable = CreateDispatchCacheTable(size); + if (pNewTable == NULL) + return false; -#else // INTERFACE_DISPATCH_CACHE_HAS_CELL_BACKPOINTER + ReplaceDispatchCacheTable(pOldTable, pNewTable); + return true; +} -struct DiscardedCacheBlock -{ - DiscardedCacheBlock * m_pNext; // for x86 and ARM, we are short of registers, thus need the m_pCell back pointers - InterfaceDispatchCache * m_pCache; // and thus need this auxiliary list -}; - -// Head of the list of discarded cache blocks that can't be re-used just yet. -static DiscardedCacheBlock * g_pDiscardedCacheList = NULL; - -// Free list of DiscardedCacheBlock items -static DiscardedCacheBlock * g_pDiscardedCacheFree = NULL; - -#endif // INTERFACE_DISPATCH_CACHE_HAS_CELL_BACKPOINTER - -// Free lists for each cache size up to the maximum. We allocate from these in preference to new memory. -static InterfaceDispatchCache * g_rgFreeLists[CID_MAX_CACHE_SIZE_LOG2 + 1]; - -// Lock protecting both g_pDiscardedCacheList and g_rgFreeLists. We don't use the OS SLIST support here since -// it imposes too much space overhead on list entries on 64-bit (each is actually 16 bytes). -static CrstStatic g_sListLock; - -// Each cache size has an associated stub used to perform lookup over that cache. -extern "C" void RhpInterfaceDispatch1(); -extern "C" void RhpInterfaceDispatch2(); -extern "C" void RhpInterfaceDispatch4(); -extern "C" void RhpInterfaceDispatch8(); -extern "C" void RhpInterfaceDispatch16(); -extern "C" void RhpInterfaceDispatch32(); -extern "C" void RhpInterfaceDispatch64(); - -extern "C" void RhpVTableOffsetDispatch(); - -typedef void (*InterfaceDispatchStub)(); - -static const PCODE g_rgDispatchStubs[CID_MAX_CACHE_SIZE_LOG2 + 1] = { - (PCODE)&RhpInterfaceDispatch1, - (PCODE)&RhpInterfaceDispatch2, - (PCODE)&RhpInterfaceDispatch4, - (PCODE)&RhpInterfaceDispatch8, - (PCODE)&RhpInterfaceDispatch16, - (PCODE)&RhpInterfaceDispatch32, - (PCODE)&RhpInterfaceDispatch64, -}; - -// Map a cache size into a linear index. -static uint32_t CacheSizeToIndex(uint32_t cCacheEntries) +static void FlushCurrentCache(DispatchCacheTable * pTable) { - switch (cCacheEntries) - { - case 1: - return 0; - case 2: - return 1; - case 4: - return 2; - case 8: - return 3; - case 16: - return 4; - case 32: - return 5; - case 64: - return 6; - default: - UNREACHABLE(); - } + LIMITED_METHOD_CONTRACT; + + uint32_t lastSize = CacheElementCount(pTable); + if (lastSize < DISPATCH_CACHE_INITIAL_SIZE) + lastSize = DISPATCH_CACHE_INITIAL_SIZE; + + // store the last size to use when creating a new table + // it is just a hint, not needed for correctness, so no synchronization + // with the writing of the table + g_dispatchCacheLastFlushSize = lastSize; + // flushing is just replacing the table with a sentinel. + ReplaceDispatchCacheTable(pTable, g_pDispatchCacheSentinelTable); } -// Allocates and initializes new cache of the given size. If given a previous version of the cache (guaranteed -// to be smaller) it will also pre-populate the new cache with the contents of the old. Additionally the -// address of the interface dispatch stub associated with this size of cache is returned. -static uintptr_t AllocateCache(uint32_t cCacheEntries, InterfaceDispatchCache * pExistingCache, const DispatchCellInfo *pNewCellInfo, PCODE * ppStub) +static bool TryGrow(DispatchCacheTable * pTable) { - if (pNewCellInfo->CellType == DispatchCellType::VTableOffset) + LIMITED_METHOD_CONTRACT; + + uint32_t newSize = CacheElementCount(pTable) * 2; + if (newSize <= DISPATCH_CACHE_MAX_SIZE) { - *ppStub = (PCODE)&RhpVTableOffsetDispatch; - ASSERT(!InterfaceDispatchCell::IsCache(pNewCellInfo->GetVTableOffset())); - return pNewCellInfo->GetVTableOffset(); + return MaybeReplaceCacheWithLarger(pTable, newSize); } - ASSERT((cCacheEntries >= 1) && (cCacheEntries <= CID_MAX_CACHE_SIZE)); - ASSERT((pExistingCache == NULL) || (pExistingCache->m_cEntries < cCacheEntries)); - - InterfaceDispatchCache * pCache = NULL; + return false; +} - // Transform cache size back into a linear index. - uint32_t idxCacheSize = CacheSizeToIndex(cCacheEntries); +static bool TryClaimEntry(DispatchCacheTable * pTable, DispatchCacheEntry * pEntry, uint32_t distance, TADDR pCell, TADDR pInstanceType, PCODE pTargetCode, bool fOnlyIfCloser) +{ + LIMITED_METHOD_CONTRACT; - // Attempt to allocate the head of the free list of the correct cache size. - if (g_rgFreeLists[idxCacheSize] != NULL) - { - CrstHolder lh(&g_sListLock); + uint32_t version = VolatileLoadWithoutBarrier(&pEntry->m_version); - pCache = g_rgFreeLists[idxCacheSize]; - if (pCache != NULL) - { - g_rgFreeLists[idxCacheSize] = pCache->m_pNextFree; - CID_COUNTER_INC(CacheReallocates); - } - } + // mask the lower version bit to make it even. + // This way we will detect both if version is changing (odd) or has changed (even, but different). + version &= ~1u; - if (pCache == NULL) + if ((version & VERSION_NUM_MASK) >= (VERSION_NUM_MASK - 2)) { - // No luck with the free list, allocate the cache from via the AllocHeap. - pCache = (InterfaceDispatchCache*)InterfaceDispatch_AllocDoublePointerAligned(sizeof(InterfaceDispatchCache) + - (sizeof(InterfaceDispatchCacheEntry) * cCacheEntries)); - if (pCache == NULL) - return (uintptr_t)NULL; - - CID_COUNTER_INC(CacheAllocates); -#ifdef FEATURE_CID_STATS - CID_g_cbMemoryAllocated += sizeof(InterfaceDispatchCacheEntry) * cCacheEntries; - CID_g_rgAllocatesBySize[idxCacheSize]++; -#endif + // If exactly VERSION_NUM_MASK updates happens between here and publishing, we may not recognize a race. + // It is extremely unlikely, but to not worry about the possibility, lets not allow version to go this high and just get a new cache. + // This will not happen often. + FlushCurrentCache(pTable); + return true; } - // We have a cache block, now initialize it. - pCache->m_pNextFree = NULL; - pCache->m_cEntries = cCacheEntries; - pCache->m_cacheHeader.Initialize(pNewCellInfo); + if (fOnlyIfCloser && !(version == 0 || (version >> VERSION_NUM_SIZE) > distance)) + return false; - // Copy over entries from previous version of the cache (if any) and zero the rest. - if (pExistingCache) - { - memcpy(pCache->m_rgEntries, - pExistingCache->m_rgEntries, - sizeof(InterfaceDispatchCacheEntry) * pExistingCache->m_cEntries); - memset(&pCache->m_rgEntries[pExistingCache->m_cEntries], - 0, - (cCacheEntries - pExistingCache->m_cEntries) * sizeof(InterfaceDispatchCacheEntry)); - } - else + uint32_t newVersion = (distance << VERSION_NUM_SIZE) + (version & VERSION_NUM_MASK) + 1; + uint32_t versionOrig = (uint32_t)InterlockedCompareExchange((LONG*)&pEntry->m_version, (LONG)newVersion, (LONG)version); + if (versionOrig != version) { - memset(pCache->m_rgEntries, - 0, - cCacheEntries * sizeof(InterfaceDispatchCacheEntry)); + // someone snatched the entry. + return false; } - // Pass back the stub the corresponds to this cache size. - *ppStub = g_rgDispatchStubs[idxCacheSize]; + pEntry->m_pCell = pCell; + pEntry->m_pInstanceType = pInstanceType; + pEntry->m_pTargetCode = pTargetCode; - return (uintptr_t)pCache; + // entry is in inconsistent state and cannot be read or written to until we + // update the version, which is the last thing we do here + VolatileStore(&pEntry->m_version, newVersion + 1); + return true; } -// Discards a cache by adding it to a list of caches that may still be in use but will be made available for -// re-allocation at the next GC. -void InterfaceDispatch_DiscardCache(InterfaceDispatchCache * pCache) +static void DispatchCacheTrySet(TADDR pCell, TADDR pInstanceType, PCODE pTargetCode) { - CID_COUNTER_INC(CacheDiscards); - - CrstHolder lh(&g_sListLock); - -#ifndef INTERFACE_DISPATCH_CACHE_HAS_CELL_BACKPOINTER - - // we can thread the list through the blocks directly - pCache->m_pNextFree = g_pDiscardedCacheList; - g_pDiscardedCacheList = pCache; - -#else // INTERFACE_DISPATCH_CACHE_HAS_CELL_BACKPOINTER - - // on other architectures, we cannot overwrite pCache->m_pNextFree yet - // because it shares storage with m_pCell which may still be used as a back - // pointer to the dispatch cell. - - // instead, allocate an auxiliary node (with its own auxiliary free list) - DiscardedCacheBlock * pDiscardedCacheBlock = g_pDiscardedCacheFree; - if (pDiscardedCacheBlock != NULL) - g_pDiscardedCacheFree = pDiscardedCacheBlock->m_pNext; - else - pDiscardedCacheBlock = (DiscardedCacheBlock *)InterfaceDispatch_AllocPointerAligned(sizeof(DiscardedCacheBlock)); - - if (pDiscardedCacheBlock != NULL) // if we did NOT get the memory, we leak the discarded block + CONTRACTL { - pDiscardedCacheBlock->m_pNext = g_pDiscardedCacheList; - pDiscardedCacheBlock->m_pCache = pCache; - - g_pDiscardedCacheList = pDiscardedCacheBlock; + NOTHROW; + GC_NOTRIGGER; + MODE_COOPERATIVE; } -#endif // INTERFACE_DISPATCH_CACHE_HAS_CELL_BACKPOINTER -} + CONTRACTL_END; -// Called during a GC to empty the list of discarded caches (which we can now guarantee aren't being accessed) -// and sort the results into the free lists we maintain for each cache size. -void InterfaceDispatch_ReclaimUnusedInterfaceDispatchCaches() -{ - // No need for any locks, we're not racing with any other threads any more. - - // Walk the list of discarded caches. -#ifndef INTERFACE_DISPATCH_CACHE_HAS_CELL_BACKPOINTER + int32_t hash = GetDispatchCacheHashCode(pCell, pInstanceType); + uint32_t bucket; + DispatchCacheTable * pTable; - // this is threaded directly through the cache blocks - InterfaceDispatchCache * pCache = g_pDiscardedCacheList; - while (pCache) + do { - InterfaceDispatchCache * pNextCache = pCache->m_pNextFree; - - // Transform cache size back into a linear index. - uint32_t idxCacheSize = CacheSizeToIndex(pCache->m_cEntries); + pTable = g_pDispatchCacheTable; + if (IsSentinel(pTable)) + { + // sentinel table is used to indicate that + // we did not allocate a real table yet or have flushed it. + // try replacing the table, but do not insert anything. + MaybeReplaceCacheWithLarger(pTable, g_dispatchCacheLastFlushSize); + return; + } - // Insert the cache onto the head of the correct free list. - pCache->m_pNextFree = g_rgFreeLists[idxCacheSize]; - g_rgFreeLists[idxCacheSize] = pCache; + bucket = HashToBucket(pTable, hash); + uint32_t index = bucket; - pCache = pNextCache; - } + for (uint32_t i = 0; i < BUCKET_SIZE;) + { + // claim the entry if unused or is more distant than us from its origin. + DispatchCacheEntry * pEntry = Element(pTable, index & TableMask(pTable)); + if (TryClaimEntry(pTable, pEntry, i, pCell, pInstanceType, pTargetCode, true /* fOnlyIfCloser */)) + return; -#else // INTERFACE_DISPATCH_CACHE_HAS_CELL_BACKPOINTER + if (pEntry->m_pCell == pCell && pEntry->m_pInstanceType == pInstanceType) + { + // looks like we already have an entry for this. + // duplicate entries are harmless, but a bit of a waste. + return; + } - // on other architectures, we use an auxiliary list instead - DiscardedCacheBlock * pDiscardedCacheBlock = g_pDiscardedCacheList; - while (pDiscardedCacheBlock) - { - InterfaceDispatchCache * pCache = pDiscardedCacheBlock->m_pCache; + // quadratic reprobe + i++; + index += i; + } - // Transform cache size back into a linear index. - uint32_t idxCacheSize = CacheSizeToIndex(pCache->m_cEntries); + // bucket is full. + } while (TryGrow(pTable)); - // Insert the cache onto the head of the correct free list. - pCache->m_pNextFree = g_rgFreeLists[idxCacheSize]; - g_rgFreeLists[idxCacheSize] = pCache; + // reread the table after TryGrow. + pTable = g_pDispatchCacheTable; - // Insert the container to its own free list - DiscardedCacheBlock * pNextDiscardedCacheBlock = pDiscardedCacheBlock->m_pNext; - pDiscardedCacheBlock->m_pNext = g_pDiscardedCacheFree; - g_pDiscardedCacheFree = pDiscardedCacheBlock; - pDiscardedCacheBlock = pNextDiscardedCacheBlock; + if (IsSentinel(pTable)) + { + // do not insert into a sentinel. + return; } -#endif // INTERFACE_DISPATCH_CACHE_HAS_CELL_BACKPOINTER + // pick a victim somewhat randomly within a bucket + // NB: ++ is not interlocked. We are ok if we lose counts here. It is just a number that changes. + uint32_t victimDistance = (uint32_t)(VictimCounter(pTable)++ & (BUCKET_SIZE - 1)); + // position the victim in a quadratic reprobe bucket + uint32_t victim = (victimDistance * victimDistance + victimDistance) / 2; - // We processed all the discarded entries, so we can simply NULL the list head. - g_pDiscardedCacheList = NULL; + TryClaimEntry(pTable, Element(pTable, (bucket + victim) & TableMask(pTable)), victimDistance, pCell, pInstanceType, pTargetCode, false /* fOnlyIfCloser */); } -// One time initialization of interface dispatch. bool InterfaceDispatch_Initialize() { - if (!InterfaceDispatch_InitializePal()) + STANDARD_VM_CONTRACT; + + g_pDispatchCacheSentinelTable = CreateDispatchCacheTable(SENTINEL_TABLE_SIZE); + if (g_pDispatchCacheSentinelTable == NULL) return false; - g_sListLock.Init(CrstInterfaceDispatchGlobalLists, CRST_DEFAULT); + DispatchCacheTable * pTable = NULL; +#ifndef _DEBUG + // Initialize to the sentinel in DEBUG as if just flushed, to ensure the sentinel can be handled in TrySet. + pTable = CreateDispatchCacheTable(DISPATCH_CACHE_INITIAL_SIZE); +#endif + g_pDispatchCacheTable = (pTable != NULL) ? pTable : g_pDispatchCacheSentinelTable; return true; } -PCODE InterfaceDispatch_UpdateDispatchCellCache(InterfaceDispatchCell * pCell, PCODE pTargetCode, MethodTable* pInstanceType, DispatchCellInfo *pNewCellInfo) +void InterfaceDispatch_UpdateDispatchCellCache(InterfaceDispatchCell * pCell, PCODE pTargetCode, MethodTable * pInstanceType, bool fCacheInCell, bool fCacheInTable) { - // Attempt to update the cache with this new mapping (if we have any cache at all, the initial state - // is none). - InterfaceDispatchCache * pCache = (InterfaceDispatchCache*)pCell->GetCache(); - uint32_t cOldCacheEntries = 0; - if (pCache != NULL) + CONTRACTL { - InterfaceDispatchCacheEntry * pCacheEntry = pCache->m_rgEntries; - for (uint32_t i = 0; i < pCache->m_cEntries; i++, pCacheEntry++) - { - if (pCacheEntry->m_pInstanceType == NULL) - { - if (UpdateCacheEntryAtomically(pCacheEntry, pInstanceType, dac_cast(pTargetCode))) - return (PCODE)pTargetCode; - } - } - - cOldCacheEntries = pCache->m_cEntries; + NOTHROW; + GC_NOTRIGGER; + MODE_COOPERATIVE; } + CONTRACTL_END; - // Failed to update an existing cache, we need to allocate a new cache. The old one, if any, might - // still be in use so we can't simply reclaim it. Instead we keep it around until the next GC at which - // point we know no code is holding a reference to it. Particular cache sizes are associated with a - // (globally shared) stub which implicitly knows the size of the cache. - - if (cOldCacheEntries == CID_MAX_CACHE_SIZE) + // If the dispatch cell doesn't cache anything yet, cache in the dispatch cell + if (fCacheInCell && InterlockedCompareExchangeT(&pCell->m_pCode, pTargetCode, (PCODE)NULL) == (PCODE)NULL) { - // We already reached the maximum cache size we wish to allocate. For now don't attempt to cache - // the mapping we just did: there's no safe way to update the existing cache right now if it - // doesn't have an empty entries. There are schemes that would let us do this at the next GC point - // but it's not clear whether we should do this or re-tune the cache max size, we need to measure - // this. - CID_COUNTER_INC(CacheSizeOverflows); - return (PCODE)pTargetCode; + // Use release semantics so the reader's acquire-load of m_pMethodTable + // guarantees the m_pCode store is visible. + pCell->m_pMethodTable = (TADDR)pInstanceType; } - - uint32_t cNewCacheEntries = cOldCacheEntries ? cOldCacheEntries * 2 : 1; - PCODE pStub; - uintptr_t newCacheValue = AllocateCache(cNewCacheEntries, pCache, pNewCellInfo, &pStub); - if (newCacheValue == 0) + else if (fCacheInTable) { - CID_COUNTER_INC(CacheOutOfMemory); - return (PCODE)pTargetCode; + // Otherwise cache in the hashtable + DispatchCacheTrySet((TADDR)pCell, (TADDR)pInstanceType, pTargetCode); } +} - if (InterfaceDispatchCell::IsCache(newCacheValue)) - { - pCache = (InterfaceDispatchCache*)newCacheValue; -#ifdef INTERFACE_DISPATCH_CACHE_HAS_CELL_BACKPOINTER - // Set back pointer to interface dispatch cell for x86 and ARM, on other - // architectures we have enough registers to make this trick unnecessary - pCache->m_pCell = pCell; -#endif // INTERFACE_DISPATCH_CACHE_HAS_CELL_BACKPOINTER - - // Add entry to the first unused slot. - InterfaceDispatchCacheEntry * pCacheEntry = &pCache->m_rgEntries[cOldCacheEntries]; - pCacheEntry->m_pInstanceType = pInstanceType; - pCacheEntry->m_pTargetCode = pTargetCode; - } +void InterfaceDispatch_FlushDispatchCache() +{ + LIMITED_METHOD_CONTRACT; - // Publish the new cache by atomically updating both the cache and stub pointers in the indirection - // cell. This returns us a cache to discard which may be NULL (no previous cache), the previous cache - // value or the cache we just allocated (another thread performed an update first). - InterfaceDispatchCache * pDiscardedCache = UpdateCellStubAndCache(pCell, pStub, newCacheValue); - if (pDiscardedCache) - InterfaceDispatch_DiscardCache(pDiscardedCache); + FlushCurrentCache(g_pDispatchCacheTable); +} + +void InterfaceDispatch_ReclaimUnusedInterfaceDispatchCaches() +{ + LIMITED_METHOD_CONTRACT; - return (PCODE)pTargetCode; + // The dispatch helpers don't contain GC safe points, so no thread is reading a table that was replaced + // before this GC started. + DispatchCacheTable * pTable = InterlockedExchangeT(&g_pDiscardedDispatchCacheTables, (DispatchCacheTable*)NULL); + while (pTable != NULL) + { + DispatchCacheTable * pNext = (DispatchCacheTable*)pTable->m_unused; + delete[] (BYTE*)pTable; + pTable = pNext; + } } #endif // FEATURE_CACHED_INTERFACE_DISPATCH diff --git a/src/coreclr/runtime/CachedInterfaceDispatch.h b/src/coreclr/runtime/CachedInterfaceDispatch.h index 690b1ebaf86be2..016e109d6ba971 100644 --- a/src/coreclr/runtime/CachedInterfaceDispatch.h +++ b/src/coreclr/runtime/CachedInterfaceDispatch.h @@ -12,64 +12,51 @@ #ifdef FEATURE_CACHED_INTERFACE_DISPATCH -// Interface dispatch caches contain an array of these entries. An instance of a cache is paired with a stub -// that implicitly knows how many entries are contained. These entries must be aligned to twice the alignment -// of a pointer due to the synchonization mechanism used to update them at runtime. -struct InterfaceDispatchCacheEntry +struct InterfaceDispatchCell; + +// The global dispatch cache is a hashtable keyed by (dispatch cell, MethodTable) that holds the dispatch +// targets that don't fit in the monomorphic cache of the dispatch cell. Its layout matches +// GenericCache in CoreLib, which is what the NativeAOT dispatch helpers probe. +struct DispatchCacheEntry { - MethodTable * m_pInstanceType; // Potential type of the object instance being dispatched on - PCODE m_pTargetCode; // Method to dispatch to if the actual instance type matches the above + // Seqlock version. In entry 0 of a table, the low two bytes hold the hash shift and the victim counter. + uint32_t m_version; + TADDR m_pCell; + TADDR m_pInstanceType; + PCODE m_pTargetCode; }; -// The interface dispatch cache itself. As well as the entries we include the cache size (since logic such as -// cache miss processing needs to determine this value in a synchronized manner, so it can't be contained in -// the owning interface dispatch indirection cell) and a list entry used to link the caches in one of a couple -// of lists related to cache reclamation. - #pragma warning(push) #pragma warning(disable:4200) // nonstandard extension used: zero-sized array in struct/union -struct InterfaceDispatchCell; -struct InterfaceDispatchCache +struct DispatchCacheTable { - InterfaceDispatchCacheHeader m_cacheHeader; - union - { - InterfaceDispatchCache * m_pNextFree; // next in free list -#ifdef INTERFACE_DISPATCH_CACHE_HAS_CELL_BACKPOINTER - // On ARM and x86 the slow path in the stubs needs to reload the cell pointer from the cache due to the lack - // of available (volatile non-argument) registers. - InterfaceDispatchCell * m_pCell; // pointer back to interface dispatch cell + // Laid out like a managed Entry[]: the dispatch helpers read the length at the same offset and + // index the entries from the same base. + TADDR m_unused; + uint32_t m_length; +#ifdef TARGET_64BIT + uint32_t m_padding; #endif - }; - uint32_t m_cEntries; - InterfaceDispatchCacheEntry m_rgEntries[]; + DispatchCacheEntry m_entries[]; }; #pragma warning(pop) +// Points at the variable that holds the current DispatchCacheTable. +extern "C" void * g_pDispatchCache; + bool InterfaceDispatch_Initialize(); -PCODE InterfaceDispatch_UpdateDispatchCellCache(InterfaceDispatchCell * pCell, PCODE pTargetCode, MethodTable* pInstanceType, DispatchCellInfo *pNewCellInfo); -void InterfaceDispatch_ReclaimUnusedInterfaceDispatchCaches(); -void InterfaceDispatch_DiscardCache(InterfaceDispatchCache * pCache); -inline void InterfaceDispatch_DiscardCacheHeader(InterfaceDispatchCacheHeader * pCache) -{ - return InterfaceDispatch_DiscardCache((InterfaceDispatchCache*)pCache); -} -inline PCODE InterfaceDispatch_SearchDispatchCellCache(InterfaceDispatchCell * pCell, MethodTable* pInstanceType) -{ - // This function must be implemented in native code so that we do not take a GC while walking the cache - InterfaceDispatchCache * pCache = (InterfaceDispatchCache*)pCell->GetCache(); - if (pCache != NULL) - { - InterfaceDispatchCacheEntry * pCacheEntry = pCache->m_rgEntries; - for (uint32_t i = 0; i < pCache->m_cEntries; i++, pCacheEntry++) - if (pCacheEntry->m_pInstanceType == pInstanceType) - return pCacheEntry->m_pTargetCode; - } +// Caches pTargetCode as the target of dispatching through pCell on an object of type pInstanceType. +// The monomorphic cache in the cell is used if it is still empty and fCacheInCell is set, the global +// dispatch cache otherwise, if fCacheInTable is set. +void InterfaceDispatch_UpdateDispatchCellCache(InterfaceDispatchCell * pCell, PCODE pTargetCode, MethodTable * pInstanceType, bool fCacheInCell, bool fCacheInTable); - return (PCODE)nullptr; -} +// Drops all entries of the global dispatch cache. Used when dispatch cells are reused for another call site. +void InterfaceDispatch_FlushDispatchCache(); + +// Called during a GC to free the dispatch cache tables that were replaced since the previous GC. +void InterfaceDispatch_ReclaimUnusedInterfaceDispatchCaches(); #endif // FEATURE_CACHED_INTERFACE_DISPATCH -#endif // __CACHEDINTERFACEDISPATCH_H__ \ No newline at end of file +#endif // __CACHEDINTERFACEDISPATCH_H__ diff --git a/src/coreclr/runtime/amd64/StubDispatch.S b/src/coreclr/runtime/amd64/StubDispatch.S index 5f231e97c698eb..0d1dbc64963778 100644 --- a/src/coreclr/runtime/amd64/StubDispatch.S +++ b/src/coreclr/runtime/amd64/StubDispatch.S @@ -6,104 +6,114 @@ #ifdef FEATURE_CACHED_INTERFACE_DISPATCH -#if defined(__APPLE__) - // Currently the build is failing without this due to an issue if the first method in the assembly file has an alternate entry at the start of the file. - // Fix, but adding an empty, unused method - LEAF_ENTRY RhpStubDispatchDoNotFailToBuild, _TEXT - ret - LEAF_END RhpStubDispatchDoNotFailToBuild, _TEXT -#endif - - -// trick to avoid PLT relocation at runtime which corrupts registers -#define REL_C_FUNC(name) C_FUNC(name)@gotpcrel - - -// Macro that generates a stub consuming a cache with the given number of entries. -.macro DEFINE_INTERFACE_DISPATCH_STUB entries - -LEAF_ENTRY RhpInterfaceDispatch\entries, _TEXT - - // r11 currently contains the indirection cell address. - // load r10 to point to the cache block. - mov r10, [r11 + OFFSETOF__InterfaceDispatchCell__m_pCache] - - // Validate r10 is a cache pointer matching the expected cache size. - // This compensates for a race where the stub was updated to expect a larger cache - // but we loaded a stale (smaller or non-cache) m_pCache value. - // On detection, re-dispatch through the indirection cell to retry with the current - // stub and cache pair. - test r10, IDC_CACHE_POINTER_MASK - jnz LOCAL_LABEL(RaceRetry_\entries) - cmp dword ptr [r10 + OFFSETOF__InterfaceDispatchCache__m_cEntries], \entries - jne LOCAL_LABEL(RaceRetry_\entries) +// On Input: +// rdi contains the this pointer +// r11 contains the address of the interface dispatch cell +LEAF_ENTRY RhpInterfaceDispatch, _TEXT // Load the MethodTable from the object instance in rdi. -#ifdef TARGET_APPLE -// Apple's linker has issues which break unwind info if -// an ALTERNATE_ENTRY is present in the middle of a function see https://github.com/dotnet/runtime/pull/114982#discussion_r2083272768 -.cfi_endproc -#endif - ALTERNATE_ENTRY RhpInterfaceDispatchAVLocation\entries -#ifdef TARGET_APPLE -.cfi_startproc -#endif - mov rax, [rdi] - - CurrentOffset = OFFSETOF__InterfaceDispatchCache__m_rgEntries - - // For each entry in the cache, see if its MethodTable type matches the MethodTable in rax. - // If so, call the second cache entry. If not, skip the InterfaceDispatchCacheEntry. - .rept \entries - cmp rax, [r10 + CurrentOffset] - jne 0f - jmp [r10 + CurrentOffset + 8] - 0: - CurrentOffset = CurrentOffset + 16 - .endr - - // r11 still contains the indirection cell address. - - jmp C_FUNC(RhpInterfaceDispatchSlow) - -LOCAL_LABEL(RaceRetry_\entries): - jmp [r11] - -LEAF_END RhpInterfaceDispatch\entries, _TEXT - -.endm // DEFINE_INTERFACE_DISPATCH_STUB - - - -// Define all the stub routines we currently need. -// -// The mrt100dbi requires these be exported to identify mrt100 code that dispatches back into managed. -// If you change or add any new dispatch stubs, please also change slr.def and dbi\process.cpp CordbProcess::GetExportStepInfo -// -// If you change or add any new dispatch stubs, exception handling might need to be aware because it refers to the -// *AVLocation symbols defined by the dispatch stubs to be able to unwind and blame user code if a NullRef happens -// during the interface dispatch. -// -DEFINE_INTERFACE_DISPATCH_STUB 1 -DEFINE_INTERFACE_DISPATCH_STUB 2 -DEFINE_INTERFACE_DISPATCH_STUB 4 -DEFINE_INTERFACE_DISPATCH_STUB 8 -DEFINE_INTERFACE_DISPATCH_STUB 16 -DEFINE_INTERFACE_DISPATCH_STUB 32 -DEFINE_INTERFACE_DISPATCH_STUB 64 - -// Initial dispatch on an interface when we don't have a cache yet. -LEAF_ENTRY RhpInitialInterfaceDispatch, _TEXT // Trigger an AV if we're dispatching on a null this. // The exception handling infrastructure is aware of the fact that this is the first - // instruction of RhpInitialInterfaceDispatch and uses it to translate an AV here + // instruction of RhpInterfaceDispatch and uses it to translate an AV here // to a NullReferenceException at the callsite. - cmp byte ptr [rdi], 0 + mov r10, [rdi] - // Just tail call to the cache miss helper. - jmp C_FUNC(RhpInterfaceDispatchSlow) + // r11 currently contains the indirection cell address. + cmp qword ptr [r11], r10 // is this the monomorphic MethodTable? + jne LOCAL_LABEL(Hashtable) + + mov rax, [r11 + 8] // load the cached monomorphic resolved code address into rax + jmp rax + +LOCAL_LABEL(Hashtable): + + // r10 = MethodTable, r11 = indirection cell address + // Look up the target in the dispatch cache hashtable (see CachedInterfaceDispatch.cpp). + // Spill argument registers to the red zone below rsp + // so we don't modify rsp (this is a LEAF_ENTRY with no unwind info). + mov [rsp - 8], rcx + mov [rsp - 16], rdx + mov [rsp - 24], r8 + mov [rsp - 32], r9 + + // Load the current table. + PREPARE_EXTERNAL_VAR g_pDispatchCache, r8 + mov r8, qword ptr [r8] + mov r8, qword ptr [r8] + + // Compute 32-bit hash: + // hash = IntPtr.GetHashCode(RotateLeft(dispatchCell, 16) ^ objectType) + mov rcx, r11 + rol rcx, 0x10 + xor rcx, r10 + mov r9, rcx + sar r9, 0x20 + xor r9d, ecx + movsxd r9, r9d + + // HashToBucket: bucket = (hash * 0x9E3779B97F4A7C15) >> hashShift + mov rax, 0x9E3779B97F4A7C15 + imul r9, rax + movzx ecx, byte ptr [r8 + 0x10] + shr r9, cl + xor ecx, ecx + +LOCAL_LABEL(ProbeLoop): + // Compute entry address: Element(table, index) = table + 0x10 + (index + 1) * 0x20 + lea eax, [r9 + 1] + movsxd rax, eax + shl rax, 5 + lea rax, [r8 + rax + 0x10] + + // Read version snapshot before key comparison (seqlock protocol). + mov edx, dword ptr [rax] + test edx, 1 + jne LOCAL_LABEL(ProbeMiss) + + // Compare key (dispatchCell, objectType) + cmp r11, qword ptr [rax + 8] + jne LOCAL_LABEL(ProbeMiss) + cmp r10, qword ptr [rax + 0x10] + jne LOCAL_LABEL(ProbeMiss) + + // Read the cached code pointer, then re-verify the version has not changed. + mov r10, qword ptr [rax + 0x18] + cmp edx, dword ptr [rax] + jne LOCAL_LABEL(CacheMiss) + + // Dispatch to cached target. + mov rax, r10 + + mov r9, [rsp - 32] + mov r8, [rsp - 24] + mov rdx, [rsp - 16] + mov rcx, [rsp - 8] + + jmp rax + +LOCAL_LABEL(ProbeMiss): + // If version is zero the rest of the bucket is unclaimed - stop probing. + test edx, edx + je LOCAL_LABEL(CacheMiss) + + // Quadratic reprobe: i++; index = (index + i) & tableMask + inc ecx + add r9d, ecx + mov eax, dword ptr [r8 + 8] + add eax, 0xFFFFFFFE + and r9d, eax + cmp ecx, 8 + jl LOCAL_LABEL(ProbeLoop) + +LOCAL_LABEL(CacheMiss): + mov r9, [rsp - 32] + mov r8, [rsp - 24] + mov rdx, [rsp - 16] + mov rcx, [rsp - 8] -LEAF_END RhpInitialInterfaceDispatch, _TEXT + // r11 still contains the indirection cell address. + jmp C_FUNC(RhpInterfaceDispatchSlow) +LEAF_END RhpInterfaceDispatch, _TEXT -#endif // FEATURE_CACHED_INTERFACE_DISPATCH \ No newline at end of file +#endif // FEATURE_CACHED_INTERFACE_DISPATCH diff --git a/src/coreclr/runtime/amd64/StubDispatch.asm b/src/coreclr/runtime/amd64/StubDispatch.asm index 1eec0c959f00e0..081a24c59a856a 100644 --- a/src/coreclr/runtime/amd64/StubDispatch.asm +++ b/src/coreclr/runtime/amd64/StubDispatch.asm @@ -8,93 +8,116 @@ ifdef FEATURE_CACHED_INTERFACE_DISPATCH EXTERN RhpInterfaceDispatchSlow : PROC -;; Macro that generates code to check a single cache entry. -CHECK_CACHE_ENTRY macro entry -NextLabel textequ @CatStr( Attempt, %entry+1 ) - cmp rax, [r10 + OFFSETOF__InterfaceDispatchCache__m_rgEntries + (entry * 16)] - jne NextLabel - jmp qword ptr [r10 + OFFSETOF__InterfaceDispatchCache__m_rgEntries + (entry * 16) + 8] -NextLabel: -endm +EXTERN g_pDispatchCache : QWORD - -;; Macro that generates a stub consuming a cache with the given number of entries. -DEFINE_INTERFACE_DISPATCH_STUB macro entries - -StubName textequ @CatStr( RhpInterfaceDispatch, entries ) -StubAVLocation textequ @CatStr( RhpInterfaceDispatchAVLocation, entries ) -RaceRetryLabel textequ @CatStr( RaceRetry, entries ) - -LEAF_ENTRY StubName, _TEXT - -;EXTERN CID_g_cInterfaceDispatches : DWORD - ;inc [CID_g_cInterfaceDispatches] - - ;; r11 currently contains the indirection cell address. - ;; load r10 to point to the cache block. - mov r10, [r11 + OFFSETOF__InterfaceDispatchCell__m_pCache] - - ;; Validate r10 is a cache pointer matching the expected cache size. - ;; This compensates for a race where the stub was updated to expect a larger cache - ;; but we loaded a stale (smaller or non-cache) m_pCache value. - ;; On detection, re-dispatch through the indirection cell to retry with the current - ;; stub and cache pair. - test r10, IDC_CACHE_POINTER_MASK - jnz RaceRetryLabel - cmp dword ptr [r10 + OFFSETOF__InterfaceDispatchCache__m_cEntries], entries - jne RaceRetryLabel +;; On Input: +;; rcx contains the this pointer +;; r11 contains the address of the interface dispatch cell +LEAF_ENTRY RhpInterfaceDispatch, _TEXT ;; Load the MethodTable from the object instance in rcx. - ALTERNATE_ENTRY StubAVLocation - mov rax, [rcx] - -CurrentEntry = 0 - while CurrentEntry lt entries - CHECK_CACHE_ENTRY %CurrentEntry -CurrentEntry = CurrentEntry + 1 - endm - - ;; r11 still contains the indirection cell address. - - jmp RhpInterfaceDispatchSlow - -RaceRetryLabel: - jmp qword ptr [r11] - -LEAF_END StubName, _TEXT - - endm ;; DEFINE_INTERFACE_DISPATCH_STUB - - -;; Define all the stub routines we currently need. -;; -;; The mrt100dbi requires these be exported to identify mrt100 code that dispatches back into managed. -;; If you change or add any new dispatch stubs, please also change slr.def and dbi\process.cpp CordbProcess::GetExportStepInfo -;; -;; If you change or add any new dispatch stubs, exception handling might need to be aware because it refers to the -;; *AVLocation symbols defined by the dispatch stubs to be able to unwind and blame user code if a NullRef happens -;; during the interface dispatch. -;; -DEFINE_INTERFACE_DISPATCH_STUB 1 -DEFINE_INTERFACE_DISPATCH_STUB 2 -DEFINE_INTERFACE_DISPATCH_STUB 4 -DEFINE_INTERFACE_DISPATCH_STUB 8 -DEFINE_INTERFACE_DISPATCH_STUB 16 -DEFINE_INTERFACE_DISPATCH_STUB 32 -DEFINE_INTERFACE_DISPATCH_STUB 64 - -;; Initial dispatch on an interface when we don't have a cache yet. -LEAF_ENTRY RhpInitialInterfaceDispatch, _TEXT ;; Trigger an AV if we're dispatching on a null this. ;; The exception handling infrastructure is aware of the fact that this is the first - ;; instruction of RhpInitialInterfaceDispatch and uses it to translate an AV here + ;; instruction of RhpInterfaceDispatch and uses it to translate an AV here ;; to a NullReferenceException at the callsite. - cmp byte ptr [rcx], 0 + mov r10, [rcx] + + ;; r11 currently contains the indirection cell address. + cmp qword ptr [r11], r10 ;; is this the monomorphic MethodTable? + jne Hashtable + + mov rax, [r11 + 8] ;; load the cached monomorphic resolved code address into rax + jmp rax + + Hashtable: + + ;; r10 = MethodTable, r11 = indirection cell address + ;; Look up the target in the dispatch cache hashtable (see CachedInterfaceDispatch.cpp). + ;; Spill argument registers to the caller-provided shadow space + ;; so we don't modify rsp (this is a LEAF_ENTRY with no unwind info). + mov [rsp + 8h], rcx + mov [rsp + 10h], rdx + mov [rsp + 18h], r8 + mov [rsp + 20h], r9 + + ;; Load the current table. + mov r8, qword ptr [g_pDispatchCache] + mov r8, qword ptr [r8] + + ;; Compute 32-bit hash: + ;; hash = IntPtr.GetHashCode(RotateLeft(dispatchCell, 16) ^ objectType) + mov rcx, r11 + rol rcx, 10h + xor rcx, r10 + mov r9, rcx + sar r9, 20h + xor r9d, ecx + movsxd r9, r9d + + ;; HashToBucket: bucket = (hash * 0x9E3779B97F4A7C15) >> hashShift + mov rax, 9E3779B97F4A7C15h + imul r9, rax + movzx ecx, byte ptr [r8 + 10h] + shr r9, cl + xor ecx, ecx + + ProbeLoop: + ;; Compute entry address: Element(table, index) = table + 10h + (index + 1) * 20h + lea eax, [r9 + 1] + movsxd rax, eax + shl rax, 5 + lea rax, [r8 + rax + 10h] + + ;; Read version snapshot before key comparison (seqlock protocol). + mov edx, dword ptr [rax] + test edx, 1 + jne ProbeMiss + + ;; Compare key (dispatchCell, objectType) + cmp r11, qword ptr [rax + 8] + jne ProbeMiss + cmp r10, qword ptr [rax + 10h] + jne ProbeMiss + + ;; Read the cached code pointer, then re-verify the version has not changed. + mov r10, qword ptr [rax + 18h] + cmp edx, dword ptr [rax] + jne CacheMiss + + ;; Dispatch to cached target. + mov rax, r10 + + mov r9, [rsp + 20h] + mov r8, [rsp + 18h] + mov rdx, [rsp + 10h] + mov rcx, [rsp + 8h] + + jmp rax + + ProbeMiss: + ;; If version is zero the rest of the bucket is unclaimed - stop probing. + test edx, edx + je CacheMiss + + ;; Quadratic reprobe: i++; index = (index + i) & tableMask + inc ecx + add r9d, ecx + mov eax, dword ptr [r8 + 8] + add eax, 0FFFFFFFEh + and r9d, eax + cmp ecx, 8 + jl ProbeLoop + + CacheMiss: + mov r9, [rsp + 20h] + mov r8, [rsp + 18h] + mov rdx, [rsp + 10h] + mov rcx, [rsp + 8h] - ;; Just tail call to the cache miss helper. - jmp RhpInterfaceDispatchSlow + ;; r11 still contains the indirection cell address. + jmp RhpInterfaceDispatchSlow -LEAF_END RhpInitialInterfaceDispatch, _TEXT +LEAF_END RhpInterfaceDispatch, _TEXT endif ;; FEATURE_CACHED_INTERFACE_DISPATCH diff --git a/src/coreclr/runtime/arm64/StubDispatch.S b/src/coreclr/runtime/arm64/StubDispatch.S index c40c9b98fc649c..a587af1d3e55f0 100644 --- a/src/coreclr/runtime/arm64/StubDispatch.S +++ b/src/coreclr/runtime/arm64/StubDispatch.S @@ -5,128 +5,110 @@ #ifdef FEATURE_CACHED_INTERFACE_DISPATCH -#if defined(__APPLE__) - // Currently the build is failing without this due to an issue if the first method in the assembly file has an alternate entry at the start of the file. - // Fix, but adding an empty, unused method - LEAF_ENTRY RhpStubDispatchDoNotFailToBuild, _TEXT - ret - LEAF_END RhpStubDispatchDoNotFailToBuild, _TEXT -#endif - - // Macro that generates code to check a single cache entry. - // \adj is the base adjustment already applied to x9. - .macro CHECK_CACHE_ENTRY entry, adj=0 - // Check a single entry in the cache. - // x9 : Cache data structure (possibly adjusted for far entries) - // x10 : Instance MethodTable* - // x11 : Indirection cell address, preserved - // x12, x13 : Trashed - // - // Use ldp to load both m_pInstanceType and m_pTargetCode in a single instruction. - // On ARM64 two separate ldr instructions can be reordered across a control dependency, - // which means a concurrent atomic cache entry update (via stlxp) could be observed as a - // torn read (new type, old target). ldp is single-copy atomic for the pair on FEAT_LSE2 - // hardware (ARMv8.4+). The cbz guard ensures correctness on pre-LSE2 hardware too: - // a torn read can only produce a zero target (entries go from 0,0 to type,target), - // so we treat it as a cache miss. - ldp x12, x13, [x9, #(OFFSETOF__InterfaceDispatchCache__m_rgEntries + (\entry * 16) - \adj)] - cmp x10, x12 - bne 0f -#ifndef TARGET_APPLE - // Apple ARM64 platforms have FEAT_LSE2, making ldp single-copy atomic for the pair. - cbz x13, 0f -#endif - br x13 -0: - .endm - -// -// Macro that generates a stub consuming a cache with the given number of entries. -// - .macro DEFINE_INTERFACE_DISPATCH_STUB entries - - NESTED_ENTRY "RhpInterfaceDispatch\entries", _TEXT, NoHandler - - // x11 holds the indirection cell address. Load the cache pointer. - ldr x9, [x11, #OFFSETOF__InterfaceDispatchCell__m_pCache] - - // Validate x9 is a cache pointer matching the expected cache size. - // This compensates for a race where the stub was updated to expect a larger cache - // but we loaded a stale (smaller or non-cache) m_pCache value. - // On detection, re-dispatch through the indirection cell to retry with the current - // stub and cache pair. - tst x9, #IDC_CACHE_POINTER_MASK - bne LOCAL_LABEL(RaceRetry_\entries) - ldr w12, [x9, #OFFSETOF__InterfaceDispatchCache__m_cEntries] - cmp w12, #\entries - bne LOCAL_LABEL(RaceRetry_\entries) +// On Input: +// x0 contains the this pointer +// x11 contains the address of the interface dispatch cell + LEAF_ENTRY RhpInterfaceDispatch, _TEXT // Load the MethodTable from the object instance in x0. -#ifdef TARGET_APPLE -// Apple's linker has issues which break unwind info if -// an ALTERNATE_ENTRY is present in the middle of a function see https://github.com/dotnet/runtime/pull/114982#discussion_r2083272768 -.cfi_endproc -#endif - ALTERNATE_ENTRY RhpInterfaceDispatchAVLocation\entries -#ifdef TARGET_APPLE -.cfi_startproc -#endif - ldr x10, [x0] - - .global CurrentEntry - .set CurrentEntry, 0 - .set BaseAdj, 0 - - .rept \entries - // ldp's signed offset must be in [-512,504] for 64-bit register pairs. - // When the offset would exceed that, re-base x9 once so subsequent entries stay in range. - .if (OFFSETOF__InterfaceDispatchCache__m_rgEntries + (CurrentEntry * 16) - BaseAdj) > 504 - add x9, x9, #(OFFSETOF__InterfaceDispatchCache__m_rgEntries + (CurrentEntry * 16) - BaseAdj) - .set BaseAdj, (OFFSETOF__InterfaceDispatchCache__m_rgEntries + (CurrentEntry * 16)) - .endif - CHECK_CACHE_ENTRY CurrentEntry, BaseAdj - .set CurrentEntry, CurrentEntry + 1 - .endr + // Trigger an AV if we're dispatching on a null this. + // The exception handling infrastructure is aware of the fact that this is the first + // instruction of RhpInterfaceDispatch and uses it to translate an AV here + // to a NullReferenceException at the callsite. + ldr x12, [x0] - // x11 still contains the indirection cell address. - b C_FUNC(RhpInterfaceDispatchSlow) + // x11 currently contains the indirection cell address. + // Load-acquire ensures that if we observe the cached MethodTable, + // the subsequent load of Code will see the value written before it. + ldar x13, [x11] // load-acquire cached MethodTable + cmp x13, x12 // is this the monomorphic MethodTable? + bne LOCAL_LABEL(Hashtable) -LOCAL_LABEL(RaceRetry_\entries): - // Race detected: re-dispatch through the indirection cell - ldr x9, [x11] + ldr x9, [x11, #8] // load the cached monomorphic resolved code address br x9 - NESTED_END "RhpInterfaceDispatch\entries", _TEXT - - .endm - -// -// Define all the stub routines we currently need. -// -// If you change or add any new dispatch stubs, exception handling might need to be aware because it refers to the -// *AVLocation symbols defined by the dispatch stubs to be able to unwind and blame user code if a NullRef happens -// during the interface dispatch. -// - DEFINE_INTERFACE_DISPATCH_STUB 1 - DEFINE_INTERFACE_DISPATCH_STUB 2 - DEFINE_INTERFACE_DISPATCH_STUB 4 - DEFINE_INTERFACE_DISPATCH_STUB 8 - DEFINE_INTERFACE_DISPATCH_STUB 16 - DEFINE_INTERFACE_DISPATCH_STUB 32 - DEFINE_INTERFACE_DISPATCH_STUB 64 - -// -// Initial dispatch on an interface when we don't have a cache yet. -// - LEAF_ENTRY RhpInitialInterfaceDispatch, _TEXT - // Trigger an AV if we're dispatching on a null this. - // The exception handling infrastructure is aware of the fact that this is the first - // instruction of RhpInitialInterfaceDispatch and uses it to translate an AV here - // to a NullReferenceException at the callsite. - ldr xzr, [x0] +LOCAL_LABEL(Hashtable): + + // x12 = MethodTable, x11 = indirection cell address + // Look up the target in the dispatch cache hashtable (see CachedInterfaceDispatch.cpp). + // Only volatile scratch registers (x9-x17) are used, so no argument + // register spilling is needed. + + // Load the current table. + PREPARE_EXTERNAL_VAR_INDIRECT g_pDispatchCache, x13 + ldr x13, [x13] + + // Compute 32-bit hash: + // hash = IntPtr.GetHashCode(RotateLeft(dispatchCell, 16) ^ objectType) + eor x14, x12, x11, ror #48 // combined = MethodTable ^ RotateLeft(cell, 16) + asr x16, x14, #32 // upper32 = combined >> 32 (arithmetic) + eor w14, w14, w16 // hash = (int)lower32 ^ (int)upper32 + sxtw x14, w14 // sign-extend hash to 64-bit + + // HashToBucket: bucket = (hash * 0x9E3779B97F4A7C15) >> hashShift + movz x16, #0x7C15 + movk x16, #0x7F4A, lsl #16 + movk x16, #0x79B9, lsl #32 + movk x16, #0x9E37, lsl #48 + mul x14, x14, x16 + ldrb w16, [x13, #0x10] // hashShift from Element[0] + lsr x14, x14, x16 // bucket index + + // Precompute loop-invariant base: table + 0x10 (start of Element data). + add x13, x13, #0x10 + mov w15, wzr // loop counter i = 0 + +LOCAL_LABEL(ProbeLoop): + // Compute entry address: Element(table, index) = base + (index + 1) * 0x20 + add w9, w14, #1 + sbfiz x9, x9, #5, #32 // sign-extend and shift left by 5 in one instruction + add x9, x13, x9 + + // Read version snapshot with load-acquire (seqlock protocol, ARM64 memory model). + // This ensures subsequent loads of key and value see data written before this version. + ldar w10, [x9] + tbnz w10, #0, LOCAL_LABEL(ProbeMiss) // skip if odd (entry being written) + + // Compare key (dispatchCell, objectType). The key is not 16-byte aligned, so it is + // loaded with two loads instead of a ldp. + ldr x16, [x9, #8] + cmp x16, x11 + bne LOCAL_LABEL(ProbeMiss) + ldr x17, [x9, #0x10] + cmp x17, x12 + bne LOCAL_LABEL(ProbeMiss) + + // Read the cached code pointer. + ldr x16, [x9, #0x18] + + // Ensure value read completes before version re-read (ARM64 needs explicit barrier). + dmb ishld + + // Re-verify version has not changed. + ldr w17, [x9] + cmp w10, w17 + bne LOCAL_LABEL(CacheMiss) + + // Dispatch to cached target. + br x16 + +LOCAL_LABEL(ProbeMiss): + // If version is zero the rest of the bucket is unclaimed - stop probing. + cbz w10, LOCAL_LABEL(CacheMiss) + + // Quadratic reprobe: i++; index = (index + i) & tableMask + add w15, w15, #1 + add w14, w14, w15 + ldr w9, [x13, #-8] // table length (at base - 0x10 + 0x08 = base - 0x08) + sub w9, w9, #2 // TableMask = Length - 2 + and w14, w14, w9 + cmp w15, #8 + blt LOCAL_LABEL(ProbeLoop) + +LOCAL_LABEL(CacheMiss): + // x11 still contains the indirection cell address. + b C_FUNC(RhpInterfaceDispatchSlow) - // Just tail call to the cache miss helper. - b C_FUNC(RhpInterfaceDispatchSlow) - LEAF_END RhpInitialInterfaceDispatch, _TEXT + LEAF_END RhpInterfaceDispatch, _TEXT #endif // FEATURE_CACHED_INTERFACE_DISPATCH diff --git a/src/coreclr/runtime/arm64/StubDispatch.asm b/src/coreclr/runtime/arm64/StubDispatch.asm index e34bdcf68e0f88..6df101124fc1a7 100644 --- a/src/coreclr/runtime/arm64/StubDispatch.asm +++ b/src/coreclr/runtime/arm64/StubDispatch.asm @@ -8,116 +8,113 @@ #ifdef FEATURE_CACHED_INTERFACE_DISPATCH EXTERN RhpInterfaceDispatchSlow + EXTERN g_pDispatchCache - ;; Macro that generates code to check a single cache entry. - MACRO - CHECK_CACHE_ENTRY $entry, $adj - ;; Check a single entry in the cache. - ;; x9 : Cache data structure (possibly adjusted for far entries) - ;; x10 : Instance MethodTable* - ;; x11 : Indirection cell address, preserved - ;; x12, x13 : Trashed - ;; $adj : Base adjustment already applied to x9 - ;; - ;; Use ldp to load both m_pInstanceType and m_pTargetCode in a single instruction. - ;; On ARM64 two separate ldr instructions can be reordered across a control dependency, - ;; which means a concurrent atomic cache entry update (via stlxp) could be observed as a - ;; torn read (new type, old target). ldp is single-copy atomic for the pair on FEAT_LSE2 - ;; hardware (ARMv8.4+). The cbz guard ensures correctness on pre-LSE2 hardware too: - ;; a torn read can only produce a zero target (entries go from 0,0 to type,target), - ;; so we treat it as a cache miss. - ldp x12, x13, [x9, #(OFFSETOF__InterfaceDispatchCache__m_rgEntries + ($entry * 16) - $adj)] - cmp x10, x12 - bne %ft0 - cbz x13, %ft0 - br x13 -0 - MEND - - -;; -;; Macro that generates a stub consuming a cache with the given number of entries. -;; - MACRO - DEFINE_INTERFACE_DISPATCH_STUB $entries - - NESTED_ENTRY RhpInterfaceDispatch$entries - - ;; x11 holds the indirection cell address. Load the cache pointer. - ldr x9, [x11, #OFFSETOF__InterfaceDispatchCell__m_pCache] - - ;; Validate x9 is a cache pointer matching the expected cache size. - ;; This compensates for a race where the stub was updated to expect a larger cache - ;; but we loaded a stale (smaller or non-cache) m_pCache value. - ;; On detection, re-dispatch through the indirection cell to retry with the current - ;; stub and cache pair. - tst x9, #IDC_CACHE_POINTER_MASK - bne CidRaceRetry_$entries - ldr w12, [x9, #OFFSETOF__InterfaceDispatchCache__m_cEntries] - cmp w12, #$entries - bne CidRaceRetry_$entries +;; On Input: +;; x0 contains the this pointer +;; x11 contains the address of the interface dispatch cell + LEAF_ENTRY RhpInterfaceDispatch ;; Load the MethodTable from the object instance in x0. - ALTERNATE_ENTRY RhpInterfaceDispatchAVLocation$entries - ldr x10, [x0] - - GBLA CurrentEntry - GBLA BaseAdj -CurrentEntry SETA 0 -BaseAdj SETA 0 - - WHILE CurrentEntry < $entries - ;; ldp's signed offset must be in [-512,504] for 64-bit register pairs. - ;; When the offset would exceed that, re-base x9 once so subsequent entries stay in range. - IF (OFFSETOF__InterfaceDispatchCache__m_rgEntries + (CurrentEntry * 16) - BaseAdj) > 504 - add x9, x9, #(OFFSETOF__InterfaceDispatchCache__m_rgEntries + (CurrentEntry * 16) - BaseAdj) -BaseAdj SETA (OFFSETOF__InterfaceDispatchCache__m_rgEntries + (CurrentEntry * 16)) - ENDIF - CHECK_CACHE_ENTRY CurrentEntry, BaseAdj -CurrentEntry SETA CurrentEntry + 1 - WEND + ;; Trigger an AV if we're dispatching on a null this. + ;; The exception handling infrastructure is aware of the fact that this is the first + ;; instruction of RhpInterfaceDispatch and uses it to translate an AV here + ;; to a NullReferenceException at the callsite. + ldr x12, [x0] - ;; x11 still contains the indirection cell address. - b RhpInterfaceDispatchSlow + ;; x11 currently contains the indirection cell address. + ;; Load-acquire ensures that if we observe the cached MethodTable, + ;; the subsequent load of Code will see the value written before it. + ldar x13, [x11] ;; load-acquire cached MethodTable + cmp x13, x12 ;; is this the monomorphic MethodTable? + bne %ft1 -CidRaceRetry_$entries - ;; Race detected: re-dispatch through the indirection cell - ldr x9, [x11] + ldr x9, [x11, #8] ;; load the cached monomorphic resolved code address br x9 - NESTED_END RhpInterfaceDispatch$entries - - MEND - -;; -;; Define all the stub routines we currently need. -;; -;; If you change or add any new dispatch stubs, exception handling might need to be aware because it refers to the -;; *AVLocation symbols defined by the dispatch stubs to be able to unwind and blame user code if a NullRef happens -;; during the interface dispatch. -;; - DEFINE_INTERFACE_DISPATCH_STUB 1 - DEFINE_INTERFACE_DISPATCH_STUB 2 - DEFINE_INTERFACE_DISPATCH_STUB 4 - DEFINE_INTERFACE_DISPATCH_STUB 8 - DEFINE_INTERFACE_DISPATCH_STUB 16 - DEFINE_INTERFACE_DISPATCH_STUB 32 - DEFINE_INTERFACE_DISPATCH_STUB 64 - - -;; -;; Initial dispatch on an interface when we don't have a cache yet. -;; - LEAF_ENTRY RhpInitialInterfaceDispatch - ;; Trigger an AV if we're dispatching on a null this. - ;; The exception handling infrastructure is aware of the fact that this is the first - ;; instruction of RhpInitialInterfaceDispatch and uses it to translate an AV here - ;; to a NullReferenceException at the callsite. - ldr xzr, [x0] +1 + ;; x12 = MethodTable, x11 = indirection cell address + ;; Look up the target in the dispatch cache hashtable (see CachedInterfaceDispatch.cpp). + ;; Only volatile scratch registers (x9-x17) are used, so no argument + ;; register spilling is needed. + + ;; Load the current table. + adrp x13, g_pDispatchCache + ldr x13, [x13, g_pDispatchCache] + ldr x13, [x13] + + ;; Compute 32-bit hash: + ;; hash = IntPtr.GetHashCode(RotateLeft(dispatchCell, 16) ^ objectType) + eor x14, x12, x11, ror #48 ;; combined = MethodTable ^ RotateLeft(cell, 16) + asr x16, x14, #32 ;; upper32 = combined >> 32 (arithmetic) + eor w14, w14, w16 ;; hash = (int)lower32 ^ (int)upper32 + sxtw x14, w14 ;; sign-extend hash to 64-bit + + ;; HashToBucket: bucket = (hash * 0x9E3779B97F4A7C15) >> hashShift + movz x16, #0x7C15 + movk x16, #0x7F4A, lsl #16 + movk x16, #0x79B9, lsl #32 + movk x16, #0x9E37, lsl #48 + mul x14, x14, x16 + ldrb w16, [x13, #0x10] ;; hashShift from Element[0] + lsr x14, x14, x16 ;; bucket index + + ;; Precompute loop-invariant base: table + 0x10 (start of Element data). + add x13, x13, #0x10 + mov w15, wzr ;; loop counter i = 0 + +2 ;; ProbeLoop + ;; Compute entry address: Element(table, index) = base + (index + 1) * 0x20 + add w9, w14, #1 + sbfiz x9, x9, #5, #32 ;; sign-extend and shift left by 5 in one instruction + add x9, x13, x9 + + ;; Read version snapshot with load-acquire (seqlock protocol, ARM64 memory model). + ;; This ensures subsequent loads of key and value see data written before this version. + ldar w10, [x9] + tbnz w10, #0, %ft3 ;; skip if odd (entry being written) + + ;; Compare key (dispatchCell, objectType). The key is not 16-byte aligned, so it is + ;; loaded with two loads instead of a ldp. + ldr x16, [x9, #8] + cmp x16, x11 + bne %ft3 + ldr x17, [x9, #0x10] + cmp x17, x12 + bne %ft3 + + ;; Read the cached code pointer. + ldr x16, [x9, #0x18] + + ;; Ensure value read completes before version re-read (ARM64 needs explicit barrier). + dmb ishld + + ;; Re-verify version has not changed. + ldr w17, [x9] + cmp w10, w17 + bne %ft4 + + ;; Dispatch to cached target. + br x16 + +3 ;; ProbeMiss + ;; If version is zero the rest of the bucket is unclaimed - stop probing. + cbz w10, %ft4 + + ;; Quadratic reprobe: i++; index = (index + i) & tableMask + add w15, w15, #1 + add w14, w14, w15 + ldr w9, [x13, #-8] ;; table length (at base - 0x10 + 0x08 = base - 0x08) + sub w9, w9, #2 ;; TableMask = Length - 2 + and w14, w14, w9 + cmp w15, #8 + blt %bt2 + +4 ;; CacheMiss + ;; x11 still contains the indirection cell address. + b RhpInterfaceDispatchSlow - ;; Just tail call to the cache miss helper. - b RhpInterfaceDispatchSlow - LEAF_END RhpInitialInterfaceDispatch + LEAF_END RhpInterfaceDispatch #endif // FEATURE_CACHED_INTERFACE_DISPATCH diff --git a/src/coreclr/tools/Common/Internal/Runtime/ModuleHeaders.cs b/src/coreclr/tools/Common/Internal/Runtime/ModuleHeaders.cs index 79183dc60ebdd4..dee3e23e8f4e37 100644 --- a/src/coreclr/tools/Common/Internal/Runtime/ModuleHeaders.cs +++ b/src/coreclr/tools/Common/Internal/Runtime/ModuleHeaders.cs @@ -16,7 +16,7 @@ internal struct ReadyToRunHeaderConstants public const uint Signature = 0x00525452; // 'RTR' public const ushort CurrentMajorVersion = 34; - public const ushort CurrentMinorVersion = 1; + public const ushort CurrentMinorVersion = 2; } #if READYTORUN #pragma warning disable 0169 diff --git a/src/coreclr/tools/Common/Internal/Runtime/ReadyToRunConstants.cs b/src/coreclr/tools/Common/Internal/Runtime/ReadyToRunConstants.cs index 78338cf0acdc8d..df8dae41b1e31f 100644 --- a/src/coreclr/tools/Common/Internal/Runtime/ReadyToRunConstants.cs +++ b/src/coreclr/tools/Common/Internal/Runtime/ReadyToRunConstants.cs @@ -386,6 +386,9 @@ public enum ReadyToRunHelper R2RToInterpreter = 0x118, WasmProfSamplepoint = 0x119, + // Interface dispatch through a cached interface dispatch cell passed in the VSD parameter register + InterfaceDispatch = 0x11A, + // ********************************************************************************************** // // These are not actually part of the R2R file format. We have them here because it's convenient. @@ -426,7 +429,6 @@ public enum ReadyToRunHelper NewArrayFast, // NativeAOT interface dispatch helpers - InterfaceDispatch, InterfaceDispatchGuarded, ResolveInterfaceMethodFast, ResolveInterfaceMethod, diff --git a/src/coreclr/tools/Common/JitInterface/CorInfoImpl.cs b/src/coreclr/tools/Common/JitInterface/CorInfoImpl.cs index 272c30be01c6fe..8225de74fec275 100644 --- a/src/coreclr/tools/Common/JitInterface/CorInfoImpl.cs +++ b/src/coreclr/tools/Common/JitInterface/CorInfoImpl.cs @@ -5039,7 +5039,10 @@ private uint getJitFlags(ref CORJIT_FLAGS flags, uint sizeInBytes) flags.Set(CorJitFlag.CORJIT_FLAG_AOT); flags.Set(CorJitFlag.CORJIT_FLAG_RELOC); flags.Set(CorJitFlag.CORJIT_FLAG_USE_PINVOKE_HELPERS); -#if !READYTORUN +#if READYTORUN + if (_compilation.NodeFactory.UseInterfaceDispatchHelper) + flags.Set(CorJitFlag.CORJIT_FLAG_USE_DISPATCH_HELPERS); +#else flags.Set(CorJitFlag.CORJIT_FLAG_USE_DISPATCH_HELPERS); #endif diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/DelayLoadHelperImport.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/DelayLoadHelperImport.cs index 00ef66205e7102..bfb65ea9ac7a18 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/DelayLoadHelperImport.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/DelayLoadHelperImport.cs @@ -44,6 +44,11 @@ public DelayLoadHelperImport( { _delayLoadHelper = factory.WasmImportThunkPortableEntrypoint(this); } + else if (useVirtualCall && factory.UseInterfaceDispatchHelper) + { + // Call sites pass the cell to the interface dispatch helper, which resolves it on the first call. + _delayLoadHelper = null; + } else { _delayLoadHelper = factory.ImportThunk(helper, importSectionNode, useVirtualCall, useJumpableStub); @@ -88,14 +93,11 @@ public override void EncodeData(ref ObjectDataBuilder dataBuilder, NodeFactory f dataBuilder.EmitNaturalInt(0); } - if (Table.EntrySize == (factory.Target.PointerSize * 2)) + Debug.Assert(Table.EntrySize % factory.Target.PointerSize == 0); + for (int offset = factory.Target.PointerSize; offset < Table.EntrySize; offset += factory.Target.PointerSize) { dataBuilder.EmitNaturalInt(0); } - else - { - Debug.Assert(Table.EntrySize == factory.Target.PointerSize); - } } public override void AddStaticDependencies(DependencySink sink, NodeFactory factory) diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/Import.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/Import.cs index 6d3fd4299081d3..44ed4c4ccd7077 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/Import.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/Import.cs @@ -74,10 +74,9 @@ protected override string GetName(NodeFactory factory) public virtual bool EmitPrecode => Table.EmitPrecode; - // Import cells live in a pointer-aligned import section whose entries are 'EntrySize' bytes - // each, so every cell is guaranteed to be aligned to 'EntrySize' (the pointer size). Keep - // this in sync with the alignment applied by the containing ImportSectionNode. - public int GetAlignment(NodeFactory factory) => Table.EntrySize; + // Import cells live in an import section whose entries are 'EntrySize' bytes each, so every + // cell is guaranteed to be aligned to the alignment applied by the containing ImportSectionNode. + public int GetAlignment(NodeFactory factory) => Table.EntryAlignment; public override void EncodeData(ref ObjectDataBuilder dataBuilder, NodeFactory factory, bool relocsOnly) { diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/ImportSectionNode.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/ImportSectionNode.cs index 414dc42edc83b3..2214c10efd7592 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/ImportSectionNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/ImportSectionNode.cs @@ -52,7 +52,7 @@ public ImportSectionNode(string name, ReadyToRunImportSectionType importType, Re _entrySize = entrySize; _emitPrecode = emitPrecode; - _imports = new ImportTable(_name + "_ImportBegin", entrySize); + _imports = new ImportTable(_name + "_ImportBegin", (byte)EntryAlignment); _signatures = new ArrayOfEmbeddedPointersNode(_name + "_SigBegin", new EmbeddedObjectNodeComparer(CompilerComparer.Instance)); _signatureList = new List(); } @@ -156,5 +156,8 @@ public override int CompareToImpl(ISortableNode other, CompilerComparer comparer } public int EntrySize => _entrySize; + + // Entries are laid out back to back, so each one is aligned to the largest power of two dividing the entry size. + public int EntryAlignment => _entrySize & -_entrySize; } } diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRunCodegenNodeFactory.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRunCodegenNodeFactory.cs index 3f294d76a9a6e0..2c5d361b50dae7 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRunCodegenNodeFactory.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRunCodegenNodeFactory.cs @@ -637,6 +637,12 @@ private void CreateNodeCaches() public ImportSectionNode DispatchImports; + /// + /// Interface call sites pass their dispatch cell to the interface dispatch helper instead of calling + /// through the cell. The cells are laid out as { MethodTable, Code, Token } for cached interface dispatch. + /// + public bool UseInterfaceDispatchHelper => OptimizationFlags.EnableCachedInterfaceDispatchSupport && !Target.IsWasm; + public ImportSectionNode StringImports; public ImportSectionNode HelperImports; @@ -1329,7 +1335,7 @@ bool HasAnyProfileDataForInput() "DispatchImports", ReadyToRunImportSectionType.StubDispatch, ReadyToRunImportSectionFlags.PCode, - (this.OptimizationFlags.EnableCachedInterfaceDispatchSupport && !Target.IsWasm) ? (byte)(2 * Target.PointerSize) : (byte)Target.PointerSize, + UseInterfaceDispatchHelper ? (byte)(3 * Target.PointerSize) : (byte)Target.PointerSize, emitPrecode: false, emitGCRefMap: true); ImportSectionsTable.AddEmbeddedObject(DispatchImports); diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/JitInterface/CorInfoImpl.ReadyToRun.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/JitInterface/CorInfoImpl.ReadyToRun.cs index 7d6bd89fd29136..728502ddd7db3c 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/JitInterface/CorInfoImpl.ReadyToRun.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/JitInterface/CorInfoImpl.ReadyToRun.cs @@ -1472,6 +1472,11 @@ private ISymbolNode GetHelperFtnUncached(CorInfoHelpFunc ftnNum, out MethodDesc id = ReadyToRunHelper.ThrowNotImplemented; break; + case CorInfoHelpFunc.CORINFO_HELP_INTERFACEDISPATCH_FOR_SLOT: + Debug.Assert(_compilation.NodeFactory.UseInterfaceDispatchHelper); + id = ReadyToRunHelper.InterfaceDispatch; + break; + case CorInfoHelpFunc.CORINFO_HELP_GETSYNCFROMCLASSHANDLE: case CorInfoHelpFunc.CORINFO_HELP_GETCLASSFROMMETHODPARAM: case CorInfoHelpFunc.CORINFO_HELP_GETREFANY: diff --git a/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/ReadyToRunSignature.cs b/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/ReadyToRunSignature.cs index ffff89bccb53ce..f22654ba100acd 100644 --- a/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/ReadyToRunSignature.cs +++ b/src/coreclr/tools/aot/ILCompiler.Reflection.ReadyToRun/ReadyToRunSignature.cs @@ -2125,6 +2125,9 @@ private void ParseHelper(StringBuilder builder) case ReadyToRunHelper.R2RToInterpreter: builder.Append("R2R_TO_INTERPRETER"); break; + case ReadyToRunHelper.InterfaceDispatch: + builder.Append("INTERFACE_DISPATCH"); + break; default: throw new BadImageFormatException(helperType.ToString()); diff --git a/src/coreclr/vm/CMakeLists.txt b/src/coreclr/vm/CMakeLists.txt index 6d9342623de121..9113fc812daca1 100644 --- a/src/coreclr/vm/CMakeLists.txt +++ b/src/coreclr/vm/CMakeLists.txt @@ -316,7 +316,6 @@ set(VM_SOURCES_WKS baseassemblyspec.cpp bundle.cpp ${RUNTIME_DIR}/CachedInterfaceDispatch.cpp - CachedInterfaceDispatch_Coreclr.cpp ${RUNTIME_DIR}/MathHelpers.cpp ${RUNTIME_DIR}/MiscNativeHelpers.cpp ${RUNTIME_DIR}/ProcessEnvironment.cpp diff --git a/src/coreclr/vm/CachedInterfaceDispatchPal.h b/src/coreclr/vm/CachedInterfaceDispatchPal.h index b5fe783229271b..37187209bd37d9 100644 --- a/src/coreclr/vm/CachedInterfaceDispatchPal.h +++ b/src/coreclr/vm/CachedInterfaceDispatchPal.h @@ -6,190 +6,59 @@ #ifdef FEATURE_CACHED_INTERFACE_DISPATCH -extern "C" void RhpInitialInterfaceDispatch(); - - -bool InterfaceDispatch_InitializePal(); - -// Allocate memory aligned at sizeof(void*)*2 boundaries -void *InterfaceDispatch_AllocDoublePointerAligned(size_t size); -// Allocate memory aligned at sizeof(void*) boundaries - -void *InterfaceDispatch_AllocPointerAligned(size_t size); - -enum Flags -{ - // The low 2 bits of the m_pCache pointer are treated specially so that we can avoid the need for - // extra fields on this type. - // OR if the m_pCache value is less than 0x1000 then this is a vtable offset and should be used as such - IDC_CachePointerPointsIsVTableOffset = 0x2, - IDC_CachePointerPointsAtCache = 0x0, - IDC_CachePointerMask = 0x3, - IDC_CachePointerMaskShift = 0x2, -}; - -enum class DispatchCellType -{ - InterfaceAndSlot = 0x0, - VTableOffset = 0x2, -}; - -struct DispatchCellInfo -{ -private: - static DispatchCellType CellTypeFromToken(DispatchToken token) - { - if (token.IsThisToken()) - { - return DispatchCellType::VTableOffset; - } - return DispatchCellType::InterfaceAndSlot; - } -public: - - DispatchCellInfo(DispatchToken token, bool hasCache) : - CellType(CellTypeFromToken(token)), - Token(token), - HasCache(hasCache ? 1 : 0) - { - - } - const DispatchCellType CellType; - const DispatchToken Token; - - uintptr_t GetVTableOffset() const - { - if (CellType == DispatchCellType::VTableOffset) - { - // The vtable offset is stored in a pointer sized field, but actually represents 2 values. - // 1. The offset of the first indirection to use. which is stored in the upper half of the - // pointer sized field (bits 16-31 of a 32 bit pointer, or bits 32-63 of a 64 bit pointer). - // - // 2. The offset of the second indirection, which is a stored is the upper half of the lower - // half of the pointer size field (bits 8-15 of a 32 bit pointer, or bits 16-31 of a 64 - // bit pointer) This second offset is always less than 255, so we only really need a single - // byte, and the assembly code on some architectures may take a dependency on that - // so the VTableOffsetToSlot function has a mask to ensure that it is only ever a single byte. - uint32_t slot = Token.GetSlotNumber(); - unsigned offsetOfIndirection = MethodTable::GetVtableOffset() + MethodTable::GetIndexOfVtableIndirection(slot) * TARGET_POINTER_SIZE; - unsigned offsetAfterIndirection = MethodTable::GetIndexAfterVtableIndirection(slot) * TARGET_POINTER_SIZE; - - uintptr_t offsetOfIndirectionPortion = (((uintptr_t)offsetOfIndirection) << ((TARGET_POINTER_SIZE * 8) / 2)); - uintptr_t offsetAfterIndirectionPortion = (((uintptr_t)offsetAfterIndirection) << ((TARGET_POINTER_SIZE * 8) / 4)); - uintptr_t flagPortion = (uintptr_t)IDC_CachePointerPointsIsVTableOffset; - - uintptr_t result = offsetOfIndirectionPortion | offsetAfterIndirectionPortion | flagPortion; - _ASSERTE(slot == VTableOffsetToSlot(result)); - return result; - } - return 0; - } - - static unsigned VTableOffsetToSlot(uintptr_t vtableOffset) - { - // See comment in GetVTableOffset() for what we're doing here. - unsigned offsetOfIndirection = (unsigned)(vtableOffset >> ((TARGET_POINTER_SIZE * 8) / 2)); - unsigned offsetAfterIndirection = (unsigned)(vtableOffset >> ((TARGET_POINTER_SIZE * 8) / 4)) & 0xFF; - unsigned slotGroupPerChunk = (offsetOfIndirection - MethodTable::GetVtableOffset()) / TARGET_POINTER_SIZE; - unsigned slot = (slotGroupPerChunk * VTABLE_SLOTS_PER_CHUNK) + (offsetAfterIndirection / TARGET_POINTER_SIZE); - return slot; - } - - const uint8_t HasCache = 0; -}; - -struct InterfaceDispatchCacheHeader +extern "C" void RhpInterfaceDispatch(); + +// One of these is allocated per interface call site. Call sites pass its address to RhpInterfaceDispatch. +// +// The first two fields are a monomorphic cache read by RhpInterfaceDispatch: if the MethodTable of the +// object matches m_pMethodTable, the call goes straight to m_pCode. The writer stores m_pCode first and +// publishes m_pMethodTable with release semantics, so a reader that observes m_pMethodTable also observes +// the matching m_pCode. All other (cell, MethodTable) pairs are cached in a global hashtable. +// +// m_token holds the interface contract (the interface type and slot being called), encoded with +// DispatchToken::ToCachedInterfaceDispatchToken so that it is never zero. Cells in ReadyToRun images +// start out with m_token == 0, the token is decoded from the import signature on the first call. +struct InterfaceDispatchCell { -private: - enum Flags - { - CH_TypeAndSlotIndex = 0x0, - CH_MetadataToken = 0x1, - CH_Mask = 0x3, - CH_Shift = 0x2, - }; + Volatile m_pMethodTable; + PCODE m_pCode; + Volatile m_token; -public: void Initialize(DispatchToken token) { - m_token = token; + LIMITED_METHOD_CONTRACT; + m_pMethodTable = 0; + m_pCode = 0; + m_token = DispatchToken::ToCachedInterfaceDispatchToken(token); } - void Initialize(const DispatchCellInfo *pNewCellInfo) + bool HasToken() const { - m_token = pNewCellInfo->Token; + LIMITED_METHOD_CONTRACT; + return m_token != 0; } - DispatchCellInfo GetDispatchCellInfo() + DispatchToken GetToken() const { - DispatchCellInfo cellInfo(m_token, true); - return cellInfo; + LIMITED_METHOD_CONTRACT; + _ASSERTE(HasToken()); + return DispatchToken::FromCachedInterfaceDispatchToken(m_token); } -private: - DispatchToken m_token; - TADDR padding; // Ensure that the size of this structure is a multiple of 2 pointers -}; - -// One of these is allocated per interface call site. It holds the stub to call, data to pass to that stub -// (cache information) and the interface contract, i.e. the interface type and slot being called. -struct InterfaceDispatchCell -{ - // The first two fields must remain together and at the beginning of the structure. This is due to the - // synchronization requirements of the code that updates these at runtime and the instructions generated - // by the binder for interface call sites. - TADDR m_pStub; // Call this code to execute the interface dispatch - Volatile m_pCache; // Context used by the stub above (one or both of the low two bits are set - // for initial dispatch, and if not set, using this as a cache pointer or - // as a vtable offset.) - DispatchCellInfo GetDispatchCellInfo() + void SetToken(DispatchToken token) { - // Capture m_pCache into a local for safe access (this is a volatile read of a value that may be - // modified on another thread while this function is executing.) - TADDR cachePointerValue = m_pCache; - - if (IsCache(cachePointerValue)) - { - return ((InterfaceDispatchCacheHeader*)cachePointerValue)->GetDispatchCellInfo(); - } - else if (DispatchToken::IsCachedInterfaceDispatchToken(cachePointerValue)) - { - return DispatchCellInfo(DispatchToken::FromCachedInterfaceDispatchToken(cachePointerValue), false); - } - else - { - _ASSERTE(IsVTableOffset(cachePointerValue)); - unsigned slot = DispatchCellInfo::VTableOffsetToSlot(cachePointerValue); - return DispatchCellInfo(DispatchToken::CreateDispatchToken(slot), false); - } - } - - static bool IsCache(TADDR value) - { - return (value & IDC_CachePointerMask) == 0; - } - - static bool IsVTableOffset(TADDR value) - { - return (value & IDC_CachePointerPointsIsVTableOffset) == IDC_CachePointerPointsIsVTableOffset; - } - - InterfaceDispatchCacheHeader* GetCache() const - { - // Capture m_pCache into a local for safe access (this is a volatile read of a value that may be - // modified on another thread while this function is executing.) - TADDR cachePointerValue = m_pCache; - if (IsCache(cachePointerValue)) - { - return (InterfaceDispatchCacheHeader*)cachePointerValue; - } - else - { - return nullptr; - } + LIMITED_METHOD_CONTRACT; + m_token = DispatchToken::ToCachedInterfaceDispatchToken(token); } }; +#ifndef DACCESS_COMPILE +// Decodes the method called through a dispatch cell in a ReadyToRun image from the import signature of the cell. +// Returns false if the method is not a vtable method in the version of the code we are running against, in which +// case *ppNonVirtualMD is set instead of *pToken. +bool DecodeReadyToRunDispatchCell(TADDR pCell, DispatchToken * pToken, MethodDesc ** ppNonVirtualMD); +#endif // !DACCESS_COMPILE + #endif // FEATURE_CACHED_INTERFACE_DISPATCH -#endif // __CACHEDINTERFACEDISPATCHPAL_H__ \ No newline at end of file +#endif // __CACHEDINTERFACEDISPATCHPAL_H__ diff --git a/src/coreclr/vm/CachedInterfaceDispatch_Coreclr.cpp b/src/coreclr/vm/CachedInterfaceDispatch_Coreclr.cpp deleted file mode 100644 index 66a359ffbd3b63..00000000000000 --- a/src/coreclr/vm/CachedInterfaceDispatch_Coreclr.cpp +++ /dev/null @@ -1,22 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -#include "common.h" - -bool InterfaceDispatch_InitializePal() -{ - return true; -} - -// Allocate memory aligned at sizeof(void*)*2 boundaries -void *InterfaceDispatch_AllocDoublePointerAligned(size_t size) -{ - return (void*)SystemDomain::GetGlobalLoaderAllocator()->GetHighFrequencyHeap()->AllocAlignedMem(size, sizeof(TADDR) * 2); -} - -// Allocate memory aligned at sizeof(void*) boundaries - -void *InterfaceDispatch_AllocPointerAligned(size_t size) -{ - return (void*)SystemDomain::GetGlobalLoaderAllocator()->GetHighFrequencyHeap()->AllocAlignedMem(size, sizeof(TADDR)); -} diff --git a/src/coreclr/vm/amd64/CachedInterfaceDispatchCoreCLR.S b/src/coreclr/vm/amd64/CachedInterfaceDispatchCoreCLR.S index 9fb7aacd7fb6c5..e173fb9ca48fd0 100644 --- a/src/coreclr/vm/amd64/CachedInterfaceDispatchCoreCLR.S +++ b/src/coreclr/vm/amd64/CachedInterfaceDispatchCoreCLR.S @@ -7,57 +7,6 @@ #ifdef FEATURE_CACHED_INTERFACE_DISPATCH -// Stub dispatch routine for dispatch to a vtable slot -LEAF_ENTRY RhpVTableOffsetDispatch, _TEXT - - // r11 currently contains the indirection cell address. - // Save it in r10 before overwriting, in case we need to re-dispatch on a race. - mov r10, r11 - // load r11 to point to the vtable offset (which is stored in the m_pCache field). - mov r11, [r11 + OFFSETOF__InterfaceDispatchCell__m_pCache] - - // Validate m_pCache has the vtable offset tag (low 2 bits == 0x2). - // A stale m_pCache from a race will have different low bits. - mov eax, r11d - and eax, IDC_CACHE_POINTER_MASK - cmp eax, 2 - jne LOCAL_LABEL(RhpVTableOffsetRaceRetry) - - // r11 now contains the VTableOffset where the upper 32 bits are the offset to adjust - // to get to the VTable chunk - mov rax, r11 - shr rax, 32 - - // Load the MethodTable from the object instance in rdi, and add it to the vtable offset - // to get the address in the vtable chunk list of what we want to dereference -#ifdef TARGET_APPLE -// Apple's linker has issues which break unwind info if -// an ALTERNATE_ENTRY is present in the middle of a function see https://github.com/dotnet/runtime/issues/119005 -.cfi_endproc -#endif - ALTERNATE_ENTRY RhpVTableOffsetDispatchAVLocation -#ifdef TARGET_APPLE -.cfi_startproc -#endif - add rax, [rdi] - - // Load the target address of the vtable chunk into rax - mov rax, [rax] - - // Compute the chunk offset - shr r11d, 16 - - // Load the target address of the virtual function into rax - mov rax, [rax + r11] - - TAILJMP_RAX - -LOCAL_LABEL(RhpVTableOffsetRaceRetry): - // Restore cell address and re-dispatch through the indirection cell - mov r11, r10 - jmp [r11] -LEAF_END RhpVTableOffsetDispatch, _TEXT - // On Input: // r11 contains the address of the indirection cell // [rsp+0] m_ReturnAddress: contains the return address of caller to stub diff --git a/src/coreclr/vm/amd64/CachedInterfaceDispatchCoreCLR.asm b/src/coreclr/vm/amd64/CachedInterfaceDispatchCoreCLR.asm index 50e267fea9bbdc..c93ab5a424229f 100644 --- a/src/coreclr/vm/amd64/CachedInterfaceDispatchCoreCLR.asm +++ b/src/coreclr/vm/amd64/CachedInterfaceDispatchCoreCLR.asm @@ -9,48 +9,6 @@ ifdef FEATURE_CACHED_INTERFACE_DISPATCH extern CID_ResolveWorker:proc extern CID_VirtualOpenDelegateDispatchWorker:proc -;; Stub dispatch routine for dispatch to a vtable slot -LEAF_ENTRY RhpVTableOffsetDispatch, _TEXT - ;; r11 currently contains the indirection cell address. - ;; Save it in r10 before overwriting, in case we need to re-dispatch on a race. - mov r10, r11 - ;; load r11 to point to the vtable offset (which is stored in the m_pCache field). - mov r11, [r11 + OFFSETOF__InterfaceDispatchCell__m_pCache] - - ;; Validate m_pCache has the vtable offset tag (low 2 bits == 0x2). - ;; A stale m_pCache from a race will have different low bits. - mov eax, r11d - and eax, IDC_CACHE_POINTER_MASK - cmp eax, 2 - jne RhpVTableOffsetRaceRetry - - ;; r11 now contains the VTableOffset where the upper 32 bits are the offset to adjust - ;; to get to the VTable chunk - mov rax, r11 - shr rax, 32 - - ;; Load the MethodTable from the object instance in rcx, and add it to the vtable offset - ;; to get the address in the vtable chunk list of what we want to dereference -ALTERNATE_ENTRY RhpVTableOffsetDispatchAVLocation - add rax, [rcx] - - ;; Load the target address of the vtable chunk into rax - mov rax, [rax] - - ;; Compute the chunk offset - shr r11d, 16 - - ;; Load the target address of the virtual function into rax - mov rax, [rax + r11] - - TAILJMP_RAX - -RhpVTableOffsetRaceRetry: - ;; Restore cell address and re-dispatch through the indirection cell - mov r11, r10 - jmp qword ptr [r11] -LEAF_END RhpVTableOffsetDispatch, _TEXT - ;; On Input: ;; r11 contains the address of the indirection cell ;; [rsp+0] m_ReturnAddress: contains the return address of caller to stub diff --git a/src/coreclr/vm/amd64/asmconstants.h b/src/coreclr/vm/amd64/asmconstants.h index 2614442b3a8588..82b7f0e0d1f912 100644 --- a/src/coreclr/vm/amd64/asmconstants.h +++ b/src/coreclr/vm/amd64/asmconstants.h @@ -501,17 +501,15 @@ ASMCONSTANTS_C_ASSERT(CallCountingStubData__TargetForThresholdReached == offseto #endif // FEATURE_TIERED_COMPILATION #ifdef FEATURE_CACHED_INTERFACE_DISPATCH -#define OFFSETOF__InterfaceDispatchCache__m_rgEntries 0x20 -ASMCONSTANTS_C_ASSERT(OFFSETOF__InterfaceDispatchCache__m_rgEntries == offsetof(InterfaceDispatchCache, m_rgEntries)) - -#define OFFSETOF__InterfaceDispatchCache__m_cEntries 0x18 -ASMCONSTANTS_C_ASSERT(OFFSETOF__InterfaceDispatchCache__m_cEntries == offsetof(InterfaceDispatchCache, m_cEntries)) - -#define OFFSETOF__InterfaceDispatchCell__m_pCache 0x08 -ASMCONSTANTS_C_ASSERT(OFFSETOF__InterfaceDispatchCell__m_pCache == offsetof(InterfaceDispatchCell, m_pCache)) - -#define IDC_CACHE_POINTER_MASK 0x3 -ASMCONSTANTS_C_ASSERT(IDC_CACHE_POINTER_MASK == ::IDC_CachePointerMask) +// RhpInterfaceDispatch hardcodes the layout of the dispatch cell and of the dispatch cache +ASMCONSTANTS_C_ASSERT(offsetof(InterfaceDispatchCell, m_pMethodTable) == 0x00) +ASMCONSTANTS_C_ASSERT(offsetof(InterfaceDispatchCell, m_pCode) == 0x08) +ASMCONSTANTS_C_ASSERT(offsetof(DispatchCacheTable, m_length) == 0x08) +ASMCONSTANTS_C_ASSERT(offsetof(DispatchCacheTable, m_entries) == 0x10) +ASMCONSTANTS_C_ASSERT(sizeof(DispatchCacheEntry) == 0x20) +ASMCONSTANTS_C_ASSERT(offsetof(DispatchCacheEntry, m_pCell) == 0x08) +ASMCONSTANTS_C_ASSERT(offsetof(DispatchCacheEntry, m_pInstanceType) == 0x10) +ASMCONSTANTS_C_ASSERT(offsetof(DispatchCacheEntry, m_pTargetCode) == 0x18) #endif // FEATURE_CACHED_INTERFACE_DISPATCH #define OFFSETOF__ThreadLocalInfo__m_pThread 0 diff --git a/src/coreclr/vm/arm64/CachedInterfaceDispatchCoreCLR.S b/src/coreclr/vm/arm64/CachedInterfaceDispatchCoreCLR.S index a7f341af392e57..c53ea9f9e9d7f0 100644 --- a/src/coreclr/vm/arm64/CachedInterfaceDispatchCoreCLR.S +++ b/src/coreclr/vm/arm64/CachedInterfaceDispatchCoreCLR.S @@ -6,58 +6,6 @@ #ifdef FEATURE_CACHED_INTERFACE_DISPATCH - // Workaround for Xcode 15 ld-classic linker which cannot deal with - // .alt_entry labels at beginning of section. - nop - -// -// Stub dispatch routine for dispatch to a vtable slot -// - LEAF_ENTRY RhpVTableOffsetDispatch, _TEXT - - // Load the MethodTable from the object instance in x0 - ALTERNATE_ENTRY RhpVTableOffsetDispatchAVLocation - ldr x9, [x0] - - // x11 currently contains the indirection cell address. - // Save it in x12 before overwriting, in case we need to re-dispatch on a race. - mov x12, x11 - - // load x11 to point to the vtable offset (which is stored in the m_pCache field). - ldr x11, [x11, #OFFSETOF__InterfaceDispatchCell__m_pCache] - - // Validate m_pCache has the vtable offset tag (low 2 bits == 0x2). - // A stale m_pCache from a race will have different low bits. - and w10, w11, #IDC_CACHE_POINTER_MASK - cmp w10, #2 - bne LOCAL_LABEL(RhpVTableOffsetRaceRetry) - - // x11 now contains the VTableOffset where the upper 32 bits are the offset to adjust - // to get to the VTable chunk - lsr x10, x11, #32 - - // Add the MethodTable to the vtable offset - // to get the address in the vtable chunk list of what we want to dereference - add x9, x10, x9 - - // Load the target address of the vtable chunk into x9 - ldr x9, [x9] - - // Compute the chunk offset - ubfx x10, x11, #16, #16 - - // Load the target address of the virtual function into x9 - ldr x9, [x9, x10] - - EPILOG_BRANCH_REG x9 - -LOCAL_LABEL(RhpVTableOffsetRaceRetry): - // Re-dispatch through the indirection cell - mov x11, x12 - ldr x9, [x11] - br x9 - LEAF_END RhpVTableOffsetDispatch, _TEXT - // // Cache miss case, call the runtime to resolve the target and update the cache. // x11 contains the interface dispatch cell address. diff --git a/src/coreclr/vm/arm64/CachedInterfaceDispatchCoreCLR.asm b/src/coreclr/vm/arm64/CachedInterfaceDispatchCoreCLR.asm index e66bf425dfd567..ed4387958cec8c 100644 --- a/src/coreclr/vm/arm64/CachedInterfaceDispatchCoreCLR.asm +++ b/src/coreclr/vm/arm64/CachedInterfaceDispatchCoreCLR.asm @@ -12,51 +12,6 @@ EXTERN CID_ResolveWorker EXTERN CID_VirtualOpenDelegateDispatchWorker -;; -;; Stub dispatch routine for dispatch to a vtable slot -;; - LEAF_ENTRY RhpVTableOffsetDispatch - - ;; x11 currently contains the indirection cell address. - ;; Save it in x12 before overwriting, in case we need to re-dispatch on a race. - mov x12, x11 - ;; load x11 to point to the vtable offset (which is stored in the m_pCache field). - ldr x11, [x11, #OFFSETOF__InterfaceDispatchCell__m_pCache] - - ;; Validate m_pCache has the vtable offset tag (low 2 bits == 0x2). - ;; A stale m_pCache from a race will have different low bits. - and w10, w11, #IDC_CACHE_POINTER_MASK - cmp w10, #2 - bne RhpVTableOffsetRaceRetry - - ;; x11 now contains the VTableOffset where the upper 32 bits are the offset to adjust - ;; to get to the VTable chunk - lsr x10, x11, #32 - - ;; Load the MethodTable from the object instance in x0, and add it to the vtable offset - ;; to get the address in the vtable chunk list of what we want to dereference - ALTERNATE_ENTRY RhpVTableOffsetDispatchAVLocation - ldr x9, [x0] - add x9, x10, x9 - - ;; Load the target address of the vtable chunk into x9 - ldr x9, [x9] - - ;; Compute the chunk offset - ubfx x10, x11, #16, #16 - - ;; Load the target address of the virtual function into x9 - ldr x9, [x9, x10] - - EPILOG_BRANCH_REG x9 - -RhpVTableOffsetRaceRetry - ;; Restore cell address and re-dispatch through the indirection cell - mov x11, x12 - ldr x9, [x11] - br x9 - LEAF_END RhpVTableOffsetDispatch - ;; ;; Cache miss case, call the runtime to resolve the target and update the cache. ;; x11 contains the interface dispatch cell address. diff --git a/src/coreclr/vm/arm64/asmconstants.h b/src/coreclr/vm/arm64/asmconstants.h index 058fb75a755a71..6e86d5414f8cae 100644 --- a/src/coreclr/vm/arm64/asmconstants.h +++ b/src/coreclr/vm/arm64/asmconstants.h @@ -249,17 +249,15 @@ ASMCONSTANTS_C_ASSERT(CallCountingStubData__TargetForThresholdReached == offseto #endif // FEATURE_TIERED_COMPILATION #ifdef FEATURE_CACHED_INTERFACE_DISPATCH -#define OFFSETOF__InterfaceDispatchCache__m_rgEntries 0x20 -ASMCONSTANTS_C_ASSERT(OFFSETOF__InterfaceDispatchCache__m_rgEntries == offsetof(InterfaceDispatchCache, m_rgEntries)) - -#define OFFSETOF__InterfaceDispatchCache__m_cEntries 0x18 -ASMCONSTANTS_C_ASSERT(OFFSETOF__InterfaceDispatchCache__m_cEntries == offsetof(InterfaceDispatchCache, m_cEntries)) - -#define OFFSETOF__InterfaceDispatchCell__m_pCache 0x08 -ASMCONSTANTS_C_ASSERT(OFFSETOF__InterfaceDispatchCell__m_pCache == offsetof(InterfaceDispatchCell, m_pCache)) - -#define IDC_CACHE_POINTER_MASK 0x3 -ASMCONSTANTS_C_ASSERT(IDC_CACHE_POINTER_MASK == ::IDC_CachePointerMask) +// RhpInterfaceDispatch hardcodes the layout of the dispatch cell and of the dispatch cache +ASMCONSTANTS_C_ASSERT(offsetof(InterfaceDispatchCell, m_pMethodTable) == 0x00) +ASMCONSTANTS_C_ASSERT(offsetof(InterfaceDispatchCell, m_pCode) == 0x08) +ASMCONSTANTS_C_ASSERT(offsetof(DispatchCacheTable, m_length) == 0x08) +ASMCONSTANTS_C_ASSERT(offsetof(DispatchCacheTable, m_entries) == 0x10) +ASMCONSTANTS_C_ASSERT(sizeof(DispatchCacheEntry) == 0x20) +ASMCONSTANTS_C_ASSERT(offsetof(DispatchCacheEntry, m_pCell) == 0x08) +ASMCONSTANTS_C_ASSERT(offsetof(DispatchCacheEntry, m_pInstanceType) == 0x10) +ASMCONSTANTS_C_ASSERT(offsetof(DispatchCacheEntry, m_pTargetCode) == 0x18) #endif // FEATURE_CACHED_INTERFACE_DISPATCH #define OFFSETOF__ThreadLocalInfo__m_pThread 0 diff --git a/src/coreclr/vm/contractimpl.h b/src/coreclr/vm/contractimpl.h index 2a253bc9fdcc0d..602784b2ae85b2 100644 --- a/src/coreclr/vm/contractimpl.h +++ b/src/coreclr/vm/contractimpl.h @@ -274,11 +274,7 @@ struct DispatchToken #ifdef FEATURE_CACHED_INTERFACE_DISPATCH //------------------------------------------------------------------------ - // A Cached Interface DispatchToken uses the low bit to indicate that it is a dispatch token, and not a cache entry - static inline BOOL IsCachedInterfaceDispatchToken(UINT_PTR maybeToken) - { - return maybeToken & 0x1; - } + // A Cached Interface DispatchToken sets the low bit so that a valid token is never zero static inline DispatchToken FromCachedInterfaceDispatchToken(UINT_PTR token) { return DispatchToken(token >> 1); diff --git a/src/coreclr/vm/dynamicmethod.cpp b/src/coreclr/vm/dynamicmethod.cpp index eb0ba79e3ad221..32887ac51547bd 100644 --- a/src/coreclr/vm/dynamicmethod.cpp +++ b/src/coreclr/vm/dynamicmethod.cpp @@ -942,19 +942,6 @@ void LCGMethodResolver::RecycleIndCells() cellcurr = list->indcell; _ASSERTE(cellcurr != NULL); -#if defined (FEATURE_CACHED_INTERFACE_DISPATCH) - // Cached dispatch dispatch uses dynamically allocated caches that need to be freed individually - if (UseCachedInterfaceDispatch()) - { - InterfaceDispatchCell *pDispatchCell = (InterfaceDispatchCell*)cellcurr; - InterfaceDispatchCacheHeader* cellCacheHeader = pDispatchCell->GetCache(); - if (cellCacheHeader != NULL) - { - InterfaceDispatch_DiscardCacheHeader(cellCacheHeader); - pDispatchCell->m_pCache = 0; - } - } -#endif if (cellprev) *((BYTE**)cellprev) = cellcurr; @@ -962,6 +949,15 @@ void LCGMethodResolver::RecycleIndCells() cellprev = cellcurr; } +#if defined (FEATURE_CACHED_INTERFACE_DISPATCH) + // The global dispatch cache is keyed by the cell address, so it must not return + // targets cached for the previous user of a recycled cell. + if (UseCachedInterfaceDispatch()) + { + InterfaceDispatch_FlushDispatchCache(); + } +#endif + // Insert the linked list to the free list of the VirtualCallStubManager of the current domain. // We should use GetLoaderAllocator because that is where the ind cell was allocated. LoaderAllocator *pLoaderAllocator = GetDynamicMethod()->GetLoaderAllocator(); diff --git a/src/coreclr/vm/jitinterface.cpp b/src/coreclr/vm/jitinterface.cpp index 458084d10a0550..ddc5aee271ae97 100644 --- a/src/coreclr/vm/jitinterface.cpp +++ b/src/coreclr/vm/jitinterface.cpp @@ -11,6 +11,7 @@ #include "field.h" #include "stublink.h" #include "virtualcallstub.h" +#include "CachedInterfaceDispatchPal.h" #include "corjit.h" #include "eeconfig.h" #include "excep.h" @@ -10787,6 +10788,14 @@ static CORJIT_FLAGS GetCompileFlags(PrepareCodeConfig* prepareConfig, MethodDesc flags.Set(CORJIT_FLAGS::CORJIT_FLAG_FROZEN_ALLOC_ALLOWED); } +#ifdef FEATURE_CACHED_INTERFACE_DISPATCH + // Interface call sites pass the dispatch cell to RhpInterfaceDispatch instead of calling through it + if (UseCachedInterfaceDispatch()) + { + flags.Set(CORJIT_FLAGS::CORJIT_FLAG_USE_DISPATCH_HELPERS); + } +#endif + // Set optimization flags if (!flags.IsSet(CORJIT_FLAGS::CORJIT_FLAG_MIN_OPT)) { @@ -14311,6 +14320,18 @@ BOOL LoadDynamicInfoEntry(Module *currentModule, return FALSE; #endif + case READYTORUN_HELPER_InterfaceDispatch: + // Code using this helper expects the dispatch cells laid out for cached interface dispatch +#if defined(FEATURE_CACHED_INTERFACE_DISPATCH) && !defined(TARGET_WASM) + if (UseCachedInterfaceDispatch()) + { + result = (size_t)GetEEFuncEntryPoint(RhpInterfaceDispatch); + break; + } +#endif + STRESS_LOG1(LF_ZAP, LL_WARNING, "READYTORUN_HELPER_InterfaceDispatch requires cached interface dispatch: %d\n", helperNum); + return FALSE; + default: STRESS_LOG1(LF_ZAP, LL_WARNING, "Unknown READYTORUN_HELPER %d\n", helperNum); _ASSERTE(!"Unknown READYTORUN_HELPER"); diff --git a/src/coreclr/vm/prestub.cpp b/src/coreclr/vm/prestub.cpp index 3575ab5d6ebc98..1b479c42126885 100644 --- a/src/coreclr/vm/prestub.cpp +++ b/src/coreclr/vm/prestub.cpp @@ -2941,6 +2941,105 @@ static void PatchExternalMethodWithVirtualDispatchPortableEntryPoint(MethodDesc } #endif // FEATURE_PORTABLE_ENTRYPOINTS +#ifdef FEATURE_CACHED_INTERFACE_DISPATCH +bool DecodeReadyToRunDispatchCell(TADDR pCell, DispatchToken * pToken, MethodDesc ** ppNonVirtualMD) +{ + CONTRACTL + { + THROWS; + GC_TRIGGERS; + MODE_ANY; + } + CONTRACTL_END; + + Module * pModule = ExecutionManager::FindReadyToRunModule(pCell); + _ASSERTE(pModule != NULL); + + GCX_PREEMP(); + + ReadyToRunLoadedImage *pNativeImage = pModule->GetReadyToRunImage(); + + RVA rva = pNativeImage->GetDataRva(pCell); + + PTR_READYTORUN_IMPORT_SECTION pImportSection = pModule->GetImportSectionForRVA(rva); + _ASSERTE(pImportSection != NULL); + _ASSERTE(pImportSection->EntrySize == sizeof(InterfaceDispatchCell)); + + COUNT_T index = (rva - pImportSection->Section.VirtualAddress) / pImportSection->EntrySize; + + PTR_DWORD pSignatures = dac_cast(pNativeImage->GetRvaData(pImportSection->Signatures)); + + PTR_BYTE pGCRefMap = dac_cast(pNativeImage->GetRvaData(pSignatures[index])); + PCCOR_SIGNATURE pBlob = pGCRefMap; + if ((pImportSection->Flags & ReadyToRunImportSectionFlags::GCRefMap) != ReadyToRunImportSectionFlags::None) + { + pBlob = GCRefMapDecoder::Skip(pBlob); + } + else + { + pGCRefMap = nullptr; + } + + BYTE kind = *pBlob++; + + ModuleBase * pInfoModule = pModule; + if (kind & READYTORUN_FIXUP_ModuleOverride) + { + DWORD moduleIndex = CorSigUncompressData(pBlob); + pInfoModule = pModule->GetModuleFromIndex(moduleIndex); + kind &= ~READYTORUN_FIXUP_ModuleOverride; + } + + MethodDesc * pMD = NULL; + TypeHandle th; + switch (kind) + { + case READYTORUN_FIXUP_VirtualEntry: + pMD = ZapSig::DecodeMethod(pModule, pInfoModule, pBlob, &th); + break; + + case READYTORUN_FIXUP_VirtualEntry_DefToken: + { + mdToken MethodDef = TokenFromRid(CorSigUncompressData(pBlob), mdtMethodDef); + _ASSERTE(pInfoModule->IsFullModule()); + pMD = MemberLoader::GetMethodDescFromMethodDef(static_cast(pInfoModule), MethodDef, FALSE); + break; + } + + case READYTORUN_FIXUP_VirtualEntry_RefToken: + { + mdToken MemberRef = TokenFromRid(CorSigUncompressData(pBlob), mdtMemberRef); + + FieldDesc * pFD = NULL; + + SigTypeContext typeContext; + MemberLoader::GetDescFromMemberRef(pInfoModule, MemberRef, &pMD, &pFD, &typeContext, FALSE /* strict metadata checks */, &th, TRUE /* actual type required */); + _ASSERTE(pMD != NULL); + break; + } + + default: + _ASSERTE(!"Unexpected ReadyToRunFixupKind"); + ThrowHR(COR_E_BADIMAGEFORMAT); + } + + pMD->PrepareForUseAsAVirtualCallTargetOfANativeImage(pGCRefMap); + + // Activate the target explicitly. + pMD->EnsureActive(); + + if (!pMD->IsVtableMethod()) + { + *ppNonVirtualMD = pMD; + return false; + } + + MethodTable * pMT = th.IsNull() ? pMD->GetMethodTable() : th.GetMethodTable(); + *pToken = VirtualCallStubManager::GetTokenFromOwnerAndSlot(pMT, pMD->GetSlot()); + return true; +} +#endif // FEATURE_CACHED_INTERFACE_DISPATCH + //========================================================================================== // In NGen images calls to external methods start out pointing to jump thunks. // These jump thunks initially point to the assembly code _ExternalMethodFixupStub @@ -3184,39 +3283,9 @@ EXTERN_C PCODE STDCALL ExternalMethodFixupWorker( #endif #if defined(FEATURE_CACHED_INTERFACE_DISPATCH) { -#ifndef TARGET_WASM - if (ALIGN_UP(rva, sizeof(TADDR) * 2) == rva && pImportSection->EntrySize == sizeof(TADDR) * 2) - { - // The entry is aligned and the size is correct, so we can use the cached interface dispatch mechanism - // to speed up further uses of this interface dispatch slot - DispatchToken token = VirtualCallStubManager::GetTokenFromOwnerAndSlot(pMT, slot); - - uintptr_t addr = (uintptr_t)RhpInitialInterfaceDispatch; - uintptr_t pCache = (uintptr_t)DispatchToken::ToCachedInterfaceDispatchToken(token); -#ifdef TARGET_64BIT - int64_t rgComparand[2] = { *(volatile int64_t*)pIndirection , *(((volatile int64_t*)pIndirection) + 1) }; - // We need to only update if the indirection cell is still pointing to the initial R2R stub - // But we don't have the address of the initial R2R stub, as that is part of the R2R image - // However, we can rely on the detail that the cache value will never be 0 once it is updated - // So we read the indirection cell data, and if the cache portion is 0, we attempt to update the complete cell - if (rgComparand[1] == 0 && PalInterlockedCompareExchange128((int64_t*)pIndirection, rgComparand[1], rgComparand[0], rgComparand) && rgComparand[1] == 0) - { - PalInterlockedCompareExchange128((int64_t*)pIndirection, pCache, addr, rgComparand); - } -#else - // Stuff the two pointers into a 64-bit value as the proposed new value for the CompareExchange64 below. - uint64_t oldValue = *(volatile uint64_t*)pIndirection; - if ((oldValue >> 32) == 0) - { - // The cache portion is 0, so we attempt to update the complete cell - int64_t iNewValue = (int64_t)((uint64_t)(uintptr_t)addr | ((uint64_t)(uintptr_t)pCache << 32)); - PalInterlockedCompareExchange64((int64_t*)pIndirection, iNewValue, oldValue); - } -#endif - } -#endif // !TARGET_WASM - - // We lost the race or the R2R image was generated without cached interface dispatch support, simply do the resolution in pure C++ + // Images compiled with cached interface dispatch support call RhpInterfaceDispatch instead of + // calling through the cell, so this is a cell of an image compiled without it. The cell is left + // pointing to the delay load thunk, simply do the resolution in pure C++. MethodTable* objectType; { GCX_COOP_THREAD_EXISTS(CURRENT_THREAD); diff --git a/src/coreclr/vm/virtualcallstub.cpp b/src/coreclr/vm/virtualcallstub.cpp index c8ac4a06b11a0c..8abdd26f339a5c 100644 --- a/src/coreclr/vm/virtualcallstub.cpp +++ b/src/coreclr/vm/virtualcallstub.cpp @@ -86,15 +86,6 @@ EXTERN_C size_t g_dispatch_cache_chain_success_counter; SPTR_IMPL_INIT(VirtualCallStubManagerManager, VirtualCallStubManagerManager, g_pManager, NULL); -#ifdef FEATURE_CACHED_INTERFACE_DISPATCH -struct CachedIndirectionCellBlockListNode -{ - CachedIndirectionCellBlockListNode *m_pNext; - TADDR m_pFiller; // Used to ensure that the Indirection Cells are double pointer aligned - InterfaceDispatchCell m_rgIndCells[0]; -}; -#endif // FEATURE_CACHED_INTERFACE_DISPATCH - #ifndef DACCESS_COMPILE BYTE* GenerateDispatchStubCellEntryMethodDesc(LoaderAllocator *pLoaderAllocator, TypeHandle ownerType, MethodDesc *pMD, LCGMethodResolver *pResolver) @@ -123,7 +114,7 @@ BYTE* GenerateDispatchStubCellEntrySlot(LoaderAllocator *pLoaderAllocator, TypeH PCODE addr; INTERFACE_DISPATCH_CACHED_OR_VSD( - addr = (PCODE)RhpInitialInterfaceDispatch // Always use the initial dispatch stub for cached interface dispatch + addr = (PCODE)RhpInterfaceDispatch // Call sites call the dispatch helper, not the cell, for cached interface dispatch , addr = pMgr->GetCallStub(token)) // Acquire a stub which is token specific in the VSD case @@ -714,26 +705,6 @@ VirtualCallStubManager::~VirtualCallStubManager() // freeing their memory takes CrstExecutableAllocatorLock, which is at the same lock level. #endif // FEATURE_VIRTUAL_STUB_DISPATCH -#ifdef FEATURE_CACHED_INTERFACE_DISPATCH - if (m_loaderAllocator->IsCollectible() && UseCachedInterfaceDispatch()) - { - CachedIndirectionCellBlockListNode * pBlockNode = m_indirectionBlocks; - while (pBlockNode != NULL) - { - for (UINT32 i = 0; i < INDCELLS_PER_BLOCK; i++) - { - InterfaceDispatchCacheHeader* cache = pBlockNode->m_rgIndCells[i].GetCache(); - if (cache != NULL) - { - InterfaceDispatch_DiscardCacheHeader(cache); - } - } - - pBlockNode = pBlockNode->m_pNext; - } - } -#endif - if (indcell_heap) { delete indcell_heap; indcell_heap = NULL;} #ifdef FEATURE_VIRTUAL_STUB_DISPATCH if (lookup_heap) { delete lookup_heap; lookup_heap = NULL;} @@ -772,8 +743,14 @@ void VirtualCallStubManager::InitStatic() STANDARD_VM_CONTRACT; #ifdef FEATURE_CACHED_INTERFACE_DISPATCH - InterfaceDispatch_Initialize(); -#endif + if (!InterfaceDispatch_Initialize()) + COMPlusThrowOM(); + +#ifndef TARGET_WASM + if (UseCachedInterfaceDispatch()) + SetJitHelperFunction(CORINFO_HELP_INTERFACEDISPATCH_FOR_SLOT, RhpInterfaceDispatch); +#endif // !TARGET_WASM +#endif // FEATURE_CACHED_INTERFACE_DISPATCH #ifdef STUB_LOGGING // Note if you change these values using environment variables then you must use hex values :-( @@ -978,7 +955,22 @@ BOOL VirtualCallStubManager::TraceManager(Thread *thread, *pRetAddr = (BYTE *)StubManagerHelpers::GetReturnAddress(pContext); // Get the token from the stub - DispatchToken token(GetTokenFromStub(pStub, pContext)); + DispatchToken token; +#if defined(FEATURE_CACHED_INTERFACE_DISPATCH) && !defined(DACCESS_COMPILE) + InterfaceDispatchCell * pCell = isCachedInterfaceDispatchStub(pStub) ? + (InterfaceDispatchCell *)StubManagerHelpers::GetIndirectionCellArg(pContext) : NULL; + if (pCell != NULL && !pCell->HasToken()) + { + // The call site has a ReadyToRun dispatch cell that wasn't dispatched through yet. + MethodDesc * pNonVirtualMD = NULL; + if (!DecodeReadyToRunDispatchCell((TADDR)pCell, &token, &pNonVirtualMD)) + return FALSE; + } + else +#endif + { + token = DispatchToken(GetTokenFromStub(pStub, pContext)); + } // Get the this object from ECX Object *pObj = StubManagerHelpers::GetThisPtr(pContext); @@ -1192,30 +1184,8 @@ BYTE *VirtualCallStubManager::GenerateStubIndirection(PCODE target, DispatchToke // Allocate from loader heap if (!ret) { - size_t alignment; - INTERFACE_DISPATCH_CACHED_OR_VSD(alignment = sizeof(TADDR) * 2, alignment = sizeof(TADDR)); - // Free list is empty, allocate a block of indcells from indcell_heap and insert it into the free list. - size_t cellsAllocationSize = cellsPerBlock * sizeOfIndCell; - size_t allocationSize = cellsAllocationSize; - -#ifdef FEATURE_CACHED_INTERFACE_DISPATCH - if (m_loaderAllocator->IsCollectible() && UseCachedInterfaceDispatch()) - { - allocationSize += sizeof(CachedIndirectionCellBlockListNode); - } -#endif // FEATURE_CACHED_INTERFACE_DISPATCH - BYTE ** pBlock = (BYTE **) (void *) indcell_heap->AllocAlignedMem(allocationSize, alignment); - -#ifdef FEATURE_CACHED_INTERFACE_DISPATCH - if (m_loaderAllocator->IsCollectible() && UseCachedInterfaceDispatch()) - { - CachedIndirectionCellBlockListNode * pBlockNode = (CachedIndirectionCellBlockListNode *)pBlock; - pBlockNode->m_pNext = m_indirectionBlocks; - m_indirectionBlocks = pBlockNode; - pBlock = (BYTE **)(&pBlockNode->m_rgIndCells[0]); - } -#endif // FEATURE_CACHED_INTERFACE_DISPATCH + BYTE ** pBlock = (BYTE **) (void *) indcell_heap->AllocAlignedMem(cellsPerBlock * sizeOfIndCell, sizeof(TADDR)); // return the first cell in the block and add the rest to the free list ret = (BYTE *)pBlock; @@ -1232,9 +1202,7 @@ BYTE *VirtualCallStubManager::GenerateStubIndirection(PCODE target, DispatchToke } INTERFACE_DISPATCH_CACHED_OR_VSD( - InterfaceDispatchCell * pCell = (InterfaceDispatchCell *)ret; - pCell->m_pStub = target; - pCell->m_pCache = DispatchToken::ToCachedInterfaceDispatchToken(token); + ((InterfaceDispatchCell *)ret)->Initialize(token); , *((PCODE *)ret) = target; ) @@ -1294,17 +1262,9 @@ size_t VirtualCallStubManager::GetTokenFromStub(PCODE stub, T_CONTEXT *pContext) #ifdef FEATURE_CACHED_INTERFACE_DISPATCH if (isCachedInterfaceDispatchStub(stub)) { - TADDR indcell = StubManagerHelpers::GetIndirectionCellArg(pContext); - VirtualCallStubManagerIterator it = - VirtualCallStubManagerManager::GlobalManager()->IterateVirtualCallStubManagers(); - while (it.Next()) - { - if (it.Current()->indcell_rangeList.IsInRange(indcell)) - { - InterfaceDispatchCell * pCell = (InterfaceDispatchCell *)indcell; - return pCell->GetDispatchCellInfo().Token.To_SIZE_T(); - } - } + // Cells in ReadyToRun images don't have a token until the first dispatch through them. + InterfaceDispatchCell * pCell = (InterfaceDispatchCell *)StubManagerHelpers::GetIndirectionCellArg(pContext); + return pCell->HasToken() ? pCell->GetToken().To_SIZE_T() : 0; } #endif // FEATURE_CACHED_INTERFACE_DISPATCH @@ -1418,13 +1378,48 @@ PCODE CachedInterfaceDispatchResolveWorker(StubCallSite* pCallSite, OBJECTREF *p if (patch && pCallSite != NULL) { - DispatchCellInfo cellInfo = ((InterfaceDispatchCell*)pCallSite->GetIndirectCell())->GetDispatchCellInfo(); - InterfaceDispatch_UpdateDispatchCellCache((InterfaceDispatchCell*)pCallSite->GetIndirectCell(), target, objectType, &cellInfo); + TADDR pCell = (TADDR)pCallSite->GetIndirectCell(); + LoaderAllocator* pCellLoaderAllocator = VirtualCallStubManager::FindLoaderAllocatorForDispatchCell(pCell); + LoaderAllocator* pTypeLoaderAllocator = objectType->GetLoaderAllocator(); + + // A cell must not cache a type that can be unloaded before the cell itself. + bool fCacheInCell = (pCellLoaderAllocator != NULL) && + (!pTypeLoaderAllocator->IsCollectible() || (pTypeLoaderAllocator == pCellLoaderAllocator)); + + // The global dispatch cache is not flushed when a LoaderAllocator is unloaded. + bool fCacheInTable = (pCellLoaderAllocator != NULL) && + !pCellLoaderAllocator->IsCollectible() && !pTypeLoaderAllocator->IsCollectible(); + + InterfaceDispatch_UpdateDispatchCellCache((InterfaceDispatchCell*)pCell, target, objectType, fCacheInCell, fCacheInTable); } return target; } +LoaderAllocator* VirtualCallStubManager::FindLoaderAllocatorForDispatchCell(TADDR pCell) +{ + CONTRACTL + { + NOTHROW; + GC_NOTRIGGER; + } + CONTRACTL_END; + + VirtualCallStubManagerIterator it = + VirtualCallStubManagerManager::GlobalManager()->IterateVirtualCallStubManagers(); + while (it.Next()) + { + if (it.Current()->indcell_rangeList.IsInRange(pCell)) + return it.Current()->m_loaderAllocator; + } + + Module* pModule = ExecutionManager::FindReadyToRunModule(pCell); + if (pModule != NULL) + return pModule->GetLoaderAllocator(); + + return NULL; +} + // Resolve a dispatch on a virtual open delegate without updating any pointers extern "C" PCODE CID_VirtualOpenDelegateDispatchWorker(TransitionBlock * pTransitionBlock, PCODE* ppMethodPtrAuxField) { @@ -1498,13 +1493,27 @@ extern "C" PCODE CID_VirtualOpenDelegateDispatchWorker(TransitionBlock * pTransi return target; } +static void SetRepresentativeSlotForDispatchToken(StubDispatchFrame * pSDFrame, DispatchToken token, MethodTable * pObjectMT) +{ + WRAPPER_NO_CONTRACT; + + MethodTable * pRepresentativeMT = pObjectMT; + if (token.IsTypedToken()) + { + pRepresentativeMT = AppDomain::GetCurrentDomain()->LookupType(token.GetTypeID()); + CONSISTENCY_CHECK(CheckPointer(pRepresentativeMT)); + } + + pSDFrame->SetRepresentativeSlot(pRepresentativeMT, token.GetSlotNumber()); +} + /* Resolve to a method and return its address or NULL if there is none Our return value is the target address that control should continue to. Our caller will enter the target address as if a direct call with the original stack frame had been made from the actual call site. Hence our strategy is to either return a target address of the actual method implementation, or the prestub if we cannot find the actual implementation. - If we are returning a real method address, we may patch the original cell site to point to different - stub. Note, if we encounter a method that hasn't been jitted + If we are returning a real method address, we may cache it in the dispatch cell or in the global + dispatch cache. Note, if we encounter a method that hasn't been jitted yet, we will return the prestub, which should cause it to be jitted and we will be able to build the dispatching stub on a later call thru the call site. If we encounter any other kind of problem, rather than throwing an exception, we will also return the @@ -1554,15 +1563,17 @@ extern "C" PCODE CID_ResolveWorker(TransitionBlock * pTransitionBlock, pSDFrame->SetCallSite(NULL, (TADDR)callSite.GetIndirectCell()); - DispatchToken representativeToken(indirectionCell->GetDispatchCellInfo().Token); - MethodTable * pRepresentativeMT = pObj->GetMethodTable(); - if (representativeToken.IsTypedToken()) + // Cells in ReadyToRun images get their token on the first dispatch through them. Until then, + // the frame reports the arguments using the GC ref map of the import cell. + bool fHasToken = indirectionCell->HasToken(); + if (fHasToken) { - pRepresentativeMT = AppDomain::GetCurrentDomain()->LookupType(representativeToken.GetTypeID()); - CONSISTENCY_CHECK(CheckPointer(pRepresentativeMT)); + SetRepresentativeSlotForDispatchToken(pSDFrame, indirectionCell->GetToken(), pObj->GetMethodTable()); + } + else + { + _ASSERTE(pSDFrame->GetGCRefMap() != NULL); } - - pSDFrame->SetRepresentativeSlot(pRepresentativeMT, representativeToken.GetSlotNumber()); pSDFrame->Push(CURRENT_THREAD); INSTALL_RESUME_AFTER_CATCH_HANDLER_WITH_FRAME(pSDFrame); @@ -1571,10 +1582,30 @@ extern "C" PCODE CID_ResolveWorker(TransitionBlock * pTransitionBlock, GCStress::MaybeTriggerAndProtect(pObj); - target = CachedInterfaceDispatchResolveWorker(&callSite, protectedObj, representativeToken); + DispatchToken representativeToken; + MethodDesc * pNonVirtualMD = NULL; + if (fHasToken) + { + representativeToken = indirectionCell->GetToken(); + } + else if (DecodeReadyToRunDispatchCell((TADDR)indirectionCell, &representativeToken, &pNonVirtualMD)) + { + indirectionCell->SetToken(representativeToken); + SetRepresentativeSlotForDispatchToken(pSDFrame, representativeToken, (*protectedObj)->GetMethodTable()); + } + + if (pNonVirtualMD != NULL) + { + // The method is no longer virtual in the version of the code we are running against. + target = pNonVirtualMD->GetMultiCallableAddrOfCode(); + } + else + { + target = CachedInterfaceDispatchResolveWorker(&callSite, protectedObj, representativeToken); + } #if _DEBUG - if (pSDFrame->GetGCRefMap() != NULL) + if (pSDFrame->GetGCRefMap() != NULL && pSDFrame->GetFunction() != NULL) { GCX_PREEMP(); _ASSERTE(CheckGCRefMapEqual(pSDFrame->GetGCRefMap(), pSDFrame->GetFunction(), true)); @@ -1786,7 +1817,7 @@ PCODE VSD_ResolveWorkerForInterfaceLookupSlot(TransitionBlock * pTransitionBlock #ifdef FEATURE_CACHED_INTERFACE_DISPATCH if (UseCachedInterfaceDispatch()) { - DispatchToken representativeToken(((InterfaceDispatchCell*)siteAddrForRegisterIndirect)->GetDispatchCellInfo().Token); + DispatchToken representativeToken(((InterfaceDispatchCell*)siteAddrForRegisterIndirect)->GetToken()); target = CachedInterfaceDispatchResolveWorker(&callSite, protectedObj, representativeToken); } else @@ -4155,28 +4186,6 @@ VirtualCallStubManager *VirtualCallStubManagerIterator::Current() #ifndef DACCESS_COMPILE -#ifdef FEATURE_CACHED_INTERFACE_DISPATCH -extern "C" void RhpInterfaceDispatch1(); -extern "C" void RhpInterfaceDispatch2(); -extern "C" void RhpInterfaceDispatch4(); -extern "C" void RhpInterfaceDispatch8(); -extern "C" void RhpInterfaceDispatch16(); -extern "C" void RhpInterfaceDispatch32(); -extern "C" void RhpInterfaceDispatch64(); - -extern "C" void RhpVTableOffsetDispatch(); - -extern "C" void RhpInterfaceDispatchAVLocation1(); -extern "C" void RhpInterfaceDispatchAVLocation2(); -extern "C" void RhpInterfaceDispatchAVLocation4(); -extern "C" void RhpInterfaceDispatchAVLocation8(); -extern "C" void RhpInterfaceDispatchAVLocation16(); -extern "C" void RhpInterfaceDispatchAVLocation32(); -extern "C" void RhpInterfaceDispatchAVLocation64(); -extern "C" void RhpVTableOffsetDispatchAVLocation(); - -#endif // FEATURE_CACHED_INTERFACE_DISPATCH - ///////////////////////////////////////////////////////////////////////////////////////////// VirtualCallStubManagerManager::VirtualCallStubManagerManager() : m_pManagers(NULL), @@ -4186,35 +4195,20 @@ VirtualCallStubManagerManager::VirtualCallStubManagerManager() LIMITED_METHOD_CONTRACT; #ifdef FEATURE_CACHED_INTERFACE_DISPATCH -#define CACHED_INTERFACE_DISPATCH_HELPER_COUNT 9 +#define CACHED_INTERFACE_DISPATCH_HELPER_COUNT 1 size_t helperCount = 0; #define RECORD_CACHED_INTERFACE_DISPATCH_HELPER(helper) _ASSERTE(helperCount < CACHED_INTERFACE_DISPATCH_HELPER_COUNT); pCachedInterfaceDispatchHelpers[helperCount++] = (PCODE)helper; #define RECORD_CACHED_INTERFACE_DISPATCH_HELPER_AVLOCATION(helper) _ASSERTE(helperCount < CACHED_INTERFACE_DISPATCH_HELPER_COUNT); pCachedInterfaceDispatchHelpersAVLocation[helperCount++] = (PCODE)helper; pCachedInterfaceDispatchHelpers = new PCODE[CACHED_INTERFACE_DISPATCH_HELPER_COUNT]; - RECORD_CACHED_INTERFACE_DISPATCH_HELPER(RhpInterfaceDispatch1); - RECORD_CACHED_INTERFACE_DISPATCH_HELPER(RhpInterfaceDispatch2); - RECORD_CACHED_INTERFACE_DISPATCH_HELPER(RhpInterfaceDispatch4); - RECORD_CACHED_INTERFACE_DISPATCH_HELPER(RhpInterfaceDispatch8); - RECORD_CACHED_INTERFACE_DISPATCH_HELPER(RhpInterfaceDispatch16); - RECORD_CACHED_INTERFACE_DISPATCH_HELPER(RhpInterfaceDispatch32); - RECORD_CACHED_INTERFACE_DISPATCH_HELPER(RhpInterfaceDispatch64); - RECORD_CACHED_INTERFACE_DISPATCH_HELPER(RhpVTableOffsetDispatch); - RECORD_CACHED_INTERFACE_DISPATCH_HELPER(RhpInitialInterfaceDispatch); + RECORD_CACHED_INTERFACE_DISPATCH_HELPER(RhpInterfaceDispatch); _ASSERTE(helperCount == CACHED_INTERFACE_DISPATCH_HELPER_COUNT); + // RhpInterfaceDispatch loads the MethodTable of 'this' in its first instruction helperCount = 0; pCachedInterfaceDispatchHelpersAVLocation = new PCODE[CACHED_INTERFACE_DISPATCH_HELPER_COUNT]; - RECORD_CACHED_INTERFACE_DISPATCH_HELPER_AVLOCATION(RhpInterfaceDispatchAVLocation1); - RECORD_CACHED_INTERFACE_DISPATCH_HELPER_AVLOCATION(RhpInterfaceDispatchAVLocation2); - RECORD_CACHED_INTERFACE_DISPATCH_HELPER_AVLOCATION(RhpInterfaceDispatchAVLocation4); - RECORD_CACHED_INTERFACE_DISPATCH_HELPER_AVLOCATION(RhpInterfaceDispatchAVLocation8); - RECORD_CACHED_INTERFACE_DISPATCH_HELPER_AVLOCATION(RhpInterfaceDispatchAVLocation16); - RECORD_CACHED_INTERFACE_DISPATCH_HELPER_AVLOCATION(RhpInterfaceDispatchAVLocation32); - RECORD_CACHED_INTERFACE_DISPATCH_HELPER_AVLOCATION(RhpInterfaceDispatchAVLocation64); - RECORD_CACHED_INTERFACE_DISPATCH_HELPER_AVLOCATION(RhpVTableOffsetDispatchAVLocation); - RECORD_CACHED_INTERFACE_DISPATCH_HELPER_AVLOCATION(RhpInitialInterfaceDispatch); + RECORD_CACHED_INTERFACE_DISPATCH_HELPER_AVLOCATION(RhpInterfaceDispatch); _ASSERTE(helperCount == CACHED_INTERFACE_DISPATCH_HELPER_COUNT); countCachedInterfaceDispatchHelpers = helperCount; diff --git a/src/coreclr/vm/virtualcallstub.h b/src/coreclr/vm/virtualcallstub.h index bad607a999c5e6..29b046786665bd 100644 --- a/src/coreclr/vm/virtualcallstub.h +++ b/src/coreclr/vm/virtualcallstub.h @@ -162,10 +162,6 @@ extern "C" ResolveCacheElem* __fastcall VSD_PromoteChainEntry(ResolveCacheElem * typedef VPTR(class VirtualCallStubManager) PTR_VirtualCallStubManager; -#ifdef FEATURE_CACHED_INTERFACE_DISPATCH -struct CachedIndirectionCellBlockListNode; -#endif // FEATURE_CACHED_INTERFACE_DISPATCH - // VirtualCallStubManager is the heart of the stub dispatch logic. See the book of the runtime entry // // file:../../doc/BookOfTheRuntime/ClassLoader/VirtualStubDispatchDesign.doc @@ -305,9 +301,6 @@ class VirtualCallStubManager : public StubManager m_cur_counter_block_for_reclaim(NULL), m_cur_counter_block_for_reclaim_index(0), m_pNext(NULL) -#if defined FEATURE_CACHED_INTERFACE_DISPATCH - , m_indirectionBlocks (0) -#endif { LIMITED_METHOD_CONTRACT; ZeroMemory(&stats, sizeof(stats)); @@ -319,6 +312,11 @@ class VirtualCallStubManager : public StubManager static bool isCachedInterfaceDispatchStub(PCODE addr); static bool isCachedInterfaceDispatchStubAVLocation(PCODE addr); +#if defined(FEATURE_CACHED_INTERFACE_DISPATCH) && !defined(DACCESS_COMPILE) + // Returns the LoaderAllocator that owns the memory of an interface dispatch cell. + static LoaderAllocator* FindLoaderAllocatorForDispatchCell(TADDR pCell); +#endif + static BOOL isStubStatic(PCODE addr) { WRAPPER_NO_CONTRACT; @@ -686,10 +684,6 @@ class VirtualCallStubManager : public StubManager // Used to keep track of all the VCSManager objects in the system. PTR_VirtualCallStubManager m_pNext; // Linked list pointer -#if defined FEATURE_CACHED_INTERFACE_DISPATCH - CachedIndirectionCellBlockListNode *m_indirectionBlocks; -#endif - public: #ifdef FEATURE_VIRTUAL_STUB_DISPATCH // Given a stub address, find the VCSManager that owns it. diff --git a/src/coreclr/vm/wasm/helpers.cpp b/src/coreclr/vm/wasm/helpers.cpp index 0f8d02a723b395..70436bca3ab3b1 100644 --- a/src/coreclr/vm/wasm/helpers.cpp +++ b/src/coreclr/vm/wasm/helpers.cpp @@ -107,9 +107,9 @@ extern "C" void STDCALL FixupPrecodeCode_End() PORTABILITY_ASSERT("FixupPrecodeCode_End is not implemented on wasm"); } -extern "C" void RhpInitialInterfaceDispatch() +extern "C" void RhpInterfaceDispatch() { - PORTABILITY_ASSERT("RhpInitialInterfaceDispatch is not implemented on wasm"); + PORTABILITY_ASSERT("RhpInterfaceDispatch is not implemented on wasm"); } unsigned FuncEvalFrame::GetFrameAttribs_Impl(void) @@ -575,46 +575,6 @@ extern "C" HRESULT __cdecl CorDBGetInterface(DebugInterface** rcInterface) return 0; } -extern "C" void RhpInterfaceDispatch1() -{ - PORTABILITY_ASSERT("RhpInterfaceDispatch1 is not implemented on wasm"); -} - -extern "C" void RhpInterfaceDispatch2() -{ - PORTABILITY_ASSERT("RhpInterfaceDispatch2 is not implemented on wasm"); -} - -extern "C" void RhpInterfaceDispatch4() -{ - PORTABILITY_ASSERT("RhpInterfaceDispatch4 is not implemented on wasm"); -} - -extern "C" void RhpInterfaceDispatch8() -{ - PORTABILITY_ASSERT("RhpInterfaceDispatch8 is not implemented on wasm"); -} - -extern "C" void RhpInterfaceDispatch16() -{ - PORTABILITY_ASSERT("RhpInterfaceDispatch16 is not implemented on wasm"); -} - -extern "C" void RhpInterfaceDispatch32() -{ - PORTABILITY_ASSERT("RhpInterfaceDispatch32 is not implemented on wasm"); -} - -extern "C" void RhpInterfaceDispatch64() -{ - PORTABILITY_ASSERT("RhpInterfaceDispatch64 is not implemented on wasm"); -} - -extern "C" void RhpVTableOffsetDispatch() -{ - PORTABILITY_ASSERT("RhpVTableOffsetDispatch is not implemented on wasm"); -} - typedef uint8_t CODE_LOCATION; CODE_LOCATION RhpAssignRefAVLocation; CODE_LOCATION RhpCheckedAssignRefAVLocation; @@ -624,46 +584,6 @@ extern "C" void ThisPtrRetBufPrecodeWorker() PORTABILITY_ASSERT("ThisPtrRetBufPrecodeWorker is not implemented on wasm"); } -extern "C" void RhpInterfaceDispatchAVLocation1() -{ - PORTABILITY_ASSERT("RhpInterfaceDispatchAVLocation1 is not implemented on wasm"); -} - -extern "C" void RhpInterfaceDispatchAVLocation2() -{ - PORTABILITY_ASSERT("RhpInterfaceDispatchAVLocation2 is not implemented on wasm"); -} - -extern "C" void RhpInterfaceDispatchAVLocation4() -{ - PORTABILITY_ASSERT("RhpInterfaceDispatchAVLocation4 is not implemented on wasm"); -} - -extern "C" void RhpInterfaceDispatchAVLocation8() -{ - PORTABILITY_ASSERT("RhpInterfaceDispatchAVLocation8 is not implemented on wasm"); -} - -extern "C" void RhpInterfaceDispatchAVLocation16() -{ - PORTABILITY_ASSERT("RhpInterfaceDispatchAVLocation16 is not implemented on wasm"); -} - -extern "C" void RhpInterfaceDispatchAVLocation32() -{ - PORTABILITY_ASSERT("RhpInterfaceDispatchAVLocation32 is not implemented on wasm"); -} - -extern "C" void RhpInterfaceDispatchAVLocation64() -{ - PORTABILITY_ASSERT("RhpInterfaceDispatchAVLocation64 is not implemented on wasm"); -} - -extern "C" void RhpVTableOffsetDispatchAVLocation() -{ - PORTABILITY_ASSERT("RhpVTableOffsetDispatchAVLocation is not implemented on wasm"); -} - extern "C" void STDCALL ThePreStubPatchLabel(void) { PORTABILITY_ASSERT("ThePreStubPatchLabel is not implemented on wasm");