-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
CorInfoImpl.cs
4392 lines (3711 loc) · 179 KB
/
CorInfoImpl.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
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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.Buffers;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Text.Unicode;
#if SUPPORT_JIT
using Internal.Runtime.CompilerServices;
#endif
using Internal.IL;
using Internal.TypeSystem;
using Internal.TypeSystem.Ecma;
using Internal.TypeSystem.Interop;
using Internal.CorConstants;
using Internal.Pgo;
using ILCompiler;
using ILCompiler.DependencyAnalysis;
#if READYTORUN
using System.Reflection.Metadata.Ecma335;
using ILCompiler.DependencyAnalysis.ReadyToRun;
#endif
using DependencyList = ILCompiler.DependencyAnalysisFramework.DependencyNodeCore<ILCompiler.DependencyAnalysis.NodeFactory>.DependencyList;
#pragma warning disable IDE0060
namespace Internal.JitInterface
{
internal enum CompilationResult
{
CompilationComplete,
CompilationRetryRequested
}
internal sealed unsafe partial class CorInfoImpl
{
//
// Global initialization and state
//
private enum ImageFileMachine
{
I386 = 0x014c,
IA64 = 0x0200,
AMD64 = 0x8664,
ARM = 0x01c4,
ARM64 = 0xaa64,
LoongArch64 = 0x6264,
RiscV64 = 0x5064,
}
internal const string JitLibrary = "clrjitilc";
#if SUPPORT_JIT
private const string JitSupportLibrary = "*";
#else
internal const string JitSupportLibrary = "jitinterface";
#endif
private IntPtr _jit;
private IntPtr _unmanagedCallbacks; // array of pointers to JIT-EE interface callbacks
private ExceptionDispatchInfo _lastException;
private struct PgoInstrumentationResults
{
public PgoInstrumentationSchema* pSchema;
public uint countSchemaItems;
public byte* pInstrumentationData;
public HRESULT hr;
}
private Dictionary<MethodDesc, PgoInstrumentationResults> _pgoResults = new Dictionary<MethodDesc, PgoInstrumentationResults>();
[DllImport(JitLibrary)]
private static extern IntPtr jitStartup(IntPtr host);
private static class JitPointerAccessor
{
[DllImport(JitLibrary)]
private static extern IntPtr getJit();
[DllImport(JitSupportLibrary)]
private static extern CorJitResult JitProcessShutdownWork(IntPtr jit);
static JitPointerAccessor()
{
s_jit = getJit();
if (s_jit != IntPtr.Zero)
{
AppDomain.CurrentDomain.ProcessExit += (_, _) => JitProcessShutdownWork(s_jit);
AppDomain.CurrentDomain.UnhandledException += (_, _) => JitProcessShutdownWork(s_jit);
}
}
public static IntPtr Get()
{
return s_jit;
}
private static readonly IntPtr s_jit;
}
private struct LikelyClassMethodRecord
{
public IntPtr handle;
public uint likelihood;
public LikelyClassMethodRecord(IntPtr handle, uint likelihood)
{
this.handle = handle;
this.likelihood = likelihood;
}
}
[DllImport(JitLibrary)]
private static extern uint getLikelyClasses(LikelyClassMethodRecord* pLikelyClasses, uint maxLikelyClasses, PgoInstrumentationSchema* schema, uint countSchemaItems, byte*pInstrumentationData, int ilOffset);
[DllImport(JitLibrary)]
private static extern uint getLikelyMethods(LikelyClassMethodRecord* pLikelyMethods, uint maxLikelyMethods, PgoInstrumentationSchema* schema, uint countSchemaItems, byte*pInstrumentationData, int ilOffset);
[DllImport(JitSupportLibrary)]
private static extern IntPtr GetJitHost(IntPtr configProvider);
//
// Per-method initialization and state
//
private static CorInfoImpl GetThis(IntPtr thisHandle)
{
CorInfoImpl _this = Unsafe.Read<CorInfoImpl>((void*)thisHandle);
Debug.Assert(_this is CorInfoImpl);
return _this;
}
[DllImport(JitSupportLibrary)]
private static extern CorJitResult JitCompileMethod(out IntPtr exception,
IntPtr jit, IntPtr thisHandle, IntPtr callbacks,
ref CORINFO_METHOD_INFO info, uint flags, out IntPtr nativeEntry, out uint codeSize);
[DllImport(JitSupportLibrary)]
private static extern IntPtr AllocException([MarshalAs(UnmanagedType.LPWStr)]string message, int messageLength);
[DllImport(JitSupportLibrary)]
private static extern void JitSetOs(IntPtr jit, CORINFO_OS os);
private IntPtr AllocException(Exception ex)
{
_lastException = ExceptionDispatchInfo.Capture(ex);
string exString = ex.ToString();
IntPtr nativeException = AllocException(exString, exString.Length);
_nativeExceptions ??= new List<IntPtr>();
_nativeExceptions.Add(nativeException);
return nativeException;
}
[DllImport(JitSupportLibrary)]
private static extern void FreeException(IntPtr obj);
[DllImport(JitSupportLibrary)]
private static extern char* GetExceptionMessage(IntPtr obj);
public static void Startup(CORINFO_OS os)
{
jitStartup(GetJitHost(JitConfigProvider.Instance.UnmanagedInstance));
JitSetOs(JitPointerAccessor.Get(), os);
}
public CorInfoImpl()
{
_jit = JitPointerAccessor.Get();
if (_jit == IntPtr.Zero)
{
throw new IOException("Failed to initialize JIT");
}
_unmanagedCallbacks = GetUnmanagedCallbacks();
}
private Logger Logger
{
get
{
return _compilation.Logger;
}
}
private CORINFO_MODULE_STRUCT_* _methodScope; // Needed to resolve CORINFO_EH_CLAUSE tokens
public static IEnumerable<PgoSchemaElem> ConvertTypeHandleHistogramsToCompactTypeHistogramFormat(PgoSchemaElem[] pgoData, CompilationModuleGroup compilationModuleGroup)
{
bool hasHistogram = false;
foreach (var elem in pgoData)
{
if (elem.InstrumentationKind == PgoInstrumentationKind.HandleHistogramTypes ||
elem.InstrumentationKind == PgoInstrumentationKind.HandleHistogramMethods)
{
// found histogram
hasHistogram = true;
break;
}
}
if (!hasHistogram)
{
foreach (var elem in pgoData)
{
yield return elem;
}
}
else
{
int currentObjectIndex = 0x1000000; // This needs to be a somewhat large non-zero number, so that the jit does not confuse it with NULL, or any other special value.
Dictionary<object, IntPtr> objectToHandle = new Dictionary<object, IntPtr>();
Dictionary<IntPtr, object> handleToObject = new Dictionary<IntPtr, object>();
MemoryStream memoryStreamInstrumentationData = new MemoryStream();
ComputeJitPgoInstrumentationSchema(LocalObjectToHandle, pgoData, out var nativeSchema, memoryStreamInstrumentationData);
var instrumentationData = memoryStreamInstrumentationData.ToArray();
for (int i = 0; i < pgoData.Length; i++)
{
if ((i + 1 < pgoData.Length) &&
(pgoData[i].InstrumentationKind == PgoInstrumentationKind.HandleHistogramIntCount ||
pgoData[i].InstrumentationKind == PgoInstrumentationKind.HandleHistogramLongCount) &&
(pgoData[i + 1].InstrumentationKind == PgoInstrumentationKind.HandleHistogramTypes ||
pgoData[i + 1].InstrumentationKind == PgoInstrumentationKind.HandleHistogramMethods))
{
PgoSchemaElem? newElem = ComputeLikelyClassMethod(i, handleToObject, nativeSchema, instrumentationData, compilationModuleGroup);
if (newElem.HasValue)
{
yield return newElem.Value;
}
i++; // The histogram is two entries long, so skip an extra entry
continue;
}
yield return pgoData[i];
}
IntPtr LocalObjectToHandle(object input)
{
if (objectToHandle.TryGetValue(input, out var result))
{
return result;
}
result = new IntPtr(currentObjectIndex++);
objectToHandle.Add(input, result);
handleToObject.Add(result, input);
return result;
}
}
}
private static PgoSchemaElem? ComputeLikelyClassMethod(int index, Dictionary<IntPtr, object> handleToObject, PgoInstrumentationSchema[] nativeSchema, byte[] instrumentationData, CompilationModuleGroup compilationModuleGroup)
{
// getLikelyClasses will use two entries from the native schema table. There must be at least two present to avoid overruning the buffer
if (index > (nativeSchema.Length - 2))
return null;
bool isType = nativeSchema[index + 1].InstrumentationKind == PgoInstrumentationKind.HandleHistogramTypes;
fixed(PgoInstrumentationSchema* pSchema = &nativeSchema[index])
{
fixed(byte* pInstrumentationData = &instrumentationData[0])
{
// We're going to store only the most popular type/method to reduce size of the profile
LikelyClassMethodRecord* likelyClassMethods = stackalloc LikelyClassMethodRecord[1];
uint numberOfRecords;
if (isType)
{
numberOfRecords = getLikelyClasses(likelyClassMethods, 1, pSchema, 2, pInstrumentationData, nativeSchema[index].ILOffset);
}
else
{
numberOfRecords = getLikelyMethods(likelyClassMethods, 1, pSchema, 2, pInstrumentationData, nativeSchema[index].ILOffset);
}
if (numberOfRecords > 0)
{
TypeSystemEntityOrUnknown[] newData = null;
if (isType)
{
TypeDesc type = (TypeDesc)handleToObject[likelyClassMethods->handle];
#if READYTORUN
if (compilationModuleGroup.VersionsWithType(type))
#endif
{
newData = new[] { new TypeSystemEntityOrUnknown(type) };
}
}
else
{
MethodDesc method = (MethodDesc)handleToObject[likelyClassMethods->handle];
#if READYTORUN
if (compilationModuleGroup.VersionsWithMethodBody(method))
#endif
{
newData = new[] { new TypeSystemEntityOrUnknown(method) };
}
}
if (newData != null)
{
PgoSchemaElem likelyClassElem = default(PgoSchemaElem);
likelyClassElem.InstrumentationKind = isType ? PgoInstrumentationKind.GetLikelyClass : PgoInstrumentationKind.GetLikelyMethod;
likelyClassElem.ILOffset = nativeSchema[index].ILOffset;
likelyClassElem.Count = 1;
likelyClassElem.Other = (int)(likelyClassMethods->likelihood | (numberOfRecords << 8));
likelyClassElem.DataObject = newData;
return likelyClassElem;
}
}
}
}
return null;
}
private CompilationResult CompileMethodInternal(IMethodNode methodCodeNodeNeedingCode, MethodIL methodIL)
{
// methodIL must not be null
if (methodIL == null)
{
ThrowHelper.ThrowInvalidProgramException(ExceptionStringID.InvalidProgramSpecific, MethodBeingCompiled);
}
CORINFO_METHOD_INFO methodInfo;
Get_CORINFO_METHOD_INFO(MethodBeingCompiled, methodIL, &methodInfo);
_methodScope = methodInfo.scope;
#if !READYTORUN
SetDebugInformation(methodCodeNodeNeedingCode, methodIL);
#endif
CorInfoImpl _this = this;
IntPtr exception;
IntPtr nativeEntry;
uint codeSize;
#pragma warning disable CS8500 // takes address of managed type
var result = JitCompileMethod(out exception,
_jit, (IntPtr)(&_this), _unmanagedCallbacks,
ref methodInfo, (uint)CorJitFlag.CORJIT_FLAG_CALL_GETJITFLAGS, out nativeEntry, out codeSize);
#pragma warning restore CS8500
if (exception != IntPtr.Zero)
{
if (_lastException != null)
{
// If we captured a managed exception, rethrow that.
// TODO: might not actually be the real reason. It could be e.g. a JIT failure/bad IL that followed
// an inlining attempt with a type system problem in it...
#if SUPPORT_JIT
_lastException.Throw();
#else
if (_lastException.SourceException is TypeSystemException)
{
// Type system exceptions can be turned into code that throws the exception at runtime.
_lastException.Throw();
}
#if READYTORUN
else if (_lastException.SourceException is RequiresRuntimeJitException)
{
// Runtime JIT requirement is not a cause for failure, we just mustn't JIT a particular method
_lastException.Throw();
}
#endif
else
{
// This is just a bug somewhere.
throw new CodeGenerationFailedException(_methodCodeNode.Method, _lastException.SourceException);
}
#endif
}
// This is a failure we don't know much about.
char* szMessage = GetExceptionMessage(exception);
string message = szMessage != null ? new string(szMessage) : "JIT Exception";
throw new Exception(message);
}
if (result == CorJitResult.CORJIT_BADCODE)
{
ThrowHelper.ThrowInvalidProgramException();
}
if (result == CorJitResult.CORJIT_IMPLLIMITATION)
{
#if READYTORUN
throw new RequiresRuntimeJitException("JIT implementation limitation");
#else
ThrowHelper.ThrowInvalidProgramException();
#endif
}
if (result != CorJitResult.CORJIT_OK)
{
#if SUPPORT_JIT
// FailFast?
throw new Exception("JIT failed");
#else
throw new CodeGenerationFailedException(_methodCodeNode.Method);
#endif
}
if (codeSize < _code.Length)
{
if (_compilation.TypeSystemContext.Target.Architecture != TargetArchitecture.ARM64
&& _compilation.TypeSystemContext.Target.Architecture != TargetArchitecture.LoongArch64
&& _compilation.TypeSystemContext.Target.Architecture != TargetArchitecture.RiscV64)
{
// For xarch/arm32/LoongArch64/RiscV64, the generated code is sometimes smaller than the memory allocated.
// In that case, trim the codeBlock to the actual value.
//
// For arm64, the allocation request of `hotCodeSize` also includes the roData size
// while the `codeSize` returned just contains the size of the native code. As such,
// there is guarantee that for armarch, (codeSize == _code.Length) is always true.
//
// Currently, hot/cold splitting is not done and hence `codeSize` just includes the size of
// hotCode. Once hot/cold splitting is done, need to trim respective `_code` or `_coldCode`
// accordingly.
Debug.Assert(codeSize != 0);
Array.Resize(ref _code, (int)codeSize);
}
}
CompilationResult compilationCompleteBehavior = CompilationResult.CompilationComplete;
DetermineIfCompilationShouldBeRetried(ref compilationCompleteBehavior);
if (compilationCompleteBehavior == CompilationResult.CompilationRetryRequested)
return compilationCompleteBehavior;
PublishCode();
PublishROData();
return CompilationResult.CompilationComplete;
}
partial void DetermineIfCompilationShouldBeRetried(ref CompilationResult result);
private void PublishCode()
{
var relocs = _codeRelocs.ToArray();
Array.Sort(relocs, (x, y) => (x.Offset - y.Offset));
int alignment = JitConfigProvider.Instance.HasFlag(CorJitFlag.CORJIT_FLAG_SIZE_OPT) ?
_compilation.NodeFactory.Target.MinimumFunctionAlignment :
_compilation.NodeFactory.Target.OptimumFunctionAlignment;
alignment = Math.Max(alignment, _codeAlignment);
var objectData = new ObjectNode.ObjectData(_code,
relocs,
alignment,
new ISymbolDefinitionNode[] { _methodCodeNode });
ObjectNode.ObjectData ehInfo = _ehClauses != null ? EncodeEHInfo() : null;
DebugEHClauseInfo[] debugEHClauseInfos = null;
if (_ehClauses != null)
{
debugEHClauseInfos = new DebugEHClauseInfo[_ehClauses.Length];
for (int i = 0; i < _ehClauses.Length; i++)
{
var clause = _ehClauses[i];
// clause.TryLength returned by the JIT is actually end offset...
// https://github.com/dotnet/runtime/issues/5282
// We subtract offset from "length" to get the actual length.
Debug.Assert(clause.TryLength >= clause.TryOffset);
Debug.Assert(clause.HandlerLength >= clause.HandlerOffset);
debugEHClauseInfos[i] = new DebugEHClauseInfo(clause.TryOffset, clause.TryLength - clause.TryOffset,
clause.HandlerOffset, clause.HandlerLength - clause.HandlerOffset);
}
}
_methodCodeNode.SetCode(objectData);
#if READYTORUN
if (_methodColdCodeNode != null)
{
var relocs2 = _coldCodeRelocs.ToArray();
Array.Sort(relocs2, (x, y) => (x.Offset - y.Offset));
var coldObjectData = new ObjectNode.ObjectData(_coldCode,
relocs2,
alignment,
new ISymbolDefinitionNode[] { _methodColdCodeNode });
_methodColdCodeNode.SetCode(coldObjectData);
_methodCodeNode.ColdCodeNode = _methodColdCodeNode;
}
#endif
_methodCodeNode.InitializeFrameInfos(_frameInfos);
#if READYTORUN
_methodCodeNode.InitializeColdFrameInfos(_coldFrameInfos);
#endif
_methodCodeNode.InitializeDebugEHClauseInfos(debugEHClauseInfos);
_methodCodeNode.InitializeGCInfo(_gcInfo);
_methodCodeNode.InitializeEHInfo(ehInfo);
_methodCodeNode.InitializeDebugLocInfos(_debugLocInfos);
_methodCodeNode.InitializeDebugVarInfos(_debugVarInfos);
#if READYTORUN
MethodDesc[] inlineeArray;
if (_inlinedMethods != null)
{
inlineeArray = new MethodDesc[_inlinedMethods.Count];
_inlinedMethods.CopyTo(inlineeArray);
Array.Sort(inlineeArray, TypeSystemComparer.Instance.Compare);
}
else
{
inlineeArray = Array.Empty<MethodDesc>();
}
_methodCodeNode.InitializeInliningInfo(inlineeArray, _compilation.NodeFactory);
// Detect cases where the instruction set support used is a superset of the baseline instruction set specification
var baselineSupport = _compilation.InstructionSetSupport;
bool needPerMethodInstructionSetFixup = false;
foreach (var instructionSet in _actualInstructionSetSupported)
{
if (!baselineSupport.IsInstructionSetSupported(instructionSet))
{
needPerMethodInstructionSetFixup = true;
}
}
foreach (var instructionSet in _actualInstructionSetUnsupported)
{
if (!baselineSupport.IsInstructionSetExplicitlyUnsupported(instructionSet))
{
needPerMethodInstructionSetFixup = true;
}
}
if (needPerMethodInstructionSetFixup)
{
TargetArchitecture architecture = _compilation.TypeSystemContext.Target.Architecture;
_actualInstructionSetSupported.ExpandInstructionSetByImplication(architecture);
_actualInstructionSetUnsupported.ExpandInstructionSetByReverseImplication(architecture);
_actualInstructionSetUnsupported.Set64BitInstructionSetVariants(architecture);
InstructionSetSupport actualSupport = new InstructionSetSupport(_actualInstructionSetSupported, _actualInstructionSetUnsupported, architecture);
var node = _compilation.SymbolNodeFactory.PerMethodInstructionSetSupportFixup(actualSupport);
AddPrecodeFixup(node);
}
Debug.Assert(_stashedPrecodeFixups.Count == 0);
if (_precodeFixups != null)
{
HashSet<ISymbolNode> computedNodes = new HashSet<ISymbolNode>();
foreach (var fixup in _precodeFixups)
{
if (computedNodes.Add(fixup))
{
if (fixup is IMethodNode methodNode)
{
try
{
_compilation.NodeFactory.DetectGenericCycles(_methodCodeNode.Method, methodNode.Method);
}
catch (TypeLoadException)
{
throw new RequiresRuntimeJitException("Requires runtime JIT - potential generic cycle detected");
}
}
_methodCodeNode.Fixups.Add(fixup);
}
}
}
if (_synthesizedPgoDependencies != null)
{
Debug.Assert(_compilation.NodeFactory.InstrumentationDataTable != null, "Expected InstrumentationDataTable to be non-null with synthesized PGO data to embed");
_compilation.NodeFactory.InstrumentationDataTable.EmbedSynthesizedPgoDataForMethods(ref _additionalDependencies, _synthesizedPgoDependencies);
}
#else
var methodIL = (MethodIL)HandleToObject((void*)_methodScope);
CodeBasedDependencyAlgorithm.AddDependenciesDueToMethodCodePresence(ref _additionalDependencies, _compilation.NodeFactory, MethodBeingCompiled, methodIL);
_methodCodeNode.InitializeDebugInfo(_debugInfo);
LocalVariableDefinition[] locals = methodIL.GetLocals();
TypeDesc[] localTypes = new TypeDesc[locals.Length];
for (int i = 0; i < localTypes.Length; i++)
localTypes[i] = locals[i].Type;
_methodCodeNode.InitializeLocalTypes(localTypes);
#endif
_methodCodeNode.InitializeNonRelocationDependencies(_additionalDependencies);
}
private void PublishROData()
{
if (_roDataBlob == null)
{
return;
}
var relocs = _roDataRelocs.ToArray();
Array.Sort(relocs, (x, y) => (x.Offset - y.Offset));
var objectData = new ObjectNode.ObjectData(_roData,
relocs,
_roDataAlignment,
new ISymbolDefinitionNode[] { _roDataBlob });
_roDataBlob.InitializeData(objectData);
}
private MethodDesc MethodBeingCompiled
{
get
{
return _methodCodeNode.Method;
}
}
private int PointerSize
{
get
{
return _compilation.TypeSystemContext.Target.PointerSize;
}
}
private Dictionary<object, GCHandle> _pins = new Dictionary<object, GCHandle>();
private IntPtr GetPin(object obj)
{
GCHandle handle;
if (!_pins.TryGetValue(obj, out handle))
{
handle = GCHandle.Alloc(obj, GCHandleType.Pinned);
_pins.Add(obj, handle);
}
return handle.AddrOfPinnedObject();
}
private List<IntPtr> _nativeExceptions;
private void CompileMethodCleanup()
{
foreach (var pin in _pins)
pin.Value.Free();
_pins.Clear();
if (_nativeExceptions != null)
{
foreach (IntPtr ex in _nativeExceptions)
FreeException(ex);
_nativeExceptions = null;
}
_methodCodeNode = null;
#if READYTORUN
_methodColdCodeNode = null;
#endif
_code = null;
_coldCode = null;
_roData = null;
_roDataBlob = null;
_codeRelocs = default(ArrayBuilder<Relocation>);
_roDataRelocs = default(ArrayBuilder<Relocation>);
#if READYTORUN
_coldCodeRelocs = default(ArrayBuilder<Relocation>);
#endif
_numFrameInfos = 0;
_usedFrameInfos = 0;
_frameInfos = null;
#if READYTORUN
_numColdFrameInfos = 0;
_usedColdFrameInfos = 0;
_coldFrameInfos = null;
#endif
_gcInfo = null;
_ehClauses = null;
_additionalDependencies = null;
#if !READYTORUN
_debugInfo = null;
#endif
_debugLocInfos = null;
_debugVarInfos = null;
_lastException = null;
#if READYTORUN
_inlinedMethods = null;
_actualInstructionSetSupported = default(InstructionSetFlags);
_actualInstructionSetUnsupported = default(InstructionSetFlags);
_precodeFixups = null;
_stashedPrecodeFixups.Clear();
_stashedInlinedMethods.Clear();
_ilBodiesNeeded = null;
_synthesizedPgoDependencies = null;
#endif
_instantiationToJitVisibleInstantiation = null;
_pgoResults.Clear();
// We need to clear out this cache because the next compilation could actually come up
// with a different MethodIL for the same MethodDesc. This happens when we need to replace
// a MethodIL with a throw helper.
_methodILScopeToHandle.Clear();
}
private Dictionary<object, IntPtr> _objectToHandle = new Dictionary<object, IntPtr>(new JitObjectComparer());
private Dictionary<MethodDesc, IntPtr> _methodILScopeToHandle = new Dictionary<MethodDesc, IntPtr>(new JitObjectComparer());
private List<object> _handleToObject = new List<object>();
private const int handleMultiplier = 8;
private const int handleBase = 0x420000;
#if DEBUG
private static readonly IntPtr s_handleHighBitSet = (sizeof(IntPtr) == 4) ? new IntPtr(0x40000000) : new IntPtr(0x4000000000000000);
#endif
private IntPtr ObjectToHandle(object obj)
{
// MethodILScopes need to go through ObjectToHandle(MethodILScope methodIL).
Debug.Assert(obj is not MethodILScope);
return ObjectToHandleUnchecked(obj);
}
private IntPtr ObjectToHandleUnchecked(object obj)
{
// SuperPMI relies on the handle returned from this function being stable for the lifetime of the crossgen2 process
// If handle deletion is implemented, please update SuperPMI
IntPtr handle;
if (!_objectToHandle.TryGetValue(obj, out handle))
{
handle = (IntPtr)(handleMultiplier * _handleToObject.Count + handleBase);
#if DEBUG
handle = new IntPtr((long)s_handleHighBitSet | (long)handle);
#endif
_handleToObject.Add(obj);
_objectToHandle.Add(obj, handle);
}
return handle;
}
private object HandleToObject(void* handle)
{
#if DEBUG
handle = (void*)(~s_handleHighBitSet & (nint)handle);
#endif
int index = ((int)handle - handleBase) / handleMultiplier;
return _handleToObject[index];
}
private MethodDesc HandleToObject(CORINFO_METHOD_STRUCT_* method) => (MethodDesc)HandleToObject((void*)method);
private CORINFO_METHOD_STRUCT_* ObjectToHandle(MethodDesc method) => (CORINFO_METHOD_STRUCT_*)ObjectToHandle((object)method);
private TypeDesc HandleToObject(CORINFO_CLASS_STRUCT_* type) => (TypeDesc)HandleToObject((void*)type);
private CORINFO_CLASS_STRUCT_* ObjectToHandle(TypeDesc type) => (CORINFO_CLASS_STRUCT_*)ObjectToHandle((object)type);
private FieldDesc HandleToObject(CORINFO_FIELD_STRUCT_* field) => (FieldDesc)HandleToObject((void*)field);
private CORINFO_FIELD_STRUCT_* ObjectToHandle(FieldDesc field) => (CORINFO_FIELD_STRUCT_*)ObjectToHandle((object)field);
private MethodILScope HandleToObject(CORINFO_MODULE_STRUCT_* module) => (MethodIL)HandleToObject((void*)module);
private MethodSignature HandleToObject(MethodSignatureInfo* method) => (MethodSignature)HandleToObject((void*)method);
private MethodSignatureInfo* ObjectToHandle(MethodSignature method) => (MethodSignatureInfo*)ObjectToHandle((object)method);
private CORINFO_MODULE_STRUCT_* ObjectToHandle(MethodILScope methodIL)
{
// RyuJIT requires CORINFO_MODULE_STRUCT to be unique. MethodILScope might not be unique
// due to ILProvider cache purging. See https://github.com/dotnet/runtime/issues/93843.
MethodDesc owningMethod = methodIL.OwningMethod;
if (!_methodILScopeToHandle.TryGetValue(owningMethod, out IntPtr handle))
_methodILScopeToHandle[owningMethod] = handle = ObjectToHandleUnchecked((object)methodIL);
return (CORINFO_MODULE_STRUCT_*)handle;
}
private bool Get_CORINFO_METHOD_INFO(MethodDesc method, MethodIL methodIL, CORINFO_METHOD_INFO* methodInfo)
{
if (methodIL == null)
{
*methodInfo = default(CORINFO_METHOD_INFO);
return false;
}
methodInfo->ftn = ObjectToHandle(method);
methodInfo->scope = ObjectToHandle(methodIL);
var ilCode = methodIL.GetILBytes();
methodInfo->ILCode = (byte*)GetPin(ilCode);
methodInfo->ILCodeSize = (uint)ilCode.Length;
methodInfo->maxStack = (uint)methodIL.MaxStack;
var exceptionRegions = methodIL.GetExceptionRegions();
methodInfo->EHcount = (uint)exceptionRegions.Length;
methodInfo->options = methodIL.IsInitLocals ? CorInfoOptions.CORINFO_OPT_INIT_LOCALS : (CorInfoOptions)0;
if (method.AcquiresInstMethodTableFromThis())
{
methodInfo->options |= CorInfoOptions.CORINFO_GENERICS_CTXT_FROM_THIS;
}
else if (method.RequiresInstMethodDescArg())
{
methodInfo->options |= CorInfoOptions.CORINFO_GENERICS_CTXT_FROM_METHODDESC;
}
else if (method.RequiresInstMethodTableArg())
{
methodInfo->options |= CorInfoOptions.CORINFO_GENERICS_CTXT_FROM_METHODTABLE;
}
methodInfo->regionKind = CorInfoRegionKind.CORINFO_REGION_NONE;
Get_CORINFO_SIG_INFO(method, sig: &methodInfo->args, methodIL);
Get_CORINFO_SIG_INFO(methodIL.GetLocals(), &methodInfo->locals);
return true;
}
private Dictionary<Instantiation, IntPtr[]> _instantiationToJitVisibleInstantiation;
private CORINFO_CLASS_STRUCT_** GetJitInstantiation(Instantiation inst)
{
IntPtr [] jitVisibleInstantiation;
_instantiationToJitVisibleInstantiation ??= new Dictionary<Instantiation, IntPtr[]>();
if (!_instantiationToJitVisibleInstantiation.TryGetValue(inst, out jitVisibleInstantiation))
{
jitVisibleInstantiation = new IntPtr[inst.Length];
for (int i = 0; i < inst.Length; i++)
jitVisibleInstantiation[i] = (IntPtr)ObjectToHandle(inst[i]);
_instantiationToJitVisibleInstantiation.Add(inst, jitVisibleInstantiation);
}
return (CORINFO_CLASS_STRUCT_**)GetPin(jitVisibleInstantiation);
}
private void Get_CORINFO_SIG_INFO(MethodDesc method, CORINFO_SIG_INFO* sig, MethodILScope scope, bool suppressHiddenArgument = false)
{
Get_CORINFO_SIG_INFO(method.Signature, sig, scope);
// Does the method have a hidden parameter?
bool hasHiddenParameter = !suppressHiddenArgument && method.RequiresInstArg();
if (method.IsIntrinsic)
{
// Some intrinsics will beg to differ about the hasHiddenParameter decision
#if !READYTORUN
if (_compilation.TypeSystemContext.IsSpecialUnboxingThunkTargetMethod(method))
hasHiddenParameter = false;
#endif
if (method.IsArrayAddressMethod())
hasHiddenParameter = true;
}
if (hasHiddenParameter)
{
sig->callConv |= CorInfoCallConv.CORINFO_CALLCONV_PARAMTYPE;
}
Instantiation owningTypeInst = method.OwningType.Instantiation;
sig->sigInst.classInstCount = (uint)owningTypeInst.Length;
if (owningTypeInst.Length != 0)
{
sig->sigInst.classInst = GetJitInstantiation(owningTypeInst);
}
sig->sigInst.methInstCount = (uint)method.Instantiation.Length;
if (method.Instantiation.Length != 0)
{
sig->sigInst.methInst = GetJitInstantiation(method.Instantiation);
}
}
private void Get_CORINFO_SIG_INFO(MethodSignature signature, CORINFO_SIG_INFO* sig, MethodILScope scope)
{
sig->callConv = (CorInfoCallConv)(signature.Flags & MethodSignatureFlags.UnmanagedCallingConventionMask);
// Varargs are not supported in .NET Core
if (sig->callConv == CorInfoCallConv.CORINFO_CALLCONV_VARARG)
ThrowHelper.ThrowBadImageFormatException();
if (!signature.IsStatic) sig->callConv |= CorInfoCallConv.CORINFO_CALLCONV_HASTHIS;
if (signature.IsExplicitThis) sig->callConv |= CorInfoCallConv.CORINFO_CALLCONV_EXPLICITTHIS;
TypeDesc returnType = signature.ReturnType;
CorInfoType corInfoRetType = asCorInfoType(signature.ReturnType, &sig->retTypeClass);
sig->_retType = (byte)corInfoRetType;
sig->retTypeSigClass = ObjectToHandle(signature.ReturnType);
#if READYTORUN
ValidateSafetyOfUsingTypeEquivalenceOfType(signature.ReturnType);
#endif
sig->flags = 0; // used by IL stubs code
sig->numArgs = (ushort)signature.Length;
sig->args = (CORINFO_ARG_LIST_STRUCT_*)0; // CORINFO_ARG_LIST_STRUCT_ is argument index
sig->sigInst.classInst = null; // Not used by the JIT
sig->sigInst.classInstCount = 0; // Not used by the JIT
sig->sigInst.methInst = null;
sig->sigInst.methInstCount = (uint)signature.GenericParameterCount;
sig->pSig = null;
sig->cbSig = 0; // Not used by the JIT
sig->methodSignature = ObjectToHandle(signature);
sig->scope = scope is not null ? ObjectToHandle(scope) : null; // scope can be null for internal calls and COM methods.
sig->token = 0; // Not used by the JIT
}
private void Get_CORINFO_SIG_INFO(LocalVariableDefinition[] locals, CORINFO_SIG_INFO* sig)
{
sig->callConv = CorInfoCallConv.CORINFO_CALLCONV_DEFAULT;
sig->_retType = (byte)CorInfoType.CORINFO_TYPE_VOID;
sig->retTypeClass = null;
sig->retTypeSigClass = null;
sig->flags = CorInfoSigInfoFlags.CORINFO_SIGFLAG_IS_LOCAL_SIG;
sig->numArgs = (ushort)locals.Length;
sig->sigInst.classInst = null;
sig->sigInst.classInstCount = 0;
sig->sigInst.methInst = null;
sig->sigInst.methInstCount = 0;
sig->args = (CORINFO_ARG_LIST_STRUCT_*)0; // CORINFO_ARG_LIST_STRUCT_ is argument index
sig->pSig = null;
sig->cbSig = 0; // Not used by the JIT
sig->methodSignature = (MethodSignatureInfo*)ObjectToHandle(locals);
sig->scope = null; // Not used by the JIT
sig->token = 0; // Not used by the JIT
}
private CorInfoType asCorInfoType(TypeDesc type)
{
return asCorInfoType(type, out _);
}
private CorInfoType asCorInfoType(TypeDesc type, out TypeDesc typeIfNotPrimitive)
{
if (type.IsEnum)
{
type = type.UnderlyingType;
}
if (type.IsPrimitive)
{
typeIfNotPrimitive = null;
Debug.Assert((CorInfoType)TypeFlags.Void == CorInfoType.CORINFO_TYPE_VOID);
Debug.Assert((CorInfoType)TypeFlags.Double == CorInfoType.CORINFO_TYPE_DOUBLE);
return (CorInfoType)type.Category;
}
if (type.IsPointer || type.IsFunctionPointer)
{
typeIfNotPrimitive = null;
return CorInfoType.CORINFO_TYPE_PTR;
}
typeIfNotPrimitive = type;
if (type.IsByRef)
{
return CorInfoType.CORINFO_TYPE_BYREF;
}
if (type.IsValueType)
{
if (_compilation.TypeSystemContext.Target.Architecture == TargetArchitecture.X86)
{
LayoutInt elementSize = type.GetElementSize();
#if READYTORUN
if (elementSize.IsIndeterminate)
{
throw new RequiresRuntimeJitException(type);
}
#endif
}
return CorInfoType.CORINFO_TYPE_VALUECLASS;
}
return CorInfoType.CORINFO_TYPE_CLASS;
}
private CorInfoType asCorInfoType(TypeDesc type, CORINFO_CLASS_STRUCT_** structType)
{
var corInfoType = asCorInfoType(type, out TypeDesc typeIfNotPrimitive);
*structType = (typeIfNotPrimitive != null) ? ObjectToHandle(typeIfNotPrimitive) : null;
return corInfoType;
}
private CORINFO_CONTEXT_STRUCT* contextFromMethod(MethodDesc method)
{
return (CORINFO_CONTEXT_STRUCT*)(((nuint)ObjectToHandle(method)) | (nuint)CorInfoContextFlags.CORINFO_CONTEXTFLAGS_METHOD);
}