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 StringRef 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   StringRef ContextName = ContextFileEnt->getName();
851 
852   // If the context info wasn't a framework, couldn't be a subframework.
853   const unsigned DotFrameworkLen = 10;
854   auto FrameworkPos = ContextName.find(".framework");
855   if (FrameworkPos == StringRef::npos ||
856       (ContextName[FrameworkPos + DotFrameworkLen] != '/' &&
857        ContextName[FrameworkPos + DotFrameworkLen] != '\\'))
858     return nullptr;
859 
860   SmallString<1024> FrameworkName(ContextName.data(), ContextName.data() +
861                                                           FrameworkPos +
862                                                           DotFrameworkLen + 1);
863 
864   // Append Frameworks/HIToolbox.framework/
865   FrameworkName += "Frameworks/";
866   FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos);
867   FrameworkName += ".framework/";
868 
869   auto &CacheLookup =
870       *FrameworkMap.insert(std::make_pair(Filename.substr(0, SlashPos),
871                                           FrameworkCacheEntry())).first;
872 
873   // Some other location?
874   if (CacheLookup.second.Directory &&
875       CacheLookup.first().size() == FrameworkName.size() &&
876       memcmp(CacheLookup.first().data(), &FrameworkName[0],
877              CacheLookup.first().size()) != 0)
878     return nullptr;
879 
880   // Cache subframework.
881   if (!CacheLookup.second.Directory) {
882     ++NumSubFrameworkLookups;
883 
884     // If the framework dir doesn't exist, we fail.
885     const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName);
886     if (!Dir) return nullptr;
887 
888     // Otherwise, if it does, remember that this is the right direntry for this
889     // framework.
890     CacheLookup.second.Directory = Dir;
891   }
892 
893   const FileEntry *FE = nullptr;
894 
895   if (RelativePath) {
896     RelativePath->clear();
897     RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
898   }
899 
900   // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
901   SmallString<1024> HeadersFilename(FrameworkName);
902   HeadersFilename += "Headers/";
903   if (SearchPath) {
904     SearchPath->clear();
905     // Without trailing '/'.
906     SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
907   }
908 
909   HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
910   if (!(FE = FileMgr.getFile(HeadersFilename, /*openFile=*/true))) {
911 
912     // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
913     HeadersFilename = FrameworkName;
914     HeadersFilename += "PrivateHeaders/";
915     if (SearchPath) {
916       SearchPath->clear();
917       // Without trailing '/'.
918       SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
919     }
920 
921     HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
922     if (!(FE = FileMgr.getFile(HeadersFilename, /*openFile=*/true)))
923       return nullptr;
924   }
925 
926   // This file is a system header or C++ unfriendly if the old file is.
927   //
928   // Note that the temporary 'DirInfo' is required here, as either call to
929   // getFileInfo could resize the vector and we don't want to rely on order
930   // of evaluation.
931   unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo;
932   getFileInfo(FE).DirInfo = DirInfo;
933 
934   FrameworkName.pop_back(); // remove the trailing '/'
935   if (!findUsableModuleForFrameworkHeader(FE, FrameworkName, RequestingModule,
936                                           SuggestedModule, /*IsSystem*/ false))
937     return nullptr;
938 
939   return FE;
940 }
941 
942 //===----------------------------------------------------------------------===//
943 // File Info Management.
944 //===----------------------------------------------------------------------===//
945 
946 /// \brief Merge the header file info provided by \p OtherHFI into the current
947 /// header file info (\p HFI)
948 static void mergeHeaderFileInfo(HeaderFileInfo &HFI,
949                                 const HeaderFileInfo &OtherHFI) {
950   assert(OtherHFI.External && "expected to merge external HFI");
951 
952   HFI.isImport |= OtherHFI.isImport;
953   HFI.isPragmaOnce |= OtherHFI.isPragmaOnce;
954   HFI.isModuleHeader |= OtherHFI.isModuleHeader;
955   HFI.NumIncludes += OtherHFI.NumIncludes;
956 
957   if (!HFI.ControllingMacro && !HFI.ControllingMacroID) {
958     HFI.ControllingMacro = OtherHFI.ControllingMacro;
959     HFI.ControllingMacroID = OtherHFI.ControllingMacroID;
960   }
961 
962   HFI.DirInfo = OtherHFI.DirInfo;
963   HFI.External = (!HFI.IsValid || HFI.External);
964   HFI.IsValid = true;
965   HFI.IndexHeaderMapHeader = OtherHFI.IndexHeaderMapHeader;
966 
967   if (HFI.Framework.empty())
968     HFI.Framework = OtherHFI.Framework;
969 }
970 
971 /// getFileInfo - Return the HeaderFileInfo structure for the specified
972 /// FileEntry.
973 HeaderFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) {
974   if (FE->getUID() >= FileInfo.size())
975     FileInfo.resize(FE->getUID() + 1);
976 
977   HeaderFileInfo *HFI = &FileInfo[FE->getUID()];
978   // FIXME: Use a generation count to check whether this is really up to date.
979   if (ExternalSource && !HFI->Resolved) {
980     HFI->Resolved = true;
981     auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE);
982 
983     HFI = &FileInfo[FE->getUID()];
984     if (ExternalHFI.External)
985       mergeHeaderFileInfo(*HFI, ExternalHFI);
986   }
987 
988   HFI->IsValid = true;
989   // We have local information about this header file, so it's no longer
990   // strictly external.
991   HFI->External = false;
992   return *HFI;
993 }
994 
995 const HeaderFileInfo *
996 HeaderSearch::getExistingFileInfo(const FileEntry *FE,
997                                   bool WantExternal) const {
998   // If we have an external source, ensure we have the latest information.
999   // FIXME: Use a generation count to check whether this is really up to date.
1000   HeaderFileInfo *HFI;
1001   if (ExternalSource) {
1002     if (FE->getUID() >= FileInfo.size()) {
1003       if (!WantExternal)
1004         return nullptr;
1005       FileInfo.resize(FE->getUID() + 1);
1006     }
1007 
1008     HFI = &FileInfo[FE->getUID()];
1009     if (!WantExternal && (!HFI->IsValid || HFI->External))
1010       return nullptr;
1011     if (!HFI->Resolved) {
1012       HFI->Resolved = true;
1013       auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE);
1014 
1015       HFI = &FileInfo[FE->getUID()];
1016       if (ExternalHFI.External)
1017         mergeHeaderFileInfo(*HFI, ExternalHFI);
1018     }
1019   } else if (FE->getUID() >= FileInfo.size()) {
1020     return nullptr;
1021   } else {
1022     HFI = &FileInfo[FE->getUID()];
1023   }
1024 
1025   if (!HFI->IsValid || (HFI->External && !WantExternal))
1026     return nullptr;
1027 
1028   return HFI;
1029 }
1030 
1031 bool HeaderSearch::isFileMultipleIncludeGuarded(const FileEntry *File) {
1032   // Check if we've ever seen this file as a header.
1033   if (auto *HFI = getExistingFileInfo(File))
1034     return HFI->isPragmaOnce || HFI->isImport || HFI->ControllingMacro ||
1035            HFI->ControllingMacroID;
1036   return false;
1037 }
1038 
1039 void HeaderSearch::MarkFileModuleHeader(const FileEntry *FE,
1040                                         ModuleMap::ModuleHeaderRole Role,
1041                                         bool isCompilingModuleHeader) {
1042   bool isModularHeader = !(Role & ModuleMap::TextualHeader);
1043 
1044   // Don't mark the file info as non-external if there's nothing to change.
1045   if (!isCompilingModuleHeader) {
1046     if (!isModularHeader)
1047       return;
1048     auto *HFI = getExistingFileInfo(FE);
1049     if (HFI && HFI->isModuleHeader)
1050       return;
1051   }
1052 
1053   auto &HFI = getFileInfo(FE);
1054   HFI.isModuleHeader |= isModularHeader;
1055   HFI.isCompilingModuleHeader |= isCompilingModuleHeader;
1056 }
1057 
1058 bool HeaderSearch::ShouldEnterIncludeFile(Preprocessor &PP,
1059                                           const FileEntry *File,
1060                                           bool isImport, Module *M) {
1061   ++NumIncluded; // Count # of attempted #includes.
1062 
1063   // Get information about this file.
1064   HeaderFileInfo &FileInfo = getFileInfo(File);
1065 
1066   // If this is a #import directive, check that we have not already imported
1067   // this header.
1068   if (isImport) {
1069     // If this has already been imported, don't import it again.
1070     FileInfo.isImport = true;
1071 
1072     // Has this already been #import'ed or #include'd?
1073     if (FileInfo.NumIncludes) return false;
1074   } else {
1075     // Otherwise, if this is a #include of a file that was previously #import'd
1076     // or if this is the second #include of a #pragma once file, ignore it.
1077     if (FileInfo.isImport)
1078       return false;
1079   }
1080 
1081   // Next, check to see if the file is wrapped with #ifndef guards.  If so, and
1082   // if the macro that guards it is defined, we know the #include has no effect.
1083   if (const IdentifierInfo *ControllingMacro
1084       = FileInfo.getControllingMacro(ExternalLookup)) {
1085     // If the header corresponds to a module, check whether the macro is already
1086     // defined in that module rather than checking in the current set of visible
1087     // modules.
1088     if (M ? PP.isMacroDefinedInLocalModule(ControllingMacro, M)
1089           : PP.isMacroDefined(ControllingMacro)) {
1090       ++NumMultiIncludeFileOptzn;
1091       return false;
1092     }
1093   }
1094 
1095   // Increment the number of times this file has been included.
1096   ++FileInfo.NumIncludes;
1097 
1098   return true;
1099 }
1100 
1101 size_t HeaderSearch::getTotalMemory() const {
1102   return SearchDirs.capacity()
1103     + llvm::capacity_in_bytes(FileInfo)
1104     + llvm::capacity_in_bytes(HeaderMaps)
1105     + LookupFileCache.getAllocator().getTotalMemory()
1106     + FrameworkMap.getAllocator().getTotalMemory();
1107 }
1108 
1109 StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) {
1110   return FrameworkNames.insert(Framework).first->first();
1111 }
1112 
1113 bool HeaderSearch::hasModuleMap(StringRef FileName,
1114                                 const DirectoryEntry *Root,
1115                                 bool IsSystem) {
1116   if (!HSOpts->ImplicitModuleMaps)
1117     return false;
1118 
1119   SmallVector<const DirectoryEntry *, 2> FixUpDirectories;
1120 
1121   StringRef DirName = FileName;
1122   do {
1123     // Get the parent directory name.
1124     DirName = llvm::sys::path::parent_path(DirName);
1125     if (DirName.empty())
1126       return false;
1127 
1128     // Determine whether this directory exists.
1129     const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
1130     if (!Dir)
1131       return false;
1132 
1133     // Try to load the module map file in this directory.
1134     switch (loadModuleMapFile(Dir, IsSystem,
1135                               llvm::sys::path::extension(Dir->getName()) ==
1136                                   ".framework")) {
1137     case LMM_NewlyLoaded:
1138     case LMM_AlreadyLoaded:
1139       // Success. All of the directories we stepped through inherit this module
1140       // map file.
1141       for (unsigned I = 0, N = FixUpDirectories.size(); I != N; ++I)
1142         DirectoryHasModuleMap[FixUpDirectories[I]] = true;
1143       return true;
1144 
1145     case LMM_NoDirectory:
1146     case LMM_InvalidModuleMap:
1147       break;
1148     }
1149 
1150     // If we hit the top of our search, we're done.
1151     if (Dir == Root)
1152       return false;
1153 
1154     // Keep track of all of the directories we checked, so we can mark them as
1155     // having module maps if we eventually do find a module map.
1156     FixUpDirectories.push_back(Dir);
1157   } while (true);
1158 }
1159 
1160 ModuleMap::KnownHeader
1161 HeaderSearch::findModuleForHeader(const FileEntry *File) const {
1162   if (ExternalSource) {
1163     // Make sure the external source has handled header info about this file,
1164     // which includes whether the file is part of a module.
1165     (void)getExistingFileInfo(File);
1166   }
1167   return ModMap.findModuleForHeader(File);
1168 }
1169 
1170 bool HeaderSearch::findUsableModuleForHeader(
1171     const FileEntry *File, const DirectoryEntry *Root, Module *RequestingModule,
1172     ModuleMap::KnownHeader *SuggestedModule, bool IsSystemHeaderDir) {
1173   if (File && SuggestedModule) {
1174     // If there is a module that corresponds to this header, suggest it.
1175     hasModuleMap(File->getName(), Root, IsSystemHeaderDir);
1176     *SuggestedModule = findModuleForHeader(File);
1177   }
1178   return true;
1179 }
1180 
1181 bool HeaderSearch::findUsableModuleForFrameworkHeader(
1182     const FileEntry *File, StringRef FrameworkName, Module *RequestingModule,
1183     ModuleMap::KnownHeader *SuggestedModule, bool IsSystemFramework) {
1184   // If we're supposed to suggest a module, look for one now.
1185   if (SuggestedModule) {
1186     // Find the top-level framework based on this framework.
1187     SmallVector<std::string, 4> SubmodulePath;
1188     const DirectoryEntry *TopFrameworkDir
1189       = ::getTopFrameworkDir(FileMgr, FrameworkName, SubmodulePath);
1190 
1191     // Determine the name of the top-level framework.
1192     StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
1193 
1194     // Load this framework module. If that succeeds, find the suggested module
1195     // for this header, if any.
1196     loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystemFramework);
1197 
1198     // FIXME: This can find a module not part of ModuleName, which is
1199     // important so that we're consistent about whether this header
1200     // corresponds to a module. Possibly we should lock down framework modules
1201     // so that this is not possible.
1202     *SuggestedModule = findModuleForHeader(File);
1203   }
1204   return true;
1205 }
1206 
1207 static const FileEntry *getPrivateModuleMap(const FileEntry *File,
1208                                             FileManager &FileMgr) {
1209   StringRef Filename = llvm::sys::path::filename(File->getName());
1210   SmallString<128>  PrivateFilename(File->getDir()->getName());
1211   if (Filename == "module.map")
1212     llvm::sys::path::append(PrivateFilename, "module_private.map");
1213   else if (Filename == "module.modulemap")
1214     llvm::sys::path::append(PrivateFilename, "module.private.modulemap");
1215   else
1216     return nullptr;
1217   return FileMgr.getFile(PrivateFilename);
1218 }
1219 
1220 bool HeaderSearch::loadModuleMapFile(const FileEntry *File, bool IsSystem) {
1221   // Find the directory for the module. For frameworks, that may require going
1222   // up from the 'Modules' directory.
1223   const DirectoryEntry *Dir = nullptr;
1224   if (getHeaderSearchOpts().ModuleMapFileHomeIsCwd)
1225     Dir = FileMgr.getDirectory(".");
1226   else {
1227     Dir = File->getDir();
1228     StringRef DirName(Dir->getName());
1229     if (llvm::sys::path::filename(DirName) == "Modules") {
1230       DirName = llvm::sys::path::parent_path(DirName);
1231       if (DirName.endswith(".framework"))
1232         Dir = FileMgr.getDirectory(DirName);
1233       // FIXME: This assert can fail if there's a race between the above check
1234       // and the removal of the directory.
1235       assert(Dir && "parent must exist");
1236     }
1237   }
1238 
1239   switch (loadModuleMapFileImpl(File, IsSystem, Dir)) {
1240   case LMM_AlreadyLoaded:
1241   case LMM_NewlyLoaded:
1242     return false;
1243   case LMM_NoDirectory:
1244   case LMM_InvalidModuleMap:
1245     return true;
1246   }
1247   llvm_unreachable("Unknown load module map result");
1248 }
1249 
1250 HeaderSearch::LoadModuleMapResult
1251 HeaderSearch::loadModuleMapFileImpl(const FileEntry *File, bool IsSystem,
1252                                     const DirectoryEntry *Dir) {
1253   assert(File && "expected FileEntry");
1254 
1255   // Check whether we've already loaded this module map, and mark it as being
1256   // loaded in case we recursively try to load it from itself.
1257   auto AddResult = LoadedModuleMaps.insert(std::make_pair(File, true));
1258   if (!AddResult.second)
1259     return AddResult.first->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
1260 
1261   if (ModMap.parseModuleMapFile(File, IsSystem, Dir)) {
1262     LoadedModuleMaps[File] = false;
1263     return LMM_InvalidModuleMap;
1264   }
1265 
1266   // Try to load a corresponding private module map.
1267   if (const FileEntry *PMMFile = getPrivateModuleMap(File, FileMgr)) {
1268     if (ModMap.parseModuleMapFile(PMMFile, IsSystem, Dir)) {
1269       LoadedModuleMaps[File] = false;
1270       return LMM_InvalidModuleMap;
1271     }
1272   }
1273 
1274   // This directory has a module map.
1275   return LMM_NewlyLoaded;
1276 }
1277 
1278 const FileEntry *
1279 HeaderSearch::lookupModuleMapFile(const DirectoryEntry *Dir, bool IsFramework) {
1280   if (!HSOpts->ImplicitModuleMaps)
1281     return nullptr;
1282   // For frameworks, the preferred spelling is Modules/module.modulemap, but
1283   // module.map at the framework root is also accepted.
1284   SmallString<128> ModuleMapFileName(Dir->getName());
1285   if (IsFramework)
1286     llvm::sys::path::append(ModuleMapFileName, "Modules");
1287   llvm::sys::path::append(ModuleMapFileName, "module.modulemap");
1288   if (const FileEntry *F = FileMgr.getFile(ModuleMapFileName))
1289     return F;
1290 
1291   // Continue to allow module.map
1292   ModuleMapFileName = Dir->getName();
1293   llvm::sys::path::append(ModuleMapFileName, "module.map");
1294   return FileMgr.getFile(ModuleMapFileName);
1295 }
1296 
1297 Module *HeaderSearch::loadFrameworkModule(StringRef Name,
1298                                           const DirectoryEntry *Dir,
1299                                           bool IsSystem) {
1300   if (Module *Module = ModMap.findModule(Name))
1301     return Module;
1302 
1303   // Try to load a module map file.
1304   switch (loadModuleMapFile(Dir, IsSystem, /*IsFramework*/true)) {
1305   case LMM_InvalidModuleMap:
1306     // Try to infer a module map from the framework directory.
1307     if (HSOpts->ImplicitModuleMaps)
1308       ModMap.inferFrameworkModule(Dir, IsSystem, /*Parent=*/nullptr);
1309     break;
1310 
1311   case LMM_AlreadyLoaded:
1312   case LMM_NoDirectory:
1313     return nullptr;
1314 
1315   case LMM_NewlyLoaded:
1316     break;
1317   }
1318 
1319   return ModMap.findModule(Name);
1320 }
1321 
1322 
1323 HeaderSearch::LoadModuleMapResult
1324 HeaderSearch::loadModuleMapFile(StringRef DirName, bool IsSystem,
1325                                 bool IsFramework) {
1326   if (const DirectoryEntry *Dir = FileMgr.getDirectory(DirName))
1327     return loadModuleMapFile(Dir, IsSystem, IsFramework);
1328 
1329   return LMM_NoDirectory;
1330 }
1331 
1332 HeaderSearch::LoadModuleMapResult
1333 HeaderSearch::loadModuleMapFile(const DirectoryEntry *Dir, bool IsSystem,
1334                                 bool IsFramework) {
1335   auto KnownDir = DirectoryHasModuleMap.find(Dir);
1336   if (KnownDir != DirectoryHasModuleMap.end())
1337     return KnownDir->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
1338 
1339   if (const FileEntry *ModuleMapFile = lookupModuleMapFile(Dir, IsFramework)) {
1340     LoadModuleMapResult Result =
1341         loadModuleMapFileImpl(ModuleMapFile, IsSystem, Dir);
1342     // Add Dir explicitly in case ModuleMapFile is in a subdirectory.
1343     // E.g. Foo.framework/Modules/module.modulemap
1344     //      ^Dir                  ^ModuleMapFile
1345     if (Result == LMM_NewlyLoaded)
1346       DirectoryHasModuleMap[Dir] = true;
1347     else if (Result == LMM_InvalidModuleMap)
1348       DirectoryHasModuleMap[Dir] = false;
1349     return Result;
1350   }
1351   return LMM_InvalidModuleMap;
1352 }
1353 
1354 void HeaderSearch::collectAllModules(SmallVectorImpl<Module *> &Modules) {
1355   Modules.clear();
1356 
1357   if (HSOpts->ImplicitModuleMaps) {
1358     // Load module maps for each of the header search directories.
1359     for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
1360       bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
1361       if (SearchDirs[Idx].isFramework()) {
1362         std::error_code EC;
1363         SmallString<128> DirNative;
1364         llvm::sys::path::native(SearchDirs[Idx].getFrameworkDir()->getName(),
1365                                 DirNative);
1366 
1367         // Search each of the ".framework" directories to load them as modules.
1368         vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
1369         for (vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
1370              Dir != DirEnd && !EC; Dir.increment(EC)) {
1371           if (llvm::sys::path::extension(Dir->getName()) != ".framework")
1372             continue;
1373 
1374           const DirectoryEntry *FrameworkDir =
1375               FileMgr.getDirectory(Dir->getName());
1376           if (!FrameworkDir)
1377             continue;
1378 
1379           // Load this framework module.
1380           loadFrameworkModule(llvm::sys::path::stem(Dir->getName()),
1381                               FrameworkDir, IsSystem);
1382         }
1383         continue;
1384       }
1385 
1386       // FIXME: Deal with header maps.
1387       if (SearchDirs[Idx].isHeaderMap())
1388         continue;
1389 
1390       // Try to load a module map file for the search directory.
1391       loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem,
1392                         /*IsFramework*/ false);
1393 
1394       // Try to load module map files for immediate subdirectories of this
1395       // search directory.
1396       loadSubdirectoryModuleMaps(SearchDirs[Idx]);
1397     }
1398   }
1399 
1400   // Populate the list of modules.
1401   for (ModuleMap::module_iterator M = ModMap.module_begin(),
1402                                MEnd = ModMap.module_end();
1403        M != MEnd; ++M) {
1404     Modules.push_back(M->getValue());
1405   }
1406 }
1407 
1408 void HeaderSearch::loadTopLevelSystemModules() {
1409   if (!HSOpts->ImplicitModuleMaps)
1410     return;
1411 
1412   // Load module maps for each of the header search directories.
1413   for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
1414     // We only care about normal header directories.
1415     if (!SearchDirs[Idx].isNormalDir()) {
1416       continue;
1417     }
1418 
1419     // Try to load a module map file for the search directory.
1420     loadModuleMapFile(SearchDirs[Idx].getDir(),
1421                       SearchDirs[Idx].isSystemHeaderDirectory(),
1422                       SearchDirs[Idx].isFramework());
1423   }
1424 }
1425 
1426 void HeaderSearch::loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir) {
1427   assert(HSOpts->ImplicitModuleMaps &&
1428          "Should not be loading subdirectory module maps");
1429 
1430   if (SearchDir.haveSearchedAllModuleMaps())
1431     return;
1432 
1433   std::error_code EC;
1434   SmallString<128> DirNative;
1435   llvm::sys::path::native(SearchDir.getDir()->getName(), DirNative);
1436   vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
1437   for (vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
1438        Dir != DirEnd && !EC; Dir.increment(EC)) {
1439     bool IsFramework =
1440         llvm::sys::path::extension(Dir->getName()) == ".framework";
1441     if (IsFramework == SearchDir.isFramework())
1442       loadModuleMapFile(Dir->getName(), SearchDir.isSystemHeaderDirectory(),
1443                         SearchDir.isFramework());
1444   }
1445 
1446   SearchDir.setSearchedAllModuleMaps(true);
1447 }
1448 
1449 std::string HeaderSearch::suggestPathToFileForDiagnostics(const FileEntry *File,
1450                                                           bool *IsSystem) {
1451   // FIXME: We assume that the path name currently cached in the FileEntry is
1452   // the most appropriate one for this analysis (and that it's spelled the same
1453   // way as the corresponding header search path).
1454   StringRef Name = File->getName();
1455 
1456   unsigned BestPrefixLength = 0;
1457   unsigned BestSearchDir;
1458 
1459   for (unsigned I = 0; I != SearchDirs.size(); ++I) {
1460     // FIXME: Support this search within frameworks and header maps.
1461     if (!SearchDirs[I].isNormalDir())
1462       continue;
1463 
1464     StringRef Dir = SearchDirs[I].getDir()->getName();
1465     for (auto NI = llvm::sys::path::begin(Name),
1466               NE = llvm::sys::path::end(Name),
1467               DI = llvm::sys::path::begin(Dir),
1468               DE = llvm::sys::path::end(Dir);
1469          /*termination condition in loop*/; ++NI, ++DI) {
1470       // '.' components in Name are ignored.
1471       while (NI != NE && *NI == ".")
1472         ++NI;
1473       if (NI == NE)
1474         break;
1475 
1476       // '.' components in Dir are ignored.
1477       while (DI != DE && *DI == ".")
1478         ++DI;
1479       if (DI == DE) {
1480         // Dir is a prefix of Name, up to '.' components and choice of path
1481         // separators.
1482         unsigned PrefixLength = NI - llvm::sys::path::begin(Name);
1483         if (PrefixLength > BestPrefixLength) {
1484           BestPrefixLength = PrefixLength;
1485           BestSearchDir = I;
1486         }
1487         break;
1488       }
1489 
1490       if (*NI != *DI)
1491         break;
1492     }
1493   }
1494 
1495   if (IsSystem)
1496     *IsSystem = BestPrefixLength ? BestSearchDir >= SystemDirIdx : false;
1497   return Name.drop_front(BestPrefixLength);
1498 }
1499