]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/include/clang/Lex/HeaderSearch.h
Merge clang 7.0.1 and several follow-up changes
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / include / clang / Lex / HeaderSearch.h
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/Basic/SourceLocation.h"
18 #include "clang/Basic/SourceManager.h"
19 #include "clang/Lex/DirectoryLookup.h"
20 #include "clang/Lex/ModuleMap.h"
21 #include "llvm/ADT/ArrayRef.h"
22 #include "llvm/ADT/DenseMap.h"
23 #include "llvm/ADT/StringMap.h"
24 #include "llvm/ADT/StringSet.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/Support/Allocator.h"
27 #include <cassert>
28 #include <cstddef>
29 #include <memory>
30 #include <string>
31 #include <utility>
32 #include <vector>
33
34 namespace clang {
35
36 class DiagnosticsEngine;
37 class DirectoryEntry;
38 class ExternalPreprocessorSource;
39 class FileEntry;
40 class FileManager;
41 class HeaderMap;
42 class HeaderSearchOptions;
43 class IdentifierInfo;
44 class LangOptions;
45 class Module;
46 class Preprocessor;
47 class TargetInfo;
48
49 /// The preprocessor keeps track of this information for each
50 /// file that is \#included.
51 struct HeaderFileInfo {
52   /// True if this is a \#import'd or \#pragma once file.
53   unsigned isImport : 1;
54
55   /// True if this is a \#pragma once file.
56   unsigned isPragmaOnce : 1;
57
58   /// DirInfo - Keep track of whether this is a system header, and if so,
59   /// whether it is C++ clean or not.  This can be set by the include paths or
60   /// by \#pragma gcc system_header.  This is an instance of
61   /// SrcMgr::CharacteristicKind.
62   unsigned DirInfo : 3;
63
64   /// Whether this header file info was supplied by an external source,
65   /// and has not changed since.
66   unsigned External : 1;
67
68   /// Whether this header is part of a module.
69   unsigned isModuleHeader : 1;
70
71   /// Whether this header is part of the module that we are building.
72   unsigned isCompilingModuleHeader : 1;
73
74   /// Whether this structure is considered to already have been
75   /// "resolved", meaning that it was loaded from the external source.
76   unsigned Resolved : 1;
77
78   /// Whether this is a header inside a framework that is currently
79   /// being built.
80   ///
81   /// When a framework is being built, the headers have not yet been placed
82   /// into the appropriate framework subdirectories, and therefore are
83   /// provided via a header map. This bit indicates when this is one of
84   /// those framework headers.
85   unsigned IndexHeaderMapHeader : 1;
86
87   /// Whether this file has been looked up as a header.
88   unsigned IsValid : 1;
89
90   /// The number of times the file has been included already.
91   unsigned short NumIncludes = 0;
92
93   /// The ID number of the controlling macro.
94   ///
95   /// This ID number will be non-zero when there is a controlling
96   /// macro whose IdentifierInfo may not yet have been loaded from
97   /// external storage.
98   unsigned ControllingMacroID = 0;
99
100   /// If this file has a \#ifndef XXX (or equivalent) guard that
101   /// protects the entire contents of the file, this is the identifier
102   /// for the macro that controls whether or not it has any effect.
103   ///
104   /// Note: Most clients should use getControllingMacro() to access
105   /// the controlling macro of this header, since
106   /// getControllingMacro() is able to load a controlling macro from
107   /// external storage.
108   const IdentifierInfo *ControllingMacro = nullptr;
109
110   /// If this header came from a framework include, this is the name
111   /// of the framework.
112   StringRef Framework;
113
114   HeaderFileInfo()
115       : isImport(false), isPragmaOnce(false), DirInfo(SrcMgr::C_User),
116         External(false), isModuleHeader(false), isCompilingModuleHeader(false),
117         Resolved(false), IndexHeaderMapHeader(false), IsValid(false)  {}
118
119   /// Retrieve the controlling macro for this header file, if
120   /// any.
121   const IdentifierInfo *
122   getControllingMacro(ExternalPreprocessorSource *External);
123
124   /// Determine whether this is a non-default header file info, e.g.,
125   /// it corresponds to an actual header we've included or tried to include.
126   bool isNonDefault() const {
127     return isImport || isPragmaOnce || NumIncludes || ControllingMacro ||
128       ControllingMacroID;
129   }
130 };
131
132 /// An external source of header file information, which may supply
133 /// information about header files already included.
134 class ExternalHeaderFileInfoSource {
135 public:
136   virtual ~ExternalHeaderFileInfoSource();
137
138   /// Retrieve the header file information for the given file entry.
139   ///
140   /// \returns Header file information for the given file entry, with the
141   /// \c External bit set. If the file entry is not known, return a
142   /// default-constructed \c HeaderFileInfo.
143   virtual HeaderFileInfo GetHeaderFileInfo(const FileEntry *FE) = 0;
144 };
145
146 /// Encapsulates the information needed to find the file referenced
147 /// by a \#include or \#include_next, (sub-)framework lookup, etc.
148 class HeaderSearch {
149   friend class DirectoryLookup;
150
151   /// This structure is used to record entries in our framework cache.
152   struct FrameworkCacheEntry {
153     /// The directory entry which should be used for the cached framework.
154     const DirectoryEntry *Directory;
155
156     /// Whether this framework has been "user-specified" to be treated as if it
157     /// were a system framework (even if it was found outside a system framework
158     /// directory).
159     bool IsUserSpecifiedSystemFramework;
160   };
161
162   /// Header-search options used to initialize this header search.
163   std::shared_ptr<HeaderSearchOptions> HSOpts;
164
165   DiagnosticsEngine &Diags;
166   FileManager &FileMgr;
167
168   /// \#include search path information.  Requests for \#include "x" search the
169   /// directory of the \#including file first, then each directory in SearchDirs
170   /// consecutively. Requests for <x> search the current dir first, then each
171   /// directory in SearchDirs, starting at AngledDirIdx, consecutively.  If
172   /// NoCurDirSearch is true, then the check for the file in the current
173   /// directory is suppressed.
174   std::vector<DirectoryLookup> SearchDirs;
175   unsigned AngledDirIdx = 0;
176   unsigned SystemDirIdx = 0;
177   bool NoCurDirSearch = false;
178
179   /// \#include prefixes for which the 'system header' property is
180   /// overridden.
181   ///
182   /// For a \#include "x" or \#include \<x> directive, the last string in this
183   /// list which is a prefix of 'x' determines whether the file is treated as
184   /// a system header.
185   std::vector<std::pair<std::string, bool>> SystemHeaderPrefixes;
186
187   /// The path to the module cache.
188   std::string ModuleCachePath;
189
190   /// All of the preprocessor-specific data about files that are
191   /// included, indexed by the FileEntry's UID.
192   mutable std::vector<HeaderFileInfo> FileInfo;
193
194   /// Keeps track of each lookup performed by LookupFile.
195   struct LookupFileCacheInfo {
196     /// Starting index in SearchDirs that the cached search was performed from.
197     /// If there is a hit and this value doesn't match the current query, the
198     /// cache has to be ignored.
199     unsigned StartIdx = 0;
200
201     /// The entry in SearchDirs that satisfied the query.
202     unsigned HitIdx = 0;
203
204     /// This is non-null if the original filename was mapped to a framework
205     /// include via a headermap.
206     const char *MappedName = nullptr;
207
208     /// Default constructor -- Initialize all members with zero.
209     LookupFileCacheInfo() = default;
210
211     void reset(unsigned StartIdx) {
212       this->StartIdx = StartIdx;
213       this->MappedName = nullptr;
214     }
215   };
216   llvm::StringMap<LookupFileCacheInfo, llvm::BumpPtrAllocator> LookupFileCache;
217
218   /// Collection mapping a framework or subframework
219   /// name like "Carbon" to the Carbon.framework directory.
220   llvm::StringMap<FrameworkCacheEntry, llvm::BumpPtrAllocator> FrameworkMap;
221
222   /// IncludeAliases - maps include file names (including the quotes or
223   /// angle brackets) to other include file names.  This is used to support the
224   /// include_alias pragma for Microsoft compatibility.
225   using IncludeAliasMap =
226       llvm::StringMap<std::string, llvm::BumpPtrAllocator>;
227   std::unique_ptr<IncludeAliasMap> IncludeAliases;
228
229   /// HeaderMaps - This is a mapping from FileEntry -> HeaderMap, uniquing
230   /// headermaps.  This vector owns the headermap.
231   std::vector<std::pair<const FileEntry *, const HeaderMap *>> HeaderMaps;
232
233   /// The mapping between modules and headers.
234   mutable ModuleMap ModMap;
235
236   /// Describes whether a given directory has a module map in it.
237   llvm::DenseMap<const DirectoryEntry *, bool> DirectoryHasModuleMap;
238
239   /// Set of module map files we've already loaded, and a flag indicating
240   /// whether they were valid or not.
241   llvm::DenseMap<const FileEntry *, bool> LoadedModuleMaps;
242
243   /// Uniqued set of framework names, which is used to track which
244   /// headers were included as framework headers.
245   llvm::StringSet<llvm::BumpPtrAllocator> FrameworkNames;
246
247   /// Entity used to resolve the identifier IDs of controlling
248   /// macros into IdentifierInfo pointers, and keep the identifire up to date,
249   /// as needed.
250   ExternalPreprocessorSource *ExternalLookup = nullptr;
251
252   /// Entity used to look up stored header file information.
253   ExternalHeaderFileInfoSource *ExternalSource = nullptr;
254
255   // Various statistics we track for performance analysis.
256   unsigned NumIncluded = 0;
257   unsigned NumMultiIncludeFileOptzn = 0;
258   unsigned NumFrameworkLookups = 0;
259   unsigned NumSubFrameworkLookups = 0;
260
261 public:
262   HeaderSearch(std::shared_ptr<HeaderSearchOptions> HSOpts,
263                SourceManager &SourceMgr, DiagnosticsEngine &Diags,
264                const LangOptions &LangOpts, const TargetInfo *Target);
265   HeaderSearch(const HeaderSearch &) = delete;
266   HeaderSearch &operator=(const HeaderSearch &) = delete;
267   ~HeaderSearch();
268
269   /// Retrieve the header-search options with which this header search
270   /// was initialized.
271   HeaderSearchOptions &getHeaderSearchOpts() const { return *HSOpts; }
272
273   FileManager &getFileMgr() const { return FileMgr; }
274
275   DiagnosticsEngine &getDiags() const { return Diags; }
276
277   /// Interface for setting the file search paths.
278   void SetSearchPaths(const std::vector<DirectoryLookup> &dirs,
279                       unsigned angledDirIdx, unsigned systemDirIdx,
280                       bool noCurDirSearch) {
281     assert(angledDirIdx <= systemDirIdx && systemDirIdx <= dirs.size() &&
282         "Directory indices are unordered");
283     SearchDirs = dirs;
284     AngledDirIdx = angledDirIdx;
285     SystemDirIdx = systemDirIdx;
286     NoCurDirSearch = noCurDirSearch;
287     //LookupFileCache.clear();
288   }
289
290   /// Add an additional search path.
291   void AddSearchPath(const DirectoryLookup &dir, bool isAngled) {
292     unsigned idx = isAngled ? SystemDirIdx : AngledDirIdx;
293     SearchDirs.insert(SearchDirs.begin() + idx, dir);
294     if (!isAngled)
295       AngledDirIdx++;
296     SystemDirIdx++;
297   }
298
299   /// Set the list of system header prefixes.
300   void SetSystemHeaderPrefixes(ArrayRef<std::pair<std::string, bool>> P) {
301     SystemHeaderPrefixes.assign(P.begin(), P.end());
302   }
303
304   /// Checks whether the map exists or not.
305   bool HasIncludeAliasMap() const { return (bool)IncludeAliases; }
306
307   /// Map the source include name to the dest include name.
308   ///
309   /// The Source should include the angle brackets or quotes, the dest
310   /// should not.  This allows for distinction between <> and "" headers.
311   void AddIncludeAlias(StringRef Source, StringRef Dest) {
312     if (!IncludeAliases)
313       IncludeAliases.reset(new IncludeAliasMap);
314     (*IncludeAliases)[Source] = Dest;
315   }
316
317   /// MapHeaderToIncludeAlias - Maps one header file name to a different header
318   /// file name, for use with the include_alias pragma.  Note that the source
319   /// file name should include the angle brackets or quotes.  Returns StringRef
320   /// as null if the header cannot be mapped.
321   StringRef MapHeaderToIncludeAlias(StringRef Source) {
322     assert(IncludeAliases && "Trying to map headers when there's no map");
323
324     // Do any filename replacements before anything else
325     IncludeAliasMap::const_iterator Iter = IncludeAliases->find(Source);
326     if (Iter != IncludeAliases->end())
327       return Iter->second;
328     return {};
329   }
330
331   /// Set the path to the module cache.
332   void setModuleCachePath(StringRef CachePath) {
333     ModuleCachePath = CachePath;
334   }
335
336   /// Retrieve the path to the module cache.
337   StringRef getModuleCachePath() const { return ModuleCachePath; }
338
339   /// Consider modules when including files from this directory.
340   void setDirectoryHasModuleMap(const DirectoryEntry* Dir) {
341     DirectoryHasModuleMap[Dir] = true;
342   }
343
344   /// Forget everything we know about headers so far.
345   void ClearFileInfo() {
346     FileInfo.clear();
347   }
348
349   void SetExternalLookup(ExternalPreprocessorSource *EPS) {
350     ExternalLookup = EPS;
351   }
352
353   ExternalPreprocessorSource *getExternalLookup() const {
354     return ExternalLookup;
355   }
356
357   /// Set the external source of header information.
358   void SetExternalSource(ExternalHeaderFileInfoSource *ES) {
359     ExternalSource = ES;
360   }
361
362   /// Set the target information for the header search, if not
363   /// already known.
364   void setTarget(const TargetInfo &Target);
365
366   /// Given a "foo" or \<foo> reference, look up the indicated file,
367   /// return null on failure.
368   ///
369   /// \returns If successful, this returns 'UsedDir', the DirectoryLookup member
370   /// the file was found in, or null if not applicable.
371   ///
372   /// \param IncludeLoc Used for diagnostics if valid.
373   ///
374   /// \param isAngled indicates whether the file reference is a <> reference.
375   ///
376   /// \param CurDir If non-null, the file was found in the specified directory
377   /// search location.  This is used to implement \#include_next.
378   ///
379   /// \param Includers Indicates where the \#including file(s) are, in case
380   /// relative searches are needed. In reverse order of inclusion.
381   ///
382   /// \param SearchPath If non-null, will be set to the search path relative
383   /// to which the file was found. If the include path is absolute, SearchPath
384   /// will be set to an empty string.
385   ///
386   /// \param RelativePath If non-null, will be set to the path relative to
387   /// SearchPath at which the file was found. This only differs from the
388   /// Filename for framework includes.
389   ///
390   /// \param SuggestedModule If non-null, and the file found is semantically
391   /// part of a known module, this will be set to the module that should
392   /// be imported instead of preprocessing/parsing the file found.
393   ///
394   /// \param IsMapped If non-null, and the search involved header maps, set to
395   /// true.
396   const FileEntry *LookupFile(
397       StringRef Filename, SourceLocation IncludeLoc, bool isAngled,
398       const DirectoryLookup *FromDir, const DirectoryLookup *&CurDir,
399       ArrayRef<std::pair<const FileEntry *, const DirectoryEntry *>> Includers,
400       SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
401       Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule,
402       bool *IsMapped, bool SkipCache = false, bool BuildSystemModule = false);
403
404   /// Look up a subframework for the specified \#include file.
405   ///
406   /// For example, if \#include'ing <HIToolbox/HIToolbox.h> from
407   /// within ".../Carbon.framework/Headers/Carbon.h", check to see if
408   /// HIToolbox is a subframework within Carbon.framework.  If so, return
409   /// the FileEntry for the designated file, otherwise return null.
410   const FileEntry *LookupSubframeworkHeader(
411       StringRef Filename, const FileEntry *RelativeFileEnt,
412       SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
413       Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule);
414
415   /// Look up the specified framework name in our framework cache.
416   /// \returns The DirectoryEntry it is in if we know, null otherwise.
417   FrameworkCacheEntry &LookupFrameworkCache(StringRef FWName) {
418     return FrameworkMap[FWName];
419   }
420
421   /// Mark the specified file as a target of a \#include,
422   /// \#include_next, or \#import directive.
423   ///
424   /// \return false if \#including the file will have no effect or true
425   /// if we should include it.
426   bool ShouldEnterIncludeFile(Preprocessor &PP, const FileEntry *File,
427                               bool isImport, bool ModulesEnabled,
428                               Module *CorrespondingModule);
429
430   /// Return whether the specified file is a normal header,
431   /// a system header, or a C++ friendly system header.
432   SrcMgr::CharacteristicKind getFileDirFlavor(const FileEntry *File) {
433     return (SrcMgr::CharacteristicKind)getFileInfo(File).DirInfo;
434   }
435
436   /// Mark the specified file as a "once only" file, e.g. due to
437   /// \#pragma once.
438   void MarkFileIncludeOnce(const FileEntry *File) {
439     HeaderFileInfo &FI = getFileInfo(File);
440     FI.isImport = true;
441     FI.isPragmaOnce = true;
442   }
443
444   /// Mark the specified file as a system header, e.g. due to
445   /// \#pragma GCC system_header.
446   void MarkFileSystemHeader(const FileEntry *File) {
447     getFileInfo(File).DirInfo = SrcMgr::C_System;
448   }
449
450   /// Mark the specified file as part of a module.
451   void MarkFileModuleHeader(const FileEntry *File,
452                             ModuleMap::ModuleHeaderRole Role,
453                             bool IsCompiledModuleHeader);
454
455   /// Increment the count for the number of times the specified
456   /// FileEntry has been entered.
457   void IncrementIncludeCount(const FileEntry *File) {
458     ++getFileInfo(File).NumIncludes;
459   }
460
461   /// Mark the specified file as having a controlling macro.
462   ///
463   /// This is used by the multiple-include optimization to eliminate
464   /// no-op \#includes.
465   void SetFileControllingMacro(const FileEntry *File,
466                                const IdentifierInfo *ControllingMacro) {
467     getFileInfo(File).ControllingMacro = ControllingMacro;
468   }
469
470   /// Return true if this is the first time encountering this header.
471   bool FirstTimeLexingFile(const FileEntry *File) {
472     return getFileInfo(File).NumIncludes == 1;
473   }
474
475   /// Determine whether this file is intended to be safe from
476   /// multiple inclusions, e.g., it has \#pragma once or a controlling
477   /// macro.
478   ///
479   /// This routine does not consider the effect of \#import
480   bool isFileMultipleIncludeGuarded(const FileEntry *File);
481
482   /// CreateHeaderMap - This method returns a HeaderMap for the specified
483   /// FileEntry, uniquing them through the 'HeaderMaps' datastructure.
484   const HeaderMap *CreateHeaderMap(const FileEntry *FE);
485
486   /// Get filenames for all registered header maps.
487   void getHeaderMapFileNames(SmallVectorImpl<std::string> &Names) const;
488
489   /// Retrieve the name of the cached module file that should be used
490   /// to load the given module.
491   ///
492   /// \param Module The module whose module file name will be returned.
493   ///
494   /// \returns The name of the module file that corresponds to this module,
495   /// or an empty string if this module does not correspond to any module file.
496   std::string getCachedModuleFileName(Module *Module);
497
498   /// Retrieve the name of the prebuilt module file that should be used
499   /// to load a module with the given name.
500   ///
501   /// \param ModuleName The module whose module file name will be returned.
502   ///
503   /// \param FileMapOnly If true, then only look in the explicit module name
504   //  to file name map and skip the directory search.
505   ///
506   /// \returns The name of the module file that corresponds to this module,
507   /// or an empty string if this module does not correspond to any module file.
508   std::string getPrebuiltModuleFileName(StringRef ModuleName,
509                                         bool FileMapOnly = false);
510
511   /// Retrieve the name of the (to-be-)cached module file that should
512   /// be used to load a module with the given name.
513   ///
514   /// \param ModuleName The module whose module file name will be returned.
515   ///
516   /// \param ModuleMapPath A path that when combined with \c ModuleName
517   /// uniquely identifies this module. See Module::ModuleMap.
518   ///
519   /// \returns The name of the module file that corresponds to this module,
520   /// or an empty string if this module does not correspond to any module file.
521   std::string getCachedModuleFileName(StringRef ModuleName,
522                                       StringRef ModuleMapPath);
523
524   /// Lookup a module Search for a module with the given name.
525   ///
526   /// \param ModuleName The name of the module we're looking for.
527   ///
528   /// \param AllowSearch Whether we are allowed to search in the various
529   /// search directories to produce a module definition. If not, this lookup
530   /// will only return an already-known module.
531   ///
532   /// \param AllowExtraModuleMapSearch Whether we allow to search modulemaps
533   /// in subdirectories.
534   ///
535   /// \returns The module with the given name.
536   Module *lookupModule(StringRef ModuleName, bool AllowSearch = true,
537                        bool AllowExtraModuleMapSearch = false);
538
539   /// Try to find a module map file in the given directory, returning
540   /// \c nullptr if none is found.
541   const FileEntry *lookupModuleMapFile(const DirectoryEntry *Dir,
542                                        bool IsFramework);
543
544   void IncrementFrameworkLookupCount() { ++NumFrameworkLookups; }
545
546   /// Determine whether there is a module map that may map the header
547   /// with the given file name to a (sub)module.
548   /// Always returns false if modules are disabled.
549   ///
550   /// \param Filename The name of the file.
551   ///
552   /// \param Root The "root" directory, at which we should stop looking for
553   /// module maps.
554   ///
555   /// \param IsSystem Whether the directories we're looking at are system
556   /// header directories.
557   bool hasModuleMap(StringRef Filename, const DirectoryEntry *Root,
558                     bool IsSystem);
559
560   /// Retrieve the module that corresponds to the given file, if any.
561   ///
562   /// \param File The header that we wish to map to a module.
563   /// \param AllowTextual Whether we want to find textual headers too.
564   ModuleMap::KnownHeader findModuleForHeader(const FileEntry *File,
565                                              bool AllowTextual = false) const;
566
567   /// Read the contents of the given module map file.
568   ///
569   /// \param File The module map file.
570   /// \param IsSystem Whether this file is in a system header directory.
571   /// \param ID If the module map file is already mapped (perhaps as part of
572   ///        processing a preprocessed module), the ID of the file.
573   /// \param Offset [inout] An offset within ID to start parsing. On exit,
574   ///        filled by the end of the parsed contents (either EOF or the
575   ///        location of an end-of-module-map pragma).
576   /// \param OriginalModuleMapFile The original path to the module map file,
577   ///        used to resolve paths within the module (this is required when
578   ///        building the module from preprocessed source).
579   /// \returns true if an error occurred, false otherwise.
580   bool loadModuleMapFile(const FileEntry *File, bool IsSystem,
581                          FileID ID = FileID(), unsigned *Offset = nullptr,
582                          StringRef OriginalModuleMapFile = StringRef());
583
584   /// Collect the set of all known, top-level modules.
585   ///
586   /// \param Modules Will be filled with the set of known, top-level modules.
587   void collectAllModules(SmallVectorImpl<Module *> &Modules);
588
589   /// Load all known, top-level system modules.
590   void loadTopLevelSystemModules();
591
592 private:
593   /// Lookup a module with the given module name and search-name.
594   ///
595   /// \param ModuleName The name of the module we're looking for.
596   ///
597   /// \param SearchName The "search-name" to derive filesystem paths from
598   /// when looking for the module map; this is usually equal to ModuleName,
599   /// but for compatibility with some buggy frameworks, additional attempts
600   /// may be made to find the module under a related-but-different search-name.
601   ///
602   /// \param AllowExtraModuleMapSearch Whether we allow to search modulemaps
603   /// in subdirectories.
604   ///
605   /// \returns The module named ModuleName.
606   Module *lookupModule(StringRef ModuleName, StringRef SearchName,
607                        bool AllowExtraModuleMapSearch = false);
608
609   /// Retrieve a module with the given name, which may be part of the
610   /// given framework.
611   ///
612   /// \param Name The name of the module to retrieve.
613   ///
614   /// \param Dir The framework directory (e.g., ModuleName.framework).
615   ///
616   /// \param IsSystem Whether the framework directory is part of the system
617   /// frameworks.
618   ///
619   /// \returns The module, if found; otherwise, null.
620   Module *loadFrameworkModule(StringRef Name,
621                               const DirectoryEntry *Dir,
622                               bool IsSystem);
623
624   /// Load all of the module maps within the immediate subdirectories
625   /// of the given search directory.
626   void loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir);
627
628   /// Find and suggest a usable module for the given file.
629   ///
630   /// \return \c true if the file can be used, \c false if we are not permitted to
631   ///         find this file due to requirements from \p RequestingModule.
632   bool findUsableModuleForHeader(const FileEntry *File,
633                                  const DirectoryEntry *Root,
634                                  Module *RequestingModule,
635                                  ModuleMap::KnownHeader *SuggestedModule,
636                                  bool IsSystemHeaderDir);
637
638   /// Find and suggest a usable module for the given file, which is part of
639   /// the specified framework.
640   ///
641   /// \return \c true if the file can be used, \c false if we are not permitted to
642   ///         find this file due to requirements from \p RequestingModule.
643   bool findUsableModuleForFrameworkHeader(
644       const FileEntry *File, StringRef FrameworkDir, Module *RequestingModule,
645       ModuleMap::KnownHeader *SuggestedModule, bool IsSystemFramework);
646
647   /// Look up the file with the specified name and determine its owning
648   /// module.
649   const FileEntry *
650   getFileAndSuggestModule(StringRef FileName, SourceLocation IncludeLoc,
651                           const DirectoryEntry *Dir, bool IsSystemHeaderDir,
652                           Module *RequestingModule,
653                           ModuleMap::KnownHeader *SuggestedModule);
654
655 public:
656   /// Retrieve the module map.
657   ModuleMap &getModuleMap() { return ModMap; }
658
659   /// Retrieve the module map.
660   const ModuleMap &getModuleMap() const { return ModMap; }
661
662   unsigned header_file_size() const { return FileInfo.size(); }
663
664   /// Return the HeaderFileInfo structure for the specified FileEntry,
665   /// in preparation for updating it in some way.
666   HeaderFileInfo &getFileInfo(const FileEntry *FE);
667
668   /// Return the HeaderFileInfo structure for the specified FileEntry,
669   /// if it has ever been filled in.
670   /// \param WantExternal Whether the caller wants purely-external header file
671   ///        info (where \p External is true).
672   const HeaderFileInfo *getExistingFileInfo(const FileEntry *FE,
673                                             bool WantExternal = true) const;
674
675   // Used by external tools
676   using search_dir_iterator = std::vector<DirectoryLookup>::const_iterator;
677
678   search_dir_iterator search_dir_begin() const { return SearchDirs.begin(); }
679   search_dir_iterator search_dir_end() const { return SearchDirs.end(); }
680   unsigned search_dir_size() const { return SearchDirs.size(); }
681
682   search_dir_iterator quoted_dir_begin() const {
683     return SearchDirs.begin();
684   }
685
686   search_dir_iterator quoted_dir_end() const {
687     return SearchDirs.begin() + AngledDirIdx;
688   }
689
690   search_dir_iterator angled_dir_begin() const {
691     return SearchDirs.begin() + AngledDirIdx;
692   }
693
694   search_dir_iterator angled_dir_end() const {
695     return SearchDirs.begin() + SystemDirIdx;
696   }
697
698   search_dir_iterator system_dir_begin() const {
699     return SearchDirs.begin() + SystemDirIdx;
700   }
701
702   search_dir_iterator system_dir_end() const { return SearchDirs.end(); }
703
704   /// Retrieve a uniqued framework name.
705   StringRef getUniqueFrameworkName(StringRef Framework);
706
707   /// Suggest a path by which the specified file could be found, for
708   /// use in diagnostics to suggest a #include.
709   ///
710   /// \param IsSystem If non-null, filled in to indicate whether the suggested
711   ///        path is relative to a system header directory.
712   std::string suggestPathToFileForDiagnostics(const FileEntry *File,
713                                               bool *IsSystem = nullptr);
714
715   /// Suggest a path by which the specified file could be found, for
716   /// use in diagnostics to suggest a #include.
717   ///
718   /// \param WorkingDir If non-empty, this will be prepended to search directory
719   /// paths that are relative.
720   std::string suggestPathToFileForDiagnostics(llvm::StringRef File,
721                                               llvm::StringRef WorkingDir,
722                                               bool *IsSystem = nullptr);
723
724   void PrintStats();
725
726   size_t getTotalMemory() const;
727
728 private:
729   /// Describes what happened when we tried to load a module map file.
730   enum LoadModuleMapResult {
731     /// The module map file had already been loaded.
732     LMM_AlreadyLoaded,
733
734     /// The module map file was loaded by this invocation.
735     LMM_NewlyLoaded,
736
737     /// There is was directory with the given name.
738     LMM_NoDirectory,
739
740     /// There was either no module map file or the module map file was
741     /// invalid.
742     LMM_InvalidModuleMap
743   };
744
745   LoadModuleMapResult loadModuleMapFileImpl(const FileEntry *File,
746                                             bool IsSystem,
747                                             const DirectoryEntry *Dir,
748                                             FileID ID = FileID(),
749                                             unsigned *Offset = nullptr);
750
751   /// Try to load the module map file in the given directory.
752   ///
753   /// \param DirName The name of the directory where we will look for a module
754   /// map file.
755   /// \param IsSystem Whether this is a system header directory.
756   /// \param IsFramework Whether this is a framework directory.
757   ///
758   /// \returns The result of attempting to load the module map file from the
759   /// named directory.
760   LoadModuleMapResult loadModuleMapFile(StringRef DirName, bool IsSystem,
761                                         bool IsFramework);
762
763   /// Try to load the module map file in the given directory.
764   ///
765   /// \param Dir The directory where we will look for a module map file.
766   /// \param IsSystem Whether this is a system header directory.
767   /// \param IsFramework Whether this is a framework directory.
768   ///
769   /// \returns The result of attempting to load the module map file from the
770   /// named directory.
771   LoadModuleMapResult loadModuleMapFile(const DirectoryEntry *Dir,
772                                         bool IsSystem, bool IsFramework);
773 };
774
775 } // namespace clang
776
777 #endif // LLVM_CLANG_LEX_HEADERSEARCH_H