File: SerializedModuleLoader.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 (1908 lines) | stat: -rw-r--r-- 73,029 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
//===--- SerializedModuleLoader.cpp - Import Swift modules ----------------===//
//
// 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
//
//===----------------------------------------------------------------------===//

#include "swift/Serialization/SerializedModuleLoader.h"
#include "ModuleFile.h"
#include "ModuleFileSharedCore.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/DiagnosticsSema.h"
#include "swift/AST/ImportCache.h"
#include "swift/AST/ModuleDependencies.h"
#include "swift/Basic/Defer.h"
#include "swift/Basic/FileTypes.h"
#include "swift/Basic/Platform.h"
#include "swift/Basic/STLExtras.h"
#include "swift/Basic/SourceManager.h"
#include "swift/Basic/Version.h"
#include "swift/Frontend/ModuleInterfaceLoader.h"
#include "swift/Option/Options.h"
#include "swift/Serialization/Validation.h"

#include "llvm/Option/OptTable.h"
#include "llvm/Option/ArgList.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/VersionTuple.h"
#include "llvm/TargetParser/Host.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/CommandLine.h"
#include <system_error>

using namespace swift;
using swift::version::Version;

namespace {

/// Apply \c body for each target-specific module file base name to search from
/// most to least desirable.
void forEachTargetModuleBasename(const ASTContext &Ctx,
                                 llvm::function_ref<void(StringRef)> body) {
  auto normalizedTarget = getTargetSpecificModuleTriple(Ctx.LangOpts.Target);

  // An arm64 module can import an arm64e module.
  std::optional<llvm::Triple> normalizedAltTarget;
  if ((normalizedTarget.getArch() == llvm::Triple::ArchType::aarch64) &&
      (normalizedTarget.getSubArch() !=
       llvm::Triple::SubArchType::AArch64SubArch_arm64e)) {
    auto altTarget = normalizedTarget;
    altTarget.setArchName("arm64e");
    normalizedAltTarget = getTargetSpecificModuleTriple(altTarget);
  }

  body(normalizedTarget.str());

  if (normalizedAltTarget) {
    body(normalizedAltTarget->str());
  }

  // We used the un-normalized architecture as a target-specific
  // module name. Fall back to that behavior.
  body(Ctx.LangOpts.Target.getArchName());

  // FIXME: We used to use "major architecture" names for these files---the
  // names checked in "#if arch(...)". Fall back to that name in the one case
  // where it's different from what Swift 4.2 supported:
  // - 32-bit ARM platforms (formerly "arm")
  // We should be able to drop this once there's an Xcode that supports the
  // new names.
  if (Ctx.LangOpts.Target.getArch() == llvm::Triple::ArchType::arm) {
    body("arm");
  }

  if (normalizedAltTarget) {
    body(normalizedAltTarget->getArchName());
  }
}

/// Apply \p body for each module search path in \p Ctx until \p body returns
/// non-None value. Returns the return value from \p body, or \c None.
std::optional<bool> forEachModuleSearchPath(
    const ASTContext &Ctx,
    llvm::function_ref<std::optional<bool>(StringRef, ModuleSearchPathKind,
                                           bool isSystem)>
        callback) {
  for (const auto &path : Ctx.SearchPathOpts.getImportSearchPaths())
    if (auto result =
            callback(path, ModuleSearchPathKind::Import, /*isSystem=*/false))
      return result;

  for (const auto &path : Ctx.SearchPathOpts.getFrameworkSearchPaths())
    if (auto result =
            callback(path.Path, ModuleSearchPathKind::Framework, path.IsSystem))
      return result;

  // Apple platforms have extra implicit framework search paths:
  // $SDKROOT/System/Library/Frameworks/ and $SDKROOT/Library/Frameworks/.
  if (Ctx.LangOpts.Target.isOSDarwin()) {
    for (const auto &path : Ctx.getDarwinImplicitFrameworkSearchPaths())
      if (auto result =
              callback(path, ModuleSearchPathKind::DarwinImplicitFramework,
                       /*isSystem=*/true))
        return result;
  }

  for (const auto &importPath :
       Ctx.SearchPathOpts.getRuntimeLibraryImportPaths()) {
    if (auto result = callback(importPath, ModuleSearchPathKind::RuntimeLibrary,
                               /*isSystem=*/true))
      return result;
  }

  return std::nullopt;
}
} // end unnamed namespace

// Defined out-of-line so that we can see ~ModuleFile.
SerializedModuleLoaderBase::SerializedModuleLoaderBase(
    ASTContext &ctx, DependencyTracker *tracker, ModuleLoadingMode loadMode,
    bool IgnoreSwiftSourceInfoFile)
    : ModuleLoader(tracker), Ctx(ctx), LoadMode(loadMode),
      IgnoreSwiftSourceInfoFile(IgnoreSwiftSourceInfoFile) {}

SerializedModuleLoaderBase::~SerializedModuleLoaderBase() = default;
ImplicitSerializedModuleLoader::~ImplicitSerializedModuleLoader() = default;
MemoryBufferSerializedModuleLoader::~MemoryBufferSerializedModuleLoader() =
    default;

void SerializedModuleLoaderBase::collectVisibleTopLevelModuleNamesImpl(
    SmallVectorImpl<Identifier> &names, StringRef extension) const {
  llvm::SmallString<16> moduleSuffix;
  moduleSuffix += '.';
  moduleSuffix += file_types::getExtension(file_types::TY_SwiftModuleFile);

  llvm::SmallString<16> suffix;
  suffix += '.';
  suffix += extension;

  SmallVector<SmallString<64>, 2> targetFiles;
  forEachTargetModuleBasename(Ctx, [&](StringRef targetName) {
    targetFiles.emplace_back(targetName);
    targetFiles.back() += suffix;
  });

  auto &fs = *Ctx.SourceMgr.getFileSystem();

  // Apply \p body for each directory entry in \p dirPath.
  auto forEachDirectoryEntryPath =
      [&](StringRef dirPath, llvm::function_ref<void(StringRef)> body) {
        std::error_code errorCode;
        llvm::vfs::directory_iterator DI = fs.dir_begin(dirPath, errorCode);
        llvm::vfs::directory_iterator End;
        for (; !errorCode && DI != End; DI.increment(errorCode))
          body(DI->path());
      };

  // Check whether target specific module file exists or not in given directory.
  // $PATH/{arch}.{extension}
  auto checkTargetFiles = [&](StringRef path) -> bool {
    llvm::SmallString<256> scratch;
    for (auto targetFile : targetFiles) {
      scratch.clear();
      llvm::sys::path::append(scratch, path, targetFile);
      // If {arch}.{extension} exists, consider it's visible. Technically, we
      // should check the file type, permission, format, etc., but it's too
      // heavy to do that for each files.
      if (fs.exists(scratch))
        return true;
    }
    return false;
  };

  forEachModuleSearchPath(Ctx, [&](StringRef searchPath,
                                   ModuleSearchPathKind Kind, bool isSystem) {
    switch (Kind) {
    case ModuleSearchPathKind::Import: {
      // Look for:
      // $PATH/{name}.swiftmodule/{arch}.{extension} or
      // $PATH/{name}.{extension}
      forEachDirectoryEntryPath(searchPath, [&](StringRef path) {
        auto pathExt = llvm::sys::path::extension(path);
        if (pathExt != moduleSuffix && pathExt != suffix)
          return;

        auto stat = fs.status(path);
        if (!stat)
          return;
        if (pathExt == moduleSuffix && stat->isDirectory()) {
          if (!checkTargetFiles(path))
            return;
        } else if (pathExt != suffix || stat->isDirectory()) {
          return;
        }
        // Extract module name.
        auto name = llvm::sys::path::filename(path).drop_back(pathExt.size());
        names.push_back(Ctx.getIdentifier(name));
      });
      return std::nullopt;
    }
    case ModuleSearchPathKind::RuntimeLibrary: {
      // Look for:
      // (Darwin OS) $PATH/{name}.swiftmodule/{arch}.{extension}
      // (Other OS)  $PATH/{name}.{extension}
      bool requireTargetSpecificModule = Ctx.LangOpts.Target.isOSDarwin();
      forEachDirectoryEntryPath(searchPath, [&](StringRef path) {
        auto pathExt = llvm::sys::path::extension(path);

        if (pathExt != moduleSuffix)
          if (requireTargetSpecificModule || pathExt != suffix)
            return;

        if (!checkTargetFiles(path)) {
          if (requireTargetSpecificModule)
            return;

          auto stat = fs.status(path);
          if (!stat || stat->isDirectory())
            return;
        }

        // Extract module name.
        auto name = llvm::sys::path::filename(path).drop_back(pathExt.size());
        names.push_back(Ctx.getIdentifier(name));
      });
      return std::nullopt;
    }
    case ModuleSearchPathKind::Framework:
    case ModuleSearchPathKind::DarwinImplicitFramework: {
      // Look for:
      // $PATH/{name}.framework/Modules/{name}.swiftmodule/{arch}.{extension}
      forEachDirectoryEntryPath(searchPath, [&](StringRef path) {
        if (llvm::sys::path::extension(path) != ".framework")
          return;

        // Extract Framework name.
        auto name = llvm::sys::path::filename(path).drop_back(
            StringLiteral(".framework").size());

        SmallString<256> moduleDir;
        llvm::sys::path::append(moduleDir, path, "Modules",
                                name + moduleSuffix);
        if (!checkTargetFiles(moduleDir))
          return;

        names.push_back(Ctx.getIdentifier(name));
      });
      return std::nullopt;
    }
    }
    llvm_unreachable("covered switch");
  });
}

