1 //===--- HeaderSearch.h - Resolve Header File Locations ---------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the HeaderSearch interface.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_LEX_HEADERSEARCH_H
15 #define LLVM_CLANG_LEX_HEADERSEARCH_H
17 #include "clang/Lex/DirectoryLookup.h"
18 #include "clang/Lex/ModuleMap.h"
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/IntrusiveRefCntPtr.h"
21 #include "llvm/ADT/OwningPtr.h"
22 #include "llvm/ADT/StringMap.h"
23 #include "llvm/ADT/StringSet.h"
24 #include "llvm/Support/Allocator.h"
29 class DiagnosticsEngine;
30 class ExternalIdentifierLookup;
33 class HeaderSearchOptions;
36 /// \brief The preprocessor keeps track of this information for each
37 /// file that is \#included.
38 struct HeaderFileInfo {
39 /// \brief True if this is a \#import'd or \#pragma once file.
40 unsigned isImport : 1;
42 /// \brief True if this is a \#pragma once file.
43 unsigned isPragmaOnce : 1;
45 /// DirInfo - Keep track of whether this is a system header, and if so,
46 /// whether it is C++ clean or not. This can be set by the include paths or
47 /// by \#pragma gcc system_header. This is an instance of
48 /// SrcMgr::CharacteristicKind.
51 /// \brief Whether this header file info was supplied by an external source.
52 unsigned External : 1;
54 /// \brief Whether this header is part of a module.
55 unsigned isModuleHeader : 1;
57 /// \brief Whether this header is part of the module that we are building.
58 unsigned isCompilingModuleHeader : 1;
60 /// \brief Whether this header is part of the module that we are building.
61 /// This is an instance of ModuleMap::ModuleHeaderRole.
62 unsigned HeaderRole : 2;
64 /// \brief Whether this structure is considered to already have been
65 /// "resolved", meaning that it was loaded from the external source.
66 unsigned Resolved : 1;
68 /// \brief Whether this is a header inside a framework that is currently
71 /// When a framework is being built, the headers have not yet been placed
72 /// into the appropriate framework subdirectories, and therefore are
73 /// provided via a header map. This bit indicates when this is one of
74 /// those framework headers.
75 unsigned IndexHeaderMapHeader : 1;
77 /// \brief The number of times the file has been included already.
78 unsigned short NumIncludes;
80 /// \brief The ID number of the controlling macro.
82 /// This ID number will be non-zero when there is a controlling
83 /// macro whose IdentifierInfo may not yet have been loaded from
85 unsigned ControllingMacroID;
87 /// If this file has a \#ifndef XXX (or equivalent) guard that
88 /// protects the entire contents of the file, this is the identifier
89 /// for the macro that controls whether or not it has any effect.
91 /// Note: Most clients should use getControllingMacro() to access
92 /// the controlling macro of this header, since
93 /// getControllingMacro() is able to load a controlling macro from
95 const IdentifierInfo *ControllingMacro;
97 /// \brief If this header came from a framework include, this is the name
102 : isImport(false), isPragmaOnce(false), DirInfo(SrcMgr::C_User),
103 External(false), isModuleHeader(false), isCompilingModuleHeader(false),
104 HeaderRole(ModuleMap::NormalHeader),
105 Resolved(false), IndexHeaderMapHeader(false),
106 NumIncludes(0), ControllingMacroID(0), ControllingMacro(0) {}
108 /// \brief Retrieve the controlling macro for this header file, if
110 const IdentifierInfo *getControllingMacro(ExternalIdentifierLookup *External);
112 /// \brief Determine whether this is a non-default header file info, e.g.,
113 /// it corresponds to an actual header we've included or tried to include.
114 bool isNonDefault() const {
115 return isImport || isPragmaOnce || NumIncludes || ControllingMacro ||
119 /// \brief Get the HeaderRole properly typed.
120 ModuleMap::ModuleHeaderRole getHeaderRole() const {
121 return static_cast<ModuleMap::ModuleHeaderRole>(HeaderRole);
124 /// \brief Set the HeaderRole properly typed.
125 void setHeaderRole(ModuleMap::ModuleHeaderRole Role) {
130 /// \brief An external source of header file information, which may supply
131 /// information about header files already included.
132 class ExternalHeaderFileInfoSource {
134 virtual ~ExternalHeaderFileInfoSource();
136 /// \brief Retrieve the header file information for the given file entry.
138 /// \returns Header file information for the given file entry, with the
139 /// \c External bit set. If the file entry is not known, return a
140 /// default-constructed \c HeaderFileInfo.
141 virtual HeaderFileInfo GetHeaderFileInfo(const FileEntry *FE) = 0;
144 /// \brief Encapsulates the information needed to find the file referenced
145 /// by a \#include or \#include_next, (sub-)framework lookup, etc.
147 /// This structure is used to record entries in our framework cache.
148 struct FrameworkCacheEntry {
149 /// The directory entry which should be used for the cached framework.
150 const DirectoryEntry *Directory;
152 /// Whether this framework has been "user-specified" to be treated as if it
153 /// were a system framework (even if it was found outside a system framework
155 bool IsUserSpecifiedSystemFramework;
158 /// \brief Header-search options used to initialize this header search.
159 IntrusiveRefCntPtr<HeaderSearchOptions> HSOpts;
161 FileManager &FileMgr;
162 /// \#include search path information. Requests for \#include "x" search the
163 /// directory of the \#including file first, then each directory in SearchDirs
164 /// consecutively. Requests for <x> search the current dir first, then each
165 /// directory in SearchDirs, starting at AngledDirIdx, consecutively. If
166 /// NoCurDirSearch is true, then the check for the file in the current
167 /// directory is suppressed.
168 std::vector<DirectoryLookup> SearchDirs;
169 unsigned AngledDirIdx;
170 unsigned SystemDirIdx;
173 /// \brief \#include prefixes for which the 'system header' property is
176 /// For a \#include "x" or \#include \<x> directive, the last string in this
177 /// list which is a prefix of 'x' determines whether the file is treated as
179 std::vector<std::pair<std::string, bool> > SystemHeaderPrefixes;
181 /// \brief The path to the module cache.
182 std::string ModuleCachePath;
184 /// \brief All of the preprocessor-specific data about files that are
185 /// included, indexed by the FileEntry's UID.
186 std::vector<HeaderFileInfo> FileInfo;
188 /// \brief Keeps track of each lookup performed by LookupFile.
190 /// The first part of the value is the starting index in SearchDirs
191 /// that the cached search was performed from. If there is a hit and
192 /// this value doesn't match the current query, the cache has to be
193 /// ignored. The second value is the entry in SearchDirs that satisfied
195 llvm::StringMap<std::pair<unsigned, unsigned>, llvm::BumpPtrAllocator>
198 /// \brief Collection mapping a framework or subframework
199 /// name like "Carbon" to the Carbon.framework directory.
200 llvm::StringMap<FrameworkCacheEntry, llvm::BumpPtrAllocator> FrameworkMap;
202 /// IncludeAliases - maps include file names (including the quotes or
203 /// angle brackets) to other include file names. This is used to support the
204 /// include_alias pragma for Microsoft compatibility.
205 typedef llvm::StringMap<std::string, llvm::BumpPtrAllocator>
207 OwningPtr<IncludeAliasMap> IncludeAliases;
209 /// HeaderMaps - This is a mapping from FileEntry -> HeaderMap, uniquing
210 /// headermaps. This vector owns the headermap.
211 std::vector<std::pair<const FileEntry*, const HeaderMap*> > HeaderMaps;
213 /// \brief The mapping between modules and headers.
214 mutable ModuleMap ModMap;
216 /// \brief Describes whether a given directory has a module map in it.
217 llvm::DenseMap<const DirectoryEntry *, bool> DirectoryHasModuleMap;
219 /// \brief Uniqued set of framework names, which is used to track which
220 /// headers were included as framework headers.
221 llvm::StringSet<llvm::BumpPtrAllocator> FrameworkNames;
223 /// \brief Entity used to resolve the identifier IDs of controlling
224 /// macros into IdentifierInfo pointers, as needed.
225 ExternalIdentifierLookup *ExternalLookup;
227 /// \brief Entity used to look up stored header file information.
228 ExternalHeaderFileInfoSource *ExternalSource;
230 // Various statistics we track for performance analysis.
231 unsigned NumIncluded;
232 unsigned NumMultiIncludeFileOptzn;
233 unsigned NumFrameworkLookups, NumSubFrameworkLookups;
235 // HeaderSearch doesn't support default or copy construction.
236 HeaderSearch(const HeaderSearch&) LLVM_DELETED_FUNCTION;
237 void operator=(const HeaderSearch&) LLVM_DELETED_FUNCTION;
239 friend class DirectoryLookup;
242 HeaderSearch(IntrusiveRefCntPtr<HeaderSearchOptions> HSOpts,
243 SourceManager &SourceMgr, DiagnosticsEngine &Diags,
244 const LangOptions &LangOpts, const TargetInfo *Target);
247 /// \brief Retrieve the header-search options with which this header search
249 HeaderSearchOptions &getHeaderSearchOpts() const { return *HSOpts; }
251 FileManager &getFileMgr() const { return FileMgr; }
253 /// \brief Interface for setting the file search paths.
254 void SetSearchPaths(const std::vector<DirectoryLookup> &dirs,
255 unsigned angledDirIdx, unsigned systemDirIdx,
256 bool noCurDirSearch) {
257 assert(angledDirIdx <= systemDirIdx && systemDirIdx <= dirs.size() &&
258 "Directory indicies are unordered");
260 AngledDirIdx = angledDirIdx;
261 SystemDirIdx = systemDirIdx;
262 NoCurDirSearch = noCurDirSearch;
263 //LookupFileCache.clear();
266 /// \brief Add an additional search path.
267 void AddSearchPath(const DirectoryLookup &dir, bool isAngled) {
268 unsigned idx = isAngled ? SystemDirIdx : AngledDirIdx;
269 SearchDirs.insert(SearchDirs.begin() + idx, dir);
275 /// \brief Set the list of system header prefixes.
276 void SetSystemHeaderPrefixes(ArrayRef<std::pair<std::string, bool> > P) {
277 SystemHeaderPrefixes.assign(P.begin(), P.end());
280 /// \brief Checks whether the map exists or not.
281 bool HasIncludeAliasMap() const {
282 return IncludeAliases.isValid();
285 /// \brief Map the source include name to the dest include name.
287 /// The Source should include the angle brackets or quotes, the dest
288 /// should not. This allows for distinction between <> and "" headers.
289 void AddIncludeAlias(StringRef Source, StringRef Dest) {
291 IncludeAliases.reset(new IncludeAliasMap);
292 (*IncludeAliases)[Source] = Dest;
295 /// MapHeaderToIncludeAlias - Maps one header file name to a different header
296 /// file name, for use with the include_alias pragma. Note that the source
297 /// file name should include the angle brackets or quotes. Returns StringRef
298 /// as null if the header cannot be mapped.
299 StringRef MapHeaderToIncludeAlias(StringRef Source) {
300 assert(IncludeAliases && "Trying to map headers when there's no map");
302 // Do any filename replacements before anything else
303 IncludeAliasMap::const_iterator Iter = IncludeAliases->find(Source);
304 if (Iter != IncludeAliases->end())
309 /// \brief Set the path to the module cache.
310 void setModuleCachePath(StringRef CachePath) {
311 ModuleCachePath = CachePath;
314 /// \brief Retrieve the path to the module cache.
315 StringRef getModuleCachePath() const { return ModuleCachePath; }
317 /// \brief Consider modules when including files from this directory.
318 void setDirectoryHasModuleMap(const DirectoryEntry* Dir) {
319 DirectoryHasModuleMap[Dir] = true;
322 /// \brief Forget everything we know about headers so far.
323 void ClearFileInfo() {
327 void SetExternalLookup(ExternalIdentifierLookup *EIL) {
328 ExternalLookup = EIL;
331 ExternalIdentifierLookup *getExternalLookup() const {
332 return ExternalLookup;
335 /// \brief Set the external source of header information.
336 void SetExternalSource(ExternalHeaderFileInfoSource *ES) {
340 /// \brief Set the target information for the header search, if not
342 void setTarget(const TargetInfo &Target);
344 /// \brief Given a "foo" or \<foo> reference, look up the indicated file,
345 /// return null on failure.
347 /// \returns If successful, this returns 'UsedDir', the DirectoryLookup member
348 /// the file was found in, or null if not applicable.
350 /// \param isAngled indicates whether the file reference is a <> reference.
352 /// \param CurDir If non-null, the file was found in the specified directory
353 /// search location. This is used to implement \#include_next.
355 /// \param CurFileEnt If non-null, indicates where the \#including file is, in
356 /// case a relative search is needed.
358 /// \param SearchPath If non-null, will be set to the search path relative
359 /// to which the file was found. If the include path is absolute, SearchPath
360 /// will be set to an empty string.
362 /// \param RelativePath If non-null, will be set to the path relative to
363 /// SearchPath at which the file was found. This only differs from the
364 /// Filename for framework includes.
366 /// \param SuggestedModule If non-null, and the file found is semantically
367 /// part of a known module, this will be set to the module that should
368 /// be imported instead of preprocessing/parsing the file found.
369 const FileEntry *LookupFile(StringRef Filename, bool isAngled,
370 const DirectoryLookup *FromDir,
371 const DirectoryLookup *&CurDir,
372 const FileEntry *CurFileEnt,
373 SmallVectorImpl<char> *SearchPath,
374 SmallVectorImpl<char> *RelativePath,
375 ModuleMap::KnownHeader *SuggestedModule,
376 bool SkipCache = false);
378 /// \brief Look up a subframework for the specified \#include file.
380 /// For example, if \#include'ing <HIToolbox/HIToolbox.h> from
381 /// within ".../Carbon.framework/Headers/Carbon.h", check to see if
382 /// HIToolbox is a subframework within Carbon.framework. If so, return
383 /// the FileEntry for the designated file, otherwise return null.
384 const FileEntry *LookupSubframeworkHeader(
386 const FileEntry *RelativeFileEnt,
387 SmallVectorImpl<char> *SearchPath,
388 SmallVectorImpl<char> *RelativePath,
389 ModuleMap::KnownHeader *SuggestedModule);
391 /// \brief Look up the specified framework name in our framework cache.
392 /// \returns The DirectoryEntry it is in if we know, null otherwise.
393 FrameworkCacheEntry &LookupFrameworkCache(StringRef FWName) {
394 return FrameworkMap.GetOrCreateValue(FWName).getValue();
397 /// \brief Mark the specified file as a target of of a \#include,
398 /// \#include_next, or \#import directive.
400 /// \return false if \#including the file will have no effect or true
401 /// if we should include it.
402 bool ShouldEnterIncludeFile(const FileEntry *File, bool isImport);
405 /// \brief Return whether the specified file is a normal header,
406 /// a system header, or a C++ friendly system header.
407 SrcMgr::CharacteristicKind getFileDirFlavor(const FileEntry *File) {
408 return (SrcMgr::CharacteristicKind)getFileInfo(File).DirInfo;
411 /// \brief Mark the specified file as a "once only" file, e.g. due to
413 void MarkFileIncludeOnce(const FileEntry *File) {
414 HeaderFileInfo &FI = getFileInfo(File);
416 FI.isPragmaOnce = true;
419 /// \brief Mark the specified file as a system header, e.g. due to
420 /// \#pragma GCC system_header.
421 void MarkFileSystemHeader(const FileEntry *File) {
422 getFileInfo(File).DirInfo = SrcMgr::C_System;
425 /// \brief Mark the specified file as part of a module.
426 void MarkFileModuleHeader(const FileEntry *File,
427 ModuleMap::ModuleHeaderRole Role,
428 bool IsCompiledModuleHeader);
430 /// \brief Increment the count for the number of times the specified
431 /// FileEntry has been entered.
432 void IncrementIncludeCount(const FileEntry *File) {
433 ++getFileInfo(File).NumIncludes;
436 /// \brief Mark the specified file as having a controlling macro.
438 /// This is used by the multiple-include optimization to eliminate
439 /// no-op \#includes.
440 void SetFileControllingMacro(const FileEntry *File,
441 const IdentifierInfo *ControllingMacro) {
442 getFileInfo(File).ControllingMacro = ControllingMacro;
445 /// \brief Return true if this is the first time encountering this header.
446 bool FirstTimeLexingFile(const FileEntry *File) {
447 return getFileInfo(File).NumIncludes == 1;
450 /// \brief Determine whether this file is intended to be safe from
451 /// multiple inclusions, e.g., it has \#pragma once or a controlling
454 /// This routine does not consider the effect of \#import
455 bool isFileMultipleIncludeGuarded(const FileEntry *File);
457 /// CreateHeaderMap - This method returns a HeaderMap for the specified
458 /// FileEntry, uniquing them through the 'HeaderMaps' datastructure.
459 const HeaderMap *CreateHeaderMap(const FileEntry *FE);
461 /// \brief Retrieve the name of the module file that should be used to
462 /// load the given module.
464 /// \param Module The module whose module file name will be returned.
466 /// \returns The name of the module file that corresponds to this module,
467 /// or an empty string if this module does not correspond to any module file.
468 std::string getModuleFileName(Module *Module);
470 /// \brief Retrieve the name of the module file that should be used to
471 /// load a module with the given name.
473 /// \param ModuleName The module whose module file name will be returned.
475 /// \returns The name of the module file that corresponds to this module,
476 /// or an empty string if this module does not correspond to any module file.
477 std::string getModuleFileName(StringRef ModuleName);
479 /// \brief Lookup a module Search for a module with the given name.
481 /// \param ModuleName The name of the module we're looking for.
483 /// \param AllowSearch Whether we are allowed to search in the various
484 /// search directories to produce a module definition. If not, this lookup
485 /// will only return an already-known module.
487 /// \returns The module with the given name.
488 Module *lookupModule(StringRef ModuleName, bool AllowSearch = true);
490 void IncrementFrameworkLookupCount() { ++NumFrameworkLookups; }
492 /// \brief Determine whether there is a module map that may map the header
493 /// with the given file name to a (sub)module.
495 /// \param Filename The name of the file.
497 /// \param Root The "root" directory, at which we should stop looking for
500 /// \param IsSystem Whether the directories we're looking at are system
501 /// header directories.
502 bool hasModuleMap(StringRef Filename, const DirectoryEntry *Root,
505 /// \brief Retrieve the module that corresponds to the given file, if any.
507 /// \param File The header that we wish to map to a module.
508 ModuleMap::KnownHeader findModuleForHeader(const FileEntry *File) const;
510 /// \brief Read the contents of the given module map file.
512 /// \param File The module map file.
513 /// \param IsSystem Whether this file is in a system header directory.
515 /// \returns true if an error occurred, false otherwise.
516 bool loadModuleMapFile(const FileEntry *File, bool IsSystem);
518 /// \brief Collect the set of all known, top-level modules.
520 /// \param Modules Will be filled with the set of known, top-level modules.
521 void collectAllModules(SmallVectorImpl<Module *> &Modules);
523 /// \brief Load all known, top-level system modules.
524 void loadTopLevelSystemModules();
527 /// \brief Retrieve a module with the given name, which may be part of the
530 /// \param Name The name of the module to retrieve.
532 /// \param Dir The framework directory (e.g., ModuleName.framework).
534 /// \param IsSystem Whether the framework directory is part of the system
537 /// \returns The module, if found; otherwise, null.
538 Module *loadFrameworkModule(StringRef Name,
539 const DirectoryEntry *Dir,
542 /// \brief Load all of the module maps within the immediate subdirectories
543 /// of the given search directory.
544 void loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir);
547 /// \brief Retrieve the module map.
548 ModuleMap &getModuleMap() { return ModMap; }
550 unsigned header_file_size() const { return FileInfo.size(); }
552 /// \brief Return the HeaderFileInfo structure for the specified FileEntry.
553 const HeaderFileInfo &getFileInfo(const FileEntry *FE) const {
554 return const_cast<HeaderSearch*>(this)->getFileInfo(FE);
557 // Used by external tools
558 typedef std::vector<DirectoryLookup>::const_iterator search_dir_iterator;
559 search_dir_iterator search_dir_begin() const { return SearchDirs.begin(); }
560 search_dir_iterator search_dir_end() const { return SearchDirs.end(); }
561 unsigned search_dir_size() const { return SearchDirs.size(); }
563 search_dir_iterator quoted_dir_begin() const {
564 return SearchDirs.begin();
566 search_dir_iterator quoted_dir_end() const {
567 return SearchDirs.begin() + AngledDirIdx;
570 search_dir_iterator angled_dir_begin() const {
571 return SearchDirs.begin() + AngledDirIdx;
573 search_dir_iterator angled_dir_end() const {
574 return SearchDirs.begin() + SystemDirIdx;
577 search_dir_iterator system_dir_begin() const {
578 return SearchDirs.begin() + SystemDirIdx;
580 search_dir_iterator system_dir_end() const { return SearchDirs.end(); }
582 /// \brief Retrieve a uniqued framework name.
583 StringRef getUniqueFrameworkName(StringRef Framework);
587 size_t getTotalMemory() const;
589 static std::string NormalizeDashIncludePath(StringRef File,
590 FileManager &FileMgr);
593 /// \brief Describes what happened when we tried to load a module map file.
594 enum LoadModuleMapResult {
595 /// \brief The module map file had already been loaded.
597 /// \brief The module map file was loaded by this invocation.
599 /// \brief There is was directory with the given name.
601 /// \brief There was either no module map file or the module map file was
606 /// \brief Try to load the module map file in the given directory.
608 /// \param DirName The name of the directory where we will look for a module
610 /// \param IsSystem Whether this is a system header directory.
612 /// \returns The result of attempting to load the module map file from the
614 LoadModuleMapResult loadModuleMapFile(StringRef DirName, bool IsSystem);
616 /// \brief Try to load the module map file in the given directory.
618 /// \param Dir The directory where we will look for a module map file.
619 /// \param IsSystem Whether this is a system header directory.
621 /// \returns The result of attempting to load the module map file from the
623 LoadModuleMapResult loadModuleMapFile(const DirectoryEntry *Dir,
626 /// \brief Return the HeaderFileInfo structure for the specified FileEntry.
627 HeaderFileInfo &getFileInfo(const FileEntry *FE);
630 } // end namespace clang