blob: beda5893acc49863a6881e69fc51d4a4f334458e [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- HeaderSearch.cpp - Resolve Header File Locations ---===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the DirectoryLookup and HeaderSearch interfaces.
11//
12//===----------------------------------------------------------------------===//
13
Chris Lattner4b009652007-07-25 00:24:17 +000014#include "clang/Lex/HeaderSearch.h"
Chris Lattnerc2043bf2007-12-17 06:36:45 +000015#include "clang/Lex/HeaderMap.h"
Chris Lattner2fd1c652007-10-07 08:58:51 +000016#include "clang/Basic/FileManager.h"
17#include "clang/Basic/IdentifierTable.h"
Chris Lattner4b009652007-07-25 00:24:17 +000018#include "llvm/System/Path.h"
19#include "llvm/ADT/SmallString.h"
20using namespace clang;
21
22HeaderSearch::HeaderSearch(FileManager &FM) : FileMgr(FM), FrameworkMap(64) {
23 SystemDirIdx = 0;
24 NoCurDirSearch = false;
25
26 NumIncluded = 0;
27 NumMultiIncludeFileOptzn = 0;
28 NumFrameworkLookups = NumSubFrameworkLookups = 0;
29}
30
Chris Lattnerc2043bf2007-12-17 06:36:45 +000031HeaderSearch::~HeaderSearch() {
32 // Delete headermaps.
33 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
34 delete HeaderMaps[i].second;
35}
36
Chris Lattner4b009652007-07-25 00:24:17 +000037void HeaderSearch::PrintStats() {
38 fprintf(stderr, "\n*** HeaderSearch Stats:\n");
39 fprintf(stderr, "%d files tracked.\n", (int)FileInfo.size());
40 unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0;
41 for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) {
42 NumOnceOnlyFiles += FileInfo[i].isImport;
43 if (MaxNumIncludes < FileInfo[i].NumIncludes)
44 MaxNumIncludes = FileInfo[i].NumIncludes;
45 NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1;
46 }
47 fprintf(stderr, " %d #import/#pragma once files.\n", NumOnceOnlyFiles);
48 fprintf(stderr, " %d included exactly once.\n", NumSingleIncludedFiles);
49 fprintf(stderr, " %d max times a file is included.\n", MaxNumIncludes);
50
51 fprintf(stderr, " %d #include/#include_next/#import.\n", NumIncluded);
52 fprintf(stderr, " %d #includes skipped due to"
53 " the multi-include optimization.\n", NumMultiIncludeFileOptzn);
54
55 fprintf(stderr, "%d framework lookups.\n", NumFrameworkLookups);
56 fprintf(stderr, "%d subframework lookups.\n", NumSubFrameworkLookups);
57}
58
Chris Lattnerc2043bf2007-12-17 06:36:45 +000059/// CreateHeaderMap - This method returns a HeaderMap for the specified
60/// FileEntry, uniquing them through the the 'HeaderMaps' datastructure.
Chris Lattner9af36d32007-12-17 18:34:53 +000061const HeaderMap *HeaderSearch::CreateHeaderMap(const FileEntry *FE) {
Chris Lattnerc2043bf2007-12-17 06:36:45 +000062 // We expect the number of headermaps to be small, and almost always empty.
Chris Lattnerb7426782007-12-17 07:52:39 +000063 // If it ever grows, use of a linear search should be re-evaluated.
Chris Lattnerc2043bf2007-12-17 06:36:45 +000064 if (!HeaderMaps.empty()) {
65 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
Chris Lattnerb7426782007-12-17 07:52:39 +000066 // Pointer equality comparison of FileEntries works because they are
67 // already uniqued by inode.
Chris Lattnerc2043bf2007-12-17 06:36:45 +000068 if (HeaderMaps[i].first == FE)
69 return HeaderMaps[i].second;
70 }
71
Chris Lattner9af36d32007-12-17 18:34:53 +000072 if (const HeaderMap *HM = HeaderMap::Create(FE)) {
Chris Lattnerc2043bf2007-12-17 06:36:45 +000073 HeaderMaps.push_back(std::make_pair(FE, HM));
74 return HM;
75 }
76
77 return 0;
78}
79
Chris Lattnerb7426782007-12-17 07:52:39 +000080//===----------------------------------------------------------------------===//
81// File lookup within a DirectoryLookup scope
82//===----------------------------------------------------------------------===//
83
Chris Lattner1df68f92007-12-17 17:57:27 +000084/// getName - Return the directory or filename corresponding to this lookup
85/// object.
86const char *DirectoryLookup::getName() const {
87 if (isNormalDir())
88 return getDir()->getName();
89 if (isFramework())
90 return getFrameworkDir()->getName();
91 assert(isHeaderMap() && "Unknown DirectoryLookup");
92 return getHeaderMap()->getFileName();
93}
94
95
Chris Lattnerb7426782007-12-17 07:52:39 +000096/// LookupFile - Lookup the specified file in this search path, returning it
97/// if it exists or returning null if not.
98const FileEntry *DirectoryLookup::LookupFile(const char *FilenameStart,
99 const char *FilenameEnd,
Chris Lattner7d0ad4a2007-12-17 08:13:48 +0000100 HeaderSearch &HS) const {
Chris Lattnerb7426782007-12-17 07:52:39 +0000101 llvm::SmallString<1024> TmpDir;
Chris Lattner7d0ad4a2007-12-17 08:13:48 +0000102 if (isNormalDir()) {
103 // Concatenate the requested file onto the directory.
104 // FIXME: Portability. Filename concatenation should be in sys::Path.
105 TmpDir += getDir()->getName();
106 TmpDir.push_back('/');
107 TmpDir.append(FilenameStart, FilenameEnd);
108 return HS.getFileMgr().getFile(TmpDir.begin(), TmpDir.end());
109 }
Chris Lattnerb7426782007-12-17 07:52:39 +0000110
Chris Lattner7d0ad4a2007-12-17 08:13:48 +0000111 if (isFramework())
112 return DoFrameworkLookup(FilenameStart, FilenameEnd, HS);
113
Chris Lattner61349712007-12-17 08:17:39 +0000114 assert(isHeaderMap() && "Unknown directory lookup");
115 return getHeaderMap()->LookupFile(FilenameStart, FilenameEnd,HS.getFileMgr());
Chris Lattnerb7426782007-12-17 07:52:39 +0000116}
117
118
Chris Lattner7d0ad4a2007-12-17 08:13:48 +0000119/// DoFrameworkLookup - Do a lookup of the specified file in the current
120/// DirectoryLookup, which is a framework directory.
121const FileEntry *DirectoryLookup::DoFrameworkLookup(const char *FilenameStart,
122 const char *FilenameEnd,
123 HeaderSearch &HS) const {
124 FileManager &FileMgr = HS.getFileMgr();
125
Chris Lattner4b009652007-07-25 00:24:17 +0000126 // Framework names must have a '/' in the filename.
127 const char *SlashPos = std::find(FilenameStart, FilenameEnd, '/');
128 if (SlashPos == FilenameEnd) return 0;
129
Chris Lattner7d0ad4a2007-12-17 08:13:48 +0000130 // Find out if this is the home for the specified framework, by checking
131 // HeaderSearch. Possible answer are yes/no and unknown.
132 const DirectoryEntry *&FrameworkDirCache =
133 HS.LookupFrameworkCache(FilenameStart, SlashPos);
Chris Lattner4b009652007-07-25 00:24:17 +0000134
Chris Lattner7d0ad4a2007-12-17 08:13:48 +0000135 // If it is known and in some other directory, fail.
136 if (FrameworkDirCache && FrameworkDirCache != getFrameworkDir())
Chris Lattner4b009652007-07-25 00:24:17 +0000137 return 0;
Chris Lattner7d0ad4a2007-12-17 08:13:48 +0000138
139 // Otherwise, construct the path to this framework dir.
140
Chris Lattner4b009652007-07-25 00:24:17 +0000141 // FrameworkName = "/System/Library/Frameworks/"
142 llvm::SmallString<1024> FrameworkName;
Chris Lattner7d0ad4a2007-12-17 08:13:48 +0000143 FrameworkName += getFrameworkDir()->getName();
Chris Lattner4b009652007-07-25 00:24:17 +0000144 if (FrameworkName.empty() || FrameworkName.back() != '/')
145 FrameworkName.push_back('/');
146
147 // FrameworkName = "/System/Library/Frameworks/Cocoa"
148 FrameworkName.append(FilenameStart, SlashPos);
149
150 // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/"
151 FrameworkName += ".framework/";
Chris Lattner7d0ad4a2007-12-17 08:13:48 +0000152
153 // If the cache entry is still unresolved, query to see if the cache entry is
154 // still unresolved. If so, check its existence now.
155 if (FrameworkDirCache == 0) {
156 HS.IncrementFrameworkLookupCount();
Chris Lattner4b009652007-07-25 00:24:17 +0000157
158 // If the framework dir doesn't exist, we fail.
Chris Lattner7d0ad4a2007-12-17 08:13:48 +0000159 // FIXME: It's probably more efficient to query this with FileMgr.getDir.
Chris Lattner4b009652007-07-25 00:24:17 +0000160 if (!llvm::sys::Path(std::string(FrameworkName.begin(),
161 FrameworkName.end())).exists())
162 return 0;
163
164 // Otherwise, if it does, remember that this is the right direntry for this
165 // framework.
Chris Lattner7d0ad4a2007-12-17 08:13:48 +0000166 FrameworkDirCache = getFrameworkDir();
Chris Lattner4b009652007-07-25 00:24:17 +0000167 }
168
169 // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"
170 unsigned OrigSize = FrameworkName.size();
171
172 FrameworkName += "Headers/";
173 FrameworkName.append(SlashPos+1, FilenameEnd);
174 if (const FileEntry *FE = FileMgr.getFile(FrameworkName.begin(),
175 FrameworkName.end())) {
176 return FE;
177 }
178
179 // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"
180 const char *Private = "Private";
181 FrameworkName.insert(FrameworkName.begin()+OrigSize, Private,
182 Private+strlen(Private));
183 return FileMgr.getFile(FrameworkName.begin(), FrameworkName.end());
184}
185
Chris Lattnerb7426782007-12-17 07:52:39 +0000186
Chris Lattner7d0ad4a2007-12-17 08:13:48 +0000187//===----------------------------------------------------------------------===//
188// Header File Location.
189//===----------------------------------------------------------------------===//
190
191
Chris Lattner4b009652007-07-25 00:24:17 +0000192/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
193/// return null on failure. isAngled indicates whether the file reference is
194/// for system #include's or not (i.e. using <> instead of ""). CurFileEnt, if
195/// non-null, indicates where the #including file is, in case a relative search
196/// is needed.
197const FileEntry *HeaderSearch::LookupFile(const char *FilenameStart,
198 const char *FilenameEnd,
199 bool isAngled,
200 const DirectoryLookup *FromDir,
201 const DirectoryLookup *&CurDir,
202 const FileEntry *CurFileEnt) {
203 // If 'Filename' is absolute, check to see if it exists and no searching.
204 // FIXME: Portability. This should be a sys::Path interface, this doesn't
205 // handle things like C:\foo.txt right, nor win32 \\network\device\blah.
206 if (FilenameStart[0] == '/') {
207 CurDir = 0;
208
209 // If this was an #include_next "/absolute/file", fail.
210 if (FromDir) return 0;
211
212 // Otherwise, just return the file.
213 return FileMgr.getFile(FilenameStart, FilenameEnd);
214 }
215
Chris Lattner4b009652007-07-25 00:24:17 +0000216 // Step #0, unless disabled, check to see if the file is in the #includer's
Chris Lattnerb7426782007-12-17 07:52:39 +0000217 // directory. This has to be based on CurFileEnt, not CurDir, because
218 // CurFileEnt could be a #include of a subdirectory (#include "foo/bar.h") and
219 // a subsequent include of "baz.h" should resolve to "whatever/foo/baz.h".
220 // This search is not done for <> headers.
Chris Lattner4b009652007-07-25 00:24:17 +0000221 if (CurFileEnt && !isAngled && !NoCurDirSearch) {
Chris Lattnerb7426782007-12-17 07:52:39 +0000222 llvm::SmallString<1024> TmpDir;
Chris Lattner4b009652007-07-25 00:24:17 +0000223 // Concatenate the requested file onto the directory.
224 // FIXME: Portability. Filename concatenation should be in sys::Path.
225 TmpDir += CurFileEnt->getDir()->getName();
226 TmpDir.push_back('/');
227 TmpDir.append(FilenameStart, FilenameEnd);
228 if (const FileEntry *FE = FileMgr.getFile(TmpDir.begin(), TmpDir.end())) {
229 // Leave CurDir unset.
Chris Lattner4b009652007-07-25 00:24:17 +0000230 // This file is a system header or C++ unfriendly if the old file is.
231 getFileInfo(FE).DirInfo = getFileInfo(CurFileEnt).DirInfo;
232 return FE;
233 }
Chris Lattner4b009652007-07-25 00:24:17 +0000234 }
235
236 CurDir = 0;
237
238 // If this is a system #include, ignore the user #include locs.
239 unsigned i = isAngled ? SystemDirIdx : 0;
240
241 // If this is a #include_next request, start searching after the directory the
242 // file was found in.
243 if (FromDir)
244 i = FromDir-&SearchDirs[0];
245
246 // Cache all of the lookups performed by this method. Many headers are
247 // multiply included, and the "pragma once" optimization prevents them from
248 // being relex/pp'd, but they would still have to search through a
249 // (potentially huge) series of SearchDirs to find it.
250 std::pair<unsigned, unsigned> &CacheLookup =
251 LookupFileCache.GetOrCreateValue(FilenameStart, FilenameEnd).getValue();
252
253 // If the entry has been previously looked up, the first value will be
254 // non-zero. If the value is equal to i (the start point of our search), then
255 // this is a matching hit.
256 if (CacheLookup.first == i+1) {
257 // Skip querying potentially lots of directories for this lookup.
258 i = CacheLookup.second;
259 } else {
260 // Otherwise, this is the first query, or the previous query didn't match
261 // our search start. We will fill in our found location below, so prime the
262 // start point value.
263 CacheLookup.first = i+1;
264 }
Chris Lattnerb7426782007-12-17 07:52:39 +0000265
Chris Lattner4b009652007-07-25 00:24:17 +0000266 // Check each directory in sequence to see if it contains this file.
267 for (; i != SearchDirs.size(); ++i) {
Chris Lattner7d0ad4a2007-12-17 08:13:48 +0000268 const FileEntry *FE =
269 SearchDirs[i].LookupFile(FilenameStart, FilenameEnd, *this);
270 if (!FE) continue;
Chris Lattner4b009652007-07-25 00:24:17 +0000271
Chris Lattner7d0ad4a2007-12-17 08:13:48 +0000272 CurDir = &SearchDirs[i];
273
274 // This file is a system header or C++ unfriendly if the dir is.
275 getFileInfo(FE).DirInfo = CurDir->getDirCharacteristic();
276
277 // Remember this location for the next lookup we do.
278 CacheLookup.second = i;
279 return FE;
Chris Lattner4b009652007-07-25 00:24:17 +0000280 }
281
282 // Otherwise, didn't find it. Remember we didn't find this.
283 CacheLookup.second = SearchDirs.size();
284 return 0;
285}
286
287/// LookupSubframeworkHeader - Look up a subframework for the specified
288/// #include file. For example, if #include'ing <HIToolbox/HIToolbox.h> from
289/// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
290/// is a subframework within Carbon.framework. If so, return the FileEntry
291/// for the designated file, otherwise return null.
292const FileEntry *HeaderSearch::
293LookupSubframeworkHeader(const char *FilenameStart,
294 const char *FilenameEnd,
295 const FileEntry *ContextFileEnt) {
296 // Framework names must have a '/' in the filename. Find it.
297 const char *SlashPos = std::find(FilenameStart, FilenameEnd, '/');
298 if (SlashPos == FilenameEnd) return 0;
299
300 // Look up the base framework name of the ContextFileEnt.
301 const char *ContextName = ContextFileEnt->getName();
302
303 // If the context info wasn't a framework, couldn't be a subframework.
304 const char *FrameworkPos = strstr(ContextName, ".framework/");
305 if (FrameworkPos == 0)
306 return 0;
307
308 llvm::SmallString<1024> FrameworkName(ContextName,
309 FrameworkPos+strlen(".framework/"));
310
311 // Append Frameworks/HIToolbox.framework/
312 FrameworkName += "Frameworks/";
313 FrameworkName.append(FilenameStart, SlashPos);
314 FrameworkName += ".framework/";
315
316 llvm::StringMapEntry<const DirectoryEntry *> &CacheLookup =
317 FrameworkMap.GetOrCreateValue(FilenameStart, SlashPos);
318
319 // Some other location?
320 if (CacheLookup.getValue() &&
321 CacheLookup.getKeyLength() == FrameworkName.size() &&
322 memcmp(CacheLookup.getKeyData(), &FrameworkName[0],
323 CacheLookup.getKeyLength()) != 0)
324 return 0;
325
326 // Cache subframework.
327 if (CacheLookup.getValue() == 0) {
328 ++NumSubFrameworkLookups;
329
330 // If the framework dir doesn't exist, we fail.
331 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName.begin(),
332 FrameworkName.end());
333 if (Dir == 0) return 0;
334
335 // Otherwise, if it does, remember that this is the right direntry for this
336 // framework.
337 CacheLookup.setValue(Dir);
338 }
339
340 const FileEntry *FE = 0;
341
342 // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
343 llvm::SmallString<1024> HeadersFilename(FrameworkName);
344 HeadersFilename += "Headers/";
345 HeadersFilename.append(SlashPos+1, FilenameEnd);
346 if (!(FE = FileMgr.getFile(HeadersFilename.begin(),
347 HeadersFilename.end()))) {
348
349 // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
350 HeadersFilename = FrameworkName;
351 HeadersFilename += "PrivateHeaders/";
352 HeadersFilename.append(SlashPos+1, FilenameEnd);
353 if (!(FE = FileMgr.getFile(HeadersFilename.begin(), HeadersFilename.end())))
354 return 0;
355 }
356
357 // This file is a system header or C++ unfriendly if the old file is.
358 getFileInfo(FE).DirInfo = getFileInfo(ContextFileEnt).DirInfo;
359 return FE;
360}
361
362//===----------------------------------------------------------------------===//
363// File Info Management.
364//===----------------------------------------------------------------------===//
365
366
367/// getFileInfo - Return the PerFileInfo structure for the specified
368/// FileEntry.
369HeaderSearch::PerFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) {
370 if (FE->getUID() >= FileInfo.size())
371 FileInfo.resize(FE->getUID()+1);
372 return FileInfo[FE->getUID()];
373}
374
375/// ShouldEnterIncludeFile - Mark the specified file as a target of of a
376/// #include, #include_next, or #import directive. Return false if #including
377/// the file will have no effect or true if we should include it.
378bool HeaderSearch::ShouldEnterIncludeFile(const FileEntry *File, bool isImport){
379 ++NumIncluded; // Count # of attempted #includes.
380
381 // Get information about this file.
382 PerFileInfo &FileInfo = getFileInfo(File);
383
384 // If this is a #import directive, check that we have not already imported
385 // this header.
386 if (isImport) {
387 // If this has already been imported, don't import it again.
388 FileInfo.isImport = true;
389
390 // Has this already been #import'ed or #include'd?
391 if (FileInfo.NumIncludes) return false;
392 } else {
393 // Otherwise, if this is a #include of a file that was previously #import'd
394 // or if this is the second #include of a #pragma once file, ignore it.
395 if (FileInfo.isImport)
396 return false;
397 }
398
399 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
400 // if the macro that guards it is defined, we know the #include has no effect.
Chris Lattner4826cbc2007-10-07 07:57:27 +0000401 if (FileInfo.ControllingMacro &&
402 FileInfo.ControllingMacro->hasMacroDefinition()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000403 ++NumMultiIncludeFileOptzn;
404 return false;
405 }
406
407 // Increment the number of times this file has been included.
408 ++FileInfo.NumIncludes;
409
410 return true;
411}
412
413