1 //===- HeaderSearch.cpp - Resolve Header File Locations -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the DirectoryLookup and HeaderSearch interfaces.
12 //===----------------------------------------------------------------------===//
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"
44 #include <system_error>
47 using namespace clang;
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));
58 return ControllingMacro;
61 if (!ControllingMacroID || !External)
64 ControllingMacro = External->GetIdentifier(ControllingMacroID);
65 return ControllingMacro;
68 ExternalHeaderFileInfoSource::~ExternalHeaderFileInfoSource() = default;
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) {}
78 HeaderSearch::~HeaderSearch() {
80 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
81 delete HeaderMaps[i].second;
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;
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);
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);
102 fprintf(stderr, "%d framework lookups.\n", NumFrameworkLookups);
103 fprintf(stderr, "%d subframework lookups.\n", NumSubFrameworkLookups);
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;
119 if (const HeaderMap *HM = HeaderMap::Create(FE, FileMgr)) {
120 HeaderMaps.push_back(std::make_pair(FE, HM));
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());
134 std::string HeaderSearch::getCachedModuleFileName(Module *Module) {
135 const FileEntry *ModuleMap =
136 getModuleMap().getModuleMapFileForUniquing(Module);
137 return getCachedModuleFileName(Module->Name, ModuleMap->getName());
140 std::string HeaderSearch::getPrebuiltModuleFileName(StringRef ModuleName,
142 // First check the module name to pcm file map.
143 auto i (HSOpts->PrebuiltModuleFiles.find(ModuleName));
144 if (i != HSOpts->PrebuiltModuleFiles.end())
147 if (FileMapOnly || HSOpts->PrebuiltModulePaths.empty())
150 // Then go through each prebuilt module directory and try to find the pcm
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();
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())
169 SmallString<256> Result(getModuleCachePath());
170 llvm::sys::fs::make_absolute(Result);
172 if (HSOpts->DisableModuleHash) {
173 llvm::sys::path::append(Result, ModuleName + ".pcm");
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.
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);
185 auto *Dir = FileMgr.getDirectory(Parent);
188 auto DirName = FileMgr.getCanonicalName(Dir);
189 auto FileName = llvm::sys::path::filename(ModuleMapPath);
191 llvm::hash_code Hash =
192 llvm::hash_combine(DirName.lower(), FileName.lower());
194 SmallString<128> HashStr;
195 llvm::APInt(64, size_t(Hash)).toStringUnsigned(HashStr, /*Radix*/36);
196 llvm::sys::path::append(Result, ModuleName + "-" + HashStr + ".pcm");
198 return Result.str().str();
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)
208 StringRef SearchName = ModuleName;
209 Module = lookupModule(ModuleName, SearchName, AllowExtraModuleMapSearch);
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.
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);
226 Module *HeaderSearch::lookupModule(StringRef ModuleName, StringRef SearchName,
227 bool AllowExtraModuleMapSearch) {
228 Module *Module = nullptr;
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)) {
243 = SearchDirs[Idx].getDirCharacteristic() != SrcMgr::C_User;
244 Module = loadFrameworkModule(ModuleName, FrameworkDir, IsSystem);
250 // FIXME: Figure out how header maps and module maps will work together.
252 // Only deal with normal search directories.
253 if (!SearchDirs[Idx].isNormalDir())
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
262 Module = ModMap.findModule(ModuleName);
267 // Search for a module map in a subdirectory with the same name as the
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);
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())
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]);
290 // Look again for the module.
291 Module = ModMap.findModule(ModuleName);
299 //===----------------------------------------------------------------------===//
300 // File lookup within a DirectoryLookup scope
301 //===----------------------------------------------------------------------===//
303 /// getName - Return the directory or filename corresponding to this lookup
305 StringRef DirectoryLookup::getName() const {
307 return getDir()->getName();
309 return getFrameworkDir()->getName();
310 assert(isHeaderMap() && "Unknown DirectoryLookup");
311 return getHeaderMap()->getFileName();
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);
324 // If there is a module that corresponds to this header, suggest it.
325 if (!findUsableModuleForHeader(File, Dir ? Dir : File->getDir(),
326 RequestingModule, SuggestedModule,
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(
338 SourceLocation IncludeLoc,
339 SmallVectorImpl<char> *SearchPath,
340 SmallVectorImpl<char> *RelativePath,
341 Module *RequestingModule,
342 ModuleMap::KnownHeader *SuggestedModule,
343 bool &InUserSpecifiedSystemFramework,
345 SmallVectorImpl<char> &MappedName) const {
346 InUserSpecifiedSystemFramework = false;
347 HasBeenMapped = false;
349 SmallString<1024> TmpDir;
351 // Concatenate the requested file onto the directory.
352 TmpDir = getDir()->getName();
353 llvm::sys::path::append(TmpDir, Filename);
355 StringRef SearchPathRef(getDir()->getName());
357 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
360 RelativePath->clear();
361 RelativePath->append(Filename.begin(), Filename.end());
364 return HS.getFileAndSuggestModule(TmpDir, IncludeLoc, getDir(),
365 isSystemHeaderDirectory(),
366 RequestingModule, SuggestedModule);
370 return DoFrameworkLookup(Filename, HS, SearchPath, RelativePath,
371 RequestingModule, SuggestedModule,
372 InUserSpecifiedSystemFramework);
374 assert(isHeaderMap() && "Unknown directory lookup");
375 const HeaderMap *HM = getHeaderMap();
376 SmallString<1024> Path;
377 StringRef Dest = HM->lookupFilename(Filename, Path);
381 const FileEntry *Result;
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)) {
388 MappedName.append(Dest.begin(), Dest.end());
389 Filename = StringRef(MappedName.begin(), MappedName.size());
390 HasBeenMapped = true;
391 Result = HM->LookupFile(Filename, HS.getFileMgr());
393 Result = HS.getFileMgr().getFile(Dest);
398 StringRef SearchPathRef(getName());
400 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
403 RelativePath->clear();
404 RelativePath->append(Filename.begin(), Filename.end());
410 /// Given a framework directory, find the top-most framework directory.
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");
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
427 // #include <Foo/Frameworks/Bar.framework/Headers/Wibble.h>
429 // where 'Bar' used to be embedded in 'Foo', is now a top-level framework
430 // which one should access with, e.g.,
432 // #include <Bar/Wibble.h>
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);
439 // Get the parent directory name.
440 DirName = llvm::sys::path::parent_path(DirName);
444 // Determine whether this directory exists.
445 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
449 // If this is a framework directory, then we're a subframework of this
451 if (llvm::sys::path::extension(DirName) == ".framework") {
452 SubmodulePath.push_back(llvm::sys::path::stem(DirName));
453 TopFrameworkDir = Dir;
457 return TopFrameworkDir;
460 static bool needModuleLookup(Module *RequestingModule,
461 bool HasSuggestedModule) {
462 return HasSuggestedModule ||
463 (RequestingModule && RequestingModule->NoUndeclaredIncludes);
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();
475 // Framework names must have a '/' in the filename.
476 size_t SlashPos = Filename.find('/');
477 if (SlashPos == StringRef::npos) return nullptr;
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));
484 // If it is known and in some other directory, fail.
485 if (CacheEntry.Directory && CacheEntry.Directory != getFrameworkDir())
488 // Otherwise, construct the path to this framework dir.
490 // FrameworkName = "/System/Library/Frameworks/"
491 SmallString<1024> FrameworkName;
492 FrameworkName += getFrameworkDir()->getName();
493 if (FrameworkName.empty() || FrameworkName.back() != '/')
494 FrameworkName.push_back('/');
496 // FrameworkName = "/System/Library/Frameworks/Cocoa"
497 StringRef ModuleName(Filename.begin(), SlashPos);
498 FrameworkName += ModuleName;
500 // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/"
501 FrameworkName += ".framework/";
503 // If the cache entry was unresolved, populate it now.
504 if (!CacheEntry.Directory) {
505 HS.IncrementFrameworkLookupCount();
507 // If the framework dir doesn't exist, we fail.
508 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName);
509 if (!Dir) return nullptr;
511 // Otherwise, if it does, remember that this is the right direntry for this
513 CacheEntry.Directory = getFrameworkDir();
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;
526 // Set the 'user-specified system framework' flag.
527 InUserSpecifiedSystemFramework = CacheEntry.IsUserSpecifiedSystemFramework;
530 RelativePath->clear();
531 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
534 // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"
535 unsigned OrigSize = FrameworkName.size();
537 FrameworkName += "Headers/";
541 // Without trailing '/'.
542 SearchPath->append(FrameworkName.begin(), FrameworkName.end()-1);
545 FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end());
546 const FileEntry *FE = FileMgr.getFile(FrameworkName,
547 /*openFile=*/!SuggestedModule);
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));
554 SearchPath->insert(SearchPath->begin()+OrigSize, Private,
555 Private+strlen(Private));
557 FE = FileMgr.getFile(FrameworkName, /*openFile=*/!SuggestedModule);
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;
566 // Determine whether this directory exists.
567 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkPath);
571 // If this is a framework directory, then we're a subframework of this
573 if (llvm::sys::path::extension(FrameworkPath) == ".framework") {
574 FoundFramework = true;
578 // Get the parent directory name.
579 FrameworkPath = llvm::sys::path::parent_path(FrameworkPath);
580 if (FrameworkPath.empty())
584 bool IsSystem = getDirCharacteristic() != SrcMgr::C_User;
585 if (FoundFramework) {
586 if (!HS.findUsableModuleForFrameworkHeader(
587 FE, FrameworkPath, RequestingModule, SuggestedModule, IsSystem))
590 if (!HS.findUsableModuleForHeader(FE, getDir(), RequestingModule,
591 SuggestedModule, IsSystem))
598 void HeaderSearch::setTarget(const TargetInfo &Target) {
599 ModMap.setTarget(Target);
602 //===----------------------------------------------------------------------===//
603 // Header File Location.
604 //===----------------------------------------------------------------------===//
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
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();
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';
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;
634 // Detect different types of framework style paths:
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>
641 // and some other variations among these lines.
646 if (I->endswith(".framework")) {
647 FrameworkName.append(I->begin(), I->end());
650 if (*I == "PrivateHeaders") {
652 IsPrivateHeader = true;
657 return FoundComp >= 2;
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))
669 bool IsIncludeePrivateHeader = false;
670 bool IsIncludeeInFramework = isFrameworkStylePath(
671 IncludeFE->getName(), IsIncludeePrivateHeader, ToFramework);
673 if (!isAngled && !FoundByHeaderMap) {
674 SmallString<128> NewInclude("<");
675 if (IsIncludeeInFramework) {
676 NewInclude += StringRef(ToFramework).drop_back(10); // drop .framework
679 NewInclude += IncludeFilename;
681 Diags.Report(IncludeLoc, diag::warn_quoted_include_in_framework_header)
683 << FixItHint::CreateReplacement(IncludeLoc, NewInclude);
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)
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) {
711 *SuggestedModule = ModuleMap::KnownHeader();
713 // If 'Filename' is absolute, check to see if it exists and no searching.
714 if (llvm::sys::path::is_absolute(Filename)) {
717 // If this was an #include_next "/absolute/file", fail.
718 if (FromDir) return nullptr;
723 RelativePath->clear();
724 RelativePath->append(Filename.begin(), Filename.end());
726 // Otherwise, just return the file.
727 return getFileAndSuggestModule(Filename, IncludeLoc, nullptr,
728 /*IsSystemHeaderDir*/false,
729 RequestingModule, SuggestedModule);
732 // This is the header that MSVC's header search would have found.
733 const FileEntry *MSFE = nullptr;
734 ModuleMap::KnownHeader MSSuggestedModule;
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;
744 for (const auto &IncluderAndDir : Includers) {
745 const FileEntry *Includer = IncluderAndDir.first;
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());
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.
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 :
763 if (const FileEntry *FE = getFileAndSuggestModule(
764 TmpDir, IncludeLoc, IncluderAndDir.second, IncluderIsSystemHeader,
765 RequestingModule, SuggestedModule)) {
767 assert(First && "only first includer can have no file");
771 // Leave CurDir unset.
772 // This file is a system header or C++ unfriendly if the old file is.
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;
782 HeaderFileInfo &ToHFI = getFileInfo(FE);
783 ToHFI.DirInfo = DirInfo;
784 ToHFI.IndexHeaderMapHeader = IndexHeaderMapHeader;
785 ToHFI.Framework = Framework;
788 StringRef SearchPathRef(IncluderAndDir.second->getName());
790 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
793 RelativePath->clear();
794 RelativePath->append(Filename.begin(), Filename.end());
797 diagnoseFrameworkInclude(Diags, IncludeLoc,
798 IncluderAndDir.second->getName(), Filename,
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)) {
810 if (SuggestedModule) {
811 MSSuggestedModule = *SuggestedModule;
812 *SuggestedModule = ModuleMap::KnownHeader();
823 // If this is a system #include, ignore the user #include locs.
824 unsigned i = isAngled ? AngledDirIdx : 0;
826 // If this is a #include_next request, start searching after the directory the
827 // file was found in.
829 i = FromDir-&SearchDirs[0];
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];
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;
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);
855 SmallString<64> MappedName;
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,
866 CacheLookup.MappedName =
867 copyString(Filename, LookupFileCache.getAllocator());
873 CurDir = &SearchDirs[i];
875 // This file is a system header or C++ unfriendly if the dir is.
876 HeaderFileInfo &HFI = getFileInfo(FE);
877 HFI.DirInfo = CurDir->getDirCharacteristic();
879 // If the directory characteristic is User but this framework was
880 // user-specified to be treated as a system framework, promote the
882 if (HFI.DirInfo == SrcMgr::C_User && InUserSpecifiedSystemFramework)
883 HFI.DirInfo = SrcMgr::C_System;
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
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(),
906 if (checkMSVCHeaderSearch(Diags, MSFE, FE, IncludeLoc)) {
908 *SuggestedModule = MSSuggestedModule;
912 bool FoundByHeaderMap = !IsMapped ? false : *IsMapped;
913 if (!Includers.empty())
914 diagnoseFrameworkInclude(Diags, IncludeLoc,
915 Includers.front().second->getName(), Filename,
916 FE, isAngled, FoundByHeaderMap);
918 // Remember this location for the next lookup we do.
919 CacheLookup.HitIdx = i;
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;
936 const FileEntry *FE =
937 LookupFile(ScratchFilename, IncludeLoc, /*isAngled=*/true, FromDir,
938 CurDir, Includers.front(), SearchPath, RelativePath,
939 RequestingModule, SuggestedModule, IsMapped);
941 if (checkMSVCHeaderSearch(Diags, MSFE, FE, IncludeLoc)) {
943 *SuggestedModule = MSSuggestedModule;
947 LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename];
948 CacheLookup.HitIdx = LookupFileCache[ScratchFilename].HitIdx;
949 // FIXME: SuggestedModule.
954 if (checkMSVCHeaderSearch(Diags, MSFE, nullptr, IncludeLoc)) {
956 *SuggestedModule = MSSuggestedModule;
960 // Otherwise, didn't find it. Remember we didn't find this.
961 CacheLookup.HitIdx = SearchDirs.size();
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?");
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;
984 // Look up the base framework name of the ContextFileEnt.
985 StringRef ContextName = ContextFileEnt->getName();
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] != '\\'))
995 SmallString<1024> FrameworkName(ContextName.data(), ContextName.data() +
997 DotFrameworkLen + 1);
999 // Append Frameworks/HIToolbox.framework/
1000 FrameworkName += "Frameworks/";
1001 FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos);
1002 FrameworkName += ".framework/";
1005 *FrameworkMap.insert(std::make_pair(Filename.substr(0, SlashPos),
1006 FrameworkCacheEntry())).first;
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)
1015 // Cache subframework.
1016 if (!CacheLookup.second.Directory) {
1017 ++NumSubFrameworkLookups;
1019 // If the framework dir doesn't exist, we fail.
1020 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName);
1021 if (!Dir) return nullptr;
1023 // Otherwise, if it does, remember that this is the right direntry for this
1025 CacheLookup.second.Directory = Dir;
1028 const FileEntry *FE = nullptr;
1031 RelativePath->clear();
1032 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
1035 // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
1036 SmallString<1024> HeadersFilename(FrameworkName);
1037 HeadersFilename += "Headers/";
1039 SearchPath->clear();
1040 // Without trailing '/'.
1041 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
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/";
1050 SearchPath->clear();
1051 // Without trailing '/'.
1052 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
1055 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
1056 if (!(FE = FileMgr.getFile(HeadersFilename, /*openFile=*/true)))
1060 // This file is a system header or C++ unfriendly if the old file is.
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
1065 unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo;
1066 getFileInfo(FE).DirInfo = DirInfo;
1068 FrameworkName.pop_back(); // remove the trailing '/'
1069 if (!findUsableModuleForFrameworkHeader(FE, FrameworkName, RequestingModule,
1070 SuggestedModule, /*IsSystem*/ false))
1076 //===----------------------------------------------------------------------===//
1077 // File Info Management.
1078 //===----------------------------------------------------------------------===//
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");
1086 HFI.isImport |= OtherHFI.isImport;
1087 HFI.isPragmaOnce |= OtherHFI.isPragmaOnce;
1088 HFI.isModuleHeader |= OtherHFI.isModuleHeader;
1089 HFI.NumIncludes += OtherHFI.NumIncludes;
1091 if (!HFI.ControllingMacro && !HFI.ControllingMacroID) {
1092 HFI.ControllingMacro = OtherHFI.ControllingMacro;
1093 HFI.ControllingMacroID = OtherHFI.ControllingMacroID;
1096 HFI.DirInfo = OtherHFI.DirInfo;
1097 HFI.External = (!HFI.IsValid || HFI.External);
1099 HFI.IndexHeaderMapHeader = OtherHFI.IndexHeaderMapHeader;
1101 if (HFI.Framework.empty())
1102 HFI.Framework = OtherHFI.Framework;
1105 /// getFileInfo - Return the HeaderFileInfo structure for the specified
1107 HeaderFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) {
1108 if (FE->getUID() >= FileInfo.size())
1109 FileInfo.resize(FE->getUID() + 1);
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);
1117 HFI = &FileInfo[FE->getUID()];
1118 if (ExternalHFI.External)
1119 mergeHeaderFileInfo(*HFI, ExternalHFI);
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;
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()) {
1139 FileInfo.resize(FE->getUID() + 1);
1142 HFI = &FileInfo[FE->getUID()];
1143 if (!WantExternal && (!HFI->IsValid || HFI->External))
1145 if (!HFI->Resolved) {
1146 HFI->Resolved = true;
1147 auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE);
1149 HFI = &FileInfo[FE->getUID()];
1150 if (ExternalHFI.External)
1151 mergeHeaderFileInfo(*HFI, ExternalHFI);
1153 } else if (FE->getUID() >= FileInfo.size()) {
1156 HFI = &FileInfo[FE->getUID()];
1159 if (!HFI->IsValid || (HFI->External && !WantExternal))
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;
1173 void HeaderSearch::MarkFileModuleHeader(const FileEntry *FE,
1174 ModuleMap::ModuleHeaderRole Role,
1175 bool isCompilingModuleHeader) {
1176 bool isModularHeader = !(Role & ModuleMap::TextualHeader);
1178 // Don't mark the file info as non-external if there's nothing to change.
1179 if (!isCompilingModuleHeader) {
1180 if (!isModularHeader)
1182 auto *HFI = getExistingFileInfo(FE);
1183 if (HFI && HFI->isModuleHeader)
1187 auto &HFI = getFileInfo(FE);
1188 HFI.isModuleHeader |= isModularHeader;
1189 HFI.isCompilingModuleHeader |= isCompilingModuleHeader;
1192 bool HeaderSearch::ShouldEnterIncludeFile(Preprocessor &PP,
1193 const FileEntry *File, bool isImport,
1194 bool ModulesEnabled, Module *M) {
1195 ++NumIncluded; // Count # of attempted #includes.
1197 // Get information about this file.
1198 HeaderFileInfo &FileInfo = getFileInfo(File);
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)
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:
1210 // module stddef { header "stddef.h" export * }
1212 // After module map parsing, this expands to:
1215 // header "/path_to_builtin_dirs/stddef.h"
1216 // textual "stddef.h"
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()));
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))
1240 // If this is a #import directive, check that we have not already imported
1243 // If this has already been imported, don't import it again.
1244 FileInfo.isImport = true;
1246 // Has this already been #import'ed or #include'd?
1247 if (FileInfo.NumIncludes && !TryEnterImported())
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())
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
1263 if (M ? PP.isMacroDefinedInLocalModule(ControllingMacro, M)
1264 : PP.isMacroDefined(ControllingMacro)) {
1265 ++NumMultiIncludeFileOptzn;
1270 // Increment the number of times this file has been included.
1271 ++FileInfo.NumIncludes;
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();
1284 StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) {
1285 return FrameworkNames.insert(Framework).first->first();
1288 bool HeaderSearch::hasModuleMap(StringRef FileName,
1289 const DirectoryEntry *Root,
1291 if (!HSOpts->ImplicitModuleMaps)
1294 SmallVector<const DirectoryEntry *, 2> FixUpDirectories;
1296 StringRef DirName = FileName;
1298 // Get the parent directory name.
1299 DirName = llvm::sys::path::parent_path(DirName);
1300 if (DirName.empty())
1303 // Determine whether this directory exists.
1304 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
1308 // Try to load the module map file in this directory.
1309 switch (loadModuleMapFile(Dir, IsSystem,
1310 llvm::sys::path::extension(Dir->getName()) ==
1312 case LMM_NewlyLoaded:
1313 case LMM_AlreadyLoaded:
1314 // Success. All of the directories we stepped through inherit this module
1316 for (unsigned I = 0, N = FixUpDirectories.size(); I != N; ++I)
1317 DirectoryHasModuleMap[FixUpDirectories[I]] = true;
1320 case LMM_NoDirectory:
1321 case LMM_InvalidModuleMap:
1325 // If we hit the top of our search, we're done.
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);
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);
1343 return ModMap.findModuleForHeader(File, AllowTextual);
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()
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())) {
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);
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);
1389 // Determine the name of the top-level framework.
1390 StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
1392 // Load this framework module. If that succeeds, find the suggested module
1393 // for this header, if any.
1394 loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystemFramework);
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);
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");
1415 return FileMgr.getFile(PrivateFilename);
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(".");
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));
1433 auto *FakeFile = FileMgr.getVirtualFile(OriginalModuleMapFile, 0, 0);
1434 Dir = FakeFile->getDir();
1437 Dir = File->getDir();
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");
1451 switch (loadModuleMapFileImpl(File, IsSystem, Dir, ID, Offset)) {
1452 case LMM_AlreadyLoaded:
1453 case LMM_NewlyLoaded:
1455 case LMM_NoDirectory:
1456 case LMM_InvalidModuleMap:
1459 llvm_unreachable("Unknown load module map result");
1462 HeaderSearch::LoadModuleMapResult
1463 HeaderSearch::loadModuleMapFileImpl(const FileEntry *File, bool IsSystem,
1464 const DirectoryEntry *Dir, FileID ID,
1466 assert(File && "expected FileEntry");
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;
1474 if (ModMap.parseModuleMapFile(File, IsSystem, Dir, ID, Offset)) {
1475 LoadedModuleMaps[File] = false;
1476 return LMM_InvalidModuleMap;
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;
1487 // This directory has a module map.
1488 return LMM_NewlyLoaded;
1492 HeaderSearch::lookupModuleMapFile(const DirectoryEntry *Dir, bool IsFramework) {
1493 if (!HSOpts->ImplicitModuleMaps)
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());
1499 llvm::sys::path::append(ModuleMapFileName, "Modules");
1500 llvm::sys::path::append(ModuleMapFileName, "module.modulemap");
1501 if (const FileEntry *F = FileMgr.getFile(ModuleMapFileName))
1504 // Continue to allow module.map
1505 ModuleMapFileName = Dir->getName();
1506 llvm::sys::path::append(ModuleMapFileName, "module.map");
1507 return FileMgr.getFile(ModuleMapFileName);
1510 Module *HeaderSearch::loadFrameworkModule(StringRef Name,
1511 const DirectoryEntry *Dir,
1513 if (Module *Module = ModMap.findModule(Name))
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);
1524 case LMM_AlreadyLoaded:
1525 case LMM_NoDirectory:
1528 case LMM_NewlyLoaded:
1532 return ModMap.findModule(Name);
1535 HeaderSearch::LoadModuleMapResult
1536 HeaderSearch::loadModuleMapFile(StringRef DirName, bool IsSystem,
1538 if (const DirectoryEntry *Dir = FileMgr.getDirectory(DirName))
1539 return loadModuleMapFile(Dir, IsSystem, IsFramework);
1541 return LMM_NoDirectory;
1544 HeaderSearch::LoadModuleMapResult
1545 HeaderSearch::loadModuleMapFile(const DirectoryEntry *Dir, bool IsSystem,
1547 auto KnownDir = DirectoryHasModuleMap.find(Dir);
1548 if (KnownDir != DirectoryHasModuleMap.end())
1549 return KnownDir->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
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;
1563 return LMM_InvalidModuleMap;
1566 void HeaderSearch::collectAllModules(SmallVectorImpl<Module *> &Modules) {
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()) {
1575 SmallString<128> DirNative;
1576 llvm::sys::path::native(SearchDirs[Idx].getFrameworkDir()->getName(),
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")
1586 const DirectoryEntry *FrameworkDir =
1587 FileMgr.getDirectory(Dir->getName());
1591 // Load this framework module.
1592 loadFrameworkModule(llvm::sys::path::stem(Dir->getName()),
1593 FrameworkDir, IsSystem);
1598 // FIXME: Deal with header maps.
1599 if (SearchDirs[Idx].isHeaderMap())
1602 // Try to load a module map file for the search directory.
1603 loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem,
1604 /*IsFramework*/ false);
1606 // Try to load module map files for immediate subdirectories of this
1607 // search directory.
1608 loadSubdirectoryModuleMaps(SearchDirs[Idx]);
1612 // Populate the list of modules.
1613 for (ModuleMap::module_iterator M = ModMap.module_begin(),
1614 MEnd = ModMap.module_end();
1616 Modules.push_back(M->getValue());
1620 void HeaderSearch::loadTopLevelSystemModules() {
1621 if (!HSOpts->ImplicitModuleMaps)
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()) {
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());
1638 void HeaderSearch::loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir) {
1639 assert(HSOpts->ImplicitModuleMaps &&
1640 "Should not be loading subdirectory module maps");
1642 if (SearchDir.haveSearchedAllModuleMaps())
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)) {
1652 llvm::sys::path::extension(Dir->getName()) == ".framework";
1653 if (IsFramework == SearchDir.isFramework())
1654 loadModuleMapFile(Dir->getName(), SearchDir.isSystemHeaderDirectory(),
1655 SearchDir.isFramework());
1658 SearchDir.setSearchedAllModuleMaps(true);
1661 std::string HeaderSearch::suggestPathToFileForDiagnostics(const FileEntry *File,
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=*/"",
1670 std::string HeaderSearch::suggestPathToFileForDiagnostics(
1671 llvm::StringRef File, llvm::StringRef WorkingDir, bool *IsSystem) {
1672 using namespace llvm::sys;
1674 unsigned BestPrefixLength = 0;
1675 unsigned BestSearchDir;
1677 for (unsigned I = 0; I != SearchDirs.size(); ++I) {
1678 // FIXME: Support this search within frameworks and header maps.
1679 if (!SearchDirs[I].isNormalDir())
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);
1687 path::remove_dots(DirPath, /*remove_dot_dot=*/true);
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 == ".")
1699 // '.' components in Dir are ignored.
1700 while (DI != DE && *DI == ".")
1703 // Dir is a prefix of File, up to '.' components and choice of path
1705 unsigned PrefixLength = NI - path::begin(File);
1706 if (PrefixLength > BestPrefixLength) {
1707 BestPrefixLength = PrefixLength;
1719 *IsSystem = BestPrefixLength ? BestSearchDir >= SystemDirIdx : false;
1720 return File.drop_front(BestPrefixLength);