void ImplicitSerializedModuleLoader::collectVisibleTopLevelModuleNames(
    SmallVectorImpl<Identifier> &names) const {
  collectVisibleTopLevelModuleNamesImpl(
      names, file_types::getExtension(file_types::TY_SwiftModuleFile));
}

std::error_code SerializedModuleLoaderBase::openModuleDocFileIfPresent(
  ImportPath::Element ModuleID,
  const SerializedModuleBaseName &BaseName,
  std::unique_ptr<llvm::MemoryBuffer> *ModuleDocBuffer) {

  if (!ModuleDocBuffer)
    return std::error_code();

  llvm::vfs::FileSystem &FS = *Ctx.SourceMgr.getFileSystem();

  // Try to open the module documentation file.  If it does not exist, ignore
  // the error.  However, pass though all other errors.
  SmallString<256>
  ModuleDocPath{BaseName.getName(file_types::TY_SwiftModuleDocFile)};

  llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ModuleDocOrErr =
    FS.getBufferForFile(ModuleDocPath);
  if (ModuleDocOrErr) {
    *ModuleDocBuffer = std::move(*ModuleDocOrErr);
  } else if (ModuleDocOrErr.getError() !=
               std::errc::no_such_file_or_directory) {
    return ModuleDocOrErr.getError();
  }

  return std::error_code();
}

std::unique_ptr<llvm::MemoryBuffer>
SerializedModuleLoaderBase::getModuleName(ASTContext &Ctx, StringRef modulePath,
                                          std::string &Name) {
  return ModuleFile::getModuleName(Ctx, modulePath, Name);
}

std::error_code
SerializedModuleLoaderBase::openModuleSourceInfoFileIfPresent(
    ImportPath::Element ModuleID,
    const SerializedModuleBaseName &BaseName,
    std::unique_ptr<llvm::MemoryBuffer> *ModuleSourceInfoBuffer) {
  if (IgnoreSwiftSourceInfoFile || !ModuleSourceInfoBuffer)
    return std::error_code();

  llvm::vfs::FileSystem &FS = *Ctx.SourceMgr.getFileSystem();

  llvm::SmallString<128>
  PathWithoutProjectDir{BaseName.getName(file_types::TY_SwiftSourceInfoFile)};

  llvm::SmallString<128> PathWithProjectDir = PathWithoutProjectDir;

  // Insert "Project" before the filename in PathWithProjectDir.
  StringRef FileName = llvm::sys::path::filename(PathWithoutProjectDir);
  llvm::sys::path::remove_filename(PathWithProjectDir);
  llvm::sys::path::append(PathWithProjectDir, "Project");
  llvm::sys::path::append(PathWithProjectDir, FileName);

  // Try to open the module source info file from the "Project" directory.
  llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
  ModuleSourceInfoOrErr = FS.getBufferForFile(PathWithProjectDir);

  // If it does not exist, try to open the module source info file adjacent to
  // the .swiftmodule file.
  if (ModuleSourceInfoOrErr.getError() == std::errc::no_such_file_or_directory)
    ModuleSourceInfoOrErr = FS.getBufferForFile(PathWithoutProjectDir);

  // If we ended up with a different file system error, return it.
  if (ModuleSourceInfoOrErr)
    *ModuleSourceInfoBuffer = std::move(*ModuleSourceInfoOrErr);
  else if (ModuleSourceInfoOrErr.getError() !=
              std::errc::no_such_file_or_directory)
    return ModuleSourceInfoOrErr.getError();

  return std::error_code();
}

std::error_code SerializedModuleLoaderBase::openModuleFile(
    ImportPath::Element ModuleID, const SerializedModuleBaseName &BaseName,
    std::unique_ptr<llvm::MemoryBuffer> *ModuleBuffer) {
  llvm::vfs::FileSystem &FS = *Ctx.SourceMgr.getFileSystem();

  // Try to open the module file first.  If we fail, don't even look for the
  // module documentation file.
  SmallString<256> ModulePath{BaseName.getName(file_types::TY_SwiftModuleFile)};

  // If there's no buffer to load into, simply check for the existence of
  // the module file.
  if (!ModuleBuffer) {
    llvm::ErrorOr<llvm::vfs::Status> statResult = FS.status(ModulePath);
    if (!statResult)
      return statResult.getError();

    if (!statResult->exists())
      return std::make_error_code(std::errc::no_such_file_or_directory);

    // FIXME: llvm::vfs::FileSystem doesn't give us information on whether or
    // not we can /read/ the file without actually trying to do so.
    return std::error_code();
  }

  // Actually load the file and error out if necessary.
  //
  // Use the default arguments except for IsVolatile that is set by the
  // frontend option -enable-volatile-modules. If set, we avoid the use of
  // mmap to workaround issues on NFS when the swiftmodule file loaded changes
  // on disk while it's in use.
  //
  // In practice, a swiftmodule file can chane when a client uses a
  // swiftmodule file from a framework while the framework is recompiled and
  // installed over existing files. Or when many processes rebuild the same
  // module interface.
  //
  // We have seen these scenarios leading to deserialization errors that on
  // the surface look like memory corruption.
  //
  // rdar://63755989
  bool enableVolatileModules = Ctx.LangOpts.EnableVolatileModules;
  llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ModuleOrErr =
      FS.getBufferForFile(ModulePath,
                          /*FileSize=*/-1,
                          /*RequiresNullTerminator=*/true,
                          /*IsVolatile=*/enableVolatileModules);
  if (!ModuleOrErr)
    return ModuleOrErr.getError();

  *ModuleBuffer = std::move(ModuleOrErr.get());
  return std::error_code();
}

llvm::ErrorOr<SerializedModuleLoaderBase::BinaryModuleImports>
SerializedModuleLoaderBase::getImportsOfModule(
    const ModuleFileSharedCore &loadedModuleFile,
    ModuleLoadingBehavior transitiveBehavior, StringRef packageName,
    bool isTestableImport) {
  llvm::StringSet<> importedModuleNames;
  std::string importedHeader = "";
  for (const auto &dependency : loadedModuleFile.getDependencies()) {
    if (dependency.isHeader()) {
      assert(importedHeader.empty() &&
             "Unexpected more than one header dependency");
      importedHeader = dependency.RawPath;
      continue;
    }

    ModuleLoadingBehavior dependencyTransitiveBehavior =
        loadedModuleFile.getTransitiveLoadingBehavior(
            dependency,
            /*importPrivateDependencies*/ false,
            /*isPartialModule*/ false, packageName, isTestableImport);
    if (dependencyTransitiveBehavior > transitiveBehavior)
      continue;

    // Find the top-level module name.
    auto modulePathStr = dependency.getPrettyPrintedPath();
    StringRef moduleName = modulePathStr;
    auto dotPos = moduleName.find('.');
    if (dotPos != std::string::npos)
      moduleName = moduleName.slice(0, dotPos);

    // Reverse rewrite of user-specified C++ standard
    // library module name to one used in the modulemap.
    // TODO: If we are going to do this for more than this module,
    // we will need a centralized system for doing module import name remap.
    if (moduleName == Ctx.Id_CxxStdlib.str())
      moduleName = "std";

    importedModuleNames.insert(moduleName);
  }

  return SerializedModuleLoaderBase::BinaryModuleImports{importedModuleNames,
                                                         importedHeader};
}

llvm::ErrorOr<ModuleDependencyInfo>
SerializedModuleLoaderBase::scanModuleFile(Twine modulePath, bool isFramework,
                                           bool isTestableImport) {
  const std::string moduleDocPath;
  const std::string sourceInfoPath;

  // Read and valid module.
  auto moduleBuf = Ctx.SourceMgr.getFileSystem()->getBufferForFile(modulePath);
  if (!moduleBuf)
    return moduleBuf.getError();

  std::shared_ptr<const ModuleFileSharedCore> loadedModuleFile;
  serialization::ValidationInfo loadInfo = ModuleFileSharedCore::load(
      "", "", std::move(moduleBuf.get()), nullptr, nullptr, isFramework,
      isRequiredOSSAModules(), Ctx.LangOpts.SDKName,
      Ctx.SearchPathOpts.DeserializedPathRecoverer, loadedModuleFile);

  if (Ctx.SearchPathOpts.ScannerModuleValidation) {
    // If failed to load, just ignore and return do not found.
    if (loadInfo.status != serialization::Status::Valid) {
      if (Ctx.LangOpts.EnableModuleLoadingRemarks)
        Ctx.Diags.diagnose(SourceLoc(), diag::skip_module_invalid,
                           modulePath.str());
      return std::make_error_code(std::errc::no_such_file_or_directory);
    }
  }

  // Some transitive dependencies of binary modules are not required to be
  // imported during normal builds.
  // TODO: This is worth revisiting for debugger purposes where
  //       loading the module is optional, and implementation-only imports
  //       from modules with testing enabled where the dependency is
  //       optional.
  auto binaryModuleImports =
      getImportsOfModule(*loadedModuleFile, ModuleLoadingBehavior::Required,
                         Ctx.LangOpts.PackageName, isTestableImport);

  // Lookup optional imports of this module also
  auto binaryModuleOptionalImports =
      getImportsOfModule(*loadedModuleFile, ModuleLoadingBehavior::Optional,
                         Ctx.LangOpts.PackageName, isTestableImport);

  auto importedModuleSet = binaryModuleImports->moduleImports;
  std::vector<ScannerImportStatementInfo> moduleImports;
  moduleImports.reserve(importedModuleSet.size());
  llvm::transform(
      importedModuleSet.keys(), std::back_inserter(moduleImports),
      [](llvm::StringRef N) { return ScannerImportStatementInfo(N.str()); });

  auto importedHeader = binaryModuleImports->headerImport;
  auto &importedOptionalModuleSet = binaryModuleOptionalImports->moduleImports;
  std::vector<ScannerImportStatementInfo> optionalModuleImports;
  for (const auto optionalImportedModule : importedOptionalModuleSet.keys())
    if (!importedModuleSet.contains(optionalImportedModule))
      optionalModuleImports.push_back(
          ScannerImportStatementInfo(optionalImportedModule.str()));

  // Attempt to resolve the module's defining .swiftinterface path
  std::string definingModulePath =
       loadedModuleFile->resolveModuleDefiningFilePath(Ctx.SearchPathOpts.getSDKPath());

  // Map the set of dependencies over to the "module dependencies".
  auto dependencies = ModuleDependencyInfo::forSwiftBinaryModule(
      modulePath.str(), moduleDocPath, sourceInfoPath, moduleImports,
      optionalModuleImports, importedHeader, definingModulePath,
      isFramework, /*module-cache-key*/ "");

  return std::move(dependencies);
}

