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