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