std::error_code ImplicitSerializedModuleLoader::findModuleFilesInDirectory(
    ImportPath::Element ModuleID, const SerializedModuleBaseName &BaseName,
    SmallVectorImpl<char> *ModuleInterfacePath,
    SmallVectorImpl<char> *ModuleInterfaceSourcePath,
    std::unique_ptr<llvm::MemoryBuffer> *ModuleBuffer,
    std::unique_ptr<llvm::MemoryBuffer> *ModuleDocBuffer,
    std::unique_ptr<llvm::MemoryBuffer> *ModuleSourceInfoBuffer,
    bool skipBuildingInterface, bool IsFramework, bool IsTestableDependencyLookup) {
  if (LoadMode == ModuleLoadingMode::OnlyInterface ||
      Ctx.IgnoreAdjacentModules)
    return std::make_error_code(std::errc::not_supported);

  auto ModuleErr = openModuleFile(ModuleID, BaseName, ModuleBuffer);
  if (ModuleErr)
    return ModuleErr;

  if (ModuleInterfaceSourcePath) {
    if (auto InterfacePath =
        BaseName.findInterfacePath(*Ctx.SourceMgr.getFileSystem(), Ctx))
      ModuleInterfaceSourcePath->assign(InterfacePath->begin(),
                                        InterfacePath->end());
  }

  if (auto ModuleSourceInfoError = openModuleSourceInfoFileIfPresent(
          ModuleID, BaseName, ModuleSourceInfoBuffer))
    return ModuleSourceInfoError;

  if (auto ModuleDocErr =
          openModuleDocFileIfPresent(ModuleID, BaseName, ModuleDocBuffer))
    return ModuleDocErr;

  return std::error_code();
}

bool ImplicitSerializedModuleLoader::maybeDiagnoseTargetMismatch(
    SourceLoc sourceLocation, StringRef moduleName,
    const SerializedModuleBaseName &absoluteBaseName) {
  llvm::vfs::FileSystem &fs = *Ctx.SourceMgr.getFileSystem();

  // Get the last component of the base name, which is the target-specific one.
  auto target = llvm::sys::path::filename(absoluteBaseName.baseName);

  // Strip off the last component to get the .swiftmodule folder.
  auto dir = absoluteBaseName.baseName;
  llvm::sys::path::remove_filename(dir);

  std::error_code errorCode;
  std::string foundArchs;
  for (llvm::vfs::directory_iterator directoryIterator =
           fs.dir_begin(dir, errorCode), endIterator;
       directoryIterator != endIterator;
       directoryIterator.increment(errorCode)) {
    if (errorCode)
      return false;
    StringRef filePath = directoryIterator->path();
    StringRef extension = llvm::sys::path::extension(filePath);
    if (file_types::lookupTypeForExtension(extension) ==
          file_types::TY_SwiftModuleFile) {
      if (!foundArchs.empty())
        foundArchs += ", ";
      foundArchs += llvm::sys::path::stem(filePath).str();
    }
  }

  if (foundArchs.empty()) {
    // Maybe this swiftmodule directory only contains swiftinterfaces, or
    // maybe something else is going on. Regardless, we shouldn't emit a
    // possibly incorrect diagnostic.
    return false;
  }

  Ctx.Diags.diagnose(sourceLocation, diag::sema_no_import_target, moduleName,
                     target, foundArchs, dir);
  return true;
}

SerializedModuleBaseName::SerializedModuleBaseName(
    StringRef parentDir, const SerializedModuleBaseName &name)
    : baseName(parentDir) {
  llvm::sys::path::append(baseName, name.baseName);
}

std::string SerializedModuleBaseName::getName(file_types::ID fileTy) const {
  auto result = baseName;
  result += '.';
  result += file_types::getExtension(fileTy);

  return std::string(result.str());
}

std::optional<std::string>
SerializedModuleBaseName::getPackageInterfacePathIfInSamePackage(
    llvm::vfs::FileSystem &fs, ASTContext &ctx) const {
  if (!ctx.LangOpts.EnablePackageInterfaceLoad)
    return std::nullopt;

  std::string packagePath{
      getName(file_types::TY_PackageSwiftModuleInterfaceFile)};

  if (fs.exists(packagePath)) {
    // Read the interface file and extract its package-name argument value
    if (auto packageName = getPackageNameFromInterface(packagePath, fs)) {
      // Return the .package.swiftinterface path if the package name applies to
      // the importer module.
      if (*packageName == ctx.LangOpts.PackageName)
        return packagePath;
    }
  }
  return std::nullopt;
}

std::optional<std::string>
SerializedModuleBaseName::getPackageNameFromInterface(
    StringRef interfacePath, llvm::vfs::FileSystem &fs) const {
  std::optional<std::string> result;
  if (auto interfaceFile = fs.getBufferForFile(interfacePath)) {
    llvm::BumpPtrAllocator alloc;
    llvm::StringSaver argSaver(alloc);
    SmallVector<const char *, 8> args;
    (void)extractCompilerFlagsFromInterface(
        interfacePath, (*interfaceFile)->getBuffer(), argSaver, args);
    for (unsigned I = 0, N = args.size(); I + 1 < N; I++) {
      StringRef current(args[I]), next(args[I + 1]);
      if (current == "-package-name") {
        // Instead of `break` here, continue to get the last value in case of
        // dupes, to be consistent with the default parsing logic.
        result = next;
      }
    }
  }
  return result;
}

std::optional<std::string>
SerializedModuleBaseName::findInterfacePath(llvm::vfs::FileSystem &fs,
                                            ASTContext &ctx) const {
  std::string interfacePath{getName(file_types::TY_SwiftModuleInterfaceFile)};
  // Ensure the public swiftinterface already exists, otherwise bail early
  // as it's considered the module doesn't exist.
  if (!fs.exists(interfacePath))
    return std::nullopt;

  // If there is a package name, try look for the package interface.
  if (!ctx.LangOpts.PackageName.empty()) {
    if (auto maybePackageInterface =
            getPackageInterfacePathIfInSamePackage(fs, ctx))
      return *maybePackageInterface;

    // If package interface is not found, check if we can load the
    // public/private interface file by checking:
    // * if AllowNonPackageInterfaceImportFromSamePackage is true
    // * if the package name is not equal so not in the same package.
    if (!ctx.LangOpts.AllowNonPackageInterfaceImportFromSamePackage) {
      if (auto packageName = getPackageNameFromInterface(interfacePath, fs)) {
        if (*packageName == ctx.LangOpts.PackageName)
          return std::nullopt;
      }
    }
  }

  // Otherwise, use the private interface instead of the public one.
  std::string privatePath{
      getName(file_types::TY_PrivateSwiftModuleInterfaceFile)};
  if (fs.exists(privatePath))
    return privatePath;

  // Otherwise return the public .swiftinterface path
  return interfacePath;
}

