Welcome to mirror list, hosted at ThFree Co, Russian Federation.

CorInfoImpl.cs « JitInterface « Common « tools « coreclr « src - github.com/dotnet/runtime.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: c5f6ba41139354c1b873ea41fbbe99d3de6a41c9 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
// 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.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;

#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

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,
        }

        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 uint GetMaxIntrinsicSIMDVectorLength(IntPtr jit, CORJIT_FLAGS* flags);

        [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>();

                ComputeJitPgoInstrumentationSchema(LocalObjectToHandle, pgoData, out var nativeSchema, out var instrumentationData);

                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;
            var result = JitCompileMethod(out exception,
                    _jit, (IntPtr)Unsafe.AsPointer(ref _this), _unmanagedCallbacks,
                    ref methodInfo, (uint)CorJitFlag.CORJIT_FLAG_CALL_GETJITFLAGS, out nativeEntry, out codeSize);
            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)
                {
                    // For xarch/arm32, 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];
                    debugEHClauseInfos[i] = new DebugEHClauseInfo(clause.TryOffset, clause.TryLength,
                                                        clause.HandlerOffset, clause.HandlerLength);
                }
            }

#pragma warning disable SA1001, SA1113, SA1115 // Comma should be on the same line as previous parameter
            _methodCodeNode.SetCode(objectData
#if !SUPPORT_JIT && !READYTORUN
                , isFoldable: (_compilation._compilationOptions & RyuJitCompilationOptions.MethodBodyFolding) != 0
#endif
                );
#pragma warning restore SA1001, SA1113, SA1115 // Comma should be on the same line as previous parameter

            _methodCodeNode.InitializeFrameInfos(_frameInfos);
            _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))
                    {
                        _methodCodeNode.Fixups.Add(fixup);
                    }
                }
            }
#else
            var methodIL = (MethodIL)HandleToObject((IntPtr)_methodScope);
            CodeBasedDependencyAlgorithm.AddDependenciesDueToMethodCodePresence(ref _additionalDependencies, _compilation.NodeFactory, MethodBeingCompiled, methodIL);
            _methodCodeNode.InitializeNonRelocationDependencies(_additionalDependencies);
            _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
        }

        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;

            _code = null;
            _coldCode = null;

            _roData = null;
            _roDataBlob = null;

            _codeRelocs = default(ArrayBuilder<Relocation>);
            _roDataRelocs = default(ArrayBuilder<Relocation>);

            _numFrameInfos = 0;
            _usedFrameInfos = 0;
            _frameInfos = null;

            _gcInfo = null;
            _ehClauses = null;

#if !READYTORUN
            _debugInfo = null;

            _additionalDependencies = 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;
#endif

            _instantiationToJitVisibleInstantiation = null;

            _pgoResults.Clear();
        }

        private Dictionary<object, IntPtr> _objectToHandle = new Dictionary<object, IntPtr>();
        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)
        {
            // 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(IntPtr handle)
        {
#if DEBUG
            handle = new IntPtr(~(long)s_handleHighBitSet & (long) handle);
#endif
            int index = ((int)handle - handleBase) / handleMultiplier;
            return _handleToObject[index];
        }

        private MethodDesc HandleToObject(CORINFO_METHOD_STRUCT_* method) => (MethodDesc)HandleToObject((IntPtr)method);
        private CORINFO_METHOD_STRUCT_* ObjectToHandle(MethodDesc method) => (CORINFO_METHOD_STRUCT_*)ObjectToHandle((object)method);
        private TypeDesc HandleToObject(CORINFO_CLASS_STRUCT_* type) => (TypeDesc)HandleToObject((IntPtr)type);
        private CORINFO_CLASS_STRUCT_* ObjectToHandle(TypeDesc type) => (CORINFO_CLASS_STRUCT_*)ObjectToHandle((object)type);
        private FieldDesc HandleToObject(CORINFO_FIELD_STRUCT_* field) => (FieldDesc)HandleToObject((IntPtr)field);
        private CORINFO_FIELD_STRUCT_* ObjectToHandle(FieldDesc field) => (CORINFO_FIELD_STRUCT_*)ObjectToHandle((object)field);
        private MethodILScope HandleToObject(CORINFO_MODULE_STRUCT_* module) => (MethodIL)HandleToObject((IntPtr)module);
        private CORINFO_MODULE_STRUCT_* ObjectToHandle(MethodILScope methodIL) => (CORINFO_MODULE_STRUCT_*)ObjectToHandle((object)methodIL);
        private MethodSignature HandleToObject(MethodSignatureInfo* method) => (MethodSignature)HandleToObject((IntPtr)method);
        private MethodSignatureInfo* ObjectToHandle(MethodSignature method) => (MethodSignatureInfo*)ObjectToHandle((object)method);

        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;

                // We only populate sigInst for intrinsic methods because most of the time,
                // JIT doesn't care what the instantiation is and this is expensive.
                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);
                }
            }

            if (hasHiddenParameter)
            {
                sig->callConv |= CorInfoCallConv.CORINFO_CALLCONV_PARAMTYPE;
            }
        }

        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;

            TypeDesc returnType = signature.ReturnType;

            CorInfoType corInfoRetType = asCorInfoType(signature.ReturnType, &sig->retTypeClass);
            sig->_retType = (byte)corInfoRetType;
            sig->retTypeSigClass = ObjectToHandle(signature.ReturnType);

            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; // Not used by the JIT
            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*)(((ulong)ObjectToHandle(method)) | (ulong)CorInfoContextFlags.CORINFO_CONTEXTFLAGS_METHOD);
        }

        private CORINFO_CONTEXT_STRUCT* contextFromType(TypeDesc type)
        {
            return (CORINFO_CONTEXT_STRUCT*)(((ulong)ObjectToHandle(type)) | (ulong)CorInfoContextFlags.CORINFO_CONTEXTFLAGS_CLASS);
        }

        private static CORINFO_CONTEXT_STRUCT* contextFromMethodBeingCompiled()
        {
            return (CORINFO_CONTEXT_STRUCT*)1;
        }

        private MethodDesc methodFromContext(CORINFO_CONTEXT_STRUCT* contextStruct)
        {
            if (contextStruct == contextFromMethodBeingCompiled())
            {
                return MethodBeingCompiled;
            }

            if (((ulong)contextStruct & (ulong)CorInfoContextFlags.CORINFO_CONTEXTFLAGS_MASK) == (ulong)CorInfoContextFlags.CORINFO_CONTEXTFLAGS_CLASS)
            {
                return null;
            }
            else
            {
                return HandleToObject((CORINFO_METHOD_STRUCT_*)((ulong)contextStruct & ~(ulong)CorInfoContextFlags.CORINFO_CONTEXTFLAGS_MASK));
            }
        }

        private TypeDesc typeFromContext(CORINFO_CONTEXT_STRUCT* contextStruct)
        {
            if (contextStruct == contextFromMethodBeingCompiled())
            {
                return MethodBeingCompiled.OwningType;
            }

            if (((ulong)contextStruct & (ulong)CorInfoContextFlags.CORINFO_CONTEXTFLAGS_MASK) == (ulong)CorInfoContextFlags.CORINFO_CONTEXTFLAGS_CLASS)
            {
                return HandleToObject((CORINFO_CLASS_STRUCT_*)((ulong)contextStruct & ~(ulong)CorInfoContextFlags.CORINFO_CONTEXTFLAGS_MASK));
            }
            else
            {
                return HandleToObject((CORINFO_METHOD_STRUCT_*)((ulong)contextStruct & ~(ulong)CorInfoContextFlags.CORINFO_CONTEXTFLAGS_MASK)).OwningType;
            }
        }

        private TypeSystemEntity entityFromContext(CORINFO_CONTEXT_STRUCT* contextStruct)
        {
            if (contextStruct == contextFromMethodBeingCompiled())
            {
                return MethodBeingCompiled.HasInstantiation ? (TypeSystemEntity)MethodBeingCompiled: (TypeSystemEntity)MethodBeingCompiled.OwningType;
            }

            return (TypeSystemEntity)HandleToObject((IntPtr)((ulong)contextStruct & ~(ulong)CorInfoContextFlags.CORINFO_CONTEXTFLAGS_MASK));
        }

        private bool isIntrinsic(CORINFO_METHOD_STRUCT_* ftn)
        {
            MethodDesc method = HandleToObject(ftn);
            return method.IsIntrinsic || HardwareIntrinsicHelpers.IsHardwareIntrinsic(method);
        }

        private uint getMethodAttribsInternal(MethodDesc method)
        {
            CorInfoFlag result = 0;

            // CORINFO_FLG_PROTECTED - verification only

            if (method.Signature.IsStatic)
                result |= CorInfoFlag.CORINFO_FLG_STATIC;

            if (method.IsSynchronized)
                result |= CorInfoFlag.CORINFO_FLG_SYNCH;
            if (method.IsIntrinsic)
                result |= CorInfoFlag.CORINFO_FLG_INTRINSIC;
            if (method.IsVirtual)
                result |= CorInfoFlag.CORINFO_FLG_VIRTUAL;
            if (method.IsAbstract)
                result |= CorInfoFlag.CORINFO_FLG_ABSTRACT;
            if (method.IsConstructor || method.IsStaticConstructor)
                result |= CorInfoFlag.CORINFO_FLG_CONSTRUCTOR;

            //
            // See if we need to embed a .cctor call at the head of the
            // method body.
            //

            // method or class might have the final bit
            if (_compilation.IsEffectivelySealed(method))
                result |= CorInfoFlag.CORINFO_FLG_FINAL;

            if (method.IsSharedByGenericInstantiations)
                result |= CorInfoFlag.CORINFO_FLG_SHAREDINST;

            if (method.IsPInvoke)
                result |= CorInfoFlag.CORINFO_FLG_PINVOKE;

#if READYTORUN
            if (method.RequireSecObject)
            {
                result |= CorInfoFlag.CORINFO_FLG_DONT_INLINE_CALLER;
            }
#endif

            if (method.IsAggressiveOptimization)
            {
                result |= CorInfoFlag.CORINFO_FLG_AGGRESSIVE_OPT;
            }

            // TODO: Cache inlining hits
            // Check for an inlining directive.

            if (method.IsNoInlining)
            {
                /* Function marked as not inlineable */
                result |= CorInfoFlag.CORINFO_FLG_DONT_INLINE;
            }
            else if (method.IsAggressiveInlining)
            {
                result |= CorInfoFlag.CORINFO_FLG_FORCEINLINE;
            }

            if (method.OwningType.IsDelegate && method.Name == "Invoke")
            {
                // This is now used to emit efficient invoke code for any delegate invoke,
                // including multicast.
                result |= CorInfoFlag.CORINFO_FLG_DELEGATE_INVOKE;

                // RyuJIT special cases this method; it would assert if it's not final
                // and we might not have set the bit in the code above.
                result |= CorInfoFlag.CORINFO_FLG_FINAL;
            }

#if READYTORUN
            // Check for SIMD intrinsics
            if (method.Context.Target.MaximumSimdVectorLength == SimdVectorLength.None)
            {
                DefType owningDefType = method.OwningType as DefType;
                if (owningDefType != null && VectorOfTFieldLayoutAlgorithm.IsVectorOfTType(owningDefType))
                {
                    throw new RequiresRuntimeJitException("This function is using SIMD intrinsics, their size is machine specific");
                }
            }
#endif

            // Check for hardware intrinsics
            if (HardwareIntrinsicHelpers.IsHardwareIntrinsic(method))
            {
                result |= CorInfoFlag.CORINFO_FLG_INTRINSIC;
            }

            // Internal calls typically turn into fcalls that do not always
            // probe for GC. Be conservative here and always let JIT know that
            // this method may not do GC checks so the JIT might need to make
            // callers fully interruptible.
            if (method.IsInternalCall)
            {
                result |= CorInfoFlag.CORINFO_FLG_NOGCCHECK;
            }

            return (uint)result;
        }

#pragma warning disable CA1822 // Mark members as static
        private void setMethodAttribs(CORINFO_METHOD_STRUCT_* ftn, CorInfoMethodRuntimeFlags attribs)
#pragma warning restore CA1822 // Mark members as static
        {
            // TODO: Inlining
        }

        private void getMethodSig(CORINFO_METHOD_STRUCT_* ftn, CORINFO_SIG_INFO* sig, CORINFO_CLASS_STRUCT_* memberParent)
        {
            MethodDesc method = HandleToObject(ftn);

            // There might be a more concrete parent type specified - this can happen when inlining.
            if (memberParent != null)
            {
                TypeDesc type = HandleToObject(memberParent);

                // Typically, the owning type of the method is a canonical type and the member parent
                // supplied by RyuJIT is a concrete instantiation.
                if (type != method.OwningType)
                {
                    Debug.Assert(type.HasSameTypeDefinition(method.OwningType));
                    Instantiation methodInst = method.Instantiation;
                    method = _compilation.TypeSystemContext.GetMethodForInstantiatedType(method.GetTypicalMethodDefinition(), (InstantiatedType)type);
                    if (methodInst.Length > 0)
                    {
                        method = method.MakeInstantiatedMethod(methodInst);
                    }
                }
            }

            Get_CORINFO_SIG_INFO(method, sig: sig, scope: null);
        }

        private bool getMethodInfo(CORINFO_METHOD_STRUCT_* ftn, CORINFO_METHOD_INFO* info)
        {
            MethodDesc method = HandleToObject(ftn);
#if READYTORUN
            // Add an early CanInline check to see if referring to the IL of the target methods is
            // permitted from within this MethodBeingCompiled, the full CanInline check will be performed
            // later.
            if (!_compilation.CanInline(MethodBeingCompiled, method))
                return false;
#endif
            MethodIL methodIL = _compilation.GetMethodIL(method);
            return Get_CORINFO_METHOD_INFO(method, methodIL, info);
        }

        private CorInfoInline canInline(CORINFO_METHOD_STRUCT_* callerHnd, CORINFO_METHOD_STRUCT_* calleeHnd)
        {
            MethodDesc callerMethod = HandleToObject(callerHnd);
            MethodDesc calleeMethod = HandleToObject(calleeHnd);

            if (_compilation.CanInline(callerMethod, calleeMethod))
            {
                // No restrictions on inlining
                return CorInfoInline.INLINE_PASS;
            }
            else
            {
                // Call may not be inlined
                return CorInfoInline.INLINE_NEVER;
            }
        }

#pragma warning disable CA1822 // Mark members as static
        private void reportTailCallDecision(CORINFO_METHOD_STRUCT_* callerHnd, CORINFO_METHOD_STRUCT_* calleeHnd, bool fIsTailPrefix, CorInfoTailCall tailCallResult, byte* reason)
