File: GenProto.cpp

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (4407 lines) | stat: -rw-r--r-- 173,053 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
//===--- GenProto.cpp - Swift IR Generation for Protocols -----------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
//  This file implements IR generation for protocols in Swift.
//
//  Protocols serve two masters: generic algorithms and existential
//  types.  In either case, the size and structure of a type is opaque
//  to the code manipulating a value.  Local values of the type must
//  be stored in fixed-size buffers (which can overflow to use heap
//  allocation), and basic operations on the type must be dynamically
//  delegated to a collection of information that "witnesses" the
//  truth that a particular type implements the protocol.
//
//  In the comments throughout this file, three type names are used:
//    'B' is the type of a fixed-size buffer
//    'T' is the type which implements a protocol
//    'W' is the type of a witness to the protocol
//
//===----------------------------------------------------------------------===//

#include "swift/AST/ASTContext.h"
#include "swift/AST/CanTypeVisitor.h"
#include "swift/AST/Types.h"
#include "swift/AST/Decl.h"
#include "swift/AST/DiagnosticsIRGen.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/LazyResolver.h"
#include "swift/AST/IRGenOptions.h"
#include "swift/AST/PackConformance.h"
#include "swift/AST/PrettyStackTrace.h"
#include "swift/AST/SubstitutionMap.h"
#include "swift/Basic/Platform.h"
#include "swift/ClangImporter/ClangModule.h"
#include "swift/IRGen/Linking.h"
#include "swift/SIL/SILDeclRef.h"
#include "swift/SIL/SILDefaultWitnessTable.h"
#include "swift/SIL/SILModule.h"
#include "swift/SIL/SILValue.h"
#include "swift/SIL/SILWitnessTable.h"
#include "swift/SIL/SILWitnessVisitor.h"
#include "swift/SIL/TypeLowering.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Module.h"

#include "CallEmission.h"
#include "ConformanceDescription.h"
#include "ConstantBuilder.h"
#include "EntryPointArgumentEmission.h"
#include "EnumPayload.h"
#include "Explosion.h"
#include "FixedTypeInfo.h"
#include "Fulfillment.h"
#include "GenArchetype.h"
#include "GenCall.h"
#include "GenCast.h"
#include "GenClass.h"
#include "GenEnum.h"
#include "GenHeap.h"
#include "GenMeta.h"
#include "GenOpaque.h"
#include "GenPack.h"
#include "GenPointerAuth.h"
#include "GenPoly.h"
#include "GenTuple.h"
#include "GenType.h"
#include "GenericRequirement.h"
#include "IRGenDebugInfo.h"
#include "IRGenFunction.h"
#include "IRGenMangler.h"
#include "IRGenModule.h"
#include "LoadableTypeInfo.h"
#include "MetadataPath.h"
#include "MetadataRequest.h"
#include "NecessaryBindings.h"
#include "ProtocolInfo.h"
#include "TypeInfo.h"

#include "GenProto.h"

using namespace swift;
using namespace irgen;

namespace {

/// A class for computing how to pass arguments to a polymorphic
/// function.  The subclasses of this are the places which need to
/// be updated if the convention changes.
class PolymorphicConvention {
protected:
  IRGenModule &IGM;
  ModuleDecl &M;
  CanSILFunctionType FnType;

  CanGenericSignature Generics;

  std::vector<MetadataSource> Sources;

  FulfillmentMap Fulfillments;

  GenericSignature::RequiredProtocols getRequiredProtocols(Type t) {
    return Generics->getRequiredProtocols(t);
  }

  CanType getSuperclassBound(Type t) {
    if (auto superclassTy = Generics->getSuperclassBound(t))
      return superclassTy->getCanonicalType();
    return CanType();
  }

public:
  PolymorphicConvention(IRGenModule &IGM, CanSILFunctionType fnType, bool considerParameterSources);

  ArrayRef<MetadataSource> getSources() const { return Sources; }

  void enumerateRequirements(const RequirementCallback &callback);

  void enumerateUnfulfilledRequirements(const RequirementCallback &callback);

  /// Returns a Fulfillment for a type parameter requirement, or
  /// nullptr if it's unfulfilled.
  const Fulfillment *getFulfillmentForTypeMetadata(CanType type) const;

  /// Returns a Fulfillment for a pack shape, or nullptr if it's
  /// unfulfilled.
  const Fulfillment *getFulfillmentForShape(CanType type) const;

  /// Return the source of type metadata at a particular source index.
  const MetadataSource &getSource(size_t SourceIndex) const {
    return Sources[SourceIndex];
  }

private:
  void initGenerics();

  template <typename ...Args>
  void considerNewTypeSource(IsExact_t isExact, MetadataSource::Kind kind,
                             CanType type, Args... args);
  bool considerType(CanType type, IsExact_t isExact,
                    unsigned sourceIndex, MetadataPath &&path);

  /// Testify to generic parameters in the Self type of a protocol
  /// witness method.
  void considerWitnessSelf(CanSILFunctionType fnType);

  /// Testify to generic parameters in the Self type of an @objc
  /// generic or protocol method.
  void considerObjCGenericSelf(CanSILFunctionType fnType);

  void considerParameter(SILParameterInfo param, unsigned paramIndex,
                         bool isSelfParameter);

  void addSelfMetadataFulfillment(CanType arg);
  void addSelfWitnessTableFulfillment(CanType arg,
                                      ProtocolConformanceRef conformance);

  void addPseudogenericFulfillments();

  struct FulfillmentMapCallback : FulfillmentMap::InterestingKeysCallback {
    PolymorphicConvention &Self;
    FulfillmentMapCallback(PolymorphicConvention &self) : Self(self) {}

    bool isInterestingType(CanType type) const override {
      return type->isTypeParameter();
    }
    bool hasInterestingType(CanType type) const override {
      return type->hasTypeParameter();
    }
    bool isInterestingPackExpansion(CanPackExpansionType type) const override {
      return type.getPatternType()->isTypeParameter();
    }
    bool hasLimitedInterestingConformances(CanType type) const override {
      return true;
    }
    GenericSignature::RequiredProtocols
    getInterestingConformances(CanType type) const override {
      return Self.getRequiredProtocols(type);
    }
    CanType getSuperclassBound(CanType type) const override {
      return Self.getSuperclassBound(type);
    }
  };
};

} // end anonymous namespace

PolymorphicConvention::PolymorphicConvention(IRGenModule &IGM,
                                             CanSILFunctionType fnType,
                                             bool considerParameterSources = true)
  : IGM(IGM), M(*IGM.getSwiftModule()), FnType(fnType){
  initGenerics();

  auto rep = fnType->getRepresentation();

  if (fnType->isPseudogeneric()) {
    // Protocol witnesses still get Self metadata no matter what. The type
    // parameters of Self are pseudogeneric, though.
    if (rep == SILFunctionTypeRepresentation::WitnessMethod)
      considerWitnessSelf(fnType);

    addPseudogenericFulfillments();
    return;
  }

  if (rep == SILFunctionTypeRepresentation::WitnessMethod) {
    // Protocol witnesses always derive all polymorphic parameter information
    // from the Self and Self witness table arguments. We also *cannot* consider
    // other arguments; doing so would potentially make the signature
    // incompatible with other witnesses for the same method.
    considerWitnessSelf(fnType);
  } else if (rep == SILFunctionTypeRepresentation::ObjCMethod) {
    // Objective-C thunks for generic methods also always derive all
    // polymorphic parameter information from the Self argument.
    considerObjCGenericSelf(fnType);
  } else {
    // We don't need to pass anything extra as long as all of the
    // archetypes (and their requirements) are producible from
    // arguments.
    unsigned selfIndex = ~0U;
    auto params = fnType->getParameters();

    if (considerParameterSources) {
      // Consider 'self' first.
      if (fnType->hasSelfParam()) {
        selfIndex = params.size() - 1;
        considerParameter(params[selfIndex], selfIndex, true);
      }

      // Now consider the rest of the parameters.
      for (auto index : indices(params)) {
        if (index != selfIndex)
          considerParameter(params[index], index, false);
      }
    }
  }
}

void PolymorphicConvention::addPseudogenericFulfillments() {
  enumerateRequirements([&](GenericRequirement reqt) {
    auto archetype = Generics.getGenericEnvironment()
                        ->mapTypeIntoContext(reqt.getTypeParameter())
                        ->getAs<ArchetypeType>();
    assert(archetype && "did not get an archetype by mapping param?");
    auto erasedTypeParam = archetype->getExistentialType()->getCanonicalType();
    Sources.emplace_back(MetadataSource::Kind::ErasedTypeMetadata,
                         reqt.getTypeParameter(), erasedTypeParam);

    MetadataPath path;
    Fulfillments.addFulfillment(reqt,
                                Sources.size() - 1, std::move(path),
                                MetadataState::Complete);
  });
}

void
irgen::enumerateGenericSignatureRequirements(CanGenericSignature signature,
                                          const RequirementCallback &callback) {
  if (!signature) return;

  for (auto type : signature->getShapeClasses())
    callback(GenericRequirement::forShape(type));

  // Get all of the type metadata.
  signature->forEachParam([&](GenericTypeParamType *gp, bool canonical) {
    if (canonical)
      callback(GenericRequirement::forMetadata(CanType(gp)));
  });

  // Get the protocol conformances.
  for (auto &reqt : signature.getRequirements()) {
    switch (reqt.getKind()) {
      // Ignore these; they don't introduce extra requirements.
      case RequirementKind::SameShape:
      case RequirementKind::Superclass:
      case RequirementKind::SameType:
      case RequirementKind::Layout:
        continue;

      case RequirementKind::Conformance: {
        auto type = CanType(reqt.getFirstType());
        auto protocol = reqt.getProtocolDecl();
        if (Lowering::TypeConverter::protocolRequiresWitnessTable(protocol)) {
          callback(GenericRequirement::forWitnessTable(type, protocol));
        }
        continue;
      }
    }
    llvm_unreachable("bad requirement kind");
  }
}

void
PolymorphicConvention::enumerateRequirements(const RequirementCallback &callback) {
  return enumerateGenericSignatureRequirements(Generics, callback);
}

void PolymorphicConvention::
enumerateUnfulfilledRequirements(const RequirementCallback &callback) {
  enumerateRequirements([&](GenericRequirement requirement) {
    if (!Fulfillments.getFulfillment(requirement))
      callback(requirement);
  });
}

void PolymorphicConvention::initGenerics() {
  Generics = FnType->getInvocationGenericSignature();
}

template <typename ...Args>
void PolymorphicConvention::considerNewTypeSource(IsExact_t isExact,
                                                  MetadataSource::Kind kind,
                                                  CanType type,
                                                  Args... args) {
  if (!Fulfillments.isInterestingTypeForFulfillments(type)) return;

  // Prospectively add a source.
  Sources.emplace_back(kind, type, std::forward<Args>(args)...);

  // Consider the source.
  if (!considerType(type, isExact, Sources.size() - 1, MetadataPath())) {
    // If it wasn't used in any fulfillments, remove it.
    Sources.pop_back();
  }
}

bool PolymorphicConvention::considerType(CanType type, IsExact_t isExact,
                                         unsigned sourceIndex,
                                         MetadataPath &&path) {
  FulfillmentMapCallback callbacks(*this);
  return Fulfillments.searchTypeMetadata(IGM, type, isExact,
                                         MetadataState::Complete, sourceIndex,
                                         std::move(path), callbacks);
}

void PolymorphicConvention::considerWitnessSelf(CanSILFunctionType fnType) {
  CanType selfTy = fnType->getSelfInstanceType(
      IGM.getSILModule(), IGM.getMaximalTypeExpansionContext());
  auto conformance = fnType->getWitnessMethodConformanceOrInvalid();

  // First, bind type metadata for Self.
  Sources.emplace_back(MetadataSource::Kind::SelfMetadata, selfTy);

  if (selfTy->is<GenericTypeParamType>()) {
    // The Self type is abstract, so we can fulfill its metadata from
    // the Self metadata parameter.
    addSelfMetadataFulfillment(selfTy);
  }

  considerType(selfTy, IsInexact, Sources.size() - 1, MetadataPath());

  // The witness table for the Self : P conformance can be
  // fulfilled from the Self witness table parameter.
  Sources.emplace_back(MetadataSource::Kind::SelfWitnessTable, selfTy);
  addSelfWitnessTableFulfillment(selfTy, conformance);
}

void PolymorphicConvention::considerObjCGenericSelf(CanSILFunctionType fnType) {
  // If this is a static method, get the instance type.
  CanType selfTy = fnType->getSelfInstanceType(
      IGM.getSILModule(), IGM.getMaximalTypeExpansionContext());
  unsigned paramIndex = fnType->getParameters().size() - 1;

  // Bind type metadata for Self.
  Sources.emplace_back(MetadataSource::Kind::ClassPointer, selfTy, paramIndex);

  if (isa<GenericTypeParamType>(selfTy))
    addSelfMetadataFulfillment(selfTy);
  else
    considerType(selfTy, IsInexact,
                 Sources.size() - 1, MetadataPath());
}

void PolymorphicConvention::considerParameter(SILParameterInfo param,
                                              unsigned paramIndex,
                                              bool isSelfParameter) {
  auto type = param.getArgumentType(IGM.getSILModule(), FnType,
                                    IGM.getMaximalTypeExpansionContext());
  switch (param.getConvention()) {
      // Indirect parameters do give us a value we can use, but right now
      // we don't bother, for no good reason. But if this is 'self',
      // consider passing an extra metatype.
    case ParameterConvention::Indirect_In:
    case ParameterConvention::Indirect_In_Guaranteed:
    case ParameterConvention::Indirect_Inout:
    case ParameterConvention::Indirect_InoutAliasable:
      if (!isSelfParameter) return;
      if (type->getNominalOrBoundGenericNominal()) {
        considerNewTypeSource(IsExact,
                              MetadataSource::Kind::GenericLValueMetadata,
                              type, paramIndex);
      }
      return;

    case ParameterConvention::Pack_Guaranteed:
    case ParameterConvention::Pack_Owned:
    case ParameterConvention::Pack_Inout:
      // Ignore packs as sources of metadata.
      // In principle, we could recurse into non-expansion components,
      // but what situation would we be in where we had concrete
      // components of a pack and weren't ABI-constrained to ignore them?
      return;

    case ParameterConvention::Direct_Owned:
    case ParameterConvention::Direct_Unowned:
    case ParameterConvention::Direct_Guaranteed:
      // Classes are sources of metadata.
      if (type->getClassOrBoundGenericClass()) {
        considerNewTypeSource(IsInexact, MetadataSource::Kind::ClassPointer,
                              type, paramIndex);
        return;
      }

      if (isa<GenericTypeParamType>(type)) {
        if (auto superclassTy = getSuperclassBound(type)) {
          considerNewTypeSource(IsInexact, MetadataSource::Kind::ClassPointer,
                                superclassTy, paramIndex);
          return;

        }
      }

      // Thick metatypes are sources of metadata.
      if (auto metatypeTy = dyn_cast<MetatypeType>(type)) {
        if (metatypeTy->getRepresentation() != MetatypeRepresentation::Thick)
          return;

        // Thick metatypes for Objective-C parameterized classes are not
        // sources of metadata.
        CanType objTy = metatypeTy.getInstanceType();
        if (auto classDecl = objTy->getClassOrBoundGenericClass())
          if (classDecl->isTypeErasedGenericClass())
            return;

        considerNewTypeSource(IsInexact, MetadataSource::Kind::Metadata, objTy,
                              paramIndex);
        return;
      }

      return;
  }
  llvm_unreachable("bad parameter convention");
}

void PolymorphicConvention::addSelfMetadataFulfillment(CanType arg) {
  unsigned source = Sources.size() - 1;
  Fulfillments.addFulfillment(GenericRequirement::forMetadata(arg),
                              source, MetadataPath(), MetadataState::Complete);
}

void PolymorphicConvention::addSelfWitnessTableFulfillment(
    CanType arg, ProtocolConformanceRef conformance) {
  auto proto = conformance.getRequirement();
  unsigned source = Sources.size() - 1;
  Fulfillments.addFulfillment(GenericRequirement::forWitnessTable(arg, proto),
                              source, MetadataPath(), MetadataState::Complete);

  if (conformance.isConcrete()) {
    FulfillmentMapCallback callbacks(*this);
    Fulfillments.searchConformance(IGM, conformance.getConcrete(), source,
                                   MetadataPath(), callbacks);
  }
}

const Fulfillment *
PolymorphicConvention::getFulfillmentForTypeMetadata(CanType type) const {
  return Fulfillments.getTypeMetadata(type);
}

const Fulfillment *
PolymorphicConvention::getFulfillmentForShape(CanType type) const {
  return Fulfillments.getShape(type);
}

void irgen::enumerateGenericParamFulfillments(IRGenModule &IGM,
                                  CanSILFunctionType fnType,
                                  GenericParamFulfillmentCallback callback) {
  PolymorphicConvention convention(IGM, fnType);

  // Check if any requirements were fulfilled by metadata stored inside a
  // captured value.
  auto generics = fnType->getInvocationGenericSignature();

  for (auto shapeClass : generics->getShapeClasses()) {
    auto fulfillment
      = convention.getFulfillmentForShape(shapeClass);
    if (fulfillment == nullptr)
      continue;

    auto &source = convention.getSource(fulfillment->SourceIndex);
    callback(GenericRequirement::forShape(shapeClass),
             source, fulfillment->Path);
  }

  for (auto genericParam : generics.getGenericParams()) {
    auto genericParamType = genericParam->getCanonicalType();

    auto fulfillment
      = convention.getFulfillmentForTypeMetadata(genericParamType);
    if (fulfillment == nullptr)
      continue;

    auto &source = convention.getSource(fulfillment->SourceIndex);
    callback(GenericRequirement::forMetadata(genericParamType),
             source, fulfillment->Path);
  }
}

namespace {

/// A class for binding type parameters of a generic function.
class EmitPolymorphicParameters : public PolymorphicConvention {
  IRGenFunction &IGF;
  SILFunction &Fn;

public:
  EmitPolymorphicParameters(IRGenFunction &IGF, SILFunction &Fn);

  void emit(EntryPointArgumentEmission &emission,
            WitnessMetadata *witnessMetadata,
            const GetParameterFn &getParameter);

private:
  CanType getTypeInContext(CanType type) const;

  CanType getArgTypeInContext(unsigned paramIndex) const;

  /// Fulfill local type data from any extra information associated with
  /// the given source.
  void bindExtraSource(const MetadataSource &source,
                       EntryPointArgumentEmission &emission,
                       WitnessMetadata *witnessMetadata);

  void bindParameterSources(const GetParameterFn &getParameter);

  void bindParameterSource(SILParameterInfo param, unsigned paramIndex,
                           const GetParameterFn &getParameter) ;
  // Did the convention decide that the parameter at the given index
  // was a class-pointer source?
  bool isClassPointerSource(unsigned paramIndex);

  // If we are building a protocol witness thunks for
  // `DistributedActorSystem.remoteCall` or
  // `DistributedTargetInvocationEncoder.record{Argument, ReturnType}`
  // `DistributedTargetInvocationDecoder.decodeNextArgument`
  // `DistributedTargetInvocationResultHandler.onReturn`
  // requirements we need to supply witness tables associated with `Res`,
  // `Argument`, `R` generic parameters which are not expressible on the
  // protocol requirement because they come from `SerializationRequirement`
  // associated type.
  void injectAdHocDistributedRequirements();
};

} // end anonymous namespace

EmitPolymorphicParameters::EmitPolymorphicParameters(IRGenFunction &IGF,
                          SILFunction &Fn)
  : PolymorphicConvention(IGF.IGM, Fn.getLoweredFunctionType()),
    IGF(IGF), Fn(Fn) {}


CanType EmitPolymorphicParameters::getTypeInContext(CanType type) const {
  return Fn.mapTypeIntoContext(type)->getCanonicalType();
}

CanType EmitPolymorphicParameters::getArgTypeInContext(unsigned paramIndex) const {
  return getTypeInContext(FnType->getParameters()[paramIndex].getArgumentType(
      IGM.getSILModule(), FnType, IGM.getMaximalTypeExpansionContext()));
}