bool SerializedModuleLoaderBase::findModule(
    ImportPath::Element moduleID, SmallVectorImpl<char> *moduleInterfacePath,
    SmallVectorImpl<char> *moduleInterfaceSourcePath,
    std::unique_ptr<llvm::MemoryBuffer> *moduleBuffer,
    std::unique_ptr<llvm::MemoryBuffer> *moduleDocBuffer,
    std::unique_ptr<llvm::MemoryBuffer> *moduleSourceInfoBuffer,
    bool skipBuildingInterface, bool isTestableDependencyLookup,
    bool &isFramework, bool &isSystemModule) {
  // Find a module with an actual, physical name on disk, in case
  // -module-alias is used (otherwise same).
  //
  // For example, if '-module-alias Foo=Bar' is passed in to the frontend,
  // and a source file has 'import Foo', a module called Bar (real name)
  // should be searched.
  StringRef moduleNameRef = Ctx.getRealModuleName(moduleID.Item).str();
  SmallString<32> moduleName(moduleNameRef);
  SerializedModuleBaseName genericBaseName(moduleName);

  auto genericModuleFileName =
      genericBaseName.getName(file_types::TY_SwiftModuleFile);

  SmallVector<SerializedModuleBaseName, 4> targetSpecificBaseNames;
  forEachTargetModuleBasename(Ctx, [&](StringRef targetName) {
    // Construct a base name like ModuleName.swiftmodule/arch-vendor-os
    SmallString<64> targetBaseName{genericModuleFileName};
    llvm::sys::path::append(targetBaseName, targetName);

    targetSpecificBaseNames.emplace_back(targetBaseName.str());
  });

  auto &fs = *Ctx.SourceMgr.getFileSystem();

  llvm::SmallString<256> currPath;

  enum class SearchResult { Found, NotFound, Error };

  /// Returns true if a target-specific module file was found, false if an error
  /// was diagnosed, or None if neither one happened and the search should
  /// continue.
  auto findTargetSpecificModuleFiles = [&](bool IsFramework) -> SearchResult {
    std::optional<SerializedModuleBaseName> firstAbsoluteBaseName;

    for (const auto &targetSpecificBaseName : targetSpecificBaseNames) {
      SerializedModuleBaseName absoluteBaseName{currPath,
                                                targetSpecificBaseName};

      if (!firstAbsoluteBaseName.has_value())
        firstAbsoluteBaseName.emplace(absoluteBaseName);

      auto result = findModuleFilesInDirectory(
          moduleID, absoluteBaseName, moduleInterfacePath,
          moduleInterfaceSourcePath, moduleBuffer, moduleDocBuffer,
          moduleSourceInfoBuffer, skipBuildingInterface, IsFramework,
          isTestableDependencyLookup);
      if (!result)
        return SearchResult::Found;
      if (result == std::errc::not_supported)
        return SearchResult::Error;
      if (result != std::errc::no_such_file_or_directory)
        return SearchResult::NotFound;
    }

    // We can only get here if all targetFileNamePairs failed with
    // 'std::errc::no_such_file_or_directory'.
    if (firstAbsoluteBaseName &&
        maybeDiagnoseTargetMismatch(moduleID.Loc, moduleName,
                                    *firstAbsoluteBaseName))
      return SearchResult::Error;

    return SearchResult::NotFound;
  };

  SmallVector<std::string, 4> InterestingFilenames = {
      (moduleName + ".framework").str(),
      genericBaseName.getName(file_types::TY_SwiftModuleInterfaceFile),
      genericBaseName.getName(file_types::TY_PrivateSwiftModuleInterfaceFile),
      genericBaseName.getName(file_types::TY_PackageSwiftModuleInterfaceFile),
      genericBaseName.getName(file_types::TY_SwiftModuleFile)};

  auto searchPaths = Ctx.SearchPathOpts.moduleSearchPathsContainingFile(
      InterestingFilenames, Ctx.SourceMgr.getFileSystem().get(),
      Ctx.LangOpts.Target.isOSDarwin());
  for (const auto &searchPath : searchPaths) {
    currPath = searchPath->getPath();
    isSystemModule = searchPath->isSystem();

    switch (searchPath->getKind()) {
    case ModuleSearchPathKind::Import:
    case ModuleSearchPathKind::RuntimeLibrary: {
      isFramework = false;

      // On Apple platforms, we can assume that the runtime libraries use
      // target-specific module files within a `.swiftmodule` directory.
      // This was not always true on non-Apple platforms, and in order to
      // ease the transition, check both layouts.
      bool checkTargetSpecificModule = true;
      if (searchPath->getKind() != ModuleSearchPathKind::RuntimeLibrary ||
          !Ctx.LangOpts.Target.isOSDarwin()) {
        auto modulePath = currPath;
        llvm::sys::path::append(modulePath, genericModuleFileName);
        llvm::ErrorOr<llvm::vfs::Status> statResult = fs.status(modulePath);

        // Even if stat fails, we can't just return the error; the path
        // we're looking for might not be "Foo.swiftmodule".
        checkTargetSpecificModule = statResult && statResult->isDirectory();
      }

      if (checkTargetSpecificModule) {
        // A .swiftmodule directory contains architecture-specific files.
        switch (findTargetSpecificModuleFiles(isFramework)) {
        case SearchResult::Found:
          return true;
        case SearchResult::NotFound:
          continue;
        case SearchResult::Error:
          return false;
        }
      }

      SerializedModuleBaseName absoluteBaseName{currPath, genericBaseName};

      auto result = findModuleFilesInDirectory(
          moduleID, absoluteBaseName, moduleInterfacePath,
          moduleInterfaceSourcePath, moduleBuffer, moduleDocBuffer,
          moduleSourceInfoBuffer, skipBuildingInterface, isFramework,
          isTestableDependencyLookup);
      if (!result)
        return true;
      if (result == std::errc::not_supported)
        return false;
      continue;
    }
    case ModuleSearchPathKind::Framework:
    case ModuleSearchPathKind::DarwinImplicitFramework: {
      isFramework = true;
      llvm::sys::path::append(currPath, moduleName + ".framework");

      // Check if the framework directory exists.
      if (!fs.exists(currPath)) {
        continue;
      }

      // Frameworks always use architecture-specific files within a
      // .swiftmodule directory.
      llvm::sys::path::append(currPath, "Modules");
      switch (findTargetSpecificModuleFiles(isFramework)) {
      case SearchResult::Found:
        return true;
      case SearchResult::NotFound:
        continue;
      case SearchResult::Error:
        return false;
      }
    }
    }
    llvm_unreachable("covered switch");
  }
  return false;
}

static std::pair<StringRef, clang::VersionTuple>
getOSAndVersionForDiagnostics(const llvm::Triple &triple) {
  StringRef osName;
  llvm::VersionTuple osVersion;
  if (triple.isMacOSX()) {
    // macOS triples represent their versions differently, so we have to use the
    // special accessor.
    triple.getMacOSXVersion(osVersion);
    osName = swift::prettyPlatformString(PlatformKind::macOS);
  } else {
    osVersion = triple.getOSVersion();
    if (triple.isWatchOS()) {
      osName = swift::prettyPlatformString(PlatformKind::watchOS);
    } else if (triple.isTvOS()) {
      assert(triple.isiOS() &&
             "LLVM treats tvOS as a kind of iOS, so tvOS is checked first");
      osName = swift::prettyPlatformString(PlatformKind::tvOS);
    } else if (triple.isiOS()) {
      osName = swift::prettyPlatformString(PlatformKind::iOS);
    }  else if (triple.isXROS()) {
      osName = swift::prettyPlatformString(PlatformKind::visionOS);
    } else {
      assert(!triple.isOSDarwin() && "unknown Apple OS");
      // Fallback to the LLVM triple name. This isn't great (it won't be
      // capitalized or anything), but it's better than nothing.
      osName = triple.getOSName();
    }
  }

  assert(!osName.empty());
  return {osName, osVersion};
}

