File: Module.cpp

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (4136 lines) | stat: -rw-r--r-- 143,057 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
//===--- Module.cpp - Swift Language Module Implementation ----------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
//  This file implements the Module class and subclasses.
//
//===----------------------------------------------------------------------===//

#include "swift/AST/Module.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/ASTMangler.h"
#include "swift/AST/ASTPrinter.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/AccessScope.h"
#include "swift/AST/Builtins.h"
#include "swift/AST/ClangModuleLoader.h"
#include "swift/AST/DiagnosticsSema.h"
#include "swift/AST/ExistentialLayout.h"
#include "swift/AST/FileUnit.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/Import.h"
#include "swift/AST/ImportCache.h"
#include "swift/AST/LazyResolver.h"
#include "swift/AST/LinkLibrary.h"
#include "swift/AST/ModuleLoader.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/NameLookupRequests.h"
#include "swift/AST/PackConformance.h"
#include "swift/AST/ParseRequests.h"
#include "swift/AST/PrettyStackTrace.h"
#include "swift/AST/PrintOptions.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/SourceFile.h"
#include "swift/AST/SynthesizedFileUnit.h"
#include "swift/AST/Type.h"
#include "swift/AST/TypeCheckRequests.h"
#include "swift/Basic/Compiler.h"
#include "swift/Basic/SourceManager.h"
#include "swift/Basic/Statistic.h"
#include "swift/Basic/StringExtras.h"
#include "swift/Demangling/ManglingMacros.h"
#include "swift/Parse/Token.h"
#include "swift/Strings.h"
#include "clang/Basic/Module.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/TinyPtrVector.h"
#include "llvm/Support/MD5.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/SaveAndRestore.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/YAMLTraits.h"

using namespace swift;

static_assert(IsTriviallyDestructible<FileUnit>::value,
              "FileUnits are BumpPtrAllocated; the d'tor may not be called");
static_assert(IsTriviallyDestructible<LoadedFile>::value,
              "LoadedFiles are BumpPtrAllocated; the d'tor may not be called");

//===----------------------------------------------------------------------===//
// Builtin Module Name lookup
//===----------------------------------------------------------------------===//

class BuiltinUnit::LookupCache {
  /// The cache of identifiers we've already looked up.  We use a
  /// single hashtable for both types and values as a minor
  /// optimization; this prevents us from having both a builtin type
  /// and a builtin value with the same name, but that's okay.
  llvm::DenseMap<Identifier, ValueDecl*> Cache;

public:
  void lookupValue(Identifier Name, NLKind LookupKind, const BuiltinUnit &M,
                   SmallVectorImpl<ValueDecl*> &Result);
};

BuiltinUnit::LookupCache &BuiltinUnit::getCache() const {
  // FIXME: This leaks. Sticking this into ASTContext isn't enough because then
  // the DenseMap will leak.
  if (!Cache)
    const_cast<BuiltinUnit *>(this)->Cache = std::make_unique<LookupCache>();
  return *Cache;
}

void BuiltinUnit::LookupCache::lookupValue(
       Identifier Name, NLKind LookupKind, const BuiltinUnit &M,
       SmallVectorImpl<ValueDecl*> &Result) {
  // Only qualified lookup ever finds anything in the builtin module.
  if (LookupKind != NLKind::QualifiedLookup) return;

  ValueDecl *&Entry = Cache[Name];
  ASTContext &Ctx = M.getParentModule()->getASTContext();
  if (!Entry) {
    if (Type Ty = getBuiltinType(Ctx, Name.str())) {
      auto *TAD = new (Ctx) TypeAliasDecl(SourceLoc(), SourceLoc(),
                                          Name, SourceLoc(),
                                          /*genericparams*/nullptr,
                                          const_cast<BuiltinUnit*>(&M));
      TAD->setUnderlyingType(Ty);
      TAD->setAccess(AccessLevel::Public);
      Entry = TAD;
    }
  }

  if (!Entry)
    Entry = getBuiltinValueDecl(Ctx, Name);

  if (Entry)
    Result.push_back(Entry);
}

// Out-of-line because std::unique_ptr wants LookupCache to be complete.
BuiltinUnit::BuiltinUnit(ModuleDecl &M)
   : FileUnit(FileUnitKind::Builtin, M) {
  M.getASTContext().addDestructorCleanup(*this);
}

//===----------------------------------------------------------------------===//
// Normal Module Name Lookup
//===----------------------------------------------------------------------===//

SourceFile::~SourceFile() = default;

/// A utility for caching global lookups into SourceFiles and modules of
/// SourceFiles. This is used for lookup of top-level declarations, as well
/// as operator lookup (which looks into types) and AnyObject dynamic lookup
/// (which looks at all class members).
class swift::SourceLookupCache {
  /// A lookup map for value decls. When declarations are added they are added
  /// under all variants of the name they can be found under.
  class ValueDeclMap {
    llvm::DenseMap<DeclName, TinyPtrVector<ValueDecl *>> Members;

  public:
    void add(ValueDecl *VD) {
      if (!VD->hasName()) return;
      VD->getName().addToLookupTable(Members, VD);
    }

    void clear() {
      Members.shrink_and_clear();
    }

    decltype(Members)::const_iterator begin() const { return Members.begin(); }
    decltype(Members)::const_iterator end() const { return Members.end(); }
    decltype(Members)::const_iterator find(DeclName Name) const {
      return Members.find(Name);
    }
  };

  ValueDeclMap TopLevelValues;
  ValueDeclMap ClassMembers;
  bool MemberCachePopulated = false;
  DeclName UniqueMacroNamePlaceholder;

  template<typename T>
  using OperatorMap = llvm::DenseMap<Identifier, TinyPtrVector<T *>>;
  OperatorMap<OperatorDecl> Operators;
  OperatorMap<PrecedenceGroupDecl> PrecedenceGroups;

  template<typename Range>
  void addToUnqualifiedLookupCache(Range decls, bool onlyOperators);
  template<typename Range>
  void addToMemberCache(Range decls);

  using AuxiliaryDeclMap = llvm::DenseMap<DeclName, TinyPtrVector<MissingDecl *>>;
  AuxiliaryDeclMap TopLevelAuxiliaryDecls;

  /// Top-level macros that produce arbitrary names.
  SmallVector<MissingDecl *, 4> TopLevelArbitraryMacros;

  SmallVector<llvm::PointerUnion<Decl *, MacroExpansionExpr *>, 4>
      MayHaveAuxiliaryDecls;
  void populateAuxiliaryDeclCache();
  SourceLookupCache(ASTContext &ctx);

public:
  SourceLookupCache(const SourceFile &SF);
  SourceLookupCache(const ModuleDecl &Mod);

  void lookupValue(DeclName Name, NLKind LookupKind,
                   OptionSet<ModuleLookupFlags> Flags,
                   SmallVectorImpl<ValueDecl*> &Result);

  /// Retrieves all the operator decls. The order of the results is not
  /// guaranteed to be meaningful.
  void getOperatorDecls(SmallVectorImpl<OperatorDecl *> &results);

  /// Retrieves all the precedence groups. The order of the results is not
  /// guaranteed to be meaningful.
  void getPrecedenceGroups(SmallVectorImpl<PrecedenceGroupDecl *> &results);

  /// Look up an operator declaration.
  ///
  /// \param name The operator name ("+", ">>", etc.)
  /// \param fixity The fixity of the operator (infix, prefix or postfix).
  void lookupOperator(Identifier name, OperatorFixity fixity,
                      TinyPtrVector<OperatorDecl *> &results);

  /// Look up a precedence group.
  ///
  /// \param name The operator name ("+", ">>", etc.)
  void lookupPrecedenceGroup(Identifier name,
                             TinyPtrVector<PrecedenceGroupDecl *> &results);

  void lookupVisibleDecls(ImportPath::Access AccessPath,
                          VisibleDeclConsumer &Consumer,
                          NLKind LookupKind);

  void populateMemberCache(const SourceFile &SF);
  void populateMemberCache(const ModuleDecl &Mod);

  void lookupClassMembers(ImportPath::Access AccessPath,
                          VisibleDeclConsumer &consumer);

  void lookupClassMember(ImportPath::Access accessPath,
                         DeclName name,
                         SmallVectorImpl<ValueDecl*> &results);

  SmallVector<ValueDecl *, 0> AllVisibleValues;
};

SourceLookupCache &SourceFile::getCache() const {
  if (!Cache) {
    const_cast<SourceFile *>(this)->Cache =
        std::make_unique<SourceLookupCache>(*this);
  }
  return *Cache;
}

static Expr *getAsExpr(Decl *decl) { return nullptr; }
static Decl *getAsDecl(Decl *decl) { return decl; }

static Expr *getAsExpr(ASTNode node) { return node.dyn_cast<Expr *>(); }
static Decl *getAsDecl(ASTNode node) { return node.dyn_cast<Decl *>(); }

template<typename Range>
void SourceLookupCache::addToUnqualifiedLookupCache(Range items,
                                                    bool onlyOperators) {
  for (auto item : items) {
    // In script mode, we'll see macro expansion expressions for freestanding
    // macros.
    if (Expr *E = getAsExpr(item)) {
      if (auto MEE = dyn_cast<MacroExpansionExpr>(E)) {
        if (!onlyOperators)
          MayHaveAuxiliaryDecls.push_back(MEE);
      }
      continue;
    }

    Decl *D = getAsDecl(item);
    if (!D)
      continue;

    if (auto *VD = dyn_cast<ValueDecl>(D)) {
      if (onlyOperators ? VD->isOperator() : VD->hasName()) {
        // Cache the value under both its compound name and its full name.
        TopLevelValues.add(VD);

        if (!onlyOperators && VD->getAttrs().hasAttribute<CustomAttr>()) {
          MayHaveAuxiliaryDecls.push_back(VD);
        }
      }
    }

    if (auto *NTD = dyn_cast<NominalTypeDecl>(D))
      if (!NTD->hasUnparsedMembers() || NTD->maybeHasOperatorDeclarations())
        addToUnqualifiedLookupCache(NTD->getMembers(), true);

    if (auto *ED = dyn_cast<ExtensionDecl>(D)) {
      // Avoid populating the cache with the members of invalid extension
      // declarations.  These members can be used to point validation inside of
      // a malformed context.
      if (ED->isInvalid()) continue;

      if (ED->getAttrs().hasAttribute<CustomAttr>()) {
        MayHaveAuxiliaryDecls.push_back(ED);
      }

      if (!ED->hasUnparsedMembers() || ED->maybeHasOperatorDeclarations())
        addToUnqualifiedLookupCache(ED->getMembers(), true);
    }

    if (auto *OD = dyn_cast<OperatorDecl>(D))
      Operators[OD->getName()].push_back(OD);

    else if (auto *PG = dyn_cast<PrecedenceGroupDecl>(D))
      PrecedenceGroups[PG->getName()].push_back(PG);

    else if (auto *MED = dyn_cast<MacroExpansionDecl>(D)) {
      if (!onlyOperators)
        MayHaveAuxiliaryDecls.push_back(MED);
    } else if (auto TLCD = dyn_cast<TopLevelCodeDecl>(D)) {
      if (auto body = TLCD->getBody()){
        addToUnqualifiedLookupCache(body->getElements(), onlyOperators);
      }
    }
  }
}

void SourceLookupCache::populateMemberCache(const SourceFile &SF) {
  if (MemberCachePopulated)
    return;

  FrontendStatsTracer tracer(SF.getASTContext().Stats,
                             "populate-source-file-class-member-cache");
  addToMemberCache(SF.getTopLevelDecls());
  MemberCachePopulated = true;
}

void SourceLookupCache::populateMemberCache(const ModuleDecl &Mod) {
  if (MemberCachePopulated)
    return;

  FrontendStatsTracer tracer(Mod.getASTContext().Stats,
                             "populate-module-class-member-cache");

  for (const FileUnit *file : Mod.getFiles()) {
    assert(isa<SourceFile>(file) ||
           isa<SynthesizedFileUnit>(file));
    SmallVector<Decl *, 8> decls;
    file->getTopLevelDecls(decls);
    addToMemberCache(decls);
  }

  MemberCachePopulated = true;
}

template <typename Range>
void SourceLookupCache::addToMemberCache(Range decls) {
  for (Decl *D : decls) {
    if (auto *NTD = dyn_cast<NominalTypeDecl>(D)) {
      if (!NTD->hasUnparsedMembers() ||
          NTD->maybeHasNestedClassDeclarations() ||
          NTD->mayContainMembersAccessedByDynamicLookup())
        addToMemberCache(NTD->getMembers());

    } else if (auto *ED = dyn_cast<ExtensionDecl>(D)) {
      if (!ED->hasUnparsedMembers() ||
          ED->maybeHasNestedClassDeclarations() ||
          ED->mayContainMembersAccessedByDynamicLookup())
        addToMemberCache(ED->getMembers());

    } else if (auto *VD = dyn_cast<ValueDecl>(D)) {
      if (VD->canBeAccessedByDynamicLookup())
        ClassMembers.add(VD);
    }
  }
}

void SourceLookupCache::populateAuxiliaryDeclCache() {
  using MacroRef = llvm::PointerUnion<FreestandingMacroExpansion *, CustomAttr *>;
  for (auto item : MayHaveAuxiliaryDecls) {
    TopLevelCodeDecl *topLevelCodeDecl = nullptr;

    // Gather macro-introduced peer names.
    llvm::SmallDenseMap<MacroRef, llvm::SmallVector<DeclName, 2>>
        introducedNames;

    /// Introduce names for a freestanding macro.
    auto introduceNamesForFreestandingMacro =
      [&](FreestandingMacroExpansion *macroRef, Decl *decl, MacroRole role) {
        bool introducesArbitraryNames = false;
        namelookup::forEachPotentialResolvedMacro(
            decl->getDeclContext()->getModuleScopeContext(),
            macroRef->getMacroName(), role,
            [&](MacroDecl *macro, const MacroRoleAttr *roleAttr) {
              // First check for arbitrary names.
              if (roleAttr->hasNameKind(MacroIntroducedDeclNameKind::Arbitrary)) {
                introducesArbitraryNames = true;
              }

              macro->getIntroducedNames(role,
                                        /*attachedTo*/ nullptr,
                                        introducedNames[macroRef]);
            });

        return introducesArbitraryNames;
      };

    // Handle macro expansion expressions, which show up in when we have
    // freestanding macros in "script" mode.
    if (auto expr = item.dyn_cast<MacroExpansionExpr *>()) {
      topLevelCodeDecl = dyn_cast<TopLevelCodeDecl>(expr->getDeclContext());
      if (topLevelCodeDecl) {
        bool introducesArbitraryNames = false;
        if (introduceNamesForFreestandingMacro(
                expr, topLevelCodeDecl, MacroRole::Declaration))
          introducesArbitraryNames = true;

        if (introduceNamesForFreestandingMacro(
                expr, topLevelCodeDecl, MacroRole::CodeItem))
          introducesArbitraryNames = true;

        // Record this macro if it introduces arbitrary names.
        if (introducesArbitraryNames) {
          TopLevelArbitraryMacros.push_back(
              MissingDecl::forUnexpandedMacro(expr, topLevelCodeDecl));
        }
      }
    }

    auto *decl = item.dyn_cast<Decl *>();
    if (decl) {
      // This code deliberately avoids `forEachAttachedMacro`, because it
      // will perform overload resolution and possibly invoke unqualified
      // lookup for macro arguments, which will recursively populate the
      // auxiliary decl cache and cause request cycles.
      //
      // We do not need a fully resolved macro until expansion. Instead, we
      // conservatively consider peer names for all macro declarations with a
      // custom attribute name. Unqualified lookup for that name will later
      // invoke expansion of the macro, and will yield no results if the resolved
      // macro does not produce the requested name, so the only impact is possibly
      // expanding earlier than needed / unnecessarily looking in the top-level
      // auxiliary decl cache.
      for (auto attrConst : decl->getAttrs().getAttributes<CustomAttr>()) {
        auto *attr = const_cast<CustomAttr *>(attrConst);
        UnresolvedMacroReference macroRef(attr);
        bool introducesArbitraryNames = false;
        namelookup::forEachPotentialResolvedMacro(
            decl->getDeclContext()->getModuleScopeContext(),
            macroRef.getMacroName(), MacroRole::Peer,
            [&](MacroDecl *macro, const MacroRoleAttr *roleAttr) {
              // First check for arbitrary names.
              if (roleAttr->hasNameKind(
                      MacroIntroducedDeclNameKind::Arbitrary)) {
                introducesArbitraryNames = true;
              }

              macro->getIntroducedNames(MacroRole::Peer,
                                        dyn_cast<ValueDecl>(decl),
                                        introducedNames[attr]);
            });

        // Record this macro where appropriate.
        if (introducesArbitraryNames)
          TopLevelArbitraryMacros.push_back(
              MissingDecl::forUnexpandedMacro(attr, decl));
      }
    }

    if (auto *med = dyn_cast_or_null<MacroExpansionDecl>(decl)) {
      bool introducesArbitraryNames =
          introduceNamesForFreestandingMacro(med, decl, MacroRole::Declaration);

      // Note whether this macro produces arbitrary names.
      if (introducesArbitraryNames)
        TopLevelArbitraryMacros.push_back(MissingDecl::forUnexpandedMacro(med, decl));
    }

    // Add macro-introduced names to the top-level auxiliary decl cache as
    // unexpanded decls represented by a MissingDecl.
    auto anchorDecl = decl ? decl : topLevelCodeDecl;
    for (auto macroNames : introducedNames) {
      auto macroRef = macroNames.getFirst();
      for (auto name : macroNames.getSecond()) {
        auto *placeholder = MissingDecl::forUnexpandedMacro(macroRef, anchorDecl);
        name.addToLookupTable(TopLevelAuxiliaryDecls, placeholder);
      }
    }
  }

  MayHaveAuxiliaryDecls.clear();
}

SourceLookupCache::SourceLookupCache(ASTContext &ctx)
  : UniqueMacroNamePlaceholder(MacroDecl::getUniqueNamePlaceholder(ctx)) { }

/// Populate our cache on the first name lookup.
SourceLookupCache::SourceLookupCache(const SourceFile &SF)
    : SourceLookupCache(SF.getASTContext())
{
  FrontendStatsTracer tracer(SF.getASTContext().Stats,
                             "source-file-populate-cache");
  addToUnqualifiedLookupCache(SF.getTopLevelItems(), false);
  addToUnqualifiedLookupCache(SF.getHoistedDecls(), false);
}

SourceLookupCache::SourceLookupCache(const ModuleDecl &M)
  : SourceLookupCache(M.getASTContext())
{
  FrontendStatsTracer tracer(M.getASTContext().Stats,
                             "module-populate-cache");
  for (const FileUnit *file : M.getFiles()) {
    auto *SF = cast<SourceFile>(file);
    addToUnqualifiedLookupCache(SF->getTopLevelItems(), false);
    addToUnqualifiedLookupCache(SF->getHoistedDecls(), false);

    if (auto *SFU = file->getSynthesizedFile()) {
      addToUnqualifiedLookupCache(SFU->getTopLevelDecls(), false);
    }
  }
}