void EmitPolymorphicParameters::bindExtraSource(
    const MetadataSource &source, EntryPointArgumentEmission &emission,
    WitnessMetadata *witnessMetadata) {
  switch (source.getKind()) {
    case MetadataSource::Kind::Metadata:
    case MetadataSource::Kind::ClassPointer:
      // Ignore these, we'll get to them when we walk the parameter list.
      return;

    case MetadataSource::Kind::GenericLValueMetadata: {
      CanType argTy = getArgTypeInContext(source.getParamIndex());

      llvm::Value *metadata = emission.getNextPolymorphicParameterAsMetadata();
      setTypeMetadataName(IGF.IGM, metadata, argTy);

      IGF.bindLocalTypeDataFromTypeMetadata(argTy, IsExact, metadata,
                                            MetadataState::Complete);
      return;
    }

    case MetadataSource::Kind::SelfMetadata: {
      assert(witnessMetadata && "no metadata for witness method");
      llvm::Value *metadata = witnessMetadata->SelfMetadata;
      assert(metadata && "no Self metadata for witness method");

      // Mark this as the cached metatype for Self.
      auto selfTy = FnType->getSelfInstanceType(
          IGM.getSILModule(), IGM.getMaximalTypeExpansionContext());
      CanType argTy = getTypeInContext(selfTy);
      setTypeMetadataName(IGF.IGM, metadata, argTy);
      auto *CD = selfTy.getClassOrBoundGenericClass();
      // The self metadata here corresponds to the conforming type.
      // For an inheritable conformance, that may be a subclass of the static
      // type, and so the self metadata will be inexact. Currently, all
      // conformances are inheritable.
      IGF.bindLocalTypeDataFromTypeMetadata(
          argTy, (!CD || CD->isFinal()) ? IsExact : IsInexact, metadata,
                                            MetadataState::Complete);
      return;
    }

    case MetadataSource::Kind::SelfWitnessTable: {
      assert(witnessMetadata && "no metadata for witness method");
      llvm::Value *selfTable = witnessMetadata->SelfWitnessTable;
      assert(selfTable && "no Self witness table for witness method");

      // Mark this as the cached witness table for Self.
      auto conformance = FnType->getWitnessMethodConformanceOrInvalid();
      auto selfProto = conformance.getRequirement();

      auto selfTy = FnType->getSelfInstanceType(
          IGM.getSILModule(), IGM.getMaximalTypeExpansionContext());
      CanType argTy = getTypeInContext(selfTy);

      setProtocolWitnessTableName(IGF.IGM, selfTable, argTy, selfProto);
      IGF.setUnscopedLocalTypeData(
          argTy,
          LocalTypeDataKind::forProtocolWitnessTable(conformance),
          selfTable);

      if (conformance.isConcrete()) {
        IGF.bindLocalTypeDataFromSelfWitnessTable(
                                          conformance.getConcrete(),
                                          selfTable,
                                          [this](CanType type) {
                                            return getTypeInContext(type);
                                          });
      }
      return;
    }

    case MetadataSource::Kind::ErasedTypeMetadata: {
      ArtificialLocation Loc(IGF.getDebugScope(), IGF.IGM.DebugInfo.get(),
                             IGF.Builder);
      CanType argTy = getTypeInContext(source.Type);
      llvm::Value *metadata = IGF.emitTypeMetadataRef(source.getFixedType());
      setTypeMetadataName(IGF.IGM, metadata, argTy);
      IGF.bindLocalTypeDataFromTypeMetadata(argTy, IsExact, metadata,
                                            MetadataState::Complete);
      return;
    }
  }
  llvm_unreachable("bad source kind!");
}

void EmitPolymorphicParameters::bindParameterSources(const GetParameterFn &getParameter) {
  auto params = FnType->getParameters();

  // Bind things from 'self' preferentially.
  if (FnType->hasSelfParam()) {
    bindParameterSource(params.back(), params.size() - 1, getParameter);
    params = params.drop_back();
  }

  for (unsigned index : indices(params)) {
    bindParameterSource(params[index], index, getParameter);
  }
}

void EmitPolymorphicParameters::
bindParameterSource(SILParameterInfo param, unsigned paramIndex,
                    const GetParameterFn &getParameter) {
  // Ignore indirect parameters for now.  This is potentially dumb.
  if (IGF.IGM.silConv.isSILIndirect(param))
    return;

  CanType paramType = getArgTypeInContext(paramIndex);

  // If the parameter is a thick metatype, bind it directly.
  // TODO: objc metatypes?
  if (auto metatype = dyn_cast<MetatypeType>(paramType)) {
    if (metatype->getRepresentation() == MetatypeRepresentation::Thick) {
      paramType = metatype.getInstanceType();
      llvm::Value *metadata = getParameter(paramIndex);
      IGF.bindLocalTypeDataFromTypeMetadata(paramType, IsInexact, metadata,
                                            MetadataState::Complete);
    } else if (metatype->getRepresentation() == MetatypeRepresentation::ObjC) {
      paramType = metatype.getInstanceType();
      llvm::Value *objcMetatype = getParameter(paramIndex);
      auto *metadata = emitObjCMetadataRefForMetadata(IGF, objcMetatype);
      IGF.bindLocalTypeDataFromTypeMetadata(paramType, IsInexact, metadata,
                                            MetadataState::Complete);
    }
    return;
  }

  // If the parameter is a class type, we only consider it interesting
  // if the convention decided it was actually a source.
  // TODO: if the class pointer is guaranteed, we can do this lazily,
  // at which point it might make sense to do it for a wider selection
  // of types.
  if (isClassPointerSource(paramIndex)) {
    llvm::Value *instanceRef = getParameter(paramIndex);
    SILType instanceType = SILType::getPrimitiveObjectType(paramType);
    llvm::Value *metadata =
      emitDynamicTypeOfHeapObject(IGF, instanceRef,
                                  MetatypeRepresentation::Thick,
                                  instanceType,
                                  Fn.getGenericSignature(),
                                  /*allow artificial subclasses*/ true);
    IGF.bindLocalTypeDataFromTypeMetadata(paramType, IsInexact, metadata,
                                          MetadataState::Complete);
    return;
  }
}

bool EmitPolymorphicParameters::isClassPointerSource(unsigned paramIndex) {
  for (auto &source : getSources()) {
    if (source.getKind() == MetadataSource::Kind::ClassPointer &&
        source.getParamIndex() == paramIndex) {
      return true;
    }
  }
  return false;
}

void EmitPolymorphicParameters::injectAdHocDistributedRequirements() {
  // FIXME: We need a better way to recognize that function is
  // a thunk for witness of `remoteCall` requirement.
  if (!Fn.hasLocation())
    return;

  auto loc = Fn.getLocation();

  auto *funcDecl = dyn_cast_or_null<FuncDecl>(loc.getAsDeclContext());
  if (!(funcDecl && funcDecl->isGeneric()))
    return;

  if (!funcDecl->isDistributedWitnessWithAdHocSerializationRequirement())
    return;

  Type genericParam;

  auto sig = funcDecl->getGenericSignature();

  // DistributedActorSystem.remoteCall
  if (funcDecl->isDistributedActorSystemRemoteCall(
          /*isVoidReturn=*/false)) {
    genericParam = funcDecl->getResultInterfaceType();
  } else {
    // DistributedTargetInvocationEncoder.record{Argument, ReturnType}
    // DistributedTargetInvocationDecoder.decodeNextArgument
    // DistributedTargetInvocationResultHandler.onReturn
    genericParam = sig.getInnermostGenericParams().front();
  }

  if (!genericParam)
    return;

  auto protocols = sig->getRequiredProtocols(genericParam);
  if (protocols.empty())
    return;

  auto archetypeTy = getTypeInContext(genericParam->getCanonicalType());
  llvm::Value *metadata = IGF.emitTypeMetadataRef(archetypeTy);

  for (auto *proto : protocols) {
    if (!Lowering::TypeConverter::protocolRequiresWitnessTable(proto))
      continue;

    // Lookup the witness table for this protocol dynamically via
    // swift_conformsToProtocol(<<archetype>>, <<protocol>>)
    auto *witnessTable = IGF.Builder.CreateCall(
        IGM.getConformsToProtocolFunctionPointer(),
        {metadata, IGM.getAddrOfProtocolDescriptor(proto)});

    IGF.setUnscopedLocalTypeData(
        archetypeTy,
        LocalTypeDataKind::forAbstractProtocolWitnessTable(proto),
        witnessTable);
  }
}

namespace {

/// A class for binding type parameters of a generic function.
class BindPolymorphicParameter : public PolymorphicConvention {
  IRGenFunction &IGF;
  CanSILFunctionType &SubstFnType;

public:
  BindPolymorphicParameter(IRGenFunction &IGF, CanSILFunctionType &origFnType,
                           CanSILFunctionType &SubstFnType)
      : PolymorphicConvention(IGF.IGM, origFnType), IGF(IGF),
        SubstFnType(SubstFnType) {}

  void emit(Explosion &in, unsigned paramIndex);

private:
  // Did the convention decide that the parameter at the given index
  // was a class-pointer source?
  bool isClassPointerSource(unsigned paramIndex);
};

} // end anonymous namespace

bool BindPolymorphicParameter::isClassPointerSource(unsigned paramIndex) {
  for (auto &source : getSources()) {
    if (source.getKind() == MetadataSource::Kind::ClassPointer &&
        source.getParamIndex() == paramIndex) {
      return true;
    }
  }
  return false;
}

void BindPolymorphicParameter::emit(Explosion &nativeParam, unsigned paramIndex) {
  if (!isClassPointerSource(paramIndex))
    return;

  assert(nativeParam.size() == 1);
  auto paramType = SubstFnType->getParameters()[paramIndex].getArgumentType(
      IGM.getSILModule(), SubstFnType, IGM.getMaximalTypeExpansionContext());
  llvm::Value *instanceRef = nativeParam.getAll()[0];
  SILType instanceType = SILType::getPrimitiveObjectType(paramType);
  llvm::Value *metadata =
    emitDynamicTypeOfHeapObject(IGF, instanceRef,
                                MetatypeRepresentation::Thick,
                                instanceType,
                                SubstFnType->getInvocationGenericSignature(),
                                /* allow artificial subclasses */ true);
  IGF.bindLocalTypeDataFromTypeMetadata(paramType, IsInexact, metadata,
                                        MetadataState::Complete);
}

void irgen::bindPolymorphicParameter(IRGenFunction &IGF,
                                     CanSILFunctionType &OrigFnType,
                                     CanSILFunctionType &SubstFnType,
                                     Explosion &nativeParam,
                                     unsigned paramIndex) {
  BindPolymorphicParameter(IGF, OrigFnType, SubstFnType)
      .emit(nativeParam, paramIndex);
}

static bool shouldSetName(IRGenModule &IGM, llvm::Value *value, CanType type) {
  // If value names are globally disabled, honor that.
  if (!IGM.EnableValueNames) return false;

  // Suppress value names for values with local archetypes
  if (type->hasLocalArchetype()) return false;

  // If the value already has a name, honor that.
  if (value->hasName()) return false;

  // Only do this for local values.
  return (isa<llvm::Instruction>(value) || isa<llvm::Argument>(value));
}

void irgen::setTypeMetadataName(IRGenModule &IGM, llvm::Value *metadata,
                                CanType type) {
  if (!shouldSetName(IGM, metadata, type)) return;

  SmallString<128> name; {
    llvm::raw_svector_ostream out(name);
    type.print(out);
  }
  metadata->setName(type->getString());
}

void irgen::setProtocolWitnessTableName(IRGenModule &IGM, llvm::Value *wtable,
                                        CanType type,
                                        ProtocolDecl *requirement) {
  if (!shouldSetName(IGM, wtable, type)) return;

  SmallString<128> name; {
    llvm::raw_svector_ostream out(name);
    type.print(out);
    out << '.' << requirement->getNameStr();
  }
  wtable->setName(name);
}

namespace {
  /// A class which lays out a witness table in the abstract.
  class WitnessTableLayout : public SILWitnessVisitor<WitnessTableLayout> {
    SmallVector<WitnessTableEntry, 16> Entries;
    bool requirementSignatureOnly;

  public:
    explicit WitnessTableLayout(ProtocolInfoKind resultKind) {
      switch (resultKind) {
      case ProtocolInfoKind::RequirementSignature:
        requirementSignatureOnly = true;
        break;
      case ProtocolInfoKind::Full:
        requirementSignatureOnly = false;
        break;
      }
    }

    bool shouldVisitRequirementSignatureOnly() {
      return requirementSignatureOnly;
    }

    void addProtocolConformanceDescriptor() { }

    /// The next witness is an out-of-line base protocol.
    void addOutOfLineBaseProtocol(ProtocolDecl *baseProto) {
      Entries.push_back(WitnessTableEntry::forOutOfLineBase(baseProto));
    }

    void addMethod(SILDeclRef func) {
      // If this assert needs to be changed, be sure to also change
      // ProtocolDescriptorBuilder::getRequirementInfo.
      assert((isa<ConstructorDecl>(func.getDecl())
                  ? (func.kind == SILDeclRef::Kind::Allocator)
                  : (func.kind == SILDeclRef::Kind::Func)) &&
             "unexpected kind for protocol witness declaration ref");
      Entries.push_back(WitnessTableEntry::forFunction(func));
    }

    void addPlaceholder(MissingMemberDecl *placeholder) {
      for (auto i : range(placeholder->getNumberOfVTableEntries())) {
        (void)i;
        Entries.push_back(WitnessTableEntry::forPlaceholder());
      }
    }

    void addAssociatedType(AssociatedType requirement) {
      Entries.push_back(WitnessTableEntry::forAssociatedType(requirement));
    }

    void addAssociatedConformance(const AssociatedConformance &req) {
      Entries.push_back(WitnessTableEntry::forAssociatedConformance(req));
    }

    ArrayRef<WitnessTableEntry> getEntries() const { return Entries; }
  };
} // end anonymous namespace

/// Return true if the witness table requires runtime instantiation to
/// handle resiliently-added requirements with default implementations.
///
/// If ignoreGenericity is true, skip the optimization for non-generic
/// conformances are considered non-resilient.
bool IRGenModule::isResilientConformance(
    const NormalProtocolConformance *conformance,
    bool ignoreGenericity
) {
  // If the protocol is not resilient, the conformance is not resilient
  // either.
  bool shouldTreatProtocolNonResilient =
    IRGen.Opts.UseFragileResilientProtocolWitnesses;
  if (!conformance->getProtocol()->isResilient() ||
      shouldTreatProtocolNonResilient)
    return false;

  auto *conformanceModule = conformance->getDeclContext()->getParentModule();

  // If the protocol and the conformance are both in the current module,
  // they're not resilient.
  if (conformanceModule == getSwiftModule() &&
      conformanceModule == conformance->getProtocol()->getParentModule())
    return false;

  // If the protocol WAS from the current module (@_originallyDefinedIn), we
  // consider the conformance non-resilient, because we used to consider it
  // non-resilient before the symbol moved. This is to ensure ABI stability
  // across module boundaries.
  if (conformanceModule == getSwiftModule() &&
      conformanceModule->getName().str() ==
      conformance->getProtocol()->getAlternateModuleName())
    return false;

  // If the protocol and the conformance are in the same module and the
  // conforming type is not generic, they're not resilient.
  //
  // This is an optimization -- a conformance of a non-generic type cannot
  // resiliently become dependent.
  if (!conformance->getDeclContext()->isGenericContext() &&
      conformanceModule == conformance->getProtocol()->getParentModule() &&
      !ignoreGenericity)
    return false;

  // We have a resilient conformance.
  return true;
}

bool IRGenModule::isResilientConformance(const RootProtocolConformance *root,
                                         bool ignoreGenericity) {
  if (auto normal = dyn_cast<NormalProtocolConformance>(root))
    return isResilientConformance(normal, ignoreGenericity);
  // Self-conformances never require this.
  return false;
}

/// Whether this protocol conformance has a dependent type witness.
static bool hasDependentTypeWitness(
                                const NormalProtocolConformance *conformance) {
  auto DC = conformance->getDeclContext();
  // If the conforming type isn't dependent, the below check is never true.
  if (!DC->isGenericContext())
    return false;

  // Check whether any of the associated types are dependent.
  if (conformance->forEachTypeWitness(
        [&](AssociatedTypeDecl *requirement, Type type,
            TypeDecl *explicitDecl) -> bool {
          // Skip associated types that don't have witness table entries.
          if (!requirement->getOverriddenDecls().empty())
            return false;

          // RESILIENCE: this could be an opaque conformance
          return type->getCanonicalType()->hasTypeParameter();
       },
       /*useResolver=*/true)) {
    return true;
  }

  return false;
}

static bool isSynthesizedNonUnique(const RootProtocolConformance *conformance) {
  if (auto normal = dyn_cast<NormalProtocolConformance>(conformance))
    return normal->isSynthesizedNonUnique();
  return false;
}

/// Determine whether a protocol can ever have a dependent conformance.
static bool protocolCanHaveDependentConformance(
    ProtocolDecl *proto,
    bool isResilient
) {
  // Objective-C protocols have never been able to have a dependent conformance.
  if (proto->isObjC())
    return false;

  // Prior to Swift 6.0, only Objective-C protocols were never able to have
  // a dependent conformance. This is overly pessimistic when the protocol
  // is a marker protocol (since they don't have requirements), but we must
  // retain backward compatibility with binaries built for earlier deployment
  // targets that concluded that these protocols might involve dependent
  // conformances. Only do this for resilient protocols.
  if (isResilient && proto->isSpecificProtocol(KnownProtocolKind::Sendable)) {
    ASTContext &ctx = proto->getASTContext();
    if (auto runtimeCompatVersion = getSwiftRuntimeCompatibilityVersionForTarget(
            ctx.LangOpts.Target)) {
      if (runtimeCompatVersion < llvm::VersionTuple(6, 0))
        return true;
    }
  }

  return Lowering::TypeConverter::protocolRequiresWitnessTable(proto);
}

static bool isDependentConformance(
              IRGenModule &IGM,
              const RootProtocolConformance *rootConformance,
              bool isResilient,
              llvm::SmallPtrSet<const NormalProtocolConformance *, 4> &visited){
  // Self-conformances are never dependent.
  auto conformance = dyn_cast<NormalProtocolConformance>(rootConformance);
  if (!conformance)
    return false;

  if (IGM.getOptions().LazyInitializeProtocolConformances) {
    const auto *MD = rootConformance->getDeclContext()->getParentModule();
    if (!(MD == IGM.getSwiftModule() || MD->isStaticLibrary()))
      return true;
  }

  // Check whether we've visited this conformance already.  If so,
  // optimistically assume it's fine --- we want the maximal fixed point.
  if (!visited.insert(conformance).second)
    return false;

  // If the conformance is resilient or synthesized, this is always true.
  if (IGM.isResilientConformance(conformance)
      || isSynthesizedNonUnique(conformance))
    return true;

  // Check whether any of the conformances are dependent.
  auto proto = conformance->getProtocol();
  for (const auto &req : proto->getRequirementSignature().getRequirements()) {
    if (req.getKind() != RequirementKind::Conformance)
      continue;

    auto assocProtocol = req.getProtocolDecl();
    if (!protocolCanHaveDependentConformance(
            assocProtocol, isResilient))
      continue;

    auto assocConformance =
      conformance->getAssociatedConformance(req.getFirstType(), assocProtocol);

    // We might be presented with a broken AST.
    if (assocConformance.isInvalid())
      return false;

    if (assocConformance.isAbstract() ||
        isDependentConformance(IGM,
                               assocConformance.getConcrete()
                                 ->getRootConformance(),
                               isResilient,
                               visited))
      return true;
  }

  if (hasDependentTypeWitness(conformance))
    return true;

  // Check if there are any conditional conformances. Other forms of conditional
  // requirements don't exist in the witness table.
  return SILWitnessTable::enumerateWitnessTableConditionalConformances(
    conformance, [](unsigned, CanType, ProtocolDecl *) { return true; });
}

static bool hasConditionalConformances(IRGenModule &IGM,
                                       const RootProtocolConformance *rootConformance,
                                       llvm::SmallPtrSet<const NormalProtocolConformance *, 4> visited) {
  // Self-conformances are never dependent.
  auto conformance = dyn_cast<NormalProtocolConformance>(rootConformance);
  if (!conformance)
    return false;

  // Check whether we've visited this conformance already.  If so,
  // optimistically assume it's fine --- we want the maximal fixed point.
  if (!visited.insert(conformance).second)
    return false;

  // Check whether any of the conformances are dependent.
  auto proto = conformance->getProtocol();
  for (const auto &req : proto->getRequirementSignature().getRequirements()) {
    if (req.getKind() != RequirementKind::Conformance)
      continue;

    auto assocProtocol = req.getProtocolDecl();
    if (assocProtocol->isObjC())
      continue;

    auto assocConformance =
      conformance->getAssociatedConformance(req.getFirstType(), assocProtocol);

    // We might be presented with a broken AST.
    if (assocConformance.isInvalid())
      return false;

    if (assocConformance.isAbstract())
      continue;

    if (hasConditionalConformances(IGM,
                               assocConformance.getConcrete()
                                 ->getRootConformance(),
                               visited))
      return true;
  }

  // Check if there are any conditional conformances. Other forms of conditional
  // requirements don't exist in the witness table.
  return SILWitnessTable::enumerateWitnessTableConditionalConformances(
    conformance, [](unsigned, CanType, ProtocolDecl *) { return true; });
}
static bool hasConditionalConformances(IRGenModule &IGM,
                                       const RootProtocolConformance *conformance) {
  llvm::SmallPtrSet<const NormalProtocolConformance *, 4> visited;
  return hasConditionalConformances(IGM, conformance, visited);
}
/// Is there anything about the given conformance that requires witness
/// tables to be dependently-generated?
bool IRGenModule::isDependentConformance(
    const RootProtocolConformance *conformance) {
  llvm::SmallPtrSet<const NormalProtocolConformance *, 4> visited;
  return ::isDependentConformance(
      *this, conformance,
      isResilientConformance(conformance, /*ignoreGenericity=*/true),
      visited);
}

