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