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_FRONTEND_AST_READER_H
15 #define LLVM_CLANG_FRONTEND_AST_READER_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/DenseSet.h"
38 #include "llvm/ADT/MapVector.h"
39 #include "llvm/ADT/OwningPtr.h"
40 #include "llvm/ADT/SmallPtrSet.h"
41 #include "llvm/ADT/SmallSet.h"
42 #include "llvm/ADT/SmallVector.h"
43 #include "llvm/ADT/StringRef.h"
44 #include "llvm/Bitcode/BitstreamReader.h"
45 #include "llvm/Support/DataTypes.h"
62 class ASTIdentifierIterator;
63 class ASTUnit; // FIXME: Layering violation and egregious hack.
67 class DiagnosticOptions;
68 class NestedNameSpecifier;
69 class CXXBaseSpecifier;
70 class CXXConstructorDecl;
71 class CXXCtorInitializer;
72 class GlobalModuleIndex;
74 class MacroDefinition;
77 class OpaqueValueExpr;
79 class PreprocessorOptions;
82 class ASTDeserializationListener;
88 struct HeaderFileInfo;
91 class ASTUnresolvedSet;
93 /// \brief Abstract interface for callback invocations by the ASTReader.
95 /// While reading an AST file, the ASTReader will call the methods of the
96 /// listener to pass on specific information. Some of the listener methods can
97 /// return true to indicate to the ASTReader that the information (and
98 /// consequently the AST file) is invalid.
99 class ASTReaderListener {
101 virtual ~ASTReaderListener();
103 /// \brief Receives the full Clang version information.
105 /// \returns true to indicate that the version is invalid. Subclasses should
106 /// generally defer to this implementation.
107 virtual bool ReadFullVersionInformation(StringRef FullVersion) {
108 return FullVersion != getClangFullRepositoryVersion();
111 /// \brief Receives the language options.
113 /// \returns true to indicate the options are invalid or false otherwise.
114 virtual bool ReadLanguageOptions(const LangOptions &LangOpts,
119 /// \brief Receives the target options.
121 /// \returns true to indicate the target options are invalid, or false
123 virtual bool ReadTargetOptions(const TargetOptions &TargetOpts,
128 /// \brief Receives the diagnostic options.
130 /// \returns true to indicate the diagnostic options are invalid, or false
132 virtual bool ReadDiagnosticOptions(const DiagnosticOptions &DiagOpts,
137 /// \brief Receives the file system options.
139 /// \returns true to indicate the file system options are invalid, or false
141 virtual bool ReadFileSystemOptions(const FileSystemOptions &FSOpts,
146 /// \brief Receives the header search options.
148 /// \returns true to indicate the header search options are invalid, or false
150 virtual bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
155 /// \brief Receives the preprocessor options.
157 /// \param SuggestedPredefines Can be filled in with the set of predefines
158 /// that are suggested by the preprocessor options. Typically only used when
159 /// loading a precompiled header.
161 /// \returns true to indicate the preprocessor options are invalid, or false
163 virtual bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
165 std::string &SuggestedPredefines) {
169 /// \brief Receives a HeaderFileInfo entry.
170 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {}
172 /// \brief Receives __COUNTER__ value.
173 virtual void ReadCounter(const serialization::ModuleFile &M,
176 /// \brief Returns true if this \c ASTReaderListener wants to receive the
177 /// input files of the AST file via \c visitInputFile, false otherwise.
178 virtual bool needsInputFileVisitation() { return false; }
180 /// \brief if \c needsInputFileVisitation returns true, this is called for each
181 /// input file of the AST file.
183 /// \returns true to continue receiving the next input file, false to stop.
184 virtual bool visitInputFile(StringRef Filename, bool isSystem) { return true;}
187 /// \brief ASTReaderListener implementation to validate the information of
188 /// the PCH file against an initialized Preprocessor.
189 class PCHValidator : public ASTReaderListener {
193 unsigned NumHeaderInfos;
196 PCHValidator(Preprocessor &PP, ASTReader &Reader)
197 : PP(PP), Reader(Reader), NumHeaderInfos(0) {}
199 virtual bool ReadLanguageOptions(const LangOptions &LangOpts,
201 virtual bool ReadTargetOptions(const TargetOptions &TargetOpts,
203 virtual bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
205 std::string &SuggestedPredefines);
206 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID);
207 virtual void ReadCounter(const serialization::ModuleFile &M, unsigned Value);
210 void Error(const char *Msg);
213 namespace serialization {
215 class ReadMethodPoolVisitor;
218 class ASTIdentifierLookupTrait;
219 /// \brief The on-disk hash table used for the DeclContext's Name lookup table.
220 typedef OnDiskChainedHashTable<ASTDeclContextNameLookupTrait>
221 ASTDeclContextNameLookupTable;
224 } // end namespace serialization
226 /// \brief Reads an AST files chain containing the contents of a translation
229 /// The ASTReader class reads bitstreams (produced by the ASTWriter
230 /// class) containing the serialized representation of a given
231 /// abstract syntax tree and its supporting data structures. An
232 /// instance of the ASTReader can be attached to an ASTContext object,
233 /// which will provide access to the contents of the AST files.
235 /// The AST reader provides lazy de-serialization of declarations, as
236 /// required when traversing the AST. Only those AST nodes that are
237 /// actually required will be de-serialized.
239 : public ExternalPreprocessorSource,
240 public ExternalPreprocessingRecordSource,
241 public ExternalHeaderFileInfoSource,
242 public ExternalSemaSource,
243 public IdentifierInfoLookup,
244 public ExternalIdentifierLookup,
245 public ExternalSLocEntrySource
248 typedef SmallVector<uint64_t, 64> RecordData;
250 /// \brief The result of reading the control block of an AST file, which
251 /// can fail for various reasons.
253 /// \brief The control block was read successfully. Aside from failures,
254 /// the AST file is safe to read into the current context.
256 /// \brief The AST file itself appears corrupted.
258 /// \brief The AST file was missing.
260 /// \brief The AST file is out-of-date relative to its input files,
261 /// and needs to be regenerated.
263 /// \brief The AST file was written by a different version of Clang.
265 /// \brief The AST file was writtten with a different language/target
267 ConfigurationMismatch,
268 /// \brief The AST file has errors.
272 /// \brief Types of AST files.
273 friend class PCHValidator;
274 friend class ASTDeclReader;
275 friend class ASTStmtReader;
276 friend class ASTIdentifierIterator;
277 friend class serialization::reader::ASTIdentifierLookupTrait;
278 friend class TypeLocReader;
279 friend class ASTWriter;
280 friend class ASTUnit; // ASTUnit needs to remap source locations.
281 friend class serialization::ReadMethodPoolVisitor;
283 typedef serialization::ModuleFile ModuleFile;
284 typedef serialization::ModuleKind ModuleKind;
285 typedef serialization::ModuleManager ModuleManager;
287 typedef ModuleManager::ModuleIterator ModuleIterator;
288 typedef ModuleManager::ModuleConstIterator ModuleConstIterator;
289 typedef ModuleManager::ModuleReverseIterator ModuleReverseIterator;
292 /// \brief The receiver of some callbacks invoked by ASTReader.
293 OwningPtr<ASTReaderListener> Listener;
295 /// \brief The receiver of deserialization events.
296 ASTDeserializationListener *DeserializationListener;
298 SourceManager &SourceMgr;
299 FileManager &FileMgr;
300 DiagnosticsEngine &Diags;
302 /// \brief The semantic analysis object that will be processing the
303 /// AST files and the translation unit that uses it.
306 /// \brief The preprocessor that will be loading the source file.
309 /// \brief The AST context into which we'll read the AST files.
312 /// \brief The AST consumer.
313 ASTConsumer *Consumer;
315 /// \brief The module manager which manages modules and their dependencies
316 ModuleManager ModuleMgr;
318 /// \brief The global module index, if loaded.
319 llvm::OwningPtr<GlobalModuleIndex> GlobalIndex;
321 /// \brief A map of global bit offsets to the module that stores entities
322 /// at those bit offsets.
323 ContinuousRangeMap<uint64_t, ModuleFile*, 4> GlobalBitOffsetsMap;
325 /// \brief A map of negated SLocEntryIDs to the modules containing them.
326 ContinuousRangeMap<unsigned, ModuleFile*, 64> GlobalSLocEntryMap;
328 typedef ContinuousRangeMap<unsigned, ModuleFile*, 64> GlobalSLocOffsetMapType;
330 /// \brief A map of reversed (SourceManager::MaxLoadedOffset - SLocOffset)
331 /// SourceLocation offsets to the modules containing them.
332 GlobalSLocOffsetMapType GlobalSLocOffsetMap;
334 /// \brief Types that have already been loaded from the chain.
336 /// When the pointer at index I is non-NULL, the type with
337 /// ID = (I + 1) << FastQual::Width has already been loaded
338 std::vector<QualType> TypesLoaded;
340 typedef ContinuousRangeMap<serialization::TypeID, ModuleFile *, 4>
343 /// \brief Mapping from global type IDs to the module in which the
344 /// type resides along with the offset that should be added to the
345 /// global type ID to produce a local ID.
346 GlobalTypeMapType GlobalTypeMap;
348 /// \brief Declarations that have already been loaded from the chain.
350 /// When the pointer at index I is non-NULL, the declaration with ID
351 /// = I + 1 has already been loaded.
352 std::vector<Decl *> DeclsLoaded;
354 typedef ContinuousRangeMap<serialization::DeclID, ModuleFile *, 4>
357 /// \brief Mapping from global declaration IDs to the module in which the
358 /// declaration resides.
359 GlobalDeclMapType GlobalDeclMap;
361 typedef std::pair<ModuleFile *, uint64_t> FileOffset;
362 typedef SmallVector<FileOffset, 2> FileOffsetsTy;
363 typedef llvm::DenseMap<serialization::DeclID, FileOffsetsTy>
364 DeclUpdateOffsetsMap;
366 /// \brief Declarations that have modifications residing in a later file
368 DeclUpdateOffsetsMap DeclUpdateOffsets;
370 struct ReplacedDeclInfo {
375 ReplacedDeclInfo() : Mod(0), Offset(0), RawLoc(0) {}
376 ReplacedDeclInfo(ModuleFile *Mod, uint64_t Offset, unsigned RawLoc)
377 : Mod(Mod), Offset(Offset), RawLoc(RawLoc) {}
380 typedef llvm::DenseMap<serialization::DeclID, ReplacedDeclInfo>
382 /// \brief Declarations that have been replaced in a later file in the chain.
383 DeclReplacementMap ReplacedDecls;
385 struct FileDeclsInfo {
387 ArrayRef<serialization::LocalDeclID> Decls;
389 FileDeclsInfo() : Mod(0) {}
390 FileDeclsInfo(ModuleFile *Mod, ArrayRef<serialization::LocalDeclID> Decls)
391 : Mod(Mod), Decls(Decls) {}
394 /// \brief Map from a FileID to the file-level declarations that it contains.
395 llvm::DenseMap<FileID, FileDeclsInfo> FileDeclIDs;
397 // Updates for visible decls can occur for other contexts than just the
398 // TU, and when we read those update records, the actual context will not
399 // be available yet (unless it's the TU), so have this pending map using the
400 // ID as a key. It will be realized when the context is actually loaded.
402 SmallVector<std::pair<serialization::reader::ASTDeclContextNameLookupTable *,
403 ModuleFile*>, 1> DeclContextVisibleUpdates;
404 typedef llvm::DenseMap<serialization::DeclID, DeclContextVisibleUpdates>
405 DeclContextVisibleUpdatesPending;
407 /// \brief Updates to the visible declarations of declaration contexts that
408 /// haven't been loaded yet.
409 DeclContextVisibleUpdatesPending PendingVisibleUpdates;
411 /// \brief The set of C++ or Objective-C classes that have forward
412 /// declarations that have not yet been linked to their definitions.
413 llvm::SmallPtrSet<Decl *, 4> PendingDefinitions;
415 typedef llvm::MapVector<Decl *, uint64_t,
416 llvm::SmallDenseMap<Decl *, unsigned, 4>,
417 SmallVector<std::pair<Decl *, uint64_t>, 4> >
420 /// \brief Functions or methods that have bodies that will be attached.
421 PendingBodiesMap PendingBodies;
423 /// \brief Read the records that describe the contents of declcontexts.
424 bool ReadDeclContextStorage(ModuleFile &M,
425 llvm::BitstreamCursor &Cursor,
426 const std::pair<uint64_t, uint64_t> &Offsets,
427 serialization::DeclContextInfo &Info);
429 /// \brief A vector containing identifiers that have already been
432 /// If the pointer at index I is non-NULL, then it refers to the
433 /// IdentifierInfo for the identifier with ID=I+1 that has already
435 std::vector<IdentifierInfo *> IdentifiersLoaded;
437 typedef ContinuousRangeMap<serialization::IdentID, ModuleFile *, 4>
438 GlobalIdentifierMapType;
440 /// \brief Mapping from global identifier IDs to the module in which the
441 /// identifier resides along with the offset that should be added to the
442 /// global identifier ID to produce a local ID.
443 GlobalIdentifierMapType GlobalIdentifierMap;
445 /// \brief A vector containing macros that have already been
448 /// If the pointer at index I is non-NULL, then it refers to the
449 /// MacroInfo for the identifier with ID=I+1 that has already
451 std::vector<MacroInfo *> MacrosLoaded;
453 typedef ContinuousRangeMap<serialization::MacroID, ModuleFile *, 4>
456 /// \brief Mapping from global macro IDs to the module in which the
457 /// macro resides along with the offset that should be added to the
458 /// global macro ID to produce a local ID.
459 GlobalMacroMapType GlobalMacroMap;
461 /// \brief A vector containing submodules that have already been loaded.
463 /// This vector is indexed by the Submodule ID (-1). NULL submodule entries
464 /// indicate that the particular submodule ID has not yet been loaded.
465 SmallVector<Module *, 2> SubmodulesLoaded;
467 typedef ContinuousRangeMap<serialization::SubmoduleID, ModuleFile *, 4>
468 GlobalSubmoduleMapType;
470 /// \brief Mapping from global submodule IDs to the module file in which the
471 /// submodule resides along with the offset that should be added to the
472 /// global submodule ID to produce a local ID.
473 GlobalSubmoduleMapType GlobalSubmoduleMap;
475 /// \brief An entity that has been hidden.
492 HiddenName(Decl *D) : Kind(Declaration), D(D), Id() { }
494 HiddenName(IdentifierInfo *II, MacroDirective *MD)
495 : Kind(MacroVisibility), MD(MD), Id(II) { }
497 NameKind getKind() const { return Kind; }
499 Decl *getDecl() const {
500 assert(getKind() == Declaration && "Hidden name is not a declaration");
504 std::pair<IdentifierInfo *, MacroDirective *> getMacro() const {
505 assert(getKind() == MacroVisibility && "Hidden name is not a macro!");
506 return std::make_pair(Id, MD);
510 /// \brief A set of hidden declarations.
511 typedef SmallVector<HiddenName, 2> HiddenNames;
513 typedef llvm::DenseMap<Module *, HiddenNames> HiddenNamesMapType;
515 /// \brief A mapping from each of the hidden submodules to the deserialized
516 /// declarations in that submodule that could be made visible.
517 HiddenNamesMapType HiddenNamesMap;
520 /// \brief A module import, export, or conflict that hasn't yet been resolved.
521 struct UnresolvedModuleRef {
522 /// \brief The file in which this module resides.
525 /// \brief The module that is importing or exporting.
528 /// \brief The kind of module reference.
529 enum { Import, Export, Conflict } Kind;
531 /// \brief The local ID of the module that is being exported.
534 /// \brief Whether this is a wildcard export.
535 unsigned IsWildcard : 1;
537 /// \brief String data.
541 /// \brief The set of module imports and exports that still need to be
543 SmallVector<UnresolvedModuleRef, 2> UnresolvedModuleRefs;
545 /// \brief A vector containing selectors that have already been loaded.
547 /// This vector is indexed by the Selector ID (-1). NULL selector
548 /// entries indicate that the particular selector ID has not yet
550 SmallVector<Selector, 16> SelectorsLoaded;
552 typedef ContinuousRangeMap<serialization::SelectorID, ModuleFile *, 4>
553 GlobalSelectorMapType;
555 /// \brief Mapping from global selector IDs to the module in which the
557 /// global selector ID to produce a local ID.
558 GlobalSelectorMapType GlobalSelectorMap;
560 /// \brief The generation number of the last time we loaded data from the
561 /// global method pool for this selector.
562 llvm::DenseMap<Selector, unsigned> SelectorGeneration;
564 struct PendingMacroInfo {
567 struct ModuleMacroDataTy {
568 serialization::GlobalMacroID GMacID;
571 struct PCHMacroDataTy {
572 uint64_t MacroDirectivesOffset;
576 ModuleMacroDataTy ModuleMacroData;
577 PCHMacroDataTy PCHMacroData;
580 PendingMacroInfo(ModuleFile *M,
581 serialization::GlobalMacroID GMacID,
582 SourceLocation ImportLoc) : M(M) {
583 ModuleMacroData.GMacID = GMacID;
584 ModuleMacroData.ImportLoc = ImportLoc.getRawEncoding();
587 PendingMacroInfo(ModuleFile *M, uint64_t MacroDirectivesOffset) : M(M) {
588 PCHMacroData.MacroDirectivesOffset = MacroDirectivesOffset;
592 typedef llvm::MapVector<IdentifierInfo *, SmallVector<PendingMacroInfo, 2> >
595 /// \brief Mapping from identifiers that have a macro history to the global
596 /// IDs have not yet been deserialized to the global IDs of those macros.
597 PendingMacroIDsMap PendingMacroIDs;
599 typedef ContinuousRangeMap<unsigned, ModuleFile *, 4>
600 GlobalPreprocessedEntityMapType;
602 /// \brief Mapping from global preprocessing entity IDs to the module in
603 /// which the preprocessed entity resides along with the offset that should be
604 /// added to the global preprocessing entitiy ID to produce a local ID.
605 GlobalPreprocessedEntityMapType GlobalPreprocessedEntityMap;
607 /// \name CodeGen-relevant special data
608 /// \brief Fields containing data that is relevant to CodeGen.
611 /// \brief The IDs of all declarations that fulfill the criteria of
612 /// "interesting" decls.
614 /// This contains the data loaded from all EXTERNAL_DEFINITIONS blocks in the
615 /// chain. The referenced declarations are deserialized and passed to the
616 /// consumer eagerly.
617 SmallVector<uint64_t, 16> ExternalDefinitions;
619 /// \brief The IDs of all tentative definitions stored in the chain.
621 /// Sema keeps track of all tentative definitions in a TU because it has to
622 /// complete them and pass them on to CodeGen. Thus, tentative definitions in
623 /// the PCH chain must be eagerly deserialized.
624 SmallVector<uint64_t, 16> TentativeDefinitions;
626 /// \brief The IDs of all CXXRecordDecls stored in the chain whose VTables are
629 /// CodeGen has to emit VTables for these records, so they have to be eagerly
631 SmallVector<uint64_t, 64> VTableUses;
633 /// \brief A snapshot of the pending instantiations in the chain.
635 /// This record tracks the instantiations that Sema has to perform at the
636 /// end of the TU. It consists of a pair of values for every pending
637 /// instantiation where the first value is the ID of the decl and the second
638 /// is the instantiation location.
639 SmallVector<uint64_t, 64> PendingInstantiations;
643 /// \name DiagnosticsEngine-relevant special data
644 /// \brief Fields containing data that is used for generating diagnostics
647 /// \brief A snapshot of Sema's unused file-scoped variable tracking, for
648 /// generating warnings.
649 SmallVector<uint64_t, 16> UnusedFileScopedDecls;
651 /// \brief A list of all the delegating constructors we've seen, to diagnose
653 SmallVector<uint64_t, 4> DelegatingCtorDecls;
655 /// \brief Method selectors used in a @selector expression. Used for
656 /// implementation of -Wselector.
657 SmallVector<uint64_t, 64> ReferencedSelectorsData;
659 /// \brief A snapshot of Sema's weak undeclared identifier tracking, for
660 /// generating warnings.
661 SmallVector<uint64_t, 64> WeakUndeclaredIdentifiers;
663 /// \brief The IDs of type aliases for ext_vectors that exist in the chain.
665 /// Used by Sema for finding sugared names for ext_vectors in diagnostics.
666 SmallVector<uint64_t, 4> ExtVectorDecls;
670 /// \name Sema-relevant special data
671 /// \brief Fields containing data that is used for semantic analysis
674 /// \brief The IDs of all locally scoped extern "C" decls in the chain.
676 /// Sema tracks these to validate that the types are consistent across all
677 /// local extern "C" declarations.
678 SmallVector<uint64_t, 16> LocallyScopedExternCDecls;
680 /// \brief The IDs of all dynamic class declarations in the chain.
682 /// Sema tracks these because it checks for the key functions being defined
683 /// at the end of the TU, in which case it directs CodeGen to emit the VTable.
684 SmallVector<uint64_t, 16> DynamicClasses;
686 /// \brief The IDs of the declarations Sema stores directly.
688 /// Sema tracks a few important decls, such as namespace std, directly.
689 SmallVector<uint64_t, 4> SemaDeclRefs;
691 /// \brief The IDs of the types ASTContext stores directly.
693 /// The AST context tracks a few important types, such as va_list, directly.
694 SmallVector<uint64_t, 16> SpecialTypes;
696 /// \brief The IDs of CUDA-specific declarations ASTContext stores directly.
698 /// The AST context tracks a few important decls, currently cudaConfigureCall,
700 SmallVector<uint64_t, 2> CUDASpecialDeclRefs;
702 /// \brief The floating point pragma option settings.
703 SmallVector<uint64_t, 1> FPPragmaOptions;
705 /// \brief The OpenCL extension settings.
706 SmallVector<uint64_t, 1> OpenCLExtensions;
708 /// \brief A list of the namespaces we've seen.
709 SmallVector<uint64_t, 4> KnownNamespaces;
711 /// \brief A list of undefined decls with internal linkage followed by the
712 /// SourceLocation of a matching ODR-use.
713 SmallVector<uint64_t, 8> UndefinedButUsed;
715 /// \brief A list of modules that were imported by precompiled headers or
716 /// any other non-module AST file.
717 SmallVector<serialization::SubmoduleID, 2> ImportedModules;
720 /// \brief The directory that the PCH we are reading is stored in.
721 std::string CurrentDir;
723 /// \brief The system include root to be used when loading the
724 /// precompiled header.
725 std::string isysroot;
727 /// \brief Whether to disable the normal validation performed on precompiled
728 /// headers when they are loaded.
729 bool DisableValidation;
731 /// \brief Whether to accept an AST file with compiler errors.
732 bool AllowASTWithCompilerErrors;
734 /// \brief Whether we are allowed to use the global module index.
737 /// \brief Whether we have tried loading the global module index yet.
738 bool TriedLoadingGlobalIndex;
740 /// \brief The current "generation" of the module file import stack, which
741 /// indicates how many separate module file load operations have occurred.
742 unsigned CurrentGeneration;
744 typedef llvm::DenseMap<unsigned, SwitchCase *> SwitchCaseMapTy;
745 /// \brief Mapping from switch-case IDs in the chain to switch-case statements
747 /// Statements usually don't have IDs, but switch cases need them, so that the
748 /// switch statement can refer to them.
749 SwitchCaseMapTy SwitchCaseStmts;
751 SwitchCaseMapTy *CurrSwitchCaseStmts;
753 /// \brief The number of source location entries de-serialized from
755 unsigned NumSLocEntriesRead;
757 /// \brief The number of source location entries in the chain.
758 unsigned TotalNumSLocEntries;
760 /// \brief The number of statements (and expressions) de-serialized
762 unsigned NumStatementsRead;
764 /// \brief The total number of statements (and expressions) stored
766 unsigned TotalNumStatements;
768 /// \brief The number of macros de-serialized from the chain.
769 unsigned NumMacrosRead;
771 /// \brief The total number of macros stored in the chain.
772 unsigned TotalNumMacros;
774 /// \brief The number of lookups into identifier tables.
775 unsigned NumIdentifierLookups;
777 /// \brief The number of lookups into identifier tables that succeed.
778 unsigned NumIdentifierLookupHits;
780 /// \brief The number of selectors that have been read.
781 unsigned NumSelectorsRead;
783 /// \brief The number of method pool entries that have been read.
784 unsigned NumMethodPoolEntriesRead;
786 /// \brief The number of times we have looked up a selector in the method
788 unsigned NumMethodPoolLookups;
790 /// \brief The number of times we have looked up a selector in the method
791 /// pool and found something.
792 unsigned NumMethodPoolHits;
794 /// \brief The number of times we have looked up a selector in the method
795 /// pool within a specific module.
796 unsigned NumMethodPoolTableLookups;
798 /// \brief The number of times we have looked up a selector in the method
799 /// pool within a specific module and found something.
800 unsigned NumMethodPoolTableHits;
802 /// \brief The total number of method pool entries in the selector table.
803 unsigned TotalNumMethodPoolEntries;
805 /// Number of lexical decl contexts read/total.
806 unsigned NumLexicalDeclContextsRead, TotalLexicalDeclContexts;
808 /// Number of visible decl contexts read/total.
809 unsigned NumVisibleDeclContextsRead, TotalVisibleDeclContexts;
811 /// Total size of modules, in bits, currently loaded
812 uint64_t TotalModulesSizeInBits;
814 /// \brief Number of Decl/types that are currently deserializing.
815 unsigned NumCurrentElementsDeserializing;
817 /// \brief Set true while we are in the process of passing deserialized
818 /// "interesting" decls to consumer inside FinishedDeserializing().
819 /// This is used as a guard to avoid recursively repeating the process of
820 /// passing decls to consumer.
821 bool PassingDeclsToConsumer;
823 /// Number of CXX base specifiers currently loaded
824 unsigned NumCXXBaseSpecifiersLoaded;
826 /// \brief The set of identifiers that were read while the AST reader was
827 /// (recursively) loading declarations.
829 /// The declarations on the identifier chain for these identifiers will be
830 /// loaded once the recursive loading has completed.
831 llvm::MapVector<IdentifierInfo *, SmallVector<uint32_t, 4> >
832 PendingIdentifierInfos;
834 /// \brief The generation number of each identifier, which keeps track of
835 /// the last time we loaded information about this identifier.
836 llvm::DenseMap<IdentifierInfo *, unsigned> IdentifierGeneration;
838 /// \brief Contains declarations and definitions that will be
839 /// "interesting" to the ASTConsumer, when we get that AST consumer.
841 /// "Interesting" declarations are those that have data that may
842 /// need to be emitted, such as inline function definitions or
843 /// Objective-C protocols.
844 std::deque<Decl *> InterestingDecls;
846 /// \brief The set of redeclarable declarations that have been deserialized
847 /// since the last time the declaration chains were linked.
848 llvm::SmallPtrSet<Decl *, 16> RedeclsDeserialized;
850 /// \brief The list of redeclaration chains that still need to be
853 /// Each element is the global declaration ID of the first declaration in
854 /// the chain. Elements in this vector should be unique; use
855 /// PendingDeclChainsKnown to ensure uniqueness.
856 SmallVector<serialization::DeclID, 16> PendingDeclChains;
858 /// \brief Keeps track of the elements added to PendingDeclChains.
859 llvm::SmallSet<serialization::DeclID, 16> PendingDeclChainsKnown;
861 /// \brief The Decl IDs for the Sema/Lexical DeclContext of a Decl that has
862 /// been loaded but its DeclContext was not set yet.
863 struct PendingDeclContextInfo {
865 serialization::GlobalDeclID SemaDC;
866 serialization::GlobalDeclID LexicalDC;
869 /// \brief The set of Decls that have been loaded but their DeclContexts are
872 /// The DeclContexts for these Decls will be set once recursive loading has
874 std::deque<PendingDeclContextInfo> PendingDeclContextInfos;
876 /// \brief The set of Objective-C categories that have been deserialized
877 /// since the last time the declaration chains were linked.
878 llvm::SmallPtrSet<ObjCCategoryDecl *, 16> CategoriesDeserialized;
880 /// \brief The set of Objective-C class definitions that have already been
881 /// loaded, for which we will need to check for categories whenever a new
882 /// module is loaded.
883 SmallVector<ObjCInterfaceDecl *, 16> ObjCClassesLoaded;
885 typedef llvm::DenseMap<Decl *, SmallVector<serialization::DeclID, 2> >
888 /// \brief A mapping from canonical declarations to the set of additional
889 /// (global, previously-canonical) declaration IDs that have been merged with
890 /// that canonical declaration.
891 MergedDeclsMap MergedDecls;
893 typedef llvm::DenseMap<serialization::GlobalDeclID,
894 SmallVector<serialization::DeclID, 2> >
895 StoredMergedDeclsMap;
897 /// \brief A mapping from canonical declaration IDs to the set of additional
898 /// declaration IDs that have been merged with that canonical declaration.
900 /// This is the deserialized representation of the entries in MergedDecls.
901 /// When we query entries in MergedDecls, they will be augmented with entries
902 /// from StoredMergedDecls.
903 StoredMergedDeclsMap StoredMergedDecls;
905 /// \brief Combine the stored merged declarations for the given canonical
906 /// declaration into the set of merged declarations.
908 /// \returns An iterator into MergedDecls that corresponds to the position of
909 /// the given canonical declaration.
910 MergedDeclsMap::iterator
911 combineStoredMergedDecls(Decl *Canon, serialization::GlobalDeclID CanonID);
913 /// \brief Ready to load the previous declaration of the given Decl.
914 void loadAndAttachPreviousDecl(Decl *D, serialization::DeclID ID);
916 /// \brief When reading a Stmt tree, Stmt operands are placed in this stack.
917 SmallVector<Stmt *, 16> StmtStack;
919 /// \brief What kind of records we are reading.
921 Read_Decl, Read_Type, Read_Stmt
924 /// \brief What kind of records we are reading.
925 ReadingKind ReadingKind;
927 /// \brief RAII object to change the reading kind.
928 class ReadingKindTracker {
930 enum ReadingKind PrevKind;
932 ReadingKindTracker(const ReadingKindTracker &) LLVM_DELETED_FUNCTION;
933 void operator=(const ReadingKindTracker &) LLVM_DELETED_FUNCTION;
936 ReadingKindTracker(enum ReadingKind newKind, ASTReader &reader)
937 : Reader(reader), PrevKind(Reader.ReadingKind) {
938 Reader.ReadingKind = newKind;
941 ~ReadingKindTracker() { Reader.ReadingKind = PrevKind; }
944 /// \brief Suggested contents of the predefines buffer, after this
945 /// PCH file has been processed.
947 /// In most cases, this string will be empty, because the predefines
948 /// buffer computed to build the PCH file will be identical to the
949 /// predefines buffer computed from the command line. However, when
950 /// there are differences that the PCH reader can work around, this
951 /// predefines buffer may contain additional definitions.
952 std::string SuggestedPredefines;
954 /// \brief Reads a statement from the specified cursor.
955 Stmt *ReadStmtFromStream(ModuleFile &F);
957 /// \brief Retrieve the file entry and 'overridden' bit for an input
958 /// file in the given module file.
959 serialization::InputFile getInputFile(ModuleFile &F, unsigned ID,
960 bool Complain = true);
962 /// \brief Get a FileEntry out of stored-in-PCH filename, making sure we take
963 /// into account all the necessary relocations.
964 const FileEntry *getFileEntry(StringRef filename);
966 void MaybeAddSystemRootToFilename(ModuleFile &M, std::string &Filename);
968 struct ImportedModule {
970 ModuleFile *ImportedBy;
971 SourceLocation ImportLoc;
973 ImportedModule(ModuleFile *Mod,
974 ModuleFile *ImportedBy,
975 SourceLocation ImportLoc)
976 : Mod(Mod), ImportedBy(ImportedBy), ImportLoc(ImportLoc) { }
979 ASTReadResult ReadASTCore(StringRef FileName, ModuleKind Type,
980 SourceLocation ImportLoc, ModuleFile *ImportedBy,
981 SmallVectorImpl<ImportedModule> &Loaded,
982 off_t ExpectedSize, time_t ExpectedModTime,
983 unsigned ClientLoadCapabilities);
984 ASTReadResult ReadControlBlock(ModuleFile &F,
985 SmallVectorImpl<ImportedModule> &Loaded,
986 unsigned ClientLoadCapabilities);
987 bool ReadASTBlock(ModuleFile &F);
988 bool ParseLineTable(ModuleFile &F, SmallVectorImpl<uint64_t> &Record);
989 bool ReadSourceManagerBlock(ModuleFile &F);
990 llvm::BitstreamCursor &SLocCursorForID(int ID);
991 SourceLocation getImportLocation(ModuleFile *F);
992 bool ReadSubmoduleBlock(ModuleFile &F);
993 static bool ParseLanguageOptions(const RecordData &Record, bool Complain,
994 ASTReaderListener &Listener);
995 static bool ParseTargetOptions(const RecordData &Record, bool Complain,
996 ASTReaderListener &Listener);
997 static bool ParseDiagnosticOptions(const RecordData &Record, bool Complain,
998 ASTReaderListener &Listener);
999 static bool ParseFileSystemOptions(const RecordData &Record, bool Complain,
1000 ASTReaderListener &Listener);
1001 static bool ParseHeaderSearchOptions(const RecordData &Record, bool Complain,
1002 ASTReaderListener &Listener);
1003 static bool ParsePreprocessorOptions(const RecordData &Record, bool Complain,
1004 ASTReaderListener &Listener,
1005 std::string &SuggestedPredefines);
1007 struct RecordLocation {
1008 RecordLocation(ModuleFile *M, uint64_t O)
1009 : F(M), Offset(O) {}
1014 QualType readTypeRecord(unsigned Index);
1015 RecordLocation TypeCursorForIndex(unsigned Index);
1016 void LoadedDecl(unsigned Index, Decl *D);
1017 Decl *ReadDeclRecord(serialization::DeclID ID);
1018 RecordLocation DeclCursorForID(serialization::DeclID ID,
1019 unsigned &RawLocation);
1020 void loadDeclUpdateRecords(serialization::DeclID ID, Decl *D);
1021 void loadPendingDeclChain(serialization::GlobalDeclID ID);
1022 void loadObjCCategories(serialization::GlobalDeclID ID, ObjCInterfaceDecl *D,
1023 unsigned PreviousGeneration = 0);
1025 RecordLocation getLocalBitOffset(uint64_t GlobalOffset);
1026 uint64_t getGlobalBitOffset(ModuleFile &M, uint32_t LocalOffset);
1028 /// \brief Returns the first preprocessed entity ID that ends after BLoc.
1029 serialization::PreprocessedEntityID
1030 findBeginPreprocessedEntity(SourceLocation BLoc) const;
1032 /// \brief Returns the first preprocessed entity ID that begins after ELoc.
1033 serialization::PreprocessedEntityID
1034 findEndPreprocessedEntity(SourceLocation ELoc) const;
1036 /// \brief Find the next module that contains entities and return the ID
1037 /// of the first entry.
1039 /// \param SLocMapI points at a chunk of a module that contains no
1040 /// preprocessed entities or the entities it contains are not the
1041 /// ones we are looking for.
1042 serialization::PreprocessedEntityID
1043 findNextPreprocessedEntity(
1044 GlobalSLocOffsetMapType::const_iterator SLocMapI) const;
1046 /// \brief Returns (ModuleFile, Local index) pair for \p GlobalIndex of a
1047 /// preprocessed entity.
1048 std::pair<ModuleFile *, unsigned>
1049 getModulePreprocessedEntity(unsigned GlobalIndex);
1051 /// \brief Returns (begin, end) pair for the preprocessed entities of a
1052 /// particular module.
1053 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
1054 getModulePreprocessedEntities(ModuleFile &Mod) const;
1056 class ModuleDeclIterator {
1059 const serialization::LocalDeclID *Pos;
1062 typedef const Decl *value_type;
1063 typedef value_type& reference;
1064 typedef value_type* pointer;
1066 ModuleDeclIterator() : Reader(0), Mod(0), Pos(0) { }
1068 ModuleDeclIterator(ASTReader *Reader, ModuleFile *Mod,
1069 const serialization::LocalDeclID *Pos)
1070 : Reader(Reader), Mod(Mod), Pos(Pos) { }
1072 value_type operator*() const {
1073 return Reader->GetDecl(Reader->getGlobalDeclID(*Mod, *Pos));
1076 ModuleDeclIterator &operator++() {
1081 ModuleDeclIterator operator++(int) {
1082 ModuleDeclIterator Prev(*this);
1087 ModuleDeclIterator &operator--() {
1092 ModuleDeclIterator operator--(int) {
1093 ModuleDeclIterator Prev(*this);
1098 friend bool operator==(const ModuleDeclIterator &LHS,
1099 const ModuleDeclIterator &RHS) {
1100 assert(LHS.Reader == RHS.Reader && LHS.Mod == RHS.Mod);
1101 return LHS.Pos == RHS.Pos;
1104 friend bool operator!=(const ModuleDeclIterator &LHS,
1105 const ModuleDeclIterator &RHS) {
1106 assert(LHS.Reader == RHS.Reader && LHS.Mod == RHS.Mod);
1107 return LHS.Pos != RHS.Pos;
1111 std::pair<ModuleDeclIterator, ModuleDeclIterator>
1112 getModuleFileLevelDecls(ModuleFile &Mod);
1114 void PassInterestingDeclsToConsumer();
1115 void PassInterestingDeclToConsumer(Decl *D);
1117 void finishPendingActions();
1119 void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name);
1121 void addPendingDeclContextInfo(Decl *D,
1122 serialization::GlobalDeclID SemaDC,
1123 serialization::GlobalDeclID LexicalDC) {
1125 PendingDeclContextInfo Info = { D, SemaDC, LexicalDC };
1126 PendingDeclContextInfos.push_back(Info);
1129 /// \brief Produce an error diagnostic and return true.
1131 /// This routine should only be used for fatal errors that have to
1132 /// do with non-routine failures (e.g., corrupted AST file).
1133 void Error(StringRef Msg);
1134 void Error(unsigned DiagID, StringRef Arg1 = StringRef(),
1135 StringRef Arg2 = StringRef());
1137 ASTReader(const ASTReader &) LLVM_DELETED_FUNCTION;
1138 void operator=(const ASTReader &) LLVM_DELETED_FUNCTION;
1140 /// \brief Load the AST file and validate its contents against the given
1143 /// \param PP the preprocessor associated with the context in which this
1144 /// precompiled header will be loaded.
1146 /// \param Context the AST context that this precompiled header will be
1149 /// \param isysroot If non-NULL, the system include path specified by the
1150 /// user. This is only used with relocatable PCH files. If non-NULL,
1151 /// a relocatable PCH file will use the default path "/".
1153 /// \param DisableValidation If true, the AST reader will suppress most
1154 /// of its regular consistency checking, allowing the use of precompiled
1155 /// headers that cannot be determined to be compatible.
1157 /// \param AllowASTWithCompilerErrors If true, the AST reader will accept an
1158 /// AST file the was created out of an AST with compiler errors,
1159 /// otherwise it will reject it.
1161 /// \param UseGlobalIndex If true, the AST reader will try to load and use
1162 /// the global module index.
1163 ASTReader(Preprocessor &PP, ASTContext &Context, StringRef isysroot = "",
1164 bool DisableValidation = false,
1165 bool AllowASTWithCompilerErrors = false,
1166 bool UseGlobalIndex = true);
1170 SourceManager &getSourceManager() const { return SourceMgr; }
1171 FileManager &getFileManager() const { return FileMgr; }
1173 /// \brief Flags that indicate what kind of AST loading failures the client
1174 /// of the AST reader can directly handle.
1176 /// When a client states that it can handle a particular kind of failure,
1177 /// the AST reader will not emit errors when producing that kind of failure.
1178 enum LoadFailureCapabilities {
1179 /// \brief The client can't handle any AST loading failures.
1181 /// \brief The client can handle an AST file that cannot load because it
1184 /// \brief The client can handle an AST file that cannot load because it
1185 /// is out-of-date relative to its input files.
1186 ARR_OutOfDate = 0x2,
1187 /// \brief The client can handle an AST file that cannot load because it
1188 /// was built with a different version of Clang.
1189 ARR_VersionMismatch = 0x4,
1190 /// \brief The client can handle an AST file that cannot load because it's
1191 /// compiled configuration doesn't match that of the context it was
1193 ARR_ConfigurationMismatch = 0x8
1196 /// \brief Load the AST file designated by the given file name.
1198 /// \param FileName The name of the AST file to load.
1200 /// \param Type The kind of AST being loaded, e.g., PCH, module, main file,
1203 /// \param ImportLoc the location where the module file will be considered as
1204 /// imported from. For non-module AST types it should be invalid.
1206 /// \param ClientLoadCapabilities The set of client load-failure
1207 /// capabilities, represented as a bitset of the enumerators of
1208 /// LoadFailureCapabilities.
1209 ASTReadResult ReadAST(const std::string &FileName, ModuleKind Type,
1210 SourceLocation ImportLoc,
1211 unsigned ClientLoadCapabilities);
1213 /// \brief Make the entities in the given module and any of its (non-explicit)
1214 /// submodules visible to name lookup.
1216 /// \param Mod The module whose names should be made visible.
1218 /// \param NameVisibility The level of visibility to give the names in the
1219 /// module. Visibility can only be increased over time.
1221 /// \param ImportLoc The location at which the import occurs.
1223 /// \param Complain Whether to complain about conflicting module imports.
1224 void makeModuleVisible(Module *Mod,
1225 Module::NameVisibilityKind NameVisibility,
1226 SourceLocation ImportLoc,
1229 /// \brief Make the names within this set of hidden names visible.
1230 void makeNamesVisible(const HiddenNames &Names, Module *Owner);
1232 /// \brief Set the AST callbacks listener.
1233 void setListener(ASTReaderListener *listener) {
1234 Listener.reset(listener);
1237 /// \brief Set the AST deserialization listener.
1238 void setDeserializationListener(ASTDeserializationListener *Listener);
1240 /// \brief Determine whether this AST reader has a global index.
1241 bool hasGlobalIndex() const { return GlobalIndex; }
1243 /// \brief Attempts to load the global index.
1245 /// \returns true if loading the global index has failed for any reason.
1246 bool loadGlobalIndex();
1248 /// \brief Determine whether we tried to load the global index, but failed,
1249 /// e.g., because it is out-of-date or does not exist.
1250 bool isGlobalIndexUnavailable() const;
1252 /// \brief Initializes the ASTContext
1253 void InitializeContext();
1255 /// \brief Add in-memory (virtual file) buffer.
1256 void addInMemoryBuffer(StringRef &FileName, llvm::MemoryBuffer *Buffer) {
1257 ModuleMgr.addInMemoryBuffer(FileName, Buffer);
1260 /// \brief Finalizes the AST reader's state before writing an AST file to
1263 /// This operation may undo temporary state in the AST that should not be
1265 void finalizeForWriting();
1267 /// \brief Retrieve the module manager.
1268 ModuleManager &getModuleManager() { return ModuleMgr; }
1270 /// \brief Retrieve the preprocessor.
1271 Preprocessor &getPreprocessor() const { return PP; }
1273 /// \brief Retrieve the name of the original source file name for the primary
1275 StringRef getOriginalSourceFile() {
1276 return ModuleMgr.getPrimaryModule().OriginalSourceFileName;
1279 /// \brief Retrieve the name of the original source file name directly from
1280 /// the AST file, without actually loading the AST file.
1281 static std::string getOriginalSourceFile(const std::string &ASTFileName,
1282 FileManager &FileMgr,
1283 DiagnosticsEngine &Diags);
1285 /// \brief Read the control block for the named AST file.
1287 /// \returns true if an error occurred, false otherwise.
1288 static bool readASTFileControlBlock(StringRef Filename,
1289 FileManager &FileMgr,
1290 ASTReaderListener &Listener);
1292 /// \brief Determine whether the given AST file is acceptable to load into a
1293 /// translation unit with the given language and target options.
1294 static bool isAcceptableASTFile(StringRef Filename,
1295 FileManager &FileMgr,
1296 const LangOptions &LangOpts,
1297 const TargetOptions &TargetOpts,
1298 const PreprocessorOptions &PPOpts);
1300 /// \brief Returns the suggested contents of the predefines buffer,
1301 /// which contains a (typically-empty) subset of the predefines
1302 /// build prior to including the precompiled header.
1303 const std::string &getSuggestedPredefines() { return SuggestedPredefines; }
1305 /// \brief Read a preallocated preprocessed entity from the external source.
1307 /// \returns null if an error occurred that prevented the preprocessed
1308 /// entity from being loaded.
1309 virtual PreprocessedEntity *ReadPreprocessedEntity(unsigned Index);
1311 /// \brief Returns a pair of [Begin, End) indices of preallocated
1312 /// preprocessed entities that \p Range encompasses.
1313 virtual std::pair<unsigned, unsigned>
1314 findPreprocessedEntitiesInRange(SourceRange Range);
1316 /// \brief Optionally returns true or false if the preallocated preprocessed
1317 /// entity with index \p Index came from file \p FID.
1318 virtual Optional<bool> isPreprocessedEntityInFileID(unsigned Index,
1321 /// \brief Read the header file information for the given file entry.
1322 virtual HeaderFileInfo GetHeaderFileInfo(const FileEntry *FE);
1324 void ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag);
1326 /// \brief Returns the number of source locations found in the chain.
1327 unsigned getTotalNumSLocs() const {
1328 return TotalNumSLocEntries;
1331 /// \brief Returns the number of identifiers found in the chain.
1332 unsigned getTotalNumIdentifiers() const {
1333 return static_cast<unsigned>(IdentifiersLoaded.size());
1336 /// \brief Returns the number of macros found in the chain.
1337 unsigned getTotalNumMacros() const {
1338 return static_cast<unsigned>(MacrosLoaded.size());
1341 /// \brief Returns the number of types found in the chain.
1342 unsigned getTotalNumTypes() const {
1343 return static_cast<unsigned>(TypesLoaded.size());
1346 /// \brief Returns the number of declarations found in the chain.
1347 unsigned getTotalNumDecls() const {
1348 return static_cast<unsigned>(DeclsLoaded.size());
1351 /// \brief Returns the number of submodules known.
1352 unsigned getTotalNumSubmodules() const {
1353 return static_cast<unsigned>(SubmodulesLoaded.size());
1356 /// \brief Returns the number of selectors found in the chain.
1357 unsigned getTotalNumSelectors() const {
1358 return static_cast<unsigned>(SelectorsLoaded.size());
1361 /// \brief Returns the number of preprocessed entities known to the AST
1363 unsigned getTotalNumPreprocessedEntities() const {
1364 unsigned Result = 0;
1365 for (ModuleConstIterator I = ModuleMgr.begin(),
1366 E = ModuleMgr.end(); I != E; ++I) {
1367 Result += (*I)->NumPreprocessedEntities;
1373 /// \brief Returns the number of C++ base specifiers found in the chain.
1374 unsigned getTotalNumCXXBaseSpecifiers() const {
1375 return NumCXXBaseSpecifiersLoaded;
1378 /// \brief Reads a TemplateArgumentLocInfo appropriate for the
1379 /// given TemplateArgument kind.
1380 TemplateArgumentLocInfo
1381 GetTemplateArgumentLocInfo(ModuleFile &F, TemplateArgument::ArgKind Kind,
1382 const RecordData &Record, unsigned &Idx);
1384 /// \brief Reads a TemplateArgumentLoc.
1386 ReadTemplateArgumentLoc(ModuleFile &F,
1387 const RecordData &Record, unsigned &Idx);
1389 /// \brief Reads a declarator info from the given record.
1390 TypeSourceInfo *GetTypeSourceInfo(ModuleFile &F,
1391 const RecordData &Record, unsigned &Idx);
1393 /// \brief Resolve a type ID into a type, potentially building a new
1395 QualType GetType(serialization::TypeID ID);
1397 /// \brief Resolve a local type ID within a given AST file into a type.
1398 QualType getLocalType(ModuleFile &F, unsigned LocalID);
1400 /// \brief Map a local type ID within a given AST file into a global type ID.
1401 serialization::TypeID getGlobalTypeID(ModuleFile &F, unsigned LocalID) const;
1403 /// \brief Read a type from the current position in the given record, which
1404 /// was read from the given AST file.
1405 QualType readType(ModuleFile &F, const RecordData &Record, unsigned &Idx) {
1406 if (Idx >= Record.size())
1409 return getLocalType(F, Record[Idx++]);
1412 /// \brief Map from a local declaration ID within a given module to a
1413 /// global declaration ID.
1414 serialization::DeclID getGlobalDeclID(ModuleFile &F,
1415 serialization::LocalDeclID LocalID) const;
1417 /// \brief Returns true if global DeclID \p ID originated from module \p M.
1418 bool isDeclIDFromModule(serialization::GlobalDeclID ID, ModuleFile &M) const;
1420 /// \brief Retrieve the module file that owns the given declaration, or NULL
1421 /// if the declaration is not from a module file.
1422 ModuleFile *getOwningModuleFile(const Decl *D);
1424 /// \brief Returns the source location for the decl \p ID.
1425 SourceLocation getSourceLocationForDeclID(serialization::GlobalDeclID ID);
1427 /// \brief Resolve a declaration ID into a declaration, potentially
1428 /// building a new declaration.
1429 Decl *GetDecl(serialization::DeclID ID);
1430 virtual Decl *GetExternalDecl(uint32_t ID);
1432 /// \brief Reads a declaration with the given local ID in the given module.
1433 Decl *GetLocalDecl(ModuleFile &F, uint32_t LocalID) {
1434 return GetDecl(getGlobalDeclID(F, LocalID));
1437 /// \brief Reads a declaration with the given local ID in the given module.
1439 /// \returns The requested declaration, casted to the given return type.
1440 template<typename T>
1441 T *GetLocalDeclAs(ModuleFile &F, uint32_t LocalID) {
1442 return cast_or_null<T>(GetLocalDecl(F, LocalID));
1445 /// \brief Map a global declaration ID into the declaration ID used to
1446 /// refer to this declaration within the given module fule.
1448 /// \returns the global ID of the given declaration as known in the given
1450 serialization::DeclID
1451 mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
1452 serialization::DeclID GlobalID);
1454 /// \brief Reads a declaration ID from the given position in a record in the
1457 /// \returns The declaration ID read from the record, adjusted to a global ID.
1458 serialization::DeclID ReadDeclID(ModuleFile &F, const RecordData &Record,
1461 /// \brief Reads a declaration from the given position in a record in the
1463 Decl *ReadDecl(ModuleFile &F, const RecordData &R, unsigned &I) {
1464 return GetDecl(ReadDeclID(F, R, I));
1467 /// \brief Reads a declaration from the given position in a record in the
1470 /// \returns The declaration read from this location, casted to the given
1472 template<typename T>
1473 T *ReadDeclAs(ModuleFile &F, const RecordData &R, unsigned &I) {
1474 return cast_or_null<T>(GetDecl(ReadDeclID(F, R, I)));
1477 /// \brief Read a CXXBaseSpecifiers ID form the given record and
1478 /// return its global bit offset.
1479 uint64_t readCXXBaseSpecifiers(ModuleFile &M, const RecordData &Record,
1482 virtual CXXBaseSpecifier *GetExternalCXXBaseSpecifiers(uint64_t Offset);
1484 /// \brief Resolve the offset of a statement into a statement.
1486 /// This operation will read a new statement from the external
1487 /// source each time it is called, and is meant to be used via a
1488 /// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
1489 virtual Stmt *GetExternalDeclStmt(uint64_t Offset);
1491 /// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1492 /// specified cursor. Read the abbreviations that are at the top of the block
1493 /// and then leave the cursor pointing into the block.
1494 bool ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor, unsigned BlockID);
1496 /// \brief Finds all the visible declarations with a given name.
1497 /// The current implementation of this method just loads the entire
1498 /// lookup table as unmaterialized references.
1500 FindExternalVisibleDeclsByName(const DeclContext *DC,
1501 DeclarationName Name);
1503 /// \brief Read all of the declarations lexically stored in a
1504 /// declaration context.
1506 /// \param DC The declaration context whose declarations will be
1509 /// \param Decls Vector that will contain the declarations loaded
1510 /// from the external source. The caller is responsible for merging
1511 /// these declarations with any declarations already stored in the
1512 /// declaration context.
1514 /// \returns true if there was an error while reading the
1515 /// declarations for this declaration context.
1516 virtual ExternalLoadResult FindExternalLexicalDecls(const DeclContext *DC,
1517 bool (*isKindWeWant)(Decl::Kind),
1518 SmallVectorImpl<Decl*> &Decls);
1520 /// \brief Get the decls that are contained in a file in the Offset/Length
1521 /// range. \p Length can be 0 to indicate a point at \p Offset instead of
1523 virtual void FindFileRegionDecls(FileID File, unsigned Offset,unsigned Length,
1524 SmallVectorImpl<Decl *> &Decls);
1526 /// \brief Notify ASTReader that we started deserialization of
1527 /// a decl or type so until FinishedDeserializing is called there may be
1528 /// decls that are initializing. Must be paired with FinishedDeserializing.
1529 virtual void StartedDeserializing() { ++NumCurrentElementsDeserializing; }
1531 /// \brief Notify ASTReader that we finished the deserialization of
1532 /// a decl or type. Must be paired with StartedDeserializing.
1533 virtual void FinishedDeserializing();
1535 /// \brief Function that will be invoked when we begin parsing a new
1536 /// translation unit involving this external AST source.
1538 /// This function will provide all of the external definitions to
1539 /// the ASTConsumer.
1540 virtual void StartTranslationUnit(ASTConsumer *Consumer);
1542 /// \brief Print some statistics about AST usage.
1543 virtual void PrintStats();
1545 /// \brief Dump information about the AST reader to standard error.
1548 /// Return the amount of memory used by memory buffers, breaking down
1549 /// by heap-backed versus mmap'ed memory.
1550 virtual void getMemoryBufferSizes(MemoryBufferSizes &sizes) const;
1552 /// \brief Initialize the semantic source with the Sema instance
1553 /// being used to perform semantic analysis on the abstract syntax
1555 virtual void InitializeSema(Sema &S);
1557 /// \brief Inform the semantic consumer that Sema is no longer available.
1558 virtual void ForgetSema() { SemaObj = 0; }
1560 /// \brief Retrieve the IdentifierInfo for the named identifier.
1562 /// This routine builds a new IdentifierInfo for the given identifier. If any
1563 /// declarations with this name are visible from translation unit scope, their
1564 /// declarations will be deserialized and introduced into the declaration
1565 /// chain of the identifier.
1566 virtual IdentifierInfo *get(const char *NameStart, const char *NameEnd);
1567 IdentifierInfo *get(StringRef Name) {
1568 return get(Name.begin(), Name.end());
1571 /// \brief Retrieve an iterator into the set of all identifiers
1572 /// in all loaded AST files.
1573 virtual IdentifierIterator *getIdentifiers();
1575 /// \brief Load the contents of the global method pool for a given
1577 virtual void ReadMethodPool(Selector Sel);
1579 /// \brief Load the set of namespaces that are known to the external source,
1580 /// which will be used during typo correction.
1581 virtual void ReadKnownNamespaces(
1582 SmallVectorImpl<NamespaceDecl *> &Namespaces);
1584 virtual void ReadUndefinedButUsed(
1585 llvm::DenseMap<NamedDecl *, SourceLocation> &Undefined);
1587 virtual void ReadTentativeDefinitions(
1588 SmallVectorImpl<VarDecl *> &TentativeDefs);
1590 virtual void ReadUnusedFileScopedDecls(
1591 SmallVectorImpl<const DeclaratorDecl *> &Decls);
1593 virtual void ReadDelegatingConstructors(
1594 SmallVectorImpl<CXXConstructorDecl *> &Decls);
1596 virtual void ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls);
1598 virtual void ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls);
1600 virtual void ReadLocallyScopedExternCDecls(
1601 SmallVectorImpl<NamedDecl *> &Decls);
1603 virtual void ReadReferencedSelectors(
1604 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels);
1606 virtual void ReadWeakUndeclaredIdentifiers(
1607 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WI);
1609 virtual void ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables);
1611 virtual void ReadPendingInstantiations(
1612 SmallVectorImpl<std::pair<ValueDecl *,
1613 SourceLocation> > &Pending);
1615 /// \brief Load a selector from disk, registering its ID if it exists.
1616 void LoadSelector(Selector Sel);
1618 void SetIdentifierInfo(unsigned ID, IdentifierInfo *II);
1619 void SetGloballyVisibleDecls(IdentifierInfo *II,
1620 const SmallVectorImpl<uint32_t> &DeclIDs,
1621 SmallVectorImpl<Decl *> *Decls = 0);
1623 /// \brief Report a diagnostic.
1624 DiagnosticBuilder Diag(unsigned DiagID);
1626 /// \brief Report a diagnostic.
1627 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
1629 IdentifierInfo *DecodeIdentifierInfo(serialization::IdentifierID ID);
1631 IdentifierInfo *GetIdentifierInfo(ModuleFile &M, const RecordData &Record,
1633 return DecodeIdentifierInfo(getGlobalIdentifierID(M, Record[Idx++]));
1636 virtual IdentifierInfo *GetIdentifier(serialization::IdentifierID ID) {
1637 // Note that we are loading an identifier.
1638 Deserializing AnIdentifier(this);
1640 return DecodeIdentifierInfo(ID);
1643 IdentifierInfo *getLocalIdentifier(ModuleFile &M, unsigned LocalID);
1645 serialization::IdentifierID getGlobalIdentifierID(ModuleFile &M,
1648 void resolvePendingMacro(IdentifierInfo *II, const PendingMacroInfo &PMInfo);
1650 void installPCHMacroDirectives(IdentifierInfo *II,
1651 ModuleFile &M, uint64_t Offset);
1653 void installImportedMacro(IdentifierInfo *II, MacroDirective *MD,
1656 /// \brief Retrieve the macro with the given ID.
1657 MacroInfo *getMacro(serialization::MacroID ID);
1659 /// \brief Retrieve the global macro ID corresponding to the given local
1660 /// ID within the given module file.
1661 serialization::MacroID getGlobalMacroID(ModuleFile &M, unsigned LocalID);
1663 /// \brief Read the source location entry with index ID.
1664 virtual bool ReadSLocEntry(int ID);
1666 /// \brief Retrieve the module import location and module name for the
1667 /// given source manager entry ID.
1668 virtual std::pair<SourceLocation, StringRef> getModuleImportLoc(int ID);
1670 /// \brief Retrieve the global submodule ID given a module and its local ID
1672 serialization::SubmoduleID
1673 getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID);
1675 /// \brief Retrieve the submodule that corresponds to a global submodule ID.
1677 Module *getSubmodule(serialization::SubmoduleID GlobalID);
1679 /// \brief Retrieve the module that corresponds to the given module ID.
1681 /// Note: overrides method in ExternalASTSource
1682 virtual Module *getModule(unsigned ID);
1684 /// \brief Retrieve a selector from the given module with its local ID
1686 Selector getLocalSelector(ModuleFile &M, unsigned LocalID);
1688 Selector DecodeSelector(serialization::SelectorID Idx);
1690 virtual Selector GetExternalSelector(serialization::SelectorID ID);
1691 uint32_t GetNumExternalSelectors();
1693 Selector ReadSelector(ModuleFile &M, const RecordData &Record, unsigned &Idx) {
1694 return getLocalSelector(M, Record[Idx++]);
1697 /// \brief Retrieve the global selector ID that corresponds to this
1698 /// the local selector ID in a given module.
1699 serialization::SelectorID getGlobalSelectorID(ModuleFile &F,
1700 unsigned LocalID) const;
1702 /// \brief Read a declaration name.
1703 DeclarationName ReadDeclarationName(ModuleFile &F,
1704 const RecordData &Record, unsigned &Idx);
1705 void ReadDeclarationNameLoc(ModuleFile &F,
1706 DeclarationNameLoc &DNLoc, DeclarationName Name,
1707 const RecordData &Record, unsigned &Idx);
1708 void ReadDeclarationNameInfo(ModuleFile &F, DeclarationNameInfo &NameInfo,
1709 const RecordData &Record, unsigned &Idx);
1711 void ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
1712 const RecordData &Record, unsigned &Idx);
1714 NestedNameSpecifier *ReadNestedNameSpecifier(ModuleFile &F,
1715 const RecordData &Record,
1718 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc(ModuleFile &F,
1719 const RecordData &Record,
1722 /// \brief Read a template name.
1723 TemplateName ReadTemplateName(ModuleFile &F, const RecordData &Record,
1726 /// \brief Read a template argument.
1727 TemplateArgument ReadTemplateArgument(ModuleFile &F,
1728 const RecordData &Record,unsigned &Idx);
1730 /// \brief Read a template parameter list.
1731 TemplateParameterList *ReadTemplateParameterList(ModuleFile &F,
1732 const RecordData &Record,
1735 /// \brief Read a template argument array.
1737 ReadTemplateArgumentList(SmallVector<TemplateArgument, 8> &TemplArgs,
1738 ModuleFile &F, const RecordData &Record,
1741 /// \brief Read a UnresolvedSet structure.
1742 void ReadUnresolvedSet(ModuleFile &F, ASTUnresolvedSet &Set,
1743 const RecordData &Record, unsigned &Idx);
1745 /// \brief Read a C++ base specifier.
1746 CXXBaseSpecifier ReadCXXBaseSpecifier(ModuleFile &F,
1747 const RecordData &Record,unsigned &Idx);
1749 /// \brief Read a CXXCtorInitializer array.
1750 std::pair<CXXCtorInitializer **, unsigned>
1751 ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
1754 /// \brief Read a source location from raw form.
1755 SourceLocation ReadSourceLocation(ModuleFile &ModuleFile, unsigned Raw) const {
1756 SourceLocation Loc = SourceLocation::getFromRawEncoding(Raw);
1757 assert(ModuleFile.SLocRemap.find(Loc.getOffset()) != ModuleFile.SLocRemap.end() &&
1758 "Cannot find offset to remap.");
1759 int Remap = ModuleFile.SLocRemap.find(Loc.getOffset())->second;
1760 return Loc.getLocWithOffset(Remap);
1763 /// \brief Read a source location.
1764 SourceLocation ReadSourceLocation(ModuleFile &ModuleFile,
1765 const RecordData &Record, unsigned &Idx) {
1766 return ReadSourceLocation(ModuleFile, Record[Idx++]);
1769 /// \brief Read a source range.
1770 SourceRange ReadSourceRange(ModuleFile &F,
1771 const RecordData &Record, unsigned &Idx);
1773 /// \brief Read an integral value
1774 llvm::APInt ReadAPInt(const RecordData &Record, unsigned &Idx);
1776 /// \brief Read a signed integral value
1777 llvm::APSInt ReadAPSInt(const RecordData &Record, unsigned &Idx);
1779 /// \brief Read a floating-point value
1780 llvm::APFloat ReadAPFloat(const RecordData &Record,
1781 const llvm::fltSemantics &Sem, unsigned &Idx);
1783 // \brief Read a string
1784 static std::string ReadString(const RecordData &Record, unsigned &Idx);
1786 /// \brief Read a version tuple.
1787 static VersionTuple ReadVersionTuple(const RecordData &Record, unsigned &Idx);
1789 CXXTemporary *ReadCXXTemporary(ModuleFile &F, const RecordData &Record,
1792 /// \brief Reads attributes from the current stream position.
1793 void ReadAttributes(ModuleFile &F, AttrVec &Attrs,
1794 const RecordData &Record, unsigned &Idx);
1796 /// \brief Reads a statement.
1797 Stmt *ReadStmt(ModuleFile &F);
1799 /// \brief Reads an expression.
1800 Expr *ReadExpr(ModuleFile &F);
1802 /// \brief Reads a sub-statement operand during statement reading.
1803 Stmt *ReadSubStmt() {
1804 assert(ReadingKind == Read_Stmt &&
1805 "Should be called only during statement reading!");
1806 // Subexpressions are stored from last to first, so the next Stmt we need
1807 // is at the back of the stack.
1808 assert(!StmtStack.empty() && "Read too many sub statements!");
1809 return StmtStack.pop_back_val();
1812 /// \brief Reads a sub-expression operand during statement reading.
1813 Expr *ReadSubExpr();
1815 /// \brief Reads a token out of a record.
1816 Token ReadToken(ModuleFile &M, const RecordData &Record, unsigned &Idx);
1818 /// \brief Reads the macro record located at the given offset.
1819 MacroInfo *ReadMacroRecord(ModuleFile &F, uint64_t Offset);
1821 /// \brief Determine the global preprocessed entity ID that corresponds to
1822 /// the given local ID within the given module.
1823 serialization::PreprocessedEntityID
1824 getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const;
1826 /// \brief Add a macro to resolve imported from a module.
1828 /// \param II The name of the macro.
1829 /// \param M The module file.
1830 /// \param GMacID The global macro ID that is associated with this identifier.
1831 /// \param ImportLoc The location where the module is imported.
1832 void addPendingMacroFromModule(IdentifierInfo *II,
1834 serialization::GlobalMacroID GMacID,
1835 SourceLocation ImportLoc);
1837 /// \brief Add a macro to deserialize its macro directive history from a PCH.
1839 /// \param II The name of the macro.
1840 /// \param M The module file.
1841 /// \param MacroDirectivesOffset Offset of the serialized macro directive
1843 void addPendingMacroFromPCH(IdentifierInfo *II,
1844 ModuleFile *M, uint64_t MacroDirectivesOffset);
1846 /// \brief Read the set of macros defined by this external macro source.
1847 virtual void ReadDefinedMacros();
1849 /// \brief Update an out-of-date identifier.
1850 virtual void updateOutOfDateIdentifier(IdentifierInfo &II);
1852 /// \brief Note that this identifier is up-to-date.
1853 void markIdentifierUpToDate(IdentifierInfo *II);
1855 /// \brief Load all external visible decls in the given DeclContext.
1856 void completeVisibleDeclsMap(const DeclContext *DC);
1858 /// \brief Retrieve the AST context that this AST reader supplements.
1859 ASTContext &getContext() { return Context; }
1861 // \brief Contains declarations that were loaded before we have
1862 // access to a Sema object.
1863 SmallVector<NamedDecl *, 16> PreloadedDecls;
1865 /// \brief Retrieve the semantic analysis object used to analyze the
1866 /// translation unit in which the precompiled header is being
1868 Sema *getSema() { return SemaObj; }
1870 /// \brief Retrieve the identifier table associated with the
1872 IdentifierTable &getIdentifierTable();
1874 /// \brief Record that the given ID maps to the given switch-case
1876 void RecordSwitchCaseID(SwitchCase *SC, unsigned ID);
1878 /// \brief Retrieve the switch-case statement with the given ID.
1879 SwitchCase *getSwitchCaseWithID(unsigned ID);
1881 void ClearSwitchCaseIDs();
1883 /// \brief Cursors for comments blocks.
1884 SmallVector<std::pair<llvm::BitstreamCursor,
1885 serialization::ModuleFile *>, 8> CommentsCursors;
1887 /// \brief Loads comments ranges.
1888 void ReadComments();
1891 /// \brief Helper class that saves the current stream position and
1892 /// then restores it when destroyed.
1893 struct SavedStreamPosition {
1894 explicit SavedStreamPosition(llvm::BitstreamCursor &Cursor)
1895 : Cursor(Cursor), Offset(Cursor.GetCurrentBitNo()) { }
1897 ~SavedStreamPosition() {
1898 Cursor.JumpToBit(Offset);
1902 llvm::BitstreamCursor &Cursor;
1906 inline void PCHValidator::Error(const char *Msg) {
1910 } // end namespace clang