blob: fa2a76ef47caff4eb5f324215e76a0f89a6d7de1 [file] [log] [blame]
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001//===--- HeaderSearch.cpp - Resolve Header File Locations ---===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner59a9ebd2006-10-18 05:34:33 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the DirectoryLookup and HeaderSearch interfaces.
11//
12//===----------------------------------------------------------------------===//
13
Chris Lattner59a9ebd2006-10-18 05:34:33 +000014#include "clang/Lex/HeaderSearch.h"
Chris Lattneref6b1362007-10-07 08:58:51 +000015#include "clang/Basic/FileManager.h"
16#include "clang/Basic/IdentifierTable.h"
Richard Smith2aedca32015-07-01 02:29:35 +000017#include "clang/Lex/ExternalPreprocessorSource.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/Lex/HeaderMap.h"
19#include "clang/Lex/HeaderSearchOptions.h"
Will Wilson0fafd342013-12-27 19:46:16 +000020#include "clang/Lex/LexDiagnostic.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000021#include "clang/Lex/Lexer.h"
Richard Smith20e883e2015-04-29 23:20:19 +000022#include "clang/Lex/Preprocessor.h"
Ben Langmuirbeee15e2014-04-14 18:00:01 +000023#include "llvm/ADT/APInt.h"
24#include "llvm/ADT/Hashing.h"
Chris Lattner43fd42e2006-10-30 03:40:58 +000025#include "llvm/ADT/SmallString.h"
Ted Kremenekae63d102011-07-27 18:41:18 +000026#include "llvm/Support/Capacity.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000027#include "llvm/Support/FileSystem.h"
28#include "llvm/Support/Path.h"
Chris Lattnerc25d8a72009-03-02 22:20:04 +000029#include <cstdio>
Benjamin Kramercfeacf52016-05-27 14:27:13 +000030#include <utility>
Douglas Gregor01c7cfa2013-01-22 23:49:45 +000031#if defined(LLVM_ON_UNIX)
Dmitri Gribenkoeadae012013-01-26 16:29:36 +000032#include <limits.h>
Douglas Gregor01c7cfa2013-01-22 23:49:45 +000033#endif
Chris Lattner59a9ebd2006-10-18 05:34:33 +000034using namespace clang;
35
Douglas Gregor99734e72009-04-25 23:30:02 +000036const IdentifierInfo *
Richard Smith2aedca32015-07-01 02:29:35 +000037HeaderFileInfo::getControllingMacro(ExternalPreprocessorSource *External) {
38 if (ControllingMacro) {
Chandler Carruth59666772016-11-04 06:32:57 +000039 if (ControllingMacro->isOutOfDate()) {
40 assert(External && "We must have an external source if we have a "
41 "controlling macro that is out of date.");
Richard Smith2aedca32015-07-01 02:29:35 +000042 External->updateOutOfDateIdentifier(
43 *const_cast<IdentifierInfo *>(ControllingMacro));
Chandler Carruth59666772016-11-04 06:32:57 +000044 }
Douglas Gregor99734e72009-04-25 23:30:02 +000045 return ControllingMacro;
Richard Smith2aedca32015-07-01 02:29:35 +000046 }
Douglas Gregor99734e72009-04-25 23:30:02 +000047
48 if (!ControllingMacroID || !External)
Craig Topperd2d442c2014-05-17 23:10:59 +000049 return nullptr;
Douglas Gregor99734e72009-04-25 23:30:02 +000050
51 ControllingMacro = External->GetIdentifier(ControllingMacroID);
52 return ControllingMacro;
53}
54
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000055ExternalHeaderFileInfoSource::~ExternalHeaderFileInfoSource() {}
Douglas Gregor09b69892011-02-10 17:09:37 +000056
David Blaikie9c28cb32017-01-06 01:04:46 +000057HeaderSearch::HeaderSearch(std::shared_ptr<HeaderSearchOptions> HSOpts,
Manuel Klimek1f76c4e2013-10-24 07:51:24 +000058 SourceManager &SourceMgr, DiagnosticsEngine &Diags,
Will Wilson0fafd342013-12-27 19:46:16 +000059 const LangOptions &LangOpts,
Douglas Gregor89929282012-01-30 06:01:29 +000060 const TargetInfo *Target)
Benjamin Kramercfeacf52016-05-27 14:27:13 +000061 : HSOpts(std::move(HSOpts)), Diags(Diags),
62 FileMgr(SourceMgr.getFileManager()), FrameworkMap(64),
63 ModMap(SourceMgr, Diags, LangOpts, Target, *this) {
Nico Weber3b1d1212011-05-24 04:31:14 +000064 AngledDirIdx = 0;
Chris Lattner641a0be2006-10-20 06:23:14 +000065 SystemDirIdx = 0;
66 NoCurDirSearch = false;
Mike Stump11289f42009-09-09 15:08:12 +000067
Craig Topperd2d442c2014-05-17 23:10:59 +000068 ExternalLookup = nullptr;
69 ExternalSource = nullptr;
Chris Lattner641a0be2006-10-20 06:23:14 +000070 NumIncluded = 0;
71 NumMultiIncludeFileOptzn = 0;
72 NumFrameworkLookups = NumSubFrameworkLookups = 0;
73}
74
Chris Lattnerc4ba38e2007-12-17 06:36:45 +000075HeaderSearch::~HeaderSearch() {
76 // Delete headermaps.
77 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
78 delete HeaderMaps[i].second;
79}
Mike Stump11289f42009-09-09 15:08:12 +000080
Chris Lattner59a9ebd2006-10-18 05:34:33 +000081void HeaderSearch::PrintStats() {
Chris Lattner23b7eb62007-06-15 23:05:46 +000082 fprintf(stderr, "\n*** HeaderSearch Stats:\n");
83 fprintf(stderr, "%d files tracked.\n", (int)FileInfo.size());
Chris Lattner59a9ebd2006-10-18 05:34:33 +000084 unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0;
85 for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) {
86 NumOnceOnlyFiles += FileInfo[i].isImport;
87 if (MaxNumIncludes < FileInfo[i].NumIncludes)
88 MaxNumIncludes = FileInfo[i].NumIncludes;
89 NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1;
90 }
Chris Lattner23b7eb62007-06-15 23:05:46 +000091 fprintf(stderr, " %d #import/#pragma once files.\n", NumOnceOnlyFiles);
92 fprintf(stderr, " %d included exactly once.\n", NumSingleIncludedFiles);
93 fprintf(stderr, " %d max times a file is included.\n", MaxNumIncludes);
Mike Stump11289f42009-09-09 15:08:12 +000094
Chris Lattner23b7eb62007-06-15 23:05:46 +000095 fprintf(stderr, " %d #include/#include_next/#import.\n", NumIncluded);
96 fprintf(stderr, " %d #includes skipped due to"
97 " the multi-include optimization.\n", NumMultiIncludeFileOptzn);
Mike Stump11289f42009-09-09 15:08:12 +000098
Chris Lattner23b7eb62007-06-15 23:05:46 +000099 fprintf(stderr, "%d framework lookups.\n", NumFrameworkLookups);
100 fprintf(stderr, "%d subframework lookups.\n", NumSubFrameworkLookups);
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000101}
102
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000103/// CreateHeaderMap - This method returns a HeaderMap for the specified
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000104/// FileEntry, uniquing them through the 'HeaderMaps' datastructure.
Chris Lattner4ffe46c2007-12-17 18:34:53 +0000105const HeaderMap *HeaderSearch::CreateHeaderMap(const FileEntry *FE) {
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000106 // We expect the number of headermaps to be small, and almost always empty.
Chris Lattnerf62f7582007-12-17 07:52:39 +0000107 // If it ever grows, use of a linear search should be re-evaluated.
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000108 if (!HeaderMaps.empty()) {
109 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
Chris Lattnerf62f7582007-12-17 07:52:39 +0000110 // Pointer equality comparison of FileEntries works because they are
111 // already uniqued by inode.
Mike Stump11289f42009-09-09 15:08:12 +0000112 if (HeaderMaps[i].first == FE)
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000113 return HeaderMaps[i].second;
114 }
Mike Stump11289f42009-09-09 15:08:12 +0000115
Chris Lattner5159f612010-11-23 08:35:12 +0000116 if (const HeaderMap *HM = HeaderMap::Create(FE, FileMgr)) {
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000117 HeaderMaps.push_back(std::make_pair(FE, HM));
118 return HM;
119 }
Mike Stump11289f42009-09-09 15:08:12 +0000120
Craig Topperd2d442c2014-05-17 23:10:59 +0000121 return nullptr;
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000122}
123
Bruno Cardoso Lopes181225b2016-12-11 04:27:28 +0000124/// \brief Get filenames for all registered header maps.
125void HeaderSearch::getHeaderMapFileNames(
126 SmallVectorImpl<std::string> &Names) const {
127 for (auto &HM : HeaderMaps)
128 Names.push_back(HM.first->getName());
129}
130
Douglas Gregor279a6c32012-01-29 17:08:11 +0000131std::string HeaderSearch::getModuleFileName(Module *Module) {
Ben Langmuir9d6448b2014-08-09 00:57:23 +0000132 const FileEntry *ModuleMap =
133 getModuleMap().getModuleMapFileForUniquing(Module);
Manman Ren11f2a472016-08-18 17:42:15 +0000134 return getModuleFileName(Module->Name, ModuleMap->getName(),
135 /*UsePrebuiltPath*/false);
Douglas Gregor279a6c32012-01-29 17:08:11 +0000136}
137
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000138std::string HeaderSearch::getModuleFileName(StringRef ModuleName,
Manman Ren11f2a472016-08-18 17:42:15 +0000139 StringRef ModuleMapPath,
140 bool UsePrebuiltPath) {
141 if (UsePrebuiltPath) {
142 if (HSOpts->PrebuiltModulePaths.empty())
143 return std::string();
144
145 // Go though each prebuilt module path and try to find the pcm file.
146 for (const std::string &Dir : HSOpts->PrebuiltModulePaths) {
147 SmallString<256> Result(Dir);
148 llvm::sys::fs::make_absolute(Result);
149
150 llvm::sys::path::append(Result, ModuleName + ".pcm");
151 if (getFileMgr().getFile(Result.str()))
152 return Result.str().str();
153 }
154 return std::string();
155 }
156
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())
Douglas Gregor279a6c32012-01-29 17:08:11 +0000160 return std::string();
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.
175 auto *Dir =
176 FileMgr.getDirectory(llvm::sys::path::parent_path(ModuleMapPath));
177 if (!Dir)
178 return std::string();
179 auto DirName = FileMgr.getCanonicalName(Dir);
180 auto FileName = llvm::sys::path::filename(ModuleMapPath);
181
182 llvm::hash_code Hash =
Adrian Prantl793038d32016-01-12 21:01:56 +0000183 llvm::hash_combine(DirName.lower(), FileName.lower());
Richard Smith54cc3c22014-12-11 20:50:24 +0000184
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000185 SmallString<128> HashStr;
Richard Smith54cc3c22014-12-11 20:50:24 +0000186 llvm::APInt(64, size_t(Hash)).toStringUnsigned(HashStr, /*Radix*/36);
Yaron Keren92e1b622015-03-18 10:17:07 +0000187 llvm::sys::path::append(Result, ModuleName + "-" + HashStr + ".pcm");
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000188 }
Douglas Gregor279a6c32012-01-29 17:08:11 +0000189 return Result.str().str();
190}
191
192Module *HeaderSearch::lookupModule(StringRef ModuleName, bool AllowSearch) {
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000193 // Look in the module map to determine if there is a module by this name.
Douglas Gregor279a6c32012-01-29 17:08:11 +0000194 Module *Module = ModMap.findModule(ModuleName);
Richard Smith47972af2015-06-16 00:08:24 +0000195 if (Module || !AllowSearch || !HSOpts->ImplicitModuleMaps)
Douglas Gregor279a6c32012-01-29 17:08:11 +0000196 return Module;
Graydon Hoare4d867642016-12-21 00:24:39 +0000197
198 StringRef SearchName = ModuleName;
199 Module = lookupModule(ModuleName, SearchName);
200
201 // The facility for "private modules" -- adjacent, optional module maps named
202 // module.private.modulemap that are supposed to define private submodules --
203 // is sometimes misused by frameworks that name their associated private
204 // module FooPrivate, rather than as a submodule named Foo.Private as
205 // intended. Here we compensate for such cases by looking in directories named
206 // Foo.framework, when we previously looked and failed to find a
207 // FooPrivate.framework.
208 if (!Module && SearchName.consume_back("Private"))
209 Module = lookupModule(ModuleName, SearchName);
210 return Module;
211}
212
213Module *HeaderSearch::lookupModule(StringRef ModuleName, StringRef SearchName) {
214 Module *Module = nullptr;
215
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000216 // Look through the various header search paths to load any available module
Douglas Gregor279a6c32012-01-29 17:08:11 +0000217 // maps, searching for a module map that describes this module.
218 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
219 if (SearchDirs[Idx].isFramework()) {
Graydon Hoare4d867642016-12-21 00:24:39 +0000220 // Search for or infer a module map for a framework. Here we use
221 // SearchName rather than ModuleName, to permit finding private modules
222 // named FooPrivate in buggy frameworks named Foo.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000223 SmallString<128> FrameworkDirName;
Douglas Gregor279a6c32012-01-29 17:08:11 +0000224 FrameworkDirName += SearchDirs[Idx].getFrameworkDir()->getName();
Graydon Hoare4d867642016-12-21 00:24:39 +0000225 llvm::sys::path::append(FrameworkDirName, SearchName + ".framework");
226 if (const DirectoryEntry *FrameworkDir
Douglas Gregor279a6c32012-01-29 17:08:11 +0000227 = FileMgr.getDirectory(FrameworkDirName)) {
228 bool IsSystem
229 = SearchDirs[Idx].getDirCharacteristic() != SrcMgr::C_User;
230 Module = loadFrameworkModule(ModuleName, FrameworkDir, IsSystem);
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000231 if (Module)
232 break;
233 }
Douglas Gregor279a6c32012-01-29 17:08:11 +0000234 }
235
236 // FIXME: Figure out how header maps and module maps will work together.
237
238 // Only deal with normal search directories.
239 if (!SearchDirs[Idx].isNormalDir())
240 continue;
Douglas Gregor963c5532013-06-21 16:28:10 +0000241
242 bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
Douglas Gregor279a6c32012-01-29 17:08:11 +0000243 // Search for a module map file in this directory.
Ben Langmuir984e1df2014-03-19 20:23:34 +0000244 if (loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem,
245 /*IsFramework*/false) == LMM_NewlyLoaded) {
Douglas Gregor279a6c32012-01-29 17:08:11 +0000246 // We just loaded a module map file; check whether the module is
247 // available now.
248 Module = ModMap.findModule(ModuleName);
249 if (Module)
250 break;
251 }
252
253 // Search for a module map in a subdirectory with the same name as the
254 // module.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000255 SmallString<128> NestedModuleMapDirName;
Douglas Gregor279a6c32012-01-29 17:08:11 +0000256 NestedModuleMapDirName = SearchDirs[Idx].getDir()->getName();
257 llvm::sys::path::append(NestedModuleMapDirName, ModuleName);
Ben Langmuir984e1df2014-03-19 20:23:34 +0000258 if (loadModuleMapFile(NestedModuleMapDirName, IsSystem,
259 /*IsFramework*/false) == LMM_NewlyLoaded){
Douglas Gregor279a6c32012-01-29 17:08:11 +0000260 // If we just loaded a module map file, look for the module again.
261 Module = ModMap.findModule(ModuleName);
262 if (Module)
263 break;
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000264 }
Douglas Gregor0339a642013-03-21 01:08:50 +0000265
266 // If we've already performed the exhaustive search for module maps in this
267 // search directory, don't do it again.
268 if (SearchDirs[Idx].haveSearchedAllModuleMaps())
269 continue;
270
271 // Load all module maps in the immediate subdirectories of this search
272 // directory.
273 loadSubdirectoryModuleMaps(SearchDirs[Idx]);
274
275 // Look again for the module.
276 Module = ModMap.findModule(ModuleName);
277 if (Module)
278 break;
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000279 }
Douglas Gregor0339a642013-03-21 01:08:50 +0000280
Douglas Gregor279a6c32012-01-29 17:08:11 +0000281 return Module;
Douglas Gregor1e44e022011-09-12 20:41:59 +0000282}
283
Chris Lattnerf62f7582007-12-17 07:52:39 +0000284//===----------------------------------------------------------------------===//
285// File lookup within a DirectoryLookup scope
286//===----------------------------------------------------------------------===//
287
Chris Lattner8d720d02007-12-17 17:57:27 +0000288/// getName - Return the directory or filename corresponding to this lookup
289/// object.
Mehdi Amini99d1b292016-10-01 16:38:28 +0000290StringRef DirectoryLookup::getName() const {
Chris Lattner8d720d02007-12-17 17:57:27 +0000291 if (isNormalDir())
292 return getDir()->getName();
293 if (isFramework())
294 return getFrameworkDir()->getName();
295 assert(isHeaderMap() && "Unknown DirectoryLookup");
296 return getHeaderMap()->getFileName();
297}
298
Richard Smith3d5b48c2015-10-16 21:42:56 +0000299const FileEntry *HeaderSearch::getFileAndSuggestModule(
Taewook Ohf42103c2016-06-13 20:40:21 +0000300 StringRef FileName, SourceLocation IncludeLoc, const DirectoryEntry *Dir,
301 bool IsSystemHeaderDir, Module *RequestingModule,
302 ModuleMap::KnownHeader *SuggestedModule) {
Richard Smith8c71eba2014-03-05 20:51:45 +0000303 // If we have a module map that might map this header, load it and
304 // check whether we'll have a suggestion for a module.
Richard Smith3d5b48c2015-10-16 21:42:56 +0000305 const FileEntry *File = getFileMgr().getFile(FileName, /*OpenFile=*/true);
Reid Klecknerafb9aae2015-10-20 18:45:57 +0000306 if (!File)
307 return nullptr;
Richard Smith8c71eba2014-03-05 20:51:45 +0000308
Richard Smith3d5b48c2015-10-16 21:42:56 +0000309 // If there is a module that corresponds to this header, suggest it.
310 if (!findUsableModuleForHeader(File, Dir ? Dir : File->getDir(),
311 RequestingModule, SuggestedModule,
312 IsSystemHeaderDir))
313 return nullptr;
Richard Smith8c71eba2014-03-05 20:51:45 +0000314
Richard Smith3d5b48c2015-10-16 21:42:56 +0000315 return File;
Richard Smith8c71eba2014-03-05 20:51:45 +0000316}
Chris Lattner8d720d02007-12-17 17:57:27 +0000317
Chris Lattnerf62f7582007-12-17 07:52:39 +0000318/// LookupFile - Lookup the specified file in this search path, returning it
319/// if it exists or returning null if not.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000320const FileEntry *DirectoryLookup::LookupFile(
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000321 StringRef &Filename,
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000322 HeaderSearch &HS,
Taewook Ohf42103c2016-06-13 20:40:21 +0000323 SourceLocation IncludeLoc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000324 SmallVectorImpl<char> *SearchPath,
Douglas Gregor97eec242011-09-15 22:00:41 +0000325 SmallVectorImpl<char> *RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000326 Module *RequestingModule,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000327 ModuleMap::KnownHeader *SuggestedModule,
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000328 bool &InUserSpecifiedSystemFramework,
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000329 bool &HasBeenMapped,
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000330 SmallVectorImpl<char> &MappedName) const {
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000331 InUserSpecifiedSystemFramework = false;
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000332 HasBeenMapped = false;
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000333
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000334 SmallString<1024> TmpDir;
Chris Lattner712e3872007-12-17 08:13:48 +0000335 if (isNormalDir()) {
336 // Concatenate the requested file onto the directory.
Eli Friedmanf7ca26a2011-07-08 20:17:28 +0000337 TmpDir = getDir()->getName();
338 llvm::sys::path::append(TmpDir, Filename);
Craig Topperd2d442c2014-05-17 23:10:59 +0000339 if (SearchPath) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000340 StringRef SearchPathRef(getDir()->getName());
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000341 SearchPath->clear();
342 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
343 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000344 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000345 RelativePath->clear();
346 RelativePath->append(Filename.begin(), Filename.end());
347 }
Richard Smith8c71eba2014-03-05 20:51:45 +0000348
Taewook Ohf42103c2016-06-13 20:40:21 +0000349 return HS.getFileAndSuggestModule(TmpDir, IncludeLoc, getDir(),
Richard Smith3d5b48c2015-10-16 21:42:56 +0000350 isSystemHeaderDirectory(),
351 RequestingModule, SuggestedModule);
Chris Lattner712e3872007-12-17 08:13:48 +0000352 }
Mike Stump11289f42009-09-09 15:08:12 +0000353
Chris Lattner712e3872007-12-17 08:13:48 +0000354 if (isFramework())
Douglas Gregor97eec242011-09-15 22:00:41 +0000355 return DoFrameworkLookup(Filename, HS, SearchPath, RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000356 RequestingModule, SuggestedModule,
357 InUserSpecifiedSystemFramework);
Mike Stump11289f42009-09-09 15:08:12 +0000358
Chris Lattner44bd21b2007-12-17 08:17:39 +0000359 assert(isHeaderMap() && "Unknown directory lookup");
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000360 const HeaderMap *HM = getHeaderMap();
361 SmallString<1024> Path;
362 StringRef Dest = HM->lookupFilename(Filename, Path);
363 if (Dest.empty())
Craig Topperd2d442c2014-05-17 23:10:59 +0000364 return nullptr;
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000365
366 const FileEntry *Result;
367
368 // Check if the headermap maps the filename to a framework include
369 // ("Foo.h" -> "Foo/Foo.h"), in which case continue header lookup using the
370 // framework include.
371 if (llvm::sys::path::is_relative(Dest)) {
372 MappedName.clear();
373 MappedName.append(Dest.begin(), Dest.end());
374 Filename = StringRef(MappedName.begin(), MappedName.size());
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000375 HasBeenMapped = true;
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000376 Result = HM->LookupFile(Filename, HS.getFileMgr());
377
378 } else {
379 Result = HS.getFileMgr().getFile(Dest);
380 }
381
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000382 if (Result) {
Craig Topperd2d442c2014-05-17 23:10:59 +0000383 if (SearchPath) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000384 StringRef SearchPathRef(getName());
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000385 SearchPath->clear();
386 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
387 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000388 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000389 RelativePath->clear();
390 RelativePath->append(Filename.begin(), Filename.end());
391 }
392 }
393 return Result;
Chris Lattnerf62f7582007-12-17 07:52:39 +0000394}
395
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000396/// \brief Given a framework directory, find the top-most framework directory.
397///
398/// \param FileMgr The file manager to use for directory lookups.
399/// \param DirName The name of the framework directory.
400/// \param SubmodulePath Will be populated with the submodule path from the
401/// returned top-level module to the originally named framework.
402static const DirectoryEntry *
403getTopFrameworkDir(FileManager &FileMgr, StringRef DirName,
404 SmallVectorImpl<std::string> &SubmodulePath) {
405 assert(llvm::sys::path::extension(DirName) == ".framework" &&
406 "Not a framework directory");
407
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000408 // Note: as an egregious but useful hack we use the real path here, because
409 // frameworks moving between top-level frameworks to embedded frameworks tend
410 // to be symlinked, and we base the logical structure of modules on the
411 // physical layout. In particular, we need to deal with crazy includes like
412 //
413 // #include <Foo/Frameworks/Bar.framework/Headers/Wibble.h>
414 //
415 // where 'Bar' used to be embedded in 'Foo', is now a top-level framework
416 // which one should access with, e.g.,
417 //
418 // #include <Bar/Wibble.h>
419 //
420 // Similar issues occur when a top-level framework has moved into an
421 // embedded framework.
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000422 const DirectoryEntry *TopFrameworkDir = FileMgr.getDirectory(DirName);
Douglas Gregore00c8b22013-01-26 00:55:12 +0000423 DirName = FileMgr.getCanonicalName(TopFrameworkDir);
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000424 do {
425 // Get the parent directory name.
426 DirName = llvm::sys::path::parent_path(DirName);
427 if (DirName.empty())
428 break;
429
430 // Determine whether this directory exists.
431 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
432 if (!Dir)
433 break;
434
435 // If this is a framework directory, then we're a subframework of this
436 // framework.
437 if (llvm::sys::path::extension(DirName) == ".framework") {
438 SubmodulePath.push_back(llvm::sys::path::stem(DirName));
439 TopFrameworkDir = Dir;
440 }
441 } while (true);
442
443 return TopFrameworkDir;
444}
Chris Lattnerf62f7582007-12-17 07:52:39 +0000445
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +0000446static bool needModuleLookup(Module *RequestingModule,
447 bool HasSuggestedModule) {
448 return HasSuggestedModule ||
449 (RequestingModule && RequestingModule->NoUndeclaredIncludes);
450}
451
Chris Lattner712e3872007-12-17 08:13:48 +0000452/// DoFrameworkLookup - Do a lookup of the specified file in the current
453/// DirectoryLookup, which is a framework directory.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000454const FileEntry *DirectoryLookup::DoFrameworkLookup(
Richard Smith3d5b48c2015-10-16 21:42:56 +0000455 StringRef Filename, HeaderSearch &HS, SmallVectorImpl<char> *SearchPath,
456 SmallVectorImpl<char> *RelativePath, Module *RequestingModule,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000457 ModuleMap::KnownHeader *SuggestedModule,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000458 bool &InUserSpecifiedSystemFramework) const {
Chris Lattner712e3872007-12-17 08:13:48 +0000459 FileManager &FileMgr = HS.getFileMgr();
Mike Stump11289f42009-09-09 15:08:12 +0000460
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000461 // Framework names must have a '/' in the filename.
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000462 size_t SlashPos = Filename.find('/');
Craig Topperd2d442c2014-05-17 23:10:59 +0000463 if (SlashPos == StringRef::npos) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000464
Chris Lattner712e3872007-12-17 08:13:48 +0000465 // Find out if this is the home for the specified framework, by checking
Daniel Dunbar17138612012-04-05 17:09:40 +0000466 // HeaderSearch. Possible answers are yes/no and unknown.
467 HeaderSearch::FrameworkCacheEntry &CacheEntry =
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000468 HS.LookupFrameworkCache(Filename.substr(0, SlashPos));
Mike Stump11289f42009-09-09 15:08:12 +0000469
Chris Lattner712e3872007-12-17 08:13:48 +0000470 // If it is known and in some other directory, fail.
Daniel Dunbar17138612012-04-05 17:09:40 +0000471 if (CacheEntry.Directory && CacheEntry.Directory != getFrameworkDir())
Craig Topperd2d442c2014-05-17 23:10:59 +0000472 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000473
Chris Lattner712e3872007-12-17 08:13:48 +0000474 // Otherwise, construct the path to this framework dir.
Mike Stump11289f42009-09-09 15:08:12 +0000475
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000476 // FrameworkName = "/System/Library/Frameworks/"
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000477 SmallString<1024> FrameworkName;
Chris Lattner712e3872007-12-17 08:13:48 +0000478 FrameworkName += getFrameworkDir()->getName();
Chris Lattnerb201d9b2006-10-30 05:09:49 +0000479 if (FrameworkName.empty() || FrameworkName.back() != '/')
480 FrameworkName.push_back('/');
Mike Stump11289f42009-09-09 15:08:12 +0000481
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000482 // FrameworkName = "/System/Library/Frameworks/Cocoa"
Douglas Gregor56c64012011-11-17 01:41:17 +0000483 StringRef ModuleName(Filename.begin(), SlashPos);
484 FrameworkName += ModuleName;
Mike Stump11289f42009-09-09 15:08:12 +0000485
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000486 // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/"
487 FrameworkName += ".framework/";
Mike Stump11289f42009-09-09 15:08:12 +0000488
Daniel Dunbar17138612012-04-05 17:09:40 +0000489 // If the cache entry was unresolved, populate it now.
Craig Topperd2d442c2014-05-17 23:10:59 +0000490 if (!CacheEntry.Directory) {
Chris Lattner712e3872007-12-17 08:13:48 +0000491 HS.IncrementFrameworkLookupCount();
Mike Stump11289f42009-09-09 15:08:12 +0000492
Chris Lattner5ed76da2006-10-22 07:24:13 +0000493 // If the framework dir doesn't exist, we fail.
Yaron Keren92e1b622015-03-18 10:17:07 +0000494 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName);
Craig Topperd2d442c2014-05-17 23:10:59 +0000495 if (!Dir) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000496
Chris Lattner5ed76da2006-10-22 07:24:13 +0000497 // Otherwise, if it does, remember that this is the right direntry for this
498 // framework.
Daniel Dunbar17138612012-04-05 17:09:40 +0000499 CacheEntry.Directory = getFrameworkDir();
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000500
501 // If this is a user search directory, check if the framework has been
502 // user-specified as a system framework.
503 if (getDirCharacteristic() == SrcMgr::C_User) {
504 SmallString<1024> SystemFrameworkMarker(FrameworkName);
505 SystemFrameworkMarker += ".system_framework";
Yaron Keren92e1b622015-03-18 10:17:07 +0000506 if (llvm::sys::fs::exists(SystemFrameworkMarker)) {
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000507 CacheEntry.IsUserSpecifiedSystemFramework = true;
508 }
509 }
Chris Lattner5ed76da2006-10-22 07:24:13 +0000510 }
Mike Stump11289f42009-09-09 15:08:12 +0000511
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000512 // Set the 'user-specified system framework' flag.
513 InUserSpecifiedSystemFramework = CacheEntry.IsUserSpecifiedSystemFramework;
514
Craig Topperd2d442c2014-05-17 23:10:59 +0000515 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000516 RelativePath->clear();
517 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
518 }
Douglas Gregor56c64012011-11-17 01:41:17 +0000519
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000520 // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"
Chris Lattnerb201d9b2006-10-30 05:09:49 +0000521 unsigned OrigSize = FrameworkName.size();
Mike Stump11289f42009-09-09 15:08:12 +0000522
Chris Lattnerb201d9b2006-10-30 05:09:49 +0000523 FrameworkName += "Headers/";
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000524
Craig Topperd2d442c2014-05-17 23:10:59 +0000525 if (SearchPath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000526 SearchPath->clear();
527 // Without trailing '/'.
528 SearchPath->append(FrameworkName.begin(), FrameworkName.end()-1);
529 }
530
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000531 FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end());
Yaron Keren92e1b622015-03-18 10:17:07 +0000532 const FileEntry *FE = FileMgr.getFile(FrameworkName,
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000533 /*openFile=*/!SuggestedModule);
534 if (!FE) {
535 // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"
536 const char *Private = "Private";
537 FrameworkName.insert(FrameworkName.begin()+OrigSize, Private,
538 Private+strlen(Private));
Craig Topperd2d442c2014-05-17 23:10:59 +0000539 if (SearchPath)
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000540 SearchPath->insert(SearchPath->begin()+OrigSize, Private,
541 Private+strlen(Private));
542
Yaron Keren92e1b622015-03-18 10:17:07 +0000543 FE = FileMgr.getFile(FrameworkName, /*openFile=*/!SuggestedModule);
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000544 }
Mike Stump11289f42009-09-09 15:08:12 +0000545
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000546 // If we found the header and are allowed to suggest a module, do so now.
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +0000547 if (FE && needModuleLookup(RequestingModule, SuggestedModule)) {
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000548 // Find the framework in which this header occurs.
Ben Langmuiref914b82014-05-15 16:20:33 +0000549 StringRef FrameworkPath = FE->getDir()->getName();
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000550 bool FoundFramework = false;
551 do {
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000552 // Determine whether this directory exists.
553 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkPath);
554 if (!Dir)
555 break;
556
557 // If this is a framework directory, then we're a subframework of this
558 // framework.
559 if (llvm::sys::path::extension(FrameworkPath) == ".framework") {
560 FoundFramework = true;
561 break;
562 }
Ben Langmuiref914b82014-05-15 16:20:33 +0000563
564 // Get the parent directory name.
565 FrameworkPath = llvm::sys::path::parent_path(FrameworkPath);
566 if (FrameworkPath.empty())
567 break;
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000568 } while (true);
569
Richard Smith3d5b48c2015-10-16 21:42:56 +0000570 bool IsSystem = getDirCharacteristic() != SrcMgr::C_User;
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000571 if (FoundFramework) {
Richard Smith3d5b48c2015-10-16 21:42:56 +0000572 if (!HS.findUsableModuleForFrameworkHeader(
573 FE, FrameworkPath, RequestingModule, SuggestedModule, IsSystem))
574 return nullptr;
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000575 } else {
Richard Smith3d5b48c2015-10-16 21:42:56 +0000576 if (!HS.findUsableModuleForHeader(FE, getDir(), RequestingModule,
577 SuggestedModule, IsSystem))
578 return nullptr;
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000579 }
580 }
Douglas Gregor97eec242011-09-15 22:00:41 +0000581 return FE;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000582}
583
Douglas Gregor89929282012-01-30 06:01:29 +0000584void HeaderSearch::setTarget(const TargetInfo &Target) {
585 ModMap.setTarget(Target);
586}
587
Chris Lattnerf62f7582007-12-17 07:52:39 +0000588
Chris Lattner712e3872007-12-17 08:13:48 +0000589//===----------------------------------------------------------------------===//
590// Header File Location.
591//===----------------------------------------------------------------------===//
592
Reid Klecknera97d4c02014-02-18 23:49:24 +0000593/// \brief Return true with a diagnostic if the file that MSVC would have found
594/// fails to match the one that Clang would have found with MSVC header search
595/// disabled.
596static bool checkMSVCHeaderSearch(DiagnosticsEngine &Diags,
597 const FileEntry *MSFE, const FileEntry *FE,
598 SourceLocation IncludeLoc) {
599 if (MSFE && FE != MSFE) {
600 Diags.Report(IncludeLoc, diag::ext_pp_include_search_ms) << MSFE->getName();
601 return true;
602 }
603 return false;
604}
Chris Lattner712e3872007-12-17 08:13:48 +0000605
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000606static const char *copyString(StringRef Str, llvm::BumpPtrAllocator &Alloc) {
607 assert(!Str.empty());
608 char *CopyStr = Alloc.Allocate<char>(Str.size()+1);
609 std::copy(Str.begin(), Str.end(), CopyStr);
610 CopyStr[Str.size()] = '\0';
611 return CopyStr;
612}
613
James Dennettc07ab2c2012-06-20 00:56:32 +0000614/// LookupFile - Given a "foo" or \<foo> reference, look up the indicated file,
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000615/// return null on failure. isAngled indicates whether the file reference is
Will Wilson0fafd342013-12-27 19:46:16 +0000616/// for system \#include's or not (i.e. using <> instead of ""). Includers, if
617/// non-empty, indicates where the \#including file(s) are, in case a relative
618/// search is needed. Microsoft mode will pass all \#including files.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000619const FileEntry *HeaderSearch::LookupFile(
Will Wilson0fafd342013-12-27 19:46:16 +0000620 StringRef Filename, SourceLocation IncludeLoc, bool isAngled,
621 const DirectoryLookup *FromDir, const DirectoryLookup *&CurDir,
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000622 ArrayRef<std::pair<const FileEntry *, const DirectoryEntry *>> Includers,
623 SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000624 Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule,
Manman Rene4a5d372016-05-17 02:15:12 +0000625 bool SkipCache, bool BuildSystemModule) {
Douglas Gregor97eec242011-09-15 22:00:41 +0000626 if (SuggestedModule)
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000627 *SuggestedModule = ModuleMap::KnownHeader();
Douglas Gregor97eec242011-09-15 22:00:41 +0000628
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000629 // If 'Filename' is absolute, check to see if it exists and no searching.
Michael J. Spencerf28df4c2010-12-17 21:22:22 +0000630 if (llvm::sys::path::is_absolute(Filename)) {
Craig Topperd2d442c2014-05-17 23:10:59 +0000631 CurDir = nullptr;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000632
633 // If this was an #include_next "/absolute/file", fail.
Craig Topperd2d442c2014-05-17 23:10:59 +0000634 if (FromDir) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000635
Craig Topperd2d442c2014-05-17 23:10:59 +0000636 if (SearchPath)
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000637 SearchPath->clear();
Craig Topperd2d442c2014-05-17 23:10:59 +0000638 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000639 RelativePath->clear();
640 RelativePath->append(Filename.begin(), Filename.end());
641 }
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000642 // Otherwise, just return the file.
Taewook Ohf42103c2016-06-13 20:40:21 +0000643 return getFileAndSuggestModule(Filename, IncludeLoc, nullptr,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000644 /*IsSystemHeaderDir*/false,
645 RequestingModule, SuggestedModule);
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000646 }
Mike Stump11289f42009-09-09 15:08:12 +0000647
Reid Klecknera97d4c02014-02-18 23:49:24 +0000648 // This is the header that MSVC's header search would have found.
Craig Topperd2d442c2014-05-17 23:10:59 +0000649 const FileEntry *MSFE = nullptr;
Richard Smith8c71eba2014-03-05 20:51:45 +0000650 ModuleMap::KnownHeader MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000651
Douglas Gregor9f93e382011-07-28 04:45:53 +0000652 // Unless disabled, check to see if the file is in the #includer's
Will Wilson0fafd342013-12-27 19:46:16 +0000653 // directory. This cannot be based on CurDir, because each includer could be
654 // a #include of a subdirectory (#include "foo/bar.h") and a subsequent
655 // include of "baz.h" should resolve to "whatever/foo/baz.h".
Chris Lattnerf62f7582007-12-17 07:52:39 +0000656 // This search is not done for <> headers.
Will Wilson0fafd342013-12-27 19:46:16 +0000657 if (!Includers.empty() && !isAngled && !NoCurDirSearch) {
NAKAMURA Takumi9cb62642013-12-10 02:36:28 +0000658 SmallString<1024> TmpDir;
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000659 bool First = true;
660 for (const auto &IncluderAndDir : Includers) {
661 const FileEntry *Includer = IncluderAndDir.first;
662
Will Wilson0fafd342013-12-27 19:46:16 +0000663 // Concatenate the requested file onto the directory.
Nikola Smiljaniccf385dc2015-05-08 06:02:37 +0000664 // FIXME: Portability. Filename concatenation should be in sys::Path.
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000665 TmpDir = IncluderAndDir.second->getName();
Nikola Smiljaniccf385dc2015-05-08 06:02:37 +0000666 TmpDir.push_back('/');
667 TmpDir.append(Filename.begin(), Filename.end());
Richard Smith8c71eba2014-03-05 20:51:45 +0000668
Richard Smith6f548ec2014-03-06 18:08:08 +0000669 // FIXME: We don't cache the result of getFileInfo across the call to
670 // getFileAndSuggestModule, because it's a reference to an element of
671 // a container that could be reallocated across this call.
Richard Smith3c1a41a2014-12-02 00:08:08 +0000672 //
Manman Rene4a5d372016-05-17 02:15:12 +0000673 // If we have no includer, that means we're processing a #include
Richard Smith3c1a41a2014-12-02 00:08:08 +0000674 // from a module build. We should treat this as a system header if we're
675 // building a [system] module.
Richard Smith6f548ec2014-03-06 18:08:08 +0000676 bool IncluderIsSystemHeader =
Manman Rene39c8142016-05-17 18:04:38 +0000677 Includer ? getFileInfo(Includer).DirInfo != SrcMgr::C_User :
678 BuildSystemModule;
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000679 if (const FileEntry *FE = getFileAndSuggestModule(
Taewook Ohf42103c2016-06-13 20:40:21 +0000680 TmpDir, IncludeLoc, IncluderAndDir.second, IncluderIsSystemHeader,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000681 RequestingModule, SuggestedModule)) {
Richard Smith3c1a41a2014-12-02 00:08:08 +0000682 if (!Includer) {
683 assert(First && "only first includer can have no file");
684 return FE;
685 }
686
Will Wilson0fafd342013-12-27 19:46:16 +0000687 // Leave CurDir unset.
688 // This file is a system header or C++ unfriendly if the old file is.
689 //
690 // Note that we only use one of FromHFI/ToHFI at once, due to potential
691 // reallocation of the underlying vector potentially making the first
692 // reference binding dangling.
Richard Smith6f548ec2014-03-06 18:08:08 +0000693 HeaderFileInfo &FromHFI = getFileInfo(Includer);
Will Wilson0fafd342013-12-27 19:46:16 +0000694 unsigned DirInfo = FromHFI.DirInfo;
695 bool IndexHeaderMapHeader = FromHFI.IndexHeaderMapHeader;
696 StringRef Framework = FromHFI.Framework;
Douglas Gregor03b5ebe2012-08-13 15:47:39 +0000697
Will Wilson0fafd342013-12-27 19:46:16 +0000698 HeaderFileInfo &ToHFI = getFileInfo(FE);
699 ToHFI.DirInfo = DirInfo;
700 ToHFI.IndexHeaderMapHeader = IndexHeaderMapHeader;
701 ToHFI.Framework = Framework;
Douglas Gregor03b5ebe2012-08-13 15:47:39 +0000702
Craig Topperd2d442c2014-05-17 23:10:59 +0000703 if (SearchPath) {
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000704 StringRef SearchPathRef(IncluderAndDir.second->getName());
Will Wilson0fafd342013-12-27 19:46:16 +0000705 SearchPath->clear();
706 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
707 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000708 if (RelativePath) {
Will Wilson0fafd342013-12-27 19:46:16 +0000709 RelativePath->clear();
710 RelativePath->append(Filename.begin(), Filename.end());
711 }
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000712 if (First)
Reid Klecknera97d4c02014-02-18 23:49:24 +0000713 return FE;
714
715 // Otherwise, we found the path via MSVC header search rules. If
716 // -Wmsvc-include is enabled, we have to keep searching to see if we
717 // would've found this header in -I or -isystem directories.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +0000718 if (Diags.isIgnored(diag::ext_pp_include_search_ms, IncludeLoc)) {
Reid Klecknera97d4c02014-02-18 23:49:24 +0000719 return FE;
720 } else {
721 MSFE = FE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000722 if (SuggestedModule) {
723 MSSuggestedModule = *SuggestedModule;
724 *SuggestedModule = ModuleMap::KnownHeader();
725 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000726 break;
727 }
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000728 }
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000729 First = false;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000730 }
731 }
Mike Stump11289f42009-09-09 15:08:12 +0000732
Craig Topperd2d442c2014-05-17 23:10:59 +0000733 CurDir = nullptr;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000734
735 // If this is a system #include, ignore the user #include locs.
Nico Weber3b1d1212011-05-24 04:31:14 +0000736 unsigned i = isAngled ? AngledDirIdx : 0;
Mike Stump11289f42009-09-09 15:08:12 +0000737
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000738 // If this is a #include_next request, start searching after the directory the
739 // file was found in.
740 if (FromDir)
741 i = FromDir-&SearchDirs[0];
Mike Stump11289f42009-09-09 15:08:12 +0000742
Chris Lattnerd4275422007-07-22 07:28:00 +0000743 // Cache all of the lookups performed by this method. Many headers are
744 // multiply included, and the "pragma once" optimization prevents them from
745 // being relex/pp'd, but they would still have to search through a
746 // (potentially huge) series of SearchDirs to find it.
David Blaikie13156b62014-11-19 03:06:06 +0000747 LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename];
Chris Lattnerd4275422007-07-22 07:28:00 +0000748
749 // If the entry has been previously looked up, the first value will be
750 // non-zero. If the value is equal to i (the start point of our search), then
751 // this is a matching hit.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000752 if (!SkipCache && CacheLookup.StartIdx == i+1) {
Chris Lattnerd4275422007-07-22 07:28:00 +0000753 // Skip querying potentially lots of directories for this lookup.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000754 i = CacheLookup.HitIdx;
755 if (CacheLookup.MappedName)
756 Filename = CacheLookup.MappedName;
Chris Lattnerd4275422007-07-22 07:28:00 +0000757 } else {
758 // Otherwise, this is the first query, or the previous query didn't match
759 // our search start. We will fill in our found location below, so prime the
760 // start point value.
Argyrios Kyrtzidis7bd78a92014-03-29 03:22:54 +0000761 CacheLookup.reset(/*StartIdx=*/i+1);
Chris Lattnerd4275422007-07-22 07:28:00 +0000762 }
Mike Stump11289f42009-09-09 15:08:12 +0000763
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000764 SmallString<64> MappedName;
765
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000766 // Check each directory in sequence to see if it contains this file.
767 for (; i != SearchDirs.size(); ++i) {
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000768 bool InUserSpecifiedSystemFramework = false;
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000769 bool HasBeenMapped = false;
Richard Smith3d5b48c2015-10-16 21:42:56 +0000770 const FileEntry *FE = SearchDirs[i].LookupFile(
Taewook Ohf42103c2016-06-13 20:40:21 +0000771 Filename, *this, IncludeLoc, SearchPath, RelativePath, RequestingModule,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000772 SuggestedModule, InUserSpecifiedSystemFramework, HasBeenMapped,
773 MappedName);
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000774 if (HasBeenMapped) {
775 CacheLookup.MappedName =
776 copyString(Filename, LookupFileCache.getAllocator());
777 }
Chris Lattner712e3872007-12-17 08:13:48 +0000778 if (!FE) continue;
Mike Stump11289f42009-09-09 15:08:12 +0000779
Chris Lattner712e3872007-12-17 08:13:48 +0000780 CurDir = &SearchDirs[i];
Mike Stump11289f42009-09-09 15:08:12 +0000781
Chris Lattner712e3872007-12-17 08:13:48 +0000782 // This file is a system header or C++ unfriendly if the dir is.
Douglas Gregor9f93e382011-07-28 04:45:53 +0000783 HeaderFileInfo &HFI = getFileInfo(FE);
784 HFI.DirInfo = CurDir->getDirCharacteristic();
Mike Stump11289f42009-09-09 15:08:12 +0000785
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000786 // If the directory characteristic is User but this framework was
787 // user-specified to be treated as a system framework, promote the
788 // characteristic.
789 if (HFI.DirInfo == SrcMgr::C_User && InUserSpecifiedSystemFramework)
790 HFI.DirInfo = SrcMgr::C_System;
791
Richard Smith8acadcb2012-06-13 20:27:03 +0000792 // If the filename matches a known system header prefix, override
793 // whether the file is a system header.
Richard Trieu871f5f32012-06-13 20:52:36 +0000794 for (unsigned j = SystemHeaderPrefixes.size(); j; --j) {
795 if (Filename.startswith(SystemHeaderPrefixes[j-1].first)) {
796 HFI.DirInfo = SystemHeaderPrefixes[j-1].second ? SrcMgr::C_System
Richard Smith8acadcb2012-06-13 20:27:03 +0000797 : SrcMgr::C_User;
798 break;
799 }
800 }
801
Douglas Gregor9f93e382011-07-28 04:45:53 +0000802 // If this file is found in a header map and uses the framework style of
803 // includes, then this header is part of a framework we're building.
804 if (CurDir->isIndexHeaderMap()) {
805 size_t SlashPos = Filename.find('/');
806 if (SlashPos != StringRef::npos) {
807 HFI.IndexHeaderMapHeader = 1;
808 HFI.Framework = getUniqueFrameworkName(StringRef(Filename.begin(),
809 SlashPos));
810 }
811 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000812
Richard Smith8c71eba2014-03-05 20:51:45 +0000813 if (checkMSVCHeaderSearch(Diags, MSFE, FE, IncludeLoc)) {
814 if (SuggestedModule)
815 *SuggestedModule = MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000816 return MSFE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000817 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000818
Chris Lattner712e3872007-12-17 08:13:48 +0000819 // Remember this location for the next lookup we do.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000820 CacheLookup.HitIdx = i;
Chris Lattner712e3872007-12-17 08:13:48 +0000821 return FE;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000822 }
Mike Stump11289f42009-09-09 15:08:12 +0000823
Douglas Gregord8575e12011-07-30 06:28:34 +0000824 // If we are including a file with a quoted include "foo.h" from inside
825 // a header in a framework that is currently being built, and we couldn't
826 // resolve "foo.h" any other way, change the include to <Foo/foo.h>, where
827 // "Foo" is the name of the framework in which the including header was found.
Richard Smith3c1a41a2014-12-02 00:08:08 +0000828 if (!Includers.empty() && Includers.front().first && !isAngled &&
Will Wilson0fafd342013-12-27 19:46:16 +0000829 Filename.find('/') == StringRef::npos) {
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000830 HeaderFileInfo &IncludingHFI = getFileInfo(Includers.front().first);
Douglas Gregord8575e12011-07-30 06:28:34 +0000831 if (IncludingHFI.IndexHeaderMapHeader) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000832 SmallString<128> ScratchFilename;
Douglas Gregord8575e12011-07-30 06:28:34 +0000833 ScratchFilename += IncludingHFI.Framework;
834 ScratchFilename += '/';
835 ScratchFilename += Filename;
Will Wilson0fafd342013-12-27 19:46:16 +0000836
Richard Smith3d5b48c2015-10-16 21:42:56 +0000837 const FileEntry *FE =
838 LookupFile(ScratchFilename, IncludeLoc, /*isAngled=*/true, FromDir,
839 CurDir, Includers.front(), SearchPath, RelativePath,
840 RequestingModule, SuggestedModule);
Reid Klecknera97d4c02014-02-18 23:49:24 +0000841
Richard Smith8c71eba2014-03-05 20:51:45 +0000842 if (checkMSVCHeaderSearch(Diags, MSFE, FE, IncludeLoc)) {
843 if (SuggestedModule)
844 *SuggestedModule = MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000845 return MSFE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000846 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000847
David Blaikie3c8c46e2014-11-19 05:48:40 +0000848 LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename];
David Blaikie13156b62014-11-19 03:06:06 +0000849 CacheLookup.HitIdx = LookupFileCache[ScratchFilename].HitIdx;
Richard Smith8c71eba2014-03-05 20:51:45 +0000850 // FIXME: SuggestedModule.
Reid Klecknera97d4c02014-02-18 23:49:24 +0000851 return FE;
Douglas Gregord8575e12011-07-30 06:28:34 +0000852 }
853 }
854
Craig Topperd2d442c2014-05-17 23:10:59 +0000855 if (checkMSVCHeaderSearch(Diags, MSFE, nullptr, IncludeLoc)) {
Richard Smith8c71eba2014-03-05 20:51:45 +0000856 if (SuggestedModule)
857 *SuggestedModule = MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000858 return MSFE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000859 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000860
Chris Lattnerd4275422007-07-22 07:28:00 +0000861 // Otherwise, didn't find it. Remember we didn't find this.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000862 CacheLookup.HitIdx = SearchDirs.size();
Craig Topperd2d442c2014-05-17 23:10:59 +0000863 return nullptr;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000864}
865
Chris Lattner63dd32b2006-10-20 04:42:40 +0000866/// LookupSubframeworkHeader - Look up a subframework for the specified
James Dennettc07ab2c2012-06-20 00:56:32 +0000867/// \#include file. For example, if \#include'ing <HIToolbox/HIToolbox.h> from
Chris Lattner63dd32b2006-10-20 04:42:40 +0000868/// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
869/// is a subframework within Carbon.framework. If so, return the FileEntry
870/// for the designated file, otherwise return null.
871const FileEntry *HeaderSearch::
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000872LookupSubframeworkHeader(StringRef Filename,
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000873 const FileEntry *ContextFileEnt,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000874 SmallVectorImpl<char> *SearchPath,
Douglas Gregorf5f94522013-02-08 00:10:48 +0000875 SmallVectorImpl<char> *RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000876 Module *RequestingModule,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000877 ModuleMap::KnownHeader *SuggestedModule) {
Chris Lattner12261882008-02-01 05:34:02 +0000878 assert(ContextFileEnt && "No context file?");
Mike Stump11289f42009-09-09 15:08:12 +0000879
Chris Lattner63dd32b2006-10-20 04:42:40 +0000880 // Framework names must have a '/' in the filename. Find it.
Douglas Gregor5ca04bd2011-12-09 16:48:01 +0000881 // FIXME: Should we permit '\' on Windows?
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000882 size_t SlashPos = Filename.find('/');
Craig Topperd2d442c2014-05-17 23:10:59 +0000883 if (SlashPos == StringRef::npos) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000884
Chris Lattner63dd32b2006-10-20 04:42:40 +0000885 // Look up the base framework name of the ContextFileEnt.
Mehdi Amini004b9c72016-10-10 22:52:47 +0000886 StringRef ContextName = ContextFileEnt->getName();
Mike Stump11289f42009-09-09 15:08:12 +0000887
Chris Lattner63dd32b2006-10-20 04:42:40 +0000888 // If the context info wasn't a framework, couldn't be a subframework.
Douglas Gregor5ca04bd2011-12-09 16:48:01 +0000889 const unsigned DotFrameworkLen = 10;
Mehdi Amini004b9c72016-10-10 22:52:47 +0000890 auto FrameworkPos = ContextName.find(".framework");
891 if (FrameworkPos == StringRef::npos ||
892 (ContextName[FrameworkPos + DotFrameworkLen] != '/' &&
893 ContextName[FrameworkPos + DotFrameworkLen] != '\\'))
Craig Topperd2d442c2014-05-17 23:10:59 +0000894 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000895
Mehdi Amini004b9c72016-10-10 22:52:47 +0000896 SmallString<1024> FrameworkName(ContextName.data(), ContextName.data() +
897 FrameworkPos +
898 DotFrameworkLen + 1);
Chris Lattner5ed76da2006-10-22 07:24:13 +0000899
Chris Lattner63dd32b2006-10-20 04:42:40 +0000900 // Append Frameworks/HIToolbox.framework/
901 FrameworkName += "Frameworks/";
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000902 FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos);
Chris Lattner63dd32b2006-10-20 04:42:40 +0000903 FrameworkName += ".framework/";
Chris Lattner577377e2006-10-20 04:55:45 +0000904
David Blaikie13156b62014-11-19 03:06:06 +0000905 auto &CacheLookup =
906 *FrameworkMap.insert(std::make_pair(Filename.substr(0, SlashPos),
907 FrameworkCacheEntry())).first;
Mike Stump11289f42009-09-09 15:08:12 +0000908
Chris Lattner5ed76da2006-10-22 07:24:13 +0000909 // Some other location?
David Blaikie13156b62014-11-19 03:06:06 +0000910 if (CacheLookup.second.Directory &&
911 CacheLookup.first().size() == FrameworkName.size() &&
912 memcmp(CacheLookup.first().data(), &FrameworkName[0],
913 CacheLookup.first().size()) != 0)
Craig Topperd2d442c2014-05-17 23:10:59 +0000914 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000915
Chris Lattner5ed76da2006-10-22 07:24:13 +0000916 // Cache subframework.
David Blaikie13156b62014-11-19 03:06:06 +0000917 if (!CacheLookup.second.Directory) {
Chris Lattner5ed76da2006-10-22 07:24:13 +0000918 ++NumSubFrameworkLookups;
Mike Stump11289f42009-09-09 15:08:12 +0000919
Chris Lattner5ed76da2006-10-22 07:24:13 +0000920 // If the framework dir doesn't exist, we fail.
Yaron Keren92e1b622015-03-18 10:17:07 +0000921 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName);
Craig Topperd2d442c2014-05-17 23:10:59 +0000922 if (!Dir) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000923
Chris Lattner5ed76da2006-10-22 07:24:13 +0000924 // Otherwise, if it does, remember that this is the right direntry for this
925 // framework.
David Blaikie13156b62014-11-19 03:06:06 +0000926 CacheLookup.second.Directory = Dir;
Chris Lattner5ed76da2006-10-22 07:24:13 +0000927 }
Mike Stump11289f42009-09-09 15:08:12 +0000928
Craig Topperd2d442c2014-05-17 23:10:59 +0000929 const FileEntry *FE = nullptr;
Chris Lattner577377e2006-10-20 04:55:45 +0000930
Craig Topperd2d442c2014-05-17 23:10:59 +0000931 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000932 RelativePath->clear();
933 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
934 }
935
Chris Lattner63dd32b2006-10-20 04:42:40 +0000936 // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000937 SmallString<1024> HeadersFilename(FrameworkName);
Chris Lattner43fd42e2006-10-30 03:40:58 +0000938 HeadersFilename += "Headers/";
Craig Topperd2d442c2014-05-17 23:10:59 +0000939 if (SearchPath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000940 SearchPath->clear();
941 // Without trailing '/'.
942 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
943 }
944
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000945 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
Yaron Keren92e1b622015-03-18 10:17:07 +0000946 if (!(FE = FileMgr.getFile(HeadersFilename, /*openFile=*/true))) {
Mike Stump11289f42009-09-09 15:08:12 +0000947
Chris Lattner63dd32b2006-10-20 04:42:40 +0000948 // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
Chris Lattner43fd42e2006-10-30 03:40:58 +0000949 HeadersFilename = FrameworkName;
950 HeadersFilename += "PrivateHeaders/";
Craig Topperd2d442c2014-05-17 23:10:59 +0000951 if (SearchPath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000952 SearchPath->clear();
953 // Without trailing '/'.
954 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
955 }
956
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000957 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
Yaron Keren92e1b622015-03-18 10:17:07 +0000958 if (!(FE = FileMgr.getFile(HeadersFilename, /*openFile=*/true)))
Craig Topperd2d442c2014-05-17 23:10:59 +0000959 return nullptr;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000960 }
Mike Stump11289f42009-09-09 15:08:12 +0000961
Chris Lattner577377e2006-10-20 04:55:45 +0000962 // This file is a system header or C++ unfriendly if the old file is.
Ted Kremenek72be0682008-02-24 03:55:14 +0000963 //
Chris Lattnerf5c619f2008-02-25 21:38:21 +0000964 // Note that the temporary 'DirInfo' is required here, as either call to
965 // getFileInfo could resize the vector and we don't want to rely on order
966 // of evaluation.
967 unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo;
968 getFileInfo(FE).DirInfo = DirInfo;
Douglas Gregorf5f94522013-02-08 00:10:48 +0000969
Richard Smith3d5b48c2015-10-16 21:42:56 +0000970 FrameworkName.pop_back(); // remove the trailing '/'
971 if (!findUsableModuleForFrameworkHeader(FE, FrameworkName, RequestingModule,
972 SuggestedModule, /*IsSystem*/ false))
973 return nullptr;
Douglas Gregorf5f94522013-02-08 00:10:48 +0000974
Chris Lattner577377e2006-10-20 04:55:45 +0000975 return FE;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000976}
977
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000978//===----------------------------------------------------------------------===//
979// File Info Management.
980//===----------------------------------------------------------------------===//
981
Douglas Gregor5d1bee22011-09-17 05:35:18 +0000982/// \brief Merge the header file info provided by \p OtherHFI into the current
983/// header file info (\p HFI)
984static void mergeHeaderFileInfo(HeaderFileInfo &HFI,
985 const HeaderFileInfo &OtherHFI) {
Richard Smithd8879c82015-08-24 21:59:32 +0000986 assert(OtherHFI.External && "expected to merge external HFI");
987
Douglas Gregor5d1bee22011-09-17 05:35:18 +0000988 HFI.isImport |= OtherHFI.isImport;
989 HFI.isPragmaOnce |= OtherHFI.isPragmaOnce;
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +0000990 HFI.isModuleHeader |= OtherHFI.isModuleHeader;
Douglas Gregor5d1bee22011-09-17 05:35:18 +0000991 HFI.NumIncludes += OtherHFI.NumIncludes;
Richard Smithd8879c82015-08-24 21:59:32 +0000992
Douglas Gregor5d1bee22011-09-17 05:35:18 +0000993 if (!HFI.ControllingMacro && !HFI.ControllingMacroID) {
994 HFI.ControllingMacro = OtherHFI.ControllingMacro;
995 HFI.ControllingMacroID = OtherHFI.ControllingMacroID;
996 }
Richard Smithd8879c82015-08-24 21:59:32 +0000997
998 HFI.DirInfo = OtherHFI.DirInfo;
999 HFI.External = (!HFI.IsValid || HFI.External);
1000 HFI.IsValid = true;
1001 HFI.IndexHeaderMapHeader = OtherHFI.IndexHeaderMapHeader;
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001002
Douglas Gregor5d1bee22011-09-17 05:35:18 +00001003 if (HFI.Framework.empty())
1004 HFI.Framework = OtherHFI.Framework;
Douglas Gregor5d1bee22011-09-17 05:35:18 +00001005}
1006
Steve Naroff3fa455a2009-04-24 20:03:17 +00001007/// getFileInfo - Return the HeaderFileInfo structure for the specified
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001008/// FileEntry.
Steve Naroff3fa455a2009-04-24 20:03:17 +00001009HeaderFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) {
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001010 if (FE->getUID() >= FileInfo.size())
Richard Smith386bb072015-08-18 23:42:23 +00001011 FileInfo.resize(FE->getUID() + 1);
1012
Richard Smithd8879c82015-08-24 21:59:32 +00001013 HeaderFileInfo *HFI = &FileInfo[FE->getUID()];
Richard Smith386bb072015-08-18 23:42:23 +00001014 // FIXME: Use a generation count to check whether this is really up to date.
Richard Smithd8879c82015-08-24 21:59:32 +00001015 if (ExternalSource && !HFI->Resolved) {
1016 HFI->Resolved = true;
1017 auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE);
1018
1019 HFI = &FileInfo[FE->getUID()];
1020 if (ExternalHFI.External)
1021 mergeHeaderFileInfo(*HFI, ExternalHFI);
Richard Smith386bb072015-08-18 23:42:23 +00001022 }
1023
Richard Smithd8879c82015-08-24 21:59:32 +00001024 HFI->IsValid = true;
Richard Smith386bb072015-08-18 23:42:23 +00001025 // We have local information about this header file, so it's no longer
1026 // strictly external.
Richard Smithd8879c82015-08-24 21:59:32 +00001027 HFI->External = false;
1028 return *HFI;
Mike Stump11289f42009-09-09 15:08:12 +00001029}
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001030
Richard Smith386bb072015-08-18 23:42:23 +00001031const HeaderFileInfo *
Richard Smithd8879c82015-08-24 21:59:32 +00001032HeaderSearch::getExistingFileInfo(const FileEntry *FE,
1033 bool WantExternal) const {
Richard Smith386bb072015-08-18 23:42:23 +00001034 // If we have an external source, ensure we have the latest information.
1035 // FIXME: Use a generation count to check whether this is really up to date.
Richard Smithd8879c82015-08-24 21:59:32 +00001036 HeaderFileInfo *HFI;
1037 if (ExternalSource) {
1038 if (FE->getUID() >= FileInfo.size()) {
1039 if (!WantExternal)
1040 return nullptr;
1041 FileInfo.resize(FE->getUID() + 1);
Richard Smith386bb072015-08-18 23:42:23 +00001042 }
Richard Smithd8879c82015-08-24 21:59:32 +00001043
1044 HFI = &FileInfo[FE->getUID()];
1045 if (!WantExternal && (!HFI->IsValid || HFI->External))
1046 return nullptr;
1047 if (!HFI->Resolved) {
1048 HFI->Resolved = true;
1049 auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE);
1050
1051 HFI = &FileInfo[FE->getUID()];
1052 if (ExternalHFI.External)
1053 mergeHeaderFileInfo(*HFI, ExternalHFI);
1054 }
1055 } else if (FE->getUID() >= FileInfo.size()) {
1056 return nullptr;
1057 } else {
1058 HFI = &FileInfo[FE->getUID()];
Ben Langmuird285c502014-03-13 16:46:36 +00001059 }
Richard Smith386bb072015-08-18 23:42:23 +00001060
Richard Smithd8879c82015-08-24 21:59:32 +00001061 if (!HFI->IsValid || (HFI->External && !WantExternal))
Richard Smith386bb072015-08-18 23:42:23 +00001062 return nullptr;
1063
Richard Smithd8879c82015-08-24 21:59:32 +00001064 return HFI;
Ben Langmuird285c502014-03-13 16:46:36 +00001065}
1066
Douglas Gregor37aa4932011-05-04 00:14:37 +00001067bool HeaderSearch::isFileMultipleIncludeGuarded(const FileEntry *File) {
1068 // Check if we've ever seen this file as a header.
Richard Smith386bb072015-08-18 23:42:23 +00001069 if (auto *HFI = getExistingFileInfo(File))
1070 return HFI->isPragmaOnce || HFI->isImport || HFI->ControllingMacro ||
1071 HFI->ControllingMacroID;
1072 return false;
Douglas Gregor37aa4932011-05-04 00:14:37 +00001073}
1074
Argyrios Kyrtzidis6f722b42013-05-08 23:46:46 +00001075void HeaderSearch::MarkFileModuleHeader(const FileEntry *FE,
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001076 ModuleMap::ModuleHeaderRole Role,
Argyrios Kyrtzidis6f722b42013-05-08 23:46:46 +00001077 bool isCompilingModuleHeader) {
Richard Smithd8879c82015-08-24 21:59:32 +00001078 bool isModularHeader = !(Role & ModuleMap::TextualHeader);
1079
1080 // Don't mark the file info as non-external if there's nothing to change.
1081 if (!isCompilingModuleHeader) {
1082 if (!isModularHeader)
1083 return;
1084 auto *HFI = getExistingFileInfo(FE);
1085 if (HFI && HFI->isModuleHeader)
1086 return;
1087 }
1088
Richard Smith386bb072015-08-18 23:42:23 +00001089 auto &HFI = getFileInfo(FE);
Richard Smithd8879c82015-08-24 21:59:32 +00001090 HFI.isModuleHeader |= isModularHeader;
Richard Smithe70dadd2015-07-10 22:27:17 +00001091 HFI.isCompilingModuleHeader |= isCompilingModuleHeader;
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001092}
1093
Richard Smith20e883e2015-04-29 23:20:19 +00001094bool HeaderSearch::ShouldEnterIncludeFile(Preprocessor &PP,
1095 const FileEntry *File,
Richard Smith035f6dc2015-07-01 01:51:38 +00001096 bool isImport, Module *M) {
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001097 ++NumIncluded; // Count # of attempted #includes.
1098
1099 // Get information about this file.
Steve Naroff3fa455a2009-04-24 20:03:17 +00001100 HeaderFileInfo &FileInfo = getFileInfo(File);
Mike Stump11289f42009-09-09 15:08:12 +00001101
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001102 // If this is a #import directive, check that we have not already imported
1103 // this header.
1104 if (isImport) {
1105 // If this has already been imported, don't import it again.
1106 FileInfo.isImport = true;
Mike Stump11289f42009-09-09 15:08:12 +00001107
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001108 // Has this already been #import'ed or #include'd?
1109 if (FileInfo.NumIncludes) return false;
1110 } else {
1111 // Otherwise, if this is a #include of a file that was previously #import'd
1112 // or if this is the second #include of a #pragma once file, ignore it.
1113 if (FileInfo.isImport)
1114 return false;
1115 }
Mike Stump11289f42009-09-09 15:08:12 +00001116
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001117 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
1118 // if the macro that guards it is defined, we know the #include has no effect.
Mike Stump11289f42009-09-09 15:08:12 +00001119 if (const IdentifierInfo *ControllingMacro
Richard Smithe70dadd2015-07-10 22:27:17 +00001120 = FileInfo.getControllingMacro(ExternalLookup)) {
1121 // If the header corresponds to a module, check whether the macro is already
1122 // defined in that module rather than checking in the current set of visible
1123 // modules.
1124 if (M ? PP.isMacroDefinedInLocalModule(ControllingMacro, M)
1125 : PP.isMacroDefined(ControllingMacro)) {
Douglas Gregor99734e72009-04-25 23:30:02 +00001126 ++NumMultiIncludeFileOptzn;
1127 return false;
1128 }
Richard Smithe70dadd2015-07-10 22:27:17 +00001129 }
Mike Stump11289f42009-09-09 15:08:12 +00001130
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001131 // Increment the number of times this file has been included.
1132 ++FileInfo.NumIncludes;
Mike Stump11289f42009-09-09 15:08:12 +00001133
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001134 return true;
1135}
1136
Ted Kremenekfbcce6f2011-07-26 23:46:11 +00001137size_t HeaderSearch::getTotalMemory() const {
1138 return SearchDirs.capacity()
Ted Kremenekae63d102011-07-27 18:41:18 +00001139 + llvm::capacity_in_bytes(FileInfo)
1140 + llvm::capacity_in_bytes(HeaderMaps)
Ted Kremenekfbcce6f2011-07-26 23:46:11 +00001141 + LookupFileCache.getAllocator().getTotalMemory()
1142 + FrameworkMap.getAllocator().getTotalMemory();
1143}
Douglas Gregor9f93e382011-07-28 04:45:53 +00001144
1145StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) {
David Blaikie13156b62014-11-19 03:06:06 +00001146 return FrameworkNames.insert(Framework).first->first();
Douglas Gregor9f93e382011-07-28 04:45:53 +00001147}
Douglas Gregor718292f2011-11-11 19:10:28 +00001148
1149bool HeaderSearch::hasModuleMap(StringRef FileName,
Douglas Gregor963c5532013-06-21 16:28:10 +00001150 const DirectoryEntry *Root,
1151 bool IsSystem) {
Richard Smith47972af2015-06-16 00:08:24 +00001152 if (!HSOpts->ImplicitModuleMaps)
Argyrios Kyrtzidis9955dbc2013-12-12 16:08:33 +00001153 return false;
1154
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001155 SmallVector<const DirectoryEntry *, 2> FixUpDirectories;
Douglas Gregor718292f2011-11-11 19:10:28 +00001156
1157 StringRef DirName = FileName;
1158 do {
1159 // Get the parent directory name.
1160 DirName = llvm::sys::path::parent_path(DirName);
1161 if (DirName.empty())
1162 return false;
Daniel Jasperca9f7382013-09-24 09:27:13 +00001163
Douglas Gregor718292f2011-11-11 19:10:28 +00001164 // Determine whether this directory exists.
1165 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
1166 if (!Dir)
1167 return false;
Daniel Jasperca9f7382013-09-24 09:27:13 +00001168
Ben Langmuir984e1df2014-03-19 20:23:34 +00001169 // Try to load the module map file in this directory.
Richard Smith3c1a41a2014-12-02 00:08:08 +00001170 switch (loadModuleMapFile(Dir, IsSystem,
1171 llvm::sys::path::extension(Dir->getName()) ==
1172 ".framework")) {
Douglas Gregor80b69042011-11-12 00:22:19 +00001173 case LMM_NewlyLoaded:
1174 case LMM_AlreadyLoaded:
Daniel Jasperca9f7382013-09-24 09:27:13 +00001175 // Success. All of the directories we stepped through inherit this module
1176 // map file.
1177 for (unsigned I = 0, N = FixUpDirectories.size(); I != N; ++I)
1178 DirectoryHasModuleMap[FixUpDirectories[I]] = true;
1179 return true;
Daniel Jasper97da9172013-10-22 08:09:47 +00001180
1181 case LMM_NoDirectory:
1182 case LMM_InvalidModuleMap:
1183 break;
Daniel Jasperca9f7382013-09-24 09:27:13 +00001184 }
1185
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001186 // If we hit the top of our search, we're done.
1187 if (Dir == Root)
1188 return false;
1189
Douglas Gregor718292f2011-11-11 19:10:28 +00001190 // Keep track of all of the directories we checked, so we can mark them as
1191 // having module maps if we eventually do find a module map.
1192 FixUpDirectories.push_back(Dir);
1193 } while (true);
Douglas Gregor718292f2011-11-11 19:10:28 +00001194}
1195
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001196ModuleMap::KnownHeader
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +00001197HeaderSearch::findModuleForHeader(const FileEntry *File,
1198 bool AllowTextual) const {
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001199 if (ExternalSource) {
1200 // Make sure the external source has handled header info about this file,
1201 // which includes whether the file is part of a module.
Richard Smith386bb072015-08-18 23:42:23 +00001202 (void)getExistingFileInfo(File);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001203 }
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +00001204 return ModMap.findModuleForHeader(File, AllowTextual);
1205}
1206
1207static bool suggestModule(HeaderSearch &HS, const FileEntry *File,
1208 Module *RequestingModule,
1209 ModuleMap::KnownHeader *SuggestedModule) {
1210 ModuleMap::KnownHeader Module =
1211 HS.findModuleForHeader(File, /*AllowTextual*/true);
1212 if (SuggestedModule)
1213 *SuggestedModule = (Module.getRole() & ModuleMap::TextualHeader)
1214 ? ModuleMap::KnownHeader()
1215 : Module;
1216
1217 // If this module specifies [no_undeclared_includes], we cannot find any
1218 // file that's in a non-dependency module.
1219 if (RequestingModule && Module && RequestingModule->NoUndeclaredIncludes) {
1220 HS.getModuleMap().resolveUses(RequestingModule, /*Complain*/false);
1221 if (!RequestingModule->directlyUses(Module.getModule())) {
1222 return false;
1223 }
1224 }
1225
1226 return true;
Douglas Gregor718292f2011-11-11 19:10:28 +00001227}
1228
Richard Smith3d5b48c2015-10-16 21:42:56 +00001229bool HeaderSearch::findUsableModuleForHeader(
1230 const FileEntry *File, const DirectoryEntry *Root, Module *RequestingModule,
1231 ModuleMap::KnownHeader *SuggestedModule, bool IsSystemHeaderDir) {
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +00001232 if (File && needModuleLookup(RequestingModule, SuggestedModule)) {
Richard Smith3d5b48c2015-10-16 21:42:56 +00001233 // If there is a module that corresponds to this header, suggest it.
1234 hasModuleMap(File->getName(), Root, IsSystemHeaderDir);
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +00001235 return suggestModule(*this, File, RequestingModule, SuggestedModule);
Richard Smith3d5b48c2015-10-16 21:42:56 +00001236 }
1237 return true;
1238}
1239
1240bool HeaderSearch::findUsableModuleForFrameworkHeader(
1241 const FileEntry *File, StringRef FrameworkName, Module *RequestingModule,
1242 ModuleMap::KnownHeader *SuggestedModule, bool IsSystemFramework) {
1243 // If we're supposed to suggest a module, look for one now.
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +00001244 if (needModuleLookup(RequestingModule, SuggestedModule)) {
Richard Smith3d5b48c2015-10-16 21:42:56 +00001245 // Find the top-level framework based on this framework.
1246 SmallVector<std::string, 4> SubmodulePath;
1247 const DirectoryEntry *TopFrameworkDir
1248 = ::getTopFrameworkDir(FileMgr, FrameworkName, SubmodulePath);
1249
1250 // Determine the name of the top-level framework.
1251 StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
1252
1253 // Load this framework module. If that succeeds, find the suggested module
1254 // for this header, if any.
1255 loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystemFramework);
1256
1257 // FIXME: This can find a module not part of ModuleName, which is
1258 // important so that we're consistent about whether this header
1259 // corresponds to a module. Possibly we should lock down framework modules
1260 // so that this is not possible.
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +00001261 return suggestModule(*this, File, RequestingModule, SuggestedModule);
Richard Smith3d5b48c2015-10-16 21:42:56 +00001262 }
1263 return true;
1264}
1265
Richard Smith9acb99e32014-12-10 03:09:48 +00001266static const FileEntry *getPrivateModuleMap(const FileEntry *File,
Ben Langmuir984e1df2014-03-19 20:23:34 +00001267 FileManager &FileMgr) {
Richard Smith9acb99e32014-12-10 03:09:48 +00001268 StringRef Filename = llvm::sys::path::filename(File->getName());
1269 SmallString<128> PrivateFilename(File->getDir()->getName());
Ben Langmuir984e1df2014-03-19 20:23:34 +00001270 if (Filename == "module.map")
Douglas Gregor80306772011-12-07 21:25:07 +00001271 llvm::sys::path::append(PrivateFilename, "module_private.map");
Ben Langmuir984e1df2014-03-19 20:23:34 +00001272 else if (Filename == "module.modulemap")
1273 llvm::sys::path::append(PrivateFilename, "module.private.modulemap");
1274 else
1275 return nullptr;
1276 return FileMgr.getFile(PrivateFilename);
Douglas Gregor2b20cb82011-11-16 00:09:06 +00001277}
1278
Ben Langmuir984e1df2014-03-19 20:23:34 +00001279bool HeaderSearch::loadModuleMapFile(const FileEntry *File, bool IsSystem) {
Richard Smith9acb99e32014-12-10 03:09:48 +00001280 // Find the directory for the module. For frameworks, that may require going
1281 // up from the 'Modules' directory.
1282 const DirectoryEntry *Dir = nullptr;
1283 if (getHeaderSearchOpts().ModuleMapFileHomeIsCwd)
1284 Dir = FileMgr.getDirectory(".");
1285 else {
1286 Dir = File->getDir();
1287 StringRef DirName(Dir->getName());
1288 if (llvm::sys::path::filename(DirName) == "Modules") {
1289 DirName = llvm::sys::path::parent_path(DirName);
1290 if (DirName.endswith(".framework"))
1291 Dir = FileMgr.getDirectory(DirName);
1292 // FIXME: This assert can fail if there's a race between the above check
1293 // and the removal of the directory.
1294 assert(Dir && "parent must exist");
1295 }
1296 }
1297
1298 switch (loadModuleMapFileImpl(File, IsSystem, Dir)) {
Ben Langmuir984e1df2014-03-19 20:23:34 +00001299 case LMM_AlreadyLoaded:
1300 case LMM_NewlyLoaded:
1301 return false;
1302 case LMM_NoDirectory:
1303 case LMM_InvalidModuleMap:
1304 return true;
1305 }
Aaron Ballmand8de5b62014-03-20 14:22:33 +00001306 llvm_unreachable("Unknown load module map result");
Ben Langmuir984e1df2014-03-19 20:23:34 +00001307}
1308
1309HeaderSearch::LoadModuleMapResult
Richard Smith9acb99e32014-12-10 03:09:48 +00001310HeaderSearch::loadModuleMapFileImpl(const FileEntry *File, bool IsSystem,
1311 const DirectoryEntry *Dir) {
Ben Langmuir984e1df2014-03-19 20:23:34 +00001312 assert(File && "expected FileEntry");
1313
Richard Smith9887d792014-10-17 01:42:53 +00001314 // Check whether we've already loaded this module map, and mark it as being
1315 // loaded in case we recursively try to load it from itself.
1316 auto AddResult = LoadedModuleMaps.insert(std::make_pair(File, true));
1317 if (!AddResult.second)
1318 return AddResult.first->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001319
Richard Smith9acb99e32014-12-10 03:09:48 +00001320 if (ModMap.parseModuleMapFile(File, IsSystem, Dir)) {
Richard Smith9887d792014-10-17 01:42:53 +00001321 LoadedModuleMaps[File] = false;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001322 return LMM_InvalidModuleMap;
1323 }
1324
1325 // Try to load a corresponding private module map.
Richard Smith9acb99e32014-12-10 03:09:48 +00001326 if (const FileEntry *PMMFile = getPrivateModuleMap(File, FileMgr)) {
1327 if (ModMap.parseModuleMapFile(PMMFile, IsSystem, Dir)) {
Richard Smith9887d792014-10-17 01:42:53 +00001328 LoadedModuleMaps[File] = false;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001329 return LMM_InvalidModuleMap;
1330 }
1331 }
1332
1333 // This directory has a module map.
Ben Langmuir984e1df2014-03-19 20:23:34 +00001334 return LMM_NewlyLoaded;
1335}
1336
1337const FileEntry *
1338HeaderSearch::lookupModuleMapFile(const DirectoryEntry *Dir, bool IsFramework) {
Richard Smith47972af2015-06-16 00:08:24 +00001339 if (!HSOpts->ImplicitModuleMaps)
Daniel Jasper21a0f552014-11-25 09:45:48 +00001340 return nullptr;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001341 // For frameworks, the preferred spelling is Modules/module.modulemap, but
1342 // module.map at the framework root is also accepted.
1343 SmallString<128> ModuleMapFileName(Dir->getName());
1344 if (IsFramework)
1345 llvm::sys::path::append(ModuleMapFileName, "Modules");
1346 llvm::sys::path::append(ModuleMapFileName, "module.modulemap");
1347 if (const FileEntry *F = FileMgr.getFile(ModuleMapFileName))
1348 return F;
1349
1350 // Continue to allow module.map
1351 ModuleMapFileName = Dir->getName();
1352 llvm::sys::path::append(ModuleMapFileName, "module.map");
1353 return FileMgr.getFile(ModuleMapFileName);
1354}
1355
1356Module *HeaderSearch::loadFrameworkModule(StringRef Name,
Douglas Gregor279a6c32012-01-29 17:08:11 +00001357 const DirectoryEntry *Dir,
1358 bool IsSystem) {
Douglas Gregorde3ef502011-11-30 23:21:26 +00001359 if (Module *Module = ModMap.findModule(Name))
Douglas Gregor56c64012011-11-17 01:41:17 +00001360 return Module;
Daniel Jasper21a0f552014-11-25 09:45:48 +00001361
Douglas Gregor56c64012011-11-17 01:41:17 +00001362 // Try to load a module map file.
Ben Langmuir984e1df2014-03-19 20:23:34 +00001363 switch (loadModuleMapFile(Dir, IsSystem, /*IsFramework*/true)) {
Douglas Gregor56c64012011-11-17 01:41:17 +00001364 case LMM_InvalidModuleMap:
Ben Langmuira5254002015-07-02 13:19:48 +00001365 // Try to infer a module map from the framework directory.
1366 if (HSOpts->ImplicitModuleMaps)
1367 ModMap.inferFrameworkModule(Dir, IsSystem, /*Parent=*/nullptr);
Douglas Gregor56c64012011-11-17 01:41:17 +00001368 break;
Daniel Jasper21a0f552014-11-25 09:45:48 +00001369
Douglas Gregor56c64012011-11-17 01:41:17 +00001370 case LMM_AlreadyLoaded:
1371 case LMM_NoDirectory:
Craig Topperd2d442c2014-05-17 23:10:59 +00001372 return nullptr;
1373
Douglas Gregor56c64012011-11-17 01:41:17 +00001374 case LMM_NewlyLoaded:
Ben Langmuira5254002015-07-02 13:19:48 +00001375 break;
Douglas Gregor56c64012011-11-17 01:41:17 +00001376 }
Douglas Gregor3a5999b2012-01-13 22:31:52 +00001377
Ben Langmuira5254002015-07-02 13:19:48 +00001378 return ModMap.findModule(Name);
Douglas Gregor56c64012011-11-17 01:41:17 +00001379}
1380
Douglas Gregor2b20cb82011-11-16 00:09:06 +00001381
Douglas Gregor80b69042011-11-12 00:22:19 +00001382HeaderSearch::LoadModuleMapResult
Ben Langmuir984e1df2014-03-19 20:23:34 +00001383HeaderSearch::loadModuleMapFile(StringRef DirName, bool IsSystem,
1384 bool IsFramework) {
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001385 if (const DirectoryEntry *Dir = FileMgr.getDirectory(DirName))
Ben Langmuir984e1df2014-03-19 20:23:34 +00001386 return loadModuleMapFile(Dir, IsSystem, IsFramework);
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001387
Douglas Gregor80b69042011-11-12 00:22:19 +00001388 return LMM_NoDirectory;
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001389}
1390
Douglas Gregor80b69042011-11-12 00:22:19 +00001391HeaderSearch::LoadModuleMapResult
Ben Langmuir984e1df2014-03-19 20:23:34 +00001392HeaderSearch::loadModuleMapFile(const DirectoryEntry *Dir, bool IsSystem,
1393 bool IsFramework) {
1394 auto KnownDir = DirectoryHasModuleMap.find(Dir);
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001395 if (KnownDir != DirectoryHasModuleMap.end())
Richard Smith9887d792014-10-17 01:42:53 +00001396 return KnownDir->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
Douglas Gregore7ab3662011-12-07 02:23:45 +00001397
Ben Langmuir984e1df2014-03-19 20:23:34 +00001398 if (const FileEntry *ModuleMapFile = lookupModuleMapFile(Dir, IsFramework)) {
Richard Smith9acb99e32014-12-10 03:09:48 +00001399 LoadModuleMapResult Result =
1400 loadModuleMapFileImpl(ModuleMapFile, IsSystem, Dir);
Ben Langmuir984e1df2014-03-19 20:23:34 +00001401 // Add Dir explicitly in case ModuleMapFile is in a subdirectory.
1402 // E.g. Foo.framework/Modules/module.modulemap
1403 // ^Dir ^ModuleMapFile
1404 if (Result == LMM_NewlyLoaded)
1405 DirectoryHasModuleMap[Dir] = true;
Richard Smith9887d792014-10-17 01:42:53 +00001406 else if (Result == LMM_InvalidModuleMap)
1407 DirectoryHasModuleMap[Dir] = false;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001408 return Result;
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001409 }
Douglas Gregor80b69042011-11-12 00:22:19 +00001410 return LMM_InvalidModuleMap;
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001411}
Douglas Gregor718292f2011-11-11 19:10:28 +00001412
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001413void HeaderSearch::collectAllModules(SmallVectorImpl<Module *> &Modules) {
Douglas Gregor07f43572012-01-29 18:15:03 +00001414 Modules.clear();
Daniel Jasper21a0f552014-11-25 09:45:48 +00001415
Richard Smith47972af2015-06-16 00:08:24 +00001416 if (HSOpts->ImplicitModuleMaps) {
Daniel Jasper21a0f552014-11-25 09:45:48 +00001417 // Load module maps for each of the header search directories.
1418 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
1419 bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
1420 if (SearchDirs[Idx].isFramework()) {
1421 std::error_code EC;
1422 SmallString<128> DirNative;
1423 llvm::sys::path::native(SearchDirs[Idx].getFrameworkDir()->getName(),
1424 DirNative);
1425
1426 // Search each of the ".framework" directories to load them as modules.
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +00001427 vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
1428 for (vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
Daniel Jasper21a0f552014-11-25 09:45:48 +00001429 Dir != DirEnd && !EC; Dir.increment(EC)) {
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +00001430 if (llvm::sys::path::extension(Dir->getName()) != ".framework")
Daniel Jasper21a0f552014-11-25 09:45:48 +00001431 continue;
1432
1433 const DirectoryEntry *FrameworkDir =
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +00001434 FileMgr.getDirectory(Dir->getName());
Daniel Jasper21a0f552014-11-25 09:45:48 +00001435 if (!FrameworkDir)
1436 continue;
1437
1438 // Load this framework module.
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +00001439 loadFrameworkModule(llvm::sys::path::stem(Dir->getName()),
1440 FrameworkDir, IsSystem);
Daniel Jasper21a0f552014-11-25 09:45:48 +00001441 }
1442 continue;
Douglas Gregor07f43572012-01-29 18:15:03 +00001443 }
Daniel Jasper21a0f552014-11-25 09:45:48 +00001444
1445 // FIXME: Deal with header maps.
1446 if (SearchDirs[Idx].isHeaderMap())
1447 continue;
1448
1449 // Try to load a module map file for the search directory.
1450 loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem,
1451 /*IsFramework*/ false);
1452
1453 // Try to load module map files for immediate subdirectories of this
1454 // search directory.
1455 loadSubdirectoryModuleMaps(SearchDirs[Idx]);
Douglas Gregor07f43572012-01-29 18:15:03 +00001456 }
Douglas Gregor07f43572012-01-29 18:15:03 +00001457 }
Daniel Jasper21a0f552014-11-25 09:45:48 +00001458
Douglas Gregor07f43572012-01-29 18:15:03 +00001459 // Populate the list of modules.
1460 for (ModuleMap::module_iterator M = ModMap.module_begin(),
1461 MEnd = ModMap.module_end();
1462 M != MEnd; ++M) {
1463 Modules.push_back(M->getValue());
1464 }
1465}
Douglas Gregor0339a642013-03-21 01:08:50 +00001466
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001467void HeaderSearch::loadTopLevelSystemModules() {
Richard Smith47972af2015-06-16 00:08:24 +00001468 if (!HSOpts->ImplicitModuleMaps)
Daniel Jasper21a0f552014-11-25 09:45:48 +00001469 return;
1470
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001471 // Load module maps for each of the header search directories.
1472 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
Douglas Gregor299787f2013-11-01 23:08:38 +00001473 // We only care about normal header directories.
1474 if (!SearchDirs[Idx].isNormalDir()) {
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001475 continue;
1476 }
1477
1478 // Try to load a module map file for the search directory.
Douglas Gregor963c5532013-06-21 16:28:10 +00001479 loadModuleMapFile(SearchDirs[Idx].getDir(),
Ben Langmuir984e1df2014-03-19 20:23:34 +00001480 SearchDirs[Idx].isSystemHeaderDirectory(),
1481 SearchDirs[Idx].isFramework());
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001482 }
1483}
1484
Douglas Gregor0339a642013-03-21 01:08:50 +00001485void HeaderSearch::loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir) {
Richard Smith47972af2015-06-16 00:08:24 +00001486 assert(HSOpts->ImplicitModuleMaps &&
Daniel Jasper21a0f552014-11-25 09:45:48 +00001487 "Should not be loading subdirectory module maps");
1488
Douglas Gregor0339a642013-03-21 01:08:50 +00001489 if (SearchDir.haveSearchedAllModuleMaps())
1490 return;
Rafael Espindolac0809172014-06-12 14:02:15 +00001491
1492 std::error_code EC;
Douglas Gregor0339a642013-03-21 01:08:50 +00001493 SmallString<128> DirNative;
1494 llvm::sys::path::native(SearchDir.getDir()->getName(), DirNative);
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +00001495 vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
1496 for (vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
Douglas Gregor0339a642013-03-21 01:08:50 +00001497 Dir != DirEnd && !EC; Dir.increment(EC)) {
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +00001498 bool IsFramework =
1499 llvm::sys::path::extension(Dir->getName()) == ".framework";
Ben Langmuir1f6a32b2015-02-24 04:58:15 +00001500 if (IsFramework == SearchDir.isFramework())
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +00001501 loadModuleMapFile(Dir->getName(), SearchDir.isSystemHeaderDirectory(),
Ben Langmuir1f6a32b2015-02-24 04:58:15 +00001502 SearchDir.isFramework());
Douglas Gregor0339a642013-03-21 01:08:50 +00001503 }
1504
1505 SearchDir.setSearchedAllModuleMaps(true);
1506}
Richard Smith4eb83932016-04-27 21:57:05 +00001507
1508std::string HeaderSearch::suggestPathToFileForDiagnostics(const FileEntry *File,
1509 bool *IsSystem) {
1510 // FIXME: We assume that the path name currently cached in the FileEntry is
1511 // the most appropriate one for this analysis (and that it's spelled the same
1512 // way as the corresponding header search path).
Mehdi Amini004b9c72016-10-10 22:52:47 +00001513 StringRef Name = File->getName();
Richard Smith4eb83932016-04-27 21:57:05 +00001514
1515 unsigned BestPrefixLength = 0;
1516 unsigned BestSearchDir;
1517
1518 for (unsigned I = 0; I != SearchDirs.size(); ++I) {
1519 // FIXME: Support this search within frameworks and header maps.
1520 if (!SearchDirs[I].isNormalDir())
1521 continue;
1522
Mehdi Amini0df59d82016-10-11 07:31:29 +00001523 StringRef Dir = SearchDirs[I].getDir()->getName();
Richard Smith4eb83932016-04-27 21:57:05 +00001524 for (auto NI = llvm::sys::path::begin(Name),
1525 NE = llvm::sys::path::end(Name),
1526 DI = llvm::sys::path::begin(Dir),
1527 DE = llvm::sys::path::end(Dir);
1528 /*termination condition in loop*/; ++NI, ++DI) {
1529 // '.' components in Name are ignored.
1530 while (NI != NE && *NI == ".")
1531 ++NI;
1532 if (NI == NE)
1533 break;
1534
1535 // '.' components in Dir are ignored.
1536 while (DI != DE && *DI == ".")
1537 ++DI;
1538 if (DI == DE) {
1539 // Dir is a prefix of Name, up to '.' components and choice of path
1540 // separators.
1541 unsigned PrefixLength = NI - llvm::sys::path::begin(Name);
1542 if (PrefixLength > BestPrefixLength) {
1543 BestPrefixLength = PrefixLength;
1544 BestSearchDir = I;
1545 }
1546 break;
1547 }
1548
1549 if (*NI != *DI)
1550 break;
1551 }
1552 }
1553
1554 if (IsSystem)
1555 *IsSystem = BestPrefixLength ? BestSearchDir >= SystemDirIdx : false;
Mehdi Amini004b9c72016-10-10 22:52:47 +00001556 return Name.drop_front(BestPrefixLength);
Richard Smith4eb83932016-04-27 21:57:05 +00001557}