static llvm::Value *
emitConditionalConformancesBuffer(IRGenFunction &IGF,
                                  const ProtocolConformance *substConformance) {
  auto rootConformance =
    dyn_cast<NormalProtocolConformance>(substConformance->getRootConformance());

  // Not a normal conformance means no conditional requirements means no need
  // for a buffer.
  if (!rootConformance)
    return llvm::UndefValue::get(IGF.IGM.WitnessTablePtrPtrTy);

  // Pointers to the witness tables, in the right order, which will be included
  // in the buffer that gets passed to the witness table accessor.
  llvm::SmallVector<llvm::Value *, 4> tables;

  auto subMap = substConformance->getSubstitutionMap();
  SILWitnessTable::enumerateWitnessTableConditionalConformances(
      rootConformance, [&](unsigned, CanType type, ProtocolDecl *proto) {
        auto substType = type.subst(subMap)->getCanonicalType();
        auto reqConformance = subMap.lookupConformance(type, proto);
        assert(reqConformance && "conditional conformance must be valid");

        tables.push_back(emitWitnessTableRef(IGF, substType, reqConformance));
        return /*finished?*/ false;
      });

  // No conditional requirements means no need for a buffer.
  if (tables.empty()) {
    return llvm::UndefValue::get(IGF.IGM.WitnessTablePtrPtrTy);
  }

  auto buffer = IGF.createAlloca(
      llvm::ArrayType::get(IGF.IGM.WitnessTablePtrTy, tables.size()),
      IGF.IGM.getPointerAlignment(), "conditional.requirement.buffer");
  buffer = IGF.Builder.CreateStructGEP(buffer, 0, Size(0));

  // Write each of the conditional witness tables into the buffer.
  for (auto idx : indices(tables)) {
    auto slot =
        IGF.Builder.CreateConstArrayGEP(buffer, idx, IGF.IGM.getPointerSize());
    auto wtable =
        IGF.Builder.CreateBitCast(tables[idx], IGF.IGM.WitnessTablePtrTy);
    IGF.Builder.CreateStore(wtable, slot);
  }

  return buffer.getAddress();
}

static llvm::Value *emitWitnessTableAccessorCall(
    IRGenFunction &IGF, const ProtocolConformance *conformance,
    llvm::Value **srcMetadataCache) {
  auto conformanceDescriptor =
    IGF.IGM.getAddrOfProtocolConformanceDescriptor(
                                             conformance->getRootConformance());

  // Emit the source metadata if we haven't yet.
  if (!*srcMetadataCache) {
    *srcMetadataCache = IGF.emitAbstractTypeMetadataRef(
      conformance->getType()->getCanonicalType());
  }

  auto conditionalTables =
      emitConditionalConformancesBuffer(IGF, conformance);

  auto call = IGF.IGM.IRGen.Opts.UseRelativeProtocolWitnessTables ?
    IGF.Builder.CreateCall(
      IGF.IGM.getGetWitnessTableRelativeFunctionPointer(),
      {conformanceDescriptor, *srcMetadataCache, conditionalTables}) :
    IGF.Builder.CreateCall(
      IGF.IGM.getGetWitnessTableFunctionPointer(),
      {conformanceDescriptor, *srcMetadataCache, conditionalTables});

  call->setCallingConv(IGF.IGM.DefaultCC);
  call->setDoesNotThrow();

  return call;
}

/// Fetch the lazy access function for the given conformance of the
/// given type.
static llvm::Function *
getWitnessTableLazyAccessFunction(IRGenModule &IGM,
                                  const ProtocolConformance *conformance) {
  auto conformingType = conformance->getType()->getCanonicalType();
  assert(!conformingType->hasArchetype());

  auto rootConformance = conformance->getRootNormalConformance();
  llvm::Function *accessor = IGM.getAddrOfWitnessTableLazyAccessFunction(
      rootConformance, conformingType, ForDefinition);

  // If we're not supposed to define the accessor, or if we already
  // have defined it, just return the pointer.
  if (!accessor->empty())
    return accessor;

  if (IGM.getOptions().optimizeForSize())
    accessor->addFnAttr(llvm::Attribute::NoInline);

  // Okay, define the accessor.
  auto cacheVariable =
      cast<llvm::GlobalVariable>(IGM.getAddrOfWitnessTableLazyCacheVariable(
          rootConformance, conformingType, ForDefinition));
  emitCacheAccessFunction(
      IGM, accessor, cacheVariable, IGM.WitnessTablePtrTy, CacheStrategy::Lazy,
      [&](IRGenFunction &IGF, Explosion &params) {
        llvm::Value *conformingMetadataCache = nullptr;
        return MetadataResponse::forComplete(emitWitnessTableAccessorCall(
            IGF, conformance, &conformingMetadataCache));
      });

  return accessor;
}

static const ProtocolConformance *
mapConformanceIntoContext(const RootProtocolConformance *conf) {
  if (auto *genericEnv = conf->getDeclContext()->getGenericEnvironmentOfContext())
    return conf->subst(genericEnv->getForwardingSubstitutionMap()).getConcrete();
  return conf;
}

WitnessIndex ProtocolInfo::getAssociatedTypeIndex(
                                    IRGenModule &IGM,
                                    AssociatedType assocType) const {
  assert(!IGM.isResilient(assocType.getSourceProtocol(),
                          ResilienceExpansion::Maximal) &&
         "Cannot ask for the associated type index of non-resilient protocol");
  for (auto &witness : getWitnessEntries()) {
    if (witness.matchesAssociatedType(assocType))
      return getNonBaseWitnessIndex(&witness);
  }
  llvm_unreachable("didn't find entry for associated type");
}

static llvm::Constant *
getConstantSignedRelativeProtocolWitnessTable(IRGenModule &IGM,
                                              llvm::Value *table) {
  auto constantTable = cast<llvm::Constant>(table);
  auto &schema = IGM.getOptions().PointerAuth.RelativeProtocolWitnessTable;
  constantTable =
      IGM.getConstantSignedPointer(constantTable, schema, PointerAuthEntity(),
                                   /*storageAddress*/ nullptr);
  return constantTable;
}

namespace {

/// Conformance info for a witness table that can be directly generated.
class DirectConformanceInfo : public ConformanceInfo {
  friend ProtocolInfo;

  const RootProtocolConformance *RootConformance;
public:
  DirectConformanceInfo(const RootProtocolConformance *C)
      : RootConformance(C) {}

  llvm::Value *getTable(IRGenFunction &IGF,
                        llvm::Value **conformingMetadataCache) const override {
    return IGF.IGM.getAddrOfWitnessTable(RootConformance);
  }

  llvm::Constant *tryGetConstantTable(IRGenModule &IGM,
                                      CanType conformingType) const override {
    if (IGM.getOptions().LazyInitializeProtocolConformances) {
      const auto *MD = RootConformance->getDeclContext()->getParentModule();
      // If the protocol conformance is defined in the current module or the
      // module will be statically linked, then we can statically initialize the
      // conformance as we know that the protocol conformance is guaranteed to
      // be present.
      if (!(MD == IGM.getSwiftModule() || MD->isStaticLibrary()))
        return nullptr;
    }
    return IGM.getAddrOfWitnessTable(RootConformance);
  }
};

/// Conformance info for a witness table that is (or may be) dependent.
class AccessorConformanceInfo : public ConformanceInfo {
  friend ProtocolInfo;

  const ProtocolConformance *Conformance;

public:
  AccessorConformanceInfo(const ProtocolConformance *C) : Conformance(C) {}

  llvm::Value *getTable(IRGenFunction &IGF,
                        llvm::Value **typeMetadataCache) const override {
    // If we're looking up a dependent type, we can't cache the result.
    if (Conformance->getType()->hasArchetype() ||
        Conformance->getType()->hasDynamicSelfType()) {
      return emitWitnessTableAccessorCall(IGF, Conformance,
                                          typeMetadataCache);
    }

    // Otherwise, call a lazy-cache function.
    auto accessor =
      getWitnessTableLazyAccessFunction(IGF.IGM, Conformance);
    llvm::CallInst *call =
        IGF.Builder.CreateCall(accessor->getFunctionType(), accessor, {});
    call->setCallingConv(IGF.IGM.DefaultCC);
    call->setDoesNotAccessMemory();
    call->setDoesNotThrow();

    return call;
  }

  llvm::Constant *tryGetConstantTable(IRGenModule &IGM,
                                      CanType conformingType) const override {
    return nullptr;
  }
};

  /// A base class for some code shared between fragile and resilient witness
  /// table layout.
  class WitnessTableBuilderBase {
  protected:
    IRGenModule &IGM;
    SILWitnessTable *SILWT;
    const RootProtocolConformance &Conformance;
    const ProtocolConformance &ConformanceInContext;
    CanType ConcreteType;

    std::optional<FulfillmentMap> Fulfillments;

    WitnessTableBuilderBase(IRGenModule &IGM, SILWitnessTable *SILWT)
        : IGM(IGM), SILWT(SILWT),
          Conformance(*SILWT->getConformance()),
          ConformanceInContext(*mapConformanceIntoContext(SILWT->getConformance())),
          ConcreteType(Conformance.getDeclContext()
                         ->mapTypeIntoContext(Conformance.getType())
                         ->getCanonicalType()) {}

    void defineAssociatedTypeWitnessTableAccessFunction(
                                        AssociatedConformance requirement,
                                        CanType associatedType,
                                        ProtocolConformanceRef conformance);

    llvm::Constant *getAssociatedConformanceWitness(
                                    AssociatedConformance requirement,
                                    CanType associatedType,
                                    ProtocolConformanceRef conformance);

    const FulfillmentMap &getFulfillmentMap() {
      if (Fulfillments) return *Fulfillments;

      Fulfillments.emplace();
      if (ConcreteType->hasArchetype()) {
        struct Callback : FulfillmentMap::InterestingKeysCallback {
          bool isInterestingType(CanType type) const override {
            return isa<ArchetypeType>(type);
          }
          bool hasInterestingType(CanType type) const override {
            return type->hasArchetype();
          }
          bool isInterestingPackExpansion(CanPackExpansionType type) const override {
            return isa<PackArchetypeType>(type.getPatternType());
          }
          bool hasLimitedInterestingConformances(CanType type) const override {
            return false;
          }
          GenericSignature::RequiredProtocols
          getInterestingConformances(CanType type) const override {
            llvm_unreachable("no limits");
          }
          CanType getSuperclassBound(CanType type) const override {
            if (auto superclassTy = cast<ArchetypeType>(type)->getSuperclass())
              return superclassTy->getCanonicalType();
            return CanType();
          }
        } callback;
        Fulfillments->searchTypeMetadata(IGM, ConcreteType, IsExact,
                                         MetadataState::Abstract,
                                         /*sourceIndex*/ 0, MetadataPath(),
                                         callback);
      }
      return *Fulfillments;
    }
  };

  /// A fragile witness table is emitted to look like one in memory, except
  /// possibly with some blank slots which are filled in by an instantiation
  /// function.
  class FragileWitnessTableBuilder : public WitnessTableBuilderBase,
                                     public SILWitnessVisitor<FragileWitnessTableBuilder> {
    ConstantArrayBuilder &Table;
    unsigned TableSize = ~0U; // will get overwritten unconditionally
    SmallVector<std::pair<size_t, const ConformanceInfo *>, 4>
      SpecializedBaseConformances;

    ArrayRef<SILWitnessTable::Entry> SILEntries;
    ArrayRef<SILWitnessTable::ConditionalConformance>
        SILConditionalConformances;

    const ProtocolInfo &PI;

    SmallVector<size_t, 4> ConditionalRequirementPrivateDataIndices;
    bool isRelative;

    void addConditionalConformances() {
      for (auto reqtIndex : indices(SILConditionalConformances)) {
        // We don't actually need to know anything about the specific
        // conformances here, just make sure we get right private data slots.
        ConditionalRequirementPrivateDataIndices.push_back(reqtIndex);
      }
    }

  public:
    FragileWitnessTableBuilder(IRGenModule &IGM, ConstantArrayBuilder &table,
                               SILWitnessTable *SILWT, bool isRelative)
        : WitnessTableBuilderBase(IGM, SILWT), Table(table),
          SILEntries(SILWT->getEntries()),
          SILConditionalConformances(SILWT->getConditionalConformances()),
          PI(IGM.getProtocolInfo(SILWT->getConformance()->getProtocol(),
                                 ProtocolInfoKind::Full)),
          isRelative(isRelative) {}

    /// The number of entries in the witness table.
    unsigned getTableSize() const { return TableSize; }

    /// The top-level entry point.
    void build() {
      addConditionalConformances();
      visitProtocolDecl(Conformance.getProtocol());
      TableSize = Table.size();
    }

    /// Add reference to the protocol conformance descriptor that generated
    /// this table.
    void addProtocolConformanceDescriptor() {
      auto descriptor =
        IGM.getAddrOfProtocolConformanceDescriptor(&Conformance);
      if (isRelative)
        Table.addRelativeAddress(descriptor);
      else
        Table.addBitCast(descriptor, IGM.Int8PtrTy);
    }

    /// A base protocol is witnessed by a pointer to the conformance
    /// of this type to that protocol.
    void addOutOfLineBaseProtocol(ProtocolDecl *baseProto) {
#ifndef NDEBUG
      auto &entry = SILEntries.front();
#endif
      SILEntries = SILEntries.slice(1);

#ifndef NDEBUG
      assert(entry.getKind() == SILWitnessTable::BaseProtocol
             && "sil witness table does not match protocol");
      assert(entry.getBaseProtocolWitness().Requirement == baseProto
             && "sil witness table does not match protocol");
      auto piIndex = PI.getBaseIndex(baseProto);
      assert((size_t)piIndex.getValue() ==
             Table.size() - WitnessTableFirstRequirementOffset &&
             "offset doesn't match ProtocolInfo layout");
#endif

      // TODO: Use the witness entry instead of falling through here.

      // Look for conformance info.
      auto *astConf = ConformanceInContext.getInheritedConformance(baseProto);
      assert(astConf->getType()->isEqual(ConcreteType));
      const ConformanceInfo &conf = IGM.getConformanceInfo(baseProto, astConf);

      // If we can emit the base witness table as a constant, do so.
      llvm::Constant *baseWitness = conf.tryGetConstantTable(IGM, ConcreteType);

      if (baseWitness && isRelative) {
        Table.addRelativeAddress(baseWitness);
        return;
      } else if (baseWitness) {
        Table.addBitCast(baseWitness, IGM.Int8PtrTy);
        return;
      }

      // Otherwise, we'll need to derive it at instantiation time.
      SpecializedBaseConformances.push_back({Table.size(), &conf});

      if (isRelative) {
        Table.addInt32(0);
        return;
      }
      Table.addNullPointer(IGM.Int8PtrTy);
    }

    void addMethod(SILDeclRef requirement) {
      auto &entry = SILEntries.front();
      SILEntries = SILEntries.slice(1);

      bool isAsyncRequirement = requirement.hasAsync();

#ifndef NDEBUG
      assert(entry.getKind() == SILWitnessTable::Method
             && "sil witness table does not match protocol");
      assert(entry.getMethodWitness().Requirement == requirement
             && "sil witness table does not match protocol");
      auto piIndex = PI.getFunctionIndex(requirement);
      assert((size_t)piIndex.getValue() ==
              Table.size() - WitnessTableFirstRequirementOffset &&
             "offset doesn't match ProtocolInfo layout");
#endif

      SILFunction *Func = entry.getMethodWitness().Witness;
      llvm::Constant *witness = nullptr;
      if (Func) {
        assert(Func->isAsync() == isAsyncRequirement);
        if (Func->isAsync()) {
          witness = IGM.getAddrOfAsyncFunctionPointer(Func);
        } else {
          witness = IGM.getAddrOfSILFunction(Func, NotForDefinition);
        }
      } else {
        // The method is removed by dead method elimination.
        // It should be never called. We add a pointer to an error function.
        if (isAsyncRequirement) {
          witness = llvm::ConstantExpr::getBitCast(
              IGM.getDeletedAsyncMethodErrorAsyncFunctionPointer(),
              IGM.FunctionPtrTy);
        } else {
          witness = llvm::ConstantExpr::getBitCast(
              IGM.getDeletedMethodErrorFn(), IGM.FunctionPtrTy);
        }
      }
      witness = llvm::ConstantExpr::getBitCast(witness, IGM.Int8PtrTy);

      if (isRelative) {
        Table.addRelativeAddress(witness);
        return;
      }

      PointerAuthSchema schema =
          isAsyncRequirement
              ? IGM.getOptions().PointerAuth.AsyncProtocolWitnesses
              : IGM.getOptions().PointerAuth.ProtocolWitnesses;
      Table.addSignedPointer(witness, schema, requirement);

      return;
    }

    void addPlaceholder(MissingMemberDecl *placeholder) {
      llvm_unreachable("cannot emit a witness table with placeholders in it");
    }

    void addAssociatedType(AssociatedType requirement) {
      auto &entry = SILEntries.front();
      SILEntries = SILEntries.slice(1);

#ifndef NDEBUG
      assert(entry.getKind() == SILWitnessTable::AssociatedType
             && "sil witness table does not match protocol");
      assert(entry.getAssociatedTypeWitness().Requirement
             == requirement.getAssociation()
             && "sil witness table does not match protocol");
      auto piIndex = PI.getAssociatedTypeIndex(IGM, requirement);
      assert((size_t)piIndex.getValue() ==
             Table.size() - WitnessTableFirstRequirementOffset &&
             "offset doesn't match ProtocolInfo layout");
#else
      (void)entry;
#endif

      auto associate =
          Conformance.getTypeWitness(requirement.getAssociation());
      llvm::Constant *witness =
          IGM.getAssociatedTypeWitness(
            associate,
            Conformance.getDeclContext()->getGenericSignatureOfContext(),
            /*inProtocolContext=*/false);
      witness = llvm::ConstantExpr::getBitCast(witness, IGM.Int8PtrTy);

      if (isRelative) {
        Table.addRelativeAddress(witness);
        return;
      }

      auto &schema = IGM.getOptions().PointerAuth
                        .ProtocolAssociatedTypeAccessFunctions;
      Table.addSignedPointer(witness, schema, requirement);
    }

    void addAssociatedConformance(AssociatedConformance requirement) {
      // FIXME: Add static witness tables for type conformances.

      auto &entry = SILEntries.front();
      (void)entry;
      SILEntries = SILEntries.slice(1);

      auto associate =
        ConformanceInContext.getAssociatedType(
          requirement.getAssociation())->getCanonicalType();

      ProtocolConformanceRef associatedConformance =
        ConformanceInContext.getAssociatedConformance(
          requirement.getAssociation(),
          requirement.getAssociatedRequirement());

#ifndef NDEBUG
      assert(entry.getKind() == SILWitnessTable::AssociatedTypeProtocol
             && "sil witness table does not match protocol");
      auto associatedWitness = entry.getAssociatedTypeProtocolWitness();
      assert(associatedWitness.Requirement == requirement.getAssociation()
             && "sil witness table does not match protocol");
      assert(associatedWitness.Protocol ==
               requirement.getAssociatedRequirement()
             && "sil witness table does not match protocol");
      auto piIndex = PI.getAssociatedConformanceIndex(requirement);
      assert((size_t)piIndex.getValue() ==
              Table.size() - WitnessTableFirstRequirementOffset &&
             "offset doesn't match ProtocolInfo layout");
#endif

      llvm::Constant *witnessEntry =
        getAssociatedConformanceWitness(requirement, associate,
                                        associatedConformance);

      if (isRelative) {
        Table.addRelativeAddress(witnessEntry);
        return;
      }

      auto &schema = IGM.getOptions().PointerAuth
                        .ProtocolAssociatedTypeWitnessTableAccessFunctions;
      Table.addSignedPointer(witnessEntry, schema, requirement);
    }

    /// Build the instantiation function that runs at the end of witness
    /// table specialization.
    llvm::Function *buildInstantiationFunction();
  };

  /// A resilient witness table consists of a list of descriptor/witness pairs,
  /// and a runtime function builds the actual witness table in memory, placing
  /// entries in the correct oder and filling in default implementations as
  /// needed.
  class ResilientWitnessTableBuilder : public WitnessTableBuilderBase {
  public:
    ResilientWitnessTableBuilder(IRGenModule &IGM, SILWitnessTable *SILWT)
        : WitnessTableBuilderBase(IGM, SILWT) {}

    /// Collect the set of resilient witnesses, which will become part of the
    /// protocol conformance descriptor.
    void collectResilientWitnesses(
                        SmallVectorImpl<llvm::Constant *> &resilientWitnesses);
  };
} // end anonymous namespace

llvm::Constant *IRGenModule::getAssociatedTypeWitness(Type type,
                                                      GenericSignature sig,
                                                      bool inProtocolContext) {
  // FIXME: If we can directly reference constant type metadata, do so.

  // Form a reference to the mangled name for this type.
  assert(!type->hasArchetype() && "type cannot contain archetypes");
  auto role = inProtocolContext
    ? MangledTypeRefRole::DefaultAssociatedTypeWitness
    : MangledTypeRefRole::Metadata;
  auto typeRef = getTypeRef(type, sig, role).first;

  // Set the low bit to indicate that this is a mangled name.
  auto witness = llvm::ConstantExpr::getBitCast(typeRef, Int8PtrTy);
  unsigned bit = ProtocolRequirementFlags::AssociatedTypeMangledNameBit;
  auto bitConstant = llvm::ConstantInt::get(IntPtrTy, bit);
  return llvm::ConstantExpr::getInBoundsGetElementPtr(Int8Ty, witness,
                                                      bitConstant);
}

