clang 19.0.0git
ASTReader.h
Go to the documentation of this file.
1//===- ASTReader.h - AST File Reader ----------------------------*- 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 ASTReader class, which reads AST files.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_SERIALIZATION_ASTREADER_H
14#define LLVM_CLANG_SERIALIZATION_ASTREADER_H
15
16#include "clang/AST/Type.h"
22#include "clang/Basic/Version.h"
29#include "clang/Sema/Sema.h"
36#include "llvm/ADT/ArrayRef.h"
37#include "llvm/ADT/DenseMap.h"
38#include "llvm/ADT/DenseSet.h"
39#include "llvm/ADT/IntrusiveRefCntPtr.h"
40#include "llvm/ADT/MapVector.h"
41#include "llvm/ADT/PagedVector.h"
42#include "llvm/ADT/STLExtras.h"
43#include "llvm/ADT/SetVector.h"
44#include "llvm/ADT/SmallPtrSet.h"
45#include "llvm/ADT/SmallVector.h"
46#include "llvm/ADT/StringMap.h"
47#include "llvm/ADT/StringRef.h"
48#include "llvm/ADT/iterator.h"
49#include "llvm/ADT/iterator_range.h"
50#include "llvm/Bitstream/BitstreamReader.h"
51#include "llvm/Support/MemoryBuffer.h"
52#include "llvm/Support/Timer.h"
53#include "llvm/Support/VersionTuple.h"
54#include <cassert>
55#include <cstddef>
56#include <cstdint>
57#include <ctime>
58#include <deque>
59#include <memory>
60#include <optional>
61#include <set>
62#include <string>
63#include <utility>
64#include <vector>
65
66namespace clang {
67
68class ASTConsumer;
69class ASTContext;
70class ASTDeserializationListener;
71class ASTReader;
72class ASTRecordReader;
73class CXXTemporary;
74class Decl;
75class DeclarationName;
76class DeclaratorDecl;
77class DeclContext;
78class EnumDecl;
79class Expr;
80class FieldDecl;
81class FileEntry;
82class FileManager;
83class FileSystemOptions;
84class FunctionDecl;
85class GlobalModuleIndex;
86struct HeaderFileInfo;
87class HeaderSearchOptions;
88class LangOptions;
89class MacroInfo;
90class InMemoryModuleCache;
91class NamedDecl;
92class NamespaceDecl;
93class ObjCCategoryDecl;
94class ObjCInterfaceDecl;
95class PCHContainerReader;
96class Preprocessor;
97class PreprocessorOptions;
98class Sema;
99class SourceManager;
100class Stmt;
101class SwitchCase;
102class TargetOptions;
103class Token;
104class TypedefNameDecl;
105class ValueDecl;
106class VarDecl;
107
108/// Abstract interface for callback invocations by the ASTReader.
109///
110/// While reading an AST file, the ASTReader will call the methods of the
111/// listener to pass on specific information. Some of the listener methods can
112/// return true to indicate to the ASTReader that the information (and
113/// consequently the AST file) is invalid.
115public:
117
118 /// Receives the full Clang version information.
119 ///
120 /// \returns true to indicate that the version is invalid. Subclasses should
121 /// generally defer to this implementation.
122 virtual bool ReadFullVersionInformation(StringRef FullVersion) {
123 return FullVersion != getClangFullRepositoryVersion();
124 }
125
126 virtual void ReadModuleName(StringRef ModuleName) {}
127 virtual void ReadModuleMapFile(StringRef ModuleMapPath) {}
128
129 /// Receives the language options.
130 ///
131 /// \returns true to indicate the options are invalid or false otherwise.
132 virtual bool ReadLanguageOptions(const LangOptions &LangOpts,
133 bool Complain,
134 bool AllowCompatibleDifferences) {
135 return false;
136 }
137
138 /// Receives the target options.
139 ///
140 /// \returns true to indicate the target options are invalid, or false
141 /// otherwise.
142 virtual bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
143 bool AllowCompatibleDifferences) {
144 return false;
145 }
146
147 /// Receives the diagnostic options.
148 ///
149 /// \returns true to indicate the diagnostic options are invalid, or false
150 /// otherwise.
151 virtual bool
153 bool Complain) {
154 return false;
155 }
156
157 /// Receives the file system options.
158 ///
159 /// \returns true to indicate the file system options are invalid, or false
160 /// otherwise.
161 virtual bool ReadFileSystemOptions(const FileSystemOptions &FSOpts,
162 bool Complain) {
163 return false;
164 }
165
166 /// Receives the header search options.
167 ///
168 /// \param HSOpts The read header search options. The following fields are
169 /// missing and are reported in ReadHeaderSearchPaths():
170 /// UserEntries, SystemHeaderPrefixes, VFSOverlayFiles.
171 ///
172 /// \returns true to indicate the header search options are invalid, or false
173 /// otherwise.
175 StringRef SpecificModuleCachePath,
176 bool Complain) {
177 return false;
178 }
179
180 /// Receives the header search paths.
181 ///
182 /// \param HSOpts The read header search paths. Only the following fields are
183 /// initialized: UserEntries, SystemHeaderPrefixes,
184 /// VFSOverlayFiles. The rest is reported in
185 /// ReadHeaderSearchOptions().
186 ///
187 /// \returns true to indicate the header search paths are invalid, or false
188 /// otherwise.
189 virtual bool ReadHeaderSearchPaths(const HeaderSearchOptions &HSOpts,
190 bool Complain) {
191 return false;
192 }
193
194 /// Receives the preprocessor options.
195 ///
196 /// \param SuggestedPredefines Can be filled in with the set of predefines
197 /// that are suggested by the preprocessor options. Typically only used when
198 /// loading a precompiled header.
199 ///
200 /// \returns true to indicate the preprocessor options are invalid, or false
201 /// otherwise.
203 bool ReadMacros, bool Complain,
204 std::string &SuggestedPredefines) {
205 return false;
206 }
207
208 /// Receives __COUNTER__ value.
210 unsigned Value) {}
211
212 /// This is called for each AST file loaded.
213 virtual void visitModuleFile(StringRef Filename,
215
216 /// Returns true if this \c ASTReaderListener wants to receive the
217 /// input files of the AST file via \c visitInputFile, false otherwise.
218 virtual bool needsInputFileVisitation() { return false; }
219
220 /// Returns true if this \c ASTReaderListener wants to receive the
221 /// system input files of the AST file via \c visitInputFile, false otherwise.
222 virtual bool needsSystemInputFileVisitation() { return false; }
223
224 /// if \c needsInputFileVisitation returns true, this is called for
225 /// each non-system input file of the AST File. If
226 /// \c needsSystemInputFileVisitation is true, then it is called for all
227 /// system input files as well.
228 ///
229 /// \returns true to continue receiving the next input file, false to stop.
230 virtual bool visitInputFile(StringRef Filename, bool isSystem,
231 bool isOverridden, bool isExplicitModule) {
232 return true;
233 }
234
235 /// Returns true if this \c ASTReaderListener wants to receive the
236 /// imports of the AST file via \c visitImport, false otherwise.
237 virtual bool needsImportVisitation() const { return false; }
238
239 /// If needsImportVisitation returns \c true, this is called for each
240 /// AST file imported by this AST file.
241 virtual void visitImport(StringRef ModuleName, StringRef Filename) {}
242
243 /// Indicates that a particular module file extension has been read.
245 const ModuleFileExtensionMetadata &Metadata) {}
246};
247
248/// Simple wrapper class for chaining listeners.
250 std::unique_ptr<ASTReaderListener> First;
251 std::unique_ptr<ASTReaderListener> Second;
252
253public:
254 /// Takes ownership of \p First and \p Second.
255 ChainedASTReaderListener(std::unique_ptr<ASTReaderListener> First,
256 std::unique_ptr<ASTReaderListener> Second)
257 : First(std::move(First)), Second(std::move(Second)) {}
258
259 std::unique_ptr<ASTReaderListener> takeFirst() { return std::move(First); }
260 std::unique_ptr<ASTReaderListener> takeSecond() { return std::move(Second); }
261
262 bool ReadFullVersionInformation(StringRef FullVersion) override;
263 void ReadModuleName(StringRef ModuleName) override;
264 void ReadModuleMapFile(StringRef ModuleMapPath) override;
265 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
266 bool AllowCompatibleDifferences) override;
267 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
268 bool AllowCompatibleDifferences) override;
270 bool Complain) override;
271 bool ReadFileSystemOptions(const FileSystemOptions &FSOpts,
272 bool Complain) override;
273
275 StringRef SpecificModuleCachePath,
276 bool Complain) override;
278 bool ReadMacros, bool Complain,
279 std::string &SuggestedPredefines) override;
280
281 void ReadCounter(const serialization::ModuleFile &M, unsigned Value) override;
282 bool needsInputFileVisitation() override;
283 bool needsSystemInputFileVisitation() override;
284 void visitModuleFile(StringRef Filename,
285 serialization::ModuleKind Kind) override;
286 bool visitInputFile(StringRef Filename, bool isSystem,
287 bool isOverridden, bool isExplicitModule) override;
289 const ModuleFileExtensionMetadata &Metadata) override;
290};
291
292/// ASTReaderListener implementation to validate the information of
293/// the PCH file against an initialized Preprocessor.
295 Preprocessor &PP;
296 ASTReader &Reader;
297
298public:
300 : PP(PP), Reader(Reader) {}
301
302 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
303 bool AllowCompatibleDifferences) override;
304 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
305 bool AllowCompatibleDifferences) override;
307 bool Complain) override;
309 bool ReadMacros, bool Complain,
310 std::string &SuggestedPredefines) override;
312 StringRef SpecificModuleCachePath,
313 bool Complain) override;
314 void ReadCounter(const serialization::ModuleFile &M, unsigned Value) override;
315};
316
317/// ASTReaderListenter implementation to set SuggestedPredefines of
318/// ASTReader which is required to use a pch file. This is the replacement
319/// of PCHValidator or SimplePCHValidator when using a pch file without
320/// validating it.
322 Preprocessor &PP;
323
324public:
326
328 bool ReadMacros, bool Complain,
329 std::string &SuggestedPredefines) override;
330};
331
332namespace serialization {
333
334class ReadMethodPoolVisitor;
335
336namespace reader {
337
339
340/// The on-disk hash table(s) used for DeclContext name lookup.
342
343} // namespace reader
344
345} // namespace serialization
346
347/// Reads an AST files chain containing the contents of a translation
348/// unit.
349///
350/// The ASTReader class reads bitstreams (produced by the ASTWriter
351/// class) containing the serialized representation of a given
352/// abstract syntax tree and its supporting data structures. An
353/// instance of the ASTReader can be attached to an ASTContext object,
354/// which will provide access to the contents of the AST files.
355///
356/// The AST reader provides lazy de-serialization of declarations, as
357/// required when traversing the AST. Only those AST nodes that are
358/// actually required will be de-serialized.
363 public ExternalSemaSource,
366{
367public:
368 /// Types of AST files.
369 friend class ASTDeclReader;
371 friend class ASTRecordReader;
372 friend class ASTUnit; // ASTUnit needs to remap source locations.
373 friend class ASTWriter;
374 friend class PCHValidator;
377 friend class TypeLocReader;
378
381
382 /// The result of reading the control block of an AST file, which
383 /// can fail for various reasons.
385 /// The control block was read successfully. Aside from failures,
386 /// the AST file is safe to read into the current context.
388
389 /// The AST file itself appears corrupted.
391
392 /// The AST file was missing.
394
395 /// The AST file is out-of-date relative to its input files,
396 /// and needs to be regenerated.
398
399 /// The AST file was written by a different version of Clang.
401
402 /// The AST file was written with a different language/target
403 /// configuration.
405
406 /// The AST file has errors.
408 };
409
416
417private:
419
420 /// The receiver of some callbacks invoked by ASTReader.
421 std::unique_ptr<ASTReaderListener> Listener;
422
423 /// The receiver of deserialization events.
424 ASTDeserializationListener *DeserializationListener = nullptr;
425
426 bool OwnsDeserializationListener = false;
427
428 SourceManager &SourceMgr;
429 FileManager &FileMgr;
430 const PCHContainerReader &PCHContainerRdr;
431 DiagnosticsEngine &Diags;
432
433 /// The semantic analysis object that will be processing the
434 /// AST files and the translation unit that uses it.
435 Sema *SemaObj = nullptr;
436
437 /// The preprocessor that will be loading the source file.
438 Preprocessor &PP;
439
440 /// The AST context into which we'll read the AST files.
441 ASTContext *ContextObj = nullptr;
442
443 /// The AST consumer.
444 ASTConsumer *Consumer = nullptr;
445
446 /// The module manager which manages modules and their dependencies
447 ModuleManager ModuleMgr;
448
449 /// A dummy identifier resolver used to merge TU-scope declarations in
450 /// C, for the cases where we don't have a Sema object to provide a real
451 /// identifier resolver.
452 IdentifierResolver DummyIdResolver;
453
454 /// A mapping from extension block names to module file extensions.
455 llvm::StringMap<std::shared_ptr<ModuleFileExtension>> ModuleFileExtensions;
456
457 /// A timer used to track the time spent deserializing.
458 std::unique_ptr<llvm::Timer> ReadTimer;
459
460 /// The location where the module file will be considered as
461 /// imported from. For non-module AST types it should be invalid.
462 SourceLocation CurrentImportLoc;
463
464 /// The module kind that is currently deserializing.
465 std::optional<ModuleKind> CurrentDeserializingModuleKind;
466
467 /// The global module index, if loaded.
468 std::unique_ptr<GlobalModuleIndex> GlobalIndex;
469
470 /// A map of global bit offsets to the module that stores entities
471 /// at those bit offsets.
473
474 /// A map of negated SLocEntryIDs to the modules containing them.
476
479
480 /// A map of reversed (SourceManager::MaxLoadedOffset - SLocOffset)
481 /// SourceLocation offsets to the modules containing them.
482 GlobalSLocOffsetMapType GlobalSLocOffsetMap;
483
484 /// Types that have already been loaded from the chain.
485 ///
486 /// When the pointer at index I is non-NULL, the type with
487 /// ID = (I + 1) << FastQual::Width has already been loaded
488 llvm::PagedVector<QualType> TypesLoaded;
489
490 using GlobalTypeMapType =
492
493 /// Mapping from global type IDs to the module in which the
494 /// type resides along with the offset that should be added to the
495 /// global type ID to produce a local ID.
496 GlobalTypeMapType GlobalTypeMap;
497
498 /// Declarations that have already been loaded from the chain.
499 ///
500 /// When the pointer at index I is non-NULL, the declaration with ID
501 /// = I + 1 has already been loaded.
502 llvm::PagedVector<Decl *> DeclsLoaded;
503
505
506 /// Mapping from global declaration IDs to the module in which the
507 /// declaration resides.
508 GlobalDeclMapType GlobalDeclMap;
509
510 using FileOffset = std::pair<ModuleFile *, uint64_t>;
512 using DeclUpdateOffsetsMap = llvm::DenseMap<GlobalDeclID, FileOffsetsTy>;
513
514 /// Declarations that have modifications residing in a later file
515 /// in the chain.
516 DeclUpdateOffsetsMap DeclUpdateOffsets;
517
518 using DelayedNamespaceOffsetMapTy =
519 llvm::DenseMap<GlobalDeclID, std::pair</*LexicalOffset*/ uint64_t,
520 /*VisibleOffset*/ uint64_t>>;
521
522 /// Mapping from global declaration IDs to the lexical and visible block
523 /// offset for delayed namespace in reduced BMI.
524 ///
525 /// We can't use the existing DeclUpdate mechanism since the DeclUpdate
526 /// may only be applied in an outer most read. However, we need to know
527 /// whether or not a DeclContext has external storage during the recursive
528 /// reading. So we need to apply the offset immediately after we read the
529 /// namespace as if it is not delayed.
530 DelayedNamespaceOffsetMapTy DelayedNamespaceOffsetMap;
531
532 struct PendingUpdateRecord {
533 Decl *D;
534 GlobalDeclID ID;
535
536 // Whether the declaration was just deserialized.
537 bool JustLoaded;
538
539 PendingUpdateRecord(GlobalDeclID ID, Decl *D, bool JustLoaded)
540 : D(D), ID(ID), JustLoaded(JustLoaded) {}
541 };
542
543 /// Declaration updates for already-loaded declarations that we need
544 /// to apply once we finish processing an import.
546
547 enum class PendingFakeDefinitionKind { NotFake, Fake, FakeLoaded };
548
549 /// The DefinitionData pointers that we faked up for class definitions
550 /// that we needed but hadn't loaded yet.
551 llvm::DenseMap<void *, PendingFakeDefinitionKind> PendingFakeDefinitionData;
552
553 /// Exception specification updates that have been loaded but not yet
554 /// propagated across the relevant redeclaration chain. The map key is the
555 /// canonical declaration (used only for deduplication) and the value is a
556 /// declaration that has an exception specification.
557 llvm::SmallMapVector<Decl *, FunctionDecl *, 4> PendingExceptionSpecUpdates;
558
559 /// Deduced return type updates that have been loaded but not yet propagated
560 /// across the relevant redeclaration chain. The map key is the canonical
561 /// declaration and the value is the deduced return type.
562 llvm::SmallMapVector<FunctionDecl *, QualType, 4> PendingDeducedTypeUpdates;
563
564 /// Functions has undededuced return type and we wish we can find the deduced
565 /// return type by iterating the redecls in other modules.
566 llvm::SmallVector<FunctionDecl *, 4> PendingUndeducedFunctionDecls;
567
568 /// Declarations that have been imported and have typedef names for
569 /// linkage purposes.
570 llvm::DenseMap<std::pair<DeclContext *, IdentifierInfo *>, NamedDecl *>
571 ImportedTypedefNamesForLinkage;
572
573 /// Mergeable declaration contexts that have anonymous declarations
574 /// within them, and those anonymous declarations.
575 llvm::DenseMap<Decl*, llvm::SmallVector<NamedDecl*, 2>>
576 AnonymousDeclarationsForMerging;
577
578 /// Map from numbering information for lambdas to the corresponding lambdas.
579 llvm::DenseMap<std::pair<const Decl *, unsigned>, NamedDecl *>
580 LambdaDeclarationsForMerging;
581
582 /// Key used to identify LifetimeExtendedTemporaryDecl for merging,
583 /// containing the lifetime-extending declaration and the mangling number.
584 using LETemporaryKey = std::pair<Decl *, unsigned>;
585
586 /// Map of already deserialiazed temporaries.
587 llvm::DenseMap<LETemporaryKey, LifetimeExtendedTemporaryDecl *>
588 LETemporaryForMerging;
589
590 struct FileDeclsInfo {
591 ModuleFile *Mod = nullptr;
592 ArrayRef<LocalDeclID> Decls;
593
594 FileDeclsInfo() = default;
595 FileDeclsInfo(ModuleFile *Mod, ArrayRef<LocalDeclID> Decls)
596 : Mod(Mod), Decls(Decls) {}
597 };
598
599 /// Map from a FileID to the file-level declarations that it contains.
600 llvm::DenseMap<FileID, FileDeclsInfo> FileDeclIDs;
601
602 /// An array of lexical contents of a declaration context, as a sequence of
603 /// Decl::Kind, DeclID pairs.
604 using unalighed_decl_id_t =
605 llvm::support::detail::packed_endian_specific_integral<
606 serialization::DeclID, llvm::endianness::native,
607 llvm::support::unaligned>;
608 using LexicalContents = ArrayRef<unalighed_decl_id_t>;
609
610 /// Map from a DeclContext to its lexical contents.
611 llvm::DenseMap<const DeclContext*, std::pair<ModuleFile*, LexicalContents>>
612 LexicalDecls;
613
614 /// Map from the TU to its lexical contents from each module file.
615 std::vector<std::pair<ModuleFile*, LexicalContents>> TULexicalDecls;
616
617 /// Map from a DeclContext to its lookup tables.
618 llvm::DenseMap<const DeclContext *,
619 serialization::reader::DeclContextLookupTable> Lookups;
620
621 // Updates for visible decls can occur for other contexts than just the
622 // TU, and when we read those update records, the actual context may not
623 // be available yet, so have this pending map using the ID as a key. It
624 // will be realized when the context is actually loaded.
625 struct PendingVisibleUpdate {
626 ModuleFile *Mod;
627 const unsigned char *Data;
628 };
629 using DeclContextVisibleUpdates = SmallVector<PendingVisibleUpdate, 1>;
630
631 /// Updates to the visible declarations of declaration contexts that
632 /// haven't been loaded yet.
633 llvm::DenseMap<GlobalDeclID, DeclContextVisibleUpdates> PendingVisibleUpdates;
634
635 /// The set of C++ or Objective-C classes that have forward
636 /// declarations that have not yet been linked to their definitions.
637 llvm::SmallPtrSet<Decl *, 4> PendingDefinitions;
638
639 using PendingBodiesMap =
640 llvm::MapVector<Decl *, uint64_t,
641 llvm::SmallDenseMap<Decl *, unsigned, 4>,
642 SmallVector<std::pair<Decl *, uint64_t>, 4>>;
643
644 /// Functions or methods that have bodies that will be attached.
645 PendingBodiesMap PendingBodies;
646
647 /// Definitions for which we have added merged definitions but not yet
648 /// performed deduplication.
649 llvm::SetVector<NamedDecl *> PendingMergedDefinitionsToDeduplicate;
650
651 /// Read the record that describes the lexical contents of a DC.
652 bool ReadLexicalDeclContextStorage(ModuleFile &M,
653 llvm::BitstreamCursor &Cursor,
654 uint64_t Offset, DeclContext *DC);
655
656 /// Read the record that describes the visible contents of a DC.
657 bool ReadVisibleDeclContextStorage(ModuleFile &M,
658 llvm::BitstreamCursor &Cursor,
659 uint64_t Offset, GlobalDeclID ID);
660
661 /// A vector containing identifiers that have already been
662 /// loaded.
663 ///
664 /// If the pointer at index I is non-NULL, then it refers to the
665 /// IdentifierInfo for the identifier with ID=I+1 that has already
666 /// been loaded.
667 std::vector<IdentifierInfo *> IdentifiersLoaded;
668
669 using GlobalIdentifierMapType =
670 ContinuousRangeMap<serialization::IdentifierID, ModuleFile *, 4>;
671
672 /// Mapping from global identifier IDs to the module in which the
673 /// identifier resides along with the offset that should be added to the
674 /// global identifier ID to produce a local ID.
675 GlobalIdentifierMapType GlobalIdentifierMap;
676
677 /// A vector containing macros that have already been
678 /// loaded.
679 ///
680 /// If the pointer at index I is non-NULL, then it refers to the
681 /// MacroInfo for the identifier with ID=I+1 that has already
682 /// been loaded.
683 std::vector<MacroInfo *> MacrosLoaded;
684
685 using LoadedMacroInfo =
686 std::pair<IdentifierInfo *, serialization::SubmoduleID>;
687
688 /// A set of #undef directives that we have loaded; used to
689 /// deduplicate the same #undef information coming from multiple module
690 /// files.
692
693 using GlobalMacroMapType =
694 ContinuousRangeMap<serialization::MacroID, ModuleFile *, 4>;
695
696 /// Mapping from global macro IDs to the module in which the
697 /// macro resides along with the offset that should be added to the
698 /// global macro ID to produce a local ID.
699 GlobalMacroMapType GlobalMacroMap;
700
701 /// A vector containing submodules that have already been loaded.
702 ///
703 /// This vector is indexed by the Submodule ID (-1). NULL submodule entries
704 /// indicate that the particular submodule ID has not yet been loaded.
705 SmallVector<Module *, 2> SubmodulesLoaded;
706
707 using GlobalSubmoduleMapType =
708 ContinuousRangeMap<serialization::SubmoduleID, ModuleFile *, 4>;
709
710 /// Mapping from global submodule IDs to the module file in which the
711 /// submodule resides along with the offset that should be added to the
712 /// global submodule ID to produce a local ID.
713 GlobalSubmoduleMapType GlobalSubmoduleMap;
714
715 /// A set of hidden declarations.
716 using HiddenNames = SmallVector<Decl *, 2>;
717 using HiddenNamesMapType = llvm::DenseMap<Module *, HiddenNames>;
718
719 /// A mapping from each of the hidden submodules to the deserialized
720 /// declarations in that submodule that could be made visible.
721 HiddenNamesMapType HiddenNamesMap;
722
723 /// A module import, export, or conflict that hasn't yet been resolved.
724 struct UnresolvedModuleRef {
725 /// The file in which this module resides.
727
728 /// The module that is importing or exporting.
729 Module *Mod;
730
731 /// The kind of module reference.
732 enum { Import, Export, Conflict, Affecting } Kind;
733
734 /// The local ID of the module that is being exported.
735 unsigned ID;
736
737 /// Whether this is a wildcard export.
738 LLVM_PREFERRED_TYPE(bool)
739 unsigned IsWildcard : 1;
740
741 /// String data.
742 StringRef String;
743 };
744
745 /// The set of module imports and exports that still need to be
746 /// resolved.
747 SmallVector<UnresolvedModuleRef, 2> UnresolvedModuleRefs;
748
749 /// A vector containing selectors that have already been loaded.
750 ///
751 /// This vector is indexed by the Selector ID (-1). NULL selector
752 /// entries indicate that the particular selector ID has not yet
753 /// been loaded.
754 SmallVector<Selector, 16> SelectorsLoaded;
755
756 using GlobalSelectorMapType =
757 ContinuousRangeMap<serialization::SelectorID, ModuleFile *, 4>;
758
759 /// Mapping from global selector IDs to the module in which the
760 /// global selector ID to produce a local ID.
761 GlobalSelectorMapType GlobalSelectorMap;
762
763 /// The generation number of the last time we loaded data from the
764 /// global method pool for this selector.
765 llvm::DenseMap<Selector, unsigned> SelectorGeneration;
766
767 /// Whether a selector is out of date. We mark a selector as out of date
768 /// if we load another module after the method pool entry was pulled in.
769 llvm::DenseMap<Selector, bool> SelectorOutOfDate;
770
771 struct PendingMacroInfo {
772 ModuleFile *M;
773 /// Offset relative to ModuleFile::MacroOffsetsBase.
774 uint32_t MacroDirectivesOffset;
775
776 PendingMacroInfo(ModuleFile *M, uint32_t MacroDirectivesOffset)
777 : M(M), MacroDirectivesOffset(MacroDirectivesOffset) {}
778 };
779
780 using PendingMacroIDsMap =
781 llvm::MapVector<IdentifierInfo *, SmallVector<PendingMacroInfo, 2>>;
782
783 /// Mapping from identifiers that have a macro history to the global
784 /// IDs have not yet been deserialized to the global IDs of those macros.
785 PendingMacroIDsMap PendingMacroIDs;
786
787 using GlobalPreprocessedEntityMapType =
788 ContinuousRangeMap<unsigned, ModuleFile *, 4>;
789
790 /// Mapping from global preprocessing entity IDs to the module in
791 /// which the preprocessed entity resides along with the offset that should be
792 /// added to the global preprocessing entity ID to produce a local ID.
793 GlobalPreprocessedEntityMapType GlobalPreprocessedEntityMap;
794
795 using GlobalSkippedRangeMapType =
796 ContinuousRangeMap<unsigned, ModuleFile *, 4>;
797
798 /// Mapping from global skipped range base IDs to the module in which
799 /// the skipped ranges reside.
800 GlobalSkippedRangeMapType GlobalSkippedRangeMap;
801
802 /// \name CodeGen-relevant special data
803 /// Fields containing data that is relevant to CodeGen.
804 //@{
805
806 /// The IDs of all declarations that fulfill the criteria of
807 /// "interesting" decls.
808 ///
809 /// This contains the data loaded from all EAGERLY_DESERIALIZED_DECLS blocks
810 /// in the chain. The referenced declarations are deserialized and passed to
811 /// the consumer eagerly.
812 SmallVector<GlobalDeclID, 16> EagerlyDeserializedDecls;
813
814 /// The IDs of all tentative definitions stored in the chain.
815 ///
816 /// Sema keeps track of all tentative definitions in a TU because it has to
817 /// complete them and pass them on to CodeGen. Thus, tentative definitions in
818 /// the PCH chain must be eagerly deserialized.
819 SmallVector<GlobalDeclID, 16> TentativeDefinitions;
820
821 /// The IDs of all CXXRecordDecls stored in the chain whose VTables are
822 /// used.
823 ///
824 /// CodeGen has to emit VTables for these records, so they have to be eagerly
825 /// deserialized.
826 struct VTableUse {
827 GlobalDeclID ID;
829 bool Used;
830 };
831 SmallVector<VTableUse> VTableUses;
832
833 /// A snapshot of the pending instantiations in the chain.
834 ///
835 /// This record tracks the instantiations that Sema has to perform at the
836 /// end of the TU. It consists of a pair of values for every pending
837 /// instantiation where the first value is the ID of the decl and the second
838 /// is the instantiation location.
839 struct PendingInstantiation {
840 GlobalDeclID ID;
842 };
843 SmallVector<PendingInstantiation, 64> PendingInstantiations;
844
845 //@}
846
847 /// \name DiagnosticsEngine-relevant special data
848 /// Fields containing data that is used for generating diagnostics
849 //@{
850
851 /// A snapshot of Sema's unused file-scoped variable tracking, for
852 /// generating warnings.
853 SmallVector<GlobalDeclID, 16> UnusedFileScopedDecls;
854
855 /// A list of all the delegating constructors we've seen, to diagnose
856 /// cycles.
857 SmallVector<GlobalDeclID, 4> DelegatingCtorDecls;
858
859 /// Method selectors used in a @selector expression. Used for
860 /// implementation of -Wselector.
861 SmallVector<serialization::SelectorID, 64> ReferencedSelectorsData;
862
863 /// A snapshot of Sema's weak undeclared identifier tracking, for
864 /// generating warnings.
865 SmallVector<serialization::IdentifierID, 64> WeakUndeclaredIdentifiers;
866
867 /// The IDs of type aliases for ext_vectors that exist in the chain.
868 ///
869 /// Used by Sema for finding sugared names for ext_vectors in diagnostics.
870 SmallVector<GlobalDeclID, 4> ExtVectorDecls;
871
872 //@}
873
874 /// \name Sema-relevant special data
875 /// Fields containing data that is used for semantic analysis
876 //@{
877
878 /// The IDs of all potentially unused typedef names in the chain.
879 ///
880 /// Sema tracks these to emit warnings.
881 SmallVector<GlobalDeclID, 16> UnusedLocalTypedefNameCandidates;
882
883 /// Our current depth in #pragma cuda force_host_device begin/end
884 /// macros.
885 unsigned ForceHostDeviceDepth = 0;
886
887 /// The IDs of the declarations Sema stores directly.
888 ///
889 /// Sema tracks a few important decls, such as namespace std, directly.
890 SmallVector<GlobalDeclID, 4> SemaDeclRefs;
891
892 /// The IDs of the types ASTContext stores directly.
893 ///
894 /// The AST context tracks a few important types, such as va_list, directly.
895 SmallVector<serialization::TypeID, 16> SpecialTypes;
896
897 /// The IDs of CUDA-specific declarations ASTContext stores directly.
898 ///
899 /// The AST context tracks a few important decls, currently cudaConfigureCall,
900 /// directly.
901 SmallVector<GlobalDeclID, 2> CUDASpecialDeclRefs;
902
903 /// The floating point pragma option settings.
904 SmallVector<uint64_t, 1> FPPragmaOptions;
905
906 /// The pragma clang optimize location (if the pragma state is "off").
907 SourceLocation OptimizeOffPragmaLocation;
908
909 /// The PragmaMSStructKind pragma ms_struct state if set, or -1.
910 int PragmaMSStructState = -1;
911
912 /// The PragmaMSPointersToMembersKind pragma pointers_to_members state.
913 int PragmaMSPointersToMembersState = -1;
914 SourceLocation PointersToMembersPragmaLocation;
915
916 /// The pragma float_control state.
917 std::optional<FPOptionsOverride> FpPragmaCurrentValue;
918 SourceLocation FpPragmaCurrentLocation;
919 struct FpPragmaStackEntry {
920 FPOptionsOverride Value;
921 SourceLocation Location;
922 SourceLocation PushLocation;
923 StringRef SlotLabel;
924 };
926 llvm::SmallVector<std::string, 2> FpPragmaStrings;
927
928 /// The pragma align/pack state.
929 std::optional<Sema::AlignPackInfo> PragmaAlignPackCurrentValue;
930 SourceLocation PragmaAlignPackCurrentLocation;
931 struct PragmaAlignPackStackEntry {
932 Sema::AlignPackInfo Value;
933 SourceLocation Location;
934 SourceLocation PushLocation;
935 StringRef SlotLabel;
936 };
938 llvm::SmallVector<std::string, 2> PragmaAlignPackStrings;
939
940 /// The OpenCL extension settings.
941 OpenCLOptions OpenCLExtensions;
942
943 /// Extensions required by an OpenCL type.
944 llvm::DenseMap<const Type *, std::set<std::string>> OpenCLTypeExtMap;
945
946 /// Extensions required by an OpenCL declaration.
947 llvm::DenseMap<const Decl *, std::set<std::string>> OpenCLDeclExtMap;
948
949 /// A list of the namespaces we've seen.
950 SmallVector<GlobalDeclID, 4> KnownNamespaces;
951
952 /// A list of undefined decls with internal linkage followed by the
953 /// SourceLocation of a matching ODR-use.
954 struct UndefinedButUsedDecl {
955 GlobalDeclID ID;
957 };
958 SmallVector<UndefinedButUsedDecl, 8> UndefinedButUsed;
959
960 /// Delete expressions to analyze at the end of translation unit.
961 SmallVector<uint64_t, 8> DelayedDeleteExprs;
962
963 // A list of late parsed template function data with their module files.
964 SmallVector<std::pair<ModuleFile *, SmallVector<uint64_t, 1>>, 4>
965 LateParsedTemplates;
966
967 /// The IDs of all decls to be checked for deferred diags.
968 ///
969 /// Sema tracks these to emit deferred diags.
970 llvm::SmallSetVector<GlobalDeclID, 4> DeclsToCheckForDeferredDiags;
971
972private:
973 struct ImportedSubmodule {
975 SourceLocation ImportLoc;
976
977 ImportedSubmodule(serialization::SubmoduleID ID, SourceLocation ImportLoc)
978 : ID(ID), ImportLoc(ImportLoc) {}
979 };
980
981 /// A list of modules that were imported by precompiled headers or
982 /// any other non-module AST file and have not yet been made visible. If a
983 /// module is made visible in the ASTReader, it will be transfered to
984 /// \c PendingImportedModulesSema.
985 SmallVector<ImportedSubmodule, 2> PendingImportedModules;
986
987 /// A list of modules that were imported by precompiled headers or
988 /// any other non-module AST file and have not yet been made visible for Sema.
989 SmallVector<ImportedSubmodule, 2> PendingImportedModulesSema;
990 //@}
991
992 /// The system include root to be used when loading the
993 /// precompiled header.
994 std::string isysroot;
995
996 /// Whether to disable the normal validation performed on precompiled
997 /// headers and module files when they are loaded.
998 DisableValidationForModuleKind DisableValidationKind;
999
1000 /// Whether to accept an AST file with compiler errors.
1001 bool AllowASTWithCompilerErrors;
1002
1003 /// Whether to accept an AST file that has a different configuration
1004 /// from the current compiler instance.
1005 bool AllowConfigurationMismatch;
1006
1007 /// Whether validate system input files.
1008 bool ValidateSystemInputs;
1009
1010 /// Whether validate headers and module maps using hash based on contents.
1011 bool ValidateASTInputFilesContent;
1012
1013 /// Whether we are allowed to use the global module index.
1014 bool UseGlobalIndex;
1015
1016 /// Whether we have tried loading the global module index yet.
1017 bool TriedLoadingGlobalIndex = false;
1018
1019 ///Whether we are currently processing update records.
1020 bool ProcessingUpdateRecords = false;
1021
1022 using SwitchCaseMapTy = llvm::DenseMap<unsigned, SwitchCase *>;
1023
1024 /// Mapping from switch-case IDs in the chain to switch-case statements
1025 ///
1026 /// Statements usually don't have IDs, but switch cases need them, so that the
1027 /// switch statement can refer to them.
1028 SwitchCaseMapTy SwitchCaseStmts;
1029
1030 SwitchCaseMapTy *CurrSwitchCaseStmts;
1031
1032 /// The number of source location entries de-serialized from
1033 /// the PCH file.
1034 unsigned NumSLocEntriesRead = 0;
1035
1036 /// The number of source location entries in the chain.
1037 unsigned TotalNumSLocEntries = 0;
1038
1039 /// The number of statements (and expressions) de-serialized
1040 /// from the chain.
1041 unsigned NumStatementsRead = 0;
1042
1043 /// The total number of statements (and expressions) stored
1044 /// in the chain.
1045 unsigned TotalNumStatements = 0;
1046
1047 /// The number of macros de-serialized from the chain.
1048 unsigned NumMacrosRead = 0;
1049
1050 /// The total number of macros stored in the chain.
1051 unsigned TotalNumMacros = 0;
1052
1053 /// The number of lookups into identifier tables.
1054 unsigned NumIdentifierLookups = 0;
1055
1056 /// The number of lookups into identifier tables that succeed.
1057 unsigned NumIdentifierLookupHits = 0;
1058
1059 /// The number of selectors that have been read.
1060 unsigned NumSelectorsRead = 0;
1061
1062 /// The number of method pool entries that have been read.
1063 unsigned NumMethodPoolEntriesRead = 0;
1064
1065 /// The number of times we have looked up a selector in the method
1066 /// pool.
1067 unsigned NumMethodPoolLookups = 0;
1068
1069 /// The number of times we have looked up a selector in the method
1070 /// pool and found something.
1071 unsigned NumMethodPoolHits = 0;
1072
1073 /// The number of times we have looked up a selector in the method
1074 /// pool within a specific module.
1075 unsigned NumMethodPoolTableLookups = 0;
1076
1077 /// The number of times we have looked up a selector in the method
1078 /// pool within a specific module and found something.
1079 unsigned NumMethodPoolTableHits = 0;
1080
1081 /// The total number of method pool entries in the selector table.
1082 unsigned TotalNumMethodPoolEntries = 0;
1083
1084 /// Number of lexical decl contexts read/total.
1085 unsigned NumLexicalDeclContextsRead = 0, TotalLexicalDeclContexts = 0;
1086
1087 /// Number of visible decl contexts read/total.
1088 unsigned NumVisibleDeclContextsRead = 0, TotalVisibleDeclContexts = 0;
1089
1090 /// Total size of modules, in bits, currently loaded
1091 uint64_t TotalModulesSizeInBits = 0;
1092
1093 /// Number of Decl/types that are currently deserializing.
1094 unsigned NumCurrentElementsDeserializing = 0;
1095
1096 /// Set true while we are in the process of passing deserialized
1097 /// "interesting" decls to consumer inside FinishedDeserializing().
1098 /// This is used as a guard to avoid recursively repeating the process of
1099 /// passing decls to consumer.
1100 bool PassingDeclsToConsumer = false;
1101
1102 /// The set of identifiers that were read while the AST reader was
1103 /// (recursively) loading declarations.
1104 ///
1105 /// The declarations on the identifier chain for these identifiers will be
1106 /// loaded once the recursive loading has completed.
1107 llvm::MapVector<IdentifierInfo *, SmallVector<GlobalDeclID, 4>>
1108 PendingIdentifierInfos;
1109
1110 /// The set of lookup results that we have faked in order to support
1111 /// merging of partially deserialized decls but that we have not yet removed.
1112 llvm::SmallMapVector<const IdentifierInfo *, SmallVector<NamedDecl *, 2>, 16>
1113 PendingFakeLookupResults;
1114
1115 /// The generation number of each identifier, which keeps track of
1116 /// the last time we loaded information about this identifier.
1117 llvm::DenseMap<const IdentifierInfo *, unsigned> IdentifierGeneration;
1118
1119 /// Contains declarations and definitions that could be
1120 /// "interesting" to the ASTConsumer, when we get that AST consumer.
1121 ///
1122 /// "Interesting" declarations are those that have data that may
1123 /// need to be emitted, such as inline function definitions or
1124 /// Objective-C protocols.
1125 std::deque<Decl *> PotentiallyInterestingDecls;
1126
1127 /// The list of deduced function types that we have not yet read, because
1128 /// they might contain a deduced return type that refers to a local type
1129 /// declared within the function.
1130 SmallVector<std::pair<FunctionDecl *, serialization::TypeID>, 16>
1131 PendingDeducedFunctionTypes;
1132
1133 /// The list of deduced variable types that we have not yet read, because
1134 /// they might contain a deduced type that refers to a local type declared
1135 /// within the variable.
1136 SmallVector<std::pair<VarDecl *, serialization::TypeID>, 16>
1137 PendingDeducedVarTypes;
1138
1139 /// The list of redeclaration chains that still need to be
1140 /// reconstructed, and the local offset to the corresponding list
1141 /// of redeclarations.
1142 SmallVector<std::pair<Decl *, uint64_t>, 16> PendingDeclChains;
1143
1144 /// The list of canonical declarations whose redeclaration chains
1145 /// need to be marked as incomplete once we're done deserializing things.
1146 SmallVector<Decl *, 16> PendingIncompleteDeclChains;
1147
1148 /// The Decl IDs for the Sema/Lexical DeclContext of a Decl that has
1149 /// been loaded but its DeclContext was not set yet.
1150 struct PendingDeclContextInfo {
1151 Decl *D;
1152 GlobalDeclID SemaDC;
1153 GlobalDeclID LexicalDC;
1154 };
1155
1156 /// The set of Decls that have been loaded but their DeclContexts are
1157 /// not set yet.
1158 ///
1159 /// The DeclContexts for these Decls will be set once recursive loading has
1160 /// been completed.
1161 std::deque<PendingDeclContextInfo> PendingDeclContextInfos;
1162
1163 template <typename DeclTy>
1164 using DuplicateObjCDecls = std::pair<DeclTy *, DeclTy *>;
1165
1166 /// When resolving duplicate ivars from Objective-C extensions we don't error
1167 /// out immediately but check if can merge identical extensions. Not checking
1168 /// extensions for equality immediately because ivar deserialization isn't
1169 /// over yet at that point.
1170 llvm::SmallMapVector<DuplicateObjCDecls<ObjCCategoryDecl>,
1172 2>
1173 PendingObjCExtensionIvarRedeclarations;
1174
1175 /// Members that have been added to classes, for which the class has not yet
1176 /// been notified. CXXRecordDecl::addedMember will be called for each of
1177 /// these once recursive deserialization is complete.
1178 SmallVector<std::pair<CXXRecordDecl*, Decl*>, 4> PendingAddedClassMembers;
1179
1180 /// The set of NamedDecls that have been loaded, but are members of a
1181 /// context that has been merged into another context where the corresponding
1182 /// declaration is either missing or has not yet been loaded.
1183 ///
1184 /// We will check whether the corresponding declaration is in fact missing
1185 /// once recursing loading has been completed.
1186 llvm::SmallVector<NamedDecl *, 16> PendingOdrMergeChecks;
1187
1188 using DataPointers =
1189 std::pair<CXXRecordDecl *, struct CXXRecordDecl::DefinitionData *>;
1190 using ObjCInterfaceDataPointers =
1191 std::pair<ObjCInterfaceDecl *,
1192 struct ObjCInterfaceDecl::DefinitionData *>;
1193 using ObjCProtocolDataPointers =
1194 std::pair<ObjCProtocolDecl *, struct ObjCProtocolDecl::DefinitionData *>;
1195
1196 /// Record definitions in which we found an ODR violation.
1197 llvm::SmallDenseMap<CXXRecordDecl *, llvm::SmallVector<DataPointers, 2>, 2>
1198 PendingOdrMergeFailures;
1199
1200 /// C/ObjC record definitions in which we found an ODR violation.
1201 llvm::SmallDenseMap<RecordDecl *, llvm::SmallVector<RecordDecl *, 2>, 2>
1202 PendingRecordOdrMergeFailures;
1203
1204 /// Function definitions in which we found an ODR violation.
1205 llvm::SmallDenseMap<FunctionDecl *, llvm::SmallVector<FunctionDecl *, 2>, 2>
1206 PendingFunctionOdrMergeFailures;
1207
1208 /// Enum definitions in which we found an ODR violation.
1209 llvm::SmallDenseMap<EnumDecl *, llvm::SmallVector<EnumDecl *, 2>, 2>
1210 PendingEnumOdrMergeFailures;
1211
1212 /// ObjCInterfaceDecl in which we found an ODR violation.
1213 llvm::SmallDenseMap<ObjCInterfaceDecl *,
1215 PendingObjCInterfaceOdrMergeFailures;
1216
1217 /// ObjCProtocolDecl in which we found an ODR violation.
1218 llvm::SmallDenseMap<ObjCProtocolDecl *,
1220 PendingObjCProtocolOdrMergeFailures;
1221
1222 /// DeclContexts in which we have diagnosed an ODR violation.
1223 llvm::SmallPtrSet<DeclContext*, 2> DiagnosedOdrMergeFailures;
1224
1225 /// The set of Objective-C categories that have been deserialized
1226 /// since the last time the declaration chains were linked.
1227 llvm::SmallPtrSet<ObjCCategoryDecl *, 16> CategoriesDeserialized;
1228
1229 /// The set of Objective-C class definitions that have already been
1230 /// loaded, for which we will need to check for categories whenever a new
1231 /// module is loaded.
1232 SmallVector<ObjCInterfaceDecl *, 16> ObjCClassesLoaded;
1233
1234 using KeyDeclsMap = llvm::DenseMap<Decl *, SmallVector<GlobalDeclID, 2>>;
1235
1236 /// A mapping from canonical declarations to the set of global
1237 /// declaration IDs for key declaration that have been merged with that
1238 /// canonical declaration. A key declaration is a formerly-canonical
1239 /// declaration whose module did not import any other key declaration for that
1240 /// entity. These are the IDs that we use as keys when finding redecl chains.
1241 KeyDeclsMap KeyDecls;
1242
1243 /// A mapping from DeclContexts to the semantic DeclContext that we
1244 /// are treating as the definition of the entity. This is used, for instance,
1245 /// when merging implicit instantiations of class templates across modules.
1246 llvm::DenseMap<DeclContext *, DeclContext *> MergedDeclContexts;
1247
1248 /// A mapping from canonical declarations of enums to their canonical
1249 /// definitions. Only populated when using modules in C++.
1250 llvm::DenseMap<EnumDecl *, EnumDecl *> EnumDefinitions;
1251
1252 /// A mapping from canonical declarations of records to their canonical
1253 /// definitions. Doesn't cover CXXRecordDecl.
1254 llvm::DenseMap<RecordDecl *, RecordDecl *> RecordDefinitions;
1255
1256 /// When reading a Stmt tree, Stmt operands are placed in this stack.
1257 SmallVector<Stmt *, 16> StmtStack;
1258
1259 /// What kind of records we are reading.
1260 enum ReadingKind {
1261 Read_None, Read_Decl, Read_Type, Read_Stmt
1262 };
1263
1264 /// What kind of records we are reading.
1265 ReadingKind ReadingKind = Read_None;
1266
1267 /// RAII object to change the reading kind.
1268 class ReadingKindTracker {
1269 ASTReader &Reader;
1270 enum ReadingKind PrevKind;
1271
1272 public:
1273 ReadingKindTracker(enum ReadingKind newKind, ASTReader &reader)
1274 : Reader(reader), PrevKind(Reader.ReadingKind) {
1275 Reader.ReadingKind = newKind;
1276 }
1277
1278 ReadingKindTracker(const ReadingKindTracker &) = delete;
1279 ReadingKindTracker &operator=(const ReadingKindTracker &) = delete;
1280 ~ReadingKindTracker() { Reader.ReadingKind = PrevKind; }
1281 };
1282
1283 /// RAII object to mark the start of processing updates.
1284 class ProcessingUpdatesRAIIObj {
1285 ASTReader &Reader;
1286 bool PrevState;
1287
1288 public:
1289 ProcessingUpdatesRAIIObj(ASTReader &reader)
1290 : Reader(reader), PrevState(Reader.ProcessingUpdateRecords) {
1291 Reader.ProcessingUpdateRecords = true;
1292 }
1293
1294 ProcessingUpdatesRAIIObj(const ProcessingUpdatesRAIIObj &) = delete;
1295 ProcessingUpdatesRAIIObj &
1296 operator=(const ProcessingUpdatesRAIIObj &) = delete;
1297 ~ProcessingUpdatesRAIIObj() { Reader.ProcessingUpdateRecords = PrevState; }
1298 };
1299
1300 /// Suggested contents of the predefines buffer, after this
1301 /// PCH file has been processed.
1302 ///
1303 /// In most cases, this string will be empty, because the predefines
1304 /// buffer computed to build the PCH file will be identical to the
1305 /// predefines buffer computed from the command line. However, when
1306 /// there are differences that the PCH reader can work around, this
1307 /// predefines buffer may contain additional definitions.
1308 std::string SuggestedPredefines;
1309
1310 llvm::DenseMap<const Decl *, bool> DefinitionSource;
1311
1312 bool shouldDisableValidationForFile(const serialization::ModuleFile &M) const;
1313
1314 /// Reads a statement from the specified cursor.
1315 Stmt *ReadStmtFromStream(ModuleFile &F);
1316
1317 /// Retrieve the stored information about an input file.
1318 serialization::InputFileInfo getInputFileInfo(ModuleFile &F, unsigned ID);
1319
1320 /// Retrieve the file entry and 'overridden' bit for an input
1321 /// file in the given module file.
1322 serialization::InputFile getInputFile(ModuleFile &F, unsigned ID,
1323 bool Complain = true);
1324
1325public:
1326 void ResolveImportedPath(ModuleFile &M, std::string &Filename);
1327 static void ResolveImportedPath(std::string &Filename, StringRef Prefix);
1328
1329 /// Returns the first key declaration for the given declaration. This
1330 /// is one that is formerly-canonical (or still canonical) and whose module
1331 /// did not import any other key declaration of the entity.
1333 D = D->getCanonicalDecl();
1334 if (D->isFromASTFile())
1335 return D;
1336
1337 auto I = KeyDecls.find(D);
1338 if (I == KeyDecls.end() || I->second.empty())
1339 return D;
1340 return GetExistingDecl(I->second[0]);
1341 }
1342 const Decl *getKeyDeclaration(const Decl *D) {
1343 return getKeyDeclaration(const_cast<Decl*>(D));
1344 }
1345
1346 /// Run a callback on each imported key declaration of \p D.
1347 template <typename Fn>
1348 void forEachImportedKeyDecl(const Decl *D, Fn Visit) {
1349 D = D->getCanonicalDecl();
1350 if (D->isFromASTFile())
1351 Visit(D);
1352
1353 auto It = KeyDecls.find(const_cast<Decl*>(D));
1354 if (It != KeyDecls.end())
1355 for (auto ID : It->second)
1356 Visit(GetExistingDecl(ID));
1357 }
1358
1359 /// Get the loaded lookup tables for \p Primary, if any.
1361 getLoadedLookupTables(DeclContext *Primary) const;
1362
1363private:
1364 struct ImportedModule {
1365 ModuleFile *Mod;
1366 ModuleFile *ImportedBy;
1367 SourceLocation ImportLoc;
1368
1369 ImportedModule(ModuleFile *Mod,
1370 ModuleFile *ImportedBy,
1371 SourceLocation ImportLoc)
1372 : Mod(Mod), ImportedBy(ImportedBy), ImportLoc(ImportLoc) {}
1373 };
1374
1375 ASTReadResult ReadASTCore(StringRef FileName, ModuleKind Type,
1376 SourceLocation ImportLoc, ModuleFile *ImportedBy,
1377 SmallVectorImpl<ImportedModule> &Loaded,
1378 off_t ExpectedSize, time_t ExpectedModTime,
1379 ASTFileSignature ExpectedSignature,
1380 unsigned ClientLoadCapabilities);
1381 ASTReadResult ReadControlBlock(ModuleFile &F,
1382 SmallVectorImpl<ImportedModule> &Loaded,
1383 const ModuleFile *ImportedBy,
1384 unsigned ClientLoadCapabilities);
1385 static ASTReadResult ReadOptionsBlock(
1386 llvm::BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
1387 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
1388 std::string &SuggestedPredefines);
1389
1390 /// Read the unhashed control block.
1391 ///
1392 /// This has no effect on \c F.Stream, instead creating a fresh cursor from
1393 /// \c F.Data and reading ahead.
1394 ASTReadResult readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
1395 unsigned ClientLoadCapabilities);
1396
1397 static ASTReadResult
1398 readUnhashedControlBlockImpl(ModuleFile *F, llvm::StringRef StreamData,
1399 unsigned ClientLoadCapabilities,
1400 bool AllowCompatibleConfigurationMismatch,
1401 ASTReaderListener *Listener,
1402 bool ValidateDiagnosticOptions);
1403
1404 llvm::Error ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities);
1405 llvm::Error ReadExtensionBlock(ModuleFile &F);
1406 void ReadModuleOffsetMap(ModuleFile &F) const;
1407 void ParseLineTable(ModuleFile &F, const RecordData &Record);
1408 llvm::Error ReadSourceManagerBlock(ModuleFile &F);
1409 SourceLocation getImportLocation(ModuleFile *F);
1410 ASTReadResult ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
1411 const ModuleFile *ImportedBy,
1412 unsigned ClientLoadCapabilities);
1413 llvm::Error ReadSubmoduleBlock(ModuleFile &F,
1414 unsigned ClientLoadCapabilities);
1415 static bool ParseLanguageOptions(const RecordData &Record, bool Complain,
1416 ASTReaderListener &Listener,
1417 bool AllowCompatibleDifferences);
1418 static bool ParseTargetOptions(const RecordData &Record, bool Complain,
1419 ASTReaderListener &Listener,
1420 bool AllowCompatibleDifferences);
1421 static bool ParseDiagnosticOptions(const RecordData &Record, bool Complain,
1422 ASTReaderListener &Listener);
1423 static bool ParseFileSystemOptions(const RecordData &Record, bool Complain,
1424 ASTReaderListener &Listener);
1425 static bool ParseHeaderSearchOptions(const RecordData &Record, bool Complain,
1426 ASTReaderListener &Listener);
1427 static bool ParseHeaderSearchPaths(const RecordData &Record, bool Complain,
1428 ASTReaderListener &Listener);
1429 static bool ParsePreprocessorOptions(const RecordData &Record, bool Complain,
1430 ASTReaderListener &Listener,
1431 std::string &SuggestedPredefines);
1432
1433 struct RecordLocation {
1434 ModuleFile *F;
1435 uint64_t Offset;
1436
1437 RecordLocation(ModuleFile *M, uint64_t O) : F(M), Offset(O) {}
1438 };
1439
1440 QualType readTypeRecord(unsigned Index);
1441 RecordLocation TypeCursorForIndex(unsigned Index);
1442 void LoadedDecl(unsigned Index, Decl *D);
1443 Decl *ReadDeclRecord(GlobalDeclID ID);
1444 void markIncompleteDeclChain(Decl *D);
1445
1446 /// Returns the most recent declaration of a declaration (which must be
1447 /// of a redeclarable kind) that is either local or has already been loaded
1448 /// merged into its redecl chain.
1449 Decl *getMostRecentExistingDecl(Decl *D);
1450
1451 RecordLocation DeclCursorForID(GlobalDeclID ID, SourceLocation &Location);
1452 void loadDeclUpdateRecords(PendingUpdateRecord &Record);
1453 void loadPendingDeclChain(Decl *D, uint64_t LocalOffset);
1454 void loadObjCCategories(GlobalDeclID ID, ObjCInterfaceDecl *D,
1455 unsigned PreviousGeneration = 0);
1456
1457 RecordLocation getLocalBitOffset(uint64_t GlobalOffset);
1458 uint64_t getGlobalBitOffset(ModuleFile &M, uint64_t LocalOffset);
1459
1460 /// Returns the first preprocessed entity ID that begins or ends after
1461 /// \arg Loc.
1463 findPreprocessedEntity(SourceLocation Loc, bool EndsAfter) const;
1464
1465 /// Find the next module that contains entities and return the ID
1466 /// of the first entry.
1467 ///
1468 /// \param SLocMapI points at a chunk of a module that contains no
1469 /// preprocessed entities or the entities it contains are not the
1470 /// ones we are looking for.
1472 findNextPreprocessedEntity(
1474
1475 /// Returns (ModuleFile, Local index) pair for \p GlobalIndex of a
1476 /// preprocessed entity.
1477 std::pair<ModuleFile *, unsigned>
1478 getModulePreprocessedEntity(unsigned GlobalIndex);
1479
1480 /// Returns (begin, end) pair for the preprocessed entities of a
1481 /// particular module.
1482 llvm::iterator_range<PreprocessingRecord::iterator>
1483 getModulePreprocessedEntities(ModuleFile &Mod) const;
1484
1485 bool canRecoverFromOutOfDate(StringRef ModuleFileName,
1486 unsigned ClientLoadCapabilities);
1487
1488public:
1489 class ModuleDeclIterator : public llvm::iterator_adaptor_base<
1490 ModuleDeclIterator, const LocalDeclID *,
1491 std::random_access_iterator_tag, const Decl *,
1492 ptrdiff_t, const Decl *, const Decl *> {
1493 ASTReader *Reader = nullptr;
1494 ModuleFile *Mod = nullptr;
1495
1496 public:
1497 ModuleDeclIterator() : iterator_adaptor_base(nullptr) {}
1498
1500 const LocalDeclID *Pos)
1501 : iterator_adaptor_base(Pos), Reader(Reader), Mod(Mod) {}
1502
1503 value_type operator*() const {
1504 return Reader->GetDecl(Reader->getGlobalDeclID(*Mod, *I));
1505 }
1506
1507 value_type operator->() const { return **this; }
1508
1509 bool operator==(const ModuleDeclIterator &RHS) const {
1510 assert(Reader == RHS.Reader && Mod == RHS.Mod);
1511 return I == RHS.I;
1512 }
1513 };
1514
1515 llvm::iterator_range<ModuleDeclIterator>
1517
1518private:
1519 bool isConsumerInterestedIn(Decl *D);
1520 void PassInterestingDeclsToConsumer();
1521 void PassInterestingDeclToConsumer(Decl *D);
1522
1523 void finishPendingActions();
1524 void diagnoseOdrViolations();
1525
1526 void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name);
1527
1528 void addPendingDeclContextInfo(Decl *D, GlobalDeclID SemaDC,
1529 GlobalDeclID LexicalDC) {
1530 assert(D);
1531 PendingDeclContextInfo Info = { D, SemaDC, LexicalDC };
1532 PendingDeclContextInfos.push_back(Info);
1533 }
1534
1535 /// Produce an error diagnostic and return true.
1536 ///
1537 /// This routine should only be used for fatal errors that have to
1538 /// do with non-routine failures (e.g., corrupted AST file).
1539 void Error(StringRef Msg) const;
1540 void Error(unsigned DiagID, StringRef Arg1 = StringRef(),
1541 StringRef Arg2 = StringRef(), StringRef Arg3 = StringRef()) const;
1542 void Error(llvm::Error &&Err) const;
1543
1544public:
1545 /// Load the AST file and validate its contents against the given
1546 /// Preprocessor.
1547 ///
1548 /// \param PP the preprocessor associated with the context in which this
1549 /// precompiled header will be loaded.
1550 ///
1551 /// \param Context the AST context that this precompiled header will be
1552 /// loaded into, if any.
1553 ///
1554 /// \param PCHContainerRdr the PCHContainerOperations to use for loading and
1555 /// creating modules.
1556 ///
1557 /// \param Extensions the list of module file extensions that can be loaded
1558 /// from the AST files.
1559 ///
1560 /// \param isysroot If non-NULL, the system include path specified by the
1561 /// user. This is only used with relocatable PCH files. If non-NULL,
1562 /// a relocatable PCH file will use the default path "/".
1563 ///
1564 /// \param DisableValidationKind If set, the AST reader will suppress most
1565 /// of its regular consistency checking, allowing the use of precompiled
1566 /// headers and module files that cannot be determined to be compatible.
1567 ///
1568 /// \param AllowASTWithCompilerErrors If true, the AST reader will accept an
1569 /// AST file the was created out of an AST with compiler errors,
1570 /// otherwise it will reject it.
1571 ///
1572 /// \param AllowConfigurationMismatch If true, the AST reader will not check
1573 /// for configuration differences between the AST file and the invocation.
1574 ///
1575 /// \param ValidateSystemInputs If true, the AST reader will validate
1576 /// system input files in addition to user input files. This is only
1577 /// meaningful if \p DisableValidation is false.
1578 ///
1579 /// \param UseGlobalIndex If true, the AST reader will try to load and use
1580 /// the global module index.
1581 ///
1582 /// \param ReadTimer If non-null, a timer used to track the time spent
1583 /// deserializing.
1584 ASTReader(Preprocessor &PP, InMemoryModuleCache &ModuleCache,
1585 ASTContext *Context, const PCHContainerReader &PCHContainerRdr,
1586 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
1587 StringRef isysroot = "",
1588 DisableValidationForModuleKind DisableValidationKind =
1590 bool AllowASTWithCompilerErrors = false,
1591 bool AllowConfigurationMismatch = false,
1592 bool ValidateSystemInputs = false,
1593 bool ValidateASTInputFilesContent = false,
1594 bool UseGlobalIndex = true,
1595 std::unique_ptr<llvm::Timer> ReadTimer = {});
1596 ASTReader(const ASTReader &) = delete;
1597 ASTReader &operator=(const ASTReader &) = delete;
1598 ~ASTReader() override;
1599
1600 SourceManager &getSourceManager() const { return SourceMgr; }
1601 FileManager &getFileManager() const { return FileMgr; }
1602 DiagnosticsEngine &getDiags() const { return Diags; }
1603
1604 /// Flags that indicate what kind of AST loading failures the client
1605 /// of the AST reader can directly handle.
1606 ///
1607 /// When a client states that it can handle a particular kind of failure,
1608 /// the AST reader will not emit errors when producing that kind of failure.
1610 /// The client can't handle any AST loading failures.
1612
1613 /// The client can handle an AST file that cannot load because it
1614 /// is missing.
1616
1617 /// The client can handle an AST file that cannot load because it
1618 /// is out-of-date relative to its input files.
1620
1621 /// The client can handle an AST file that cannot load because it
1622 /// was built with a different version of Clang.
1624
1625 /// The client can handle an AST file that cannot load because it's
1626 /// compiled configuration doesn't match that of the context it was
1627 /// loaded into.
1629
1630 /// If a module file is marked with errors treat it as out-of-date so the
1631 /// caller can rebuild it.
1634
1635 /// Load the AST file designated by the given file name.
1636 ///
1637 /// \param FileName The name of the AST file to load.
1638 ///
1639 /// \param Type The kind of AST being loaded, e.g., PCH, module, main file,
1640 /// or preamble.
1641 ///
1642 /// \param ImportLoc the location where the module file will be considered as
1643 /// imported from. For non-module AST types it should be invalid.
1644 ///
1645 /// \param ClientLoadCapabilities The set of client load-failure
1646 /// capabilities, represented as a bitset of the enumerators of
1647 /// LoadFailureCapabilities.
1648 ///
1649 /// \param LoadedModuleFile The optional out-parameter refers to the new
1650 /// loaded modules. In case the module specified by FileName is already
1651 /// loaded, the module file pointer referred by NewLoadedModuleFile wouldn't
1652 /// change. Otherwise if the AST file get loaded successfully,
1653 /// NewLoadedModuleFile would refer to the address of the new loaded top level
1654 /// module. The state of NewLoadedModuleFile is unspecified if the AST file
1655 /// isn't loaded successfully.
1657 SourceLocation ImportLoc,
1658 unsigned ClientLoadCapabilities,
1659 ModuleFile **NewLoadedModuleFile = nullptr);
1660
1661 /// Make the entities in the given module and any of its (non-explicit)
1662 /// submodules visible to name lookup.
1663 ///
1664 /// \param Mod The module whose names should be made visible.
1665 ///
1666 /// \param NameVisibility The level of visibility to give the names in the
1667 /// module. Visibility can only be increased over time.
1668 ///
1669 /// \param ImportLoc The location at which the import occurs.
1670 void makeModuleVisible(Module *Mod,
1671 Module::NameVisibilityKind NameVisibility,
1672 SourceLocation ImportLoc);
1673
1674 /// Make the names within this set of hidden names visible.
1675 void makeNamesVisible(const HiddenNames &Names, Module *Owner);
1676
1677 /// Note that MergedDef is a redefinition of the canonical definition
1678 /// Def, so Def should be visible whenever MergedDef is.
1679 void mergeDefinitionVisibility(NamedDecl *Def, NamedDecl *MergedDef);
1680
1681 /// Take the AST callbacks listener.
1682 std::unique_ptr<ASTReaderListener> takeListener() {
1683 return std::move(Listener);
1684 }
1685
1686 /// Set the AST callbacks listener.
1687 void setListener(std::unique_ptr<ASTReaderListener> Listener) {
1688 this->Listener = std::move(Listener);
1689 }
1690
1691 /// Add an AST callback listener.
1692 ///
1693 /// Takes ownership of \p L.
1694 void addListener(std::unique_ptr<ASTReaderListener> L) {
1695 if (Listener)
1696 L = std::make_unique<ChainedASTReaderListener>(std::move(L),
1697 std::move(Listener));
1698 Listener = std::move(L);
1699 }
1700
1701 /// RAII object to temporarily add an AST callback listener.
1703 ASTReader &Reader;
1704 bool Chained = false;
1705
1706 public:
1707 ListenerScope(ASTReader &Reader, std::unique_ptr<ASTReaderListener> L)
1708 : Reader(Reader) {
1709 auto Old = Reader.takeListener();
1710 if (Old) {
1711 Chained = true;
1712 L = std::make_unique<ChainedASTReaderListener>(std::move(L),
1713 std::move(Old));
1714 }
1715 Reader.setListener(std::move(L));
1716 }
1717
1719 auto New = Reader.takeListener();
1720 if (Chained)
1721 Reader.setListener(static_cast<ChainedASTReaderListener *>(New.get())
1722 ->takeSecond());
1723 }
1724 };
1725
1726 /// Set the AST deserialization listener.
1728 bool TakeOwnership = false);
1729
1730 /// Get the AST deserialization listener.
1732 return DeserializationListener;
1733 }
1734
1735 /// Determine whether this AST reader has a global index.
1736 bool hasGlobalIndex() const { return (bool)GlobalIndex; }
1737
1738 /// Return global module index.
1739 GlobalModuleIndex *getGlobalIndex() { return GlobalIndex.get(); }
1740
1741 /// Reset reader for a reload try.
1742 void resetForReload() { TriedLoadingGlobalIndex = false; }
1743
1744 /// Attempts to load the global index.
1745 ///
1746 /// \returns true if loading the global index has failed for any reason.
1747 bool loadGlobalIndex();
1748
1749 /// Determine whether we tried to load the global index, but failed,
1750 /// e.g., because it is out-of-date or does not exist.
1751 bool isGlobalIndexUnavailable() const;
1752
1753 /// Initializes the ASTContext
1754 void InitializeContext();
1755
1756 /// Update the state of Sema after loading some additional modules.
1757 void UpdateSema();
1758
1759 /// Add in-memory (virtual file) buffer.
1761 std::unique_ptr<llvm::MemoryBuffer> Buffer) {
1762 ModuleMgr.addInMemoryBuffer(FileName, std::move(Buffer));
1763 }
1764
1765 /// Finalizes the AST reader's state before writing an AST file to
1766 /// disk.
1767 ///
1768 /// This operation may undo temporary state in the AST that should not be
1769 /// emitted.
1770 void finalizeForWriting();
1771
1772 /// Retrieve the module manager.
1773 ModuleManager &getModuleManager() { return ModuleMgr; }
1774 const ModuleManager &getModuleManager() const { return ModuleMgr; }
1775
1776 /// Retrieve the preprocessor.
1777 Preprocessor &getPreprocessor() const { return PP; }
1778
1779 /// Retrieve the name of the original source file name for the primary
1780 /// module file.
1782 return ModuleMgr.getPrimaryModule().OriginalSourceFileName;
1783 }
1784
1785 /// Retrieve the name of the original source file name directly from
1786 /// the AST file, without actually loading the AST file.
1787 static std::string
1788 getOriginalSourceFile(const std::string &ASTFileName, FileManager &FileMgr,
1789 const PCHContainerReader &PCHContainerRdr,
1790 DiagnosticsEngine &Diags);
1791
1792 /// Read the control block for the named AST file.
1793 ///
1794 /// \returns true if an error occurred, false otherwise.
1795 static bool readASTFileControlBlock(
1796 StringRef Filename, FileManager &FileMgr,
1797 const InMemoryModuleCache &ModuleCache,
1798 const PCHContainerReader &PCHContainerRdr, bool FindModuleFileExtensions,
1799 ASTReaderListener &Listener, bool ValidateDiagnosticOptions,
1800 unsigned ClientLoadCapabilities = ARR_ConfigurationMismatch |
1802
1803 /// Determine whether the given AST file is acceptable to load into a
1804 /// translation unit with the given language and target options.
1805 static bool isAcceptableASTFile(StringRef Filename, FileManager &FileMgr,
1806 const InMemoryModuleCache &ModuleCache,
1807 const PCHContainerReader &PCHContainerRdr,
1808 const LangOptions &LangOpts,
1809 const TargetOptions &TargetOpts,
1810 const PreprocessorOptions &PPOpts,
1811 StringRef ExistingModuleCachePath,
1812 bool RequireStrictOptionMatches = false);
1813
1814 /// Returns the suggested contents of the predefines buffer,
1815 /// which contains a (typically-empty) subset of the predefines
1816 /// build prior to including the precompiled header.
1817 const std::string &getSuggestedPredefines() { return SuggestedPredefines; }
1818
1819 /// Read a preallocated preprocessed entity from the external source.
1820 ///
1821 /// \returns null if an error occurred that prevented the preprocessed
1822 /// entity from being loaded.
1823 PreprocessedEntity *ReadPreprocessedEntity(unsigned Index) override;
1824
1825 /// Returns a pair of [Begin, End) indices of preallocated
1826 /// preprocessed entities that \p Range encompasses.
1827 std::pair<unsigned, unsigned>
1829
1830 /// Optionally returns true or false if the preallocated preprocessed
1831 /// entity with index \p Index came from file \p FID.
1832 std::optional<bool> isPreprocessedEntityInFileID(unsigned Index,
1833 FileID FID) override;
1834
1835 /// Read a preallocated skipped range from the external source.
1836 SourceRange ReadSkippedRange(unsigned Index) override;
1837
1838 /// Read the header file information for the given file entry.
1840
1842
1843 /// Returns the number of source locations found in the chain.
1844 unsigned getTotalNumSLocs() const {
1845 return TotalNumSLocEntries;
1846 }
1847
1848 /// Returns the number of identifiers found in the chain.
1849 unsigned getTotalNumIdentifiers() const {
1850 return static_cast<unsigned>(IdentifiersLoaded.size());
1851 }
1852
1853 /// Returns the number of macros found in the chain.
1854 unsigned getTotalNumMacros() const {
1855 return static_cast<unsigned>(MacrosLoaded.size());
1856 }
1857
1858 /// Returns the number of types found in the chain.
1859 unsigned getTotalNumTypes() const {
1860 return static_cast<unsigned>(TypesLoaded.size());
1861 }
1862
1863 /// Returns the number of declarations found in the chain.
1864 unsigned getTotalNumDecls() const {
1865 return static_cast<unsigned>(DeclsLoaded.size());
1866 }
1867
1868 /// Returns the number of submodules known.
1869 unsigned getTotalNumSubmodules() const {
1870 return static_cast<unsigned>(SubmodulesLoaded.size());
1871 }
1872
1873 /// Returns the number of selectors found in the chain.
1874 unsigned getTotalNumSelectors() const {
1875 return static_cast<unsigned>(SelectorsLoaded.size());
1876 }
1877
1878 /// Returns the number of preprocessed entities known to the AST
1879 /// reader.
1881 unsigned Result = 0;
1882 for (const auto &M : ModuleMgr)
1883 Result += M.NumPreprocessedEntities;
1884 return Result;
1885 }
1886
1887 /// Resolve a type ID into a type, potentially building a new
1888 /// type.
1890
1891 /// Resolve a local type ID within a given AST file into a type.
1892 QualType getLocalType(ModuleFile &F, unsigned LocalID);
1893
1894 /// Map a local type ID within a given AST file into a global type ID.
1895 serialization::TypeID getGlobalTypeID(ModuleFile &F, unsigned LocalID) const;
1896
1897 /// Read a type from the current position in the given record, which
1898 /// was read from the given AST file.
1899 QualType readType(ModuleFile &F, const RecordData &Record, unsigned &Idx) {
1900 if (Idx >= Record.size())
1901 return {};
1902
1903 return getLocalType(F, Record[Idx++]);
1904 }
1905
1906 /// Map from a local declaration ID within a given module to a
1907 /// global declaration ID.
1909
1910 /// Returns true if global DeclID \p ID originated from module \p M.
1911 bool isDeclIDFromModule(GlobalDeclID ID, ModuleFile &M) const;
1912
1913 /// Retrieve the module file that owns the given declaration, or NULL
1914 /// if the declaration is not from a module file.
1916
1917 /// Returns the source location for the decl \p ID.
1919
1920 /// Resolve a declaration ID into a declaration, potentially
1921 /// building a new declaration.
1923 Decl *GetExternalDecl(GlobalDeclID ID) override;
1924
1925 /// Resolve a declaration ID into a declaration. Return 0 if it's not
1926 /// been loaded yet.
1928
1929 /// Reads a declaration with the given local ID in the given module.
1931 return GetDecl(getGlobalDeclID(F, LocalID));
1932 }
1933
1934 /// Reads a declaration with the given local ID in the given module.
1935 ///
1936 /// \returns The requested declaration, casted to the given return type.
1937 template <typename T> T *GetLocalDeclAs(ModuleFile &F, LocalDeclID LocalID) {
1938 return cast_or_null<T>(GetLocalDecl(F, LocalID));
1939 }
1940
1941 /// Map a global declaration ID into the declaration ID used to
1942 /// refer to this declaration within the given module fule.
1943 ///
1944 /// \returns the global ID of the given declaration as known in the given
1945 /// module file.
1947 GlobalDeclID GlobalID);
1948
1949 /// Reads a declaration ID from the given position in a record in the
1950 /// given module.
1951 ///
1952 /// \returns The declaration ID read from the record, adjusted to a global ID.
1954 unsigned &Idx);
1955
1956 /// Reads a declaration from the given position in a record in the
1957 /// given module.
1958 Decl *ReadDecl(ModuleFile &F, const RecordData &R, unsigned &I) {
1959 return GetDecl(ReadDeclID(F, R, I));
1960 }
1961
1962 /// Reads a declaration from the given position in a record in the
1963 /// given module.
1964 ///
1965 /// \returns The declaration read from this location, casted to the given
1966 /// result type.
1967 template<typename T>
1968 T *ReadDeclAs(ModuleFile &F, const RecordData &R, unsigned &I) {
1969 return cast_or_null<T>(GetDecl(ReadDeclID(F, R, I)));
1970 }
1971
1972 /// If any redeclarations of \p D have been imported since it was
1973 /// last checked, this digs out those redeclarations and adds them to the
1974 /// redeclaration chain for \p D.
1975 void CompleteRedeclChain(const Decl *D) override;
1976
1977 CXXBaseSpecifier *GetExternalCXXBaseSpecifiers(uint64_t Offset) override;
1978
1979 /// Resolve the offset of a statement into a statement.
1980 ///
1981 /// This operation will read a new statement from the external
1982 /// source each time it is called, and is meant to be used via a
1983 /// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
1984 Stmt *GetExternalDeclStmt(uint64_t Offset) override;
1985
1986 /// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1987 /// specified cursor. Read the abbreviations that are at the top of the block
1988 /// and then leave the cursor pointing into the block.
1989 static llvm::Error ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
1990 unsigned BlockID,
1991 uint64_t *StartOfBlockOffset = nullptr);
1992
1993 /// Finds all the visible declarations with a given name.
1994 /// The current implementation of this method just loads the entire
1995 /// lookup table as unmaterialized references.
1997 DeclarationName Name) override;
1998
1999 /// Read all of the declarations lexically stored in a
2000 /// declaration context.
2001 ///
2002 /// \param DC The declaration context whose declarations will be
2003 /// read.
2004 ///
2005 /// \param IsKindWeWant A predicate indicating which declaration kinds
2006 /// we are interested in.
2007 ///
2008 /// \param Decls Vector that will contain the declarations loaded
2009 /// from the external source. The caller is responsible for merging
2010 /// these declarations with any declarations already stored in the
2011 /// declaration context.
2012 void
2014 llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
2015 SmallVectorImpl<Decl *> &Decls) override;
2016
2017 /// Get the decls that are contained in a file in the Offset/Length
2018 /// range. \p Length can be 0 to indicate a point at \p Offset instead of
2019 /// a range.
2020 void FindFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2021 SmallVectorImpl<Decl *> &Decls) override;
2022
2023 /// Notify ASTReader that we started deserialization of
2024 /// a decl or type so until FinishedDeserializing is called there may be
2025 /// decls that are initializing. Must be paired with FinishedDeserializing.
2026 void StartedDeserializing() override;
2027
2028 /// Notify ASTReader that we finished the deserialization of
2029 /// a decl or type. Must be paired with StartedDeserializing.
2030 void FinishedDeserializing() override;
2031
2032 /// Function that will be invoked when we begin parsing a new
2033 /// translation unit involving this external AST source.
2034 ///
2035 /// This function will provide all of the external definitions to
2036 /// the ASTConsumer.
2037 void StartTranslationUnit(ASTConsumer *Consumer) override;
2038
2039 /// Print some statistics about AST usage.
2040 void PrintStats() override;
2041
2042 /// Dump information about the AST reader to standard error.
2043 void dump();
2044
2045 /// Return the amount of memory used by memory buffers, breaking down
2046 /// by heap-backed versus mmap'ed memory.
2047 void getMemoryBufferSizes(MemoryBufferSizes &sizes) const override;
2048
2049 /// Initialize the semantic source with the Sema instance
2050 /// being used to perform semantic analysis on the abstract syntax
2051 /// tree.
2052 void InitializeSema(Sema &S) override;
2053
2054 /// Inform the semantic consumer that Sema is no longer available.
2055 void ForgetSema() override { SemaObj = nullptr; }
2056
2057 /// Retrieve the IdentifierInfo for the named identifier.
2058 ///
2059 /// This routine builds a new IdentifierInfo for the given identifier. If any
2060 /// declarations with this name are visible from translation unit scope, their
2061 /// declarations will be deserialized and introduced into the declaration
2062 /// chain of the identifier.
2063 IdentifierInfo *get(StringRef Name) override;
2064
2065 /// Retrieve an iterator into the set of all identifiers
2066 /// in all loaded AST files.
2068
2069 /// Load the contents of the global method pool for a given
2070 /// selector.
2071 void ReadMethodPool(Selector Sel) override;
2072
2073 /// Load the contents of the global method pool for a given
2074 /// selector if necessary.
2075 void updateOutOfDateSelector(Selector Sel) override;
2076
2077 /// Load the set of namespaces that are known to the external source,
2078 /// which will be used during typo correction.
2080 SmallVectorImpl<NamespaceDecl *> &Namespaces) override;
2081
2083 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) override;
2084
2085 void ReadMismatchingDeleteExpressions(llvm::MapVector<
2086 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
2087 Exprs) override;
2088
2090 SmallVectorImpl<VarDecl *> &TentativeDefs) override;
2091
2094
2097
2099
2102
2104 llvm::SmallSetVector<Decl *, 4> &Decls) override;
2105
2107 SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) override;
2108
2110 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WeakIDs) override;
2111
2113
2115 SmallVectorImpl<std::pair<ValueDecl *,
2116 SourceLocation>> &Pending) override;
2117
2119 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
2120 &LPTMap) override;
2121
2122 void AssignedLambdaNumbering(const CXXRecordDecl *Lambda) override;
2123
2124 /// Load a selector from disk, registering its ID if it exists.
2125 void LoadSelector(Selector Sel);
2126
2127 void SetIdentifierInfo(unsigned ID, IdentifierInfo *II);
2129 const SmallVectorImpl<GlobalDeclID> &DeclIDs,
2130 SmallVectorImpl<Decl *> *Decls = nullptr);
2131
2132 /// Report a diagnostic.
2133 DiagnosticBuilder Diag(unsigned DiagID) const;
2134
2135 /// Report a diagnostic.
2136 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) const;
2137
2139
2141 unsigned &Idx) {
2143 }
2144
2146 // Note that we are loading an identifier.
2147 Deserializing AnIdentifier(this);
2148
2149 return DecodeIdentifierInfo(ID);
2150 }
2151
2152 IdentifierInfo *getLocalIdentifier(ModuleFile &M, unsigned LocalID);
2153
2155 unsigned LocalID);
2156
2157 void resolvePendingMacro(IdentifierInfo *II, const PendingMacroInfo &PMInfo);
2158
2159 /// Retrieve the macro with the given ID.
2161
2162 /// Retrieve the global macro ID corresponding to the given local
2163 /// ID within the given module file.
2165
2166 /// Read the source location entry with index ID.
2167 bool ReadSLocEntry(int ID) override;
2168 /// Get the index ID for the loaded SourceLocation offset.
2169 int getSLocEntryID(SourceLocation::UIntTy SLocOffset) override;
2170 /// Try to read the offset of the SLocEntry at the given index in the given
2171 /// module file.
2173 unsigned Index);
2174
2175 /// Retrieve the module import location and module name for the
2176 /// given source manager entry ID.
2177 std::pair<SourceLocation, StringRef> getModuleImportLoc(int ID) override;
2178
2179 /// Retrieve the global submodule ID given a module and its local ID
2180 /// number.
2182 unsigned LocalID) const;
2183
2184 /// Retrieve the submodule that corresponds to a global submodule ID.
2185 ///
2187
2188 /// Retrieve the module that corresponds to the given module ID.
2189 ///
2190 /// Note: overrides method in ExternalASTSource
2191 Module *getModule(unsigned ID) override;
2192
2193 /// Retrieve the module file with a given local ID within the specified
2194 /// ModuleFile.
2195 ModuleFile *getLocalModuleFile(ModuleFile &M, unsigned ID) const;
2196
2197 /// Get an ID for the given module file.
2198 unsigned getModuleFileID(ModuleFile *M);
2199
2200 /// Return a descriptor for the corresponding module.
2201 std::optional<ASTSourceDescriptor> getSourceDescriptor(unsigned ID) override;
2202
2203 ExtKind hasExternalDefinitions(const Decl *D) override;
2204
2205 /// Retrieve a selector from the given module with its local ID
2206 /// number.
2207 Selector getLocalSelector(ModuleFile &M, unsigned LocalID);
2208
2210
2212 uint32_t GetNumExternalSelectors() override;
2213
2214 Selector ReadSelector(ModuleFile &M, const RecordData &Record, unsigned &Idx) {
2215 return getLocalSelector(M, Record[Idx++]);
2216 }
2217
2218 /// Retrieve the global selector ID that corresponds to this
2219 /// the local selector ID in a given module.
2221 unsigned LocalID) const;
2222
2223 /// Read the contents of a CXXCtorInitializer array.
2224 CXXCtorInitializer **GetExternalCXXCtorInitializers(uint64_t Offset) override;
2225
2226 /// Read a AlignPackInfo from raw form.
2229 }
2230
2232
2233 /// Read a source location from raw form and return it in its
2234 /// originating module file's source location space.
2235 std::pair<SourceLocation, unsigned>
2237 LocSeq *Seq = nullptr) const {
2239 }
2240
2241 /// Read a source location from raw form.
2243 LocSeq *Seq = nullptr) const {
2244 if (!MF.ModuleOffsetMap.empty())
2245 ReadModuleOffsetMap(MF);
2246
2247 auto [Loc, ModuleFileIndex] = ReadUntranslatedSourceLocation(Raw, Seq);
2248 ModuleFile *OwningModuleFile =
2249 ModuleFileIndex == 0 ? &MF : MF.DependentModules[ModuleFileIndex - 1];
2250
2251 assert(!SourceMgr.isLoadedSourceLocation(Loc) &&
2252 "Run out source location space");
2253
2254 return TranslateSourceLocation(*OwningModuleFile, Loc);
2255 }
2256
2257 /// Translate a source location from another module file's source
2258 /// location space into ours.
2260 SourceLocation Loc) const {
2261 if (Loc.isInvalid())
2262 return Loc;
2263
2264 // FIXME: TranslateSourceLocation is not re-enterable. It is problematic
2265 // to call TranslateSourceLocation on a translated source location.
2266 // We either need a method to know whether or not a source location is
2267 // translated or refactor the code to make it clear that
2268 // TranslateSourceLocation won't be called with translated source location.
2269
2270 return Loc.getLocWithOffset(ModuleFile.SLocEntryBaseOffset - 2);
2271 }
2272
2273 /// Read a source location.
2275 const RecordDataImpl &Record, unsigned &Idx,
2276 LocSeq *Seq = nullptr) {
2277 return ReadSourceLocation(ModuleFile, Record[Idx++], Seq);
2278 }
2279
2280 /// Read a FileID.
2282 unsigned &Idx) const {
2283 return TranslateFileID(F, FileID::get(Record[Idx++]));
2284 }
2285
2286 /// Translate a FileID from another module file's FileID space into ours.
2288 assert(FID.ID >= 0 && "Reading non-local FileID.");
2289 return FileID::get(F.SLocEntryBaseID + FID.ID - 1);
2290 }
2291
2292 /// Read a source range.
2294 unsigned &Idx, LocSeq *Seq = nullptr);
2295
2296 static llvm::BitVector ReadBitVector(const RecordData &Record,
2297 const StringRef Blob);
2298
2299 // Read a string
2300 static std::string ReadString(const RecordDataImpl &Record, unsigned &Idx);
2301
2302 // Skip a string
2303 static void SkipString(const RecordData &Record, unsigned &Idx) {
2304 Idx += Record[Idx] + 1;
2305 }
2306
2307 // Read a path
2308 std::string ReadPath(ModuleFile &F, const RecordData &Record, unsigned &Idx);
2309
2310 // Read a path
2311 std::string ReadPath(StringRef BaseDirectory, const RecordData &Record,
2312 unsigned &Idx);
2313
2314 // Skip a path
2315 static void SkipPath(const RecordData &Record, unsigned &Idx) {
2316 SkipString(Record, Idx);
2317 }
2318
2319 /// Read a version tuple.
2320 static VersionTuple ReadVersionTuple(const RecordData &Record, unsigned &Idx);
2321
2323 unsigned &Idx);
2324
2325 /// Reads a statement.
2327
2328 /// Reads an expression.
2330
2331 /// Reads a sub-statement operand during statement reading.
2333 assert(ReadingKind == Read_Stmt &&
2334 "Should be called only during statement reading!");
2335 // Subexpressions are stored from last to first, so the next Stmt we need
2336 // is at the back of the stack.
2337 assert(!StmtStack.empty() && "Read too many sub-statements!");
2338 return StmtStack.pop_back_val();
2339 }
2340
2341 /// Reads a sub-expression operand during statement reading.
2342 Expr *ReadSubExpr();
2343
2344 /// Reads a token out of a record.
2345 Token ReadToken(ModuleFile &M, const RecordDataImpl &Record, unsigned &Idx);
2346
2347 /// Reads the macro record located at the given offset.
2348 MacroInfo *ReadMacroRecord(ModuleFile &F, uint64_t Offset);
2349
2350 /// Determine the global preprocessed entity ID that corresponds to
2351 /// the given local ID within the given module.
2353 getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const;
2354
2355 /// Add a macro to deserialize its macro directive history.
2356 ///
2357 /// \param II The name of the macro.
2358 /// \param M The module file.
2359 /// \param MacroDirectivesOffset Offset of the serialized macro directive
2360 /// history.
2362 uint32_t MacroDirectivesOffset);
2363
2364 /// Read the set of macros defined by this external macro source.
2365 void ReadDefinedMacros() override;
2366
2367 /// Update an out-of-date identifier.
2368 void updateOutOfDateIdentifier(const IdentifierInfo &II) override;
2369
2370 /// Note that this identifier is up-to-date.
2371 void markIdentifierUpToDate(const IdentifierInfo *II);
2372
2373 /// Load all external visible decls in the given DeclContext.
2374 void completeVisibleDeclsMap(const DeclContext *DC) override;
2375
2376 /// Retrieve the AST context that this AST reader supplements.
2378 assert(ContextObj && "requested AST context when not loading AST");
2379 return *ContextObj;
2380 }
2381
2382 // Contains the IDs for declarations that were requested before we have
2383 // access to a Sema object.
2385
2386 /// Retrieve the semantic analysis object used to analyze the
2387 /// translation unit in which the precompiled header is being
2388 /// imported.
2389 Sema *getSema() { return SemaObj; }
2390
2391 /// Get the identifier resolver used for name lookup / updates
2392 /// in the translation unit scope. We have one of these even if we don't
2393 /// have a Sema object.
2395
2396 /// Retrieve the identifier table associated with the
2397 /// preprocessor.
2399
2400 /// Record that the given ID maps to the given switch-case
2401 /// statement.
2402 void RecordSwitchCaseID(SwitchCase *SC, unsigned ID);
2403
2404 /// Retrieve the switch-case statement with the given ID.
2405 SwitchCase *getSwitchCaseWithID(unsigned ID);
2406
2407 void ClearSwitchCaseIDs();
2408
2409 /// Cursors for comments blocks.
2410 SmallVector<std::pair<llvm::BitstreamCursor,
2412
2413 /// Loads comments ranges.
2414 void ReadComments() override;
2415
2416 /// Visit all the input file infos of the given module file.
2418 serialization::ModuleFile &MF, bool IncludeSystem,
2419 llvm::function_ref<void(const serialization::InputFileInfo &IFI,
2420 bool IsSystem)>
2421 Visitor);
2422
2423 /// Visit all the input files of the given module file.
2425 bool IncludeSystem, bool Complain,
2426 llvm::function_ref<void(const serialization::InputFile &IF,
2427 bool isSystem)> Visitor);
2428
2429 /// Visit all the top-level module maps loaded when building the given module
2430 /// file.
2432 llvm::function_ref<void(FileEntryRef)> Visitor);
2433
2434 bool isProcessingUpdateRecords() { return ProcessingUpdateRecords; }
2435};
2436
2437/// A simple helper class to unpack an integer to bits and consuming
2438/// the bits in order.
2440 constexpr static uint32_t BitsIndexUpbound = 32;
2441
2442public:
2443 BitsUnpacker(uint32_t V) { updateValue(V); }
2444 BitsUnpacker(const BitsUnpacker &) = delete;
2448 ~BitsUnpacker() = default;
2449
2450 void updateValue(uint32_t V) {
2451 Value = V;
2452 CurrentBitsIndex = 0;
2453 }
2454
2455 void advance(uint32_t BitsWidth) { CurrentBitsIndex += BitsWidth; }
2456
2457 bool getNextBit() {
2458 assert(isValid());
2459 return Value & (1 << CurrentBitsIndex++);
2460 }
2461
2462 uint32_t getNextBits(uint32_t Width) {
2463 assert(isValid());
2464 assert(Width < BitsIndexUpbound);
2465 uint32_t Ret = (Value >> CurrentBitsIndex) & ((1 << Width) - 1);
2466 CurrentBitsIndex += Width;
2467 return Ret;
2468 }
2469
2470 bool canGetNextNBits(uint32_t Width) const {
2471 return CurrentBitsIndex + Width < BitsIndexUpbound;
2472 }
2473
2474private:
2475 bool isValid() const { return CurrentBitsIndex < BitsIndexUpbound; }
2476
2477 uint32_t Value;
2478 uint32_t CurrentBitsIndex = ~0;
2479};
2480
2481inline bool shouldSkipCheckingODR(const Decl *D) {
2482 return D->getASTContext().getLangOpts().SkipODRCheckInGMF &&
2484}
2485
2486} // namespace clang
2487
2488#endif // LLVM_CLANG_SERIALIZATION_ASTREADER_H
#define V(N, I)
Definition: ASTContext.h:3285
Defines the Diagnostic-related interfaces.
StringRef Filename
Definition: Format.cpp:2975
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
llvm::MachO::Record Record
Definition: MachO.h:31
Defines the clang::OpenCLOptions class.
SourceRange Range
Definition: SemaObjC.cpp:754
SourceLocation Loc
Definition: SemaObjC.cpp:755
Defines the clang::SourceLocation class and associated facilities.
const char * Data
C Language Family Type Representation.
Defines version macros and version-related utility functions for Clang.
ASTConsumer - This is an abstract interface that should be implemented by clients that read ASTs.
Definition: ASTConsumer.h:33
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:182
const LangOptions & getLangOpts() const
Definition: ASTContext.h:775
An identifier-lookup iterator that enumerates all of the identifiers stored within a set of AST files...
Definition: ASTReader.cpp:8373
Abstract interface for callback invocations by the ASTReader.
Definition: ASTReader.h:114
virtual bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath, bool Complain)
Receives the header search options.
Definition: ASTReader.h:174
virtual void ReadModuleMapFile(StringRef ModuleMapPath)
Definition: ASTReader.h:127
virtual bool needsInputFileVisitation()
Returns true if this ASTReaderListener wants to receive the input files of the AST file via visitInpu...
Definition: ASTReader.h:218
virtual bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain, bool AllowCompatibleDifferences)
Receives the target options.
Definition: ASTReader.h:142
virtual bool visitInputFile(StringRef Filename, bool isSystem, bool isOverridden, bool isExplicitModule)
if needsInputFileVisitation returns true, this is called for each non-system input file of the AST Fi...
Definition: ASTReader.h:230
virtual bool ReadHeaderSearchPaths(const HeaderSearchOptions &HSOpts, bool Complain)
Receives the header search paths.
Definition: ASTReader.h:189
virtual bool ReadFileSystemOptions(const FileSystemOptions &FSOpts, bool Complain)
Receives the file system options.
Definition: ASTReader.h:161
virtual bool ReadDiagnosticOptions(IntrusiveRefCntPtr< DiagnosticOptions > DiagOpts, bool Complain)
Receives the diagnostic options.
Definition: ASTReader.h:152
virtual void readModuleFileExtension(const ModuleFileExtensionMetadata &Metadata)
Indicates that a particular module file extension has been read.
Definition: ASTReader.h:244
virtual bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain, bool AllowCompatibleDifferences)
Receives the language options.
Definition: ASTReader.h:132
virtual void visitImport(StringRef ModuleName, StringRef Filename)
If needsImportVisitation returns true, this is called for each AST file imported by this AST file.
Definition: ASTReader.h:241
virtual void visitModuleFile(StringRef Filename, serialization::ModuleKind Kind)
This is called for each AST file loaded.
Definition: ASTReader.h:213
virtual bool needsImportVisitation() const
Returns true if this ASTReaderListener wants to receive the imports of the AST file via visitImport,...
Definition: ASTReader.h:237
virtual bool ReadFullVersionInformation(StringRef FullVersion)
Receives the full Clang version information.
Definition: ASTReader.h:122
virtual void ReadCounter(const serialization::ModuleFile &M, unsigned Value)
Receives COUNTER value.
Definition: ASTReader.h:209
virtual void ReadModuleName(StringRef ModuleName)
Definition: ASTReader.h:126
virtual bool needsSystemInputFileVisitation()
Returns true if this ASTReaderListener wants to receive the system input files of the AST file via vi...
Definition: ASTReader.h:222
virtual bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool ReadMacros, bool Complain, std::string &SuggestedPredefines)
Receives the preprocessor options.
Definition: ASTReader.h:202
RAII object to temporarily add an AST callback listener.
Definition: ASTReader.h:1702
ListenerScope(ASTReader &Reader, std::unique_ptr< ASTReaderListener > L)
Definition: ASTReader.h:1707
bool operator==(const ModuleDeclIterator &RHS) const
Definition: ASTReader.h:1509
ModuleDeclIterator(ASTReader *Reader, ModuleFile *Mod, const LocalDeclID *Pos)
Definition: ASTReader.h:1499
Reads an AST files chain containing the contents of a translation unit.
Definition: ASTReader.h:366
std::optional< bool > isPreprocessedEntityInFileID(unsigned Index, FileID FID) override
Optionally returns true or false if the preallocated preprocessed entity with index Index came from f...
Definition: ASTReader.cpp:6473
PreprocessedEntity * ReadPreprocessedEntity(unsigned Index) override
Read a preallocated preprocessed entity from the external source.
Definition: ASTReader.cpp:6254
void markIdentifierUpToDate(const IdentifierInfo *II)
Note that this identifier is up-to-date.
Definition: ASTReader.cpp:2249
void visitTopLevelModuleMaps(serialization::ModuleFile &MF, llvm::function_ref< void(FileEntryRef)> Visitor)
Visit all the top-level module maps loaded when building the given module file.
Definition: ASTReader.cpp:9535
void setDeserializationListener(ASTDeserializationListener *Listener, bool TakeOwnership=false)
Set the AST deserialization listener.
Definition: ASTReader.cpp:899
SmallVectorImpl< uint64_t > RecordDataImpl
Definition: ASTReader.h:380
serialization::SubmoduleID getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) const
Retrieve the global submodule ID given a module and its local ID number.
Definition: ASTReader.cpp:8960
ExtKind hasExternalDefinitions(const Decl *D) override
Definition: ASTReader.cpp:9041
IdentifierTable & getIdentifierTable()
Retrieve the identifier table associated with the preprocessor.
Definition: ASTReader.cpp:9410
SourceLocationEncoding::RawLocEncoding RawLocEncoding
Definition: ASTReader.h:2231
ModuleManager & getModuleManager()
Retrieve the module manager.
Definition: ASTReader.h:1773
ASTReader & operator=(const ASTReader &)=delete
bool isDeclIDFromModule(GlobalDeclID ID, ModuleFile &M) const
Returns true if global DeclID ID originated from module M.
Definition: ASTReader.cpp:7661
bool ReadSLocEntry(int ID) override
Read the source location entry with index ID.
Definition: ASTReader.cpp:1533
void RecordSwitchCaseID(SwitchCase *SC, unsigned ID)
Record that the given ID maps to the given switch-case statement.
Definition: ASTReader.cpp:9416
DiagnosticBuilder Diag(unsigned DiagID) const
Report a diagnostic.
Definition: ASTReader.cpp:9400
unsigned getTotalNumPreprocessedEntities() const
Returns the number of preprocessed entities known to the AST reader.
Definition: ASTReader.h:1880
ASTContext & getContext()
Retrieve the AST context that this AST reader supplements.
Definition: ASTReader.h:2377
ModuleManager::ModuleIterator ModuleIterator
Definition: ASTReader.h:413
static std::string ReadString(const RecordDataImpl &Record, unsigned &Idx)
Definition: ASTReader.cpp:9359
void ReadDeclsToCheckForDeferredDiags(llvm::SmallSetVector< Decl *, 4 > &Decls) override
Read the set of decls to be checked for deferred diags.
Definition: ASTReader.cpp:8695
void InitializeSema(Sema &S) override
Initialize the semantic source with the Sema instance being used to perform semantic analysis on the ...
Definition: ASTReader.cpp:8203
LoadFailureCapabilities
Flags that indicate what kind of AST loading failures the client of the AST reader can directly handl...
Definition: ASTReader.h:1609
@ ARR_Missing
The client can handle an AST file that cannot load because it is missing.
Definition: ASTReader.h:1615
@ ARR_None
The client can't handle any AST loading failures.
Definition: ASTReader.h:1611
@ ARR_ConfigurationMismatch
The client can handle an AST file that cannot load because it's compiled configuration doesn't match ...
Definition: ASTReader.h:1628
@ ARR_OutOfDate
The client can handle an AST file that cannot load because it is out-of-date relative to its input fi...
Definition: ASTReader.h:1619
@ ARR_TreatModuleWithErrorsAsOutOfDate
If a module file is marked with errors treat it as out-of-date so the caller can rebuild it.
Definition: ASTReader.h:1632
@ ARR_VersionMismatch
The client can handle an AST file that cannot load because it was built with a different version of C...
Definition: ASTReader.h:1623
void ReadMismatchingDeleteExpressions(llvm::MapVector< FieldDecl *, llvm::SmallVector< std::pair< SourceLocation, bool >, 4 > > &Exprs) override
Definition: ASTReader.cpp:8625
void FindFileRegionDecls(FileID File, unsigned Offset, unsigned Length, SmallVectorImpl< Decl * > &Decls) override
Get the decls that are contained in a file in the Offset/Length range.
Definition: ASTReader.cpp:7928
SourceRange ReadSkippedRange(unsigned Index) override
Read a preallocated skipped range from the external source.
Definition: ASTReader.cpp:6240
const std::string & getSuggestedPredefines()
Returns the suggested contents of the predefines buffer, which contains a (typically-empty) subset of...
Definition: ASTReader.h:1817
void dump()
Dump information about the AST reader to standard error.
Definition: ASTReader.cpp:8167
serialization::IdentifierID getGlobalIdentifierID(ModuleFile &M, unsigned LocalID)
Definition: ASTReader.cpp:8903
void AssignedLambdaNumbering(const CXXRecordDecl *Lambda) override
Notify the external source that a lambda was assigned a mangling number.
Definition: ASTReader.cpp:8796
MacroInfo * ReadMacroRecord(ModuleFile &F, uint64_t Offset)
Reads the macro record located at the given offset.
Definition: ASTReader.cpp:1834
SmallVector< std::pair< llvm::BitstreamCursor, serialization::ModuleFile * >, 8 > CommentsCursors
Cursors for comments blocks.
Definition: ASTReader.h:2411
Selector getLocalSelector(ModuleFile &M, unsigned LocalID)
Retrieve a selector from the given module with its local ID number.
Definition: ASTReader.cpp:9048
void FindExternalLexicalDecls(const DeclContext *DC, llvm::function_ref< bool(Decl::Kind)> IsKindWeWant, SmallVectorImpl< Decl * > &Decls) override
Read all of the declarations lexically stored in a declaration context.
Definition: ASTReader.cpp:7852
std::optional< ASTSourceDescriptor > getSourceDescriptor(unsigned ID) override
Return a descriptor for the corresponding module.
Definition: ASTReader.cpp:9023
const serialization::reader::DeclContextLookupTable * getLoadedLookupTables(DeclContext *Primary) const
Get the loaded lookup tables for Primary, if any.
Definition: ASTReader.cpp:8021
void ClearSwitchCaseIDs()
Definition: ASTReader.cpp:9428
Sema::AlignPackInfo ReadAlignPackInfo(uint32_t Raw) const
Read a AlignPackInfo from raw form.
Definition: ASTReader.h:2227
QualType readType(ModuleFile &F, const RecordData &Record, unsigned &Idx)
Read a type from the current position in the given record, which was read from the given AST file.
Definition: ASTReader.h:1899
SourceLocation ReadSourceLocation(ModuleFile &MF, RawLocEncoding Raw, LocSeq *Seq=nullptr) const
Read a source location from raw form.
Definition: ASTReader.h:2242
void SetGloballyVisibleDecls(IdentifierInfo *II, const SmallVectorImpl< GlobalDeclID > &DeclIDs, SmallVectorImpl< Decl * > *Decls=nullptr)
Set the globally-visible declarations associated with the given identifier.
Definition: ASTReader.cpp:8836
void SetIdentifierInfo(unsigned ID, IdentifierInfo *II)
Definition: ASTReader.cpp:8812
serialization::ModuleKind ModuleKind
Definition: ASTReader.h:411
bool loadGlobalIndex()
Attempts to load the global index.
Definition: ASTReader.cpp:4341
void ReadComments() override
Loads comments ranges.
Definition: ASTReader.cpp:9432
SourceManager & getSourceManager() const
Definition: ASTReader.h:1600
SourceLocation getSourceLocationForDeclID(GlobalDeclID ID)
Returns the source location for the decl ID.
Definition: ASTReader.cpp:7679
void makeModuleVisible(Module *Mod, Module::NameVisibilityKind NameVisibility, SourceLocation ImportLoc)
Make the entities in the given module and any of its (non-explicit) submodules visible to name lookup...
Definition: ASTReader.cpp:4277
unsigned getTotalNumSubmodules() const
Returns the number of submodules known.
Definition: ASTReader.h:1869
ASTReader(const ASTReader &)=delete
void finalizeForWriting()
Finalizes the AST reader's state before writing an AST file to disk.
Definition: ASTReader.cpp:5231
Sema * getSema()
Retrieve the semantic analysis object used to analyze the translation unit in which the precompiled h...
Definition: ASTReader.h:2389
unsigned getTotalNumIdentifiers() const
Returns the number of identifiers found in the chain.
Definition: ASTReader.h:1849
CXXCtorInitializer ** GetExternalCXXCtorInitializers(uint64_t Offset) override
Read the contents of a CXXCtorInitializer array.
Definition: ASTReader.cpp:7571
void visitInputFileInfos(serialization::ModuleFile &MF, bool IncludeSystem, llvm::function_ref< void(const serialization::InputFileInfo &IFI, bool IsSystem)> Visitor)
Visit all the input file infos of the given module file.
Definition: ASTReader.cpp:9504
const ModuleManager & getModuleManager() const
Definition: ASTReader.h:1774
unsigned getTotalNumSLocs() const
Returns the number of source locations found in the chain.
Definition: ASTReader.h:1844
void StartTranslationUnit(ASTConsumer *Consumer) override
Function that will be invoked when we begin parsing a new translation unit involving this external AS...
Definition: ASTReader.cpp:8047
LocalDeclID mapGlobalIDToModuleFileGlobalID(ModuleFile &M, GlobalDeclID GlobalID)
Map a global declaration ID into the declaration ID used to refer to this declaration within the give...
Definition: ASTReader.cpp:7803
void resolvePendingMacro(IdentifierInfo *II, const PendingMacroInfo &PMInfo)
Definition: ASTReader.cpp:2260
bool FindExternalVisibleDeclsByName(const DeclContext *DC, DeclarationName Name) override
Finds all the visible declarations with a given name.
Definition: ASTReader.cpp:7969
void ReadTentativeDefinitions(SmallVectorImpl< VarDecl * > &TentativeDefs) override
Read the set of tentative definitions known to the external Sema source.
Definition: ASTReader.cpp:8641
Decl * GetExternalDecl(GlobalDeclID ID) override
Resolve a declaration ID into a declaration, potentially building a new declaration.
Definition: ASTReader.cpp:7512
std::pair< SourceLocation, unsigned > ReadUntranslatedSourceLocation(RawLocEncoding Raw, LocSeq *Seq=nullptr) const
Read a source location from raw form and return it in its originating module file's source location s...
Definition: ASTReader.h:2236
llvm::Expected< SourceLocation::UIntTy > readSLocOffset(ModuleFile *F, unsigned Index)
Try to read the offset of the SLocEntry at the given index in the given module file.
Definition: ASTReader.cpp:1461
void forEachImportedKeyDecl(const Decl *D, Fn Visit)
Run a callback on each imported key declaration of D.
Definition: ASTReader.h:1348
~ASTReader() override
static void SkipPath(const RecordData &Record, unsigned &Idx)
Definition: ASTReader.h:2315
Stmt * ReadSubStmt()
Reads a sub-statement operand during statement reading.
Definition: ASTReader.h:2332
void CompleteRedeclChain(const Decl *D) override
If any redeclarations of D have been imported since it was last checked, this digs out those redeclar...
Definition: ASTReader.cpp:7514
Expr * ReadSubExpr()
Reads a sub-expression operand during statement reading.
SourceLocation TranslateSourceLocation(ModuleFile &ModuleFile, SourceLocation Loc) const
Translate a source location from another module file's source location space into ours.
Definition: ASTReader.h:2259
static llvm::Error ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor, unsigned BlockID, uint64_t *StartOfBlockOffset=nullptr)
ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the specified cursor.
Definition: ASTReader.cpp:1755
serialization::PreprocessedEntityID getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const
Determine the global preprocessed entity ID that corresponds to the given local ID within the given m...
Definition: ASTReader.cpp:1965
std::pair< unsigned, unsigned > findPreprocessedEntitiesInRange(SourceRange Range) override
Returns a pair of [Begin, End) indices of preallocated preprocessed entities that Range encompasses.
Definition: ASTReader.cpp:6460
IdentifierInfo * get(StringRef Name) override
Retrieve the IdentifierInfo for the named identifier.
Definition: ASTReader.cpp:8334
void visitInputFiles(serialization::ModuleFile &MF, bool IncludeSystem, bool Complain, llvm::function_ref< void(const serialization::InputFile &IF, bool isSystem)> Visitor)
Visit all the input files of the given module file.
Definition: ASTReader.cpp:9520
Module * getModule(unsigned ID) override
Retrieve the module that corresponds to the given module ID.
Definition: ASTReader.cpp:8989
llvm::iterator_range< ModuleDeclIterator > getModuleFileLevelDecls(ModuleFile &Mod)
Definition: ASTReader.cpp:6233
GlobalDeclID ReadDeclID(ModuleFile &F, const RecordData &Record, unsigned &Idx)
Reads a declaration ID from the given position in a record in the given module.
Definition: ASTReader.cpp:7821
Stmt * GetExternalDeclStmt(uint64_t Offset) override
Resolve the offset of a statement into a statement.
Definition: ASTReader.cpp:7836
Selector GetExternalSelector(serialization::SelectorID ID) override
Resolve a selector ID into a selector.
Definition: ASTReader.cpp:9077
unsigned getTotalNumSelectors() const
Returns the number of selectors found in the chain.
Definition: ASTReader.h:1874
MacroInfo * getMacro(serialization::MacroID ID)
Retrieve the macro with the given ID.
Definition: ASTReader.cpp:8918
void ReadUndefinedButUsed(llvm::MapVector< NamedDecl *, SourceLocation > &Undefined) override
Load the set of used but not defined functions or variables with internal linkage,...
Definition: ASTReader.cpp:8614
void ReadDelegatingConstructors(SmallVectorImpl< CXXConstructorDecl * > &Decls) override
Read the set of delegating constructors known to the external Sema source.
Definition: ASTReader.cpp:8662
unsigned getTotalNumTypes() const
Returns the number of types found in the chain.
Definition: ASTReader.h:1859
QualType GetType(serialization::TypeID ID)
Resolve a type ID into a type, potentially building a new type.
Definition: ASTReader.cpp:7138
void addPendingMacro(IdentifierInfo *II, ModuleFile *M, uint32_t MacroDirectivesOffset)
Add a macro to deserialize its macro directive history.
Definition: ASTReader.cpp:2100
SourceRange ReadSourceRange(ModuleFile &F, const RecordData &Record, unsigned &Idx, LocSeq *Seq=nullptr)
Read a source range.
Definition: ASTReader.cpp:9334
GlobalDeclID getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const
Map from a local declaration ID within a given module to a global declaration ID.
Definition: ASTReader.cpp:7645
Expr * ReadExpr(ModuleFile &F)
Reads an expression.
void ReadWeakUndeclaredIdentifiers(SmallVectorImpl< std::pair< IdentifierInfo *, WeakInfo > > &WeakIDs) override
Read the set of weak, undeclared identifiers known to the external Sema source.
Definition: ASTReader.cpp:8723
void completeVisibleDeclsMap(const DeclContext *DC) override
Load all external visible decls in the given DeclContext.
Definition: ASTReader.cpp:7997
void ReadUnusedLocalTypedefNameCandidates(llvm::SmallSetVector< const TypedefNameDecl *, 4 > &Decls) override
Read the set of potentially unused typedefs known to the source.
Definition: ASTReader.cpp:8683
IdentifierResolver & getIdResolver()
Get the identifier resolver used for name lookup / updates in the translation unit scope.
static bool readASTFileControlBlock(StringRef Filename, FileManager &FileMgr, const InMemoryModuleCache &ModuleCache, const PCHContainerReader &PCHContainerRdr, bool FindModuleFileExtensions, ASTReaderListener &Listener, bool ValidateDiagnosticOptions, unsigned ClientLoadCapabilities=ARR_ConfigurationMismatch|ARR_OutOfDate)
Read the control block for the named AST file.
Definition: ASTReader.cpp:5399
void ReadExtVectorDecls(SmallVectorImpl< TypedefNameDecl * > &Decls) override
Read the set of ext_vector type declarations known to the external Sema source.
Definition: ASTReader.cpp:8673
void ResolveImportedPath(ModuleFile &M, std::string &Filename)
If we are loading a relocatable PCH or module file, and the filename is not an absolute path,...
Definition: ASTReader.cpp:2687
static void SkipString(const RecordData &Record, unsigned &Idx)
Definition: ASTReader.h:2303
ModuleFile * getOwningModuleFile(const Decl *D)
Retrieve the module file that owns the given declaration, or NULL if the declaration is not from a mo...
Definition: ASTReader.cpp:7670
SmallVector< GlobalDeclID, 16 > PreloadedDeclIDs
Definition: ASTReader.h:2384
std::pair< SourceLocation, StringRef > getModuleImportLoc(int ID) override
Retrieve the module import location and module name for the given source manager entry ID.
Definition: ASTReader.cpp:1718
void ReadUnusedFileScopedDecls(SmallVectorImpl< const DeclaratorDecl * > &Decls) override
Read the set of unused file-scope declarations known to the external Sema source.
Definition: ASTReader.cpp:8651
void ReadReferencedSelectors(SmallVectorImpl< std::pair< Selector, SourceLocation > > &Sels) override
Read the set of referenced selectors known to the external Sema source.
Definition: ASTReader.cpp:8705
Selector DecodeSelector(serialization::SelectorID Idx)
Definition: ASTReader.cpp:9052
ASTReadResult ReadAST(StringRef FileName, ModuleKind Type, SourceLocation ImportLoc, unsigned ClientLoadCapabilities, ModuleFile **NewLoadedModuleFile=nullptr)
Load the AST file designated by the given file name.
Definition: ASTReader.cpp:4432
StringRef getOriginalSourceFile()
Retrieve the name of the original source file name for the primary module file.
Definition: ASTReader.h:1781
std::string ReadPath(ModuleFile &F, const RecordData &Record, unsigned &Idx)
Definition: ASTReader.cpp:9366
ASTDeserializationListener * getDeserializationListener()
Get the AST deserialization listener.
Definition: ASTReader.h:1731
void addListener(std::unique_ptr< ASTReaderListener > L)
Add an AST callback listener.
Definition: ASTReader.h:1694
unsigned getModuleFileID(ModuleFile *M)
Get an ID for the given module file.
Definition: ASTReader.cpp:9006
Decl * getKeyDeclaration(Decl *D)
Returns the first key declaration for the given declaration.
Definition: ASTReader.h:1332
void setListener(std::unique_ptr< ASTReaderListener > Listener)
Set the AST callbacks listener.
Definition: ASTReader.h:1687
Selector ReadSelector(ModuleFile &M, const RecordData &Record, unsigned &Idx)
Definition: ASTReader.h:2214
ModuleManager::ModuleReverseIterator ModuleReverseIterator
Definition: ASTReader.h:415
IdentifierInfo * DecodeIdentifierInfo(serialization::IdentifierID ID)
Definition: ASTReader.cpp:8868
ASTReadResult
The result of reading the control block of an AST file, which can fail for various reasons.
Definition: ASTReader.h:384
@ Success
The control block was read successfully.
Definition: ASTReader.h:387
@ ConfigurationMismatch
The AST file was written with a different language/target configuration.
Definition: ASTReader.h:404
@ OutOfDate
The AST file is out-of-date relative to its input files, and needs to be regenerated.
Definition: ASTReader.h:397
@ Failure
The AST file itself appears corrupted.
Definition: ASTReader.h:390
@ VersionMismatch
The AST file was written by a different version of Clang.
Definition: ASTReader.h:400
@ HadErrors
The AST file has errors.
Definition: ASTReader.h:407
@ Missing
The AST file was missing.
Definition: ASTReader.h:393
void addInMemoryBuffer(StringRef &FileName, std::unique_ptr< llvm::MemoryBuffer > Buffer)
Add in-memory (virtual file) buffer.
Definition: ASTReader.h:1760
static VersionTuple ReadVersionTuple(const RecordData &Record, unsigned &Idx)
Read a version tuple.
Definition: ASTReader.cpp:9381
Token ReadToken(ModuleFile &M, const RecordDataImpl &Record, unsigned &Idx)
Reads a token out of a record.
Definition: ASTReader.cpp:1782
SwitchCase * getSwitchCaseWithID(unsigned ID)
Retrieve the switch-case statement with the given ID.
Definition: ASTReader.cpp:9423
FileID TranslateFileID(ModuleFile &F, FileID FID) const
Translate a FileID from another module file's FileID space into ours.
Definition: ASTReader.h:2287
void ReadLateParsedTemplates(llvm::MapVector< const FunctionDecl *, std::unique_ptr< LateParsedTemplate > > &LPTMap) override
Read the set of late parsed template functions for this source.
Definition: ASTReader.cpp:8766
IdentifierIterator * getIdentifiers() override
Retrieve an iterator into the set of all identifiers in all loaded AST files.
Definition: ASTReader.cpp:8459
void ReadUsedVTables(SmallVectorImpl< ExternalVTableUse > &VTables) override
Read the set of used vtables known to the external Sema source.
Definition: ASTReader.cpp:8741
bool isGlobalIndexUnavailable() const
Determine whether we tried to load the global index, but failed, e.g., because it is out-of-date or d...
Definition: ASTReader.cpp:4366
uint32_t GetNumExternalSelectors() override
Returns the number of selectors known to the external AST source.
Definition: ASTReader.cpp:9081
void updateOutOfDateSelector(Selector Sel) override
Load the contents of the global method pool for a given selector if necessary.
Definition: ASTReader.cpp:8598
Decl * GetExistingDecl(GlobalDeclID ID)
Resolve a declaration ID into a declaration.
Definition: ASTReader.cpp:7757
T * ReadDeclAs(ModuleFile &F, const RecordData &R, unsigned &I)
Reads a declaration from the given position in a record in the given module.
Definition: ASTReader.h:1968
Stmt * ReadStmt(ModuleFile &F)
Reads a statement.
static llvm::BitVector ReadBitVector(const RecordData &Record, const StringRef Blob)
Definition: ASTReader.cpp:9341
ModuleFile * getLocalModuleFile(ModuleFile &M, unsigned ID) const
Retrieve the module file with a given local ID within the specified ModuleFile.
Definition: ASTReader.cpp:8993
void ForgetSema() override
Inform the semantic consumer that Sema is no longer available.
Definition: ASTReader.h:2055
DiagnosticsEngine & getDiags() const
Definition: ASTReader.h:1602
void LoadSelector(Selector Sel)
Load a selector from disk, registering its ID if it exists.
Definition: ASTReader.cpp:8807
IdentifierInfo * getLocalIdentifier(ModuleFile &M, unsigned LocalID)
Definition: ASTReader.cpp:8899
void ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag)
Definition: ASTReader.cpp:6532
void makeNamesVisible(const HiddenNames &Names, Module *Owner)
Make the names within this set of hidden names visible.
Definition: ASTReader.cpp:4263
void UpdateSema()
Update the state of Sema after loading some additional modules.
Definition: ASTReader.cpp:8229
Decl * GetDecl(GlobalDeclID ID)
Resolve a declaration ID into a declaration, potentially building a new declaration.
Definition: ASTReader.cpp:7782
Decl * GetLocalDecl(ModuleFile &F, LocalDeclID LocalID)
Reads a declaration with the given local ID in the given module.
Definition: ASTReader.h:1930
bool isProcessingUpdateRecords()
Definition: ASTReader.h:2434
T * GetLocalDeclAs(ModuleFile &F, LocalDeclID LocalID)
Reads a declaration with the given local ID in the given module.
Definition: ASTReader.h:1937
ASTReader(Preprocessor &PP, InMemoryModuleCache &ModuleCache, ASTContext *Context, const PCHContainerReader &PCHContainerRdr, ArrayRef< std::shared_ptr< ModuleFileExtension > > Extensions, StringRef isysroot="", DisableValidationForModuleKind DisableValidationKind=DisableValidationForModuleKind::None, bool AllowASTWithCompilerErrors=false, bool AllowConfigurationMismatch=false, bool ValidateSystemInputs=false, bool ValidateASTInputFilesContent=false, bool UseGlobalIndex=true, std::unique_ptr< llvm::Timer > ReadTimer={})
Load the AST file and validate its contents against the given Preprocessor.
int getSLocEntryID(SourceLocation::UIntTy SLocOffset) override
Get the index ID for the loaded SourceLocation offset.
Definition: ASTReader.cpp:1496
void ReadPendingInstantiations(SmallVectorImpl< std::pair< ValueDecl *, SourceLocation > > &Pending) override
Read the set of pending instantiations known to the external Sema source.
Definition: ASTReader.cpp:8754
Preprocessor & getPreprocessor() const
Retrieve the preprocessor.
Definition: ASTReader.h:1777
CXXTemporary * ReadCXXTemporary(ModuleFile &F, const RecordData &Record, unsigned &Idx)
Definition: ASTReader.cpp:9393
void ReadKnownNamespaces(SmallVectorImpl< NamespaceDecl * > &Namespaces) override
Load the set of namespaces that are known to the external source, which will be used during typo corr...
Definition: ASTReader.cpp:8603
const Decl * getKeyDeclaration(const Decl *D)
Definition: ASTReader.h:1342
ModuleManager::ModuleConstIterator ModuleConstIterator
Definition: ASTReader.h:414
QualType getLocalType(ModuleFile &F, unsigned LocalID)
Resolve a local type ID within a given AST file into a type.
Definition: ASTReader.cpp:7430
Decl * ReadDecl(ModuleFile &F, const RecordData &R, unsigned &I)
Reads a declaration from the given position in a record in the given module.
Definition: ASTReader.h:1958
Module * getSubmodule(serialization::SubmoduleID GlobalID)
Retrieve the submodule that corresponds to a global submodule ID.
Definition: ASTReader.cpp:8975
void PrintStats() override
Print some statistics about AST usage.
Definition: ASTReader.cpp:8057
void mergeDefinitionVisibility(NamedDecl *Def, NamedDecl *MergedDef)
Note that MergedDef is a redefinition of the canonical definition Def, so Def should be visible whene...
Definition: ASTReader.cpp:4326
serialization::SelectorID getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const
Retrieve the global selector ID that corresponds to this the local selector ID in a given module.
Definition: ASTReader.cpp:9087
SmallVector< uint64_t, 64 > RecordData
Definition: ASTReader.h:379
unsigned getTotalNumMacros() const
Returns the number of macros found in the chain.
Definition: ASTReader.h:1854
FileID ReadFileID(ModuleFile &F, const RecordDataImpl &Record, unsigned &Idx) const
Read a FileID.
Definition: ASTReader.h:2281
void StartedDeserializing() override
Notify ASTReader that we started deserialization of a decl or type so until FinishedDeserializing is ...
void ReadMethodPool(Selector Sel) override
Load the contents of the global method pool for a given selector.
Definition: ASTReader.cpp:8558
void InitializeContext()
Initializes the ASTContext.
Definition: ASTReader.cpp:5087
CXXBaseSpecifier * GetExternalCXXBaseSpecifiers(uint64_t Offset) override
Resolve the offset of a set of C++ base specifiers in the decl stream into an array of specifiers.
Definition: ASTReader.cpp:7603
std::unique_ptr< ASTReaderListener > takeListener()
Take the AST callbacks listener.
Definition: ASTReader.h:1682
void resetForReload()
Reset reader for a reload try.
Definition: ASTReader.h:1742
FileManager & getFileManager() const
Definition: ASTReader.h:1601
unsigned getTotalNumDecls() const
Returns the number of declarations found in the chain.
Definition: ASTReader.h:1864
serialization::TypeID getGlobalTypeID(ModuleFile &F, unsigned LocalID) const
Map a local type ID within a given AST file into a global type ID.
Definition: ASTReader.cpp:7435
static bool isAcceptableASTFile(StringRef Filename, FileManager &FileMgr, const InMemoryModuleCache &ModuleCache, const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts, const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts, StringRef ExistingModuleCachePath, bool RequireStrictOptionMatches=false)
Determine whether the given AST file is acceptable to load into a translation unit with the given lan...
Definition: ASTReader.cpp:5693
void FinishedDeserializing() override
Notify ASTReader that we finished the deserialization of a decl or type.
IdentifierInfo * readIdentifier(ModuleFile &M, const RecordData &Record, unsigned &Idx)
Definition: ASTReader.h:2140
void updateOutOfDateIdentifier(const IdentifierInfo &II) override
Update an out-of-date identifier.
Definition: ASTReader.cpp:2224
void ReadDefinedMacros() override
Read the set of macros defined by this external macro source.
Definition: ASTReader.cpp:2106
GlobalModuleIndex * getGlobalIndex()
Return global module index.
Definition: ASTReader.h:1739
IdentifierInfo * GetIdentifier(serialization::IdentifierID ID) override
Definition: ASTReader.h:2145
HeaderFileInfo GetHeaderFileInfo(FileEntryRef FE) override
Read the header file information for the given file entry.
Definition: ASTReader.cpp:6523
SourceLocation ReadSourceLocation(ModuleFile &ModuleFile, const RecordDataImpl &Record, unsigned &Idx, LocSeq *Seq=nullptr)
Read a source location.
Definition: ASTReader.h:2274
serialization::MacroID getGlobalMacroID(ModuleFile &M, unsigned LocalID)
Retrieve the global macro ID corresponding to the given local ID within the given module file.
Definition: ASTReader.cpp:8945
serialization::ModuleFile ModuleFile
Definition: ASTReader.h:410
bool hasGlobalIndex() const
Determine whether this AST reader has a global index.
Definition: ASTReader.h:1736
An object for streaming information from a record.
Utility class for loading a ASTContext from an AST file.
Definition: ASTUnit.h:89
Writes an AST file containing the contents of a translation unit.
Definition: ASTWriter.h:90
A simple helper class to unpack an integer to bits and consuming the bits in order.
Definition: ASTReader.h:2439
BitsUnpacker operator=(const BitsUnpacker &)=delete
uint32_t getNextBits(uint32_t Width)
Definition: ASTReader.h:2462
void advance(uint32_t BitsWidth)
Definition: ASTReader.h:2455
bool canGetNextNBits(uint32_t Width) const
Definition: ASTReader.h:2470
BitsUnpacker(BitsUnpacker &&)=delete
BitsUnpacker(const BitsUnpacker &)=delete
void updateValue(uint32_t V)
Definition: ASTReader.h:2450
BitsUnpacker operator=(BitsUnpacker &&)=delete
BitsUnpacker(uint32_t V)
Definition: ASTReader.h:2443
~BitsUnpacker()=default
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
Represents a C++ base or member initializer.
Definition: DeclCXX.h:2300
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
Represents a C++ temporary.
Definition: ExprCXX.h:1453
Simple wrapper class for chaining listeners.
Definition: ASTReader.h:249
bool visitInputFile(StringRef Filename, bool isSystem, bool isOverridden, bool isExplicitModule) override
if needsInputFileVisitation returns true, this is called for each non-system input file of the AST Fi...
Definition: ASTReader.cpp:244
std::unique_ptr< ASTReaderListener > takeSecond()
Definition: ASTReader.h:260
bool ReadFullVersionInformation(StringRef FullVersion) override
Receives the full Clang version information.
Definition: ASTReader.cpp:157
bool ReadFileSystemOptions(const FileSystemOptions &FSOpts, bool Complain) override
Receives the file system options.
Definition: ASTReader.cpp:198
std::unique_ptr< ASTReaderListener > takeFirst()
Definition: ASTReader.h:259
bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool ReadMacros, bool Complain, std::string &SuggestedPredefines) override
Receives the preprocessor options.
Definition: ASTReader.cpp:213
void ReadCounter(const serialization::ModuleFile &M, unsigned Value) override
Receives COUNTER value.
Definition: ASTReader.cpp:222
void ReadModuleMapFile(StringRef ModuleMapPath) override
Definition: ASTReader.cpp:167
bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath, bool Complain) override
Receives the header search options.
Definition: ASTReader.cpp:204
bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain, bool AllowCompatibleDifferences) override
Receives the target options.
Definition: ASTReader.cpp:182
void ReadModuleName(StringRef ModuleName) override
Definition: ASTReader.cpp:162
bool needsInputFileVisitation() override
Returns true if this ASTReaderListener wants to receive the input files of the AST file via visitInpu...
Definition: ASTReader.cpp:228
ChainedASTReaderListener(std::unique_ptr< ASTReaderListener > First, std::unique_ptr< ASTReaderListener > Second)
Takes ownership of First and Second.
Definition: ASTReader.h:255
bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain, bool AllowCompatibleDifferences) override
Receives the language options.
Definition: ASTReader.cpp:173
void readModuleFileExtension(const ModuleFileExtensionMetadata &Metadata) override
Indicates that a particular module file extension has been read.
Definition: ASTReader.cpp:260
bool ReadDiagnosticOptions(IntrusiveRefCntPtr< DiagnosticOptions > DiagOpts, bool Complain) override
Receives the diagnostic options.
Definition: ASTReader.cpp:191
void visitModuleFile(StringRef Filename, serialization::ModuleKind Kind) override
This is called for each AST file loaded.
Definition: ASTReader.cpp:238
bool needsSystemInputFileVisitation() override
Returns true if this ASTReaderListener wants to receive the system input files of the AST file via vi...
Definition: ASTReader.cpp:233
A map from continuous integer ranges to some value, with a very specialized interface.
typename Representation::const_iterator const_iterator
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1436
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:501
Kind
Lists the kind of concrete classes of Decl.
Definition: DeclBase.h:89
bool isFromExplicitGlobalModule() const
Whether this declaration comes from explicit global module.
Definition: DeclBase.cpp:1105
bool isFromASTFile() const
Determine whether this declaration came from an AST file (such as a precompiled header or module) rat...
Definition: DeclBase.h:776
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:968
The name of a declaration.
A little helper class used to produce diagnostics.
Definition: Diagnostic.h:1271
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:192
This represents one expression.
Definition: Expr.h:110
RAII class for safely pairing a StartedDeserializing call with FinishedDeserializing.
MemoryBufferSizes getMemoryBufferSizes() const
Return the amount of memory used by memory buffers, breaking down by heap-backed versus mmap'ed memor...
An external source of header file information, which may supply information about header files alread...
Definition: HeaderSearch.h:163
An abstract class that should be subclassed by any external source of preprocessing record entries.
Abstract interface for external sources of preprocessor information.
External source of source location entries.
An abstract interface that should be implemented by external AST sources that also provide informatio...
Represents a member of a struct/union/class.
Definition: Decl.h:3058
A reference to a FileEntry that includes the name of the file as it was accessed by the FileManager's...
Definition: FileEntry.h:57
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
Keeps track of options that affect how file operations are performed.
Represents a function declaration or definition.
Definition: Decl.h:1971
A global index for a set of module files, providing information about the identifiers within those mo...
HeaderSearchOptions - Helper class for storing options related to the initialization of the HeaderSea...
Provides lookups to, and iteration over, IdentiferInfo objects.
One of these records is kept for each identifier that is lexed.
An iterator that walks over all of the known identifiers in the lookup table.
IdentifierResolver - Keeps track of shadowed decls on enclosing scopes.
Implements an efficient mapping from strings to IdentifierInfo nodes.
In-memory cache for modules.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:461
Encapsulates the data about a macro definition (e.g.
Definition: MacroInfo.h:39
Describes a module or submodule.
Definition: Module.h:105
NameVisibilityKind
Describes the visibility of the various names within a particular module.
Definition: Module.h:387
This represents a decl that may have a name.
Definition: Decl.h:249
This abstract interface provides operations for unwrapping containers for serialized ASTs (precompile...
ASTReaderListener implementation to validate the information of the PCH file against an initialized P...
Definition: ASTReader.h:294
PCHValidator(Preprocessor &PP, ASTReader &Reader)
Definition: ASTReader.h:299
bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain, bool AllowCompatibleDifferences) override
Receives the target options.
Definition: ASTReader.cpp:459
void ReadCounter(const serialization::ModuleFile &M, unsigned Value) override
Receives COUNTER value.
Definition: ASTReader.cpp:866
bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool ReadMacros, bool Complain, std::string &SuggestedPredefines) override
Receives the preprocessor options.
Definition: ASTReader.cpp:814
bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath, bool Complain) override
Receives the header search options.
Definition: ASTReader.cpp:856
bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain, bool AllowCompatibleDifferences) override
Receives the language options.
Definition: ASTReader.cpp:450
bool ReadDiagnosticOptions(IntrusiveRefCntPtr< DiagnosticOptions > DiagOpts, bool Complain) override
Receives the diagnostic options.
Definition: ASTReader.cpp:579
Base class that describes a preprocessed entity, which may be a preprocessor directive or macro expan...
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:128
A (possibly-)qualified type.
Definition: Type.h:940
Smart pointer class that efficiently represents Objective-C method names.
static AlignPackInfo getFromRawEncoding(unsigned Encoding)
Definition: Sema.h:1243
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:449
ASTReaderListenter implementation to set SuggestedPredefines of ASTReader which is required to use a ...
Definition: ASTReader.h:321
bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool ReadMacros, bool Complain, std::string &SuggestedPredefines) override
Receives the preprocessor options.
Definition: ASTReader.cpp:824
SimpleASTReaderListener(Preprocessor &PP)
Definition: ASTReader.h:325
static std::pair< SourceLocation, unsigned > decode(RawLocEncoding, SourceLocationSequence *=nullptr)
Serialized encoding of a sequence of SourceLocations.
Encodes a location in the source.
This class handles loading and caching of source files into memory.
bool isLoadedSourceLocation(SourceLocation Loc) const
Returns true if Loc came from a PCH/Module.
A trivial tuple used to represent a source range.
Stmt - This represents one statement.
Definition: Stmt.h:84
Options for controlling the target.
Definition: TargetOptions.h:26
Token - This structure provides full information about a lexed token.
Definition: Token.h:36
The base class of the type hierarchy.
Definition: Type.h:1813
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:706
The input file that has been loaded from this AST file, along with bools indicating whether this was ...
Definition: ModuleFile.h:78
Information about a module that has been loaded by the ASTReader.
Definition: ModuleFile.h:124
int SLocEntryBaseID
The base ID in the source manager's view of this module.
Definition: ModuleFile.h:285
llvm::SmallVector< ModuleFile *, 16 > DependentModules
List of modules which this modules dependent on.
Definition: ModuleFile.h:520
std::string OriginalSourceFileName
The original source file name that was used to build the primary AST file, which may have been modifi...
Definition: ModuleFile.h:154
StringRef ModuleOffsetMap
The module offset map data for this file.
Definition: ModuleFile.h:244
SourceLocation::UIntTy SLocEntryBaseOffset
The base offset in the source manager's view of this module.
Definition: ModuleFile.h:288
Manages the set of modules loaded by an AST reader.
Definition: ModuleManager.h:47
ModuleFile & getPrimaryModule()
Returns the primary module associated with the manager, that is, the first module loaded.
llvm::pointee_iterator< SmallVectorImpl< std::unique_ptr< ModuleFile > >::const_iterator > ModuleConstIterator
void addInMemoryBuffer(StringRef FileName, std::unique_ptr< llvm::MemoryBuffer > Buffer)
Add an in-memory buffer the list of known buffers.
llvm::pointee_iterator< SmallVectorImpl< std::unique_ptr< ModuleFile > >::reverse_iterator > ModuleReverseIterator
llvm::pointee_iterator< SmallVectorImpl< std::unique_ptr< ModuleFile > >::iterator > ModuleIterator
Class that performs lookup for an identifier stored in an AST file.
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
uint32_t TypeID
An ID number that refers to a type in an AST file.
Definition: ASTBitCodes.h:81
uint32_t SubmoduleID
An ID number that refers to a submodule in a module file.
Definition: ASTBitCodes.h:161
uint32_t SelectorID
An ID number that refers to an ObjC selector in an AST file.
Definition: ASTBitCodes.h:143
uint32_t PreprocessedEntityID
An ID number that refers to an entity in the detailed preprocessing record.
Definition: ASTBitCodes.h:158
DeclIDBase::DeclID DeclID
An ID number that refers to a declaration in an AST file.
Definition: ASTBitCodes.h:69
ModuleKind
Specifies the kind of module that has been loaded.
Definition: ModuleFile.h:42
uint32_t MacroID
An ID number that refers to a macro in an AST file.
Definition: ASTBitCodes.h:130
uint32_t IdentifierID
An ID number that refers to an identifier in an AST file.
Definition: ASTBitCodes.h:62
The JSON file list parser is used to communicate input to InstallAPI.
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
@ Module
Module linkage, which indicates that the entity can be referred to from other translation units withi...
@ Result
The result type of a method or function.
const FunctionProtoType * T
DisableValidationForModuleKind
Whether to disable the normal validation performed on precompiled headers and module files when they ...
@ None
Perform validation, don't disable it.
bool shouldSkipCheckingODR(const Decl *D)
Definition: ASTReader.h:2481
std::string getClangFullRepositoryVersion()
Retrieves the full repository version that is an amalgamation of the information in getClangRepositor...
Definition: Version.cpp:68
unsigned long uint64_t
Definition: Format.h:5428
The preprocessor keeps track of this information for each file that is #included.
Definition: HeaderSearch.h:58
Metadata for a module file extension.
The input file info that has been loaded from an AST file.
Definition: ModuleFile.h:63