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