LoadedFile *SerializedModuleLoaderBase::loadAST(
    ModuleDecl &M, std::optional<SourceLoc> diagLoc,
    StringRef moduleInterfacePath, StringRef moduleInterfaceSourcePath,
    std::unique_ptr<llvm::MemoryBuffer> moduleInputBuffer,
    std::unique_ptr<llvm::MemoryBuffer> moduleDocInputBuffer,
    std::unique_ptr<llvm::MemoryBuffer> moduleSourceInfoInputBuffer,
    bool isFramework) {
  assert(moduleInputBuffer);

  // The buffers are moved into the shared core, so grab their IDs now in case
  // they're needed for diagnostics later.
  StringRef moduleBufferID = moduleInputBuffer->getBufferIdentifier();
  StringRef moduleDocBufferID;
  if (moduleDocInputBuffer)
    moduleDocBufferID = moduleDocInputBuffer->getBufferIdentifier();
  StringRef moduleSourceInfoID;
  if (moduleSourceInfoInputBuffer)
    moduleSourceInfoID = moduleSourceInfoInputBuffer->getBufferIdentifier();

  if (moduleInputBuffer->getBufferSize() % 4 != 0) {
    if (diagLoc)
      Ctx.Diags.diagnose(*diagLoc, diag::serialization_malformed_module,
                         moduleBufferID);
    return nullptr;
  }

  std::unique_ptr<ModuleFile> loadedModuleFile;
  std::shared_ptr<const ModuleFileSharedCore> loadedModuleFileCore;
  serialization::ValidationInfo loadInfo = ModuleFileSharedCore::load(
      moduleInterfacePath, moduleInterfaceSourcePath,
      std::move(moduleInputBuffer), std::move(moduleDocInputBuffer),
      std::move(moduleSourceInfoInputBuffer), isFramework,
      isRequiredOSSAModules(),
      Ctx.LangOpts.SDKName,
      Ctx.SearchPathOpts.DeserializedPathRecoverer, loadedModuleFileCore);
  SerializedASTFile *fileUnit = nullptr;

  if (loadInfo.status == serialization::Status::Valid) {
    loadedModuleFile =
        std::make_unique<ModuleFile>(std::move(loadedModuleFileCore));
    M.setResilienceStrategy(loadedModuleFile->getResilienceStrategy());

    // We've loaded the file. Now try to bring it into the AST.
    fileUnit = new (Ctx) SerializedASTFile(M, *loadedModuleFile);
    M.setStaticLibrary(loadedModuleFile->isStaticLibrary());
    M.setHasHermeticSealAtLink(loadedModuleFile->hasHermeticSealAtLink());
    M.setIsEmbeddedSwiftModule(loadedModuleFile->isEmbeddedSwiftModule());
    if (loadedModuleFile->isTestable())
      M.setTestingEnabled();
    if (loadedModuleFile->arePrivateImportsEnabled())
      M.setPrivateImportsEnabled();
    if (loadedModuleFile->isImplicitDynamicEnabled())
      M.setImplicitDynamicEnabled();
    if (loadedModuleFile->hasIncrementalInfo())
      M.setHasIncrementalInfo();
    if (loadedModuleFile->isBuiltFromInterface())
      M.setIsBuiltFromInterface();
    if (loadedModuleFile->allowNonResilientAccess())
      M.setAllowNonResilientAccess();
    if (loadedModuleFile->serializePackageEnabled())
      M.setSerializePackageEnabled();
    if (!loadedModuleFile->getModuleABIName().empty())
      M.setABIName(Ctx.getIdentifier(loadedModuleFile->getModuleABIName()));
    if (loadedModuleFile->isConcurrencyChecked())
      M.setIsConcurrencyChecked();
    if (loadedModuleFile->hasCxxInteroperability())
      M.setHasCxxInteroperability();
    if (!loadedModuleFile->getModulePackageName().empty()) {
      M.setPackageName(Ctx.getIdentifier(loadedModuleFile->getModulePackageName()));
    }
    M.setUserModuleVersion(loadedModuleFile->getUserModuleVersion());
    for (auto name: loadedModuleFile->getAllowableClientNames()) {
      M.addAllowableClientName(Ctx.getIdentifier(name));
    }
    if (Ctx.LangOpts.BypassResilienceChecks)
      M.setBypassResilience();
    auto diagLocOrInvalid = diagLoc.value_or(SourceLoc());
    loadInfo.status = loadedModuleFile->associateWithFileContext(
        fileUnit, diagLocOrInvalid, Ctx.LangOpts.AllowModuleWithCompilerErrors);

    // FIXME: This seems wrong. Overlay for system Clang module doesn't
    // necessarily mean it's "system" module. User can make their own overlay
    // in non-system directory.
    // Remove this block after we fix the test suite.
    if (auto shadowed = loadedModuleFile->getUnderlyingModule())
      if (shadowed->isSystemModule())
        M.setIsSystemModule(true);

    if (loadInfo.status == serialization::Status::Valid ||
        (Ctx.LangOpts.AllowModuleWithCompilerErrors &&
         (loadInfo.status == serialization::Status::TargetTooNew ||
          loadInfo.status == serialization::Status::TargetIncompatible))) {
      if (loadedModuleFile->hasSourceInfoFile() &&
          !loadedModuleFile->hasSourceInfo())
        Ctx.Diags.diagnose(diagLocOrInvalid,
                           diag::serialization_malformed_sourceinfo,
                           moduleSourceInfoID);

      Ctx.bumpGeneration();
      LoadedModuleFiles.emplace_back(std::move(loadedModuleFile),
                                     Ctx.getCurrentGeneration());
      findOverlayFiles(diagLoc.value_or(SourceLoc()), &M, fileUnit);
    } else {
      fileUnit = nullptr;
    }
  }

  if (loadInfo.status != serialization::Status::Valid) {
    if (diagLoc)
      serialization::diagnoseSerializedASTLoadFailure(
          Ctx, *diagLoc, loadInfo, moduleBufferID, moduleDocBufferID,
          loadedModuleFile.get(), M.getName());

    // Even though the module failed to load, it's possible its contents
    // include a source buffer that need to survive because it's already been
    // used for diagnostics.
    // Note this is only necessary in case a bridging header failed to load
    // during the `associateWithFileContext()` call.
    if (loadedModuleFile &&
        loadedModuleFile->mayHaveDiagnosticsPointingAtBuffer())
      OrphanedModuleFiles.push_back(std::move(loadedModuleFile));
  } else {
    // Report non-fatal compiler tag mismatch on stderr only to avoid
    // polluting the IDE UI.
    if (!loadInfo.problematicRevision.empty()) {
      llvm::errs() << "remark: compiled module was created by a different " <<
                      "version of the compiler '" <<
                      loadInfo.problematicRevision <<
                      "': " << moduleBufferID << "\n";
    }
  }

  // The -experimental-hermetic-seal-at-link flag turns on dead-stripping
  // optimizations assuming library code can be optimized against client code.
  // If the imported module was built with -experimental-hermetic-seal-at-link
  // but the current module isn't, error out.
  if (M.hasHermeticSealAtLink() && !Ctx.LangOpts.HermeticSealAtLink) {
    Ctx.Diags.diagnose(diagLoc.value_or(SourceLoc()),
                       diag::need_hermetic_seal_to_import_module, M.getName());
  }

  if (M.isEmbeddedSwiftModule() &&
      !Ctx.LangOpts.hasFeature(Feature::Embedded)) {
    Ctx.Diags.diagnose(diagLoc.value_or(SourceLoc()),
                       diag::cannot_import_embedded_module, M.getName());
  }

  if (!M.isEmbeddedSwiftModule() &&
      Ctx.LangOpts.hasFeature(Feature::Embedded)) {
    Ctx.Diags.diagnose(diagLoc.value_or(SourceLoc()),
                       diag::cannot_import_non_embedded_module, M.getName());
  }

  // Non-resilient modules built with C++ interoperability enabled
  // are typically incompatible with clients that do not enable
  // C++ interoperability.
  if (M.hasCxxInteroperability() &&
      M.getResilienceStrategy() != ResilienceStrategy::Resilient &&
      !Ctx.LangOpts.EnableCXXInterop &&
      Ctx.LangOpts.RequireCxxInteropToImportCxxInteropModule &&
      M.getName().str() != CXX_MODULE_NAME) {
    auto loc = diagLoc.value_or(SourceLoc());
    Ctx.Diags.diagnose(loc, diag::need_cxx_interop_to_import_module,
                       M.getName());
    Ctx.Diags.diagnose(loc, diag::enable_cxx_interop_docs);
  }

  return fileUnit;
}

bool SerializedModuleLoaderBase::isRequiredOSSAModules() const {
  return Ctx.SILOpts.EnableOSSAModules;
}

void swift::serialization::diagnoseSerializedASTLoadFailure(
    ASTContext &Ctx, SourceLoc diagLoc,
    const serialization::ValidationInfo &loadInfo,
    StringRef moduleBufferID, StringRef moduleDocBufferID,
    ModuleFile *loadedModuleFile, Identifier ModuleName) {
  auto diagnoseDifferentLanguageVersion = [&](StringRef shortVersion) -> bool {
    if (shortVersion.empty())
      return false;

    SmallString<32> versionBuf;
    llvm::raw_svector_ostream versionString(versionBuf);
    versionString << Version::getCurrentLanguageVersion();
    if (versionString.str() == shortVersion)
      return false;

    Ctx.Diags.diagnose(
        diagLoc, diag::serialization_module_language_version_mismatch,
        loadInfo.shortVersion, versionString.str(), moduleBufferID);
    return true;
  };

  switch (loadInfo.status) {
  case serialization::Status::Valid:
    llvm_unreachable("At this point we know loading has failed");

  case serialization::Status::FormatTooNew:
    if (diagnoseDifferentLanguageVersion(loadInfo.shortVersion))
      break;
    Ctx.Diags.diagnose(diagLoc, diag::serialization_module_too_new,
                       moduleBufferID);
    break;
  case serialization::Status::FormatTooOld:
    if (diagnoseDifferentLanguageVersion(loadInfo.shortVersion))
      break;
    Ctx.Diags.diagnose(diagLoc, diag::serialization_module_too_old, ModuleName,
                       moduleBufferID);
    break;
  case serialization::Status::NotInOSSA:
    // soft reject, silently ignore.
    break;
  case serialization::Status::RevisionIncompatible:
    Ctx.Diags.diagnose(diagLoc, diag::serialization_module_incompatible_revision,
                       loadInfo.problematicRevision, ModuleName, moduleBufferID);
    break;
  case serialization::Status::ChannelIncompatible:
    Ctx.Diags.diagnose(diagLoc, diag::serialization_module_incompatible_channel,
                       loadInfo.problematicChannel,
                       version::getCurrentCompilerChannel(),
                       ModuleName, moduleBufferID);
    break;
  case serialization::Status::Malformed:
    Ctx.Diags.diagnose(diagLoc, diag::serialization_malformed_module,
                       moduleBufferID);
    break;

  case serialization::Status::MalformedDocumentation:
    assert(!moduleDocBufferID.empty());
    Ctx.Diags.diagnose(diagLoc, diag::serialization_malformed_module,
                       moduleDocBufferID);
    break;

  case serialization::Status::MissingDependency:
  case serialization::Status::CircularDependency:
  case serialization::Status::MissingUnderlyingModule:
    serialization::diagnoseSerializedASTLoadFailureTransitive(
      Ctx, diagLoc, loadInfo.status,
      loadedModuleFile, ModuleName, /*forTestable*/false);
    break;

  case serialization::Status::FailedToLoadBridgingHeader:
    // We already emitted a diagnostic about the bridging header. Just emit
    // a generic message here.
    Ctx.Diags.diagnose(diagLoc, diag::serialization_load_failed,
                       ModuleName.str());
    break;

  case serialization::Status::NameMismatch: {
    // FIXME: This doesn't handle a non-debugger REPL, which should also treat
    // this as a non-fatal error.
    auto diagKind = diag::serialization_name_mismatch;
    if (Ctx.LangOpts.DebuggerSupport)
      diagKind = diag::serialization_name_mismatch_repl;
    Ctx.Diags.diagnose(diagLoc, diagKind, loadInfo.name, ModuleName.str());
    break;
  }

  case serialization::Status::TargetIncompatible: {
    // FIXME: This doesn't handle a non-debugger REPL, which should also treat
    // this as a non-fatal error.
    auto diagKind = diag::serialization_target_incompatible;
    if (Ctx.LangOpts.DebuggerSupport ||
        Ctx.LangOpts.AllowModuleWithCompilerErrors)
      diagKind = diag::serialization_target_incompatible_repl;
    Ctx.Diags.diagnose(diagLoc, diagKind, ModuleName, loadInfo.targetTriple,
                       moduleBufferID);
    break;
  }

  case serialization::Status::TargetTooNew: {
    llvm::Triple moduleTarget(llvm::Triple::normalize(loadInfo.targetTriple));

    std::pair<StringRef, clang::VersionTuple> moduleOSInfo =
        getOSAndVersionForDiagnostics(moduleTarget);
    std::pair<StringRef, clang::VersionTuple> compilationOSInfo =
        getOSAndVersionForDiagnostics(Ctx.LangOpts.Target);

    // FIXME: This doesn't handle a non-debugger REPL, which should also treat
    // this as a non-fatal error.
    auto diagKind = diag::serialization_target_too_new;
    if (Ctx.LangOpts.DebuggerSupport ||
        Ctx.LangOpts.AllowModuleWithCompilerErrors)
      diagKind = diag::serialization_target_too_new_repl;
    Ctx.Diags.diagnose(diagLoc, diagKind, compilationOSInfo.first,
                       compilationOSInfo.second, ModuleName,
                       moduleOSInfo.second, moduleBufferID);
    break;
  }

  case serialization::Status::SDKMismatch:
    auto currentSDK = Ctx.LangOpts.SDKName;
    auto moduleSDK = loadInfo.sdkName;
    Ctx.Diags.diagnose(diagLoc, diag::serialization_sdk_mismatch,
                       ModuleName, moduleSDK, currentSDK, moduleBufferID);
    break;
  }
}