void SourceLookupCache::lookupValue(DeclName Name, NLKind LookupKind,
                                    OptionSet<ModuleLookupFlags> Flags,
                                    SmallVectorImpl<ValueDecl*> &Result) {
  auto I = TopLevelValues.find(Name);
  if (I != TopLevelValues.end()) {
    Result.reserve(I->second.size());
    for (ValueDecl *Elt : I->second)
      Result.push_back(Elt);
  }

  // If we aren't supposed to find names introduced by macros, we're done.
  if (Flags.contains(ModuleLookupFlags::ExcludeMacroExpansions))
    return;

  // Add top-level auxiliary decls to the result.
  //
  // FIXME: We need to not consider auxiliary decls if we're doing lookup
  // from inside a macro argument at module scope.
  populateAuxiliaryDeclCache();
  DeclName keyName = MacroDecl::isUniqueMacroName(Name.getBaseName())
    ? UniqueMacroNamePlaceholder
    : Name;
  auto auxDecls = TopLevelAuxiliaryDecls.find(keyName);

  // Check macro expansions that could produce this name.
  SmallVector<MissingDecl *, 4> unexpandedDecls;
  if (auxDecls != TopLevelAuxiliaryDecls.end()) {
    unexpandedDecls.insert(
      unexpandedDecls.end(), auxDecls->second.begin(), auxDecls->second.end());
  }

  // Check macro expansions that can produce arbitrary names.
  unexpandedDecls.insert(
      unexpandedDecls.end(),
      TopLevelArbitraryMacros.begin(), TopLevelArbitraryMacros.end());

  if (unexpandedDecls.empty())
    return;

  // Add matching expanded peers and freestanding declarations to the results.
  SmallPtrSet<ValueDecl *, 4> macroExpandedDecls;
  for (auto *unexpandedDecl : unexpandedDecls) {
    unexpandedDecl->forEachMacroExpandedDecl(
        [&](ValueDecl *decl) {
          if (decl->getName().matchesRef(Name)) {
            if (macroExpandedDecls.insert(decl).second)
              Result.push_back(decl);
          }
        });
  }
}

void SourceLookupCache::getPrecedenceGroups(
    SmallVectorImpl<PrecedenceGroupDecl *> &results) {
  for (auto &groups : PrecedenceGroups)
    results.append(groups.second.begin(), groups.second.end());
}

void SourceLookupCache::getOperatorDecls(
    SmallVectorImpl<OperatorDecl *> &results) {
  for (auto &ops : Operators)
    results.append(ops.second.begin(), ops.second.end());
}

void SourceLookupCache::lookupOperator(Identifier name, OperatorFixity fixity,
                                       TinyPtrVector<OperatorDecl *> &results) {
  auto ops = Operators.find(name);
  if (ops == Operators.end())
    return;

  for (auto *op : ops->second)
    if (op->getFixity() == fixity)
      results.push_back(op);
}

void SourceLookupCache::lookupPrecedenceGroup(
    Identifier name, TinyPtrVector<PrecedenceGroupDecl *> &results) {
  auto groups = PrecedenceGroups.find(name);
  if (groups == PrecedenceGroups.end())
    return;

  for (auto *group : groups->second)
    results.push_back(group);
}

void SourceLookupCache::lookupVisibleDecls(ImportPath::Access AccessPath,
                                           VisibleDeclConsumer &Consumer,
                                           NLKind LookupKind) {
  assert(AccessPath.size() <= 1 && "can only refer to top-level decls");

  if (!AccessPath.empty()) {
    auto I = TopLevelValues.find(AccessPath.front().Item);
    if (I == TopLevelValues.end()) return;

    for (auto vd : I->second)
      Consumer.foundDecl(vd, DeclVisibilityKind::VisibleAtTopLevel);
    return;
  }

  for (auto &tlv : TopLevelValues) {
    for (ValueDecl *vd : tlv.second) {
      // Declarations are added under their full and simple names.  Skip the
      // entry for the simple name so that we report each declaration once.
      if (tlv.first.isSimpleName() && !vd->getName().isSimpleName())
        continue;
      Consumer.foundDecl(vd, DeclVisibilityKind::VisibleAtTopLevel);
    }
  }

  populateAuxiliaryDeclCache();
  SmallVector<MissingDecl *, 4> unexpandedDecls;
  for (auto &entry : TopLevelAuxiliaryDecls) {
    for (auto &decl : entry.second) {
      (void) decl;
      unexpandedDecls.append(entry.second.begin(), entry.second.end());
    }
  }

  // Store macro expanded decls in a 'SmallSetVector' because different
  // MissingDecls might be created by a single macro expansion. (e.g. multiple
  // 'names' in macro role attributes). Since expansions are cached, it doesn't
  // cause duplicated expansions, but different 'unexpandedDecl' may report the
  // same 'ValueDecl'.
  llvm::SmallSetVector<ValueDecl *, 4> macroExpandedDecls;
  for (MissingDecl *unexpandedDecl : unexpandedDecls) {
    unexpandedDecl->forEachMacroExpandedDecl([&](ValueDecl *vd) {
      macroExpandedDecls.insert(vd);
    });
  }
  for (auto *vd : macroExpandedDecls) {
    Consumer.foundDecl(vd, DeclVisibilityKind::VisibleAtTopLevel);
  }
}

void SourceLookupCache::lookupClassMembers(ImportPath::Access accessPath,
                                           VisibleDeclConsumer &consumer) {
  assert(accessPath.size() <= 1 && "can only refer to top-level decls");

  if (!accessPath.empty()) {
    for (auto &member : ClassMembers) {
      // Non-simple names are also stored under their simple name, so make
      // sure to only report them once.
      if (!member.first.isSimpleName())
        continue;

      for (ValueDecl *vd : member.second) {
        auto *nominal = vd->getDeclContext()->getSelfNominalTypeDecl();
        if (nominal && nominal->getName() == accessPath.front().Item)
          consumer.foundDecl(vd, DeclVisibilityKind::DynamicLookup,
                             DynamicLookupInfo::AnyObject);
      }
    }
    return;
  }

  for (auto &member : ClassMembers) {
    // Non-simple names are also stored under their simple name, so make sure to
    // only report them once.
    if (!member.first.isSimpleName())
      continue;

    for (ValueDecl *vd : member.second)
      consumer.foundDecl(vd, DeclVisibilityKind::DynamicLookup,
                         DynamicLookupInfo::AnyObject);
  }
}

void SourceLookupCache::lookupClassMember(ImportPath::Access accessPath,
                                          DeclName name,
                                          SmallVectorImpl<ValueDecl*> &results) {
  assert(accessPath.size() <= 1 && "can only refer to top-level decls");

  auto iter = ClassMembers.find(name);
  if (iter == ClassMembers.end())
    return;

  if (!accessPath.empty()) {
    for (ValueDecl *vd : iter->second) {
      auto *nominal = vd->getDeclContext()->getSelfNominalTypeDecl();
      if (nominal && nominal->getName() == accessPath.front().Item)
        results.push_back(vd);
    }
    return;
  }

  results.append(iter->second.begin(), iter->second.end());
}

//===----------------------------------------------------------------------===//
// Module Implementation
//===----------------------------------------------------------------------===//

ModuleDecl::ModuleDecl(Identifier name, ASTContext &ctx,
                       ImplicitImportInfo importInfo)
    : DeclContext(DeclContextKind::Module, nullptr),
      TypeDecl(DeclKind::Module, &ctx, name, SourceLoc(), {}),
      ImportInfo(importInfo) {

  ctx.addDestructorCleanup(*this);
  setImplicit();
  setInterfaceType(ModuleType::get(this));
  setAccess(AccessLevel::Public);

  Bits.ModuleDecl.StaticLibrary = 0;
  Bits.ModuleDecl.TestingEnabled = 0;
  Bits.ModuleDecl.FailedToLoad = 0;
  Bits.ModuleDecl.RawResilienceStrategy = 0;
  Bits.ModuleDecl.HasResolvedImports = 0;
  Bits.ModuleDecl.PrivateImportsEnabled = 0;
  Bits.ModuleDecl.ImplicitDynamicEnabled = 0;
  Bits.ModuleDecl.IsSystemModule = 0;
  Bits.ModuleDecl.IsNonSwiftModule = 0;
  Bits.ModuleDecl.IsMainModule = 0;
  Bits.ModuleDecl.HasIncrementalInfo = 0;
  Bits.ModuleDecl.HasHermeticSealAtLink = 0;
  Bits.ModuleDecl.IsEmbeddedSwiftModule = 0;
  Bits.ModuleDecl.IsConcurrencyChecked = 0;
  Bits.ModuleDecl.ObjCNameLookupCachePopulated = 0;
  Bits.ModuleDecl.HasCxxInteroperability = 0;
  Bits.ModuleDecl.AllowNonResilientAccess = 0;
  Bits.ModuleDecl.SerializePackageEnabled = 0;
}

void ModuleDecl::setIsSystemModule(bool flag) {
  Bits.ModuleDecl.IsSystemModule = flag;
}

bool ModuleDecl::isNonUserModule() const {
  // For clang submodules, retrieve their top level module (submodules have no
  // source path, so we'd always return false for them).
  ModuleDecl *mod = const_cast<ModuleDecl *>(this)->getTopLevelModule();

  auto &evaluator = getASTContext().evaluator;
  return evaluateOrDefault(evaluator, IsNonUserModuleRequest{mod}, false);
}

ImplicitImportList ModuleDecl::getImplicitImports() const {
  auto &evaluator = getASTContext().evaluator;
  auto *mutableThis = const_cast<ModuleDecl *>(this);
  return evaluateOrDefault(evaluator, ModuleImplicitImportsRequest{mutableThis},
                           {});
}

void ModuleDecl::addFile(FileUnit &newFile) {
  // If this is a LoadedFile, make sure it loaded without error.
  assert(!(isa<LoadedFile>(newFile) &&
           cast<LoadedFile>(newFile).hadLoadError()));

  // Require Main and REPL files to be the first file added.
  assert(Files.empty() ||
         !isa<SourceFile>(newFile) ||
         cast<SourceFile>(newFile).Kind == SourceFileKind::Library ||
         cast<SourceFile>(newFile).Kind == SourceFileKind::SIL);
  Files.push_back(&newFile);
  clearLookupCache();
}

void ModuleDecl::addAuxiliaryFile(SourceFile &sourceFile) {
  AuxiliaryFiles.push_back(&sourceFile);
}

namespace {
  /// Compare the source location ranges for two files, as an ordering to
  /// use for fast searches.
  struct SourceFileRangeComparison {
    SourceManager *sourceMgr;

    bool operator()(SourceFile *lhs, SourceFile *rhs) const {
      auto lhsRange = sourceMgr->getRangeForBuffer(*lhs->getBufferID());
      auto rhsRange = sourceMgr->getRangeForBuffer(*rhs->getBufferID());

      std::less<const char *> pointerCompare;
      return pointerCompare(
          (const char *)lhsRange.getStart().getOpaquePointerValue(),
          (const char *)rhsRange.getStart().getOpaquePointerValue());
    }

    bool operator()(SourceFile *lhs, SourceLoc rhsLoc) const {
      auto lhsRange = sourceMgr->getRangeForBuffer(*lhs->getBufferID());

      std::less<const char *> pointerCompare;
      return pointerCompare(
          (const char *)lhsRange.getEnd().getOpaquePointerValue(),
          (const char *)rhsLoc.getOpaquePointerValue());
    }

    bool operator()(SourceLoc lhsLoc, SourceFile *rhs) const {
      auto rhsRange = sourceMgr->getRangeForBuffer(*rhs->getBufferID());

      std::less<const char *> pointerCompare;
      return pointerCompare(
          (const char *)lhsLoc.getOpaquePointerValue(),
          (const char *)rhsRange.getEnd().getOpaquePointerValue());
    }
  };
}

class swift::ModuleSourceFileLocationMap {
public:
  unsigned numFiles = 0;
  unsigned numAuxiliaryFiles = 0;
  std::vector<SourceFile *> allSourceFiles;
  SourceFile *lastSourceFile = nullptr;
};

void ModuleDecl::updateSourceFileLocationMap() {
  // Allocate a source file location map, if we don't have one already.
  if (!sourceFileLocationMap) {
    ASTContext &ctx = getASTContext();
    sourceFileLocationMap = ctx.Allocate<ModuleSourceFileLocationMap>();
    ctx.addCleanup([sourceFileLocationMap=sourceFileLocationMap]() {
      sourceFileLocationMap->~ModuleSourceFileLocationMap();
    });
  }

  // If we are up-to-date, there's nothing to do.
  ArrayRef<FileUnit *> files = Files;
  if (sourceFileLocationMap->numFiles == files.size() &&
      sourceFileLocationMap->numAuxiliaryFiles ==
          AuxiliaryFiles.size())
    return;

  // Rebuild the range structure.
  sourceFileLocationMap->allSourceFiles.clear();

  // First, add all of the source files with a backing buffer.
  for (auto *fileUnit : files) {
    if (auto sourceFile = dyn_cast<SourceFile>(fileUnit)) {
      if (sourceFile->getBufferID())
        sourceFileLocationMap->allSourceFiles.push_back(sourceFile);
    }
  }

  // Next, add all of the macro expansion files.
  for (auto *sourceFile : AuxiliaryFiles)
    sourceFileLocationMap->allSourceFiles.push_back(sourceFile);

  // Finally, sort them all so we can do a binary search for lookup.
  std::sort(sourceFileLocationMap->allSourceFiles.begin(),
            sourceFileLocationMap->allSourceFiles.end(),
            SourceFileRangeComparison{&getASTContext().SourceMgr});

  sourceFileLocationMap->numFiles = files.size();
  sourceFileLocationMap->numAuxiliaryFiles = AuxiliaryFiles.size();
}

SourceFile *ModuleDecl::getSourceFileContainingLocation(SourceLoc loc) {
  if (loc.isInvalid())
    return nullptr;

  // Check whether this location is in a "replaced" range, in which case
  // we want to use the original source file.
  auto &sourceMgr = getASTContext().SourceMgr;
  SourceLoc adjustedLoc = loc;
  for (const auto &pair : sourceMgr.getReplacedRanges()) {
    if (sourceMgr.rangeContainsTokenLoc(pair.second, loc)) {
      adjustedLoc = pair.first.Start;
      break;
    }
  }

  // Before we do any extra work, check the last source file we found a result
  // in to see if it contains this.
  if (sourceFileLocationMap) {
    if (auto lastSourceFile = sourceFileLocationMap->lastSourceFile) {
      auto range = sourceMgr.getRangeForBuffer(*lastSourceFile->getBufferID());
      if (range.contains(adjustedLoc))
        return lastSourceFile;
    }
  }

  updateSourceFileLocationMap();

  auto found = std::lower_bound(sourceFileLocationMap->allSourceFiles.begin(),
                                sourceFileLocationMap->allSourceFiles.end(),
                                adjustedLoc,
                                SourceFileRangeComparison{&sourceMgr});
  if (found == sourceFileLocationMap->allSourceFiles.end())
    return nullptr;

  auto foundSourceFile = *found;
  auto foundRange = sourceMgr.getRangeForBuffer(*foundSourceFile->getBufferID());
  // Positions inside an empty file or at EOF should still be considered within
  // this file.
  if (!foundRange.contains(adjustedLoc) && adjustedLoc != foundRange.getEnd())
    return nullptr;

  // Update the last source file.
  sourceFileLocationMap->lastSourceFile = foundSourceFile;
  return foundSourceFile;
}

std::pair<unsigned, SourceLoc>
ModuleDecl::getOriginalLocation(SourceLoc loc) const {
  assert(loc.isValid());

  SourceManager &SM = getASTContext().SourceMgr;
  unsigned bufferID = SM.findBufferContainingLoc(loc);

  SourceLoc startLoc = loc;
  unsigned startBufferID = bufferID;
  while (const GeneratedSourceInfo *info =
             SM.getGeneratedSourceInfo(bufferID)) {
    switch (info->kind) {
#define MACRO_ROLE(Name, Description)  \
    case GeneratedSourceInfo::Name##MacroExpansion:
#include "swift/Basic/MacroRoles.def"
    {
      // Location was within a macro expansion, return the expansion site, not
      // the insertion location.
      if (info->attachedMacroCustomAttr) {
        loc = info->attachedMacroCustomAttr->getLocation();
      } else {
        ASTNode expansionNode = ASTNode::getFromOpaqueValue(info->astNode);
        loc = expansionNode.getStartLoc();
      }
      bufferID = SM.findBufferContainingLoc(loc);
      break;
    }
    case GeneratedSourceInfo::DefaultArgument:
      // No original location as it's not actually in any source file
    case GeneratedSourceInfo::ReplacedFunctionBody:
      // There's not really any "original" location for locations within
      // replaced function bodies. The body is actually different code to the
      // original file.
    case GeneratedSourceInfo::PrettyPrinted:
      // No original location, return the original buffer/location
      return {startBufferID, startLoc};
    }
  }

  return {bufferID, loc};
}

ArrayRef<SourceFile *>
PrimarySourceFilesRequest::evaluate(Evaluator &evaluator,
                                    ModuleDecl *mod) const {
  assert(mod->isMainModule() && "Only the main module can have primaries");

  SmallVector<SourceFile *, 8> primaries;
  for (auto *file : mod->getFiles()) {
    if (auto *SF = dyn_cast<SourceFile>(file)) {
      if (SF->isPrimary())
        primaries.push_back(SF);
    }
  }
  return mod->getASTContext().AllocateCopy(primaries);
}

ArrayRef<SourceFile *> ModuleDecl::getPrimarySourceFiles() const {
  auto &eval = getASTContext().evaluator;
  auto *mutableThis = const_cast<ModuleDecl *>(this);
  return evaluateOrDefault(eval, PrimarySourceFilesRequest{mutableThis}, {});
}

SourceFile *IDEInspectionFileRequest::evaluate(Evaluator &evaluator,
                                               ModuleDecl *mod) const {
  const auto &SM = mod->getASTContext().SourceMgr;
  assert(mod->isMainModule() && "Can only do completion in the main module");
  assert(SM.hasIDEInspectionTargetBuffer() && "Not in IDE inspection mode?");

  for (auto *file : mod->getFiles()) {
    auto *SF = dyn_cast<SourceFile>(file);
    if (SF && SF->getBufferID() == SM.getIDEInspectionTargetBufferID())
      return SF;
  }
  llvm_unreachable("Couldn't find the completion file?");
}

#define FORWARD(name, args)                                                    \
  for (const FileUnit *file : getFiles()) {                                    \
    file->name args;                                                           \
    if (auto *synth = file->getSynthesizedFile()) {                            \
      synth->name args;                                                        \
    }                                                                          \
  }

