summaryrefslogtreecommitdiff
path: root/src/vm/i386/stublinkerx86.cpp
blob: 7020e40e51b7cfdf092c0880472ca24d9275e150 (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
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.


// NOTE on Frame Size C_ASSERT usage in this file 
// if the frame size changes then the stubs have to be revisited for correctness
// kindly revist the logic and then update the constants so that the C_ASSERT will again fire
// if someone changes the frame size.  You are expected to keep this hard coded constant
// up to date so that changes in the frame size trigger errors at compile time if the code is not altered

// Precompiled Header

#include "common.h"

#include "field.h"
#include "stublink.h"

#include "frames.h"
#include "excep.h"
#include "dllimport.h"
#include "log.h"
#include "comdelegate.h"
#include "array.h"
#include "jitinterface.h"
#include "codeman.h"
#include "dbginterface.h"
#include "eeprofinterfaces.h"
#include "eeconfig.h"
#ifdef _TARGET_X86_
#include "asmconstants.h"
#endif // _TARGET_X86_
#include "class.h"
#include "stublink.inl"

#ifdef FEATURE_COMINTEROP
#include "comtoclrcall.h"
#include "runtimecallablewrapper.h"
#include "comcache.h"
#include "olevariant.h"
#include "notifyexternals.h"
#endif // FEATURE_COMINTEROP

#ifdef FEATURE_PREJIT
#include "compile.h"
#endif

#if defined(_DEBUG) && defined(STUBLINKER_GENERATES_UNWIND_INFO)
#include <psapi.h>
#endif


#ifndef DACCESS_COMPILE

extern "C" VOID __cdecl StubRareEnable(Thread *pThread);
#ifdef FEATURE_COMINTEROP
extern "C" HRESULT __cdecl StubRareDisableHR(Thread *pThread);
#endif // FEATURE_COMINTEROP
extern "C" VOID __cdecl StubRareDisableTHROW(Thread *pThread, Frame *pFrame);

#ifndef FEATURE_ARRAYSTUB_AS_IL
extern "C" VOID __cdecl ArrayOpStubNullException(void);
extern "C" VOID __cdecl ArrayOpStubRangeException(void);
extern "C" VOID __cdecl ArrayOpStubTypeMismatchException(void);

#if defined(_TARGET_AMD64_)
#define EXCEPTION_HELPERS(base) \
    extern "C" VOID __cdecl base##_RSIRDI_ScratchArea(void); \
    extern "C" VOID __cdecl base##_ScratchArea(void); \
    extern "C" VOID __cdecl base##_RSIRDI(void); \
    extern "C" VOID __cdecl base(void)
EXCEPTION_HELPERS(ArrayOpStubNullException);
EXCEPTION_HELPERS(ArrayOpStubRangeException);
EXCEPTION_HELPERS(ArrayOpStubTypeMismatchException);
#undef EXCEPTION_HELPERS
#endif // !_TARGET_AMD64_
#endif // !FEATURE_ARRAYSTUB_AS_IL

#if defined(_TARGET_AMD64_)
#if defined(_DEBUG)
extern "C" VOID __cdecl DebugCheckStubUnwindInfo();
#endif // _DEBUG
#endif // _TARGET_AMD64_

// Presumably this code knows what it is doing with TLS.  If we are hiding these
// services from normal code, reveal them here.
#ifdef TlsGetValue
#undef TlsGetValue
#endif

#ifdef FEATURE_COMINTEROP
Thread* __stdcall CreateThreadBlockReturnHr(ComMethodFrame *pFrame);
#endif



#ifdef _TARGET_AMD64_

BOOL IsPreservedReg (X86Reg reg)
{
    UINT16 PreservedRegMask =
          (1 << kRBX)
        | (1 << kRBP)
        | (1 << kRSI)
        | (1 << kRDI)
        | (1 << kR12)
        | (1 << kR13)
        | (1 << kR14)
        | (1 << kR15);
    return PreservedRegMask & (1 << reg);
}

#endif // _TARGET_AMD64_

#ifdef _TARGET_AMD64_
//-----------------------------------------------------------------------
// InstructionFormat for near Jump and short Jump
//-----------------------------------------------------------------------

//X64EmitTailcallWithRSPAdjust
class X64NearJumpSetup : public InstructionFormat
{
    public:
        X64NearJumpSetup() : InstructionFormat(  InstructionFormat::k8|InstructionFormat::k32
                                                       | InstructionFormat::k64Small | InstructionFormat::k64
                                                      )
        {
            LIMITED_METHOD_CONTRACT;
        }

        virtual UINT GetSizeOfInstruction(UINT refsize, UINT variationCode)
        {
            LIMITED_METHOD_CONTRACT
            switch (refsize)
            {
                case k8:
                    return 0;

                case k32:
                    return 0;

                case k64Small:
                    return 5;

                case k64:
                    return 10;

                default:
                    _ASSERTE(!"unexpected refsize");
                    return 0;

            }
        }

        virtual VOID EmitInstruction(UINT refsize, __int64 fixedUpReference, BYTE *pOutBuffer, UINT variationCode, BYTE *pDataBuffer)
        {
            LIMITED_METHOD_CONTRACT
            if (k8 == refsize)
            {
                // do nothing, X64NearJump will take care of this
            }
            else if (k32 == refsize)
            {
                // do nothing, X64NearJump will take care of this
            }
            else if (k64Small == refsize)
            {
                UINT64 TargetAddress = (INT64)pOutBuffer + fixedUpReference + GetSizeOfInstruction(refsize, variationCode);
                _ASSERTE(FitsInU4(TargetAddress));

                // mov eax, imm32  ; zero-extended
                pOutBuffer[0] = 0xB8;
                *((UINT32*)&pOutBuffer[1]) = (UINT32)TargetAddress;
            }
            else if (k64 == refsize)
            {
                // mov rax, imm64
                pOutBuffer[0] = REX_PREFIX_BASE | REX_OPERAND_SIZE_64BIT;
                pOutBuffer[1] = 0xB8;
                *((UINT64*)&pOutBuffer[2]) = (UINT64)(((INT64)pOutBuffer) + fixedUpReference + GetSizeOfInstruction(refsize, variationCode));
            }
            else
            {
                _ASSERTE(!"unreached");
            }
        }

        virtual BOOL CanReach(UINT refsize, UINT variationCode, BOOL fExternal, INT_PTR offset)
        {
            STATIC_CONTRACT_NOTHROW;
            STATIC_CONTRACT_GC_NOTRIGGER;
            STATIC_CONTRACT_FORBID_FAULT;


            if (fExternal)
            {
                switch (refsize)
                {
                case InstructionFormat::k8:
                    // For external, we don't have enough info to predict
                    // the offset.
                    return FALSE;

                case InstructionFormat::k32:
                    return sizeof(PVOID) <= sizeof(UINT32);

                case InstructionFormat::k64Small:
                    return FitsInI4(offset);

                case InstructionFormat::k64:
                    // intentional fallthru
                case InstructionFormat::kAllowAlways:
                    return TRUE;

                default:
                    _ASSERTE(0);
                    return FALSE;
                }
            }
            else
            {
                switch (refsize)
                {
                case InstructionFormat::k8:
                    return FitsInI1(offset);

                case InstructionFormat::k32:
                    return FitsInI4(offset);

                case InstructionFormat::k64Small:
                    // EmitInstruction emits a non-relative jmp for
                    // k64Small.  We don't have enough info to predict the
                    // target address.  (Even if we did, this would only
                    // handle the set of unsigned offsets with bit 31 set
                    // and no higher bits set, too uncommon/hard to test.)
                    return FALSE;

                case InstructionFormat::k64:
                    // intentional fallthru
                case InstructionFormat::kAllowAlways:
                    return TRUE;
                default:
                    _ASSERTE(0);
                    return FALSE;
                }
            }
        }
};

class X64NearJumpExecute : public InstructionFormat
{
    public:
        X64NearJumpExecute() : InstructionFormat(  InstructionFormat::k8|InstructionFormat::k32
                                                 | InstructionFormat::k64Small | InstructionFormat::k64
                                                 )
        {
            LIMITED_METHOD_CONTRACT;
        }

        virtual UINT GetSizeOfInstruction(UINT refsize, UINT variationCode)
        {
            LIMITED_METHOD_CONTRACT
            switch (refsize)
            {
                case k8:
                    return 2;

                case k32:
                    return 5;

                case k64Small:
                    return 3;

                case k64:
                    return 3;

                default:
                    _ASSERTE(!"unexpected refsize");
                    return 0;

            }
        }

        virtual VOID EmitInstruction(UINT refsize, __int64 fixedUpReference, BYTE *pOutBuffer, UINT variationCode, BYTE *pDataBuffer)
        {
            LIMITED_METHOD_CONTRACT
            if (k8 == refsize)
            {
                pOutBuffer[0] = 0xeb;
                *((__int8*)(pOutBuffer+1)) = (__int8)fixedUpReference;
            }
            else if (k32 == refsize)
            {
                pOutBuffer[0] = 0xe9;
                *((__int32*)(pOutBuffer+1)) = (__int32)fixedUpReference;
            }
            else if (k64Small == refsize)
            {
                // REX.W jmp rax
                pOutBuffer[0] = REX_PREFIX_BASE | REX_OPERAND_SIZE_64BIT;
                pOutBuffer[1] = 0xFF;
                pOutBuffer[2] = 0xE0;
            }
            else if (k64 == refsize)
            {
                // REX.W jmp rax
                pOutBuffer[0] = REX_PREFIX_BASE | REX_OPERAND_SIZE_64BIT;
                pOutBuffer[1] = 0xFF;
                pOutBuffer[2] = 0xE0;
            }
            else
            {
                _ASSERTE(!"unreached");
            }
        }

        virtual BOOL CanReach(UINT refsize, UINT variationCode, BOOL fExternal, INT_PTR offset)
        {
            STATIC_CONTRACT_NOTHROW;
            STATIC_CONTRACT_GC_NOTRIGGER;
            STATIC_CONTRACT_FORBID_FAULT;


            if (fExternal)
            {
                switch (refsize)
                {
                case InstructionFormat::k8:
                    // For external, we don't have enough info to predict
                    // the offset.
                    return FALSE;

                case InstructionFormat::k32:
                    return sizeof(PVOID) <= sizeof(UINT32);

                case InstructionFormat::k64Small:
                    return FitsInI4(offset);

                case InstructionFormat::k64:
                    // intentional fallthru
                case InstructionFormat::kAllowAlways:
                    return TRUE;

                default:
                    _ASSERTE(0);
                    return FALSE;
                }
            }
            else
            {
                switch (refsize)
                {
                case InstructionFormat::k8:
                    return FitsInI1(offset);

                case InstructionFormat::k32:
                    return FitsInI4(offset);

                case InstructionFormat::k64Small:
                    // EmitInstruction emits a non-relative jmp for
                    // k64Small.  We don't have enough info to predict the
                    // target address.  (Even if we did, this would only
                    // handle the set of unsigned offsets with bit 31 set
                    // and no higher bits set, too uncommon/hard to test.)
                    return FALSE;

                case InstructionFormat::k64:
                    // intentional fallthru
                case InstructionFormat::kAllowAlways:
                    return TRUE;
                default:
                    _ASSERTE(0);
                    return FALSE;
                }
            }
        }
};

#endif

//-----------------------------------------------------------------------
// InstructionFormat for near Jump and short Jump
//-----------------------------------------------------------------------
class X86NearJump : public InstructionFormat
{
    public:
        X86NearJump() : InstructionFormat(  InstructionFormat::k8|InstructionFormat::k32
#ifdef _TARGET_AMD64_
                                          | InstructionFormat::k64Small | InstructionFormat::k64
#endif // _TARGET_AMD64_
                                          )
        {
            LIMITED_METHOD_CONTRACT;
        }

        virtual UINT GetSizeOfInstruction(UINT refsize, UINT variationCode)
        {
            LIMITED_METHOD_CONTRACT
            switch (refsize)
            {
                case k8:
                    return 2;

                case k32:
                    return 5;
#ifdef _TARGET_AMD64_
                case k64Small:
                    return 5 + 2;

                case k64:
                    return 12;
#endif // _TARGET_AMD64_
                default:
                    _ASSERTE(!"unexpected refsize");
                    return 0;

            }
        }

        virtual VOID EmitInstruction(UINT refsize, __int64 fixedUpReference, BYTE *pOutBuffer, UINT variationCode, BYTE *pDataBuffer)
        {
            LIMITED_METHOD_CONTRACT
            if (k8 == refsize)
            {
                pOutBuffer[0] = 0xeb;
                *((__int8*)(pOutBuffer+1)) = (__int8)fixedUpReference;
            }
            else if (k32 == refsize)
            {
                pOutBuffer[0] = 0xe9;
                *((__int32*)(pOutBuffer+1)) = (__int32)fixedUpReference;
            }
#ifdef _TARGET_AMD64_
            else if (k64Small == refsize)
            {
                UINT64 TargetAddress = (INT64)pOutBuffer + fixedUpReference + GetSizeOfInstruction(refsize, variationCode);
                _ASSERTE(FitsInU4(TargetAddress));

                // mov eax, imm32  ; zero-extended
                pOutBuffer[0] = 0xB8;
                *((UINT32*)&pOutBuffer[1]) = (UINT32)TargetAddress;

                // jmp rax
                pOutBuffer[5] = 0xFF;
                pOutBuffer[6] = 0xE0;
            }
            else if (k64 == refsize)
            {
                // mov rax, imm64
                pOutBuffer[0] = REX_PREFIX_BASE | REX_OPERAND_SIZE_64BIT;
                pOutBuffer[1] = 0xB8;
                *((UINT64*)&pOutBuffer[2]) = (UINT64)(((INT64)pOutBuffer) + fixedUpReference + GetSizeOfInstruction(refsize, variationCode));

                // jmp rax
                pOutBuffer[10] = 0xFF;
                pOutBuffer[11] = 0xE0;
            }
#endif // _TARGET_AMD64_
            else
            {
                _ASSERTE(!"unreached");
            }
        }

        virtual BOOL CanReach(UINT refsize, UINT variationCode, BOOL fExternal, INT_PTR offset)
        {
            STATIC_CONTRACT_NOTHROW;
            STATIC_CONTRACT_GC_NOTRIGGER;
            STATIC_CONTRACT_FORBID_FAULT;


            if (fExternal)
            {
                switch (refsize)
                {
                case InstructionFormat::k8:
                    // For external, we don't have enough info to predict
                    // the offset.
                    return FALSE;

                case InstructionFormat::k32:
                    return sizeof(PVOID) <= sizeof(UINT32);

#ifdef _TARGET_AMD64_
                case InstructionFormat::k64Small:
                    return FitsInI4(offset);

                case InstructionFormat::k64:
                    // intentional fallthru
#endif
                case InstructionFormat::kAllowAlways:
                    return TRUE;

                default:
                    _ASSERTE(0);
                    return FALSE;
                }
            }
            else
            {
                switch (refsize)
                {
                case InstructionFormat::k8:
                    return FitsInI1(offset);

                case InstructionFormat::k32:
#ifdef _TARGET_AMD64_
                    return FitsInI4(offset);
#else
                    return TRUE;
#endif

#ifdef _TARGET_AMD64_
                case InstructionFormat::k64Small:
                    // EmitInstruction emits a non-relative jmp for
                    // k64Small.  We don't have enough info to predict the
                    // target address.  (Even if we did, this would only
                    // handle the set of unsigned offsets with bit 31 set
                    // and no higher bits set, too uncommon/hard to test.)
                    return FALSE;

                case InstructionFormat::k64:
                    // intentional fallthru
#endif
                case InstructionFormat::kAllowAlways:
                    return TRUE;
                default:
                    _ASSERTE(0);
                    return FALSE;
                }
            }
        }
};


//-----------------------------------------------------------------------
// InstructionFormat for conditional jump. Set the variationCode
// to members of X86CondCode.
//-----------------------------------------------------------------------
class X86CondJump : public InstructionFormat
{
    public:
        X86CondJump(UINT allowedSizes) : InstructionFormat(allowedSizes)
        {
            LIMITED_METHOD_CONTRACT;
        }

        virtual UINT GetSizeOfInstruction(UINT refsize, UINT variationCode)
        {
        LIMITED_METHOD_CONTRACT
            return (refsize == k8 ? 2 : 6);
        }

        virtual VOID EmitInstruction(UINT refsize, __int64 fixedUpReference, BYTE *pOutBuffer, UINT variationCode, BYTE *pDataBuffer)
        {
        LIMITED_METHOD_CONTRACT
        if (refsize == k8)
        {
                pOutBuffer[0] = static_cast<BYTE>(0x70 | variationCode);
                *((__int8*)(pOutBuffer+1)) = (__int8)fixedUpReference;
        }
        else
        {
                pOutBuffer[0] = 0x0f;
                pOutBuffer[1] = static_cast<BYTE>(0x80 | variationCode);
                *((__int32*)(pOutBuffer+2)) = (__int32)fixedUpReference;
            }
        }
};


//-----------------------------------------------------------------------
// InstructionFormat for near call.
//-----------------------------------------------------------------------
class X86Call : public InstructionFormat
{
    public:
        X86Call ()
            : InstructionFormat(  InstructionFormat::k32
#ifdef _TARGET_AMD64_
                                | InstructionFormat::k64Small | InstructionFormat::k64
#endif // _TARGET_AMD64_
                                )
        {
            LIMITED_METHOD_CONTRACT;
        }

        virtual UINT GetSizeOfInstruction(UINT refsize, UINT variationCode)
        {
            LIMITED_METHOD_CONTRACT;

            switch (refsize)
            {
            case k32:
                return 5;

#ifdef _TARGET_AMD64_
            case k64Small:
                return 5 + 2;

            case k64:
                return 10 + 2;
#endif // _TARGET_AMD64_

            default:
                _ASSERTE(!"unexpected refsize");
                return 0;
            }
        }

        virtual VOID EmitInstruction(UINT refsize, __int64 fixedUpReference, BYTE *pOutBuffer, UINT variationCode, BYTE *pDataBuffer)
        {
            LIMITED_METHOD_CONTRACT

            switch (refsize)
            {
            case k32:
                pOutBuffer[0] = 0xE8;
                *((__int32*)(1+pOutBuffer)) = (__int32)fixedUpReference;
                break;

#ifdef _TARGET_AMD64_
            case k64Small:
                UINT64 TargetAddress;

                TargetAddress = (INT64)pOutBuffer + fixedUpReference + GetSizeOfInstruction(refsize, variationCode);
                _ASSERTE(FitsInU4(TargetAddress));

                // mov  eax,<fixedUpReference>  ; zero-extends
                pOutBuffer[0] = 0xB8;
                *((UINT32*)&pOutBuffer[1]) = (UINT32)TargetAddress;

                // call rax
                pOutBuffer[5] = 0xff;
                pOutBuffer[6] = 0xd0;
                break;

            case k64:
                // mov  rax,<fixedUpReference>
                pOutBuffer[0] = REX_PREFIX_BASE | REX_OPERAND_SIZE_64BIT;
                pOutBuffer[1] = 0xB8;
                *((UINT64*)&pOutBuffer[2]) = (UINT64)(((INT64)pOutBuffer) + fixedUpReference + GetSizeOfInstruction(refsize, variationCode));

                // call rax
                pOutBuffer[10] = 0xff;
                pOutBuffer[11] = 0xd0;
                break;
#endif // _TARGET_AMD64_

            default:
                _ASSERTE(!"unreached");
                break;
            }
        }

// For x86, the default CanReach implementation will suffice.  It only needs
// to handle k32.
#ifdef _TARGET_AMD64_
        virtual BOOL CanReach(UINT refsize, UINT variationCode, BOOL fExternal, INT_PTR offset)
        {
            if (fExternal)
            {
                switch (refsize)
                {
                case InstructionFormat::k32:
                    // For external, we don't have enough info to predict
                    // the offset.
                    return FALSE;

                case InstructionFormat::k64Small:
                    return FitsInI4(offset);

                case InstructionFormat::k64:
                    // intentional fallthru
                case InstructionFormat::kAllowAlways:
                    return TRUE;

                default:
                    _ASSERTE(0);
                    return FALSE;
                }
            }
            else
            {
                switch (refsize)
                {
                case InstructionFormat::k32:
                    return FitsInI4(offset);

                case InstructionFormat::k64Small:
                    // EmitInstruction emits a non-relative jmp for
                    // k64Small.  We don't have enough info to predict the
                    // target address.  (Even if we did, this would only
                    // handle the set of unsigned offsets with bit 31 set
                    // and no higher bits set, too uncommon/hard to test.)
                    return FALSE;

                case InstructionFormat::k64:
                    // intentional fallthru
                case InstructionFormat::kAllowAlways:
                    return TRUE;
                default:
                    _ASSERTE(0);
                    return FALSE;
                }
            }
        }
#endif // _TARGET_AMD64_
};


//-----------------------------------------------------------------------
// InstructionFormat for push imm32.
//-----------------------------------------------------------------------
class X86PushImm32 : public InstructionFormat
{
    public:
        X86PushImm32(UINT allowedSizes) : InstructionFormat(allowedSizes)
        {
            LIMITED_METHOD_CONTRACT;
        }

        virtual UINT GetSizeOfInstruction(UINT refsize, UINT variationCode)
        {
            LIMITED_METHOD_CONTRACT;

            return 5;
        }

        virtual VOID EmitInstruction(UINT refsize, __int64 fixedUpReference, BYTE *pOutBuffer, UINT variationCode, BYTE *pDataBuffer)
        {
            LIMITED_METHOD_CONTRACT;

            pOutBuffer[0] = 0x68;
            // only support absolute pushimm32 of the label address. The fixedUpReference is
            // the offset to the label from the current point, so add to get address
            *((__int32*)(1+pOutBuffer)) = (__int32)(fixedUpReference);
        }
};

#if defined(_TARGET_AMD64_)
//-----------------------------------------------------------------------
// InstructionFormat for lea reg, [RIP relative].
//-----------------------------------------------------------------------
class X64LeaRIP : public InstructionFormat
{
    public:
        X64LeaRIP() : InstructionFormat(InstructionFormat::k64Small)
        {
            LIMITED_METHOD_CONTRACT;
        }

        virtual UINT GetSizeOfInstruction(UINT refsize, UINT variationCode)
        {
            LIMITED_METHOD_CONTRACT;

            return 7;
        }

        virtual BOOL CanReach(UINT refsize, UINT variationCode, BOOL fExternal, INT_PTR offset)
        {
            if (fExternal)
            {
                switch (refsize)
                {
                case InstructionFormat::k64Small:
                    // For external, we don't have enough info to predict
                    // the offset.
                    return FALSE;

                case InstructionFormat::k64:
                    // intentional fallthru
                case InstructionFormat::kAllowAlways:
                    return TRUE;

                default:
                    _ASSERTE(0);
                    return FALSE;
                }
            }
            else
            {
                switch (refsize)
                {
                case InstructionFormat::k64Small:
                    return FitsInI4(offset);

                case InstructionFormat::k64:
                    // intentional fallthru
                case InstructionFormat::kAllowAlways:
                    return TRUE;

                default:
                    _ASSERTE(0);
                    return FALSE;
                }
            }
        }

        virtual VOID EmitInstruction(UINT refsize, __int64 fixedUpReference, BYTE *pOutBuffer, UINT variationCode, BYTE *pDataBuffer)
        {
            LIMITED_METHOD_CONTRACT;

            X86Reg reg = (X86Reg)variationCode;
            BYTE rex = REX_PREFIX_BASE | REX_OPERAND_SIZE_64BIT;

            if (reg >= kR8)
            {
                rex |= REX_MODRM_REG_EXT;
                reg = X86RegFromAMD64Reg(reg);
            }

            pOutBuffer[0] = rex;
            pOutBuffer[1] = 0x8D;
            pOutBuffer[2] = 0x05 | (reg << 3);
            // only support absolute pushimm32 of the label address. The fixedUpReference is
            // the offset to the label from the current point, so add to get address
            *((__int32*)(3+pOutBuffer)) = (__int32)(fixedUpReference);
        }
};

#endif // _TARGET_AMD64_

#if defined(_TARGET_AMD64_)
static BYTE gX64NearJumpSetup[sizeof(X64NearJumpSetup)];
static BYTE gX64NearJumpExecute[sizeof(X64NearJumpExecute)];
static BYTE gX64LeaRIP[sizeof(X64LeaRIP)];
#endif

static BYTE gX86NearJump[sizeof(X86NearJump)];
static BYTE gX86CondJump[sizeof(X86CondJump)];
static BYTE gX86Call[sizeof(X86Call)];
static BYTE gX86PushImm32[sizeof(X86PushImm32)];

/* static */ void StubLinkerCPU::Init()
{
    CONTRACTL
    {
        THROWS;
        GC_NOTRIGGER;
        INJECT_FAULT(COMPlusThrowOM(););
    }
    CONTRACTL_END;
    new (gX86NearJump) X86NearJump();
    new (gX86CondJump) X86CondJump( InstructionFormat::k8|InstructionFormat::k32);
    new (gX86Call) X86Call();
    new (gX86PushImm32) X86PushImm32(InstructionFormat::k32);

#if defined(_TARGET_AMD64_)
    new (gX64NearJumpSetup) X64NearJumpSetup();
    new (gX64NearJumpExecute) X64NearJumpExecute();
    new (gX64LeaRIP) X64LeaRIP();
#endif
}

//---------------------------------------------------------------
// Emits:
//    mov destReg, srcReg
//---------------------------------------------------------------
VOID StubLinkerCPU::X86EmitMovRegReg(X86Reg destReg, X86Reg srcReg)
{
    STANDARD_VM_CONTRACT;

#ifdef _TARGET_AMD64_
    BYTE rex = REX_PREFIX_BASE | REX_OPERAND_SIZE_64BIT;

    if (destReg >= kR8)
    {
        rex |= REX_MODRM_RM_EXT;
        destReg = X86RegFromAMD64Reg(destReg);
    }
    if (srcReg >= kR8)
    {
        rex |= REX_MODRM_REG_EXT;
        srcReg = X86RegFromAMD64Reg(srcReg);
    }
    Emit8(rex);
#endif

    Emit8(0x89);
    Emit8(static_cast<UINT8>(0xC0 | (srcReg << 3) | destReg));
}

//---------------------------------------------------------------

VOID StubLinkerCPU::X86EmitMovSPReg(X86Reg srcReg)
{
    STANDARD_VM_CONTRACT;
    const X86Reg kESP = (X86Reg)4;
    X86EmitMovRegReg(kESP, srcReg);
}

VOID StubLinkerCPU::X86EmitMovRegSP(X86Reg destReg)
{
    STANDARD_VM_CONTRACT;
    const X86Reg kESP = (X86Reg)4;
    X86EmitMovRegReg(destReg, kESP);
}


//---------------------------------------------------------------
// Emits:
//    PUSH <reg32>
//---------------------------------------------------------------
VOID StubLinkerCPU::X86EmitPushReg(X86Reg reg)
{
    STANDARD_VM_CONTRACT;

#ifdef STUBLINKER_GENERATES_UNWIND_INFO
    X86Reg origReg = reg;
#endif

#ifdef _TARGET_AMD64_
    if (reg >= kR8)
    {
        Emit8(REX_PREFIX_BASE | REX_OPERAND_SIZE_64BIT | REX_OPCODE_REG_EXT);
        reg = X86RegFromAMD64Reg(reg);
    }
#endif
    Emit8(static_cast<UINT8>(0x50 + reg));

#ifdef STUBLINKER_GENERATES_UNWIND_INFO
    if (IsPreservedReg(origReg))
    {
        UnwindPushedReg(origReg);
    }
    else
#endif
    {
        Push(sizeof(void*));
    }
}


//---------------------------------------------------------------
// Emits:
//    POP <reg32>
//---------------------------------------------------------------
VOID StubLinkerCPU::X86EmitPopReg(X86Reg reg)
{
    STANDARD_VM_CONTRACT;

#ifdef _TARGET_AMD64_
    if (reg >= kR8)
    {
        Emit8(REX_PREFIX_BASE | REX_OPERAND_SIZE_64BIT | REX_OPCODE_REG_EXT);
        reg = X86RegFromAMD64Reg(reg);
    }
#endif // _TARGET_AMD64_

    Emit8(static_cast<UINT8>(0x58 + reg));
    Pop(sizeof(void*));
}

//---------------------------------------------------------------
// Emits:
//    PUSH <imm32>
//---------------------------------------------------------------
VOID StubLinkerCPU::X86EmitPushImm32(UINT32 value)
{
    STANDARD_VM_CONTRACT;

    Emit8(0x68);
    Emit32(value);
    Push(sizeof(void*));
}


//---------------------------------------------------------------
// Emits:
//    PUSH <imm32>
//---------------------------------------------------------------
VOID StubLinkerCPU::X86EmitPushImm32(CodeLabel &target)
{
    STANDARD_VM_CONTRACT;

    EmitLabelRef(&target, reinterpret_cast<X86PushImm32&>(gX86PushImm32), 0);
}


//---------------------------------------------------------------
// Emits:
//    PUSH <imm8>
//---------------------------------------------------------------
VOID StubLinkerCPU::X86EmitPushImm8(BYTE value)
{
    STANDARD_VM_CONTRACT;

    Emit8(0x6a);
    Emit8(value);
    Push(sizeof(void*));
}


//---------------------------------------------------------------
// Emits:
//    PUSH <ptr>
//---------------------------------------------------------------
VOID StubLinkerCPU::X86EmitPushImmPtr(LPVOID value WIN64_ARG(X86Reg tmpReg /*=kR10*/))
{
    STANDARD_VM_CONTRACT;

#ifdef _TARGET_AMD64_
    X86EmitRegLoad(tmpReg, (UINT_PTR) value);
    X86EmitPushReg(tmpReg);
#else
    X86EmitPushImm32((UINT_PTR) value);
#endif
}

//---------------------------------------------------------------
// Emits:
//    XOR <reg32>,<reg32>
//---------------------------------------------------------------
VOID StubLinkerCPU::X86EmitZeroOutReg(X86Reg reg)
{
    STANDARD_VM_CONTRACT;

#ifdef _TARGET_AMD64_
    // 32-bit results are zero-extended, so we only need the REX byte if
    // it's an extended register.
    if (reg >= kR8)
    {
        Emit8(REX_PREFIX_BASE | REX_MODRM_REG_EXT | REX_MODRM_RM_EXT);
        reg = X86RegFromAMD64Reg(reg);
    }
#endif
    Emit8(0x33);
    Emit8(static_cast<UINT8>(0xc0 | (reg << 3) | reg));
}

//---------------------------------------------------------------
// Emits:
//    jmp [reg]
//---------------------------------------------------------------
VOID StubLinkerCPU::X86EmitJumpReg(X86Reg reg)
{
    CONTRACTL
    {
        STANDARD_VM_CHECK;
    }
    CONTRACTL_END;

    Emit8(0xff);
    Emit8(static_cast<BYTE>(0xe0) | static_cast<BYTE>(reg));
}

//---------------------------------------------------------------
// Emits:
//    CMP <reg32>,imm32
//---------------------------------------------------------------
VOID StubLinkerCPU::X86EmitCmpRegImm32(X86Reg reg, INT32 imm32)
{
    CONTRACTL
    {
        STANDARD_VM_CHECK;
        PRECONDITION((int) reg < NumX86Regs);
    }
    CONTRACTL_END;

#ifdef _TARGET_AMD64_
    BYTE rex = REX_PREFIX_BASE | REX_OPERAND_SIZE_64BIT;

    if (reg >= kR8)
    {
        rex |= REX_OPCODE_REG_EXT;
        reg = X86RegFromAMD64Reg(reg);
    }
    Emit8(rex);
#endif

    if (FitsInI1(imm32)) {
        Emit8(0x83);
        Emit8(static_cast<UINT8>(0xF8 | reg));
        Emit8((INT8)imm32);
    } else {
        Emit8(0x81);
        Emit8(static_cast<UINT8>(0xF8 | reg));
        Emit32(imm32);
    }
}

#ifdef _TARGET_AMD64_
//---------------------------------------------------------------
// Emits:
//    CMP [reg+offs], imm32
//    CMP [reg], imm32
//---------------------------------------------------------------
VOID StubLinkerCPU:: X86EmitCmpRegIndexImm32(X86Reg reg, INT32 offs, INT32 imm32)
{
    STANDARD_VM_CONTRACT;

    BYTE rex = REX_PREFIX_BASE | REX_OPERAND_SIZE_64BIT;

    if (reg >= kR8)
    {
        rex |= REX_OPCODE_REG_EXT;
        reg = X86RegFromAMD64Reg(reg);
    }
    Emit8(rex);

    X64EmitCmp32RegIndexImm32(reg, offs, imm32);
}

VOID StubLinkerCPU:: X64EmitCmp32RegIndexImm32(X86Reg reg, INT32 offs, INT32 imm32)
#else // _TARGET_AMD64_
VOID StubLinkerCPU:: X86EmitCmpRegIndexImm32(X86Reg reg, INT32 offs, INT32 imm32)
#endif // _TARGET_AMD64_
{
    CONTRACTL
    {
        STANDARD_VM_CHECK;
        PRECONDITION((int) reg < NumX86Regs);
    }
    CONTRACTL_END;

    //
    // The binary representation of "cmp [mem], imm32" is :
    // 1000-00sw  mod11-1r/m
    //
    
    unsigned wBit = (FitsInI1(imm32) ? 0 : 1);
    Emit8(static_cast<UINT8>(0x80 | wBit));
    
    unsigned modBits;
    if (offs == 0)
        modBits = 0;
    else if (FitsInI1(offs))
        modBits = 1;
    else
        modBits = 2;
    
    Emit8(static_cast<UINT8>((modBits << 6) | 0x38 | reg));

    if (offs)
    {
        if (FitsInI1(offs))
            Emit8((INT8)offs);
        else
            Emit32(offs);
    }
    
    if (FitsInI1(imm32))
        Emit8((INT8)imm32);
    else
        Emit32(imm32);
}

//---------------------------------------------------------------
// Emits:
#if defined(_TARGET_AMD64_)
//  mov     rax, <target>
//  add     rsp, imm32
//  jmp     rax
#else
//  add     rsp, imm32
//  jmp     <target>
#endif
//---------------------------------------------------------------
VOID StubLinkerCPU::X86EmitTailcallWithESPAdjust(CodeLabel *pTarget, INT32 imm32)
{
    STANDARD_VM_CONTRACT;

#if defined(_TARGET_AMD64_)
    EmitLabelRef(pTarget, reinterpret_cast<X64NearJumpSetup&>(gX64NearJumpSetup), 0);
    X86EmitAddEsp(imm32);
    EmitLabelRef(pTarget, reinterpret_cast<X64NearJumpExecute&>(gX64NearJumpExecute), 0);
#else
    X86EmitAddEsp(imm32);
    X86EmitNearJump(pTarget);
#endif
}

//---------------------------------------------------------------
// Emits:
#if defined(_TARGET_AMD64_)
//  mov     rax, <target>
//  pop     reg
//  jmp     rax
#else
//  pop     reg
//  jmp     <target>
#endif
//---------------------------------------------------------------
VOID StubLinkerCPU::X86EmitTailcallWithSinglePop(CodeLabel *pTarget, X86Reg reg)
{
    STANDARD_VM_CONTRACT;

#if defined(_TARGET_AMD64_)
    EmitLabelRef(pTarget, reinterpret_cast<X64NearJumpSetup&>(gX64NearJumpSetup), 0);
    X86EmitPopReg(reg);
    EmitLabelRef(pTarget, reinterpret_cast<X64NearJumpExecute&>(gX64NearJumpExecute), 0);
#else
    X86EmitPopReg(reg);
    X86EmitNearJump(pTarget);
#endif
}

//---------------------------------------------------------------
// Emits:
//    JMP <ofs8>   or
//    JMP <ofs32}
//---------------------------------------------------------------
VOID StubLinkerCPU::X86EmitNearJump(CodeLabel *target)
{
    STANDARD_VM_CONTRACT;
    EmitLabelRef(target, reinterpret_cast<X86NearJump&>(gX86NearJump), 0);
}


//---------------------------------------------------------------
// Emits:
//    Jcc <ofs8> or
//    Jcc <ofs32>
//---------------------------------------------------------------
VOID StubLinkerCPU::X86EmitCondJump(CodeLabel *target, X86CondCode::cc condcode)
{
    STANDARD_VM_CONTRACT;
    EmitLabelRef(target, reinterpret_cast<X86CondJump&>(gX86CondJump), condcode);
}


//---------------------------------------------------------------
// Emits:
//    call <ofs32>
//---------------------------------------------------------------
VOID StubLinkerCPU::X86EmitCall(CodeLabel *target, int iArgBytes)
{
    STANDARD_VM_CONTRACT;

    EmitLabelRef(target, reinterpret_cast<X86Call&>(gX86Call), 0);

    INDEBUG(Emit8(0x90));   // Emit a nop after the call in debug so that
                            // we know that this is a call that can directly call
                            // managed code
#ifndef _TARGET_AMD64_
    Pop(iArgBytes);
#endif // !_TARGET_AMD64_
}


//---------------------------------------------------------------
// Emits:
//    ret n
//---------------------------------------------------------------
VOID StubLinkerCPU::X86EmitReturn(WORD wArgBytes)
{
    CONTRACTL
    {
        STANDARD_VM_CHECK;
#if defined(_TARGET_AMD64_) || defined(UNIX_X86_ABI)
        PRECONDITION(wArgBytes == 0);
#endif

    }
    CONTRACTL_END;

    if (wArgBytes == 0)
        Emit8(0xc3);
    else
    {
        Emit8(0xc2);
        Emit16(wArgBytes);
    }

    Pop(wArgBytes);
}

#ifdef _TARGET_AMD64_
//---------------------------------------------------------------
// Emits:
//    JMP <ofs8>   or
//    JMP <ofs32}
//---------------------------------------------------------------
VOID StubLinkerCPU::X86EmitLeaRIP(CodeLabel *target, X86Reg reg)
{
    STANDARD_VM_CONTRACT;
    EmitLabelRef(target, reinterpret_cast<X64LeaRIP&>(gX64LeaRIP), reg);
}
#endif // _TARGET_AMD64_



VOID StubLinkerCPU::X86EmitPushRegs(unsigned regSet)
{
    STANDARD_VM_CONTRACT;

    for (X86Reg r = kEAX; r <= NumX86Regs; r = (X86Reg)(r+1))
        if (regSet & (1U<<r))
        {
            X86EmitPushReg(r);
        }
}


VOID StubLinkerCPU::X86EmitPopRegs(unsigned regSet)
{
    STANDARD_VM_CONTRACT;

    for (X86Reg r = NumX86Regs; r >= kEAX; r = (X86Reg)(r-1))
        if (regSet & (1U<<r))
            X86EmitPopReg(r);
}


//---------------------------------------------------------------
// Emits:
//    mov <dstreg>, [<srcreg> + <ofs>]
//---------------------------------------------------------------
VOID StubLinkerCPU::X86EmitIndexRegLoad(X86Reg dstreg,
                                        X86Reg srcreg,
                                        __int32 ofs)
{
    STANDARD_VM_CONTRACT;
    X86EmitOffsetModRM(0x8b, dstreg, srcreg, ofs);
}


//---------------------------------------------------------------
// Emits:
//    mov [<dstreg> + <ofs>],<srcreg>
//
// Note: If you intend to use this to perform 64bit moves to a RSP
//       based offset, then this method may not work. Consider
//       using X86EmitIndexRegStoreRSP.
//---------------------------------------------------------------
VOID StubLinkerCPU::X86EmitIndexRegStore(X86Reg dstreg,
                                         __int32 ofs,
                                         X86Reg srcreg)
{
    STANDARD_VM_CONTRACT;

    if (dstreg != kESP_Unsafe)
        X86EmitOffsetModRM(0x89, srcreg, dstreg, ofs);
    else
        X86EmitOp(0x89, srcreg, (X86Reg)kESP_Unsafe,  ofs);
}

#if defined(_TARGET_AMD64_)
//---------------------------------------------------------------
// Emits:
//    mov [RSP + <ofs>],<srcreg>
//
// It marks the instruction has 64bit so that the processor
// performs a 8byte data move to a RSP based stack location.
//---------------------------------------------------------------
VOID StubLinkerCPU::X86EmitIndexRegStoreRSP(__int32 ofs,
                                         X86Reg srcreg)
{
    STANDARD_VM_CONTRACT;

    X86EmitOp(0x89, srcreg, (X86Reg)kESP_Unsafe,  ofs, (X86Reg)0, 0, k64BitOp);
}

//---------------------------------------------------------------
// Emits:
//    mov [R12 + <ofs>],<srcreg>
//
// It marks the instruction has 64bit so that the processor
// performs a 8byte data move to a R12 based stack location.
//---------------------------------------------------------------
VOID StubLinkerCPU::X86EmitIndexRegStoreR12(__int32 ofs,
                                         X86Reg srcreg)
{
    STANDARD_VM_CONTRACT;

    X86EmitOp(0x89, srcreg, (X86Reg)kR12,  ofs, (X86Reg)0, 0, k64BitOp);
}
#endif // defined(_TARGET_AMD64_)

//---------------------------------------------------------------
// Emits:
//    push dword ptr [<srcreg> + <ofs>]
//---------------------------------------------------------------
VOID StubLinkerCPU::X86EmitIndexPush(X86Reg srcreg, __int32 ofs)
{
    STANDARD_VM_CONTRACT;

    if(srcreg != kESP_Unsafe)
        X86EmitOffsetModRM(0xff, (X86Reg)0x6, srcreg, ofs);
    else
        X86EmitOp(0xff,(X86Reg)0x6, srcreg, ofs);

    Push(sizeof(void*));
}

//---------------------------------------------------------------
// Emits:
//    push dword ptr [<baseReg> + <indexReg>*<scale> + <ofs>]
//---------------------------------------------------------------
VOID StubLinkerCPU::X86EmitBaseIndexPush(
        X86Reg baseReg,
        X86Reg indexReg,
        __int32 scale,
        __int32 ofs)
{
    STANDARD_VM_CONTRACT;

    X86EmitOffsetModRmSIB(0xff, (X86Reg)0x6, baseReg, indexReg, scale, ofs);
    Push(sizeof(void*));
}

//---------------------------------------------------------------
// Emits:
//    push dword ptr [ESP + <ofs>]
//---------------------------------------------------------------
VOID StubLinkerCPU::X86EmitSPIndexPush(__int32 ofs)
{
    STANDARD_VM_CONTRACT;

    __int8 ofs8 = (__int8) ofs;
    if (ofs == (__int32) ofs8)
    {
        // The offset can be expressed in a byte (can use the byte
        // form of the push esp instruction)

        BYTE code[] = {0xff, 0x74, 0x24, (BYTE)ofs8};
        EmitBytes(code, sizeof(code));   
    }
    else
    {
        // The offset requires 4 bytes (need to use the long form
        // of the push esp instruction)
 
        BYTE code[] = {0xff, 0xb4, 0x24, 0x0, 0x0, 0x0, 0x0};
        *(__int32 *)(&code[3]) = ofs;        
        EmitBytes(code, sizeof(code));
    }
    
    Push(sizeof(void*));
}


//---------------------------------------------------------------
// Emits:
//    pop dword ptr [<srcreg> + <ofs>]
//---------------------------------------------------------------
VOID StubLinkerCPU::X86EmitIndexPop(X86Reg srcreg, __int32 ofs)
{
    STANDARD_VM_CONTRACT;

    if(srcreg != kESP_Unsafe)
        X86EmitOffsetModRM(0x8f, (X86Reg)0x0, srcreg, ofs);
    else
        X86EmitOp(0x8f,(X86Reg)0x0, srcreg, ofs);

    Pop(sizeof(void*));
}

//---------------------------------------------------------------
// Emits:
//    lea <dstreg>, [<srcreg> + <ofs>
//---------------------------------------------------------------
VOID StubLinkerCPU::X86EmitIndexLea(X86Reg dstreg, X86Reg srcreg, __int32 ofs)
{
    CONTRACTL
    {
        STANDARD_VM_CHECK;
        PRECONDITION((int) dstreg < NumX86Regs);
        PRECONDITION((int) srcreg < NumX86Regs);
    }
    CONTRACTL_END;

    X86EmitOffsetModRM(0x8d, dstreg, srcreg, ofs);
}

#if defined(_TARGET_AMD64_)
VOID StubLinkerCPU::X86EmitIndexLeaRSP(X86Reg dstreg, X86Reg srcreg, __int32 ofs)
{
    STANDARD_VM_CONTRACT;

    X86EmitOp(0x8d, dstreg, (X86Reg)kESP_Unsafe,  ofs, (X86Reg)0, 0, k64BitOp);
}
#endif // defined(_TARGET_AMD64_)

//---------------------------------------------------------------
// Emits:
//   sub esp, IMM
//---------------------------------------------------------------
VOID StubLinkerCPU::X86EmitSubEsp(INT32 imm32)
{
    STANDARD_VM_CONTRACT;

    if (imm32 < 0x1000-100)
    {
        // As long as the esp size is less than 1 page plus a small
        // safety fudge factor, we can just bump esp.
        X86EmitSubEspWorker(imm32);
    }
    else
    {
        // Otherwise, must touch at least one byte for each page.
        while (imm32 >= 0x1000)
        {

            X86EmitSubEspWorker(0x1000-4);
            X86EmitPushReg(kEAX);

            imm32 -= 0x1000;
        }
        if (imm32 < 500)
        {
            X86EmitSubEspWorker(imm32);
        }
        else
        {
            // If the remainder is large, touch the last byte - again,
            // as a fudge factor.
            X86EmitSubEspWorker(imm32-4);
            X86EmitPushReg(kEAX);
        }
    }
}


//---------------------------------------------------------------
// Emits:
//   sub esp, IMM
//---------------------------------------------------------------
VOID StubLinkerCPU::X86EmitSubEspWorker(INT32 imm32)
{
    CONTRACTL
    {
        STANDARD_VM_CHECK;

    // On Win32, stacks must be faulted in one page at a time.
        PRECONDITION(imm32 < 0x1000);
    }
    CONTRACTL_END;

    if (!imm32)
    {
        // nop
    }
    else
    {
        X86_64BitOperands();

        if (FitsInI1(imm32))
        {
            Emit16(0xec83);
            Emit8((INT8)imm32);
        }
        else
        {
            Emit16(0xec81);
            Emit32(imm32);
        }

        Push(imm32);
    }
}


//---------------------------------------------------------------
// Emits:
//   add esp, IMM
//---------------------------------------------------------------
VOID StubLinkerCPU::X86EmitAddEsp(INT32 imm32)
{
    STANDARD_VM_CONTRACT;

    if (!imm32)
    {
        // nop
    }
    else
    {
        X86_64BitOperands();

        if (FitsInI1(imm32))
        {
            Emit16(0xc483);
            Emit8((INT8)imm32);
        }
        else
        {
            Emit16(0xc481);
            Emit32(imm32);
        }
    }
    Pop(imm32);
}

VOID StubLinkerCPU::X86EmitAddReg(X86Reg reg, INT32 imm32)
{
    CONTRACTL
    {
        STANDARD_VM_CHECK;
        PRECONDITION((int) reg < NumX86Regs);
    }
    CONTRACTL_END;

    if (imm32 == 0)
        return;

#ifdef _TARGET_AMD64_
    BYTE rex = REX_PREFIX_BASE | REX_OPERAND_SIZE_64BIT;

    if (reg >= kR8)
    {
        rex |= REX_OPCODE_REG_EXT;
        reg = X86RegFromAMD64Reg(reg);
    }
    Emit8(rex);
#endif

    if (FitsInI1(imm32)) {
        Emit8(0x83);
        Emit8(static_cast<UINT8>(0xC0 | reg));
        Emit8(static_cast<UINT8>(imm32));
    } else {
        Emit8(0x81);
        Emit8(static_cast<UINT8>(0xC0 | reg));
        Emit32(imm32);
    }
}

//---------------------------------------------------------------
// Emits: add destReg, srcReg
//---------------------------------------------------------------

VOID StubLinkerCPU::X86EmitAddRegReg(X86Reg destReg, X86Reg srcReg)
{
    STANDARD_VM_CONTRACT;

    X86EmitR2ROp(0x01, srcReg, destReg);
}




VOID StubLinkerCPU::X86EmitSubReg(X86Reg reg, INT32 imm32)
{
    CONTRACTL
    {
        STANDARD_VM_CHECK;
        PRECONDITION((int) reg < NumX86Regs);
    }
    CONTRACTL_END;

#ifdef _TARGET_AMD64_
    BYTE rex = REX_PREFIX_BASE | REX_OPERAND_SIZE_64BIT;

    if (reg >= kR8)
    {
        rex |= REX_OPCODE_REG_EXT;
        reg = X86RegFromAMD64Reg(reg);
    }
    Emit8(rex);
#endif

    if (FitsInI1(imm32)) {
        Emit8(0x83);
        Emit8(static_cast<UINT8>(0xE8 | reg));
        Emit8(static_cast<UINT8>(imm32));
    } else {
        Emit8(0x81);
        Emit8(static_cast<UINT8>(0xE8 | reg));
        Emit32(imm32);
    }
}

//---------------------------------------------------------------
// Emits: sub destReg, srcReg
//---------------------------------------------------------------

VOID StubLinkerCPU::X86EmitSubRegReg(X86Reg destReg, X86Reg srcReg)
{
    STANDARD_VM_CONTRACT;

    X86EmitR2ROp(0x29, srcReg, destReg);
}

#if defined(_TARGET_AMD64_)

//---------------------------------------------------------------
// movdqa destXmmreg, srcXmmReg
//---------------------------------------------------------------
VOID StubLinkerCPU::X64EmitMovXmmXmm(X86Reg destXmmreg, X86Reg srcXmmReg)
{
    STANDARD_VM_CONTRACT;
    // There are several that could be used to mov xmm registers. MovAps is 
    // what C++ compiler uses so let's use it here too.
    X86EmitR2ROp(X86_INSTR_MOVAPS_R_RM, destXmmreg, srcXmmReg, k32BitOp);
}

//---------------------------------------------------------------
// movdqa XmmN, [baseReg + offset]
//---------------------------------------------------------------
VOID StubLinkerCPU::X64EmitMovdqaFromMem(X86Reg Xmmreg, X86Reg baseReg, __int32 ofs)
{
    STANDARD_VM_CONTRACT;
    X64EmitMovXmmWorker(0x66, 0x6F, Xmmreg, baseReg, ofs);
}

//---------------------------------------------------------------
// movdqa [baseReg + offset], XmmN
//---------------------------------------------------------------
VOID StubLinkerCPU::X64EmitMovdqaToMem(X86Reg Xmmreg, X86Reg baseReg, __int32 ofs)
{
    STANDARD_VM_CONTRACT;
    X64EmitMovXmmWorker(0x66, 0x7F, Xmmreg, baseReg, ofs);
}

//---------------------------------------------------------------
// movsd XmmN, [baseReg + offset]
//---------------------------------------------------------------
VOID StubLinkerCPU::X64EmitMovSDFromMem(X86Reg Xmmreg, X86Reg baseReg, __int32 ofs)
{
    STANDARD_VM_CONTRACT;
    X64EmitMovXmmWorker(0xF2, 0x10, Xmmreg, baseReg, ofs);
}

//---------------------------------------------------------------
// movsd [baseReg + offset], XmmN
//---------------------------------------------------------------
VOID StubLinkerCPU::X64EmitMovSDToMem(X86Reg Xmmreg, X86Reg baseReg, __int32 ofs)
{
    STANDARD_VM_CONTRACT;
    X64EmitMovXmmWorker(0xF2, 0x11, Xmmreg, baseReg, ofs);
}

//---------------------------------------------------------------
// movss XmmN, [baseReg + offset]
//---------------------------------------------------------------
VOID StubLinkerCPU::X64EmitMovSSFromMem(X86Reg Xmmreg, X86Reg baseReg, __int32 ofs)
{
    STANDARD_VM_CONTRACT;
    X64EmitMovXmmWorker(0xF3, 0x10, Xmmreg, baseReg, ofs);
}

//---------------------------------------------------------------
// movss [baseReg + offset], XmmN
//---------------------------------------------------------------
VOID StubLinkerCPU::X64EmitMovSSToMem(X86Reg Xmmreg, X86Reg baseReg, __int32 ofs)
{
    STANDARD_VM_CONTRACT;
    X64EmitMovXmmWorker(0xF3, 0x11, Xmmreg, baseReg, ofs);
}

//---------------------------------------------------------------
// Helper method for emitting of XMM from/to memory moves
//---------------------------------------------------------------
VOID StubLinkerCPU::X64EmitMovXmmWorker(BYTE prefix, BYTE opcode, X86Reg Xmmreg, X86Reg baseReg, __int32 ofs)
{
    STANDARD_VM_CONTRACT;

    BYTE    codeBuffer[10];
    unsigned int     nBytes  = 0;
    
    // Setup the legacyPrefix for movsd
    codeBuffer[nBytes++] = prefix;
    
    // By default, assume we dont have to emit the REX byte.
    bool fEmitRex = false;
    
    BYTE rex = REX_PREFIX_BASE;

    if (baseReg >= kR8)
    {
        rex |= REX_MODRM_RM_EXT;
        baseReg = X86RegFromAMD64Reg(baseReg);
        fEmitRex = true;
    }
    if (Xmmreg >= kXMM8)
    {
        rex |= REX_MODRM_REG_EXT;
        Xmmreg = X86RegFromAMD64Reg(Xmmreg);
        fEmitRex = true;
    }

    if (fEmitRex == true)
    {
        codeBuffer[nBytes++] = rex;
    }
    
    // Next, specify the two byte opcode - first byte is always 0x0F.
    codeBuffer[nBytes++] = 0x0F;    
    codeBuffer[nBytes++] = opcode; 
    
    BYTE modrm = static_cast<BYTE>((Xmmreg << 3) | baseReg);
    bool fOffsetFitsInSignedByte = FitsInI1(ofs)?true:false;
    
    if (fOffsetFitsInSignedByte)
        codeBuffer[nBytes++] = 0x40|modrm;
    else
        codeBuffer[nBytes++] = 0x80|modrm;
    
    // If we are dealing with RSP or R12 as the baseReg, we need to emit the SIB byte.
    if ((baseReg == (X86Reg)4 /*kRSP*/) || (baseReg == kR12))
    {
        codeBuffer[nBytes++] = 0x24;
    }
    
    // Finally, specify the offset
    if (fOffsetFitsInSignedByte)
    {
        codeBuffer[nBytes++] = (BYTE)ofs;
    }
    else
    {
        *((__int32*)(codeBuffer+nBytes)) = ofs;
        nBytes += 4;
    }
    
    _ASSERTE(nBytes <= _countof(codeBuffer));
    
    // Lastly, emit the encoded bytes
    EmitBytes(codeBuffer, nBytes);    
}

#endif // defined(_TARGET_AMD64_)

//---------------------------------------------------------------
// Emits a MOD/RM for accessing a dword at [<indexreg> + ofs32]
//---------------------------------------------------------------
VOID StubLinkerCPU::X86EmitOffsetModRM(BYTE opcode, X86Reg opcodereg, X86Reg indexreg, __int32 ofs)
{
    STANDARD_VM_CONTRACT;

    BYTE    codeBuffer[7];
    BYTE*   code    = codeBuffer;
    int     nBytes  = 0;
#ifdef _TARGET_AMD64_
    code++;
    //
    // code points to base X86 instruction,
    // codeBuffer points to full AMD64 instruction
    //
    BYTE rex = REX_PREFIX_BASE | REX_OPERAND_SIZE_64BIT;

    if (indexreg >= kR8)
    {
        rex |= REX_MODRM_RM_EXT;
        indexreg = X86RegFromAMD64Reg(indexreg);
    }
    if (opcodereg >= kR8)
    {
        rex |= REX_MODRM_REG_EXT;
        opcodereg = X86RegFromAMD64Reg(opcodereg);
    }

    nBytes++;
    code[-1] = rex;
#endif
    code[0] = opcode;
    nBytes++;
    BYTE modrm = static_cast<BYTE>((opcodereg << 3) | indexreg);
    if (ofs == 0 && indexreg != kEBP)
    {
        code[1] = modrm;
        nBytes++;
        EmitBytes(codeBuffer, nBytes);
    }
    else if (FitsInI1(ofs))
    {
        code[1] = 0x40|modrm;
        code[2] = (BYTE)ofs;
        nBytes += 2;
        EmitBytes(codeBuffer, nBytes);
    }
    else
    {
        code[1] = 0x80|modrm;
        *((__int32*)(2+code)) = ofs;
        nBytes += 5;
        EmitBytes(codeBuffer, nBytes);
    }
}

//---------------------------------------------------------------
// Emits a MOD/RM for accessing a dword at [<baseReg> + <indexReg>*<scale> + ofs32]
//---------------------------------------------------------------
VOID StubLinkerCPU::X86EmitOffsetModRmSIB(BYTE opcode, X86Reg opcodeOrReg, X86Reg baseReg, X86Reg indexReg, __int32 scale, __int32 ofs)
{
    CONTRACTL
    {
        STANDARD_VM_CHECK;
        PRECONDITION(scale == 1 || scale == 2 || scale == 4 || scale == 8);
        PRECONDITION(indexReg != kESP_Unsafe);
    }
    CONTRACTL_END;

    BYTE    codeBuffer[8];
    BYTE*   code    = codeBuffer;
    int     nBytes  = 0;

#ifdef _TARGET_AMD64_
    _ASSERTE(!"NYI");
#endif
    code[0] = opcode;
    nBytes++;

    BYTE scaleEnc = 0;
    switch(scale) 
    {
        case 1: scaleEnc = 0; break;
        case 2: scaleEnc = 1; break;
        case 4: scaleEnc = 2; break;
        case 8: scaleEnc = 3; break;
        default: _ASSERTE(!"Unexpected");
    }

    BYTE sib = static_cast<BYTE>((scaleEnc << 6) | (indexReg << 3) | baseReg);

    if (FitsInI1(ofs))
    {
        code[1] = static_cast<BYTE>(0x44 | (opcodeOrReg << 3));
        code[2] = sib;
        code[3] = (BYTE)ofs;
        nBytes += 3;
        EmitBytes(codeBuffer, nBytes);
    }
    else
    {
        code[1] = static_cast<BYTE>(0x84 | (opcodeOrReg << 3));
        code[2] = sib;
        *(__int32*)(&code[3]) = ofs;
        nBytes += 6;
        EmitBytes(codeBuffer, nBytes);
    }
}



VOID StubLinkerCPU::X86EmitRegLoad(X86Reg reg, UINT_PTR imm)
{
    STANDARD_VM_CONTRACT;

    if (!imm)
    {
        X86EmitZeroOutReg(reg);
        return;
    }

    UINT cbimm = sizeof(void*);

#ifdef _TARGET_AMD64_
    // amd64 zero-extends all 32-bit operations.  If the immediate will fit in
    // 32 bits, use the smaller encoding.

    if (reg >= kR8 || !FitsInU4(imm))
    {
        BYTE rex = REX_PREFIX_BASE | REX_OPERAND_SIZE_64BIT;
        if (reg >= kR8)
        {
            rex |= REX_MODRM_RM_EXT;
            reg = X86RegFromAMD64Reg(reg);
        }
        Emit8(rex);
    }
    else
    {
        // amd64 is little endian, so the &imm below will correctly read off
        // the low 4 bytes.
        cbimm = sizeof(UINT32);
    }
#endif // _TARGET_AMD64_
    Emit8(0xB8 | (BYTE)reg);
    EmitBytes((BYTE*)&imm, cbimm);
}


//---------------------------------------------------------------
// Emits the most efficient form of the operation:
//
//    opcode   altreg, [basereg + scaledreg*scale + ofs]
//
// or
//
//    opcode   [basereg + scaledreg*scale + ofs], altreg
//
// (the opcode determines which comes first.)
//
//
// Limitations:
//
//    scale must be 0,1,2,4 or 8.
//    if scale == 0, scaledreg is ignored.
//    basereg and altreg may be equal to 4 (ESP) but scaledreg cannot
//    for some opcodes, "altreg" may actually select an operation
//      rather than a second register argument.
//    if basereg is EBP, scale must be 0.
//
//---------------------------------------------------------------
VOID StubLinkerCPU::X86EmitOp(WORD    opcode,
                              X86Reg  altreg,
                              X86Reg  basereg,
                              __int32 ofs /*=0*/,
                              X86Reg  scaledreg /*=0*/,
                              BYTE    scale /*=0*/
                    AMD64_ARG(X86OperandSize OperandSize /*= k32BitOp*/))
{
    CONTRACTL
    {
        STANDARD_VM_CHECK;

        // All 2-byte opcodes start with 0x0f.
        PRECONDITION(!(opcode >> 8) || (opcode & 0xff) == 0x0f);

        PRECONDITION(scale == 0 || scale == 1 || scale == 2 || scale == 4 || scale == 8);
        PRECONDITION(scaledreg != (X86Reg)4);
        PRECONDITION(!(basereg == kEBP && scale != 0));

        PRECONDITION( ((UINT)basereg)   < NumX86Regs );
        PRECONDITION( ((UINT)scaledreg) < NumX86Regs );
        PRECONDITION( ((UINT)altreg)    < NumX86Regs );
    }
    CONTRACTL_END;

#ifdef _TARGET_AMD64_
    if (   k64BitOp == OperandSize
        || altreg    >= kR8
        || basereg   >= kR8
        || scaledreg >= kR8)
    {
        BYTE rex = REX_PREFIX_BASE;

        if (k64BitOp == OperandSize)
            rex |= REX_OPERAND_SIZE_64BIT;

        if (altreg >= kR8)
        {
            rex |= REX_MODRM_REG_EXT;
            altreg = X86RegFromAMD64Reg(altreg);
        }

        if (basereg >= kR8)
        {
            // basereg might be in the modrm or sib fields.  This will be
            // decided below, but the encodings are the same either way.
            _ASSERTE(REX_SIB_BASE_EXT == REX_MODRM_RM_EXT);
            rex |= REX_SIB_BASE_EXT;
            basereg = X86RegFromAMD64Reg(basereg);
        }

        if (scaledreg >= kR8)
        {
            rex |= REX_SIB_INDEX_EXT;
            scaledreg = X86RegFromAMD64Reg(scaledreg);
        }

        Emit8(rex);
    }
#endif // _TARGET_AMD64_

    BYTE modrmbyte = static_cast<BYTE>(altreg << 3);
    BOOL fNeedSIB  = FALSE;
    BYTE SIBbyte = 0;
    BYTE ofssize;
    BYTE scaleselect= 0;

    if (ofs == 0 && basereg != kEBP)
    {
        ofssize = 0; // Don't change this constant!
    }
    else if (FitsInI1(ofs))
    {
        ofssize = 1; // Don't change this constant!
    }
    else
    {
        ofssize = 2; // Don't change this constant!
    }

    switch (scale)
    {
        case 1: scaleselect = 0; break;
        case 2: scaleselect = 1; break;
        case 4: scaleselect = 2; break;
        case 8: scaleselect = 3; break;
    }

    if (scale == 0 && basereg != (X86Reg)4 /*ESP*/)
    {
        // [basereg + ofs]
        modrmbyte |= basereg | (ofssize << 6);
    }
    else if (scale == 0)
    {
        // [esp + ofs]
        _ASSERTE(basereg == (X86Reg)4);
        fNeedSIB = TRUE;
        SIBbyte  = 0044;

        modrmbyte |= 4 | (ofssize << 6);
    }
    else
    {

        //[basereg + scaledreg*scale + ofs]

        modrmbyte |= 0004 | (ofssize << 6);
        fNeedSIB = TRUE;
        SIBbyte = static_cast<BYTE>((scaleselect << 6) | (scaledreg << 3) | basereg);

    }

    //Some sanity checks:
    _ASSERTE(!(fNeedSIB && basereg == kEBP)); // EBP not valid as a SIB base register.
    _ASSERTE(!( (!fNeedSIB) && basereg == (X86Reg)4 )) ; // ESP addressing requires SIB byte

    Emit8((BYTE)opcode);

    if (opcode >> 8)
        Emit8(opcode >> 8);

    Emit8(modrmbyte);
    if (fNeedSIB)
    {
        Emit8(SIBbyte);
    }
    switch (ofssize)
    {
        case 0: break;
        case 1: Emit8( (__int8)ofs ); break;
        case 2: Emit32( ofs ); break;
        default: _ASSERTE(!"Can't get here.");
    }
}


// Emits
//
//    opcode altreg, modrmreg
//
// or
//
//    opcode modrmreg, altreg
//  
// (the opcode determines which one comes first)
//
// For single-operand opcodes, "altreg" actually selects
// an operation rather than a register.

VOID StubLinkerCPU::X86EmitR2ROp (WORD opcode,
                                  X86Reg altreg,
                                  X86Reg modrmreg
                        AMD64_ARG(X86OperandSize OperandSize /*= k64BitOp*/)
                                  )
{
    CONTRACTL
    {
        STANDARD_VM_CHECK;

        // All 2-byte opcodes start with 0x0f.
        PRECONDITION(!(opcode >> 8) || (opcode & 0xff) == 0x0f);

        PRECONDITION( ((UINT)altreg) < NumX86Regs );
        PRECONDITION( ((UINT)modrmreg) < NumX86Regs );
    }
    CONTRACTL_END;

#ifdef _TARGET_AMD64_
    BYTE rex = 0;

    if (modrmreg >= kR8)
    {
        rex |= REX_MODRM_RM_EXT;
        modrmreg = X86RegFromAMD64Reg(modrmreg);
    }

    if (altreg >= kR8)
    {
        rex |= REX_MODRM_REG_EXT;
        altreg = X86RegFromAMD64Reg(altreg);
    }

    if (k64BitOp == OperandSize)
        rex |= REX_OPERAND_SIZE_64BIT;

    if (rex)
        Emit8(REX_PREFIX_BASE | rex);
#endif // _TARGET_AMD64_

    Emit8((BYTE)opcode);

    if (opcode >> 8)
        Emit8(opcode >> 8);

    Emit8(static_cast<UINT8>(0300 | (altreg << 3) | modrmreg));
}


//---------------------------------------------------------------
// Emits:
//   op altreg, [esp+ofs]
//---------------------------------------------------------------
VOID StubLinkerCPU::X86EmitEspOffset(BYTE opcode,
                                     X86Reg altreg,
                                     __int32 ofs
                           AMD64_ARG(X86OperandSize OperandSize /*= k64BitOp*/)
                                     )
{
    STANDARD_VM_CONTRACT;

    BYTE    codeBuffer[8];
    BYTE   *code = codeBuffer;
    int     nBytes;

#ifdef _TARGET_AMD64_
    BYTE rex = 0;

    if (k64BitOp == OperandSize)
        rex |= REX_OPERAND_SIZE_64BIT;

    if (altreg >= kR8)
    {
        rex |= REX_MODRM_REG_EXT;
        altreg = X86RegFromAMD64Reg(altreg);
    }

    if (rex)
    {
        *code = (REX_PREFIX_BASE | rex);
        code++;
        nBytes = 1;
    }
    else
#endif // _TARGET_AMD64_
    {
        nBytes = 0;
    }

    code[0] = opcode;
    BYTE modrm = static_cast<BYTE>((altreg << 3) | 004);
    if (ofs == 0)
    {
        code[1] = modrm;
        code[2] = 0044;
        EmitBytes(codeBuffer, 3 + nBytes);
    }
    else if (FitsInI1(ofs))
    {
        code[1] = 0x40|modrm;
        code[2] = 0044;
        code[3] = (BYTE)ofs;
        EmitBytes(codeBuffer, 4 + nBytes);
    }
    else
    {
        code[1] = 0x80|modrm;
        code[2] = 0044;
        *((__int32*)(3+code)) = ofs;
        EmitBytes(codeBuffer, 7 + nBytes);
    }

}

//---------------------------------------------------------------

VOID StubLinkerCPU::X86EmitPushEBPframe()
{
    STANDARD_VM_CONTRACT;
    
    //  push ebp
    X86EmitPushReg(kEBP);
    // mov ebp,esp
    X86EmitMovRegSP(kEBP);
}

#ifdef _DEBUG
//---------------------------------------------------------------
// Emits:
//     mov <reg32>,0xcccccccc
//---------------------------------------------------------------
VOID StubLinkerCPU::X86EmitDebugTrashReg(X86Reg reg)
{
    STANDARD_VM_CONTRACT;

#ifdef _TARGET_AMD64_
    BYTE rex = REX_PREFIX_BASE | REX_OPERAND_SIZE_64BIT;

    if (reg >= kR8)
    {
        rex |= REX_OPCODE_REG_EXT;
        reg = X86RegFromAMD64Reg(reg);
    }
    Emit8(rex);
    Emit8(0xb8|reg);
    Emit64(0xcccccccccccccccc);
#else
    Emit8(static_cast<UINT8>(0xb8 | reg));
    Emit32(0xcccccccc);
#endif
}
#endif //_DEBUG


// Get X86Reg indexes of argument registers based on offset into ArgumentRegister
X86Reg GetX86ArgumentRegisterFromOffset(size_t ofs)
{
    CONTRACT(X86Reg)
    {
        NOTHROW;
        GC_NOTRIGGER;

    }
    CONTRACT_END;

    #define ARGUMENT_REGISTER(reg) if (ofs == offsetof(ArgumentRegisters, reg)) RETURN  k##reg ;
    ENUM_ARGUMENT_REGISTERS();
    #undef ARGUMENT_REGISTER

    _ASSERTE(0);//Can't get here.
    RETURN kEBP;
}


#ifdef _TARGET_AMD64_
static const X86Reg c_argRegs[] = { 
    #define ARGUMENT_REGISTER(regname) k##regname,
    ENUM_ARGUMENT_REGISTERS()
    #undef ARGUMENT_REGISTER
};
#endif


#ifndef CROSSGEN_COMPILE

#if defined(_DEBUG) && !defined(FEATURE_PAL)
void StubLinkerCPU::EmitJITHelperLoggingThunk(PCODE pJitHelper, LPVOID helperFuncCount)
{
    STANDARD_VM_CONTRACT;

    VMHELPCOUNTDEF* pHelperFuncCount = (VMHELPCOUNTDEF*)helperFuncCount;
/*
        push        rcx
        mov         rcx, &(pHelperFuncCount->count)
   lock inc        [rcx]
        pop         rcx
#ifdef _TARGET_AMD64_
        mov         rax, <pJitHelper>
        jmp         rax
#else
        jmp         <pJitHelper>
#endif
*/

    // push     rcx
    // mov      rcx, &(pHelperFuncCount->count)
    X86EmitPushReg(kECX);
    X86EmitRegLoad(kECX, (UINT_PTR)(&(pHelperFuncCount->count)));

    // lock inc [rcx]
    BYTE lock_inc_RCX[] = { 0xf0, 0xff, 0x01 };
    EmitBytes(lock_inc_RCX, sizeof(lock_inc_RCX));

#if defined(_TARGET_AMD64_)
    // mov      rax, <pJitHelper>
    // pop      rcx
    // jmp      rax
#else
    // pop      rcx
    // jmp      <pJitHelper>
#endif
    X86EmitTailcallWithSinglePop(NewExternalCodeLabel(pJitHelper), kECX);
}
#endif // _DEBUG && !FEATURE_PAL

VOID StubLinkerCPU::X86EmitCurrentThreadFetch(X86Reg dstreg, unsigned preservedRegSet)
{
    CONTRACTL
    {
        STANDARD_VM_CHECK;

        // It doesn't make sense to have the destination register be preserved
        PRECONDITION((preservedRegSet & (1 << dstreg)) == 0);
        AMD64_ONLY(PRECONDITION(dstreg < 8)); // code below doesn't support high registers
    }
    CONTRACTL_END;

#ifdef FEATURE_PAL

    X86EmitPushRegs(preservedRegSet & ((1 << kEAX) | (1 << kEDX) | (1 << kECX)));

    // call GetThread
    X86EmitCall(NewExternalCodeLabel((LPVOID)GetThread), sizeof(void*));

    // mov dstreg, eax
    X86EmitMovRegReg(dstreg, kEAX);

    X86EmitPopRegs(preservedRegSet & ((1 << kEAX) | (1 << kEDX) | (1 << kECX)));

#ifdef _DEBUG
    // Trash caller saved regs that we were not told to preserve, and that aren't the dstreg.
    preservedRegSet |= 1 << dstreg;
    if (!(preservedRegSet & (1 << kEAX)))
        X86EmitDebugTrashReg(kEAX);
    if (!(preservedRegSet & (1 << kEDX)))
        X86EmitDebugTrashReg(kEDX);
    if (!(preservedRegSet & (1 << kECX)))
        X86EmitDebugTrashReg(kECX);
#endif // _DEBUG

#else // FEATURE_PAL

#ifdef _TARGET_AMD64_
    BYTE code[] = { 0x65,0x48,0x8b,0x04,0x25 };    // mov dstreg, qword ptr gs:[IMM32]
    static const int regByteIndex = 3;
#elif defined(_TARGET_X86_)
    BYTE code[] = { 0x64,0x8b,0x05 };              // mov dstreg, dword ptr fs:[IMM32]
    static const int regByteIndex = 2;
#endif
    code[regByteIndex] |= (dstreg << 3);

    EmitBytes(code, sizeof(code));
    Emit32(offsetof(TEB, ThreadLocalStoragePointer));

    X86EmitIndexRegLoad(dstreg, dstreg, sizeof(void *) * (g_TlsIndex & 0xFFFF));

    X86EmitIndexRegLoad(dstreg, dstreg, (g_TlsIndex & 0x7FFF0000) >> 16);

#endif // FEATURE_PAL
}

#if defined(_TARGET_X86_)

#if defined(PROFILING_SUPPORTED) && !defined(FEATURE_STUBS_AS_IL)
VOID StubLinkerCPU::EmitProfilerComCallProlog(TADDR pFrameVptr, X86Reg regFrame)
{
    STANDARD_VM_CONTRACT;

    if (pFrameVptr == UMThkCallFrame::GetMethodFrameVPtr())
    {
        // Load the methoddesc into ECX (UMThkCallFrame->m_pvDatum->m_pMD)
        X86EmitIndexRegLoad(kECX, regFrame, UMThkCallFrame::GetOffsetOfDatum());
        X86EmitIndexRegLoad(kECX, kECX, UMEntryThunk::GetOffsetOfMethodDesc());

        // Push arguments and notify profiler
        X86EmitPushImm32(COR_PRF_TRANSITION_CALL);      // Reason
        X86EmitPushReg(kECX);                           // MethodDesc*
        X86EmitCall(NewExternalCodeLabel((LPVOID) ProfilerUnmanagedToManagedTransitionMD), 2*sizeof(void*));
    }

#ifdef FEATURE_COMINTEROP
    else if (pFrameVptr == ComMethodFrame::GetMethodFrameVPtr())
    {
        // Load the methoddesc into ECX (Frame->m_pvDatum->m_pMD)
        X86EmitIndexRegLoad(kECX, regFrame, ComMethodFrame::GetOffsetOfDatum());
        X86EmitIndexRegLoad(kECX, kECX, ComCallMethodDesc::GetOffsetOfMethodDesc());

        // Push arguments and notify profiler
        X86EmitPushImm32(COR_PRF_TRANSITION_CALL);      // Reason
        X86EmitPushReg(kECX);                           // MethodDesc*
        X86EmitCall(NewExternalCodeLabel((LPVOID) ProfilerUnmanagedToManagedTransitionMD), 2*sizeof(void*));
    }
#endif // FEATURE_COMINTEROP

    // Unrecognized frame vtbl
    else
    {
        _ASSERTE(!"Unrecognized vtble passed to EmitComMethodStubProlog with profiling turned on.");
    }
}


VOID StubLinkerCPU::EmitProfilerComCallEpilog(TADDR pFrameVptr, X86Reg regFrame)
{
    CONTRACTL
    {
        STANDARD_VM_CHECK;
#ifdef FEATURE_COMINTEROP
        PRECONDITION(pFrameVptr == UMThkCallFrame::GetMethodFrameVPtr() || pFrameVptr == ComMethodFrame::GetMethodFrameVPtr());
#else 
        PRECONDITION(pFrameVptr == UMThkCallFrame::GetMethodFrameVPtr());
#endif // FEATURE_COMINTEROP
    }
    CONTRACTL_END;

    if (pFrameVptr == UMThkCallFrame::GetMethodFrameVPtr())
    {
        // Load the methoddesc into ECX (UMThkCallFrame->m_pvDatum->m_pMD)
        X86EmitIndexRegLoad(kECX, regFrame, UMThkCallFrame::GetOffsetOfDatum());
        X86EmitIndexRegLoad(kECX, kECX, UMEntryThunk::GetOffsetOfMethodDesc());

        // Push arguments and notify profiler
        X86EmitPushImm32(COR_PRF_TRANSITION_RETURN);    // Reason
        X86EmitPushReg(kECX);                           // MethodDesc*
        X86EmitCall(NewExternalCodeLabel((LPVOID) ProfilerManagedToUnmanagedTransitionMD), 2*sizeof(void*));
    }

#ifdef FEATURE_COMINTEROP
    else if (pFrameVptr == ComMethodFrame::GetMethodFrameVPtr())
    {
        // Load the methoddesc into ECX (Frame->m_pvDatum->m_pMD)
        X86EmitIndexRegLoad(kECX, regFrame, ComMethodFrame::GetOffsetOfDatum());
        X86EmitIndexRegLoad(kECX, kECX, ComCallMethodDesc::GetOffsetOfMethodDesc());

        // Push arguments and notify profiler
        X86EmitPushImm32(COR_PRF_TRANSITION_RETURN);    // Reason
        X86EmitPushReg(kECX);                           // MethodDesc*
        X86EmitCall(NewExternalCodeLabel((LPVOID) ProfilerManagedToUnmanagedTransitionMD), 2*sizeof(void*));
    }
#endif // FEATURE_COMINTEROP

    // Unrecognized frame vtbl
    else
    {
        _ASSERTE(!"Unrecognized vtble passed to EmitComMethodStubEpilog with profiling turned on.");
    }
}
#endif // PROFILING_SUPPORTED && !FEATURE_STUBS_AS_IL


#ifndef FEATURE_STUBS_AS_IL
//========================================================================
//  Prolog for entering managed code from COM
//  pushes the appropriate frame ptr
//  sets up a thread and returns a label that needs to be emitted by the caller
//  At the end:
//  ESI will hold the pointer to the ComMethodFrame or UMThkCallFrame
//  EBX will hold the result of GetThread()
//  EDI will hold the previous Frame ptr

void StubLinkerCPU::EmitComMethodStubProlog(TADDR pFrameVptr,
                                            CodeLabel** rgRareLabels,
                                            CodeLabel** rgRejoinLabels,
                                            BOOL bShouldProfile)
{
    CONTRACTL
    {
        STANDARD_VM_CHECK;

        PRECONDITION(rgRareLabels != NULL);
        PRECONDITION(rgRareLabels[0] != NULL && rgRareLabels[1] != NULL && rgRareLabels[2] != NULL);
        PRECONDITION(rgRejoinLabels != NULL);
        PRECONDITION(rgRejoinLabels[0] != NULL && rgRejoinLabels[1] != NULL && rgRejoinLabels[2] != NULL);
    }
    CONTRACTL_END;

    // push ebp     ;; save callee-saved register
    // push ebx     ;; save callee-saved register
    // push esi     ;; save callee-saved register
    // push edi     ;; save callee-saved register
    X86EmitPushEBPframe();

    X86EmitPushReg(kEBX);
    X86EmitPushReg(kESI);
    X86EmitPushReg(kEDI);

    // push eax ; datum
    X86EmitPushReg(kEAX);

    // push edx ;leave room for m_next (edx is an arbitrary choice)
    X86EmitPushReg(kEDX);

    // push IMM32 ; push Frame vptr
    X86EmitPushImmPtr((LPVOID) pFrameVptr);

    X86EmitPushImmPtr((LPVOID)GetProcessGSCookie());

    // lea esi, [esp+4] ;; set ESI -> new frame
    X86EmitEspOffset(0x8d, kESI, 4);    // lea ESI, [ESP+4]

    if (pFrameVptr == UMThkCallFrame::GetMethodFrameVPtr())
    {
        // Preserve argument registers for thiscall/fastcall
        X86EmitPushReg(kECX);
        X86EmitPushReg(kEDX);
    }

    // Emit Setup thread
    EmitSetup(rgRareLabels[0]);  // rareLabel for rare setup
    EmitLabel(rgRejoinLabels[0]); // rejoin label for rare setup

#ifdef PROFILING_SUPPORTED
    // If profiling is active, emit code to notify profiler of transition
    // Must do this before preemptive GC is disabled, so no problem if the
    // profiler blocks.
    if (CORProfilerTrackTransitions() && bShouldProfile)
    {
        EmitProfilerComCallProlog(pFrameVptr, /*Frame*/ kESI);
    }
#endif // PROFILING_SUPPORTED

    //-----------------------------------------------------------------------
    // Generate the inline part of disabling preemptive GC.  It is critical
    // that this part happen before we link in the frame.  That's because
    // we won't be able to unlink the frame from preemptive mode.  And during
    // shutdown, we cannot switch to cooperative mode under some circumstances
    //-----------------------------------------------------------------------
    EmitDisable(rgRareLabels[1], /*fCallIn=*/TRUE, kEBX); // rare disable gc
    EmitLabel(rgRejoinLabels[1]);                         // rejoin for rare disable gc

    // If we take an SO after installing the new frame but before getting the exception
    // handlers in place, we will have a corrupt frame stack.  So probe-by-touch first for 
    // sufficient stack space to erect the handler.  Because we know we will be touching
    // that stack right away when install the handler, this probe-by-touch will not incur
    // unnecessary cache misses.   And this allows us to do the probe with one instruction.
    
    // Note that for Win64, the personality routine will handle unlinking the frame, so
    // we don't need to probe in the Win64 stubs.  The exception is ComToCLRWorker
    // where we don't setup a personality routine.  However, we push the frame inside
    // that function and it is probe-protected with an entry point probe first, so we are
    // OK there too.
 
    // We push two registers to setup the EH handler and none to setup the frame
    // so probe for double that to give ourselves a small margin for error.
    // mov eax, [esp+n] ;; probe for sufficient stack to setup EH
    X86EmitEspOffset(0x8B, kEAX, -0x20);   
     // mov edi,[ebx + Thread.GetFrame()]  ;; get previous frame
    X86EmitIndexRegLoad(kEDI, kEBX, Thread::GetOffsetOfCurrentFrame());

    // mov [esi + Frame.m_next], edi
    X86EmitIndexRegStore(kESI, Frame::GetOffsetOfNextLink(), kEDI);

    // mov [ebx + Thread.GetFrame()], esi
    X86EmitIndexRegStore(kEBX, Thread::GetOffsetOfCurrentFrame(), kESI);

    if (pFrameVptr == UMThkCallFrame::GetMethodFrameVPtr())
    {
        // push UnmanagedToManagedExceptHandler
        X86EmitPushImmPtr((LPVOID)UMThunkPrestubHandler);

        // mov eax, fs:[0]
        static const BYTE codeSEH1[] = { 0x64, 0xA1, 0x0, 0x0, 0x0, 0x0};
        EmitBytes(codeSEH1, sizeof(codeSEH1));

        // push eax
        X86EmitPushReg(kEAX);

        // mov dword ptr fs:[0], esp
        static const BYTE codeSEH2[] = { 0x64, 0x89, 0x25, 0x0, 0x0, 0x0, 0x0};
        EmitBytes(codeSEH2, sizeof(codeSEH2));
    }

#if _DEBUG
    if (Frame::ShouldLogTransitions())
    {
        // call LogTransition
        X86EmitPushReg(kESI);
        X86EmitCall(NewExternalCodeLabel((LPVOID) Frame::LogTransition), sizeof(void*));
    }
#endif
}

//========================================================================
//  Epilog for stubs that enter managed code from COM
//
//  At this point of the stub, the state should be as follows:
//  ESI holds the ComMethodFrame or UMThkCallFrame ptr
//  EBX holds the result of GetThread()
//  EDI holds the previous Frame ptr
//
void StubLinkerCPU::EmitComMethodStubEpilog(TADDR pFrameVptr,
                                            CodeLabel** rgRareLabels,
                                            CodeLabel** rgRejoinLabels,
                                            BOOL bShouldProfile)
{
    CONTRACTL
    {
        STANDARD_VM_CHECK;

        PRECONDITION(rgRareLabels != NULL);
        PRECONDITION(rgRareLabels[0] != NULL && rgRareLabels[1] != NULL && rgRareLabels[2] != NULL);
        PRECONDITION(rgRejoinLabels != NULL);
        PRECONDITION(rgRejoinLabels[0] != NULL && rgRejoinLabels[1] != NULL && rgRejoinLabels[2] != NULL);
    }
    CONTRACTL_END;

    EmitCheckGSCookie(kESI, UnmanagedToManagedFrame::GetOffsetOfGSCookie());

    if (pFrameVptr == UMThkCallFrame::GetMethodFrameVPtr())
    {
        // if we are using exceptions, unlink the SEH
        // mov ecx,[esp]  ;;pointer to the next exception record
        X86EmitEspOffset(0x8b, kECX, 0);

        // mov dword ptr fs:[0], ecx
        static const BYTE codeSEH[] = { 0x64, 0x89, 0x0D, 0x0, 0x0, 0x0, 0x0 };
        EmitBytes(codeSEH, sizeof(codeSEH));

        X86EmitAddEsp(sizeof(EXCEPTION_REGISTRATION_RECORD));
    }

    // mov [ebx + Thread.GetFrame()], edi  ;; restore previous frame
    X86EmitIndexRegStore(kEBX, Thread::GetOffsetOfCurrentFrame(), kEDI);

    //-----------------------------------------------------------------------
    // Generate the inline part of disabling preemptive GC
    //-----------------------------------------------------------------------
    EmitEnable(rgRareLabels[2]); // rare gc
    EmitLabel(rgRejoinLabels[2]);        // rejoin for rare gc

    if (pFrameVptr == UMThkCallFrame::GetMethodFrameVPtr())
    {
        // Restore argument registers for thiscall/fastcall
        X86EmitPopReg(kEDX);
        X86EmitPopReg(kECX);
    }

    // add esp, popstack
    X86EmitAddEsp(sizeof(GSCookie) + UnmanagedToManagedFrame::GetOffsetOfCalleeSavedRegisters());

    // pop edi        ; restore callee-saved registers
    // pop esi
    // pop ebx
    // pop ebp
    X86EmitPopReg(kEDI);
    X86EmitPopReg(kESI);
    X86EmitPopReg(kEBX);
    X86EmitPopReg(kEBP);

    //    jmp eax //reexecute!
    X86EmitR2ROp(0xff, (X86Reg)4, kEAX);

    // ret
    // This will never be executed. It is just to help out stack-walking logic 
    // which disassembles the epilog to unwind the stack. A "ret" instruction 
    // indicates that no more code needs to be disassembled, if the stack-walker
    // keeps on going past the previous "jmp eax".
    X86EmitReturn(0);

    //-----------------------------------------------------------------------
    // The out-of-line portion of enabling preemptive GC - rarely executed
    //-----------------------------------------------------------------------
    EmitLabel(rgRareLabels[2]);  // label for rare enable gc
    EmitRareEnable(rgRejoinLabels[2]); // emit rare enable gc

    //-----------------------------------------------------------------------
    // The out-of-line portion of disabling preemptive GC - rarely executed
    //-----------------------------------------------------------------------
    EmitLabel(rgRareLabels[1]);  // label for rare disable gc
    EmitRareDisable(rgRejoinLabels[1]); // emit rare disable gc

    //-----------------------------------------------------------------------
    // The out-of-line portion of setup thread - rarely executed
    //-----------------------------------------------------------------------
    EmitLabel(rgRareLabels[0]);  // label for rare setup thread
    EmitRareSetup(rgRejoinLabels[0], /*fThrow*/ TRUE); // emit rare setup thread
}
#endif // !FEATURE_STUBS_AS_IL

//---------------------------------------------------------------
// Emit code to store the setup current Thread structure in eax.
// TRASHES  eax,ecx&edx.
// RESULTS  ebx = current Thread
//---------------------------------------------------------------
VOID StubLinkerCPU::EmitSetup(CodeLabel *pForwardRef)
{
    STANDARD_VM_CONTRACT;

    X86EmitCurrentThreadFetch(kEBX, 0);

    // cmp ebx, 0
    static const BYTE b[] = { 0x83, 0xFB, 0x0};

    EmitBytes(b, sizeof(b));

    // jz RarePath
    X86EmitCondJump(pForwardRef, X86CondCode::kJZ);

#ifdef _DEBUG
    X86EmitDebugTrashReg(kECX);
    X86EmitDebugTrashReg(kEDX);
#endif
}

VOID StubLinkerCPU::EmitRareSetup(CodeLabel *pRejoinPoint, BOOL fThrow)
{
    STANDARD_VM_CONTRACT;

#ifndef FEATURE_COMINTEROP
    _ASSERTE(fThrow);
#else // !FEATURE_COMINTEROP
    if (!fThrow)
    {
        X86EmitPushReg(kESI);
        X86EmitCall(NewExternalCodeLabel((LPVOID) CreateThreadBlockReturnHr), sizeof(void*));
    }
    else
#endif // !FEATURE_COMINTEROP
    {
        X86EmitCall(NewExternalCodeLabel((LPVOID) CreateThreadBlockThrow), 0);
    }

    // mov ebx,eax
    Emit16(0xc389);
    X86EmitNearJump(pRejoinPoint);
}

//========================================================================
#endif // _TARGET_X86_
//========================================================================
#if defined(FEATURE_COMINTEROP) && defined(_TARGET_X86_)
//========================================================================
//  Epilog for stubs that enter managed code from COM
//
//  On entry, ESI points to the Frame
//  ESP points to below FramedMethodFrame::m_vc5Frame
//  EBX hold GetThread()
//  EDI holds the previous Frame

void StubLinkerCPU::EmitSharedComMethodStubEpilog(TADDR pFrameVptr,
                                                  CodeLabel** rgRareLabels,
                                                  CodeLabel** rgRejoinLabels,
                                                  unsigned offsetRetThunk,
                                                  BOOL bShouldProfile)
{
    CONTRACTL
    {
        STANDARD_VM_CHECK;

        PRECONDITION(rgRareLabels != NULL);
        PRECONDITION(rgRareLabels[0] != NULL && rgRareLabels[1] != NULL && rgRareLabels[2] != NULL);
        PRECONDITION(rgRejoinLabels != NULL);
        PRECONDITION(rgRejoinLabels[0] != NULL && rgRejoinLabels[1] != NULL && rgRejoinLabels[2] != NULL);
    }
    CONTRACTL_END;

    CodeLabel *NoEntryLabel;
    NoEntryLabel = NewCodeLabel();

    EmitCheckGSCookie(kESI, UnmanagedToManagedFrame::GetOffsetOfGSCookie());

    // mov [ebx + Thread.GetFrame()], edi  ;; restore previous frame
    X86EmitIndexRegStore(kEBX, Thread::GetOffsetOfCurrentFrame(), kEDI);

    //-----------------------------------------------------------------------
    // Generate the inline part of enabling preemptive GC
    //-----------------------------------------------------------------------
    EmitLabel(NoEntryLabel);    // need to enable preemp mode even when we fail the disable as rare disable will return in coop mode
    
    EmitEnable(rgRareLabels[2]);     // rare enable gc
    EmitLabel(rgRejoinLabels[2]);        // rejoin for rare enable gc

#ifdef PROFILING_SUPPORTED
    // If profiling is active, emit code to notify profiler of transition
    if (CORProfilerTrackTransitions() && bShouldProfile)
    {
        // Save return value
        X86EmitPushReg(kEAX);
        X86EmitPushReg(kEDX);

        EmitProfilerComCallEpilog(pFrameVptr, kESI);

        // Restore return value
        X86EmitPopReg(kEDX);
        X86EmitPopReg(kEAX);
    }
#endif // PROFILING_SUPPORTED

    X86EmitAddEsp(sizeof(GSCookie) + UnmanagedToManagedFrame::GetOffsetOfDatum());

    // pop ecx
    X86EmitPopReg(kECX); // pop the MethodDesc*

    // pop edi        ; restore callee-saved registers
    // pop esi
    // pop ebx
    // pop ebp
    X86EmitPopReg(kEDI);
    X86EmitPopReg(kESI);
    X86EmitPopReg(kEBX);
    X86EmitPopReg(kEBP);

    // add ecx, offsetRetThunk
    X86EmitAddReg(kECX, offsetRetThunk);

    // jmp ecx
    // This will jump to the "ret cbStackArgs" instruction in COMMETHOD_PREPAD.
    static const BYTE bjmpecx[] = { 0xff, 0xe1 };
    EmitBytes(bjmpecx, sizeof(bjmpecx));

    // ret
    // This will never be executed. It is just to help out stack-walking logic 
    // which disassembles the epilog to unwind the stack. A "ret" instruction 
    // indicates that no more code needs to be disassembled, if the stack-walker
    // keeps on going past the previous "jmp ecx".
    X86EmitReturn(0);

    //-----------------------------------------------------------------------
    // The out-of-line portion of enabling preemptive GC - rarely executed
    //-----------------------------------------------------------------------
    EmitLabel(rgRareLabels[2]);  // label for rare enable gc
    EmitRareEnable(rgRejoinLabels[2]); // emit rare enable gc

    //-----------------------------------------------------------------------
    // The out-of-line portion of disabling preemptive GC - rarely executed
    //-----------------------------------------------------------------------
    EmitLabel(rgRareLabels[1]);  // label for rare disable gc
    EmitRareDisableHRESULT(rgRejoinLabels[1], NoEntryLabel);

    //-----------------------------------------------------------------------
    // The out-of-line portion of setup thread - rarely executed
    //-----------------------------------------------------------------------
    EmitLabel(rgRareLabels[0]);  // label for rare setup thread
    EmitRareSetup(rgRejoinLabels[0],/*fThrow*/ FALSE); // emit rare setup thread
}

//========================================================================
#endif // defined(FEATURE_COMINTEROP) && defined(_TARGET_X86_)

#ifndef FEATURE_STUBS_AS_IL
/*==============================================================================
    Pushes a TransitionFrame on the stack
    If you make any changes to the prolog instruction sequence, be sure
    to update UpdateRegdisplay, too!!  This service should only be called from
    within the runtime.  It should not be called for any unmanaged -> managed calls in.

    At the end of the generated prolog stub code:
    pFrame is in ESI/RSI.
    the previous pFrame is in EDI/RDI
    The current Thread* is in EBX/RBX.
    For x86, ESP points to TransitionFrame
    For amd64, ESP points to the space reserved for the outgoing argument registers
*/

VOID StubLinkerCPU::EmitMethodStubProlog(TADDR pFrameVptr, int transitionBlockOffset)
{
    STANDARD_VM_CONTRACT;

#ifdef _TARGET_AMD64_
    X86EmitPushReg(kR15);   // CalleeSavedRegisters
    X86EmitPushReg(kR14);
    X86EmitPushReg(kR13);
    X86EmitPushReg(kR12);
    X86EmitPushReg(kRBP);
    X86EmitPushReg(kRBX);
    X86EmitPushReg(kRSI);
    X86EmitPushReg(kRDI);

    // Push m_datum
    X86EmitPushReg(SCRATCH_REGISTER_X86REG);

    // push edx ;leave room for m_next (edx is an arbitrary choice)
    X86EmitPushReg(kEDX);

    // push Frame vptr
    X86EmitPushImmPtr((LPVOID) pFrameVptr);

    // mov rsi, rsp
    X86EmitR2ROp(0x8b, kRSI, (X86Reg)4 /*kESP*/);
    UnwindSetFramePointer(kRSI);

    // Save ArgumentRegisters
    #define ARGUMENT_REGISTER(regname) X86EmitRegSave(k##regname, SecureDelegateFrame::GetOffsetOfTransitionBlock() + \
        sizeof(TransitionBlock) + offsetof(ArgumentRegisters, regname));
    ENUM_ARGUMENT_REGISTERS();
    #undef ARGUMENT_REGISTER

    _ASSERTE(((Frame*)&pFrameVptr)->GetGSCookiePtr() == PTR_GSCookie(PBYTE(&pFrameVptr) - sizeof(GSCookie)));
    X86EmitPushImmPtr((LPVOID)GetProcessGSCookie());

    // sub rsp, 4*sizeof(void*)           ;; allocate callee scratch area and ensure rsp is 16-byte-aligned
    const INT32 padding = sizeof(ArgumentRegisters) + ((sizeof(FramedMethodFrame) % (2 * sizeof(LPVOID))) ? 0 : sizeof(LPVOID));
    X86EmitSubEsp(padding);
#endif // _TARGET_AMD64_

#ifdef _TARGET_X86_
    // push ebp     ;; save callee-saved register
    // mov ebp,esp
    // push ebx     ;; save callee-saved register
    // push esi     ;; save callee-saved register
    // push edi     ;; save callee-saved register
    X86EmitPushEBPframe();

    X86EmitPushReg(kEBX);
    X86EmitPushReg(kESI);
    X86EmitPushReg(kEDI);

    // Push & initialize ArgumentRegisters
    #define ARGUMENT_REGISTER(regname) X86EmitPushReg(k##regname);
    ENUM_ARGUMENT_REGISTERS();
    #undef ARGUMENT_REGISTER

    // Push m_datum
    X86EmitPushReg(kEAX);

    // push edx ;leave room for m_next (edx is an arbitrary choice)
    X86EmitPushReg(kEDX);

    // push Frame vptr
    X86EmitPushImmPtr((LPVOID) pFrameVptr);

    // mov esi,esp
    X86EmitMovRegSP(kESI);

    X86EmitPushImmPtr((LPVOID)GetProcessGSCookie());
#endif // _TARGET_X86_

    // ebx <-- GetThread()
    X86EmitCurrentThreadFetch(kEBX, 0);

#if _DEBUG

    // call ObjectRefFlush
#ifdef _TARGET_AMD64_

    // mov rcx, rbx
    X86EmitR2ROp(0x8b, kECX, kEBX);         // arg in reg

#else // !_TARGET_AMD64_
    X86EmitPushReg(kEBX);                   // arg on stack
#endif // _TARGET_AMD64_

    // Make the call
    X86EmitCall(NewExternalCodeLabel((LPVOID) Thread::ObjectRefFlush), sizeof(void*));

#endif // _DEBUG

    // mov edi,[ebx + Thread.GetFrame()]    ;; get previous frame
    X86EmitIndexRegLoad(kEDI, kEBX, Thread::GetOffsetOfCurrentFrame());

    // mov [esi + Frame.m_next], edi
    X86EmitIndexRegStore(kESI, Frame::GetOffsetOfNextLink(), kEDI);

    // mov [ebx + Thread.GetFrame()], esi
    X86EmitIndexRegStore(kEBX, Thread::GetOffsetOfCurrentFrame(), kESI);

#if _DEBUG

    if (Frame::ShouldLogTransitions())
    {
        // call LogTransition
#ifdef _TARGET_AMD64_

        // mov rcx, rsi
        X86EmitR2ROp(0x8b, kECX, kESI);         // arg in reg

#else // !_TARGET_AMD64_
        X86EmitPushReg(kESI);                   // arg on stack
#endif // _TARGET_AMD64_
         
        X86EmitCall(NewExternalCodeLabel((LPVOID) Frame::LogTransition), sizeof(void*));

#ifdef _TARGET_AMD64_
    // Reload parameter registers
    // mov r, [esp+offs]
    #define ARGUMENT_REGISTER(regname) X86EmitEspOffset(0x8b, k##regname, sizeof(ArgumentRegisters) + \
        sizeof(TransitionFrame) + offsetof(ArgumentRegisters, regname));
    ENUM_ARGUMENT_REGISTERS();
    #undef ARGUMENT_REGISTER

#endif // _TARGET_AMD64_
    }

