blob: 129fa1ae35fae1bb8a49e17df8ba2f3d851a57e7 [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
Douglas Gregor8c5a7602009-04-25 23:30:02 +000023const IdentifierInfo *
24HeaderFileInfo::getControllingMacro(ExternalIdentifierLookup *External) {
25 if (ControllingMacro)
26 return ControllingMacro;
27
28 if (!ControllingMacroID || !External)
29 return 0;
30
31 ControllingMacro = External->GetIdentifier(ControllingMacroID);
32 return ControllingMacro;
33}
34
Reid Spencer5f016e22007-07-11 17:01:13 +000035HeaderSearch::HeaderSearch(FileManager &FM) : FileMgr(FM), FrameworkMap(64) {
36 SystemDirIdx = 0;
37 NoCurDirSearch = false;
Douglas Gregor8c5a7602009-04-25 23:30:02 +000038
39 ExternalLookup = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000040 NumIncluded = 0;
41 NumMultiIncludeFileOptzn = 0;
42 NumFrameworkLookups = NumSubFrameworkLookups = 0;
43}
44
Chris Lattner822da612007-12-17 06:36:45 +000045HeaderSearch::~HeaderSearch() {
46 // Delete headermaps.
47 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
48 delete HeaderMaps[i].second;
49}
50
Reid Spencer5f016e22007-07-11 17:01:13 +000051void HeaderSearch::PrintStats() {
52 fprintf(stderr, "\n*** HeaderSearch Stats:\n");
53 fprintf(stderr, "%d files tracked.\n", (int)FileInfo.size());
54 unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0;
55 for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) {
56 NumOnceOnlyFiles += FileInfo[i].isImport;
57 if (MaxNumIncludes < FileInfo[i].NumIncludes)
58 MaxNumIncludes = FileInfo[i].NumIncludes;
59 NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1;
60 }
61 fprintf(stderr, " %d #import/#pragma once files.\n", NumOnceOnlyFiles);
62 fprintf(stderr, " %d included exactly once.\n", NumSingleIncludedFiles);
63 fprintf(stderr, " %d max times a file is included.\n", MaxNumIncludes);
64
65 fprintf(stderr, " %d #include/#include_next/#import.\n", NumIncluded);
66 fprintf(stderr, " %d #includes skipped due to"
67 " the multi-include optimization.\n", NumMultiIncludeFileOptzn);
68
69 fprintf(stderr, "%d framework lookups.\n", NumFrameworkLookups);
70 fprintf(stderr, "%d subframework lookups.\n", NumSubFrameworkLookups);
71}
72
Chris Lattner822da612007-12-17 06:36:45 +000073/// CreateHeaderMap - This method returns a HeaderMap for the specified
74/// FileEntry, uniquing them through the the 'HeaderMaps' datastructure.
Chris Lattner1bfd4a62007-12-17 18:34:53 +000075const HeaderMap *HeaderSearch::CreateHeaderMap(const FileEntry *FE) {
Chris Lattner822da612007-12-17 06:36:45 +000076 // We expect the number of headermaps to be small, and almost always empty.
Chris Lattnerdf772332007-12-17 07:52:39 +000077 // If it ever grows, use of a linear search should be re-evaluated.
Chris Lattner822da612007-12-17 06:36:45 +000078 if (!HeaderMaps.empty()) {
79 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
Chris Lattnerdf772332007-12-17 07:52:39 +000080 // Pointer equality comparison of FileEntries works because they are
81 // already uniqued by inode.
Chris Lattner822da612007-12-17 06:36:45 +000082 if (HeaderMaps[i].first == FE)
83 return HeaderMaps[i].second;
84 }
85
Chris Lattner1bfd4a62007-12-17 18:34:53 +000086 if (const HeaderMap *HM = HeaderMap::Create(FE)) {
Chris Lattner822da612007-12-17 06:36:45 +000087 HeaderMaps.push_back(std::make_pair(FE, HM));
88 return HM;
89 }
90
91 return 0;
92}
93
Chris Lattnerdf772332007-12-17 07:52:39 +000094//===----------------------------------------------------------------------===//
95// File lookup within a DirectoryLookup scope
96//===----------------------------------------------------------------------===//
97
Chris Lattner3af66a92007-12-17 17:57:27 +000098/// getName - Return the directory or filename corresponding to this lookup
99/// object.
100const char *DirectoryLookup::getName() const {
101 if (isNormalDir())
102 return getDir()->getName();
103 if (isFramework())
104 return getFrameworkDir()->getName();
105 assert(isHeaderMap() && "Unknown DirectoryLookup");
106 return getHeaderMap()->getFileName();
107}
108
109
Chris Lattnerdf772332007-12-17 07:52:39 +0000110/// LookupFile - Lookup the specified file in this search path, returning it
111/// if it exists or returning null if not.
112const FileEntry *DirectoryLookup::LookupFile(const char *FilenameStart,
113 const char *FilenameEnd,
Chris Lattnerafded5b2007-12-17 08:13:48 +0000114 HeaderSearch &HS) const {
Chris Lattnerdf772332007-12-17 07:52:39 +0000115 llvm::SmallString<1024> TmpDir;
Chris Lattnerafded5b2007-12-17 08:13:48 +0000116 if (isNormalDir()) {
117 // Concatenate the requested file onto the directory.
118 // FIXME: Portability. Filename concatenation should be in sys::Path.
119 TmpDir += getDir()->getName();
120 TmpDir.push_back('/');
121 TmpDir.append(FilenameStart, FilenameEnd);
122 return HS.getFileMgr().getFile(TmpDir.begin(), TmpDir.end());
123 }
Chris Lattnerdf772332007-12-17 07:52:39 +0000124
Chris Lattnerafded5b2007-12-17 08:13:48 +0000125 if (isFramework())
126 return DoFrameworkLookup(FilenameStart, FilenameEnd, HS);
127
Chris Lattnerb09e71f2007-12-17 08:17:39 +0000128 assert(isHeaderMap() && "Unknown directory lookup");
129 return getHeaderMap()->LookupFile(FilenameStart, FilenameEnd,HS.getFileMgr());
Chris Lattnerdf772332007-12-17 07:52:39 +0000130}
131
132
Chris Lattnerafded5b2007-12-17 08:13:48 +0000133/// DoFrameworkLookup - Do a lookup of the specified file in the current
134/// DirectoryLookup, which is a framework directory.
135const FileEntry *DirectoryLookup::DoFrameworkLookup(const char *FilenameStart,
136 const char *FilenameEnd,
137 HeaderSearch &HS) const {
138 FileManager &FileMgr = HS.getFileMgr();
139
Reid Spencer5f016e22007-07-11 17:01:13 +0000140 // Framework names must have a '/' in the filename.
141 const char *SlashPos = std::find(FilenameStart, FilenameEnd, '/');
142 if (SlashPos == FilenameEnd) return 0;
143
Chris Lattnerafded5b2007-12-17 08:13:48 +0000144 // Find out if this is the home for the specified framework, by checking
145 // HeaderSearch. Possible answer are yes/no and unknown.
146 const DirectoryEntry *&FrameworkDirCache =
147 HS.LookupFrameworkCache(FilenameStart, SlashPos);
Reid Spencer5f016e22007-07-11 17:01:13 +0000148
Chris Lattnerafded5b2007-12-17 08:13:48 +0000149 // If it is known and in some other directory, fail.
150 if (FrameworkDirCache && FrameworkDirCache != getFrameworkDir())
Reid Spencer5f016e22007-07-11 17:01:13 +0000151 return 0;
Chris Lattnerafded5b2007-12-17 08:13:48 +0000152
153 // Otherwise, construct the path to this framework dir.
154
Reid Spencer5f016e22007-07-11 17:01:13 +0000155 // FrameworkName = "/System/Library/Frameworks/"
156 llvm::SmallString<1024> FrameworkName;
Chris Lattnerafded5b2007-12-17 08:13:48 +0000157 FrameworkName += getFrameworkDir()->getName();
Reid Spencer5f016e22007-07-11 17:01:13 +0000158 if (FrameworkName.empty() || FrameworkName.back() != '/')
159 FrameworkName.push_back('/');
160
161 // FrameworkName = "/System/Library/Frameworks/Cocoa"
162 FrameworkName.append(FilenameStart, SlashPos);
163
164 // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/"
165 FrameworkName += ".framework/";
Chris Lattnerafded5b2007-12-17 08:13:48 +0000166
167 // If the cache entry is still unresolved, query to see if the cache entry is
168 // still unresolved. If so, check its existence now.
169 if (FrameworkDirCache == 0) {
170 HS.IncrementFrameworkLookupCount();
Reid Spencer5f016e22007-07-11 17:01:13 +0000171
172 // If the framework dir doesn't exist, we fail.
Chris Lattnerafded5b2007-12-17 08:13:48 +0000173 // FIXME: It's probably more efficient to query this with FileMgr.getDir.
Reid Spencer5f016e22007-07-11 17:01:13 +0000174 if (!llvm::sys::Path(std::string(FrameworkName.begin(),
175 FrameworkName.end())).exists())
176 return 0;
177
178 // Otherwise, if it does, remember that this is the right direntry for this
179 // framework.
Chris Lattnerafded5b2007-12-17 08:13:48 +0000180 FrameworkDirCache = getFrameworkDir();
Reid Spencer5f016e22007-07-11 17:01:13 +0000181 }
182
183 // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"
184 unsigned OrigSize = FrameworkName.size();
185
186 FrameworkName += "Headers/";
187 FrameworkName.append(SlashPos+1, FilenameEnd);
188 if (const FileEntry *FE = FileMgr.getFile(FrameworkName.begin(),
189 FrameworkName.end())) {
190 return FE;
191 }
192
193 // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"
194 const char *Private = "Private";
195 FrameworkName.insert(FrameworkName.begin()+OrigSize, Private,
196 Private+strlen(Private));
197 return FileMgr.getFile(FrameworkName.begin(), FrameworkName.end());
198}
199
Chris Lattnerdf772332007-12-17 07:52:39 +0000200
Chris Lattnerafded5b2007-12-17 08:13:48 +0000201//===----------------------------------------------------------------------===//
202// Header File Location.
203//===----------------------------------------------------------------------===//
204
205
Reid Spencer5f016e22007-07-11 17:01:13 +0000206/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
207/// return null on failure. isAngled indicates whether the file reference is
208/// for system #include's or not (i.e. using <> instead of ""). CurFileEnt, if
209/// non-null, indicates where the #including file is, in case a relative search
210/// is needed.
211const FileEntry *HeaderSearch::LookupFile(const char *FilenameStart,
212 const char *FilenameEnd,
213 bool isAngled,
214 const DirectoryLookup *FromDir,
215 const DirectoryLookup *&CurDir,
216 const FileEntry *CurFileEnt) {
217 // If 'Filename' is absolute, check to see if it exists and no searching.
218 // FIXME: Portability. This should be a sys::Path interface, this doesn't
219 // handle things like C:\foo.txt right, nor win32 \\network\device\blah.
220 if (FilenameStart[0] == '/') {
221 CurDir = 0;
222
223 // If this was an #include_next "/absolute/file", fail.
224 if (FromDir) return 0;
225
226 // Otherwise, just return the file.
227 return FileMgr.getFile(FilenameStart, FilenameEnd);
228 }
229
Reid Spencer5f016e22007-07-11 17:01:13 +0000230 // Step #0, unless disabled, check to see if the file is in the #includer's
Chris Lattnerdf772332007-12-17 07:52:39 +0000231 // directory. This has to be based on CurFileEnt, not CurDir, because
232 // CurFileEnt could be a #include of a subdirectory (#include "foo/bar.h") and
233 // a subsequent include of "baz.h" should resolve to "whatever/foo/baz.h".
234 // This search is not done for <> headers.
Reid Spencer5f016e22007-07-11 17:01:13 +0000235 if (CurFileEnt && !isAngled && !NoCurDirSearch) {
Chris Lattnerdf772332007-12-17 07:52:39 +0000236 llvm::SmallString<1024> TmpDir;
Reid Spencer5f016e22007-07-11 17:01:13 +0000237 // Concatenate the requested file onto the directory.
238 // FIXME: Portability. Filename concatenation should be in sys::Path.
239 TmpDir += CurFileEnt->getDir()->getName();
240 TmpDir.push_back('/');
241 TmpDir.append(FilenameStart, FilenameEnd);
242 if (const FileEntry *FE = FileMgr.getFile(TmpDir.begin(), TmpDir.end())) {
243 // Leave CurDir unset.
Reid Spencer5f016e22007-07-11 17:01:13 +0000244 // This file is a system header or C++ unfriendly if the old file is.
Ted Kremenekca63fa02008-02-24 03:55:14 +0000245 //
Chris Lattnerc9dde4f2008-02-25 21:38:21 +0000246 // Note that the temporary 'DirInfo' is required here, as either call to
247 // getFileInfo could resize the vector and we don't want to rely on order
248 // of evaluation.
249 unsigned DirInfo = getFileInfo(CurFileEnt).DirInfo;
250 getFileInfo(FE).DirInfo = DirInfo;
Reid Spencer5f016e22007-07-11 17:01:13 +0000251 return FE;
252 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000253 }
254
255 CurDir = 0;
256
257 // If this is a system #include, ignore the user #include locs.
258 unsigned i = isAngled ? SystemDirIdx : 0;
259
260 // If this is a #include_next request, start searching after the directory the
261 // file was found in.
262 if (FromDir)
263 i = FromDir-&SearchDirs[0];
264
Chris Lattner9960ae82007-07-22 07:28:00 +0000265 // Cache all of the lookups performed by this method. Many headers are
266 // multiply included, and the "pragma once" optimization prevents them from
267 // being relex/pp'd, but they would still have to search through a
268 // (potentially huge) series of SearchDirs to find it.
269 std::pair<unsigned, unsigned> &CacheLookup =
270 LookupFileCache.GetOrCreateValue(FilenameStart, FilenameEnd).getValue();
271
272 // If the entry has been previously looked up, the first value will be
273 // non-zero. If the value is equal to i (the start point of our search), then
274 // this is a matching hit.
275 if (CacheLookup.first == i+1) {
276 // Skip querying potentially lots of directories for this lookup.
277 i = CacheLookup.second;
278 } else {
279 // Otherwise, this is the first query, or the previous query didn't match
280 // our search start. We will fill in our found location below, so prime the
281 // start point value.
282 CacheLookup.first = i+1;
283 }
Chris Lattnerdf772332007-12-17 07:52:39 +0000284
Reid Spencer5f016e22007-07-11 17:01:13 +0000285 // Check each directory in sequence to see if it contains this file.
286 for (; i != SearchDirs.size(); ++i) {
Chris Lattnerafded5b2007-12-17 08:13:48 +0000287 const FileEntry *FE =
288 SearchDirs[i].LookupFile(FilenameStart, FilenameEnd, *this);
289 if (!FE) continue;
Reid Spencer5f016e22007-07-11 17:01:13 +0000290
Chris Lattnerafded5b2007-12-17 08:13:48 +0000291 CurDir = &SearchDirs[i];
292
293 // This file is a system header or C++ unfriendly if the dir is.
294 getFileInfo(FE).DirInfo = CurDir->getDirCharacteristic();
295
296 // Remember this location for the next lookup we do.
297 CacheLookup.second = i;
298 return FE;
Reid Spencer5f016e22007-07-11 17:01:13 +0000299 }
300
Chris Lattner9960ae82007-07-22 07:28:00 +0000301 // Otherwise, didn't find it. Remember we didn't find this.
302 CacheLookup.second = SearchDirs.size();
Reid Spencer5f016e22007-07-11 17:01:13 +0000303 return 0;
304}
305
306/// LookupSubframeworkHeader - Look up a subframework for the specified
307/// #include file. For example, if #include'ing <HIToolbox/HIToolbox.h> from
308/// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
309/// is a subframework within Carbon.framework. If so, return the FileEntry
310/// for the designated file, otherwise return null.
311const FileEntry *HeaderSearch::
312LookupSubframeworkHeader(const char *FilenameStart,
313 const char *FilenameEnd,
314 const FileEntry *ContextFileEnt) {
Chris Lattner9415a0c2008-02-01 05:34:02 +0000315 assert(ContextFileEnt && "No context file?");
316
Reid Spencer5f016e22007-07-11 17:01:13 +0000317 // Framework names must have a '/' in the filename. Find it.
318 const char *SlashPos = std::find(FilenameStart, FilenameEnd, '/');
319 if (SlashPos == FilenameEnd) return 0;
320
321 // Look up the base framework name of the ContextFileEnt.
322 const char *ContextName = ContextFileEnt->getName();
323
324 // If the context info wasn't a framework, couldn't be a subframework.
325 const char *FrameworkPos = strstr(ContextName, ".framework/");
326 if (FrameworkPos == 0)
327 return 0;
328
329 llvm::SmallString<1024> FrameworkName(ContextName,
330 FrameworkPos+strlen(".framework/"));
331
332 // Append Frameworks/HIToolbox.framework/
333 FrameworkName += "Frameworks/";
334 FrameworkName.append(FilenameStart, SlashPos);
335 FrameworkName += ".framework/";
336
337 llvm::StringMapEntry<const DirectoryEntry *> &CacheLookup =
338 FrameworkMap.GetOrCreateValue(FilenameStart, SlashPos);
339
340 // Some other location?
341 if (CacheLookup.getValue() &&
342 CacheLookup.getKeyLength() == FrameworkName.size() &&
343 memcmp(CacheLookup.getKeyData(), &FrameworkName[0],
344 CacheLookup.getKeyLength()) != 0)
345 return 0;
346
347 // Cache subframework.
348 if (CacheLookup.getValue() == 0) {
349 ++NumSubFrameworkLookups;
350
351 // If the framework dir doesn't exist, we fail.
352 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName.begin(),
353 FrameworkName.end());
354 if (Dir == 0) return 0;
355
356 // Otherwise, if it does, remember that this is the right direntry for this
357 // framework.
358 CacheLookup.setValue(Dir);
359 }
360
361 const FileEntry *FE = 0;
362
363 // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
364 llvm::SmallString<1024> HeadersFilename(FrameworkName);
365 HeadersFilename += "Headers/";
366 HeadersFilename.append(SlashPos+1, FilenameEnd);
367 if (!(FE = FileMgr.getFile(HeadersFilename.begin(),
368 HeadersFilename.end()))) {
369
370 // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
371 HeadersFilename = FrameworkName;
372 HeadersFilename += "PrivateHeaders/";
373 HeadersFilename.append(SlashPos+1, FilenameEnd);
374 if (!(FE = FileMgr.getFile(HeadersFilename.begin(), HeadersFilename.end())))
375 return 0;
376 }
377
378 // This file is a system header or C++ unfriendly if the old file is.
Ted Kremenekca63fa02008-02-24 03:55:14 +0000379 //
Chris Lattnerc9dde4f2008-02-25 21:38:21 +0000380 // Note that the temporary 'DirInfo' is required here, as either call to
381 // getFileInfo could resize the vector and we don't want to rely on order
382 // of evaluation.
383 unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo;
384 getFileInfo(FE).DirInfo = DirInfo;
Reid Spencer5f016e22007-07-11 17:01:13 +0000385 return FE;
386}
387
388//===----------------------------------------------------------------------===//
389// File Info Management.
390//===----------------------------------------------------------------------===//
391
392
Steve Naroff83d63c72009-04-24 20:03:17 +0000393/// getFileInfo - Return the HeaderFileInfo structure for the specified
Reid Spencer5f016e22007-07-11 17:01:13 +0000394/// FileEntry.
Steve Naroff83d63c72009-04-24 20:03:17 +0000395HeaderFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000396 if (FE->getUID() >= FileInfo.size())
397 FileInfo.resize(FE->getUID()+1);
398 return FileInfo[FE->getUID()];
399}
400
Steve Naroff83d63c72009-04-24 20:03:17 +0000401void HeaderSearch::setHeaderFileInfoForUID(HeaderFileInfo HFI, unsigned UID) {
402 if (UID >= FileInfo.size())
403 FileInfo.resize(UID+1);
404 FileInfo[UID] = HFI;
405}
406
Reid Spencer5f016e22007-07-11 17:01:13 +0000407/// 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.
Steve Naroff83d63c72009-04-24 20:03:17 +0000414 HeaderFileInfo &FileInfo = getFileInfo(File);
Reid Spencer5f016e22007-07-11 17:01:13 +0000415
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.
Douglas Gregor8c5a7602009-04-25 23:30:02 +0000433 if (const IdentifierInfo *ControllingMacro
434 = FileInfo.getControllingMacro(ExternalLookup))
435 if (ControllingMacro->hasMacroDefinition()) {
436 ++NumMultiIncludeFileOptzn;
437 return false;
438 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000439
440 // Increment the number of times this file has been included.
441 ++FileInfo.NumIncludes;
442
443 return true;
444}
445
446