SourceLookupCache &ModuleDecl::getSourceLookupCache() const {
  if (!Cache) {
    const_cast<ModuleDecl *>(this)->Cache =
        std::make_unique<SourceLookupCache>(*this);
  }
  return *Cache;
}

ModuleDecl *ModuleDecl::getTopLevelModule(bool overlay) {
  // If this is a Clang module, ask the Clang importer for the top-level module.
  // We need to check isNonSwiftModule() to ensure we don't look through
  // overlays.
  if (isNonSwiftModule()) {
    if (auto *underlying = findUnderlyingClangModule()) {
      auto &ctx = getASTContext();
      auto *clangLoader = ctx.getClangModuleLoader();
      return clangLoader->getWrapperForModule(underlying->getTopLevelModule(),
                                              overlay);
    }
  }
  // Swift modules don't currently support submodules.
  return this;
}

static bool isParsedModule(const ModuleDecl *mod) {
  // FIXME: If we ever get mixed modules that contain both SourceFiles and other
  // kinds of file units, this will break; there all callers of this function should
  // themselves assert that all file units in the module are SourceFiles when this
  // function returns true.
  auto files = mod->getFiles();
  return (files.size() > 0 &&
          isa<SourceFile>(files[0]) &&
          cast<SourceFile>(files[0])->Kind != SourceFileKind::SIL);
}

void ModuleDecl::lookupValue(DeclName Name, NLKind LookupKind,
                             OptionSet<ModuleLookupFlags> Flags,
                             SmallVectorImpl<ValueDecl*> &Result) const {
  auto *stats = getASTContext().Stats;
  if (stats)
    ++stats->getFrontendCounters().NumModuleLookupValue;

  if (isParsedModule(this)) {
    getSourceLookupCache().lookupValue(Name, LookupKind, Flags, Result);
    return;
  }

  FORWARD(lookupValue, (Name, LookupKind, Flags, Result));
}

TypeDecl * ModuleDecl::lookupLocalType(StringRef MangledName) const {
  for (auto file : getFiles()) {
    auto TD = file->lookupLocalType(MangledName);
    if (TD)
      return TD;
  }
  return nullptr;
}

OpaqueTypeDecl *
ModuleDecl::lookupOpaqueResultType(StringRef MangledName) {
  for (auto file : getFiles()) {
    auto OTD = file->lookupOpaqueResultType(MangledName);
    if (OTD)
      return OTD;
  }
  return nullptr;
}

void ModuleDecl::lookupMember(SmallVectorImpl<ValueDecl*> &results,
                              DeclContext *container, DeclName name,
                              Identifier privateDiscriminator) const {
  size_t oldSize = results.size();
  bool alreadyInPrivateContext = false;

  auto containerDecl = container->getAsDecl();
  // If FileUnit, then use FileUnit::lookupValue instead.
  assert(containerDecl != nullptr && "This context does not support lookup.");

  if (auto nominal = dyn_cast<NominalTypeDecl>(containerDecl)) {
    auto lookupResults = nominal->lookupDirect(name);

    // Filter out declarations from other modules.
    llvm::copy_if(lookupResults,
                  std::back_inserter(results),
                  [this](const ValueDecl *VD) -> bool {
      return VD->getModuleContext() == this;
    });

    auto AS = nominal->getFormalAccessScope();
    if (AS.isPrivate() || AS.isFileScope())
      alreadyInPrivateContext = true;
  } else if (isa<ModuleDecl>(containerDecl)) {
    assert(container == this);
    this->lookupValue(name, NLKind::QualifiedLookup, results);
  } else if (!isa<GenericTypeDecl>(containerDecl)) {
    // If ExtensionDecl, then use ExtensionDecl::lookupDirect instead.
    llvm_unreachable("This context does not support lookup.");
  }

  // Filter by private-discriminator, or filter out private decls if there isn't
  // one...unless we're already in a private context, in which case everything
  // is private and a discriminator is unnecessary.
  if (alreadyInPrivateContext) {
    assert(privateDiscriminator.empty() && "unnecessary private discriminator");
    // Don't remove anything; everything here is private anyway.

  } else if (privateDiscriminator.empty()) {
    auto newEnd = std::remove_if(results.begin()+oldSize, results.end(),
                                 [](const ValueDecl *VD) -> bool {
      return VD->getFormalAccess() <= AccessLevel::FilePrivate;
    });
    results.erase(newEnd, results.end());

  } else {
    auto newEnd = std::remove_if(results.begin()+oldSize, results.end(),
                                 [=](const ValueDecl *VD) -> bool {
      if (VD->getFormalAccess() > AccessLevel::FilePrivate)
        return true;
      auto enclosingFile =
        cast<FileUnit>(VD->getDeclContext()->getModuleScopeContext());
      auto discriminator = enclosingFile->getDiscriminatorForPrivateDecl(VD);
      return discriminator != privateDiscriminator;
    });
    results.erase(newEnd, results.end());
  }
}

void ModuleDecl::lookupObjCMethods(
       ObjCSelector selector,
       SmallVectorImpl<AbstractFunctionDecl *> &results) const {
  FORWARD(lookupObjCMethods, (selector, results));
}

void ModuleDecl::lookupImportedSPIGroups(
                        const ModuleDecl *importedModule,
                        llvm::SmallSetVector<Identifier, 4> &spiGroups) const {
  FORWARD(lookupImportedSPIGroups, (importedModule, spiGroups));
}

void BuiltinUnit::lookupValue(DeclName name, NLKind lookupKind,
                              OptionSet<ModuleLookupFlags> Flags,
                              SmallVectorImpl<ValueDecl*> &result) const {
  getCache().lookupValue(name.getBaseIdentifier(), lookupKind, *this, result);
}

void BuiltinUnit::lookupObjCMethods(
       ObjCSelector selector,
       SmallVectorImpl<AbstractFunctionDecl *> &results) const {
  // No @objc methods in the Builtin module.
}

void SourceFile::lookupValue(DeclName name, NLKind lookupKind,
                             OptionSet<ModuleLookupFlags> flags,
                             SmallVectorImpl<ValueDecl*> &result) const {
  getCache().lookupValue(name, lookupKind, flags, result);
}

void ModuleDecl::lookupVisibleDecls(ImportPath::Access AccessPath,
                                    VisibleDeclConsumer &Consumer,
                                    NLKind LookupKind) const {
  if (isParsedModule(this)) {
    auto &cache = getSourceLookupCache();
    cache.lookupVisibleDecls(AccessPath, Consumer, LookupKind);
    assert(Cache.get() == &cache && "cache invalidated during lookup");
    return;
  }

  FORWARD(lookupVisibleDecls, (AccessPath, Consumer, LookupKind));
}

void SourceFile::lookupVisibleDecls(ImportPath::Access AccessPath,
                                    VisibleDeclConsumer &Consumer,
                                    NLKind LookupKind) const {
  getCache().lookupVisibleDecls(AccessPath, Consumer, LookupKind);
}

void ModuleDecl::lookupClassMembers(ImportPath::Access accessPath,
                                    VisibleDeclConsumer &consumer) const {
  if (isParsedModule(this)) {
    auto &cache = getSourceLookupCache();
    cache.populateMemberCache(*this);
    cache.lookupClassMembers(accessPath, consumer);
    return;
  }

  FORWARD(lookupClassMembers, (accessPath, consumer));
}

void SourceFile::lookupClassMembers(ImportPath::Access accessPath,
                                    VisibleDeclConsumer &consumer) const {
  auto &cache = getCache();
  cache.populateMemberCache(*this);
  cache.lookupClassMembers(accessPath, consumer);
}

ASTNode SourceFile::getMacroExpansion() const {
  if (Kind != SourceFileKind::MacroExpansion)
    return nullptr;

  return getNodeInEnclosingSourceFile();
}

SourceRange SourceFile::getMacroInsertionRange() const {
  if (Kind != SourceFileKind::MacroExpansion)
    return SourceRange();

  auto generatedInfo =
      *getASTContext().SourceMgr.getGeneratedSourceInfo(*getBufferID());
  auto origRange = generatedInfo.originalSourceRange;
  return {origRange.getStart(), origRange.getEnd()};
}

CustomAttr *SourceFile::getAttachedMacroAttribute() const {
  if (Kind != SourceFileKind::MacroExpansion)
    return nullptr;

  auto genInfo =
      *getASTContext().SourceMgr.getGeneratedSourceInfo(*getBufferID());
  return genInfo.attachedMacroCustomAttr;
}

std::optional<MacroRole> SourceFile::getFulfilledMacroRole() const {
  if (Kind != SourceFileKind::MacroExpansion)
    return std::nullopt;

  auto genInfo =
      *getASTContext().SourceMgr.getGeneratedSourceInfo(*getBufferID());
  switch (genInfo.kind) {
#define MACRO_ROLE(Name, Description)               \
  case GeneratedSourceInfo::Name##MacroExpansion: \
    return MacroRole::Name;
#include "swift/Basic/MacroRoles.def"

  case GeneratedSourceInfo::ReplacedFunctionBody:
  case GeneratedSourceInfo::PrettyPrinted:
  case GeneratedSourceInfo::DefaultArgument:
    return std::nullopt;
  }
}

SourceFile *SourceFile::getEnclosingSourceFile() const {
  if (Kind != SourceFileKind::MacroExpansion &&
      Kind != SourceFileKind::DefaultArgument)
    return nullptr;

  auto genInfo =
      *getASTContext().SourceMgr.getGeneratedSourceInfo(*getBufferID());
  auto sourceLoc = genInfo.originalSourceRange.getStart();
  return getParentModule()->getSourceFileContainingLocation(sourceLoc);
}

ASTNode SourceFile::getNodeInEnclosingSourceFile() const {
  if (Kind != SourceFileKind::MacroExpansion &&
      Kind != SourceFileKind::DefaultArgument)
    return nullptr;

  auto genInfo =
      *getASTContext().SourceMgr.getGeneratedSourceInfo(*getBufferID());
  return ASTNode::getFromOpaqueValue(genInfo.astNode);
}

void ModuleDecl::lookupClassMember(ImportPath::Access accessPath,
                                   DeclName name,
                                   SmallVectorImpl<ValueDecl*> &results) const {
  auto *stats = getASTContext().Stats;
  if (stats)
    ++stats->getFrontendCounters().NumModuleLookupClassMember;

  if (isParsedModule(this)) {
    FrontendStatsTracer tracer(getASTContext().Stats,
                               "source-file-lookup-class-member");
    auto &cache = getSourceLookupCache();
    cache.populateMemberCache(*this);
    cache.lookupClassMember(accessPath, name, results);
    return;
  }

  FORWARD(lookupClassMember, (accessPath, name, results));
}

void SourceFile::lookupClassMember(ImportPath::Access accessPath,
                                   DeclName name,
                                   SmallVectorImpl<ValueDecl*> &results) const {
  FrontendStatsTracer tracer(getASTContext().Stats,
                             "source-file-lookup-class-member");
  auto &cache = getCache();
  cache.populateMemberCache(*this);
  cache.lookupClassMember(accessPath, name, results);
}

void SourceFile::lookupObjCMethods(
       ObjCSelector selector,
       SmallVectorImpl<AbstractFunctionDecl *> &results) const {
  // FIXME: Make sure this table is complete, somehow.
  auto known = ObjCMethods.find(selector);
  if (known == ObjCMethods.end()) return;
  results.append(known->second.begin(), known->second.end());
}

bool ModuleDecl::shouldCollectDisplayDecls() const {
  for (const FileUnit *file : Files) {
    if (!file->shouldCollectDisplayDecls())
      return false;
  }
  return true;
}

void ModuleDecl::getLocalTypeDecls(SmallVectorImpl<TypeDecl*> &Results) const {
  FORWARD(getLocalTypeDecls, (Results));
}

void ModuleDecl::getTopLevelDecls(SmallVectorImpl<Decl*> &Results) const {
  FORWARD(getTopLevelDecls, (Results));
}

void ModuleDecl::getTopLevelDeclsWithAuxiliaryDecls(
    SmallVectorImpl<Decl *> &Results) const {
  FORWARD(getTopLevelDeclsWithAuxiliaryDecls, (Results));
}

void ModuleDecl::dumpDisplayDecls() const {
  SmallVector<Decl *, 32> Decls;
  getDisplayDecls(Decls);
  for (auto *D : Decls) {
    D->dump(llvm::errs());
    llvm::errs() << "\n";
  }
}

void ModuleDecl::dumpTopLevelDecls() const {
  SmallVector<Decl *, 32> Decls;
  getTopLevelDecls(Decls);
  for (auto *D : Decls) {
    D->dump(llvm::errs());
    llvm::errs() << "\n";
  }
}

void ModuleDecl::getExportedPrespecializations(
    SmallVectorImpl<Decl *> &Results) const {
  FORWARD(getExportedPrespecializations, (Results));
}

void ModuleDecl::getTopLevelDeclsWhereAttributesMatch(
              SmallVectorImpl<Decl*> &Results,
              llvm::function_ref<bool(DeclAttributes)> matchAttributes) const {
  FORWARD(getTopLevelDeclsWhereAttributesMatch, (Results, matchAttributes));
}

void ModuleDecl::lookupTopLevelDeclsByObjCName(SmallVectorImpl<Decl *> &Results,
                                               DeclName name) {
  if (!isObjCNameLookupCachePopulated())
    populateObjCNameLookupCache();

  // A top level decl can't be special anyways
  if (name.isSpecial())
    return;

  auto resultsForFileUnit = ObjCNameLookupCache.find(name.getBaseIdentifier());
  if (resultsForFileUnit == ObjCNameLookupCache.end())
    return;

  Results.append(resultsForFileUnit->second.begin(),
                 resultsForFileUnit->second.end());
}

void ModuleDecl::populateObjCNameLookupCache() {
  SmallVector<Decl *> topLevelObjCExposedDeclsInFileUnit;
  auto hasObjCAttrNamePredicate = [](const DeclAttributes &attrs) -> bool {
    return attrs.hasAttribute<ObjCAttr>();
  };

  for (FileUnit *file : getFiles()) {
    file->getTopLevelDeclsWhereAttributesMatch(
        topLevelObjCExposedDeclsInFileUnit, hasObjCAttrNamePredicate);
    if (auto *synth = file->getSynthesizedFile()) {
      synth->getTopLevelDeclsWhereAttributesMatch(
          topLevelObjCExposedDeclsInFileUnit, hasObjCAttrNamePredicate);
    }
  }

  for (Decl *decl : topLevelObjCExposedDeclsInFileUnit) {
    if (ValueDecl *VD = dyn_cast<ValueDecl>(decl); VD && VD->hasName()) {
      const auto &declObjCAttribute = VD->getAttrs().getAttribute<ObjCAttr>();
      // No top level decl (class, protocol, extension etc.) is allowed to have a
      // compound name, @objc provided or otherwise. Global functions are allowed to
      // have compound names, but not allowed to have @objc attributes. Thus we
      // are sure to not hit asserts getting the simple name.
      //
      // Similarly, init, dealloc and subscript (the special names) can't be top 
      // level decls, so we won't hit asserts getting the base identifier out of the
      // value decl.
      const Identifier &declObjCName =
          declObjCAttribute->hasName()
              ? declObjCAttribute->getName()->getSimpleName()
              : VD->getName().getBaseIdentifier();
      ObjCNameLookupCache[declObjCName].push_back(decl);
    }
  }

  setIsObjCNameLookupCachePopulated(true);
}

void SourceFile::getTopLevelDecls(SmallVectorImpl<Decl*> &Results) const {
  auto decls = getTopLevelDecls();
  Results.append(decls.begin(), decls.end());
}

void ModuleDecl::getOperatorDecls(
    SmallVectorImpl<OperatorDecl *> &results) const {
  // For a parsed module, we can check the source cache on the module rather
  // than doing an O(N) search over the source files.
  if (isParsedModule(this)) {
    getSourceLookupCache().getOperatorDecls(results);
    return;
  }
  FORWARD(getOperatorDecls, (results));
}

void SourceFile::getOperatorDecls(
       SmallVectorImpl<OperatorDecl*> &results) const {
  getCache().getOperatorDecls(results);
}

void ModuleDecl::getPrecedenceGroups(
       SmallVectorImpl<PrecedenceGroupDecl*> &results) const {
  // For a parsed module, we can check the source cache on the module rather
  // than doing an O(N) search over the source files.
  if (isParsedModule(this)) {
    getSourceLookupCache().getPrecedenceGroups(results);
    return;
  }
  FORWARD(getPrecedenceGroups, (results));
}

void SourceFile::getPrecedenceGroups(
       SmallVectorImpl<PrecedenceGroupDecl*> &results) const {
  getCache().getPrecedenceGroups(results);
}

void SourceFile::getLocalTypeDecls(SmallVectorImpl<TypeDecl*> &Results) const {
  auto decls = getLocalTypeDecls();
  Results.append(decls.begin(), decls.end());
}

void
SourceFile::getOpaqueReturnTypeDecls(SmallVectorImpl<OpaqueTypeDecl*> &Results)
const {
  auto result = const_cast<SourceFile *>(this)->getOpaqueReturnTypeDecls();
  llvm::copy(result, std::back_inserter(Results));
}

TypeDecl *SourceFile::lookupLocalType(llvm::StringRef mangledName) const {
  ASTContext &ctx = getASTContext();
  for (auto typeDecl : getLocalTypeDecls()) {
    auto typeMangledName = evaluateOrDefault(ctx.evaluator,
                                             MangleLocalTypeDeclRequest { typeDecl },
                                             std::string());
    if (mangledName == typeMangledName)
      return typeDecl;
  }

  return nullptr;
}

std::optional<ExternalSourceLocs::RawLocs>
SourceFile::getExternalRawLocsForDecl(const Decl *D) const {
  auto *FileCtx = D->getDeclContext()->getModuleScopeContext();
  assert(FileCtx == this && "D doesn't belong to this source file");
  if (FileCtx != this) {
    // D doesn't belong to this file. This shouldn't happen in practice.
    return std::nullopt;
  }

  SourceLoc MainLoc = D->getLoc(/*SerializedOK=*/false);
  if (MainLoc.isInvalid())
    return std::nullopt;

  // TODO: Rather than grabbing the location of the macro expansion, we should
  // instead add the generated buffer tree - that would need to include source
  // if we want to be able to retrieve documentation within generated buffers.
  SourceManager &SM = getASTContext().SourceMgr;
  bool InGeneratedBuffer =
      !SM.rangeContainsTokenLoc(SM.getRangeForBuffer(BufferID), MainLoc);
  if (InGeneratedBuffer) {
    int UnderlyingBufferID;
    std::tie(UnderlyingBufferID, MainLoc) =
        D->getModuleContext()->getOriginalLocation(MainLoc);
    if (BufferID != UnderlyingBufferID)
      return std::nullopt;
  }

  auto setLoc = [&](ExternalSourceLocs::RawLoc &RawLoc, SourceLoc Loc) {
    if (!Loc.isValid())
      return;

    RawLoc.Offset = SM.getLocOffsetInBuffer(Loc, BufferID);
    std::tie(RawLoc.Line, RawLoc.Column) = SM.getLineAndColumnInBuffer(Loc);

    auto *VF = SM.getVirtualFile(Loc);
    if (!VF)
      return;

    RawLoc.Directive.Offset =
        SM.getLocOffsetInBuffer(VF->Range.getStart(), BufferID);
    RawLoc.Directive.LineOffset = VF->LineOffset;
    RawLoc.Directive.Length = VF->Range.getByteLength();
    RawLoc.Directive.Name = StringRef(VF->Name);
  };

  ExternalSourceLocs::RawLocs Result;

  Result.SourceFilePath = SM.getIdentifierForBuffer(BufferID);
  setLoc(Result.Loc, MainLoc);
  if (!InGeneratedBuffer) {
    for (const auto &SRC : D->getRawComment().Comments) {
      Result.DocRanges.emplace_back(ExternalSourceLocs::RawLoc(),
                                    SRC.Range.getByteLength());
      setLoc(Result.DocRanges.back().first, SRC.Range.getStart());
    }
    setLoc(Result.StartLoc, D->getStartLoc());
    setLoc(Result.EndLoc, D->getEndLoc());
  }

  return Result;
}

