blob: 2cc29ecbed8aedcca5c546ac9ba2b6a2f32c0bc2 [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"
Chris Lattner3daed522009-03-02 22:20:04 +000020#include <cstdio>
Reid Spencer5f016e22007-07-11 17:01:13 +000021using namespace clang;
22
23HeaderSearch::HeaderSearch(FileManager &FM) : FileMgr(FM), FrameworkMap(64) {
24 SystemDirIdx = 0;
25 NoCurDirSearch = false;
26
27 NumIncluded = 0;
28 NumMultiIncludeFileOptzn = 0;
29 NumFrameworkLookups = NumSubFrameworkLookups = 0;
30}
31
Chris Lattner822da612007-12-17 06:36:45 +000032HeaderSearch::~HeaderSearch() {
33 // Delete headermaps.
34 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
35 delete HeaderMaps[i].second;
36}
37
Reid Spencer5f016e22007-07-11 17:01:13 +000038void HeaderSearch::PrintStats() {
39 fprintf(stderr, "\n*** HeaderSearch Stats:\n");
40 fprintf(stderr, "%d files tracked.\n", (int)FileInfo.size());
41 unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0;
42 for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) {
43 NumOnceOnlyFiles += FileInfo[i].isImport;
44 if (MaxNumIncludes < FileInfo[i].NumIncludes)
45 MaxNumIncludes = FileInfo[i].NumIncludes;
46 NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1;
47 }
48 fprintf(stderr, " %d #import/#pragma once files.\n", NumOnceOnlyFiles);
49 fprintf(stderr, " %d included exactly once.\n", NumSingleIncludedFiles);
50 fprintf(stderr, " %d max times a file is included.\n", MaxNumIncludes);
51
52 fprintf(stderr, " %d #include/#include_next/#import.\n", NumIncluded);
53 fprintf(stderr, " %d #includes skipped due to"
54 " the multi-include optimization.\n", NumMultiIncludeFileOptzn);
55
56 fprintf(stderr, "%d framework lookups.\n", NumFrameworkLookups);
57 fprintf(stderr, "%d subframework lookups.\n", NumSubFrameworkLookups);
58}
59
Chris Lattner822da612007-12-17 06:36:45 +000060/// CreateHeaderMap - This method returns a HeaderMap for the specified
61/// FileEntry, uniquing them through the the 'HeaderMaps' datastructure.
Chris Lattner1bfd4a62007-12-17 18:34:53 +000062const HeaderMap *HeaderSearch::CreateHeaderMap(const FileEntry *FE) {
Chris Lattner822da612007-12-17 06:36:45 +000063 // We expect the number of headermaps to be small, and almost always empty.
Chris Lattnerdf772332007-12-17 07:52:39 +000064 // If it ever grows, use of a linear search should be re-evaluated.
Chris Lattner822da612007-12-17 06:36:45 +000065 if (!HeaderMaps.empty()) {
66 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
Chris Lattnerdf772332007-12-17 07:52:39 +000067 // Pointer equality comparison of FileEntries works because they are
68 // already uniqued by inode.
Chris Lattner822da612007-12-17 06:36:45 +000069 if (HeaderMaps[i].first == FE)
70 return HeaderMaps[i].second;
71 }
72
Chris Lattner1bfd4a62007-12-17 18:34:53 +000073 if (const HeaderMap *HM = HeaderMap::Create(FE)) {
Chris Lattner822da612007-12-17 06:36:45 +000074 HeaderMaps.push_back(std::make_pair(FE, HM));
75 return HM;
76 }
77
78 return 0;
79}
80
Chris Lattnerdf772332007-12-17 07:52:39 +000081//===----------------------------------------------------------------------===//
82// File lookup within a DirectoryLookup scope
83//===----------------------------------------------------------------------===//
84
Chris Lattner3af66a92007-12-17 17:57:27 +000085/// getName - Return the directory or filename corresponding to this lookup
86/// object.
87const char *DirectoryLookup::getName() const {
88 if (isNormalDir())
89 return getDir()->getName();
90 if (isFramework())
91 return getFrameworkDir()->getName();
92 assert(isHeaderMap() && "Unknown DirectoryLookup");
93 return getHeaderMap()->getFileName();
94}
95
96
Chris Lattnerdf772332007-12-17 07:52:39 +000097/// LookupFile - Lookup the specified file in this search path, returning it
98/// if it exists or returning null if not.
99const FileEntry *DirectoryLookup::LookupFile(const char *FilenameStart,
100 const char *FilenameEnd,
Chris Lattnerafded5b2007-12-17 08:13:48 +0000101 HeaderSearch &HS) const {
Chris Lattnerdf772332007-12-17 07:52:39 +0000102 llvm::SmallString<1024> TmpDir;
Chris Lattnerafded5b2007-12-17 08:13:48 +0000103 if (isNormalDir()) {
104 // Concatenate the requested file onto the directory.
105 // FIXME: Portability. Filename concatenation should be in sys::Path.
106 TmpDir += getDir()->getName();
107 TmpDir.push_back('/');
108 TmpDir.append(FilenameStart, FilenameEnd);
109 return HS.getFileMgr().getFile(TmpDir.begin(), TmpDir.end());
110 }
Chris Lattnerdf772332007-12-17 07:52:39 +0000111
Chris Lattnerafded5b2007-12-17 08:13:48 +0000112 if (isFramework())
113 return DoFrameworkLookup(FilenameStart, FilenameEnd, HS);
114
Chris Lattnerb09e71f2007-12-17 08:17:39 +0000115 assert(isHeaderMap() && "Unknown directory lookup");
116 return getHeaderMap()->LookupFile(FilenameStart, FilenameEnd,HS.getFileMgr());
Chris Lattnerdf772332007-12-17 07:52:39 +0000117}
118
119
Chris Lattnerafded5b2007-12-17 08:13:48 +0000120/// DoFrameworkLookup - Do a lookup of the specified file in the current
121/// DirectoryLookup, which is a framework directory.
122const FileEntry *DirectoryLookup::DoFrameworkLookup(const char *FilenameStart,
123 const char *FilenameEnd,
124 HeaderSearch &HS) const {
125 FileManager &FileMgr = HS.getFileMgr();
126
Reid Spencer5f016e22007-07-11 17:01:13 +0000127 // Framework names must have a '/' in the filename.
128 const char *SlashPos = std::find(FilenameStart, FilenameEnd, '/');
129 if (SlashPos == FilenameEnd) return 0;
130
Chris Lattnerafded5b2007-12-17 08:13:48 +0000131 // Find out if this is the home for the specified framework, by checking
132 // HeaderSearch. Possible answer are yes/no and unknown.
133 const DirectoryEntry *&FrameworkDirCache =
134 HS.LookupFrameworkCache(FilenameStart, SlashPos);
Reid Spencer5f016e22007-07-11 17:01:13 +0000135
Chris Lattnerafded5b2007-12-17 08:13:48 +0000136 // If it is known and in some other directory, fail.
137 if (FrameworkDirCache && FrameworkDirCache != getFrameworkDir())
Reid Spencer5f016e22007-07-11 17:01:13 +0000138 return 0;
Chris Lattnerafded5b2007-12-17 08:13:48 +0000139
140 // Otherwise, construct the path to this framework dir.
141
Reid Spencer5f016e22007-07-11 17:01:13 +0000142 // FrameworkName = "/System/Library/Frameworks/"
143 llvm::SmallString<1024> FrameworkName;
Chris Lattnerafded5b2007-12-17 08:13:48 +0000144 FrameworkName += getFrameworkDir()->getName();
Reid Spencer5f016e22007-07-11 17:01:13 +0000145 if (FrameworkName.empty() || FrameworkName.back() != '/')
146 FrameworkName.push_back('/');
147
148 // FrameworkName = "/System/Library/Frameworks/Cocoa"
149 FrameworkName.append(FilenameStart, SlashPos);
150
151 // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/"
152 FrameworkName += ".framework/";
Chris Lattnerafded5b2007-12-17 08:13:48 +0000153
154 // If the cache entry is still unresolved, query to see if the cache entry is
155 // still unresolved. If so, check its existence now.
156 if (FrameworkDirCache == 0) {
157 HS.IncrementFrameworkLookupCount();
Reid Spencer5f016e22007-07-11 17:01:13 +0000158
159 // If the framework dir doesn't exist, we fail.
Chris Lattnerafded5b2007-12-17 08:13:48 +0000160 // FIXME: It's probably more efficient to query this with FileMgr.getDir.
Reid Spencer5f016e22007-07-11 17:01:13 +0000161 if (!llvm::sys::Path(std::string(FrameworkName.begin(),
162 FrameworkName.end())).exists())
163 return 0;
164
165 // Otherwise, if it does, remember that this is the right direntry for this
166 // framework.
Chris Lattnerafded5b2007-12-17 08:13:48 +0000167 FrameworkDirCache = getFrameworkDir();
Reid Spencer5f016e22007-07-11 17:01:13 +0000168 }
169
170 // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"
171 unsigned OrigSize = FrameworkName.size();
172
173 FrameworkName += "Headers/";
174 FrameworkName.append(SlashPos+1, FilenameEnd);
175 if (const FileEntry *FE = FileMgr.getFile(FrameworkName.begin(),
176 FrameworkName.end())) {
177 return FE;
178 }
179
180 // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"
181 const char *Private = "Private";
182 FrameworkName.insert(FrameworkName.begin()+OrigSize, Private,
183 Private+strlen(Private));
184 return FileMgr.getFile(FrameworkName.begin(), FrameworkName.end());
185}
186
Chris Lattnerdf772332007-12-17 07:52:39 +0000187
Chris Lattnerafded5b2007-12-17 08:13:48 +0000188//===----------------------------------------------------------------------===//
189// Header File Location.
190//===----------------------------------------------------------------------===//
191
192
Reid Spencer5f016e22007-07-11 17:01:13 +0000193/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
194/// return null on failure. isAngled indicates whether the file reference is
195/// for system #include's or not (i.e. using <> instead of ""). CurFileEnt, if
196/// non-null, indicates where the #including file is, in case a relative search
197/// is needed.
198const FileEntry *HeaderSearch::LookupFile(const char *FilenameStart,
199 const char *FilenameEnd,
200 bool isAngled,
201 const DirectoryLookup *FromDir,
202 const DirectoryLookup *&CurDir,
203 const FileEntry *CurFileEnt) {
204 // If 'Filename' is absolute, check to see if it exists and no searching.
205 // FIXME: Portability. This should be a sys::Path interface, this doesn't
206 // handle things like C:\foo.txt right, nor win32 \\network\device\blah.
207 if (FilenameStart[0] == '/') {
208 CurDir = 0;
209
210 // If this was an #include_next "/absolute/file", fail.
211 if (FromDir) return 0;
212
213 // Otherwise, just return the file.
214 return FileMgr.getFile(FilenameStart, FilenameEnd);
215 }
216
Reid Spencer5f016e22007-07-11 17:01:13 +0000217 // Step #0, unless disabled, check to see if the file is in the #includer's
Chris Lattnerdf772332007-12-17 07:52:39 +0000218 // directory. This has to be based on CurFileEnt, not CurDir, because
219 // CurFileEnt could be a #include of a subdirectory (#include "foo/bar.h") and
220 // a subsequent include of "baz.h" should resolve to "whatever/foo/baz.h".
221 // This search is not done for <> headers.
Reid Spencer5f016e22007-07-11 17:01:13 +0000222 if (CurFileEnt && !isAngled && !NoCurDirSearch) {
Chris Lattnerdf772332007-12-17 07:52:39 +0000223 llvm::SmallString<1024> TmpDir;
Reid Spencer5f016e22007-07-11 17:01:13 +0000224 // Concatenate the requested file onto the directory.
225 // FIXME: Portability. Filename concatenation should be in sys::Path.
226 TmpDir += CurFileEnt->getDir()->getName();
227 TmpDir.push_back('/');
228 TmpDir.append(FilenameStart, FilenameEnd);
229 if (const FileEntry *FE = FileMgr.getFile(TmpDir.begin(), TmpDir.end())) {
230 // Leave CurDir unset.
Reid Spencer5f016e22007-07-11 17:01:13 +0000231 // This file is a system header or C++ unfriendly if the old file is.
Ted Kremenekca63fa02008-02-24 03:55:14 +0000232 //
Chris Lattnerc9dde4f2008-02-25 21:38:21 +0000233 // Note that the temporary 'DirInfo' is required here, as either call to
234 // getFileInfo could resize the vector and we don't want to rely on order
235 // of evaluation.
236 unsigned DirInfo = getFileInfo(CurFileEnt).DirInfo;
237 getFileInfo(FE).DirInfo = DirInfo;
Reid Spencer5f016e22007-07-11 17:01:13 +0000238 return FE;
239 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000240 }
241
242 CurDir = 0;
243
244 // If this is a system #include, ignore the user #include locs.
245 unsigned i = isAngled ? SystemDirIdx : 0;
246
247 // If this is a #include_next request, start searching after the directory the
248 // file was found in.
249 if (FromDir)
250 i = FromDir-&SearchDirs[0];
251
Chris Lattner9960ae82007-07-22 07:28:00 +0000252 // Cache all of the lookups performed by this method. Many headers are
253 // multiply included, and the "pragma once" optimization prevents them from
254 // being relex/pp'd, but they would still have to search through a
255 // (potentially huge) series of SearchDirs to find it.
256 std::pair<unsigned, unsigned> &CacheLookup =
257 LookupFileCache.GetOrCreateValue(FilenameStart, FilenameEnd).getValue();
258
259 // If the entry has been previously looked up, the first value will be
260 // non-zero. If the value is equal to i (the start point of our search), then
261 // this is a matching hit.
262 if (CacheLookup.first == i+1) {
263 // Skip querying potentially lots of directories for this lookup.
264 i = CacheLookup.second;
265 } else {
266 // Otherwise, this is the first query, or the previous query didn't match
267 // our search start. We will fill in our found location below, so prime the
268 // start point value.
269 CacheLookup.first = i+1;
270 }
Chris Lattnerdf772332007-12-17 07:52:39 +0000271
Reid Spencer5f016e22007-07-11 17:01:13 +0000272 // Check each directory in sequence to see if it contains this file.
273 for (; i != SearchDirs.size(); ++i) {
Chris Lattnerafded5b2007-12-17 08:13:48 +0000274 const FileEntry *FE =
275 SearchDirs[i].LookupFile(FilenameStart, FilenameEnd, *this);
276 if (!FE) continue;
Reid Spencer5f016e22007-07-11 17:01:13 +0000277
Chris Lattnerafded5b2007-12-17 08:13:48 +0000278 CurDir = &SearchDirs[i];
279
280 // This file is a system header or C++ unfriendly if the dir is.
281 getFileInfo(FE).DirInfo = CurDir->getDirCharacteristic();
282
283 // Remember this location for the next lookup we do.
284 CacheLookup.second = i;
285 return FE;
Reid Spencer5f016e22007-07-11 17:01:13 +0000286 }
287
Chris Lattner9960ae82007-07-22 07:28:00 +0000288 // Otherwise, didn't find it. Remember we didn't find this.
289 CacheLookup.second = SearchDirs.size();
Reid Spencer5f016e22007-07-11 17:01:13 +0000290 return 0;
291}
292
293/// LookupSubframeworkHeader - Look up a subframework for the specified
294/// #include file. For example, if #include'ing <HIToolbox/HIToolbox.h> from
295/// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
296/// is a subframework within Carbon.framework. If so, return the FileEntry
297/// for the designated file, otherwise return null.
298const FileEntry *HeaderSearch::
299LookupSubframeworkHeader(const char *FilenameStart,
300 const char *FilenameEnd,
301 const FileEntry *ContextFileEnt) {
Chris Lattner9415a0c2008-02-01 05:34:02 +0000302 assert(ContextFileEnt && "No context file?");
303
Reid Spencer5f016e22007-07-11 17:01:13 +0000304 // Framework names must have a '/' in the filename. Find it.
305 const char *SlashPos = std::find(FilenameStart, FilenameEnd, '/');
306 if (SlashPos == FilenameEnd) return 0;
307
308 // Look up the base framework name of the ContextFileEnt.
309 const char *ContextName = ContextFileEnt->getName();
310
311 // If the context info wasn't a framework, couldn't be a subframework.
312 const char *FrameworkPos = strstr(ContextName, ".framework/");
313 if (FrameworkPos == 0)
314 return 0;
315
316 llvm::SmallString<1024> FrameworkName(ContextName,
317 FrameworkPos+strlen(".framework/"));
318
319 // Append Frameworks/HIToolbox.framework/
320 FrameworkName += "Frameworks/";
321 FrameworkName.append(FilenameStart, SlashPos);
322 FrameworkName += ".framework/";
323
324 llvm::StringMapEntry<const DirectoryEntry *> &CacheLookup =
325 FrameworkMap.GetOrCreateValue(FilenameStart, SlashPos);
326
327 // Some other location?
328 if (CacheLookup.getValue() &&
329 CacheLookup.getKeyLength() == FrameworkName.size() &&
330 memcmp(CacheLookup.getKeyData(), &FrameworkName[0],
331 CacheLookup.getKeyLength()) != 0)
332 return 0;
333
334 // Cache subframework.
335 if (CacheLookup.getValue() == 0) {
336 ++NumSubFrameworkLookups;
337
338 // If the framework dir doesn't exist, we fail.
339 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName.begin(),
340 FrameworkName.end());
341 if (Dir == 0) return 0;
342
343 // Otherwise, if it does, remember that this is the right direntry for this
344 // framework.
345 CacheLookup.setValue(Dir);
346 }
347
348 const FileEntry *FE = 0;
349
350 // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
351 llvm::SmallString<1024> HeadersFilename(FrameworkName);
352 HeadersFilename += "Headers/";
353 HeadersFilename.append(SlashPos+1, FilenameEnd);
354 if (!(FE = FileMgr.getFile(HeadersFilename.begin(),
355 HeadersFilename.end()))) {
356
357 // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
358 HeadersFilename = FrameworkName;
359 HeadersFilename += "PrivateHeaders/";
360 HeadersFilename.append(SlashPos+1, FilenameEnd);
361 if (!(FE = FileMgr.getFile(HeadersFilename.begin(), HeadersFilename.end())))
362 return 0;
363 }
364
365 // This file is a system header or C++ unfriendly if the old file is.
Ted Kremenekca63fa02008-02-24 03:55:14 +0000366 //
Chris Lattnerc9dde4f2008-02-25 21:38:21 +0000367 // Note that the temporary 'DirInfo' is required here, as either call to
368 // getFileInfo could resize the vector and we don't want to rely on order
369 // of evaluation.
370 unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo;
371 getFileInfo(FE).DirInfo = DirInfo;
Reid Spencer5f016e22007-07-11 17:01:13 +0000372 return FE;
373}
374
375//===----------------------------------------------------------------------===//
376// File Info Management.
377//===----------------------------------------------------------------------===//
378
379
380/// getFileInfo - Return the PerFileInfo structure for the specified
381/// FileEntry.
382HeaderSearch::PerFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) {
383 if (FE->getUID() >= FileInfo.size())
384 FileInfo.resize(FE->getUID()+1);
385 return FileInfo[FE->getUID()];
386}
387
388/// ShouldEnterIncludeFile - Mark the specified file as a target of of a
389/// #include, #include_next, or #import directive. Return false if #including
390/// the file will have no effect or true if we should include it.
391bool HeaderSearch::ShouldEnterIncludeFile(const FileEntry *File, bool isImport){
392 ++NumIncluded; // Count # of attempted #includes.
393
394 // Get information about this file.
395 PerFileInfo &FileInfo = getFileInfo(File);
396
397 // If this is a #import directive, check that we have not already imported
398 // this header.
399 if (isImport) {
400 // If this has already been imported, don't import it again.
401 FileInfo.isImport = true;
402
403 // Has this already been #import'ed or #include'd?
404 if (FileInfo.NumIncludes) return false;
405 } else {
406 // Otherwise, if this is a #include of a file that was previously #import'd
407 // or if this is the second #include of a #pragma once file, ignore it.
408 if (FileInfo.isImport)
409 return false;
410 }
411
412 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
413 // if the macro that guards it is defined, we know the #include has no effect.
Chris Lattner9c46de42007-10-07 07:57:27 +0000414 if (FileInfo.ControllingMacro &&
415 FileInfo.ControllingMacro->hasMacroDefinition()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000416 ++NumMultiIncludeFileOptzn;
417 return false;
418 }
419
420 // Increment the number of times this file has been included.
421 ++FileInfo.NumIncludes;
422
423 return true;
424}
425
426