#pragma warning restore CA1822 // Mark members as static
        {
        }

        private void getEHinfo(CORINFO_METHOD_STRUCT_* ftn, uint EHnumber, ref CORINFO_EH_CLAUSE clause)
        {
            var methodIL = _compilation.GetMethodIL(HandleToObject(ftn));

            var ehRegion = methodIL.GetExceptionRegions()[EHnumber];

            clause.Flags = (CORINFO_EH_CLAUSE_FLAGS)ehRegion.Kind;
            clause.TryOffset = (uint)ehRegion.TryOffset;
            clause.TryLength = (uint)ehRegion.TryLength;
            clause.HandlerOffset = (uint)ehRegion.HandlerOffset;
            clause.HandlerLength = (uint)ehRegion.HandlerLength;
            clause.ClassTokenOrOffset = (uint)((ehRegion.Kind == ILExceptionRegionKind.Filter) ? ehRegion.FilterOffset : ehRegion.ClassToken);
        }

        private CORINFO_CLASS_STRUCT_* getMethodClass(CORINFO_METHOD_STRUCT_* method)
        {
            var m = HandleToObject(method);
            return ObjectToHandle(m.OwningType);
        }

        private CORINFO_MODULE_STRUCT_* getMethodModule(CORINFO_METHOD_STRUCT_* method)
        {
            MethodDesc m = HandleToObject(method);
            if (m is UnboxingMethodDesc unboxingMethodDesc)
            {
                m = unboxingMethodDesc.Target;
            }

            MethodIL methodIL = _compilation.GetMethodIL(m);
            if (methodIL == null)
            {
                return null;
            }
            return ObjectToHandle(methodIL);
        }

        private bool resolveVirtualMethod(CORINFO_DEVIRTUALIZATION_INFO* info)
        {
            // Initialize OUT fields
            info->devirtualizedMethod = null;
            info->requiresInstMethodTableArg = false;
            info->exactContext = null;
            info->detail = CORINFO_DEVIRTUALIZATION_DETAIL.CORINFO_DEVIRTUALIZATION_UNKNOWN;

            TypeDesc objType = HandleToObject(info->objClass);

            // __Canon cannot be devirtualized
            if (objType.IsCanonicalDefinitionType(CanonicalFormKind.Any))
            {
                info->detail = CORINFO_DEVIRTUALIZATION_DETAIL.CORINFO_DEVIRTUALIZATION_FAILED_CANON;
                return false;
            }

            MethodDesc decl = HandleToObject(info->virtualMethod);
            Debug.Assert(!decl.HasInstantiation);

            if ((info->context != null) && decl.OwningType.IsInterface)
            {
                TypeDesc ownerTypeDesc = typeFromContext(info->context);
                if (decl.OwningType != ownerTypeDesc)
                {
                    Debug.Assert(ownerTypeDesc is InstantiatedType);
                    decl = _compilation.TypeSystemContext.GetMethodForInstantiatedType(decl.GetTypicalMethodDefinition(), (InstantiatedType)ownerTypeDesc);
                }
            }

            MethodDesc originalImpl = _compilation.ResolveVirtualMethod(decl, objType, out info->detail);

            if (originalImpl == null)
            {
                // If this assert fires, we failed to devirtualize, probably due to a failure to resolve the
                // virtual to an exact target. This should never happen in practice if the input IL is valid,
                // and the algorithm for virtual function resolution is correct; however, if it does, this is
                // a safe condition, and we could delete this assert. This assert exists in order to help identify
                // cases where the virtual function resolution algorithm either does not function, or is not used
                // correctly.
#if DEBUG
                if (info->detail == CORINFO_DEVIRTUALIZATION_DETAIL.CORINFO_DEVIRTUALIZATION_UNKNOWN)
                {
                    Console.Error.WriteLine($"Failed devirtualization with unexpected unknown failure while compiling {MethodBeingCompiled} with decl {decl} targeting type {objType}");
                    Debug.Assert(info->detail != CORINFO_DEVIRTUALIZATION_DETAIL.CORINFO_DEVIRTUALIZATION_UNKNOWN);
                }
#endif
                return false;
            }

            TypeDesc owningType = originalImpl.OwningType;

            // RyuJIT expects to get the canonical form back
            MethodDesc impl = originalImpl.GetCanonMethodTarget(CanonicalFormKind.Specific);

            bool unboxingStub = impl.OwningType.IsValueType;

            MethodDesc nonUnboxingImpl = impl;
            if (unboxingStub)
            {
                impl = getUnboxingThunk(impl);
            }

#if READYTORUN
            // As there are a variety of situations where the resolved virtual method may be different at compile and runtime (primarily due to subtle differences
            // in the virtual resolution algorithm between the runtime and the compiler, although details such as whether or not type equivalence is enabled
            // can also have an effect), record any decisions made, and if there are differences, simply skip use of the compiled method.
            var resolver = _compilation.NodeFactory.Resolver;

            MethodWithToken methodWithTokenDecl;

            if (info->pResolvedTokenVirtualMethod != null)
            {
                methodWithTokenDecl = ComputeMethodWithToken(decl, ref *info->pResolvedTokenVirtualMethod, null, false);
            }
            else
            {
                ModuleToken declToken = resolver.GetModuleTokenForMethod(decl.GetTypicalMethodDefinition(), allowDynamicallyCreatedReference: false, throwIfNotFound: false);
                if (declToken.IsNull)
                {
                    info->detail = CORINFO_DEVIRTUALIZATION_DETAIL.CORINFO_DEVIRTUALIZATION_FAILED_DECL_NOT_REPRESENTABLE;
                    return false;
                }
                if (!_compilation.CompilationModuleGroup.VersionsWithTypeReference(decl.OwningType))
                {
                    info->detail = CORINFO_DEVIRTUALIZATION_DETAIL.CORINFO_DEVIRTUALIZATION_FAILED_DECL_NOT_REPRESENTABLE;
                    return false;
                }
                methodWithTokenDecl = new MethodWithToken(decl, declToken, null, false, null, devirtualizedMethodOwner: decl.OwningType);
            }
            MethodWithToken methodWithTokenImpl;
#endif

            if (decl == originalImpl)
            {
#if READYTORUN
                methodWithTokenImpl = methodWithTokenDecl;
#endif
                if (info->pResolvedTokenVirtualMethod != null)
                {
                    info->resolvedTokenDevirtualizedMethod = *info->pResolvedTokenVirtualMethod;
                }
                else
                {
                    info->resolvedTokenDevirtualizedMethod = CreateResolvedTokenFromMethod(this, decl
#if READYTORUN
                        , methodWithTokenDecl
#endif
                        );
                }
                info->resolvedTokenDevirtualizedUnboxedMethod = default(CORINFO_RESOLVED_TOKEN);
            }
            else
            {
#if READYTORUN
                methodWithTokenImpl = new MethodWithToken(nonUnboxingImpl, resolver.GetModuleTokenForMethod(nonUnboxingImpl.GetTypicalMethodDefinition(), allowDynamicallyCreatedReference: false, throwIfNotFound: true), null, unboxingStub, null, devirtualizedMethodOwner: impl.OwningType);
#endif

                info->resolvedTokenDevirtualizedMethod = CreateResolvedTokenFromMethod(this, impl
#if READYTORUN
                    , methodWithTokenImpl
#endif
                    );

                if (unboxingStub)
                {
                    info->resolvedTokenDevirtualizedUnboxedMethod = info->resolvedTokenDevirtualizedMethod;
                    info->resolvedTokenDevirtualizedUnboxedMethod.tokenContext = contextFromMethod(nonUnboxingImpl);
                    info->resolvedTokenDevirtualizedUnboxedMethod.hMethod = ObjectToHandle(nonUnboxingImpl);
                }
                else
                {
                    info->resolvedTokenDevirtualizedUnboxedMethod = default(CORINFO_RESOLVED_TOKEN);
                }
            }

#if READYTORUN
            // Testing has not shown that concerns about virtual matching are significant
            // Only generate verification for builds with the stress mode enabled
            if (_compilation.SymbolNodeFactory.VerifyTypeAndFieldLayout)
            {
                ISymbolNode virtualResolutionNode = _compilation.SymbolNodeFactory.CheckVirtualFunctionOverride(methodWithTokenDecl, objType, methodWithTokenImpl);
                AddPrecodeFixup(virtualResolutionNode);
            }
#endif
            info->detail = CORINFO_DEVIRTUALIZATION_DETAIL.CORINFO_DEVIRTUALIZATION_SUCCESS;
            info->devirtualizedMethod = ObjectToHandle(impl);
            info->requiresInstMethodTableArg = false;
            info->exactContext = contextFromType(owningType);

            return true;

            static CORINFO_RESOLVED_TOKEN CreateResolvedTokenFromMethod(CorInfoImpl jitInterface, MethodDesc method
#if READYTORUN
                , MethodWithToken methodWithToken
#endif
                )
            {
#if !READYTORUN
                MethodDesc unboxedMethodDesc = method.IsUnboxingThunk() ? method.GetUnboxedMethod() : method;
                var methodWithToken = new
                {
                    Method = unboxedMethodDesc,
                    OwningType = unboxedMethodDesc.OwningType,
                };
#endif

                CORINFO_RESOLVED_TOKEN result = default(CORINFO_RESOLVED_TOKEN);
                MethodILScope scope = jitInterface._compilation.GetMethodIL(methodWithToken.Method);
                scope ??= EcmaMethodILScope.Create((EcmaMethod)methodWithToken.Method.GetTypicalMethodDefinition());
                result.tokenScope = jitInterface.ObjectToHandle(scope);
                result.tokenContext = jitInterface.contextFromMethod(method);
#if READYTORUN
                result.token = methodWithToken.Token.Token;
                if (methodWithToken.Token.TokenType != CorTokenType.mdtMethodDef)
                {
                    Debug.Assert(false); // This should never happen, but we protect against total failure with the throw below.
                    throw new RequiresRuntimeJitException("Attempt to devirtualize and unable to create token for devirtualized method");
                }
#else
                result.token = (mdToken)0x06BAAAAD;
#endif
                result.tokenType = CorInfoTokenKind.CORINFO_TOKENKIND_DevirtualizedMethod;
                result.hClass = jitInterface.ObjectToHandle(methodWithToken.OwningType);
                result.hMethod = jitInterface.ObjectToHandle(method);

                return result;
            }
        }

        private CORINFO_METHOD_STRUCT_* getUnboxedEntry(CORINFO_METHOD_STRUCT_* ftn, ref bool requiresInstMethodTableArg)
        {
            MethodDesc result = null;
            requiresInstMethodTableArg = false;

            MethodDesc method = HandleToObject(ftn);
            if (method.IsUnboxingThunk())
            {
                result = method.GetUnboxedMethod();
                requiresInstMethodTableArg = method.RequiresInstMethodTableArg();
            }

            return result != null ? ObjectToHandle(result) : null;
        }

        private CORINFO_CLASS_STRUCT_* getDefaultComparerClass(CORINFO_CLASS_STRUCT_* elemType)
        {
            TypeDesc comparand = HandleToObject(elemType);
            TypeDesc comparer = IL.Stubs.ComparerIntrinsics.GetComparerForType(comparand);
            return comparer != null ? ObjectToHandle(comparer) : null;
        }

        private CORINFO_CLASS_STRUCT_* getDefaultEqualityComparerClass(CORINFO_CLASS_STRUCT_* elemType)
        {
            TypeDesc comparand = HandleToObject(elemType);
            TypeDesc comparer = IL.Stubs.ComparerIntrinsics.GetEqualityComparerForType(comparand);
            return comparer != null ? ObjectToHandle(comparer) : null;
        }

        private bool isIntrinsicType(CORINFO_CLASS_STRUCT_* classHnd)
        {
            TypeDesc type = HandleToObject(classHnd);
            return type.IsIntrinsic;
        }

        private CorInfoCallConvExtension getUnmanagedCallConv(CORINFO_METHOD_STRUCT_* method, CORINFO_SIG_INFO* sig, ref bool pSuppressGCTransition)
        {
            pSuppressGCTransition = false;

            if (method != null)
            {
                MethodDesc methodDesc = HandleToObject(method);
                CorInfoCallConvExtension callConv = GetUnmanagedCallConv(HandleToObject(method), out pSuppressGCTransition);
                return callConv;
            }
            else
            {
                Debug.Assert(sig != null);

                CorInfoCallConvExtension callConv = GetUnmanagedCallConv(HandleToObject(sig->methodSignature), out pSuppressGCTransition);
                return callConv;
            }
        }
        private static CorInfoCallConvExtension GetUnmanagedCallConv(MethodDesc methodDesc, out bool suppressGCTransition)
        {
            UnmanagedCallingConventions callingConventions;

            if ((methodDesc.Signature.Flags & MethodSignatureFlags.UnmanagedCallingConventionMask) == 0)
            {
                if (methodDesc.IsPInvoke)
                {
                    callingConventions = methodDesc.GetPInvokeMethodCallingConventions();
                }
                else
                {
                    Debug.Assert(methodDesc.IsUnmanagedCallersOnly);
                    callingConventions = methodDesc.GetUnmanagedCallersOnlyMethodCallingConventions();
                }
            }
            else
            {
                callingConventions = methodDesc.Signature.GetStandaloneMethodSignatureCallingConventions();
            }

            return ToCorInfoCallConvExtension(callingConventions, out suppressGCTransition);
        }

        private static CorInfoCallConvExtension GetUnmanagedCallConv(MethodSignature signature, out bool suppressGCTransition)
        {
            return ToCorInfoCallConvExtension(signature.GetStandaloneMethodSignatureCallingConventions(), out suppressGCTransition);
        }

        private static CorInfoCallConvExtension ToCorInfoCallConvExtension(UnmanagedCallingConventions callConvs, out bool suppressGCTransition)
        {
            CorInfoCallConvExtension result;
            switch (callConvs & UnmanagedCallingConventions.CallingConventionMask)
            {
                case UnmanagedCallingConventions.Cdecl:
                    result = CorInfoCallConvExtension.C;
                    break;
                case UnmanagedCallingConventions.Stdcall:
                    result = CorInfoCallConvExtension.Stdcall;
                    break;
                case UnmanagedCallingConventions.Thiscall:
                    result = CorInfoCallConvExtension.Thiscall;
                    break;
                case UnmanagedCallingConventions.Fastcall:
                    result = CorInfoCallConvExtension.Fastcall;
                    break;
                default:
                    ThrowHelper.ThrowInvalidProgramException();
                    result = CorInfoCallConvExtension.Managed; // unreachable
                    break;
            }

            if ((callConvs & UnmanagedCallingConventions.IsMemberFunction) != 0)
            {
                result = result switch
                {
                    CorInfoCallConvExtension.C => CorInfoCallConvExtension.CMemberFunction,
                    CorInfoCallConvExtension.Stdcall => CorInfoCallConvExtension.StdcallMemberFunction,
                    CorInfoCallConvExtension.Fastcall => CorInfoCallConvExtension.FastcallMemberFunction,
                    _ => result,
                };
            }

            suppressGCTransition = (callConvs & UnmanagedCallingConventions.IsSuppressGcTransition) != 0;

            return result;
        }

        private bool satisfiesMethodConstraints(CORINFO_CLASS_STRUCT_* parent, CORINFO_METHOD_STRUCT_* method)
        { throw new NotImplementedException("satisfiesMethodConstraints"); }
        private bool isCompatibleDelegate(CORINFO_CLASS_STRUCT_* objCls, CORINFO_CLASS_STRUCT_* methodParentCls, CORINFO_METHOD_STRUCT_* method, CORINFO_CLASS_STRUCT_* delegateCls, ref bool pfIsOpenDelegate)
        { throw new NotImplementedException("isCompatibleDelegate"); }
        private void setPatchpointInfo(PatchpointInfo* patchpointInfo)
        { throw new NotImplementedException("setPatchpointInfo"); }
        private PatchpointInfo* getOSRInfo(ref uint ilOffset)
        { throw new NotImplementedException("getOSRInfo"); }

#pragma warning disable CA1822 // Mark members as static
        private void methodMustBeLoadedBeforeCodeIsRun(CORINFO_METHOD_STRUCT_* method)
