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