void ModuleDecl::ImportCollector::collect(
    const ImportedModule &importedModule) {
  auto *module = importedModule.importedModule;

  if (!module->shouldCollectDisplayDecls())
    return;

  if (importFilter && !importFilter(module))
    return;

  if (importedModule.getAccessPath().size() > 0) {
    auto collectDecls = [&](ValueDecl *VD, DeclVisibilityKind reason) {
      if (reason == DeclVisibilityKind::VisibleAtTopLevel)
        this->qualifiedImports[module].insert(VD);
    };
    auto consumer = makeDeclConsumer(std::move(collectDecls));
    module->lookupVisibleDecls(importedModule.getAccessPath(), consumer,
                               NLKind::UnqualifiedLookup);
  } else {
    imports.insert(module);
  }
}

static void
collectExportedImports(const ModuleDecl *topLevelModule,
                       ModuleDecl::ImportCollector &importCollector) {
  SmallVector<const ModuleDecl *> stack;
  stack.push_back(topLevelModule);
  while (!stack.empty()) {
    const ModuleDecl *module = stack.pop_back_val();
    if (module->isNonSwiftModule())
      continue;

    for (const FileUnit *file : module->getFiles()) {
      if (const SourceFile *source = dyn_cast<SourceFile>(file)) {
        if (source->hasImports()) {
          for (const auto &import : source->getImports()) {
            if (import.options.contains(ImportFlags::Exported) &&
                import.docVisibility.value_or(AccessLevel::Public) >=
                importCollector.minimumDocVisibility) {
              importCollector.collect(import.module);
              stack.push_back(import.module.importedModule);
            }
          }
        }
      } else {
        SmallVector<ImportedModule, 8> exportedImports;
        file->getImportedModules(exportedImports,
                                 ModuleDecl::ImportFilterKind::Exported);
        for (const auto &im : exportedImports) {
          // Skip collecting the underlying clang module as we already have the relevant import.
          if (module->isClangOverlayOf(im.importedModule))
            continue;
          importCollector.collect(im);
          stack.push_back(im.importedModule);
        }
      }
    }
  }
}

void ModuleDecl::getDisplayDecls(SmallVectorImpl<Decl*> &Results, bool Recursive) const {
  if (Recursive) {
    ImportCollector importCollector;
    this->getDisplayDeclsRecursivelyAndImports(Results, importCollector);
  } else {
    // FIXME: Should this do extra access control filtering?
    FORWARD(getDisplayDecls, (Results));
  }
}

void ModuleDecl::getDisplayDeclsRecursivelyAndImports(
    SmallVectorImpl<Decl *> &results, ImportCollector &importCollector) const {
  this->getDisplayDecls(results, /*Recursive=*/false);

  // Look up imports recursively.
  collectExportedImports(this, importCollector);
  for (const auto &QI : importCollector.qualifiedImports) {
    auto Module = QI.getFirst();
    if (importCollector.imports.contains(Module))
      continue;

    auto &Decls = QI.getSecond();
    results.append(Decls.begin(), Decls.end());
  }

  for (const ModuleDecl *import : importCollector.imports)
    import->getDisplayDecls(results);

#ifndef NDEBUG
  llvm::DenseSet<Decl *> visited;
  for (auto *D : results) {
    // decls synthesized from implicit clang decls may appear multiple times;
    // e.g. if multiple modules with underlying clang modules are re-exported.
    // including duplicates of these is harmless, so skip them when counting
    // this assertion
    if (const auto *CD = D->getClangDecl()) {
      if (CD->isImplicit())
        continue;
    }
    auto inserted = visited.insert(D).second;
    assert(inserted && "there should be no duplicate decls");
  }
#endif
}

Fingerprint SourceFile::getInterfaceHash() const {
  assert(hasInterfaceHash() && "Interface hash not enabled");
  auto &eval = getASTContext().evaluator;
  auto *mutableThis = const_cast<SourceFile *>(this);
  std::optional<StableHasher> interfaceHasher =
      evaluateOrDefault(eval, ParseSourceFileRequest{mutableThis}, {})
          .InterfaceHasher;
  return Fingerprint{StableHasher{interfaceHasher.value()}.finalize()};
}

Fingerprint SourceFile::getInterfaceHashIncludingTypeMembers() const {
  /// FIXME: Gross. Hashing multiple "hash" values.
  auto hash = StableHasher::defaultHasher();
  hash.combine(getInterfaceHash());

  std::function<void(IterableDeclContext *)> hashTypeBodyFingerprints =
      [&](IterableDeclContext *IDC) {
        if (auto fp = IDC->getBodyFingerprint())
          hash.combine(*fp);
        for (auto *member : IDC->getParsedMembers())
          if (auto *childIDC = dyn_cast<IterableDeclContext>(member))
            hashTypeBodyFingerprints(childIDC);
      };

  for (auto *D : getTopLevelDecls()) {
    if (auto IDC = dyn_cast<IterableDeclContext>(D))
      hashTypeBodyFingerprints(IDC);
  }

  return Fingerprint{std::move(hash)};
}

void DirectOperatorLookupRequest::writeDependencySink(
    evaluator::DependencyCollector &reqTracker,
    const TinyPtrVector<OperatorDecl *> &ops) const {
  auto &desc = std::get<0>(getStorage());
  reqTracker.addTopLevelName(desc.name);
}

TinyPtrVector<OperatorDecl *>
DirectOperatorLookupRequest::evaluate(Evaluator &evaluator,
                                      OperatorLookupDescriptor descriptor,
                                      OperatorFixity fixity) const {
  // For a parsed module, we can check the source cache on the module rather
  // than doing an O(N) search over the source files.
  TinyPtrVector<OperatorDecl *> results;
  if (auto module = descriptor.getModule()) {
    if (isParsedModule(module)) {
      module->getSourceLookupCache().lookupOperator(descriptor.name, fixity,
                                                    results);
      return results;
    }
  }

  // Otherwise query each file.
  for (auto *file : descriptor.getFiles())
    file->lookupOperatorDirect(descriptor.name, fixity, results);

  return results;
}

void SourceFile::lookupOperatorDirect(
    Identifier name, OperatorFixity fixity,
    TinyPtrVector<OperatorDecl *> &results) const {
  getCache().lookupOperator(name, fixity, results);
}

void DirectPrecedenceGroupLookupRequest::writeDependencySink(
    evaluator::DependencyCollector &reqTracker,
    const TinyPtrVector<PrecedenceGroupDecl *> &groups) const {
  auto &desc = std::get<0>(getStorage());
  reqTracker.addTopLevelName(desc.name);
}

TinyPtrVector<PrecedenceGroupDecl *>
DirectPrecedenceGroupLookupRequest::evaluate(
    Evaluator &evaluator, OperatorLookupDescriptor descriptor) const {
  // For a parsed module, we can check the source cache on the module rather
  // than doing an O(N) search over the source files.
  TinyPtrVector<PrecedenceGroupDecl *> results;
  if (auto module = descriptor.getModule()) {
    if (isParsedModule(module)) {
      module->getSourceLookupCache().lookupPrecedenceGroup(descriptor.name,
                                                           results);
      return results;
    }
  }

  // Otherwise query each file.
  for (auto *file : descriptor.getFiles())
    file->lookupPrecedenceGroupDirect(descriptor.name, results);

  return results;
}

void SourceFile::lookupPrecedenceGroupDirect(
    Identifier name, TinyPtrVector<PrecedenceGroupDecl *> &results) const {
  getCache().lookupPrecedenceGroup(name, results);
}

void ModuleDecl::getImportedModules(SmallVectorImpl<ImportedModule> &modules,
                                    ModuleDecl::ImportFilter filter) const {
  FORWARD(getImportedModules, (modules, filter));
}

void ModuleDecl::getMissingImportedModules(
    SmallVectorImpl<ImportedModule> &imports) const {
  FORWARD(getMissingImportedModules, (imports));
}

const llvm::DenseMap<const clang::Module *, ModuleDecl *> &
ModuleDecl::getVisibleClangModules(PrintOptions::InterfaceMode contentMode) {
  if (CachedVisibleClangModuleSet.find(contentMode) != CachedVisibleClangModuleSet.end())
    return CachedVisibleClangModuleSet[contentMode];
  else
    CachedVisibleClangModuleSet.emplace(contentMode, VisibleClangModuleSet{});
  VisibleClangModuleSet &result = CachedVisibleClangModuleSet[contentMode];

  // For the current module, consider both private and public imports.
  ModuleDecl::ImportFilter Filter = ModuleDecl::ImportFilterKind::Exported;
  Filter |= ModuleDecl::ImportFilterKind::Default;

  // For private or package swiftinterfaces, also look through @_spiOnly imports.
  if (contentMode != PrintOptions::InterfaceMode::Public)
    Filter |= ModuleDecl::ImportFilterKind::SPIOnly;
  // Consider package import for package interface
  if (contentMode == PrintOptions::InterfaceMode::Package)
    Filter |= ModuleDecl::ImportFilterKind::PackageOnly;

  SmallVector<ImportedModule, 32> Imports;
  getImportedModules(Imports, Filter);

  SmallVector<ModuleDecl *, 32> ModulesToProcess;
  for (const auto &Import : Imports)
    ModulesToProcess.push_back(Import.importedModule);

  SmallPtrSet<ModuleDecl *, 32> Processed;
  while (!ModulesToProcess.empty()) {
    ModuleDecl *Mod = ModulesToProcess.back();
    ModulesToProcess.pop_back();

    if (!Processed.insert(Mod).second)
      continue;

    if (const clang::Module *ClangModule = Mod->findUnderlyingClangModule())
      result[ClangModule] = Mod;

    // For transitive imports, consider only public imports.
    Imports.clear();
    Mod->getImportedModules(Imports, ModuleDecl::ImportFilterKind::Exported);
    for (const auto &Import : Imports) {
      ModulesToProcess.push_back(Import.importedModule);
    }
  }

  return result;
}

void
SourceFile::getImportedModules(SmallVectorImpl<ImportedModule> &modules,
                               ModuleDecl::ImportFilter filter) const {
  // FIXME: Ideally we should assert that the file has had its imports resolved
  // before calling this function. However unfortunately that can cause issues
  // for overlays which can depend on a Clang submodule for the underlying
  // framework they are overlaying, which causes us to attempt to load the
  // overlay again. We need to find a way to ensure that an overlay dependency
  // with the same name as the overlay always loads the underlying Clang module.
  // We currently handle this for a direct import from the overlay, but not when
  // it happens through other imports.
  assert(filter && "no imports requested?");
  if (!Imports)
    return;

  for (auto desc : *Imports) {
    ModuleDecl::ImportFilter requiredFilter;
    if (desc.options.contains(ImportFlags::Exported))
      requiredFilter |= ModuleDecl::ImportFilterKind::Exported;
    else if (desc.options.contains(ImportFlags::ImplementationOnly))
      requiredFilter |= ModuleDecl::ImportFilterKind::ImplementationOnly;
    else if (desc.accessLevel <= AccessLevel::Internal)
      requiredFilter |= ModuleDecl::ImportFilterKind::InternalOrBelow;
    else if (desc.accessLevel <= AccessLevel::Package)
      requiredFilter |= ModuleDecl::ImportFilterKind::PackageOnly;
    else if (desc.options.contains(ImportFlags::SPIOnly))
      requiredFilter |= ModuleDecl::ImportFilterKind::SPIOnly;
    else
      requiredFilter |= ModuleDecl::ImportFilterKind::Default;

    if (!separatelyImportedOverlays.lookup(desc.module.importedModule).empty())
      requiredFilter |= ModuleDecl::ImportFilterKind::ShadowedByCrossImportOverlay;

    if (filter.contains(requiredFilter))
      modules.push_back(desc.module);
  }
}

void SourceFile::getMissingImportedModules(
    SmallVectorImpl<ImportedModule> &modules) const {
  for (auto module : MissingImportedModules)
    modules.push_back(module);
}

void SourceFile::dumpSeparatelyImportedOverlays() const {
  for (auto &pair : separatelyImportedOverlays) {
    auto &underlying = std::get<0>(pair);
    auto &overlays = std::get<1>(pair);

    llvm::errs() << (void*)underlying << " ";
    underlying->dump(llvm::errs());

    for (auto overlay : overlays) {
      llvm::errs() << "- ";
      llvm::errs() << (void*)overlay << " ";
      overlay->dump(llvm::errs());
    }
  }
}

void ModuleDecl::getImportedModulesForLookup(
    SmallVectorImpl<ImportedModule> &modules) const {
  FORWARD(getImportedModulesForLookup, (modules));
}

ModuleDecl::ReverseFullNameIterator::ReverseFullNameIterator(
    const ModuleDecl *M) {
  assert(M);
  // Note: This will look through overlays as well, but that's fine for name
  // generation purposes. The point of an overlay is to
  if (auto *clangModule = M->findUnderlyingClangModule())
    current = clangModule;
  else
    current = M;
}

StringRef ModuleDecl::ReverseFullNameIterator::operator*() const {
  assert(current && "all name components exhausted");
  // Return the module's real (binary) name, which can be different from
  // the name if module aliasing was used (-module-alias flag). The real
  // name is used for serialization and loading.
  if (auto *swiftModule = current.dyn_cast<const ModuleDecl *>())
    return swiftModule->getRealName().str();

  auto *clangModule =
      static_cast<const clang::Module *>(current.get<const void *>());
  if (!clangModule->isSubModule() && clangModule->Name == "std")
    return "CxxStdlib";
  return clangModule->Name;
}

ModuleDecl::ReverseFullNameIterator &
ModuleDecl::ReverseFullNameIterator::operator++() {
  if (!current)
    return *this;

  if (current.is<const ModuleDecl *>()) {
    current = nullptr;
    return *this;
  }

  auto *clangModule =
      static_cast<const clang::Module *>(current.get<const void *>());
  if (clangModule->Parent)
    current = clangModule->Parent;
  else
    current = nullptr;
  return *this;
}

void
ModuleDecl::ReverseFullNameIterator::printForward(raw_ostream &out,
                                                  StringRef delim) const {
  SmallVector<StringRef, 8> elements(*this, {});
  llvm::interleave(
      llvm::reverse(elements), [&out](StringRef next) { out << next; },
      [&out, delim] { out << delim; });
}

void
ImportedModule::removeDuplicates(SmallVectorImpl<ImportedModule> &imports) {
  std::sort(imports.begin(), imports.end(),
            [](const ImportedModule &lhs, const ImportedModule &rhs) -> bool {
    // Arbitrarily sort by name to get a deterministic order.
    if (lhs.importedModule != rhs.importedModule) {
      return std::lexicographical_compare(
          lhs.importedModule->getReverseFullModuleName(), {},
          rhs.importedModule->getReverseFullModuleName(), {});
    }
    return std::lexicographical_compare(
        lhs.accessPath.begin(), lhs.accessPath.end(), rhs.accessPath.begin(),
        rhs.accessPath.end(),
        [](const ImportPath::Element &lElem, const ImportPath::Element &rElem) {
          return lElem.Item.str() < rElem.Item.str();
        });
  });
  auto last = std::unique(
      imports.begin(), imports.end(),
      [](const ImportedModule &lhs, const ImportedModule &rhs) -> bool {
        if (lhs.importedModule != rhs.importedModule)
          return false;
        return lhs.accessPath.isSameAs(rhs.accessPath);
      });
  imports.erase(last, imports.end());
}

Identifier ModuleDecl::getRealName() const {
  // This will return the real name for an alias (if used) or getName()
  return getASTContext().getRealModuleName(getName());
}

bool ModuleDecl::allowImportedBy(ModuleDecl *importer) const {
  if (allowableClientNames.empty())
    return true;
  for (auto id: allowableClientNames) {
    if (importer->getRealName() == id)
      return true;
    if (importer->getABIName() == id)
      return true;
  }
  return false;
}

Identifier ModuleDecl::getABIName() const {
  if (!ModuleABIName.empty())
    return ModuleABIName;

  // Hard code that the _Concurrency module has Swift as its ABI name.
  // FIXME: This works around a backward-compatibility issue where
  // -module-abi-name is not supported on existing Swift compilers. Remove
  // this hack later and pass -module-abi-name when building the _Concurrency
  // module.
  if (getName().str() == SWIFT_CONCURRENCY_NAME) {
    ModuleABIName = getASTContext().getIdentifier(STDLIB_NAME);
    return ModuleABIName;
  }

  return getName();
}

StringRef ModuleDecl::getModuleFilename() const {
  // FIXME: Audit uses of this function and figure out how to migrate them to
  // per-file names. Modules can consist of more than one file.
  StringRef Result;
  for (auto F : getFiles()) {
    if (auto SF = dyn_cast<SourceFile>(F)) {
      if (!Result.empty())
        return StringRef();
      Result = SF->getFilename();
      continue;
    }
    if (auto LF = dyn_cast<LoadedFile>(F)) {
      if (!Result.empty())
        return StringRef();
      Result = LF->getFilename();
      continue;
    }
    // Skip synthesized files.
    if (auto *SFU = dyn_cast<SynthesizedFileUnit>(F))
      continue;
    return StringRef();
  }
  return Result;
}

StringRef ModuleDecl::getModuleSourceFilename() const {
  for (auto F : getFiles()) {
    if (auto LF = dyn_cast<LoadedFile>(F))
      return LF->getSourceFilename();
  }
  return StringRef();
}

StringRef ModuleDecl::getModuleLoadedFilename() const {
  for (auto F : getFiles()) {
    if (auto LF = dyn_cast<LoadedFile>(F)) {
      return LF->getLoadedFilename();
    }
  }
  return StringRef();
}

bool ModuleDecl::isStdlibModule() const {
  return !getParent() && getName() == getASTContext().StdlibModuleName;
}

