blob: 0aef7ff5c4070f28c654763a79cd11af0b3c4ffe [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
Dmitri Gribenkof8579502013-01-12 19:30:44 +000057HeaderSearch::HeaderSearch(IntrusiveRefCntPtr<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
Douglas Gregor279a6c32012-01-29 17:08:11 +0000124std::string HeaderSearch::getModuleFileName(Module *Module) {
Ben Langmuir9d6448b2014-08-09 00:57:23 +0000125 const FileEntry *ModuleMap =
126 getModuleMap().getModuleMapFileForUniquing(Module);
Manman Ren11f2a472016-08-18 17:42:15 +0000127 return getModuleFileName(Module->Name, ModuleMap->getName(),
128 /*UsePrebuiltPath*/false);
Douglas Gregor279a6c32012-01-29 17:08:11 +0000129}
130
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000131std::string HeaderSearch::getModuleFileName(StringRef ModuleName,
Manman Ren11f2a472016-08-18 17:42:15 +0000132 StringRef ModuleMapPath,
133 bool UsePrebuiltPath) {
134 if (UsePrebuiltPath) {
135 if (HSOpts->PrebuiltModulePaths.empty())
136 return std::string();
137
138 // Go though each prebuilt module path and try to find the pcm file.
139 for (const std::string &Dir : HSOpts->PrebuiltModulePaths) {
140 SmallString<256> Result(Dir);
141 llvm::sys::fs::make_absolute(Result);
142
143 llvm::sys::path::append(Result, ModuleName + ".pcm");
144 if (getFileMgr().getFile(Result.str()))
145 return Result.str().str();
146 }
147 return std::string();
148 }
149
Richard Smithd520a252015-07-21 18:07:47 +0000150 // If we don't have a module cache path or aren't supposed to use one, we
151 // can't do anything.
Richard Smith3938f0c2015-08-15 00:34:15 +0000152 if (getModuleCachePath().empty())
Douglas Gregor279a6c32012-01-29 17:08:11 +0000153 return std::string();
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000154
Richard Smith3938f0c2015-08-15 00:34:15 +0000155 SmallString<256> Result(getModuleCachePath());
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000156 llvm::sys::fs::make_absolute(Result);
157
158 if (HSOpts->DisableModuleHash) {
159 llvm::sys::path::append(Result, ModuleName + ".pcm");
160 } else {
161 // Construct the name <ModuleName>-<hash of ModuleMapPath>.pcm which should
Richard Smith54cc3c22014-12-11 20:50:24 +0000162 // ideally be globally unique to this particular module. Name collisions
163 // in the hash are safe (because any translation unit can only import one
164 // module with each name), but result in a loss of caching.
165 //
166 // To avoid false-negatives, we form as canonical a path as we can, and map
167 // to lower-case in case we're on a case-insensitive file system.
168 auto *Dir =
169 FileMgr.getDirectory(llvm::sys::path::parent_path(ModuleMapPath));
170 if (!Dir)
171 return std::string();
172 auto DirName = FileMgr.getCanonicalName(Dir);
173 auto FileName = llvm::sys::path::filename(ModuleMapPath);
174
175 llvm::hash_code Hash =
Adrian Prantl793038d32016-01-12 21:01:56 +0000176 llvm::hash_combine(DirName.lower(), FileName.lower());
Richard Smith54cc3c22014-12-11 20:50:24 +0000177
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000178 SmallString<128> HashStr;
Richard Smith54cc3c22014-12-11 20:50:24 +0000179 llvm::APInt(64, size_t(Hash)).toStringUnsigned(HashStr, /*Radix*/36);
Yaron Keren92e1b622015-03-18 10:17:07 +0000180 llvm::sys::path::append(Result, ModuleName + "-" + HashStr + ".pcm");
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000181 }
Douglas Gregor279a6c32012-01-29 17:08:11 +0000182 return Result.str().str();
183}
184
185Module *HeaderSearch::lookupModule(StringRef ModuleName, bool AllowSearch) {
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000186 // Look in the module map to determine if there is a module by this name.
Douglas Gregor279a6c32012-01-29 17:08:11 +0000187 Module *Module = ModMap.findModule(ModuleName);
Richard Smith47972af2015-06-16 00:08:24 +0000188 if (Module || !AllowSearch || !HSOpts->ImplicitModuleMaps)
Douglas Gregor279a6c32012-01-29 17:08:11 +0000189 return Module;
190
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000191 // Look through the various header search paths to load any available module
Douglas Gregor279a6c32012-01-29 17:08:11 +0000192 // maps, searching for a module map that describes this module.
193 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
194 if (SearchDirs[Idx].isFramework()) {
195 // Search for or infer a module map for a framework.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000196 SmallString<128> FrameworkDirName;
Douglas Gregor279a6c32012-01-29 17:08:11 +0000197 FrameworkDirName += SearchDirs[Idx].getFrameworkDir()->getName();
198 llvm::sys::path::append(FrameworkDirName, ModuleName + ".framework");
199 if (const DirectoryEntry *FrameworkDir
200 = FileMgr.getDirectory(FrameworkDirName)) {
201 bool IsSystem
202 = SearchDirs[Idx].getDirCharacteristic() != SrcMgr::C_User;
203 Module = loadFrameworkModule(ModuleName, FrameworkDir, IsSystem);
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000204 if (Module)
205 break;
206 }
Douglas Gregor279a6c32012-01-29 17:08:11 +0000207 }
208
209 // FIXME: Figure out how header maps and module maps will work together.
210
211 // Only deal with normal search directories.
212 if (!SearchDirs[Idx].isNormalDir())
213 continue;
Douglas Gregor963c5532013-06-21 16:28:10 +0000214
215 bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
Douglas Gregor279a6c32012-01-29 17:08:11 +0000216 // Search for a module map file in this directory.
Ben Langmuir984e1df2014-03-19 20:23:34 +0000217 if (loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem,
218 /*IsFramework*/false) == LMM_NewlyLoaded) {
Douglas Gregor279a6c32012-01-29 17:08:11 +0000219 // We just loaded a module map file; check whether the module is
220 // available now.
221 Module = ModMap.findModule(ModuleName);
222 if (Module)
223 break;
224 }
225
226 // Search for a module map in a subdirectory with the same name as the
227 // module.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000228 SmallString<128> NestedModuleMapDirName;
Douglas Gregor279a6c32012-01-29 17:08:11 +0000229 NestedModuleMapDirName = SearchDirs[Idx].getDir()->getName();
230 llvm::sys::path::append(NestedModuleMapDirName, ModuleName);
Ben Langmuir984e1df2014-03-19 20:23:34 +0000231 if (loadModuleMapFile(NestedModuleMapDirName, IsSystem,
232 /*IsFramework*/false) == LMM_NewlyLoaded){
Douglas Gregor279a6c32012-01-29 17:08:11 +0000233 // If we just loaded a module map file, look for the module again.
234 Module = ModMap.findModule(ModuleName);
235 if (Module)
236 break;
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000237 }
Douglas Gregor0339a642013-03-21 01:08:50 +0000238
239 // If we've already performed the exhaustive search for module maps in this
240 // search directory, don't do it again.
241 if (SearchDirs[Idx].haveSearchedAllModuleMaps())
242 continue;
243
244 // Load all module maps in the immediate subdirectories of this search
245 // directory.
246 loadSubdirectoryModuleMaps(SearchDirs[Idx]);
247
248 // Look again for the module.
249 Module = ModMap.findModule(ModuleName);
250 if (Module)
251 break;
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000252 }
Douglas Gregor0339a642013-03-21 01:08:50 +0000253
Douglas Gregor279a6c32012-01-29 17:08:11 +0000254 return Module;
Douglas Gregor1e44e022011-09-12 20:41:59 +0000255}
256
Chris Lattnerf62f7582007-12-17 07:52:39 +0000257//===----------------------------------------------------------------------===//
258// File lookup within a DirectoryLookup scope
259//===----------------------------------------------------------------------===//
260
Chris Lattner8d720d02007-12-17 17:57:27 +0000261/// getName - Return the directory or filename corresponding to this lookup
262/// object.
Mehdi Amini99d1b292016-10-01 16:38:28 +0000263StringRef DirectoryLookup::getName() const {
Chris Lattner8d720d02007-12-17 17:57:27 +0000264 if (isNormalDir())
265 return getDir()->getName();
266 if (isFramework())
267 return getFrameworkDir()->getName();
268 assert(isHeaderMap() && "Unknown DirectoryLookup");
269 return getHeaderMap()->getFileName();
270}
271
Richard Smith3d5b48c2015-10-16 21:42:56 +0000272const FileEntry *HeaderSearch::getFileAndSuggestModule(
Taewook Ohf42103c2016-06-13 20:40:21 +0000273 StringRef FileName, SourceLocation IncludeLoc, const DirectoryEntry *Dir,
274 bool IsSystemHeaderDir, Module *RequestingModule,
275 ModuleMap::KnownHeader *SuggestedModule) {
Richard Smith8c71eba2014-03-05 20:51:45 +0000276 // If we have a module map that might map this header, load it and
277 // check whether we'll have a suggestion for a module.
Richard Smith3d5b48c2015-10-16 21:42:56 +0000278 const FileEntry *File = getFileMgr().getFile(FileName, /*OpenFile=*/true);
Reid Klecknerafb9aae2015-10-20 18:45:57 +0000279 if (!File)
280 return nullptr;
Richard Smith8c71eba2014-03-05 20:51:45 +0000281
Richard Smith3d5b48c2015-10-16 21:42:56 +0000282 // If there is a module that corresponds to this header, suggest it.
283 if (!findUsableModuleForHeader(File, Dir ? Dir : File->getDir(),
284 RequestingModule, SuggestedModule,
285 IsSystemHeaderDir))
286 return nullptr;
Richard Smith8c71eba2014-03-05 20:51:45 +0000287
Richard Smith3d5b48c2015-10-16 21:42:56 +0000288 return File;
Richard Smith8c71eba2014-03-05 20:51:45 +0000289}
Chris Lattner8d720d02007-12-17 17:57:27 +0000290
Chris Lattnerf62f7582007-12-17 07:52:39 +0000291/// LookupFile - Lookup the specified file in this search path, returning it
292/// if it exists or returning null if not.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000293const FileEntry *DirectoryLookup::LookupFile(
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000294 StringRef &Filename,
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000295 HeaderSearch &HS,
Taewook Ohf42103c2016-06-13 20:40:21 +0000296 SourceLocation IncludeLoc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000297 SmallVectorImpl<char> *SearchPath,
Douglas Gregor97eec242011-09-15 22:00:41 +0000298 SmallVectorImpl<char> *RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000299 Module *RequestingModule,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000300 ModuleMap::KnownHeader *SuggestedModule,
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000301 bool &InUserSpecifiedSystemFramework,
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000302 bool &HasBeenMapped,
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000303 SmallVectorImpl<char> &MappedName) const {
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000304 InUserSpecifiedSystemFramework = false;
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000305 HasBeenMapped = false;
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000306
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000307 SmallString<1024> TmpDir;
Chris Lattner712e3872007-12-17 08:13:48 +0000308 if (isNormalDir()) {
309 // Concatenate the requested file onto the directory.
Eli Friedmanf7ca26a2011-07-08 20:17:28 +0000310 TmpDir = getDir()->getName();
311 llvm::sys::path::append(TmpDir, Filename);
Craig Topperd2d442c2014-05-17 23:10:59 +0000312 if (SearchPath) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000313 StringRef SearchPathRef(getDir()->getName());
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000314 SearchPath->clear();
315 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
316 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000317 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000318 RelativePath->clear();
319 RelativePath->append(Filename.begin(), Filename.end());
320 }
Richard Smith8c71eba2014-03-05 20:51:45 +0000321
Taewook Ohf42103c2016-06-13 20:40:21 +0000322 return HS.getFileAndSuggestModule(TmpDir, IncludeLoc, getDir(),
Richard Smith3d5b48c2015-10-16 21:42:56 +0000323 isSystemHeaderDirectory(),
324 RequestingModule, SuggestedModule);
Chris Lattner712e3872007-12-17 08:13:48 +0000325 }
Mike Stump11289f42009-09-09 15:08:12 +0000326
Chris Lattner712e3872007-12-17 08:13:48 +0000327 if (isFramework())
Douglas Gregor97eec242011-09-15 22:00:41 +0000328 return DoFrameworkLookup(Filename, HS, SearchPath, RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000329 RequestingModule, SuggestedModule,
330 InUserSpecifiedSystemFramework);
Mike Stump11289f42009-09-09 15:08:12 +0000331
Chris Lattner44bd21b2007-12-17 08:17:39 +0000332 assert(isHeaderMap() && "Unknown directory lookup");
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000333 const HeaderMap *HM = getHeaderMap();
334 SmallString<1024> Path;
335 StringRef Dest = HM->lookupFilename(Filename, Path);
336 if (Dest.empty())
Craig Topperd2d442c2014-05-17 23:10:59 +0000337 return nullptr;
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000338
339 const FileEntry *Result;
340
341 // Check if the headermap maps the filename to a framework include
342 // ("Foo.h" -> "Foo/Foo.h"), in which case continue header lookup using the
343 // framework include.
344 if (llvm::sys::path::is_relative(Dest)) {
345 MappedName.clear();
346 MappedName.append(Dest.begin(), Dest.end());
347 Filename = StringRef(MappedName.begin(), MappedName.size());
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000348 HasBeenMapped = true;
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000349 Result = HM->LookupFile(Filename, HS.getFileMgr());
350
351 } else {
352 Result = HS.getFileMgr().getFile(Dest);
353 }
354
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000355 if (Result) {
Craig Topperd2d442c2014-05-17 23:10:59 +0000356 if (SearchPath) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000357 StringRef SearchPathRef(getName());
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000358 SearchPath->clear();
359 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
360 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000361 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000362 RelativePath->clear();
363 RelativePath->append(Filename.begin(), Filename.end());
364 }
365 }
366 return Result;
Chris Lattnerf62f7582007-12-17 07:52:39 +0000367}
368
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000369/// \brief Given a framework directory, find the top-most framework directory.
370///
371/// \param FileMgr The file manager to use for directory lookups.
372/// \param DirName The name of the framework directory.
373/// \param SubmodulePath Will be populated with the submodule path from the
374/// returned top-level module to the originally named framework.
375static const DirectoryEntry *
376getTopFrameworkDir(FileManager &FileMgr, StringRef DirName,
377 SmallVectorImpl<std::string> &SubmodulePath) {
378 assert(llvm::sys::path::extension(DirName) == ".framework" &&
379 "Not a framework directory");
380
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000381 // Note: as an egregious but useful hack we use the real path here, because
382 // frameworks moving between top-level frameworks to embedded frameworks tend
383 // to be symlinked, and we base the logical structure of modules on the
384 // physical layout. In particular, we need to deal with crazy includes like
385 //
386 // #include <Foo/Frameworks/Bar.framework/Headers/Wibble.h>
387 //
388 // where 'Bar' used to be embedded in 'Foo', is now a top-level framework
389 // which one should access with, e.g.,
390 //
391 // #include <Bar/Wibble.h>
392 //
393 // Similar issues occur when a top-level framework has moved into an
394 // embedded framework.
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000395 const DirectoryEntry *TopFrameworkDir = FileMgr.getDirectory(DirName);
Douglas Gregore00c8b22013-01-26 00:55:12 +0000396 DirName = FileMgr.getCanonicalName(TopFrameworkDir);
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000397 do {
398 // Get the parent directory name.
399 DirName = llvm::sys::path::parent_path(DirName);
400 if (DirName.empty())
401 break;
402
403 // Determine whether this directory exists.
404 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
405 if (!Dir)
406 break;
407
408 // If this is a framework directory, then we're a subframework of this
409 // framework.
410 if (llvm::sys::path::extension(DirName) == ".framework") {
411 SubmodulePath.push_back(llvm::sys::path::stem(DirName));
412 TopFrameworkDir = Dir;
413 }
414 } while (true);
415
416 return TopFrameworkDir;
417}
Chris Lattnerf62f7582007-12-17 07:52:39 +0000418
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +0000419static bool needModuleLookup(Module *RequestingModule,
420 bool HasSuggestedModule) {
421 return HasSuggestedModule ||
422 (RequestingModule && RequestingModule->NoUndeclaredIncludes);
423}
424
Chris Lattner712e3872007-12-17 08:13:48 +0000425/// DoFrameworkLookup - Do a lookup of the specified file in the current
426/// DirectoryLookup, which is a framework directory.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000427const FileEntry *DirectoryLookup::DoFrameworkLookup(
Richard Smith3d5b48c2015-10-16 21:42:56 +0000428 StringRef Filename, HeaderSearch &HS, SmallVectorImpl<char> *SearchPath,
429 SmallVectorImpl<char> *RelativePath, Module *RequestingModule,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000430 ModuleMap::KnownHeader *SuggestedModule,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000431 bool &InUserSpecifiedSystemFramework) const {
Chris Lattner712e3872007-12-17 08:13:48 +0000432 FileManager &FileMgr = HS.getFileMgr();
Mike Stump11289f42009-09-09 15:08:12 +0000433
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000434 // Framework names must have a '/' in the filename.
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000435 size_t SlashPos = Filename.find('/');
Craig Topperd2d442c2014-05-17 23:10:59 +0000436 if (SlashPos == StringRef::npos) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000437
Chris Lattner712e3872007-12-17 08:13:48 +0000438 // Find out if this is the home for the specified framework, by checking
Daniel Dunbar17138612012-04-05 17:09:40 +0000439 // HeaderSearch. Possible answers are yes/no and unknown.
440 HeaderSearch::FrameworkCacheEntry &CacheEntry =
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000441 HS.LookupFrameworkCache(Filename.substr(0, SlashPos));
Mike Stump11289f42009-09-09 15:08:12 +0000442
Chris Lattner712e3872007-12-17 08:13:48 +0000443 // If it is known and in some other directory, fail.
Daniel Dunbar17138612012-04-05 17:09:40 +0000444 if (CacheEntry.Directory && CacheEntry.Directory != getFrameworkDir())
Craig Topperd2d442c2014-05-17 23:10:59 +0000445 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000446
Chris Lattner712e3872007-12-17 08:13:48 +0000447 // Otherwise, construct the path to this framework dir.
Mike Stump11289f42009-09-09 15:08:12 +0000448
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000449 // FrameworkName = "/System/Library/Frameworks/"
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000450 SmallString<1024> FrameworkName;
Chris Lattner712e3872007-12-17 08:13:48 +0000451 FrameworkName += getFrameworkDir()->getName();
Chris Lattnerb201d9b2006-10-30 05:09:49 +0000452 if (FrameworkName.empty() || FrameworkName.back() != '/')
453 FrameworkName.push_back('/');
Mike Stump11289f42009-09-09 15:08:12 +0000454
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000455 // FrameworkName = "/System/Library/Frameworks/Cocoa"
Douglas Gregor56c64012011-11-17 01:41:17 +0000456 StringRef ModuleName(Filename.begin(), SlashPos);
457 FrameworkName += ModuleName;
Mike Stump11289f42009-09-09 15:08:12 +0000458
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000459 // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/"
460 FrameworkName += ".framework/";
Mike Stump11289f42009-09-09 15:08:12 +0000461
Daniel Dunbar17138612012-04-05 17:09:40 +0000462 // If the cache entry was unresolved, populate it now.
Craig Topperd2d442c2014-05-17 23:10:59 +0000463 if (!CacheEntry.Directory) {
Chris Lattner712e3872007-12-17 08:13:48 +0000464 HS.IncrementFrameworkLookupCount();
Mike Stump11289f42009-09-09 15:08:12 +0000465
Chris Lattner5ed76da2006-10-22 07:24:13 +0000466 // If the framework dir doesn't exist, we fail.
Yaron Keren92e1b622015-03-18 10:17:07 +0000467 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName);
Craig Topperd2d442c2014-05-17 23:10:59 +0000468 if (!Dir) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000469
Chris Lattner5ed76da2006-10-22 07:24:13 +0000470 // Otherwise, if it does, remember that this is the right direntry for this
471 // framework.
Daniel Dunbar17138612012-04-05 17:09:40 +0000472 CacheEntry.Directory = getFrameworkDir();
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000473
474 // If this is a user search directory, check if the framework has been
475 // user-specified as a system framework.
476 if (getDirCharacteristic() == SrcMgr::C_User) {
477 SmallString<1024> SystemFrameworkMarker(FrameworkName);
478 SystemFrameworkMarker += ".system_framework";
Yaron Keren92e1b622015-03-18 10:17:07 +0000479 if (llvm::sys::fs::exists(SystemFrameworkMarker)) {
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000480 CacheEntry.IsUserSpecifiedSystemFramework = true;
481 }
482 }
Chris Lattner5ed76da2006-10-22 07:24:13 +0000483 }
Mike Stump11289f42009-09-09 15:08:12 +0000484
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000485 // Set the 'user-specified system framework' flag.
486 InUserSpecifiedSystemFramework = CacheEntry.IsUserSpecifiedSystemFramework;
487
Craig Topperd2d442c2014-05-17 23:10:59 +0000488 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000489 RelativePath->clear();
490 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
491 }
Douglas Gregor56c64012011-11-17 01:41:17 +0000492
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000493 // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"
Chris Lattnerb201d9b2006-10-30 05:09:49 +0000494 unsigned OrigSize = FrameworkName.size();
Mike Stump11289f42009-09-09 15:08:12 +0000495
Chris Lattnerb201d9b2006-10-30 05:09:49 +0000496 FrameworkName += "Headers/";
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000497
Craig Topperd2d442c2014-05-17 23:10:59 +0000498 if (SearchPath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000499 SearchPath->clear();
500 // Without trailing '/'.
501 SearchPath->append(FrameworkName.begin(), FrameworkName.end()-1);
502 }
503
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000504 FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end());
Yaron Keren92e1b622015-03-18 10:17:07 +0000505 const FileEntry *FE = FileMgr.getFile(FrameworkName,
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000506 /*openFile=*/!SuggestedModule);
507 if (!FE) {
508 // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"
509 const char *Private = "Private";
510 FrameworkName.insert(FrameworkName.begin()+OrigSize, Private,
511 Private+strlen(Private));
Craig Topperd2d442c2014-05-17 23:10:59 +0000512 if (SearchPath)
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000513 SearchPath->insert(SearchPath->begin()+OrigSize, Private,
514 Private+strlen(Private));
515
Yaron Keren92e1b622015-03-18 10:17:07 +0000516 FE = FileMgr.getFile(FrameworkName, /*openFile=*/!SuggestedModule);
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000517 }
Mike Stump11289f42009-09-09 15:08:12 +0000518
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000519 // If we found the header and are allowed to suggest a module, do so now.
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +0000520 if (FE && needModuleLookup(RequestingModule, SuggestedModule)) {
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000521 // Find the framework in which this header occurs.
Ben Langmuiref914b82014-05-15 16:20:33 +0000522 StringRef FrameworkPath = FE->getDir()->getName();
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000523 bool FoundFramework = false;
524 do {
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000525 // Determine whether this directory exists.
526 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkPath);
527 if (!Dir)
528 break;
529
530 // If this is a framework directory, then we're a subframework of this
531 // framework.
532 if (llvm::sys::path::extension(FrameworkPath) == ".framework") {
533 FoundFramework = true;
534 break;
535 }
Ben Langmuiref914b82014-05-15 16:20:33 +0000536
537 // Get the parent directory name.
538 FrameworkPath = llvm::sys::path::parent_path(FrameworkPath);
539 if (FrameworkPath.empty())
540 break;
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000541 } while (true);
542
Richard Smith3d5b48c2015-10-16 21:42:56 +0000543 bool IsSystem = getDirCharacteristic() != SrcMgr::C_User;
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000544 if (FoundFramework) {
Richard Smith3d5b48c2015-10-16 21:42:56 +0000545 if (!HS.findUsableModuleForFrameworkHeader(
546 FE, FrameworkPath, RequestingModule, SuggestedModule, IsSystem))
547 return nullptr;
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000548 } else {
Richard Smith3d5b48c2015-10-16 21:42:56 +0000549 if (!HS.findUsableModuleForHeader(FE, getDir(), RequestingModule,
550 SuggestedModule, IsSystem))
551 return nullptr;
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000552 }
553 }
Douglas Gregor97eec242011-09-15 22:00:41 +0000554 return FE;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000555}
556
Douglas Gregor89929282012-01-30 06:01:29 +0000557void HeaderSearch::setTarget(const TargetInfo &Target) {
558 ModMap.setTarget(Target);
559}
560
Chris Lattnerf62f7582007-12-17 07:52:39 +0000561
Chris Lattner712e3872007-12-17 08:13:48 +0000562//===----------------------------------------------------------------------===//
563// Header File Location.
564//===----------------------------------------------------------------------===//
565
Reid Klecknera97d4c02014-02-18 23:49:24 +0000566/// \brief Return true with a diagnostic if the file that MSVC would have found
567/// fails to match the one that Clang would have found with MSVC header search
568/// disabled.
569static bool checkMSVCHeaderSearch(DiagnosticsEngine &Diags,
570 const FileEntry *MSFE, const FileEntry *FE,
571 SourceLocation IncludeLoc) {
572 if (MSFE && FE != MSFE) {
573 Diags.Report(IncludeLoc, diag::ext_pp_include_search_ms) << MSFE->getName();
574 return true;
575 }
576 return false;
577}
Chris Lattner712e3872007-12-17 08:13:48 +0000578
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000579static const char *copyString(StringRef Str, llvm::BumpPtrAllocator &Alloc) {
580 assert(!Str.empty());
581 char *CopyStr = Alloc.Allocate<char>(Str.size()+1);
582 std::copy(Str.begin(), Str.end(), CopyStr);
583 CopyStr[Str.size()] = '\0';
584 return CopyStr;
585}
586
James Dennettc07ab2c2012-06-20 00:56:32 +0000587/// LookupFile - Given a "foo" or \<foo> reference, look up the indicated file,
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000588/// return null on failure. isAngled indicates whether the file reference is
Will Wilson0fafd342013-12-27 19:46:16 +0000589/// for system \#include's or not (i.e. using <> instead of ""). Includers, if
590/// non-empty, indicates where the \#including file(s) are, in case a relative
591/// search is needed. Microsoft mode will pass all \#including files.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000592const FileEntry *HeaderSearch::LookupFile(
Will Wilson0fafd342013-12-27 19:46:16 +0000593 StringRef Filename, SourceLocation IncludeLoc, bool isAngled,
594 const DirectoryLookup *FromDir, const DirectoryLookup *&CurDir,
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000595 ArrayRef<std::pair<const FileEntry *, const DirectoryEntry *>> Includers,
596 SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000597 Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule,
Manman Rene4a5d372016-05-17 02:15:12 +0000598 bool SkipCache, bool BuildSystemModule) {
Douglas Gregor97eec242011-09-15 22:00:41 +0000599 if (SuggestedModule)
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000600 *SuggestedModule = ModuleMap::KnownHeader();
Douglas Gregor97eec242011-09-15 22:00:41 +0000601
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000602 // If 'Filename' is absolute, check to see if it exists and no searching.
Michael J. Spencerf28df4c2010-12-17 21:22:22 +0000603 if (llvm::sys::path::is_absolute(Filename)) {
Craig Topperd2d442c2014-05-17 23:10:59 +0000604 CurDir = nullptr;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000605
606 // If this was an #include_next "/absolute/file", fail.
Craig Topperd2d442c2014-05-17 23:10:59 +0000607 if (FromDir) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000608
Craig Topperd2d442c2014-05-17 23:10:59 +0000609 if (SearchPath)
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000610 SearchPath->clear();
Craig Topperd2d442c2014-05-17 23:10:59 +0000611 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000612 RelativePath->clear();
613 RelativePath->append(Filename.begin(), Filename.end());
614 }
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000615 // Otherwise, just return the file.
Taewook Ohf42103c2016-06-13 20:40:21 +0000616 return getFileAndSuggestModule(Filename, IncludeLoc, nullptr,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000617 /*IsSystemHeaderDir*/false,
618 RequestingModule, SuggestedModule);
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000619 }
Mike Stump11289f42009-09-09 15:08:12 +0000620
Reid Klecknera97d4c02014-02-18 23:49:24 +0000621 // This is the header that MSVC's header search would have found.
Craig Topperd2d442c2014-05-17 23:10:59 +0000622 const FileEntry *MSFE = nullptr;
Richard Smith8c71eba2014-03-05 20:51:45 +0000623 ModuleMap::KnownHeader MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000624
Douglas Gregor9f93e382011-07-28 04:45:53 +0000625 // Unless disabled, check to see if the file is in the #includer's
Will Wilson0fafd342013-12-27 19:46:16 +0000626 // directory. This cannot be based on CurDir, because each includer could be
627 // a #include of a subdirectory (#include "foo/bar.h") and a subsequent
628 // include of "baz.h" should resolve to "whatever/foo/baz.h".
Chris Lattnerf62f7582007-12-17 07:52:39 +0000629 // This search is not done for <> headers.
Will Wilson0fafd342013-12-27 19:46:16 +0000630 if (!Includers.empty() && !isAngled && !NoCurDirSearch) {
NAKAMURA Takumi9cb62642013-12-10 02:36:28 +0000631 SmallString<1024> TmpDir;
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000632 bool First = true;
633 for (const auto &IncluderAndDir : Includers) {
634 const FileEntry *Includer = IncluderAndDir.first;
635
Will Wilson0fafd342013-12-27 19:46:16 +0000636 // Concatenate the requested file onto the directory.
Nikola Smiljaniccf385dc2015-05-08 06:02:37 +0000637 // FIXME: Portability. Filename concatenation should be in sys::Path.
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000638 TmpDir = IncluderAndDir.second->getName();
Nikola Smiljaniccf385dc2015-05-08 06:02:37 +0000639 TmpDir.push_back('/');
640 TmpDir.append(Filename.begin(), Filename.end());
Richard Smith8c71eba2014-03-05 20:51:45 +0000641
Richard Smith6f548ec2014-03-06 18:08:08 +0000642 // FIXME: We don't cache the result of getFileInfo across the call to
643 // getFileAndSuggestModule, because it's a reference to an element of
644 // a container that could be reallocated across this call.
Richard Smith3c1a41a2014-12-02 00:08:08 +0000645 //
Manman Rene4a5d372016-05-17 02:15:12 +0000646 // If we have no includer, that means we're processing a #include
Richard Smith3c1a41a2014-12-02 00:08:08 +0000647 // from a module build. We should treat this as a system header if we're
648 // building a [system] module.
Richard Smith6f548ec2014-03-06 18:08:08 +0000649 bool IncluderIsSystemHeader =
Manman Rene39c8142016-05-17 18:04:38 +0000650 Includer ? getFileInfo(Includer).DirInfo != SrcMgr::C_User :
651 BuildSystemModule;
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000652 if (const FileEntry *FE = getFileAndSuggestModule(
Taewook Ohf42103c2016-06-13 20:40:21 +0000653 TmpDir, IncludeLoc, IncluderAndDir.second, IncluderIsSystemHeader,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000654 RequestingModule, SuggestedModule)) {
Richard Smith3c1a41a2014-12-02 00:08:08 +0000655 if (!Includer) {
656 assert(First && "only first includer can have no file");
657 return FE;
658 }
659
Will Wilson0fafd342013-12-27 19:46:16 +0000660 // Leave CurDir unset.
661 // This file is a system header or C++ unfriendly if the old file is.
662 //
663 // Note that we only use one of FromHFI/ToHFI at once, due to potential
664 // reallocation of the underlying vector potentially making the first
665 // reference binding dangling.
Richard Smith6f548ec2014-03-06 18:08:08 +0000666 HeaderFileInfo &FromHFI = getFileInfo(Includer);
Will Wilson0fafd342013-12-27 19:46:16 +0000667 unsigned DirInfo = FromHFI.DirInfo;
668 bool IndexHeaderMapHeader = FromHFI.IndexHeaderMapHeader;
669 StringRef Framework = FromHFI.Framework;
Douglas Gregor03b5ebe2012-08-13 15:47:39 +0000670
Will Wilson0fafd342013-12-27 19:46:16 +0000671 HeaderFileInfo &ToHFI = getFileInfo(FE);
672 ToHFI.DirInfo = DirInfo;
673 ToHFI.IndexHeaderMapHeader = IndexHeaderMapHeader;
674 ToHFI.Framework = Framework;
Douglas Gregor03b5ebe2012-08-13 15:47:39 +0000675
Craig Topperd2d442c2014-05-17 23:10:59 +0000676 if (SearchPath) {
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000677 StringRef SearchPathRef(IncluderAndDir.second->getName());
Will Wilson0fafd342013-12-27 19:46:16 +0000678 SearchPath->clear();
679 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
680 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000681 if (RelativePath) {
Will Wilson0fafd342013-12-27 19:46:16 +0000682 RelativePath->clear();
683 RelativePath->append(Filename.begin(), Filename.end());
684 }
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000685 if (First)
Reid Klecknera97d4c02014-02-18 23:49:24 +0000686 return FE;
687
688 // Otherwise, we found the path via MSVC header search rules. If
689 // -Wmsvc-include is enabled, we have to keep searching to see if we
690 // would've found this header in -I or -isystem directories.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +0000691 if (Diags.isIgnored(diag::ext_pp_include_search_ms, IncludeLoc)) {
Reid Klecknera97d4c02014-02-18 23:49:24 +0000692 return FE;
693 } else {
694 MSFE = FE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000695 if (SuggestedModule) {
696 MSSuggestedModule = *SuggestedModule;
697 *SuggestedModule = ModuleMap::KnownHeader();
698 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000699 break;
700 }
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000701 }
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000702 First = false;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000703 }
704 }
Mike Stump11289f42009-09-09 15:08:12 +0000705
Craig Topperd2d442c2014-05-17 23:10:59 +0000706 CurDir = nullptr;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000707
708 // If this is a system #include, ignore the user #include locs.
Nico Weber3b1d1212011-05-24 04:31:14 +0000709 unsigned i = isAngled ? AngledDirIdx : 0;
Mike Stump11289f42009-09-09 15:08:12 +0000710
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000711 // If this is a #include_next request, start searching after the directory the
712 // file was found in.
713 if (FromDir)
714 i = FromDir-&SearchDirs[0];
Mike Stump11289f42009-09-09 15:08:12 +0000715
Chris Lattnerd4275422007-07-22 07:28:00 +0000716 // Cache all of the lookups performed by this method. Many headers are
717 // multiply included, and the "pragma once" optimization prevents them from
718 // being relex/pp'd, but they would still have to search through a
719 // (potentially huge) series of SearchDirs to find it.
David Blaikie13156b62014-11-19 03:06:06 +0000720 LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename];
Chris Lattnerd4275422007-07-22 07:28:00 +0000721
722 // If the entry has been previously looked up, the first value will be
723 // non-zero. If the value is equal to i (the start point of our search), then
724 // this is a matching hit.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000725 if (!SkipCache && CacheLookup.StartIdx == i+1) {
Chris Lattnerd4275422007-07-22 07:28:00 +0000726 // Skip querying potentially lots of directories for this lookup.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000727 i = CacheLookup.HitIdx;
728 if (CacheLookup.MappedName)
729 Filename = CacheLookup.MappedName;
Chris Lattnerd4275422007-07-22 07:28:00 +0000730 } else {
731 // Otherwise, this is the first query, or the previous query didn't match
732 // our search start. We will fill in our found location below, so prime the
733 // start point value.
Argyrios Kyrtzidis7bd78a92014-03-29 03:22:54 +0000734 CacheLookup.reset(/*StartIdx=*/i+1);
Chris Lattnerd4275422007-07-22 07:28:00 +0000735 }
Mike Stump11289f42009-09-09 15:08:12 +0000736
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000737 SmallString<64> MappedName;
738
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000739 // Check each directory in sequence to see if it contains this file.
740 for (; i != SearchDirs.size(); ++i) {
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000741 bool InUserSpecifiedSystemFramework = false;
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000742 bool HasBeenMapped = false;
Richard Smith3d5b48c2015-10-16 21:42:56 +0000743 const FileEntry *FE = SearchDirs[i].LookupFile(
Taewook Ohf42103c2016-06-13 20:40:21 +0000744 Filename, *this, IncludeLoc, SearchPath, RelativePath, RequestingModule,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000745 SuggestedModule, InUserSpecifiedSystemFramework, HasBeenMapped,
746 MappedName);
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000747 if (HasBeenMapped) {
748 CacheLookup.MappedName =
749 copyString(Filename, LookupFileCache.getAllocator());
750 }
Chris Lattner712e3872007-12-17 08:13:48 +0000751 if (!FE) continue;
Mike Stump11289f42009-09-09 15:08:12 +0000752
Chris Lattner712e3872007-12-17 08:13:48 +0000753 CurDir = &SearchDirs[i];
Mike Stump11289f42009-09-09 15:08:12 +0000754
Chris Lattner712e3872007-12-17 08:13:48 +0000755 // This file is a system header or C++ unfriendly if the dir is.
Douglas Gregor9f93e382011-07-28 04:45:53 +0000756 HeaderFileInfo &HFI = getFileInfo(FE);
757 HFI.DirInfo = CurDir->getDirCharacteristic();
Mike Stump11289f42009-09-09 15:08:12 +0000758
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000759 // If the directory characteristic is User but this framework was
760 // user-specified to be treated as a system framework, promote the
761 // characteristic.
762 if (HFI.DirInfo == SrcMgr::C_User && InUserSpecifiedSystemFramework)
763 HFI.DirInfo = SrcMgr::C_System;
764
Richard Smith8acadcb2012-06-13 20:27:03 +0000765 // If the filename matches a known system header prefix, override
766 // whether the file is a system header.
Richard Trieu871f5f32012-06-13 20:52:36 +0000767 for (unsigned j = SystemHeaderPrefixes.size(); j; --j) {
768 if (Filename.startswith(SystemHeaderPrefixes[j-1].first)) {
769 HFI.DirInfo = SystemHeaderPrefixes[j-1].second ? SrcMgr::C_System
Richard Smith8acadcb2012-06-13 20:27:03 +0000770 : SrcMgr::C_User;
771 break;
772 }
773 }
774
Douglas Gregor9f93e382011-07-28 04:45:53 +0000775 // If this file is found in a header map and uses the framework style of
776 // includes, then this header is part of a framework we're building.
777 if (CurDir->isIndexHeaderMap()) {
778 size_t SlashPos = Filename.find('/');
779 if (SlashPos != StringRef::npos) {
780 HFI.IndexHeaderMapHeader = 1;
781 HFI.Framework = getUniqueFrameworkName(StringRef(Filename.begin(),
782 SlashPos));
783 }
784 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000785
Richard Smith8c71eba2014-03-05 20:51:45 +0000786 if (checkMSVCHeaderSearch(Diags, MSFE, FE, IncludeLoc)) {
787 if (SuggestedModule)
788 *SuggestedModule = MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000789 return MSFE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000790 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000791
Chris Lattner712e3872007-12-17 08:13:48 +0000792 // Remember this location for the next lookup we do.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000793 CacheLookup.HitIdx = i;
Chris Lattner712e3872007-12-17 08:13:48 +0000794 return FE;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000795 }
Mike Stump11289f42009-09-09 15:08:12 +0000796
Douglas Gregord8575e12011-07-30 06:28:34 +0000797 // If we are including a file with a quoted include "foo.h" from inside
798 // a header in a framework that is currently being built, and we couldn't
799 // resolve "foo.h" any other way, change the include to <Foo/foo.h>, where
800 // "Foo" is the name of the framework in which the including header was found.
Richard Smith3c1a41a2014-12-02 00:08:08 +0000801 if (!Includers.empty() && Includers.front().first && !isAngled &&
Will Wilson0fafd342013-12-27 19:46:16 +0000802 Filename.find('/') == StringRef::npos) {
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000803 HeaderFileInfo &IncludingHFI = getFileInfo(Includers.front().first);
Douglas Gregord8575e12011-07-30 06:28:34 +0000804 if (IncludingHFI.IndexHeaderMapHeader) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000805 SmallString<128> ScratchFilename;
Douglas Gregord8575e12011-07-30 06:28:34 +0000806 ScratchFilename += IncludingHFI.Framework;
807 ScratchFilename += '/';
808 ScratchFilename += Filename;
Will Wilson0fafd342013-12-27 19:46:16 +0000809
Richard Smith3d5b48c2015-10-16 21:42:56 +0000810 const FileEntry *FE =
811 LookupFile(ScratchFilename, IncludeLoc, /*isAngled=*/true, FromDir,
812 CurDir, Includers.front(), SearchPath, RelativePath,
813 RequestingModule, SuggestedModule);
Reid Klecknera97d4c02014-02-18 23:49:24 +0000814
Richard Smith8c71eba2014-03-05 20:51:45 +0000815 if (checkMSVCHeaderSearch(Diags, MSFE, FE, IncludeLoc)) {
816 if (SuggestedModule)
817 *SuggestedModule = MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000818 return MSFE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000819 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000820
David Blaikie3c8c46e2014-11-19 05:48:40 +0000821 LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename];
David Blaikie13156b62014-11-19 03:06:06 +0000822 CacheLookup.HitIdx = LookupFileCache[ScratchFilename].HitIdx;
Richard Smith8c71eba2014-03-05 20:51:45 +0000823 // FIXME: SuggestedModule.
Reid Klecknera97d4c02014-02-18 23:49:24 +0000824 return FE;
Douglas Gregord8575e12011-07-30 06:28:34 +0000825 }
826 }
827
Craig Topperd2d442c2014-05-17 23:10:59 +0000828 if (checkMSVCHeaderSearch(Diags, MSFE, nullptr, IncludeLoc)) {
Richard Smith8c71eba2014-03-05 20:51:45 +0000829 if (SuggestedModule)
830 *SuggestedModule = MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000831 return MSFE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000832 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000833
Chris Lattnerd4275422007-07-22 07:28:00 +0000834 // Otherwise, didn't find it. Remember we didn't find this.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000835 CacheLookup.HitIdx = SearchDirs.size();
Craig Topperd2d442c2014-05-17 23:10:59 +0000836 return nullptr;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000837}
838
Chris Lattner63dd32b2006-10-20 04:42:40 +0000839/// LookupSubframeworkHeader - Look up a subframework for the specified
James Dennettc07ab2c2012-06-20 00:56:32 +0000840/// \#include file. For example, if \#include'ing <HIToolbox/HIToolbox.h> from
Chris Lattner63dd32b2006-10-20 04:42:40 +0000841/// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
842/// is a subframework within Carbon.framework. If so, return the FileEntry
843/// for the designated file, otherwise return null.
844const FileEntry *HeaderSearch::
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000845LookupSubframeworkHeader(StringRef Filename,
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000846 const FileEntry *ContextFileEnt,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000847 SmallVectorImpl<char> *SearchPath,
Douglas Gregorf5f94522013-02-08 00:10:48 +0000848 SmallVectorImpl<char> *RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000849 Module *RequestingModule,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000850 ModuleMap::KnownHeader *SuggestedModule) {
Chris Lattner12261882008-02-01 05:34:02 +0000851 assert(ContextFileEnt && "No context file?");
Mike Stump11289f42009-09-09 15:08:12 +0000852
Chris Lattner63dd32b2006-10-20 04:42:40 +0000853 // Framework names must have a '/' in the filename. Find it.
Douglas Gregor5ca04bd2011-12-09 16:48:01 +0000854 // FIXME: Should we permit '\' on Windows?
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000855 size_t SlashPos = Filename.find('/');
Craig Topperd2d442c2014-05-17 23:10:59 +0000856 if (SlashPos == StringRef::npos) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000857
Chris Lattner63dd32b2006-10-20 04:42:40 +0000858 // Look up the base framework name of the ContextFileEnt.
Mehdi Amini004b9c72016-10-10 22:52:47 +0000859 StringRef ContextName = ContextFileEnt->getName();
Mike Stump11289f42009-09-09 15:08:12 +0000860
Chris Lattner63dd32b2006-10-20 04:42:40 +0000861 // If the context info wasn't a framework, couldn't be a subframework.
Douglas Gregor5ca04bd2011-12-09 16:48:01 +0000862 const unsigned DotFrameworkLen = 10;
Mehdi Amini004b9c72016-10-10 22:52:47 +0000863 auto FrameworkPos = ContextName.find(".framework");
864 if (FrameworkPos == StringRef::npos ||
865 (ContextName[FrameworkPos + DotFrameworkLen] != '/' &&
866 ContextName[FrameworkPos + DotFrameworkLen] != '\\'))
Craig Topperd2d442c2014-05-17 23:10:59 +0000867 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000868
Mehdi Amini004b9c72016-10-10 22:52:47 +0000869 SmallString<1024> FrameworkName(ContextName.data(), ContextName.data() +
870 FrameworkPos +
871 DotFrameworkLen + 1);
Chris Lattner5ed76da2006-10-22 07:24:13 +0000872
Chris Lattner63dd32b2006-10-20 04:42:40 +0000873 // Append Frameworks/HIToolbox.framework/
874 FrameworkName += "Frameworks/";
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000875 FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos);
Chris Lattner63dd32b2006-10-20 04:42:40 +0000876 FrameworkName += ".framework/";
Chris Lattner577377e2006-10-20 04:55:45 +0000877
David Blaikie13156b62014-11-19 03:06:06 +0000878 auto &CacheLookup =
879 *FrameworkMap.insert(std::make_pair(Filename.substr(0, SlashPos),
880 FrameworkCacheEntry())).first;
Mike Stump11289f42009-09-09 15:08:12 +0000881
Chris Lattner5ed76da2006-10-22 07:24:13 +0000882 // Some other location?
David Blaikie13156b62014-11-19 03:06:06 +0000883 if (CacheLookup.second.Directory &&
884 CacheLookup.first().size() == FrameworkName.size() &&
885 memcmp(CacheLookup.first().data(), &FrameworkName[0],
886 CacheLookup.first().size()) != 0)
Craig Topperd2d442c2014-05-17 23:10:59 +0000887 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000888
Chris Lattner5ed76da2006-10-22 07:24:13 +0000889 // Cache subframework.
David Blaikie13156b62014-11-19 03:06:06 +0000890 if (!CacheLookup.second.Directory) {
Chris Lattner5ed76da2006-10-22 07:24:13 +0000891 ++NumSubFrameworkLookups;
Mike Stump11289f42009-09-09 15:08:12 +0000892
Chris Lattner5ed76da2006-10-22 07:24:13 +0000893 // If the framework dir doesn't exist, we fail.
Yaron Keren92e1b622015-03-18 10:17:07 +0000894 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName);
Craig Topperd2d442c2014-05-17 23:10:59 +0000895 if (!Dir) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000896
Chris Lattner5ed76da2006-10-22 07:24:13 +0000897 // Otherwise, if it does, remember that this is the right direntry for this
898 // framework.
David Blaikie13156b62014-11-19 03:06:06 +0000899 CacheLookup.second.Directory = Dir;
Chris Lattner5ed76da2006-10-22 07:24:13 +0000900 }
Mike Stump11289f42009-09-09 15:08:12 +0000901
Craig Topperd2d442c2014-05-17 23:10:59 +0000902 const FileEntry *FE = nullptr;
Chris Lattner577377e2006-10-20 04:55:45 +0000903
Craig Topperd2d442c2014-05-17 23:10:59 +0000904 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000905 RelativePath->clear();
906 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
907 }
908
Chris Lattner63dd32b2006-10-20 04:42:40 +0000909 // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000910 SmallString<1024> HeadersFilename(FrameworkName);
Chris Lattner43fd42e2006-10-30 03:40:58 +0000911 HeadersFilename += "Headers/";
Craig Topperd2d442c2014-05-17 23:10:59 +0000912 if (SearchPath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000913 SearchPath->clear();
914 // Without trailing '/'.
915 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
916 }
917
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000918 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
Yaron Keren92e1b622015-03-18 10:17:07 +0000919 if (!(FE = FileMgr.getFile(HeadersFilename, /*openFile=*/true))) {
Mike Stump11289f42009-09-09 15:08:12 +0000920
Chris Lattner63dd32b2006-10-20 04:42:40 +0000921 // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
Chris Lattner43fd42e2006-10-30 03:40:58 +0000922 HeadersFilename = FrameworkName;
923 HeadersFilename += "PrivateHeaders/";
Craig Topperd2d442c2014-05-17 23:10:59 +0000924 if (SearchPath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000925 SearchPath->clear();
926 // Without trailing '/'.
927 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
928 }
929
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000930 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
Yaron Keren92e1b622015-03-18 10:17:07 +0000931 if (!(FE = FileMgr.getFile(HeadersFilename, /*openFile=*/true)))
Craig Topperd2d442c2014-05-17 23:10:59 +0000932 return nullptr;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000933 }
Mike Stump11289f42009-09-09 15:08:12 +0000934
Chris Lattner577377e2006-10-20 04:55:45 +0000935 // This file is a system header or C++ unfriendly if the old file is.
Ted Kremenek72be0682008-02-24 03:55:14 +0000936 //
Chris Lattnerf5c619f2008-02-25 21:38:21 +0000937 // Note that the temporary 'DirInfo' is required here, as either call to
938 // getFileInfo could resize the vector and we don't want to rely on order
939 // of evaluation.
940 unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo;
941 getFileInfo(FE).DirInfo = DirInfo;
Douglas Gregorf5f94522013-02-08 00:10:48 +0000942
Richard Smith3d5b48c2015-10-16 21:42:56 +0000943 FrameworkName.pop_back(); // remove the trailing '/'
944 if (!findUsableModuleForFrameworkHeader(FE, FrameworkName, RequestingModule,
945 SuggestedModule, /*IsSystem*/ false))
946 return nullptr;
Douglas Gregorf5f94522013-02-08 00:10:48 +0000947
Chris Lattner577377e2006-10-20 04:55:45 +0000948 return FE;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000949}
950
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000951//===----------------------------------------------------------------------===//
952// File Info Management.
953//===----------------------------------------------------------------------===//
954
Douglas Gregor5d1bee22011-09-17 05:35:18 +0000955/// \brief Merge the header file info provided by \p OtherHFI into the current
956/// header file info (\p HFI)
957static void mergeHeaderFileInfo(HeaderFileInfo &HFI,
958 const HeaderFileInfo &OtherHFI) {
Richard Smithd8879c82015-08-24 21:59:32 +0000959 assert(OtherHFI.External && "expected to merge external HFI");
960
Douglas Gregor5d1bee22011-09-17 05:35:18 +0000961 HFI.isImport |= OtherHFI.isImport;
962 HFI.isPragmaOnce |= OtherHFI.isPragmaOnce;
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +0000963 HFI.isModuleHeader |= OtherHFI.isModuleHeader;
Douglas Gregor5d1bee22011-09-17 05:35:18 +0000964 HFI.NumIncludes += OtherHFI.NumIncludes;
Richard Smithd8879c82015-08-24 21:59:32 +0000965
Douglas Gregor5d1bee22011-09-17 05:35:18 +0000966 if (!HFI.ControllingMacro && !HFI.ControllingMacroID) {
967 HFI.ControllingMacro = OtherHFI.ControllingMacro;
968 HFI.ControllingMacroID = OtherHFI.ControllingMacroID;
969 }
Richard Smithd8879c82015-08-24 21:59:32 +0000970
971 HFI.DirInfo = OtherHFI.DirInfo;
972 HFI.External = (!HFI.IsValid || HFI.External);
973 HFI.IsValid = true;
974 HFI.IndexHeaderMapHeader = OtherHFI.IndexHeaderMapHeader;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000975
Douglas Gregor5d1bee22011-09-17 05:35:18 +0000976 if (HFI.Framework.empty())
977 HFI.Framework = OtherHFI.Framework;
Douglas Gregor5d1bee22011-09-17 05:35:18 +0000978}
979
Steve Naroff3fa455a2009-04-24 20:03:17 +0000980/// getFileInfo - Return the HeaderFileInfo structure for the specified
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000981/// FileEntry.
Steve Naroff3fa455a2009-04-24 20:03:17 +0000982HeaderFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) {
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000983 if (FE->getUID() >= FileInfo.size())
Richard Smith386bb072015-08-18 23:42:23 +0000984 FileInfo.resize(FE->getUID() + 1);
985
Richard Smithd8879c82015-08-24 21:59:32 +0000986 HeaderFileInfo *HFI = &FileInfo[FE->getUID()];
Richard Smith386bb072015-08-18 23:42:23 +0000987 // FIXME: Use a generation count to check whether this is really up to date.
Richard Smithd8879c82015-08-24 21:59:32 +0000988 if (ExternalSource && !HFI->Resolved) {
989 HFI->Resolved = true;
990 auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE);
991
992 HFI = &FileInfo[FE->getUID()];
993 if (ExternalHFI.External)
994 mergeHeaderFileInfo(*HFI, ExternalHFI);
Richard Smith386bb072015-08-18 23:42:23 +0000995 }
996
Richard Smithd8879c82015-08-24 21:59:32 +0000997 HFI->IsValid = true;
Richard Smith386bb072015-08-18 23:42:23 +0000998 // We have local information about this header file, so it's no longer
999 // strictly external.
Richard Smithd8879c82015-08-24 21:59:32 +00001000 HFI->External = false;
1001 return *HFI;
Mike Stump11289f42009-09-09 15:08:12 +00001002}
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001003
Richard Smith386bb072015-08-18 23:42:23 +00001004const HeaderFileInfo *
Richard Smithd8879c82015-08-24 21:59:32 +00001005HeaderSearch::getExistingFileInfo(const FileEntry *FE,
1006 bool WantExternal) const {
Richard Smith386bb072015-08-18 23:42:23 +00001007 // If we have an external source, ensure we have the latest information.
1008 // FIXME: Use a generation count to check whether this is really up to date.
Richard Smithd8879c82015-08-24 21:59:32 +00001009 HeaderFileInfo *HFI;
1010 if (ExternalSource) {
1011 if (FE->getUID() >= FileInfo.size()) {
1012 if (!WantExternal)
1013 return nullptr;
1014 FileInfo.resize(FE->getUID() + 1);
Richard Smith386bb072015-08-18 23:42:23 +00001015 }
Richard Smithd8879c82015-08-24 21:59:32 +00001016
1017 HFI = &FileInfo[FE->getUID()];
1018 if (!WantExternal && (!HFI->IsValid || HFI->External))
1019 return nullptr;
1020 if (!HFI->Resolved) {
1021 HFI->Resolved = true;
1022 auto ExternalHFI = ExternalSource->GetHeaderFileInfo(FE);
1023
1024 HFI = &FileInfo[FE->getUID()];
1025 if (ExternalHFI.External)
1026 mergeHeaderFileInfo(*HFI, ExternalHFI);
1027 }
1028 } else if (FE->getUID() >= FileInfo.size()) {
1029 return nullptr;
1030 } else {
1031 HFI = &FileInfo[FE->getUID()];
Ben Langmuird285c502014-03-13 16:46:36 +00001032 }
Richard Smith386bb072015-08-18 23:42:23 +00001033
Richard Smithd8879c82015-08-24 21:59:32 +00001034 if (!HFI->IsValid || (HFI->External && !WantExternal))
Richard Smith386bb072015-08-18 23:42:23 +00001035 return nullptr;
1036
Richard Smithd8879c82015-08-24 21:59:32 +00001037 return HFI;
Ben Langmuird285c502014-03-13 16:46:36 +00001038}
1039
Douglas Gregor37aa4932011-05-04 00:14:37 +00001040bool HeaderSearch::isFileMultipleIncludeGuarded(const FileEntry *File) {
1041 // Check if we've ever seen this file as a header.
Richard Smith386bb072015-08-18 23:42:23 +00001042 if (auto *HFI = getExistingFileInfo(File))
1043 return HFI->isPragmaOnce || HFI->isImport || HFI->ControllingMacro ||
1044 HFI->ControllingMacroID;
1045 return false;
Douglas Gregor37aa4932011-05-04 00:14:37 +00001046}
1047
Argyrios Kyrtzidis6f722b42013-05-08 23:46:46 +00001048void HeaderSearch::MarkFileModuleHeader(const FileEntry *FE,
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001049 ModuleMap::ModuleHeaderRole Role,
Argyrios Kyrtzidis6f722b42013-05-08 23:46:46 +00001050 bool isCompilingModuleHeader) {
Richard Smithd8879c82015-08-24 21:59:32 +00001051 bool isModularHeader = !(Role & ModuleMap::TextualHeader);
1052
1053 // Don't mark the file info as non-external if there's nothing to change.
1054 if (!isCompilingModuleHeader) {
1055 if (!isModularHeader)
1056 return;
1057 auto *HFI = getExistingFileInfo(FE);
1058 if (HFI && HFI->isModuleHeader)
1059 return;
1060 }
1061
Richard Smith386bb072015-08-18 23:42:23 +00001062 auto &HFI = getFileInfo(FE);
Richard Smithd8879c82015-08-24 21:59:32 +00001063 HFI.isModuleHeader |= isModularHeader;
Richard Smithe70dadd2015-07-10 22:27:17 +00001064 HFI.isCompilingModuleHeader |= isCompilingModuleHeader;
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001065}
1066
Richard Smith20e883e2015-04-29 23:20:19 +00001067bool HeaderSearch::ShouldEnterIncludeFile(Preprocessor &PP,
1068 const FileEntry *File,
Richard Smith035f6dc2015-07-01 01:51:38 +00001069 bool isImport, Module *M) {
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001070 ++NumIncluded; // Count # of attempted #includes.
1071
1072 // Get information about this file.
Steve Naroff3fa455a2009-04-24 20:03:17 +00001073 HeaderFileInfo &FileInfo = getFileInfo(File);
Mike Stump11289f42009-09-09 15:08:12 +00001074
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001075 // If this is a #import directive, check that we have not already imported
1076 // this header.
1077 if (isImport) {
1078 // If this has already been imported, don't import it again.
1079 FileInfo.isImport = true;
Mike Stump11289f42009-09-09 15:08:12 +00001080
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001081 // Has this already been #import'ed or #include'd?
1082 if (FileInfo.NumIncludes) return false;
1083 } else {
1084 // Otherwise, if this is a #include of a file that was previously #import'd
1085 // or if this is the second #include of a #pragma once file, ignore it.
1086 if (FileInfo.isImport)
1087 return false;
1088 }
Mike Stump11289f42009-09-09 15:08:12 +00001089
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001090 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
1091 // if the macro that guards it is defined, we know the #include has no effect.
Mike Stump11289f42009-09-09 15:08:12 +00001092 if (const IdentifierInfo *ControllingMacro
Richard Smithe70dadd2015-07-10 22:27:17 +00001093 = FileInfo.getControllingMacro(ExternalLookup)) {
1094 // If the header corresponds to a module, check whether the macro is already
1095 // defined in that module rather than checking in the current set of visible
1096 // modules.
1097 if (M ? PP.isMacroDefinedInLocalModule(ControllingMacro, M)
1098 : PP.isMacroDefined(ControllingMacro)) {
Douglas Gregor99734e72009-04-25 23:30:02 +00001099 ++NumMultiIncludeFileOptzn;
1100 return false;
1101 }
Richard Smithe70dadd2015-07-10 22:27:17 +00001102 }
Mike Stump11289f42009-09-09 15:08:12 +00001103
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001104 // Increment the number of times this file has been included.
1105 ++FileInfo.NumIncludes;
Mike Stump11289f42009-09-09 15:08:12 +00001106
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001107 return true;
1108}
1109
Ted Kremenekfbcce6f2011-07-26 23:46:11 +00001110size_t HeaderSearch::getTotalMemory() const {
1111 return SearchDirs.capacity()
Ted Kremenekae63d102011-07-27 18:41:18 +00001112 + llvm::capacity_in_bytes(FileInfo)
1113 + llvm::capacity_in_bytes(HeaderMaps)
Ted Kremenekfbcce6f2011-07-26 23:46:11 +00001114 + LookupFileCache.getAllocator().getTotalMemory()
1115 + FrameworkMap.getAllocator().getTotalMemory();
1116}
Douglas Gregor9f93e382011-07-28 04:45:53 +00001117
1118StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) {
David Blaikie13156b62014-11-19 03:06:06 +00001119 return FrameworkNames.insert(Framework).first->first();
Douglas Gregor9f93e382011-07-28 04:45:53 +00001120}
Douglas Gregor718292f2011-11-11 19:10:28 +00001121
1122bool HeaderSearch::hasModuleMap(StringRef FileName,
Douglas Gregor963c5532013-06-21 16:28:10 +00001123 const DirectoryEntry *Root,
1124 bool IsSystem) {
Richard Smith47972af2015-06-16 00:08:24 +00001125 if (!HSOpts->ImplicitModuleMaps)
Argyrios Kyrtzidis9955dbc2013-12-12 16:08:33 +00001126 return false;
1127
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001128 SmallVector<const DirectoryEntry *, 2> FixUpDirectories;
Douglas Gregor718292f2011-11-11 19:10:28 +00001129
1130 StringRef DirName = FileName;
1131 do {
1132 // Get the parent directory name.
1133 DirName = llvm::sys::path::parent_path(DirName);
1134 if (DirName.empty())
1135 return false;
Daniel Jasperca9f7382013-09-24 09:27:13 +00001136
Douglas Gregor718292f2011-11-11 19:10:28 +00001137 // Determine whether this directory exists.
1138 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
1139 if (!Dir)
1140 return false;
Daniel Jasperca9f7382013-09-24 09:27:13 +00001141
Ben Langmuir984e1df2014-03-19 20:23:34 +00001142 // Try to load the module map file in this directory.
Richard Smith3c1a41a2014-12-02 00:08:08 +00001143 switch (loadModuleMapFile(Dir, IsSystem,
1144 llvm::sys::path::extension(Dir->getName()) ==
1145 ".framework")) {
Douglas Gregor80b69042011-11-12 00:22:19 +00001146 case LMM_NewlyLoaded:
1147 case LMM_AlreadyLoaded:
Daniel Jasperca9f7382013-09-24 09:27:13 +00001148 // Success. All of the directories we stepped through inherit this module
1149 // map file.
1150 for (unsigned I = 0, N = FixUpDirectories.size(); I != N; ++I)
1151 DirectoryHasModuleMap[FixUpDirectories[I]] = true;
1152 return true;
Daniel Jasper97da9172013-10-22 08:09:47 +00001153
1154 case LMM_NoDirectory:
1155 case LMM_InvalidModuleMap:
1156 break;
Daniel Jasperca9f7382013-09-24 09:27:13 +00001157 }
1158
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001159 // If we hit the top of our search, we're done.
1160 if (Dir == Root)
1161 return false;
1162
Douglas Gregor718292f2011-11-11 19:10:28 +00001163 // Keep track of all of the directories we checked, so we can mark them as
1164 // having module maps if we eventually do find a module map.
1165 FixUpDirectories.push_back(Dir);
1166 } while (true);
Douglas Gregor718292f2011-11-11 19:10:28 +00001167}
1168
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001169ModuleMap::KnownHeader
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +00001170HeaderSearch::findModuleForHeader(const FileEntry *File,
1171 bool AllowTextual) const {
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001172 if (ExternalSource) {
1173 // Make sure the external source has handled header info about this file,
1174 // which includes whether the file is part of a module.
Richard Smith386bb072015-08-18 23:42:23 +00001175 (void)getExistingFileInfo(File);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001176 }
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +00001177 return ModMap.findModuleForHeader(File, AllowTextual);
1178}
1179
1180static bool suggestModule(HeaderSearch &HS, const FileEntry *File,
1181 Module *RequestingModule,
1182 ModuleMap::KnownHeader *SuggestedModule) {
1183 ModuleMap::KnownHeader Module =
1184 HS.findModuleForHeader(File, /*AllowTextual*/true);
1185 if (SuggestedModule)
1186 *SuggestedModule = (Module.getRole() & ModuleMap::TextualHeader)
1187 ? ModuleMap::KnownHeader()
1188 : Module;
1189
1190 // If this module specifies [no_undeclared_includes], we cannot find any
1191 // file that's in a non-dependency module.
1192 if (RequestingModule && Module && RequestingModule->NoUndeclaredIncludes) {
1193 HS.getModuleMap().resolveUses(RequestingModule, /*Complain*/false);
1194 if (!RequestingModule->directlyUses(Module.getModule())) {
1195 return false;
1196 }
1197 }
1198
1199 return true;
Douglas Gregor718292f2011-11-11 19:10:28 +00001200}
1201
Richard Smith3d5b48c2015-10-16 21:42:56 +00001202bool HeaderSearch::findUsableModuleForHeader(
1203 const FileEntry *File, const DirectoryEntry *Root, Module *RequestingModule,
1204 ModuleMap::KnownHeader *SuggestedModule, bool IsSystemHeaderDir) {
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +00001205 if (File && needModuleLookup(RequestingModule, SuggestedModule)) {
Richard Smith3d5b48c2015-10-16 21:42:56 +00001206 // If there is a module that corresponds to this header, suggest it.
1207 hasModuleMap(File->getName(), Root, IsSystemHeaderDir);
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +00001208 return suggestModule(*this, File, RequestingModule, SuggestedModule);
Richard Smith3d5b48c2015-10-16 21:42:56 +00001209 }
1210 return true;
1211}
1212
1213bool HeaderSearch::findUsableModuleForFrameworkHeader(
1214 const FileEntry *File, StringRef FrameworkName, Module *RequestingModule,
1215 ModuleMap::KnownHeader *SuggestedModule, bool IsSystemFramework) {
1216 // If we're supposed to suggest a module, look for one now.
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +00001217 if (needModuleLookup(RequestingModule, SuggestedModule)) {
Richard Smith3d5b48c2015-10-16 21:42:56 +00001218 // Find the top-level framework based on this framework.
1219 SmallVector<std::string, 4> SubmodulePath;
1220 const DirectoryEntry *TopFrameworkDir
1221 = ::getTopFrameworkDir(FileMgr, FrameworkName, SubmodulePath);
1222
1223 // Determine the name of the top-level framework.
1224 StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
1225
1226 // Load this framework module. If that succeeds, find the suggested module
1227 // for this header, if any.
1228 loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystemFramework);
1229
1230 // FIXME: This can find a module not part of ModuleName, which is
1231 // important so that we're consistent about whether this header
1232 // corresponds to a module. Possibly we should lock down framework modules
1233 // so that this is not possible.
Bruno Cardoso Lopesed84df02016-10-21 01:41:56 +00001234 return suggestModule(*this, File, RequestingModule, SuggestedModule);
Richard Smith3d5b48c2015-10-16 21:42:56 +00001235 }
1236 return true;
1237}
1238
Richard Smith9acb99e32014-12-10 03:09:48 +00001239static const FileEntry *getPrivateModuleMap(const FileEntry *File,
Ben Langmuir984e1df2014-03-19 20:23:34 +00001240 FileManager &FileMgr) {
Richard Smith9acb99e32014-12-10 03:09:48 +00001241 StringRef Filename = llvm::sys::path::filename(File->getName());
1242 SmallString<128> PrivateFilename(File->getDir()->getName());
Ben Langmuir984e1df2014-03-19 20:23:34 +00001243 if (Filename == "module.map")
Douglas Gregor80306772011-12-07 21:25:07 +00001244 llvm::sys::path::append(PrivateFilename, "module_private.map");
Ben Langmuir984e1df2014-03-19 20:23:34 +00001245 else if (Filename == "module.modulemap")
1246 llvm::sys::path::append(PrivateFilename, "module.private.modulemap");
1247 else
1248 return nullptr;
1249 return FileMgr.getFile(PrivateFilename);
Douglas Gregor2b20cb82011-11-16 00:09:06 +00001250}
1251
Ben Langmuir984e1df2014-03-19 20:23:34 +00001252bool HeaderSearch::loadModuleMapFile(const FileEntry *File, bool IsSystem) {
Richard Smith9acb99e32014-12-10 03:09:48 +00001253 // Find the directory for the module. For frameworks, that may require going
1254 // up from the 'Modules' directory.
1255 const DirectoryEntry *Dir = nullptr;
1256 if (getHeaderSearchOpts().ModuleMapFileHomeIsCwd)
1257 Dir = FileMgr.getDirectory(".");
1258 else {
1259 Dir = File->getDir();
1260 StringRef DirName(Dir->getName());
1261 if (llvm::sys::path::filename(DirName) == "Modules") {
1262 DirName = llvm::sys::path::parent_path(DirName);
1263 if (DirName.endswith(".framework"))
1264 Dir = FileMgr.getDirectory(DirName);
1265 // FIXME: This assert can fail if there's a race between the above check
1266 // and the removal of the directory.
1267 assert(Dir && "parent must exist");
1268 }
1269 }
1270
1271 switch (loadModuleMapFileImpl(File, IsSystem, Dir)) {
Ben Langmuir984e1df2014-03-19 20:23:34 +00001272 case LMM_AlreadyLoaded:
1273 case LMM_NewlyLoaded:
1274 return false;
1275 case LMM_NoDirectory:
1276 case LMM_InvalidModuleMap:
1277 return true;
1278 }
Aaron Ballmand8de5b62014-03-20 14:22:33 +00001279 llvm_unreachable("Unknown load module map result");
Ben Langmuir984e1df2014-03-19 20:23:34 +00001280}
1281
1282HeaderSearch::LoadModuleMapResult
Richard Smith9acb99e32014-12-10 03:09:48 +00001283HeaderSearch::loadModuleMapFileImpl(const FileEntry *File, bool IsSystem,
1284 const DirectoryEntry *Dir) {
Ben Langmuir984e1df2014-03-19 20:23:34 +00001285 assert(File && "expected FileEntry");
1286
Richard Smith9887d792014-10-17 01:42:53 +00001287 // Check whether we've already loaded this module map, and mark it as being
1288 // loaded in case we recursively try to load it from itself.
1289 auto AddResult = LoadedModuleMaps.insert(std::make_pair(File, true));
1290 if (!AddResult.second)
1291 return AddResult.first->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001292
Richard Smith9acb99e32014-12-10 03:09:48 +00001293 if (ModMap.parseModuleMapFile(File, IsSystem, Dir)) {
Richard Smith9887d792014-10-17 01:42:53 +00001294 LoadedModuleMaps[File] = false;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001295 return LMM_InvalidModuleMap;
1296 }
1297
1298 // Try to load a corresponding private module map.
Richard Smith9acb99e32014-12-10 03:09:48 +00001299 if (const FileEntry *PMMFile = getPrivateModuleMap(File, FileMgr)) {
1300 if (ModMap.parseModuleMapFile(PMMFile, IsSystem, Dir)) {
Richard Smith9887d792014-10-17 01:42:53 +00001301 LoadedModuleMaps[File] = false;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001302 return LMM_InvalidModuleMap;
1303 }
1304 }
1305
1306 // This directory has a module map.
Ben Langmuir984e1df2014-03-19 20:23:34 +00001307 return LMM_NewlyLoaded;
1308}
1309
1310const FileEntry *
1311HeaderSearch::lookupModuleMapFile(const DirectoryEntry *Dir, bool IsFramework) {
Richard Smith47972af2015-06-16 00:08:24 +00001312 if (!HSOpts->ImplicitModuleMaps)
Daniel Jasper21a0f552014-11-25 09:45:48 +00001313 return nullptr;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001314 // For frameworks, the preferred spelling is Modules/module.modulemap, but
1315 // module.map at the framework root is also accepted.
1316 SmallString<128> ModuleMapFileName(Dir->getName());
1317 if (IsFramework)
1318 llvm::sys::path::append(ModuleMapFileName, "Modules");
1319 llvm::sys::path::append(ModuleMapFileName, "module.modulemap");
1320 if (const FileEntry *F = FileMgr.getFile(ModuleMapFileName))
1321 return F;
1322
1323 // Continue to allow module.map
1324 ModuleMapFileName = Dir->getName();
1325 llvm::sys::path::append(ModuleMapFileName, "module.map");
1326 return FileMgr.getFile(ModuleMapFileName);
1327}
1328
1329Module *HeaderSearch::loadFrameworkModule(StringRef Name,
Douglas Gregor279a6c32012-01-29 17:08:11 +00001330 const DirectoryEntry *Dir,
1331 bool IsSystem) {
Douglas Gregorde3ef502011-11-30 23:21:26 +00001332 if (Module *Module = ModMap.findModule(Name))
Douglas Gregor56c64012011-11-17 01:41:17 +00001333 return Module;
Daniel Jasper21a0f552014-11-25 09:45:48 +00001334
Douglas Gregor56c64012011-11-17 01:41:17 +00001335 // Try to load a module map file.
Ben Langmuir984e1df2014-03-19 20:23:34 +00001336 switch (loadModuleMapFile(Dir, IsSystem, /*IsFramework*/true)) {
Douglas Gregor56c64012011-11-17 01:41:17 +00001337 case LMM_InvalidModuleMap:
Ben Langmuira5254002015-07-02 13:19:48 +00001338 // Try to infer a module map from the framework directory.
1339 if (HSOpts->ImplicitModuleMaps)
1340 ModMap.inferFrameworkModule(Dir, IsSystem, /*Parent=*/nullptr);
Douglas Gregor56c64012011-11-17 01:41:17 +00001341 break;
Daniel Jasper21a0f552014-11-25 09:45:48 +00001342
Douglas Gregor56c64012011-11-17 01:41:17 +00001343 case LMM_AlreadyLoaded:
1344 case LMM_NoDirectory:
Craig Topperd2d442c2014-05-17 23:10:59 +00001345 return nullptr;
1346
Douglas Gregor56c64012011-11-17 01:41:17 +00001347 case LMM_NewlyLoaded:
Ben Langmuira5254002015-07-02 13:19:48 +00001348 break;
Douglas Gregor56c64012011-11-17 01:41:17 +00001349 }
Douglas Gregor3a5999b2012-01-13 22:31:52 +00001350
Ben Langmuira5254002015-07-02 13:19:48 +00001351 return ModMap.findModule(Name);
Douglas Gregor56c64012011-11-17 01:41:17 +00001352}
1353
Douglas Gregor2b20cb82011-11-16 00:09:06 +00001354
Douglas Gregor80b69042011-11-12 00:22:19 +00001355HeaderSearch::LoadModuleMapResult
Ben Langmuir984e1df2014-03-19 20:23:34 +00001356HeaderSearch::loadModuleMapFile(StringRef DirName, bool IsSystem,
1357 bool IsFramework) {
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001358 if (const DirectoryEntry *Dir = FileMgr.getDirectory(DirName))
Ben Langmuir984e1df2014-03-19 20:23:34 +00001359 return loadModuleMapFile(Dir, IsSystem, IsFramework);
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001360
Douglas Gregor80b69042011-11-12 00:22:19 +00001361 return LMM_NoDirectory;
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001362}
1363
Douglas Gregor80b69042011-11-12 00:22:19 +00001364HeaderSearch::LoadModuleMapResult
Ben Langmuir984e1df2014-03-19 20:23:34 +00001365HeaderSearch::loadModuleMapFile(const DirectoryEntry *Dir, bool IsSystem,
1366 bool IsFramework) {
1367 auto KnownDir = DirectoryHasModuleMap.find(Dir);
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001368 if (KnownDir != DirectoryHasModuleMap.end())
Richard Smith9887d792014-10-17 01:42:53 +00001369 return KnownDir->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
Douglas Gregore7ab3662011-12-07 02:23:45 +00001370
Ben Langmuir984e1df2014-03-19 20:23:34 +00001371 if (const FileEntry *ModuleMapFile = lookupModuleMapFile(Dir, IsFramework)) {
Richard Smith9acb99e32014-12-10 03:09:48 +00001372 LoadModuleMapResult Result =
1373 loadModuleMapFileImpl(ModuleMapFile, IsSystem, Dir);
Ben Langmuir984e1df2014-03-19 20:23:34 +00001374 // Add Dir explicitly in case ModuleMapFile is in a subdirectory.
1375 // E.g. Foo.framework/Modules/module.modulemap
1376 // ^Dir ^ModuleMapFile
1377 if (Result == LMM_NewlyLoaded)
1378 DirectoryHasModuleMap[Dir] = true;
Richard Smith9887d792014-10-17 01:42:53 +00001379 else if (Result == LMM_InvalidModuleMap)
1380 DirectoryHasModuleMap[Dir] = false;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001381 return Result;
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001382 }
Douglas Gregor80b69042011-11-12 00:22:19 +00001383 return LMM_InvalidModuleMap;
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001384}
Douglas Gregor718292f2011-11-11 19:10:28 +00001385
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001386void HeaderSearch::collectAllModules(SmallVectorImpl<Module *> &Modules) {
Douglas Gregor07f43572012-01-29 18:15:03 +00001387 Modules.clear();
Daniel Jasper21a0f552014-11-25 09:45:48 +00001388
Richard Smith47972af2015-06-16 00:08:24 +00001389 if (HSOpts->ImplicitModuleMaps) {
Daniel Jasper21a0f552014-11-25 09:45:48 +00001390 // Load module maps for each of the header search directories.
1391 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
1392 bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
1393 if (SearchDirs[Idx].isFramework()) {
1394 std::error_code EC;
1395 SmallString<128> DirNative;
1396 llvm::sys::path::native(SearchDirs[Idx].getFrameworkDir()->getName(),
1397 DirNative);
1398
1399 // Search each of the ".framework" directories to load them as modules.
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +00001400 vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
1401 for (vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
Daniel Jasper21a0f552014-11-25 09:45:48 +00001402 Dir != DirEnd && !EC; Dir.increment(EC)) {
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +00001403 if (llvm::sys::path::extension(Dir->getName()) != ".framework")
Daniel Jasper21a0f552014-11-25 09:45:48 +00001404 continue;
1405
1406 const DirectoryEntry *FrameworkDir =
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +00001407 FileMgr.getDirectory(Dir->getName());
Daniel Jasper21a0f552014-11-25 09:45:48 +00001408 if (!FrameworkDir)
1409 continue;
1410
1411 // Load this framework module.
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +00001412 loadFrameworkModule(llvm::sys::path::stem(Dir->getName()),
1413 FrameworkDir, IsSystem);
Daniel Jasper21a0f552014-11-25 09:45:48 +00001414 }
1415 continue;
Douglas Gregor07f43572012-01-29 18:15:03 +00001416 }
Daniel Jasper21a0f552014-11-25 09:45:48 +00001417
1418 // FIXME: Deal with header maps.
1419 if (SearchDirs[Idx].isHeaderMap())
1420 continue;
1421
1422 // Try to load a module map file for the search directory.
1423 loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem,
1424 /*IsFramework*/ false);
1425
1426 // Try to load module map files for immediate subdirectories of this
1427 // search directory.
1428 loadSubdirectoryModuleMaps(SearchDirs[Idx]);
Douglas Gregor07f43572012-01-29 18:15:03 +00001429 }
Douglas Gregor07f43572012-01-29 18:15:03 +00001430 }
Daniel Jasper21a0f552014-11-25 09:45:48 +00001431
Douglas Gregor07f43572012-01-29 18:15:03 +00001432 // Populate the list of modules.
1433 for (ModuleMap::module_iterator M = ModMap.module_begin(),
1434 MEnd = ModMap.module_end();
1435 M != MEnd; ++M) {
1436 Modules.push_back(M->getValue());
1437 }
1438}
Douglas Gregor0339a642013-03-21 01:08:50 +00001439
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001440void HeaderSearch::loadTopLevelSystemModules() {
Richard Smith47972af2015-06-16 00:08:24 +00001441 if (!HSOpts->ImplicitModuleMaps)
Daniel Jasper21a0f552014-11-25 09:45:48 +00001442 return;
1443
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001444 // Load module maps for each of the header search directories.
1445 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
Douglas Gregor299787f2013-11-01 23:08:38 +00001446 // We only care about normal header directories.
1447 if (!SearchDirs[Idx].isNormalDir()) {
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001448 continue;
1449 }
1450
1451 // Try to load a module map file for the search directory.
Douglas Gregor963c5532013-06-21 16:28:10 +00001452 loadModuleMapFile(SearchDirs[Idx].getDir(),
Ben Langmuir984e1df2014-03-19 20:23:34 +00001453 SearchDirs[Idx].isSystemHeaderDirectory(),
1454 SearchDirs[Idx].isFramework());
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001455 }
1456}
1457
Douglas Gregor0339a642013-03-21 01:08:50 +00001458void HeaderSearch::loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir) {
Richard Smith47972af2015-06-16 00:08:24 +00001459 assert(HSOpts->ImplicitModuleMaps &&
Daniel Jasper21a0f552014-11-25 09:45:48 +00001460 "Should not be loading subdirectory module maps");
1461
Douglas Gregor0339a642013-03-21 01:08:50 +00001462 if (SearchDir.haveSearchedAllModuleMaps())
1463 return;
Rafael Espindolac0809172014-06-12 14:02:15 +00001464
1465 std::error_code EC;
Douglas Gregor0339a642013-03-21 01:08:50 +00001466 SmallString<128> DirNative;
1467 llvm::sys::path::native(SearchDir.getDir()->getName(), DirNative);
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +00001468 vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
1469 for (vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
Douglas Gregor0339a642013-03-21 01:08:50 +00001470 Dir != DirEnd && !EC; Dir.increment(EC)) {
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +00001471 bool IsFramework =
1472 llvm::sys::path::extension(Dir->getName()) == ".framework";
Ben Langmuir1f6a32b2015-02-24 04:58:15 +00001473 if (IsFramework == SearchDir.isFramework())
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +00001474 loadModuleMapFile(Dir->getName(), SearchDir.isSystemHeaderDirectory(),
Ben Langmuir1f6a32b2015-02-24 04:58:15 +00001475 SearchDir.isFramework());
Douglas Gregor0339a642013-03-21 01:08:50 +00001476 }
1477
1478 SearchDir.setSearchedAllModuleMaps(true);
1479}
Richard Smith4eb83932016-04-27 21:57:05 +00001480
1481std::string HeaderSearch::suggestPathToFileForDiagnostics(const FileEntry *File,
1482 bool *IsSystem) {
1483 // FIXME: We assume that the path name currently cached in the FileEntry is
1484 // the most appropriate one for this analysis (and that it's spelled the same
1485 // way as the corresponding header search path).
Mehdi Amini004b9c72016-10-10 22:52:47 +00001486 StringRef Name = File->getName();
Richard Smith4eb83932016-04-27 21:57:05 +00001487
1488 unsigned BestPrefixLength = 0;
1489 unsigned BestSearchDir;
1490
1491 for (unsigned I = 0; I != SearchDirs.size(); ++I) {
1492 // FIXME: Support this search within frameworks and header maps.
1493 if (!SearchDirs[I].isNormalDir())
1494 continue;
1495
Mehdi Amini0df59d82016-10-11 07:31:29 +00001496 StringRef Dir = SearchDirs[I].getDir()->getName();
Richard Smith4eb83932016-04-27 21:57:05 +00001497 for (auto NI = llvm::sys::path::begin(Name),
1498 NE = llvm::sys::path::end(Name),
1499 DI = llvm::sys::path::begin(Dir),
1500 DE = llvm::sys::path::end(Dir);
1501 /*termination condition in loop*/; ++NI, ++DI) {
1502 // '.' components in Name are ignored.
1503 while (NI != NE && *NI == ".")
1504 ++NI;
1505 if (NI == NE)
1506 break;
1507
1508 // '.' components in Dir are ignored.
1509 while (DI != DE && *DI == ".")
1510 ++DI;
1511 if (DI == DE) {
1512 // Dir is a prefix of Name, up to '.' components and choice of path
1513 // separators.
1514 unsigned PrefixLength = NI - llvm::sys::path::begin(Name);
1515 if (PrefixLength > BestPrefixLength) {
1516 BestPrefixLength = PrefixLength;
1517 BestSearchDir = I;
1518 }
1519 break;
1520 }
1521
1522 if (*NI != *DI)
1523 break;
1524 }
1525 }
1526
1527 if (IsSystem)
1528 *IsSystem = BestPrefixLength ? BestSearchDir >= SystemDirIdx : false;
Mehdi Amini004b9c72016-10-10 22:52:47 +00001529 return Name.drop_front(BestPrefixLength);
Richard Smith4eb83932016-04-27 21:57:05 +00001530}