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

NativeLayoutVertexNode.cs « DependencyAnalysis « Compiler « src « ILCompiler.Compiler « src - github.com/mono/corert.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: d48937e59ebf43eda0930bff3447962cae5016dd (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
// 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.

using System;
using System.Collections.Generic;
using System.Diagnostics;

using Internal.NativeFormat;
using Internal.Runtime;
using Internal.TypeSystem;
using ILCompiler.DependencyAnalysisFramework;

namespace ILCompiler.DependencyAnalysis
{
    /// <summary>
    /// Wrapper nodes for native layout vertex structures. These wrapper nodes are "abstract" as they do not 
    /// generate any data. They are used to keep track of the dependency nodes required by a Vertex structure.
    /// 
    /// Any node in the graph that references data in the native layout blob needs to create one of these
    /// NativeLayoutVertexNode nodes, and track it as a dependency of itself.
    /// Example: MethodCodeNodes that are saved to the table in the ExactMethodInstantiationsNode reference 
    /// signatures stored in the native layout blob, so a NativeLayoutPlacedSignatureVertexNode node is created
    /// and returned as a static dependency of the associated MethodCodeNode (in the GetStaticDependencies API).
    /// 
    /// Each NativeLayoutVertexNode that gets marked in the graph will register itself with the NativeLayoutInfoNode,
    /// so that the NativeLayoutInfoNode can write it later to the native layout blob during the call to its GetData API.
    /// </summary>
    public abstract class NativeLayoutVertexNode : DependencyNodeCore<NodeFactory>
    {
        public override bool HasConditionalStaticDependencies => false;
        public override bool HasDynamicDependencies => false;
        public override bool InterestingForDynamicDependencyAnalysis => false;
        public override bool StaticDependenciesAreComputed => true;


        [Conditional("DEBUG")]
        public virtual void CheckIfMarkedEnoughToWrite()
        {
            Debug.Assert(Marked);
        }

        public override IEnumerable<CombinedDependencyListEntry> GetConditionalStaticDependencies(NodeFactory context)
        {
            return Array.Empty<CombinedDependencyListEntry>();
        }

        public override IEnumerable<CombinedDependencyListEntry> SearchDynamicDependencies(List<DependencyNodeCore<NodeFactory>> markedNodes, int firstNode, NodeFactory context)
        {
            return Array.Empty<CombinedDependencyListEntry>();
        }

        protected override void OnMarked(NodeFactory context)
        {
            context.MetadataManager.NativeLayoutInfo.AddVertexNodeToNativeLayout(this);
        }

        public abstract Vertex WriteVertex(NodeFactory factory);

        protected NativeWriter GetNativeWriter(NodeFactory factory)
        {
            // There is only one native layout info blob, so only one writer for now...
            return factory.MetadataManager.NativeLayoutInfo.Writer;
        }
    }

    /// <summary>
    /// Any NativeLayoutVertexNode that needs to expose the native layout Vertex after it has been saved
    /// needs to derive from this NativeLayoutSavedVertexNode class.
    /// 
    /// A nativelayout Vertex should typically only be exposed for Vertex offset fetching purposes, after the native
    /// writer is saved (Vertex offsets get generated when the native writer gets saved).
    /// 
    /// It is important for whoever derives from this class to produce unified Vertices. Calling the WriteVertex method
    /// multiple times should always produce the same exact unified Vertex each time (hence the assert in SetSavedVertex).
    /// All nativewriter.Getxyz methods return unified Vertices.
    /// 
    /// When exposing a saved Vertex that is a result of a section placement operation (Section.Place(...)), always make 
    /// sure a unified Vertex is being placed in the section (Section.Place creates a PlacedVertex structure that wraps the 
    /// Vertex to be placed, so if the Vertex to be placed is unified, there will only be a single unified PlacedVertex 
    /// structure created for that placed Vertex).
    /// </summary>
    public abstract class NativeLayoutSavedVertexNode : NativeLayoutVertexNode
    {
        public Vertex SavedVertex { get; private set; }
        protected Vertex SetSavedVertex(Vertex value)
        {
            Debug.Assert(SavedVertex == null || Object.ReferenceEquals(SavedVertex, value));
            SavedVertex = value;
            return value;
        }
    }

    internal abstract class NativeLayoutMethodEntryVertexNode : NativeLayoutSavedVertexNode
    {
        [Flags]
        public enum MethodEntryFlags
        {
            CreateInstantiatedSignature = 1,
            SaveEntryPoint = 2,
        }

        protected readonly MethodDesc _method;
        private MethodEntryFlags _flags;
        private NativeLayoutTypeSignatureVertexNode _containingTypeSig;
        private NativeLayoutMethodSignatureVertexNode _methodSig;
        private NativeLayoutTypeSignatureVertexNode[] _instantiationArgsSig;

        public NativeLayoutMethodEntryVertexNode(NodeFactory factory, MethodDesc method, MethodEntryFlags flags)
        {
            _method = method;
            _flags = flags;
            _methodSig = factory.NativeLayout.MethodSignatureVertex(method.GetTypicalMethodDefinition().Signature);

            if ((_flags & MethodEntryFlags.CreateInstantiatedSignature) == 0)
            {
                _containingTypeSig = factory.NativeLayout.TypeSignatureVertex(method.OwningType);
                if (method.HasInstantiation && !method.IsMethodDefinition)
                {
                    _instantiationArgsSig = new NativeLayoutTypeSignatureVertexNode[method.Instantiation.Length];
                    for (int i = 0; i < _instantiationArgsSig.Length; i++)
                        _instantiationArgsSig[i] = factory.NativeLayout.TypeSignatureVertex(method.Instantiation[i]);
                }
            }
        }

        public override IEnumerable<DependencyListEntry> GetStaticDependencies(NodeFactory context)
        {
            DependencyList dependencies = new DependencyList();

            dependencies.Add(new DependencyListEntry(_methodSig, "NativeLayoutMethodEntryVertexNode method signature"));
            if ((_flags & MethodEntryFlags.CreateInstantiatedSignature) != 0)
            {
                dependencies.Add(new DependencyListEntry(context.NecessaryTypeSymbol(_method.OwningType), "NativeLayoutMethodEntryVertexNode containing type"));
                foreach (var arg in _method.Instantiation)
                    dependencies.Add(new DependencyListEntry(context.NecessaryTypeSymbol(arg), "NativeLayoutMethodEntryVertexNode instantiation argument type"));
            }
            else
            {
                dependencies.Add(new DependencyListEntry(_containingTypeSig, "NativeLayoutMethodEntryVertexNode containing type signature"));
                if (_method.HasInstantiation && !_method.IsMethodDefinition)
                {
                    foreach (var arg in _instantiationArgsSig)
                        dependencies.Add(new DependencyListEntry(arg, "NativeLayoutMethodEntryVertexNode instantiation argument signature"));
                }
            }

            if ((_flags & MethodEntryFlags.SaveEntryPoint) != 0)
            {
                bool unboxingStub;
                IMethodNode methodEntryPointNode = GetMethodEntrypointNode(context, out unboxingStub);
                dependencies.Add(new DependencyListEntry(methodEntryPointNode, "NativeLayoutMethodEntryVertexNode entrypoint"));
            }

            return dependencies;
        }

        public override Vertex WriteVertex(NodeFactory factory)
        {
            Debug.Assert(Marked, "WriteVertex should only happen for marked vertices");

            Vertex containingType = GetContainingTypeVertex(factory);
            Vertex methodSig = _methodSig.WriteVertex(factory);
            Vertex methodNameAndSig = GetNativeWriter(factory).GetMethodNameAndSigSignature(_method.Name, methodSig);

            Vertex[] args = null;
            MethodFlags flags = 0;
            if (_method.HasInstantiation && !_method.IsMethodDefinition)
            {
                Debug.Assert(_instantiationArgsSig == null || (_instantiationArgsSig != null && _method.Instantiation.Length == _instantiationArgsSig.Length));

                flags |= MethodFlags.HasInstantiation;
                args = new Vertex[_method.Instantiation.Length];

                for (int i = 0; i < args.Length; i++)
                {
                    if ((_flags & MethodEntryFlags.CreateInstantiatedSignature) != 0)
                    {
                        IEETypeNode eetypeNode = factory.NecessaryTypeSymbol(_method.Instantiation[i]);
                        uint typeIndex = factory.MetadataManager.NativeLayoutInfo.ExternalReferences.GetIndex(eetypeNode);
                        args[i] = GetNativeWriter(factory).GetExternalTypeSignature(typeIndex);
                    }
                    else
                    {
                        args[i] = _instantiationArgsSig[i].WriteVertex(factory);
                    }
                }
            }

            uint fptrReferenceId = 0;
            if ((_flags & MethodEntryFlags.SaveEntryPoint) != 0)
            {
                flags |= MethodFlags.HasFunctionPointer;

                bool unboxingStub;
                IMethodNode methodEntryPointNode = GetMethodEntrypointNode(factory, out unboxingStub);
                fptrReferenceId = factory.MetadataManager.NativeLayoutInfo.ExternalReferences.GetIndex(methodEntryPointNode);

                if (unboxingStub)
                    flags |= MethodFlags.IsUnboxingStub;
                if (methodEntryPointNode.Method.IsCanonicalMethod(CanonicalFormKind.Universal))
                    flags |= MethodFlags.FunctionPointerIsUSG;
            }

            return GetNativeWriter(factory).GetMethodSignature((uint)flags, fptrReferenceId, containingType, methodNameAndSig, args);
        }

        private Vertex GetContainingTypeVertex(NodeFactory factory)
        {
            if ((_flags & MethodEntryFlags.CreateInstantiatedSignature) != 0)
            {
                IEETypeNode eetypeNode = factory.NecessaryTypeSymbol(_method.OwningType);
                uint typeIndex = factory.MetadataManager.NativeLayoutInfo.ExternalReferences.GetIndex(eetypeNode);
                return GetNativeWriter(factory).GetExternalTypeSignature(typeIndex);
            }
            else
            {
                return _containingTypeSig.WriteVertex(factory);
            }
        }

        protected virtual IMethodNode GetMethodEntrypointNode(NodeFactory factory, out bool unboxingStub)
        {
            unboxingStub = _method.OwningType.IsValueType && !_method.Signature.IsStatic;
            IMethodNode methodEntryPointNode = factory.MethodEntrypoint(_method, unboxingStub);
            return methodEntryPointNode;
        }
    }

    internal sealed class NativeLayoutMethodLdTokenVertexNode : NativeLayoutMethodEntryVertexNode
    {
        protected override string GetName(NodeFactory factory) => "NativeLayoutMethodLdTokenVertexNode_" + factory.NameMangler.GetMangledMethodName(_method);

        public NativeLayoutMethodLdTokenVertexNode(NodeFactory factory, MethodDesc method)
            : base(factory, method, 0)
        {
        }

        public override Vertex WriteVertex(NodeFactory factory)
        {
            Debug.Assert(Marked, "WriteVertex should only happen for marked vertices");

            Vertex methodEntryVertex = base.WriteVertex(factory);
            return SetSavedVertex(factory.MetadataManager.NativeLayoutInfo.LdTokenInfoSection.Place(methodEntryVertex));
        }
    }

    internal sealed class NativeLayoutFieldLdTokenVertexNode : NativeLayoutSavedVertexNode
    {
        private readonly FieldDesc _field;
        private readonly NativeLayoutTypeSignatureVertexNode _containingTypeSig;

        public NativeLayoutFieldLdTokenVertexNode(NodeFactory factory, FieldDesc field)
        {
            _field = field;
            _containingTypeSig = factory.NativeLayout.TypeSignatureVertex(field.OwningType);
        }

        protected override string GetName(NodeFactory factory) => "NativeLayoutFieldLdTokenVertexNode_" + factory.NameMangler.GetMangledFieldName(_field);

        public override IEnumerable<DependencyListEntry> GetStaticDependencies(NodeFactory context)
        {
            return new DependencyListEntry[]
            {
                new DependencyListEntry(_containingTypeSig, "NativeLayoutFieldLdTokenVertexNode containing type signature"),
            };
        }

        public override Vertex WriteVertex(NodeFactory factory)
        {
            Debug.Assert(Marked, "WriteVertex should only happen for marked vertices");

            Vertex containingType = _containingTypeSig.WriteVertex(factory);

            Vertex unplacedVertex = GetNativeWriter(factory).GetFieldSignature(containingType, _field.Name);

            return SetSavedVertex(factory.MetadataManager.NativeLayoutInfo.LdTokenInfoSection.Place(unplacedVertex));
        }
    }

    internal sealed class NativeLayoutMethodSignatureVertexNode : NativeLayoutVertexNode
    {
        private Internal.TypeSystem.MethodSignature _signature;
        private NativeLayoutTypeSignatureVertexNode _returnTypeSig;
        private NativeLayoutTypeSignatureVertexNode[] _parametersSig;

        protected override string GetName(NodeFactory factory) => "NativeLayoutMethodSignatureVertexNode " + _signature.GetName();

        public NativeLayoutMethodSignatureVertexNode(NodeFactory factory, Internal.TypeSystem.MethodSignature signature)
        {
            _signature = signature;
            _returnTypeSig = factory.NativeLayout.TypeSignatureVertex(signature.ReturnType);
            _parametersSig = new NativeLayoutTypeSignatureVertexNode[signature.Length];
            for (int i = 0; i < _parametersSig.Length; i++)
                _parametersSig[i] = factory.NativeLayout.TypeSignatureVertex(signature[i]);
        }

        public override IEnumerable<DependencyListEntry> GetStaticDependencies(NodeFactory context)
        {
            DependencyList dependencies = new DependencyList();

            dependencies.Add(new DependencyListEntry(_returnTypeSig, "NativeLayoutMethodSignatureVertexNode return type signature"));
            foreach (var arg in _parametersSig)
                dependencies.Add(new DependencyListEntry(arg, "NativeLayoutMethodSignatureVertexNode parameter signature"));

            return dependencies;
        }

        public override Vertex WriteVertex(NodeFactory factory)
        {
            Debug.Assert(Marked, "WriteVertex should only happen for marked vertices");

            MethodCallingConvention methodCallingConvention = default(MethodCallingConvention);

            if (_signature.GenericParameterCount > 0)
                methodCallingConvention |= MethodCallingConvention.Generic;
            if (_signature.IsStatic)
                methodCallingConvention |= MethodCallingConvention.Static;

            Debug.Assert(_signature.Length == _parametersSig.Length);

            Vertex returnType = _returnTypeSig.WriteVertex(factory);
            Vertex[] parameters = new Vertex[_parametersSig.Length];
            for (int i = 0; i < _parametersSig.Length; i++)
                parameters[i] = _parametersSig[i].WriteVertex(factory);

            Vertex signature = GetNativeWriter(factory).GetMethodSigSignature((uint)methodCallingConvention, (uint)_signature.GenericParameterCount, returnType, parameters);
            return factory.MetadataManager.NativeLayoutInfo.SignaturesSection.Place(signature);
        }
    }

    internal sealed class NativeLayoutMethodNameAndSignatureVertexNode : NativeLayoutVertexNode
    {
        private MethodDesc _method;
        private NativeLayoutMethodSignatureVertexNode _methodSig;

        protected override string GetName(NodeFactory factory) => "NativeLayoutMethodNameAndSignatureVertexNode" + factory.NameMangler.GetMangledMethodName(_method);

        public NativeLayoutMethodNameAndSignatureVertexNode(NodeFactory factory, MethodDesc method)
        {
            _method = method;
            _methodSig = factory.NativeLayout.MethodSignatureVertex(method.Signature);
        }
        public override IEnumerable<DependencyListEntry> GetStaticDependencies(NodeFactory context)
        {
            return new DependencyListEntry[] { new DependencyListEntry(_methodSig, "NativeLayoutMethodNameAndSignatureVertexNode signature vertex") };
        }
        public override Vertex WriteVertex(NodeFactory factory)
        {
            Debug.Assert(Marked, "WriteVertex should only happen for marked vertices");

            Vertex methodSig = _methodSig.WriteVertex(factory);
            return GetNativeWriter(factory).GetMethodNameAndSigSignature(_method.Name, methodSig);
        }
    }

    internal abstract class NativeLayoutTypeSignatureVertexNode : NativeLayoutVertexNode
    {
        protected readonly TypeDesc _type;

        protected NativeLayoutTypeSignatureVertexNode(TypeDesc type)
        {
            _type = type;
        }

        protected override string GetName(NodeFactory factory) => "NativeLayoutTypeSignatureVertexNode: " + _type.ToString();

        public static NativeLayoutTypeSignatureVertexNode NewTypeSignatureVertexNode(NodeFactory factory, TypeDesc type)
        {
            switch (type.Category)
            {
                case Internal.TypeSystem.TypeFlags.Array:
                case Internal.TypeSystem.TypeFlags.SzArray:
                case Internal.TypeSystem.TypeFlags.Pointer:
                case Internal.TypeSystem.TypeFlags.ByRef:
                    return new NativeLayoutParameterizedTypeSignatureVertexNode(factory, type);

                case Internal.TypeSystem.TypeFlags.SignatureTypeVariable:
                case Internal.TypeSystem.TypeFlags.SignatureMethodVariable:
                    return new NativeLayoutGenericVarSignatureVertexNode(factory, type);

                // TODO Internal.TypeSystem.TypeFlags.FunctionPointer (Runtime parsing also not yet implemented)
                case Internal.TypeSystem.TypeFlags.FunctionPointer:
                    throw new NotImplementedException("FunctionPointer signature");

                default:
                    {
                        Debug.Assert(type.IsDefType);

                        if (type.HasInstantiation && !type.IsGenericDefinition)
                            return new NativeLayoutInstantiatedTypeSignatureVertexNode(factory, type);
                        else
                            return new NativeLayoutEETypeSignatureVertexNode(factory, type);
                    }
            }
        }

        sealed class NativeLayoutParameterizedTypeSignatureVertexNode : NativeLayoutTypeSignatureVertexNode
        {
            private NativeLayoutVertexNode _parameterTypeSig;

            public NativeLayoutParameterizedTypeSignatureVertexNode(NodeFactory factory, TypeDesc type) : base(type)
            {
                _parameterTypeSig = factory.NativeLayout.TypeSignatureVertex(((ParameterizedType)type).ParameterType);
            }
            public override IEnumerable<DependencyListEntry> GetStaticDependencies(NodeFactory context)
            {
                return new DependencyListEntry[] { new DependencyListEntry(_parameterTypeSig, "NativeLayoutParameterizedTypeSignatureVertexNode parameter type signature") };
            }
            public override Vertex WriteVertex(NodeFactory factory)
            {
                Debug.Assert(Marked, "WriteVertex should only happen for marked vertices");

                switch (_type.Category)
                {
                    case Internal.TypeSystem.TypeFlags.SzArray:
                        return GetNativeWriter(factory).GetModifierTypeSignature(TypeModifierKind.Array, _parameterTypeSig.WriteVertex(factory));

                    case Internal.TypeSystem.TypeFlags.Pointer:
                        return GetNativeWriter(factory).GetModifierTypeSignature(TypeModifierKind.Pointer, _parameterTypeSig.WriteVertex(factory));

                    case Internal.TypeSystem.TypeFlags.ByRef:
                        return GetNativeWriter(factory).GetModifierTypeSignature(TypeModifierKind.ByRef, _parameterTypeSig.WriteVertex(factory));

                    case Internal.TypeSystem.TypeFlags.Array:
                        {
                            Vertex elementType = _parameterTypeSig.WriteVertex(factory);

                            // Skip bounds and lobounds (TODO)
                            var bounds = Array.Empty<uint>();
                            var lobounds = Array.Empty<uint>();

                            return GetNativeWriter(factory).GetMDArrayTypeSignature(elementType, (uint)((ArrayType)_type).Rank, bounds, lobounds);
                        }
                }

                Debug.Fail("UNREACHABLE");
                return null;
            }
        }

        sealed class NativeLayoutGenericVarSignatureVertexNode : NativeLayoutTypeSignatureVertexNode
        {
            public NativeLayoutGenericVarSignatureVertexNode(NodeFactory factory, TypeDesc type) : base(type)
            {
            }
            public override IEnumerable<DependencyListEntry> GetStaticDependencies(NodeFactory context)
            {
                return Array.Empty<DependencyListEntry>();
            }
            public override Vertex WriteVertex(NodeFactory factory)
            {
                Debug.Assert(Marked, "WriteVertex should only happen for marked vertices");

                switch (_type.Category)
                {
                    case Internal.TypeSystem.TypeFlags.SignatureTypeVariable:
                        return GetNativeWriter(factory).GetVariableTypeSignature((uint)((SignatureVariable)_type).Index, false);

                    case Internal.TypeSystem.TypeFlags.SignatureMethodVariable:
                        return GetNativeWriter(factory).GetVariableTypeSignature((uint)((SignatureMethodVariable)_type).Index, true);
                }

                Debug.Fail("UNREACHABLE");
                return null;
            }
        }

        sealed class NativeLayoutInstantiatedTypeSignatureVertexNode : NativeLayoutTypeSignatureVertexNode
        {
            private NativeLayoutTypeSignatureVertexNode _genericTypeDefSig;
            private NativeLayoutTypeSignatureVertexNode[] _instantiationArgs;

            public NativeLayoutInstantiatedTypeSignatureVertexNode(NodeFactory factory, TypeDesc type) : base(type)
            {
                Debug.Assert(type.HasInstantiation && !type.IsGenericDefinition);

                _genericTypeDefSig = factory.NativeLayout.TypeSignatureVertex(type.GetTypeDefinition());
                _instantiationArgs = new NativeLayoutTypeSignatureVertexNode[type.Instantiation.Length];
                for (int i = 0; i < _instantiationArgs.Length; i++)
                    _instantiationArgs[i] = factory.NativeLayout.TypeSignatureVertex(type.Instantiation[i]);

            }
            public override IEnumerable<DependencyListEntry> GetStaticDependencies(NodeFactory context)
            {
                DependencyList dependencies = new DependencyList();

                dependencies.Add(new DependencyListEntry(_genericTypeDefSig, "NativeLayoutInstantiatedTypeSignatureVertexNode generic definition signature"));
                foreach (var arg in _instantiationArgs)
                    dependencies.Add(new DependencyListEntry(arg, "NativeLayoutInstantiatedTypeSignatureVertexNode instantiation argument signature"));

                return dependencies;
            }
            public override Vertex WriteVertex(NodeFactory factory)
            {
                Debug.Assert(Marked, "WriteVertex should only happen for marked vertices");

                Vertex genericDefVertex = _genericTypeDefSig.WriteVertex(factory);
                Vertex[] args = new Vertex[_instantiationArgs.Length];
                for (int i = 0; i < args.Length; i++)
                    args[i] = _instantiationArgs[i].WriteVertex(factory);

                return GetNativeWriter(factory).GetInstantiationTypeSignature(genericDefVertex, args);
            }
        }

        sealed class NativeLayoutEETypeSignatureVertexNode : NativeLayoutTypeSignatureVertexNode
        {
            public NativeLayoutEETypeSignatureVertexNode(NodeFactory factory, TypeDesc type) : base(type)
            {
                Debug.Assert(!type.IsRuntimeDeterminedSubtype);
                Debug.Assert(!type.HasInstantiation || type.IsGenericDefinition);
            }
            public override IEnumerable<DependencyListEntry> GetStaticDependencies(NodeFactory context)
            {
                return new DependencyListEntry[]
                {
                    new DependencyListEntry(context.NecessaryTypeSymbol(_type), "NativeLayoutEETypeVertexNode containing type signature")
                };
            }
            public override Vertex WriteVertex(NodeFactory factory)
            {
                Debug.Assert(Marked, "WriteVertex should only happen for marked vertices");

                IEETypeNode eetypeNode = factory.NecessaryTypeSymbol(_type);
                uint typeIndex = factory.MetadataManager.NativeLayoutInfo.ExternalReferences.GetIndex(eetypeNode);
                return GetNativeWriter(factory).GetExternalTypeSignature(typeIndex);
            }
        }
    }

    public sealed class NativeLayoutExternalReferenceVertexNode : NativeLayoutVertexNode
    {
        private ISymbolNode _symbol;

        public NativeLayoutExternalReferenceVertexNode(NodeFactory factory, ISymbolNode symbol)
        {
            _symbol = symbol;
        }

        protected override string GetName(NodeFactory factory) => "NativeLayoutISymbolNodeReferenceVertexNode " + _symbol.GetMangledName(factory.NameMangler);

        public override IEnumerable<DependencyListEntry> GetStaticDependencies(NodeFactory context)
        {
            return new DependencyListEntry[]
            {
                new DependencyListEntry(_symbol, "NativeLayoutISymbolNodeReferenceVertexNode containing symbol")
            };
        }

        public override Vertex WriteVertex(NodeFactory factory)
        {
            Debug.Assert(Marked, "WriteVertex should only happen for marked vertices");

            uint symbolIndex = factory.MetadataManager.NativeLayoutInfo.ExternalReferences.GetIndex(_symbol);
            return GetNativeWriter(factory).GetUnsignedConstant(symbolIndex);
        }
    }

    internal sealed class NativeLayoutPlacedSignatureVertexNode : NativeLayoutSavedVertexNode
    {
        private NativeLayoutVertexNode _signatureToBePlaced;

        protected override string GetName(NodeFactory factory) => "NativeLayoutPlacedSignatureVertexNode";

        public NativeLayoutPlacedSignatureVertexNode(NativeLayoutVertexNode signatureToBePlaced)
        {
            _signatureToBePlaced = signatureToBePlaced;
        }
        public override IEnumerable<DependencyListEntry> GetStaticDependencies(NodeFactory context)
        {
            return new DependencyListEntry[] { new DependencyListEntry(_signatureToBePlaced, "NativeLayoutPlacedSignatureVertexNode placed signature") };
        }
        public override Vertex WriteVertex(NodeFactory factory)
        {
            // This vertex doesn't need to assert as marked, as it simply represents the concept of an existing vertex which has been placed.

            // Always use the NativeLayoutInfo blob for names and sigs, even if the associated types/methods are written elsewhere.
            // This saves space, since we can Unify more signatures, allows optimizations in comparing sigs in the same module, and 
            // prevents the dynamic type loader having to know about other native layout sections (since sigs contain types). If we are 
            // using a non-native layout info writer, write the sig to the native layout info, and refer to it by offset in its own 
            // section.  At runtime, we will assume all names and sigs are in the native layout and find it.

            Vertex signature = _signatureToBePlaced.WriteVertex(factory);
            return SetSavedVertex(factory.MetadataManager.NativeLayoutInfo.SignaturesSection.Place(signature));
        }
    }

    internal sealed class NativeLayoutPlacedVertexSequenceOfUIntVertexNode : NativeLayoutSavedVertexNode
    {
        private List<uint> _uints;

        protected override string GetName(NodeFactory factory) => "NativeLayoutPlacedVertexSequenceVertexNode";
        public NativeLayoutPlacedVertexSequenceOfUIntVertexNode(List<uint> uints)
        {
            _uints = uints;
        }

        public override IEnumerable<DependencyListEntry> GetStaticDependencies(NodeFactory context)
        {
            // There are no interesting dependencies
            return null;
        }

        public override Vertex WriteVertex(NodeFactory factory)
        {
            // Eagerly return the SavedVertex so that we can unify the VertexSequence
            if (SavedVertex != null)
                return SavedVertex;

            // This vertex doesn't need to assert as marked, as it simply represents the concept of an existing vertex which has been placed.

            NativeWriter writer = GetNativeWriter(factory);

            VertexSequence sequence = new VertexSequence();
            foreach (uint value in _uints)
            {
                sequence.Append(writer.GetUnsignedConstant(value));
            }

            return SetSavedVertex(factory.MetadataManager.NativeLayoutInfo.SignaturesSection.Place(sequence));
        }
    }

    internal sealed class NativeLayoutPlacedVertexSequenceVertexNode : NativeLayoutSavedVertexNode
    {
        private List<NativeLayoutVertexNode> _vertices;

        protected override string GetName(NodeFactory factory) => "NativeLayoutPlacedVertexSequenceVertexNode";
        public NativeLayoutPlacedVertexSequenceVertexNode(List<NativeLayoutVertexNode> vertices)
        {
            _vertices = vertices;
        }

        public override IEnumerable<DependencyListEntry> GetStaticDependencies(NodeFactory context)
        {
            DependencyListEntry[] dependencies = new DependencyListEntry[_vertices.Count];
            for (int i = 0; i < _vertices.Count; i++)
            {
                dependencies[i] = new DependencyListEntry(_vertices[i], "NativeLayoutPlacedVertexSequenceVertexNode element");
            }

            return dependencies;
        }

        public override Vertex WriteVertex(NodeFactory factory)
        {
            // Eagerly return the SavedVertex so that we can unify the VertexSequence
            if (SavedVertex != null)
                return SavedVertex;

            // This vertex doesn't need to assert as marked, as it simply represents the concept of an existing vertex which has been placed.

            VertexSequence sequence = new VertexSequence();
            foreach (NativeLayoutVertexNode vertex in _vertices)
            {
                sequence.Append(vertex.WriteVertex(factory));
            }

            return SetSavedVertex(factory.MetadataManager.NativeLayoutInfo.SignaturesSection.Place(sequence));
        }
    }

    internal sealed class NativeLayoutTemplateMethodSignatureVertexNode : NativeLayoutMethodEntryVertexNode
    {
        protected override string GetName(NodeFactory factory) => "NativeLayoutTemplateMethodSignatureVertexNode_" + factory.NameMangler.GetMangledMethodName(_method);

        public NativeLayoutTemplateMethodSignatureVertexNode(NodeFactory factory, MethodDesc method)
            : base(factory, method, MethodEntryFlags.CreateInstantiatedSignature | (method.IsVirtual ? MethodEntryFlags.SaveEntryPoint : 0))
        {
        }

        public override Vertex WriteVertex(NodeFactory factory)
        {
            Debug.Assert(Marked, "WriteVertex should only happen for marked vertices");

            Vertex methodEntryVertex = base.WriteVertex(factory);
            return SetSavedVertex(factory.MetadataManager.NativeLayoutInfo.TemplatesSection.Place(methodEntryVertex));
        }

        protected override IMethodNode GetMethodEntrypointNode(NodeFactory factory, out bool unboxingStub)
        {
            // Only GVM templates need entry points.
            Debug.Assert(_method.IsVirtual);
            unboxingStub = _method.OwningType.IsValueType;
            IMethodNode methodEntryPointNode = factory.MethodEntrypoint(_method, unboxingStub);
            // Note: We don't set the IsUnboxingStub flag on template methods (all template lookups performed at runtime are performed with this flag not set,
            // since it can't always be conveniently computed for a concrete method before looking up its template)
            unboxingStub = false;
            return methodEntryPointNode;
        }

        public override IEnumerable<DependencyListEntry> GetStaticDependencies(NodeFactory context)
        {
            DependencyList dependencies = (DependencyList)base.GetStaticDependencies(context);

            foreach (var arg in _method.Instantiation)
            {
                foreach (var dependency in context.NativeLayout.TemplateConstructableTypes(arg))
                {
                    dependencies.Add(new DependencyListEntry(dependency, "Dependencies to make a generic method template viable Method Instantiation"));
                }
            }


            foreach (var dependency in context.NativeLayout.TemplateConstructableTypes(_method.OwningType))
            {
                dependencies.Add(new DependencyListEntry(dependency, "Dependencies to make a generic method template viable OwningType"));
            }

            return dependencies;
        }
    }

    public sealed class NativeLayoutDictionarySignatureNode : NativeLayoutSavedVertexNode
    {
        private TypeSystemEntity _owningMethodOrType;
        public NativeLayoutDictionarySignatureNode(NodeFactory nodeFactory, TypeSystemEntity owningMethodOrType)
        {
            if (owningMethodOrType is MethodDesc)
            {
                MethodDesc owningMethod = (MethodDesc)owningMethodOrType;
                Debug.Assert(owningMethod.IsCanonicalMethod(CanonicalFormKind.Universal) || nodeFactory.LazyGenericsPolicy.UsesLazyGenerics(owningMethod));
                Debug.Assert(owningMethod.IsCanonicalMethod(CanonicalFormKind.Any));
                Debug.Assert(owningMethod.HasInstantiation);
            }
            else
            {
                TypeDesc owningType = (TypeDesc)owningMethodOrType;
                Debug.Assert(owningType.IsCanonicalSubtype(CanonicalFormKind.Universal) || nodeFactory.LazyGenericsPolicy.UsesLazyGenerics(owningType));
                Debug.Assert(owningType.IsCanonicalSubtype(CanonicalFormKind.Any));
            }

            _owningMethodOrType = owningMethodOrType;
        }

        private GenericContextKind ContextKind(NodeFactory factory)
        {
            if (_owningMethodOrType is MethodDesc)
            {
                MethodDesc owningMethod = (MethodDesc)_owningMethodOrType;
                Debug.Assert(owningMethod.HasInstantiation);
                return GenericContextKind.FromMethodHiddenArg | GenericContextKind.NeedsUSGContext;
            }
            else
            {
                TypeDesc owningType = (TypeDesc)_owningMethodOrType;
                if (owningType.IsSzArray || owningType.HasSameTypeDefinition(factory.ArrayOfTClass) || owningType.IsValueType || owningType.IsSealed())
                {
                    return GenericContextKind.FromHiddenArg | GenericContextKind.NeedsUSGContext;
                }
                else
                {
                    return GenericContextKind.FromHiddenArg | GenericContextKind.NeedsUSGContext | GenericContextKind.HasDeclaringType;
                }
            }
        }

        public override IEnumerable<DependencyListEntry> GetStaticDependencies(NodeFactory context)
        {
            if ((ContextKind(context) & GenericContextKind.HasDeclaringType) != 0)
            {
                return new DependencyListEntry[] 
                {
                    new DependencyListEntry(context.NativeLayout.TypeSignatureVertex((TypeDesc)_owningMethodOrType), "DeclaringType signature"),
                    new DependencyListEntry(context.GenericDictionaryLayout(_owningMethodOrType), "Dictionary Layout")
                };
            }
            else
            {
                return new DependencyListEntry[]
                {
                    new DependencyListEntry(context.GenericDictionaryLayout(_owningMethodOrType), "Dictionary Layout")
                };
            }
        }

        public override Vertex WriteVertex(NodeFactory factory)
        {
            Debug.Assert(Marked, "WriteVertex should only happen for marked vertices");

            VertexSequence sequence = new VertexSequence();

            DictionaryLayoutNode associatedLayout = factory.GenericDictionaryLayout(_owningMethodOrType);
            Debug.Assert(associatedLayout.Marked);
            ICollection<NativeLayoutVertexNode> templateLayout = associatedLayout.GetTemplateEntries(factory);

            foreach (NativeLayoutVertexNode dictionaryEntry in templateLayout)
            {
                dictionaryEntry.CheckIfMarkedEnoughToWrite();
                sequence.Append(dictionaryEntry.WriteVertex(factory));
            }

            Vertex signature;

            GenericContextKind contextKind = ContextKind(factory);
            NativeWriter nativeWriter = GetNativeWriter(factory);

            if ((contextKind & GenericContextKind.HasDeclaringType) != 0)
            {
                signature = nativeWriter.GetTuple(factory.NativeLayout.TypeSignatureVertex((TypeDesc)_owningMethodOrType).WriteVertex(factory), sequence);
            }
            else
            {
                signature = sequence;
            }

            Vertex signatureWithContextKind = nativeWriter.GetTuple(nativeWriter.GetUnsignedConstant((uint)contextKind), signature);
            return SetSavedVertex(factory.MetadataManager.NativeLayoutInfo.SignaturesSection.Place(signatureWithContextKind));
        }

        protected override string GetName(NodeFactory factory) => $"Dictionary layout signature for {_owningMethodOrType.ToString()}";
    }

    public sealed class NativeLayoutTemplateMethodLayoutVertexNode : NativeLayoutSavedVertexNode
    {
        private MethodDesc _method;

        protected override string GetName(NodeFactory factory) => "NativeLayoutTemplateMethodLayoutVertexNode" + factory.NameMangler.GetMangledMethodName(_method);

        public NativeLayoutTemplateMethodLayoutVertexNode(NodeFactory factory, MethodDesc method)
        {
            _method = method;
            Debug.Assert(method.HasInstantiation);
            Debug.Assert(method.IsCanonicalMethod(CanonicalFormKind.Any));
            Debug.Assert(method.GetCanonMethodTarget(CanonicalFormKind.Specific) == method, "Assert that the canonical method passed in is in standard canonical form");
        }

        public override IEnumerable<DependencyListEntry> GetStaticDependencies(NodeFactory context)
        {
            foreach (var dependency in context.NativeLayout.TemplateConstructableTypes(_method.OwningType))
            {
                yield return new DependencyListEntry(dependency, "method OwningType itself must be template loadable");
            }

            foreach (var type in _method.Instantiation)
            {
                foreach (var dependency in context.NativeLayout.TemplateConstructableTypes(type))
                {
                    yield return new DependencyListEntry(dependency, "method's instantiation arguments must be template loadable");
                }
            }

            yield return new DependencyListEntry(context.GenericDictionaryLayout(_method), "Dictionary layout");
        }

        private int CompareDictionaryEntries(KeyValuePair<int, NativeLayoutVertexNode> left, KeyValuePair<int, NativeLayoutVertexNode> right)
        {
            return left.Key - right.Key;
        }

        public override Vertex WriteVertex(NodeFactory factory)
        {
            Debug.Assert(Marked, "WriteVertex should only happen for marked vertices");

            VertexBag layoutInfo = new VertexBag();

            DictionaryLayoutNode associatedLayout = factory.GenericDictionaryLayout(_method);
            ICollection<NativeLayoutVertexNode> templateLayout = associatedLayout.GetTemplateEntries(factory);
            
            if (!(_method.IsCanonicalMethod(CanonicalFormKind.Universal) || (factory.LazyGenericsPolicy.UsesLazyGenerics(_method))) && (templateLayout.Count > 0))
            {
                List<NativeLayoutVertexNode> dictionaryVertices = new List<NativeLayoutVertexNode>();

                foreach (NativeLayoutVertexNode dictionaryEntry in templateLayout)
                {
                    dictionaryEntry.CheckIfMarkedEnoughToWrite();
                    dictionaryVertices.Add(dictionaryEntry);
                }
                NativeLayoutVertexNode dictionaryLayout = factory.NativeLayout.PlacedVertexSequence(dictionaryVertices);

                layoutInfo.Append(BagElementKind.DictionaryLayout, dictionaryLayout.WriteVertex(factory));
            }

            factory.MetadataManager.NativeLayoutInfo.TemplatesSection.Place(layoutInfo);

            return SetSavedVertex(layoutInfo);
        }
    }

    public sealed class NativeLayoutTemplateTypeLayoutVertexNode : NativeLayoutSavedVertexNode
    {
        private TypeDesc _type;
        private bool _isUniversalCanon;

        protected override string GetName(NodeFactory factory) => "NativeLayoutTemplateTypeLayoutVertexNode_" + factory.NameMangler.GetMangledTypeName(_type);

        public NativeLayoutTemplateTypeLayoutVertexNode(NodeFactory factory, TypeDesc type)
        {
            Debug.Assert(type.IsCanonicalSubtype(CanonicalFormKind.Any));
            Debug.Assert(type.ConvertToCanonForm(CanonicalFormKind.Specific) == type, "Assert that the canonical type passed in is in standard canonical form");
            _isUniversalCanon = type.IsCanonicalSubtype(CanonicalFormKind.Universal);

            _type = GetActualTemplateTypeForType(factory, type);
        }

        private static TypeDesc GetActualTemplateTypeForType(NodeFactory factory, TypeDesc type)
        {
            DefType defType = type as DefType;
            if (defType == null)
            {
                Debug.Assert(GenericTypesTemplateMap.IsArrayTypeEligibleForTemplate(type));
                defType = type.GetClosestDefType().ConvertToSharedRuntimeDeterminedForm();
                Debug.Assert(defType.Instantiation.Length == 1);
                return factory.TypeSystemContext.GetArrayType(defType.Instantiation[0]);
            }
            else
            {
                return defType.ConvertToSharedRuntimeDeterminedForm();
            }
        }

        private ISymbolNode GetStaticsNode(NodeFactory context, out BagElementKind staticsBagKind)
        {
            ISymbolNode symbol;

            if (context is UtcNodeFactory)
            {
                symbol = ((UtcNodeFactory)context).TypeGCStaticDescSymbol((MetadataType)_type.GetClosestDefType().ConvertToCanonForm(CanonicalFormKind.Specific));
                staticsBagKind = BagElementKind.GcStaticDesc;
            }
            else
            {
                symbol = context.GCStaticEEType(GCPointerMap.FromStaticLayout(_type.GetClosestDefType()));
                staticsBagKind = BagElementKind.GcStaticEEType;
            }

            return symbol;
        }

        private ISymbolNode GetThreadStaticsNode(NodeFactory context, out BagElementKind staticsBagKind)
        {
            ISymbolNode symbol;

            if (context is UtcNodeFactory)
            {
                symbol = ((UtcNodeFactory)context).TypeThreadStaticGCDescNode((MetadataType)_type.GetClosestDefType().ConvertToCanonForm(CanonicalFormKind.Specific));
                staticsBagKind = BagElementKind.ThreadStaticDesc;
            }
            else
            {
                symbol = context.GCStaticEEType(GCPointerMap.FromThreadStaticLayout(_type.GetClosestDefType()));
                staticsBagKind = BagElementKind.End; // GC static EETypes not yet implemented in type loader
            }

            return symbol;
        }

        public override IEnumerable<DependencyListEntry> GetStaticDependencies(NodeFactory context)
        {
            ISymbolNode typeNode = context.MaximallyConstructableType(_type.ConvertToCanonForm(CanonicalFormKind.Specific));

            yield return new DependencyListEntry(typeNode, "Template EEType");

            foreach (var dependency in context.NativeLayout.TemplateConstructableTypes(_type))
            {
                yield return new DependencyListEntry(dependency, "type itslef must be template loadable");
            }

            yield return new DependencyListEntry(context.GenericDictionaryLayout(_type.ConvertToCanonForm(CanonicalFormKind.Specific).GetClosestDefType()), "Dictionary layout");

            foreach (TypeDesc iface in _type.RuntimeInterfaces)
            {
                yield return new DependencyListEntry(context.NativeLayout.TypeSignatureVertex(iface), "template interface list");

                foreach (var dependency in context.NativeLayout.TemplateConstructableTypes(iface))
                {
                    yield return new DependencyListEntry(dependency, "interface type dependency must be template loadable");
                }
            }

            if (context.TypeSystemContext.HasLazyStaticConstructor(_type))
            {
                yield return new DependencyListEntry(context.MethodEntrypoint(_type.GetStaticConstructor().GetCanonMethodTarget(CanonicalFormKind.Specific)), "cctor for template");
            }

            if (!_isUniversalCanon)
            {
                if (_type.GetClosestDefType().GCStaticFieldSize.AsInt > 0)
                {
                    BagElementKind ignored;
                    yield return new DependencyListEntry(GetStaticsNode(context, out ignored), "type gc static info");
                }

                if (_type.GetClosestDefType().ThreadGcStaticFieldSize.AsInt > 0)
                {
                    BagElementKind ignored;
                    yield return new DependencyListEntry(GetThreadStaticsNode(context, out ignored), "type thread static info");
                }
            }

            if (_type.BaseType != null && !_type.BaseType.IsRuntimeDeterminedSubtype)
            {
                TypeDesc baseType = _type.BaseType;
                do
                {
                    yield return new DependencyListEntry(context.MaximallyConstructableType(baseType), "base types of canonical types must have their full vtables");
                    baseType = baseType.BaseType;
                } while (baseType != null);
            }

            if (_type.BaseType != null && _type.BaseType.IsRuntimeDeterminedSubtype)
            {
                yield return new DependencyListEntry(context.NativeLayout.PlacedSignatureVertex(context.NativeLayout.TypeSignatureVertex(_type.BaseType)), "template base type");

                foreach (var dependency in context.NativeLayout.TemplateConstructableTypes(_type.BaseType))
                {
                    yield return new DependencyListEntry(dependency, "base type must be template loadable");
                }
            }
            else if (_type.IsDelegate && _isUniversalCanon)
            {
                // For USG delegate, we need to write the signature of the Invoke method to the native layout.
                // This signature is used by the calling convention converter to marshal parameters during delegate calls.
                yield return new DependencyListEntry(context.NativeLayout.MethodSignatureVertex(_type.GetMethod("Invoke", null).GetTypicalMethodDefinition().Signature), "invoke method signature");
            }

            if (_isUniversalCanon)
            {
                // For universal canonical template types, we need to write out field layout information so that we 
                // can correctly compute the type sizes for dynamically created types at runtime, and construct
                // their GCDesc info
                foreach (FieldDesc field in _type.GetFields())
                {
                    // If this field does not contribute to layout, skip
                    if (field.HasRva || field.IsLiteral)
                    {
                        continue;
                    }

                    DependencyListEntry typeForFieldLayout;

                    if (field.FieldType.IsGCPointer)
                    {
                        typeForFieldLayout = new DependencyListEntry(context.NativeLayout.PlacedSignatureVertex(context.NativeLayout.TypeSignatureVertex(field.Context.GetWellKnownType(WellKnownType.Object))), "universal field layout type object sized");
                    }
                    else if (field.FieldType.IsPointer || field.FieldType.IsFunctionPointer)
                    {
                        typeForFieldLayout = new DependencyListEntry(context.NativeLayout.PlacedSignatureVertex(context.NativeLayout.TypeSignatureVertex(field.Context.GetWellKnownType(WellKnownType.IntPtr))), "universal field layout type IntPtr sized");
                    }
                    else
                    {
                        typeForFieldLayout = new DependencyListEntry(context.NativeLayout.PlacedSignatureVertex(context.NativeLayout.TypeSignatureVertex(field.FieldType)), "universal field layout type");

                        // And ensure the type can be properly laid out
                        foreach (var dependency in context.NativeLayout.TemplateConstructableTypes(field.FieldType))
                        {
                            yield return new DependencyListEntry(dependency, "template construction dependency");
                        }
                    }

                    yield return typeForFieldLayout;
                }

                // We also need to write out the signatures of interesting methods in the type's vtable, which
                // will be needed by the calling convention translation logic at runtime, when the type's methods
                // get invoked. This logic gathers nodes for entries *unconditionally* present. (entries may be conditionally
                // present if a type has a vtable which has a size computed by usage not by IL contents)
                List<NativeLayoutVertexNode> vtableSignatureNodeEntries = null;
                int currentVTableIndexUnused = 0;
                ProcessVTableEntriesForCallingConventionSignatureGeneration(context, VTableEntriesToProcess.AllOnTypesThatShouldProduceFullVTables, ref currentVTableIndexUnused,
                    (int vtableIndex, bool isSealedVTableSlot, MethodDesc declMethod, MethodDesc implMethod) =>
                    {
                        if (implMethod.IsAbstract)
                            return;

                        if (UniversalGenericParameterLayout.VTableMethodRequiresCallingConventionConverter(implMethod))
                        {
                            if (vtableSignatureNodeEntries == null)
                                vtableSignatureNodeEntries = new List<NativeLayoutVertexNode>();

                            vtableSignatureNodeEntries.Add(context.NativeLayout.MethodSignatureVertex(declMethod.GetTypicalMethodDefinition().Signature));
                        }
                    }
                    , _type, _type, _type);

                if (vtableSignatureNodeEntries != null)
                {
                    foreach (NativeLayoutVertexNode node in vtableSignatureNodeEntries)
                        yield return new DependencyListEntry(node, "vtable cctor sig");
                }
            }
        }

        public override bool HasConditionalStaticDependencies => _isUniversalCanon;
        public override IEnumerable<CombinedDependencyListEntry> GetConditionalStaticDependencies(NodeFactory context)
        {
            List<CombinedDependencyListEntry> conditionalDependencies = null;

            if (_isUniversalCanon)
            {
                // We also need to write out the signatures of interesting methods in the type's vtable, which
                // will be needed by the calling convention translation logic at runtime, when the type's methods
                // get invoked. This logic gathers nodes for entries *conditionally* present. (entries may be conditionally
                // present if a type has a vtable which has a size computed by usage not by IL contents)

                int currentVTableIndexUnused = 0;
                ProcessVTableEntriesForCallingConventionSignatureGeneration(context, VTableEntriesToProcess.AllOnTypesThatProducePartialVTables, ref currentVTableIndexUnused,
                    (int vtableIndex, bool isSealedVTableSlot, MethodDesc declMethod, MethodDesc implMethod) =>
                    {
                        if (implMethod.IsAbstract)
                            return;

                        if (UniversalGenericParameterLayout.VTableMethodRequiresCallingConventionConverter(implMethod))
                        {
                            if (conditionalDependencies == null)
                                conditionalDependencies = new List<CombinedDependencyListEntry>();

                            conditionalDependencies.Add(
                                new CombinedDependencyListEntry(context.NativeLayout.MethodSignatureVertex(declMethod.GetTypicalMethodDefinition().Signature),
                                                                context.VirtualMethodUse(declMethod),
                                                                "conditional vtable cctor sig"));
                        }
                    }
                    , _type, _type, _type);
            }

            if (conditionalDependencies != null)
                return conditionalDependencies;
            else
                return Array.Empty<CombinedDependencyListEntry>();
        }

        private int CompareDictionaryEntries(KeyValuePair<int, NativeLayoutVertexNode> left, KeyValuePair<int, NativeLayoutVertexNode> right)
        {
            return left.Key - right.Key;
        }

        private bool HasInstantiationDeterminedSize()
        {
            Debug.Assert(_isUniversalCanon);
            return _type.GetClosestDefType().InstanceFieldSize.IsIndeterminate;
        }

        public override Vertex WriteVertex(NodeFactory factory)
        {
            Debug.Assert(Marked, "WriteVertex should only happen for marked vertices");

            VertexBag layoutInfo = new VertexBag();

            DictionaryLayoutNode associatedLayout = factory.GenericDictionaryLayout(_type.ConvertToCanonForm(CanonicalFormKind.Specific).GetClosestDefType());
            ICollection<NativeLayoutVertexNode> templateLayout = associatedLayout.GetTemplateEntries(factory);
            
            NativeWriter writer = GetNativeWriter(factory);

            // Interfaces
            if (_type.RuntimeInterfaces.Length > 0)
            {
                List<NativeLayoutVertexNode> implementedInterfacesList = new List<NativeLayoutVertexNode>();

                foreach (TypeDesc iface in _type.RuntimeInterfaces)
                {
                    implementedInterfacesList.Add(factory.NativeLayout.TypeSignatureVertex(iface));
                }
                NativeLayoutVertexNode implementedInterfaces = factory.NativeLayout.PlacedVertexSequence(implementedInterfacesList);

                layoutInfo.Append(BagElementKind.ImplementedInterfaces, implementedInterfaces.WriteVertex(factory));
            }

            if (!(_isUniversalCanon || (factory.LazyGenericsPolicy.UsesLazyGenerics(_type)) )&& (templateLayout.Count > 0))
            {
                List<NativeLayoutVertexNode> dictionaryVertices = new List<NativeLayoutVertexNode>();

                foreach (NativeLayoutVertexNode dictionaryEntry in templateLayout)
                {
                    dictionaryEntry.CheckIfMarkedEnoughToWrite();
                    dictionaryVertices.Add(dictionaryEntry);
                }
                NativeLayoutVertexNode dictionaryLayout = factory.NativeLayout.PlacedVertexSequence(dictionaryVertices);

                layoutInfo.Append(BagElementKind.DictionaryLayout, dictionaryLayout.WriteVertex(factory));
            }

            Internal.NativeFormat.TypeFlags typeFlags = default(Internal.NativeFormat.TypeFlags);

            if (factory.TypeSystemContext.HasLazyStaticConstructor(_type))
            {
                MethodDesc cctorMethod = _type.GetStaticConstructor();
                MethodDesc canonCctorMethod = cctorMethod.GetCanonMethodTarget(CanonicalFormKind.Specific);
                ISymbolNode cctorSymbol = factory.MethodEntrypoint(canonCctorMethod);
                uint cctorStaticsIndex = factory.MetadataManager.NativeLayoutInfo.StaticsReferences.GetIndex(cctorSymbol);
                layoutInfo.AppendUnsigned(BagElementKind.ClassConstructorPointer, cctorStaticsIndex);

                typeFlags = typeFlags | Internal.NativeFormat.TypeFlags.HasClassConstructor;
            }

            if (!_isUniversalCanon)
            {
                DefType closestDefType = _type.GetClosestDefType();
                if (closestDefType.NonGCStaticFieldSize.AsInt != 0)
                {
                    layoutInfo.AppendUnsigned(BagElementKind.NonGcStaticDataSize, checked((uint)closestDefType.NonGCStaticFieldSize.AsInt));
                }

                if (closestDefType.GCStaticFieldSize.AsInt != 0)
                {
                    layoutInfo.AppendUnsigned(BagElementKind.GcStaticDataSize, checked((uint)closestDefType.GCStaticFieldSize.AsInt));
                    BagElementKind staticDescBagType;
                    ISymbolNode staticsDescSymbol = GetStaticsNode(factory, out staticDescBagType);
                    uint gcStaticsSymbolIndex = factory.MetadataManager.NativeLayoutInfo.StaticsReferences.GetIndex(staticsDescSymbol);
                    layoutInfo.AppendUnsigned(staticDescBagType, gcStaticsSymbolIndex);
                }

                if (closestDefType.ThreadGcStaticFieldSize.AsInt != 0)
                {
                    layoutInfo.AppendUnsigned(BagElementKind.ThreadStaticDataSize, checked((uint)closestDefType.ThreadGcStaticFieldSize.AsInt));
                    BagElementKind threadStaticDescBagType;
                    ISymbolNode threadStaticsDescSymbol = GetThreadStaticsNode(factory, out threadStaticDescBagType);
                    uint threadStaticsSymbolIndex = factory.MetadataManager.NativeLayoutInfo.StaticsReferences.GetIndex(threadStaticsDescSymbol);
                    layoutInfo.AppendUnsigned(threadStaticDescBagType, threadStaticsSymbolIndex);
                }
            }
            else
            {
                Debug.Assert(_isUniversalCanon);
                // Determine if type has instantiation determined size
                if (!_type.IsInterface && HasInstantiationDeterminedSize())
                {
                    typeFlags = typeFlags | Internal.NativeFormat.TypeFlags.HasInstantiationDeterminedSize;
                }
            }

            if (_type.BaseType != null && _type.BaseType.IsRuntimeDeterminedSubtype)
            {
                layoutInfo.Append(BagElementKind.BaseType, factory.NativeLayout.PlacedSignatureVertex(factory.NativeLayout.TypeSignatureVertex(_type.BaseType)).WriteVertex(factory));
            }
            else if (_type.IsDelegate && _isUniversalCanon)
            {
                // For USG delegate, we need to write the signature of the Invoke method to the native layout.
                // This signature is used by the calling convention converter to marshal parameters during delegate calls.
                MethodDesc delegateInvokeMethod = _type.GetMethod("Invoke", null).GetTypicalMethodDefinition();
                NativeLayoutMethodSignatureVertexNode invokeSignatureVertexNode = factory.NativeLayout.MethodSignatureVertex(delegateInvokeMethod.Signature);
                layoutInfo.Append(BagElementKind.DelegateInvokeSignature, invokeSignatureVertexNode.WriteVertex(factory));
            }

            if (typeFlags != default(Internal.NativeFormat.TypeFlags))
                layoutInfo.AppendUnsigned(BagElementKind.TypeFlags, (uint)typeFlags);

            if (!_type.IsArrayTypeWithoutGenericInterfaces() && ConstructedEETypeNode.CreationAllowed(_type))
            {
                SealedVTableNode sealedVTable = factory.SealedVTable(_type.ConvertToCanonForm(CanonicalFormKind.Specific));

                sealedVTable.BuildSealedVTableSlots(factory, relocsOnly: false /* This is the final emission phase */);

                if (sealedVTable.NumSealedVTableEntries > 0)
                    layoutInfo.AppendUnsigned(BagElementKind.SealedVTableEntries, (uint)sealedVTable.NumSealedVTableEntries);
            }

            if (_type.GetTypeDefinition().HasVariance || factory.TypeSystemContext.IsGenericArrayInterfaceType(_type))
            {
                // Runtime casting logic relies on all interface types implemented on arrays
                // to have the variant flag set (even if all the arguments are non-variant).
                // This supports e.g. casting uint[] to ICollection<int>
                List<uint> varianceFlags = new List<uint>();
                foreach (GenericParameterDesc param in _type.GetTypeDefinition().Instantiation)
                {
                    varianceFlags.Add((uint)param.Variance);
                }

                layoutInfo.Append(BagElementKind.GenericVarianceInfo, factory.NativeLayout.PlacedUIntVertexSequence(varianceFlags).WriteVertex(factory));
            }
            else if (_type.GetTypeDefinition() == factory.ArrayOfTEnumeratorType)
            {
                // Generic array enumerators use special variance rules recognized by the runtime
                List<uint> varianceFlag = new List<uint>();
                varianceFlag.Add((uint)Internal.Runtime.GenericVariance.ArrayCovariant);
                layoutInfo.Append(BagElementKind.GenericVarianceInfo, factory.NativeLayout.PlacedUIntVertexSequence(varianceFlag).WriteVertex(factory));
            }

            if (_isUniversalCanon)
            {
                // For universal canonical template types, we need to write out field layout information so that we 
                // can correctly compute the type sizes for dynamically created types at runtime, and construct
                // their GCDesc info
                VertexSequence fieldsSequence = null;

                foreach (FieldDesc field in _type.GetFields())
                {
                    // If this field does contribute to layout, skip
                    if (field.HasRva || field.IsLiteral)
                        continue;

                    // NOTE: The order and contents of the signature vertices emitted here is what we consider a field ordinal for the
                    // purpose of NativeLayoutFieldOffsetGenericDictionarySlotNode. 

                    FieldStorage fieldStorage = FieldStorage.Instance;
                    if (field.IsStatic)
                    {
                        if (field.IsThreadStatic)
                            fieldStorage = FieldStorage.TLSStatic;
                        else if (field.HasGCStaticBase)
                            fieldStorage = FieldStorage.GCStatic;
                        else
                            fieldStorage = FieldStorage.NonGCStatic;
                    }


                    NativeLayoutVertexNode fieldTypeSignature;
                    if (field.FieldType.IsGCPointer)
                    {
                        fieldTypeSignature = factory.NativeLayout.PlacedSignatureVertex(factory.NativeLayout.TypeSignatureVertex(field.Context.GetWellKnownType(WellKnownType.Object)));
                    }
                    else if (field.FieldType.IsPointer || field.FieldType.IsFunctionPointer)
                    {
                        fieldTypeSignature = factory.NativeLayout.PlacedSignatureVertex(factory.NativeLayout.TypeSignatureVertex(field.Context.GetWellKnownType(WellKnownType.IntPtr)));
                    }
                    else
                    {
                        fieldTypeSignature = factory.NativeLayout.PlacedSignatureVertex(factory.NativeLayout.TypeSignatureVertex(field.FieldType));
                    }

                    Vertex staticFieldVertexData = writer.GetTuple(fieldTypeSignature.WriteVertex(factory), writer.GetUnsignedConstant((uint)fieldStorage));

                    if (fieldsSequence == null)
                        fieldsSequence = new VertexSequence();
                    fieldsSequence.Append(staticFieldVertexData);
                }

                if (fieldsSequence != null)
                {
                    Vertex placedFieldsLayout = factory.MetadataManager.NativeLayoutInfo.SignaturesSection.Place(fieldsSequence);
                    layoutInfo.Append(BagElementKind.FieldLayout, placedFieldsLayout);
                }

                // We also need to write out the signatures of interesting methods in the type's vtable, which
                // will be needed by the calling convention translation logic at runtime, when the type's methods
                // get invoked.
                int currentVTableIndexUnused = 0;
                VertexSequence vtableSignaturesSequence = null;
                
                ProcessVTableEntriesForCallingConventionSignatureGeneration(factory, VTableEntriesToProcess.AllInVTable, ref currentVTableIndexUnused,
                    (int vtableIndex, bool isSealedVTableSlot, MethodDesc declMethod, MethodDesc implMethod) =>
                    {
                        if (implMethod.IsAbstract)
                            return;

                        if (UniversalGenericParameterLayout.VTableMethodRequiresCallingConventionConverter(implMethod))
                        {
                            if (vtableSignaturesSequence == null)
                                vtableSignaturesSequence = new VertexSequence();

                            NativeLayoutVertexNode methodSignature = factory.NativeLayout.MethodSignatureVertex(declMethod.GetTypicalMethodDefinition().Signature);
                            Vertex signatureVertex = GetNativeWriter(factory).GetRelativeOffsetSignature(methodSignature.WriteVertex(factory));

                            Vertex vtableSignatureEntry = writer.GetTuple(
                                writer.GetUnsignedConstant((uint)((vtableIndex << 1) | (isSealedVTableSlot ? 1 : 0))),
                                factory.MetadataManager.NativeLayoutInfo.TemplatesSection.Place(signatureVertex));

                            vtableSignaturesSequence.Append(vtableSignatureEntry);
                        }
                    }
                    , _type, _type, _type);

                if (vtableSignaturesSequence != null)
                {
                    Vertex placedVtableSigs = factory.MetadataManager.NativeLayoutInfo.TemplatesSection.Place(vtableSignaturesSequence);
                    layoutInfo.Append(BagElementKind.VTableMethodSignatures, placedVtableSigs);
                }
            }

            factory.MetadataManager.NativeLayoutInfo.TemplatesSection.Place(layoutInfo);

            return SetSavedVertex(layoutInfo);
        }

        private enum VTableEntriesToProcess
        {
            AllInVTable,
            AllOnTypesThatShouldProduceFullVTables,
            AllOnTypesThatProducePartialVTables
        }

        private static IEnumerable<MethodDesc> EnumVirtualSlotsDeclaredOnType(TypeDesc declType)
        {
            // VirtualMethodUse of Foo<SomeType>.Method will bring in VirtualMethodUse
            // of Foo<__Canon>.Method. This in turn should bring in Foo<OtherType>.Method.
            DefType defType = declType.GetClosestDefType();

            Debug.Assert(!declType.IsInterface);

            IEnumerable<MethodDesc> allSlots = defType.EnumAllVirtualSlots();

            foreach (var method in allSlots)
            {
                // Generic virtual methods are tracked by an orthogonal mechanism.
                if (method.HasInstantiation)
                    continue;

                // Current type doesn't define this slot. Another VTableSlice will take care of this.
                if (method.OwningType != defType)
                    continue;

                yield return method;
            }
        }

        /// <summary>
        /// Process the vtable entries of a type by calling operation with the vtable index, declaring method, and implementing method
        /// Process them in order from 0th entry to last. 
        /// Skip generic virtual methods, as they are not present in the vtable itself
        /// Do not adjust vtable index for generic dictionary slot
        /// The vtable index is only actually valid if whichEntries is set to VTableEntriesToProcess.AllInVTable
        /// </summary>
        private void ProcessVTableEntriesForCallingConventionSignatureGeneration(NodeFactory factory, VTableEntriesToProcess whichEntries, ref int currentVTableIndex, Action<int, bool, MethodDesc, MethodDesc> operation, TypeDesc implType, TypeDesc declType, TypeDesc templateType)
        {
            if (implType.IsInterface)
                return;

            declType = declType.GetClosestDefType();
            templateType = templateType.ConvertToCanonForm(CanonicalFormKind.Specific);

            bool canShareNormalCanonicalCode = declType != declType.ConvertToCanonForm(CanonicalFormKind.Specific);

            var baseType = declType.BaseType;
            if (baseType != null)
            {
                Debug.Assert(templateType.BaseType != null);
                ProcessVTableEntriesForCallingConventionSignatureGeneration(factory, whichEntries, ref currentVTableIndex, operation, implType, baseType, templateType.BaseType);
            }

            IEnumerable<MethodDesc> vtableEntriesToProcess;

            if (ConstructedEETypeNode.CreationAllowed(declType))
            {
                switch (whichEntries)
                {
                    case VTableEntriesToProcess.AllInVTable:
                        vtableEntriesToProcess = factory.VTable(declType).Slots;
                        break;

                    case VTableEntriesToProcess.AllOnTypesThatShouldProduceFullVTables:
                        if (factory.VTable(declType).HasFixedSlots)
                        {
                            vtableEntriesToProcess = factory.VTable(declType).Slots;
                        }
                        else
                        {
                            vtableEntriesToProcess = Array.Empty<MethodDesc>();
                        }
                        break;

                    case VTableEntriesToProcess.AllOnTypesThatProducePartialVTables:
                        if (factory.VTable(declType).HasFixedSlots)
                        {
                            vtableEntriesToProcess = Array.Empty<MethodDesc>();
                        }
                        else
                        {
                            vtableEntriesToProcess = EnumVirtualSlotsDeclaredOnType(declType);
                        }
                        break;

                    default:
                        throw new Exception();
                }
            }
            else
            {
                // If allocating an object of the EEType isn't permitted, don't process any vtable entries.
                vtableEntriesToProcess = Array.Empty<MethodDesc>();
            }

            // Dictionary slot
            if (declType.HasGenericDictionarySlot() || templateType.HasGenericDictionarySlot())
                currentVTableIndex++;

            int sealedVTableSlot = 0;
            DefType closestDefType = implType.GetClosestDefType();

            // Actual vtable slots follow
            foreach (MethodDesc declMethod in vtableEntriesToProcess)
            {
                // No generic virtual methods can appear in the vtable!
                Debug.Assert(!declMethod.HasInstantiation);

                MethodDesc implMethod = closestDefType.FindVirtualFunctionTargetMethodOnObjectType(declMethod);

                if (implMethod.CanMethodBeInSealedVTable() && !implType.IsArrayTypeWithoutGenericInterfaces())
                {
                    // Sealed vtable entries on other types in the hierarchy should not be reported (types read entries
                    // from their own sealed vtables, and not from the sealed vtables of base types).
                    if (implMethod.OwningType == closestDefType)
                        operation(sealedVTableSlot++, true, declMethod, implMethod);
                }
                else
                {
                    operation(currentVTableIndex++, false, declMethod, implMethod);
                }
            }
        }
    }

    public abstract class NativeLayoutGenericDictionarySlotNode : NativeLayoutVertexNode
    {
        public abstract override IEnumerable<DependencyListEntry> GetStaticDependencies(NodeFactory context);
        protected abstract Vertex WriteSignatureVertex(NativeWriter writer, NodeFactory factory);
        protected abstract FixupSignatureKind SignatureKind { get; }

        public override Vertex WriteVertex(NodeFactory factory)
        {
            CheckIfMarkedEnoughToWrite();

            NativeWriter writer = GetNativeWriter(factory);
            return writer.GetFixupSignature(SignatureKind, WriteSignatureVertex(writer, factory));
        }
    }

    public abstract class NativeLayoutTypeSignatureBasedGenericDictionarySlotNode : NativeLayoutGenericDictionarySlotNode
    {
        NativeLayoutTypeSignatureVertexNode _signature;
        TypeDesc _type;

        public NativeLayoutTypeSignatureBasedGenericDictionarySlotNode(NodeFactory factory, TypeDesc type)
        {
            _signature = factory.NativeLayout.TypeSignatureVertex(type);
            _type = type;
        }

        protected abstract string NodeTypeName { get; }
        protected sealed override string GetName(NodeFactory factory) => NodeTypeName + factory.NameMangler.GetMangledTypeName(_type);

        public sealed override IEnumerable<DependencyListEntry> GetStaticDependencies(NodeFactory factory)
        {
            yield return new DependencyListEntry(_signature, "TypeSignature");

            foreach (var dependency in factory.NativeLayout.TemplateConstructableTypes(_type))
            {
                yield return new DependencyListEntry(dependency, "template construction dependency");
            }
        }

        protected sealed override Vertex WriteSignatureVertex(NativeWriter writer, NodeFactory factory)
        {
            return _signature.WriteVertex(factory);
        }
    }

    public sealed class NativeLayoutTypeHandleGenericDictionarySlotNode : NativeLayoutTypeSignatureBasedGenericDictionarySlotNode
    {
        public NativeLayoutTypeHandleGenericDictionarySlotNode(NodeFactory factory, TypeDesc type) : base(factory, type)
        {
        }

        protected override string NodeTypeName => "NativeLayoutTypeHandleGenericDictionarySlotNode_";

        protected override FixupSignatureKind SignatureKind => FixupSignatureKind.TypeHandle;
    }

    public sealed class NativeLayoutUnwrapNullableGenericDictionarySlotNode : NativeLayoutTypeSignatureBasedGenericDictionarySlotNode
    {
        public NativeLayoutUnwrapNullableGenericDictionarySlotNode(NodeFactory factory, TypeDesc type) : base(factory, type)
        {
        }

        protected override string NodeTypeName => "NativeLayoutUnwrapNullableGenericDictionarySlotNode_";

        protected override FixupSignatureKind SignatureKind => FixupSignatureKind.UnwrapNullableType;
    }

    public sealed class NativeLayoutTypeSizeGenericDictionarySlotNode : NativeLayoutTypeSignatureBasedGenericDictionarySlotNode
    {
        public NativeLayoutTypeSizeGenericDictionarySlotNode(NodeFactory factory, TypeDesc type) : base(factory, type)
        {
        }

        protected override string NodeTypeName => "NativeLayoutTypeSizeGenericDictionarySlotNode_";

        protected override FixupSignatureKind SignatureKind => FixupSignatureKind.TypeSize;
    }

    public sealed class NativeLayoutAllocateObjectGenericDictionarySlotNode : NativeLayoutTypeSignatureBasedGenericDictionarySlotNode
    {
        public NativeLayoutAllocateObjectGenericDictionarySlotNode(NodeFactory factory, TypeDesc type) : base(factory, type)
        {
        }

        protected override string NodeTypeName => "NativeLayoutAllocateObjectGenericDictionarySlotNode_";

        protected override FixupSignatureKind SignatureKind => FixupSignatureKind.AllocateObject;
    }

    public sealed class NativeLayoutCastClassGenericDictionarySlotNode : NativeLayoutTypeSignatureBasedGenericDictionarySlotNode
    {
        public NativeLayoutCastClassGenericDictionarySlotNode(NodeFactory factory, TypeDesc type) : base(factory, type)
        {
        }

        protected override string NodeTypeName => "NativeLayoutAllocateCastClassDictionarySlotNode_";

        protected override FixupSignatureKind SignatureKind => FixupSignatureKind.CastClass;
    }

    public sealed class NativeLayoutIsInstGenericDictionarySlotNode : NativeLayoutTypeSignatureBasedGenericDictionarySlotNode
    {
        public NativeLayoutIsInstGenericDictionarySlotNode(NodeFactory factory, TypeDesc type) : base(factory, type)
        {
        }

        protected override string NodeTypeName => "NativeLayoutIsInstGenericDictionarySlotNode_";

        protected override FixupSignatureKind SignatureKind => FixupSignatureKind.IsInst;
    }

    public sealed class NativeLayoutTlsIndexGenericDictionarySlotNode : NativeLayoutTypeSignatureBasedGenericDictionarySlotNode
    {
        public NativeLayoutTlsIndexGenericDictionarySlotNode(NodeFactory factory, TypeDesc type) : base(factory, type)
        {
        }

        protected override string NodeTypeName => "NativeLayoutTlsIndexGenericDictionarySlotNode_";

        protected override FixupSignatureKind SignatureKind => FixupSignatureKind.TlsIndex;
    }

    public sealed class NativeLayoutTlsOffsetGenericDictionarySlotNode : NativeLayoutTypeSignatureBasedGenericDictionarySlotNode
    {
        public NativeLayoutTlsOffsetGenericDictionarySlotNode(NodeFactory factory, TypeDesc type) : base(factory, type)
        {
        }

        protected override string NodeTypeName => "NativeLayoutTlsOffsetGenericDictionarySlotNode_";

        protected override FixupSignatureKind SignatureKind => FixupSignatureKind.TlsOffset;
    }

    public sealed class NativeLayoutDefaultConstructorGenericDictionarySlotNode : NativeLayoutTypeSignatureBasedGenericDictionarySlotNode
    {
        public NativeLayoutDefaultConstructorGenericDictionarySlotNode(NodeFactory factory, TypeDesc type) : base(factory, type)
        {
        }

        protected override string NodeTypeName => "NativeLayoutDefaultConstructorGenericDictionarySlotNode_";

        protected override FixupSignatureKind SignatureKind => FixupSignatureKind.DefaultConstructor;
    }

    public sealed class NativeLayoutAllocateArrayGenericDictionarySlotNode : NativeLayoutTypeSignatureBasedGenericDictionarySlotNode
    {
        public NativeLayoutAllocateArrayGenericDictionarySlotNode(NodeFactory factory, TypeDesc type) : base(factory, type)
        {
            Debug.Assert(type.IsArray); // TODO! Verify that the passed in type is the array type and not the element type of the array.
        }

        protected override string NodeTypeName => "NativeLayoutAllocateArrayGenericDictionarySlotNode_";

        protected override FixupSignatureKind SignatureKind => FixupSignatureKind.AllocateArray;
    }

    public abstract class NativeLayoutStaticsGenericDictionarySlotNode : NativeLayoutGenericDictionarySlotNode
    {
        NativeLayoutTypeSignatureVertexNode _signature;
        TypeDesc _type;

        public NativeLayoutStaticsGenericDictionarySlotNode(NodeFactory factory, TypeDesc type)
        {
            _signature = factory.NativeLayout.TypeSignatureVertex(type);
            _type = type;
        }

        protected abstract StaticDataKind StaticDataKindFlag { get; }
        protected abstract string NodeTypeName { get; }

        protected sealed override string GetName(NodeFactory factory) => NodeTypeName + factory.NameMangler.GetMangledTypeName(_type);

        protected sealed override FixupSignatureKind SignatureKind => FixupSignatureKind.StaticData;
        public sealed override IEnumerable<DependencyListEntry> GetStaticDependencies(NodeFactory factory)
        {
            yield return new DependencyListEntry(_signature, "TypeSignature");

            foreach (var dependency in factory.NativeLayout.TemplateConstructableTypes(_type))
            {
                yield return new DependencyListEntry(dependency, "template construction dependency");
            }
        }

        protected sealed override Vertex WriteSignatureVertex(NativeWriter writer, NodeFactory factory)
        {
            return writer.GetStaticDataSignature(_signature.WriteVertex(factory), StaticDataKindFlag);
        }
    }

    public sealed class NativeLayoutGcStaticsGenericDictionarySlotNode : NativeLayoutStaticsGenericDictionarySlotNode
    {
        public NativeLayoutGcStaticsGenericDictionarySlotNode(NodeFactory factory, TypeDesc type) : base(factory, type)
        { }

        protected override StaticDataKind StaticDataKindFlag => StaticDataKind.Gc;
        protected override string NodeTypeName => "NativeLayoutGcStaticsGenericDictionarySlotNode_";
    }

    public sealed class NativeLayoutNonGcStaticsGenericDictionarySlotNode : NativeLayoutStaticsGenericDictionarySlotNode
    {
        public NativeLayoutNonGcStaticsGenericDictionarySlotNode(NodeFactory factory, TypeDesc type) : base(factory, type)
        { }

        protected override StaticDataKind StaticDataKindFlag => StaticDataKind.NonGc;
        protected override string NodeTypeName => "NativeLayoutNonGcStaticsGenericDictionarySlotNode_";
    }

    public sealed class NativeLayoutInterfaceDispatchGenericDictionarySlotNode : NativeLayoutGenericDictionarySlotNode
    {
        NativeLayoutTypeSignatureVertexNode _signature;
        MethodDesc _method;

        public NativeLayoutInterfaceDispatchGenericDictionarySlotNode(NodeFactory factory, MethodDesc method)
        {
            _signature = factory.NativeLayout.TypeSignatureVertex(method.OwningType);
            _method = method;
        }

        protected sealed override string GetName(NodeFactory factory) => "NativeLayoutInterfaceDispatchGenericDictionarySlotNode_" + factory.NameMangler.GetMangledMethodName(_method);

        protected sealed override FixupSignatureKind SignatureKind => FixupSignatureKind.InterfaceCall;
        public sealed override IEnumerable<DependencyListEntry> GetStaticDependencies(NodeFactory factory)
        {
            yield return new DependencyListEntry(_signature, "TypeSignature");

            MethodDesc method = _method;
            if (method.IsRuntimeDeterminedExactMethod)
                method = method.GetCanonMethodTarget(CanonicalFormKind.Specific);

            if (!factory.VTable(method.OwningType).HasFixedSlots)
            {
                yield return new DependencyListEntry(factory.VirtualMethodUse(method), "Slot number");
            }

            foreach (var dependency in factory.NativeLayout.TemplateConstructableTypes(method.OwningType))
            {
                yield return new DependencyListEntry(dependency, "template construction dependency");
            }
        }

        protected sealed override Vertex WriteSignatureVertex(NativeWriter writer, NodeFactory factory)
        {
            MethodDesc method = _method;
            if (method.IsRuntimeDeterminedExactMethod)
                method = method.GetCanonMethodTarget(CanonicalFormKind.Specific);

            int slot = VirtualMethodSlotHelper.GetVirtualMethodSlot(factory, method, method.OwningType);

            return writer.GetMethodSlotSignature(_signature.WriteVertex(factory), checked((uint)slot));
        }
    }

    public sealed class NativeLayoutMethodDictionaryGenericDictionarySlotNode : NativeLayoutGenericDictionarySlotNode
    {
        MethodDesc _method;
        WrappedMethodDictionaryVertexNode _wrappedNode;

        private class WrappedMethodDictionaryVertexNode : NativeLayoutMethodEntryVertexNode
        {
            public WrappedMethodDictionaryVertexNode(NodeFactory factory, MethodDesc method) :
                base(factory, method, default(MethodEntryFlags))
            {
            }

            protected override IMethodNode GetMethodEntrypointNode(NodeFactory factory, out bool unboxingStub)
            {
                throw new NotSupportedException();
            }

            protected sealed override string GetName(NodeFactory factory) => "WrappedMethodEntryVertexNodeForDictionarySlot_" + factory.NameMangler.GetMangledMethodName(_method);
        }


        public NativeLayoutMethodDictionaryGenericDictionarySlotNode(NodeFactory factory, MethodDesc method)
        {
            Debug.Assert(method.HasInstantiation);
            _method = method;
            _wrappedNode = new WrappedMethodDictionaryVertexNode(factory, method);
        }

        protected sealed override string GetName(NodeFactory factory) => "NativeLayoutMethodDictionaryGenericDictionarySlotNode_" + factory.NameMangler.GetMangledMethodName(_method);
        protected sealed override FixupSignatureKind SignatureKind => FixupSignatureKind.MethodDictionary;
        public sealed override IEnumerable<DependencyListEntry> GetStaticDependencies(NodeFactory factory)
        {
            foreach (var dependency in factory.NativeLayout.TemplateConstructableTypes(_method.OwningType))
            {
                yield return new DependencyListEntry(dependency, "template construction dependency for method OwningType");
            }

            foreach (var type in _method.Instantiation)
            {
                foreach (var dependency in factory.NativeLayout.TemplateConstructableTypes(type))
                    yield return new DependencyListEntry(dependency, "template construction dependency for method Instantiation types");
            }

            yield return new DependencyListEntry(_wrappedNode, "wrappednode");
        }

        protected sealed override Vertex WriteSignatureVertex(NativeWriter writer, NodeFactory factory)
        {
            return _wrappedNode.WriteVertex(factory);
        }
    }

    public sealed class NativeLayoutFieldOffsetGenericDictionarySlotNode : NativeLayoutGenericDictionarySlotNode
    {
        FieldDesc _field;

        public NativeLayoutFieldOffsetGenericDictionarySlotNode(FieldDesc field)
        {
            _field = field;
        }

        protected sealed override string GetName(NodeFactory factory) => "NativeLayoutFieldOffsetGenericDictionarySlotNode_" + factory.NameMangler.GetMangledFieldName(_field);

        protected sealed override FixupSignatureKind SignatureKind => FixupSignatureKind.FieldOffset;

        public sealed override IEnumerable<DependencyListEntry> GetStaticDependencies(NodeFactory factory)
        {
            yield return new DependencyListEntry(factory.NativeLayout.TypeSignatureVertex(_field.OwningType), "Field Containing Type Signature");

            foreach (var dependency in factory.NativeLayout.TemplateConstructableTypes(_field.OwningType))
            {
                yield return new DependencyListEntry(dependency, "template construction dependency");
            }
        }

        protected sealed override Vertex WriteSignatureVertex(NativeWriter writer, NodeFactory factory)
        {
            NativeWriter nativeWriter = GetNativeWriter(factory);

            // NOTE: The order and contents of the field ordinal emitted here is based on the order of emission for fields
            // in the USG template generation.
            Vertex typeVertex = factory.NativeLayout.TypeSignatureVertex(_field.OwningType).WriteVertex(factory);
            return nativeWriter.GetTuple(typeVertex, nativeWriter.GetUnsignedConstant(checked((uint)_field.GetFieldOrdinal())));
        }
    }

    public sealed class NativeLayoutFieldLdTokenGenericDictionarySlotNode : NativeLayoutGenericDictionarySlotNode
    {
        FieldDesc _field;

        public NativeLayoutFieldLdTokenGenericDictionarySlotNode(FieldDesc field)
        {
            _field = field;
        }

        protected sealed override string GetName(NodeFactory factory) => "NativeLayoutFieldLdTokenGenericDictionarySlotNode_" + factory.NameMangler.GetMangledFieldName(_field);

        protected sealed override FixupSignatureKind SignatureKind => FixupSignatureKind.FieldLdToken;

        public sealed override IEnumerable<DependencyListEntry> GetStaticDependencies(NodeFactory factory)
        {
            yield return new DependencyListEntry(factory.NativeLayout.FieldLdTokenVertex(_field), "Field Signature");

            foreach (var dependency in factory.NativeLayout.TemplateConstructableTypes(_field.OwningType))
            {
                yield return new DependencyListEntry(dependency, "template construction dependency");
            }
        }

        protected sealed override Vertex WriteSignatureVertex(NativeWriter writer, NodeFactory factory)
        {
            Vertex ldToken = factory.NativeLayout.FieldLdTokenVertex(_field).WriteVertex(factory);
            return GetNativeWriter(factory).GetRelativeOffsetSignature(ldToken);
        }
    }

    public sealed class NativeLayoutVTableOffsetGenericDictionarySlotNode : NativeLayoutGenericDictionarySlotNode
    {
        MethodDesc _method;
        MethodDesc _slotDefiningMethod;

        public NativeLayoutVTableOffsetGenericDictionarySlotNode(MethodDesc method)
        {
            _method = method;
            MethodDesc typicalSlotDefiningMethod = MetadataVirtualMethodAlgorithm.FindSlotDefiningMethodForVirtualMethod(method.GetTypicalMethodDefinition());
            _slotDefiningMethod = _method.OwningType.FindMethodOnTypeWithMatchingTypicalMethod(typicalSlotDefiningMethod);
            Debug.Assert(method.IsRuntimeDeterminedExactMethod);
            Debug.Assert(!method.HasInstantiation);
            Debug.Assert(!method.OwningType.IsInterface);
            Debug.Assert(method.OwningType.IsDefType);
            Debug.Assert(method.IsVirtual);
        }

        protected sealed override string GetName(NodeFactory factory) => "NativeLayoutVTableOffsetGenericDictionarySlotNode_" + factory.NameMangler.GetMangledMethodName(_method);

        protected sealed override FixupSignatureKind SignatureKind => FixupSignatureKind.VTableOffset;

        public sealed override IEnumerable<DependencyListEntry> GetStaticDependencies(NodeFactory factory)
        {
            yield return new DependencyListEntry(factory.NativeLayout.TypeSignatureVertex(_slotDefiningMethod.OwningType), "Method VTableOffset Containing Type Signature");

            foreach (var dependency in factory.NativeLayout.TemplateConstructableTypes(_slotDefiningMethod.OwningType))
            {
                yield return new DependencyListEntry(dependency, "template construction dependency");
            }
        }

        protected sealed override Vertex WriteSignatureVertex(NativeWriter writer, NodeFactory factory)
        {
            NativeWriter nativeWriter = GetNativeWriter(factory);

            int slot = VirtualMethodSlotHelper.GetVirtualMethodSlot(factory, _slotDefiningMethod, _slotDefiningMethod.OwningType);
            Vertex typeVertex = factory.NativeLayout.TypeSignatureVertex(_slotDefiningMethod.OwningType).WriteVertex(factory);
            return nativeWriter.GetTuple(typeVertex, nativeWriter.GetUnsignedConstant((uint)slot));
        }
    }

    public sealed class NativeLayoutMethodLdTokenGenericDictionarySlotNode : NativeLayoutGenericDictionarySlotNode
    {
        MethodDesc _method;

        public NativeLayoutMethodLdTokenGenericDictionarySlotNode(MethodDesc method)
        {
            _method = method;
        }

        protected sealed override string GetName(NodeFactory factory) => "NativeLayoutMethodLdTokenGenericDictionarySlotNode_" + factory.NameMangler.GetMangledMethodName(_method);

        protected sealed override FixupSignatureKind SignatureKind => FixupSignatureKind.MethodLdToken;

        public sealed override IEnumerable<DependencyListEntry> GetStaticDependencies(NodeFactory factory)
        {
            yield return new DependencyListEntry(factory.NativeLayout.MethodLdTokenVertex(_method), "Method Signature");

            foreach (var dependency in factory.NativeLayout.TemplateConstructableTypes(_method.OwningType))
            {
                yield return new DependencyListEntry(dependency, "template construction dependency for method OwningType");
            }

            foreach (var type in _method.Instantiation)
            {
                foreach (var dependency in factory.NativeLayout.TemplateConstructableTypes(type))
                    yield return new DependencyListEntry(dependency, "template construction dependency for method Instantiation types");
            }
        }

        protected sealed override Vertex WriteSignatureVertex(NativeWriter writer, NodeFactory factory)
        {
            Vertex ldToken = factory.NativeLayout.MethodLdTokenVertex(_method).WriteVertex(factory);
            return GetNativeWriter(factory).GetRelativeOffsetSignature(ldToken);
        }
    }

    public sealed class NativeLayoutCallingConventionConverterGenericDictionarySlotNode : NativeLayoutGenericDictionarySlotNode
    {
        Internal.TypeSystem.MethodSignature _signature;
        CallingConventionConverterKind _converterKind;

        public NativeLayoutCallingConventionConverterGenericDictionarySlotNode(Internal.TypeSystem.MethodSignature signature, CallingConventionConverterKind converterKind)
        {
            _signature = signature;
            _converterKind = converterKind;
        }

        protected sealed override string GetName(NodeFactory factory) => 
            "NativeLayoutCallingConventionConverterGenericDictionarySlotNode" + _converterKind.ToString() +
             _signature.GetName();

        protected sealed override FixupSignatureKind SignatureKind => FixupSignatureKind.CallingConventionConverter;

        public sealed override IEnumerable<DependencyListEntry> GetStaticDependencies(NodeFactory factory)
        {
            yield return new DependencyListEntry(factory.NativeLayout.MethodSignatureVertex(_signature), "Method Signature");

            for (int i = 0; i < _signature.Length; i++)
            {
                foreach (var dep in factory.NativeLayout.UniversalTemplateConstructableTypes(_signature[i]))
                {
                    yield return new DependencyListEntry(dep, "template construction dependency");
                }
            }
            foreach (var dep in factory.NativeLayout.UniversalTemplateConstructableTypes(_signature.ReturnType))
            {
                yield return new DependencyListEntry(dep, "template construction dependency");
            }
        }

        protected sealed override Vertex WriteSignatureVertex(NativeWriter writer, NodeFactory factory)
        {
            Vertex signatureStream = factory.NativeLayout.MethodSignatureVertex(_signature).WriteVertex(factory);
            return GetNativeWriter(factory).GetCallingConventionConverterSignature((uint)_converterKind, signatureStream);
        }
    }

    public sealed class NativeLayoutConstrainedMethodDictionarySlotNode : NativeLayoutGenericDictionarySlotNode
    {
        MethodDesc _constrainedMethod;
        TypeDesc _constraintType;
        bool _directCall;

        public NativeLayoutConstrainedMethodDictionarySlotNode(MethodDesc constrainedMethod, TypeDesc constraintType, bool directCall)
        {
            _constrainedMethod = constrainedMethod;
            _constraintType = constraintType;
            _directCall = directCall;
            Debug.Assert(_constrainedMethod.OwningType.IsInterface);
            Debug.Assert(!_constrainedMethod.HasInstantiation || !directCall);
        }

        protected sealed override string GetName(NodeFactory factory) =>
            "NativeLayoutConstrainedMethodDictionarySlotNode_"
            + (_directCall ? "Direct" : "")
            + factory.NameMangler.GetMangledMethodName(_constrainedMethod) 
            + ","
            + factory.NameMangler.GetMangledTypeName(_constraintType);

        protected sealed override FixupSignatureKind SignatureKind => _constrainedMethod.HasInstantiation ? FixupSignatureKind.GenericConstrainedMethod :
            (_directCall ? FixupSignatureKind.NonGenericDirectConstrainedMethod : FixupSignatureKind.NonGenericConstrainedMethod);

        public sealed override IEnumerable<DependencyListEntry> GetStaticDependencies(NodeFactory factory)
        {
            DependencyNodeCore<NodeFactory> constrainedMethodDescriptorNode;
            if (_constrainedMethod.HasInstantiation)
            {
                constrainedMethodDescriptorNode = factory.NativeLayout.MethodLdTokenVertex(_constrainedMethod);
            }
            else
            {
                constrainedMethodDescriptorNode = factory.NativeLayout.TypeSignatureVertex(_constrainedMethod.OwningType);
            }

            yield return new DependencyListEntry(factory.NativeLayout.TypeSignatureVertex(_constraintType), "ConstraintType");

            yield return new DependencyListEntry(constrainedMethodDescriptorNode, "ConstrainedMethodType");

            foreach (var dependency in factory.NativeLayout.TemplateConstructableTypes(_constrainedMethod.OwningType))
            {
                yield return new DependencyListEntry(dependency, "template construction dependency constrainedMethod OwningType");
            }

            foreach (var type in _constrainedMethod.Instantiation)
            {
                foreach (var dependency in factory.NativeLayout.TemplateConstructableTypes(type))
                    yield return new DependencyListEntry(dependency, "template construction dependency constrainedMethod Instantiation type");
            }

            foreach (var dependency in factory.NativeLayout.TemplateConstructableTypes(_constraintType))
                yield return new DependencyListEntry(dependency, "template construction dependency constraintType");
        }

        protected sealed override Vertex WriteSignatureVertex(NativeWriter writer, NodeFactory factory)
        {
            Vertex constraintType = factory.NativeLayout.TypeSignatureVertex(_constraintType).WriteVertex(factory);
            if (_constrainedMethod.HasInstantiation)
            {
                Debug.Assert(SignatureKind == FixupSignatureKind.GenericConstrainedMethod);
                Vertex constrainedMethodVertex = factory.NativeLayout.MethodLdTokenVertex(_constrainedMethod).WriteVertex(factory);
                Vertex relativeOffsetVertex = GetNativeWriter(factory).GetRelativeOffsetSignature(constrainedMethodVertex);
                return writer.GetTuple(constraintType, relativeOffsetVertex);
            }
            else
            {
                Debug.Assert((SignatureKind == FixupSignatureKind.NonGenericConstrainedMethod) || (SignatureKind == FixupSignatureKind.NonGenericDirectConstrainedMethod));
                Vertex methodType = factory.NativeLayout.TypeSignatureVertex(_constrainedMethod.OwningType).WriteVertex(factory);
                var canonConstrainedMethod = _constrainedMethod.GetCanonMethodTarget(CanonicalFormKind.Specific);
                int interfaceSlot = VirtualMethodSlotHelper.GetVirtualMethodSlot(factory, canonConstrainedMethod, canonConstrainedMethod.OwningType);
                Vertex interfaceSlotVertex = writer.GetUnsignedConstant(checked((uint)interfaceSlot));
                return writer.GetTuple(constraintType, methodType, interfaceSlotVertex);
            }
        }
    }

    public sealed class NativeLayoutMethodEntrypointGenericDictionarySlotNode : NativeLayoutGenericDictionarySlotNode
    {
        MethodDesc _method;
        WrappedMethodEntryVertexNode _wrappedNode;

        private class WrappedMethodEntryVertexNode : NativeLayoutMethodEntryVertexNode
        {
            public bool _unboxingStub;
            public IMethodNode _functionPointerNode;

            public WrappedMethodEntryVertexNode(NodeFactory factory, MethodDesc method, bool unboxingStub, IMethodNode functionPointerNode) :
                base(factory, method, functionPointerNode != null ? MethodEntryFlags.SaveEntryPoint : default(MethodEntryFlags))
            {
                _unboxingStub = unboxingStub;
                _functionPointerNode = functionPointerNode;
            }

            protected override IMethodNode GetMethodEntrypointNode(NodeFactory factory, out bool unboxingStub)
            {
                unboxingStub = _unboxingStub;
                return _functionPointerNode;
            }

            protected sealed override string GetName(NodeFactory factory) => "WrappedMethodEntryVertexNodeForDictionarySlot_" + (_unboxingStub ? "Unboxing_" : "") + factory.NameMangler.GetMangledMethodName(_method);
        }


        public NativeLayoutMethodEntrypointGenericDictionarySlotNode(NodeFactory factory, MethodDesc method, IMethodNode functionPointerNode, bool unboxingStub)
        {
            _method = method;
            _wrappedNode = new WrappedMethodEntryVertexNode(factory, method, unboxingStub, functionPointerNode);
        }

        protected sealed override string GetName(NodeFactory factory) => "NativeLayoutMethodEntrypointGenericDictionarySlotNode_" + (_wrappedNode._unboxingStub ? "Unboxing_" : "") + factory.NameMangler.GetMangledMethodName(_method);
        protected sealed override FixupSignatureKind SignatureKind => FixupSignatureKind.Method;
        public sealed override IEnumerable<DependencyListEntry> GetStaticDependencies(NodeFactory factory)
        {
            foreach (var dependency in factory.NativeLayout.TemplateConstructableTypes(_method.OwningType))
            {
                yield return new DependencyListEntry(dependency, "template construction dependency for method OwningType");
            }

            foreach (var type in _method.Instantiation)
            {
                foreach (var dependency in factory.NativeLayout.TemplateConstructableTypes(type))
                    yield return new DependencyListEntry(dependency, "template construction dependency for method Instantiation types");
            }

            yield return new DependencyListEntry(_wrappedNode, "wrappednode");
        }

        protected sealed override Vertex WriteSignatureVertex(NativeWriter writer, NodeFactory factory)
        {
            return _wrappedNode.WriteVertex(factory);
        }
    }

    public sealed class NativeLayoutIntegerDictionarySlotNode : NativeLayoutGenericDictionarySlotNode
    {
        int _value;

        public NativeLayoutIntegerDictionarySlotNode(int value)
        {
            _value = value;
        }

        protected override FixupSignatureKind SignatureKind => FixupSignatureKind.IntValue;

        public override IEnumerable<DependencyListEntry> GetStaticDependencies(NodeFactory context)
        {
            return null;
        }

        protected override string GetName(NodeFactory context) => "NativeLayoutIntegerDictionarySlotNode_" + _value.ToStringInvariant();

        protected override Vertex WriteSignatureVertex(NativeWriter writer, NodeFactory factory)
        {
            return writer.GetUnsignedConstant((uint)_value);
        }

        public override void CheckIfMarkedEnoughToWrite()
        {
            // Do nothing, this node does not need marking
        }
    }

    public sealed class NativeLayoutPointerToOtherSlotDictionarySlotNode : NativeLayoutGenericDictionarySlotNode
    {
        int _otherSlotIndex;

        public NativeLayoutPointerToOtherSlotDictionarySlotNode(int otherSlotIndex)
        {
            _otherSlotIndex = otherSlotIndex;
        }

        protected override FixupSignatureKind SignatureKind => FixupSignatureKind.PointerToOtherSlot;

        public override IEnumerable<DependencyListEntry> GetStaticDependencies(NodeFactory context)
        {
            return null;
        }

        protected override string GetName(NodeFactory context) => "NativeLayoutPointerToOtherSlotDictionarySlotNode_" + _otherSlotIndex.ToStringInvariant();

        protected override Vertex WriteSignatureVertex(NativeWriter writer, NodeFactory factory)
        {
            return writer.GetUnsignedConstant((uint)_otherSlotIndex);
        }

        public override void CheckIfMarkedEnoughToWrite()
        {
            // Do nothing, this node does not need marking
        }
    }

    public sealed class NativeLayoutNotSupportedDictionarySlotNode : NativeLayoutGenericDictionarySlotNode
    {
        protected override FixupSignatureKind SignatureKind => FixupSignatureKind.NotYetSupported;

        public override IEnumerable<DependencyListEntry> GetStaticDependencies(NodeFactory context)
        {
            return null;
        }

        protected override string GetName(NodeFactory context) => "NativeLayoutNotSupportedDictionarySlotNode";
        
        protected override Vertex WriteSignatureVertex(NativeWriter writer, NodeFactory factory)
        {
            return writer.GetUnsignedConstant(0xDEADBEEF);
        }
    }
}