bool ModuleDecl::hasStandardSubstitutions() const {
  return !getParent() &&
      (getName() == getASTContext().StdlibModuleName ||
       getName() == getASTContext().Id_Concurrency);
}

bool ModuleDecl::isSwiftShimsModule() const {
  return !getParent() && getName() == getASTContext().SwiftShimsModuleName;
}

bool ModuleDecl::isOnoneSupportModule() const {
  return !getParent() && getName().str() == SWIFT_ONONE_SUPPORT;
}

bool ModuleDecl::isFoundationModule() const {
  return !getParent() && getName() == getASTContext().Id_Foundation;
}

bool ModuleDecl::isBuiltinModule() const {
  return this == getASTContext().TheBuiltinModule;
}

bool SourceFile::registerMainDecl(ValueDecl *mainDecl, SourceLoc diagLoc) {
  assert(mainDecl);
  if (mainDecl == MainDecl)
    return false;

  ArtificialMainKind kind = mainDecl->getArtificialMainKind();
  if (getParentModule()->registerEntryPointFile(this, diagLoc, kind))
    return true;

  MainDecl = mainDecl;
  MainDeclDiagLoc = diagLoc;

  return false;
}

NominalTypeDecl *ModuleDecl::getMainTypeDecl() const {
  if (!EntryPointInfo.hasEntryPoint())
    return nullptr;
  auto *file = EntryPointInfo.getEntryPointFile();
  if (!file)
    return nullptr;
  auto *mainDecl = file->getMainDecl();
  if (!mainDecl)
    return nullptr;
  auto *func = dyn_cast<FuncDecl>(file->getMainDecl());
  if (!func)
    return nullptr;
  auto *nominalType = dyn_cast<NominalTypeDecl>(func->getDeclContext());
  return nominalType;
}

bool ModuleDecl::registerEntryPointFile(
    FileUnit *file, SourceLoc diagLoc, std::optional<ArtificialMainKind> kind) {
  if (!EntryPointInfo.hasEntryPoint()) {
    EntryPointInfo.setEntryPointFile(file);
    return false;
  }

  if (diagLoc.isInvalid())
    return true;

  assert(kind.has_value() && "multiple entry points without attributes");

  // %select indices for UI/NSApplication-related diagnostics.
  enum : unsigned {
    UIApplicationMainClass = 0,
    NSApplicationMainClass = 1,
    MainType = 2,
  } mainTypeDiagKind;

  switch (kind.value()) {
  case ArtificialMainKind::UIApplicationMain:
    mainTypeDiagKind = UIApplicationMainClass;
    break;
  case ArtificialMainKind::NSApplicationMain:
    mainTypeDiagKind = NSApplicationMainClass;
    break;
  case ArtificialMainKind::TypeMain:
    mainTypeDiagKind = MainType;
    break;
  }

  FileUnit *existingFile = EntryPointInfo.getEntryPointFile();
  const Decl *existingDecl = existingFile->getMainDecl();
  SourceLoc existingDiagLoc;

  if (auto *sourceFile = dyn_cast<SourceFile>(existingFile)) {
    if (existingDecl) {
      existingDiagLoc = sourceFile->getMainDeclDiagLoc();
    } else {
      if (auto bufID = sourceFile->getBufferID())
        existingDiagLoc = getASTContext().SourceMgr.getLocForBufferStart(*bufID);
    }
  }

  if (existingDecl) {
    if (EntryPointInfo.markDiagnosedMultipleMainClasses()) {
      // If we already have a main type, and we haven't diagnosed it,
      // do so now.
      if (existingDiagLoc.isValid()) {
        getASTContext().Diags.diagnose(existingDiagLoc,
                                       diag::attr_ApplicationMain_multiple,
                                       mainTypeDiagKind);
      } else {
        getASTContext().Diags.diagnose(existingDecl,
                                       diag::attr_ApplicationMain_multiple,
                                       mainTypeDiagKind);
      }
    }

    // Always diagnose the new class.
    getASTContext().Diags.diagnose(diagLoc, diag::attr_ApplicationMain_multiple,
                                   mainTypeDiagKind);

  } else {
    // We don't have an existing class, but we /do/ have a file in script mode.
    // Diagnose that.
    if (EntryPointInfo.markDiagnosedMainClassWithScript()) {
      getASTContext().Diags.diagnose(
          diagLoc, diag::attr_ApplicationMain_with_script, mainTypeDiagKind);

      if (existingDiagLoc.isValid()) {
        getASTContext().Diags.diagnose(existingDiagLoc,
                           diag::attr_ApplicationMain_script_here);
        getASTContext().Diags.diagnose(existingDiagLoc,
                           diag::attr_ApplicationMain_parse_as_library);
      }
    }
  }

  return true;
}

void ModuleDecl::collectLinkLibraries(LinkLibraryCallback callback) const {
  bool hasSourceFile = false;

  for (auto *file : getFiles()) {
    if (isa<SourceFile>(file)) {
      hasSourceFile = true;
    } else {
      file->collectLinkLibraries(callback);
    }

    if (auto *synth = file->getSynthesizedFile()) {
      synth->collectLinkLibraries(callback);
    }
  }

  if (!hasSourceFile)
    return;

  llvm::SmallDenseSet<ModuleDecl *, 32> visited;
  SmallVector<ImportedModule, 32> stack;

  ModuleDecl::ImportFilter filter = {
      ModuleDecl::ImportFilterKind::Exported,
      ModuleDecl::ImportFilterKind::Default};

  ModuleDecl::ImportFilter topLevelFilter = filter;
  topLevelFilter |= ModuleDecl::ImportFilterKind::ImplementationOnly;
  topLevelFilter |= ModuleDecl::ImportFilterKind::InternalOrBelow;
  topLevelFilter |= ModuleDecl::ImportFilterKind::PackageOnly,
  topLevelFilter |= ModuleDecl::ImportFilterKind::SPIOnly;
  getImportedModules(stack, topLevelFilter);

  // Make sure the top-level module is first; we want pre-order-ish traversal.
  stack.emplace_back(ImportPath::Access(), const_cast<ModuleDecl *>(this));

  while (!stack.empty()) {
    auto next = stack.pop_back_val().importedModule;

    if (!visited.insert(next).second)
      continue;

    if (next->getName() != getName()) {
      next->collectLinkLibraries(callback);
    }

    next->getImportedModules(stack, filter);
  }
}

void
SourceFile::collectLinkLibraries(ModuleDecl::LinkLibraryCallback callback) const {}

bool ModuleDecl::walk(ASTWalker &Walker) {
  llvm::SaveAndRestore<ASTWalker::ParentTy> SAR(Walker.Parent, this);
  for (auto SF : getFiles())
    if (SF->walk(Walker))
      return true;
  return false;
}

ModuleDecl *ModuleDecl::getUnderlyingModuleIfOverlay() const {
  for (auto *FU : getFiles()) {
    if (auto *Mod = FU->getUnderlyingModuleIfOverlay())
      return Mod;
  }
  return nullptr;
}

const clang::Module *ModuleDecl::findUnderlyingClangModule() const {
  for (auto *FU : getFiles()) {
    if (auto *Mod = FU->getUnderlyingClangModule())
      return Mod;
  }
  return nullptr;
}

void ModuleDecl::collectBasicSourceFileInfo(
    llvm::function_ref<void(const BasicSourceFileInfo &)> callback) const {
  for (const FileUnit *fileUnit : getFiles()) {
    if (const auto *SF = dyn_cast<SourceFile>(fileUnit)) {
      callback(BasicSourceFileInfo(SF));
    } else if (auto *serialized = dyn_cast<LoadedFile>(fileUnit)) {
      serialized->collectBasicSourceFileInfo(callback);
    }
  }
}

void ModuleDecl::collectSerializedSearchPath(
    llvm::function_ref<void(StringRef)> callback) const {
  for (const FileUnit *fileUnit : getFiles()) {
    if (auto *serialized = dyn_cast<LoadedFile>(fileUnit)) {
      serialized->collectSerializedSearchPath(callback);
    }
  }
}

Fingerprint ModuleDecl::getFingerprint() const {
  StableHasher hasher = StableHasher::defaultHasher();
  SmallVector<Fingerprint, 16> FPs;
  collectBasicSourceFileInfo([&](const BasicSourceFileInfo &bsfi) {
    // For incremental imports, the hash must be insensitive to type-body
    // changes, so use the one without type members.
    FPs.emplace_back(bsfi.getInterfaceHashExcludingTypeMembers());
  });
  
  // Sort the fingerprints lexicographically so we have a stable hash despite
  // an unstable ordering of files across rebuilds.
  // FIXME: If we used a commutative hash combine (say, if we could take an
  // XOR here) we could avoid this sort.
  std::sort(FPs.begin(), FPs.end(), std::less<Fingerprint>());
  for (const auto &FP : FPs) {
    hasher.combine(FP);
  }

  return Fingerprint{std::move(hasher)};
}

bool ModuleDecl::isExternallyConsumed() const {
  // Modules for executables aren't expected to be consumed by other modules.
  // This picks up all kinds of entrypoints, including script mode,
  // @UIApplicationMain and @NSApplicationMain.
  if (hasEntryPoint()) {
    return false;
  }

  // If an implicit Objective-C header was needed to construct this module, it
  // must be the product of a library target.
  if (!getImplicitImportInfo().BridgingHeaderPath.empty()) {
    return false;
  }

  // App extensions are special beasts because they build without entrypoints
  // like library targets, but they behave like executable targets because
  // their associated modules are not suitable for distribution.
  // However, app extension libraries might be consumed externally.
  if (getASTContext().LangOpts.EnableAppExtensionRestrictions &&
      !getASTContext().LangOpts.EnableAppExtensionLibraryRestrictions) {
    return false;
  }

  // FIXME: This is still a lousy approximation of whether the module file will
  // be externally consumed.
  return true;
}

//===----------------------------------------------------------------------===//
// Cross-Import Overlays
//===----------------------------------------------------------------------===//

namespace swift {
/// Represents a file containing information about cross-module overlays.
class OverlayFile : public ASTAllocated<OverlayFile> {
  friend class ModuleDecl;
  /// The file that data should be loaded from.
  StringRef filePath;

  /// The list of module names; empty if loading failed.
  llvm::TinyPtrVector<Identifier> overlayModuleNames;

  enum class State { Pending, Loaded, Failed };
  State state = State::Pending;

  /// Actually loads the overlay module name list. This should mutate
  /// \c overlayModuleNames, but not \c filePath.
  ///
  /// \returns \c true on success, \c false on failure. Diagnoses any failures
  ///          before returning.
  bool loadOverlayModuleNames(const ModuleDecl *M, SourceLoc diagLoc,
                              Identifier bystandingModule);
  bool loadOverlayModuleNames(ASTContext &ctx,
                              StringRef module,
                              StringRef bystandingModule,
                              SourceLoc diagLoc);
public:
  OverlayFile(StringRef filePath)
      : filePath(filePath) {
    assert(!filePath.empty());
  }

  /// Returns the list of additional modules that should be imported if both
  /// the primary and secondary modules have been imported. This may load a
  /// file; if so, it will diagnose any errors itself and arrange for the file
  /// to not be loaded again.
  ///
  /// The result can be empty, either because of an error or because the file
  /// didn't contain any overlay module names.
  ArrayRef<Identifier> getOverlayModuleNames(const ModuleDecl *M,
                                             SourceLoc diagLoc,
                                             Identifier bystandingModule) {
    if (state == State::Pending) {
      state = loadOverlayModuleNames(M, diagLoc, bystandingModule)
            ? State::Loaded : State::Failed;
    }
    return overlayModuleNames;
  }
};
}

void ModuleDecl::addCrossImportOverlayFile(StringRef file) {
  auto &ctx = getASTContext();

  Identifier secondaryModule = ctx.getIdentifier(llvm::sys::path::stem(file));
  declaredCrossImports[secondaryModule]
      .push_back(new (ctx) OverlayFile(ctx.AllocateCopy(file)));
}

llvm::SmallSetVector<Identifier, 4>
ModuleDecl::collectCrossImportOverlay(ASTContext &ctx,
                                      StringRef file,
                                      StringRef moduleName,
                                      StringRef &bystandingModule) {
  OverlayFile ovFile(file);
  bystandingModule = llvm::sys::path::stem(file);
  ovFile.loadOverlayModuleNames(ctx, moduleName, bystandingModule, SourceLoc());
  llvm::SmallSetVector<Identifier, 4> result;
  for (auto Id: ovFile.overlayModuleNames) {
    result.insert(Id);
  }
  return result;
}

bool ModuleDecl::mightDeclareCrossImportOverlays() const {
  return !declaredCrossImports.empty();
}

void ModuleDecl::
findDeclaredCrossImportOverlays(Identifier bystanderName,
                                SmallVectorImpl<Identifier> &overlayNames,
                                SourceLoc diagLoc) const {
  if (getName() == bystanderName)
    // We don't currently support self-cross-imports.
    return;

  for (auto &crossImportFile : declaredCrossImports.lookup(bystanderName))
    llvm::copy(crossImportFile->getOverlayModuleNames(this, diagLoc,
                                                      bystanderName),
               std::back_inserter(overlayNames));
}

void ModuleDecl::getDeclaredCrossImportBystanders(
    SmallVectorImpl<Identifier> &otherModules) {
  for (auto &pair : declaredCrossImports)
    otherModules.push_back(std::get<0>(pair));
}

void ModuleDecl::findDeclaredCrossImportOverlaysTransitive(
    SmallVectorImpl<ModuleDecl *> &overlayModules) {
  SmallVector<ModuleDecl *, 1> worklist;
  SmallPtrSet<ModuleDecl *, 1> seen;
  SourceLoc unused;

  worklist.push_back(this);
  if (auto *clangModule = getUnderlyingModuleIfOverlay())
    worklist.push_back(clangModule);

  while (!worklist.empty()) {
    ModuleDecl *current = worklist.back();
    worklist.pop_back();
    for (auto &pair: current->declaredCrossImports) {
      Identifier &bystander = std::get<0>(pair);
      for (auto *file: std::get<1>(pair)) {
        auto overlays = file->getOverlayModuleNames(current, unused, bystander);
        for (Identifier overlay: overlays) {
          // We don't present non-underscored overlays as part of the underlying
          // module, so ignore them.
          if (!overlay.hasUnderscoredNaming())
            continue;
          ModuleDecl *overlayMod =
              getASTContext().getModuleByName(overlay.str());
          if (!overlayMod)
            continue;
          if (seen.insert(overlayMod).second) {
            overlayModules.push_back(overlayMod);
            worklist.push_back(overlayMod);
            if (auto *clangModule = overlayMod->getUnderlyingModuleIfOverlay())
              worklist.push_back(clangModule);
          }
        }
      }
    }
  }
}

namespace {
  using CrossImportMap =
      llvm::SmallDenseMap<Identifier, SmallVector<OverlayFile *, 1>>;


  Identifier getBystanderIfDeclaring(ModuleDecl *mod, ModuleDecl *overlay,
                                     CrossImportMap modCrossImports) {
    auto ret = std::find_if(modCrossImports.begin(), modCrossImports.end(),
                            [&](CrossImportMap::iterator::value_type &pair) {
      for (OverlayFile *file: std::get<1>(pair)) {
        ArrayRef<Identifier> overlays = file->getOverlayModuleNames(
            mod, SourceLoc(), std::get<0>(pair));
        if (std::find(overlays.begin(), overlays.end(),
                      overlay->getName()) != overlays.end())
          return true;
      }
      return false;
    });
    return ret != modCrossImports.end() ? ret->first : Identifier();
  }
}

std::pair<ModuleDecl *, Identifier>
ModuleDecl::getDeclaringModuleAndBystander() {
  if (declaringModuleAndBystander)
    return *declaringModuleAndBystander;

  if (!hasUnderscoredNaming())
    return *(declaringModuleAndBystander = {nullptr, Identifier()});

  // Search the transitive set of imported @_exported modules to see if any have
  // this module as their overlay.
  SmallPtrSet<ModuleDecl *, 16> seen;
  SmallVector<ImportedModule, 16> imported;
  SmallVector<ImportedModule, 16> furtherImported;
  ModuleDecl *overlayModule = this;

  getImportedModules(imported, ModuleDecl::ImportFilterKind::Exported);
  while (!imported.empty()) {
    ModuleDecl *importedModule = imported.back().importedModule;
    imported.pop_back();
    if (!seen.insert(importedModule).second)
      continue;

    Identifier bystander = getBystanderIfDeclaring(
        importedModule, overlayModule, importedModule->declaredCrossImports);
    if (!bystander.empty())
      return *(declaringModuleAndBystander = {importedModule, bystander});

    // Also check the imported module's underlying module if it's a traditional
    // overlay (i.e. not a cross-import overlay).
    if (auto *clangModule = importedModule->getUnderlyingModuleIfOverlay()) {
      Identifier bystander = getBystanderIfDeclaring(
          clangModule, overlayModule, clangModule->declaredCrossImports);
      if (!bystander.empty())
        return *(declaringModuleAndBystander = {clangModule, bystander});
    }

    if (!importedModule->hasUnderscoredNaming())
      continue;

    furtherImported.clear();
    importedModule->getImportedModules(furtherImported,
                                       ModuleDecl::ImportFilterKind::Exported);
    imported.append(furtherImported.begin(), furtherImported.end());
  }

  return *(declaringModuleAndBystander = {nullptr, Identifier()});
}

bool ModuleDecl::isClangOverlayOf(ModuleDecl *potentialUnderlying) const {
  return getUnderlyingModuleIfOverlay() == potentialUnderlying;
}

bool ModuleDecl::isSameModuleLookingThroughOverlays(
  ModuleDecl *other) {
  if (this == other) {
    return true;
  }

  if (this->isClangOverlayOf(other) || other->isClangOverlayOf(this)) {
    return true;
  }

  return false;
}

bool ModuleDecl::isCrossImportOverlayOf(ModuleDecl *other) {
  ModuleDecl *current = this;
  ModuleDecl *otherClang = other->getUnderlyingModuleIfOverlay();
  while ((current = current->getDeclaringModuleAndBystander().first)) {
    if (current == other || current == otherClang)
      return true;
  }
  return false;
}

ModuleDecl *ModuleDecl::getDeclaringModuleIfCrossImportOverlay() {
  ModuleDecl *current = this, *declaring = nullptr;
  while ((current = current->getDeclaringModuleAndBystander().first))
    declaring = current;
  return declaring;
}

bool ModuleDecl::getRequiredBystandersIfCrossImportOverlay(
    ModuleDecl *declaring, SmallVectorImpl<Identifier> &bystanderNames) {
  auto *clangModule = declaring->getUnderlyingModuleIfOverlay();
  auto current = std::make_pair(this, Identifier());
  while ((current = current.first->getDeclaringModuleAndBystander()).first) {
    bystanderNames.push_back(current.second);
    if (current.first == declaring || current.first == clangModule)
      return true;
  }
  return false;
}

