blob: 64329255184252b27c68f619bcc60009067e92c0 [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 Gregor713b7c02013-01-26 00:55:12 +0000271/// FIXME: HACK HACK HACK!
272static llvm::DenseMap<const DirectoryEntry *, const DirectoryEntry *>
273 TopFrameworkDirs;
274
Douglas Gregor7005b902013-01-10 01:43:00 +0000275/// \brief Given a framework directory, find the top-most framework directory.
276///
277/// \param FileMgr The file manager to use for directory lookups.
278/// \param DirName The name of the framework directory.
279/// \param SubmodulePath Will be populated with the submodule path from the
280/// returned top-level module to the originally named framework.
281static const DirectoryEntry *
282getTopFrameworkDir(FileManager &FileMgr, StringRef DirName,
283 SmallVectorImpl<std::string> &SubmodulePath) {
284 assert(llvm::sys::path::extension(DirName) == ".framework" &&
285 "Not a framework directory");
286
Douglas Gregor7005b902013-01-10 01:43:00 +0000287 // Note: as an egregious but useful hack we use the real path here, because
288 // frameworks moving between top-level frameworks to embedded frameworks tend
289 // to be symlinked, and we base the logical structure of modules on the
290 // physical layout. In particular, we need to deal with crazy includes like
291 //
292 // #include <Foo/Frameworks/Bar.framework/Headers/Wibble.h>
293 //
294 // where 'Bar' used to be embedded in 'Foo', is now a top-level framework
295 // which one should access with, e.g.,
296 //
297 // #include <Bar/Wibble.h>
298 //
299 // Similar issues occur when a top-level framework has moved into an
300 // embedded framework.
Douglas Gregor7005b902013-01-10 01:43:00 +0000301 const DirectoryEntry *TopFrameworkDir = FileMgr.getDirectory(DirName);
Douglas Gregor713b7c02013-01-26 00:55:12 +0000302 DirName = FileMgr.getCanonicalName(TopFrameworkDir);
Douglas Gregor7005b902013-01-10 01:43:00 +0000303 do {
304 // Get the parent directory name.
305 DirName = llvm::sys::path::parent_path(DirName);
306 if (DirName.empty())
307 break;
308
309 // Determine whether this directory exists.
310 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
311 if (!Dir)
312 break;
313
314 // If this is a framework directory, then we're a subframework of this
315 // framework.
316 if (llvm::sys::path::extension(DirName) == ".framework") {
317 SubmodulePath.push_back(llvm::sys::path::stem(DirName));
318 TopFrameworkDir = Dir;
319 }
320 } while (true);
321
322 return TopFrameworkDir;
323}
Chris Lattnerdf772332007-12-17 07:52:39 +0000324
Chris Lattnerafded5b2007-12-17 08:13:48 +0000325/// DoFrameworkLookup - Do a lookup of the specified file in the current
326/// DirectoryLookup, which is a framework directory.
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000327const FileEntry *DirectoryLookup::DoFrameworkLookup(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000328 StringRef Filename,
Manuel Klimek74124942011-04-26 21:50:03 +0000329 HeaderSearch &HS,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000330 SmallVectorImpl<char> *SearchPath,
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000331 SmallVectorImpl<char> *RelativePath,
Daniel Dunbar85ff9692012-04-05 17:10:06 +0000332 Module **SuggestedModule,
333 bool &InUserSpecifiedSystemFramework) const
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000334{
Chris Lattnerafded5b2007-12-17 08:13:48 +0000335 FileManager &FileMgr = HS.getFileMgr();
Mike Stump1eb44332009-09-09 15:08:12 +0000336
Reid Spencer5f016e22007-07-11 17:01:13 +0000337 // Framework names must have a '/' in the filename.
Chris Lattnera1394812010-01-10 01:35:12 +0000338 size_t SlashPos = Filename.find('/');
Chris Lattner5f9e2722011-07-23 10:55:15 +0000339 if (SlashPos == StringRef::npos) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000340
Chris Lattnerafded5b2007-12-17 08:13:48 +0000341 // Find out if this is the home for the specified framework, by checking
Daniel Dunbar9ee35f92012-04-05 17:09:40 +0000342 // HeaderSearch. Possible answers are yes/no and unknown.
343 HeaderSearch::FrameworkCacheEntry &CacheEntry =
Chris Lattnera1394812010-01-10 01:35:12 +0000344 HS.LookupFrameworkCache(Filename.substr(0, SlashPos));
Mike Stump1eb44332009-09-09 15:08:12 +0000345
Chris Lattnerafded5b2007-12-17 08:13:48 +0000346 // If it is known and in some other directory, fail.
Daniel Dunbar9ee35f92012-04-05 17:09:40 +0000347 if (CacheEntry.Directory && CacheEntry.Directory != getFrameworkDir())
Reid Spencer5f016e22007-07-11 17:01:13 +0000348 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000349
Chris Lattnerafded5b2007-12-17 08:13:48 +0000350 // Otherwise, construct the path to this framework dir.
Mike Stump1eb44332009-09-09 15:08:12 +0000351
Reid Spencer5f016e22007-07-11 17:01:13 +0000352 // FrameworkName = "/System/Library/Frameworks/"
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000353 SmallString<1024> FrameworkName;
Chris Lattnerafded5b2007-12-17 08:13:48 +0000354 FrameworkName += getFrameworkDir()->getName();
Reid Spencer5f016e22007-07-11 17:01:13 +0000355 if (FrameworkName.empty() || FrameworkName.back() != '/')
356 FrameworkName.push_back('/');
Mike Stump1eb44332009-09-09 15:08:12 +0000357
Reid Spencer5f016e22007-07-11 17:01:13 +0000358 // FrameworkName = "/System/Library/Frameworks/Cocoa"
Douglas Gregor2821c7f2011-11-17 01:41:17 +0000359 StringRef ModuleName(Filename.begin(), SlashPos);
360 FrameworkName += ModuleName;
Mike Stump1eb44332009-09-09 15:08:12 +0000361
Reid Spencer5f016e22007-07-11 17:01:13 +0000362 // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/"
363 FrameworkName += ".framework/";
Mike Stump1eb44332009-09-09 15:08:12 +0000364
Daniel Dunbar9ee35f92012-04-05 17:09:40 +0000365 // If the cache entry was unresolved, populate it now.
366 if (CacheEntry.Directory == 0) {
Chris Lattnerafded5b2007-12-17 08:13:48 +0000367 HS.IncrementFrameworkLookupCount();
Mike Stump1eb44332009-09-09 15:08:12 +0000368
Reid Spencer5f016e22007-07-11 17:01:13 +0000369 // If the framework dir doesn't exist, we fail.
Daniel Dunbar85ff9692012-04-05 17:10:06 +0000370 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName.str());
371 if (Dir == 0) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000372
Reid Spencer5f016e22007-07-11 17:01:13 +0000373 // Otherwise, if it does, remember that this is the right direntry for this
374 // framework.
Daniel Dunbar9ee35f92012-04-05 17:09:40 +0000375 CacheEntry.Directory = getFrameworkDir();
Daniel Dunbar85ff9692012-04-05 17:10:06 +0000376
377 // If this is a user search directory, check if the framework has been
378 // user-specified as a system framework.
379 if (getDirCharacteristic() == SrcMgr::C_User) {
380 SmallString<1024> SystemFrameworkMarker(FrameworkName);
381 SystemFrameworkMarker += ".system_framework";
382 if (llvm::sys::fs::exists(SystemFrameworkMarker.str())) {
383 CacheEntry.IsUserSpecifiedSystemFramework = true;
384 }
385 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000386 }
Mike Stump1eb44332009-09-09 15:08:12 +0000387
Daniel Dunbar85ff9692012-04-05 17:10:06 +0000388 // Set the 'user-specified system framework' flag.
389 InUserSpecifiedSystemFramework = CacheEntry.IsUserSpecifiedSystemFramework;
390
Manuel Klimek74124942011-04-26 21:50:03 +0000391 if (RelativePath != NULL) {
392 RelativePath->clear();
393 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
394 }
Douglas Gregor2821c7f2011-11-17 01:41:17 +0000395
Reid Spencer5f016e22007-07-11 17:01:13 +0000396 // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"
397 unsigned OrigSize = FrameworkName.size();
Mike Stump1eb44332009-09-09 15:08:12 +0000398
Reid Spencer5f016e22007-07-11 17:01:13 +0000399 FrameworkName += "Headers/";
Manuel Klimek74124942011-04-26 21:50:03 +0000400
401 if (SearchPath != NULL) {
402 SearchPath->clear();
403 // Without trailing '/'.
404 SearchPath->append(FrameworkName.begin(), FrameworkName.end()-1);
405 }
406
Chris Lattnera1394812010-01-10 01:35:12 +0000407 FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end());
Douglas Gregor7005b902013-01-10 01:43:00 +0000408 const FileEntry *FE = FileMgr.getFile(FrameworkName.str(),
409 /*openFile=*/!SuggestedModule);
410 if (!FE) {
411 // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"
412 const char *Private = "Private";
413 FrameworkName.insert(FrameworkName.begin()+OrigSize, Private,
414 Private+strlen(Private));
415 if (SearchPath != NULL)
416 SearchPath->insert(SearchPath->begin()+OrigSize, Private,
417 Private+strlen(Private));
418
419 FE = FileMgr.getFile(FrameworkName.str(), /*openFile=*/!SuggestedModule);
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000420 }
Mike Stump1eb44332009-09-09 15:08:12 +0000421
Douglas Gregor7005b902013-01-10 01:43:00 +0000422 // If we found the header and are allowed to suggest a module, do so now.
423 if (FE && SuggestedModule) {
424 // Find the framework in which this header occurs.
425 StringRef FrameworkPath = FE->getName();
426 bool FoundFramework = false;
427 do {
428 // Get the parent directory name.
429 FrameworkPath = llvm::sys::path::parent_path(FrameworkPath);
430 if (FrameworkPath.empty())
431 break;
Manuel Klimek74124942011-04-26 21:50:03 +0000432
Douglas Gregor7005b902013-01-10 01:43:00 +0000433 // Determine whether this directory exists.
434 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkPath);
435 if (!Dir)
436 break;
437
438 // If this is a framework directory, then we're a subframework of this
439 // framework.
440 if (llvm::sys::path::extension(FrameworkPath) == ".framework") {
441 FoundFramework = true;
442 break;
443 }
444 } while (true);
445
446 if (FoundFramework) {
447 // Find the top-level framework based on this framework.
448 SmallVector<std::string, 4> SubmodulePath;
449 const DirectoryEntry *TopFrameworkDir
450 = ::getTopFrameworkDir(FileMgr, FrameworkPath, SubmodulePath);
451
452 // Determine the name of the top-level framework.
453 StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
454
455 // Load this framework module. If that succeeds, find the suggested module
456 // for this header, if any.
457 bool IsSystem = getDirCharacteristic() != SrcMgr::C_User;
458 if (HS.loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystem)) {
459 *SuggestedModule = HS.findModuleForHeader(FE);
460 }
461 } else {
462 *SuggestedModule = HS.findModuleForHeader(FE);
463 }
464 }
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000465 return FE;
Reid Spencer5f016e22007-07-11 17:01:13 +0000466}
467
Douglas Gregordc58aa72012-01-30 06:01:29 +0000468void HeaderSearch::setTarget(const TargetInfo &Target) {
469 ModMap.setTarget(Target);
470}
471
Chris Lattnerdf772332007-12-17 07:52:39 +0000472
Chris Lattnerafded5b2007-12-17 08:13:48 +0000473//===----------------------------------------------------------------------===//
474// Header File Location.
475//===----------------------------------------------------------------------===//
476
477
James Dennett853519c2012-06-20 00:56:32 +0000478/// LookupFile - Given a "foo" or \<foo> reference, look up the indicated file,
Reid Spencer5f016e22007-07-11 17:01:13 +0000479/// return null on failure. isAngled indicates whether the file reference is
James Dennett853519c2012-06-20 00:56:32 +0000480/// for system \#include's or not (i.e. using <> instead of ""). CurFileEnt, if
481/// non-null, indicates where the \#including file is, in case a relative search
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000482/// is needed.
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000483const FileEntry *HeaderSearch::LookupFile(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000484 StringRef Filename,
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000485 bool isAngled,
486 const DirectoryLookup *FromDir,
487 const DirectoryLookup *&CurDir,
488 const FileEntry *CurFileEnt,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000489 SmallVectorImpl<char> *SearchPath,
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000490 SmallVectorImpl<char> *RelativePath,
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000491 Module **SuggestedModule,
Douglas Gregor1c2e9332011-11-20 17:46:46 +0000492 bool SkipCache)
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000493{
494 if (SuggestedModule)
Douglas Gregorc69c42e2011-11-17 22:44:56 +0000495 *SuggestedModule = 0;
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000496
Reid Spencer5f016e22007-07-11 17:01:13 +0000497 // If 'Filename' is absolute, check to see if it exists and no searching.
Michael J. Spencer256053b2010-12-17 21:22:22 +0000498 if (llvm::sys::path::is_absolute(Filename)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000499 CurDir = 0;
500
501 // If this was an #include_next "/absolute/file", fail.
502 if (FromDir) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000503
Manuel Klimek74124942011-04-26 21:50:03 +0000504 if (SearchPath != NULL)
505 SearchPath->clear();
506 if (RelativePath != NULL) {
507 RelativePath->clear();
508 RelativePath->append(Filename.begin(), Filename.end());
509 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000510 // Otherwise, just return the file.
Argyrios Kyrtzidis3cd01282011-03-16 19:17:25 +0000511 return FileMgr.getFile(Filename, /*openFile=*/true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000512 }
Mike Stump1eb44332009-09-09 15:08:12 +0000513
Douglas Gregor65e02fa2011-07-28 04:45:53 +0000514 // Unless disabled, check to see if the file is in the #includer's
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000515 // directory. This has to be based on CurFileEnt, not CurDir, because
516 // CurFileEnt could be a #include of a subdirectory (#include "foo/bar.h") and
Chris Lattnerdf772332007-12-17 07:52:39 +0000517 // a subsequent include of "baz.h" should resolve to "whatever/foo/baz.h".
518 // This search is not done for <> headers.
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000519 if (CurFileEnt && !isAngled && !NoCurDirSearch) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000520 SmallString<1024> TmpDir;
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000521 // Concatenate the requested file onto the directory.
522 // FIXME: Portability. Filename concatenation should be in sys::Path.
523 TmpDir += CurFileEnt->getDir()->getName();
524 TmpDir.push_back('/');
525 TmpDir.append(Filename.begin(), Filename.end());
Argyrios Kyrtzidis3cd01282011-03-16 19:17:25 +0000526 if (const FileEntry *FE = FileMgr.getFile(TmpDir.str(),/*openFile=*/true)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000527 // Leave CurDir unset.
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000528 // This file is a system header or C++ unfriendly if the old file is.
529 //
Douglas Gregor21efbb62012-08-13 15:47:39 +0000530 // Note that we only use one of FromHFI/ToHFI at once, due to potential
531 // reallocation of the underlying vector potentially making the first
532 // reference binding dangling.
533 HeaderFileInfo &FromHFI = getFileInfo(CurFileEnt);
534 unsigned DirInfo = FromHFI.DirInfo;
535 bool IndexHeaderMapHeader = FromHFI.IndexHeaderMapHeader;
536 StringRef Framework = FromHFI.Framework;
537
538 HeaderFileInfo &ToHFI = getFileInfo(FE);
539 ToHFI.DirInfo = DirInfo;
540 ToHFI.IndexHeaderMapHeader = IndexHeaderMapHeader;
541 ToHFI.Framework = Framework;
542
Manuel Klimek74124942011-04-26 21:50:03 +0000543 if (SearchPath != NULL) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000544 StringRef SearchPathRef(CurFileEnt->getDir()->getName());
Manuel Klimek74124942011-04-26 21:50:03 +0000545 SearchPath->clear();
546 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
547 }
548 if (RelativePath != NULL) {
549 RelativePath->clear();
550 RelativePath->append(Filename.begin(), Filename.end());
551 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000552 return FE;
553 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000554 }
Mike Stump1eb44332009-09-09 15:08:12 +0000555
Reid Spencer5f016e22007-07-11 17:01:13 +0000556 CurDir = 0;
557
558 // If this is a system #include, ignore the user #include locs.
Nico Weber74a5fd82011-05-24 04:31:14 +0000559 unsigned i = isAngled ? AngledDirIdx : 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000560
Reid Spencer5f016e22007-07-11 17:01:13 +0000561 // If this is a #include_next request, start searching after the directory the
562 // file was found in.
563 if (FromDir)
564 i = FromDir-&SearchDirs[0];
Mike Stump1eb44332009-09-09 15:08:12 +0000565
Chris Lattner9960ae82007-07-22 07:28:00 +0000566 // Cache all of the lookups performed by this method. Many headers are
567 // multiply included, and the "pragma once" optimization prevents them from
568 // being relex/pp'd, but they would still have to search through a
569 // (potentially huge) series of SearchDirs to find it.
570 std::pair<unsigned, unsigned> &CacheLookup =
Chris Lattnera1394812010-01-10 01:35:12 +0000571 LookupFileCache.GetOrCreateValue(Filename).getValue();
Chris Lattner9960ae82007-07-22 07:28:00 +0000572
573 // If the entry has been previously looked up, the first value will be
574 // non-zero. If the value is equal to i (the start point of our search), then
575 // this is a matching hit.
Douglas Gregor1c2e9332011-11-20 17:46:46 +0000576 if (!SkipCache && CacheLookup.first == i+1) {
Chris Lattner9960ae82007-07-22 07:28:00 +0000577 // Skip querying potentially lots of directories for this lookup.
578 i = CacheLookup.second;
579 } else {
580 // Otherwise, this is the first query, or the previous query didn't match
581 // our search start. We will fill in our found location below, so prime the
582 // start point value.
583 CacheLookup.first = i+1;
584 }
Mike Stump1eb44332009-09-09 15:08:12 +0000585
Reid Spencer5f016e22007-07-11 17:01:13 +0000586 // Check each directory in sequence to see if it contains this file.
587 for (; i != SearchDirs.size(); ++i) {
Daniel Dunbar85ff9692012-04-05 17:10:06 +0000588 bool InUserSpecifiedSystemFramework = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000589 const FileEntry *FE =
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000590 SearchDirs[i].LookupFile(Filename, *this, SearchPath, RelativePath,
Daniel Dunbar85ff9692012-04-05 17:10:06 +0000591 SuggestedModule, InUserSpecifiedSystemFramework);
Chris Lattnerafded5b2007-12-17 08:13:48 +0000592 if (!FE) continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000593
Chris Lattnerafded5b2007-12-17 08:13:48 +0000594 CurDir = &SearchDirs[i];
Mike Stump1eb44332009-09-09 15:08:12 +0000595
Chris Lattnerafded5b2007-12-17 08:13:48 +0000596 // This file is a system header or C++ unfriendly if the dir is.
Douglas Gregor65e02fa2011-07-28 04:45:53 +0000597 HeaderFileInfo &HFI = getFileInfo(FE);
598 HFI.DirInfo = CurDir->getDirCharacteristic();
Mike Stump1eb44332009-09-09 15:08:12 +0000599
Daniel Dunbar85ff9692012-04-05 17:10:06 +0000600 // If the directory characteristic is User but this framework was
601 // user-specified to be treated as a system framework, promote the
602 // characteristic.
603 if (HFI.DirInfo == SrcMgr::C_User && InUserSpecifiedSystemFramework)
604 HFI.DirInfo = SrcMgr::C_System;
605
Richard Smithf122a132012-06-13 20:27:03 +0000606 // If the filename matches a known system header prefix, override
607 // whether the file is a system header.
Richard Trieu4ef2f6a2012-06-13 20:52:36 +0000608 for (unsigned j = SystemHeaderPrefixes.size(); j; --j) {
609 if (Filename.startswith(SystemHeaderPrefixes[j-1].first)) {
610 HFI.DirInfo = SystemHeaderPrefixes[j-1].second ? SrcMgr::C_System
Richard Smithf122a132012-06-13 20:27:03 +0000611 : SrcMgr::C_User;
612 break;
613 }
614 }
615
Douglas Gregor65e02fa2011-07-28 04:45:53 +0000616 // If this file is found in a header map and uses the framework style of
617 // includes, then this header is part of a framework we're building.
618 if (CurDir->isIndexHeaderMap()) {
619 size_t SlashPos = Filename.find('/');
620 if (SlashPos != StringRef::npos) {
621 HFI.IndexHeaderMapHeader = 1;
622 HFI.Framework = getUniqueFrameworkName(StringRef(Filename.begin(),
623 SlashPos));
624 }
625 }
626
Chris Lattnerafded5b2007-12-17 08:13:48 +0000627 // Remember this location for the next lookup we do.
628 CacheLookup.second = i;
629 return FE;
Reid Spencer5f016e22007-07-11 17:01:13 +0000630 }
Mike Stump1eb44332009-09-09 15:08:12 +0000631
Douglas Gregor2c7b7802011-07-30 06:28:34 +0000632 // If we are including a file with a quoted include "foo.h" from inside
633 // a header in a framework that is currently being built, and we couldn't
634 // resolve "foo.h" any other way, change the include to <Foo/foo.h>, where
635 // "Foo" is the name of the framework in which the including header was found.
636 if (CurFileEnt && !isAngled && Filename.find('/') == StringRef::npos) {
637 HeaderFileInfo &IncludingHFI = getFileInfo(CurFileEnt);
638 if (IncludingHFI.IndexHeaderMapHeader) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000639 SmallString<128> ScratchFilename;
Douglas Gregor2c7b7802011-07-30 06:28:34 +0000640 ScratchFilename += IncludingHFI.Framework;
641 ScratchFilename += '/';
642 ScratchFilename += Filename;
643
644 const FileEntry *Result = LookupFile(ScratchFilename, /*isAngled=*/true,
645 FromDir, CurDir, CurFileEnt,
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000646 SearchPath, RelativePath,
647 SuggestedModule);
Douglas Gregor2c7b7802011-07-30 06:28:34 +0000648 std::pair<unsigned, unsigned> &CacheLookup
649 = LookupFileCache.GetOrCreateValue(Filename).getValue();
650 CacheLookup.second
651 = LookupFileCache.GetOrCreateValue(ScratchFilename).getValue().second;
652 return Result;
653 }
654 }
655
Chris Lattner9960ae82007-07-22 07:28:00 +0000656 // Otherwise, didn't find it. Remember we didn't find this.
657 CacheLookup.second = SearchDirs.size();
Reid Spencer5f016e22007-07-11 17:01:13 +0000658 return 0;
659}
660
661/// LookupSubframeworkHeader - Look up a subframework for the specified
James Dennett853519c2012-06-20 00:56:32 +0000662/// \#include file. For example, if \#include'ing <HIToolbox/HIToolbox.h> from
Reid Spencer5f016e22007-07-11 17:01:13 +0000663/// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
664/// is a subframework within Carbon.framework. If so, return the FileEntry
665/// for the designated file, otherwise return null.
666const FileEntry *HeaderSearch::
Chris Lattner5f9e2722011-07-23 10:55:15 +0000667LookupSubframeworkHeader(StringRef Filename,
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000668 const FileEntry *ContextFileEnt,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000669 SmallVectorImpl<char> *SearchPath,
670 SmallVectorImpl<char> *RelativePath) {
Chris Lattner9415a0c2008-02-01 05:34:02 +0000671 assert(ContextFileEnt && "No context file?");
Mike Stump1eb44332009-09-09 15:08:12 +0000672
Reid Spencer5f016e22007-07-11 17:01:13 +0000673 // Framework names must have a '/' in the filename. Find it.
Douglas Gregorefda0e82011-12-09 16:48:01 +0000674 // FIXME: Should we permit '\' on Windows?
Chris Lattnera1394812010-01-10 01:35:12 +0000675 size_t SlashPos = Filename.find('/');
Chris Lattner5f9e2722011-07-23 10:55:15 +0000676 if (SlashPos == StringRef::npos) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000677
Reid Spencer5f016e22007-07-11 17:01:13 +0000678 // Look up the base framework name of the ContextFileEnt.
679 const char *ContextName = ContextFileEnt->getName();
Mike Stump1eb44332009-09-09 15:08:12 +0000680
Reid Spencer5f016e22007-07-11 17:01:13 +0000681 // If the context info wasn't a framework, couldn't be a subframework.
Douglas Gregorefda0e82011-12-09 16:48:01 +0000682 const unsigned DotFrameworkLen = 10;
683 const char *FrameworkPos = strstr(ContextName, ".framework");
684 if (FrameworkPos == 0 ||
685 (FrameworkPos[DotFrameworkLen] != '/' &&
686 FrameworkPos[DotFrameworkLen] != '\\'))
Reid Spencer5f016e22007-07-11 17:01:13 +0000687 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000688
Daniel Dunbar9ee35f92012-04-05 17:09:40 +0000689 SmallString<1024> FrameworkName(ContextName, FrameworkPos+DotFrameworkLen+1);
Reid Spencer5f016e22007-07-11 17:01:13 +0000690
691 // Append Frameworks/HIToolbox.framework/
692 FrameworkName += "Frameworks/";
Chris Lattnera1394812010-01-10 01:35:12 +0000693 FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos);
Reid Spencer5f016e22007-07-11 17:01:13 +0000694 FrameworkName += ".framework/";
695
Daniel Dunbar9ee35f92012-04-05 17:09:40 +0000696 llvm::StringMapEntry<FrameworkCacheEntry> &CacheLookup =
Chris Lattner65382272010-11-21 09:55:08 +0000697 FrameworkMap.GetOrCreateValue(Filename.substr(0, SlashPos));
Mike Stump1eb44332009-09-09 15:08:12 +0000698
Reid Spencer5f016e22007-07-11 17:01:13 +0000699 // Some other location?
Daniel Dunbar9ee35f92012-04-05 17:09:40 +0000700 if (CacheLookup.getValue().Directory &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000701 CacheLookup.getKeyLength() == FrameworkName.size() &&
702 memcmp(CacheLookup.getKeyData(), &FrameworkName[0],
703 CacheLookup.getKeyLength()) != 0)
704 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000705
Reid Spencer5f016e22007-07-11 17:01:13 +0000706 // Cache subframework.
Daniel Dunbar9ee35f92012-04-05 17:09:40 +0000707 if (CacheLookup.getValue().Directory == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000708 ++NumSubFrameworkLookups;
Mike Stump1eb44332009-09-09 15:08:12 +0000709
Reid Spencer5f016e22007-07-11 17:01:13 +0000710 // If the framework dir doesn't exist, we fail.
Chris Lattner39b49bc2010-11-23 08:35:12 +0000711 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName.str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000712 if (Dir == 0) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000713
Reid Spencer5f016e22007-07-11 17:01:13 +0000714 // Otherwise, if it does, remember that this is the right direntry for this
715 // framework.
Daniel Dunbar9ee35f92012-04-05 17:09:40 +0000716 CacheLookup.getValue().Directory = Dir;
Reid Spencer5f016e22007-07-11 17:01:13 +0000717 }
Mike Stump1eb44332009-09-09 15:08:12 +0000718
Reid Spencer5f016e22007-07-11 17:01:13 +0000719 const FileEntry *FE = 0;
720
Manuel Klimek74124942011-04-26 21:50:03 +0000721 if (RelativePath != NULL) {
722 RelativePath->clear();
723 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
724 }
725
Reid Spencer5f016e22007-07-11 17:01:13 +0000726 // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000727 SmallString<1024> HeadersFilename(FrameworkName);
Reid Spencer5f016e22007-07-11 17:01:13 +0000728 HeadersFilename += "Headers/";
Manuel Klimek74124942011-04-26 21:50:03 +0000729 if (SearchPath != NULL) {
730 SearchPath->clear();
731 // Without trailing '/'.
732 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
733 }
734
Chris Lattnera1394812010-01-10 01:35:12 +0000735 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
Argyrios Kyrtzidis3cd01282011-03-16 19:17:25 +0000736 if (!(FE = FileMgr.getFile(HeadersFilename.str(), /*openFile=*/true))) {
Mike Stump1eb44332009-09-09 15:08:12 +0000737
Reid Spencer5f016e22007-07-11 17:01:13 +0000738 // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
739 HeadersFilename = FrameworkName;
740 HeadersFilename += "PrivateHeaders/";
Manuel Klimek74124942011-04-26 21:50:03 +0000741 if (SearchPath != NULL) {
742 SearchPath->clear();
743 // Without trailing '/'.
744 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
745 }
746
Chris Lattnera1394812010-01-10 01:35:12 +0000747 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
Argyrios Kyrtzidis3cd01282011-03-16 19:17:25 +0000748 if (!(FE = FileMgr.getFile(HeadersFilename.str(), /*openFile=*/true)))
Reid Spencer5f016e22007-07-11 17:01:13 +0000749 return 0;
750 }
Mike Stump1eb44332009-09-09 15:08:12 +0000751
Reid Spencer5f016e22007-07-11 17:01:13 +0000752 // This file is a system header or C++ unfriendly if the old file is.
Ted Kremenekca63fa02008-02-24 03:55:14 +0000753 //
Chris Lattnerc9dde4f2008-02-25 21:38:21 +0000754 // Note that the temporary 'DirInfo' is required here, as either call to
755 // getFileInfo could resize the vector and we don't want to rely on order
756 // of evaluation.
757 unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo;
758 getFileInfo(FE).DirInfo = DirInfo;
Reid Spencer5f016e22007-07-11 17:01:13 +0000759 return FE;
760}
761
Chandler Carruthcb381ea2011-12-09 01:33:57 +0000762/// \brief Helper static function to normalize a path for injection into
763/// a synthetic header.
764/*static*/ std::string
765HeaderSearch::NormalizeDashIncludePath(StringRef File, FileManager &FileMgr) {
766 // Implicit include paths should be resolved relative to the current
767 // working directory first, and then use the regular header search
768 // mechanism. The proper way to handle this is to have the
769 // predefines buffer located at the current working directory, but
770 // it has no file entry. For now, workaround this by using an
771 // absolute path if we find the file here, and otherwise letting
772 // header search handle it.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000773 SmallString<128> Path(File);
Chandler Carruthcb381ea2011-12-09 01:33:57 +0000774 llvm::sys::fs::make_absolute(Path);
775 bool exists;
776 if (llvm::sys::fs::exists(Path.str(), exists) || !exists)
777 Path = File;
778 else if (exists)
779 FileMgr.getFile(File);
780
781 return Lexer::Stringify(Path.str());
782}
783
Reid Spencer5f016e22007-07-11 17:01:13 +0000784//===----------------------------------------------------------------------===//
785// File Info Management.
786//===----------------------------------------------------------------------===//
787
Douglas Gregor8f8d5812011-09-17 05:35:18 +0000788/// \brief Merge the header file info provided by \p OtherHFI into the current
789/// header file info (\p HFI)
790static void mergeHeaderFileInfo(HeaderFileInfo &HFI,
791 const HeaderFileInfo &OtherHFI) {
792 HFI.isImport |= OtherHFI.isImport;
793 HFI.isPragmaOnce |= OtherHFI.isPragmaOnce;
794 HFI.NumIncludes += OtherHFI.NumIncludes;
795
796 if (!HFI.ControllingMacro && !HFI.ControllingMacroID) {
797 HFI.ControllingMacro = OtherHFI.ControllingMacro;
798 HFI.ControllingMacroID = OtherHFI.ControllingMacroID;
799 }
800
801 if (OtherHFI.External) {
802 HFI.DirInfo = OtherHFI.DirInfo;
803 HFI.External = OtherHFI.External;
804 HFI.IndexHeaderMapHeader = OtherHFI.IndexHeaderMapHeader;
805 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000806
Douglas Gregor8f8d5812011-09-17 05:35:18 +0000807 if (HFI.Framework.empty())
808 HFI.Framework = OtherHFI.Framework;
809
810 HFI.Resolved = true;
811}
812
Steve Naroff83d63c72009-04-24 20:03:17 +0000813/// getFileInfo - Return the HeaderFileInfo structure for the specified
Reid Spencer5f016e22007-07-11 17:01:13 +0000814/// FileEntry.
Steve Naroff83d63c72009-04-24 20:03:17 +0000815HeaderFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000816 if (FE->getUID() >= FileInfo.size())
817 FileInfo.resize(FE->getUID()+1);
Douglas Gregorcfbf1c72011-02-10 17:09:37 +0000818
819 HeaderFileInfo &HFI = FileInfo[FE->getUID()];
Douglas Gregor8f8d5812011-09-17 05:35:18 +0000820 if (ExternalSource && !HFI.Resolved)
821 mergeHeaderFileInfo(HFI, ExternalSource->GetHeaderFileInfo(FE));
Douglas Gregorcfbf1c72011-02-10 17:09:37 +0000822 return HFI;
Mike Stump1eb44332009-09-09 15:08:12 +0000823}
Reid Spencer5f016e22007-07-11 17:01:13 +0000824
Douglas Gregordd3e5542011-05-04 00:14:37 +0000825bool HeaderSearch::isFileMultipleIncludeGuarded(const FileEntry *File) {
826 // Check if we've ever seen this file as a header.
827 if (File->getUID() >= FileInfo.size())
828 return false;
829
830 // Resolve header file info from the external source, if needed.
831 HeaderFileInfo &HFI = FileInfo[File->getUID()];
Douglas Gregor8f8d5812011-09-17 05:35:18 +0000832 if (ExternalSource && !HFI.Resolved)
833 mergeHeaderFileInfo(HFI, ExternalSource->GetHeaderFileInfo(File));
Douglas Gregordd3e5542011-05-04 00:14:37 +0000834
Argyrios Kyrtzidis44dfff62012-12-10 20:08:37 +0000835 return HFI.isPragmaOnce || HFI.isImport ||
836 HFI.ControllingMacro || HFI.ControllingMacroID;
Douglas Gregordd3e5542011-05-04 00:14:37 +0000837}
838
Steve Naroff83d63c72009-04-24 20:03:17 +0000839void HeaderSearch::setHeaderFileInfoForUID(HeaderFileInfo HFI, unsigned UID) {
840 if (UID >= FileInfo.size())
841 FileInfo.resize(UID+1);
Douglas Gregorcfbf1c72011-02-10 17:09:37 +0000842 HFI.Resolved = true;
Steve Naroff83d63c72009-04-24 20:03:17 +0000843 FileInfo[UID] = HFI;
844}
845
Reid Spencer5f016e22007-07-11 17:01:13 +0000846bool HeaderSearch::ShouldEnterIncludeFile(const FileEntry *File, bool isImport){
847 ++NumIncluded; // Count # of attempted #includes.
848
849 // Get information about this file.
Steve Naroff83d63c72009-04-24 20:03:17 +0000850 HeaderFileInfo &FileInfo = getFileInfo(File);
Mike Stump1eb44332009-09-09 15:08:12 +0000851
Reid Spencer5f016e22007-07-11 17:01:13 +0000852 // If this is a #import directive, check that we have not already imported
853 // this header.
854 if (isImport) {
855 // If this has already been imported, don't import it again.
856 FileInfo.isImport = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000857
Reid Spencer5f016e22007-07-11 17:01:13 +0000858 // Has this already been #import'ed or #include'd?
859 if (FileInfo.NumIncludes) return false;
860 } else {
861 // Otherwise, if this is a #include of a file that was previously #import'd
862 // or if this is the second #include of a #pragma once file, ignore it.
863 if (FileInfo.isImport)
864 return false;
865 }
Mike Stump1eb44332009-09-09 15:08:12 +0000866
Reid Spencer5f016e22007-07-11 17:01:13 +0000867 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
868 // if the macro that guards it is defined, we know the #include has no effect.
Mike Stump1eb44332009-09-09 15:08:12 +0000869 if (const IdentifierInfo *ControllingMacro
Douglas Gregor8c5a7602009-04-25 23:30:02 +0000870 = FileInfo.getControllingMacro(ExternalLookup))
871 if (ControllingMacro->hasMacroDefinition()) {
872 ++NumMultiIncludeFileOptzn;
873 return false;
874 }
Mike Stump1eb44332009-09-09 15:08:12 +0000875
Reid Spencer5f016e22007-07-11 17:01:13 +0000876 // Increment the number of times this file has been included.
877 ++FileInfo.NumIncludes;
Mike Stump1eb44332009-09-09 15:08:12 +0000878
Reid Spencer5f016e22007-07-11 17:01:13 +0000879 return true;
880}
881
Ted Kremenekd1194fb2011-07-26 23:46:11 +0000882size_t HeaderSearch::getTotalMemory() const {
883 return SearchDirs.capacity()
Ted Kremenekeabea452011-07-27 18:41:18 +0000884 + llvm::capacity_in_bytes(FileInfo)
885 + llvm::capacity_in_bytes(HeaderMaps)
Ted Kremenekd1194fb2011-07-26 23:46:11 +0000886 + LookupFileCache.getAllocator().getTotalMemory()
887 + FrameworkMap.getAllocator().getTotalMemory();
888}
Douglas Gregor65e02fa2011-07-28 04:45:53 +0000889
890StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) {
891 return FrameworkNames.GetOrCreateValue(Framework).getKey();
892}
Douglas Gregora30cfe52011-11-11 19:10:28 +0000893
894bool HeaderSearch::hasModuleMap(StringRef FileName,
895 const DirectoryEntry *Root) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000896 SmallVector<const DirectoryEntry *, 2> FixUpDirectories;
Douglas Gregora30cfe52011-11-11 19:10:28 +0000897
898 StringRef DirName = FileName;
899 do {
900 // Get the parent directory name.
901 DirName = llvm::sys::path::parent_path(DirName);
902 if (DirName.empty())
903 return false;
904
905 // Determine whether this directory exists.
906 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
907 if (!Dir)
908 return false;
909
Douglas Gregorcf70d782011-11-12 00:05:07 +0000910 // Try to load the module map file in this directory.
Douglas Gregor26697972011-11-12 00:22:19 +0000911 switch (loadModuleMapFile(Dir)) {
912 case LMM_NewlyLoaded:
913 case LMM_AlreadyLoaded:
Douglas Gregorcf70d782011-11-12 00:05:07 +0000914 // Success. All of the directories we stepped through inherit this module
915 // map file.
Douglas Gregora30cfe52011-11-11 19:10:28 +0000916 for (unsigned I = 0, N = FixUpDirectories.size(); I != N; ++I)
917 DirectoryHasModuleMap[FixUpDirectories[I]] = true;
918
919 return true;
Douglas Gregor26697972011-11-12 00:22:19 +0000920
921 case LMM_NoDirectory:
922 case LMM_InvalidModuleMap:
923 break;
Douglas Gregora30cfe52011-11-11 19:10:28 +0000924 }
Douglas Gregora30cfe52011-11-11 19:10:28 +0000925
Douglas Gregorcf70d782011-11-12 00:05:07 +0000926 // If we hit the top of our search, we're done.
927 if (Dir == Root)
928 return false;
929
Douglas Gregora30cfe52011-11-11 19:10:28 +0000930 // Keep track of all of the directories we checked, so we can mark them as
931 // having module maps if we eventually do find a module map.
932 FixUpDirectories.push_back(Dir);
933 } while (true);
Douglas Gregora30cfe52011-11-11 19:10:28 +0000934}
935
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000936Module *HeaderSearch::findModuleForHeader(const FileEntry *File) {
Douglas Gregor51f564f2011-12-31 04:05:44 +0000937 if (Module *Mod = ModMap.findModuleForHeader(File))
938 return Mod;
Douglas Gregor65f3b5e2011-11-11 22:18:48 +0000939
Douglas Gregorc69c42e2011-11-17 22:44:56 +0000940 return 0;
Douglas Gregora30cfe52011-11-11 19:10:28 +0000941}
942
Douglas Gregordb1cde72011-11-16 00:09:06 +0000943bool HeaderSearch::loadModuleMapFile(const FileEntry *File) {
944 const DirectoryEntry *Dir = File->getDir();
945
946 llvm::DenseMap<const DirectoryEntry *, bool>::iterator KnownDir
947 = DirectoryHasModuleMap.find(Dir);
948 if (KnownDir != DirectoryHasModuleMap.end())
949 return !KnownDir->second;
950
951 bool Result = ModMap.parseModuleMapFile(File);
Douglas Gregor4813442c2011-12-07 21:25:07 +0000952 if (!Result && llvm::sys::path::filename(File->getName()) == "module.map") {
953 // If the file we loaded was a module.map, look for the corresponding
954 // module_private.map.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000955 SmallString<128> PrivateFilename(Dir->getName());
Douglas Gregor4813442c2011-12-07 21:25:07 +0000956 llvm::sys::path::append(PrivateFilename, "module_private.map");
957 if (const FileEntry *PrivateFile = FileMgr.getFile(PrivateFilename))
958 Result = ModMap.parseModuleMapFile(PrivateFile);
959 }
960
961 DirectoryHasModuleMap[Dir] = !Result;
Douglas Gregordb1cde72011-11-16 00:09:06 +0000962 return Result;
963}
964
Douglas Gregore434ec72012-01-29 17:08:11 +0000965Module *HeaderSearch::loadFrameworkModule(StringRef Name,
966 const DirectoryEntry *Dir,
967 bool IsSystem) {
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000968 if (Module *Module = ModMap.findModule(Name))
Douglas Gregor2821c7f2011-11-17 01:41:17 +0000969 return Module;
970
971 // Try to load a module map file.
972 switch (loadModuleMapFile(Dir)) {
973 case LMM_InvalidModuleMap:
974 break;
975
976 case LMM_AlreadyLoaded:
977 case LMM_NoDirectory:
978 return 0;
979
980 case LMM_NewlyLoaded:
981 return ModMap.findModule(Name);
982 }
Douglas Gregora8c6fea2012-01-13 22:31:52 +0000983
Douglas Gregor7005b902013-01-10 01:43:00 +0000984 // Figure out the top-level framework directory and the submodule path from
985 // that top-level framework to the requested framework.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000986 SmallVector<std::string, 2> SubmodulePath;
Douglas Gregora8c6fea2012-01-13 22:31:52 +0000987 SubmodulePath.push_back(Name);
Douglas Gregor7005b902013-01-10 01:43:00 +0000988 const DirectoryEntry *TopFrameworkDir
989 = ::getTopFrameworkDir(FileMgr, Dir->getName(), SubmodulePath);
Douglas Gregor82e52372012-11-06 19:39:40 +0000990
Douglas Gregor82e52372012-11-06 19:39:40 +0000991
Douglas Gregora8c6fea2012-01-13 22:31:52 +0000992 // Try to infer a module map from the top-level framework directory.
993 Module *Result = ModMap.inferFrameworkModule(SubmodulePath.back(),
Douglas Gregora1f1fad2012-01-27 19:52:33 +0000994 TopFrameworkDir,
995 IsSystem,
Douglas Gregora8c6fea2012-01-13 22:31:52 +0000996 /*Parent=*/0);
Douglas Gregor7005b902013-01-10 01:43:00 +0000997 if (!Result)
998 return 0;
Douglas Gregora8c6fea2012-01-13 22:31:52 +0000999
1000 // Follow the submodule path to find the requested (sub)framework module
1001 // within the top-level framework module.
1002 SubmodulePath.pop_back();
1003 while (!SubmodulePath.empty() && Result) {
1004 Result = ModMap.lookupModuleQualified(SubmodulePath.back(), Result);
1005 SubmodulePath.pop_back();
1006 }
1007 return Result;
Douglas Gregor2821c7f2011-11-17 01:41:17 +00001008}
1009
Douglas Gregordb1cde72011-11-16 00:09:06 +00001010
Douglas Gregor26697972011-11-12 00:22:19 +00001011HeaderSearch::LoadModuleMapResult
1012HeaderSearch::loadModuleMapFile(StringRef DirName) {
Douglas Gregorcf70d782011-11-12 00:05:07 +00001013 if (const DirectoryEntry *Dir = FileMgr.getDirectory(DirName))
1014 return loadModuleMapFile(Dir);
1015
Douglas Gregor26697972011-11-12 00:22:19 +00001016 return LMM_NoDirectory;
Douglas Gregorcf70d782011-11-12 00:05:07 +00001017}
1018
Douglas Gregor26697972011-11-12 00:22:19 +00001019HeaderSearch::LoadModuleMapResult
1020HeaderSearch::loadModuleMapFile(const DirectoryEntry *Dir) {
Douglas Gregorcf70d782011-11-12 00:05:07 +00001021 llvm::DenseMap<const DirectoryEntry *, bool>::iterator KnownDir
1022 = DirectoryHasModuleMap.find(Dir);
1023 if (KnownDir != DirectoryHasModuleMap.end())
Douglas Gregor26697972011-11-12 00:22:19 +00001024 return KnownDir->second? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
Douglas Gregorcf70d782011-11-12 00:05:07 +00001025
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001026 SmallString<128> ModuleMapFileName;
Douglas Gregorcf70d782011-11-12 00:05:07 +00001027 ModuleMapFileName += Dir->getName();
Douglas Gregor587986e2011-12-07 02:23:45 +00001028 unsigned ModuleMapDirNameLen = ModuleMapFileName.size();
Douglas Gregorcf70d782011-11-12 00:05:07 +00001029 llvm::sys::path::append(ModuleMapFileName, "module.map");
1030 if (const FileEntry *ModuleMapFile = FileMgr.getFile(ModuleMapFileName)) {
1031 // We have found a module map file. Try to parse it.
Douglas Gregor587986e2011-12-07 02:23:45 +00001032 if (ModMap.parseModuleMapFile(ModuleMapFile)) {
1033 // No suitable module map.
1034 DirectoryHasModuleMap[Dir] = false;
1035 return LMM_InvalidModuleMap;
Douglas Gregorcf70d782011-11-12 00:05:07 +00001036 }
Douglas Gregor587986e2011-12-07 02:23:45 +00001037
1038 // This directory has a module map.
1039 DirectoryHasModuleMap[Dir] = true;
1040
1041 // Check whether there is a private module map that we need to load as well.
1042 ModuleMapFileName.erase(ModuleMapFileName.begin() + ModuleMapDirNameLen,
1043 ModuleMapFileName.end());
1044 llvm::sys::path::append(ModuleMapFileName, "module_private.map");
1045 if (const FileEntry *PrivateModuleMapFile
1046 = FileMgr.getFile(ModuleMapFileName)) {
1047 if (ModMap.parseModuleMapFile(PrivateModuleMapFile)) {
1048 // No suitable module map.
1049 DirectoryHasModuleMap[Dir] = false;
1050 return LMM_InvalidModuleMap;
1051 }
1052 }
1053
1054 return LMM_NewlyLoaded;
Douglas Gregorcf70d782011-11-12 00:05:07 +00001055 }
1056
1057 // No suitable module map.
1058 DirectoryHasModuleMap[Dir] = false;
Douglas Gregor26697972011-11-12 00:22:19 +00001059 return LMM_InvalidModuleMap;
Douglas Gregorcf70d782011-11-12 00:05:07 +00001060}
Douglas Gregora30cfe52011-11-11 19:10:28 +00001061
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001062void HeaderSearch::collectAllModules(SmallVectorImpl<Module *> &Modules) {
Douglas Gregorc5b2e582012-01-29 18:15:03 +00001063 Modules.clear();
1064
1065 // Load module maps for each of the header search directories.
1066 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
1067 if (SearchDirs[Idx].isFramework()) {
1068 llvm::error_code EC;
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001069 SmallString<128> DirNative;
Douglas Gregorc5b2e582012-01-29 18:15:03 +00001070 llvm::sys::path::native(SearchDirs[Idx].getFrameworkDir()->getName(),
1071 DirNative);
1072
1073 // Search each of the ".framework" directories to load them as modules.
1074 bool IsSystem = SearchDirs[Idx].getDirCharacteristic() != SrcMgr::C_User;
1075 for (llvm::sys::fs::directory_iterator Dir(DirNative.str(), EC), DirEnd;
1076 Dir != DirEnd && !EC; Dir.increment(EC)) {
1077 if (llvm::sys::path::extension(Dir->path()) != ".framework")
1078 continue;
1079
1080 const DirectoryEntry *FrameworkDir = FileMgr.getDirectory(Dir->path());
1081 if (!FrameworkDir)
1082 continue;
1083
1084 // Load this framework module.
1085 loadFrameworkModule(llvm::sys::path::stem(Dir->path()), FrameworkDir,
1086 IsSystem);
1087 }
1088 continue;
1089 }
1090
1091 // FIXME: Deal with header maps.
1092 if (SearchDirs[Idx].isHeaderMap())
1093 continue;
1094
1095 // Try to load a module map file for the search directory.
1096 loadModuleMapFile(SearchDirs[Idx].getDir());
1097
1098 // Try to load module map files for immediate subdirectories of this search
1099 // directory.
1100 llvm::error_code EC;
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001101 SmallString<128> DirNative;
Douglas Gregorc5b2e582012-01-29 18:15:03 +00001102 llvm::sys::path::native(SearchDirs[Idx].getDir()->getName(), DirNative);
1103 for (llvm::sys::fs::directory_iterator Dir(DirNative.str(), EC), DirEnd;
1104 Dir != DirEnd && !EC; Dir.increment(EC)) {
1105 loadModuleMapFile(Dir->path());
1106 }
1107 }
1108
1109 // Populate the list of modules.
1110 for (ModuleMap::module_iterator M = ModMap.module_begin(),
1111 MEnd = ModMap.module_end();
1112 M != MEnd; ++M) {
1113 Modules.push_back(M->getValue());
1114 }
1115}