#pragma warning restore CA1822 // Mark members as static
        {
        }

        private CORINFO_METHOD_STRUCT_* mapMethodDeclToMethodImpl(CORINFO_METHOD_STRUCT_* method)
        { throw new NotImplementedException("mapMethodDeclToMethodImpl"); }

        private static object ResolveTokenWithSubstitution(MethodILScope methodIL, mdToken token, Instantiation typeInst, Instantiation methodInst)
        {
            // Grab the generic definition of the method IL, resolve the token within the definition,
            // and instantiate it with the given context.
            object result = methodIL.GetMethodILScopeDefinition().GetObject((int)token);

            if (result is MethodDesc methodResult)
            {
                result = methodResult.InstantiateSignature(typeInst, methodInst);
            }
            else if (result is FieldDesc fieldResult)
            {
                result = fieldResult.InstantiateSignature(typeInst, methodInst);
            }
            else
            {
                result = ((TypeDesc)result).InstantiateSignature(typeInst, methodInst);
            }

            return result;
        }

        private static object ResolveTokenInScope(MethodILScope methodIL, object typeOrMethodContext, mdToken token)
        {
            MethodDesc owningMethod = methodIL.OwningMethod;

            // If token context differs from the scope, it means we're inlining.
            // If we're inlining a shared method body, we might be able to un-share
            // the referenced token and avoid runtime lookups.
            // Resolve the token in the inlining context.

            object result;
            if (owningMethod != typeOrMethodContext &&
                owningMethod.IsCanonicalMethod(CanonicalFormKind.Any))
            {
                Instantiation methodInst = default;

                Instantiation typeInst;
                if (typeOrMethodContext is TypeDesc typeContext)
                {
                    Debug.Assert(typeContext.HasSameTypeDefinition(owningMethod.OwningType) || typeContext.IsArray);
                    typeInst = typeContext.Instantiation;
                }
                else
                {
                    var methodContext = (MethodDesc)typeOrMethodContext;
                    // Allow cases where the method's do not have instantiations themselves, if
                    // 1. The method defining the context is generic, but the target method is not
                    // 2. Both methods are not generic
                    // 3. The methods are the same generic
                    // AND
                    // The methods are on the same type
                    Debug.Assert((methodContext.HasInstantiation && !owningMethod.HasInstantiation) ||
                        (!methodContext.HasInstantiation && !owningMethod.HasInstantiation) ||
                        methodContext.GetTypicalMethodDefinition() == owningMethod.GetTypicalMethodDefinition() ||
                        (owningMethod.Name == "CreateDefaultInstance" && methodContext.Name == "CreateInstance"));
                    Debug.Assert(methodContext.OwningType.HasSameTypeDefinition(owningMethod.OwningType));
                    typeInst = methodContext.OwningType.Instantiation;
                    methodInst = methodContext.Instantiation;
                }

                result = ResolveTokenWithSubstitution(methodIL, token, typeInst, methodInst);
            }
            else
            {
                // Not inlining - just resolve the token within the methodIL
                result = methodIL.GetObject((int)token);
            }

            return result;
        }

        private object GetRuntimeDeterminedObjectForToken(ref CORINFO_RESOLVED_TOKEN pResolvedToken)
        {
            // Since RyuJIT operates on canonical types (as opposed to runtime determined ones), but the
            // dependency analysis operates on runtime determined ones, we convert the resolved token
            // to the runtime determined form (e.g. Foo<__Canon> becomes Foo<T__Canon>).

            var methodIL = HandleToObject(pResolvedToken.tokenScope);

            var typeOrMethodContext = (pResolvedToken.tokenContext == contextFromMethodBeingCompiled()) ?
                MethodBeingCompiled : HandleToObject((IntPtr)pResolvedToken.tokenContext);

            object result = GetRuntimeDeterminedObjectForToken(methodIL, typeOrMethodContext, pResolvedToken.token);
            if (pResolvedToken.tokenType == CorInfoTokenKind.CORINFO_TOKENKIND_Newarr)
                result = ((TypeDesc)result).MakeArrayType();

            return result;
        }

        private static object GetRuntimeDeterminedObjectForToken(MethodILScope methodIL, object typeOrMethodContext, mdToken token)
        {
            object result = ResolveTokenInScope(methodIL, typeOrMethodContext, token);

            if (result is MethodDesc method)
            {
                if (method.IsSharedByGenericInstantiations)
                {
                    MethodDesc sharedMethod = methodIL.OwningMethod.GetSharedRuntimeFormMethodTarget();
                    result = ResolveTokenWithSubstitution(methodIL, token, sharedMethod.OwningType.Instantiation, sharedMethod.Instantiation);
                    Debug.Assert(((MethodDesc)result).IsRuntimeDeterminedExactMethod);
                }
            }
            else if (result is FieldDesc field)
            {
                if (field.OwningType.IsCanonicalSubtype(CanonicalFormKind.Any))
                {
                    MethodDesc sharedMethod = methodIL.OwningMethod.GetSharedRuntimeFormMethodTarget();
                    result = ResolveTokenWithSubstitution(methodIL, token, sharedMethod.OwningType.Instantiation, sharedMethod.Instantiation);
                    Debug.Assert(((FieldDesc)result).OwningType.IsRuntimeDeterminedSubtype);
                }
            }
            else
            {
                TypeDesc type = (TypeDesc)result;
                if (type.IsCanonicalSubtype(CanonicalFormKind.Any))
                {
                    MethodDesc sharedMethod = methodIL.OwningMethod.GetSharedRuntimeFormMethodTarget();
                    result = ResolveTokenWithSubstitution(methodIL, token, sharedMethod.OwningType.Instantiation, sharedMethod.Instantiation);
                    Debug.Assert(((TypeDesc)result).IsRuntimeDeterminedSubtype ||
                        /* If the resolved type is not runtime determined there's a chance we went down this path
                           because there was a literal typeof(__Canon) in the compiled IL - check for that
                           by resolving the token in the definition. */
                        ((TypeDesc)methodIL.GetMethodILScopeDefinition().GetObject((int)token)).IsCanonicalDefinitionType(CanonicalFormKind.Any));
                }
            }

            return result;
        }

        private void resolveToken(ref CORINFO_RESOLVED_TOKEN pResolvedToken)
        {
            var methodIL = HandleToObject(pResolvedToken.tokenScope);

            var typeOrMethodContext = (pResolvedToken.tokenContext == contextFromMethodBeingCompiled()) ?
                MethodBeingCompiled : HandleToObject((IntPtr)pResolvedToken.tokenContext);

            object result = ResolveTokenInScope(methodIL, typeOrMethodContext, pResolvedToken.token);

            pResolvedToken.hClass = null;
            pResolvedToken.hMethod = null;
            pResolvedToken.hField = null;

#if READYTORUN
            TypeDesc owningType = methodIL.OwningMethod.GetTypicalMethodDefinition().OwningType;
            bool recordToken;
            if (!_compilation.CompilationModuleGroup.VersionsWithMethodBody(methodIL.OwningMethod.GetTypicalMethodDefinition()))
            {
                recordToken = (methodIL.GetMethodILScopeDefinition() is IMethodTokensAreUseableInCompilation) && owningType is EcmaType;
            }
            else
            {
                recordToken = (_compilation.CompilationModuleGroup.VersionsWithType(owningType) || _compilation.CompilationModuleGroup.CrossModuleInlineableType(owningType)) && owningType is EcmaType;
            }
#endif

            if (result is MethodDesc method)
            {
                pResolvedToken.hMethod = ObjectToHandle(method);

                TypeDesc owningClass = method.OwningType;
                pResolvedToken.hClass = ObjectToHandle(owningClass);

#if !SUPPORT_JIT
                _compilation.TypeSystemContext.EnsureLoadableMethod(method);
#endif

#if READYTORUN
                if (recordToken)
                {
                    ModuleToken methodModuleToken = HandleToModuleToken(ref pResolvedToken);
                    var resolver = _compilation.NodeFactory.Resolver;
                    resolver.AddModuleTokenForMethod(method, methodModuleToken);
                }
#else
                _compilation.NodeFactory.MetadataManager.GetDependenciesDueToAccess(ref _additionalDependencies, _compilation.NodeFactory, (MethodIL)methodIL, method);
#endif
            }
            else
            if (result is FieldDesc)
            {
                FieldDesc field = result as FieldDesc;

                // References to literal fields from IL body should never resolve.
                // The CLR would throw a MissingFieldException while jitting and so should we.
                if (field.IsLiteral)
                    ThrowHelper.ThrowMissingFieldException(field.OwningType, field.Name);

                pResolvedToken.hField = ObjectToHandle(field);

                TypeDesc owningClass = field.OwningType;
                pResolvedToken.hClass = ObjectToHandle(owningClass);

#if !SUPPORT_JIT
                _compilation.TypeSystemContext.EnsureLoadableType(owningClass);
#endif

#if !READYTORUN
                _compilation.NodeFactory.MetadataManager.GetDependenciesDueToAccess(ref _additionalDependencies, _compilation.NodeFactory, (MethodIL)methodIL, field);
#endif
            }
            else
            {
                TypeDesc type = (TypeDesc)result;

#if READYTORUN
                if (recordToken)
                {
                    _compilation.NodeFactory.Resolver.AddModuleTokenForType(type, HandleToModuleToken(ref pResolvedToken));
                }
#endif

                if (pResolvedToken.tokenType == CorInfoTokenKind.CORINFO_TOKENKIND_Newarr)
                {
                    if (type.IsVoid)
                        ThrowHelper.ThrowInvalidProgramException(ExceptionStringID.InvalidProgramSpecific, methodIL.OwningMethod);

                    type = type.MakeArrayType();
                }
                pResolvedToken.hClass = ObjectToHandle(type);

#if !SUPPORT_JIT
                _compilation.TypeSystemContext.EnsureLoadableType(type);
#endif
            }

            pResolvedToken.pTypeSpec = null;
            pResolvedToken.cbTypeSpec = 0;
            pResolvedToken.pMethodSpec = null;
            pResolvedToken.cbMethodSpec = 0;
        }

        private bool tryResolveToken(ref CORINFO_RESOLVED_TOKEN pResolvedToken)
        {
            resolveToken(ref pResolvedToken);
            return true;
        }

        private void findSig(CORINFO_MODULE_STRUCT_* module, uint sigTOK, CORINFO_CONTEXT_STRUCT* context, CORINFO_SIG_INFO* sig)
        {
            var methodIL = HandleToObject(module);
            var methodSig = (MethodSignature)methodIL.GetObject((int)sigTOK);

            Get_CORINFO_SIG_INFO(methodSig, sig, methodIL);

#if !READYTORUN
            // Check whether we need to report this as a fat pointer call
            if (_compilation.IsFatPointerCandidate(methodIL.OwningMethod, methodSig))
            {
                sig->flags |= CorInfoSigInfoFlags.CORINFO_SIGFLAG_FAT_CALL;
            }
#else
            VerifyMethodSignatureIsStable(methodSig);
#endif
        }

        private void findCallSiteSig(CORINFO_MODULE_STRUCT_* module, uint methTOK, CORINFO_CONTEXT_STRUCT* context, CORINFO_SIG_INFO* sig)
        {
            var methodIL = HandleToObject(module);
            Get_CORINFO_SIG_INFO(((MethodDesc)methodIL.GetObject((int)methTOK)), sig: sig, methodIL);
        }

        private CORINFO_CLASS_STRUCT_* getTokenTypeAsHandle(ref CORINFO_RESOLVED_TOKEN pResolvedToken)
        {
            WellKnownType result = WellKnownType.RuntimeTypeHandle;

            if (pResolvedToken.hMethod != null)
            {
                result = WellKnownType.RuntimeMethodHandle;
            }
            else
            if (pResolvedToken.hField != null)
            {
                result = WellKnownType.RuntimeFieldHandle;
            }

            return ObjectToHandle(_compilation.TypeSystemContext.GetWellKnownType(result));
        }

        private static CorInfoCanSkipVerificationResult canSkipVerification(CORINFO_MODULE_STRUCT_* module)
        {
            return CorInfoCanSkipVerificationResult.CORINFO_VERIFICATION_CAN_SKIP;
        }

        private bool isValidToken(CORINFO_MODULE_STRUCT_* module, uint metaTOK)
        { throw new NotImplementedException("isValidToken"); }
        private bool isValidStringRef(CORINFO_MODULE_STRUCT_* module, uint metaTOK)
        { throw new NotImplementedException("isValidStringRef"); }

        private int getStringLiteral(CORINFO_MODULE_STRUCT_* module, uint metaTOK, char* buffer, int size)
        {
            Debug.Assert(size >= 0);

            MethodILScope methodIL = HandleToObject(module);
            string str = (string)methodIL.GetObject((int)metaTOK);

            if (buffer != null)
            {
                // Copy str's content to buffer
                str.AsSpan(0, Math.Min(size, str.Length)).CopyTo(new Span<char>(buffer, size));
            }
            return str.Length;
        }

        private CorInfoType asCorInfoType(CORINFO_CLASS_STRUCT_* cls)
        {
            var type = HandleToObject(cls);
            return asCorInfoType(type);
        }

        private byte* getClassName(CORINFO_CLASS_STRUCT_* cls)
        {
            var type = HandleToObject(cls);
            StringBuilder nameBuilder = new StringBuilder();
            TypeString.Instance.AppendName(nameBuilder, type);
            return (byte*)GetPin(StringToUTF8(nameBuilder.ToString()));
        }

        private byte* getClassNameFromMetadata(CORINFO_CLASS_STRUCT_* cls, byte** namespaceName)
        {
            var type = HandleToObject(cls) as MetadataType;
            if (type != null)
            {
                if (namespaceName != null)
                    *namespaceName = (byte*)GetPin(StringToUTF8(type.Namespace));
                return (byte*)GetPin(StringToUTF8(type.Name));
            }

            if (namespaceName != null)
                *namespaceName = null;
            return null;
        }

        private CORINFO_CLASS_STRUCT_* getTypeInstantiationArgument(CORINFO_CLASS_STRUCT_* cls, uint index)
        {
            TypeDesc type = HandleToObject(cls);
            Instantiation inst = type.Instantiation;

            return index < (uint)inst.Length ? ObjectToHandle(inst[(int)index]) : null;
        }


        private int appendClassName(char** ppBuf, ref int pnBufLen, CORINFO_CLASS_STRUCT_* cls, bool fNamespace, bool fFullInst, bool fAssembly)
        {
            // We support enough of this to make SIMD work, but not much else.

            Debug.Assert(fNamespace && !fFullInst && !fAssembly);

            var type = HandleToObject(cls);
            string name = TypeString.Instance.FormatName(type);

            int length = name.Length;
            if (pnBufLen > 0)
            {
                char* buffer = *ppBuf;
                int lengthToCopy = Math.Min(name.Length, pnBufLen);
                for (int i = 0; i < lengthToCopy; i++)
                    buffer[i] = name[i];
                if (name.Length < pnBufLen)
                {
                    buffer[name.Length] = (char)0;
                }
                else
                {
                    buffer[pnBufLen - 1] = (char)0;
                    lengthToCopy -= 1;
                }

                pnBufLen -= lengthToCopy;
                *ppBuf = buffer + lengthToCopy;
            }

            return length;
        }

        private bool isValueClass(CORINFO_CLASS_STRUCT_* cls)
        {
            return HandleToObject(cls).IsValueType;
        }

#pragma warning disable CA1822 // Mark members as static
        private CorInfoInlineTypeCheck canInlineTypeCheck(CORINFO_CLASS_STRUCT_* cls, CorInfoInlineTypeCheckSource source)
