1 //===--- ASTReader.h - AST File Reader --------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the ASTReader class, which reads AST files.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_SERIALIZATION_ASTREADER_H
15 #define LLVM_CLANG_SERIALIZATION_ASTREADER_H
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/DeclarationName.h"
19 #include "clang/AST/TemplateBase.h"
20 #include "clang/Basic/Diagnostic.h"
21 #include "clang/Basic/FileManager.h"
22 #include "clang/Basic/FileSystemOptions.h"
23 #include "clang/Basic/IdentifierTable.h"
24 #include "clang/Basic/SourceManager.h"
25 #include "clang/Basic/Version.h"
26 #include "clang/Lex/ExternalPreprocessorSource.h"
27 #include "clang/Lex/HeaderSearch.h"
28 #include "clang/Lex/PreprocessingRecord.h"
29 #include "clang/Sema/ExternalSemaSource.h"
30 #include "clang/Serialization/ASTBitCodes.h"
31 #include "clang/Serialization/ContinuousRangeMap.h"
32 #include "clang/Serialization/Module.h"
33 #include "clang/Serialization/ModuleManager.h"
34 #include "llvm/ADT/APFloat.h"
35 #include "llvm/ADT/APInt.h"
36 #include "llvm/ADT/APSInt.h"
37 #include "llvm/ADT/MapVector.h"
38 #include "llvm/ADT/SmallPtrSet.h"
39 #include "llvm/ADT/SmallSet.h"
40 #include "llvm/ADT/SmallVector.h"
41 #include "llvm/ADT/StringRef.h"
42 #include "llvm/ADT/TinyPtrVector.h"
43 #include "llvm/Bitcode/BitstreamReader.h"
44 #include "llvm/Support/DataTypes.h"
61 class ASTIdentifierIterator;
62 class ASTUnit; // FIXME: Layering violation and egregious hack.
66 class DefMacroDirective;
67 class DiagnosticOptions;
68 class NestedNameSpecifier;
69 class CXXBaseSpecifier;
70 class CXXConstructorDecl;
71 class CXXCtorInitializer;
72 class GlobalModuleIndex;
74 class MacroDefinition;
78 class OpaqueValueExpr;
80 class PreprocessorOptions;
83 class ASTDeserializationListener;
89 struct HeaderFileInfo;
92 class LazyASTUnresolvedSet;
94 /// \brief Abstract interface for callback invocations by the ASTReader.
96 /// While reading an AST file, the ASTReader will call the methods of the
97 /// listener to pass on specific information. Some of the listener methods can
98 /// return true to indicate to the ASTReader that the information (and
99 /// consequently the AST file) is invalid.
100 class ASTReaderListener {
102 virtual ~ASTReaderListener();
104 /// \brief Receives the full Clang version information.
106 /// \returns true to indicate that the version is invalid. Subclasses should
107 /// generally defer to this implementation.
108 virtual bool ReadFullVersionInformation(StringRef FullVersion) {
109 return FullVersion != getClangFullRepositoryVersion();
112 virtual void ReadModuleName(StringRef ModuleName) {}
113 virtual void ReadModuleMapFile(StringRef ModuleMapPath) {}
115 /// \brief Receives the language options.
117 /// \returns true to indicate the options are invalid or false otherwise.
118 virtual bool ReadLanguageOptions(const LangOptions &LangOpts,
120 bool AllowCompatibleDifferences) {
124 /// \brief Receives the target options.
126 /// \returns true to indicate the target options are invalid, or false
128 virtual bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
129 bool AllowCompatibleDifferences) {
133 /// \brief Receives the diagnostic options.
135 /// \returns true to indicate the diagnostic options are invalid, or false
138 ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
143 /// \brief Receives the file system options.
145 /// \returns true to indicate the file system options are invalid, or false
147 virtual bool ReadFileSystemOptions(const FileSystemOptions &FSOpts,
152 /// \brief Receives the header search options.
154 /// \returns true to indicate the header search options are invalid, or false
156 virtual bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
157 StringRef SpecificModuleCachePath,
162 /// \brief Receives the preprocessor options.
164 /// \param SuggestedPredefines Can be filled in with the set of predefines
165 /// that are suggested by the preprocessor options. Typically only used when
166 /// loading a precompiled header.
168 /// \returns true to indicate the preprocessor options are invalid, or false
170 virtual bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
172 std::string &SuggestedPredefines) {
176 /// \brief Receives __COUNTER__ value.
177 virtual void ReadCounter(const serialization::ModuleFile &M,
180 /// This is called for each AST file loaded.
181 virtual void visitModuleFile(StringRef Filename) {}
183 /// \brief Returns true if this \c ASTReaderListener wants to receive the
184 /// input files of the AST file via \c visitInputFile, false otherwise.
185 virtual bool needsInputFileVisitation() { return false; }
186 /// \brief Returns true if this \c ASTReaderListener wants to receive the
187 /// system input files of the AST file via \c visitInputFile, false otherwise.
188 virtual bool needsSystemInputFileVisitation() { return false; }
189 /// \brief if \c needsInputFileVisitation returns true, this is called for
190 /// each non-system input file of the AST File. If
191 /// \c needsSystemInputFileVisitation is true, then it is called for all
192 /// system input files as well.
194 /// \returns true to continue receiving the next input file, false to stop.
195 virtual bool visitInputFile(StringRef Filename, bool isSystem,
200 /// \brief Returns true if this \c ASTReaderListener wants to receive the
201 /// imports of the AST file via \c visitImport, false otherwise.
202 virtual bool needsImportVisitation() const { return false; }
203 /// \brief If needsImportVisitation returns \c true, this is called for each
204 /// AST file imported by this AST file.
205 virtual void visitImport(StringRef Filename) {}
208 /// \brief Simple wrapper class for chaining listeners.
209 class ChainedASTReaderListener : public ASTReaderListener {
210 std::unique_ptr<ASTReaderListener> First;
211 std::unique_ptr<ASTReaderListener> Second;
214 /// Takes ownership of \p First and \p Second.
215 ChainedASTReaderListener(std::unique_ptr<ASTReaderListener> First,
216 std::unique_ptr<ASTReaderListener> Second)
217 : First(std::move(First)), Second(std::move(Second)) {}
219 std::unique_ptr<ASTReaderListener> takeFirst() { return std::move(First); }
220 std::unique_ptr<ASTReaderListener> takeSecond() { return std::move(Second); }
222 bool ReadFullVersionInformation(StringRef FullVersion) override;
223 void ReadModuleName(StringRef ModuleName) override;
224 void ReadModuleMapFile(StringRef ModuleMapPath) override;
225 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
226 bool AllowCompatibleDifferences) override;
227 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
228 bool AllowCompatibleDifferences) override;
229 bool ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
230 bool Complain) override;
231 bool ReadFileSystemOptions(const FileSystemOptions &FSOpts,
232 bool Complain) override;
234 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
235 StringRef SpecificModuleCachePath,
236 bool Complain) override;
237 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
239 std::string &SuggestedPredefines) override;
241 void ReadCounter(const serialization::ModuleFile &M, unsigned Value) override;
242 bool needsInputFileVisitation() override;
243 bool needsSystemInputFileVisitation() override;
244 void visitModuleFile(StringRef Filename) override;
245 bool visitInputFile(StringRef Filename, bool isSystem,
246 bool isOverridden) override;
249 /// \brief ASTReaderListener implementation to validate the information of
250 /// the PCH file against an initialized Preprocessor.
251 class PCHValidator : public ASTReaderListener {
256 PCHValidator(Preprocessor &PP, ASTReader &Reader)
257 : PP(PP), Reader(Reader) {}
259 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
260 bool AllowCompatibleDifferences) override;
261 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
262 bool AllowCompatibleDifferences) override;
263 bool ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
264 bool Complain) override;
265 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool Complain,
266 std::string &SuggestedPredefines) override;
267 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
268 StringRef SpecificModuleCachePath,
269 bool Complain) override;
270 void ReadCounter(const serialization::ModuleFile &M, unsigned Value) override;
273 void Error(const char *Msg);
276 namespace serialization {
278 class ReadMethodPoolVisitor;
281 class ASTIdentifierLookupTrait;
282 /// \brief The on-disk hash table used for the DeclContext's Name lookup table.
283 typedef llvm::OnDiskIterableChainedHashTable<ASTDeclContextNameLookupTrait>
284 ASTDeclContextNameLookupTable;
287 } // end namespace serialization
289 /// \brief Reads an AST files chain containing the contents of a translation
292 /// The ASTReader class reads bitstreams (produced by the ASTWriter
293 /// class) containing the serialized representation of a given
294 /// abstract syntax tree and its supporting data structures. An
295 /// instance of the ASTReader can be attached to an ASTContext object,
296 /// which will provide access to the contents of the AST files.
298 /// The AST reader provides lazy de-serialization of declarations, as
299 /// required when traversing the AST. Only those AST nodes that are
300 /// actually required will be de-serialized.
302 : public ExternalPreprocessorSource,
303 public ExternalPreprocessingRecordSource,
304 public ExternalHeaderFileInfoSource,
305 public ExternalSemaSource,
306 public IdentifierInfoLookup,
307 public ExternalIdentifierLookup,
308 public ExternalSLocEntrySource
311 typedef SmallVector<uint64_t, 64> RecordData;
312 typedef SmallVectorImpl<uint64_t> RecordDataImpl;
314 /// \brief The result of reading the control block of an AST file, which
315 /// can fail for various reasons.
317 /// \brief The control block was read successfully. Aside from failures,
318 /// the AST file is safe to read into the current context.
320 /// \brief The AST file itself appears corrupted.
322 /// \brief The AST file was missing.
324 /// \brief The AST file is out-of-date relative to its input files,
325 /// and needs to be regenerated.
327 /// \brief The AST file was written by a different version of Clang.
329 /// \brief The AST file was writtten with a different language/target
331 ConfigurationMismatch,
332 /// \brief The AST file has errors.
336 /// \brief Types of AST files.
337 friend class PCHValidator;
338 friend class ASTDeclReader;
339 friend class ASTStmtReader;
340 friend class ASTIdentifierIterator;
341 friend class serialization::reader::ASTIdentifierLookupTrait;
342 friend class TypeLocReader;
343 friend class ASTWriter;
344 friend class ASTUnit; // ASTUnit needs to remap source locations.
345 friend class serialization::ReadMethodPoolVisitor;
347 typedef serialization::ModuleFile ModuleFile;
348 typedef serialization::ModuleKind ModuleKind;
349 typedef serialization::ModuleManager ModuleManager;
351 typedef ModuleManager::ModuleIterator ModuleIterator;
352 typedef ModuleManager::ModuleConstIterator ModuleConstIterator;
353 typedef ModuleManager::ModuleReverseIterator ModuleReverseIterator;
356 /// \brief The receiver of some callbacks invoked by ASTReader.
357 std::unique_ptr<ASTReaderListener> Listener;
359 /// \brief The receiver of deserialization events.
360 ASTDeserializationListener *DeserializationListener;
361 bool OwnsDeserializationListener;
363 SourceManager &SourceMgr;
364 FileManager &FileMgr;
365 DiagnosticsEngine &Diags;
367 /// \brief The semantic analysis object that will be processing the
368 /// AST files and the translation unit that uses it.
371 /// \brief The preprocessor that will be loading the source file.
374 /// \brief The AST context into which we'll read the AST files.
377 /// \brief The AST consumer.
378 ASTConsumer *Consumer;
380 /// \brief The module manager which manages modules and their dependencies
381 ModuleManager ModuleMgr;
383 /// \brief The location where the module file will be considered as
384 /// imported from. For non-module AST types it should be invalid.
385 SourceLocation CurrentImportLoc;
387 /// \brief The global module index, if loaded.
388 std::unique_ptr<GlobalModuleIndex> GlobalIndex;
390 /// \brief A map of global bit offsets to the module that stores entities
391 /// at those bit offsets.
392 ContinuousRangeMap<uint64_t, ModuleFile*, 4> GlobalBitOffsetsMap;
394 /// \brief A map of negated SLocEntryIDs to the modules containing them.
395 ContinuousRangeMap<unsigned, ModuleFile*, 64> GlobalSLocEntryMap;
397 typedef ContinuousRangeMap<unsigned, ModuleFile*, 64> GlobalSLocOffsetMapType;
399 /// \brief A map of reversed (SourceManager::MaxLoadedOffset - SLocOffset)
400 /// SourceLocation offsets to the modules containing them.
401 GlobalSLocOffsetMapType GlobalSLocOffsetMap;
403 /// \brief Types that have already been loaded from the chain.
405 /// When the pointer at index I is non-NULL, the type with
406 /// ID = (I + 1) << FastQual::Width has already been loaded
407 std::vector<QualType> TypesLoaded;
409 typedef ContinuousRangeMap<serialization::TypeID, ModuleFile *, 4>
412 /// \brief Mapping from global type IDs to the module in which the
413 /// type resides along with the offset that should be added to the
414 /// global type ID to produce a local ID.
415 GlobalTypeMapType GlobalTypeMap;
417 /// \brief Declarations that have already been loaded from the chain.
419 /// When the pointer at index I is non-NULL, the declaration with ID
420 /// = I + 1 has already been loaded.
421 std::vector<Decl *> DeclsLoaded;
423 typedef ContinuousRangeMap<serialization::DeclID, ModuleFile *, 4>
426 /// \brief Mapping from global declaration IDs to the module in which the
427 /// declaration resides.
428 GlobalDeclMapType GlobalDeclMap;
430 typedef std::pair<ModuleFile *, uint64_t> FileOffset;
431 typedef SmallVector<FileOffset, 2> FileOffsetsTy;
432 typedef llvm::DenseMap<serialization::DeclID, FileOffsetsTy>
433 DeclUpdateOffsetsMap;
435 /// \brief Declarations that have modifications residing in a later file
437 DeclUpdateOffsetsMap DeclUpdateOffsets;
439 /// \brief Declaration updates for already-loaded declarations that we need
440 /// to apply once we finish processing an import.
441 llvm::SmallVector<std::pair<serialization::GlobalDeclID, Decl*>, 16>
442 PendingUpdateRecords;
444 enum class PendingFakeDefinitionKind { NotFake, Fake, FakeLoaded };
446 /// \brief The DefinitionData pointers that we faked up for class definitions
447 /// that we needed but hadn't loaded yet.
448 llvm::DenseMap<void *, PendingFakeDefinitionKind> PendingFakeDefinitionData;
450 /// \brief Exception specification updates that have been loaded but not yet
451 /// propagated across the relevant redeclaration chain. The map key is the
452 /// canonical declaration (used only for deduplication) and the value is a
453 /// declaration that has an exception specification.
454 llvm::SmallMapVector<Decl *, FunctionDecl *, 4> PendingExceptionSpecUpdates;
456 struct ReplacedDeclInfo {
461 ReplacedDeclInfo() : Mod(nullptr), Offset(0), RawLoc(0) {}
462 ReplacedDeclInfo(ModuleFile *Mod, uint64_t Offset, unsigned RawLoc)
463 : Mod(Mod), Offset(Offset), RawLoc(RawLoc) {}
466 typedef llvm::DenseMap<serialization::DeclID, ReplacedDeclInfo>
468 /// \brief Declarations that have been replaced in a later file in the chain.
469 DeclReplacementMap ReplacedDecls;
471 /// \brief Declarations that have been imported and have typedef names for
472 /// linkage purposes.
473 llvm::DenseMap<std::pair<DeclContext*, IdentifierInfo*>, NamedDecl*>
474 ImportedTypedefNamesForLinkage;
476 /// \brief Mergeable declaration contexts that have anonymous declarations
477 /// within them, and those anonymous declarations.
478 llvm::DenseMap<DeclContext*, llvm::SmallVector<NamedDecl*, 2>>
479 AnonymousDeclarationsForMerging;
481 struct FileDeclsInfo {
483 ArrayRef<serialization::LocalDeclID> Decls;
485 FileDeclsInfo() : Mod(nullptr) {}
486 FileDeclsInfo(ModuleFile *Mod, ArrayRef<serialization::LocalDeclID> Decls)
487 : Mod(Mod), Decls(Decls) {}
490 /// \brief Map from a FileID to the file-level declarations that it contains.
491 llvm::DenseMap<FileID, FileDeclsInfo> FileDeclIDs;
493 // Updates for visible decls can occur for other contexts than just the
494 // TU, and when we read those update records, the actual context will not
495 // be available yet (unless it's the TU), so have this pending map using the
496 // ID as a key. It will be realized when the context is actually loaded.
498 SmallVector<std::pair<serialization::reader::ASTDeclContextNameLookupTable *,
499 ModuleFile*>, 1> DeclContextVisibleUpdates;
500 typedef llvm::DenseMap<serialization::DeclID, DeclContextVisibleUpdates>
501 DeclContextVisibleUpdatesPending;
503 /// \brief Updates to the visible declarations of declaration contexts that
504 /// haven't been loaded yet.
505 DeclContextVisibleUpdatesPending PendingVisibleUpdates;
507 /// \brief The set of C++ or Objective-C classes that have forward
508 /// declarations that have not yet been linked to their definitions.
509 llvm::SmallPtrSet<Decl *, 4> PendingDefinitions;
511 typedef llvm::MapVector<Decl *, uint64_t,
512 llvm::SmallDenseMap<Decl *, unsigned, 4>,
513 SmallVector<std::pair<Decl *, uint64_t>, 4> >
516 /// \brief Functions or methods that have bodies that will be attached.
517 PendingBodiesMap PendingBodies;
519 /// \brief Definitions for which we have added merged definitions but not yet
520 /// performed deduplication.
521 llvm::SetVector<NamedDecl*> PendingMergedDefinitionsToDeduplicate;
523 /// \brief Read the records that describe the contents of declcontexts.
524 bool ReadDeclContextStorage(ModuleFile &M,
525 llvm::BitstreamCursor &Cursor,
526 const std::pair<uint64_t, uint64_t> &Offsets,
527 serialization::DeclContextInfo &Info);
529 /// \brief A vector containing identifiers that have already been
532 /// If the pointer at index I is non-NULL, then it refers to the
533 /// IdentifierInfo for the identifier with ID=I+1 that has already
535 std::vector<IdentifierInfo *> IdentifiersLoaded;
537 typedef ContinuousRangeMap<serialization::IdentID, ModuleFile *, 4>
538 GlobalIdentifierMapType;
540 /// \brief Mapping from global identifier IDs to the module in which the
541 /// identifier resides along with the offset that should be added to the
542 /// global identifier ID to produce a local ID.
543 GlobalIdentifierMapType GlobalIdentifierMap;
545 /// \brief A vector containing macros that have already been
548 /// If the pointer at index I is non-NULL, then it refers to the
549 /// MacroInfo for the identifier with ID=I+1 that has already
551 std::vector<MacroInfo *> MacrosLoaded;
553 typedef std::pair<IdentifierInfo *, serialization::SubmoduleID>
556 /// \brief A set of #undef directives that we have loaded; used to
557 /// deduplicate the same #undef information coming from multiple module
559 llvm::DenseSet<LoadedMacroInfo> LoadedUndefs;
561 typedef ContinuousRangeMap<serialization::MacroID, ModuleFile *, 4>
564 /// \brief Mapping from global macro IDs to the module in which the
565 /// macro resides along with the offset that should be added to the
566 /// global macro ID to produce a local ID.
567 GlobalMacroMapType GlobalMacroMap;
569 /// \brief A vector containing submodules that have already been loaded.
571 /// This vector is indexed by the Submodule ID (-1). NULL submodule entries
572 /// indicate that the particular submodule ID has not yet been loaded.
573 SmallVector<Module *, 2> SubmodulesLoaded;
575 typedef ContinuousRangeMap<serialization::SubmoduleID, ModuleFile *, 4>
576 GlobalSubmoduleMapType;
578 /// \brief Mapping from global submodule IDs to the module file in which the
579 /// submodule resides along with the offset that should be added to the
580 /// global submodule ID to produce a local ID.
581 GlobalSubmoduleMapType GlobalSubmoduleMap;
583 /// \brief A set of hidden declarations.
584 typedef SmallVector<Decl*, 2> HiddenNames;
585 typedef llvm::DenseMap<Module *, HiddenNames> HiddenNamesMapType;
587 /// \brief A mapping from each of the hidden submodules to the deserialized
588 /// declarations in that submodule that could be made visible.
589 HiddenNamesMapType HiddenNamesMap;
592 /// \brief A module import, export, or conflict that hasn't yet been resolved.
593 struct UnresolvedModuleRef {
594 /// \brief The file in which this module resides.
597 /// \brief The module that is importing or exporting.
600 /// \brief The kind of module reference.
601 enum { Import, Export, Conflict } Kind;
603 /// \brief The local ID of the module that is being exported.
606 /// \brief Whether this is a wildcard export.
607 unsigned IsWildcard : 1;
609 /// \brief String data.
613 /// \brief The set of module imports and exports that still need to be
615 SmallVector<UnresolvedModuleRef, 2> UnresolvedModuleRefs;
617 /// \brief A vector containing selectors that have already been loaded.
619 /// This vector is indexed by the Selector ID (-1). NULL selector
620 /// entries indicate that the particular selector ID has not yet
622 SmallVector<Selector, 16> SelectorsLoaded;
624 typedef ContinuousRangeMap<serialization::SelectorID, ModuleFile *, 4>
625 GlobalSelectorMapType;
627 /// \brief Mapping from global selector IDs to the module in which the
629 /// global selector ID to produce a local ID.
630 GlobalSelectorMapType GlobalSelectorMap;
632 /// \brief The generation number of the last time we loaded data from the
633 /// global method pool for this selector.
634 llvm::DenseMap<Selector, unsigned> SelectorGeneration;
636 struct PendingMacroInfo {
638 uint64_t MacroDirectivesOffset;
640 PendingMacroInfo(ModuleFile *M, uint64_t MacroDirectivesOffset)
641 : M(M), MacroDirectivesOffset(MacroDirectivesOffset) {}
644 typedef llvm::MapVector<IdentifierInfo *, SmallVector<PendingMacroInfo, 2> >
647 /// \brief Mapping from identifiers that have a macro history to the global
648 /// IDs have not yet been deserialized to the global IDs of those macros.
649 PendingMacroIDsMap PendingMacroIDs;
651 typedef ContinuousRangeMap<unsigned, ModuleFile *, 4>
652 GlobalPreprocessedEntityMapType;
654 /// \brief Mapping from global preprocessing entity IDs to the module in
655 /// which the preprocessed entity resides along with the offset that should be
656 /// added to the global preprocessing entitiy ID to produce a local ID.
657 GlobalPreprocessedEntityMapType GlobalPreprocessedEntityMap;
659 /// \name CodeGen-relevant special data
660 /// \brief Fields containing data that is relevant to CodeGen.
663 /// \brief The IDs of all declarations that fulfill the criteria of
664 /// "interesting" decls.
666 /// This contains the data loaded from all EAGERLY_DESERIALIZED_DECLS blocks
667 /// in the chain. The referenced declarations are deserialized and passed to
668 /// the consumer eagerly.
669 SmallVector<uint64_t, 16> EagerlyDeserializedDecls;
671 /// \brief The IDs of all tentative definitions stored in the chain.
673 /// Sema keeps track of all tentative definitions in a TU because it has to
674 /// complete them and pass them on to CodeGen. Thus, tentative definitions in
675 /// the PCH chain must be eagerly deserialized.
676 SmallVector<uint64_t, 16> TentativeDefinitions;
678 /// \brief The IDs of all CXXRecordDecls stored in the chain whose VTables are
681 /// CodeGen has to emit VTables for these records, so they have to be eagerly
683 SmallVector<uint64_t, 64> VTableUses;
685 /// \brief A snapshot of the pending instantiations in the chain.
687 /// This record tracks the instantiations that Sema has to perform at the
688 /// end of the TU. It consists of a pair of values for every pending
689 /// instantiation where the first value is the ID of the decl and the second
690 /// is the instantiation location.
691 SmallVector<uint64_t, 64> PendingInstantiations;
695 /// \name DiagnosticsEngine-relevant special data
696 /// \brief Fields containing data that is used for generating diagnostics
699 /// \brief A snapshot of Sema's unused file-scoped variable tracking, for
700 /// generating warnings.
701 SmallVector<uint64_t, 16> UnusedFileScopedDecls;
703 /// \brief A list of all the delegating constructors we've seen, to diagnose
705 SmallVector<uint64_t, 4> DelegatingCtorDecls;
707 /// \brief Method selectors used in a @selector expression. Used for
708 /// implementation of -Wselector.
709 SmallVector<uint64_t, 64> ReferencedSelectorsData;
711 /// \brief A snapshot of Sema's weak undeclared identifier tracking, for
712 /// generating warnings.
713 SmallVector<uint64_t, 64> WeakUndeclaredIdentifiers;
715 /// \brief The IDs of type aliases for ext_vectors that exist in the chain.
717 /// Used by Sema for finding sugared names for ext_vectors in diagnostics.
718 SmallVector<uint64_t, 4> ExtVectorDecls;
722 /// \name Sema-relevant special data
723 /// \brief Fields containing data that is used for semantic analysis
726 /// \brief The IDs of all potentially unused typedef names in the chain.
728 /// Sema tracks these to emit warnings.
729 SmallVector<uint64_t, 16> UnusedLocalTypedefNameCandidates;
731 /// \brief The IDs of the declarations Sema stores directly.
733 /// Sema tracks a few important decls, such as namespace std, directly.
734 SmallVector<uint64_t, 4> SemaDeclRefs;
736 /// \brief The IDs of the types ASTContext stores directly.
738 /// The AST context tracks a few important types, such as va_list, directly.
739 SmallVector<uint64_t, 16> SpecialTypes;
741 /// \brief The IDs of CUDA-specific declarations ASTContext stores directly.
743 /// The AST context tracks a few important decls, currently cudaConfigureCall,
745 SmallVector<uint64_t, 2> CUDASpecialDeclRefs;
747 /// \brief The floating point pragma option settings.
748 SmallVector<uint64_t, 1> FPPragmaOptions;
750 /// \brief The pragma clang optimize location (if the pragma state is "off").
751 SourceLocation OptimizeOffPragmaLocation;
753 /// \brief The OpenCL extension settings.
754 SmallVector<uint64_t, 1> OpenCLExtensions;
756 /// \brief A list of the namespaces we've seen.
757 SmallVector<uint64_t, 4> KnownNamespaces;
759 /// \brief A list of undefined decls with internal linkage followed by the
760 /// SourceLocation of a matching ODR-use.
761 SmallVector<uint64_t, 8> UndefinedButUsed;
763 /// \brief Delete expressions to analyze at the end of translation unit.
764 SmallVector<uint64_t, 8> DelayedDeleteExprs;
766 // \brief A list of late parsed template function data.
767 SmallVector<uint64_t, 1> LateParsedTemplates;
769 struct ImportedSubmodule {
770 serialization::SubmoduleID ID;
771 SourceLocation ImportLoc;
773 ImportedSubmodule(serialization::SubmoduleID ID, SourceLocation ImportLoc)
774 : ID(ID), ImportLoc(ImportLoc) {}
777 /// \brief A list of modules that were imported by precompiled headers or
778 /// any other non-module AST file.
779 SmallVector<ImportedSubmodule, 2> ImportedModules;
782 /// \brief The directory that the PCH we are reading is stored in.
783 std::string CurrentDir;
785 /// \brief The system include root to be used when loading the
786 /// precompiled header.
787 std::string isysroot;
789 /// \brief Whether to disable the normal validation performed on precompiled
790 /// headers when they are loaded.
791 bool DisableValidation;
793 /// \brief Whether to accept an AST file with compiler errors.
794 bool AllowASTWithCompilerErrors;
796 /// \brief Whether to accept an AST file that has a different configuration
797 /// from the current compiler instance.
798 bool AllowConfigurationMismatch;
800 /// \brief Whether validate system input files.
801 bool ValidateSystemInputs;
803 /// \brief Whether we are allowed to use the global module index.
806 /// \brief Whether we have tried loading the global module index yet.
807 bool TriedLoadingGlobalIndex;
809 typedef llvm::DenseMap<unsigned, SwitchCase *> SwitchCaseMapTy;
810 /// \brief Mapping from switch-case IDs in the chain to switch-case statements
812 /// Statements usually don't have IDs, but switch cases need them, so that the
813 /// switch statement can refer to them.
814 SwitchCaseMapTy SwitchCaseStmts;
816 SwitchCaseMapTy *CurrSwitchCaseStmts;
818 /// \brief The number of source location entries de-serialized from
820 unsigned NumSLocEntriesRead;
822 /// \brief The number of source location entries in the chain.
823 unsigned TotalNumSLocEntries;
825 /// \brief The number of statements (and expressions) de-serialized
827 unsigned NumStatementsRead;
829 /// \brief The total number of statements (and expressions) stored
831 unsigned TotalNumStatements;
833 /// \brief The number of macros de-serialized from the chain.
834 unsigned NumMacrosRead;
836 /// \brief The total number of macros stored in the chain.
837 unsigned TotalNumMacros;
839 /// \brief The number of lookups into identifier tables.
840 unsigned NumIdentifierLookups;
842 /// \brief The number of lookups into identifier tables that succeed.
843 unsigned NumIdentifierLookupHits;
845 /// \brief The number of selectors that have been read.
846 unsigned NumSelectorsRead;
848 /// \brief The number of method pool entries that have been read.
849 unsigned NumMethodPoolEntriesRead;
851 /// \brief The number of times we have looked up a selector in the method
853 unsigned NumMethodPoolLookups;
855 /// \brief The number of times we have looked up a selector in the method
856 /// pool and found something.
857 unsigned NumMethodPoolHits;
859 /// \brief The number of times we have looked up a selector in the method
860 /// pool within a specific module.
861 unsigned NumMethodPoolTableLookups;
863 /// \brief The number of times we have looked up a selector in the method
864 /// pool within a specific module and found something.
865 unsigned NumMethodPoolTableHits;
867 /// \brief The total number of method pool entries in the selector table.
868 unsigned TotalNumMethodPoolEntries;
870 /// Number of lexical decl contexts read/total.
871 unsigned NumLexicalDeclContextsRead, TotalLexicalDeclContexts;
873 /// Number of visible decl contexts read/total.
874 unsigned NumVisibleDeclContextsRead, TotalVisibleDeclContexts;
876 /// Total size of modules, in bits, currently loaded
877 uint64_t TotalModulesSizeInBits;
879 /// \brief Number of Decl/types that are currently deserializing.
880 unsigned NumCurrentElementsDeserializing;
882 /// \brief Set true while we are in the process of passing deserialized
883 /// "interesting" decls to consumer inside FinishedDeserializing().
884 /// This is used as a guard to avoid recursively repeating the process of
885 /// passing decls to consumer.
886 bool PassingDeclsToConsumer;
888 /// \brief The set of identifiers that were read while the AST reader was
889 /// (recursively) loading declarations.
891 /// The declarations on the identifier chain for these identifiers will be
892 /// loaded once the recursive loading has completed.
893 llvm::MapVector<IdentifierInfo *, SmallVector<uint32_t, 4> >
894 PendingIdentifierInfos;
896 /// \brief The set of lookup results that we have faked in order to support
897 /// merging of partially deserialized decls but that we have not yet removed.
898 llvm::SmallMapVector<IdentifierInfo *, SmallVector<NamedDecl*, 2>, 16>
899 PendingFakeLookupResults;
901 /// \brief The generation number of each identifier, which keeps track of
902 /// the last time we loaded information about this identifier.
903 llvm::DenseMap<IdentifierInfo *, unsigned> IdentifierGeneration;
905 /// \brief Contains declarations and definitions that will be
906 /// "interesting" to the ASTConsumer, when we get that AST consumer.
908 /// "Interesting" declarations are those that have data that may
909 /// need to be emitted, such as inline function definitions or
910 /// Objective-C protocols.
911 std::deque<Decl *> InterestingDecls;
913 /// \brief The set of redeclarable declarations that have been deserialized
914 /// since the last time the declaration chains were linked.
915 llvm::SmallPtrSet<Decl *, 16> RedeclsDeserialized;
917 /// \brief The list of redeclaration chains that still need to be
920 /// Each element is the canonical declaration of the chain.
921 /// Elements in this vector should be unique; use
922 /// PendingDeclChainsKnown to ensure uniqueness.
923 SmallVector<Decl *, 16> PendingDeclChains;
925 /// \brief Keeps track of the elements added to PendingDeclChains.
926 llvm::SmallSet<Decl *, 16> PendingDeclChainsKnown;
928 /// \brief The list of canonical declarations whose redeclaration chains
929 /// need to be marked as incomplete once we're done deserializing things.
930 SmallVector<Decl *, 16> PendingIncompleteDeclChains;
932 /// \brief The Decl IDs for the Sema/Lexical DeclContext of a Decl that has
933 /// been loaded but its DeclContext was not set yet.
934 struct PendingDeclContextInfo {
936 serialization::GlobalDeclID SemaDC;
937 serialization::GlobalDeclID LexicalDC;
940 /// \brief The set of Decls that have been loaded but their DeclContexts are
943 /// The DeclContexts for these Decls will be set once recursive loading has
945 std::deque<PendingDeclContextInfo> PendingDeclContextInfos;
947 /// \brief The set of NamedDecls that have been loaded, but are members of a
948 /// context that has been merged into another context where the corresponding
949 /// declaration is either missing or has not yet been loaded.
951 /// We will check whether the corresponding declaration is in fact missing
952 /// once recursing loading has been completed.
953 llvm::SmallVector<NamedDecl *, 16> PendingOdrMergeChecks;
955 /// \brief Record definitions in which we found an ODR violation.
956 llvm::SmallDenseMap<CXXRecordDecl *, llvm::TinyPtrVector<CXXRecordDecl *>, 2>
957 PendingOdrMergeFailures;
959 /// \brief DeclContexts in which we have diagnosed an ODR violation.
960 llvm::SmallPtrSet<DeclContext*, 2> DiagnosedOdrMergeFailures;
962 /// \brief The set of Objective-C categories that have been deserialized
963 /// since the last time the declaration chains were linked.
964 llvm::SmallPtrSet<ObjCCategoryDecl *, 16> CategoriesDeserialized;
966 /// \brief The set of Objective-C class definitions that have already been
967 /// loaded, for which we will need to check for categories whenever a new
968 /// module is loaded.
969 SmallVector<ObjCInterfaceDecl *, 16> ObjCClassesLoaded;
971 /// \brief A mapping from a primary context for a declaration chain to the
972 /// other declarations of that entity that also have name lookup tables.
973 /// Used when we merge together two class definitions that have different
974 /// sets of declared special member functions.
975 llvm::DenseMap<const DeclContext*, SmallVector<const DeclContext*, 2>>
978 typedef llvm::DenseMap<Decl *, SmallVector<serialization::DeclID, 2> >
981 /// \brief A mapping from canonical declarations to the set of additional
982 /// (global, previously-canonical) declaration IDs that have been merged with
983 /// that canonical declaration.
984 MergedDeclsMap MergedDecls;
986 /// \brief A mapping from DeclContexts to the semantic DeclContext that we
987 /// are treating as the definition of the entity. This is used, for instance,
988 /// when merging implicit instantiations of class templates across modules.
989 llvm::DenseMap<DeclContext *, DeclContext *> MergedDeclContexts;
991 /// \brief A mapping from canonical declarations of enums to their canonical
992 /// definitions. Only populated when using modules in C++.
993 llvm::DenseMap<EnumDecl *, EnumDecl *> EnumDefinitions;
995 /// \brief When reading a Stmt tree, Stmt operands are placed in this stack.
996 SmallVector<Stmt *, 16> StmtStack;
998 /// \brief What kind of records we are reading.
1000 Read_None, Read_Decl, Read_Type, Read_Stmt
1003 /// \brief What kind of records we are reading.
1004 ReadingKind ReadingKind;
1006 /// \brief RAII object to change the reading kind.
1007 class ReadingKindTracker {
1009 enum ReadingKind PrevKind;
1011 ReadingKindTracker(const ReadingKindTracker &) = delete;
1012 void operator=(const ReadingKindTracker &) = delete;
1015 ReadingKindTracker(enum ReadingKind newKind, ASTReader &reader)
1016 : Reader(reader), PrevKind(Reader.ReadingKind) {
1017 Reader.ReadingKind = newKind;
1020 ~ReadingKindTracker() { Reader.ReadingKind = PrevKind; }
1023 /// \brief Suggested contents of the predefines buffer, after this
1024 /// PCH file has been processed.
1026 /// In most cases, this string will be empty, because the predefines
1027 /// buffer computed to build the PCH file will be identical to the
1028 /// predefines buffer computed from the command line. However, when
1029 /// there are differences that the PCH reader can work around, this
1030 /// predefines buffer may contain additional definitions.
1031 std::string SuggestedPredefines;
1033 /// \brief Reads a statement from the specified cursor.
1034 Stmt *ReadStmtFromStream(ModuleFile &F);
1036 struct InputFileInfo {
1037 std::string Filename;
1043 /// \brief Reads the stored information about an input file.
1044 InputFileInfo readInputFileInfo(ModuleFile &F, unsigned ID);
1045 /// \brief A convenience method to read the filename from an input file.
1046 std::string getInputFileName(ModuleFile &F, unsigned ID);
1048 /// \brief Retrieve the file entry and 'overridden' bit for an input
1049 /// file in the given module file.
1050 serialization::InputFile getInputFile(ModuleFile &F, unsigned ID,
1051 bool Complain = true);
1054 void ResolveImportedPath(ModuleFile &M, std::string &Filename);
1055 static void ResolveImportedPath(std::string &Filename, StringRef Prefix);
1058 struct ImportedModule {
1060 ModuleFile *ImportedBy;
1061 SourceLocation ImportLoc;
1063 ImportedModule(ModuleFile *Mod,
1064 ModuleFile *ImportedBy,
1065 SourceLocation ImportLoc)
1066 : Mod(Mod), ImportedBy(ImportedBy), ImportLoc(ImportLoc) { }
1069 ASTReadResult ReadASTCore(StringRef FileName, ModuleKind Type,
1070 SourceLocation ImportLoc, ModuleFile *ImportedBy,
1071 SmallVectorImpl<ImportedModule> &Loaded,
1072 off_t ExpectedSize, time_t ExpectedModTime,
1073 serialization::ASTFileSignature ExpectedSignature,
1074 unsigned ClientLoadCapabilities);
1075 ASTReadResult ReadControlBlock(ModuleFile &F,
1076 SmallVectorImpl<ImportedModule> &Loaded,
1077 const ModuleFile *ImportedBy,
1078 unsigned ClientLoadCapabilities);
1079 ASTReadResult ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities);
1080 bool ParseLineTable(ModuleFile &F, const RecordData &Record);
1081 bool ReadSourceManagerBlock(ModuleFile &F);
1082 llvm::BitstreamCursor &SLocCursorForID(int ID);
1083 SourceLocation getImportLocation(ModuleFile *F);
1084 ASTReadResult ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
1085 const ModuleFile *ImportedBy,
1086 unsigned ClientLoadCapabilities);
1087 ASTReadResult ReadSubmoduleBlock(ModuleFile &F,
1088 unsigned ClientLoadCapabilities);
1089 static bool ParseLanguageOptions(const RecordData &Record, bool Complain,
1090 ASTReaderListener &Listener,
1091 bool AllowCompatibleDifferences);
1092 static bool ParseTargetOptions(const RecordData &Record, bool Complain,
1093 ASTReaderListener &Listener,
1094 bool AllowCompatibleDifferences);
1095 static bool ParseDiagnosticOptions(const RecordData &Record, bool Complain,
1096 ASTReaderListener &Listener);
1097 static bool ParseFileSystemOptions(const RecordData &Record, bool Complain,
1098 ASTReaderListener &Listener);
1099 static bool ParseHeaderSearchOptions(const RecordData &Record, bool Complain,
1100 ASTReaderListener &Listener);
1101 static bool ParsePreprocessorOptions(const RecordData &Record, bool Complain,
1102 ASTReaderListener &Listener,
1103 std::string &SuggestedPredefines);
1105 struct RecordLocation {
1106 RecordLocation(ModuleFile *M, uint64_t O)
1107 : F(M), Offset(O) {}
1112 QualType readTypeRecord(unsigned Index);
1113 void readExceptionSpec(ModuleFile &ModuleFile,
1114 SmallVectorImpl<QualType> &ExceptionStorage,
1115 FunctionProtoType::ExceptionSpecInfo &ESI,
1116 const RecordData &Record, unsigned &Index);
1117 RecordLocation TypeCursorForIndex(unsigned Index);
1118 void LoadedDecl(unsigned Index, Decl *D);
1119 Decl *ReadDeclRecord(serialization::DeclID ID);
1120 void markIncompleteDeclChain(Decl *Canon);
1122 /// \brief Returns the most recent declaration of a declaration (which must be
1123 /// of a redeclarable kind) that is either local or has already been loaded
1124 /// merged into its redecl chain.
1125 Decl *getMostRecentExistingDecl(Decl *D);
1127 template <typename Fn>
1128 void forEachFormerlyCanonicalImportedDecl(const Decl *D, Fn Visit) {
1129 D = D->getCanonicalDecl();
1130 if (D->isFromASTFile())
1133 auto It = MergedDecls.find(const_cast<Decl*>(D));
1134 if (It != MergedDecls.end())
1135 for (auto ID : It->second)
1136 Visit(GetExistingDecl(ID));
1139 RecordLocation DeclCursorForID(serialization::DeclID ID,
1140 unsigned &RawLocation);
1141 void loadDeclUpdateRecords(serialization::DeclID ID, Decl *D);
1142 void loadPendingDeclChain(Decl *D);
1143 void loadObjCCategories(serialization::GlobalDeclID ID, ObjCInterfaceDecl *D,
1144 unsigned PreviousGeneration = 0);
1146 RecordLocation getLocalBitOffset(uint64_t GlobalOffset);
1147 uint64_t getGlobalBitOffset(ModuleFile &M, uint32_t LocalOffset);
1149 /// \brief Returns the first preprocessed entity ID that begins or ends after
1151 serialization::PreprocessedEntityID
1152 findPreprocessedEntity(SourceLocation Loc, bool EndsAfter) const;
1154 /// \brief Find the next module that contains entities and return the ID
1155 /// of the first entry.
1157 /// \param SLocMapI points at a chunk of a module that contains no
1158 /// preprocessed entities or the entities it contains are not the
1159 /// ones we are looking for.
1160 serialization::PreprocessedEntityID
1161 findNextPreprocessedEntity(
1162 GlobalSLocOffsetMapType::const_iterator SLocMapI) const;
1164 /// \brief Returns (ModuleFile, Local index) pair for \p GlobalIndex of a
1165 /// preprocessed entity.
1166 std::pair<ModuleFile *, unsigned>
1167 getModulePreprocessedEntity(unsigned GlobalIndex);
1169 /// \brief Returns (begin, end) pair for the preprocessed entities of a
1170 /// particular module.
1171 llvm::iterator_range<PreprocessingRecord::iterator>
1172 getModulePreprocessedEntities(ModuleFile &Mod) const;
1174 class ModuleDeclIterator
1175 : public llvm::iterator_adaptor_base<
1176 ModuleDeclIterator, const serialization::LocalDeclID *,
1177 std::random_access_iterator_tag, const Decl *, ptrdiff_t,
1178 const Decl *, const Decl *> {
1183 ModuleDeclIterator()
1184 : iterator_adaptor_base(nullptr), Reader(nullptr), Mod(nullptr) {}
1186 ModuleDeclIterator(ASTReader *Reader, ModuleFile *Mod,
1187 const serialization::LocalDeclID *Pos)
1188 : iterator_adaptor_base(Pos), Reader(Reader), Mod(Mod) {}
1190 value_type operator*() const {
1191 return Reader->GetDecl(Reader->getGlobalDeclID(*Mod, *I));
1193 value_type operator->() const { return **this; }
1195 bool operator==(const ModuleDeclIterator &RHS) const {
1196 assert(Reader == RHS.Reader && Mod == RHS.Mod);
1201 llvm::iterator_range<ModuleDeclIterator>
1202 getModuleFileLevelDecls(ModuleFile &Mod);
1204 void PassInterestingDeclsToConsumer();
1205 void PassInterestingDeclToConsumer(Decl *D);
1207 void finishPendingActions();
1208 void diagnoseOdrViolations();
1210 void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name);
1212 void addPendingDeclContextInfo(Decl *D,
1213 serialization::GlobalDeclID SemaDC,
1214 serialization::GlobalDeclID LexicalDC) {
1216 PendingDeclContextInfo Info = { D, SemaDC, LexicalDC };
1217 PendingDeclContextInfos.push_back(Info);
1220 /// \brief Produce an error diagnostic and return true.
1222 /// This routine should only be used for fatal errors that have to
1223 /// do with non-routine failures (e.g., corrupted AST file).
1224 void Error(StringRef Msg);
1225 void Error(unsigned DiagID, StringRef Arg1 = StringRef(),
1226 StringRef Arg2 = StringRef());
1228 ASTReader(const ASTReader &) = delete;
1229 void operator=(const ASTReader &) = delete;
1231 /// \brief Load the AST file and validate its contents against the given
1234 /// \param PP the preprocessor associated with the context in which this
1235 /// precompiled header will be loaded.
1237 /// \param Context the AST context that this precompiled header will be
1240 /// \param isysroot If non-NULL, the system include path specified by the
1241 /// user. This is only used with relocatable PCH files. If non-NULL,
1242 /// a relocatable PCH file will use the default path "/".
1244 /// \param DisableValidation If true, the AST reader will suppress most
1245 /// of its regular consistency checking, allowing the use of precompiled
1246 /// headers that cannot be determined to be compatible.
1248 /// \param AllowASTWithCompilerErrors If true, the AST reader will accept an
1249 /// AST file the was created out of an AST with compiler errors,
1250 /// otherwise it will reject it.
1252 /// \param AllowConfigurationMismatch If true, the AST reader will not check
1253 /// for configuration differences between the AST file and the invocation.
1255 /// \param ValidateSystemInputs If true, the AST reader will validate
1256 /// system input files in addition to user input files. This is only
1257 /// meaningful if \p DisableValidation is false.
1259 /// \param UseGlobalIndex If true, the AST reader will try to load and use
1260 /// the global module index.
1261 ASTReader(Preprocessor &PP, ASTContext &Context, StringRef isysroot = "",
1262 bool DisableValidation = false,
1263 bool AllowASTWithCompilerErrors = false,
1264 bool AllowConfigurationMismatch = false,
1265 bool ValidateSystemInputs = false,
1266 bool UseGlobalIndex = true);
1268 ~ASTReader() override;
1270 SourceManager &getSourceManager() const { return SourceMgr; }
1271 FileManager &getFileManager() const { return FileMgr; }
1273 /// \brief Flags that indicate what kind of AST loading failures the client
1274 /// of the AST reader can directly handle.
1276 /// When a client states that it can handle a particular kind of failure,
1277 /// the AST reader will not emit errors when producing that kind of failure.
1278 enum LoadFailureCapabilities {
1279 /// \brief The client can't handle any AST loading failures.
1281 /// \brief The client can handle an AST file that cannot load because it
1284 /// \brief The client can handle an AST file that cannot load because it
1285 /// is out-of-date relative to its input files.
1286 ARR_OutOfDate = 0x2,
1287 /// \brief The client can handle an AST file that cannot load because it
1288 /// was built with a different version of Clang.
1289 ARR_VersionMismatch = 0x4,
1290 /// \brief The client can handle an AST file that cannot load because it's
1291 /// compiled configuration doesn't match that of the context it was
1293 ARR_ConfigurationMismatch = 0x8
1296 /// \brief Load the AST file designated by the given file name.
1298 /// \param FileName The name of the AST file to load.
1300 /// \param Type The kind of AST being loaded, e.g., PCH, module, main file,
1303 /// \param ImportLoc the location where the module file will be considered as
1304 /// imported from. For non-module AST types it should be invalid.
1306 /// \param ClientLoadCapabilities The set of client load-failure
1307 /// capabilities, represented as a bitset of the enumerators of
1308 /// LoadFailureCapabilities.
1309 ASTReadResult ReadAST(const std::string &FileName, ModuleKind Type,
1310 SourceLocation ImportLoc,
1311 unsigned ClientLoadCapabilities);
1313 /// \brief Make the entities in the given module and any of its (non-explicit)
1314 /// submodules visible to name lookup.
1316 /// \param Mod The module whose names should be made visible.
1318 /// \param NameVisibility The level of visibility to give the names in the
1319 /// module. Visibility can only be increased over time.
1321 /// \param ImportLoc The location at which the import occurs.
1322 void makeModuleVisible(Module *Mod,
1323 Module::NameVisibilityKind NameVisibility,
1324 SourceLocation ImportLoc);
1326 /// \brief Make the names within this set of hidden names visible.
1327 void makeNamesVisible(const HiddenNames &Names, Module *Owner);
1329 /// \brief Take the AST callbacks listener.
1330 std::unique_ptr<ASTReaderListener> takeListener() {
1331 return std::move(Listener);
1334 /// \brief Set the AST callbacks listener.
1335 void setListener(std::unique_ptr<ASTReaderListener> Listener) {
1336 this->Listener = std::move(Listener);
1339 /// \brief Add an AST callback listener.
1341 /// Takes ownership of \p L.
1342 void addListener(std::unique_ptr<ASTReaderListener> L) {
1344 L = llvm::make_unique<ChainedASTReaderListener>(std::move(L),
1345 std::move(Listener));
1346 Listener = std::move(L);
1349 /// RAII object to temporarily add an AST callback listener.
1350 class ListenerScope {
1355 ListenerScope(ASTReader &Reader, std::unique_ptr<ASTReaderListener> L)
1356 : Reader(Reader), Chained(false) {
1357 auto Old = Reader.takeListener();
1360 L = llvm::make_unique<ChainedASTReaderListener>(std::move(L),
1363 Reader.setListener(std::move(L));
1366 auto New = Reader.takeListener();
1368 Reader.setListener(static_cast<ChainedASTReaderListener *>(New.get())
1373 /// \brief Set the AST deserialization listener.
1374 void setDeserializationListener(ASTDeserializationListener *Listener,
1375 bool TakeOwnership = false);
1377 /// \brief Determine whether this AST reader has a global index.
1378 bool hasGlobalIndex() const { return (bool)GlobalIndex; }
1380 /// \brief Return global module index.
1381 GlobalModuleIndex *getGlobalIndex() { return GlobalIndex.get(); }
1383 /// \brief Reset reader for a reload try.
1384 void resetForReload() { TriedLoadingGlobalIndex = false; }
1386 /// \brief Attempts to load the global index.
1388 /// \returns true if loading the global index has failed for any reason.
1389 bool loadGlobalIndex();
1391 /// \brief Determine whether we tried to load the global index, but failed,
1392 /// e.g., because it is out-of-date or does not exist.
1393 bool isGlobalIndexUnavailable() const;
1395 /// \brief Initializes the ASTContext
1396 void InitializeContext();
1398 /// \brief Update the state of Sema after loading some additional modules.
1401 /// \brief Add in-memory (virtual file) buffer.
1402 void addInMemoryBuffer(StringRef &FileName,
1403 std::unique_ptr<llvm::MemoryBuffer> Buffer) {
1404 ModuleMgr.addInMemoryBuffer(FileName, std::move(Buffer));
1407 /// \brief Finalizes the AST reader's state before writing an AST file to
1410 /// This operation may undo temporary state in the AST that should not be
1412 void finalizeForWriting();
1414 /// \brief Retrieve the module manager.
1415 ModuleManager &getModuleManager() { return ModuleMgr; }
1417 /// \brief Retrieve the preprocessor.
1418 Preprocessor &getPreprocessor() const { return PP; }
1420 /// \brief Retrieve the name of the original source file name for the primary
1422 StringRef getOriginalSourceFile() {
1423 return ModuleMgr.getPrimaryModule().OriginalSourceFileName;
1426 /// \brief Retrieve the name of the original source file name directly from
1427 /// the AST file, without actually loading the AST file.
1428 static std::string getOriginalSourceFile(const std::string &ASTFileName,
1429 FileManager &FileMgr,
1430 DiagnosticsEngine &Diags);
1432 /// \brief Read the control block for the named AST file.
1434 /// \returns true if an error occurred, false otherwise.
1435 static bool readASTFileControlBlock(StringRef Filename,
1436 FileManager &FileMgr,
1437 ASTReaderListener &Listener);
1439 /// \brief Determine whether the given AST file is acceptable to load into a
1440 /// translation unit with the given language and target options.
1441 static bool isAcceptableASTFile(StringRef Filename,
1442 FileManager &FileMgr,
1443 const LangOptions &LangOpts,
1444 const TargetOptions &TargetOpts,
1445 const PreprocessorOptions &PPOpts,
1446 std::string ExistingModuleCachePath);
1448 /// \brief Returns the suggested contents of the predefines buffer,
1449 /// which contains a (typically-empty) subset of the predefines
1450 /// build prior to including the precompiled header.
1451 const std::string &getSuggestedPredefines() { return SuggestedPredefines; }
1453 /// \brief Read a preallocated preprocessed entity from the external source.
1455 /// \returns null if an error occurred that prevented the preprocessed
1456 /// entity from being loaded.
1457 PreprocessedEntity *ReadPreprocessedEntity(unsigned Index) override;
1459 /// \brief Returns a pair of [Begin, End) indices of preallocated
1460 /// preprocessed entities that \p Range encompasses.
1461 std::pair<unsigned, unsigned>
1462 findPreprocessedEntitiesInRange(SourceRange Range) override;
1464 /// \brief Optionally returns true or false if the preallocated preprocessed
1465 /// entity with index \p Index came from file \p FID.
1466 Optional<bool> isPreprocessedEntityInFileID(unsigned Index,
1467 FileID FID) override;
1469 /// \brief Read the header file information for the given file entry.
1470 HeaderFileInfo GetHeaderFileInfo(const FileEntry *FE) override;
1472 void ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag);
1474 /// \brief Returns the number of source locations found in the chain.
1475 unsigned getTotalNumSLocs() const {
1476 return TotalNumSLocEntries;
1479 /// \brief Returns the number of identifiers found in the chain.
1480 unsigned getTotalNumIdentifiers() const {
1481 return static_cast<unsigned>(IdentifiersLoaded.size());
1484 /// \brief Returns the number of macros found in the chain.
1485 unsigned getTotalNumMacros() const {
1486 return static_cast<unsigned>(MacrosLoaded.size());
1489 /// \brief Returns the number of types found in the chain.
1490 unsigned getTotalNumTypes() const {
1491 return static_cast<unsigned>(TypesLoaded.size());
1494 /// \brief Returns the number of declarations found in the chain.
1495 unsigned getTotalNumDecls() const {
1496 return static_cast<unsigned>(DeclsLoaded.size());
1499 /// \brief Returns the number of submodules known.
1500 unsigned getTotalNumSubmodules() const {
1501 return static_cast<unsigned>(SubmodulesLoaded.size());
1504 /// \brief Returns the number of selectors found in the chain.
1505 unsigned getTotalNumSelectors() const {
1506 return static_cast<unsigned>(SelectorsLoaded.size());
1509 /// \brief Returns the number of preprocessed entities known to the AST
1511 unsigned getTotalNumPreprocessedEntities() const {
1512 unsigned Result = 0;
1513 for (ModuleConstIterator I = ModuleMgr.begin(),
1514 E = ModuleMgr.end(); I != E; ++I) {
1515 Result += (*I)->NumPreprocessedEntities;
1521 /// \brief Reads a TemplateArgumentLocInfo appropriate for the
1522 /// given TemplateArgument kind.
1523 TemplateArgumentLocInfo
1524 GetTemplateArgumentLocInfo(ModuleFile &F, TemplateArgument::ArgKind Kind,
1525 const RecordData &Record, unsigned &Idx);
1527 /// \brief Reads a TemplateArgumentLoc.
1529 ReadTemplateArgumentLoc(ModuleFile &F,
1530 const RecordData &Record, unsigned &Idx);
1532 const ASTTemplateArgumentListInfo*
1533 ReadASTTemplateArgumentListInfo(ModuleFile &F,
1534 const RecordData &Record, unsigned &Index);
1536 /// \brief Reads a declarator info from the given record.
1537 TypeSourceInfo *GetTypeSourceInfo(ModuleFile &F,
1538 const RecordData &Record, unsigned &Idx);
1540 /// \brief Resolve a type ID into a type, potentially building a new
1542 QualType GetType(serialization::TypeID ID);
1544 /// \brief Resolve a local type ID within a given AST file into a type.
1545 QualType getLocalType(ModuleFile &F, unsigned LocalID);
1547 /// \brief Map a local type ID within a given AST file into a global type ID.
1548 serialization::TypeID getGlobalTypeID(ModuleFile &F, unsigned LocalID) const;
1550 /// \brief Read a type from the current position in the given record, which
1551 /// was read from the given AST file.
1552 QualType readType(ModuleFile &F, const RecordData &Record, unsigned &Idx) {
1553 if (Idx >= Record.size())
1556 return getLocalType(F, Record[Idx++]);
1559 /// \brief Map from a local declaration ID within a given module to a
1560 /// global declaration ID.
1561 serialization::DeclID getGlobalDeclID(ModuleFile &F,
1562 serialization::LocalDeclID LocalID) const;
1564 /// \brief Returns true if global DeclID \p ID originated from module \p M.
1565 bool isDeclIDFromModule(serialization::GlobalDeclID ID, ModuleFile &M) const;
1567 /// \brief Retrieve the module file that owns the given declaration, or NULL
1568 /// if the declaration is not from a module file.
1569 ModuleFile *getOwningModuleFile(const Decl *D);
1571 /// \brief Get the best name we know for the module that owns the given
1572 /// declaration, or an empty string if the declaration is not from a module.
1573 std::string getOwningModuleNameForDiagnostic(const Decl *D);
1575 /// \brief Returns the source location for the decl \p ID.
1576 SourceLocation getSourceLocationForDeclID(serialization::GlobalDeclID ID);
1578 /// \brief Resolve a declaration ID into a declaration, potentially
1579 /// building a new declaration.
1580 Decl *GetDecl(serialization::DeclID ID);
1581 Decl *GetExternalDecl(uint32_t ID) override;
1583 /// \brief Resolve a declaration ID into a declaration. Return 0 if it's not
1584 /// been loaded yet.
1585 Decl *GetExistingDecl(serialization::DeclID ID);
1587 /// \brief Reads a declaration with the given local ID in the given module.
1588 Decl *GetLocalDecl(ModuleFile &F, uint32_t LocalID) {
1589 return GetDecl(getGlobalDeclID(F, LocalID));
1592 /// \brief Reads a declaration with the given local ID in the given module.
1594 /// \returns The requested declaration, casted to the given return type.
1595 template<typename T>
1596 T *GetLocalDeclAs(ModuleFile &F, uint32_t LocalID) {
1597 return cast_or_null<T>(GetLocalDecl(F, LocalID));
1600 /// \brief Map a global declaration ID into the declaration ID used to
1601 /// refer to this declaration within the given module fule.
1603 /// \returns the global ID of the given declaration as known in the given
1605 serialization::DeclID
1606 mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
1607 serialization::DeclID GlobalID);
1609 /// \brief Reads a declaration ID from the given position in a record in the
1612 /// \returns The declaration ID read from the record, adjusted to a global ID.
1613 serialization::DeclID ReadDeclID(ModuleFile &F, const RecordData &Record,
1616 /// \brief Reads a declaration from the given position in a record in the
1618 Decl *ReadDecl(ModuleFile &F, const RecordData &R, unsigned &I) {
1619 return GetDecl(ReadDeclID(F, R, I));
1622 /// \brief Reads a declaration from the given position in a record in the
1625 /// \returns The declaration read from this location, casted to the given
1627 template<typename T>
1628 T *ReadDeclAs(ModuleFile &F, const RecordData &R, unsigned &I) {
1629 return cast_or_null<T>(GetDecl(ReadDeclID(F, R, I)));
1632 /// \brief If any redeclarations of \p D have been imported since it was
1633 /// last checked, this digs out those redeclarations and adds them to the
1634 /// redeclaration chain for \p D.
1635 void CompleteRedeclChain(const Decl *D) override;
1637 /// \brief Read a CXXBaseSpecifiers ID form the given record and
1638 /// return its global bit offset.
1639 uint64_t readCXXBaseSpecifiers(ModuleFile &M, const RecordData &Record,
1642 CXXBaseSpecifier *GetExternalCXXBaseSpecifiers(uint64_t Offset) override;
1644 /// \brief Resolve the offset of a statement into a statement.
1646 /// This operation will read a new statement from the external
1647 /// source each time it is called, and is meant to be used via a
1648 /// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
1649 Stmt *GetExternalDeclStmt(uint64_t Offset) override;
1651 /// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1652 /// specified cursor. Read the abbreviations that are at the top of the block
1653 /// and then leave the cursor pointing into the block.
1654 bool ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor, unsigned BlockID);
1656 /// \brief Finds all the visible declarations with a given name.
1657 /// The current implementation of this method just loads the entire
1658 /// lookup table as unmaterialized references.
1659 bool FindExternalVisibleDeclsByName(const DeclContext *DC,
1660 DeclarationName Name) override;
1662 /// \brief Read all of the declarations lexically stored in a
1663 /// declaration context.
1665 /// \param DC The declaration context whose declarations will be
1668 /// \param Decls Vector that will contain the declarations loaded
1669 /// from the external source. The caller is responsible for merging
1670 /// these declarations with any declarations already stored in the
1671 /// declaration context.
1673 /// \returns true if there was an error while reading the
1674 /// declarations for this declaration context.
1675 ExternalLoadResult FindExternalLexicalDecls(const DeclContext *DC,
1676 bool (*isKindWeWant)(Decl::Kind),
1677 SmallVectorImpl<Decl*> &Decls) override;
1679 /// \brief Get the decls that are contained in a file in the Offset/Length
1680 /// range. \p Length can be 0 to indicate a point at \p Offset instead of
1682 void FindFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
1683 SmallVectorImpl<Decl *> &Decls) override;
1685 /// \brief Notify ASTReader that we started deserialization of
1686 /// a decl or type so until FinishedDeserializing is called there may be
1687 /// decls that are initializing. Must be paired with FinishedDeserializing.
1688 void StartedDeserializing() override { ++NumCurrentElementsDeserializing; }
1690 /// \brief Notify ASTReader that we finished the deserialization of
1691 /// a decl or type. Must be paired with StartedDeserializing.
1692 void FinishedDeserializing() override;
1694 /// \brief Function that will be invoked when we begin parsing a new
1695 /// translation unit involving this external AST source.
1697 /// This function will provide all of the external definitions to
1698 /// the ASTConsumer.
1699 void StartTranslationUnit(ASTConsumer *Consumer) override;
1701 /// \brief Print some statistics about AST usage.
1702 void PrintStats() override;
1704 /// \brief Dump information about the AST reader to standard error.
1707 /// Return the amount of memory used by memory buffers, breaking down
1708 /// by heap-backed versus mmap'ed memory.
1709 void getMemoryBufferSizes(MemoryBufferSizes &sizes) const override;
1711 /// \brief Initialize the semantic source with the Sema instance
1712 /// being used to perform semantic analysis on the abstract syntax
1714 void InitializeSema(Sema &S) override;
1716 /// \brief Inform the semantic consumer that Sema is no longer available.
1717 void ForgetSema() override { SemaObj = nullptr; }
1719 /// \brief Retrieve the IdentifierInfo for the named identifier.
1721 /// This routine builds a new IdentifierInfo for the given identifier. If any
1722 /// declarations with this name are visible from translation unit scope, their
1723 /// declarations will be deserialized and introduced into the declaration
1724 /// chain of the identifier.
1725 virtual IdentifierInfo *get(const char *NameStart, const char *NameEnd);
1726 IdentifierInfo *get(StringRef Name) override {
1727 return get(Name.begin(), Name.end());
1730 /// \brief Retrieve an iterator into the set of all identifiers
1731 /// in all loaded AST files.
1732 IdentifierIterator *getIdentifiers() override;
1734 /// \brief Load the contents of the global method pool for a given
1736 void ReadMethodPool(Selector Sel) override;
1738 /// \brief Load the set of namespaces that are known to the external source,
1739 /// which will be used during typo correction.
1740 void ReadKnownNamespaces(
1741 SmallVectorImpl<NamespaceDecl *> &Namespaces) override;
1743 void ReadUndefinedButUsed(
1744 llvm::DenseMap<NamedDecl *, SourceLocation> &Undefined) override;
1746 void ReadMismatchingDeleteExpressions(llvm::MapVector<
1747 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
1750 void ReadTentativeDefinitions(
1751 SmallVectorImpl<VarDecl *> &TentativeDefs) override;
1753 void ReadUnusedFileScopedDecls(
1754 SmallVectorImpl<const DeclaratorDecl *> &Decls) override;
1756 void ReadDelegatingConstructors(
1757 SmallVectorImpl<CXXConstructorDecl *> &Decls) override;
1759 void ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) override;
1761 void ReadUnusedLocalTypedefNameCandidates(
1762 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) override;
1764 void ReadReferencedSelectors(
1765 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) override;
1767 void ReadWeakUndeclaredIdentifiers(
1768 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WI) override;
1770 void ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) override;
1772 void ReadPendingInstantiations(
1773 SmallVectorImpl<std::pair<ValueDecl *,
1774 SourceLocation> > &Pending) override;
1776 void ReadLateParsedTemplates(
1777 llvm::MapVector<const FunctionDecl *, LateParsedTemplate *> &LPTMap)
1780 /// \brief Load a selector from disk, registering its ID if it exists.
1781 void LoadSelector(Selector Sel);
1783 void SetIdentifierInfo(unsigned ID, IdentifierInfo *II);
1784 void SetGloballyVisibleDecls(IdentifierInfo *II,
1785 const SmallVectorImpl<uint32_t> &DeclIDs,
1786 SmallVectorImpl<Decl *> *Decls = nullptr);
1788 /// \brief Report a diagnostic.
1789 DiagnosticBuilder Diag(unsigned DiagID);
1791 /// \brief Report a diagnostic.
1792 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
1794 IdentifierInfo *DecodeIdentifierInfo(serialization::IdentifierID ID);
1796 IdentifierInfo *GetIdentifierInfo(ModuleFile &M, const RecordData &Record,
1798 return DecodeIdentifierInfo(getGlobalIdentifierID(M, Record[Idx++]));
1801 IdentifierInfo *GetIdentifier(serialization::IdentifierID ID) override {
1802 // Note that we are loading an identifier.
1803 Deserializing AnIdentifier(this);
1805 return DecodeIdentifierInfo(ID);
1808 IdentifierInfo *getLocalIdentifier(ModuleFile &M, unsigned LocalID);
1810 serialization::IdentifierID getGlobalIdentifierID(ModuleFile &M,
1813 void resolvePendingMacro(IdentifierInfo *II, const PendingMacroInfo &PMInfo);
1815 /// \brief Retrieve the macro with the given ID.
1816 MacroInfo *getMacro(serialization::MacroID ID);
1818 /// \brief Retrieve the global macro ID corresponding to the given local
1819 /// ID within the given module file.
1820 serialization::MacroID getGlobalMacroID(ModuleFile &M, unsigned LocalID);
1822 /// \brief Read the source location entry with index ID.
1823 bool ReadSLocEntry(int ID) override;
1825 /// \brief Retrieve the module import location and module name for the
1826 /// given source manager entry ID.
1827 std::pair<SourceLocation, StringRef> getModuleImportLoc(int ID) override;
1829 /// \brief Retrieve the global submodule ID given a module and its local ID
1831 serialization::SubmoduleID
1832 getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID);
1834 /// \brief Retrieve the submodule that corresponds to a global submodule ID.
1836 Module *getSubmodule(serialization::SubmoduleID GlobalID);
1838 /// \brief Retrieve the module that corresponds to the given module ID.
1840 /// Note: overrides method in ExternalASTSource
1841 Module *getModule(unsigned ID) override;
1843 /// \brief Retrieve a selector from the given module with its local ID
1845 Selector getLocalSelector(ModuleFile &M, unsigned LocalID);
1847 Selector DecodeSelector(serialization::SelectorID Idx);
1849 Selector GetExternalSelector(serialization::SelectorID ID) override;
1850 uint32_t GetNumExternalSelectors() override;
1852 Selector ReadSelector(ModuleFile &M, const RecordData &Record, unsigned &Idx) {
1853 return getLocalSelector(M, Record[Idx++]);
1856 /// \brief Retrieve the global selector ID that corresponds to this
1857 /// the local selector ID in a given module.
1858 serialization::SelectorID getGlobalSelectorID(ModuleFile &F,
1859 unsigned LocalID) const;
1861 /// \brief Read a declaration name.
1862 DeclarationName ReadDeclarationName(ModuleFile &F,
1863 const RecordData &Record, unsigned &Idx);
1864 void ReadDeclarationNameLoc(ModuleFile &F,
1865 DeclarationNameLoc &DNLoc, DeclarationName Name,
1866 const RecordData &Record, unsigned &Idx);
1867 void ReadDeclarationNameInfo(ModuleFile &F, DeclarationNameInfo &NameInfo,
1868 const RecordData &Record, unsigned &Idx);
1870 void ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
1871 const RecordData &Record, unsigned &Idx);
1873 NestedNameSpecifier *ReadNestedNameSpecifier(ModuleFile &F,
1874 const RecordData &Record,
1877 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc(ModuleFile &F,
1878 const RecordData &Record,
1881 /// \brief Read a template name.
1882 TemplateName ReadTemplateName(ModuleFile &F, const RecordData &Record,
1885 /// \brief Read a template argument.
1886 TemplateArgument ReadTemplateArgument(ModuleFile &F,
1887 const RecordData &Record,unsigned &Idx);
1889 /// \brief Read a template parameter list.
1890 TemplateParameterList *ReadTemplateParameterList(ModuleFile &F,
1891 const RecordData &Record,
1894 /// \brief Read a template argument array.
1896 ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
1897 ModuleFile &F, const RecordData &Record,
1900 /// \brief Read a UnresolvedSet structure.
1901 void ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
1902 const RecordData &Record, unsigned &Idx);
1904 /// \brief Read a C++ base specifier.
1905 CXXBaseSpecifier ReadCXXBaseSpecifier(ModuleFile &F,
1906 const RecordData &Record,unsigned &Idx);
1908 /// \brief Read a CXXCtorInitializer array.
1909 CXXCtorInitializer **
1910 ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
1913 /// \brief Read a CXXCtorInitializers ID from the given record and
1914 /// return its global bit offset.
1915 uint64_t ReadCXXCtorInitializersRef(ModuleFile &M, const RecordData &Record,
1918 /// \brief Read the contents of a CXXCtorInitializer array.
1919 CXXCtorInitializer **GetExternalCXXCtorInitializers(uint64_t Offset) override;
1921 /// \brief Read a source location from raw form.
1922 SourceLocation ReadSourceLocation(ModuleFile &ModuleFile, unsigned Raw) const {
1923 SourceLocation Loc = SourceLocation::getFromRawEncoding(Raw);
1924 assert(ModuleFile.SLocRemap.find(Loc.getOffset()) != ModuleFile.SLocRemap.end() &&
1925 "Cannot find offset to remap.");
1926 int Remap = ModuleFile.SLocRemap.find(Loc.getOffset())->second;
1927 return Loc.getLocWithOffset(Remap);
1930 /// \brief Read a source location.
1931 SourceLocation ReadSourceLocation(ModuleFile &ModuleFile,
1932 const RecordDataImpl &Record,
1934 return ReadSourceLocation(ModuleFile, Record[Idx++]);
1937 /// \brief Read a source range.
1938 SourceRange ReadSourceRange(ModuleFile &F,
1939 const RecordData &Record, unsigned &Idx);
1941 /// \brief Read an integral value
1942 llvm::APInt ReadAPInt(const RecordData &Record, unsigned &Idx);
1944 /// \brief Read a signed integral value
1945 llvm::APSInt ReadAPSInt(const RecordData &Record, unsigned &Idx);
1947 /// \brief Read a floating-point value
1948 llvm::APFloat ReadAPFloat(const RecordData &Record,
1949 const llvm::fltSemantics &Sem, unsigned &Idx);
1951 // \brief Read a string
1952 static std::string ReadString(const RecordData &Record, unsigned &Idx);
1954 // \brief Read a path
1955 std::string ReadPath(ModuleFile &F, const RecordData &Record, unsigned &Idx);
1957 /// \brief Read a version tuple.
1958 static VersionTuple ReadVersionTuple(const RecordData &Record, unsigned &Idx);
1960 CXXTemporary *ReadCXXTemporary(ModuleFile &F, const RecordData &Record,
1963 /// \brief Reads attributes from the current stream position.
1964 void ReadAttributes(ModuleFile &F, AttrVec &Attrs,
1965 const RecordData &Record, unsigned &Idx);
1967 /// \brief Reads a statement.
1968 Stmt *ReadStmt(ModuleFile &F);
1970 /// \brief Reads an expression.
1971 Expr *ReadExpr(ModuleFile &F);
1973 /// \brief Reads a sub-statement operand during statement reading.
1974 Stmt *ReadSubStmt() {
1975 assert(ReadingKind == Read_Stmt &&
1976 "Should be called only during statement reading!");
1977 // Subexpressions are stored from last to first, so the next Stmt we need
1978 // is at the back of the stack.
1979 assert(!StmtStack.empty() && "Read too many sub-statements!");
1980 return StmtStack.pop_back_val();
1983 /// \brief Reads a sub-expression operand during statement reading.
1984 Expr *ReadSubExpr();
1986 /// \brief Reads a token out of a record.
1987 Token ReadToken(ModuleFile &M, const RecordDataImpl &Record, unsigned &Idx);
1989 /// \brief Reads the macro record located at the given offset.
1990 MacroInfo *ReadMacroRecord(ModuleFile &F, uint64_t Offset);
1992 /// \brief Determine the global preprocessed entity ID that corresponds to
1993 /// the given local ID within the given module.
1994 serialization::PreprocessedEntityID
1995 getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const;
1997 /// \brief Add a macro to deserialize its macro directive history.
1999 /// \param II The name of the macro.
2000 /// \param M The module file.
2001 /// \param MacroDirectivesOffset Offset of the serialized macro directive
2003 void addPendingMacro(IdentifierInfo *II, ModuleFile *M,
2004 uint64_t MacroDirectivesOffset);
2006 /// \brief Read the set of macros defined by this external macro source.
2007 void ReadDefinedMacros() override;
2009 /// \brief Update an out-of-date identifier.
2010 void updateOutOfDateIdentifier(IdentifierInfo &II) override;
2012 /// \brief Note that this identifier is up-to-date.
2013 void markIdentifierUpToDate(IdentifierInfo *II);
2015 /// \brief Load all external visible decls in the given DeclContext.
2016 void completeVisibleDeclsMap(const DeclContext *DC) override;
2018 /// \brief Retrieve the AST context that this AST reader supplements.
2019 ASTContext &getContext() { return Context; }
2021 // \brief Contains the IDs for declarations that were requested before we have
2022 // access to a Sema object.
2023 SmallVector<uint64_t, 16> PreloadedDeclIDs;
2025 /// \brief Retrieve the semantic analysis object used to analyze the
2026 /// translation unit in which the precompiled header is being
2028 Sema *getSema() { return SemaObj; }
2030 /// \brief Retrieve the identifier table associated with the
2032 IdentifierTable &getIdentifierTable();
2034 /// \brief Record that the given ID maps to the given switch-case
2036 void RecordSwitchCaseID(SwitchCase *SC, unsigned ID);
2038 /// \brief Retrieve the switch-case statement with the given ID.
2039 SwitchCase *getSwitchCaseWithID(unsigned ID);
2041 void ClearSwitchCaseIDs();
2043 /// \brief Cursors for comments blocks.
2044 SmallVector<std::pair<llvm::BitstreamCursor,
2045 serialization::ModuleFile *>, 8> CommentsCursors;
2047 //RIDErief Loads comments ranges.
2048 void ReadComments() override;
2050 /// Return all input files for the given module file.
2051 void getInputFiles(ModuleFile &F,
2052 SmallVectorImpl<serialization::InputFile> &Files);
2055 /// \brief Helper class that saves the current stream position and
2056 /// then restores it when destroyed.
2057 struct SavedStreamPosition {
2058 explicit SavedStreamPosition(llvm::BitstreamCursor &Cursor)
2059 : Cursor(Cursor), Offset(Cursor.GetCurrentBitNo()) { }
2061 ~SavedStreamPosition() {
2062 Cursor.JumpToBit(Offset);
2066 llvm::BitstreamCursor &Cursor;
2070 inline void PCHValidator::Error(const char *Msg) {
2074 } // end namespace clang