Skip to content

Commit

Permalink
On 64 bit platforms, "stelem.ref" and "ldelema" ignore the high bits …
Browse files Browse the repository at this point in the history
…of a native int index (#71571)

Add support for native int indices in stelem.ref and ldelema helper functions. This required changing the abi of these functions, which required bumping the major R2R version number. As we have already done that for .NET 7, this is a minor cost. Note that this is still broken on Mono, and that bug is #71656 

Fixes #52817
  • Loading branch information
davidwrighton authored Jul 6, 2022
1 parent f29ae44 commit 0e30a6f
Show file tree
Hide file tree
Showing 13 changed files with 148 additions and 18 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -553,7 +553,7 @@ internal struct ArrayElement
[StackTraceHidden]
[DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
private static ref object? LdelemaRef(Array array, int index, void* type)
private static ref object? LdelemaRef(Array array, nint index, void* type)
{
// this will throw appropriate exceptions if array is null or access is out of range.
ref object? element = ref Unsafe.As<ArrayElement[]>(array)[index].Value;
Expand All @@ -569,7 +569,7 @@ internal struct ArrayElement
[StackTraceHidden]
[DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
private static void StelemRef(Array array, int index, object? obj)
private static void StelemRef(Array array, nint index, object? obj)
{
// this will throw appropriate exceptions if array is null or access is out of range.
ref object? element = ref Unsafe.As<ArrayElement[]>(array)[index].Value;
Expand Down
10 changes: 5 additions & 5 deletions src/coreclr/inc/jiteeversionguid.h
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,11 @@ typedef const GUID *LPCGUID;
#define GUID_DEFINED
#endif // !GUID_DEFINED

constexpr GUID JITEEVersionIdentifier = { /* f2faa5fc-a1ec-4244-aebb-5597bfd7153a */
0xf2faa5fc,
0xa1ec,
0x4244,
{0xae, 0xbb, 0x55, 0x97, 0xbf, 0xd7, 0x15, 0x3a}
constexpr GUID JITEEVersionIdentifier = { /* 0d853657-7a01-421f-b1b0-d22a8e691441 */
0x0d853657,
0x7a01,
0x421f,
{0xb1, 0xb0, 0xd2, 0x2a, 0x8e, 0x69, 0x14, 0x41}
};

//////////////////////////////////////////////////////////////////////////////////////////////////////////
Expand Down
8 changes: 6 additions & 2 deletions src/coreclr/inc/readytorun.h
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@
#define READYTORUN_SIGNATURE 0x00525452 // 'RTR'

// Keep these in sync with src/coreclr/tools/Common/Internal/Runtime/ModuleHeaders.cs
#define READYTORUN_MAJOR_VERSION 0x0006
#define READYTORUN_MINOR_VERSION 0x0003
#define READYTORUN_MAJOR_VERSION 0x0007
#define READYTORUN_MINOR_VERSION 0x0000

#define MINIMUM_READYTORUN_MAJOR_VERSION 0x006

Expand Down Expand Up @@ -401,6 +401,10 @@ enum ReadyToRunHelper
READYTORUN_HELPER_StackProbe = 0x111,

READYTORUN_HELPER_GetCurrentManagedThreadId = 0x112,

// Array helpers for use with native ints
READYTORUN_HELPER_Stelem_Ref_I = 0x113,
READYTORUN_HELPER_Ldelema_Ref_I = 0x114,
};

#include "readytoruninstructionset.h"
Expand Down
38 changes: 36 additions & 2 deletions src/coreclr/jit/importer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -13711,7 +13711,24 @@ void Compiler::impImportBlockCode(BasicBlock* block)
GenTree* type = op1;
GenTree* index = impPopStack().val;
GenTree* arr = impPopStack().val;
op1 = gtNewHelperCallNode(CORINFO_HELP_LDELEMA_REF, TYP_BYREF, arr, index, type);
#ifdef TARGET_64BIT
// The CLI Spec allows an array to be indexed by either an int32 or a native int.
// The array helper takes a native int for array length.
// So if we have an int, explicitly extend it to be a native int.
if (genActualType(index->TypeGet()) != TYP_I_IMPL)
{
if (index->IsIntegralConst())
{
index->gtType = TYP_I_IMPL;
}
else
{
bool isUnsigned = false;
index = gtNewCastNode(TYP_I_IMPL, index, isUnsigned, TYP_I_IMPL);
}
}
#endif // TARGET_64BIT
op1 = gtNewHelperCallNode(CORINFO_HELP_LDELEMA_REF, TYP_BYREF, arr, index, type);
}

impPushOnStack(op1, tiRetVal);
Expand Down Expand Up @@ -13852,7 +13869,24 @@ void Compiler::impImportBlockCode(BasicBlock* block)

impPopStack(3);

// Else call a helper function to do the assignment
// Else call a helper function to do the assignment
#ifdef TARGET_64BIT
// The CLI Spec allows an array to be indexed by either an int32 or a native int.
// The array helper takes a native int for array length.
// So if we have an int, explicitly extend it to be a native int.
if (genActualType(index->TypeGet()) != TYP_I_IMPL)
{
if (index->IsIntegralConst())
{
index->gtType = TYP_I_IMPL;
}
else
{
bool isUnsigned = false;
index = gtNewCastNode(TYP_I_IMPL, index, isUnsigned, TYP_I_IMPL);
}
}
#endif // TARGET_64BIT
op1 = gtNewHelperCallNode(CORINFO_HELP_ARRADDR_ST, TYP_VOID, array, index, value);
goto SPILL_APPEND;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,15 @@ public static ref T Add<T>(ref T source, int elementOffset)
return ref AddByteOffset(ref source, (IntPtr)(elementOffset * (nint)SizeOf<T>()));
}

/// <summary>
/// Adds an element offset to the given reference.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ref T Add<T>(ref T source, IntPtr elementOffset)
{
return ref AddByteOffset(ref source, (IntPtr)((nint)elementOffset * (nint)SizeOf<T>()));
}

/// <summary>
/// Reinterprets the given location as a reference to a value of type <typeparamref name="T"/>.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -743,7 +743,7 @@ internal struct ArrayElement
// Array stelem/ldelema helpers with RyuJIT conventions
//
[RuntimeExport("RhpStelemRef")]
public static unsafe void StelemRef(Array array, int index, object obj)
public static unsafe void StelemRef(Array array, nint index, object obj)
{
// This is supported only on arrays
Debug.Assert(array.GetMethodTable()->IsArray, "first argument must be an array");
Expand Down Expand Up @@ -814,7 +814,7 @@ private static unsafe void StelemRef_Helper(ref object element, MethodTable* ele
}

[RuntimeExport("RhpLdelemaRef")]
public static unsafe ref object LdelemaRef(Array array, int index, IntPtr elementType)
public static unsafe ref object LdelemaRef(Array array, nint index, IntPtr elementType)
{
Debug.Assert(array.GetMethodTable()->IsArray, "first argument must be an array");

Expand Down
2 changes: 1 addition & 1 deletion src/coreclr/nativeaot/Runtime/inc/ModuleHeaders.h
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ struct ReadyToRunHeaderConstants
{
static const uint32_t Signature = 0x00525452; // 'RTR'

static const uint32_t CurrentMajorVersion = 6;
static const uint32_t CurrentMajorVersion = 7;
static const uint32_t CurrentMinorVersion = 0;
};

Expand Down
4 changes: 2 additions & 2 deletions src/coreclr/tools/Common/Internal/Runtime/ModuleHeaders.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ internal struct ReadyToRunHeaderConstants
{
public const uint Signature = 0x00525452; // 'RTR'

public const ushort CurrentMajorVersion = 6;
public const ushort CurrentMinorVersion = 3;
public const ushort CurrentMajorVersion = 7;
public const ushort CurrentMinorVersion = 0;
}

#pragma warning disable 0169
Expand Down
4 changes: 2 additions & 2 deletions src/coreclr/vm/corelib.h
Original file line number Diff line number Diff line change
Expand Up @@ -1226,8 +1226,8 @@ DEFINE_METHOD(CASTHELPERS, CHKCASTINTERFACE, ChkCastInterface, SM_Ptr
DEFINE_METHOD(CASTHELPERS, CHKCASTCLASS, ChkCastClass, SM_PtrVoid_Obj_RetObj)
DEFINE_METHOD(CASTHELPERS, CHKCASTCLASSSPECIAL, ChkCastClassSpecial, SM_PtrVoid_Obj_RetObj)
DEFINE_METHOD(CASTHELPERS, UNBOX, Unbox, SM_PtrVoid_Obj_RetRefByte)
DEFINE_METHOD(CASTHELPERS, STELEMREF, StelemRef, SM_Array_Int_Obj_RetVoid)
DEFINE_METHOD(CASTHELPERS, LDELEMAREF, LdelemaRef, SM_Array_Int_PtrVoid_RetRefObj)
DEFINE_METHOD(CASTHELPERS, STELEMREF, StelemRef, SM_Array_IntPtr_Obj_RetVoid)
DEFINE_METHOD(CASTHELPERS, LDELEMAREF, LdelemaRef, SM_Array_IntPtr_PtrVoid_RetRefObj)

DEFINE_CLASS_U(System, GCMemoryInfoData, GCMemoryInfoData)
DEFINE_FIELD_U(_highMemoryLoadThresholdBytes, GCMemoryInfoData, highMemLoadThresholdBytes)
Expand Down
2 changes: 2 additions & 0 deletions src/coreclr/vm/metasig.h
Original file line number Diff line number Diff line change
Expand Up @@ -604,6 +604,8 @@ DEFINE_METASIG(GM(RetT, IMAGE_CEE_CS_CALLCONV_DEFAULT, 1, _, M(0)))
DEFINE_METASIG_T(SM(Array_Int_Array_Int_Int_RetVoid, C(ARRAY) i C(ARRAY) i i, v))
DEFINE_METASIG_T(SM(Array_Int_Obj_RetVoid, C(ARRAY) i j, v))
DEFINE_METASIG_T(SM(Array_Int_PtrVoid_RetRefObj, C(ARRAY) i P(v), r(j)))
DEFINE_METASIG_T(SM(Array_IntPtr_Obj_RetVoid, C(ARRAY) I j, v))
DEFINE_METASIG_T(SM(Array_IntPtr_PtrVoid_RetRefObj, C(ARRAY) I P(v), r(j)))

DEFINE_METASIG(SM(Obj_IntPtr_Bool_RetVoid, j I F, v))
DEFINE_METASIG(SM(IntPtr_Obj_RetVoid, I j, v))
Expand Down
66 changes: 66 additions & 0 deletions src/tests/JIT/Directed/Arrays/nintindexoutofrange.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
using System;
using System.Runtime.CompilerServices;

class NintIndexOutOfRangeTest
{
[MethodImpl(MethodImplOptions.NoInlining)]
static void Stelem_Ref(object[] arr, nint i, Object value)
=> arr[i] = value;

[MethodImpl(MethodImplOptions.NoInlining)]
static void LdElemATestHelper(ref object nothingOfInterest)
{}

[MethodImpl(MethodImplOptions.NoInlining)]
static void LdElemA(object[] arr, nint i)
{
LdElemATestHelper(ref arr[i]);
}

public static unsafe int Main()
{
long longIndex = ((long)1) << 32;
nint index = (nint)longIndex;
bool failed = false;

// On a 32bit platform, just succeed.
if (sizeof(long) != sizeof(nint))
return 100;

var arr = new Object[10];
// Try store to invalid index with null
try
{
Stelem_Ref(arr, index, null);
failed = true;
Console.WriteLine("Failed to throw IndexOutOfRange when storing null");
}
catch (IndexOutOfRangeException) {}

// Try store to invalid index with actual value
try
{
Stelem_Ref(arr, index, new object());
failed = true;
Console.WriteLine("Failed to throw IndexOutOfRange when storing object");
}
catch (IndexOutOfRangeException) {}

// Try to load element address
try
{
LdElemA(arr, index);
failed = true;
Console.WriteLine("Failed to throw IndexOutOfRange when accessing element");
}
catch (IndexOutOfRangeException) {}

if (failed)
return 1;
else
return 100;
}
}
12 changes: 12 additions & 0 deletions src/tests/JIT/Directed/Arrays/nintindexoutofrange.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<CLRTestPriority>0</CLRTestPriority>
</PropertyGroup>
<PropertyGroup>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
<Compile Include="nintindexoutofrange.cs" />
</ItemGroup>
</Project>
3 changes: 3 additions & 0 deletions src/tests/issues.targets
Original file line number Diff line number Diff line change
Expand Up @@ -1454,6 +1454,9 @@

<!-- Known failures for mono runtime on *all* architectures/operating systems in *all* runtime modes -->
<ItemGroup Condition="'$(RuntimeFlavor)' == 'mono'" >
<ExcludeList Include = "$(XUnitTestBinBase)/JIT/Directed/Arrays/nintindexoutofrange/**">
<Issue>https://github.com/dotnet/runtime/issues/71656</Issue>
</ExcludeList>
<ExcludeList Include = "$(XUnitTestBinBase)/JIT/HardwareIntrinsics/X86/X86Base/Pause*/**">
<Issue>https://github.com/dotnet/runtime/issues/61693</Issue>
</ExcludeList>
Expand Down

0 comments on commit 0e30a6f

Please sign in to comment.