#pragma warning restore CA1822 // Mark members as static
        {
            // TODO: when we support multiple modules at runtime, this will need to do more work
            // NOTE: cls can be null
            return CorInfoInlineTypeCheck.CORINFO_INLINE_TYPECHECK_PASS;
        }

        private uint getClassAttribs(CORINFO_CLASS_STRUCT_* cls)
        {
            TypeDesc type = HandleToObject(cls);
            return getClassAttribsInternal(type);
        }

        private uint getClassAttribsInternal(TypeDesc type)
        {
            // TODO: Support for verification (CORINFO_FLG_GENERIC_TYPE_VARIABLE)

            CorInfoFlag result = (CorInfoFlag)0;

            var metadataType = type as MetadataType;

            // The array flag is used to identify the faked-up methods on
            // array types, i.e. .ctor, Get, Set and Address
            if (type.IsArray)
                result |= CorInfoFlag.CORINFO_FLG_ARRAY;

            if (type.IsInterface)
                result |= CorInfoFlag.CORINFO_FLG_INTERFACE;

            if (type.IsArray || type.IsString)
                result |= CorInfoFlag.CORINFO_FLG_VAROBJSIZE;

            if (type.IsValueType)
            {
                result |= CorInfoFlag.CORINFO_FLG_VALUECLASS;

                if (metadataType.IsByRefLike)
                    result |= CorInfoFlag.CORINFO_FLG_BYREF_LIKE;

                // The CLR has more complicated rules around CUSTOMLAYOUT, but this will do.
                if (metadataType.IsExplicitLayout || (metadataType.IsSequentialLayout && metadataType.GetClassLayout().Size != 0) || metadataType.IsWellKnownType(WellKnownType.TypedReference))
                    result |= CorInfoFlag.CORINFO_FLG_CUSTOMLAYOUT;

                if (metadataType.IsUnsafeValueType)
                    result |= CorInfoFlag.CORINFO_FLG_UNSAFE_VALUECLASS;
            }

            if (type.IsCanonicalSubtype(CanonicalFormKind.Any))
                result |= CorInfoFlag.CORINFO_FLG_SHAREDINST;

            if (type.HasVariance)
                result |= CorInfoFlag.CORINFO_FLG_VARIANCE;

            if (type.IsDelegate)
                result |= CorInfoFlag.CORINFO_FLG_DELEGATE;

            if (_compilation.IsEffectivelySealed(type))
                result |= CorInfoFlag.CORINFO_FLG_FINAL;

            if (type.IsIntrinsic)
                result |= CorInfoFlag.CORINFO_FLG_INTRINSIC_TYPE;

            if (metadataType != null)
            {
                if (metadataType.ContainsGCPointers)
                    result |= CorInfoFlag.CORINFO_FLG_CONTAINS_GC_PTR;

                if (metadataType.IsBeforeFieldInit)
                    result |= CorInfoFlag.CORINFO_FLG_BEFOREFIELDINIT;

                // Assume overlapping fields for explicit layout.
                if (metadataType.IsExplicitLayout)
                    result |= CorInfoFlag.CORINFO_FLG_OVERLAPPING_FIELDS;

                if (metadataType.IsAbstract)
                    result |= CorInfoFlag.CORINFO_FLG_ABSTRACT;
            }

#if READYTORUN
            if (!_compilation.CompilationModuleGroup.VersionsWithType(type))
            {
                // Prevent the JIT from drilling into types outside of the current versioning bubble
                result |= CorInfoFlag.CORINFO_FLG_DONT_DIG_FIELDS;
                result &= ~CorInfoFlag.CORINFO_FLG_BEFOREFIELDINIT;
            }
#endif

            return (uint)result;
        }

        private CORINFO_MODULE_STRUCT_* getClassModule(CORINFO_CLASS_STRUCT_* cls)
        { throw new NotImplementedException("getClassModule"); }
        private CORINFO_ASSEMBLY_STRUCT_* getModuleAssembly(CORINFO_MODULE_STRUCT_* mod)
        { throw new NotImplementedException("getModuleAssembly"); }
        private byte* getAssemblyName(CORINFO_ASSEMBLY_STRUCT_* assem)
        { throw new NotImplementedException("getAssemblyName"); }

#pragma warning disable CA1822 // Mark members as static
        private void* LongLifetimeMalloc(UIntPtr sz)
#pragma warning restore CA1822 // Mark members as static
        {
            return (void*)Marshal.AllocCoTaskMem((int)sz);
        }

#pragma warning disable CA1822 // Mark members as static
        private void LongLifetimeFree(void* obj)