#endif // _DEBUG


#ifdef _TARGET_AMD64_
    // OK for the debugger to examine the new frame now
    // (Note that if it's not OK yet for some stub, another patch label
    // can be emitted later which will override this one.)    
    EmitPatchLabel();
#else
    // For x86, the patch label can be specified only after the GSCookie is pushed
    // Otherwise the debugger will see a Frame without a valid GSCookie
#endif
}

/*==============================================================================
 EmitMethodStubEpilog generates the part of the stub that will pop off the
 Frame
 
 restoreArgRegs - indicates whether the argument registers need to be
                  restored from m_argumentRegisters
  
 At this point of the stub:
    pFrame is in ESI/RSI.
    the previous pFrame is in EDI/RDI
    The current Thread* is in EBX/RBX.
    For x86, ESP points to the FramedMethodFrame::NegInfo
*/

VOID StubLinkerCPU::EmitMethodStubEpilog(WORD numArgBytes, int transitionBlockOffset)
{
    STANDARD_VM_CONTRACT;

    // mov [ebx + Thread.GetFrame()], edi  ;; restore previous frame
    X86EmitIndexRegStore(kEBX, Thread::GetOffsetOfCurrentFrame(), kEDI);

#ifdef _TARGET_X86_
    // deallocate Frame
    X86EmitAddEsp(sizeof(GSCookie) + transitionBlockOffset + TransitionBlock::GetOffsetOfCalleeSavedRegisters());

#elif defined(_TARGET_AMD64_)
    // lea rsp, [rsi + <offset of preserved registers>]
    X86EmitOffsetModRM(0x8d, (X86Reg)4 /*kRSP*/, kRSI, transitionBlockOffset + TransitionBlock::GetOffsetOfCalleeSavedRegisters());
#endif // _TARGET_AMD64_

    // pop edi        ; restore callee-saved registers
    // pop esi
    // pop ebx
    // pop ebp
    X86EmitPopReg(kEDI);
    X86EmitPopReg(kESI);
    X86EmitPopReg(kEBX);
    X86EmitPopReg(kEBP);

#ifdef _TARGET_AMD64_
    X86EmitPopReg(kR12);
    X86EmitPopReg(kR13);
    X86EmitPopReg(kR14);
    X86EmitPopReg(kR15);
#endif

#if defined(_TARGET_AMD64_) || defined(UNIX_X86_ABI)
    // Caller deallocates argument space.  (Bypasses ASSERT in
    // X86EmitReturn.)
    numArgBytes = 0;
#endif

    X86EmitReturn(numArgBytes);
}