static void buildAssociatedTypeValueName(CanType depAssociatedType,
                                         SmallString<128> &name) {
  if (auto memberType = dyn_cast<DependentMemberType>(depAssociatedType)) {
    buildAssociatedTypeValueName(memberType.getBase(), name);
    name += '.';
    name += memberType->getName().str();
  } else {
    assert(isa<GenericTypeParamType>(depAssociatedType)); // Self
  }
}

llvm::Constant *WitnessTableBuilderBase::getAssociatedConformanceWitness(
                                AssociatedConformance requirement,
                                CanType associatedType,
                                ProtocolConformanceRef conformance) {
  defineAssociatedTypeWitnessTableAccessFunction(requirement, associatedType,
                                                 conformance);
  assert(isa<NormalProtocolConformance>(Conformance) && "has associated type");
  auto conf = cast<NormalProtocolConformance>(&Conformance);
  return IGM.getMangledAssociatedConformance(conf, requirement);
}

void WitnessTableBuilderBase::defineAssociatedTypeWitnessTableAccessFunction(
                                AssociatedConformance requirement,
                                CanType associatedType,
                                ProtocolConformanceRef associatedConformance) {
  bool hasArchetype = associatedType->hasArchetype();
  OpaqueTypeArchetypeType *associatedRootOpaqueType = nullptr;
  if (auto assocArchetype = dyn_cast<ArchetypeType>(associatedType)) {
    associatedRootOpaqueType = dyn_cast<OpaqueTypeArchetypeType>(
                                                     assocArchetype->getRoot());
  }

  assert(isa<NormalProtocolConformance>(Conformance) && "has associated type");

  // Emit an access function.
  llvm::Function *accessor =
    IGM.getAddrOfAssociatedTypeWitnessTableAccessFunction(
                                  cast<NormalProtocolConformance>(&Conformance),
                                                          requirement);

  IRGenFunction IGF(IGM, accessor);
  if (IGM.DebugInfo)
    IGM.DebugInfo->emitArtificialFunction(IGF, accessor);

  if (IGM.getOptions().optimizeForSize())
    accessor->addFnAttr(llvm::Attribute::NoInline);

  Explosion parameters = IGF.collectParameters();

  llvm::Value *associatedTypeMetadata = parameters.claimNext();

  // We use a non-standard name for the type that states the association
  // requirement rather than the concrete type.
  if (IGM.EnableValueNames) {
    SmallString<128> name;
    name += ConcreteType->getString();
    buildAssociatedTypeValueName(requirement.getAssociation(), name);
    associatedTypeMetadata->setName(name);
  }

  llvm::Value *self = parameters.claimNext();
  setTypeMetadataName(IGM, self, ConcreteType);

  Address destTable(parameters.claimNext(), IGM.WitnessTableTy,
                    IGM.getPointerAlignment());
  setProtocolWitnessTableName(IGM, destTable.getAddress(), ConcreteType,
                              Conformance.getProtocol());

  ProtocolDecl *associatedProtocol = requirement.getAssociatedRequirement();

  const ConformanceInfo *conformanceI = nullptr;

  if (associatedConformance.isConcrete()) {
    assert(associatedType->isEqual(associatedConformance.getConcrete()->getType()));

    conformanceI = &IGM.getConformanceInfo(associatedProtocol,
                                           associatedConformance.getConcrete());

    // If we can emit a constant table, do so.
    if (auto constantTable =
          conformanceI->tryGetConstantTable(IGM, associatedType)) {
      constantTable =
          getConstantSignedRelativeProtocolWitnessTable(IGM, constantTable);
      IGF.Builder.CreateRet(constantTable);
      return;
    }
  }

  // If there are no archetypes, return a reference to the table.
  if (!hasArchetype && !associatedRootOpaqueType) {
    auto wtable = conformanceI->getTable(IGF, &associatedTypeMetadata);
    IGF.Builder.CreateRet(wtable);
    return;
  }

  IGF.bindLocalTypeDataFromSelfWitnessTable(
        &Conformance,
        destTable.getAddress(),
        [&](CanType type) {
          return Conformance.getDeclContext()->mapTypeIntoContext(type)
                   ->getCanonicalType();
        });

  // If the witness table is directly fulfillable from the type, do so.
  if (auto fulfillment =
        getFulfillmentMap().getWitnessTable(associatedType,
                                            associatedProtocol)) {
    // We don't know that 'self' is any better than an abstract metadata here.
    auto source = MetadataResponse::forBounded(self, MetadataState::Abstract);

    llvm::Value *wtable =
      fulfillment->Path.followFromTypeMetadata(IGF, ConcreteType, source,
                                               MetadataState::Complete,
                                               /*cache*/ nullptr)
                       .getMetadata();
    IGF.Builder.CreateRet(wtable);
    return;
  }

  // Bind local type data from the metadata arguments.
  IGF.bindLocalTypeDataFromTypeMetadata(associatedType, IsExact,
                                        associatedTypeMetadata,
                                        MetadataState::Abstract);
  IGF.bindLocalTypeDataFromTypeMetadata(ConcreteType, IsExact, self,
                                        MetadataState::Abstract);

  // Find abstract conformances.
  // TODO: provide an API to find the best metadata path to the conformance
  // and decide whether it's expensive enough to be worth caching.
  if (!conformanceI) {
    assert(associatedConformance.isAbstract());
    auto wtable =
      emitArchetypeWitnessTableRef(IGF, cast<ArchetypeType>(associatedType),
                                   associatedConformance.getAbstract());
    IGF.Builder.CreateRet(wtable);
    return;
  }

  // Handle concrete conformances involving archetypes.
  auto wtable = conformanceI->getTable(IGF, &associatedTypeMetadata);
  IGF.Builder.CreateRet(wtable);
}

void ResilientWitnessTableBuilder::collectResilientWitnesses(
                      SmallVectorImpl<llvm::Constant *> &resilientWitnesses) {
  assert(isa<NormalProtocolConformance>(Conformance) &&
         "resilient conformance should always be normal");
  auto &conformance = cast<NormalProtocolConformance>(Conformance);

  assert(resilientWitnesses.empty());
  for (auto &entry : SILWT->getEntries()) {
    // Associated type witness.
    if (entry.getKind() == SILWitnessTable::AssociatedType) {
      // Associated type witness.
      auto assocType = entry.getAssociatedTypeWitness().Requirement;
      auto associate = conformance.getTypeWitness(assocType);

      llvm::Constant *witness =
          IGM.getAssociatedTypeWitness(
            associate,
            conformance.getDeclContext()->getGenericSignatureOfContext(),
            /*inProtocolContext=*/false);
      resilientWitnesses.push_back(witness);
      continue;
    }

    // Associated conformance access function.
    if (entry.getKind() == SILWitnessTable::AssociatedTypeProtocol) {
      const auto &witness = entry.getAssociatedTypeProtocolWitness();

      auto associate =
        ConformanceInContext.getAssociatedType(
          witness.Requirement)->getCanonicalType();

      ProtocolConformanceRef associatedConformance =
        ConformanceInContext.getAssociatedConformance(witness.Requirement,
                                                      witness.Protocol);
      AssociatedConformance requirement(SILWT->getProtocol(),
                                        witness.Requirement,
                                        witness.Protocol);

      llvm::Constant *witnessEntry =
        getAssociatedConformanceWitness(requirement, associate,
                                        associatedConformance);
      resilientWitnesses.push_back(witnessEntry);
      continue;
    }

    // Inherited conformance witnesses.
    if (entry.getKind() == SILWitnessTable::BaseProtocol) {
      const auto &witness = entry.getBaseProtocolWitness();
      auto baseProto = witness.Requirement;
      auto proto = SILWT->getProtocol();
      CanType selfType = proto->getSelfInterfaceType()->getCanonicalType();
      AssociatedConformance requirement(proto, selfType, baseProto);
      ProtocolConformanceRef inheritedConformance =
        ConformanceInContext.getAssociatedConformance(selfType, baseProto);
      llvm::Constant *witnessEntry =
        getAssociatedConformanceWitness(requirement, ConcreteType,
                                        inheritedConformance);
      resilientWitnesses.push_back(witnessEntry);
      continue;
    }

    if (entry.getKind() != SILWitnessTable::Method)
      continue;

    SILFunction *Func = entry.getMethodWitness().Witness;
    llvm::Constant *witness;
    if (Func) {
      if (Func->isAsync())
        witness = IGM.getAddrOfAsyncFunctionPointer(Func);
      else
        witness = IGM.getAddrOfSILFunction(Func, NotForDefinition);
    } else {
      // The method is removed by dead method elimination.
      // It should be never called. We add a null pointer.
      witness = nullptr;
    }
    resilientWitnesses.push_back(witness);
  }
}

llvm::Function *FragileWitnessTableBuilder::buildInstantiationFunction() {
  // We need an instantiation function if any base conformance
  // is non-dependent.
  if (SpecializedBaseConformances.empty())
    return nullptr;

  assert(isa<NormalProtocolConformance>(Conformance) &&
         "self-conformance requiring instantiation function?");

  llvm::Function *fn =
    IGM.getAddrOfGenericWitnessTableInstantiationFunction(
          cast<NormalProtocolConformance>(&Conformance));
  IRGenFunction IGF(IGM, fn);
  if (IGM.DebugInfo)
    IGM.DebugInfo->emitArtificialFunction(IGF, fn);

  auto PointerAlignment = IGM.getPointerAlignment();
  auto PointerSize = IGM.getPointerSize();

  // Break out the parameters.
  Explosion params = IGF.collectParameters();
  Address wtable(params.claimNext(), IGM.WitnessTableTy, PointerAlignment);
  llvm::Value *metadata = params.claimNext();
  IGF.bindLocalTypeDataFromTypeMetadata(ConcreteType, IsExact, metadata,
                                        MetadataState::Complete);
  llvm::Value *instantiationArgs = params.claimNext();
  Address conditionalTables(
      IGF.Builder.CreateBitCast(instantiationArgs,
                                IGF.IGM.WitnessTablePtrPtrTy),
      IGM.WitnessTablePtrTy, PointerAlignment);

  // Register local type data for the conditional conformance witness tables.
  for (auto idx : indices(ConditionalRequirementPrivateDataIndices)) {
    Address conditionalTablePtr =
        IGF.Builder.CreateConstArrayGEP(conditionalTables, idx, PointerSize);
    auto conditionalTable = IGF.Builder.CreateLoad(conditionalTablePtr);

    const auto &condConformance = SILConditionalConformances[idx];
    CanType reqTypeInContext =
      Conformance.getDeclContext()
        ->mapTypeIntoContext(condConformance.Requirement)
        ->getCanonicalType();
    if (auto archetype = dyn_cast<ArchetypeType>(reqTypeInContext)) {
      auto condProto = condConformance.Conformance.getRequirement();
      IGF.setUnscopedLocalTypeData(
             archetype,
             LocalTypeDataKind::forAbstractProtocolWitnessTable(condProto),
             conditionalTable);
    }
  }

  // Initialize all the specialized base conformances.
  for (auto &base : SpecializedBaseConformances) {
    // Ask the ConformanceInfo to emit the wtable.
    llvm::Value *baseWTable =
      base.second->getTable(IGF, &metadata);

    baseWTable = IGF.Builder.CreateBitCast(baseWTable, IGM.Int8PtrTy);

    // Store that to the appropriate slot in the new witness table.
    Address slot =
        IGF.Builder.CreateConstArrayGEP(wtable, base.first, PointerSize);
    IGF.Builder.CreateStore(baseWTable, slot);
  }


  IGF.Builder.CreateRetVoid();

  return fn;
}

/// Produce a reference for the conforming entity of a protocol conformance
/// descriptor, which is usually the conforming concrete type.
static TypeEntityReference getConformingEntityReference(
    IRGenModule &IGM, const RootProtocolConformance *conformance) {
  // This is a conformance of a protocol to another protocol. Module it as
  // an extension.
  if (isa<NormalProtocolConformance>(conformance) &&
      cast<NormalProtocolConformance>(conformance)->isConformanceOfProtocol()) {
    auto ext = cast<ExtensionDecl>(conformance->getDeclContext());
    auto linkEntity = LinkEntity::forExtensionDescriptor(ext);
    IGM.IRGen.noteUseOfExtensionDescriptor(ext);
    return IGM.getContextDescriptorEntityReference(linkEntity);
  }

  return IGM.getTypeEntityReference(
             conformance->getDeclContext()->getSelfNominalTypeDecl());
}

namespace {
  /// Builds a protocol conformance descriptor.
  class ProtocolConformanceDescriptorBuilder {
    IRGenModule &IGM;
    ConstantStructBuilder &B;
    const RootProtocolConformance *Conformance;
    SILWitnessTable *SILWT;
    ConformanceDescription Description;
    ConformanceFlags Flags;

    using PlaceholderPosition =
      ConstantAggregateBuilderBase::PlaceholderPosition;
    std::optional<PlaceholderPosition> FlagsPP;

  public:
    ProtocolConformanceDescriptorBuilder(
                                 IRGenModule &IGM,
                                 ConstantStructBuilder &B,
                                 const ConformanceDescription &description)
      : IGM(IGM), B(B), Conformance(description.conformance),
        SILWT(description.wtable), Description(description) { }

    void layout() {
      addProtocol();
      addConformingType();
      addWitnessTable();
      addFlags();
      addContext();
      addConditionalRequirements();
      addResilientWitnesses();
      addGenericWitnessTable();

      // We fill the flags last, since we continue filling them in
      // after the call to addFlags() deposits the placeholder.
      B.fillPlaceholderWithInt(*FlagsPP, IGM.Int32Ty,
                               Flags.getIntValue());

      B.suggestType(IGM.ProtocolConformanceDescriptorTy);
    }

    void addProtocol() {
      // Relative reference to the protocol descriptor.
      auto protocol = Conformance->getProtocol();
      auto descriptorRef = IGM.getAddrOfLLVMVariableOrGOTEquivalent(
                                   LinkEntity::forProtocolDescriptor(protocol));
      B.addRelativeAddress(descriptorRef);
    }

    void addConformingType() {
      // Add a relative reference to the type, with the type reference
      // kind stored in the flags.
      auto ref = getConformingEntityReference(IGM, Conformance);
      B.addRelativeAddress(ref.getValue());
      Flags = Flags.withTypeReferenceKind(ref.getKind());
    }

    void addWitnessTable() {
      // Relative reference to the witness table.
      B.addRelativeAddressOrNull(Description.pattern);
    }

    void addFlags() {
      // Miscellaneous flags.
      if (auto conf = dyn_cast<NormalProtocolConformance>(Conformance)) {
        Flags = Flags.withIsRetroactive(conf->isRetroactive());
        Flags = Flags.withIsSynthesizedNonUnique(conf->isSynthesizedNonUnique());
        Flags = Flags.withIsConformanceOfProtocol(conf->isConformanceOfProtocol());
      } else {
        Flags = Flags.withIsRetroactive(false)
                     .withIsSynthesizedNonUnique(false);
      }

      // Add a placeholder for the flags.
      FlagsPP = B.addPlaceholderWithSize(IGM.Int32Ty);
    }

    void addContext() {
      auto normal = dyn_cast<NormalProtocolConformance>(Conformance);
      if (!normal || !normal->isRetroactive())
        return;

      auto moduleContext =
        normal->getDeclContext()->getModuleScopeContext();
      ConstantReference moduleContextRef =
        IGM.getAddrOfParentContextDescriptor(moduleContext,
                                             /*fromAnonymousContext=*/false);
      B.addRelativeAddress(moduleContextRef);
    }

    void addConditionalRequirements() {
      auto normal = dyn_cast<NormalProtocolConformance>(Conformance);
      if (!normal)
        return;

      // Compute the inverse requirements from the generic signature where the
      // conformance occurs.
      SmallVector<Requirement, 2> condReqs;
      SmallVector<InverseRequirement, 2> inverses;
      if (auto genericSig =
              normal->getDeclContext()->getGenericSignatureOfContext()) {
        genericSig->getRequirementsWithInverses(condReqs, inverses);
      }
      condReqs.clear();

      for (auto condReq : normal->getConditionalRequirements()) {
        // We don't need to collect conditional requirements for invertible
        // protocol requirements here, since they are encoded in the inverse
        // list above.
        if (!condReq.isInvertibleProtocolRequirement()) {
          condReqs.push_back(condReq);
        }
      }
      if (condReqs.empty()) {
        // For a protocol P that conforms to another protocol, introduce a
        // conditional requirement for that P's Self: P. This aligns with
        // SILWitnessTable::enumerateWitnessTableConditionalConformances().
        if (auto selfProto = normal->getDeclContext()->getSelfProtocolDecl()) {
          auto selfType = selfProto->getSelfInterfaceType()->getCanonicalType();
          condReqs.emplace_back(RequirementKind::Conformance, selfType,
                                   selfProto->getDeclaredInterfaceType());
        }

        if (condReqs.empty() && inverses.empty())
          return;
      }

      auto nominal = normal->getDeclContext()->getSelfNominalTypeDecl();
      auto sig = nominal->getGenericSignatureOfContext();
      auto metadata = irgen::addGenericRequirements(
          IGM, B, sig, condReqs, inverses);

      Flags = Flags.withNumConditionalRequirements(metadata.NumRequirements);
      Flags = Flags.withNumConditionalPackDescriptors(
          metadata.GenericPackArguments.size());

      // Collect the shape classes from the nominal type's generic signature.
      sig->forEachParam([&](GenericTypeParamType *param, bool canonical) {
        if (canonical && param->isParameterPack()) {
          auto reducedShape = sig->getReducedShape(param)->getCanonicalType();
          if (reducedShape->isEqual(param))
            metadata.ShapeClasses.push_back(reducedShape);
        }
      });

      irgen::addGenericPackShapeDescriptors(
          IGM, B, metadata.ShapeClasses,
          metadata.GenericPackArguments);
    }

    void addResilientWitnesses() {
      if (Description.resilientWitnesses.empty())
        return;
      assert(!IGM.IRGen.Opts.UseFragileResilientProtocolWitnesses);

      Flags = Flags.withHasResilientWitnesses(true);

      // TargetResilientWitnessesHeader
      ArrayRef<llvm::Constant *> witnesses = Description.resilientWitnesses;
      B.addInt32(witnesses.size());
      for (const auto &entry : SILWT->getEntries()) {
        // Add the requirement descriptor.
        if (entry.getKind() == SILWitnessTable::AssociatedType) {
          // Associated type descriptor.
          auto assocType = entry.getAssociatedTypeWitness().Requirement;
          auto assocTypeDescriptor =
            IGM.getAddrOfLLVMVariableOrGOTEquivalent(
              LinkEntity::forAssociatedTypeDescriptor(assocType));
          B.addRelativeAddress(assocTypeDescriptor);
        } else if (entry.getKind() == SILWitnessTable::AssociatedTypeProtocol) {
          // Associated conformance descriptor.
          const auto &witness = entry.getAssociatedTypeProtocolWitness();

          AssociatedConformance requirement(SILWT->getProtocol(),
                                            witness.Requirement,
                                            witness.Protocol);
          auto assocConformanceDescriptor =
            IGM.getAddrOfLLVMVariableOrGOTEquivalent(
              LinkEntity::forAssociatedConformanceDescriptor(requirement));
          B.addRelativeAddress(assocConformanceDescriptor);
        } else if (entry.getKind() == SILWitnessTable::BaseProtocol) {
          // Associated conformance descriptor for a base protocol.
          const auto &witness = entry.getBaseProtocolWitness();
          auto proto = SILWT->getProtocol();
          BaseConformance requirement(proto, witness.Requirement);
          auto baseConformanceDescriptor =
            IGM.getAddrOfLLVMVariableOrGOTEquivalent(
              LinkEntity::forBaseConformanceDescriptor(requirement));
          B.addRelativeAddress(baseConformanceDescriptor);
        } else if (entry.getKind() == SILWitnessTable::Method) {
          // Method descriptor.
          auto declRef = entry.getMethodWitness().Requirement;
          auto requirement =
            IGM.getAddrOfLLVMVariableOrGOTEquivalent(
              LinkEntity::forMethodDescriptor(declRef));
          B.addRelativeAddress(requirement);
        } else {
          // Not part of the resilient witness table.
          continue;
        }

        // Add the witness.
        llvm::Constant *witness = witnesses.front();
        if (auto *fn = llvm::dyn_cast<llvm::Function>(witness)) {
          B.addCompactFunctionReference(fn);
        } else {
          B.addRelativeAddress(witness);
        }
        witnesses = witnesses.drop_front();
      }
      assert(witnesses.empty() && "Wrong # of resilient witnesses");
    }

