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