// On entry, ESI should be pointing to the Frame

VOID StubLinkerCPU::EmitCheckGSCookie(X86Reg frameReg, int gsCookieOffset)
{
    STANDARD_VM_CONTRACT;

#ifdef _DEBUG
    // cmp dword ptr[frameReg-gsCookieOffset], gsCookie
#ifdef _TARGET_X86_
    X86EmitCmpRegIndexImm32(frameReg, gsCookieOffset, GetProcessGSCookie());
#else
    X64EmitCmp32RegIndexImm32(frameReg, gsCookieOffset, (INT32)GetProcessGSCookie());
#endif
    
    CodeLabel * pLabel = NewCodeLabel();
    X86EmitCondJump(pLabel, X86CondCode::kJE);
    
    X86EmitCall(NewExternalCodeLabel((LPVOID) JIT_FailFast), 0);

    EmitLabel(pLabel);
#endif
}
#endif // !FEATURE_STUBS_AS_IL


// This method unboxes the THIS pointer and then calls pRealMD
// If it's shared code for a method in a generic value class, then also extract the vtable pointer
// and pass it as an extra argument.  Thus this stub generator really covers both
//   - Unboxing, non-instantiating stubs
//   - Unboxing, method-table-instantiating stubs
VOID StubLinkerCPU::EmitUnboxMethodStub(MethodDesc* pUnboxMD)
{
    CONTRACTL
    {
        STANDARD_VM_CHECK;
        PRECONDITION(!pUnboxMD->IsStatic());
    }
    CONTRACTL_END;

#ifdef FEATURE_STUBS_AS_IL
    _ASSERTE(!pUnboxMD->RequiresInstMethodTableArg());
#else
    if (pUnboxMD->RequiresInstMethodTableArg())
    {
        EmitInstantiatingMethodStub(pUnboxMD, NULL);
        return;
    }
#endif

    //
    // unboxing a value class simply means adding sizeof(void*) to the THIS pointer
    //
#ifdef _TARGET_AMD64_
    X86EmitAddReg(THIS_kREG, sizeof(void*));

    // Use direct call if possible
    if (pUnboxMD->HasStableEntryPoint())
    {
        X86EmitRegLoad(kRAX, pUnboxMD->GetStableEntryPoint());// MOV RAX, DWORD
    }
    else
    {
        X86EmitRegLoad(kRAX, (UINT_PTR)pUnboxMD->GetAddrOfSlot()); // MOV RAX, DWORD
        
        X86EmitIndexRegLoad(kRAX, kRAX);                // MOV RAX, [RAX]
    }

    Emit16(X86_INSTR_JMP_EAX);                          // JMP EAX
#else // _TARGET_AMD64_
    X86EmitAddReg(THIS_kREG, sizeof(void*));

    // Use direct call if possible
    if (pUnboxMD->HasStableEntryPoint())
    {
        X86EmitNearJump(NewExternalCodeLabel((LPVOID) pUnboxMD->GetStableEntryPoint()));
    }
    else
    {
        // jmp [slot]
        Emit16(0x25ff);
        Emit32((DWORD)(size_t)pUnboxMD->GetAddrOfSlot());
    }
#endif //_TARGET_AMD64_
}


