summaryrefslogtreecommitdiff
path: root/src/vm/classcompat.cpp
blob: b677045f0bd1c900ed1e9dbc2de877c3daeb6e77 (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
// 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.
// ===========================================================================
// File: CLASSCOMPAT.CPP

// ===========================================================================
// This file contains backward compatibility functionality for COM Interop.
// ===========================================================================
//


#include "common.h"

#ifndef DACCESS_COMPILE

#include "clsload.hpp"
#include "method.hpp"
#include "class.h"
#include "classcompat.h"
#include "object.h"
#include "field.h"
#include "util.hpp"
#include "excep.h"
#include "threads.h"
#include "stublink.h"
#include "dllimport.h"
#include "jitinterface.h"
#include "eeconfig.h"
#include "log.h"
#include "fieldmarshaler.h"
#include "cgensys.h"
#include "gcheaputilities.h"
#include "dbginterface.h"
#include "comdelegate.h"
#include "sigformat.h"
#include "eeprofinterfaces.h"
#include "dllimportcallback.h"
#include "listlock.h"
#include "methodimpl.h"
#include "guidfromname.h"
#include "encee.h"
#include "encee.h"
#include "comsynchronizable.h"
#include "customattribute.h"
#include "virtualcallstub.h"
#include "eeconfig.h"
#include "contractimpl.h"
#include "prettyprintsig.h"

#include "comcallablewrapper.h"
#include "clrtocomcall.h"
#include "runtimecallablewrapper.h"

#include "generics.h"
#include "contractimpl.h"

//////////////////////////////////////////////////////////////////////////////////////////////
ClassCompat::InterfaceInfo_t* InteropMethodTableData::FindInterface(MethodTable *pInterface)
{
    WRAPPER_NO_CONTRACT;

    for (DWORD i = 0; i < cInterfaceMap; i++)
    {
        ClassCompat::InterfaceInfo_t *iMap = &pInterfaceMap[i];
        if (iMap->m_pMethodTable->IsEquivalentTo(pInterface))
        {
            // Extensible RCW's need to be handled specially because they can have interfaces 
            // in their map that are added at runtime. These interfaces will have a start offset 
            // of -1 to indicate this. We cannot take for granted that every instance of this 
            // COM object has this interface so FindInterface on these interfaces is made to fail.
            //
            // However, we are only considering the statically available slots here
            // (m_wNumInterface doesn't contain the dynamic slots), so we can safely
            // ignore this detail.
            return iMap;
        }
    }

    return NULL;
}

//////////////////////////////////////////////////////////////////////////////////////////////
// get start slot for interface
// returns -1 if interface not found
WORD InteropMethodTableData::GetStartSlotForInterface(MethodTable* pInterface)
{
    WRAPPER_NO_CONTRACT;

    ClassCompat::InterfaceInfo_t* pInfo = FindInterface(pInterface);

    if (pInfo != NULL)
    {
        WORD startSlot = pInfo->GetInteropStartSlot();
        _ASSERTE(startSlot != MethodTable::NO_SLOT);
        return startSlot;
    }

    return MethodTable::NO_SLOT;
}

//////////////////////////////////////////////////////////////////////////////////////////////
// This will return the interop slot for pMD in pMT. It will traverse the inheritance tree
// to find a match.
/*static*/ WORD InteropMethodTableData::GetSlotForMethodDesc(MethodTable *pMT, MethodDesc *pMD)
{
    while (pMT)
    {
        InteropMethodTableData *pData = pMT->LookupComInteropData();
        _ASSERTE(pData);
        for (DWORD i = 0; i < pData->cVTable; i++)
        {
            if (pData->pVTable[i].pMD == pMD)
                return (WORD) i;
        }
        pMT = pMT->GetParentMethodTable();
    }

    return MethodTable::NO_SLOT;
}

//////////////////////////////////////////////////////////////////////////////////////////////
InteropMethodTableSlotDataMap::InteropMethodTableSlotDataMap(InteropMethodTableSlotData *pSlotData, DWORD cSlotData)
{
    m_pSlotData = pSlotData;
    m_cSlotData = cSlotData;
    m_iCurSlot = 0;
}

//////////////////////////////////////////////////////////////////////////////////////////////
InteropMethodTableSlotData *InteropMethodTableSlotDataMap::Exists_Helper(MethodDesc *pMD)
{
    LIMITED_METHOD_CONTRACT;
    for (DWORD i = 0; i < m_cSlotData; i++)
    {
        if (m_pSlotData[i].pDeclMD == pMD)
        {
            return (&m_pSlotData[i]);
        }
    }

    return (NULL);
}

//////////////////////////////////////////////////////////////////////////////////////////////
BOOL InteropMethodTableSlotDataMap::Exists(MethodDesc *pMD)
{
    return (Exists_Helper(pMD) != NULL);
}

//////////////////////////////////////////////////////////////////////////////////////////////
InteropMethodTableSlotData *InteropMethodTableSlotDataMap::GetData(MethodDesc *pMD)
{
    LIMITED_METHOD_CONTRACT;
    InteropMethodTableSlotData *pEntry = Exists_Helper(pMD);

    if (pEntry)
        return pEntry;

    pEntry = GetNewEntry();
    pEntry->pMD = pMD;
    pEntry->pDeclMD = pMD;
    return (pEntry);
}

//////////////////////////////////////////////////////////////////////////////////////////////
InteropMethodTableSlotData *InteropMethodTableSlotDataMap::GetNewEntry()
{
    WRAPPER_NO_CONTRACT;
    _ASSERTE(m_iCurSlot < m_cSlotData);
    InteropMethodTableSlotData *pEntry = &m_pSlotData[m_iCurSlot++];
    pEntry->pMD = NULL;
    pEntry->wFlags = 0;
    pEntry->wSlot = MethodTable::NO_SLOT;
    pEntry->pDeclMD = NULL;
    return (pEntry);
}

namespace ClassCompat
{

//////////////////////////////////////////////////////////////////////////////////////////////
InteropMethodTableData *MethodTableBuilder::BuildInteropVTable(AllocMemTracker *pamTracker)
{
    CONTRACTL {
        STANDARD_VM_CHECK;
        INSTANCE_CHECK;
    } CONTRACTL_END;

    MethodTable * pThisMT = GetHalfBakedMethodTable();

    // This should never be called for interfaces or for generic types.
    _ASSERTE(!pThisMT->IsInterface());
    _ASSERTE(!pThisMT->ContainsGenericVariables());
    _ASSERTE(!pThisMT->HasGenericClassInstantiationInHierarchy());

    // Array method tables are created quite differently
    if (pThisMT->IsArray())
        return BuildInteropVTableForArray(pamTracker);

#ifdef _DEBUG
    BOOL fDump = FALSE;
    LPCUTF8 fullName = pThisMT->GetDebugClassName();
    if (fullName) {
        LPWSTR wszRegName = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_BreakOnInteropVTableBuild);
        if (wszRegName) {        
            { // Poor man's narrow
                LPWSTR fromPtr = wszRegName;
                LPUTF8 toPtr = (LPUTF8) wszRegName;
                LPUTF8 result = toPtr;
                while(*fromPtr != 0)
                    *toPtr++ = (char) *fromPtr++;
                *toPtr = 0;
            }
            LPCUTF8 regName = (LPCUTF8) wszRegName;
            LPCUTF8 bracket = (LPCUTF8) strchr(fullName, '[');
            size_t len = strlen(fullName);
            if (bracket != NULL)
                len = bracket - fullName;
            if (strncmp(fullName, regName, len) == 0) {
                _ASSERTE(!"BreakOnInteropVTableBuild");
                fDump = TRUE;
            }
            delete [] wszRegName;
        }
    }
#endif // _DEBUG

    //Get Check Point for the thread-based allocator

    HRESULT hr = S_OK;
    Module *pModule = pThisMT->GetModule();
    mdToken cl = pThisMT->GetCl();
    MethodTable *pParentMethodTable = pThisMT->GetParentMethodTable();

    // The following structs, defined as private members of MethodTableBuilder, contain the necessary local
    // parameters needed for MethodTableBuilder

    // Look at the struct definitions for a detailed list of all parameters available
    // to MethodTableBuilder.

    bmtErrorInfo bmtError;
    bmtProperties bmtProp;
    bmtVtable bmtVT;
    bmtParentInfo bmtParent;
    bmtInterfaceInfo bmtInterface;
    bmtMethodInfo bmtMethod(pModule->GetMDImport());
    bmtTypeInfo bmtType;
    bmtMethodImplInfo bmtMethodImpl(pModule->GetMDImport());

    //Initialize structs

    bmtError.resIDWhy = IDS_CLASSLOAD_GENERAL;          // Set the reason and the offending method def. If the method information
    bmtError.pThrowable = NULL;
    bmtError.pModule  = pModule;
    bmtError.cl       = cl;

    bmtType.pMDImport = pModule->GetMDImport();
    bmtType.pModule = pModule;
    bmtType.cl = cl;

    bmtParent.parentSubst = GetHalfBakedMethodTable()->GetSubstitutionForParent(NULL);
    if (FAILED(bmtType.pMDImport->GetTypeDefProps(
        bmtType.cl, 
        &(bmtType.dwAttr),
        &(bmtParent.token))))
    {
        BuildMethodTableThrowException(IDS_CLASSLOAD_BADFORMAT);
    }
    
    SetBMTData(
        &bmtError,
        &bmtProp,
        &bmtVT,
        &bmtParent,
        &bmtInterface,
        &bmtMethod,
        &bmtType,
        &bmtMethodImpl);

    // Populate the BMT data structures from the attributes of the incoming MT
    if (pThisMT->IsValueType()) SetIsValueClass();
    if (pThisMT->IsEnum()) SetEnum();
    if (pThisMT->HasLayout()) SetHasLayout();
    if (pThisMT->IsDelegate()) SetIsDelegate();
#ifdef FEATURE_COMINTEROP
    if(pThisMT->GetClass()->IsComClassInterface()) SetIsComClassInterface();
#endif
        
    // Populate the interface list - these are allocated on the thread's stacking allocator
    //@TODO: This doesn't work for generics - fix if generics will be exposed to COM
    BuildingInterfaceInfo_t *pBuildingInterfaceList;
    WORD wNumInterfaces;
    BuildInteropVTable_InterfaceList(&pBuildingInterfaceList, &wNumInterfaces);

    bmtInterface.wInterfaceMapSize = wNumInterfaces;

    WORD i;

    // Interfaces have a parent class of Object, but we don't really want to inherit all of
    // Object's virtual methods, so pretend we don't have a parent class - at the bottom of this
    // function we reset the parent method table
    if (IsInterface())
    {
        pParentMethodTable = NULL;
    }

    bmtParent.pParentMethodTable = pParentMethodTable;

    // Com Import classes are special
    if (IsComImport()  && !IsEnum() && !IsInterface() && !IsValueClass() && !IsDelegate())
    {
        _ASSERTE(pParentMethodTable == g_pBaseCOMObject || pThisMT->IsWinRTObjectType());
        _ASSERTE(!(HasLayout()));

        // if the current class is imported
        bmtProp.fIsComObjectType = TRUE;
    }

    bmtParent.pParentMethodTable = pParentMethodTable;

    if (pParentMethodTable != NULL)
    {         
        if (pParentMethodTable->IsComObjectType())
        {
            // if the parent class is of ComObjectType
            // so is the child
            bmtProp.fIsComObjectType = TRUE;
        }
    }

    // resolve unresolved interfaces, determine an upper bound on the size of the interface map,
    // and determine the size of the largest interface (in # slots)
    BuildInteropVTable_ResolveInterfaces(pBuildingInterfaceList, &bmtType, &bmtInterface, &bmtVT, &bmtParent, bmtError);

    // Enumerate this class's members
    EnumerateMethodImpls();

    // Enumerate this class's members
    EnumerateClassMethods();

    AllocateMethodWorkingMemory();

    // Allocate the working memory for the interop data
    {
        ////////////////
        // The interop data for the VTable for COM Interop backward compatibility

        // Allocate space to hold on to the MethodDesc for each entry
        bmtVT.ppSDVtable = new (GetStackingAllocator()) InteropMethodTableSlotData*[bmtVT.dwMaxVtableSize];
        ZeroMemory(bmtVT.ppSDVtable, bmtVT.dwMaxVtableSize * sizeof(InteropMethodTableSlotData*));

        // Allocate space to hold on to the MethodDesc for each entry
        bmtVT.ppSDNonVtable = new (GetStackingAllocator()) InteropMethodTableSlotData*[NumDeclaredMethods()];
        ZeroMemory(bmtVT.ppSDNonVtable , sizeof(InteropMethodTableSlotData*)*NumDeclaredMethods());


        DWORD cMaxEntries = (bmtVT.dwMaxVtableSize * 2) + (NumDeclaredMethods() * 2);
        InteropMethodTableSlotData *pInteropData = new (GetStackingAllocator()) InteropMethodTableSlotData[cMaxEntries];
        memset(pInteropData, 0, cMaxEntries * sizeof(InteropMethodTableSlotData));

        bmtVT.pInteropData = new (GetStackingAllocator()) InteropMethodTableSlotDataMap(pInteropData, cMaxEntries);

        // Initialize the map with parent information
        if (bmtParent.pParentMethodTable != NULL)
        {
            InteropMethodTableData *pParentInteropData = bmtParent.pParentMethodTable->LookupComInteropData();
            _ASSERTE(pParentInteropData);

            for ( i = 0; i < pParentInteropData->cVTable; i++)
            {
                InteropMethodTableSlotData *pParentSlot = &pParentInteropData->pVTable[i];
                InteropMethodTableSlotData *pNewEntry = bmtVT.pInteropData->GetData(pParentSlot->pDeclMD);
                pNewEntry->pMD = pParentSlot->pMD;
                pNewEntry->pDeclMD = pParentSlot->pDeclMD;
                pNewEntry->wFlags = pParentSlot->wFlags;
                pNewEntry->wSlot = pParentSlot->wSlot;

                bmtVT.ppSDVtable[i] = pNewEntry;
            }
        }
    }

    // Determine vtable placement for each member in this class
    BuildInteropVTable_PlaceMembers(&bmtType, wNumInterfaces, pBuildingInterfaceList, &bmtMethod,
                                    &bmtError, &bmtProp, &bmtParent, &bmtInterface, &bmtMethodImpl, &bmtVT);

    // First copy what we can leverage from the parent's interface map.
    // The parent's interface map will be identical to the beginning of this class's interface map (i.e.
    // the interfaces will be listed in the identical order).
    if (bmtParent.wNumParentInterfaces > 0)
    {
        PREFIX_ASSUME(pParentMethodTable != NULL); // We have to have parent to have parent interfaces

        _ASSERTE(pParentMethodTable->LookupComInteropData());
        _ASSERTE(bmtParent.wNumParentInterfaces == pParentMethodTable->LookupComInteropData()->cInterfaceMap);
        InterfaceInfo_t *pParentInterfaceList = pParentMethodTable->LookupComInteropData()->pInterfaceMap;


        for (i = 0; i < bmtParent.wNumParentInterfaces; i++)
        {
#ifdef _DEBUG
            _ASSERTE(pParentInterfaceList[i].m_pMethodTable == bmtInterface.pInterfaceMap[i].m_pMethodTable);

            MethodTable *pMT = pParentInterfaceList[i].m_pMethodTable;

            // If the interface resides entirely inside the parent's class methods (i.e. no duplicate
            // slots), then we can place this interface in an identical spot to in the parent.
            //
            // Note carefully: the vtable for this interface could start within the first GetNumVirtuals()
            // entries, but could actually extend beyond it, if we were particularly efficient at placing
            // this interface, so check that the end of the interface vtable is before
            // pParentMethodTable->GetNumVirtuals().

            _ASSERTE(pParentInterfaceList[i].GetInteropStartSlot() + pMT->GetNumVirtuals() <= 
                     pParentMethodTable->LookupComInteropData()->cVTable);
#endif // _DEBUG
            // Interface lies inside parent's methods, so we can place it
            bmtInterface.pInterfaceMap[i].SetInteropStartSlot(pParentInterfaceList[i].GetInteropStartSlot());
        }
    }

    //
    // If we are a class, then there may be some unplaced vtable methods (which are by definition
    // interface methods, otherwise they'd already have been placed).  Place as many unplaced methods
    // as possible, in the order preferred by interfaces.  However, do not allow any duplicates - once
    // a method has been placed, it cannot be placed again - if we are unable to neatly place an interface,
    // create duplicate slots for it starting at dwCurrentDuplicateVtableSlot.  Fill out the interface
    // map for all interfaces as they are placed.
    //
    // If we are an interface, then all methods are already placed.  Fill out the interface map for
    // interfaces as they are placed.
    //
    if (!IsInterface())
    {
        BuildInteropVTable_PlaceVtableMethods(
            &bmtInterface,
            wNumInterfaces,
            pBuildingInterfaceList,
            &bmtVT,
            &bmtMethod,
            &bmtType,
            &bmtError,
            &bmtProp,
            &bmtParent);

        BuildInteropVTable_PlaceMethodImpls(
            &bmtType,
            &bmtMethodImpl,
            &bmtError,
            &bmtInterface,
            &bmtVT,
            &bmtParent);
    }

#ifdef _DEBUG
    if (IsInterface() == FALSE)
    {
        for (i = 0; i < bmtInterface.wInterfaceMapSize; i++)
        {
            _ASSERTE(bmtInterface.pInterfaceMap[i].GetInteropStartSlot() != MethodTable::NO_SLOT);
    }
    }
#endif // _DEBUG

    // Place all non vtable methods
    for (i = 0; i < bmtVT.wCurrentNonVtableSlot; i++)
    {
        bmtVT.SetMethodDescForSlot(bmtVT.wCurrentVtableSlot + i, bmtVT.ppSDNonVtable[i]->pMD);
        CONSISTENCY_CHECK(bmtVT.ppSDNonVtable[i]->wSlot != MethodTable::NO_SLOT);
        bmtVT.ppSDVtable[bmtVT.wCurrentVtableSlot + i] = bmtVT.ppSDNonVtable[i];
    }

    // Must copy overridden slots to duplicate entries in the vtable
    BuildInteropVTable_PropagateInheritance(&bmtVT);

    // ensure we didn't overflow the temporary vtable
    _ASSERTE(bmtVT.wCurrentNonVtableSlot <= bmtVT.dwMaxVtableSize);

    // Finalize.
    InteropMethodTableData *pInteropMT = NULL;

    FinalizeInteropVTable(
                      pamTracker,
                      pThisMT->GetLoaderAllocator(),
                      &bmtVT, 
                      &bmtInterface,  
                      &bmtType,  
                      &bmtProp,  
                      &bmtMethod,
                      &bmtError,  
                      &bmtParent,
                      &pInteropMT);
    _ASSERTE(pInteropMT);

#ifdef _DEBUG
    if (fDump)
    {
        CQuickBytes qb;
        DWORD       cb = 0;
        PCCOR_SIGNATURE pSig;
        ULONG           cbSig;

        printf("InteropMethodTable\n--------------\n");
        printf("VTable\n------\n");

        for (DWORD i = 0; i < pInteropMT->cVTable; i++)
        {
            // Print the method name
            InteropMethodTableSlotData *pInteropMD = &pInteropMT->pVTable[i];
            printf(pInteropMD->pMD->GetName());
            printf(" ");

            // Print the sig
            if (FAILED(pInteropMD->pMD->GetMDImport()->GetSigOfMethodDef(pInteropMD->pMD->GetMemberDef(), &cbSig, &pSig)))
            {
                pSig = NULL;
                cbSig = 0;
            }
            PrettyPrintSigInternalLegacy(pSig, cbSig, "", &qb, pInteropMD->pMD->GetMDImport());
            printf((LPCUTF8) qb.Ptr());
            printf("\n");
        }
    }
#endif // _DEBUG

    NullBMTData();

    return pInteropMT;
}

//---------------------------------------------------------------------------------------
InteropMethodTableData *MethodTableBuilder::BuildInteropVTableForArray(AllocMemTracker *pamTracker)
{
    CONTRACTL {
        STANDARD_VM_CHECK;
        INSTANCE_CHECK;
        PRECONDITION(GetHalfBakedMethodTable()->IsArray());
        PRECONDITION(GetHalfBakedMethodTable()->GetNumVirtuals() == GetHalfBakedMethodTable()->GetParentMethodTable()->GetNumVirtuals());
    } CONTRACTL_END;

    MethodTable * pThisMT = GetHalfBakedMethodTable();

    // Get the interop data for the parent
    MethodTable *pParentMT = pThisMT->GetParentMethodTable();
    InteropMethodTableData *pParentMTData = pParentMT->GetComInteropData();
    CONSISTENCY_CHECK(pParentMTData != NULL);

    // Allocate in the same heap as the array itself
    LoaderHeap *pHeap = pThisMT->GetLoaderAllocator()->GetLowFrequencyHeap();

    // Allocate the overall structure
    InteropMethodTableData *pMTData = (InteropMethodTableData *)(void *) pamTracker->Track(pHeap->AllocMem(S_SIZE_T(sizeof(InteropMethodTableData))));
    memset(pMTData, 0, sizeof(InteropMethodTableData));

    // Allocate the vtable - this is just a copy from System.Array
    pMTData->cVTable = pParentMTData->cVTable;
    if (pMTData->cVTable != 0)
    {
        pMTData->pVTable = (InteropMethodTableSlotData *)(void *)
            pamTracker->Track(pHeap->AllocMem(S_SIZE_T(sizeof(InteropMethodTableSlotData)) * S_SIZE_T(pMTData->cVTable)));

        // Copy the vtable
        for (DWORD i = 0; i < pMTData->cVTable; i++)
            pMTData->pVTable[i] = pParentMTData->pVTable[i];
    }

    // Allocate the non-vtable
    pMTData->cNonVTable = pThisMT->GetNumMethods() - pThisMT->GetNumVirtuals();
    if (pMTData->cNonVTable != 0)
    {
        pMTData->pNonVTable = (InteropMethodTableSlotData *)(void *)
            pamTracker->Track(pHeap->AllocMem(S_SIZE_T(sizeof(InteropMethodTableSlotData)) * S_SIZE_T(pMTData->cNonVTable)));

        // Copy the non-vtable
        UINT32 iCurRealSlot = pThisMT->GetNumVirtuals();
        WORD iCurInteropSlot = pMTData->cVTable;
        for (DWORD i = 0; i < pMTData->cNonVTable; i++, iCurRealSlot++, iCurInteropSlot++)
        {
            pMTData->pNonVTable[i].wSlot = iCurInteropSlot;
            pMTData->pNonVTable[i].pMD = pThisMT->GetMethodDescForSlot(iCurRealSlot);
        }
    }

    // Allocate the interface map
    pMTData->cInterfaceMap = pParentMTData->cInterfaceMap;
    if (pMTData->cInterfaceMap != 0)
    {
        pMTData->pInterfaceMap = (InterfaceInfo_t *)(void *)
            pamTracker->Track(pHeap->AllocMem(S_SIZE_T(sizeof(InterfaceInfo_t)) * S_SIZE_T(pMTData->cInterfaceMap)));

        // Copy the interface map
        for (DWORD i = 0; i < pMTData->cInterfaceMap; i++)
            pMTData->pInterfaceMap[i] = pParentMTData->pInterfaceMap[i];
    }

    return pMTData;
}

//---------------------------------------------------------------------------------------
VOID MethodTableBuilder::BuildInteropVTable_InterfaceList(
        BuildingInterfaceInfo_t **ppBuildingInterfaceList,
        WORD *pcBuildingInterfaceList)
{
    STANDARD_VM_CONTRACT;

    // Initialize arguments
    *pcBuildingInterfaceList = 0;
    *ppBuildingInterfaceList = NULL;

    // Get the thread for stacking allocator
    Thread *pThread = GetThread();

    // Get the metadata for enumerating the interfaces of the class
    IMDInternalImport *pMDImport = GetModule()->GetMDImport();

    // Now load all the interfaces
    HENUMInternalHolder hEnumInterfaceImpl(pMDImport);
    hEnumInterfaceImpl.EnumInit(mdtInterfaceImpl, GetCl());

    // Get the count for the number of interfaces from metadata
    DWORD cAllInterfaces = pMDImport->EnumGetCount(&hEnumInterfaceImpl);
    WORD cNonGenericItfs = 0;

    // Iterate through each interface token and get the type for the interface and put
    // it into the BuildingInterfaceInfo_t struct.
    if (cAllInterfaces != 0)
    {
        mdInterfaceImpl ii;
        Module *pModule = GetModule();

        // Allocate the BuildingInterfaceList table
        *ppBuildingInterfaceList = new(GetStackingAllocator()) BuildingInterfaceInfo_t[cAllInterfaces];
        BuildingInterfaceInfo_t *pInterfaceBuildInfo = *ppBuildingInterfaceList;

        while (pMDImport->EnumNext(&hEnumInterfaceImpl, &ii))
        {
            mdTypeRef crInterface;
            TypeHandle intType;
            
            // Get properties on this interface
            if (FAILED(pMDImport->GetTypeOfInterfaceImpl(ii, &crInterface)))
            {
                BuildMethodTableThrowException(IDS_CLASSLOAD_BADFORMAT);
            }
            SigTypeContext typeContext = SigTypeContext(TypeHandle(GetHalfBakedMethodTable()));
            intType = ClassLoader::LoadTypeDefOrRefOrSpecThrowing(pModule, crInterface, &typeContext,
                                                                  ClassLoader::ThrowIfNotFound, 
                                                                  ClassLoader::FailIfUninstDefOrRef);

            // At this point, the interface should never have any non instantiated generic parameters.
            _ASSERTE(!intType.IsGenericTypeDefinition());

            // Skip any generic interfaces.
            if (intType.GetNumGenericArgs() != 0)
                continue;

            pInterfaceBuildInfo[cNonGenericItfs].m_pMethodTable = intType.AsMethodTable();
            _ASSERTE(pInterfaceBuildInfo[cNonGenericItfs].m_pMethodTable != NULL);
            _ASSERTE(pInterfaceBuildInfo[cNonGenericItfs].m_pMethodTable->IsInterface());
            cNonGenericItfs++;
        }
        _ASSERTE(cNonGenericItfs <= cAllInterfaces);
    }

    *pcBuildingInterfaceList = cNonGenericItfs;
}

//---------------------------------------------------------------------------------------
// Used by BuildInteropVTable
//
// Determine vtable placement for each member in this class
//

#ifdef _PREFAST_
#pragma warning(push)
#pragma warning(disable:21000) // Suppress PREFast warning about overly large function
#endif
VOID MethodTableBuilder::BuildInteropVTable_PlaceMembers(
    bmtTypeInfo* bmtType,
                           DWORD numDeclaredInterfaces,
                           BuildingInterfaceInfo_t *pBuildingInterfaceList, 
    bmtMethodInfo* bmtMethod,
                           bmtErrorInfo* bmtError, 
                           bmtProperties* bmtProp, 
                           bmtParentInfo* bmtParent, 
                           bmtInterfaceInfo* bmtInterface, 
                           bmtMethodImplInfo* bmtMethodImpl,
                           bmtVtable* bmtVT)
{
    CONTRACTL
    {
        STANDARD_VM_CHECK;
        PRECONDITION(CheckPointer(this));
        PRECONDITION(CheckPointer(bmtType));
        PRECONDITION(CheckPointer(bmtMethod));
        PRECONDITION(CheckPointer(bmtError));
        PRECONDITION(CheckPointer(bmtProp));
        PRECONDITION(CheckPointer(bmtInterface));
        PRECONDITION(CheckPointer(bmtParent));
        PRECONDITION(CheckPointer(bmtMethodImpl));
        PRECONDITION(CheckPointer(bmtVT));
    }
    CONTRACTL_END;

    _ASSERTE(!IsInterface());

    Module * pModule = GetModule();

#ifdef _DEBUG
    LPCUTF8 pszDebugName,pszDebugNamespace;
    if (FAILED(bmtType->pModule->GetMDImport()->GetNameOfTypeDef(GetCl(), &pszDebugName, &pszDebugNamespace)))
    {
        pszDebugName = pszDebugNamespace = "Invalid TypeDef record";
    }
#endif // _DEBUG

    HRESULT hr = S_OK;
    DWORD i, j;
    DWORD  dwClassDeclFlags = 0xffffffff;
    DWORD  dwClassNullDeclFlags = 0xffffffff;

    for (i = 0; i < NumDeclaredMethods(); i++)
    {
        LPCUTF8     szMemberName = NULL;
        PCCOR_SIGNATURE pMemberSignature = NULL;
        DWORD       cMemberSignature = 0;
        mdToken     tokMember;
        DWORD       dwMemberAttrs;
        DWORD       dwDescrOffset;
        DWORD       dwImplFlags;
        BOOL        fMethodImplementsInterface = FALSE;
        DWORD       dwMDImplementsInterfaceNum = 0;
        DWORD       dwMDImplementsSlotNum = 0;
        DWORD       dwParentAttrs;

        tokMember = bmtMethod->rgMethodTokens[i];
        dwMemberAttrs = bmtMethod->rgMethodAttrs[i];
        dwDescrOffset = bmtMethod->rgMethodRVA[i];
        dwImplFlags = bmtMethod->rgMethodImplFlags[i];

        DWORD Classification = bmtMethod->rgMethodClassifications[i];

        // If this member is a method which overrides a parent method, it will be set to non-NULL
        MethodDesc *pParentMethodDesc = NULL;

        szMemberName = bmtMethod->rgszMethodName[i];

        // constructors and class initialisers are special
        if (!IsMdRTSpecialName(dwMemberAttrs))
        { 
            // The method does not have the special marking
            if (IsMdVirtual(dwMemberAttrs)) 
            {
                // Hash that a method with this name exists in this class
                // Note that ctors and static ctors are not added to the table
                DWORD dwHashName = HashStringA(szMemberName);

                // If the member is marked with a new slot we do not need to find it
                // in the parent
                if (!IsMdNewSlot(dwMemberAttrs)) 
                {
                    // If we're not doing sanity checks, then assume that any method declared static
                    // does not attempt to override some virtual parent.
                    if (!IsMdStatic(dwMemberAttrs) && bmtParent->pParentMethodTable != NULL)
                    {
                        // Attempt to find the method with this name and signature in the parent class.
                        // This method may or may not create pParentMethodHash (if it does not already exist).
                        // It also may or may not fill in pMemberSignature/cMemberSignature. 
                        // An error is only returned when we can not create the hash.
                        // NOTE: This operation touches metadata
                        {
                            BOOL fMethodConstraintsMatch = FALSE; 
                            VERIFY(SUCCEEDED(LoaderFindMethodInClass(
                                                          szMemberName, 
                                                          bmtType->pModule, 
                                                          tokMember, 
                                                          &pParentMethodDesc, 
                                                          &pMemberSignature, &cMemberSignature,
                                                          dwHashName,
                                                          &fMethodConstraintsMatch)));
                            //this assert should hold because interop methods cannot be generic
                            _ASSERTE(pParentMethodDesc == NULL || fMethodConstraintsMatch);
                        }

                        if (pParentMethodDesc != NULL)
                        {
                            dwParentAttrs = pParentMethodDesc->GetAttrs();

                            _ASSERTE(IsMdVirtual(dwParentAttrs) && "Non virtual methods should not be searched");
                            _ASSERTE(!(IsMdFinal(dwParentAttrs)));
                        }
                    }
                }
            }
        }

        if(pParentMethodDesc == NULL) {
            // This method does not exist in the parent.  If we are a class, check whether this
            // method implements any interface.  If true, we can't place this method now.
            if ((!IsInterface()) &&
                (   IsMdPublic(dwMemberAttrs) &&
                    IsMdVirtual(dwMemberAttrs) &&
                    !IsMdStatic(dwMemberAttrs) &&
                    !IsMdRTSpecialName(dwMemberAttrs))) {

                // Don't check parent class interfaces - if the parent class had to implement an interface,
                // then it is already guaranteed that we inherited that method.
                _ASSERTE(!bmtParent->pParentMethodTable || bmtParent->pParentMethodTable->LookupComInteropData());
                DWORD numInheritedInts = (bmtParent->pParentMethodTable ?
                    (DWORD) bmtParent->pParentMethodTable->LookupComInteropData()->cInterfaceMap: 0);

                for (j = numInheritedInts; j < bmtInterface->wInterfaceMapSize; j++)
                {
                    MethodTable *pInterface = bmtInterface->pInterfaceMap[j].m_pMethodTable;
                    if (pMemberSignature == NULL)
                    {   // We've been trying to avoid asking for the signature - now we need it
                        if (FAILED(bmtType->pMDImport->GetSigOfMethodDef(tokMember, &cMemberSignature, &pMemberSignature)))
                        {
                            BuildMethodTableThrowException(IDS_CLASSLOAD_BADFORMAT);
                        }
                    }

                    WORD slotNum = (WORD) (-1);
                    MethodDesc *pItfMD = MemberLoader::FindMethod(pInterface, 
                        szMemberName, pMemberSignature, cMemberSignature, bmtType->pModule);

                    if (pItfMD != NULL)
                    {
                        // This method implements an interface - don't place it
                        fMethodImplementsInterface = TRUE;

                        // Keep track of this fact and use it while placing the interface
                        slotNum = (WORD) pItfMD->GetSlot();
                        if (bmtInterface->pppInterfaceImplementingMD[j] == NULL)
                        {
                            bmtInterface->pppInterfaceImplementingMD[j] = new (GetStackingAllocator()) MethodDesc * [pInterface->GetNumVirtuals()];
                            memset(bmtInterface->pppInterfaceImplementingMD[j], 0, sizeof(MethodDesc *) * pInterface->GetNumVirtuals());

                            bmtInterface->pppInterfaceDeclaringMD[j] = new (GetStackingAllocator()) MethodDesc * [pInterface->GetNumVirtuals()];
                            memset(bmtInterface->pppInterfaceDeclaringMD[j], 0, sizeof(MethodDesc *) * pInterface->GetNumVirtuals());
                        }

                        bmtInterface->pppInterfaceDeclaringMD[j][slotNum] = pItfMD;

                        dwMDImplementsInterfaceNum = j;
                        dwMDImplementsSlotNum = slotNum;
                        break;
                    }
                }
            }
        }

        // Now find the MethodDesc associated with this method
        MethodDesc *pNewMD = MemberLoader::FindMethod(GetHalfBakedMethodTable(), tokMember);
        _ASSERTE(!bmtVT->pInteropData->Exists(pNewMD));
        InteropMethodTableSlotData *pNewMDData = bmtVT->pInteropData->GetData(pNewMD);

        _ASSERTE(pNewMD != NULL);
        _ASSERTE(dwMemberAttrs == pNewMD->GetAttrs());

        _ASSERTE(bmtParent->ppParentMethodDescBufPtr != NULL);
        _ASSERTE(((bmtParent->ppParentMethodDescBufPtr - bmtParent->ppParentMethodDescBuf) / sizeof(MethodDesc*))
                  < NumDeclaredMethods());
        *(bmtParent->ppParentMethodDescBufPtr++) = pParentMethodDesc;
        *(bmtParent->ppParentMethodDescBufPtr++) = pNewMD;

        if (fMethodImplementsInterface  && IsMdVirtual(dwMemberAttrs))
        {
            bmtInterface->pppInterfaceImplementingMD[dwMDImplementsInterfaceNum][dwMDImplementsSlotNum] = pNewMD;
        }

        // Set the MethodDesc value
        bmtMethod->ppMethodDescList[i] = pNewMD;

        // Make sure that fcalls have a 0 rva.  This is assumed by the prejit fixup logic
        _ASSERTE(((Classification & ~mdcMethodImpl) != mcFCall) || dwDescrOffset == 0);

        // Non-virtual method
        if (IsMdStatic(dwMemberAttrs) ||
            !IsMdVirtual(dwMemberAttrs) ||
            IsMdRTSpecialName(dwMemberAttrs))
        {
            // Non-virtual method (doesn't go into the vtable)
            _ASSERTE(bmtVT->pNonVtableMD[bmtVT->wCurrentNonVtableSlot] == NULL);

            // Set the data for the method
            pNewMDData->wSlot = bmtVT->wCurrentNonVtableSlot;

            // Add the slot into the non-virtual method table
            bmtVT->pNonVtableMD[bmtVT->wCurrentNonVtableSlot] = pNewMD;
            bmtVT->ppSDNonVtable[bmtVT->wCurrentNonVtableSlot] = pNewMDData;

            // Increment the current non-virtual method table slot
            bmtVT->wCurrentNonVtableSlot++;
        }

        // Virtual method
        else
        {
            if (IsInterface())
            {   // (shouldn't happen for this codepath)
                UNREACHABLE();
            }

            else if (pParentMethodDesc != NULL)
            {   // We are overriding a parent's vtable slot
                CONSISTENCY_CHECK(bmtVT->pInteropData->Exists(pParentMethodDesc));
                WORD slotNumber = bmtVT->pInteropData->GetData(pParentMethodDesc)->wSlot;

                // If the MethodDesc was inherited by an interface but not implemented,
                // then the interface's MethodDesc is sitting in the slot and will not reflect
                // the true slot number. Need to find the starting slot of the interface in
                // the parent class to figure out the true slot (starting slot + itf slot)
                if (pParentMethodDesc->IsInterface())
                {
                    MethodTable *pItfMT = pParentMethodDesc->GetMethodTable();
                    WORD startSlot = bmtParent->pParentMethodTable->LookupComInteropData()->GetStartSlotForInterface(pItfMT);
                    _ASSERTE(startSlot != (WORD) -1);
                    slotNumber += startSlot;
                }

                // we are overriding a parent method, so place this method now
                bmtVT->SetMethodDescForSlot(slotNumber, pNewMD);
                bmtVT->ppSDVtable[slotNumber] = pNewMDData;

                pNewMDData->wSlot = slotNumber;
            }

            else if (!fMethodImplementsInterface)
            {   // Place it unless we will do it when laying out an interface or it is a body to
            // a method impl. If it is an impl then we will use the slots used by the definition.

                // Store the slot for this method
                pNewMDData->wSlot = bmtVT->wCurrentVtableSlot;

                // Now copy the method into the vtable, and interop data
                bmtVT->SetMethodDescForSlot(bmtVT->wCurrentVtableSlot, pNewMD);
                bmtVT->ppSDVtable[bmtVT->wCurrentVtableSlot] = pNewMDData;

                // Increment current vtable slot, since we're not overriding a parent slot
                bmtVT->wCurrentVtableSlot++;
            }
        }

        if(Classification & mdcMethodImpl)
        {   // If this method serves as the BODY of a MethodImpl specification, then
        // we should iterate all the MethodImpl's for this class and see just how many
        // of them this method participates in as the BODY.
            for(DWORD m = 0; m < bmtMethodImpl->dwNumberMethodImpls; m++)
            {
                if(tokMember == bmtMethodImpl->rgMethodImplTokens[m].methodBody)
                {
                    MethodDesc* desc = NULL;
                    mdToken mdDecl = bmtMethodImpl->rgMethodImplTokens[m].methodDecl;
                    Substitution *pDeclSubst = &bmtMethodImpl->pMethodDeclSubsts[m];

                    // Get the parent
                    mdToken tkParent = mdTypeDefNil;
                    if (TypeFromToken(mdDecl) == mdtMethodDef || TypeFromToken(mdDecl) == mdtMemberRef)
                    {
                        hr = bmtType->pMDImport->GetParentToken(mdDecl,&tkParent);
                        if (FAILED(hr))
                        {
                            BuildMethodTableThrowException(hr, *bmtError);
                        }
                    }

                    if (GetCl() == tkParent)
                    {   // The DECL has been declared
                    // within the class that we're currently building.
                        hr = S_OK;

                        if(bmtError->pThrowable != NULL)
                            *(bmtError->pThrowable) = NULL;

                        // <TODO>Verify that the substitution doesn't change for this case </TODO>
                        if(TypeFromToken(mdDecl) != mdtMethodDef) {
                            hr = FindMethodDeclarationForMethodImpl(
                                        bmtType->pMDImport,
                                        GetCl(),
                                        mdDecl,
                                        &mdDecl);
                            _ASSERTE(SUCCEEDED(hr));

                            // Make sure the virtual states are the same
                            DWORD dwDescAttrs;
                            if (FAILED(bmtType->pMDImport->GetMethodDefProps(mdDecl, &dwDescAttrs)))
                            {
                                BuildMethodTableThrowException(IDS_CLASSLOAD_BADFORMAT);
                            }
                            _ASSERTE(IsMdVirtual(dwMemberAttrs) == IsMdVirtual(dwDescAttrs));
                        }
                    }
                    else
                    {
                        SigTypeContext typeContext;

                        desc = MemberLoader::GetMethodDescFromMemberDefOrRefOrSpec(bmtType->pModule,
                                                                               mdDecl,
                                                                               &typeContext,
                                                                               FALSE, FALSE); // don't demand generic method args
                        mdDecl = mdTokenNil;
                        // Make sure the body is virtaul
                        _ASSERTE(IsMdVirtual(dwMemberAttrs));
                    }

                    // Only add the method impl if the interface it is declared on is non generic.
                    // NULL desc represent method impls to methods on the current class which
                    // we know isn't generic.
                    if ((desc == NULL) || (desc->GetMethodTable()->GetNumGenericArgs() == 0))
                    {
                        bmtMethodImpl->AddMethod(pNewMD,
                                                 desc,
                                                 mdDecl,
                                                 pDeclSubst);
                    }
                }
            }
        }
    } /* end ... for each member */
}

#ifdef _PREFAST_
#pragma warning(pop)
#endif

//---------------------------------------------------------------------------------------
// Resolve unresolved interfaces, determine an upper bound on the size of the interface map,
// and determine the size of the largest interface (in # slots)
VOID MethodTableBuilder::BuildInteropVTable_ResolveInterfaces(
                                BuildingInterfaceInfo_t *pBuildingInterfaceList, 
                                bmtTypeInfo* bmtType, 
                                bmtInterfaceInfo* bmtInterface, 
                                bmtVtable* bmtVT, 
                                bmtParentInfo* bmtParent, 
                                const bmtErrorInfo & bmtError)
{

    CONTRACTL
    {
        STANDARD_VM_CHECK;
        PRECONDITION(CheckPointer(this));
        PRECONDITION(CheckPointer(bmtInterface));
        PRECONDITION(CheckPointer(bmtVT));
        PRECONDITION(CheckPointer(bmtParent));
    }
    CONTRACTL_END;

    HRESULT hr = S_OK;
    DWORD i;
    Thread *pThread = GetThread();

    // resolve unresolved interfaces, determine an upper bound on the size of the interface map,
    // and determine the size of the largest interface (in # slots)
    bmtInterface->dwMaxExpandedInterfaces = 0; // upper bound on max # interfaces implemented by this class

    // First look through the interfaces explicitly declared by this class
    for (i = 0; i < bmtInterface->wInterfaceMapSize; i++)
    {
        MethodTable *pInterface = pBuildingInterfaceList[i].m_pMethodTable;

        bmtInterface->dwMaxExpandedInterfaces += (1+ pInterface->GetNumInterfaces());
    }

    // Now look at interfaces inherited from the parent
    if (bmtParent->pParentMethodTable != NULL)
    {
        _ASSERTE(bmtParent->pParentMethodTable->LookupComInteropData());
        InteropMethodTableData *pInteropData = bmtParent->pParentMethodTable->LookupComInteropData();
        InterfaceInfo_t *pParentInterfaceMap = pInteropData->pInterfaceMap;

        for (i = 0; i < pInteropData->cInterfaceMap; i++)
        {
            MethodTable *pInterface = pParentInterfaceMap[i].m_pMethodTable;

            bmtInterface->dwMaxExpandedInterfaces += (1+pInterface->GetNumInterfaces());
        }
    }

    // Create a fully expanded map of all interfaces we implement
    bmtInterface->pInterfaceMap = new (GetStackingAllocator()) InterfaceInfo_t[bmtInterface->dwMaxExpandedInterfaces];

    // # slots of largest interface
    bmtInterface->dwLargestInterfaceSize = 0;

    DWORD dwNumDeclaredInterfaces = bmtInterface->wInterfaceMapSize;

    BuildInteropVTable_CreateInterfaceMap(pBuildingInterfaceList, bmtInterface, &bmtInterface->wInterfaceMapSize, &bmtInterface->dwLargestInterfaceSize, bmtParent->pParentMethodTable);

    _ASSERTE(bmtInterface->wInterfaceMapSize <= bmtInterface->dwMaxExpandedInterfaces);

    if (bmtInterface->dwLargestInterfaceSize > 0)
    {
        // This is needed later - for each interface, we get the MethodDesc pointer for each
        // method.  We need to be able to persist at most one interface at a time, so we
        // need enough memory for the largest interface.
        bmtInterface->ppInterfaceMethodDescList = new (GetStackingAllocator()) MethodDesc*[bmtInterface->dwLargestInterfaceSize];

        bmtInterface->ppInterfaceDeclMethodDescList = new (GetStackingAllocator()) MethodDesc*[bmtInterface->dwLargestInterfaceSize];
    }

    EEClass *pParentClass = (IsInterface() || bmtParent->pParentMethodTable == NULL) ? NULL : bmtParent->pParentMethodTable->GetClass();

    // For all the new interfaces we bring in, sum the methods
    bmtInterface->dwTotalNewInterfaceMethods = 0;
    if (pParentClass != NULL)
    {
        for (i = bmtParent->pParentMethodTable->GetNumInterfaces(); i < (bmtInterface->wInterfaceMapSize); i++)
            bmtInterface->dwTotalNewInterfaceMethods += 
                bmtInterface->pInterfaceMap[i].m_pMethodTable->GetNumVirtuals();
    }

    // The interface map is probably smaller than dwMaxExpandedInterfaces, so we'll copy the
    // appropriate number of bytes when we allocate the real thing later.

    // Inherit parental slot counts
    if (pParentClass != NULL)
    {
        InteropMethodTableData *pParentInteropMT = bmtParent->pParentMethodTable->LookupComInteropData();
        bmtVT->wCurrentVtableSlot         = pParentInteropMT->cVTable;
        bmtParent->wNumParentInterfaces   = pParentInteropMT->cInterfaceMap;
    }
    else
    {
        bmtVT->wCurrentVtableSlot          = 0;
        bmtParent->wNumParentInterfaces   = 0;
    }

    bmtVT->wCurrentNonVtableSlot      = 0;

    bmtInterface->pppInterfaceImplementingMD = (MethodDesc ***) GetStackingAllocator()->Alloc(S_UINT32(sizeof(MethodDesc *)) * S_UINT32(bmtInterface->dwMaxExpandedInterfaces));
    memset(bmtInterface->pppInterfaceImplementingMD, 0, sizeof(MethodDesc *) * bmtInterface->dwMaxExpandedInterfaces);

    bmtInterface->pppInterfaceDeclaringMD = (MethodDesc ***) GetStackingAllocator()->Alloc(S_UINT32(sizeof(MethodDesc *)) * S_UINT32(bmtInterface->dwMaxExpandedInterfaces));
    memset(bmtInterface->pppInterfaceDeclaringMD, 0, sizeof(MethodDesc *) * bmtInterface->dwMaxExpandedInterfaces);

    return;

}

//---------------------------------------------------------------------------------------
// Fill out a fully expanded interface map, such that if we are declared to implement I3, and I3 extends I1,I2,
// then I1,I2 are added to our list if they are not already present.
//
// Returns FALSE for failure.  <TODO>Currently we don't fail, but @TODO perhaps we should fail if we recurse
// too much.</TODO>
//
VOID MethodTableBuilder::BuildInteropVTable_CreateInterfaceMap(BuildingInterfaceInfo_t *pBuildingInterfaceList,
                                                    bmtInterfaceInfo* bmtInterface,
                                                    WORD *pwInterfaceListSize,
                                                    DWORD *pdwMaxInterfaceMethods,
                                                    MethodTable *pParentMethodTable)
{
    STANDARD_VM_CONTRACT;

    WORD    i;
    InterfaceInfo_t *pInterfaceMap = bmtInterface->pInterfaceMap;
    WORD wNumInterfaces = bmtInterface->wInterfaceMapSize;

    // pdwInterfaceListSize points to bmtInterface->pInterfaceMapSize so we cache it above
    *pwInterfaceListSize = 0;

    // First inherit all the parent's interfaces.  This is important, because our interface map must
    // list the interfaces in identical order to our parent.
    //
    // <NICE> we should document the reasons why.  One reason is that DispatchMapTypeIDs can be indexes
    // into the list </NICE>
    if (pParentMethodTable != NULL)
    {
        _ASSERTE(pParentMethodTable->LookupComInteropData());
        InteropMethodTableData *pInteropData = pParentMethodTable->LookupComInteropData();
        InterfaceInfo_t *pParentInterfaceMap = pInteropData->pInterfaceMap;
        unsigned cParentInterfaceMap = pInteropData->cInterfaceMap;

        // The parent's interface list is known to be fully expanded
        for (i = 0; i < cParentInterfaceMap; i++)
        {
            // Need to keep track of the interface with the largest number of methods
            if (pParentInterfaceMap[i].m_pMethodTable->GetNumVirtuals() > *pdwMaxInterfaceMethods)
            {
                *pdwMaxInterfaceMethods = pParentInterfaceMap[i].m_pMethodTable->GetNumVirtuals();
            }

            pInterfaceMap[*pwInterfaceListSize].m_pMethodTable = pParentInterfaceMap[i].m_pMethodTable;
            pInterfaceMap[*pwInterfaceListSize].SetInteropStartSlot(MethodTable::NO_SLOT);
            pInterfaceMap[*pwInterfaceListSize].m_wFlags = 0;
            (*pwInterfaceListSize)++;
        }
    }

    // Go through each interface we explicitly implement (if a class), or extend (if an interface)
    for (i = 0; i < wNumInterfaces; i++)
    {
        MethodTable *pDeclaredInterface = pBuildingInterfaceList[i].m_pMethodTable;

        BuildInteropVTable_ExpandInterface(pInterfaceMap, pDeclaredInterface,
                                           pwInterfaceListSize, pdwMaxInterfaceMethods,
                                           TRUE);
    }
}

//---------------------------------------------------------------------------------------
// Given an interface map to fill out, expand pNewInterface (and its sub-interfaces) into it, increasing
// pdwInterfaceListSize as appropriate, and avoiding duplicates.
//
VOID MethodTableBuilder::BuildInteropVTable_ExpandInterface(InterfaceInfo_t *pInterfaceMap, 
                              MethodTable *pNewInterface, 
                              WORD *pwInterfaceListSize, 
                              DWORD *pdwMaxInterfaceMethods,
                              BOOL fDirect)
{
    STANDARD_VM_CONTRACT;

    DWORD i;

    // The interface list contains the fully expanded set of interfaces from the parent then
    // we start adding all the interfaces we declare. We need to know which interfaces
    // we declare but do not need duplicates of the ones we declare. This means we can
    // duplicate our parent entries.

    // Is it already present in the list?
    for (i = 0; i < (*pwInterfaceListSize); i++) {
        if (pInterfaceMap[i].m_pMethodTable->IsEquivalentTo(pNewInterface)) {
            if(fDirect) {
                pInterfaceMap[i].m_wFlags |= InterfaceInfo_t::interface_declared_on_class;
            }
            return; // found it, don't add it again
        }
    }

    if (pNewInterface->GetNumVirtuals() > *pdwMaxInterfaceMethods) {
        *pdwMaxInterfaceMethods = pNewInterface->GetNumVirtuals();
    }

    // Add it and each sub-interface
    pInterfaceMap[*pwInterfaceListSize].m_pMethodTable = pNewInterface;
    pInterfaceMap[*pwInterfaceListSize].SetInteropStartSlot(MethodTable::NO_SLOT);
    pInterfaceMap[*pwInterfaceListSize].m_wFlags = 0;

    if(fDirect)
        pInterfaceMap[*pwInterfaceListSize].m_wFlags |= InterfaceInfo_t::interface_declared_on_class;

    (*pwInterfaceListSize)++;

    if (pNewInterface->GetNumInterfaces() != 0) {
        MethodTable::InterfaceMapIterator it = pNewInterface->IterateInterfaceMap();
        while (it.Next()) {
            BuildInteropVTable_ExpandInterface(pInterfaceMap, it.GetInterface(),
                                               pwInterfaceListSize, pdwMaxInterfaceMethods, FALSE);
        }
    }

    return;
}

// If we are a class, then there may be some unplaced vtable methods (which are by definition
// interface methods, otherwise they'd already have been placed).  Place as many unplaced methods
// as possible, in the order preferred by interfaces.  However, do not allow any duplicates - once
// a method has been placed, it cannot be placed again - if we are unable to neatly place an interface,
// create duplicate slots for it starting at dwCurrentDuplicateVtableSlot.  Fill out the interface
// map for all interfaces as they are placed.
//
// If we are an interface, then all methods are already placed.  Fill out the interface map for
// interfaces as they are placed.
//

//---------------------------------------------------------------------------------------
VOID MethodTableBuilder::BuildInteropVTable_PlaceVtableMethods(
    bmtInterfaceInfo* bmtInterface, 
                                                       DWORD numDeclaredInterfaces,
                                                       BuildingInterfaceInfo_t *pBuildingInterfaceList,                
                                                       bmtVtable* bmtVT, 
    bmtMethodInfo* bmtMethod,
    bmtTypeInfo* bmtType,
                                                       bmtErrorInfo* bmtError, 
                                                       bmtProperties* bmtProp, 
                                                       bmtParentInfo* bmtParent)
{
    STANDARD_VM_CONTRACT;

    DWORD i;
    BOOL fParentInterface;
    
    for (WORD wCurInterface = 0; 
         wCurInterface < bmtInterface->wInterfaceMapSize; 
         wCurInterface++)
    {
        fParentInterface = FALSE;
        // Keep track of the current interface
        InterfaceInfo_t *pCurItfInfo = &(bmtInterface->pInterfaceMap[wCurInterface]);
        // The interface we are attempting to place
        MethodTable *pInterface = pCurItfInfo->m_pMethodTable;

        // Did we place this interface already due to the parent class's interface placement?
        if (pCurItfInfo->GetInteropStartSlot() != MethodTable::NO_SLOT)
        {
            // If we have declared it then we re-lay it out
            if(pCurItfInfo->IsDeclaredOnClass())
            {
                // This should be in the outer IF statement, not this inner one, but we'll keep
                // it this way to remain consistent for backward compatibility.
                fParentInterface = TRUE;

                // If the interface is folded into the non-interface portion of the vtable, we need to unfold it.
                WORD wStartSlot = pCurItfInfo->GetInteropStartSlot();
                MethodTable::MethodIterator it(pInterface);
                for (; it.IsValid(); it.Next())
                {
                    if (it.IsVirtual())
                    {
                        if(bmtVT->ppSDVtable[wStartSlot+it.GetSlotNumber()]->wSlot == wStartSlot+it.GetSlotNumber())
                        {   // If the MD slot is equal to the vtable slot number, then this means the interface
                    // was folded into the non-interface part of the vtable and needs to get unfolded
                    // in case a specific override occurs for one of the conceptually two distinct
                    // slots and not the other (i.e., a MethodImpl overrides an interface method but not
                    // the class' virtual method).
                            pCurItfInfo->SetInteropStartSlot(MethodTable::NO_SLOT);
                            fParentInterface = FALSE;
                            break;
                        }
                    }
                }
            }
            else
            {
                continue;
            }
        }

        if (pInterface->GetNumVirtuals() == 0)
        {
            // no calls can be made to this interface anyway
            // so initialize the slot number to 0
            pCurItfInfo->SetInteropStartSlot((WORD) 0);
            continue;
        }

        // If this interface has not been given a starting position do that now.
        if(!fParentInterface) 
            pCurItfInfo->SetInteropStartSlot(bmtVT->wCurrentVtableSlot);

        // For each method declared in this interface
        {
            MethodTable::MethodIterator it(pInterface);
            for (; it.IsValid(); it.Next())
            {
                if (it.IsVirtual())
                {
                    DWORD       dwMemberAttrs;

                    // See if we have info gathered while placing members
                    if (bmtInterface->pppInterfaceImplementingMD[wCurInterface] && bmtInterface->pppInterfaceImplementingMD[wCurInterface][it.GetSlotNumber()] != NULL)
                    {
                        bmtInterface->ppInterfaceMethodDescList[it.GetSlotNumber()] = bmtInterface->pppInterfaceImplementingMD[wCurInterface][it.GetSlotNumber()];
                        bmtInterface->ppInterfaceDeclMethodDescList[it.GetSlotNumber()] = bmtInterface->pppInterfaceDeclaringMD[wCurInterface][it.GetSlotNumber()];
                        continue;
                    }

                    MethodDesc *pInterfaceMD = pInterface->GetMethodDescForSlot(it.GetSlotNumber());
                    _ASSERTE(pInterfaceMD  != NULL);

                    LPCUTF8     pszInterfaceMethodName  = pInterfaceMD->GetNameOnNonArrayClass();
                    PCCOR_SIGNATURE pInterfaceMethodSig;
                    DWORD       cInterfaceMethodSig;

                    pInterfaceMD->GetSig(&pInterfaceMethodSig, &cInterfaceMethodSig);

                    // Try to find the method explicitly declared in our class
                    for (i = 0; i < NumDeclaredMethods(); i++)
                    {
                        // look for interface method candidates only
                        dwMemberAttrs = bmtMethod->rgMethodAttrs[i];

                        // Note that non-publics can legally be exposed via an interface.
                        if (IsMdVirtual(dwMemberAttrs) && IsMdPublic(dwMemberAttrs))
                        {
                            LPCUTF8     pszMemberName;

                            pszMemberName = bmtMethod->rgszMethodName[i];
                            _ASSERTE(!(pszMemberName == NULL));

#ifdef _DEBUG
                            if(GetHalfBakedClass()->m_fDebuggingClass && g_pConfig->ShouldBreakOnMethod(pszMemberName))
                                CONSISTENCY_CHECK_MSGF(false, ("BreakOnMethodName: '%s' ", pszMemberName));
#endif // _DEBUG

                            if (strcmp(pszMemberName,pszInterfaceMethodName) == 0)
                            {
                                PCCOR_SIGNATURE pMemberSignature;
                                DWORD       cMemberSignature;

                                _ASSERTE(TypeFromToken(bmtMethod->rgMethodTokens[i]) == mdtMethodDef);
                                if (FAILED(bmtType->pMDImport->GetSigOfMethodDef(
                                    bmtMethod->rgMethodTokens[i], 
                                    &cMemberSignature, 
                                    &pMemberSignature)))
                                {
                                    BuildMethodTableThrowException(IDS_CLASSLOAD_BADFORMAT);
                                }

                                if (MetaSig::CompareMethodSigs(
                                    pMemberSignature,
                                    cMemberSignature,
                                    bmtType->pModule, NULL,
                                    pInterfaceMethodSig,
                                    cInterfaceMethodSig,
                                    pInterfaceMD->GetModule(), NULL))
                                {   // Found match, break from loop
                                    break;
                                }
                            }
                        }
                    } // end ... try to find method
                    
                    _ASSERTE(it.GetSlotNumber() < bmtInterface->dwLargestInterfaceSize);
                    
                    if (i >= NumDeclaredMethods())
                    {
                        // if this interface has been layed out by our parent then
                        // we do not need to define a new method desc for it
                        if(fParentInterface) 
                        {
                            bmtInterface->ppInterfaceMethodDescList[it.GetSlotNumber()] = NULL;
                            bmtInterface->ppInterfaceDeclMethodDescList[it.GetSlotNumber()] = NULL;
                        }
                        else 
                        {
                            // We will use the interface implemenation if we do not find one in the 
                            // parent. It will have to be overriden by the a method impl unless the 
                            // class is abstract or it is a special COM type class.

                            MethodDesc* pParentMD = NULL;
                            if(bmtParent->pParentMethodTable)
                            {
#ifdef _DEBUG
                                if(GetHalfBakedClass()->m_fDebuggingClass && g_pConfig->ShouldBreakOnMethod(pszInterfaceMethodName))
                                    CONSISTENCY_CHECK_MSGF(false, ("BreakOnMethodName: '%s' ", pszInterfaceMethodName));
#endif // _DEBUG
                                // Check the parent class
                                pParentMD = MemberLoader::FindMethod(bmtParent->pParentMethodTable,
                                    pszInterfaceMethodName,
                                                                     pInterfaceMethodSig,
                                                                     cInterfaceMethodSig,
                                                                     pInterfaceMD->GetModule(), 
                                                                     MemberLoader::FM_Default, 
                                                                     &bmtParent->parentSubst);                        
                            }
                            // make sure we do a better back patching for these methods
                            if(pParentMD && IsMdVirtual(pParentMD->GetAttrs()))
                            {
                                bmtInterface->ppInterfaceMethodDescList[it.GetSlotNumber()] = pParentMD;
                                bmtInterface->ppInterfaceDeclMethodDescList[it.GetSlotNumber()] = pInterfaceMD;
                            }
                            else
                            {
                                bmtInterface->ppInterfaceMethodDescList[it.GetSlotNumber()] = pInterfaceMD;
                                bmtVT->pInteropData->GetData(pInterfaceMD)->wSlot = pInterfaceMD->GetSlot();
                                bmtInterface->ppInterfaceDeclMethodDescList[it.GetSlotNumber()] = NULL;
                            }
                        }
                    }
                    else
                    {
                        // Found as declared method in class. If the interface was layed out by the parent we 
                        // will be overridding their slot so our method counts do not increase. We will fold
                        // our method into our parent's interface if we have not been placed.
                        if(fParentInterface)
                        {
                            WORD dwSlot = (WORD) (pCurItfInfo->GetInteropStartSlot() + it.GetSlotNumber());
                            _ASSERTE(bmtVT->wCurrentVtableSlot > dwSlot);
                            MethodDesc *pMD = bmtMethod->ppMethodDescList[i];
                            InteropMethodTableSlotData *pMDData = bmtVT->pInteropData->GetData(pMD);
                            _ASSERTE(pMD && "Missing MethodDesc for declared method in class.");
                            if(pMDData->wSlot == MethodTable::NO_SLOT)
                            {
                                pMDData->wSlot = dwSlot;
                            }

                            // Set the slot and interop data
                            bmtVT->SetMethodDescForSlot(dwSlot, pMD);
                            bmtVT->ppSDVtable[dwSlot] = pMDData;
                            _ASSERTE( bmtVT->GetMethodDescForSlot(dwSlot) != NULL);
                            bmtInterface->ppInterfaceMethodDescList[it.GetSlotNumber()] = NULL;
                            bmtInterface->ppInterfaceDeclMethodDescList[it.GetSlotNumber()] = NULL;
                        }
                        else
                        {
                            bmtInterface->ppInterfaceMethodDescList[it.GetSlotNumber()] = bmtMethod->ppMethodDescList[i];
                            bmtInterface->ppInterfaceDeclMethodDescList[it.GetSlotNumber()] = pInterfaceMD;
                        }
                    }
                }
            }
        }

        {
            MethodTable::MethodIterator it(pInterface);
            for (; it.IsValid(); it.Next())
            {
                if (it.IsVirtual())
                {
                    // The entry can be null if the interface was previously
                    // laid out by a parent and we did not have a method
                    // that subclassed the interface.
                    if(bmtInterface->ppInterfaceMethodDescList[it.GetSlotNumber()] != NULL)
                    {
                        // Get the MethodDesc which was allocated for the method
                        MethodDesc *pMD = bmtInterface->ppInterfaceMethodDescList[it.GetSlotNumber()];
                        InteropMethodTableSlotData *pMDData = bmtVT->pInteropData->GetData(pMD);

                        if (pMDData->wSlot == (WORD) MethodTable::NO_SLOT)
                        {
                            pMDData->wSlot = (WORD) bmtVT->wCurrentVtableSlot;
                        }

                        // Set the vtable slot
                        _ASSERTE(bmtVT->GetMethodDescForSlot(bmtVT->wCurrentVtableSlot) == NULL);
                        bmtVT->SetMethodDescForSlot(bmtVT->wCurrentVtableSlot, pMD);
                        _ASSERTE(bmtVT->GetMethodDescForSlot(bmtVT->wCurrentVtableSlot) != NULL);
                        bmtVT->ppSDVtable[bmtVT->wCurrentVtableSlot] = pMDData;

                        // Increment the current vtable slot
                        bmtVT->wCurrentVtableSlot++;
                    }
                }
            }
        }
    }
}

//---------------------------------------------------------------------------------------
// We should have collected all the method impls. Cycle through them creating the method impl
// structure that holds the information about which slots are overridden.
VOID MethodTableBuilder::BuildInteropVTable_PlaceMethodImpls(
        bmtTypeInfo* bmtType,
        bmtMethodImplInfo* bmtMethodImpl,
        bmtErrorInfo* bmtError, 
        bmtInterfaceInfo* bmtInterface, 
        bmtVtable* bmtVT,
        bmtParentInfo* bmtParent)

{
    STANDARD_VM_CONTRACT;

    if(bmtMethodImpl->pIndex == 0) 
        return;

    DWORD pIndex = 0;

    // Allocate some temporary storage. The number of overrides for a single method impl
    // cannot be greater then the number of vtable slots. 
    DWORD* slots = (DWORD*) new (GetStackingAllocator()) DWORD[bmtVT->wCurrentVtableSlot];
    MethodDesc **replaced = new (GetStackingAllocator()) MethodDesc*[bmtVT->wCurrentVtableSlot];

    while(pIndex < bmtMethodImpl->pIndex) {

        DWORD slotIndex = 0;
        DWORD dwItfCount = 0;
        MethodDesc* next = bmtMethodImpl->GetBodyMethodDesc(pIndex);
        MethodDesc* body = NULL;

        // The signature for the body of the method impl. We cache the signature until all 
        // the method impl's using the same body are done.
        PCCOR_SIGNATURE pBodySignature = NULL;
        DWORD           cBodySignature = 0;

        // The impls are sorted according to the method descs for the body of the method impl.
        // Loop through the impls until the next body is found. When a single body
        // has been done move the slots implemented and method descs replaced into the storage
        // found on the body method desc. 
        do { // collect information until we reach the next body  
            body = next;

            // Get the declaration part of the method impl. It will either be a token
            // (declaration is on this type) or a method desc.
            MethodDesc* pDecl = bmtMethodImpl->GetDeclarationMethodDesc(pIndex);
            if(pDecl == NULL) {
                // The declaration is on this type to get the token.
                mdMethodDef mdef = bmtMethodImpl->GetDeclarationToken(pIndex);

                BuildInteropVTable_PlaceLocalDeclaration(mdef, 
                                           body,
                                           bmtType,
                                           bmtError,
                                           bmtVT,
                                           slots,             // Adds override to the slot and replaced arrays.
                                           replaced,
                                           &slotIndex,        // Increments count
                                           &pBodySignature,   // Fills in the signature
                                           &cBodySignature);
            }
            else {
                // Method impls to methods on generic interfaces should have already
                // been filtered out.
                _ASSERTE(pDecl->GetMethodTable()->GetNumGenericArgs() == 0);
                    
                if(pDecl->GetMethodTable()->IsInterface()) {
                    BuildInteropVTable_PlaceInterfaceDeclaration(pDecl,
                                                   body,
                                                   bmtMethodImpl->GetDeclarationSubst(pIndex),
                                                   bmtType,
                                                   bmtInterface,
                                                   bmtError,
                                                   bmtVT,
                                                   slots,
                                                   replaced,
                                                   &slotIndex,        // Increments count
                                                   &pBodySignature,   // Fills in the signature
                                                   &cBodySignature);
                }
                else {
                    BuildInteropVTable_PlaceParentDeclaration(pDecl,                                                
                                                body,
                                                bmtMethodImpl->GetDeclarationSubst(pIndex),
                                                bmtType,
                                                bmtError,
                                                bmtVT,
                                                bmtParent,
                                                slots,
                                                replaced,
                                                &slotIndex,        // Increments count
                                                &pBodySignature,   // Fills in the signature
                                                &cBodySignature);
                }                   
            }

            // Move to the next body
            pIndex++;

            // we hit the end of the list so leave
            next = pIndex < bmtMethodImpl->pIndex ? bmtMethodImpl->GetBodyMethodDesc(pIndex) : NULL;
        } while(next == body) ;
    }  // while(next != NULL)
}

//---------------------------------------------------------------------------------------
VOID MethodTableBuilder::BuildInteropVTable_PlaceLocalDeclaration(
                                       mdMethodDef      mdef,
                                       MethodDesc*      body,
                                       bmtTypeInfo* bmtType,
                                       bmtErrorInfo*    bmtError, 
                                       bmtVtable*       bmtVT,
                                       DWORD*           slots,
                                       MethodDesc**     replaced,
                                       DWORD*           pSlotIndex,
                                       PCCOR_SIGNATURE* ppBodySignature,
                                       DWORD*           pcBodySignature)
{
    STANDARD_VM_CONTRACT;

    // we search on the token and m_cl
    for(USHORT i = 0; i < bmtVT->wCurrentVtableSlot; i++)
    {
        // Make sure we haven't already been MethodImpl'd
        _ASSERTE(bmtVT->ppSDVtable[i]->pMD == bmtVT->ppSDVtable[i]->pDeclMD);

        // We get the current slot.  Since we are looking for a method declaration 
        // that is on our class we would never match up with a method obtained from 
        // one of our parents or an Interface. 
        MethodDesc *pMD = bmtVT->ppSDVtable[i]->pMD;

        // If we get a null then we have already replaced this one. We can't check it
        // so we will just by by-pass this. 
        if(pMD->GetMemberDef() == mdef)  
        {
            InteropMethodTableSlotData *pDeclData = bmtVT->pInteropData->GetData(pMD);
            InteropMethodTableSlotData *pImplData = bmtVT->pInteropData->GetData(body);

            // If the body has not been placed then place it here. We do not
            // place bodies for method impl's until we find a spot for them.
            if (pImplData->wSlot == MethodTable::NO_SLOT)
            {
                pImplData->wSlot = (WORD) i;
            }

            // We implement this slot, record it
            slots[*pSlotIndex] = i;
            replaced[*pSlotIndex] = pMD;
            bmtVT->SetMethodDescForSlot(i, body);
            pDeclData->pMD = pImplData->pMD;
            pDeclData->wSlot = pImplData->wSlot;
            bmtVT->ppSDVtable[i] = pDeclData;

            // increment the counter 
            (*pSlotIndex)++;
        }
    }
}

//---------------------------------------------------------------------------------------
VOID MethodTableBuilder::BuildInteropVTable_PlaceInterfaceDeclaration(
                                           MethodDesc*       pItfDecl,
                                           MethodDesc*       pImplBody,
                                           const Substitution *pDeclSubst,
                                           bmtTypeInfo*  bmtType,
                                           bmtInterfaceInfo* bmtInterface, 
                                           bmtErrorInfo*     bmtError, 
                                           bmtVtable*        bmtVT,
                                           DWORD*            slots,
                                           MethodDesc**      replaced,
                                           DWORD*            pSlotIndex,
                                           PCCOR_SIGNATURE*  ppBodySignature,
                                           DWORD*            pcBodySignature)
{
    STANDARD_VM_CONTRACT;

    _ASSERTE(pItfDecl && pItfDecl->IsInterface() && !(pItfDecl->IsMethodImpl()));

    // the fact that an interface only shows up once in the vtable
    // When we are looking for a method desc then the declaration is on
    // some class or interface that this class implements. The declaration
    // will either be to an interface or to a class. If it is to a
    // interface then we need to search for that interface. From that
    // slot number of the method in the interface we can calculate the offset 
    // into our vtable. If it is to a class it must be a subclass. This uses
    // the fact that an interface only shows up once in the vtable.

    BOOL fInterfaceFound = FALSE;
    // Check our vtable for entries that we are suppose to override. 
    // Since this is an external method we must also check the inteface map.
    // We want to replace any interface methods even if they have been replaced
    // by a base class. 
    for(USHORT i = 0; i < bmtInterface->wInterfaceMapSize; i++)
    {
        MethodTable *pInterface = bmtInterface->pInterfaceMap[i].m_pMethodTable;

        if (pInterface->IsEquivalentTo(pItfDecl->GetMethodTable()))
        {
            // We found an interface so no error
            fInterfaceFound = TRUE;

            WORD wSlot = (WORD) -1;
            MethodDesc *pMD = NULL;

            // Find out where the interface map is set on our vtable
            WORD wStartingSlot = (USHORT) bmtInterface->pInterfaceMap[i].GetInteropStartSlot();

            // We need to duplicate the interface to avoid copies. Currently, interfaces
            // do not overlap so we just need to check to see if there is a non-duplicated
            // MD. If there is then the interface shares it with the class which means
            // we need to copy the whole interface
            for(wSlot = wStartingSlot; wSlot < pInterface->GetNumVirtuals() + wStartingSlot; wSlot++)
            {
                // This check will tell us if the method in this slot is the first instance (not a duplicate)
                if(bmtVT->ppSDVtable[wSlot]->wSlot == wSlot)
                    break;
            }

            if(wSlot < pInterface->GetNumVirtuals() + wStartingSlot)
            {
                // Check to see if we have allocated the temporay array of starting values.
                // This array is used to backpatch entries to the original location. These 
                // values are never used but will cause problems later when we finish 
                // laying out the method table.
                if(bmtInterface->pdwOriginalStart == NULL)
                {
                    Thread *pThread = GetThread();
                    bmtInterface->pdwOriginalStart = new (GetStackingAllocator()) DWORD[bmtInterface->dwMaxExpandedInterfaces];
                    memset(bmtInterface->pdwOriginalStart, 0, sizeof(DWORD)*bmtInterface->dwMaxExpandedInterfaces);
                }

                _ASSERTE(bmtInterface->pInterfaceMap[i].GetInteropStartSlot() != (WORD) 0 && "We assume that an interface does not start at position 0");
                _ASSERTE(bmtInterface->pdwOriginalStart[i] == 0 && "We should not move an interface twice"); 
                bmtInterface->pdwOriginalStart[i] = bmtInterface->pInterfaceMap[i].GetInteropStartSlot();

                // The interface now starts at the end of the map.
                bmtInterface->pInterfaceMap[i].SetInteropStartSlot(bmtVT->wCurrentVtableSlot);
                for(WORD d = wStartingSlot; d < pInterface->GetNumVirtuals() + wStartingSlot; d++)
                {
                    // Copy the MD
                    //@TODO: Maybe need to create new slot data entries for this copy-out based on
                    //@TODO: the MD's of the interface slots.
                    InteropMethodTableSlotData *pDataCopy = bmtVT->ppSDVtable[d];
                    bmtVT->SetMethodDescForSlot(bmtVT->wCurrentVtableSlot, pDataCopy->pMD);
                    bmtVT->ppSDVtable[bmtVT->wCurrentVtableSlot] = pDataCopy;
                    // Increment the various counters
                    bmtVT->wCurrentVtableSlot++;
                }
                // Reset the starting slot to the known value
                wStartingSlot = bmtInterface->pInterfaceMap[i].GetInteropStartSlot();
            }

            // Make sure we have placed the interface map.
            _ASSERTE(wStartingSlot != MethodTable::NO_SLOT); 

            // Get the Slot location of the method desc (slot of the itf MD + start slot for this class)
            wSlot = pItfDecl->GetSlot() + wStartingSlot;
            _ASSERTE(wSlot < bmtVT->wCurrentVtableSlot);

            // Get our current method desc for this slot
            pMD = bmtVT->ppSDVtable[wSlot]->pMD;

            // If we have not got the method impl signature go get it now. It is cached
            // in our caller
            if (*ppBodySignature == NULL)
            {
                if (FAILED(bmtType->pMDImport->GetSigOfMethodDef(
                    pImplBody->GetMemberDef(),
                    pcBodySignature, 
                    ppBodySignature)))
                {
                    BuildMethodTableThrowException(IDS_CLASSLOAD_BADFORMAT);
                }
            }
            
            InteropMethodTableSlotData *pImplSlotData = bmtVT->pInteropData->GetData(pImplBody);
            _ASSERTE(pImplSlotData->wSlot != MethodTable::NO_SLOT);
            // If the body has not been placed then place it now.
            if (pImplSlotData->wSlot == MethodTable::NO_SLOT)
            {
                pImplSlotData->wSlot = wSlot;
            }

            // Store away the values
            InteropMethodTableSlotData *pItfSlotData = bmtVT->pInteropData->GetData(pItfDecl);
            slots[*pSlotIndex] = wSlot;
            replaced[*pSlotIndex] = pItfDecl;
            bmtVT->SetMethodDescForSlot(wSlot, pImplBody);
            pItfSlotData->pMD = pImplBody;
            pItfSlotData->wSlot = pImplSlotData->wSlot;
            bmtVT->ppSDVtable[wSlot] = pItfSlotData;

            // increment the counter 
            (*pSlotIndex)++;

            // if we have moved the interface we need to back patch the original location
            // if we had left an interface place holder.
            if(bmtInterface->pdwOriginalStart && bmtInterface->pdwOriginalStart[i] != 0)
            {
                USHORT slot = (USHORT) bmtInterface->pdwOriginalStart[i] + pItfDecl->GetSlot();
                MethodDesc* pSlotMD = bmtVT->ppSDVtable[slot]->pMD;
                if(pSlotMD->GetMethodTable() && pSlotMD->IsInterface())
                {
                    bmtVT->SetMethodDescForSlot(slot, pImplBody);
                    bmtVT->ppSDVtable[slot] = pItfSlotData;
                }
            }
            break;
        }
    }

    _ASSERTE(fInterfaceFound);
}

//---------------------------------------------------------------------------------------
VOID MethodTableBuilder::BuildInteropVTable_PlaceParentDeclaration(
                                        MethodDesc*       pDecl,
                                        MethodDesc*       pImplBody,
                                        const Substitution *pDeclSubst,
                                        bmtTypeInfo*  bmtType,
                                        bmtErrorInfo*     bmtError, 
                                        bmtVtable*        bmtVT,
                                        bmtParentInfo*    bmtParent,
                                        DWORD*            slots,
                                        MethodDesc**      replaced,
                                        DWORD*            pSlotIndex,
                                        PCCOR_SIGNATURE*  ppBodySignature,
                                        DWORD*            pcBodySignature)
{
    STANDARD_VM_CONTRACT;

    _ASSERTE(pDecl && !pDecl->IsInterface());

    BOOL fRet = FALSE;	

    // Verify that the class of the declaration is in our heirarchy
    MethodTable* declType = pDecl->GetMethodTable();
    MethodTable* pParentMT = bmtParent->pParentMethodTable;
    while(pParentMT != NULL)
    {

        if(declType == pParentMT)
            break;
        pParentMT = pParentMT->GetParentMethodTable();
    }
    _ASSERTE(pParentMT);

    // Compare the signature for the token in the specified scope
    // If we have not got the method impl signature go get it now
    if (*ppBodySignature == NULL)
    {
        if (FAILED(bmtType->pMDImport->GetSigOfMethodDef(
            pImplBody->GetMemberDef(), 
            pcBodySignature, 
            ppBodySignature)))
        {
            BuildMethodTableThrowException(IDS_CLASSLOAD_BADFORMAT);
        }
    }

    // We get the method from the parents slot. We will replace the method that is currently
    // defined in that slot and any duplicates for that method desc. 
    WORD wSlot = InteropMethodTableData::GetSlotForMethodDesc(pParentMT, pDecl);
    InteropMethodTableSlotData *pDeclData = bmtVT->ppSDVtable[wSlot];
    InteropMethodTableSlotData *pImplData = bmtVT->pInteropData->GetData(pImplBody);

    // Get the real method desc (a base class may have overridden the method
    // with a method impl)
    MethodDesc* pReplaceDesc = pDeclData->pDeclMD;

    // If the body has not been placed then place it here
    if(pImplData->wSlot == MethodTable::NO_SLOT)
    {
        pImplData->wSlot = wSlot;
    }

    slots[*pSlotIndex] = wSlot;
    replaced[*pSlotIndex] = pReplaceDesc;
    bmtVT->SetMethodDescForSlot(wSlot, pImplBody);
    pDeclData->pMD = pImplData->pMD;
    pDeclData->wSlot = pImplData->wSlot;
    bmtVT->ppSDVtable[wSlot] = pDeclData;

    // increment the counter 
    (*pSlotIndex)++;

    // we search for all duplicates
    for(USHORT i = wSlot+1; i < bmtVT->wCurrentVtableSlot; i++)
    {
        MethodDesc *pMD = bmtVT->ppSDVtable[i]->pMD;

        MethodDesc* pRealDesc = bmtVT->ppSDVtable[i]->pDeclMD;

        if(pRealDesc == pReplaceDesc) 
        {
            // We do not want to override a body to another method impl
            _ASSERTE(!pRealDesc->IsMethodImpl());

            // Make sure we are not overridding another method impl
            _ASSERTE(!(pMD != pImplBody && pMD->IsMethodImpl() && pMD->GetMethodTable() == NULL));

            slots[*pSlotIndex] = i;
            replaced[*pSlotIndex] = pRealDesc;
            bmtVT->pVtable[i] = bmtVT->pVtable[wSlot];
            bmtVT->pVtableMD[i] = bmtVT->pVtableMD[wSlot];
            bmtVT->ppSDVtable[i] = bmtVT->ppSDVtable[wSlot];

            // increment the counter 
            (*pSlotIndex)++;
        }
    }
}

//---------------------------------------------------------------------------------------
VOID   MethodTableBuilder::BuildInteropVTable_PropagateInheritance(
    bmtVtable *bmtVT)
{
    STANDARD_VM_CONTRACT;

    for (DWORD i = 0; i < bmtVT->wCurrentVtableSlot; i++)
    {
        // For now only propagate inheritance for method desc that are not interface MD's.
        // This is not sufficient but InterfaceImpl's will complete the picture.
        InteropMethodTableSlotData *pMDData = bmtVT->ppSDVtable[i];
        MethodDesc* pMD = pMDData->pMD;
        CONSISTENCY_CHECK_MSG(CheckPointer(pMD), "Could not resolve MethodDesc Slot!");

        if(!pMD->IsInterface() && pMDData->GetSlot() != i)
        {
            pMDData->SetDuplicate();
            bmtVT->pVtable[i] = bmtVT->pVtable[pMDData->GetSlot()];
            bmtVT->pVtableMD[i] = bmtVT->pVtableMD[pMDData->GetSlot()];
            bmtVT->ppSDVtable[i]->pMD = bmtVT->ppSDVtable[pMDData->GetSlot()]->pMD;
        }
    }
}


//---------------------------------------------------------------------------------------
VOID   MethodTableBuilder::FinalizeInteropVTable(
        AllocMemTracker *pamTracker,
        LoaderAllocator* pAllocator,
        bmtVtable* bmtVT, 
        bmtInterfaceInfo* bmtInterface, 
        bmtTypeInfo* bmtType, 
        bmtProperties* bmtProp, 
        bmtMethodInfo* bmtMethod,
        bmtErrorInfo* bmtError, 
        bmtParentInfo* bmtParent,
        InteropMethodTableData **ppInteropMT)
{
    STANDARD_VM_CONTRACT;

    LoaderHeap *pHeap = pAllocator->GetLowFrequencyHeap();

    // Allocate the overall structure
    InteropMethodTableData *pMTData = (InteropMethodTableData *) pamTracker->Track(pHeap->AllocMem(S_SIZE_T(sizeof(InteropMethodTableData))));
#ifdef LOGGING
    g_sdStats.m_cbComInteropData += sizeof(InteropMethodTableData);
#endif
    memset(pMTData, 0, sizeof(InteropMethodTableData));

    // Allocate the vtable
    pMTData->cVTable = bmtVT->wCurrentVtableSlot;
    if (pMTData->cVTable != 0)
    {
        pMTData->pVTable = (InteropMethodTableSlotData *)
            pamTracker->Track(pHeap->AllocMem(S_SIZE_T(sizeof(InteropMethodTableSlotData)) * S_SIZE_T(pMTData->cVTable)));
#ifdef LOGGING
        g_sdStats.m_cbComInteropData += sizeof(InteropMethodTableSlotData) * pMTData->cVTable;
#endif

        {   // Copy the vtable
            for (DWORD i = 0; i < pMTData->cVTable; i++)
            {
                CONSISTENCY_CHECK(bmtVT->ppSDVtable[i]->wSlot != MethodTable::NO_SLOT);
                pMTData->pVTable[i] = *bmtVT->ppSDVtable[i];
            }
        }
    }

    // Allocate the non-vtable
    pMTData->cNonVTable = bmtVT->wCurrentNonVtableSlot;
    if (pMTData->cNonVTable != 0)
    {
        pMTData->pNonVTable = (InteropMethodTableSlotData *)
            pamTracker->Track(pHeap->AllocMem(S_SIZE_T(sizeof(InteropMethodTableSlotData)) * S_SIZE_T(pMTData->cNonVTable)));
#ifdef LOGGING
        g_sdStats.m_cbComInteropData += sizeof(InteropMethodTableSlotData) * pMTData->cNonVTable;
#endif

        {   // Copy the non-vtable
            for (DWORD i = 0; i < pMTData->cNonVTable; i++)
            {
                CONSISTENCY_CHECK(bmtVT->ppSDVtable[i]->wSlot != MethodTable::NO_SLOT);
                pMTData->pNonVTable[i] = *bmtVT->ppSDNonVtable[i];
            }
        }
    }

    // Allocate the interface map
    pMTData->cInterfaceMap = bmtInterface->wInterfaceMapSize;
    if (pMTData->cInterfaceMap != 0)
    {
        pMTData->pInterfaceMap = (InterfaceInfo_t *)
            pamTracker->Track(pHeap->AllocMem(S_SIZE_T(sizeof(InterfaceInfo_t)) * S_SIZE_T(pMTData->cInterfaceMap)));
#ifdef LOGGING
        g_sdStats.m_cbComInteropData += sizeof(InterfaceInfo_t) * pMTData->cInterfaceMap;
#endif

        {   // Copy the interface map
            for (DWORD i = 0; i < pMTData->cInterfaceMap; i++)
            {
                pMTData->pInterfaceMap[i] = bmtInterface->pInterfaceMap[i];
            }
        }
    }

    *ppInteropMT = pMTData;
}

//*******************************************************************************
VOID    MethodTableBuilder::EnumerateMethodImpls()
{
    STANDARD_VM_CONTRACT;

    HRESULT hr = S_OK;
    IMDInternalImport *pMDInternalImport = bmtType->pMDImport;
    DWORD rid, maxRidMD, maxRidMR;
    hr = bmtMethodImpl->hEnumMethodImpl.EnumMethodImplInitNoThrow(GetCl());

    if (FAILED(hr))
    {
        BuildMethodTableThrowException(hr, *bmtError);
    }

    // This gets the count out of the metadata interface.
    bmtMethodImpl->dwNumberMethodImpls = bmtMethodImpl->hEnumMethodImpl.EnumMethodImplGetCount();

    // This is the first pass. In this we will simply enumerate the token pairs and fill in
    // the data structures. In addition, we'll sort the list and eliminate duplicates.
    if (bmtMethodImpl->dwNumberMethodImpls > 0)
    {
        //
        // Allocate the structures to keep track of the token pairs
        //
        bmtMethodImpl->rgMethodImplTokens = new (GetStackingAllocator())
            bmtMethodImplInfo::MethodImplTokenPair[bmtMethodImpl->dwNumberMethodImpls];
            
        // Iterate through each MethodImpl declared on this class
        for (DWORD i = 0; i < bmtMethodImpl->dwNumberMethodImpls; i++)
        {
            // Grab the next set of body/decl tokens
            hr = bmtMethodImpl->hEnumMethodImpl.EnumMethodImplNext(
                &bmtMethodImpl->rgMethodImplTokens[i].methodBody, 
                &bmtMethodImpl->rgMethodImplTokens[i].methodDecl);
            if (FAILED(hr))
            {
                BuildMethodTableThrowException(IDS_CLASSLOAD_BADFORMAT);
            }
            if (hr == S_FALSE)
            {
                // In the odd case that the enumerator fails before we've reached the total reported
                // entries, let's reset the count and just break out. (Should we throw?)
                bmtMethodImpl->dwNumberMethodImpls = i;
                break;
            }
        }

        // No need to do any sorting or duplicate elimination if there's not two or more methodImpls
        if (bmtMethodImpl->dwNumberMethodImpls > 1)
        {
            // Now sort
            qsort(bmtMethodImpl->rgMethodImplTokens,
                  bmtMethodImpl->dwNumberMethodImpls,
                  sizeof(bmtMethodImplInfo::MethodImplTokenPair),
                  &bmtMethodImplInfo::MethodImplTokenPair::Compare);

            // Now eliminate duplicates
            for (DWORD i = 0; i < bmtMethodImpl->dwNumberMethodImpls - 1; i++)
            {
                CONSISTENCY_CHECK((i + 1) < bmtMethodImpl->dwNumberMethodImpls);

                bmtMethodImplInfo::MethodImplTokenPair *e1 = &bmtMethodImpl->rgMethodImplTokens[i];
                bmtMethodImplInfo::MethodImplTokenPair *e2 = &bmtMethodImpl->rgMethodImplTokens[i + 1];

                // If the pair are equal, eliminate the first one, and reduce the total count by one.
                if (bmtMethodImplInfo::MethodImplTokenPair::Equal(e1, e2))
                {
                    DWORD dwCopyNum = bmtMethodImpl->dwNumberMethodImpls - (i + 1);
                    memcpy(e1, e2, dwCopyNum * sizeof(bmtMethodImplInfo::MethodImplTokenPair));
                    bmtMethodImpl->dwNumberMethodImpls--;
                    CONSISTENCY_CHECK(bmtMethodImpl->dwNumberMethodImpls > 0);
                }
            }
        }
    }

    if (bmtMethodImpl->dwNumberMethodImpls != 0)
    {
        //
        // Allocate the structures to keep track of the impl matches
        //
        bmtMethodImpl->pMethodDeclSubsts = new (GetStackingAllocator()) Substitution[bmtMethodImpl->dwNumberMethodImpls]; 
        bmtMethodImpl->rgEntries = new (GetStackingAllocator()) bmtMethodImplInfo::Entry[bmtMethodImpl->dwNumberMethodImpls];

        // These are used for verification
        maxRidMD = pMDInternalImport->GetCountWithTokenKind(mdtMethodDef);
        maxRidMR = pMDInternalImport->GetCountWithTokenKind(mdtMemberRef);

        // Iterate through each MethodImpl declared on this class
        for (DWORD i = 0; i < bmtMethodImpl->dwNumberMethodImpls; i++)
        {
            PCCOR_SIGNATURE pSigDecl = NULL;
            PCCOR_SIGNATURE pSigBody = NULL;
            ULONG           cbSigDecl;
            ULONG           cbSigBody;
            mdToken tkParent;

            mdToken theBody, theDecl;
            Substitution theDeclSubst(bmtType->pModule, SigPointer(), NULL); // this can get updated later below.

            theBody = bmtMethodImpl->rgMethodImplTokens[i].methodBody;
            theDecl = bmtMethodImpl->rgMethodImplTokens[i].methodDecl;

            // IMPLEMENTATION LIMITATION: currently, we require that the body of a methodImpl
            // belong to the current type. This is because we need to allocate a different
            // type of MethodDesc for bodies that are part of methodImpls.
            if (TypeFromToken(theBody) != mdtMethodDef)
            {
                mdToken theNewBody;
                hr = FindMethodDeclarationForMethodImpl(bmtType->pMDImport,
                                                        GetCl(),
                                                        theBody,
                                                        &theNewBody);
                if (FAILED(hr))
                {
                    BuildMethodTableThrowException(hr, IDS_CLASSLOAD_MI_ILLEGAL_BODY, mdMethodDefNil);
                }
                theBody = theNewBody;

                // Make sure to update the stored token with the resolved token.
                bmtMethodImpl->rgMethodImplTokens[i].methodBody = theBody;
            }

            if (TypeFromToken(theBody) != mdtMethodDef)
            {
                BuildMethodTableThrowException(BFA_METHODDECL_NOT_A_METHODDEF);
            }
            CONSISTENCY_CHECK(theBody == bmtMethodImpl->rgMethodImplTokens[i].methodBody);

            //
            // Now that the tokens of Decl and Body are obtained, do the MD validation
            //

            rid = RidFromToken(theDecl);

            // Perform initial rudimentary validation of the token. Full token verification
            // will be done in TestMethodImpl when placing the methodImpls.
            if (TypeFromToken(theDecl) == mdtMethodDef)
            {
                // Decl must be valid token
                if ((rid == 0)||(rid > maxRidMD))
                {
                    BuildMethodTableThrowException(IDS_CLASSLOAD_MI_ILLEGAL_TOKEN_DECL);
                }
                // Get signature and length
                if (FAILED(pMDInternalImport->GetSigOfMethodDef(theDecl, &cbSigDecl, &pSigDecl)))
                {
                    BuildMethodTableThrowException(IDS_CLASSLOAD_BADFORMAT);
                }
            }

            // The token is not a MethodDef (likely a MemberRef)
            else
            {
                // Decl must be valid token
                if ((TypeFromToken(theDecl) != mdtMemberRef) || (rid == 0) || (rid > maxRidMR))
                {
                    bmtError->resIDWhy = IDS_CLASSLOAD_MI_ILLEGAL_TOKEN_DECL;
                    BuildMethodTableThrowException(IDS_CLASSLOAD_MI_ILLEGAL_TOKEN_DECL);
                }
                
                // Get signature and length
                LPCSTR szDeclName;
                if (FAILED(pMDInternalImport->GetNameAndSigOfMemberRef(theDecl, &pSigDecl, &cbSigDecl, &szDeclName)))
                {
                    BuildMethodTableThrowException(IDS_CLASSLOAD_BADFORMAT);
                }
                
                // Get parent
                hr = pMDInternalImport->GetParentToken(theDecl,&tkParent);
                if (FAILED(hr))
                    BuildMethodTableThrowException(hr, *bmtError);

                theDeclSubst = Substitution(tkParent, bmtType->pModule, NULL);
            }

            // Perform initial rudimentary validation of the token. Full token verification
            // will be done in TestMethodImpl when placing the methodImpls.
            {
                // Body must be valid token
                rid = RidFromToken(theBody);
                if ((rid == 0)||(rid > maxRidMD))
                {
                    BuildMethodTableThrowException(IDS_CLASSLOAD_MI_ILLEGAL_TOKEN_BODY);
                }
                // Body's parent must be this class
                hr = pMDInternalImport->GetParentToken(theBody,&tkParent);
                if (FAILED(hr))
                    BuildMethodTableThrowException(hr, *bmtError);
                if(tkParent != GetCl())
                {
                    BuildMethodTableThrowException(IDS_CLASSLOAD_MI_ILLEGAL_BODY);
                }
            }
            // Decl's and Body's signatures must match
            if ((pSigDecl != NULL) && (cbSigDecl != 0))
            {
                if (FAILED(pMDInternalImport->GetSigOfMethodDef(theBody,&cbSigBody, &pSigBody)) || 
                    (pSigBody == NULL) || 
                    (cbSigBody == 0))
                {
                    BuildMethodTableThrowException(IDS_CLASSLOAD_MI_MISSING_SIG_BODY);
                }
                // Can't use memcmp because there may be two AssemblyRefs
                // in this scope, pointing to the same assembly, etc.).
                if (!MetaSig::CompareMethodSigs(pSigDecl,
                                                cbSigDecl,
                                                bmtType->pModule,
                                                &theDeclSubst,
                                                pSigBody,
                                                cbSigBody,
                                                bmtType->pModule,
                                                NULL))
                {
                    BuildMethodTableThrowException(IDS_CLASSLOAD_MI_BODY_DECL_MISMATCH);
                }
            }
            else
            {
                BuildMethodTableThrowException(IDS_CLASSLOAD_MI_MISSING_SIG_DECL);
            }

            bmtMethodImpl->pMethodDeclSubsts[i] = theDeclSubst;

        }
    }
}

//*******************************************************************************
//
// Used by BuildMethodTable
//
// Enumerate this class's members
//
#ifdef _PREFAST_
#pragma warning(push)
#pragma warning(disable:21000) // Suppress PREFast warning about overly large function
#endif
VOID    MethodTableBuilder::EnumerateClassMethods()
{
    CONTRACTL
    {
        STANDARD_VM_CHECK;
        PRECONDITION(CheckPointer(bmtType));
        PRECONDITION(CheckPointer(bmtMethod));
        PRECONDITION(CheckPointer(bmtProp));
        PRECONDITION(CheckPointer(bmtVT));
        PRECONDITION(CheckPointer(bmtError));
    }
    CONTRACTL_END;

    HRESULT hr = S_OK;
    DWORD i;
    IMDInternalImport *pMDInternalImport = bmtType->pMDImport;
    mdToken tok;
    DWORD dwMemberAttrs;
    BOOL fIsClassEnum = IsEnum();
    BOOL fIsClassInterface = IsInterface();
    BOOL fIsClassValueType = IsValueClass();
#ifdef FEATURE_COMINTEROP
    BOOL fIsClassComImport = IsComImport();
#endif
    BOOL fIsClassNotAbstract = (IsTdAbstract(GetAttrClass()) == 0);
    PCCOR_SIGNATURE pMemberSignature;
    ULONG           cMemberSignature;

    //
    // Run through the method list and calculate the following:
    // # methods.
    // # "other" methods (i.e. static or private)
    // # non-other methods
    //

    bmtVT->dwMaxVtableSize     = 0; // we'll fix this later to be the real upper bound on vtable size
    bmtMethod->cMethods = 0;

    hr = bmtMethod->hEnumMethod.EnumInitNoThrow(mdtMethodDef, GetCl());
    if (FAILED(hr))
    {
        _ASSERTE(!"Cannot count memberdefs");
        if (FAILED(hr))
        {
            BuildMethodTableThrowException(hr, *bmtError);
        }
    }

    // Allocate an array to contain the method tokens as well as information about the methods.
    bmtMethod->cMethAndGaps = bmtMethod->hEnumMethod.EnumGetCount();

    bmtMethod->rgMethodTokens = new (GetStackingAllocator()) mdToken[bmtMethod->cMethAndGaps]; 
    bmtMethod->rgMethodRVA = new (GetStackingAllocator()) ULONG[bmtMethod->cMethAndGaps]; 
    bmtMethod->rgMethodAttrs = new (GetStackingAllocator()) DWORD[bmtMethod->cMethAndGaps]; 
    bmtMethod->rgMethodImplFlags = new (GetStackingAllocator()) DWORD[bmtMethod->cMethAndGaps]; 
    bmtMethod->rgMethodClassifications = new (GetStackingAllocator()) DWORD[bmtMethod->cMethAndGaps]; 

    bmtMethod->rgszMethodName = new (GetStackingAllocator()) LPCSTR[bmtMethod->cMethAndGaps];

    bmtMethod->rgMethodImpl = new (GetStackingAllocator()) BYTE[bmtMethod->cMethAndGaps]; 
    bmtMethod->rgMethodType = new (GetStackingAllocator()) BYTE[bmtMethod->cMethAndGaps]; 

    enum { SeenCtor = 1, SeenInvoke = 2, SeenBeginInvoke = 4, SeenEndInvoke = 8};
    unsigned delegateMethodsSeen = 0;

    for (i = 0; i < bmtMethod->cMethAndGaps; i++)
    {
        ULONG dwMethodRVA;
        DWORD dwImplFlags;
        DWORD Classification;
        LPSTR strMethodName;

        //
        // Go to the next method and retrieve its attributes.
        //

        bmtMethod->hEnumMethod.EnumNext(&tok);
        DWORD   rid = RidFromToken(tok);
        if ((rid == 0)||(rid > pMDInternalImport->GetCountWithTokenKind(mdtMethodDef)))
        {
            BuildMethodTableThrowException(BFA_METHOD_TOKEN_OUT_OF_RANGE);
        }

        if (FAILED(pMDInternalImport->GetMethodDefProps(tok, &dwMemberAttrs)))
        {
            BuildMethodTableThrowException(IDS_CLASSLOAD_BADFORMAT);
        }
        if (IsMdRTSpecialName(dwMemberAttrs) || IsMdVirtual(dwMemberAttrs) || IsDelegate())
        {
            if (FAILED(pMDInternalImport->GetNameOfMethodDef(tok, (LPCSTR *)&strMethodName)))
            {
                BuildMethodTableThrowException(IDS_CLASSLOAD_BADFORMAT);
            }
            if (IsStrLongerThan(strMethodName,MAX_CLASS_NAME))
            {
                BuildMethodTableThrowException(BFA_METHOD_NAME_TOO_LONG);
            }
        }
        else
            strMethodName = NULL;

        HENUMInternalHolder hEnumTyPars(pMDInternalImport);
        hr = hEnumTyPars.EnumInitNoThrow(mdtGenericParam, tok);
        if (FAILED(hr))
        {
            BuildMethodTableThrowException(hr, *bmtError);
        }

        WORD numGenericMethodArgs = (WORD) hEnumTyPars.EnumGetCount();

        if (numGenericMethodArgs != 0)
        {
            for (unsigned methIdx = 0; methIdx < numGenericMethodArgs; methIdx++)
            {
                mdGenericParam tkTyPar;
                pMDInternalImport->EnumNext(&hEnumTyPars, &tkTyPar);
                DWORD flags;
                if (FAILED(pMDInternalImport->GetGenericParamProps(tkTyPar, NULL, &flags, NULL, NULL, NULL)))
                {
                    BuildMethodTableThrowException(IDS_CLASSLOAD_BADFORMAT);
                }
                
                if (0 != (flags & ~(gpVarianceMask | gpSpecialConstraintMask)))
                {
                    BuildMethodTableThrowException(IDS_CLASSLOAD_BADFORMAT);
                }
                switch (flags & gpVarianceMask)
                {
                    case gpNonVariant:
                        break;

                    case gpCovariant: // intentional fallthru
                    case gpContravariant:
                        BuildMethodTableThrowException(VLDTR_E_GP_ILLEGAL_VARIANT_MVAR);
                        break;

                    default:
                        BuildMethodTableThrowException(IDS_CLASSLOAD_BADFORMAT);

                }
            }
        }

        //
        // We need to check if there are any gaps in the vtable. These are
        // represented by methods with the mdSpecial flag and a name of the form
        // _VTblGap_nnn (to represent nnn empty slots) or _VTblGap (to represent a
        // single empty slot).
        //

        if (IsMdRTSpecialName(dwMemberAttrs))
        {
            PREFIX_ASSUME(strMethodName != NULL); // if we've gotten here we've called GetNameOfMethodDef

            // The slot is special, but it might not be a vtable spacer. To
            // determine that we must look at the name.
            if (strncmp(strMethodName, "_VtblGap", 8) == 0)
            {
                                //
                // This slot doesn't really exist, don't add it to the method
                // table. Instead it represents one or more empty slots, encoded
                // in the method name. Locate the beginning of the count in the
                // name. There are these points to consider:
                //   There may be no count present at all (in which case the
                //   count is taken as one).
                //   There may be an additional count just after Gap but before
                //   the '_'. We ignore this.
                                //

                LPCSTR pos = strMethodName + 8;

                // Skip optional number.
                while (IS_DIGIT(*pos))
                    pos++;

                WORD n = 0;

                // Check for presence of count.
                if (*pos == '\0')
                    n = 1;
                else
                {
                    if (*pos != '_')
                    {
                        BuildMethodTableThrowException(COR_E_BADIMAGEFORMAT,
                                                       IDS_CLASSLOAD_BADSPECIALMETHOD,
                                                       tok);
                    }

                    // Skip '_'.
                    pos++;

                    // Read count.
                    bool fReadAtLeastOneDigit = false;
                    while (IS_DIGIT(*pos))
                    {
                        _ASSERTE(n < 6552);
                        n *= 10;
                        n += DIGIT_TO_INT(*pos);
                        pos++;
                        fReadAtLeastOneDigit = true;
                    }

                    // Check for end of name.
                    if (*pos != '\0' || !fReadAtLeastOneDigit)
                    {
                        BuildMethodTableThrowException(COR_E_BADIMAGEFORMAT,
                                                       IDS_CLASSLOAD_BADSPECIALMETHOD,
                                                       tok);
                    }
                }

#ifdef FEATURE_COMINTEROP
                // Record vtable gap in mapping list.
                if (GetHalfBakedClass()->GetSparseCOMInteropVTableMap() == NULL)
                    GetHalfBakedClass()->SetSparseCOMInteropVTableMap(new SparseVTableMap());

                GetHalfBakedClass()->GetSparseCOMInteropVTableMap()->RecordGap(NumDeclaredMethods(), n);

                bmtProp->fSparse = true;
#endif // FEATURE_COMINTEROP
                continue;
            }

        }


        //
        // This is a real method so add it to the enumeration of methods. We now need to retrieve
        // information on the method and store it for later use.
        //
        if (FAILED(pMDInternalImport->GetMethodImplProps(tok, &dwMethodRVA, &dwImplFlags)))
        {
            BuildMethodTableThrowException(BFA_INVALID_TOKEN);
        }
        //
        // But first - minimal flags validity checks
        //
        // No methods in Enums!
        if (fIsClassEnum)
        {
            BuildMethodTableThrowException(BFA_METHOD_IN_A_ENUM);
        }
        // RVA : 0
        if (dwMethodRVA != 0)
        {
#ifdef FEATURE_COMINTEROP
            if(fIsClassComImport)
            {
                BuildMethodTableThrowException(BFA_METHOD_WITH_NONZERO_RVA);
            }
#endif // FEATURE_COMINTEROP
            if(IsMdAbstract(dwMemberAttrs))
            {
                BuildMethodTableThrowException(BFA_ABSTRACT_METHOD_WITH_RVA);
            }
            if(IsMiRuntime(dwImplFlags))
            {
                BuildMethodTableThrowException(BFA_RUNTIME_METHOD_WITH_RVA);
            }
            if(IsMiInternalCall(dwImplFlags))
            {
                BuildMethodTableThrowException(BFA_INTERNAL_METHOD_WITH_RVA);
            }
        }

        // Abstract / not abstract
        if(IsMdAbstract(dwMemberAttrs))
        {
            if(fIsClassNotAbstract)
            {
                BuildMethodTableThrowException(BFA_AB_METHOD_IN_AB_CLASS);
            }
            if(!IsMdVirtual(dwMemberAttrs))
            {
                BuildMethodTableThrowException(BFA_NONVIRT_AB_METHOD);
            }
        }
        else if(fIsClassInterface && strMethodName &&
                (strcmp(strMethodName, COR_CCTOR_METHOD_NAME)))
        {
            BuildMethodTableThrowException(BFA_NONAB_NONCCTOR_METHOD_ON_INT);
        }

        // Virtual / not virtual
        if(IsMdVirtual(dwMemberAttrs))
        {
            if(IsMdPinvokeImpl(dwMemberAttrs))
            {
                BuildMethodTableThrowException(BFA_VIRTUAL_PINVOKE_METHOD);
            }
            if(IsMdStatic(dwMemberAttrs))
            {
                BuildMethodTableThrowException(BFA_VIRTUAL_STATIC_METHOD);
            }
            if(strMethodName && (0==strcmp(strMethodName, COR_CTOR_METHOD_NAME)))
            {
                BuildMethodTableThrowException(BFA_VIRTUAL_INSTANCE_CTOR);
            }
        }

        // Some interface checks.
        // We only need them if default interface method support is disabled or if this is fragile crossgen
#if !defined(FEATURE_DEFAULT_INTERFACES) || defined(FEATURE_NATIVE_IMAGE_GENERATION)
        if (fIsClassInterface
#if defined(FEATURE_DEFAULT_INTERFACES)
            // Only fragile crossgen wasn't upgraded to deal with default interface methods.
            && !IsReadyToRunCompilation()
#endif
            )
        {
            if (IsMdVirtual(dwMemberAttrs))
            {
                if (!IsMdAbstract(dwMemberAttrs))
                {
                    BuildMethodTableThrowException(BFA_VIRTUAL_NONAB_INT_METHOD);
                }
            }
            else
            {
                // Instance method
                if (!IsMdStatic(dwMemberAttrs))
                {
                    BuildMethodTableThrowException(BFA_NONVIRT_INST_INT_METHOD);
                }
            }
        }
#endif // !defined(FEATURE_DEFAULT_INTERFACES) || defined(FEATURE_NATIVE_IMAGE_GENERATION)

        // No synchronized methods in ValueTypes
        if(fIsClassValueType && IsMiSynchronized(dwImplFlags))
        {
            BuildMethodTableThrowException(BFA_SYNC_METHOD_IN_VT);
        }

        // Global methods:
        if(IsGlobalClass())
        {
            if(!IsMdStatic(dwMemberAttrs))
            {
                BuildMethodTableThrowException(BFA_NONSTATIC_GLOBAL_METHOD);
            }
            if (strMethodName)  //<TODO>@todo: investigate mc++ generating null name</TODO>
            {
                if(0==strcmp(strMethodName, COR_CTOR_METHOD_NAME))
                {
                    BuildMethodTableThrowException(BFA_GLOBAL_INST_CTOR);
                }
            }
        }
        //@GENERICS:
        // Generic methods or methods in generic classes
        // may not be part of a COM Import class, PInvoke, internal call.
        if ((numGenericMethodArgs != 0) &&
            (
#ifdef FEATURE_COMINTEROP
             fIsClassComImport ||
             bmtProp->fComEventItfType ||
#endif // FEATURE_COMINTEROP
             IsMdPinvokeImpl(dwMemberAttrs) ||
             IsMiInternalCall(dwImplFlags)))
        {
            BuildMethodTableThrowException(BFA_BAD_PLACE_FOR_GENERIC_METHOD);
        }

        // Generic methods may not be marked "runtime".  However note that
        // methods in generic delegate classes are, hence we don't apply this to
        // methods in generic classes in general.
        if (numGenericMethodArgs != 0 && IsMiRuntime(dwImplFlags))
        {
            BuildMethodTableThrowException(BFA_GENERIC_METHOD_RUNTIME_IMPL);
        }

        // Signature validation
        if (FAILED(pMDInternalImport->GetSigOfMethodDef(tok,&cMemberSignature, &pMemberSignature)))
        {
            BuildMethodTableThrowException(IDS_CLASSLOAD_BADFORMAT);
        }
        hr = validateTokenSig(tok,pMemberSignature,cMemberSignature,dwMemberAttrs,pMDInternalImport);
        if (FAILED(hr))
        {
            BuildMethodTableThrowException(hr, BFA_BAD_SIGNATURE, mdMethodDefNil);
        }

        //
        // Determine the method's classification.
        //

        if (IsReallyMdPinvokeImpl(dwMemberAttrs) || IsMiInternalCall(dwImplFlags))
        {
            hr = NDirect::HasNAT_LAttribute(pMDInternalImport, tok, dwMemberAttrs);

            // There was a problem querying for the attribute
            if (FAILED(hr))
            {
                BuildMethodTableThrowException(hr, IDS_CLASSLOAD_BADPINVOKE, tok);
            }

            // The attribute is not present
            if (hr == S_FALSE)
            {
#ifdef FEATURE_COMINTEROP
                if (fIsClassComImport || bmtProp->fComEventItfType)
                {
                    // tlbimported component
                    if (IsMdRTSpecialName(dwMemberAttrs))
                    {
                        // constructor is special
                        Classification = mcFCall;
                    }
                    else
                    {
                        // Tlbimported components we have some
                        // method descs in the call which are just used
                        // for handling methodimpls of all interface methods
                        Classification = mcComInterop;
                    }
                }
                else
#endif // FEATURE_COMINTEROP
                if (dwMethodRVA == 0)
                    Classification = mcFCall;
                else
                    Classification = mcNDirect;
            }
            // The NAT_L attribute is present, marking this method as NDirect
            else
            {
                CONSISTENCY_CHECK(hr == S_OK);
                Classification = mcNDirect;
            }
        }
        else if (IsMiRuntime(dwImplFlags))
        {
                // currently the only runtime implemented functions are delegate instance methods
            if (!IsDelegate() || IsMdStatic(dwMemberAttrs) || IsMdAbstract(dwMemberAttrs))
            {
                BuildMethodTableThrowException(BFA_BAD_RUNTIME_IMPL);
            }

            unsigned newDelegateMethodSeen = 0;

            if (IsMdRTSpecialName(dwMemberAttrs))   // .ctor
            {
                if (strcmp(strMethodName, COR_CTOR_METHOD_NAME) != 0 || IsMdVirtual(dwMemberAttrs))
                {
                    BuildMethodTableThrowException(BFA_BAD_FLAGS_ON_DELEGATE);
                }
                newDelegateMethodSeen = SeenCtor;
                Classification = mcFCall;
            }
            else
            {
                if (strcmp(strMethodName, "Invoke") == 0)
                    newDelegateMethodSeen = SeenInvoke;
                else if (strcmp(strMethodName, "BeginInvoke") == 0)
                    newDelegateMethodSeen = SeenBeginInvoke;
                else if (strcmp(strMethodName, "EndInvoke") == 0)
                    newDelegateMethodSeen = SeenEndInvoke;
                else
                {
                    BuildMethodTableThrowException(BFA_UNKNOWN_DELEGATE_METHOD);
                }
                Classification = mcEEImpl;
            }

            // If we get here we have either set newDelegateMethodSeen or we have thrown a BMT exception
            _ASSERTE(newDelegateMethodSeen != 0);

            if ((delegateMethodsSeen & newDelegateMethodSeen) != 0)
            {
                BuildMethodTableThrowException(BFA_DUPLICATE_DELEGATE_METHOD);
            }

            delegateMethodsSeen |= newDelegateMethodSeen;
        }
        else if (numGenericMethodArgs != 0)
        {
            //We use an instantiated method desc to represent a generic method
            Classification = mcInstantiated;
        }
        else if (fIsClassInterface)
        {
#ifdef FEATURE_COMINTEROP
            if (IsMdStatic(dwMemberAttrs))
            {
                // Static methods in interfaces need nothing special.
                Classification = mcIL;
            }
            else if (bmtProp->fIsMngStandardItf)
            {
                // If the interface is a standard managed interface then allocate space for an FCall method desc.
                Classification = mcFCall;
            }
            else if (IsMdAbstract(dwMemberAttrs))
            {
                // If COM interop is supported then all other interface MDs may be
                // accessed via COM interop <TODO> mcComInterop MDs are BIG -
                // this is very often a waste of space </TODO>
                // @DIM_TODO - What if default interface method is called through COM interop?
                Classification = mcComInterop;
            }
            else
#endif // !FEATURE_COMINTEROP
            {
                // This codepath is used by remoting and default interface methods
                Classification = mcIL;
            }
        }
        else
        {
            Classification = mcIL;
        }

        // Generic methods should always be mcInstantiated
        if (!((numGenericMethodArgs == 0) || ((Classification & mdcClassification) == mcInstantiated)))
        {
            BuildMethodTableThrowException(BFA_GENERIC_METHODS_INST);
        }
        // count how many overrides this method does All methods bodies are defined
        // on this type so we can just compare the tok with the body token found
        // from the overrides.
        for(DWORD impls = 0; impls < bmtMethodImpl->dwNumberMethodImpls; impls++) {
            if(bmtMethodImpl->rgMethodImplTokens[impls].methodBody == tok) {
                Classification |= mdcMethodImpl;
                break;
            }
        }

        // For delegates we don't allow any non-runtime implemented bodies
        // for any of the four special methods
        if (IsDelegate() && !IsMiRuntime(dwImplFlags))
        {
            if ((strcmp(strMethodName, COR_CTOR_METHOD_NAME) == 0) ||
                (strcmp(strMethodName, "Invoke")             == 0) || 
                (strcmp(strMethodName, "BeginInvoke")        == 0) || 
                (strcmp(strMethodName, "EndInvoke")          == 0)   )  
            {
                BuildMethodTableThrowException(BFA_ILLEGAL_DELEGATE_METHOD);
            }
        }

        //
        // Compute the type & other info
        //

        // Set the index into the storage locations
        BYTE impl;
        if (Classification & mdcMethodImpl)
        {
            impl = METHOD_IMPL;
        }
        else
        {
            impl = METHOD_IMPL_NOT;
        }

        BYTE type;
        if ((Classification & mdcClassification)  == mcNDirect)
        {
            type = METHOD_TYPE_NDIRECT;
        }
        else if ((Classification & mdcClassification) == mcFCall)
        {
            type = METHOD_TYPE_FCALL;
        }
        else if ((Classification & mdcClassification) == mcEEImpl)
        {
            type = METHOD_TYPE_EEIMPL;
        }
#ifdef FEATURE_COMINTEROP
        else if ((Classification & mdcClassification) == mcComInterop)
        {
            type = METHOD_TYPE_INTEROP;
        }
#endif // FEATURE_COMINTEROP
        else if ((Classification & mdcClassification) == mcInstantiated)
        {
            type = METHOD_TYPE_INSTANTIATED;
        }
        else
        {
            type = METHOD_TYPE_NORMAL;
        }

        //
        // Store the method and the information we have gathered on it in the metadata info structure.
        //

        bmtMethod->SetMethodData(NumDeclaredMethods(),
                                 tok,
                                 dwMemberAttrs,
                                 dwMethodRVA,
                                 dwImplFlags,
                                 Classification,
                                 strMethodName,
                                 impl,
                                 type);

        IncNumDeclaredMethods();

        //
        // Update the count of the various types of methods.
        //

        bmtVT->dwMaxVtableSize++;
    }

    // Check to see that we have all of the required delegate methods (ECMA 13.6 Delegates)
    if (IsDelegate())
    {
        // Do we have all four special delegate methods 
        // or just the two special delegate methods 
        if ((delegateMethodsSeen != (SeenCtor | SeenInvoke | SeenBeginInvoke | SeenEndInvoke)) &&
            (delegateMethodsSeen != (SeenCtor | SeenInvoke)) )
        {
            BuildMethodTableThrowException(BFA_MISSING_DELEGATE_METHOD);
        }
    }

    if (i != bmtMethod->cMethAndGaps)
    {
        BuildMethodTableThrowException(COR_E_BADIMAGEFORMAT, IDS_CLASSLOAD_BAD_METHOD_COUNT, mdTokenNil);
    }

    bmtMethod->hEnumMethod.EnumReset();

#ifdef FEATURE_COMINTEROP
    //
    // If the interface is sparse, we need to finalize the mapping list by
    // telling it how many real methods we found.
    //

    if (bmtProp->fSparse)
    {
        GetHalfBakedClass()->GetSparseCOMInteropVTableMap()->FinalizeMapping(NumDeclaredMethods());
    }
#endif // FEATURE_COMINTEROP
}

#ifdef _PREFAST_
#pragma warning(pop)
#endif

//*******************************************************************************
//
// Used by BuildMethodTable
//
// Determines the maximum size of the vtable and allocates the temporary storage arrays
// Also copies the parent's vtable into the working vtable.
//
VOID    MethodTableBuilder::AllocateMethodWorkingMemory()
{
    CONTRACTL
    {
        STANDARD_VM_CHECK;
        PRECONDITION(CheckPointer(this));
        PRECONDITION(CheckPointer(bmtMethod));
        PRECONDITION(CheckPointer(bmtVT));
        PRECONDITION(CheckPointer(bmtInterface));
        PRECONDITION(CheckPointer(bmtParent));

    }
    CONTRACTL_END;

    DWORD i;
    // Allocate a MethodDesc* for each method (needed later when doing interfaces), and a FieldDesc* for each field
    bmtMethod->ppMethodDescList = new (GetStackingAllocator()) MethodDesc*[NumDeclaredMethods()];
    ZeroMemory(bmtMethod->ppMethodDescList, NumDeclaredMethods() * sizeof(MethodDesc *));

    // Create a temporary function table (we don't know how large the vtable will be until the very end,
    // since duplicated interfaces are stored at the end of it).  Calculate an upper bound.
    //
    // Upper bound is: The parent's class vtable size, plus every method declared in
    //                 this class, plus the size of every interface we implement
    //
    // In the case of value classes, we add # InstanceMethods again, since we have boxed and unboxed versions
    // of every vtable method.
    //
    if (IsValueClass())
    {
        bmtVT->dwMaxVtableSize += NumDeclaredMethods();
        bmtMethod->ppUnboxMethodDescList = new (GetStackingAllocator()) MethodDesc*[NumDeclaredMethods()];
        ZeroMemory(bmtMethod->ppUnboxMethodDescList, NumDeclaredMethods() * sizeof(MethodDesc*));
    }

    // sanity check
    _ASSERTE(bmtParent->pParentMethodTable == NULL ||
             (bmtInterface->wInterfaceMapSize - bmtParent->pParentMethodTable->GetNumInterfaces()) >= 0);

    // add parent vtable size
    bmtVT->dwMaxVtableSize += bmtVT->wCurrentVtableSlot;

    for (i = 0; i < bmtInterface->wInterfaceMapSize; i++)
    {
        // We double the interface size because we may end up duplicating the Interface for MethodImpls
        bmtVT->dwMaxVtableSize += (bmtInterface->pInterfaceMap[i].m_pMethodTable->GetNumVirtuals() * 2);
    }

    // Allocate the temporary vtable
    bmtVT->pVtable = new (GetStackingAllocator())PCODE [bmtVT->dwMaxVtableSize];
    ZeroMemory(bmtVT->pVtable, bmtVT->dwMaxVtableSize * sizeof(PCODE));
    bmtVT->pVtableMD = new (GetStackingAllocator()) MethodDesc*[bmtVT->dwMaxVtableSize];
    ZeroMemory(bmtVT->pVtableMD, bmtVT->dwMaxVtableSize * sizeof(MethodDesc*));

    // Allocate the temporary non-vtable
    bmtVT->pNonVtableMD = new (GetStackingAllocator()) MethodDesc*[NumDeclaredMethods()];
    ZeroMemory(bmtVT->pNonVtableMD, sizeof(MethodDesc*) * NumDeclaredMethods());

    if (bmtParent->pParentMethodTable != NULL)
    {
        // Copy parent's vtable into our "temp" vtable
        {
            MethodTable::MethodIterator it(bmtParent->pParentMethodTable);
            for (;it.IsValid() && it.IsVirtual(); it.Next()) {                
                DWORD slot = it.GetSlotNumber();
                bmtVT->pVtable[slot] = it.GetTarget().GetTarget();
                bmtVT->pVtableMD[slot] = NULL; // MethodDescs are resolved lazily
            }
            bmtVT->pParentMethodTable = bmtParent->pParentMethodTable;
        }

#if 0
        // @<TODO>todo: Figure out the right way to override Equals for value
        // types only.
        //
        // This is broken because
        // (a) g_pObjectClass->FindMethod("Equals", &gsig_IM_Obj_RetBool); will return
        //      the EqualsValue method
        // (b) When mscorlib has been preloaded (and thus the munge already done
        //      ahead of time), we cannot easily find both methods
        //      to compute EqualsAddr & EqualsSlot
        //
        // For now, the Equals method has a runtime check to see if it's
        // comparing value types.
        //</TODO>

        // If it is a value type, over ride a few of the base class methods.
        if (IsValueClass())
        {
            static WORD EqualsSlot;

            // If we haven't been through here yet, get some stuff from the Object class definition.
            if (EqualsSlot == NULL)
            {
                // Get the slot of the Equals method.
                MethodDesc *pEqualsMD = g_pObjectClass->FindMethod("Equals", &gsig_IM_Obj_RetBool);
                THROW_BAD_FORMAT_MAYBE(pEqualsMD != NULL, 0, this);
                EqualsSlot = pEqualsMD->GetSlot();

                // Get the address of the EqualsValue method.
                MethodDesc *pEqualsValueMD = g_pObjectClass->FindMethod("EqualsValue", &gsig_IM_Obj_RetBool);
                THROW_BAD_FORMAT_MAYBE(pEqualsValueMD != NULL, 0, this);

                // Patch the EqualsValue method desc in a dangerous way to
                // look like the Equals method desc.
                pEqualsValueMD->SetSlot(EqualsSlot);
                pEqualsValueMD->SetMemberDef(pEqualsMD->GetMemberDef());
            }

            // Override the valuetype "Equals" with "EqualsValue".
            bmtVT->SetMethodDescForSlot(EqualsSlot, EqualsSlot);
        }
#endif // 0
    }

    if (NumDeclaredMethods() > 0)
    {
        bmtParent->ppParentMethodDescBuf = (MethodDesc **)
            GetStackingAllocator()->Alloc(S_UINT32(2) * S_UINT32(NumDeclaredMethods()) *
                                          S_UINT32(sizeof(MethodDesc*)));

        bmtParent->ppParentMethodDescBufPtr = bmtParent->ppParentMethodDescBuf;
    }
}

//*******************************************************************************
//
// Find a method in this class hierarchy - used ONLY by the loader during layout.  Do not use at runtime.
//
// *ppMemberSignature must be NULL on entry - it and *pcMemberSignature may or may not be filled out
//
// ppMethodDesc will be filled out with NULL if no matching method in the hierarchy is found.
//
// Returns FALSE if there was an error of some kind.
//
// pMethodConstraintsMatch receives the result of comparing the method constraints.
HRESULT MethodTableBuilder::LoaderFindMethodInClass(
    LPCUTF8             pszMemberName,
    Module*             pModule,
    mdMethodDef         mdToken,
    MethodDesc **       ppMethodDesc,
    PCCOR_SIGNATURE *   ppMemberSignature,
    DWORD *             pcMemberSignature,
    DWORD               dwHashName,
    BOOL *              pMethodConstraintsMatch)
{
    CONTRACTL
    {
        STANDARD_VM_CHECK;
        PRECONDITION(CheckPointer(this));
        PRECONDITION(CheckPointer(bmtParent));
        PRECONDITION(CheckPointer(pModule));
        PRECONDITION(CheckPointer(ppMethodDesc));
        PRECONDITION(CheckPointer(ppMemberSignature));
        PRECONDITION(CheckPointer(pcMemberSignature));
    }
    CONTRACTL_END;
    
    HRESULT          hr;
    MethodHashEntry *pEntry;
    DWORD            dwNameHashValue;
    
    _ASSERTE(pModule);
    _ASSERTE(*ppMemberSignature == NULL);
    
    // No method found yet
    *ppMethodDesc = NULL;
    
    // Have we created a hash of all the methods in the class chain?
    if (bmtParent->pParentMethodHash == NULL)
    {
        // There may be such a method, so we will now create a hash table to reduce the pain for
        // further lookups
        
        // <TODO> Are we really sure that this is worth doing? </TODO>
        bmtParent->pParentMethodHash = CreateMethodChainHash(bmtParent->pParentMethodTable);
    }
    
    // Look to see if the method exists in the parent hash
    pEntry = bmtParent->pParentMethodHash->Lookup(pszMemberName, dwHashName);
    if (pEntry == NULL)
    {
        return S_OK; // No method by this name exists in the hierarchy
    }
    
    // Get signature of the method we're searching for - we will need this to verify an exact name-signature match
    IfFailRet(pModule->GetMDImport()->GetSigOfMethodDef(
        mdToken, 
        pcMemberSignature, 
        ppMemberSignature));
    
    // Hash value we are looking for in the chain
    dwNameHashValue = pEntry->m_dwHashValue;
    
    // We've found a method with the same name, but the signature may be different
    // Traverse the chain of all methods with this name
    while (1)
    {
        PCCOR_SIGNATURE     pHashMethodSig  = NULL;
        DWORD               cHashMethodSig  = 0;
        Substitution *      pSubst          = NULL;
        MethodDesc *        entryDesc       = pEntry->m_pDesc;
        MethodTable *       entryMT         = entryDesc->GetMethodTable();
        MethodTable *       entryCanonMT    = entryMT->GetCanonicalMethodTable();

        // If entry is in a parameterized type, its signature may need to be instantiated all the way down the chain
        // To understand why consider the following example:
        //   class C<T> { void m(T) { ...body... } }
        //   class D<T> : C<T[]> { /* inherits m with signature void m(T[]) */ }
        //   class E<T> : D<List<T>> { void m(List<T>[]) { ... body... } }
        // Now suppose that we've got the signature of E::m in our hand and are comparing it with the methoddesc for C.m
        // They're not syntactically the same but are if you instantiate "all the way up"
        // Possible optimization: don't bother constructing the substitution if the signature of pEntry is closed
        if (entryCanonMT->GetNumGenericArgs() > 0)
        {
            MethodTable *here = GetHalfBakedMethodTable();
            _ASSERTE(here->GetModule());
            MethodTable *pParent = bmtParent->pParentMethodTable;

            for (;;)
            {
                Substitution *newSubst = new Substitution;
                *newSubst = here->GetSubstitutionForParent(pSubst);
                pSubst = newSubst;

                here = pParent->GetCanonicalMethodTable();
                if (entryCanonMT == here)
                    break;
                pParent = pParent->GetParentMethodTable();
                _ASSERT(pParent != NULL);
            }            
        }

        // Get sig of entry in hash chain
        entryDesc->GetSig(&pHashMethodSig, &cHashMethodSig);

        // Note instantiation info
        {
            hr = MetaSig::CompareMethodSigsNT(*ppMemberSignature, *pcMemberSignature, pModule, NULL,
                                                      pHashMethodSig, cHashMethodSig, entryDesc->GetModule(), pSubst);

            if (hr == S_OK)
            {   // Found a match
                *ppMethodDesc = entryDesc;
                // Check the constraints are consistent,
                // and return the result to the caller.
                // We do this here to avoid recalculating pSubst.
                *pMethodConstraintsMatch =
                    MetaSig::CompareMethodConstraints(NULL, pModule, mdToken, pSubst,
                                                      entryDesc->GetModule(),
                                                      entryDesc->GetMemberDef());
            }
            
            if (pSubst != NULL)
            {
                pSubst->DeleteChain();
                pSubst = NULL;
            }
            
            if (FAILED(hr) || hr == S_OK)
            {
                return hr;
            }
        }
        
        do
        {   // Advance to next item in the hash chain which has the same name
            pEntry = pEntry->m_pNext; // Next entry in the hash chain

            if (pEntry == NULL)
            {
                return S_OK; // End of hash chain, no match found
            }
        } while ((pEntry->m_dwHashValue != dwNameHashValue) || (strcmp(pEntry->m_pKey, pszMemberName) != 0));
    }

    return S_OK;
}

//*******************************************************************************
//
// Find a method declaration that must reside in the scope passed in. This method cannot be called if
// the reference travels to another scope.
//
// Protect against finding a declaration that lives within
// us (the type being created)
//

HRESULT MethodTableBuilder::FindMethodDeclarationForMethodImpl(
    IMDInternalImport * pMDInternalImport, // Scope in which tkClass and tkMethod are defined.
    mdTypeDef           tkClass,           // Type that the method def resides in
    mdToken             tkMethod,          // Token that is being located (MemberRef or MethodDef)
    mdMethodDef *       ptkMethodDef)      // Method definition for Member
{
    STANDARD_VM_CONTRACT;

    HRESULT hr = S_OK;

    PCCOR_SIGNATURE pSig;  // Signature of Member
    DWORD           cSig;
    LPCUTF8         szMember = NULL;
    // The token should be a member ref or def. If it is a ref then we need to travel
    // back to us hopefully.
    if(TypeFromToken(tkMethod) == mdtMemberRef)
    {
        // Get the parent
        mdToken typeref;
        if (FAILED(pMDInternalImport->GetParentOfMemberRef(tkMethod, &typeref)))
        {
            BAD_FORMAT_NOTHROW_ASSERT(!"Invalid MemberRef record");
            IfFailRet(COR_E_TYPELOAD);
        }
        
        while (TypeFromToken(typeref) == mdtTypeSpec)
        {
            // Added so that method impls can refer to instantiated interfaces or classes
            if (FAILED(pMDInternalImport->GetSigFromToken(typeref, &cSig, &pSig)))
            {
                BAD_FORMAT_NOTHROW_ASSERT(!"Invalid TypeSpec record");
                IfFailRet(COR_E_TYPELOAD);
            }
            CorElementType elemType = (CorElementType) *pSig++;

            // If this is a generic inst, we expect that the next elem is ELEMENT_TYPE_CLASS,
            // which is handled in the case below.
            if (elemType == ELEMENT_TYPE_GENERICINST)
            {
                elemType = (CorElementType) *pSig++;
                BAD_FORMAT_NOTHROW_ASSERT(elemType == ELEMENT_TYPE_CLASS);
            }

            // This covers E_T_GENERICINST and E_T_CLASS typespec formats. We don't expect
            // any other kinds to come through here.
            if (elemType == ELEMENT_TYPE_CLASS)
            {
                CorSigUncompressToken(pSig, &typeref);
            }
            else
            {
                // This is an unrecognized signature format.
                BuildMethodTableThrowException(COR_E_BADIMAGEFORMAT,
                                               IDS_CLASSLOAD_MI_BAD_SIG,
                                               mdMethodDefNil);
            }
        }

        // If parent is a method def then this is a varags method
        if (TypeFromToken(typeref) == mdtMethodDef)
        {
            mdTypeDef typeDef;
            IfFailRet(pMDInternalImport->GetParentToken(typeref, &typeDef));

            // Make sure it is a typedef
            if (TypeFromToken(typeDef) != mdtTypeDef)
            {
                BAD_FORMAT_NOTHROW_ASSERT(!"MethodDef without TypeDef as Parent");
                IfFailRet(COR_E_TYPELOAD);
            }
            BAD_FORMAT_NOTHROW_ASSERT(typeDef == tkClass);
            // This is the real method we are overriding
            // <TODO>@TODO: CTS this may be illegal and we could throw an error</TODO>
            *ptkMethodDef = typeref;
        }

        else
        {
            // Verify that the ref points back to us
            mdToken tkDef = mdTokenNil;

            // We only get here when we know the token does not reference a type
            // in a different scope.
            if(TypeFromToken(typeref) == mdtTypeRef)
            {
                LPCUTF8 pszNameSpace;
                LPCUTF8 pszClassName;

                if (FAILED(pMDInternalImport->GetNameOfTypeRef(typeref, &pszNameSpace, &pszClassName)))
                {
                    IfFailRet(COR_E_TYPELOAD);
                }
                mdToken tkRes;
                if (FAILED(pMDInternalImport->GetResolutionScopeOfTypeRef(typeref, &tkRes)))
                {
                    IfFailRet(COR_E_TYPELOAD);
                }
                hr = pMDInternalImport->FindTypeDef(pszNameSpace,
                                                    pszClassName,
                                                    (TypeFromToken(tkRes) == mdtTypeRef) ? tkRes : mdTokenNil,
                                                    &tkDef);
                if(FAILED(hr))
                {
                    IfFailRet(COR_E_TYPELOAD);
                }
            }

            // We get a typedef when the parent of the token is a typespec to the type.
            else if (TypeFromToken(typeref) == mdtTypeDef)
            {
                tkDef = typeref;
            }

            else
            {
                CONSISTENCY_CHECK_MSGF(FALSE, ("Invalid methodimpl signature in class %s.", GetDebugClassName()));
                BuildMethodTableThrowException(COR_E_BADIMAGEFORMAT,
                                               IDS_CLASSLOAD_MI_BAD_SIG,
                                               mdMethodDefNil);
            }

            // If we required that the typedef be the same type as the current class,
            // and it doesn't match, we need to return a failure result.
            if (tkDef != tkClass)
            {
                IfFailRet(COR_E_TYPELOAD);
            }
            
            IfFailRet(pMDInternalImport->GetNameAndSigOfMemberRef(tkMethod, &pSig, &cSig, &szMember));
            
            if (isCallConv(
                MetaSig::GetCallingConvention(NULL, Signature(pSig, cSig)), 
                IMAGE_CEE_CS_CALLCONV_FIELD))
            {
                return VLDTR_E_MR_BADCALLINGCONV;
            }
            
            hr = pMDInternalImport->FindMethodDef(
                tkDef, szMember, pSig, cSig, ptkMethodDef);
            IfFailRet(hr);
        }
    }

    else if (TypeFromToken(tkMethod) == mdtMethodDef)
    {
        mdTypeDef typeDef;

        // Verify that we are the parent
        hr = pMDInternalImport->GetParentToken(tkMethod, &typeDef);
        IfFailRet(hr);

        if(typeDef != tkClass)
        {
            IfFailRet(COR_E_TYPELOAD);
        }

        *ptkMethodDef = tkMethod;
    }

    else
    {
        IfFailRet(COR_E_TYPELOAD);
    }

    return hr;
}

//*******************************************************************************
void MethodTableBuilder::bmtMethodImplInfo::AddMethod(MethodDesc* pImplDesc, MethodDesc* pDesc, mdToken mdDecl, Substitution *pDeclSubst)
{
    LIMITED_METHOD_CONTRACT;
    _ASSERTE((pDesc == NULL || mdDecl == mdTokenNil) && (pDesc != NULL || mdDecl != mdTokenNil));
    rgEntries[pIndex].pDeclDesc = pDesc;
    rgEntries[pIndex].declToken = mdDecl;
    rgEntries[pIndex].declSubst = *pDeclSubst;
    rgEntries[pIndex].pBodyDesc = pImplDesc;
    pIndex++;
}

//*******************************************************************************
// Returns TRUE if tok acts as a body for any methodImpl entry. FALSE, otherwise.
BOOL MethodTableBuilder::bmtMethodImplInfo::IsBody(mdToken tok)
{
    LIMITED_METHOD_CONTRACT;
    CONSISTENCY_CHECK(TypeFromToken(tok) == mdtMethodDef);
    for (DWORD i = 0; i < pIndex; i++) {
        if (GetBodyMethodDesc(i)->GetMemberDef() == tok) {
            return TRUE;
        }
    }
    return FALSE;
}

//*******************************************************************************
// Returns TRUE for success, FALSE for failure
void MethodNameHash::Init(DWORD dwMaxEntries, StackingAllocator *pAllocator)
{
    CONTRACTL
    {
        THROWS;
        GC_NOTRIGGER;
        PRECONDITION(CheckPointer(this));
    }
    CONTRACTL_END;

    // Given dwMaxEntries, determine a good value for the number of hash buckets
    m_dwNumBuckets = (dwMaxEntries / 10);

    if (m_dwNumBuckets < 5)
        m_dwNumBuckets = 5;

    S_UINT32 scbMemory = (S_UINT32(m_dwNumBuckets) * S_UINT32(sizeof(MethodHashEntry*))) +
                         (S_UINT32(dwMaxEntries) * S_UINT32(sizeof(MethodHashEntry)));

    if (scbMemory.IsOverflow())
    {
        ThrowHR(E_INVALIDARG);
    }

    if (pAllocator)
    {
        m_pMemoryStart = (BYTE*)pAllocator->Alloc(scbMemory);
    }
    else
    {   // We're given the number of hash table entries we're going to insert,
        // so we can allocate the appropriate size
        m_pMemoryStart = new BYTE[scbMemory.Value()];
    }

    INDEBUG(m_pDebugEndMemory = m_pMemoryStart + scbMemory.Value();)

    // Current alloc ptr
    m_pMemory       = m_pMemoryStart;

    // Allocate the buckets out of the alloc ptr
    m_pBuckets      = (MethodHashEntry**) m_pMemory;
    m_pMemory += sizeof(MethodHashEntry*)*m_dwNumBuckets;

    // Buckets all point to empty lists to begin with
    memset(m_pBuckets, 0, scbMemory.Value());
}

//*******************************************************************************
// Insert new entry at head of list
void MethodNameHash::Insert(LPCUTF8 pszName, MethodDesc *pDesc)
{
    LIMITED_METHOD_CONTRACT;
    DWORD           dwHash = HashStringA(pszName);
    DWORD           dwBucket = dwHash % m_dwNumBuckets;
    MethodHashEntry*pNewEntry;

    pNewEntry = (MethodHashEntry *) m_pMemory;
    m_pMemory += sizeof(MethodHashEntry);

    _ASSERTE(m_pMemory <= m_pDebugEndMemory);

    // Insert at head of bucket chain
    pNewEntry->m_pNext        = m_pBuckets[dwBucket];
    pNewEntry->m_pDesc        = pDesc;
    pNewEntry->m_dwHashValue  = dwHash;
    pNewEntry->m_pKey         = pszName;

    m_pBuckets[dwBucket] = pNewEntry;
}

//*******************************************************************************
// Return the first MethodHashEntry with this name, or NULL if there is no such entry
MethodHashEntry *MethodNameHash::Lookup(LPCUTF8 pszName, DWORD dwHash)
{
    STATIC_CONTRACT_NOTHROW;
    STATIC_CONTRACT_GC_NOTRIGGER;
    STATIC_CONTRACT_FORBID_FAULT;


    if (!dwHash)
        dwHash = HashStringA(pszName);
    DWORD           dwBucket = dwHash % m_dwNumBuckets;
    MethodHashEntry*pSearch;

    for (pSearch = m_pBuckets[dwBucket]; pSearch; pSearch = pSearch->m_pNext)
    {
        if (pSearch->m_dwHashValue == dwHash && !strcmp(pSearch->m_pKey, pszName))
            return pSearch;
    }

    return NULL;
}

//*******************************************************************************
//
// Create a hash of all methods in this class.  The hash is from method name to MethodDesc.
//
MethodNameHash *MethodTableBuilder::CreateMethodChainHash(MethodTable *pMT)
{
    STANDARD_VM_CONTRACT;

    MethodNameHash *pHash = new (GetStackingAllocator()) MethodNameHash();

    pHash->Init(pMT->GetNumVirtuals(), GetStackingAllocator());

    MethodTable::MethodIterator it(pMT);
    for (;it.IsValid(); it.Next())
    {
        if (it.IsVirtual())
            {
            MethodDesc *pImplDesc = it.GetMethodDesc();
            CONSISTENCY_CHECK(CheckPointer(pImplDesc));
            MethodDesc *pDeclDesc = it.GetDeclMethodDesc();
            CONSISTENCY_CHECK(CheckPointer(pDeclDesc));

            CONSISTENCY_CHECK(pMT->IsInterface() || !pDeclDesc->IsInterface());
            pHash->Insert(pDeclDesc->GetNameOnNonArrayClass(), pDeclDesc);
        }
    }

    // Success
    return pHash;
}

//*******************************************************************************
void MethodTableBuilder::SetBMTData(
    bmtErrorInfo *bmtError,
    bmtProperties *bmtProp,
    bmtVtable *bmtVT,
    bmtParentInfo *bmtParent,
    bmtInterfaceInfo *bmtInterface,
    bmtMethodInfo *bmtMethod,
    bmtTypeInfo *bmtType,
    bmtMethodImplInfo *bmtMethodImpl)
{
    LIMITED_METHOD_CONTRACT;
    this->bmtError = bmtError;
    this->bmtProp = bmtProp;
    this->bmtVT = bmtVT;
    this->bmtParent = bmtParent;
    this->bmtInterface = bmtInterface;
    this->bmtMethod = bmtMethod;
    this->bmtType = bmtType;
    this->bmtMethodImpl = bmtMethodImpl;
}

//*******************************************************************************
void MethodTableBuilder::NullBMTData()
{
    LIMITED_METHOD_CONTRACT;
    this->bmtError = NULL;
    this->bmtProp = NULL;
    this->bmtVT = NULL;
    this->bmtParent = NULL;
    this->bmtInterface = NULL;
    this->bmtMethod = NULL;
    this->bmtType = NULL;
    this->bmtMethodImpl = NULL;
}

//*******************************************************************************
/*static*/
VOID DECLSPEC_NORETURN MethodTableBuilder::BuildMethodTableThrowException(
    HRESULT hr,
    const bmtErrorInfo & bmtError)
{
    STANDARD_VM_CONTRACT;

    LPCUTF8 pszClassName, pszNameSpace;
    if (FAILED(bmtError.pModule->GetMDImport()->GetNameOfTypeDef(bmtError.cl, &pszClassName, &pszNameSpace)))
    {
        pszClassName = pszNameSpace = "Invalid TypeDef record";
    }
    
    if (IsNilToken(bmtError.dMethodDefInError) && bmtError.szMethodNameForError == NULL) {
        if (hr == E_OUTOFMEMORY)
            COMPlusThrowOM();
        else
            bmtError.pModule->GetAssembly()->ThrowTypeLoadException(pszNameSpace, pszClassName,
                                                                    bmtError.resIDWhy);
    }
    else {
        LPCUTF8 szMethodName;
        if (bmtError.szMethodNameForError == NULL)
        {
            if (FAILED((bmtError.pModule->GetMDImport())->GetNameOfMethodDef(bmtError.dMethodDefInError, &szMethodName)))
            {
                szMethodName = "Invalid MethodDef record";
            }
        }
        else
            szMethodName = bmtError.szMethodNameForError;

        bmtError.pModule->GetAssembly()->ThrowTypeLoadException(pszNameSpace, pszClassName,
                                                                szMethodName, bmtError.resIDWhy);
    }

}

//*******************************************************************************
/* static */
int __cdecl MethodTableBuilder::bmtMethodImplInfo::MethodImplTokenPair::Compare(
        const void *elem1,
        const void *elem2)
{
    STATIC_CONTRACT_LEAF;
    MethodImplTokenPair *e1 = (MethodImplTokenPair *)elem1;
    MethodImplTokenPair *e2 = (MethodImplTokenPair *)elem2;
    if (e1->methodBody < e2->methodBody) return -1;
    else if (e1->methodBody > e2->methodBody) return 1;
    else if (e1->methodDecl < e2->methodDecl) return -1;
    else if (e1->methodDecl > e2->methodDecl) return 1;
    else return 0;
}

//*******************************************************************************
/* static */
BOOL MethodTableBuilder::bmtMethodImplInfo::MethodImplTokenPair::Equal(
        const MethodImplTokenPair *elem1,
        const MethodImplTokenPair *elem2)
{
    STATIC_CONTRACT_LEAF;
    return ((elem1->methodBody == elem2->methodBody) &&
            (elem1->methodDecl == elem2->methodDecl));
}


}; // namespace ClassCompat

#endif // !DACCESS_COMPILE