File: Type.cpp

package info (click to toggle)
swiftlang 6.1.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,791,532 kB
  • sloc: cpp: 9,901,743; ansic: 2,201,431; asm: 1,091,827; python: 308,252; objc: 82,166; f90: 80,126; lisp: 38,358; pascal: 25,559; sh: 20,429; ml: 5,058; perl: 4,745; makefile: 4,484; awk: 3,535; javascript: 3,018; xml: 918; fortran: 664; cs: 573; ruby: 396
file content (4925 lines) | stat: -rw-r--r-- 168,067 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
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
//===--- Type.cpp - Swift Language Type ASTs ------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 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 the Type class and subclasses.
//
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "ast-types"

#include "clang/AST/Type.h"
#include "ForeignRepresentationInfo.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/ClangModuleLoader.h"
#include "swift/AST/Concurrency.h"
#include "swift/AST/ConformanceLookup.h"
#include "swift/AST/Decl.h"
#include "swift/AST/ExistentialLayout.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/LazyResolver.h"
#include "swift/AST/Module.h"
#include "swift/AST/PackConformance.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/PrettyStackTrace.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/ReferenceCounting.h"
#include "swift/AST/SILLayout.h"
#include "swift/AST/SubstitutionMap.h"
#include "swift/AST/TypeCheckRequests.h"
#include "swift/AST/TypeLoc.h"
#include "swift/AST/TypeRepr.h"
#include "swift/AST/TypeTransform.h"
#include "swift/AST/TypeVisitor.h"
#include "swift/AST/TypeWalker.h"
#include "swift/AST/Types.h"
#include "swift/Basic/Assertions.h"
#include "swift/Basic/Compiler.h"
#include "llvm/ADT/APFloat.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <functional>
#include <iterator>
using namespace swift;

#define TYPE(Id, _) \
  static_assert(IsTriviallyDestructible<Id##Type>::value, \
                "Types are BumpPtrAllocated; the destructor is never called");
#include "swift/AST/TypeNodes.def"

void TypeLoc::setType(Type Ty) {
  assert(!Ty || !Ty->hasTypeVariable() || !Ty->hasPlaceholder());
  this->Ty = Ty;
}

bool TypeLoc::isError() const {
  assert(wasValidated() && "Type not yet validated");
  return getType()->hasError();
}

SourceRange TypeLoc::getSourceRange() const {
  if (TyR)
    return TyR->getSourceRange();
  return SourceRange();
}

SourceLoc TypeLoc::getLoc() const {
  if (TyR) return TyR->getLoc();
  return SourceLoc();
}

NominalTypeDecl *CanType::getAnyNominal() const {
  return dyn_cast_or_null<NominalTypeDecl>(getAnyGeneric());
}

GenericTypeDecl *CanType::getAnyGeneric() const {
  // FIXME: Remove checking for existential types. `getAnyGeneric` should return
  // the GenericTypeDecl the type is directly bound to.
  if (auto existential = dyn_cast<ExistentialType>(*this))
    return existential->getConstraintType()->getAnyGeneric();
  if (auto ppt = dyn_cast<ParameterizedProtocolType>(*this))
    return ppt->getBaseType()->getDecl();
  if (auto Ty = dyn_cast<AnyGenericType>(*this))
    return Ty->getDecl();
  return nullptr;
}

//===----------------------------------------------------------------------===//
// Various Type Methods.
//===----------------------------------------------------------------------===//

/// isEqual - Return true if these two types are equal, ignoring sugar.
bool TypeBase::isEqual(Type Other) const {
  return getCanonicalType() == Other.getPointer()->getCanonicalType();
}

/// hasReferenceSemantics - Does this type have reference semantics?
bool TypeBase::hasReferenceSemantics() {
  return getCanonicalType().hasReferenceSemantics();
}

bool TypeBase::isUninhabited() {
  // Empty enum declarations are uninhabited
  if (auto nominalDecl = getAnyNominal())
    if (auto enumDecl = dyn_cast<EnumDecl>(nominalDecl))
      // Objective-C enums may be allowed to hold any value representable by
      // the underlying type, but only if they come from clang.
      if (enumDecl->getAllElements().empty() &&
          !(enumDecl->isObjC() && enumDecl->hasClangNode()))
        return true;
  return false;
}

bool TypeBase::isStructurallyUninhabited() {
  if (isUninhabited()) return true;
  
  // Tuples of uninhabited types are uninhabited
  if (auto *TTy = getAs<TupleType>())
    for (auto eltTy : TTy->getElementTypes())
      if (eltTy->isStructurallyUninhabited())
        return true;
  return false;
}

bool TypeBase::isAny() {
  Type constraint = this;
  if (auto existential = constraint->getAs<ExistentialType>())
    constraint = existential->getConstraintType();
  return constraint->isEqual(getASTContext().TheAnyType);
}

bool TypeBase::isMarkerExistential() {
  Type constraint = this;
  if (auto existential = constraint->getAs<ExistentialType>())
    constraint = existential->getConstraintType();

  if (!constraint->isConstraintType())
    return false;

  auto layout = constraint->getExistentialLayout();
  if (layout.hasExplicitAnyObject ||
      layout.explicitSuperclass) {
    return false;
  }

  for (auto *proto : layout.getProtocols()) {
    if (!proto->isMarkerProtocol())
      return false;
  }

  return true;
}

bool TypeBase::isSendableExistential() {
  Type constraint = this;
  if (auto existential = constraint->getAs<ExistentialType>())
    constraint = existential->getConstraintType();

  if (!constraint->isConstraintType())
    return false;

  return constraint->getKnownProtocol() == KnownProtocolKind::Sendable;
}

bool TypeBase::isPlaceholder() {
  return is<PlaceholderType>();
}

bool TypeBase::isAnyClassReferenceType() {
  return getCanonicalType().isAnyClassReferenceType();
}

bool CanType::isReferenceTypeImpl(CanType type, const GenericSignatureImpl *sig,
                                  bool functionsCount) {
  switch (type->getKind()) {
#define SUGARED_TYPE(id, parent) case TypeKind::id:
#define TYPE(id, parent)
#include "swift/AST/TypeNodes.def"
    llvm_unreachable("sugared canonical type?");

  // These types are always class references.
  case TypeKind::BuiltinNativeObject:
  case TypeKind::BuiltinBridgeObject:
  case TypeKind::Class:
  case TypeKind::BoundGenericClass:
  case TypeKind::SILBox:
    return true;

  // For Self types, recur on the underlying type.
  case TypeKind::DynamicSelf:
    return isReferenceTypeImpl(cast<DynamicSelfType>(type).getSelfType(),
                               sig, functionsCount);
  case TypeKind::SILMoveOnlyWrapped:
    return isReferenceTypeImpl(
        cast<SILMoveOnlyWrappedType>(type)->getInnerType(), sig,
        functionsCount);

  // Archetypes and existentials are only class references if class-bounded.
  case TypeKind::PrimaryArchetype:
  case TypeKind::OpenedArchetype:
  case TypeKind::OpaqueTypeArchetype:
  case TypeKind::PackArchetype:
  case TypeKind::ElementArchetype:
    return cast<ArchetypeType>(type)->requiresClass();
  case TypeKind::Protocol:
    return cast<ProtocolType>(type)->requiresClass();
  case TypeKind::ProtocolComposition:
    return cast<ProtocolCompositionType>(type)->requiresClass();
  case TypeKind::ParameterizedProtocol:
    return cast<ParameterizedProtocolType>(type)->getBaseType()->requiresClass();
  case TypeKind::Existential:
    return isReferenceTypeImpl(cast<ExistentialType>(type).getConstraintType(),
                               sig, functionsCount);

  case TypeKind::UnboundGeneric:
    return isa<ClassDecl>(cast<UnboundGenericType>(type)->getDecl());

  // Functions have reference semantics, but are not class references.
  case TypeKind::Function:
  case TypeKind::GenericFunction:
  case TypeKind::SILFunction:
    return functionsCount;

  // Nothing else is statically just a class reference.
  case TypeKind::SILBlockStorage:
  case TypeKind::Error:
  case TypeKind::Unresolved:
  case TypeKind::BuiltinInteger:
  case TypeKind::BuiltinIntegerLiteral:
  case TypeKind::BuiltinFloat:
  case TypeKind::BuiltinRawPointer:
  case TypeKind::BuiltinRawUnsafeContinuation:
  case TypeKind::BuiltinJob:
  case TypeKind::BuiltinExecutor:
  case TypeKind::BuiltinDefaultActorStorage:
  case TypeKind::BuiltinNonDefaultDistributedActorStorage:
  case TypeKind::BuiltinPackIndex:
  case TypeKind::BuiltinUnsafeValueBuffer:
  case TypeKind::BuiltinVector:
  case TypeKind::Tuple:
  case TypeKind::Enum:
  case TypeKind::Struct:
  case TypeKind::Metatype:
  case TypeKind::ExistentialMetatype:
  case TypeKind::Module:
  case TypeKind::LValue:
  case TypeKind::InOut:
  case TypeKind::TypeVariable:
  case TypeKind::Placeholder:
  case TypeKind::BoundGenericEnum:
  case TypeKind::BoundGenericStruct:
  case TypeKind::SILToken:
  case TypeKind::Pack:
  case TypeKind::PackExpansion:
  case TypeKind::PackElement:
  case TypeKind::SILPack:
  case TypeKind::BuiltinTuple:
  case TypeKind::ErrorUnion:
  case TypeKind::Integer:
  case TypeKind::BuiltinUnboundGeneric:
  case TypeKind::BuiltinFixedArray:
#define REF_STORAGE(Name, ...) \
  case TypeKind::Name##Storage:
#include "swift/AST/ReferenceStorage.def"
    return false;

  case TypeKind::GenericTypeParam:
  case TypeKind::DependentMember:
    assert(sig && "dependent types can't answer reference semantics query");
    return sig->requiresClass(type);
  }

  llvm_unreachable("Unhandled type kind!");
}

/// Are variables of this type permitted to have
/// ownership attributes?
///
/// This includes:
///   - class types, generic or not
///   - archetypes with class or class protocol bounds
///   - existentials with class or class protocol bounds
/// But not:
///   - function types
bool TypeBase::allowsOwnership(const GenericSignatureImpl *sig) {
  return getCanonicalType().allowsOwnership(sig);
}

static void expandDefaults(SmallVectorImpl<ProtocolDecl *> &protocols,
                           InvertibleProtocolSet inverses,
                           ASTContext &ctx) {
  for (auto ip : InvertibleProtocolSet::allKnown()) {
    if (!inverses.contains(ip)) {
      auto *proto = ctx.getProtocol(getKnownProtocolKind(ip));
      protocols.push_back(proto);
    }
  }

  ProtocolType::canonicalizeProtocols(protocols);
}

ExistentialLayout::ExistentialLayout(CanProtocolType type) {
  auto *protoDecl = type->getDecl();

  hasExplicitAnyObject = false;
  containsObjCProtocol = protoDecl->isObjC();
  containsSwiftProtocol = (!protoDecl->isObjC() &&
                           !protoDecl->isMarkerProtocol());
  representsAnyObject = false;

  protocols.push_back(protoDecl);
  expandDefaults(protocols, InvertibleProtocolSet(), type->getASTContext());
}

ExistentialLayout::ExistentialLayout(CanProtocolCompositionType type) {
  hasExplicitAnyObject = type->hasExplicitAnyObject();
  containsObjCProtocol = false;
  containsSwiftProtocol = false;

  auto members = type.getMembers();
  if (!members.empty() &&
      (members[0].getClassOrBoundGenericClass() ||
       isa<UnboundGenericType>(members[0]))) {
    explicitSuperclass = members[0];
    members = members.slice(1);
  }

  for (auto member : members) {
    ProtocolDecl *protoDecl;
    if (auto protocolType = dyn_cast<ProtocolType>(member)) {
      protoDecl = protocolType->getDecl();
    } else {
      auto *parameterizedType = member->castTo<ParameterizedProtocolType>();
      protoDecl = parameterizedType->getProtocol();
      parameterized.push_back(parameterizedType);
    }
    if (protoDecl->isObjC())
      containsObjCProtocol = true;
    else if (!protoDecl->isMarkerProtocol())
      containsSwiftProtocol = true;
    protocols.push_back(protoDecl);
  }

  auto inverses = type->getInverses();
  expandDefaults(protocols, inverses, type->getASTContext());

  representsAnyObject = [&]() {
    if (!hasExplicitAnyObject)
      return false;

    if (explicitSuperclass)
      return false;

    if (!inverses.empty())
      return false;

    for (auto *proto : protocols) {
      if (!proto->getInvertibleProtocolKind())
        return false;
    }

    return true;
  }();
}

ExistentialLayout::ExistentialLayout(CanParameterizedProtocolType type)
    : ExistentialLayout(type.getBaseType()) {
  parameterized.push_back(type);
}

ExistentialLayout TypeBase::getExistentialLayout() {
  return getCanonicalType().getExistentialLayout();
}

ExistentialLayout CanType::getExistentialLayout() {
  CanType ty = *this;

  // Always remove one layer of move only ness.
  if (auto mv = dyn_cast<SILMoveOnlyWrappedType>(ty))
    ty = mv->getInnerType();

  if (auto existential = dyn_cast<ExistentialType>(ty))
    return existential->getConstraintType()->getExistentialLayout();

  if (auto metatype = dyn_cast<ExistentialMetatypeType>(ty))
    return metatype->getInstanceType()->getExistentialLayout();

  if (auto proto = dyn_cast<ProtocolType>(ty))
    return ExistentialLayout(proto);

  if (auto param = dyn_cast<ParameterizedProtocolType>(ty))
    return ExistentialLayout(param);

  auto comp = cast<ProtocolCompositionType>(ty);
  return ExistentialLayout(comp);
}

bool ExistentialLayout::requiresClass() const {
  if (hasExplicitAnyObject || explicitSuperclass)
    return true;

  for (auto proto : getProtocols()) {
    if (proto->requiresClass())
      return true;
  }

  return false;
}

Type ExistentialLayout::getSuperclass() const {
  if (explicitSuperclass)
    return explicitSuperclass;

  for (auto protoDecl : getProtocols()) {
    auto genericSig = protoDecl->getGenericSignature();
    if (auto superclass = genericSig->getSuperclassBound(
          protoDecl->getSelfInterfaceType()))
      return superclass;
  }

  return Type();
}

bool TypeBase::isObjCExistentialType() {
  return getCanonicalType().isObjCExistentialType();
}

bool TypeBase::isTypeErasedGenericClassType() {
  return getCanonicalType().isTypeErasedGenericClassType();
}

bool CanType::isObjCExistentialTypeImpl(CanType type) {
  if (!type.isExistentialType())
    return false;

  return type.getExistentialLayout().isObjC();
}

bool CanType::isTypeErasedGenericClassTypeImpl(CanType type) {
  if (auto nom = type->getAnyNominal())
    return nom->isTypeErasedGenericClass();
  return false;
}

NominalTypeDecl *TypeBase::getAnyActor() {
  // Nominal types: check whether the declaration is an actor.
  if (auto nominal = getAnyNominal()) {
    if (nominal->isAnyActor())
      return nominal;
  }

  // Archetypes check for conformance to Actor.
  if (auto archetype = getAs<ArchetypeType>()) {
    for (auto proto : archetype->getConformsTo()) {
      if (proto->isAnyActor())
        return proto;
    }

    return nullptr;
  }

  if (auto self = getAs<DynamicSelfType>()) {
    return self->getSelfType()->getAnyActor();
  }

  // Existential types: check for Actor protocol.
  if (isExistentialType()) {
    auto layout = getExistentialLayout();
    if (auto superclass = layout.getSuperclass()) {
      if (auto actor = superclass->getAnyActor())
        return actor;
    }

    for (auto proto : layout.getProtocols()) {
      if (proto->isAnyActor())
        return proto;
    }

    return nullptr;
  }

  return nullptr;
}

bool TypeBase::isActorType() {
  if (auto actor = getAnyActor())
    return actor->isActor();
  return false;
}

bool TypeBase::isAnyActorType() {
  if (auto actor = getAnyActor())
    return actor->isAnyActor();
  return false;
}

bool TypeBase::isDistributedActor() {
  if (auto actor = getAnyActor())
    return actor->isDistributedActor();
  return false;
}

std::optional<KnownProtocolKind> TypeBase::getKnownProtocol() {
  if (auto protoTy = this->getAs<ProtocolType>())
    if (auto protoDecl = protoTy->getDecl())
      return protoDecl->getKnownProtocolKind();

  return std::nullopt;
}

bool TypeBase::isSpecialized() {
  Type t = getCanonicalType();

  for (;;) {
    if (!t || !t->getAnyNominal())
      return false;
    if (t->is<BoundGenericType>())
      return true;
    t = t->getNominalParent();
  }

  return false;
}

bool TypeBase::hasLocalArchetypeFromEnvironment(
    GenericEnvironment *env) const {
  if (!hasLocalArchetype())
    return false;

  return getCanonicalType().findIf([&](Type type) -> bool {
    auto *local = dyn_cast<LocalArchetypeType>(type.getPointer());
    return local && local->getGenericEnvironment() == env;
  });
}

Type TypeBase::addCurriedSelfType(const DeclContext *dc) {
  if (!dc->isTypeContext())
    return this;

  auto *type = this;

  GenericSignature sig = dc->getGenericSignatureOfContext();
  if (auto *genericFn = type->getAs<GenericFunctionType>()) {
    sig = genericFn->getGenericSignature();
    type = FunctionType::get(genericFn->getParams(),
                             genericFn->getResult(),
                             genericFn->getExtInfo());
  }

  auto selfTy = dc->getSelfInterfaceType();
  auto selfParam = AnyFunctionType::Param(selfTy);
  // FIXME: Verify ExtInfo state is correct, not working by accident.
  if (sig) {
    GenericFunctionType::ExtInfo info;
    return GenericFunctionType::get(sig, {selfParam}, type, info);
  }
  FunctionType::ExtInfo info;
  return FunctionType::get({selfParam}, type, info);
}

void TypeBase::getTypeVariables(
    SmallPtrSetImpl<TypeVariableType *> &typeVariables) {
  // If we know we don't have any type variables, we're done.
  if (hasTypeVariable()) {
    auto addTypeVariables = [&](Type type) -> bool {
      if (auto tv = dyn_cast<TypeVariableType>(type.getPointer())) {
        typeVariables.insert(tv);
      }

      return false;
    };

    // Use Type::findIf() to walk the types, finding type variables along the
    // way.
    getCanonicalType().findIf(addTypeVariables);
    Type(this).findIf(addTypeVariables);
    assert((!typeVariables.empty() || hasError()) &&
           "Did not find type variables!");
  }
}

static bool isLegalSILType(CanType type);

static bool isLegalSILTypeOrPackExpansion(CanType type) {
  // Pack expansions aren't legal in arbitrary positions in SIL;
  // for example, we should never see a function parameter or result
  // of pack-expansion type.  But they're allowed within SILPackTypes
  // and SIL TupleTypes as long as their pattern types are legal.
  // The count type should always be an AST type.
  if (auto packExpansionType = dyn_cast<PackExpansionType>(type)) {
    return isLegalSILType(packExpansionType.getPatternType());
  }

  return isLegalSILType(type);
}

static bool isLegalSILType(CanType type) {
  // L-values and inouts are not legal.
  if (!type->isMaterializable()) return false;

  // Function types must be lowered.
  if (isa<AnyFunctionType>(type)) return false;

  // Metatypes must have a representation.
  if (auto meta = dyn_cast<AnyMetatypeType>(type))
    return meta->hasRepresentation();

  // Tuples are legal if all their elements are legal.
  if (auto tupleType = dyn_cast<TupleType>(type)) {
    for (auto eltType : tupleType.getElementTypes()) {
      if (!isLegalSILTypeOrPackExpansion(eltType)) return false;
    }
    return true;
  }

  // Packs must be lowered.
  if (isa<PackType>(type)) return false;

  // Optionals are legal if their object type is legal.
  if (auto objectType = type.getOptionalObjectType()) {
    return isLegalSILType(objectType);
  }

  // Reference storage types are legal if their object type is legal.
  if (auto refType = dyn_cast<ReferenceStorageType>(type))
    return isLegalSILType(refType.getReferentType());

  return true;
}

bool TypeBase::isLegalSILType() {
  return ::isLegalSILType(getCanonicalType());
}

static bool isLegalFormalType(CanType type) {
  // L-values and inouts are not formal types.
  if (!type->isMaterializable()) return false;

  // Function types must not be lowered.
  if (isa<SILFunctionType>(type)) return false;

  // Pack types must not be lowered.
  if (isa<SILPackType>(type)) return false;

  // Reference storage types are not formal types.
  if (isa<ReferenceStorageType>(type)) return false;

  // Metatypes must not have a representation.
  if (auto meta = dyn_cast<AnyMetatypeType>(type))
    return !meta->hasRepresentation();

  // Tuples are legal if all their elements are legal.
  if (auto tupleType = dyn_cast<TupleType>(type)) {
    for (auto eltType : tupleType.getElementTypes()) {
      if (!isLegalFormalType(eltType)) return false;
    }
    return true;
  }

  // Optionals are legal if their object type is legal.
  if (auto objectType = type.getOptionalObjectType()) {
    return isLegalFormalType(objectType);
  }

  // Expansions are legal if their pattern type is legal.
  if (auto expansionType = dyn_cast<PackExpansionType>(type)) {
    return isLegalFormalType(expansionType.getPatternType());
  }

  return true;
}

bool TypeBase::isLegalFormalType() {
  return ::isLegalFormalType(getCanonicalType());
}

