1 //===- HeaderSearch.cpp - Resolve Header File Locations -------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements the DirectoryLookup and HeaderSearch interfaces.
11 //===----------------------------------------------------------------------===//
13 #include "clang/Lex/HeaderSearch.h"
14 #include "clang/Basic/Diagnostic.h"
15 #include "clang/Basic/FileManager.h"
16 #include "clang/Basic/IdentifierTable.h"
17 #include "clang/Basic/Module.h"
18 #include "clang/Basic/SourceManager.h"
19 #include "clang/Lex/DirectoryLookup.h"
20 #include "clang/Lex/ExternalPreprocessorSource.h"
21 #include "clang/Lex/HeaderMap.h"
22 #include "clang/Lex/HeaderSearchOptions.h"
23 #include "clang/Lex/LexDiagnostic.h"
24 #include "clang/Lex/ModuleMap.h"
25 #include "clang/Lex/Preprocessor.h"
26 #include "llvm/ADT/APInt.h"
27 #include "llvm/ADT/Hashing.h"
28 #include "llvm/ADT/SmallString.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/StringRef.h"
31 #include "llvm/Support/Allocator.h"
32 #include "llvm/Support/Capacity.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/FileSystem.h"
35 #include "llvm/Support/Path.h"
36 #include "llvm/Support/VirtualFileSystem.h"
43 #include <system_error>
46 using namespace clang;
48 const IdentifierInfo *
49 HeaderFileInfo::getControllingMacro(ExternalPreprocessorSource *External) {
50 if (ControllingMacro) {
51 if (ControllingMacro->isOutOfDate()) {
52 assert(External && "We must have an external source if we have a "
53 "controlling macro that is out of date.");
54 External->updateOutOfDateIdentifier(
55 *const_cast<IdentifierInfo *>(ControllingMacro));
57 return ControllingMacro;
60 if (!ControllingMacroID || !External)
63 ControllingMacro = External->GetIdentifier(ControllingMacroID);
64 return ControllingMacro;
67 ExternalHeaderFileInfoSource::~ExternalHeaderFileInfoSource() = default;
69 HeaderSearch::HeaderSearch(std::shared_ptr<HeaderSearchOptions> HSOpts,
70 SourceManager &SourceMgr, DiagnosticsEngine &Diags,
71 const LangOptions &LangOpts,
72 const TargetInfo *Target)
73 : HSOpts(std::move(HSOpts)), Diags(Diags),
74 FileMgr(SourceMgr.getFileManager()), FrameworkMap(64),
75 ModMap(SourceMgr, Diags, LangOpts, Target, *this) {}
77 void HeaderSearch::PrintStats() {
78 fprintf(stderr, "\n*** HeaderSearch Stats:\n");
79 fprintf(stderr, "%d files tracked.\n", (int)FileInfo.size());
80 unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0;
81 for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) {
82 NumOnceOnlyFiles += FileInfo[i].isImport;
83 if (MaxNumIncludes < FileInfo[i].NumIncludes)
84 MaxNumIncludes = FileInfo[i].NumIncludes;
85 NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1;
87 fprintf(stderr, " %d #import/#pragma once files.\n", NumOnceOnlyFiles);
88 fprintf(stderr, " %d included exactly once.\n", NumSingleIncludedFiles);
89 fprintf(stderr, " %d max times a file is included.\n", MaxNumIncludes);
91 fprintf(stderr, " %d #include/#include_next/#import.\n", NumIncluded);
92 fprintf(stderr, " %d #includes skipped due to"
93 " the multi-include optimization.\n", NumMultiIncludeFileOptzn);
95 fprintf(stderr, "%d framework lookups.\n", NumFrameworkLookups);
96 fprintf(stderr, "%d subframework lookups.\n", NumSubFrameworkLookups);
99 /// CreateHeaderMap - This method returns a HeaderMap for the specified
100 /// FileEntry, uniquing them through the 'HeaderMaps' datastructure.
101 const HeaderMap *HeaderSearch::CreateHeaderMap(const FileEntry *FE) {
102 // We expect the number of headermaps to be small, and almost always empty.
103 // If it ever grows, use of a linear search should be re-evaluated.
104 if (!HeaderMaps.empty()) {
105 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
106 // Pointer equality comparison of FileEntries works because they are
107 // already uniqued by inode.
108 if (HeaderMaps[i].first == FE)
109 return HeaderMaps[i].second.get();
112 if (std::unique_ptr<HeaderMap> HM = HeaderMap::Create(FE, FileMgr)) {
113 HeaderMaps.emplace_back(FE, std::move(HM));
114 return HeaderMaps.back().second.get();
120 /// Get filenames for all registered header maps.
121 void HeaderSearch::getHeaderMapFileNames(
122 SmallVectorImpl<std::string> &Names) const {
123 for (auto &HM : HeaderMaps)
124 Names.push_back(HM.first->getName());
127 std::string HeaderSearch::getCachedModuleFileName(Module *Module) {
128 const FileEntry *ModuleMap =
129 getModuleMap().getModuleMapFileForUniquing(Module);
130 return getCachedModuleFileName(Module->Name, ModuleMap->getName());
133 std::string HeaderSearch::getPrebuiltModuleFileName(StringRef ModuleName,
135 // First check the module name to pcm file map.
136 auto i (HSOpts->PrebuiltModuleFiles.find(ModuleName));
137 if (i != HSOpts->PrebuiltModuleFiles.end())
140 if (FileMapOnly || HSOpts->PrebuiltModulePaths.empty())
143 // Then go through each prebuilt module directory and try to find the pcm
145 for (const std::string &Dir : HSOpts->PrebuiltModulePaths) {
146 SmallString<256> Result(Dir);
147 llvm::sys::fs::make_absolute(Result);
148 llvm::sys::path::append(Result, ModuleName + ".pcm");
149 if (getFileMgr().getFile(Result.str()))
150 return Result.str().str();
155 std::string HeaderSearch::getCachedModuleFileName(StringRef ModuleName,
156 StringRef ModuleMapPath) {
157 // If we don't have a module cache path or aren't supposed to use one, we
158 // can't do anything.
159 if (getModuleCachePath().empty())
162 SmallString<256> Result(getModuleCachePath());
163 llvm::sys::fs::make_absolute(Result);
165 if (HSOpts->DisableModuleHash) {
166 llvm::sys::path::append(Result, ModuleName + ".pcm");
168 // Construct the name <ModuleName>-<hash of ModuleMapPath>.pcm which should
169 // ideally be globally unique to this particular module. Name collisions
170 // in the hash are safe (because any translation unit can only import one
171 // module with each name), but result in a loss of caching.
173 // To avoid false-negatives, we form as canonical a path as we can, and map
174 // to lower-case in case we're on a case-insensitive file system.
175 std::string Parent = llvm::sys::path::parent_path(ModuleMapPath);
178 auto *Dir = FileMgr.getDirectory(Parent);
181 auto DirName = FileMgr.getCanonicalName(Dir);
182 auto FileName = llvm::sys::path::filename(ModuleMapPath);
184 llvm::hash_code Hash =
185 llvm::hash_combine(DirName.lower(), FileName.lower());
187 SmallString<128> HashStr;
188 llvm::APInt(64, size_t(Hash)).toStringUnsigned(HashStr, /*Radix*/36);
189 llvm::sys::path::append(Result, ModuleName + "-" + HashStr + ".pcm");
191 return Result.str().str();
194 Module *HeaderSearch::lookupModule(StringRef ModuleName, bool AllowSearch,
195 bool AllowExtraModuleMapSearch) {
196 // Look in the module map to determine if there is a module by this name.
197 Module *Module = ModMap.findModule(ModuleName);
198 if (Module || !AllowSearch || !HSOpts->ImplicitModuleMaps)
201 StringRef SearchName = ModuleName;
202 Module = lookupModule(ModuleName, SearchName, AllowExtraModuleMapSearch);
204 // The facility for "private modules" -- adjacent, optional module maps named
205 // module.private.modulemap that are supposed to define private submodules --
206 // may have different flavors of names: FooPrivate, Foo_Private and Foo.Private.
208 // Foo.Private is now deprecated in favor of Foo_Private. Users of FooPrivate
209 // should also rename to Foo_Private. Representing private as submodules
210 // could force building unwanted dependencies into the parent module and cause
211 // dependency cycles.
212 if (!Module && SearchName.consume_back("_Private"))
213 Module = lookupModule(ModuleName, SearchName, AllowExtraModuleMapSearch);
214 if (!Module && SearchName.consume_back("Private"))
215 Module = lookupModule(ModuleName, SearchName, AllowExtraModuleMapSearch);
219 Module *HeaderSearch::lookupModule(StringRef ModuleName, StringRef SearchName,
220 bool AllowExtraModuleMapSearch) {
221 Module *Module = nullptr;
223 // Look through the various header search paths to load any available module
224 // maps, searching for a module map that describes this module.
225 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
226 if (SearchDirs[Idx].isFramework()) {
227 // Search for or infer a module map for a framework. Here we use
228 // SearchName rather than ModuleName, to permit finding private modules
229 // named FooPrivate in buggy frameworks named Foo.
230 SmallString<128> FrameworkDirName;
231 FrameworkDirName += SearchDirs[Idx].getFrameworkDir()->getName();
232 llvm::sys::path::append(FrameworkDirName, SearchName + ".framework");
233 if (const DirectoryEntry *FrameworkDir
234 = FileMgr.getDirectory(FrameworkDirName)) {
236 = SearchDirs[Idx].getDirCharacteristic() != SrcMgr::C_User;
237 Module = loadFrameworkModule(ModuleName, FrameworkDir, IsSystem);
243 // FIXME: Figure out how header maps and module maps will work together.
245 // Only deal with normal search directories.
246 if (!SearchDirs[Idx].isNormalDir())
249 bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
250 // Search for a module map file in this directory.
251 if (loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem,
252 /*IsFramework*/false) == LMM_NewlyLoaded) {
253 // We just loaded a module map file; check whether the module is
255 Module = ModMap.findModule(ModuleName);
260 // Search for a module map in a subdirectory with the same name as the
262 SmallString<128> NestedModuleMapDirName;
263 NestedModuleMapDirName = SearchDirs[Idx].getDir()->getName();
264 llvm::sys::path::append(NestedModuleMapDirName, ModuleName);
265 if (loadModuleMapFile(NestedModuleMapDirName, IsSystem,
266 /*IsFramework*/false) == LMM_NewlyLoaded){
267 // If we just loaded a module map file, look for the module again.
268 Module = ModMap.findModule(ModuleName);
273 // If we've already performed the exhaustive search for module maps in this
274 // search directory, don't do it again.
275 if (SearchDirs[Idx].haveSearchedAllModuleMaps())
278 // Load all module maps in the immediate subdirectories of this search
279 // directory if ModuleName was from @import.
280 if (AllowExtraModuleMapSearch)
281 loadSubdirectoryModuleMaps(SearchDirs[Idx]);
283 // Look again for the module.
284 Module = ModMap.findModule(ModuleName);
292 //===----------------------------------------------------------------------===//
293 // File lookup within a DirectoryLookup scope
294 //===----------------------------------------------------------------------===//
296 /// getName - Return the directory or filename corresponding to this lookup
298 StringRef DirectoryLookup::getName() const {
300 return getDir()->getName();
302 return getFrameworkDir()->getName();
303 assert(isHeaderMap() && "Unknown DirectoryLookup");
304 return getHeaderMap()->getFileName();
307 const FileEntry *HeaderSearch::getFileAndSuggestModule(
308 StringRef FileName, SourceLocation IncludeLoc, const DirectoryEntry *Dir,
309 bool IsSystemHeaderDir, Module *RequestingModule,
310 ModuleMap::KnownHeader *SuggestedModule) {
311 // If we have a module map that might map this header, load it and
312 // check whether we'll have a suggestion for a module.
313 const FileEntry *File = getFileMgr().getFile(FileName, /*OpenFile=*/true);
317 // If there is a module that corresponds to this header, suggest it.
318 if (!findUsableModuleForHeader(File, Dir ? Dir : File->getDir(),
319 RequestingModule, SuggestedModule,
326 /// LookupFile - Lookup the specified file in this search path, returning it
327 /// if it exists or returning null if not.
328 const FileEntry *DirectoryLookup::LookupFile(
331 SourceLocation IncludeLoc,
332 SmallVectorImpl<char> *SearchPath,
333 SmallVectorImpl<char> *RelativePath,
334 Module *RequestingModule,
335 ModuleMap::KnownHeader *SuggestedModule,
336 bool &InUserSpecifiedSystemFramework,
337 bool &IsFrameworkFound,
339 SmallVectorImpl<char> &MappedName) const {
340 InUserSpecifiedSystemFramework = false;
341 HasBeenMapped = false;
343 SmallString<1024> TmpDir;
345 // Concatenate the requested file onto the directory.
346 TmpDir = getDir()->getName();
347 llvm::sys::path::append(TmpDir, Filename);
349 StringRef SearchPathRef(getDir()->getName());
351 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
354 RelativePath->clear();
355 RelativePath->append(Filename.begin(), Filename.end());
358 return HS.getFileAndSuggestModule(TmpDir, IncludeLoc, getDir(),
359 isSystemHeaderDirectory(),
360 RequestingModule, SuggestedModule);
364 return DoFrameworkLookup(Filename, HS, SearchPath, RelativePath,
365 RequestingModule, SuggestedModule,
366 InUserSpecifiedSystemFramework, IsFrameworkFound);
368 assert(isHeaderMap() && "Unknown directory lookup");
369 const HeaderMap *HM = getHeaderMap();
370 SmallString<1024> Path;
371 StringRef Dest = HM->lookupFilename(Filename, Path);
375 const FileEntry *Result;
377 // Check if the headermap maps the filename to a framework include
378 // ("Foo.h" -> "Foo/Foo.h"), in which case continue header lookup using the
379 // framework include.
380 if (llvm::sys::path::is_relative(Dest)) {
382 MappedName.append(Dest.begin(), Dest.end());
383 Filename = StringRef(MappedName.begin(), MappedName.size());
384 HasBeenMapped = true;
385 Result = HM->LookupFile(Filename, HS.getFileMgr());
387 Result = HS.getFileMgr().getFile(Dest);
392 StringRef SearchPathRef(getName());
394 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
397 RelativePath->clear();
398 RelativePath->append(Filename.begin(), Filename.end());
404 /// Given a framework directory, find the top-most framework directory.
406 /// \param FileMgr The file manager to use for directory lookups.
407 /// \param DirName The name of the framework directory.
408 /// \param SubmodulePath Will be populated with the submodule path from the
409 /// returned top-level module to the originally named framework.
410 static const DirectoryEntry *
411 getTopFrameworkDir(FileManager &FileMgr, StringRef DirName,
412 SmallVectorImpl<std::string> &SubmodulePath) {
413 assert(llvm::sys::path::extension(DirName) == ".framework" &&
414 "Not a framework directory");
416 // Note: as an egregious but useful hack we use the real path here, because
417 // frameworks moving between top-level frameworks to embedded frameworks tend
418 // to be symlinked, and we base the logical structure of modules on the
419 // physical layout. In particular, we need to deal with crazy includes like
421 // #include <Foo/Frameworks/Bar.framework/Headers/Wibble.h>
423 // where 'Bar' used to be embedded in 'Foo', is now a top-level framework
424 // which one should access with, e.g.,
426 // #include <Bar/Wibble.h>
428 // Similar issues occur when a top-level framework has moved into an
429 // embedded framework.
430 const DirectoryEntry *TopFrameworkDir = FileMgr.getDirectory(DirName);
431 DirName = FileMgr.getCanonicalName(TopFrameworkDir);
433 // Get the parent directory name.
434 DirName = llvm::sys::path::parent_path(DirName);
438 // Determine whether this directory exists.
439 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
443 // If this is a framework directory, then we're a subframework of this
445 if (llvm::sys::path::extension(DirName) == ".framework") {
446 SubmodulePath.push_back(llvm::sys::path::stem(DirName));
447 TopFrameworkDir = Dir;
451 return TopFrameworkDir;
454 static bool needModuleLookup(Module *RequestingModule,
455 bool HasSuggestedModule) {
456 return HasSuggestedModule ||
457 (RequestingModule && RequestingModule->NoUndeclaredIncludes);
460 /// DoFrameworkLookup - Do a lookup of the specified file in the current
461 /// DirectoryLookup, which is a framework directory.
462 const FileEntry *DirectoryLookup::DoFrameworkLookup(
463 StringRef Filename, HeaderSearch &HS, SmallVectorImpl<char> *SearchPath,
464 SmallVectorImpl<char> *RelativePath, Module *RequestingModule,
465 ModuleMap::KnownHeader *SuggestedModule,
466 bool &InUserSpecifiedSystemFramework, bool &IsFrameworkFound) const {
467 FileManager &FileMgr = HS.getFileMgr();
469 // Framework names must have a '/' in the filename.
470 size_t SlashPos = Filename.find('/');
471 if (SlashPos == StringRef::npos) return nullptr;
473 // Find out if this is the home for the specified framework, by checking
474 // HeaderSearch. Possible answers are yes/no and unknown.
475 FrameworkCacheEntry &CacheEntry =
476 HS.LookupFrameworkCache(Filename.substr(0, SlashPos));
478 // If it is known and in some other directory, fail.
479 if (CacheEntry.Directory && CacheEntry.Directory != getFrameworkDir())
482 // Otherwise, construct the path to this framework dir.
484 // FrameworkName = "/System/Library/Frameworks/"
485 SmallString<1024> FrameworkName;
486 FrameworkName += getFrameworkDir()->getName();
487 if (FrameworkName.empty() || FrameworkName.back() != '/')
488 FrameworkName.push_back('/');
490 // FrameworkName = "/System/Library/Frameworks/Cocoa"
491 StringRef ModuleName(Filename.begin(), SlashPos);
492 FrameworkName += ModuleName;
494 // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/"
495 FrameworkName += ".framework/";
497 // If the cache entry was unresolved, populate it now.
498 if (!CacheEntry.Directory) {
499 HS.IncrementFrameworkLookupCount();
501 // If the framework dir doesn't exist, we fail.
502 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName);
503 if (!Dir) return nullptr;
505 // Otherwise, if it does, remember that this is the right direntry for this
507 CacheEntry.Directory = getFrameworkDir();
509 // If this is a user search directory, check if the framework has been
510 // user-specified as a system framework.
511 if (getDirCharacteristic() == SrcMgr::C_User) {
512 SmallString<1024> SystemFrameworkMarker(FrameworkName);
513 SystemFrameworkMarker += ".system_framework";
514 if (llvm::sys::fs::exists(SystemFrameworkMarker)) {
515 CacheEntry.IsUserSpecifiedSystemFramework = true;
521 InUserSpecifiedSystemFramework = CacheEntry.IsUserSpecifiedSystemFramework;
522 IsFrameworkFound = CacheEntry.Directory;
525 RelativePath->clear();
526 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
529 // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"
530 unsigned OrigSize = FrameworkName.size();
532 FrameworkName += "Headers/";
536 // Without trailing '/'.
537 SearchPath->append(FrameworkName.begin(), FrameworkName.end()-1);
540 FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end());
541 const FileEntry *FE = FileMgr.getFile(FrameworkName,
542 /*OpenFile=*/!SuggestedModule);
544 // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"
545 const char *Private = "Private";
546 FrameworkName.insert(FrameworkName.begin()+OrigSize, Private,
547 Private+strlen(Private));
549 SearchPath->insert(SearchPath->begin()+OrigSize, Private,
550 Private+strlen(Private));
552 FE = FileMgr.getFile(FrameworkName, /*OpenFile=*/!SuggestedModule);
555 // If we found the header and are allowed to suggest a module, do so now.
556 if (FE && needModuleLookup(RequestingModule, SuggestedModule)) {
557 // Find the framework in which this header occurs.
558 StringRef FrameworkPath = FE->getDir()->getName();
559 bool FoundFramework = false;
561 // Determine whether this directory exists.
562 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkPath);
566 // If this is a framework directory, then we're a subframework of this
568 if (llvm::sys::path::extension(FrameworkPath) == ".framework") {
569 FoundFramework = true;
573 // Get the parent directory name.
574 FrameworkPath = llvm::sys::path::parent_path(FrameworkPath);
575 if (FrameworkPath.empty())
579 bool IsSystem = getDirCharacteristic() != SrcMgr::C_User;
580 if (FoundFramework) {
581 if (!HS.findUsableModuleForFrameworkHeader(
582 FE, FrameworkPath, RequestingModule, SuggestedModule, IsSystem))
585 if (!HS.findUsableModuleForHeader(FE, getDir(), RequestingModule,
586 SuggestedModule, IsSystem))
593 void HeaderSearch::setTarget(const TargetInfo &Target) {
594 ModMap.setTarget(Target);
597 //===----------------------------------------------------------------------===//
598 // Header File Location.
599 //===----------------------------------------------------------------------===//
601 /// Return true with a diagnostic if the file that MSVC would have found
602 /// fails to match the one that Clang would have found with MSVC header search
604 static bool checkMSVCHeaderSearch(DiagnosticsEngine &Diags,
605 const FileEntry *MSFE, const FileEntry *FE,
606 SourceLocation IncludeLoc) {
607 if (MSFE && FE != MSFE) {
608 Diags.Report(IncludeLoc, diag::ext_pp_include_search_ms) << MSFE->getName();
614 static const char *copyString(StringRef Str, llvm::BumpPtrAllocator &Alloc) {
615 assert(!Str.empty());
616 char *CopyStr = Alloc.Allocate<char>(Str.size()+1);
617 std::copy(Str.begin(), Str.end(), CopyStr);
618 CopyStr[Str.size()] = '\0';
622 static bool isFrameworkStylePath(StringRef Path, bool &IsPrivateHeader,
623 SmallVectorImpl<char> &FrameworkName) {
624 using namespace llvm::sys;
625 path::const_iterator I = path::begin(Path);
626 path::const_iterator E = path::end(Path);
627 IsPrivateHeader = false;
629 // Detect different types of framework style paths:
631 // ...Foo.framework/{Headers,PrivateHeaders}
632 // ...Foo.framework/Versions/{A,Current}/{Headers,PrivateHeaders}
633 // ...Foo.framework/Frameworks/Nested.framework/{Headers,PrivateHeaders}
634 // ...<other variations with 'Versions' like in the above path>
636 // and some other variations among these lines.
641 if (I->endswith(".framework")) {
642 FrameworkName.append(I->begin(), I->end());
645 if (*I == "PrivateHeaders") {
647 IsPrivateHeader = true;
652 return !FrameworkName.empty() && FoundComp >= 2;
656 diagnoseFrameworkInclude(DiagnosticsEngine &Diags, SourceLocation IncludeLoc,
657 StringRef Includer, StringRef IncludeFilename,
658 const FileEntry *IncludeFE, bool isAngled = false,
659 bool FoundByHeaderMap = false) {
660 bool IsIncluderPrivateHeader = false;
661 SmallString<128> FromFramework, ToFramework;
662 if (!isFrameworkStylePath(Includer, IsIncluderPrivateHeader, FromFramework))
664 bool IsIncludeePrivateHeader = false;
665 bool IsIncludeeInFramework = isFrameworkStylePath(
666 IncludeFE->getName(), IsIncludeePrivateHeader, ToFramework);
668 if (!isAngled && !FoundByHeaderMap) {
669 SmallString<128> NewInclude("<");
670 if (IsIncludeeInFramework) {
671 NewInclude += StringRef(ToFramework).drop_back(10); // drop .framework
674 NewInclude += IncludeFilename;
676 Diags.Report(IncludeLoc, diag::warn_quoted_include_in_framework_header)
678 << FixItHint::CreateReplacement(IncludeLoc, NewInclude);
681 // Headers in Foo.framework/Headers should not include headers
682 // from Foo.framework/PrivateHeaders, since this violates public/private
683 // API boundaries and can cause modular dependency cycles.
684 if (!IsIncluderPrivateHeader && IsIncludeeInFramework &&
685 IsIncludeePrivateHeader && FromFramework == ToFramework)
686 Diags.Report(IncludeLoc, diag::warn_framework_include_private_from_public)
690 /// LookupFile - Given a "foo" or \<foo> reference, look up the indicated file,
691 /// return null on failure. isAngled indicates whether the file reference is
692 /// for system \#include's or not (i.e. using <> instead of ""). Includers, if
693 /// non-empty, indicates where the \#including file(s) are, in case a relative
694 /// search is needed. Microsoft mode will pass all \#including files.
695 const FileEntry *HeaderSearch::LookupFile(
696 StringRef Filename, SourceLocation IncludeLoc, bool isAngled,
697 const DirectoryLookup *FromDir, const DirectoryLookup *&CurDir,
698 ArrayRef<std::pair<const FileEntry *, const DirectoryEntry *>> Includers,
699 SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
700 Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule,
701 bool *IsMapped, bool *IsFrameworkFound, bool SkipCache,
702 bool BuildSystemModule) {
706 if (IsFrameworkFound)
707 *IsFrameworkFound = false;
710 *SuggestedModule = ModuleMap::KnownHeader();
712 // If 'Filename' is absolute, check to see if it exists and no searching.
713 if (llvm::sys::path::is_absolute(Filename)) {
716 // If this was an #include_next "/absolute/file", fail.
717 if (FromDir) return nullptr;
722 RelativePath->clear();
723 RelativePath->append(Filename.begin(), Filename.end());
725 // Otherwise, just return the file.
726 return getFileAndSuggestModule(Filename, IncludeLoc, nullptr,
727 /*IsSystemHeaderDir*/false,
728 RequestingModule, SuggestedModule);
731 // This is the header that MSVC's header search would have found.
732 const FileEntry *MSFE = nullptr;
733 ModuleMap::KnownHeader MSSuggestedModule;
735 // Unless disabled, check to see if the file is in the #includer's
736 // directory. This cannot be based on CurDir, because each includer could be
737 // a #include of a subdirectory (#include "foo/bar.h") and a subsequent
738 // include of "baz.h" should resolve to "whatever/foo/baz.h".
739 // This search is not done for <> headers.
740 if (!Includers.empty() && !isAngled && !NoCurDirSearch) {
741 SmallString<1024> TmpDir;
743 for (const auto &IncluderAndDir : Includers) {
744 const FileEntry *Includer = IncluderAndDir.first;
746 // Concatenate the requested file onto the directory.
747 // FIXME: Portability. Filename concatenation should be in sys::Path.
748 TmpDir = IncluderAndDir.second->getName();
749 TmpDir.push_back('/');
750 TmpDir.append(Filename.begin(), Filename.end());
752 // FIXME: We don't cache the result of getFileInfo across the call to
753 // getFileAndSuggestModule, because it's a reference to an element of
754 // a container that could be reallocated across this call.
756 // If we have no includer, that means we're processing a #include
757 // from a module build. We should treat this as a system header if we're
758 // building a [system] module.
759 bool IncluderIsSystemHeader =
760 Includer ? getFileInfo(Includer).DirInfo != SrcMgr::C_User :
762 if (const FileEntry *FE = getFileAndSuggestModule(
763 TmpDir, IncludeLoc, IncluderAndDir.second, IncluderIsSystemHeader,
764 RequestingModule, SuggestedModule)) {
766 assert(First && "only first includer can have no file");
770 // Leave CurDir unset.
771 // This file is a system header or C++ unfriendly if the old file is.
773 // Note that we only use one of FromHFI/ToHFI at once, due to potential
774 // reallocation of the underlying vector potentially making the first
775 // reference binding dangling.
776 HeaderFileInfo &FromHFI = getFileInfo(Includer);
777 unsigned DirInfo = FromHFI.DirInfo;
778 bool IndexHeaderMapHeader = FromHFI.IndexHeaderMapHeader;
779 StringRef Framework = FromHFI.Framework;
781 HeaderFileInfo &ToHFI = getFileInfo(FE);
782 ToHFI.DirInfo = DirInfo;
783 ToHFI.IndexHeaderMapHeader = IndexHeaderMapHeader;
784 ToHFI.Framework = Framework;
787 StringRef SearchPathRef(IncluderAndDir.second->getName());
789 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
792 RelativePath->clear();
793 RelativePath->append(Filename.begin(), Filename.end());
796 diagnoseFrameworkInclude(Diags, IncludeLoc,
797 IncluderAndDir.second->getName(), Filename,
802 // Otherwise, we found the path via MSVC header search rules. If
803 // -Wmsvc-include is enabled, we have to keep searching to see if we
804 // would've found this header in -I or -isystem directories.
805 if (Diags.isIgnored(diag::ext_pp_include_search_ms, IncludeLoc)) {
809 if (SuggestedModule) {
810 MSSuggestedModule = *SuggestedModule;
811 *SuggestedModule = ModuleMap::KnownHeader();
822 // If this is a system #include, ignore the user #include locs.
823 unsigned i = isAngled ? AngledDirIdx : 0;
825 // If this is a #include_next request, start searching after the directory the
826 // file was found in.
828 i = FromDir-&SearchDirs[0];
830 // Cache all of the lookups performed by this method. Many headers are
831 // multiply included, and the "pragma once" optimization prevents them from
832 // being relex/pp'd, but they would still have to search through a
833 // (potentially huge) series of SearchDirs to find it.
834 LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename];
836 // If the entry has been previously looked up, the first value will be
837 // non-zero. If the value is equal to i (the start point of our search), then
838 // this is a matching hit.
839 if (!SkipCache && CacheLookup.StartIdx == i+1) {
840 // Skip querying potentially lots of directories for this lookup.
841 i = CacheLookup.HitIdx;
842 if (CacheLookup.MappedName) {
843 Filename = CacheLookup.MappedName;
848 // Otherwise, this is the first query, or the previous query didn't match
849 // our search start. We will fill in our found location below, so prime the
850 // start point value.
851 CacheLookup.reset(/*StartIdx=*/i+1);
854 SmallString<64> MappedName;
856 // Check each directory in sequence to see if it contains this file.
857 for (; i != SearchDirs.size(); ++i) {
858 bool InUserSpecifiedSystemFramework = false;
859 bool HasBeenMapped = false;
860 bool IsFrameworkFoundInDir = false;
861 const FileEntry *FE = SearchDirs[i].LookupFile(
862 Filename, *this, IncludeLoc, SearchPath, RelativePath, RequestingModule,
863 SuggestedModule, InUserSpecifiedSystemFramework, IsFrameworkFoundInDir,
864 HasBeenMapped, MappedName);
866 CacheLookup.MappedName =
867 copyString(Filename, LookupFileCache.getAllocator());
871 if (IsFrameworkFound)
872 // Because we keep a filename remapped for subsequent search directory
873 // lookups, ignore IsFrameworkFoundInDir after the first remapping and not
874 // just for remapping in a current search directory.
875 *IsFrameworkFound |= (IsFrameworkFoundInDir && !CacheLookup.MappedName);
878 CurDir = &SearchDirs[i];
880 // This file is a system header or C++ unfriendly if the dir is.
881 HeaderFileInfo &HFI = getFileInfo(FE);
882 HFI.DirInfo = CurDir->getDirCharacteristic();
884 // If the directory characteristic is User but this framework was
885 // user-specified to be treated as a system framework, promote the
887 if (HFI.DirInfo == SrcMgr::C_User && InUserSpecifiedSystemFramework)
888 HFI.DirInfo = SrcMgr::C_System;
890 // If the filename matches a known system header prefix, override
891 // whether the file is a system header.
892 for (unsigned j = SystemHeaderPrefixes.size(); j; --j) {
893 if (Filename.startswith(SystemHeaderPrefixes[j-1].first)) {
894 HFI.DirInfo = SystemHeaderPrefixes[j-1].second ? SrcMgr::C_System
900 // If this file is found in a header map and uses the framework style of
901 // includes, then this header is part of a framework we're building.
902 if (CurDir->isIndexHeaderMap()) {
903 size_t SlashPos = Filename.find('/');
904 if (SlashPos != StringRef::npos) {
905 HFI.IndexHeaderMapHeader = 1;
906 HFI.Framework = getUniqueFrameworkName(StringRef(Filename.begin(),
911 if (checkMSVCHeaderSearch(Diags, MSFE, FE, IncludeLoc)) {
913 *SuggestedModule = MSSuggestedModule;
917 bool FoundByHeaderMap = !IsMapped ? false : *IsMapped;
918 if (!Includers.empty())
919 diagnoseFrameworkInclude(Diags, IncludeLoc,
920 Includers.front().second->getName(), Filename,
921 FE, isAngled, FoundByHeaderMap);
923 // Remember this location for the next lookup we do.
924 CacheLookup.HitIdx = i;
928 // If we are including a file with a quoted include "foo.h" from inside
929 // a header in a framework that is currently being built, and we couldn't
930 // resolve "foo.h" any other way, change the include to <Foo/foo.h>, where
931 // "Foo" is the name of the framework in which the including header was found.
932 if (!Includers.empty() && Includers.front().first && !isAngled &&
933 Filename.find('/') == StringRef::npos) {
934 HeaderFileInfo &IncludingHFI = getFileInfo(Includers.front().first);
935 if (IncludingHFI.IndexHeaderMapHeader) {
936 SmallString<128> ScratchFilename;
937 ScratchFilename += IncludingHFI.Framework;
938 ScratchFilename += '/';
939 ScratchFilename += Filename;
941 const FileEntry *FE = LookupFile(
942 ScratchFilename, IncludeLoc, /*isAngled=*/true, FromDir, CurDir,
943 Includers.front(), SearchPath, RelativePath, RequestingModule,
944 SuggestedModule, IsMapped, /*IsFrameworkFound=*/nullptr);
946 if (checkMSVCHeaderSearch(Diags, MSFE, FE, IncludeLoc)) {
948 *SuggestedModule = MSSuggestedModule;
952 LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename];
953 CacheLookup.HitIdx = LookupFileCache[ScratchFilename].HitIdx;
954 // FIXME: SuggestedModule.
959 if (checkMSVCHeaderSearch(Diags, MSFE, nullptr, IncludeLoc)) {
961 *SuggestedModule = MSSuggestedModule;
965 // Otherwise, didn't find it. Remember we didn't find this.
966 CacheLookup.HitIdx = SearchDirs.size();
970 /// LookupSubframeworkHeader - Look up a subframework for the specified
971 /// \#include file. For example, if \#include'ing <HIToolbox/HIToolbox.h> from
972 /// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
973 /// is a subframework within Carbon.framework. If so, return the FileEntry
974 /// for the designated file, otherwise return null.
975 const FileEntry *HeaderSearch::
976 LookupSubframeworkHeader(StringRef Filename,
977 const FileEntry *ContextFileEnt,
978 SmallVectorImpl<char> *SearchPath,
979 SmallVectorImpl<char> *RelativePath,
980 Module *RequestingModule,
981 ModuleMap::KnownHeader *SuggestedModule) {
982 assert(ContextFileEnt && "No context file?");
984 // Framework names must have a '/' in the filename. Find it.
985 // FIXME: Should we permit '\' on Windows?
986 size_t SlashPos = Filename.find('/');
987 if (SlashPos == StringRef::npos) return nullptr;
989 // Look up the base framework name of the ContextFileEnt.
990 StringRef ContextName = ContextFileEnt->getName();
992 // If the context info wasn't a framework, couldn't be a subframework.
993 const unsigned DotFrameworkLen = 10;
994 auto FrameworkPos = ContextName.find(".framework");
995 if (FrameworkPos == StringRef::npos ||
996 (ContextName[FrameworkPos + DotFrameworkLen] != '/' &&
997 ContextName[FrameworkPos + DotFrameworkLen] != '\\'))
1000 SmallString<1024> FrameworkName(ContextName.data(), ContextName.data() +
1002 DotFrameworkLen + 1);
1004 // Append Frameworks/HIToolbox.framework/
1005 FrameworkName += "Frameworks/";
1006 FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos);
1007 FrameworkName += ".framework/";
1010 *FrameworkMap.insert(std::make_pair(Filename.substr(0, SlashPos),
1011 FrameworkCacheEntry())).first;
1013 // Some other location?
1014 if (CacheLookup.second.Directory &&
1015 CacheLookup.first().size() == FrameworkName.size() &&
1016 memcmp(CacheLookup.first().data(), &FrameworkName[0],
1017 CacheLookup.first().size()) != 0)
1020 // Cache subframework.
1021 if (!CacheLookup.second.Directory) {
1022 ++NumSubFrameworkLookups;
1024 // If the framework dir doesn't exist, we fail.
1025 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName);
1026 if (!Dir) return nullptr;
1028 // Otherwise, if it does, remember that this is the right direntry for this
1030 CacheLookup.second.Directory = Dir;
1033 const FileEntry *FE = nullptr;
1036 RelativePath->clear();
1037 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
1040 // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
1041 SmallString<1024> HeadersFilename(FrameworkName);
1042 HeadersFilename += "Headers/";
1044 SearchPath->clear();
1045 // Without trailing '/'.
1046 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
1049 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
1050 if (!(FE = FileMgr.getFile(HeadersFilename, /*OpenFile=*/true))) {
1051 // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
1052 HeadersFilename = FrameworkName;
1053 HeadersFilename += "PrivateHeaders/";
1055 SearchPath->clear();
1056 // Without trailing '/'.
1057 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
1060 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
1061 if (!(FE = FileMgr.getFile(HeadersFilename, /*OpenFile=*/true)))
1065 // This file is a system header or C++ unfriendly if the old file is.
1067 // Note that the temporary 'DirInfo' is required here, as either call to
1068 // getFileInfo could resize the vector and we don't want to rely on order
1070 unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo;
1071 getFileInfo(FE).DirInfo = DirInfo;
1073 FrameworkName.pop_back(); // remove the trailing '/'
1074 if (!findUsableModuleForFrameworkHeader(FE, FrameworkName, RequestingModule,
1075 SuggestedModule, /*IsSystem*/ false))
1081 //===----------------------------------------------------------------------===//
1082 // File Info Management.
1083 //===----------------------------------------------------------------------===//
1085 /// Merge the header file info provided by \p OtherHFI into the current
1086 /// header file info (\p HFI)
1087 static void mergeHeaderFileInfo(HeaderFileInfo &HFI,
1088 const HeaderFileInfo &OtherHFI) {
1089 assert(OtherHFI.External && "expected to merge external HFI");
1091 HFI.isImport |= OtherHFI.isImport;
1092 HFI.isPragmaOnce |= OtherHFI.isPragmaOnce;
1093 HFI.isModuleHeader |= OtherHFI.isModuleHeader;
1094 HFI.NumIncludes += OtherHFI.NumIncludes;
1096 if (!HFI.ControllingMacro && !HFI.ControllingMacroID) {
1097 HFI.ControllingMacro = OtherHFI.ControllingMacro;
1098 HFI.ControllingMacroID = OtherHFI.ControllingMacroID;
1101 HFI.DirInfo = OtherHFI.DirInfo;
1102 HFI.External = (!HFI.IsValid || HFI.External);
1104 HFI.IndexHeaderMapHeader = OtherHFI.IndexHeaderMapHeader;
1106 if (HFI.Framework.empty())
1107 HFI.Framework = OtherHFI.Framework;
1110 /// getFileInfo - Return the HeaderFileInfo structure for the specified
1112 HeaderFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) {
1113 if (FE->getUID() >= FileInfo.size())
1114 FileInfo.resize(FE->getUID() + 1);
1116 HeaderFileInfo *HFI = &FileInfo[FE->getUID()];
1117 // FIXME: Use a generation count to check whether this is really up to date.
1118 if (ExternalSource && !HFI->Resolved) {
1119 HFI->Resolved = true;
1120 auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE);
1122 HFI = &FileInfo[FE->getUID()];
1123 if (ExternalHFI.External)
1124 mergeHeaderFileInfo(*HFI, ExternalHFI);
1127 HFI->IsValid = true;
1128 // We have local information about this header file, so it's no longer
1129 // strictly external.
1130 HFI->External = false;
1134 const HeaderFileInfo *
1135 HeaderSearch::getExistingFileInfo(const FileEntry *FE,
1136 bool WantExternal) const {
1137 // If we have an external source, ensure we have the latest information.
1138 // FIXME: Use a generation count to check whether this is really up to date.
1139 HeaderFileInfo *HFI;
1140 if (ExternalSource) {
1141 if (FE->getUID() >= FileInfo.size()) {
1144 FileInfo.resize(FE->getUID() + 1);
1147 HFI = &FileInfo[FE->getUID()];
1148 if (!WantExternal && (!HFI->IsValid || HFI->External))
1150 if (!HFI->Resolved) {
1151 HFI->Resolved = true;
1152 auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE);
1154 HFI = &FileInfo[FE->getUID()];
1155 if (ExternalHFI.External)
1156 mergeHeaderFileInfo(*HFI, ExternalHFI);
1158 } else if (FE->getUID() >= FileInfo.size()) {
1161 HFI = &FileInfo[FE->getUID()];
1164 if (!HFI->IsValid || (HFI->External && !WantExternal))
1170 bool HeaderSearch::isFileMultipleIncludeGuarded(const FileEntry *File) {
1171 // Check if we've ever seen this file as a header.
1172 if (auto *HFI = getExistingFileInfo(File))
1173 return HFI->isPragmaOnce || HFI->isImport || HFI->ControllingMacro ||
1174 HFI->ControllingMacroID;
1178 void HeaderSearch::MarkFileModuleHeader(const FileEntry *FE,
1179 ModuleMap::ModuleHeaderRole Role,
1180 bool isCompilingModuleHeader) {
1181 bool isModularHeader = !(Role & ModuleMap::TextualHeader);
1183 // Don't mark the file info as non-external if there's nothing to change.
1184 if (!isCompilingModuleHeader) {
1185 if (!isModularHeader)
1187 auto *HFI = getExistingFileInfo(FE);
1188 if (HFI && HFI->isModuleHeader)
1192 auto &HFI = getFileInfo(FE);
1193 HFI.isModuleHeader |= isModularHeader;
1194 HFI.isCompilingModuleHeader |= isCompilingModuleHeader;
1197 bool HeaderSearch::ShouldEnterIncludeFile(Preprocessor &PP,
1198 const FileEntry *File, bool isImport,
1199 bool ModulesEnabled, Module *M) {
1200 ++NumIncluded; // Count # of attempted #includes.
1202 // Get information about this file.
1203 HeaderFileInfo &FileInfo = getFileInfo(File);
1205 // FIXME: this is a workaround for the lack of proper modules-aware support
1206 // for #import / #pragma once
1207 auto TryEnterImported = [&]() -> bool {
1208 if (!ModulesEnabled)
1210 // Ensure FileInfo bits are up to date.
1211 ModMap.resolveHeaderDirectives(File);
1212 // Modules with builtins are special; multiple modules use builtins as
1213 // modular headers, example:
1215 // module stddef { header "stddef.h" export * }
1217 // After module map parsing, this expands to:
1220 // header "/path_to_builtin_dirs/stddef.h"
1221 // textual "stddef.h"
1224 // It's common that libc++ and system modules will both define such
1225 // submodules. Make sure cached results for a builtin header won't
1226 // prevent other builtin modules to potentially enter the builtin header.
1227 // Note that builtins are header guarded and the decision to actually
1228 // enter them is postponed to the controlling macros logic below.
1229 bool TryEnterHdr = false;
1230 if (FileInfo.isCompilingModuleHeader && FileInfo.isModuleHeader)
1231 TryEnterHdr = File->getDir() == ModMap.getBuiltinDir() &&
1232 ModuleMap::isBuiltinHeader(
1233 llvm::sys::path::filename(File->getName()));
1235 // Textual headers can be #imported from different modules. Since ObjC
1236 // headers find in the wild might rely only on #import and do not contain
1237 // controlling macros, be conservative and only try to enter textual headers
1238 // if such macro is present.
1239 if (!FileInfo.isModuleHeader &&
1240 FileInfo.getControllingMacro(ExternalLookup))
1245 // If this is a #import directive, check that we have not already imported
1248 // If this has already been imported, don't import it again.
1249 FileInfo.isImport = true;
1251 // Has this already been #import'ed or #include'd?
1252 if (FileInfo.NumIncludes && !TryEnterImported())
1255 // Otherwise, if this is a #include of a file that was previously #import'd
1256 // or if this is the second #include of a #pragma once file, ignore it.
1257 if (FileInfo.isImport && !TryEnterImported())
1261 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
1262 // if the macro that guards it is defined, we know the #include has no effect.
1263 if (const IdentifierInfo *ControllingMacro
1264 = FileInfo.getControllingMacro(ExternalLookup)) {
1265 // If the header corresponds to a module, check whether the macro is already
1266 // defined in that module rather than checking in the current set of visible
1268 if (M ? PP.isMacroDefinedInLocalModule(ControllingMacro, M)
1269 : PP.isMacroDefined(ControllingMacro)) {
1270 ++NumMultiIncludeFileOptzn;
1275 // Increment the number of times this file has been included.
1276 ++FileInfo.NumIncludes;
1281 size_t HeaderSearch::getTotalMemory() const {
1282 return SearchDirs.capacity()
1283 + llvm::capacity_in_bytes(FileInfo)
1284 + llvm::capacity_in_bytes(HeaderMaps)
1285 + LookupFileCache.getAllocator().getTotalMemory()
1286 + FrameworkMap.getAllocator().getTotalMemory();
1289 StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) {
1290 return FrameworkNames.insert(Framework).first->first();
1293 bool HeaderSearch::hasModuleMap(StringRef FileName,
1294 const DirectoryEntry *Root,
1296 if (!HSOpts->ImplicitModuleMaps)
1299 SmallVector<const DirectoryEntry *, 2> FixUpDirectories;
1301 StringRef DirName = FileName;
1303 // Get the parent directory name.
1304 DirName = llvm::sys::path::parent_path(DirName);
1305 if (DirName.empty())
1308 // Determine whether this directory exists.
1309 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
1313 // Try to load the module map file in this directory.
1314 switch (loadModuleMapFile(Dir, IsSystem,
1315 llvm::sys::path::extension(Dir->getName()) ==
1317 case LMM_NewlyLoaded:
1318 case LMM_AlreadyLoaded:
1319 // Success. All of the directories we stepped through inherit this module
1321 for (unsigned I = 0, N = FixUpDirectories.size(); I != N; ++I)
1322 DirectoryHasModuleMap[FixUpDirectories[I]] = true;
1325 case LMM_NoDirectory:
1326 case LMM_InvalidModuleMap:
1330 // If we hit the top of our search, we're done.
1334 // Keep track of all of the directories we checked, so we can mark them as
1335 // having module maps if we eventually do find a module map.
1336 FixUpDirectories.push_back(Dir);
1340 ModuleMap::KnownHeader
1341 HeaderSearch::findModuleForHeader(const FileEntry *File,
1342 bool AllowTextual) const {
1343 if (ExternalSource) {
1344 // Make sure the external source has handled header info about this file,
1345 // which includes whether the file is part of a module.
1346 (void)getExistingFileInfo(File);
1348 return ModMap.findModuleForHeader(File, AllowTextual);
1351 static bool suggestModule(HeaderSearch &HS, const FileEntry *File,
1352 Module *RequestingModule,
1353 ModuleMap::KnownHeader *SuggestedModule) {
1354 ModuleMap::KnownHeader Module =
1355 HS.findModuleForHeader(File, /*AllowTextual*/true);
1356 if (SuggestedModule)
1357 *SuggestedModule = (Module.getRole() & ModuleMap::TextualHeader)
1358 ? ModuleMap::KnownHeader()
1361 // If this module specifies [no_undeclared_includes], we cannot find any
1362 // file that's in a non-dependency module.
1363 if (RequestingModule && Module && RequestingModule->NoUndeclaredIncludes) {
1364 HS.getModuleMap().resolveUses(RequestingModule, /*Complain*/false);
1365 if (!RequestingModule->directlyUses(Module.getModule())) {
1373 bool HeaderSearch::findUsableModuleForHeader(
1374 const FileEntry *File, const DirectoryEntry *Root, Module *RequestingModule,
1375 ModuleMap::KnownHeader *SuggestedModule, bool IsSystemHeaderDir) {
1376 if (File && needModuleLookup(RequestingModule, SuggestedModule)) {
1377 // If there is a module that corresponds to this header, suggest it.
1378 hasModuleMap(File->getName(), Root, IsSystemHeaderDir);
1379 return suggestModule(*this, File, RequestingModule, SuggestedModule);
1384 bool HeaderSearch::findUsableModuleForFrameworkHeader(
1385 const FileEntry *File, StringRef FrameworkName, Module *RequestingModule,
1386 ModuleMap::KnownHeader *SuggestedModule, bool IsSystemFramework) {
1387 // If we're supposed to suggest a module, look for one now.
1388 if (needModuleLookup(RequestingModule, SuggestedModule)) {
1389 // Find the top-level framework based on this framework.
1390 SmallVector<std::string, 4> SubmodulePath;
1391 const DirectoryEntry *TopFrameworkDir
1392 = ::getTopFrameworkDir(FileMgr, FrameworkName, SubmodulePath);
1394 // Determine the name of the top-level framework.
1395 StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
1397 // Load this framework module. If that succeeds, find the suggested module
1398 // for this header, if any.
1399 loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystemFramework);
1401 // FIXME: This can find a module not part of ModuleName, which is
1402 // important so that we're consistent about whether this header
1403 // corresponds to a module. Possibly we should lock down framework modules
1404 // so that this is not possible.
1405 return suggestModule(*this, File, RequestingModule, SuggestedModule);
1410 static const FileEntry *getPrivateModuleMap(const FileEntry *File,
1411 FileManager &FileMgr) {
1412 StringRef Filename = llvm::sys::path::filename(File->getName());
1413 SmallString<128> PrivateFilename(File->getDir()->getName());
1414 if (Filename == "module.map")
1415 llvm::sys::path::append(PrivateFilename, "module_private.map");
1416 else if (Filename == "module.modulemap")
1417 llvm::sys::path::append(PrivateFilename, "module.private.modulemap");
1420 return FileMgr.getFile(PrivateFilename);
1423 bool HeaderSearch::loadModuleMapFile(const FileEntry *File, bool IsSystem,
1424 FileID ID, unsigned *Offset,
1425 StringRef OriginalModuleMapFile) {
1426 // Find the directory for the module. For frameworks, that may require going
1427 // up from the 'Modules' directory.
1428 const DirectoryEntry *Dir = nullptr;
1429 if (getHeaderSearchOpts().ModuleMapFileHomeIsCwd)
1430 Dir = FileMgr.getDirectory(".");
1432 if (!OriginalModuleMapFile.empty()) {
1433 // We're building a preprocessed module map. Find or invent the directory
1434 // that it originally occupied.
1435 Dir = FileMgr.getDirectory(
1436 llvm::sys::path::parent_path(OriginalModuleMapFile));
1438 auto *FakeFile = FileMgr.getVirtualFile(OriginalModuleMapFile, 0, 0);
1439 Dir = FakeFile->getDir();
1442 Dir = File->getDir();
1445 StringRef DirName(Dir->getName());
1446 if (llvm::sys::path::filename(DirName) == "Modules") {
1447 DirName = llvm::sys::path::parent_path(DirName);
1448 if (DirName.endswith(".framework"))
1449 Dir = FileMgr.getDirectory(DirName);
1450 // FIXME: This assert can fail if there's a race between the above check
1451 // and the removal of the directory.
1452 assert(Dir && "parent must exist");
1456 switch (loadModuleMapFileImpl(File, IsSystem, Dir, ID, Offset)) {
1457 case LMM_AlreadyLoaded:
1458 case LMM_NewlyLoaded:
1460 case LMM_NoDirectory:
1461 case LMM_InvalidModuleMap:
1464 llvm_unreachable("Unknown load module map result");
1467 HeaderSearch::LoadModuleMapResult
1468 HeaderSearch::loadModuleMapFileImpl(const FileEntry *File, bool IsSystem,
1469 const DirectoryEntry *Dir, FileID ID,
1471 assert(File && "expected FileEntry");
1473 // Check whether we've already loaded this module map, and mark it as being
1474 // loaded in case we recursively try to load it from itself.
1475 auto AddResult = LoadedModuleMaps.insert(std::make_pair(File, true));
1476 if (!AddResult.second)
1477 return AddResult.first->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
1479 if (ModMap.parseModuleMapFile(File, IsSystem, Dir, ID, Offset)) {
1480 LoadedModuleMaps[File] = false;
1481 return LMM_InvalidModuleMap;
1484 // Try to load a corresponding private module map.
1485 if (const FileEntry *PMMFile = getPrivateModuleMap(File, FileMgr)) {
1486 if (ModMap.parseModuleMapFile(PMMFile, IsSystem, Dir)) {
1487 LoadedModuleMaps[File] = false;
1488 return LMM_InvalidModuleMap;
1492 // This directory has a module map.
1493 return LMM_NewlyLoaded;
1497 HeaderSearch::lookupModuleMapFile(const DirectoryEntry *Dir, bool IsFramework) {
1498 if (!HSOpts->ImplicitModuleMaps)
1500 // For frameworks, the preferred spelling is Modules/module.modulemap, but
1501 // module.map at the framework root is also accepted.
1502 SmallString<128> ModuleMapFileName(Dir->getName());
1504 llvm::sys::path::append(ModuleMapFileName, "Modules");
1505 llvm::sys::path::append(ModuleMapFileName, "module.modulemap");
1506 if (const FileEntry *F = FileMgr.getFile(ModuleMapFileName))
1509 // Continue to allow module.map
1510 ModuleMapFileName = Dir->getName();
1511 llvm::sys::path::append(ModuleMapFileName, "module.map");
1512 return FileMgr.getFile(ModuleMapFileName);
1515 Module *HeaderSearch::loadFrameworkModule(StringRef Name,
1516 const DirectoryEntry *Dir,
1518 if (Module *Module = ModMap.findModule(Name))
1521 // Try to load a module map file.
1522 switch (loadModuleMapFile(Dir, IsSystem, /*IsFramework*/true)) {
1523 case LMM_InvalidModuleMap:
1524 // Try to infer a module map from the framework directory.
1525 if (HSOpts->ImplicitModuleMaps)
1526 ModMap.inferFrameworkModule(Dir, IsSystem, /*Parent=*/nullptr);
1529 case LMM_AlreadyLoaded:
1530 case LMM_NoDirectory:
1533 case LMM_NewlyLoaded:
1537 return ModMap.findModule(Name);
1540 HeaderSearch::LoadModuleMapResult
1541 HeaderSearch::loadModuleMapFile(StringRef DirName, bool IsSystem,
1543 if (const DirectoryEntry *Dir = FileMgr.getDirectory(DirName))
1544 return loadModuleMapFile(Dir, IsSystem, IsFramework);
1546 return LMM_NoDirectory;
1549 HeaderSearch::LoadModuleMapResult
1550 HeaderSearch::loadModuleMapFile(const DirectoryEntry *Dir, bool IsSystem,
1552 auto KnownDir = DirectoryHasModuleMap.find(Dir);
1553 if (KnownDir != DirectoryHasModuleMap.end())
1554 return KnownDir->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
1556 if (const FileEntry *ModuleMapFile = lookupModuleMapFile(Dir, IsFramework)) {
1557 LoadModuleMapResult Result =
1558 loadModuleMapFileImpl(ModuleMapFile, IsSystem, Dir);
1559 // Add Dir explicitly in case ModuleMapFile is in a subdirectory.
1560 // E.g. Foo.framework/Modules/module.modulemap
1561 // ^Dir ^ModuleMapFile
1562 if (Result == LMM_NewlyLoaded)
1563 DirectoryHasModuleMap[Dir] = true;
1564 else if (Result == LMM_InvalidModuleMap)
1565 DirectoryHasModuleMap[Dir] = false;
1568 return LMM_InvalidModuleMap;
1571 void HeaderSearch::collectAllModules(SmallVectorImpl<Module *> &Modules) {
1574 if (HSOpts->ImplicitModuleMaps) {
1575 // Load module maps for each of the header search directories.
1576 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
1577 bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
1578 if (SearchDirs[Idx].isFramework()) {
1580 SmallString<128> DirNative;
1581 llvm::sys::path::native(SearchDirs[Idx].getFrameworkDir()->getName(),
1584 // Search each of the ".framework" directories to load them as modules.
1585 llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
1586 for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC),
1588 Dir != DirEnd && !EC; Dir.increment(EC)) {
1589 if (llvm::sys::path::extension(Dir->path()) != ".framework")
1592 const DirectoryEntry *FrameworkDir =
1593 FileMgr.getDirectory(Dir->path());
1597 // Load this framework module.
1598 loadFrameworkModule(llvm::sys::path::stem(Dir->path()), FrameworkDir,
1604 // FIXME: Deal with header maps.
1605 if (SearchDirs[Idx].isHeaderMap())
1608 // Try to load a module map file for the search directory.
1609 loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem,
1610 /*IsFramework*/ false);
1612 // Try to load module map files for immediate subdirectories of this
1613 // search directory.
1614 loadSubdirectoryModuleMaps(SearchDirs[Idx]);
1618 // Populate the list of modules.
1619 for (ModuleMap::module_iterator M = ModMap.module_begin(),
1620 MEnd = ModMap.module_end();
1622 Modules.push_back(M->getValue());
1626 void HeaderSearch::loadTopLevelSystemModules() {
1627 if (!HSOpts->ImplicitModuleMaps)
1630 // Load module maps for each of the header search directories.
1631 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
1632 // We only care about normal header directories.
1633 if (!SearchDirs[Idx].isNormalDir()) {
1637 // Try to load a module map file for the search directory.
1638 loadModuleMapFile(SearchDirs[Idx].getDir(),
1639 SearchDirs[Idx].isSystemHeaderDirectory(),
1640 SearchDirs[Idx].isFramework());
1644 void HeaderSearch::loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir) {
1645 assert(HSOpts->ImplicitModuleMaps &&
1646 "Should not be loading subdirectory module maps");
1648 if (SearchDir.haveSearchedAllModuleMaps())
1652 SmallString<128> Dir = SearchDir.getDir()->getName();
1653 FileMgr.makeAbsolutePath(Dir);
1654 SmallString<128> DirNative;
1655 llvm::sys::path::native(Dir, DirNative);
1656 llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
1657 for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
1658 Dir != DirEnd && !EC; Dir.increment(EC)) {
1659 bool IsFramework = llvm::sys::path::extension(Dir->path()) == ".framework";
1660 if (IsFramework == SearchDir.isFramework())
1661 loadModuleMapFile(Dir->path(), SearchDir.isSystemHeaderDirectory(),
1662 SearchDir.isFramework());
1665 SearchDir.setSearchedAllModuleMaps(true);
1668 std::string HeaderSearch::suggestPathToFileForDiagnostics(
1669 const FileEntry *File, llvm::StringRef MainFile, bool *IsSystem) {
1670 // FIXME: We assume that the path name currently cached in the FileEntry is
1671 // the most appropriate one for this analysis (and that it's spelled the
1672 // same way as the corresponding header search path).
1673 return suggestPathToFileForDiagnostics(File->getName(), /*WorkingDir=*/"",
1674 MainFile, IsSystem);
1677 std::string HeaderSearch::suggestPathToFileForDiagnostics(
1678 llvm::StringRef File, llvm::StringRef WorkingDir, llvm::StringRef MainFile,
1680 using namespace llvm::sys;
1682 unsigned BestPrefixLength = 0;
1683 // Checks whether Dir and File shares a common prefix, if they do and that's
1684 // the longest prefix we've seen so for it returns true and updates the
1685 // BestPrefixLength accordingly.
1686 auto CheckDir = [&](llvm::StringRef Dir) -> bool {
1687 llvm::SmallString<32> DirPath(Dir.begin(), Dir.end());
1688 if (!WorkingDir.empty() && !path::is_absolute(Dir))
1689 fs::make_absolute(WorkingDir, DirPath);
1690 path::remove_dots(DirPath, /*remove_dot_dot=*/true);
1692 for (auto NI = path::begin(File), NE = path::end(File),
1693 DI = path::begin(Dir), DE = path::end(Dir);
1694 /*termination condition in loop*/; ++NI, ++DI) {
1695 // '.' components in File are ignored.
1696 while (NI != NE && *NI == ".")
1701 // '.' components in Dir are ignored.
1702 while (DI != DE && *DI == ".")
1705 // Dir is a prefix of File, up to '.' components and choice of path
1707 unsigned PrefixLength = NI - path::begin(File);
1708 if (PrefixLength > BestPrefixLength) {
1709 BestPrefixLength = PrefixLength;
1715 // Consider all path separators equal.
1716 if (NI->size() == 1 && DI->size() == 1 &&
1717 path::is_separator(NI->front()) && path::is_separator(DI->front()))
1726 for (unsigned I = 0; I != SearchDirs.size(); ++I) {
1727 // FIXME: Support this search within frameworks and header maps.
1728 if (!SearchDirs[I].isNormalDir())
1731 StringRef Dir = SearchDirs[I].getDir()->getName();
1732 if (CheckDir(Dir) && IsSystem)
1733 *IsSystem = BestPrefixLength ? I >= SystemDirIdx : false;
1736 // Try to shorten include path using TUs directory, if we couldn't find any
1737 // suitable prefix in include search paths.
1738 if (!BestPrefixLength && CheckDir(path::parent_path(MainFile)) && IsSystem)
1742 return path::convert_to_slash(File.drop_front(BestPrefixLength));