]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Lex/HeaderSearch.cpp
Upgrade to OpenSSH 5.8p2.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Lex / HeaderSearch.cpp
1 //===--- HeaderSearch.cpp - Resolve Header File Locations ---===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements the DirectoryLookup and HeaderSearch interfaces.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "clang/Lex/HeaderSearch.h"
15 #include "clang/Lex/HeaderMap.h"
16 #include "clang/Basic/FileManager.h"
17 #include "clang/Basic/IdentifierTable.h"
18 #include "llvm/Support/FileSystem.h"
19 #include "llvm/Support/Path.h"
20 #include "llvm/ADT/SmallString.h"
21 #include <cstdio>
22 using namespace clang;
23
24 const IdentifierInfo *
25 HeaderFileInfo::getControllingMacro(ExternalIdentifierLookup *External) {
26   if (ControllingMacro)
27     return ControllingMacro;
28
29   if (!ControllingMacroID || !External)
30     return 0;
31
32   ControllingMacro = External->GetIdentifier(ControllingMacroID);
33   return ControllingMacro;
34 }
35
36 ExternalHeaderFileInfoSource::~ExternalHeaderFileInfoSource() {}
37
38 HeaderSearch::HeaderSearch(FileManager &FM)
39     : FileMgr(FM), FrameworkMap(64) {
40   SystemDirIdx = 0;
41   NoCurDirSearch = false;
42
43   ExternalLookup = 0;
44   ExternalSource = 0;
45   NumIncluded = 0;
46   NumMultiIncludeFileOptzn = 0;
47   NumFrameworkLookups = NumSubFrameworkLookups = 0;
48 }
49
50 HeaderSearch::~HeaderSearch() {
51   // Delete headermaps.
52   for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
53     delete HeaderMaps[i].second;
54 }
55
56 void HeaderSearch::PrintStats() {
57   fprintf(stderr, "\n*** HeaderSearch Stats:\n");
58   fprintf(stderr, "%d files tracked.\n", (int)FileInfo.size());
59   unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0;
60   for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) {
61     NumOnceOnlyFiles += FileInfo[i].isImport;
62     if (MaxNumIncludes < FileInfo[i].NumIncludes)
63       MaxNumIncludes = FileInfo[i].NumIncludes;
64     NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1;
65   }
66   fprintf(stderr, "  %d #import/#pragma once files.\n", NumOnceOnlyFiles);
67   fprintf(stderr, "  %d included exactly once.\n", NumSingleIncludedFiles);
68   fprintf(stderr, "  %d max times a file is included.\n", MaxNumIncludes);
69
70   fprintf(stderr, "  %d #include/#include_next/#import.\n", NumIncluded);
71   fprintf(stderr, "    %d #includes skipped due to"
72           " the multi-include optimization.\n", NumMultiIncludeFileOptzn);
73
74   fprintf(stderr, "%d framework lookups.\n", NumFrameworkLookups);
75   fprintf(stderr, "%d subframework lookups.\n", NumSubFrameworkLookups);
76 }
77
78 /// CreateHeaderMap - This method returns a HeaderMap for the specified
79 /// FileEntry, uniquing them through the the 'HeaderMaps' datastructure.
80 const HeaderMap *HeaderSearch::CreateHeaderMap(const FileEntry *FE) {
81   // We expect the number of headermaps to be small, and almost always empty.
82   // If it ever grows, use of a linear search should be re-evaluated.
83   if (!HeaderMaps.empty()) {
84     for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
85       // Pointer equality comparison of FileEntries works because they are
86       // already uniqued by inode.
87       if (HeaderMaps[i].first == FE)
88         return HeaderMaps[i].second;
89   }
90
91   if (const HeaderMap *HM = HeaderMap::Create(FE, FileMgr)) {
92     HeaderMaps.push_back(std::make_pair(FE, HM));
93     return HM;
94   }
95
96   return 0;
97 }
98
99 //===----------------------------------------------------------------------===//
100 // File lookup within a DirectoryLookup scope
101 //===----------------------------------------------------------------------===//
102
103 /// getName - Return the directory or filename corresponding to this lookup
104 /// object.
105 const char *DirectoryLookup::getName() const {
106   if (isNormalDir())
107     return getDir()->getName();
108   if (isFramework())
109     return getFrameworkDir()->getName();
110   assert(isHeaderMap() && "Unknown DirectoryLookup");
111   return getHeaderMap()->getFileName();
112 }
113
114
115 /// LookupFile - Lookup the specified file in this search path, returning it
116 /// if it exists or returning null if not.
117 const FileEntry *DirectoryLookup::LookupFile(
118     llvm::StringRef Filename,
119     HeaderSearch &HS,
120     llvm::SmallVectorImpl<char> *SearchPath,
121     llvm::SmallVectorImpl<char> *RelativePath) const {
122   llvm::SmallString<1024> TmpDir;
123   if (isNormalDir()) {
124     // Concatenate the requested file onto the directory.
125     // FIXME: Portability.  Filename concatenation should be in sys::Path.
126     TmpDir += getDir()->getName();
127     TmpDir.push_back('/');
128     TmpDir.append(Filename.begin(), Filename.end());
129     if (SearchPath != NULL) {
130       llvm::StringRef SearchPathRef(getDir()->getName());
131       SearchPath->clear();
132       SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
133     }
134     if (RelativePath != NULL) {
135       RelativePath->clear();
136       RelativePath->append(Filename.begin(), Filename.end());
137     }
138     return HS.getFileMgr().getFile(TmpDir.str(), /*openFile=*/true);
139   }
140
141   if (isFramework())
142     return DoFrameworkLookup(Filename, HS, SearchPath, RelativePath);
143
144   assert(isHeaderMap() && "Unknown directory lookup");
145   const FileEntry * const Result = getHeaderMap()->LookupFile(
146       Filename, HS.getFileMgr());
147   if (Result) {
148     if (SearchPath != NULL) {
149       llvm::StringRef SearchPathRef(getName());
150       SearchPath->clear();
151       SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
152     }
153     if (RelativePath != NULL) {
154       RelativePath->clear();
155       RelativePath->append(Filename.begin(), Filename.end());
156     }
157   }
158   return Result;
159 }
160
161
162 /// DoFrameworkLookup - Do a lookup of the specified file in the current
163 /// DirectoryLookup, which is a framework directory.
164 const FileEntry *DirectoryLookup::DoFrameworkLookup(
165     llvm::StringRef Filename,
166     HeaderSearch &HS,
167     llvm::SmallVectorImpl<char> *SearchPath,
168     llvm::SmallVectorImpl<char> *RelativePath) const {
169   FileManager &FileMgr = HS.getFileMgr();
170
171   // Framework names must have a '/' in the filename.
172   size_t SlashPos = Filename.find('/');
173   if (SlashPos == llvm::StringRef::npos) return 0;
174
175   // Find out if this is the home for the specified framework, by checking
176   // HeaderSearch.  Possible answer are yes/no and unknown.
177   const DirectoryEntry *&FrameworkDirCache =
178     HS.LookupFrameworkCache(Filename.substr(0, SlashPos));
179
180   // If it is known and in some other directory, fail.
181   if (FrameworkDirCache && FrameworkDirCache != getFrameworkDir())
182     return 0;
183
184   // Otherwise, construct the path to this framework dir.
185
186   // FrameworkName = "/System/Library/Frameworks/"
187   llvm::SmallString<1024> FrameworkName;
188   FrameworkName += getFrameworkDir()->getName();
189   if (FrameworkName.empty() || FrameworkName.back() != '/')
190     FrameworkName.push_back('/');
191
192   // FrameworkName = "/System/Library/Frameworks/Cocoa"
193   FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos);
194
195   // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/"
196   FrameworkName += ".framework/";
197
198   // If the cache entry is still unresolved, query to see if the cache entry is
199   // still unresolved.  If so, check its existence now.
200   if (FrameworkDirCache == 0) {
201     HS.IncrementFrameworkLookupCount();
202
203     // If the framework dir doesn't exist, we fail.
204     // FIXME: It's probably more efficient to query this with FileMgr.getDir.
205     bool Exists;
206     if (llvm::sys::fs::exists(FrameworkName.str(), Exists) || !Exists)
207       return 0;
208
209     // Otherwise, if it does, remember that this is the right direntry for this
210     // framework.
211     FrameworkDirCache = getFrameworkDir();
212   }
213
214   if (RelativePath != NULL) {
215     RelativePath->clear();
216     RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
217   }
218
219   // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"
220   unsigned OrigSize = FrameworkName.size();
221
222   FrameworkName += "Headers/";
223
224   if (SearchPath != NULL) {
225     SearchPath->clear();
226     // Without trailing '/'.
227     SearchPath->append(FrameworkName.begin(), FrameworkName.end()-1);
228   }
229
230   FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end());
231   if (const FileEntry *FE = FileMgr.getFile(FrameworkName.str(),
232                                             /*openFile=*/true)) {
233     return FE;
234   }
235
236   // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"
237   const char *Private = "Private";
238   FrameworkName.insert(FrameworkName.begin()+OrigSize, Private,
239                        Private+strlen(Private));
240   if (SearchPath != NULL)
241     SearchPath->insert(SearchPath->begin()+OrigSize, Private,
242                        Private+strlen(Private));
243
244   return FileMgr.getFile(FrameworkName.str(), /*openFile=*/true);
245 }
246
247
248 //===----------------------------------------------------------------------===//
249 // Header File Location.
250 //===----------------------------------------------------------------------===//
251
252
253 /// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
254 /// return null on failure.  isAngled indicates whether the file reference is
255 /// for system #include's or not (i.e. using <> instead of "").  CurFileEnt, if
256 /// non-null, indicates where the #including file is, in case a relative search
257 /// is needed.
258 const FileEntry *HeaderSearch::LookupFile(
259     llvm::StringRef Filename,
260     bool isAngled,
261     const DirectoryLookup *FromDir,
262     const DirectoryLookup *&CurDir,
263     const FileEntry *CurFileEnt,
264     llvm::SmallVectorImpl<char> *SearchPath,
265     llvm::SmallVectorImpl<char> *RelativePath) {
266   // If 'Filename' is absolute, check to see if it exists and no searching.
267   if (llvm::sys::path::is_absolute(Filename)) {
268     CurDir = 0;
269
270     // If this was an #include_next "/absolute/file", fail.
271     if (FromDir) return 0;
272
273     if (SearchPath != NULL)
274       SearchPath->clear();
275     if (RelativePath != NULL) {
276       RelativePath->clear();
277       RelativePath->append(Filename.begin(), Filename.end());
278     }
279     // Otherwise, just return the file.
280     return FileMgr.getFile(Filename, /*openFile=*/true);
281   }
282
283   // Step #0, unless disabled, check to see if the file is in the #includer's
284   // directory.  This has to be based on CurFileEnt, not CurDir, because
285   // CurFileEnt could be a #include of a subdirectory (#include "foo/bar.h") and
286   // a subsequent include of "baz.h" should resolve to "whatever/foo/baz.h".
287   // This search is not done for <> headers.
288   if (CurFileEnt && !isAngled && !NoCurDirSearch) {
289     llvm::SmallString<1024> TmpDir;
290     // Concatenate the requested file onto the directory.
291     // FIXME: Portability.  Filename concatenation should be in sys::Path.
292     TmpDir += CurFileEnt->getDir()->getName();
293     TmpDir.push_back('/');
294     TmpDir.append(Filename.begin(), Filename.end());
295     if (const FileEntry *FE = FileMgr.getFile(TmpDir.str(),/*openFile=*/true)) {
296       // Leave CurDir unset.
297       // This file is a system header or C++ unfriendly if the old file is.
298       //
299       // Note that the temporary 'DirInfo' is required here, as either call to
300       // getFileInfo could resize the vector and we don't want to rely on order
301       // of evaluation.
302       unsigned DirInfo = getFileInfo(CurFileEnt).DirInfo;
303       getFileInfo(FE).DirInfo = DirInfo;
304       if (SearchPath != NULL) {
305         llvm::StringRef SearchPathRef(CurFileEnt->getDir()->getName());
306         SearchPath->clear();
307         SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
308       }
309       if (RelativePath != NULL) {
310         RelativePath->clear();
311         RelativePath->append(Filename.begin(), Filename.end());
312       }
313       return FE;
314     }
315   }
316
317   CurDir = 0;
318
319   // If this is a system #include, ignore the user #include locs.
320   unsigned i = isAngled ? SystemDirIdx : 0;
321
322   // If this is a #include_next request, start searching after the directory the
323   // file was found in.
324   if (FromDir)
325     i = FromDir-&SearchDirs[0];
326
327   // Cache all of the lookups performed by this method.  Many headers are
328   // multiply included, and the "pragma once" optimization prevents them from
329   // being relex/pp'd, but they would still have to search through a
330   // (potentially huge) series of SearchDirs to find it.
331   std::pair<unsigned, unsigned> &CacheLookup =
332     LookupFileCache.GetOrCreateValue(Filename).getValue();
333
334   // If the entry has been previously looked up, the first value will be
335   // non-zero.  If the value is equal to i (the start point of our search), then
336   // this is a matching hit.
337   if (CacheLookup.first == i+1) {
338     // Skip querying potentially lots of directories for this lookup.
339     i = CacheLookup.second;
340   } else {
341     // Otherwise, this is the first query, or the previous query didn't match
342     // our search start.  We will fill in our found location below, so prime the
343     // start point value.
344     CacheLookup.first = i+1;
345   }
346
347   // Check each directory in sequence to see if it contains this file.
348   for (; i != SearchDirs.size(); ++i) {
349     const FileEntry *FE =
350       SearchDirs[i].LookupFile(Filename, *this, SearchPath, RelativePath);
351     if (!FE) continue;
352
353     CurDir = &SearchDirs[i];
354
355     // This file is a system header or C++ unfriendly if the dir is.
356     getFileInfo(FE).DirInfo = CurDir->getDirCharacteristic();
357
358     // Remember this location for the next lookup we do.
359     CacheLookup.second = i;
360     return FE;
361   }
362
363   // Otherwise, didn't find it. Remember we didn't find this.
364   CacheLookup.second = SearchDirs.size();
365   return 0;
366 }
367
368 /// LookupSubframeworkHeader - Look up a subframework for the specified
369 /// #include file.  For example, if #include'ing <HIToolbox/HIToolbox.h> from
370 /// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
371 /// is a subframework within Carbon.framework.  If so, return the FileEntry
372 /// for the designated file, otherwise return null.
373 const FileEntry *HeaderSearch::
374 LookupSubframeworkHeader(llvm::StringRef Filename,
375                          const FileEntry *ContextFileEnt,
376                          llvm::SmallVectorImpl<char> *SearchPath,
377                          llvm::SmallVectorImpl<char> *RelativePath) {
378   assert(ContextFileEnt && "No context file?");
379
380   // Framework names must have a '/' in the filename.  Find it.
381   size_t SlashPos = Filename.find('/');
382   if (SlashPos == llvm::StringRef::npos) return 0;
383
384   // Look up the base framework name of the ContextFileEnt.
385   const char *ContextName = ContextFileEnt->getName();
386
387   // If the context info wasn't a framework, couldn't be a subframework.
388   const char *FrameworkPos = strstr(ContextName, ".framework/");
389   if (FrameworkPos == 0)
390     return 0;
391
392   llvm::SmallString<1024> FrameworkName(ContextName,
393                                         FrameworkPos+strlen(".framework/"));
394
395   // Append Frameworks/HIToolbox.framework/
396   FrameworkName += "Frameworks/";
397   FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos);
398   FrameworkName += ".framework/";
399
400   llvm::StringMapEntry<const DirectoryEntry *> &CacheLookup =
401     FrameworkMap.GetOrCreateValue(Filename.substr(0, SlashPos));
402
403   // Some other location?
404   if (CacheLookup.getValue() &&
405       CacheLookup.getKeyLength() == FrameworkName.size() &&
406       memcmp(CacheLookup.getKeyData(), &FrameworkName[0],
407              CacheLookup.getKeyLength()) != 0)
408     return 0;
409
410   // Cache subframework.
411   if (CacheLookup.getValue() == 0) {
412     ++NumSubFrameworkLookups;
413
414     // If the framework dir doesn't exist, we fail.
415     const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName.str());
416     if (Dir == 0) return 0;
417
418     // Otherwise, if it does, remember that this is the right direntry for this
419     // framework.
420     CacheLookup.setValue(Dir);
421   }
422
423   const FileEntry *FE = 0;
424
425   if (RelativePath != NULL) {
426     RelativePath->clear();
427     RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
428   }
429
430   // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
431   llvm::SmallString<1024> HeadersFilename(FrameworkName);
432   HeadersFilename += "Headers/";
433   if (SearchPath != NULL) {
434     SearchPath->clear();
435     // Without trailing '/'.
436     SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
437   }
438
439   HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
440   if (!(FE = FileMgr.getFile(HeadersFilename.str(), /*openFile=*/true))) {
441
442     // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
443     HeadersFilename = FrameworkName;
444     HeadersFilename += "PrivateHeaders/";
445     if (SearchPath != NULL) {
446       SearchPath->clear();
447       // Without trailing '/'.
448       SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
449     }
450
451     HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
452     if (!(FE = FileMgr.getFile(HeadersFilename.str(), /*openFile=*/true)))
453       return 0;
454   }
455
456   // This file is a system header or C++ unfriendly if the old file is.
457   //
458   // Note that the temporary 'DirInfo' is required here, as either call to
459   // getFileInfo could resize the vector and we don't want to rely on order
460   // of evaluation.
461   unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo;
462   getFileInfo(FE).DirInfo = DirInfo;
463   return FE;
464 }
465
466 //===----------------------------------------------------------------------===//
467 // File Info Management.
468 //===----------------------------------------------------------------------===//
469
470
471 /// getFileInfo - Return the HeaderFileInfo structure for the specified
472 /// FileEntry.
473 HeaderFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) {
474   if (FE->getUID() >= FileInfo.size())
475     FileInfo.resize(FE->getUID()+1);
476   
477   HeaderFileInfo &HFI = FileInfo[FE->getUID()];
478   if (ExternalSource && !HFI.Resolved) {
479     HFI = ExternalSource->GetHeaderFileInfo(FE);
480     HFI.Resolved = true;
481   }
482   return HFI;
483 }
484
485 void HeaderSearch::setHeaderFileInfoForUID(HeaderFileInfo HFI, unsigned UID) {
486   if (UID >= FileInfo.size())
487     FileInfo.resize(UID+1);
488   HFI.Resolved = true;
489   FileInfo[UID] = HFI;
490 }
491
492 /// ShouldEnterIncludeFile - Mark the specified file as a target of of a
493 /// #include, #include_next, or #import directive.  Return false if #including
494 /// the file will have no effect or true if we should include it.
495 bool HeaderSearch::ShouldEnterIncludeFile(const FileEntry *File, bool isImport){
496   ++NumIncluded; // Count # of attempted #includes.
497
498   // Get information about this file.
499   HeaderFileInfo &FileInfo = getFileInfo(File);
500
501   // If this is a #import directive, check that we have not already imported
502   // this header.
503   if (isImport) {
504     // If this has already been imported, don't import it again.
505     FileInfo.isImport = true;
506
507     // Has this already been #import'ed or #include'd?
508     if (FileInfo.NumIncludes) return false;
509   } else {
510     // Otherwise, if this is a #include of a file that was previously #import'd
511     // or if this is the second #include of a #pragma once file, ignore it.
512     if (FileInfo.isImport)
513       return false;
514   }
515
516   // Next, check to see if the file is wrapped with #ifndef guards.  If so, and
517   // if the macro that guards it is defined, we know the #include has no effect.
518   if (const IdentifierInfo *ControllingMacro
519       = FileInfo.getControllingMacro(ExternalLookup))
520     if (ControllingMacro->hasMacroDefinition()) {
521       ++NumMultiIncludeFileOptzn;
522       return false;
523     }
524
525   // Increment the number of times this file has been included.
526   ++FileInfo.NumIncludes;
527
528   return true;
529 }
530
531