namespace {
struct OverlayFileContents {
  struct Module {
    std::string name;
  };

  unsigned version;
  std::vector<Module> modules;

  static llvm::ErrorOr<OverlayFileContents>
  load(std::unique_ptr<llvm::MemoryBuffer> input,
       SmallVectorImpl<std::string> &errorMessages);
};
} // end anonymous namespace

namespace llvm {
namespace yaml {
template <>
struct MappingTraits<OverlayFileContents::Module> {
  static void mapping(IO &io, OverlayFileContents::Module &module) {
    io.mapRequired("name", module.name);
  }
};

template <>
struct SequenceElementTraits<OverlayFileContents::Module> {
  static const bool flow = false;
};

template <>
struct MappingTraits<OverlayFileContents> {
  static void mapping(IO &io, OverlayFileContents &contents) {
    io.mapRequired("version", contents.version);
    io.mapRequired("modules", contents.modules);
  }
};
}
} // end namespace 'llvm'

static void pushYAMLError(const llvm::SMDiagnostic &diag, void *Context) {
  auto &errorMessages = *static_cast<SmallVectorImpl<std::string> *>(Context);
  errorMessages.emplace_back(diag.getMessage());
}

llvm::ErrorOr<OverlayFileContents>
OverlayFileContents::load(std::unique_ptr<llvm::MemoryBuffer> input,
                          SmallVectorImpl<std::string> &errorMessages) {
  llvm::yaml::Input yamlInput(input->getBuffer(), /*Ctxt=*/nullptr,
                              pushYAMLError, &errorMessages);
  OverlayFileContents contents;
  yamlInput >> contents;

  if (auto error = yamlInput.error())
    return error;

  if (contents.version > 1) {
    std::string message = (Twine("key 'version' has invalid value: ") + Twine(contents.version)).str();
    errorMessages.emplace_back(std::move(message));
    return make_error_code(std::errc::result_out_of_range);
  }

  return contents;
}

bool
OverlayFile::loadOverlayModuleNames(ASTContext &ctx, StringRef module,
                                    StringRef bystanderName,
                                    SourceLoc diagLoc) {
  llvm::vfs::FileSystem &fs = *ctx.SourceMgr.getFileSystem();

  auto bufOrError = fs.getBufferForFile(filePath);
  if (!bufOrError) {
    ctx.Diags.diagnose(diagLoc, diag::cannot_load_swiftoverlay_file,
                       module, bystanderName,
                       bufOrError.getError().message(), filePath);
    return false;
  }

  SmallVector<std::string, 4> errorMessages;
  auto contentsOrErr = OverlayFileContents::load(std::move(bufOrError.get()),
                                                 errorMessages);
  if (!contentsOrErr) {
    if (errorMessages.empty())
      errorMessages.push_back(contentsOrErr.getError().message());

    for (auto message : errorMessages)
      ctx.Diags.diagnose(diagLoc, diag::cannot_load_swiftoverlay_file,
                         module, bystanderName, message, filePath);
    return false;
  }

  auto contents = std::move(*contentsOrErr);

  for (const auto &module : contents.modules) {
    auto moduleIdent = ctx.getIdentifier(module.name);
    overlayModuleNames.push_back(moduleIdent);
  }

  return true;
}

bool
OverlayFile::loadOverlayModuleNames(const ModuleDecl *M, SourceLoc diagLoc,
                                    Identifier bystanderName) {
  return loadOverlayModuleNames(M->getASTContext(),
                                M->getName().str(),
                                bystanderName.str(),
                                diagLoc);
}

//===----------------------------------------------------------------------===//
// SourceFile Implementation
//===----------------------------------------------------------------------===//

void SourceFile::print(raw_ostream &OS, const PrintOptions &PO) {
  StreamPrinter Printer(OS);
  print(Printer, PO);
}

void SourceFile::print(ASTPrinter &Printer, const PrintOptions &PO) {
  std::set<DeclKind> MajorDeclKinds = {DeclKind::Class, DeclKind::Enum,
    DeclKind::Extension, DeclKind::Protocol, DeclKind::Struct};
  SmallVector<Decl *> topLevelDecls;
  getTopLevelDeclsWithAuxiliaryDecls(topLevelDecls);
  for (auto decl : topLevelDecls) {
    if (!decl->shouldPrintInContext(PO))
      continue;
    // For a major decl, we print an empty line before it.
    if (MajorDeclKinds.find(decl->getKind()) != MajorDeclKinds.end())
      Printer << "\n";
    if (decl->print(Printer, PO))
      Printer << "\n";
  }
}

void
SourceFile::setImports(ArrayRef<AttributedImport<ImportedModule>> imports) {
  assert(!Imports && "Already computed imports");
  Imports = getASTContext().AllocateCopy(imports);
}

std::optional<AttributedImport<ImportedModule>>
SourceFile::findImport(const ModuleDecl *module) const {
  return evaluateOrDefault(getASTContext().evaluator,
                           ImportDeclRequest{this, module}, std::nullopt);
}

std::optional<AttributedImport<ImportedModule>>
ImportDeclRequest::evaluate(Evaluator &evaluator, const SourceFile *sf,
                            const ModuleDecl *module) const {
  auto &ctx = sf->getASTContext();
  auto imports = sf->getImports();

  auto mutModule = const_cast<ModuleDecl *>(module);
  // Look to see if the owning module was directly imported.
  for (const auto &import : imports) {
    if (import.module.importedModule
            ->isSameModuleLookingThroughOverlays(mutModule))
      return import;
  }

  // Now look for transitive imports.
  auto &importCache = ctx.getImportCache();
  for (const auto &import : imports) {
    auto &importSet = importCache.getImportSet(import.module.importedModule);
    for (const auto &transitive : importSet.getTransitiveImports()) {
      if (transitive.importedModule
              ->isSameModuleLookingThroughOverlays(mutModule)) {
        return import;
      }
    }
  }

  return std::nullopt;
}

bool SourceFile::hasImportUsedPreconcurrency(
    AttributedImport<ImportedModule> import) const {
  return PreconcurrencyImportsUsed.count(import) != 0;
}

void SourceFile::setImportUsedPreconcurrency(
    AttributedImport<ImportedModule> import) {
  PreconcurrencyImportsUsed.insert(import);
}

AccessLevel
SourceFile::getMaxAccessLevelUsingImport(
    const ModuleDecl *mod) const {
  auto known = ImportsUseAccessLevel.find(mod);
  if (known == ImportsUseAccessLevel.end())
    return AccessLevel::Internal;
  return known->second;
}

void SourceFile::registerAccessLevelUsingImport(
    AttributedImport<ImportedModule> import,
    AccessLevel accessLevel) {
  auto mod = import.module.importedModule;
  auto known = ImportsUseAccessLevel.find(mod);
  if (known == ImportsUseAccessLevel.end())
    ImportsUseAccessLevel[mod] = accessLevel;
  else
    ImportsUseAccessLevel[mod] = std::max(accessLevel, known->second);
}

bool HasImportsMatchingFlagRequest::evaluate(Evaluator &evaluator,
                                             SourceFile *SF,
                                             ImportFlags flag) const {
  for (auto desc : SF->getImports()) {
    if (desc.options.contains(flag))
      return true;
  }
  return false;
}

std::optional<bool> HasImportsMatchingFlagRequest::getCachedResult() const {
  SourceFile *sourceFile = std::get<0>(getStorage());
  ImportFlags flag = std::get<1>(getStorage());
  if (sourceFile->validCachedImportOptions.contains(flag))
    return sourceFile->cachedImportOptions.contains(flag);

  return std::nullopt;
}

void HasImportsMatchingFlagRequest::cacheResult(bool value) const {
  SourceFile *sourceFile = std::get<0>(getStorage());
  ImportFlags flag = std::get<1>(getStorage());

  sourceFile->validCachedImportOptions |= flag;
  if (value)
    sourceFile->cachedImportOptions |= flag;
}

void swift::simple_display(llvm::raw_ostream &out, ImportOptions options) {
  using Flag = std::pair<ImportFlags, StringRef>;
  Flag possibleFlags[] = {
#define FLAG(Name) {ImportFlags::Name, #Name},
    FLAG(Exported)
    FLAG(Testable)
    FLAG(PrivateImport)
    FLAG(ImplementationOnly)
    FLAG(SPIAccessControl)
    FLAG(Preconcurrency)
    FLAG(WeakLinked)
    FLAG(Reserved)
#undef FLAG
  };

  auto flagsToPrint = llvm::make_filter_range(
      possibleFlags, [&](Flag flag) { return options & flag.first; });

  out << "{ ";
  interleave(
      flagsToPrint, [&](Flag flag) { out << flag.second; },
      [&] { out << ", "; });
  out << " }";
}

bool SourceFile::hasImportsWithFlag(ImportFlags flag) const {
  auto &ctx = getASTContext();
  auto *mutableThis = const_cast<SourceFile *>(this);
  return evaluateOrDefault(
      ctx.evaluator, HasImportsMatchingFlagRequest{mutableThis, flag}, false);
}

ImportFlags SourceFile::getImportFlags(const ModuleDecl *module) const {
  unsigned flags = 0x0;
  for (auto import : *Imports) {
    if (import.module.importedModule == module)
      flags |= import.options.toRaw();
  }
  return ImportFlags(flags);
}

bool SourceFile::hasTestableOrPrivateImport(
    AccessLevel accessLevel, const swift::ValueDecl *ofDecl,
    SourceFile::ImportQueryKind queryKind) const {
  auto *module = ofDecl->getModuleContext();
  switch (accessLevel) {
  case AccessLevel::Internal:
  case AccessLevel::Package:
  case AccessLevel::Public:
  case AccessLevel::Open:
    // internal/public access only needs an import marked as @_private. The
    // filename does not need to match (and we don't serialize it for such
    // decls).
    return llvm::any_of(*Imports,
        [module, queryKind](AttributedImport<ImportedModule> desc) -> bool {
          if (queryKind == ImportQueryKind::TestableAndPrivate)
            return desc.module.importedModule == module &&
                   (desc.options.contains(ImportFlags::PrivateImport) ||
                    desc.options.contains(ImportFlags::Testable));
          else if (queryKind == ImportQueryKind::TestableOnly)
            return desc.module.importedModule == module &&
                   desc.options.contains(ImportFlags::Testable);
          else {
            assert(queryKind == ImportQueryKind::PrivateOnly);
            return desc.module.importedModule == module &&
                   desc.options.contains(ImportFlags::PrivateImport);
          }
        });
  case AccessLevel::FilePrivate:
  case AccessLevel::Private:
    // Fallthrough.
    break;
  }

  if (queryKind == ImportQueryKind::TestableOnly)
    return false;

  auto *DC = ofDecl->getDeclContext();
  if (!DC)
    return false;
  auto *scope = DC->getModuleScopeContext();
  if (!scope)
    return false;

  StringRef filename;
  if (auto *file = dyn_cast<LoadedFile>(scope)) {
    filename = file->getFilenameForPrivateDecl(ofDecl);
  } else
    return false;

  if (filename.empty())
    return false;

  return llvm::any_of(*Imports,
      [module, filename](AttributedImport<ImportedModule> desc) {
        return desc.module.importedModule == module &&
              desc.options.contains(ImportFlags::PrivateImport) &&
              desc.sourceFileArg == filename;
      });
}

RestrictedImportKind SourceFile::getRestrictedImportKind(const ModuleDecl *module) const {
  auto &imports = getASTContext().getImportCache();
  RestrictedImportKind importKind = RestrictedImportKind::MissingImport;

  // Workaround for the cases where the bridging header isn't properly
  // imported implicitly.
  if (module->getName().str() == CLANG_HEADER_MODULE_NAME)
    return RestrictedImportKind::None;

  // Look at the imports of this source file.
  for (auto &desc : *Imports) {
    if (desc.options.contains(ImportFlags::ImplementationOnly)) {
      if (importKind < RestrictedImportKind::ImplementationOnly &&
          imports.isImportedBy(module, desc.module.importedModule))
        importKind = RestrictedImportKind::ImplementationOnly;
    }
    else if (desc.options.contains(ImportFlags::SPIOnly)) {
      if (importKind < RestrictedImportKind::SPIOnly &&
          imports.isImportedBy(module, desc.module.importedModule))
        importKind = RestrictedImportKind::SPIOnly;
    }
    // If the module is imported publicly, there's no restriction.
    else if (imports.isImportedBy(module, desc.module.importedModule))
      return RestrictedImportKind::None;
  }

  // Now check this file's enclosing module in case there are re-exports.
  if (imports.isImportedBy(module, getParentModule()))
    return RestrictedImportKind::None;

  return importKind;
}

ImportAccessLevel
SourceFile::getImportAccessLevel(const ModuleDecl *targetModule) const {
  assert(Imports.has_value());

  // Leave it to the caller to avoid calling this service for a self import.
  // We want to return AccessLevel::Public, but there's no import site to return.
  assert(targetModule != getParentModule() &&
         "getImportAccessLevel doesn't support checking for a self-import");

  auto &imports = getASTContext().getImportCache();
  ImportAccessLevel restrictiveImport = std::nullopt;

  for (auto &import : *Imports) {
    if ((!restrictiveImport.has_value() ||
         import.accessLevel > restrictiveImport->accessLevel) &&
        imports.isImportedBy(targetModule, import.module.importedModule)) {
      restrictiveImport = import;
    }
  }

  return restrictiveImport;
}

CharSourceRange
IfConfigClauseRangeInfo::getDirectiveRange(const SourceManager &SM) const {
  return CharSourceRange(SM, DirectiveLoc, BodyLoc);
}

CharSourceRange
IfConfigClauseRangeInfo::getBodyRange(const SourceManager &SM) const {
  return CharSourceRange(SM, BodyLoc, EndLoc);
}

CharSourceRange
IfConfigClauseRangeInfo::getWholeRange(const SourceManager &SM) const {
  return CharSourceRange(SM, DirectiveLoc, EndLoc);
}

void SourceFile::recordIfConfigClauseRangeInfo(
    const IfConfigClauseRangeInfo &range) {
  IfConfigClauseRanges.Ranges.push_back(range);
  IfConfigClauseRanges.IsSorted = false;
}

ArrayRef<IfConfigClauseRangeInfo> SourceFile::getIfConfigClauseRanges() const {
  if (!IfConfigClauseRanges.IsSorted) {
    auto &SM = getASTContext().SourceMgr;
    // Sort the ranges if we need to.
    llvm::sort(
        IfConfigClauseRanges.Ranges, [&](const IfConfigClauseRangeInfo &lhs,
                                         const IfConfigClauseRangeInfo &rhs) {
          return SM.isBeforeInBuffer(lhs.getStartLoc(), rhs.getStartLoc());
        });

    // Be defensive and eliminate duplicates in case we've parsed twice.
    auto newEnd = llvm::unique(
        IfConfigClauseRanges.Ranges, [&](const IfConfigClauseRangeInfo &lhs,
                                         const IfConfigClauseRangeInfo &rhs) {
          if (lhs.getStartLoc() != rhs.getStartLoc())
            return false;
          assert(lhs.getBodyRange(SM) == rhs.getBodyRange(SM) &&
                 "range changed on a re-parse?");
          return true;
        });
    IfConfigClauseRanges.Ranges.erase(newEnd,
                                      IfConfigClauseRanges.Ranges.end());
    IfConfigClauseRanges.IsSorted = true;
  }

  return IfConfigClauseRanges.Ranges;
}

ArrayRef<IfConfigClauseRangeInfo>
SourceFile::getIfConfigClausesWithin(SourceRange outer) const {
  auto &SM = getASTContext().SourceMgr;
  assert(SM.getRangeForBuffer(BufferID).contains(outer.Start) &&
         "Range not within this file?");

  // First let's find the first #if that is after the outer start loc.
  auto ranges = getIfConfigClauseRanges();
  auto lower = llvm::lower_bound(
      ranges, outer.Start,
      [&](const IfConfigClauseRangeInfo &range, SourceLoc loc) {
        return SM.isBeforeInBuffer(range.getStartLoc(), loc);
      });
  if (lower == ranges.end() ||
      SM.isBeforeInBuffer(outer.End, lower->getStartLoc())) {
    return {};
  }
  // Next let's find the first #if that's after the outer end loc.
  auto upper = llvm::upper_bound(
      ranges, outer.End,
      [&](SourceLoc loc, const IfConfigClauseRangeInfo &range) {
        return SM.isBeforeInBuffer(loc, range.getStartLoc());
      });
  return llvm::ArrayRef(lower, upper - lower);
}

void ModuleDecl::setPackageName(Identifier name) {
  Package = PackageUnit::create(name, *this, getASTContext());
}

bool ModuleDecl::isImportedImplementationOnly(const ModuleDecl *module) const {
  if (module == this) return false;

  auto &imports = getASTContext().getImportCache();

  // Look through non-implementation-only imports to see if module is imported
  // in some other way. Otherwise we assume it's implementation-only imported.
  ModuleDecl::ImportFilter filter = {
    ModuleDecl::ImportFilterKind::Exported,
    ModuleDecl::ImportFilterKind::Default,
    ModuleDecl::ImportFilterKind::PackageOnly,
    ModuleDecl::ImportFilterKind::SPIOnly,
    ModuleDecl::ImportFilterKind::ShadowedByCrossImportOverlay};
  SmallVector<ImportedModule, 4> results;
  getImportedModules(results, filter);

  for (auto &desc : results) {
    if (imports.isImportedBy(module, desc.importedModule))
      return false;
  }

  return true;
}

bool ModuleDecl::
canBeUsedForCrossModuleOptimization(DeclContext *ctxt) const {
  ModuleDecl *moduleOfCtxt = ctxt->getParentModule();

  // If the context defined in the same module - or is the same module, it's
  // fine.
  if (moduleOfCtxt == this)
    return true;

  // See if context is imported in a "regular" way, i.e. not with
  // @_implementationOnly, `package import` or @_spiOnly.
  ModuleDecl::ImportFilter filter = {
    ModuleDecl::ImportFilterKind::ImplementationOnly,
    ModuleDecl::ImportFilterKind::PackageOnly,
    ModuleDecl::ImportFilterKind::SPIOnly
  };
  SmallVector<ImportedModule, 4> results;
  getImportedModules(results, filter);

  auto &imports = getASTContext().getImportCache();
  for (auto &desc : results) {
    if (imports.isImportedBy(moduleOfCtxt, desc.importedModule))
      return false;
  }
  return true;
}

void SourceFile::lookupImportedSPIGroups(
                        const ModuleDecl *importedModule,
                        llvm::SmallSetVector<Identifier, 4> &spiGroups) const {
  auto &imports = getASTContext().getImportCache();
  for (auto &import : *Imports) {
    if (import.options.contains(ImportFlags::SPIAccessControl) &&
        (importedModule == import.module.importedModule ||
         imports.isImportedByViaSwiftOnly(importedModule,
                                       import.module.importedModule))) {
      spiGroups.insert(import.spiGroups.begin(), import.spiGroups.end());
    }
  }
}

