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