HeaderSearch.h revision 65e02fa80e1c185f18e5f81cefc30d75383a7301
1//===--- HeaderSearch.h - Resolve Header File Locations ---------*- C++ -*-===//
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 defines the HeaderSearch interface.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_LEX_HEADERSEARCH_H
15#define LLVM_CLANG_LEX_HEADERSEARCH_H
16
17#include "clang/Lex/DirectoryLookup.h"
18#include "llvm/ADT/StringMap.h"
19#include "llvm/ADT/StringSet.h"
20#include "llvm/Support/Allocator.h"
21#include <vector>
22
23namespace clang {
24
25class ExternalIdentifierLookup;
26class FileEntry;
27class FileManager;
28class IdentifierInfo;
29
30/// HeaderFileInfo - The preprocessor keeps track of this information for each
31/// file that is #included.
32struct HeaderFileInfo {
33  /// isImport - True if this is a #import'd or #pragma once file.
34  unsigned isImport : 1;
35
36  /// isPragmaOnce - True if this is  #pragma once file.
37  unsigned isPragmaOnce : 1;
38
39  /// DirInfo - Keep track of whether this is a system header, and if so,
40  /// whether it is C++ clean or not.  This can be set by the include paths or
41  /// by #pragma gcc system_header.  This is an instance of
42  /// SrcMgr::CharacteristicKind.
43  unsigned DirInfo : 2;
44
45  /// \brief Whether this header file info was supplied by an external source.
46  unsigned External : 1;
47
48  /// \brief Whether this structure is considered to already have been
49  /// "resolved", meaning that it was loaded from the external source.
50  unsigned Resolved : 1;
51
52  /// \brief Whether this is a header inside a framework that is currently
53  /// being built.
54  ///
55  /// When a framework is being built, the headers have not yet been placed
56  /// into the appropriate framework subdirectories, and therefore are
57  /// provided via a header map. This bit indicates when this is one of
58  /// those framework headers.
59  unsigned IndexHeaderMapHeader : 1;
60
61  /// NumIncludes - This is the number of times the file has been included
62  /// already.
63  unsigned short NumIncludes;
64
65  /// \brief The ID number of the controlling macro.
66  ///
67  /// This ID number will be non-zero when there is a controlling
68  /// macro whose IdentifierInfo may not yet have been loaded from
69  /// external storage.
70  unsigned ControllingMacroID;
71
72  /// ControllingMacro - If this file has a #ifndef XXX (or equivalent) guard
73  /// that protects the entire contents of the file, this is the identifier
74  /// for the macro that controls whether or not it has any effect.
75  ///
76  /// Note: Most clients should use getControllingMacro() to access
77  /// the controlling macro of this header, since
78  /// getControllingMacro() is able to load a controlling macro from
79  /// external storage.
80  const IdentifierInfo *ControllingMacro;
81
82  /// \brief If this header came from a framework include, this is the name
83  /// of the framework.
84  StringRef Framework;
85
86  HeaderFileInfo()
87    : isImport(false), isPragmaOnce(false), DirInfo(SrcMgr::C_User),
88      External(false), Resolved(false), IndexHeaderMapHeader(false),
89      NumIncludes(0), ControllingMacroID(0), ControllingMacro(0)  {}
90
91  /// \brief Retrieve the controlling macro for this header file, if
92  /// any.
93  const IdentifierInfo *getControllingMacro(ExternalIdentifierLookup *External);
94
95  /// \brief Determine whether this is a non-default header file info, e.g.,
96  /// it corresponds to an actual header we've included or tried to include.
97  bool isNonDefault() const {
98    return isImport || isPragmaOnce || NumIncludes || ControllingMacro ||
99      ControllingMacroID;
100  }
101};
102
103/// \brief An external source of header file information, which may supply
104/// information about header files already included.
105class ExternalHeaderFileInfoSource {
106public:
107  virtual ~ExternalHeaderFileInfoSource();
108
109  /// \brief Retrieve the header file information for the given file entry.
110  ///
111  /// \returns Header file information for the given file entry, with the
112  /// \c External bit set. If the file entry is not known, return a
113  /// default-constructed \c HeaderFileInfo.
114  virtual HeaderFileInfo GetHeaderFileInfo(const FileEntry *FE) = 0;
115};
116
117/// HeaderSearch - This class encapsulates the information needed to find the
118/// file referenced by a #include or #include_next, (sub-)framework lookup, etc.
119class HeaderSearch {
120  FileManager &FileMgr;
121  /// #include search path information.  Requests for #include "x" search the
122  /// directory of the #including file first, then each directory in SearchDirs
123  /// consecutively. Requests for <x> search the current dir first, then each
124  /// directory in SearchDirs, starting at AngledDirIdx, consecutively.  If
125  /// NoCurDirSearch is true, then the check for the file in the current
126  /// directory is suppressed.
127  std::vector<DirectoryLookup> SearchDirs;
128  unsigned AngledDirIdx;
129  unsigned SystemDirIdx;
130  bool NoCurDirSearch;
131
132  /// FileInfo - This contains all of the preprocessor-specific data about files
133  /// that are included.  The vector is indexed by the FileEntry's UID.
134  ///
135  std::vector<HeaderFileInfo> FileInfo;
136
137  /// LookupFileCache - This is keeps track of each lookup performed by
138  /// LookupFile.  The first part of the value is the starting index in
139  /// SearchDirs that the cached search was performed from.  If there is a hit
140  /// and this value doesn't match the current query, the cache has to be
141  /// ignored.  The second value is the entry in SearchDirs that satisfied the
142  /// query.
143  llvm::StringMap<std::pair<unsigned, unsigned>, llvm::BumpPtrAllocator>
144    LookupFileCache;
145
146
147  /// FrameworkMap - This is a collection mapping a framework or subframework
148  /// name like "Carbon" to the Carbon.framework directory.
149  llvm::StringMap<const DirectoryEntry *, llvm::BumpPtrAllocator>
150    FrameworkMap;
151
152  /// HeaderMaps - This is a mapping from FileEntry -> HeaderMap, uniquing
153  /// headermaps.  This vector owns the headermap.
154  std::vector<std::pair<const FileEntry*, const HeaderMap*> > HeaderMaps;
155
156  /// \brief Uniqued set of framework names, which is used to track which
157  /// headers were included as framework headers.
158  llvm::StringSet<llvm::BumpPtrAllocator> FrameworkNames;
159
160  /// \brief Entity used to resolve the identifier IDs of controlling
161  /// macros into IdentifierInfo pointers, as needed.
162  ExternalIdentifierLookup *ExternalLookup;
163
164  /// \brief Entity used to look up stored header file information.
165  ExternalHeaderFileInfoSource *ExternalSource;
166
167  // Various statistics we track for performance analysis.
168  unsigned NumIncluded;
169  unsigned NumMultiIncludeFileOptzn;
170  unsigned NumFrameworkLookups, NumSubFrameworkLookups;
171
172  // HeaderSearch doesn't support default or copy construction.
173  explicit HeaderSearch();
174  explicit HeaderSearch(const HeaderSearch&);
175  void operator=(const HeaderSearch&);
176public:
177  HeaderSearch(FileManager &FM);
178  ~HeaderSearch();
179
180  FileManager &getFileMgr() const { return FileMgr; }
181
182  /// SetSearchPaths - Interface for setting the file search paths.
183  ///
184  void SetSearchPaths(const std::vector<DirectoryLookup> &dirs,
185                      unsigned angledDirIdx, unsigned systemDirIdx,
186                      bool noCurDirSearch) {
187    assert(angledDirIdx <= systemDirIdx && systemDirIdx <= dirs.size() &&
188        "Directory indicies are unordered");
189    SearchDirs = dirs;
190    AngledDirIdx = angledDirIdx;
191    SystemDirIdx = systemDirIdx;
192    NoCurDirSearch = noCurDirSearch;
193    //LookupFileCache.clear();
194  }
195
196  /// ClearFileInfo - Forget everything we know about headers so far.
197  void ClearFileInfo() {
198    FileInfo.clear();
199  }
200
201  void SetExternalLookup(ExternalIdentifierLookup *EIL) {
202    ExternalLookup = EIL;
203  }
204
205  ExternalIdentifierLookup *getExternalLookup() const {
206    return ExternalLookup;
207  }
208
209  /// \brief Set the external source of header information.
210  void SetExternalSource(ExternalHeaderFileInfoSource *ES) {
211    ExternalSource = ES;
212  }
213
214  /// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
215  /// return null on failure.
216  ///
217  /// \returns If successful, this returns 'UsedDir', the DirectoryLookup member
218  /// the file was found in, or null if not applicable.
219  ///
220  /// \param isAngled indicates whether the file reference is a <> reference.
221  ///
222  /// \param CurDir If non-null, the file was found in the specified directory
223  /// search location.  This is used to implement #include_next.
224  ///
225  /// \param CurFileEnt If non-null, indicates where the #including file is, in
226  /// case a relative search is needed.
227  ///
228  /// \param SearchPath If non-null, will be set to the search path relative
229  /// to which the file was found. If the include path is absolute, SearchPath
230  /// will be set to an empty string.
231  ///
232  /// \param RelativePath If non-null, will be set to the path relative to
233  /// SearchPath at which the file was found. This only differs from the
234  /// Filename for framework includes.
235  const FileEntry *LookupFile(StringRef Filename, bool isAngled,
236                              const DirectoryLookup *FromDir,
237                              const DirectoryLookup *&CurDir,
238                              const FileEntry *CurFileEnt,
239                              SmallVectorImpl<char> *SearchPath,
240                              SmallVectorImpl<char> *RelativePath);
241
242  /// LookupSubframeworkHeader - Look up a subframework for the specified
243  /// #include file.  For example, if #include'ing <HIToolbox/HIToolbox.h> from
244  /// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
245  /// is a subframework within Carbon.framework.  If so, return the FileEntry
246  /// for the designated file, otherwise return null.
247  const FileEntry *LookupSubframeworkHeader(
248      StringRef Filename,
249      const FileEntry *RelativeFileEnt,
250      SmallVectorImpl<char> *SearchPath,
251      SmallVectorImpl<char> *RelativePath);
252
253  /// LookupFrameworkCache - Look up the specified framework name in our
254  /// framework cache, returning the DirectoryEntry it is in if we know,
255  /// otherwise, return null.
256  const DirectoryEntry *&LookupFrameworkCache(StringRef FWName) {
257    return FrameworkMap.GetOrCreateValue(FWName).getValue();
258  }
259
260  /// ShouldEnterIncludeFile - Mark the specified file as a target of of a
261  /// #include, #include_next, or #import directive.  Return false if #including
262  /// the file will have no effect or true if we should include it.
263  bool ShouldEnterIncludeFile(const FileEntry *File, bool isImport);
264
265
266  /// getFileDirFlavor - Return whether the specified file is a normal header,
267  /// a system header, or a C++ friendly system header.
268  SrcMgr::CharacteristicKind getFileDirFlavor(const FileEntry *File) {
269    return (SrcMgr::CharacteristicKind)getFileInfo(File).DirInfo;
270  }
271
272  /// MarkFileIncludeOnce - Mark the specified file as a "once only" file, e.g.
273  /// due to #pragma once.
274  void MarkFileIncludeOnce(const FileEntry *File) {
275    HeaderFileInfo &FI = getFileInfo(File);
276    FI.isImport = true;
277    FI.isPragmaOnce = true;
278  }
279
280  /// MarkFileSystemHeader - Mark the specified file as a system header, e.g.
281  /// due to #pragma GCC system_header.
282  void MarkFileSystemHeader(const FileEntry *File) {
283    getFileInfo(File).DirInfo = SrcMgr::C_System;
284  }
285
286  /// IncrementIncludeCount - Increment the count for the number of times the
287  /// specified FileEntry has been entered.
288  void IncrementIncludeCount(const FileEntry *File) {
289    ++getFileInfo(File).NumIncludes;
290  }
291
292  /// SetFileControllingMacro - Mark the specified file as having a controlling
293  /// macro.  This is used by the multiple-include optimization to eliminate
294  /// no-op #includes.
295  void SetFileControllingMacro(const FileEntry *File,
296                               const IdentifierInfo *ControllingMacro) {
297    getFileInfo(File).ControllingMacro = ControllingMacro;
298  }
299
300  /// \brief Determine whether this file is intended to be safe from
301  /// multiple inclusions, e.g., it has #pragma once or a controlling
302  /// macro.
303  ///
304  /// This routine does not consider the effect of #import
305  bool isFileMultipleIncludeGuarded(const FileEntry *File);
306
307  /// CreateHeaderMap - This method returns a HeaderMap for the specified
308  /// FileEntry, uniquing them through the the 'HeaderMaps' datastructure.
309  const HeaderMap *CreateHeaderMap(const FileEntry *FE);
310
311  void IncrementFrameworkLookupCount() { ++NumFrameworkLookups; }
312
313  typedef std::vector<HeaderFileInfo>::const_iterator header_file_iterator;
314  header_file_iterator header_file_begin() const { return FileInfo.begin(); }
315  header_file_iterator header_file_end() const { return FileInfo.end(); }
316  unsigned header_file_size() const { return FileInfo.size(); }
317
318  // Used by ASTReader.
319  void setHeaderFileInfoForUID(HeaderFileInfo HFI, unsigned UID);
320
321  // Used by external tools
322  typedef std::vector<DirectoryLookup>::const_iterator search_dir_iterator;
323  search_dir_iterator search_dir_begin() const { return SearchDirs.begin(); }
324  search_dir_iterator search_dir_end() const { return SearchDirs.end(); }
325  unsigned search_dir_size() const { return SearchDirs.size(); }
326
327  search_dir_iterator quoted_dir_begin() const {
328    return SearchDirs.begin();
329  }
330  search_dir_iterator quoted_dir_end() const {
331    return SearchDirs.begin() + AngledDirIdx;
332  }
333
334  search_dir_iterator angled_dir_begin() const {
335    return SearchDirs.begin() + AngledDirIdx;
336  }
337  search_dir_iterator angled_dir_end() const {
338    return SearchDirs.begin() + SystemDirIdx;
339  }
340
341  search_dir_iterator system_dir_begin() const {
342    return SearchDirs.begin() + SystemDirIdx;
343  }
344  search_dir_iterator system_dir_end() const { return SearchDirs.end(); }
345
346  /// \brief Retrieve a uniqued framework name.
347  StringRef getUniqueFrameworkName(StringRef Framework);
348
349  void PrintStats();
350
351  size_t getTotalMemory() const;
352
353private:
354
355  /// getFileInfo - Return the HeaderFileInfo structure for the specified
356  /// FileEntry.
357  HeaderFileInfo &getFileInfo(const FileEntry *FE);
358};
359
360}  // end namespace clang
361
362#endif
363