    void addGenericWitnessTable() {
      if (!Description.requiresSpecialization)
        return;

      Flags = Flags.withHasGenericWitnessTable(true);

      // WitnessTableSizeInWords
      B.addInt(IGM.Int16Ty, Description.witnessTableSize);
      // WitnessTablePrivateSizeInWordsAndRequiresInstantiation
      B.addInt(IGM.Int16Ty,
               (Description.witnessTablePrivateSize << 1) |
                Description.requiresSpecialization);
      // Instantiation function
      B.addCompactFunctionReferenceOrNull(Description.instantiationFn);

      // Private data
      if (IGM.IRGen.Opts.NoPreallocatedInstantiationCaches) {
        B.addInt32(0);
      } else {
        auto privateDataTy =
          llvm::ArrayType::get(IGM.Int8PtrTy,
                               swift::NumGenericMetadataPrivateDataWords);
        auto privateDataInit = llvm::Constant::getNullValue(privateDataTy);
        
        IRGenMangler mangler;
        auto symbolName =
          mangler.mangleProtocolConformanceInstantiationCache(Conformance);
        
        auto privateData =
          new llvm::GlobalVariable(IGM.Module, privateDataTy,
                                   /*constant*/ false,
                                   llvm::GlobalVariable::InternalLinkage,
                                   privateDataInit, symbolName);
        B.addRelativeAddress(privateData);
      }
    }
  };
}

void IRGenModule::emitProtocolConformance(
                                const ConformanceDescription &record) {
  auto conformance = record.conformance;

  // Emit additional metadata to be used by reflection.
  emitAssociatedTypeMetadataRecord(conformance);

  // Form the protocol conformance descriptor.
  ConstantInitBuilder initBuilder(*this);
  auto init = initBuilder.beginStruct();
  ProtocolConformanceDescriptorBuilder builder(*this, init, record);
  builder.layout();

  auto var =
    cast<llvm::GlobalVariable>(
          getAddrOfProtocolConformanceDescriptor(conformance,
                                                 init.finishAndCreateFuture()));
  var->setConstant(true);
  setTrueConstGlobal(var);
}

void IRGenerator::ensureRelativeSymbolCollocation(SILWitnessTable &wt) {
  if (!CurrentIGM)
    return;

  // Only resilient conformances use relative pointers for witness methods.
  if (wt.isDeclaration() || isAvailableExternally(wt.getLinkage()) ||
      !CurrentIGM->isResilientConformance(wt.getConformance()))
    return;

  for (auto &entry : wt.getEntries()) {
    if (entry.getKind() != SILWitnessTable::Method)
      continue;
    auto *witness = entry.getMethodWitness().Witness;
    if (witness)
      forceLocalEmitOfLazyFunction(witness);
  }
}

void IRGenerator::ensureRelativeSymbolCollocation(SILDefaultWitnessTable &wt) {
  if (!CurrentIGM)
    return;

  for (auto &entry : wt.getEntries()) {
    if (entry.getKind() != SILWitnessTable::Method)
      continue;
    auto *witness = entry.getMethodWitness().Witness;
    if (witness)
      forceLocalEmitOfLazyFunction(witness);
  }
}

/// Do a memoized witness-table layout for a protocol.
const ProtocolInfo &IRGenModule::getProtocolInfo(ProtocolDecl *protocol,
                                                 ProtocolInfoKind kind) {
  // If the protocol is resilient, we cannot know the full witness table layout.
  assert(!isResilient(protocol, ResilienceExpansion::Maximal) ||
         kind == ProtocolInfoKind::RequirementSignature);

  return Types.getProtocolInfo(protocol, kind);
}

/// Do a memoized witness-table layout for a protocol.
const ProtocolInfo &TypeConverter::getProtocolInfo(ProtocolDecl *protocol,
                                                   ProtocolInfoKind kind) {
  // Check whether we've already translated this protocol.
  auto it = Protocols.find(protocol);
  if (it != Protocols.end() && it->getSecond()->getKind() >= kind)
    return *it->getSecond();

  // If not, lay out the protocol's witness table, if it needs one.
  WitnessTableLayout layout(kind);
  if (Lowering::TypeConverter::protocolRequiresWitnessTable(protocol))
    layout.visitProtocolDecl(protocol);

  // Create a ProtocolInfo object from the layout.
  std::unique_ptr<ProtocolInfo> info = ProtocolInfo::create(layout.getEntries(),
                                                            kind);

  // Verify that we haven't generated an incompatible layout.
  if (it != Protocols.end()) {
    ArrayRef<WitnessTableEntry> originalEntries =
        it->second->getWitnessEntries();
    ArrayRef<WitnessTableEntry> newEntries = info->getWitnessEntries();
    assert(newEntries.size() >= originalEntries.size());
    assert(newEntries.take_front(originalEntries.size()) == originalEntries);
    (void)originalEntries;
    (void)newEntries;
  }

  // Memoize.
  std::unique_ptr<const ProtocolInfo> &cachedInfo = Protocols[protocol];
  cachedInfo = std::move(info);

  // Done.
  return *cachedInfo;
}

/// Allocate a new ProtocolInfo.
std::unique_ptr<ProtocolInfo>
ProtocolInfo::create(ArrayRef<WitnessTableEntry> table, ProtocolInfoKind kind) {
  size_t bufferSize = totalSizeToAlloc<WitnessTableEntry>(table.size());
  void *buffer = ::operator new(bufferSize);
  return std::unique_ptr<ProtocolInfo>(new(buffer) ProtocolInfo(table, kind));
}

// Provide a unique home for the ConformanceInfo vtable.
void ConformanceInfo::anchor() {}

/// Find the conformance information for a protocol.
const ConformanceInfo &
IRGenModule::getConformanceInfo(const ProtocolDecl *protocol,
                                const ProtocolConformance *conformance) {
  assert(conformance->getProtocol() == protocol &&
         "conformance is for wrong protocol");

  auto checkCache =
      [this](const ProtocolConformance *conf) -> const ConformanceInfo * {
    // Check whether we've already cached this.
    auto it = Conformances.find(conf);
    if (it != Conformances.end())
      return it->second.get();

    return nullptr;
  };

  if (auto found = checkCache(conformance))
    return *found;

  //  Drill down to the root normal
  auto rootConformance = conformance->getRootConformance();

  const ConformanceInfo *info;
  // If the conformance is dependent in any way, we need to unique it.
  // Under a relative protocol witness table implementation conformances are
  // always direct.
  //
  // FIXME: Both implementations of ConformanceInfo are trivially-destructible,
  // so in theory we could allocate them on a BumpPtrAllocator. But there's not
  // a good one for us to use. (The ASTContext's outlives the IRGenModule in
  // batch mode.)
  if (!IRGen.Opts.UseRelativeProtocolWitnessTables &&
      (isDependentConformance(rootConformance) ||
      // Foreign types need to go through the accessor to unique the witness
      // table.
      isSynthesizedNonUnique(rootConformance))) {
    info = new AccessorConformanceInfo(conformance);
    Conformances.try_emplace(conformance, info);
  } else if(IRGen.Opts.UseRelativeProtocolWitnessTables &&
            hasConditionalConformances(*this, rootConformance)) {
    info = new AccessorConformanceInfo(conformance);
    Conformances.try_emplace(conformance, info);
  } else {
    // Otherwise, we can use a direct-referencing conformance, which can get
    // away with the non-specialized conformance.
    if (auto found = checkCache(rootConformance))
      return *found;

    info = new DirectConformanceInfo(rootConformance);
    Conformances.try_emplace(rootConformance, info);
  }

  return *info;
}

/// Whether the witness table will be constant.
static bool isConstantWitnessTable(SILWitnessTable *wt) {
  for (const auto &entry : wt->getEntries()) {
    switch (entry.getKind()) {
    case SILWitnessTable::Invalid:
    case SILWitnessTable::BaseProtocol:
    case SILWitnessTable::Method:
      continue;

    case SILWitnessTable::AssociatedType:
    case SILWitnessTable::AssociatedTypeProtocol:
      // Associated types and conformances are cached in the witness table.
      // FIXME: If we start emitting constant references to here,
      // we will need to ask the witness table builder for this information.
      return false;
    }
  }

  return true;
}

static void addWTableTypeMetadata(IRGenModule &IGM,
                                  llvm::GlobalVariable *global,
                                  SILWitnessTable *wt) {
  auto conf = wt->getConformance();

  uint64_t minOffset = UINT64_MAX;
  uint64_t maxOffset = 0;
  for (auto entry : wt->getEntries()) {
    if (entry.getKind() != SILWitnessTable::WitnessKind::Method)
      continue;

    auto mw = entry.getMethodWitness();
    auto member = mw.Requirement;

    auto &fnProtoInfo =
        IGM.getProtocolInfo(conf->getProtocol(), ProtocolInfoKind::Full);
    auto index = fnProtoInfo.getFunctionIndex(member).forProtocolWitnessTable();
    auto entrySize = IGM.IRGen.Opts.UseRelativeProtocolWitnessTables ?
      4 : IGM.getPointerSize().getValue();
    auto offset = index.getValue() * entrySize;
    global->addTypeMetadata(offset, typeIdForMethod(IGM, member));

    minOffset = std::min(minOffset, offset);
    maxOffset = std::max(maxOffset, offset);
  }

  if (minOffset == UINT64_MAX)
    return;

  using VCallVisibility = llvm::GlobalObject::VCallVisibility;
  VCallVisibility vis = VCallVisibility::VCallVisibilityPublic;
  auto linkage = stripExternalFromLinkage(wt->getLinkage());
  switch (linkage) {
  case SILLinkage::Private:
    vis = VCallVisibility::VCallVisibilityTranslationUnit;
    break;
  case SILLinkage::Hidden:
  case SILLinkage::Shared:
    vis = VCallVisibility::VCallVisibilityLinkageUnit;
    break;
  case SILLinkage::Public:
  case SILLinkage::PublicExternal:
  case SILLinkage::PublicNonABI:
  case SILLinkage::Package:
  case SILLinkage::PackageExternal:
  case SILLinkage::PackageNonABI:
  case SILLinkage::HiddenExternal:
    if (IGM.getOptions().InternalizeAtLink) {
      vis = VCallVisibility::VCallVisibilityLinkageUnit;
    }
    break;
  }

  auto relptrSize = IGM.DataLayout.getTypeAllocSize(IGM.Int32Ty).getKnownMinValue();
  IGM.setVCallVisibility(global, vis,
                         std::make_pair(minOffset, maxOffset + relptrSize));
}

void IRGenModule::emitSILWitnessTable(SILWitnessTable *wt) {
  if (Context.LangOpts.hasFeature(Feature::Embedded)) {
    return;
  }

  // Don't emit a witness table if it is a declaration.
  if (wt->isDeclaration())
    return;

  // Don't emit a witness table that is available externally.
  // It can end up in having duplicate symbols for generated associated type
  // metadata access functions.
  // Also, it is not a big benefit for LLVM to emit such witness tables.
  if (isAvailableExternally(wt->getLinkage()))
    return;

  // Ensure that relatively-referenced symbols for witness thunks are collocated
  // in the same LLVM module.
  IRGen.ensureRelativeSymbolCollocation(*wt);

  auto conf = wt->getConformance();
  PrettyStackTraceConformance _st("emitting witness table for", conf);

  unsigned tableSize = 0;
  llvm::GlobalVariable *global = nullptr;
  llvm::Function *instantiationFunction = nullptr;
  bool isDependent = isDependentConformance(conf);
  SmallVector<llvm::Constant *, 4> resilientWitnesses;
  bool isResilient = isResilientConformance(conf);
  bool useRelativeProtocolWitnessTable =
    IRGen.Opts.UseRelativeProtocolWitnessTables;
  if (useRelativeProtocolWitnessTable &&
      !conf->getConditionalRequirements().empty()) {
    auto sig = conf->getGenericSignature();
    sig->forEachParam([&](GenericTypeParamType *param, bool canonical) {
                      if (param->isParameterPack()) {
#ifndef NDEBUG
                        wt->dump();
#endif
                        llvm::report_fatal_error("use of relative protcol witness tables not supported");
                      }});
  }
  if (!isResilient) {
    // Build the witness table.
    ConstantInitBuilder builder(*this);
    auto witnessTableEntryTy = useRelativeProtocolWitnessTable ?
      (llvm::Type*)RelativeAddressTy : (llvm::Type*)Int8PtrTy;
    auto wtableContents = builder.beginArray(witnessTableEntryTy);
    FragileWitnessTableBuilder wtableBuilder(*this, wtableContents, wt,
                                             useRelativeProtocolWitnessTable);
    wtableBuilder.build();

    // Produce the initializer value.
    auto initializer = wtableContents.finishAndCreateFuture();

    global = cast<llvm::GlobalVariable>(
      (isDependent && conf->getDeclContext()->isGenericContext() &&
       !useRelativeProtocolWitnessTable)
        ? getAddrOfWitnessTablePattern(cast<NormalProtocolConformance>(conf),
                                       initializer)
        : getAddrOfWitnessTable(conf, initializer));
    // Eelative protocol witness tables are always constant. They don't cache
    // results in the table.
    global->setConstant(useRelativeProtocolWitnessTable ||
                        isConstantWitnessTable(wt));
    global->setAlignment(
        llvm::MaybeAlign(getWitnessTableAlignment().getValue()));

    if (getOptions().WitnessMethodElimination) {
      addWTableTypeMetadata(*this, global, wt);
    }

    tableSize = wtableBuilder.getTableSize();
    instantiationFunction = wtableBuilder.buildInstantiationFunction();
  } else {
    if (IRGen.Opts.UseRelativeProtocolWitnessTables)
      llvm::report_fatal_error("resilient relative protocol witness tables are not supported");

    // Build the witness table.
    ResilientWitnessTableBuilder wtableBuilder(*this, wt);

    // Collect the resilient witnesses to go into the conformance descriptor.
    wtableBuilder.collectResilientWitnesses(resilientWitnesses);
  }

  // Collect the information that will go into the protocol conformance
  // descriptor.
  unsigned tablePrivateSize = wt->getConditionalConformances().size();
  ConformanceDescription description(conf, wt, global, tableSize,
                                     tablePrivateSize, isDependent);

  // Build the instantiation function, we if need one.
  description.instantiationFn = instantiationFunction;
  description.resilientWitnesses = std::move(resilientWitnesses);

  // Record this conformance descriptor.
  addProtocolConformance(std::move(description));

  IRGen.noteUseOfTypeContextDescriptor(
      conf->getDeclContext()->getSelfNominalTypeDecl(),
      RequireMetadata);
}

/// True if a function's signature in LLVM carries polymorphic parameters.
/// Generic functions and protocol witnesses carry polymorphic parameters.
bool irgen::hasPolymorphicParameters(CanSILFunctionType ty) {
  switch (ty->getRepresentation()) {
  case SILFunctionTypeRepresentation::Block:
    // Should never be polymorphic.
    assert(!ty->isPolymorphic() && "polymorphic C function?!");
    return false;

  case SILFunctionTypeRepresentation::Thick:
  case SILFunctionTypeRepresentation::Thin:
  case SILFunctionTypeRepresentation::Method:
  case SILFunctionTypeRepresentation::Closure:
  case SILFunctionTypeRepresentation::KeyPathAccessorGetter:
  case SILFunctionTypeRepresentation::KeyPathAccessorSetter:
  case SILFunctionTypeRepresentation::KeyPathAccessorEquals:
  case SILFunctionTypeRepresentation::KeyPathAccessorHash:
    return ty->isPolymorphic();

  case SILFunctionTypeRepresentation::CFunctionPointer:
  case SILFunctionTypeRepresentation::ObjCMethod:
  case SILFunctionTypeRepresentation::CXXMethod:
    // May be polymorphic at the SIL level, but no type metadata is actually
    // passed.
    return false;

  case SILFunctionTypeRepresentation::WitnessMethod:
    // Always carries polymorphic parameters for the Self type.
    return true;
  }

  llvm_unreachable("Not a valid SILFunctionTypeRepresentation.");
}

/// Emit a polymorphic parameters clause, binding all the metadata necessary.
void EmitPolymorphicParameters::emit(EntryPointArgumentEmission &emission,
                                     WitnessMetadata *witnessMetadata,
                                     const GetParameterFn &getParameter) {
  // Collect any early sources and bind local type data from them.
  for (auto &source : getSources()) {
    bindExtraSource(source, emission, witnessMetadata);
  }

  auto subs = Fn.getForwardingSubstitutionMap();

  // Collect any concrete type metadata that's been passed separately.
  enumerateUnfulfilledRequirements([&](GenericRequirement requirement) {
    llvm::Value *value = emission.getNextPolymorphicParameter(requirement);
    bindGenericRequirement(IGF, requirement, value, MetadataState::Complete,
                           subs);
  });

  // Bind all the fulfillments we can from the formal parameters.
  bindParameterSources(getParameter);

  // Inject ad-hoc requirements related to `SerializationRequirement`
  // associated type.
  injectAdHocDistributedRequirements();
}

MetadataResponse
MetadataPath::followFromTypeMetadata(IRGenFunction &IGF,
                                     CanType sourceType,
                                     MetadataResponse source,
                                     DynamicMetadataRequest request,
                                     Map<MetadataResponse> *cache) const {
  LocalTypeDataKey key = {
    sourceType,
    LocalTypeDataKind::forFormalTypeMetadata()
  };
  return follow(IGF, key, source, Path.begin(), Path.end(), request, cache);
}

MetadataResponse
MetadataPath::followFromWitnessTable(IRGenFunction &IGF,
                                     CanType conformingType,
                                     ProtocolConformanceRef conformance,
                                     MetadataResponse source,
                                     DynamicMetadataRequest request,
                                     Map<MetadataResponse> *cache) const {
  LocalTypeDataKey key = {
    conformingType,
    LocalTypeDataKind::forProtocolWitnessTable(conformance)
  };
  return follow(IGF, key, source, Path.begin(), Path.end(), request, cache);
}

/// Follow this metadata path.
///
/// \param sourceKey - A description of the source value.  Not necessarily
///   an appropriate caching key.
/// \param cache - If given, this cache will be used to short-circuit
///   the lookup; otherwise, the global (but dominance-sensitive) cache
///   in the IRGenFunction will be used.  This caching system is somewhat
///   more efficient than what IGF provides, but it's less general, and it
///   should probably be removed.
MetadataResponse MetadataPath::follow(IRGenFunction &IGF,
                                      LocalTypeDataKey sourceKey,
                                      MetadataResponse source,
                                      iterator begin, iterator end,
                                      DynamicMetadataRequest finalRequest,
                                      Map<MetadataResponse> *cache) {
  assert(source && "no source metadata value!");

  // The invariant is that this iterator starts a path from source and
  // that sourceKey is correctly describes it.
  iterator i = begin;

  // Before we begin emitting code to generate the actual path, try to find
  // the latest point in the path that we've cached a value for.

  // If the caller gave us a cache to use, check that.  This lookup is very
  // efficient and doesn't even require us to parse the prefix.
  if (cache) {
    auto result = cache->findPrefix(begin, end);
    if (result.first) {
      source = *result.first;

      // If that was the end, there's no more work to do; don't bother
      // adjusting the source key.
      if (result.second == end)
        return source;

      // Advance the source key past the cached prefix.
      while (i != result.second) {
        Component component = *i++;
        (void) followComponent(IGF, sourceKey, MetadataResponse(), component,
                               MetadataState::Abstract);
      }
    }

  // Otherwise, make a pass over the path looking for available concrete
  // entries in the IGF's local type data cache.
  } else {
    auto skipI = i;
    LocalTypeDataKey skipKey = sourceKey;
    while (skipI != end) {
      Component component = *skipI++;
      (void) followComponent(IGF, skipKey, MetadataResponse(), component,
                             MetadataState::Abstract);

      // Check the cache for a concrete value.  We don't want an abstract
      // cache entry because, if one exists, we'll just end up here again
      // recursively.
      auto skipRequest =
        (skipI == end ? finalRequest : MetadataState::Abstract);
      if (auto skipResponse =
            IGF.tryGetConcreteLocalTypeData(skipKey, skipRequest)) {
        // Advance the baseline information for the source to the current
        // point in the path, then continue the search.
        sourceKey = skipKey;
        source = skipResponse;
        i = skipI;
      }
    }
  }

  // Drill in on the actual source value.
  while (i != end) {
    auto component = *i++;

    auto componentRequest =
      (i == end ? finalRequest : MetadataState::Abstract);
    source = followComponent(IGF, sourceKey, source,
                             component, componentRequest);

    // If we have a cache, remember this in the cache at the next position.
    if (cache) {
      cache->insertNew(begin, i, source);

    // Otherwise, insert it into the global cache (at the updated source key).
    } else {
      IGF.setScopedLocalTypeData(sourceKey, source);
    }
  }

  return source;
}

