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