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