#if defined(FEATURE_SHARE_GENERIC_CODE) && !defined(FEATURE_STUBS_AS_IL)
// The stub generated by this method passes an extra dictionary argument before jumping to 
// shared-instantiation generic code.
//
// pMD is either
//    * An InstantiatedMethodDesc for a generic method whose code is shared across instantiations.
//      In this case, the extra argument is the InstantiatedMethodDesc for the instantiation-specific stub itself.
// or * A MethodDesc for a static method in a generic class whose code is shared across instantiations.
//      In this case, the extra argument is the MethodTable pointer of the instantiated type.
// or * A MethodDesc for unboxing stub. In this case, the extra argument is null.
VOID StubLinkerCPU::EmitInstantiatingMethodStub(MethodDesc* pMD, void* extra)
{
    CONTRACTL
    {
        STANDARD_VM_CHECK;
        PRECONDITION(pMD->RequiresInstArg());
    }
    CONTRACTL_END;

    MetaSig msig(pMD);
    ArgIterator argit(&msig);

#ifdef _TARGET_AMD64_
    int paramTypeArgOffset = argit.GetParamTypeArgOffset();
    int paramTypeArgIndex = TransitionBlock::GetArgumentIndexFromOffset(paramTypeArgOffset);

    CorElementType argTypes[5];

    int firstRealArg = paramTypeArgIndex + 1;
    int argNum = firstRealArg;

    //
    // Compute types of the 4 register args and first stack arg
    //

    CorElementType sigType;
    while ((sigType = msig.NextArgNormalized()) != ELEMENT_TYPE_END)
    {
        argTypes[argNum++] = sigType;
        if (argNum > 4)
            break;
    }
    msig.Reset();

    BOOL fUseInstantiatingMethodStubWorker = FALSE;

    if (argNum > 4)
    {
        //
        // We will need to go through assembly helper.
        //
        fUseInstantiatingMethodStubWorker = TRUE;

        // Allocate space for frame before pushing the arguments for the assembly helper
        X86EmitSubEsp((INT32)(AlignUp(sizeof(void *) /* extra stack param */ + sizeof(GSCookie) + sizeof(StubHelperFrame), 16) - sizeof(void *) /* return address */));

        //
        // Store extra arg stack arg param for the helper.
        //
        CorElementType argType = argTypes[--argNum];
        switch (argType)
        {
        case ELEMENT_TYPE_R4:
            // movss dword ptr [rsp], xmm?
            X64EmitMovSSToMem(kXMM3, (X86Reg)4 /*kRSP*/);
            break;
        case ELEMENT_TYPE_R8:
            // movsd qword ptr [rsp], xmm?
            X64EmitMovSDToMem(kXMM3, (X86Reg)4 /*kRSP*/);
            break;
        default:
            X86EmitIndexRegStoreRSP(0, kR9);
            break;
        }
    }

    //
    // Shuffle the register arguments
    //
    while (argNum > firstRealArg)
    {
        CorElementType argType = argTypes[--argNum];

        switch (argType)
        {
            case ELEMENT_TYPE_R4:
            case ELEMENT_TYPE_R8:
                // mov xmm#, xmm#-1
                X64EmitMovXmmXmm((X86Reg)argNum, (X86Reg)(argNum - 1));
                break;
            default:
                //mov reg#, reg#-1
                X86EmitMovRegReg(c_argRegs[argNum], c_argRegs[argNum-1]);
                break;
        }
    }

    //
    // Setup the hidden instantiation argument
    //
    if (extra != NULL)
    {
        X86EmitRegLoad(c_argRegs[paramTypeArgIndex], (UINT_PTR)extra);
    }
    else
    {
        X86EmitIndexRegLoad(c_argRegs[paramTypeArgIndex], THIS_kREG);

        X86EmitAddReg(THIS_kREG, sizeof(void*));
    }

    // Use direct call if possible
    if (pMD->HasStableEntryPoint())
    {
        X86EmitRegLoad(kRAX, pMD->GetStableEntryPoint());// MOV RAX, DWORD
    }
    else
    {
        X86EmitRegLoad(kRAX, (UINT_PTR)pMD->GetAddrOfSlot()); // MOV RAX, DWORD
        
        X86EmitIndexRegLoad(kRAX, kRAX);                // MOV RAX, [RAX]
    }

    if (fUseInstantiatingMethodStubWorker)
    {
        X86EmitPushReg(kRAX);

        UINT cbStack = argit.SizeOfArgStack();
        _ASSERTE(cbStack > 0);

        X86EmitPushImm32((AlignUp(cbStack, 16) / sizeof(void*)) - 1);           // -1 for extra stack arg

        X86EmitRegLoad(kRAX, GetEEFuncEntryPoint(InstantiatingMethodStubWorker));// MOV RAX, DWORD
    }
    else
    {
        _ASSERTE(argit.SizeOfArgStack() == 0);
    }

    Emit16(X86_INSTR_JMP_EAX);

#else   
    int paramTypeArgOffset = argit.GetParamTypeArgOffset();

    // It's on the stack
    if (TransitionBlock::IsStackArgumentOffset(paramTypeArgOffset))
    {
        // Pop return address into AX
        X86EmitPopReg(kEAX);

        if (extra != NULL)
        {
            // Push extra dictionary argument
            X86EmitPushImmPtr(extra);
        }
        else
        {
            // Push the vtable pointer from "this"
            X86EmitIndexPush(THIS_kREG, 0);
        }

        // Put return address back
        X86EmitPushReg(kEAX);
    }
    // It's in a register
    else
    {
        X86Reg paramReg = GetX86ArgumentRegisterFromOffset(paramTypeArgOffset - TransitionBlock::GetOffsetOfArgumentRegisters());

        if (extra != NULL)
        {
            X86EmitRegLoad(paramReg, (UINT_PTR)extra);
        }
        else
        {
            // Just extract the vtable pointer from "this"
            X86EmitIndexRegLoad(paramReg, THIS_kREG);
        }
    }

    if (extra == NULL)
    {
        // Unboxing stub case.
        X86EmitAddReg(THIS_kREG, sizeof(void*));
    }

    // Use direct call if possible
    if (pMD->HasStableEntryPoint())
    {
        X86EmitNearJump(NewExternalCodeLabel((LPVOID) pMD->GetStableEntryPoint()));
    }
    else
    {
        // jmp [slot]
        Emit16(0x25ff);
        Emit32((DWORD)(size_t)pMD->GetAddrOfSlot());
    }
#endif //
}
#endif // FEATURE_SHARE_GENERIC_CODE && FEATURE_STUBS_AS_IL


#if defined(_DEBUG) && defined(STUBLINKER_GENERATES_UNWIND_INFO) 

typedef BOOL GetModuleInformationProc(
  HANDLE hProcess,
  HMODULE hModule,
  LPMODULEINFO lpmodinfo,
  DWORD cb
);

GetModuleInformationProc *g_pfnGetModuleInformation = NULL;

extern "C" VOID __cdecl DebugCheckStubUnwindInfoWorker (CONTEXT *pStubContext)
{
    BEGIN_ENTRYPOINT_VOIDRET;

    LOG((LF_STUBS, LL_INFO1000000, "checking stub unwind info:\n"));

    //
    // Make a copy of the CONTEXT.  RtlVirtualUnwind will modify this copy.
    // DebugCheckStubUnwindInfo will need to restore registers from the
    // original CONTEXT.
    //
    CONTEXT ctx = *pStubContext;
    ctx.ContextFlags = (CONTEXT_CONTROL | CONTEXT_INTEGER);

    //
    // Find the upper bound of the stack and address range of KERNEL32.  This
    // is where we expect the unwind to stop.
    //
    void *pvStackTop = GetThread()->GetCachedStackBase();

    if (!g_pfnGetModuleInformation)
    {
        HMODULE hmodPSAPI = WszGetModuleHandle(W("PSAPI.DLL"));

        if (!hmodPSAPI)
        {
            hmodPSAPI = WszLoadLibrary(W("PSAPI.DLL"));
            if (!hmodPSAPI)
            {
                _ASSERTE(!"unable to load PSAPI.DLL");
                goto ErrExit;
            }
        }

        g_pfnGetModuleInformation = (GetModuleInformationProc*)GetProcAddress(hmodPSAPI, "GetModuleInformation");
        if (!g_pfnGetModuleInformation)
        {
            _ASSERTE(!"can't find PSAPI!GetModuleInformation");
            goto ErrExit;
        }

        // Intentionally leak hmodPSAPI.  We don't want to
        // LoadLibrary/FreeLibrary every time, this is slow + produces lots of
        // debugger spew.  This is just debugging code after all...
    }

    HMODULE hmodKERNEL32 = WszGetModuleHandle(W("KERNEL32"));
    _ASSERTE(hmodKERNEL32);

    MODULEINFO modinfoKERNEL32;
    if (!g_pfnGetModuleInformation(GetCurrentProcess(), hmodKERNEL32, &modinfoKERNEL32, sizeof(modinfoKERNEL32)))
    {
        _ASSERTE(!"unable to get bounds of KERNEL32");
        goto ErrExit;
    }

    //
    // Unwind until IP is 0, sp is at the stack top, and callee IP is in kernel32.
    //

    for (;;)
    {
        ULONG64 ControlPc = (ULONG64)GetIP(&ctx);

        LOG((LF_STUBS, LL_INFO1000000, "pc %p, sp %p\n", ControlPc, GetSP(&ctx)));

        ULONG64 ImageBase;
        T_RUNTIME_FUNCTION *pFunctionEntry = RtlLookupFunctionEntry(
                ControlPc,
                &ImageBase,
                NULL);
        if (pFunctionEntry)
        {
            PVOID HandlerData;
            ULONG64 EstablisherFrame;

            RtlVirtualUnwind(
                    0,
                    ImageBase,
                    ControlPc,
                    pFunctionEntry,
                    &ctx,
                    &HandlerData,
                    &EstablisherFrame,
                    NULL);

            ULONG64 NewControlPc = (ULONG64)GetIP(&ctx);

            LOG((LF_STUBS, LL_INFO1000000, "function %p, image %p, new pc %p, new sp %p\n", pFunctionEntry, ImageBase, NewControlPc, GetSP(&ctx)));

            if (!NewControlPc)
            {
                if (dac_cast<PTR_BYTE>(GetSP(&ctx)) < (BYTE*)pvStackTop - 0x100)
                {
                    _ASSERTE(!"SP did not end up at top of stack");
                    goto ErrExit;
                }

                if (!(   ControlPc > (ULONG64)modinfoKERNEL32.lpBaseOfDll
                      && ControlPc < (ULONG64)modinfoKERNEL32.lpBaseOfDll + modinfoKERNEL32.SizeOfImage))
                {
                    _ASSERTE(!"PC did not end up in KERNEL32");
                    goto ErrExit;
                }

                break;
            }
        }
        else
        {
            // Nested functions that do not use any stack space or nonvolatile
            // registers are not required to have unwind info (ex.
            // USER32!ZwUserCreateWindowEx).
            ctx.Rip = *(ULONG64*)(ctx.Rsp);
            ctx.Rsp += sizeof(ULONG64);
        }
    }
ErrExit:
    
    END_ENTRYPOINT_VOIDRET;
    return;
}

//virtual
VOID StubLinkerCPU::EmitUnwindInfoCheckWorker (CodeLabel *pCheckLabel)
{
    STANDARD_VM_CONTRACT;
    X86EmitCall(pCheckLabel, 0);
}

//virtual
VOID StubLinkerCPU::EmitUnwindInfoCheckSubfunction()
{
    STANDARD_VM_CONTRACT;

#ifdef _TARGET_AMD64_
    // X86EmitCall will generate "mov rax, target/jmp rax", so we have to save
    // rax on the stack.  DO NOT use X86EmitPushReg.  That will induce infinite
    // recursion, since the push may require more unwind info.  This "push rax"
    // will be accounted for by DebugCheckStubUnwindInfo's unwind info
    // (considered part of its locals), so there doesn't have to be unwind
    // info for it.
    Emit8(0x50);
#endif

    X86EmitNearJump(NewExternalCodeLabel(DebugCheckStubUnwindInfo));
}

#endif // defined(_DEBUG) && defined(STUBLINKER_GENERATES_UNWIND_INFO)


#ifdef _TARGET_X86_

//-----------------------------------------------------------------------
// Generates the inline portion of the code to enable preemptive GC. Hopefully,
// the inline code is all that will execute most of the time. If this code
// path is entered at certain times, however, it will need to jump out to
// a separate out-of-line path which is more expensive. The "pForwardRef"
// label indicates the start of the out-of-line path.
//
// Assumptions:
//      ebx = Thread
// Preserves
//      all registers except ecx.
//
//-----------------------------------------------------------------------
VOID StubLinkerCPU::EmitEnable(CodeLabel *pForwardRef)
{
    CONTRACTL
    {
        STANDARD_VM_CHECK;

        PRECONDITION(4 == sizeof( ((Thread*)0)->m_State ));
        PRECONDITION(4 == sizeof( ((Thread*)0)->m_fPreemptiveGCDisabled ));
    }
    CONTRACTL_END;

    // move byte ptr [ebx + Thread.m_fPreemptiveGCDisabled],0
    X86EmitOffsetModRM(0xc6, (X86Reg)0, kEBX, Thread::GetOffsetOfGCFlag());
    Emit8(0);

    _ASSERTE(FitsInI1(Thread::TS_CatchAtSafePoint));

    // test byte ptr [ebx + Thread.m_State], TS_CatchAtSafePoint
    X86EmitOffsetModRM(0xf6, (X86Reg)0, kEBX, Thread::GetOffsetOfState());
    Emit8(Thread::TS_CatchAtSafePoint);

    // jnz RarePath
    X86EmitCondJump(pForwardRef, X86CondCode::kJNZ);

#ifdef _DEBUG
    X86EmitDebugTrashReg(kECX);
#endif

}


//-----------------------------------------------------------------------
// Generates the out-of-line portion of the code to enable preemptive GC.
// After the work is done, the code jumps back to the "pRejoinPoint"
// which should be emitted right after the inline part is generated.
//
// Assumptions:
//      ebx = Thread
// Preserves
//      all registers except ecx.
//
//-----------------------------------------------------------------------
VOID StubLinkerCPU::EmitRareEnable(CodeLabel *pRejoinPoint)
{
    STANDARD_VM_CONTRACT;

    X86EmitCall(NewExternalCodeLabel((LPVOID) StubRareEnable), 0);
#ifdef _DEBUG
    X86EmitDebugTrashReg(kECX);
#endif
    if (pRejoinPoint)
    {
        X86EmitNearJump(pRejoinPoint);
    }

}


//-----------------------------------------------------------------------
// Generates the inline portion of the code to disable preemptive GC. Hopefully,
// the inline code is all that will execute most of the time. If this code
// path is entered at certain times, however, it will need to jump out to
// a separate out-of-line path which is more expensive. The "pForwardRef"
// label indicates the start of the out-of-line path.
//
// Assumptions:
//      ebx = Thread
// Preserves
//      all registers except ecx.
//
//-----------------------------------------------------------------------
VOID StubLinkerCPU::EmitDisable(CodeLabel *pForwardRef, BOOL fCallIn, X86Reg ThreadReg)
{
    CONTRACTL
    {
        STANDARD_VM_CHECK;

        PRECONDITION(4 == sizeof( ((Thread*)0)->m_fPreemptiveGCDisabled ));
        PRECONDITION(4 == sizeof(g_TrapReturningThreads));
    }
    CONTRACTL_END;

    // move byte ptr [ebx + Thread.m_fPreemptiveGCDisabled],1
    X86EmitOffsetModRM(0xc6, (X86Reg)0, ThreadReg, Thread::GetOffsetOfGCFlag());
    Emit8(1);

    // cmp dword ptr g_TrapReturningThreads, 0
    Emit16(0x3d83);
    EmitPtr((void *)&g_TrapReturningThreads);
    Emit8(0);

    // jnz RarePath
    X86EmitCondJump(pForwardRef, X86CondCode::kJNZ);

#if defined(FEATURE_COMINTEROP) && !defined(FEATURE_CORESYSTEM)
    // If we are checking whether the current thread holds the loader lock, vector
    // such cases to the rare disable pathway, where we can check again.
    if (fCallIn && ShouldCheckLoaderLock())
    {
        X86EmitPushReg(kEAX);
        X86EmitPushReg(kEDX);

        if (ThreadReg == kECX)
            X86EmitPushReg(kECX);

        // BOOL AuxUlibIsDLLSynchronizationHeld(BOOL *IsHeld)
        //
        // So we need to be sure that both the return value and the passed BOOL are both TRUE.
        // If either is FALSE, then the call failed or the lock is not held.  Either way, the
        // probe should not fire.

        X86EmitPushReg(kEDX);               // BOOL temp
        Emit8(0x54);                        // push ESP because arg is &temp
        X86EmitCall(NewExternalCodeLabel((LPVOID) AuxUlibIsDLLSynchronizationHeld), 0);

        // callee has popped.
        X86EmitPopReg(kEDX);                // recover temp

        CodeLabel   *pPopLabel = NewCodeLabel();

        Emit16(0xc085);                     // test eax, eax
        X86EmitCondJump(pPopLabel, X86CondCode::kJZ);

        Emit16(0xd285);                     // test edx, edx

        EmitLabel(pPopLabel);               // retain the conditional flags across the pops

        if (ThreadReg == kECX)
            X86EmitPopReg(kECX);

        X86EmitPopReg(kEDX);
        X86EmitPopReg(kEAX);

        X86EmitCondJump(pForwardRef, X86CondCode::kJNZ);
    }
#endif

#ifdef _DEBUG
    if (ThreadReg != kECX)
        X86EmitDebugTrashReg(kECX);
#endif

}


//-----------------------------------------------------------------------
// Generates the out-of-line portion of the code to disable preemptive GC.
// After the work is done, the code jumps back to the "pRejoinPoint"
// which should be emitted right after the inline part is generated.  However,
// if we cannot execute managed code at this time, an exception is thrown
// which cannot be caught by managed code.
//
// Assumptions:
//      ebx = Thread
// Preserves
//      all registers except ecx, eax.
//
//-----------------------------------------------------------------------
VOID StubLinkerCPU::EmitRareDisable(CodeLabel *pRejoinPoint)
{
    STANDARD_VM_CONTRACT;

    X86EmitCall(NewExternalCodeLabel((LPVOID) StubRareDisableTHROW), 0);

#ifdef _DEBUG
    X86EmitDebugTrashReg(kECX);
#endif
    X86EmitNearJump(pRejoinPoint);
}

#ifdef FEATURE_COMINTEROP
//-----------------------------------------------------------------------
// Generates the out-of-line portion of the code to disable preemptive GC.
// After the work is done, the code normally jumps back to the "pRejoinPoint"
// which should be emitted right after the inline part is generated.  However,
// if we cannot execute managed code at this time, an HRESULT is returned
// via the ExitPoint.
//
// Assumptions:
//      ebx = Thread
// Preserves
//      all registers except ecx, eax.
//
//-----------------------------------------------------------------------
VOID StubLinkerCPU::EmitRareDisableHRESULT(CodeLabel *pRejoinPoint, CodeLabel *pExitPoint)
{
    STANDARD_VM_CONTRACT;

    X86EmitCall(NewExternalCodeLabel((LPVOID) StubRareDisableHR), 0);

#ifdef _DEBUG
    X86EmitDebugTrashReg(kECX);
#endif

    // test eax, eax  ;; test the result of StubRareDisableHR
    Emit16(0xc085);

    // JZ pRejoinPoint
    X86EmitCondJump(pRejoinPoint, X86CondCode::kJZ);

    X86EmitNearJump(pExitPoint);
}
#endif // FEATURE_COMINTEROP

#endif // _TARGET_X86_

#endif // CROSSGEN_COMPILE