#pragma warning restore CA1822 // Mark members as static
        {
            Marshal.FreeCoTaskMem((IntPtr)obj);
        }

        private UIntPtr getClassModuleIdForStatics(CORINFO_CLASS_STRUCT_* cls, CORINFO_MODULE_STRUCT_** pModule, void** ppIndirection)
        { throw new NotImplementedException("getClassModuleIdForStatics"); }

        private uint getClassSize(CORINFO_CLASS_STRUCT_* cls)
        {
            TypeDesc type = HandleToObject(cls);
            LayoutInt classSize = type.GetElementSize();
#if READYTORUN
            if (classSize.IsIndeterminate)
            {
                throw new RequiresRuntimeJitException(type);
            }

            if (NeedsTypeLayoutCheck(type))
            {
                ISymbolNode node = _compilation.SymbolNodeFactory.CheckTypeLayout(type);
                AddPrecodeFixup(node);
            }
#endif
            return (uint)classSize.AsInt;
        }

        private uint getHeapClassSize(CORINFO_CLASS_STRUCT_* cls)
        {
            TypeDesc type = HandleToObject(cls);

            Debug.Assert(!type.IsValueType);
            Debug.Assert(type.IsDefType);
            Debug.Assert(!type.IsString);
#if READYTORUN
            Debug.Assert(_compilation.IsInheritanceChainLayoutFixedInCurrentVersionBubble(type));
#endif

            return (uint)((DefType)type).InstanceByteCount.AsInt;
        }

        private bool canAllocateOnStack(CORINFO_CLASS_STRUCT_* cls)
        {
            TypeDesc type = HandleToObject(cls);

            Debug.Assert(!type.IsValueType);
            Debug.Assert(type.IsDefType);

            bool result = !type.HasFinalizer;

#if READYTORUN
            if (!_compilation.IsInheritanceChainLayoutFixedInCurrentVersionBubble(type))
                result = false;
#endif

            return result;
        }

        /// <summary>
        /// Managed implementation of CEEInfo::getClassAlignmentRequirementStatic
        /// </summary>
        public static int GetClassAlignmentRequirementStatic(DefType type)
        {
            int alignment = type.Context.Target.PointerSize;

            if (type is MetadataType metadataType && metadataType.HasLayout())
            {
                if (metadataType.IsSequentialLayout || MarshalUtils.IsBlittableType(metadataType))
                {
                    alignment = metadataType.InstanceFieldAlignment.AsInt;
                }
            }

            if (type.Context.Target.Architecture == TargetArchitecture.ARM &&
                alignment < 8 && type.RequiresAlign8())
            {
                // If the structure contains 64-bit primitive fields and the platform requires 8-byte alignment for
                // such fields then make sure we return at least 8-byte alignment. Note that it's technically possible
                // to create unmanaged APIs that take unaligned structures containing such fields and this
                // unconditional alignment bump would cause us to get the calling convention wrong on platforms such
                // as ARM. If we see such cases in the future we'd need to add another control (such as an alignment
                // property for the StructLayout attribute or a marshaling directive attribute for p/invoke arguments)
                // that allows more precise control. For now we'll go with the likely scenario.
                alignment = 8;
            }

            return alignment;
        }

        private Dictionary<DefType, bool> _doubleAlignHeuristicCache = new Dictionary<DefType, bool>();

        //*******************************************************************************
        //
        // Heuristic to determine if we should have instances of this class 8 byte aligned
        //
        private static bool ShouldAlign8(int dwR8Fields, int dwTotalFields)
        {
            return dwR8Fields*2>dwTotalFields && dwR8Fields>=2;
        }

        private static bool ShouldAlign8(DefType type)
        {
            int instanceFields = 0;
            int doubleFields = 0;
            var doubleType = type.Context.GetWellKnownType(WellKnownType.Double);
            foreach (var field in type.GetFields())
            {
                if (field.IsStatic)
                    continue;

                instanceFields++;

                if (field.FieldType == doubleType)
                    doubleFields++;
            }

            return ShouldAlign8(doubleFields, instanceFields);
        }

        private uint getClassAlignmentRequirement(CORINFO_CLASS_STRUCT_* cls, bool fDoubleAlignHint)
        {
            DefType type = (DefType)HandleToObject(cls);


            var target = type.Context.Target;
            if (fDoubleAlignHint)
            {
                if (target.Architecture == TargetArchitecture.X86)
                {
                    if ((type.IsValueType) && (type.InstanceFieldAlignment.AsInt > 4))
                    {
                        // On X86, double aligning the stack is expensive. if fDoubleAlignHint is true
                        // only align the local variable if it has a large enough fraction of double fields
                        // in comparison to the total field count.
                        if (!_doubleAlignHeuristicCache.TryGetValue(type, out bool doDoubleAlign))
                        {
                            doDoubleAlign = ShouldAlign8(type);
                            _doubleAlignHeuristicCache.Add(type, doDoubleAlign);
                        }

                        // Return the size of the double align hint. Ignore the actual alignment info account
                        // so that structs with 64-bit integer fields do not trigger double aligned frames on x86.
                        if (doDoubleAlign)
                            return 8;
                    }

                    return (uint)target.PointerSize;
                }
            }

            return (uint)GetClassAlignmentRequirementStatic(type);
        }

        private int MarkGcField(byte* gcPtrs, CorInfoGCType gcType)
        {
            // Ensure that if we have multiple fields with the same offset,
            // that we don't double count the data in the gc layout.
            if (*gcPtrs == (byte)CorInfoGCType.TYPE_GC_NONE)
            {
                *gcPtrs = (byte)gcType;
                return 1;
            }
            else
            {
                Debug.Assert(*gcPtrs == (byte)gcType);
                return 0;
            }
        }

        private int GatherClassGCLayout(TypeDesc type, byte* gcPtrs)
        {
            int result = 0;

            foreach (var field in type.GetFields())
            {
                if (field.IsStatic)
                    continue;

                CorInfoGCType gcType = CorInfoGCType.TYPE_GC_NONE;

                var fieldType = field.FieldType;
                if (fieldType.IsValueType)
                {
                    var fieldDefType = (DefType)fieldType;
                    if (!fieldDefType.ContainsGCPointers && !fieldDefType.IsByRefLike)
                        continue;

                    gcType = CorInfoGCType.TYPE_GC_OTHER;
                }
                else if (fieldType.IsGCPointer)
                {
                    gcType = CorInfoGCType.TYPE_GC_REF;
                }
                else if (fieldType.IsByRef)
                {
                    gcType = CorInfoGCType.TYPE_GC_BYREF;
                }
                else
                {
                    continue;
                }

                Debug.Assert(field.Offset.AsInt % PointerSize == 0);
                byte* fieldGcPtrs = gcPtrs + field.Offset.AsInt / PointerSize;

                if (gcType == CorInfoGCType.TYPE_GC_OTHER)
                {
                    result += GatherClassGCLayout(fieldType, fieldGcPtrs);
                }
                else
                {
                    result += MarkGcField(fieldGcPtrs, gcType);
                }
            }
            return result;
        }

        private uint getClassGClayout(CORINFO_CLASS_STRUCT_* cls, byte* gcPtrs)
        {
            uint result = 0;

            DefType type = (DefType)HandleToObject(cls);

            int pointerSize = PointerSize;

            int ptrsCount = AlignmentHelper.AlignUp(type.InstanceFieldSize.AsInt, pointerSize) / pointerSize;

            // Assume no GC pointers at first
            for (int i = 0; i < ptrsCount; i++)
                gcPtrs[i] = (byte)CorInfoGCType.TYPE_GC_NONE;

            if (type.ContainsGCPointers || type.IsByRefLike)
            {
                result = (uint)GatherClassGCLayout(type, gcPtrs);
            }
            return result;
        }

        private uint getClassNumInstanceFields(CORINFO_CLASS_STRUCT_* cls)
        {
            TypeDesc type = HandleToObject(cls);

            uint result = 0;
            foreach (var field in type.GetFields())
            {
                if (!field.IsStatic)
                    result++;
            }

            return result;
        }

        private CORINFO_FIELD_STRUCT_* getFieldInClass(CORINFO_CLASS_STRUCT_* clsHnd, int num)
        {
            TypeDesc classWithFields = HandleToObject(clsHnd);

            int iCurrentFoundField = -1;
            foreach (var field in classWithFields.GetFields())
            {
                if (field.IsStatic)
                    continue;

                ++iCurrentFoundField;
                if (iCurrentFoundField == num)
                {
                    return ObjectToHandle(field);
                }
            }

            // We could not find the field that was searched for.
            throw new InvalidOperationException();
        }

        private bool checkMethodModifier(CORINFO_METHOD_STRUCT_* hMethod, byte* modifier, bool fOptional)
        { throw new NotImplementedException("checkMethodModifier"); }

        private CorInfoHelpFunc getSharedCCtorHelper(CORINFO_CLASS_STRUCT_* clsHnd)
        { throw new NotImplementedException("getSharedCCtorHelper"); }

        private CORINFO_CLASS_STRUCT_* getTypeForBox(CORINFO_CLASS_STRUCT_* cls)
        {
            var type = HandleToObject(cls);

            var typeForBox = type.IsNullable ? type.Instantiation[0] : type;

            return ObjectToHandle(typeForBox);
        }

        private CorInfoHelpFunc getBoxHelper(CORINFO_CLASS_STRUCT_* cls)
        {
            var type = HandleToObject(cls);

            if (type.IsByRefLike)
                ThrowHelper.ThrowInvalidProgramException(ExceptionStringID.InvalidProgramSpecific, MethodBeingCompiled);

            return type.IsNullable ? CorInfoHelpFunc.CORINFO_HELP_BOX_NULLABLE : CorInfoHelpFunc.CORINFO_HELP_BOX;
        }

        private CorInfoHelpFunc getUnBoxHelper(CORINFO_CLASS_STRUCT_* cls)
        {
            var type = HandleToObject(cls);

            return type.IsNullable ? CorInfoHelpFunc.CORINFO_HELP_UNBOX_NULLABLE : CorInfoHelpFunc.CORINFO_HELP_UNBOX;
        }

        private byte* getHelperName(CorInfoHelpFunc helpFunc)
        {
            return (byte*)GetPin(StringToUTF8(helpFunc.ToString()));
        }

        private CorInfoInitClassResult initClass(CORINFO_FIELD_STRUCT_* field, CORINFO_METHOD_STRUCT_* method, CORINFO_CONTEXT_STRUCT* context)
        {
            FieldDesc fd = field == null ? null : HandleToObject(field);
            Debug.Assert(fd == null || fd.IsStatic);

            MethodDesc md = method == null ? MethodBeingCompiled : HandleToObject(method);
            TypeDesc type = fd != null ? fd.OwningType : typeFromContext(context);

            if (
#if READYTORUN
                IsClassPreInited(type)
#else
                _isFallbackBodyCompilation ||
                !_compilation.HasLazyStaticConstructor(type)
#endif
                )
            {
                return CorInfoInitClassResult.CORINFO_INITCLASS_NOT_REQUIRED;
            }

            MetadataType typeToInit = (MetadataType)type;

            if (fd == null)
            {
                if (typeToInit.IsBeforeFieldInit)
                {
                    // We can wait for field accesses to run .cctor
                    return CorInfoInitClassResult.CORINFO_INITCLASS_NOT_REQUIRED;
                }

                // Run .cctor on statics & constructors
                if (md.Signature.IsStatic)
                {
                    // Except don't class construct on .cctor - it would be circular
                    if (md.IsStaticConstructor)
                    {
                        return CorInfoInitClassResult.CORINFO_INITCLASS_NOT_REQUIRED;
                    }
                }
                else if (!md.IsConstructor && !typeToInit.IsValueType && !typeToInit.IsInterface)
                {
                    // According to the spec, we should be able to do this optimization for both reference and valuetypes.
                    // To maintain backward compatibility, we are doing it for reference types only.
                    // We don't do this for interfaces though, as those don't have instance constructors.
                    // For instance methods of types with precise-initialization
                    // semantics, we can assume that the .ctor triggered the
                    // type initialization.
                    // This does not hold for NULL "this" object. However, the spec does
                    // not require that case to work.
                    return CorInfoInitClassResult.CORINFO_INITCLASS_NOT_REQUIRED;
                }
            }

            if (typeToInit.IsCanonicalSubtype(CanonicalFormKind.Any))
            {
                if (fd == null && method != null && context == contextFromMethodBeingCompiled())
                {
                    // If we're inling a call to a method in our own type, then we should already
                    // have triggered the .cctor when caller was itself called.
                    return CorInfoInitClassResult.CORINFO_INITCLASS_NOT_REQUIRED;
                }

                // Shared generic code has to use helper. Moreover, tell JIT not to inline since
                // inlining of generic dictionary lookups is not supported.
                return CorInfoInitClassResult.CORINFO_INITCLASS_USE_HELPER | CorInfoInitClassResult.CORINFO_INITCLASS_DONT_INLINE;
            }

            //
            // Try to prove that the initialization is not necessary because of nesting
            //

            if (fd == null)
            {
                // Handled above
                Debug.Assert(!typeToInit.IsBeforeFieldInit);

                if (method != null && typeToInit == MethodBeingCompiled.OwningType)
                {
                    // If we're inling a call to a method in our own type, then we should already
                    // have triggered the .cctor when caller was itself called.
                    return CorInfoInitClassResult.CORINFO_INITCLASS_NOT_REQUIRED;
                }
            }
            else
            {
                // This optimization may cause static fields in reference types to be accessed without cctor being triggered
                // for NULL "this" object. It does not conform with what the spec says. However, we have been historically
                // doing it for perf reasons.
                if (!typeToInit.IsValueType && !typeToInit.IsInterface && !typeToInit.IsBeforeFieldInit)
                {
                    if (typeToInit == typeFromContext(context) || typeToInit == MethodBeingCompiled.OwningType)
                    {
                        // The class will be initialized by the time we access the field.
                        return CorInfoInitClassResult.CORINFO_INITCLASS_NOT_REQUIRED;
                    }
                }

                // If we are currently compiling the class constructor for this static field access then we can skip the initClass
                if (MethodBeingCompiled.OwningType == typeToInit && MethodBeingCompiled.IsStaticConstructor)
                {
                    // The class will be initialized by the time we access the field.
                    return CorInfoInitClassResult.CORINFO_INITCLASS_NOT_REQUIRED;
                }
            }

            return CorInfoInitClassResult.CORINFO_INITCLASS_USE_HELPER;
        }

        private CORINFO_CLASS_STRUCT_* getBuiltinClass(CorInfoClassId classId)
        {
            switch (classId)
            {
                case CorInfoClassId.CLASSID_SYSTEM_OBJECT:
                    return ObjectToHandle(_compilation.TypeSystemContext.GetWellKnownType(WellKnownType.Object));

                case CorInfoClassId.CLASSID_TYPED_BYREF:
                    return ObjectToHandle(_compilation.TypeSystemContext.GetWellKnownType(WellKnownType.TypedReference));

                case CorInfoClassId.CLASSID_TYPE_HANDLE:
                    return ObjectToHandle(_compilation.TypeSystemContext.GetWellKnownType(WellKnownType.RuntimeTypeHandle));

                case CorInfoClassId.CLASSID_FIELD_HANDLE:
                    return ObjectToHandle(_compilation.TypeSystemContext.GetWellKnownType(WellKnownType.RuntimeFieldHandle));

                case CorInfoClassId.CLASSID_METHOD_HANDLE:
                    return ObjectToHandle(_compilation.TypeSystemContext.GetWellKnownType(WellKnownType.RuntimeMethodHandle));

                case CorInfoClassId.CLASSID_ARGUMENT_HANDLE:
                    ThrowHelper.ThrowTypeLoadException("System", "RuntimeArgumentHandle", _compilation.TypeSystemContext.SystemModule);
                    return null;

                case CorInfoClassId.CLASSID_STRING:
                    return ObjectToHandle(_compilation.TypeSystemContext.GetWellKnownType(WellKnownType.String));

                case CorInfoClassId.CLASSID_RUNTIME_TYPE:
                    return ObjectToHandle(_compilation.TypeSystemContext.SystemModule.GetKnownType("System", "RuntimeType"));

                default:
                    throw new NotImplementedException();
            }
        }

        private CorInfoType getTypeForPrimitiveValueClass(CORINFO_CLASS_STRUCT_* cls)
        {
            var type = HandleToObject(cls);

            if (!type.IsPrimitive && !type.IsEnum)
                return CorInfoType.CORINFO_TYPE_UNDEF;

            return asCorInfoType(type);
        }

        private CorInfoType getTypeForPrimitiveNumericClass(CORINFO_CLASS_STRUCT_* cls)
        {
            var type = HandleToObject(cls);

            if (type.IsPrimitiveNumeric)
                return asCorInfoType(type);

            return CorInfoType.CORINFO_TYPE_UNDEF;
        }

        private bool canCast(CORINFO_CLASS_STRUCT_* child, CORINFO_CLASS_STRUCT_* parent)
        { throw new NotImplementedException("canCast"); }
        private bool areTypesEquivalent(CORINFO_CLASS_STRUCT_* cls1, CORINFO_CLASS_STRUCT_* cls2)
        { throw new NotImplementedException("areTypesEquivalent"); }

        private TypeCompareState compareTypesForCast(CORINFO_CLASS_STRUCT_* fromClass, CORINFO_CLASS_STRUCT_* toClass)
        {
            TypeDesc fromType = HandleToObject(fromClass);
            TypeDesc toType = HandleToObject(toClass);

            TypeCompareState result = TypeCompareState.May;

            if (fromType.IsIDynamicInterfaceCastable)
            {
                result = TypeCompareState.May;
            }
            else if (toType.IsNullable)
            {
                // If casting to Nullable<T>, don't try to optimize
                result = TypeCompareState.May;
            }
            else if (!fromType.IsCanonicalSubtype(CanonicalFormKind.Any) && !toType.IsCanonicalSubtype(CanonicalFormKind.Any))
            {
                // If the types are not shared, we can check directly.
                if (fromType.CanCastTo(toType))
                    result = TypeCompareState.Must;
                else
                    result = TypeCompareState.MustNot;
            }
            else if (fromType.IsCanonicalSubtype(CanonicalFormKind.Any) && !toType.IsCanonicalSubtype(CanonicalFormKind.Any))
            {
                // Casting from a shared type to an unshared type.
                // Only handle casts to interface types for now
                if (toType.IsInterface)
                {
                    // Do a preliminary check.
                    bool canCast = fromType.CanCastTo(toType);

                    // Pass back positive results unfiltered. The unknown type
                    // parameters in fromClass did not come into play.
                    if (canCast)
                    {
                        result = TypeCompareState.Must;
                    }
                    // We have __Canon parameter(s) in fromClass, somewhere.
                    //
                    // In CanCastTo, these __Canon(s) won't match the interface or
                    // instantiated types on the interface, so CanCastTo may
                    // return false negatives.
                    //
                    // Only report MustNot if the fromClass is not __Canon
                    // and the interface is not instantiated; then there is
                    // no way for the fromClass __Canon(s) to confuse things.
                    //
                    //    __Canon       -> IBar             May
                    //    IFoo<__Canon> -> IFoo<string>     May
                    //    IFoo<__Canon> -> IBar             MustNot
                    //
                    else if (fromType.IsCanonicalDefinitionType(CanonicalFormKind.Any))
                    {
                        result = TypeCompareState.May;
                    }
                    else if (toType.HasInstantiation)
                    {
                        result = TypeCompareState.May;
                    }
                    else
                    {
                        result = TypeCompareState.MustNot;
                    }
                }
            }

#if READYTORUN
            // In R2R it is a breaking change for a previously positive
            // cast to become negative, but not for a previously negative
            // cast to become positive. So in R2R a negative result is
            // always reported back as May.
            if (result == TypeCompareState.MustNot)
            {
                result = TypeCompareState.May;
            }
#endif

            return result;
        }

        private TypeCompareState compareTypesForEquality(CORINFO_CLASS_STRUCT_* cls1, CORINFO_CLASS_STRUCT_* cls2)
        {
            TypeCompareState result = TypeCompareState.May;

            TypeDesc type1 = HandleToObject(cls1);
            TypeDesc type2 = HandleToObject(cls2);

            // If neither type is a canonical subtype, type handle comparison suffices
            if (!type1.IsCanonicalSubtype(CanonicalFormKind.Any) && !type2.IsCanonicalSubtype(CanonicalFormKind.Any))
            {
                result = (type1 == type2 ? TypeCompareState.Must : TypeCompareState.MustNot);
            }
            // If either or both types are canonical subtypes, we can sometimes prove inequality.
            else
            {
                // If either is a value type then the types cannot
                // be equal unless the type defs are the same.
                if (type1.IsValueType || type2.IsValueType)
                {
                    if (!type1.IsCanonicalDefinitionType(CanonicalFormKind.Universal) && !type2.IsCanonicalDefinitionType(CanonicalFormKind.Universal))
                    {
                        if (!type1.HasSameTypeDefinition(type2))
                        {
                            result = TypeCompareState.MustNot;
                        }
                    }
                }
                // If we have two ref types that are not __Canon, then the
                // types cannot be equal unless the type defs are the same.
                else
                {
                    if (!type1.IsCanonicalDefinitionType(CanonicalFormKind.Any) && !type2.IsCanonicalDefinitionType(CanonicalFormKind.Any))
                    {
                        if (!type1.HasSameTypeDefinition(type2))
                        {
                            result = TypeCompareState.MustNot;
                        }
                    }
                }
            }

            return result;
        }

        private CORINFO_CLASS_STRUCT_* mergeClasses(CORINFO_CLASS_STRUCT_* cls1, CORINFO_CLASS_STRUCT_* cls2)
        {
            TypeDesc type1 = HandleToObject(cls1);
            TypeDesc type2 = HandleToObject(cls2);

            TypeDesc merged = TypeExtensions.MergeTypesToCommonParent(type1, type2);

#if DEBUG
            // Make sure the merge is reflexive in the cases we "support".
            TypeDesc reflexive = TypeExtensions.MergeTypesToCommonParent(type2, type1);

            // If both sides are classes than either they have a common non-interface parent (in which case it is
            // reflexive)
            // OR they share a common interface, and it can be order dependent (if they share multiple interfaces
            // in common)
            if (!type1.IsInterface && !type2.IsInterface)
            {
                if (merged.IsInterface)
                {
                    Debug.Assert(reflexive.IsInterface);
                }
                else
                {
                    Debug.Assert(merged == reflexive);
                }
            }
            // Both results must either be interfaces or classes.  They cannot be mixed.
            Debug.Assert(merged.IsInterface == reflexive.IsInterface);

            // If the result of the merge was a class, then the result of the reflexive merge was the same class.
            if (!merged.IsInterface)
            {
                Debug.Assert(merged == reflexive);
            }

            // If both sides are arrays, then the result is either an array or g_pArrayClass.  The above is
            // actually true for reference types as well, but it is a little excessive to deal with.
            if (type1.IsArray && type2.IsArray)
            {
                TypeDesc arrayClass = _compilation.TypeSystemContext.GetWellKnownType(WellKnownType.Array);
                Debug.Assert((merged.IsArray && reflexive.IsArray)
                         || ((merged == arrayClass) && (reflexive == arrayClass)));
            }

            // The results must always be assignable
            Debug.Assert(type1.CanCastTo(merged) && type2.CanCastTo(merged) && type1.CanCastTo(reflexive)
                     && type2.CanCastTo(reflexive));
#endif

            return ObjectToHandle(merged);
        }

        private bool isMoreSpecificType(CORINFO_CLASS_STRUCT_* cls1, CORINFO_CLASS_STRUCT_* cls2)
        {
            TypeDesc type1 = HandleToObject(cls1);
            TypeDesc type2 = HandleToObject(cls2);

            // If we have a mixture of shared and unshared types,
            // consider the unshared type as more specific.
            bool isType1CanonSubtype = type1.IsCanonicalSubtype(CanonicalFormKind.Any);
            bool isType2CanonSubtype = type2.IsCanonicalSubtype(CanonicalFormKind.Any);
            if (isType1CanonSubtype != isType2CanonSubtype)
            {
                // Only one of type1 and type2 is shared.
                // type2 is more specific if type1 is the shared type.
                return isType1CanonSubtype;
            }

            // Otherwise both types are either shared or not shared.
            // Look for a common parent type.
            TypeDesc merged = TypeExtensions.MergeTypesToCommonParent(type1, type2);

            // If the common parent is type1, then type2 is more specific.
            return merged == type1;
        }

        private CORINFO_CLASS_STRUCT_* getParentType(CORINFO_CLASS_STRUCT_* cls)
        { throw new NotImplementedException("getParentType"); }

        private CorInfoType getChildType(CORINFO_CLASS_STRUCT_* clsHnd, CORINFO_CLASS_STRUCT_** clsRet)
        {
            CorInfoType result = CorInfoType.CORINFO_TYPE_UNDEF;

            var td = HandleToObject(clsHnd);
            if (td.IsArray || td.IsByRef || td.IsPointer)
            {
                TypeDesc returnType = ((ParameterizedType)td).ParameterType;
                result = asCorInfoType(returnType, clsRet);
            }
            else
#pragma warning disable IDE0059 // Unnecessary assignment of a value
                clsRet = null;
#pragma warning restore IDE0059 // Unnecessary assignment of a value

            return result;
        }

        private bool satisfiesClassConstraints(CORINFO_CLASS_STRUCT_* cls)
        { throw new NotImplementedException("satisfiesClassConstraints"); }

        private bool isSDArray(CORINFO_CLASS_STRUCT_* cls)
        {
            var td = HandleToObject(cls);
            return td.IsSzArray;
        }

        private uint getArrayRank(CORINFO_CLASS_STRUCT_* cls)
        {
            uint rank = 0;
            var td = HandleToObject(cls) as ArrayType;
            if (td != null)
            {
                rank = (uint)td.Rank;
            }
            return rank;
        }

        private CorInfoArrayIntrinsic getArrayIntrinsicID(CORINFO_METHOD_STRUCT_* ftn)
        {
            CorInfoArrayIntrinsic kind = CorInfoArrayIntrinsic.ILLEGAL;
            if (HandleToObject(ftn) is ArrayMethod am)
            {
                kind = am.Kind switch
                {
                    ArrayMethodKind.Get => CorInfoArrayIntrinsic.GET,
                    ArrayMethodKind.Set => CorInfoArrayIntrinsic.SET,
                    ArrayMethodKind.Address => CorInfoArrayIntrinsic.ADDRESS,
                    _ => CorInfoArrayIntrinsic.ILLEGAL
                };
            }
            return kind;
        }

        private void* getArrayInitializationData(CORINFO_FIELD_STRUCT_* field, uint size)
        {
            var fd = HandleToObject(field);

            // Check for invalid arguments passed to InitializeArray intrinsic
            if (!fd.HasRva ||
                size > fd.FieldType.GetElementSize().AsInt)
            {
                return null;
            }

            return (void*)ObjectToHandle(_compilation.GetFieldRvaData(fd));
        }

#pragma warning disable CA1822 // Mark members as static
        private CorInfoIsAccessAllowedResult canAccessClass(ref CORINFO_RESOLVED_TOKEN pResolvedToken, CORINFO_METHOD_STRUCT_* callerHandle, ref CORINFO_HELPER_DESC pAccessHelper)
