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