VOID StubLinkerCPU::EmitShuffleThunk(ShuffleEntry *pShuffleEntryArray)
{
    STANDARD_VM_CONTRACT;

#ifdef _TARGET_AMD64_

    // mov SCRATCHREG,rsp
    X86_64BitOperands();
    Emit8(0x8b);
    Emit8(0304 | (SCRATCH_REGISTER_X86REG << 3));

    // save the real target in r11, will jump to it later.  r10 is used below.
    // Windows: mov r11, rcx
    // Unix: mov r11, rdi
    X86EmitMovRegReg(kR11, THIS_kREG);

#ifdef UNIX_AMD64_ABI
    for (ShuffleEntry* pEntry = pShuffleEntryArray; pEntry->srcofs != ShuffleEntry::SENTINEL; pEntry++)
    {
        if (pEntry->srcofs & ShuffleEntry::REGMASK)
        {
            // Source in a general purpose or float register, destination in the same kind of a register or on stack
            int srcRegIndex = pEntry->srcofs & ShuffleEntry::OFSREGMASK;

            if (pEntry->dstofs & ShuffleEntry::REGMASK)
            {
                // Source in register, destination in register

                // Both the srcofs and dstofs must be of the same kind of registers - float or general purpose.
                _ASSERTE((pEntry->dstofs & ShuffleEntry::FPREGMASK) == (pEntry->srcofs & ShuffleEntry::FPREGMASK));
                int dstRegIndex = pEntry->dstofs & ShuffleEntry::OFSREGMASK;

                if (pEntry->srcofs & ShuffleEntry::FPREGMASK) 
                {
                    // movdqa dstReg, srcReg
                    X64EmitMovXmmXmm((X86Reg)(kXMM0 + dstRegIndex), (X86Reg)(kXMM0 + srcRegIndex));
                }
                else
                {
                    // mov dstReg, srcReg
                    X86EmitMovRegReg(c_argRegs[dstRegIndex], c_argRegs[srcRegIndex]);
                }
            }
            else
            {
                // Source in register, destination on stack
                int dstOffset = (pEntry->dstofs + 1) * sizeof(void*);

                if (pEntry->srcofs & ShuffleEntry::FPREGMASK) 
                {
                    if (pEntry->dstofs & ShuffleEntry::FPSINGLEMASK)
                    {
                        // movss [rax + dst], srcReg
                        X64EmitMovSSToMem((X86Reg)(kXMM0 + srcRegIndex), SCRATCH_REGISTER_X86REG, dstOffset);
                    }
                    else
                    {
                        // movsd [rax + dst], srcReg
                        X64EmitMovSDToMem((X86Reg)(kXMM0 + srcRegIndex), SCRATCH_REGISTER_X86REG, dstOffset);
                    }
                }
                else
                {
                    // mov [rax + dst], srcReg
                    X86EmitIndexRegStore (SCRATCH_REGISTER_X86REG, dstOffset, c_argRegs[srcRegIndex]);
                }
            }
        }
        else if (pEntry->dstofs & ShuffleEntry::REGMASK)
        {
            // Source on stack, destination in register
            _ASSERTE(!(pEntry->srcofs & ShuffleEntry::REGMASK));

            int dstRegIndex = pEntry->dstofs & ShuffleEntry::OFSREGMASK;
            int srcOffset = (pEntry->srcofs + 1) * sizeof(void*);

            if (pEntry->dstofs & ShuffleEntry::FPREGMASK) 
            {
                if (pEntry->dstofs & ShuffleEntry::FPSINGLEMASK)
                {
                    // movss dstReg, [rax + src]
                    X64EmitMovSSFromMem((X86Reg)(kXMM0 + dstRegIndex), SCRATCH_REGISTER_X86REG, srcOffset);
                }
                else
                {
                    // movsd dstReg, [rax + src]
                    X64EmitMovSDFromMem((X86Reg)(kXMM0 + dstRegIndex), SCRATCH_REGISTER_X86REG, srcOffset);
                }
            }
            else
            {
                // mov dstreg, [rax + src]
                X86EmitIndexRegLoad(c_argRegs[dstRegIndex], SCRATCH_REGISTER_X86REG, srcOffset);
            }
        }
        else
        {
            // Source on stack, destination on stack
            _ASSERTE(!(pEntry->srcofs & ShuffleEntry::REGMASK));
            _ASSERTE(!(pEntry->dstofs & ShuffleEntry::REGMASK));

            // mov r10, [rax + src]
            X86EmitIndexRegLoad (kR10, SCRATCH_REGISTER_X86REG, (pEntry->srcofs + 1) * sizeof(void*));

            // mov [rax + dst], r10
            X86EmitIndexRegStore (SCRATCH_REGISTER_X86REG, (pEntry->dstofs + 1) * sizeof(void*), kR10);
        }
    }
#else // UNIX_AMD64_ABI
    UINT step = 1;

    if (pShuffleEntryArray->argtype == ELEMENT_TYPE_END)
    {
        // Special handling of open instance methods with return buffer. Move "this"
        // by two slots, and leave the "retbufptr" between the two slots intact.

        // mov rcx, r8
        X86EmitMovRegReg(kRCX, kR8);

        // Skip this entry
        pShuffleEntryArray++;

        // Skip this entry and leave retbufptr intact
        step += 2;
    }

    // Now shuffle the args by one position:
    //   steps 1-3 : reg args (rcx, rdx, r8)
    //   step  4   : stack->reg arg (r9)
    //   step >4   : stack args

    for(;
        pShuffleEntryArray->srcofs != ShuffleEntry::SENTINEL;
        step++, pShuffleEntryArray++)
    {
        switch (step)
        {
        case 1:
        case 2:
        case 3:
            switch (pShuffleEntryArray->argtype)
            {
            case ELEMENT_TYPE_R4:
            case ELEMENT_TYPE_R8:
                // mov xmm-1#, xmm#
                X64EmitMovXmmXmm((X86Reg)(step - 1), (X86Reg)(step));
                break;
            default:
                // mov argRegs[step-1], argRegs[step]
                X86EmitMovRegReg(c_argRegs[step-1], c_argRegs[step]);
                break;
            }
            break;

        case 4:
        {
            switch (pShuffleEntryArray->argtype)
            {
            case ELEMENT_TYPE_R4:
                X64EmitMovSSFromMem(kXMM3, kRAX, 0x28);
                break;

            case ELEMENT_TYPE_R8:
                X64EmitMovSDFromMem(kXMM3, kRAX, 0x28);
                break;

            default:
                // mov r9, [rax + 28h]
                X86EmitIndexRegLoad (kR9, SCRATCH_REGISTER_X86REG, 5*sizeof(void*));
            }
            break;
        }
        default:

            // mov r10, [rax + (step+1)*sizeof(void*)]
            X86EmitIndexRegLoad (kR10, SCRATCH_REGISTER_X86REG, (step+1)*sizeof(void*));

            // mov [rax + step*sizeof(void*)], r10
            X86EmitIndexRegStore (SCRATCH_REGISTER_X86REG, step*sizeof(void*), kR10);
        }
    }
#endif // UNIX_AMD64_ABI

    // mov r10, [r11 + Delegate._methodptraux]
    X86EmitIndexRegLoad(kR10, kR11, DelegateObject::GetOffsetOfMethodPtrAux());
    // add r11, DelegateObject::GetOffsetOfMethodPtrAux() - load the indirection cell into r11
    X86EmitAddReg(kR11, DelegateObject::GetOffsetOfMethodPtrAux());
    // Now jump to real target
    //   jmp r10
    X86EmitR2ROp(0xff, (X86Reg)4, kR10);

#else // _TARGET_AMD64_

    UINT espadjust = 0;
    BOOL haveMemMemMove = FALSE;

    ShuffleEntry *pWalk = NULL;
    for (pWalk = pShuffleEntryArray; pWalk->srcofs != ShuffleEntry::SENTINEL; pWalk++)
    {
        if (!(pWalk->dstofs & ShuffleEntry::REGMASK) &&
            !(pWalk->srcofs & ShuffleEntry::REGMASK) &&
              pWalk->srcofs != pWalk->dstofs)
        {
            haveMemMemMove = TRUE;
            espadjust = sizeof(void*);
            break;
        }
    }

    if (haveMemMemMove)
    {
        // push ecx
        X86EmitPushReg(THIS_kREG);
    }
    else
    {
        // mov eax, ecx
        Emit8(0x8b);
        Emit8(0300 | SCRATCH_REGISTER_X86REG << 3 | THIS_kREG);
    }
    
    UINT16 emptySpot = 0x4 | ShuffleEntry::REGMASK;

    while (true)
    {
        for (pWalk = pShuffleEntryArray; pWalk->srcofs != ShuffleEntry::SENTINEL; pWalk++)
            if (pWalk->dstofs == emptySpot)
                break;
            
        if (pWalk->srcofs == ShuffleEntry::SENTINEL)
            break;
        
        if ((pWalk->dstofs & ShuffleEntry::REGMASK))
        {
            if (pWalk->srcofs & ShuffleEntry::REGMASK)
            {
                // mov <dstReg>,<srcReg>
                Emit8(0x8b);
                Emit8(static_cast<UINT8>(0300 |
                        (GetX86ArgumentRegisterFromOffset( pWalk->dstofs & ShuffleEntry::OFSMASK ) << 3) |
                        (GetX86ArgumentRegisterFromOffset( pWalk->srcofs & ShuffleEntry::OFSMASK ))));
            }
            else
            {
                X86EmitEspOffset(0x8b, GetX86ArgumentRegisterFromOffset( pWalk->dstofs & ShuffleEntry::OFSMASK ), pWalk->srcofs+espadjust);
            }
        }
        else
        {
            // if the destination is not a register, the source shouldn't be either.
            _ASSERTE(!(pWalk->srcofs & ShuffleEntry::REGMASK));
            if (pWalk->srcofs != pWalk->dstofs)
            {
               X86EmitEspOffset(0x8b, kEAX, pWalk->srcofs+espadjust);
               X86EmitEspOffset(0x89, kEAX, pWalk->dstofs+espadjust);
            }
        }
        emptySpot = pWalk->srcofs;
    }
    
    // Capture the stacksizedelta while we're at the end of the list.
    _ASSERTE(pWalk->srcofs == ShuffleEntry::SENTINEL);

    if (haveMemMemMove)
        X86EmitPopReg(SCRATCH_REGISTER_X86REG);

#ifdef UNIX_X86_ABI
    _ASSERTE(pWalk->stacksizedelta == 0);
#endif

    if (pWalk->stacksizedelta)
        X86EmitAddEsp(pWalk->stacksizedelta);

    // Now jump to real target
    //   JMP [SCRATCHREG]
    // we need to jump indirect so that for virtual delegates eax contains a pointer to the indirection cell
    X86EmitAddReg(SCRATCH_REGISTER_X86REG, DelegateObject::GetOffsetOfMethodPtrAux());
    static const BYTE bjmpeax[] = { 0xff, 0x20 };
    EmitBytes(bjmpeax, sizeof(bjmpeax));
    
#endif // _TARGET_AMD64_
}


#if !defined(CROSSGEN_COMPILE) && !defined(FEATURE_STUBS_AS_IL)

//===========================================================================
// Computes hash code for MulticastDelegate.Invoke()
UINT_PTR StubLinkerCPU::HashMulticastInvoke(MetaSig* pSig)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
    }
    CONTRACTL_END;

    ArgIterator argit(pSig);

    UINT numStackBytes = argit.SizeOfArgStack();

    if (numStackBytes > 0x7FFF) 
        COMPlusThrow(kNotSupportedException, W("NotSupported_TooManyArgs"));

#ifdef _TARGET_AMD64_
    // Generate a hash key as follows:
    //      UINT Arg0Type:2; // R4 (1), R8 (2), other (3)
    //      UINT Arg1Type:2; // R4 (1), R8 (2), other (3)
    //      UINT Arg2Type:2; // R4 (1), R8 (2), other (3)
    //      UINT Arg3Type:2; // R4 (1), R8 (2), other (3)
    //      UINT NumArgs:24; // number of arguments
    // (This should cover all the prestub variations)

    _ASSERTE(!(numStackBytes & 7));
    UINT hash = (numStackBytes / sizeof(void*)) << 8;

    UINT argNum = 0;

    // NextArg() doesn't take into account the "this" pointer.
    // That's why we have to special case it here.
    if (argit.HasThis())
    {
        hash |= 3 << (2*argNum);
        argNum++;
    }

    if (argit.HasRetBuffArg())
    {
        hash |= 3 << (2*argNum);
        argNum++;
    }

    for (; argNum < 4; argNum++)
    {
        switch (pSig->NextArgNormalized())
        {
        case ELEMENT_TYPE_END:
            argNum = 4;
            break;
        case ELEMENT_TYPE_R4:
            hash |= 1 << (2*argNum);
            break;
        case ELEMENT_TYPE_R8:
            hash |= 2 << (2*argNum);
            break;
        default:
            hash |= 3 << (2*argNum);
            break;
        }
    }

#else // _TARGET_AMD64_

    // check if the function is returning a float, in which case the stub has to take
    // care of popping the floating point stack except for the last invocation

    _ASSERTE(!(numStackBytes & 3));

    UINT hash = numStackBytes;

    if (CorTypeInfo::IsFloat(pSig->GetReturnType()))
    {
        hash |= 2;
    }
#endif // _TARGET_AMD64_

    return hash;
}

#ifdef _TARGET_X86_
//===========================================================================
// Emits code for MulticastDelegate.Invoke()
VOID StubLinkerCPU::EmitDelegateInvoke()
{
    STANDARD_VM_CONTRACT;

    CodeLabel *pNullLabel = NewCodeLabel();

    // test THISREG, THISREG
    X86EmitR2ROp(0x85, THIS_kREG, THIS_kREG);

    // jz null
    X86EmitCondJump(pNullLabel, X86CondCode::kJZ);

    // mov SCRATCHREG, [THISREG + Delegate.FP]  ; Save target stub in register
    X86EmitIndexRegLoad(SCRATCH_REGISTER_X86REG, THIS_kREG, DelegateObject::GetOffsetOfMethodPtr());

    // mov THISREG, [THISREG + Delegate.OR]  ; replace "this" pointer
    X86EmitIndexRegLoad(THIS_kREG, THIS_kREG, DelegateObject::GetOffsetOfTarget());

    // jmp SCRATCHREG
    Emit16(0xe0ff | (SCRATCH_REGISTER_X86REG<<8));

    // Do a null throw
    EmitLabel(pNullLabel);

    // mov ECX, CORINFO_NullReferenceException
    Emit8(0xb8+kECX);
    Emit32(CORINFO_NullReferenceException);

    X86EmitCall(NewExternalCodeLabel(GetEEFuncEntryPoint(JIT_InternalThrowFromHelper)), 0);
    
    X86EmitReturn(0);
}
#endif // _TARGET_X86_

VOID StubLinkerCPU::EmitMulticastInvoke(UINT_PTR hash)
{
    STANDARD_VM_CONTRACT;

    int thisRegOffset = MulticastFrame::GetOffsetOfTransitionBlock() + 
        TransitionBlock::GetOffsetOfArgumentRegisters() + offsetof(ArgumentRegisters, THIS_REG);

    // push the methoddesc on the stack
    // mov eax, [ecx + offsetof(_methodAuxPtr)]
    X86EmitIndexRegLoad(SCRATCH_REGISTER_X86REG, THIS_kREG, DelegateObject::GetOffsetOfMethodPtrAux());
    
    // Push a MulticastFrame on the stack.
    EmitMethodStubProlog(MulticastFrame::GetMethodFrameVPtr(), MulticastFrame::GetOffsetOfTransitionBlock());

#ifdef _TARGET_X86_
    // Frame is ready to be inspected by debugger for patch location
    EmitPatchLabel();
#else // _TARGET_AMD64_

    // Save register arguments in their home locations.
    // Non-FP registers are already saved by EmitMethodStubProlog.
    // (Assumes Sig.NextArg() does not enum RetBuffArg or "this".)

    int            argNum      = 0;
    __int32        argOfs      = MulticastFrame::GetOffsetOfTransitionBlock() + TransitionBlock::GetOffsetOfArgs();
    CorElementType argTypes[4];
    CorElementType argType;

    // 'this'
    argOfs += sizeof(void*);
    argTypes[argNum] = ELEMENT_TYPE_I8;
    argNum++;

    do
    {
        argType = ELEMENT_TYPE_END;

        switch ((hash >> (2 * argNum)) & 3)
        {
        case 0:
            argType = ELEMENT_TYPE_END;
            break;
        case 1:
            argType = ELEMENT_TYPE_R4;

            // movss dword ptr [rsp + argOfs], xmm?
            X64EmitMovSSToMem((X86Reg)argNum, kRSI, argOfs);
            break;
        case 2:
            argType = ELEMENT_TYPE_R8;

            // movsd qword ptr [rsp + argOfs], xmm?
            X64EmitMovSDToMem((X86Reg)argNum, kRSI, argOfs);
            break;
        default:
            argType = ELEMENT_TYPE_I;
            break;
        }

        argOfs += sizeof(void*);
        argTypes[argNum] = argType;
        argNum++;
    }
    while (argNum < 4 && ELEMENT_TYPE_END != argType);

    _ASSERTE(4 == argNum || ELEMENT_TYPE_END == argTypes[argNum-1]);

#endif // _TARGET_AMD64_

    // TODO: on AMD64, pick different regs for locals so don't need the pushes

    // push edi     ;; Save EDI (want to use it as loop index)
    X86EmitPushReg(kEDI);

    // xor edi,edi  ;; Loop counter: EDI=0,1,2...
    X86EmitZeroOutReg(kEDI);

    CodeLabel *pLoopLabel = NewCodeLabel();
    CodeLabel *pEndLoopLabel = NewCodeLabel();

    EmitLabel(pLoopLabel);

    // Entry:
    //   EDI == iteration counter

    // mov ecx, [esi + this]     ;; get delegate
    X86EmitIndexRegLoad(THIS_kREG, kESI, thisRegOffset);

    // cmp edi,[ecx]._invocationCount
    X86EmitOp(0x3b, kEDI, THIS_kREG, DelegateObject::GetOffsetOfInvocationCount());

    // je ENDLOOP
    X86EmitCondJump(pEndLoopLabel, X86CondCode::kJZ);

#ifdef _TARGET_AMD64_

    INT32 numStackBytes = (INT32)((hash >> 8) * sizeof(void *));

    INT32 stackUsed, numStackArgs, ofs;

    // Push any stack args, plus an extra location
    // for rsp alignment if needed

    numStackArgs = numStackBytes / sizeof(void*);

    // 1 push above, so stack is currently misaligned
    const unsigned STACK_ALIGN_ADJUST = 8;

    if (!numStackArgs)
    {
        // sub rsp, 28h             ;; 4 reg arg home locs + rsp alignment
        stackUsed = 0x20 + STACK_ALIGN_ADJUST;
        X86EmitSubEsp(stackUsed);
    }
    else
    {
        stackUsed = numStackArgs * sizeof(void*);

        // If the stack is misaligned, then an odd number of arguments
        // will naturally align the stack.
        if (   ((numStackArgs & 1) == 0)
            != (STACK_ALIGN_ADJUST == 0))
        {
            X86EmitPushReg(kRAX);
            stackUsed += sizeof(void*);
        }

        ofs = MulticastFrame::GetOffsetOfTransitionBlock() +
            TransitionBlock::GetOffsetOfArgs() + sizeof(ArgumentRegisters) + numStackBytes;

        while (numStackArgs--)
        {
            ofs -= sizeof(void*);

            // push [rsi + ofs]     ;; Push stack args
            X86EmitIndexPush(kESI, ofs);
        }

        // sub rsp, 20h             ;; Create 4 reg arg home locations
        X86EmitSubEsp(0x20);

        stackUsed += 0x20;
    }

    for(
        argNum = 0, argOfs = MulticastFrame::GetOffsetOfTransitionBlock() + TransitionBlock::GetOffsetOfArgs();
        argNum < 4 && argTypes[argNum] != ELEMENT_TYPE_END;
        argNum++, argOfs += sizeof(void*)
        )
    {
        switch (argTypes[argNum])
        {
        case ELEMENT_TYPE_R4:
            // movss xmm?, dword ptr [rsi + argOfs]
            X64EmitMovSSFromMem((X86Reg)argNum, kRSI, argOfs);
            break;
        case ELEMENT_TYPE_R8:
            // movsd xmm?, qword ptr [rsi + argOfs]
            X64EmitMovSDFromMem((X86Reg)argNum, kRSI, argOfs);
            break;
        default:
            if (c_argRegs[argNum] != THIS_kREG)
            {
                // mov r*, [rsi + dstOfs]
                X86EmitIndexRegLoad(c_argRegs[argNum], kESI,argOfs);
            }
            break;
        } // switch
    }

    //    mov SCRATCHREG, [rcx+Delegate._invocationList]  ;;fetch invocation list
    X86EmitIndexRegLoad(SCRATCH_REGISTER_X86REG, THIS_kREG, DelegateObject::GetOffsetOfInvocationList());

    //    mov SCRATCHREG, [SCRATCHREG+m_Array+rdi*8]    ;; index into invocation list
    X86EmitOp(0x8b, kEAX, SCRATCH_REGISTER_X86REG, static_cast<int>(PtrArray::GetDataOffset()), kEDI, sizeof(void*), k64BitOp);

    //    mov THISREG, [SCRATCHREG+Delegate.object]  ;;replace "this" pointer
    X86EmitIndexRegLoad(THIS_kREG, SCRATCH_REGISTER_X86REG, DelegateObject::GetOffsetOfTarget());

    // call [SCRATCHREG+Delegate.target] ;; call current subscriber
    X86EmitOffsetModRM(0xff, (X86Reg)2, SCRATCH_REGISTER_X86REG, DelegateObject::GetOffsetOfMethodPtr());

    // add rsp, stackUsed           ;; Clean up stack
    X86EmitAddEsp(stackUsed);

    //    inc edi
    Emit16(0xC7FF);

#else // _TARGET_AMD64_

    UINT16 numStackBytes = static_cast<UINT16>(hash & ~3);

    //    ..repush & reenregister args..
    INT32 ofs = numStackBytes + MulticastFrame::GetOffsetOfTransitionBlock() + TransitionBlock::GetOffsetOfArgs();
    while (ofs != MulticastFrame::GetOffsetOfTransitionBlock() + TransitionBlock::GetOffsetOfArgs())
    {
        ofs -= sizeof(void*);
        X86EmitIndexPush(kESI, ofs);
    }

    #define ARGUMENT_REGISTER(regname) if (k##regname != THIS_kREG) { X86EmitIndexRegLoad(k##regname, kESI, \
        offsetof(ArgumentRegisters, regname) + MulticastFrame::GetOffsetOfTransitionBlock() + TransitionBlock::GetOffsetOfArgumentRegisters()); }

    ENUM_ARGUMENT_REGISTERS_BACKWARD();

    #undef ARGUMENT_REGISTER

    //    mov SCRATCHREG, [ecx+Delegate._invocationList]  ;;fetch invocation list
    X86EmitIndexRegLoad(SCRATCH_REGISTER_X86REG, THIS_kREG, DelegateObject::GetOffsetOfInvocationList());

    //    mov SCRATCHREG, [SCRATCHREG+m_Array+edi*4]    ;; index into invocation list
    X86EmitOp(0x8b, kEAX, SCRATCH_REGISTER_X86REG, PtrArray::GetDataOffset(), kEDI, sizeof(void*));

    //    mov THISREG, [SCRATCHREG+Delegate.object]  ;;replace "this" pointer
    X86EmitIndexRegLoad(THIS_kREG, SCRATCH_REGISTER_X86REG, DelegateObject::GetOffsetOfTarget());

    //    call [SCRATCHREG+Delegate.target] ;; call current subscriber
    X86EmitOffsetModRM(0xff, (X86Reg)2, SCRATCH_REGISTER_X86REG, DelegateObject::GetOffsetOfMethodPtr());
    INDEBUG(Emit8(0x90));       // Emit a nop after the call in debug so that
                                // we know that this is a call that can directly call
                                // managed code

    //    inc edi
    Emit8(0x47);

    if (hash & 2) // CorTypeInfo::IsFloat(pSig->GetReturnType())
    {
        // if the return value is a float/double check if we just did the last call - if not,
        // emit the pop of the float stack

        // mov SCRATCHREG, [esi + this]     ;; get delegate
        X86EmitIndexRegLoad(SCRATCH_REGISTER_X86REG, kESI, thisRegOffset);

        // cmp edi,[SCRATCHREG]._invocationCount
        X86EmitOffsetModRM(0x3b, kEDI, SCRATCH_REGISTER_X86REG, DelegateObject::GetOffsetOfInvocationCount());

        CodeLabel *pNoFloatStackPopLabel = NewCodeLabel();

        // je NOFLOATSTACKPOP
        X86EmitCondJump(pNoFloatStackPopLabel, X86CondCode::kJZ);

        // fstp 0
        Emit16(0xd8dd);

        // NoFloatStackPopLabel:
        EmitLabel(pNoFloatStackPopLabel);
    }

#endif // _TARGET_AMD64_

    // The debugger may need to stop here, so grab the offset of this code.
    EmitPatchLabel();

    // jmp LOOP
    X86EmitNearJump(pLoopLabel);

    //ENDLOOP:
    EmitLabel(pEndLoopLabel);

    // pop edi     ;; Restore edi
    X86EmitPopReg(kEDI);
 
    EmitCheckGSCookie(kESI, MulticastFrame::GetOffsetOfGSCookie());

    // Epilog
    EmitMethodStubEpilog(numStackBytes, MulticastFrame::GetOffsetOfTransitionBlock());
}

VOID StubLinkerCPU::EmitSecureDelegateInvoke(UINT_PTR hash)
{
    STANDARD_VM_CONTRACT;

    int thisRegOffset = SecureDelegateFrame::GetOffsetOfTransitionBlock() +
        TransitionBlock::GetOffsetOfArgumentRegisters() + offsetof(ArgumentRegisters, THIS_REG);

    // push the methoddesc on the stack
    // mov eax, [ecx + offsetof(_invocationCount)]
    X86EmitIndexRegLoad(SCRATCH_REGISTER_X86REG, THIS_kREG, DelegateObject::GetOffsetOfInvocationCount());
    
    // Push a SecureDelegateFrame on the stack.
    EmitMethodStubProlog(SecureDelegateFrame::GetMethodFrameVPtr(), SecureDelegateFrame::GetOffsetOfTransitionBlock());

#ifdef _TARGET_X86_
    // Frame is ready to be inspected by debugger for patch location
    EmitPatchLabel();
#else // _TARGET_AMD64_

    // Save register arguments in their home locations.
    // Non-FP registers are already saved by EmitMethodStubProlog.
    // (Assumes Sig.NextArg() does not enum RetBuffArg or "this".)

    int            argNum      = 0;
    __int32        argOfs      = SecureDelegateFrame::GetOffsetOfTransitionBlock() + TransitionBlock::GetOffsetOfArgs();
    CorElementType argTypes[4];
    CorElementType argType;

    // 'this'
    argOfs += sizeof(void*);
    argTypes[argNum] = ELEMENT_TYPE_I8;
    argNum++;

    do
    {
        argType = ELEMENT_TYPE_END;

        switch ((hash >> (2 * argNum)) & 3)
        {
        case 0:
            argType = ELEMENT_TYPE_END;
            break;
        case 1:
            argType = ELEMENT_TYPE_R4;

            // movss dword ptr [rsp + argOfs], xmm?
            X64EmitMovSSToMem((X86Reg)argNum, kRSI, argOfs);
            break;
        case 2:
            argType = ELEMENT_TYPE_R8;

            // movsd qword ptr [rsp + argOfs], xmm?
            X64EmitMovSSToMem((X86Reg)argNum, kRSI, argOfs);
            break;
        default:
            argType = ELEMENT_TYPE_I;
            break;
        }

        argOfs += sizeof(void*);
        argTypes[argNum] = argType;
        argNum++;
    }
    while (argNum < 4 && ELEMENT_TYPE_END != argType);

    _ASSERTE(4 == argNum || ELEMENT_TYPE_END == argTypes[argNum-1]);

#endif // _TARGET_AMD64_

    // mov ecx, [esi + this]     ;; get delegate
    X86EmitIndexRegLoad(THIS_kREG, kESI, thisRegOffset);

#ifdef _TARGET_AMD64_

    INT32 numStackBytes = (INT32)((hash >> 8) * sizeof(void *));

    INT32 stackUsed, numStackArgs, ofs;

    // Push any stack args, plus an extra location
    // for rsp alignment if needed

    numStackArgs = numStackBytes / sizeof(void*);

    // 1 push above, so stack is currently misaligned
    const unsigned STACK_ALIGN_ADJUST = 0;

    if (!numStackArgs)
    {
        // sub rsp, 28h             ;; 4 reg arg home locs + rsp alignment
        stackUsed = 0x20 + STACK_ALIGN_ADJUST;
        X86EmitSubEsp(stackUsed);
    }
    else
    {
        stackUsed = numStackArgs * sizeof(void*);

        // If the stack is misaligned, then an odd number of arguments
        // will naturally align the stack.
        if (   ((numStackArgs & 1) == 0)
            != (STACK_ALIGN_ADJUST == 0))
        {
            X86EmitPushReg(kRAX);
            stackUsed += sizeof(void*);
        }

        ofs = SecureDelegateFrame::GetOffsetOfTransitionBlock() +
            TransitionBlock::GetOffsetOfArgs() + sizeof(ArgumentRegisters) + numStackBytes;

        while (numStackArgs--)
        {
            ofs -= sizeof(void*);

            // push [rsi + ofs]     ;; Push stack args
            X86EmitIndexPush(kESI, ofs);
        }

        // sub rsp, 20h             ;; Create 4 reg arg home locations
        X86EmitSubEsp(0x20);

        stackUsed += 0x20;
    }

    int thisArgNum = 0;

    for(
        argNum = 0, argOfs = SecureDelegateFrame::GetOffsetOfTransitionBlock() + TransitionBlock::GetOffsetOfArgs();
        argNum < 4 && argTypes[argNum] != ELEMENT_TYPE_END;
        argNum++, argOfs += sizeof(void*)
        )
    {
        switch (argTypes[argNum])
        {
        case ELEMENT_TYPE_R4:
            // movss xmm?, dword ptr [rsi + argOfs]
            X64EmitMovSSFromMem((X86Reg)argNum, kRSI, argOfs);
            break;
        case ELEMENT_TYPE_R8:
            // movsd xmm?, qword ptr [rsi + argOfs]
            X64EmitMovSDFromMem((X86Reg)argNum, kRSI, argOfs);
            break;
        default:
            if (c_argRegs[argNum] != THIS_kREG)
            {
                // mov r*, [rsi + dstOfs]
                X86EmitIndexRegLoad(c_argRegs[argNum], kESI,argOfs);
            }
            break;
        } // switch
    }

    //    mov SCRATCHREG, [rcx+Delegate._invocationList]  ;;fetch the inner delegate
    X86EmitIndexRegLoad(SCRATCH_REGISTER_X86REG, THIS_kREG, DelegateObject::GetOffsetOfInvocationList());

    //    mov THISREG, [SCRATCHREG+Delegate.object]  ;;replace "this" pointer
    X86EmitIndexRegLoad(c_argRegs[thisArgNum], SCRATCH_REGISTER_X86REG, DelegateObject::GetOffsetOfTarget());

    // call [SCRATCHREG+Delegate.target] ;; call current subscriber
    X86EmitOffsetModRM(0xff, (X86Reg)2, SCRATCH_REGISTER_X86REG, DelegateObject::GetOffsetOfMethodPtr());

    // add rsp, stackUsed           ;; Clean up stack
    X86EmitAddEsp(stackUsed);

#else // _TARGET_AMD64_

    UINT16 numStackBytes = static_cast<UINT16>(hash & ~3);

    //    ..repush & reenregister args..
    INT32 ofs = numStackBytes + SecureDelegateFrame::GetOffsetOfTransitionBlock() + TransitionBlock::GetOffsetOfArgs();
    while (ofs != SecureDelegateFrame::GetOffsetOfTransitionBlock() + TransitionBlock::GetOffsetOfArgs())
    {
        ofs -= sizeof(void*);
        X86EmitIndexPush(kESI, ofs);
    }

    #define ARGUMENT_REGISTER(regname) if (k##regname != THIS_kREG) { X86EmitIndexRegLoad(k##regname, kESI, \
        offsetof(ArgumentRegisters, regname) + SecureDelegateFrame::GetOffsetOfTransitionBlock() + TransitionBlock::GetOffsetOfArgumentRegisters()); }

    ENUM_ARGUMENT_REGISTERS_BACKWARD();

    #undef ARGUMENT_REGISTER

    //    mov SCRATCHREG, [ecx+Delegate._invocationList]  ;;fetch the inner delegate
    X86EmitIndexRegLoad(SCRATCH_REGISTER_X86REG, THIS_kREG, DelegateObject::GetOffsetOfInvocationList());

    //    mov THISREG, [SCRATCHREG+Delegate.object]  ;;replace "this" pointer
    X86EmitIndexRegLoad(THIS_kREG, SCRATCH_REGISTER_X86REG, DelegateObject::GetOffsetOfTarget());

    //    call [SCRATCHREG+Delegate.target] ;; call current subscriber
    X86EmitOffsetModRM(0xff, (X86Reg)2, SCRATCH_REGISTER_X86REG, DelegateObject::GetOffsetOfMethodPtr());
    INDEBUG(Emit8(0x90));       // Emit a nop after the call in debug so that
                                // we know that this is a call that can directly call
                                // managed code

