blob: 44ae35c8b7e4f82dff4f5d300fd67b4228f71bba [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 //
Chris Lattnerc9dde4f2008-02-25 21:38:21 +0000232 // Note that the temporary 'DirInfo' is required here, as either call to
233 // getFileInfo could resize the vector and we don't want to rely on order
234 // of evaluation.
235 unsigned DirInfo = getFileInfo(CurFileEnt).DirInfo;
236 getFileInfo(FE).DirInfo = DirInfo;
Reid Spencer5f016e22007-07-11 17:01:13 +0000237 return FE;
238 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000239 }
240
241 CurDir = 0;
242
243 // If this is a system #include, ignore the user #include locs.
244 unsigned i = isAngled ? SystemDirIdx : 0;
245
246 // If this is a #include_next request, start searching after the directory the
247 // file was found in.
248 if (FromDir)
249 i = FromDir-&SearchDirs[0];
250
Chris Lattner9960ae82007-07-22 07:28:00 +0000251 // Cache all of the lookups performed by this method. Many headers are
252 // multiply included, and the "pragma once" optimization prevents them from
253 // being relex/pp'd, but they would still have to search through a
254 // (potentially huge) series of SearchDirs to find it.
255 std::pair<unsigned, unsigned> &CacheLookup =
256 LookupFileCache.GetOrCreateValue(FilenameStart, FilenameEnd).getValue();
257
258 // If the entry has been previously looked up, the first value will be
259 // non-zero. If the value is equal to i (the start point of our search), then
260 // this is a matching hit.
261 if (CacheLookup.first == i+1) {
262 // Skip querying potentially lots of directories for this lookup.
263 i = CacheLookup.second;
264 } else {
265 // Otherwise, this is the first query, or the previous query didn't match
266 // our search start. We will fill in our found location below, so prime the
267 // start point value.
268 CacheLookup.first = i+1;
269 }
Chris Lattnerdf772332007-12-17 07:52:39 +0000270
Reid Spencer5f016e22007-07-11 17:01:13 +0000271 // Check each directory in sequence to see if it contains this file.
272 for (; i != SearchDirs.size(); ++i) {
Chris Lattnerafded5b2007-12-17 08:13:48 +0000273 const FileEntry *FE =
274 SearchDirs[i].LookupFile(FilenameStart, FilenameEnd, *this);
275 if (!FE) continue;
Reid Spencer5f016e22007-07-11 17:01:13 +0000276
Chris Lattnerafded5b2007-12-17 08:13:48 +0000277 CurDir = &SearchDirs[i];
278
279 // This file is a system header or C++ unfriendly if the dir is.
280 getFileInfo(FE).DirInfo = CurDir->getDirCharacteristic();
281
282 // Remember this location for the next lookup we do.
283 CacheLookup.second = i;
284 return FE;
Reid Spencer5f016e22007-07-11 17:01:13 +0000285 }
286
Chris Lattner9960ae82007-07-22 07:28:00 +0000287 // Otherwise, didn't find it. Remember we didn't find this.
288 CacheLookup.second = SearchDirs.size();
Reid Spencer5f016e22007-07-11 17:01:13 +0000289 return 0;
290}
291
292/// LookupSubframeworkHeader - Look up a subframework for the specified
293/// #include file. For example, if #include'ing <HIToolbox/HIToolbox.h> from
294/// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
295/// is a subframework within Carbon.framework. If so, return the FileEntry
296/// for the designated file, otherwise return null.
297const FileEntry *HeaderSearch::
298LookupSubframeworkHeader(const char *FilenameStart,
299 const char *FilenameEnd,
300 const FileEntry *ContextFileEnt) {
Chris Lattner9415a0c2008-02-01 05:34:02 +0000301 assert(ContextFileEnt && "No context file?");
302
Reid Spencer5f016e22007-07-11 17:01:13 +0000303 // Framework names must have a '/' in the filename. Find it.
304 const char *SlashPos = std::find(FilenameStart, FilenameEnd, '/');
305 if (SlashPos == FilenameEnd) return 0;
306
307 // Look up the base framework name of the ContextFileEnt.
308 const char *ContextName = ContextFileEnt->getName();
309
310 // If the context info wasn't a framework, couldn't be a subframework.
311 const char *FrameworkPos = strstr(ContextName, ".framework/");
312 if (FrameworkPos == 0)
313 return 0;
314
315 llvm::SmallString<1024> FrameworkName(ContextName,
316 FrameworkPos+strlen(".framework/"));
317
318 // Append Frameworks/HIToolbox.framework/
319 FrameworkName += "Frameworks/";
320 FrameworkName.append(FilenameStart, SlashPos);
321 FrameworkName += ".framework/";
322
323 llvm::StringMapEntry<const DirectoryEntry *> &CacheLookup =
324 FrameworkMap.GetOrCreateValue(FilenameStart, SlashPos);
325
326 // Some other location?
327 if (CacheLookup.getValue() &&
328 CacheLookup.getKeyLength() == FrameworkName.size() &&
329 memcmp(CacheLookup.getKeyData(), &FrameworkName[0],
330 CacheLookup.getKeyLength()) != 0)
331 return 0;
332
333 // Cache subframework.
334 if (CacheLookup.getValue() == 0) {
335 ++NumSubFrameworkLookups;
336
337 // If the framework dir doesn't exist, we fail.
338 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName.begin(),
339 FrameworkName.end());
340 if (Dir == 0) return 0;
341
342 // Otherwise, if it does, remember that this is the right direntry for this
343 // framework.
344 CacheLookup.setValue(Dir);
345 }
346
347 const FileEntry *FE = 0;
348
349 // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
350 llvm::SmallString<1024> HeadersFilename(FrameworkName);
351 HeadersFilename += "Headers/";
352 HeadersFilename.append(SlashPos+1, FilenameEnd);
353 if (!(FE = FileMgr.getFile(HeadersFilename.begin(),
354 HeadersFilename.end()))) {
355
356 // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
357 HeadersFilename = FrameworkName;
358 HeadersFilename += "PrivateHeaders/";
359 HeadersFilename.append(SlashPos+1, FilenameEnd);
360 if (!(FE = FileMgr.getFile(HeadersFilename.begin(), HeadersFilename.end())))
361 return 0;
362 }
363
364 // This file is a system header or C++ unfriendly if the old file is.
Ted Kremenekca63fa02008-02-24 03:55:14 +0000365 //
Chris Lattnerc9dde4f2008-02-25 21:38:21 +0000366 // Note that the temporary 'DirInfo' is required here, as either call to
367 // getFileInfo could resize the vector and we don't want to rely on order
368 // of evaluation.
369 unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo;
370 getFileInfo(FE).DirInfo = DirInfo;
Reid Spencer5f016e22007-07-11 17:01:13 +0000371 return FE;
372}
373
374//===----------------------------------------------------------------------===//
375// File Info Management.
376//===----------------------------------------------------------------------===//
377
378
379/// getFileInfo - Return the PerFileInfo structure for the specified
380/// FileEntry.
381HeaderSearch::PerFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) {
382 if (FE->getUID() >= FileInfo.size())
383 FileInfo.resize(FE->getUID()+1);
384 return FileInfo[FE->getUID()];
385}
386
387/// ShouldEnterIncludeFile - Mark the specified file as a target of of a
388/// #include, #include_next, or #import directive. Return false if #including
389/// the file will have no effect or true if we should include it.
390bool HeaderSearch::ShouldEnterIncludeFile(const FileEntry *File, bool isImport){
391 ++NumIncluded; // Count # of attempted #includes.
392
393 // Get information about this file.
394 PerFileInfo &FileInfo = getFileInfo(File);
395
396 // If this is a #import directive, check that we have not already imported
397 // this header.
398 if (isImport) {
399 // If this has already been imported, don't import it again.
400 FileInfo.isImport = true;
401
402 // Has this already been #import'ed or #include'd?
403 if (FileInfo.NumIncludes) return false;
404 } else {
405 // Otherwise, if this is a #include of a file that was previously #import'd
406 // or if this is the second #include of a #pragma once file, ignore it.
407 if (FileInfo.isImport)
408 return false;
409 }
410
411 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
412 // if the macro that guards it is defined, we know the #include has no effect.
Chris Lattner9c46de42007-10-07 07:57:27 +0000413 if (FileInfo.ControllingMacro &&
414 FileInfo.ControllingMacro->hasMacroDefinition()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000415 ++NumMultiIncludeFileOptzn;
416 return false;
417 }
418
419 // Increment the number of times this file has been included.
420 ++FileInfo.NumIncludes;
421
422 return true;
423}
424
425