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/Statistic.h"
31 #include "llvm/ADT/StringRef.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/Support/Allocator.h"
34 #include "llvm/Support/Capacity.h"
35 #include "llvm/Support/Errc.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/FileSystem.h"
38 #include "llvm/Support/Path.h"
39 #include "llvm/Support/VirtualFileSystem.h"
46 #include <system_error>
49 using namespace clang
;
51 #define DEBUG_TYPE "file-search"
53 ALWAYS_ENABLED_STATISTIC(NumIncluded
, "Number of attempted #includes.");
54 ALWAYS_ENABLED_STATISTIC(
55 NumMultiIncludeFileOptzn
,
56 "Number of #includes skipped due to the multi-include optimization.");
57 ALWAYS_ENABLED_STATISTIC(NumFrameworkLookups
, "Number of framework lookups.");
58 ALWAYS_ENABLED_STATISTIC(NumSubFrameworkLookups
,
59 "Number of subframework lookups.");
61 const IdentifierInfo
*
62 HeaderFileInfo::getControllingMacro(ExternalPreprocessorSource
*External
) {
63 if (ControllingMacro
) {
64 if (ControllingMacro
->isOutOfDate()) {
65 assert(External
&& "We must have an external source if we have a "
66 "controlling macro that is out of date.");
67 External
->updateOutOfDateIdentifier(
68 *const_cast<IdentifierInfo
*>(ControllingMacro
));
70 return ControllingMacro
;
73 if (!ControllingMacroID
|| !External
)
76 ControllingMacro
= External
->GetIdentifier(ControllingMacroID
);
77 return ControllingMacro
;
80 ExternalHeaderFileInfoSource::~ExternalHeaderFileInfoSource() = default;
82 HeaderSearch::HeaderSearch(std::shared_ptr
<HeaderSearchOptions
> HSOpts
,
83 SourceManager
&SourceMgr
, DiagnosticsEngine
&Diags
,
84 const LangOptions
&LangOpts
,
85 const TargetInfo
*Target
)
86 : HSOpts(std::move(HSOpts
)), Diags(Diags
),
87 FileMgr(SourceMgr
.getFileManager()), FrameworkMap(64),
88 ModMap(SourceMgr
, Diags
, LangOpts
, Target
, *this) {}
90 void HeaderSearch::PrintStats() {
91 llvm::errs() << "\n*** HeaderSearch Stats:\n"
92 << FileInfo
.size() << " files tracked.\n";
93 unsigned NumOnceOnlyFiles
= 0;
94 for (unsigned i
= 0, e
= FileInfo
.size(); i
!= e
; ++i
)
95 NumOnceOnlyFiles
+= (FileInfo
[i
].isPragmaOnce
|| FileInfo
[i
].isImport
);
96 llvm::errs() << " " << NumOnceOnlyFiles
<< " #import/#pragma once files.\n";
98 llvm::errs() << " " << NumIncluded
<< " #include/#include_next/#import.\n"
99 << " " << NumMultiIncludeFileOptzn
100 << " #includes skipped due to the multi-include optimization.\n";
102 llvm::errs() << NumFrameworkLookups
<< " framework lookups.\n"
103 << NumSubFrameworkLookups
<< " subframework lookups.\n";
106 void HeaderSearch::SetSearchPaths(
107 std::vector
<DirectoryLookup
> dirs
, unsigned int angledDirIdx
,
108 unsigned int systemDirIdx
, bool noCurDirSearch
,
109 llvm::DenseMap
<unsigned int, unsigned int> searchDirToHSEntry
) {
110 assert(angledDirIdx
<= systemDirIdx
&& systemDirIdx
<= dirs
.size() &&
111 "Directory indices are unordered");
112 SearchDirs
= std::move(dirs
);
113 SearchDirsUsage
.assign(SearchDirs
.size(), false);
114 AngledDirIdx
= angledDirIdx
;
115 SystemDirIdx
= systemDirIdx
;
116 NoCurDirSearch
= noCurDirSearch
;
117 SearchDirToHSEntry
= std::move(searchDirToHSEntry
);
118 //LookupFileCache.clear();
119 indexInitialHeaderMaps();
122 void HeaderSearch::AddSearchPath(const DirectoryLookup
&dir
, bool isAngled
) {
123 unsigned idx
= isAngled
? SystemDirIdx
: AngledDirIdx
;
124 SearchDirs
.insert(SearchDirs
.begin() + idx
, dir
);
125 SearchDirsUsage
.insert(SearchDirsUsage
.begin() + idx
, false);
131 std::vector
<bool> HeaderSearch::computeUserEntryUsage() const {
132 std::vector
<bool> UserEntryUsage(HSOpts
->UserEntries
.size());
133 for (unsigned I
= 0, E
= SearchDirsUsage
.size(); I
< E
; ++I
) {
134 // Check whether this DirectoryLookup has been successfully used.
135 if (SearchDirsUsage
[I
]) {
136 auto UserEntryIdxIt
= SearchDirToHSEntry
.find(I
);
137 // Check whether this DirectoryLookup maps to a HeaderSearch::UserEntry.
138 if (UserEntryIdxIt
!= SearchDirToHSEntry
.end())
139 UserEntryUsage
[UserEntryIdxIt
->second
] = true;
142 return UserEntryUsage
;
145 /// CreateHeaderMap - This method returns a HeaderMap for the specified
146 /// FileEntry, uniquing them through the 'HeaderMaps' datastructure.
147 const HeaderMap
*HeaderSearch::CreateHeaderMap(FileEntryRef FE
) {
148 // We expect the number of headermaps to be small, and almost always empty.
149 // If it ever grows, use of a linear search should be re-evaluated.
150 if (!HeaderMaps
.empty()) {
151 for (unsigned i
= 0, e
= HeaderMaps
.size(); i
!= e
; ++i
)
152 // Pointer equality comparison of FileEntries works because they are
153 // already uniqued by inode.
154 if (HeaderMaps
[i
].first
== FE
)
155 return HeaderMaps
[i
].second
.get();
158 if (std::unique_ptr
<HeaderMap
> HM
= HeaderMap::Create(FE
, FileMgr
)) {
159 HeaderMaps
.emplace_back(FE
, std::move(HM
));
160 return HeaderMaps
.back().second
.get();
166 /// Get filenames for all registered header maps.
167 void HeaderSearch::getHeaderMapFileNames(
168 SmallVectorImpl
<std::string
> &Names
) const {
169 for (auto &HM
: HeaderMaps
)
170 Names
.push_back(std::string(HM
.first
.getName()));
173 std::string
HeaderSearch::getCachedModuleFileName(Module
*Module
) {
174 OptionalFileEntryRef ModuleMap
=
175 getModuleMap().getModuleMapFileForUniquing(Module
);
176 // The ModuleMap maybe a nullptr, when we load a cached C++ module without
177 // *.modulemap file. In this case, just return an empty string.
180 return getCachedModuleFileName(Module
->Name
, ModuleMap
->getNameAsRequested());
183 std::string
HeaderSearch::getPrebuiltModuleFileName(StringRef ModuleName
,
185 // First check the module name to pcm file map.
186 auto i(HSOpts
->PrebuiltModuleFiles
.find(ModuleName
));
187 if (i
!= HSOpts
->PrebuiltModuleFiles
.end())
190 if (FileMapOnly
|| HSOpts
->PrebuiltModulePaths
.empty())
193 // Then go through each prebuilt module directory and try to find the pcm
195 for (const std::string
&Dir
: HSOpts
->PrebuiltModulePaths
) {
196 SmallString
<256> Result(Dir
);
197 llvm::sys::fs::make_absolute(Result
);
198 if (ModuleName
.contains(':'))
199 // The separator of C++20 modules partitions (':') is not good for file
200 // systems, here clang and gcc choose '-' by default since it is not a
201 // valid character of C++ indentifiers. So we could avoid conflicts.
202 llvm::sys::path::append(Result
, ModuleName
.split(':').first
+ "-" +
203 ModuleName
.split(':').second
+
206 llvm::sys::path::append(Result
, ModuleName
+ ".pcm");
207 if (getFileMgr().getFile(Result
.str()))
208 return std::string(Result
);
214 std::string
HeaderSearch::getPrebuiltImplicitModuleFileName(Module
*Module
) {
215 OptionalFileEntryRef ModuleMap
=
216 getModuleMap().getModuleMapFileForUniquing(Module
);
217 StringRef ModuleName
= Module
->Name
;
218 StringRef ModuleMapPath
= ModuleMap
->getName();
219 StringRef ModuleCacheHash
= HSOpts
->DisableModuleHash
? "" : getModuleHash();
220 for (const std::string
&Dir
: HSOpts
->PrebuiltModulePaths
) {
221 SmallString
<256> CachePath(Dir
);
222 llvm::sys::fs::make_absolute(CachePath
);
223 llvm::sys::path::append(CachePath
, ModuleCacheHash
);
224 std::string FileName
=
225 getCachedModuleFileNameImpl(ModuleName
, ModuleMapPath
, CachePath
);
226 if (!FileName
.empty() && getFileMgr().getFile(FileName
))
232 std::string
HeaderSearch::getCachedModuleFileName(StringRef ModuleName
,
233 StringRef ModuleMapPath
) {
234 return getCachedModuleFileNameImpl(ModuleName
, ModuleMapPath
,
235 getModuleCachePath());
238 std::string
HeaderSearch::getCachedModuleFileNameImpl(StringRef ModuleName
,
239 StringRef ModuleMapPath
,
240 StringRef CachePath
) {
241 // If we don't have a module cache path or aren't supposed to use one, we
242 // can't do anything.
243 if (CachePath
.empty())
246 SmallString
<256> Result(CachePath
);
247 llvm::sys::fs::make_absolute(Result
);
249 if (HSOpts
->DisableModuleHash
) {
250 llvm::sys::path::append(Result
, ModuleName
+ ".pcm");
252 // Construct the name <ModuleName>-<hash of ModuleMapPath>.pcm which should
253 // ideally be globally unique to this particular module. Name collisions
254 // in the hash are safe (because any translation unit can only import one
255 // module with each name), but result in a loss of caching.
257 // To avoid false-negatives, we form as canonical a path as we can, and map
258 // to lower-case in case we're on a case-insensitive file system.
259 SmallString
<128> CanonicalPath(ModuleMapPath
);
260 if (getModuleMap().canonicalizeModuleMapPath(CanonicalPath
))
263 llvm::hash_code Hash
= llvm::hash_combine(CanonicalPath
.str().lower());
265 SmallString
<128> HashStr
;
266 llvm::APInt(64, size_t(Hash
)).toStringUnsigned(HashStr
, /*Radix*/36);
267 llvm::sys::path::append(Result
, ModuleName
+ "-" + HashStr
+ ".pcm");
269 return Result
.str().str();
272 Module
*HeaderSearch::lookupModule(StringRef ModuleName
,
273 SourceLocation ImportLoc
, bool AllowSearch
,
274 bool AllowExtraModuleMapSearch
) {
275 // Look in the module map to determine if there is a module by this name.
276 Module
*Module
= ModMap
.findModule(ModuleName
);
277 if (Module
|| !AllowSearch
|| !HSOpts
->ImplicitModuleMaps
)
280 StringRef SearchName
= ModuleName
;
281 Module
= lookupModule(ModuleName
, SearchName
, ImportLoc
,
282 AllowExtraModuleMapSearch
);
284 // The facility for "private modules" -- adjacent, optional module maps named
285 // module.private.modulemap that are supposed to define private submodules --
286 // may have different flavors of names: FooPrivate, Foo_Private and Foo.Private.
288 // Foo.Private is now deprecated in favor of Foo_Private. Users of FooPrivate
289 // should also rename to Foo_Private. Representing private as submodules
290 // could force building unwanted dependencies into the parent module and cause
291 // dependency cycles.
292 if (!Module
&& SearchName
.consume_back("_Private"))
293 Module
= lookupModule(ModuleName
, SearchName
, ImportLoc
,
294 AllowExtraModuleMapSearch
);
295 if (!Module
&& SearchName
.consume_back("Private"))
296 Module
= lookupModule(ModuleName
, SearchName
, ImportLoc
,
297 AllowExtraModuleMapSearch
);
301 Module
*HeaderSearch::lookupModule(StringRef ModuleName
, StringRef SearchName
,
302 SourceLocation ImportLoc
,
303 bool AllowExtraModuleMapSearch
) {
304 Module
*Module
= nullptr;
306 // Look through the various header search paths to load any available module
307 // maps, searching for a module map that describes this module.
308 for (DirectoryLookup
&Dir
: search_dir_range()) {
309 if (Dir
.isFramework()) {
310 // Search for or infer a module map for a framework. Here we use
311 // SearchName rather than ModuleName, to permit finding private modules
312 // named FooPrivate in buggy frameworks named Foo.
313 SmallString
<128> FrameworkDirName
;
314 FrameworkDirName
+= Dir
.getFrameworkDirRef()->getName();
315 llvm::sys::path::append(FrameworkDirName
, SearchName
+ ".framework");
316 if (auto FrameworkDir
=
317 FileMgr
.getOptionalDirectoryRef(FrameworkDirName
)) {
318 bool IsSystem
= Dir
.getDirCharacteristic() != SrcMgr::C_User
;
319 Module
= loadFrameworkModule(ModuleName
, *FrameworkDir
, IsSystem
);
325 // FIXME: Figure out how header maps and module maps will work together.
327 // Only deal with normal search directories.
328 if (!Dir
.isNormalDir())
331 bool IsSystem
= Dir
.isSystemHeaderDirectory();
332 // Only returns std::nullopt if not a normal directory, which we just
334 DirectoryEntryRef NormalDir
= *Dir
.getDirRef();
335 // Search for a module map file in this directory.
336 if (loadModuleMapFile(NormalDir
, IsSystem
,
337 /*IsFramework*/false) == LMM_NewlyLoaded
) {
338 // We just loaded a module map file; check whether the module is
340 Module
= ModMap
.findModule(ModuleName
);
345 // Search for a module map in a subdirectory with the same name as the
347 SmallString
<128> NestedModuleMapDirName
;
348 NestedModuleMapDirName
= Dir
.getDirRef()->getName();
349 llvm::sys::path::append(NestedModuleMapDirName
, ModuleName
);
350 if (loadModuleMapFile(NestedModuleMapDirName
, IsSystem
,
351 /*IsFramework*/false) == LMM_NewlyLoaded
){
352 // If we just loaded a module map file, look for the module again.
353 Module
= ModMap
.findModule(ModuleName
);
358 // If we've already performed the exhaustive search for module maps in this
359 // search directory, don't do it again.
360 if (Dir
.haveSearchedAllModuleMaps())
363 // Load all module maps in the immediate subdirectories of this search
364 // directory if ModuleName was from @import.
365 if (AllowExtraModuleMapSearch
)
366 loadSubdirectoryModuleMaps(Dir
);
368 // Look again for the module.
369 Module
= ModMap
.findModule(ModuleName
);
377 void HeaderSearch::indexInitialHeaderMaps() {
378 llvm::StringMap
<unsigned, llvm::BumpPtrAllocator
> Index(SearchDirs
.size());
380 // Iterate over all filename keys and associate them with the index i.
381 for (unsigned i
= 0; i
!= SearchDirs
.size(); ++i
) {
382 auto &Dir
= SearchDirs
[i
];
384 // We're concerned with only the initial contiguous run of header
385 // maps within SearchDirs, which can be 99% of SearchDirs when
386 // SearchDirs.size() is ~10000.
387 if (!Dir
.isHeaderMap()) {
388 SearchDirHeaderMapIndex
= std::move(Index
);
389 FirstNonHeaderMapSearchDirIdx
= i
;
393 // Give earlier keys precedence over identical later keys.
394 auto Callback
= [&](StringRef Filename
) {
395 Index
.try_emplace(Filename
.lower(), i
);
397 Dir
.getHeaderMap()->forEachKey(Callback
);
401 //===----------------------------------------------------------------------===//
402 // File lookup within a DirectoryLookup scope
403 //===----------------------------------------------------------------------===//
405 /// getName - Return the directory or filename corresponding to this lookup
407 StringRef
DirectoryLookup::getName() const {
409 return getDirRef()->getName();
411 return getFrameworkDirRef()->getName();
412 assert(isHeaderMap() && "Unknown DirectoryLookup");
413 return getHeaderMap()->getFileName();
416 OptionalFileEntryRef
HeaderSearch::getFileAndSuggestModule(
417 StringRef FileName
, SourceLocation IncludeLoc
, const DirectoryEntry
*Dir
,
418 bool IsSystemHeaderDir
, Module
*RequestingModule
,
419 ModuleMap::KnownHeader
*SuggestedModule
, bool OpenFile
/*=true*/,
420 bool CacheFailures
/*=true*/) {
421 // If we have a module map that might map this header, load it and
422 // check whether we'll have a suggestion for a module.
423 auto File
= getFileMgr().getFileRef(FileName
, OpenFile
, CacheFailures
);
425 // For rare, surprising errors (e.g. "out of file handles"), diag the EC
427 std::error_code EC
= llvm::errorToErrorCode(File
.takeError());
428 if (EC
!= llvm::errc::no_such_file_or_directory
&&
429 EC
!= llvm::errc::invalid_argument
&&
430 EC
!= llvm::errc::is_a_directory
&& EC
!= llvm::errc::not_a_directory
) {
431 Diags
.Report(IncludeLoc
, diag::err_cannot_open_file
)
432 << FileName
<< EC
.message();
437 // If there is a module that corresponds to this header, suggest it.
438 if (!findUsableModuleForHeader(
439 *File
, Dir
? Dir
: File
->getFileEntry().getDir(), RequestingModule
,
440 SuggestedModule
, IsSystemHeaderDir
))
446 /// LookupFile - Lookup the specified file in this search path, returning it
447 /// if it exists or returning null if not.
448 OptionalFileEntryRef
DirectoryLookup::LookupFile(
449 StringRef
&Filename
, HeaderSearch
&HS
, SourceLocation IncludeLoc
,
450 SmallVectorImpl
<char> *SearchPath
, SmallVectorImpl
<char> *RelativePath
,
451 Module
*RequestingModule
, ModuleMap::KnownHeader
*SuggestedModule
,
452 bool &InUserSpecifiedSystemFramework
, bool &IsFrameworkFound
,
453 bool &IsInHeaderMap
, SmallVectorImpl
<char> &MappedName
,
454 bool OpenFile
) const {
455 InUserSpecifiedSystemFramework
= false;
456 IsInHeaderMap
= false;
459 SmallString
<1024> TmpDir
;
461 // Concatenate the requested file onto the directory.
462 TmpDir
= getDirRef()->getName();
463 llvm::sys::path::append(TmpDir
, Filename
);
465 StringRef
SearchPathRef(getDirRef()->getName());
467 SearchPath
->append(SearchPathRef
.begin(), SearchPathRef
.end());
470 RelativePath
->clear();
471 RelativePath
->append(Filename
.begin(), Filename
.end());
474 return HS
.getFileAndSuggestModule(
475 TmpDir
, IncludeLoc
, getDir(), isSystemHeaderDirectory(),
476 RequestingModule
, SuggestedModule
, OpenFile
);
480 return DoFrameworkLookup(Filename
, HS
, SearchPath
, RelativePath
,
481 RequestingModule
, SuggestedModule
,
482 InUserSpecifiedSystemFramework
, IsFrameworkFound
);
484 assert(isHeaderMap() && "Unknown directory lookup");
485 const HeaderMap
*HM
= getHeaderMap();
486 SmallString
<1024> Path
;
487 StringRef Dest
= HM
->lookupFilename(Filename
, Path
);
491 IsInHeaderMap
= true;
493 auto FixupSearchPathAndFindUsableModule
=
494 [&](FileEntryRef File
) -> OptionalFileEntryRef
{
496 StringRef
SearchPathRef(getName());
498 SearchPath
->append(SearchPathRef
.begin(), SearchPathRef
.end());
501 RelativePath
->clear();
502 RelativePath
->append(Filename
.begin(), Filename
.end());
504 if (!HS
.findUsableModuleForHeader(File
, File
.getFileEntry().getDir(),
505 RequestingModule
, SuggestedModule
,
506 isSystemHeaderDirectory())) {
512 // Check if the headermap maps the filename to a framework include
513 // ("Foo.h" -> "Foo/Foo.h"), in which case continue header lookup using the
514 // framework include.
515 if (llvm::sys::path::is_relative(Dest
)) {
516 MappedName
.append(Dest
.begin(), Dest
.end());
517 Filename
= StringRef(MappedName
.begin(), MappedName
.size());
518 Dest
= HM
->lookupFilename(Filename
, Path
);
521 if (auto Res
= HS
.getFileMgr().getOptionalFileRef(Dest
, OpenFile
)) {
522 return FixupSearchPathAndFindUsableModule(*Res
);
525 // Header maps need to be marked as used whenever the filename matches.
526 // The case where the target file **exists** is handled by callee of this
527 // function as part of the regular logic that applies to include search paths.
528 // The case where the target file **does not exist** is handled here:
529 HS
.noteLookupUsage(HS
.searchDirIdx(*this), IncludeLoc
);
533 /// Given a framework directory, find the top-most framework directory.
535 /// \param FileMgr The file manager to use for directory lookups.
536 /// \param DirName The name of the framework directory.
537 /// \param SubmodulePath Will be populated with the submodule path from the
538 /// returned top-level module to the originally named framework.
539 static OptionalDirectoryEntryRef
540 getTopFrameworkDir(FileManager
&FileMgr
, StringRef DirName
,
541 SmallVectorImpl
<std::string
> &SubmodulePath
) {
542 assert(llvm::sys::path::extension(DirName
) == ".framework" &&
543 "Not a framework directory");
545 // Note: as an egregious but useful hack we use the real path here, because
546 // frameworks moving between top-level frameworks to embedded frameworks tend
547 // to be symlinked, and we base the logical structure of modules on the
548 // physical layout. In particular, we need to deal with crazy includes like
550 // #include <Foo/Frameworks/Bar.framework/Headers/Wibble.h>
552 // where 'Bar' used to be embedded in 'Foo', is now a top-level framework
553 // which one should access with, e.g.,
555 // #include <Bar/Wibble.h>
557 // Similar issues occur when a top-level framework has moved into an
558 // embedded framework.
559 auto TopFrameworkDir
= FileMgr
.getOptionalDirectoryRef(DirName
);
562 DirName
= FileMgr
.getCanonicalName(*TopFrameworkDir
);
564 // Get the parent directory name.
565 DirName
= llvm::sys::path::parent_path(DirName
);
569 // Determine whether this directory exists.
570 auto Dir
= FileMgr
.getOptionalDirectoryRef(DirName
);
574 // If this is a framework directory, then we're a subframework of this
576 if (llvm::sys::path::extension(DirName
) == ".framework") {
577 SubmodulePath
.push_back(std::string(llvm::sys::path::stem(DirName
)));
578 TopFrameworkDir
= *Dir
;
582 return TopFrameworkDir
;
585 static bool needModuleLookup(Module
*RequestingModule
,
586 bool HasSuggestedModule
) {
587 return HasSuggestedModule
||
588 (RequestingModule
&& RequestingModule
->NoUndeclaredIncludes
);
591 /// DoFrameworkLookup - Do a lookup of the specified file in the current
592 /// DirectoryLookup, which is a framework directory.
593 OptionalFileEntryRef
DirectoryLookup::DoFrameworkLookup(
594 StringRef Filename
, HeaderSearch
&HS
, SmallVectorImpl
<char> *SearchPath
,
595 SmallVectorImpl
<char> *RelativePath
, Module
*RequestingModule
,
596 ModuleMap::KnownHeader
*SuggestedModule
,
597 bool &InUserSpecifiedSystemFramework
, bool &IsFrameworkFound
) const {
598 FileManager
&FileMgr
= HS
.getFileMgr();
600 // Framework names must have a '/' in the filename.
601 size_t SlashPos
= Filename
.find('/');
602 if (SlashPos
== StringRef::npos
)
605 // Find out if this is the home for the specified framework, by checking
606 // HeaderSearch. Possible answers are yes/no and unknown.
607 FrameworkCacheEntry
&CacheEntry
=
608 HS
.LookupFrameworkCache(Filename
.substr(0, SlashPos
));
610 // If it is known and in some other directory, fail.
611 if (CacheEntry
.Directory
&& CacheEntry
.Directory
!= getFrameworkDirRef())
614 // Otherwise, construct the path to this framework dir.
616 // FrameworkName = "/System/Library/Frameworks/"
617 SmallString
<1024> FrameworkName
;
618 FrameworkName
+= getFrameworkDirRef()->getName();
619 if (FrameworkName
.empty() || FrameworkName
.back() != '/')
620 FrameworkName
.push_back('/');
622 // FrameworkName = "/System/Library/Frameworks/Cocoa"
623 StringRef
ModuleName(Filename
.begin(), SlashPos
);
624 FrameworkName
+= ModuleName
;
626 // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/"
627 FrameworkName
+= ".framework/";
629 // If the cache entry was unresolved, populate it now.
630 if (!CacheEntry
.Directory
) {
631 ++NumFrameworkLookups
;
633 // If the framework dir doesn't exist, we fail.
634 auto Dir
= FileMgr
.getDirectory(FrameworkName
);
638 // Otherwise, if it does, remember that this is the right direntry for this
640 CacheEntry
.Directory
= getFrameworkDirRef();
642 // If this is a user search directory, check if the framework has been
643 // user-specified as a system framework.
644 if (getDirCharacteristic() == SrcMgr::C_User
) {
645 SmallString
<1024> SystemFrameworkMarker(FrameworkName
);
646 SystemFrameworkMarker
+= ".system_framework";
647 if (llvm::sys::fs::exists(SystemFrameworkMarker
)) {
648 CacheEntry
.IsUserSpecifiedSystemFramework
= true;
654 InUserSpecifiedSystemFramework
= CacheEntry
.IsUserSpecifiedSystemFramework
;
655 IsFrameworkFound
= CacheEntry
.Directory
.has_value();
658 RelativePath
->clear();
659 RelativePath
->append(Filename
.begin()+SlashPos
+1, Filename
.end());
662 // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"
663 unsigned OrigSize
= FrameworkName
.size();
665 FrameworkName
+= "Headers/";
669 // Without trailing '/'.
670 SearchPath
->append(FrameworkName
.begin(), FrameworkName
.end()-1);
673 FrameworkName
.append(Filename
.begin()+SlashPos
+1, Filename
.end());
676 FileMgr
.getOptionalFileRef(FrameworkName
, /*OpenFile=*/!SuggestedModule
);
678 // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"
679 const char *Private
= "Private";
680 FrameworkName
.insert(FrameworkName
.begin()+OrigSize
, Private
,
681 Private
+strlen(Private
));
683 SearchPath
->insert(SearchPath
->begin()+OrigSize
, Private
,
684 Private
+strlen(Private
));
686 File
= FileMgr
.getOptionalFileRef(FrameworkName
,
687 /*OpenFile=*/!SuggestedModule
);
690 // If we found the header and are allowed to suggest a module, do so now.
691 if (File
&& needModuleLookup(RequestingModule
, SuggestedModule
)) {
692 // Find the framework in which this header occurs.
693 StringRef FrameworkPath
= File
->getDir().getName();
694 bool FoundFramework
= false;
696 // Determine whether this directory exists.
697 auto Dir
= FileMgr
.getDirectory(FrameworkPath
);
701 // If this is a framework directory, then we're a subframework of this
703 if (llvm::sys::path::extension(FrameworkPath
) == ".framework") {
704 FoundFramework
= true;
708 // Get the parent directory name.
709 FrameworkPath
= llvm::sys::path::parent_path(FrameworkPath
);
710 if (FrameworkPath
.empty())
714 bool IsSystem
= getDirCharacteristic() != SrcMgr::C_User
;
715 if (FoundFramework
) {
716 if (!HS
.findUsableModuleForFrameworkHeader(*File
, FrameworkPath
,
718 SuggestedModule
, IsSystem
))
721 if (!HS
.findUsableModuleForHeader(*File
, getDir(), RequestingModule
,
722 SuggestedModule
, IsSystem
))
731 void HeaderSearch::cacheLookupSuccess(LookupFileCacheInfo
&CacheLookup
,
732 ConstSearchDirIterator HitIt
,
733 SourceLocation Loc
) {
734 CacheLookup
.HitIt
= HitIt
;
735 noteLookupUsage(HitIt
.Idx
, Loc
);
738 void HeaderSearch::noteLookupUsage(unsigned HitIdx
, SourceLocation Loc
) {
739 SearchDirsUsage
[HitIdx
] = true;
741 auto UserEntryIdxIt
= SearchDirToHSEntry
.find(HitIdx
);
742 if (UserEntryIdxIt
!= SearchDirToHSEntry
.end())
743 Diags
.Report(Loc
, diag::remark_pp_search_path_usage
)
744 << HSOpts
->UserEntries
[UserEntryIdxIt
->second
].Path
;
747 void HeaderSearch::setTarget(const TargetInfo
&Target
) {
748 ModMap
.setTarget(Target
);
751 //===----------------------------------------------------------------------===//
752 // Header File Location.
753 //===----------------------------------------------------------------------===//
755 /// Return true with a diagnostic if the file that MSVC would have found
756 /// fails to match the one that Clang would have found with MSVC header search
758 static bool checkMSVCHeaderSearch(DiagnosticsEngine
&Diags
,
759 OptionalFileEntryRef MSFE
,
761 SourceLocation IncludeLoc
) {
762 if (MSFE
&& FE
!= *MSFE
) {
763 Diags
.Report(IncludeLoc
, diag::ext_pp_include_search_ms
) << MSFE
->getName();
769 static const char *copyString(StringRef Str
, llvm::BumpPtrAllocator
&Alloc
) {
770 assert(!Str
.empty());
771 char *CopyStr
= Alloc
.Allocate
<char>(Str
.size()+1);
772 std::copy(Str
.begin(), Str
.end(), CopyStr
);
773 CopyStr
[Str
.size()] = '\0';
777 static bool isFrameworkStylePath(StringRef Path
, bool &IsPrivateHeader
,
778 SmallVectorImpl
<char> &FrameworkName
,
779 SmallVectorImpl
<char> &IncludeSpelling
) {
780 using namespace llvm::sys
;
781 path::const_iterator I
= path::begin(Path
);
782 path::const_iterator E
= path::end(Path
);
783 IsPrivateHeader
= false;
785 // Detect different types of framework style paths:
787 // ...Foo.framework/{Headers,PrivateHeaders}
788 // ...Foo.framework/Versions/{A,Current}/{Headers,PrivateHeaders}
789 // ...Foo.framework/Frameworks/Nested.framework/{Headers,PrivateHeaders}
790 // ...<other variations with 'Versions' like in the above path>
792 // and some other variations among these lines.
795 if (*I
== "Headers") {
797 } else if (*I
== "PrivateHeaders") {
799 IsPrivateHeader
= true;
800 } else if (I
->endswith(".framework")) {
801 StringRef Name
= I
->drop_back(10); // Drop .framework
802 // Need to reset the strings and counter to support nested frameworks.
803 FrameworkName
.clear();
804 FrameworkName
.append(Name
.begin(), Name
.end());
805 IncludeSpelling
.clear();
806 IncludeSpelling
.append(Name
.begin(), Name
.end());
808 } else if (FoundComp
>= 2) {
809 IncludeSpelling
.push_back('/');
810 IncludeSpelling
.append(I
->begin(), I
->end());
815 return !FrameworkName
.empty() && FoundComp
>= 2;
819 diagnoseFrameworkInclude(DiagnosticsEngine
&Diags
, SourceLocation IncludeLoc
,
820 StringRef Includer
, StringRef IncludeFilename
,
821 FileEntryRef IncludeFE
, bool isAngled
= false,
822 bool FoundByHeaderMap
= false) {
823 bool IsIncluderPrivateHeader
= false;
824 SmallString
<128> FromFramework
, ToFramework
;
825 SmallString
<128> FromIncludeSpelling
, ToIncludeSpelling
;
826 if (!isFrameworkStylePath(Includer
, IsIncluderPrivateHeader
, FromFramework
,
827 FromIncludeSpelling
))
829 bool IsIncludeePrivateHeader
= false;
830 bool IsIncludeeInFramework
=
831 isFrameworkStylePath(IncludeFE
.getName(), IsIncludeePrivateHeader
,
832 ToFramework
, ToIncludeSpelling
);
834 if (!isAngled
&& !FoundByHeaderMap
) {
835 SmallString
<128> NewInclude("<");
836 if (IsIncludeeInFramework
) {
837 NewInclude
+= ToIncludeSpelling
;
840 NewInclude
+= IncludeFilename
;
843 Diags
.Report(IncludeLoc
, diag::warn_quoted_include_in_framework_header
)
845 << FixItHint::CreateReplacement(IncludeLoc
, NewInclude
);
848 // Headers in Foo.framework/Headers should not include headers
849 // from Foo.framework/PrivateHeaders, since this violates public/private
850 // API boundaries and can cause modular dependency cycles.
851 if (!IsIncluderPrivateHeader
&& IsIncludeeInFramework
&&
852 IsIncludeePrivateHeader
&& FromFramework
== ToFramework
)
853 Diags
.Report(IncludeLoc
, diag::warn_framework_include_private_from_public
)
857 /// LookupFile - Given a "foo" or \<foo> reference, look up the indicated file,
858 /// return null on failure. isAngled indicates whether the file reference is
859 /// for system \#include's or not (i.e. using <> instead of ""). Includers, if
860 /// non-empty, indicates where the \#including file(s) are, in case a relative
861 /// search is needed. Microsoft mode will pass all \#including files.
862 OptionalFileEntryRef
HeaderSearch::LookupFile(
863 StringRef Filename
, SourceLocation IncludeLoc
, bool isAngled
,
864 ConstSearchDirIterator FromDir
, ConstSearchDirIterator
*CurDirArg
,
865 ArrayRef
<std::pair
<OptionalFileEntryRef
, DirectoryEntryRef
>> Includers
,
866 SmallVectorImpl
<char> *SearchPath
, SmallVectorImpl
<char> *RelativePath
,
867 Module
*RequestingModule
, ModuleMap::KnownHeader
*SuggestedModule
,
868 bool *IsMapped
, bool *IsFrameworkFound
, bool SkipCache
,
869 bool BuildSystemModule
, bool OpenFile
, bool CacheFailures
) {
870 ConstSearchDirIterator CurDirLocal
= nullptr;
871 ConstSearchDirIterator
&CurDir
= CurDirArg
? *CurDirArg
: CurDirLocal
;
876 if (IsFrameworkFound
)
877 *IsFrameworkFound
= false;
880 *SuggestedModule
= ModuleMap::KnownHeader();
882 // If 'Filename' is absolute, check to see if it exists and no searching.
883 if (llvm::sys::path::is_absolute(Filename
)) {
886 // If this was an #include_next "/absolute/file", fail.
893 RelativePath
->clear();
894 RelativePath
->append(Filename
.begin(), Filename
.end());
896 // Otherwise, just return the file.
897 return getFileAndSuggestModule(Filename
, IncludeLoc
, nullptr,
898 /*IsSystemHeaderDir*/ false,
899 RequestingModule
, SuggestedModule
, OpenFile
,
903 // This is the header that MSVC's header search would have found.
904 ModuleMap::KnownHeader MSSuggestedModule
;
905 OptionalFileEntryRef MSFE
;
907 // Unless disabled, check to see if the file is in the #includer's
908 // directory. This cannot be based on CurDir, because each includer could be
909 // a #include of a subdirectory (#include "foo/bar.h") and a subsequent
910 // include of "baz.h" should resolve to "whatever/foo/baz.h".
911 // This search is not done for <> headers.
912 if (!Includers
.empty() && !isAngled
&& !NoCurDirSearch
) {
913 SmallString
<1024> TmpDir
;
915 for (const auto &IncluderAndDir
: Includers
) {
916 OptionalFileEntryRef Includer
= IncluderAndDir
.first
;
918 // Concatenate the requested file onto the directory.
919 TmpDir
= IncluderAndDir
.second
.getName();
920 llvm::sys::path::append(TmpDir
, Filename
);
922 // FIXME: We don't cache the result of getFileInfo across the call to
923 // getFileAndSuggestModule, because it's a reference to an element of
924 // a container that could be reallocated across this call.
926 // If we have no includer, that means we're processing a #include
927 // from a module build. We should treat this as a system header if we're
928 // building a [system] module.
929 bool IncluderIsSystemHeader
=
930 Includer
? getFileInfo(*Includer
).DirInfo
!= SrcMgr::C_User
:
932 if (OptionalFileEntryRef FE
= getFileAndSuggestModule(
933 TmpDir
, IncludeLoc
, IncluderAndDir
.second
, IncluderIsSystemHeader
,
934 RequestingModule
, SuggestedModule
)) {
936 assert(First
&& "only first includer can have no file");
940 // Leave CurDir unset.
941 // This file is a system header or C++ unfriendly if the old file is.
943 // Note that we only use one of FromHFI/ToHFI at once, due to potential
944 // reallocation of the underlying vector potentially making the first
945 // reference binding dangling.
946 HeaderFileInfo
&FromHFI
= getFileInfo(*Includer
);
947 unsigned DirInfo
= FromHFI
.DirInfo
;
948 bool IndexHeaderMapHeader
= FromHFI
.IndexHeaderMapHeader
;
949 StringRef Framework
= FromHFI
.Framework
;
951 HeaderFileInfo
&ToHFI
= getFileInfo(*FE
);
952 ToHFI
.DirInfo
= DirInfo
;
953 ToHFI
.IndexHeaderMapHeader
= IndexHeaderMapHeader
;
954 ToHFI
.Framework
= Framework
;
957 StringRef
SearchPathRef(IncluderAndDir
.second
.getName());
959 SearchPath
->append(SearchPathRef
.begin(), SearchPathRef
.end());
962 RelativePath
->clear();
963 RelativePath
->append(Filename
.begin(), Filename
.end());
966 diagnoseFrameworkInclude(Diags
, IncludeLoc
,
967 IncluderAndDir
.second
.getName(), Filename
,
972 // Otherwise, we found the path via MSVC header search rules. If
973 // -Wmsvc-include is enabled, we have to keep searching to see if we
974 // would've found this header in -I or -isystem directories.
975 if (Diags
.isIgnored(diag::ext_pp_include_search_ms
, IncludeLoc
)) {
979 if (SuggestedModule
) {
980 MSSuggestedModule
= *SuggestedModule
;
981 *SuggestedModule
= ModuleMap::KnownHeader();
992 // If this is a system #include, ignore the user #include locs.
993 ConstSearchDirIterator It
=
994 isAngled
? angled_dir_begin() : search_dir_begin();
996 // If this is a #include_next request, start searching after the directory the
997 // file was found in.
1001 // Cache all of the lookups performed by this method. Many headers are
1002 // multiply included, and the "pragma once" optimization prevents them from
1003 // being relex/pp'd, but they would still have to search through a
1004 // (potentially huge) series of SearchDirs to find it.
1005 LookupFileCacheInfo
&CacheLookup
= LookupFileCache
[Filename
];
1007 ConstSearchDirIterator NextIt
= std::next(It
);
1010 if (CacheLookup
.StartIt
== NextIt
&&
1011 CacheLookup
.RequestingModule
== RequestingModule
) {
1012 // HIT: Skip querying potentially lots of directories for this lookup.
1013 if (CacheLookup
.HitIt
)
1014 It
= CacheLookup
.HitIt
;
1015 if (CacheLookup
.MappedName
) {
1016 Filename
= CacheLookup
.MappedName
;
1021 // MISS: This is the first query, or the previous query didn't match
1022 // our search start. We will fill in our found location below, so prime
1023 // the start point value.
1024 CacheLookup
.reset(RequestingModule
, /*NewStartIt=*/NextIt
);
1026 if (It
== search_dir_begin() && FirstNonHeaderMapSearchDirIdx
> 0) {
1027 // Handle cold misses of user includes in the presence of many header
1028 // maps. We avoid searching perhaps thousands of header maps by
1029 // jumping directly to the correct one or jumping beyond all of them.
1030 auto Iter
= SearchDirHeaderMapIndex
.find(Filename
.lower());
1031 if (Iter
== SearchDirHeaderMapIndex
.end())
1032 // Not in index => Skip to first SearchDir after initial header maps
1033 It
= search_dir_nth(FirstNonHeaderMapSearchDirIdx
);
1035 // In index => Start with a specific header map
1036 It
= search_dir_nth(Iter
->second
);
1040 CacheLookup
.reset(RequestingModule
, /*NewStartIt=*/NextIt
);
1043 SmallString
<64> MappedName
;
1045 // Check each directory in sequence to see if it contains this file.
1046 for (; It
!= search_dir_end(); ++It
) {
1047 bool InUserSpecifiedSystemFramework
= false;
1048 bool IsInHeaderMap
= false;
1049 bool IsFrameworkFoundInDir
= false;
1050 OptionalFileEntryRef File
= It
->LookupFile(
1051 Filename
, *this, IncludeLoc
, SearchPath
, RelativePath
, RequestingModule
,
1052 SuggestedModule
, InUserSpecifiedSystemFramework
, IsFrameworkFoundInDir
,
1053 IsInHeaderMap
, MappedName
, OpenFile
);
1054 if (!MappedName
.empty()) {
1055 assert(IsInHeaderMap
&& "MappedName should come from a header map");
1056 CacheLookup
.MappedName
=
1057 copyString(MappedName
, LookupFileCache
.getAllocator());
1060 // A filename is mapped when a header map remapped it to a relative path
1061 // used in subsequent header search or to an absolute path pointing to an
1063 *IsMapped
|= (!MappedName
.empty() || (IsInHeaderMap
&& File
));
1064 if (IsFrameworkFound
)
1065 // Because we keep a filename remapped for subsequent search directory
1066 // lookups, ignore IsFrameworkFoundInDir after the first remapping and not
1067 // just for remapping in a current search directory.
1068 *IsFrameworkFound
|= (IsFrameworkFoundInDir
&& !CacheLookup
.MappedName
);
1074 IncludeNames
[*File
] = Filename
;
1076 // This file is a system header or C++ unfriendly if the dir is.
1077 HeaderFileInfo
&HFI
= getFileInfo(*File
);
1078 HFI
.DirInfo
= CurDir
->getDirCharacteristic();
1080 // If the directory characteristic is User but this framework was
1081 // user-specified to be treated as a system framework, promote the
1083 if (HFI
.DirInfo
== SrcMgr::C_User
&& InUserSpecifiedSystemFramework
)
1084 HFI
.DirInfo
= SrcMgr::C_System
;
1086 // If the filename matches a known system header prefix, override
1087 // whether the file is a system header.
1088 for (unsigned j
= SystemHeaderPrefixes
.size(); j
; --j
) {
1089 if (Filename
.startswith(SystemHeaderPrefixes
[j
-1].first
)) {
1090 HFI
.DirInfo
= SystemHeaderPrefixes
[j
-1].second
? SrcMgr::C_System
1096 // Set the `Framework` info if this file is in a header map with framework
1097 // style include spelling or found in a framework dir. The header map case
1098 // is possible when building frameworks which use header maps.
1099 if (CurDir
->isHeaderMap() && isAngled
) {
1100 size_t SlashPos
= Filename
.find('/');
1101 if (SlashPos
!= StringRef::npos
)
1103 getUniqueFrameworkName(StringRef(Filename
.begin(), SlashPos
));
1104 if (CurDir
->isIndexHeaderMap())
1105 HFI
.IndexHeaderMapHeader
= 1;
1106 } else if (CurDir
->isFramework()) {
1107 size_t SlashPos
= Filename
.find('/');
1108 if (SlashPos
!= StringRef::npos
)
1110 getUniqueFrameworkName(StringRef(Filename
.begin(), SlashPos
));
1113 if (checkMSVCHeaderSearch(Diags
, MSFE
, &File
->getFileEntry(), IncludeLoc
)) {
1114 if (SuggestedModule
)
1115 *SuggestedModule
= MSSuggestedModule
;
1119 bool FoundByHeaderMap
= !IsMapped
? false : *IsMapped
;
1120 if (!Includers
.empty())
1121 diagnoseFrameworkInclude(Diags
, IncludeLoc
,
1122 Includers
.front().second
.getName(), Filename
,
1123 *File
, isAngled
, FoundByHeaderMap
);
1125 // Remember this location for the next lookup we do.
1126 cacheLookupSuccess(CacheLookup
, It
, IncludeLoc
);
1130 // If we are including a file with a quoted include "foo.h" from inside
1131 // a header in a framework that is currently being built, and we couldn't
1132 // resolve "foo.h" any other way, change the include to <Foo/foo.h>, where
1133 // "Foo" is the name of the framework in which the including header was found.
1134 if (!Includers
.empty() && Includers
.front().first
&& !isAngled
&&
1135 !Filename
.contains('/')) {
1136 HeaderFileInfo
&IncludingHFI
= getFileInfo(*Includers
.front().first
);
1137 if (IncludingHFI
.IndexHeaderMapHeader
) {
1138 SmallString
<128> ScratchFilename
;
1139 ScratchFilename
+= IncludingHFI
.Framework
;
1140 ScratchFilename
+= '/';
1141 ScratchFilename
+= Filename
;
1143 OptionalFileEntryRef File
= LookupFile(
1144 ScratchFilename
, IncludeLoc
, /*isAngled=*/true, FromDir
, &CurDir
,
1145 Includers
.front(), SearchPath
, RelativePath
, RequestingModule
,
1146 SuggestedModule
, IsMapped
, /*IsFrameworkFound=*/nullptr);
1148 if (checkMSVCHeaderSearch(Diags
, MSFE
,
1149 File
? &File
->getFileEntry() : nullptr,
1151 if (SuggestedModule
)
1152 *SuggestedModule
= MSSuggestedModule
;
1156 cacheLookupSuccess(LookupFileCache
[Filename
],
1157 LookupFileCache
[ScratchFilename
].HitIt
, IncludeLoc
);
1158 // FIXME: SuggestedModule.
1163 if (checkMSVCHeaderSearch(Diags
, MSFE
, nullptr, IncludeLoc
)) {
1164 if (SuggestedModule
)
1165 *SuggestedModule
= MSSuggestedModule
;
1169 // Otherwise, didn't find it. Remember we didn't find this.
1170 CacheLookup
.HitIt
= search_dir_end();
1171 return std::nullopt
;
1174 /// LookupSubframeworkHeader - Look up a subframework for the specified
1175 /// \#include file. For example, if \#include'ing <HIToolbox/HIToolbox.h> from
1176 /// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
1177 /// is a subframework within Carbon.framework. If so, return the FileEntry
1178 /// for the designated file, otherwise return null.
1179 OptionalFileEntryRef
HeaderSearch::LookupSubframeworkHeader(
1180 StringRef Filename
, FileEntryRef ContextFileEnt
,
1181 SmallVectorImpl
<char> *SearchPath
, SmallVectorImpl
<char> *RelativePath
,
1182 Module
*RequestingModule
, ModuleMap::KnownHeader
*SuggestedModule
) {
1183 // Framework names must have a '/' in the filename. Find it.
1184 // FIXME: Should we permit '\' on Windows?
1185 size_t SlashPos
= Filename
.find('/');
1186 if (SlashPos
== StringRef::npos
)
1187 return std::nullopt
;
1189 // Look up the base framework name of the ContextFileEnt.
1190 StringRef ContextName
= ContextFileEnt
.getName();
1192 // If the context info wasn't a framework, couldn't be a subframework.
1193 const unsigned DotFrameworkLen
= 10;
1194 auto FrameworkPos
= ContextName
.find(".framework");
1195 if (FrameworkPos
== StringRef::npos
||
1196 (ContextName
[FrameworkPos
+ DotFrameworkLen
] != '/' &&
1197 ContextName
[FrameworkPos
+ DotFrameworkLen
] != '\\'))
1198 return std::nullopt
;
1200 SmallString
<1024> FrameworkName(ContextName
.data(), ContextName
.data() +
1202 DotFrameworkLen
+ 1);
1204 // Append Frameworks/HIToolbox.framework/
1205 FrameworkName
+= "Frameworks/";
1206 FrameworkName
.append(Filename
.begin(), Filename
.begin()+SlashPos
);
1207 FrameworkName
+= ".framework/";
1210 *FrameworkMap
.insert(std::make_pair(Filename
.substr(0, SlashPos
),
1211 FrameworkCacheEntry())).first
;
1213 // Some other location?
1214 if (CacheLookup
.second
.Directory
&&
1215 CacheLookup
.first().size() == FrameworkName
.size() &&
1216 memcmp(CacheLookup
.first().data(), &FrameworkName
[0],
1217 CacheLookup
.first().size()) != 0)
1218 return std::nullopt
;
1220 // Cache subframework.
1221 if (!CacheLookup
.second
.Directory
) {
1222 ++NumSubFrameworkLookups
;
1224 // If the framework dir doesn't exist, we fail.
1225 auto Dir
= FileMgr
.getOptionalDirectoryRef(FrameworkName
);
1227 return std::nullopt
;
1229 // Otherwise, if it does, remember that this is the right direntry for this
1231 CacheLookup
.second
.Directory
= Dir
;
1236 RelativePath
->clear();
1237 RelativePath
->append(Filename
.begin()+SlashPos
+1, Filename
.end());
1240 // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
1241 SmallString
<1024> HeadersFilename(FrameworkName
);
1242 HeadersFilename
+= "Headers/";
1244 SearchPath
->clear();
1245 // Without trailing '/'.
1246 SearchPath
->append(HeadersFilename
.begin(), HeadersFilename
.end()-1);
1249 HeadersFilename
.append(Filename
.begin()+SlashPos
+1, Filename
.end());
1250 auto File
= FileMgr
.getOptionalFileRef(HeadersFilename
, /*OpenFile=*/true);
1252 // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
1253 HeadersFilename
= FrameworkName
;
1254 HeadersFilename
+= "PrivateHeaders/";
1256 SearchPath
->clear();
1257 // Without trailing '/'.
1258 SearchPath
->append(HeadersFilename
.begin(), HeadersFilename
.end()-1);
1261 HeadersFilename
.append(Filename
.begin()+SlashPos
+1, Filename
.end());
1262 File
= FileMgr
.getOptionalFileRef(HeadersFilename
, /*OpenFile=*/true);
1265 return std::nullopt
;
1268 // This file is a system header or C++ unfriendly if the old file is.
1270 // Note that the temporary 'DirInfo' is required here, as either call to
1271 // getFileInfo could resize the vector and we don't want to rely on order
1273 unsigned DirInfo
= getFileInfo(ContextFileEnt
).DirInfo
;
1274 getFileInfo(*File
).DirInfo
= DirInfo
;
1276 FrameworkName
.pop_back(); // remove the trailing '/'
1277 if (!findUsableModuleForFrameworkHeader(*File
, FrameworkName
,
1278 RequestingModule
, SuggestedModule
,
1279 /*IsSystem*/ false))
1280 return std::nullopt
;
1285 //===----------------------------------------------------------------------===//
1286 // File Info Management.
1287 //===----------------------------------------------------------------------===//
1289 /// Merge the header file info provided by \p OtherHFI into the current
1290 /// header file info (\p HFI)
1291 static void mergeHeaderFileInfo(HeaderFileInfo
&HFI
,
1292 const HeaderFileInfo
&OtherHFI
) {
1293 assert(OtherHFI
.External
&& "expected to merge external HFI");
1295 HFI
.isImport
|= OtherHFI
.isImport
;
1296 HFI
.isPragmaOnce
|= OtherHFI
.isPragmaOnce
;
1297 HFI
.isModuleHeader
|= OtherHFI
.isModuleHeader
;
1299 if (!HFI
.ControllingMacro
&& !HFI
.ControllingMacroID
) {
1300 HFI
.ControllingMacro
= OtherHFI
.ControllingMacro
;
1301 HFI
.ControllingMacroID
= OtherHFI
.ControllingMacroID
;
1304 HFI
.DirInfo
= OtherHFI
.DirInfo
;
1305 HFI
.External
= (!HFI
.IsValid
|| HFI
.External
);
1307 HFI
.IndexHeaderMapHeader
= OtherHFI
.IndexHeaderMapHeader
;
1309 if (HFI
.Framework
.empty())
1310 HFI
.Framework
= OtherHFI
.Framework
;
1313 /// getFileInfo - Return the HeaderFileInfo structure for the specified
1315 HeaderFileInfo
&HeaderSearch::getFileInfo(FileEntryRef FE
) {
1316 if (FE
.getUID() >= FileInfo
.size())
1317 FileInfo
.resize(FE
.getUID() + 1);
1319 HeaderFileInfo
*HFI
= &FileInfo
[FE
.getUID()];
1320 // FIXME: Use a generation count to check whether this is really up to date.
1321 if (ExternalSource
&& !HFI
->Resolved
) {
1322 auto ExternalHFI
= ExternalSource
->GetHeaderFileInfo(FE
);
1323 if (ExternalHFI
.IsValid
) {
1324 HFI
->Resolved
= true;
1325 if (ExternalHFI
.External
)
1326 mergeHeaderFileInfo(*HFI
, ExternalHFI
);
1330 HFI
->IsValid
= true;
1331 // We have local information about this header file, so it's no longer
1332 // strictly external.
1333 HFI
->External
= false;
1337 const HeaderFileInfo
*
1338 HeaderSearch::getExistingFileInfo(FileEntryRef FE
, bool WantExternal
) const {
1339 // If we have an external source, ensure we have the latest information.
1340 // FIXME: Use a generation count to check whether this is really up to date.
1341 HeaderFileInfo
*HFI
;
1342 if (ExternalSource
) {
1343 if (FE
.getUID() >= FileInfo
.size()) {
1346 FileInfo
.resize(FE
.getUID() + 1);
1349 HFI
= &FileInfo
[FE
.getUID()];
1350 if (!WantExternal
&& (!HFI
->IsValid
|| HFI
->External
))
1352 if (!HFI
->Resolved
) {
1353 auto ExternalHFI
= ExternalSource
->GetHeaderFileInfo(FE
);
1354 if (ExternalHFI
.IsValid
) {
1355 HFI
->Resolved
= true;
1356 if (ExternalHFI
.External
)
1357 mergeHeaderFileInfo(*HFI
, ExternalHFI
);
1360 } else if (FE
.getUID() >= FileInfo
.size()) {
1363 HFI
= &FileInfo
[FE
.getUID()];
1366 if (!HFI
->IsValid
|| (HFI
->External
&& !WantExternal
))
1372 bool HeaderSearch::isFileMultipleIncludeGuarded(FileEntryRef File
) const {
1373 // Check if we've entered this file and found an include guard or #pragma
1374 // once. Note that we dor't check for #import, because that's not a property
1375 // of the file itself.
1376 if (auto *HFI
= getExistingFileInfo(File
))
1377 return HFI
->isPragmaOnce
|| HFI
->ControllingMacro
||
1378 HFI
->ControllingMacroID
;
1382 void HeaderSearch::MarkFileModuleHeader(FileEntryRef FE
,
1383 ModuleMap::ModuleHeaderRole Role
,
1384 bool isCompilingModuleHeader
) {
1385 bool isModularHeader
= ModuleMap::isModular(Role
);
1387 // Don't mark the file info as non-external if there's nothing to change.
1388 if (!isCompilingModuleHeader
) {
1389 if (!isModularHeader
)
1391 auto *HFI
= getExistingFileInfo(FE
);
1392 if (HFI
&& HFI
->isModuleHeader
)
1396 auto &HFI
= getFileInfo(FE
);
1397 HFI
.isModuleHeader
|= isModularHeader
;
1398 HFI
.isCompilingModuleHeader
|= isCompilingModuleHeader
;
1401 bool HeaderSearch::ShouldEnterIncludeFile(Preprocessor
&PP
,
1402 FileEntryRef File
, bool isImport
,
1403 bool ModulesEnabled
, Module
*M
,
1404 bool &IsFirstIncludeOfFile
) {
1405 ++NumIncluded
; // Count # of attempted #includes.
1407 IsFirstIncludeOfFile
= false;
1409 // Get information about this file.
1410 HeaderFileInfo
&FileInfo
= getFileInfo(File
);
1412 // FIXME: this is a workaround for the lack of proper modules-aware support
1413 // for #import / #pragma once
1414 auto TryEnterImported
= [&]() -> bool {
1415 if (!ModulesEnabled
)
1417 // Ensure FileInfo bits are up to date.
1418 ModMap
.resolveHeaderDirectives(File
);
1419 // Modules with builtins are special; multiple modules use builtins as
1420 // modular headers, example:
1422 // module stddef { header "stddef.h" export * }
1424 // After module map parsing, this expands to:
1427 // header "/path_to_builtin_dirs/stddef.h"
1428 // textual "stddef.h"
1431 // It's common that libc++ and system modules will both define such
1432 // submodules. Make sure cached results for a builtin header won't
1433 // prevent other builtin modules from potentially entering the builtin
1434 // header. Note that builtins are header guarded and the decision to
1435 // actually enter them is postponed to the controlling macros logic below.
1436 bool TryEnterHdr
= false;
1437 if (FileInfo
.isCompilingModuleHeader
&& FileInfo
.isModuleHeader
)
1438 TryEnterHdr
= ModMap
.isBuiltinHeader(File
);
1440 // Textual headers can be #imported from different modules. Since ObjC
1441 // headers find in the wild might rely only on #import and do not contain
1442 // controlling macros, be conservative and only try to enter textual headers
1443 // if such macro is present.
1444 if (!FileInfo
.isModuleHeader
&&
1445 FileInfo
.getControllingMacro(ExternalLookup
))
1450 // If this is a #import directive, check that we have not already imported
1453 // If this has already been imported, don't import it again.
1454 FileInfo
.isImport
= true;
1456 // Has this already been #import'ed or #include'd?
1457 if (PP
.alreadyIncluded(File
) && !TryEnterImported())
1460 // Otherwise, if this is a #include of a file that was previously #import'd
1461 // or if this is the second #include of a #pragma once file, ignore it.
1462 if ((FileInfo
.isPragmaOnce
|| FileInfo
.isImport
) && !TryEnterImported())
1466 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
1467 // if the macro that guards it is defined, we know the #include has no effect.
1468 if (const IdentifierInfo
*ControllingMacro
1469 = FileInfo
.getControllingMacro(ExternalLookup
)) {
1470 // If the header corresponds to a module, check whether the macro is already
1471 // defined in that module rather than checking in the current set of visible
1473 if (M
? PP
.isMacroDefinedInLocalModule(ControllingMacro
, M
)
1474 : PP
.isMacroDefined(ControllingMacro
)) {
1475 ++NumMultiIncludeFileOptzn
;
1480 IsFirstIncludeOfFile
= PP
.markIncluded(File
);
1485 size_t HeaderSearch::getTotalMemory() const {
1486 return SearchDirs
.capacity()
1487 + llvm::capacity_in_bytes(FileInfo
)
1488 + llvm::capacity_in_bytes(HeaderMaps
)
1489 + LookupFileCache
.getAllocator().getTotalMemory()
1490 + FrameworkMap
.getAllocator().getTotalMemory();
1493 unsigned HeaderSearch::searchDirIdx(const DirectoryLookup
&DL
) const {
1494 return &DL
- &*SearchDirs
.begin();
1497 StringRef
HeaderSearch::getUniqueFrameworkName(StringRef Framework
) {
1498 return FrameworkNames
.insert(Framework
).first
->first();
1501 StringRef
HeaderSearch::getIncludeNameForHeader(const FileEntry
*File
) const {
1502 auto It
= IncludeNames
.find(File
);
1503 if (It
== IncludeNames
.end())
1508 bool HeaderSearch::hasModuleMap(StringRef FileName
,
1509 const DirectoryEntry
*Root
,
1511 if (!HSOpts
->ImplicitModuleMaps
)
1514 SmallVector
<const DirectoryEntry
*, 2> FixUpDirectories
;
1516 StringRef DirName
= FileName
;
1518 // Get the parent directory name.
1519 DirName
= llvm::sys::path::parent_path(DirName
);
1520 if (DirName
.empty())
1523 // Determine whether this directory exists.
1524 auto Dir
= FileMgr
.getOptionalDirectoryRef(DirName
);
1528 // Try to load the module map file in this directory.
1529 switch (loadModuleMapFile(*Dir
, IsSystem
,
1530 llvm::sys::path::extension(Dir
->getName()) ==
1532 case LMM_NewlyLoaded
:
1533 case LMM_AlreadyLoaded
:
1534 // Success. All of the directories we stepped through inherit this module
1536 for (unsigned I
= 0, N
= FixUpDirectories
.size(); I
!= N
; ++I
)
1537 DirectoryHasModuleMap
[FixUpDirectories
[I
]] = true;
1540 case LMM_NoDirectory
:
1541 case LMM_InvalidModuleMap
:
1545 // If we hit the top of our search, we're done.
1549 // Keep track of all of the directories we checked, so we can mark them as
1550 // having module maps if we eventually do find a module map.
1551 FixUpDirectories
.push_back(*Dir
);
1555 ModuleMap::KnownHeader
1556 HeaderSearch::findModuleForHeader(FileEntryRef File
, bool AllowTextual
,
1557 bool AllowExcluded
) const {
1558 if (ExternalSource
) {
1559 // Make sure the external source has handled header info about this file,
1560 // which includes whether the file is part of a module.
1561 (void)getExistingFileInfo(File
);
1563 return ModMap
.findModuleForHeader(File
, AllowTextual
, AllowExcluded
);
1566 ArrayRef
<ModuleMap::KnownHeader
>
1567 HeaderSearch::findAllModulesForHeader(FileEntryRef File
) const {
1568 if (ExternalSource
) {
1569 // Make sure the external source has handled header info about this file,
1570 // which includes whether the file is part of a module.
1571 (void)getExistingFileInfo(File
);
1573 return ModMap
.findAllModulesForHeader(File
);
1576 ArrayRef
<ModuleMap::KnownHeader
>
1577 HeaderSearch::findResolvedModulesForHeader(FileEntryRef File
) const {
1578 if (ExternalSource
) {
1579 // Make sure the external source has handled header info about this file,
1580 // which includes whether the file is part of a module.
1581 (void)getExistingFileInfo(File
);
1583 return ModMap
.findResolvedModulesForHeader(File
);
1586 static bool suggestModule(HeaderSearch
&HS
, FileEntryRef File
,
1587 Module
*RequestingModule
,
1588 ModuleMap::KnownHeader
*SuggestedModule
) {
1589 ModuleMap::KnownHeader Module
=
1590 HS
.findModuleForHeader(File
, /*AllowTextual*/true);
1592 // If this module specifies [no_undeclared_includes], we cannot find any
1593 // file that's in a non-dependency module.
1594 if (RequestingModule
&& Module
&& RequestingModule
->NoUndeclaredIncludes
) {
1595 HS
.getModuleMap().resolveUses(RequestingModule
, /*Complain*/ false);
1596 if (!RequestingModule
->directlyUses(Module
.getModule())) {
1597 // Builtin headers are a special case. Multiple modules can use the same
1598 // builtin as a modular header (see also comment in
1599 // ShouldEnterIncludeFile()), so the builtin header may have been
1600 // "claimed" by an unrelated module. This shouldn't prevent us from
1601 // including the builtin header textually in this module.
1602 if (HS
.getModuleMap().isBuiltinHeader(File
)) {
1603 if (SuggestedModule
)
1604 *SuggestedModule
= ModuleMap::KnownHeader();
1607 // TODO: Add this module (or just its module map file) into something like
1608 // `RequestingModule->AffectingClangModules`.
1613 if (SuggestedModule
)
1614 *SuggestedModule
= (Module
.getRole() & ModuleMap::TextualHeader
)
1615 ? ModuleMap::KnownHeader()
1621 bool HeaderSearch::findUsableModuleForHeader(
1622 FileEntryRef File
, const DirectoryEntry
*Root
, Module
*RequestingModule
,
1623 ModuleMap::KnownHeader
*SuggestedModule
, bool IsSystemHeaderDir
) {
1624 if (needModuleLookup(RequestingModule
, SuggestedModule
)) {
1625 // If there is a module that corresponds to this header, suggest it.
1626 hasModuleMap(File
.getNameAsRequested(), Root
, IsSystemHeaderDir
);
1627 return suggestModule(*this, File
, RequestingModule
, SuggestedModule
);
1632 bool HeaderSearch::findUsableModuleForFrameworkHeader(
1633 FileEntryRef File
, StringRef FrameworkName
, Module
*RequestingModule
,
1634 ModuleMap::KnownHeader
*SuggestedModule
, bool IsSystemFramework
) {
1635 // If we're supposed to suggest a module, look for one now.
1636 if (needModuleLookup(RequestingModule
, SuggestedModule
)) {
1637 // Find the top-level framework based on this framework.
1638 SmallVector
<std::string
, 4> SubmodulePath
;
1639 OptionalDirectoryEntryRef TopFrameworkDir
=
1640 ::getTopFrameworkDir(FileMgr
, FrameworkName
, SubmodulePath
);
1641 assert(TopFrameworkDir
&& "Could not find the top-most framework dir");
1643 // Determine the name of the top-level framework.
1644 StringRef ModuleName
= llvm::sys::path::stem(TopFrameworkDir
->getName());
1646 // Load this framework module. If that succeeds, find the suggested module
1647 // for this header, if any.
1648 loadFrameworkModule(ModuleName
, *TopFrameworkDir
, IsSystemFramework
);
1650 // FIXME: This can find a module not part of ModuleName, which is
1651 // important so that we're consistent about whether this header
1652 // corresponds to a module. Possibly we should lock down framework modules
1653 // so that this is not possible.
1654 return suggestModule(*this, File
, RequestingModule
, SuggestedModule
);
1659 static OptionalFileEntryRef
getPrivateModuleMap(FileEntryRef File
,
1660 FileManager
&FileMgr
) {
1661 StringRef Filename
= llvm::sys::path::filename(File
.getName());
1662 SmallString
<128> PrivateFilename(File
.getDir().getName());
1663 if (Filename
== "module.map")
1664 llvm::sys::path::append(PrivateFilename
, "module_private.map");
1665 else if (Filename
== "module.modulemap")
1666 llvm::sys::path::append(PrivateFilename
, "module.private.modulemap");
1668 return std::nullopt
;
1669 return FileMgr
.getOptionalFileRef(PrivateFilename
);
1672 bool HeaderSearch::loadModuleMapFile(FileEntryRef File
, bool IsSystem
,
1673 FileID ID
, unsigned *Offset
,
1674 StringRef OriginalModuleMapFile
) {
1675 // Find the directory for the module. For frameworks, that may require going
1676 // up from the 'Modules' directory.
1677 OptionalDirectoryEntryRef Dir
;
1678 if (getHeaderSearchOpts().ModuleMapFileHomeIsCwd
) {
1679 Dir
= FileMgr
.getOptionalDirectoryRef(".");
1681 if (!OriginalModuleMapFile
.empty()) {
1682 // We're building a preprocessed module map. Find or invent the directory
1683 // that it originally occupied.
1684 Dir
= FileMgr
.getOptionalDirectoryRef(
1685 llvm::sys::path::parent_path(OriginalModuleMapFile
));
1687 auto FakeFile
= FileMgr
.getVirtualFileRef(OriginalModuleMapFile
, 0, 0);
1688 Dir
= FakeFile
.getDir();
1691 Dir
= File
.getDir();
1694 assert(Dir
&& "parent must exist");
1695 StringRef
DirName(Dir
->getName());
1696 if (llvm::sys::path::filename(DirName
) == "Modules") {
1697 DirName
= llvm::sys::path::parent_path(DirName
);
1698 if (DirName
.endswith(".framework"))
1699 if (auto MaybeDir
= FileMgr
.getOptionalDirectoryRef(DirName
))
1701 // FIXME: This assert can fail if there's a race between the above check
1702 // and the removal of the directory.
1703 assert(Dir
&& "parent must exist");
1707 assert(Dir
&& "module map home directory must exist");
1708 switch (loadModuleMapFileImpl(File
, IsSystem
, *Dir
, ID
, Offset
)) {
1709 case LMM_AlreadyLoaded
:
1710 case LMM_NewlyLoaded
:
1712 case LMM_NoDirectory
:
1713 case LMM_InvalidModuleMap
:
1716 llvm_unreachable("Unknown load module map result");
1719 HeaderSearch::LoadModuleMapResult
1720 HeaderSearch::loadModuleMapFileImpl(FileEntryRef File
, bool IsSystem
,
1721 DirectoryEntryRef Dir
, FileID ID
,
1723 // Check whether we've already loaded this module map, and mark it as being
1724 // loaded in case we recursively try to load it from itself.
1725 auto AddResult
= LoadedModuleMaps
.insert(std::make_pair(File
, true));
1726 if (!AddResult
.second
)
1727 return AddResult
.first
->second
? LMM_AlreadyLoaded
: LMM_InvalidModuleMap
;
1729 if (ModMap
.parseModuleMapFile(File
, IsSystem
, Dir
, ID
, Offset
)) {
1730 LoadedModuleMaps
[File
] = false;
1731 return LMM_InvalidModuleMap
;
1734 // Try to load a corresponding private module map.
1735 if (OptionalFileEntryRef PMMFile
= getPrivateModuleMap(File
, FileMgr
)) {
1736 if (ModMap
.parseModuleMapFile(*PMMFile
, IsSystem
, Dir
)) {
1737 LoadedModuleMaps
[File
] = false;
1738 return LMM_InvalidModuleMap
;
1742 // This directory has a module map.
1743 return LMM_NewlyLoaded
;
1746 OptionalFileEntryRef
1747 HeaderSearch::lookupModuleMapFile(DirectoryEntryRef Dir
, bool IsFramework
) {
1748 if (!HSOpts
->ImplicitModuleMaps
)
1749 return std::nullopt
;
1750 // For frameworks, the preferred spelling is Modules/module.modulemap, but
1751 // module.map at the framework root is also accepted.
1752 SmallString
<128> ModuleMapFileName(Dir
.getName());
1754 llvm::sys::path::append(ModuleMapFileName
, "Modules");
1755 llvm::sys::path::append(ModuleMapFileName
, "module.modulemap");
1756 if (auto F
= FileMgr
.getOptionalFileRef(ModuleMapFileName
))
1759 // Continue to allow module.map
1760 ModuleMapFileName
= Dir
.getName();
1761 llvm::sys::path::append(ModuleMapFileName
, "module.map");
1762 if (auto F
= FileMgr
.getOptionalFileRef(ModuleMapFileName
))
1765 // For frameworks, allow to have a private module map with a preferred
1766 // spelling when a public module map is absent.
1768 ModuleMapFileName
= Dir
.getName();
1769 llvm::sys::path::append(ModuleMapFileName
, "Modules",
1770 "module.private.modulemap");
1771 if (auto F
= FileMgr
.getOptionalFileRef(ModuleMapFileName
))
1774 return std::nullopt
;
1777 Module
*HeaderSearch::loadFrameworkModule(StringRef Name
, DirectoryEntryRef Dir
,
1779 // Try to load a module map file.
1780 switch (loadModuleMapFile(Dir
, IsSystem
, /*IsFramework*/true)) {
1781 case LMM_InvalidModuleMap
:
1782 // Try to infer a module map from the framework directory.
1783 if (HSOpts
->ImplicitModuleMaps
)
1784 ModMap
.inferFrameworkModule(Dir
, IsSystem
, /*Parent=*/nullptr);
1787 case LMM_NoDirectory
:
1790 case LMM_AlreadyLoaded
:
1791 case LMM_NewlyLoaded
:
1795 return ModMap
.findModule(Name
);
1798 HeaderSearch::LoadModuleMapResult
1799 HeaderSearch::loadModuleMapFile(StringRef DirName
, bool IsSystem
,
1801 if (auto Dir
= FileMgr
.getOptionalDirectoryRef(DirName
))
1802 return loadModuleMapFile(*Dir
, IsSystem
, IsFramework
);
1804 return LMM_NoDirectory
;
1807 HeaderSearch::LoadModuleMapResult
1808 HeaderSearch::loadModuleMapFile(DirectoryEntryRef Dir
, bool IsSystem
,
1810 auto KnownDir
= DirectoryHasModuleMap
.find(Dir
);
1811 if (KnownDir
!= DirectoryHasModuleMap
.end())
1812 return KnownDir
->second
? LMM_AlreadyLoaded
: LMM_InvalidModuleMap
;
1814 if (OptionalFileEntryRef ModuleMapFile
=
1815 lookupModuleMapFile(Dir
, IsFramework
)) {
1816 LoadModuleMapResult Result
=
1817 loadModuleMapFileImpl(*ModuleMapFile
, IsSystem
, Dir
);
1818 // Add Dir explicitly in case ModuleMapFile is in a subdirectory.
1819 // E.g. Foo.framework/Modules/module.modulemap
1820 // ^Dir ^ModuleMapFile
1821 if (Result
== LMM_NewlyLoaded
)
1822 DirectoryHasModuleMap
[Dir
] = true;
1823 else if (Result
== LMM_InvalidModuleMap
)
1824 DirectoryHasModuleMap
[Dir
] = false;
1827 return LMM_InvalidModuleMap
;
1830 void HeaderSearch::collectAllModules(SmallVectorImpl
<Module
*> &Modules
) {
1833 if (HSOpts
->ImplicitModuleMaps
) {
1834 // Load module maps for each of the header search directories.
1835 for (DirectoryLookup
&DL
: search_dir_range()) {
1836 bool IsSystem
= DL
.isSystemHeaderDirectory();
1837 if (DL
.isFramework()) {
1839 SmallString
<128> DirNative
;
1840 llvm::sys::path::native(DL
.getFrameworkDirRef()->getName(), DirNative
);
1842 // Search each of the ".framework" directories to load them as modules.
1843 llvm::vfs::FileSystem
&FS
= FileMgr
.getVirtualFileSystem();
1844 for (llvm::vfs::directory_iterator Dir
= FS
.dir_begin(DirNative
, EC
),
1846 Dir
!= DirEnd
&& !EC
; Dir
.increment(EC
)) {
1847 if (llvm::sys::path::extension(Dir
->path()) != ".framework")
1850 auto FrameworkDir
= FileMgr
.getOptionalDirectoryRef(Dir
->path());
1854 // Load this framework module.
1855 loadFrameworkModule(llvm::sys::path::stem(Dir
->path()), *FrameworkDir
,
1861 // FIXME: Deal with header maps.
1862 if (DL
.isHeaderMap())
1865 // Try to load a module map file for the search directory.
1866 loadModuleMapFile(*DL
.getDirRef(), IsSystem
, /*IsFramework*/ false);
1868 // Try to load module map files for immediate subdirectories of this
1869 // search directory.
1870 loadSubdirectoryModuleMaps(DL
);
1874 // Populate the list of modules.
1875 llvm::transform(ModMap
.modules(), std::back_inserter(Modules
),
1876 [](const auto &NameAndMod
) { return NameAndMod
.second
; });
1879 void HeaderSearch::loadTopLevelSystemModules() {
1880 if (!HSOpts
->ImplicitModuleMaps
)
1883 // Load module maps for each of the header search directories.
1884 for (const DirectoryLookup
&DL
: search_dir_range()) {
1885 // We only care about normal header directories.
1886 if (!DL
.isNormalDir())
1889 // Try to load a module map file for the search directory.
1890 loadModuleMapFile(*DL
.getDirRef(), DL
.isSystemHeaderDirectory(),
1895 void HeaderSearch::loadSubdirectoryModuleMaps(DirectoryLookup
&SearchDir
) {
1896 assert(HSOpts
->ImplicitModuleMaps
&&
1897 "Should not be loading subdirectory module maps");
1899 if (SearchDir
.haveSearchedAllModuleMaps())
1903 SmallString
<128> Dir
= SearchDir
.getDirRef()->getName();
1904 FileMgr
.makeAbsolutePath(Dir
);
1905 SmallString
<128> DirNative
;
1906 llvm::sys::path::native(Dir
, DirNative
);
1907 llvm::vfs::FileSystem
&FS
= FileMgr
.getVirtualFileSystem();
1908 for (llvm::vfs::directory_iterator Dir
= FS
.dir_begin(DirNative
, EC
), DirEnd
;
1909 Dir
!= DirEnd
&& !EC
; Dir
.increment(EC
)) {
1910 if (Dir
->type() == llvm::sys::fs::file_type::regular_file
)
1912 bool IsFramework
= llvm::sys::path::extension(Dir
->path()) == ".framework";
1913 if (IsFramework
== SearchDir
.isFramework())
1914 loadModuleMapFile(Dir
->path(), SearchDir
.isSystemHeaderDirectory(),
1915 SearchDir
.isFramework());
1918 SearchDir
.setSearchedAllModuleMaps(true);
1921 std::string
HeaderSearch::suggestPathToFileForDiagnostics(
1922 FileEntryRef File
, llvm::StringRef MainFile
, bool *IsAngled
) const {
1923 return suggestPathToFileForDiagnostics(File
.getName(), /*WorkingDir=*/"",
1924 MainFile
, IsAngled
);
1927 std::string
HeaderSearch::suggestPathToFileForDiagnostics(
1928 llvm::StringRef File
, llvm::StringRef WorkingDir
, llvm::StringRef MainFile
,
1929 bool *IsAngled
) const {
1930 using namespace llvm::sys
;
1932 llvm::SmallString
<32> FilePath
= File
;
1933 // remove_dots switches to backslashes on windows as a side-effect!
1934 // We always want to suggest forward slashes for includes.
1935 // (not remove_dots(..., posix) as that misparses windows paths).
1936 path::remove_dots(FilePath
, /*remove_dot_dot=*/true);
1937 path::native(FilePath
, path::Style::posix
);
1940 unsigned BestPrefixLength
= 0;
1941 // Checks whether `Dir` is a strict path prefix of `File`. If so and that's
1942 // the longest prefix we've seen so for it, returns true and updates the
1943 // `BestPrefixLength` accordingly.
1944 auto CheckDir
= [&](llvm::SmallString
<32> Dir
) -> bool {
1945 if (!WorkingDir
.empty() && !path::is_absolute(Dir
))
1946 fs::make_absolute(WorkingDir
, Dir
);
1947 path::remove_dots(Dir
, /*remove_dot_dot=*/true);
1948 for (auto NI
= path::begin(File
), NE
= path::end(File
),
1949 DI
= path::begin(Dir
), DE
= path::end(Dir
);
1950 NI
!= NE
; ++NI
, ++DI
) {
1952 // Dir is a prefix of File, up to choice of path separators.
1953 unsigned PrefixLength
= NI
- path::begin(File
);
1954 if (PrefixLength
> BestPrefixLength
) {
1955 BestPrefixLength
= PrefixLength
;
1961 // Consider all path separators equal.
1962 if (NI
->size() == 1 && DI
->size() == 1 &&
1963 path::is_separator(NI
->front()) && path::is_separator(DI
->front()))
1966 // Special case Apple .sdk folders since the search path is typically a
1967 // symlink like `iPhoneSimulator14.5.sdk` while the file is instead
1968 // located in `iPhoneSimulator.sdk` (the real folder).
1969 if (NI
->endswith(".sdk") && DI
->endswith(".sdk")) {
1970 StringRef NBasename
= path::stem(*NI
);
1971 StringRef DBasename
= path::stem(*DI
);
1972 if (DBasename
.startswith(NBasename
))
1982 bool BestPrefixIsFramework
= false;
1983 for (const DirectoryLookup
&DL
: search_dir_range()) {
1984 if (DL
.isNormalDir()) {
1985 StringRef Dir
= DL
.getDirRef()->getName();
1986 if (CheckDir(Dir
)) {
1988 *IsAngled
= BestPrefixLength
&& isSystem(DL
.getDirCharacteristic());
1989 BestPrefixIsFramework
= false;
1991 } else if (DL
.isFramework()) {
1992 StringRef Dir
= DL
.getFrameworkDirRef()->getName();
1993 if (CheckDir(Dir
)) {
1994 // Framework includes by convention use <>.
1996 *IsAngled
= BestPrefixLength
;
1997 BestPrefixIsFramework
= true;
2002 // Try to shorten include path using TUs directory, if we couldn't find any
2003 // suitable prefix in include search paths.
2004 if (!BestPrefixLength
&& CheckDir(path::parent_path(MainFile
))) {
2007 BestPrefixIsFramework
= false;
2010 // Try resolving resulting filename via reverse search in header maps,
2011 // key from header name is user preferred name for the include file.
2012 StringRef Filename
= File
.drop_front(BestPrefixLength
);
2013 for (const DirectoryLookup
&DL
: search_dir_range()) {
2014 if (!DL
.isHeaderMap())
2017 StringRef SpelledFilename
=
2018 DL
.getHeaderMap()->reverseLookupFilename(Filename
);
2019 if (!SpelledFilename
.empty()) {
2020 Filename
= SpelledFilename
;
2021 BestPrefixIsFramework
= false;
2026 // If the best prefix is a framework path, we need to compute the proper
2027 // include spelling for the framework header.
2028 bool IsPrivateHeader
;
2029 SmallString
<128> FrameworkName
, IncludeSpelling
;
2030 if (BestPrefixIsFramework
&&
2031 isFrameworkStylePath(Filename
, IsPrivateHeader
, FrameworkName
,
2033 Filename
= IncludeSpelling
;
2035 return path::convert_to_slash(Filename
);