#pragma warning restore CA1822 // Mark members as static
        {
            // TODO: Access check
            return CorInfoIsAccessAllowedResult.CORINFO_ACCESS_ALLOWED;
        }

        private byte* getFieldName(CORINFO_FIELD_STRUCT_* ftn, byte** moduleName)
        {
            var field = HandleToObject(ftn);
            if (moduleName != null)
            {
                MetadataType typeDef = field.OwningType.GetTypeDefinition() as MetadataType;
                if (typeDef != null)
                    *moduleName = (byte*)GetPin(StringToUTF8(typeDef.GetFullName()));
                else
                    *moduleName = (byte*)GetPin(StringToUTF8("unknown"));
            }

            return (byte*)GetPin(StringToUTF8(field.Name));
        }

        private CORINFO_CLASS_STRUCT_* getFieldClass(CORINFO_FIELD_STRUCT_* field)
        {
            var fieldDesc = HandleToObject(field);
            return ObjectToHandle(fieldDesc.OwningType);
        }

        private CorInfoType getFieldType(CORINFO_FIELD_STRUCT_* field, CORINFO_CLASS_STRUCT_** structType, CORINFO_CLASS_STRUCT_* memberParent)
        {
            FieldDesc fieldDesc = HandleToObject(field);
            TypeDesc fieldType = fieldDesc.FieldType;

            CorInfoType type;
            if (structType != null)
            {
                type = asCorInfoType(fieldType, structType);
            }
            else
            {
                type = asCorInfoType(fieldType);
            }

            return type;
        }

        private uint getFieldOffset(CORINFO_FIELD_STRUCT_* field)
        {
            var fieldDesc = HandleToObject(field);

            Debug.Assert(fieldDesc.Offset != FieldAndOffset.InvalidOffset);

            return (uint)fieldDesc.Offset.AsInt;
        }

        private static CORINFO_FIELD_ACCESSOR getFieldIntrinsic(FieldDesc field)
        {
            Debug.Assert(field.IsIntrinsic);

            var owningType = field.OwningType;
            if ((owningType.IsWellKnownType(WellKnownType.IntPtr) ||
                    owningType.IsWellKnownType(WellKnownType.UIntPtr)) &&
                        field.Name == "Zero")
            {
                return CORINFO_FIELD_ACCESSOR.CORINFO_FIELD_INTRINSIC_ZERO;
            }
            else if (owningType.IsString && field.Name == "Empty")
            {
                return CORINFO_FIELD_ACCESSOR.CORINFO_FIELD_INTRINSIC_EMPTY_STRING;
            }
            else if (owningType.Name == "BitConverter" && owningType.Namespace == "System" &&
                field.Name == "IsLittleEndian")
            {
                return CORINFO_FIELD_ACCESSOR.CORINFO_FIELD_INTRINSIC_ISLITTLEENDIAN;
            }

            return (CORINFO_FIELD_ACCESSOR)(-1);
        }

        private bool isFieldStatic(CORINFO_FIELD_STRUCT_* fldHnd)
        {
            return HandleToObject(fldHnd).IsStatic;
        }

        private void getBoundaries(CORINFO_METHOD_STRUCT_* ftn, ref uint cILOffsets, ref uint* pILOffsets, BoundaryTypes* implicitBoundaries)
        {
            // TODO: Debugging
            cILOffsets = 0;
            pILOffsets = null;
            *implicitBoundaries = BoundaryTypes.DEFAULT_BOUNDARIES;
        }

        private void getVars(CORINFO_METHOD_STRUCT_* ftn, ref uint cVars, ILVarInfo** vars, ref bool extendOthers)
        {
            // TODO: Debugging

            cVars = 0;
            *vars = null;

            // Just tell the JIT to extend everything.
            extendOthers = true;
        }

#pragma warning disable CA1822 // Mark members as static
        private void reportRichMappings(InlineTreeNode* inlineTree, uint numInlineTree, RichOffsetMapping* mappings, uint numMappings)
#pragma warning restore CA1822 // Mark members as static
        {
            Marshal.FreeHGlobal((IntPtr)inlineTree);
            Marshal.FreeHGlobal((IntPtr)mappings);
        }

#pragma warning disable CA1822 // Mark members as static
        private void* allocateArray(UIntPtr cBytes)
#pragma warning restore CA1822 // Mark members as static
        {
            return (void*)Marshal.AllocHGlobal((IntPtr)(void*)cBytes);
        }

#pragma warning disable CA1822 // Mark members as static
        private void freeArray(void* array)
#pragma warning restore CA1822 // Mark members as static
        {
            Marshal.FreeHGlobal((IntPtr)array);
        }

#pragma warning disable CA1822 // Mark members as static
        private CORINFO_ARG_LIST_STRUCT_* getArgNext(CORINFO_ARG_LIST_STRUCT_* args)
#pragma warning restore CA1822 // Mark members as static
        {
            return (CORINFO_ARG_LIST_STRUCT_*)((int)args + 1);
        }

        private CorInfoTypeWithMod getArgType(CORINFO_SIG_INFO* sig, CORINFO_ARG_LIST_STRUCT_* args, CORINFO_CLASS_STRUCT_** vcTypeRet)
        {
            int index = (int)args;
            object sigObj = HandleToObject((IntPtr)sig->methodSignature);

            MethodSignature methodSig = sigObj as MethodSignature;

            if (methodSig != null)
            {
                TypeDesc type = methodSig[index];

                CorInfoType corInfoType = asCorInfoType(type, vcTypeRet);
                return (CorInfoTypeWithMod)corInfoType;
            }
            else
            {
                LocalVariableDefinition[] locals = (LocalVariableDefinition[])sigObj;
                TypeDesc type = locals[index].Type;

                CorInfoType corInfoType = asCorInfoType(type, vcTypeRet);

                return (CorInfoTypeWithMod)corInfoType | (locals[index].IsPinned ? CorInfoTypeWithMod.CORINFO_TYPE_MOD_PINNED : 0);
            }
        }

        private CORINFO_CLASS_STRUCT_* getArgClass(CORINFO_SIG_INFO* sig, CORINFO_ARG_LIST_STRUCT_* args)
        {
            int index = (int)args;
            object sigObj = HandleToObject((IntPtr)sig->methodSignature);

            MethodSignature methodSig = sigObj as MethodSignature;
            if (methodSig != null)
            {
                TypeDesc type = methodSig[index];
                return ObjectToHandle(type);
            }
            else
            {
                LocalVariableDefinition[] locals = (LocalVariableDefinition[])sigObj;
                TypeDesc type = locals[index].Type;
                return ObjectToHandle(type);
            }
        }

        private CorInfoHFAElemType getHFAType(CORINFO_CLASS_STRUCT_* hClass)
        {
            var type = (DefType)HandleToObject(hClass);

            // See MethodTable::GetHFAType and Compiler::GetHfaType.
            return (type.ValueTypeShapeCharacteristics & ValueTypeShapeCharacteristics.AggregateMask) switch
            {
                ValueTypeShapeCharacteristics.Float32Aggregate => CorInfoHFAElemType.CORINFO_HFA_ELEM_FLOAT,
                ValueTypeShapeCharacteristics.Float64Aggregate => CorInfoHFAElemType.CORINFO_HFA_ELEM_DOUBLE,
                ValueTypeShapeCharacteristics.Vector64Aggregate => CorInfoHFAElemType.CORINFO_HFA_ELEM_VECTOR64,
                ValueTypeShapeCharacteristics.Vector128Aggregate => CorInfoHFAElemType.CORINFO_HFA_ELEM_VECTOR128,
                _ => CorInfoHFAElemType.CORINFO_HFA_ELEM_NONE
            };
        }

        private HRESULT GetErrorHRESULT(_EXCEPTION_POINTERS* pExceptionPointers)
        { throw new NotImplementedException("GetErrorHRESULT"); }
        private uint GetErrorMessage(char* buffer, uint bufferLength)
        { throw new NotImplementedException("GetErrorMessage"); }

#pragma warning disable CA1822 // Mark members as static
        private int FilterException(_EXCEPTION_POINTERS* pExceptionPointers)
#pragma warning restore CA1822 // Mark members as static
        {
            // This method is completely handled by the C++ wrapper to the JIT-EE interface,
            // and should never reach the managed implementation.
            Debug.Fail("CorInfoImpl.FilterException should not be called");
            throw new NotSupportedException("FilterException");
        }

#pragma warning disable CA1822 // Mark members as static
        private bool runWithErrorTrap(void* function, void* parameter)
#pragma warning restore CA1822 // Mark members as static
        {
            // This method is completely handled by the C++ wrapper to the JIT-EE interface,
            // and should never reach the managed implementation.
            Debug.Fail("CorInfoImpl.runWithErrorTrap should not be called");
            throw new NotSupportedException("runWithErrorTrap");
        }

#pragma warning disable CA1822 // Mark members as static
        private bool runWithSPMIErrorTrap(void* function, void* parameter)
#pragma warning restore CA1822 // Mark members as static
        {
            // This method is completely handled by the C++ wrapper to the JIT-EE interface,
            // and should never reach the managed implementation.
            Debug.Fail("CorInfoImpl.runWithSPMIErrorTrap should not be called");
            throw new NotSupportedException("runWithSPMIErrorTrap");
        }

        private void ThrowExceptionForJitResult(HRESULT result)
        { throw new NotImplementedException("ThrowExceptionForJitResult"); }
        private void ThrowExceptionForHelper(ref CORINFO_HELPER_DESC throwHelper)
        { throw new NotImplementedException("ThrowExceptionForHelper"); }

        public static CORINFO_OS TargetToOs(TargetDetails target)
        {
            return target.IsWindows ? CORINFO_OS.CORINFO_WINNT :
                   target.IsOSX ? CORINFO_OS.CORINFO_MACOS : CORINFO_OS.CORINFO_UNIX;
        }

        private void getEEInfo(ref CORINFO_EE_INFO pEEInfoOut)
        {
            pEEInfoOut = default(CORINFO_EE_INFO);

#if DEBUG
            // In debug, write some bogus data to the struct to ensure we have filled everything
            // properly.
            fixed (CORINFO_EE_INFO* tmp = &pEEInfoOut)
                MemoryHelper.FillMemory((byte*)tmp, 0xcc, Marshal.SizeOf<CORINFO_EE_INFO>());
#endif

            int pointerSize = this.PointerSize;

            pEEInfoOut.inlinedCallFrameInfo.size = (uint)SizeOfPInvokeTransitionFrame;

            pEEInfoOut.offsetOfDelegateInstance = (uint)pointerSize;            // Delegate::m_firstParameter
            pEEInfoOut.offsetOfDelegateFirstTarget = OffsetOfDelegateFirstTarget;

            pEEInfoOut.sizeOfReversePInvokeFrame = (uint)SizeOfReversePInvokeTransitionFrame;

            pEEInfoOut.osPageSize = new UIntPtr(0x1000);

            pEEInfoOut.maxUncheckedOffsetForNullObject = (_compilation.NodeFactory.Target.IsWindows) ?
                new UIntPtr(32 * 1024 - 1) : new UIntPtr((uint)pEEInfoOut.osPageSize / 2 - 1);

            pEEInfoOut.targetAbi = TargetABI;
            pEEInfoOut.osType = TargetToOs(_compilation.NodeFactory.Target);
        }

#pragma warning disable CA1822 // Mark members as static
        private char* getJitTimeLogFilename()
#pragma warning restore CA1822 // Mark members as static
        {
            return null;
        }

        private mdToken getMethodDefFromMethod(CORINFO_METHOD_STRUCT_* hMethod)
        {
            MethodDesc method = HandleToObject(hMethod);
#if READYTORUN
            if (method is UnboxingMethodDesc unboxingMethodDesc)
            {
                method = unboxingMethodDesc.Target;
            }
#endif
            MethodDesc methodDefinition = method.GetTypicalMethodDefinition();

            // Need to cast down to EcmaMethod. Do not use this as a precedent that casting to Ecma*
            // within the JitInterface is fine. We might want to consider moving this to Compilation.
            TypeSystem.Ecma.EcmaMethod ecmaMethodDefinition = methodDefinition as TypeSystem.Ecma.EcmaMethod;
            if (ecmaMethodDefinition != null)
            {
                return (mdToken)System.Reflection.Metadata.Ecma335.MetadataTokens.GetToken(ecmaMethodDefinition.Handle);
            }

            return 0;
        }

        private static byte[] StringToUTF8(string s)
        {
            int byteCount = Encoding.UTF8.GetByteCount(s);
            byte[] bytes = new byte[byteCount + 1];
            Encoding.UTF8.GetBytes(s, 0, s.Length, bytes, 0);
            return bytes;
        }

        private byte* getMethodName(CORINFO_METHOD_STRUCT_* ftn, byte** moduleName)
        {
            MethodDesc method = HandleToObject(ftn);

            if (moduleName != null)
            {
                MetadataType typeDef = method.OwningType.GetTypeDefinition() as MetadataType;
                if (typeDef != null)
                    *moduleName = (byte*)GetPin(StringToUTF8(typeDef.GetFullName()));
                else
                    *moduleName = (byte*)GetPin(StringToUTF8("unknown"));
            }

            return (byte*)GetPin(StringToUTF8(method.Name));
        }

        private static string getMethodNameFromMetadataImpl(MethodDesc method, out string className, out string namespaceName, out string enclosingClassName)
        {
            className = null;
            namespaceName = null;
            enclosingClassName = null;

            string result = method.Name;

            MetadataType owningType = method.OwningType as MetadataType;
            if (owningType != null)
            {
                className = owningType.Name;
                namespaceName = owningType.Namespace;

                // Query enclosingClassName when the method is in a nested class
                // and get the namespace of enclosing classes (nested class's namespace is empty)
                var containingType = owningType.ContainingType;
                if (containingType != null)
                {
                    enclosingClassName = containingType.Name;
                    namespaceName = containingType.Namespace;
                }
            }

            return result;
        }

        private byte* getMethodNameFromMetadata(CORINFO_METHOD_STRUCT_* ftn, byte** className, byte** namespaceName, byte** enclosingClassName)
        {
            MethodDesc method = HandleToObject(ftn);

            string result;
            string classResult;
            string namespaceResult;
            string enclosingResult;

            result = getMethodNameFromMetadataImpl(method, out classResult, out namespaceResult, out enclosingResult);

            if (className != null)
                *className = classResult != null ? (byte*)GetPin(StringToUTF8(classResult)) : null;
            if (namespaceName != null)
                *namespaceName = namespaceResult != null ? (byte*)GetPin(StringToUTF8(namespaceResult)) : null;
            if (enclosingClassName != null)
                *enclosingClassName = enclosingResult != null ? (byte*)GetPin(StringToUTF8(enclosingResult)) : null;

            return result != null ? (byte*)GetPin(StringToUTF8(result)) : null;
        }

        private uint getMethodHash(CORINFO_METHOD_STRUCT_* ftn)
        {
            return (uint)HandleToObject(ftn).GetHashCode();
        }

        private UIntPtr findNameOfToken(CORINFO_MODULE_STRUCT_* moduleHandle, mdToken token, byte* szFQName, UIntPtr FQNameCapacity)
        { throw new NotImplementedException("findNameOfToken"); }

        private bool getSystemVAmd64PassStructInRegisterDescriptor(CORINFO_CLASS_STRUCT_* structHnd, SYSTEMV_AMD64_CORINFO_STRUCT_REG_PASSING_DESCRIPTOR* structPassInRegDescPtr)
        {
            TypeDesc typeDesc = HandleToObject(structHnd);

            SystemVStructClassificator.GetSystemVAmd64PassStructInRegisterDescriptor(typeDesc, out *structPassInRegDescPtr);
            return true;
        }

        private uint getLoongArch64PassStructInRegisterFlags(CORINFO_CLASS_STRUCT_* cls)
        {
            TypeDesc typeDesc = HandleToObject(cls);
            return LoongArch64PassStructInRegister.GetLoongArch64PassStructInRegisterFlags(typeDesc);
        }

        private uint getThreadTLSIndex(ref void* ppIndirection)
        { throw new NotImplementedException("getThreadTLSIndex"); }
        private void* getInlinedCallFrameVptr(ref void* ppIndirection)
        { throw new NotImplementedException("getInlinedCallFrameVptr"); }

        private Dictionary<CorInfoHelpFunc, ISymbolNode> _helperCache = new Dictionary<CorInfoHelpFunc, ISymbolNode>();
        private void* getHelperFtn(CorInfoHelpFunc ftnNum, ref void* ppIndirection)
        {
            ISymbolNode entryPoint;
            if (!_helperCache.TryGetValue(ftnNum, out entryPoint))
            {
                entryPoint = GetHelperFtnUncached(ftnNum);
                _helperCache.Add(ftnNum, entryPoint);
            }
            if (entryPoint.RepresentsIndirectionCell)
            {
                ppIndirection = (void*)ObjectToHandle(entryPoint);
                return null;
            }
            else
            {
                ppIndirection = null;
                return (void*)ObjectToHandle(entryPoint);
            }
        }

        private void getFunctionFixedEntryPoint(CORINFO_METHOD_STRUCT_* ftn, bool isUnsafeFunctionPointer, ref CORINFO_CONST_LOOKUP pResult)
        { throw new NotImplementedException("getFunctionFixedEntryPoint"); }

