-
Notifications
You must be signed in to change notification settings - Fork 4.5k
/
CastHelpers.cs
628 lines (525 loc) · 21 KB
/
CastHelpers.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using Internal.Runtime.CompilerServices;
namespace System.Runtime.CompilerServices
{
internal static unsafe class CastHelpers
{
private static int[]? s_table;
[DebuggerDisplay("Source = {_source}; Target = {_targetAndResult & ~1}; Result = {_targetAndResult & 1}; VersionNum = {_version & ((1 << 29) - 1)}; Distance = {_version >> 29};")]
[StructLayout(LayoutKind.Sequential)]
private struct CastCacheEntry
{
// version has the following structure:
// [ distance:3bit | versionNum:29bit ]
//
// distance is how many iterations the entry is from it ideal position.
// we use that for preemption.
//
// versionNum is a monotonicaly increasing numerical tag.
// Writer "claims" entry by atomically incrementing the tag. Thus odd number indicates an entry in progress.
// Upon completion of adding an entry the tag is incremented again making it even. Even number indicates a complete entry.
//
// Readers will read the version twice before and after retrieving the entry.
// To have a usable entry both reads must yield the same even version.
//
internal int _version;
internal nuint _source;
// pointers have unused lower bits due to alignment, we use one for the result
internal nuint _targetAndResult;
};
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int KeyToBucket(ref int tableData, nuint source, nuint target)
{
// upper bits of addresses do not vary much, so to reduce loss due to cancelling out,
// we do `rotl(source, <half-size>) ^ target` for mixing inputs.
// then we use fibonacci hashing to reduce the value to desired size.
int hashShift = HashShift(ref tableData);
#if TARGET_64BIT
ulong hash = (((ulong)source << 32) | ((ulong)source >> 32)) ^ (ulong)target;
return (int)((hash * 11400714819323198485ul) >> hashShift);
#else
uint hash = (((uint)source >> 16) | ((uint)source << 16)) ^ (uint)target;
return (int)((hash * 2654435769u) >> hashShift);
#endif
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static ref int TableData(int[] table)
{
// element 0 is used for embedded aux data
return ref MemoryMarshal.GetArrayDataReference(table);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static ref CastCacheEntry Element(ref int tableData, int index)
{
// element 0 is used for embedded aux data, skip it
return ref Unsafe.Add(ref Unsafe.As<int, CastCacheEntry>(ref tableData), index + 1);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int HashShift(ref int tableData)
{
return tableData;
}
// TableMask is "size - 1"
// we need that more often that we need size
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int TableMask(ref int tableData)
{
return Unsafe.Add(ref tableData, 1);
}
private enum CastResult
{
CannotCast = 0,
CanCast = 1,
MaybeCast = 2
}
// NOTE!!
// This is a copy of C++ implementation in castcache.cpp
// Keep the copies, if possible, in sync.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static CastResult TryGet(nuint source, nuint target)
{
const int BUCKET_SIZE = 8;
// table is initialized and updated by native code that guarantees it is not null.
ref int tableData = ref TableData(s_table!);
int index = KeyToBucket(ref tableData, source, target);
for (int i = 0; i < BUCKET_SIZE;)
{
ref CastCacheEntry pEntry = ref Element(ref tableData, index);
// must read in this order: version -> [entry parts] -> version
// if version is odd or changes, the entry is inconsistent and thus ignored
int version = Volatile.Read(ref pEntry._version);
nuint entrySource = pEntry._source;
// mask the lower version bit to make it even.
// This way we can check if version is odd or changing in just one compare.
version &= ~1;
if (entrySource == source)
{
nuint entryTargetAndResult = pEntry._targetAndResult;
// target never has its lower bit set.
// a matching entryTargetAndResult would the have same bits, except for the lowest one, which is the result.
entryTargetAndResult ^= target;
if (entryTargetAndResult <= 1)
{
// make sure 'version' is loaded after 'source' and 'targetAndResults'
//
// We can either:
// - use acquires for both _source and _targetAndResults or
// - issue a load barrier before reading _version
// benchmarks on available hardware show that use of a read barrier is cheaper.
Interlocked.ReadMemoryBarrier();
if (version != pEntry._version)
{
// oh, so close, the entry is in inconsistent state.
// it is either changing or has changed while we were reading.
// treat it as a miss.
break;
}
return (CastResult)entryTargetAndResult;
}
}
if (version == 0)
{
// the rest of the bucket is unclaimed, no point to search further
break;
}
// quadratic reprobe
i++;
index = (index + i) & TableMask(ref tableData);
}
return CastResult.MaybeCast;
}
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern object IsInstanceOfAny_NoCacheLookup(void* toTypeHnd, object obj);
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern object ChkCastAny_NoCacheLookup(void* toTypeHnd, object obj);
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern ref byte Unbox_Helper(void* toTypeHnd, object obj);
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void WriteBarrier(ref object? dst, object obj);
// IsInstanceOf test used for unusual cases (naked type parameters, variant generic types)
// Unlike the IsInstanceOfInterface and IsInstanceOfClass functions,
// this test must deal with all kinds of type tests
[DebuggerHidden]
[StackTraceHidden]
[DebuggerStepThrough]
private static object? IsInstanceOfAny(void* toTypeHnd, object? obj)
{
if (obj != null)
{
void* mt = RuntimeHelpers.GetMethodTable(obj);
if (mt != toTypeHnd)
{
CastResult result = TryGet((nuint)mt, (nuint)toTypeHnd);
if (result == CastResult.CanCast)
{
// do nothing
}
else if (result == CastResult.CannotCast)
{
obj = null;
}
else
{
goto slowPath;
}
}
}
return obj;
slowPath:
// fall through to the slow helper
return IsInstanceOfAny_NoCacheLookup(toTypeHnd, obj);
}
[DebuggerHidden]
[StackTraceHidden]
[DebuggerStepThrough]
private static object? IsInstanceOfInterface(void* toTypeHnd, object? obj)
{
const int unrollSize = 4;
if (obj != null)
{
MethodTable* mt = RuntimeHelpers.GetMethodTable(obj);
nint interfaceCount = mt->InterfaceCount;
if (interfaceCount != 0)
{
MethodTable** interfaceMap = mt->InterfaceMap;
if (interfaceCount < unrollSize)
{
// If not enough for unrolled, jmp straight to small loop
// as we already know there is one or more interfaces so don't need to check again.
goto few;
}
do
{
if (interfaceMap[0] == toTypeHnd ||
interfaceMap[1] == toTypeHnd ||
interfaceMap[2] == toTypeHnd ||
interfaceMap[3] == toTypeHnd)
{
goto done;
}
interfaceMap += unrollSize;
interfaceCount -= unrollSize;
} while (interfaceCount >= unrollSize);
if (interfaceCount == 0)
{
// If none remaining, skip the short loop
goto extra;
}
few:
do
{
if (interfaceMap[0] == toTypeHnd)
{
goto done;
}
// Assign next offset
interfaceMap++;
interfaceCount--;
} while (interfaceCount > 0);
}
extra:
if (mt->NonTrivialInterfaceCast)
{
goto slowPath;
}
obj = null;
}
done:
return obj;
slowPath:
return IsInstance_Helper(toTypeHnd, obj);
}
[DebuggerHidden]
[StackTraceHidden]
[DebuggerStepThrough]
private static object? IsInstanceOfClass(void* toTypeHnd, object? obj)
{
if (obj == null || RuntimeHelpers.GetMethodTable(obj) == toTypeHnd)
return obj;
MethodTable* mt = RuntimeHelpers.GetMethodTable(obj)->ParentMethodTable;
for (; ; )
{
if (mt == toTypeHnd)
goto done;
if (mt == null)
break;
mt = mt->ParentMethodTable;
if (mt == toTypeHnd)
goto done;
if (mt == null)
break;
mt = mt->ParentMethodTable;
if (mt == toTypeHnd)
goto done;
if (mt == null)
break;
mt = mt->ParentMethodTable;
if (mt == toTypeHnd)
goto done;
if (mt == null)
break;
mt = mt->ParentMethodTable;
}
// this helper is not supposed to be used with type-equivalent "to" type.
Debug.Assert(!((MethodTable*)toTypeHnd)->HasTypeEquivalence);
obj = null;
done:
return obj;
}
[DebuggerHidden]
[StackTraceHidden]
[DebuggerStepThrough]
[MethodImpl(MethodImplOptions.NoInlining)]
private static object? IsInstance_Helper(void* toTypeHnd, object obj)
{
CastResult result = TryGet((nuint)RuntimeHelpers.GetMethodTable(obj), (nuint)toTypeHnd);
if (result == CastResult.CanCast)
{
return obj;
}
else if (result == CastResult.CannotCast)
{
return null;
}
// fall through to the slow helper
return IsInstanceOfAny_NoCacheLookup(toTypeHnd, obj);
}
// ChkCast test used for unusual cases (naked type parameters, variant generic types)
// Unlike the ChkCastInterface and ChkCastClass functions,
// this test must deal with all kinds of type tests
[DebuggerHidden]
[StackTraceHidden]
[DebuggerStepThrough]
private static object? ChkCastAny(void* toTypeHnd, object? obj)
{
CastResult result;
if (obj != null)
{
void* mt = RuntimeHelpers.GetMethodTable(obj);
if (mt != toTypeHnd)
{
result = TryGet((nuint)mt, (nuint)toTypeHnd);
if (result != CastResult.CanCast)
{
goto slowPath;
}
}
}
return obj;
slowPath:
// fall through to the slow helper
object objRet = ChkCastAny_NoCacheLookup(toTypeHnd, obj);
// Make sure that the fast helper have not lied
Debug.Assert(result != CastResult.CannotCast);
return objRet;
}
[DebuggerHidden]
[StackTraceHidden]
[DebuggerStepThrough]
[MethodImpl(MethodImplOptions.NoInlining)]
private static object? ChkCast_Helper(void* toTypeHnd, object obj)
{
CastResult result = TryGet((nuint)RuntimeHelpers.GetMethodTable(obj), (nuint)toTypeHnd);
if (result == CastResult.CanCast)
{
return obj;
}
// fall through to the slow helper
return ChkCastAny_NoCacheLookup(toTypeHnd, obj);
}
[DebuggerHidden]
[StackTraceHidden]
[DebuggerStepThrough]
private static object? ChkCastInterface(void* toTypeHnd, object? obj)
{
const int unrollSize = 4;
if (obj != null)
{
MethodTable* mt = RuntimeHelpers.GetMethodTable(obj);
nint interfaceCount = mt->InterfaceCount;
if (interfaceCount == 0)
{
goto slowPath;
}
MethodTable** interfaceMap = mt->InterfaceMap;
if (interfaceCount < unrollSize)
{
// If not enough for unrolled, jmp straight to small loop
// as we already know there is one or more interfaces so don't need to check again.
goto few;
}
do
{
if (interfaceMap[0] == toTypeHnd ||
interfaceMap[1] == toTypeHnd ||
interfaceMap[2] == toTypeHnd ||
interfaceMap[3] == toTypeHnd)
{
goto done;
}
// Assign next offset
interfaceMap += unrollSize;
interfaceCount -= unrollSize;
} while (interfaceCount >= unrollSize);
if (interfaceCount == 0)
{
// If none remaining, skip the short loop
goto slowPath;
}
few:
do
{
if (interfaceMap[0] == toTypeHnd)
{
goto done;
}
// Assign next offset
interfaceMap++;
interfaceCount--;
} while (interfaceCount > 0);
goto slowPath;
}
done:
return obj;
slowPath:
return ChkCast_Helper(toTypeHnd, obj);
}
[DebuggerHidden]
[StackTraceHidden]
[DebuggerStepThrough]
private static object? ChkCastClass(void* toTypeHnd, object? obj)
{
if (obj == null || RuntimeHelpers.GetMethodTable(obj) == toTypeHnd)
{
return obj;
}
return ChkCastClassSpecial(toTypeHnd, obj);
}
[DebuggerHidden]
[StackTraceHidden]
[DebuggerStepThrough]
private static object? ChkCastClassSpecial(void* toTypeHnd, object obj)
{
MethodTable* mt = RuntimeHelpers.GetMethodTable(obj);
Debug.Assert(mt != toTypeHnd, "The check for the trivial cases should be inlined by the JIT");
for (; ; )
{
mt = mt->ParentMethodTable;
if (mt == toTypeHnd)
goto done;
if (mt == null)
break;
mt = mt->ParentMethodTable;
if (mt == toTypeHnd)
goto done;
if (mt == null)
break;
mt = mt->ParentMethodTable;
if (mt == toTypeHnd)
goto done;
if (mt == null)
break;
mt = mt->ParentMethodTable;
if (mt == toTypeHnd)
goto done;
if (mt == null)
break;
}
goto slowPath;
done:
return obj;
slowPath:
return ChkCast_Helper(toTypeHnd, obj);
}
[DebuggerHidden]
[StackTraceHidden]
[DebuggerStepThrough]
private static ref byte Unbox(void* toTypeHnd, object obj)
{
// this will throw NullReferenceException if obj is null, attributed to the user code, as expected.
if (RuntimeHelpers.GetMethodTable(obj) == toTypeHnd)
return ref obj.GetRawData();
return ref Unbox_Helper(toTypeHnd, obj);
}
internal struct ArrayElement
{
public object? Value;
}
[DebuggerHidden]
[StackTraceHidden]
[DebuggerStepThrough]
private static ref object? ThrowArrayMismatchException()
{
throw new ArrayTypeMismatchException();
}
[DebuggerHidden]
[StackTraceHidden]
[DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
private static ref object? LdelemaRef(Array array, int 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;
void* elementType = RuntimeHelpers.GetMethodTable(array)->ElementType;
if (elementType == type)
return ref element;
return ref ThrowArrayMismatchException();
}
[DebuggerHidden]
[StackTraceHidden]
[DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
private static void StelemRef(Array array, int 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;
void* elementType = RuntimeHelpers.GetMethodTable(array)->ElementType;
if (obj == null)
goto assigningNull;
if (elementType != RuntimeHelpers.GetMethodTable(obj))
goto notExactMatch;
doWrite:
WriteBarrier(ref element, obj);
return;
assigningNull:
element = null;
return;
notExactMatch:
if (array.GetType() == typeof(object[]))
goto doWrite;
StelemRef_Helper(ref element, elementType, obj);
}
[DebuggerHidden]
[StackTraceHidden]
[DebuggerStepThrough]
[MethodImpl(MethodImplOptions.NoInlining)]
private static void StelemRef_Helper(ref object? element, void* elementType, object obj)
{
CastResult result = TryGet((nuint)RuntimeHelpers.GetMethodTable(obj), (nuint)elementType);
if (result == CastResult.CanCast)
{
WriteBarrier(ref element, obj);
return;
}
StelemRef_Helper_NoCacheLookup(ref element, elementType, obj);
}
[DebuggerHidden]
[StackTraceHidden]
[DebuggerStepThrough]
private static void StelemRef_Helper_NoCacheLookup(ref object? element, void* elementType, object obj)
{
Debug.Assert(obj != null);
obj = IsInstanceOfAny_NoCacheLookup(elementType, obj);
if (obj != null)
{
WriteBarrier(ref element, obj);
return;
}
throw new ArrayTypeMismatchException();
}
}
}