[docs] Add LICENSE.txt to the root of the mono-repo
[llvm-project.git] / clang / lib / Lex / HeaderSearch.cpp
blob219c62663ebd05f615e85ad196af2cebdfed9921
1 //===- HeaderSearch.cpp - Resolve Header File Locations -------------------===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 //
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"
40 #include <algorithm>
41 #include <cassert>
42 #include <cstddef>
43 #include <cstdio>
44 #include <cstring>
45 #include <string>
46 #include <system_error>
47 #include <utility>
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)
74 return nullptr;
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();
121 void HeaderSearch::AddSearchPath(const DirectoryLookup &dir, bool isAngled) {
122 unsigned idx = isAngled ? SystemDirIdx : AngledDirIdx;
123 SearchDirs.insert(SearchDirs.begin() + idx, dir);
124 SearchDirsUsage.insert(SearchDirsUsage.begin() + idx, false);
125 if (!isAngled)
126 AngledDirIdx++;
127 SystemDirIdx++;
130 std::vector<bool> HeaderSearch::computeUserEntryUsage() const {
131 std::vector<bool> UserEntryUsage(HSOpts->UserEntries.size());
132 for (unsigned I = 0, E = SearchDirsUsage.size(); I < E; ++I) {
133 // Check whether this DirectoryLookup has been successfully used.
134 if (SearchDirsUsage[I]) {
135 auto UserEntryIdxIt = SearchDirToHSEntry.find(I);
136 // Check whether this DirectoryLookup maps to a HeaderSearch::UserEntry.
137 if (UserEntryIdxIt != SearchDirToHSEntry.end())
138 UserEntryUsage[UserEntryIdxIt->second] = true;
141 return UserEntryUsage;
144 /// CreateHeaderMap - This method returns a HeaderMap for the specified
145 /// FileEntry, uniquing them through the 'HeaderMaps' datastructure.
146 const HeaderMap *HeaderSearch::CreateHeaderMap(const FileEntry *FE) {
147 // We expect the number of headermaps to be small, and almost always empty.
148 // If it ever grows, use of a linear search should be re-evaluated.
149 if (!HeaderMaps.empty()) {
150 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
151 // Pointer equality comparison of FileEntries works because they are
152 // already uniqued by inode.
153 if (HeaderMaps[i].first == FE)
154 return HeaderMaps[i].second.get();
157 if (std::unique_ptr<HeaderMap> HM = HeaderMap::Create(FE, FileMgr)) {
158 HeaderMaps.emplace_back(FE, std::move(HM));
159 return HeaderMaps.back().second.get();
162 return nullptr;
165 /// Get filenames for all registered header maps.
166 void HeaderSearch::getHeaderMapFileNames(
167 SmallVectorImpl<std::string> &Names) const {
168 for (auto &HM : HeaderMaps)
169 Names.push_back(std::string(HM.first->getName()));
172 std::string HeaderSearch::getCachedModuleFileName(Module *Module) {
173 const FileEntry *ModuleMap =
174 getModuleMap().getModuleMapFileForUniquing(Module);
175 // The ModuleMap maybe a nullptr, when we load a cached C++ module without
176 // *.modulemap file. In this case, just return an empty string.
177 if (ModuleMap == nullptr)
178 return {};
179 return getCachedModuleFileName(Module->Name, ModuleMap->getName());
182 std::string HeaderSearch::getPrebuiltModuleFileName(StringRef ModuleName,
183 bool FileMapOnly) {
184 // First check the module name to pcm file map.
185 auto i(HSOpts->PrebuiltModuleFiles.find(ModuleName));
186 if (i != HSOpts->PrebuiltModuleFiles.end())
187 return i->second;
189 if (FileMapOnly || HSOpts->PrebuiltModulePaths.empty())
190 return {};
192 // Then go through each prebuilt module directory and try to find the pcm
193 // file.
194 for (const std::string &Dir : HSOpts->PrebuiltModulePaths) {
195 SmallString<256> Result(Dir);
196 llvm::sys::fs::make_absolute(Result);
197 if (ModuleName.contains(':'))
198 // The separator of C++20 modules partitions (':') is not good for file
199 // systems, here clang and gcc choose '-' by default since it is not a
200 // valid character of C++ indentifiers. So we could avoid conflicts.
201 llvm::sys::path::append(Result, ModuleName.split(':').first + "-" +
202 ModuleName.split(':').second +
203 ".pcm");
204 else
205 llvm::sys::path::append(Result, ModuleName + ".pcm");
206 if (getFileMgr().getFile(Result.str()))
207 return std::string(Result);
210 return {};
213 std::string HeaderSearch::getPrebuiltImplicitModuleFileName(Module *Module) {
214 const FileEntry *ModuleMap =
215 getModuleMap().getModuleMapFileForUniquing(Module);
216 StringRef ModuleName = Module->Name;
217 StringRef ModuleMapPath = ModuleMap->getName();
218 StringRef ModuleCacheHash = HSOpts->DisableModuleHash ? "" : getModuleHash();
219 for (const std::string &Dir : HSOpts->PrebuiltModulePaths) {
220 SmallString<256> CachePath(Dir);
221 llvm::sys::fs::make_absolute(CachePath);
222 llvm::sys::path::append(CachePath, ModuleCacheHash);
223 std::string FileName =
224 getCachedModuleFileNameImpl(ModuleName, ModuleMapPath, CachePath);
225 if (!FileName.empty() && getFileMgr().getFile(FileName))
226 return FileName;
228 return {};
231 std::string HeaderSearch::getCachedModuleFileName(StringRef ModuleName,
232 StringRef ModuleMapPath) {
233 return getCachedModuleFileNameImpl(ModuleName, ModuleMapPath,
234 getModuleCachePath());
237 std::string HeaderSearch::getCachedModuleFileNameImpl(StringRef ModuleName,
238 StringRef ModuleMapPath,
239 StringRef CachePath) {
240 // If we don't have a module cache path or aren't supposed to use one, we
241 // can't do anything.
242 if (CachePath.empty())
243 return {};
245 SmallString<256> Result(CachePath);
246 llvm::sys::fs::make_absolute(Result);
248 if (HSOpts->DisableModuleHash) {
249 llvm::sys::path::append(Result, ModuleName + ".pcm");
250 } else {
251 // Construct the name <ModuleName>-<hash of ModuleMapPath>.pcm which should
252 // ideally be globally unique to this particular module. Name collisions
253 // in the hash are safe (because any translation unit can only import one
254 // module with each name), but result in a loss of caching.
256 // To avoid false-negatives, we form as canonical a path as we can, and map
257 // to lower-case in case we're on a case-insensitive file system.
258 std::string Parent =
259 std::string(llvm::sys::path::parent_path(ModuleMapPath));
260 if (Parent.empty())
261 Parent = ".";
262 auto Dir = FileMgr.getDirectory(Parent);
263 if (!Dir)
264 return {};
265 auto DirName = FileMgr.getCanonicalName(*Dir);
266 auto FileName = llvm::sys::path::filename(ModuleMapPath);
268 llvm::hash_code Hash =
269 llvm::hash_combine(DirName.lower(), FileName.lower());
271 SmallString<128> HashStr;
272 llvm::APInt(64, size_t(Hash)).toStringUnsigned(HashStr, /*Radix*/36);
273 llvm::sys::path::append(Result, ModuleName + "-" + HashStr + ".pcm");
275 return Result.str().str();
278 Module *HeaderSearch::lookupModule(StringRef ModuleName,
279 SourceLocation ImportLoc, bool AllowSearch,
280 bool AllowExtraModuleMapSearch) {
281 // Look in the module map to determine if there is a module by this name.
282 Module *Module = ModMap.findModule(ModuleName);
283 if (Module || !AllowSearch || !HSOpts->ImplicitModuleMaps)
284 return Module;
286 StringRef SearchName = ModuleName;
287 Module = lookupModule(ModuleName, SearchName, ImportLoc,
288 AllowExtraModuleMapSearch);
290 // The facility for "private modules" -- adjacent, optional module maps named
291 // module.private.modulemap that are supposed to define private submodules --
292 // may have different flavors of names: FooPrivate, Foo_Private and Foo.Private.
294 // Foo.Private is now deprecated in favor of Foo_Private. Users of FooPrivate
295 // should also rename to Foo_Private. Representing private as submodules
296 // could force building unwanted dependencies into the parent module and cause
297 // dependency cycles.
298 if (!Module && SearchName.consume_back("_Private"))
299 Module = lookupModule(ModuleName, SearchName, ImportLoc,
300 AllowExtraModuleMapSearch);
301 if (!Module && SearchName.consume_back("Private"))
302 Module = lookupModule(ModuleName, SearchName, ImportLoc,
303 AllowExtraModuleMapSearch);
304 return Module;
307 Module *HeaderSearch::lookupModule(StringRef ModuleName, StringRef SearchName,
308 SourceLocation ImportLoc,
309 bool AllowExtraModuleMapSearch) {
310 Module *Module = nullptr;
312 // Look through the various header search paths to load any available module
313 // maps, searching for a module map that describes this module.
314 for (DirectoryLookup Dir : search_dir_range()) {
315 if (Dir.isFramework()) {
316 // Search for or infer a module map for a framework. Here we use
317 // SearchName rather than ModuleName, to permit finding private modules
318 // named FooPrivate in buggy frameworks named Foo.
319 SmallString<128> FrameworkDirName;
320 FrameworkDirName += Dir.getFrameworkDir()->getName();
321 llvm::sys::path::append(FrameworkDirName, SearchName + ".framework");
322 if (auto FrameworkDir =
323 FileMgr.getOptionalDirectoryRef(FrameworkDirName)) {
324 bool IsSystem = Dir.getDirCharacteristic() != SrcMgr::C_User;
325 Module = loadFrameworkModule(ModuleName, *FrameworkDir, IsSystem);
326 if (Module)
327 break;
331 // FIXME: Figure out how header maps and module maps will work together.
333 // Only deal with normal search directories.
334 if (!Dir.isNormalDir())
335 continue;
337 bool IsSystem = Dir.isSystemHeaderDirectory();
338 // Only returns None if not a normal directory, which we just checked
339 DirectoryEntryRef NormalDir = *Dir.getDirRef();
340 // Search for a module map file in this directory.
341 if (loadModuleMapFile(NormalDir, IsSystem,
342 /*IsFramework*/false) == LMM_NewlyLoaded) {
343 // We just loaded a module map file; check whether the module is
344 // available now.
345 Module = ModMap.findModule(ModuleName);
346 if (Module)
347 break;
350 // Search for a module map in a subdirectory with the same name as the
351 // module.
352 SmallString<128> NestedModuleMapDirName;
353 NestedModuleMapDirName = Dir.getDir()->getName();
354 llvm::sys::path::append(NestedModuleMapDirName, ModuleName);
355 if (loadModuleMapFile(NestedModuleMapDirName, IsSystem,
356 /*IsFramework*/false) == LMM_NewlyLoaded){
357 // If we just loaded a module map file, look for the module again.
358 Module = ModMap.findModule(ModuleName);
359 if (Module)
360 break;
363 // If we've already performed the exhaustive search for module maps in this
364 // search directory, don't do it again.
365 if (Dir.haveSearchedAllModuleMaps())
366 continue;
368 // Load all module maps in the immediate subdirectories of this search
369 // directory if ModuleName was from @import.
370 if (AllowExtraModuleMapSearch)
371 loadSubdirectoryModuleMaps(Dir);
373 // Look again for the module.
374 Module = ModMap.findModule(ModuleName);
375 if (Module)
376 break;
379 return Module;
382 //===----------------------------------------------------------------------===//
383 // File lookup within a DirectoryLookup scope
384 //===----------------------------------------------------------------------===//
386 /// getName - Return the directory or filename corresponding to this lookup
387 /// object.
388 StringRef DirectoryLookup::getName() const {
389 // FIXME: Use the name from \c DirectoryEntryRef.
390 if (isNormalDir())
391 return getDir()->getName();
392 if (isFramework())
393 return getFrameworkDir()->getName();
394 assert(isHeaderMap() && "Unknown DirectoryLookup");
395 return getHeaderMap()->getFileName();
398 Optional<FileEntryRef> HeaderSearch::getFileAndSuggestModule(
399 StringRef FileName, SourceLocation IncludeLoc, const DirectoryEntry *Dir,
400 bool IsSystemHeaderDir, Module *RequestingModule,
401 ModuleMap::KnownHeader *SuggestedModule, bool OpenFile /*=true*/,
402 bool CacheFailures /*=true*/) {
403 // If we have a module map that might map this header, load it and
404 // check whether we'll have a suggestion for a module.
405 auto File = getFileMgr().getFileRef(FileName, OpenFile, CacheFailures);
406 if (!File) {
407 // For rare, surprising errors (e.g. "out of file handles"), diag the EC
408 // message.
409 std::error_code EC = llvm::errorToErrorCode(File.takeError());
410 if (EC != llvm::errc::no_such_file_or_directory &&
411 EC != llvm::errc::invalid_argument &&
412 EC != llvm::errc::is_a_directory && EC != llvm::errc::not_a_directory) {
413 Diags.Report(IncludeLoc, diag::err_cannot_open_file)
414 << FileName << EC.message();
416 return None;
419 // If there is a module that corresponds to this header, suggest it.
420 if (!findUsableModuleForHeader(
421 &File->getFileEntry(), Dir ? Dir : File->getFileEntry().getDir(),
422 RequestingModule, SuggestedModule, IsSystemHeaderDir))
423 return None;
425 return *File;
428 /// LookupFile - Lookup the specified file in this search path, returning it
429 /// if it exists or returning null if not.
430 Optional<FileEntryRef> DirectoryLookup::LookupFile(
431 StringRef &Filename, HeaderSearch &HS, SourceLocation IncludeLoc,
432 SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
433 Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule,
434 bool &InUserSpecifiedSystemFramework, bool &IsFrameworkFound,
435 bool &IsInHeaderMap, SmallVectorImpl<char> &MappedName,
436 bool OpenFile) const {
437 InUserSpecifiedSystemFramework = false;
438 IsInHeaderMap = false;
439 MappedName.clear();
441 SmallString<1024> TmpDir;
442 if (isNormalDir()) {
443 // Concatenate the requested file onto the directory.
444 TmpDir = getDirRef()->getName();
445 llvm::sys::path::append(TmpDir, Filename);
446 if (SearchPath) {
447 StringRef SearchPathRef(getDirRef()->getName());
448 SearchPath->clear();
449 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
451 if (RelativePath) {
452 RelativePath->clear();
453 RelativePath->append(Filename.begin(), Filename.end());
456 return HS.getFileAndSuggestModule(
457 TmpDir, IncludeLoc, getDir(), isSystemHeaderDirectory(),
458 RequestingModule, SuggestedModule, OpenFile);
461 if (isFramework())
462 return DoFrameworkLookup(Filename, HS, SearchPath, RelativePath,
463 RequestingModule, SuggestedModule,
464 InUserSpecifiedSystemFramework, IsFrameworkFound);
466 assert(isHeaderMap() && "Unknown directory lookup");
467 const HeaderMap *HM = getHeaderMap();
468 SmallString<1024> Path;
469 StringRef Dest = HM->lookupFilename(Filename, Path);
470 if (Dest.empty())
471 return None;
473 IsInHeaderMap = true;
475 auto FixupSearchPath = [&]() {
476 if (SearchPath) {
477 StringRef SearchPathRef(getName());
478 SearchPath->clear();
479 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
481 if (RelativePath) {
482 RelativePath->clear();
483 RelativePath->append(Filename.begin(), Filename.end());
487 // Check if the headermap maps the filename to a framework include
488 // ("Foo.h" -> "Foo/Foo.h"), in which case continue header lookup using the
489 // framework include.
490 if (llvm::sys::path::is_relative(Dest)) {
491 MappedName.append(Dest.begin(), Dest.end());
492 Filename = StringRef(MappedName.begin(), MappedName.size());
493 Dest = HM->lookupFilename(Filename, Path);
496 if (auto Res = HS.getFileMgr().getOptionalFileRef(Dest, OpenFile)) {
497 FixupSearchPath();
498 return *Res;
501 // Header maps need to be marked as used whenever the filename matches.
502 // The case where the target file **exists** is handled by callee of this
503 // function as part of the regular logic that applies to include search paths.
504 // The case where the target file **does not exist** is handled here:
505 HS.noteLookupUsage(HS.searchDirIdx(*this), IncludeLoc);
506 return None;
509 /// Given a framework directory, find the top-most framework directory.
511 /// \param FileMgr The file manager to use for directory lookups.
512 /// \param DirName The name of the framework directory.
513 /// \param SubmodulePath Will be populated with the submodule path from the
514 /// returned top-level module to the originally named framework.
515 static Optional<DirectoryEntryRef>
516 getTopFrameworkDir(FileManager &FileMgr, StringRef DirName,
517 SmallVectorImpl<std::string> &SubmodulePath) {
518 assert(llvm::sys::path::extension(DirName) == ".framework" &&
519 "Not a framework directory");
521 // Note: as an egregious but useful hack we use the real path here, because
522 // frameworks moving between top-level frameworks to embedded frameworks tend
523 // to be symlinked, and we base the logical structure of modules on the
524 // physical layout. In particular, we need to deal with crazy includes like
526 // #include <Foo/Frameworks/Bar.framework/Headers/Wibble.h>
528 // where 'Bar' used to be embedded in 'Foo', is now a top-level framework
529 // which one should access with, e.g.,
531 // #include <Bar/Wibble.h>
533 // Similar issues occur when a top-level framework has moved into an
534 // embedded framework.
535 auto TopFrameworkDir = FileMgr.getOptionalDirectoryRef(DirName);
537 if (TopFrameworkDir)
538 DirName = FileMgr.getCanonicalName(*TopFrameworkDir);
539 do {
540 // Get the parent directory name.
541 DirName = llvm::sys::path::parent_path(DirName);
542 if (DirName.empty())
543 break;
545 // Determine whether this directory exists.
546 auto Dir = FileMgr.getOptionalDirectoryRef(DirName);
547 if (!Dir)
548 break;
550 // If this is a framework directory, then we're a subframework of this
551 // framework.
552 if (llvm::sys::path::extension(DirName) == ".framework") {
553 SubmodulePath.push_back(std::string(llvm::sys::path::stem(DirName)));
554 TopFrameworkDir = *Dir;
556 } while (true);
558 return TopFrameworkDir;
561 static bool needModuleLookup(Module *RequestingModule,
562 bool HasSuggestedModule) {
563 return HasSuggestedModule ||
564 (RequestingModule && RequestingModule->NoUndeclaredIncludes);
567 /// DoFrameworkLookup - Do a lookup of the specified file in the current
568 /// DirectoryLookup, which is a framework directory.
569 Optional<FileEntryRef> DirectoryLookup::DoFrameworkLookup(
570 StringRef Filename, HeaderSearch &HS, SmallVectorImpl<char> *SearchPath,
571 SmallVectorImpl<char> *RelativePath, Module *RequestingModule,
572 ModuleMap::KnownHeader *SuggestedModule,
573 bool &InUserSpecifiedSystemFramework, bool &IsFrameworkFound) const {
574 FileManager &FileMgr = HS.getFileMgr();
576 // Framework names must have a '/' in the filename.
577 size_t SlashPos = Filename.find('/');
578 if (SlashPos == StringRef::npos)
579 return None;
581 // Find out if this is the home for the specified framework, by checking
582 // HeaderSearch. Possible answers are yes/no and unknown.
583 FrameworkCacheEntry &CacheEntry =
584 HS.LookupFrameworkCache(Filename.substr(0, SlashPos));
586 // If it is known and in some other directory, fail.
587 if (CacheEntry.Directory && CacheEntry.Directory != getFrameworkDirRef())
588 return None;
590 // Otherwise, construct the path to this framework dir.
592 // FrameworkName = "/System/Library/Frameworks/"
593 SmallString<1024> FrameworkName;
594 FrameworkName += getFrameworkDirRef()->getName();
595 if (FrameworkName.empty() || FrameworkName.back() != '/')
596 FrameworkName.push_back('/');
598 // FrameworkName = "/System/Library/Frameworks/Cocoa"
599 StringRef ModuleName(Filename.begin(), SlashPos);
600 FrameworkName += ModuleName;
602 // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/"
603 FrameworkName += ".framework/";
605 // If the cache entry was unresolved, populate it now.
606 if (!CacheEntry.Directory) {
607 ++NumFrameworkLookups;
609 // If the framework dir doesn't exist, we fail.
610 auto Dir = FileMgr.getDirectory(FrameworkName);
611 if (!Dir)
612 return None;
614 // Otherwise, if it does, remember that this is the right direntry for this
615 // framework.
616 CacheEntry.Directory = getFrameworkDirRef();
618 // If this is a user search directory, check if the framework has been
619 // user-specified as a system framework.
620 if (getDirCharacteristic() == SrcMgr::C_User) {
621 SmallString<1024> SystemFrameworkMarker(FrameworkName);
622 SystemFrameworkMarker += ".system_framework";
623 if (llvm::sys::fs::exists(SystemFrameworkMarker)) {
624 CacheEntry.IsUserSpecifiedSystemFramework = true;
629 // Set out flags.
630 InUserSpecifiedSystemFramework = CacheEntry.IsUserSpecifiedSystemFramework;
631 IsFrameworkFound = CacheEntry.Directory.has_value();
633 if (RelativePath) {
634 RelativePath->clear();
635 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
638 // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"
639 unsigned OrigSize = FrameworkName.size();
641 FrameworkName += "Headers/";
643 if (SearchPath) {
644 SearchPath->clear();
645 // Without trailing '/'.
646 SearchPath->append(FrameworkName.begin(), FrameworkName.end()-1);
649 FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end());
651 auto File =
652 FileMgr.getOptionalFileRef(FrameworkName, /*OpenFile=*/!SuggestedModule);
653 if (!File) {
654 // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"
655 const char *Private = "Private";
656 FrameworkName.insert(FrameworkName.begin()+OrigSize, Private,
657 Private+strlen(Private));
658 if (SearchPath)
659 SearchPath->insert(SearchPath->begin()+OrigSize, Private,
660 Private+strlen(Private));
662 File = FileMgr.getOptionalFileRef(FrameworkName,
663 /*OpenFile=*/!SuggestedModule);
666 // If we found the header and are allowed to suggest a module, do so now.
667 if (File && needModuleLookup(RequestingModule, SuggestedModule)) {
668 // Find the framework in which this header occurs.
669 StringRef FrameworkPath = File->getFileEntry().getDir()->getName();
670 bool FoundFramework = false;
671 do {
672 // Determine whether this directory exists.
673 auto Dir = FileMgr.getDirectory(FrameworkPath);
674 if (!Dir)
675 break;
677 // If this is a framework directory, then we're a subframework of this
678 // framework.
679 if (llvm::sys::path::extension(FrameworkPath) == ".framework") {
680 FoundFramework = true;
681 break;
684 // Get the parent directory name.
685 FrameworkPath = llvm::sys::path::parent_path(FrameworkPath);
686 if (FrameworkPath.empty())
687 break;
688 } while (true);
690 bool IsSystem = getDirCharacteristic() != SrcMgr::C_User;
691 if (FoundFramework) {
692 if (!HS.findUsableModuleForFrameworkHeader(
693 &File->getFileEntry(), FrameworkPath, RequestingModule,
694 SuggestedModule, IsSystem))
695 return None;
696 } else {
697 if (!HS.findUsableModuleForHeader(&File->getFileEntry(), getDir(),
698 RequestingModule, SuggestedModule,
699 IsSystem))
700 return None;
703 if (File)
704 return *File;
705 return None;
708 void HeaderSearch::cacheLookupSuccess(LookupFileCacheInfo &CacheLookup,
709 ConstSearchDirIterator HitIt,
710 SourceLocation Loc) {
711 CacheLookup.HitIt = HitIt;
712 noteLookupUsage(HitIt.Idx, Loc);
715 void HeaderSearch::noteLookupUsage(unsigned HitIdx, SourceLocation Loc) {
716 SearchDirsUsage[HitIdx] = true;
718 auto UserEntryIdxIt = SearchDirToHSEntry.find(HitIdx);
719 if (UserEntryIdxIt != SearchDirToHSEntry.end())
720 Diags.Report(Loc, diag::remark_pp_search_path_usage)
721 << HSOpts->UserEntries[UserEntryIdxIt->second].Path;
724 void HeaderSearch::setTarget(const TargetInfo &Target) {
725 ModMap.setTarget(Target);
728 //===----------------------------------------------------------------------===//
729 // Header File Location.
730 //===----------------------------------------------------------------------===//
732 /// Return true with a diagnostic if the file that MSVC would have found
733 /// fails to match the one that Clang would have found with MSVC header search
734 /// disabled.
735 static bool checkMSVCHeaderSearch(DiagnosticsEngine &Diags,
736 const FileEntry *MSFE, const FileEntry *FE,
737 SourceLocation IncludeLoc) {
738 if (MSFE && FE != MSFE) {
739 Diags.Report(IncludeLoc, diag::ext_pp_include_search_ms) << MSFE->getName();
740 return true;
742 return false;
745 static const char *copyString(StringRef Str, llvm::BumpPtrAllocator &Alloc) {
746 assert(!Str.empty());
747 char *CopyStr = Alloc.Allocate<char>(Str.size()+1);
748 std::copy(Str.begin(), Str.end(), CopyStr);
749 CopyStr[Str.size()] = '\0';
750 return CopyStr;
753 static bool isFrameworkStylePath(StringRef Path, bool &IsPrivateHeader,
754 SmallVectorImpl<char> &FrameworkName,
755 SmallVectorImpl<char> &IncludeSpelling) {
756 using namespace llvm::sys;
757 path::const_iterator I = path::begin(Path);
758 path::const_iterator E = path::end(Path);
759 IsPrivateHeader = false;
761 // Detect different types of framework style paths:
763 // ...Foo.framework/{Headers,PrivateHeaders}
764 // ...Foo.framework/Versions/{A,Current}/{Headers,PrivateHeaders}
765 // ...Foo.framework/Frameworks/Nested.framework/{Headers,PrivateHeaders}
766 // ...<other variations with 'Versions' like in the above path>
768 // and some other variations among these lines.
769 int FoundComp = 0;
770 while (I != E) {
771 if (*I == "Headers") {
772 ++FoundComp;
773 } else if (*I == "PrivateHeaders") {
774 ++FoundComp;
775 IsPrivateHeader = true;
776 } else if (I->endswith(".framework")) {
777 StringRef Name = I->drop_back(10); // Drop .framework
778 // Need to reset the strings and counter to support nested frameworks.
779 FrameworkName.clear();
780 FrameworkName.append(Name.begin(), Name.end());
781 IncludeSpelling.clear();
782 IncludeSpelling.append(Name.begin(), Name.end());
783 FoundComp = 1;
784 } else if (FoundComp >= 2) {
785 IncludeSpelling.push_back('/');
786 IncludeSpelling.append(I->begin(), I->end());
788 ++I;
791 return !FrameworkName.empty() && FoundComp >= 2;
794 static void
795 diagnoseFrameworkInclude(DiagnosticsEngine &Diags, SourceLocation IncludeLoc,
796 StringRef Includer, StringRef IncludeFilename,
797 const FileEntry *IncludeFE, bool isAngled = false,
798 bool FoundByHeaderMap = false) {
799 bool IsIncluderPrivateHeader = false;
800 SmallString<128> FromFramework, ToFramework;
801 SmallString<128> FromIncludeSpelling, ToIncludeSpelling;
802 if (!isFrameworkStylePath(Includer, IsIncluderPrivateHeader, FromFramework,
803 FromIncludeSpelling))
804 return;
805 bool IsIncludeePrivateHeader = false;
806 bool IsIncludeeInFramework =
807 isFrameworkStylePath(IncludeFE->getName(), IsIncludeePrivateHeader,
808 ToFramework, ToIncludeSpelling);
810 if (!isAngled && !FoundByHeaderMap) {
811 SmallString<128> NewInclude("<");
812 if (IsIncludeeInFramework) {
813 NewInclude += ToIncludeSpelling;
814 NewInclude += ">";
815 } else {
816 NewInclude += IncludeFilename;
817 NewInclude += ">";
819 Diags.Report(IncludeLoc, diag::warn_quoted_include_in_framework_header)
820 << IncludeFilename
821 << FixItHint::CreateReplacement(IncludeLoc, NewInclude);
824 // Headers in Foo.framework/Headers should not include headers
825 // from Foo.framework/PrivateHeaders, since this violates public/private
826 // API boundaries and can cause modular dependency cycles.
827 if (!IsIncluderPrivateHeader && IsIncludeeInFramework &&
828 IsIncludeePrivateHeader && FromFramework == ToFramework)
829 Diags.Report(IncludeLoc, diag::warn_framework_include_private_from_public)
830 << IncludeFilename;
833 /// LookupFile - Given a "foo" or \<foo> reference, look up the indicated file,
834 /// return null on failure. isAngled indicates whether the file reference is
835 /// for system \#include's or not (i.e. using <> instead of ""). Includers, if
836 /// non-empty, indicates where the \#including file(s) are, in case a relative
837 /// search is needed. Microsoft mode will pass all \#including files.
838 Optional<FileEntryRef> HeaderSearch::LookupFile(
839 StringRef Filename, SourceLocation IncludeLoc, bool isAngled,
840 ConstSearchDirIterator FromDir, ConstSearchDirIterator *CurDirArg,
841 ArrayRef<std::pair<const FileEntry *, const DirectoryEntry *>> Includers,
842 SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
843 Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule,
844 bool *IsMapped, bool *IsFrameworkFound, bool SkipCache,
845 bool BuildSystemModule, bool OpenFile, bool CacheFailures) {
846 ConstSearchDirIterator CurDirLocal = nullptr;
847 ConstSearchDirIterator &CurDir = CurDirArg ? *CurDirArg : CurDirLocal;
849 if (IsMapped)
850 *IsMapped = false;
852 if (IsFrameworkFound)
853 *IsFrameworkFound = false;
855 if (SuggestedModule)
856 *SuggestedModule = ModuleMap::KnownHeader();
858 // If 'Filename' is absolute, check to see if it exists and no searching.
859 if (llvm::sys::path::is_absolute(Filename)) {
860 CurDir = nullptr;
862 // If this was an #include_next "/absolute/file", fail.
863 if (FromDir)
864 return None;
866 if (SearchPath)
867 SearchPath->clear();
868 if (RelativePath) {
869 RelativePath->clear();
870 RelativePath->append(Filename.begin(), Filename.end());
872 // Otherwise, just return the file.
873 return getFileAndSuggestModule(Filename, IncludeLoc, nullptr,
874 /*IsSystemHeaderDir*/ false,
875 RequestingModule, SuggestedModule, OpenFile,
876 CacheFailures);
879 // This is the header that MSVC's header search would have found.
880 ModuleMap::KnownHeader MSSuggestedModule;
881 Optional<FileEntryRef> MSFE;
883 // Unless disabled, check to see if the file is in the #includer's
884 // directory. This cannot be based on CurDir, because each includer could be
885 // a #include of a subdirectory (#include "foo/bar.h") and a subsequent
886 // include of "baz.h" should resolve to "whatever/foo/baz.h".
887 // This search is not done for <> headers.
888 if (!Includers.empty() && !isAngled && !NoCurDirSearch) {
889 SmallString<1024> TmpDir;
890 bool First = true;
891 for (const auto &IncluderAndDir : Includers) {
892 const FileEntry *Includer = IncluderAndDir.first;
894 // Concatenate the requested file onto the directory.
895 // FIXME: Portability. Filename concatenation should be in sys::Path.
896 TmpDir = IncluderAndDir.second->getName();
897 TmpDir.push_back('/');
898 TmpDir.append(Filename.begin(), Filename.end());
900 // FIXME: We don't cache the result of getFileInfo across the call to
901 // getFileAndSuggestModule, because it's a reference to an element of
902 // a container that could be reallocated across this call.
904 // If we have no includer, that means we're processing a #include
905 // from a module build. We should treat this as a system header if we're
906 // building a [system] module.
907 bool IncluderIsSystemHeader =
908 Includer ? getFileInfo(Includer).DirInfo != SrcMgr::C_User :
909 BuildSystemModule;
910 if (Optional<FileEntryRef> FE = getFileAndSuggestModule(
911 TmpDir, IncludeLoc, IncluderAndDir.second, IncluderIsSystemHeader,
912 RequestingModule, SuggestedModule)) {
913 if (!Includer) {
914 assert(First && "only first includer can have no file");
915 return FE;
918 // Leave CurDir unset.
919 // This file is a system header or C++ unfriendly if the old file is.
921 // Note that we only use one of FromHFI/ToHFI at once, due to potential
922 // reallocation of the underlying vector potentially making the first
923 // reference binding dangling.
924 HeaderFileInfo &FromHFI = getFileInfo(Includer);
925 unsigned DirInfo = FromHFI.DirInfo;
926 bool IndexHeaderMapHeader = FromHFI.IndexHeaderMapHeader;
927 StringRef Framework = FromHFI.Framework;
929 HeaderFileInfo &ToHFI = getFileInfo(&FE->getFileEntry());
930 ToHFI.DirInfo = DirInfo;
931 ToHFI.IndexHeaderMapHeader = IndexHeaderMapHeader;
932 ToHFI.Framework = Framework;
934 if (SearchPath) {
935 StringRef SearchPathRef(IncluderAndDir.second->getName());
936 SearchPath->clear();
937 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
939 if (RelativePath) {
940 RelativePath->clear();
941 RelativePath->append(Filename.begin(), Filename.end());
943 if (First) {
944 diagnoseFrameworkInclude(Diags, IncludeLoc,
945 IncluderAndDir.second->getName(), Filename,
946 &FE->getFileEntry());
947 return FE;
950 // Otherwise, we found the path via MSVC header search rules. If
951 // -Wmsvc-include is enabled, we have to keep searching to see if we
952 // would've found this header in -I or -isystem directories.
953 if (Diags.isIgnored(diag::ext_pp_include_search_ms, IncludeLoc)) {
954 return FE;
955 } else {
956 MSFE = FE;
957 if (SuggestedModule) {
958 MSSuggestedModule = *SuggestedModule;
959 *SuggestedModule = ModuleMap::KnownHeader();
961 break;
964 First = false;
968 CurDir = nullptr;
970 // If this is a system #include, ignore the user #include locs.
971 ConstSearchDirIterator It =
972 isAngled ? angled_dir_begin() : search_dir_begin();
974 // If this is a #include_next request, start searching after the directory the
975 // file was found in.
976 if (FromDir)
977 It = FromDir;
979 // Cache all of the lookups performed by this method. Many headers are
980 // multiply included, and the "pragma once" optimization prevents them from
981 // being relex/pp'd, but they would still have to search through a
982 // (potentially huge) series of SearchDirs to find it.
983 LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename];
985 ConstSearchDirIterator NextIt = std::next(It);
987 // If the entry has been previously looked up, the first value will be
988 // non-zero. If the value is equal to i (the start point of our search), then
989 // this is a matching hit.
990 if (!SkipCache && CacheLookup.StartIt == NextIt) {
991 // Skip querying potentially lots of directories for this lookup.
992 if (CacheLookup.HitIt)
993 It = CacheLookup.HitIt;
994 if (CacheLookup.MappedName) {
995 Filename = CacheLookup.MappedName;
996 if (IsMapped)
997 *IsMapped = true;
999 } else {
1000 // Otherwise, this is the first query, or the previous query didn't match
1001 // our search start. We will fill in our found location below, so prime the
1002 // start point value.
1003 CacheLookup.reset(/*NewStartIt=*/NextIt);
1006 SmallString<64> MappedName;
1008 // Check each directory in sequence to see if it contains this file.
1009 for (; It != search_dir_end(); ++It) {
1010 bool InUserSpecifiedSystemFramework = false;
1011 bool IsInHeaderMap = false;
1012 bool IsFrameworkFoundInDir = false;
1013 Optional<FileEntryRef> File = It->LookupFile(
1014 Filename, *this, IncludeLoc, SearchPath, RelativePath, RequestingModule,
1015 SuggestedModule, InUserSpecifiedSystemFramework, IsFrameworkFoundInDir,
1016 IsInHeaderMap, MappedName, OpenFile);
1017 if (!MappedName.empty()) {
1018 assert(IsInHeaderMap && "MappedName should come from a header map");
1019 CacheLookup.MappedName =
1020 copyString(MappedName, LookupFileCache.getAllocator());
1022 if (IsMapped)
1023 // A filename is mapped when a header map remapped it to a relative path
1024 // used in subsequent header search or to an absolute path pointing to an
1025 // existing file.
1026 *IsMapped |= (!MappedName.empty() || (IsInHeaderMap && File));
1027 if (IsFrameworkFound)
1028 // Because we keep a filename remapped for subsequent search directory
1029 // lookups, ignore IsFrameworkFoundInDir after the first remapping and not
1030 // just for remapping in a current search directory.
1031 *IsFrameworkFound |= (IsFrameworkFoundInDir && !CacheLookup.MappedName);
1032 if (!File)
1033 continue;
1035 CurDir = It;
1037 const auto FE = &File->getFileEntry();
1038 IncludeNames[FE] = Filename;
1040 // This file is a system header or C++ unfriendly if the dir is.
1041 HeaderFileInfo &HFI = getFileInfo(FE);
1042 HFI.DirInfo = CurDir->getDirCharacteristic();
1044 // If the directory characteristic is User but this framework was
1045 // user-specified to be treated as a system framework, promote the
1046 // characteristic.
1047 if (HFI.DirInfo == SrcMgr::C_User && InUserSpecifiedSystemFramework)
1048 HFI.DirInfo = SrcMgr::C_System;
1050 // If the filename matches a known system header prefix, override
1051 // whether the file is a system header.
1052 for (unsigned j = SystemHeaderPrefixes.size(); j; --j) {
1053 if (Filename.startswith(SystemHeaderPrefixes[j-1].first)) {
1054 HFI.DirInfo = SystemHeaderPrefixes[j-1].second ? SrcMgr::C_System
1055 : SrcMgr::C_User;
1056 break;
1060 // Set the `Framework` info if this file is in a header map with framework
1061 // style include spelling or found in a framework dir. The header map case
1062 // is possible when building frameworks which use header maps.
1063 if (CurDir->isHeaderMap() && isAngled) {
1064 size_t SlashPos = Filename.find('/');
1065 if (SlashPos != StringRef::npos)
1066 HFI.Framework =
1067 getUniqueFrameworkName(StringRef(Filename.begin(), SlashPos));
1068 if (CurDir->isIndexHeaderMap())
1069 HFI.IndexHeaderMapHeader = 1;
1070 } else if (CurDir->isFramework()) {
1071 size_t SlashPos = Filename.find('/');
1072 if (SlashPos != StringRef::npos)
1073 HFI.Framework =
1074 getUniqueFrameworkName(StringRef(Filename.begin(), SlashPos));
1077 if (checkMSVCHeaderSearch(Diags, MSFE ? &MSFE->getFileEntry() : nullptr,
1078 &File->getFileEntry(), IncludeLoc)) {
1079 if (SuggestedModule)
1080 *SuggestedModule = MSSuggestedModule;
1081 return MSFE;
1084 bool FoundByHeaderMap = !IsMapped ? false : *IsMapped;
1085 if (!Includers.empty())
1086 diagnoseFrameworkInclude(
1087 Diags, IncludeLoc, Includers.front().second->getName(), Filename,
1088 &File->getFileEntry(), isAngled, FoundByHeaderMap);
1090 // Remember this location for the next lookup we do.
1091 cacheLookupSuccess(CacheLookup, It, IncludeLoc);
1092 return File;
1095 // If we are including a file with a quoted include "foo.h" from inside
1096 // a header in a framework that is currently being built, and we couldn't
1097 // resolve "foo.h" any other way, change the include to <Foo/foo.h>, where
1098 // "Foo" is the name of the framework in which the including header was found.
1099 if (!Includers.empty() && Includers.front().first && !isAngled &&
1100 !Filename.contains('/')) {
1101 HeaderFileInfo &IncludingHFI = getFileInfo(Includers.front().first);
1102 if (IncludingHFI.IndexHeaderMapHeader) {
1103 SmallString<128> ScratchFilename;
1104 ScratchFilename += IncludingHFI.Framework;
1105 ScratchFilename += '/';
1106 ScratchFilename += Filename;
1108 Optional<FileEntryRef> File = LookupFile(
1109 ScratchFilename, IncludeLoc, /*isAngled=*/true, FromDir, &CurDir,
1110 Includers.front(), SearchPath, RelativePath, RequestingModule,
1111 SuggestedModule, IsMapped, /*IsFrameworkFound=*/nullptr);
1113 if (checkMSVCHeaderSearch(Diags, MSFE ? &MSFE->getFileEntry() : nullptr,
1114 File ? &File->getFileEntry() : nullptr,
1115 IncludeLoc)) {
1116 if (SuggestedModule)
1117 *SuggestedModule = MSSuggestedModule;
1118 return MSFE;
1121 cacheLookupSuccess(LookupFileCache[Filename],
1122 LookupFileCache[ScratchFilename].HitIt, IncludeLoc);
1123 // FIXME: SuggestedModule.
1124 return File;
1128 if (checkMSVCHeaderSearch(Diags, MSFE ? &MSFE->getFileEntry() : nullptr,
1129 nullptr, IncludeLoc)) {
1130 if (SuggestedModule)
1131 *SuggestedModule = MSSuggestedModule;
1132 return MSFE;
1135 // Otherwise, didn't find it. Remember we didn't find this.
1136 CacheLookup.HitIt = search_dir_end();
1137 return None;
1140 /// LookupSubframeworkHeader - Look up a subframework for the specified
1141 /// \#include file. For example, if \#include'ing <HIToolbox/HIToolbox.h> from
1142 /// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
1143 /// is a subframework within Carbon.framework. If so, return the FileEntry
1144 /// for the designated file, otherwise return null.
1145 Optional<FileEntryRef> HeaderSearch::LookupSubframeworkHeader(
1146 StringRef Filename, const FileEntry *ContextFileEnt,
1147 SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
1148 Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule) {
1149 assert(ContextFileEnt && "No context file?");
1151 // Framework names must have a '/' in the filename. Find it.
1152 // FIXME: Should we permit '\' on Windows?
1153 size_t SlashPos = Filename.find('/');
1154 if (SlashPos == StringRef::npos)
1155 return None;
1157 // Look up the base framework name of the ContextFileEnt.
1158 StringRef ContextName = ContextFileEnt->getName();
1160 // If the context info wasn't a framework, couldn't be a subframework.
1161 const unsigned DotFrameworkLen = 10;
1162 auto FrameworkPos = ContextName.find(".framework");
1163 if (FrameworkPos == StringRef::npos ||
1164 (ContextName[FrameworkPos + DotFrameworkLen] != '/' &&
1165 ContextName[FrameworkPos + DotFrameworkLen] != '\\'))
1166 return None;
1168 SmallString<1024> FrameworkName(ContextName.data(), ContextName.data() +
1169 FrameworkPos +
1170 DotFrameworkLen + 1);
1172 // Append Frameworks/HIToolbox.framework/
1173 FrameworkName += "Frameworks/";
1174 FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos);
1175 FrameworkName += ".framework/";
1177 auto &CacheLookup =
1178 *FrameworkMap.insert(std::make_pair(Filename.substr(0, SlashPos),
1179 FrameworkCacheEntry())).first;
1181 // Some other location?
1182 if (CacheLookup.second.Directory &&
1183 CacheLookup.first().size() == FrameworkName.size() &&
1184 memcmp(CacheLookup.first().data(), &FrameworkName[0],
1185 CacheLookup.first().size()) != 0)
1186 return None;
1188 // Cache subframework.
1189 if (!CacheLookup.second.Directory) {
1190 ++NumSubFrameworkLookups;
1192 // If the framework dir doesn't exist, we fail.
1193 auto Dir = FileMgr.getOptionalDirectoryRef(FrameworkName);
1194 if (!Dir)
1195 return None;
1197 // Otherwise, if it does, remember that this is the right direntry for this
1198 // framework.
1199 CacheLookup.second.Directory = Dir;
1203 if (RelativePath) {
1204 RelativePath->clear();
1205 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
1208 // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
1209 SmallString<1024> HeadersFilename(FrameworkName);
1210 HeadersFilename += "Headers/";
1211 if (SearchPath) {
1212 SearchPath->clear();
1213 // Without trailing '/'.
1214 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
1217 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
1218 auto File = FileMgr.getOptionalFileRef(HeadersFilename, /*OpenFile=*/true);
1219 if (!File) {
1220 // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
1221 HeadersFilename = FrameworkName;
1222 HeadersFilename += "PrivateHeaders/";
1223 if (SearchPath) {
1224 SearchPath->clear();
1225 // Without trailing '/'.
1226 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
1229 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
1230 File = FileMgr.getOptionalFileRef(HeadersFilename, /*OpenFile=*/true);
1232 if (!File)
1233 return None;
1236 // This file is a system header or C++ unfriendly if the old file is.
1238 // Note that the temporary 'DirInfo' is required here, as either call to
1239 // getFileInfo could resize the vector and we don't want to rely on order
1240 // of evaluation.
1241 unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo;
1242 getFileInfo(&File->getFileEntry()).DirInfo = DirInfo;
1244 FrameworkName.pop_back(); // remove the trailing '/'
1245 if (!findUsableModuleForFrameworkHeader(&File->getFileEntry(), FrameworkName,
1246 RequestingModule, SuggestedModule,
1247 /*IsSystem*/ false))
1248 return None;
1250 return *File;
1253 //===----------------------------------------------------------------------===//
1254 // File Info Management.
1255 //===----------------------------------------------------------------------===//
1257 /// Merge the header file info provided by \p OtherHFI into the current
1258 /// header file info (\p HFI)
1259 static void mergeHeaderFileInfo(HeaderFileInfo &HFI,
1260 const HeaderFileInfo &OtherHFI) {
1261 assert(OtherHFI.External && "expected to merge external HFI");
1263 HFI.isImport |= OtherHFI.isImport;
1264 HFI.isPragmaOnce |= OtherHFI.isPragmaOnce;
1265 HFI.isModuleHeader |= OtherHFI.isModuleHeader;
1267 if (!HFI.ControllingMacro && !HFI.ControllingMacroID) {
1268 HFI.ControllingMacro = OtherHFI.ControllingMacro;
1269 HFI.ControllingMacroID = OtherHFI.ControllingMacroID;
1272 HFI.DirInfo = OtherHFI.DirInfo;
1273 HFI.External = (!HFI.IsValid || HFI.External);
1274 HFI.IsValid = true;
1275 HFI.IndexHeaderMapHeader = OtherHFI.IndexHeaderMapHeader;
1277 if (HFI.Framework.empty())
1278 HFI.Framework = OtherHFI.Framework;
1281 /// getFileInfo - Return the HeaderFileInfo structure for the specified
1282 /// FileEntry.
1283 HeaderFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) {
1284 if (FE->getUID() >= FileInfo.size())
1285 FileInfo.resize(FE->getUID() + 1);
1287 HeaderFileInfo *HFI = &FileInfo[FE->getUID()];
1288 // FIXME: Use a generation count to check whether this is really up to date.
1289 if (ExternalSource && !HFI->Resolved) {
1290 auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE);
1291 if (ExternalHFI.IsValid) {
1292 HFI->Resolved = true;
1293 if (ExternalHFI.External)
1294 mergeHeaderFileInfo(*HFI, ExternalHFI);
1298 HFI->IsValid = true;
1299 // We have local information about this header file, so it's no longer
1300 // strictly external.
1301 HFI->External = false;
1302 return *HFI;
1305 const HeaderFileInfo *
1306 HeaderSearch::getExistingFileInfo(const FileEntry *FE,
1307 bool WantExternal) const {
1308 // If we have an external source, ensure we have the latest information.
1309 // FIXME: Use a generation count to check whether this is really up to date.
1310 HeaderFileInfo *HFI;
1311 if (ExternalSource) {
1312 if (FE->getUID() >= FileInfo.size()) {
1313 if (!WantExternal)
1314 return nullptr;
1315 FileInfo.resize(FE->getUID() + 1);
1318 HFI = &FileInfo[FE->getUID()];
1319 if (!WantExternal && (!HFI->IsValid || HFI->External))
1320 return nullptr;
1321 if (!HFI->Resolved) {
1322 auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE);
1323 if (ExternalHFI.IsValid) {
1324 HFI->Resolved = true;
1325 if (ExternalHFI.External)
1326 mergeHeaderFileInfo(*HFI, ExternalHFI);
1329 } else if (FE->getUID() >= FileInfo.size()) {
1330 return nullptr;
1331 } else {
1332 HFI = &FileInfo[FE->getUID()];
1335 if (!HFI->IsValid || (HFI->External && !WantExternal))
1336 return nullptr;
1338 return HFI;
1341 bool HeaderSearch::isFileMultipleIncludeGuarded(const FileEntry *File) {
1342 // Check if we've entered this file and found an include guard or #pragma
1343 // once. Note that we dor't check for #import, because that's not a property
1344 // of the file itself.
1345 if (auto *HFI = getExistingFileInfo(File))
1346 return HFI->isPragmaOnce || HFI->ControllingMacro ||
1347 HFI->ControllingMacroID;
1348 return false;
1351 void HeaderSearch::MarkFileModuleHeader(const FileEntry *FE,
1352 ModuleMap::ModuleHeaderRole Role,
1353 bool isCompilingModuleHeader) {
1354 bool isModularHeader = !(Role & ModuleMap::TextualHeader);
1356 // Don't mark the file info as non-external if there's nothing to change.
1357 if (!isCompilingModuleHeader) {
1358 if (!isModularHeader)
1359 return;
1360 auto *HFI = getExistingFileInfo(FE);
1361 if (HFI && HFI->isModuleHeader)
1362 return;
1365 auto &HFI = getFileInfo(FE);
1366 HFI.isModuleHeader |= isModularHeader;
1367 HFI.isCompilingModuleHeader |= isCompilingModuleHeader;
1370 bool HeaderSearch::ShouldEnterIncludeFile(Preprocessor &PP,
1371 const FileEntry *File, bool isImport,
1372 bool ModulesEnabled, Module *M,
1373 bool &IsFirstIncludeOfFile) {
1374 ++NumIncluded; // Count # of attempted #includes.
1376 IsFirstIncludeOfFile = false;
1378 // Get information about this file.
1379 HeaderFileInfo &FileInfo = getFileInfo(File);
1381 // FIXME: this is a workaround for the lack of proper modules-aware support
1382 // for #import / #pragma once
1383 auto TryEnterImported = [&]() -> bool {
1384 if (!ModulesEnabled)
1385 return false;
1386 // Ensure FileInfo bits are up to date.
1387 ModMap.resolveHeaderDirectives(File);
1388 // Modules with builtins are special; multiple modules use builtins as
1389 // modular headers, example:
1391 // module stddef { header "stddef.h" export * }
1393 // After module map parsing, this expands to:
1395 // module stddef {
1396 // header "/path_to_builtin_dirs/stddef.h"
1397 // textual "stddef.h"
1398 // }
1400 // It's common that libc++ and system modules will both define such
1401 // submodules. Make sure cached results for a builtin header won't
1402 // prevent other builtin modules from potentially entering the builtin
1403 // header. Note that builtins are header guarded and the decision to
1404 // actually enter them is postponed to the controlling macros logic below.
1405 bool TryEnterHdr = false;
1406 if (FileInfo.isCompilingModuleHeader && FileInfo.isModuleHeader)
1407 TryEnterHdr = ModMap.isBuiltinHeader(File);
1409 // Textual headers can be #imported from different modules. Since ObjC
1410 // headers find in the wild might rely only on #import and do not contain
1411 // controlling macros, be conservative and only try to enter textual headers
1412 // if such macro is present.
1413 if (!FileInfo.isModuleHeader &&
1414 FileInfo.getControllingMacro(ExternalLookup))
1415 TryEnterHdr = true;
1416 return TryEnterHdr;
1419 // If this is a #import directive, check that we have not already imported
1420 // this header.
1421 if (isImport) {
1422 // If this has already been imported, don't import it again.
1423 FileInfo.isImport = true;
1425 // Has this already been #import'ed or #include'd?
1426 if (PP.alreadyIncluded(File) && !TryEnterImported())
1427 return false;
1428 } else {
1429 // Otherwise, if this is a #include of a file that was previously #import'd
1430 // or if this is the second #include of a #pragma once file, ignore it.
1431 if ((FileInfo.isPragmaOnce || FileInfo.isImport) && !TryEnterImported())
1432 return false;
1435 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
1436 // if the macro that guards it is defined, we know the #include has no effect.
1437 if (const IdentifierInfo *ControllingMacro
1438 = FileInfo.getControllingMacro(ExternalLookup)) {
1439 // If the header corresponds to a module, check whether the macro is already
1440 // defined in that module rather than checking in the current set of visible
1441 // modules.
1442 if (M ? PP.isMacroDefinedInLocalModule(ControllingMacro, M)
1443 : PP.isMacroDefined(ControllingMacro)) {
1444 ++NumMultiIncludeFileOptzn;
1445 return false;
1449 IsFirstIncludeOfFile = PP.markIncluded(File);
1451 return true;
1454 size_t HeaderSearch::getTotalMemory() const {
1455 return SearchDirs.capacity()
1456 + llvm::capacity_in_bytes(FileInfo)
1457 + llvm::capacity_in_bytes(HeaderMaps)
1458 + LookupFileCache.getAllocator().getTotalMemory()
1459 + FrameworkMap.getAllocator().getTotalMemory();
1462 unsigned HeaderSearch::searchDirIdx(const DirectoryLookup &DL) const {
1463 return &DL - &*SearchDirs.begin();
1466 StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) {
1467 return FrameworkNames.insert(Framework).first->first();
1470 StringRef HeaderSearch::getIncludeNameForHeader(const FileEntry *File) const {
1471 auto It = IncludeNames.find(File);
1472 if (It == IncludeNames.end())
1473 return {};
1474 return It->second;
1477 bool HeaderSearch::hasModuleMap(StringRef FileName,
1478 const DirectoryEntry *Root,
1479 bool IsSystem) {
1480 if (!HSOpts->ImplicitModuleMaps)
1481 return false;
1483 SmallVector<const DirectoryEntry *, 2> FixUpDirectories;
1485 StringRef DirName = FileName;
1486 do {
1487 // Get the parent directory name.
1488 DirName = llvm::sys::path::parent_path(DirName);
1489 if (DirName.empty())
1490 return false;
1492 // Determine whether this directory exists.
1493 auto Dir = FileMgr.getOptionalDirectoryRef(DirName);
1494 if (!Dir)
1495 return false;
1497 // Try to load the module map file in this directory.
1498 switch (loadModuleMapFile(*Dir, IsSystem,
1499 llvm::sys::path::extension(Dir->getName()) ==
1500 ".framework")) {
1501 case LMM_NewlyLoaded:
1502 case LMM_AlreadyLoaded:
1503 // Success. All of the directories we stepped through inherit this module
1504 // map file.
1505 for (unsigned I = 0, N = FixUpDirectories.size(); I != N; ++I)
1506 DirectoryHasModuleMap[FixUpDirectories[I]] = true;
1507 return true;
1509 case LMM_NoDirectory:
1510 case LMM_InvalidModuleMap:
1511 break;
1514 // If we hit the top of our search, we're done.
1515 if (*Dir == Root)
1516 return false;
1518 // Keep track of all of the directories we checked, so we can mark them as
1519 // having module maps if we eventually do find a module map.
1520 FixUpDirectories.push_back(*Dir);
1521 } while (true);
1524 ModuleMap::KnownHeader
1525 HeaderSearch::findModuleForHeader(const FileEntry *File,
1526 bool AllowTextual) const {
1527 if (ExternalSource) {
1528 // Make sure the external source has handled header info about this file,
1529 // which includes whether the file is part of a module.
1530 (void)getExistingFileInfo(File);
1532 return ModMap.findModuleForHeader(File, AllowTextual);
1535 ArrayRef<ModuleMap::KnownHeader>
1536 HeaderSearch::findAllModulesForHeader(const FileEntry *File) const {
1537 if (ExternalSource) {
1538 // Make sure the external source has handled header info about this file,
1539 // which includes whether the file is part of a module.
1540 (void)getExistingFileInfo(File);
1542 return ModMap.findAllModulesForHeader(File);
1545 static bool suggestModule(HeaderSearch &HS, const FileEntry *File,
1546 Module *RequestingModule,
1547 ModuleMap::KnownHeader *SuggestedModule) {
1548 ModuleMap::KnownHeader Module =
1549 HS.findModuleForHeader(File, /*AllowTextual*/true);
1551 // If this module specifies [no_undeclared_includes], we cannot find any
1552 // file that's in a non-dependency module.
1553 if (RequestingModule && Module && RequestingModule->NoUndeclaredIncludes) {
1554 HS.getModuleMap().resolveUses(RequestingModule, /*Complain*/ false);
1555 if (!RequestingModule->directlyUses(Module.getModule())) {
1556 // Builtin headers are a special case. Multiple modules can use the same
1557 // builtin as a modular header (see also comment in
1558 // ShouldEnterIncludeFile()), so the builtin header may have been
1559 // "claimed" by an unrelated module. This shouldn't prevent us from
1560 // including the builtin header textually in this module.
1561 if (HS.getModuleMap().isBuiltinHeader(File)) {
1562 if (SuggestedModule)
1563 *SuggestedModule = ModuleMap::KnownHeader();
1564 return true;
1566 return false;
1570 if (SuggestedModule)
1571 *SuggestedModule = (Module.getRole() & ModuleMap::TextualHeader)
1572 ? ModuleMap::KnownHeader()
1573 : Module;
1575 return true;
1578 bool HeaderSearch::findUsableModuleForHeader(
1579 const FileEntry *File, const DirectoryEntry *Root, Module *RequestingModule,
1580 ModuleMap::KnownHeader *SuggestedModule, bool IsSystemHeaderDir) {
1581 if (File && needModuleLookup(RequestingModule, SuggestedModule)) {
1582 // If there is a module that corresponds to this header, suggest it.
1583 hasModuleMap(File->getName(), Root, IsSystemHeaderDir);
1584 return suggestModule(*this, File, RequestingModule, SuggestedModule);
1586 return true;
1589 bool HeaderSearch::findUsableModuleForFrameworkHeader(
1590 const FileEntry *File, StringRef FrameworkName, Module *RequestingModule,
1591 ModuleMap::KnownHeader *SuggestedModule, bool IsSystemFramework) {
1592 // If we're supposed to suggest a module, look for one now.
1593 if (needModuleLookup(RequestingModule, SuggestedModule)) {
1594 // Find the top-level framework based on this framework.
1595 SmallVector<std::string, 4> SubmodulePath;
1596 Optional<DirectoryEntryRef> TopFrameworkDir =
1597 ::getTopFrameworkDir(FileMgr, FrameworkName, SubmodulePath);
1598 assert(TopFrameworkDir && "Could not find the top-most framework dir");
1600 // Determine the name of the top-level framework.
1601 StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
1603 // Load this framework module. If that succeeds, find the suggested module
1604 // for this header, if any.
1605 loadFrameworkModule(ModuleName, *TopFrameworkDir, IsSystemFramework);
1607 // FIXME: This can find a module not part of ModuleName, which is
1608 // important so that we're consistent about whether this header
1609 // corresponds to a module. Possibly we should lock down framework modules
1610 // so that this is not possible.
1611 return suggestModule(*this, File, RequestingModule, SuggestedModule);
1613 return true;
1616 static const FileEntry *getPrivateModuleMap(const FileEntry *File,
1617 FileManager &FileMgr) {
1618 StringRef Filename = llvm::sys::path::filename(File->getName());
1619 SmallString<128> PrivateFilename(File->getDir()->getName());
1620 if (Filename == "module.map")
1621 llvm::sys::path::append(PrivateFilename, "module_private.map");
1622 else if (Filename == "module.modulemap")
1623 llvm::sys::path::append(PrivateFilename, "module.private.modulemap");
1624 else
1625 return nullptr;
1626 if (auto File = FileMgr.getFile(PrivateFilename))
1627 return *File;
1628 return nullptr;
1631 bool HeaderSearch::loadModuleMapFile(const FileEntry *File, bool IsSystem,
1632 FileID ID, unsigned *Offset,
1633 StringRef OriginalModuleMapFile) {
1634 // Find the directory for the module. For frameworks, that may require going
1635 // up from the 'Modules' directory.
1636 Optional<DirectoryEntryRef> Dir;
1637 if (getHeaderSearchOpts().ModuleMapFileHomeIsCwd) {
1638 Dir = FileMgr.getOptionalDirectoryRef(".");
1639 } else {
1640 if (!OriginalModuleMapFile.empty()) {
1641 // We're building a preprocessed module map. Find or invent the directory
1642 // that it originally occupied.
1643 Dir = FileMgr.getOptionalDirectoryRef(
1644 llvm::sys::path::parent_path(OriginalModuleMapFile));
1645 if (!Dir) {
1646 auto FakeFile = FileMgr.getVirtualFileRef(OriginalModuleMapFile, 0, 0);
1647 Dir = FakeFile.getDir();
1649 } else {
1650 // TODO: Replace with `Dir = File.getDir()` when `File` is switched to
1651 // `FileEntryRef`.
1652 Dir = FileMgr.getOptionalDirectoryRef(File->getDir()->getName());
1655 assert(Dir && "parent must exist");
1656 StringRef DirName(Dir->getName());
1657 if (llvm::sys::path::filename(DirName) == "Modules") {
1658 DirName = llvm::sys::path::parent_path(DirName);
1659 if (DirName.endswith(".framework"))
1660 if (auto MaybeDir = FileMgr.getOptionalDirectoryRef(DirName))
1661 Dir = *MaybeDir;
1662 // FIXME: This assert can fail if there's a race between the above check
1663 // and the removal of the directory.
1664 assert(Dir && "parent must exist");
1668 assert(Dir && "module map home directory must exist");
1669 switch (loadModuleMapFileImpl(File, IsSystem, *Dir, ID, Offset)) {
1670 case LMM_AlreadyLoaded:
1671 case LMM_NewlyLoaded:
1672 return false;
1673 case LMM_NoDirectory:
1674 case LMM_InvalidModuleMap:
1675 return true;
1677 llvm_unreachable("Unknown load module map result");
1680 HeaderSearch::LoadModuleMapResult
1681 HeaderSearch::loadModuleMapFileImpl(const FileEntry *File, bool IsSystem,
1682 DirectoryEntryRef Dir, FileID ID,
1683 unsigned *Offset) {
1684 assert(File && "expected FileEntry");
1686 // Check whether we've already loaded this module map, and mark it as being
1687 // loaded in case we recursively try to load it from itself.
1688 auto AddResult = LoadedModuleMaps.insert(std::make_pair(File, true));
1689 if (!AddResult.second)
1690 return AddResult.first->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
1692 if (ModMap.parseModuleMapFile(File, IsSystem, Dir, ID, Offset)) {
1693 LoadedModuleMaps[File] = false;
1694 return LMM_InvalidModuleMap;
1697 // Try to load a corresponding private module map.
1698 if (const FileEntry *PMMFile = getPrivateModuleMap(File, FileMgr)) {
1699 if (ModMap.parseModuleMapFile(PMMFile, IsSystem, Dir)) {
1700 LoadedModuleMaps[File] = false;
1701 return LMM_InvalidModuleMap;
1705 // This directory has a module map.
1706 return LMM_NewlyLoaded;
1709 const FileEntry *
1710 HeaderSearch::lookupModuleMapFile(const DirectoryEntry *Dir, bool IsFramework) {
1711 if (!HSOpts->ImplicitModuleMaps)
1712 return nullptr;
1713 // For frameworks, the preferred spelling is Modules/module.modulemap, but
1714 // module.map at the framework root is also accepted.
1715 SmallString<128> ModuleMapFileName(Dir->getName());
1716 if (IsFramework)
1717 llvm::sys::path::append(ModuleMapFileName, "Modules");
1718 llvm::sys::path::append(ModuleMapFileName, "module.modulemap");
1719 if (auto F = FileMgr.getFile(ModuleMapFileName))
1720 return *F;
1722 // Continue to allow module.map
1723 ModuleMapFileName = Dir->getName();
1724 llvm::sys::path::append(ModuleMapFileName, "module.map");
1725 if (auto F = FileMgr.getFile(ModuleMapFileName))
1726 return *F;
1728 // For frameworks, allow to have a private module map with a preferred
1729 // spelling when a public module map is absent.
1730 if (IsFramework) {
1731 ModuleMapFileName = Dir->getName();
1732 llvm::sys::path::append(ModuleMapFileName, "Modules",
1733 "module.private.modulemap");
1734 if (auto F = FileMgr.getFile(ModuleMapFileName))
1735 return *F;
1737 return nullptr;
1740 Module *HeaderSearch::loadFrameworkModule(StringRef Name, DirectoryEntryRef Dir,
1741 bool IsSystem) {
1742 if (Module *Module = ModMap.findModule(Name))
1743 return Module;
1745 // Try to load a module map file.
1746 switch (loadModuleMapFile(Dir, IsSystem, /*IsFramework*/true)) {
1747 case LMM_InvalidModuleMap:
1748 // Try to infer a module map from the framework directory.
1749 if (HSOpts->ImplicitModuleMaps)
1750 ModMap.inferFrameworkModule(Dir, IsSystem, /*Parent=*/nullptr);
1751 break;
1753 case LMM_AlreadyLoaded:
1754 case LMM_NoDirectory:
1755 return nullptr;
1757 case LMM_NewlyLoaded:
1758 break;
1761 return ModMap.findModule(Name);
1764 HeaderSearch::LoadModuleMapResult
1765 HeaderSearch::loadModuleMapFile(StringRef DirName, bool IsSystem,
1766 bool IsFramework) {
1767 if (auto Dir = FileMgr.getOptionalDirectoryRef(DirName))
1768 return loadModuleMapFile(*Dir, IsSystem, IsFramework);
1770 return LMM_NoDirectory;
1773 HeaderSearch::LoadModuleMapResult
1774 HeaderSearch::loadModuleMapFile(DirectoryEntryRef Dir, bool IsSystem,
1775 bool IsFramework) {
1776 auto KnownDir = DirectoryHasModuleMap.find(Dir);
1777 if (KnownDir != DirectoryHasModuleMap.end())
1778 return KnownDir->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
1780 if (const FileEntry *ModuleMapFile = lookupModuleMapFile(Dir, IsFramework)) {
1781 LoadModuleMapResult Result =
1782 loadModuleMapFileImpl(ModuleMapFile, IsSystem, Dir);
1783 // Add Dir explicitly in case ModuleMapFile is in a subdirectory.
1784 // E.g. Foo.framework/Modules/module.modulemap
1785 // ^Dir ^ModuleMapFile
1786 if (Result == LMM_NewlyLoaded)
1787 DirectoryHasModuleMap[Dir] = true;
1788 else if (Result == LMM_InvalidModuleMap)
1789 DirectoryHasModuleMap[Dir] = false;
1790 return Result;
1792 return LMM_InvalidModuleMap;
1795 void HeaderSearch::collectAllModules(SmallVectorImpl<Module *> &Modules) {
1796 Modules.clear();
1798 if (HSOpts->ImplicitModuleMaps) {
1799 // Load module maps for each of the header search directories.
1800 for (DirectoryLookup &DL : search_dir_range()) {
1801 bool IsSystem = DL.isSystemHeaderDirectory();
1802 if (DL.isFramework()) {
1803 std::error_code EC;
1804 SmallString<128> DirNative;
1805 llvm::sys::path::native(DL.getFrameworkDir()->getName(), DirNative);
1807 // Search each of the ".framework" directories to load them as modules.
1808 llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
1809 for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC),
1810 DirEnd;
1811 Dir != DirEnd && !EC; Dir.increment(EC)) {
1812 if (llvm::sys::path::extension(Dir->path()) != ".framework")
1813 continue;
1815 auto FrameworkDir = FileMgr.getOptionalDirectoryRef(Dir->path());
1816 if (!FrameworkDir)
1817 continue;
1819 // Load this framework module.
1820 loadFrameworkModule(llvm::sys::path::stem(Dir->path()), *FrameworkDir,
1821 IsSystem);
1823 continue;
1826 // FIXME: Deal with header maps.
1827 if (DL.isHeaderMap())
1828 continue;
1830 // Try to load a module map file for the search directory.
1831 loadModuleMapFile(*DL.getDirRef(), IsSystem, /*IsFramework*/ false);
1833 // Try to load module map files for immediate subdirectories of this
1834 // search directory.
1835 loadSubdirectoryModuleMaps(DL);
1839 // Populate the list of modules.
1840 llvm::transform(ModMap.modules(), std::back_inserter(Modules),
1841 [](const auto &NameAndMod) { return NameAndMod.second; });
1844 void HeaderSearch::loadTopLevelSystemModules() {
1845 if (!HSOpts->ImplicitModuleMaps)
1846 return;
1848 // Load module maps for each of the header search directories.
1849 for (const DirectoryLookup &DL : search_dir_range()) {
1850 // We only care about normal header directories.
1851 if (!DL.isNormalDir())
1852 continue;
1854 // Try to load a module map file for the search directory.
1855 loadModuleMapFile(*DL.getDirRef(), DL.isSystemHeaderDirectory(),
1856 DL.isFramework());
1860 void HeaderSearch::loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir) {
1861 assert(HSOpts->ImplicitModuleMaps &&
1862 "Should not be loading subdirectory module maps");
1864 if (SearchDir.haveSearchedAllModuleMaps())
1865 return;
1867 std::error_code EC;
1868 SmallString<128> Dir = SearchDir.getDir()->getName();
1869 FileMgr.makeAbsolutePath(Dir);
1870 SmallString<128> DirNative;
1871 llvm::sys::path::native(Dir, DirNative);
1872 llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
1873 for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
1874 Dir != DirEnd && !EC; Dir.increment(EC)) {
1875 bool IsFramework = llvm::sys::path::extension(Dir->path()) == ".framework";
1876 if (IsFramework == SearchDir.isFramework())
1877 loadModuleMapFile(Dir->path(), SearchDir.isSystemHeaderDirectory(),
1878 SearchDir.isFramework());
1881 SearchDir.setSearchedAllModuleMaps(true);
1884 std::string HeaderSearch::suggestPathToFileForDiagnostics(
1885 const FileEntry *File, llvm::StringRef MainFile, bool *IsSystem) {
1886 // FIXME: We assume that the path name currently cached in the FileEntry is
1887 // the most appropriate one for this analysis (and that it's spelled the
1888 // same way as the corresponding header search path).
1889 return suggestPathToFileForDiagnostics(File->getName(), /*WorkingDir=*/"",
1890 MainFile, IsSystem);
1893 std::string HeaderSearch::suggestPathToFileForDiagnostics(
1894 llvm::StringRef File, llvm::StringRef WorkingDir, llvm::StringRef MainFile,
1895 bool *IsSystem) {
1896 using namespace llvm::sys;
1898 unsigned BestPrefixLength = 0;
1899 // Checks whether `Dir` is a strict path prefix of `File`. If so and that's
1900 // the longest prefix we've seen so for it, returns true and updates the
1901 // `BestPrefixLength` accordingly.
1902 auto CheckDir = [&](llvm::StringRef Dir) -> bool {
1903 llvm::SmallString<32> DirPath(Dir.begin(), Dir.end());
1904 if (!WorkingDir.empty() && !path::is_absolute(Dir))
1905 fs::make_absolute(WorkingDir, DirPath);
1906 path::remove_dots(DirPath, /*remove_dot_dot=*/true);
1907 Dir = DirPath;
1908 for (auto NI = path::begin(File), NE = path::end(File),
1909 DI = path::begin(Dir), DE = path::end(Dir);
1910 /*termination condition in loop*/; ++NI, ++DI) {
1911 // '.' components in File are ignored.
1912 while (NI != NE && *NI == ".")
1913 ++NI;
1914 if (NI == NE)
1915 break;
1917 // '.' components in Dir are ignored.
1918 while (DI != DE && *DI == ".")
1919 ++DI;
1920 if (DI == DE) {
1921 // Dir is a prefix of File, up to '.' components and choice of path
1922 // separators.
1923 unsigned PrefixLength = NI - path::begin(File);
1924 if (PrefixLength > BestPrefixLength) {
1925 BestPrefixLength = PrefixLength;
1926 return true;
1928 break;
1931 // Consider all path separators equal.
1932 if (NI->size() == 1 && DI->size() == 1 &&
1933 path::is_separator(NI->front()) && path::is_separator(DI->front()))
1934 continue;
1936 // Special case Apple .sdk folders since the search path is typically a
1937 // symlink like `iPhoneSimulator14.5.sdk` while the file is instead
1938 // located in `iPhoneSimulator.sdk` (the real folder).
1939 if (NI->endswith(".sdk") && DI->endswith(".sdk")) {
1940 StringRef NBasename = path::stem(*NI);
1941 StringRef DBasename = path::stem(*DI);
1942 if (DBasename.startswith(NBasename))
1943 continue;
1946 if (*NI != *DI)
1947 break;
1949 return false;
1952 bool BestPrefixIsFramework = false;
1953 for (const DirectoryLookup &DL : search_dir_range()) {
1954 if (DL.isNormalDir()) {
1955 StringRef Dir = DL.getDir()->getName();
1956 if (CheckDir(Dir)) {
1957 if (IsSystem)
1958 *IsSystem = BestPrefixLength && isSystem(DL.getDirCharacteristic());
1959 BestPrefixIsFramework = false;
1961 } else if (DL.isFramework()) {
1962 StringRef Dir = DL.getFrameworkDir()->getName();
1963 if (CheckDir(Dir)) {
1964 if (IsSystem)
1965 *IsSystem = BestPrefixLength && isSystem(DL.getDirCharacteristic());
1966 BestPrefixIsFramework = true;
1971 // Try to shorten include path using TUs directory, if we couldn't find any
1972 // suitable prefix in include search paths.
1973 if (!BestPrefixLength && CheckDir(path::parent_path(MainFile))) {
1974 if (IsSystem)
1975 *IsSystem = false;
1976 BestPrefixIsFramework = false;
1979 // Try resolving resulting filename via reverse search in header maps,
1980 // key from header name is user preferred name for the include file.
1981 StringRef Filename = File.drop_front(BestPrefixLength);
1982 for (const DirectoryLookup &DL : search_dir_range()) {
1983 if (!DL.isHeaderMap())
1984 continue;
1986 StringRef SpelledFilename =
1987 DL.getHeaderMap()->reverseLookupFilename(Filename);
1988 if (!SpelledFilename.empty()) {
1989 Filename = SpelledFilename;
1990 BestPrefixIsFramework = false;
1991 break;
1995 // If the best prefix is a framework path, we need to compute the proper
1996 // include spelling for the framework header.
1997 bool IsPrivateHeader;
1998 SmallString<128> FrameworkName, IncludeSpelling;
1999 if (BestPrefixIsFramework &&
2000 isFrameworkStylePath(Filename, IsPrivateHeader, FrameworkName,
2001 IncludeSpelling)) {
2002 Filename = IncludeSpelling;
2004 return path::convert_to_slash(Filename);