xref: /freebsd/contrib/llvm-project/clang/include/clang/Lex/HeaderSearch.h (revision 700637cbb5e582861067a11aaca4d053546871d2)
1 //===- HeaderSearch.h - Resolve Header File Locations -----------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the HeaderSearch interface.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_CLANG_LEX_HEADERSEARCH_H
14 #define LLVM_CLANG_LEX_HEADERSEARCH_H
15 
16 #include "clang/Basic/SourceLocation.h"
17 #include "clang/Basic/SourceManager.h"
18 #include "clang/Lex/DirectoryLookup.h"
19 #include "clang/Lex/ExternalPreprocessorSource.h"
20 #include "clang/Lex/HeaderMap.h"
21 #include "clang/Lex/ModuleMap.h"
22 #include "llvm/ADT/ArrayRef.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/ADT/StringMap.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/ADT/StringSet.h"
28 #include "llvm/Support/Allocator.h"
29 #include <cassert>
30 #include <cstddef>
31 #include <memory>
32 #include <string>
33 #include <utility>
34 #include <vector>
35 
36 namespace llvm {
37 
38 class Triple;
39 
40 } // namespace llvm
41 
42 namespace clang {
43 
44 class DiagnosticsEngine;
45 class DirectoryEntry;
46 class ExternalPreprocessorSource;
47 class FileEntry;
48 class FileManager;
49 class HeaderSearch;
50 class HeaderSearchOptions;
51 class IdentifierInfo;
52 class LangOptions;
53 class Module;
54 class Preprocessor;
55 class TargetInfo;
56 
57 /// The preprocessor keeps track of this information for each
58 /// file that is \#included.
59 struct HeaderFileInfo {
60   // TODO: Whether the file was included is not a property of the file itself.
61   // It's a preprocessor state, move it there.
62   /// True if this file has been included (or imported) **locally**.
63   LLVM_PREFERRED_TYPE(bool)
64   unsigned IsLocallyIncluded : 1;
65 
66   // TODO: Whether the file was imported is not a property of the file itself.
67   // It's a preprocessor state, move it there.
68   /// True if this is a \#import'd file.
69   LLVM_PREFERRED_TYPE(bool)
70   unsigned isImport : 1;
71 
72   /// True if this is a \#pragma once file.
73   LLVM_PREFERRED_TYPE(bool)
74   unsigned isPragmaOnce : 1;
75 
76   /// Keep track of whether this is a system header, and if so,
77   /// whether it is C++ clean or not.  This can be set by the include paths or
78   /// by \#pragma gcc system_header.  This is an instance of
79   /// SrcMgr::CharacteristicKind.
80   LLVM_PREFERRED_TYPE(SrcMgr::CharacteristicKind)
81   unsigned DirInfo : 3;
82 
83   /// Whether this header file info was supplied by an external source,
84   /// and has not changed since.
85   LLVM_PREFERRED_TYPE(bool)
86   unsigned External : 1;
87 
88   /// Whether this header is part of and built with a module.  i.e. it is listed
89   /// in a module map, and is not `excluded` or `textual`. (same meaning as
90   /// `ModuleMap::isModular()`).
91   LLVM_PREFERRED_TYPE(bool)
92   unsigned isModuleHeader : 1;
93 
94   /// Whether this header is a `textual header` in a module. If a header is
95   /// textual in one module and normal in another module, this bit will not be
96   /// set, only `isModuleHeader`.
97   LLVM_PREFERRED_TYPE(bool)
98   unsigned isTextualModuleHeader : 1;
99 
100   /// Whether this header is part of the module that we are building, even if it
101   /// doesn't build with the module. i.e. this will include `excluded` and
102   /// `textual` headers as well as normal headers.
103   LLVM_PREFERRED_TYPE(bool)
104   unsigned isCompilingModuleHeader : 1;
105 
106   /// Whether this structure is considered to already have been
107   /// "resolved", meaning that it was loaded from the external source.
108   LLVM_PREFERRED_TYPE(bool)
109   unsigned Resolved : 1;
110 
111   /// Whether this file has been looked up as a header.
112   LLVM_PREFERRED_TYPE(bool)
113   unsigned IsValid : 1;
114 
115   /// If this file has a \#ifndef XXX (or equivalent) guard that
116   /// protects the entire contents of the file, this is the identifier
117   /// for the macro that controls whether or not it has any effect.
118   ///
119   /// Note: Most clients should use getControllingMacro() to access
120   /// the controlling macro of this header, since
121   /// getControllingMacro() is able to load a controlling macro from
122   /// external storage.
123   LazyIdentifierInfoPtr LazyControllingMacro;
124 
HeaderFileInfoHeaderFileInfo125   HeaderFileInfo()
126       : IsLocallyIncluded(false), isImport(false), isPragmaOnce(false),
127         DirInfo(SrcMgr::C_User), External(false), isModuleHeader(false),
128         isTextualModuleHeader(false), isCompilingModuleHeader(false),
129         Resolved(false), IsValid(false) {}
130 
131   /// Retrieve the controlling macro for this header file, if
132   /// any.
133   const IdentifierInfo *
134   getControllingMacro(ExternalPreprocessorSource *External);
135 
136   /// Update the module membership bits based on the header role.
137   ///
138   /// isModuleHeader will potentially be set, but not cleared.
139   /// isTextualModuleHeader will be set or cleared based on the role update.
140   void mergeModuleMembership(ModuleMap::ModuleHeaderRole Role);
141 };
142 
143 static_assert(sizeof(HeaderFileInfo) <= 16);
144 
145 /// An external source of header file information, which may supply
146 /// information about header files already included.
147 class ExternalHeaderFileInfoSource {
148 public:
149   virtual ~ExternalHeaderFileInfoSource();
150 
151   /// Retrieve the header file information for the given file entry.
152   ///
153   /// \returns Header file information for the given file entry, with the
154   /// \c External bit set. If the file entry is not known, return a
155   /// default-constructed \c HeaderFileInfo.
156   virtual HeaderFileInfo GetHeaderFileInfo(FileEntryRef FE) = 0;
157 };
158 
159 /// This structure is used to record entries in our framework cache.
160 struct FrameworkCacheEntry {
161   /// The directory entry which should be used for the cached framework.
162   OptionalDirectoryEntryRef Directory;
163 
164   /// Whether this framework has been "user-specified" to be treated as if it
165   /// were a system framework (even if it was found outside a system framework
166   /// directory).
167   bool IsUserSpecifiedSystemFramework;
168 };
169 
170 namespace detail {
171 template <bool Const, typename T>
172 using Qualified = std::conditional_t<Const, const T, T>;
173 
174 /// Forward iterator over the search directories of \c HeaderSearch.
175 template <bool IsConst>
176 struct SearchDirIteratorImpl
177     : llvm::iterator_facade_base<SearchDirIteratorImpl<IsConst>,
178                                  std::forward_iterator_tag,
179                                  Qualified<IsConst, DirectoryLookup>> {
180   /// Const -> non-const iterator conversion.
181   template <typename Enable = std::enable_if<IsConst, bool>>
SearchDirIteratorImplSearchDirIteratorImpl182   SearchDirIteratorImpl(const SearchDirIteratorImpl<false> &Other)
183       : HS(Other.HS), Idx(Other.Idx) {}
184 
185   SearchDirIteratorImpl(const SearchDirIteratorImpl &) = default;
186 
187   SearchDirIteratorImpl &operator=(const SearchDirIteratorImpl &) = default;
188 
189   bool operator==(const SearchDirIteratorImpl &RHS) const {
190     return HS == RHS.HS && Idx == RHS.Idx;
191   }
192 
193   SearchDirIteratorImpl &operator++() {
194     assert(*this && "Invalid iterator.");
195     ++Idx;
196     return *this;
197   }
198 
199   Qualified<IsConst, DirectoryLookup> &operator*() const {
200     assert(*this && "Invalid iterator.");
201     return HS->SearchDirs[Idx];
202   }
203 
204   /// Creates an invalid iterator.
SearchDirIteratorImplSearchDirIteratorImpl205   SearchDirIteratorImpl(std::nullptr_t) : HS(nullptr), Idx(0) {}
206 
207   /// Checks whether the iterator is valid.
208   explicit operator bool() const { return HS != nullptr; }
209 
210 private:
211   /// The parent \c HeaderSearch. This is \c nullptr for invalid iterator.
212   Qualified<IsConst, HeaderSearch> *HS;
213 
214   /// The index of the current element.
215   size_t Idx;
216 
217   /// The constructor that creates a valid iterator.
SearchDirIteratorImplSearchDirIteratorImpl218   SearchDirIteratorImpl(Qualified<IsConst, HeaderSearch> &HS, size_t Idx)
219       : HS(&HS), Idx(Idx) {}
220 
221   /// Only HeaderSearch is allowed to instantiate valid iterators.
222   friend HeaderSearch;
223 
224   /// Enables const -> non-const conversion.
225   friend SearchDirIteratorImpl<!IsConst>;
226 };
227 } // namespace detail
228 
229 using ConstSearchDirIterator = detail::SearchDirIteratorImpl<true>;
230 using SearchDirIterator = detail::SearchDirIteratorImpl<false>;
231 
232 using ConstSearchDirRange = llvm::iterator_range<ConstSearchDirIterator>;
233 using SearchDirRange = llvm::iterator_range<SearchDirIterator>;
234 
235 /// Encapsulates the information needed to find the file referenced
236 /// by a \#include or \#include_next, (sub-)framework lookup, etc.
237 class HeaderSearch {
238   friend class DirectoryLookup;
239 
240   friend ConstSearchDirIterator;
241   friend SearchDirIterator;
242 
243   /// Header-search options used to initialize this header search.
244   const HeaderSearchOptions &HSOpts;
245 
246   /// Mapping from SearchDir to HeaderSearchOptions::UserEntries indices.
247   llvm::DenseMap<unsigned, unsigned> SearchDirToHSEntry;
248 
249   DiagnosticsEngine &Diags;
250   FileManager &FileMgr;
251 
252   /// \#include search path information.  Requests for \#include "x" search the
253   /// directory of the \#including file first, then each directory in SearchDirs
254   /// consecutively. Requests for <x> search the current dir first, then each
255   /// directory in SearchDirs, starting at AngledDirIdx, consecutively.
256   std::vector<DirectoryLookup> SearchDirs;
257   /// Whether the DirectoryLookup at the corresponding index in SearchDirs has
258   /// been successfully used to lookup a file.
259   std::vector<bool> SearchDirsUsage;
260   unsigned AngledDirIdx = 0;
261   unsigned SystemDirIdx = 0;
262 
263   /// Maps HeaderMap keys to SearchDir indices. When HeaderMaps are used
264   /// heavily, SearchDirs can start with thousands of HeaderMaps, so this Index
265   /// lets us avoid scanning them all to find a match.
266   llvm::StringMap<unsigned, llvm::BumpPtrAllocator> SearchDirHeaderMapIndex;
267 
268   /// The index of the first SearchDir that isn't a header map.
269   unsigned FirstNonHeaderMapSearchDirIdx = 0;
270 
271   /// \#include prefixes for which the 'system header' property is
272   /// overridden.
273   ///
274   /// For a \#include "x" or \#include \<x> directive, the last string in this
275   /// list which is a prefix of 'x' determines whether the file is treated as
276   /// a system header.
277   std::vector<std::pair<std::string, bool>> SystemHeaderPrefixes;
278 
279   /// The hash used for module cache paths.
280   std::string ModuleHash;
281 
282   /// The path to the module cache.
283   std::string ModuleCachePath;
284 
285   /// All of the preprocessor-specific data about files that are
286   /// included, indexed by the FileEntry's UID.
287   mutable std::vector<HeaderFileInfo> FileInfo;
288 
289   /// Keeps track of each lookup performed by LookupFile.
290   struct LookupFileCacheInfo {
291     // The requesting module for the lookup we cached.
292     const Module *RequestingModule = nullptr;
293 
294     /// Starting search directory iterator that the cached search was performed
295     /// from. If there is a hit and this value doesn't match the current query,
296     /// the cache has to be ignored.
297     ConstSearchDirIterator StartIt = nullptr;
298 
299     /// The search directory iterator that satisfied the query.
300     ConstSearchDirIterator HitIt = nullptr;
301 
302     /// This is non-null if the original filename was mapped to a framework
303     /// include via a headermap.
304     const char *MappedName = nullptr;
305 
306     /// Default constructor -- Initialize all members with zero.
307     LookupFileCacheInfo() = default;
308 
resetLookupFileCacheInfo309     void reset(const Module *NewRequestingModule,
310                ConstSearchDirIterator NewStartIt) {
311       RequestingModule = NewRequestingModule;
312       StartIt = NewStartIt;
313       MappedName = nullptr;
314     }
315   };
316   llvm::StringMap<LookupFileCacheInfo, llvm::BumpPtrAllocator> LookupFileCache;
317 
318   /// Collection mapping a framework or subframework
319   /// name like "Carbon" to the Carbon.framework directory.
320   llvm::StringMap<FrameworkCacheEntry, llvm::BumpPtrAllocator> FrameworkMap;
321 
322   /// Maps include file names (including the quotes or
323   /// angle brackets) to other include file names.  This is used to support the
324   /// include_alias pragma for Microsoft compatibility.
325   using IncludeAliasMap =
326       llvm::StringMap<std::string, llvm::BumpPtrAllocator>;
327   std::unique_ptr<IncludeAliasMap> IncludeAliases;
328 
329   /// This is a mapping from FileEntry -> HeaderMap, uniquing headermaps.
330   std::vector<std::pair<FileEntryRef, std::unique_ptr<HeaderMap>>> HeaderMaps;
331 
332   /// The mapping between modules and headers.
333   mutable ModuleMap ModMap;
334 
335   struct ModuleMapDirectoryState {
336     OptionalFileEntryRef ModuleMapFile;
337     enum {
338       Parsed,
339       Loaded,
340       Invalid,
341     } Status;
342   };
343 
344   /// Describes whether a given directory has a module map in it.
345   llvm::DenseMap<const DirectoryEntry *, ModuleMapDirectoryState>
346       DirectoryModuleMap;
347 
348   /// Set of module map files we've already loaded, and a flag indicating
349   /// whether they were valid or not.
350   llvm::DenseMap<const FileEntry *, bool> LoadedModuleMaps;
351 
352   /// Set of module map files we've already parsed, and a flag indicating
353   /// whether they were valid or not.
354   llvm::DenseMap<const FileEntry *, bool> ParsedModuleMaps;
355 
356   // A map of discovered headers with their associated include file name.
357   llvm::DenseMap<const FileEntry *, llvm::SmallString<64>> IncludeNames;
358 
359   /// Uniqued set of framework names, which is used to track which
360   /// headers were included as framework headers.
361   llvm::StringSet<llvm::BumpPtrAllocator> FrameworkNames;
362 
363   /// Entity used to resolve the identifier IDs of controlling
364   /// macros into IdentifierInfo pointers, and keep the identifire up to date,
365   /// as needed.
366   ExternalPreprocessorSource *ExternalLookup = nullptr;
367 
368   /// Entity used to look up stored header file information.
369   ExternalHeaderFileInfoSource *ExternalSource = nullptr;
370 
371   /// Scan all of the header maps at the beginning of SearchDirs and
372   /// map their keys to the SearchDir index of their header map.
373   void indexInitialHeaderMaps();
374 
375 public:
376   HeaderSearch(const HeaderSearchOptions &HSOpts, SourceManager &SourceMgr,
377                DiagnosticsEngine &Diags, const LangOptions &LangOpts,
378                const TargetInfo *Target);
379   HeaderSearch(const HeaderSearch &) = delete;
380   HeaderSearch &operator=(const HeaderSearch &) = delete;
381 
382   /// Retrieve the header-search options with which this header search
383   /// was initialized.
getHeaderSearchOpts()384   const HeaderSearchOptions &getHeaderSearchOpts() const { return HSOpts; }
385 
getFileMgr()386   FileManager &getFileMgr() const { return FileMgr; }
387 
getDiags()388   DiagnosticsEngine &getDiags() const { return Diags; }
389 
390   /// Interface for setting the file search paths.
391   void SetSearchPaths(std::vector<DirectoryLookup> dirs, unsigned angledDirIdx,
392                       unsigned systemDirIdx,
393                       llvm::DenseMap<unsigned, unsigned> searchDirToHSEntry);
394 
395   /// Add an additional search path.
396   void AddSearchPath(const DirectoryLookup &dir, bool isAngled);
397 
398   /// Add an additional system search path.
AddSystemSearchPath(const DirectoryLookup & dir)399   void AddSystemSearchPath(const DirectoryLookup &dir) {
400     SearchDirs.push_back(dir);
401     SearchDirsUsage.push_back(false);
402   }
403 
404   /// Set the list of system header prefixes.
SetSystemHeaderPrefixes(ArrayRef<std::pair<std::string,bool>> P)405   void SetSystemHeaderPrefixes(ArrayRef<std::pair<std::string, bool>> P) {
406     SystemHeaderPrefixes.assign(P.begin(), P.end());
407   }
408 
409   /// Checks whether the map exists or not.
HasIncludeAliasMap()410   bool HasIncludeAliasMap() const { return (bool)IncludeAliases; }
411 
412   /// Map the source include name to the dest include name.
413   ///
414   /// The Source should include the angle brackets or quotes, the dest
415   /// should not.  This allows for distinction between <> and "" headers.
AddIncludeAlias(StringRef Source,StringRef Dest)416   void AddIncludeAlias(StringRef Source, StringRef Dest) {
417     if (!IncludeAliases)
418       IncludeAliases.reset(new IncludeAliasMap);
419     (*IncludeAliases)[Source] = std::string(Dest);
420   }
421 
422   /// Maps one header file name to a different header
423   /// file name, for use with the include_alias pragma.  Note that the source
424   /// file name should include the angle brackets or quotes.  Returns StringRef
425   /// as null if the header cannot be mapped.
MapHeaderToIncludeAlias(StringRef Source)426   StringRef MapHeaderToIncludeAlias(StringRef Source) {
427     assert(IncludeAliases && "Trying to map headers when there's no map");
428 
429     // Do any filename replacements before anything else
430     IncludeAliasMap::const_iterator Iter = IncludeAliases->find(Source);
431     if (Iter != IncludeAliases->end())
432       return Iter->second;
433     return {};
434   }
435 
436   /// Set the hash to use for module cache paths.
setModuleHash(StringRef Hash)437   void setModuleHash(StringRef Hash) { ModuleHash = std::string(Hash); }
438 
439   /// Set the path to the module cache.
setModuleCachePath(StringRef CachePath)440   void setModuleCachePath(StringRef CachePath) {
441     ModuleCachePath = std::string(CachePath);
442   }
443 
444   /// Retrieve the module hash.
getModuleHash()445   StringRef getModuleHash() const { return ModuleHash; }
446 
447   /// Retrieve the path to the module cache.
getModuleCachePath()448   StringRef getModuleCachePath() const { return ModuleCachePath; }
449 
450   /// Forget everything we know about headers so far.
ClearFileInfo()451   void ClearFileInfo() {
452     FileInfo.clear();
453   }
454 
SetExternalLookup(ExternalPreprocessorSource * EPS)455   void SetExternalLookup(ExternalPreprocessorSource *EPS) {
456     ExternalLookup = EPS;
457   }
458 
getExternalLookup()459   ExternalPreprocessorSource *getExternalLookup() const {
460     return ExternalLookup;
461   }
462 
463   /// Set the external source of header information.
SetExternalSource(ExternalHeaderFileInfoSource * ES)464   void SetExternalSource(ExternalHeaderFileInfoSource *ES) {
465     ExternalSource = ES;
466   }
467 
468   /// Set the target information for the header search, if not
469   /// already known.
470   void setTarget(const TargetInfo &Target);
471 
472   /// Given a "foo" or \<foo> reference, look up the indicated file,
473   /// return null on failure.
474   ///
475   /// \returns If successful, this returns 'UsedDir', the DirectoryLookup member
476   /// the file was found in, or null if not applicable.
477   ///
478   /// \param IncludeLoc Used for diagnostics if valid.
479   ///
480   /// \param isAngled indicates whether the file reference is a <> reference.
481   ///
482   /// \param CurDir If non-null, the file was found in the specified directory
483   /// search location.  This is used to implement \#include_next.
484   ///
485   /// \param Includers Indicates where the \#including file(s) are, in case
486   /// relative searches are needed. In reverse order of inclusion.
487   ///
488   /// \param SearchPath If non-null, will be set to the search path relative
489   /// to which the file was found. If the include path is absolute, SearchPath
490   /// will be set to an empty string.
491   ///
492   /// \param RelativePath If non-null, will be set to the path relative to
493   /// SearchPath at which the file was found. This only differs from the
494   /// Filename for framework includes.
495   ///
496   /// \param SuggestedModule If non-null, and the file found is semantically
497   /// part of a known module, this will be set to the module that should
498   /// be imported instead of preprocessing/parsing the file found.
499   ///
500   /// \param IsMapped If non-null, and the search involved header maps, set to
501   /// true.
502   ///
503   /// \param IsFrameworkFound If non-null, will be set to true if a framework is
504   /// found in any of searched SearchDirs. Will be set to false if a framework
505   /// is found only through header maps. Doesn't guarantee the requested file is
506   /// found.
507   OptionalFileEntryRef LookupFile(
508       StringRef Filename, SourceLocation IncludeLoc, bool isAngled,
509       ConstSearchDirIterator FromDir, ConstSearchDirIterator *CurDir,
510       ArrayRef<std::pair<OptionalFileEntryRef, DirectoryEntryRef>> Includers,
511       SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
512       Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule,
513       bool *IsMapped, bool *IsFrameworkFound, bool SkipCache = false,
514       bool BuildSystemModule = false, bool OpenFile = true,
515       bool CacheFailures = true);
516 
517   /// Look up a subframework for the specified \#include file.
518   ///
519   /// For example, if \#include'ing <HIToolbox/HIToolbox.h> from
520   /// within ".../Carbon.framework/Headers/Carbon.h", check to see if
521   /// HIToolbox is a subframework within Carbon.framework.  If so, return
522   /// the FileEntry for the designated file, otherwise return null.
523   OptionalFileEntryRef LookupSubframeworkHeader(
524       StringRef Filename, FileEntryRef ContextFileEnt,
525       SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
526       Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule);
527 
528   /// Look up the specified framework name in our framework cache.
529   /// \returns The DirectoryEntry it is in if we know, null otherwise.
LookupFrameworkCache(StringRef FWName)530   FrameworkCacheEntry &LookupFrameworkCache(StringRef FWName) {
531     return FrameworkMap[FWName];
532   }
533 
534   /// Mark the specified file as a target of a \#include,
535   /// \#include_next, or \#import directive.
536   ///
537   /// \return false if \#including the file will have no effect or true
538   /// if we should include it.
539   ///
540   /// \param M The module to which `File` belongs (this should usually be the
541   /// SuggestedModule returned by LookupFile/LookupSubframeworkHeader)
542   bool ShouldEnterIncludeFile(Preprocessor &PP, FileEntryRef File,
543                               bool isImport, bool ModulesEnabled, Module *M,
544                               bool &IsFirstIncludeOfFile);
545 
546   /// Return whether the specified file is a normal header,
547   /// a system header, or a C++ friendly system header.
getFileDirFlavor(FileEntryRef File)548   SrcMgr::CharacteristicKind getFileDirFlavor(FileEntryRef File) {
549     if (const HeaderFileInfo *HFI = getExistingFileInfo(File))
550       return (SrcMgr::CharacteristicKind)HFI->DirInfo;
551     return (SrcMgr::CharacteristicKind)HeaderFileInfo().DirInfo;
552   }
553 
554   /// Mark the specified file as a "once only" file due to
555   /// \#pragma once.
MarkFileIncludeOnce(FileEntryRef File)556   void MarkFileIncludeOnce(FileEntryRef File) {
557     getFileInfo(File).isPragmaOnce = true;
558   }
559 
560   /// Mark the specified file as a system header, e.g. due to
561   /// \#pragma GCC system_header.
MarkFileSystemHeader(FileEntryRef File)562   void MarkFileSystemHeader(FileEntryRef File) {
563     getFileInfo(File).DirInfo = SrcMgr::C_System;
564   }
565 
566   /// Mark the specified file as part of a module.
567   void MarkFileModuleHeader(FileEntryRef FE, ModuleMap::ModuleHeaderRole Role,
568                             bool isCompilingModuleHeader);
569 
570   /// Mark the specified file as having a controlling macro.
571   ///
572   /// This is used by the multiple-include optimization to eliminate
573   /// no-op \#includes.
SetFileControllingMacro(FileEntryRef File,const IdentifierInfo * ControllingMacro)574   void SetFileControllingMacro(FileEntryRef File,
575                                const IdentifierInfo *ControllingMacro) {
576     getFileInfo(File).LazyControllingMacro = ControllingMacro;
577   }
578 
579   /// Determine whether this file is intended to be safe from
580   /// multiple inclusions, e.g., it has \#pragma once or a controlling
581   /// macro.
582   ///
583   /// This routine does not consider the effect of \#import
584   bool isFileMultipleIncludeGuarded(FileEntryRef File) const;
585 
586   /// Determine whether the given file is known to have ever been \#imported.
hasFileBeenImported(FileEntryRef File)587   bool hasFileBeenImported(FileEntryRef File) const {
588     const HeaderFileInfo *FI = getExistingFileInfo(File);
589     return FI && FI->isImport;
590   }
591 
592   /// Determine which HeaderSearchOptions::UserEntries have been successfully
593   /// used so far and mark their index with 'true' in the resulting bit vector.
594   /// Note: implicit module maps don't contribute to entry usage.
595   std::vector<bool> computeUserEntryUsage() const;
596 
597   /// Collect which HeaderSearchOptions::VFSOverlayFiles have been meaningfully
598   /// used so far and mark their index with 'true' in the resulting bit vector.
599   ///
600   /// Note: this ignores VFSs that redirect non-affecting files such as unused
601   /// modulemaps.
602   std::vector<bool> collectVFSUsageAndClear() const;
603 
604   /// This method returns a HeaderMap for the specified
605   /// FileEntry, uniquing them through the 'HeaderMaps' datastructure.
606   const HeaderMap *CreateHeaderMap(FileEntryRef FE);
607 
608   /// Get filenames for all registered header maps.
609   void getHeaderMapFileNames(SmallVectorImpl<std::string> &Names) const;
610 
611   /// Retrieve the name of the cached module file that should be used
612   /// to load the given module.
613   ///
614   /// \param Module The module whose module file name will be returned.
615   ///
616   /// \returns The name of the module file that corresponds to this module,
617   /// or an empty string if this module does not correspond to any module file.
618   std::string getCachedModuleFileName(Module *Module);
619 
620   /// Retrieve the name of the prebuilt module file that should be used
621   /// to load a module with the given name.
622   ///
623   /// \param ModuleName The module whose module file name will be returned.
624   ///
625   /// \param FileMapOnly If true, then only look in the explicit module name
626   //  to file name map and skip the directory search.
627   ///
628   /// \returns The name of the module file that corresponds to this module,
629   /// or an empty string if this module does not correspond to any module file.
630   std::string getPrebuiltModuleFileName(StringRef ModuleName,
631                                         bool FileMapOnly = false);
632 
633   /// Retrieve the name of the prebuilt module file that should be used
634   /// to load the given module.
635   ///
636   /// \param Module The module whose module file name will be returned.
637   ///
638   /// \returns The name of the module file that corresponds to this module,
639   /// or an empty string if this module does not correspond to any module file.
640   std::string getPrebuiltImplicitModuleFileName(Module *Module);
641 
642   /// Retrieve the name of the (to-be-)cached module file that should
643   /// be used to load a module with the given name.
644   ///
645   /// \param ModuleName The module whose module file name will be returned.
646   ///
647   /// \param ModuleMapPath A path that when combined with \c ModuleName
648   /// uniquely identifies this module. See Module::ModuleMap.
649   ///
650   /// \returns The name of the module file that corresponds to this module,
651   /// or an empty string if this module does not correspond to any module file.
652   std::string getCachedModuleFileName(StringRef ModuleName,
653                                       StringRef ModuleMapPath);
654 
655   /// Lookup a module Search for a module with the given name.
656   ///
657   /// \param ModuleName The name of the module we're looking for.
658   ///
659   /// \param ImportLoc Location of the module include/import.
660   ///
661   /// \param AllowSearch Whether we are allowed to search in the various
662   /// search directories to produce a module definition. If not, this lookup
663   /// will only return an already-known module.
664   ///
665   /// \param AllowExtraModuleMapSearch Whether we allow to search modulemaps
666   /// in subdirectories.
667   ///
668   /// \returns The module with the given name.
669   Module *lookupModule(StringRef ModuleName,
670                        SourceLocation ImportLoc = SourceLocation(),
671                        bool AllowSearch = true,
672                        bool AllowExtraModuleMapSearch = false);
673 
674   /// Try to find a module map file in the given directory, returning
675   /// \c nullopt if none is found.
676   OptionalFileEntryRef lookupModuleMapFile(DirectoryEntryRef Dir,
677                                            bool IsFramework);
678 
679   /// Determine whether there is a module map that may map the header
680   /// with the given file name to a (sub)module.
681   /// Always returns false if modules are disabled.
682   ///
683   /// \param Filename The name of the file.
684   ///
685   /// \param Root The "root" directory, at which we should stop looking for
686   /// module maps.
687   ///
688   /// \param IsSystem Whether the directories we're looking at are system
689   /// header directories.
690   bool hasModuleMap(StringRef Filename, const DirectoryEntry *Root,
691                     bool IsSystem);
692 
693   /// Retrieve the module that corresponds to the given file, if any.
694   ///
695   /// \param File The header that we wish to map to a module.
696   /// \param AllowTextual Whether we want to find textual headers too.
697   ModuleMap::KnownHeader findModuleForHeader(FileEntryRef File,
698                                              bool AllowTextual = false,
699                                              bool AllowExcluded = false) const;
700 
701   /// Retrieve all the modules corresponding to the given file.
702   ///
703   /// \ref findModuleForHeader should typically be used instead of this.
704   ArrayRef<ModuleMap::KnownHeader>
705   findAllModulesForHeader(FileEntryRef File) const;
706 
707   /// Like \ref findAllModulesForHeader, but do not attempt to infer module
708   /// ownership from umbrella headers if we've not already done so.
709   ArrayRef<ModuleMap::KnownHeader>
710   findResolvedModulesForHeader(FileEntryRef File) const;
711 
712   /// Read the contents of the given module map file.
713   ///
714   /// \param File The module map file.
715   /// \param IsSystem Whether this file is in a system header directory.
716   /// \param ID If the module map file is already mapped (perhaps as part of
717   ///        processing a preprocessed module), the ID of the file.
718   /// \param Offset [inout] An offset within ID to start parsing. On exit,
719   ///        filled by the end of the parsed contents (either EOF or the
720   ///        location of an end-of-module-map pragma).
721   /// \param OriginalModuleMapFile The original path to the module map file,
722   ///        used to resolve paths within the module (this is required when
723   ///        building the module from preprocessed source).
724   /// \returns true if an error occurred, false otherwise.
725   bool parseAndLoadModuleMapFile(FileEntryRef File, bool IsSystem,
726                                  FileID ID = FileID(),
727                                  unsigned *Offset = nullptr,
728                                  StringRef OriginalModuleMapFile = StringRef());
729 
730   /// Collect the set of all known, top-level modules.
731   ///
732   /// \param Modules Will be filled with the set of known, top-level modules.
733   void collectAllModules(SmallVectorImpl<Module *> &Modules);
734 
735   /// Load all known, top-level system modules.
736   void loadTopLevelSystemModules();
737 
738 private:
739   /// Lookup a module with the given module name and search-name.
740   ///
741   /// \param ModuleName The name of the module we're looking for.
742   ///
743   /// \param SearchName The "search-name" to derive filesystem paths from
744   /// when looking for the module map; this is usually equal to ModuleName,
745   /// but for compatibility with some buggy frameworks, additional attempts
746   /// may be made to find the module under a related-but-different search-name.
747   ///
748   /// \param ImportLoc Location of the module include/import.
749   ///
750   /// \param AllowExtraModuleMapSearch Whether we allow to search modulemaps
751   /// in subdirectories.
752   ///
753   /// \returns The module named ModuleName.
754   Module *lookupModule(StringRef ModuleName, StringRef SearchName,
755                        SourceLocation ImportLoc,
756                        bool AllowExtraModuleMapSearch = false);
757 
758   /// Retrieve the name of the (to-be-)cached module file that should
759   /// be used to load a module with the given name.
760   ///
761   /// \param ModuleName The module whose module file name will be returned.
762   ///
763   /// \param ModuleMapPath A path that when combined with \c ModuleName
764   /// uniquely identifies this module. See Module::ModuleMap.
765   ///
766   /// \param CachePath A path to the module cache.
767   ///
768   /// \returns The name of the module file that corresponds to this module,
769   /// or an empty string if this module does not correspond to any module file.
770   std::string getCachedModuleFileNameImpl(StringRef ModuleName,
771                                           StringRef ModuleMapPath,
772                                           StringRef CachePath);
773 
774   /// Retrieve a module with the given name, which may be part of the
775   /// given framework.
776   ///
777   /// \param Name The name of the module to retrieve.
778   ///
779   /// \param Dir The framework directory (e.g., ModuleName.framework).
780   ///
781   /// \param IsSystem Whether the framework directory is part of the system
782   /// frameworks.
783   ///
784   /// \returns The module, if found; otherwise, null.
785   Module *loadFrameworkModule(StringRef Name, DirectoryEntryRef Dir,
786                               bool IsSystem);
787 
788   /// Load all of the module maps within the immediate subdirectories
789   /// of the given search directory.
790   void loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir);
791 
792   /// Find and suggest a usable module for the given file.
793   ///
794   /// \return \c true if the file can be used, \c false if we are not permitted to
795   ///         find this file due to requirements from \p RequestingModule.
796   bool findUsableModuleForHeader(FileEntryRef File, const DirectoryEntry *Root,
797                                  Module *RequestingModule,
798                                  ModuleMap::KnownHeader *SuggestedModule,
799                                  bool IsSystemHeaderDir);
800 
801   /// Find and suggest a usable module for the given file, which is part of
802   /// the specified framework.
803   ///
804   /// \return \c true if the file can be used, \c false if we are not permitted to
805   ///         find this file due to requirements from \p RequestingModule.
806   bool findUsableModuleForFrameworkHeader(
807       FileEntryRef File, StringRef FrameworkName, Module *RequestingModule,
808       ModuleMap::KnownHeader *SuggestedModule, bool IsSystemFramework);
809 
810   /// Look up the file with the specified name and determine its owning
811   /// module.
812   OptionalFileEntryRef
813   getFileAndSuggestModule(StringRef FileName, SourceLocation IncludeLoc,
814                           const DirectoryEntry *Dir, bool IsSystemHeaderDir,
815                           Module *RequestingModule,
816                           ModuleMap::KnownHeader *SuggestedModule,
817                           bool OpenFile = true, bool CacheFailures = true);
818 
819   /// Cache the result of a successful lookup at the given include location
820   /// using the search path at \c HitIt.
821   void cacheLookupSuccess(LookupFileCacheInfo &CacheLookup,
822                           ConstSearchDirIterator HitIt,
823                           SourceLocation IncludeLoc);
824 
825   /// Note that a lookup at the given include location was successful using the
826   /// search path at index `HitIdx`.
827   void noteLookupUsage(unsigned HitIdx, SourceLocation IncludeLoc);
828 
829 public:
830   /// Retrieve the module map.
getModuleMap()831   ModuleMap &getModuleMap() { return ModMap; }
832 
833   /// Retrieve the module map.
getModuleMap()834   const ModuleMap &getModuleMap() const { return ModMap; }
835 
header_file_size()836   unsigned header_file_size() const { return FileInfo.size(); }
837 
838   /// Return the HeaderFileInfo structure for the specified FileEntry, in
839   /// preparation for updating it in some way.
840   HeaderFileInfo &getFileInfo(FileEntryRef FE);
841 
842   /// Return the HeaderFileInfo structure for the specified FileEntry, if it has
843   /// ever been filled in (either locally or externally).
844   const HeaderFileInfo *getExistingFileInfo(FileEntryRef FE) const;
845 
846   /// Return the headerFileInfo structure for the specified FileEntry, if it has
847   /// ever been filled in locally.
848   const HeaderFileInfo *getExistingLocalFileInfo(FileEntryRef FE) const;
849 
search_dir_begin()850   SearchDirIterator search_dir_begin() { return {*this, 0}; }
search_dir_end()851   SearchDirIterator search_dir_end() { return {*this, SearchDirs.size()}; }
search_dir_range()852   SearchDirRange search_dir_range() {
853     return {search_dir_begin(), search_dir_end()};
854   }
855 
search_dir_begin()856   ConstSearchDirIterator search_dir_begin() const { return quoted_dir_begin(); }
search_dir_nth(size_t n)857   ConstSearchDirIterator search_dir_nth(size_t n) const {
858     assert(n < SearchDirs.size());
859     return {*this, n};
860   }
search_dir_end()861   ConstSearchDirIterator search_dir_end() const { return system_dir_end(); }
search_dir_range()862   ConstSearchDirRange search_dir_range() const {
863     return {search_dir_begin(), search_dir_end()};
864   }
865 
search_dir_size()866   unsigned search_dir_size() const { return SearchDirs.size(); }
867 
quoted_dir_begin()868   ConstSearchDirIterator quoted_dir_begin() const { return {*this, 0}; }
quoted_dir_end()869   ConstSearchDirIterator quoted_dir_end() const { return angled_dir_begin(); }
870 
angled_dir_begin()871   ConstSearchDirIterator angled_dir_begin() const {
872     return {*this, AngledDirIdx};
873   }
angled_dir_end()874   ConstSearchDirIterator angled_dir_end() const { return system_dir_begin(); }
875 
system_dir_begin()876   ConstSearchDirIterator system_dir_begin() const {
877     return {*this, SystemDirIdx};
878   }
system_dir_end()879   ConstSearchDirIterator system_dir_end() const {
880     return {*this, SearchDirs.size()};
881   }
882 
883   /// Get the index of the given search directory.
884   unsigned searchDirIdx(const DirectoryLookup &DL) const;
885 
886   /// Retrieve a uniqued framework name.
887   StringRef getUniqueFrameworkName(StringRef Framework);
888 
889   /// Retrieve the include name for the header.
890   ///
891   /// \param File The entry for a given header.
892   /// \returns The name of how the file was included when the header's location
893   /// was resolved.
894   StringRef getIncludeNameForHeader(const FileEntry *File) const;
895 
896   /// Suggest a path by which the specified file could be found, for use in
897   /// diagnostics to suggest a #include. Returned path will only contain forward
898   /// slashes as separators. MainFile is the absolute path of the file that we
899   /// are generating the diagnostics for. It will try to shorten the path using
900   /// MainFile location, if none of the include search directories were prefix
901   /// of File.
902   ///
903   /// \param IsAngled If non-null, filled in to indicate whether the suggested
904   ///        path should be referenced as <Header.h> instead of "Header.h".
905   std::string suggestPathToFileForDiagnostics(FileEntryRef File,
906                                               llvm::StringRef MainFile,
907                                               bool *IsAngled = nullptr) const;
908 
909   /// Suggest a path by which the specified file could be found, for use in
910   /// diagnostics to suggest a #include. Returned path will only contain forward
911   /// slashes as separators. MainFile is the absolute path of the file that we
912   /// are generating the diagnostics for. It will try to shorten the path using
913   /// MainFile location, if none of the include search directories were prefix
914   /// of File.
915   ///
916   /// \param WorkingDir If non-empty, this will be prepended to search directory
917   /// paths that are relative.
918   std::string suggestPathToFileForDiagnostics(llvm::StringRef File,
919                                               llvm::StringRef WorkingDir,
920                                               llvm::StringRef MainFile,
921                                               bool *IsAngled = nullptr) const;
922 
923   void PrintStats();
924 
925   size_t getTotalMemory() const;
926 
927 private:
928   /// Describes what happened when we tried to load or parse a module map file.
929   enum ModuleMapResult {
930     /// The module map file had already been processed.
931     MMR_AlreadyProcessed,
932 
933     /// The module map file was processed by this invocation.
934     MMR_NewlyProcessed,
935 
936     /// There is was directory with the given name.
937     MMR_NoDirectory,
938 
939     /// There was either no module map file or the module map file was
940     /// invalid.
941     MMR_InvalidModuleMap
942   };
943 
944   ModuleMapResult parseAndLoadModuleMapFileImpl(FileEntryRef File,
945                                                 bool IsSystem,
946                                                 DirectoryEntryRef Dir,
947                                                 FileID ID = FileID(),
948                                                 unsigned *Offset = nullptr);
949 
950   ModuleMapResult parseModuleMapFileImpl(FileEntryRef File, bool IsSystem,
951                                          DirectoryEntryRef Dir,
952                                          FileID ID = FileID());
953 
954   /// Try to load the module map file in the given directory.
955   ///
956   /// \param DirName The name of the directory where we will look for a module
957   /// map file.
958   /// \param IsSystem Whether this is a system header directory.
959   /// \param IsFramework Whether this is a framework directory.
960   ///
961   /// \returns The result of attempting to load the module map file from the
962   /// named directory.
963   ModuleMapResult parseAndLoadModuleMapFile(StringRef DirName, bool IsSystem,
964                                             bool IsFramework);
965 
966   /// Try to load the module map file in the given directory.
967   ///
968   /// \param Dir The directory where we will look for a module map file.
969   /// \param IsSystem Whether this is a system header directory.
970   /// \param IsFramework Whether this is a framework directory.
971   ///
972   /// \returns The result of attempting to load the module map file from the
973   /// named directory.
974   ModuleMapResult parseAndLoadModuleMapFile(DirectoryEntryRef Dir,
975                                             bool IsSystem, bool IsFramework);
976 
977   ModuleMapResult parseModuleMapFile(StringRef DirName, bool IsSystem,
978                                      bool IsFramework);
979   ModuleMapResult parseModuleMapFile(DirectoryEntryRef Dir, bool IsSystem,
980                                      bool IsFramework);
981 };
982 
983 /// Apply the header search options to get given HeaderSearch object.
984 void ApplyHeaderSearchOptions(HeaderSearch &HS,
985                               const HeaderSearchOptions &HSOpts,
986                               const LangOptions &Lang,
987                               const llvm::Triple &triple);
988 
989 } // namespace clang
990 
991 #endif // LLVM_CLANG_LEX_HEADERSEARCH_H
992