blob: 7363afc771c9663a2e73d23e59067d3066007bd4 [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>
Reid Spencer5f016e22007-07-11 17:01:13 +000026using namespace clang;
27
Douglas Gregor8c5a7602009-04-25 23:30:02 +000028const IdentifierInfo *
29HeaderFileInfo::getControllingMacro(ExternalIdentifierLookup *External) {
30 if (ControllingMacro)
31 return ControllingMacro;
32
33 if (!ControllingMacroID || !External)
34 return 0;
35
36 ControllingMacro = External->GetIdentifier(ControllingMacroID);
37 return ControllingMacro;
38}
39
Douglas Gregorcfbf1c72011-02-10 17:09:37 +000040ExternalHeaderFileInfoSource::~ExternalHeaderFileInfoSource() {}
41
Douglas Gregorc042edd2012-10-24 16:19:39 +000042HeaderSearch::HeaderSearch(llvm::IntrusiveRefCntPtr<HeaderSearchOptions> HSOpts,
43 FileManager &FM, DiagnosticsEngine &Diags,
Douglas Gregordc58aa72012-01-30 06:01:29 +000044 const LangOptions &LangOpts,
45 const TargetInfo *Target)
Douglas Gregorc042edd2012-10-24 16:19:39 +000046 : HSOpts(HSOpts), FileMgr(FM), FrameworkMap(64),
Douglas Gregordc58aa72012-01-30 06:01:29 +000047 ModMap(FileMgr, *Diags.getClient(), LangOpts, Target)
Douglas Gregor8e238062011-11-11 00:35:06 +000048{
Nico Weber74a5fd82011-05-24 04:31:14 +000049 AngledDirIdx = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000050 SystemDirIdx = 0;
51 NoCurDirSearch = false;
Mike Stump1eb44332009-09-09 15:08:12 +000052
Douglas Gregor8c5a7602009-04-25 23:30:02 +000053 ExternalLookup = 0;
Douglas Gregorcfbf1c72011-02-10 17:09:37 +000054 ExternalSource = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000055 NumIncluded = 0;
56 NumMultiIncludeFileOptzn = 0;
57 NumFrameworkLookups = NumSubFrameworkLookups = 0;
58}
59
Chris Lattner822da612007-12-17 06:36:45 +000060HeaderSearch::~HeaderSearch() {
61 // Delete headermaps.
62 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
63 delete HeaderMaps[i].second;
64}
Mike Stump1eb44332009-09-09 15:08:12 +000065
Reid Spencer5f016e22007-07-11 17:01:13 +000066void HeaderSearch::PrintStats() {
67 fprintf(stderr, "\n*** HeaderSearch Stats:\n");
68 fprintf(stderr, "%d files tracked.\n", (int)FileInfo.size());
69 unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0;
70 for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) {
71 NumOnceOnlyFiles += FileInfo[i].isImport;
72 if (MaxNumIncludes < FileInfo[i].NumIncludes)
73 MaxNumIncludes = FileInfo[i].NumIncludes;
74 NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1;
75 }
76 fprintf(stderr, " %d #import/#pragma once files.\n", NumOnceOnlyFiles);
77 fprintf(stderr, " %d included exactly once.\n", NumSingleIncludedFiles);
78 fprintf(stderr, " %d max times a file is included.\n", MaxNumIncludes);
Mike Stump1eb44332009-09-09 15:08:12 +000079
Reid Spencer5f016e22007-07-11 17:01:13 +000080 fprintf(stderr, " %d #include/#include_next/#import.\n", NumIncluded);
81 fprintf(stderr, " %d #includes skipped due to"
82 " the multi-include optimization.\n", NumMultiIncludeFileOptzn);
Mike Stump1eb44332009-09-09 15:08:12 +000083
Reid Spencer5f016e22007-07-11 17:01:13 +000084 fprintf(stderr, "%d framework lookups.\n", NumFrameworkLookups);
85 fprintf(stderr, "%d subframework lookups.\n", NumSubFrameworkLookups);
86}
87
Chris Lattner822da612007-12-17 06:36:45 +000088/// CreateHeaderMap - This method returns a HeaderMap for the specified
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +000089/// FileEntry, uniquing them through the 'HeaderMaps' datastructure.
Chris Lattner1bfd4a62007-12-17 18:34:53 +000090const HeaderMap *HeaderSearch::CreateHeaderMap(const FileEntry *FE) {
Chris Lattner822da612007-12-17 06:36:45 +000091 // We expect the number of headermaps to be small, and almost always empty.
Chris Lattnerdf772332007-12-17 07:52:39 +000092 // If it ever grows, use of a linear search should be re-evaluated.
Chris Lattner822da612007-12-17 06:36:45 +000093 if (!HeaderMaps.empty()) {
94 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
Chris Lattnerdf772332007-12-17 07:52:39 +000095 // Pointer equality comparison of FileEntries works because they are
96 // already uniqued by inode.
Mike Stump1eb44332009-09-09 15:08:12 +000097 if (HeaderMaps[i].first == FE)
Chris Lattner822da612007-12-17 06:36:45 +000098 return HeaderMaps[i].second;
99 }
Mike Stump1eb44332009-09-09 15:08:12 +0000100
Chris Lattner39b49bc2010-11-23 08:35:12 +0000101 if (const HeaderMap *HM = HeaderMap::Create(FE, FileMgr)) {
Chris Lattner822da612007-12-17 06:36:45 +0000102 HeaderMaps.push_back(std::make_pair(FE, HM));
103 return HM;
104 }
Mike Stump1eb44332009-09-09 15:08:12 +0000105
Chris Lattner822da612007-12-17 06:36:45 +0000106 return 0;
107}
108
Douglas Gregore434ec72012-01-29 17:08:11 +0000109std::string HeaderSearch::getModuleFileName(Module *Module) {
Douglas Gregor9a6da692011-09-12 20:41:59 +0000110 // If we don't have a module cache path, we can't do anything.
Douglas Gregore434ec72012-01-29 17:08:11 +0000111 if (ModuleCachePath.empty())
112 return std::string();
113
114
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000115 SmallString<256> Result(ModuleCachePath);
Douglas Gregore434ec72012-01-29 17:08:11 +0000116 llvm::sys::path::append(Result, Module->getTopLevelModule()->Name + ".pcm");
117 return Result.str().str();
118}
119
120std::string HeaderSearch::getModuleFileName(StringRef ModuleName) {
121 // If we don't have a module cache path, we can't do anything.
122 if (ModuleCachePath.empty())
123 return std::string();
Douglas Gregor6e975c42011-09-13 23:15:45 +0000124
Douglas Gregore434ec72012-01-29 17:08:11 +0000125
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000126 SmallString<256> Result(ModuleCachePath);
Douglas Gregore434ec72012-01-29 17:08:11 +0000127 llvm::sys::path::append(Result, ModuleName + ".pcm");
128 return Result.str().str();
129}
130
131Module *HeaderSearch::lookupModule(StringRef ModuleName, bool AllowSearch) {
Douglas Gregorcf70d782011-11-12 00:05:07 +0000132 // Look in the module map to determine if there is a module by this name.
Douglas Gregore434ec72012-01-29 17:08:11 +0000133 Module *Module = ModMap.findModule(ModuleName);
134 if (Module || !AllowSearch)
135 return Module;
136
Douglas Gregor7005b902013-01-10 01:43:00 +0000137 // Look through the various header search paths to load any available module
Douglas Gregore434ec72012-01-29 17:08:11 +0000138 // maps, searching for a module map that describes this module.
139 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
140 if (SearchDirs[Idx].isFramework()) {
141 // Search for or infer a module map for a framework.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000142 SmallString<128> FrameworkDirName;
Douglas Gregore434ec72012-01-29 17:08:11 +0000143 FrameworkDirName += SearchDirs[Idx].getFrameworkDir()->getName();
144 llvm::sys::path::append(FrameworkDirName, ModuleName + ".framework");
145 if (const DirectoryEntry *FrameworkDir
146 = FileMgr.getDirectory(FrameworkDirName)) {
147 bool IsSystem
148 = SearchDirs[Idx].getDirCharacteristic() != SrcMgr::C_User;
149 Module = loadFrameworkModule(ModuleName, FrameworkDir, IsSystem);
Douglas Gregorcf70d782011-11-12 00:05:07 +0000150 if (Module)
151 break;
152 }
Douglas Gregore434ec72012-01-29 17:08:11 +0000153 }
154
155 // FIXME: Figure out how header maps and module maps will work together.
156
157 // Only deal with normal search directories.
158 if (!SearchDirs[Idx].isNormalDir())
159 continue;
160
161 // Search for a module map file in this directory.
162 if (loadModuleMapFile(SearchDirs[Idx].getDir()) == LMM_NewlyLoaded) {
163 // We just loaded a module map file; check whether the module is
164 // available now.
165 Module = ModMap.findModule(ModuleName);
166 if (Module)
167 break;
168 }
169
170 // Search for a module map in a subdirectory with the same name as the
171 // module.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000172 SmallString<128> NestedModuleMapDirName;
Douglas Gregore434ec72012-01-29 17:08:11 +0000173 NestedModuleMapDirName = SearchDirs[Idx].getDir()->getName();
174 llvm::sys::path::append(NestedModuleMapDirName, ModuleName);
175 if (loadModuleMapFile(NestedModuleMapDirName) == LMM_NewlyLoaded) {
176 // If we just loaded a module map file, look for the module again.
177 Module = ModMap.findModule(ModuleName);
178 if (Module)
179 break;
Douglas Gregorcf70d782011-11-12 00:05:07 +0000180 }
181 }
Douglas Gregore434ec72012-01-29 17:08:11 +0000182
183 return Module;
Douglas Gregor9a6da692011-09-12 20:41:59 +0000184}
185
Chris Lattnerdf772332007-12-17 07:52:39 +0000186//===----------------------------------------------------------------------===//
187// File lookup within a DirectoryLookup scope
188//===----------------------------------------------------------------------===//
189
Chris Lattner3af66a92007-12-17 17:57:27 +0000190/// getName - Return the directory or filename corresponding to this lookup
191/// object.
192const char *DirectoryLookup::getName() const {
193 if (isNormalDir())
194 return getDir()->getName();
195 if (isFramework())
196 return getFrameworkDir()->getName();
197 assert(isHeaderMap() && "Unknown DirectoryLookup");
198 return getHeaderMap()->getFileName();
199}
200
201
Chris Lattnerdf772332007-12-17 07:52:39 +0000202/// LookupFile - Lookup the specified file in this search path, returning it
203/// if it exists or returning null if not.
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000204const FileEntry *DirectoryLookup::LookupFile(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000205 StringRef Filename,
Manuel Klimek74124942011-04-26 21:50:03 +0000206 HeaderSearch &HS,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000207 SmallVectorImpl<char> *SearchPath,
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000208 SmallVectorImpl<char> *RelativePath,
Daniel Dunbar85ff9692012-04-05 17:10:06 +0000209 Module **SuggestedModule,
210 bool &InUserSpecifiedSystemFramework) const {
211 InUserSpecifiedSystemFramework = false;
212
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000213 SmallString<1024> TmpDir;
Chris Lattnerafded5b2007-12-17 08:13:48 +0000214 if (isNormalDir()) {
215 // Concatenate the requested file onto the directory.
Eli Friedmana6e023c2011-07-08 20:17:28 +0000216 TmpDir = getDir()->getName();
217 llvm::sys::path::append(TmpDir, Filename);
Manuel Klimek74124942011-04-26 21:50:03 +0000218 if (SearchPath != NULL) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000219 StringRef SearchPathRef(getDir()->getName());
Manuel Klimek74124942011-04-26 21:50:03 +0000220 SearchPath->clear();
221 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
222 }
223 if (RelativePath != NULL) {
224 RelativePath->clear();
225 RelativePath->append(Filename.begin(), Filename.end());
226 }
Douglas Gregora30cfe52011-11-11 19:10:28 +0000227
228 // If we have a module map that might map this header, load it and
229 // check whether we'll have a suggestion for a module.
230 if (SuggestedModule && HS.hasModuleMap(TmpDir, getDir())) {
231 const FileEntry *File = HS.getFileMgr().getFile(TmpDir.str(),
232 /*openFile=*/false);
233 if (!File)
234 return File;
235
236 // If there is a module that corresponds to this header,
237 // suggest it.
Douglas Gregor5e3f9222011-12-08 17:01:29 +0000238 *SuggestedModule = HS.findModuleForHeader(File);
Douglas Gregora30cfe52011-11-11 19:10:28 +0000239 return File;
240 }
241
Argyrios Kyrtzidis3cd01282011-03-16 19:17:25 +0000242 return HS.getFileMgr().getFile(TmpDir.str(), /*openFile=*/true);
Chris Lattnerafded5b2007-12-17 08:13:48 +0000243 }
Mike Stump1eb44332009-09-09 15:08:12 +0000244
Chris Lattnerafded5b2007-12-17 08:13:48 +0000245 if (isFramework())
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000246 return DoFrameworkLookup(Filename, HS, SearchPath, RelativePath,
Daniel Dunbar85ff9692012-04-05 17:10:06 +0000247 SuggestedModule, InUserSpecifiedSystemFramework);
Mike Stump1eb44332009-09-09 15:08:12 +0000248
Chris Lattnerb09e71f2007-12-17 08:17:39 +0000249 assert(isHeaderMap() && "Unknown directory lookup");
Manuel Klimek74124942011-04-26 21:50:03 +0000250 const FileEntry * const Result = getHeaderMap()->LookupFile(
251 Filename, HS.getFileMgr());
252 if (Result) {
253 if (SearchPath != NULL) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000254 StringRef SearchPathRef(getName());
Manuel Klimek74124942011-04-26 21:50:03 +0000255 SearchPath->clear();
256 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
257 }
258 if (RelativePath != NULL) {
259 RelativePath->clear();
260 RelativePath->append(Filename.begin(), Filename.end());
261 }
262 }
263 return Result;
Chris Lattnerdf772332007-12-17 07:52:39 +0000264}
265
Douglas Gregor7005b902013-01-10 01:43:00 +0000266/// \brief Given a framework directory, find the top-most framework directory.
267///
268/// \param FileMgr The file manager to use for directory lookups.
269/// \param DirName The name of the framework directory.
270/// \param SubmodulePath Will be populated with the submodule path from the
271/// returned top-level module to the originally named framework.
272static const DirectoryEntry *
273getTopFrameworkDir(FileManager &FileMgr, StringRef DirName,
274 SmallVectorImpl<std::string> &SubmodulePath) {
275 assert(llvm::sys::path::extension(DirName) == ".framework" &&
276 "Not a framework directory");
277
278#ifdef LLVM_ON_UNIX
279 // Note: as an egregious but useful hack we use the real path here, because
280 // frameworks moving between top-level frameworks to embedded frameworks tend
281 // to be symlinked, and we base the logical structure of modules on the
282 // physical layout. In particular, we need to deal with crazy includes like
283 //
284 // #include <Foo/Frameworks/Bar.framework/Headers/Wibble.h>
285 //
286 // where 'Bar' used to be embedded in 'Foo', is now a top-level framework
287 // which one should access with, e.g.,
288 //
289 // #include <Bar/Wibble.h>
290 //
291 // Similar issues occur when a top-level framework has moved into an
292 // embedded framework.
293 char RealDirName[PATH_MAX];
294 if (realpath(DirName.str().c_str(), RealDirName))
295 DirName = RealDirName;
296#endif
297
298 const DirectoryEntry *TopFrameworkDir = FileMgr.getDirectory(DirName);
299 do {
300 // Get the parent directory name.
301 DirName = llvm::sys::path::parent_path(DirName);
302 if (DirName.empty())
303 break;
304
305 // Determine whether this directory exists.
306 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
307 if (!Dir)
308 break;
309
310 // If this is a framework directory, then we're a subframework of this
311 // framework.
312 if (llvm::sys::path::extension(DirName) == ".framework") {
313 SubmodulePath.push_back(llvm::sys::path::stem(DirName));
314 TopFrameworkDir = Dir;
315 }
316 } while (true);
317
318 return TopFrameworkDir;
319}
Chris Lattnerdf772332007-12-17 07:52:39 +0000320
Chris Lattnerafded5b2007-12-17 08:13:48 +0000321/// DoFrameworkLookup - Do a lookup of the specified file in the current
322/// DirectoryLookup, which is a framework directory.
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000323const FileEntry *DirectoryLookup::DoFrameworkLookup(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000324 StringRef Filename,
Manuel Klimek74124942011-04-26 21:50:03 +0000325 HeaderSearch &HS,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000326 SmallVectorImpl<char> *SearchPath,
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000327 SmallVectorImpl<char> *RelativePath,
Daniel Dunbar85ff9692012-04-05 17:10:06 +0000328 Module **SuggestedModule,
329 bool &InUserSpecifiedSystemFramework) const
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000330{
Chris Lattnerafded5b2007-12-17 08:13:48 +0000331 FileManager &FileMgr = HS.getFileMgr();
Mike Stump1eb44332009-09-09 15:08:12 +0000332
Reid Spencer5f016e22007-07-11 17:01:13 +0000333 // Framework names must have a '/' in the filename.
Chris Lattnera1394812010-01-10 01:35:12 +0000334 size_t SlashPos = Filename.find('/');
Chris Lattner5f9e2722011-07-23 10:55:15 +0000335 if (SlashPos == StringRef::npos) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000336
Chris Lattnerafded5b2007-12-17 08:13:48 +0000337 // Find out if this is the home for the specified framework, by checking
Daniel Dunbar9ee35f92012-04-05 17:09:40 +0000338 // HeaderSearch. Possible answers are yes/no and unknown.
339 HeaderSearch::FrameworkCacheEntry &CacheEntry =
Chris Lattnera1394812010-01-10 01:35:12 +0000340 HS.LookupFrameworkCache(Filename.substr(0, SlashPos));
Mike Stump1eb44332009-09-09 15:08:12 +0000341
Chris Lattnerafded5b2007-12-17 08:13:48 +0000342 // If it is known and in some other directory, fail.
Daniel Dunbar9ee35f92012-04-05 17:09:40 +0000343 if (CacheEntry.Directory && CacheEntry.Directory != getFrameworkDir())
Reid Spencer5f016e22007-07-11 17:01:13 +0000344 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000345
Chris Lattnerafded5b2007-12-17 08:13:48 +0000346 // Otherwise, construct the path to this framework dir.
Mike Stump1eb44332009-09-09 15:08:12 +0000347
Reid Spencer5f016e22007-07-11 17:01:13 +0000348 // FrameworkName = "/System/Library/Frameworks/"
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000349 SmallString<1024> FrameworkName;
Chris Lattnerafded5b2007-12-17 08:13:48 +0000350 FrameworkName += getFrameworkDir()->getName();
Reid Spencer5f016e22007-07-11 17:01:13 +0000351 if (FrameworkName.empty() || FrameworkName.back() != '/')
352 FrameworkName.push_back('/');
Mike Stump1eb44332009-09-09 15:08:12 +0000353
Reid Spencer5f016e22007-07-11 17:01:13 +0000354 // FrameworkName = "/System/Library/Frameworks/Cocoa"
Douglas Gregor2821c7f2011-11-17 01:41:17 +0000355 StringRef ModuleName(Filename.begin(), SlashPos);
356 FrameworkName += ModuleName;
Mike Stump1eb44332009-09-09 15:08:12 +0000357
Reid Spencer5f016e22007-07-11 17:01:13 +0000358 // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/"
359 FrameworkName += ".framework/";
Mike Stump1eb44332009-09-09 15:08:12 +0000360
Daniel Dunbar9ee35f92012-04-05 17:09:40 +0000361 // If the cache entry was unresolved, populate it now.
362 if (CacheEntry.Directory == 0) {
Chris Lattnerafded5b2007-12-17 08:13:48 +0000363 HS.IncrementFrameworkLookupCount();
Mike Stump1eb44332009-09-09 15:08:12 +0000364
Reid Spencer5f016e22007-07-11 17:01:13 +0000365 // If the framework dir doesn't exist, we fail.
Daniel Dunbar85ff9692012-04-05 17:10:06 +0000366 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName.str());
367 if (Dir == 0) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000368
Reid Spencer5f016e22007-07-11 17:01:13 +0000369 // Otherwise, if it does, remember that this is the right direntry for this
370 // framework.
Daniel Dunbar9ee35f92012-04-05 17:09:40 +0000371 CacheEntry.Directory = getFrameworkDir();
Daniel Dunbar85ff9692012-04-05 17:10:06 +0000372
373 // If this is a user search directory, check if the framework has been
374 // user-specified as a system framework.
375 if (getDirCharacteristic() == SrcMgr::C_User) {
376 SmallString<1024> SystemFrameworkMarker(FrameworkName);
377 SystemFrameworkMarker += ".system_framework";
378 if (llvm::sys::fs::exists(SystemFrameworkMarker.str())) {
379 CacheEntry.IsUserSpecifiedSystemFramework = true;
380 }
381 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000382 }
Mike Stump1eb44332009-09-09 15:08:12 +0000383
Daniel Dunbar85ff9692012-04-05 17:10:06 +0000384 // Set the 'user-specified system framework' flag.
385 InUserSpecifiedSystemFramework = CacheEntry.IsUserSpecifiedSystemFramework;
386
Manuel Klimek74124942011-04-26 21:50:03 +0000387 if (RelativePath != NULL) {
388 RelativePath->clear();
389 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
390 }
Douglas Gregor2821c7f2011-11-17 01:41:17 +0000391
Reid Spencer5f016e22007-07-11 17:01:13 +0000392 // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"
393 unsigned OrigSize = FrameworkName.size();
Mike Stump1eb44332009-09-09 15:08:12 +0000394
Reid Spencer5f016e22007-07-11 17:01:13 +0000395 FrameworkName += "Headers/";
Manuel Klimek74124942011-04-26 21:50:03 +0000396
397 if (SearchPath != NULL) {
398 SearchPath->clear();
399 // Without trailing '/'.
400 SearchPath->append(FrameworkName.begin(), FrameworkName.end()-1);
401 }
402
Chris Lattnera1394812010-01-10 01:35:12 +0000403 FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end());
Douglas Gregor7005b902013-01-10 01:43:00 +0000404 const FileEntry *FE = FileMgr.getFile(FrameworkName.str(),
405 /*openFile=*/!SuggestedModule);
406 if (!FE) {
407 // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"
408 const char *Private = "Private";
409 FrameworkName.insert(FrameworkName.begin()+OrigSize, Private,
410 Private+strlen(Private));
411 if (SearchPath != NULL)
412 SearchPath->insert(SearchPath->begin()+OrigSize, Private,
413 Private+strlen(Private));
414
415 FE = FileMgr.getFile(FrameworkName.str(), /*openFile=*/!SuggestedModule);
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000416 }
Mike Stump1eb44332009-09-09 15:08:12 +0000417
Douglas Gregor7005b902013-01-10 01:43:00 +0000418 // If we found the header and are allowed to suggest a module, do so now.
419 if (FE && SuggestedModule) {
420 // Find the framework in which this header occurs.
421 StringRef FrameworkPath = FE->getName();
422 bool FoundFramework = false;
423 do {
424 // Get the parent directory name.
425 FrameworkPath = llvm::sys::path::parent_path(FrameworkPath);
426 if (FrameworkPath.empty())
427 break;
Manuel Klimek74124942011-04-26 21:50:03 +0000428
Douglas Gregor7005b902013-01-10 01:43:00 +0000429 // Determine whether this directory exists.
430 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkPath);
431 if (!Dir)
432 break;
433
434 // If this is a framework directory, then we're a subframework of this
435 // framework.
436 if (llvm::sys::path::extension(FrameworkPath) == ".framework") {
437 FoundFramework = true;
438 break;
439 }
440 } while (true);
441
442 if (FoundFramework) {
443 // Find the top-level framework based on this framework.
444 SmallVector<std::string, 4> SubmodulePath;
445 const DirectoryEntry *TopFrameworkDir
446 = ::getTopFrameworkDir(FileMgr, FrameworkPath, SubmodulePath);
447
448 // Determine the name of the top-level framework.
449 StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
450
451 // Load this framework module. If that succeeds, find the suggested module
452 // for this header, if any.
453 bool IsSystem = getDirCharacteristic() != SrcMgr::C_User;
454 if (HS.loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystem)) {
455 *SuggestedModule = HS.findModuleForHeader(FE);
456 }
457 } else {
458 *SuggestedModule = HS.findModuleForHeader(FE);
459 }
460 }
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000461 return FE;
Reid Spencer5f016e22007-07-11 17:01:13 +0000462}
463
Douglas Gregordc58aa72012-01-30 06:01:29 +0000464void HeaderSearch::setTarget(const TargetInfo &Target) {
465 ModMap.setTarget(Target);
466}
467
Chris Lattnerdf772332007-12-17 07:52:39 +0000468
Chris Lattnerafded5b2007-12-17 08:13:48 +0000469//===----------------------------------------------------------------------===//
470// Header File Location.
471//===----------------------------------------------------------------------===//
472
473
James Dennett853519c2012-06-20 00:56:32 +0000474/// LookupFile - Given a "foo" or \<foo> reference, look up the indicated file,
Reid Spencer5f016e22007-07-11 17:01:13 +0000475/// return null on failure. isAngled indicates whether the file reference is
James Dennett853519c2012-06-20 00:56:32 +0000476/// for system \#include's or not (i.e. using <> instead of ""). CurFileEnt, if
477/// non-null, indicates where the \#including file is, in case a relative search
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000478/// is needed.
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000479const FileEntry *HeaderSearch::LookupFile(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000480 StringRef Filename,
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000481 bool isAngled,
482 const DirectoryLookup *FromDir,
483 const DirectoryLookup *&CurDir,
484 const FileEntry *CurFileEnt,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000485 SmallVectorImpl<char> *SearchPath,
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000486 SmallVectorImpl<char> *RelativePath,
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000487 Module **SuggestedModule,
Douglas Gregor1c2e9332011-11-20 17:46:46 +0000488 bool SkipCache)
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000489{
490 if (SuggestedModule)
Douglas Gregorc69c42e2011-11-17 22:44:56 +0000491 *SuggestedModule = 0;
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000492
Reid Spencer5f016e22007-07-11 17:01:13 +0000493 // If 'Filename' is absolute, check to see if it exists and no searching.
Michael J. Spencer256053b2010-12-17 21:22:22 +0000494 if (llvm::sys::path::is_absolute(Filename)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000495 CurDir = 0;
496
497 // If this was an #include_next "/absolute/file", fail.
498 if (FromDir) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000499
Manuel Klimek74124942011-04-26 21:50:03 +0000500 if (SearchPath != NULL)
501 SearchPath->clear();
502 if (RelativePath != NULL) {
503 RelativePath->clear();
504 RelativePath->append(Filename.begin(), Filename.end());
505 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000506 // Otherwise, just return the file.
Argyrios Kyrtzidis3cd01282011-03-16 19:17:25 +0000507 return FileMgr.getFile(Filename, /*openFile=*/true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000508 }
Mike Stump1eb44332009-09-09 15:08:12 +0000509
Douglas Gregor65e02fa2011-07-28 04:45:53 +0000510 // Unless disabled, check to see if the file is in the #includer's
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000511 // directory. This has to be based on CurFileEnt, not CurDir, because
512 // CurFileEnt could be a #include of a subdirectory (#include "foo/bar.h") and
Chris Lattnerdf772332007-12-17 07:52:39 +0000513 // a subsequent include of "baz.h" should resolve to "whatever/foo/baz.h".
514 // This search is not done for <> headers.
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000515 if (CurFileEnt && !isAngled && !NoCurDirSearch) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000516 SmallString<1024> TmpDir;
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000517 // Concatenate the requested file onto the directory.
518 // FIXME: Portability. Filename concatenation should be in sys::Path.
519 TmpDir += CurFileEnt->getDir()->getName();
520 TmpDir.push_back('/');
521 TmpDir.append(Filename.begin(), Filename.end());
Argyrios Kyrtzidis3cd01282011-03-16 19:17:25 +0000522 if (const FileEntry *FE = FileMgr.getFile(TmpDir.str(),/*openFile=*/true)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000523 // Leave CurDir unset.
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000524 // This file is a system header or C++ unfriendly if the old file is.
525 //
Douglas Gregor21efbb62012-08-13 15:47:39 +0000526 // Note that we only use one of FromHFI/ToHFI at once, due to potential
527 // reallocation of the underlying vector potentially making the first
528 // reference binding dangling.
529 HeaderFileInfo &FromHFI = getFileInfo(CurFileEnt);
530 unsigned DirInfo = FromHFI.DirInfo;
531 bool IndexHeaderMapHeader = FromHFI.IndexHeaderMapHeader;
532 StringRef Framework = FromHFI.Framework;
533
534 HeaderFileInfo &ToHFI = getFileInfo(FE);
535 ToHFI.DirInfo = DirInfo;
536 ToHFI.IndexHeaderMapHeader = IndexHeaderMapHeader;
537 ToHFI.Framework = Framework;
538
Manuel Klimek74124942011-04-26 21:50:03 +0000539 if (SearchPath != NULL) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000540 StringRef SearchPathRef(CurFileEnt->getDir()->getName());
Manuel Klimek74124942011-04-26 21:50:03 +0000541 SearchPath->clear();
542 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
543 }
544 if (RelativePath != NULL) {
545 RelativePath->clear();
546 RelativePath->append(Filename.begin(), Filename.end());
547 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000548 return FE;
549 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000550 }
Mike Stump1eb44332009-09-09 15:08:12 +0000551
Reid Spencer5f016e22007-07-11 17:01:13 +0000552 CurDir = 0;
553
554 // If this is a system #include, ignore the user #include locs.
Nico Weber74a5fd82011-05-24 04:31:14 +0000555 unsigned i = isAngled ? AngledDirIdx : 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000556
Reid Spencer5f016e22007-07-11 17:01:13 +0000557 // If this is a #include_next request, start searching after the directory the
558 // file was found in.
559 if (FromDir)
560 i = FromDir-&SearchDirs[0];
Mike Stump1eb44332009-09-09 15:08:12 +0000561
Chris Lattner9960ae82007-07-22 07:28:00 +0000562 // Cache all of the lookups performed by this method. Many headers are
563 // multiply included, and the "pragma once" optimization prevents them from
564 // being relex/pp'd, but they would still have to search through a
565 // (potentially huge) series of SearchDirs to find it.
566 std::pair<unsigned, unsigned> &CacheLookup =
Chris Lattnera1394812010-01-10 01:35:12 +0000567 LookupFileCache.GetOrCreateValue(Filename).getValue();
Chris Lattner9960ae82007-07-22 07:28:00 +0000568
569 // If the entry has been previously looked up, the first value will be
570 // non-zero. If the value is equal to i (the start point of our search), then
571 // this is a matching hit.
Douglas Gregor1c2e9332011-11-20 17:46:46 +0000572 if (!SkipCache && CacheLookup.first == i+1) {
Chris Lattner9960ae82007-07-22 07:28:00 +0000573 // Skip querying potentially lots of directories for this lookup.
574 i = CacheLookup.second;
575 } else {
576 // Otherwise, this is the first query, or the previous query didn't match
577 // our search start. We will fill in our found location below, so prime the
578 // start point value.
579 CacheLookup.first = i+1;
580 }
Mike Stump1eb44332009-09-09 15:08:12 +0000581
Reid Spencer5f016e22007-07-11 17:01:13 +0000582 // Check each directory in sequence to see if it contains this file.
583 for (; i != SearchDirs.size(); ++i) {
Daniel Dunbar85ff9692012-04-05 17:10:06 +0000584 bool InUserSpecifiedSystemFramework = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000585 const FileEntry *FE =
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000586 SearchDirs[i].LookupFile(Filename, *this, SearchPath, RelativePath,
Daniel Dunbar85ff9692012-04-05 17:10:06 +0000587 SuggestedModule, InUserSpecifiedSystemFramework);
Chris Lattnerafded5b2007-12-17 08:13:48 +0000588 if (!FE) continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000589
Chris Lattnerafded5b2007-12-17 08:13:48 +0000590 CurDir = &SearchDirs[i];
Mike Stump1eb44332009-09-09 15:08:12 +0000591
Chris Lattnerafded5b2007-12-17 08:13:48 +0000592 // This file is a system header or C++ unfriendly if the dir is.
Douglas Gregor65e02fa2011-07-28 04:45:53 +0000593 HeaderFileInfo &HFI = getFileInfo(FE);
594 HFI.DirInfo = CurDir->getDirCharacteristic();
Mike Stump1eb44332009-09-09 15:08:12 +0000595
Daniel Dunbar85ff9692012-04-05 17:10:06 +0000596 // If the directory characteristic is User but this framework was
597 // user-specified to be treated as a system framework, promote the
598 // characteristic.
599 if (HFI.DirInfo == SrcMgr::C_User && InUserSpecifiedSystemFramework)
600 HFI.DirInfo = SrcMgr::C_System;
601
Richard Smithf122a132012-06-13 20:27:03 +0000602 // If the filename matches a known system header prefix, override
603 // whether the file is a system header.
Richard Trieu4ef2f6a2012-06-13 20:52:36 +0000604 for (unsigned j = SystemHeaderPrefixes.size(); j; --j) {
605 if (Filename.startswith(SystemHeaderPrefixes[j-1].first)) {
606 HFI.DirInfo = SystemHeaderPrefixes[j-1].second ? SrcMgr::C_System
Richard Smithf122a132012-06-13 20:27:03 +0000607 : SrcMgr::C_User;
608 break;
609 }
610 }
611
Douglas Gregor65e02fa2011-07-28 04:45:53 +0000612 // If this file is found in a header map and uses the framework style of
613 // includes, then this header is part of a framework we're building.
614 if (CurDir->isIndexHeaderMap()) {
615 size_t SlashPos = Filename.find('/');
616 if (SlashPos != StringRef::npos) {
617 HFI.IndexHeaderMapHeader = 1;
618 HFI.Framework = getUniqueFrameworkName(StringRef(Filename.begin(),
619 SlashPos));
620 }
621 }
622
Chris Lattnerafded5b2007-12-17 08:13:48 +0000623 // Remember this location for the next lookup we do.
624 CacheLookup.second = i;
625 return FE;
Reid Spencer5f016e22007-07-11 17:01:13 +0000626 }
Mike Stump1eb44332009-09-09 15:08:12 +0000627
Douglas Gregor2c7b7802011-07-30 06:28:34 +0000628 // If we are including a file with a quoted include "foo.h" from inside
629 // a header in a framework that is currently being built, and we couldn't
630 // resolve "foo.h" any other way, change the include to <Foo/foo.h>, where
631 // "Foo" is the name of the framework in which the including header was found.
632 if (CurFileEnt && !isAngled && Filename.find('/') == StringRef::npos) {
633 HeaderFileInfo &IncludingHFI = getFileInfo(CurFileEnt);
634 if (IncludingHFI.IndexHeaderMapHeader) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000635 SmallString<128> ScratchFilename;
Douglas Gregor2c7b7802011-07-30 06:28:34 +0000636 ScratchFilename += IncludingHFI.Framework;
637 ScratchFilename += '/';
638 ScratchFilename += Filename;
639
640 const FileEntry *Result = LookupFile(ScratchFilename, /*isAngled=*/true,
641 FromDir, CurDir, CurFileEnt,
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000642 SearchPath, RelativePath,
643 SuggestedModule);
Douglas Gregor2c7b7802011-07-30 06:28:34 +0000644 std::pair<unsigned, unsigned> &CacheLookup
645 = LookupFileCache.GetOrCreateValue(Filename).getValue();
646 CacheLookup.second
647 = LookupFileCache.GetOrCreateValue(ScratchFilename).getValue().second;
648 return Result;
649 }
650 }
651
Chris Lattner9960ae82007-07-22 07:28:00 +0000652 // Otherwise, didn't find it. Remember we didn't find this.
653 CacheLookup.second = SearchDirs.size();
Reid Spencer5f016e22007-07-11 17:01:13 +0000654 return 0;
655}
656
657/// LookupSubframeworkHeader - Look up a subframework for the specified
James Dennett853519c2012-06-20 00:56:32 +0000658/// \#include file. For example, if \#include'ing <HIToolbox/HIToolbox.h> from
Reid Spencer5f016e22007-07-11 17:01:13 +0000659/// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
660/// is a subframework within Carbon.framework. If so, return the FileEntry
661/// for the designated file, otherwise return null.
662const FileEntry *HeaderSearch::
Chris Lattner5f9e2722011-07-23 10:55:15 +0000663LookupSubframeworkHeader(StringRef Filename,
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000664 const FileEntry *ContextFileEnt,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000665 SmallVectorImpl<char> *SearchPath,
666 SmallVectorImpl<char> *RelativePath) {
Chris Lattner9415a0c2008-02-01 05:34:02 +0000667 assert(ContextFileEnt && "No context file?");
Mike Stump1eb44332009-09-09 15:08:12 +0000668
Reid Spencer5f016e22007-07-11 17:01:13 +0000669 // Framework names must have a '/' in the filename. Find it.
Douglas Gregorefda0e82011-12-09 16:48:01 +0000670 // FIXME: Should we permit '\' on Windows?
Chris Lattnera1394812010-01-10 01:35:12 +0000671 size_t SlashPos = Filename.find('/');
Chris Lattner5f9e2722011-07-23 10:55:15 +0000672 if (SlashPos == StringRef::npos) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000673
Reid Spencer5f016e22007-07-11 17:01:13 +0000674 // Look up the base framework name of the ContextFileEnt.
675 const char *ContextName = ContextFileEnt->getName();
Mike Stump1eb44332009-09-09 15:08:12 +0000676
Reid Spencer5f016e22007-07-11 17:01:13 +0000677 // If the context info wasn't a framework, couldn't be a subframework.
Douglas Gregorefda0e82011-12-09 16:48:01 +0000678 const unsigned DotFrameworkLen = 10;
679 const char *FrameworkPos = strstr(ContextName, ".framework");
680 if (FrameworkPos == 0 ||
681 (FrameworkPos[DotFrameworkLen] != '/' &&
682 FrameworkPos[DotFrameworkLen] != '\\'))
Reid Spencer5f016e22007-07-11 17:01:13 +0000683 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000684
Daniel Dunbar9ee35f92012-04-05 17:09:40 +0000685 SmallString<1024> FrameworkName(ContextName, FrameworkPos+DotFrameworkLen+1);
Reid Spencer5f016e22007-07-11 17:01:13 +0000686
687 // Append Frameworks/HIToolbox.framework/
688 FrameworkName += "Frameworks/";
Chris Lattnera1394812010-01-10 01:35:12 +0000689 FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos);
Reid Spencer5f016e22007-07-11 17:01:13 +0000690 FrameworkName += ".framework/";
691
Daniel Dunbar9ee35f92012-04-05 17:09:40 +0000692 llvm::StringMapEntry<FrameworkCacheEntry> &CacheLookup =
Chris Lattner65382272010-11-21 09:55:08 +0000693 FrameworkMap.GetOrCreateValue(Filename.substr(0, SlashPos));
Mike Stump1eb44332009-09-09 15:08:12 +0000694
Reid Spencer5f016e22007-07-11 17:01:13 +0000695 // Some other location?
Daniel Dunbar9ee35f92012-04-05 17:09:40 +0000696 if (CacheLookup.getValue().Directory &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000697 CacheLookup.getKeyLength() == FrameworkName.size() &&
698 memcmp(CacheLookup.getKeyData(), &FrameworkName[0],
699 CacheLookup.getKeyLength()) != 0)
700 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000701
Reid Spencer5f016e22007-07-11 17:01:13 +0000702 // Cache subframework.
Daniel Dunbar9ee35f92012-04-05 17:09:40 +0000703 if (CacheLookup.getValue().Directory == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000704 ++NumSubFrameworkLookups;
Mike Stump1eb44332009-09-09 15:08:12 +0000705
Reid Spencer5f016e22007-07-11 17:01:13 +0000706 // If the framework dir doesn't exist, we fail.
Chris Lattner39b49bc2010-11-23 08:35:12 +0000707 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName.str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000708 if (Dir == 0) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000709
Reid Spencer5f016e22007-07-11 17:01:13 +0000710 // Otherwise, if it does, remember that this is the right direntry for this
711 // framework.
Daniel Dunbar9ee35f92012-04-05 17:09:40 +0000712 CacheLookup.getValue().Directory = Dir;
Reid Spencer5f016e22007-07-11 17:01:13 +0000713 }
Mike Stump1eb44332009-09-09 15:08:12 +0000714
Reid Spencer5f016e22007-07-11 17:01:13 +0000715 const FileEntry *FE = 0;
716
Manuel Klimek74124942011-04-26 21:50:03 +0000717 if (RelativePath != NULL) {
718 RelativePath->clear();
719 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
720 }
721
Reid Spencer5f016e22007-07-11 17:01:13 +0000722 // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000723 SmallString<1024> HeadersFilename(FrameworkName);
Reid Spencer5f016e22007-07-11 17:01:13 +0000724 HeadersFilename += "Headers/";
Manuel Klimek74124942011-04-26 21:50:03 +0000725 if (SearchPath != NULL) {
726 SearchPath->clear();
727 // Without trailing '/'.
728 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
729 }
730
Chris Lattnera1394812010-01-10 01:35:12 +0000731 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
Argyrios Kyrtzidis3cd01282011-03-16 19:17:25 +0000732 if (!(FE = FileMgr.getFile(HeadersFilename.str(), /*openFile=*/true))) {
Mike Stump1eb44332009-09-09 15:08:12 +0000733
Reid Spencer5f016e22007-07-11 17:01:13 +0000734 // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
735 HeadersFilename = FrameworkName;
736 HeadersFilename += "PrivateHeaders/";
Manuel Klimek74124942011-04-26 21:50:03 +0000737 if (SearchPath != NULL) {
738 SearchPath->clear();
739 // Without trailing '/'.
740 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
741 }
742
Chris Lattnera1394812010-01-10 01:35:12 +0000743 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
Argyrios Kyrtzidis3cd01282011-03-16 19:17:25 +0000744 if (!(FE = FileMgr.getFile(HeadersFilename.str(), /*openFile=*/true)))
Reid Spencer5f016e22007-07-11 17:01:13 +0000745 return 0;
746 }
Mike Stump1eb44332009-09-09 15:08:12 +0000747
Reid Spencer5f016e22007-07-11 17:01:13 +0000748 // This file is a system header or C++ unfriendly if the old file is.
Ted Kremenekca63fa02008-02-24 03:55:14 +0000749 //
Chris Lattnerc9dde4f2008-02-25 21:38:21 +0000750 // Note that the temporary 'DirInfo' is required here, as either call to
751 // getFileInfo could resize the vector and we don't want to rely on order
752 // of evaluation.
753 unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo;
754 getFileInfo(FE).DirInfo = DirInfo;
Reid Spencer5f016e22007-07-11 17:01:13 +0000755 return FE;
756}
757
Chandler Carruthcb381ea2011-12-09 01:33:57 +0000758/// \brief Helper static function to normalize a path for injection into
759/// a synthetic header.
760/*static*/ std::string
761HeaderSearch::NormalizeDashIncludePath(StringRef File, FileManager &FileMgr) {
762 // Implicit include paths should be resolved relative to the current
763 // working directory first, and then use the regular header search
764 // mechanism. The proper way to handle this is to have the
765 // predefines buffer located at the current working directory, but
766 // it has no file entry. For now, workaround this by using an
767 // absolute path if we find the file here, and otherwise letting
768 // header search handle it.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000769 SmallString<128> Path(File);
Chandler Carruthcb381ea2011-12-09 01:33:57 +0000770 llvm::sys::fs::make_absolute(Path);
771 bool exists;
772 if (llvm::sys::fs::exists(Path.str(), exists) || !exists)
773 Path = File;
774 else if (exists)
775 FileMgr.getFile(File);
776
777 return Lexer::Stringify(Path.str());
778}
779
Reid Spencer5f016e22007-07-11 17:01:13 +0000780//===----------------------------------------------------------------------===//
781// File Info Management.
782//===----------------------------------------------------------------------===//
783
Douglas Gregor8f8d5812011-09-17 05:35:18 +0000784/// \brief Merge the header file info provided by \p OtherHFI into the current
785/// header file info (\p HFI)
786static void mergeHeaderFileInfo(HeaderFileInfo &HFI,
787 const HeaderFileInfo &OtherHFI) {
788 HFI.isImport |= OtherHFI.isImport;
789 HFI.isPragmaOnce |= OtherHFI.isPragmaOnce;
790 HFI.NumIncludes += OtherHFI.NumIncludes;
791
792 if (!HFI.ControllingMacro && !HFI.ControllingMacroID) {
793 HFI.ControllingMacro = OtherHFI.ControllingMacro;
794 HFI.ControllingMacroID = OtherHFI.ControllingMacroID;
795 }
796
797 if (OtherHFI.External) {
798 HFI.DirInfo = OtherHFI.DirInfo;
799 HFI.External = OtherHFI.External;
800 HFI.IndexHeaderMapHeader = OtherHFI.IndexHeaderMapHeader;
801 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000802
Douglas Gregor8f8d5812011-09-17 05:35:18 +0000803 if (HFI.Framework.empty())
804 HFI.Framework = OtherHFI.Framework;
805
806 HFI.Resolved = true;
807}
808
Steve Naroff83d63c72009-04-24 20:03:17 +0000809/// getFileInfo - Return the HeaderFileInfo structure for the specified
Reid Spencer5f016e22007-07-11 17:01:13 +0000810/// FileEntry.
Steve Naroff83d63c72009-04-24 20:03:17 +0000811HeaderFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000812 if (FE->getUID() >= FileInfo.size())
813 FileInfo.resize(FE->getUID()+1);
Douglas Gregorcfbf1c72011-02-10 17:09:37 +0000814
815 HeaderFileInfo &HFI = FileInfo[FE->getUID()];
Douglas Gregor8f8d5812011-09-17 05:35:18 +0000816 if (ExternalSource && !HFI.Resolved)
817 mergeHeaderFileInfo(HFI, ExternalSource->GetHeaderFileInfo(FE));
Douglas Gregorcfbf1c72011-02-10 17:09:37 +0000818 return HFI;
Mike Stump1eb44332009-09-09 15:08:12 +0000819}
Reid Spencer5f016e22007-07-11 17:01:13 +0000820
Douglas Gregordd3e5542011-05-04 00:14:37 +0000821bool HeaderSearch::isFileMultipleIncludeGuarded(const FileEntry *File) {
822 // Check if we've ever seen this file as a header.
823 if (File->getUID() >= FileInfo.size())
824 return false;
825
826 // Resolve header file info from the external source, if needed.
827 HeaderFileInfo &HFI = FileInfo[File->getUID()];
Douglas Gregor8f8d5812011-09-17 05:35:18 +0000828 if (ExternalSource && !HFI.Resolved)
829 mergeHeaderFileInfo(HFI, ExternalSource->GetHeaderFileInfo(File));
Douglas Gregordd3e5542011-05-04 00:14:37 +0000830
Argyrios Kyrtzidis44dfff62012-12-10 20:08:37 +0000831 return HFI.isPragmaOnce || HFI.isImport ||
832 HFI.ControllingMacro || HFI.ControllingMacroID;
Douglas Gregordd3e5542011-05-04 00:14:37 +0000833}
834
Steve Naroff83d63c72009-04-24 20:03:17 +0000835void HeaderSearch::setHeaderFileInfoForUID(HeaderFileInfo HFI, unsigned UID) {
836 if (UID >= FileInfo.size())
837 FileInfo.resize(UID+1);
Douglas Gregorcfbf1c72011-02-10 17:09:37 +0000838 HFI.Resolved = true;
Steve Naroff83d63c72009-04-24 20:03:17 +0000839 FileInfo[UID] = HFI;
840}
841
Reid Spencer5f016e22007-07-11 17:01:13 +0000842bool HeaderSearch::ShouldEnterIncludeFile(const FileEntry *File, bool isImport){
843 ++NumIncluded; // Count # of attempted #includes.
844
845 // Get information about this file.
Steve Naroff83d63c72009-04-24 20:03:17 +0000846 HeaderFileInfo &FileInfo = getFileInfo(File);
Mike Stump1eb44332009-09-09 15:08:12 +0000847
Reid Spencer5f016e22007-07-11 17:01:13 +0000848 // If this is a #import directive, check that we have not already imported
849 // this header.
850 if (isImport) {
851 // If this has already been imported, don't import it again.
852 FileInfo.isImport = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000853
Reid Spencer5f016e22007-07-11 17:01:13 +0000854 // Has this already been #import'ed or #include'd?
855 if (FileInfo.NumIncludes) return false;
856 } else {
857 // Otherwise, if this is a #include of a file that was previously #import'd
858 // or if this is the second #include of a #pragma once file, ignore it.
859 if (FileInfo.isImport)
860 return false;
861 }
Mike Stump1eb44332009-09-09 15:08:12 +0000862
Reid Spencer5f016e22007-07-11 17:01:13 +0000863 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
864 // if the macro that guards it is defined, we know the #include has no effect.
Mike Stump1eb44332009-09-09 15:08:12 +0000865 if (const IdentifierInfo *ControllingMacro
Douglas Gregor8c5a7602009-04-25 23:30:02 +0000866 = FileInfo.getControllingMacro(ExternalLookup))
867 if (ControllingMacro->hasMacroDefinition()) {
868 ++NumMultiIncludeFileOptzn;
869 return false;
870 }
Mike Stump1eb44332009-09-09 15:08:12 +0000871
Reid Spencer5f016e22007-07-11 17:01:13 +0000872 // Increment the number of times this file has been included.
873 ++FileInfo.NumIncludes;
Mike Stump1eb44332009-09-09 15:08:12 +0000874
Reid Spencer5f016e22007-07-11 17:01:13 +0000875 return true;
876}
877
Ted Kremenekd1194fb2011-07-26 23:46:11 +0000878size_t HeaderSearch::getTotalMemory() const {
879 return SearchDirs.capacity()
Ted Kremenekeabea452011-07-27 18:41:18 +0000880 + llvm::capacity_in_bytes(FileInfo)
881 + llvm::capacity_in_bytes(HeaderMaps)
Ted Kremenekd1194fb2011-07-26 23:46:11 +0000882 + LookupFileCache.getAllocator().getTotalMemory()
883 + FrameworkMap.getAllocator().getTotalMemory();
884}
Douglas Gregor65e02fa2011-07-28 04:45:53 +0000885
886StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) {
887 return FrameworkNames.GetOrCreateValue(Framework).getKey();
888}
Douglas Gregora30cfe52011-11-11 19:10:28 +0000889
890bool HeaderSearch::hasModuleMap(StringRef FileName,
891 const DirectoryEntry *Root) {
892 llvm::SmallVector<const DirectoryEntry *, 2> FixUpDirectories;
893
894 StringRef DirName = FileName;
895 do {
896 // Get the parent directory name.
897 DirName = llvm::sys::path::parent_path(DirName);
898 if (DirName.empty())
899 return false;
900
901 // Determine whether this directory exists.
902 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
903 if (!Dir)
904 return false;
905
Douglas Gregorcf70d782011-11-12 00:05:07 +0000906 // Try to load the module map file in this directory.
Douglas Gregor26697972011-11-12 00:22:19 +0000907 switch (loadModuleMapFile(Dir)) {
908 case LMM_NewlyLoaded:
909 case LMM_AlreadyLoaded:
Douglas Gregorcf70d782011-11-12 00:05:07 +0000910 // Success. All of the directories we stepped through inherit this module
911 // map file.
Douglas Gregora30cfe52011-11-11 19:10:28 +0000912 for (unsigned I = 0, N = FixUpDirectories.size(); I != N; ++I)
913 DirectoryHasModuleMap[FixUpDirectories[I]] = true;
914
915 return true;
Douglas Gregor26697972011-11-12 00:22:19 +0000916
917 case LMM_NoDirectory:
918 case LMM_InvalidModuleMap:
919 break;
Douglas Gregora30cfe52011-11-11 19:10:28 +0000920 }
Douglas Gregora30cfe52011-11-11 19:10:28 +0000921
Douglas Gregorcf70d782011-11-12 00:05:07 +0000922 // If we hit the top of our search, we're done.
923 if (Dir == Root)
924 return false;
925
Douglas Gregora30cfe52011-11-11 19:10:28 +0000926 // Keep track of all of the directories we checked, so we can mark them as
927 // having module maps if we eventually do find a module map.
928 FixUpDirectories.push_back(Dir);
929 } while (true);
Douglas Gregora30cfe52011-11-11 19:10:28 +0000930}
931
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000932Module *HeaderSearch::findModuleForHeader(const FileEntry *File) {
Douglas Gregor51f564f2011-12-31 04:05:44 +0000933 if (Module *Mod = ModMap.findModuleForHeader(File))
934 return Mod;
Douglas Gregor65f3b5e2011-11-11 22:18:48 +0000935
Douglas Gregorc69c42e2011-11-17 22:44:56 +0000936 return 0;
Douglas Gregora30cfe52011-11-11 19:10:28 +0000937}
938
Douglas Gregordb1cde72011-11-16 00:09:06 +0000939bool HeaderSearch::loadModuleMapFile(const FileEntry *File) {
940 const DirectoryEntry *Dir = File->getDir();
941
942 llvm::DenseMap<const DirectoryEntry *, bool>::iterator KnownDir
943 = DirectoryHasModuleMap.find(Dir);
944 if (KnownDir != DirectoryHasModuleMap.end())
945 return !KnownDir->second;
946
947 bool Result = ModMap.parseModuleMapFile(File);
Douglas Gregor4813442c2011-12-07 21:25:07 +0000948 if (!Result && llvm::sys::path::filename(File->getName()) == "module.map") {
949 // If the file we loaded was a module.map, look for the corresponding
950 // module_private.map.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000951 SmallString<128> PrivateFilename(Dir->getName());
Douglas Gregor4813442c2011-12-07 21:25:07 +0000952 llvm::sys::path::append(PrivateFilename, "module_private.map");
953 if (const FileEntry *PrivateFile = FileMgr.getFile(PrivateFilename))
954 Result = ModMap.parseModuleMapFile(PrivateFile);
955 }
956
957 DirectoryHasModuleMap[Dir] = !Result;
Douglas Gregordb1cde72011-11-16 00:09:06 +0000958 return Result;
959}
960
Douglas Gregore434ec72012-01-29 17:08:11 +0000961Module *HeaderSearch::loadFrameworkModule(StringRef Name,
962 const DirectoryEntry *Dir,
963 bool IsSystem) {
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000964 if (Module *Module = ModMap.findModule(Name))
Douglas Gregor2821c7f2011-11-17 01:41:17 +0000965 return Module;
966
967 // Try to load a module map file.
968 switch (loadModuleMapFile(Dir)) {
969 case LMM_InvalidModuleMap:
970 break;
971
972 case LMM_AlreadyLoaded:
973 case LMM_NoDirectory:
974 return 0;
975
976 case LMM_NewlyLoaded:
977 return ModMap.findModule(Name);
978 }
Douglas Gregora8c6fea2012-01-13 22:31:52 +0000979
Douglas Gregor7005b902013-01-10 01:43:00 +0000980 // Figure out the top-level framework directory and the submodule path from
981 // that top-level framework to the requested framework.
982 llvm::SmallVector<std::string, 2> SubmodulePath;
Douglas Gregora8c6fea2012-01-13 22:31:52 +0000983 SubmodulePath.push_back(Name);
Douglas Gregor7005b902013-01-10 01:43:00 +0000984 const DirectoryEntry *TopFrameworkDir
985 = ::getTopFrameworkDir(FileMgr, Dir->getName(), SubmodulePath);
Douglas Gregor82e52372012-11-06 19:39:40 +0000986
Douglas Gregor82e52372012-11-06 19:39:40 +0000987
Douglas Gregora8c6fea2012-01-13 22:31:52 +0000988 // Try to infer a module map from the top-level framework directory.
989 Module *Result = ModMap.inferFrameworkModule(SubmodulePath.back(),
Douglas Gregora1f1fad2012-01-27 19:52:33 +0000990 TopFrameworkDir,
991 IsSystem,
Douglas Gregora8c6fea2012-01-13 22:31:52 +0000992 /*Parent=*/0);
Douglas Gregor7005b902013-01-10 01:43:00 +0000993 if (!Result)
994 return 0;
Douglas Gregora8c6fea2012-01-13 22:31:52 +0000995
996 // Follow the submodule path to find the requested (sub)framework module
997 // within the top-level framework module.
998 SubmodulePath.pop_back();
999 while (!SubmodulePath.empty() && Result) {
1000 Result = ModMap.lookupModuleQualified(SubmodulePath.back(), Result);
1001 SubmodulePath.pop_back();
1002 }
1003 return Result;
Douglas Gregor2821c7f2011-11-17 01:41:17 +00001004}
1005
Douglas Gregordb1cde72011-11-16 00:09:06 +00001006
Douglas Gregor26697972011-11-12 00:22:19 +00001007HeaderSearch::LoadModuleMapResult
1008HeaderSearch::loadModuleMapFile(StringRef DirName) {
Douglas Gregorcf70d782011-11-12 00:05:07 +00001009 if (const DirectoryEntry *Dir = FileMgr.getDirectory(DirName))
1010 return loadModuleMapFile(Dir);
1011
Douglas Gregor26697972011-11-12 00:22:19 +00001012 return LMM_NoDirectory;
Douglas Gregorcf70d782011-11-12 00:05:07 +00001013}
1014
Douglas Gregor26697972011-11-12 00:22:19 +00001015HeaderSearch::LoadModuleMapResult
1016HeaderSearch::loadModuleMapFile(const DirectoryEntry *Dir) {
Douglas Gregorcf70d782011-11-12 00:05:07 +00001017 llvm::DenseMap<const DirectoryEntry *, bool>::iterator KnownDir
1018 = DirectoryHasModuleMap.find(Dir);
1019 if (KnownDir != DirectoryHasModuleMap.end())
Douglas Gregor26697972011-11-12 00:22:19 +00001020 return KnownDir->second? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
Douglas Gregorcf70d782011-11-12 00:05:07 +00001021
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001022 SmallString<128> ModuleMapFileName;
Douglas Gregorcf70d782011-11-12 00:05:07 +00001023 ModuleMapFileName += Dir->getName();
Douglas Gregor587986e2011-12-07 02:23:45 +00001024 unsigned ModuleMapDirNameLen = ModuleMapFileName.size();
Douglas Gregorcf70d782011-11-12 00:05:07 +00001025 llvm::sys::path::append(ModuleMapFileName, "module.map");
1026 if (const FileEntry *ModuleMapFile = FileMgr.getFile(ModuleMapFileName)) {
1027 // We have found a module map file. Try to parse it.
Douglas Gregor587986e2011-12-07 02:23:45 +00001028 if (ModMap.parseModuleMapFile(ModuleMapFile)) {
1029 // No suitable module map.
1030 DirectoryHasModuleMap[Dir] = false;
1031 return LMM_InvalidModuleMap;
Douglas Gregorcf70d782011-11-12 00:05:07 +00001032 }
Douglas Gregor587986e2011-12-07 02:23:45 +00001033
1034 // This directory has a module map.
1035 DirectoryHasModuleMap[Dir] = true;
1036
1037 // Check whether there is a private module map that we need to load as well.
1038 ModuleMapFileName.erase(ModuleMapFileName.begin() + ModuleMapDirNameLen,
1039 ModuleMapFileName.end());
1040 llvm::sys::path::append(ModuleMapFileName, "module_private.map");
1041 if (const FileEntry *PrivateModuleMapFile
1042 = FileMgr.getFile(ModuleMapFileName)) {
1043 if (ModMap.parseModuleMapFile(PrivateModuleMapFile)) {
1044 // No suitable module map.
1045 DirectoryHasModuleMap[Dir] = false;
1046 return LMM_InvalidModuleMap;
1047 }
1048 }
1049
1050 return LMM_NewlyLoaded;
Douglas Gregorcf70d782011-11-12 00:05:07 +00001051 }
1052
1053 // No suitable module map.
1054 DirectoryHasModuleMap[Dir] = false;
Douglas Gregor26697972011-11-12 00:22:19 +00001055 return LMM_InvalidModuleMap;
Douglas Gregorcf70d782011-11-12 00:05:07 +00001056}
Douglas Gregora30cfe52011-11-11 19:10:28 +00001057
Douglas Gregorc5b2e582012-01-29 18:15:03 +00001058void HeaderSearch::collectAllModules(llvm::SmallVectorImpl<Module *> &Modules) {
1059 Modules.clear();
1060
1061 // Load module maps for each of the header search directories.
1062 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
1063 if (SearchDirs[Idx].isFramework()) {
1064 llvm::error_code EC;
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001065 SmallString<128> DirNative;
Douglas Gregorc5b2e582012-01-29 18:15:03 +00001066 llvm::sys::path::native(SearchDirs[Idx].getFrameworkDir()->getName(),
1067 DirNative);
1068
1069 // Search each of the ".framework" directories to load them as modules.
1070 bool IsSystem = SearchDirs[Idx].getDirCharacteristic() != SrcMgr::C_User;
1071 for (llvm::sys::fs::directory_iterator Dir(DirNative.str(), EC), DirEnd;
1072 Dir != DirEnd && !EC; Dir.increment(EC)) {
1073 if (llvm::sys::path::extension(Dir->path()) != ".framework")
1074 continue;
1075
1076 const DirectoryEntry *FrameworkDir = FileMgr.getDirectory(Dir->path());
1077 if (!FrameworkDir)
1078 continue;
1079
1080 // Load this framework module.
1081 loadFrameworkModule(llvm::sys::path::stem(Dir->path()), FrameworkDir,
1082 IsSystem);
1083 }
1084 continue;
1085 }
1086
1087 // FIXME: Deal with header maps.
1088 if (SearchDirs[Idx].isHeaderMap())
1089 continue;
1090
1091 // Try to load a module map file for the search directory.
1092 loadModuleMapFile(SearchDirs[Idx].getDir());
1093
1094 // Try to load module map files for immediate subdirectories of this search
1095 // directory.
1096 llvm::error_code EC;
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001097 SmallString<128> DirNative;
Douglas Gregorc5b2e582012-01-29 18:15:03 +00001098 llvm::sys::path::native(SearchDirs[Idx].getDir()->getName(), DirNative);
1099 for (llvm::sys::fs::directory_iterator Dir(DirNative.str(), EC), DirEnd;
1100 Dir != DirEnd && !EC; Dir.increment(EC)) {
1101 loadModuleMapFile(Dir->path());
1102 }
1103 }
1104
1105 // Populate the list of modules.
1106 for (ModuleMap::module_iterator M = ModMap.module_begin(),
1107 MEnd = ModMap.module_end();
1108 M != MEnd; ++M) {
1109 Modules.push_back(M->getValue());
1110 }
1111}