#endif // _TARGET_AMD64_

    // The debugger may need to stop here, so grab the offset of this code.
    EmitPatchLabel();

    EmitCheckGSCookie(kESI, SecureDelegateFrame::GetOffsetOfGSCookie());

    // Epilog
    EmitMethodStubEpilog(numStackBytes, SecureDelegateFrame::GetOffsetOfTransitionBlock());
}
#endif // !CROSSGEN_COMPILE && !FEATURE_STUBS_AS_IL

#if !defined(CROSSGEN_COMPILE) && !defined(FEATURE_ARRAYSTUB_AS_IL)

// Little helper to generate code to move nbytes bytes of non Ref memory

void generate_noref_copy (unsigned nbytes, StubLinkerCPU* sl)
{
    CONTRACTL
    {
        THROWS;
        GC_NOTRIGGER;
        INJECT_FAULT(COMPlusThrowOM(););
    }
    CONTRACTL_END;

    // If the size is pointer-aligned, we'll use movsd
    if (IS_ALIGNED(nbytes, sizeof(void*)))
    {
        // If there are less than 4 pointers to copy, "unroll" the "rep movsd"
        if (nbytes <= 3*sizeof(void*))
        {
            while (nbytes > 0)
            {
                // movsd
                sl->X86_64BitOperands();
                sl->Emit8(0xa5);

                nbytes -= sizeof(void*);
            }
        }
        else
        {
            // mov ECX, size / 4
            sl->Emit8(0xb8+kECX);
            sl->Emit32(nbytes / sizeof(void*));

            // repe movsd
            sl->Emit8(0xf3);
            sl->X86_64BitOperands();
            sl->Emit8(0xa5);
        }
    }
    else
    {
        // mov ECX, size
        sl->Emit8(0xb8+kECX);
        sl->Emit32(nbytes);

        // repe movsb
        sl->Emit16(0xa4f3);
    }
}


X86Reg LoadArrayOpArg (
        UINT32 idxloc,
        StubLinkerCPU *psl,
        X86Reg kRegIfFromMem,
        UINT ofsadjust
        AMD64_ARG(StubLinkerCPU::X86OperandSize OperandSize = StubLinkerCPU::k64BitOp)
        )
{
    STANDARD_VM_CONTRACT;

    if (!TransitionBlock::IsStackArgumentOffset(idxloc))
        return GetX86ArgumentRegisterFromOffset(idxloc - TransitionBlock::GetOffsetOfArgumentRegisters());

    psl->X86EmitEspOffset(0x8b, kRegIfFromMem, idxloc + ofsadjust AMD64_ARG(OperandSize));
    return kRegIfFromMem;
}

VOID StubLinkerCPU::EmitArrayOpStubThrow(unsigned exConst, unsigned cbRetArg)
{
    STANDARD_VM_CONTRACT;

    //ArrayOpStub*Exception
    X86EmitPopReg(kESI);
    X86EmitPopReg(kEDI);

    //mov CORINFO_NullReferenceException_ASM, %ecx
    Emit8(0xb8 | kECX);
    Emit32(exConst);
    //InternalExceptionWorker

    X86EmitPopReg(kEDX);
    // add pArrayOpScript->m_cbretpop, %esp (was add %eax, %esp)
    Emit8(0x81);
    Emit8(0xc0 | 0x4);
    Emit32(cbRetArg);
    X86EmitPushReg(kEDX);
    X86EmitNearJump(NewExternalCodeLabel((PVOID)JIT_InternalThrow));
}

//===========================================================================
// Emits code to do an array operation.
#ifdef _PREFAST_
#pragma warning(push)
#pragma warning(disable:21000) // Suppress PREFast warning about overly large function
#endif
VOID StubLinkerCPU::EmitArrayOpStub(const ArrayOpScript* pArrayOpScript)
{
    STANDARD_VM_CONTRACT;

    // This is the offset to the parameters/what's already pushed on the stack:
    // return address.
    const INT  locsize     = sizeof(void*);

    // ArrayOpScript's stack offsets are built using ArgIterator, which
    // assumes a TransitionBlock has been pushed, which is not the case
    // here.  rsp + ofsadjust should point at the first argument.  Any further
    // stack modifications below need to adjust ofsadjust appropriately.
    // baseofsadjust needs to be the stack adjustment at the entry point -
    // this is used further below to compute how much stack space was used.
    
    INT ofsadjust = locsize - (INT)sizeof(TransitionBlock);

    // Register usage
    //
    //                                          x86                 AMD64
    // Inputs:
    //  managed array                           THIS_kREG (ecx)     THIS_kREG (rcx)
    //  index 0                                 edx                 rdx
    //  index 1/value                           <stack>             r8
    //  index 2/value                           <stack>             r9
    //  expected element type for LOADADDR      eax                 rax                 rdx
    // Working registers:
    //  total (accumulates unscaled offset)     edi                 r10
    //  factor (accumulates the slice factor)   esi                 r11
    X86Reg kArrayRefReg = THIS_kREG;
#ifdef _TARGET_AMD64_
    const X86Reg kArrayMTReg  = kR10;
    const X86Reg kTotalReg    = kR10;
    const X86Reg kFactorReg   = kR11;
#else
    const X86Reg kArrayMTReg  = kESI;
    const X86Reg kTotalReg    = kEDI;
    const X86Reg kFactorReg   = kESI;
#endif

#ifdef _TARGET_AMD64_
    // Simplifying assumption for fNeedPrologue.
    _ASSERTE(!pArrayOpScript->m_gcDesc || (pArrayOpScript->m_flags & ArrayOpScript::NEEDSWRITEBARRIER));
    // Simplifying assumption for saving rsi and rdi.
    _ASSERTE(!(pArrayOpScript->m_flags & ArrayOpScript::HASRETVALBUFFER) || ArgIterator::IsArgPassedByRef(pArrayOpScript->m_elemsize));

    // Cases where we need to make calls
    BOOL fNeedScratchArea = (   (pArrayOpScript->m_flags & (ArrayOpScript::NEEDSTYPECHECK | ArrayOpScript::NEEDSWRITEBARRIER))
                             && (   pArrayOpScript->m_op == ArrayOpScript::STORE
                                 || (   pArrayOpScript->m_op == ArrayOpScript::LOAD
                                     && (pArrayOpScript->m_flags & ArrayOpScript::HASRETVALBUFFER))));

    // Cases where we need to copy large values
    BOOL fNeedRSIRDI = (   ArgIterator::IsArgPassedByRef(pArrayOpScript->m_elemsize)
                        && ArrayOpScript::LOADADDR != pArrayOpScript->m_op);

    BOOL fNeedPrologue = (   fNeedScratchArea
                          || fNeedRSIRDI);
#endif

    X86Reg       kValueReg;

    CodeLabel *Epilog = NewCodeLabel();
    CodeLabel *Inner_nullexception = NewCodeLabel();
    CodeLabel *Inner_rangeexception = NewCodeLabel();
    CodeLabel *Inner_typeMismatchexception = NULL;

    //
    // Set up the stack frame.
    //
    //
    // x86:
    //          value
    //          <index n-1>
    //          ...
    //          <index 1>
    //          return address
    //          saved edi
    // esp ->   saved esi
    //
    //
    // AMD64:
    //          value, if rank > 2
    //          ...
    // + 0x48   more indices
    // + 0x40   r9 home
    // + 0x38   r8 home
    // + 0x30   rdx home
    // + 0x28   rcx home
    // + 0x20   return address
    // + 0x18   scratch area (callee's r9)
    // + 0x10   scratch area (callee's r8)
    // +    8   scratch area (callee's rdx)
    // rsp ->   scratch area (callee's rcx)
    //
    // If the element type is a value class w/ object references, then rsi
    // and rdi will also be saved above the scratch area:
    //
    // ...
    // + 0x28   saved rsi
    // + 0x20   saved rdi
    // + 0x18   scratch area (callee's r9)
    // + 0x10   scratch area (callee's r8)
    // +    8   scratch area (callee's rdx)
    // rsp ->   scratch area (callee's rcx)
    //
    // And if no call or movsb is necessary, then the scratch area sits
    // directly under the MethodDesc*.

    BOOL fSavedESI = FALSE;
    BOOL fSavedEDI = FALSE;

#ifdef _TARGET_AMD64_
    if (fNeedPrologue)
    {
        // Save argument registers if we'll be making a call before using
        // them.  Note that in this case the element value will always be an
        // object type, and never be in an xmm register.

        if (   (pArrayOpScript->m_flags & ArrayOpScript::NEEDSTYPECHECK)
            && ArrayOpScript::STORE == pArrayOpScript->m_op)
        {
            // mov      [rsp+0x08], rcx
            X86EmitEspOffset(0x89, kRCX, 0x08);
            X86EmitEspOffset(0x89, kRDX, 0x10);
            X86EmitEspOffset(0x89, kR8,  0x18);

            if (pArrayOpScript->m_rank >= 2)
                X86EmitEspOffset(0x89, kR9, 0x20);
        }

        if (fNeedRSIRDI)
        {
            X86EmitPushReg(kRSI);
            X86EmitPushReg(kRDI);

            fSavedESI = fSavedEDI = TRUE;

            ofsadjust += 0x10;
        }

        if (fNeedScratchArea)
        {
            // Callee scratch area (0x8 for aligned esp)
            X86EmitSubEsp(sizeof(ArgumentRegisters) + 0x8);
            ofsadjust += sizeof(ArgumentRegisters) + 0x8;
        }
    }
#else
    // Preserve the callee-saved registers
    // NOTE: if you change the sequence of these pushes, you must also update:
    //  ArrayOpStubNullException
    //  ArrayOpStubRangeException
    //  ArrayOpStubTypeMismatchException
    _ASSERTE(      kTotalReg == kEDI);
    X86EmitPushReg(kTotalReg);
    _ASSERTE(      kFactorReg == kESI);
    X86EmitPushReg(kFactorReg);

    fSavedESI = fSavedEDI = TRUE;

    ofsadjust += 2*sizeof(void*);
#endif

    // Check for null.
    X86EmitR2ROp(0x85, kArrayRefReg, kArrayRefReg);             //   TEST ECX, ECX
    X86EmitCondJump(Inner_nullexception, X86CondCode::kJZ);     //   jz  Inner_nullexception

    // Do Type Check if needed
    if (pArrayOpScript->m_flags & ArrayOpScript::NEEDSTYPECHECK)
    {
        if (pArrayOpScript->m_op == ArrayOpScript::STORE)
        {
            // Get the value to be stored.
            kValueReg = LoadArrayOpArg(pArrayOpScript->m_fValLoc, this, kEAX, ofsadjust);

            X86EmitR2ROp(0x85, kValueReg, kValueReg);                   // TEST kValueReg, kValueReg
            CodeLabel *CheckPassed = NewCodeLabel();
            X86EmitCondJump(CheckPassed, X86CondCode::kJZ);             // storing NULL is OK

                                                                        // mov EAX, element type ; possibly trashes kValueReg
            X86EmitOp(0x8b, kArrayMTReg, kArrayRefReg, 0 AMD64_ARG(k64BitOp)); // mov ESI/R10, [kArrayRefReg]

            X86EmitOp(0x8b, kEAX, kValueReg, 0 AMD64_ARG(k64BitOp));    // mov EAX, [kValueReg]  ; possibly trashes kValueReg
                                                                        // cmp EAX, [ESI/R10+m_ElementType]

            X86EmitOp(0x3b, kEAX, kArrayMTReg, MethodTable::GetOffsetOfArrayElementTypeHandle() AMD64_ARG(k64BitOp));
            X86EmitCondJump(CheckPassed, X86CondCode::kJZ);             // Exact match is OK

            X86EmitRegLoad(kEAX, (UINT_PTR)g_pObjectClass);             // mov EAX, g_pObjectMethodTable
                                                                        // cmp EAX, [ESI/R10+m_ElementType]

            X86EmitOp(0x3b, kEAX, kArrayMTReg, MethodTable::GetOffsetOfArrayElementTypeHandle() AMD64_ARG(k64BitOp));
            X86EmitCondJump(CheckPassed, X86CondCode::kJZ);             // Assigning to array of object is OK

            // Try to call the fast helper first ( ObjIsInstanceOfNoGC ).
            // If that fails we will fall back to calling the slow helper ( ArrayStoreCheck ) that erects a frame.
            // See also JitInterfaceX86::JIT_Stelem_Ref  
                                   
#ifdef _TARGET_AMD64_
            // RCX contains pointer to object to check (Object*)
            // RDX contains array type handle 
            
            // mov RCX, [rsp+offsetToObject] ; RCX = Object*
            X86EmitEspOffset(0x8b, kRCX, ofsadjust + pArrayOpScript->m_fValLoc); 

            // get Array TypeHandle 
            // mov RDX, [RSP+offsetOfTypeHandle]                       

            X86EmitEspOffset(0x8b, kRDX,   ofsadjust
                                         + TransitionBlock::GetOffsetOfArgumentRegisters()
                                         + FIELD_OFFSET(ArgumentRegisters, THIS_REG));
                                 
            // mov RDX, [kArrayMTReg+offsetof(MethodTable, m_ElementType)]
            X86EmitIndexRegLoad(kRDX, kArrayMTReg, MethodTable::GetOffsetOfArrayElementTypeHandle());
            
#else
            X86EmitPushReg(kEDX);      // Save EDX
            X86EmitPushReg(kECX);      // Pass array object

            X86EmitIndexPush(kArrayMTReg, MethodTable::GetOffsetOfArrayElementTypeHandle()); // push [kArrayMTReg + m_ElementType] ; Array element type handle 

            // get address of value to store
            _ASSERTE(TransitionBlock::IsStackArgumentOffset(pArrayOpScript->m_fValLoc)); // on x86, value will never get a register
            X86EmitSPIndexPush(pArrayOpScript->m_fValLoc + ofsadjust + 3*sizeof(void*)); // push [ESP+offset] ; the object pointer

#endif //_AMD64
                        
          
            // emit a call to the fast helper            
            // One side effect of this is that we are going to generate a "jnz Epilog" and we DON'T need it 
            // in the fast path, however there are no side effects in emitting
            // it in the fast path anyway. the reason for that is that it makes
            // the cleanup code much easier ( we have only 1 place to cleanup the stack and
            // restore it to the original state )
            X86EmitCall(NewExternalCodeLabel((LPVOID)ObjIsInstanceOfNoGC), 0);
            X86EmitCmpRegImm32( kEAX, TypeHandle::CanCast); // CMP EAX, CanCast ; if ObjIsInstanceOfNoGC returns CanCast, we will go the fast path
            CodeLabel * Cleanup = NewCodeLabel();
            X86EmitCondJump(Cleanup, X86CondCode::kJZ);
                                               
#ifdef _TARGET_AMD64_
            // get address of value to store
            // lea rcx, [rsp+offs]
            X86EmitEspOffset(0x8d, kRCX,   ofsadjust + pArrayOpScript->m_fValLoc);

            // get address of 'this'/rcx
            // lea rdx, [rsp+offs]
            X86EmitEspOffset(0x8d, kRDX,   ofsadjust
                                         + TransitionBlock::GetOffsetOfArgumentRegisters()
                                         + FIELD_OFFSET(ArgumentRegisters, THIS_REG));

#else           
            // The stack is already setup correctly for the slow helper.            
            _ASSERTE(TransitionBlock::IsStackArgumentOffset(pArrayOpScript->m_fValLoc)); // on x86, value will never get a register
            X86EmitEspOffset(0x8d, kECX, pArrayOpScript->m_fValLoc + ofsadjust + 2*sizeof(void*));      // lea ECX, [ESP+offset]
            
            // get address of 'this'
            X86EmitEspOffset(0x8d, kEDX, 0);    // lea EDX, [ESP]       ; (address of ECX) 

            
#endif 
            AMD64_ONLY(_ASSERTE(fNeedScratchArea));
            X86EmitCall(NewExternalCodeLabel((LPVOID)ArrayStoreCheck), 0);
          
            EmitLabel(Cleanup);           
#ifdef _TARGET_AMD64_
            X86EmitEspOffset(0x8b, kRCX, 0x00 + ofsadjust + TransitionBlock::GetOffsetOfArgumentRegisters());
            X86EmitEspOffset(0x8b, kRDX, 0x08 + ofsadjust + TransitionBlock::GetOffsetOfArgumentRegisters());
            X86EmitEspOffset(0x8b, kR8, 0x10 + ofsadjust + TransitionBlock::GetOffsetOfArgumentRegisters());

            if (pArrayOpScript->m_rank >= 2)
                X86EmitEspOffset(0x8b, kR9, 0x18 + ofsadjust + TransitionBlock::GetOffsetOfArgumentRegisters());
#else
            X86EmitPopReg(kECX);        // restore regs
            X86EmitPopReg(kEDX);

            
            X86EmitR2ROp(0x3B, kEAX, kEAX);                             //   CMP EAX, EAX
            X86EmitCondJump(Epilog, X86CondCode::kJNZ);         // This branch never taken, but epilog walker uses it
#endif

            EmitLabel(CheckPassed);
        }
        else
        {
            _ASSERTE(pArrayOpScript->m_op == ArrayOpScript::LOADADDR);

            // Load up the hidden type parameter into 'typeReg'
            X86Reg typeReg = LoadArrayOpArg(pArrayOpScript->m_typeParamOffs, this, kEAX, ofsadjust);

            // 'typeReg' holds the typeHandle for the ARRAY.  This must be a ArrayTypeDesc*, so
            // mask off the low two bits to get the TypeDesc*
            X86EmitR2ROp(0x83, (X86Reg)4, typeReg);    //   AND typeReg, 0xFFFFFFFC
            Emit8(0xFC);

            // If 'typeReg' is NULL then we're executing the readonly ::Address and no type check is
            // needed.
            CodeLabel *Inner_passedTypeCheck = NewCodeLabel();

            X86EmitCondJump(Inner_passedTypeCheck, X86CondCode::kJZ);
            
            // Get the parameter of the parameterize type
            // mov typeReg, [typeReg.m_Arg]
            X86EmitOp(0x8b, typeReg, typeReg, offsetof(ParamTypeDesc, m_Arg) AMD64_ARG(k64BitOp));
            
            // Compare this against the element type of the array.
            // mov ESI/R10, [kArrayRefReg]
            X86EmitOp(0x8b, kArrayMTReg, kArrayRefReg, 0 AMD64_ARG(k64BitOp));
            // cmp typeReg, [ESI/R10+m_ElementType];
            X86EmitOp(0x3b, typeReg, kArrayMTReg, MethodTable::GetOffsetOfArrayElementTypeHandle() AMD64_ARG(k64BitOp));

            // Throw error if not equal
            Inner_typeMismatchexception = NewCodeLabel();
            X86EmitCondJump(Inner_typeMismatchexception, X86CondCode::kJNZ);
            EmitLabel(Inner_passedTypeCheck);
        }
    }

    CodeLabel* DoneCheckLabel = 0;
    if (pArrayOpScript->m_rank == 1 && pArrayOpScript->m_fHasLowerBounds)
    {
        DoneCheckLabel = NewCodeLabel();
        CodeLabel* NotSZArrayLabel = NewCodeLabel();

        // for rank1 arrays, we might actually have two different layouts depending on
        // if we are ELEMENT_TYPE_ARRAY or ELEMENT_TYPE_SZARRAY.

            // mov EAX, [ARRAY]          // EAX holds the method table
        X86_64BitOperands();
        X86EmitOp(0x8b, kEAX, kArrayRefReg);

            // test [EAX + m_dwFlags], enum_flag_Category_IfArrayThenSzArray
        X86_64BitOperands();
        X86EmitOffsetModRM(0xf7, (X86Reg)0, kEAX, MethodTable::GetOffsetOfFlags());
        Emit32(MethodTable::GetIfArrayThenSzArrayFlag());

            // jz NotSZArrayLabel
        X86EmitCondJump(NotSZArrayLabel, X86CondCode::kJZ);

            //Load the passed-in index into the scratch register.
        const ArrayOpIndexSpec *pai = pArrayOpScript->GetArrayOpIndexSpecs();
        X86Reg idxReg = LoadArrayOpArg(pai->m_idxloc, this, SCRATCH_REGISTER_X86REG, ofsadjust);

            // cmp idxReg, [kArrayRefReg + LENGTH]
        X86EmitOp(0x3b, idxReg, kArrayRefReg, ArrayBase::GetOffsetOfNumComponents());

            // jae Inner_rangeexception
        X86EmitCondJump(Inner_rangeexception, X86CondCode::kJAE);

            // <TODO> if we cared efficiency of this, this move can be optimized</TODO>
        X86EmitR2ROp(0x8b, kTotalReg, idxReg AMD64_ARG(k32BitOp));

            // sub ARRAY. 8                  // 8 is accounts for the Lower bound and Dim count in the ARRAY
        X86EmitSubReg(kArrayRefReg, 8);      // adjust this pointer so that indexing works out for SZARRAY

        X86EmitNearJump(DoneCheckLabel);
        EmitLabel(NotSZArrayLabel);
    }

    // For each index, range-check and mix into accumulated total.
    UINT idx = pArrayOpScript->m_rank;
    BOOL firstTime = TRUE;
    while (idx--)
    {
        const ArrayOpIndexSpec *pai = pArrayOpScript->GetArrayOpIndexSpecs() + idx;

        //Load the passed-in index into the scratch register.
        X86Reg srcreg = LoadArrayOpArg(pai->m_idxloc, this, SCRATCH_REGISTER_X86REG, ofsadjust AMD64_ARG(k32BitOp));
        if (SCRATCH_REGISTER_X86REG != srcreg)
            X86EmitR2ROp(0x8b, SCRATCH_REGISTER_X86REG, srcreg AMD64_ARG(k32BitOp));

        // sub SCRATCH, dword ptr [kArrayRefReg + LOWERBOUND]
        if (pArrayOpScript->m_fHasLowerBounds)
        {
            X86EmitOp(0x2b, SCRATCH_REGISTER_X86REG, kArrayRefReg, pai->m_lboundofs);
        }

        // cmp SCRATCH, dword ptr [kArrayRefReg + LENGTH]
        X86EmitOp(0x3b, SCRATCH_REGISTER_X86REG, kArrayRefReg, pai->m_lengthofs);

        // jae Inner_rangeexception
        X86EmitCondJump(Inner_rangeexception, X86CondCode::kJAE);


        // SCRATCH == idx - LOWERBOUND
        //
        // imul SCRATCH, FACTOR
        if (!firstTime)
        {
            //Can skip the first time since FACTOR==1
            X86EmitR2ROp(0xaf0f, SCRATCH_REGISTER_X86REG, kFactorReg AMD64_ARG(k32BitOp));
        }

        // TOTAL += SCRATCH
        if (firstTime)
        {
            // First time, we must zero-init TOTAL. Since
            // zero-initing and then adding is just equivalent to a
            // "mov", emit a "mov"
            //    mov  TOTAL, SCRATCH
            X86EmitR2ROp(0x8b, kTotalReg, SCRATCH_REGISTER_X86REG AMD64_ARG(k32BitOp));
        }
        else
        {
            //    add  TOTAL, SCRATCH
            X86EmitR2ROp(0x03, kTotalReg, SCRATCH_REGISTER_X86REG AMD64_ARG(k32BitOp));
        }

        // FACTOR *= [kArrayRefReg + LENGTH]
        if (idx != 0)
        {
            // No need to update FACTOR on the last iteration
            //  since we won't use it again

            if (firstTime)
            {
                // must init FACTOR to 1 first: hence,
                // the "imul" becomes a "mov"
                // mov FACTOR, [kArrayRefReg + LENGTH]
                X86EmitOp(0x8b, kFactorReg, kArrayRefReg, pai->m_lengthofs);
            }
            else
            {
                // imul FACTOR, [kArrayRefReg + LENGTH]
                X86EmitOp(0xaf0f, kFactorReg, kArrayRefReg, pai->m_lengthofs);
            }
        }

        firstTime = FALSE;
    }

    if (DoneCheckLabel != 0)
        EmitLabel(DoneCheckLabel);

    // Pass these values to X86EmitArrayOp() to generate the element address.
    X86Reg elemBaseReg   = kArrayRefReg;
    X86Reg elemScaledReg = kTotalReg;
    UINT32 elemSize      = pArrayOpScript->m_elemsize;
    UINT32 elemOfs       = pArrayOpScript->m_ofsoffirst;

    if (!(elemSize == 1 || elemSize == 2 || elemSize == 4 || elemSize == 8))
    {
        switch (elemSize)
        {
            // No way to express this as a SIB byte. Fold the scale
            // into TOTAL.

            case 16:
                // shl TOTAL,4
                X86EmitR2ROp(0xc1, (X86Reg)4, kTotalReg AMD64_ARG(k32BitOp));
                Emit8(4);
                break;

            case 32:
                // shl TOTAL,5
                X86EmitR2ROp(0xc1, (X86Reg)4, kTotalReg AMD64_ARG(k32BitOp));
                Emit8(5);
                break;

            case 64:
                // shl TOTAL,6
                X86EmitR2ROp(0xc1, (X86Reg)4, kTotalReg AMD64_ARG(k32BitOp));
                Emit8(6);
                break;

            default:
                // imul TOTAL, elemScale
                X86EmitR2ROp(0x69, kTotalReg, kTotalReg AMD64_ARG(k32BitOp));
                Emit32(elemSize);
                break;
        }
        elemSize = 1;
    }

    _ASSERTE(FitsInU1(elemSize));
    BYTE elemScale = static_cast<BYTE>(elemSize);

    // Now, do the operation:

    switch (pArrayOpScript->m_op)
    {
        case ArrayOpScript::LOADADDR:
            // lea eax, ELEMADDR
            X86EmitOp(0x8d, kEAX, elemBaseReg, elemOfs, elemScaledReg, elemScale AMD64_ARG(k64BitOp));
            break;

        case ArrayOpScript::LOAD:
            if (pArrayOpScript->m_flags & ArrayOpScript::HASRETVALBUFFER)
            {
                // Ensure that these registers have been saved!
                _ASSERTE(fSavedESI && fSavedEDI);

                //lea esi, ELEMADDR
                X86EmitOp(0x8d, kESI, elemBaseReg, elemOfs, elemScaledReg, elemScale AMD64_ARG(k64BitOp));

                _ASSERTE(!TransitionBlock::IsStackArgumentOffset(pArrayOpScript->m_fRetBufLoc));
                // mov edi, retbufptr
                X86EmitR2ROp(0x8b, kEDI, GetX86ArgumentRegisterFromOffset(pArrayOpScript->m_fRetBufLoc - TransitionBlock::GetOffsetOfArgumentRegisters()));

COPY_VALUE_CLASS:
                {
                    size_t size = pArrayOpScript->m_elemsize;
                    size_t total = 0;
                    if(pArrayOpScript->m_gcDesc)
                    {
                        CGCDescSeries* cur = pArrayOpScript->m_gcDesc->GetHighestSeries();
                        if ((cur->startoffset-elemOfs) > 0)
                            generate_noref_copy ((unsigned) (cur->startoffset - elemOfs), this);
                        total += cur->startoffset - elemOfs;

                        SSIZE_T cnt = (SSIZE_T) pArrayOpScript->m_gcDesc->GetNumSeries();
                        // special array encoding
                        _ASSERTE(cnt < 0);

                        for (SSIZE_T __i = 0; __i > cnt; __i--)
                        {
                            HALF_SIZE_T skip =  cur->val_serie[__i].skip;
                            HALF_SIZE_T nptrs = cur->val_serie[__i].nptrs;
                            total += nptrs*sizeof (DWORD*);
                            do
                            {
                                AMD64_ONLY(_ASSERTE(fNeedScratchArea));

                                X86EmitCall(NewExternalCodeLabel((LPVOID) JIT_ByRefWriteBarrier), 0);
                            } while (--nptrs);
                            if (skip > 0)
                            {
                                //check if we are at the end of the series
                                if (__i == (cnt + 1))
                                    skip = skip - (HALF_SIZE_T)(cur->startoffset - elemOfs);
                                if (skip > 0)
                                    generate_noref_copy (skip, this);
                            }
                            total += skip;
                        }

                        _ASSERTE (size == total);
                    }
                    else
                    {
                        // no ref anywhere, just copy the bytes.
                        _ASSERTE (size);
                        generate_noref_copy ((unsigned)size, this);
                    }
                }
            }
            else
            {
                switch (pArrayOpScript->m_elemsize)
                {
                case 1:
                    // mov[zs]x eax, byte ptr ELEMADDR
                    X86EmitOp(pArrayOpScript->m_signed ? 0xbe0f : 0xb60f, kEAX, elemBaseReg, elemOfs, elemScaledReg, elemScale);
                    break;

                case 2:
                    // mov[zs]x eax, word ptr ELEMADDR
                    X86EmitOp(pArrayOpScript->m_signed ? 0xbf0f : 0xb70f, kEAX, elemBaseReg, elemOfs, elemScaledReg, elemScale);
                    break;

                case 4:
                    if (pArrayOpScript->m_flags & ArrayOpScript::ISFPUTYPE)
                    {
#ifdef _TARGET_AMD64_
                        // movss xmm0, dword ptr ELEMADDR
                        Emit8(0xf3);
                        X86EmitOp(0x100f, (X86Reg)0, elemBaseReg, elemOfs, elemScaledReg, elemScale);
#else // !_TARGET_AMD64_
                        // fld dword ptr ELEMADDR
                        X86EmitOp(0xd9, (X86Reg)0, elemBaseReg, elemOfs, elemScaledReg, elemScale);
#endif // !_TARGET_AMD64_
                    }
                    else
                    {
                        // mov eax, ELEMADDR
                        X86EmitOp(0x8b, kEAX, elemBaseReg, elemOfs, elemScaledReg, elemScale);
                    }
                    break;

                case 8:
                    if (pArrayOpScript->m_flags & ArrayOpScript::ISFPUTYPE)
                    {
#ifdef _TARGET_AMD64_
                        // movsd xmm0, qword ptr ELEMADDR
                        Emit8(0xf2);
                        X86EmitOp(0x100f, (X86Reg)0, elemBaseReg, elemOfs, elemScaledReg, elemScale);
#else // !_TARGET_AMD64_
                        // fld qword ptr ELEMADDR
                        X86EmitOp(0xdd, (X86Reg)0, elemBaseReg, elemOfs, elemScaledReg, elemScale);
#endif // !_TARGET_AMD64_
                    }
                    else
                    {
                        // mov eax, ELEMADDR
                        X86EmitOp(0x8b, kEAX, elemBaseReg, elemOfs, elemScaledReg, elemScale AMD64_ARG(k64BitOp));
#ifdef _TARGET_X86_
                        // mov edx, ELEMADDR + 4
                        X86EmitOp(0x8b, kEDX, elemBaseReg, elemOfs + 4, elemScaledReg, elemScale);
#endif
                    }
                    break;

                default:
                    _ASSERTE(0);
                }
            }

            break;

        case ArrayOpScript::STORE:

            switch (pArrayOpScript->m_elemsize)
            {
            case 1:
                // mov SCRATCH, [esp + valoffset]
                kValueReg = LoadArrayOpArg(pArrayOpScript->m_fValLoc, this, SCRATCH_REGISTER_X86REG, ofsadjust);
                // mov byte ptr ELEMADDR, SCRATCH.b
                X86EmitOp(0x88, kValueReg, elemBaseReg, elemOfs, elemScaledReg, elemScale);
                break;
            case 2:
                // mov SCRATCH, [esp + valoffset]
                kValueReg = LoadArrayOpArg(pArrayOpScript->m_fValLoc, this, SCRATCH_REGISTER_X86REG, ofsadjust);
                // mov word ptr ELEMADDR, SCRATCH.w
                Emit8(0x66);
                X86EmitOp(0x89, kValueReg, elemBaseReg, elemOfs, elemScaledReg, elemScale);
                break;
            case 4:
#ifndef _TARGET_AMD64_
                if (pArrayOpScript->m_flags & ArrayOpScript::NEEDSWRITEBARRIER)
                {
                    // mov SCRATCH, [esp + valoffset]
                    kValueReg = LoadArrayOpArg(pArrayOpScript->m_fValLoc, this, SCRATCH_REGISTER_X86REG, ofsadjust);

                    _ASSERTE(SCRATCH_REGISTER_X86REG == kEAX); // value to store is already in EAX where we want it.
                    // lea edx, ELEMADDR
                    X86EmitOp(0x8d, kEDX, elemBaseReg, elemOfs, elemScaledReg, elemScale);

                    // call JIT_Writeable_Thunks_Buf.WriteBarrierReg[0] (== EAX)
                    X86EmitCall(NewExternalCodeLabel((LPVOID) &JIT_WriteBarrierEAX), 0);
                }
                else
#else // _TARGET_AMD64_
                if (pArrayOpScript->m_flags & ArrayOpScript::ISFPUTYPE)
                {
                    if (!TransitionBlock::IsStackArgumentOffset(pArrayOpScript->m_fValLoc))
                    {
                        kValueReg = (X86Reg)TransitionBlock::GetArgumentIndexFromOffset(pArrayOpScript->m_fValLoc);
                    }
                    else
                    {
                        kValueReg = (X86Reg)0;  // xmm0

                        // movss xmm0, dword ptr [rsp+??]
                        Emit8(0xf3);
                        X86EmitOp(0x100f, kValueReg, (X86Reg)4 /*rsp*/, ofsadjust + pArrayOpScript->m_fValLoc);
                    }

                    // movss dword ptr ELEMADDR, xmm?
                    Emit8(0xf3);
                    X86EmitOp(0x110f, kValueReg, elemBaseReg, elemOfs, elemScaledReg, elemScale);
                }
                else
#endif // _TARGET_AMD64_
                {
                    // mov SCRATCH, [esp + valoffset]
                    kValueReg = LoadArrayOpArg(pArrayOpScript->m_fValLoc, this, SCRATCH_REGISTER_X86REG, ofsadjust AMD64_ARG(k32BitOp));

                    // mov ELEMADDR, SCRATCH
                    X86EmitOp(0x89, kValueReg, elemBaseReg, elemOfs, elemScaledReg, elemScale);
                }
                break;

            case 8:

                if (!(pArrayOpScript->m_flags & ArrayOpScript::NEEDSWRITEBARRIER))
                {
#ifdef _TARGET_AMD64_
                    if (pArrayOpScript->m_flags & ArrayOpScript::ISFPUTYPE)
                    {
                        if (!TransitionBlock::IsStackArgumentOffset(pArrayOpScript->m_fValLoc))
                        {
                            kValueReg = (X86Reg)TransitionBlock::GetArgumentIndexFromOffset(pArrayOpScript->m_fValLoc);
                        }
                        else
                        {
                            kValueReg = (X86Reg)0;  // xmm0

                            // movsd xmm0, qword ptr [rsp+??]
                            Emit8(0xf2);
                            X86EmitOp(0x100f, kValueReg, (X86Reg)4 /*rsp*/, ofsadjust + pArrayOpScript->m_fValLoc);
                        }

                        // movsd qword ptr ELEMADDR, xmm?
                        Emit8(0xf2);
                        X86EmitOp(0x110f, kValueReg, elemBaseReg, elemOfs, elemScaledReg, elemScale);
                    }
                    else
                    {
                    // mov SCRATCH, [esp + valoffset]
                        kValueReg = LoadArrayOpArg(pArrayOpScript->m_fValLoc, this, SCRATCH_REGISTER_X86REG, ofsadjust);

                        // mov ELEMADDR, SCRATCH
                        X86EmitOp(0x89, kValueReg, elemBaseReg, elemOfs, elemScaledReg, elemScale, k64BitOp);
                    }
#else // !_TARGET_AMD64_
                    _ASSERTE(TransitionBlock::IsStackArgumentOffset(pArrayOpScript->m_fValLoc)); // on x86, value will never get a register: so too lazy to implement that case
                    // mov SCRATCH, [esp + valoffset]
                    X86EmitEspOffset(0x8b, SCRATCH_REGISTER_X86REG, pArrayOpScript->m_fValLoc + ofsadjust);
                    // mov ELEMADDR, SCRATCH
                    X86EmitOp(0x89, SCRATCH_REGISTER_X86REG, elemBaseReg, elemOfs, elemScaledReg, elemScale);

                    _ASSERTE(TransitionBlock::IsStackArgumentOffset(pArrayOpScript->m_fValLoc)); // on x86, value will never get a register: so too lazy to implement that case
                    // mov SCRATCH, [esp + valoffset + 4]
                    X86EmitEspOffset(0x8b, SCRATCH_REGISTER_X86REG, pArrayOpScript->m_fValLoc + ofsadjust + 4);
                    // mov ELEMADDR+4, SCRATCH
                    X86EmitOp(0x89, SCRATCH_REGISTER_X86REG, elemBaseReg, elemOfs+4, elemScaledReg, elemScale);
#endif // !_TARGET_AMD64_
                    break;
                }
#ifdef _TARGET_AMD64_
                else
                {
                    _ASSERTE(SCRATCH_REGISTER_X86REG == kEAX); // value to store is already in EAX where we want it.
                    // lea rcx, ELEMADDR
                    X86EmitOp(0x8d, kRCX, elemBaseReg, elemOfs, elemScaledReg, elemScale, k64BitOp);

                    // mov rdx, [rsp + valoffset]
                    kValueReg = LoadArrayOpArg(pArrayOpScript->m_fValLoc, this, kRDX, ofsadjust);
                    _ASSERT(kRCX != kValueReg);
                    if (kRDX != kValueReg)
                        X86EmitR2ROp(0x8b, kRDX, kValueReg);

                    _ASSERTE(fNeedScratchArea);
                    X86EmitCall(NewExternalCodeLabel((PVOID)JIT_WriteBarrier), 0);
                    break;
                }
#endif // _TARGET_AMD64_
                    // FALL THROUGH (on x86)
            default:
                // Ensure that these registers have been saved!
                _ASSERTE(fSavedESI && fSavedEDI);

#ifdef _TARGET_AMD64_
                // mov rsi, [rsp + valoffset]
                kValueReg = LoadArrayOpArg(pArrayOpScript->m_fValLoc, this, kRSI, ofsadjust);
                if (kRSI != kValueReg)
                    X86EmitR2ROp(0x8b, kRSI, kValueReg);
#else // !_TARGET_AMD64_
                _ASSERTE(TransitionBlock::IsStackArgumentOffset(pArrayOpScript->m_fValLoc));
                // lea esi, [esp + valoffset]
                X86EmitEspOffset(0x8d, kESI, pArrayOpScript->m_fValLoc + ofsadjust);
#endif // !_TARGET_AMD64_

                // lea edi, ELEMADDR
                X86EmitOp(0x8d, kEDI, elemBaseReg, elemOfs, elemScaledReg, elemScale AMD64_ARG(k64BitOp));
                goto COPY_VALUE_CLASS;
            }
            break;

        default:
            _ASSERTE(0);
    }

    EmitLabel(Epilog);

#ifdef _TARGET_AMD64_
    if (fNeedPrologue)
    {
        if (fNeedScratchArea)
        {
            // Throw away scratch area
            X86EmitAddEsp(sizeof(ArgumentRegisters) + 0x8);
        }

        if (fSavedEDI)
            X86EmitPopReg(kRDI);

        if (fSavedESI)
            X86EmitPopReg(kRSI);
    }

    X86EmitReturn(0);
#else // !_TARGET_AMD64_
    // Restore the callee-saved registers
    X86EmitPopReg(kFactorReg);
    X86EmitPopReg(kTotalReg);

#ifndef UNIX_X86_ABI
    // ret N
    X86EmitReturn(pArrayOpScript->m_cbretpop);
#else
    X86EmitReturn(0);
#endif
#endif // !_TARGET_AMD64_

    // Exception points must clean up the stack for all those extra args.
    // kFactorReg and kTotalReg will be popped by the jump targets.

    void *pvExceptionThrowFn;

#if defined(_TARGET_AMD64_)
#define ARRAYOP_EXCEPTION_HELPERS(base)      { (PVOID)base, (PVOID)base##_RSIRDI, (PVOID)base##_ScratchArea, (PVOID)base##_RSIRDI_ScratchArea }
 static void *rgNullExceptionHelpers[]           = ARRAYOP_EXCEPTION_HELPERS(ArrayOpStubNullException);
    static void *rgRangeExceptionHelpers[]          = ARRAYOP_EXCEPTION_HELPERS(ArrayOpStubRangeException);
    static void *rgTypeMismatchExceptionHelpers[]   = ARRAYOP_EXCEPTION_HELPERS(ArrayOpStubTypeMismatchException);
#undef ARRAYOP_EXCEPTION_HELPERS

    UINT iExceptionHelper = (fNeedRSIRDI ? 1 : 0) + (fNeedScratchArea ? 2 : 0);
#endif // defined(_TARGET_AMD64_)

    EmitLabel(Inner_nullexception);

#ifndef _TARGET_AMD64_
    pvExceptionThrowFn = (LPVOID)ArrayOpStubNullException;

    Emit8(0xb8);        // mov EAX, <stack cleanup>
    Emit32(pArrayOpScript->m_cbretpop);
#else //_TARGET_AMD64_
    pvExceptionThrowFn = rgNullExceptionHelpers[iExceptionHelper];
#endif //!_TARGET_AMD64_
    X86EmitNearJump(NewExternalCodeLabel(pvExceptionThrowFn));

    EmitLabel(Inner_rangeexception);
#ifndef _TARGET_AMD64_
    pvExceptionThrowFn = (LPVOID)ArrayOpStubRangeException;
    Emit8(0xb8);        // mov EAX, <stack cleanup>
    Emit32(pArrayOpScript->m_cbretpop);
#else //_TARGET_AMD64_
    pvExceptionThrowFn = rgRangeExceptionHelpers[iExceptionHelper];
#endif //!_TARGET_AMD64_
    X86EmitNearJump(NewExternalCodeLabel(pvExceptionThrowFn));

    if (Inner_typeMismatchexception != NULL)
    {
        EmitLabel(Inner_typeMismatchexception);
#ifndef _TARGET_AMD64_
        pvExceptionThrowFn = (LPVOID)ArrayOpStubTypeMismatchException;
        Emit8(0xb8);        // mov EAX, <stack cleanup>
        Emit32(pArrayOpScript->m_cbretpop);
#else //_TARGET_AMD64_
        pvExceptionThrowFn = rgTypeMismatchExceptionHelpers[iExceptionHelper];
#endif //!_TARGET_AMD64_
        X86EmitNearJump(NewExternalCodeLabel(pvExceptionThrowFn));
    }
}
#ifdef _PREFAST_
#pragma warning(pop)
#endif