bool shouldImplicitImportAsSPI(ArrayRef<Identifier> spiGroups) {
  for (auto group : spiGroups) {
    if (group.empty())
      return true;
  }
  return false;
}

bool SourceFile::isImportedAsSPI(const ValueDecl *targetDecl) const {
  auto targetModule = targetDecl->getModuleContext();
  llvm::SmallSetVector<Identifier, 4> importedSPIGroups;

  // Objective-C SPIs are always imported implicitly.
  if (targetDecl->hasClangNode())
    return !targetDecl->getSPIGroups().empty();
  if (shouldImplicitImportAsSPI(targetDecl->getSPIGroups()))
    return true;

  if (hasTestableOrPrivateImport(AccessLevel::Public, targetDecl, PrivateOnly))
    return true;

  lookupImportedSPIGroups(targetModule, importedSPIGroups);
  if (importedSPIGroups.empty())
    return false;

  auto declSPIGroups = targetDecl->getSPIGroups();
  for (auto declSPI : declSPIGroups)
    if (importedSPIGroups.count(declSPI))
      return true;

  return false;
}

bool ModuleDecl::isImportedAsSPI(const SpecializeAttr *attr,
                                 const ValueDecl *targetDecl) const {
  auto declSPIGroups = attr->getSPIGroups();
  if (shouldImplicitImportAsSPI(declSPIGroups))
    return true;

  auto targetModule = targetDecl->getModuleContext();
  llvm::SmallSetVector<Identifier, 4> importedSPIGroups;
  lookupImportedSPIGroups(targetModule, importedSPIGroups);
  if (importedSPIGroups.empty()) return false;

  for (auto declSPI : declSPIGroups)
    if (importedSPIGroups.count(declSPI))
      return true;

  return false;
}

bool ModuleDecl::isImportedAsSPI(Identifier spiGroup,
                                 const ModuleDecl *fromModule) const {
  if (shouldImplicitImportAsSPI({spiGroup}))
    return true;

  llvm::SmallSetVector<Identifier, 4> importedSPIGroups;
  lookupImportedSPIGroups(fromModule, importedSPIGroups);
  if (importedSPIGroups.empty())
    return false;
  return importedSPIGroups.count(spiGroup);
}

bool ModuleDecl::isImportedAsWeakLinked(const ModuleDecl *module) const {
  return getASTContext().getImportCache().isWeakImportedBy(module, this);
}

bool Decl::isSPI() const {
  return !getSPIGroups().empty();
}

ArrayRef<Identifier> Decl::getSPIGroups() const {
  const Decl *D = abstractSyntaxDeclForAvailableAttribute(this);

  if (!isa<ValueDecl>(D) &&
      !isa<ExtensionDecl>(D))
    return ArrayRef<Identifier>();

  return evaluateOrDefault(getASTContext().evaluator,
                           SPIGroupsRequest{ D },
                           ArrayRef<Identifier>());
}

llvm::ArrayRef<Identifier>
SPIGroupsRequest::evaluate(Evaluator &evaluator, const Decl *decl) const {
  // Applies only to public ValueDecls and ExtensionDecls.
  assert (isa<ValueDecl>(decl) ||
          isa<ExtensionDecl>(decl));

  // First, look for local attributes.
  llvm::SetVector<Identifier> spiGroups;
  for (auto attr : decl->getAttrs().getAttributes<SPIAccessControlAttr>())
    for (auto spi : attr->getSPIGroups())
      spiGroups.insert(spi);

  // Backing storage for a wrapped property gets the SPI groups from the
  // original property.
  if (auto varDecl = dyn_cast<VarDecl>(decl))
    if (auto originalDecl = varDecl->getOriginalWrappedProperty()) {
      auto originalSPIs = originalDecl->getSPIGroups();
      spiGroups.insert(originalSPIs.begin(), originalSPIs.end());
    }

  // If there is no local SPI information, look at the context.
  if (spiGroups.empty()) {

    // Then in the extended nominal type.
    if (auto extension = dyn_cast<ExtensionDecl>(decl)) {
      if (auto extended = extension->getExtendedNominal()) {
        auto extSPIs = extended->getSPIGroups();
        if (!extSPIs.empty()) return extSPIs;
      }
    }

    // And finally in the parent context.
    auto parent = decl->getDeclContext();
    if (auto parentD = parent->getAsDecl()) {
      if (!isa<ModuleDecl>(parentD)) {
        return parentD->getSPIGroups();
      }
    }
  }

  auto &ctx = decl->getASTContext();
  return ctx.AllocateCopy(spiGroups.getArrayRef());
}

LibraryLevel ModuleDecl::getLibraryLevel() const {
  return evaluateOrDefault(getASTContext().evaluator,
                           ModuleLibraryLevelRequest{this},
                           LibraryLevel::Other);
}

LibraryLevel
ModuleLibraryLevelRequest::evaluate(Evaluator &evaluator,
                                    const ModuleDecl *module) const {
  auto &ctx = module->getASTContext();
  namespace path = llvm::sys::path;
  SmallString<128> scratch;

  /// Is \p path under the folder SDK/a/b/c/d/e?
  auto hasSDKPrefix =
    [&](StringRef path, const Twine &a, const Twine &b = "",
        const Twine &c = "", const Twine &d = "", const Twine &e = "") {
    scratch = ctx.SearchPathOpts.getSDKPath();
    path::append(scratch, a, b, c, d);
    path::append(scratch, e);
    return path.starts_with(scratch);
  };

  /// Is \p modulePath from System/Library/PrivateFrameworks/?
  auto fromPrivateFrameworks = [&](StringRef modulePath) -> bool {
    if (!ctx.LangOpts.Target.isOSDarwin()) return false;

    return hasSDKPrefix(modulePath, "AppleInternal", "Library", "Frameworks") ||
           hasSDKPrefix(modulePath, "System", "Library", "PrivateFrameworks") ||
           hasSDKPrefix(modulePath, "System", "iOSSupport", "System", "Library", "PrivateFrameworks") ||
           hasSDKPrefix(modulePath, "usr", "local", "include");
  };

  if (module->isNonSwiftModule()) {
    if (auto *underlying = module->findUnderlyingClangModule()) {
      // Imported clangmodules are SPI if they are defined by a private
      // modulemap or from the PrivateFrameworks folder in the SDK.
      bool moduleIsSPI = underlying->ModuleMapIsPrivate ||
                         fromPrivateFrameworks(underlying->PresumedModuleMapFile);
      return moduleIsSPI ? LibraryLevel::SPI : LibraryLevel::API;
    }
    return LibraryLevel::Other;

  } else if (module->isMainModule()) {
    // The current compilation target.
    return ctx.LangOpts.LibraryLevel;

  } else {
    // Other Swift modules are SPI if they are from the PrivateFrameworks
    // folder in the SDK.
    auto modulePath = module->getModuleFilename();
    return fromPrivateFrameworks(modulePath) ?
      LibraryLevel::SPI : LibraryLevel::API;
  }
}

bool SourceFile::shouldCrossImport() const {
  return Kind != SourceFileKind::SIL && Kind != SourceFileKind::Interface &&
         getASTContext().LangOpts.EnableCrossImportOverlays;
}

void ModuleDecl::clearLookupCache() {
  getASTContext().getImportCache().clear();

  setIsObjCNameLookupCachePopulated(false);
  ObjCNameLookupCache.clear();

  if (!Cache)
    return;

  // Abandon any current cache. We'll rebuild it on demand.
  Cache.reset();
}

void
SourceFile::cacheVisibleDecls(SmallVectorImpl<ValueDecl*> &&globals) const {
  SmallVectorImpl<ValueDecl*> &cached = getCache().AllVisibleValues;
  cached = std::move(globals);
}

const SmallVectorImpl<ValueDecl *> &
SourceFile::getCachedVisibleDecls() const {
  return getCache().AllVisibleValues;
}

llvm::StringMap<SourceFilePathInfo>
SourceFile::getInfoForUsedFilePaths() const {
  llvm::StringMap<SourceFilePathInfo> result;

  if (BufferID != -1) {
    result[getFilename()].physicalFileLoc =
        getASTContext().SourceMgr.getLocForBufferStart(BufferID);
  }

  for (auto &vpath : VirtualFilePaths) {
    result[vpath.Item].virtualFileLocs.insert(vpath.Loc);
  }

  return result;
}

/// Returns a map of filenames to a map of file paths to SourceFilePathInfo
/// instances, for all SourceFiles in the module.
static llvm::StringMap<llvm::StringMap<SourceFilePathInfo>>
getInfoForUsedFileNames(const ModuleDecl *module) {
  llvm::StringMap<llvm::StringMap<SourceFilePathInfo>> result;

  for (auto *file : module->getFiles()) {
    auto *sourceFile = dyn_cast<SourceFile>(file);
    if (!sourceFile) continue;

    for (auto &pair : sourceFile->getInfoForUsedFilePaths()) {
      StringRef fullPath = pair.first();
      StringRef fileName = llvm::sys::path::filename(fullPath);
      auto &info = pair.second;

      result[fileName][fullPath].merge(info);
    }
  }

  return result;
}

static void computeFileID(const ModuleDecl *module, StringRef name,
                          SmallVectorImpl<char> &result) {
  result.assign(module->getNameStr().begin(), module->getNameStr().end());
  result.push_back('/');
  result.append(name.begin(), name.end());
}

static StringRef
resolveFileIDConflicts(const ModuleDecl *module, StringRef fileString,
                       const llvm::StringMap<SourceFilePathInfo> &paths,
                       bool shouldDiagnose) {
  assert(paths.size() > 1);

  /// The path we consider to be "correct"; we will emit fix-its changing the
  /// other paths to match this one.
  StringRef winner = "";

  // First, select a winner.
  for (const auto &pathPair : paths) {
    // If there is a physical file with this name, we use its path and stop
    // looking.
    if (pathPair.second.physicalFileLoc.isValid()) {
      winner = pathPair.first();
      break;
    }

    // Otherwise, we favor the lexicographically "smaller" path.
    if (winner.empty() || winner > pathPair.first()) {
      winner = pathPair.first();
    }
  }

  // If we're not diagnosing, that's all we need to do.
  if (!shouldDiagnose)
    return winner;

  SmallString<64> winnerLiteral;
  llvm::raw_svector_ostream winnerLiteralStream{winnerLiteral};
  swift::printAsQuotedString(winnerLiteralStream, winner);

  auto &diags = module->getASTContext().Diags;

  // Diagnose the conflict at each #sourceLocation that specifies it.
  for (const auto &pathPair : paths) {
    bool isWinner = (pathPair.first() == winner);

    // Don't diagnose #sourceLocations that match the physical file.
    if (pathPair.second.physicalFileLoc.isValid()) {
      if (!isWinner) {
        // The driver is responsible for diagnosing this, but naughty people who
        // have directly invoked the frontend could make it happen here instead.
        StringRef filename = llvm::sys::path::filename(winner);
        diags.diagnose(SourceLoc(), diag::error_two_files_same_name,
                       filename, winner, pathPair.first());
        diags.diagnose(SourceLoc(), diag::note_explain_two_files_same_name);
      }
      continue;
    }

    for (auto loc : pathPair.second.virtualFileLocs) {
      diags.diagnose(loc,
                     diag::source_location_creates_file_id_conflicts,
                     fileString);

      // Offer a fix-it unless it would be tautological.
      if (!isWinner)
        diags.diagnose(loc, diag::fixit_correct_source_location_file, winner)
          .fixItReplace(loc, winnerLiteral);
    }
  }

  return winner;
}

llvm::StringMap<std::pair<std::string, bool>>
ModuleDecl::computeFileIDMap(bool shouldDiagnose) const {
  llvm::StringMap<std::pair<std::string, bool>> result;
  SmallString<64> scratch;

  for (auto &namePair : getInfoForUsedFileNames(this)) {
    computeFileID(this, namePair.first(), scratch);
    auto &infoForPaths = namePair.second;

    assert(!infoForPaths.empty());

    // TODO: In the future, we'd like to handle these conflicts gracefully by
    // generating a unique `#fileID` string for each conflicting name. For now,
    // we will simply warn about conflicts.
    StringRef winner = infoForPaths.begin()->first();
    if (infoForPaths.size() > 1)
      winner = resolveFileIDConflicts(this, scratch, infoForPaths,
                                      shouldDiagnose);

    for (auto &pathPair : infoForPaths) {
      result[pathPair.first()] =
          std::make_pair(scratch.str().str(), pathPair.first() == winner);
    }
  }

  return result;
}

SourceFile::SourceFile(ModuleDecl &M, SourceFileKind K,
                       std::optional<unsigned> bufferID,
                       ParsingOptions parsingOpts, bool isPrimary)
    : FileUnit(FileUnitKind::Source, M), BufferID(bufferID ? *bufferID : -1),
      ParsingOpts(parsingOpts), IsPrimary(isPrimary), Kind(K) {
  M.getASTContext().addDestructorCleanup(*this);

  assert(!IsPrimary || M.isMainModule() &&
         "A primary cannot appear outside the main module");

  if (isScriptMode()) {
    bool problem = M.registerEntryPointFile(this, SourceLoc(), std::nullopt);
    assert(!problem && "multiple main files?");
    (void)problem;
  }

  if (Kind == SourceFileKind::MacroExpansion ||
      Kind == SourceFileKind::DefaultArgument)
    M.addAuxiliaryFile(*this);
}

SourceFile::ParsingOptions
SourceFile::getDefaultParsingOptions(const LangOptions &langOpts) {
  ParsingOptions opts;
  if (langOpts.DisablePoundIfEvaluation)
    opts |= ParsingFlags::DisablePoundIfEvaluation;
  if (langOpts.CollectParsedToken)
    opts |= ParsingFlags::CollectParsedTokens;
  if (langOpts.hasFeature(Feature::ParserRoundTrip))
    opts |= ParsingFlags::RoundTrip;
  if (langOpts.hasFeature(Feature::ParserValidation))
    opts |= ParsingFlags::ValidateNewParserDiagnostics;
  return opts;
}

ArrayRef<Token> SourceFile::getAllTokens() const {
  assert(shouldCollectTokens() && "Disabled");
  auto &eval = getASTContext().evaluator;
  auto *mutableThis = const_cast<SourceFile *>(this);
  return *evaluateOrDefault(eval, ParseSourceFileRequest{mutableThis}, {})
              .CollectedTokens;
}

bool SourceFile::shouldCollectTokens() const {
  return Kind != SourceFileKind::SIL &&
         ParsingOpts.contains(ParsingFlags::CollectParsedTokens);
}

bool SourceFile::hasDelayedBodyParsing() const {
  if (ParsingOpts.contains(ParsingFlags::DisableDelayedBodies))
    return false;

  // Not supported right now.
  if (Kind == SourceFileKind::SIL)
    return false;
  if (shouldCollectTokens())
    return false;

  return true;
}

/// Add a hoisted declaration. See Decl::isHoisted().
void SourceFile::addHoistedDecl(Decl *d) {
  assert(d->isHoisted());
  Hoisted.push_back(d);
}

ArrayRef<Decl *> SourceFile::getTopLevelDecls() const {
  auto &ctx = getASTContext();
  auto *mutableThis = const_cast<SourceFile *>(this);
  return evaluateOrDefault(
      ctx.evaluator, ParseTopLevelDeclsRequest{mutableThis}, {});
}

void SourceFile::addTopLevelDecl(Decl *d) {
  // Force decl parsing if we haven't already.
  (void)getTopLevelItems();
  Items->push_back(d);

  // FIXME: This violates core properties of the evaluator.
  auto &ctx = getASTContext();
  auto *mutableThis = const_cast<SourceFile *>(this);
  ctx.evaluator.clearCachedOutput(ParseTopLevelDeclsRequest{mutableThis});
}

void SourceFile::prependTopLevelDecl(Decl *d) {
  // Force decl parsing if we haven't already.
  (void)getTopLevelItems();
  Items->insert(Items->begin(), d);

  // FIXME: This violates core properties of the evaluator.
  auto &ctx = getASTContext();
  auto *mutableThis = const_cast<SourceFile *>(this);
  ctx.evaluator.clearCachedOutput(ParseTopLevelDeclsRequest{mutableThis});
}

void SourceFile::addDelayedFunction(AbstractFunctionDecl *AFD) {
  // If we defer type checking to runtime, we won't
  // have to type check `AFD` ahead of time
  auto &Ctx = getASTContext();
  if (Ctx.TypeCheckerOpts.DeferToRuntime &&
      Ctx.LangOpts.hasFeature(Feature::LazyImmediate))
    return;
  DelayedFunctions.push_back(AFD);
}

void SourceFile::typeCheckDelayedFunctions() {

  for (unsigned i = 0; i < DelayedFunctions.size(); i++) {
    auto *AFD = DelayedFunctions[i];
    assert(!AFD->getDeclContext()->isLocalContext());
    AFD->getTypecheckedBody();
  }

  DelayedFunctions.clear();
}

ArrayRef<ASTNode> SourceFile::getTopLevelItems() const {
  auto &ctx = getASTContext();
  auto *mutableThis = const_cast<SourceFile *>(this);
  return evaluateOrDefault(ctx.evaluator, ParseSourceFileRequest{mutableThis},
                           {}).TopLevelItems;
}

ArrayRef<Decl *> SourceFile::getHoistedDecls() const {
  return Hoisted;
}

void *SourceFile::getExportedSourceFile() const {
  auto &eval = getASTContext().evaluator;
  return evaluateOrDefault(eval, ExportedSourceFileRequest{this}, nullptr);
}

bool FileUnit::walk(ASTWalker &walker) {
  SmallVector<Decl *, 64> Decls;
  getTopLevelDecls(Decls);
  llvm::SaveAndRestore<ASTWalker::ParentTy> SAR(walker.Parent,
                                                getParentModule());

  bool SkipInternal = getKind() == FileUnitKind::SerializedAST &&
      !walker.shouldWalkSerializedTopLevelInternalDecls();
  for (Decl *D : Decls) {
    if (SkipInternal) {
      // Ignore if the decl isn't visible
      if (auto *VD = dyn_cast<ValueDecl>(D)) {
        if (VD->getFormalAccess() < AccessLevel::Public)
          continue;
      }

      // Also ignore if the extended nominal isn't visible
      if (auto *ED = dyn_cast<ExtensionDecl>(D)) {
        auto *ND = ED->getExtendedNominal();
        if (ND && ND->getFormalAccess() < AccessLevel::Public)
          continue;
      }
    }

#ifndef NDEBUG
    PrettyStackTraceDecl debugStack("walking into decl", D);
#endif

    if (D->walk(walker))
      return true;

    if (walker.shouldWalkAccessorsTheOldWay()) {
      // Pretend that accessors share a parent with the storage.
      //
      // FIXME: Update existing ASTWalkers to deal with accessors appearing as
      // children of the storage instead.
      if (auto *ASD = dyn_cast<AbstractStorageDecl>(D)) {
        for (auto AD : ASD->getAllAccessors()) {
          if (AD->walk(walker))
            return true;
        }
      }
    }
  }

  return false;
}

