blob: 14d44cc3da29e5984bbe2c0cec4096bd968d534a [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- HeaderSearch.cpp - Resolve Header File Locations ---===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the DirectoryLookup and HeaderSearch interfaces.
11//
12//===----------------------------------------------------------------------===//
13
Reid Spencer5f016e22007-07-11 17:01:13 +000014#include "clang/Lex/HeaderSearch.h"
Douglas Gregora30cfe52011-11-11 19:10:28 +000015#include "clang/Basic/Diagnostic.h"
Chris Lattnerc7229c32007-10-07 08:58:51 +000016#include "clang/Basic/FileManager.h"
17#include "clang/Basic/IdentifierTable.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000018#include "clang/Lex/HeaderMap.h"
19#include "clang/Lex/HeaderSearchOptions.h"
20#include "clang/Lex/Lexer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000021#include "llvm/ADT/SmallString.h"
Ted Kremenekeabea452011-07-27 18:41:18 +000022#include "llvm/Support/Capacity.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000023#include "llvm/Support/FileSystem.h"
24#include "llvm/Support/Path.h"
Chris Lattner3daed522009-03-02 22:20:04 +000025#include <cstdio>
Douglas Gregor3cc62772013-01-22 23:49:45 +000026#if defined(LLVM_ON_UNIX)
27#if defined(__linux__)
28#include <linux/limits.h>
29#endif
30#endif
Reid Spencer5f016e22007-07-11 17:01:13 +000031using namespace clang;
32
Douglas Gregor8c5a7602009-04-25 23:30:02 +000033const IdentifierInfo *
34HeaderFileInfo::getControllingMacro(ExternalIdentifierLookup *External) {
35 if (ControllingMacro)
36 return ControllingMacro;
37
38 if (!ControllingMacroID || !External)
39 return 0;
40
41 ControllingMacro = External->GetIdentifier(ControllingMacroID);
42 return ControllingMacro;
43}
44
Douglas Gregorcfbf1c72011-02-10 17:09:37 +000045ExternalHeaderFileInfoSource::~ExternalHeaderFileInfoSource() {}
46
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000047HeaderSearch::HeaderSearch(IntrusiveRefCntPtr<HeaderSearchOptions> HSOpts,
Douglas Gregorc042edd2012-10-24 16:19:39 +000048 FileManager &FM, DiagnosticsEngine &Diags,
Douglas Gregordc58aa72012-01-30 06:01:29 +000049 const LangOptions &LangOpts,
50 const TargetInfo *Target)
Douglas Gregorc042edd2012-10-24 16:19:39 +000051 : HSOpts(HSOpts), FileMgr(FM), FrameworkMap(64),
Douglas Gregordc58aa72012-01-30 06:01:29 +000052 ModMap(FileMgr, *Diags.getClient(), LangOpts, Target)
Douglas Gregor8e238062011-11-11 00:35:06 +000053{
Nico Weber74a5fd82011-05-24 04:31:14 +000054 AngledDirIdx = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000055 SystemDirIdx = 0;
56 NoCurDirSearch = false;
Mike Stump1eb44332009-09-09 15:08:12 +000057
Douglas Gregor8c5a7602009-04-25 23:30:02 +000058 ExternalLookup = 0;
Douglas Gregorcfbf1c72011-02-10 17:09:37 +000059 ExternalSource = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000060 NumIncluded = 0;
61 NumMultiIncludeFileOptzn = 0;
62 NumFrameworkLookups = NumSubFrameworkLookups = 0;
63}
64
Chris Lattner822da612007-12-17 06:36:45 +000065HeaderSearch::~HeaderSearch() {
66 // Delete headermaps.
67 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
68 delete HeaderMaps[i].second;
69}
Mike Stump1eb44332009-09-09 15:08:12 +000070
Reid Spencer5f016e22007-07-11 17:01:13 +000071void HeaderSearch::PrintStats() {
72 fprintf(stderr, "\n*** HeaderSearch Stats:\n");
73 fprintf(stderr, "%d files tracked.\n", (int)FileInfo.size());
74 unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0;
75 for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) {
76 NumOnceOnlyFiles += FileInfo[i].isImport;
77 if (MaxNumIncludes < FileInfo[i].NumIncludes)
78 MaxNumIncludes = FileInfo[i].NumIncludes;
79 NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1;
80 }
81 fprintf(stderr, " %d #import/#pragma once files.\n", NumOnceOnlyFiles);
82 fprintf(stderr, " %d included exactly once.\n", NumSingleIncludedFiles);
83 fprintf(stderr, " %d max times a file is included.\n", MaxNumIncludes);
Mike Stump1eb44332009-09-09 15:08:12 +000084
Reid Spencer5f016e22007-07-11 17:01:13 +000085 fprintf(stderr, " %d #include/#include_next/#import.\n", NumIncluded);
86 fprintf(stderr, " %d #includes skipped due to"
87 " the multi-include optimization.\n", NumMultiIncludeFileOptzn);
Mike Stump1eb44332009-09-09 15:08:12 +000088
Reid Spencer5f016e22007-07-11 17:01:13 +000089 fprintf(stderr, "%d framework lookups.\n", NumFrameworkLookups);
90 fprintf(stderr, "%d subframework lookups.\n", NumSubFrameworkLookups);
91}
92
Chris Lattner822da612007-12-17 06:36:45 +000093/// CreateHeaderMap - This method returns a HeaderMap for the specified
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +000094/// FileEntry, uniquing them through the 'HeaderMaps' datastructure.
Chris Lattner1bfd4a62007-12-17 18:34:53 +000095const HeaderMap *HeaderSearch::CreateHeaderMap(const FileEntry *FE) {
Chris Lattner822da612007-12-17 06:36:45 +000096 // We expect the number of headermaps to be small, and almost always empty.
Chris Lattnerdf772332007-12-17 07:52:39 +000097 // If it ever grows, use of a linear search should be re-evaluated.
Chris Lattner822da612007-12-17 06:36:45 +000098 if (!HeaderMaps.empty()) {
99 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
Chris Lattnerdf772332007-12-17 07:52:39 +0000100 // Pointer equality comparison of FileEntries works because they are
101 // already uniqued by inode.
Mike Stump1eb44332009-09-09 15:08:12 +0000102 if (HeaderMaps[i].first == FE)
Chris Lattner822da612007-12-17 06:36:45 +0000103 return HeaderMaps[i].second;
104 }
Mike Stump1eb44332009-09-09 15:08:12 +0000105
Chris Lattner39b49bc2010-11-23 08:35:12 +0000106 if (const HeaderMap *HM = HeaderMap::Create(FE, FileMgr)) {
Chris Lattner822da612007-12-17 06:36:45 +0000107 HeaderMaps.push_back(std::make_pair(FE, HM));
108 return HM;
109 }
Mike Stump1eb44332009-09-09 15:08:12 +0000110
Chris Lattner822da612007-12-17 06:36:45 +0000111 return 0;
112}
113
Douglas Gregore434ec72012-01-29 17:08:11 +0000114std::string HeaderSearch::getModuleFileName(Module *Module) {
Douglas Gregor9a6da692011-09-12 20:41:59 +0000115 // If we don't have a module cache path, we can't do anything.
Douglas Gregore434ec72012-01-29 17:08:11 +0000116 if (ModuleCachePath.empty())
117 return std::string();
118
119
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000120 SmallString<256> Result(ModuleCachePath);
Douglas Gregore434ec72012-01-29 17:08:11 +0000121 llvm::sys::path::append(Result, Module->getTopLevelModule()->Name + ".pcm");
122 return Result.str().str();
123}
124
125std::string HeaderSearch::getModuleFileName(StringRef ModuleName) {
126 // If we don't have a module cache path, we can't do anything.
127 if (ModuleCachePath.empty())
128 return std::string();
Douglas Gregor6e975c42011-09-13 23:15:45 +0000129
Douglas Gregore434ec72012-01-29 17:08:11 +0000130
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000131 SmallString<256> Result(ModuleCachePath);
Douglas Gregore434ec72012-01-29 17:08:11 +0000132 llvm::sys::path::append(Result, ModuleName + ".pcm");
133 return Result.str().str();
134}
135
136Module *HeaderSearch::lookupModule(StringRef ModuleName, bool AllowSearch) {
Douglas Gregorcf70d782011-11-12 00:05:07 +0000137 // Look in the module map to determine if there is a module by this name.
Douglas Gregore434ec72012-01-29 17:08:11 +0000138 Module *Module = ModMap.findModule(ModuleName);
139 if (Module || !AllowSearch)
140 return Module;
141
Douglas Gregor7005b902013-01-10 01:43:00 +0000142 // Look through the various header search paths to load any available module
Douglas Gregore434ec72012-01-29 17:08:11 +0000143 // maps, searching for a module map that describes this module.
144 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
145 if (SearchDirs[Idx].isFramework()) {
146 // Search for or infer a module map for a framework.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000147 SmallString<128> FrameworkDirName;
Douglas Gregore434ec72012-01-29 17:08:11 +0000148 FrameworkDirName += SearchDirs[Idx].getFrameworkDir()->getName();
149 llvm::sys::path::append(FrameworkDirName, ModuleName + ".framework");
150 if (const DirectoryEntry *FrameworkDir
151 = FileMgr.getDirectory(FrameworkDirName)) {
152 bool IsSystem
153 = SearchDirs[Idx].getDirCharacteristic() != SrcMgr::C_User;
154 Module = loadFrameworkModule(ModuleName, FrameworkDir, IsSystem);
Douglas Gregorcf70d782011-11-12 00:05:07 +0000155 if (Module)
156 break;
157 }
Douglas Gregore434ec72012-01-29 17:08:11 +0000158 }
159
160 // FIXME: Figure out how header maps and module maps will work together.
161
162 // Only deal with normal search directories.
163 if (!SearchDirs[Idx].isNormalDir())
164 continue;
165
166 // Search for a module map file in this directory.
167 if (loadModuleMapFile(SearchDirs[Idx].getDir()) == LMM_NewlyLoaded) {
168 // We just loaded a module map file; check whether the module is
169 // available now.
170 Module = ModMap.findModule(ModuleName);
171 if (Module)
172 break;
173 }
174
175 // Search for a module map in a subdirectory with the same name as the
176 // module.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000177 SmallString<128> NestedModuleMapDirName;
Douglas Gregore434ec72012-01-29 17:08:11 +0000178 NestedModuleMapDirName = SearchDirs[Idx].getDir()->getName();
179 llvm::sys::path::append(NestedModuleMapDirName, ModuleName);
180 if (loadModuleMapFile(NestedModuleMapDirName) == LMM_NewlyLoaded) {
181 // If we just loaded a module map file, look for the module again.
182 Module = ModMap.findModule(ModuleName);
183 if (Module)
184 break;
Douglas Gregorcf70d782011-11-12 00:05:07 +0000185 }
186 }
Douglas Gregore434ec72012-01-29 17:08:11 +0000187
188 return Module;
Douglas Gregor9a6da692011-09-12 20:41:59 +0000189}
190
Chris Lattnerdf772332007-12-17 07:52:39 +0000191//===----------------------------------------------------------------------===//
192// File lookup within a DirectoryLookup scope
193//===----------------------------------------------------------------------===//
194
Chris Lattner3af66a92007-12-17 17:57:27 +0000195/// getName - Return the directory or filename corresponding to this lookup
196/// object.
197const char *DirectoryLookup::getName() const {
198 if (isNormalDir())
199 return getDir()->getName();
200 if (isFramework())
201 return getFrameworkDir()->getName();
202 assert(isHeaderMap() && "Unknown DirectoryLookup");
203 return getHeaderMap()->getFileName();
204}
205
206
Chris Lattnerdf772332007-12-17 07:52:39 +0000207/// LookupFile - Lookup the specified file in this search path, returning it
208/// if it exists or returning null if not.
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000209const FileEntry *DirectoryLookup::LookupFile(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000210 StringRef Filename,
Manuel Klimek74124942011-04-26 21:50:03 +0000211 HeaderSearch &HS,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000212 SmallVectorImpl<char> *SearchPath,
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000213 SmallVectorImpl<char> *RelativePath,
Daniel Dunbar85ff9692012-04-05 17:10:06 +0000214 Module **SuggestedModule,
215 bool &InUserSpecifiedSystemFramework) const {
216 InUserSpecifiedSystemFramework = false;
217
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000218 SmallString<1024> TmpDir;
Chris Lattnerafded5b2007-12-17 08:13:48 +0000219 if (isNormalDir()) {
220 // Concatenate the requested file onto the directory.
Eli Friedmana6e023c2011-07-08 20:17:28 +0000221 TmpDir = getDir()->getName();
222 llvm::sys::path::append(TmpDir, Filename);
Manuel Klimek74124942011-04-26 21:50:03 +0000223 if (SearchPath != NULL) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000224 StringRef SearchPathRef(getDir()->getName());
Manuel Klimek74124942011-04-26 21:50:03 +0000225 SearchPath->clear();
226 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
227 }
228 if (RelativePath != NULL) {
229 RelativePath->clear();
230 RelativePath->append(Filename.begin(), Filename.end());
231 }
Douglas Gregora30cfe52011-11-11 19:10:28 +0000232
233 // If we have a module map that might map this header, load it and
234 // check whether we'll have a suggestion for a module.
235 if (SuggestedModule && HS.hasModuleMap(TmpDir, getDir())) {
236 const FileEntry *File = HS.getFileMgr().getFile(TmpDir.str(),
237 /*openFile=*/false);
238 if (!File)
239 return File;
240
241 // If there is a module that corresponds to this header,
242 // suggest it.
Douglas Gregor5e3f9222011-12-08 17:01:29 +0000243 *SuggestedModule = HS.findModuleForHeader(File);
Douglas Gregora30cfe52011-11-11 19:10:28 +0000244 return File;
245 }
246
Argyrios Kyrtzidis3cd01282011-03-16 19:17:25 +0000247 return HS.getFileMgr().getFile(TmpDir.str(), /*openFile=*/true);
Chris Lattnerafded5b2007-12-17 08:13:48 +0000248 }
Mike Stump1eb44332009-09-09 15:08:12 +0000249
Chris Lattnerafded5b2007-12-17 08:13:48 +0000250 if (isFramework())
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000251 return DoFrameworkLookup(Filename, HS, SearchPath, RelativePath,
Daniel Dunbar85ff9692012-04-05 17:10:06 +0000252 SuggestedModule, InUserSpecifiedSystemFramework);
Mike Stump1eb44332009-09-09 15:08:12 +0000253
Chris Lattnerb09e71f2007-12-17 08:17:39 +0000254 assert(isHeaderMap() && "Unknown directory lookup");
Manuel Klimek74124942011-04-26 21:50:03 +0000255 const FileEntry * const Result = getHeaderMap()->LookupFile(
256 Filename, HS.getFileMgr());
257 if (Result) {
258 if (SearchPath != NULL) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000259 StringRef SearchPathRef(getName());
Manuel Klimek74124942011-04-26 21:50:03 +0000260 SearchPath->clear();
261 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
262 }
263 if (RelativePath != NULL) {
264 RelativePath->clear();
265 RelativePath->append(Filename.begin(), Filename.end());
266 }
267 }
268 return Result;
Chris Lattnerdf772332007-12-17 07:52:39 +0000269}
270
Douglas Gregor7005b902013-01-10 01:43:00 +0000271/// \brief Given a framework directory, find the top-most framework directory.
272///
273/// \param FileMgr The file manager to use for directory lookups.
274/// \param DirName The name of the framework directory.
275/// \param SubmodulePath Will be populated with the submodule path from the
276/// returned top-level module to the originally named framework.
277static const DirectoryEntry *
278getTopFrameworkDir(FileManager &FileMgr, StringRef DirName,
279 SmallVectorImpl<std::string> &SubmodulePath) {
280 assert(llvm::sys::path::extension(DirName) == ".framework" &&
281 "Not a framework directory");
282
283#ifdef LLVM_ON_UNIX
284 // Note: as an egregious but useful hack we use the real path here, because
285 // frameworks moving between top-level frameworks to embedded frameworks tend
286 // to be symlinked, and we base the logical structure of modules on the
287 // physical layout. In particular, we need to deal with crazy includes like
288 //
289 // #include <Foo/Frameworks/Bar.framework/Headers/Wibble.h>
290 //
291 // where 'Bar' used to be embedded in 'Foo', is now a top-level framework
292 // which one should access with, e.g.,
293 //
294 // #include <Bar/Wibble.h>
295 //
296 // Similar issues occur when a top-level framework has moved into an
297 // embedded framework.
298 char RealDirName[PATH_MAX];
299 if (realpath(DirName.str().c_str(), RealDirName))
300 DirName = RealDirName;
301#endif
302
303 const DirectoryEntry *TopFrameworkDir = FileMgr.getDirectory(DirName);
304 do {
305 // Get the parent directory name.
306 DirName = llvm::sys::path::parent_path(DirName);
307 if (DirName.empty())
308 break;
309
310 // Determine whether this directory exists.
311 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
312 if (!Dir)
313 break;
314
315 // If this is a framework directory, then we're a subframework of this
316 // framework.
317 if (llvm::sys::path::extension(DirName) == ".framework") {
318 SubmodulePath.push_back(llvm::sys::path::stem(DirName));
319 TopFrameworkDir = Dir;
320 }
321 } while (true);
322
323 return TopFrameworkDir;
324}
Chris Lattnerdf772332007-12-17 07:52:39 +0000325
Chris Lattnerafded5b2007-12-17 08:13:48 +0000326/// DoFrameworkLookup - Do a lookup of the specified file in the current
327/// DirectoryLookup, which is a framework directory.
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000328const FileEntry *DirectoryLookup::DoFrameworkLookup(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000329 StringRef Filename,
Manuel Klimek74124942011-04-26 21:50:03 +0000330 HeaderSearch &HS,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000331 SmallVectorImpl<char> *SearchPath,
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000332 SmallVectorImpl<char> *RelativePath,
Daniel Dunbar85ff9692012-04-05 17:10:06 +0000333 Module **SuggestedModule,
334 bool &InUserSpecifiedSystemFramework) const
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000335{
Chris Lattnerafded5b2007-12-17 08:13:48 +0000336 FileManager &FileMgr = HS.getFileMgr();
Mike Stump1eb44332009-09-09 15:08:12 +0000337
Reid Spencer5f016e22007-07-11 17:01:13 +0000338 // Framework names must have a '/' in the filename.
Chris Lattnera1394812010-01-10 01:35:12 +0000339 size_t SlashPos = Filename.find('/');
Chris Lattner5f9e2722011-07-23 10:55:15 +0000340 if (SlashPos == StringRef::npos) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000341
Chris Lattnerafded5b2007-12-17 08:13:48 +0000342 // Find out if this is the home for the specified framework, by checking
Daniel Dunbar9ee35f92012-04-05 17:09:40 +0000343 // HeaderSearch. Possible answers are yes/no and unknown.
344 HeaderSearch::FrameworkCacheEntry &CacheEntry =
Chris Lattnera1394812010-01-10 01:35:12 +0000345 HS.LookupFrameworkCache(Filename.substr(0, SlashPos));
Mike Stump1eb44332009-09-09 15:08:12 +0000346
Chris Lattnerafded5b2007-12-17 08:13:48 +0000347 // If it is known and in some other directory, fail.
Daniel Dunbar9ee35f92012-04-05 17:09:40 +0000348 if (CacheEntry.Directory && CacheEntry.Directory != getFrameworkDir())
Reid Spencer5f016e22007-07-11 17:01:13 +0000349 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000350
Chris Lattnerafded5b2007-12-17 08:13:48 +0000351 // Otherwise, construct the path to this framework dir.
Mike Stump1eb44332009-09-09 15:08:12 +0000352
Reid Spencer5f016e22007-07-11 17:01:13 +0000353 // FrameworkName = "/System/Library/Frameworks/"
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000354 SmallString<1024> FrameworkName;
Chris Lattnerafded5b2007-12-17 08:13:48 +0000355 FrameworkName += getFrameworkDir()->getName();
Reid Spencer5f016e22007-07-11 17:01:13 +0000356 if (FrameworkName.empty() || FrameworkName.back() != '/')
357 FrameworkName.push_back('/');
Mike Stump1eb44332009-09-09 15:08:12 +0000358
Reid Spencer5f016e22007-07-11 17:01:13 +0000359 // FrameworkName = "/System/Library/Frameworks/Cocoa"
Douglas Gregor2821c7f2011-11-17 01:41:17 +0000360 StringRef ModuleName(Filename.begin(), SlashPos);
361 FrameworkName += ModuleName;
Mike Stump1eb44332009-09-09 15:08:12 +0000362
Reid Spencer5f016e22007-07-11 17:01:13 +0000363 // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/"
364 FrameworkName += ".framework/";
Mike Stump1eb44332009-09-09 15:08:12 +0000365
Daniel Dunbar9ee35f92012-04-05 17:09:40 +0000366 // If the cache entry was unresolved, populate it now.
367 if (CacheEntry.Directory == 0) {
Chris Lattnerafded5b2007-12-17 08:13:48 +0000368 HS.IncrementFrameworkLookupCount();
Mike Stump1eb44332009-09-09 15:08:12 +0000369
Reid Spencer5f016e22007-07-11 17:01:13 +0000370 // If the framework dir doesn't exist, we fail.
Daniel Dunbar85ff9692012-04-05 17:10:06 +0000371 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName.str());
372 if (Dir == 0) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000373
Reid Spencer5f016e22007-07-11 17:01:13 +0000374 // Otherwise, if it does, remember that this is the right direntry for this
375 // framework.
Daniel Dunbar9ee35f92012-04-05 17:09:40 +0000376 CacheEntry.Directory = getFrameworkDir();
Daniel Dunbar85ff9692012-04-05 17:10:06 +0000377
378 // If this is a user search directory, check if the framework has been
379 // user-specified as a system framework.
380 if (getDirCharacteristic() == SrcMgr::C_User) {
381 SmallString<1024> SystemFrameworkMarker(FrameworkName);
382 SystemFrameworkMarker += ".system_framework";
383 if (llvm::sys::fs::exists(SystemFrameworkMarker.str())) {
384 CacheEntry.IsUserSpecifiedSystemFramework = true;
385 }
386 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000387 }
Mike Stump1eb44332009-09-09 15:08:12 +0000388
Daniel Dunbar85ff9692012-04-05 17:10:06 +0000389 // Set the 'user-specified system framework' flag.
390 InUserSpecifiedSystemFramework = CacheEntry.IsUserSpecifiedSystemFramework;
391
Manuel Klimek74124942011-04-26 21:50:03 +0000392 if (RelativePath != NULL) {
393 RelativePath->clear();
394 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
395 }
Douglas Gregor2821c7f2011-11-17 01:41:17 +0000396
Reid Spencer5f016e22007-07-11 17:01:13 +0000397 // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"
398 unsigned OrigSize = FrameworkName.size();
Mike Stump1eb44332009-09-09 15:08:12 +0000399
Reid Spencer5f016e22007-07-11 17:01:13 +0000400 FrameworkName += "Headers/";
Manuel Klimek74124942011-04-26 21:50:03 +0000401
402 if (SearchPath != NULL) {
403 SearchPath->clear();
404 // Without trailing '/'.
405 SearchPath->append(FrameworkName.begin(), FrameworkName.end()-1);
406 }
407
Chris Lattnera1394812010-01-10 01:35:12 +0000408 FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end());
Douglas Gregor7005b902013-01-10 01:43:00 +0000409 const FileEntry *FE = FileMgr.getFile(FrameworkName.str(),
410 /*openFile=*/!SuggestedModule);
411 if (!FE) {
412 // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"
413 const char *Private = "Private";
414 FrameworkName.insert(FrameworkName.begin()+OrigSize, Private,
415 Private+strlen(Private));
416 if (SearchPath != NULL)
417 SearchPath->insert(SearchPath->begin()+OrigSize, Private,
418 Private+strlen(Private));
419
420 FE = FileMgr.getFile(FrameworkName.str(), /*openFile=*/!SuggestedModule);
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000421 }
Mike Stump1eb44332009-09-09 15:08:12 +0000422
Douglas Gregor7005b902013-01-10 01:43:00 +0000423 // If we found the header and are allowed to suggest a module, do so now.
424 if (FE && SuggestedModule) {
425 // Find the framework in which this header occurs.
426 StringRef FrameworkPath = FE->getName();
427 bool FoundFramework = false;
428 do {
429 // Get the parent directory name.
430 FrameworkPath = llvm::sys::path::parent_path(FrameworkPath);
431 if (FrameworkPath.empty())
432 break;
Manuel Klimek74124942011-04-26 21:50:03 +0000433
Douglas Gregor7005b902013-01-10 01:43:00 +0000434 // Determine whether this directory exists.
435 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkPath);
436 if (!Dir)
437 break;
438
439 // If this is a framework directory, then we're a subframework of this
440 // framework.
441 if (llvm::sys::path::extension(FrameworkPath) == ".framework") {
442 FoundFramework = true;
443 break;
444 }
445 } while (true);
446
447 if (FoundFramework) {
448 // Find the top-level framework based on this framework.
449 SmallVector<std::string, 4> SubmodulePath;
450 const DirectoryEntry *TopFrameworkDir
451 = ::getTopFrameworkDir(FileMgr, FrameworkPath, SubmodulePath);
452
453 // Determine the name of the top-level framework.
454 StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
455
456 // Load this framework module. If that succeeds, find the suggested module
457 // for this header, if any.
458 bool IsSystem = getDirCharacteristic() != SrcMgr::C_User;
459 if (HS.loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystem)) {
460 *SuggestedModule = HS.findModuleForHeader(FE);
461 }
462 } else {
463 *SuggestedModule = HS.findModuleForHeader(FE);
464 }
465 }
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000466 return FE;
Reid Spencer5f016e22007-07-11 17:01:13 +0000467}
468
Douglas Gregordc58aa72012-01-30 06:01:29 +0000469void HeaderSearch::setTarget(const TargetInfo &Target) {
470 ModMap.setTarget(Target);
471}
472
Chris Lattnerdf772332007-12-17 07:52:39 +0000473
Chris Lattnerafded5b2007-12-17 08:13:48 +0000474//===----------------------------------------------------------------------===//
475// Header File Location.
476//===----------------------------------------------------------------------===//
477
478
James Dennett853519c2012-06-20 00:56:32 +0000479/// LookupFile - Given a "foo" or \<foo> reference, look up the indicated file,
Reid Spencer5f016e22007-07-11 17:01:13 +0000480/// return null on failure. isAngled indicates whether the file reference is
James Dennett853519c2012-06-20 00:56:32 +0000481/// for system \#include's or not (i.e. using <> instead of ""). CurFileEnt, if
482/// non-null, indicates where the \#including file is, in case a relative search
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000483/// is needed.
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000484const FileEntry *HeaderSearch::LookupFile(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000485 StringRef Filename,
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000486 bool isAngled,
487 const DirectoryLookup *FromDir,
488 const DirectoryLookup *&CurDir,
489 const FileEntry *CurFileEnt,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000490 SmallVectorImpl<char> *SearchPath,
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000491 SmallVectorImpl<char> *RelativePath,
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000492 Module **SuggestedModule,
Douglas Gregor1c2e9332011-11-20 17:46:46 +0000493 bool SkipCache)
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000494{
495 if (SuggestedModule)
Douglas Gregorc69c42e2011-11-17 22:44:56 +0000496 *SuggestedModule = 0;
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000497
Reid Spencer5f016e22007-07-11 17:01:13 +0000498 // If 'Filename' is absolute, check to see if it exists and no searching.
Michael J. Spencer256053b2010-12-17 21:22:22 +0000499 if (llvm::sys::path::is_absolute(Filename)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000500 CurDir = 0;
501
502 // If this was an #include_next "/absolute/file", fail.
503 if (FromDir) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000504
Manuel Klimek74124942011-04-26 21:50:03 +0000505 if (SearchPath != NULL)
506 SearchPath->clear();
507 if (RelativePath != NULL) {
508 RelativePath->clear();
509 RelativePath->append(Filename.begin(), Filename.end());
510 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000511 // Otherwise, just return the file.
Argyrios Kyrtzidis3cd01282011-03-16 19:17:25 +0000512 return FileMgr.getFile(Filename, /*openFile=*/true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000513 }
Mike Stump1eb44332009-09-09 15:08:12 +0000514
Douglas Gregor65e02fa2011-07-28 04:45:53 +0000515 // Unless disabled, check to see if the file is in the #includer's
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000516 // directory. This has to be based on CurFileEnt, not CurDir, because
517 // CurFileEnt could be a #include of a subdirectory (#include "foo/bar.h") and
Chris Lattnerdf772332007-12-17 07:52:39 +0000518 // a subsequent include of "baz.h" should resolve to "whatever/foo/baz.h".
519 // This search is not done for <> headers.
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000520 if (CurFileEnt && !isAngled && !NoCurDirSearch) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000521 SmallString<1024> TmpDir;
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000522 // Concatenate the requested file onto the directory.
523 // FIXME: Portability. Filename concatenation should be in sys::Path.
524 TmpDir += CurFileEnt->getDir()->getName();
525 TmpDir.push_back('/');
526 TmpDir.append(Filename.begin(), Filename.end());
Argyrios Kyrtzidis3cd01282011-03-16 19:17:25 +0000527 if (const FileEntry *FE = FileMgr.getFile(TmpDir.str(),/*openFile=*/true)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000528 // Leave CurDir unset.
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000529 // This file is a system header or C++ unfriendly if the old file is.
530 //
Douglas Gregor21efbb62012-08-13 15:47:39 +0000531 // Note that we only use one of FromHFI/ToHFI at once, due to potential
532 // reallocation of the underlying vector potentially making the first
533 // reference binding dangling.
534 HeaderFileInfo &FromHFI = getFileInfo(CurFileEnt);
535 unsigned DirInfo = FromHFI.DirInfo;
536 bool IndexHeaderMapHeader = FromHFI.IndexHeaderMapHeader;
537 StringRef Framework = FromHFI.Framework;
538
539 HeaderFileInfo &ToHFI = getFileInfo(FE);
540 ToHFI.DirInfo = DirInfo;
541 ToHFI.IndexHeaderMapHeader = IndexHeaderMapHeader;
542 ToHFI.Framework = Framework;
543
Manuel Klimek74124942011-04-26 21:50:03 +0000544 if (SearchPath != NULL) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000545 StringRef SearchPathRef(CurFileEnt->getDir()->getName());
Manuel Klimek74124942011-04-26 21:50:03 +0000546 SearchPath->clear();
547 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
548 }
549 if (RelativePath != NULL) {
550 RelativePath->clear();
551 RelativePath->append(Filename.begin(), Filename.end());
552 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000553 return FE;
554 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000555 }
Mike Stump1eb44332009-09-09 15:08:12 +0000556
Reid Spencer5f016e22007-07-11 17:01:13 +0000557 CurDir = 0;
558
559 // If this is a system #include, ignore the user #include locs.
Nico Weber74a5fd82011-05-24 04:31:14 +0000560 unsigned i = isAngled ? AngledDirIdx : 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000561
Reid Spencer5f016e22007-07-11 17:01:13 +0000562 // If this is a #include_next request, start searching after the directory the
563 // file was found in.
564 if (FromDir)
565 i = FromDir-&SearchDirs[0];
Mike Stump1eb44332009-09-09 15:08:12 +0000566
Chris Lattner9960ae82007-07-22 07:28:00 +0000567 // Cache all of the lookups performed by this method. Many headers are
568 // multiply included, and the "pragma once" optimization prevents them from
569 // being relex/pp'd, but they would still have to search through a
570 // (potentially huge) series of SearchDirs to find it.
571 std::pair<unsigned, unsigned> &CacheLookup =
Chris Lattnera1394812010-01-10 01:35:12 +0000572 LookupFileCache.GetOrCreateValue(Filename).getValue();
Chris Lattner9960ae82007-07-22 07:28:00 +0000573
574 // If the entry has been previously looked up, the first value will be
575 // non-zero. If the value is equal to i (the start point of our search), then
576 // this is a matching hit.
Douglas Gregor1c2e9332011-11-20 17:46:46 +0000577 if (!SkipCache && CacheLookup.first == i+1) {
Chris Lattner9960ae82007-07-22 07:28:00 +0000578 // Skip querying potentially lots of directories for this lookup.
579 i = CacheLookup.second;
580 } else {
581 // Otherwise, this is the first query, or the previous query didn't match
582 // our search start. We will fill in our found location below, so prime the
583 // start point value.
584 CacheLookup.first = i+1;
585 }
Mike Stump1eb44332009-09-09 15:08:12 +0000586
Reid Spencer5f016e22007-07-11 17:01:13 +0000587 // Check each directory in sequence to see if it contains this file.
588 for (; i != SearchDirs.size(); ++i) {
Daniel Dunbar85ff9692012-04-05 17:10:06 +0000589 bool InUserSpecifiedSystemFramework = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000590 const FileEntry *FE =
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000591 SearchDirs[i].LookupFile(Filename, *this, SearchPath, RelativePath,
Daniel Dunbar85ff9692012-04-05 17:10:06 +0000592 SuggestedModule, InUserSpecifiedSystemFramework);
Chris Lattnerafded5b2007-12-17 08:13:48 +0000593 if (!FE) continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000594
Chris Lattnerafded5b2007-12-17 08:13:48 +0000595 CurDir = &SearchDirs[i];
Mike Stump1eb44332009-09-09 15:08:12 +0000596
Chris Lattnerafded5b2007-12-17 08:13:48 +0000597 // This file is a system header or C++ unfriendly if the dir is.
Douglas Gregor65e02fa2011-07-28 04:45:53 +0000598 HeaderFileInfo &HFI = getFileInfo(FE);
599 HFI.DirInfo = CurDir->getDirCharacteristic();
Mike Stump1eb44332009-09-09 15:08:12 +0000600
Daniel Dunbar85ff9692012-04-05 17:10:06 +0000601 // If the directory characteristic is User but this framework was
602 // user-specified to be treated as a system framework, promote the
603 // characteristic.
604 if (HFI.DirInfo == SrcMgr::C_User && InUserSpecifiedSystemFramework)
605 HFI.DirInfo = SrcMgr::C_System;
606
Richard Smithf122a132012-06-13 20:27:03 +0000607 // If the filename matches a known system header prefix, override
608 // whether the file is a system header.
Richard Trieu4ef2f6a2012-06-13 20:52:36 +0000609 for (unsigned j = SystemHeaderPrefixes.size(); j; --j) {
610 if (Filename.startswith(SystemHeaderPrefixes[j-1].first)) {
611 HFI.DirInfo = SystemHeaderPrefixes[j-1].second ? SrcMgr::C_System
Richard Smithf122a132012-06-13 20:27:03 +0000612 : SrcMgr::C_User;
613 break;
614 }
615 }
616
Douglas Gregor65e02fa2011-07-28 04:45:53 +0000617 // If this file is found in a header map and uses the framework style of
618 // includes, then this header is part of a framework we're building.
619 if (CurDir->isIndexHeaderMap()) {
620 size_t SlashPos = Filename.find('/');
621 if (SlashPos != StringRef::npos) {
622 HFI.IndexHeaderMapHeader = 1;
623 HFI.Framework = getUniqueFrameworkName(StringRef(Filename.begin(),
624 SlashPos));
625 }
626 }
627
Chris Lattnerafded5b2007-12-17 08:13:48 +0000628 // Remember this location for the next lookup we do.
629 CacheLookup.second = i;
630 return FE;
Reid Spencer5f016e22007-07-11 17:01:13 +0000631 }
Mike Stump1eb44332009-09-09 15:08:12 +0000632
Douglas Gregor2c7b7802011-07-30 06:28:34 +0000633 // If we are including a file with a quoted include "foo.h" from inside
634 // a header in a framework that is currently being built, and we couldn't
635 // resolve "foo.h" any other way, change the include to <Foo/foo.h>, where
636 // "Foo" is the name of the framework in which the including header was found.
637 if (CurFileEnt && !isAngled && Filename.find('/') == StringRef::npos) {
638 HeaderFileInfo &IncludingHFI = getFileInfo(CurFileEnt);
639 if (IncludingHFI.IndexHeaderMapHeader) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000640 SmallString<128> ScratchFilename;
Douglas Gregor2c7b7802011-07-30 06:28:34 +0000641 ScratchFilename += IncludingHFI.Framework;
642 ScratchFilename += '/';
643 ScratchFilename += Filename;
644
645 const FileEntry *Result = LookupFile(ScratchFilename, /*isAngled=*/true,
646 FromDir, CurDir, CurFileEnt,
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000647 SearchPath, RelativePath,
648 SuggestedModule);
Douglas Gregor2c7b7802011-07-30 06:28:34 +0000649 std::pair<unsigned, unsigned> &CacheLookup
650 = LookupFileCache.GetOrCreateValue(Filename).getValue();
651 CacheLookup.second
652 = LookupFileCache.GetOrCreateValue(ScratchFilename).getValue().second;
653 return Result;
654 }
655 }
656
Chris Lattner9960ae82007-07-22 07:28:00 +0000657 // Otherwise, didn't find it. Remember we didn't find this.
658 CacheLookup.second = SearchDirs.size();
Reid Spencer5f016e22007-07-11 17:01:13 +0000659 return 0;
660}
661
662/// LookupSubframeworkHeader - Look up a subframework for the specified
James Dennett853519c2012-06-20 00:56:32 +0000663/// \#include file. For example, if \#include'ing <HIToolbox/HIToolbox.h> from
Reid Spencer5f016e22007-07-11 17:01:13 +0000664/// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
665/// is a subframework within Carbon.framework. If so, return the FileEntry
666/// for the designated file, otherwise return null.
667const FileEntry *HeaderSearch::
Chris Lattner5f9e2722011-07-23 10:55:15 +0000668LookupSubframeworkHeader(StringRef Filename,
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000669 const FileEntry *ContextFileEnt,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000670 SmallVectorImpl<char> *SearchPath,
671 SmallVectorImpl<char> *RelativePath) {
Chris Lattner9415a0c2008-02-01 05:34:02 +0000672 assert(ContextFileEnt && "No context file?");
Mike Stump1eb44332009-09-09 15:08:12 +0000673
Reid Spencer5f016e22007-07-11 17:01:13 +0000674 // Framework names must have a '/' in the filename. Find it.
Douglas Gregorefda0e82011-12-09 16:48:01 +0000675 // FIXME: Should we permit '\' on Windows?
Chris Lattnera1394812010-01-10 01:35:12 +0000676 size_t SlashPos = Filename.find('/');
Chris Lattner5f9e2722011-07-23 10:55:15 +0000677 if (SlashPos == StringRef::npos) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000678
Reid Spencer5f016e22007-07-11 17:01:13 +0000679 // Look up the base framework name of the ContextFileEnt.
680 const char *ContextName = ContextFileEnt->getName();
Mike Stump1eb44332009-09-09 15:08:12 +0000681
Reid Spencer5f016e22007-07-11 17:01:13 +0000682 // If the context info wasn't a framework, couldn't be a subframework.
Douglas Gregorefda0e82011-12-09 16:48:01 +0000683 const unsigned DotFrameworkLen = 10;
684 const char *FrameworkPos = strstr(ContextName, ".framework");
685 if (FrameworkPos == 0 ||
686 (FrameworkPos[DotFrameworkLen] != '/' &&
687 FrameworkPos[DotFrameworkLen] != '\\'))
Reid Spencer5f016e22007-07-11 17:01:13 +0000688 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000689
Daniel Dunbar9ee35f92012-04-05 17:09:40 +0000690 SmallString<1024> FrameworkName(ContextName, FrameworkPos+DotFrameworkLen+1);
Reid Spencer5f016e22007-07-11 17:01:13 +0000691
692 // Append Frameworks/HIToolbox.framework/
693 FrameworkName += "Frameworks/";
Chris Lattnera1394812010-01-10 01:35:12 +0000694 FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos);
Reid Spencer5f016e22007-07-11 17:01:13 +0000695 FrameworkName += ".framework/";
696
Daniel Dunbar9ee35f92012-04-05 17:09:40 +0000697 llvm::StringMapEntry<FrameworkCacheEntry> &CacheLookup =
Chris Lattner65382272010-11-21 09:55:08 +0000698 FrameworkMap.GetOrCreateValue(Filename.substr(0, SlashPos));
Mike Stump1eb44332009-09-09 15:08:12 +0000699
Reid Spencer5f016e22007-07-11 17:01:13 +0000700 // Some other location?
Daniel Dunbar9ee35f92012-04-05 17:09:40 +0000701 if (CacheLookup.getValue().Directory &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000702 CacheLookup.getKeyLength() == FrameworkName.size() &&
703 memcmp(CacheLookup.getKeyData(), &FrameworkName[0],
704 CacheLookup.getKeyLength()) != 0)
705 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000706
Reid Spencer5f016e22007-07-11 17:01:13 +0000707 // Cache subframework.
Daniel Dunbar9ee35f92012-04-05 17:09:40 +0000708 if (CacheLookup.getValue().Directory == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000709 ++NumSubFrameworkLookups;
Mike Stump1eb44332009-09-09 15:08:12 +0000710
Reid Spencer5f016e22007-07-11 17:01:13 +0000711 // If the framework dir doesn't exist, we fail.
Chris Lattner39b49bc2010-11-23 08:35:12 +0000712 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName.str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000713 if (Dir == 0) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000714
Reid Spencer5f016e22007-07-11 17:01:13 +0000715 // Otherwise, if it does, remember that this is the right direntry for this
716 // framework.
Daniel Dunbar9ee35f92012-04-05 17:09:40 +0000717 CacheLookup.getValue().Directory = Dir;
Reid Spencer5f016e22007-07-11 17:01:13 +0000718 }
Mike Stump1eb44332009-09-09 15:08:12 +0000719
Reid Spencer5f016e22007-07-11 17:01:13 +0000720 const FileEntry *FE = 0;
721
Manuel Klimek74124942011-04-26 21:50:03 +0000722 if (RelativePath != NULL) {
723 RelativePath->clear();
724 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
725 }
726
Reid Spencer5f016e22007-07-11 17:01:13 +0000727 // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000728 SmallString<1024> HeadersFilename(FrameworkName);
Reid Spencer5f016e22007-07-11 17:01:13 +0000729 HeadersFilename += "Headers/";
Manuel Klimek74124942011-04-26 21:50:03 +0000730 if (SearchPath != NULL) {
731 SearchPath->clear();
732 // Without trailing '/'.
733 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
734 }
735
Chris Lattnera1394812010-01-10 01:35:12 +0000736 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
Argyrios Kyrtzidis3cd01282011-03-16 19:17:25 +0000737 if (!(FE = FileMgr.getFile(HeadersFilename.str(), /*openFile=*/true))) {
Mike Stump1eb44332009-09-09 15:08:12 +0000738
Reid Spencer5f016e22007-07-11 17:01:13 +0000739 // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
740 HeadersFilename = FrameworkName;
741 HeadersFilename += "PrivateHeaders/";
Manuel Klimek74124942011-04-26 21:50:03 +0000742 if (SearchPath != NULL) {
743 SearchPath->clear();
744 // Without trailing '/'.
745 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
746 }
747
Chris Lattnera1394812010-01-10 01:35:12 +0000748 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
Argyrios Kyrtzidis3cd01282011-03-16 19:17:25 +0000749 if (!(FE = FileMgr.getFile(HeadersFilename.str(), /*openFile=*/true)))
Reid Spencer5f016e22007-07-11 17:01:13 +0000750 return 0;
751 }
Mike Stump1eb44332009-09-09 15:08:12 +0000752
Reid Spencer5f016e22007-07-11 17:01:13 +0000753 // This file is a system header or C++ unfriendly if the old file is.
Ted Kremenekca63fa02008-02-24 03:55:14 +0000754 //
Chris Lattnerc9dde4f2008-02-25 21:38:21 +0000755 // Note that the temporary 'DirInfo' is required here, as either call to
756 // getFileInfo could resize the vector and we don't want to rely on order
757 // of evaluation.
758 unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo;
759 getFileInfo(FE).DirInfo = DirInfo;
Reid Spencer5f016e22007-07-11 17:01:13 +0000760 return FE;
761}
762
Chandler Carruthcb381ea2011-12-09 01:33:57 +0000763/// \brief Helper static function to normalize a path for injection into
764/// a synthetic header.
765/*static*/ std::string
766HeaderSearch::NormalizeDashIncludePath(StringRef File, FileManager &FileMgr) {
767 // Implicit include paths should be resolved relative to the current
768 // working directory first, and then use the regular header search
769 // mechanism. The proper way to handle this is to have the
770 // predefines buffer located at the current working directory, but
771 // it has no file entry. For now, workaround this by using an
772 // absolute path if we find the file here, and otherwise letting
773 // header search handle it.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000774 SmallString<128> Path(File);
Chandler Carruthcb381ea2011-12-09 01:33:57 +0000775 llvm::sys::fs::make_absolute(Path);
776 bool exists;
777 if (llvm::sys::fs::exists(Path.str(), exists) || !exists)
778 Path = File;
779 else if (exists)
780 FileMgr.getFile(File);
781
782 return Lexer::Stringify(Path.str());
783}
784
Reid Spencer5f016e22007-07-11 17:01:13 +0000785//===----------------------------------------------------------------------===//
786// File Info Management.
787//===----------------------------------------------------------------------===//
788
Douglas Gregor8f8d5812011-09-17 05:35:18 +0000789/// \brief Merge the header file info provided by \p OtherHFI into the current
790/// header file info (\p HFI)
791static void mergeHeaderFileInfo(HeaderFileInfo &HFI,
792 const HeaderFileInfo &OtherHFI) {
793 HFI.isImport |= OtherHFI.isImport;
794 HFI.isPragmaOnce |= OtherHFI.isPragmaOnce;
795 HFI.NumIncludes += OtherHFI.NumIncludes;
796
797 if (!HFI.ControllingMacro && !HFI.ControllingMacroID) {
798 HFI.ControllingMacro = OtherHFI.ControllingMacro;
799 HFI.ControllingMacroID = OtherHFI.ControllingMacroID;
800 }
801
802 if (OtherHFI.External) {
803 HFI.DirInfo = OtherHFI.DirInfo;
804 HFI.External = OtherHFI.External;
805 HFI.IndexHeaderMapHeader = OtherHFI.IndexHeaderMapHeader;
806 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000807
Douglas Gregor8f8d5812011-09-17 05:35:18 +0000808 if (HFI.Framework.empty())
809 HFI.Framework = OtherHFI.Framework;
810
811 HFI.Resolved = true;
812}
813
Steve Naroff83d63c72009-04-24 20:03:17 +0000814/// getFileInfo - Return the HeaderFileInfo structure for the specified
Reid Spencer5f016e22007-07-11 17:01:13 +0000815/// FileEntry.
Steve Naroff83d63c72009-04-24 20:03:17 +0000816HeaderFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000817 if (FE->getUID() >= FileInfo.size())
818 FileInfo.resize(FE->getUID()+1);
Douglas Gregorcfbf1c72011-02-10 17:09:37 +0000819
820 HeaderFileInfo &HFI = FileInfo[FE->getUID()];
Douglas Gregor8f8d5812011-09-17 05:35:18 +0000821 if (ExternalSource && !HFI.Resolved)
822 mergeHeaderFileInfo(HFI, ExternalSource->GetHeaderFileInfo(FE));
Douglas Gregorcfbf1c72011-02-10 17:09:37 +0000823 return HFI;
Mike Stump1eb44332009-09-09 15:08:12 +0000824}
Reid Spencer5f016e22007-07-11 17:01:13 +0000825
Douglas Gregordd3e5542011-05-04 00:14:37 +0000826bool HeaderSearch::isFileMultipleIncludeGuarded(const FileEntry *File) {
827 // Check if we've ever seen this file as a header.
828 if (File->getUID() >= FileInfo.size())
829 return false;
830
831 // Resolve header file info from the external source, if needed.
832 HeaderFileInfo &HFI = FileInfo[File->getUID()];
Douglas Gregor8f8d5812011-09-17 05:35:18 +0000833 if (ExternalSource && !HFI.Resolved)
834 mergeHeaderFileInfo(HFI, ExternalSource->GetHeaderFileInfo(File));
Douglas Gregordd3e5542011-05-04 00:14:37 +0000835
Argyrios Kyrtzidis44dfff62012-12-10 20:08:37 +0000836 return HFI.isPragmaOnce || HFI.isImport ||
837 HFI.ControllingMacro || HFI.ControllingMacroID;
Douglas Gregordd3e5542011-05-04 00:14:37 +0000838}
839
Steve Naroff83d63c72009-04-24 20:03:17 +0000840void HeaderSearch::setHeaderFileInfoForUID(HeaderFileInfo HFI, unsigned UID) {
841 if (UID >= FileInfo.size())
842 FileInfo.resize(UID+1);
Douglas Gregorcfbf1c72011-02-10 17:09:37 +0000843 HFI.Resolved = true;
Steve Naroff83d63c72009-04-24 20:03:17 +0000844 FileInfo[UID] = HFI;
845}
846
Reid Spencer5f016e22007-07-11 17:01:13 +0000847bool HeaderSearch::ShouldEnterIncludeFile(const FileEntry *File, bool isImport){
848 ++NumIncluded; // Count # of attempted #includes.
849
850 // Get information about this file.
Steve Naroff83d63c72009-04-24 20:03:17 +0000851 HeaderFileInfo &FileInfo = getFileInfo(File);
Mike Stump1eb44332009-09-09 15:08:12 +0000852
Reid Spencer5f016e22007-07-11 17:01:13 +0000853 // If this is a #import directive, check that we have not already imported
854 // this header.
855 if (isImport) {
856 // If this has already been imported, don't import it again.
857 FileInfo.isImport = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000858
Reid Spencer5f016e22007-07-11 17:01:13 +0000859 // Has this already been #import'ed or #include'd?
860 if (FileInfo.NumIncludes) return false;
861 } else {
862 // Otherwise, if this is a #include of a file that was previously #import'd
863 // or if this is the second #include of a #pragma once file, ignore it.
864 if (FileInfo.isImport)
865 return false;
866 }
Mike Stump1eb44332009-09-09 15:08:12 +0000867
Reid Spencer5f016e22007-07-11 17:01:13 +0000868 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
869 // if the macro that guards it is defined, we know the #include has no effect.
Mike Stump1eb44332009-09-09 15:08:12 +0000870 if (const IdentifierInfo *ControllingMacro
Douglas Gregor8c5a7602009-04-25 23:30:02 +0000871 = FileInfo.getControllingMacro(ExternalLookup))
872 if (ControllingMacro->hasMacroDefinition()) {
873 ++NumMultiIncludeFileOptzn;
874 return false;
875 }
Mike Stump1eb44332009-09-09 15:08:12 +0000876
Reid Spencer5f016e22007-07-11 17:01:13 +0000877 // Increment the number of times this file has been included.
878 ++FileInfo.NumIncludes;
Mike Stump1eb44332009-09-09 15:08:12 +0000879
Reid Spencer5f016e22007-07-11 17:01:13 +0000880 return true;
881}
882
Ted Kremenekd1194fb2011-07-26 23:46:11 +0000883size_t HeaderSearch::getTotalMemory() const {
884 return SearchDirs.capacity()
Ted Kremenekeabea452011-07-27 18:41:18 +0000885 + llvm::capacity_in_bytes(FileInfo)
886 + llvm::capacity_in_bytes(HeaderMaps)
Ted Kremenekd1194fb2011-07-26 23:46:11 +0000887 + LookupFileCache.getAllocator().getTotalMemory()
888 + FrameworkMap.getAllocator().getTotalMemory();
889}
Douglas Gregor65e02fa2011-07-28 04:45:53 +0000890
891StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) {
892 return FrameworkNames.GetOrCreateValue(Framework).getKey();
893}
Douglas Gregora30cfe52011-11-11 19:10:28 +0000894
895bool HeaderSearch::hasModuleMap(StringRef FileName,
896 const DirectoryEntry *Root) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000897 SmallVector<const DirectoryEntry *, 2> FixUpDirectories;
Douglas Gregora30cfe52011-11-11 19:10:28 +0000898
899 StringRef DirName = FileName;
900 do {
901 // Get the parent directory name.
902 DirName = llvm::sys::path::parent_path(DirName);
903 if (DirName.empty())
904 return false;
905
906 // Determine whether this directory exists.
907 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
908 if (!Dir)
909 return false;
910
Douglas Gregorcf70d782011-11-12 00:05:07 +0000911 // Try to load the module map file in this directory.
Douglas Gregor26697972011-11-12 00:22:19 +0000912 switch (loadModuleMapFile(Dir)) {
913 case LMM_NewlyLoaded:
914 case LMM_AlreadyLoaded:
Douglas Gregorcf70d782011-11-12 00:05:07 +0000915 // Success. All of the directories we stepped through inherit this module
916 // map file.
Douglas Gregora30cfe52011-11-11 19:10:28 +0000917 for (unsigned I = 0, N = FixUpDirectories.size(); I != N; ++I)
918 DirectoryHasModuleMap[FixUpDirectories[I]] = true;
919
920 return true;
Douglas Gregor26697972011-11-12 00:22:19 +0000921
922 case LMM_NoDirectory:
923 case LMM_InvalidModuleMap:
924 break;
Douglas Gregora30cfe52011-11-11 19:10:28 +0000925 }
Douglas Gregora30cfe52011-11-11 19:10:28 +0000926
Douglas Gregorcf70d782011-11-12 00:05:07 +0000927 // If we hit the top of our search, we're done.
928 if (Dir == Root)
929 return false;
930
Douglas Gregora30cfe52011-11-11 19:10:28 +0000931 // Keep track of all of the directories we checked, so we can mark them as
932 // having module maps if we eventually do find a module map.
933 FixUpDirectories.push_back(Dir);
934 } while (true);
Douglas Gregora30cfe52011-11-11 19:10:28 +0000935}
936
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000937Module *HeaderSearch::findModuleForHeader(const FileEntry *File) {
Douglas Gregor51f564f2011-12-31 04:05:44 +0000938 if (Module *Mod = ModMap.findModuleForHeader(File))
939 return Mod;
Douglas Gregor65f3b5e2011-11-11 22:18:48 +0000940
Douglas Gregorc69c42e2011-11-17 22:44:56 +0000941 return 0;
Douglas Gregora30cfe52011-11-11 19:10:28 +0000942}
943
Douglas Gregordb1cde72011-11-16 00:09:06 +0000944bool HeaderSearch::loadModuleMapFile(const FileEntry *File) {
945 const DirectoryEntry *Dir = File->getDir();
946
947 llvm::DenseMap<const DirectoryEntry *, bool>::iterator KnownDir
948 = DirectoryHasModuleMap.find(Dir);
949 if (KnownDir != DirectoryHasModuleMap.end())
950 return !KnownDir->second;
951
952 bool Result = ModMap.parseModuleMapFile(File);
Douglas Gregor4813442c2011-12-07 21:25:07 +0000953 if (!Result && llvm::sys::path::filename(File->getName()) == "module.map") {
954 // If the file we loaded was a module.map, look for the corresponding
955 // module_private.map.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000956 SmallString<128> PrivateFilename(Dir->getName());
Douglas Gregor4813442c2011-12-07 21:25:07 +0000957 llvm::sys::path::append(PrivateFilename, "module_private.map");
958 if (const FileEntry *PrivateFile = FileMgr.getFile(PrivateFilename))
959 Result = ModMap.parseModuleMapFile(PrivateFile);
960 }
961
962 DirectoryHasModuleMap[Dir] = !Result;
Douglas Gregordb1cde72011-11-16 00:09:06 +0000963 return Result;
964}
965
Douglas Gregore434ec72012-01-29 17:08:11 +0000966Module *HeaderSearch::loadFrameworkModule(StringRef Name,
967 const DirectoryEntry *Dir,
968 bool IsSystem) {
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000969 if (Module *Module = ModMap.findModule(Name))
Douglas Gregor2821c7f2011-11-17 01:41:17 +0000970 return Module;
971
972 // Try to load a module map file.
973 switch (loadModuleMapFile(Dir)) {
974 case LMM_InvalidModuleMap:
975 break;
976
977 case LMM_AlreadyLoaded:
978 case LMM_NoDirectory:
979 return 0;
980
981 case LMM_NewlyLoaded:
982 return ModMap.findModule(Name);
983 }
Douglas Gregora8c6fea2012-01-13 22:31:52 +0000984
Douglas Gregor7005b902013-01-10 01:43:00 +0000985 // Figure out the top-level framework directory and the submodule path from
986 // that top-level framework to the requested framework.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000987 SmallVector<std::string, 2> SubmodulePath;
Douglas Gregora8c6fea2012-01-13 22:31:52 +0000988 SubmodulePath.push_back(Name);
Douglas Gregor7005b902013-01-10 01:43:00 +0000989 const DirectoryEntry *TopFrameworkDir
990 = ::getTopFrameworkDir(FileMgr, Dir->getName(), SubmodulePath);
Douglas Gregor82e52372012-11-06 19:39:40 +0000991
Douglas Gregor82e52372012-11-06 19:39:40 +0000992
Douglas Gregora8c6fea2012-01-13 22:31:52 +0000993 // Try to infer a module map from the top-level framework directory.
994 Module *Result = ModMap.inferFrameworkModule(SubmodulePath.back(),
Douglas Gregora1f1fad2012-01-27 19:52:33 +0000995 TopFrameworkDir,
996 IsSystem,
Douglas Gregora8c6fea2012-01-13 22:31:52 +0000997 /*Parent=*/0);
Douglas Gregor7005b902013-01-10 01:43:00 +0000998 if (!Result)
999 return 0;
Douglas Gregora8c6fea2012-01-13 22:31:52 +00001000
1001 // Follow the submodule path to find the requested (sub)framework module
1002 // within the top-level framework module.
1003 SubmodulePath.pop_back();
1004 while (!SubmodulePath.empty() && Result) {
1005 Result = ModMap.lookupModuleQualified(SubmodulePath.back(), Result);
1006 SubmodulePath.pop_back();
1007 }
1008 return Result;
Douglas Gregor2821c7f2011-11-17 01:41:17 +00001009}
1010
Douglas Gregordb1cde72011-11-16 00:09:06 +00001011
Douglas Gregor26697972011-11-12 00:22:19 +00001012HeaderSearch::LoadModuleMapResult
1013HeaderSearch::loadModuleMapFile(StringRef DirName) {
Douglas Gregorcf70d782011-11-12 00:05:07 +00001014 if (const DirectoryEntry *Dir = FileMgr.getDirectory(DirName))
1015 return loadModuleMapFile(Dir);
1016
Douglas Gregor26697972011-11-12 00:22:19 +00001017 return LMM_NoDirectory;
Douglas Gregorcf70d782011-11-12 00:05:07 +00001018}
1019
Douglas Gregor26697972011-11-12 00:22:19 +00001020HeaderSearch::LoadModuleMapResult
1021HeaderSearch::loadModuleMapFile(const DirectoryEntry *Dir) {
Douglas Gregorcf70d782011-11-12 00:05:07 +00001022 llvm::DenseMap<const DirectoryEntry *, bool>::iterator KnownDir
1023 = DirectoryHasModuleMap.find(Dir);
1024 if (KnownDir != DirectoryHasModuleMap.end())
Douglas Gregor26697972011-11-12 00:22:19 +00001025 return KnownDir->second? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
Douglas Gregorcf70d782011-11-12 00:05:07 +00001026
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001027 SmallString<128> ModuleMapFileName;
Douglas Gregorcf70d782011-11-12 00:05:07 +00001028 ModuleMapFileName += Dir->getName();
Douglas Gregor587986e2011-12-07 02:23:45 +00001029 unsigned ModuleMapDirNameLen = ModuleMapFileName.size();
Douglas Gregorcf70d782011-11-12 00:05:07 +00001030 llvm::sys::path::append(ModuleMapFileName, "module.map");
1031 if (const FileEntry *ModuleMapFile = FileMgr.getFile(ModuleMapFileName)) {
1032 // We have found a module map file. Try to parse it.
Douglas Gregor587986e2011-12-07 02:23:45 +00001033 if (ModMap.parseModuleMapFile(ModuleMapFile)) {
1034 // No suitable module map.
1035 DirectoryHasModuleMap[Dir] = false;
1036 return LMM_InvalidModuleMap;
Douglas Gregorcf70d782011-11-12 00:05:07 +00001037 }
Douglas Gregor587986e2011-12-07 02:23:45 +00001038
1039 // This directory has a module map.
1040 DirectoryHasModuleMap[Dir] = true;
1041
1042 // Check whether there is a private module map that we need to load as well.
1043 ModuleMapFileName.erase(ModuleMapFileName.begin() + ModuleMapDirNameLen,
1044 ModuleMapFileName.end());
1045 llvm::sys::path::append(ModuleMapFileName, "module_private.map");
1046 if (const FileEntry *PrivateModuleMapFile
1047 = FileMgr.getFile(ModuleMapFileName)) {
1048 if (ModMap.parseModuleMapFile(PrivateModuleMapFile)) {
1049 // No suitable module map.
1050 DirectoryHasModuleMap[Dir] = false;
1051 return LMM_InvalidModuleMap;
1052 }
1053 }
1054
1055 return LMM_NewlyLoaded;
Douglas Gregorcf70d782011-11-12 00:05:07 +00001056 }
1057
1058 // No suitable module map.
1059 DirectoryHasModuleMap[Dir] = false;
Douglas Gregor26697972011-11-12 00:22:19 +00001060 return LMM_InvalidModuleMap;
Douglas Gregorcf70d782011-11-12 00:05:07 +00001061}
Douglas Gregora30cfe52011-11-11 19:10:28 +00001062
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001063void HeaderSearch::collectAllModules(SmallVectorImpl<Module *> &Modules) {
Douglas Gregorc5b2e582012-01-29 18:15:03 +00001064 Modules.clear();
1065
1066 // Load module maps for each of the header search directories.
1067 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
1068 if (SearchDirs[Idx].isFramework()) {
1069 llvm::error_code EC;
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001070 SmallString<128> DirNative;
Douglas Gregorc5b2e582012-01-29 18:15:03 +00001071 llvm::sys::path::native(SearchDirs[Idx].getFrameworkDir()->getName(),
1072 DirNative);
1073
1074 // Search each of the ".framework" directories to load them as modules.
1075 bool IsSystem = SearchDirs[Idx].getDirCharacteristic() != SrcMgr::C_User;
1076 for (llvm::sys::fs::directory_iterator Dir(DirNative.str(), EC), DirEnd;
1077 Dir != DirEnd && !EC; Dir.increment(EC)) {
1078 if (llvm::sys::path::extension(Dir->path()) != ".framework")
1079 continue;
1080
1081 const DirectoryEntry *FrameworkDir = FileMgr.getDirectory(Dir->path());
1082 if (!FrameworkDir)
1083 continue;
1084
1085 // Load this framework module.
1086 loadFrameworkModule(llvm::sys::path::stem(Dir->path()), FrameworkDir,
1087 IsSystem);
1088 }
1089 continue;
1090 }
1091
1092 // FIXME: Deal with header maps.
1093 if (SearchDirs[Idx].isHeaderMap())
1094 continue;
1095
1096 // Try to load a module map file for the search directory.
1097 loadModuleMapFile(SearchDirs[Idx].getDir());
1098
1099 // Try to load module map files for immediate subdirectories of this search
1100 // directory.
1101 llvm::error_code EC;
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001102 SmallString<128> DirNative;
Douglas Gregorc5b2e582012-01-29 18:15:03 +00001103 llvm::sys::path::native(SearchDirs[Idx].getDir()->getName(), DirNative);
1104 for (llvm::sys::fs::directory_iterator Dir(DirNative.str(), EC), DirEnd;
1105 Dir != DirEnd && !EC; Dir.increment(EC)) {
1106 loadModuleMapFile(Dir->path());
1107 }
1108 }
1109
1110 // Populate the list of modules.
1111 for (ModuleMap::module_iterator M = ModMap.module_begin(),
1112 MEnd = ModMap.module_end();
1113 M != MEnd; ++M) {
1114 Modules.push_back(M->getValue());
1115 }
1116}