#endif // !CROSSGEN_COMPILE && !FEATURE_ARRAYSTUB_AS_IL

#if !defined(CROSSGEN_COMPILE) && !defined(FEATURE_STUBS_AS_IL)
//===========================================================================
// Emits code to break into debugger
VOID StubLinkerCPU::EmitDebugBreak()
{
    STANDARD_VM_CONTRACT;

    // int3
    Emit8(0xCC);
}

#if defined(FEATURE_COMINTEROP) && defined(_TARGET_X86_)

#ifdef _MSC_VER
#pragma warning(push)
#pragma warning (disable : 4740) // There is inline asm code in this function, which disables
                                 // global optimizations.
#pragma warning (disable : 4731)
#endif  // _MSC_VER
Thread* __stdcall CreateThreadBlockReturnHr(ComMethodFrame *pFrame)
{

    WRAPPER_NO_CONTRACT;

    Thread *pThread = NULL;

    HRESULT hr = S_OK;

    // This means that a thread is FIRST coming in from outside the EE.
    BEGIN_ENTRYPOINT_THROWS;
    pThread = SetupThreadNoThrow(&hr);
    END_ENTRYPOINT_THROWS;

    if (pThread == NULL) {
        // Unwind stack, and return hr
        // NOTE: assumes __stdcall
        // Note that this code does not handle the rare COM signatures that do not return HRESULT
        // compute the callee pop stack bytes
        UINT numArgStackBytes = pFrame->GetNumCallerStackBytes();
        unsigned frameSize = sizeof(Frame) + sizeof(LPVOID);
        LPBYTE iEsp = ((LPBYTE)pFrame) + ComMethodFrame::GetOffsetOfCalleeSavedRegisters();
        __asm
        {
            mov eax, hr
            mov edx, numArgStackBytes
            //*****************************************
            // reset the stack pointer
            // none of the locals above can be used in the asm below
            // if we wack the stack pointer
            mov esp, iEsp
            // pop callee saved registers
            pop edi
            pop esi
            pop ebx
            pop ebp
            pop ecx         ; //return address
            // pop the callee cleanup stack args
            add esp, edx    ;// callee cleanup of args
            jmp ecx;        // jump to the address to continue execution

            // We will never get here. This "ret" is just so that code-disassembling
            // profilers know to stop disassembling any further
            ret
        }
    }

    return pThread;
}
#if defined(_MSC_VER)
#pragma warning(pop)
#endif

#endif // FEATURE_COMINTEROP && _TARGET_X86_

#endif // !CROSSGEN_COMPILE && !FEATURE_STUBS_AS_IL

#endif // !DACCESS_COMPILE


#ifdef _TARGET_AMD64_

//
// TailCallFrame Object Scanning
//
// This handles scanning/promotion of GC objects that were
// protected by the TailCallHelper routine.  Note that the objects
// being protected is somewhat dynamic and is dependent upon the
// the callee...
//

void TailCallFrame::GcScanRoots(promote_func *fn, ScanContext* sc)
{
    WRAPPER_NO_CONTRACT;

    if (m_pGCLayout != NULL)
    {
        struct FrameOffsetDecoder {
        private:
            TADDR prevOffset;
            TADDR rangeEnd;
            BOOL   maybeInterior;
            BOOL   atEnd;
            PTR_SBYTE pbOffsets;

            DWORD ReadNumber() {
                signed char i;
                DWORD offset = 0;
                while ((i = *pbOffsets++) >= 0) 
                {
                    offset = (offset << 7) | i;
                }
                offset = (offset << 7) | (i & 0x7F);
                return offset;
            }

        public:
            FrameOffsetDecoder(PTR_GSCookie _base, TADDR offsets)
                : prevOffset(dac_cast<TADDR>(_base)), rangeEnd(~0LL), atEnd(FALSE), pbOffsets(dac_cast<PTR_SBYTE>(offsets)) { maybeInterior = FALSE;}

            bool MoveNext() {
                LIMITED_METHOD_CONTRACT;

                if (rangeEnd < prevOffset)
                {
                    prevOffset -= sizeof(void*);
                    return true;
                }
                if (atEnd) return false;
                DWORD offset = ReadNumber();
                atEnd = (offset & 1);
                BOOL range = (offset & 2);
                maybeInterior = (offset & 0x80000000);

                offset &= 0x7FFFFFFC;
                
#ifdef _WIN64
                offset <<= 1;
#endif
                offset += sizeof(void*);
                _ASSERTE(prevOffset > offset);
                prevOffset -= offset;

                if (range)
                {
                    _ASSERTE(!atEnd);
                    _ASSERTE(!maybeInterior);
                    DWORD offsetEnd = ReadNumber();
                    atEnd = (offsetEnd & 1);
                    offsetEnd = (offsetEnd & ~1) << 1;
                    // range encoding starts with a range of 3 (2 is better to encode as
                    // 2 offsets), so 0 == 2 (the last offset in the range)
                    offsetEnd += sizeof(void*) * 2;
                    rangeEnd = prevOffset - offsetEnd;
                }

                return true;
            }

            BOOL MaybeInterior() const { return maybeInterior; }

            PTR_PTR_Object Current() const { return PTR_PTR_Object(prevOffset); }

        } decoder(GetGSCookiePtr(), m_pGCLayout);

        while (decoder.MoveNext())
        {
            PTR_PTR_Object ppRef = decoder.Current();

            LOG((LF_GC, INFO3, "Tail Call Frame Promoting" FMT_ADDR "to",
                 DBG_ADDR(OBJECTREF_TO_UNCHECKED_OBJECTREF(*ppRef)) ));
            if (decoder.MaybeInterior())
                PromoteCarefully(fn, ppRef, sc, GC_CALL_INTERIOR|CHECK_APP_DOMAIN);
            else
                (*fn)(ppRef, sc, 0);
            LOG((LF_GC, INFO3, FMT_ADDR "\n", DBG_ADDR(OBJECTREF_TO_UNCHECKED_OBJECTREF(*ppRef)) ));
        }
    }
}

#ifndef DACCESS_COMPILE
static void EncodeOneGCOffset(CPUSTUBLINKER *pSl, ULONG delta, BOOL maybeInterior, BOOL range, BOOL last)
{
    CONTRACTL
    {
        THROWS; // From the stublinker
        MODE_ANY;
        GC_NOTRIGGER;
    }
    CONTRACTL_END;

    // Everything should be pointer aligned
    // but we use a high bit for interior, and the 0 bit to denote the end of the list
    // we use the 1 bit to denote a range
    _ASSERTE((delta % sizeof(void*)) == 0);

#if defined(_WIN64)
    // For 64-bit, we have 3 bits of alignment, so we allow larger frames
    // by shifting and gaining a free high-bit.
    ULONG encodedDelta = delta >> 1;
#else
    // For 32-bit, we just limit our frame size to <2GB.
    ULONG encodedDelta = delta;
#endif
    _ASSERTE((encodedDelta & 0x80000003) == 0);
    if (last)
    {
        encodedDelta |= 1;
    }

    if (range)
    {
        encodedDelta |= 2;
    }
    else if (maybeInterior)
    {
        _ASSERTE(!range);
        encodedDelta |= 0x80000000;
    }

    BYTE bytes[5];
    UINT index = 5;
    bytes[--index] = (BYTE)((encodedDelta & 0x7F) | 0x80);
    encodedDelta >>= 7;
    while (encodedDelta > 0)
    {
        bytes[--index] = (BYTE)(encodedDelta & 0x7F);
        encodedDelta >>= 7;
    }
    pSl->EmitBytes(&bytes[index], 5 - index);
}

static void EncodeGCOffsets(CPUSTUBLINKER *pSl, /* const */ ULONGARRAY & gcOffsets)
{
    CONTRACTL
    {
        THROWS;
        MODE_ANY;
        GC_NOTRIGGER;
    }
    CONTRACTL_END;

    _ASSERTE(gcOffsets.Count() > 0);

    ULONG prevOffset = 0;
    int i = 0;
    BOOL last = FALSE;
    do {
        ULONG offset = gcOffsets[i];
        // Everything should be pointer aligned
        // but we use the 0-bit to mean maybeInterior, for byrefs.
        _ASSERTE(((offset % sizeof(void*)) == 0) || ((offset % sizeof(void*)) == 1));
        BOOL maybeInterior = (offset & 1);
        offset &= ~1;

        // Encode just deltas because they're smaller (and the list should be sorted)
        _ASSERTE(offset >= (prevOffset + sizeof(void*)));
        ULONG delta = offset - (prevOffset + sizeof(void*));
        if (!maybeInterior && gcOffsets.Count() > i + 2)
        {
            // Check for a potential range.
            // Only do it if we have 3 or more pointers in a row
            ULONG rangeOffset = offset;
            int j = i + 1;
            do {
                ULONG nextOffset = gcOffsets[j];
                // interior pointers can't be in ranges
                if (nextOffset & 1)
                     break;
                // ranges must be saturated
                if (nextOffset != (rangeOffset + sizeof(void*)))
                     break;
                j++;
                rangeOffset = nextOffset;
            } while(j < gcOffsets.Count());

            if (j > (i + 2))
            {
                EncodeOneGCOffset(pSl, delta, FALSE, TRUE, last); 
                i = j - 1;
                _ASSERTE(rangeOffset >= (offset + (sizeof(void*) * 2)));
                delta = rangeOffset - (offset + (sizeof(void*) * 2));
                offset = rangeOffset;
            }
        }
        last = (++i == gcOffsets.Count());


        EncodeOneGCOffset(pSl, delta, maybeInterior, FALSE, last); 

        prevOffset = offset;
    } while (!last);
}

static void AppendGCLayout(ULONGARRAY &gcLayout, size_t baseOffset, BOOL fIsTypedRef, TypeHandle VMClsHnd)
{
    STANDARD_VM_CONTRACT;

    _ASSERTE((baseOffset % 16) == 0);
    _ASSERTE(FitsInU4(baseOffset));

    if (fIsTypedRef)
    {
        *gcLayout.AppendThrowing() = (ULONG)(baseOffset | 1); // "| 1" to mark it as an interior pointer
    }
    else if (!VMClsHnd.IsNativeValueType())
    {
        MethodTable* pMT = VMClsHnd.GetMethodTable();
        _ASSERTE(pMT);
        _ASSERTE(pMT->IsValueType());

        BOOL isByRefLike = pMT->IsByRefLike();
        if (isByRefLike)
        {
            FindByRefPointerOffsetsInByRefLikeObject(
                pMT,
                0 /* baseOffset */,
                [&](size_t pointerOffset)
                {
                    // 'gcLayout' requires stack offsets relative to the top of the stack to be recorded, such that subtracting
                    // the offset from the stack top yields the address of the field, given that subtracting 'baseOffset' from
                    // the stack top yields the address of the first field in this struct. See TailCallFrame::GcScanRoots() for
                    // how these offsets are used to calculate stack addresses for fields.
                    _ASSERTE(pointerOffset < baseOffset);
                    size_t stackOffsetFromTop = baseOffset - pointerOffset;
                    _ASSERTE(FitsInU4(stackOffsetFromTop));

                    // Offsets in 'gcLayout' are expected to be in increasing order
                    int gcLayoutInsertIndex = gcLayout.Count();
                    _ASSERTE(gcLayoutInsertIndex >= 0);
                    for (; gcLayoutInsertIndex != 0; --gcLayoutInsertIndex)
                    {
                        ULONG prevStackOffsetFromTop = gcLayout[gcLayoutInsertIndex - 1] & ~(ULONG)1;
                        if (stackOffsetFromTop > prevStackOffsetFromTop)
                        {
                            break;
                        }
                        if (stackOffsetFromTop == prevStackOffsetFromTop)
                        {
                            return;
                        }
                    }

                    _ASSERTE(gcLayout.Count() == 0 || stackOffsetFromTop > (gcLayout[gcLayout.Count() - 1] & ~(ULONG)1));
                    *gcLayout.InsertThrowing(gcLayoutInsertIndex) = (ULONG)(stackOffsetFromTop | 1); // "| 1" to mark it as an interior pointer
                });
        }

        // walk the GC descriptors, reporting the correct offsets
        if (pMT->ContainsPointers())
        {
            // size of instance when unboxed must be adjusted for the syncblock
            // index and the VTable pointer.
            DWORD       size = pMT->GetBaseSize();

            // we don't include this term in our 'ppstop' calculation below.
            _ASSERTE(pMT->GetComponentSize() == 0);

            CGCDesc* map = CGCDesc::GetCGCDescFromMT(pMT);
            CGCDescSeries* cur = map->GetLowestSeries();
            CGCDescSeries* last = map->GetHighestSeries();

            _ASSERTE(cur <= last);
            do
            {
                // offset to embedded references in this series must be
                // adjusted by the VTable pointer, when in the unboxed state.
                size_t   adjustOffset = cur->GetSeriesOffset() - sizeof(void *);

                _ASSERTE(baseOffset >= adjustOffset);
                size_t start = baseOffset - adjustOffset;
                size_t stop = start - (cur->GetSeriesSize() + size);
                for (size_t off = stop + sizeof(void*); off <= start; off += sizeof(void*))
                {
                    _ASSERTE(FitsInU4(off));

                    int gcLayoutInsertIndex = gcLayout.Count();
                    _ASSERTE(gcLayoutInsertIndex >= 0);
                    if (isByRefLike)
                    {
                        // Offsets in 'gcLayout' are expected to be in increasing order and for by-ref-like types the by-refs would
                        // have already been inserted into 'gcLayout' above. Find the appropriate index at which to insert this
                        // offset.
                        while (gcLayoutInsertIndex != 0 && off < gcLayout[gcLayoutInsertIndex - 1])
                        {
                            --gcLayoutInsertIndex;
                            _ASSERTE(off != (gcLayout[gcLayoutInsertIndex] & ~(ULONG)1));
                        }
                    }

                    _ASSERTE(gcLayoutInsertIndex == 0 || off > (gcLayout[gcLayoutInsertIndex - 1] & ~(ULONG)1));
                    *gcLayout.InsertThrowing(gcLayoutInsertIndex) = (ULONG)off;
                }
                cur++;

            } while (cur <= last);
        }
    }
}