bool TypeBase::hasTypeRepr() const {
  // A type has a source-printable representation if none of its sub-pieces do
  // /not/ have a source-printable representation.
  return !Type(const_cast<TypeBase *>(this)).findIf([](Type subTy) -> bool {
    switch (subTy->getKind()) {
    case TypeKind::Error:
    case TypeKind::Unresolved:
    case TypeKind::TypeVariable:
      return true;

    case TypeKind::OpenedArchetype:
    case TypeKind::OpaqueTypeArchetype:
    case TypeKind::GenericFunction:
    case TypeKind::LValue:
      return true;

#define REF_STORAGE(Name, ...) \
    case TypeKind::Name##Storage: return true;
#include "swift/AST/ReferenceStorage.def"

    case TypeKind::SILFunction:
    case TypeKind::SILBlockStorage:
    case TypeKind::SILBox:
    case TypeKind::SILToken:
      return true;

    default:
      return false;
    }
  });
}

bool TypeBase::isVoid() {
  if (auto TT = getAs<TupleType>())
    return TT->getNumElements() == 0;
  return false;
}

#define KNOWN_STDLIB_TYPE_DECL(NAME, DECL_CLASS, NUM_GENERIC_PARAMS) \
/** Check if this type is equal to Swift.NAME. */ \
bool TypeBase::is##NAME() { \
  if (auto generic = getAnyGeneric()) { \
    if (isa<DECL_CLASS>(generic)) { \
      return getASTContext().get##NAME##Decl() == generic; \
    } \
  } \
  return false; \
}
#include "swift/AST/KnownStdlibTypes.def"

Type TypeBase::getRValueType() {
  // If the type is not an lvalue, this is a no-op.
  if (!hasLValueType())
    return this;

  return Type(this).transformRec([](TypeBase *t) -> std::optional<Type> {
      if (auto *lvalueTy = dyn_cast<LValueType>(t))
        return lvalueTy->getObjectType();
      return std::nullopt;
    });
}

Type TypeBase::getOptionalObjectType() {
  if (auto boundTy = getAs<BoundGenericEnumType>())
    if (boundTy->getDecl()->isOptionalDecl())
      return boundTy->getGenericArgs()[0];
  return Type();
}

CanType CanType::getOptionalObjectTypeImpl(CanType type) {
  if (auto boundTy = dyn_cast<BoundGenericEnumType>(type))
    if (boundTy->getDecl()->isOptionalDecl())
      return boundTy.getGenericArgs()[0];
  return CanType();
}

Type TypeBase::wrapInOptionalType() const {
  auto &ctx = getASTContext();
  auto *result = BoundGenericEnumType::get(ctx.getOptionalDecl(), Type(),
                                           { getCanonicalType() });
  return result;
}

CanType CanType::wrapInOptionalTypeImpl(CanType type) {
  return type->wrapInOptionalType()->getCanonicalType();
}

Type TypeBase::isArrayType() {
  if (auto boundStruct = getAs<BoundGenericStructType>()) {
    if (boundStruct->getDecl() == getASTContext().getArrayDecl())
      return boundStruct->getGenericArgs()[0];
  }
  return Type();
}

Type TypeBase::getAnyPointerElementType(PointerTypeKind &PTK) {
  auto &C = getASTContext();
  if (isUnsafeMutableRawPointer()) {
    PTK = PTK_UnsafeMutableRawPointer;
    return C.TheEmptyTupleType;
  }
  if (isUnsafeRawPointer()) {
    PTK = PTK_UnsafeRawPointer;
    return C.TheEmptyTupleType;
  }
  if (auto boundTy = getAs<BoundGenericType>()) {
    if (boundTy->isUnsafeMutablePointer()) {
      PTK = PTK_UnsafeMutablePointer;
    } else if (boundTy->isUnsafePointer()) {
      PTK = PTK_UnsafePointer;
    } else if (boundTy->isAutoreleasingUnsafeMutablePointer()) {
      PTK = PTK_AutoreleasingUnsafeMutablePointer;
    } else {
      return Type();
    }
    return boundTy->getGenericArgs()[0];
  }
  return Type();
}

Type TypeBase::wrapInPointer(PointerTypeKind kind) {
  ASTContext &ctx = getASTContext();
  NominalTypeDecl *pointerDecl = ([&ctx, kind] {
    switch (kind) {
    case PTK_UnsafeMutableRawPointer:
    case PTK_UnsafeRawPointer:
      // these pointer types don't take arguments.
      return (NominalTypeDecl*)nullptr;
    case PTK_UnsafePointer:
      return ctx.getUnsafePointerDecl();
    case PTK_UnsafeMutablePointer:
      return ctx.getUnsafeMutablePointerDecl();
    case PTK_AutoreleasingUnsafeMutablePointer:
      return ctx.getAutoreleasingUnsafeMutablePointerDecl();
    }
    llvm_unreachable("bad kind");
  }());

  assert(pointerDecl);
  // Don't fail hard on null pointerDecl.
  if (!pointerDecl) {
    return Type();
  }
  return BoundGenericType::get(pointerDecl, /*parent*/nullptr, Type(this));
}

Type TypeBase::getAnyBufferPointerElementType(BufferPointerTypeKind &BPTK) {
  auto &C = getASTContext();
  if (isUnsafeMutableRawBufferPointer()) {
    BPTK = BPTK_UnsafeMutableRawBufferPointer;
    return C.TheEmptyTupleType;
  }
  if (isUnsafeRawBufferPointer()) {
    BPTK = BPTK_UnsafeRawBufferPointer;
    return C.TheEmptyTupleType;
  }
  if (auto boundTy = getAs<BoundGenericType>()) {
    if (boundTy->isUnsafeMutableBufferPointer()) {
      BPTK = BPTK_UnsafeMutableBufferPointer;
    } else if (boundTy->isUnsafeBufferPointer()) {
      BPTK = BPTK_UnsafeBufferPointer;
    } else {
      return Type();
    }
    return boundTy->getGenericArgs()[0];
  }
  return Type();
}

Type TypeBase::lookThroughSingleOptionalType() {
  Type type(this);
  if (auto objType = type->getOptionalObjectType())
    type = objType;
  return type;
}

Type TypeBase::lookThroughAllOptionalTypes() {
  Type type(this);
  while (auto objType = type->getOptionalObjectType())
    type = objType;

  return type;
}

Type TypeBase::lookThroughAllOptionalTypes(SmallVectorImpl<Type> &optionals){
  Type type(this);
  while (auto objType = type->getOptionalObjectType()) {
    optionals.push_back(type);
    type = objType;
  }

  return type;
}

unsigned int TypeBase::getOptionalityDepth() {
  Type type(this);
  unsigned int depth = 0;
  while (auto objType = type->getOptionalObjectType()) {
    type = objType;
    ++depth;
  }
  return depth;
}

Type TypeBase::stripConcurrency(bool recurse, bool dropGlobalActor) {
  // Look through optionals.
  if (Type optionalObject = getOptionalObjectType()) {
    Type newOptionalObject =
        optionalObject->stripConcurrency(recurse, dropGlobalActor);
    if (optionalObject->isEqual(newOptionalObject))
      return Type(this);

    return OptionalType::get(newOptionalObject);
  }

  // Function types.
  if (auto fnType = getAs<AnyFunctionType>()) {
    // Strip off Sendable and (possibly) the global actor.
    ASTExtInfo extInfo =
        fnType->hasExtInfo() ? fnType->getExtInfo() : ASTExtInfo();
    extInfo = extInfo.withSendable(false);
    if (dropGlobalActor)
      extInfo = extInfo.withoutIsolation();

    ArrayRef<AnyFunctionType::Param> params = fnType->getParams();
    Type resultType = fnType->getResult();

    SmallVector<AnyFunctionType::Param, 4> newParams;
    if (recurse) {
      for (unsigned paramIdx : indices(params)) {
        const auto &param = params[paramIdx];
        Type newParamType = param.getPlainType()->stripConcurrency(
            recurse, dropGlobalActor);

        if (!newParams.empty()) {
          newParams.push_back(param.withType(newParamType));
          continue;
        }

        if (newParamType->isEqual(param.getPlainType()))
          continue;

        newParams.append(params.begin(), params.begin() + paramIdx);
        newParams.push_back(param.withType(newParamType));
      }

      if (!newParams.empty())
        params = newParams;

      resultType = resultType->stripConcurrency(recurse, dropGlobalActor);
    }

    // Drop Sendable requirements.
    GenericSignature genericSig;
    if (auto genericFnType = dyn_cast<GenericFunctionType>(fnType)) {
      auto requirements = genericFnType->getRequirements();
      SmallVector<Requirement, 4> newRequirements;
      for (unsigned reqIdx : indices(requirements)) {
        // If it's a Sendable requirement, skip it.
        const auto &req = requirements[reqIdx];
        if (req.getKind() == RequirementKind::Conformance &&
            req.getProtocolDecl()
              ->isSpecificProtocol(KnownProtocolKind::Sendable))
          continue;

        newRequirements.push_back(req);
      }

      if (newRequirements.size() == requirements.size()) {
        genericSig = genericFnType->getGenericSignature();
      } else {
        genericSig = GenericSignature::get(
            genericFnType->getGenericParams(), newRequirements);
      }
    }

    Type newFnType;
    if (genericSig) {
      newFnType = GenericFunctionType::get(
          genericSig, params, resultType, extInfo);
    } else {
      newFnType = FunctionType::get(params, resultType, extInfo);
    }
    if (newFnType->isEqual(this))
      return Type(this);

    return newFnType;
  }

  if (auto existentialType = getAs<ExistentialType>()) {
    auto newConstraintType = existentialType->getConstraintType()
        ->stripConcurrency(recurse, dropGlobalActor);
    if (newConstraintType.getPointer() ==
            existentialType->getConstraintType().getPointer())
      return Type(this);

    if (newConstraintType->getClassOrBoundGenericClass())
      return newConstraintType;

    return ExistentialType::get(newConstraintType);
  }

  if (auto protocolType = getAs<ProtocolType>()) {
    if (protocolType->getDecl()->isSpecificProtocol(
            KnownProtocolKind::Sendable))
      return getASTContext().TheAnyType;

    return Type(this);
  }

  if (auto protocolCompositionType = getAs<ProtocolCompositionType>()) {
    SmallVector<Type, 4> newMembers;
    auto members = protocolCompositionType->getMembers();
    for (unsigned i : indices(members)) {
      auto memberType = members[i];
      auto newMemberType =
          memberType->stripConcurrency(recurse, dropGlobalActor);
      if (!newMembers.empty()) {
        newMembers.push_back(newMemberType);
        continue;
      }

      if (memberType.getPointer() != newMemberType.getPointer()) {
        newMembers.append(members.begin(), members.begin() + i);
        newMembers.push_back(newMemberType);
        continue;
      }
    }

    if (!newMembers.empty()) {
      return ProtocolCompositionType::get(
          getASTContext(), newMembers,
          protocolCompositionType->getInverses(),
          protocolCompositionType->hasExplicitAnyObject());
    }

    return Type(this);
  }

  if (auto existentialMetatype = getAs<ExistentialMetatypeType>()) {
    auto instanceType = existentialMetatype->getExistentialInstanceType();
    auto newInstanceType =
        instanceType->stripConcurrency(recurse, dropGlobalActor);
    if (instanceType.getPointer() != newInstanceType.getPointer()) {
      std::optional<MetatypeRepresentation> repr;
      if (existentialMetatype->hasRepresentation())
        repr = existentialMetatype->getRepresentation();
      return ExistentialMetatypeType::get(
          newInstanceType, repr, getASTContext());
    }

    return Type(this);
  }

  if (auto *BGT = getAs<BoundGenericType>()) {
    if (!recurse)
      return Type(this);

    bool anyChanged = false;
    SmallVector<Type, 2> genericArgs;
    llvm::transform(BGT->getGenericArgs(), std::back_inserter(genericArgs),
                    [&](Type argTy) {
                      auto newArgTy =
                          argTy->stripConcurrency(recurse, dropGlobalActor);
                      anyChanged |= !newArgTy->isEqual(argTy);
                      return newArgTy;
                    });

    return anyChanged ? BoundGenericType::get(BGT->getDecl(), BGT->getParent(),
                                              genericArgs)
                      : Type(this);
  }

  if (auto *tuple = getAs<TupleType>()) {
    if (!recurse)
      return Type(this);

    bool anyChanged = false;
    SmallVector<TupleTypeElt, 2> elts;
    llvm::transform(
        tuple->getElements(), std::back_inserter(elts), [&](const auto &elt) {
          auto eltTy = elt.getType();
          auto strippedTy = eltTy->stripConcurrency(recurse, dropGlobalActor);
          anyChanged |= !strippedTy->isEqual(eltTy);
          return elt.getWithType(strippedTy);
        });

    return anyChanged ? TupleType::get(elts, getASTContext()) : Type(this);
  }

  if (auto *arrayTy = dyn_cast<ArraySliceType>(this)) {
    auto newBaseTy =
        arrayTy->getBaseType()->stripConcurrency(recurse, dropGlobalActor);
    return newBaseTy->isEqual(arrayTy->getBaseType())
               ? Type(this)
               : ArraySliceType::get(newBaseTy);
  }

  if (auto *dictTy = dyn_cast<DictionaryType>(this)) {
    auto keyTy = dictTy->getKeyType();
    auto strippedKeyTy = keyTy->stripConcurrency(recurse, dropGlobalActor);
    auto valueTy = dictTy->getValueType();
    auto strippedValueTy = valueTy->stripConcurrency(recurse, dropGlobalActor);

    return keyTy->isEqual(strippedKeyTy) && valueTy->isEqual(strippedValueTy)
               ? Type(this)
               : DictionaryType::get(strippedKeyTy, strippedValueTy);
  }

  return Type(this);
}

bool TypeBase::isAnyObject() {
  auto canTy = getCanonicalType();

  if (!canTy.isExistentialType() || canTy.isForeignReferenceType())
    return false;

  return canTy.getExistentialLayout().isAnyObject();
}

bool ExistentialLayout::isErrorExistential() const {
  auto protocols = getProtocols();
  return (!hasExplicitAnyObject &&
          !explicitSuperclass &&
          protocols.size() == 1 &&
          protocols[0]->isSpecificProtocol(KnownProtocolKind::Error));
}

bool ExistentialLayout::isExistentialWithError(ASTContext &ctx) const {
  auto errorProto = ctx.getProtocol(KnownProtocolKind::Error);
  if (!errorProto) return false;

  for (auto protoDecl : getProtocols()) {
    if (protoDecl == errorProto || protoDecl->inheritsFrom(errorProto))
      return true;
  }

  return false;
}

LayoutConstraint ExistentialLayout::getLayoutConstraint() const {
  if (hasExplicitAnyObject) {
    return LayoutConstraint::getLayoutConstraint(
      LayoutConstraintKind::Class);
  }

  return LayoutConstraint();
}

bool TypeBase::isExistentialWithError() {
  auto canTy = getCanonicalType();

  if (!canTy.isExistentialType()) return false;

  // FIXME: Compute this as a bit in TypeBase so this operation isn't
  // overly expensive.
  auto layout = canTy.getExistentialLayout();
  return layout.isExistentialWithError(getASTContext());
}

bool TypeBase::isOpenedExistentialWithError() {
  if (auto archetype = getAs<OpenedArchetypeType>()) {
    auto errorProto = getASTContext().getErrorDecl();
    if (!errorProto) return false;

    for (auto protoDecl : archetype->getConformsTo()) {
      if (protoDecl == errorProto || protoDecl->inheritsFrom(errorProto))
        return true;
    }
  }
  return false;
}

bool TypeBase::isStdlibType() {
  if (auto *NTD = getAnyNominal()) {
    auto *DC = NTD->getDeclContext();
    return DC->isModuleScopeContext() &&
           DC->getParentModule()->isStdlibModule();
  }
  return false;
}

bool TypeBase::isCGFloat() {
  auto *NTD = getAnyNominal();
  if (!NTD)
    return false;

  auto *DC = NTD->getDeclContext();
  if (!DC->isModuleScopeContext())
    return false;

  auto *module = DC->getParentModule();
  // On macOS `CGFloat` is part of a `CoreGraphics` module,
  // but on Linux it could be found in `Foundation`.
  return (module->getName().is("CoreGraphics") ||
          module->getName().is("Foundation")   ||
          module->getName().is("CoreFoundation")) &&
         NTD->getName().is("CGFloat");
}

bool TypeBase::isKnownStdlibCollectionType() {
  if (isArray() || isDictionary() || isSet()) {
    return true;
  }

  return false;
}

/// Remove argument labels from the function type.
Type TypeBase::removeArgumentLabels(unsigned numArgumentLabels) {
  // If there is nothing to remove, don't.
  if (numArgumentLabels == 0) return Type(this);

  auto fnType = castTo<AnyFunctionType>();

  // Drop argument labels from the input type.
  llvm::SmallVector<AnyFunctionType::Param, 8> unlabeledParams;
  unlabeledParams.reserve(fnType->getNumParams());
  for (const auto &param : fnType->getParams())
    unlabeledParams.push_back(param.getWithoutLabels());

  auto result = fnType->getResult()
                      ->removeArgumentLabels(numArgumentLabels - 1);

  if (auto *genericFnType = dyn_cast<GenericFunctionType>(fnType)) {
    return GenericFunctionType::get(genericFnType->getGenericSignature(),
                                    unlabeledParams, result,
                                    fnType->getExtInfo());
  }

  return FunctionType::get(unlabeledParams, result, fnType->getExtInfo());
}

Type TypeBase::replaceCovariantResultType(Type newResultType,
                                          unsigned uncurryLevel) {
  if (uncurryLevel == 0) {
    bool isLValue = is<LValueType>();

    auto loadedTy = getWithoutSpecifierType();
    if (auto objectType = loadedTy->getOptionalObjectType()) {
      newResultType = OptionalType::get(
          objectType->replaceCovariantResultType(newResultType, uncurryLevel));
    }

    return isLValue ? LValueType::get(newResultType) : newResultType;
  }

  // Determine the input and result types of this function.
  auto fnType = this->castTo<AnyFunctionType>();
  auto inputType = fnType->getParams();
  Type resultType =
    fnType->getResult()->replaceCovariantResultType(newResultType,
                                                    uncurryLevel - 1);

  // Produce the resulting function type.
  if (auto genericFn = dyn_cast<GenericFunctionType>(fnType)) {
    return GenericFunctionType::get(genericFn->getGenericSignature(),
                                    inputType, resultType,
                                    fnType->getExtInfo());
  }
  
  return FunctionType::get(inputType, resultType, fnType->getExtInfo());
}

/// Whether this parameter accepts an unlabeled trailing closure argument
/// using the more-restrictive forward-scan rule.
static bool allowsUnlabeledTrailingClosureParameter(const ParamDecl *param) {
  // inout parameters never allow an unlabeled trailing closure.
  if (param->isInOut())
    return false;

  Type paramType = param->isVariadic() ? param->getVarargBaseTy()
                                       : param->getInterfaceType();
  paramType = paramType->getRValueType()->lookThroughAllOptionalTypes();

  // For autoclosure parameters, look through the autoclosure result type
  // to get the actual argument type.
  if (param->isAutoClosure()) {
    auto fnType = paramType->getAs<AnyFunctionType>();
    if (!fnType)
      return false;

    paramType = fnType->getResult()->lookThroughAllOptionalTypes();
  }

  // After lookup through all optional types, this parameter allows an
  // unlabeled trailing closure if it is (structurally) a function type.
  return paramType->is<AnyFunctionType>();
}

ParameterListInfo::ParameterListInfo(
    ArrayRef<AnyFunctionType::Param> params,
    const ValueDecl *paramOwner,
    bool skipCurriedSelf) {
  defaultArguments.resize(params.size());
  propertyWrappers.resize(params.size());
  implicitSelfCapture.resize(params.size());
  inheritActorContext.resize(params.size());
  variadicGenerics.resize(params.size());
  sendingParameters.resize(params.size());

  // No parameter owner means no parameter list means no default arguments
  // - hand back the zeroed bitvector.
  //
  // FIXME: We ought to not request parameter list info in this case.
  if (!paramOwner)
    return;

  // If the decl has a curried self, but we're not allowed to skip it, return.
  if (paramOwner->hasCurriedSelf() && !skipCurriedSelf)
    return;

  // Find the corresponding parameter list.
  const ParameterList *paramList =
      getParameterList(const_cast<ValueDecl *>(paramOwner));

  // No parameter list means no default arguments - hand back the zeroed
  // bitvector.
  if (!paramList) {
    assert(!paramOwner->hasParameterList());
    return;
  }

  if (params.empty())
    return;

  // Arguments and parameters are not guaranteed to always line-up
  // perfectly, e.g. failure diagnostics tries to match argument type
  // to different "candidate" parameters.
  if (params.size() != paramList->size())
    return;

  // Now we have enough information to determine which parameters accept
  // unlabeled trailing closures.
  acceptsUnlabeledTrailingClosures.resize(params.size());

  // Note which parameters have default arguments and/or accept unlabeled
  // trailing closure arguments with the forward-scan rule.
  for (auto i : range(0, params.size())) {
    auto param = paramList->get(i);
    if (param->isDefaultArgument()) {
      defaultArguments.set(i);
    }

    if (allowsUnlabeledTrailingClosureParameter(param)) {
      acceptsUnlabeledTrailingClosures.set(i);
    }

    if (param->hasExternalPropertyWrapper()) {
      propertyWrappers.set(i);
    }

    if (param->getAttrs().hasAttribute<ImplicitSelfCaptureAttr>()) {
      implicitSelfCapture.set(i);
    }

    if (param->getAttrs().hasAttribute<InheritActorContextAttr>()) {
      inheritActorContext.set(i);
    }

    if (param->getInterfaceType()->is<PackExpansionType>()) {
      variadicGenerics.set(i);
    }

    if (param->isSending()) {
      sendingParameters.set(i);
    }
  }
}

