Path: blob/main/contrib/llvm-project/clang/lib/Lex/HeaderSearch.cpp
35233 views
//===- HeaderSearch.cpp - Resolve Header File Locations -------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file implements the DirectoryLookup and HeaderSearch interfaces.9//10//===----------------------------------------------------------------------===//1112#include "clang/Lex/HeaderSearch.h"13#include "clang/Basic/Diagnostic.h"14#include "clang/Basic/FileManager.h"15#include "clang/Basic/IdentifierTable.h"16#include "clang/Basic/Module.h"17#include "clang/Basic/SourceManager.h"18#include "clang/Lex/DirectoryLookup.h"19#include "clang/Lex/ExternalPreprocessorSource.h"20#include "clang/Lex/HeaderMap.h"21#include "clang/Lex/HeaderSearchOptions.h"22#include "clang/Lex/LexDiagnostic.h"23#include "clang/Lex/ModuleMap.h"24#include "clang/Lex/Preprocessor.h"25#include "llvm/ADT/APInt.h"26#include "llvm/ADT/Hashing.h"27#include "llvm/ADT/STLExtras.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/Support/Allocator.h"33#include "llvm/Support/Capacity.h"34#include "llvm/Support/Errc.h"35#include "llvm/Support/ErrorHandling.h"36#include "llvm/Support/FileSystem.h"37#include "llvm/Support/Path.h"38#include "llvm/Support/VirtualFileSystem.h"39#include "llvm/Support/xxhash.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>4849using namespace clang;5051#define DEBUG_TYPE "file-search"5253ALWAYS_ENABLED_STATISTIC(NumIncluded, "Number of attempted #includes.");54ALWAYS_ENABLED_STATISTIC(55NumMultiIncludeFileOptzn,56"Number of #includes skipped due to the multi-include optimization.");57ALWAYS_ENABLED_STATISTIC(NumFrameworkLookups, "Number of framework lookups.");58ALWAYS_ENABLED_STATISTIC(NumSubFrameworkLookups,59"Number of subframework lookups.");6061const IdentifierInfo *62HeaderFileInfo::getControllingMacro(ExternalPreprocessorSource *External) {63if (LazyControllingMacro.isID()) {64if (!External)65return nullptr;6667LazyControllingMacro =68External->GetIdentifier(LazyControllingMacro.getID());69return LazyControllingMacro.getPtr();70}7172IdentifierInfo *ControllingMacro = LazyControllingMacro.getPtr();73if (ControllingMacro && ControllingMacro->isOutOfDate()) {74assert(External && "We must have an external source if we have a "75"controlling macro that is out of date.");76External->updateOutOfDateIdentifier(*ControllingMacro);77}78return ControllingMacro;79}8081ExternalHeaderFileInfoSource::~ExternalHeaderFileInfoSource() = default;8283HeaderSearch::HeaderSearch(std::shared_ptr<HeaderSearchOptions> HSOpts,84SourceManager &SourceMgr, DiagnosticsEngine &Diags,85const LangOptions &LangOpts,86const TargetInfo *Target)87: HSOpts(std::move(HSOpts)), Diags(Diags),88FileMgr(SourceMgr.getFileManager()), FrameworkMap(64),89ModMap(SourceMgr, Diags, LangOpts, Target, *this) {}9091void HeaderSearch::PrintStats() {92llvm::errs() << "\n*** HeaderSearch Stats:\n"93<< FileInfo.size() << " files tracked.\n";94unsigned NumOnceOnlyFiles = 0;95for (unsigned i = 0, e = FileInfo.size(); i != e; ++i)96NumOnceOnlyFiles += (FileInfo[i].isPragmaOnce || FileInfo[i].isImport);97llvm::errs() << " " << NumOnceOnlyFiles << " #import/#pragma once files.\n";9899llvm::errs() << " " << NumIncluded << " #include/#include_next/#import.\n"100<< " " << NumMultiIncludeFileOptzn101<< " #includes skipped due to the multi-include optimization.\n";102103llvm::errs() << NumFrameworkLookups << " framework lookups.\n"104<< NumSubFrameworkLookups << " subframework lookups.\n";105}106107void HeaderSearch::SetSearchPaths(108std::vector<DirectoryLookup> dirs, unsigned int angledDirIdx,109unsigned int systemDirIdx,110llvm::DenseMap<unsigned int, unsigned int> searchDirToHSEntry) {111assert(angledDirIdx <= systemDirIdx && systemDirIdx <= dirs.size() &&112"Directory indices are unordered");113SearchDirs = std::move(dirs);114SearchDirsUsage.assign(SearchDirs.size(), false);115AngledDirIdx = angledDirIdx;116SystemDirIdx = systemDirIdx;117SearchDirToHSEntry = std::move(searchDirToHSEntry);118//LookupFileCache.clear();119indexInitialHeaderMaps();120}121122void HeaderSearch::AddSearchPath(const DirectoryLookup &dir, bool isAngled) {123unsigned idx = isAngled ? SystemDirIdx : AngledDirIdx;124SearchDirs.insert(SearchDirs.begin() + idx, dir);125SearchDirsUsage.insert(SearchDirsUsage.begin() + idx, false);126if (!isAngled)127AngledDirIdx++;128SystemDirIdx++;129}130131std::vector<bool> HeaderSearch::computeUserEntryUsage() const {132std::vector<bool> UserEntryUsage(HSOpts->UserEntries.size());133for (unsigned I = 0, E = SearchDirsUsage.size(); I < E; ++I) {134// Check whether this DirectoryLookup has been successfully used.135if (SearchDirsUsage[I]) {136auto UserEntryIdxIt = SearchDirToHSEntry.find(I);137// Check whether this DirectoryLookup maps to a HeaderSearch::UserEntry.138if (UserEntryIdxIt != SearchDirToHSEntry.end())139UserEntryUsage[UserEntryIdxIt->second] = true;140}141}142return UserEntryUsage;143}144145std::vector<bool> HeaderSearch::collectVFSUsageAndClear() const {146std::vector<bool> VFSUsage;147if (!getHeaderSearchOpts().ModulesIncludeVFSUsage)148return VFSUsage;149150llvm::vfs::FileSystem &RootFS = FileMgr.getVirtualFileSystem();151// TODO: This only works if the `RedirectingFileSystem`s were all created by152// `createVFSFromOverlayFiles`.153RootFS.visit([&](llvm::vfs::FileSystem &FS) {154if (auto *RFS = dyn_cast<llvm::vfs::RedirectingFileSystem>(&FS)) {155VFSUsage.push_back(RFS->hasBeenUsed());156RFS->clearHasBeenUsed();157}158});159assert(VFSUsage.size() == getHeaderSearchOpts().VFSOverlayFiles.size() &&160"A different number of RedirectingFileSystem's were present than "161"-ivfsoverlay options passed to Clang!");162// VFS visit order is the opposite of VFSOverlayFiles order.163std::reverse(VFSUsage.begin(), VFSUsage.end());164return VFSUsage;165}166167/// CreateHeaderMap - This method returns a HeaderMap for the specified168/// FileEntry, uniquing them through the 'HeaderMaps' datastructure.169const HeaderMap *HeaderSearch::CreateHeaderMap(FileEntryRef FE) {170// We expect the number of headermaps to be small, and almost always empty.171// If it ever grows, use of a linear search should be re-evaluated.172if (!HeaderMaps.empty()) {173for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)174// Pointer equality comparison of FileEntries works because they are175// already uniqued by inode.176if (HeaderMaps[i].first == FE)177return HeaderMaps[i].second.get();178}179180if (std::unique_ptr<HeaderMap> HM = HeaderMap::Create(FE, FileMgr)) {181HeaderMaps.emplace_back(FE, std::move(HM));182return HeaderMaps.back().second.get();183}184185return nullptr;186}187188/// Get filenames for all registered header maps.189void HeaderSearch::getHeaderMapFileNames(190SmallVectorImpl<std::string> &Names) const {191for (auto &HM : HeaderMaps)192Names.push_back(std::string(HM.first.getName()));193}194195std::string HeaderSearch::getCachedModuleFileName(Module *Module) {196OptionalFileEntryRef ModuleMap =197getModuleMap().getModuleMapFileForUniquing(Module);198// The ModuleMap maybe a nullptr, when we load a cached C++ module without199// *.modulemap file. In this case, just return an empty string.200if (!ModuleMap)201return {};202return getCachedModuleFileName(Module->Name, ModuleMap->getNameAsRequested());203}204205std::string HeaderSearch::getPrebuiltModuleFileName(StringRef ModuleName,206bool FileMapOnly) {207// First check the module name to pcm file map.208auto i(HSOpts->PrebuiltModuleFiles.find(ModuleName));209if (i != HSOpts->PrebuiltModuleFiles.end())210return i->second;211212if (FileMapOnly || HSOpts->PrebuiltModulePaths.empty())213return {};214215// Then go through each prebuilt module directory and try to find the pcm216// file.217for (const std::string &Dir : HSOpts->PrebuiltModulePaths) {218SmallString<256> Result(Dir);219llvm::sys::fs::make_absolute(Result);220if (ModuleName.contains(':'))221// The separator of C++20 modules partitions (':') is not good for file222// systems, here clang and gcc choose '-' by default since it is not a223// valid character of C++ indentifiers. So we could avoid conflicts.224llvm::sys::path::append(Result, ModuleName.split(':').first + "-" +225ModuleName.split(':').second +226".pcm");227else228llvm::sys::path::append(Result, ModuleName + ".pcm");229if (getFileMgr().getFile(Result.str()))230return std::string(Result);231}232233return {};234}235236std::string HeaderSearch::getPrebuiltImplicitModuleFileName(Module *Module) {237OptionalFileEntryRef ModuleMap =238getModuleMap().getModuleMapFileForUniquing(Module);239StringRef ModuleName = Module->Name;240StringRef ModuleMapPath = ModuleMap->getName();241StringRef ModuleCacheHash = HSOpts->DisableModuleHash ? "" : getModuleHash();242for (const std::string &Dir : HSOpts->PrebuiltModulePaths) {243SmallString<256> CachePath(Dir);244llvm::sys::fs::make_absolute(CachePath);245llvm::sys::path::append(CachePath, ModuleCacheHash);246std::string FileName =247getCachedModuleFileNameImpl(ModuleName, ModuleMapPath, CachePath);248if (!FileName.empty() && getFileMgr().getFile(FileName))249return FileName;250}251return {};252}253254std::string HeaderSearch::getCachedModuleFileName(StringRef ModuleName,255StringRef ModuleMapPath) {256return getCachedModuleFileNameImpl(ModuleName, ModuleMapPath,257getModuleCachePath());258}259260std::string HeaderSearch::getCachedModuleFileNameImpl(StringRef ModuleName,261StringRef ModuleMapPath,262StringRef CachePath) {263// If we don't have a module cache path or aren't supposed to use one, we264// can't do anything.265if (CachePath.empty())266return {};267268SmallString<256> Result(CachePath);269llvm::sys::fs::make_absolute(Result);270271if (HSOpts->DisableModuleHash) {272llvm::sys::path::append(Result, ModuleName + ".pcm");273} else {274// Construct the name <ModuleName>-<hash of ModuleMapPath>.pcm which should275// ideally be globally unique to this particular module. Name collisions276// in the hash are safe (because any translation unit can only import one277// module with each name), but result in a loss of caching.278//279// To avoid false-negatives, we form as canonical a path as we can, and map280// to lower-case in case we're on a case-insensitive file system.281SmallString<128> CanonicalPath(ModuleMapPath);282if (getModuleMap().canonicalizeModuleMapPath(CanonicalPath))283return {};284285auto Hash = llvm::xxh3_64bits(CanonicalPath.str().lower());286287SmallString<128> HashStr;288llvm::APInt(64, Hash).toStringUnsigned(HashStr, /*Radix*/36);289llvm::sys::path::append(Result, ModuleName + "-" + HashStr + ".pcm");290}291return Result.str().str();292}293294Module *HeaderSearch::lookupModule(StringRef ModuleName,295SourceLocation ImportLoc, bool AllowSearch,296bool AllowExtraModuleMapSearch) {297// Look in the module map to determine if there is a module by this name.298Module *Module = ModMap.findModule(ModuleName);299if (Module || !AllowSearch || !HSOpts->ImplicitModuleMaps)300return Module;301302StringRef SearchName = ModuleName;303Module = lookupModule(ModuleName, SearchName, ImportLoc,304AllowExtraModuleMapSearch);305306// The facility for "private modules" -- adjacent, optional module maps named307// module.private.modulemap that are supposed to define private submodules --308// may have different flavors of names: FooPrivate, Foo_Private and Foo.Private.309//310// Foo.Private is now deprecated in favor of Foo_Private. Users of FooPrivate311// should also rename to Foo_Private. Representing private as submodules312// could force building unwanted dependencies into the parent module and cause313// dependency cycles.314if (!Module && SearchName.consume_back("_Private"))315Module = lookupModule(ModuleName, SearchName, ImportLoc,316AllowExtraModuleMapSearch);317if (!Module && SearchName.consume_back("Private"))318Module = lookupModule(ModuleName, SearchName, ImportLoc,319AllowExtraModuleMapSearch);320return Module;321}322323Module *HeaderSearch::lookupModule(StringRef ModuleName, StringRef SearchName,324SourceLocation ImportLoc,325bool AllowExtraModuleMapSearch) {326Module *Module = nullptr;327328// Look through the various header search paths to load any available module329// maps, searching for a module map that describes this module.330for (DirectoryLookup &Dir : search_dir_range()) {331if (Dir.isFramework()) {332// Search for or infer a module map for a framework. Here we use333// SearchName rather than ModuleName, to permit finding private modules334// named FooPrivate in buggy frameworks named Foo.335SmallString<128> FrameworkDirName;336FrameworkDirName += Dir.getFrameworkDirRef()->getName();337llvm::sys::path::append(FrameworkDirName, SearchName + ".framework");338if (auto FrameworkDir =339FileMgr.getOptionalDirectoryRef(FrameworkDirName)) {340bool IsSystem = Dir.getDirCharacteristic() != SrcMgr::C_User;341Module = loadFrameworkModule(ModuleName, *FrameworkDir, IsSystem);342if (Module)343break;344}345}346347// FIXME: Figure out how header maps and module maps will work together.348349// Only deal with normal search directories.350if (!Dir.isNormalDir())351continue;352353bool IsSystem = Dir.isSystemHeaderDirectory();354// Only returns std::nullopt if not a normal directory, which we just355// checked356DirectoryEntryRef NormalDir = *Dir.getDirRef();357// Search for a module map file in this directory.358if (loadModuleMapFile(NormalDir, IsSystem,359/*IsFramework*/false) == LMM_NewlyLoaded) {360// We just loaded a module map file; check whether the module is361// available now.362Module = ModMap.findModule(ModuleName);363if (Module)364break;365}366367// Search for a module map in a subdirectory with the same name as the368// module.369SmallString<128> NestedModuleMapDirName;370NestedModuleMapDirName = Dir.getDirRef()->getName();371llvm::sys::path::append(NestedModuleMapDirName, ModuleName);372if (loadModuleMapFile(NestedModuleMapDirName, IsSystem,373/*IsFramework*/false) == LMM_NewlyLoaded){374// If we just loaded a module map file, look for the module again.375Module = ModMap.findModule(ModuleName);376if (Module)377break;378}379380// If we've already performed the exhaustive search for module maps in this381// search directory, don't do it again.382if (Dir.haveSearchedAllModuleMaps())383continue;384385// Load all module maps in the immediate subdirectories of this search386// directory if ModuleName was from @import.387if (AllowExtraModuleMapSearch)388loadSubdirectoryModuleMaps(Dir);389390// Look again for the module.391Module = ModMap.findModule(ModuleName);392if (Module)393break;394}395396return Module;397}398399void HeaderSearch::indexInitialHeaderMaps() {400llvm::StringMap<unsigned, llvm::BumpPtrAllocator> Index(SearchDirs.size());401402// Iterate over all filename keys and associate them with the index i.403for (unsigned i = 0; i != SearchDirs.size(); ++i) {404auto &Dir = SearchDirs[i];405406// We're concerned with only the initial contiguous run of header407// maps within SearchDirs, which can be 99% of SearchDirs when408// SearchDirs.size() is ~10000.409if (!Dir.isHeaderMap()) {410SearchDirHeaderMapIndex = std::move(Index);411FirstNonHeaderMapSearchDirIdx = i;412break;413}414415// Give earlier keys precedence over identical later keys.416auto Callback = [&](StringRef Filename) {417Index.try_emplace(Filename.lower(), i);418};419Dir.getHeaderMap()->forEachKey(Callback);420}421}422423//===----------------------------------------------------------------------===//424// File lookup within a DirectoryLookup scope425//===----------------------------------------------------------------------===//426427/// getName - Return the directory or filename corresponding to this lookup428/// object.429StringRef DirectoryLookup::getName() const {430if (isNormalDir())431return getDirRef()->getName();432if (isFramework())433return getFrameworkDirRef()->getName();434assert(isHeaderMap() && "Unknown DirectoryLookup");435return getHeaderMap()->getFileName();436}437438OptionalFileEntryRef HeaderSearch::getFileAndSuggestModule(439StringRef FileName, SourceLocation IncludeLoc, const DirectoryEntry *Dir,440bool IsSystemHeaderDir, Module *RequestingModule,441ModuleMap::KnownHeader *SuggestedModule, bool OpenFile /*=true*/,442bool CacheFailures /*=true*/) {443// If we have a module map that might map this header, load it and444// check whether we'll have a suggestion for a module.445auto File = getFileMgr().getFileRef(FileName, OpenFile, CacheFailures);446if (!File) {447// For rare, surprising errors (e.g. "out of file handles"), diag the EC448// message.449std::error_code EC = llvm::errorToErrorCode(File.takeError());450if (EC != llvm::errc::no_such_file_or_directory &&451EC != llvm::errc::invalid_argument &&452EC != llvm::errc::is_a_directory && EC != llvm::errc::not_a_directory) {453Diags.Report(IncludeLoc, diag::err_cannot_open_file)454<< FileName << EC.message();455}456return std::nullopt;457}458459// If there is a module that corresponds to this header, suggest it.460if (!findUsableModuleForHeader(461*File, Dir ? Dir : File->getFileEntry().getDir(), RequestingModule,462SuggestedModule, IsSystemHeaderDir))463return std::nullopt;464465return *File;466}467468/// LookupFile - Lookup the specified file in this search path, returning it469/// if it exists or returning null if not.470OptionalFileEntryRef DirectoryLookup::LookupFile(471StringRef &Filename, HeaderSearch &HS, SourceLocation IncludeLoc,472SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,473Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule,474bool &InUserSpecifiedSystemFramework, bool &IsFrameworkFound,475bool &IsInHeaderMap, SmallVectorImpl<char> &MappedName,476bool OpenFile) const {477InUserSpecifiedSystemFramework = false;478IsInHeaderMap = false;479MappedName.clear();480481SmallString<1024> TmpDir;482if (isNormalDir()) {483// Concatenate the requested file onto the directory.484TmpDir = getDirRef()->getName();485llvm::sys::path::append(TmpDir, Filename);486if (SearchPath) {487StringRef SearchPathRef(getDirRef()->getName());488SearchPath->clear();489SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());490}491if (RelativePath) {492RelativePath->clear();493RelativePath->append(Filename.begin(), Filename.end());494}495496return HS.getFileAndSuggestModule(497TmpDir, IncludeLoc, getDir(), isSystemHeaderDirectory(),498RequestingModule, SuggestedModule, OpenFile);499}500501if (isFramework())502return DoFrameworkLookup(Filename, HS, SearchPath, RelativePath,503RequestingModule, SuggestedModule,504InUserSpecifiedSystemFramework, IsFrameworkFound);505506assert(isHeaderMap() && "Unknown directory lookup");507const HeaderMap *HM = getHeaderMap();508SmallString<1024> Path;509StringRef Dest = HM->lookupFilename(Filename, Path);510if (Dest.empty())511return std::nullopt;512513IsInHeaderMap = true;514515auto FixupSearchPathAndFindUsableModule =516[&](FileEntryRef File) -> OptionalFileEntryRef {517if (SearchPath) {518StringRef SearchPathRef(getName());519SearchPath->clear();520SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());521}522if (RelativePath) {523RelativePath->clear();524RelativePath->append(Filename.begin(), Filename.end());525}526if (!HS.findUsableModuleForHeader(File, File.getFileEntry().getDir(),527RequestingModule, SuggestedModule,528isSystemHeaderDirectory())) {529return std::nullopt;530}531return File;532};533534// Check if the headermap maps the filename to a framework include535// ("Foo.h" -> "Foo/Foo.h"), in which case continue header lookup using the536// framework include.537if (llvm::sys::path::is_relative(Dest)) {538MappedName.append(Dest.begin(), Dest.end());539Filename = StringRef(MappedName.begin(), MappedName.size());540Dest = HM->lookupFilename(Filename, Path);541}542543if (auto Res = HS.getFileMgr().getOptionalFileRef(Dest, OpenFile)) {544return FixupSearchPathAndFindUsableModule(*Res);545}546547// Header maps need to be marked as used whenever the filename matches.548// The case where the target file **exists** is handled by callee of this549// function as part of the regular logic that applies to include search paths.550// The case where the target file **does not exist** is handled here:551HS.noteLookupUsage(HS.searchDirIdx(*this), IncludeLoc);552return std::nullopt;553}554555/// Given a framework directory, find the top-most framework directory.556///557/// \param FileMgr The file manager to use for directory lookups.558/// \param DirName The name of the framework directory.559/// \param SubmodulePath Will be populated with the submodule path from the560/// returned top-level module to the originally named framework.561static OptionalDirectoryEntryRef562getTopFrameworkDir(FileManager &FileMgr, StringRef DirName,563SmallVectorImpl<std::string> &SubmodulePath) {564assert(llvm::sys::path::extension(DirName) == ".framework" &&565"Not a framework directory");566567// Note: as an egregious but useful hack we use the real path here, because568// frameworks moving between top-level frameworks to embedded frameworks tend569// to be symlinked, and we base the logical structure of modules on the570// physical layout. In particular, we need to deal with crazy includes like571//572// #include <Foo/Frameworks/Bar.framework/Headers/Wibble.h>573//574// where 'Bar' used to be embedded in 'Foo', is now a top-level framework575// which one should access with, e.g.,576//577// #include <Bar/Wibble.h>578//579// Similar issues occur when a top-level framework has moved into an580// embedded framework.581auto TopFrameworkDir = FileMgr.getOptionalDirectoryRef(DirName);582583if (TopFrameworkDir)584DirName = FileMgr.getCanonicalName(*TopFrameworkDir);585do {586// Get the parent directory name.587DirName = llvm::sys::path::parent_path(DirName);588if (DirName.empty())589break;590591// Determine whether this directory exists.592auto Dir = FileMgr.getOptionalDirectoryRef(DirName);593if (!Dir)594break;595596// If this is a framework directory, then we're a subframework of this597// framework.598if (llvm::sys::path::extension(DirName) == ".framework") {599SubmodulePath.push_back(std::string(llvm::sys::path::stem(DirName)));600TopFrameworkDir = *Dir;601}602} while (true);603604return TopFrameworkDir;605}606607static bool needModuleLookup(Module *RequestingModule,608bool HasSuggestedModule) {609return HasSuggestedModule ||610(RequestingModule && RequestingModule->NoUndeclaredIncludes);611}612613/// DoFrameworkLookup - Do a lookup of the specified file in the current614/// DirectoryLookup, which is a framework directory.615OptionalFileEntryRef DirectoryLookup::DoFrameworkLookup(616StringRef Filename, HeaderSearch &HS, SmallVectorImpl<char> *SearchPath,617SmallVectorImpl<char> *RelativePath, Module *RequestingModule,618ModuleMap::KnownHeader *SuggestedModule,619bool &InUserSpecifiedSystemFramework, bool &IsFrameworkFound) const {620FileManager &FileMgr = HS.getFileMgr();621622// Framework names must have a '/' in the filename.623size_t SlashPos = Filename.find('/');624if (SlashPos == StringRef::npos)625return std::nullopt;626627// Find out if this is the home for the specified framework, by checking628// HeaderSearch. Possible answers are yes/no and unknown.629FrameworkCacheEntry &CacheEntry =630HS.LookupFrameworkCache(Filename.substr(0, SlashPos));631632// If it is known and in some other directory, fail.633if (CacheEntry.Directory && CacheEntry.Directory != getFrameworkDirRef())634return std::nullopt;635636// Otherwise, construct the path to this framework dir.637638// FrameworkName = "/System/Library/Frameworks/"639SmallString<1024> FrameworkName;640FrameworkName += getFrameworkDirRef()->getName();641if (FrameworkName.empty() || FrameworkName.back() != '/')642FrameworkName.push_back('/');643644// FrameworkName = "/System/Library/Frameworks/Cocoa"645StringRef ModuleName(Filename.begin(), SlashPos);646FrameworkName += ModuleName;647648// FrameworkName = "/System/Library/Frameworks/Cocoa.framework/"649FrameworkName += ".framework/";650651// If the cache entry was unresolved, populate it now.652if (!CacheEntry.Directory) {653++NumFrameworkLookups;654655// If the framework dir doesn't exist, we fail.656auto Dir = FileMgr.getDirectory(FrameworkName);657if (!Dir)658return std::nullopt;659660// Otherwise, if it does, remember that this is the right direntry for this661// framework.662CacheEntry.Directory = getFrameworkDirRef();663664// If this is a user search directory, check if the framework has been665// user-specified as a system framework.666if (getDirCharacteristic() == SrcMgr::C_User) {667SmallString<1024> SystemFrameworkMarker(FrameworkName);668SystemFrameworkMarker += ".system_framework";669if (llvm::sys::fs::exists(SystemFrameworkMarker)) {670CacheEntry.IsUserSpecifiedSystemFramework = true;671}672}673}674675// Set out flags.676InUserSpecifiedSystemFramework = CacheEntry.IsUserSpecifiedSystemFramework;677IsFrameworkFound = CacheEntry.Directory.has_value();678679if (RelativePath) {680RelativePath->clear();681RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());682}683684// Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"685unsigned OrigSize = FrameworkName.size();686687FrameworkName += "Headers/";688689if (SearchPath) {690SearchPath->clear();691// Without trailing '/'.692SearchPath->append(FrameworkName.begin(), FrameworkName.end()-1);693}694695FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end());696697auto File =698FileMgr.getOptionalFileRef(FrameworkName, /*OpenFile=*/!SuggestedModule);699if (!File) {700// Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"701const char *Private = "Private";702FrameworkName.insert(FrameworkName.begin()+OrigSize, Private,703Private+strlen(Private));704if (SearchPath)705SearchPath->insert(SearchPath->begin()+OrigSize, Private,706Private+strlen(Private));707708File = FileMgr.getOptionalFileRef(FrameworkName,709/*OpenFile=*/!SuggestedModule);710}711712// If we found the header and are allowed to suggest a module, do so now.713if (File && needModuleLookup(RequestingModule, SuggestedModule)) {714// Find the framework in which this header occurs.715StringRef FrameworkPath = File->getDir().getName();716bool FoundFramework = false;717do {718// Determine whether this directory exists.719auto Dir = FileMgr.getDirectory(FrameworkPath);720if (!Dir)721break;722723// If this is a framework directory, then we're a subframework of this724// framework.725if (llvm::sys::path::extension(FrameworkPath) == ".framework") {726FoundFramework = true;727break;728}729730// Get the parent directory name.731FrameworkPath = llvm::sys::path::parent_path(FrameworkPath);732if (FrameworkPath.empty())733break;734} while (true);735736bool IsSystem = getDirCharacteristic() != SrcMgr::C_User;737if (FoundFramework) {738if (!HS.findUsableModuleForFrameworkHeader(*File, FrameworkPath,739RequestingModule,740SuggestedModule, IsSystem))741return std::nullopt;742} else {743if (!HS.findUsableModuleForHeader(*File, getDir(), RequestingModule,744SuggestedModule, IsSystem))745return std::nullopt;746}747}748if (File)749return *File;750return std::nullopt;751}752753void HeaderSearch::cacheLookupSuccess(LookupFileCacheInfo &CacheLookup,754ConstSearchDirIterator HitIt,755SourceLocation Loc) {756CacheLookup.HitIt = HitIt;757noteLookupUsage(HitIt.Idx, Loc);758}759760void HeaderSearch::noteLookupUsage(unsigned HitIdx, SourceLocation Loc) {761SearchDirsUsage[HitIdx] = true;762763auto UserEntryIdxIt = SearchDirToHSEntry.find(HitIdx);764if (UserEntryIdxIt != SearchDirToHSEntry.end())765Diags.Report(Loc, diag::remark_pp_search_path_usage)766<< HSOpts->UserEntries[UserEntryIdxIt->second].Path;767}768769void HeaderSearch::setTarget(const TargetInfo &Target) {770ModMap.setTarget(Target);771}772773//===----------------------------------------------------------------------===//774// Header File Location.775//===----------------------------------------------------------------------===//776777/// Return true with a diagnostic if the file that MSVC would have found778/// fails to match the one that Clang would have found with MSVC header search779/// disabled.780static bool checkMSVCHeaderSearch(DiagnosticsEngine &Diags,781OptionalFileEntryRef MSFE,782const FileEntry *FE,783SourceLocation IncludeLoc) {784if (MSFE && FE != *MSFE) {785Diags.Report(IncludeLoc, diag::ext_pp_include_search_ms) << MSFE->getName();786return true;787}788return false;789}790791static const char *copyString(StringRef Str, llvm::BumpPtrAllocator &Alloc) {792assert(!Str.empty());793char *CopyStr = Alloc.Allocate<char>(Str.size()+1);794std::copy(Str.begin(), Str.end(), CopyStr);795CopyStr[Str.size()] = '\0';796return CopyStr;797}798799static bool isFrameworkStylePath(StringRef Path, bool &IsPrivateHeader,800SmallVectorImpl<char> &FrameworkName,801SmallVectorImpl<char> &IncludeSpelling) {802using namespace llvm::sys;803path::const_iterator I = path::begin(Path);804path::const_iterator E = path::end(Path);805IsPrivateHeader = false;806807// Detect different types of framework style paths:808//809// ...Foo.framework/{Headers,PrivateHeaders}810// ...Foo.framework/Versions/{A,Current}/{Headers,PrivateHeaders}811// ...Foo.framework/Frameworks/Nested.framework/{Headers,PrivateHeaders}812// ...<other variations with 'Versions' like in the above path>813//814// and some other variations among these lines.815int FoundComp = 0;816while (I != E) {817if (*I == "Headers") {818++FoundComp;819} else if (*I == "PrivateHeaders") {820++FoundComp;821IsPrivateHeader = true;822} else if (I->ends_with(".framework")) {823StringRef Name = I->drop_back(10); // Drop .framework824// Need to reset the strings and counter to support nested frameworks.825FrameworkName.clear();826FrameworkName.append(Name.begin(), Name.end());827IncludeSpelling.clear();828IncludeSpelling.append(Name.begin(), Name.end());829FoundComp = 1;830} else if (FoundComp >= 2) {831IncludeSpelling.push_back('/');832IncludeSpelling.append(I->begin(), I->end());833}834++I;835}836837return !FrameworkName.empty() && FoundComp >= 2;838}839840static void841diagnoseFrameworkInclude(DiagnosticsEngine &Diags, SourceLocation IncludeLoc,842StringRef Includer, StringRef IncludeFilename,843FileEntryRef IncludeFE, bool isAngled = false,844bool FoundByHeaderMap = false) {845bool IsIncluderPrivateHeader = false;846SmallString<128> FromFramework, ToFramework;847SmallString<128> FromIncludeSpelling, ToIncludeSpelling;848if (!isFrameworkStylePath(Includer, IsIncluderPrivateHeader, FromFramework,849FromIncludeSpelling))850return;851bool IsIncludeePrivateHeader = false;852bool IsIncludeeInFramework =853isFrameworkStylePath(IncludeFE.getName(), IsIncludeePrivateHeader,854ToFramework, ToIncludeSpelling);855856if (!isAngled && !FoundByHeaderMap) {857SmallString<128> NewInclude("<");858if (IsIncludeeInFramework) {859NewInclude += ToIncludeSpelling;860NewInclude += ">";861} else {862NewInclude += IncludeFilename;863NewInclude += ">";864}865Diags.Report(IncludeLoc, diag::warn_quoted_include_in_framework_header)866<< IncludeFilename867<< FixItHint::CreateReplacement(IncludeLoc, NewInclude);868}869870// Headers in Foo.framework/Headers should not include headers871// from Foo.framework/PrivateHeaders, since this violates public/private872// API boundaries and can cause modular dependency cycles.873if (!IsIncluderPrivateHeader && IsIncludeeInFramework &&874IsIncludeePrivateHeader && FromFramework == ToFramework)875Diags.Report(IncludeLoc, diag::warn_framework_include_private_from_public)876<< IncludeFilename;877}878879/// LookupFile - Given a "foo" or \<foo> reference, look up the indicated file,880/// return null on failure. isAngled indicates whether the file reference is881/// for system \#include's or not (i.e. using <> instead of ""). Includers, if882/// non-empty, indicates where the \#including file(s) are, in case a relative883/// search is needed. Microsoft mode will pass all \#including files.884OptionalFileEntryRef HeaderSearch::LookupFile(885StringRef Filename, SourceLocation IncludeLoc, bool isAngled,886ConstSearchDirIterator FromDir, ConstSearchDirIterator *CurDirArg,887ArrayRef<std::pair<OptionalFileEntryRef, DirectoryEntryRef>> Includers,888SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,889Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule,890bool *IsMapped, bool *IsFrameworkFound, bool SkipCache,891bool BuildSystemModule, bool OpenFile, bool CacheFailures) {892ConstSearchDirIterator CurDirLocal = nullptr;893ConstSearchDirIterator &CurDir = CurDirArg ? *CurDirArg : CurDirLocal;894895if (IsMapped)896*IsMapped = false;897898if (IsFrameworkFound)899*IsFrameworkFound = false;900901if (SuggestedModule)902*SuggestedModule = ModuleMap::KnownHeader();903904// If 'Filename' is absolute, check to see if it exists and no searching.905if (llvm::sys::path::is_absolute(Filename)) {906CurDir = nullptr;907908// If this was an #include_next "/absolute/file", fail.909if (FromDir)910return std::nullopt;911912if (SearchPath)913SearchPath->clear();914if (RelativePath) {915RelativePath->clear();916RelativePath->append(Filename.begin(), Filename.end());917}918// Otherwise, just return the file.919return getFileAndSuggestModule(Filename, IncludeLoc, nullptr,920/*IsSystemHeaderDir*/ false,921RequestingModule, SuggestedModule, OpenFile,922CacheFailures);923}924925// This is the header that MSVC's header search would have found.926ModuleMap::KnownHeader MSSuggestedModule;927OptionalFileEntryRef MSFE;928929// Check to see if the file is in the #includer's directory. This cannot be930// based on CurDir, because each includer could be a #include of a931// subdirectory (#include "foo/bar.h") and a subsequent include of "baz.h"932// should resolve to "whatever/foo/baz.h". This search is not done for <>933// headers.934if (!Includers.empty() && !isAngled) {935SmallString<1024> TmpDir;936bool First = true;937for (const auto &IncluderAndDir : Includers) {938OptionalFileEntryRef Includer = IncluderAndDir.first;939940// Concatenate the requested file onto the directory.941TmpDir = IncluderAndDir.second.getName();942llvm::sys::path::append(TmpDir, Filename);943944// FIXME: We don't cache the result of getFileInfo across the call to945// getFileAndSuggestModule, because it's a reference to an element of946// a container that could be reallocated across this call.947//948// If we have no includer, that means we're processing a #include949// from a module build. We should treat this as a system header if we're950// building a [system] module.951bool IncluderIsSystemHeader = [&]() {952if (!Includer)953return BuildSystemModule;954const HeaderFileInfo *HFI = getExistingFileInfo(*Includer);955assert(HFI && "includer without file info");956return HFI->DirInfo != SrcMgr::C_User;957}();958if (OptionalFileEntryRef FE = getFileAndSuggestModule(959TmpDir, IncludeLoc, IncluderAndDir.second, IncluderIsSystemHeader,960RequestingModule, SuggestedModule)) {961if (!Includer) {962assert(First && "only first includer can have no file");963return FE;964}965966// Leave CurDir unset.967// This file is a system header or C++ unfriendly if the old file is.968//969// Note that we only use one of FromHFI/ToHFI at once, due to potential970// reallocation of the underlying vector potentially making the first971// reference binding dangling.972const HeaderFileInfo *FromHFI = getExistingFileInfo(*Includer);973assert(FromHFI && "includer without file info");974unsigned DirInfo = FromHFI->DirInfo;975bool IndexHeaderMapHeader = FromHFI->IndexHeaderMapHeader;976StringRef Framework = FromHFI->Framework;977978HeaderFileInfo &ToHFI = getFileInfo(*FE);979ToHFI.DirInfo = DirInfo;980ToHFI.IndexHeaderMapHeader = IndexHeaderMapHeader;981ToHFI.Framework = Framework;982983if (SearchPath) {984StringRef SearchPathRef(IncluderAndDir.second.getName());985SearchPath->clear();986SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());987}988if (RelativePath) {989RelativePath->clear();990RelativePath->append(Filename.begin(), Filename.end());991}992if (First) {993diagnoseFrameworkInclude(Diags, IncludeLoc,994IncluderAndDir.second.getName(), Filename,995*FE);996return FE;997}998999// Otherwise, we found the path via MSVC header search rules. If1000// -Wmsvc-include is enabled, we have to keep searching to see if we1001// would've found this header in -I or -isystem directories.1002if (Diags.isIgnored(diag::ext_pp_include_search_ms, IncludeLoc)) {1003return FE;1004} else {1005MSFE = FE;1006if (SuggestedModule) {1007MSSuggestedModule = *SuggestedModule;1008*SuggestedModule = ModuleMap::KnownHeader();1009}1010break;1011}1012}1013First = false;1014}1015}10161017CurDir = nullptr;10181019// If this is a system #include, ignore the user #include locs.1020ConstSearchDirIterator It =1021isAngled ? angled_dir_begin() : search_dir_begin();10221023// If this is a #include_next request, start searching after the directory the1024// file was found in.1025if (FromDir)1026It = FromDir;10271028// Cache all of the lookups performed by this method. Many headers are1029// multiply included, and the "pragma once" optimization prevents them from1030// being relex/pp'd, but they would still have to search through a1031// (potentially huge) series of SearchDirs to find it.1032LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename];10331034ConstSearchDirIterator NextIt = std::next(It);10351036if (!SkipCache) {1037if (CacheLookup.StartIt == NextIt &&1038CacheLookup.RequestingModule == RequestingModule) {1039// HIT: Skip querying potentially lots of directories for this lookup.1040if (CacheLookup.HitIt)1041It = CacheLookup.HitIt;1042if (CacheLookup.MappedName) {1043Filename = CacheLookup.MappedName;1044if (IsMapped)1045*IsMapped = true;1046}1047} else {1048// MISS: This is the first query, or the previous query didn't match1049// our search start. We will fill in our found location below, so prime1050// the start point value.1051CacheLookup.reset(RequestingModule, /*NewStartIt=*/NextIt);10521053if (It == search_dir_begin() && FirstNonHeaderMapSearchDirIdx > 0) {1054// Handle cold misses of user includes in the presence of many header1055// maps. We avoid searching perhaps thousands of header maps by1056// jumping directly to the correct one or jumping beyond all of them.1057auto Iter = SearchDirHeaderMapIndex.find(Filename.lower());1058if (Iter == SearchDirHeaderMapIndex.end())1059// Not in index => Skip to first SearchDir after initial header maps1060It = search_dir_nth(FirstNonHeaderMapSearchDirIdx);1061else1062// In index => Start with a specific header map1063It = search_dir_nth(Iter->second);1064}1065}1066} else {1067CacheLookup.reset(RequestingModule, /*NewStartIt=*/NextIt);1068}10691070SmallString<64> MappedName;10711072// Check each directory in sequence to see if it contains this file.1073for (; It != search_dir_end(); ++It) {1074bool InUserSpecifiedSystemFramework = false;1075bool IsInHeaderMap = false;1076bool IsFrameworkFoundInDir = false;1077OptionalFileEntryRef File = It->LookupFile(1078Filename, *this, IncludeLoc, SearchPath, RelativePath, RequestingModule,1079SuggestedModule, InUserSpecifiedSystemFramework, IsFrameworkFoundInDir,1080IsInHeaderMap, MappedName, OpenFile);1081if (!MappedName.empty()) {1082assert(IsInHeaderMap && "MappedName should come from a header map");1083CacheLookup.MappedName =1084copyString(MappedName, LookupFileCache.getAllocator());1085}1086if (IsMapped)1087// A filename is mapped when a header map remapped it to a relative path1088// used in subsequent header search or to an absolute path pointing to an1089// existing file.1090*IsMapped |= (!MappedName.empty() || (IsInHeaderMap && File));1091if (IsFrameworkFound)1092// Because we keep a filename remapped for subsequent search directory1093// lookups, ignore IsFrameworkFoundInDir after the first remapping and not1094// just for remapping in a current search directory.1095*IsFrameworkFound |= (IsFrameworkFoundInDir && !CacheLookup.MappedName);1096if (!File)1097continue;10981099CurDir = It;11001101IncludeNames[*File] = Filename;11021103// This file is a system header or C++ unfriendly if the dir is.1104HeaderFileInfo &HFI = getFileInfo(*File);1105HFI.DirInfo = CurDir->getDirCharacteristic();11061107// If the directory characteristic is User but this framework was1108// user-specified to be treated as a system framework, promote the1109// characteristic.1110if (HFI.DirInfo == SrcMgr::C_User && InUserSpecifiedSystemFramework)1111HFI.DirInfo = SrcMgr::C_System;11121113// If the filename matches a known system header prefix, override1114// whether the file is a system header.1115for (unsigned j = SystemHeaderPrefixes.size(); j; --j) {1116if (Filename.starts_with(SystemHeaderPrefixes[j - 1].first)) {1117HFI.DirInfo = SystemHeaderPrefixes[j-1].second ? SrcMgr::C_System1118: SrcMgr::C_User;1119break;1120}1121}11221123// Set the `Framework` info if this file is in a header map with framework1124// style include spelling or found in a framework dir. The header map case1125// is possible when building frameworks which use header maps.1126if (CurDir->isHeaderMap() && isAngled) {1127size_t SlashPos = Filename.find('/');1128if (SlashPos != StringRef::npos)1129HFI.Framework =1130getUniqueFrameworkName(StringRef(Filename.begin(), SlashPos));1131if (CurDir->isIndexHeaderMap())1132HFI.IndexHeaderMapHeader = 1;1133} else if (CurDir->isFramework()) {1134size_t SlashPos = Filename.find('/');1135if (SlashPos != StringRef::npos)1136HFI.Framework =1137getUniqueFrameworkName(StringRef(Filename.begin(), SlashPos));1138}11391140if (checkMSVCHeaderSearch(Diags, MSFE, &File->getFileEntry(), IncludeLoc)) {1141if (SuggestedModule)1142*SuggestedModule = MSSuggestedModule;1143return MSFE;1144}11451146bool FoundByHeaderMap = !IsMapped ? false : *IsMapped;1147if (!Includers.empty())1148diagnoseFrameworkInclude(Diags, IncludeLoc,1149Includers.front().second.getName(), Filename,1150*File, isAngled, FoundByHeaderMap);11511152// Remember this location for the next lookup we do.1153cacheLookupSuccess(CacheLookup, It, IncludeLoc);1154return File;1155}11561157// If we are including a file with a quoted include "foo.h" from inside1158// a header in a framework that is currently being built, and we couldn't1159// resolve "foo.h" any other way, change the include to <Foo/foo.h>, where1160// "Foo" is the name of the framework in which the including header was found.1161if (!Includers.empty() && Includers.front().first && !isAngled &&1162!Filename.contains('/')) {1163const HeaderFileInfo *IncludingHFI =1164getExistingFileInfo(*Includers.front().first);1165assert(IncludingHFI && "includer without file info");1166if (IncludingHFI->IndexHeaderMapHeader) {1167SmallString<128> ScratchFilename;1168ScratchFilename += IncludingHFI->Framework;1169ScratchFilename += '/';1170ScratchFilename += Filename;11711172OptionalFileEntryRef File = LookupFile(1173ScratchFilename, IncludeLoc, /*isAngled=*/true, FromDir, &CurDir,1174Includers.front(), SearchPath, RelativePath, RequestingModule,1175SuggestedModule, IsMapped, /*IsFrameworkFound=*/nullptr);11761177if (checkMSVCHeaderSearch(Diags, MSFE,1178File ? &File->getFileEntry() : nullptr,1179IncludeLoc)) {1180if (SuggestedModule)1181*SuggestedModule = MSSuggestedModule;1182return MSFE;1183}11841185cacheLookupSuccess(LookupFileCache[Filename],1186LookupFileCache[ScratchFilename].HitIt, IncludeLoc);1187// FIXME: SuggestedModule.1188return File;1189}1190}11911192if (checkMSVCHeaderSearch(Diags, MSFE, nullptr, IncludeLoc)) {1193if (SuggestedModule)1194*SuggestedModule = MSSuggestedModule;1195return MSFE;1196}11971198// Otherwise, didn't find it. Remember we didn't find this.1199CacheLookup.HitIt = search_dir_end();1200return std::nullopt;1201}12021203/// LookupSubframeworkHeader - Look up a subframework for the specified1204/// \#include file. For example, if \#include'ing <HIToolbox/HIToolbox.h> from1205/// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox1206/// is a subframework within Carbon.framework. If so, return the FileEntry1207/// for the designated file, otherwise return null.1208OptionalFileEntryRef HeaderSearch::LookupSubframeworkHeader(1209StringRef Filename, FileEntryRef ContextFileEnt,1210SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,1211Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule) {1212// Framework names must have a '/' in the filename. Find it.1213// FIXME: Should we permit '\' on Windows?1214size_t SlashPos = Filename.find('/');1215if (SlashPos == StringRef::npos)1216return std::nullopt;12171218// Look up the base framework name of the ContextFileEnt.1219StringRef ContextName = ContextFileEnt.getName();12201221// If the context info wasn't a framework, couldn't be a subframework.1222const unsigned DotFrameworkLen = 10;1223auto FrameworkPos = ContextName.find(".framework");1224if (FrameworkPos == StringRef::npos ||1225(ContextName[FrameworkPos + DotFrameworkLen] != '/' &&1226ContextName[FrameworkPos + DotFrameworkLen] != '\\'))1227return std::nullopt;12281229SmallString<1024> FrameworkName(ContextName.data(), ContextName.data() +1230FrameworkPos +1231DotFrameworkLen + 1);12321233// Append Frameworks/HIToolbox.framework/1234FrameworkName += "Frameworks/";1235FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos);1236FrameworkName += ".framework/";12371238auto &CacheLookup =1239*FrameworkMap.insert(std::make_pair(Filename.substr(0, SlashPos),1240FrameworkCacheEntry())).first;12411242// Some other location?1243if (CacheLookup.second.Directory &&1244CacheLookup.first().size() == FrameworkName.size() &&1245memcmp(CacheLookup.first().data(), &FrameworkName[0],1246CacheLookup.first().size()) != 0)1247return std::nullopt;12481249// Cache subframework.1250if (!CacheLookup.second.Directory) {1251++NumSubFrameworkLookups;12521253// If the framework dir doesn't exist, we fail.1254auto Dir = FileMgr.getOptionalDirectoryRef(FrameworkName);1255if (!Dir)1256return std::nullopt;12571258// Otherwise, if it does, remember that this is the right direntry for this1259// framework.1260CacheLookup.second.Directory = Dir;1261}126212631264if (RelativePath) {1265RelativePath->clear();1266RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());1267}12681269// Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"1270SmallString<1024> HeadersFilename(FrameworkName);1271HeadersFilename += "Headers/";1272if (SearchPath) {1273SearchPath->clear();1274// Without trailing '/'.1275SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);1276}12771278HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());1279auto File = FileMgr.getOptionalFileRef(HeadersFilename, /*OpenFile=*/true);1280if (!File) {1281// Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"1282HeadersFilename = FrameworkName;1283HeadersFilename += "PrivateHeaders/";1284if (SearchPath) {1285SearchPath->clear();1286// Without trailing '/'.1287SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);1288}12891290HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());1291File = FileMgr.getOptionalFileRef(HeadersFilename, /*OpenFile=*/true);12921293if (!File)1294return std::nullopt;1295}12961297// This file is a system header or C++ unfriendly if the old file is.1298const HeaderFileInfo *ContextHFI = getExistingFileInfo(ContextFileEnt);1299assert(ContextHFI && "context file without file info");1300// Note that the temporary 'DirInfo' is required here, as the call to1301// getFileInfo could resize the vector and might invalidate 'ContextHFI'.1302unsigned DirInfo = ContextHFI->DirInfo;1303getFileInfo(*File).DirInfo = DirInfo;13041305FrameworkName.pop_back(); // remove the trailing '/'1306if (!findUsableModuleForFrameworkHeader(*File, FrameworkName,1307RequestingModule, SuggestedModule,1308/*IsSystem*/ false))1309return std::nullopt;13101311return *File;1312}13131314//===----------------------------------------------------------------------===//1315// File Info Management.1316//===----------------------------------------------------------------------===//13171318static bool moduleMembershipNeedsMerge(const HeaderFileInfo *HFI,1319ModuleMap::ModuleHeaderRole Role) {1320if (ModuleMap::isModular(Role))1321return !HFI->isModuleHeader || HFI->isTextualModuleHeader;1322if (!HFI->isModuleHeader && (Role & ModuleMap::TextualHeader))1323return !HFI->isTextualModuleHeader;1324return false;1325}13261327static void mergeHeaderFileInfoModuleBits(HeaderFileInfo &HFI,1328bool isModuleHeader,1329bool isTextualModuleHeader) {1330HFI.isModuleHeader |= isModuleHeader;1331if (HFI.isModuleHeader)1332HFI.isTextualModuleHeader = false;1333else1334HFI.isTextualModuleHeader |= isTextualModuleHeader;1335}13361337void HeaderFileInfo::mergeModuleMembership(ModuleMap::ModuleHeaderRole Role) {1338mergeHeaderFileInfoModuleBits(*this, ModuleMap::isModular(Role),1339(Role & ModuleMap::TextualHeader));1340}13411342/// Merge the header file info provided by \p OtherHFI into the current1343/// header file info (\p HFI)1344static void mergeHeaderFileInfo(HeaderFileInfo &HFI,1345const HeaderFileInfo &OtherHFI) {1346assert(OtherHFI.External && "expected to merge external HFI");13471348HFI.isImport |= OtherHFI.isImport;1349HFI.isPragmaOnce |= OtherHFI.isPragmaOnce;1350mergeHeaderFileInfoModuleBits(HFI, OtherHFI.isModuleHeader,1351OtherHFI.isTextualModuleHeader);13521353if (!HFI.LazyControllingMacro.isValid())1354HFI.LazyControllingMacro = OtherHFI.LazyControllingMacro;13551356HFI.DirInfo = OtherHFI.DirInfo;1357HFI.External = (!HFI.IsValid || HFI.External);1358HFI.IsValid = true;1359HFI.IndexHeaderMapHeader = OtherHFI.IndexHeaderMapHeader;13601361if (HFI.Framework.empty())1362HFI.Framework = OtherHFI.Framework;1363}13641365HeaderFileInfo &HeaderSearch::getFileInfo(FileEntryRef FE) {1366if (FE.getUID() >= FileInfo.size())1367FileInfo.resize(FE.getUID() + 1);13681369HeaderFileInfo *HFI = &FileInfo[FE.getUID()];1370// FIXME: Use a generation count to check whether this is really up to date.1371if (ExternalSource && !HFI->Resolved) {1372auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE);1373if (ExternalHFI.IsValid) {1374HFI->Resolved = true;1375if (ExternalHFI.External)1376mergeHeaderFileInfo(*HFI, ExternalHFI);1377}1378}13791380HFI->IsValid = true;1381// We assume the caller has local information about this header file, so it's1382// no longer strictly external.1383HFI->External = false;1384return *HFI;1385}13861387const HeaderFileInfo *HeaderSearch::getExistingFileInfo(FileEntryRef FE) const {1388HeaderFileInfo *HFI;1389if (ExternalSource) {1390if (FE.getUID() >= FileInfo.size())1391FileInfo.resize(FE.getUID() + 1);13921393HFI = &FileInfo[FE.getUID()];1394// FIXME: Use a generation count to check whether this is really up to date.1395if (!HFI->Resolved) {1396auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE);1397if (ExternalHFI.IsValid) {1398HFI->Resolved = true;1399if (ExternalHFI.External)1400mergeHeaderFileInfo(*HFI, ExternalHFI);1401}1402}1403} else if (FE.getUID() < FileInfo.size()) {1404HFI = &FileInfo[FE.getUID()];1405} else {1406HFI = nullptr;1407}14081409return (HFI && HFI->IsValid) ? HFI : nullptr;1410}14111412const HeaderFileInfo *1413HeaderSearch::getExistingLocalFileInfo(FileEntryRef FE) const {1414HeaderFileInfo *HFI;1415if (FE.getUID() < FileInfo.size()) {1416HFI = &FileInfo[FE.getUID()];1417} else {1418HFI = nullptr;1419}14201421return (HFI && HFI->IsValid && !HFI->External) ? HFI : nullptr;1422}14231424bool HeaderSearch::isFileMultipleIncludeGuarded(FileEntryRef File) const {1425// Check if we've entered this file and found an include guard or #pragma1426// once. Note that we dor't check for #import, because that's not a property1427// of the file itself.1428if (auto *HFI = getExistingFileInfo(File))1429return HFI->isPragmaOnce || HFI->LazyControllingMacro.isValid();1430return false;1431}14321433void HeaderSearch::MarkFileModuleHeader(FileEntryRef FE,1434ModuleMap::ModuleHeaderRole Role,1435bool isCompilingModuleHeader) {1436// Don't mark the file info as non-external if there's nothing to change.1437if (!isCompilingModuleHeader) {1438if ((Role & ModuleMap::ExcludedHeader))1439return;1440auto *HFI = getExistingFileInfo(FE);1441if (HFI && !moduleMembershipNeedsMerge(HFI, Role))1442return;1443}14441445auto &HFI = getFileInfo(FE);1446HFI.mergeModuleMembership(Role);1447HFI.isCompilingModuleHeader |= isCompilingModuleHeader;1448}14491450bool HeaderSearch::ShouldEnterIncludeFile(Preprocessor &PP,1451FileEntryRef File, bool isImport,1452bool ModulesEnabled, Module *M,1453bool &IsFirstIncludeOfFile) {1454// An include file should be entered if either:1455// 1. This is the first include of the file.1456// 2. This file can be included multiple times, that is it's not an1457// "include-once" file.1458//1459// Include-once is controlled by these preprocessor directives.1460//1461// #pragma once1462// This directive is in the include file, and marks it as an include-once1463// file.1464//1465// #import <file>1466// This directive is in the includer, and indicates that the include file1467// should only be entered if this is the first include.1468++NumIncluded;1469IsFirstIncludeOfFile = false;1470HeaderFileInfo &FileInfo = getFileInfo(File);14711472auto MaybeReenterImportedFile = [&]() -> bool {1473// Modules add a wrinkle though: what's included isn't necessarily visible.1474// Consider this module.1475// module Example {1476// module A { header "a.h" export * }1477// module B { header "b.h" export * }1478// }1479// b.h includes c.h. The main file includes a.h, which will trigger a module1480// build of Example, and c.h will be included. However, c.h isn't visible to1481// the main file. Normally this is fine, the main file can just include c.h1482// if it needs it. If c.h is in a module, the include will translate into a1483// module import, this function will be skipped, and everything will work as1484// expected. However, if c.h is not in a module (or is `textual`), then this1485// function will run. If c.h is include-once, it will not be entered from1486// the main file and it will still not be visible.14871488// If modules aren't enabled then there's no visibility issue. Always1489// respect `#pragma once`.1490if (!ModulesEnabled || FileInfo.isPragmaOnce)1491return false;14921493// Ensure FileInfo bits are up to date.1494ModMap.resolveHeaderDirectives(File);14951496// This brings up a subtlety of #import - it's not a very good indicator of1497// include-once. Developers are often unaware of the difference between1498// #include and #import, and tend to use one or the other indiscrimiately.1499// In order to support #include on include-once headers that lack macro1500// guards and `#pragma once` (which is the vast majority of Objective-C1501// headers), if a file is ever included with #import, it's marked as1502// isImport in the HeaderFileInfo and treated as include-once. This allows1503// #include to work in Objective-C.1504// #include <Foundation/Foundation.h>1505// #include <Foundation/NSString.h>1506// Foundation.h has an #import of NSString.h, and so the second #include is1507// skipped even though NSString.h has no `#pragma once` and no macro guard.1508//1509// However, this helpfulness causes problems with modules. If c.h is not an1510// include-once file, but something included it with #import anyway (as is1511// typical in Objective-C code), this include will be skipped and c.h will1512// not be visible. Consider it not include-once if it is a `textual` header1513// in a module.1514if (FileInfo.isTextualModuleHeader)1515return true;15161517if (FileInfo.isCompilingModuleHeader) {1518// It's safer to re-enter a file whose module is being built because its1519// declarations will still be scoped to a single module.1520if (FileInfo.isModuleHeader) {1521// Headers marked as "builtin" are covered by the system module maps1522// rather than the builtin ones. Some versions of the Darwin module fail1523// to mark stdarg.h and stddef.h as textual. Attempt to re-enter these1524// files while building their module to allow them to function properly.1525if (ModMap.isBuiltinHeader(File))1526return true;1527} else {1528// Files that are excluded from their module can potentially be1529// re-entered from their own module. This might cause redeclaration1530// errors if another module saw this file first, but there's a1531// reasonable chance that its module will build first. However if1532// there's no controlling macro, then trust the #import and assume this1533// really is an include-once file.1534if (FileInfo.getControllingMacro(ExternalLookup))1535return true;1536}1537}1538// If the include file has a macro guard, then it might still not be1539// re-entered if the controlling macro is visibly defined. e.g. another1540// header in the module being built included this file and local submodule1541// visibility is not enabled.15421543// It might be tempting to re-enter the include-once file if it's not1544// visible in an attempt to make it visible. However this will still cause1545// redeclaration errors against the known-but-not-visible declarations. The1546// include file not being visible will most likely cause "undefined x"1547// errors, but at least there's a slim chance of compilation succeeding.1548return false;1549};15501551if (isImport) {1552// As discussed above, record that this file was ever `#import`ed, and treat1553// it as an include-once file from here out.1554FileInfo.isImport = true;1555if (PP.alreadyIncluded(File) && !MaybeReenterImportedFile())1556return false;1557} else {1558// isPragmaOnce and isImport are only set after the file has been included1559// at least once. If either are set then this is a repeat #include of an1560// include-once file.1561if (FileInfo.isPragmaOnce ||1562(FileInfo.isImport && !MaybeReenterImportedFile()))1563return false;1564}15651566// As a final optimization, check for a macro guard and skip entering the file1567// if the controlling macro is defined. The macro guard will effectively erase1568// the file's contents, and the include would have no effect other than to1569// waste time opening and reading a file.1570if (const IdentifierInfo *ControllingMacro =1571FileInfo.getControllingMacro(ExternalLookup)) {1572// If the header corresponds to a module, check whether the macro is already1573// defined in that module rather than checking all visible modules. This is1574// mainly to cover corner cases where the same controlling macro is used in1575// different files in multiple modules.1576if (M ? PP.isMacroDefinedInLocalModule(ControllingMacro, M)1577: PP.isMacroDefined(ControllingMacro)) {1578++NumMultiIncludeFileOptzn;1579return false;1580}1581}15821583FileInfo.IsLocallyIncluded = true;1584IsFirstIncludeOfFile = PP.markIncluded(File);1585return true;1586}15871588size_t HeaderSearch::getTotalMemory() const {1589return SearchDirs.capacity()1590+ llvm::capacity_in_bytes(FileInfo)1591+ llvm::capacity_in_bytes(HeaderMaps)1592+ LookupFileCache.getAllocator().getTotalMemory()1593+ FrameworkMap.getAllocator().getTotalMemory();1594}15951596unsigned HeaderSearch::searchDirIdx(const DirectoryLookup &DL) const {1597return &DL - &*SearchDirs.begin();1598}15991600StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) {1601return FrameworkNames.insert(Framework).first->first();1602}16031604StringRef HeaderSearch::getIncludeNameForHeader(const FileEntry *File) const {1605auto It = IncludeNames.find(File);1606if (It == IncludeNames.end())1607return {};1608return It->second;1609}16101611bool HeaderSearch::hasModuleMap(StringRef FileName,1612const DirectoryEntry *Root,1613bool IsSystem) {1614if (!HSOpts->ImplicitModuleMaps)1615return false;16161617SmallVector<const DirectoryEntry *, 2> FixUpDirectories;16181619StringRef DirName = FileName;1620do {1621// Get the parent directory name.1622DirName = llvm::sys::path::parent_path(DirName);1623if (DirName.empty())1624return false;16251626// Determine whether this directory exists.1627auto Dir = FileMgr.getOptionalDirectoryRef(DirName);1628if (!Dir)1629return false;16301631// Try to load the module map file in this directory.1632switch (loadModuleMapFile(*Dir, IsSystem,1633llvm::sys::path::extension(Dir->getName()) ==1634".framework")) {1635case LMM_NewlyLoaded:1636case LMM_AlreadyLoaded:1637// Success. All of the directories we stepped through inherit this module1638// map file.1639for (unsigned I = 0, N = FixUpDirectories.size(); I != N; ++I)1640DirectoryHasModuleMap[FixUpDirectories[I]] = true;1641return true;16421643case LMM_NoDirectory:1644case LMM_InvalidModuleMap:1645break;1646}16471648// If we hit the top of our search, we're done.1649if (*Dir == Root)1650return false;16511652// Keep track of all of the directories we checked, so we can mark them as1653// having module maps if we eventually do find a module map.1654FixUpDirectories.push_back(*Dir);1655} while (true);1656}16571658ModuleMap::KnownHeader1659HeaderSearch::findModuleForHeader(FileEntryRef File, bool AllowTextual,1660bool AllowExcluded) const {1661if (ExternalSource) {1662// Make sure the external source has handled header info about this file,1663// which includes whether the file is part of a module.1664(void)getExistingFileInfo(File);1665}1666return ModMap.findModuleForHeader(File, AllowTextual, AllowExcluded);1667}16681669ArrayRef<ModuleMap::KnownHeader>1670HeaderSearch::findAllModulesForHeader(FileEntryRef File) const {1671if (ExternalSource) {1672// Make sure the external source has handled header info about this file,1673// which includes whether the file is part of a module.1674(void)getExistingFileInfo(File);1675}1676return ModMap.findAllModulesForHeader(File);1677}16781679ArrayRef<ModuleMap::KnownHeader>1680HeaderSearch::findResolvedModulesForHeader(FileEntryRef File) const {1681if (ExternalSource) {1682// Make sure the external source has handled header info about this file,1683// which includes whether the file is part of a module.1684(void)getExistingFileInfo(File);1685}1686return ModMap.findResolvedModulesForHeader(File);1687}16881689static bool suggestModule(HeaderSearch &HS, FileEntryRef File,1690Module *RequestingModule,1691ModuleMap::KnownHeader *SuggestedModule) {1692ModuleMap::KnownHeader Module =1693HS.findModuleForHeader(File, /*AllowTextual*/true);16941695// If this module specifies [no_undeclared_includes], we cannot find any1696// file that's in a non-dependency module.1697if (RequestingModule && Module && RequestingModule->NoUndeclaredIncludes) {1698HS.getModuleMap().resolveUses(RequestingModule, /*Complain*/ false);1699if (!RequestingModule->directlyUses(Module.getModule())) {1700// Builtin headers are a special case. Multiple modules can use the same1701// builtin as a modular header (see also comment in1702// ShouldEnterIncludeFile()), so the builtin header may have been1703// "claimed" by an unrelated module. This shouldn't prevent us from1704// including the builtin header textually in this module.1705if (HS.getModuleMap().isBuiltinHeader(File)) {1706if (SuggestedModule)1707*SuggestedModule = ModuleMap::KnownHeader();1708return true;1709}1710// TODO: Add this module (or just its module map file) into something like1711// `RequestingModule->AffectingClangModules`.1712return false;1713}1714}17151716if (SuggestedModule)1717*SuggestedModule = (Module.getRole() & ModuleMap::TextualHeader)1718? ModuleMap::KnownHeader()1719: Module;17201721return true;1722}17231724bool HeaderSearch::findUsableModuleForHeader(1725FileEntryRef File, const DirectoryEntry *Root, Module *RequestingModule,1726ModuleMap::KnownHeader *SuggestedModule, bool IsSystemHeaderDir) {1727if (needModuleLookup(RequestingModule, SuggestedModule)) {1728// If there is a module that corresponds to this header, suggest it.1729hasModuleMap(File.getNameAsRequested(), Root, IsSystemHeaderDir);1730return suggestModule(*this, File, RequestingModule, SuggestedModule);1731}1732return true;1733}17341735bool HeaderSearch::findUsableModuleForFrameworkHeader(1736FileEntryRef File, StringRef FrameworkName, Module *RequestingModule,1737ModuleMap::KnownHeader *SuggestedModule, bool IsSystemFramework) {1738// If we're supposed to suggest a module, look for one now.1739if (needModuleLookup(RequestingModule, SuggestedModule)) {1740// Find the top-level framework based on this framework.1741SmallVector<std::string, 4> SubmodulePath;1742OptionalDirectoryEntryRef TopFrameworkDir =1743::getTopFrameworkDir(FileMgr, FrameworkName, SubmodulePath);1744assert(TopFrameworkDir && "Could not find the top-most framework dir");17451746// Determine the name of the top-level framework.1747StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());17481749// Load this framework module. If that succeeds, find the suggested module1750// for this header, if any.1751loadFrameworkModule(ModuleName, *TopFrameworkDir, IsSystemFramework);17521753// FIXME: This can find a module not part of ModuleName, which is1754// important so that we're consistent about whether this header1755// corresponds to a module. Possibly we should lock down framework modules1756// so that this is not possible.1757return suggestModule(*this, File, RequestingModule, SuggestedModule);1758}1759return true;1760}17611762static OptionalFileEntryRef getPrivateModuleMap(FileEntryRef File,1763FileManager &FileMgr,1764DiagnosticsEngine &Diags) {1765StringRef Filename = llvm::sys::path::filename(File.getName());1766SmallString<128> PrivateFilename(File.getDir().getName());1767if (Filename == "module.map")1768llvm::sys::path::append(PrivateFilename, "module_private.map");1769else if (Filename == "module.modulemap")1770llvm::sys::path::append(PrivateFilename, "module.private.modulemap");1771else1772return std::nullopt;1773auto PMMFile = FileMgr.getOptionalFileRef(PrivateFilename);1774if (PMMFile) {1775if (Filename == "module.map")1776Diags.Report(diag::warn_deprecated_module_dot_map)1777<< PrivateFilename << 11778<< File.getDir().getName().ends_with(".framework");1779}1780return PMMFile;1781}17821783bool HeaderSearch::loadModuleMapFile(FileEntryRef File, bool IsSystem,1784FileID ID, unsigned *Offset,1785StringRef OriginalModuleMapFile) {1786// Find the directory for the module. For frameworks, that may require going1787// up from the 'Modules' directory.1788OptionalDirectoryEntryRef Dir;1789if (getHeaderSearchOpts().ModuleMapFileHomeIsCwd) {1790Dir = FileMgr.getOptionalDirectoryRef(".");1791} else {1792if (!OriginalModuleMapFile.empty()) {1793// We're building a preprocessed module map. Find or invent the directory1794// that it originally occupied.1795Dir = FileMgr.getOptionalDirectoryRef(1796llvm::sys::path::parent_path(OriginalModuleMapFile));1797if (!Dir) {1798auto FakeFile = FileMgr.getVirtualFileRef(OriginalModuleMapFile, 0, 0);1799Dir = FakeFile.getDir();1800}1801} else {1802Dir = File.getDir();1803}18041805assert(Dir && "parent must exist");1806StringRef DirName(Dir->getName());1807if (llvm::sys::path::filename(DirName) == "Modules") {1808DirName = llvm::sys::path::parent_path(DirName);1809if (DirName.ends_with(".framework"))1810if (auto MaybeDir = FileMgr.getOptionalDirectoryRef(DirName))1811Dir = *MaybeDir;1812// FIXME: This assert can fail if there's a race between the above check1813// and the removal of the directory.1814assert(Dir && "parent must exist");1815}1816}18171818assert(Dir && "module map home directory must exist");1819switch (loadModuleMapFileImpl(File, IsSystem, *Dir, ID, Offset)) {1820case LMM_AlreadyLoaded:1821case LMM_NewlyLoaded:1822return false;1823case LMM_NoDirectory:1824case LMM_InvalidModuleMap:1825return true;1826}1827llvm_unreachable("Unknown load module map result");1828}18291830HeaderSearch::LoadModuleMapResult1831HeaderSearch::loadModuleMapFileImpl(FileEntryRef File, bool IsSystem,1832DirectoryEntryRef Dir, FileID ID,1833unsigned *Offset) {1834// Check whether we've already loaded this module map, and mark it as being1835// loaded in case we recursively try to load it from itself.1836auto AddResult = LoadedModuleMaps.insert(std::make_pair(File, true));1837if (!AddResult.second)1838return AddResult.first->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;18391840if (ModMap.parseModuleMapFile(File, IsSystem, Dir, ID, Offset)) {1841LoadedModuleMaps[File] = false;1842return LMM_InvalidModuleMap;1843}18441845// Try to load a corresponding private module map.1846if (OptionalFileEntryRef PMMFile =1847getPrivateModuleMap(File, FileMgr, Diags)) {1848if (ModMap.parseModuleMapFile(*PMMFile, IsSystem, Dir)) {1849LoadedModuleMaps[File] = false;1850return LMM_InvalidModuleMap;1851}1852}18531854// This directory has a module map.1855return LMM_NewlyLoaded;1856}18571858OptionalFileEntryRef1859HeaderSearch::lookupModuleMapFile(DirectoryEntryRef Dir, bool IsFramework) {1860if (!HSOpts->ImplicitModuleMaps)1861return std::nullopt;1862// For frameworks, the preferred spelling is Modules/module.modulemap, but1863// module.map at the framework root is also accepted.1864SmallString<128> ModuleMapFileName(Dir.getName());1865if (IsFramework)1866llvm::sys::path::append(ModuleMapFileName, "Modules");1867llvm::sys::path::append(ModuleMapFileName, "module.modulemap");1868if (auto F = FileMgr.getOptionalFileRef(ModuleMapFileName))1869return *F;18701871// Continue to allow module.map, but warn it's deprecated.1872ModuleMapFileName = Dir.getName();1873llvm::sys::path::append(ModuleMapFileName, "module.map");1874if (auto F = FileMgr.getOptionalFileRef(ModuleMapFileName)) {1875Diags.Report(diag::warn_deprecated_module_dot_map)1876<< ModuleMapFileName << 0 << IsFramework;1877return *F;1878}18791880// For frameworks, allow to have a private module map with a preferred1881// spelling when a public module map is absent.1882if (IsFramework) {1883ModuleMapFileName = Dir.getName();1884llvm::sys::path::append(ModuleMapFileName, "Modules",1885"module.private.modulemap");1886if (auto F = FileMgr.getOptionalFileRef(ModuleMapFileName))1887return *F;1888}1889return std::nullopt;1890}18911892Module *HeaderSearch::loadFrameworkModule(StringRef Name, DirectoryEntryRef Dir,1893bool IsSystem) {1894// Try to load a module map file.1895switch (loadModuleMapFile(Dir, IsSystem, /*IsFramework*/true)) {1896case LMM_InvalidModuleMap:1897// Try to infer a module map from the framework directory.1898if (HSOpts->ImplicitModuleMaps)1899ModMap.inferFrameworkModule(Dir, IsSystem, /*Parent=*/nullptr);1900break;19011902case LMM_NoDirectory:1903return nullptr;19041905case LMM_AlreadyLoaded:1906case LMM_NewlyLoaded:1907break;1908}19091910return ModMap.findModule(Name);1911}19121913HeaderSearch::LoadModuleMapResult1914HeaderSearch::loadModuleMapFile(StringRef DirName, bool IsSystem,1915bool IsFramework) {1916if (auto Dir = FileMgr.getOptionalDirectoryRef(DirName))1917return loadModuleMapFile(*Dir, IsSystem, IsFramework);19181919return LMM_NoDirectory;1920}19211922HeaderSearch::LoadModuleMapResult1923HeaderSearch::loadModuleMapFile(DirectoryEntryRef Dir, bool IsSystem,1924bool IsFramework) {1925auto KnownDir = DirectoryHasModuleMap.find(Dir);1926if (KnownDir != DirectoryHasModuleMap.end())1927return KnownDir->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;19281929if (OptionalFileEntryRef ModuleMapFile =1930lookupModuleMapFile(Dir, IsFramework)) {1931LoadModuleMapResult Result =1932loadModuleMapFileImpl(*ModuleMapFile, IsSystem, Dir);1933// Add Dir explicitly in case ModuleMapFile is in a subdirectory.1934// E.g. Foo.framework/Modules/module.modulemap1935// ^Dir ^ModuleMapFile1936if (Result == LMM_NewlyLoaded)1937DirectoryHasModuleMap[Dir] = true;1938else if (Result == LMM_InvalidModuleMap)1939DirectoryHasModuleMap[Dir] = false;1940return Result;1941}1942return LMM_InvalidModuleMap;1943}19441945void HeaderSearch::collectAllModules(SmallVectorImpl<Module *> &Modules) {1946Modules.clear();19471948if (HSOpts->ImplicitModuleMaps) {1949// Load module maps for each of the header search directories.1950for (DirectoryLookup &DL : search_dir_range()) {1951bool IsSystem = DL.isSystemHeaderDirectory();1952if (DL.isFramework()) {1953std::error_code EC;1954SmallString<128> DirNative;1955llvm::sys::path::native(DL.getFrameworkDirRef()->getName(), DirNative);19561957// Search each of the ".framework" directories to load them as modules.1958llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();1959for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC),1960DirEnd;1961Dir != DirEnd && !EC; Dir.increment(EC)) {1962if (llvm::sys::path::extension(Dir->path()) != ".framework")1963continue;19641965auto FrameworkDir = FileMgr.getOptionalDirectoryRef(Dir->path());1966if (!FrameworkDir)1967continue;19681969// Load this framework module.1970loadFrameworkModule(llvm::sys::path::stem(Dir->path()), *FrameworkDir,1971IsSystem);1972}1973continue;1974}19751976// FIXME: Deal with header maps.1977if (DL.isHeaderMap())1978continue;19791980// Try to load a module map file for the search directory.1981loadModuleMapFile(*DL.getDirRef(), IsSystem, /*IsFramework*/ false);19821983// Try to load module map files for immediate subdirectories of this1984// search directory.1985loadSubdirectoryModuleMaps(DL);1986}1987}19881989// Populate the list of modules.1990llvm::transform(ModMap.modules(), std::back_inserter(Modules),1991[](const auto &NameAndMod) { return NameAndMod.second; });1992}19931994void HeaderSearch::loadTopLevelSystemModules() {1995if (!HSOpts->ImplicitModuleMaps)1996return;19971998// Load module maps for each of the header search directories.1999for (const DirectoryLookup &DL : search_dir_range()) {2000// We only care about normal header directories.2001if (!DL.isNormalDir())2002continue;20032004// Try to load a module map file for the search directory.2005loadModuleMapFile(*DL.getDirRef(), DL.isSystemHeaderDirectory(),2006DL.isFramework());2007}2008}20092010void HeaderSearch::loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir) {2011assert(HSOpts->ImplicitModuleMaps &&2012"Should not be loading subdirectory module maps");20132014if (SearchDir.haveSearchedAllModuleMaps())2015return;20162017std::error_code EC;2018SmallString<128> Dir = SearchDir.getDirRef()->getName();2019FileMgr.makeAbsolutePath(Dir);2020SmallString<128> DirNative;2021llvm::sys::path::native(Dir, DirNative);2022llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();2023for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;2024Dir != DirEnd && !EC; Dir.increment(EC)) {2025if (Dir->type() == llvm::sys::fs::file_type::regular_file)2026continue;2027bool IsFramework = llvm::sys::path::extension(Dir->path()) == ".framework";2028if (IsFramework == SearchDir.isFramework())2029loadModuleMapFile(Dir->path(), SearchDir.isSystemHeaderDirectory(),2030SearchDir.isFramework());2031}20322033SearchDir.setSearchedAllModuleMaps(true);2034}20352036std::string HeaderSearch::suggestPathToFileForDiagnostics(2037FileEntryRef File, llvm::StringRef MainFile, bool *IsAngled) const {2038return suggestPathToFileForDiagnostics(File.getName(), /*WorkingDir=*/"",2039MainFile, IsAngled);2040}20412042std::string HeaderSearch::suggestPathToFileForDiagnostics(2043llvm::StringRef File, llvm::StringRef WorkingDir, llvm::StringRef MainFile,2044bool *IsAngled) const {2045using namespace llvm::sys;20462047llvm::SmallString<32> FilePath = File;2048if (!WorkingDir.empty() && !path::is_absolute(FilePath))2049fs::make_absolute(WorkingDir, FilePath);2050// remove_dots switches to backslashes on windows as a side-effect!2051// We always want to suggest forward slashes for includes.2052// (not remove_dots(..., posix) as that misparses windows paths).2053path::remove_dots(FilePath, /*remove_dot_dot=*/true);2054path::native(FilePath, path::Style::posix);2055File = FilePath;20562057unsigned BestPrefixLength = 0;2058// Checks whether `Dir` is a strict path prefix of `File`. If so and that's2059// the longest prefix we've seen so for it, returns true and updates the2060// `BestPrefixLength` accordingly.2061auto CheckDir = [&](llvm::SmallString<32> Dir) -> bool {2062if (!WorkingDir.empty() && !path::is_absolute(Dir))2063fs::make_absolute(WorkingDir, Dir);2064path::remove_dots(Dir, /*remove_dot_dot=*/true);2065for (auto NI = path::begin(File), NE = path::end(File),2066DI = path::begin(Dir), DE = path::end(Dir);2067NI != NE; ++NI, ++DI) {2068if (DI == DE) {2069// Dir is a prefix of File, up to choice of path separators.2070unsigned PrefixLength = NI - path::begin(File);2071if (PrefixLength > BestPrefixLength) {2072BestPrefixLength = PrefixLength;2073return true;2074}2075break;2076}20772078// Consider all path separators equal.2079if (NI->size() == 1 && DI->size() == 1 &&2080path::is_separator(NI->front()) && path::is_separator(DI->front()))2081continue;20822083// Special case Apple .sdk folders since the search path is typically a2084// symlink like `iPhoneSimulator14.5.sdk` while the file is instead2085// located in `iPhoneSimulator.sdk` (the real folder).2086if (NI->ends_with(".sdk") && DI->ends_with(".sdk")) {2087StringRef NBasename = path::stem(*NI);2088StringRef DBasename = path::stem(*DI);2089if (DBasename.starts_with(NBasename))2090continue;2091}20922093if (*NI != *DI)2094break;2095}2096return false;2097};20982099bool BestPrefixIsFramework = false;2100for (const DirectoryLookup &DL : search_dir_range()) {2101if (DL.isNormalDir()) {2102StringRef Dir = DL.getDirRef()->getName();2103if (CheckDir(Dir)) {2104if (IsAngled)2105*IsAngled = BestPrefixLength && isSystem(DL.getDirCharacteristic());2106BestPrefixIsFramework = false;2107}2108} else if (DL.isFramework()) {2109StringRef Dir = DL.getFrameworkDirRef()->getName();2110if (CheckDir(Dir)) {2111// Framework includes by convention use <>.2112if (IsAngled)2113*IsAngled = BestPrefixLength;2114BestPrefixIsFramework = true;2115}2116}2117}21182119// Try to shorten include path using TUs directory, if we couldn't find any2120// suitable prefix in include search paths.2121if (!BestPrefixLength && CheckDir(path::parent_path(MainFile))) {2122if (IsAngled)2123*IsAngled = false;2124BestPrefixIsFramework = false;2125}21262127// Try resolving resulting filename via reverse search in header maps,2128// key from header name is user preferred name for the include file.2129StringRef Filename = File.drop_front(BestPrefixLength);2130for (const DirectoryLookup &DL : search_dir_range()) {2131if (!DL.isHeaderMap())2132continue;21332134StringRef SpelledFilename =2135DL.getHeaderMap()->reverseLookupFilename(Filename);2136if (!SpelledFilename.empty()) {2137Filename = SpelledFilename;2138BestPrefixIsFramework = false;2139break;2140}2141}21422143// If the best prefix is a framework path, we need to compute the proper2144// include spelling for the framework header.2145bool IsPrivateHeader;2146SmallString<128> FrameworkName, IncludeSpelling;2147if (BestPrefixIsFramework &&2148isFrameworkStylePath(Filename, IsPrivateHeader, FrameworkName,2149IncludeSpelling)) {2150Filename = IncludeSpelling;2151}2152return path::convert_to_slash(Filename);2153}215421552156