blob: 02fd87c8226d3f4baf2641d0531be9cb7c8e38bd [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"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "clang/Lex/HeaderMap.h"
18#include "clang/Lex/HeaderSearchOptions.h"
Will Wilson0fafd342013-12-27 19:46:16 +000019#include "clang/Lex/LexDiagnostic.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000020#include "clang/Lex/Lexer.h"
Ben Langmuirbeee15e2014-04-14 18:00:01 +000021#include "llvm/ADT/APInt.h"
22#include "llvm/ADT/Hashing.h"
Chris Lattner43fd42e2006-10-30 03:40:58 +000023#include "llvm/ADT/SmallString.h"
Ted Kremenekae63d102011-07-27 18:41:18 +000024#include "llvm/Support/Capacity.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "llvm/Support/FileSystem.h"
26#include "llvm/Support/Path.h"
Daniel Jasperba7f2f72013-09-24 09:14:14 +000027#include "llvm/Support/raw_ostream.h"
Chris Lattnerc25d8a72009-03-02 22:20:04 +000028#include <cstdio>
Douglas Gregor01c7cfa2013-01-22 23:49:45 +000029#if defined(LLVM_ON_UNIX)
Dmitri Gribenkoeadae012013-01-26 16:29:36 +000030#include <limits.h>
Douglas Gregor01c7cfa2013-01-22 23:49:45 +000031#endif
Chris Lattner59a9ebd2006-10-18 05:34:33 +000032using namespace clang;
33
Douglas Gregor99734e72009-04-25 23:30:02 +000034const IdentifierInfo *
35HeaderFileInfo::getControllingMacro(ExternalIdentifierLookup *External) {
36 if (ControllingMacro)
37 return ControllingMacro;
38
39 if (!ControllingMacroID || !External)
Craig Topperd2d442c2014-05-17 23:10:59 +000040 return nullptr;
Douglas Gregor99734e72009-04-25 23:30:02 +000041
42 ControllingMacro = External->GetIdentifier(ControllingMacroID);
43 return ControllingMacro;
44}
45
Douglas Gregor09b69892011-02-10 17:09:37 +000046ExternalHeaderFileInfoSource::~ExternalHeaderFileInfoSource() {}
47
Dmitri Gribenkof8579502013-01-12 19:30:44 +000048HeaderSearch::HeaderSearch(IntrusiveRefCntPtr<HeaderSearchOptions> HSOpts,
Manuel Klimek1f76c4e2013-10-24 07:51:24 +000049 SourceManager &SourceMgr, DiagnosticsEngine &Diags,
Will Wilson0fafd342013-12-27 19:46:16 +000050 const LangOptions &LangOpts,
Douglas Gregor89929282012-01-30 06:01:29 +000051 const TargetInfo *Target)
Will Wilsonba2f1462013-12-27 20:02:27 +000052 : HSOpts(HSOpts), Diags(Diags), FileMgr(SourceMgr.getFileManager()),
Daniel Jasper21a0f552014-11-25 09:45:48 +000053 FrameworkMap(64), ModMap(SourceMgr, Diags, LangOpts, Target, *this),
54 LangOpts(LangOpts) {
Nico Weber3b1d1212011-05-24 04:31:14 +000055 AngledDirIdx = 0;
Chris Lattner641a0be2006-10-20 06:23:14 +000056 SystemDirIdx = 0;
57 NoCurDirSearch = false;
Mike Stump11289f42009-09-09 15:08:12 +000058
Craig Topperd2d442c2014-05-17 23:10:59 +000059 ExternalLookup = nullptr;
60 ExternalSource = nullptr;
Chris Lattner641a0be2006-10-20 06:23:14 +000061 NumIncluded = 0;
62 NumMultiIncludeFileOptzn = 0;
63 NumFrameworkLookups = NumSubFrameworkLookups = 0;
64}
65
Chris Lattnerc4ba38e2007-12-17 06:36:45 +000066HeaderSearch::~HeaderSearch() {
67 // Delete headermaps.
68 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
69 delete HeaderMaps[i].second;
70}
Mike Stump11289f42009-09-09 15:08:12 +000071
Chris Lattner59a9ebd2006-10-18 05:34:33 +000072void HeaderSearch::PrintStats() {
Chris Lattner23b7eb62007-06-15 23:05:46 +000073 fprintf(stderr, "\n*** HeaderSearch Stats:\n");
74 fprintf(stderr, "%d files tracked.\n", (int)FileInfo.size());
Chris Lattner59a9ebd2006-10-18 05:34:33 +000075 unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0;
76 for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) {
77 NumOnceOnlyFiles += FileInfo[i].isImport;
78 if (MaxNumIncludes < FileInfo[i].NumIncludes)
79 MaxNumIncludes = FileInfo[i].NumIncludes;
80 NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1;
81 }
Chris Lattner23b7eb62007-06-15 23:05:46 +000082 fprintf(stderr, " %d #import/#pragma once files.\n", NumOnceOnlyFiles);
83 fprintf(stderr, " %d included exactly once.\n", NumSingleIncludedFiles);
84 fprintf(stderr, " %d max times a file is included.\n", MaxNumIncludes);
Mike Stump11289f42009-09-09 15:08:12 +000085
Chris Lattner23b7eb62007-06-15 23:05:46 +000086 fprintf(stderr, " %d #include/#include_next/#import.\n", NumIncluded);
87 fprintf(stderr, " %d #includes skipped due to"
88 " the multi-include optimization.\n", NumMultiIncludeFileOptzn);
Mike Stump11289f42009-09-09 15:08:12 +000089
Chris Lattner23b7eb62007-06-15 23:05:46 +000090 fprintf(stderr, "%d framework lookups.\n", NumFrameworkLookups);
91 fprintf(stderr, "%d subframework lookups.\n", NumSubFrameworkLookups);
Chris Lattner59a9ebd2006-10-18 05:34:33 +000092}
93
Chris Lattnerc4ba38e2007-12-17 06:36:45 +000094/// CreateHeaderMap - This method returns a HeaderMap for the specified
Sylvestre Ledru830885c2012-07-23 08:59:39 +000095/// FileEntry, uniquing them through the 'HeaderMaps' datastructure.
Chris Lattner4ffe46c2007-12-17 18:34:53 +000096const HeaderMap *HeaderSearch::CreateHeaderMap(const FileEntry *FE) {
Chris Lattnerc4ba38e2007-12-17 06:36:45 +000097 // We expect the number of headermaps to be small, and almost always empty.
Chris Lattnerf62f7582007-12-17 07:52:39 +000098 // If it ever grows, use of a linear search should be re-evaluated.
Chris Lattnerc4ba38e2007-12-17 06:36:45 +000099 if (!HeaderMaps.empty()) {
100 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
Chris Lattnerf62f7582007-12-17 07:52:39 +0000101 // Pointer equality comparison of FileEntries works because they are
102 // already uniqued by inode.
Mike Stump11289f42009-09-09 15:08:12 +0000103 if (HeaderMaps[i].first == FE)
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000104 return HeaderMaps[i].second;
105 }
Mike Stump11289f42009-09-09 15:08:12 +0000106
Chris Lattner5159f612010-11-23 08:35:12 +0000107 if (const HeaderMap *HM = HeaderMap::Create(FE, FileMgr)) {
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000108 HeaderMaps.push_back(std::make_pair(FE, HM));
109 return HM;
110 }
Mike Stump11289f42009-09-09 15:08:12 +0000111
Craig Topperd2d442c2014-05-17 23:10:59 +0000112 return nullptr;
Chris Lattnerc4ba38e2007-12-17 06:36:45 +0000113}
114
Douglas Gregor279a6c32012-01-29 17:08:11 +0000115std::string HeaderSearch::getModuleFileName(Module *Module) {
Ben Langmuir9d6448b2014-08-09 00:57:23 +0000116 const FileEntry *ModuleMap =
117 getModuleMap().getModuleMapFileForUniquing(Module);
118 return getModuleFileName(Module->Name, ModuleMap->getName());
Douglas Gregor279a6c32012-01-29 17:08:11 +0000119}
120
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000121std::string HeaderSearch::getModuleFileName(StringRef ModuleName,
122 StringRef ModuleMapPath) {
Douglas Gregor279a6c32012-01-29 17:08:11 +0000123 // If we don't have a module cache path, we can't do anything.
124 if (ModuleCachePath.empty())
125 return std::string();
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000126
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000127 SmallString<256> Result(ModuleCachePath);
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000128 llvm::sys::fs::make_absolute(Result);
129
130 if (HSOpts->DisableModuleHash) {
131 llvm::sys::path::append(Result, ModuleName + ".pcm");
132 } else {
133 // Construct the name <ModuleName>-<hash of ModuleMapPath>.pcm which should
134 // be globally unique to this particular module. To avoid false-negatives
135 // on case-insensitive filesystems, we use lower-case, which is safe because
136 // to cause a collision the modules must have the same name, which is an
137 // error if they are imported in the same translation.
138 SmallString<256> AbsModuleMapPath(ModuleMapPath);
139 llvm::sys::fs::make_absolute(AbsModuleMapPath);
Richard Smith3464e322014-12-06 00:09:19 +0000140 llvm::sys::path::native(AbsModuleMapPath);
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000141 llvm::APInt Code(64, llvm::hash_value(AbsModuleMapPath.str().lower()));
142 SmallString<128> HashStr;
143 Code.toStringUnsigned(HashStr, /*Radix*/36);
144 llvm::sys::path::append(Result, ModuleName + "-" + HashStr.str() + ".pcm");
145 }
Douglas Gregor279a6c32012-01-29 17:08:11 +0000146 return Result.str().str();
147}
148
149Module *HeaderSearch::lookupModule(StringRef ModuleName, bool AllowSearch) {
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000150 // Look in the module map to determine if there is a module by this name.
Douglas Gregor279a6c32012-01-29 17:08:11 +0000151 Module *Module = ModMap.findModule(ModuleName);
Daniel Jasper21a0f552014-11-25 09:45:48 +0000152 if (Module || !AllowSearch || !LangOpts.ModulesImplicitMaps)
Douglas Gregor279a6c32012-01-29 17:08:11 +0000153 return Module;
154
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000155 // Look through the various header search paths to load any available module
Douglas Gregor279a6c32012-01-29 17:08:11 +0000156 // maps, searching for a module map that describes this module.
157 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
158 if (SearchDirs[Idx].isFramework()) {
159 // Search for or infer a module map for a framework.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000160 SmallString<128> FrameworkDirName;
Douglas Gregor279a6c32012-01-29 17:08:11 +0000161 FrameworkDirName += SearchDirs[Idx].getFrameworkDir()->getName();
162 llvm::sys::path::append(FrameworkDirName, ModuleName + ".framework");
163 if (const DirectoryEntry *FrameworkDir
164 = FileMgr.getDirectory(FrameworkDirName)) {
165 bool IsSystem
166 = SearchDirs[Idx].getDirCharacteristic() != SrcMgr::C_User;
167 Module = loadFrameworkModule(ModuleName, FrameworkDir, IsSystem);
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000168 if (Module)
169 break;
170 }
Douglas Gregor279a6c32012-01-29 17:08:11 +0000171 }
172
173 // FIXME: Figure out how header maps and module maps will work together.
174
175 // Only deal with normal search directories.
176 if (!SearchDirs[Idx].isNormalDir())
177 continue;
Douglas Gregor963c5532013-06-21 16:28:10 +0000178
179 bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
Douglas Gregor279a6c32012-01-29 17:08:11 +0000180 // Search for a module map file in this directory.
Ben Langmuir984e1df2014-03-19 20:23:34 +0000181 if (loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem,
182 /*IsFramework*/false) == LMM_NewlyLoaded) {
Douglas Gregor279a6c32012-01-29 17:08:11 +0000183 // We just loaded a module map file; check whether the module is
184 // available now.
185 Module = ModMap.findModule(ModuleName);
186 if (Module)
187 break;
188 }
189
190 // Search for a module map in a subdirectory with the same name as the
191 // module.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000192 SmallString<128> NestedModuleMapDirName;
Douglas Gregor279a6c32012-01-29 17:08:11 +0000193 NestedModuleMapDirName = SearchDirs[Idx].getDir()->getName();
194 llvm::sys::path::append(NestedModuleMapDirName, ModuleName);
Ben Langmuir984e1df2014-03-19 20:23:34 +0000195 if (loadModuleMapFile(NestedModuleMapDirName, IsSystem,
196 /*IsFramework*/false) == LMM_NewlyLoaded){
Douglas Gregor279a6c32012-01-29 17:08:11 +0000197 // If we just loaded a module map file, look for the module again.
198 Module = ModMap.findModule(ModuleName);
199 if (Module)
200 break;
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000201 }
Douglas Gregor0339a642013-03-21 01:08:50 +0000202
203 // If we've already performed the exhaustive search for module maps in this
204 // search directory, don't do it again.
205 if (SearchDirs[Idx].haveSearchedAllModuleMaps())
206 continue;
207
208 // Load all module maps in the immediate subdirectories of this search
209 // directory.
210 loadSubdirectoryModuleMaps(SearchDirs[Idx]);
211
212 // Look again for the module.
213 Module = ModMap.findModule(ModuleName);
214 if (Module)
215 break;
Douglas Gregoraf28ec82011-11-12 00:05:07 +0000216 }
Douglas Gregor0339a642013-03-21 01:08:50 +0000217
Douglas Gregor279a6c32012-01-29 17:08:11 +0000218 return Module;
Douglas Gregor1e44e022011-09-12 20:41:59 +0000219}
220
Chris Lattnerf62f7582007-12-17 07:52:39 +0000221//===----------------------------------------------------------------------===//
222// File lookup within a DirectoryLookup scope
223//===----------------------------------------------------------------------===//
224
Chris Lattner8d720d02007-12-17 17:57:27 +0000225/// getName - Return the directory or filename corresponding to this lookup
226/// object.
227const char *DirectoryLookup::getName() const {
228 if (isNormalDir())
229 return getDir()->getName();
230 if (isFramework())
231 return getFrameworkDir()->getName();
232 assert(isHeaderMap() && "Unknown DirectoryLookup");
233 return getHeaderMap()->getFileName();
234}
235
Richard Smith8c71eba2014-03-05 20:51:45 +0000236static const FileEntry *
237getFileAndSuggestModule(HeaderSearch &HS, StringRef FileName,
238 const DirectoryEntry *Dir, bool IsSystemHeaderDir,
239 ModuleMap::KnownHeader *SuggestedModule) {
240 // If we have a module map that might map this header, load it and
241 // check whether we'll have a suggestion for a module.
242 HS.hasModuleMap(FileName, Dir, IsSystemHeaderDir);
243 if (SuggestedModule) {
244 const FileEntry *File = HS.getFileMgr().getFile(FileName,
245 /*OpenFile=*/false);
246 if (File) {
247 // If there is a module that corresponds to this header, suggest it.
248 *SuggestedModule = HS.findModuleForHeader(File);
249
250 // FIXME: This appears to be a no-op. We loaded the module map for this
251 // directory at the start of this function.
252 if (!SuggestedModule->getModule() &&
253 HS.hasModuleMap(FileName, Dir, IsSystemHeaderDir))
254 *SuggestedModule = HS.findModuleForHeader(File);
255 }
256
257 return File;
258 }
259
260 return HS.getFileMgr().getFile(FileName, /*openFile=*/true);
261}
Chris Lattner8d720d02007-12-17 17:57:27 +0000262
Chris Lattnerf62f7582007-12-17 07:52:39 +0000263/// LookupFile - Lookup the specified file in this search path, returning it
264/// if it exists or returning null if not.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000265const FileEntry *DirectoryLookup::LookupFile(
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000266 StringRef &Filename,
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000267 HeaderSearch &HS,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000268 SmallVectorImpl<char> *SearchPath,
Douglas Gregor97eec242011-09-15 22:00:41 +0000269 SmallVectorImpl<char> *RelativePath,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000270 ModuleMap::KnownHeader *SuggestedModule,
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000271 bool &InUserSpecifiedSystemFramework,
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000272 bool &HasBeenMapped,
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000273 SmallVectorImpl<char> &MappedName) const {
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000274 InUserSpecifiedSystemFramework = false;
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000275 HasBeenMapped = false;
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000276
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000277 SmallString<1024> TmpDir;
Chris Lattner712e3872007-12-17 08:13:48 +0000278 if (isNormalDir()) {
279 // Concatenate the requested file onto the directory.
Eli Friedmanf7ca26a2011-07-08 20:17:28 +0000280 TmpDir = getDir()->getName();
281 llvm::sys::path::append(TmpDir, Filename);
Craig Topperd2d442c2014-05-17 23:10:59 +0000282 if (SearchPath) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000283 StringRef SearchPathRef(getDir()->getName());
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000284 SearchPath->clear();
285 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
286 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000287 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000288 RelativePath->clear();
289 RelativePath->append(Filename.begin(), Filename.end());
290 }
Richard Smith8c71eba2014-03-05 20:51:45 +0000291
292 return getFileAndSuggestModule(HS, TmpDir.str(), getDir(),
293 isSystemHeaderDirectory(),
294 SuggestedModule);
Chris Lattner712e3872007-12-17 08:13:48 +0000295 }
Mike Stump11289f42009-09-09 15:08:12 +0000296
Chris Lattner712e3872007-12-17 08:13:48 +0000297 if (isFramework())
Douglas Gregor97eec242011-09-15 22:00:41 +0000298 return DoFrameworkLookup(Filename, HS, SearchPath, RelativePath,
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000299 SuggestedModule, InUserSpecifiedSystemFramework);
Mike Stump11289f42009-09-09 15:08:12 +0000300
Chris Lattner44bd21b2007-12-17 08:17:39 +0000301 assert(isHeaderMap() && "Unknown directory lookup");
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000302 const HeaderMap *HM = getHeaderMap();
303 SmallString<1024> Path;
304 StringRef Dest = HM->lookupFilename(Filename, Path);
305 if (Dest.empty())
Craig Topperd2d442c2014-05-17 23:10:59 +0000306 return nullptr;
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000307
308 const FileEntry *Result;
309
310 // Check if the headermap maps the filename to a framework include
311 // ("Foo.h" -> "Foo/Foo.h"), in which case continue header lookup using the
312 // framework include.
313 if (llvm::sys::path::is_relative(Dest)) {
314 MappedName.clear();
315 MappedName.append(Dest.begin(), Dest.end());
316 Filename = StringRef(MappedName.begin(), MappedName.size());
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000317 HasBeenMapped = true;
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000318 Result = HM->LookupFile(Filename, HS.getFileMgr());
319
320 } else {
321 Result = HS.getFileMgr().getFile(Dest);
322 }
323
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000324 if (Result) {
Craig Topperd2d442c2014-05-17 23:10:59 +0000325 if (SearchPath) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000326 StringRef SearchPathRef(getName());
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000327 SearchPath->clear();
328 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
329 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000330 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000331 RelativePath->clear();
332 RelativePath->append(Filename.begin(), Filename.end());
333 }
334 }
335 return Result;
Chris Lattnerf62f7582007-12-17 07:52:39 +0000336}
337
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000338/// \brief Given a framework directory, find the top-most framework directory.
339///
340/// \param FileMgr The file manager to use for directory lookups.
341/// \param DirName The name of the framework directory.
342/// \param SubmodulePath Will be populated with the submodule path from the
343/// returned top-level module to the originally named framework.
344static const DirectoryEntry *
345getTopFrameworkDir(FileManager &FileMgr, StringRef DirName,
346 SmallVectorImpl<std::string> &SubmodulePath) {
347 assert(llvm::sys::path::extension(DirName) == ".framework" &&
348 "Not a framework directory");
349
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000350 // Note: as an egregious but useful hack we use the real path here, because
351 // frameworks moving between top-level frameworks to embedded frameworks tend
352 // to be symlinked, and we base the logical structure of modules on the
353 // physical layout. In particular, we need to deal with crazy includes like
354 //
355 // #include <Foo/Frameworks/Bar.framework/Headers/Wibble.h>
356 //
357 // where 'Bar' used to be embedded in 'Foo', is now a top-level framework
358 // which one should access with, e.g.,
359 //
360 // #include <Bar/Wibble.h>
361 //
362 // Similar issues occur when a top-level framework has moved into an
363 // embedded framework.
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000364 const DirectoryEntry *TopFrameworkDir = FileMgr.getDirectory(DirName);
Douglas Gregore00c8b22013-01-26 00:55:12 +0000365 DirName = FileMgr.getCanonicalName(TopFrameworkDir);
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000366 do {
367 // Get the parent directory name.
368 DirName = llvm::sys::path::parent_path(DirName);
369 if (DirName.empty())
370 break;
371
372 // Determine whether this directory exists.
373 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
374 if (!Dir)
375 break;
376
377 // If this is a framework directory, then we're a subframework of this
378 // framework.
379 if (llvm::sys::path::extension(DirName) == ".framework") {
380 SubmodulePath.push_back(llvm::sys::path::stem(DirName));
381 TopFrameworkDir = Dir;
382 }
383 } while (true);
384
385 return TopFrameworkDir;
386}
Chris Lattnerf62f7582007-12-17 07:52:39 +0000387
Chris Lattner712e3872007-12-17 08:13:48 +0000388/// DoFrameworkLookup - Do a lookup of the specified file in the current
389/// DirectoryLookup, which is a framework directory.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000390const FileEntry *DirectoryLookup::DoFrameworkLookup(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000391 StringRef Filename,
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000392 HeaderSearch &HS,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000393 SmallVectorImpl<char> *SearchPath,
Douglas Gregor97eec242011-09-15 22:00:41 +0000394 SmallVectorImpl<char> *RelativePath,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000395 ModuleMap::KnownHeader *SuggestedModule,
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000396 bool &InUserSpecifiedSystemFramework) const
Douglas Gregor97eec242011-09-15 22:00:41 +0000397{
Chris Lattner712e3872007-12-17 08:13:48 +0000398 FileManager &FileMgr = HS.getFileMgr();
Mike Stump11289f42009-09-09 15:08:12 +0000399
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000400 // Framework names must have a '/' in the filename.
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000401 size_t SlashPos = Filename.find('/');
Craig Topperd2d442c2014-05-17 23:10:59 +0000402 if (SlashPos == StringRef::npos) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000403
Chris Lattner712e3872007-12-17 08:13:48 +0000404 // Find out if this is the home for the specified framework, by checking
Daniel Dunbar17138612012-04-05 17:09:40 +0000405 // HeaderSearch. Possible answers are yes/no and unknown.
406 HeaderSearch::FrameworkCacheEntry &CacheEntry =
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000407 HS.LookupFrameworkCache(Filename.substr(0, SlashPos));
Mike Stump11289f42009-09-09 15:08:12 +0000408
Chris Lattner712e3872007-12-17 08:13:48 +0000409 // If it is known and in some other directory, fail.
Daniel Dunbar17138612012-04-05 17:09:40 +0000410 if (CacheEntry.Directory && CacheEntry.Directory != getFrameworkDir())
Craig Topperd2d442c2014-05-17 23:10:59 +0000411 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000412
Chris Lattner712e3872007-12-17 08:13:48 +0000413 // Otherwise, construct the path to this framework dir.
Mike Stump11289f42009-09-09 15:08:12 +0000414
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000415 // FrameworkName = "/System/Library/Frameworks/"
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000416 SmallString<1024> FrameworkName;
Chris Lattner712e3872007-12-17 08:13:48 +0000417 FrameworkName += getFrameworkDir()->getName();
Chris Lattnerb201d9b2006-10-30 05:09:49 +0000418 if (FrameworkName.empty() || FrameworkName.back() != '/')
419 FrameworkName.push_back('/');
Mike Stump11289f42009-09-09 15:08:12 +0000420
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000421 // FrameworkName = "/System/Library/Frameworks/Cocoa"
Douglas Gregor56c64012011-11-17 01:41:17 +0000422 StringRef ModuleName(Filename.begin(), SlashPos);
423 FrameworkName += ModuleName;
Mike Stump11289f42009-09-09 15:08:12 +0000424
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000425 // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/"
426 FrameworkName += ".framework/";
Mike Stump11289f42009-09-09 15:08:12 +0000427
Daniel Dunbar17138612012-04-05 17:09:40 +0000428 // If the cache entry was unresolved, populate it now.
Craig Topperd2d442c2014-05-17 23:10:59 +0000429 if (!CacheEntry.Directory) {
Chris Lattner712e3872007-12-17 08:13:48 +0000430 HS.IncrementFrameworkLookupCount();
Mike Stump11289f42009-09-09 15:08:12 +0000431
Chris Lattner5ed76da2006-10-22 07:24:13 +0000432 // If the framework dir doesn't exist, we fail.
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000433 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName.str());
Craig Topperd2d442c2014-05-17 23:10:59 +0000434 if (!Dir) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000435
Chris Lattner5ed76da2006-10-22 07:24:13 +0000436 // Otherwise, if it does, remember that this is the right direntry for this
437 // framework.
Daniel Dunbar17138612012-04-05 17:09:40 +0000438 CacheEntry.Directory = getFrameworkDir();
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000439
440 // If this is a user search directory, check if the framework has been
441 // user-specified as a system framework.
442 if (getDirCharacteristic() == SrcMgr::C_User) {
443 SmallString<1024> SystemFrameworkMarker(FrameworkName);
444 SystemFrameworkMarker += ".system_framework";
445 if (llvm::sys::fs::exists(SystemFrameworkMarker.str())) {
446 CacheEntry.IsUserSpecifiedSystemFramework = true;
447 }
448 }
Chris Lattner5ed76da2006-10-22 07:24:13 +0000449 }
Mike Stump11289f42009-09-09 15:08:12 +0000450
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000451 // Set the 'user-specified system framework' flag.
452 InUserSpecifiedSystemFramework = CacheEntry.IsUserSpecifiedSystemFramework;
453
Craig Topperd2d442c2014-05-17 23:10:59 +0000454 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000455 RelativePath->clear();
456 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
457 }
Douglas Gregor56c64012011-11-17 01:41:17 +0000458
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000459 // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"
Chris Lattnerb201d9b2006-10-30 05:09:49 +0000460 unsigned OrigSize = FrameworkName.size();
Mike Stump11289f42009-09-09 15:08:12 +0000461
Chris Lattnerb201d9b2006-10-30 05:09:49 +0000462 FrameworkName += "Headers/";
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000463
Craig Topperd2d442c2014-05-17 23:10:59 +0000464 if (SearchPath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000465 SearchPath->clear();
466 // Without trailing '/'.
467 SearchPath->append(FrameworkName.begin(), FrameworkName.end()-1);
468 }
469
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000470 FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end());
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000471 const FileEntry *FE = FileMgr.getFile(FrameworkName.str(),
472 /*openFile=*/!SuggestedModule);
473 if (!FE) {
474 // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"
475 const char *Private = "Private";
476 FrameworkName.insert(FrameworkName.begin()+OrigSize, Private,
477 Private+strlen(Private));
Craig Topperd2d442c2014-05-17 23:10:59 +0000478 if (SearchPath)
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000479 SearchPath->insert(SearchPath->begin()+OrigSize, Private,
480 Private+strlen(Private));
481
482 FE = FileMgr.getFile(FrameworkName.str(), /*openFile=*/!SuggestedModule);
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000483 }
Mike Stump11289f42009-09-09 15:08:12 +0000484
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000485 // If we found the header and are allowed to suggest a module, do so now.
486 if (FE && SuggestedModule) {
487 // Find the framework in which this header occurs.
Ben Langmuiref914b82014-05-15 16:20:33 +0000488 StringRef FrameworkPath = FE->getDir()->getName();
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000489 bool FoundFramework = false;
490 do {
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000491 // Determine whether this directory exists.
492 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkPath);
493 if (!Dir)
494 break;
495
496 // If this is a framework directory, then we're a subframework of this
497 // framework.
498 if (llvm::sys::path::extension(FrameworkPath) == ".framework") {
499 FoundFramework = true;
500 break;
501 }
Ben Langmuiref914b82014-05-15 16:20:33 +0000502
503 // Get the parent directory name.
504 FrameworkPath = llvm::sys::path::parent_path(FrameworkPath);
505 if (FrameworkPath.empty())
506 break;
Douglas Gregor4ddf2222013-01-10 01:43:00 +0000507 } while (true);
508
509 if (FoundFramework) {
510 // Find the top-level framework based on this framework.
511 SmallVector<std::string, 4> SubmodulePath;
512 const DirectoryEntry *TopFrameworkDir
513 = ::getTopFrameworkDir(FileMgr, FrameworkPath, SubmodulePath);
514
515 // Determine the name of the top-level framework.
516 StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
517
518 // Load this framework module. If that succeeds, find the suggested module
519 // for this header, if any.
520 bool IsSystem = getDirCharacteristic() != SrcMgr::C_User;
521 if (HS.loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystem)) {
522 *SuggestedModule = HS.findModuleForHeader(FE);
523 }
524 } else {
525 *SuggestedModule = HS.findModuleForHeader(FE);
526 }
527 }
Douglas Gregor97eec242011-09-15 22:00:41 +0000528 return FE;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000529}
530
Douglas Gregor89929282012-01-30 06:01:29 +0000531void HeaderSearch::setTarget(const TargetInfo &Target) {
532 ModMap.setTarget(Target);
533}
534
Chris Lattnerf62f7582007-12-17 07:52:39 +0000535
Chris Lattner712e3872007-12-17 08:13:48 +0000536//===----------------------------------------------------------------------===//
537// Header File Location.
538//===----------------------------------------------------------------------===//
539
Reid Klecknera97d4c02014-02-18 23:49:24 +0000540/// \brief Return true with a diagnostic if the file that MSVC would have found
541/// fails to match the one that Clang would have found with MSVC header search
542/// disabled.
543static bool checkMSVCHeaderSearch(DiagnosticsEngine &Diags,
544 const FileEntry *MSFE, const FileEntry *FE,
545 SourceLocation IncludeLoc) {
546 if (MSFE && FE != MSFE) {
547 Diags.Report(IncludeLoc, diag::ext_pp_include_search_ms) << MSFE->getName();
548 return true;
549 }
550 return false;
551}
Chris Lattner712e3872007-12-17 08:13:48 +0000552
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000553static const char *copyString(StringRef Str, llvm::BumpPtrAllocator &Alloc) {
554 assert(!Str.empty());
555 char *CopyStr = Alloc.Allocate<char>(Str.size()+1);
556 std::copy(Str.begin(), Str.end(), CopyStr);
557 CopyStr[Str.size()] = '\0';
558 return CopyStr;
559}
560
James Dennettc07ab2c2012-06-20 00:56:32 +0000561/// LookupFile - Given a "foo" or \<foo> reference, look up the indicated file,
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000562/// return null on failure. isAngled indicates whether the file reference is
Will Wilson0fafd342013-12-27 19:46:16 +0000563/// for system \#include's or not (i.e. using <> instead of ""). Includers, if
564/// non-empty, indicates where the \#including file(s) are, in case a relative
565/// search is needed. Microsoft mode will pass all \#including files.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000566const FileEntry *HeaderSearch::LookupFile(
Will Wilson0fafd342013-12-27 19:46:16 +0000567 StringRef Filename, SourceLocation IncludeLoc, bool isAngled,
568 const DirectoryLookup *FromDir, const DirectoryLookup *&CurDir,
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000569 ArrayRef<std::pair<const FileEntry *, const DirectoryEntry *>> Includers,
570 SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
Will Wilson0fafd342013-12-27 19:46:16 +0000571 ModuleMap::KnownHeader *SuggestedModule, bool SkipCache) {
Douglas Gregor97eec242011-09-15 22:00:41 +0000572 if (SuggestedModule)
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000573 *SuggestedModule = ModuleMap::KnownHeader();
Douglas Gregor97eec242011-09-15 22:00:41 +0000574
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000575 // If 'Filename' is absolute, check to see if it exists and no searching.
Michael J. Spencerf28df4c2010-12-17 21:22:22 +0000576 if (llvm::sys::path::is_absolute(Filename)) {
Craig Topperd2d442c2014-05-17 23:10:59 +0000577 CurDir = nullptr;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000578
579 // If this was an #include_next "/absolute/file", fail.
Craig Topperd2d442c2014-05-17 23:10:59 +0000580 if (FromDir) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000581
Craig Topperd2d442c2014-05-17 23:10:59 +0000582 if (SearchPath)
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000583 SearchPath->clear();
Craig Topperd2d442c2014-05-17 23:10:59 +0000584 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000585 RelativePath->clear();
586 RelativePath->append(Filename.begin(), Filename.end());
587 }
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000588 // Otherwise, just return the file.
Argyrios Kyrtzidisd6278e32011-03-16 19:17:25 +0000589 return FileMgr.getFile(Filename, /*openFile=*/true);
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000590 }
Mike Stump11289f42009-09-09 15:08:12 +0000591
Reid Klecknera97d4c02014-02-18 23:49:24 +0000592 // This is the header that MSVC's header search would have found.
Craig Topperd2d442c2014-05-17 23:10:59 +0000593 const FileEntry *MSFE = nullptr;
Richard Smith8c71eba2014-03-05 20:51:45 +0000594 ModuleMap::KnownHeader MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000595
Douglas Gregor9f93e382011-07-28 04:45:53 +0000596 // Unless disabled, check to see if the file is in the #includer's
Will Wilson0fafd342013-12-27 19:46:16 +0000597 // directory. This cannot be based on CurDir, because each includer could be
598 // a #include of a subdirectory (#include "foo/bar.h") and a subsequent
599 // include of "baz.h" should resolve to "whatever/foo/baz.h".
Chris Lattnerf62f7582007-12-17 07:52:39 +0000600 // This search is not done for <> headers.
Will Wilson0fafd342013-12-27 19:46:16 +0000601 if (!Includers.empty() && !isAngled && !NoCurDirSearch) {
NAKAMURA Takumi9cb62642013-12-10 02:36:28 +0000602 SmallString<1024> TmpDir;
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000603 bool First = true;
604 for (const auto &IncluderAndDir : Includers) {
605 const FileEntry *Includer = IncluderAndDir.first;
606
Will Wilson0fafd342013-12-27 19:46:16 +0000607 // Concatenate the requested file onto the directory.
608 // FIXME: Portability. Filename concatenation should be in sys::Path.
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000609 TmpDir = IncluderAndDir.second->getName();
Will Wilson0fafd342013-12-27 19:46:16 +0000610 TmpDir.push_back('/');
611 TmpDir.append(Filename.begin(), Filename.end());
Richard Smith8c71eba2014-03-05 20:51:45 +0000612
Richard Smith6f548ec2014-03-06 18:08:08 +0000613 // FIXME: We don't cache the result of getFileInfo across the call to
614 // getFileAndSuggestModule, because it's a reference to an element of
615 // a container that could be reallocated across this call.
Richard Smith3c1a41a2014-12-02 00:08:08 +0000616 //
617 // FIXME: If we have no includer, that means we're processing a #include
618 // from a module build. We should treat this as a system header if we're
619 // building a [system] module.
Richard Smith6f548ec2014-03-06 18:08:08 +0000620 bool IncluderIsSystemHeader =
Richard Smith3c1a41a2014-12-02 00:08:08 +0000621 Includer && getFileInfo(Includer).DirInfo != SrcMgr::C_User;
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000622 if (const FileEntry *FE = getFileAndSuggestModule(
623 *this, TmpDir.str(), IncluderAndDir.second,
624 IncluderIsSystemHeader, SuggestedModule)) {
Richard Smith3c1a41a2014-12-02 00:08:08 +0000625 if (!Includer) {
626 assert(First && "only first includer can have no file");
627 return FE;
628 }
629
Will Wilson0fafd342013-12-27 19:46:16 +0000630 // Leave CurDir unset.
631 // This file is a system header or C++ unfriendly if the old file is.
632 //
633 // Note that we only use one of FromHFI/ToHFI at once, due to potential
634 // reallocation of the underlying vector potentially making the first
635 // reference binding dangling.
Richard Smith6f548ec2014-03-06 18:08:08 +0000636 HeaderFileInfo &FromHFI = getFileInfo(Includer);
Will Wilson0fafd342013-12-27 19:46:16 +0000637 unsigned DirInfo = FromHFI.DirInfo;
638 bool IndexHeaderMapHeader = FromHFI.IndexHeaderMapHeader;
639 StringRef Framework = FromHFI.Framework;
Douglas Gregor03b5ebe2012-08-13 15:47:39 +0000640
Will Wilson0fafd342013-12-27 19:46:16 +0000641 HeaderFileInfo &ToHFI = getFileInfo(FE);
642 ToHFI.DirInfo = DirInfo;
643 ToHFI.IndexHeaderMapHeader = IndexHeaderMapHeader;
644 ToHFI.Framework = Framework;
Douglas Gregor03b5ebe2012-08-13 15:47:39 +0000645
Craig Topperd2d442c2014-05-17 23:10:59 +0000646 if (SearchPath) {
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000647 StringRef SearchPathRef(IncluderAndDir.second->getName());
Will Wilson0fafd342013-12-27 19:46:16 +0000648 SearchPath->clear();
649 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
650 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000651 if (RelativePath) {
Will Wilson0fafd342013-12-27 19:46:16 +0000652 RelativePath->clear();
653 RelativePath->append(Filename.begin(), Filename.end());
654 }
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000655 if (First)
Reid Klecknera97d4c02014-02-18 23:49:24 +0000656 return FE;
657
658 // Otherwise, we found the path via MSVC header search rules. If
659 // -Wmsvc-include is enabled, we have to keep searching to see if we
660 // would've found this header in -I or -isystem directories.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +0000661 if (Diags.isIgnored(diag::ext_pp_include_search_ms, IncludeLoc)) {
Reid Klecknera97d4c02014-02-18 23:49:24 +0000662 return FE;
663 } else {
664 MSFE = FE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000665 if (SuggestedModule) {
666 MSSuggestedModule = *SuggestedModule;
667 *SuggestedModule = ModuleMap::KnownHeader();
668 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000669 break;
670 }
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000671 }
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000672 First = false;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000673 }
674 }
Mike Stump11289f42009-09-09 15:08:12 +0000675
Craig Topperd2d442c2014-05-17 23:10:59 +0000676 CurDir = nullptr;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000677
678 // If this is a system #include, ignore the user #include locs.
Nico Weber3b1d1212011-05-24 04:31:14 +0000679 unsigned i = isAngled ? AngledDirIdx : 0;
Mike Stump11289f42009-09-09 15:08:12 +0000680
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000681 // If this is a #include_next request, start searching after the directory the
682 // file was found in.
683 if (FromDir)
684 i = FromDir-&SearchDirs[0];
Mike Stump11289f42009-09-09 15:08:12 +0000685
Chris Lattnerd4275422007-07-22 07:28:00 +0000686 // Cache all of the lookups performed by this method. Many headers are
687 // multiply included, and the "pragma once" optimization prevents them from
688 // being relex/pp'd, but they would still have to search through a
689 // (potentially huge) series of SearchDirs to find it.
David Blaikie13156b62014-11-19 03:06:06 +0000690 LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename];
Chris Lattnerd4275422007-07-22 07:28:00 +0000691
692 // If the entry has been previously looked up, the first value will be
693 // non-zero. If the value is equal to i (the start point of our search), then
694 // this is a matching hit.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000695 if (!SkipCache && CacheLookup.StartIdx == i+1) {
Chris Lattnerd4275422007-07-22 07:28:00 +0000696 // Skip querying potentially lots of directories for this lookup.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000697 i = CacheLookup.HitIdx;
698 if (CacheLookup.MappedName)
699 Filename = CacheLookup.MappedName;
Chris Lattnerd4275422007-07-22 07:28:00 +0000700 } else {
701 // Otherwise, this is the first query, or the previous query didn't match
702 // our search start. We will fill in our found location below, so prime the
703 // start point value.
Argyrios Kyrtzidis7bd78a92014-03-29 03:22:54 +0000704 CacheLookup.reset(/*StartIdx=*/i+1);
Chris Lattnerd4275422007-07-22 07:28:00 +0000705 }
Mike Stump11289f42009-09-09 15:08:12 +0000706
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000707 SmallString<64> MappedName;
708
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000709 // Check each directory in sequence to see if it contains this file.
710 for (; i != SearchDirs.size(); ++i) {
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000711 bool InUserSpecifiedSystemFramework = false;
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000712 bool HasBeenMapped = false;
Mike Stump11289f42009-09-09 15:08:12 +0000713 const FileEntry *FE =
Douglas Gregor97eec242011-09-15 22:00:41 +0000714 SearchDirs[i].LookupFile(Filename, *this, SearchPath, RelativePath,
Argyrios Kyrtzidis75fa9ed2014-02-14 14:58:28 +0000715 SuggestedModule, InUserSpecifiedSystemFramework,
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000716 HasBeenMapped, MappedName);
717 if (HasBeenMapped) {
718 CacheLookup.MappedName =
719 copyString(Filename, LookupFileCache.getAllocator());
720 }
Chris Lattner712e3872007-12-17 08:13:48 +0000721 if (!FE) continue;
Mike Stump11289f42009-09-09 15:08:12 +0000722
Chris Lattner712e3872007-12-17 08:13:48 +0000723 CurDir = &SearchDirs[i];
Mike Stump11289f42009-09-09 15:08:12 +0000724
Chris Lattner712e3872007-12-17 08:13:48 +0000725 // This file is a system header or C++ unfriendly if the dir is.
Douglas Gregor9f93e382011-07-28 04:45:53 +0000726 HeaderFileInfo &HFI = getFileInfo(FE);
727 HFI.DirInfo = CurDir->getDirCharacteristic();
Mike Stump11289f42009-09-09 15:08:12 +0000728
Daniel Dunbar3c9bc4d2012-04-05 17:10:06 +0000729 // If the directory characteristic is User but this framework was
730 // user-specified to be treated as a system framework, promote the
731 // characteristic.
732 if (HFI.DirInfo == SrcMgr::C_User && InUserSpecifiedSystemFramework)
733 HFI.DirInfo = SrcMgr::C_System;
734
Richard Smith8acadcb2012-06-13 20:27:03 +0000735 // If the filename matches a known system header prefix, override
736 // whether the file is a system header.
Richard Trieu871f5f32012-06-13 20:52:36 +0000737 for (unsigned j = SystemHeaderPrefixes.size(); j; --j) {
738 if (Filename.startswith(SystemHeaderPrefixes[j-1].first)) {
739 HFI.DirInfo = SystemHeaderPrefixes[j-1].second ? SrcMgr::C_System
Richard Smith8acadcb2012-06-13 20:27:03 +0000740 : SrcMgr::C_User;
741 break;
742 }
743 }
744
Douglas Gregor9f93e382011-07-28 04:45:53 +0000745 // If this file is found in a header map and uses the framework style of
746 // includes, then this header is part of a framework we're building.
747 if (CurDir->isIndexHeaderMap()) {
748 size_t SlashPos = Filename.find('/');
749 if (SlashPos != StringRef::npos) {
750 HFI.IndexHeaderMapHeader = 1;
751 HFI.Framework = getUniqueFrameworkName(StringRef(Filename.begin(),
752 SlashPos));
753 }
754 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000755
Richard Smith8c71eba2014-03-05 20:51:45 +0000756 if (checkMSVCHeaderSearch(Diags, MSFE, FE, IncludeLoc)) {
757 if (SuggestedModule)
758 *SuggestedModule = MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000759 return MSFE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000760 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000761
Chris Lattner712e3872007-12-17 08:13:48 +0000762 // Remember this location for the next lookup we do.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000763 CacheLookup.HitIdx = i;
Chris Lattner712e3872007-12-17 08:13:48 +0000764 return FE;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000765 }
Mike Stump11289f42009-09-09 15:08:12 +0000766
Douglas Gregord8575e12011-07-30 06:28:34 +0000767 // If we are including a file with a quoted include "foo.h" from inside
768 // a header in a framework that is currently being built, and we couldn't
769 // resolve "foo.h" any other way, change the include to <Foo/foo.h>, where
770 // "Foo" is the name of the framework in which the including header was found.
Richard Smith3c1a41a2014-12-02 00:08:08 +0000771 if (!Includers.empty() && Includers.front().first && !isAngled &&
Will Wilson0fafd342013-12-27 19:46:16 +0000772 Filename.find('/') == StringRef::npos) {
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000773 HeaderFileInfo &IncludingHFI = getFileInfo(Includers.front().first);
Douglas Gregord8575e12011-07-30 06:28:34 +0000774 if (IncludingHFI.IndexHeaderMapHeader) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000775 SmallString<128> ScratchFilename;
Douglas Gregord8575e12011-07-30 06:28:34 +0000776 ScratchFilename += IncludingHFI.Framework;
777 ScratchFilename += '/';
778 ScratchFilename += Filename;
Will Wilson0fafd342013-12-27 19:46:16 +0000779
Reid Klecknera97d4c02014-02-18 23:49:24 +0000780 const FileEntry *FE = LookupFile(
Will Wilson0fafd342013-12-27 19:46:16 +0000781 ScratchFilename, IncludeLoc, /*isAngled=*/true, FromDir, CurDir,
782 Includers.front(), SearchPath, RelativePath, SuggestedModule);
Reid Klecknera97d4c02014-02-18 23:49:24 +0000783
Richard Smith8c71eba2014-03-05 20:51:45 +0000784 if (checkMSVCHeaderSearch(Diags, MSFE, FE, IncludeLoc)) {
785 if (SuggestedModule)
786 *SuggestedModule = MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000787 return MSFE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000788 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000789
David Blaikie3c8c46e2014-11-19 05:48:40 +0000790 LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename];
David Blaikie13156b62014-11-19 03:06:06 +0000791 CacheLookup.HitIdx = LookupFileCache[ScratchFilename].HitIdx;
Richard Smith8c71eba2014-03-05 20:51:45 +0000792 // FIXME: SuggestedModule.
Reid Klecknera97d4c02014-02-18 23:49:24 +0000793 return FE;
Douglas Gregord8575e12011-07-30 06:28:34 +0000794 }
795 }
796
Craig Topperd2d442c2014-05-17 23:10:59 +0000797 if (checkMSVCHeaderSearch(Diags, MSFE, nullptr, IncludeLoc)) {
Richard Smith8c71eba2014-03-05 20:51:45 +0000798 if (SuggestedModule)
799 *SuggestedModule = MSSuggestedModule;
Reid Klecknera97d4c02014-02-18 23:49:24 +0000800 return MSFE;
Richard Smith8c71eba2014-03-05 20:51:45 +0000801 }
Reid Klecknera97d4c02014-02-18 23:49:24 +0000802
Chris Lattnerd4275422007-07-22 07:28:00 +0000803 // Otherwise, didn't find it. Remember we didn't find this.
Argyrios Kyrtzidis34fad422014-03-11 06:21:28 +0000804 CacheLookup.HitIdx = SearchDirs.size();
Craig Topperd2d442c2014-05-17 23:10:59 +0000805 return nullptr;
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000806}
807
Chris Lattner63dd32b2006-10-20 04:42:40 +0000808/// LookupSubframeworkHeader - Look up a subframework for the specified
James Dennettc07ab2c2012-06-20 00:56:32 +0000809/// \#include file. For example, if \#include'ing <HIToolbox/HIToolbox.h> from
Chris Lattner63dd32b2006-10-20 04:42:40 +0000810/// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
811/// is a subframework within Carbon.framework. If so, return the FileEntry
812/// for the designated file, otherwise return null.
813const FileEntry *HeaderSearch::
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000814LookupSubframeworkHeader(StringRef Filename,
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000815 const FileEntry *ContextFileEnt,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000816 SmallVectorImpl<char> *SearchPath,
Douglas Gregorf5f94522013-02-08 00:10:48 +0000817 SmallVectorImpl<char> *RelativePath,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000818 ModuleMap::KnownHeader *SuggestedModule) {
Chris Lattner12261882008-02-01 05:34:02 +0000819 assert(ContextFileEnt && "No context file?");
Mike Stump11289f42009-09-09 15:08:12 +0000820
Chris Lattner63dd32b2006-10-20 04:42:40 +0000821 // Framework names must have a '/' in the filename. Find it.
Douglas Gregor5ca04bd2011-12-09 16:48:01 +0000822 // FIXME: Should we permit '\' on Windows?
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000823 size_t SlashPos = Filename.find('/');
Craig Topperd2d442c2014-05-17 23:10:59 +0000824 if (SlashPos == StringRef::npos) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000825
Chris Lattner63dd32b2006-10-20 04:42:40 +0000826 // Look up the base framework name of the ContextFileEnt.
Chris Lattner48043482006-10-27 05:12:36 +0000827 const char *ContextName = ContextFileEnt->getName();
Mike Stump11289f42009-09-09 15:08:12 +0000828
Chris Lattner63dd32b2006-10-20 04:42:40 +0000829 // If the context info wasn't a framework, couldn't be a subframework.
Douglas Gregor5ca04bd2011-12-09 16:48:01 +0000830 const unsigned DotFrameworkLen = 10;
831 const char *FrameworkPos = strstr(ContextName, ".framework");
Craig Topperd2d442c2014-05-17 23:10:59 +0000832 if (FrameworkPos == nullptr ||
Douglas Gregor5ca04bd2011-12-09 16:48:01 +0000833 (FrameworkPos[DotFrameworkLen] != '/' &&
834 FrameworkPos[DotFrameworkLen] != '\\'))
Craig Topperd2d442c2014-05-17 23:10:59 +0000835 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000836
Daniel Dunbar17138612012-04-05 17:09:40 +0000837 SmallString<1024> FrameworkName(ContextName, FrameworkPos+DotFrameworkLen+1);
Chris Lattner5ed76da2006-10-22 07:24:13 +0000838
Chris Lattner63dd32b2006-10-20 04:42:40 +0000839 // Append Frameworks/HIToolbox.framework/
840 FrameworkName += "Frameworks/";
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000841 FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos);
Chris Lattner63dd32b2006-10-20 04:42:40 +0000842 FrameworkName += ".framework/";
Chris Lattner577377e2006-10-20 04:55:45 +0000843
David Blaikie13156b62014-11-19 03:06:06 +0000844 auto &CacheLookup =
845 *FrameworkMap.insert(std::make_pair(Filename.substr(0, SlashPos),
846 FrameworkCacheEntry())).first;
Mike Stump11289f42009-09-09 15:08:12 +0000847
Chris Lattner5ed76da2006-10-22 07:24:13 +0000848 // Some other location?
David Blaikie13156b62014-11-19 03:06:06 +0000849 if (CacheLookup.second.Directory &&
850 CacheLookup.first().size() == FrameworkName.size() &&
851 memcmp(CacheLookup.first().data(), &FrameworkName[0],
852 CacheLookup.first().size()) != 0)
Craig Topperd2d442c2014-05-17 23:10:59 +0000853 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000854
Chris Lattner5ed76da2006-10-22 07:24:13 +0000855 // Cache subframework.
David Blaikie13156b62014-11-19 03:06:06 +0000856 if (!CacheLookup.second.Directory) {
Chris Lattner5ed76da2006-10-22 07:24:13 +0000857 ++NumSubFrameworkLookups;
Mike Stump11289f42009-09-09 15:08:12 +0000858
Chris Lattner5ed76da2006-10-22 07:24:13 +0000859 // If the framework dir doesn't exist, we fail.
Chris Lattner5159f612010-11-23 08:35:12 +0000860 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName.str());
Craig Topperd2d442c2014-05-17 23:10:59 +0000861 if (!Dir) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000862
Chris Lattner5ed76da2006-10-22 07:24:13 +0000863 // Otherwise, if it does, remember that this is the right direntry for this
864 // framework.
David Blaikie13156b62014-11-19 03:06:06 +0000865 CacheLookup.second.Directory = Dir;
Chris Lattner5ed76da2006-10-22 07:24:13 +0000866 }
Mike Stump11289f42009-09-09 15:08:12 +0000867
Craig Topperd2d442c2014-05-17 23:10:59 +0000868 const FileEntry *FE = nullptr;
Chris Lattner577377e2006-10-20 04:55:45 +0000869
Craig Topperd2d442c2014-05-17 23:10:59 +0000870 if (RelativePath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000871 RelativePath->clear();
872 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
873 }
874
Chris Lattner63dd32b2006-10-20 04:42:40 +0000875 // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000876 SmallString<1024> HeadersFilename(FrameworkName);
Chris Lattner43fd42e2006-10-30 03:40:58 +0000877 HeadersFilename += "Headers/";
Craig Topperd2d442c2014-05-17 23:10:59 +0000878 if (SearchPath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000879 SearchPath->clear();
880 // Without trailing '/'.
881 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
882 }
883
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000884 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
Argyrios Kyrtzidisd6278e32011-03-16 19:17:25 +0000885 if (!(FE = FileMgr.getFile(HeadersFilename.str(), /*openFile=*/true))) {
Mike Stump11289f42009-09-09 15:08:12 +0000886
Chris Lattner63dd32b2006-10-20 04:42:40 +0000887 // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
Chris Lattner43fd42e2006-10-30 03:40:58 +0000888 HeadersFilename = FrameworkName;
889 HeadersFilename += "PrivateHeaders/";
Craig Topperd2d442c2014-05-17 23:10:59 +0000890 if (SearchPath) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000891 SearchPath->clear();
892 // Without trailing '/'.
893 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
894 }
895
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000896 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
Argyrios Kyrtzidisd6278e32011-03-16 19:17:25 +0000897 if (!(FE = FileMgr.getFile(HeadersFilename.str(), /*openFile=*/true)))
Craig Topperd2d442c2014-05-17 23:10:59 +0000898 return nullptr;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000899 }
Mike Stump11289f42009-09-09 15:08:12 +0000900
Chris Lattner577377e2006-10-20 04:55:45 +0000901 // This file is a system header or C++ unfriendly if the old file is.
Ted Kremenek72be0682008-02-24 03:55:14 +0000902 //
Chris Lattnerf5c619f2008-02-25 21:38:21 +0000903 // Note that the temporary 'DirInfo' is required here, as either call to
904 // getFileInfo could resize the vector and we don't want to rely on order
905 // of evaluation.
906 unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo;
907 getFileInfo(FE).DirInfo = DirInfo;
Douglas Gregorf5f94522013-02-08 00:10:48 +0000908
909 // If we're supposed to suggest a module, look for one now.
910 if (SuggestedModule) {
911 // Find the top-level framework based on this framework.
912 FrameworkName.pop_back(); // remove the trailing '/'
913 SmallVector<std::string, 4> SubmodulePath;
914 const DirectoryEntry *TopFrameworkDir
915 = ::getTopFrameworkDir(FileMgr, FrameworkName, SubmodulePath);
916
917 // Determine the name of the top-level framework.
918 StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
919
920 // Load this framework module. If that succeeds, find the suggested module
921 // for this header, if any.
922 bool IsSystem = false;
923 if (loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystem)) {
924 *SuggestedModule = findModuleForHeader(FE);
925 }
926 }
927
Chris Lattner577377e2006-10-20 04:55:45 +0000928 return FE;
Chris Lattner63dd32b2006-10-20 04:42:40 +0000929}
930
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000931//===----------------------------------------------------------------------===//
932// File Info Management.
933//===----------------------------------------------------------------------===//
934
Douglas Gregor5d1bee22011-09-17 05:35:18 +0000935/// \brief Merge the header file info provided by \p OtherHFI into the current
936/// header file info (\p HFI)
937static void mergeHeaderFileInfo(HeaderFileInfo &HFI,
938 const HeaderFileInfo &OtherHFI) {
939 HFI.isImport |= OtherHFI.isImport;
940 HFI.isPragmaOnce |= OtherHFI.isPragmaOnce;
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +0000941 HFI.isModuleHeader |= OtherHFI.isModuleHeader;
Douglas Gregor5d1bee22011-09-17 05:35:18 +0000942 HFI.NumIncludes += OtherHFI.NumIncludes;
943
944 if (!HFI.ControllingMacro && !HFI.ControllingMacroID) {
945 HFI.ControllingMacro = OtherHFI.ControllingMacro;
946 HFI.ControllingMacroID = OtherHFI.ControllingMacroID;
947 }
948
949 if (OtherHFI.External) {
950 HFI.DirInfo = OtherHFI.DirInfo;
951 HFI.External = OtherHFI.External;
952 HFI.IndexHeaderMapHeader = OtherHFI.IndexHeaderMapHeader;
953 }
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000954
Douglas Gregor5d1bee22011-09-17 05:35:18 +0000955 if (HFI.Framework.empty())
956 HFI.Framework = OtherHFI.Framework;
957
958 HFI.Resolved = true;
959}
960
Steve Naroff3fa455a2009-04-24 20:03:17 +0000961/// getFileInfo - Return the HeaderFileInfo structure for the specified
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000962/// FileEntry.
Steve Naroff3fa455a2009-04-24 20:03:17 +0000963HeaderFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) {
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000964 if (FE->getUID() >= FileInfo.size())
965 FileInfo.resize(FE->getUID()+1);
Douglas Gregor09b69892011-02-10 17:09:37 +0000966
967 HeaderFileInfo &HFI = FileInfo[FE->getUID()];
Douglas Gregor5d1bee22011-09-17 05:35:18 +0000968 if (ExternalSource && !HFI.Resolved)
969 mergeHeaderFileInfo(HFI, ExternalSource->GetHeaderFileInfo(FE));
Ben Langmuird285c502014-03-13 16:46:36 +0000970 HFI.IsValid = 1;
Douglas Gregor09b69892011-02-10 17:09:37 +0000971 return HFI;
Mike Stump11289f42009-09-09 15:08:12 +0000972}
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000973
Ben Langmuird285c502014-03-13 16:46:36 +0000974bool HeaderSearch::tryGetFileInfo(const FileEntry *FE, HeaderFileInfo &Result) const {
975 if (FE->getUID() >= FileInfo.size())
976 return false;
977 const HeaderFileInfo &HFI = FileInfo[FE->getUID()];
978 if (HFI.IsValid) {
979 Result = HFI;
980 return true;
981 }
982 return false;
983}
984
Douglas Gregor37aa4932011-05-04 00:14:37 +0000985bool HeaderSearch::isFileMultipleIncludeGuarded(const FileEntry *File) {
986 // Check if we've ever seen this file as a header.
987 if (File->getUID() >= FileInfo.size())
988 return false;
989
990 // Resolve header file info from the external source, if needed.
991 HeaderFileInfo &HFI = FileInfo[File->getUID()];
Douglas Gregor5d1bee22011-09-17 05:35:18 +0000992 if (ExternalSource && !HFI.Resolved)
993 mergeHeaderFileInfo(HFI, ExternalSource->GetHeaderFileInfo(File));
Douglas Gregor37aa4932011-05-04 00:14:37 +0000994
Argyrios Kyrtzidis0d355df2012-12-10 20:08:37 +0000995 return HFI.isPragmaOnce || HFI.isImport ||
996 HFI.ControllingMacro || HFI.ControllingMacroID;
Douglas Gregor37aa4932011-05-04 00:14:37 +0000997}
998
Argyrios Kyrtzidis6f722b42013-05-08 23:46:46 +0000999void HeaderSearch::MarkFileModuleHeader(const FileEntry *FE,
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001000 ModuleMap::ModuleHeaderRole Role,
Argyrios Kyrtzidis6f722b42013-05-08 23:46:46 +00001001 bool isCompilingModuleHeader) {
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001002 if (FE->getUID() >= FileInfo.size())
1003 FileInfo.resize(FE->getUID()+1);
1004
1005 HeaderFileInfo &HFI = FileInfo[FE->getUID()];
1006 HFI.isModuleHeader = true;
Argyrios Kyrtzidis6f722b42013-05-08 23:46:46 +00001007 HFI.isCompilingModuleHeader = isCompilingModuleHeader;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001008 HFI.setHeaderRole(Role);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001009}
1010
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001011bool HeaderSearch::ShouldEnterIncludeFile(const FileEntry *File, bool isImport){
1012 ++NumIncluded; // Count # of attempted #includes.
1013
1014 // Get information about this file.
Steve Naroff3fa455a2009-04-24 20:03:17 +00001015 HeaderFileInfo &FileInfo = getFileInfo(File);
Mike Stump11289f42009-09-09 15:08:12 +00001016
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001017 // If this is a #import directive, check that we have not already imported
1018 // this header.
1019 if (isImport) {
1020 // If this has already been imported, don't import it again.
1021 FileInfo.isImport = true;
Mike Stump11289f42009-09-09 15:08:12 +00001022
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001023 // Has this already been #import'ed or #include'd?
1024 if (FileInfo.NumIncludes) return false;
1025 } else {
1026 // Otherwise, if this is a #include of a file that was previously #import'd
1027 // or if this is the second #include of a #pragma once file, ignore it.
1028 if (FileInfo.isImport)
1029 return false;
1030 }
Mike Stump11289f42009-09-09 15:08:12 +00001031
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001032 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
1033 // if the macro that guards it is defined, we know the #include has no effect.
Mike Stump11289f42009-09-09 15:08:12 +00001034 if (const IdentifierInfo *ControllingMacro
Douglas Gregor99734e72009-04-25 23:30:02 +00001035 = FileInfo.getControllingMacro(ExternalLookup))
1036 if (ControllingMacro->hasMacroDefinition()) {
1037 ++NumMultiIncludeFileOptzn;
1038 return false;
1039 }
Mike Stump11289f42009-09-09 15:08:12 +00001040
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001041 // Increment the number of times this file has been included.
1042 ++FileInfo.NumIncludes;
Mike Stump11289f42009-09-09 15:08:12 +00001043
Chris Lattner59a9ebd2006-10-18 05:34:33 +00001044 return true;
1045}
1046
Ted Kremenekfbcce6f2011-07-26 23:46:11 +00001047size_t HeaderSearch::getTotalMemory() const {
1048 return SearchDirs.capacity()
Ted Kremenekae63d102011-07-27 18:41:18 +00001049 + llvm::capacity_in_bytes(FileInfo)
1050 + llvm::capacity_in_bytes(HeaderMaps)
Ted Kremenekfbcce6f2011-07-26 23:46:11 +00001051 + LookupFileCache.getAllocator().getTotalMemory()
1052 + FrameworkMap.getAllocator().getTotalMemory();
1053}
Douglas Gregor9f93e382011-07-28 04:45:53 +00001054
1055StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) {
David Blaikie13156b62014-11-19 03:06:06 +00001056 return FrameworkNames.insert(Framework).first->first();
Douglas Gregor9f93e382011-07-28 04:45:53 +00001057}
Douglas Gregor718292f2011-11-11 19:10:28 +00001058
1059bool HeaderSearch::hasModuleMap(StringRef FileName,
Douglas Gregor963c5532013-06-21 16:28:10 +00001060 const DirectoryEntry *Root,
1061 bool IsSystem) {
Daniel Jasper21a0f552014-11-25 09:45:48 +00001062 if (!enabledModules() || !LangOpts.ModulesImplicitMaps)
Argyrios Kyrtzidis9955dbc2013-12-12 16:08:33 +00001063 return false;
1064
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001065 SmallVector<const DirectoryEntry *, 2> FixUpDirectories;
Douglas Gregor718292f2011-11-11 19:10:28 +00001066
1067 StringRef DirName = FileName;
1068 do {
1069 // Get the parent directory name.
1070 DirName = llvm::sys::path::parent_path(DirName);
1071 if (DirName.empty())
1072 return false;
Daniel Jasperca9f7382013-09-24 09:27:13 +00001073
Douglas Gregor718292f2011-11-11 19:10:28 +00001074 // Determine whether this directory exists.
1075 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
1076 if (!Dir)
1077 return false;
Daniel Jasperca9f7382013-09-24 09:27:13 +00001078
Ben Langmuir984e1df2014-03-19 20:23:34 +00001079 // Try to load the module map file in this directory.
Richard Smith3c1a41a2014-12-02 00:08:08 +00001080 switch (loadModuleMapFile(Dir, IsSystem,
1081 llvm::sys::path::extension(Dir->getName()) ==
1082 ".framework")) {
Douglas Gregor80b69042011-11-12 00:22:19 +00001083 case LMM_NewlyLoaded:
1084 case LMM_AlreadyLoaded:
Daniel Jasperca9f7382013-09-24 09:27:13 +00001085 // Success. All of the directories we stepped through inherit this module
1086 // map file.
1087 for (unsigned I = 0, N = FixUpDirectories.size(); I != N; ++I)
1088 DirectoryHasModuleMap[FixUpDirectories[I]] = true;
1089 return true;
Daniel Jasper97da9172013-10-22 08:09:47 +00001090
1091 case LMM_NoDirectory:
1092 case LMM_InvalidModuleMap:
1093 break;
Daniel Jasperca9f7382013-09-24 09:27:13 +00001094 }
1095
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001096 // If we hit the top of our search, we're done.
1097 if (Dir == Root)
1098 return false;
1099
Douglas Gregor718292f2011-11-11 19:10:28 +00001100 // Keep track of all of the directories we checked, so we can mark them as
1101 // having module maps if we eventually do find a module map.
1102 FixUpDirectories.push_back(Dir);
1103 } while (true);
Douglas Gregor718292f2011-11-11 19:10:28 +00001104}
1105
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001106ModuleMap::KnownHeader
1107HeaderSearch::findModuleForHeader(const FileEntry *File) const {
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001108 if (ExternalSource) {
1109 // Make sure the external source has handled header info about this file,
1110 // which includes whether the file is part of a module.
1111 (void)getFileInfo(File);
1112 }
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001113 return ModMap.findModuleForHeader(File);
Douglas Gregor718292f2011-11-11 19:10:28 +00001114}
1115
Richard Smith9acb99e32014-12-10 03:09:48 +00001116static const FileEntry *getPrivateModuleMap(const FileEntry *File,
Ben Langmuir984e1df2014-03-19 20:23:34 +00001117 FileManager &FileMgr) {
Richard Smith9acb99e32014-12-10 03:09:48 +00001118 StringRef Filename = llvm::sys::path::filename(File->getName());
1119 SmallString<128> PrivateFilename(File->getDir()->getName());
Ben Langmuir984e1df2014-03-19 20:23:34 +00001120 if (Filename == "module.map")
Douglas Gregor80306772011-12-07 21:25:07 +00001121 llvm::sys::path::append(PrivateFilename, "module_private.map");
Ben Langmuir984e1df2014-03-19 20:23:34 +00001122 else if (Filename == "module.modulemap")
1123 llvm::sys::path::append(PrivateFilename, "module.private.modulemap");
1124 else
1125 return nullptr;
1126 return FileMgr.getFile(PrivateFilename);
Douglas Gregor2b20cb82011-11-16 00:09:06 +00001127}
1128
Ben Langmuir984e1df2014-03-19 20:23:34 +00001129bool HeaderSearch::loadModuleMapFile(const FileEntry *File, bool IsSystem) {
Richard Smith9acb99e32014-12-10 03:09:48 +00001130 // Find the directory for the module. For frameworks, that may require going
1131 // up from the 'Modules' directory.
1132 const DirectoryEntry *Dir = nullptr;
1133 if (getHeaderSearchOpts().ModuleMapFileHomeIsCwd)
1134 Dir = FileMgr.getDirectory(".");
1135 else {
1136 Dir = File->getDir();
1137 StringRef DirName(Dir->getName());
1138 if (llvm::sys::path::filename(DirName) == "Modules") {
1139 DirName = llvm::sys::path::parent_path(DirName);
1140 if (DirName.endswith(".framework"))
1141 Dir = FileMgr.getDirectory(DirName);
1142 // FIXME: This assert can fail if there's a race between the above check
1143 // and the removal of the directory.
1144 assert(Dir && "parent must exist");
1145 }
1146 }
1147
1148 switch (loadModuleMapFileImpl(File, IsSystem, Dir)) {
Ben Langmuir984e1df2014-03-19 20:23:34 +00001149 case LMM_AlreadyLoaded:
1150 case LMM_NewlyLoaded:
1151 return false;
1152 case LMM_NoDirectory:
1153 case LMM_InvalidModuleMap:
1154 return true;
1155 }
Aaron Ballmand8de5b62014-03-20 14:22:33 +00001156 llvm_unreachable("Unknown load module map result");
Ben Langmuir984e1df2014-03-19 20:23:34 +00001157}
1158
1159HeaderSearch::LoadModuleMapResult
Richard Smith9acb99e32014-12-10 03:09:48 +00001160HeaderSearch::loadModuleMapFileImpl(const FileEntry *File, bool IsSystem,
1161 const DirectoryEntry *Dir) {
Ben Langmuir984e1df2014-03-19 20:23:34 +00001162 assert(File && "expected FileEntry");
1163
Richard Smith9887d792014-10-17 01:42:53 +00001164 // Check whether we've already loaded this module map, and mark it as being
1165 // loaded in case we recursively try to load it from itself.
1166 auto AddResult = LoadedModuleMaps.insert(std::make_pair(File, true));
1167 if (!AddResult.second)
1168 return AddResult.first->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001169
Richard Smith9acb99e32014-12-10 03:09:48 +00001170 if (ModMap.parseModuleMapFile(File, IsSystem, Dir)) {
Richard Smith9887d792014-10-17 01:42:53 +00001171 LoadedModuleMaps[File] = false;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001172 return LMM_InvalidModuleMap;
1173 }
1174
1175 // Try to load a corresponding private module map.
Richard Smith9acb99e32014-12-10 03:09:48 +00001176 if (const FileEntry *PMMFile = getPrivateModuleMap(File, FileMgr)) {
1177 if (ModMap.parseModuleMapFile(PMMFile, IsSystem, Dir)) {
Richard Smith9887d792014-10-17 01:42:53 +00001178 LoadedModuleMaps[File] = false;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001179 return LMM_InvalidModuleMap;
1180 }
1181 }
1182
1183 // This directory has a module map.
Ben Langmuir984e1df2014-03-19 20:23:34 +00001184 return LMM_NewlyLoaded;
1185}
1186
1187const FileEntry *
1188HeaderSearch::lookupModuleMapFile(const DirectoryEntry *Dir, bool IsFramework) {
Daniel Jasper21a0f552014-11-25 09:45:48 +00001189 if (!LangOpts.ModulesImplicitMaps)
1190 return nullptr;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001191 // For frameworks, the preferred spelling is Modules/module.modulemap, but
1192 // module.map at the framework root is also accepted.
1193 SmallString<128> ModuleMapFileName(Dir->getName());
1194 if (IsFramework)
1195 llvm::sys::path::append(ModuleMapFileName, "Modules");
1196 llvm::sys::path::append(ModuleMapFileName, "module.modulemap");
1197 if (const FileEntry *F = FileMgr.getFile(ModuleMapFileName))
1198 return F;
1199
1200 // Continue to allow module.map
1201 ModuleMapFileName = Dir->getName();
1202 llvm::sys::path::append(ModuleMapFileName, "module.map");
1203 return FileMgr.getFile(ModuleMapFileName);
1204}
1205
1206Module *HeaderSearch::loadFrameworkModule(StringRef Name,
Douglas Gregor279a6c32012-01-29 17:08:11 +00001207 const DirectoryEntry *Dir,
1208 bool IsSystem) {
Douglas Gregorde3ef502011-11-30 23:21:26 +00001209 if (Module *Module = ModMap.findModule(Name))
Douglas Gregor56c64012011-11-17 01:41:17 +00001210 return Module;
Daniel Jasper21a0f552014-11-25 09:45:48 +00001211
Douglas Gregor56c64012011-11-17 01:41:17 +00001212 // Try to load a module map file.
Ben Langmuir984e1df2014-03-19 20:23:34 +00001213 switch (loadModuleMapFile(Dir, IsSystem, /*IsFramework*/true)) {
Douglas Gregor56c64012011-11-17 01:41:17 +00001214 case LMM_InvalidModuleMap:
1215 break;
Daniel Jasper21a0f552014-11-25 09:45:48 +00001216
Douglas Gregor56c64012011-11-17 01:41:17 +00001217 case LMM_AlreadyLoaded:
1218 case LMM_NoDirectory:
Craig Topperd2d442c2014-05-17 23:10:59 +00001219 return nullptr;
1220
Douglas Gregor56c64012011-11-17 01:41:17 +00001221 case LMM_NewlyLoaded:
1222 return ModMap.findModule(Name);
1223 }
Douglas Gregor3a5999b2012-01-13 22:31:52 +00001224
Douglas Gregor9194a912012-11-06 19:39:40 +00001225
Ben Langmuirc3ea5652014-03-20 18:27:26 +00001226 // Try to infer a module map from the framework directory.
Daniel Jasper21a0f552014-11-25 09:45:48 +00001227 if (LangOpts.ModulesImplicitMaps)
1228 return ModMap.inferFrameworkModule(Name, Dir, IsSystem, /*Parent=*/nullptr);
1229
1230 return nullptr;
Douglas Gregor56c64012011-11-17 01:41:17 +00001231}
1232
Douglas Gregor2b20cb82011-11-16 00:09:06 +00001233
Douglas Gregor80b69042011-11-12 00:22:19 +00001234HeaderSearch::LoadModuleMapResult
Ben Langmuir984e1df2014-03-19 20:23:34 +00001235HeaderSearch::loadModuleMapFile(StringRef DirName, bool IsSystem,
1236 bool IsFramework) {
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001237 if (const DirectoryEntry *Dir = FileMgr.getDirectory(DirName))
Ben Langmuir984e1df2014-03-19 20:23:34 +00001238 return loadModuleMapFile(Dir, IsSystem, IsFramework);
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001239
Douglas Gregor80b69042011-11-12 00:22:19 +00001240 return LMM_NoDirectory;
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001241}
1242
Douglas Gregor80b69042011-11-12 00:22:19 +00001243HeaderSearch::LoadModuleMapResult
Ben Langmuir984e1df2014-03-19 20:23:34 +00001244HeaderSearch::loadModuleMapFile(const DirectoryEntry *Dir, bool IsSystem,
1245 bool IsFramework) {
1246 auto KnownDir = DirectoryHasModuleMap.find(Dir);
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001247 if (KnownDir != DirectoryHasModuleMap.end())
Richard Smith9887d792014-10-17 01:42:53 +00001248 return KnownDir->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
Douglas Gregore7ab3662011-12-07 02:23:45 +00001249
Ben Langmuir984e1df2014-03-19 20:23:34 +00001250 if (const FileEntry *ModuleMapFile = lookupModuleMapFile(Dir, IsFramework)) {
Richard Smith9acb99e32014-12-10 03:09:48 +00001251 LoadModuleMapResult Result =
1252 loadModuleMapFileImpl(ModuleMapFile, IsSystem, Dir);
Ben Langmuir984e1df2014-03-19 20:23:34 +00001253 // Add Dir explicitly in case ModuleMapFile is in a subdirectory.
1254 // E.g. Foo.framework/Modules/module.modulemap
1255 // ^Dir ^ModuleMapFile
1256 if (Result == LMM_NewlyLoaded)
1257 DirectoryHasModuleMap[Dir] = true;
Richard Smith9887d792014-10-17 01:42:53 +00001258 else if (Result == LMM_InvalidModuleMap)
1259 DirectoryHasModuleMap[Dir] = false;
Ben Langmuir984e1df2014-03-19 20:23:34 +00001260 return Result;
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001261 }
Douglas Gregor80b69042011-11-12 00:22:19 +00001262 return LMM_InvalidModuleMap;
Douglas Gregoraf28ec82011-11-12 00:05:07 +00001263}
Douglas Gregor718292f2011-11-11 19:10:28 +00001264
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001265void HeaderSearch::collectAllModules(SmallVectorImpl<Module *> &Modules) {
Douglas Gregor07f43572012-01-29 18:15:03 +00001266 Modules.clear();
Daniel Jasper21a0f552014-11-25 09:45:48 +00001267
1268 if (LangOpts.ModulesImplicitMaps) {
1269 // Load module maps for each of the header search directories.
1270 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
1271 bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
1272 if (SearchDirs[Idx].isFramework()) {
1273 std::error_code EC;
1274 SmallString<128> DirNative;
1275 llvm::sys::path::native(SearchDirs[Idx].getFrameworkDir()->getName(),
1276 DirNative);
1277
1278 // Search each of the ".framework" directories to load them as modules.
1279 for (llvm::sys::fs::directory_iterator Dir(DirNative.str(), EC), DirEnd;
1280 Dir != DirEnd && !EC; Dir.increment(EC)) {
1281 if (llvm::sys::path::extension(Dir->path()) != ".framework")
1282 continue;
1283
1284 const DirectoryEntry *FrameworkDir =
1285 FileMgr.getDirectory(Dir->path());
1286 if (!FrameworkDir)
1287 continue;
1288
1289 // Load this framework module.
1290 loadFrameworkModule(llvm::sys::path::stem(Dir->path()), FrameworkDir,
1291 IsSystem);
1292 }
1293 continue;
Douglas Gregor07f43572012-01-29 18:15:03 +00001294 }
Daniel Jasper21a0f552014-11-25 09:45:48 +00001295
1296 // FIXME: Deal with header maps.
1297 if (SearchDirs[Idx].isHeaderMap())
1298 continue;
1299
1300 // Try to load a module map file for the search directory.
1301 loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem,
1302 /*IsFramework*/ false);
1303
1304 // Try to load module map files for immediate subdirectories of this
1305 // search directory.
1306 loadSubdirectoryModuleMaps(SearchDirs[Idx]);
Douglas Gregor07f43572012-01-29 18:15:03 +00001307 }
Douglas Gregor07f43572012-01-29 18:15:03 +00001308 }
Daniel Jasper21a0f552014-11-25 09:45:48 +00001309
Douglas Gregor07f43572012-01-29 18:15:03 +00001310 // Populate the list of modules.
1311 for (ModuleMap::module_iterator M = ModMap.module_begin(),
1312 MEnd = ModMap.module_end();
1313 M != MEnd; ++M) {
1314 Modules.push_back(M->getValue());
1315 }
1316}
Douglas Gregor0339a642013-03-21 01:08:50 +00001317
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001318void HeaderSearch::loadTopLevelSystemModules() {
Daniel Jasper21a0f552014-11-25 09:45:48 +00001319 if (!LangOpts.ModulesImplicitMaps)
1320 return;
1321
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001322 // Load module maps for each of the header search directories.
1323 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
Douglas Gregor299787f2013-11-01 23:08:38 +00001324 // We only care about normal header directories.
1325 if (!SearchDirs[Idx].isNormalDir()) {
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001326 continue;
1327 }
1328
1329 // Try to load a module map file for the search directory.
Douglas Gregor963c5532013-06-21 16:28:10 +00001330 loadModuleMapFile(SearchDirs[Idx].getDir(),
Ben Langmuir984e1df2014-03-19 20:23:34 +00001331 SearchDirs[Idx].isSystemHeaderDirectory(),
1332 SearchDirs[Idx].isFramework());
Douglas Gregor64a1fa52013-05-10 22:52:27 +00001333 }
1334}
1335
Douglas Gregor0339a642013-03-21 01:08:50 +00001336void HeaderSearch::loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir) {
Daniel Jasper21a0f552014-11-25 09:45:48 +00001337 assert(LangOpts.ModulesImplicitMaps &&
1338 "Should not be loading subdirectory module maps");
1339
Douglas Gregor0339a642013-03-21 01:08:50 +00001340 if (SearchDir.haveSearchedAllModuleMaps())
1341 return;
Rafael Espindolac0809172014-06-12 14:02:15 +00001342
1343 std::error_code EC;
Douglas Gregor0339a642013-03-21 01:08:50 +00001344 SmallString<128> DirNative;
1345 llvm::sys::path::native(SearchDir.getDir()->getName(), DirNative);
1346 for (llvm::sys::fs::directory_iterator Dir(DirNative.str(), EC), DirEnd;
1347 Dir != DirEnd && !EC; Dir.increment(EC)) {
Ben Langmuir984e1df2014-03-19 20:23:34 +00001348 loadModuleMapFile(Dir->path(), SearchDir.isSystemHeaderDirectory(),
1349 SearchDir.isFramework());
Douglas Gregor0339a642013-03-21 01:08:50 +00001350 }
1351
1352 SearchDir.setSearchedAllModuleMaps(true);
1353}