llvm::Value *IRGenFunction::optionallyLoadFromConditionalProtocolWitnessTable(
  llvm::Value *wtable) {
  if (!IGM.IRGen.Opts.UseRelativeProtocolWitnessTables)
    return wtable;

  auto *ptrVal = Builder.CreatePtrToInt(wtable, IGM.IntPtrTy);
  auto *one = llvm::ConstantInt::get(IGM.IntPtrTy, 1);
  auto *isCond = Builder.CreateAnd(ptrVal, one);
  auto *isCondBB = llvm::BasicBlock::Create(IGM.getLLVMContext());
  auto *endBB = llvm::BasicBlock::Create(IGM.getLLVMContext());
  auto *origBB = Builder.GetInsertBlock();
  isCond = Builder.CreateICmpEQ(isCond, one);
  Builder.CreateCondBr(isCond, isCondBB, endBB);

  Builder.emitBlock(isCondBB);
  ConditionalDominanceScope condition (*this);
  auto *mask = Builder.CreateNot(one);
  auto *wtableAddr = Builder.CreateAnd(ptrVal, mask);
  wtableAddr = Builder.CreateIntToPtr(wtableAddr, IGM.WitnessTablePtrPtrTy);
  auto *wtableDeref = Builder.CreateLoad(Address(wtableAddr,
                                                 IGM.WitnessTablePtrTy,
                                                 IGM.getPointerAlignment()));
  Builder.CreateBr(endBB);

  Builder.emitBlock(endBB);
  auto *phi = Builder.CreatePHI(wtable->getType(), 2);
  phi->addIncoming(wtable, origBB);
  phi->addIncoming(wtableDeref, isCondBB);
  if (auto &schema = getOptions().PointerAuth.RelativeProtocolWitnessTable) {
    auto info = PointerAuthInfo::emit(*this, schema, nullptr,
                                      PointerAuthEntity());
    return emitPointerAuthAuth(*this, phi, info);
  }
  return phi;
}

llvm::Value *irgen::loadParentProtocolWitnessTable(IRGenFunction &IGF,
                                            llvm::Value *wtable,
                                            WitnessIndex index) {
  auto &IGM = IGF.IGM;
  if (!IGM.IRGen.Opts.UseRelativeProtocolWitnessTables) {
    auto baseWTable =
      emitInvariantLoadOfOpaqueWitness(IGF,/*isProtocolWitness*/true, wtable,
                                       index);
    return baseWTable;
  }

  llvm::SmallString<40> fnName;
  llvm::raw_svector_ostream(fnName)
    << "__swift_relative_protocol_witness_table_parent_"
    << index.getValue();

  auto helperFn = cast<llvm::Function>(IGM.getOrCreateHelperFunction(
    fnName, IGM.WitnessTablePtrTy, {IGM.WitnessTablePtrTy},
    [&](IRGenFunction &subIGF) {

  auto it = subIGF.CurFn->arg_begin();
  llvm::Value *wtable =  &*it;
  auto &Builder = subIGF.Builder;
  auto *ptrVal = Builder.CreatePtrToInt(wtable, IGM.IntPtrTy);
  auto *one = llvm::ConstantInt::get(IGM.IntPtrTy, 1);
  auto *isCond = Builder.CreateAnd(ptrVal, one);
  auto *isNotCondBB = llvm::BasicBlock::Create(IGM.getLLVMContext());
  auto *isCondBB = llvm::BasicBlock::Create(IGM.getLLVMContext());
  auto *endBB = llvm::BasicBlock::Create(IGM.getLLVMContext());
  isCond = Builder.CreateICmpEQ(isCond, one);
  Builder.CreateCondBr(isCond, isCondBB, isNotCondBB);

  Builder.emitBlock(isCondBB);
  auto *mask = Builder.CreateNot(one);
  auto *wtableAddr = Builder.CreateAnd(ptrVal, mask);
  wtableAddr = Builder.CreateIntToPtr(wtableAddr, IGM.WitnessTablePtrTy);
  auto addr = slotForLoadOfOpaqueWitness(subIGF, wtableAddr, index,
                                         false /*isRelative*/);
  llvm::Value *baseWTable = Builder.CreateLoad(addr);
  baseWTable = subIGF.Builder.CreateBitCast(baseWTable, IGM.WitnessTablePtrTy);
  Builder.CreateBr(endBB);

  Builder.emitBlock(isNotCondBB);
  if (auto &schema = subIGF.getOptions().PointerAuth.RelativeProtocolWitnessTable) {
    auto info = PointerAuthInfo::emit(subIGF, schema, nullptr,
                                      PointerAuthEntity());
    wtable = emitPointerAuthAuth(subIGF, wtable, info);
  }
  auto baseWTable2 =
      emitInvariantLoadOfOpaqueWitness(subIGF,/*isProtocolWitness*/true, wtable,
                                       index);
  baseWTable2 = subIGF.Builder.CreateBitCast(baseWTable2,
                                          subIGF.IGM.WitnessTablePtrTy);
  if (auto &schema = subIGF.getOptions().PointerAuth.RelativeProtocolWitnessTable) {
    auto info = PointerAuthInfo::emit(subIGF, schema, nullptr,
                                      PointerAuthEntity());
    baseWTable2 = emitPointerAuthSign(subIGF, baseWTable2, info);

    baseWTable2 = subIGF.Builder.CreateBitCast(baseWTable2,
                                            IGM.WitnessTablePtrTy);
  }

  Builder.CreateBr(endBB);

  Builder.emitBlock(endBB);
  auto *phi = Builder.CreatePHI(wtable->getType(), 2);
  phi->addIncoming(baseWTable, isCondBB);
  phi->addIncoming(baseWTable2, isNotCondBB);
  Builder.CreateRet(phi);

  }, true /*noinline*/));

  auto *call = IGF.Builder.CreateCallWithoutDbgLoc(
    helperFn->getFunctionType(), helperFn, {wtable});
  call->setCallingConv(IGF.IGM.DefaultCC);
  call->setDoesNotThrow();
  return call;
}

llvm::Value *irgen::loadConditionalConformance(IRGenFunction &IGF,
                                               llvm::Value *wtable,
                                               WitnessIndex index) {

  auto &IGM = IGF.IGM;
  if (!IGM.IRGen.Opts.UseRelativeProtocolWitnessTables) {
    return emitInvariantLoadOfOpaqueWitness(IGF, /*isProtocolWitness*/true,
                                            wtable, index);
  }

  auto &Builder = IGF.Builder;
  auto *one = llvm::ConstantInt::get(IGM.IntPtrTy, 1);
  auto *mask = Builder.CreateNot(one);
  auto *ptrVal = Builder.CreatePtrToInt(wtable, IGM.IntPtrTy);
  auto *wtableAddr = Builder.CreateAnd(ptrVal, mask);
  wtableAddr = Builder.CreateIntToPtr(wtableAddr, IGM.WitnessTablePtrTy);
  auto addr = slotForLoadOfOpaqueWitness(IGF, wtableAddr, index,
                                         false /*isRelative*/);
  return Builder.CreateLoad(addr);
}

/// Call an associated-type witness table access function.  Does not do
/// any caching or drill down to implied protocols.
static llvm::Value *
emitAssociatedTypeWitnessTableRef(IRGenFunction &IGF,
                                  llvm::Value *parentMetadata,
                                  llvm::Value *wtable,
                                  AssociatedConformance conformance,
                                  llvm::Value *associatedTypeMetadata) {
  auto sourceProtocol = conformance.getSourceProtocol();
  auto assocConformanceDescriptor =
    IGF.IGM.getAddrOfAssociatedConformanceDescriptor(conformance);
  auto baseDescriptor =
    IGF.IGM.getAddrOfProtocolRequirementsBaseDescriptor(sourceProtocol);

  auto call = IGF.IGM.IRGen.Opts.UseRelativeProtocolWitnessTables ?
    IGF.Builder.CreateCall(
      IGF.IGM.getGetAssociatedConformanceWitnessRelativeFunctionPointer(),
      {wtable, parentMetadata, associatedTypeMetadata, baseDescriptor,
       assocConformanceDescriptor}) :
    IGF.Builder.CreateCall(
      IGF.IGM.getGetAssociatedConformanceWitnessFunctionPointer(),
      {wtable, parentMetadata, associatedTypeMetadata, baseDescriptor,
       assocConformanceDescriptor});
  call->setDoesNotThrow();
  call->setDoesNotAccessMemory();
  return call;
}

/// Drill down on a single stage of component.
///
/// sourceType and sourceDecl will be adjusted to refer to the new
/// component.  Source can be null, in which case this will be the only
/// thing done.
MetadataResponse MetadataPath::followComponent(IRGenFunction &IGF,
                                               LocalTypeDataKey &sourceKey,
                                               MetadataResponse source,
                                               Component component,
                                               DynamicMetadataRequest request) {
  switch (component.getKind()) {
  case Component::Kind::NominalTypeArgument:
  case Component::Kind::NominalTypeArgumentConformance:
  case Component::Kind::NominalTypeArgumentShape: {
    assert(sourceKey.Kind == LocalTypeDataKind::forFormalTypeMetadata());
    auto type = sourceKey.Type;
    if (auto archetypeTy = dyn_cast<ArchetypeType>(type))
      type = archetypeTy->getSuperclass()->getCanonicalType();
    auto *nominal = type.getAnyNominal();
    auto reqtIndex = component.getPrimaryIndex();

    GenericTypeRequirements requirements(IGF.IGM, nominal);
    auto &requirement = requirements.getRequirements()[reqtIndex];

    auto module = IGF.getSwiftModule();
    auto subs = sourceKey.Type->getContextSubstitutionMap(module, nominal);
    auto sub = requirement.getTypeParameter().subst(subs)->getCanonicalType();

    // In either case, we need to change the type.
    sourceKey.Type = sub;

    // If this is a type argument, we've fully updated sourceKey.
    if (component.getKind() == Component::Kind::NominalTypeArgument) {
      assert(requirement.isAnyMetadata() && "index mismatch!");

      if (!source) return MetadataResponse();

      auto sourceMetadata = source.getMetadata();
      auto *argMetadata = requirement.isMetadataPack()
          ? emitArgumentMetadataPackRef(IGF, nominal, requirements, reqtIndex,
                                        sourceMetadata)
          : emitArgumentMetadataRef(IGF, nominal, requirements, reqtIndex,
                                    sourceMetadata);
      setTypeMetadataName(IGF.IGM, argMetadata, sourceKey.Type);

      // Assume that the argument metadata is complete if the metadata is.
      auto argState = getPresumedMetadataStateForTypeArgument(
                                           source.getStaticLowerBoundOnState());
      auto response = MetadataResponse::forBounded(argMetadata, argState);

      // Do a dynamic check if necessary to satisfy the request.
      assert((requirement.isMetadata() || request.isSatisfiedBy(response)) &&
             "checkTypeMetadataState for packs is currently unimplemented");
      return emitCheckTypeMetadataState(IGF, request, response);

    // If this is a shape class, load the value.
    } else if (component.getKind() == Component::Kind::NominalTypeArgumentShape) {
      assert(requirement.isShape() && "index mismatch!");

      sourceKey.Kind = LocalTypeDataKind::forPackShapeExpression();

      if (!source) return MetadataResponse();

      auto sourceMetadata = source.getMetadata();
      auto shape = emitArgumentPackShapeRef(IGF, nominal,
                                            requirements, reqtIndex,
                                            sourceMetadata);

      return MetadataResponse::forComplete(shape);

    // Otherwise, we need to switch sourceKey.Kind to the appropriate
    // conformance kind.
    } else if (component.getKind() == Component::Kind::NominalTypeArgumentConformance) {
      assert(requirement.isAnyWitnessTable() && "index mismatch!");
      auto conformance = subs.lookupConformance(requirement.getTypeParameter(),
                                                requirement.getProtocol());
      assert(conformance.getRequirement() == requirement.getProtocol());
      sourceKey.Kind = LocalTypeDataKind::forProtocolWitnessTable(conformance);

      if (!source) return MetadataResponse();

      auto sourceMetadata = source.getMetadata();
      auto protocol = conformance.getRequirement();
      auto wtable = requirement.isWitnessTablePack()
        ? emitArgumentWitnessTablePackRef(IGF, nominal, requirements,
                                          reqtIndex, sourceMetadata)
        : emitArgumentWitnessTableRef(IGF, nominal, requirements, reqtIndex,
                                      sourceMetadata);
      setProtocolWitnessTableName(IGF.IGM, wtable, sourceKey.Type, protocol);

      return MetadataResponse::forComplete(wtable);
    }

    llvm_unreachable("Bad component kind");
  }

  case Component::Kind::PackExpansionCount: {
    assert(sourceKey.Kind == LocalTypeDataKind::forPackShapeExpression());

    auto componentIndex = component.getPrimaryIndex();

    auto packType = cast<PackType>(sourceKey.Type);
    auto expansion = cast<PackExpansionType>(
        packType.getElementType(componentIndex));
    sourceKey.Type = expansion.getCountType();

    if (!source) return MetadataResponse();

    // Count the number of pack expansions in the pack.
    size_t numExpansions = 0;
    for (auto eltType : packType.getElementTypes()) {
      if (auto eltExpansion = dyn_cast<PackExpansionType>(eltType)) {
        assert(eltExpansion.getCountType() == expansion.getCountType());
        numExpansions++;
      }
    }
    assert(numExpansions >= 1);
    size_t numScalars = packType->getNumElements() - numExpansions;

    llvm::Value *count = source.getMetadata();

    // Subtract the number of scalars.
    if (numScalars > 0) {
      count = IGF.Builder.CreateSub(count,
                                    IGF.IGM.getSize(Size(numScalars)));
    }
    // Divide by the number of pack expansions.
    if (numExpansions > 1) {
      count = IGF.Builder.CreateUDiv(count,
                                     IGF.IGM.getSize(Size(numExpansions)));
    }

    return MetadataResponse::forComplete(count);
  }

  case Component::Kind::PackExpansionPattern: {
    assert(sourceKey.Kind == LocalTypeDataKind::forFormalTypeMetadata() ||
           sourceKey.Kind.isPackProtocolConformance());
    bool isTypeMetadata =
      (sourceKey.Kind == LocalTypeDataKind::forFormalTypeMetadata());

    auto componentIndex = component.getPrimaryIndex();

    // Change the key type to the pattern type.
    auto packType = cast<PackType>(sourceKey.Type);
    auto expansion = cast<PackExpansionType>(
        packType.getElementType(componentIndex));
    sourceKey.Type = expansion.getPatternType();

    // If this is a pack conformance, change the key kind to the
    // appropriate component.
    if (!isTypeMetadata) {
      sourceKey.Kind = LocalTypeDataKind::forProtocolWitnessTable(
          sourceKey.Kind.getPackProtocolConformance()
                           ->getPatternConformances()[componentIndex]);
    }

    if (!source) return MetadataResponse();

    // Compute the offset of the start of the pack component.
    // We can skip even computing this in the very likely case that the
    // component index is zero.
    if (componentIndex == 0) return source;
    auto dynamicIndex =
      emitIndexOfStructuralPackComponent(IGF, packType, componentIndex);

    // Slice into the pack.
    auto eltTy = (isTypeMetadata ? IGF.IGM.TypeMetadataPtrTy
                                 : IGF.IGM.WitnessTablePtrTy);
    auto subPack =
      IGF.Builder.CreateInBoundsGEP(eltTy, source.getMetadata(),
                                    dynamicIndex);

    // The pack slice has the same state as the containing pack.
    auto state = source.getStaticLowerBoundOnState();
    if (source.hasDynamicState())
      return MetadataResponse(subPack, source.getDynamicState(), state);
    return MetadataResponse::forBounded(subPack, state);
  }

  case Component::Kind::OutOfLineBaseProtocol: {
    auto conformance = sourceKey.Kind.getProtocolConformance();
    auto protocol = conformance.getRequirement();
    auto &pi = IGF.IGM.getProtocolInfo(protocol,
                                       ProtocolInfoKind::RequirementSignature);

    auto &entry = pi.getWitnessEntries()[component.getPrimaryIndex()];
    assert(entry.isOutOfLineBase());
    auto inheritedProtocol = entry.getBase();

    sourceKey.Kind =
      LocalTypeDataKind::forAbstractProtocolWitnessTable(inheritedProtocol);
    if (conformance.isConcrete()) {
      auto inheritedConformance =
        conformance.getConcrete()->getInheritedConformance(inheritedProtocol);
      if (inheritedConformance) {
        sourceKey.Kind = LocalTypeDataKind::forConcreteProtocolWitnessTable(
                                                          inheritedConformance);
      }
    }

    if (!source) return MetadataResponse();

    auto wtable = source.getMetadata();
    WitnessIndex index(component.getPrimaryIndex(), /*prefix*/ false);
    auto baseWTable = loadParentProtocolWitnessTable(IGF, wtable,
                                       index.forProtocolWitnessTable());
    baseWTable =
      IGF.Builder.CreateBitCast(baseWTable, IGF.IGM.WitnessTablePtrTy);
    setProtocolWitnessTableName(IGF.IGM, baseWTable, sourceKey.Type,
                                inheritedProtocol);

    return MetadataResponse::forComplete(baseWTable);
  }

  case Component::Kind::AssociatedConformance: {
    auto sourceType = sourceKey.Type;
    auto sourceConformance = sourceKey.Kind.getProtocolConformance();
    auto sourceProtocol = sourceConformance.getRequirement();
    auto &pi = IGF.IGM.getProtocolInfo(sourceProtocol,
                                       ProtocolInfoKind::RequirementSignature);

    auto &entry = pi.getWitnessEntries()[component.getPrimaryIndex()];
    assert(entry.isAssociatedConformance());
    auto association = entry.getAssociatedConformancePath();
    auto associatedRequirement = entry.getAssociatedConformanceRequirement();

    CanType associatedType =
      sourceConformance.getAssociatedType(sourceType, association)
        ->getCanonicalType();
    sourceKey.Type = associatedType;

    auto associatedConformance =
      sourceConformance.getAssociatedConformance(sourceType, association,
                                                 associatedRequirement);
    sourceKey.Kind =
      LocalTypeDataKind::forProtocolWitnessTable(associatedConformance);

    assert((associatedConformance.isConcrete() ||
            isa<ArchetypeType>(sourceKey.Type)) &&
           "couldn't find concrete conformance for concrete type");

    if (!source) return MetadataResponse();

    auto *sourceMetadata =
        IGF.emitAbstractTypeMetadataRef(sourceType);

    // Try to avoid circularity when realizing the associated metadata.
    //
    // Suppose we are asked to produce the witness table for some
    // conformance access path (T : P)(Self.X : Q)(Self.Y : R).
    //
    // The associated conformance accessor for (Self.Y : R) takes the
    // metadata for T.X and T.X : Q as arguments. If T.X is concrete,
    // there are two ways of building it:
    //
    // a) Using the knowledge of the concrete type to build it directly,
    // by first constructing the type metadata for its generic arguments.
    //
    // b) Obtaining T.X from the witness table for T : P. This will also
    // construct the generic type, but from the generic environment
    // of the concrete type of T, and not the abstract environment of
    // our conformance access path.
    //
    // Now, say that T.X == Foo<T.X.Y>, with "Foo<A> where A : R".
    //
    // If approach a) is taken, then constructing Foo<T.X.Y> requires
    // recovering the conformance T.X.Y : R, which recursively evaluates
    // the same conformance access path, eventually causing a stack
    // overflow.
    //
    // With approach b) on the other hand, the type metadata for
    // Foo<T.X.Y> is constructed from the concrete type metadata for T,
    // which must provide some other conformance access path for the
    // conformance to R.
    //
    // This is not very principled, and a remaining issue is with conformance
    // requirements where the subject type consists of multiple terms.
    //
    // A better approach would be for conformance access paths to directly
    // record how type metadata at each intermediate step is constructed.
    llvm::Value *associatedMetadata = nullptr;

    if (auto response = IGF.tryGetLocalTypeMetadata(associatedType,
                                                    MetadataState::Abstract)) {
      // The associated type metadata was already cached, so we're fine.
      associatedMetadata = response.getMetadata();
    } else {
      // If the associated type is concrete and the parent type is an archetype,
      // it is better to realize the associated type metadata from the witness
      // table of the parent's conformance, instead of realizing the concrete
      // type directly.
      auto depMemType = cast<DependentMemberType>(association);
      CanType baseSubstType =
        sourceConformance.getAssociatedType(sourceType, depMemType.getBase())
          ->getCanonicalType();
      if (auto archetypeType = dyn_cast<ArchetypeType>(baseSubstType)) {
        AssociatedType baseAssocType(depMemType->getAssocType());

        MetadataResponse response =
          emitAssociatedTypeMetadataRef(IGF, archetypeType, baseAssocType,
                                        MetadataState::Abstract);

        // Cache this response in case we have to realize the associated type
        // again later.
        IGF.setScopedLocalTypeMetadata(associatedType, response);

        associatedMetadata = response.getMetadata();
      } else {
        // Ok, fall back to realizing the (possibly concrete) type.
        associatedMetadata =
          IGF.emitAbstractTypeMetadataRef(sourceKey.Type);
      }
    }

    auto sourceWTable = source.getMetadata();

    AssociatedConformance associatedConformanceRef(sourceProtocol,
                                                   association,
                                                   associatedRequirement);
    auto associatedWTable = 
      emitAssociatedTypeWitnessTableRef(IGF, sourceMetadata, sourceWTable,
                                        associatedConformanceRef,
                                        associatedMetadata);

    setProtocolWitnessTableName(IGF.IGM, associatedWTable, sourceKey.Type,
                                associatedRequirement);

    return MetadataResponse::forComplete(associatedWTable);
  }

  case Component::Kind::ConditionalConformance: {
    auto sourceConformance = sourceKey.Kind.getProtocolConformance();

    auto reqtIndex = component.getPrimaryIndex();

    ProtocolDecl *conformingProto;
    auto found = SILWitnessTable::enumerateWitnessTableConditionalConformances(
        sourceConformance.getConcrete(),
        [&](unsigned index, CanType type, ProtocolDecl *proto) {
          if (reqtIndex == index) {
            conformingProto = proto;
            sourceKey.Type = type;
            // done!
            return true;
          }
          return /*finished?*/ false;
        });
    assert(found && "too many conditional conformances");
    (void)found;

    sourceKey.Kind =
        LocalTypeDataKind::forAbstractProtocolWitnessTable(conformingProto);

    if (!source) return MetadataResponse();

    WitnessIndex index(privateWitnessTableIndexToTableOffset(reqtIndex),
                       /*prefix*/ false);

    auto sourceWTable = source.getMetadata();
    auto capturedWTable = loadConditionalConformance(IGF, sourceWTable,
                                                     index.forProtocolWitnessTable());
    capturedWTable =
      IGF.Builder.CreateBitCast(capturedWTable, IGF.IGM.WitnessTablePtrTy);
    setProtocolWitnessTableName(IGF.IGM, capturedWTable, sourceKey.Type,
                                conformingProto);

    return MetadataResponse::forComplete(capturedWTable);
  }

  case Component::Kind::TuplePack: {
    assert(component.getPrimaryIndex() == 0);

    auto tupleType = cast<TupleType>(sourceKey.Type);
    auto packType = tupleType.getInducedPackType();

    sourceKey.Kind = LocalTypeDataKind::forFormalTypeMetadata();
    sourceKey.Type = packType;

    if (!source) return MetadataResponse();

    auto sourceMetadata = source.getMetadata();
    return emitInducedTupleTypeMetadataPackRef(IGF, packType,
                                               sourceMetadata);
  }

  case Component::Kind::TupleShape: {
    assert(component.getPrimaryIndex() == 0);

    auto tupleType = cast<TupleType>(sourceKey.Type);

    sourceKey.Kind = LocalTypeDataKind::forPackShapeExpression();
    sourceKey.Type = tupleType.getInducedPackType();

    if (!source) return MetadataResponse();

    auto sourceMetadata = source.getMetadata();
    auto count = irgen::emitTupleTypeMetadataLength(IGF, sourceMetadata);

    return MetadataResponse::forComplete(count);
  }

  case Component::Kind::Impossible:
    llvm_unreachable("following an impossible path!");

  } 
  llvm_unreachable("bad metadata path component");
}

