blob: 899c9d87a93d49fd53c777a7c9a049a720fad8e5 [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"
Chris Lattnerc7229c32007-10-07 08:58:51 +000016#include "clang/Basic/FileManager.h"
17#include "clang/Basic/IdentifierTable.h"
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattner822da612007-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
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattner822da612007-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 Lattner1bfd4a62007-12-17 18:34:53 +000061const HeaderMap *HeaderSearch::CreateHeaderMap(const FileEntry *FE) {
Chris Lattner822da612007-12-17 06:36:45 +000062 // We expect the number of headermaps to be small, and almost always empty.
Chris Lattnerdf772332007-12-17 07:52:39 +000063 // If it ever grows, use of a linear search should be re-evaluated.
Chris Lattner822da612007-12-17 06:36:45 +000064 if (!HeaderMaps.empty()) {
65 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
Chris Lattnerdf772332007-12-17 07:52:39 +000066 // Pointer equality comparison of FileEntries works because they are
67 // already uniqued by inode.
Chris Lattner822da612007-12-17 06:36:45 +000068 if (HeaderMaps[i].first == FE)
69 return HeaderMaps[i].second;
70 }
71
Chris Lattner1bfd4a62007-12-17 18:34:53 +000072 if (const HeaderMap *HM = HeaderMap::Create(FE)) {
Chris Lattner822da612007-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 Lattnerdf772332007-12-17 07:52:39 +000080//===----------------------------------------------------------------------===//
81// File lookup within a DirectoryLookup scope
82//===----------------------------------------------------------------------===//
83
Chris Lattner3af66a92007-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 Lattnerdf772332007-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 Lattnerafded5b2007-12-17 08:13:48 +0000100 HeaderSearch &HS) const {
Chris Lattnerdf772332007-12-17 07:52:39 +0000101 llvm::SmallString<1024> TmpDir;
Chris Lattnerafded5b2007-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 Lattnerdf772332007-12-17 07:52:39 +0000110
Chris Lattnerafded5b2007-12-17 08:13:48 +0000111 if (isFramework())
112 return DoFrameworkLookup(FilenameStart, FilenameEnd, HS);
113
Chris Lattnerb09e71f2007-12-17 08:17:39 +0000114 assert(isHeaderMap() && "Unknown directory lookup");
115 return getHeaderMap()->LookupFile(FilenameStart, FilenameEnd,HS.getFileMgr());
Chris Lattnerdf772332007-12-17 07:52:39 +0000116}
117
118
Chris Lattnerafded5b2007-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
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattnerafded5b2007-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);
Reid Spencer5f016e22007-07-11 17:01:13 +0000134
Chris Lattnerafded5b2007-12-17 08:13:48 +0000135 // If it is known and in some other directory, fail.
136 if (FrameworkDirCache && FrameworkDirCache != getFrameworkDir())
Reid Spencer5f016e22007-07-11 17:01:13 +0000137 return 0;
Chris Lattnerafded5b2007-12-17 08:13:48 +0000138
139 // Otherwise, construct the path to this framework dir.
140
Reid Spencer5f016e22007-07-11 17:01:13 +0000141 // FrameworkName = "/System/Library/Frameworks/"
142 llvm::SmallString<1024> FrameworkName;
Chris Lattnerafded5b2007-12-17 08:13:48 +0000143 FrameworkName += getFrameworkDir()->getName();
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattnerafded5b2007-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();
Reid Spencer5f016e22007-07-11 17:01:13 +0000157
158 // If the framework dir doesn't exist, we fail.
Chris Lattnerafded5b2007-12-17 08:13:48 +0000159 // FIXME: It's probably more efficient to query this with FileMgr.getDir.
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattnerafded5b2007-12-17 08:13:48 +0000166 FrameworkDirCache = getFrameworkDir();
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattnerdf772332007-12-17 07:52:39 +0000186
Chris Lattnerafded5b2007-12-17 08:13:48 +0000187//===----------------------------------------------------------------------===//
188// Header File Location.
189//===----------------------------------------------------------------------===//
190
191
Reid Spencer5f016e22007-07-11 17:01:13 +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
Reid Spencer5f016e22007-07-11 17:01:13 +0000216 // Step #0, unless disabled, check to see if the file is in the #includer's
Chris Lattnerdf772332007-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.
Reid Spencer5f016e22007-07-11 17:01:13 +0000221 if (CurFileEnt && !isAngled && !NoCurDirSearch) {
Chris Lattnerdf772332007-12-17 07:52:39 +0000222 llvm::SmallString<1024> TmpDir;
Reid Spencer5f016e22007-07-11 17:01:13 +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.
Reid Spencer5f016e22007-07-11 17:01:13 +0000230 // This file is a system header or C++ unfriendly if the old file is.
Ted Kremenekca63fa02008-02-24 03:55:14 +0000231
232 // Note: Don't use:
233 //
234 // getFileInfo(FE).DirInfo = getFileInfo(CurFileEnt).DirInfo;
235 //
236 // MSVC, behind the scenes, does this:
237 //
238 // PerFileInfo &pf1 = getFileInfo(CurFileEnt);
239 // PerFileInfo &pf2 = getFileInfo(FE);
240 // pf2.DirInfo = pf1.DirInfo
241 //
242 // The problem is that if there's a resize() of the FileInfo vector during
243 // the getFileInfo(FE) call, pf1 will point to invalid data. To fix
244 // this problem, make the assignment through a temporary.
245 unsigned int tmp = getFileInfo(CurFileEnt).DirInfo;
246 getFileInfo(FE).DirInfo = tmp;
Reid Spencer5f016e22007-07-11 17:01:13 +0000247 return FE;
248 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000249 }
250
251 CurDir = 0;
252
253 // If this is a system #include, ignore the user #include locs.
254 unsigned i = isAngled ? SystemDirIdx : 0;
255
256 // If this is a #include_next request, start searching after the directory the
257 // file was found in.
258 if (FromDir)
259 i = FromDir-&SearchDirs[0];
260
Chris Lattner9960ae82007-07-22 07:28:00 +0000261 // Cache all of the lookups performed by this method. Many headers are
262 // multiply included, and the "pragma once" optimization prevents them from
263 // being relex/pp'd, but they would still have to search through a
264 // (potentially huge) series of SearchDirs to find it.
265 std::pair<unsigned, unsigned> &CacheLookup =
266 LookupFileCache.GetOrCreateValue(FilenameStart, FilenameEnd).getValue();
267
268 // If the entry has been previously looked up, the first value will be
269 // non-zero. If the value is equal to i (the start point of our search), then
270 // this is a matching hit.
271 if (CacheLookup.first == i+1) {
272 // Skip querying potentially lots of directories for this lookup.
273 i = CacheLookup.second;
274 } else {
275 // Otherwise, this is the first query, or the previous query didn't match
276 // our search start. We will fill in our found location below, so prime the
277 // start point value.
278 CacheLookup.first = i+1;
279 }
Chris Lattnerdf772332007-12-17 07:52:39 +0000280
Reid Spencer5f016e22007-07-11 17:01:13 +0000281 // Check each directory in sequence to see if it contains this file.
282 for (; i != SearchDirs.size(); ++i) {
Chris Lattnerafded5b2007-12-17 08:13:48 +0000283 const FileEntry *FE =
284 SearchDirs[i].LookupFile(FilenameStart, FilenameEnd, *this);
285 if (!FE) continue;
Reid Spencer5f016e22007-07-11 17:01:13 +0000286
Chris Lattnerafded5b2007-12-17 08:13:48 +0000287 CurDir = &SearchDirs[i];
288
289 // This file is a system header or C++ unfriendly if the dir is.
290 getFileInfo(FE).DirInfo = CurDir->getDirCharacteristic();
291
292 // Remember this location for the next lookup we do.
293 CacheLookup.second = i;
294 return FE;
Reid Spencer5f016e22007-07-11 17:01:13 +0000295 }
296
Chris Lattner9960ae82007-07-22 07:28:00 +0000297 // Otherwise, didn't find it. Remember we didn't find this.
298 CacheLookup.second = SearchDirs.size();
Reid Spencer5f016e22007-07-11 17:01:13 +0000299 return 0;
300}
301
302/// LookupSubframeworkHeader - Look up a subframework for the specified
303/// #include file. For example, if #include'ing <HIToolbox/HIToolbox.h> from
304/// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
305/// is a subframework within Carbon.framework. If so, return the FileEntry
306/// for the designated file, otherwise return null.
307const FileEntry *HeaderSearch::
308LookupSubframeworkHeader(const char *FilenameStart,
309 const char *FilenameEnd,
310 const FileEntry *ContextFileEnt) {
Chris Lattner9415a0c2008-02-01 05:34:02 +0000311 assert(ContextFileEnt && "No context file?");
312
Reid Spencer5f016e22007-07-11 17:01:13 +0000313 // Framework names must have a '/' in the filename. Find it.
314 const char *SlashPos = std::find(FilenameStart, FilenameEnd, '/');
315 if (SlashPos == FilenameEnd) return 0;
316
317 // Look up the base framework name of the ContextFileEnt.
318 const char *ContextName = ContextFileEnt->getName();
319
320 // If the context info wasn't a framework, couldn't be a subframework.
321 const char *FrameworkPos = strstr(ContextName, ".framework/");
322 if (FrameworkPos == 0)
323 return 0;
324
325 llvm::SmallString<1024> FrameworkName(ContextName,
326 FrameworkPos+strlen(".framework/"));
327
328 // Append Frameworks/HIToolbox.framework/
329 FrameworkName += "Frameworks/";
330 FrameworkName.append(FilenameStart, SlashPos);
331 FrameworkName += ".framework/";
332
333 llvm::StringMapEntry<const DirectoryEntry *> &CacheLookup =
334 FrameworkMap.GetOrCreateValue(FilenameStart, SlashPos);
335
336 // Some other location?
337 if (CacheLookup.getValue() &&
338 CacheLookup.getKeyLength() == FrameworkName.size() &&
339 memcmp(CacheLookup.getKeyData(), &FrameworkName[0],
340 CacheLookup.getKeyLength()) != 0)
341 return 0;
342
343 // Cache subframework.
344 if (CacheLookup.getValue() == 0) {
345 ++NumSubFrameworkLookups;
346
347 // If the framework dir doesn't exist, we fail.
348 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName.begin(),
349 FrameworkName.end());
350 if (Dir == 0) return 0;
351
352 // Otherwise, if it does, remember that this is the right direntry for this
353 // framework.
354 CacheLookup.setValue(Dir);
355 }
356
357 const FileEntry *FE = 0;
358
359 // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
360 llvm::SmallString<1024> HeadersFilename(FrameworkName);
361 HeadersFilename += "Headers/";
362 HeadersFilename.append(SlashPos+1, FilenameEnd);
363 if (!(FE = FileMgr.getFile(HeadersFilename.begin(),
364 HeadersFilename.end()))) {
365
366 // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
367 HeadersFilename = FrameworkName;
368 HeadersFilename += "PrivateHeaders/";
369 HeadersFilename.append(SlashPos+1, FilenameEnd);
370 if (!(FE = FileMgr.getFile(HeadersFilename.begin(), HeadersFilename.end())))
371 return 0;
372 }
373
374 // This file is a system header or C++ unfriendly if the old file is.
Ted Kremenekca63fa02008-02-24 03:55:14 +0000375
376 // Note: Don't use:
377 //
378 // getFileInfo(FE).DirInfo = getFileInfo(ContextFileEnt).DirInfo;
379 //
380 // MSVC, behind the scenes, does this:
381 //
382 // PerFileInfo &pf1 = getFileInfo(ContextFileEnt);
383 // PerFileInfo &pf2 = getFileInfo(FE);
384 // pf2.DirInfo = pf1.DirInfo
385 //
386 // The problem is that if there's a resize() of the FileInfo vector during
387 // the getFileInfo(FE) call, pf1 will point to invalid data. The solution
388 // is to make the assignment through a temporary.
389 unsigned int tmp = getFileInfo(ContextFileEnt).DirInfo;
390 getFileInfo(FE).DirInfo = tmp;
Reid Spencer5f016e22007-07-11 17:01:13 +0000391 return FE;
392}
393
394//===----------------------------------------------------------------------===//
395// File Info Management.
396//===----------------------------------------------------------------------===//
397
398
399/// getFileInfo - Return the PerFileInfo structure for the specified
400/// FileEntry.
401HeaderSearch::PerFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) {
402 if (FE->getUID() >= FileInfo.size())
403 FileInfo.resize(FE->getUID()+1);
404 return FileInfo[FE->getUID()];
405}
406
407/// ShouldEnterIncludeFile - Mark the specified file as a target of of a
408/// #include, #include_next, or #import directive. Return false if #including
409/// the file will have no effect or true if we should include it.
410bool HeaderSearch::ShouldEnterIncludeFile(const FileEntry *File, bool isImport){
411 ++NumIncluded; // Count # of attempted #includes.
412
413 // Get information about this file.
414 PerFileInfo &FileInfo = getFileInfo(File);
415
416 // If this is a #import directive, check that we have not already imported
417 // this header.
418 if (isImport) {
419 // If this has already been imported, don't import it again.
420 FileInfo.isImport = true;
421
422 // Has this already been #import'ed or #include'd?
423 if (FileInfo.NumIncludes) return false;
424 } else {
425 // Otherwise, if this is a #include of a file that was previously #import'd
426 // or if this is the second #include of a #pragma once file, ignore it.
427 if (FileInfo.isImport)
428 return false;
429 }
430
431 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
432 // if the macro that guards it is defined, we know the #include has no effect.
Chris Lattner9c46de42007-10-07 07:57:27 +0000433 if (FileInfo.ControllingMacro &&
434 FileInfo.ControllingMacro->hasMacroDefinition()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000435 ++NumMultiIncludeFileOptzn;
436 return false;
437 }
438
439 // Increment the number of times this file has been included.
440 ++FileInfo.NumIncludes;
441
442 return true;
443}
444
445