void swift::serialization::diagnoseSerializedASTLoadFailureTransitive(
    ASTContext &Ctx, SourceLoc diagLoc, const serialization::Status status,
    ModuleFile *loadedModuleFile, Identifier ModuleName, bool forTestable) {
  switch (status) {
  case serialization::Status::Valid:
  case serialization::Status::FormatTooNew:
  case serialization::Status::FormatTooOld:
  case serialization::Status::NotInOSSA:
  case serialization::Status::RevisionIncompatible:
  case serialization::Status::ChannelIncompatible:
  case serialization::Status::Malformed:
  case serialization::Status::MalformedDocumentation:
  case serialization::Status::FailedToLoadBridgingHeader:
  case serialization::Status::NameMismatch:
  case serialization::Status::TargetIncompatible:
  case serialization::Status::TargetTooNew:
  case serialization::Status::SDKMismatch:
    llvm_unreachable("status not handled by "
        "diagnoseSerializedASTLoadFailureTransitive");

  case serialization::Status::MissingDependency: {
    // Figure out /which/ dependencies are missing.
    // FIXME: Dependencies should be de-duplicated at serialization time,
    // not now.
    llvm::StringSet<> duplicates;
    llvm::SmallVector<ModuleFile::Dependency, 4> missing;
    std::copy_if(
        loadedModuleFile->getDependencies().begin(),
        loadedModuleFile->getDependencies().end(), std::back_inserter(missing),
        [&duplicates, &loadedModuleFile, forTestable](
            const ModuleFile::Dependency &dependency) -> bool {
          if (dependency.isLoaded() || dependency.isHeader() ||
              loadedModuleFile->getTransitiveLoadingBehavior(dependency,
                                                             forTestable)
                != ModuleLoadingBehavior::Required) {
            return false;
          }
          return duplicates.insert(dependency.Core.RawPath).second;
        });

    // FIXME: only show module part of RawAccessPath
    assert(!missing.empty() && "unknown missing dependency?");
    if (missing.size() == 1) {
      Ctx.Diags.diagnose(diagLoc, diag::serialization_missing_single_dependency,
                         missing.front().Core.getPrettyPrintedPath());
    } else {
      llvm::SmallString<64> missingNames;
      missingNames += '\'';
      interleave(missing,
                 [&](const ModuleFile::Dependency &next) {
                   missingNames += next.Core.getPrettyPrintedPath();
                 },
                 [&] { missingNames += "', '"; });
      missingNames += '\'';

      Ctx.Diags.diagnose(diagLoc, diag::serialization_missing_dependencies,
                         missingNames);
    }

    if (Ctx.SearchPathOpts.getSDKPath().empty() &&
        llvm::Triple(llvm::sys::getProcessTriple()).isMacOSX()) {
      Ctx.Diags.diagnose(SourceLoc(), diag::sema_no_import_no_sdk);
      Ctx.Diags.diagnose(SourceLoc(), diag::sema_no_import_no_sdk_xcrun);
    }
    break;
  }

  case serialization::Status::CircularDependency: {
    auto circularDependencyIter = llvm::find_if(
        loadedModuleFile->getDependencies(),
        [](const ModuleFile::Dependency &next) {
          return next.isLoaded() &&
                 !(next.Import.has_value() &&
                   next.Import->importedModule->hasResolvedImports());
        });
    assert(circularDependencyIter !=
               loadedModuleFile->getDependencies().end() &&
           "circular dependency reported, but no module with unresolved "
           "imports found");

    // FIXME: We should include the path of the circularity as well, but that's
    // hard because we're discovering this /while/ resolving imports, which
    // means the problematic modules haven't been recorded yet.
    Ctx.Diags.diagnose(diagLoc, diag::serialization_circular_dependency,
                       circularDependencyIter->Core.getPrettyPrintedPath(),
                       ModuleName);
    break;
  }

  case serialization::Status::MissingUnderlyingModule: {
    Ctx.Diags.diagnose(diagLoc, diag::serialization_missing_underlying_module,
                       ModuleName);
    if (Ctx.SearchPathOpts.getSDKPath().empty() &&
        llvm::Triple(llvm::sys::getProcessTriple()).isMacOSX()) {
      Ctx.Diags.diagnose(SourceLoc(), diag::sema_no_import_no_sdk);
      Ctx.Diags.diagnose(SourceLoc(), diag::sema_no_import_no_sdk_xcrun);
    }
    break;
  }
  }
}

bool swift::extractCompilerFlagsFromInterface(
    StringRef interfacePath, StringRef buffer, llvm::StringSaver &ArgSaver,
    SmallVectorImpl<const char *> &SubArgs,
    std::optional<llvm::Triple> PreferredTarget) {
  SmallVector<StringRef, 1> FlagMatches;
  auto FlagRe = llvm::Regex("^// swift-module-flags:(.*)$", llvm::Regex::Newline);
  if (!FlagRe.match(buffer, &FlagMatches))
    return true;
  assert(FlagMatches.size() == 2);
  llvm::cl::TokenizeGNUCommandLine(FlagMatches[1], ArgSaver, SubArgs);

  // If the target triple parsed from the Swift interface file differs
  // only in subarchitecture from the compatible target triple, then
  // we have loaded a Swift interface from a different-but-compatible
  // architecture slice. Use the compatible subarchitecture.
  for (unsigned I = 1; I < SubArgs.size(); ++I) {
    if (strcmp(SubArgs[I - 1], "-target") != 0) {
      continue;
    }
    llvm::Triple target(SubArgs[I]);
    if (PreferredTarget &&
        target.getSubArch() != PreferredTarget->getSubArch() &&
        target.getArch() == PreferredTarget->getArch() &&
        target.getVendor() == PreferredTarget->getVendor() &&
        target.getOS() == PreferredTarget->getOS() &&
        target.getEnvironment() == PreferredTarget->getEnvironment())
      target.setArch(PreferredTarget->getArch(), PreferredTarget->getSubArch());
    SubArgs[I] = ArgSaver.save(target.str()).data();
  }

  SmallVector<StringRef, 1> IgnFlagMatches;
  // Cherry-pick supported options from the ignorable list.
  auto IgnFlagRe = llvm::Regex("^// swift-module-flags-ignorable:(.*)$",
                               llvm::Regex::Newline);
  auto hasIgnorableFlags = IgnFlagRe.match(buffer, &IgnFlagMatches);

  // Check for ignorable-private flags
  SmallVector<StringRef, 1> IgnPrivateFlagMatches;
  auto IgnPrivateFlagRe = llvm::Regex("^// swift-module-flags-ignorable-private:(.*)$",
                               llvm::Regex::Newline);
  auto hasIgnorablePrivateFlags = IgnPrivateFlagRe.match(buffer, &IgnPrivateFlagMatches);

  // It's OK the interface doesn't have the ignorable list (private or not), we just
  // ignore them all.
  if (!hasIgnorableFlags && !hasIgnorablePrivateFlags)
    return false;

  SmallVector<const char *, 8> IgnSubArgs;
  if (hasIgnorableFlags)
    llvm::cl::TokenizeGNUCommandLine(IgnFlagMatches[1], ArgSaver, IgnSubArgs);
  if (hasIgnorablePrivateFlags)
    llvm::cl::TokenizeGNUCommandLine(IgnPrivateFlagMatches[1], ArgSaver, IgnSubArgs);

  std::unique_ptr<llvm::opt::OptTable> table = swift::createSwiftOptTable();
  unsigned missingArgIdx = 0;
  unsigned missingArgCount = 0;
  auto parsedIgns = table->ParseArgs(IgnSubArgs, missingArgIdx, missingArgCount);
  for (auto parse: parsedIgns) {
    // Check if the option is a frontend option. This will filter out unknown
    // options and input-like options.
    if (!parse->getOption().hasFlag(options::FrontendOption))
      continue;
    auto spelling = ArgSaver.save(parse->getSpelling());
    auto &values = parse->getValues();
    if (spelling.endswith("=")) {
      // Handle the case like -tbd-install_name=Foo. This should be rare because
      // most equal-separated arguments are alias to the separate form.
      assert(values.size() == 1);
      SubArgs.push_back(ArgSaver.save((llvm::Twine(spelling) + values[0]).str()).data());
    } else {
      // Push the supported option and its value to the list.
      SubArgs.push_back(spelling.data());
      for (auto value: values)
        SubArgs.push_back(value);
    }
  }

  return false;
}

