blob: e56eb6c915ca3a1222ad5745e7409f31587a3e2d [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"
Chris Lattner822da612007-12-17 06:36:45 +000015#include "clang/Lex/HeaderMap.h"
Chandler Carruthcb381ea2011-12-09 01:33:57 +000016#include "clang/Lex/Lexer.h"
Douglas Gregora30cfe52011-11-11 19:10:28 +000017#include "clang/Basic/Diagnostic.h"
Chris Lattnerc7229c32007-10-07 08:58:51 +000018#include "clang/Basic/FileManager.h"
19#include "clang/Basic/IdentifierTable.h"
Michael J. Spencer32bef4e2011-01-10 02:34:13 +000020#include "llvm/Support/FileSystem.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000021#include "llvm/Support/Path.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "llvm/ADT/SmallString.h"
Ted Kremenekeabea452011-07-27 18:41:18 +000023#include "llvm/Support/Capacity.h"
Chris Lattner3daed522009-03-02 22:20:04 +000024#include <cstdio>
Reid Spencer5f016e22007-07-11 17:01:13 +000025using namespace clang;
26
Douglas Gregor8c5a7602009-04-25 23:30:02 +000027const IdentifierInfo *
28HeaderFileInfo::getControllingMacro(ExternalIdentifierLookup *External) {
29 if (ControllingMacro)
30 return ControllingMacro;
31
32 if (!ControllingMacroID || !External)
33 return 0;
34
35 ControllingMacro = External->GetIdentifier(ControllingMacroID);
36 return ControllingMacro;
37}
38
Douglas Gregorcfbf1c72011-02-10 17:09:37 +000039ExternalHeaderFileInfoSource::~ExternalHeaderFileInfoSource() {}
40
Douglas Gregor51f564f2011-12-31 04:05:44 +000041HeaderSearch::HeaderSearch(FileManager &FM, DiagnosticsEngine &Diags,
42 const LangOptions &LangOpts)
Douglas Gregora30cfe52011-11-11 19:10:28 +000043 : FileMgr(FM), Diags(Diags), FrameworkMap(64),
Douglas Gregor51f564f2011-12-31 04:05:44 +000044 ModMap(FileMgr, *Diags.getClient(), LangOpts)
Douglas Gregor8e238062011-11-11 00:35:06 +000045{
Nico Weber74a5fd82011-05-24 04:31:14 +000046 AngledDirIdx = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000047 SystemDirIdx = 0;
48 NoCurDirSearch = false;
Mike Stump1eb44332009-09-09 15:08:12 +000049
Douglas Gregor8c5a7602009-04-25 23:30:02 +000050 ExternalLookup = 0;
Douglas Gregorcfbf1c72011-02-10 17:09:37 +000051 ExternalSource = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000052 NumIncluded = 0;
53 NumMultiIncludeFileOptzn = 0;
54 NumFrameworkLookups = NumSubFrameworkLookups = 0;
55}
56
Chris Lattner822da612007-12-17 06:36:45 +000057HeaderSearch::~HeaderSearch() {
58 // Delete headermaps.
59 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
60 delete HeaderMaps[i].second;
61}
Mike Stump1eb44332009-09-09 15:08:12 +000062
Reid Spencer5f016e22007-07-11 17:01:13 +000063void HeaderSearch::PrintStats() {
64 fprintf(stderr, "\n*** HeaderSearch Stats:\n");
65 fprintf(stderr, "%d files tracked.\n", (int)FileInfo.size());
66 unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0;
67 for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) {
68 NumOnceOnlyFiles += FileInfo[i].isImport;
69 if (MaxNumIncludes < FileInfo[i].NumIncludes)
70 MaxNumIncludes = FileInfo[i].NumIncludes;
71 NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1;
72 }
73 fprintf(stderr, " %d #import/#pragma once files.\n", NumOnceOnlyFiles);
74 fprintf(stderr, " %d included exactly once.\n", NumSingleIncludedFiles);
75 fprintf(stderr, " %d max times a file is included.\n", MaxNumIncludes);
Mike Stump1eb44332009-09-09 15:08:12 +000076
Reid Spencer5f016e22007-07-11 17:01:13 +000077 fprintf(stderr, " %d #include/#include_next/#import.\n", NumIncluded);
78 fprintf(stderr, " %d #includes skipped due to"
79 " the multi-include optimization.\n", NumMultiIncludeFileOptzn);
Mike Stump1eb44332009-09-09 15:08:12 +000080
Reid Spencer5f016e22007-07-11 17:01:13 +000081 fprintf(stderr, "%d framework lookups.\n", NumFrameworkLookups);
82 fprintf(stderr, "%d subframework lookups.\n", NumSubFrameworkLookups);
83}
84
Chris Lattner822da612007-12-17 06:36:45 +000085/// CreateHeaderMap - This method returns a HeaderMap for the specified
86/// FileEntry, uniquing them through the the 'HeaderMaps' datastructure.
Chris Lattner1bfd4a62007-12-17 18:34:53 +000087const HeaderMap *HeaderSearch::CreateHeaderMap(const FileEntry *FE) {
Chris Lattner822da612007-12-17 06:36:45 +000088 // We expect the number of headermaps to be small, and almost always empty.
Chris Lattnerdf772332007-12-17 07:52:39 +000089 // If it ever grows, use of a linear search should be re-evaluated.
Chris Lattner822da612007-12-17 06:36:45 +000090 if (!HeaderMaps.empty()) {
91 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
Chris Lattnerdf772332007-12-17 07:52:39 +000092 // Pointer equality comparison of FileEntries works because they are
93 // already uniqued by inode.
Mike Stump1eb44332009-09-09 15:08:12 +000094 if (HeaderMaps[i].first == FE)
Chris Lattner822da612007-12-17 06:36:45 +000095 return HeaderMaps[i].second;
96 }
Mike Stump1eb44332009-09-09 15:08:12 +000097
Chris Lattner39b49bc2010-11-23 08:35:12 +000098 if (const HeaderMap *HM = HeaderMap::Create(FE, FileMgr)) {
Chris Lattner822da612007-12-17 06:36:45 +000099 HeaderMaps.push_back(std::make_pair(FE, HM));
100 return HM;
101 }
Mike Stump1eb44332009-09-09 15:08:12 +0000102
Chris Lattner822da612007-12-17 06:36:45 +0000103 return 0;
104}
105
Douglas Gregore434ec72012-01-29 17:08:11 +0000106std::string HeaderSearch::getModuleFileName(Module *Module) {
Douglas Gregor9a6da692011-09-12 20:41:59 +0000107 // If we don't have a module cache path, we can't do anything.
Douglas Gregore434ec72012-01-29 17:08:11 +0000108 if (ModuleCachePath.empty())
109 return std::string();
110
111
112 llvm::SmallString<256> Result(ModuleCachePath);
113 llvm::sys::path::append(Result, Module->getTopLevelModule()->Name + ".pcm");
114 return Result.str().str();
115}
116
117std::string HeaderSearch::getModuleFileName(StringRef ModuleName) {
118 // If we don't have a module cache path, we can't do anything.
119 if (ModuleCachePath.empty())
120 return std::string();
Douglas Gregor6e975c42011-09-13 23:15:45 +0000121
Douglas Gregore434ec72012-01-29 17:08:11 +0000122
123 llvm::SmallString<256> Result(ModuleCachePath);
124 llvm::sys::path::append(Result, ModuleName + ".pcm");
125 return Result.str().str();
126}
127
128Module *HeaderSearch::lookupModule(StringRef ModuleName, bool AllowSearch) {
Douglas Gregorcf70d782011-11-12 00:05:07 +0000129 // Look in the module map to determine if there is a module by this name.
Douglas Gregore434ec72012-01-29 17:08:11 +0000130 Module *Module = ModMap.findModule(ModuleName);
131 if (Module || !AllowSearch)
132 return Module;
133
134 // Look through the various header search paths to load any avai;able module
135 // maps, searching for a module map that describes this module.
136 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
137 if (SearchDirs[Idx].isFramework()) {
138 // Search for or infer a module map for a framework.
139 llvm::SmallString<128> FrameworkDirName;
140 FrameworkDirName += SearchDirs[Idx].getFrameworkDir()->getName();
141 llvm::sys::path::append(FrameworkDirName, ModuleName + ".framework");
142 if (const DirectoryEntry *FrameworkDir
143 = FileMgr.getDirectory(FrameworkDirName)) {
144 bool IsSystem
145 = SearchDirs[Idx].getDirCharacteristic() != SrcMgr::C_User;
146 Module = loadFrameworkModule(ModuleName, FrameworkDir, IsSystem);
Douglas Gregorcf70d782011-11-12 00:05:07 +0000147 if (Module)
148 break;
149 }
Douglas Gregore434ec72012-01-29 17:08:11 +0000150 }
151
152 // FIXME: Figure out how header maps and module maps will work together.
153
154 // Only deal with normal search directories.
155 if (!SearchDirs[Idx].isNormalDir())
156 continue;
157
158 // Search for a module map file in this directory.
159 if (loadModuleMapFile(SearchDirs[Idx].getDir()) == LMM_NewlyLoaded) {
160 // We just loaded a module map file; check whether the module is
161 // available now.
162 Module = ModMap.findModule(ModuleName);
163 if (Module)
164 break;
165 }
166
167 // Search for a module map in a subdirectory with the same name as the
168 // module.
169 llvm::SmallString<128> NestedModuleMapDirName;
170 NestedModuleMapDirName = SearchDirs[Idx].getDir()->getName();
171 llvm::sys::path::append(NestedModuleMapDirName, ModuleName);
172 if (loadModuleMapFile(NestedModuleMapDirName) == LMM_NewlyLoaded) {
173 // If we just loaded a module map file, look for the module again.
174 Module = ModMap.findModule(ModuleName);
175 if (Module)
176 break;
Douglas Gregorcf70d782011-11-12 00:05:07 +0000177 }
178 }
Douglas Gregore434ec72012-01-29 17:08:11 +0000179
180 return Module;
Douglas Gregor9a6da692011-09-12 20:41:59 +0000181}
182
Chris Lattnerdf772332007-12-17 07:52:39 +0000183//===----------------------------------------------------------------------===//
184// File lookup within a DirectoryLookup scope
185//===----------------------------------------------------------------------===//
186
Chris Lattner3af66a92007-12-17 17:57:27 +0000187/// getName - Return the directory or filename corresponding to this lookup
188/// object.
189const char *DirectoryLookup::getName() const {
190 if (isNormalDir())
191 return getDir()->getName();
192 if (isFramework())
193 return getFrameworkDir()->getName();
194 assert(isHeaderMap() && "Unknown DirectoryLookup");
195 return getHeaderMap()->getFileName();
196}
197
198
Chris Lattnerdf772332007-12-17 07:52:39 +0000199/// LookupFile - Lookup the specified file in this search path, returning it
200/// if it exists or returning null if not.
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000201const FileEntry *DirectoryLookup::LookupFile(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000202 StringRef Filename,
Manuel Klimek74124942011-04-26 21:50:03 +0000203 HeaderSearch &HS,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000204 SmallVectorImpl<char> *SearchPath,
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000205 SmallVectorImpl<char> *RelativePath,
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000206 Module **SuggestedModule) const {
Chris Lattnerdf772332007-12-17 07:52:39 +0000207 llvm::SmallString<1024> TmpDir;
Chris Lattnerafded5b2007-12-17 08:13:48 +0000208 if (isNormalDir()) {
209 // Concatenate the requested file onto the directory.
Eli Friedmana6e023c2011-07-08 20:17:28 +0000210 TmpDir = getDir()->getName();
211 llvm::sys::path::append(TmpDir, Filename);
Manuel Klimek74124942011-04-26 21:50:03 +0000212 if (SearchPath != NULL) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000213 StringRef SearchPathRef(getDir()->getName());
Manuel Klimek74124942011-04-26 21:50:03 +0000214 SearchPath->clear();
215 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
216 }
217 if (RelativePath != NULL) {
218 RelativePath->clear();
219 RelativePath->append(Filename.begin(), Filename.end());
220 }
Douglas Gregora30cfe52011-11-11 19:10:28 +0000221
222 // If we have a module map that might map this header, load it and
223 // check whether we'll have a suggestion for a module.
224 if (SuggestedModule && HS.hasModuleMap(TmpDir, getDir())) {
225 const FileEntry *File = HS.getFileMgr().getFile(TmpDir.str(),
226 /*openFile=*/false);
227 if (!File)
228 return File;
229
230 // If there is a module that corresponds to this header,
231 // suggest it.
Douglas Gregor5e3f9222011-12-08 17:01:29 +0000232 *SuggestedModule = HS.findModuleForHeader(File);
Douglas Gregora30cfe52011-11-11 19:10:28 +0000233 return File;
234 }
235
Argyrios Kyrtzidis3cd01282011-03-16 19:17:25 +0000236 return HS.getFileMgr().getFile(TmpDir.str(), /*openFile=*/true);
Chris Lattnerafded5b2007-12-17 08:13:48 +0000237 }
Mike Stump1eb44332009-09-09 15:08:12 +0000238
Chris Lattnerafded5b2007-12-17 08:13:48 +0000239 if (isFramework())
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000240 return DoFrameworkLookup(Filename, HS, SearchPath, RelativePath,
Douglas Gregor5e3f9222011-12-08 17:01:29 +0000241 SuggestedModule);
Mike Stump1eb44332009-09-09 15:08:12 +0000242
Chris Lattnerb09e71f2007-12-17 08:17:39 +0000243 assert(isHeaderMap() && "Unknown directory lookup");
Manuel Klimek74124942011-04-26 21:50:03 +0000244 const FileEntry * const Result = getHeaderMap()->LookupFile(
245 Filename, HS.getFileMgr());
246 if (Result) {
247 if (SearchPath != NULL) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000248 StringRef SearchPathRef(getName());
Manuel Klimek74124942011-04-26 21:50:03 +0000249 SearchPath->clear();
250 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
251 }
252 if (RelativePath != NULL) {
253 RelativePath->clear();
254 RelativePath->append(Filename.begin(), Filename.end());
255 }
256 }
257 return Result;
Chris Lattnerdf772332007-12-17 07:52:39 +0000258}
259
260
Chris Lattnerafded5b2007-12-17 08:13:48 +0000261/// DoFrameworkLookup - Do a lookup of the specified file in the current
262/// DirectoryLookup, which is a framework directory.
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000263const FileEntry *DirectoryLookup::DoFrameworkLookup(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000264 StringRef Filename,
Manuel Klimek74124942011-04-26 21:50:03 +0000265 HeaderSearch &HS,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000266 SmallVectorImpl<char> *SearchPath,
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000267 SmallVectorImpl<char> *RelativePath,
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000268 Module **SuggestedModule) const
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000269{
Chris Lattnerafded5b2007-12-17 08:13:48 +0000270 FileManager &FileMgr = HS.getFileMgr();
Mike Stump1eb44332009-09-09 15:08:12 +0000271
Reid Spencer5f016e22007-07-11 17:01:13 +0000272 // Framework names must have a '/' in the filename.
Chris Lattnera1394812010-01-10 01:35:12 +0000273 size_t SlashPos = Filename.find('/');
Chris Lattner5f9e2722011-07-23 10:55:15 +0000274 if (SlashPos == StringRef::npos) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000275
Chris Lattnerafded5b2007-12-17 08:13:48 +0000276 // Find out if this is the home for the specified framework, by checking
277 // HeaderSearch. Possible answer are yes/no and unknown.
Mike Stump1eb44332009-09-09 15:08:12 +0000278 const DirectoryEntry *&FrameworkDirCache =
Chris Lattnera1394812010-01-10 01:35:12 +0000279 HS.LookupFrameworkCache(Filename.substr(0, SlashPos));
Mike Stump1eb44332009-09-09 15:08:12 +0000280
Chris Lattnerafded5b2007-12-17 08:13:48 +0000281 // If it is known and in some other directory, fail.
282 if (FrameworkDirCache && FrameworkDirCache != getFrameworkDir())
Reid Spencer5f016e22007-07-11 17:01:13 +0000283 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000284
Chris Lattnerafded5b2007-12-17 08:13:48 +0000285 // Otherwise, construct the path to this framework dir.
Mike Stump1eb44332009-09-09 15:08:12 +0000286
Reid Spencer5f016e22007-07-11 17:01:13 +0000287 // FrameworkName = "/System/Library/Frameworks/"
288 llvm::SmallString<1024> FrameworkName;
Chris Lattnerafded5b2007-12-17 08:13:48 +0000289 FrameworkName += getFrameworkDir()->getName();
Reid Spencer5f016e22007-07-11 17:01:13 +0000290 if (FrameworkName.empty() || FrameworkName.back() != '/')
291 FrameworkName.push_back('/');
Mike Stump1eb44332009-09-09 15:08:12 +0000292
Reid Spencer5f016e22007-07-11 17:01:13 +0000293 // FrameworkName = "/System/Library/Frameworks/Cocoa"
Douglas Gregor2821c7f2011-11-17 01:41:17 +0000294 StringRef ModuleName(Filename.begin(), SlashPos);
295 FrameworkName += ModuleName;
Mike Stump1eb44332009-09-09 15:08:12 +0000296
Reid Spencer5f016e22007-07-11 17:01:13 +0000297 // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/"
298 FrameworkName += ".framework/";
Mike Stump1eb44332009-09-09 15:08:12 +0000299
Chris Lattnerafded5b2007-12-17 08:13:48 +0000300 // If the cache entry is still unresolved, query to see if the cache entry is
301 // still unresolved. If so, check its existence now.
302 if (FrameworkDirCache == 0) {
303 HS.IncrementFrameworkLookupCount();
Mike Stump1eb44332009-09-09 15:08:12 +0000304
Reid Spencer5f016e22007-07-11 17:01:13 +0000305 // If the framework dir doesn't exist, we fail.
Chris Lattnerafded5b2007-12-17 08:13:48 +0000306 // FIXME: It's probably more efficient to query this with FileMgr.getDir.
Michael J. Spencer32bef4e2011-01-10 02:34:13 +0000307 bool Exists;
308 if (llvm::sys::fs::exists(FrameworkName.str(), Exists) || !Exists)
Reid Spencer5f016e22007-07-11 17:01:13 +0000309 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000310
Reid Spencer5f016e22007-07-11 17:01:13 +0000311 // Otherwise, if it does, remember that this is the right direntry for this
312 // framework.
Chris Lattnerafded5b2007-12-17 08:13:48 +0000313 FrameworkDirCache = getFrameworkDir();
Reid Spencer5f016e22007-07-11 17:01:13 +0000314 }
Mike Stump1eb44332009-09-09 15:08:12 +0000315
Manuel Klimek74124942011-04-26 21:50:03 +0000316 if (RelativePath != NULL) {
317 RelativePath->clear();
318 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
319 }
320
Douglas Gregor2821c7f2011-11-17 01:41:17 +0000321 // If we're allowed to look for modules, try to load or create the module
322 // corresponding to this framework.
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000323 Module *Module = 0;
Douglas Gregor2821c7f2011-11-17 01:41:17 +0000324 if (SuggestedModule) {
325 if (const DirectoryEntry *FrameworkDir
Douglas Gregora1f1fad2012-01-27 19:52:33 +0000326 = FileMgr.getDirectory(FrameworkName)) {
327 bool IsSystem = getDirCharacteristic() != SrcMgr::C_User;
Douglas Gregore434ec72012-01-29 17:08:11 +0000328 Module = HS.loadFrameworkModule(ModuleName, FrameworkDir, IsSystem);
Douglas Gregora1f1fad2012-01-27 19:52:33 +0000329 }
Douglas Gregor2821c7f2011-11-17 01:41:17 +0000330 }
331
Reid Spencer5f016e22007-07-11 17:01:13 +0000332 // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"
333 unsigned OrigSize = FrameworkName.size();
Mike Stump1eb44332009-09-09 15:08:12 +0000334
Reid Spencer5f016e22007-07-11 17:01:13 +0000335 FrameworkName += "Headers/";
Manuel Klimek74124942011-04-26 21:50:03 +0000336
337 if (SearchPath != NULL) {
338 SearchPath->clear();
339 // Without trailing '/'.
340 SearchPath->append(FrameworkName.begin(), FrameworkName.end()-1);
341 }
342
Douglas Gregor2821c7f2011-11-17 01:41:17 +0000343 // Determine whether this is the module we're building or not.
Douglas Gregor09833922011-12-06 17:31:28 +0000344 bool AutomaticImport = Module;
Chris Lattnera1394812010-01-10 01:35:12 +0000345 FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end());
Argyrios Kyrtzidis3cd01282011-03-16 19:17:25 +0000346 if (const FileEntry *FE = FileMgr.getFile(FrameworkName.str(),
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000347 /*openFile=*/!AutomaticImport)) {
348 if (AutomaticImport)
Douglas Gregor09833922011-12-06 17:31:28 +0000349 *SuggestedModule = HS.findModuleForHeader(FE);
Reid Spencer5f016e22007-07-11 17:01:13 +0000350 return FE;
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000351 }
Mike Stump1eb44332009-09-09 15:08:12 +0000352
Reid Spencer5f016e22007-07-11 17:01:13 +0000353 // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"
354 const char *Private = "Private";
Mike Stump1eb44332009-09-09 15:08:12 +0000355 FrameworkName.insert(FrameworkName.begin()+OrigSize, Private,
Reid Spencer5f016e22007-07-11 17:01:13 +0000356 Private+strlen(Private));
Manuel Klimek74124942011-04-26 21:50:03 +0000357 if (SearchPath != NULL)
358 SearchPath->insert(SearchPath->begin()+OrigSize, Private,
359 Private+strlen(Private));
360
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000361 const FileEntry *FE = FileMgr.getFile(FrameworkName.str(),
362 /*openFile=*/!AutomaticImport);
363 if (FE && AutomaticImport)
Douglas Gregor09833922011-12-06 17:31:28 +0000364 *SuggestedModule = HS.findModuleForHeader(FE);
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000365 return FE;
Reid Spencer5f016e22007-07-11 17:01:13 +0000366}
367
Chris Lattnerdf772332007-12-17 07:52:39 +0000368
Chris Lattnerafded5b2007-12-17 08:13:48 +0000369//===----------------------------------------------------------------------===//
370// Header File Location.
371//===----------------------------------------------------------------------===//
372
373
Reid Spencer5f016e22007-07-11 17:01:13 +0000374/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
375/// return null on failure. isAngled indicates whether the file reference is
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000376/// for system #include's or not (i.e. using <> instead of ""). CurFileEnt, if
377/// non-null, indicates where the #including file is, in case a relative search
378/// is needed.
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000379const FileEntry *HeaderSearch::LookupFile(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000380 StringRef Filename,
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000381 bool isAngled,
382 const DirectoryLookup *FromDir,
383 const DirectoryLookup *&CurDir,
384 const FileEntry *CurFileEnt,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000385 SmallVectorImpl<char> *SearchPath,
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000386 SmallVectorImpl<char> *RelativePath,
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000387 Module **SuggestedModule,
Douglas Gregor1c2e9332011-11-20 17:46:46 +0000388 bool SkipCache)
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000389{
390 if (SuggestedModule)
Douglas Gregorc69c42e2011-11-17 22:44:56 +0000391 *SuggestedModule = 0;
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000392
Reid Spencer5f016e22007-07-11 17:01:13 +0000393 // If 'Filename' is absolute, check to see if it exists and no searching.
Michael J. Spencer256053b2010-12-17 21:22:22 +0000394 if (llvm::sys::path::is_absolute(Filename)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000395 CurDir = 0;
396
397 // If this was an #include_next "/absolute/file", fail.
398 if (FromDir) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000399
Manuel Klimek74124942011-04-26 21:50:03 +0000400 if (SearchPath != NULL)
401 SearchPath->clear();
402 if (RelativePath != NULL) {
403 RelativePath->clear();
404 RelativePath->append(Filename.begin(), Filename.end());
405 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000406 // Otherwise, just return the file.
Argyrios Kyrtzidis3cd01282011-03-16 19:17:25 +0000407 return FileMgr.getFile(Filename, /*openFile=*/true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000408 }
Mike Stump1eb44332009-09-09 15:08:12 +0000409
Douglas Gregor65e02fa2011-07-28 04:45:53 +0000410 // Unless disabled, check to see if the file is in the #includer's
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000411 // directory. This has to be based on CurFileEnt, not CurDir, because
412 // CurFileEnt could be a #include of a subdirectory (#include "foo/bar.h") and
Chris Lattnerdf772332007-12-17 07:52:39 +0000413 // a subsequent include of "baz.h" should resolve to "whatever/foo/baz.h".
414 // This search is not done for <> headers.
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000415 if (CurFileEnt && !isAngled && !NoCurDirSearch) {
416 llvm::SmallString<1024> TmpDir;
417 // Concatenate the requested file onto the directory.
418 // FIXME: Portability. Filename concatenation should be in sys::Path.
419 TmpDir += CurFileEnt->getDir()->getName();
420 TmpDir.push_back('/');
421 TmpDir.append(Filename.begin(), Filename.end());
Argyrios Kyrtzidis3cd01282011-03-16 19:17:25 +0000422 if (const FileEntry *FE = FileMgr.getFile(TmpDir.str(),/*openFile=*/true)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000423 // Leave CurDir unset.
Douglas Gregor10fe93d2010-08-08 07:49:23 +0000424 // This file is a system header or C++ unfriendly if the old file is.
425 //
426 // Note that the temporary 'DirInfo' is required here, as either call to
427 // getFileInfo could resize the vector and we don't want to rely on order
428 // of evaluation.
429 unsigned DirInfo = getFileInfo(CurFileEnt).DirInfo;
Chris Lattnerc9dde4f2008-02-25 21:38:21 +0000430 getFileInfo(FE).DirInfo = DirInfo;
Manuel Klimek74124942011-04-26 21:50:03 +0000431 if (SearchPath != NULL) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000432 StringRef SearchPathRef(CurFileEnt->getDir()->getName());
Manuel Klimek74124942011-04-26 21:50:03 +0000433 SearchPath->clear();
434 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
435 }
436 if (RelativePath != NULL) {
437 RelativePath->clear();
438 RelativePath->append(Filename.begin(), Filename.end());
439 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000440 return FE;
441 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000442 }
Mike Stump1eb44332009-09-09 15:08:12 +0000443
Reid Spencer5f016e22007-07-11 17:01:13 +0000444 CurDir = 0;
445
446 // If this is a system #include, ignore the user #include locs.
Nico Weber74a5fd82011-05-24 04:31:14 +0000447 unsigned i = isAngled ? AngledDirIdx : 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000448
Reid Spencer5f016e22007-07-11 17:01:13 +0000449 // If this is a #include_next request, start searching after the directory the
450 // file was found in.
451 if (FromDir)
452 i = FromDir-&SearchDirs[0];
Mike Stump1eb44332009-09-09 15:08:12 +0000453
Chris Lattner9960ae82007-07-22 07:28:00 +0000454 // Cache all of the lookups performed by this method. Many headers are
455 // multiply included, and the "pragma once" optimization prevents them from
456 // being relex/pp'd, but they would still have to search through a
457 // (potentially huge) series of SearchDirs to find it.
458 std::pair<unsigned, unsigned> &CacheLookup =
Chris Lattnera1394812010-01-10 01:35:12 +0000459 LookupFileCache.GetOrCreateValue(Filename).getValue();
Chris Lattner9960ae82007-07-22 07:28:00 +0000460
461 // If the entry has been previously looked up, the first value will be
462 // non-zero. If the value is equal to i (the start point of our search), then
463 // this is a matching hit.
Douglas Gregor1c2e9332011-11-20 17:46:46 +0000464 if (!SkipCache && CacheLookup.first == i+1) {
Chris Lattner9960ae82007-07-22 07:28:00 +0000465 // Skip querying potentially lots of directories for this lookup.
466 i = CacheLookup.second;
467 } else {
468 // Otherwise, this is the first query, or the previous query didn't match
469 // our search start. We will fill in our found location below, so prime the
470 // start point value.
471 CacheLookup.first = i+1;
472 }
Mike Stump1eb44332009-09-09 15:08:12 +0000473
Reid Spencer5f016e22007-07-11 17:01:13 +0000474 // Check each directory in sequence to see if it contains this file.
475 for (; i != SearchDirs.size(); ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +0000476 const FileEntry *FE =
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000477 SearchDirs[i].LookupFile(Filename, *this, SearchPath, RelativePath,
Douglas Gregor5e3f9222011-12-08 17:01:29 +0000478 SuggestedModule);
Chris Lattnerafded5b2007-12-17 08:13:48 +0000479 if (!FE) continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000480
Chris Lattnerafded5b2007-12-17 08:13:48 +0000481 CurDir = &SearchDirs[i];
Mike Stump1eb44332009-09-09 15:08:12 +0000482
Chris Lattnerafded5b2007-12-17 08:13:48 +0000483 // This file is a system header or C++ unfriendly if the dir is.
Douglas Gregor65e02fa2011-07-28 04:45:53 +0000484 HeaderFileInfo &HFI = getFileInfo(FE);
485 HFI.DirInfo = CurDir->getDirCharacteristic();
Mike Stump1eb44332009-09-09 15:08:12 +0000486
Douglas Gregor65e02fa2011-07-28 04:45:53 +0000487 // If this file is found in a header map and uses the framework style of
488 // includes, then this header is part of a framework we're building.
489 if (CurDir->isIndexHeaderMap()) {
490 size_t SlashPos = Filename.find('/');
491 if (SlashPos != StringRef::npos) {
492 HFI.IndexHeaderMapHeader = 1;
493 HFI.Framework = getUniqueFrameworkName(StringRef(Filename.begin(),
494 SlashPos));
495 }
496 }
497
Chris Lattnerafded5b2007-12-17 08:13:48 +0000498 // Remember this location for the next lookup we do.
499 CacheLookup.second = i;
500 return FE;
Reid Spencer5f016e22007-07-11 17:01:13 +0000501 }
Mike Stump1eb44332009-09-09 15:08:12 +0000502
Douglas Gregor2c7b7802011-07-30 06:28:34 +0000503 // If we are including a file with a quoted include "foo.h" from inside
504 // a header in a framework that is currently being built, and we couldn't
505 // resolve "foo.h" any other way, change the include to <Foo/foo.h>, where
506 // "Foo" is the name of the framework in which the including header was found.
507 if (CurFileEnt && !isAngled && Filename.find('/') == StringRef::npos) {
508 HeaderFileInfo &IncludingHFI = getFileInfo(CurFileEnt);
509 if (IncludingHFI.IndexHeaderMapHeader) {
510 llvm::SmallString<128> ScratchFilename;
511 ScratchFilename += IncludingHFI.Framework;
512 ScratchFilename += '/';
513 ScratchFilename += Filename;
514
515 const FileEntry *Result = LookupFile(ScratchFilename, /*isAngled=*/true,
516 FromDir, CurDir, CurFileEnt,
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000517 SearchPath, RelativePath,
518 SuggestedModule);
Douglas Gregor2c7b7802011-07-30 06:28:34 +0000519 std::pair<unsigned, unsigned> &CacheLookup
520 = LookupFileCache.GetOrCreateValue(Filename).getValue();
521 CacheLookup.second
522 = LookupFileCache.GetOrCreateValue(ScratchFilename).getValue().second;
523 return Result;
524 }
525 }
526
Chris Lattner9960ae82007-07-22 07:28:00 +0000527 // Otherwise, didn't find it. Remember we didn't find this.
528 CacheLookup.second = SearchDirs.size();
Reid Spencer5f016e22007-07-11 17:01:13 +0000529 return 0;
530}
531
532/// LookupSubframeworkHeader - Look up a subframework for the specified
533/// #include file. For example, if #include'ing <HIToolbox/HIToolbox.h> from
534/// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
535/// is a subframework within Carbon.framework. If so, return the FileEntry
536/// for the designated file, otherwise return null.
537const FileEntry *HeaderSearch::
Chris Lattner5f9e2722011-07-23 10:55:15 +0000538LookupSubframeworkHeader(StringRef Filename,
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000539 const FileEntry *ContextFileEnt,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000540 SmallVectorImpl<char> *SearchPath,
541 SmallVectorImpl<char> *RelativePath) {
Chris Lattner9415a0c2008-02-01 05:34:02 +0000542 assert(ContextFileEnt && "No context file?");
Mike Stump1eb44332009-09-09 15:08:12 +0000543
Reid Spencer5f016e22007-07-11 17:01:13 +0000544 // Framework names must have a '/' in the filename. Find it.
Douglas Gregorefda0e82011-12-09 16:48:01 +0000545 // FIXME: Should we permit '\' on Windows?
Chris Lattnera1394812010-01-10 01:35:12 +0000546 size_t SlashPos = Filename.find('/');
Chris Lattner5f9e2722011-07-23 10:55:15 +0000547 if (SlashPos == StringRef::npos) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000548
Reid Spencer5f016e22007-07-11 17:01:13 +0000549 // Look up the base framework name of the ContextFileEnt.
550 const char *ContextName = ContextFileEnt->getName();
Mike Stump1eb44332009-09-09 15:08:12 +0000551
Reid Spencer5f016e22007-07-11 17:01:13 +0000552 // If the context info wasn't a framework, couldn't be a subframework.
Douglas Gregorefda0e82011-12-09 16:48:01 +0000553 const unsigned DotFrameworkLen = 10;
554 const char *FrameworkPos = strstr(ContextName, ".framework");
555 if (FrameworkPos == 0 ||
556 (FrameworkPos[DotFrameworkLen] != '/' &&
557 FrameworkPos[DotFrameworkLen] != '\\'))
Reid Spencer5f016e22007-07-11 17:01:13 +0000558 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000559
560 llvm::SmallString<1024> FrameworkName(ContextName,
Douglas Gregorefda0e82011-12-09 16:48:01 +0000561 FrameworkPos+DotFrameworkLen+1);
Reid Spencer5f016e22007-07-11 17:01:13 +0000562
563 // Append Frameworks/HIToolbox.framework/
564 FrameworkName += "Frameworks/";
Chris Lattnera1394812010-01-10 01:35:12 +0000565 FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos);
Reid Spencer5f016e22007-07-11 17:01:13 +0000566 FrameworkName += ".framework/";
567
568 llvm::StringMapEntry<const DirectoryEntry *> &CacheLookup =
Chris Lattner65382272010-11-21 09:55:08 +0000569 FrameworkMap.GetOrCreateValue(Filename.substr(0, SlashPos));
Mike Stump1eb44332009-09-09 15:08:12 +0000570
Reid Spencer5f016e22007-07-11 17:01:13 +0000571 // Some other location?
572 if (CacheLookup.getValue() &&
573 CacheLookup.getKeyLength() == FrameworkName.size() &&
574 memcmp(CacheLookup.getKeyData(), &FrameworkName[0],
575 CacheLookup.getKeyLength()) != 0)
576 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000577
Reid Spencer5f016e22007-07-11 17:01:13 +0000578 // Cache subframework.
579 if (CacheLookup.getValue() == 0) {
580 ++NumSubFrameworkLookups;
Mike Stump1eb44332009-09-09 15:08:12 +0000581
Reid Spencer5f016e22007-07-11 17:01:13 +0000582 // If the framework dir doesn't exist, we fail.
Chris Lattner39b49bc2010-11-23 08:35:12 +0000583 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName.str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000584 if (Dir == 0) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000585
Reid Spencer5f016e22007-07-11 17:01:13 +0000586 // Otherwise, if it does, remember that this is the right direntry for this
587 // framework.
588 CacheLookup.setValue(Dir);
589 }
Mike Stump1eb44332009-09-09 15:08:12 +0000590
Reid Spencer5f016e22007-07-11 17:01:13 +0000591 const FileEntry *FE = 0;
592
Manuel Klimek74124942011-04-26 21:50:03 +0000593 if (RelativePath != NULL) {
594 RelativePath->clear();
595 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
596 }
597
Reid Spencer5f016e22007-07-11 17:01:13 +0000598 // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
599 llvm::SmallString<1024> HeadersFilename(FrameworkName);
600 HeadersFilename += "Headers/";
Manuel Klimek74124942011-04-26 21:50:03 +0000601 if (SearchPath != NULL) {
602 SearchPath->clear();
603 // Without trailing '/'.
604 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
605 }
606
Chris Lattnera1394812010-01-10 01:35:12 +0000607 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
Argyrios Kyrtzidis3cd01282011-03-16 19:17:25 +0000608 if (!(FE = FileMgr.getFile(HeadersFilename.str(), /*openFile=*/true))) {
Mike Stump1eb44332009-09-09 15:08:12 +0000609
Reid Spencer5f016e22007-07-11 17:01:13 +0000610 // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
611 HeadersFilename = FrameworkName;
612 HeadersFilename += "PrivateHeaders/";
Manuel Klimek74124942011-04-26 21:50:03 +0000613 if (SearchPath != NULL) {
614 SearchPath->clear();
615 // Without trailing '/'.
616 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
617 }
618
Chris Lattnera1394812010-01-10 01:35:12 +0000619 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
Argyrios Kyrtzidis3cd01282011-03-16 19:17:25 +0000620 if (!(FE = FileMgr.getFile(HeadersFilename.str(), /*openFile=*/true)))
Reid Spencer5f016e22007-07-11 17:01:13 +0000621 return 0;
622 }
Mike Stump1eb44332009-09-09 15:08:12 +0000623
Reid Spencer5f016e22007-07-11 17:01:13 +0000624 // This file is a system header or C++ unfriendly if the old file is.
Ted Kremenekca63fa02008-02-24 03:55:14 +0000625 //
Chris Lattnerc9dde4f2008-02-25 21:38:21 +0000626 // Note that the temporary 'DirInfo' is required here, as either call to
627 // getFileInfo could resize the vector and we don't want to rely on order
628 // of evaluation.
629 unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo;
630 getFileInfo(FE).DirInfo = DirInfo;
Reid Spencer5f016e22007-07-11 17:01:13 +0000631 return FE;
632}
633
Chandler Carruthcb381ea2011-12-09 01:33:57 +0000634/// \brief Helper static function to normalize a path for injection into
635/// a synthetic header.
636/*static*/ std::string
637HeaderSearch::NormalizeDashIncludePath(StringRef File, FileManager &FileMgr) {
638 // Implicit include paths should be resolved relative to the current
639 // working directory first, and then use the regular header search
640 // mechanism. The proper way to handle this is to have the
641 // predefines buffer located at the current working directory, but
642 // it has no file entry. For now, workaround this by using an
643 // absolute path if we find the file here, and otherwise letting
644 // header search handle it.
645 llvm::SmallString<128> Path(File);
646 llvm::sys::fs::make_absolute(Path);
647 bool exists;
648 if (llvm::sys::fs::exists(Path.str(), exists) || !exists)
649 Path = File;
650 else if (exists)
651 FileMgr.getFile(File);
652
653 return Lexer::Stringify(Path.str());
654}
655
Reid Spencer5f016e22007-07-11 17:01:13 +0000656//===----------------------------------------------------------------------===//
657// File Info Management.
658//===----------------------------------------------------------------------===//
659
Douglas Gregor8f8d5812011-09-17 05:35:18 +0000660/// \brief Merge the header file info provided by \p OtherHFI into the current
661/// header file info (\p HFI)
662static void mergeHeaderFileInfo(HeaderFileInfo &HFI,
663 const HeaderFileInfo &OtherHFI) {
664 HFI.isImport |= OtherHFI.isImport;
665 HFI.isPragmaOnce |= OtherHFI.isPragmaOnce;
666 HFI.NumIncludes += OtherHFI.NumIncludes;
667
668 if (!HFI.ControllingMacro && !HFI.ControllingMacroID) {
669 HFI.ControllingMacro = OtherHFI.ControllingMacro;
670 HFI.ControllingMacroID = OtherHFI.ControllingMacroID;
671 }
672
673 if (OtherHFI.External) {
674 HFI.DirInfo = OtherHFI.DirInfo;
675 HFI.External = OtherHFI.External;
676 HFI.IndexHeaderMapHeader = OtherHFI.IndexHeaderMapHeader;
677 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000678
Douglas Gregor8f8d5812011-09-17 05:35:18 +0000679 if (HFI.Framework.empty())
680 HFI.Framework = OtherHFI.Framework;
681
682 HFI.Resolved = true;
683}
684
Steve Naroff83d63c72009-04-24 20:03:17 +0000685/// getFileInfo - Return the HeaderFileInfo structure for the specified
Reid Spencer5f016e22007-07-11 17:01:13 +0000686/// FileEntry.
Steve Naroff83d63c72009-04-24 20:03:17 +0000687HeaderFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000688 if (FE->getUID() >= FileInfo.size())
689 FileInfo.resize(FE->getUID()+1);
Douglas Gregorcfbf1c72011-02-10 17:09:37 +0000690
691 HeaderFileInfo &HFI = FileInfo[FE->getUID()];
Douglas Gregor8f8d5812011-09-17 05:35:18 +0000692 if (ExternalSource && !HFI.Resolved)
693 mergeHeaderFileInfo(HFI, ExternalSource->GetHeaderFileInfo(FE));
Douglas Gregorcfbf1c72011-02-10 17:09:37 +0000694 return HFI;
Mike Stump1eb44332009-09-09 15:08:12 +0000695}
Reid Spencer5f016e22007-07-11 17:01:13 +0000696
Douglas Gregordd3e5542011-05-04 00:14:37 +0000697bool HeaderSearch::isFileMultipleIncludeGuarded(const FileEntry *File) {
698 // Check if we've ever seen this file as a header.
699 if (File->getUID() >= FileInfo.size())
700 return false;
701
702 // Resolve header file info from the external source, if needed.
703 HeaderFileInfo &HFI = FileInfo[File->getUID()];
Douglas Gregor8f8d5812011-09-17 05:35:18 +0000704 if (ExternalSource && !HFI.Resolved)
705 mergeHeaderFileInfo(HFI, ExternalSource->GetHeaderFileInfo(File));
Douglas Gregordd3e5542011-05-04 00:14:37 +0000706
707 return HFI.isPragmaOnce || HFI.ControllingMacro || HFI.ControllingMacroID;
708}
709
Steve Naroff83d63c72009-04-24 20:03:17 +0000710void HeaderSearch::setHeaderFileInfoForUID(HeaderFileInfo HFI, unsigned UID) {
711 if (UID >= FileInfo.size())
712 FileInfo.resize(UID+1);
Douglas Gregorcfbf1c72011-02-10 17:09:37 +0000713 HFI.Resolved = true;
Steve Naroff83d63c72009-04-24 20:03:17 +0000714 FileInfo[UID] = HFI;
715}
716
Reid Spencer5f016e22007-07-11 17:01:13 +0000717/// ShouldEnterIncludeFile - Mark the specified file as a target of of a
718/// #include, #include_next, or #import directive. Return false if #including
719/// the file will have no effect or true if we should include it.
720bool HeaderSearch::ShouldEnterIncludeFile(const FileEntry *File, bool isImport){
721 ++NumIncluded; // Count # of attempted #includes.
722
723 // Get information about this file.
Steve Naroff83d63c72009-04-24 20:03:17 +0000724 HeaderFileInfo &FileInfo = getFileInfo(File);
Mike Stump1eb44332009-09-09 15:08:12 +0000725
Reid Spencer5f016e22007-07-11 17:01:13 +0000726 // If this is a #import directive, check that we have not already imported
727 // this header.
728 if (isImport) {
729 // If this has already been imported, don't import it again.
730 FileInfo.isImport = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000731
Reid Spencer5f016e22007-07-11 17:01:13 +0000732 // Has this already been #import'ed or #include'd?
733 if (FileInfo.NumIncludes) return false;
734 } else {
735 // Otherwise, if this is a #include of a file that was previously #import'd
736 // or if this is the second #include of a #pragma once file, ignore it.
737 if (FileInfo.isImport)
738 return false;
739 }
Mike Stump1eb44332009-09-09 15:08:12 +0000740
Reid Spencer5f016e22007-07-11 17:01:13 +0000741 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
742 // if the macro that guards it is defined, we know the #include has no effect.
Mike Stump1eb44332009-09-09 15:08:12 +0000743 if (const IdentifierInfo *ControllingMacro
Douglas Gregor8c5a7602009-04-25 23:30:02 +0000744 = FileInfo.getControllingMacro(ExternalLookup))
745 if (ControllingMacro->hasMacroDefinition()) {
746 ++NumMultiIncludeFileOptzn;
747 return false;
748 }
Mike Stump1eb44332009-09-09 15:08:12 +0000749
Reid Spencer5f016e22007-07-11 17:01:13 +0000750 // Increment the number of times this file has been included.
751 ++FileInfo.NumIncludes;
Mike Stump1eb44332009-09-09 15:08:12 +0000752
Reid Spencer5f016e22007-07-11 17:01:13 +0000753 return true;
754}
755
Ted Kremenekd1194fb2011-07-26 23:46:11 +0000756size_t HeaderSearch::getTotalMemory() const {
757 return SearchDirs.capacity()
Ted Kremenekeabea452011-07-27 18:41:18 +0000758 + llvm::capacity_in_bytes(FileInfo)
759 + llvm::capacity_in_bytes(HeaderMaps)
Ted Kremenekd1194fb2011-07-26 23:46:11 +0000760 + LookupFileCache.getAllocator().getTotalMemory()
761 + FrameworkMap.getAllocator().getTotalMemory();
762}
Douglas Gregor65e02fa2011-07-28 04:45:53 +0000763
764StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) {
765 return FrameworkNames.GetOrCreateValue(Framework).getKey();
766}
Douglas Gregora30cfe52011-11-11 19:10:28 +0000767
768bool HeaderSearch::hasModuleMap(StringRef FileName,
769 const DirectoryEntry *Root) {
770 llvm::SmallVector<const DirectoryEntry *, 2> FixUpDirectories;
771
772 StringRef DirName = FileName;
773 do {
774 // Get the parent directory name.
775 DirName = llvm::sys::path::parent_path(DirName);
776 if (DirName.empty())
777 return false;
778
779 // Determine whether this directory exists.
780 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
781 if (!Dir)
782 return false;
783
Douglas Gregorcf70d782011-11-12 00:05:07 +0000784 // Try to load the module map file in this directory.
Douglas Gregor26697972011-11-12 00:22:19 +0000785 switch (loadModuleMapFile(Dir)) {
786 case LMM_NewlyLoaded:
787 case LMM_AlreadyLoaded:
Douglas Gregorcf70d782011-11-12 00:05:07 +0000788 // Success. All of the directories we stepped through inherit this module
789 // map file.
Douglas Gregora30cfe52011-11-11 19:10:28 +0000790 for (unsigned I = 0, N = FixUpDirectories.size(); I != N; ++I)
791 DirectoryHasModuleMap[FixUpDirectories[I]] = true;
792
793 return true;
Douglas Gregor26697972011-11-12 00:22:19 +0000794
795 case LMM_NoDirectory:
796 case LMM_InvalidModuleMap:
797 break;
Douglas Gregora30cfe52011-11-11 19:10:28 +0000798 }
Douglas Gregora30cfe52011-11-11 19:10:28 +0000799
Douglas Gregorcf70d782011-11-12 00:05:07 +0000800 // If we hit the top of our search, we're done.
801 if (Dir == Root)
802 return false;
803
Douglas Gregora30cfe52011-11-11 19:10:28 +0000804 // Keep track of all of the directories we checked, so we can mark them as
805 // having module maps if we eventually do find a module map.
806 FixUpDirectories.push_back(Dir);
807 } while (true);
Douglas Gregora30cfe52011-11-11 19:10:28 +0000808}
809
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000810Module *HeaderSearch::findModuleForHeader(const FileEntry *File) {
Douglas Gregor51f564f2011-12-31 04:05:44 +0000811 if (Module *Mod = ModMap.findModuleForHeader(File))
812 return Mod;
Douglas Gregor65f3b5e2011-11-11 22:18:48 +0000813
Douglas Gregorc69c42e2011-11-17 22:44:56 +0000814 return 0;
Douglas Gregora30cfe52011-11-11 19:10:28 +0000815}
816
Douglas Gregordb1cde72011-11-16 00:09:06 +0000817bool HeaderSearch::loadModuleMapFile(const FileEntry *File) {
818 const DirectoryEntry *Dir = File->getDir();
819
820 llvm::DenseMap<const DirectoryEntry *, bool>::iterator KnownDir
821 = DirectoryHasModuleMap.find(Dir);
822 if (KnownDir != DirectoryHasModuleMap.end())
823 return !KnownDir->second;
824
825 bool Result = ModMap.parseModuleMapFile(File);
Douglas Gregor4813442c2011-12-07 21:25:07 +0000826 if (!Result && llvm::sys::path::filename(File->getName()) == "module.map") {
827 // If the file we loaded was a module.map, look for the corresponding
828 // module_private.map.
829 llvm::SmallString<128> PrivateFilename(Dir->getName());
830 llvm::sys::path::append(PrivateFilename, "module_private.map");
831 if (const FileEntry *PrivateFile = FileMgr.getFile(PrivateFilename))
832 Result = ModMap.parseModuleMapFile(PrivateFile);
833 }
834
835 DirectoryHasModuleMap[Dir] = !Result;
Douglas Gregordb1cde72011-11-16 00:09:06 +0000836 return Result;
837}
838
Douglas Gregore434ec72012-01-29 17:08:11 +0000839Module *HeaderSearch::loadFrameworkModule(StringRef Name,
840 const DirectoryEntry *Dir,
841 bool IsSystem) {
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000842 if (Module *Module = ModMap.findModule(Name))
Douglas Gregor2821c7f2011-11-17 01:41:17 +0000843 return Module;
844
845 // Try to load a module map file.
846 switch (loadModuleMapFile(Dir)) {
847 case LMM_InvalidModuleMap:
848 break;
849
850 case LMM_AlreadyLoaded:
851 case LMM_NoDirectory:
852 return 0;
853
854 case LMM_NewlyLoaded:
855 return ModMap.findModule(Name);
856 }
Douglas Gregora8c6fea2012-01-13 22:31:52 +0000857
858 // The top-level framework directory, from which we'll infer a framework
859 // module.
860 const DirectoryEntry *TopFrameworkDir = Dir;
Douglas Gregor2821c7f2011-11-17 01:41:17 +0000861
Douglas Gregora8c6fea2012-01-13 22:31:52 +0000862 // The path from the module we're actually looking for back to the top-level
863 // framework name.
864 llvm::SmallVector<StringRef, 2> SubmodulePath;
865 SubmodulePath.push_back(Name);
866
867 // Walk the directory structure to find any enclosing frameworks.
868 StringRef DirName = Dir->getName();
869 do {
870 // Get the parent directory name.
871 DirName = llvm::sys::path::parent_path(DirName);
872 if (DirName.empty())
873 break;
874
875 // Determine whether this directory exists.
876 Dir = FileMgr.getDirectory(DirName);
877 if (!Dir)
878 break;
879
880 // If this is a framework directory, then we're a subframework of this
881 // framework.
882 if (llvm::sys::path::extension(DirName) == ".framework") {
883 SubmodulePath.push_back(llvm::sys::path::stem(DirName));
884 TopFrameworkDir = Dir;
885 }
886 } while (true);
887
888 // Try to infer a module map from the top-level framework directory.
889 Module *Result = ModMap.inferFrameworkModule(SubmodulePath.back(),
Douglas Gregora1f1fad2012-01-27 19:52:33 +0000890 TopFrameworkDir,
891 IsSystem,
Douglas Gregora8c6fea2012-01-13 22:31:52 +0000892 /*Parent=*/0);
893
894 // Follow the submodule path to find the requested (sub)framework module
895 // within the top-level framework module.
896 SubmodulePath.pop_back();
897 while (!SubmodulePath.empty() && Result) {
898 Result = ModMap.lookupModuleQualified(SubmodulePath.back(), Result);
899 SubmodulePath.pop_back();
900 }
901 return Result;
Douglas Gregor2821c7f2011-11-17 01:41:17 +0000902}
903
Douglas Gregordb1cde72011-11-16 00:09:06 +0000904
Douglas Gregor26697972011-11-12 00:22:19 +0000905HeaderSearch::LoadModuleMapResult
906HeaderSearch::loadModuleMapFile(StringRef DirName) {
Douglas Gregorcf70d782011-11-12 00:05:07 +0000907 if (const DirectoryEntry *Dir = FileMgr.getDirectory(DirName))
908 return loadModuleMapFile(Dir);
909
Douglas Gregor26697972011-11-12 00:22:19 +0000910 return LMM_NoDirectory;
Douglas Gregorcf70d782011-11-12 00:05:07 +0000911}
912
Douglas Gregor26697972011-11-12 00:22:19 +0000913HeaderSearch::LoadModuleMapResult
914HeaderSearch::loadModuleMapFile(const DirectoryEntry *Dir) {
Douglas Gregorcf70d782011-11-12 00:05:07 +0000915 llvm::DenseMap<const DirectoryEntry *, bool>::iterator KnownDir
916 = DirectoryHasModuleMap.find(Dir);
917 if (KnownDir != DirectoryHasModuleMap.end())
Douglas Gregor26697972011-11-12 00:22:19 +0000918 return KnownDir->second? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
Douglas Gregorcf70d782011-11-12 00:05:07 +0000919
920 llvm::SmallString<128> ModuleMapFileName;
921 ModuleMapFileName += Dir->getName();
Douglas Gregor587986e2011-12-07 02:23:45 +0000922 unsigned ModuleMapDirNameLen = ModuleMapFileName.size();
Douglas Gregorcf70d782011-11-12 00:05:07 +0000923 llvm::sys::path::append(ModuleMapFileName, "module.map");
924 if (const FileEntry *ModuleMapFile = FileMgr.getFile(ModuleMapFileName)) {
925 // We have found a module map file. Try to parse it.
Douglas Gregor587986e2011-12-07 02:23:45 +0000926 if (ModMap.parseModuleMapFile(ModuleMapFile)) {
927 // No suitable module map.
928 DirectoryHasModuleMap[Dir] = false;
929 return LMM_InvalidModuleMap;
Douglas Gregorcf70d782011-11-12 00:05:07 +0000930 }
Douglas Gregor587986e2011-12-07 02:23:45 +0000931
932 // This directory has a module map.
933 DirectoryHasModuleMap[Dir] = true;
934
935 // Check whether there is a private module map that we need to load as well.
936 ModuleMapFileName.erase(ModuleMapFileName.begin() + ModuleMapDirNameLen,
937 ModuleMapFileName.end());
938 llvm::sys::path::append(ModuleMapFileName, "module_private.map");
939 if (const FileEntry *PrivateModuleMapFile
940 = FileMgr.getFile(ModuleMapFileName)) {
941 if (ModMap.parseModuleMapFile(PrivateModuleMapFile)) {
942 // No suitable module map.
943 DirectoryHasModuleMap[Dir] = false;
944 return LMM_InvalidModuleMap;
945 }
946 }
947
948 return LMM_NewlyLoaded;
Douglas Gregorcf70d782011-11-12 00:05:07 +0000949 }
950
951 // No suitable module map.
952 DirectoryHasModuleMap[Dir] = false;
Douglas Gregor26697972011-11-12 00:22:19 +0000953 return LMM_InvalidModuleMap;
Douglas Gregorcf70d782011-11-12 00:05:07 +0000954}
Douglas Gregora30cfe52011-11-11 19:10:28 +0000955
Douglas Gregorc5b2e582012-01-29 18:15:03 +0000956void HeaderSearch::collectAllModules(llvm::SmallVectorImpl<Module *> &Modules) {
957 Modules.clear();
958
959 // Load module maps for each of the header search directories.
960 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
961 if (SearchDirs[Idx].isFramework()) {
962 llvm::error_code EC;
963 llvm::SmallString<128> DirNative;
964 llvm::sys::path::native(SearchDirs[Idx].getFrameworkDir()->getName(),
965 DirNative);
966
967 // Search each of the ".framework" directories to load them as modules.
968 bool IsSystem = SearchDirs[Idx].getDirCharacteristic() != SrcMgr::C_User;
969 for (llvm::sys::fs::directory_iterator Dir(DirNative.str(), EC), DirEnd;
970 Dir != DirEnd && !EC; Dir.increment(EC)) {
971 if (llvm::sys::path::extension(Dir->path()) != ".framework")
972 continue;
973
974 const DirectoryEntry *FrameworkDir = FileMgr.getDirectory(Dir->path());
975 if (!FrameworkDir)
976 continue;
977
978 // Load this framework module.
979 loadFrameworkModule(llvm::sys::path::stem(Dir->path()), FrameworkDir,
980 IsSystem);
981 }
982 continue;
983 }
984
985 // FIXME: Deal with header maps.
986 if (SearchDirs[Idx].isHeaderMap())
987 continue;
988
989 // Try to load a module map file for the search directory.
990 loadModuleMapFile(SearchDirs[Idx].getDir());
991
992 // Try to load module map files for immediate subdirectories of this search
993 // directory.
994 llvm::error_code EC;
995 llvm::SmallString<128> DirNative;
996 llvm::sys::path::native(SearchDirs[Idx].getDir()->getName(), DirNative);
997 for (llvm::sys::fs::directory_iterator Dir(DirNative.str(), EC), DirEnd;
998 Dir != DirEnd && !EC; Dir.increment(EC)) {
999 loadModuleMapFile(Dir->path());
1000 }
1001 }
1002
1003 // Populate the list of modules.
1004 for (ModuleMap::module_iterator M = ModMap.module_begin(),
1005 MEnd = ModMap.module_end();
1006 M != MEnd; ++M) {
1007 Modules.push_back(M->getValue());
1008 }
1009}
1010