Stub * StubLinkerCPU::CreateTailCallCopyArgsThunk(CORINFO_SIG_INFO * pSig,
                                                  MethodDesc* pMD,
                                                  CorInfoHelperTailCallSpecialHandling flags)
{
    STANDARD_VM_CONTRACT;

    CPUSTUBLINKER   sl;
    CPUSTUBLINKER*  pSl = &sl;

    // Generates a function that looks like this:
    // size_t CopyArguments(va_list args,         (RCX)
    //                      CONTEXT *pCtx,        (RDX)
    //                      DWORD64 *pvStack,     (R8)
    //                      size_t cbStack)       (R9)
    // {
    //     if (pCtx != NULL) {
    //         foreach (arg in args) {
    //             copy into pCtx or pvStack
    //         }
    //     }
    //     return <size of stack needed>;
    // }
    //

    CodeLabel *pNullLabel = pSl->NewCodeLabel();

    // test rdx, rdx
    pSl->X86EmitR2ROp(0x85, kRDX, kRDX);

    // jz NullLabel
    pSl->X86EmitCondJump(pNullLabel, X86CondCode::kJZ);

    UINT nArgSlot = 0;
    UINT totalArgs = pSig->totalILArgs() + ((pSig->isVarArg() || pSig->hasTypeArg()) ? 1 : 0);
    bool fR10Loaded = false;
    UINT cbArg;
    static const UINT rgcbArgRegCtxtOffsets[4] = { offsetof(CONTEXT, Rcx), offsetof(CONTEXT, Rdx),
                                                   offsetof(CONTEXT, R8), offsetof(CONTEXT, R9) };
    static const UINT rgcbFpArgRegCtxtOffsets[4] = { offsetof(CONTEXT, Xmm0.Low), offsetof(CONTEXT, Xmm1.Low),
                                                     offsetof(CONTEXT, Xmm2.Low), offsetof(CONTEXT, Xmm3.Low) };

    ULONGARRAY gcLayout;

    // On input to the function R9 contains the size of the buffer
    // The first time this macro runs, R10 is loaded with the 'top' of the Frame
    // and R9 is changed to point to the 'top' of the copy buffer.
    // Then both R9 and R10 are decremented by the size of the struct we're copying
    // So R10 is the value to put in the argument slot, and R9 is where the data
    // should be copied to (or zeroed out in the case of the return buffer).
#define LOAD_STRUCT_OFFSET_IF_NEEDED(cbSize)                                      \
    {                                                                             \
        _ASSERTE(cbSize > 0);                                                     \
        _ASSERTE(FitsInI4(cbSize));                                               \
        __int32 offset = (__int32)cbSize;                                         \
        if (!fR10Loaded) {                                                        \
            /* mov r10, [rdx + offset of RSP] */                                  \
            pSl->X86EmitIndexRegLoad(kR10, kRDX, offsetof(CONTEXT, Rsp));         \
            /* add an extra 8 because RSP is pointing at the return address */    \
            offset -= 8;                                                          \
            /* add r10, r9 */                                                     \
            pSl->X86EmitAddRegReg(kR10, kR9);                                     \
            /* add r9, r8 */                                                      \
            pSl->X86EmitAddRegReg(kR9, kR8);                                      \
            fR10Loaded = true;                                                    \
        }                                                                         \
        /* sub r10, offset */                                                     \
        pSl->X86EmitSubReg(kR10, offset);                                         \
        /* sub r9, cbSize */                                                      \
        pSl->X86EmitSubReg(kR9, cbSize);                                          \
    }


    if (flags & CORINFO_TAILCALL_STUB_DISPATCH_ARG) {
        // This is set for stub dispatch
        // The JIT placed an extra argument in the list that needs to
        // get shoved into R11, and not counted.
        // pCtx->R11 = va_arg(args, DWORD64);

        // mov rax, [rcx]
        pSl->X86EmitIndexRegLoad(kRAX, kRCX, 0);
        // add rcx, 8
        pSl->X86EmitAddReg(kRCX, 8);
        // mov [rdx + offset of R11], rax
        pSl->X86EmitIndexRegStore(kRDX, offsetof(CONTEXT, R11), kRAX);
    }

    ULONG cbStructOffset = 0;

    // First comes the 'this' pointer
    if (pSig->hasThis()) {
        // mov rax, [rcx]
        pSl->X86EmitIndexRegLoad(kRAX, kRCX, 0);
        // add rcx, 8
        pSl->X86EmitAddReg(kRCX, 8);
        // mov [rdx + offset of RCX/RDX], rax
        pSl->X86EmitIndexRegStore(kRDX, rgcbArgRegCtxtOffsets[nArgSlot++], kRAX);
    }

    // Next the return buffer
    cbArg = 0;
    TypeHandle th(pSig->retTypeClass);
    if ((pSig->retType == CORINFO_TYPE_REFANY) || (pSig->retType == CORINFO_TYPE_VALUECLASS)) {
        cbArg = th.GetSize();
    }

    if (ArgIterator::IsArgPassedByRef(cbArg)) {
        totalArgs++;

        // We always reserve space for the return buffer, and we always zero it out,
        // so the GC won't complain, but if it's already pointing above the frame,
        // then we need to pass it in (so it will get passed out).
        // Otherwise we assume the caller is returning void, so we just pass in
        // dummy space to be overwritten.
        UINT cbUsed = (cbArg + 0xF) & ~0xF;
        LOAD_STRUCT_OFFSET_IF_NEEDED(cbUsed);
        // now emit a 'memset(r9, 0, cbUsed)'
        {
            // xorps xmm0, xmm0
            pSl->X86EmitR2ROp(X86_INSTR_XORPS, kXMM0, kXMM0);
            if (cbUsed <= 4 * 16) {
                // movaps [r9], xmm0
                pSl->X86EmitOp(X86_INSTR_MOVAPS_RM_R, kXMM0, kR9, 0);
                if (16 < cbUsed) {
                    // movaps [r9 + 16], xmm0
                    pSl->X86EmitOp(X86_INSTR_MOVAPS_RM_R, kXMM0, kR9, 16);
                    if (32 < cbUsed) {
                        // movaps [r9 + 32], xmm0
                        pSl->X86EmitOp(X86_INSTR_MOVAPS_RM_R, kXMM0, kR9, 32);
                        if (48 < cbUsed) {
                            // movaps [r9 + 48], xmm0
                            pSl->X86EmitOp(X86_INSTR_MOVAPS_RM_R, kXMM0, kR9, 48);
                        }
                    }
                }
            }
            else {
                // a loop (one double-quadword at a time)
                pSl->X86EmitZeroOutReg(kR11);
                // LoopLabel:
                CodeLabel *pLoopLabel = pSl->NewCodeLabel();
                pSl->EmitLabel(pLoopLabel);
                // movaps [r9 + r11], xmm0
                pSl->X86EmitOp(X86_INSTR_MOVAPS_RM_R, kXMM0, kR9, 0, kR11, 1);
                // add r11, 16
                pSl->X86EmitAddReg(kR11, 16);
                // cmp r11, cbUsed
                pSl->X86EmitCmpRegImm32(kR11, cbUsed);
                // jl LoopLabel
                pSl->X86EmitCondJump(pLoopLabel, X86CondCode::kJL);
            }
        }
        cbStructOffset += cbUsed;
        AppendGCLayout(gcLayout, cbStructOffset, pSig->retType == CORINFO_TYPE_REFANY, th);

        // mov rax, [rcx]
        pSl->X86EmitIndexRegLoad(kRAX, kRCX, 0);
        // add rcx, 8
        pSl->X86EmitAddReg(kRCX, 8);
        // cmp rax, [rdx + offset of R12]
        pSl->X86EmitOffsetModRM(0x3B, kRAX, kRDX, offsetof(CONTEXT, R12));

        CodeLabel *pSkipLabel = pSl->NewCodeLabel();
        // jnb SkipLabel
        pSl->X86EmitCondJump(pSkipLabel, X86CondCode::kJNB);

        // Also check the lower bound of the stack in case the return buffer is on the GC heap
        // and the GC heap is below the stack
        // cmp rax, rsp
        pSl->X86EmitR2ROp(0x3B, kRAX, (X86Reg)4 /*kRSP*/);
        // jna SkipLabel
        pSl->X86EmitCondJump(pSkipLabel, X86CondCode::kJB);
        // mov rax, r10
        pSl->X86EmitMovRegReg(kRAX, kR10);
        // SkipLabel:
        pSl->EmitLabel(pSkipLabel);
        // mov [rdx + offset of RCX], rax
        pSl->X86EmitIndexRegStore(kRDX, rgcbArgRegCtxtOffsets[nArgSlot++], kRAX);
    }

    // VarArgs Cookie *or* Generics Instantiation Parameter
    if (pSig->hasTypeArg() || pSig->isVarArg()) {
        // mov rax, [rcx]
        pSl->X86EmitIndexRegLoad(kRAX, kRCX, 0);
        // add rcx, 8
        pSl->X86EmitAddReg(kRCX, 8);
        // mov [rdx + offset of RCX/RDX], rax
        pSl->X86EmitIndexRegStore(kRDX, rgcbArgRegCtxtOffsets[nArgSlot++], kRAX);
    }

    _ASSERTE(nArgSlot <= 4);

    // Now for *all* the 'real' arguments
    SigPointer ptr((PCCOR_SIGNATURE)pSig->args);
    Module * module = GetModule(pSig->scope);
    Instantiation classInst((TypeHandle*)pSig->sigInst.classInst, pSig->sigInst.classInstCount);
    Instantiation methodInst((TypeHandle*)pSig->sigInst.methInst, pSig->sigInst.methInstCount);
    SigTypeContext typeCtxt(classInst, methodInst);

    for( ;nArgSlot < totalArgs; ptr.SkipExactlyOne()) {
        CorElementType et = ptr.PeekElemTypeNormalized(module, &typeCtxt);
        if (et == ELEMENT_TYPE_SENTINEL)
            continue;

        // mov rax, [rcx]
        pSl->X86EmitIndexRegLoad(kRAX, kRCX, 0);
        // add rcx, 8
        pSl->X86EmitAddReg(kRCX, 8);
        switch (et) {
        case ELEMENT_TYPE_INTERNAL:
            // TODO
            _ASSERTE(!"Shouldn't see ELEMENT_TYPE_INTERNAL");
            break;
        case ELEMENT_TYPE_TYPEDBYREF:
        case ELEMENT_TYPE_VALUETYPE:
            th = ptr.GetTypeHandleThrowing(module, &typeCtxt, ClassLoader::LoadTypes, CLASS_LOAD_UNRESTOREDTYPEKEY);
            _ASSERTE(!th.IsNull());
            g_IBCLogger.LogEEClassAndMethodTableAccess(th.GetMethodTable());
            cbArg = (UINT)th.GetSize();
            if (ArgIterator::IsArgPassedByRef(cbArg)) {
                UINT cbUsed = (cbArg + 0xF) & ~0xF;
                LOAD_STRUCT_OFFSET_IF_NEEDED(cbUsed);
                // rax has the source pointer
                // r9 has the intermediate copy location
                // r10 has the final destination
                if (nArgSlot < 4) {
                    pSl->X86EmitIndexRegStore(kRDX, rgcbArgRegCtxtOffsets[nArgSlot++], kR10);
                }
                else {
                    pSl->X86EmitIndexRegStore(kR8, 8 * nArgSlot++, kR10);
                }
                // now emit a 'memcpy(rax, r9, cbUsed)'
                // These structs are supposed to be 16-byte aligned, but
                // Reflection puts them on the GC heap, which is only 8-byte
                // aligned.  It also means we have to be careful about not
                // copying too much (because we might cross a page boundary)
                UINT cbUsed16 = (cbArg + 7) & ~0xF;
                _ASSERTE((cbUsed16 == cbUsed) || ((cbUsed16 + 16) == cbUsed));

                if (cbArg <= 192) {
                    // Unrolled version (6 x 16 bytes in parallel)
                    UINT offset = 0;
                    while (offset < cbUsed16) {
                        // movups xmm0, [rax + offset]
                        pSl->X86EmitOp(X86_INSTR_MOVUPS_R_RM, kXMM0, kRAX, offset);
                        if (offset + 16 < cbUsed16) {
                            // movups xmm1, [rax + offset + 16]
                            pSl->X86EmitOp(X86_INSTR_MOVUPS_R_RM, kXMM1, kRAX, offset + 16);
                            if (offset + 32 < cbUsed16) {
                                // movups xmm2, [rax + offset + 32]
                                pSl->X86EmitOp(X86_INSTR_MOVUPS_R_RM, kXMM2, kRAX, offset + 32);
                                if (offset + 48 < cbUsed16) {
                                    // movups xmm3, [rax + offset + 48]
                                    pSl->X86EmitOp(X86_INSTR_MOVUPS_R_RM, kXMM3, kRAX, offset + 48);
                                    if (offset + 64 < cbUsed16) {
                                        // movups xmm4, [rax + offset + 64]
                                        pSl->X86EmitOp(X86_INSTR_MOVUPS_R_RM, kXMM4, kRAX, offset + 64);
                                        if (offset + 80 < cbUsed16) {
                                            // movups xmm5, [rax + offset + 80]
                                            pSl->X86EmitOp(X86_INSTR_MOVUPS_R_RM, kXMM5, kRAX, offset + 80);
                                        }
                                    }
                                }
                            }
                        }
                        // movaps [r9 + offset], xmm0
                        pSl->X86EmitOp(X86_INSTR_MOVAPS_RM_R, kXMM0, kR9, offset);
                        offset += 16;
                        if (offset < cbUsed16) {
                            // movaps [r9 + 16], xmm1
                            pSl->X86EmitOp(X86_INSTR_MOVAPS_RM_R, kXMM1, kR9, offset);
                            offset += 16;
                            if (offset < cbUsed16) {
                                // movaps [r9 + 32], xmm2
                                pSl->X86EmitOp(X86_INSTR_MOVAPS_RM_R, kXMM2, kR9, offset);
                                offset += 16;
                                if (offset < cbUsed16) {
                                    // movaps [r9 + 48], xmm3
                                    pSl->X86EmitOp(X86_INSTR_MOVAPS_RM_R, kXMM3, kR9, offset);
                                    offset += 16;
                                    if (offset < cbUsed16) {
                                        // movaps [r9 + 64], xmm4
                                        pSl->X86EmitOp(X86_INSTR_MOVAPS_RM_R, kXMM4, kR9, offset);
                                        offset += 16;
                                        if (offset < cbUsed16) {
                                            // movaps [r9 + 80], xmm5
                                            pSl->X86EmitOp(X86_INSTR_MOVAPS_RM_R, kXMM5, kR9, offset);
                                            offset += 16;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    // Copy the last 8 bytes if needed
                    if (cbUsed > cbUsed16) {
                        _ASSERTE(cbUsed16 < cbArg);
                        // movlps xmm0, [rax + offset]
                        pSl->X86EmitOp(X86_INSTR_MOVLPS_R_RM, kXMM0, kRAX, offset);
                        // movlps [r9 + offset], xmm0
                        pSl->X86EmitOp(X86_INSTR_MOVLPS_RM_R, kXMM0, kR9, offset);
                    }
                }
                else {
                    // a loop (one double-quadword at a time)
                    pSl->X86EmitZeroOutReg(kR11);
                    // LoopLabel:
                    CodeLabel *pLoopLabel = pSl->NewCodeLabel();
                    pSl->EmitLabel(pLoopLabel);
                    // movups xmm0, [rax + r11]
                    pSl->X86EmitOp(X86_INSTR_MOVUPS_R_RM, kXMM0, kRAX, 0, kR11, 1);
                    // movaps [r9 + r11], xmm0
                    pSl->X86EmitOp(X86_INSTR_MOVAPS_RM_R, kXMM0, kR9, 0, kR11, 1);
                    // add r11, 16
                    pSl->X86EmitAddReg(kR11, 16);
                    // cmp r11, cbUsed16
                    pSl->X86EmitCmpRegImm32(kR11, cbUsed16);
                    // jl LoopLabel
                    pSl->X86EmitCondJump(pLoopLabel, X86CondCode::kJL);
                    if (cbArg > cbUsed16) {
                        _ASSERTE(cbUsed16 + 8 >= cbArg);
                        // movlps xmm0, [rax + r11]
                        pSl->X86EmitOp(X86_INSTR_MOVLPS_R_RM, kXMM0, kRAX, 0, kR11, 1);
                        // movlps [r9 + r11], xmm0
                        pSl->X86EmitOp(X86_INSTR_MOVLPS_RM_R, kXMM0, kR9, 0, kR11, 1);
                    }
                }
                cbStructOffset += cbUsed;
                AppendGCLayout(gcLayout, cbStructOffset, et == ELEMENT_TYPE_TYPEDBYREF, th);
                break;
            }

            //
            // Explicit Fall-Through for non-IsArgPassedByRef
            //

        default:
            if (nArgSlot < 4) {
                pSl->X86EmitIndexRegStore(kRDX, rgcbArgRegCtxtOffsets[nArgSlot], kRAX);
                if ((et == ELEMENT_TYPE_R4) || (et == ELEMENT_TYPE_R8)) {
                    pSl->X86EmitIndexRegStore(kRDX, rgcbFpArgRegCtxtOffsets[nArgSlot], kRAX);
                }
            }
            else {
                pSl->X86EmitIndexRegStore(kR8, 8 * nArgSlot, kRAX);
            }
            nArgSlot++;
            break;
        }
    }

#undef LOAD_STRUCT_OFFSET_IF_NEEDED

    // Keep our 4 shadow slots and even number of slots (to keep 16-byte aligned)
    if (nArgSlot < 4) 
        nArgSlot = 4;
    else if (nArgSlot & 1)
        nArgSlot++;

    _ASSERTE((cbStructOffset % 16) == 0);

    // xor eax, eax
    pSl->X86EmitZeroOutReg(kRAX);
    // ret
    pSl->X86EmitReturn(0);

    // NullLabel:
    pSl->EmitLabel(pNullLabel);

    CodeLabel *pGCLayoutLabel = NULL;
    if (gcLayout.Count() == 0) {
        // xor eax, eax
        pSl->X86EmitZeroOutReg(kRAX);
    }
    else {
        // lea rax, [rip + offset to gclayout]
        pGCLayoutLabel = pSl->NewCodeLabel();
        pSl->X86EmitLeaRIP(pGCLayoutLabel, kRAX);
    }
    // mov [r9], rax
    pSl->X86EmitIndexRegStore(kR9, 0, kRAX);
    // mov rax, cbStackNeeded
    pSl->X86EmitRegLoad(kRAX, cbStructOffset + nArgSlot * 8);
    // ret
    pSl->X86EmitReturn(0);

    if (gcLayout.Count() > 0) {
        // GCLayout:
        pSl->EmitLabel(pGCLayoutLabel);
        EncodeGCOffsets(pSl, gcLayout);
    }

    LoaderHeap* pHeap = pMD->GetLoaderAllocator()->GetStubHeap();
    return pSl->Link(pHeap);
}
#endif // DACCESS_COMPILE

#endif // _TARGET_AMD64_


#ifdef HAS_FIXUP_PRECODE

#ifdef HAS_FIXUP_PRECODE_CHUNKS
TADDR FixupPrecode::GetMethodDesc()
{
    LIMITED_METHOD_CONTRACT;
    SUPPORTS_DAC;

    // This lookup is also manually inlined in PrecodeFixupThunk assembly code
    TADDR base = *PTR_TADDR(GetBase());
    if (base == NULL)
        return NULL;
    return base + (m_MethodDescChunkIndex * MethodDesc::ALIGNMENT);
}
#endif

#ifdef FIXUP_PRECODE_PREALLOCATE_DYNAMIC_METHOD_JUMP_STUBS
PCODE FixupPrecode::GetDynamicMethodPrecodeFixupJumpStub()
{
    WRAPPER_NO_CONTRACT;
    _ASSERTE(((PTR_MethodDesc)GetMethodDesc())->IsLCGMethod());

    // The precode fixup jump stub is shared by all fixup precodes in a chunk, and immediately follows the MethodDesc. Jump
    // stubs cannot be reused currently for the same method:
    //   - The jump stub's target would change separately from the precode being updated from "call Func" to "jmp Func", both
    //     changes would have to be done atomically with runtime suspension, which is not done currently
    //   - When changing the entry point from one version of jitted code to another, the jump stub's target pointer is not
    //     aligned to 8 bytes in order to be able to do an interlocked update of the target address
    // So, when initially the precode intends to be of the form "call PrecodeFixupThunk", if the target address happens to be
    // too far for a relative 32-bit jump, it will use the shared precode fixup jump stub. When changing the entry point to
    // jitted code, the jump stub associated with the precode is patched, and the precode is updated to use that jump stub.
    //
    // Notes:
    // - Dynamic method descs, and hence their precodes and preallocated jump stubs, may be reused for a different method
    //   (along with reinitializing the precode), but only with a transition where the original method is no longer accessible
    //   to user code
    // - Concurrent calls to a dynamic method that has not yet been jitted may trigger multiple writes to the jump stub
    //   associated with the precode, but only to the same target address (and while the precode is still pointing to
    //   PrecodeFixupThunk)
    return GetBase() + sizeof(PTR_MethodDesc);
}

PCODE FixupPrecode::GetDynamicMethodEntryJumpStub()
{
    WRAPPER_NO_CONTRACT;
    _ASSERTE(((PTR_MethodDesc)GetMethodDesc())->IsLCGMethod());

    // m_PrecodeChunkIndex has a value inverted to the order of precodes in memory (the precode at the lowest address has the
    // highest index, and the precode at the highest address has the lowest index). To map a precode to its jump stub by memory
    // order, invert the precode index to get the jump stub index. Also skip the precode fixup jump stub (see
    // GetDynamicMethodPrecodeFixupJumpStub()).
    UINT32 count = ((PTR_MethodDesc)GetMethodDesc())->GetMethodDescChunk()->GetCount();
    _ASSERTE(m_PrecodeChunkIndex < count);
    SIZE_T jumpStubIndex = count - m_PrecodeChunkIndex;

    return GetBase() + sizeof(PTR_MethodDesc) + jumpStubIndex * BACK_TO_BACK_JUMP_ALLOCATE_SIZE;
}
#endif // FIXUP_PRECODE_PREALLOCATE_DYNAMIC_METHOD_JUMP_STUBS

#ifdef DACCESS_COMPILE
void FixupPrecode::EnumMemoryRegions(CLRDataEnumMemoryFlags flags)
{
    SUPPORTS_DAC;
    DacEnumMemoryRegion(dac_cast<TADDR>(this), sizeof(FixupPrecode));

    DacEnumMemoryRegion(GetBase(), sizeof(TADDR));
}
#endif // DACCESS_COMPILE

#endif // HAS_FIXUP_PRECODE

#ifndef DACCESS_COMPILE

void rel32SetInterlocked(/*PINT32*/ PVOID pRel32, TADDR target, MethodDesc* pMD)
{
    CONTRACTL
    {
        THROWS;         // Creating a JumpStub could throw OutOfMemory
        GC_NOTRIGGER;
    }
    CONTRACTL_END;

    INT32 targetRel32 = rel32UsingJumpStub((INT32*)pRel32, target, pMD);

    _ASSERTE(IS_ALIGNED(pRel32, sizeof(INT32)));
    FastInterlockExchange((LONG*)pRel32, (LONG)targetRel32);
}

BOOL rel32SetInterlocked(/*PINT32*/ PVOID pRel32, TADDR target, TADDR expected, MethodDesc* pMD)
{
    CONTRACTL
    {
        THROWS;         // Creating a JumpStub could throw OutOfMemory
        GC_NOTRIGGER;
    }
    CONTRACTL_END;

    BYTE* callAddrAdj = (BYTE*)pRel32 + 4;
    INT32 expectedRel32 = static_cast<INT32>((BYTE*)expected - callAddrAdj);

    INT32 targetRel32 = rel32UsingJumpStub((INT32*)pRel32, target, pMD);

    _ASSERTE(IS_ALIGNED(pRel32, sizeof(INT32)));
    return FastInterlockCompareExchange((LONG*)pRel32, (LONG)targetRel32, (LONG)expectedRel32) == (LONG)expectedRel32;
}

void StubPrecode::Init(MethodDesc* pMD, LoaderAllocator *pLoaderAllocator /* = NULL */,
    BYTE type /* = StubPrecode::Type */, TADDR target /* = NULL */)
{
    WRAPPER_NO_CONTRACT;

    IN_WIN64(m_movR10 = X86_INSTR_MOV_R10_IMM64);   // mov r10, pMethodDesc
    IN_WIN32(m_movEAX = X86_INSTR_MOV_EAX_IMM32);   // mov eax, pMethodDesc
    m_pMethodDesc = (TADDR)pMD;
    IN_WIN32(m_mov_rm_r = X86_INSTR_MOV_RM_R);      // mov reg,reg
    m_type = type;
    m_jmp = X86_INSTR_JMP_REL32;        // jmp rel32

    if (pLoaderAllocator != NULL)
    {
        // Use pMD == NULL in all precode initialization methods to allocate the initial jump stub in non-dynamic heap
        // that has the same lifetime like as the precode itself
        if (target == NULL)
            target = GetPreStubEntryPoint();
        m_rel32 = rel32UsingJumpStub(&m_rel32, target, NULL /* pMD */, pLoaderAllocator);
    }
}

#ifdef HAS_NDIRECT_IMPORT_PRECODE

void NDirectImportPrecode::Init(MethodDesc* pMD, LoaderAllocator *pLoaderAllocator)
{
    WRAPPER_NO_CONTRACT;
    StubPrecode::Init(pMD, pLoaderAllocator, NDirectImportPrecode::Type, GetEEFuncEntryPoint(NDirectImportThunk));
}

#endif // HAS_NDIRECT_IMPORT_PRECODE


#ifdef HAS_FIXUP_PRECODE
void FixupPrecode::Init(MethodDesc* pMD, LoaderAllocator *pLoaderAllocator, int iMethodDescChunkIndex /*=0*/, int iPrecodeChunkIndex /*=0*/)
{
    WRAPPER_NO_CONTRACT;

    m_op   = X86_INSTR_CALL_REL32;       // call PrecodeFixupThunk
    m_type = FixupPrecode::TypePrestub;

    // Initialize chunk indices only if they are not initialized yet. This is necessary to make MethodDesc::Reset work.
    if (m_PrecodeChunkIndex == 0)
    {
        _ASSERTE(FitsInU1(iPrecodeChunkIndex));
        m_PrecodeChunkIndex = static_cast<BYTE>(iPrecodeChunkIndex);
    }

    if (iMethodDescChunkIndex != -1)
    {
        if (m_MethodDescChunkIndex == 0)
        {
            _ASSERTE(FitsInU1(iMethodDescChunkIndex));
            m_MethodDescChunkIndex = static_cast<BYTE>(iMethodDescChunkIndex);
        }

        if (*(void**)GetBase() == NULL)
            *(void**)GetBase() = (BYTE*)pMD - (iMethodDescChunkIndex * MethodDesc::ALIGNMENT);
    }

    _ASSERTE(GetMethodDesc() == (TADDR)pMD);

    PCODE target = (PCODE)GetEEFuncEntryPoint(PrecodeFixupThunk);
#ifdef FIXUP_PRECODE_PREALLOCATE_DYNAMIC_METHOD_JUMP_STUBS
    if (pMD->IsLCGMethod())
    {
        m_rel32 = rel32UsingPreallocatedJumpStub(&m_rel32, target, GetDynamicMethodPrecodeFixupJumpStub(), false /* emitJump */);
        return;
    }
#endif // FIXUP_PRECODE_PREALLOCATE_DYNAMIC_METHOD_JUMP_STUBS
    if (pLoaderAllocator != NULL)
    {
        m_rel32 = rel32UsingJumpStub(&m_rel32, target, NULL /* pMD */, pLoaderAllocator);
    }
}

void FixupPrecode::ResetTargetInterlocked()
{
    CONTRACTL
    {
        THROWS;         // Creating a JumpStub could throw OutOfMemory
        GC_NOTRIGGER;
    }
    CONTRACTL_END;

    FixupPrecode newValue = *this;
    newValue.m_op = X86_INSTR_CALL_REL32; // call PrecodeFixupThunk
    newValue.m_type = FixupPrecode::TypePrestub;

    PCODE target = (PCODE)GetEEFuncEntryPoint(PrecodeFixupThunk);
    MethodDesc* pMD = (MethodDesc*)GetMethodDesc();
#ifdef FIXUP_PRECODE_PREALLOCATE_DYNAMIC_METHOD_JUMP_STUBS
    // The entry point of LCG methods cannot revert back to the original entry point, as their jump stubs would have to be
    // reused, which is currently not supported. This method is intended for resetting the entry point while the method is
    // callable, which implies that the entry point may later be changed again to something else. Currently, this is not done
    // for LCG methods. See GetDynamicMethodPrecodeFixupJumpStub() for more.
    _ASSERTE(!pMD->IsLCGMethod());
#endif // FIXUP_PRECODE_PREALLOCATE_DYNAMIC_METHOD_JUMP_STUBS

    newValue.m_rel32 = rel32UsingJumpStub(&m_rel32, target, pMD);

    _ASSERTE(IS_ALIGNED(this, sizeof(INT64)));
    EnsureWritableExecutablePages(this, sizeof(INT64));
    FastInterlockExchangeLong((INT64*)this, *(INT64*)&newValue);
}

BOOL FixupPrecode::SetTargetInterlocked(TADDR target, TADDR expected)
{
    CONTRACTL
    {
        THROWS;         // Creating a JumpStub could throw OutOfMemory
        GC_NOTRIGGER;
    }
    CONTRACTL_END;

    INT64 oldValue = *(INT64*)this;
    BYTE* pOldValue = (BYTE*)&oldValue;

    MethodDesc * pMD = (MethodDesc*)GetMethodDesc();
    g_IBCLogger.LogMethodPrecodeWriteAccess(pMD);
    
#ifdef FIXUP_PRECODE_PREALLOCATE_DYNAMIC_METHOD_JUMP_STUBS
    // A different jump stub is used for this case, see Init(). This call is unexpected for resetting the entry point.
    _ASSERTE(!pMD->IsLCGMethod() || target != (TADDR)GetEEFuncEntryPoint(PrecodeFixupThunk));
#endif // FIXUP_PRECODE_PREALLOCATE_DYNAMIC_METHOD_JUMP_STUBS

    INT64 newValue = oldValue;
    BYTE* pNewValue = (BYTE*)&newValue;

    if (pOldValue[OFFSETOF_PRECODE_TYPE_CALL_OR_JMP] == FixupPrecode::TypePrestub)
    {
        pNewValue[OFFSETOF_PRECODE_TYPE_CALL_OR_JMP] = FixupPrecode::Type;

        pOldValue[offsetof(FixupPrecode, m_op)] = X86_INSTR_CALL_REL32;
        pNewValue[offsetof(FixupPrecode, m_op)] = X86_INSTR_JMP_REL32;
    }
    else if (pOldValue[OFFSETOF_PRECODE_TYPE_CALL_OR_JMP] == FixupPrecode::Type)
    {
#ifdef FEATURE_CODE_VERSIONING
        // No change needed, jmp is already in place
#else
        // Setting the target more than once is unexpected
        return FALSE;
#endif
    }
    else
    {
        // Pre-existing code doesn't conform to the expectations for a FixupPrecode
        return FALSE;
    }
	
    *(INT32*)(&pNewValue[offsetof(FixupPrecode, m_rel32)]) =
#ifdef FIXUP_PRECODE_PREALLOCATE_DYNAMIC_METHOD_JUMP_STUBS
        pMD->IsLCGMethod() ?
            rel32UsingPreallocatedJumpStub(&m_rel32, target, GetDynamicMethodEntryJumpStub(), true /* emitJump */) :
#endif // FIXUP_PRECODE_PREALLOCATE_DYNAMIC_METHOD_JUMP_STUBS
            rel32UsingJumpStub(&m_rel32, target, pMD);

    _ASSERTE(IS_ALIGNED(this, sizeof(INT64)));
    EnsureWritableExecutablePages(this, sizeof(INT64));
    return FastInterlockCompareExchangeLong((INT64*) this, newValue, oldValue) == oldValue;
}

#ifdef FEATURE_NATIVE_IMAGE_GENERATION
// Partial initialization. Used to save regrouped chunks.
void FixupPrecode::InitForSave(int iPrecodeChunkIndex)
{
    m_op   = X86_INSTR_CALL_REL32;       // call PrecodeFixupThunk
    m_type = FixupPrecode::TypePrestub;

    _ASSERTE(FitsInU1(iPrecodeChunkIndex));
    m_PrecodeChunkIndex = static_cast<BYTE>(iPrecodeChunkIndex);

    // The rest is initialized in code:FixupPrecode::Fixup
}

void FixupPrecode::Fixup(DataImage *image, MethodDesc * pMD)
{
    STANDARD_VM_CONTRACT;

    // Note that GetMethodDesc() does not return the correct value because of 
    // regrouping of MethodDescs into hot and cold blocks. That's why the caller
    // has to supply the actual MethodDesc

    SSIZE_T mdChunkOffset;
    ZapNode * pMDChunkNode = image->GetNodeForStructure(pMD, &mdChunkOffset);
    ZapNode * pHelperThunk = image->GetHelperThunk(CORINFO_HELP_EE_PRECODE_FIXUP);

    image->FixupFieldToNode(this, offsetof(FixupPrecode, m_rel32),
                            pHelperThunk, 0, IMAGE_REL_BASED_REL32);

    // Set the actual chunk index
    FixupPrecode * pNewPrecode = (FixupPrecode *)image->GetImagePointer(this);

    size_t mdOffset   = mdChunkOffset - sizeof(MethodDescChunk);
    size_t chunkIndex = mdOffset / MethodDesc::ALIGNMENT;
    _ASSERTE(FitsInU1(chunkIndex));
    pNewPrecode->m_MethodDescChunkIndex = (BYTE) chunkIndex;

    // Fixup the base of MethodDescChunk
    if (m_PrecodeChunkIndex == 0)
    {
        image->FixupFieldToNode(this, (BYTE *)GetBase() - (BYTE *)this,
            pMDChunkNode, sizeof(MethodDescChunk));
    }
}
#endif // FEATURE_NATIVE_IMAGE_GENERATION

#endif // HAS_FIXUP_PRECODE

#endif // !DACCESS_COMPILE


#ifdef HAS_THISPTR_RETBUF_PRECODE

// rel32 jmp target that points back to the jump (infinite loop).
// Used to mark uninitialized ThisPtrRetBufPrecode target
#define REL32_JMP_SELF (-5)

#ifndef DACCESS_COMPILE
void ThisPtrRetBufPrecode::Init(MethodDesc* pMD, LoaderAllocator *pLoaderAllocator)
{
    WRAPPER_NO_CONTRACT;

    IN_WIN64(m_nop1 = X86_INSTR_NOP;)   // nop
#ifdef UNIX_AMD64_ABI
    m_prefix1 = 0x48;
    m_movScratchArg0 = 0xC78B;          // mov rax,rdi
    m_prefix2 = 0x48;
    m_movArg0Arg1 = 0xFE8B;             // mov rdi,rsi
    m_prefix3 = 0x48;
    m_movArg1Scratch = 0xF08B;          // mov rsi,rax
#else
    IN_WIN64(m_prefix1 = 0x48;)
    m_movScratchArg0 = 0xC889;          // mov r/eax,r/ecx
    IN_WIN64(m_prefix2 = 0x48;)
    m_movArg0Arg1 = 0xD189;             // mov r/ecx,r/edx
    IN_WIN64(m_prefix3 = 0x48;)
    m_movArg1Scratch = 0xC289;          // mov r/edx,r/eax
#endif
    m_nop2 = X86_INSTR_NOP;             // nop
    m_jmp = X86_INSTR_JMP_REL32;        // jmp rel32
    m_pMethodDesc = (TADDR)pMD;

    // This precode is never patched lazily - avoid unnecessary jump stub allocation
    m_rel32 = REL32_JMP_SELF;
}

BOOL ThisPtrRetBufPrecode::SetTargetInterlocked(TADDR target, TADDR expected)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
    }
    CONTRACTL_END;

    // This precode is never patched lazily - the interlocked semantics is not required.
    _ASSERTE(m_rel32 == REL32_JMP_SELF);

    // Use pMD == NULL to allocate the jump stub in non-dynamic heap that has the same lifetime as the precode itself
    INT32 newRel32 = rel32UsingJumpStub(&m_rel32, target, NULL /* pMD */, ((MethodDesc *)GetMethodDesc())->GetLoaderAllocator());

    _ASSERTE(IS_ALIGNED(&m_rel32, sizeof(INT32)));
    FastInterlockExchange((LONG *)&m_rel32, (LONG)newRel32);
    return TRUE;
}
#endif // !DACCESS_COMPILE

PCODE ThisPtrRetBufPrecode::GetTarget()
{ 
    LIMITED_METHOD_DAC_CONTRACT;

    // This precode is never patched lazily - pretend that the uninitialized m_rel32 points to prestub
    if (m_rel32 == REL32_JMP_SELF)
        return GetPreStubEntryPoint();

    return rel32Decode(PTR_HOST_MEMBER_TADDR(ThisPtrRetBufPrecode, this, m_rel32));
}

#endif // HAS_THISPTR_RETBUF_PRECODE