llvm::VersionTuple
swift::extractUserModuleVersionFromInterface(StringRef moduleInterfacePath) {
  llvm::VersionTuple result;
  // Read the interface file and extract its compiler arguments line
  if (auto file = llvm::MemoryBuffer::getFile(moduleInterfacePath)) {
    llvm::BumpPtrAllocator alloc;
    llvm::StringSaver argSaver(alloc);
    SmallVector<const char*, 8> args;
    (void)extractCompilerFlagsFromInterface(moduleInterfacePath,
                                            (*file)->getBuffer(), argSaver, args);
    for (unsigned I = 0, N = args.size(); I + 1 < N; I++) {
      // Check the version number specified via -user-module-version.
      StringRef current(args[I]), next(args[I + 1]);
      if (current == "-user-module-version") {
        // Sanitize versions that are too long
        while(next.count('.') > 3) {
          next = next.rsplit('.').first;
        }
        result.tryParse(next);
        break;
      }
    }
  }
  return result;
}

bool SerializedModuleLoaderBase::canImportModule(
    ImportPath::Module path, SourceLoc loc, ModuleVersionInfo *versionInfo,
    bool isTestableDependencyLookup) {
  // FIXME: Swift submodules?
  if (path.hasSubmodule())
    return false;

  // Look on disk.
  SmallString<256> moduleInterfaceSourcePath;
  std::unique_ptr<llvm::MemoryBuffer> moduleInputBuffer;
  bool isFramework = false;
  bool isSystemModule = false;

  auto mID = path[0];
  auto found = findModule(
      mID, /*moduleInterfacePath=*/nullptr, &moduleInterfaceSourcePath,
      &moduleInputBuffer,
      /*moduleDocBuffer=*/nullptr, /*moduleSourceInfoBuffer=*/nullptr,
      /*skipBuildingInterface=*/true, isTestableDependencyLookup,
      isFramework, isSystemModule);
  // If we cannot find the module, don't continue.
  if (!found)
    return false;

  if (!moduleInterfaceSourcePath.empty()) {
    // If we found interface and version is not requested, we're done.
    if (!versionInfo)
      return true;

    auto moduleVersion =
        extractUserModuleVersionFromInterface(moduleInterfaceSourcePath);

    // If version is requested and found in interface, return the version.
    // Otherwise fallback to binary module handling.
    if (!moduleVersion.empty()) {
      versionInfo->setVersion(moduleVersion,
                              ModuleVersionSourceKind::SwiftInterface);
      return true;
    }
  }

  if (moduleInputBuffer) {
    auto metaData = serialization::validateSerializedAST(
        moduleInputBuffer->getBuffer(), Ctx.SILOpts.EnableOSSAModules,
        Ctx.LangOpts.SDKName);

    // If we only found binary module, make sure that is valid.
    if (metaData.status != serialization::Status::Valid &&
        moduleInterfaceSourcePath.empty()) {
      // Emit warning if the canImport check location is known.
      if (loc.isValid())
        Ctx.Diags.diagnose(loc, diag::can_import_invalid_swiftmodule,
                           moduleInputBuffer->getBufferIdentifier());

      return false;
    }

    if (versionInfo)
      versionInfo->setVersion(metaData.userModuleVersion,
                              ModuleVersionSourceKind::SwiftBinaryModule);
  }

  if (versionInfo && !versionInfo->isValid()) {
    // If no version is found, set it to empty version.
    versionInfo->setVersion(llvm::VersionTuple(),
                            ModuleVersionSourceKind::SwiftBinaryModule);
  }

  return true;
}

bool MemoryBufferSerializedModuleLoader::canImportModule(
    ImportPath::Module path, SourceLoc loc, ModuleVersionInfo *versionInfo,
    bool isTestableDependencyLookup) {
  // FIXME: Swift submodules?
  if (path.hasSubmodule())
    return false;

  auto mID = path[0];
  auto mIt = MemoryBuffers.find(mID.Item.str());
  if (mIt == MemoryBuffers.end())
    return false;

  if (!versionInfo)
    return true;

  versionInfo->setVersion(mIt->second.userVersion,
                          ModuleVersionSourceKind::SwiftBinaryModule);
  return true;
}

ModuleDecl *
SerializedModuleLoaderBase::loadModule(SourceLoc importLoc,
                                       ImportPath::Module path,
                                       bool AllowMemoryCache) {
  // FIXME: Swift submodules?
  if (path.size() > 1)
    return nullptr;

  auto moduleID = path[0];
  bool isFramework = false;
  bool isSystemModule = false;

  llvm::SmallString<256> moduleInterfacePath;
  llvm::SmallString<256> moduleInterfaceSourcePath;
  std::unique_ptr<llvm::MemoryBuffer> moduleInputBuffer;
  std::unique_ptr<llvm::MemoryBuffer> moduleDocInputBuffer;
  std::unique_ptr<llvm::MemoryBuffer> moduleSourceInfoInputBuffer;

  // Look on disk.
  if (!findModule(moduleID, &moduleInterfacePath, &moduleInterfaceSourcePath,
                  &moduleInputBuffer, &moduleDocInputBuffer,
                  &moduleSourceInfoInputBuffer,
                  /*skipBuildingInterface=*/false,
                  /*isTestableDependencyLookup=*/false,
                  isFramework,
                  isSystemModule)) {
    return nullptr;
  }

  assert(moduleInputBuffer);

  auto M = ModuleDecl::create(moduleID.Item, Ctx);
  M->setIsSystemModule(isSystemModule);
  if (AllowMemoryCache)
    Ctx.addLoadedModule(M);
  SWIFT_DEFER { M->setHasResolvedImports(); };

  llvm::sys::path::native(moduleInterfacePath);
  auto *file =
      loadAST(*M, moduleID.Loc, moduleInterfacePath, moduleInterfaceSourcePath,
              std::move(moduleInputBuffer), std::move(moduleDocInputBuffer),
              std::move(moduleSourceInfoInputBuffer), isFramework);
  if (file) {
    M->addFile(*file);
  } else {
    M->setFailedToLoad();
  }

  if (dependencyTracker && file) {
    auto DepPath = file->getFilename();
    // Don't record cached artifacts as dependencies.
    if (!isCached(DepPath)) {
      if (M->hasIncrementalInfo()) {
        dependencyTracker->addIncrementalDependency(DepPath,
                                                    M->getFingerprint());
      } else {
        dependencyTracker->addDependency(DepPath, /*isSystem=*/false);
      }
    }
  }
  return M;
}

ModuleDecl *
MemoryBufferSerializedModuleLoader::loadModule(SourceLoc importLoc,
                                               ImportPath::Module path,
                                               bool AllowMemoryCache) {
  // FIXME: Swift submodules?
  if (path.size() > 1)
    return nullptr;

  auto moduleID = path[0];

  // See if we find it in the registered memory buffers.

  // FIXME: Right now this works only with access paths of length 1.
  // Once submodules are designed, this needs to support suffix
  // matching and a search path.
  auto bufIter = MemoryBuffers.find(moduleID.Item.str());
  if (bufIter == MemoryBuffers.end())
    return nullptr;

  bool isFramework = false;
  std::unique_ptr<llvm::MemoryBuffer> moduleInputBuffer;
  moduleInputBuffer = std::move(bufIter->second.buffer);
  MemoryBuffers.erase(bufIter);
  assert(moduleInputBuffer);

  auto *M = ModuleDecl::create(moduleID.Item, Ctx);
  SWIFT_DEFER { M->setHasResolvedImports(); };
  if (AllowMemoryCache)
    Ctx.addLoadedModule(M);

  auto *file = loadAST(*M, moduleID.Loc, /*moduleInterfacePath=*/"",
                       /*moduleInterfaceSourcePath=*/"",
                       std::move(moduleInputBuffer), {}, {}, isFramework);
  if (!file) {
    Ctx.removeLoadedModule(moduleID.Item);
    return nullptr;
  }

  // The MemoryBuffer loader is used by LLDB during debugging. Modules imported
  // from .swift_ast sections are never produced from textual interfaces. By
  // disabling resilience the debugger can directly access private members.
  if (BypassResilience)
    M->setBypassResilience();
  M->addFile(*file);
  return M;
}

void SerializedModuleLoaderBase::loadExtensions(NominalTypeDecl *nominal,
                                                unsigned previousGeneration) {
  for (auto &modulePair : LoadedModuleFiles) {
    if (modulePair.second <= previousGeneration)
      continue;
    modulePair.first->loadExtensions(nominal);
  }
}

void SerializedModuleLoaderBase::loadObjCMethods(
       NominalTypeDecl *typeDecl,
       ObjCSelector selector,
       bool isInstanceMethod,
       unsigned previousGeneration,
       llvm::TinyPtrVector<AbstractFunctionDecl *> &methods) {
  for (auto &modulePair : LoadedModuleFiles) {
    if (modulePair.second <= previousGeneration)
      continue;
    modulePair.first->loadObjCMethods(typeDecl, selector, isInstanceMethod,
                                      methods);
  }
}

void SerializedModuleLoaderBase::loadDerivativeFunctionConfigurations(
    AbstractFunctionDecl *originalAFD, unsigned int previousGeneration,
    llvm::SetVector<AutoDiffConfig> &results) {
  for (auto &modulePair : LoadedModuleFiles) {
    if (modulePair.second <= previousGeneration)
      continue;
    modulePair.first->loadDerivativeFunctionConfigurations(originalAFD,
                                                           results);
  }
}