#pragma warning disable CA1822 // Mark members as static
        private CorInfoHelpFunc getLazyStringLiteralHelper(CORINFO_MODULE_STRUCT_* handle)
#pragma warning restore CA1822 // Mark members as static
        {
            // TODO: Lazy string literal helper
            return CorInfoHelpFunc.CORINFO_HELP_UNDEF;
        }

        private CORINFO_MODULE_STRUCT_* embedModuleHandle(CORINFO_MODULE_STRUCT_* handle, ref void* ppIndirection)
        { throw new NotImplementedException("embedModuleHandle"); }

        private CORINFO_FIELD_STRUCT_* embedFieldHandle(CORINFO_FIELD_STRUCT_* handle, ref void* ppIndirection)
        { throw new NotImplementedException("embedFieldHandle"); }

        private static CORINFO_RUNTIME_LOOKUP_KIND GetGenericRuntimeLookupKind(MethodDesc method)
        {
            if (method.RequiresInstMethodDescArg())
                return CORINFO_RUNTIME_LOOKUP_KIND.CORINFO_LOOKUP_METHODPARAM;
            else if (method.RequiresInstMethodTableArg())
                return CORINFO_RUNTIME_LOOKUP_KIND.CORINFO_LOOKUP_CLASSPARAM;
            else
            {
                Debug.Assert(method.AcquiresInstMethodTableFromThis());
                return CORINFO_RUNTIME_LOOKUP_KIND.CORINFO_LOOKUP_THISOBJ;
            }
        }

        private void getLocationOfThisType(CORINFO_METHOD_STRUCT_* context, ref CORINFO_LOOKUP_KIND result)
        {
            MethodDesc method = HandleToObject(context);

            if (method.IsSharedByGenericInstantiations)
            {
                result.needsRuntimeLookup = true;
                result.runtimeLookupKind = GetGenericRuntimeLookupKind(method);
            }
            else
            {
                result.needsRuntimeLookup = false;
                result.runtimeLookupKind = CORINFO_RUNTIME_LOOKUP_KIND.CORINFO_LOOKUP_THISOBJ;
            }
        }

        private void* GetCookieForPInvokeCalliSig(CORINFO_SIG_INFO* szMetaSig, ref void* ppIndirection)
        { throw new NotImplementedException("GetCookieForPInvokeCalliSig"); }
#pragma warning disable CA1822 // Mark members as static
        private CORINFO_JUST_MY_CODE_HANDLE_* getJustMyCodeHandle(CORINFO_METHOD_STRUCT_* method, ref CORINFO_JUST_MY_CODE_HANDLE_* ppIndirection)
#pragma warning restore CA1822 // Mark members as static
        {
            ppIndirection = null;
            return null;
        }
        private void GetProfilingHandle(ref bool pbHookFunction, ref void* pProfilerHandle, ref bool pbIndirectedHandles)
        { throw new NotImplementedException("GetProfilingHandle"); }

        /// <summary>
        /// Create a CORINFO_CONST_LOOKUP to a symbol and put the address into the addr field
        /// </summary>
        private CORINFO_CONST_LOOKUP CreateConstLookupToSymbol(ISymbolNode symbol)
        {
            CORINFO_CONST_LOOKUP constLookup = default(CORINFO_CONST_LOOKUP);
            constLookup.addr = (void*)ObjectToHandle(symbol);
            constLookup.accessType = symbol.RepresentsIndirectionCell ? InfoAccessType.IAT_PVALUE : InfoAccessType.IAT_VALUE;
            return constLookup;
        }

        private bool canAccessFamily(CORINFO_METHOD_STRUCT_* hCaller, CORINFO_CLASS_STRUCT_* hInstanceType)
        { throw new NotImplementedException("canAccessFamily"); }
        private bool isRIDClassDomainID(CORINFO_CLASS_STRUCT_* cls)
        { throw new NotImplementedException("isRIDClassDomainID"); }
        private uint getClassDomainID(CORINFO_CLASS_STRUCT_* cls, ref void* ppIndirection)
        { throw new NotImplementedException("getClassDomainID"); }

        private void* getFieldAddress(CORINFO_FIELD_STRUCT_* field, void** ppIndirection)
        {
            FieldDesc fieldDesc = HandleToObject(field);
            Debug.Assert(fieldDesc.HasRva);
            ISymbolNode node = _compilation.GetFieldRvaData(fieldDesc);
            void *handle = (void *)ObjectToHandle(node);
            if (node.RepresentsIndirectionCell)
            {
                *ppIndirection = handle;
                return null;
            }
            else
            {
                if (ppIndirection != null)
                    *ppIndirection = null;
                return handle;
            }
        }

        private CORINFO_CLASS_STRUCT_* getStaticFieldCurrentClass(CORINFO_FIELD_STRUCT_* field, byte* pIsSpeculative)
        {
            if (pIsSpeculative != null)
                *pIsSpeculative = 1;

            return null;
        }

        private IntPtr getVarArgsHandle(CORINFO_SIG_INFO* pSig, ref void* ppIndirection)
        { throw new NotImplementedException("getVarArgsHandle"); }
        private bool canGetVarArgsHandle(CORINFO_SIG_INFO* pSig)
        { throw new NotImplementedException("canGetVarArgsHandle"); }

        private InfoAccessType emptyStringLiteral(ref void* ppValue)
        {
            return constructStringLiteral(_methodScope, (mdToken)CorTokenType.mdtString, ref ppValue);
        }

        private uint getFieldThreadLocalStoreID(CORINFO_FIELD_STRUCT_* field, ref void* ppIndirection)
        { throw new NotImplementedException("getFieldThreadLocalStoreID"); }
        private void addActiveDependency(CORINFO_MODULE_STRUCT_* moduleFrom, CORINFO_MODULE_STRUCT_* moduleTo)
        { throw new NotImplementedException("addActiveDependency"); }
        private CORINFO_METHOD_STRUCT_* GetDelegateCtor(CORINFO_METHOD_STRUCT_* methHnd, CORINFO_CLASS_STRUCT_* clsHnd, CORINFO_METHOD_STRUCT_* targetMethodHnd, ref DelegateCtorArgs pCtorData)
        { throw new NotImplementedException("GetDelegateCtor"); }
        private void MethodCompileComplete(CORINFO_METHOD_STRUCT_* methHnd)
        { throw new NotImplementedException("MethodCompileComplete"); }

#pragma warning disable CA1822 // Mark members as static
        private bool getTailCallHelpers(ref CORINFO_RESOLVED_TOKEN callToken, CORINFO_SIG_INFO* sig, CORINFO_GET_TAILCALL_HELPERS_FLAGS flags, ref CORINFO_TAILCALL_HELPERS pResult)
#pragma warning restore CA1822 // Mark members as static
        {
            // Slow tailcalls are not supported yet
            // https://github.com/dotnet/runtime/issues/35423
#if READYTORUN
            throw new RequiresRuntimeJitException(nameof(getTailCallHelpers));
#else
            return false;
#endif
        }

        private byte[] _code;
        private byte[] _coldCode;
        private int _codeAlignment;

        private byte[] _roData;

        private MethodReadOnlyDataNode _roDataBlob;
        private int _roDataAlignment;

        private int _numFrameInfos;
        private int _usedFrameInfos;
        private FrameInfo[] _frameInfos;

        private byte[] _gcInfo;
        private CORINFO_EH_CLAUSE[] _ehClauses;

        private void allocMem(ref AllocMemArgs args)
        {
            args.hotCodeBlock = (void*)GetPin(_code = new byte[args.hotCodeSize]);
            args.hotCodeBlockRW = args.hotCodeBlock;

            if (args.coldCodeSize != 0)
            {
                args.coldCodeBlock = (void*)GetPin(_coldCode = new byte[args.coldCodeSize]);
                args.coldCodeBlockRW = args.coldCodeBlock;
            }

            _codeAlignment = -1;
            if ((args.flag & CorJitAllocMemFlag.CORJIT_ALLOCMEM_FLG_32BYTE_ALIGN) != 0)
            {
                _codeAlignment = 32;
            }
            else if ((args.flag & CorJitAllocMemFlag.CORJIT_ALLOCMEM_FLG_16BYTE_ALIGN) != 0)
            {
                _codeAlignment = 16;
            }

            if (args.roDataSize != 0)
            {
                _roDataAlignment = 8;

                if ((args.flag & CorJitAllocMemFlag.CORJIT_ALLOCMEM_FLG_RODATA_32BYTE_ALIGN) != 0)
                {
                    _roDataAlignment = 32;
                }
                else if ((args.flag & CorJitAllocMemFlag.CORJIT_ALLOCMEM_FLG_RODATA_16BYTE_ALIGN) != 0)
                {
                    _roDataAlignment = 16;
                }
                else if (args.roDataSize < 8)
                {
                    _roDataAlignment = PointerSize;
                }

                _roData = new byte[args.roDataSize];

                _roDataBlob = new MethodReadOnlyDataNode(MethodBeingCompiled);

                args.roDataBlock = (void*)GetPin(_roData);
                args.roDataBlockRW = args.roDataBlock;
            }

            if (_numFrameInfos > 0)
            {
                _frameInfos = new FrameInfo[_numFrameInfos];
            }
        }

        private void reserveUnwindInfo(bool isFunclet, bool isColdCode, uint unwindSize)
        {
            _numFrameInfos++;
        }

        private void allocUnwindInfo(byte* pHotCode, byte* pColdCode, uint startOffset, uint endOffset, uint unwindSize, byte* pUnwindBlock, CorJitFuncKind funcKind)
        {
            Debug.Assert(FrameInfoFlags.Filter == (FrameInfoFlags)CorJitFuncKind.CORJIT_FUNC_FILTER);
            Debug.Assert(FrameInfoFlags.Handler == (FrameInfoFlags)CorJitFuncKind.CORJIT_FUNC_HANDLER);

            FrameInfoFlags flags = (FrameInfoFlags)funcKind;

            if (funcKind == CorJitFuncKind.CORJIT_FUNC_ROOT)
            {
                if (this.MethodBeingCompiled.IsUnmanagedCallersOnly)
                    flags |= FrameInfoFlags.ReversePInvoke;
            }

            byte[] blobData = new byte[unwindSize];

            for (uint i = 0; i < unwindSize; i++)
            {
                blobData[i] = pUnwindBlock[i];
            }

#if !READYTORUN
            var target = _compilation.TypeSystemContext.Target;

            if (target.Architecture == TargetArchitecture.ARM64 && target.OperatingSystem == TargetOS.Linux)
            {
                blobData = CompressARM64CFI(blobData);
            }
#endif

            _frameInfos[_usedFrameInfos++] = new FrameInfo(flags, (int)startOffset, (int)endOffset, blobData);
        }

        private void* allocGCInfo(UIntPtr size)
        {
            _gcInfo = new byte[(int)size];
            return (void*)GetPin(_gcInfo);
        }

#pragma warning disable CA1822 // Mark members as static
        private bool logMsg(uint level, byte* fmt, IntPtr args)
#pragma warning restore CA1822 // Mark members as static
        {
            // Console.WriteLine(Marshal.PtrToStringUTF8((IntPtr)fmt));
            return false;
        }

        private int doAssert(byte* szFile, int iLine, byte* szExpr)
        {
            Logger.LogMessage(Marshal.PtrToStringUTF8((IntPtr)szFile) + ":" + iLine);
            Logger.LogMessage(Marshal.PtrToStringUTF8((IntPtr)szExpr));

            return 1;
        }

#pragma warning disable CA1822 // Mark members as static
        private void reportFatalError(CorJitResult result)
#pragma warning restore CA1822 // Mark members as static
        {
            // We could add some logging here, but for now it's unnecessary.
            // CompileMethod is going to fail with this CorJitResult anyway.
        }

#pragma warning disable CA1822 // Mark members as static
        private void recordCallSite(uint instrOffset, CORINFO_SIG_INFO* callSig, CORINFO_METHOD_STRUCT_* methodHandle)
