HeaderSearch.h revision 6e975c4517958bcc11c834336d340797356058db
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  /// \brief The path to the module cache.
133  std::string ModuleCachePath;
134
135  /// FileInfo - This contains all of the preprocessor-specific data about files
136  /// that are included.  The vector is indexed by the FileEntry's UID.
137  ///
138  std::vector<HeaderFileInfo> FileInfo;
139
140  /// LookupFileCache - This is keeps track of each lookup performed by
141  /// LookupFile.  The first part of the value is the starting index in
142  /// SearchDirs that the cached search was performed from.  If there is a hit
143  /// and this value doesn't match the current query, the cache has to be
144  /// ignored.  The second value is the entry in SearchDirs that satisfied the
145  /// query.
146  llvm::StringMap<std::pair<unsigned, unsigned>, llvm::BumpPtrAllocator>
147    LookupFileCache;
148
149
150  /// FrameworkMap - This is a collection mapping a framework or subframework
151  /// name like "Carbon" to the Carbon.framework directory.
152  llvm::StringMap<const DirectoryEntry *, llvm::BumpPtrAllocator>
153    FrameworkMap;
154
155  /// HeaderMaps - This is a mapping from FileEntry -> HeaderMap, uniquing
156  /// headermaps.  This vector owns the headermap.
157  std::vector<std::pair<const FileEntry*, const HeaderMap*> > HeaderMaps;
158
159  /// \brief Uniqued set of framework names, which is used to track which
160  /// headers were included as framework headers.
161  llvm::StringSet<llvm::BumpPtrAllocator> FrameworkNames;
162
163  /// \brief Entity used to resolve the identifier IDs of controlling
164  /// macros into IdentifierInfo pointers, as needed.
165  ExternalIdentifierLookup *ExternalLookup;
166
167  /// \brief Entity used to look up stored header file information.
168  ExternalHeaderFileInfoSource *ExternalSource;
169
170  // Various statistics we track for performance analysis.
171  unsigned NumIncluded;
172  unsigned NumMultiIncludeFileOptzn;
173  unsigned NumFrameworkLookups, NumSubFrameworkLookups;
174
175  // HeaderSearch doesn't support default or copy construction.
176  explicit HeaderSearch();
177  explicit HeaderSearch(const HeaderSearch&);
178  void operator=(const HeaderSearch&);
179public:
180  HeaderSearch(FileManager &FM);
181  ~HeaderSearch();
182
183  FileManager &getFileMgr() const { return FileMgr; }
184
185  /// SetSearchPaths - Interface for setting the file search paths.
186  ///
187  void SetSearchPaths(const std::vector<DirectoryLookup> &dirs,
188                      unsigned angledDirIdx, unsigned systemDirIdx,
189                      bool noCurDirSearch) {
190    assert(angledDirIdx <= systemDirIdx && systemDirIdx <= dirs.size() &&
191        "Directory indicies are unordered");
192    SearchDirs = dirs;
193    AngledDirIdx = angledDirIdx;
194    SystemDirIdx = systemDirIdx;
195    NoCurDirSearch = noCurDirSearch;
196    //LookupFileCache.clear();
197  }
198
199  /// \brief Set the path to the module cache.
200  void setModuleCachePath(StringRef Path) {
201    ModuleCachePath = Path;
202  }
203
204  /// ClearFileInfo - Forget everything we know about headers so far.
205  void ClearFileInfo() {
206    FileInfo.clear();
207  }
208
209  void SetExternalLookup(ExternalIdentifierLookup *EIL) {
210    ExternalLookup = EIL;
211  }
212
213  ExternalIdentifierLookup *getExternalLookup() const {
214    return ExternalLookup;
215  }
216
217  /// \brief Set the external source of header information.
218  void SetExternalSource(ExternalHeaderFileInfoSource *ES) {
219    ExternalSource = ES;
220  }
221
222  /// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
223  /// return null on failure.
224  ///
225  /// \returns If successful, this returns 'UsedDir', the DirectoryLookup member
226  /// the file was found in, or null if not applicable.
227  ///
228  /// \param isAngled indicates whether the file reference is a <> reference.
229  ///
230  /// \param CurDir If non-null, the file was found in the specified directory
231  /// search location.  This is used to implement #include_next.
232  ///
233  /// \param CurFileEnt If non-null, indicates where the #including file is, in
234  /// case a relative search is needed.
235  ///
236  /// \param SearchPath If non-null, will be set to the search path relative
237  /// to which the file was found. If the include path is absolute, SearchPath
238  /// will be set to an empty string.
239  ///
240  /// \param RelativePath If non-null, will be set to the path relative to
241  /// SearchPath at which the file was found. This only differs from the
242  /// Filename for framework includes.
243  const FileEntry *LookupFile(StringRef Filename, bool isAngled,
244                              const DirectoryLookup *FromDir,
245                              const DirectoryLookup *&CurDir,
246                              const FileEntry *CurFileEnt,
247                              SmallVectorImpl<char> *SearchPath,
248                              SmallVectorImpl<char> *RelativePath);
249
250  /// LookupSubframeworkHeader - Look up a subframework for the specified
251  /// #include file.  For example, if #include'ing <HIToolbox/HIToolbox.h> from
252  /// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
253  /// is a subframework within Carbon.framework.  If so, return the FileEntry
254  /// for the designated file, otherwise return null.
255  const FileEntry *LookupSubframeworkHeader(
256      StringRef Filename,
257      const FileEntry *RelativeFileEnt,
258      SmallVectorImpl<char> *SearchPath,
259      SmallVectorImpl<char> *RelativePath);
260
261  /// LookupFrameworkCache - Look up the specified framework name in our
262  /// framework cache, returning the DirectoryEntry it is in if we know,
263  /// otherwise, return null.
264  const DirectoryEntry *&LookupFrameworkCache(StringRef FWName) {
265    return FrameworkMap.GetOrCreateValue(FWName).getValue();
266  }
267
268  /// ShouldEnterIncludeFile - Mark the specified file as a target of of a
269  /// #include, #include_next, or #import directive.  Return false if #including
270  /// the file will have no effect or true if we should include it.
271  bool ShouldEnterIncludeFile(const FileEntry *File, bool isImport);
272
273
274  /// getFileDirFlavor - Return whether the specified file is a normal header,
275  /// a system header, or a C++ friendly system header.
276  SrcMgr::CharacteristicKind getFileDirFlavor(const FileEntry *File) {
277    return (SrcMgr::CharacteristicKind)getFileInfo(File).DirInfo;
278  }
279
280  /// MarkFileIncludeOnce - Mark the specified file as a "once only" file, e.g.
281  /// due to #pragma once.
282  void MarkFileIncludeOnce(const FileEntry *File) {
283    HeaderFileInfo &FI = getFileInfo(File);
284    FI.isImport = true;
285    FI.isPragmaOnce = true;
286  }
287
288  /// MarkFileSystemHeader - Mark the specified file as a system header, e.g.
289  /// due to #pragma GCC system_header.
290  void MarkFileSystemHeader(const FileEntry *File) {
291    getFileInfo(File).DirInfo = SrcMgr::C_System;
292  }
293
294  /// IncrementIncludeCount - Increment the count for the number of times the
295  /// specified FileEntry has been entered.
296  void IncrementIncludeCount(const FileEntry *File) {
297    ++getFileInfo(File).NumIncludes;
298  }
299
300  /// SetFileControllingMacro - Mark the specified file as having a controlling
301  /// macro.  This is used by the multiple-include optimization to eliminate
302  /// no-op #includes.
303  void SetFileControllingMacro(const FileEntry *File,
304                               const IdentifierInfo *ControllingMacro) {
305    getFileInfo(File).ControllingMacro = ControllingMacro;
306  }
307
308  /// \brief Determine whether this file is intended to be safe from
309  /// multiple inclusions, e.g., it has #pragma once or a controlling
310  /// macro.
311  ///
312  /// This routine does not consider the effect of #import
313  bool isFileMultipleIncludeGuarded(const FileEntry *File);
314
315  /// CreateHeaderMap - This method returns a HeaderMap for the specified
316  /// FileEntry, uniquing them through the the 'HeaderMaps' datastructure.
317  const HeaderMap *CreateHeaderMap(const FileEntry *FE);
318
319  /// \brief Search in the module cache path for a module with the given
320  /// name.
321  ///
322  /// \param If non-NULL, will be set to the module file name we expected to
323  /// find (regardless of whether it was actually found or not).
324  ///
325  /// \param UmbrellaHeader If non-NULL, and no module was found in the module
326  /// cache, this routine will search in the framework paths to determine
327  /// whether a module can be built from an umbrella header. If so, the pointee
328  /// will be set to the path of the umbrella header.
329  ///
330  /// \returns A file describing the named module, if available, or NULL to
331  /// indicate that the module could not be found.
332  const FileEntry *lookupModule(StringRef ModuleName,
333                                std::string *ModuleFileName = 0,
334                                std::string *UmbrellaHeader = 0);
335
336  void IncrementFrameworkLookupCount() { ++NumFrameworkLookups; }
337
338  typedef std::vector<HeaderFileInfo>::const_iterator header_file_iterator;
339  header_file_iterator header_file_begin() const { return FileInfo.begin(); }
340  header_file_iterator header_file_end() const { return FileInfo.end(); }
341  unsigned header_file_size() const { return FileInfo.size(); }
342
343  // Used by ASTReader.
344  void setHeaderFileInfoForUID(HeaderFileInfo HFI, unsigned UID);
345
346  // Used by external tools
347  typedef std::vector<DirectoryLookup>::const_iterator search_dir_iterator;
348  search_dir_iterator search_dir_begin() const { return SearchDirs.begin(); }
349  search_dir_iterator search_dir_end() const { return SearchDirs.end(); }
350  unsigned search_dir_size() const { return SearchDirs.size(); }
351
352  search_dir_iterator quoted_dir_begin() const {
353    return SearchDirs.begin();
354  }
355  search_dir_iterator quoted_dir_end() const {
356    return SearchDirs.begin() + AngledDirIdx;
357  }
358
359  search_dir_iterator angled_dir_begin() const {
360    return SearchDirs.begin() + AngledDirIdx;
361  }
362  search_dir_iterator angled_dir_end() const {
363    return SearchDirs.begin() + SystemDirIdx;
364  }
365
366  search_dir_iterator system_dir_begin() const {
367    return SearchDirs.begin() + SystemDirIdx;
368  }
369  search_dir_iterator system_dir_end() const { return SearchDirs.end(); }
370
371  /// \brief Retrieve a uniqued framework name.
372  StringRef getUniqueFrameworkName(StringRef Framework);
373
374  void PrintStats();
375
376  size_t getTotalMemory() const;
377
378private:
379
380  /// getFileInfo - Return the HeaderFileInfo structure for the specified
381  /// FileEntry.
382  HeaderFileInfo &getFileInfo(const FileEntry *FE);
383};
384
385}  // end namespace clang
386
387#endif
388