bool SourceFile::walk(ASTWalker &walker) {
  llvm::SaveAndRestore<ASTWalker::ParentTy> SAR(walker.Parent,
                                                getParentModule());
  for (auto Item : getTopLevelItems()) {
    if (auto D = Item.dyn_cast<Decl *>()) {
      if (D->walk(walker))
        return true;
    } else {
      Item.walk(walker);
    }

    if (walker.shouldWalkAccessorsTheOldWay()) {
      // Pretend that accessors share a parent with the storage.
      //
      // FIXME: Update existing ASTWalkers to deal with accessors appearing as
      // children of the storage instead.
      if (auto *ASD = dyn_cast_or_null<AbstractStorageDecl>(
              Item.dyn_cast<Decl *>())) {
        for (auto AD : ASD->getAllAccessors()) {
          if (AD->walk(walker))
            return true;
        }
      }
    }
  }
  return false;
}

StringRef SourceFile::getFilename() const {
  if (BufferID == -1)
    return "";
  SourceManager &SM = getASTContext().SourceMgr;
  return SM.getIdentifierForBuffer(BufferID);
}

ASTScope &SourceFile::getScope() {
  if (!Scope)
    Scope = new (getASTContext()) ASTScope(this);
  return *Scope.get();
}

Identifier SourceFile::getPrivateDiscriminator(bool createIfMissing) const {
  if (!PrivateDiscriminator.empty() || !createIfMissing)
    return PrivateDiscriminator;

  StringRef name = getFilename();
  if (name.empty()) {
    assert(1 == count_if(getParentModule()->getFiles(),
                         [](const FileUnit *FU) -> bool {
                           return isa<SourceFile>(FU) &&
                                  cast<SourceFile>(FU)->getFilename().empty();
                         }) &&
           "can't promise uniqueness if multiple source files are nameless");

    // We still need a discriminator, so keep going.
  }

  // Use a hash of the basename of the source file as our discriminator.
  // This keeps us from leaking information about the original filename
  // while still providing uniqueness. Using the basename makes the
  // discriminator invariant across source checkout locations.
  // FIXME: Use a faster hash here? We don't need security, just uniqueness.
  llvm::MD5 hash;
  hash.update(getParentModule()->getName().str());
  hash.update(llvm::sys::path::filename(name));
  llvm::MD5::MD5Result result;
  hash.final(result);

  // Use the hash as a hex string, prefixed with an underscore to make sure
  // it is a valid identifier.
  // FIXME: There are more compact ways to encode a 16-byte value.
  SmallString<33> buffer{"_"};
  SmallString<32> hashString;
  llvm::MD5::stringifyResult(result, hashString);
  buffer += hashString;
  PrivateDiscriminator = getASTContext().getIdentifier(buffer.str().upper());
  return PrivateDiscriminator;
}

Identifier
SourceFile::getDiscriminatorForPrivateDecl(const Decl *D) const {
  assert(D->getDeclContext()->getModuleScopeContext() == this ||
         D->getDeclContext()->getModuleScopeContext() == getSynthesizedFile());
  return getPrivateDiscriminator(/*createIfMissing=*/true);
}

SynthesizedFileUnit *FileUnit::getSynthesizedFile() const {
  return cast_or_null<SynthesizedFileUnit>(SynthesizedFileAndKind.getPointer());
}

SynthesizedFileUnit &FileUnit::getOrCreateSynthesizedFile() {
  auto SynthesizedFile = getSynthesizedFile();
  if (!SynthesizedFile) {
    if (auto thisSynth = dyn_cast<SynthesizedFileUnit>(this))
      return *thisSynth;
    SynthesizedFile = new (getASTContext()) SynthesizedFileUnit(*this);
    SynthesizedFileAndKind.setPointer(SynthesizedFile);
  }
  return *SynthesizedFile;
}

TypeRefinementContext *SourceFile::getTypeRefinementContext() const {
  return TRC;
}

void SourceFile::setTypeRefinementContext(TypeRefinementContext *Root) {
  TRC = Root;
}

ArrayRef<OpaqueTypeDecl *> SourceFile::getOpaqueReturnTypeDecls() {
  for (auto *vd : UnvalidatedDeclsWithOpaqueReturnTypes.takeVector()) {
    if (auto opaqueDecl = vd->getOpaqueResultTypeDecl()) {
      auto inserted = ValidatedOpaqueReturnTypes.insert(
                {opaqueDecl->getOpaqueReturnTypeIdentifier().str(),
                 opaqueDecl});
      if (inserted.second) {
        OpaqueReturnTypes.push_back(opaqueDecl);
      }
    }
  }

  return OpaqueReturnTypes;
}

OpaqueTypeDecl *
SourceFile::lookupOpaqueResultType(StringRef MangledName) {
  // Check already-validated decls.
  auto found = ValidatedOpaqueReturnTypes.find(MangledName);
  if (found != ValidatedOpaqueReturnTypes.end())
    return found->second;

  // If there are unvalidated decls with opaque types, go through and validate
  // them now.
  (void) getOpaqueReturnTypeDecls();

  found = ValidatedOpaqueReturnTypes.find(MangledName);
  if (found != ValidatedOpaqueReturnTypes.end())
    return found->second;

  // Otherwise, we don't have a matching opaque decl.
  return nullptr;
}

bool SourceFile::isAsyncTopLevelSourceFile() const {
  return isScriptMode() &&
         (bool)evaluateOrDefault(getASTContext().evaluator,
                                 GetSourceFileAsyncNode{this}, ASTNode());
}

ASTNode GetSourceFileAsyncNode::evaluate(Evaluator &eval,
                                         const SourceFile *sf) const {
  for (Decl *d : sf->getTopLevelDecls()) {
    TopLevelCodeDecl *tld = dyn_cast<TopLevelCodeDecl>(d);
    if (tld && tld->getBody()) {
      if (ASTNode asyncNode = tld->getBody()->findAsyncNode())
        return asyncNode;
    }
  }
  return ASTNode();
}

ArrayRef<TypeDecl *> SourceFile::getLocalTypeDecls() const {
  auto *mutableThis = const_cast<SourceFile *>(this);
  return evaluateOrDefault(getASTContext().evaluator,
                           LocalTypeDeclsRequest{mutableThis}, {});
}

namespace {
class LocalTypeDeclCollector : public ASTWalker {
  SmallVectorImpl<TypeDecl *> &results;

public:
  LocalTypeDeclCollector(SmallVectorImpl<TypeDecl *> &results)
      : results(results) {}

  MacroWalking getMacroWalkingBehavior() const override {
    return MacroWalking::Expansion;
  }

  PreWalkAction walkToDeclPre(Decl *D) override {
    switch (D->getKind()) {
    case DeclKind::Enum:
    case DeclKind::Struct:
    case DeclKind::Class:
    case DeclKind::Protocol:
    case DeclKind::TypeAlias:
      if (D->getDeclContext()->isLocalContext())
        results.push_back(cast<TypeDecl>(D));
      break;
    default:
      break;
    }
    return Action::Continue();
  }
};
} // namespace

ArrayRef<TypeDecl *> LocalTypeDeclsRequest::evaluate(Evaluator &evaluator,
                                                     SourceFile *sf) const {
  SmallVector<TypeDecl *> results;
  LocalTypeDeclCollector collector(results);
  sf->walk(collector);
  return sf->getASTContext().AllocateCopy(results);
}

//===----------------------------------------------------------------------===//
// SynthesizedFileUnit Implementation
//===----------------------------------------------------------------------===//

SynthesizedFileUnit::SynthesizedFileUnit(FileUnit &FU)
    : FileUnit(FileUnitKind::Synthesized, *FU.getParentModule()), FU(FU) {
  FU.getASTContext().addDestructorCleanup(*this);
}

Identifier
SynthesizedFileUnit::getDiscriminatorForPrivateDecl(const Decl *D) const {
  assert(D->getDeclContext()->getModuleScopeContext() == this);

  // Use cached primitive discriminator if it exists.
  if (!PrivateDiscriminator.empty())
    return PrivateDiscriminator;

  // Start with the discriminator that the file we belong to would use.
  auto ownerDiscriminator = getFileUnit().getDiscriminatorForPrivateDecl(D);

  // Hash that with a special string to produce a different value that preserves
  // the entropy of the original.
  // TODO: Use a more robust discriminator for synthesized files. Pick something
  // that cannot conflict with `SourceFile` discriminators.
  llvm::MD5 hash;
  hash.update(ownerDiscriminator.str());
  hash.update("SYNTHESIZED FILE");
  llvm::MD5::MD5Result result;
  hash.final(result);

  // Use the hash as a hex string, prefixed with an underscore to make sure
  // it is a valid identifier.
  // FIXME: There are more compact ways to encode a 16-byte value.
  SmallString<33> buffer{"_"};
  SmallString<32> hashString;
  llvm::MD5::stringifyResult(result, hashString);
  buffer += hashString;
  PrivateDiscriminator = getASTContext().getIdentifier(buffer.str().upper());
  return PrivateDiscriminator;
}

void SynthesizedFileUnit::lookupValue(
    DeclName name, NLKind lookupKind,
    OptionSet<ModuleLookupFlags> Flags,
    SmallVectorImpl<ValueDecl *> &result) const {
  for (auto *decl : TopLevelDecls) {
    if (auto VD = dyn_cast<ValueDecl>(decl)) {
      if (VD->getName().matchesRef(name)) {
        result.push_back(VD);
      }
    }
  }
}

void SynthesizedFileUnit::lookupObjCMethods(
    ObjCSelector selector,
    SmallVectorImpl<AbstractFunctionDecl *> &results) const {
  // Synthesized files only contain top-level declarations, no `@objc` methods.
}

void SynthesizedFileUnit::getTopLevelDecls(
    SmallVectorImpl<swift::Decl *> &results) const {
  results.append(TopLevelDecls.begin(), TopLevelDecls.end());
}

//===----------------------------------------------------------------------===//
// Miscellaneous
//===----------------------------------------------------------------------===//

void FileUnit::anchor() {}
void FileUnit::getTopLevelDeclsWhereAttributesMatch(
            SmallVectorImpl<Decl*> &Results,
            llvm::function_ref<bool(DeclAttributes)> matchAttributes) const {
  auto prevSize = Results.size();
  getTopLevelDecls(Results);

  // Filter out unwanted decls that were just added to Results.
  // Note: We could apply this check in all implementations of
  // getTopLevelDecls instead or in everything that creates a Decl.
  auto newEnd = std::remove_if(Results.begin() + prevSize, Results.end(),
                               [&matchAttributes](const Decl *D) -> bool {
      return !matchAttributes(D->getAttrs());
    });
  Results.erase(newEnd, Results.end());
}

void FileUnit::getTopLevelDeclsWithAuxiliaryDecls(
    SmallVectorImpl<Decl*> &results) const {

  std::function<void(Decl *)> addResult;
  addResult = [&](Decl *decl) {
    results.push_back(decl);
    decl->visitAuxiliaryDecls(addResult);
  };

  SmallVector<Decl *, 32> nonExpandedDecls;
  nonExpandedDecls.reserve(results.capacity());
  getTopLevelDecls(nonExpandedDecls);
  for (auto *decl : nonExpandedDecls) {
    addResult(decl);
  }
}

void FileUnit::dumpDisplayDecls() const {
  SmallVector<Decl *, 32> Decls;
  getDisplayDecls(Decls);
  for (auto *D : Decls) {
    D->dump(llvm::errs());
  }
}

void FileUnit::dumpTopLevelDecls() const {
  SmallVector<Decl *, 32> Decls;
  getTopLevelDecls(Decls);
  for (auto *D : Decls) {
    D->dump(llvm::errs());
  }
}

void swift::simple_display(llvm::raw_ostream &out, const FileUnit *file) {
  if (!file) {
    out << "(null)";
    return;
  }

  switch (file->getKind()) {
  case FileUnitKind::Source:
    out << '\"' << cast<SourceFile>(file)->getFilename() << '\"';
    return;
  case FileUnitKind::Builtin:
    out << "(Builtin)";
    return;
  case FileUnitKind::Synthesized:
    out << "(synthesized)";
    return;
  case FileUnitKind::DWARFModule:
  case FileUnitKind::ClangModule:
  case FileUnitKind::SerializedAST:
    out << '\"' << cast<LoadedFile>(file)->getFilename() << '\"';
    return;
  }
  llvm_unreachable("Unhandled case in switch");
}

StringRef LoadedFile::getFilename() const {
  return "";
}

static const clang::Module *
getClangModule(llvm::PointerUnion<const ModuleDecl *, const void *> Union) {
  return static_cast<const clang::Module *>(Union.get<const void *>());
}

StringRef ModuleEntity::getName(bool useRealNameIfAliased) const {
  assert(!Mod.isNull());
  if (auto SwiftMod = Mod.dyn_cast<const ModuleDecl*>())
    return useRealNameIfAliased ? SwiftMod->getRealName().str() : SwiftMod->getName().str();
  return getClangModule(Mod)->Name;
}

std::string ModuleEntity::getFullName(bool useRealNameIfAliased) const {
  assert(!Mod.isNull());
  if (auto SwiftMod = Mod.dyn_cast<const ModuleDecl*>())
    return std::string(useRealNameIfAliased ? SwiftMod->getRealName() : SwiftMod->getName());
  return getClangModule(Mod)->getFullModuleName();
}

bool ModuleEntity::isSystemModule() const {
  assert(!Mod.isNull());
  if (auto SwiftMod = Mod.dyn_cast<const ModuleDecl*>())
    return SwiftMod->isSystemModule();
  return getClangModule(Mod)->IsSystem;
}

bool ModuleEntity::isNonUserModule() const {
  assert(!Mod.isNull());
  if (auto *SwiftMod = Mod.dyn_cast<const ModuleDecl *>())
    return SwiftMod->isNonUserModule();
  // TODO: Should handle clang modules as well
  return getClangModule(Mod)->IsSystem;
}

bool ModuleEntity::isBuiltinModule() const {
  assert(!Mod.isNull());
  if (auto SwiftMod = Mod.dyn_cast<const ModuleDecl*>())
    return SwiftMod->isBuiltinModule();
  return false;
}

const ModuleDecl* ModuleEntity::getAsSwiftModule() const {
  assert(!Mod.isNull());
  if (auto SwiftMod = Mod.dyn_cast<const ModuleDecl*>())
    return SwiftMod;
  return nullptr;
}

const clang::Module* ModuleEntity::getAsClangModule() const {
  assert(!Mod.isNull());
  if (Mod.is<const ModuleDecl*>())
    return nullptr;
  return getClangModule(Mod);
}

// See swift/Basic/Statistic.h for declaration: this enables tracing SourceFiles, is
// defined here to avoid too much layering violation / circular linkage
// dependency.

struct SourceFileTraceFormatter : public UnifiedStatsReporter::TraceFormatter {
  void traceName(const void *Entity, raw_ostream &OS) const override {
    if (!Entity)
      return;
    const SourceFile *SF = static_cast<const SourceFile *>(Entity);
    OS << llvm::sys::path::filename(SF->getFilename());
  }
  void traceLoc(const void *Entity, SourceManager *SM,
                clang::SourceManager *CSM, raw_ostream &OS) const override {
    // SourceFiles don't have SourceLocs of their own; they contain them.
  }
};

static SourceFileTraceFormatter TF;

template<>
const UnifiedStatsReporter::TraceFormatter*
FrontendStatsTracer::getTraceFormatter<const SourceFile *>() {
  return &TF;
}

bool IsNonUserModuleRequest::evaluate(Evaluator &evaluator, ModuleDecl *mod) const {
  // If there's no SDK path, fallback to checking whether the module was
  // in the system search path or a clang system module
  SearchPathOptions &searchPathOpts = mod->getASTContext().SearchPathOpts;
  StringRef sdkPath = searchPathOpts.getSDKPath();
  if (sdkPath.empty() && mod->isSystemModule())
    return true;

  // Some temporary module's get created with no module name and they have no
  // files. Avoid running `getFiles` on them (which will assert if there
  // aren't any).
  if (!mod->hasName() || mod->getFiles().empty())
    return false;
  
  auto *LF = dyn_cast_or_null<LoadedFile>(mod->getFiles().front());
  if (!LF)
    return false;
  
  StringRef modulePath = LF->getSourceFilename();
  if (modulePath.empty())
    return false;

  StringRef runtimePath = searchPathOpts.RuntimeResourcePath;
  return (!runtimePath.empty() && pathStartsWith(runtimePath, modulePath)) ||
      (!sdkPath.empty() && pathStartsWith(sdkPath, modulePath));
}

version::Version ModuleDecl::getLanguageVersionBuiltWith() const {
  for (auto *F : getFiles()) {
    auto *LD = dyn_cast<LoadedFile>(F);
    if (!LD)
      continue;

    auto version = LD->getLanguageVersionBuiltWith();
    if (!version.empty())
      return version;
  }

  return version::Version();
}

bool swift::diagnoseMissingImportForMember(const ValueDecl *decl,
                                           const DeclContext *dc,
                                           SourceLoc loc) {
  if (decl->findImport(dc))
    return false;

  auto &ctx = dc->getASTContext();
  auto definingModule = decl->getModuleContext();
  ctx.Diags.diagnose(loc, diag::candidate_from_missing_import,
                     decl->getDescriptiveKind(), decl->getName(),
                     definingModule);

  SourceLoc bestLoc =
      ctx.Diags.getBestAddImportFixItLoc(decl, dc->getParentSourceFile());
  if (!bestLoc.isValid())
    return false;

  llvm::SmallString<64> importText;

  // Check other source files for import flags that should be applied to the
  // fix-it for consistency with the rest of the imports in the module.
  auto parentModule = dc->getParentModule();
  OptionSet<ImportFlags> flags;
  for (auto file : parentModule->getFiles()) {
    if (auto sf = dyn_cast<SourceFile>(file))
      flags |= sf->getImportFlags(definingModule);
  }

  if (flags.contains(ImportFlags::Exported) ||
      parentModule->isClangOverlayOf(definingModule))
    importText += "@_exported ";
  if (flags.contains(ImportFlags::ImplementationOnly))
    importText += "@_implementationOnly ";
  if (flags.contains(ImportFlags::WeakLinked))
    importText += "@_weakLinked ";
  if (flags.contains(ImportFlags::SPIOnly))
    importText += "@_spiOnly ";

  // FIXME: Access level should be considered, too.

  // @_spi imports.
  if (decl->isSPI()) {
    auto spiGroups = decl->getSPIGroups();
    if (!spiGroups.empty()) {
      importText += "@_spi(";
      importText += spiGroups[0].str();
      importText += ") ";
    }
  }

  importText += "import ";
  importText += definingModule->getName().str();
  importText += "\n";
  ctx.Diags.diagnose(bestLoc, diag::candidate_add_import, definingModule)
      .fixItInsert(bestLoc, importText);

  return true;
}