blob: 99d0d52f11500bde8793d32567c093cfbee31c25 [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.
61const HeaderMap *HeaderSearch::CreateHeaderMap(const FileEntry *FE,
62 std::string &ErrorInfo) {
63 // We expect the number of headermaps to be small, and almost always empty.
Chris Lattnerb7426782007-12-17 07:52:39 +000064 // If it ever grows, use of a linear search should be re-evaluated.
Chris Lattnerc2043bf2007-12-17 06:36:45 +000065 if (!HeaderMaps.empty()) {
66 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
Chris Lattnerb7426782007-12-17 07:52:39 +000067 // Pointer equality comparison of FileEntries works because they are
68 // already uniqued by inode.
Chris Lattnerc2043bf2007-12-17 06:36:45 +000069 if (HeaderMaps[i].first == FE)
70 return HeaderMaps[i].second;
71 }
72
73 if (const HeaderMap *HM = HeaderMap::Create(FE, ErrorInfo)) {
74 HeaderMaps.push_back(std::make_pair(FE, HM));
75 return HM;
76 }
77
78 return 0;
79}
80
Chris Lattnerb7426782007-12-17 07:52:39 +000081//===----------------------------------------------------------------------===//
82// File lookup within a DirectoryLookup scope
83//===----------------------------------------------------------------------===//
84
Chris Lattner1df68f92007-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 Lattnerb7426782007-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 Lattner7d0ad4a2007-12-17 08:13:48 +0000101 HeaderSearch &HS) const {
Chris Lattnerb7426782007-12-17 07:52:39 +0000102 llvm::SmallString<1024> TmpDir;
Chris Lattner7d0ad4a2007-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 Lattnerb7426782007-12-17 07:52:39 +0000111
Chris Lattner7d0ad4a2007-12-17 08:13:48 +0000112 if (isFramework())
113 return DoFrameworkLookup(FilenameStart, FilenameEnd, HS);
114
Chris Lattner61349712007-12-17 08:17:39 +0000115 assert(isHeaderMap() && "Unknown directory lookup");
116 return getHeaderMap()->LookupFile(FilenameStart, FilenameEnd,HS.getFileMgr());
Chris Lattnerb7426782007-12-17 07:52:39 +0000117}
118
119
Chris Lattner7d0ad4a2007-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
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattner7d0ad4a2007-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);
Chris Lattner4b009652007-07-25 00:24:17 +0000135
Chris Lattner7d0ad4a2007-12-17 08:13:48 +0000136 // If it is known and in some other directory, fail.
137 if (FrameworkDirCache && FrameworkDirCache != getFrameworkDir())
Chris Lattner4b009652007-07-25 00:24:17 +0000138 return 0;
Chris Lattner7d0ad4a2007-12-17 08:13:48 +0000139
140 // Otherwise, construct the path to this framework dir.
141
Chris Lattner4b009652007-07-25 00:24:17 +0000142 // FrameworkName = "/System/Library/Frameworks/"
143 llvm::SmallString<1024> FrameworkName;
Chris Lattner7d0ad4a2007-12-17 08:13:48 +0000144 FrameworkName += getFrameworkDir()->getName();
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattner7d0ad4a2007-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();
Chris Lattner4b009652007-07-25 00:24:17 +0000158
159 // If the framework dir doesn't exist, we fail.
Chris Lattner7d0ad4a2007-12-17 08:13:48 +0000160 // FIXME: It's probably more efficient to query this with FileMgr.getDir.
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattner7d0ad4a2007-12-17 08:13:48 +0000167 FrameworkDirCache = getFrameworkDir();
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattnerb7426782007-12-17 07:52:39 +0000187
Chris Lattner7d0ad4a2007-12-17 08:13:48 +0000188//===----------------------------------------------------------------------===//
189// Header File Location.
190//===----------------------------------------------------------------------===//
191
192
Chris Lattner4b009652007-07-25 00:24:17 +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
Chris Lattner4b009652007-07-25 00:24:17 +0000217 // Step #0, unless disabled, check to see if the file is in the #includer's
Chris Lattnerb7426782007-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.
Chris Lattner4b009652007-07-25 00:24:17 +0000222 if (CurFileEnt && !isAngled && !NoCurDirSearch) {
Chris Lattnerb7426782007-12-17 07:52:39 +0000223 llvm::SmallString<1024> TmpDir;
Chris Lattner4b009652007-07-25 00:24:17 +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.
Chris Lattner4b009652007-07-25 00:24:17 +0000231 // This file is a system header or C++ unfriendly if the old file is.
232 getFileInfo(FE).DirInfo = getFileInfo(CurFileEnt).DirInfo;
233 return FE;
234 }
Chris Lattner4b009652007-07-25 00:24:17 +0000235 }
236
237 CurDir = 0;
238
239 // If this is a system #include, ignore the user #include locs.
240 unsigned i = isAngled ? SystemDirIdx : 0;
241
242 // If this is a #include_next request, start searching after the directory the
243 // file was found in.
244 if (FromDir)
245 i = FromDir-&SearchDirs[0];
246
247 // Cache all of the lookups performed by this method. Many headers are
248 // multiply included, and the "pragma once" optimization prevents them from
249 // being relex/pp'd, but they would still have to search through a
250 // (potentially huge) series of SearchDirs to find it.
251 std::pair<unsigned, unsigned> &CacheLookup =
252 LookupFileCache.GetOrCreateValue(FilenameStart, FilenameEnd).getValue();
253
254 // If the entry has been previously looked up, the first value will be
255 // non-zero. If the value is equal to i (the start point of our search), then
256 // this is a matching hit.
257 if (CacheLookup.first == i+1) {
258 // Skip querying potentially lots of directories for this lookup.
259 i = CacheLookup.second;
260 } else {
261 // Otherwise, this is the first query, or the previous query didn't match
262 // our search start. We will fill in our found location below, so prime the
263 // start point value.
264 CacheLookup.first = i+1;
265 }
Chris Lattnerb7426782007-12-17 07:52:39 +0000266
Chris Lattner4b009652007-07-25 00:24:17 +0000267 // Check each directory in sequence to see if it contains this file.
268 for (; i != SearchDirs.size(); ++i) {
Chris Lattner7d0ad4a2007-12-17 08:13:48 +0000269 const FileEntry *FE =
270 SearchDirs[i].LookupFile(FilenameStart, FilenameEnd, *this);
271 if (!FE) continue;
Chris Lattner4b009652007-07-25 00:24:17 +0000272
Chris Lattner7d0ad4a2007-12-17 08:13:48 +0000273 CurDir = &SearchDirs[i];
274
275 // This file is a system header or C++ unfriendly if the dir is.
276 getFileInfo(FE).DirInfo = CurDir->getDirCharacteristic();
277
278 // Remember this location for the next lookup we do.
279 CacheLookup.second = i;
280 return FE;
Chris Lattner4b009652007-07-25 00:24:17 +0000281 }
282
283 // Otherwise, didn't find it. Remember we didn't find this.
284 CacheLookup.second = SearchDirs.size();
285 return 0;
286}
287
288/// LookupSubframeworkHeader - Look up a subframework for the specified
289/// #include file. For example, if #include'ing <HIToolbox/HIToolbox.h> from
290/// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
291/// is a subframework within Carbon.framework. If so, return the FileEntry
292/// for the designated file, otherwise return null.
293const FileEntry *HeaderSearch::
294LookupSubframeworkHeader(const char *FilenameStart,
295 const char *FilenameEnd,
296 const FileEntry *ContextFileEnt) {
297 // Framework names must have a '/' in the filename. Find it.
298 const char *SlashPos = std::find(FilenameStart, FilenameEnd, '/');
299 if (SlashPos == FilenameEnd) return 0;
300
301 // Look up the base framework name of the ContextFileEnt.
302 const char *ContextName = ContextFileEnt->getName();
303
304 // If the context info wasn't a framework, couldn't be a subframework.
305 const char *FrameworkPos = strstr(ContextName, ".framework/");
306 if (FrameworkPos == 0)
307 return 0;
308
309 llvm::SmallString<1024> FrameworkName(ContextName,
310 FrameworkPos+strlen(".framework/"));
311
312 // Append Frameworks/HIToolbox.framework/
313 FrameworkName += "Frameworks/";
314 FrameworkName.append(FilenameStart, SlashPos);
315 FrameworkName += ".framework/";
316
317 llvm::StringMapEntry<const DirectoryEntry *> &CacheLookup =
318 FrameworkMap.GetOrCreateValue(FilenameStart, SlashPos);
319
320 // Some other location?
321 if (CacheLookup.getValue() &&
322 CacheLookup.getKeyLength() == FrameworkName.size() &&
323 memcmp(CacheLookup.getKeyData(), &FrameworkName[0],
324 CacheLookup.getKeyLength()) != 0)
325 return 0;
326
327 // Cache subframework.
328 if (CacheLookup.getValue() == 0) {
329 ++NumSubFrameworkLookups;
330
331 // If the framework dir doesn't exist, we fail.
332 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName.begin(),
333 FrameworkName.end());
334 if (Dir == 0) return 0;
335
336 // Otherwise, if it does, remember that this is the right direntry for this
337 // framework.
338 CacheLookup.setValue(Dir);
339 }
340
341 const FileEntry *FE = 0;
342
343 // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
344 llvm::SmallString<1024> HeadersFilename(FrameworkName);
345 HeadersFilename += "Headers/";
346 HeadersFilename.append(SlashPos+1, FilenameEnd);
347 if (!(FE = FileMgr.getFile(HeadersFilename.begin(),
348 HeadersFilename.end()))) {
349
350 // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
351 HeadersFilename = FrameworkName;
352 HeadersFilename += "PrivateHeaders/";
353 HeadersFilename.append(SlashPos+1, FilenameEnd);
354 if (!(FE = FileMgr.getFile(HeadersFilename.begin(), HeadersFilename.end())))
355 return 0;
356 }
357
358 // This file is a system header or C++ unfriendly if the old file is.
359 getFileInfo(FE).DirInfo = getFileInfo(ContextFileEnt).DirInfo;
360 return FE;
361}
362
363//===----------------------------------------------------------------------===//
364// File Info Management.
365//===----------------------------------------------------------------------===//
366
367
368/// getFileInfo - Return the PerFileInfo structure for the specified
369/// FileEntry.
370HeaderSearch::PerFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) {
371 if (FE->getUID() >= FileInfo.size())
372 FileInfo.resize(FE->getUID()+1);
373 return FileInfo[FE->getUID()];
374}
375
376/// ShouldEnterIncludeFile - Mark the specified file as a target of of a
377/// #include, #include_next, or #import directive. Return false if #including
378/// the file will have no effect or true if we should include it.
379bool HeaderSearch::ShouldEnterIncludeFile(const FileEntry *File, bool isImport){
380 ++NumIncluded; // Count # of attempted #includes.
381
382 // Get information about this file.
383 PerFileInfo &FileInfo = getFileInfo(File);
384
385 // If this is a #import directive, check that we have not already imported
386 // this header.
387 if (isImport) {
388 // If this has already been imported, don't import it again.
389 FileInfo.isImport = true;
390
391 // Has this already been #import'ed or #include'd?
392 if (FileInfo.NumIncludes) return false;
393 } else {
394 // Otherwise, if this is a #include of a file that was previously #import'd
395 // or if this is the second #include of a #pragma once file, ignore it.
396 if (FileInfo.isImport)
397 return false;
398 }
399
400 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
401 // if the macro that guards it is defined, we know the #include has no effect.
Chris Lattner4826cbc2007-10-07 07:57:27 +0000402 if (FileInfo.ControllingMacro &&
403 FileInfo.ControllingMacro->hasMacroDefinition()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000404 ++NumMultiIncludeFileOptzn;
405 return false;
406 }
407
408 // Increment the number of times this file has been included.
409 ++FileInfo.NumIncludes;
410
411 return true;
412}
413
414