blob: 8b6a19e080fa009094e975879d1bc972aedb0612 [file] [log] [blame]
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +00001//===- HeaderSearch.cpp - Resolve Header File Locations -------------------===//
Chris Lattner59a9ebd2006-10-18 05:34:33 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Chris Lattner59a9ebd2006-10-18 05:34:33 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the DirectoryLookup and HeaderSearch interfaces.
10//
11//===----------------------------------------------------------------------===//
12
Chris Lattner59a9ebd2006-10-18 05:34:33 +000013#include "clang/Lex/HeaderSearch.h"
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +000014#include "clang/Basic/Diagnostic.h"
Chris Lattneref6b1362007-10-07 08:58:51 +000015#include "clang/Basic/FileManager.h"
16#include "clang/Basic/IdentifierTable.h"
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +000017#include "clang/Basic/Module.h"
18#include "clang/Basic/SourceManager.h"
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +000019#include "clang/Lex/DirectoryLookup.h"
Richard Smith2aedca32015-07-01 02:29:35 +000020#include "clang/Lex/ExternalPreprocessorSource.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/Lex/HeaderMap.h"
22#include "clang/Lex/HeaderSearchOptions.h"
Will Wilson0fafd342013-12-27 19:46:16 +000023#include "clang/Lex/LexDiagnostic.h"
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +000024#include "clang/Lex/ModuleMap.h"
Richard Smith20e883e2015-04-29 23:20:19 +000025#include "clang/Lex/Preprocessor.h"
Ben Langmuirbeee15e2014-04-14 18:00:01 +000026#include "llvm/ADT/APInt.h"
27#include "llvm/ADT/Hashing.h"
Chris Lattner43fd42e2006-10-30 03:40:58 +000028#include "llvm/ADT/SmallString.h"
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +000029#include "llvm/ADT/SmallVector.h"
30#include "llvm/ADT/StringRef.h"
31#include "llvm/Support/Allocator.h"
Ted Kremenekae63d102011-07-27 18:41:18 +000032#include "llvm/Support/Capacity.h"
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +000033#include "llvm/Support/ErrorHandling.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000034#include "llvm/Support/FileSystem.h"
35#include "llvm/Support/Path.h"
Jonas Devliegherefc514902018-10-10 13:27:25 +000036#include "llvm/Support/VirtualFileSystem.h"
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +000037#include <algorithm>
38#include <cassert>
39#include <cstddef>
Chris Lattnerc25d8a72009-03-02 22:20:04 +000040#include <cstdio>
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +000041#include <cstring>
42#include <string>
43#include <system_error>
Benjamin Kramercfeacf52016-05-27 14:27:13 +000044#include <utility>
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +000045
Chris Lattner59a9ebd2006-10-18 05:34:33 +000046using namespace clang;
47
Douglas Gregor99734e72009-04-25 23:30:02 +000048const IdentifierInfo *
Richard Smith2aedca32015-07-01 02:29:35 +000049HeaderFileInfo::getControllingMacro(ExternalPreprocessorSource *External) {
50 if (ControllingMacro) {
Chandler Carruth59666772016-11-04 06:32:57 +000051 if (ControllingMacro->isOutOfDate()) {
52 assert(External && "We must have an external source if we have a "
53 "controlling macro that is out of date.");
Richard Smith2aedca32015-07-01 02:29:35 +000054 External->updateOutOfDateIdentifier(
55 *const_cast<IdentifierInfo *>(ControllingMacro));
Chandler Carruth59666772016-11-04 06:32:57 +000056 }
Douglas Gregor99734e72009-04-25 23:30:02 +000057 return ControllingMacro;
Richard Smith2aedca32015-07-01 02:29:35 +000058 }
Douglas Gregor99734e72009-04-25 23:30:02 +000059
60 if (!ControllingMacroID || !External)
Craig Topperd2d442c2014-05-17 23:10:59 +000061 return nullptr;
Douglas Gregor99734e72009-04-25 23:30:02 +000062
63 ControllingMacro = External->GetIdentifier(ControllingMacroID);
64 return ControllingMacro;
65}
66
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +000067ExternalHeaderFileInfoSource::~ExternalHeaderFileInfoSource() = default;
Douglas Gregor09b69892011-02-10 17:09:37 +000068
David Blaikie9c28cb32017-01-06 01:04:46 +000069HeaderSearch::HeaderSearch(std::shared_ptr<HeaderSearchOptions> HSOpts,
Manuel Klimek1f76c4e2013-10-24 07:51:24 +000070 SourceManager &SourceMgr, DiagnosticsEngine &Diags,
Will Wilson0fafd342013-12-27 19:46:16 +000071 const LangOptions &LangOpts,
Douglas Gregor89929282012-01-30 06:01:29 +000072 const TargetInfo *Target)
Benjamin Kramercfeacf52016-05-27 14:27:13 +000073 : HSOpts(std::move(HSOpts)), Diags(Diags),
74 FileMgr(SourceMgr.getFileManager()), FrameworkMap(64),
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +000075 ModMap(SourceMgr, Diags, LangOpts, Target, *this) {}
Chris Lattner641a0be2006-10-20 06:23:14 +000076
Chris Lattner59a9ebd2006-10-18 05:34:33 +000077void HeaderSearch::PrintStats() {
Chris Lattner23b7eb62007-06-15 23:05:46 +000078 fprintf(stderr, "\n*** HeaderSearch Stats:\n");
79 fprintf(stderr, "%d files tracked.\n", (int)FileInfo.size());
Chris Lattner59a9ebd2006-10-18 05:34:33 +000080 unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0;
81 for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) {
82 NumOnceOnlyFiles += FileInfo[i].isImport;
83 if (MaxNumIncludes < FileInfo[i].NumIncludes)
84 MaxNumIncludes = FileInfo[i].NumIncludes;
85 NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1;
86 }
Chris Lattner23b7eb62007-06-15 23:05:46 +000087 fprintf(stderr, " %d #import/#pragma once files.\n", NumOnceOnlyFiles);
88 fprintf(stderr, " %d included exactly once.\n", NumSingleIncludedFiles);
89 fprintf(stderr, " %d max times a file is included.\n", MaxNumIncludes);
Mike Stump11289f42009-09-09 15:08:12 +000090
Chris Lattner23b7eb62007-06-15 23:05:46 +000091 fprintf(stderr, " %d #include/#include_next/#import.\n", NumIncluded);
92 fprintf(stderr, " %d #includes skipped due to"
93 " the multi-include optimization.\n", NumMultiIncludeFileOptzn);
Mike Stump11289f42009-09-09 15:08:12 +000094
Chris Lattner23b7eb62007-06-15 23:05:46 +000095 fprintf(stderr, "%d framework lookups.\n", NumFrameworkLookups);
96 fprintf(stderr, "%d subframework lookups.\n", NumSubFrameworkLookups);
Chris Lattner59a9ebd2006-10-18 05:34:33 +000097}
98
Chris Lattnerc4ba38e2007-12-17 06:36:45 +000099/// CreateHeaderMap - This method returns a HeaderMap for the specified
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000100/// FileEntry, uniquing them through the 'HeaderMaps' datastructure.
Chris Lattner4ffe46c2007-12-17 18:34:53 +0000101const HeaderMap *HeaderSearch::CreateHeaderMap(const FileEntry *FE) {
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000102 // We expect the number of headermaps to be small, and almost always empty.
Chris Lattnerf62f7582007-12-17 07:52:39 +0000103 // If it ever grows, use of a linear search should be re-evaluated.
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000104 if (!HeaderMaps.empty()) {
105 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
Chris Lattnerf62f7582007-12-17 07:52:39 +0000106 // Pointer equality comparison of FileEntries works because they are
107 // already uniqued by inode.
Mike Stump11289f42009-09-09 15:08:12 +0000108 if (HeaderMaps[i].first == FE)
Fangrui Song48769772018-08-20 19:15:02 +0000109 return HeaderMaps[i].second.get();
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000110 }
Mike Stump11289f42009-09-09 15:08:12 +0000111
Fangrui Song48769772018-08-20 19:15:02 +0000112 if (std::unique_ptr<HeaderMap> HM = HeaderMap::Create(FE, FileMgr)) {
113 HeaderMaps.emplace_back(FE, std::move(HM));
114 return HeaderMaps.back().second.get();
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000115 }
Mike Stump11289f42009-09-09 15:08:12 +0000116
Craig Topperd2d442c2014-05-17 23:10:59 +0000117 return nullptr;
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000118}
119
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000120/// Get filenames for all registered header maps.
Bruno Cardoso Lopes181225b2016-12-11 04:27:28 +0000121void HeaderSearch::getHeaderMapFileNames(
122 SmallVectorImpl<std::string> &Names) const {
123 for (auto &HM : HeaderMaps)
124 Names.push_back(HM.first->getName());
125}
126
Boris Kolpackovd30446f2017-08-31 06:26:43 +0000127std::string HeaderSearch::getCachedModuleFileName(Module *Module) {
Ben Langmuir9d6448b2014-08-09 00:57:23 +0000128 const FileEntry *ModuleMap =
129 getModuleMap().getModuleMapFileForUniquing(Module);
Boris Kolpackovd30446f2017-08-31 06:26:43 +0000130 return getCachedModuleFileName(Module->Name, ModuleMap->getName());
Douglas Gregor279a6c32012-01-29 17:08:11 +0000131}
132
Boris Kolpackovd30446f2017-08-31 06:26:43 +0000133std::string HeaderSearch::getPrebuiltModuleFileName(StringRef ModuleName,
134 bool FileMapOnly) {
135 // First check the module name to pcm file map.
136 auto i (HSOpts->PrebuiltModuleFiles.find(ModuleName));
137 if (i != HSOpts->PrebuiltModuleFiles.end())
138 return i->second;
139
140 if (FileMapOnly || HSOpts->PrebuiltModulePaths.empty())
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +0000141 return {};
Manman Ren11f2a472016-08-18 17:42:15 +0000142
Boris Kolpackovd30446f2017-08-31 06:26:43 +0000143 // Then go through each prebuilt module directory and try to find the pcm
144 // file.
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +0000145 for (const std::string &Dir : HSOpts->PrebuiltModulePaths) {
146 SmallString<256> Result(Dir);
147 llvm::sys::fs::make_absolute(Result);
148 llvm::sys::path::append(Result, ModuleName + ".pcm");
149 if (getFileMgr().getFile(Result.str()))
150 return Result.str().str();
Manman Ren11f2a472016-08-18 17:42:15 +0000151 }
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +0000152 return {};
153}
Manman Ren11f2a472016-08-18 17:42:15 +0000154
Boris Kolpackovd30446f2017-08-31 06:26:43 +0000155std::string HeaderSearch::getCachedModuleFileName(StringRef ModuleName,
156 StringRef ModuleMapPath) {
Richard Smithd520a252015-07-21 18:07:47 +0000157 // If we don't have a module cache path or aren't supposed to use one, we
158 // can't do anything.
Richard Smith3938f0c2015-08-15 00:34:15 +0000159 if (getModuleCachePath().empty())
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +0000160 return {};
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000161
Richard Smith3938f0c2015-08-15 00:34:15 +0000162 SmallString<256> Result(getModuleCachePath());
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000163 llvm::sys::fs::make_absolute(Result);
164
165 if (HSOpts->DisableModuleHash) {
166 llvm::sys::path::append(Result, ModuleName + ".pcm");
167 } else {
168 // Construct the name <ModuleName>-<hash of ModuleMapPath>.pcm which should
Richard Smith54cc3c22014-12-11 20:50:24 +0000169 // ideally be globally unique to this particular module. Name collisions
170 // in the hash are safe (because any translation unit can only import one
171 // module with each name), but result in a loss of caching.
172 //
173 // To avoid false-negatives, we form as canonical a path as we can, and map
174 // to lower-case in case we're on a case-insensitive file system.
Richard Smith3f57cff2017-03-09 00:58:22 +0000175 std::string Parent = llvm::sys::path::parent_path(ModuleMapPath);
176 if (Parent.empty())
177 Parent = ".";
Harlan Haskins8d323d12019-08-01 21:31:56 +0000178 auto Dir = FileMgr.getDirectory(Parent);
Richard Smith54cc3c22014-12-11 20:50:24 +0000179 if (!Dir)
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +0000180 return {};
Harlan Haskins8d323d12019-08-01 21:31:56 +0000181 auto DirName = FileMgr.getCanonicalName(*Dir);
Richard Smith54cc3c22014-12-11 20:50:24 +0000182 auto FileName = llvm::sys::path::filename(ModuleMapPath);
183
184 llvm::hash_code Hash =
Adrian Prantl793038d32016-01-12 21:01:56 +0000185 llvm::hash_combine(DirName.lower(), FileName.lower());
Richard Smith54cc3c22014-12-11 20:50:24 +0000186
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000187 SmallString<128> HashStr;
Richard Smith54cc3c22014-12-11 20:50:24 +0000188 llvm::APInt(64, size_t(Hash)).toStringUnsigned(HashStr, /*Radix*/36);
Yaron Keren92e1b622015-03-18 10:17:07 +0000189 llvm::sys::path::append(Result, ModuleName + "-" + HashStr + ".pcm");
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000190 }
Douglas Gregor279a6c32012-01-29 17:08:11 +0000191 return Result.str().str();
192}
193
Bruno Cardoso Lopes52431f32018-07-18 23:21:19 +0000194Module *HeaderSearch::lookupModule(StringRef ModuleName, bool AllowSearch,
195 bool AllowExtraModuleMapSearch) {
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000196 // Look in the module map to determine if there is a module by this name.
Douglas Gregor279a6c32012-01-29 17:08:11 +0000197 Module *Module = ModMap.findModule(ModuleName);
Richard Smith47972af2015-06-16 00:08:24 +0000198 if (Module || !AllowSearch || !HSOpts->ImplicitModuleMaps)
Douglas Gregor279a6c32012-01-29 17:08:11 +0000199 return Module;
Graydon Hoare4d867642016-12-21 00:24:39 +0000200
201 StringRef SearchName = ModuleName;
Bruno Cardoso Lopes52431f32018-07-18 23:21:19 +0000202 Module = lookupModule(ModuleName, SearchName, AllowExtraModuleMapSearch);
Graydon Hoare4d867642016-12-21 00:24:39 +0000203
204 // The facility for "private modules" -- adjacent, optional module maps named
205 // module.private.modulemap that are supposed to define private submodules --
Bruno Cardoso Lopes297299192017-12-22 02:53:30 +0000206 // may have different flavors of names: FooPrivate, Foo_Private and Foo.Private.
207 //
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000208 // Foo.Private is now deprecated in favor of Foo_Private. Users of FooPrivate
Bruno Cardoso Lopes297299192017-12-22 02:53:30 +0000209 // should also rename to Foo_Private. Representing private as submodules
210 // could force building unwanted dependencies into the parent module and cause
211 // dependency cycles.
212 if (!Module && SearchName.consume_back("_Private"))
Bruno Cardoso Lopes52431f32018-07-18 23:21:19 +0000213 Module = lookupModule(ModuleName, SearchName, AllowExtraModuleMapSearch);
Graydon Hoare4d867642016-12-21 00:24:39 +0000214 if (!Module && SearchName.consume_back("Private"))
Bruno Cardoso Lopes52431f32018-07-18 23:21:19 +0000215 Module = lookupModule(ModuleName, SearchName, AllowExtraModuleMapSearch);
Graydon Hoare4d867642016-12-21 00:24:39 +0000216 return Module;
217}
218
Bruno Cardoso Lopes52431f32018-07-18 23:21:19 +0000219Module *HeaderSearch::lookupModule(StringRef ModuleName, StringRef SearchName,
220 bool AllowExtraModuleMapSearch) {
Graydon Hoare4d867642016-12-21 00:24:39 +0000221 Module *Module = nullptr;
222
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000223 // Look through the various header search paths to load any available module
Douglas Gregor279a6c32012-01-29 17:08:11 +0000224 // maps, searching for a module map that describes this module.
225 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
226 if (SearchDirs[Idx].isFramework()) {
Graydon Hoare4d867642016-12-21 00:24:39 +0000227 // Search for or infer a module map for a framework. Here we use
228 // SearchName rather than ModuleName, to permit finding private modules
229 // named FooPrivate in buggy frameworks named Foo.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000230 SmallString<128> FrameworkDirName;
Douglas Gregor279a6c32012-01-29 17:08:11 +0000231 FrameworkDirName += SearchDirs[Idx].getFrameworkDir()->getName();
Graydon Hoare4d867642016-12-21 00:24:39 +0000232 llvm::sys::path::append(FrameworkDirName, SearchName + ".framework");
Harlan Haskins8d323d12019-08-01 21:31:56 +0000233 if (auto FrameworkDir = FileMgr.getDirectory(FrameworkDirName)) {
Douglas Gregor279a6c32012-01-29 17:08:11 +0000234 bool IsSystem
235 = SearchDirs[Idx].getDirCharacteristic() != SrcMgr::C_User;
Harlan Haskins8d323d12019-08-01 21:31:56 +0000236 Module = loadFrameworkModule(ModuleName, *FrameworkDir, IsSystem);
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000237 if (Module)
238 break;
239 }
Douglas Gregor279a6c32012-01-29 17:08:11 +0000240 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000241
Douglas Gregor279a6c32012-01-29 17:08:11 +0000242 // FIXME: Figure out how header maps and module maps will work together.
Fangrui Song6907ce22018-07-30 19:24:48 +0000243
Douglas Gregor279a6c32012-01-29 17:08:11 +0000244 // Only deal with normal search directories.
245 if (!SearchDirs[Idx].isNormalDir())
246 continue;
Douglas Gregor963c5532013-06-21 16:28:10 +0000247
248 bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
Douglas Gregor279a6c32012-01-29 17:08:11 +0000249 // Search for a module map file in this directory.
Ben Langmuir984e1df2014-03-19 20:23:34 +0000250 if (loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem,
251 /*IsFramework*/false) == LMM_NewlyLoaded) {
Douglas Gregor279a6c32012-01-29 17:08:11 +0000252 // We just loaded a module map file; check whether the module is
253 // available now.
254 Module = ModMap.findModule(ModuleName);
255 if (Module)
256 break;
257 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000258
Douglas Gregor279a6c32012-01-29 17:08:11 +0000259 // Search for a module map in a subdirectory with the same name as the
260 // module.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000261 SmallString<128> NestedModuleMapDirName;
Douglas Gregor279a6c32012-01-29 17:08:11 +0000262 NestedModuleMapDirName = SearchDirs[Idx].getDir()->getName();
263 llvm::sys::path::append(NestedModuleMapDirName, ModuleName);
Ben Langmuir984e1df2014-03-19 20:23:34 +0000264 if (loadModuleMapFile(NestedModuleMapDirName, IsSystem,
265 /*IsFramework*/false) == LMM_NewlyLoaded){
Douglas Gregor279a6c32012-01-29 17:08:11 +0000266 // If we just loaded a module map file, look for the module again.
267 Module = ModMap.findModule(ModuleName);
268 if (Module)
269 break;
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000270 }
Douglas Gregor0339a642013-03-21 01:08:50 +0000271
272 // If we've already performed the exhaustive search for module maps in this
273 // search directory, don't do it again.
274 if (SearchDirs[Idx].haveSearchedAllModuleMaps())
275 continue;
276
277 // Load all module maps in the immediate subdirectories of this search
Bruno Cardoso Lopes52431f32018-07-18 23:21:19 +0000278 // directory if ModuleName was from @import.
279 if (AllowExtraModuleMapSearch)
280 loadSubdirectoryModuleMaps(SearchDirs[Idx]);
Douglas Gregor0339a642013-03-21 01:08:50 +0000281
282 // Look again for the module.
283 Module = ModMap.findModule(ModuleName);
284 if (Module)
285 break;
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000286 }
Douglas Gregor0339a642013-03-21 01:08:50 +0000287
Douglas Gregor279a6c32012-01-29 17:08:11 +0000288 return Module;
Douglas Gregor1e44e022011-09-12 20:41:59 +0000289}
290
Chris Lattnerf62f7582007-12-17 07:52:39 +0000291//===----------------------------------------------------------------------===//
292// File lookup within a DirectoryLookup scope
293//===----------------------------------------------------------------------===//
294
Chris Lattner8d720d02007-12-17 17:57:27 +0000295/// getName - Return the directory or filename corresponding to this lookup
296/// object.
Mehdi Amini99d1b292016-10-01 16:38:28 +0000297StringRef DirectoryLookup::getName() const {
Chris Lattner8d720d02007-12-17 17:57:27 +0000298 if (isNormalDir())
299 return getDir()->getName();
300 if (isFramework())
301 return getFrameworkDir()->getName();
302 assert(isHeaderMap() && "Unknown DirectoryLookup");
303 return getHeaderMap()->getFileName();
304}
305
Richard Smith3d5b48c2015-10-16 21:42:56 +0000306const FileEntry *HeaderSearch::getFileAndSuggestModule(
Taewook Ohf42103c2016-06-13 20:40:21 +0000307 StringRef FileName, SourceLocation IncludeLoc, const DirectoryEntry *Dir,
308 bool IsSystemHeaderDir, Module *RequestingModule,
309 ModuleMap::KnownHeader *SuggestedModule) {
Richard Smith8c71eba2014-03-05 20:51:45 +0000310 // If we have a module map that might map this header, load it and
311 // check whether we'll have a suggestion for a module.
Nico Weberbabdfde2019-08-08 17:58:32 +0000312 llvm::ErrorOr<const FileEntry *> File =
313 getFileMgr().getFile(FileName, /*OpenFile=*/true);
314 if (!File) {
315 // For rare, surprising errors (e.g. "out of file handles"), diag the EC
316 // message.
317 std::error_code EC = File.getError();
318 if (EC != std::errc::no_such_file_or_directory &&
Reid Kleckner1d63b022019-08-08 21:35:03 +0000319 EC != std::errc::invalid_argument && EC != std::errc::is_a_directory) {
320 Diags.Report(IncludeLoc, diag::err_cannot_open_file)
321 << FileName << EC.message();
Nico Weberbabdfde2019-08-08 17:58:32 +0000322 }
Reid Klecknerafb9aae2015-10-20 18:45:57 +0000323 return nullptr;
Nico Weberbabdfde2019-08-08 17:58:32 +0000324 }
Richard Smith8c71eba2014-03-05 20:51:45 +0000325
Richard Smith3d5b48c2015-10-16 21:42:56 +0000326 // If there is a module that corresponds to this header, suggest it.
Harlan Haskins8d323d12019-08-01 21:31:56 +0000327 if (!findUsableModuleForHeader(*File, Dir ? Dir : (*File)->getDir(),
Richard Smith3d5b48c2015-10-16 21:42:56 +0000328 RequestingModule, SuggestedModule,
329 IsSystemHeaderDir))
330 return nullptr;
Richard Smith8c71eba2014-03-05 20:51:45 +0000331
Harlan Haskins8d323d12019-08-01 21:31:56 +0000332 return *File;
Richard Smith8c71eba2014-03-05 20:51:45 +0000333}
Chris Lattner8d720d02007-12-17 17:57:27 +0000334
Chris Lattnerf62f7582007-12-17 07:52:39 +0000335/// LookupFile - Lookup the specified file in this search path, returning it
336/// if it exists or returning null if not.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000337const FileEntry *DirectoryLookup::LookupFile(
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000338 StringRef &Filename,
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000339 HeaderSearch &HS,
Taewook Ohf42103c2016-06-13 20:40:21 +0000340 SourceLocation IncludeLoc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000341 SmallVectorImpl<char> *SearchPath,
Douglas Gregor97eec242011-09-15 22:00:41 +0000342 SmallVectorImpl<char> *RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000343 Module *RequestingModule,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000344 ModuleMap::KnownHeader *SuggestedModule,
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000345 bool &InUserSpecifiedSystemFramework,
Volodymyr Sapsai421380a2019-02-05 22:34:55 +0000346 bool &IsFrameworkFound,
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000347 bool &HasBeenMapped,
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000348 SmallVectorImpl<char> &MappedName) const {
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000349 InUserSpecifiedSystemFramework = false;
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000350 HasBeenMapped = false;
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000351
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000352 SmallString<1024> TmpDir;
Chris Lattner712e3872007-12-17 08:13:48 +0000353 if (isNormalDir()) {
354 // Concatenate the requested file onto the directory.
Eli Friedmanf7ca26a2011-07-08 20:17:28 +0000355 TmpDir = getDir()->getName();
356 llvm::sys::path::append(TmpDir, Filename);
Craig Topperd2d442c2014-05-17 23:10:59 +0000357 if (SearchPath) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000358 StringRef SearchPathRef(getDir()->getName());
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000359 SearchPath->clear();
360 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
361 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000362 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000363 RelativePath->clear();
364 RelativePath->append(Filename.begin(), Filename.end());
365 }
Richard Smith8c71eba2014-03-05 20:51:45 +0000366
Taewook Ohf42103c2016-06-13 20:40:21 +0000367 return HS.getFileAndSuggestModule(TmpDir, IncludeLoc, getDir(),
Richard Smith3d5b48c2015-10-16 21:42:56 +0000368 isSystemHeaderDirectory(),
369 RequestingModule, SuggestedModule);
Chris Lattner712e3872007-12-17 08:13:48 +0000370 }
Mike Stump11289f42009-09-09 15:08:12 +0000371
Chris Lattner712e3872007-12-17 08:13:48 +0000372 if (isFramework())
Douglas Gregor97eec242011-09-15 22:00:41 +0000373 return DoFrameworkLookup(Filename, HS, SearchPath, RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000374 RequestingModule, SuggestedModule,
Volodymyr Sapsai421380a2019-02-05 22:34:55 +0000375 InUserSpecifiedSystemFramework, IsFrameworkFound);
Mike Stump11289f42009-09-09 15:08:12 +0000376
Chris Lattner44bd21b2007-12-17 08:17:39 +0000377 assert(isHeaderMap() && "Unknown directory lookup");
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000378 const HeaderMap *HM = getHeaderMap();
379 SmallString<1024> Path;
380 StringRef Dest = HM->lookupFilename(Filename, Path);
381 if (Dest.empty())
Craig Topperd2d442c2014-05-17 23:10:59 +0000382 return nullptr;
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000383
384 const FileEntry *Result;
385
386 // Check if the headermap maps the filename to a framework include
387 // ("Foo.h" -> "Foo/Foo.h"), in which case continue header lookup using the
388 // framework include.
389 if (llvm::sys::path::is_relative(Dest)) {
390 MappedName.clear();
391 MappedName.append(Dest.begin(), Dest.end());
392 Filename = StringRef(MappedName.begin(), MappedName.size());
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000393 HasBeenMapped = true;
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000394 Result = HM->LookupFile(Filename, HS.getFileMgr());
Harlan Haskins8d323d12019-08-01 21:31:56 +0000395 } else if (auto Res = HS.getFileMgr().getFile(Dest)) {
396 Result = *Res;
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000397 } else {
Harlan Haskins8d323d12019-08-01 21:31:56 +0000398 Result = nullptr;
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000399 }
400
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000401 if (Result) {
Craig Topperd2d442c2014-05-17 23:10:59 +0000402 if (SearchPath) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000403 StringRef SearchPathRef(getName());
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000404 SearchPath->clear();
405 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
406 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000407 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000408 RelativePath->clear();
409 RelativePath->append(Filename.begin(), Filename.end());
410 }
411 }
412 return Result;
Chris Lattnerf62f7582007-12-17 07:52:39 +0000413}
414
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000415/// Given a framework directory, find the top-most framework directory.
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000416///
417/// \param FileMgr The file manager to use for directory lookups.
418/// \param DirName The name of the framework directory.
419/// \param SubmodulePath Will be populated with the submodule path from the
420/// returned top-level module to the originally named framework.
421static const DirectoryEntry *
422getTopFrameworkDir(FileManager &FileMgr, StringRef DirName,
423 SmallVectorImpl<std::string> &SubmodulePath) {
424 assert(llvm::sys::path::extension(DirName) == ".framework" &&
425 "Not a framework directory");
426
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000427 // Note: as an egregious but useful hack we use the real path here, because
428 // frameworks moving between top-level frameworks to embedded frameworks tend
429 // to be symlinked, and we base the logical structure of modules on the
430 // physical layout. In particular, we need to deal with crazy includes like
431 //
432 // #include <Foo/Frameworks/Bar.framework/Headers/Wibble.h>
433 //
434 // where 'Bar' used to be embedded in 'Foo', is now a top-level framework
435 // which one should access with, e.g.,
436 //
437 // #include <Bar/Wibble.h>
438 //
439 // Similar issues occur when a top-level framework has moved into an
440 // embedded framework.
Harlan Haskins8d323d12019-08-01 21:31:56 +0000441 const DirectoryEntry *TopFrameworkDir = nullptr;
442 if (auto TopFrameworkDirOrErr = FileMgr.getDirectory(DirName))
443 TopFrameworkDir = *TopFrameworkDirOrErr;
444
445 if (TopFrameworkDir)
446 DirName = FileMgr.getCanonicalName(TopFrameworkDir);
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000447 do {
448 // Get the parent directory name.
449 DirName = llvm::sys::path::parent_path(DirName);
450 if (DirName.empty())
451 break;
452
453 // Determine whether this directory exists.
Harlan Haskins8d323d12019-08-01 21:31:56 +0000454 auto Dir = FileMgr.getDirectory(DirName);
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000455 if (!Dir)
456 break;
457
458 // If this is a framework directory, then we're a subframework of this
459 // framework.
460 if (llvm::sys::path::extension(DirName) == ".framework") {
461 SubmodulePath.push_back(llvm::sys::path::stem(DirName));
Harlan Haskins8d323d12019-08-01 21:31:56 +0000462 TopFrameworkDir = *Dir;
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000463 }
464 } while (true);
465
466 return TopFrameworkDir;
467}
Chris Lattnerf62f7582007-12-17 07:52:39 +0000468
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +0000469static bool needModuleLookup(Module *RequestingModule,
470 bool HasSuggestedModule) {
471 return HasSuggestedModule ||
472 (RequestingModule && RequestingModule->NoUndeclaredIncludes);
473}
474
Chris Lattner712e3872007-12-17 08:13:48 +0000475/// DoFrameworkLookup - Do a lookup of the specified file in the current
476/// DirectoryLookup, which is a framework directory.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000477const FileEntry *DirectoryLookup::DoFrameworkLookup(
Richard Smith3d5b48c2015-10-16 21:42:56 +0000478 StringRef Filename, HeaderSearch &HS, SmallVectorImpl<char> *SearchPath,
479 SmallVectorImpl<char> *RelativePath, Module *RequestingModule,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000480 ModuleMap::KnownHeader *SuggestedModule,
Volodymyr Sapsai421380a2019-02-05 22:34:55 +0000481 bool &InUserSpecifiedSystemFramework, bool &IsFrameworkFound) const {
Chris Lattner712e3872007-12-17 08:13:48 +0000482 FileManager &FileMgr = HS.getFileMgr();
Mike Stump11289f42009-09-09 15:08:12 +0000483
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000484 // Framework names must have a '/' in the filename.
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000485 size_t SlashPos = Filename.find('/');
Craig Topperd2d442c2014-05-17 23:10:59 +0000486 if (SlashPos == StringRef::npos) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000487
Chris Lattner712e3872007-12-17 08:13:48 +0000488 // Find out if this is the home for the specified framework, by checking
Daniel Dunbar17138612012-04-05 17:09:40 +0000489 // HeaderSearch. Possible answers are yes/no and unknown.
Volodymyr Sapsai421380a2019-02-05 22:34:55 +0000490 FrameworkCacheEntry &CacheEntry =
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000491 HS.LookupFrameworkCache(Filename.substr(0, SlashPos));
Mike Stump11289f42009-09-09 15:08:12 +0000492
Chris Lattner712e3872007-12-17 08:13:48 +0000493 // If it is known and in some other directory, fail.
Daniel Dunbar17138612012-04-05 17:09:40 +0000494 if (CacheEntry.Directory && CacheEntry.Directory != getFrameworkDir())
Craig Topperd2d442c2014-05-17 23:10:59 +0000495 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000496
Chris Lattner712e3872007-12-17 08:13:48 +0000497 // Otherwise, construct the path to this framework dir.
Mike Stump11289f42009-09-09 15:08:12 +0000498
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000499 // FrameworkName = "/System/Library/Frameworks/"
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000500 SmallString<1024> FrameworkName;
Chris Lattner712e3872007-12-17 08:13:48 +0000501 FrameworkName += getFrameworkDir()->getName();
Chris Lattnerb201d9b2006-10-30 05:09:49 +0000502 if (FrameworkName.empty() || FrameworkName.back() != '/')
503 FrameworkName.push_back('/');
Mike Stump11289f42009-09-09 15:08:12 +0000504
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000505 // FrameworkName = "/System/Library/Frameworks/Cocoa"
Douglas Gregor56c64012011-11-17 01:41:17 +0000506 StringRef ModuleName(Filename.begin(), SlashPos);
507 FrameworkName += ModuleName;
Mike Stump11289f42009-09-09 15:08:12 +0000508
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000509 // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/"
510 FrameworkName += ".framework/";
Mike Stump11289f42009-09-09 15:08:12 +0000511
Daniel Dunbar17138612012-04-05 17:09:40 +0000512 // If the cache entry was unresolved, populate it now.
Craig Topperd2d442c2014-05-17 23:10:59 +0000513 if (!CacheEntry.Directory) {
Chris Lattner712e3872007-12-17 08:13:48 +0000514 HS.IncrementFrameworkLookupCount();
Mike Stump11289f42009-09-09 15:08:12 +0000515
Chris Lattner5ed76da2006-10-22 07:24:13 +0000516 // If the framework dir doesn't exist, we fail.
Harlan Haskins8d323d12019-08-01 21:31:56 +0000517 auto Dir = FileMgr.getDirectory(FrameworkName);
Craig Topperd2d442c2014-05-17 23:10:59 +0000518 if (!Dir) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000519
Chris Lattner5ed76da2006-10-22 07:24:13 +0000520 // Otherwise, if it does, remember that this is the right direntry for this
521 // framework.
Daniel Dunbar17138612012-04-05 17:09:40 +0000522 CacheEntry.Directory = getFrameworkDir();
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000523
524 // If this is a user search directory, check if the framework has been
525 // user-specified as a system framework.
526 if (getDirCharacteristic() == SrcMgr::C_User) {
527 SmallString<1024> SystemFrameworkMarker(FrameworkName);
528 SystemFrameworkMarker += ".system_framework";
Yaron Keren92e1b622015-03-18 10:17:07 +0000529 if (llvm::sys::fs::exists(SystemFrameworkMarker)) {
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000530 CacheEntry.IsUserSpecifiedSystemFramework = true;
531 }
532 }
Chris Lattner5ed76da2006-10-22 07:24:13 +0000533 }
Mike Stump11289f42009-09-09 15:08:12 +0000534
Volodymyr Sapsai421380a2019-02-05 22:34:55 +0000535 // Set out flags.
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000536 InUserSpecifiedSystemFramework = CacheEntry.IsUserSpecifiedSystemFramework;
Volodymyr Sapsai421380a2019-02-05 22:34:55 +0000537 IsFrameworkFound = CacheEntry.Directory;
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000538
Craig Topperd2d442c2014-05-17 23:10:59 +0000539 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000540 RelativePath->clear();
541 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
542 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000543
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000544 // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"
Chris Lattnerb201d9b2006-10-30 05:09:49 +0000545 unsigned OrigSize = FrameworkName.size();
Mike Stump11289f42009-09-09 15:08:12 +0000546
Chris Lattnerb201d9b2006-10-30 05:09:49 +0000547 FrameworkName += "Headers/";
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000548
Craig Topperd2d442c2014-05-17 23:10:59 +0000549 if (SearchPath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000550 SearchPath->clear();
551 // Without trailing '/'.
552 SearchPath->append(FrameworkName.begin(), FrameworkName.end()-1);
553 }
554
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000555 FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end());
Harlan Haskins8d323d12019-08-01 21:31:56 +0000556
557 const FileEntry *FE = nullptr;
558 if (auto File = FileMgr.getFile(FrameworkName, /*OpenFile=*/!SuggestedModule))
559 FE = *File;
560
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000561 if (!FE) {
562 // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"
563 const char *Private = "Private";
564 FrameworkName.insert(FrameworkName.begin()+OrigSize, Private,
565 Private+strlen(Private));
Craig Topperd2d442c2014-05-17 23:10:59 +0000566 if (SearchPath)
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000567 SearchPath->insert(SearchPath->begin()+OrigSize, Private,
568 Private+strlen(Private));
569
Harlan Haskins8d323d12019-08-01 21:31:56 +0000570 if (auto File = FileMgr.getFile(FrameworkName,
571 /*OpenFile=*/!SuggestedModule))
572 FE = *File;
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000573 }
Mike Stump11289f42009-09-09 15:08:12 +0000574
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000575 // If we found the header and are allowed to suggest a module, do so now.
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +0000576 if (FE && needModuleLookup(RequestingModule, SuggestedModule)) {
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000577 // Find the framework in which this header occurs.
Ben Langmuiref914b82014-05-15 16:20:33 +0000578 StringRef FrameworkPath = FE->getDir()->getName();
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000579 bool FoundFramework = false;
580 do {
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000581 // Determine whether this directory exists.
Harlan Haskins8d323d12019-08-01 21:31:56 +0000582 auto Dir = FileMgr.getDirectory(FrameworkPath);
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000583 if (!Dir)
584 break;
585
586 // If this is a framework directory, then we're a subframework of this
587 // framework.
588 if (llvm::sys::path::extension(FrameworkPath) == ".framework") {
589 FoundFramework = true;
590 break;
591 }
Ben Langmuiref914b82014-05-15 16:20:33 +0000592
593 // Get the parent directory name.
594 FrameworkPath = llvm::sys::path::parent_path(FrameworkPath);
595 if (FrameworkPath.empty())
596 break;
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000597 } while (true);
598
Richard Smith3d5b48c2015-10-16 21:42:56 +0000599 bool IsSystem = getDirCharacteristic() != SrcMgr::C_User;
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000600 if (FoundFramework) {
Richard Smith3d5b48c2015-10-16 21:42:56 +0000601 if (!HS.findUsableModuleForFrameworkHeader(
602 FE, FrameworkPath, RequestingModule, SuggestedModule, IsSystem))
603 return nullptr;
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000604 } else {
Richard Smith3d5b48c2015-10-16 21:42:56 +0000605 if (!HS.findUsableModuleForHeader(FE, getDir(), RequestingModule,
606 SuggestedModule, IsSystem))
607 return nullptr;
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000608 }
609 }
Douglas Gregor97eec242011-09-15 22:00:41 +0000610 return FE;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000611}
612
Douglas Gregor89929282012-01-30 06:01:29 +0000613void HeaderSearch::setTarget(const TargetInfo &Target) {
614 ModMap.setTarget(Target);
615}
616
Chris Lattner712e3872007-12-17 08:13:48 +0000617//===----------------------------------------------------------------------===//
618// Header File Location.
619//===----------------------------------------------------------------------===//
620
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000621/// Return true with a diagnostic if the file that MSVC would have found
Reid Klecknera97d4c02014-02-18 23:49:24 +0000622/// fails to match the one that Clang would have found with MSVC header search
623/// disabled.
624static bool checkMSVCHeaderSearch(DiagnosticsEngine &Diags,
625 const FileEntry *MSFE, const FileEntry *FE,
626 SourceLocation IncludeLoc) {
627 if (MSFE && FE != MSFE) {
628 Diags.Report(IncludeLoc, diag::ext_pp_include_search_ms) << MSFE->getName();
629 return true;
630 }
631 return false;
632}
Chris Lattner712e3872007-12-17 08:13:48 +0000633
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000634static const char *copyString(StringRef Str, llvm::BumpPtrAllocator &Alloc) {
635 assert(!Str.empty());
636 char *CopyStr = Alloc.Allocate<char>(Str.size()+1);
637 std::copy(Str.begin(), Str.end(), CopyStr);
638 CopyStr[Str.size()] = '\0';
639 return CopyStr;
640}
641
Bruno Cardoso Lopes1b3b69f2018-06-25 22:24:17 +0000642static bool isFrameworkStylePath(StringRef Path, bool &IsPrivateHeader,
Bruno Cardoso Lopesa9c51fe2018-06-22 18:05:17 +0000643 SmallVectorImpl<char> &FrameworkName) {
644 using namespace llvm::sys;
645 path::const_iterator I = path::begin(Path);
646 path::const_iterator E = path::end(Path);
Bruno Cardoso Lopes1b3b69f2018-06-25 22:24:17 +0000647 IsPrivateHeader = false;
Bruno Cardoso Lopesa9c51fe2018-06-22 18:05:17 +0000648
649 // Detect different types of framework style paths:
650 //
651 // ...Foo.framework/{Headers,PrivateHeaders}
652 // ...Foo.framework/Versions/{A,Current}/{Headers,PrivateHeaders}
653 // ...Foo.framework/Frameworks/Nested.framework/{Headers,PrivateHeaders}
654 // ...<other variations with 'Versions' like in the above path>
655 //
656 // and some other variations among these lines.
657 int FoundComp = 0;
658 while (I != E) {
Bruno Cardoso Lopes1b3b69f2018-06-25 22:24:17 +0000659 if (*I == "Headers")
660 ++FoundComp;
Bruno Cardoso Lopesa9c51fe2018-06-22 18:05:17 +0000661 if (I->endswith(".framework")) {
662 FrameworkName.append(I->begin(), I->end());
663 ++FoundComp;
664 }
Bruno Cardoso Lopes1b3b69f2018-06-25 22:24:17 +0000665 if (*I == "PrivateHeaders") {
Bruno Cardoso Lopesa9c51fe2018-06-22 18:05:17 +0000666 ++FoundComp;
Bruno Cardoso Lopes1b3b69f2018-06-25 22:24:17 +0000667 IsPrivateHeader = true;
668 }
Bruno Cardoso Lopesa9c51fe2018-06-22 18:05:17 +0000669 ++I;
670 }
671
Erik Pilkingtonabacc252018-09-20 19:00:03 +0000672 return !FrameworkName.empty() && FoundComp >= 2;
Bruno Cardoso Lopesa9c51fe2018-06-22 18:05:17 +0000673}
674
675static void
676diagnoseFrameworkInclude(DiagnosticsEngine &Diags, SourceLocation IncludeLoc,
677 StringRef Includer, StringRef IncludeFilename,
678 const FileEntry *IncludeFE, bool isAngled = false,
679 bool FoundByHeaderMap = false) {
Bruno Cardoso Lopes1b3b69f2018-06-25 22:24:17 +0000680 bool IsIncluderPrivateHeader = false;
Bruno Cardoso Lopesa9c51fe2018-06-22 18:05:17 +0000681 SmallString<128> FromFramework, ToFramework;
Bruno Cardoso Lopes1b3b69f2018-06-25 22:24:17 +0000682 if (!isFrameworkStylePath(Includer, IsIncluderPrivateHeader, FromFramework))
Bruno Cardoso Lopesa9c51fe2018-06-22 18:05:17 +0000683 return;
Bruno Cardoso Lopes1b3b69f2018-06-25 22:24:17 +0000684 bool IsIncludeePrivateHeader = false;
685 bool IsIncludeeInFramework = isFrameworkStylePath(
686 IncludeFE->getName(), IsIncludeePrivateHeader, ToFramework);
Bruno Cardoso Lopesa9c51fe2018-06-22 18:05:17 +0000687
688 if (!isAngled && !FoundByHeaderMap) {
689 SmallString<128> NewInclude("<");
690 if (IsIncludeeInFramework) {
691 NewInclude += StringRef(ToFramework).drop_back(10); // drop .framework
692 NewInclude += "/";
693 }
694 NewInclude += IncludeFilename;
695 NewInclude += ">";
696 Diags.Report(IncludeLoc, diag::warn_quoted_include_in_framework_header)
697 << IncludeFilename
698 << FixItHint::CreateReplacement(IncludeLoc, NewInclude);
699 }
Bruno Cardoso Lopes1b3b69f2018-06-25 22:24:17 +0000700
701 // Headers in Foo.framework/Headers should not include headers
702 // from Foo.framework/PrivateHeaders, since this violates public/private
703 // API boundaries and can cause modular dependency cycles.
704 if (!IsIncluderPrivateHeader && IsIncludeeInFramework &&
705 IsIncludeePrivateHeader && FromFramework == ToFramework)
706 Diags.Report(IncludeLoc, diag::warn_framework_include_private_from_public)
707 << IncludeFilename;
Bruno Cardoso Lopesa9c51fe2018-06-22 18:05:17 +0000708}
709
James Dennettc07ab2c2012-06-20 00:56:32 +0000710/// LookupFile - Given a "foo" or \<foo> reference, look up the indicated file,
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000711/// return null on failure. isAngled indicates whether the file reference is
Will Wilson0fafd342013-12-27 19:46:16 +0000712/// for system \#include's or not (i.e. using <> instead of ""). Includers, if
713/// non-empty, indicates where the \#including file(s) are, in case a relative
714/// search is needed. Microsoft mode will pass all \#including files.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000715const FileEntry *HeaderSearch::LookupFile(
Will Wilson0fafd342013-12-27 19:46:16 +0000716 StringRef Filename, SourceLocation IncludeLoc, bool isAngled,
717 const DirectoryLookup *FromDir, const DirectoryLookup *&CurDir,
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000718 ArrayRef<std::pair<const FileEntry *, const DirectoryEntry *>> Includers,
719 SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000720 Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule,
Volodymyr Sapsai421380a2019-02-05 22:34:55 +0000721 bool *IsMapped, bool *IsFrameworkFound, bool SkipCache,
722 bool BuildSystemModule) {
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000723 if (IsMapped)
724 *IsMapped = false;
725
Volodymyr Sapsai421380a2019-02-05 22:34:55 +0000726 if (IsFrameworkFound)
727 *IsFrameworkFound = false;
728
Douglas Gregor97eec242011-09-15 22:00:41 +0000729 if (SuggestedModule)
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000730 *SuggestedModule = ModuleMap::KnownHeader();
Fangrui Song6907ce22018-07-30 19:24:48 +0000731
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000732 // If 'Filename' is absolute, check to see if it exists and no searching.
Michael J. Spencerf28df4c2010-12-17 21:22:22 +0000733 if (llvm::sys::path::is_absolute(Filename)) {
Craig Topperd2d442c2014-05-17 23:10:59 +0000734 CurDir = nullptr;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000735
736 // If this was an #include_next "/absolute/file", fail.
Craig Topperd2d442c2014-05-17 23:10:59 +0000737 if (FromDir) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000738
Craig Topperd2d442c2014-05-17 23:10:59 +0000739 if (SearchPath)
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000740 SearchPath->clear();
Craig Topperd2d442c2014-05-17 23:10:59 +0000741 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000742 RelativePath->clear();
743 RelativePath->append(Filename.begin(), Filename.end());
744 }
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000745 // Otherwise, just return the file.
Taewook Ohf42103c2016-06-13 20:40:21 +0000746 return getFileAndSuggestModule(Filename, IncludeLoc, nullptr,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000747 /*IsSystemHeaderDir*/false,
748 RequestingModule, SuggestedModule);
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000749 }
Mike Stump11289f42009-09-09 15:08:12 +0000750
Reid Klecknera97d4c02014-02-18 23:49:24 +0000751 // This is the header that MSVC's header search would have found.
Craig Topperd2d442c2014-05-17 23:10:59 +0000752 const FileEntry *MSFE = nullptr;
Richard Smith8c71eba2014-03-05 20:51:45 +0000753 ModuleMap::KnownHeader MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000754
Douglas Gregor9f93e382011-07-28 04:45:53 +0000755 // Unless disabled, check to see if the file is in the #includer's
Will Wilson0fafd342013-12-27 19:46:16 +0000756 // directory. This cannot be based on CurDir, because each includer could be
757 // a #include of a subdirectory (#include "foo/bar.h") and a subsequent
758 // include of "baz.h" should resolve to "whatever/foo/baz.h".
Chris Lattnerf62f7582007-12-17 07:52:39 +0000759 // This search is not done for <> headers.
Will Wilson0fafd342013-12-27 19:46:16 +0000760 if (!Includers.empty() && !isAngled && !NoCurDirSearch) {
NAKAMURA Takumi9cb62642013-12-10 02:36:28 +0000761 SmallString<1024> TmpDir;
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000762 bool First = true;
763 for (const auto &IncluderAndDir : Includers) {
764 const FileEntry *Includer = IncluderAndDir.first;
765
Will Wilson0fafd342013-12-27 19:46:16 +0000766 // Concatenate the requested file onto the directory.
Nikola Smiljaniccf385dc2015-05-08 06:02:37 +0000767 // FIXME: Portability. Filename concatenation should be in sys::Path.
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000768 TmpDir = IncluderAndDir.second->getName();
Nikola Smiljaniccf385dc2015-05-08 06:02:37 +0000769 TmpDir.push_back('/');
770 TmpDir.append(Filename.begin(), Filename.end());
Richard Smith8c71eba2014-03-05 20:51:45 +0000771
Richard Smith6f548ec2014-03-06 18:08:08 +0000772 // FIXME: We don't cache the result of getFileInfo across the call to
773 // getFileAndSuggestModule, because it's a reference to an element of
774 // a container that could be reallocated across this call.
Richard Smith3c1a41a2014-12-02 00:08:08 +0000775 //
Manman Rene4a5d372016-05-17 02:15:12 +0000776 // If we have no includer, that means we're processing a #include
Richard Smith3c1a41a2014-12-02 00:08:08 +0000777 // from a module build. We should treat this as a system header if we're
778 // building a [system] module.
Richard Smith6f548ec2014-03-06 18:08:08 +0000779 bool IncluderIsSystemHeader =
Manman Rene39c8142016-05-17 18:04:38 +0000780 Includer ? getFileInfo(Includer).DirInfo != SrcMgr::C_User :
781 BuildSystemModule;
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000782 if (const FileEntry *FE = getFileAndSuggestModule(
Taewook Ohf42103c2016-06-13 20:40:21 +0000783 TmpDir, IncludeLoc, IncluderAndDir.second, IncluderIsSystemHeader,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000784 RequestingModule, SuggestedModule)) {
Richard Smith3c1a41a2014-12-02 00:08:08 +0000785 if (!Includer) {
786 assert(First && "only first includer can have no file");
787 return FE;
788 }
789
Will Wilson0fafd342013-12-27 19:46:16 +0000790 // Leave CurDir unset.
791 // This file is a system header or C++ unfriendly if the old file is.
792 //
793 // Note that we only use one of FromHFI/ToHFI at once, due to potential
794 // reallocation of the underlying vector potentially making the first
795 // reference binding dangling.
Richard Smith6f548ec2014-03-06 18:08:08 +0000796 HeaderFileInfo &FromHFI = getFileInfo(Includer);
Will Wilson0fafd342013-12-27 19:46:16 +0000797 unsigned DirInfo = FromHFI.DirInfo;
798 bool IndexHeaderMapHeader = FromHFI.IndexHeaderMapHeader;
799 StringRef Framework = FromHFI.Framework;
Douglas Gregor03b5ebe2012-08-13 15:47:39 +0000800
Will Wilson0fafd342013-12-27 19:46:16 +0000801 HeaderFileInfo &ToHFI = getFileInfo(FE);
802 ToHFI.DirInfo = DirInfo;
803 ToHFI.IndexHeaderMapHeader = IndexHeaderMapHeader;
804 ToHFI.Framework = Framework;
Douglas Gregor03b5ebe2012-08-13 15:47:39 +0000805
Craig Topperd2d442c2014-05-17 23:10:59 +0000806 if (SearchPath) {
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000807 StringRef SearchPathRef(IncluderAndDir.second->getName());
Will Wilson0fafd342013-12-27 19:46:16 +0000808 SearchPath->clear();
809 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
810 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000811 if (RelativePath) {
Will Wilson0fafd342013-12-27 19:46:16 +0000812 RelativePath->clear();
813 RelativePath->append(Filename.begin(), Filename.end());
814 }
Bruno Cardoso Lopesa9c51fe2018-06-22 18:05:17 +0000815 if (First) {
816 diagnoseFrameworkInclude(Diags, IncludeLoc,
817 IncluderAndDir.second->getName(), Filename,
818 FE);
Reid Klecknera97d4c02014-02-18 23:49:24 +0000819 return FE;
Bruno Cardoso Lopesa9c51fe2018-06-22 18:05:17 +0000820 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000821
822 // Otherwise, we found the path via MSVC header search rules. If
823 // -Wmsvc-include is enabled, we have to keep searching to see if we
824 // would've found this header in -I or -isystem directories.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +0000825 if (Diags.isIgnored(diag::ext_pp_include_search_ms, IncludeLoc)) {
Reid Klecknera97d4c02014-02-18 23:49:24 +0000826 return FE;
827 } else {
828 MSFE = FE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000829 if (SuggestedModule) {
830 MSSuggestedModule = *SuggestedModule;
831 *SuggestedModule = ModuleMap::KnownHeader();
832 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000833 break;
834 }
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000835 }
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000836 First = false;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000837 }
838 }
Mike Stump11289f42009-09-09 15:08:12 +0000839
Craig Topperd2d442c2014-05-17 23:10:59 +0000840 CurDir = nullptr;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000841
842 // If this is a system #include, ignore the user #include locs.
Nico Weber3b1d1212011-05-24 04:31:14 +0000843 unsigned i = isAngled ? AngledDirIdx : 0;
Mike Stump11289f42009-09-09 15:08:12 +0000844
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000845 // If this is a #include_next request, start searching after the directory the
846 // file was found in.
847 if (FromDir)
848 i = FromDir-&SearchDirs[0];
Mike Stump11289f42009-09-09 15:08:12 +0000849
Chris Lattnerd4275422007-07-22 07:28:00 +0000850 // Cache all of the lookups performed by this method. Many headers are
851 // multiply included, and the "pragma once" optimization prevents them from
852 // being relex/pp'd, but they would still have to search through a
853 // (potentially huge) series of SearchDirs to find it.
David Blaikie13156b62014-11-19 03:06:06 +0000854 LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename];
Chris Lattnerd4275422007-07-22 07:28:00 +0000855
856 // If the entry has been previously looked up, the first value will be
857 // non-zero. If the value is equal to i (the start point of our search), then
858 // this is a matching hit.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000859 if (!SkipCache && CacheLookup.StartIdx == i+1) {
Chris Lattnerd4275422007-07-22 07:28:00 +0000860 // Skip querying potentially lots of directories for this lookup.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000861 i = CacheLookup.HitIdx;
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000862 if (CacheLookup.MappedName) {
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000863 Filename = CacheLookup.MappedName;
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000864 if (IsMapped)
865 *IsMapped = true;
866 }
Chris Lattnerd4275422007-07-22 07:28:00 +0000867 } else {
868 // Otherwise, this is the first query, or the previous query didn't match
869 // our search start. We will fill in our found location below, so prime the
870 // start point value.
Argyrios Kyrtzidis7bd78a92014-03-29 03:22:54 +0000871 CacheLookup.reset(/*StartIdx=*/i+1);
Chris Lattnerd4275422007-07-22 07:28:00 +0000872 }
Mike Stump11289f42009-09-09 15:08:12 +0000873
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000874 SmallString<64> MappedName;
875
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000876 // Check each directory in sequence to see if it contains this file.
877 for (; i != SearchDirs.size(); ++i) {
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000878 bool InUserSpecifiedSystemFramework = false;
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000879 bool HasBeenMapped = false;
Volodymyr Sapsai421380a2019-02-05 22:34:55 +0000880 bool IsFrameworkFoundInDir = false;
Richard Smith3d5b48c2015-10-16 21:42:56 +0000881 const FileEntry *FE = SearchDirs[i].LookupFile(
Taewook Ohf42103c2016-06-13 20:40:21 +0000882 Filename, *this, IncludeLoc, SearchPath, RelativePath, RequestingModule,
Volodymyr Sapsai421380a2019-02-05 22:34:55 +0000883 SuggestedModule, InUserSpecifiedSystemFramework, IsFrameworkFoundInDir,
884 HasBeenMapped, MappedName);
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000885 if (HasBeenMapped) {
886 CacheLookup.MappedName =
887 copyString(Filename, LookupFileCache.getAllocator());
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000888 if (IsMapped)
889 *IsMapped = true;
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000890 }
Volodymyr Sapsai421380a2019-02-05 22:34:55 +0000891 if (IsFrameworkFound)
Volodymyr Sapsaie32ff092019-05-27 19:15:30 +0000892 // Because we keep a filename remapped for subsequent search directory
893 // lookups, ignore IsFrameworkFoundInDir after the first remapping and not
894 // just for remapping in a current search directory.
895 *IsFrameworkFound |= (IsFrameworkFoundInDir && !CacheLookup.MappedName);
Chris Lattner712e3872007-12-17 08:13:48 +0000896 if (!FE) continue;
Mike Stump11289f42009-09-09 15:08:12 +0000897
Chris Lattner712e3872007-12-17 08:13:48 +0000898 CurDir = &SearchDirs[i];
Mike Stump11289f42009-09-09 15:08:12 +0000899
Chris Lattner712e3872007-12-17 08:13:48 +0000900 // This file is a system header or C++ unfriendly if the dir is.
Douglas Gregor9f93e382011-07-28 04:45:53 +0000901 HeaderFileInfo &HFI = getFileInfo(FE);
902 HFI.DirInfo = CurDir->getDirCharacteristic();
Mike Stump11289f42009-09-09 15:08:12 +0000903
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000904 // If the directory characteristic is User but this framework was
905 // user-specified to be treated as a system framework, promote the
906 // characteristic.
907 if (HFI.DirInfo == SrcMgr::C_User && InUserSpecifiedSystemFramework)
908 HFI.DirInfo = SrcMgr::C_System;
909
Richard Smith8acadcb2012-06-13 20:27:03 +0000910 // If the filename matches a known system header prefix, override
911 // whether the file is a system header.
Richard Trieu871f5f32012-06-13 20:52:36 +0000912 for (unsigned j = SystemHeaderPrefixes.size(); j; --j) {
913 if (Filename.startswith(SystemHeaderPrefixes[j-1].first)) {
914 HFI.DirInfo = SystemHeaderPrefixes[j-1].second ? SrcMgr::C_System
Richard Smith8acadcb2012-06-13 20:27:03 +0000915 : SrcMgr::C_User;
916 break;
917 }
918 }
919
Douglas Gregor9f93e382011-07-28 04:45:53 +0000920 // If this file is found in a header map and uses the framework style of
921 // includes, then this header is part of a framework we're building.
922 if (CurDir->isIndexHeaderMap()) {
923 size_t SlashPos = Filename.find('/');
924 if (SlashPos != StringRef::npos) {
925 HFI.IndexHeaderMapHeader = 1;
Fangrui Song6907ce22018-07-30 19:24:48 +0000926 HFI.Framework = getUniqueFrameworkName(StringRef(Filename.begin(),
Douglas Gregor9f93e382011-07-28 04:45:53 +0000927 SlashPos));
928 }
929 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000930
Richard Smith8c71eba2014-03-05 20:51:45 +0000931 if (checkMSVCHeaderSearch(Diags, MSFE, FE, IncludeLoc)) {
932 if (SuggestedModule)
933 *SuggestedModule = MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000934 return MSFE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000935 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000936
Bruno Cardoso Lopesa9c51fe2018-06-22 18:05:17 +0000937 bool FoundByHeaderMap = !IsMapped ? false : *IsMapped;
938 if (!Includers.empty())
939 diagnoseFrameworkInclude(Diags, IncludeLoc,
940 Includers.front().second->getName(), Filename,
941 FE, isAngled, FoundByHeaderMap);
942
Chris Lattner712e3872007-12-17 08:13:48 +0000943 // Remember this location for the next lookup we do.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000944 CacheLookup.HitIdx = i;
Chris Lattner712e3872007-12-17 08:13:48 +0000945 return FE;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000946 }
Mike Stump11289f42009-09-09 15:08:12 +0000947
Douglas Gregord8575e12011-07-30 06:28:34 +0000948 // If we are including a file with a quoted include "foo.h" from inside
949 // a header in a framework that is currently being built, and we couldn't
950 // resolve "foo.h" any other way, change the include to <Foo/foo.h>, where
951 // "Foo" is the name of the framework in which the including header was found.
Richard Smith3c1a41a2014-12-02 00:08:08 +0000952 if (!Includers.empty() && Includers.front().first && !isAngled &&
Will Wilson0fafd342013-12-27 19:46:16 +0000953 Filename.find('/') == StringRef::npos) {
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000954 HeaderFileInfo &IncludingHFI = getFileInfo(Includers.front().first);
Douglas Gregord8575e12011-07-30 06:28:34 +0000955 if (IncludingHFI.IndexHeaderMapHeader) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000956 SmallString<128> ScratchFilename;
Douglas Gregord8575e12011-07-30 06:28:34 +0000957 ScratchFilename += IncludingHFI.Framework;
958 ScratchFilename += '/';
959 ScratchFilename += Filename;
Will Wilson0fafd342013-12-27 19:46:16 +0000960
Volodymyr Sapsai421380a2019-02-05 22:34:55 +0000961 const FileEntry *FE = LookupFile(
962 ScratchFilename, IncludeLoc, /*isAngled=*/true, FromDir, CurDir,
963 Includers.front(), SearchPath, RelativePath, RequestingModule,
964 SuggestedModule, IsMapped, /*IsFrameworkFound=*/nullptr);
Reid Klecknera97d4c02014-02-18 23:49:24 +0000965
Richard Smith8c71eba2014-03-05 20:51:45 +0000966 if (checkMSVCHeaderSearch(Diags, MSFE, FE, IncludeLoc)) {
967 if (SuggestedModule)
968 *SuggestedModule = MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000969 return MSFE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000970 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000971
David Blaikie3c8c46e2014-11-19 05:48:40 +0000972 LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename];
David Blaikie13156b62014-11-19 03:06:06 +0000973 CacheLookup.HitIdx = LookupFileCache[ScratchFilename].HitIdx;
Richard Smith8c71eba2014-03-05 20:51:45 +0000974 // FIXME: SuggestedModule.
Reid Klecknera97d4c02014-02-18 23:49:24 +0000975 return FE;
Douglas Gregord8575e12011-07-30 06:28:34 +0000976 }
977 }
978
Craig Topperd2d442c2014-05-17 23:10:59 +0000979 if (checkMSVCHeaderSearch(Diags, MSFE, nullptr, IncludeLoc)) {
Richard Smith8c71eba2014-03-05 20:51:45 +0000980 if (SuggestedModule)
981 *SuggestedModule = MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000982 return MSFE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000983 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000984
Chris Lattnerd4275422007-07-22 07:28:00 +0000985 // Otherwise, didn't find it. Remember we didn't find this.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000986 CacheLookup.HitIdx = SearchDirs.size();
Craig Topperd2d442c2014-05-17 23:10:59 +0000987 return nullptr;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000988}
989
Chris Lattner63dd32b2006-10-20 04:42:40 +0000990/// LookupSubframeworkHeader - Look up a subframework for the specified
James Dennettc07ab2c2012-06-20 00:56:32 +0000991/// \#include file. For example, if \#include'ing <HIToolbox/HIToolbox.h> from
Chris Lattner63dd32b2006-10-20 04:42:40 +0000992/// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
993/// is a subframework within Carbon.framework. If so, return the FileEntry
994/// for the designated file, otherwise return null.
995const FileEntry *HeaderSearch::
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000996LookupSubframeworkHeader(StringRef Filename,
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000997 const FileEntry *ContextFileEnt,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000998 SmallVectorImpl<char> *SearchPath,
Douglas Gregorf5f94522013-02-08 00:10:48 +0000999 SmallVectorImpl<char> *RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +00001000 Module *RequestingModule,
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001001 ModuleMap::KnownHeader *SuggestedModule) {
Chris Lattner12261882008-02-01 05:34:02 +00001002 assert(ContextFileEnt && "No context file?");
Mike Stump11289f42009-09-09 15:08:12 +00001003
Chris Lattner63dd32b2006-10-20 04:42:40 +00001004 // Framework names must have a '/' in the filename. Find it.
Douglas Gregor5ca04bd2011-12-09 16:48:01 +00001005 // FIXME: Should we permit '\' on Windows?
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001006 size_t SlashPos = Filename.find('/');
Craig Topperd2d442c2014-05-17 23:10:59 +00001007 if (SlashPos == StringRef::npos) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001008
Chris Lattner63dd32b2006-10-20 04:42:40 +00001009 // Look up the base framework name of the ContextFileEnt.
Mehdi Amini004b9c72016-10-10 22:52:47 +00001010 StringRef ContextName = ContextFileEnt->getName();
Mike Stump11289f42009-09-09 15:08:12 +00001011
Chris Lattner63dd32b2006-10-20 04:42:40 +00001012 // If the context info wasn't a framework, couldn't be a subframework.
Douglas Gregor5ca04bd2011-12-09 16:48:01 +00001013 const unsigned DotFrameworkLen = 10;
Mehdi Amini004b9c72016-10-10 22:52:47 +00001014 auto FrameworkPos = ContextName.find(".framework");
1015 if (FrameworkPos == StringRef::npos ||
1016 (ContextName[FrameworkPos + DotFrameworkLen] != '/' &&
1017 ContextName[FrameworkPos + DotFrameworkLen] != '\\'))
Craig Topperd2d442c2014-05-17 23:10:59 +00001018 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001019
Mehdi Amini004b9c72016-10-10 22:52:47 +00001020 SmallString<1024> FrameworkName(ContextName.data(), ContextName.data() +
1021 FrameworkPos +
1022 DotFrameworkLen + 1);
Chris Lattner5ed76da2006-10-22 07:24:13 +00001023
Chris Lattner63dd32b2006-10-20 04:42:40 +00001024 // Append Frameworks/HIToolbox.framework/
1025 FrameworkName += "Frameworks/";
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001026 FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos);
Chris Lattner63dd32b2006-10-20 04:42:40 +00001027 FrameworkName += ".framework/";
Chris Lattner577377e2006-10-20 04:55:45 +00001028
David Blaikie13156b62014-11-19 03:06:06 +00001029 auto &CacheLookup =
1030 *FrameworkMap.insert(std::make_pair(Filename.substr(0, SlashPos),
1031 FrameworkCacheEntry())).first;
Mike Stump11289f42009-09-09 15:08:12 +00001032
Chris Lattner5ed76da2006-10-22 07:24:13 +00001033 // Some other location?
David Blaikie13156b62014-11-19 03:06:06 +00001034 if (CacheLookup.second.Directory &&
1035 CacheLookup.first().size() == FrameworkName.size() &&
1036 memcmp(CacheLookup.first().data(), &FrameworkName[0],
1037 CacheLookup.first().size()) != 0)
Craig Topperd2d442c2014-05-17 23:10:59 +00001038 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001039
Chris Lattner5ed76da2006-10-22 07:24:13 +00001040 // Cache subframework.
David Blaikie13156b62014-11-19 03:06:06 +00001041 if (!CacheLookup.second.Directory) {
Chris Lattner5ed76da2006-10-22 07:24:13 +00001042 ++NumSubFrameworkLookups;
Mike Stump11289f42009-09-09 15:08:12 +00001043
Chris Lattner5ed76da2006-10-22 07:24:13 +00001044 // If the framework dir doesn't exist, we fail.
Harlan Haskins8d323d12019-08-01 21:31:56 +00001045 auto Dir = FileMgr.getDirectory(FrameworkName);
Craig Topperd2d442c2014-05-17 23:10:59 +00001046 if (!Dir) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001047
Chris Lattner5ed76da2006-10-22 07:24:13 +00001048 // Otherwise, if it does, remember that this is the right direntry for this
1049 // framework.
Harlan Haskins8d323d12019-08-01 21:31:56 +00001050 CacheLookup.second.Directory = *Dir;
Chris Lattner5ed76da2006-10-22 07:24:13 +00001051 }
Mike Stump11289f42009-09-09 15:08:12 +00001052
Craig Topperd2d442c2014-05-17 23:10:59 +00001053 const FileEntry *FE = nullptr;
Chris Lattner577377e2006-10-20 04:55:45 +00001054
Craig Topperd2d442c2014-05-17 23:10:59 +00001055 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +00001056 RelativePath->clear();
1057 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
1058 }
1059
Chris Lattner63dd32b2006-10-20 04:42:40 +00001060 // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001061 SmallString<1024> HeadersFilename(FrameworkName);
Chris Lattner43fd42e2006-10-30 03:40:58 +00001062 HeadersFilename += "Headers/";
Craig Topperd2d442c2014-05-17 23:10:59 +00001063 if (SearchPath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +00001064 SearchPath->clear();
1065 // Without trailing '/'.
1066 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
1067 }
1068
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001069 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
Harlan Haskins8d323d12019-08-01 21:31:56 +00001070 if (auto File = FileMgr.getFile(HeadersFilename, /*OpenFile=*/true))
1071 FE = *File;
1072
1073 if (!FE) {
Chris Lattner63dd32b2006-10-20 04:42:40 +00001074 // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
Chris Lattner43fd42e2006-10-30 03:40:58 +00001075 HeadersFilename = FrameworkName;
1076 HeadersFilename += "PrivateHeaders/";
Craig Topperd2d442c2014-05-17 23:10:59 +00001077 if (SearchPath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +00001078 SearchPath->clear();
1079 // Without trailing '/'.
1080 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
1081 }
1082
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001083 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
Harlan Haskins8d323d12019-08-01 21:31:56 +00001084 if (auto File = FileMgr.getFile(HeadersFilename, /*OpenFile=*/true))
1085 FE = *File;
1086
1087 if (!FE)
Craig Topperd2d442c2014-05-17 23:10:59 +00001088 return nullptr;
Chris Lattner63dd32b2006-10-20 04:42:40 +00001089 }
Mike Stump11289f42009-09-09 15:08:12 +00001090
Chris Lattner577377e2006-10-20 04:55:45 +00001091 // This file is a system header or C++ unfriendly if the old file is.
Ted Kremenek72be0682008-02-24 03:55:14 +00001092 //
Chris Lattnerf5c619f2008-02-25 21:38:21 +00001093 // Note that the temporary 'DirInfo' is required here, as either call to
1094 // getFileInfo could resize the vector and we don't want to rely on order
1095 // of evaluation.
1096 unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo;
1097 getFileInfo(FE).DirInfo = DirInfo;
Douglas Gregorf5f94522013-02-08 00:10:48 +00001098
Richard Smith3d5b48c2015-10-16 21:42:56 +00001099 FrameworkName.pop_back(); // remove the trailing '/'
1100 if (!findUsableModuleForFrameworkHeader(FE, FrameworkName, RequestingModule,
1101 SuggestedModule, /*IsSystem*/ false))
1102 return nullptr;
Douglas Gregorf5f94522013-02-08 00:10:48 +00001103
Chris Lattner577377e2006-10-20 04:55:45 +00001104 return FE;
Chris Lattner63dd32b2006-10-20 04:42:40 +00001105}
1106
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001107//===----------------------------------------------------------------------===//
1108// File Info Management.
1109//===----------------------------------------------------------------------===//
1110
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001111/// Merge the header file info provided by \p OtherHFI into the current
Douglas Gregor5d1bee22011-09-17 05:35:18 +00001112/// header file info (\p HFI)
Fangrui Song6907ce22018-07-30 19:24:48 +00001113static void mergeHeaderFileInfo(HeaderFileInfo &HFI,
Douglas Gregor5d1bee22011-09-17 05:35:18 +00001114 const HeaderFileInfo &OtherHFI) {
Richard Smithd8879c82015-08-24 21:59:32 +00001115 assert(OtherHFI.External && "expected to merge external HFI");
1116
Douglas Gregor5d1bee22011-09-17 05:35:18 +00001117 HFI.isImport |= OtherHFI.isImport;
1118 HFI.isPragmaOnce |= OtherHFI.isPragmaOnce;
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001119 HFI.isModuleHeader |= OtherHFI.isModuleHeader;
Douglas Gregor5d1bee22011-09-17 05:35:18 +00001120 HFI.NumIncludes += OtherHFI.NumIncludes;
Richard Smithd8879c82015-08-24 21:59:32 +00001121
Douglas Gregor5d1bee22011-09-17 05:35:18 +00001122 if (!HFI.ControllingMacro && !HFI.ControllingMacroID) {
1123 HFI.ControllingMacro = OtherHFI.ControllingMacro;
1124 HFI.ControllingMacroID = OtherHFI.ControllingMacroID;
1125 }
Richard Smithd8879c82015-08-24 21:59:32 +00001126
1127 HFI.DirInfo = OtherHFI.DirInfo;
1128 HFI.External = (!HFI.IsValid || HFI.External);
1129 HFI.IsValid = true;
1130 HFI.IndexHeaderMapHeader = OtherHFI.IndexHeaderMapHeader;
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001131
Douglas Gregor5d1bee22011-09-17 05:35:18 +00001132 if (HFI.Framework.empty())
1133 HFI.Framework = OtherHFI.Framework;
Douglas Gregor5d1bee22011-09-17 05:35:18 +00001134}
Fangrui Song6907ce22018-07-30 19:24:48 +00001135
Steve Naroff3fa455a2009-04-24 20:03:17 +00001136/// getFileInfo - Return the HeaderFileInfo structure for the specified
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001137/// FileEntry.
Steve Naroff3fa455a2009-04-24 20:03:17 +00001138HeaderFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) {
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001139 if (FE->getUID() >= FileInfo.size())
Richard Smith386bb072015-08-18 23:42:23 +00001140 FileInfo.resize(FE->getUID() + 1);
1141
Richard Smithd8879c82015-08-24 21:59:32 +00001142 HeaderFileInfo *HFI = &FileInfo[FE->getUID()];
Richard Smith386bb072015-08-18 23:42:23 +00001143 // FIXME: Use a generation count to check whether this is really up to date.
Richard Smithd8879c82015-08-24 21:59:32 +00001144 if (ExternalSource && !HFI->Resolved) {
1145 HFI->Resolved = true;
1146 auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE);
1147
1148 HFI = &FileInfo[FE->getUID()];
1149 if (ExternalHFI.External)
1150 mergeHeaderFileInfo(*HFI, ExternalHFI);
Richard Smith386bb072015-08-18 23:42:23 +00001151 }
1152
Richard Smithd8879c82015-08-24 21:59:32 +00001153 HFI->IsValid = true;
Richard Smith386bb072015-08-18 23:42:23 +00001154 // We have local information about this header file, so it's no longer
1155 // strictly external.
Richard Smithd8879c82015-08-24 21:59:32 +00001156 HFI->External = false;
1157 return *HFI;
Mike Stump11289f42009-09-09 15:08:12 +00001158}
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001159
Richard Smith386bb072015-08-18 23:42:23 +00001160const HeaderFileInfo *
Richard Smithd8879c82015-08-24 21:59:32 +00001161HeaderSearch::getExistingFileInfo(const FileEntry *FE,
1162 bool WantExternal) const {
Richard Smith386bb072015-08-18 23:42:23 +00001163 // If we have an external source, ensure we have the latest information.
1164 // FIXME: Use a generation count to check whether this is really up to date.
Richard Smithd8879c82015-08-24 21:59:32 +00001165 HeaderFileInfo *HFI;
1166 if (ExternalSource) {
1167 if (FE->getUID() >= FileInfo.size()) {
1168 if (!WantExternal)
1169 return nullptr;
1170 FileInfo.resize(FE->getUID() + 1);
Richard Smith386bb072015-08-18 23:42:23 +00001171 }
Richard Smithd8879c82015-08-24 21:59:32 +00001172
1173 HFI = &FileInfo[FE->getUID()];
1174 if (!WantExternal && (!HFI->IsValid || HFI->External))
1175 return nullptr;
1176 if (!HFI->Resolved) {
1177 HFI->Resolved = true;
1178 auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE);
1179
1180 HFI = &FileInfo[FE->getUID()];
1181 if (ExternalHFI.External)
1182 mergeHeaderFileInfo(*HFI, ExternalHFI);
1183 }
1184 } else if (FE->getUID() >= FileInfo.size()) {
1185 return nullptr;
1186 } else {
1187 HFI = &FileInfo[FE->getUID()];
Ben Langmuird285c502014-03-13 16:46:36 +00001188 }
Richard Smith386bb072015-08-18 23:42:23 +00001189
Richard Smithd8879c82015-08-24 21:59:32 +00001190 if (!HFI->IsValid || (HFI->External && !WantExternal))
Richard Smith386bb072015-08-18 23:42:23 +00001191 return nullptr;
1192
Richard Smithd8879c82015-08-24 21:59:32 +00001193 return HFI;
Ben Langmuird285c502014-03-13 16:46:36 +00001194}
1195
Douglas Gregor37aa4932011-05-04 00:14:37 +00001196bool HeaderSearch::isFileMultipleIncludeGuarded(const FileEntry *File) {
1197 // Check if we've ever seen this file as a header.
Richard Smith386bb072015-08-18 23:42:23 +00001198 if (auto *HFI = getExistingFileInfo(File))
1199 return HFI->isPragmaOnce || HFI->isImport || HFI->ControllingMacro ||
1200 HFI->ControllingMacroID;
1201 return false;
Douglas Gregor37aa4932011-05-04 00:14:37 +00001202}
1203
Argyrios Kyrtzidis6f722b42013-05-08 23:46:46 +00001204void HeaderSearch::MarkFileModuleHeader(const FileEntry *FE,
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001205 ModuleMap::ModuleHeaderRole Role,
Argyrios Kyrtzidis6f722b42013-05-08 23:46:46 +00001206 bool isCompilingModuleHeader) {
Richard Smithd8879c82015-08-24 21:59:32 +00001207 bool isModularHeader = !(Role & ModuleMap::TextualHeader);
1208
1209 // Don't mark the file info as non-external if there's nothing to change.
1210 if (!isCompilingModuleHeader) {
1211 if (!isModularHeader)
1212 return;
1213 auto *HFI = getExistingFileInfo(FE);
1214 if (HFI && HFI->isModuleHeader)
1215 return;
1216 }
1217
Richard Smith386bb072015-08-18 23:42:23 +00001218 auto &HFI = getFileInfo(FE);
Richard Smithd8879c82015-08-24 21:59:32 +00001219 HFI.isModuleHeader |= isModularHeader;
Richard Smithe70dadd2015-07-10 22:27:17 +00001220 HFI.isCompilingModuleHeader |= isCompilingModuleHeader;
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001221}
1222
Richard Smith20e883e2015-04-29 23:20:19 +00001223bool HeaderSearch::ShouldEnterIncludeFile(Preprocessor &PP,
Bruno Cardoso Lopesba1b5c92017-01-11 02:14:51 +00001224 const FileEntry *File, bool isImport,
1225 bool ModulesEnabled, Module *M) {
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001226 ++NumIncluded; // Count # of attempted #includes.
1227
1228 // Get information about this file.
Steve Naroff3fa455a2009-04-24 20:03:17 +00001229 HeaderFileInfo &FileInfo = getFileInfo(File);
Mike Stump11289f42009-09-09 15:08:12 +00001230
Bruno Cardoso Lopesba1b5c92017-01-11 02:14:51 +00001231 // FIXME: this is a workaround for the lack of proper modules-aware support
1232 // for #import / #pragma once
Eugene Zelenkoafd1b1c2017-12-06 23:18:41 +00001233 auto TryEnterImported = [&]() -> bool {
Bruno Cardoso Lopesba1b5c92017-01-11 02:14:51 +00001234 if (!ModulesEnabled)
1235 return false;
Richard Smith040e1262017-06-02 01:55:39 +00001236 // Ensure FileInfo bits are up to date.
1237 ModMap.resolveHeaderDirectives(File);
Bruno Cardoso Lopesba1b5c92017-01-11 02:14:51 +00001238 // Modules with builtins are special; multiple modules use builtins as
1239 // modular headers, example:
1240 //
1241 // module stddef { header "stddef.h" export * }
1242 //
1243 // After module map parsing, this expands to:
1244 //
1245 // module stddef {
1246 // header "/path_to_builtin_dirs/stddef.h"
1247 // textual "stddef.h"
1248 // }
1249 //
1250 // It's common that libc++ and system modules will both define such
1251 // submodules. Make sure cached results for a builtin header won't
1252 // prevent other builtin modules to potentially enter the builtin header.
1253 // Note that builtins are header guarded and the decision to actually
1254 // enter them is postponed to the controlling macros logic below.
1255 bool TryEnterHdr = false;
1256 if (FileInfo.isCompilingModuleHeader && FileInfo.isModuleHeader)
1257 TryEnterHdr = File->getDir() == ModMap.getBuiltinDir() &&
1258 ModuleMap::isBuiltinHeader(
1259 llvm::sys::path::filename(File->getName()));
1260
1261 // Textual headers can be #imported from different modules. Since ObjC
1262 // headers find in the wild might rely only on #import and do not contain
1263 // controlling macros, be conservative and only try to enter textual headers
1264 // if such macro is present.
Bruno Cardoso Lopes4164dd92017-08-12 01:38:26 +00001265 if (!FileInfo.isModuleHeader &&
Bruno Cardoso Lopesba1b5c92017-01-11 02:14:51 +00001266 FileInfo.getControllingMacro(ExternalLookup))
1267 TryEnterHdr = true;
1268 return TryEnterHdr;
1269 };
1270
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001271 // If this is a #import directive, check that we have not already imported
1272 // this header.
1273 if (isImport) {
1274 // If this has already been imported, don't import it again.
1275 FileInfo.isImport = true;
Mike Stump11289f42009-09-09 15:08:12 +00001276
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001277 // Has this already been #import'ed or #include'd?
Bruno Cardoso Lopesba1b5c92017-01-11 02:14:51 +00001278 if (FileInfo.NumIncludes && !TryEnterImported())
1279 return false;
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001280 } else {
1281 // Otherwise, if this is a #include of a file that was previously #import'd
1282 // or if this is the second #include of a #pragma once file, ignore it.
Bruno Cardoso Lopesba1b5c92017-01-11 02:14:51 +00001283 if (FileInfo.isImport && !TryEnterImported())
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001284 return false;
1285 }
Mike Stump11289f42009-09-09 15:08:12 +00001286
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001287 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
1288 // if the macro that guards it is defined, we know the #include has no effect.
Mike Stump11289f42009-09-09 15:08:12 +00001289 if (const IdentifierInfo *ControllingMacro
Richard Smithe70dadd2015-07-10 22:27:17 +00001290 = FileInfo.getControllingMacro(ExternalLookup)) {
1291 // If the header corresponds to a module, check whether the macro is already
1292 // defined in that module rather than checking in the current set of visible
1293 // modules.
1294 if (M ? PP.isMacroDefinedInLocalModule(ControllingMacro, M)
1295 : PP.isMacroDefined(ControllingMacro)) {
Douglas Gregor99734e72009-04-25 23:30:02 +00001296 ++NumMultiIncludeFileOptzn;
1297 return false;
1298 }
Richard Smithe70dadd2015-07-10 22:27:17 +00001299 }
Mike Stump11289f42009-09-09 15:08:12 +00001300
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001301 // Increment the number of times this file has been included.
1302 ++FileInfo.NumIncludes;
Mike Stump11289f42009-09-09 15:08:12 +00001303
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001304 return true;
1305}
1306
Ted Kremenekfbcce6f2011-07-26 23:46:11 +00001307size_t HeaderSearch::getTotalMemory() const {
1308 return SearchDirs.capacity()
Ted Kremenekae63d102011-07-27 18:41:18 +00001309 + llvm::capacity_in_bytes(FileInfo)
1310 + llvm::capacity_in_bytes(HeaderMaps)
Ted Kremenekfbcce6f2011-07-26 23:46:11 +00001311 + LookupFileCache.getAllocator().getTotalMemory()
1312 + FrameworkMap.getAllocator().getTotalMemory();
1313}
Douglas Gregor9f93e382011-07-28 04:45:53 +00001314
1315StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) {
David Blaikie13156b62014-11-19 03:06:06 +00001316 return FrameworkNames.insert(Framework).first->first();
Douglas Gregor9f93e382011-07-28 04:45:53 +00001317}
Douglas Gregor718292f2011-11-11 19:10:28 +00001318
Fangrui Song6907ce22018-07-30 19:24:48 +00001319bool HeaderSearch::hasModuleMap(StringRef FileName,
Douglas Gregor963c5532013-06-21 16:28:10 +00001320 const DirectoryEntry *Root,
1321 bool IsSystem) {
Richard Smith47972af2015-06-16 00:08:24 +00001322 if (!HSOpts->ImplicitModuleMaps)
Argyrios Kyrtzidis9955dbc2013-12-12 16:08:33 +00001323 return false;
1324
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001325 SmallVector<const DirectoryEntry *, 2> FixUpDirectories;
Fangrui Song6907ce22018-07-30 19:24:48 +00001326
Douglas Gregor718292f2011-11-11 19:10:28 +00001327 StringRef DirName = FileName;
1328 do {
1329 // Get the parent directory name.
1330 DirName = llvm::sys::path::parent_path(DirName);
1331 if (DirName.empty())
1332 return false;
Daniel Jasperca9f7382013-09-24 09:27:13 +00001333
Douglas Gregor718292f2011-11-11 19:10:28 +00001334 // Determine whether this directory exists.
Harlan Haskins8d323d12019-08-01 21:31:56 +00001335 auto Dir = FileMgr.getDirectory(DirName);
Douglas Gregor718292f2011-11-11 19:10:28 +00001336 if (!Dir)
1337 return false;
Daniel Jasperca9f7382013-09-24 09:27:13 +00001338
Ben Langmuir984e1df2014-03-19 20:23:34 +00001339 // Try to load the module map file in this directory.
Harlan Haskins8d323d12019-08-01 21:31:56 +00001340 switch (loadModuleMapFile(*Dir, IsSystem,
1341 llvm::sys::path::extension((*Dir)->getName()) ==
Richard Smith3c1a41a2014-12-02 00:08:08 +00001342 ".framework")) {
Douglas Gregor80b69042011-11-12 00:22:19 +00001343 case LMM_NewlyLoaded:
1344 case LMM_AlreadyLoaded:
Daniel Jasperca9f7382013-09-24 09:27:13 +00001345 // Success. All of the directories we stepped through inherit this module
1346 // map file.
1347 for (unsigned I = 0, N = FixUpDirectories.size(); I != N; ++I)
1348 DirectoryHasModuleMap[FixUpDirectories[I]] = true;
1349 return true;
Daniel Jasper97da9172013-10-22 08:09:47 +00001350
1351 case LMM_NoDirectory:
1352 case LMM_InvalidModuleMap:
1353 break;
Daniel Jasperca9f7382013-09-24 09:27:13 +00001354 }
1355
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001356 // If we hit the top of our search, we're done.
Harlan Haskins8d323d12019-08-01 21:31:56 +00001357 if (*Dir == Root)
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001358 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00001359
Douglas Gregor718292f2011-11-11 19:10:28 +00001360 // Keep track of all of the directories we checked, so we can mark them as
1361 // having module maps if we eventually do find a module map.
Harlan Haskins8d323d12019-08-01 21:31:56 +00001362 FixUpDirectories.push_back(*Dir);
Douglas Gregor718292f2011-11-11 19:10:28 +00001363 } while (true);
Douglas Gregor718292f2011-11-11 19:10:28 +00001364}
1365
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001366ModuleMap::KnownHeader
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +00001367HeaderSearch::findModuleForHeader(const FileEntry *File,
1368 bool AllowTextual) const {
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001369 if (ExternalSource) {
1370 // Make sure the external source has handled header info about this file,
1371 // which includes whether the file is part of a module.
Richard Smith386bb072015-08-18 23:42:23 +00001372 (void)getExistingFileInfo(File);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001373 }
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +00001374 return ModMap.findModuleForHeader(File, AllowTextual);
1375}
1376
1377static bool suggestModule(HeaderSearch &HS, const FileEntry *File,
1378 Module *RequestingModule,
1379 ModuleMap::KnownHeader *SuggestedModule) {
1380 ModuleMap::KnownHeader Module =
1381 HS.findModuleForHeader(File, /*AllowTextual*/true);
1382 if (SuggestedModule)
1383 *SuggestedModule = (Module.getRole() & ModuleMap::TextualHeader)
1384 ? ModuleMap::KnownHeader()
1385 : Module;
1386
1387 // If this module specifies [no_undeclared_includes], we cannot find any
1388 // file that's in a non-dependency module.
1389 if (RequestingModule && Module && RequestingModule->NoUndeclaredIncludes) {
1390 HS.getModuleMap().resolveUses(RequestingModule, /*Complain*/false);
1391 if (!RequestingModule->directlyUses(Module.getModule())) {
1392 return false;
1393 }
1394 }
1395
1396 return true;
Douglas Gregor718292f2011-11-11 19:10:28 +00001397}
1398
Richard Smith3d5b48c2015-10-16 21:42:56 +00001399bool HeaderSearch::findUsableModuleForHeader(
1400 const FileEntry *File, const DirectoryEntry *Root, Module *RequestingModule,
1401 ModuleMap::KnownHeader *SuggestedModule, bool IsSystemHeaderDir) {
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +00001402 if (File && needModuleLookup(RequestingModule, SuggestedModule)) {
Richard Smith3d5b48c2015-10-16 21:42:56 +00001403 // If there is a module that corresponds to this header, suggest it.
1404 hasModuleMap(File->getName(), Root, IsSystemHeaderDir);
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +00001405 return suggestModule(*this, File, RequestingModule, SuggestedModule);
Richard Smith3d5b48c2015-10-16 21:42:56 +00001406 }
1407 return true;
1408}
1409
1410bool HeaderSearch::findUsableModuleForFrameworkHeader(
1411 const FileEntry *File, StringRef FrameworkName, Module *RequestingModule,
1412 ModuleMap::KnownHeader *SuggestedModule, bool IsSystemFramework) {
1413 // If we're supposed to suggest a module, look for one now.
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +00001414 if (needModuleLookup(RequestingModule, SuggestedModule)) {
Richard Smith3d5b48c2015-10-16 21:42:56 +00001415 // Find the top-level framework based on this framework.
1416 SmallVector<std::string, 4> SubmodulePath;
1417 const DirectoryEntry *TopFrameworkDir
1418 = ::getTopFrameworkDir(FileMgr, FrameworkName, SubmodulePath);
Fangrui Song6907ce22018-07-30 19:24:48 +00001419
Richard Smith3d5b48c2015-10-16 21:42:56 +00001420 // Determine the name of the top-level framework.
1421 StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
1422
1423 // Load this framework module. If that succeeds, find the suggested module
1424 // for this header, if any.
1425 loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystemFramework);
1426
1427 // FIXME: This can find a module not part of ModuleName, which is
1428 // important so that we're consistent about whether this header
1429 // corresponds to a module. Possibly we should lock down framework modules
1430 // so that this is not possible.
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +00001431 return suggestModule(*this, File, RequestingModule, SuggestedModule);
Richard Smith3d5b48c2015-10-16 21:42:56 +00001432 }
1433 return true;
1434}
1435
Richard Smith9acb99e32014-12-10 03:09:48 +00001436static const FileEntry *getPrivateModuleMap(const FileEntry *File,
Ben Langmuir984e1df2014-03-19 20:23:34 +00001437 FileManager &FileMgr) {
Richard Smith9acb99e32014-12-10 03:09:48 +00001438 StringRef Filename = llvm::sys::path::filename(File->getName());
1439 SmallString<128> PrivateFilename(File->getDir()->getName());
Ben Langmuir984e1df2014-03-19 20:23:34 +00001440 if (Filename == "module.map")
Douglas Gregor80306772011-12-07 21:25:07 +00001441 llvm::sys::path::append(PrivateFilename, "module_private.map");
Ben Langmuir984e1df2014-03-19 20:23:34 +00001442 else if (Filename == "module.modulemap")
1443 llvm::sys::path::append(PrivateFilename, "module.private.modulemap");
1444 else
1445 return nullptr;
Harlan Haskins8d323d12019-08-01 21:31:56 +00001446 if (auto File = FileMgr.getFile(PrivateFilename))
1447 return *File;
1448 return nullptr;
Douglas Gregor2b20cb82011-11-16 00:09:06 +00001449}
1450
Richard Smith8128f332017-05-05 22:18:51 +00001451bool HeaderSearch::loadModuleMapFile(const FileEntry *File, bool IsSystem,
Richard Smith8b706102017-05-31 20:56:55 +00001452 FileID ID, unsigned *Offset,
1453 StringRef OriginalModuleMapFile) {
Richard Smith9acb99e32014-12-10 03:09:48 +00001454 // Find the directory for the module. For frameworks, that may require going
1455 // up from the 'Modules' directory.
1456 const DirectoryEntry *Dir = nullptr;
Harlan Haskins8d323d12019-08-01 21:31:56 +00001457 if (getHeaderSearchOpts().ModuleMapFileHomeIsCwd) {
1458 if (auto DirOrErr = FileMgr.getDirectory("."))
1459 Dir = *DirOrErr;
1460 } else {
Richard Smith8b706102017-05-31 20:56:55 +00001461 if (!OriginalModuleMapFile.empty()) {
1462 // We're building a preprocessed module map. Find or invent the directory
1463 // that it originally occupied.
Harlan Haskins8d323d12019-08-01 21:31:56 +00001464 auto DirOrErr = FileMgr.getDirectory(
Richard Smith8b706102017-05-31 20:56:55 +00001465 llvm::sys::path::parent_path(OriginalModuleMapFile));
Harlan Haskins8d323d12019-08-01 21:31:56 +00001466 if (DirOrErr) {
1467 Dir = *DirOrErr;
1468 } else {
Richard Smith8b706102017-05-31 20:56:55 +00001469 auto *FakeFile = FileMgr.getVirtualFile(OriginalModuleMapFile, 0, 0);
1470 Dir = FakeFile->getDir();
1471 }
1472 } else {
1473 Dir = File->getDir();
1474 }
1475
Richard Smith9acb99e32014-12-10 03:09:48 +00001476 StringRef DirName(Dir->getName());
1477 if (llvm::sys::path::filename(DirName) == "Modules") {
1478 DirName = llvm::sys::path::parent_path(DirName);
1479 if (DirName.endswith(".framework"))
Harlan Haskins8d323d12019-08-01 21:31:56 +00001480 if (auto DirOrErr = FileMgr.getDirectory(DirName))
1481 Dir = *DirOrErr;
Richard Smith9acb99e32014-12-10 03:09:48 +00001482 // FIXME: This assert can fail if there's a race between the above check
1483 // and the removal of the directory.
1484 assert(Dir && "parent must exist");
1485 }
1486 }
1487
Bruno Cardoso Lopesc192d192018-01-05 22:13:56 +00001488 switch (loadModuleMapFileImpl(File, IsSystem, Dir, ID, Offset)) {
Ben Langmuir984e1df2014-03-19 20:23:34 +00001489 case LMM_AlreadyLoaded:
1490 case LMM_NewlyLoaded:
1491 return false;
1492 case LMM_NoDirectory:
1493 case LMM_InvalidModuleMap:
1494 return true;
1495 }
Aaron Ballmand8de5b62014-03-20 14:22:33 +00001496 llvm_unreachable("Unknown load module map result");
Ben Langmuir984e1df2014-03-19 20:23:34 +00001497}
1498
Bruno Cardoso Lopesc192d192018-01-05 22:13:56 +00001499HeaderSearch::LoadModuleMapResult
1500HeaderSearch::loadModuleMapFileImpl(const FileEntry *File, bool IsSystem,
1501 const DirectoryEntry *Dir, FileID ID,
1502 unsigned *Offset) {
Ben Langmuir984e1df2014-03-19 20:23:34 +00001503 assert(File && "expected FileEntry");
1504
Richard Smith9887d792014-10-17 01:42:53 +00001505 // Check whether we've already loaded this module map, and mark it as being
1506 // loaded in case we recursively try to load it from itself.
1507 auto AddResult = LoadedModuleMaps.insert(std::make_pair(File, true));
1508 if (!AddResult.second)
1509 return AddResult.first->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001510
Bruno Cardoso Lopesc192d192018-01-05 22:13:56 +00001511 if (ModMap.parseModuleMapFile(File, IsSystem, Dir, ID, Offset)) {
Richard Smith9887d792014-10-17 01:42:53 +00001512 LoadedModuleMaps[File] = false;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001513 return LMM_InvalidModuleMap;
1514 }
1515
1516 // Try to load a corresponding private module map.
Richard Smith9acb99e32014-12-10 03:09:48 +00001517 if (const FileEntry *PMMFile = getPrivateModuleMap(File, FileMgr)) {
Bruno Cardoso Lopesc192d192018-01-05 22:13:56 +00001518 if (ModMap.parseModuleMapFile(PMMFile, IsSystem, Dir)) {
Richard Smith9887d792014-10-17 01:42:53 +00001519 LoadedModuleMaps[File] = false;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001520 return LMM_InvalidModuleMap;
1521 }
1522 }
1523
1524 // This directory has a module map.
Ben Langmuir984e1df2014-03-19 20:23:34 +00001525 return LMM_NewlyLoaded;
1526}
1527
1528const FileEntry *
1529HeaderSearch::lookupModuleMapFile(const DirectoryEntry *Dir, bool IsFramework) {
Richard Smith47972af2015-06-16 00:08:24 +00001530 if (!HSOpts->ImplicitModuleMaps)
Daniel Jasper21a0f552014-11-25 09:45:48 +00001531 return nullptr;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001532 // For frameworks, the preferred spelling is Modules/module.modulemap, but
1533 // module.map at the framework root is also accepted.
1534 SmallString<128> ModuleMapFileName(Dir->getName());
1535 if (IsFramework)
1536 llvm::sys::path::append(ModuleMapFileName, "Modules");
1537 llvm::sys::path::append(ModuleMapFileName, "module.modulemap");
Harlan Haskins8d323d12019-08-01 21:31:56 +00001538 if (auto F = FileMgr.getFile(ModuleMapFileName))
1539 return *F;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001540
1541 // Continue to allow module.map
1542 ModuleMapFileName = Dir->getName();
1543 llvm::sys::path::append(ModuleMapFileName, "module.map");
Harlan Haskins8d323d12019-08-01 21:31:56 +00001544 if (auto F = FileMgr.getFile(ModuleMapFileName))
1545 return *F;
1546 return nullptr;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001547}
1548
1549Module *HeaderSearch::loadFrameworkModule(StringRef Name,
Douglas Gregor279a6c32012-01-29 17:08:11 +00001550 const DirectoryEntry *Dir,
1551 bool IsSystem) {
Douglas Gregorde3ef502011-11-30 23:21:26 +00001552 if (Module *Module = ModMap.findModule(Name))
Douglas Gregor56c64012011-11-17 01:41:17 +00001553 return Module;
Daniel Jasper21a0f552014-11-25 09:45:48 +00001554
Douglas Gregor56c64012011-11-17 01:41:17 +00001555 // Try to load a module map file.
Ben Langmuir984e1df2014-03-19 20:23:34 +00001556 switch (loadModuleMapFile(Dir, IsSystem, /*IsFramework*/true)) {
Douglas Gregor56c64012011-11-17 01:41:17 +00001557 case LMM_InvalidModuleMap:
Ben Langmuira5254002015-07-02 13:19:48 +00001558 // Try to infer a module map from the framework directory.
1559 if (HSOpts->ImplicitModuleMaps)
1560 ModMap.inferFrameworkModule(Dir, IsSystem, /*Parent=*/nullptr);
Douglas Gregor56c64012011-11-17 01:41:17 +00001561 break;
Daniel Jasper21a0f552014-11-25 09:45:48 +00001562
Douglas Gregor56c64012011-11-17 01:41:17 +00001563 case LMM_AlreadyLoaded:
1564 case LMM_NoDirectory:
Craig Topperd2d442c2014-05-17 23:10:59 +00001565 return nullptr;
1566
Douglas Gregor56c64012011-11-17 01:41:17 +00001567 case LMM_NewlyLoaded:
Ben Langmuira5254002015-07-02 13:19:48 +00001568 break;
Douglas Gregor56c64012011-11-17 01:41:17 +00001569 }
Douglas Gregor3a5999b2012-01-13 22:31:52 +00001570
Ben Langmuira5254002015-07-02 13:19:48 +00001571 return ModMap.findModule(Name);
Douglas Gregor56c64012011-11-17 01:41:17 +00001572}
1573
Fangrui Song6907ce22018-07-30 19:24:48 +00001574HeaderSearch::LoadModuleMapResult
Ben Langmuir984e1df2014-03-19 20:23:34 +00001575HeaderSearch::loadModuleMapFile(StringRef DirName, bool IsSystem,
1576 bool IsFramework) {
Harlan Haskins8d323d12019-08-01 21:31:56 +00001577 if (auto Dir = FileMgr.getDirectory(DirName))
1578 return loadModuleMapFile(*Dir, IsSystem, IsFramework);
Fangrui Song6907ce22018-07-30 19:24:48 +00001579
Douglas Gregor80b69042011-11-12 00:22:19 +00001580 return LMM_NoDirectory;
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001581}
1582
Fangrui Song6907ce22018-07-30 19:24:48 +00001583HeaderSearch::LoadModuleMapResult
Ben Langmuir984e1df2014-03-19 20:23:34 +00001584HeaderSearch::loadModuleMapFile(const DirectoryEntry *Dir, bool IsSystem,
1585 bool IsFramework) {
1586 auto KnownDir = DirectoryHasModuleMap.find(Dir);
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001587 if (KnownDir != DirectoryHasModuleMap.end())
Richard Smith9887d792014-10-17 01:42:53 +00001588 return KnownDir->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
Douglas Gregore7ab3662011-12-07 02:23:45 +00001589
Ben Langmuir984e1df2014-03-19 20:23:34 +00001590 if (const FileEntry *ModuleMapFile = lookupModuleMapFile(Dir, IsFramework)) {
Bruno Cardoso Lopesc192d192018-01-05 22:13:56 +00001591 LoadModuleMapResult Result =
1592 loadModuleMapFileImpl(ModuleMapFile, IsSystem, Dir);
Ben Langmuir984e1df2014-03-19 20:23:34 +00001593 // Add Dir explicitly in case ModuleMapFile is in a subdirectory.
1594 // E.g. Foo.framework/Modules/module.modulemap
1595 // ^Dir ^ModuleMapFile
1596 if (Result == LMM_NewlyLoaded)
1597 DirectoryHasModuleMap[Dir] = true;
Richard Smith9887d792014-10-17 01:42:53 +00001598 else if (Result == LMM_InvalidModuleMap)
1599 DirectoryHasModuleMap[Dir] = false;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001600 return Result;
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001601 }
Douglas Gregor80b69042011-11-12 00:22:19 +00001602 return LMM_InvalidModuleMap;
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001603}
Douglas Gregor718292f2011-11-11 19:10:28 +00001604
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001605void HeaderSearch::collectAllModules(SmallVectorImpl<Module *> &Modules) {
Douglas Gregor07f43572012-01-29 18:15:03 +00001606 Modules.clear();
Daniel Jasper21a0f552014-11-25 09:45:48 +00001607
Richard Smith47972af2015-06-16 00:08:24 +00001608 if (HSOpts->ImplicitModuleMaps) {
Daniel Jasper21a0f552014-11-25 09:45:48 +00001609 // Load module maps for each of the header search directories.
1610 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
1611 bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
1612 if (SearchDirs[Idx].isFramework()) {
1613 std::error_code EC;
1614 SmallString<128> DirNative;
1615 llvm::sys::path::native(SearchDirs[Idx].getFrameworkDir()->getName(),
1616 DirNative);
1617
1618 // Search each of the ".framework" directories to load them as modules.
Duncan P. N. Exon Smithdb8a7422019-03-26 22:32:06 +00001619 llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
Jonas Devliegherefc514902018-10-10 13:27:25 +00001620 for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC),
1621 DirEnd;
Daniel Jasper21a0f552014-11-25 09:45:48 +00001622 Dir != DirEnd && !EC; Dir.increment(EC)) {
Sam McCall0ae00562018-09-14 12:47:38 +00001623 if (llvm::sys::path::extension(Dir->path()) != ".framework")
Daniel Jasper21a0f552014-11-25 09:45:48 +00001624 continue;
1625
Harlan Haskins8d323d12019-08-01 21:31:56 +00001626 auto FrameworkDir =
Sam McCall0ae00562018-09-14 12:47:38 +00001627 FileMgr.getDirectory(Dir->path());
Daniel Jasper21a0f552014-11-25 09:45:48 +00001628 if (!FrameworkDir)
1629 continue;
1630
1631 // Load this framework module.
Harlan Haskins8d323d12019-08-01 21:31:56 +00001632 loadFrameworkModule(llvm::sys::path::stem(Dir->path()), *FrameworkDir,
Sam McCall0ae00562018-09-14 12:47:38 +00001633 IsSystem);
Daniel Jasper21a0f552014-11-25 09:45:48 +00001634 }
1635 continue;
Douglas Gregor07f43572012-01-29 18:15:03 +00001636 }
Daniel Jasper21a0f552014-11-25 09:45:48 +00001637
1638 // FIXME: Deal with header maps.
1639 if (SearchDirs[Idx].isHeaderMap())
1640 continue;
1641
1642 // Try to load a module map file for the search directory.
1643 loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem,
1644 /*IsFramework*/ false);
1645
1646 // Try to load module map files for immediate subdirectories of this
1647 // search directory.
1648 loadSubdirectoryModuleMaps(SearchDirs[Idx]);
Douglas Gregor07f43572012-01-29 18:15:03 +00001649 }
Douglas Gregor07f43572012-01-29 18:15:03 +00001650 }
Daniel Jasper21a0f552014-11-25 09:45:48 +00001651
Douglas Gregor07f43572012-01-29 18:15:03 +00001652 // Populate the list of modules.
Fangrui Song6907ce22018-07-30 19:24:48 +00001653 for (ModuleMap::module_iterator M = ModMap.module_begin(),
Douglas Gregor07f43572012-01-29 18:15:03 +00001654 MEnd = ModMap.module_end();
1655 M != MEnd; ++M) {
1656 Modules.push_back(M->getValue());
1657 }
1658}
Douglas Gregor0339a642013-03-21 01:08:50 +00001659
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001660void HeaderSearch::loadTopLevelSystemModules() {
Richard Smith47972af2015-06-16 00:08:24 +00001661 if (!HSOpts->ImplicitModuleMaps)
Daniel Jasper21a0f552014-11-25 09:45:48 +00001662 return;
1663
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001664 // Load module maps for each of the header search directories.
1665 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
Douglas Gregor299787f2013-11-01 23:08:38 +00001666 // We only care about normal header directories.
1667 if (!SearchDirs[Idx].isNormalDir()) {
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001668 continue;
1669 }
1670
1671 // Try to load a module map file for the search directory.
Douglas Gregor963c5532013-06-21 16:28:10 +00001672 loadModuleMapFile(SearchDirs[Idx].getDir(),
Ben Langmuir984e1df2014-03-19 20:23:34 +00001673 SearchDirs[Idx].isSystemHeaderDirectory(),
1674 SearchDirs[Idx].isFramework());
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001675 }
1676}
1677
Douglas Gregor0339a642013-03-21 01:08:50 +00001678void HeaderSearch::loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir) {
Richard Smith47972af2015-06-16 00:08:24 +00001679 assert(HSOpts->ImplicitModuleMaps &&
Daniel Jasper21a0f552014-11-25 09:45:48 +00001680 "Should not be loading subdirectory module maps");
1681
Douglas Gregor0339a642013-03-21 01:08:50 +00001682 if (SearchDir.haveSearchedAllModuleMaps())
1683 return;
Rafael Espindolac0809172014-06-12 14:02:15 +00001684
1685 std::error_code EC;
Alex Lorenz7d76ef92018-11-14 01:08:03 +00001686 SmallString<128> Dir = SearchDir.getDir()->getName();
1687 FileMgr.makeAbsolutePath(Dir);
Douglas Gregor0339a642013-03-21 01:08:50 +00001688 SmallString<128> DirNative;
Alex Lorenz7d76ef92018-11-14 01:08:03 +00001689 llvm::sys::path::native(Dir, DirNative);
Duncan P. N. Exon Smithdb8a7422019-03-26 22:32:06 +00001690 llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
Jonas Devliegherefc514902018-10-10 13:27:25 +00001691 for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
Douglas Gregor0339a642013-03-21 01:08:50 +00001692 Dir != DirEnd && !EC; Dir.increment(EC)) {
Sam McCall0ae00562018-09-14 12:47:38 +00001693 bool IsFramework = llvm::sys::path::extension(Dir->path()) == ".framework";
Ben Langmuir1f6a32b2015-02-24 04:58:15 +00001694 if (IsFramework == SearchDir.isFramework())
Sam McCall0ae00562018-09-14 12:47:38 +00001695 loadModuleMapFile(Dir->path(), SearchDir.isSystemHeaderDirectory(),
Ben Langmuir1f6a32b2015-02-24 04:58:15 +00001696 SearchDir.isFramework());
Douglas Gregor0339a642013-03-21 01:08:50 +00001697 }
1698
1699 SearchDir.setSearchedAllModuleMaps(true);
1700}
Richard Smith4eb83932016-04-27 21:57:05 +00001701
Kadir Cetinkaya1f6d9842019-07-03 07:47:19 +00001702std::string HeaderSearch::suggestPathToFileForDiagnostics(
1703 const FileEntry *File, llvm::StringRef MainFile, bool *IsSystem) {
Richard Smith4eb83932016-04-27 21:57:05 +00001704 // FIXME: We assume that the path name currently cached in the FileEntry is
Eric Liudffb1a82018-01-29 13:21:23 +00001705 // the most appropriate one for this analysis (and that it's spelled the
1706 // same way as the corresponding header search path).
Kadir Cetinkaya1f6d9842019-07-03 07:47:19 +00001707 return suggestPathToFileForDiagnostics(File->getName(), /*WorkingDir=*/"",
1708 MainFile, IsSystem);
Eric Liudffb1a82018-01-29 13:21:23 +00001709}
1710
1711std::string HeaderSearch::suggestPathToFileForDiagnostics(
Kadir Cetinkaya1f6d9842019-07-03 07:47:19 +00001712 llvm::StringRef File, llvm::StringRef WorkingDir, llvm::StringRef MainFile,
1713 bool *IsSystem) {
Eric Liudffb1a82018-01-29 13:21:23 +00001714 using namespace llvm::sys;
Richard Smith4eb83932016-04-27 21:57:05 +00001715
1716 unsigned BestPrefixLength = 0;
Kadir Cetinkaya1f6d9842019-07-03 07:47:19 +00001717 // Checks whether Dir and File shares a common prefix, if they do and that's
1718 // the longest prefix we've seen so for it returns true and updates the
1719 // BestPrefixLength accordingly.
1720 auto CheckDir = [&](llvm::StringRef Dir) -> bool {
Eric Liudffb1a82018-01-29 13:21:23 +00001721 llvm::SmallString<32> DirPath(Dir.begin(), Dir.end());
Kadir Cetinkaya936c67d2019-04-24 09:23:31 +00001722 if (!WorkingDir.empty() && !path::is_absolute(Dir))
Pavel Labath1ad53ca2019-01-16 09:55:32 +00001723 fs::make_absolute(WorkingDir, DirPath);
Kadir Cetinkaya936c67d2019-04-24 09:23:31 +00001724 path::remove_dots(DirPath, /*remove_dot_dot=*/true);
1725 Dir = DirPath;
Eric Liudffb1a82018-01-29 13:21:23 +00001726 for (auto NI = path::begin(File), NE = path::end(File),
1727 DI = path::begin(Dir), DE = path::end(Dir);
Richard Smith4eb83932016-04-27 21:57:05 +00001728 /*termination condition in loop*/; ++NI, ++DI) {
Eric Liudffb1a82018-01-29 13:21:23 +00001729 // '.' components in File are ignored.
Richard Smith4eb83932016-04-27 21:57:05 +00001730 while (NI != NE && *NI == ".")
1731 ++NI;
1732 if (NI == NE)
1733 break;
1734
1735 // '.' components in Dir are ignored.
1736 while (DI != DE && *DI == ".")
1737 ++DI;
1738 if (DI == DE) {
Eric Liudffb1a82018-01-29 13:21:23 +00001739 // Dir is a prefix of File, up to '.' components and choice of path
Richard Smith4eb83932016-04-27 21:57:05 +00001740 // separators.
Eric Liudffb1a82018-01-29 13:21:23 +00001741 unsigned PrefixLength = NI - path::begin(File);
Richard Smith4eb83932016-04-27 21:57:05 +00001742 if (PrefixLength > BestPrefixLength) {
1743 BestPrefixLength = PrefixLength;
Kadir Cetinkaya1f6d9842019-07-03 07:47:19 +00001744 return true;
Richard Smith4eb83932016-04-27 21:57:05 +00001745 }
1746 break;
1747 }
1748
Kadir Cetinkaya51f85b42019-06-06 18:49:16 +00001749 // Consider all path separators equal.
1750 if (NI->size() == 1 && DI->size() == 1 &&
1751 path::is_separator(NI->front()) && path::is_separator(DI->front()))
1752 continue;
1753
Richard Smith4eb83932016-04-27 21:57:05 +00001754 if (*NI != *DI)
1755 break;
1756 }
Kadir Cetinkaya1f6d9842019-07-03 07:47:19 +00001757 return false;
1758 };
1759
1760 for (unsigned I = 0; I != SearchDirs.size(); ++I) {
1761 // FIXME: Support this search within frameworks and header maps.
1762 if (!SearchDirs[I].isNormalDir())
1763 continue;
1764
1765 StringRef Dir = SearchDirs[I].getDir()->getName();
1766 if (CheckDir(Dir) && IsSystem)
1767 *IsSystem = BestPrefixLength ? I >= SystemDirIdx : false;
Richard Smith4eb83932016-04-27 21:57:05 +00001768 }
1769
Kadir Cetinkaya1f6d9842019-07-03 07:47:19 +00001770 // Try to shorten include path using TUs directory, if we couldn't find any
1771 // suitable prefix in include search paths.
1772 if (!BestPrefixLength && CheckDir(path::parent_path(MainFile)) && IsSystem)
1773 *IsSystem = false;
1774
1775
Kadir Cetinkaya40f8f7f2019-04-24 08:45:03 +00001776 return path::convert_to_slash(File.drop_front(BestPrefixLength));
Richard Smith4eb83932016-04-27 21:57:05 +00001777}