bool ParameterListInfo::hasDefaultArgument(unsigned paramIdx) const {
  return paramIdx < defaultArguments.size() ? defaultArguments[paramIdx]
      : false;
}

bool ParameterListInfo::acceptsUnlabeledTrailingClosureArgument(
    unsigned paramIdx) const {
  return paramIdx >= acceptsUnlabeledTrailingClosures.size() ||
      acceptsUnlabeledTrailingClosures[paramIdx];
}

bool ParameterListInfo::hasExternalPropertyWrapper(unsigned paramIdx) const {
  return paramIdx < propertyWrappers.size() ? propertyWrappers[paramIdx] : false;
}

bool ParameterListInfo::isImplicitSelfCapture(unsigned paramIdx) const {
  return paramIdx < implicitSelfCapture.size()
      ? implicitSelfCapture[paramIdx]
      : false;
}

bool ParameterListInfo::inheritsActorContext(unsigned paramIdx) const {
  return paramIdx < inheritActorContext.size()
      ? inheritActorContext[paramIdx]
      : false;
}

bool ParameterListInfo::isVariadicGenericParameter(unsigned paramIdx) const {
  return paramIdx < variadicGenerics.size()
      ? variadicGenerics[paramIdx]
      : false;
}

bool ParameterListInfo::isSendingParameter(unsigned paramIdx) const {
  return paramIdx < sendingParameters.size() ? sendingParameters[paramIdx]
                                             : false;
}

/// Turn a param list into a symbolic and printable representation that does not
/// include the types, something like (_:, b:, c:)
std::string swift::getParamListAsString(ArrayRef<AnyFunctionType::Param> params) {
  std::string result = "(";

  interleave(params,
             [&](const AnyFunctionType::Param &param) {
               if (!param.getLabel().empty())
                 result += param.getLabel().str();
               else
                 result += "_";
               result += ":";
             },
             [&] { result += ", "; });

  result += ')';
  return result;
}

/// Rebuilds the given 'self' type using the given object type as the
/// replacement for the object type of self.
static AnyFunctionType::Param
rebuildSelfTypeWithObjectType(AnyFunctionType::Param selfParam,
                              Type objectTy) {
  if (selfParam.getPlainType()->getAs<MetatypeType>())
    objectTy = MetatypeType::get(objectTy);

  return selfParam.withType(objectTy);
}

/// Returns a new function type exactly like this one but with the self
/// parameter replaced. Only makes sense for members of classes.
Type TypeBase::replaceSelfParameterType(Type newSelf) {
  auto fnTy = castTo<AnyFunctionType>();

  auto params = fnTy->getParams();
  assert(params.size() == 1);
  auto selfParam = rebuildSelfTypeWithObjectType(params[0], newSelf);

  if (auto genericFnTy = getAs<GenericFunctionType>()) {
    return GenericFunctionType::get(genericFnTy->getGenericSignature(),
                                    {selfParam},
                                    fnTy->getResult(),
                                    fnTy->getExtInfo());
  }

  return FunctionType::get({selfParam},
                           fnTy->getResult(),
                           fnTy->getExtInfo());
}

/// Look through a metatype, or just return the original type if it is
/// not a metatype.
Type TypeBase::getMetatypeInstanceType() {
  if (auto existentialMetaType = getAs<ExistentialMetatypeType>())
    return existentialMetaType->getExistentialInstanceType();

  if (auto metaTy = getAs<AnyMetatypeType>())
    return metaTy->getInstanceType();

  return this;
}

using ParameterizedProtocolMap =
  llvm::DenseMap<ProtocolDecl *, ParameterizedProtocolType *>;

/// Collect the protocols in the existential type T into the given
/// vector.
static void addProtocols(Type T,
                         SmallVectorImpl<ProtocolDecl *> &Protocols,
                         ParameterizedProtocolMap &Parameterized,
                         Type &Superclass,
                         InvertibleProtocolSet &Inverses,
                         bool &HasExplicitAnyObject) {
  if (auto Proto = T->getAs<ProtocolType>()) {
    Protocols.push_back(Proto->getDecl());
    return;
  }

  if (auto PC = T->getAs<ProtocolCompositionType>()) {
    Inverses.insertAll(PC->getInverses());
    HasExplicitAnyObject |= PC->hasExplicitAnyObject();
    for (auto P : PC->getMembers()) {
      addProtocols(P, Protocols, Parameterized, Superclass, Inverses,
                   HasExplicitAnyObject);
    }
    return;
  }

  if (auto PP = T->getAs<ParameterizedProtocolType>()) {
    Parameterized.insert({PP->getProtocol(), PP});
    Protocols.push_back(PP->getProtocol());
    return;
  }

  assert(isa<ClassDecl>(T->getAnyNominal()) && "Non-class, non-protocol "
         "member in protocol composition");
  assert((!Superclass || Superclass->isEqual(T)) &&
         "Should have diagnosed multiple superclasses by now");
  Superclass = T;
}

static void canonicalizeProtocols(SmallVectorImpl<ProtocolDecl *> &protocols,
                                  ParameterizedProtocolMap *parameterized) {
  // Skip a bunch of useless work.
  if (protocols.size() <= 1)
    return;

  llvm::SmallDenseMap<ProtocolDecl *, unsigned> known;
  bool zappedAny = false;

  // Seed the stack with the protocol declarations in the original list.
  // Zap any obvious duplicates along the way.
  for (unsigned i : indices(protocols)) {
    // If we have not seen this protocol before, record its index.
    if (known.count(protocols[i]) == 0) {
      known[protocols[i]] = i;
      continue;
    }

    // We have seen this protocol before; zap this occurrence.
    protocols[i] = nullptr;
    zappedAny = true;
  }
  
  // Walk the inheritance hierarchies of all of the protocols. If we run into
  // one of the known protocols, zap it from the original list.
  for (unsigned i : indices(protocols)) {
    auto *proto = protocols[i];
    if (proto == nullptr)
      continue;

    // The below algorithm assumes the inheritance graph is acyclic. Just skip
    // it if we have invalid code.
    if (proto->hasCircularInheritedProtocols())
      continue;

    // Add the protocols we inherited.
    auto allInherited = proto->getAllInheritedProtocols();
    for (auto *inherited : allInherited) {
      auto found = known.find(inherited);
      if (found != known.end()) {
        // Don't zap protocols associated with parameterized types.
        if (parameterized && parameterized->count(inherited))
          return;

        protocols[found->second] = nullptr;
        zappedAny = true;
      }
    }
  }
  
  if (zappedAny) {
    protocols.erase(std::remove(protocols.begin(), protocols.end(), nullptr),
                    protocols.end());
  }

  // Sort the set of protocols by module + name, to give a stable
  // ordering.
  llvm::array_pod_sort(protocols.begin(), protocols.end(), TypeDecl::compare);
}

void ProtocolType::canonicalizeProtocols(
       SmallVectorImpl<ProtocolDecl *> &protocols) {
  return ::canonicalizeProtocols(protocols, nullptr);
}

static void
getCanonicalParams(AnyFunctionType *funcType,
                   CanGenericSignature genericSig,
                   SmallVectorImpl<AnyFunctionType::Param> &canParams) {
  auto origParams = funcType->getParams();
  for (auto param : origParams) {
    canParams.emplace_back(param.getCanonical(genericSig));
  }
}

AnyFunctionType::Param
AnyFunctionType::Param::getCanonical(CanGenericSignature genericSig) const {
  // Canonicalize the type and drop the internal label to canonicalize the
  // Param.
  return Param(getPlainType()->getReducedType(genericSig),
               getLabel(), getParameterFlags(),
               /*InternalLabel=*/Identifier());
}

CanType TypeBase::computeCanonicalType() {
  assert(!hasCanonicalTypeComputed() && "called unnecessarily");

  TypeBase *Result = nullptr;
  switch (getKind()) {
#define ALWAYS_CANONICAL_TYPE(id, parent) case TypeKind::id:
#define TYPE(id, parent)
#include "swift/AST/TypeNodes.def"
  case TypeKind::Error:
  case TypeKind::Unresolved:
  case TypeKind::TypeVariable:
  case TypeKind::Placeholder:
  case TypeKind::BuiltinTuple:
    llvm_unreachable("these types are always canonical");

#define SUGARED_TYPE(id, parent) \
  case TypeKind::id: \
    Result = cast<id##Type>(this)-> \
             getSinglyDesugaredType()->getCanonicalType().getPointer(); \
    break;
#define TYPE(id, parent)
#include "swift/AST/TypeNodes.def"

  case TypeKind::Enum:
  case TypeKind::Struct:
  case TypeKind::Class:
  case TypeKind::Protocol: {
    auto nominalTy = cast<NominalType>(this);
    auto parentTy = nominalTy->getParent()->getCanonicalType();
    Result = NominalType::get(nominalTy->getDecl(), parentTy,
                              parentTy->getASTContext());
    break;
  }

  case TypeKind::Pack: {
    PackType *PT = cast<PackType>(this);
    assert(PT->getNumElements() != 0 && "Empty packs are always canonical");

    SmallVector<Type, 8> CanTys;
    CanTys.reserve(PT->getNumElements());
    for (Type field : PT->getElementTypes()) {
      CanTys.push_back(field->getCanonicalType());
    }

    const ASTContext &C = CanTys[0]->getASTContext();
    Result = PackType::get(C, CanTys)->castTo<PackType>();
    break;
  }

  case TypeKind::PackExpansion: {
    auto *expansion = cast<PackExpansionType>(this);
    auto patternType = expansion->getPatternType()->getCanonicalType();
    auto countType = expansion->getCountType()->getCanonicalType();
    if (auto packArchetype = dyn_cast<PackArchetypeType>(countType))
      countType = packArchetype->getReducedShape();
    Result = PackExpansionType::get(patternType, countType);
    break;
  }

  case TypeKind::PackElement: {
    auto *element = cast<PackElementType>(this);
    auto packType = element->getPackType()->getCanonicalType();
    Result = PackElementType::get(packType, element->getLevel());
    break;
  }

  case TypeKind::Tuple: {
    TupleType *TT = cast<TupleType>(this);
    assert(TT->getNumElements() != 0 && "Empty tuples are always canonical");

    SmallVector<TupleTypeElt, 8> CanElts;
    CanElts.reserve(TT->getNumElements());
    for (const TupleTypeElt &field : TT->getElements()) {
      assert(!field.getType().isNull() &&
             "Cannot get canonical type of un-typechecked TupleType!");
      CanElts.push_back(field.getWithType(field.getType()->getCanonicalType()));
    }

    const ASTContext &C = CanElts[0].getType()->getASTContext();
    Result = TupleType::get(CanElts, C)->castTo<TupleType>();
    break;
  }

  case TypeKind::GenericTypeParam: {
    GenericTypeParamType *gp = cast<GenericTypeParamType>(this);
    auto gpDecl = gp->getDecl();
    auto &C = gpDecl->getASTContext();
    Result =
        GenericTypeParamType::get(gp->getParamKind(), gp->getDepth(),
                                  gp->getIndex(), gp->getValueType(),
                                  C);
    break;
  }

  case TypeKind::DependentMember: {
    auto dependent = cast<DependentMemberType>(this);
    auto base = dependent->getBase()->getCanonicalType();
    if (auto assocType = dependent->getAssocType())
      Result = DependentMemberType::get(base, assocType);
    else
      Result = DependentMemberType::get(base, dependent->getName());
    break;
  }

#define REF_STORAGE(Name, ...) \
  case TypeKind::Name##Storage:
#include "swift/AST/ReferenceStorage.def"
  {
    auto ref = cast<ReferenceStorageType>(this);
    Type referentType = ref->getReferentType()->getCanonicalType();
    Result = ReferenceStorageType::get(referentType, ref->getOwnership(),
                                       referentType->getASTContext());
    break;
  }
  case TypeKind::LValue:
    Result = LValueType::get(cast<LValueType>(this)->getObjectType()
                               ->getCanonicalType());
    break;
  case TypeKind::InOut:
    Result = InOutType::get(getInOutObjectType()->getCanonicalType());
    break;
  case TypeKind::Function:
  case TypeKind::GenericFunction: {
    AnyFunctionType *funcTy = cast<AnyFunctionType>(this);

    PrettyStackTraceType trace(funcTy->getResult()->getASTContext(),
                               "computing canonical type for ", this);

    CanGenericSignature genericSig;
    if (auto *genericFnTy = dyn_cast<GenericFunctionType>(this))
      genericSig = genericFnTy->getGenericSignature().getCanonicalSignature();

    // Transform the parameter and result types.
    SmallVector<AnyFunctionType::Param, 8> canParams;
    getCanonicalParams(funcTy, genericSig, canParams);
    auto resultTy = funcTy->getResult()->getReducedType(genericSig);

    std::optional<ASTExtInfo> extInfo = std::nullopt;
    if (funcTy->hasExtInfo())
      extInfo = funcTy->getCanonicalExtInfo(useClangTypes(resultTy));
    if (genericSig) {
      Result = GenericFunctionType::get(genericSig, canParams, resultTy,
                                        extInfo);
    } else {
      Result = FunctionType::get(canParams, resultTy, extInfo);
    }
    assert(Result->isCanonical());
    break;
  }

  case TypeKind::SILBlockStorage:
  case TypeKind::SILBox:
  case TypeKind::SILFunction:
  case TypeKind::SILToken:
  case TypeKind::SILMoveOnlyWrapped:
    llvm_unreachable("SIL-only types are always canonical!");

  case TypeKind::ProtocolComposition: {
    auto *PCT = cast<ProtocolCompositionType>(this);
    SmallVector<Type, 4> CanProtos;
    for (Type t : PCT->getMembers())
      CanProtos.push_back(t->getCanonicalType());
    assert(!CanProtos.empty() && "Non-canonical empty composition?");
    const ASTContext &C = CanProtos[0]->getASTContext();
    Type Composition = ProtocolCompositionType::get(C, CanProtos,
                                                    PCT->getInverses(),
                                                    PCT->hasExplicitAnyObject());
    Result = Composition.getPointer();
    break;
  }
  case TypeKind::ParameterizedProtocol: {
    auto *PPT = cast<ParameterizedProtocolType>(this);
    auto Base = cast<ProtocolType>(PPT->getBaseType()->getCanonicalType());
    SmallVector<Type, 1> CanArgs;
    for (Type t : PPT->getArgs())
      CanArgs.push_back(t->getCanonicalType());
    auto &C = Base->getASTContext();
    Result = ParameterizedProtocolType::get(C, Base, CanArgs);
    break;
  }
  case TypeKind::Existential: {
    auto *existential = cast<ExistentialType>(this);
    auto constraint = existential->getConstraintType()->getCanonicalType();
    Result = ExistentialType::get(constraint).getPointer();
    break;
  }
  case TypeKind::ExistentialMetatype: {
    auto metatype = cast<ExistentialMetatypeType>(this);
    auto instanceType = metatype->getInstanceType()->getCanonicalType();
    if (metatype->hasRepresentation())
      Result = ExistentialMetatypeType::get(instanceType,
                                            metatype->getRepresentation());
    else
      Result = ExistentialMetatypeType::get(instanceType);
    break;
  }
  case TypeKind::Metatype: {
    MetatypeType *MT = cast<MetatypeType>(this);
    Type InstanceTy = MT->getInstanceType()->getCanonicalType();
    if (MT->hasRepresentation())
      Result = MetatypeType::get(InstanceTy, MT->getRepresentation());
    else
      Result = MetatypeType::get(InstanceTy);
    break;
  }
  case TypeKind::DynamicSelf: {
    DynamicSelfType *DST = cast<DynamicSelfType>(this);
    Type SelfTy = DST->getSelfType()->getCanonicalType();
    Result = DynamicSelfType::get(SelfTy, SelfTy->getASTContext());
    break;
  }
  case TypeKind::UnboundGeneric: {
    auto unbound = cast<UnboundGenericType>(this);
    Type parentTy = unbound->getParent()->getCanonicalType();
    Result = UnboundGenericType::get(unbound->getDecl(), parentTy,
                                     parentTy->getASTContext());
    break;
  }
  case TypeKind::BoundGenericClass:
  case TypeKind::BoundGenericEnum:
  case TypeKind::BoundGenericStruct: {
    BoundGenericType *BGT = cast<BoundGenericType>(this);
    Type parentTy;
    if (BGT->getParent())
      parentTy = BGT->getParent()->getCanonicalType();
    SmallVector<Type, 4> CanGenericArgs;
    for (Type Arg : BGT->getGenericArgs())
      CanGenericArgs.push_back(Arg->getCanonicalType());
    Result = BoundGenericType::get(BGT->getDecl(), parentTy, CanGenericArgs);
    break;
  }
  case TypeKind::ErrorUnion: {
    SmallVector<Type, 2> newTerms;
    for (auto term : cast<ErrorUnionType>(this)->getTerms()) {
      newTerms.push_back(term->getCanonicalType());
    }
    ASTContext &ctx = newTerms[0]->getASTContext();
    Result = ErrorUnionType::get(ctx, newTerms).getPointer();
    break;
  }
  }

  // Cache the canonical type for future queries.
  assert(Result && "Case not implemented!");
  return CanonicalType = CanType(Result);
}

CanType TypeBase::getReducedType(GenericSignature sig) {
  return sig.getReducedType(this);
}

CanType TypeBase::getMinimalCanonicalType() const {
  const auto MinimalTy = getCanonicalType().transformRec(
      [](TypeBase *Ty) -> std::optional<Type> {
    const CanType CanTy = CanType(Ty);

    if (const auto ET = dyn_cast<ExistentialType>(CanTy)) {
      const auto PCT =
          dyn_cast<ProtocolCompositionType>(ET.getConstraintType());
      if (!PCT) {
        return CanTy;
      }

      const auto MinimalTy = PCT->getMinimalCanonicalType();
      if (MinimalTy->getClassOrBoundGenericClass()) {
        return MinimalTy;
      }

      return ExistentialType::get(MinimalTy);
    }

    if (const auto EM = dyn_cast<ExistentialMetatypeType>(CanTy)) {
      const auto PCT = dyn_cast<ProtocolCompositionType>(EM.getInstanceType());
      if (!PCT) {
        return CanTy;
      }

      const auto MinimalTy = PCT->getMinimalCanonicalType();
      if (MinimalTy->getClassOrBoundGenericClass()) {
        return MetatypeType::get(MinimalTy);
      }

      return ExistentialMetatypeType::get(MinimalTy);
    }

    if (const auto Composition = dyn_cast<ProtocolCompositionType>(CanTy)) {
      return Composition->getMinimalCanonicalType();
    }

    return std::nullopt;
  });

  return CanType(MinimalTy);
}

TypeBase *TypeBase::reconstituteSugar(bool Recursive) {
  auto Func = [Recursive](TypeBase *Ty) -> std::optional<Type> {
    if (auto boundGeneric = dyn_cast<BoundGenericType>(Ty)) {

      auto getGenericArg = [&](unsigned i) -> Type {
        auto arg = boundGeneric->getGenericArgs()[i];
        if (Recursive)
          arg = arg->reconstituteSugar(Recursive);
        return arg;
      };

      if (boundGeneric->isArray())
        return Type(ArraySliceType::get(getGenericArg(0)));
      if (boundGeneric->isDictionary())
        return Type(DictionaryType::get(getGenericArg(0), getGenericArg(1)));
      if (boundGeneric->isOptional())
        return Type(OptionalType::get(getGenericArg(0)));
    }
    return std::nullopt;
  };
  if (Recursive)
    return Type(this).transformRec(Func).getPointer();

  if (auto result = Func(this))
    return result->getPointer();

  return this;
}

TypeBase *TypeBase::getWithoutSyntaxSugar() {
  auto Func = [](TypeBase *Ty) -> std::optional<Type> {
    if (auto *syntaxSugarType = dyn_cast<SyntaxSugarType>(Ty))
      return syntaxSugarType->getSinglyDesugaredType()->getWithoutSyntaxSugar();
    return std::nullopt;
  };
  return Type(this).transformRec(Func).getPointer();
}