std::error_code MemoryBufferSerializedModuleLoader::findModuleFilesInDirectory(
    ImportPath::Element ModuleID, const SerializedModuleBaseName &BaseName,
    SmallVectorImpl<char> *ModuleInterfacePath,
    SmallVectorImpl<char> *ModuleInterfaceSourcePath,
    std::unique_ptr<llvm::MemoryBuffer> *ModuleBuffer,
    std::unique_ptr<llvm::MemoryBuffer> *ModuleDocBuffer,
    std::unique_ptr<llvm::MemoryBuffer> *ModuleSourceInfoBuffer,
    bool skipBuildingInterface, bool IsFramework,
    bool isTestableDependencyLookup) {
  // This is a soft error instead of an llvm_unreachable because this API is
  // primarily used by LLDB which makes it more likely that unwitting changes to
  // the Swift compiler accidentally break the contract.
  assert(false && "not supported");
  return std::make_error_code(std::errc::not_supported);
}

bool MemoryBufferSerializedModuleLoader::maybeDiagnoseTargetMismatch(
    SourceLoc sourceLocation, StringRef moduleName,
    const SerializedModuleBaseName &absoluteBaseName) {
  return false;
}

void SerializedModuleLoaderBase::verifyAllModules() {
#ifndef NDEBUG
  for (const LoadedModulePair &loaded : LoadedModuleFiles)
    loaded.first->verify();
#endif
}

//-----------------------------------------------------------------------------
// SerializedASTFile implementation
//-----------------------------------------------------------------------------

void SerializedASTFile::getImportedModules(
    SmallVectorImpl<ImportedModule> &imports,
    ModuleDecl::ImportFilter filter) const {
  File.getImportedModules(imports, filter);
}

void SerializedASTFile::collectLinkLibrariesFromImports(
    ModuleDecl::LinkLibraryCallback callback) const {
  llvm::SmallVector<ImportedModule, 8> Imports;
  File.getImportedModules(Imports, {ModuleDecl::ImportFilterKind::Exported,
                                    ModuleDecl::ImportFilterKind::Default});

  for (auto Import : Imports)
    Import.importedModule->collectLinkLibraries(callback);
}

void SerializedASTFile::collectLinkLibraries(
    ModuleDecl::LinkLibraryCallback callback) const {
  if (isSIB()) {
    collectLinkLibrariesFromImports(callback);
  } else {
    File.collectLinkLibraries(callback);
  }
}

void SerializedASTFile::loadDependenciesForTestable(SourceLoc diagLoc) const {
  serialization::Status status =
    File.loadDependenciesForFileContext(this, diagLoc, /*forTestable=*/true);

  if (status != serialization::Status::Valid) {
    serialization::diagnoseSerializedASTLoadFailureTransitive(
        getASTContext(), diagLoc, status, &File,
        getParentModule()->getName(), /*forTestable*/true);
  }
}

bool SerializedASTFile::isSIB() const {
  return File.isSIB();
}

bool SerializedASTFile::hadLoadError() const {
  return File.hasError();
}

bool SerializedASTFile::isSystemModule() const {
  if (auto Mod = File.getUnderlyingModule()) {
    return Mod->isSystemModule();
  }
  return false;
}

void SerializedASTFile::lookupValue(DeclName name, NLKind lookupKind,
                                    OptionSet<ModuleLookupFlags> Flags,
                                    SmallVectorImpl<ValueDecl*> &results) const{
  File.lookupValue(name, results);
}

StringRef
SerializedASTFile::getFilenameForPrivateDecl(const Decl *decl) const {
  return File.FilenamesForPrivateValues.lookup(decl);
}

TypeDecl *SerializedASTFile::lookupLocalType(llvm::StringRef MangledName) const{
  return File.lookupLocalType(MangledName);
}

OpaqueTypeDecl *
SerializedASTFile::lookupOpaqueResultType(StringRef MangledName) {
  return File.lookupOpaqueResultType(MangledName);
}

TypeDecl *
SerializedASTFile::lookupNestedType(Identifier name,
                                    const NominalTypeDecl *parent) const {
  return File.lookupNestedType(name, parent);
}

void SerializedASTFile::lookupOperatorDirect(
    Identifier name, OperatorFixity fixity,
    TinyPtrVector<OperatorDecl *> &results) const {
  if (auto *op = File.lookupOperator(name, fixity))
    results.push_back(op);
}

void SerializedASTFile::lookupPrecedenceGroupDirect(
    Identifier name, TinyPtrVector<PrecedenceGroupDecl *> &results) const {
  if (auto *group = File.lookupPrecedenceGroup(name))
    results.push_back(group);
}

void SerializedASTFile::lookupVisibleDecls(ImportPath::Access accessPath,
                                           VisibleDeclConsumer &consumer,
                                           NLKind lookupKind) const {
  File.lookupVisibleDecls(accessPath, consumer, lookupKind);
}

void SerializedASTFile::lookupClassMembers(ImportPath::Access accessPath,
                                           VisibleDeclConsumer &consumer) const{
  File.lookupClassMembers(accessPath, consumer);
}

void
SerializedASTFile::lookupClassMember(ImportPath::Access accessPath,
                                     DeclName name,
                                     SmallVectorImpl<ValueDecl*> &decls) const {
  File.lookupClassMember(accessPath, name, decls);
}

void SerializedASTFile::lookupObjCMethods(
       ObjCSelector selector,
       SmallVectorImpl<AbstractFunctionDecl *> &results) const {
  File.lookupObjCMethods(selector, results);
}

std::optional<Fingerprint>
SerializedASTFile::loadFingerprint(const IterableDeclContext *IDC) const {
  return File.loadFingerprint(IDC);
}

void SerializedASTFile::lookupImportedSPIGroups(
                        const ModuleDecl *importedModule,
                        llvm::SmallSetVector<Identifier, 4> &spiGroups) const {
  auto M = getParentModule();
  auto &imports = M->getASTContext().getImportCache();
  for (auto &dep : File.Dependencies) {
    if (!dep.Import.has_value())
      continue;

    if (dep.Import->importedModule == importedModule ||
        (imports.isImportedBy(importedModule, dep.Import->importedModule) &&
         imports.isImportedByViaSwiftOnly(importedModule,
                                          dep.Import->importedModule))) {
      spiGroups.insert(dep.spiGroups.begin(), dep.spiGroups.end());
    }
  }
}

std::optional<CommentInfo>
SerializedASTFile::getCommentForDecl(const Decl *D) const {
  return File.getCommentForDecl(D);
}

bool SerializedASTFile::hasLoadedSwiftDoc() const {
  return File.hasLoadedSwiftDoc();
}

std::optional<ExternalSourceLocs::RawLocs>
SerializedASTFile::getExternalRawLocsForDecl(const Decl *D) const {
  return File.getExternalRawLocsForDecl(D);
}

std::optional<StringRef>
SerializedASTFile::getGroupNameForDecl(const Decl *D) const {
  return File.getGroupNameForDecl(D);
}

std::optional<StringRef>
SerializedASTFile::getSourceFileNameForDecl(const Decl *D) const {
  return File.getSourceFileNameForDecl(D);
}

std::optional<unsigned>
SerializedASTFile::getSourceOrderForDecl(const Decl *D) const {
  return File.getSourceOrderForDecl(D);
}

void SerializedASTFile::collectAllGroups(
    SmallVectorImpl<StringRef> &Names) const {
  File.collectAllGroups(Names);
}

std::optional<StringRef>
SerializedASTFile::getGroupNameByUSR(StringRef USR) const {
  return File.getGroupNameByUSR(USR);
}

void
SerializedASTFile::getTopLevelDecls(SmallVectorImpl<Decl*> &results) const {
  File.getTopLevelDecls(results);
}

void SerializedASTFile::getExportedPrespecializations(
    SmallVectorImpl<Decl *> &results) const {
  File.getExportedPrespecializations(results);
}
void SerializedASTFile::getTopLevelDeclsWhereAttributesMatch(
              SmallVectorImpl<Decl*> &results,
              llvm::function_ref<bool(DeclAttributes)> matchAttributes) const {
  File.getTopLevelDecls(results, matchAttributes);
}

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

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

void
SerializedASTFile::getLocalTypeDecls(SmallVectorImpl<TypeDecl*> &results) const{
  File.getLocalTypeDecls(results);
}

void
SerializedASTFile::getOpaqueReturnTypeDecls(
                              SmallVectorImpl<OpaqueTypeDecl*> &results) const {
  File.getOpaqueReturnTypeDecls(results);
}

void
SerializedASTFile::getDisplayDecls(SmallVectorImpl<Decl*> &results, bool recursive) const {
  File.getDisplayDecls(results, recursive);
}

StringRef SerializedASTFile::getFilename() const {
  return File.getModuleFilename();
}

StringRef SerializedASTFile::getLoadedFilename() const {
  return File.getModuleLoadedFilename();
}

StringRef SerializedASTFile::getSourceFilename() const {
  return File.getModuleSourceFilename();
}

StringRef SerializedASTFile::getTargetTriple() const {
  return File.getTargetTriple();
}

ModuleDecl *SerializedASTFile::getUnderlyingModuleIfOverlay() const {
  return File.getUnderlyingModule();
}

const clang::Module *SerializedASTFile::getUnderlyingClangModule() const {
  if (auto *UnderlyingModule = File.getUnderlyingModule())
    return UnderlyingModule->findUnderlyingClangModule();
  return nullptr;
}

Identifier
SerializedASTFile::getDiscriminatorForPrivateDecl(const Decl *D) const {
  Identifier discriminator = File.getDiscriminatorForPrivateDecl(D);
  assert(!discriminator.empty() && "no discriminator found for value");
  return discriminator;
}

void SerializedASTFile::collectBasicSourceFileInfo(
    llvm::function_ref<void(const BasicSourceFileInfo &)> callback) const {
  File.collectBasicSourceFileInfo(callback);
}

void SerializedASTFile::collectSerializedSearchPath(
    llvm::function_ref<void(StringRef)> callback) const {
  File.collectSerializedSearchPath(callback);
}