void MetadataPath::dump() const {
  auto &out = llvm::errs();
  print(out);
  out << '\n';
}
void MetadataPath::print(llvm::raw_ostream &out) const {
  for (auto i = Path.begin(), e = Path.end(); i != e; ++i) {
    if (i != Path.begin()) out << ".";
    auto component = *i;
    switch (component.getKind()) {
    case Component::Kind::OutOfLineBaseProtocol:
      out << "out_of_line_base_protocol[" << component.getPrimaryIndex() << "]";
      break;
    case Component::Kind::AssociatedConformance:
      out << "associated_conformance[" << component.getPrimaryIndex() << "]";
      break;
    case Component::Kind::NominalTypeArgument:
      out << "nominal_type_argument[" << component.getPrimaryIndex() << "]";
      break;
    case Component::Kind::NominalTypeArgumentConformance:
      out << "nominal_type_argument_conformance["
          << component.getPrimaryIndex() << "]";
      break;
    case Component::Kind::NominalTypeArgumentShape:
      out << "nominal_type_argument_shape["
          << component.getPrimaryIndex() << "]";
      break;
    case Component::Kind::PackExpansionCount:
      out << "pack_expansion_count[" << component.getPrimaryIndex() << "]";
      break;
    case Component::Kind::PackExpansionPattern:
      out << "pack_expansion_pattern[" << component.getPrimaryIndex() << "]";
      break;
    case Component::Kind::ConditionalConformance:
      out << "conditional_conformance[" << component.getPrimaryIndex() << "]";
      break;
    case Component::Kind::TuplePack:
      out << "tuple_pack";
      break;
    case Component::Kind::TupleShape:
      out << "tuple_shape";
      break;
    case Component::Kind::Impossible:
      out << "impossible";
      break;
    }
  }
}

/// Collect any required metadata for a witness method from the end of
/// the given parameter list.
void irgen::collectTrailingWitnessMetadata(
    IRGenFunction &IGF, SILFunction &fn,
    NativeCCEntryPointArgumentEmission &emission,
    WitnessMetadata &witnessMetadata) {
  assert(fn.getLoweredFunctionType()->getRepresentation()
           == SILFunctionTypeRepresentation::WitnessMethod);

  llvm::Value *wtable = emission.getSelfWitnessTable();
  assert(wtable->getType() == IGF.IGM.WitnessTablePtrTy &&
         "parameter signature mismatch: witness metadata didn't "
         "end in witness table?");
  wtable->setName("SelfWitnessTable");
  witnessMetadata.SelfWitnessTable = wtable;

  llvm::Value *metatype = emission.getSelfMetadata();
  assert(metatype->getType() == IGF.IGM.TypeMetadataPtrTy &&
         "parameter signature mismatch: witness metadata didn't "
         "end in metatype?");
  metatype->setName("Self");
  witnessMetadata.SelfMetadata = metatype;
}

/// Perform all the bindings necessary to emit the given declaration.
void irgen::emitPolymorphicParameters(IRGenFunction &IGF, SILFunction &Fn,
                                      EntryPointArgumentEmission &emission,
                                      WitnessMetadata *witnessMetadata,
                                      const GetParameterFn &getParameter) {
  EmitPolymorphicParameters(IGF, Fn).emit(emission, witnessMetadata,
                                          getParameter);
}

/// Given an array of polymorphic arguments as might be set up by
/// GenericArguments, bind the polymorphic parameters.
void irgen::emitPolymorphicParametersFromArray(IRGenFunction &IGF,
                                               NominalTypeDecl *typeDecl,
                                               Address array,
                                               MetadataState state) {
  GenericTypeRequirements requirements(IGF.IGM, typeDecl);

  array = IGF.Builder.CreateElementBitCast(array, IGF.IGM.TypeMetadataPtrTy);

  SubstitutionMap subs;
  if (auto *genericEnv = typeDecl->getGenericEnvironment())
    subs = genericEnv->getForwardingSubstitutionMap();

  // Okay, bind everything else from the context.
  requirements.bindFromBuffer(IGF, array, state, subs);
}

Size NecessaryBindings::getBufferSize(IRGenModule &IGM) const {
  // We need one pointer for each archetype or witness table.
  return IGM.getPointerSize() * size();
}

void NecessaryBindings::restore(IRGenFunction &IGF, Address buffer,
                                MetadataState metadataState) const {
  bindFromGenericRequirementsBuffer(IGF, getRequirements(), buffer,
                                    metadataState, SubMap);
}

void NecessaryBindings::save(IRGenFunction &IGF, Address buffer) const {
  emitInitOfGenericRequirementsBuffer(IGF, getRequirements(), buffer,
                                      MetadataState::Complete, SubMap,
                                      /*onHeapPacks=*/!NoEscape);
}

llvm::Value *irgen::emitWitnessTableRef(IRGenFunction &IGF,
                                        CanType srcType,
                                        ProtocolConformanceRef conformance) {
  llvm::Value *srcMetadataCache = nullptr;
  return emitWitnessTableRef(IGF, srcType, &srcMetadataCache, conformance);
}

/// Emit a protocol witness table for a conformance.
llvm::Value *irgen::emitWitnessTableRef(IRGenFunction &IGF,
                                        CanType srcType,
                                        llvm::Value **srcMetadataCache,
                                        ProtocolConformanceRef conformance) {
  assert(!srcType->getASTContext().LangOpts.hasFeature(Feature::Embedded));

  auto proto = conformance.getRequirement();
  assert(Lowering::TypeConverter::protocolRequiresWitnessTable(proto)
         && "protocol does not have witness tables?!");

  // Look through any opaque types we're allowed to.
  if (srcType->hasOpaqueArchetype()) {
    std::tie(srcType, conformance) =
      IGF.IGM.substOpaqueTypesWithUnderlyingTypes(srcType, conformance);
  }
  
  // If we don't have concrete conformance information, the type must be
  // an archetype and the conformance must be via one of the protocol
  // requirements of the archetype. Look at what's locally bound.
  ProtocolConformance *concreteConformance;
  if (conformance.isAbstract()) {
    auto archetype = cast<ArchetypeType>(srcType);
    return emitArchetypeWitnessTableRef(IGF, archetype, proto);

  // All other source types should be concrete enough that we have
  // conformance info for them.  However, that conformance info might be
  // more concrete than we're expecting.
  // TODO: make a best effort to devirtualize, maybe?
  } else if (conformance.isPack()) {
    auto pack = cast<PackType>(srcType);
    return emitWitnessTablePackRef(IGF, pack, conformance.getPack());
  } else {
    concreteConformance = conformance.getConcrete();
  }
  assert(concreteConformance->getProtocol() == proto);

  auto cacheKind =
    LocalTypeDataKind::forConcreteProtocolWitnessTable(concreteConformance);

  // Check immediately for an existing cache entry.
  auto wtable = IGF.tryGetLocalTypeData(srcType, cacheKind);
  if (wtable) return wtable;

  auto &conformanceI = IGF.IGM.getConformanceInfo(proto, concreteConformance);
  wtable = conformanceI.getTable(IGF, srcMetadataCache);
  if (isa<llvm::Constant>(wtable))
    wtable = getConstantSignedRelativeProtocolWitnessTable(IGF.IGM, wtable);

  IGF.setScopedLocalTypeData(srcType, cacheKind, wtable);
  return wtable;
}

static CanType getOrigSelfType(IRGenModule &IGM,
                               CanSILFunctionType origFnType) {
  // Grab the apparent 'self' type.  If there isn't a 'self' type,
  // we're not going to try to access this anyway.
  assert(!origFnType->getParameters().empty());

  auto selfParam = origFnType->getParameters().back();
  CanType inputType = selfParam.getArgumentType(
      IGM.getSILModule(), origFnType, IGM.getMaximalTypeExpansionContext());
  // If the parameter is a direct metatype parameter, this is a static method
  // of the instance type. We can assume this because:
  // - metatypes cannot directly conform to protocols
  // - even if they could, they would conform as a value type 'self' and thus
  //   be passed indirectly as an @in or @inout parameter.
  if (auto meta = dyn_cast<MetatypeType>(inputType)) {
    if (!selfParam.isFormalIndirect())
      inputType = meta.getInstanceType();
  }
  
  return inputType;
}

static CanType getSubstSelfType(IRGenModule &IGM,
                                CanSILFunctionType origFnType,
                                SubstitutionMap subs) {
  CanType inputType = getOrigSelfType(IGM, origFnType);
  
  // Substitute the `self` type.
  // FIXME: This has to be done as a formal AST type substitution rather than
  // a SIL function type substitution, because some nominal types (viz
  // Optional) have type lowering recursively applied to their type parameters.
  // Substituting into the original lowered function type like this is still
  // problematic if we ever allow methods or protocol conformances on structural
  // types; we'd really need to separately record the formal Self type in the
  // SIL function type to make that work, which could be managed by having a
  // "substituted generic signature" concept.
  if (!subs.empty()) {
    inputType = inputType.subst(subs)->getCanonicalType();
  }
  
  return inputType;
}

namespace {
  class EmitPolymorphicArguments : public PolymorphicConvention {
    IRGenFunction &IGF;
  public:
    EmitPolymorphicArguments(IRGenFunction &IGF,
                             CanSILFunctionType polyFn)
      : PolymorphicConvention(IGF.IGM, polyFn), IGF(IGF) {}

    void emit(SubstitutionMap subs,
              WitnessMetadata *witnessMetadata, Explosion &out);

  private:
    void emitEarlySources(SubstitutionMap subs, Explosion &out) {
      for (auto &source : getSources()) {
        switch (source.getKind()) {
        // Already accounted for in the parameters.
        case MetadataSource::Kind::ClassPointer:
        case MetadataSource::Kind::Metadata:
          continue;

        // Needs a special argument.
        case MetadataSource::Kind::GenericLValueMetadata: {
          out.add(
              IGF.emitTypeMetadataRef(getSubstSelfType(IGF.IGM, FnType, subs)));
          continue;
        }

        // Witness 'Self' arguments are added as a special case in
        // EmitPolymorphicArguments::emit.
        case MetadataSource::Kind::SelfMetadata:
        case MetadataSource::Kind::SelfWitnessTable:
          continue;

        // No influence on the arguments.
        case MetadataSource::Kind::ErasedTypeMetadata:
          continue;
        }
        llvm_unreachable("bad source kind!");
      }
    }
  };
} // end anonymous namespace

/// Pass all the arguments necessary for the given function.
void irgen::emitPolymorphicArguments(IRGenFunction &IGF,
                                     CanSILFunctionType origFnType,
                                     SubstitutionMap subs,
                                     WitnessMetadata *witnessMetadata,
                                     Explosion &out) {
  EmitPolymorphicArguments(IGF, origFnType).emit(subs, witnessMetadata, out);
}

void EmitPolymorphicArguments::emit(SubstitutionMap subs,
                                    WitnessMetadata *witnessMetadata,
                                    Explosion &out) {
  // Add all the early sources.
  emitEarlySources(subs, out);

  // For now, treat all archetypes independently.
  enumerateUnfulfilledRequirements([&](GenericRequirement requirement) {
    llvm::Value *requiredValue =
      emitGenericRequirementFromSubstitutions(IGF, requirement,
                                              MetadataState::Complete,
                                              subs);
    out.add(requiredValue);
  });

  // For a witness call, add the Self argument metadata arguments last.
  for (auto &source : getSources()) {
    switch (source.getKind()) {
    case MetadataSource::Kind::Metadata:
    case MetadataSource::Kind::ClassPointer:
      // Already accounted for in the arguments.
      continue;

    case MetadataSource::Kind::GenericLValueMetadata:
      // Added in the early phase.
      continue;

    case MetadataSource::Kind::SelfMetadata: {
      assert(witnessMetadata && "no metadata structure for witness method");
      auto self = IGF.emitTypeMetadataRef(
                                      getSubstSelfType(IGF.IGM, FnType, subs));
      witnessMetadata->SelfMetadata = self;
      continue;
    }

    case MetadataSource::Kind::SelfWitnessTable: {
      // Added later.
      continue;
    }

    case MetadataSource::Kind::ErasedTypeMetadata:
      // No influence on the arguments.
      continue;
    }
    llvm_unreachable("bad source kind");
  }
}

NecessaryBindings
NecessaryBindings::forPartialApplyForwarder(IRGenModule &IGM,
                                            CanSILFunctionType origType,
                                            SubstitutionMap subs,
                                            bool noEscape,
                                            bool considerParameterSources) {
  NecessaryBindings bindings(subs, noEscape);
  bindings.computeBindings(IGM, origType, considerParameterSources);
  return bindings;
}

void NecessaryBindings::computeBindings(
    IRGenModule &IGM, CanSILFunctionType origType,
    bool considerParameterSources) {

  // Bail out early if we don't have polymorphic parameters.
  if (!hasPolymorphicParameters(origType))
    return;

  // Figure out what we're actually required to pass:
  PolymorphicConvention convention(IGM, origType, considerParameterSources);

  //   - extra sources
  for (auto &source : convention.getSources()) {
    switch (source.getKind()) {
    case MetadataSource::Kind::Metadata:
    case MetadataSource::Kind::ClassPointer:
      continue;

    case MetadataSource::Kind::GenericLValueMetadata:
      addRequirement(GenericRequirement::forMetadata(
          getOrigSelfType(IGM, origType)));
      continue;

    case MetadataSource::Kind::SelfMetadata:
      // Async functions pass the SelfMetadata and SelfWitnessTable parameters
      // along explicitly.
      addRequirement(GenericRequirement::forMetadata(
          getOrigSelfType(IGM, origType)));
      continue;

    case MetadataSource::Kind::SelfWitnessTable:
      // We'll just pass undef in cases like this.
      continue;

    case MetadataSource::Kind::ErasedTypeMetadata:
      // Fixed in the body.
      continue;
    }
    llvm_unreachable("bad source kind");
  }

  //  - unfulfilled requirements
  convention.enumerateUnfulfilledRequirements(
                                        [&](GenericRequirement requirement) {
    addRequirement(requirement);
  });
}

/// The information we need to record in generic type metadata
/// is the information in the type's generic signature.  This is
/// simply the information that would be passed to a generic function
/// that takes the (thick) parent metatype as an argument.
GenericTypeRequirements::GenericTypeRequirements(IRGenModule &IGM,
                                                 NominalTypeDecl *typeDecl)
  : GenericTypeRequirements(IGM, typeDecl->getGenericSignatureOfContext()) {}

GenericTypeRequirements::GenericTypeRequirements(IRGenModule &IGM,
                                                 GenericSignature ncGenerics) {
  // We only need to do something here if the declaration context is
  // somehow generic.
  if (!ncGenerics || ncGenerics->areAllParamsConcrete()) return;

  // Construct a representative function type.
  auto generics = ncGenerics.getCanonicalSignature();
  auto fnType = SILFunctionType::get(
      generics, SILFunctionType::ExtInfo(), SILCoroutineKind::None,
      /*callee*/ ParameterConvention::Direct_Unowned,
      /*params*/ {}, /*yields*/ {},
      /*results*/ {}, /*error*/ std::nullopt,
      /*pattern subs*/ SubstitutionMap(),
      /*invocation subs*/ SubstitutionMap(), IGM.Context);

  // Figure out what we're actually still required to pass 
  PolymorphicConvention convention(IGM, fnType);
  convention.enumerateUnfulfilledRequirements([&](GenericRequirement reqt) {
    assert(generics->isReducedType(reqt.getTypeParameter()));
    Requirements.push_back(reqt);
  });

  // We do not need to consider extra sources.
}

void GenericTypeRequirements::emitInitOfBuffer(IRGenFunction &IGF,
                                               SubstitutionMap subs,
                                               Address buffer) {
  if (Requirements.empty()) return;

  emitInitOfGenericRequirementsBuffer(IGF, Requirements, buffer,
                                      MetadataState::Complete, subs);
}

void irgen::emitInitOfGenericRequirementsBuffer(IRGenFunction &IGF,
                               ArrayRef<GenericRequirement> requirements,
                               Address buffer,
                               MetadataState metadataState,
                               SubstitutionMap subs,
                               bool onHeapPacks) {
  if (requirements.empty()) return;

  // Cast the buffer to %type**.
  buffer = IGF.Builder.CreateElementBitCast(buffer, IGF.IGM.TypeMetadataPtrTy);

  for (auto index : indices(requirements)) {
    // GEP to the appropriate slot.
    Address slot = buffer;
    if (index != 0) {
      slot = IGF.Builder.CreateConstArrayGEP(slot, index,
                                             IGF.IGM.getPointerSize());
    }

    llvm::Value *value = emitGenericRequirementFromSubstitutions(
        IGF, requirements[index], metadataState, subs, onHeapPacks);
    slot = IGF.Builder.CreateElementBitCast(slot,
                                       requirements[index].getType(IGF.IGM));
    IGF.Builder.CreateStore(value, slot);
  }
}

llvm::Value *
irgen::emitGenericRequirementFromSubstitutions(IRGenFunction &IGF,
                                               GenericRequirement requirement,
                                               MetadataState metadataState,
                                               SubstitutionMap subs,
                                               bool onHeapPacks) {
  CanType depTy = requirement.getTypeParameter();
  CanType argType = depTy.subst(subs)->getCanonicalType();

  switch (requirement.getKind()) {
  case GenericRequirement::Kind::Shape:
    return IGF.emitPackShapeExpression(argType);

  case GenericRequirement::Kind::Metadata:
    return IGF.emitTypeMetadataRef(argType, metadataState).getMetadata();

  case GenericRequirement::Kind::MetadataPack: {
    auto metadata = IGF.emitTypeMetadataRef(argType, metadataState).getMetadata();
    metadata = IGF.Builder.CreateBitCast(metadata, IGF.IGM.TypeMetadataPtrPtrTy);

    // FIXME: We should track if this pack is already known to be on the heap
    if (onHeapPacks) {
      auto shape = IGF.emitPackShapeExpression(argType);
      metadata = IGF.Builder.CreateCall(IGF.IGM.getAllocateMetadataPackFunctionPointer(),
                                        {metadata, shape});
    }

    return metadata;
  }

  case GenericRequirement::Kind::WitnessTable: {
    auto conformance = subs.lookupConformance(depTy, requirement.getProtocol());
    return emitWitnessTableRef(IGF, argType, conformance);
  }

  case GenericRequirement::Kind::WitnessTablePack: {
    auto conformance = subs.lookupConformance(depTy, requirement.getProtocol());
    auto wtable = emitWitnessTableRef(IGF, argType, conformance);
    wtable = IGF.Builder.CreateBitCast(wtable, IGF.IGM.WitnessTablePtrPtrTy);

    // FIXME: We should track if this pack is already known to be on the heap
    if (onHeapPacks) {
      auto shape = IGF.emitPackShapeExpression(argType);
      wtable = IGF.Builder.CreateCall(IGF.IGM.getAllocateWitnessTablePackFunctionPointer(),
                                      {wtable, shape});
    }

    return wtable;
  }
  }
}

