xref: /freebsd/contrib/llvm-project/clang/lib/Lex/HeaderSearch.cpp (revision 5ca8e32633c4ffbbcd6762e5888b6a4ba0708c6c)
1 //===- HeaderSearch.cpp - Resolve Header File Locations -------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements the DirectoryLookup and HeaderSearch interfaces.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/Lex/HeaderSearch.h"
14 #include "clang/Basic/Diagnostic.h"
15 #include "clang/Basic/FileManager.h"
16 #include "clang/Basic/IdentifierTable.h"
17 #include "clang/Basic/Module.h"
18 #include "clang/Basic/SourceManager.h"
19 #include "clang/Lex/DirectoryLookup.h"
20 #include "clang/Lex/ExternalPreprocessorSource.h"
21 #include "clang/Lex/HeaderMap.h"
22 #include "clang/Lex/HeaderSearchOptions.h"
23 #include "clang/Lex/LexDiagnostic.h"
24 #include "clang/Lex/ModuleMap.h"
25 #include "clang/Lex/Preprocessor.h"
26 #include "llvm/ADT/APInt.h"
27 #include "llvm/ADT/Hashing.h"
28 #include "llvm/ADT/SmallString.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/ADT/StringRef.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/Support/Allocator.h"
34 #include "llvm/Support/Capacity.h"
35 #include "llvm/Support/Errc.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/FileSystem.h"
38 #include "llvm/Support/Path.h"
39 #include "llvm/Support/VirtualFileSystem.h"
40 #include <algorithm>
41 #include <cassert>
42 #include <cstddef>
43 #include <cstdio>
44 #include <cstring>
45 #include <string>
46 #include <system_error>
47 #include <utility>
48 
49 using namespace clang;
50 
51 #define DEBUG_TYPE "file-search"
52 
53 ALWAYS_ENABLED_STATISTIC(NumIncluded, "Number of attempted #includes.");
54 ALWAYS_ENABLED_STATISTIC(
55     NumMultiIncludeFileOptzn,
56     "Number of #includes skipped due to the multi-include optimization.");
57 ALWAYS_ENABLED_STATISTIC(NumFrameworkLookups, "Number of framework lookups.");
58 ALWAYS_ENABLED_STATISTIC(NumSubFrameworkLookups,
59                          "Number of subframework lookups.");
60 
61 const IdentifierInfo *
62 HeaderFileInfo::getControllingMacro(ExternalPreprocessorSource *External) {
63   if (ControllingMacro) {
64     if (ControllingMacro->isOutOfDate()) {
65       assert(External && "We must have an external source if we have a "
66                          "controlling macro that is out of date.");
67       External->updateOutOfDateIdentifier(
68           *const_cast<IdentifierInfo *>(ControllingMacro));
69     }
70     return ControllingMacro;
71   }
72 
73   if (!ControllingMacroID || !External)
74     return nullptr;
75 
76   ControllingMacro = External->GetIdentifier(ControllingMacroID);
77   return ControllingMacro;
78 }
79 
80 ExternalHeaderFileInfoSource::~ExternalHeaderFileInfoSource() = default;
81 
82 HeaderSearch::HeaderSearch(std::shared_ptr<HeaderSearchOptions> HSOpts,
83                            SourceManager &SourceMgr, DiagnosticsEngine &Diags,
84                            const LangOptions &LangOpts,
85                            const TargetInfo *Target)
86     : HSOpts(std::move(HSOpts)), Diags(Diags),
87       FileMgr(SourceMgr.getFileManager()), FrameworkMap(64),
88       ModMap(SourceMgr, Diags, LangOpts, Target, *this) {}
89 
90 void HeaderSearch::PrintStats() {
91   llvm::errs() << "\n*** HeaderSearch Stats:\n"
92                << FileInfo.size() << " files tracked.\n";
93   unsigned NumOnceOnlyFiles = 0;
94   for (unsigned i = 0, e = FileInfo.size(); i != e; ++i)
95     NumOnceOnlyFiles += (FileInfo[i].isPragmaOnce || FileInfo[i].isImport);
96   llvm::errs() << "  " << NumOnceOnlyFiles << " #import/#pragma once files.\n";
97 
98   llvm::errs() << "  " << NumIncluded << " #include/#include_next/#import.\n"
99                << "    " << NumMultiIncludeFileOptzn
100                << " #includes skipped due to the multi-include optimization.\n";
101 
102   llvm::errs() << NumFrameworkLookups << " framework lookups.\n"
103                << NumSubFrameworkLookups << " subframework lookups.\n";
104 }
105 
106 void HeaderSearch::SetSearchPaths(
107     std::vector<DirectoryLookup> dirs, unsigned int angledDirIdx,
108     unsigned int systemDirIdx, bool noCurDirSearch,
109     llvm::DenseMap<unsigned int, unsigned int> searchDirToHSEntry) {
110   assert(angledDirIdx <= systemDirIdx && systemDirIdx <= dirs.size() &&
111          "Directory indices are unordered");
112   SearchDirs = std::move(dirs);
113   SearchDirsUsage.assign(SearchDirs.size(), false);
114   AngledDirIdx = angledDirIdx;
115   SystemDirIdx = systemDirIdx;
116   NoCurDirSearch = noCurDirSearch;
117   SearchDirToHSEntry = std::move(searchDirToHSEntry);
118   //LookupFileCache.clear();
119   indexInitialHeaderMaps();
120 }
121 
122 void HeaderSearch::AddSearchPath(const DirectoryLookup &dir, bool isAngled) {
123   unsigned idx = isAngled ? SystemDirIdx : AngledDirIdx;
124   SearchDirs.insert(SearchDirs.begin() + idx, dir);
125   SearchDirsUsage.insert(SearchDirsUsage.begin() + idx, false);
126   if (!isAngled)
127     AngledDirIdx++;
128   SystemDirIdx++;
129 }
130 
131 std::vector<bool> HeaderSearch::computeUserEntryUsage() const {
132   std::vector<bool> UserEntryUsage(HSOpts->UserEntries.size());
133   for (unsigned I = 0, E = SearchDirsUsage.size(); I < E; ++I) {
134     // Check whether this DirectoryLookup has been successfully used.
135     if (SearchDirsUsage[I]) {
136       auto UserEntryIdxIt = SearchDirToHSEntry.find(I);
137       // Check whether this DirectoryLookup maps to a HeaderSearch::UserEntry.
138       if (UserEntryIdxIt != SearchDirToHSEntry.end())
139         UserEntryUsage[UserEntryIdxIt->second] = true;
140     }
141   }
142   return UserEntryUsage;
143 }
144 
145 /// CreateHeaderMap - This method returns a HeaderMap for the specified
146 /// FileEntry, uniquing them through the 'HeaderMaps' datastructure.
147 const HeaderMap *HeaderSearch::CreateHeaderMap(const FileEntry *FE) {
148   // We expect the number of headermaps to be small, and almost always empty.
149   // If it ever grows, use of a linear search should be re-evaluated.
150   if (!HeaderMaps.empty()) {
151     for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
152       // Pointer equality comparison of FileEntries works because they are
153       // already uniqued by inode.
154       if (HeaderMaps[i].first == FE)
155         return HeaderMaps[i].second.get();
156   }
157 
158   if (std::unique_ptr<HeaderMap> HM = HeaderMap::Create(FE, FileMgr)) {
159     HeaderMaps.emplace_back(FE, std::move(HM));
160     return HeaderMaps.back().second.get();
161   }
162 
163   return nullptr;
164 }
165 
166 /// Get filenames for all registered header maps.
167 void HeaderSearch::getHeaderMapFileNames(
168     SmallVectorImpl<std::string> &Names) const {
169   for (auto &HM : HeaderMaps)
170     Names.push_back(std::string(HM.first->getName()));
171 }
172 
173 std::string HeaderSearch::getCachedModuleFileName(Module *Module) {
174   OptionalFileEntryRef ModuleMap =
175       getModuleMap().getModuleMapFileForUniquing(Module);
176   // The ModuleMap maybe a nullptr, when we load a cached C++ module without
177   // *.modulemap file. In this case, just return an empty string.
178   if (!ModuleMap)
179     return {};
180   return getCachedModuleFileName(Module->Name, ModuleMap->getName());
181 }
182 
183 std::string HeaderSearch::getPrebuiltModuleFileName(StringRef ModuleName,
184                                                     bool FileMapOnly) {
185   // First check the module name to pcm file map.
186   auto i(HSOpts->PrebuiltModuleFiles.find(ModuleName));
187   if (i != HSOpts->PrebuiltModuleFiles.end())
188     return i->second;
189 
190   if (FileMapOnly || HSOpts->PrebuiltModulePaths.empty())
191     return {};
192 
193   // Then go through each prebuilt module directory and try to find the pcm
194   // file.
195   for (const std::string &Dir : HSOpts->PrebuiltModulePaths) {
196     SmallString<256> Result(Dir);
197     llvm::sys::fs::make_absolute(Result);
198     if (ModuleName.contains(':'))
199       // The separator of C++20 modules partitions (':') is not good for file
200       // systems, here clang and gcc choose '-' by default since it is not a
201       // valid character of C++ indentifiers. So we could avoid conflicts.
202       llvm::sys::path::append(Result, ModuleName.split(':').first + "-" +
203                                           ModuleName.split(':').second +
204                                           ".pcm");
205     else
206       llvm::sys::path::append(Result, ModuleName + ".pcm");
207     if (getFileMgr().getFile(Result.str()))
208       return std::string(Result);
209   }
210 
211   return {};
212 }
213 
214 std::string HeaderSearch::getPrebuiltImplicitModuleFileName(Module *Module) {
215   OptionalFileEntryRef ModuleMap =
216       getModuleMap().getModuleMapFileForUniquing(Module);
217   StringRef ModuleName = Module->Name;
218   StringRef ModuleMapPath = ModuleMap->getName();
219   StringRef ModuleCacheHash = HSOpts->DisableModuleHash ? "" : getModuleHash();
220   for (const std::string &Dir : HSOpts->PrebuiltModulePaths) {
221     SmallString<256> CachePath(Dir);
222     llvm::sys::fs::make_absolute(CachePath);
223     llvm::sys::path::append(CachePath, ModuleCacheHash);
224     std::string FileName =
225         getCachedModuleFileNameImpl(ModuleName, ModuleMapPath, CachePath);
226     if (!FileName.empty() && getFileMgr().getFile(FileName))
227       return FileName;
228   }
229   return {};
230 }
231 
232 std::string HeaderSearch::getCachedModuleFileName(StringRef ModuleName,
233                                                   StringRef ModuleMapPath) {
234   return getCachedModuleFileNameImpl(ModuleName, ModuleMapPath,
235                                      getModuleCachePath());
236 }
237 
238 std::string HeaderSearch::getCachedModuleFileNameImpl(StringRef ModuleName,
239                                                       StringRef ModuleMapPath,
240                                                       StringRef CachePath) {
241   // If we don't have a module cache path or aren't supposed to use one, we
242   // can't do anything.
243   if (CachePath.empty())
244     return {};
245 
246   SmallString<256> Result(CachePath);
247   llvm::sys::fs::make_absolute(Result);
248 
249   if (HSOpts->DisableModuleHash) {
250     llvm::sys::path::append(Result, ModuleName + ".pcm");
251   } else {
252     // Construct the name <ModuleName>-<hash of ModuleMapPath>.pcm which should
253     // ideally be globally unique to this particular module. Name collisions
254     // in the hash are safe (because any translation unit can only import one
255     // module with each name), but result in a loss of caching.
256     //
257     // To avoid false-negatives, we form as canonical a path as we can, and map
258     // to lower-case in case we're on a case-insensitive file system.
259     SmallString<128> CanonicalPath(ModuleMapPath);
260     if (getModuleMap().canonicalizeModuleMapPath(CanonicalPath))
261       return {};
262 
263     llvm::hash_code Hash = llvm::hash_combine(CanonicalPath.str().lower());
264 
265     SmallString<128> HashStr;
266     llvm::APInt(64, size_t(Hash)).toStringUnsigned(HashStr, /*Radix*/36);
267     llvm::sys::path::append(Result, ModuleName + "-" + HashStr + ".pcm");
268   }
269   return Result.str().str();
270 }
271 
272 Module *HeaderSearch::lookupModule(StringRef ModuleName,
273                                    SourceLocation ImportLoc, bool AllowSearch,
274                                    bool AllowExtraModuleMapSearch) {
275   // Look in the module map to determine if there is a module by this name.
276   Module *Module = ModMap.findModule(ModuleName);
277   if (Module || !AllowSearch || !HSOpts->ImplicitModuleMaps)
278     return Module;
279 
280   StringRef SearchName = ModuleName;
281   Module = lookupModule(ModuleName, SearchName, ImportLoc,
282                         AllowExtraModuleMapSearch);
283 
284   // The facility for "private modules" -- adjacent, optional module maps named
285   // module.private.modulemap that are supposed to define private submodules --
286   // may have different flavors of names: FooPrivate, Foo_Private and Foo.Private.
287   //
288   // Foo.Private is now deprecated in favor of Foo_Private. Users of FooPrivate
289   // should also rename to Foo_Private. Representing private as submodules
290   // could force building unwanted dependencies into the parent module and cause
291   // dependency cycles.
292   if (!Module && SearchName.consume_back("_Private"))
293     Module = lookupModule(ModuleName, SearchName, ImportLoc,
294                           AllowExtraModuleMapSearch);
295   if (!Module && SearchName.consume_back("Private"))
296     Module = lookupModule(ModuleName, SearchName, ImportLoc,
297                           AllowExtraModuleMapSearch);
298   return Module;
299 }
300 
301 Module *HeaderSearch::lookupModule(StringRef ModuleName, StringRef SearchName,
302                                    SourceLocation ImportLoc,
303                                    bool AllowExtraModuleMapSearch) {
304   Module *Module = nullptr;
305 
306   // Look through the various header search paths to load any available module
307   // maps, searching for a module map that describes this module.
308   for (DirectoryLookup &Dir : search_dir_range()) {
309     if (Dir.isFramework()) {
310       // Search for or infer a module map for a framework. Here we use
311       // SearchName rather than ModuleName, to permit finding private modules
312       // named FooPrivate in buggy frameworks named Foo.
313       SmallString<128> FrameworkDirName;
314       FrameworkDirName += Dir.getFrameworkDirRef()->getName();
315       llvm::sys::path::append(FrameworkDirName, SearchName + ".framework");
316       if (auto FrameworkDir =
317               FileMgr.getOptionalDirectoryRef(FrameworkDirName)) {
318         bool IsSystem = Dir.getDirCharacteristic() != SrcMgr::C_User;
319         Module = loadFrameworkModule(ModuleName, *FrameworkDir, IsSystem);
320         if (Module)
321           break;
322       }
323     }
324 
325     // FIXME: Figure out how header maps and module maps will work together.
326 
327     // Only deal with normal search directories.
328     if (!Dir.isNormalDir())
329       continue;
330 
331     bool IsSystem = Dir.isSystemHeaderDirectory();
332     // Only returns std::nullopt if not a normal directory, which we just
333     // checked
334     DirectoryEntryRef NormalDir = *Dir.getDirRef();
335     // Search for a module map file in this directory.
336     if (loadModuleMapFile(NormalDir, IsSystem,
337                           /*IsFramework*/false) == LMM_NewlyLoaded) {
338       // We just loaded a module map file; check whether the module is
339       // available now.
340       Module = ModMap.findModule(ModuleName);
341       if (Module)
342         break;
343     }
344 
345     // Search for a module map in a subdirectory with the same name as the
346     // module.
347     SmallString<128> NestedModuleMapDirName;
348     NestedModuleMapDirName = Dir.getDirRef()->getName();
349     llvm::sys::path::append(NestedModuleMapDirName, ModuleName);
350     if (loadModuleMapFile(NestedModuleMapDirName, IsSystem,
351                           /*IsFramework*/false) == LMM_NewlyLoaded){
352       // If we just loaded a module map file, look for the module again.
353       Module = ModMap.findModule(ModuleName);
354       if (Module)
355         break;
356     }
357 
358     // If we've already performed the exhaustive search for module maps in this
359     // search directory, don't do it again.
360     if (Dir.haveSearchedAllModuleMaps())
361       continue;
362 
363     // Load all module maps in the immediate subdirectories of this search
364     // directory if ModuleName was from @import.
365     if (AllowExtraModuleMapSearch)
366       loadSubdirectoryModuleMaps(Dir);
367 
368     // Look again for the module.
369     Module = ModMap.findModule(ModuleName);
370     if (Module)
371       break;
372   }
373 
374   return Module;
375 }
376 
377 void HeaderSearch::indexInitialHeaderMaps() {
378   llvm::StringMap<unsigned, llvm::BumpPtrAllocator> Index(SearchDirs.size());
379 
380   // Iterate over all filename keys and associate them with the index i.
381   for (unsigned i = 0; i != SearchDirs.size(); ++i) {
382     auto &Dir = SearchDirs[i];
383 
384     // We're concerned with only the initial contiguous run of header
385     // maps within SearchDirs, which can be 99% of SearchDirs when
386     // SearchDirs.size() is ~10000.
387     if (!Dir.isHeaderMap()) {
388       SearchDirHeaderMapIndex = std::move(Index);
389       FirstNonHeaderMapSearchDirIdx = i;
390       break;
391     }
392 
393     // Give earlier keys precedence over identical later keys.
394     auto Callback = [&](StringRef Filename) {
395       Index.try_emplace(Filename.lower(), i);
396     };
397     Dir.getHeaderMap()->forEachKey(Callback);
398   }
399 }
400 
401 //===----------------------------------------------------------------------===//
402 // File lookup within a DirectoryLookup scope
403 //===----------------------------------------------------------------------===//
404 
405 /// getName - Return the directory or filename corresponding to this lookup
406 /// object.
407 StringRef DirectoryLookup::getName() const {
408   if (isNormalDir())
409     return getDirRef()->getName();
410   if (isFramework())
411     return getFrameworkDirRef()->getName();
412   assert(isHeaderMap() && "Unknown DirectoryLookup");
413   return getHeaderMap()->getFileName();
414 }
415 
416 OptionalFileEntryRef HeaderSearch::getFileAndSuggestModule(
417     StringRef FileName, SourceLocation IncludeLoc, const DirectoryEntry *Dir,
418     bool IsSystemHeaderDir, Module *RequestingModule,
419     ModuleMap::KnownHeader *SuggestedModule, bool OpenFile /*=true*/,
420     bool CacheFailures /*=true*/) {
421   // If we have a module map that might map this header, load it and
422   // check whether we'll have a suggestion for a module.
423   auto File = getFileMgr().getFileRef(FileName, OpenFile, CacheFailures);
424   if (!File) {
425     // For rare, surprising errors (e.g. "out of file handles"), diag the EC
426     // message.
427     std::error_code EC = llvm::errorToErrorCode(File.takeError());
428     if (EC != llvm::errc::no_such_file_or_directory &&
429         EC != llvm::errc::invalid_argument &&
430         EC != llvm::errc::is_a_directory && EC != llvm::errc::not_a_directory) {
431       Diags.Report(IncludeLoc, diag::err_cannot_open_file)
432           << FileName << EC.message();
433     }
434     return std::nullopt;
435   }
436 
437   // If there is a module that corresponds to this header, suggest it.
438   if (!findUsableModuleForHeader(
439           *File, Dir ? Dir : File->getFileEntry().getDir(), RequestingModule,
440           SuggestedModule, IsSystemHeaderDir))
441     return std::nullopt;
442 
443   return *File;
444 }
445 
446 /// LookupFile - Lookup the specified file in this search path, returning it
447 /// if it exists or returning null if not.
448 OptionalFileEntryRef DirectoryLookup::LookupFile(
449     StringRef &Filename, HeaderSearch &HS, SourceLocation IncludeLoc,
450     SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
451     Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule,
452     bool &InUserSpecifiedSystemFramework, bool &IsFrameworkFound,
453     bool &IsInHeaderMap, SmallVectorImpl<char> &MappedName,
454     bool OpenFile) const {
455   InUserSpecifiedSystemFramework = false;
456   IsInHeaderMap = false;
457   MappedName.clear();
458 
459   SmallString<1024> TmpDir;
460   if (isNormalDir()) {
461     // Concatenate the requested file onto the directory.
462     TmpDir = getDirRef()->getName();
463     llvm::sys::path::append(TmpDir, Filename);
464     if (SearchPath) {
465       StringRef SearchPathRef(getDirRef()->getName());
466       SearchPath->clear();
467       SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
468     }
469     if (RelativePath) {
470       RelativePath->clear();
471       RelativePath->append(Filename.begin(), Filename.end());
472     }
473 
474     return HS.getFileAndSuggestModule(
475         TmpDir, IncludeLoc, getDir(), isSystemHeaderDirectory(),
476         RequestingModule, SuggestedModule, OpenFile);
477   }
478 
479   if (isFramework())
480     return DoFrameworkLookup(Filename, HS, SearchPath, RelativePath,
481                              RequestingModule, SuggestedModule,
482                              InUserSpecifiedSystemFramework, IsFrameworkFound);
483 
484   assert(isHeaderMap() && "Unknown directory lookup");
485   const HeaderMap *HM = getHeaderMap();
486   SmallString<1024> Path;
487   StringRef Dest = HM->lookupFilename(Filename, Path);
488   if (Dest.empty())
489     return std::nullopt;
490 
491   IsInHeaderMap = true;
492 
493   auto FixupSearchPathAndFindUsableModule =
494       [&](FileEntryRef File) -> OptionalFileEntryRef {
495     if (SearchPath) {
496       StringRef SearchPathRef(getName());
497       SearchPath->clear();
498       SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
499     }
500     if (RelativePath) {
501       RelativePath->clear();
502       RelativePath->append(Filename.begin(), Filename.end());
503     }
504     if (!HS.findUsableModuleForHeader(File, File.getFileEntry().getDir(),
505                                       RequestingModule, SuggestedModule,
506                                       isSystemHeaderDirectory())) {
507       return std::nullopt;
508     }
509     return File;
510   };
511 
512   // Check if the headermap maps the filename to a framework include
513   // ("Foo.h" -> "Foo/Foo.h"), in which case continue header lookup using the
514   // framework include.
515   if (llvm::sys::path::is_relative(Dest)) {
516     MappedName.append(Dest.begin(), Dest.end());
517     Filename = StringRef(MappedName.begin(), MappedName.size());
518     Dest = HM->lookupFilename(Filename, Path);
519   }
520 
521   if (auto Res = HS.getFileMgr().getOptionalFileRef(Dest, OpenFile)) {
522     return FixupSearchPathAndFindUsableModule(*Res);
523   }
524 
525   // Header maps need to be marked as used whenever the filename matches.
526   // The case where the target file **exists** is handled by callee of this
527   // function as part of the regular logic that applies to include search paths.
528   // The case where the target file **does not exist** is handled here:
529   HS.noteLookupUsage(HS.searchDirIdx(*this), IncludeLoc);
530   return std::nullopt;
531 }
532 
533 /// Given a framework directory, find the top-most framework directory.
534 ///
535 /// \param FileMgr The file manager to use for directory lookups.
536 /// \param DirName The name of the framework directory.
537 /// \param SubmodulePath Will be populated with the submodule path from the
538 /// returned top-level module to the originally named framework.
539 static OptionalDirectoryEntryRef
540 getTopFrameworkDir(FileManager &FileMgr, StringRef DirName,
541                    SmallVectorImpl<std::string> &SubmodulePath) {
542   assert(llvm::sys::path::extension(DirName) == ".framework" &&
543          "Not a framework directory");
544 
545   // Note: as an egregious but useful hack we use the real path here, because
546   // frameworks moving between top-level frameworks to embedded frameworks tend
547   // to be symlinked, and we base the logical structure of modules on the
548   // physical layout. In particular, we need to deal with crazy includes like
549   //
550   //   #include <Foo/Frameworks/Bar.framework/Headers/Wibble.h>
551   //
552   // where 'Bar' used to be embedded in 'Foo', is now a top-level framework
553   // which one should access with, e.g.,
554   //
555   //   #include <Bar/Wibble.h>
556   //
557   // Similar issues occur when a top-level framework has moved into an
558   // embedded framework.
559   auto TopFrameworkDir = FileMgr.getOptionalDirectoryRef(DirName);
560 
561   if (TopFrameworkDir)
562     DirName = FileMgr.getCanonicalName(*TopFrameworkDir);
563   do {
564     // Get the parent directory name.
565     DirName = llvm::sys::path::parent_path(DirName);
566     if (DirName.empty())
567       break;
568 
569     // Determine whether this directory exists.
570     auto Dir = FileMgr.getOptionalDirectoryRef(DirName);
571     if (!Dir)
572       break;
573 
574     // If this is a framework directory, then we're a subframework of this
575     // framework.
576     if (llvm::sys::path::extension(DirName) == ".framework") {
577       SubmodulePath.push_back(std::string(llvm::sys::path::stem(DirName)));
578       TopFrameworkDir = *Dir;
579     }
580   } while (true);
581 
582   return TopFrameworkDir;
583 }
584 
585 static bool needModuleLookup(Module *RequestingModule,
586                              bool HasSuggestedModule) {
587   return HasSuggestedModule ||
588          (RequestingModule && RequestingModule->NoUndeclaredIncludes);
589 }
590 
591 /// DoFrameworkLookup - Do a lookup of the specified file in the current
592 /// DirectoryLookup, which is a framework directory.
593 OptionalFileEntryRef DirectoryLookup::DoFrameworkLookup(
594     StringRef Filename, HeaderSearch &HS, SmallVectorImpl<char> *SearchPath,
595     SmallVectorImpl<char> *RelativePath, Module *RequestingModule,
596     ModuleMap::KnownHeader *SuggestedModule,
597     bool &InUserSpecifiedSystemFramework, bool &IsFrameworkFound) const {
598   FileManager &FileMgr = HS.getFileMgr();
599 
600   // Framework names must have a '/' in the filename.
601   size_t SlashPos = Filename.find('/');
602   if (SlashPos == StringRef::npos)
603     return std::nullopt;
604 
605   // Find out if this is the home for the specified framework, by checking
606   // HeaderSearch.  Possible answers are yes/no and unknown.
607   FrameworkCacheEntry &CacheEntry =
608     HS.LookupFrameworkCache(Filename.substr(0, SlashPos));
609 
610   // If it is known and in some other directory, fail.
611   if (CacheEntry.Directory && CacheEntry.Directory != getFrameworkDirRef())
612     return std::nullopt;
613 
614   // Otherwise, construct the path to this framework dir.
615 
616   // FrameworkName = "/System/Library/Frameworks/"
617   SmallString<1024> FrameworkName;
618   FrameworkName += getFrameworkDirRef()->getName();
619   if (FrameworkName.empty() || FrameworkName.back() != '/')
620     FrameworkName.push_back('/');
621 
622   // FrameworkName = "/System/Library/Frameworks/Cocoa"
623   StringRef ModuleName(Filename.begin(), SlashPos);
624   FrameworkName += ModuleName;
625 
626   // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/"
627   FrameworkName += ".framework/";
628 
629   // If the cache entry was unresolved, populate it now.
630   if (!CacheEntry.Directory) {
631     ++NumFrameworkLookups;
632 
633     // If the framework dir doesn't exist, we fail.
634     auto Dir = FileMgr.getDirectory(FrameworkName);
635     if (!Dir)
636       return std::nullopt;
637 
638     // Otherwise, if it does, remember that this is the right direntry for this
639     // framework.
640     CacheEntry.Directory = getFrameworkDirRef();
641 
642     // If this is a user search directory, check if the framework has been
643     // user-specified as a system framework.
644     if (getDirCharacteristic() == SrcMgr::C_User) {
645       SmallString<1024> SystemFrameworkMarker(FrameworkName);
646       SystemFrameworkMarker += ".system_framework";
647       if (llvm::sys::fs::exists(SystemFrameworkMarker)) {
648         CacheEntry.IsUserSpecifiedSystemFramework = true;
649       }
650     }
651   }
652 
653   // Set out flags.
654   InUserSpecifiedSystemFramework = CacheEntry.IsUserSpecifiedSystemFramework;
655   IsFrameworkFound = CacheEntry.Directory.has_value();
656 
657   if (RelativePath) {
658     RelativePath->clear();
659     RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
660   }
661 
662   // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"
663   unsigned OrigSize = FrameworkName.size();
664 
665   FrameworkName += "Headers/";
666 
667   if (SearchPath) {
668     SearchPath->clear();
669     // Without trailing '/'.
670     SearchPath->append(FrameworkName.begin(), FrameworkName.end()-1);
671   }
672 
673   FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end());
674 
675   auto File =
676       FileMgr.getOptionalFileRef(FrameworkName, /*OpenFile=*/!SuggestedModule);
677   if (!File) {
678     // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"
679     const char *Private = "Private";
680     FrameworkName.insert(FrameworkName.begin()+OrigSize, Private,
681                          Private+strlen(Private));
682     if (SearchPath)
683       SearchPath->insert(SearchPath->begin()+OrigSize, Private,
684                          Private+strlen(Private));
685 
686     File = FileMgr.getOptionalFileRef(FrameworkName,
687                                       /*OpenFile=*/!SuggestedModule);
688   }
689 
690   // If we found the header and are allowed to suggest a module, do so now.
691   if (File && needModuleLookup(RequestingModule, SuggestedModule)) {
692     // Find the framework in which this header occurs.
693     StringRef FrameworkPath = File->getDir().getName();
694     bool FoundFramework = false;
695     do {
696       // Determine whether this directory exists.
697       auto Dir = FileMgr.getDirectory(FrameworkPath);
698       if (!Dir)
699         break;
700 
701       // If this is a framework directory, then we're a subframework of this
702       // framework.
703       if (llvm::sys::path::extension(FrameworkPath) == ".framework") {
704         FoundFramework = true;
705         break;
706       }
707 
708       // Get the parent directory name.
709       FrameworkPath = llvm::sys::path::parent_path(FrameworkPath);
710       if (FrameworkPath.empty())
711         break;
712     } while (true);
713 
714     bool IsSystem = getDirCharacteristic() != SrcMgr::C_User;
715     if (FoundFramework) {
716       if (!HS.findUsableModuleForFrameworkHeader(*File, FrameworkPath,
717                                                  RequestingModule,
718                                                  SuggestedModule, IsSystem))
719         return std::nullopt;
720     } else {
721       if (!HS.findUsableModuleForHeader(*File, getDir(), RequestingModule,
722                                         SuggestedModule, IsSystem))
723         return std::nullopt;
724     }
725   }
726   if (File)
727     return *File;
728   return std::nullopt;
729 }
730 
731 void HeaderSearch::cacheLookupSuccess(LookupFileCacheInfo &CacheLookup,
732                                       ConstSearchDirIterator HitIt,
733                                       SourceLocation Loc) {
734   CacheLookup.HitIt = HitIt;
735   noteLookupUsage(HitIt.Idx, Loc);
736 }
737 
738 void HeaderSearch::noteLookupUsage(unsigned HitIdx, SourceLocation Loc) {
739   SearchDirsUsage[HitIdx] = true;
740 
741   auto UserEntryIdxIt = SearchDirToHSEntry.find(HitIdx);
742   if (UserEntryIdxIt != SearchDirToHSEntry.end())
743     Diags.Report(Loc, diag::remark_pp_search_path_usage)
744         << HSOpts->UserEntries[UserEntryIdxIt->second].Path;
745 }
746 
747 void HeaderSearch::setTarget(const TargetInfo &Target) {
748   ModMap.setTarget(Target);
749 }
750 
751 //===----------------------------------------------------------------------===//
752 // Header File Location.
753 //===----------------------------------------------------------------------===//
754 
755 /// Return true with a diagnostic if the file that MSVC would have found
756 /// fails to match the one that Clang would have found with MSVC header search
757 /// disabled.
758 static bool checkMSVCHeaderSearch(DiagnosticsEngine &Diags,
759                                   const FileEntry *MSFE, const FileEntry *FE,
760                                   SourceLocation IncludeLoc) {
761   if (MSFE && FE != MSFE) {
762     Diags.Report(IncludeLoc, diag::ext_pp_include_search_ms) << MSFE->getName();
763     return true;
764   }
765   return false;
766 }
767 
768 static const char *copyString(StringRef Str, llvm::BumpPtrAllocator &Alloc) {
769   assert(!Str.empty());
770   char *CopyStr = Alloc.Allocate<char>(Str.size()+1);
771   std::copy(Str.begin(), Str.end(), CopyStr);
772   CopyStr[Str.size()] = '\0';
773   return CopyStr;
774 }
775 
776 static bool isFrameworkStylePath(StringRef Path, bool &IsPrivateHeader,
777                                  SmallVectorImpl<char> &FrameworkName,
778                                  SmallVectorImpl<char> &IncludeSpelling) {
779   using namespace llvm::sys;
780   path::const_iterator I = path::begin(Path);
781   path::const_iterator E = path::end(Path);
782   IsPrivateHeader = false;
783 
784   // Detect different types of framework style paths:
785   //
786   //   ...Foo.framework/{Headers,PrivateHeaders}
787   //   ...Foo.framework/Versions/{A,Current}/{Headers,PrivateHeaders}
788   //   ...Foo.framework/Frameworks/Nested.framework/{Headers,PrivateHeaders}
789   //   ...<other variations with 'Versions' like in the above path>
790   //
791   // and some other variations among these lines.
792   int FoundComp = 0;
793   while (I != E) {
794     if (*I == "Headers") {
795       ++FoundComp;
796     } else if (*I == "PrivateHeaders") {
797       ++FoundComp;
798       IsPrivateHeader = true;
799     } else if (I->endswith(".framework")) {
800       StringRef Name = I->drop_back(10); // Drop .framework
801       // Need to reset the strings and counter to support nested frameworks.
802       FrameworkName.clear();
803       FrameworkName.append(Name.begin(), Name.end());
804       IncludeSpelling.clear();
805       IncludeSpelling.append(Name.begin(), Name.end());
806       FoundComp = 1;
807     } else if (FoundComp >= 2) {
808       IncludeSpelling.push_back('/');
809       IncludeSpelling.append(I->begin(), I->end());
810     }
811     ++I;
812   }
813 
814   return !FrameworkName.empty() && FoundComp >= 2;
815 }
816 
817 static void
818 diagnoseFrameworkInclude(DiagnosticsEngine &Diags, SourceLocation IncludeLoc,
819                          StringRef Includer, StringRef IncludeFilename,
820                          const FileEntry *IncludeFE, bool isAngled = false,
821                          bool FoundByHeaderMap = false) {
822   bool IsIncluderPrivateHeader = false;
823   SmallString<128> FromFramework, ToFramework;
824   SmallString<128> FromIncludeSpelling, ToIncludeSpelling;
825   if (!isFrameworkStylePath(Includer, IsIncluderPrivateHeader, FromFramework,
826                             FromIncludeSpelling))
827     return;
828   bool IsIncludeePrivateHeader = false;
829   bool IsIncludeeInFramework =
830       isFrameworkStylePath(IncludeFE->getName(), IsIncludeePrivateHeader,
831                            ToFramework, ToIncludeSpelling);
832 
833   if (!isAngled && !FoundByHeaderMap) {
834     SmallString<128> NewInclude("<");
835     if (IsIncludeeInFramework) {
836       NewInclude += ToIncludeSpelling;
837       NewInclude += ">";
838     } else {
839       NewInclude += IncludeFilename;
840       NewInclude += ">";
841     }
842     Diags.Report(IncludeLoc, diag::warn_quoted_include_in_framework_header)
843         << IncludeFilename
844         << FixItHint::CreateReplacement(IncludeLoc, NewInclude);
845   }
846 
847   // Headers in Foo.framework/Headers should not include headers
848   // from Foo.framework/PrivateHeaders, since this violates public/private
849   // API boundaries and can cause modular dependency cycles.
850   if (!IsIncluderPrivateHeader && IsIncludeeInFramework &&
851       IsIncludeePrivateHeader && FromFramework == ToFramework)
852     Diags.Report(IncludeLoc, diag::warn_framework_include_private_from_public)
853         << IncludeFilename;
854 }
855 
856 /// LookupFile - Given a "foo" or \<foo> reference, look up the indicated file,
857 /// return null on failure.  isAngled indicates whether the file reference is
858 /// for system \#include's or not (i.e. using <> instead of ""). Includers, if
859 /// non-empty, indicates where the \#including file(s) are, in case a relative
860 /// search is needed. Microsoft mode will pass all \#including files.
861 OptionalFileEntryRef HeaderSearch::LookupFile(
862     StringRef Filename, SourceLocation IncludeLoc, bool isAngled,
863     ConstSearchDirIterator FromDir, ConstSearchDirIterator *CurDirArg,
864     ArrayRef<std::pair<const FileEntry *, DirectoryEntryRef>> Includers,
865     SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
866     Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule,
867     bool *IsMapped, bool *IsFrameworkFound, bool SkipCache,
868     bool BuildSystemModule, bool OpenFile, bool CacheFailures) {
869   ConstSearchDirIterator CurDirLocal = nullptr;
870   ConstSearchDirIterator &CurDir = CurDirArg ? *CurDirArg : CurDirLocal;
871 
872   if (IsMapped)
873     *IsMapped = false;
874 
875   if (IsFrameworkFound)
876     *IsFrameworkFound = false;
877 
878   if (SuggestedModule)
879     *SuggestedModule = ModuleMap::KnownHeader();
880 
881   // If 'Filename' is absolute, check to see if it exists and no searching.
882   if (llvm::sys::path::is_absolute(Filename)) {
883     CurDir = nullptr;
884 
885     // If this was an #include_next "/absolute/file", fail.
886     if (FromDir)
887       return std::nullopt;
888 
889     if (SearchPath)
890       SearchPath->clear();
891     if (RelativePath) {
892       RelativePath->clear();
893       RelativePath->append(Filename.begin(), Filename.end());
894     }
895     // Otherwise, just return the file.
896     return getFileAndSuggestModule(Filename, IncludeLoc, nullptr,
897                                    /*IsSystemHeaderDir*/ false,
898                                    RequestingModule, SuggestedModule, OpenFile,
899                                    CacheFailures);
900   }
901 
902   // This is the header that MSVC's header search would have found.
903   ModuleMap::KnownHeader MSSuggestedModule;
904   OptionalFileEntryRef MSFE;
905 
906   // Unless disabled, check to see if the file is in the #includer's
907   // directory.  This cannot be based on CurDir, because each includer could be
908   // a #include of a subdirectory (#include "foo/bar.h") and a subsequent
909   // include of "baz.h" should resolve to "whatever/foo/baz.h".
910   // This search is not done for <> headers.
911   if (!Includers.empty() && !isAngled && !NoCurDirSearch) {
912     SmallString<1024> TmpDir;
913     bool First = true;
914     for (const auto &IncluderAndDir : Includers) {
915       const FileEntry *Includer = IncluderAndDir.first;
916 
917       // Concatenate the requested file onto the directory.
918       // FIXME: Portability.  Filename concatenation should be in sys::Path.
919       TmpDir = IncluderAndDir.second.getName();
920       TmpDir.push_back('/');
921       TmpDir.append(Filename.begin(), Filename.end());
922 
923       // FIXME: We don't cache the result of getFileInfo across the call to
924       // getFileAndSuggestModule, because it's a reference to an element of
925       // a container that could be reallocated across this call.
926       //
927       // If we have no includer, that means we're processing a #include
928       // from a module build. We should treat this as a system header if we're
929       // building a [system] module.
930       bool IncluderIsSystemHeader =
931           Includer ? getFileInfo(Includer).DirInfo != SrcMgr::C_User :
932           BuildSystemModule;
933       if (OptionalFileEntryRef FE = getFileAndSuggestModule(
934               TmpDir, IncludeLoc, IncluderAndDir.second, IncluderIsSystemHeader,
935               RequestingModule, SuggestedModule)) {
936         if (!Includer) {
937           assert(First && "only first includer can have no file");
938           return FE;
939         }
940 
941         // Leave CurDir unset.
942         // This file is a system header or C++ unfriendly if the old file is.
943         //
944         // Note that we only use one of FromHFI/ToHFI at once, due to potential
945         // reallocation of the underlying vector potentially making the first
946         // reference binding dangling.
947         HeaderFileInfo &FromHFI = getFileInfo(Includer);
948         unsigned DirInfo = FromHFI.DirInfo;
949         bool IndexHeaderMapHeader = FromHFI.IndexHeaderMapHeader;
950         StringRef Framework = FromHFI.Framework;
951 
952         HeaderFileInfo &ToHFI = getFileInfo(&FE->getFileEntry());
953         ToHFI.DirInfo = DirInfo;
954         ToHFI.IndexHeaderMapHeader = IndexHeaderMapHeader;
955         ToHFI.Framework = Framework;
956 
957         if (SearchPath) {
958           StringRef SearchPathRef(IncluderAndDir.second.getName());
959           SearchPath->clear();
960           SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
961         }
962         if (RelativePath) {
963           RelativePath->clear();
964           RelativePath->append(Filename.begin(), Filename.end());
965         }
966         if (First) {
967           diagnoseFrameworkInclude(Diags, IncludeLoc,
968                                    IncluderAndDir.second.getName(), Filename,
969                                    &FE->getFileEntry());
970           return FE;
971         }
972 
973         // Otherwise, we found the path via MSVC header search rules.  If
974         // -Wmsvc-include is enabled, we have to keep searching to see if we
975         // would've found this header in -I or -isystem directories.
976         if (Diags.isIgnored(diag::ext_pp_include_search_ms, IncludeLoc)) {
977           return FE;
978         } else {
979           MSFE = FE;
980           if (SuggestedModule) {
981             MSSuggestedModule = *SuggestedModule;
982             *SuggestedModule = ModuleMap::KnownHeader();
983           }
984           break;
985         }
986       }
987       First = false;
988     }
989   }
990 
991   CurDir = nullptr;
992 
993   // If this is a system #include, ignore the user #include locs.
994   ConstSearchDirIterator It =
995       isAngled ? angled_dir_begin() : search_dir_begin();
996 
997   // If this is a #include_next request, start searching after the directory the
998   // file was found in.
999   if (FromDir)
1000     It = FromDir;
1001 
1002   // Cache all of the lookups performed by this method.  Many headers are
1003   // multiply included, and the "pragma once" optimization prevents them from
1004   // being relex/pp'd, but they would still have to search through a
1005   // (potentially huge) series of SearchDirs to find it.
1006   LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename];
1007 
1008   ConstSearchDirIterator NextIt = std::next(It);
1009 
1010   if (!SkipCache) {
1011     if (CacheLookup.StartIt == NextIt &&
1012         CacheLookup.RequestingModule == RequestingModule) {
1013       // HIT: Skip querying potentially lots of directories for this lookup.
1014       if (CacheLookup.HitIt)
1015         It = CacheLookup.HitIt;
1016       if (CacheLookup.MappedName) {
1017         Filename = CacheLookup.MappedName;
1018         if (IsMapped)
1019           *IsMapped = true;
1020       }
1021     } else {
1022       // MISS: This is the first query, or the previous query didn't match
1023       // our search start.  We will fill in our found location below, so prime
1024       // the start point value.
1025       CacheLookup.reset(RequestingModule, /*NewStartIt=*/NextIt);
1026 
1027       if (It == search_dir_begin() && FirstNonHeaderMapSearchDirIdx > 0) {
1028         // Handle cold misses of user includes in the presence of many header
1029         // maps.  We avoid searching perhaps thousands of header maps by
1030         // jumping directly to the correct one or jumping beyond all of them.
1031         auto Iter = SearchDirHeaderMapIndex.find(Filename.lower());
1032         if (Iter == SearchDirHeaderMapIndex.end())
1033           // Not in index => Skip to first SearchDir after initial header maps
1034           It = search_dir_nth(FirstNonHeaderMapSearchDirIdx);
1035         else
1036           // In index => Start with a specific header map
1037           It = search_dir_nth(Iter->second);
1038       }
1039     }
1040   } else {
1041     CacheLookup.reset(RequestingModule, /*NewStartIt=*/NextIt);
1042   }
1043 
1044   SmallString<64> MappedName;
1045 
1046   // Check each directory in sequence to see if it contains this file.
1047   for (; It != search_dir_end(); ++It) {
1048     bool InUserSpecifiedSystemFramework = false;
1049     bool IsInHeaderMap = false;
1050     bool IsFrameworkFoundInDir = false;
1051     OptionalFileEntryRef File = It->LookupFile(
1052         Filename, *this, IncludeLoc, SearchPath, RelativePath, RequestingModule,
1053         SuggestedModule, InUserSpecifiedSystemFramework, IsFrameworkFoundInDir,
1054         IsInHeaderMap, MappedName, OpenFile);
1055     if (!MappedName.empty()) {
1056       assert(IsInHeaderMap && "MappedName should come from a header map");
1057       CacheLookup.MappedName =
1058           copyString(MappedName, LookupFileCache.getAllocator());
1059     }
1060     if (IsMapped)
1061       // A filename is mapped when a header map remapped it to a relative path
1062       // used in subsequent header search or to an absolute path pointing to an
1063       // existing file.
1064       *IsMapped |= (!MappedName.empty() || (IsInHeaderMap && File));
1065     if (IsFrameworkFound)
1066       // Because we keep a filename remapped for subsequent search directory
1067       // lookups, ignore IsFrameworkFoundInDir after the first remapping and not
1068       // just for remapping in a current search directory.
1069       *IsFrameworkFound |= (IsFrameworkFoundInDir && !CacheLookup.MappedName);
1070     if (!File)
1071       continue;
1072 
1073     CurDir = It;
1074 
1075     const auto FE = &File->getFileEntry();
1076     IncludeNames[FE] = Filename;
1077 
1078     // This file is a system header or C++ unfriendly if the dir is.
1079     HeaderFileInfo &HFI = getFileInfo(FE);
1080     HFI.DirInfo = CurDir->getDirCharacteristic();
1081 
1082     // If the directory characteristic is User but this framework was
1083     // user-specified to be treated as a system framework, promote the
1084     // characteristic.
1085     if (HFI.DirInfo == SrcMgr::C_User && InUserSpecifiedSystemFramework)
1086       HFI.DirInfo = SrcMgr::C_System;
1087 
1088     // If the filename matches a known system header prefix, override
1089     // whether the file is a system header.
1090     for (unsigned j = SystemHeaderPrefixes.size(); j; --j) {
1091       if (Filename.startswith(SystemHeaderPrefixes[j-1].first)) {
1092         HFI.DirInfo = SystemHeaderPrefixes[j-1].second ? SrcMgr::C_System
1093                                                        : SrcMgr::C_User;
1094         break;
1095       }
1096     }
1097 
1098     // Set the `Framework` info if this file is in a header map with framework
1099     // style include spelling or found in a framework dir. The header map case
1100     // is possible when building frameworks which use header maps.
1101     if (CurDir->isHeaderMap() && isAngled) {
1102       size_t SlashPos = Filename.find('/');
1103       if (SlashPos != StringRef::npos)
1104         HFI.Framework =
1105             getUniqueFrameworkName(StringRef(Filename.begin(), SlashPos));
1106       if (CurDir->isIndexHeaderMap())
1107         HFI.IndexHeaderMapHeader = 1;
1108     } else if (CurDir->isFramework()) {
1109       size_t SlashPos = Filename.find('/');
1110       if (SlashPos != StringRef::npos)
1111         HFI.Framework =
1112             getUniqueFrameworkName(StringRef(Filename.begin(), SlashPos));
1113     }
1114 
1115     if (checkMSVCHeaderSearch(Diags, MSFE ? &MSFE->getFileEntry() : nullptr,
1116                               &File->getFileEntry(), IncludeLoc)) {
1117       if (SuggestedModule)
1118         *SuggestedModule = MSSuggestedModule;
1119       return MSFE;
1120     }
1121 
1122     bool FoundByHeaderMap = !IsMapped ? false : *IsMapped;
1123     if (!Includers.empty())
1124       diagnoseFrameworkInclude(
1125           Diags, IncludeLoc, Includers.front().second.getName(), Filename,
1126           &File->getFileEntry(), isAngled, FoundByHeaderMap);
1127 
1128     // Remember this location for the next lookup we do.
1129     cacheLookupSuccess(CacheLookup, It, IncludeLoc);
1130     return File;
1131   }
1132 
1133   // If we are including a file with a quoted include "foo.h" from inside
1134   // a header in a framework that is currently being built, and we couldn't
1135   // resolve "foo.h" any other way, change the include to <Foo/foo.h>, where
1136   // "Foo" is the name of the framework in which the including header was found.
1137   if (!Includers.empty() && Includers.front().first && !isAngled &&
1138       !Filename.contains('/')) {
1139     HeaderFileInfo &IncludingHFI = getFileInfo(Includers.front().first);
1140     if (IncludingHFI.IndexHeaderMapHeader) {
1141       SmallString<128> ScratchFilename;
1142       ScratchFilename += IncludingHFI.Framework;
1143       ScratchFilename += '/';
1144       ScratchFilename += Filename;
1145 
1146       OptionalFileEntryRef File = LookupFile(
1147           ScratchFilename, IncludeLoc, /*isAngled=*/true, FromDir, &CurDir,
1148           Includers.front(), SearchPath, RelativePath, RequestingModule,
1149           SuggestedModule, IsMapped, /*IsFrameworkFound=*/nullptr);
1150 
1151       if (checkMSVCHeaderSearch(Diags, MSFE ? &MSFE->getFileEntry() : nullptr,
1152                                 File ? &File->getFileEntry() : nullptr,
1153                                 IncludeLoc)) {
1154         if (SuggestedModule)
1155           *SuggestedModule = MSSuggestedModule;
1156         return MSFE;
1157       }
1158 
1159       cacheLookupSuccess(LookupFileCache[Filename],
1160                          LookupFileCache[ScratchFilename].HitIt, IncludeLoc);
1161       // FIXME: SuggestedModule.
1162       return File;
1163     }
1164   }
1165 
1166   if (checkMSVCHeaderSearch(Diags, MSFE ? &MSFE->getFileEntry() : nullptr,
1167                             nullptr, IncludeLoc)) {
1168     if (SuggestedModule)
1169       *SuggestedModule = MSSuggestedModule;
1170     return MSFE;
1171   }
1172 
1173   // Otherwise, didn't find it. Remember we didn't find this.
1174   CacheLookup.HitIt = search_dir_end();
1175   return std::nullopt;
1176 }
1177 
1178 /// LookupSubframeworkHeader - Look up a subframework for the specified
1179 /// \#include file.  For example, if \#include'ing <HIToolbox/HIToolbox.h> from
1180 /// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
1181 /// is a subframework within Carbon.framework.  If so, return the FileEntry
1182 /// for the designated file, otherwise return null.
1183 OptionalFileEntryRef HeaderSearch::LookupSubframeworkHeader(
1184     StringRef Filename, const FileEntry *ContextFileEnt,
1185     SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
1186     Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule) {
1187   assert(ContextFileEnt && "No context file?");
1188 
1189   // Framework names must have a '/' in the filename.  Find it.
1190   // FIXME: Should we permit '\' on Windows?
1191   size_t SlashPos = Filename.find('/');
1192   if (SlashPos == StringRef::npos)
1193     return std::nullopt;
1194 
1195   // Look up the base framework name of the ContextFileEnt.
1196   StringRef ContextName = ContextFileEnt->getName();
1197 
1198   // If the context info wasn't a framework, couldn't be a subframework.
1199   const unsigned DotFrameworkLen = 10;
1200   auto FrameworkPos = ContextName.find(".framework");
1201   if (FrameworkPos == StringRef::npos ||
1202       (ContextName[FrameworkPos + DotFrameworkLen] != '/' &&
1203        ContextName[FrameworkPos + DotFrameworkLen] != '\\'))
1204     return std::nullopt;
1205 
1206   SmallString<1024> FrameworkName(ContextName.data(), ContextName.data() +
1207                                                           FrameworkPos +
1208                                                           DotFrameworkLen + 1);
1209 
1210   // Append Frameworks/HIToolbox.framework/
1211   FrameworkName += "Frameworks/";
1212   FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos);
1213   FrameworkName += ".framework/";
1214 
1215   auto &CacheLookup =
1216       *FrameworkMap.insert(std::make_pair(Filename.substr(0, SlashPos),
1217                                           FrameworkCacheEntry())).first;
1218 
1219   // Some other location?
1220   if (CacheLookup.second.Directory &&
1221       CacheLookup.first().size() == FrameworkName.size() &&
1222       memcmp(CacheLookup.first().data(), &FrameworkName[0],
1223              CacheLookup.first().size()) != 0)
1224     return std::nullopt;
1225 
1226   // Cache subframework.
1227   if (!CacheLookup.second.Directory) {
1228     ++NumSubFrameworkLookups;
1229 
1230     // If the framework dir doesn't exist, we fail.
1231     auto Dir = FileMgr.getOptionalDirectoryRef(FrameworkName);
1232     if (!Dir)
1233       return std::nullopt;
1234 
1235     // Otherwise, if it does, remember that this is the right direntry for this
1236     // framework.
1237     CacheLookup.second.Directory = Dir;
1238   }
1239 
1240 
1241   if (RelativePath) {
1242     RelativePath->clear();
1243     RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
1244   }
1245 
1246   // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
1247   SmallString<1024> HeadersFilename(FrameworkName);
1248   HeadersFilename += "Headers/";
1249   if (SearchPath) {
1250     SearchPath->clear();
1251     // Without trailing '/'.
1252     SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
1253   }
1254 
1255   HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
1256   auto File = FileMgr.getOptionalFileRef(HeadersFilename, /*OpenFile=*/true);
1257   if (!File) {
1258     // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
1259     HeadersFilename = FrameworkName;
1260     HeadersFilename += "PrivateHeaders/";
1261     if (SearchPath) {
1262       SearchPath->clear();
1263       // Without trailing '/'.
1264       SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
1265     }
1266 
1267     HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
1268     File = FileMgr.getOptionalFileRef(HeadersFilename, /*OpenFile=*/true);
1269 
1270     if (!File)
1271       return std::nullopt;
1272   }
1273 
1274   // This file is a system header or C++ unfriendly if the old file is.
1275   //
1276   // Note that the temporary 'DirInfo' is required here, as either call to
1277   // getFileInfo could resize the vector and we don't want to rely on order
1278   // of evaluation.
1279   unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo;
1280   getFileInfo(&File->getFileEntry()).DirInfo = DirInfo;
1281 
1282   FrameworkName.pop_back(); // remove the trailing '/'
1283   if (!findUsableModuleForFrameworkHeader(*File, FrameworkName,
1284                                           RequestingModule, SuggestedModule,
1285                                           /*IsSystem*/ false))
1286     return std::nullopt;
1287 
1288   return *File;
1289 }
1290 
1291 //===----------------------------------------------------------------------===//
1292 // File Info Management.
1293 //===----------------------------------------------------------------------===//
1294 
1295 /// Merge the header file info provided by \p OtherHFI into the current
1296 /// header file info (\p HFI)
1297 static void mergeHeaderFileInfo(HeaderFileInfo &HFI,
1298                                 const HeaderFileInfo &OtherHFI) {
1299   assert(OtherHFI.External && "expected to merge external HFI");
1300 
1301   HFI.isImport |= OtherHFI.isImport;
1302   HFI.isPragmaOnce |= OtherHFI.isPragmaOnce;
1303   HFI.isModuleHeader |= OtherHFI.isModuleHeader;
1304 
1305   if (!HFI.ControllingMacro && !HFI.ControllingMacroID) {
1306     HFI.ControllingMacro = OtherHFI.ControllingMacro;
1307     HFI.ControllingMacroID = OtherHFI.ControllingMacroID;
1308   }
1309 
1310   HFI.DirInfo = OtherHFI.DirInfo;
1311   HFI.External = (!HFI.IsValid || HFI.External);
1312   HFI.IsValid = true;
1313   HFI.IndexHeaderMapHeader = OtherHFI.IndexHeaderMapHeader;
1314 
1315   if (HFI.Framework.empty())
1316     HFI.Framework = OtherHFI.Framework;
1317 }
1318 
1319 /// getFileInfo - Return the HeaderFileInfo structure for the specified
1320 /// FileEntry.
1321 HeaderFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) {
1322   if (FE->getUID() >= FileInfo.size())
1323     FileInfo.resize(FE->getUID() + 1);
1324 
1325   HeaderFileInfo *HFI = &FileInfo[FE->getUID()];
1326   // FIXME: Use a generation count to check whether this is really up to date.
1327   if (ExternalSource && !HFI->Resolved) {
1328     auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE);
1329     if (ExternalHFI.IsValid) {
1330       HFI->Resolved = true;
1331       if (ExternalHFI.External)
1332         mergeHeaderFileInfo(*HFI, ExternalHFI);
1333     }
1334   }
1335 
1336   HFI->IsValid = true;
1337   // We have local information about this header file, so it's no longer
1338   // strictly external.
1339   HFI->External = false;
1340   return *HFI;
1341 }
1342 
1343 const HeaderFileInfo *
1344 HeaderSearch::getExistingFileInfo(const FileEntry *FE,
1345                                   bool WantExternal) const {
1346   // If we have an external source, ensure we have the latest information.
1347   // FIXME: Use a generation count to check whether this is really up to date.
1348   HeaderFileInfo *HFI;
1349   if (ExternalSource) {
1350     if (FE->getUID() >= FileInfo.size()) {
1351       if (!WantExternal)
1352         return nullptr;
1353       FileInfo.resize(FE->getUID() + 1);
1354     }
1355 
1356     HFI = &FileInfo[FE->getUID()];
1357     if (!WantExternal && (!HFI->IsValid || HFI->External))
1358       return nullptr;
1359     if (!HFI->Resolved) {
1360       auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE);
1361       if (ExternalHFI.IsValid) {
1362         HFI->Resolved = true;
1363         if (ExternalHFI.External)
1364           mergeHeaderFileInfo(*HFI, ExternalHFI);
1365       }
1366     }
1367   } else if (FE->getUID() >= FileInfo.size()) {
1368     return nullptr;
1369   } else {
1370     HFI = &FileInfo[FE->getUID()];
1371   }
1372 
1373   if (!HFI->IsValid || (HFI->External && !WantExternal))
1374     return nullptr;
1375 
1376   return HFI;
1377 }
1378 
1379 bool HeaderSearch::isFileMultipleIncludeGuarded(const FileEntry *File) const {
1380   // Check if we've entered this file and found an include guard or #pragma
1381   // once. Note that we dor't check for #import, because that's not a property
1382   // of the file itself.
1383   if (auto *HFI = getExistingFileInfo(File))
1384     return HFI->isPragmaOnce || HFI->ControllingMacro ||
1385            HFI->ControllingMacroID;
1386   return false;
1387 }
1388 
1389 void HeaderSearch::MarkFileModuleHeader(const FileEntry *FE,
1390                                         ModuleMap::ModuleHeaderRole Role,
1391                                         bool isCompilingModuleHeader) {
1392   bool isModularHeader = ModuleMap::isModular(Role);
1393 
1394   // Don't mark the file info as non-external if there's nothing to change.
1395   if (!isCompilingModuleHeader) {
1396     if (!isModularHeader)
1397       return;
1398     auto *HFI = getExistingFileInfo(FE);
1399     if (HFI && HFI->isModuleHeader)
1400       return;
1401   }
1402 
1403   auto &HFI = getFileInfo(FE);
1404   HFI.isModuleHeader |= isModularHeader;
1405   HFI.isCompilingModuleHeader |= isCompilingModuleHeader;
1406 }
1407 
1408 bool HeaderSearch::ShouldEnterIncludeFile(Preprocessor &PP,
1409                                           const FileEntry *File, bool isImport,
1410                                           bool ModulesEnabled, Module *M,
1411                                           bool &IsFirstIncludeOfFile) {
1412   ++NumIncluded; // Count # of attempted #includes.
1413 
1414   IsFirstIncludeOfFile = false;
1415 
1416   // Get information about this file.
1417   HeaderFileInfo &FileInfo = getFileInfo(File);
1418 
1419   // FIXME: this is a workaround for the lack of proper modules-aware support
1420   // for #import / #pragma once
1421   auto TryEnterImported = [&]() -> bool {
1422     if (!ModulesEnabled)
1423       return false;
1424     // Ensure FileInfo bits are up to date.
1425     ModMap.resolveHeaderDirectives(File);
1426     // Modules with builtins are special; multiple modules use builtins as
1427     // modular headers, example:
1428     //
1429     //    module stddef { header "stddef.h" export * }
1430     //
1431     // After module map parsing, this expands to:
1432     //
1433     //    module stddef {
1434     //      header "/path_to_builtin_dirs/stddef.h"
1435     //      textual "stddef.h"
1436     //    }
1437     //
1438     // It's common that libc++ and system modules will both define such
1439     // submodules. Make sure cached results for a builtin header won't
1440     // prevent other builtin modules from potentially entering the builtin
1441     // header. Note that builtins are header guarded and the decision to
1442     // actually enter them is postponed to the controlling macros logic below.
1443     bool TryEnterHdr = false;
1444     if (FileInfo.isCompilingModuleHeader && FileInfo.isModuleHeader)
1445       TryEnterHdr = ModMap.isBuiltinHeader(File);
1446 
1447     // Textual headers can be #imported from different modules. Since ObjC
1448     // headers find in the wild might rely only on #import and do not contain
1449     // controlling macros, be conservative and only try to enter textual headers
1450     // if such macro is present.
1451     if (!FileInfo.isModuleHeader &&
1452         FileInfo.getControllingMacro(ExternalLookup))
1453       TryEnterHdr = true;
1454     return TryEnterHdr;
1455   };
1456 
1457   // If this is a #import directive, check that we have not already imported
1458   // this header.
1459   if (isImport) {
1460     // If this has already been imported, don't import it again.
1461     FileInfo.isImport = true;
1462 
1463     // Has this already been #import'ed or #include'd?
1464     if (PP.alreadyIncluded(File) && !TryEnterImported())
1465       return false;
1466   } else {
1467     // Otherwise, if this is a #include of a file that was previously #import'd
1468     // or if this is the second #include of a #pragma once file, ignore it.
1469     if ((FileInfo.isPragmaOnce || FileInfo.isImport) && !TryEnterImported())
1470       return false;
1471   }
1472 
1473   // Next, check to see if the file is wrapped with #ifndef guards.  If so, and
1474   // if the macro that guards it is defined, we know the #include has no effect.
1475   if (const IdentifierInfo *ControllingMacro
1476       = FileInfo.getControllingMacro(ExternalLookup)) {
1477     // If the header corresponds to a module, check whether the macro is already
1478     // defined in that module rather than checking in the current set of visible
1479     // modules.
1480     if (M ? PP.isMacroDefinedInLocalModule(ControllingMacro, M)
1481           : PP.isMacroDefined(ControllingMacro)) {
1482       ++NumMultiIncludeFileOptzn;
1483       return false;
1484     }
1485   }
1486 
1487   IsFirstIncludeOfFile = PP.markIncluded(File);
1488 
1489   return true;
1490 }
1491 
1492 size_t HeaderSearch::getTotalMemory() const {
1493   return SearchDirs.capacity()
1494     + llvm::capacity_in_bytes(FileInfo)
1495     + llvm::capacity_in_bytes(HeaderMaps)
1496     + LookupFileCache.getAllocator().getTotalMemory()
1497     + FrameworkMap.getAllocator().getTotalMemory();
1498 }
1499 
1500 unsigned HeaderSearch::searchDirIdx(const DirectoryLookup &DL) const {
1501   return &DL - &*SearchDirs.begin();
1502 }
1503 
1504 StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) {
1505   return FrameworkNames.insert(Framework).first->first();
1506 }
1507 
1508 StringRef HeaderSearch::getIncludeNameForHeader(const FileEntry *File) const {
1509   auto It = IncludeNames.find(File);
1510   if (It == IncludeNames.end())
1511     return {};
1512   return It->second;
1513 }
1514 
1515 bool HeaderSearch::hasModuleMap(StringRef FileName,
1516                                 const DirectoryEntry *Root,
1517                                 bool IsSystem) {
1518   if (!HSOpts->ImplicitModuleMaps)
1519     return false;
1520 
1521   SmallVector<const DirectoryEntry *, 2> FixUpDirectories;
1522 
1523   StringRef DirName = FileName;
1524   do {
1525     // Get the parent directory name.
1526     DirName = llvm::sys::path::parent_path(DirName);
1527     if (DirName.empty())
1528       return false;
1529 
1530     // Determine whether this directory exists.
1531     auto Dir = FileMgr.getOptionalDirectoryRef(DirName);
1532     if (!Dir)
1533       return false;
1534 
1535     // Try to load the module map file in this directory.
1536     switch (loadModuleMapFile(*Dir, IsSystem,
1537                               llvm::sys::path::extension(Dir->getName()) ==
1538                                   ".framework")) {
1539     case LMM_NewlyLoaded:
1540     case LMM_AlreadyLoaded:
1541       // Success. All of the directories we stepped through inherit this module
1542       // map file.
1543       for (unsigned I = 0, N = FixUpDirectories.size(); I != N; ++I)
1544         DirectoryHasModuleMap[FixUpDirectories[I]] = true;
1545       return true;
1546 
1547     case LMM_NoDirectory:
1548     case LMM_InvalidModuleMap:
1549       break;
1550     }
1551 
1552     // If we hit the top of our search, we're done.
1553     if (*Dir == Root)
1554       return false;
1555 
1556     // Keep track of all of the directories we checked, so we can mark them as
1557     // having module maps if we eventually do find a module map.
1558     FixUpDirectories.push_back(*Dir);
1559   } while (true);
1560 }
1561 
1562 ModuleMap::KnownHeader
1563 HeaderSearch::findModuleForHeader(FileEntryRef File, bool AllowTextual,
1564                                   bool AllowExcluded) const {
1565   if (ExternalSource) {
1566     // Make sure the external source has handled header info about this file,
1567     // which includes whether the file is part of a module.
1568     (void)getExistingFileInfo(File);
1569   }
1570   return ModMap.findModuleForHeader(File, AllowTextual, AllowExcluded);
1571 }
1572 
1573 ArrayRef<ModuleMap::KnownHeader>
1574 HeaderSearch::findAllModulesForHeader(FileEntryRef File) const {
1575   if (ExternalSource) {
1576     // Make sure the external source has handled header info about this file,
1577     // which includes whether the file is part of a module.
1578     (void)getExistingFileInfo(File);
1579   }
1580   return ModMap.findAllModulesForHeader(File);
1581 }
1582 
1583 ArrayRef<ModuleMap::KnownHeader>
1584 HeaderSearch::findResolvedModulesForHeader(const FileEntry *File) const {
1585   if (ExternalSource) {
1586     // Make sure the external source has handled header info about this file,
1587     // which includes whether the file is part of a module.
1588     (void)getExistingFileInfo(File);
1589   }
1590   return ModMap.findResolvedModulesForHeader(File);
1591 }
1592 
1593 static bool suggestModule(HeaderSearch &HS, FileEntryRef File,
1594                           Module *RequestingModule,
1595                           ModuleMap::KnownHeader *SuggestedModule) {
1596   ModuleMap::KnownHeader Module =
1597       HS.findModuleForHeader(File, /*AllowTextual*/true);
1598 
1599   // If this module specifies [no_undeclared_includes], we cannot find any
1600   // file that's in a non-dependency module.
1601   if (RequestingModule && Module && RequestingModule->NoUndeclaredIncludes) {
1602     HS.getModuleMap().resolveUses(RequestingModule, /*Complain*/ false);
1603     if (!RequestingModule->directlyUses(Module.getModule())) {
1604       // Builtin headers are a special case. Multiple modules can use the same
1605       // builtin as a modular header (see also comment in
1606       // ShouldEnterIncludeFile()), so the builtin header may have been
1607       // "claimed" by an unrelated module. This shouldn't prevent us from
1608       // including the builtin header textually in this module.
1609       if (HS.getModuleMap().isBuiltinHeader(File)) {
1610         if (SuggestedModule)
1611           *SuggestedModule = ModuleMap::KnownHeader();
1612         return true;
1613       }
1614       // TODO: Add this module (or just its module map file) into something like
1615       // `RequestingModule->AffectingClangModules`.
1616       return false;
1617     }
1618   }
1619 
1620   if (SuggestedModule)
1621     *SuggestedModule = (Module.getRole() & ModuleMap::TextualHeader)
1622                            ? ModuleMap::KnownHeader()
1623                            : Module;
1624 
1625   return true;
1626 }
1627 
1628 bool HeaderSearch::findUsableModuleForHeader(
1629     FileEntryRef File, const DirectoryEntry *Root, Module *RequestingModule,
1630     ModuleMap::KnownHeader *SuggestedModule, bool IsSystemHeaderDir) {
1631   if (needModuleLookup(RequestingModule, SuggestedModule)) {
1632     // If there is a module that corresponds to this header, suggest it.
1633     hasModuleMap(File.getName(), Root, IsSystemHeaderDir);
1634     return suggestModule(*this, File, RequestingModule, SuggestedModule);
1635   }
1636   return true;
1637 }
1638 
1639 bool HeaderSearch::findUsableModuleForFrameworkHeader(
1640     FileEntryRef File, StringRef FrameworkName, Module *RequestingModule,
1641     ModuleMap::KnownHeader *SuggestedModule, bool IsSystemFramework) {
1642   // If we're supposed to suggest a module, look for one now.
1643   if (needModuleLookup(RequestingModule, SuggestedModule)) {
1644     // Find the top-level framework based on this framework.
1645     SmallVector<std::string, 4> SubmodulePath;
1646     OptionalDirectoryEntryRef TopFrameworkDir =
1647         ::getTopFrameworkDir(FileMgr, FrameworkName, SubmodulePath);
1648     assert(TopFrameworkDir && "Could not find the top-most framework dir");
1649 
1650     // Determine the name of the top-level framework.
1651     StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
1652 
1653     // Load this framework module. If that succeeds, find the suggested module
1654     // for this header, if any.
1655     loadFrameworkModule(ModuleName, *TopFrameworkDir, IsSystemFramework);
1656 
1657     // FIXME: This can find a module not part of ModuleName, which is
1658     // important so that we're consistent about whether this header
1659     // corresponds to a module. Possibly we should lock down framework modules
1660     // so that this is not possible.
1661     return suggestModule(*this, File, RequestingModule, SuggestedModule);
1662   }
1663   return true;
1664 }
1665 
1666 static const FileEntry *getPrivateModuleMap(FileEntryRef File,
1667                                             FileManager &FileMgr) {
1668   StringRef Filename = llvm::sys::path::filename(File.getName());
1669   SmallString<128>  PrivateFilename(File.getDir().getName());
1670   if (Filename == "module.map")
1671     llvm::sys::path::append(PrivateFilename, "module_private.map");
1672   else if (Filename == "module.modulemap")
1673     llvm::sys::path::append(PrivateFilename, "module.private.modulemap");
1674   else
1675     return nullptr;
1676   if (auto File = FileMgr.getFile(PrivateFilename))
1677     return *File;
1678   return nullptr;
1679 }
1680 
1681 bool HeaderSearch::loadModuleMapFile(FileEntryRef File, bool IsSystem,
1682                                      FileID ID, unsigned *Offset,
1683                                      StringRef OriginalModuleMapFile) {
1684   // Find the directory for the module. For frameworks, that may require going
1685   // up from the 'Modules' directory.
1686   OptionalDirectoryEntryRef Dir;
1687   if (getHeaderSearchOpts().ModuleMapFileHomeIsCwd) {
1688     Dir = FileMgr.getOptionalDirectoryRef(".");
1689   } else {
1690     if (!OriginalModuleMapFile.empty()) {
1691       // We're building a preprocessed module map. Find or invent the directory
1692       // that it originally occupied.
1693       Dir = FileMgr.getOptionalDirectoryRef(
1694           llvm::sys::path::parent_path(OriginalModuleMapFile));
1695       if (!Dir) {
1696         auto FakeFile = FileMgr.getVirtualFileRef(OriginalModuleMapFile, 0, 0);
1697         Dir = FakeFile.getDir();
1698       }
1699     } else {
1700       Dir = File.getDir();
1701     }
1702 
1703     assert(Dir && "parent must exist");
1704     StringRef DirName(Dir->getName());
1705     if (llvm::sys::path::filename(DirName) == "Modules") {
1706       DirName = llvm::sys::path::parent_path(DirName);
1707       if (DirName.endswith(".framework"))
1708         if (auto MaybeDir = FileMgr.getOptionalDirectoryRef(DirName))
1709           Dir = *MaybeDir;
1710       // FIXME: This assert can fail if there's a race between the above check
1711       // and the removal of the directory.
1712       assert(Dir && "parent must exist");
1713     }
1714   }
1715 
1716   assert(Dir && "module map home directory must exist");
1717   switch (loadModuleMapFileImpl(File, IsSystem, *Dir, ID, Offset)) {
1718   case LMM_AlreadyLoaded:
1719   case LMM_NewlyLoaded:
1720     return false;
1721   case LMM_NoDirectory:
1722   case LMM_InvalidModuleMap:
1723     return true;
1724   }
1725   llvm_unreachable("Unknown load module map result");
1726 }
1727 
1728 HeaderSearch::LoadModuleMapResult
1729 HeaderSearch::loadModuleMapFileImpl(FileEntryRef File, bool IsSystem,
1730                                     DirectoryEntryRef Dir, FileID ID,
1731                                     unsigned *Offset) {
1732   // Check whether we've already loaded this module map, and mark it as being
1733   // loaded in case we recursively try to load it from itself.
1734   auto AddResult = LoadedModuleMaps.insert(std::make_pair(File, true));
1735   if (!AddResult.second)
1736     return AddResult.first->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
1737 
1738   if (ModMap.parseModuleMapFile(File, IsSystem, Dir, ID, Offset)) {
1739     LoadedModuleMaps[File] = false;
1740     return LMM_InvalidModuleMap;
1741   }
1742 
1743   // Try to load a corresponding private module map.
1744   if (const FileEntry *PMMFile = getPrivateModuleMap(File, FileMgr)) {
1745     if (ModMap.parseModuleMapFile(PMMFile, IsSystem, Dir)) {
1746       LoadedModuleMaps[File] = false;
1747       return LMM_InvalidModuleMap;
1748     }
1749   }
1750 
1751   // This directory has a module map.
1752   return LMM_NewlyLoaded;
1753 }
1754 
1755 OptionalFileEntryRef
1756 HeaderSearch::lookupModuleMapFile(DirectoryEntryRef Dir, bool IsFramework) {
1757   if (!HSOpts->ImplicitModuleMaps)
1758     return std::nullopt;
1759   // For frameworks, the preferred spelling is Modules/module.modulemap, but
1760   // module.map at the framework root is also accepted.
1761   SmallString<128> ModuleMapFileName(Dir.getName());
1762   if (IsFramework)
1763     llvm::sys::path::append(ModuleMapFileName, "Modules");
1764   llvm::sys::path::append(ModuleMapFileName, "module.modulemap");
1765   if (auto F = FileMgr.getOptionalFileRef(ModuleMapFileName))
1766     return *F;
1767 
1768   // Continue to allow module.map
1769   ModuleMapFileName = Dir.getName();
1770   llvm::sys::path::append(ModuleMapFileName, "module.map");
1771   if (auto F = FileMgr.getOptionalFileRef(ModuleMapFileName))
1772     return *F;
1773 
1774   // For frameworks, allow to have a private module map with a preferred
1775   // spelling when a public module map is absent.
1776   if (IsFramework) {
1777     ModuleMapFileName = Dir.getName();
1778     llvm::sys::path::append(ModuleMapFileName, "Modules",
1779                             "module.private.modulemap");
1780     if (auto F = FileMgr.getOptionalFileRef(ModuleMapFileName))
1781       return *F;
1782   }
1783   return std::nullopt;
1784 }
1785 
1786 Module *HeaderSearch::loadFrameworkModule(StringRef Name, DirectoryEntryRef Dir,
1787                                           bool IsSystem) {
1788   // Try to load a module map file.
1789   switch (loadModuleMapFile(Dir, IsSystem, /*IsFramework*/true)) {
1790   case LMM_InvalidModuleMap:
1791     // Try to infer a module map from the framework directory.
1792     if (HSOpts->ImplicitModuleMaps)
1793       ModMap.inferFrameworkModule(Dir, IsSystem, /*Parent=*/nullptr);
1794     break;
1795 
1796   case LMM_NoDirectory:
1797     return nullptr;
1798 
1799   case LMM_AlreadyLoaded:
1800   case LMM_NewlyLoaded:
1801     break;
1802   }
1803 
1804   return ModMap.findModule(Name);
1805 }
1806 
1807 HeaderSearch::LoadModuleMapResult
1808 HeaderSearch::loadModuleMapFile(StringRef DirName, bool IsSystem,
1809                                 bool IsFramework) {
1810   if (auto Dir = FileMgr.getOptionalDirectoryRef(DirName))
1811     return loadModuleMapFile(*Dir, IsSystem, IsFramework);
1812 
1813   return LMM_NoDirectory;
1814 }
1815 
1816 HeaderSearch::LoadModuleMapResult
1817 HeaderSearch::loadModuleMapFile(DirectoryEntryRef Dir, bool IsSystem,
1818                                 bool IsFramework) {
1819   auto KnownDir = DirectoryHasModuleMap.find(Dir);
1820   if (KnownDir != DirectoryHasModuleMap.end())
1821     return KnownDir->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
1822 
1823   if (OptionalFileEntryRef ModuleMapFile =
1824           lookupModuleMapFile(Dir, IsFramework)) {
1825     LoadModuleMapResult Result =
1826         loadModuleMapFileImpl(*ModuleMapFile, IsSystem, Dir);
1827     // Add Dir explicitly in case ModuleMapFile is in a subdirectory.
1828     // E.g. Foo.framework/Modules/module.modulemap
1829     //      ^Dir                  ^ModuleMapFile
1830     if (Result == LMM_NewlyLoaded)
1831       DirectoryHasModuleMap[Dir] = true;
1832     else if (Result == LMM_InvalidModuleMap)
1833       DirectoryHasModuleMap[Dir] = false;
1834     return Result;
1835   }
1836   return LMM_InvalidModuleMap;
1837 }
1838 
1839 void HeaderSearch::collectAllModules(SmallVectorImpl<Module *> &Modules) {
1840   Modules.clear();
1841 
1842   if (HSOpts->ImplicitModuleMaps) {
1843     // Load module maps for each of the header search directories.
1844     for (DirectoryLookup &DL : search_dir_range()) {
1845       bool IsSystem = DL.isSystemHeaderDirectory();
1846       if (DL.isFramework()) {
1847         std::error_code EC;
1848         SmallString<128> DirNative;
1849         llvm::sys::path::native(DL.getFrameworkDirRef()->getName(), DirNative);
1850 
1851         // Search each of the ".framework" directories to load them as modules.
1852         llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
1853         for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC),
1854                                            DirEnd;
1855              Dir != DirEnd && !EC; Dir.increment(EC)) {
1856           if (llvm::sys::path::extension(Dir->path()) != ".framework")
1857             continue;
1858 
1859           auto FrameworkDir = FileMgr.getOptionalDirectoryRef(Dir->path());
1860           if (!FrameworkDir)
1861             continue;
1862 
1863           // Load this framework module.
1864           loadFrameworkModule(llvm::sys::path::stem(Dir->path()), *FrameworkDir,
1865                               IsSystem);
1866         }
1867         continue;
1868       }
1869 
1870       // FIXME: Deal with header maps.
1871       if (DL.isHeaderMap())
1872         continue;
1873 
1874       // Try to load a module map file for the search directory.
1875       loadModuleMapFile(*DL.getDirRef(), IsSystem, /*IsFramework*/ false);
1876 
1877       // Try to load module map files for immediate subdirectories of this
1878       // search directory.
1879       loadSubdirectoryModuleMaps(DL);
1880     }
1881   }
1882 
1883   // Populate the list of modules.
1884   llvm::transform(ModMap.modules(), std::back_inserter(Modules),
1885                   [](const auto &NameAndMod) { return NameAndMod.second; });
1886 }
1887 
1888 void HeaderSearch::loadTopLevelSystemModules() {
1889   if (!HSOpts->ImplicitModuleMaps)
1890     return;
1891 
1892   // Load module maps for each of the header search directories.
1893   for (const DirectoryLookup &DL : search_dir_range()) {
1894     // We only care about normal header directories.
1895     if (!DL.isNormalDir())
1896       continue;
1897 
1898     // Try to load a module map file for the search directory.
1899     loadModuleMapFile(*DL.getDirRef(), DL.isSystemHeaderDirectory(),
1900                       DL.isFramework());
1901   }
1902 }
1903 
1904 void HeaderSearch::loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir) {
1905   assert(HSOpts->ImplicitModuleMaps &&
1906          "Should not be loading subdirectory module maps");
1907 
1908   if (SearchDir.haveSearchedAllModuleMaps())
1909     return;
1910 
1911   std::error_code EC;
1912   SmallString<128> Dir = SearchDir.getDirRef()->getName();
1913   FileMgr.makeAbsolutePath(Dir);
1914   SmallString<128> DirNative;
1915   llvm::sys::path::native(Dir, DirNative);
1916   llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
1917   for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
1918        Dir != DirEnd && !EC; Dir.increment(EC)) {
1919     if (Dir->type() == llvm::sys::fs::file_type::regular_file)
1920       continue;
1921     bool IsFramework = llvm::sys::path::extension(Dir->path()) == ".framework";
1922     if (IsFramework == SearchDir.isFramework())
1923       loadModuleMapFile(Dir->path(), SearchDir.isSystemHeaderDirectory(),
1924                         SearchDir.isFramework());
1925   }
1926 
1927   SearchDir.setSearchedAllModuleMaps(true);
1928 }
1929 
1930 std::string HeaderSearch::suggestPathToFileForDiagnostics(
1931     const FileEntry *File, llvm::StringRef MainFile, bool *IsSystem) const {
1932   // FIXME: We assume that the path name currently cached in the FileEntry is
1933   // the most appropriate one for this analysis (and that it's spelled the
1934   // same way as the corresponding header search path).
1935   return suggestPathToFileForDiagnostics(File->getName(), /*WorkingDir=*/"",
1936                                          MainFile, IsSystem);
1937 }
1938 
1939 std::string HeaderSearch::suggestPathToFileForDiagnostics(
1940     llvm::StringRef File, llvm::StringRef WorkingDir, llvm::StringRef MainFile,
1941     bool *IsSystem) const {
1942   using namespace llvm::sys;
1943 
1944   llvm::SmallString<32> FilePath = File;
1945   // remove_dots switches to backslashes on windows as a side-effect!
1946   // We always want to suggest forward slashes for includes.
1947   // (not remove_dots(..., posix) as that misparses windows paths).
1948   path::remove_dots(FilePath, /*remove_dot_dot=*/true);
1949   path::native(FilePath, path::Style::posix);
1950   File = FilePath;
1951 
1952   unsigned BestPrefixLength = 0;
1953   // Checks whether `Dir` is a strict path prefix of `File`. If so and that's
1954   // the longest prefix we've seen so for it, returns true and updates the
1955   // `BestPrefixLength` accordingly.
1956   auto CheckDir = [&](llvm::SmallString<32> Dir) -> bool {
1957     if (!WorkingDir.empty() && !path::is_absolute(Dir))
1958       fs::make_absolute(WorkingDir, Dir);
1959     path::remove_dots(Dir, /*remove_dot_dot=*/true);
1960     for (auto NI = path::begin(File), NE = path::end(File),
1961               DI = path::begin(Dir), DE = path::end(Dir);
1962          NI != NE; ++NI, ++DI) {
1963       if (DI == DE) {
1964         // Dir is a prefix of File, up to choice of path separators.
1965         unsigned PrefixLength = NI - path::begin(File);
1966         if (PrefixLength > BestPrefixLength) {
1967           BestPrefixLength = PrefixLength;
1968           return true;
1969         }
1970         break;
1971       }
1972 
1973       // Consider all path separators equal.
1974       if (NI->size() == 1 && DI->size() == 1 &&
1975           path::is_separator(NI->front()) && path::is_separator(DI->front()))
1976         continue;
1977 
1978       // Special case Apple .sdk folders since the search path is typically a
1979       // symlink like `iPhoneSimulator14.5.sdk` while the file is instead
1980       // located in `iPhoneSimulator.sdk` (the real folder).
1981       if (NI->endswith(".sdk") && DI->endswith(".sdk")) {
1982         StringRef NBasename = path::stem(*NI);
1983         StringRef DBasename = path::stem(*DI);
1984         if (DBasename.startswith(NBasename))
1985           continue;
1986       }
1987 
1988       if (*NI != *DI)
1989         break;
1990     }
1991     return false;
1992   };
1993 
1994   bool BestPrefixIsFramework = false;
1995   for (const DirectoryLookup &DL : search_dir_range()) {
1996     if (DL.isNormalDir()) {
1997       StringRef Dir = DL.getDirRef()->getName();
1998       if (CheckDir(Dir)) {
1999         if (IsSystem)
2000           *IsSystem = BestPrefixLength && isSystem(DL.getDirCharacteristic());
2001         BestPrefixIsFramework = false;
2002       }
2003     } else if (DL.isFramework()) {
2004       StringRef Dir = DL.getFrameworkDirRef()->getName();
2005       if (CheckDir(Dir)) {
2006         if (IsSystem)
2007           *IsSystem = BestPrefixLength && isSystem(DL.getDirCharacteristic());
2008         BestPrefixIsFramework = true;
2009       }
2010     }
2011   }
2012 
2013   // Try to shorten include path using TUs directory, if we couldn't find any
2014   // suitable prefix in include search paths.
2015   if (!BestPrefixLength && CheckDir(path::parent_path(MainFile))) {
2016     if (IsSystem)
2017       *IsSystem = false;
2018     BestPrefixIsFramework = false;
2019   }
2020 
2021   // Try resolving resulting filename via reverse search in header maps,
2022   // key from header name is user preferred name for the include file.
2023   StringRef Filename = File.drop_front(BestPrefixLength);
2024   for (const DirectoryLookup &DL : search_dir_range()) {
2025     if (!DL.isHeaderMap())
2026       continue;
2027 
2028     StringRef SpelledFilename =
2029         DL.getHeaderMap()->reverseLookupFilename(Filename);
2030     if (!SpelledFilename.empty()) {
2031       Filename = SpelledFilename;
2032       BestPrefixIsFramework = false;
2033       break;
2034     }
2035   }
2036 
2037   // If the best prefix is a framework path, we need to compute the proper
2038   // include spelling for the framework header.
2039   bool IsPrivateHeader;
2040   SmallString<128> FrameworkName, IncludeSpelling;
2041   if (BestPrefixIsFramework &&
2042       isFrameworkStylePath(Filename, IsPrivateHeader, FrameworkName,
2043                            IncludeSpelling)) {
2044     Filename = IncludeSpelling;
2045   }
2046   return path::convert_to_slash(Filename);
2047 }
2048