1 //===--- HeaderSearch.cpp - Resolve Header File Locations ---===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements the DirectoryLookup and HeaderSearch interfaces.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Lex/HeaderSearch.h"
15 #include "clang/Basic/FileManager.h"
16 #include "clang/Basic/IdentifierTable.h"
17 #include "clang/Lex/ExternalPreprocessorSource.h"
18 #include "clang/Lex/HeaderMap.h"
19 #include "clang/Lex/HeaderSearchOptions.h"
20 #include "clang/Lex/LexDiagnostic.h"
21 #include "clang/Lex/Lexer.h"
22 #include "clang/Lex/Preprocessor.h"
23 #include "llvm/ADT/APInt.h"
24 #include "llvm/ADT/Hashing.h"
25 #include "llvm/ADT/SmallString.h"
26 #include "llvm/Support/Capacity.h"
27 #include "llvm/Support/FileSystem.h"
28 #include "llvm/Support/Path.h"
29 #include <cstdio>
30 #include <utility>
31 #if defined(LLVM_ON_UNIX)
32 #include <limits.h>
33 #endif
34 using namespace clang;
35 
36 const IdentifierInfo *
37 HeaderFileInfo::getControllingMacro(ExternalPreprocessorSource *External) {
38   if (ControllingMacro) {
39     if (ControllingMacro->isOutOfDate()) {
40       assert(External && "We must have an external source if we have a "
41                          "controlling macro that is out of date.");
42       External->updateOutOfDateIdentifier(
43           *const_cast<IdentifierInfo *>(ControllingMacro));
44     }
45     return ControllingMacro;
46   }
47 
48   if (!ControllingMacroID || !External)
49     return nullptr;
50 
51   ControllingMacro = External->GetIdentifier(ControllingMacroID);
52   return ControllingMacro;
53 }
54 
55 ExternalHeaderFileInfoSource::~ExternalHeaderFileInfoSource() {}
56 
57 HeaderSearch::HeaderSearch(IntrusiveRefCntPtr<HeaderSearchOptions> HSOpts,
58                            SourceManager &SourceMgr, DiagnosticsEngine &Diags,
59                            const LangOptions &LangOpts,
60                            const TargetInfo *Target)
61     : HSOpts(std::move(HSOpts)), Diags(Diags),
62       FileMgr(SourceMgr.getFileManager()), FrameworkMap(64),
63       ModMap(SourceMgr, Diags, LangOpts, Target, *this) {
64   AngledDirIdx = 0;
65   SystemDirIdx = 0;
66   NoCurDirSearch = false;
67 
68   ExternalLookup = nullptr;
69   ExternalSource = nullptr;
70   NumIncluded = 0;
71   NumMultiIncludeFileOptzn = 0;
72   NumFrameworkLookups = NumSubFrameworkLookups = 0;
73 }
74 
75 HeaderSearch::~HeaderSearch() {
76   // Delete headermaps.
77   for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
78     delete HeaderMaps[i].second;
79 }
80 
81 void HeaderSearch::PrintStats() {
82   fprintf(stderr, "\n*** HeaderSearch Stats:\n");
83   fprintf(stderr, "%d files tracked.\n", (int)FileInfo.size());
84   unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0;
85   for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) {
86     NumOnceOnlyFiles += FileInfo[i].isImport;
87     if (MaxNumIncludes < FileInfo[i].NumIncludes)
88       MaxNumIncludes = FileInfo[i].NumIncludes;
89     NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1;
90   }
91   fprintf(stderr, "  %d #import/#pragma once files.\n", NumOnceOnlyFiles);
92   fprintf(stderr, "  %d included exactly once.\n", NumSingleIncludedFiles);
93   fprintf(stderr, "  %d max times a file is included.\n", MaxNumIncludes);
94 
95   fprintf(stderr, "  %d #include/#include_next/#import.\n", NumIncluded);
96   fprintf(stderr, "    %d #includes skipped due to"
97           " the multi-include optimization.\n", NumMultiIncludeFileOptzn);
98 
99   fprintf(stderr, "%d framework lookups.\n", NumFrameworkLookups);
100   fprintf(stderr, "%d subframework lookups.\n", NumSubFrameworkLookups);
101 }
102 
103 /// CreateHeaderMap - This method returns a HeaderMap for the specified
104 /// FileEntry, uniquing them through the 'HeaderMaps' datastructure.
105 const HeaderMap *HeaderSearch::CreateHeaderMap(const FileEntry *FE) {
106   // We expect the number of headermaps to be small, and almost always empty.
107   // If it ever grows, use of a linear search should be re-evaluated.
108   if (!HeaderMaps.empty()) {
109     for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
110       // Pointer equality comparison of FileEntries works because they are
111       // already uniqued by inode.
112       if (HeaderMaps[i].first == FE)
113         return HeaderMaps[i].second;
114   }
115 
116   if (const HeaderMap *HM = HeaderMap::Create(FE, FileMgr)) {
117     HeaderMaps.push_back(std::make_pair(FE, HM));
118     return HM;
119   }
120 
121   return nullptr;
122 }
123 
124 /// \brief Get filenames for all registered header maps.
125 void HeaderSearch::getHeaderMapFileNames(
126     SmallVectorImpl<std::string> &Names) const {
127   for (auto &HM : HeaderMaps)
128     Names.push_back(HM.first->getName());
129 }
130 
131 std::string HeaderSearch::getModuleFileName(Module *Module) {
132   const FileEntry *ModuleMap =
133       getModuleMap().getModuleMapFileForUniquing(Module);
134   return getModuleFileName(Module->Name, ModuleMap->getName(),
135                            /*UsePrebuiltPath*/false);
136 }
137 
138 std::string HeaderSearch::getModuleFileName(StringRef ModuleName,
139                                             StringRef ModuleMapPath,
140                                             bool UsePrebuiltPath) {
141   if (UsePrebuiltPath) {
142     if (HSOpts->PrebuiltModulePaths.empty())
143       return std::string();
144 
145     // Go though each prebuilt module path and try to find the pcm file.
146     for (const std::string &Dir : HSOpts->PrebuiltModulePaths) {
147       SmallString<256> Result(Dir);
148       llvm::sys::fs::make_absolute(Result);
149 
150       llvm::sys::path::append(Result, ModuleName + ".pcm");
151       if (getFileMgr().getFile(Result.str()))
152         return Result.str().str();
153     }
154     return std::string();
155   }
156 
157   // If we don't have a module cache path or aren't supposed to use one, we
158   // can't do anything.
159   if (getModuleCachePath().empty())
160     return std::string();
161 
162   SmallString<256> Result(getModuleCachePath());
163   llvm::sys::fs::make_absolute(Result);
164 
165   if (HSOpts->DisableModuleHash) {
166     llvm::sys::path::append(Result, ModuleName + ".pcm");
167   } else {
168     // Construct the name <ModuleName>-<hash of ModuleMapPath>.pcm which should
169     // ideally be globally unique to this particular module. Name collisions
170     // in the hash are safe (because any translation unit can only import one
171     // module with each name), but result in a loss of caching.
172     //
173     // To avoid false-negatives, we form as canonical a path as we can, and map
174     // to lower-case in case we're on a case-insensitive file system.
175    auto *Dir =
176         FileMgr.getDirectory(llvm::sys::path::parent_path(ModuleMapPath));
177     if (!Dir)
178       return std::string();
179     auto DirName = FileMgr.getCanonicalName(Dir);
180     auto FileName = llvm::sys::path::filename(ModuleMapPath);
181 
182     llvm::hash_code Hash =
183       llvm::hash_combine(DirName.lower(), FileName.lower());
184 
185     SmallString<128> HashStr;
186     llvm::APInt(64, size_t(Hash)).toStringUnsigned(HashStr, /*Radix*/36);
187     llvm::sys::path::append(Result, ModuleName + "-" + HashStr + ".pcm");
188   }
189   return Result.str().str();
190 }
191 
192 Module *HeaderSearch::lookupModule(StringRef ModuleName, bool AllowSearch) {
193   // Look in the module map to determine if there is a module by this name.
194   Module *Module = ModMap.findModule(ModuleName);
195   if (Module || !AllowSearch || !HSOpts->ImplicitModuleMaps)
196     return Module;
197 
198   // Look through the various header search paths to load any available module
199   // maps, searching for a module map that describes this module.
200   for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
201     if (SearchDirs[Idx].isFramework()) {
202       // Search for or infer a module map for a framework.
203       SmallString<128> FrameworkDirName;
204       FrameworkDirName += SearchDirs[Idx].getFrameworkDir()->getName();
205       llvm::sys::path::append(FrameworkDirName, ModuleName + ".framework");
206       if (const DirectoryEntry *FrameworkDir
207             = FileMgr.getDirectory(FrameworkDirName)) {
208         bool IsSystem
209           = SearchDirs[Idx].getDirCharacteristic() != SrcMgr::C_User;
210         Module = loadFrameworkModule(ModuleName, FrameworkDir, IsSystem);
211         if (Module)
212           break;
213       }
214     }
215 
216     // FIXME: Figure out how header maps and module maps will work together.
217 
218     // Only deal with normal search directories.
219     if (!SearchDirs[Idx].isNormalDir())
220       continue;
221 
222     bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
223     // Search for a module map file in this directory.
224     if (loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem,
225                           /*IsFramework*/false) == LMM_NewlyLoaded) {
226       // We just loaded a module map file; check whether the module is
227       // available now.
228       Module = ModMap.findModule(ModuleName);
229       if (Module)
230         break;
231     }
232 
233     // Search for a module map in a subdirectory with the same name as the
234     // module.
235     SmallString<128> NestedModuleMapDirName;
236     NestedModuleMapDirName = SearchDirs[Idx].getDir()->getName();
237     llvm::sys::path::append(NestedModuleMapDirName, ModuleName);
238     if (loadModuleMapFile(NestedModuleMapDirName, IsSystem,
239                           /*IsFramework*/false) == LMM_NewlyLoaded){
240       // If we just loaded a module map file, look for the module again.
241       Module = ModMap.findModule(ModuleName);
242       if (Module)
243         break;
244     }
245 
246     // If we've already performed the exhaustive search for module maps in this
247     // search directory, don't do it again.
248     if (SearchDirs[Idx].haveSearchedAllModuleMaps())
249       continue;
250 
251     // Load all module maps in the immediate subdirectories of this search
252     // directory.
253     loadSubdirectoryModuleMaps(SearchDirs[Idx]);
254 
255     // Look again for the module.
256     Module = ModMap.findModule(ModuleName);
257     if (Module)
258       break;
259   }
260 
261   return Module;
262 }
263 
264 //===----------------------------------------------------------------------===//
265 // File lookup within a DirectoryLookup scope
266 //===----------------------------------------------------------------------===//
267 
268 /// getName - Return the directory or filename corresponding to this lookup
269 /// object.
270 StringRef DirectoryLookup::getName() const {
271   if (isNormalDir())
272     return getDir()->getName();
273   if (isFramework())
274     return getFrameworkDir()->getName();
275   assert(isHeaderMap() && "Unknown DirectoryLookup");
276   return getHeaderMap()->getFileName();
277 }
278 
279 const FileEntry *HeaderSearch::getFileAndSuggestModule(
280     StringRef FileName, SourceLocation IncludeLoc, const DirectoryEntry *Dir,
281     bool IsSystemHeaderDir, Module *RequestingModule,
282     ModuleMap::KnownHeader *SuggestedModule) {
283   // If we have a module map that might map this header, load it and
284   // check whether we'll have a suggestion for a module.
285   const FileEntry *File = getFileMgr().getFile(FileName, /*OpenFile=*/true);
286   if (!File)
287     return nullptr;
288 
289   // If there is a module that corresponds to this header, suggest it.
290   if (!findUsableModuleForHeader(File, Dir ? Dir : File->getDir(),
291                                  RequestingModule, SuggestedModule,
292                                  IsSystemHeaderDir))
293     return nullptr;
294 
295   return File;
296 }
297 
298 /// LookupFile - Lookup the specified file in this search path, returning it
299 /// if it exists or returning null if not.
300 const FileEntry *DirectoryLookup::LookupFile(
301     StringRef &Filename,
302     HeaderSearch &HS,
303     SourceLocation IncludeLoc,
304     SmallVectorImpl<char> *SearchPath,
305     SmallVectorImpl<char> *RelativePath,
306     Module *RequestingModule,
307     ModuleMap::KnownHeader *SuggestedModule,
308     bool &InUserSpecifiedSystemFramework,
309     bool &HasBeenMapped,
310     SmallVectorImpl<char> &MappedName) const {
311   InUserSpecifiedSystemFramework = false;
312   HasBeenMapped = false;
313 
314   SmallString<1024> TmpDir;
315   if (isNormalDir()) {
316     // Concatenate the requested file onto the directory.
317     TmpDir = getDir()->getName();
318     llvm::sys::path::append(TmpDir, Filename);
319     if (SearchPath) {
320       StringRef SearchPathRef(getDir()->getName());
321       SearchPath->clear();
322       SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
323     }
324     if (RelativePath) {
325       RelativePath->clear();
326       RelativePath->append(Filename.begin(), Filename.end());
327     }
328 
329     return HS.getFileAndSuggestModule(TmpDir, IncludeLoc, getDir(),
330                                       isSystemHeaderDirectory(),
331                                       RequestingModule, SuggestedModule);
332   }
333 
334   if (isFramework())
335     return DoFrameworkLookup(Filename, HS, SearchPath, RelativePath,
336                              RequestingModule, SuggestedModule,
337                              InUserSpecifiedSystemFramework);
338 
339   assert(isHeaderMap() && "Unknown directory lookup");
340   const HeaderMap *HM = getHeaderMap();
341   SmallString<1024> Path;
342   StringRef Dest = HM->lookupFilename(Filename, Path);
343   if (Dest.empty())
344     return nullptr;
345 
346   const FileEntry *Result;
347 
348   // Check if the headermap maps the filename to a framework include
349   // ("Foo.h" -> "Foo/Foo.h"), in which case continue header lookup using the
350   // framework include.
351   if (llvm::sys::path::is_relative(Dest)) {
352     MappedName.clear();
353     MappedName.append(Dest.begin(), Dest.end());
354     Filename = StringRef(MappedName.begin(), MappedName.size());
355     HasBeenMapped = true;
356     Result = HM->LookupFile(Filename, HS.getFileMgr());
357 
358   } else {
359     Result = HS.getFileMgr().getFile(Dest);
360   }
361 
362   if (Result) {
363     if (SearchPath) {
364       StringRef SearchPathRef(getName());
365       SearchPath->clear();
366       SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
367     }
368     if (RelativePath) {
369       RelativePath->clear();
370       RelativePath->append(Filename.begin(), Filename.end());
371     }
372   }
373   return Result;
374 }
375 
376 /// \brief Given a framework directory, find the top-most framework directory.
377 ///
378 /// \param FileMgr The file manager to use for directory lookups.
379 /// \param DirName The name of the framework directory.
380 /// \param SubmodulePath Will be populated with the submodule path from the
381 /// returned top-level module to the originally named framework.
382 static const DirectoryEntry *
383 getTopFrameworkDir(FileManager &FileMgr, StringRef DirName,
384                    SmallVectorImpl<std::string> &SubmodulePath) {
385   assert(llvm::sys::path::extension(DirName) == ".framework" &&
386          "Not a framework directory");
387 
388   // Note: as an egregious but useful hack we use the real path here, because
389   // frameworks moving between top-level frameworks to embedded frameworks tend
390   // to be symlinked, and we base the logical structure of modules on the
391   // physical layout. In particular, we need to deal with crazy includes like
392   //
393   //   #include <Foo/Frameworks/Bar.framework/Headers/Wibble.h>
394   //
395   // where 'Bar' used to be embedded in 'Foo', is now a top-level framework
396   // which one should access with, e.g.,
397   //
398   //   #include <Bar/Wibble.h>
399   //
400   // Similar issues occur when a top-level framework has moved into an
401   // embedded framework.
402   const DirectoryEntry *TopFrameworkDir = FileMgr.getDirectory(DirName);
403   DirName = FileMgr.getCanonicalName(TopFrameworkDir);
404   do {
405     // Get the parent directory name.
406     DirName = llvm::sys::path::parent_path(DirName);
407     if (DirName.empty())
408       break;
409 
410     // Determine whether this directory exists.
411     const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
412     if (!Dir)
413       break;
414 
415     // If this is a framework directory, then we're a subframework of this
416     // framework.
417     if (llvm::sys::path::extension(DirName) == ".framework") {
418       SubmodulePath.push_back(llvm::sys::path::stem(DirName));
419       TopFrameworkDir = Dir;
420     }
421   } while (true);
422 
423   return TopFrameworkDir;
424 }
425 
426 static bool needModuleLookup(Module *RequestingModule,
427                              bool HasSuggestedModule) {
428   return HasSuggestedModule ||
429          (RequestingModule && RequestingModule->NoUndeclaredIncludes);
430 }
431 
432 /// DoFrameworkLookup - Do a lookup of the specified file in the current
433 /// DirectoryLookup, which is a framework directory.
434 const FileEntry *DirectoryLookup::DoFrameworkLookup(
435     StringRef Filename, HeaderSearch &HS, SmallVectorImpl<char> *SearchPath,
436     SmallVectorImpl<char> *RelativePath, Module *RequestingModule,
437     ModuleMap::KnownHeader *SuggestedModule,
438     bool &InUserSpecifiedSystemFramework) const {
439   FileManager &FileMgr = HS.getFileMgr();
440 
441   // Framework names must have a '/' in the filename.
442   size_t SlashPos = Filename.find('/');
443   if (SlashPos == StringRef::npos) return nullptr;
444 
445   // Find out if this is the home for the specified framework, by checking
446   // HeaderSearch.  Possible answers are yes/no and unknown.
447   HeaderSearch::FrameworkCacheEntry &CacheEntry =
448     HS.LookupFrameworkCache(Filename.substr(0, SlashPos));
449 
450   // If it is known and in some other directory, fail.
451   if (CacheEntry.Directory && CacheEntry.Directory != getFrameworkDir())
452     return nullptr;
453 
454   // Otherwise, construct the path to this framework dir.
455 
456   // FrameworkName = "/System/Library/Frameworks/"
457   SmallString<1024> FrameworkName;
458   FrameworkName += getFrameworkDir()->getName();
459   if (FrameworkName.empty() || FrameworkName.back() != '/')
460     FrameworkName.push_back('/');
461 
462   // FrameworkName = "/System/Library/Frameworks/Cocoa"
463   StringRef ModuleName(Filename.begin(), SlashPos);
464   FrameworkName += ModuleName;
465 
466   // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/"
467   FrameworkName += ".framework/";
468 
469   // If the cache entry was unresolved, populate it now.
470   if (!CacheEntry.Directory) {
471     HS.IncrementFrameworkLookupCount();
472 
473     // If the framework dir doesn't exist, we fail.
474     const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName);
475     if (!Dir) return nullptr;
476 
477     // Otherwise, if it does, remember that this is the right direntry for this
478     // framework.
479     CacheEntry.Directory = getFrameworkDir();
480 
481     // If this is a user search directory, check if the framework has been
482     // user-specified as a system framework.
483     if (getDirCharacteristic() == SrcMgr::C_User) {
484       SmallString<1024> SystemFrameworkMarker(FrameworkName);
485       SystemFrameworkMarker += ".system_framework";
486       if (llvm::sys::fs::exists(SystemFrameworkMarker)) {
487         CacheEntry.IsUserSpecifiedSystemFramework = true;
488       }
489     }
490   }
491 
492   // Set the 'user-specified system framework' flag.
493   InUserSpecifiedSystemFramework = CacheEntry.IsUserSpecifiedSystemFramework;
494 
495   if (RelativePath) {
496     RelativePath->clear();
497     RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
498   }
499 
500   // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"
501   unsigned OrigSize = FrameworkName.size();
502 
503   FrameworkName += "Headers/";
504 
505   if (SearchPath) {
506     SearchPath->clear();
507     // Without trailing '/'.
508     SearchPath->append(FrameworkName.begin(), FrameworkName.end()-1);
509   }
510 
511   FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end());
512   const FileEntry *FE = FileMgr.getFile(FrameworkName,
513                                         /*openFile=*/!SuggestedModule);
514   if (!FE) {
515     // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"
516     const char *Private = "Private";
517     FrameworkName.insert(FrameworkName.begin()+OrigSize, Private,
518                          Private+strlen(Private));
519     if (SearchPath)
520       SearchPath->insert(SearchPath->begin()+OrigSize, Private,
521                          Private+strlen(Private));
522 
523     FE = FileMgr.getFile(FrameworkName, /*openFile=*/!SuggestedModule);
524   }
525 
526   // If we found the header and are allowed to suggest a module, do so now.
527   if (FE && needModuleLookup(RequestingModule, SuggestedModule)) {
528     // Find the framework in which this header occurs.
529     StringRef FrameworkPath = FE->getDir()->getName();
530     bool FoundFramework = false;
531     do {
532       // Determine whether this directory exists.
533       const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkPath);
534       if (!Dir)
535         break;
536 
537       // If this is a framework directory, then we're a subframework of this
538       // framework.
539       if (llvm::sys::path::extension(FrameworkPath) == ".framework") {
540         FoundFramework = true;
541         break;
542       }
543 
544       // Get the parent directory name.
545       FrameworkPath = llvm::sys::path::parent_path(FrameworkPath);
546       if (FrameworkPath.empty())
547         break;
548     } while (true);
549 
550     bool IsSystem = getDirCharacteristic() != SrcMgr::C_User;
551     if (FoundFramework) {
552       if (!HS.findUsableModuleForFrameworkHeader(
553               FE, FrameworkPath, RequestingModule, SuggestedModule, IsSystem))
554         return nullptr;
555     } else {
556       if (!HS.findUsableModuleForHeader(FE, getDir(), RequestingModule,
557                                         SuggestedModule, IsSystem))
558         return nullptr;
559     }
560   }
561   return FE;
562 }
563 
564 void HeaderSearch::setTarget(const TargetInfo &Target) {
565   ModMap.setTarget(Target);
566 }
567 
568 
569 //===----------------------------------------------------------------------===//
570 // Header File Location.
571 //===----------------------------------------------------------------------===//
572 
573 /// \brief Return true with a diagnostic if the file that MSVC would have found
574 /// fails to match the one that Clang would have found with MSVC header search
575 /// disabled.
576 static bool checkMSVCHeaderSearch(DiagnosticsEngine &Diags,
577                                   const FileEntry *MSFE, const FileEntry *FE,
578                                   SourceLocation IncludeLoc) {
579   if (MSFE && FE != MSFE) {
580     Diags.Report(IncludeLoc, diag::ext_pp_include_search_ms) << MSFE->getName();
581     return true;
582   }
583   return false;
584 }
585 
586 static const char *copyString(StringRef Str, llvm::BumpPtrAllocator &Alloc) {
587   assert(!Str.empty());
588   char *CopyStr = Alloc.Allocate<char>(Str.size()+1);
589   std::copy(Str.begin(), Str.end(), CopyStr);
590   CopyStr[Str.size()] = '\0';
591   return CopyStr;
592 }
593 
594 /// LookupFile - Given a "foo" or \<foo> reference, look up the indicated file,
595 /// return null on failure.  isAngled indicates whether the file reference is
596 /// for system \#include's or not (i.e. using <> instead of ""). Includers, if
597 /// non-empty, indicates where the \#including file(s) are, in case a relative
598 /// search is needed. Microsoft mode will pass all \#including files.
599 const FileEntry *HeaderSearch::LookupFile(
600     StringRef Filename, SourceLocation IncludeLoc, bool isAngled,
601     const DirectoryLookup *FromDir, const DirectoryLookup *&CurDir,
602     ArrayRef<std::pair<const FileEntry *, const DirectoryEntry *>> Includers,
603     SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
604     Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule,
605     bool SkipCache, bool BuildSystemModule) {
606   if (SuggestedModule)
607     *SuggestedModule = ModuleMap::KnownHeader();
608 
609   // If 'Filename' is absolute, check to see if it exists and no searching.
610   if (llvm::sys::path::is_absolute(Filename)) {
611     CurDir = nullptr;
612 
613     // If this was an #include_next "/absolute/file", fail.
614     if (FromDir) return nullptr;
615 
616     if (SearchPath)
617       SearchPath->clear();
618     if (RelativePath) {
619       RelativePath->clear();
620       RelativePath->append(Filename.begin(), Filename.end());
621     }
622     // Otherwise, just return the file.
623     return getFileAndSuggestModule(Filename, IncludeLoc, nullptr,
624                                    /*IsSystemHeaderDir*/false,
625                                    RequestingModule, SuggestedModule);
626   }
627 
628   // This is the header that MSVC's header search would have found.
629   const FileEntry *MSFE = nullptr;
630   ModuleMap::KnownHeader MSSuggestedModule;
631 
632   // Unless disabled, check to see if the file is in the #includer's
633   // directory.  This cannot be based on CurDir, because each includer could be
634   // a #include of a subdirectory (#include "foo/bar.h") and a subsequent
635   // include of "baz.h" should resolve to "whatever/foo/baz.h".
636   // This search is not done for <> headers.
637   if (!Includers.empty() && !isAngled && !NoCurDirSearch) {
638     SmallString<1024> TmpDir;
639     bool First = true;
640     for (const auto &IncluderAndDir : Includers) {
641       const FileEntry *Includer = IncluderAndDir.first;
642 
643       // Concatenate the requested file onto the directory.
644       // FIXME: Portability.  Filename concatenation should be in sys::Path.
645       TmpDir = IncluderAndDir.second->getName();
646       TmpDir.push_back('/');
647       TmpDir.append(Filename.begin(), Filename.end());
648 
649       // FIXME: We don't cache the result of getFileInfo across the call to
650       // getFileAndSuggestModule, because it's a reference to an element of
651       // a container that could be reallocated across this call.
652       //
653       // If we have no includer, that means we're processing a #include
654       // from a module build. We should treat this as a system header if we're
655       // building a [system] module.
656       bool IncluderIsSystemHeader =
657           Includer ? getFileInfo(Includer).DirInfo != SrcMgr::C_User :
658           BuildSystemModule;
659       if (const FileEntry *FE = getFileAndSuggestModule(
660               TmpDir, IncludeLoc, IncluderAndDir.second, IncluderIsSystemHeader,
661               RequestingModule, SuggestedModule)) {
662         if (!Includer) {
663           assert(First && "only first includer can have no file");
664           return FE;
665         }
666 
667         // Leave CurDir unset.
668         // This file is a system header or C++ unfriendly if the old file is.
669         //
670         // Note that we only use one of FromHFI/ToHFI at once, due to potential
671         // reallocation of the underlying vector potentially making the first
672         // reference binding dangling.
673         HeaderFileInfo &FromHFI = getFileInfo(Includer);
674         unsigned DirInfo = FromHFI.DirInfo;
675         bool IndexHeaderMapHeader = FromHFI.IndexHeaderMapHeader;
676         StringRef Framework = FromHFI.Framework;
677 
678         HeaderFileInfo &ToHFI = getFileInfo(FE);
679         ToHFI.DirInfo = DirInfo;
680         ToHFI.IndexHeaderMapHeader = IndexHeaderMapHeader;
681         ToHFI.Framework = Framework;
682 
683         if (SearchPath) {
684           StringRef SearchPathRef(IncluderAndDir.second->getName());
685           SearchPath->clear();
686           SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
687         }
688         if (RelativePath) {
689           RelativePath->clear();
690           RelativePath->append(Filename.begin(), Filename.end());
691         }
692         if (First)
693           return FE;
694 
695         // Otherwise, we found the path via MSVC header search rules.  If
696         // -Wmsvc-include is enabled, we have to keep searching to see if we
697         // would've found this header in -I or -isystem directories.
698         if (Diags.isIgnored(diag::ext_pp_include_search_ms, IncludeLoc)) {
699           return FE;
700         } else {
701           MSFE = FE;
702           if (SuggestedModule) {
703             MSSuggestedModule = *SuggestedModule;
704             *SuggestedModule = ModuleMap::KnownHeader();
705           }
706           break;
707         }
708       }
709       First = false;
710     }
711   }
712 
713   CurDir = nullptr;
714 
715   // If this is a system #include, ignore the user #include locs.
716   unsigned i = isAngled ? AngledDirIdx : 0;
717 
718   // If this is a #include_next request, start searching after the directory the
719   // file was found in.
720   if (FromDir)
721     i = FromDir-&SearchDirs[0];
722 
723   // Cache all of the lookups performed by this method.  Many headers are
724   // multiply included, and the "pragma once" optimization prevents them from
725   // being relex/pp'd, but they would still have to search through a
726   // (potentially huge) series of SearchDirs to find it.
727   LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename];
728 
729   // If the entry has been previously looked up, the first value will be
730   // non-zero.  If the value is equal to i (the start point of our search), then
731   // this is a matching hit.
732   if (!SkipCache && CacheLookup.StartIdx == i+1) {
733     // Skip querying potentially lots of directories for this lookup.
734     i = CacheLookup.HitIdx;
735     if (CacheLookup.MappedName)
736       Filename = CacheLookup.MappedName;
737   } else {
738     // Otherwise, this is the first query, or the previous query didn't match
739     // our search start.  We will fill in our found location below, so prime the
740     // start point value.
741     CacheLookup.reset(/*StartIdx=*/i+1);
742   }
743 
744   SmallString<64> MappedName;
745 
746   // Check each directory in sequence to see if it contains this file.
747   for (; i != SearchDirs.size(); ++i) {
748     bool InUserSpecifiedSystemFramework = false;
749     bool HasBeenMapped = false;
750     const FileEntry *FE = SearchDirs[i].LookupFile(
751         Filename, *this, IncludeLoc, SearchPath, RelativePath, RequestingModule,
752         SuggestedModule, InUserSpecifiedSystemFramework, HasBeenMapped,
753         MappedName);
754     if (HasBeenMapped) {
755       CacheLookup.MappedName =
756           copyString(Filename, LookupFileCache.getAllocator());
757     }
758     if (!FE) continue;
759 
760     CurDir = &SearchDirs[i];
761 
762     // This file is a system header or C++ unfriendly if the dir is.
763     HeaderFileInfo &HFI = getFileInfo(FE);
764     HFI.DirInfo = CurDir->getDirCharacteristic();
765 
766     // If the directory characteristic is User but this framework was
767     // user-specified to be treated as a system framework, promote the
768     // characteristic.
769     if (HFI.DirInfo == SrcMgr::C_User && InUserSpecifiedSystemFramework)
770       HFI.DirInfo = SrcMgr::C_System;
771 
772     // If the filename matches a known system header prefix, override
773     // whether the file is a system header.
774     for (unsigned j = SystemHeaderPrefixes.size(); j; --j) {
775       if (Filename.startswith(SystemHeaderPrefixes[j-1].first)) {
776         HFI.DirInfo = SystemHeaderPrefixes[j-1].second ? SrcMgr::C_System
777                                                        : SrcMgr::C_User;
778         break;
779       }
780     }
781 
782     // If this file is found in a header map and uses the framework style of
783     // includes, then this header is part of a framework we're building.
784     if (CurDir->isIndexHeaderMap()) {
785       size_t SlashPos = Filename.find('/');
786       if (SlashPos != StringRef::npos) {
787         HFI.IndexHeaderMapHeader = 1;
788         HFI.Framework = getUniqueFrameworkName(StringRef(Filename.begin(),
789                                                          SlashPos));
790       }
791     }
792 
793     if (checkMSVCHeaderSearch(Diags, MSFE, FE, IncludeLoc)) {
794       if (SuggestedModule)
795         *SuggestedModule = MSSuggestedModule;
796       return MSFE;
797     }
798 
799     // Remember this location for the next lookup we do.
800     CacheLookup.HitIdx = i;
801     return FE;
802   }
803 
804   // If we are including a file with a quoted include "foo.h" from inside
805   // a header in a framework that is currently being built, and we couldn't
806   // resolve "foo.h" any other way, change the include to <Foo/foo.h>, where
807   // "Foo" is the name of the framework in which the including header was found.
808   if (!Includers.empty() && Includers.front().first && !isAngled &&
809       Filename.find('/') == StringRef::npos) {
810     HeaderFileInfo &IncludingHFI = getFileInfo(Includers.front().first);
811     if (IncludingHFI.IndexHeaderMapHeader) {
812       SmallString<128> ScratchFilename;
813       ScratchFilename += IncludingHFI.Framework;
814       ScratchFilename += '/';
815       ScratchFilename += Filename;
816 
817       const FileEntry *FE =
818           LookupFile(ScratchFilename, IncludeLoc, /*isAngled=*/true, FromDir,
819                      CurDir, Includers.front(), SearchPath, RelativePath,
820                      RequestingModule, SuggestedModule);
821 
822       if (checkMSVCHeaderSearch(Diags, MSFE, FE, IncludeLoc)) {
823         if (SuggestedModule)
824           *SuggestedModule = MSSuggestedModule;
825         return MSFE;
826       }
827 
828       LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename];
829       CacheLookup.HitIdx = LookupFileCache[ScratchFilename].HitIdx;
830       // FIXME: SuggestedModule.
831       return FE;
832     }
833   }
834 
835   if (checkMSVCHeaderSearch(Diags, MSFE, nullptr, IncludeLoc)) {
836     if (SuggestedModule)
837       *SuggestedModule = MSSuggestedModule;
838     return MSFE;
839   }
840 
841   // Otherwise, didn't find it. Remember we didn't find this.
842   CacheLookup.HitIdx = SearchDirs.size();
843   return nullptr;
844 }
845 
846 /// LookupSubframeworkHeader - Look up a subframework for the specified
847 /// \#include file.  For example, if \#include'ing <HIToolbox/HIToolbox.h> from
848 /// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
849 /// is a subframework within Carbon.framework.  If so, return the FileEntry
850 /// for the designated file, otherwise return null.
851 const FileEntry *HeaderSearch::
852 LookupSubframeworkHeader(StringRef Filename,
853                          const FileEntry *ContextFileEnt,
854                          SmallVectorImpl<char> *SearchPath,
855                          SmallVectorImpl<char> *RelativePath,
856                          Module *RequestingModule,
857                          ModuleMap::KnownHeader *SuggestedModule) {
858   assert(ContextFileEnt && "No context file?");
859 
860   // Framework names must have a '/' in the filename.  Find it.
861   // FIXME: Should we permit '\' on Windows?
862   size_t SlashPos = Filename.find('/');
863   if (SlashPos == StringRef::npos) return nullptr;
864 
865   // Look up the base framework name of the ContextFileEnt.
866   StringRef ContextName = ContextFileEnt->getName();
867 
868   // If the context info wasn't a framework, couldn't be a subframework.
869   const unsigned DotFrameworkLen = 10;
870   auto FrameworkPos = ContextName.find(".framework");
871   if (FrameworkPos == StringRef::npos ||
872       (ContextName[FrameworkPos + DotFrameworkLen] != '/' &&
873        ContextName[FrameworkPos + DotFrameworkLen] != '\\'))
874     return nullptr;
875 
876   SmallString<1024> FrameworkName(ContextName.data(), ContextName.data() +
877                                                           FrameworkPos +
878                                                           DotFrameworkLen + 1);
879 
880   // Append Frameworks/HIToolbox.framework/
881   FrameworkName += "Frameworks/";
882   FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos);
883   FrameworkName += ".framework/";
884 
885   auto &CacheLookup =
886       *FrameworkMap.insert(std::make_pair(Filename.substr(0, SlashPos),
887                                           FrameworkCacheEntry())).first;
888 
889   // Some other location?
890   if (CacheLookup.second.Directory &&
891       CacheLookup.first().size() == FrameworkName.size() &&
892       memcmp(CacheLookup.first().data(), &FrameworkName[0],
893              CacheLookup.first().size()) != 0)
894     return nullptr;
895 
896   // Cache subframework.
897   if (!CacheLookup.second.Directory) {
898     ++NumSubFrameworkLookups;
899 
900     // If the framework dir doesn't exist, we fail.
901     const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName);
902     if (!Dir) return nullptr;
903 
904     // Otherwise, if it does, remember that this is the right direntry for this
905     // framework.
906     CacheLookup.second.Directory = Dir;
907   }
908 
909   const FileEntry *FE = nullptr;
910 
911   if (RelativePath) {
912     RelativePath->clear();
913     RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
914   }
915 
916   // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
917   SmallString<1024> HeadersFilename(FrameworkName);
918   HeadersFilename += "Headers/";
919   if (SearchPath) {
920     SearchPath->clear();
921     // Without trailing '/'.
922     SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
923   }
924 
925   HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
926   if (!(FE = FileMgr.getFile(HeadersFilename, /*openFile=*/true))) {
927 
928     // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
929     HeadersFilename = FrameworkName;
930     HeadersFilename += "PrivateHeaders/";
931     if (SearchPath) {
932       SearchPath->clear();
933       // Without trailing '/'.
934       SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
935     }
936 
937     HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
938     if (!(FE = FileMgr.getFile(HeadersFilename, /*openFile=*/true)))
939       return nullptr;
940   }
941 
942   // This file is a system header or C++ unfriendly if the old file is.
943   //
944   // Note that the temporary 'DirInfo' is required here, as either call to
945   // getFileInfo could resize the vector and we don't want to rely on order
946   // of evaluation.
947   unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo;
948   getFileInfo(FE).DirInfo = DirInfo;
949 
950   FrameworkName.pop_back(); // remove the trailing '/'
951   if (!findUsableModuleForFrameworkHeader(FE, FrameworkName, RequestingModule,
952                                           SuggestedModule, /*IsSystem*/ false))
953     return nullptr;
954 
955   return FE;
956 }
957 
958 //===----------------------------------------------------------------------===//
959 // File Info Management.
960 //===----------------------------------------------------------------------===//
961 
962 /// \brief Merge the header file info provided by \p OtherHFI into the current
963 /// header file info (\p HFI)
964 static void mergeHeaderFileInfo(HeaderFileInfo &HFI,
965                                 const HeaderFileInfo &OtherHFI) {
966   assert(OtherHFI.External && "expected to merge external HFI");
967 
968   HFI.isImport |= OtherHFI.isImport;
969   HFI.isPragmaOnce |= OtherHFI.isPragmaOnce;
970   HFI.isModuleHeader |= OtherHFI.isModuleHeader;
971   HFI.NumIncludes += OtherHFI.NumIncludes;
972 
973   if (!HFI.ControllingMacro && !HFI.ControllingMacroID) {
974     HFI.ControllingMacro = OtherHFI.ControllingMacro;
975     HFI.ControllingMacroID = OtherHFI.ControllingMacroID;
976   }
977 
978   HFI.DirInfo = OtherHFI.DirInfo;
979   HFI.External = (!HFI.IsValid || HFI.External);
980   HFI.IsValid = true;
981   HFI.IndexHeaderMapHeader = OtherHFI.IndexHeaderMapHeader;
982 
983   if (HFI.Framework.empty())
984     HFI.Framework = OtherHFI.Framework;
985 }
986 
987 /// getFileInfo - Return the HeaderFileInfo structure for the specified
988 /// FileEntry.
989 HeaderFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) {
990   if (FE->getUID() >= FileInfo.size())
991     FileInfo.resize(FE->getUID() + 1);
992 
993   HeaderFileInfo *HFI = &FileInfo[FE->getUID()];
994   // FIXME: Use a generation count to check whether this is really up to date.
995   if (ExternalSource && !HFI->Resolved) {
996     HFI->Resolved = true;
997     auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE);
998 
999     HFI = &FileInfo[FE->getUID()];
1000     if (ExternalHFI.External)
1001       mergeHeaderFileInfo(*HFI, ExternalHFI);
1002   }
1003 
1004   HFI->IsValid = true;
1005   // We have local information about this header file, so it's no longer
1006   // strictly external.
1007   HFI->External = false;
1008   return *HFI;
1009 }
1010 
1011 const HeaderFileInfo *
1012 HeaderSearch::getExistingFileInfo(const FileEntry *FE,
1013                                   bool WantExternal) const {
1014   // If we have an external source, ensure we have the latest information.
1015   // FIXME: Use a generation count to check whether this is really up to date.
1016   HeaderFileInfo *HFI;
1017   if (ExternalSource) {
1018     if (FE->getUID() >= FileInfo.size()) {
1019       if (!WantExternal)
1020         return nullptr;
1021       FileInfo.resize(FE->getUID() + 1);
1022     }
1023 
1024     HFI = &FileInfo[FE->getUID()];
1025     if (!WantExternal && (!HFI->IsValid || HFI->External))
1026       return nullptr;
1027     if (!HFI->Resolved) {
1028       HFI->Resolved = true;
1029       auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE);
1030 
1031       HFI = &FileInfo[FE->getUID()];
1032       if (ExternalHFI.External)
1033         mergeHeaderFileInfo(*HFI, ExternalHFI);
1034     }
1035   } else if (FE->getUID() >= FileInfo.size()) {
1036     return nullptr;
1037   } else {
1038     HFI = &FileInfo[FE->getUID()];
1039   }
1040 
1041   if (!HFI->IsValid || (HFI->External && !WantExternal))
1042     return nullptr;
1043 
1044   return HFI;
1045 }
1046 
1047 bool HeaderSearch::isFileMultipleIncludeGuarded(const FileEntry *File) {
1048   // Check if we've ever seen this file as a header.
1049   if (auto *HFI = getExistingFileInfo(File))
1050     return HFI->isPragmaOnce || HFI->isImport || HFI->ControllingMacro ||
1051            HFI->ControllingMacroID;
1052   return false;
1053 }
1054 
1055 void HeaderSearch::MarkFileModuleHeader(const FileEntry *FE,
1056                                         ModuleMap::ModuleHeaderRole Role,
1057                                         bool isCompilingModuleHeader) {
1058   bool isModularHeader = !(Role & ModuleMap::TextualHeader);
1059 
1060   // Don't mark the file info as non-external if there's nothing to change.
1061   if (!isCompilingModuleHeader) {
1062     if (!isModularHeader)
1063       return;
1064     auto *HFI = getExistingFileInfo(FE);
1065     if (HFI && HFI->isModuleHeader)
1066       return;
1067   }
1068 
1069   auto &HFI = getFileInfo(FE);
1070   HFI.isModuleHeader |= isModularHeader;
1071   HFI.isCompilingModuleHeader |= isCompilingModuleHeader;
1072 }
1073 
1074 bool HeaderSearch::ShouldEnterIncludeFile(Preprocessor &PP,
1075                                           const FileEntry *File,
1076                                           bool isImport, Module *M) {
1077   ++NumIncluded; // Count # of attempted #includes.
1078 
1079   // Get information about this file.
1080   HeaderFileInfo &FileInfo = getFileInfo(File);
1081 
1082   // If this is a #import directive, check that we have not already imported
1083   // this header.
1084   if (isImport) {
1085     // If this has already been imported, don't import it again.
1086     FileInfo.isImport = true;
1087 
1088     // Has this already been #import'ed or #include'd?
1089     if (FileInfo.NumIncludes) return false;
1090   } else {
1091     // Otherwise, if this is a #include of a file that was previously #import'd
1092     // or if this is the second #include of a #pragma once file, ignore it.
1093     if (FileInfo.isImport)
1094       return false;
1095   }
1096 
1097   // Next, check to see if the file is wrapped with #ifndef guards.  If so, and
1098   // if the macro that guards it is defined, we know the #include has no effect.
1099   if (const IdentifierInfo *ControllingMacro
1100       = FileInfo.getControllingMacro(ExternalLookup)) {
1101     // If the header corresponds to a module, check whether the macro is already
1102     // defined in that module rather than checking in the current set of visible
1103     // modules.
1104     if (M ? PP.isMacroDefinedInLocalModule(ControllingMacro, M)
1105           : PP.isMacroDefined(ControllingMacro)) {
1106       ++NumMultiIncludeFileOptzn;
1107       return false;
1108     }
1109   }
1110 
1111   // Increment the number of times this file has been included.
1112   ++FileInfo.NumIncludes;
1113 
1114   return true;
1115 }
1116 
1117 size_t HeaderSearch::getTotalMemory() const {
1118   return SearchDirs.capacity()
1119     + llvm::capacity_in_bytes(FileInfo)
1120     + llvm::capacity_in_bytes(HeaderMaps)
1121     + LookupFileCache.getAllocator().getTotalMemory()
1122     + FrameworkMap.getAllocator().getTotalMemory();
1123 }
1124 
1125 StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) {
1126   return FrameworkNames.insert(Framework).first->first();
1127 }
1128 
1129 bool HeaderSearch::hasModuleMap(StringRef FileName,
1130                                 const DirectoryEntry *Root,
1131                                 bool IsSystem) {
1132   if (!HSOpts->ImplicitModuleMaps)
1133     return false;
1134 
1135   SmallVector<const DirectoryEntry *, 2> FixUpDirectories;
1136 
1137   StringRef DirName = FileName;
1138   do {
1139     // Get the parent directory name.
1140     DirName = llvm::sys::path::parent_path(DirName);
1141     if (DirName.empty())
1142       return false;
1143 
1144     // Determine whether this directory exists.
1145     const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
1146     if (!Dir)
1147       return false;
1148 
1149     // Try to load the module map file in this directory.
1150     switch (loadModuleMapFile(Dir, IsSystem,
1151                               llvm::sys::path::extension(Dir->getName()) ==
1152                                   ".framework")) {
1153     case LMM_NewlyLoaded:
1154     case LMM_AlreadyLoaded:
1155       // Success. All of the directories we stepped through inherit this module
1156       // map file.
1157       for (unsigned I = 0, N = FixUpDirectories.size(); I != N; ++I)
1158         DirectoryHasModuleMap[FixUpDirectories[I]] = true;
1159       return true;
1160 
1161     case LMM_NoDirectory:
1162     case LMM_InvalidModuleMap:
1163       break;
1164     }
1165 
1166     // If we hit the top of our search, we're done.
1167     if (Dir == Root)
1168       return false;
1169 
1170     // Keep track of all of the directories we checked, so we can mark them as
1171     // having module maps if we eventually do find a module map.
1172     FixUpDirectories.push_back(Dir);
1173   } while (true);
1174 }
1175 
1176 ModuleMap::KnownHeader
1177 HeaderSearch::findModuleForHeader(const FileEntry *File,
1178                                   bool AllowTextual) const {
1179   if (ExternalSource) {
1180     // Make sure the external source has handled header info about this file,
1181     // which includes whether the file is part of a module.
1182     (void)getExistingFileInfo(File);
1183   }
1184   return ModMap.findModuleForHeader(File, AllowTextual);
1185 }
1186 
1187 static bool suggestModule(HeaderSearch &HS, const FileEntry *File,
1188                           Module *RequestingModule,
1189                           ModuleMap::KnownHeader *SuggestedModule) {
1190   ModuleMap::KnownHeader Module =
1191       HS.findModuleForHeader(File, /*AllowTextual*/true);
1192   if (SuggestedModule)
1193     *SuggestedModule = (Module.getRole() & ModuleMap::TextualHeader)
1194                            ? ModuleMap::KnownHeader()
1195                            : Module;
1196 
1197   // If this module specifies [no_undeclared_includes], we cannot find any
1198   // file that's in a non-dependency module.
1199   if (RequestingModule && Module && RequestingModule->NoUndeclaredIncludes) {
1200     HS.getModuleMap().resolveUses(RequestingModule, /*Complain*/false);
1201     if (!RequestingModule->directlyUses(Module.getModule())) {
1202       return false;
1203     }
1204   }
1205 
1206   return true;
1207 }
1208 
1209 bool HeaderSearch::findUsableModuleForHeader(
1210     const FileEntry *File, const DirectoryEntry *Root, Module *RequestingModule,
1211     ModuleMap::KnownHeader *SuggestedModule, bool IsSystemHeaderDir) {
1212   if (File && needModuleLookup(RequestingModule, SuggestedModule)) {
1213     // If there is a module that corresponds to this header, suggest it.
1214     hasModuleMap(File->getName(), Root, IsSystemHeaderDir);
1215     return suggestModule(*this, File, RequestingModule, SuggestedModule);
1216   }
1217   return true;
1218 }
1219 
1220 bool HeaderSearch::findUsableModuleForFrameworkHeader(
1221     const FileEntry *File, StringRef FrameworkName, Module *RequestingModule,
1222     ModuleMap::KnownHeader *SuggestedModule, bool IsSystemFramework) {
1223   // If we're supposed to suggest a module, look for one now.
1224   if (needModuleLookup(RequestingModule, SuggestedModule)) {
1225     // Find the top-level framework based on this framework.
1226     SmallVector<std::string, 4> SubmodulePath;
1227     const DirectoryEntry *TopFrameworkDir
1228       = ::getTopFrameworkDir(FileMgr, FrameworkName, SubmodulePath);
1229 
1230     // Determine the name of the top-level framework.
1231     StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
1232 
1233     // Load this framework module. If that succeeds, find the suggested module
1234     // for this header, if any.
1235     loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystemFramework);
1236 
1237     // FIXME: This can find a module not part of ModuleName, which is
1238     // important so that we're consistent about whether this header
1239     // corresponds to a module. Possibly we should lock down framework modules
1240     // so that this is not possible.
1241     return suggestModule(*this, File, RequestingModule, SuggestedModule);
1242   }
1243   return true;
1244 }
1245 
1246 static const FileEntry *getPrivateModuleMap(const FileEntry *File,
1247                                             FileManager &FileMgr) {
1248   StringRef Filename = llvm::sys::path::filename(File->getName());
1249   SmallString<128>  PrivateFilename(File->getDir()->getName());
1250   if (Filename == "module.map")
1251     llvm::sys::path::append(PrivateFilename, "module_private.map");
1252   else if (Filename == "module.modulemap")
1253     llvm::sys::path::append(PrivateFilename, "module.private.modulemap");
1254   else
1255     return nullptr;
1256   return FileMgr.getFile(PrivateFilename);
1257 }
1258 
1259 bool HeaderSearch::loadModuleMapFile(const FileEntry *File, bool IsSystem) {
1260   // Find the directory for the module. For frameworks, that may require going
1261   // up from the 'Modules' directory.
1262   const DirectoryEntry *Dir = nullptr;
1263   if (getHeaderSearchOpts().ModuleMapFileHomeIsCwd)
1264     Dir = FileMgr.getDirectory(".");
1265   else {
1266     Dir = File->getDir();
1267     StringRef DirName(Dir->getName());
1268     if (llvm::sys::path::filename(DirName) == "Modules") {
1269       DirName = llvm::sys::path::parent_path(DirName);
1270       if (DirName.endswith(".framework"))
1271         Dir = FileMgr.getDirectory(DirName);
1272       // FIXME: This assert can fail if there's a race between the above check
1273       // and the removal of the directory.
1274       assert(Dir && "parent must exist");
1275     }
1276   }
1277 
1278   switch (loadModuleMapFileImpl(File, IsSystem, Dir)) {
1279   case LMM_AlreadyLoaded:
1280   case LMM_NewlyLoaded:
1281     return false;
1282   case LMM_NoDirectory:
1283   case LMM_InvalidModuleMap:
1284     return true;
1285   }
1286   llvm_unreachable("Unknown load module map result");
1287 }
1288 
1289 HeaderSearch::LoadModuleMapResult
1290 HeaderSearch::loadModuleMapFileImpl(const FileEntry *File, bool IsSystem,
1291                                     const DirectoryEntry *Dir) {
1292   assert(File && "expected FileEntry");
1293 
1294   // Check whether we've already loaded this module map, and mark it as being
1295   // loaded in case we recursively try to load it from itself.
1296   auto AddResult = LoadedModuleMaps.insert(std::make_pair(File, true));
1297   if (!AddResult.second)
1298     return AddResult.first->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
1299 
1300   if (ModMap.parseModuleMapFile(File, IsSystem, Dir)) {
1301     LoadedModuleMaps[File] = false;
1302     return LMM_InvalidModuleMap;
1303   }
1304 
1305   // Try to load a corresponding private module map.
1306   if (const FileEntry *PMMFile = getPrivateModuleMap(File, FileMgr)) {
1307     if (ModMap.parseModuleMapFile(PMMFile, IsSystem, Dir)) {
1308       LoadedModuleMaps[File] = false;
1309       return LMM_InvalidModuleMap;
1310     }
1311   }
1312 
1313   // This directory has a module map.
1314   return LMM_NewlyLoaded;
1315 }
1316 
1317 const FileEntry *
1318 HeaderSearch::lookupModuleMapFile(const DirectoryEntry *Dir, bool IsFramework) {
1319   if (!HSOpts->ImplicitModuleMaps)
1320     return nullptr;
1321   // For frameworks, the preferred spelling is Modules/module.modulemap, but
1322   // module.map at the framework root is also accepted.
1323   SmallString<128> ModuleMapFileName(Dir->getName());
1324   if (IsFramework)
1325     llvm::sys::path::append(ModuleMapFileName, "Modules");
1326   llvm::sys::path::append(ModuleMapFileName, "module.modulemap");
1327   if (const FileEntry *F = FileMgr.getFile(ModuleMapFileName))
1328     return F;
1329 
1330   // Continue to allow module.map
1331   ModuleMapFileName = Dir->getName();
1332   llvm::sys::path::append(ModuleMapFileName, "module.map");
1333   return FileMgr.getFile(ModuleMapFileName);
1334 }
1335 
1336 Module *HeaderSearch::loadFrameworkModule(StringRef Name,
1337                                           const DirectoryEntry *Dir,
1338                                           bool IsSystem) {
1339   if (Module *Module = ModMap.findModule(Name))
1340     return Module;
1341 
1342   // Try to load a module map file.
1343   switch (loadModuleMapFile(Dir, IsSystem, /*IsFramework*/true)) {
1344   case LMM_InvalidModuleMap:
1345     // Try to infer a module map from the framework directory.
1346     if (HSOpts->ImplicitModuleMaps)
1347       ModMap.inferFrameworkModule(Dir, IsSystem, /*Parent=*/nullptr);
1348     break;
1349 
1350   case LMM_AlreadyLoaded:
1351   case LMM_NoDirectory:
1352     return nullptr;
1353 
1354   case LMM_NewlyLoaded:
1355     break;
1356   }
1357 
1358   return ModMap.findModule(Name);
1359 }
1360 
1361 
1362 HeaderSearch::LoadModuleMapResult
1363 HeaderSearch::loadModuleMapFile(StringRef DirName, bool IsSystem,
1364                                 bool IsFramework) {
1365   if (const DirectoryEntry *Dir = FileMgr.getDirectory(DirName))
1366     return loadModuleMapFile(Dir, IsSystem, IsFramework);
1367 
1368   return LMM_NoDirectory;
1369 }
1370 
1371 HeaderSearch::LoadModuleMapResult
1372 HeaderSearch::loadModuleMapFile(const DirectoryEntry *Dir, bool IsSystem,
1373                                 bool IsFramework) {
1374   auto KnownDir = DirectoryHasModuleMap.find(Dir);
1375   if (KnownDir != DirectoryHasModuleMap.end())
1376     return KnownDir->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
1377 
1378   if (const FileEntry *ModuleMapFile = lookupModuleMapFile(Dir, IsFramework)) {
1379     LoadModuleMapResult Result =
1380         loadModuleMapFileImpl(ModuleMapFile, IsSystem, Dir);
1381     // Add Dir explicitly in case ModuleMapFile is in a subdirectory.
1382     // E.g. Foo.framework/Modules/module.modulemap
1383     //      ^Dir                  ^ModuleMapFile
1384     if (Result == LMM_NewlyLoaded)
1385       DirectoryHasModuleMap[Dir] = true;
1386     else if (Result == LMM_InvalidModuleMap)
1387       DirectoryHasModuleMap[Dir] = false;
1388     return Result;
1389   }
1390   return LMM_InvalidModuleMap;
1391 }
1392 
1393 void HeaderSearch::collectAllModules(SmallVectorImpl<Module *> &Modules) {
1394   Modules.clear();
1395 
1396   if (HSOpts->ImplicitModuleMaps) {
1397     // Load module maps for each of the header search directories.
1398     for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
1399       bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
1400       if (SearchDirs[Idx].isFramework()) {
1401         std::error_code EC;
1402         SmallString<128> DirNative;
1403         llvm::sys::path::native(SearchDirs[Idx].getFrameworkDir()->getName(),
1404                                 DirNative);
1405 
1406         // Search each of the ".framework" directories to load them as modules.
1407         vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
1408         for (vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
1409              Dir != DirEnd && !EC; Dir.increment(EC)) {
1410           if (llvm::sys::path::extension(Dir->getName()) != ".framework")
1411             continue;
1412 
1413           const DirectoryEntry *FrameworkDir =
1414               FileMgr.getDirectory(Dir->getName());
1415           if (!FrameworkDir)
1416             continue;
1417 
1418           // Load this framework module.
1419           loadFrameworkModule(llvm::sys::path::stem(Dir->getName()),
1420                               FrameworkDir, IsSystem);
1421         }
1422         continue;
1423       }
1424 
1425       // FIXME: Deal with header maps.
1426       if (SearchDirs[Idx].isHeaderMap())
1427         continue;
1428 
1429       // Try to load a module map file for the search directory.
1430       loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem,
1431                         /*IsFramework*/ false);
1432 
1433       // Try to load module map files for immediate subdirectories of this
1434       // search directory.
1435       loadSubdirectoryModuleMaps(SearchDirs[Idx]);
1436     }
1437   }
1438 
1439   // Populate the list of modules.
1440   for (ModuleMap::module_iterator M = ModMap.module_begin(),
1441                                MEnd = ModMap.module_end();
1442        M != MEnd; ++M) {
1443     Modules.push_back(M->getValue());
1444   }
1445 }
1446 
1447 void HeaderSearch::loadTopLevelSystemModules() {
1448   if (!HSOpts->ImplicitModuleMaps)
1449     return;
1450 
1451   // Load module maps for each of the header search directories.
1452   for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
1453     // We only care about normal header directories.
1454     if (!SearchDirs[Idx].isNormalDir()) {
1455       continue;
1456     }
1457 
1458     // Try to load a module map file for the search directory.
1459     loadModuleMapFile(SearchDirs[Idx].getDir(),
1460                       SearchDirs[Idx].isSystemHeaderDirectory(),
1461                       SearchDirs[Idx].isFramework());
1462   }
1463 }
1464 
1465 void HeaderSearch::loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir) {
1466   assert(HSOpts->ImplicitModuleMaps &&
1467          "Should not be loading subdirectory module maps");
1468 
1469   if (SearchDir.haveSearchedAllModuleMaps())
1470     return;
1471 
1472   std::error_code EC;
1473   SmallString<128> DirNative;
1474   llvm::sys::path::native(SearchDir.getDir()->getName(), DirNative);
1475   vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
1476   for (vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
1477        Dir != DirEnd && !EC; Dir.increment(EC)) {
1478     bool IsFramework =
1479         llvm::sys::path::extension(Dir->getName()) == ".framework";
1480     if (IsFramework == SearchDir.isFramework())
1481       loadModuleMapFile(Dir->getName(), SearchDir.isSystemHeaderDirectory(),
1482                         SearchDir.isFramework());
1483   }
1484 
1485   SearchDir.setSearchedAllModuleMaps(true);
1486 }
1487 
1488 std::string HeaderSearch::suggestPathToFileForDiagnostics(const FileEntry *File,
1489                                                           bool *IsSystem) {
1490   // FIXME: We assume that the path name currently cached in the FileEntry is
1491   // the most appropriate one for this analysis (and that it's spelled the same
1492   // way as the corresponding header search path).
1493   StringRef Name = File->getName();
1494 
1495   unsigned BestPrefixLength = 0;
1496   unsigned BestSearchDir;
1497 
1498   for (unsigned I = 0; I != SearchDirs.size(); ++I) {
1499     // FIXME: Support this search within frameworks and header maps.
1500     if (!SearchDirs[I].isNormalDir())
1501       continue;
1502 
1503     StringRef Dir = SearchDirs[I].getDir()->getName();
1504     for (auto NI = llvm::sys::path::begin(Name),
1505               NE = llvm::sys::path::end(Name),
1506               DI = llvm::sys::path::begin(Dir),
1507               DE = llvm::sys::path::end(Dir);
1508          /*termination condition in loop*/; ++NI, ++DI) {
1509       // '.' components in Name are ignored.
1510       while (NI != NE && *NI == ".")
1511         ++NI;
1512       if (NI == NE)
1513         break;
1514 
1515       // '.' components in Dir are ignored.
1516       while (DI != DE && *DI == ".")
1517         ++DI;
1518       if (DI == DE) {
1519         // Dir is a prefix of Name, up to '.' components and choice of path
1520         // separators.
1521         unsigned PrefixLength = NI - llvm::sys::path::begin(Name);
1522         if (PrefixLength > BestPrefixLength) {
1523           BestPrefixLength = PrefixLength;
1524           BestSearchDir = I;
1525         }
1526         break;
1527       }
1528 
1529       if (*NI != *DI)
1530         break;
1531     }
1532   }
1533 
1534   if (IsSystem)
1535     *IsSystem = BestPrefixLength ? BestSearchDir >= SystemDirIdx : false;
1536   return Name.drop_front(BestPrefixLength);
1537 }
1538