void GenericTypeRequirements::bindFromBuffer(IRGenFunction &IGF,
                                             Address buffer,
                                             MetadataState metadataState,
                                             SubstitutionMap subs) {
  bindFromGenericRequirementsBuffer(IGF, Requirements, buffer,
                                    metadataState, subs);
}

void irgen::bindFromGenericRequirementsBuffer(IRGenFunction &IGF,
                                              ArrayRef<GenericRequirement> requirements,
                                              Address buffer,
                                              MetadataState metadataState,
                                              SubstitutionMap subs) {
  if (requirements.empty()) return;

  // Cast the buffer to %type**.
  buffer = IGF.Builder.CreateElementBitCast(buffer, IGF.IGM.TypeMetadataPtrTy);

  for (auto index : indices(requirements)) {
    // GEP to the appropriate slot.
    Address slot = buffer;
    if (index != 0) {
      slot = IGF.Builder.CreateConstArrayGEP(slot, index,
                                             IGF.IGM.getPointerSize());
    }

    // Cast if necessary.
    slot = IGF.Builder.CreateElementBitCast(
        slot, requirements[index].getType(IGF.IGM));

    llvm::Value *value = IGF.Builder.CreateLoad(slot);
    bindGenericRequirement(IGF, requirements[index], value, metadataState, subs);
  }
}

llvm::Type *GenericRequirement::typeForKind(IRGenModule &IGM,
                                            GenericRequirement::Kind kind) {
  switch (kind) {
  case GenericRequirement::Kind::Shape:
    return IGM.SizeTy;
  case GenericRequirement::Kind::Metadata:
    return IGM.TypeMetadataPtrTy;
  case GenericRequirement::Kind::WitnessTable:
    return IGM.WitnessTablePtrTy;
  case GenericRequirement::Kind::MetadataPack:
    return IGM.TypeMetadataPtrPtrTy;
  case GenericRequirement::Kind::WitnessTablePack:
    return IGM.WitnessTablePtrPtrTy;
  }
}

void irgen::bindGenericRequirement(IRGenFunction &IGF,
                                   GenericRequirement requirement,
                                   llvm::Value *value,
                                   MetadataState metadataState,
                                   SubstitutionMap subs) {
  // Get the corresponding context type.
  auto type = requirement.getTypeParameter();
  if (subs)
    type = type.subst(subs)->getCanonicalType();

  // FIXME: Remove this
  bool wasUnwrappedPack = false;
  if (auto packType = dyn_cast<PackType>(type)) {
    if (auto expansionType = packType.unwrapSingletonPackExpansion()) {
      if (auto archetypeType = dyn_cast_or_null<PackArchetypeType>(
            expansionType.getPatternType())) {
        type = archetypeType;
        wasUnwrappedPack = true;
      }
    }
  }

  assert(value->getType() == requirement.getType(IGF.IGM));
  switch (requirement.getKind()) {
  case GenericRequirement::Kind::Shape: {
    assert(isa<ArchetypeType>(type));
    auto kind = LocalTypeDataKind::forPackShapeExpression();
    IGF.setUnscopedLocalTypeData(type, kind, value);
    break;
  }

  case GenericRequirement::Kind::Metadata:
  case GenericRequirement::Kind::MetadataPack: {
    setTypeMetadataName(IGF.IGM, value, type);
    IGF.bindLocalTypeDataFromTypeMetadata(type, IsExact, value, metadataState);
    break;
  }

  case GenericRequirement::Kind::WitnessTable:
  case GenericRequirement::Kind::WitnessTablePack: {
    auto proto = requirement.getProtocol();
    setProtocolWitnessTableName(IGF.IGM, value, type, proto);

    if (subs) {
      auto conf = subs.lookupConformance(requirement.getTypeParameter(), proto);

      // FIXME: Remove this
      if (conf.isPack() && isa<PackArchetypeType>(type)) {
        assert(wasUnwrappedPack);
        assert(conf.getPack()->getPatternConformances().size() == 1);
        conf = conf.getPack()->getPatternConformances()[0];
      }

      auto kind = LocalTypeDataKind::forProtocolWitnessTable(conf);
      IGF.setUnscopedLocalTypeData(type, kind, value);
    } else {
      auto kind = LocalTypeDataKind::forAbstractProtocolWitnessTable(proto);
      IGF.setUnscopedLocalTypeData(type, kind, value);
    }
    break;
  }
  }
}

namespace {
  /// A class for expanding a polymorphic signature.
  class ExpandPolymorphicSignature : public PolymorphicConvention {
    unsigned numShapes = 0;
    unsigned numTypeMetadataPtrs = 0;
    unsigned numWitnessTablePtrs = 0;

  public:
    ExpandPolymorphicSignature(IRGenModule &IGM, CanSILFunctionType fn)
      : PolymorphicConvention(IGM, fn) {}

    ExpandedSignature
    expand(SmallVectorImpl<llvm::Type *> &out,
           SmallVectorImpl<PolymorphicSignatureExpandedTypeSource> *reqs) {
      auto outStartSize = out.size();
      (void)outStartSize;
      for (auto &source : getSources())
        addEarlySource(source, out, reqs);

      enumerateUnfulfilledRequirements([&](GenericRequirement reqt) {
        if (reqs)
          reqs->push_back(reqt);
        out.push_back(reqt.getType(IGM));
        switch (reqt.getKind()) {
        case GenericRequirement::Kind::Shape:
          ++numShapes;
          break;
        case GenericRequirement::Kind::Metadata:
        case GenericRequirement::Kind::MetadataPack:
          ++numTypeMetadataPtrs;
          break;
        case GenericRequirement::Kind::WitnessTable:
        case GenericRequirement::Kind::WitnessTablePack:
          ++numWitnessTablePtrs;
          break;
        }
      });
      assert((!reqs || reqs->size() == (out.size() - outStartSize)) &&
             "missing type source for type");
      return {numShapes, numTypeMetadataPtrs, numWitnessTablePtrs};
    }

  private:
    /// Add signature elements for the source metadata.
    void addEarlySource(
        const MetadataSource &source, SmallVectorImpl<llvm::Type *> &out,
        SmallVectorImpl<PolymorphicSignatureExpandedTypeSource> *reqs) {
      switch (source.getKind()) {
      case MetadataSource::Kind::ClassPointer: return; // already accounted for
      case MetadataSource::Kind::Metadata: return; // already accounted for
      case MetadataSource::Kind::GenericLValueMetadata:
        if (reqs)
          reqs->push_back(source);
        ++numTypeMetadataPtrs;
        return out.push_back(IGM.TypeMetadataPtrTy);
      case MetadataSource::Kind::SelfMetadata:
      case MetadataSource::Kind::SelfWitnessTable:
        return; // handled as a special case in expand()
      case MetadataSource::Kind::ErasedTypeMetadata:
        return; // fixed in the body
      }
      llvm_unreachable("bad source kind");
    }
  };
} // end anonymous namespace

/// Given a generic signature, add the argument types required in order to call it.
ExpandedSignature irgen::expandPolymorphicSignature(
    IRGenModule &IGM, CanSILFunctionType polyFn,
    SmallVectorImpl<llvm::Type *> &out,
    SmallVectorImpl<PolymorphicSignatureExpandedTypeSource> *outReqs) {
  return ExpandPolymorphicSignature(IGM, polyFn).expand(out, outReqs);
}

void irgen::expandTrailingWitnessSignature(IRGenModule &IGM,
                                           CanSILFunctionType polyFn,
                                           SmallVectorImpl<llvm::Type*> &out) {
  assert(polyFn->getRepresentation()
          == SILFunctionTypeRepresentation::WitnessMethod);

  assert(getTrailingWitnessSignatureLength(IGM, polyFn) == 2);

  // A witness method always provides Self.
  out.push_back(IGM.TypeMetadataPtrTy);

  // A witness method always provides the witness table for Self.
  out.push_back(IGM.WitnessTablePtrTy);
}

static llvm::Value *emitWTableSlotLoad(IRGenFunction &IGF, llvm::Value *wtable,
                                       SILDeclRef member, Address slot,
                                       bool isRelativeTable) {
  if (IGF.IGM.getOptions().WitnessMethodElimination) {
    // For LLVM IR WME, emit a @llvm.type.checked.load with the type of the
    // method.
    auto slotAsPointer = IGF.Builder.CreateElementBitCast(slot, IGF.IGM.Int8Ty);
    auto typeId = typeIdForMethod(IGF.IGM, member);

    // Arguments for @llvm.type.checked.load: 1) target address, 2) offset -
    // always 0 because target address is directly pointing to the right slot,
    // 3) type identifier, i.e. the mangled name of the *base* method.
    SmallVector<llvm::Value *, 8> args;
    args.push_back(slotAsPointer.getAddress());
    args.push_back(llvm::ConstantInt::get(IGF.IGM.Int32Ty, 0));
    args.push_back(llvm::MetadataAsValue::get(*IGF.IGM.LLVMContext, typeId));

    // TODO/FIXME: Using @llvm.type.checked.load loses the "invariant" marker
    // which could mean redundant loads don't get removed.
    llvm::Value *checkedLoad =
        isRelativeTable ? IGF.Builder.CreateIntrinsicCall(
                              llvm::Intrinsic::type_checked_load_relative, args)
                        : IGF.Builder.CreateIntrinsicCall(
                              llvm::Intrinsic::type_checked_load, args);
    return IGF.Builder.CreateExtractValue(checkedLoad, 0);
  }

  if (isRelativeTable)
    return IGF.emitLoadOfRelativePointer(slot, false, IGF.IGM.Int8Ty);

  // Not doing LLVM IR WME, can just be a direct load.
  return IGF.emitInvariantLoad(slot);
}

static FunctionPointer emitRelativeProtocolWitnessTableAccess(IRGenFunction &IGF,
                                                              WitnessIndex index,
                                                              llvm::Value *wtable,
                                                              SILDeclRef member) {
  auto witnessTableTy = wtable->getType();
  auto &IGM = IGF.IGM;
  llvm::SmallString<40> fnName;
  auto entity = LinkEntity::forMethodDescriptor(member);
  auto mangled = entity.mangleAsString();
  llvm::raw_svector_ostream(fnName)
    << "__swift_relative_protocol_witness_table_access_"
    << index.forProtocolWitnessTable().getValue()
    << "_" << mangled;

  auto fnType = IGF.IGM.getSILTypes().getConstantFunctionType(
    IGF.IGM.getMaximalTypeExpansionContext(), member);
  Signature signature = IGF.IGM.getSignature(fnType);

  auto helperFn = cast<llvm::Function>(IGM.getOrCreateHelperFunction(
    fnName, IGM.Int8PtrTy, {witnessTableTy},
    [&](IRGenFunction &subIGF) {

    auto it = subIGF.CurFn->arg_begin();
    llvm::Value *wtable =  &*it;
    wtable = subIGF.optionallyLoadFromConditionalProtocolWitnessTable(wtable);
    auto slot = slotForLoadOfOpaqueWitness(subIGF, wtable,
                                           index.forProtocolWitnessTable(),
                                           true);
    llvm::Value *witnessFnPtr = emitWTableSlotLoad(subIGF, wtable, member, slot,
                                                   true);

    subIGF.Builder.CreateRet(witnessFnPtr);

  }, true /*noinline*/));

  auto *call = IGF.Builder.CreateCallWithoutDbgLoc(
    helperFn->getFunctionType(), helperFn, {wtable});
  call->setCallingConv(IGF.IGM.DefaultCC);
  call->setDoesNotThrow();
  auto fn = IGF.Builder.CreateBitCast(call, signature.getType()->getPointerTo());
  return FunctionPointer::createUnsigned(fnType, fn, signature, true);
}

FunctionPointer irgen::emitWitnessMethodValue(IRGenFunction &IGF,
                                              llvm::Value *wtable,
                                              SILDeclRef member) {
  auto *fn = cast<AbstractFunctionDecl>(member.getDecl());
  auto proto = cast<ProtocolDecl>(fn->getDeclContext());

  assert(!IGF.IGM.isResilient(proto, ResilienceExpansion::Maximal));

  // Find the witness we're interested in.
  auto &fnProtoInfo = IGF.IGM.getProtocolInfo(proto, ProtocolInfoKind::Full);
  auto index = fnProtoInfo.getFunctionIndex(member);
  auto isRelativeTable = IGF.IGM.IRGen.Opts.UseRelativeProtocolWitnessTables;
  if (isRelativeTable) {
    return emitRelativeProtocolWitnessTableAccess(IGF, index, wtable, member);
  }

  wtable = IGF.optionallyLoadFromConditionalProtocolWitnessTable(wtable);
  auto slot =
      slotForLoadOfOpaqueWitness(IGF, wtable, index.forProtocolWitnessTable(),
                                 false/*isRelativeTable*/);
  llvm::Value *witnessFnPtr = emitWTableSlotLoad(IGF, wtable, member, slot,
                                                 false/*isRelativeTable*/);

  auto fnType = IGF.IGM.getSILTypes().getConstantFunctionType(
      IGF.IGM.getMaximalTypeExpansionContext(), member);
  Signature signature = IGF.IGM.getSignature(fnType);
  witnessFnPtr = IGF.Builder.CreateBitCast(witnessFnPtr,
                                           signature.getType()->getPointerTo());

  auto &schema = fnType->isAsync()
                     ? IGF.getOptions().PointerAuth.AsyncProtocolWitnesses
                     : IGF.getOptions().PointerAuth.ProtocolWitnesses;
  auto authInfo = PointerAuthInfo::emit(IGF, schema, slot.getAddress(), member);

  return FunctionPointer::createSigned(fnType, witnessFnPtr, authInfo,
                                       signature);
}

FunctionPointer irgen::emitWitnessMethodValue(
    IRGenFunction &IGF, CanType baseTy, llvm::Value **baseMetadataCache,
    SILDeclRef member, ProtocolConformanceRef conformance) {
  llvm::Value *wtable = emitWitnessTableRef(IGF, baseTy, baseMetadataCache,
                                            conformance);

  return emitWitnessMethodValue(IGF, wtable, member);
}

llvm::Value *irgen::computeResilientWitnessTableIndex(
                                            IRGenFunction &IGF,
                                            ProtocolDecl *proto,
                                            llvm::Constant *reqtDescriptor) {
  // The requirement base descriptor refers to the first requirement in the
  // protocol descriptor, offset by the start of the witness table requirements.
  auto requirementsBaseDescriptor =
    IGF.IGM.getAddrOfProtocolRequirementsBaseDescriptor(proto);

  // Subtract the two pointers to determine the offset to this particular
  // requirement.
  auto baseAddress = IGF.Builder.CreatePtrToInt(requirementsBaseDescriptor,
                                                IGF.IGM.IntPtrTy);
  auto reqtAddress = IGF.Builder.CreatePtrToInt(reqtDescriptor,
                                                IGF.IGM.IntPtrTy);
  auto offset = IGF.Builder.CreateSub(reqtAddress, baseAddress);

  // Determine how to adjust the byte offset we have to make it a witness
  // table offset.
  const auto &dataLayout = IGF.IGM.Module.getDataLayout();
  auto protoReqSize =
    dataLayout.getTypeAllocSizeInBits(IGF.IGM.ProtocolRequirementStructTy);
  auto ptrSize = dataLayout.getTypeAllocSizeInBits(IGF.IGM.Int8PtrTy);
  assert(protoReqSize >= ptrSize && "> 64-bit pointers?");
  assert((protoReqSize % ptrSize == 0) && "Must be evenly divisible");
  (void)ptrSize;
  unsigned factor = protoReqSize / 8;
  auto factorConstant = llvm::ConstantInt::get(IGF.IGM.IntPtrTy, factor);
  return IGF.Builder.CreateUDiv(offset, factorConstant);
}

MetadataResponse
irgen::emitAssociatedTypeMetadataRef(IRGenFunction &IGF,
                                     llvm::Value *parentMetadata,
                                     llvm::Value *wtable,
                                     AssociatedType associatedType,
                                     DynamicMetadataRequest request) {
  auto &IGM = IGF.IGM;

  // Extract the requirements base descriptor.
  auto reqBaseDescriptor =
    IGM.getAddrOfProtocolRequirementsBaseDescriptor(
                                          associatedType.getSourceProtocol());

  // Extract the associated type descriptor.
  auto assocTypeDescriptor =
    IGM.getAddrOfAssociatedTypeDescriptor(associatedType.getAssociation());
  // Call swift_getAssociatedTypeWitness().
  auto call =
    IGF.IGM.IRGen.Opts.UseRelativeProtocolWitnessTables ?
      IGF.Builder.CreateCall(IGM.getGetAssociatedTypeWitnessRelativeFunctionPointer(),
                             {request.get(IGF), wtable, parentMetadata,
                              reqBaseDescriptor, assocTypeDescriptor}) :
      IGF.Builder.CreateCall(IGM.getGetAssociatedTypeWitnessFunctionPointer(),
                             {request.get(IGF), wtable, parentMetadata,
                              reqBaseDescriptor, assocTypeDescriptor});
  call->setDoesNotThrow();
  call->setDoesNotAccessMemory();
  return MetadataResponse::handle(IGF, request, call);
}

Signature
IRGenModule::getAssociatedTypeWitnessTableAccessFunctionSignature() {
  auto &fnType = AssociatedTypeWitnessTableAccessFunctionTy;
  if (!fnType) {
    // The associated type metadata is passed first so that this function is
    // CC-compatible with a conformance's witness table access function.
    fnType = llvm::FunctionType::get(WitnessTablePtrTy,
                                     { TypeMetadataPtrTy,
                                       TypeMetadataPtrTy,
                                       WitnessTablePtrTy },
                                     /*varargs*/ false);
  }

  auto attrs = llvm::AttributeList().addFnAttribute(getLLVMContext(),
                                                    llvm::Attribute::NoUnwind);
  return Signature(fnType, attrs, SwiftCC);
}

/// Load a reference to the protocol descriptor for the given protocol.
///
/// For Swift protocols, this is a constant reference to the protocol descriptor
/// symbol.
/// For ObjC protocols, descriptors are uniqued at runtime by the ObjC runtime.
/// We need to load the unique reference from a global variable fixed up at
/// startup.
///
/// The result is always a ProtocolDescriptorRefTy whose low bit will be
/// set to indicate when this is an Objective-C protocol.
llvm::Value *irgen::emitProtocolDescriptorRef(IRGenFunction &IGF,
                                              ProtocolDecl *protocol) {
  if (!protocol->isObjC()) {
    return IGF.Builder.CreatePtrToInt(
      IGF.IGM.getAddrOfProtocolDescriptor(protocol),
      IGF.IGM.ProtocolDescriptorRefTy);
  }

  llvm::Value *val = emitReferenceToObjCProtocol(IGF, protocol);
  val = IGF.Builder.CreatePtrToInt(val, IGF.IGM.ProtocolDescriptorRefTy);

  // Set the low bit to indicate that this is an Objective-C protocol.
  auto *isObjCBit = llvm::ConstantInt::get(IGF.IGM.ProtocolDescriptorRefTy, 1);
  val = IGF.Builder.CreateOr(val, isObjCBit);

  return val;
}

llvm::Constant *IRGenModule::getAddrOfGenericEnvironment(
                                                CanGenericSignature signature) {
  if (!signature)
    return nullptr;

  IRGenMangler mangler;
  auto symbolName = mangler.mangleSymbolNameForGenericEnvironment(signature);
  return getAddrOfStringForMetadataRef(symbolName, /*alignment=*/0, false,
      [&] (ConstantInitBuilder &builder) -> ConstantInitFuture {
        /// Collect the cumulative count of parameters at each level.
        llvm::SmallVector<uint16_t, 4> genericParamCounts;
        unsigned curDepth = 0;
        unsigned genericParamCount = 0;
        for (const auto &gp : signature.getGenericParams()) {
          if (curDepth != gp->getDepth()) {
            genericParamCounts.push_back(genericParamCount);
            curDepth = gp->getDepth();
          }

          ++genericParamCount;
        }
        genericParamCounts.push_back(genericParamCount);

        auto flags = GenericEnvironmentFlags()
          .withNumGenericParameterLevels(genericParamCounts.size())
          .withNumGenericRequirements(signature.getRequirements().size());

        ConstantStructBuilder fields = builder.beginStruct();
        fields.setPacked(true);

        // Flags
        fields.addInt32(flags.getIntValue());

        // Parameter counts.
        for (auto count : genericParamCounts) {
          fields.addInt16(count);
        }

        // Generic parameters.
        auto metadata =
            irgen::addGenericParameters(*this, fields, signature, /*implicit=*/false);
        assert(metadata.NumParamsEmitted == metadata.NumParams &&
               "Implicit GenericParamDescriptors not supported here");
        assert(metadata.GenericPackArguments.empty() &&
               "We don't support packs here yet");

        // Need to pad the structure after generic parameters
        // up to four bytes because generic requirements that
        // follow expect that alignment.
        fields.addAlignmentPadding(Alignment(4));

        // Generic requirements
        irgen::addGenericRequirements(*this, fields, signature);
        return fields.finishAndCreateFuture();
      });
}