#define TYPE(Id, Parent)
#define SUGARED_TYPE(Id, Parent) \
  static_assert(std::is_base_of<SugarType, Id##Type>::value, "Sugar mismatch");
#include "swift/AST/TypeNodes.def"

Type SugarType::getSinglyDesugaredTypeSlow() {
  // Find the generic type that implements this syntactic sugar type.
  NominalTypeDecl *implDecl;

  // XXX -- If the Decl and Type class hierarchies agreed on spelling, then
  // we could handle the entire switch statement via macros.
  switch (getKind()) {
#define TYPE(Id, Parent) \
  case TypeKind::Id: llvm_unreachable("non-sugared type?");
#define SUGARED_TYPE(Id, Parent)
#include "swift/AST/TypeNodes.def"
  case TypeKind::TypeAlias:
    llvm_unreachable("bound type alias types always have an underlying type");
  case TypeKind::ArraySlice:
  case TypeKind::VariadicSequence:
    implDecl = Context->getArrayDecl();
    break;
  case TypeKind::Optional:
    implDecl = Context->getOptionalDecl();
    break;
  case TypeKind::Dictionary:
    implDecl = Context->getDictionaryDecl();
    break;
  }
  if (!implDecl) {
    return ErrorType::get(*Context);
  }

  Bits.SugarType.HasCachedType = true;
  if (auto Ty = dyn_cast<UnarySyntaxSugarType>(this)) {
    UnderlyingType = BoundGenericType::get(implDecl, Type(), Ty->getBaseType());
  } else if (auto Ty = dyn_cast<DictionaryType>(this)) {
    UnderlyingType = BoundGenericType::get(implDecl, Type(),
                                      { Ty->getKeyType(), Ty->getValueType() });
  } else {
    llvm_unreachable("Not UnarySyntaxSugarType or DictionaryType?");
  }

  // Record the implementation type.
  return UnderlyingType;
}

ArrayRef<Type> TypeAliasType::getDirectGenericArgs() const {
  if (!typealias->isGeneric()) return { };

  // Otherwise, the innermost replacement types are the direct
  // generic arguments.
  return getSubstitutionMap().getInnermostReplacementTypes();
}

GenericTypeParamType::GenericTypeParamType(GenericTypeParamDecl *param,
                                           RecursiveTypeProperties props)
  : SubstitutableType(TypeKind::GenericTypeParam, nullptr, props),
    Decl(param) {
  ASSERT(param->getDepth() != GenericTypeParamDecl::InvalidDepth);
  Depth = param->getDepth();
  IsDecl = true;
  Index = param->getIndex();
  ParamKind = param->getParamKind();
  ValueType = param->getValueType();
}

GenericTypeParamType::GenericTypeParamType(Identifier name,
                                           GenericTypeParamType *canType,
                                           const ASTContext &ctx)
    : SubstitutableType(TypeKind::GenericTypeParam, nullptr,
                        canType->getRecursiveProperties()),
      Decl(nullptr) {
  Name = name;
  Depth = canType->getDepth();
  IsDecl = false;
  Index = canType->getIndex();
  ParamKind = canType->getParamKind();
  ValueType = canType->getValueType();

  setCanonicalType(CanType(canType));
}

GenericTypeParamType::GenericTypeParamType(GenericTypeParamKind paramKind,
                                           unsigned depth, unsigned index,
                                           Type valueType,
                                           RecursiveTypeProperties props,
                                           const ASTContext &ctx)
    : SubstitutableType(TypeKind::GenericTypeParam, &ctx, props),
      Decl(nullptr) {
  Depth = depth;
  IsDecl = false;
  Index = index;
  ParamKind = paramKind;
  ValueType = valueType;
}

GenericTypeParamDecl *GenericTypeParamType::getOpaqueDecl() const {
  auto *decl = getDecl();
  if (decl && decl->isOpaqueType())
    return decl;
  return nullptr;
}

Identifier GenericTypeParamType::getName() const {
  // Use the declaration name if we still have that sugar.
  if (auto decl = getDecl())
    return decl->getName();

  if (!isCanonical())
    return Name;

  // Otherwise, we're canonical. Produce an anonymous '<tau>_n_n' name.

  // getASTContext() doesn't actually mutate an already-canonical type.
  auto &C = const_cast<GenericTypeParamType*>(this)->getASTContext();
  auto &names = C.CanonicalGenericTypeParamTypeNames;

  auto key = (getDepth() << 16) | getIndex();

  auto cached = names.find(key);
  if (cached != names.end())
    return cached->second;
  
  llvm::SmallString<10> nameBuf;
  llvm::raw_svector_ostream os(nameBuf);

  static const char *tau = SWIFT_UTF8("\u03C4_");

  os << tau << getDepth() << '_' << getIndex();
  Identifier name = C.getIdentifier(os.str());
  names.insert({key, name});
  return name;
}

Type GenericTypeParamType::getValueType() const {
  if (getDecl())
    return getDecl()->getValueType();

  return ValueType;
}

const llvm::fltSemantics &BuiltinFloatType::getAPFloatSemantics() const {
  switch (getFPKind()) {
  case BuiltinFloatType::IEEE16:  return APFloat::IEEEhalf();
  case BuiltinFloatType::IEEE32:  return APFloat::IEEEsingle();
  case BuiltinFloatType::IEEE64:  return APFloat::IEEEdouble();
  case BuiltinFloatType::IEEE80:  return APFloat::x87DoubleExtended();
  case BuiltinFloatType::IEEE128: return APFloat::IEEEquad();
  case BuiltinFloatType::PPC128:  return APFloat::PPCDoubleDouble();
  }
  llvm::report_fatal_error("Unknown FP semantics");
}

bool TypeBase::mayBeCallable(DeclContext *dc) {
  if (is<AnyFunctionType>())
    return true;

  // Callable for construction.
  if (is<AnyMetatypeType>())
    return true;

  // Unresolved types that could potentially be callable.
  if (isPlaceholder() || is<UnresolvedType>() ||
      isTypeParameter() || isTypeVariableOrMember()) {
    return true;
  }
  // Callable nominal types.
  if (isCallAsFunctionType(dc) || hasDynamicCallableAttribute())
    return true;

  return false;
}

bool TypeBase::mayHaveSuperclass() {
  if (getClassOrBoundGenericClass())
    return true;

  if (auto archetype = getAs<ArchetypeType>())
    return (bool)archetype->requiresClass();

  return is<DynamicSelfType>();
}

bool TypeBase::satisfiesClassConstraint() {
  return mayHaveSuperclass() || isObjCExistentialType();
}

Type TypeBase::getSuperclass(bool useArchetypes) {
  auto *nominalDecl = getAnyNominal();
  auto *classDecl = dyn_cast_or_null<ClassDecl>(nominalDecl);

  // Handle some special non-class types here.
  if (!classDecl) {
    if (auto archetype = getAs<ArchetypeType>())
      return archetype->getSuperclass();

    if (auto dynamicSelfTy = getAs<DynamicSelfType>())
      return dynamicSelfTy->getSelfType();

    if (isExistentialType())
      return getExistentialLayout().getSuperclass();

    // No other types have superclasses.
    return Type();
  }

  // We have a class, so get the superclass type.
  //
  // If the derived class is generic, the superclass type may contain
  // generic type parameters from the signature of the derived class.
  Type superclassTy = classDecl->getSuperclass();

  // If there's no superclass, or it is fully concrete, we're done.
  if (!superclassTy || !superclassTy->hasTypeParameter() ||
      hasUnboundGenericType())
    return superclassTy;

  // Gather substitutions from the self type, and apply them to the original
  // superclass type to form the substituted superclass type.
  auto subMap = getContextSubstitutionMap(classDecl,
                                          (useArchetypes
                                           ? classDecl->getGenericEnvironment()
                                           : nullptr));
  return superclassTy.subst(subMap);
}

Type TypeBase::getRootClass(bool useArchetypes) {
  Type iterator = this;
  assert(iterator);

  while (auto superclass = iterator->getSuperclass(useArchetypes)) {
    iterator = superclass;
  }

  return iterator;
}

bool TypeBase::isExactSuperclassOf(Type ty) {
  // For there to be a superclass relationship, we must be a class, and
  // the potential subtype must be a class, superclass-bounded archetype,
  // or subclass existential involving an imported class and @objc
  // protocol.
  if (!getClassOrBoundGenericClass() ||
      !(ty->mayHaveSuperclass() ||
        (ty->isObjCExistentialType() &&
         ty->getSuperclass() &&
         ty->getSuperclass()->getAnyNominal()->hasClangNode())))
    return false;

  SmallPtrSet<ClassDecl *, 8> seen;
  do {
    if (auto *classDecl = ty->getClassOrBoundGenericClass())
      if (!seen.insert(classDecl).second)
        return false;
    if (ty->isEqual(this))
      return true;
  } while ((ty = ty->getSuperclass()));
  return false;
}

bool TypeBase::isValueParameter() {
  Type t(this);

  return t->is<GenericTypeParamType>() &&
         t->castTo<GenericTypeParamType>()->isValue();
}

namespace {
class IsBindableVisitor : public TypeVisitor<IsBindableVisitor, CanType, CanType> {
public:
  using VisitBindingCallback =
    llvm::function_ref<CanType (ArchetypeType *, CanType)>;
    
  VisitBindingCallback VisitBinding;
  
  IsBindableVisitor(VisitBindingCallback visit) : VisitBinding(visit) {}

  CanType visitArchetypeType(ArchetypeType *orig, CanType subst) {
    if (!subst->isTypeParameter()) {
      // Check that the archetype isn't constrained in a way that makes the
      // binding impossible.
      // For instance, if the archetype is class-constrained, and the binding
      // is not a class, it can never be bound.
      if (orig->requiresClass()
          && !subst->satisfiesClassConstraint())
        return CanType();

      if (auto superclass = orig->getSuperclass())
        if (!superclass->isBindableToSuperclassOf(subst))
          return CanType();

      // TODO: If the archetype has a superclass constraint, check that the
      // substitution is a subclass.
      
      // TODO: For private types or protocols, we might be able to definitively
      // deny bindings.
      
      // Otherwise, there may be an external retroactive conformance that
      // allows the binding.
    }
    // Let the binding succeed.
    return VisitBinding(orig, subst);
  }
  
  CanType visitType(TypeBase *orig, CanType subst) {
    if (CanType(orig) == subst)
      return subst;
    
    return CanType();
  }
  
  CanType visitDynamicSelfType(DynamicSelfType *orig, CanType subst) {
    // A "dynamic self" type can be bound to another dynamic self type, or the
    // non-dynamic base class type.
    if (auto dynSubst = dyn_cast<DynamicSelfType>(subst)) {
      if (auto newBase = visit(orig->getSelfType(), dynSubst.getSelfType())) {
        return CanDynamicSelfType::get(newBase, orig->getASTContext())
                                 ->getCanonicalType();
      }
      return CanType();
    }
    
    if (auto newNonDynBase = visit(orig->getSelfType(), subst)) {
      return newNonDynBase;
    }
    return CanType();
  }
  
  /// Handle a nominal type with generic parameters anywhere in its context.
  /// \c origType and \c substType must already have been established to be
  /// instantiations of the same \c NominalTypeDecl.
  CanType handleGenericNominalType(NominalTypeDecl *decl,
                                   CanType origType,
                                   CanType substType) {
    assert(origType->getAnyNominal() == decl
           && substType->getAnyNominal() == decl);
    
    LLVM_DEBUG(llvm::dbgs() << "\n---\nTesting bindability of:\n";
               origType->print(llvm::dbgs());
               llvm::dbgs() << "\nto subst type:\n";
               substType->print(llvm::dbgs()););
    
    auto origSubMap = origType->getContextSubstitutionMap(
        decl, decl->getGenericEnvironment());
    auto substSubMap = substType->getContextSubstitutionMap(
        decl, decl->getGenericEnvironment());

    auto genericSig = decl->getGenericSignature();
    
    SmallVector<Type, 4> newParams;
    llvm::DenseMap<SubstitutableType *, Type> newParamsMap;
    bool didChange = false;
    
    LLVM_DEBUG(llvm::dbgs() << "\nNominal type generic signature:\n";
               genericSig.print(llvm::dbgs()));
    
    for (auto gpTy : genericSig.getGenericParams()) {
      auto gp = gpTy->getCanonicalType();
      
      auto orig = gp.subst(origSubMap)->getCanonicalType();
      auto subst = gp.subst(substSubMap)->getCanonicalType();
      
      auto newParam = visit(orig, subst);
      if (!newParam)
        return CanType();
      
      newParams.push_back(newParam);
      newParamsMap.insert({gp->castTo<GenericTypeParamType>(), newParam});
      didChange |= (newParam != subst);
    }
    
    SmallVector<ProtocolConformanceRef, 4> newConformances;

    // Collect conformances for the new substitutions, and verify that they don't
    // invalidate the binding to the original type.
    for (const auto &req : genericSig.getRequirements()) {
      if (req.getKind() != RequirementKind::Conformance) continue;

      auto canTy = req.getFirstType()->getCanonicalType();
      
      // Verify the generic requirements, if the subst type is bound to
      // concrete type.
      auto *proto = req.getProtocolDecl();
      if (!canTy.subst(substSubMap)->isTypeParameter()) {
        auto origConf = origSubMap.lookupConformance(canTy, proto);
        auto substConf = substSubMap.lookupConformance(canTy, proto);

        if (origConf.isConcrete()) {
          if (!substConf.isConcrete())
            return CanType();
          if (origConf.getConcrete()->getRootConformance()
                != substConf.getConcrete()->getRootConformance())
            return CanType();
        }
      }
      
      // Gather the conformances for the new binding type, if the type changed.
      if (didChange) {
        auto newSubstTy = req.getFirstType().subst(
          QueryTypeSubstitutionMap{newParamsMap},
          LookUpConformanceInModule());
        
        auto newConformance
          = lookupConformance(newSubstTy, proto, /*allowMissing=*/true);
        if (!newConformance)
          return CanType();
        newConformances.push_back(newConformance);
      }
    }

    if (!didChange)
      return substType;
    
    // Build the new substituted generic type.
    auto newSubMap = SubstitutionMap::get(genericSig,
                                          newParams,
                                          newConformances);
    return decl->getDeclaredInterfaceType().subst(newSubMap)
               ->getCanonicalType();
  }
  
  CanType visitNominalType(NominalType *nom, CanType subst) {
    if (auto substNom = dyn_cast<NominalType>(subst)) {
      auto nomDecl = nom->getDecl();
      if (nom->getDecl() != substNom->getDecl())
        return CanType();
      
      // If the type is generic (because it's a nested type in a generic context),
      // process the generic type bindings.
      if (!isa<ProtocolDecl>(nomDecl) && nomDecl->isGenericContext()) {
        return handleGenericNominalType(nomDecl, CanType(nom), subst);
      }
      // Otherwise, the nongeneric nominal types trivially match.
      return subst;
    }
    return CanType();
  }
  
  CanType visitAnyMetatypeType(AnyMetatypeType *meta, CanType subst) {
    if (auto substMeta = dyn_cast<AnyMetatypeType>(subst)) {
      if (substMeta->getKind() != meta->getKind())
        return CanType();
      
      auto substInstance = visit(meta->getInstanceType()->getCanonicalType(),
                               substMeta->getInstanceType()->getCanonicalType());
      if (!substInstance)
        return CanType();
      
      if (substInstance == substMeta.getInstanceType())
        return subst;
      
      return isa<ExistentialMetatypeType>(substMeta)
        ? CanType(CanExistentialMetatypeType::get(substInstance))
        : CanType(CanMetatypeType::get(substInstance));
    }
    return CanType();
  }
  
  CanType visitTupleType(TupleType *tuple, CanType subst) {
    if (auto substTuple = dyn_cast<TupleType>(subst)) {
      // Tuple elements must match.
      if (tuple->getNumElements() != substTuple->getNumElements())
        return CanType();
      // TODO: Label reordering?
      SmallVector<TupleTypeElt, 4> newElements;
      bool didChange = false;
      for (unsigned i : indices(tuple->getElements())) {
        auto elt = tuple->getElements()[i],
             substElt = substTuple->getElements()[i];
        if (elt.getName() != substElt.getName())
          return CanType();
        auto newElt = visit(elt.getType(),
                            substElt.getType()->getCanonicalType());
        if (!newElt)
          return CanType();
        newElements.push_back(substElt.getWithType(newElt));
        didChange = didChange | (newElt != CanType(substElt.getType()));
      }
      if (!didChange)
        return subst;
      return TupleType::get(newElements, subst->getASTContext())
        ->getCanonicalType();
    }
    return CanType();
  }
  
  CanType visitDependentMemberType(DependentMemberType *dt, CanType subst) {
    return subst;
  }
  CanType visitGenericTypeParamType(GenericTypeParamType *dt, CanType subst) {
    return subst;
  }
  
  CanType visitFunctionType(FunctionType *func, CanType subst) {
    if (auto substFunc = dyn_cast<FunctionType>(subst)) {
      if (!func->hasSameExtInfoAs(substFunc))
        return CanType();
      
      if (func->getParams().size() != substFunc->getParams().size())
        return CanType();

      SmallVector<AnyFunctionType::Param, 4> newParams;
      bool didChange = false;
      for (unsigned i : indices(func->getParams())) {
        auto param = func->getParams()[i];
        auto substParam = substFunc.getParams()[i];
        if (param.getParameterFlags() != substParam.getParameterFlags())
          return CanType();
        
        auto newParamTy =
          visit(param.getPlainType(), substParam.getPlainType());
        if (!newParamTy)
          return CanType();
        
        newParams.push_back(substParam.withType(newParamTy));
        didChange = didChange | (newParamTy != substParam.getPlainType());
      }
      
      auto newReturn = visit(func->getResult()->getCanonicalType(),
                             substFunc->getResult()->getCanonicalType());
      if (!newReturn)
        return CanType();
      if (!didChange && newReturn == substFunc.getResult())
        return subst;
      return FunctionType::get(newParams, newReturn, func->getExtInfo())
        ->getCanonicalType();
    }
    return CanType();
  }
  
  CanType visitSILFunctionType(SILFunctionType *func, CanType subst) {
    if (auto substFunc = dyn_cast<SILFunctionType>(subst)) {
      if (!func->hasSameExtInfoAs(substFunc))
        return CanType();

      if (func->getInvocationGenericSignature()
          || substFunc->getInvocationGenericSignature()) {
        auto sig = func->getInvocationGenericSignature();
        if (sig != substFunc->getInvocationGenericSignature())
          return CanType();

        auto origSubs = func->getPatternSubstitutions();
        auto substSubs = substFunc->getPatternSubstitutions();

        if ((bool) origSubs != (bool) substSubs)
          return CanType();

        for (unsigned i : indices(origSubs.getReplacementTypes())) {
          auto origType =
            origSubs.getReplacementTypes()[i]->getReducedType(sig);
          auto substType =
            substSubs.getReplacementTypes()[i]->getReducedType(sig);

          auto newType = visit(origType, substType);

          if (!newType)
            return CanType();

          // We can test SILFunctionTypes for bindability, but we can't
          // transform them.
          assert(newType == substType
                 && "cannot transform SILFunctionTypes");
        }
      }

      // Compare substituted function types.
      if (func->getPatternGenericSignature()
          || substFunc->getPatternGenericSignature()) {
        if (func->getPatternGenericSignature()
              != substFunc->getPatternGenericSignature())
          return CanType();
        
        auto sig = func->getPatternGenericSignature();
        
        auto origSubs = func->getPatternSubstitutions();
        auto substSubs = substFunc->getPatternSubstitutions();
        
        for (unsigned i : indices(origSubs.getReplacementTypes())) {
          auto origType =
            origSubs.getReplacementTypes()[i]->getReducedType(sig);
          auto substType =
            substSubs.getReplacementTypes()[i]->getReducedType(sig);
          
          auto newType = visit(origType, substType);
          
          if (!newType)
            return CanType();
          
          // We can test SILFunctionTypes for bindability, but we can't
          // transform them.
          assert(newType == substType
                 && "cannot transform SILFunctionTypes");
        }
        
        return subst;
      }
      
      if (func->getParameters().size() != substFunc->getParameters().size())
        return CanType();
      if (func->getResults().size() != substFunc->getResults().size())
        return CanType();
      
      for (unsigned i : indices(func->getParameters())) {
        if (func->getParameters()[i].getConvention()
              != substFunc->getParameters()[i].getConvention())
          return CanType();
        
        auto origParam = func->getParameters()[i].getInterfaceType();
        auto substParam = substFunc->getParameters()[i].getInterfaceType();
        auto newParam = visit(origParam, substParam);
        if (!newParam)
          return CanType();
        
        // We can test SILFunctionTypes for bindability, but we can't
        // transform them.
        assert(newParam == substParam
               && "cannot transform SILFunctionTypes");
      }

      for (unsigned i : indices(func->getResults())) {
        if (func->getResults()[i].getConvention()
            != substFunc->getResults()[i].getConvention())
          return CanType();

        auto origResult = func->getResults()[i].getInterfaceType();
        auto substResult = substFunc->getResults()[i].getInterfaceType();
        auto newResult = visit(origResult, substResult);
        if (!newResult)
          return CanType();

        // We can test SILFunctionTypes for bindability, but we can't
        // transform them.
        assert(newResult == substResult
               && "cannot transform SILFunctionTypes");
      }
      
      return subst;
    }
    
    return CanType();
  }
  
  CanType visitBoundGenericType(BoundGenericType *bgt, CanType subst) {
    auto substBGT = dyn_cast<BoundGenericType>(subst);
    if (!substBGT)
      return CanType();
    
    if (bgt->getDecl() != substBGT->getDecl())
      return CanType();

    auto *decl = bgt->getDecl();

    return handleGenericNominalType(decl, CanType(bgt), subst);
  }
};
}

CanType TypeBase::substituteBindingsTo(Type ty,
                             IsBindableVisitor::VisitBindingCallback substFn) {
  return IsBindableVisitor(substFn)
    .visit(getCanonicalType(), ty->getCanonicalType());
}

bool TypeBase::isBindableTo(Type ty) {
  // Keep a mapping of archetype bindings, so we reject types that try to bind
  // different types to the same type parameter, e.g.
  // `Foo<T,T>`.isBindableTo(`Foo<Int, String>`).
  llvm::DenseMap<ArchetypeType *, CanType> Bindings;
  
  return !substituteBindingsTo(ty,
    [&](ArchetypeType *archetype, CanType binding) -> CanType {
      // If we already bound this archetype, make sure the new binding candidate
      // is the same type.
      auto bound = Bindings.find(archetype);
      if (bound != Bindings.end()) {
        if (!bound->second->isEqual(binding))
          return CanType();
      } else {
        Bindings.insert({archetype, binding});
      }
      return binding;
    })
    .isNull();
}

bool TypeBase::isBindableToSuperclassOf(Type ty) {
  // Do an exact match if no archetypes are involved.
  if (!hasArchetype())
    return isExactSuperclassOf(ty);
  
  // For there to be a superclass relationship,
  // the potential subtype must be a class or superclass-bounded archetype.
  if (!ty->mayHaveSuperclass())
    return false;

  SmallPtrSet<ClassDecl *, 8> seen;
  do {
    if (auto *classDecl = ty->getClassOrBoundGenericClass())
      if (!seen.insert(classDecl).second)
        return false;
    if (isBindableTo(ty))
      return true;
  } while ((ty = ty->getSuperclass()));
  return false;
}

static bool isBridgeableObjectType(CanType type) {
  // Metatypes aren't always trivially bridgeable unless they've been
  // SIL-lowered to have an @objc representation.
  if (auto metaTy = dyn_cast<AnyMetatypeType>(type)) {
    if (!metaTy->hasRepresentation())
      return false;

    if (metaTy->getRepresentation() != MetatypeRepresentation::ObjC)
      return false;

    if (auto metatype = dyn_cast<MetatypeType>(type)) {
      CanType instanceType = metatype.getInstanceType();
      return instanceType->mayHaveSuperclass();
    }

    // @objc protocol metatypes.
    if (auto metatype = dyn_cast<ExistentialMetatypeType>(type)) {
      return metatype.getInstanceType()->isObjCExistentialType();
    }
  }

  // Classes and class-constrained archetypes.
  if (type->mayHaveSuperclass())
    return true;

  // Pure-ObjC existential types.
  if (type.isObjCExistentialType()) {
    return true;
  }

  // Blocks.
  if (auto fnType = dyn_cast<AnyFunctionType>(type)) {
    return fnType->getRepresentation()
      == AnyFunctionType::Representation::Block;
  } else if (auto fnType = dyn_cast<SILFunctionType>(type)) {
    return fnType->getRepresentation()
      == SILFunctionType::Representation::Block;
  }

  return false;
}

static bool hasRetainablePointerRepresentation(CanType type) {
  // Look through one level of Optional<> or ImplicitlyUnwrappedOptional<>.
  if (auto objType = type.getOptionalObjectType()) {
    type = objType;
  }

  return isBridgeableObjectType(type);
}

bool TypeBase::hasRetainablePointerRepresentation() {
  return ::hasRetainablePointerRepresentation(getCanonicalType());
}

bool TypeBase::isBridgeableObjectType() {
  return ::isBridgeableObjectType(getCanonicalType());
}

bool TypeBase::isPotentiallyBridgedValueType() {
  // struct and enum types
  if (auto nominal = getAnyNominal()) {
    if (isa<StructDecl>(nominal) || isa<EnumDecl>(nominal))
      return true;
  }

  // Error existentials.
  if (isExistentialWithError()) return true;

  // Archetypes that aren't class-constrained.
  if (auto archetype = getAs<ArchetypeType>())
    return !archetype->requiresClass();

  return false;
}

/// Determine whether this is a representable Objective-C object type.
static ForeignRepresentableKind
getObjCObjectRepresentable(Type type, const DeclContext *dc) {
  // @objc metatypes are representable when their instance type is.
  if (auto metatype = type->getAs<AnyMetatypeType>()) {
    auto instanceType = metatype->getInstanceType();

    // Consider metatype of any existential type as not Objective-C
    // representable.
    if (metatype->is<MetatypeType>() && instanceType->isAnyExistentialType())
      return ForeignRepresentableKind::None;

    // If the instance type is not representable verbatim, the metatype is not
    // representable.
    if (getObjCObjectRepresentable(instanceType, dc)
          != ForeignRepresentableKind::Object)
      return ForeignRepresentableKind::None;

    // Objective-C metatypes are trivially representable.
    if (metatype->hasRepresentation() &&
        metatype->getRepresentation() == MetatypeRepresentation::ObjC)
      return ForeignRepresentableKind::Object;

    // All other metatypes are bridged.
    return ForeignRepresentableKind::Bridged;
  }

  // DynamicSelfType is always representable in Objective-C, even if
  // the class is not @objc, allowing Self-returning methods to witness
  // @objc protocol requirements.
  if (type->is<DynamicSelfType>())
    return ForeignRepresentableKind::Object;

  // @objc classes.
  if (auto classDecl = type->getClassOrBoundGenericClass()) {
    if (classDecl->isObjC())
      return ForeignRepresentableKind::Object;
  }

  // Objective-C existential types are trivially representable if
  // they don't have a superclass constraint, or if the superclass
  // constraint is an @objc class.
  if (type->isExistentialType()) {
    auto layout = type->getExistentialLayout();
    if (layout.isObjC() &&
        (!layout.explicitSuperclass ||
         getObjCObjectRepresentable(layout.explicitSuperclass, dc) ==
           ForeignRepresentableKind::Object))
      return ForeignRepresentableKind::Object;
  }

  // Existentials consisting of only marker protocols can be bridged to id.
  if (type->isMarkerExistential()) {
    return ForeignRepresentableKind::Bridged;
  }

  if (auto tyContext = dc->getInnermostTypeContext()) {
    // Class-constrained generic parameters, from ObjC generic classes.
    if (auto *classDecl = tyContext->getSelfClassDecl())
      if (classDecl->hasClangNode())
        if (auto archetype = type->getAs<ArchetypeType>())
          if (archetype->requiresClass())
            return ForeignRepresentableKind::Object;

    // The 'Self' parameter in a protocol is representable in Objective-C.
    if (auto *protoDecl = dyn_cast<ProtocolDecl>(tyContext))
      if (type->isEqual(dc->mapTypeIntoContext(protoDecl->getSelfInterfaceType())))
        return ForeignRepresentableKind::Object;
  }

  return ForeignRepresentableKind::None;
}

/// Determine the foreign representation of this type.
///
/// This function determines when and how a particular type is mapped
/// into a foreign language. Any changes to the logic here also need
/// to be reflected in PrintAsClang, so that the Swift type will be
/// properly printed for (Objective-)C and in SIL's bridging logic.
static std::pair<ForeignRepresentableKind, ProtocolConformance *>
getForeignRepresentable(Type type, ForeignLanguage language,
                        const DeclContext *dc) {
  // Local function that simply produces a failing result.
  auto failure = []() -> std::pair<ForeignRepresentableKind,
                                   ProtocolConformance *> {
    return { ForeignRepresentableKind::None, nullptr };
  };
  
  // If type has an error let's fail early.
  if (type->hasError())
    return failure();

  // Look through one level of optional type, but remember that we did.
  bool wasOptional = false;
  if (auto valueType = type->getOptionalObjectType()) {
    type = valueType;
    wasOptional = true;
  }

  if (auto existential = type->getAs<ExistentialType>())
    type = existential->getConstraintType();

  // Objective-C object types, including metatypes.
  if (language == ForeignLanguage::ObjectiveC) {
    auto representable = getObjCObjectRepresentable(type, dc);
    if (representable != ForeignRepresentableKind::None)
      return { representable, nullptr };
  }

  // Function types.
  if (auto functionType = type->getAs<FunctionType>()) {
    // Cannot handle async or throwing functions.
    if (functionType->getExtInfo().isAsync() ||
        functionType->getExtInfo().isThrowing())
      return failure();

    // Whether we have found any types that are bridged.
    bool anyBridged = false;
    bool anyStaticBridged = false;

    // Local function to combine the result of a recursive invocation.
    //
    // Returns true on failure.
    auto recurse = [&](Type componentType) -> bool {
      switch (componentType->getForeignRepresentableIn(language, dc).first) {
      case ForeignRepresentableKind::None:
        return true;

      case ForeignRepresentableKind::Trivial:
      case ForeignRepresentableKind::Object:
        return false;

      case ForeignRepresentableKind::Bridged:
      case ForeignRepresentableKind::BridgedError:
        anyBridged = true;
        return false;

      case ForeignRepresentableKind::StaticBridged:
        anyStaticBridged = true;
        return false;
      }

      llvm_unreachable("Unhandled ForeignRepresentableKind in switch.");
    };

    // Check the representation of the function type.
    bool isBlock = false;
    switch (functionType->getRepresentation()) {
    case AnyFunctionType::Representation::Thin:
      return failure();

    case AnyFunctionType::Representation::Swift:
      anyStaticBridged = true;
      break;

    case AnyFunctionType::Representation::Block:
      isBlock = true;
      break;

    case AnyFunctionType::Representation::CFunctionPointer:
      break;
    }

    auto success = [](bool anyStaticBridged,
                      bool anyBridged,
                      bool isBlock) -> std::pair<ForeignRepresentableKind,
                                                 ProtocolConformance *> {
      // We have something representable; check how it is representable.
      return { anyStaticBridged ? ForeignRepresentableKind::StaticBridged
                   : anyBridged ? ForeignRepresentableKind::Bridged
                   : isBlock    ? ForeignRepresentableKind::Object
                   : ForeignRepresentableKind::Trivial,
                   nullptr };
    };

    // Look at the result type.
    Type resultType = functionType->getResult();
    if (!resultType->isVoid() && recurse(resultType))
      return failure();

    // Look at the input params.
    for (const auto &param : functionType->getParams()) {
      if (param.isVariadic())
        return failure();
      if (recurse(param.getOldType()))
        return failure();
    }

    return success(anyStaticBridged, anyBridged, isBlock);
  }

  // Give special dispensation to builtin types for testing purposes.
  if (type->is<BuiltinType>())
    return { ForeignRepresentableKind::Trivial, nullptr };

  auto nominal = type->getAnyNominal();
  if (!nominal) return failure();

  ASTContext &ctx = nominal->getASTContext();

  // Unmanaged<T> can be trivially represented in Objective-C if T
  // is trivially represented in Objective-C.
  if (language == ForeignLanguage::ObjectiveC && type->isUnmanaged()) {
    auto boundGenericType = type->getAs<BoundGenericType>();

    // Note: works around a broken Unmanaged<> definition.
    if (!boundGenericType || boundGenericType->getGenericArgs().size() != 1)
      return failure();
    
    auto typeArgument = boundGenericType->getGenericArgs()[0];
    if (typeArgument->isTriviallyRepresentableIn(language, dc))
      return { ForeignRepresentableKind::Trivial, nullptr };

    return failure();
  }

  // If the type was imported from Clang, check whether it is
  // representable in the requested language.
  if (nominal->hasClangNode() || nominal->isObjC()) {
    switch (language) {
    case ForeignLanguage::C:
      // Imported classes and protocols are not representable in C.
      if (isa<ClassDecl>(nominal) || isa<ProtocolDecl>(nominal))
        return failure();
      LLVM_FALLTHROUGH;

    case ForeignLanguage::ObjectiveC:
      if (isa<StructDecl>(nominal) || isa<EnumDecl>(nominal)) {
        // Non-trivial C++ classes and structures are not
        // supported by @objc attribute, even though they can
        // be represented in Objective-C++.
        if (auto *cxxRec = dyn_cast_or_null<clang::CXXRecordDecl>(
                nominal->getClangDecl())) {
          if (cxxRec->hasNonTrivialCopyConstructor() ||
              cxxRec->hasNonTrivialMoveConstructor() ||
              cxxRec->hasNonTrivialDestructor())
            return failure();
        }

        // Optional structs are not representable in (Objective-)C if they
        // originally came from C, whether or not they are bridged, unless they
        // came from swift_newtype. If they are defined in Swift, they are only
        // representable if they are bridged (checked below).
        if (wasOptional) {
          if (nominal->hasClangNode()) {
            Type underlyingType =
                nominal->getDeclaredInterfaceType()
                       ->getSwiftNewtypeUnderlyingType();
            if (underlyingType) {
              return getForeignRepresentable(OptionalType::get(underlyingType),
                                             language, dc);
            }
            return failure();
          }
          break;
        }
      }

      return { ForeignRepresentableKind::Trivial, nullptr };
    }
  }

  // Pointers may be representable in ObjC.
  PointerTypeKind pointerKind;
  if (auto pointerElt = type->getAnyPointerElementType(pointerKind)) {
    switch (pointerKind) {
    case PTK_UnsafeMutableRawPointer:
    case PTK_UnsafeRawPointer:
    case PTK_UnsafeMutablePointer:
    case PTK_UnsafePointer:
      // An UnsafeMutablePointer<T> or UnsafePointer<T> is
      // representable if T is trivially representable or Void.
      if (pointerElt->isVoid() ||
          pointerElt->isTriviallyRepresentableIn(language, dc))
        return { ForeignRepresentableKind::Trivial, nullptr };

      return failure();

    case PTK_AutoreleasingUnsafeMutablePointer:
      // An AutoreleasingUnsafeMutablePointer<T> is representable in
      // Objective-C if T is a representable object type in
      // Objective-C.

      // Allow one level of optionality.
      if (auto objectType = pointerElt->getOptionalObjectType())
        pointerElt = objectType;

      if (language == ForeignLanguage::ObjectiveC &&
          getObjCObjectRepresentable(pointerElt, dc)
            != ForeignRepresentableKind::None)
        return { ForeignRepresentableKind::Trivial, nullptr };

      return failure();
    }
  }

  // Determine whether this nominal type is known to be representable
  // in this foreign language.
  auto result = ctx.getForeignRepresentationInfo(nominal, language, dc);
  if (result.getKind() == ForeignRepresentableKind::None) return failure();

  if (wasOptional && !result.isRepresentableAsOptional())
    return failure();
  
  // If our nominal type has type arguments, make sure they are
  // representable as well. Because type arguments are not actually
  // translated separately, whether they are trivially representable
  // or bridged representable doesn't impact our final result.
  if (auto boundGenericType = type->getAs<BoundGenericType>()) {
    for (auto typeArg : boundGenericType->getGenericArgs()) {
      // Type arguments cannot be optional.
      if (typeArg->getOptionalObjectType())
        return failure();

      // A type parameter can appear here when we're looking at an
      // extension of an @objc imported class.
      //
      // FIXME: Make this more principled.
      if (typeArg->isTypeParameter())
        continue;

      // And must be representable either an object or bridged.
      switch (typeArg->getForeignRepresentableIn(language, dc).first) {
      case ForeignRepresentableKind::None:
      case ForeignRepresentableKind::StaticBridged:
        return failure();

      case ForeignRepresentableKind::Trivial:
        // FIXME: We allow trivially-representable cases that also
        // conform to _ObjectiveCBridgeable. This may not be desirable
        // and should be re-evaluated.
        if (auto nominal = typeArg->getAnyNominal()) {
          if (auto objcBridgeable
                = ctx.getProtocol(KnownProtocolKind::ObjectiveCBridgeable)) {
            SmallVector<ProtocolConformance *, 1> conformances;
            if (nominal->lookupConformance(objcBridgeable, conformances))
              break;
          }
        }
        
        return failure();
        
      case ForeignRepresentableKind::Object:
      case ForeignRepresentableKind::Bridged:
      case ForeignRepresentableKind::BridgedError:
        break;
      }
    }
    
    // Specialize the conformance we were given for the type we're testing.
    if (result.getKind() == ForeignRepresentableKind::Bridged
        && !result.getConformance()->getType()->isEqual(type)) {
      auto specialized = type->getASTContext()
        .getSpecializedConformance(type,
             cast<NormalProtocolConformance>(result.getConformance()),
             boundGenericType->getContextSubstitutionMap());
      result = ForeignRepresentationInfo::forBridged(specialized);
    }
  }

  return { result.getKind(), result.getConformance() };
}

std::pair<ForeignRepresentableKind, ProtocolConformance *>
TypeBase::getForeignRepresentableIn(ForeignLanguage language,
                                    const DeclContext *dc) {
  return getForeignRepresentable(Type(this), language, dc);
}

bool TypeBase::isRepresentableIn(ForeignLanguage language,
                                 const DeclContext *dc) {
  switch (getForeignRepresentableIn(language, dc).first) {
  case ForeignRepresentableKind::None:
    return false;

  case ForeignRepresentableKind::Trivial:
  case ForeignRepresentableKind::Object:
  case ForeignRepresentableKind::Bridged:
  case ForeignRepresentableKind::BridgedError:
  case ForeignRepresentableKind::StaticBridged:
    return true;
  }

  llvm_unreachable("Unhandled ForeignRepresentableKind in switch.");
}

bool TypeBase::isTriviallyRepresentableIn(ForeignLanguage language,
                                          const DeclContext *dc) {
  switch (getForeignRepresentableIn(language, dc).first) {
  case ForeignRepresentableKind::None:
  case ForeignRepresentableKind::Bridged:
  case ForeignRepresentableKind::BridgedError:
  case ForeignRepresentableKind::StaticBridged:
    return false;

  case ForeignRepresentableKind::Trivial:
  case ForeignRepresentableKind::Object:
    return true;
  }

  llvm_unreachable("Unhandled ForeignRepresentableKind in switch.");
}

static bool isABICompatibleEvenAddingOptional(CanType t1, CanType t2) {
  // Classes, class-constrained archetypes, and pure-ObjC existential
  // types all have single retainable pointer representation; optionality
  // change is allowed.
  // NOTE: This doesn't use isAnyClassReferenceType because we want it to
  // return a conservative answer for dependent types. There's probably
  // a better answer here, though.
  if ((t1->mayHaveSuperclass() || t1->isObjCExistentialType()) &&
      (t2->mayHaveSuperclass() || t2->isObjCExistentialType())) {
    return true;
  }

  // Class metatypes are ABI-compatible even under optionality change.
  if (auto metaTy1 = dyn_cast<MetatypeType>(t1)) {
    if (auto metaTy2 = dyn_cast<MetatypeType>(t2)) {
      if (metaTy1.getInstanceType().getClassOrBoundGenericClass() &&
          metaTy2.getInstanceType().getClassOrBoundGenericClass()) {
        return true;
      }
    }
  }

  return false;
}

namespace {
  enum class ParameterPosition {
    NotParameter,
    Parameter,
    ParameterTupleElement
  };

  enum class OptionalUnwrapping {
    None,
    OptionalToOptional,
    ValueToOptional,
    OptionalToValue
  };
} // end anonymous namespace

static bool matchesFunctionType(CanAnyFunctionType fn1, CanAnyFunctionType fn2,
                                TypeMatchOptions matchMode,
                                OptionalUnwrapping insideOptional,
                                llvm::function_ref<bool()> paramsAndResultMatch) {
  // FIXME: Handle generic functions in non-ABI matches.
  if (!matchMode.contains(TypeMatchFlags::AllowABICompatible)) {
    if (!isa<FunctionType>(fn1) || !isa<FunctionType>(fn2))
      return false;
  }

  // When checking overrides, allow the base type to be throwing even if the
  // overriding type isn't.
  auto ext1 = fn1->getExtInfo();
  auto ext2 = fn2->getExtInfo();
  if (matchMode.contains(TypeMatchFlags::AllowOverride)) {
    // Removing 'throwing' is ABI-compatible for synchronous functions, but
    // not for async ones.
    if (ext2.isThrowing() && !ext1.isThrowing() &&
        ext2.getThrownError().isNull() &&
        !(ext2.isAsync() &&
          matchMode.contains(TypeMatchFlags::AllowABICompatible))) {
      ext1 = ext1.withThrows(true, ext2.getThrownError());
    }

    // Removing '@Sendable' is ABI-compatible because there's nothing wrong with
    // a function being sendable when it doesn't need to be.
    if (!ext2.isSendable())
      ext1 = ext1.withSendable(false);
  }

  if (matchMode.contains(TypeMatchFlags::IgnoreFunctionSendability)) {
    ext1 = ext1.withSendable(false);
    ext2 = ext2.withSendable(false);
  }

  if (matchMode.contains(TypeMatchFlags::IgnoreFunctionGlobalActorIsolation)) {
    if (ext1.getGlobalActor())
      ext1 = ext1.withoutIsolation();
    if (ext2.getGlobalActor())
      ext2 = ext2.withoutIsolation();
  }

  // If specified, allow an escaping function parameter to override a
  // non-escaping function parameter when the parameter is optional.
  // Note that this is checking 'ext2' rather than 'ext1' because parameters
  // must be contravariant for the containing function to be covariant.
  if (matchMode.contains(
          TypeMatchFlags::IgnoreNonEscapingForOptionalFunctionParam) &&
      insideOptional == OptionalUnwrapping::OptionalToOptional) {
    if (!ext2.isNoEscape())
      ext1 = ext1.withNoEscape(false);
  }
  if (!ext1.isEqualTo(ext2, useClangTypes(fn1)))
    return false;

  return paramsAndResultMatch();
}

static bool matches(CanType t1, CanType t2, TypeMatchOptions matchMode,
                    ParameterPosition paramPosition,
                    OptionalUnwrapping insideOptional) {
  if (t1 == t2) return true;

  // First try unwrapping optionals.
  // Make sure we only unwrap at most one layer of optional.
  if (insideOptional == OptionalUnwrapping::None) {
    // Value-to-optional and optional-to-optional.
    if (auto obj2 = t2.getOptionalObjectType()) {
      // Optional-to-optional.
      if (auto obj1 = t1.getOptionalObjectType()) {
        // Allow T? and T! to freely match one another.
        return matches(obj1, obj2, matchMode, ParameterPosition::NotParameter,
                       OptionalUnwrapping::OptionalToOptional);
      }

      // Value-to-optional.
      if (matchMode.contains(TypeMatchFlags::AllowABICompatible)) {
        if (isABICompatibleEvenAddingOptional(t1, obj2))
          return true;
      }
      if (matchMode.contains(TypeMatchFlags::AllowOverride) ||
          matchMode.contains(TypeMatchFlags::AllowTopLevelOptionalMismatch)) {
        return matches(t1, obj2, matchMode, ParameterPosition::NotParameter,
                       OptionalUnwrapping::ValueToOptional);
      }

    } else if (matchMode.contains(
                 TypeMatchFlags::AllowTopLevelOptionalMismatch)) {
      // Optional-to-value, normally disallowed.
      if (auto obj1 = t1.getOptionalObjectType()) {
        return matches(obj1, t2, matchMode, ParameterPosition::NotParameter,
                       OptionalUnwrapping::OptionalToValue);
      }
    }
  }

  // Scalar-to-tuple and tuple-to-tuple.
  if (auto tuple2 = dyn_cast<TupleType>(t2)) {
    // We only ever look into singleton tuples on the RHS if we're
    // certain that the LHS isn't also a singleton tuple.
    ParameterPosition elementPosition;
    switch (paramPosition) {
    case ParameterPosition::NotParameter:
    case ParameterPosition::ParameterTupleElement:
      elementPosition = ParameterPosition::NotParameter;
      break;
    case ParameterPosition::Parameter:
      elementPosition = ParameterPosition::ParameterTupleElement;
      break;
    }

    auto tuple1 = dyn_cast<TupleType>(t1);
    if (!tuple1 || tuple1->getNumElements() != tuple2->getNumElements()) {
      if (tuple2->getNumElements() == 1) {
        return matches(t1, tuple2.getElementType(0), matchMode, elementPosition,
                       OptionalUnwrapping::None);
      }
      return false;
    }

    for (auto i : indices(tuple1.getElementTypes())) {
      if (!matches(tuple1.getElementType(i), tuple2.getElementType(i),
                   matchMode, elementPosition, OptionalUnwrapping::None)) {
        return false;
      }
    }
    return true;
  }

  // Function-to-function.
  if (auto fn2 = dyn_cast<AnyFunctionType>(t2)) {
    auto fn1 = dyn_cast<AnyFunctionType>(t1);
    if (!fn1)
      return false;

    auto paramsAndResultMatch = [&]() {
      auto fn2Params = fn2.getParams();
      auto fn1Params = fn1.getParams();
      if (fn2Params.size() != fn1Params.size()) {
        return false;
      }

      // Inputs are contravariant.
      for (auto i : indices(fn2.getParams())) {
        if (!matches(fn2Params[i].getOldType(), fn1Params[i].getOldType(),
                     matchMode, ParameterPosition::ParameterTupleElement,
                     OptionalUnwrapping::None)) {
          return false;
        }
      }

      // Results are covariant.
      return (matches(fn1.getResult(), fn2.getResult(), matchMode,
                      ParameterPosition::NotParameter,
                      OptionalUnwrapping::None));
    };

    return matchesFunctionType(fn1, fn2, matchMode, insideOptional,
                               paramsAndResultMatch);
  }

  // Class-to-class.
  if (matchMode.contains(TypeMatchFlags::AllowOverride))
    if (t2->isExactSuperclassOf(t1))
      return true;

  if (matchMode.contains(TypeMatchFlags::AllowABICompatible))
    if (isABICompatibleEvenAddingOptional(t1, t2))
      return true;

  if (matchMode.contains(TypeMatchFlags::AllowCompatibleOpaqueTypeArchetypes))
    if (auto opaque1 = t1->getAs<OpaqueTypeArchetypeType>())
      if (auto opaque2 = t2->getAs<OpaqueTypeArchetypeType>())
        return opaque1->getDecl()->getOpaqueInterfaceGenericSignature()
                 .getCanonicalSignature() ==
               opaque2->getDecl()->getOpaqueInterfaceGenericSignature()
                  .getCanonicalSignature() &&
               opaque1->getSubstitutions().getCanonical() ==
                 opaque2->getSubstitutions().getCanonical() &&
               opaque1->getInterfaceType()->getCanonicalType()->matches(
                   opaque2->getInterfaceType()->getCanonicalType(), matchMode);

  if (matchMode.contains(TypeMatchFlags::IgnoreSendability)) {
    // Support `any Sendable` -> `Any` matching inside generic types
    // e.g. collections and optionals (i.e. `[String: (any Sendable)?]`).
    if (auto *generic1 = t1->getAs<BoundGenericType>()) {
      if (auto *generic2 = t2->getAs<BoundGenericType>()) {
        if (generic1->getDecl() == generic2->getDecl()) {
          auto genericArgs1 = generic1->getGenericArgs();
          auto genericArgs2 = generic2->getGenericArgs();

          if (genericArgs1.size() == genericArgs2.size() &&
              llvm::all_of(llvm::zip_equal(genericArgs1, genericArgs2),
                           [&](const auto &elt) -> bool {
                             return matches(
                                 std::get<0>(elt)->getCanonicalType(),
                                 std::get<1>(elt)->getCanonicalType(),
                                 matchMode, ParameterPosition::NotParameter,
                                 OptionalUnwrapping::None);
                           }))
            return true;
        }
      }
    }

    // Attempting to match `any Sendable` by `Any` is allowed in this mode.
    if (t1->isAny()) {
      auto *PD = dyn_cast_or_null<ProtocolDecl>(t2->getAnyNominal());
      if (PD && PD->isSpecificProtocol(KnownProtocolKind::Sendable))
        return true;
    }
  }

  return false;
}

bool TypeBase::matches(Type other, TypeMatchOptions matchMode) {
  return ::matches(getCanonicalType(), other->getCanonicalType(), matchMode,
                   ParameterPosition::NotParameter, OptionalUnwrapping::None);
}

bool TypeBase::matchesParameter(Type other, TypeMatchOptions matchMode) {
  return ::matches(getCanonicalType(), other->getCanonicalType(), matchMode,
                   ParameterPosition::Parameter, OptionalUnwrapping::None);
}

bool TypeBase::matchesFunctionType(Type other, TypeMatchOptions matchMode,
                                   llvm::function_ref<bool()> paramsAndResultMatch) {
  auto thisFnTy = dyn_cast<AnyFunctionType>(getCanonicalType());
  auto otherFnTy = dyn_cast<AnyFunctionType>(other->getCanonicalType());

  assert(thisFnTy && otherFnTy);
  return ::matchesFunctionType(thisFnTy, otherFnTy, matchMode,
                               OptionalUnwrapping::None, paramsAndResultMatch);
}

/// getNamedElementId - If this tuple has a field with the specified name,
/// return the field index, otherwise return -1.
int TupleType::getNamedElementId(Identifier I) const {
  for (unsigned i = 0, e = Bits.TupleType.Count; i != e; ++i) {
    if (getTrailingObjects<TupleTypeElt>()[i].getName() == I)
      return i;
  }

  // Otherwise, name not found.
  return -1;
}

ArchetypeType::ArchetypeType(TypeKind Kind,
                             const ASTContext &Ctx,
                             RecursiveTypeProperties properties,
                             Type InterfaceType,
                             ArrayRef<ProtocolDecl *> ConformsTo,
                             Type Superclass, LayoutConstraint Layout,
                             GenericEnvironment *Environment)
  : SubstitutableType(Kind, &Ctx, properties),
    InterfaceType(InterfaceType),
    Environment(Environment)
{
  // Set up the bits we need for trailing objects to work.
  Bits.ArchetypeType.HasSuperclass = static_cast<bool>(Superclass);
  Bits.ArchetypeType.HasLayoutConstraint = static_cast<bool>(Layout);
  Bits.ArchetypeType.NumProtocols = ConformsTo.size();

  // Record the superclass.
  if (Superclass)
    *getSubclassTrailingObjects<Type>() = Superclass;

  // Record the layout constraint.
  if (Layout)
    *getSubclassTrailingObjects<LayoutConstraint>() = Layout;

  // Copy the protocols.
  std::uninitialized_copy(ConformsTo.begin(), ConformsTo.end(),
                          getSubclassTrailingObjects<ProtocolDecl *>());
}

bool ArchetypeType::isRoot() const {
  return getInterfaceType()->is<GenericTypeParamType>();
}

Type ArchetypeType::getExistentialType() const {
  auto *genericEnv = getGenericEnvironment();

  // Opened types hold this directly.
  if (auto *opened = dyn_cast<OpenedArchetypeType>(this)) {
    if (opened->isRoot()) {
      return genericEnv->maybeApplyOuterContextSubstitutions(
          genericEnv->getOpenedExistentialType());
    }
  }

  // Otherwise we compute it via a generic signature query.
  auto interfaceType = getInterfaceType();
  auto genericSig = genericEnv->getGenericSignature();

  auto existentialType = genericSig->getExistentialType(interfaceType);
  return genericEnv->maybeApplyOuterContextSubstitutions(existentialType);
}

bool ArchetypeType::requiresClass() const {
  if (auto layout = getLayoutConstraint())
    return layout->isClass();
  return false;
}

Type ArchetypeType::getSuperclass() const {
  if (!Bits.ArchetypeType.HasSuperclass) return Type();

  auto *genericEnv = getGenericEnvironment();
  return genericEnv->mapTypeIntoContext(
      *getSubclassTrailingObjects<Type>());
}

Type ArchetypeType::getValueType() const {
  if (auto gp = getInterfaceType()->getAs<GenericTypeParamType>())
    return gp->getValueType();

  return Type();
}

Type ArchetypeType::getNestedType(AssociatedTypeDecl *assocType) {
  Type interfaceType = getInterfaceType();
  Type memberInterfaceType =
      DependentMemberType::get(interfaceType, assocType);
  auto genericSig = getGenericEnvironment()->getGenericSignature();
  if (genericSig->isValidTypeParameter(memberInterfaceType)) {
    return getGenericEnvironment()->getOrCreateArchetypeFromInterfaceType(
        memberInterfaceType);
  }

  return Type();
}

Type ArchetypeType::getNestedTypeByName(Identifier name) {
  Type interfaceType = getInterfaceType();
  Type memberInterfaceType = DependentMemberType::get(interfaceType, name);
  auto genericSig = getGenericEnvironment()->getGenericSignature();
  if (genericSig->isValidTypeParameter(memberInterfaceType)) {
    return getGenericEnvironment()->getOrCreateArchetypeFromInterfaceType(
        memberInterfaceType);
  }

  return Type();
}

Identifier ArchetypeType::getName() const {
  assert(InterfaceType);
  if (auto depMemTy = InterfaceType->getAs<DependentMemberType>())
    return depMemTy->getName();
  return InterfaceType->castTo<GenericTypeParamType>()->getName();
}

std::string ArchetypeType::getFullName() const {
  return InterfaceType.getString();
}

/// Determine the recursive type properties for an archetype.
RecursiveTypeProperties ArchetypeType::archetypeProperties(
    RecursiveTypeProperties properties,
    ArrayRef<ProtocolDecl *> conformsTo,
    Type superclass,
    SubstitutionMap subs
) {
  properties |= subs.getRecursiveProperties();

  for (auto proto : conformsTo) {
    if (proto->isUnsafe()) {
      properties |= RecursiveTypeProperties::IsUnsafe;
      break;
    }
  }

  if (superclass) {
    auto superclassProps = superclass->getRecursiveProperties();
    superclassProps.removeHasTypeParameter();
    superclassProps.removeHasDependentMember();
    properties |= superclassProps;
  }

  return properties;
}

PrimaryArchetypeType::PrimaryArchetypeType(const ASTContext &Ctx,
                                     GenericEnvironment *GenericEnv,
                                     Type InterfaceType,
                                     ArrayRef<ProtocolDecl *> ConformsTo,
                                     Type Superclass, LayoutConstraint Layout,
                                     RecursiveTypeProperties Properties)
  : ArchetypeType(TypeKind::PrimaryArchetype, Ctx, Properties,
                  InterfaceType, ConformsTo, Superclass, Layout, GenericEnv)
{
  assert(!InterfaceType->isParameterPack());
}

CanPrimaryArchetypeType
PrimaryArchetypeType::getNew(const ASTContext &Ctx,
                      GenericEnvironment *GenericEnv,
                      Type InterfaceType,
                      SmallVectorImpl<ProtocolDecl *> &ConformsTo,
                      Type Superclass,
                      LayoutConstraint Layout) {
  assert(!Superclass || Superclass->getClassOrBoundGenericClass());
  assert(GenericEnv && "missing generic environment for archetype");

  // Gather the set of protocol declarations to which this archetype conforms.
  ProtocolType::canonicalizeProtocols(ConformsTo);

  RecursiveTypeProperties Properties = archetypeProperties(
    RecursiveTypeProperties::HasPrimaryArchetype,
    ConformsTo, Superclass, SubstitutionMap());
  assert(!Properties.hasTypeVariable());

  auto arena = AllocationArena::Permanent;
  void *mem = Ctx.Allocate(
    PrimaryArchetypeType::totalSizeToAlloc<ProtocolDecl *, Type, LayoutConstraint>(
          ConformsTo.size(), Superclass ? 1 : 0, Layout ? 1 : 0),
      alignof(PrimaryArchetypeType), arena);

  return CanPrimaryArchetypeType(::new (mem) PrimaryArchetypeType(
      Ctx, GenericEnv, InterfaceType, ConformsTo, Superclass, Layout,
      Properties));
}

OpaqueTypeArchetypeType::OpaqueTypeArchetypeType(
    GenericEnvironment *environment,
    RecursiveTypeProperties properties,
    Type interfaceType,
    ArrayRef<ProtocolDecl*> conformsTo,
    Type superclass, LayoutConstraint layout)
  : ArchetypeType(TypeKind::OpaqueTypeArchetype, interfaceType->getASTContext(),
                  properties, interfaceType, conformsTo, superclass, layout,
                  environment)
{
  assert(!interfaceType->isParameterPack());
}

OpaqueTypeDecl *OpaqueTypeArchetypeType::getDecl() const {
  return Environment->getOpaqueTypeDecl();
}

SubstitutionMap OpaqueTypeArchetypeType::getSubstitutions() const {
  return Environment->getOuterSubstitutions();
}

OpenedArchetypeType::OpenedArchetypeType(
    GenericEnvironment *environment, Type interfaceType,
    ArrayRef<ProtocolDecl *> conformsTo, Type superclass,
    LayoutConstraint layout, RecursiveTypeProperties properties)
  : LocalArchetypeType(TypeKind::OpenedArchetype,
                       interfaceType->getASTContext(), properties,
                       interfaceType, conformsTo, superclass, layout,
                       environment)
{
  assert(!interfaceType->isParameterPack());
}

PackArchetypeType::PackArchetypeType(
    const ASTContext &Ctx, GenericEnvironment *GenericEnv, Type InterfaceType,
    ArrayRef<ProtocolDecl *> ConformsTo, Type Superclass,
    LayoutConstraint Layout, PackShape Shape,
    RecursiveTypeProperties Properties)
  : ArchetypeType(TypeKind::PackArchetype, Ctx, Properties,
                    InterfaceType, ConformsTo, Superclass, Layout, GenericEnv) {
  assert(InterfaceType->isParameterPack());
  *getTrailingObjects<PackShape>() = Shape;
}

CanPackArchetypeType
PackArchetypeType::get(const ASTContext &Ctx,
                       GenericEnvironment *GenericEnv,
                       Type InterfaceType, Type ShapeType,
                       SmallVectorImpl<ProtocolDecl *> &ConformsTo,
                       Type Superclass, LayoutConstraint Layout) {
  assert(!Superclass || Superclass->getClassOrBoundGenericClass());
  assert(GenericEnv && "missing generic environment for archetype");

  // Gather the set of protocol declarations to which this archetype conforms.
  ProtocolType::canonicalizeProtocols(ConformsTo);

  RecursiveTypeProperties properties = archetypeProperties(
    (RecursiveTypeProperties::HasPrimaryArchetype |
     RecursiveTypeProperties::HasPackArchetype),
    ConformsTo, Superclass, SubstitutionMap());
  assert(!properties.hasTypeVariable());

  auto arena = AllocationArena::Permanent;
  void *mem =
      Ctx.Allocate(PackArchetypeType::totalSizeToAlloc<ProtocolDecl *, Type,
                                                       LayoutConstraint, PackShape>(
                       ConformsTo.size(), Superclass ? 1 : 0, Layout ? 1 : 0,
                       /*shapeSize*/1),
                   alignof(PackArchetypeType), arena);

  return CanPackArchetypeType(::new (mem) PackArchetypeType(
      Ctx, GenericEnv, InterfaceType, ConformsTo, Superclass, Layout,
      {ShapeType}, properties));
}

CanType PackArchetypeType::getReducedShape() {
  // mapTypeIntoContext() also calls getReducedShape() via
  // PackExpansionType::get(), so avoid that by short-circuiting
  // the case where the pack archetype represents its own
  // shape class.
  auto shapeType = getTrailingObjects<PackShape>()->shapeType;
  if (shapeType->isEqual(getInterfaceType()))
    return CanType(this);

  return getGenericEnvironment()
      ->mapTypeIntoContext(shapeType)
      ->getCanonicalType();
}

ElementArchetypeType::ElementArchetypeType(
    const ASTContext &Ctx, GenericEnvironment *GenericEnv, Type InterfaceType,
    ArrayRef<ProtocolDecl *> ConformsTo, Type Superclass,
    LayoutConstraint Layout)
    : LocalArchetypeType(TypeKind::ElementArchetype, Ctx,
                         RecursiveTypeProperties::HasElementArchetype,
                         InterfaceType,
                         ConformsTo, Superclass, Layout, GenericEnv) {
}

CanTypeWrapper<ElementArchetypeType> ElementArchetypeType::getNew(
    GenericEnvironment *environment, Type interfaceType,
    ArrayRef<ProtocolDecl *> conformsTo, Type superclass,
    LayoutConstraint layout) {
  assert(!interfaceType->isParameterPack());
  assert((!superclass || !superclass->hasArchetype())
         && "superclass must be interface type");
  auto arena = AllocationArena::Permanent;
  ASTContext &ctx = interfaceType->getASTContext();
  void *mem = ctx.Allocate(
    ElementArchetypeType::totalSizeToAlloc<ProtocolDecl *,Type,LayoutConstraint>(
      conformsTo.size(),
      superclass ? 1 : 0,
      layout ? 1 : 0),
      alignof(ElementArchetypeType), arena);

  return CanElementArchetypeType(::new (mem) ElementArchetypeType(
      ctx, environment, interfaceType, conformsTo, superclass, layout));
}

UUID ElementArchetypeType::getOpenedElementID() const {
  return getGenericEnvironment()->getOpenedElementUUID();
}

CanExistentialType CanExistentialType::get(CanType constraint) {
  assert(!(constraint->isAny() || constraint->isAnyObject()) &&
         "Any(Object) may not apppear as canonical constraint type");
  assert(!constraint->is<ExistentialMetatypeType>() &&
         "Existential metatype may not apppear as canonical constraint type");
  return CanExistentialType(
      ExistentialType::get(constraint)->castTo<ExistentialType>());
}

void ProtocolCompositionType::Profile(llvm::FoldingSetNodeID &ID,
                                      ArrayRef<Type> Members,
                                      InvertibleProtocolSet Inverses,
                                      bool HasExplicitAnyObject) {
  ID.AddBoolean(HasExplicitAnyObject);
  for (auto T : Members)
    ID.AddPointer(T.getPointer());
  for (auto IP : Inverses)
    ID.AddInteger((uint8_t)IP);
}

ParameterizedProtocolType::ParameterizedProtocolType(
    const ASTContext *ctx,
    ProtocolType *base, ArrayRef<Type> args,
    RecursiveTypeProperties properties)
  : TypeBase(TypeKind::ParameterizedProtocol, /*Context=*/ctx, properties),
    Base(base) {
  assert(args.size() > 0);
  Bits.ParameterizedProtocolType.ArgCount = args.size();
  for (unsigned i : indices(args))
    getTrailingObjects<Type>()[i] = args[i];
}

void ParameterizedProtocolType::Profile(llvm::FoldingSetNodeID &ID,
                                        ProtocolType *baseTy,
                                        ArrayRef<Type> args) {
  ID.AddPointer(baseTy);
  for (auto arg : args)
    ID.AddPointer(arg.getPointer());
}

void ParameterizedProtocolType::getRequirements(
    Type baseType, SmallVectorImpl<Requirement> &reqs) const {
  auto *protoDecl = getProtocol();

  auto assocTypes = protoDecl->getPrimaryAssociatedTypes();
  auto argTypes = getArgs();
  assert(argTypes.size() <= assocTypes.size());

  auto conformance = lookupConformance(baseType, protoDecl);
  auto subMap = SubstitutionMap::getProtocolSubstitutions(
      protoDecl, baseType, conformance);

  for (unsigned i : indices(argTypes)) {
    auto argType = argTypes[i];
    auto *assocType = assocTypes[i];

    Type subjectType;
    if (baseType->isTypeParameter()) {
      // Fast path.
      subjectType = DependentMemberType::get(baseType, assocType);
    } else {
      // Do a general type substitution here because the associated type might be
      // from an inherited protocol, in which case we will evaluate a non-trivial
      // conformance path.
      subjectType = assocType->getDeclaredInterfaceType().subst(subMap);
    }

    reqs.emplace_back(RequirementKind::SameType, subjectType, argType);
  }
}

bool ProtocolType::requiresClass() {
  return getDecl()->requiresClass();
}

bool ProtocolCompositionType::requiresClass() {
  return getExistentialLayout().requiresClass();
}

/// Constructs a protocol composition corresponding to the `Any` type.
Type ProtocolCompositionType::theAnyType(const ASTContext &C) {
  return ProtocolCompositionType::get(C, {}, /*Inverses=*/{},
                                      /*HasExplicitAnyObject=*/false);
}

/// Constructs a protocol composition containing the `AnyObject` constraint.
Type ProtocolCompositionType::theAnyObjectType(const ASTContext &C) {
  return ProtocolCompositionType::get(C, {}, /*Inverses=*/{},
                                      /*HasExplicitAnyObject=*/true);
}

Type ProtocolCompositionType::getInverseOf(const ASTContext &C,
                                           InvertibleProtocolKind IP) {
  return ProtocolCompositionType::get(C, {}, /*Inverses=*/{IP},
                                      /*HasExplicitAnyObject=*/false);
}

Type ProtocolCompositionType::withoutMarkerProtocols() const {
  SmallVector<Type, 4> newMembers;
  llvm::copy_if(getMembers(), std::back_inserter(newMembers), [](Type member) {
    auto *P = member->getAs<ProtocolType>();
    return !(P && P->getDecl()->isMarkerProtocol());
  });

  if (newMembers.size() == getMembers().size())
    return Type(const_cast<ProtocolCompositionType *>(this));

  return ProtocolCompositionType::get(getASTContext(), newMembers,
                                      getInverses(), hasExplicitAnyObject());
}

Type ProtocolCompositionType::get(const ASTContext &C,
                                  ArrayRef<Type> Members,
                                  InvertibleProtocolSet Inverses,
                                  bool HasExplicitAnyObject) {
  // Fast path for 'AnyObject', 'Any', and '~Copyable'.
  if (Members.empty()) {
    return build(C, Members, Inverses, HasExplicitAnyObject);
  }

  // Whether this composition has an `AnyObject` or protocol-inverse member
  // that is not reflected in the Members array.
  auto haveExtraMember = [&]{
    return HasExplicitAnyObject || !Inverses.empty();
  };

  // If there's a single member and no layout constraint or inverses,
  // return that type.
  if (Members.size() == 1 && !haveExtraMember()) {
    return Members.front();
  }

  for (Type t : Members) {
    if (!t->isCanonical())
      return build(C, Members, Inverses, HasExplicitAnyObject);
  }

  Type Superclass;
  SmallVector<ProtocolDecl *, 4> Protocols;
  ParameterizedProtocolMap Parameterized;
  for (Type t : Members) {
    addProtocols(t, Protocols, Parameterized, Superclass,
                 Inverses, HasExplicitAnyObject);
  }

  // Form the set of canonical component types.
  SmallVector<Type, 4> CanTypes;

  // The presence of a superclass constraint makes AnyObject redundant.
  if (Superclass) {
    HasExplicitAnyObject = false;
    CanTypes.push_back(Superclass->getCanonicalType());
  }

  // If there are any parameterized protocols, the canonicalization
  // algorithm gets more complex.
  canonicalizeProtocols(Protocols, &Parameterized);

  for (auto proto : Protocols) {
    // If we have a parameterized type for this protocol, use the
    // canonical type of that.  Sema should prevent us from building
    // compositions with the same protocol and conflicting constraints.
    if (!Parameterized.empty()) {
      auto it = Parameterized.find(proto);
      if (it != Parameterized.end()) {
        CanTypes.push_back(it->second->getCanonicalType());
        continue;
      }
    }

    CanTypes.push_back(proto->getDeclaredInterfaceType());
  }

  // If one member remains with no extra members, return that type.
  if (CanTypes.size() == 1 && !haveExtraMember())
    return CanTypes.front();

  return build(C, CanTypes, Inverses, HasExplicitAnyObject);
}

CanType ProtocolCompositionType::getMinimalCanonicalType() const {
  auto &Ctx = getASTContext();

  auto existentialSig = Ctx.getOpenedExistentialSignature(getCanonicalType());
  auto result = existentialSig.OpenedSig->getUpperBound(
      existentialSig.SelfType,
      /*forExistentialSelf=*/true,
      /*includeParameterizedProtocols=*/true);
  return result.subst(existentialSig.Generalization)->getCanonicalType();
}

ClangTypeInfo AnyFunctionType::getClangTypeInfo() const {
  switch (getKind()) {
  case TypeKind::Function:
    return cast<FunctionType>(this)->getClangTypeInfo();
  case TypeKind::GenericFunction:
    // Generic functions do not have C types.
    return ClangTypeInfo();
  default:
    llvm_unreachable("Illegal type kind for AnyFunctionType.");
  }
}

Type AnyFunctionType::getThrownError() const {
  switch (getKind()) {
  case TypeKind::Function:
    return cast<FunctionType>(this)->getThrownError();
  case TypeKind::GenericFunction:
    return cast<GenericFunctionType>(this)->getThrownError();
  default:
    llvm_unreachable("Illegal type kind for AnyFunctionType.");
  }
}

bool AnyFunctionType::isSendable() const {
  return getExtInfo().isSendable();
}

Type AnyFunctionType::getGlobalActor() const {
  switch (getKind()) {
  case TypeKind::Function:
    return cast<FunctionType>(this)->getGlobalActor();
  case TypeKind::GenericFunction:
    return cast<GenericFunctionType>(this)->getGlobalActor();
  default:
    llvm_unreachable("Illegal type kind for AnyFunctionType.");
  }
}

llvm::ArrayRef<LifetimeDependenceInfo>
AnyFunctionType::getLifetimeDependencies() const {
  switch (getKind()) {
  case TypeKind::Function:
    return cast<FunctionType>(this)->getLifetimeDependencies();
  case TypeKind::GenericFunction:
    return cast<GenericFunctionType>(this)->getLifetimeDependencies();

  default:
    llvm_unreachable("Illegal type kind for AnyFunctionType.");
  }
}

std::optional<LifetimeDependenceInfo>
AnyFunctionType::getLifetimeDependenceFor(unsigned targetIndex) const {
  switch (getKind()) {
  case TypeKind::Function:
    return cast<FunctionType>(this)->getLifetimeDependenceFor(targetIndex);
  case TypeKind::GenericFunction:
    return cast<GenericFunctionType>(this)->getLifetimeDependenceFor(
        targetIndex);

  default:
    llvm_unreachable("Illegal type kind for AnyFunctionType.");
  }
}

std::optional<LifetimeDependenceInfo>
AnyFunctionType::getLifetimeDependenceForResult(const ValueDecl *decl) const {
  auto resultIndex =
      decl->hasCurriedSelf() ? getNumParams() + 1 : getNumParams();
  return getLifetimeDependenceFor(resultIndex);
}

ClangTypeInfo AnyFunctionType::getCanonicalClangTypeInfo() const {
  return getClangTypeInfo().getCanonical();
}

ASTExtInfo
AnyFunctionType::getCanonicalExtInfo(bool useClangFunctionType) const {
  assert(hasExtInfo());

  CanGenericSignature genericSig;
  if (auto *genericFnTy = dyn_cast<GenericFunctionType>(this))
    genericSig = genericFnTy->getGenericSignature().getCanonicalSignature();

  Type globalActor = getGlobalActor();
  if (globalActor)
    globalActor = globalActor->getReducedType(genericSig);

  // When there is an explicitly-specified thrown error, canonicalize it's type.
  auto bits = Bits.AnyFunctionType.ExtInfoBits;
  Type thrownError = getThrownError();
  if (thrownError) {
    thrownError = thrownError->getReducedType(genericSig);

    //   - If the thrown error is `any Error`, the function throws and we
    //     drop the thrown error.
    if (thrownError->isEqual(
            thrownError->getASTContext().getErrorExistentialType())) {
      thrownError = Type();

      //   - If the thrown error is `Never`, the function does not throw and
      //     we drop the thrown error.
    } else if (thrownError->isNever()) {
      thrownError = Type();
      bits = bits & ~ASTExtInfoBuilder::ThrowsMask;
    }
  }

  return ExtInfo(bits,
                 useClangFunctionType ? getCanonicalClangTypeInfo()
                                      : ClangTypeInfo(),
                 globalActor, thrownError, getLifetimeDependencies());
}

bool AnyFunctionType::hasNonDerivableClangType() {
  auto clangTypeInfo = getClangTypeInfo();
  if (clangTypeInfo.empty())
    return false;
  auto computedClangType = getASTContext().getClangFunctionType(
      getParams(), getResult(), getRepresentation());
  assert(computedClangType && "Failed to compute Clang type.");
  return clangTypeInfo != ClangTypeInfo(computedClangType);
}

bool AnyFunctionType::hasSameExtInfoAs(const AnyFunctionType *otherFn) {
  return getExtInfo().isEqualTo(otherFn->getExtInfo(), useClangTypes(this));
}

bool swift::hasIsolatedParameter(ArrayRef<AnyFunctionType::Param> params) {
  for (auto &param : params) {
    if (param.isIsolated())
      return true;
  }
  return false;
}

ClangTypeInfo SILFunctionType::getClangTypeInfo() const {
  if (!Bits.SILFunctionType.HasClangTypeInfo)
    return ClangTypeInfo();
  auto *info = getTrailingObjects<ClangTypeInfo>();
  assert(!info->empty() &&
         "If the ClangTypeInfo was empty, we shouldn't have stored it.");
  return *info;
}

bool SILFunctionType::hasNonDerivableClangType() {
  auto clangTypeInfo = getClangTypeInfo();
  if (clangTypeInfo.empty())
    return false;
  auto results = getResults();
  auto computedClangType = getASTContext().getCanonicalClangFunctionType(
      getParameters(),
      results.empty() ? std::nullopt : std::optional<SILResultInfo>(results[0]),
      getRepresentation());
  assert(computedClangType && "Failed to compute Clang type.");
  return clangTypeInfo != ClangTypeInfo(computedClangType);
}

bool SILFunctionType::hasSameExtInfoAs(const SILFunctionType *otherFn) {
  return getExtInfo().isEqualTo(otherFn->getExtInfo(), useClangTypes(this));
}

DependentMemberType *TypeBase::findUnresolvedDependentMemberType() {
  if (!hasTypeParameter()) return nullptr;

  DependentMemberType *unresolvedDepMemTy = nullptr;
  Type(this).findIf([&](Type type) -> bool {
    if (auto depMemTy = type->getAs<DependentMemberType>()) {
      if (depMemTy->getAssocType() == nullptr) {
        unresolvedDepMemTy = depMemTy;
        return true;
      }
    }
    return false;
  });

  return unresolvedDepMemTy;
}

bool TypeBase::isNoEscape() const {
  auto type = getCanonicalType();

  if (auto silFuncTy = dyn_cast<SILFunctionType>(type))
    return silFuncTy->isNoEscape();

  if (auto funcTy = dyn_cast<FunctionType>(type))
    return funcTy->isNoEscape();

  if (auto tupleTy = dyn_cast<TupleType>(type)) {
    for (auto eltTy : tupleTy.getElementTypes())
      if (eltTy->isNoEscape())
        return true;
  }

  return false;
}

Identifier DependentMemberType::getName() const {
  if (NameOrAssocType.is<Identifier>())
    return NameOrAssocType.get<Identifier>();

  return NameOrAssocType.get<AssociatedTypeDecl *>()->getName();
}

Type Type::transformRec(
    llvm::function_ref<std::optional<Type>(TypeBase *)> fn) const {
  class Transform : public TypeTransform<Transform> {
    llvm::function_ref<std::optional<Type>(TypeBase *)> fn;
  public:
    explicit Transform(llvm::function_ref<std::optional<Type>(TypeBase *)> fn,
                       ASTContext &ctx) : TypeTransform(ctx), fn(fn) {}

    std::optional<Type> transform(TypeBase *type, TypePosition position) {
      return fn(type);
    }
  };

  return Transform(fn, (*this)->getASTContext()).doIt(*this, TypePosition::Invariant);
}

Type Type::transformWithPosition(
    TypePosition pos,
    llvm::function_ref<std::optional<Type>(TypeBase *, TypePosition)> fn)
    const {
  class Transform : public TypeTransform<Transform> {
    llvm::function_ref<std::optional<Type>(TypeBase *, TypePosition)> fn;
  public:
    explicit Transform(llvm::function_ref<std::optional<Type>(TypeBase *, TypePosition)> fn,
                       ASTContext &ctx) : TypeTransform(ctx), fn(fn) {}

    std::optional<Type> transform(TypeBase *type, TypePosition position) {
      return fn(type, position);
    }
  };

  return Transform(fn, (*this)->getASTContext()).doIt(*this, pos);
}

bool Type::findIf(llvm::function_ref<bool(Type)> pred) const {
  class Walker : public TypeWalker {
    llvm::function_ref<bool(Type)> Pred;
  public:
    explicit Walker(llvm::function_ref<bool(Type)> pred) : Pred(pred) {}

    Action walkToTypePre(Type ty) override {
      if (Pred(ty))
        return Action::Stop;
      return Action::Continue;
    }
  };

  return walk(Walker(pred));
}

TypeTraitResult TypeBase::canBeClass() {
  // Any bridgeable object type can be a class.
  if (isBridgeableObjectType())
    return TypeTraitResult::Is;

  CanType self = getCanonicalType();

  // Archetypes with a trivial layout constraint can never
  // represent a class.
  if (auto Archetype = dyn_cast<ArchetypeType>(self)) {
    if (auto Layout = Archetype->getLayoutConstraint()) {
      if (Layout->isTrivial())
        return TypeTraitResult::IsNot;
      if (Layout->isClass())
        return TypeTraitResult::Is;
    }
  }

  // Dependent types might be bound to classes.
  if (isa<SubstitutableType>(self))
    return TypeTraitResult::CanBe;
  if (isa<DependentMemberType>(self))
    return TypeTraitResult::CanBe;
  
  return TypeTraitResult::IsNot;
}

bool Type::isPrivateSystemType(bool treatNonBuiltinProtocolsAsPublic) const {
  Type Ty = *this;
  if (!Ty)
    return false;

  if (auto existential = dyn_cast<ExistentialType>(Ty.getPointer()))
    return existential->getConstraintType().isPrivateSystemType(
        treatNonBuiltinProtocolsAsPublic);

  // A 'public' typealias can have an 'internal' type.
  if (auto *NAT = dyn_cast<TypeAliasType>(Ty.getPointer())) {
    auto *AliasDecl = NAT->getDecl();
    if (auto parent = NAT->getParent()) {
      if (parent.isPrivateSystemType(treatNonBuiltinProtocolsAsPublic))
        return true;
    }

    if (AliasDecl->isPrivateSystemDecl(treatNonBuiltinProtocolsAsPublic))
      return true;

    return Type(NAT->getSinglyDesugaredType())
        .isPrivateSystemType(treatNonBuiltinProtocolsAsPublic);
  }

  if (Type Unwrapped = Ty->getOptionalObjectType())
    return Unwrapped.isPrivateSystemType(treatNonBuiltinProtocolsAsPublic);

  if (auto TyD = Ty->getAnyNominal())
    if (TyD->isPrivateSystemDecl(treatNonBuiltinProtocolsAsPublic))
      return true;

  return false;
}

// NOTE: If you add a new SOMETIMES_LOADABLE_CHECKED_REF_STORAGE type, then you
// may or may not want to emulate what 'unowned' does.
bool UnownedStorageType::isLoadable(ResilienceExpansion resilience) const {
  auto ty = getReferentType();
  if (auto underlyingTy = ty->getOptionalObjectType())
    ty = underlyingTy;
  return ty->getReferenceCounting() == ReferenceCounting::Native;
}

ReferenceCounting TypeBase::getReferenceCounting() {
  CanType type = getCanonicalType();
  ASTContext &ctx = type->getASTContext();

  if (isForeignReferenceType())
    return lookThroughAllOptionalTypes()
                   ->getClassOrBoundGenericClass()
                   ->hasRefCountingAnnotations()
               ? ReferenceCounting::Custom
               : ReferenceCounting::None;

  // In the absence of Objective-C interoperability, everything uses native
  // reference counting or is the builtin BridgeObject.
  if (!ctx.LangOpts.EnableObjCInterop) {
    return type->getKind() == TypeKind::BuiltinBridgeObject
             ? ReferenceCounting::Bridge
             : ReferenceCounting::Native;
  }

  switch (type->getKind()) {
#define SUGARED_TYPE(id, parent) case TypeKind::id:
#define TYPE(id, parent)
#include "swift/AST/TypeNodes.def"
    llvm_unreachable("sugared canonical type?");

  case TypeKind::BuiltinNativeObject:
  case TypeKind::SILBox:
    return ReferenceCounting::Native;

  case TypeKind::BuiltinBridgeObject:
    return ReferenceCounting::Bridge;

  case TypeKind::Class:
    return cast<ClassType>(type)->getDecl()->getObjectModel();
  case TypeKind::BoundGenericClass:
    return cast<BoundGenericClassType>(type)->getDecl()->getObjectModel();
  case TypeKind::UnboundGeneric:
    return cast<ClassDecl>(cast<UnboundGenericType>(type)->getDecl())
        ->getObjectModel();

  case TypeKind::DynamicSelf:
    return cast<DynamicSelfType>(type).getSelfType()
        ->getReferenceCounting();
  case TypeKind::SILMoveOnlyWrapped:
    return cast<SILMoveOnlyWrappedType>(type)
        ->getInnerType()
        ->getReferenceCounting();

  case TypeKind::PrimaryArchetype:
  case TypeKind::OpenedArchetype:
  case TypeKind::OpaqueTypeArchetype:
  case TypeKind::PackArchetype:
  case TypeKind::ElementArchetype: {
    auto archetype = cast<ArchetypeType>(type);
    auto layout = archetype->getLayoutConstraint();
    (void)layout;
    assert(layout && layout->isRefCounted());
    if (auto supertype = archetype->getSuperclass())
      return supertype->getReferenceCounting();
    return ReferenceCounting::Unknown;
  }

  case TypeKind::Protocol:
  case TypeKind::ProtocolComposition: {
    auto layout = type->getExistentialLayout();
    assert(layout.requiresClass() && "Opaque existentials don't use refcounting");
    if (auto superclass = layout.getSuperclass())
      return superclass->getReferenceCounting();
    return ReferenceCounting::Unknown;
  }

  case TypeKind::ParameterizedProtocol: {
    return cast<ParameterizedProtocolType>(this)
      ->getBaseType()
      ->getReferenceCounting();
  }

  case TypeKind::Existential:
    return cast<ExistentialType>(type)->getConstraintType()
        ->getReferenceCounting();

  case TypeKind::Function:
  case TypeKind::GenericFunction:
  case TypeKind::SILFunction:
  case TypeKind::SILBlockStorage:
  case TypeKind::Error:
  case TypeKind::Unresolved:
  case TypeKind::BuiltinInteger:
  case TypeKind::BuiltinIntegerLiteral:
  case TypeKind::BuiltinFloat:
  case TypeKind::BuiltinRawPointer:
  case TypeKind::BuiltinRawUnsafeContinuation:
  case TypeKind::BuiltinJob:
  case TypeKind::BuiltinExecutor:
  case TypeKind::BuiltinDefaultActorStorage:
  case TypeKind::BuiltinNonDefaultDistributedActorStorage:
  case TypeKind::BuiltinPackIndex:
  case TypeKind::BuiltinUnsafeValueBuffer:
  case TypeKind::BuiltinVector:
  case TypeKind::Tuple:
  case TypeKind::Enum:
  case TypeKind::Struct:
  case TypeKind::Metatype:
  case TypeKind::ExistentialMetatype:
  case TypeKind::Module:
  case TypeKind::LValue:
  case TypeKind::InOut:
  case TypeKind::TypeVariable:
  case TypeKind::Placeholder:
  case TypeKind::BoundGenericEnum:
  case TypeKind::BoundGenericStruct:
  case TypeKind::SILToken:
  case TypeKind::GenericTypeParam:
  case TypeKind::DependentMember:
  case TypeKind::Pack:
  case TypeKind::PackExpansion:
  case TypeKind::PackElement:
  case TypeKind::SILPack:
  case TypeKind::BuiltinTuple:
  case TypeKind::ErrorUnion:
  case TypeKind::Integer:
  case TypeKind::BuiltinUnboundGeneric:
  case TypeKind::BuiltinFixedArray:
#define REF_STORAGE(Name, ...) \
  case TypeKind::Name##Storage:
#include "swift/AST/ReferenceStorage.def"
    llvm_unreachable("type is not a class reference");
  }

  llvm_unreachable("Unhandled type kind!");
}

//
// SILBoxType implementation
//

void SILBoxType::Profile(llvm::FoldingSetNodeID &id, SILLayout *Layout,
                         SubstitutionMap Substitutions) {
  id.AddPointer(Layout);
  Substitutions.profile(id);
}

static RecursiveTypeProperties getBoxRecursiveProperties(
    SILLayout *Layout, SubstitutionMap subMap) {
  RecursiveTypeProperties props;
  for (auto &field : Layout->getFields()) {
    auto fieldProps = field.getLoweredType()->getRecursiveProperties();
    fieldProps.removeHasTypeParameter();
    fieldProps.removeHasDependentMember();
    props |= fieldProps;
  }
  for (auto replacementType : subMap.getReplacementTypes()) {
    if (replacementType) props |= replacementType->getRecursiveProperties();
  }
  return props;
}

SILBoxType::SILBoxType(ASTContext &C,
                       SILLayout *Layout, SubstitutionMap Substitutions)
  : TypeBase(TypeKind::SILBox, &C,
             getBoxRecursiveProperties(Layout, Substitutions)),
    Layout(Layout), Substitutions(Substitutions) {
  assert(Substitutions.isCanonical());
}

AnyFunctionType *AnyFunctionType::getWithoutDifferentiability() const {
  SmallVector<Param, 8> newParams;
  for (auto &param : getParams()) {
    Param newParam(param.getPlainType(), param.getLabel(),
                   param.getParameterFlags().withNoDerivative(false));
    newParams.push_back(newParam);
  }
  auto nonDiffExtInfo =
      getExtInfo()
          .intoBuilder()
          .withDifferentiabilityKind(DifferentiabilityKind::NonDifferentiable)
          .build();
  if (isa<FunctionType>(this))
    return FunctionType::get(newParams, getResult(), nonDiffExtInfo);
  assert(isa<GenericFunctionType>(this));
  return GenericFunctionType::get(getOptGenericSignature(), newParams,
                                  getResult(), nonDiffExtInfo);
}

AnyFunctionType *AnyFunctionType::getWithoutThrowing() const {
  auto info = getExtInfo().intoBuilder().withThrows(false, Type()).build();
  return withExtInfo(info);
}

std::optional<Type> AnyFunctionType::getEffectiveThrownErrorType() const {
  // A non-throwing function... has no thrown interface type.
  if (!isThrowing())
    return std::nullopt;

  // If there is no specified thrown error type, it throws "any Error".
  Type thrownError = getThrownError();
  if (!thrownError)
    return getASTContext().getErrorExistentialType();

  // If the thrown interface type is "Never", this function does not throw.
  if (thrownError->isNever())
    return std::nullopt;

  // Otherwise, return the typed error.
  return thrownError;
}

Type AnyFunctionType::getEffectiveThrownErrorTypeOrNever() const {
  if (auto thrown = getEffectiveThrownErrorType())
    return *thrown;

  return getASTContext().getNeverType();
}

std::optional<TangentSpace>
TypeBase::getAutoDiffTangentSpace(LookupConformanceFn lookupConformance) {
  assert(lookupConformance);
  auto &ctx = getASTContext();

  Type cacheKey = this;
  auto lookup = ctx.AutoDiffTangentSpaces.find(cacheKey);
  if (lookup != ctx.AutoDiffTangentSpaces.end())
    return lookup->getSecond();
  auto cache = [&](std::optional<TangentSpace> tangentSpace) {
    ctx.AutoDiffTangentSpaces.insert({cacheKey, tangentSpace});
    return tangentSpace;
  };

  // For tuple types: the tangent space is a tuple of the elements'  tangent
  // space types, for the elements that have a tangent space.
  if (auto *tupleTy = getAs<TupleType>()) {
    SmallVector<TupleTypeElt, 8> newElts;
    for (auto elt : tupleTy->getElements()) {
      auto eltSpace = elt.getType()->getAutoDiffTangentSpace(lookupConformance);
      if (!eltSpace)
        continue;
      newElts.push_back(elt.getWithType(eltSpace->getType()));
    }
    if (newElts.empty())
      return cache(
          TangentSpace::getTuple(ctx.TheEmptyTupleType->castTo<TupleType>()));
    if (newElts.size() == 1)
      return cache(TangentSpace::getTangentVector(newElts.front().getType()));
    auto *tupleType = TupleType::get(newElts, ctx);
    return cache(TangentSpace::getTuple(tupleType));
  }

  // For `Differentiable`-conforming types: the tangent space is the
  // `TangentVector` associated type.
  auto *differentiableProtocol =
      ctx.getProtocol(KnownProtocolKind::Differentiable);
  if (!differentiableProtocol)
    return cache(std::nullopt);
  auto associatedTypeLookup =
      differentiableProtocol->lookupDirect(ctx.Id_TangentVector);
  assert(associatedTypeLookup.size() == 1);
  auto *assocDecl = cast<AssociatedTypeDecl>(associatedTypeLookup[0]);

  // Try to get the `TangentVector` associated type of `base`.
  // Return the associated type if it is valid.
  auto conformance = swift::lookupConformance(this, differentiableProtocol);
  auto assocTy = conformance.getTypeWitness(this, assocDecl);
  if (!assocTy->hasError())
    return cache(TangentSpace::getTangentVector(assocTy));

  // Otherwise, there is no associated tangent space. Return `None`.
  return cache(std::nullopt);
}

bool TypeBase::isForeignReferenceType() {
  if (auto *classDecl = lookThroughAllOptionalTypes()->getClassOrBoundGenericClass())
    return classDecl->isForeignReferenceType();
  return false;
}

bool TypeBase::hasSimpleTypeRepr() const {
  // NOTE: Please keep this logic in sync with TypeRepr::isSimple().
  switch (getKind()) {
  case TypeKind::Function:
  case TypeKind::GenericFunction:
    return false;

  case TypeKind::Metatype:
    return !cast<const AnyMetatypeType>(this)->hasRepresentation();

  case TypeKind::ExistentialMetatype:
  case TypeKind::Existential:
    return false;

  case TypeKind::OpaqueTypeArchetype:
  case TypeKind::OpenedArchetype:
    return false;

  case TypeKind::PrimaryArchetype: {
    auto archetype = cast<const PrimaryArchetypeType>(this);
    auto interface = archetype->getInterfaceType();
    return interface->hasSimpleTypeRepr();
  }

  case TypeKind::ProtocolComposition: {
    // 'Any', 'AnyObject' and single protocol compositions are simple
    auto composition = cast<const ProtocolCompositionType>(this);
    auto memberCount = composition->getMembers().size();
    if (composition->hasExplicitAnyObject())
      return memberCount == 0;
    return memberCount <= 1;
  }

  case TypeKind::GenericTypeParam: {
    if (cast<const GenericTypeParamType>(this)->getOpaqueDecl())
      return false;
    return true;
  }

  default:
    return true;
  }
}

bool CanType::isErrorExistentialType() const {
  if (!isExistentialTypeImpl(*this))
    return false;

  return const_cast<CanType *>(this)->getExistentialLayout().isErrorExistential();
}

bool CanType::isForeignReferenceType() {
  if (auto *classDecl = getPointer()->lookThroughAllOptionalTypes()->getClassOrBoundGenericClass())
    return classDecl->isForeignReferenceType();
  return false;
}

// Creates an `AnyFunctionType` from the given parameters, result type,
// generic signature, and `ExtInfo`.
static AnyFunctionType *
makeFunctionType(ArrayRef<AnyFunctionType::Param> parameters, Type resultType,
                 GenericSignature genericSignature,
                 AnyFunctionType::ExtInfo extInfo) {
  if (genericSignature)
    return GenericFunctionType::get(genericSignature, parameters, resultType,
                                    extInfo);
  return FunctionType::get(parameters, resultType, extInfo);
}

AnyFunctionType *AnyFunctionType::getAutoDiffDerivativeFunctionType(
    IndexSubset *parameterIndices, AutoDiffDerivativeFunctionKind kind,
    LookupConformanceFn lookupConformance, GenericSignature derivativeGenSig,
    bool makeSelfParamFirst) {
  assert(!parameterIndices->isEmpty() &&
         "Expected at least one differentiability parameter");
  auto &ctx = getASTContext();

  // If `derivativeGenSig` is not defined, use the current function's type
  // generic signature.
  if (!derivativeGenSig)
    derivativeGenSig = getOptGenericSignature();

  // Unwrap curry levels. At most, two parameter lists are necessary, for
  // curried method types with a `(Self)` parameter list.
  // TODO(TF-874): Simplify curry level logic.
  SmallVector<AnyFunctionType *, 2> curryLevels;
  auto *currentLevel = castTo<AnyFunctionType>();
  for (unsigned i : range(2)) {
    (void)i;
    if (currentLevel == nullptr)
      break;
    curryLevels.push_back(currentLevel);
    currentLevel = currentLevel->getResult()->getAs<AnyFunctionType>();
  }

  auto originalResult = curryLevels.back()->getResult();

  auto linearMapTypeExpected = getAutoDiffDerivativeFunctionLinearMapType(
      parameterIndices, kind.getLinearMapKind(), lookupConformance,
      makeSelfParamFirst);
  assert(linearMapTypeExpected && "Linear map type is invalid");
  Type linearMapType = linearMapTypeExpected.get();

  // Build the full derivative function type: `(T...) -> (R, LinearMapType)`.
  SmallVector<TupleTypeElt, 2> retElts;
  retElts.push_back(originalResult);
  retElts.push_back(linearMapType);
  auto retTy = TupleType::get(retElts, ctx);
  auto *derivativeFunctionType =
      makeFunctionType(curryLevels.back()->getParams(), retTy,
                       curryLevels.size() == 1 ? derivativeGenSig : nullptr,
                       curryLevels.back()->getExtInfo());

  // Wrap the derivative function type in additional curry levels.
  auto curryLevelsWithoutLast =
      ArrayRef<AnyFunctionType *>(curryLevels).drop_back(1);
  for (auto pair : enumerate(llvm::reverse(curryLevelsWithoutLast))) {
    unsigned i = pair.index();
    auto *curryLevel = pair.value();
    derivativeFunctionType = makeFunctionType(
        curryLevel->getParams(), derivativeFunctionType,
        i == curryLevelsWithoutLast.size() - 1 ? derivativeGenSig : nullptr,
        curryLevel->getExtInfo());
  }

  return derivativeFunctionType;
}

llvm::Expected<AnyFunctionType *>
AnyFunctionType::getAutoDiffDerivativeFunctionLinearMapType(
    IndexSubset *parameterIndices, AutoDiffLinearMapKind kind,
    LookupConformanceFn lookupConformance, bool makeSelfParamFirst) {
  auto &ctx = getASTContext();
  // Error if differentiability parameter indices are empty.
  if (parameterIndices->isEmpty())
    return llvm::make_error<DerivativeFunctionTypeError>(
        this, DerivativeFunctionTypeError::Kind::NoDifferentiabilityParameters);

  // Get differentiability parameters.
  SmallVector<AnyFunctionType::Param, 8> diffParams;
  getSubsetParameters(parameterIndices, diffParams,
                      /*reverseCurryLevels*/ !makeSelfParamFirst);

  // Get the original non-inout semantic result types.
  SmallVector<AutoDiffSemanticFunctionResultType, 1> originalResults;
  autodiff::getFunctionSemanticResults(this, parameterIndices, originalResults);
  // Error if no original semantic results.
  if (originalResults.empty())
    return llvm::make_error<DerivativeFunctionTypeError>(
        this, DerivativeFunctionTypeError::Kind::NoSemanticResults);

  // Accumulate non-semantic result tangent spaces.
  SmallVector<Type, 1> resultTanTypes, inoutTanTypes;
  for (auto i : range(originalResults.size())) {
    auto originalResult = originalResults[i];
    auto originalResultType = originalResult.type;

    // Voids currently have a defined tangent vector, so ignore them.
    if (originalResultType->isVoid())
      continue;

    // Get the original semantic result type's `TangentVector` associated type.
    // Error if a semantic result has no tangent space.
    auto resultTan =
        originalResultType->getAutoDiffTangentSpace(lookupConformance);
    if (!resultTan)
      return llvm::make_error<DerivativeFunctionTypeError>(
        this, DerivativeFunctionTypeError::Kind::NonDifferentiableResult,
        std::make_pair(originalResultType, unsigned(originalResult.index)));

    if (!originalResult.isSemanticResultParameter)
      resultTanTypes.push_back(resultTan->getType());
  }

  // Compute the result linear map function type.
  FunctionType *linearMapType;
  switch (kind) {
  case AutoDiffLinearMapKind::Differential: {
    // Compute the differential type, returned by JVP functions.
    //
    // Case 1: original function has no `inout` parameters.
    // - Original:     `(T0, T1, ...) -> R`
    // - Differential: `(T0.Tan, T1.Tan, ...) -> R.Tan`
    //
    // Case 2: original function has a wrt `inout` parameter.
    // - Original:      `(T0, inout T1, ...) -> Void`
    // - Differential:  `(T0.Tan, inout T1.Tan, ...) -> Void`
    SmallVector<AnyFunctionType::Param, 4> differentialParams;
    for (auto i : range(diffParams.size())) {
      auto diffParam = diffParams[i];
      auto paramType = diffParam.getPlainType();
      auto paramTan = paramType->getAutoDiffTangentSpace(lookupConformance);
      // Error if parameter has no tangent space.
      if (!paramTan)
        return llvm::make_error<DerivativeFunctionTypeError>(
            this,
            DerivativeFunctionTypeError::Kind::
                NonDifferentiableDifferentiabilityParameter,
            std::make_pair(paramType, i));

      differentialParams.push_back(AnyFunctionType::Param(
          paramTan->getType(), Identifier(), diffParam.getParameterFlags()));
    }
    Type differentialResult;
    if (resultTanTypes.empty()) {
      differentialResult = ctx.TheEmptyTupleType;
    } else if (resultTanTypes.size() == 1) {
      differentialResult = resultTanTypes.front();
    } else {
      SmallVector<TupleTypeElt, 2> differentialResults;
      for (auto i : range(resultTanTypes.size())) {
        auto resultTanType = resultTanTypes[i];
        differentialResults.push_back(
            TupleTypeElt(resultTanType, Identifier()));
      }
      differentialResult = TupleType::get(differentialResults, ctx);
    }

    // FIXME: Verify ExtInfo state is correct, not working by accident.
    FunctionType::ExtInfo info;
    linearMapType =
        FunctionType::get(differentialParams, differentialResult, info);
    break;
  }
  case AutoDiffLinearMapKind::Pullback: {
    // Compute the pullback type, returned by VJP functions.
    //
    // Case 1: original function has no `inout` parameters.
    // - Original: `(T0, T1, ...) -> R`
    // - Pullback: `R.Tan -> (T0.Tan, T1.Tan, ...)`
    //
    // Case 2: original function has wrt `inout` parameters.
    // - Original: `(T0, inout T1, ...) -> R`
    // - Pullback: `(R.Tan, inout T1.Tan) -> (T0.Tan, ...)`
    SmallVector<TupleTypeElt, 4> pullbackResults;
    SmallVector<AnyFunctionType::Param, 2> semanticResultParams;
    for (auto i : range(diffParams.size())) {
      auto diffParam = diffParams[i];
      auto paramType = diffParam.getPlainType();
      auto paramTan = paramType->getAutoDiffTangentSpace(lookupConformance);
      // Error if parameter has no tangent space.
      if (!paramTan)
        return llvm::make_error<DerivativeFunctionTypeError>(
            this,
            DerivativeFunctionTypeError::Kind::
                NonDifferentiableDifferentiabilityParameter,
            std::make_pair(paramType, i));

      if (diffParam.isAutoDiffSemanticResult()) {
        if (paramType->isVoid())
          continue;
        semanticResultParams.push_back(diffParam);
        continue;
      }
      pullbackResults.emplace_back(paramTan->getType());
    }
    Type pullbackResult;
    if (pullbackResults.empty()) {
      pullbackResult = ctx.TheEmptyTupleType;
    } else if (pullbackResults.size() == 1) {
      pullbackResult = pullbackResults.front().getType();
    } else {
      pullbackResult = TupleType::get(pullbackResults, ctx);
    }
    // First accumulate non-inout results as pullback parameters.
    SmallVector<FunctionType::Param, 2> pullbackParams;
    for (auto i : range(resultTanTypes.size())) {
      auto resultTanType = resultTanTypes[i];
      auto flags = ParameterTypeFlags().withInOut(false);
      pullbackParams.push_back(AnyFunctionType::Param(
          resultTanType, Identifier(), flags));
    }
    // Then append semantic result parameters.
    for (auto i : range(semanticResultParams.size())) {
      auto semanticResultParam = semanticResultParams[i];
      auto semanticResultParamType = semanticResultParam.getPlainType();
      auto semanticResultParamTan =
          semanticResultParamType->getAutoDiffTangentSpace(lookupConformance);
      auto flags = ParameterTypeFlags().withInOut(true);
      pullbackParams.push_back(AnyFunctionType::Param(
          semanticResultParamTan->getType(), Identifier(), flags));
    }
    // FIXME: Verify ExtInfo state is correct, not working by accident.
    FunctionType::ExtInfo info;
    linearMapType = FunctionType::get(pullbackParams, pullbackResult, info);
    break;
  }
  }

  assert(linearMapType && "Expected linear map type");
  return linearMapType;
}

CanSILFunctionType
SILFunctionType::withInvocationSubstitutions(SubstitutionMap subs) const {
  subs = subs.getCanonical();
  if (subs == getInvocationSubstitutions())
    return CanSILFunctionType(const_cast<SILFunctionType*>(this));

  assert(!subs || CanGenericSignature(subs.getGenericSignature())
                    == getInvocationGenericSignature());
  return SILFunctionType::get(getInvocationGenericSignature(),
                          getExtInfo(), getCoroutineKind(),
                          getCalleeConvention(),
                          getParameters(), getYields(), getResults(),
                          getOptionalErrorResult(),
                          getPatternSubstitutions(), subs,
                          const_cast<SILFunctionType*>(this)->getASTContext(),
                          getWitnessMethodConformanceOrInvalid());
}

CanSILFunctionType
SILFunctionType::withPatternSubstitutions(SubstitutionMap subs) const {
  subs = subs.getCanonical();
  if (subs == getPatternSubstitutions())
    return CanSILFunctionType(const_cast<SILFunctionType*>(this));

  assert(!subs || CanGenericSignature(subs.getGenericSignature())
                    == getPatternGenericSignature());
  return SILFunctionType::get(getInvocationGenericSignature(),
                          getExtInfo(), getCoroutineKind(),
                          getCalleeConvention(),
                          getParameters(), getYields(), getResults(),
                          getOptionalErrorResult(),
                          subs, getInvocationSubstitutions(),
                          const_cast<SILFunctionType*>(this)->getASTContext(),
                          getWitnessMethodConformanceOrInvalid());
}

CanSILFunctionType
SILFunctionType::withPatternSpecialization(CanGenericSignature sig,
                                           SubstitutionMap subs,
                                           ProtocolConformanceRef
                                             witnessConformance) const {
  assert(!hasInvocationSubstitutions());
  subs = subs.getCanonical();
  assert(!subs || CanGenericSignature(subs.getGenericSignature())
                    == getSubstGenericSignature());
  return SILFunctionType::get(sig,
                          getExtInfo(), getCoroutineKind(),
                          getCalleeConvention(),
                          getParameters(), getYields(), getResults(),
                          getOptionalErrorResult(),
                          subs, SubstitutionMap(),
                          const_cast<SILFunctionType*>(this)->getASTContext(),
                          witnessConformance);
}

APInt IntegerType::getValue() const {
  return BuiltinIntegerWidth::arbitrary().parse(getDigitsText(), /*radix*/ 0,
                                                isNegative());
}

SourceLoc swift::extractNearestSourceLoc(Type ty) {
  if (auto nominal = ty->getAnyNominal())
    return extractNearestSourceLoc(nominal);

  return SourceLoc();
}

StringRef swift::getNameForParamSpecifier(ParamSpecifier specifier) {
  switch (specifier) {
  case ParamSpecifier::Default:
    return "default";
  case ParamSpecifier::InOut:
    return "inout";
  case ParamSpecifier::Borrowing:
    return "borrowing";
  case ParamSpecifier::Consuming:
    return "consuming";
  case ParamSpecifier::LegacyShared:
    return "__shared";
  case ParamSpecifier::LegacyOwned:
    return "__owned";
  case ParamSpecifier::ImplicitlyCopyableConsuming:
    return "implicitly_copyable_consuming";
  }
}

std::optional<DiagnosticBehavior>
TypeBase::getConcurrencyDiagnosticBehaviorLimit(DeclContext *declCtx) const {
  auto *self = const_cast<TypeBase *>(this);

  if (auto *nomDecl = self->getNominalOrBoundGenericNominal()) {
    // First try to just grab the exact concurrency diagnostic behavior.
    if (auto result =
            swift::getConcurrencyDiagnosticBehaviorLimit(nomDecl, declCtx)) {
      return result;
    }

    // But if we get nothing, see if we can come up with diagnostic behavior by
    // merging our fields if we have a struct.
    if (auto *structDecl = dyn_cast<StructDecl>(nomDecl)) {
      std::optional<DiagnosticBehavior> diagnosticBehavior;
      auto substMap = self->getContextSubstitutionMap();
      for (auto storedProperty : structDecl->getStoredProperties()) {
        auto lhs = diagnosticBehavior.value_or(DiagnosticBehavior::Unspecified);
        auto astType = storedProperty->getInterfaceType().subst(substMap);
        auto rhs = astType->getConcurrencyDiagnosticBehaviorLimit(declCtx);
        auto result = lhs.merge(rhs.value_or(DiagnosticBehavior::Unspecified));
        if (result != DiagnosticBehavior::Unspecified)
          diagnosticBehavior = result;
      }
      return diagnosticBehavior;
    }
  }

  // When attempting to determine the diagnostic behavior limit of a tuple, just
  // merge for each of the elements.
  if (auto *tupleType = self->getAs<TupleType>()) {
    std::optional<DiagnosticBehavior> diagnosticBehavior;
    for (auto tupleType : tupleType->getElements()) {
      auto lhs = diagnosticBehavior.value_or(DiagnosticBehavior::Unspecified);

      auto type = tupleType.getType()->getCanonicalType();
      auto rhs = type->getConcurrencyDiagnosticBehaviorLimit(declCtx);
      auto result = lhs.merge(rhs.value_or(DiagnosticBehavior::Unspecified));
      if (result != DiagnosticBehavior::Unspecified)
        diagnosticBehavior = result;
    }
    return diagnosticBehavior;
  }

  return {};
}

GenericTypeParamKind
TypeBase::getMatchingParamKind() {
  if (auto gtpt = dyn_cast<GenericTypeParamType>(this)) {
    return gtpt->getParamKind();
  }
  
  if (auto arch = dyn_cast<ArchetypeType>(this)) {
    return arch->mapTypeOutOfContext()->getMatchingParamKind();
  }
  
  if (isa<IntegerType>(this)) {
    return GenericTypeParamKind::Value;
  }
  
  if (isa<PackType>(this)) {
    return GenericTypeParamKind::Pack;
  }
  
  return GenericTypeParamKind::Type;
}