#pragma warning restore CA1822 // Mark members as static
        {
        }

        private ArrayBuilder<Relocation> _codeRelocs;
        private ArrayBuilder<Relocation> _roDataRelocs;


        /// <summary>
        /// Various type of block.
        /// </summary>
        public enum BlockType : sbyte
        {
            /// <summary>Not a generated block.</summary>
            Unknown = -1,
            /// <summary>Represent code.</summary>
            Code = 0,
            /// <summary>Represent cold code (i.e. code not called frequently).</summary>
            ColdCode = 1,
            /// <summary>Read-only data.</summary>
            ROData = 2,
            /// <summary>Instrumented Block Count Data</summary>
            BBCounts = 3
        }

        private BlockType findKnownBlock(void* location, out int offset)
        {
            fixed (byte* pCode = _code)
            {
                if (pCode <= (byte*)location && (byte*)location < pCode + _code.Length)
                {
                    offset = (int)((byte*)location - pCode);
                    return BlockType.Code;
                }
            }

            if (_coldCode != null)
            {
                fixed (byte* pColdCode = _coldCode)
                {
                    if (pColdCode <= (byte*)location && (byte*)location < pColdCode + _coldCode.Length)
                    {
                        offset = (int)((byte*)location - pColdCode);
                        return BlockType.ColdCode;
                    }
                }
            }

            if (_roData != null)
            {
                fixed (byte* pROData = _roData)
                {
                    if (pROData <= (byte*)location && (byte*)location < pROData + _roData.Length)
                    {
                        offset = (int)((byte*)location - pROData);
                        return BlockType.ROData;
                    }
                }
            }

            {
                BlockType retBlockType = BlockType.Unknown;
                offset = 0;
                findKnownBBCountBlock(ref retBlockType, location, ref offset);
                if (retBlockType == BlockType.BBCounts)
                    return retBlockType;
            }

            offset = 0;
            return BlockType.Unknown;
        }

        partial void findKnownBBCountBlock(ref BlockType blockType, void* location, ref int offset);

        private ref ArrayBuilder<Relocation> findRelocBlock(BlockType blockType, out int length)
        {
            switch (blockType)
            {
                case BlockType.Code:
                    length = _code.Length;
                    return ref _codeRelocs;
                case BlockType.ROData:
                    length = _roData.Length;
                    return ref _roDataRelocs;
                default:
                    throw new NotImplementedException("Arbitrary relocs");
            }
        }

        // Translates relocation type constants used by JIT (defined in winnt.h) to RelocType enumeration
        private static RelocType GetRelocType(TargetArchitecture targetArchitecture, ushort fRelocType)
        {
            switch (targetArchitecture)
            {
                case TargetArchitecture.ARM64:
                {
                    const ushort IMAGE_REL_ARM64_BRANCH26 = 3;
                    const ushort IMAGE_REL_ARM64_PAGEBASE_REL21 = 4;
                    const ushort IMAGE_REL_ARM64_PAGEOFFSET_12A = 6;

                    switch (fRelocType)
                    {
                        case IMAGE_REL_ARM64_BRANCH26:
                            return RelocType.IMAGE_REL_BASED_ARM64_BRANCH26;
                        case IMAGE_REL_ARM64_PAGEBASE_REL21:
                            return RelocType.IMAGE_REL_BASED_ARM64_PAGEBASE_REL21;
                        case IMAGE_REL_ARM64_PAGEOFFSET_12A:
                            return RelocType.IMAGE_REL_BASED_ARM64_PAGEOFFSET_12A;
                        default:
                            Debug.Fail("Invalid RelocType: " + fRelocType);
                            return 0;
                    }
                }
                case TargetArchitecture.LoongArch64:
                {
                    const ushort IMAGE_REL_LOONGARCH64_PC = 3;
                    const ushort IMAGE_REL_LOONGARCH64_JIR = 4;

                    switch (fRelocType)
                    {
                        case IMAGE_REL_LOONGARCH64_PC:
                            return RelocType.IMAGE_REL_BASED_LOONGARCH64_PC;
                        case IMAGE_REL_LOONGARCH64_JIR:
                            return RelocType.IMAGE_REL_BASED_LOONGARCH64_JIR;
                        default:
                            Debug.Fail("Invalid RelocType: " + fRelocType);
                            return 0;
                    }
                }
                default:
                    return (RelocType)fRelocType;
            }
        }

        private void recordRelocation(void* location, void* locationRW, void* target, ushort fRelocType, ushort slotNum, int addlDelta)
        {
            // slotNum is not used
            Debug.Assert(slotNum == 0);

            int relocOffset;
            BlockType locationBlock = findKnownBlock(location, out relocOffset);
            Debug.Assert(locationBlock != BlockType.Unknown, "BlockType.Unknown not expected");

            int length;
            ref ArrayBuilder<Relocation> sourceBlock = ref findRelocBlock(locationBlock, out length);

            int relocDelta;
            BlockType targetBlock = findKnownBlock(target, out relocDelta);

            ISymbolNode relocTarget;
            switch (targetBlock)
            {
                case BlockType.Code:
                    relocTarget = _methodCodeNode;
                    break;

                case BlockType.ColdCode:
                    // TODO: Arbitrary relocs
                    throw new NotImplementedException("ColdCode relocs");

                case BlockType.ROData:
                    relocTarget = _roDataBlob;
                    break;

#if READYTORUN
                case BlockType.BBCounts:
                    relocTarget = null;
                    break;
#endif

                default:
                    // Reloc points to something outside of the generated blocks
                    var targetObject = HandleToObject((IntPtr)target);

#if READYTORUN
                    if (targetObject is RequiresRuntimeJitIfUsedSymbol requiresRuntimeSymbol)
                    {
                        throw new RequiresRuntimeJitException(requiresRuntimeSymbol.Message);
                    }
#endif

                    relocTarget = (ISymbolNode)targetObject;
                    break;
            }

            relocDelta += addlDelta;

            TargetArchitecture targetArchitecture = _compilation.TypeSystemContext.Target.Architecture;
            RelocType relocType = GetRelocType(targetArchitecture, fRelocType);
            // relocDelta is stored as the value
            Relocation.WriteValue(relocType, location, relocDelta);

            if (sourceBlock.Count == 0)
                sourceBlock.EnsureCapacity(length / 32 + 1);
            sourceBlock.Add(new Relocation(relocType, relocOffset, relocTarget));
        }

        private ushort getRelocTypeHint(void* target)
        {
            switch (_compilation.TypeSystemContext.Target.Architecture)
            {
                case TargetArchitecture.X64:
                    return (ushort)RelocType.IMAGE_REL_BASED_REL32;

                case TargetArchitecture.ARM:
                    return (ushort)RelocType.IMAGE_REL_BASED_THUMB_BRANCH24;

                default:
                    return ushort.MaxValue;
            }
        }

        private uint getExpectedTargetArchitecture()
        {
            TargetArchitecture arch = _compilation.TypeSystemContext.Target.Architecture;

            switch (arch)
            {
                case TargetArchitecture.X86:
                    return (uint)ImageFileMachine.I386;
                case TargetArchitecture.X64:
                    return (uint)ImageFileMachine.AMD64;
                case TargetArchitecture.ARM:
                    return (uint)ImageFileMachine.ARM;
                case TargetArchitecture.ARM64:
                    return (uint)ImageFileMachine.ARM64;
                case TargetArchitecture.LoongArch64:
                    return (uint)ImageFileMachine.LoongArch64;
                default:
                    throw new NotImplementedException("Expected target architecture is not supported");
            }
        }

        private bool doesFieldBelongToClass(CORINFO_FIELD_STRUCT_* fld, CORINFO_CLASS_STRUCT_* cls)
        {
            var field = HandleToObject(fld);
            var queryType = HandleToObject(cls);

            Debug.Assert(!field.IsStatic);

            // doesFieldBelongToClass implements the predicate of...
            // if field is not associated with the class in any way, return false.
            // if field is the only FieldDesc that the JIT might see for a given class handle
            // and logical field pair then return true. This is needed as the field handle here
            // is used as a key into a hashtable mapping writes to fields to value numbers.
            //
            // In this implementation this is made more complex as the JIT is exposed to CORINFO_FIELD_STRUCT
            // pointers which represent exact instantions, so performing exact matching is the necessary approach

            // BaseType._field, BaseType -> true
            // BaseType._field, DerivedType -> true
            // BaseType<__Canon>._field, BaseType<__Canon> -> true
            // BaseType<__Canon>._field, BaseType<string> -> false
            // BaseType<__Canon>._field, BaseType<object> -> false
            // BaseType<sbyte>._field, BaseType<sbyte> -> true
            // BaseType<sbyte>._field, BaseType<byte> -> false

            var fieldOwnerType = field.OwningType;

            while (queryType != null)
            {
                if (fieldOwnerType == queryType)
                    return true;
                queryType = queryType.BaseType;
            }

            return false;
        }

        private bool isMethodDefinedInCoreLib()
        {
            TypeDesc owningType = MethodBeingCompiled.OwningType;
            MetadataType owningMetadataType = owningType as MetadataType;
            if (owningMetadataType == null)
            {
                return false;
            }
            return owningMetadataType.Module == _compilation.TypeSystemContext.SystemModule;
        }

        private uint getJitFlags(ref CORJIT_FLAGS flags, uint sizeInBytes)
        {
            // Read the user-defined configuration options.
            foreach (var flag in JitConfigProvider.Instance.Flags)
                flags.Set(flag);

            flags.InstructionSetFlags.Add(_compilation.InstructionSetSupport.OptimisticFlags);

            // Set the rest of the flags that don't make sense to expose publicly.
            flags.Set(CorJitFlag.CORJIT_FLAG_SKIP_VERIFICATION);
            flags.Set(CorJitFlag.CORJIT_FLAG_READYTORUN);
            flags.Set(CorJitFlag.CORJIT_FLAG_RELOC);
            flags.Set(CorJitFlag.CORJIT_FLAG_PREJIT);
            flags.Set(CorJitFlag.CORJIT_FLAG_USE_PINVOKE_HELPERS);

            TargetArchitecture targetArchitecture = _compilation.TypeSystemContext.Target.Architecture;

            switch (targetArchitecture)
            {
                case TargetArchitecture.X64:
                case TargetArchitecture.X86:
                    Debug.Assert(InstructionSet.X86_SSE2 == InstructionSet.X64_SSE2);
                    Debug.Assert(_compilation.InstructionSetSupport.IsInstructionSetSupported(InstructionSet.X86_SSE2));
                    break;

                case TargetArchitecture.ARM64:
                    Debug.Assert(_compilation.InstructionSetSupport.IsInstructionSetSupported(InstructionSet.ARM64_AdvSimd));
                    break;
            }

#if READYTORUN
            if (targetArchitecture == TargetArchitecture.ARM && !_compilation.TypeSystemContext.Target.IsWindows)
                flags.Set(CorJitFlag.CORJIT_FLAG_RELATIVE_CODE_RELOCS);
#endif

            if (this.MethodBeingCompiled.IsUnmanagedCallersOnly)
            {
                // Validate UnmanagedCallersOnlyAttribute usage
                if (!this.MethodBeingCompiled.Signature.IsStatic) // Must be a static method
                {
                    ThrowHelper.ThrowInvalidProgramException(ExceptionStringID.InvalidProgramNonStaticMethod, this.MethodBeingCompiled);
                }

                if (this.MethodBeingCompiled.HasInstantiation || this.MethodBeingCompiled.OwningType.HasInstantiation) // No generics involved
                {
                    ThrowHelper.ThrowInvalidProgramException(ExceptionStringID.InvalidProgramGenericMethod, this.MethodBeingCompiled);
                }

#if READYTORUN
                // TODO: enable this check in full AOT
                if (Marshaller.IsMarshallingRequired(this.MethodBeingCompiled.Signature, Array.Empty<ParameterMetadata>(), ((MetadataType)this.MethodBeingCompiled.OwningType).Module)) // Only blittable arguments
                {
                    ThrowHelper.ThrowInvalidProgramException(ExceptionStringID.InvalidProgramNonBlittableTypes, this.MethodBeingCompiled);
                }
#endif

                flags.Set(CorJitFlag.CORJIT_FLAG_REVERSE_PINVOKE);
            }

            if (this.MethodBeingCompiled.IsPInvoke)
            {
                flags.Set(CorJitFlag.CORJIT_FLAG_IL_STUB);
            }

            if (this.MethodBeingCompiled.IsNoOptimization)
            {
                flags.Set(CorJitFlag.CORJIT_FLAG_MIN_OPT);
            }

            if (this.MethodBeingCompiled.Context.Target.Abi == TargetAbi.NativeAotArmel)
            {
                flags.Set(CorJitFlag.CORJIT_FLAG_SOFTFP_ABI);
            }

            return (uint)sizeof(CORJIT_FLAGS);
        }

        private PgoSchemaElem[] getPgoInstrumentationResults(MethodDesc method)
        {
            return _compilation.ProfileData[method]?.SchemaData;
        }

        public static void ComputeJitPgoInstrumentationSchema(Func<object, IntPtr> objectToHandle, PgoSchemaElem[] pgoResultsSchemas, out PgoInstrumentationSchema[] nativeSchemas, out byte[] instrumentationData, Func<TypeDesc, bool> typeFilter = null)
        {
            nativeSchemas = new PgoInstrumentationSchema[pgoResultsSchemas.Length];
            MemoryStream msInstrumentationData = new MemoryStream();
            BinaryWriter bwInstrumentationData = new BinaryWriter(msInstrumentationData);
            for (int i = 0; i < nativeSchemas.Length; i++)
            {
                if ((bwInstrumentationData.BaseStream.Position % 8) == 4)
                {
                    bwInstrumentationData.Write(0);
                }

                Debug.Assert((bwInstrumentationData.BaseStream.Position % 8) == 0);
                nativeSchemas[i].Offset = new IntPtr(checked((int)bwInstrumentationData.BaseStream.Position));
                nativeSchemas[i].ILOffset = pgoResultsSchemas[i].ILOffset;
                nativeSchemas[i].Count = pgoResultsSchemas[i].Count;
                nativeSchemas[i].Other = pgoResultsSchemas[i].Other;
                nativeSchemas[i].InstrumentationKind = (PgoInstrumentationKind)pgoResultsSchemas[i].InstrumentationKind;

                if (pgoResultsSchemas[i].DataObject == null)
                {
                    bwInstrumentationData.Write(pgoResultsSchemas[i].DataLong);
                }
                else
                {
                    object dataObject = pgoResultsSchemas[i].DataObject;
                    if (dataObject is int[] intArray)
                    {
                        foreach (int intVal in intArray)
                            bwInstrumentationData.Write(intVal);
                    }
                    else if (dataObject is long[] longArray)
                    {
                        foreach (long longVal in longArray)
                            bwInstrumentationData.Write(longVal);
                    }
                    else if (dataObject is TypeSystemEntityOrUnknown[] typeArray)
                    {
                        foreach (TypeSystemEntityOrUnknown typeVal in typeArray)
                        {
                            IntPtr ptrVal;

                            if (typeVal.AsType != null && (typeFilter == null || typeFilter(typeVal.AsType)))
                            {
                                ptrVal = (IntPtr)objectToHandle(typeVal.AsType);
                            }
                            else if (typeVal.AsMethod != null)
                            {
                                ptrVal = (IntPtr)objectToHandle(typeVal.AsMethod);
                            }
                            else
                            {
                                // The "Unknown types are the values from 1-33
                                ptrVal = new IntPtr((typeVal.AsUnknown % 32) + 1);
                            }

                            if (IntPtr.Size == 4)
                                bwInstrumentationData.Write((int)ptrVal);
                            else
                                bwInstrumentationData.Write((long)ptrVal);
                        }
                    }
                }
            }

            bwInstrumentationData.Flush();

            instrumentationData = msInstrumentationData.ToArray();
        }

        private HRESULT getPgoInstrumentationResults(CORINFO_METHOD_STRUCT_* ftnHnd, ref PgoInstrumentationSchema* pSchema, ref uint countSchemaItems, byte** pInstrumentationData,
            ref PgoSource pPgoSource)
        {
            MethodDesc methodDesc = HandleToObject(ftnHnd);

            if (!_pgoResults.TryGetValue(methodDesc, out PgoInstrumentationResults pgoResults))
            {
                var pgoResultsSchemas = getPgoInstrumentationResults(methodDesc);
                if (pgoResultsSchemas == null)
                {
                    pgoResults.hr = HRESULT.E_NOTIMPL;
                }
                else
                {
#pragma warning disable SA1001, SA1113, SA1115 // Commas should be spaced correctly
                    ComputeJitPgoInstrumentationSchema(ObjectToHandle, pgoResultsSchemas, out var nativeSchemas, out var instrumentationData
#if !READYTORUN
                        , _compilation.CanConstructType
#endif
                        );
#pragma warning restore SA1001, SA1113, SA1115 // Commas should be spaced correctly

                    pgoResults.pInstrumentationData = (byte*)GetPin(instrumentationData);
                    pgoResults.countSchemaItems = (uint)nativeSchemas.Length;
                    pgoResults.pSchema = (PgoInstrumentationSchema*)GetPin(nativeSchemas);
                    pgoResults.hr = HRESULT.S_OK;
                }

                _pgoResults.Add(methodDesc, pgoResults);
            }

            pSchema = pgoResults.pSchema;
            countSchemaItems = pgoResults.countSchemaItems;
            *pInstrumentationData = pgoResults.pInstrumentationData;
            pPgoSource = PgoSource.Static;
            return pgoResults.hr;
        }

#if READYTORUN
        InstructionSetFlags _actualInstructionSetSupported;
        InstructionSetFlags _actualInstructionSetUnsupported;

        private bool notifyInstructionSetUsage(InstructionSet instructionSet, bool supportEnabled)
        {
            instructionSet = InstructionSetFlags.ConvertToImpliedInstructionSetForVectorInstructionSets(_compilation.TypeSystemContext.Target.Architecture, instructionSet);

            Debug.Assert(!_compilation.InstructionSetSupport.NonSpecifiableFlags.HasInstructionSet(instructionSet));

            if (supportEnabled)
            {
                _actualInstructionSetSupported.AddInstructionSet(instructionSet);
            }
            else
            {
                // By policy we code review all changes into corelib, such that failing to use an instruction
                // set is not a reason to not support usage of it.
                if (!isMethodDefinedInCoreLib())
                {
                    _actualInstructionSetUnsupported.AddInstructionSet(instructionSet);
                }
            }
            return supportEnabled;
        }
#else
        private bool notifyInstructionSetUsage(InstructionSet instructionSet, bool supportEnabled)
        {
            instructionSet = InstructionSetFlags.ConvertToImpliedInstructionSetForVectorInstructionSets(_compilation.TypeSystemContext.Target.Architecture, instructionSet);

            Debug.Assert(!_compilation.InstructionSetSupport.NonSpecifiableFlags.HasInstructionSet(instructionSet));

            return supportEnabled ? _compilation.InstructionSetSupport.IsInstructionSetSupported(instructionSet) : false;
        }
#endif
    }
}