blob: 719b9fb9c689c8a72c76dd00ac2bc415b13471ce [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +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
Reid Spencer5f016e22007-07-11 17:01:13 +000014#include "clang/Lex/HeaderSearch.h"
Chris Lattnerc7229c32007-10-07 08:58:51 +000015#include "clang/Basic/FileManager.h"
16#include "clang/Basic/IdentifierTable.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000017#include "llvm/System/Path.h"
18#include "llvm/ADT/SmallString.h"
19using namespace clang;
20
21HeaderSearch::HeaderSearch(FileManager &FM) : FileMgr(FM), FrameworkMap(64) {
22 SystemDirIdx = 0;
23 NoCurDirSearch = false;
24
25 NumIncluded = 0;
26 NumMultiIncludeFileOptzn = 0;
27 NumFrameworkLookups = NumSubFrameworkLookups = 0;
28}
29
30void HeaderSearch::PrintStats() {
31 fprintf(stderr, "\n*** HeaderSearch Stats:\n");
32 fprintf(stderr, "%d files tracked.\n", (int)FileInfo.size());
33 unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0;
34 for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) {
35 NumOnceOnlyFiles += FileInfo[i].isImport;
36 if (MaxNumIncludes < FileInfo[i].NumIncludes)
37 MaxNumIncludes = FileInfo[i].NumIncludes;
38 NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1;
39 }
40 fprintf(stderr, " %d #import/#pragma once files.\n", NumOnceOnlyFiles);
41 fprintf(stderr, " %d included exactly once.\n", NumSingleIncludedFiles);
42 fprintf(stderr, " %d max times a file is included.\n", MaxNumIncludes);
43
44 fprintf(stderr, " %d #include/#include_next/#import.\n", NumIncluded);
45 fprintf(stderr, " %d #includes skipped due to"
46 " the multi-include optimization.\n", NumMultiIncludeFileOptzn);
47
48 fprintf(stderr, "%d framework lookups.\n", NumFrameworkLookups);
49 fprintf(stderr, "%d subframework lookups.\n", NumSubFrameworkLookups);
50}
51
52//===----------------------------------------------------------------------===//
53// Header File Location.
54//===----------------------------------------------------------------------===//
55
56const FileEntry *HeaderSearch::DoFrameworkLookup(const DirectoryEntry *Dir,
57 const char *FilenameStart,
58 const char *FilenameEnd) {
59 // Framework names must have a '/' in the filename.
60 const char *SlashPos = std::find(FilenameStart, FilenameEnd, '/');
61 if (SlashPos == FilenameEnd) return 0;
62
63 llvm::StringMapEntry<const DirectoryEntry *> &CacheLookup =
64 FrameworkMap.GetOrCreateValue(FilenameStart, SlashPos);
65
66 // If it is some other directory, fail.
67 if (CacheLookup.getValue() && CacheLookup.getValue() != Dir)
68 return 0;
69
70 // FrameworkName = "/System/Library/Frameworks/"
71 llvm::SmallString<1024> FrameworkName;
72 FrameworkName += Dir->getName();
73 if (FrameworkName.empty() || FrameworkName.back() != '/')
74 FrameworkName.push_back('/');
75
76 // FrameworkName = "/System/Library/Frameworks/Cocoa"
77 FrameworkName.append(FilenameStart, SlashPos);
78
79 // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/"
80 FrameworkName += ".framework/";
81
82 if (CacheLookup.getValue() == 0) {
83 ++NumFrameworkLookups;
84
85 // If the framework dir doesn't exist, we fail.
86 if (!llvm::sys::Path(std::string(FrameworkName.begin(),
87 FrameworkName.end())).exists())
88 return 0;
89
90 // Otherwise, if it does, remember that this is the right direntry for this
91 // framework.
92 CacheLookup.setValue(Dir);
93 }
94
95 // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"
96 unsigned OrigSize = FrameworkName.size();
97
98 FrameworkName += "Headers/";
99 FrameworkName.append(SlashPos+1, FilenameEnd);
100 if (const FileEntry *FE = FileMgr.getFile(FrameworkName.begin(),
101 FrameworkName.end())) {
102 return FE;
103 }
104
105 // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"
106 const char *Private = "Private";
107 FrameworkName.insert(FrameworkName.begin()+OrigSize, Private,
108 Private+strlen(Private));
109 return FileMgr.getFile(FrameworkName.begin(), FrameworkName.end());
110}
111
112/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
113/// return null on failure. isAngled indicates whether the file reference is
114/// for system #include's or not (i.e. using <> instead of ""). CurFileEnt, if
115/// non-null, indicates where the #including file is, in case a relative search
116/// is needed.
117const FileEntry *HeaderSearch::LookupFile(const char *FilenameStart,
118 const char *FilenameEnd,
119 bool isAngled,
120 const DirectoryLookup *FromDir,
121 const DirectoryLookup *&CurDir,
122 const FileEntry *CurFileEnt) {
123 // If 'Filename' is absolute, check to see if it exists and no searching.
124 // FIXME: Portability. This should be a sys::Path interface, this doesn't
125 // handle things like C:\foo.txt right, nor win32 \\network\device\blah.
126 if (FilenameStart[0] == '/') {
127 CurDir = 0;
128
129 // If this was an #include_next "/absolute/file", fail.
130 if (FromDir) return 0;
131
132 // Otherwise, just return the file.
133 return FileMgr.getFile(FilenameStart, FilenameEnd);
134 }
135
136 llvm::SmallString<1024> TmpDir;
137
138 // Step #0, unless disabled, check to see if the file is in the #includer's
139 // directory. This search is not done for <> headers.
140 if (CurFileEnt && !isAngled && !NoCurDirSearch) {
141 // Concatenate the requested file onto the directory.
142 // FIXME: Portability. Filename concatenation should be in sys::Path.
143 TmpDir += CurFileEnt->getDir()->getName();
144 TmpDir.push_back('/');
145 TmpDir.append(FilenameStart, FilenameEnd);
146 if (const FileEntry *FE = FileMgr.getFile(TmpDir.begin(), TmpDir.end())) {
147 // Leave CurDir unset.
148
149 // This file is a system header or C++ unfriendly if the old file is.
150 getFileInfo(FE).DirInfo = getFileInfo(CurFileEnt).DirInfo;
151 return FE;
152 }
153 TmpDir.clear();
154 }
155
156 CurDir = 0;
157
158 // If this is a system #include, ignore the user #include locs.
159 unsigned i = isAngled ? SystemDirIdx : 0;
160
161 // If this is a #include_next request, start searching after the directory the
162 // file was found in.
163 if (FromDir)
164 i = FromDir-&SearchDirs[0];
165
Chris Lattner9960ae82007-07-22 07:28:00 +0000166 // Cache all of the lookups performed by this method. Many headers are
167 // multiply included, and the "pragma once" optimization prevents them from
168 // being relex/pp'd, but they would still have to search through a
169 // (potentially huge) series of SearchDirs to find it.
170 std::pair<unsigned, unsigned> &CacheLookup =
171 LookupFileCache.GetOrCreateValue(FilenameStart, FilenameEnd).getValue();
172
173 // If the entry has been previously looked up, the first value will be
174 // non-zero. If the value is equal to i (the start point of our search), then
175 // this is a matching hit.
176 if (CacheLookup.first == i+1) {
177 // Skip querying potentially lots of directories for this lookup.
178 i = CacheLookup.second;
179 } else {
180 // Otherwise, this is the first query, or the previous query didn't match
181 // our search start. We will fill in our found location below, so prime the
182 // start point value.
183 CacheLookup.first = i+1;
184 }
185
Reid Spencer5f016e22007-07-11 17:01:13 +0000186 // Check each directory in sequence to see if it contains this file.
187 for (; i != SearchDirs.size(); ++i) {
188 const FileEntry *FE = 0;
189 if (!SearchDirs[i].isFramework()) {
190 // FIXME: Portability. Adding file to dir should be in sys::Path.
191 // Concatenate the requested file onto the directory.
192 TmpDir.clear();
193 TmpDir += SearchDirs[i].getDir()->getName();
194 TmpDir.push_back('/');
195 TmpDir.append(FilenameStart, FilenameEnd);
196 FE = FileMgr.getFile(TmpDir.begin(), TmpDir.end());
197 } else {
198 FE = DoFrameworkLookup(SearchDirs[i].getDir(), FilenameStart,FilenameEnd);
199 }
200
201 if (FE) {
202 CurDir = &SearchDirs[i];
203
204 // This file is a system header or C++ unfriendly if the dir is.
205 getFileInfo(FE).DirInfo = CurDir->getDirCharacteristic();
Chris Lattner9960ae82007-07-22 07:28:00 +0000206
207 // Remember this location for the next lookup we do.
208 CacheLookup.second = i;
Reid Spencer5f016e22007-07-11 17:01:13 +0000209 return FE;
210 }
211 }
212
Chris Lattner9960ae82007-07-22 07:28:00 +0000213 // Otherwise, didn't find it. Remember we didn't find this.
214 CacheLookup.second = SearchDirs.size();
Reid Spencer5f016e22007-07-11 17:01:13 +0000215 return 0;
216}
217
218/// LookupSubframeworkHeader - Look up a subframework for the specified
219/// #include file. For example, if #include'ing <HIToolbox/HIToolbox.h> from
220/// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
221/// is a subframework within Carbon.framework. If so, return the FileEntry
222/// for the designated file, otherwise return null.
223const FileEntry *HeaderSearch::
224LookupSubframeworkHeader(const char *FilenameStart,
225 const char *FilenameEnd,
226 const FileEntry *ContextFileEnt) {
227 // Framework names must have a '/' in the filename. Find it.
228 const char *SlashPos = std::find(FilenameStart, FilenameEnd, '/');
229 if (SlashPos == FilenameEnd) return 0;
230
231 // Look up the base framework name of the ContextFileEnt.
232 const char *ContextName = ContextFileEnt->getName();
233
234 // If the context info wasn't a framework, couldn't be a subframework.
235 const char *FrameworkPos = strstr(ContextName, ".framework/");
236 if (FrameworkPos == 0)
237 return 0;
238
239 llvm::SmallString<1024> FrameworkName(ContextName,
240 FrameworkPos+strlen(".framework/"));
241
242 // Append Frameworks/HIToolbox.framework/
243 FrameworkName += "Frameworks/";
244 FrameworkName.append(FilenameStart, SlashPos);
245 FrameworkName += ".framework/";
246
247 llvm::StringMapEntry<const DirectoryEntry *> &CacheLookup =
248 FrameworkMap.GetOrCreateValue(FilenameStart, SlashPos);
249
250 // Some other location?
251 if (CacheLookup.getValue() &&
252 CacheLookup.getKeyLength() == FrameworkName.size() &&
253 memcmp(CacheLookup.getKeyData(), &FrameworkName[0],
254 CacheLookup.getKeyLength()) != 0)
255 return 0;
256
257 // Cache subframework.
258 if (CacheLookup.getValue() == 0) {
259 ++NumSubFrameworkLookups;
260
261 // If the framework dir doesn't exist, we fail.
262 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName.begin(),
263 FrameworkName.end());
264 if (Dir == 0) return 0;
265
266 // Otherwise, if it does, remember that this is the right direntry for this
267 // framework.
268 CacheLookup.setValue(Dir);
269 }
270
271 const FileEntry *FE = 0;
272
273 // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
274 llvm::SmallString<1024> HeadersFilename(FrameworkName);
275 HeadersFilename += "Headers/";
276 HeadersFilename.append(SlashPos+1, FilenameEnd);
277 if (!(FE = FileMgr.getFile(HeadersFilename.begin(),
278 HeadersFilename.end()))) {
279
280 // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
281 HeadersFilename = FrameworkName;
282 HeadersFilename += "PrivateHeaders/";
283 HeadersFilename.append(SlashPos+1, FilenameEnd);
284 if (!(FE = FileMgr.getFile(HeadersFilename.begin(), HeadersFilename.end())))
285 return 0;
286 }
287
288 // This file is a system header or C++ unfriendly if the old file is.
289 getFileInfo(FE).DirInfo = getFileInfo(ContextFileEnt).DirInfo;
290 return FE;
291}
292
293//===----------------------------------------------------------------------===//
294// File Info Management.
295//===----------------------------------------------------------------------===//
296
297
298/// getFileInfo - Return the PerFileInfo structure for the specified
299/// FileEntry.
300HeaderSearch::PerFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) {
301 if (FE->getUID() >= FileInfo.size())
302 FileInfo.resize(FE->getUID()+1);
303 return FileInfo[FE->getUID()];
304}
305
306/// ShouldEnterIncludeFile - Mark the specified file as a target of of a
307/// #include, #include_next, or #import directive. Return false if #including
308/// the file will have no effect or true if we should include it.
309bool HeaderSearch::ShouldEnterIncludeFile(const FileEntry *File, bool isImport){
310 ++NumIncluded; // Count # of attempted #includes.
311
312 // Get information about this file.
313 PerFileInfo &FileInfo = getFileInfo(File);
314
315 // If this is a #import directive, check that we have not already imported
316 // this header.
317 if (isImport) {
318 // If this has already been imported, don't import it again.
319 FileInfo.isImport = true;
320
321 // Has this already been #import'ed or #include'd?
322 if (FileInfo.NumIncludes) return false;
323 } else {
324 // Otherwise, if this is a #include of a file that was previously #import'd
325 // or if this is the second #include of a #pragma once file, ignore it.
326 if (FileInfo.isImport)
327 return false;
328 }
329
330 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
331 // if the macro that guards it is defined, we know the #include has no effect.
Chris Lattner9c46de42007-10-07 07:57:27 +0000332 if (FileInfo.ControllingMacro &&
333 FileInfo.ControllingMacro->hasMacroDefinition()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000334 ++NumMultiIncludeFileOptzn;
335 return false;
336 }
337
338 // Increment the number of times this file has been included.
339 ++FileInfo.NumIncludes;
340
341 return true;
342}
343
344