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