Home | History | Annotate | Download | only in Serialization
      1 //===--- ASTReader.h - AST File Reader --------------------------*- C++ -*-===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 //  This file defines the ASTReader class, which reads AST files.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #ifndef LLVM_CLANG_SERIALIZATION_ASTREADER_H
     15 #define LLVM_CLANG_SERIALIZATION_ASTREADER_H
     16 
     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/ModuleFileExtension.h"
     34 #include "clang/Serialization/ModuleManager.h"
     35 #include "llvm/ADT/APFloat.h"
     36 #include "llvm/ADT/APInt.h"
     37 #include "llvm/ADT/APSInt.h"
     38 #include "llvm/ADT/MapVector.h"
     39 #include "llvm/ADT/SmallPtrSet.h"
     40 #include "llvm/ADT/SmallSet.h"
     41 #include "llvm/ADT/SmallVector.h"
     42 #include "llvm/ADT/StringMap.h"
     43 #include "llvm/ADT/StringRef.h"
     44 #include "llvm/ADT/TinyPtrVector.h"
     45 #include "llvm/Bitcode/BitstreamReader.h"
     46 #include "llvm/Support/DataTypes.h"
     47 #include "llvm/Support/Timer.h"
     48 #include <deque>
     49 #include <map>
     50 #include <memory>
     51 #include <string>
     52 #include <utility>
     53 #include <vector>
     54 
     55 namespace llvm {
     56   class MemoryBuffer;
     57 }
     58 
     59 namespace clang {
     60 
     61 class AddrLabelExpr;
     62 class ASTConsumer;
     63 class ASTContext;
     64 class ASTIdentifierIterator;
     65 class ASTUnit; // FIXME: Layering violation and egregious hack.
     66 class Attr;
     67 class Decl;
     68 class DeclContext;
     69 class DefMacroDirective;
     70 class DiagnosticOptions;
     71 class NestedNameSpecifier;
     72 class CXXBaseSpecifier;
     73 class CXXConstructorDecl;
     74 class CXXCtorInitializer;
     75 class GlobalModuleIndex;
     76 class GotoStmt;
     77 class MacroDefinition;
     78 class MacroDirective;
     79 class ModuleMacro;
     80 class NamedDecl;
     81 class OpaqueValueExpr;
     82 class Preprocessor;
     83 class PreprocessorOptions;
     84 class Sema;
     85 class SwitchCase;
     86 class ASTDeserializationListener;
     87 class ASTWriter;
     88 class ASTReader;
     89 class ASTDeclReader;
     90 class ASTStmtReader;
     91 class TypeLocReader;
     92 struct HeaderFileInfo;
     93 class VersionTuple;
     94 class TargetOptions;
     95 class LazyASTUnresolvedSet;
     96 
     97 /// \brief Abstract interface for callback invocations by the ASTReader.
     98 ///
     99 /// While reading an AST file, the ASTReader will call the methods of the
    100 /// listener to pass on specific information. Some of the listener methods can
    101 /// return true to indicate to the ASTReader that the information (and
    102 /// consequently the AST file) is invalid.
    103 class ASTReaderListener {
    104 public:
    105   virtual ~ASTReaderListener();
    106 
    107   /// \brief Receives the full Clang version information.
    108   ///
    109   /// \returns true to indicate that the version is invalid. Subclasses should
    110   /// generally defer to this implementation.
    111   virtual bool ReadFullVersionInformation(StringRef FullVersion) {
    112     return FullVersion != getClangFullRepositoryVersion();
    113   }
    114 
    115   virtual void ReadModuleName(StringRef ModuleName) {}
    116   virtual void ReadModuleMapFile(StringRef ModuleMapPath) {}
    117 
    118   /// \brief Receives the language options.
    119   ///
    120   /// \returns true to indicate the options are invalid or false otherwise.
    121   virtual bool ReadLanguageOptions(const LangOptions &LangOpts,
    122                                    bool Complain,
    123                                    bool AllowCompatibleDifferences) {
    124     return false;
    125   }
    126 
    127   /// \brief Receives the target options.
    128   ///
    129   /// \returns true to indicate the target options are invalid, or false
    130   /// otherwise.
    131   virtual bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
    132                                  bool AllowCompatibleDifferences) {
    133     return false;
    134   }
    135 
    136   /// \brief Receives the diagnostic options.
    137   ///
    138   /// \returns true to indicate the diagnostic options are invalid, or false
    139   /// otherwise.
    140   virtual bool
    141   ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
    142                         bool Complain) {
    143     return false;
    144   }
    145 
    146   /// \brief Receives the file system options.
    147   ///
    148   /// \returns true to indicate the file system options are invalid, or false
    149   /// otherwise.
    150   virtual bool ReadFileSystemOptions(const FileSystemOptions &FSOpts,
    151                                      bool Complain) {
    152     return false;
    153   }
    154 
    155   /// \brief Receives the header search options.
    156   ///
    157   /// \returns true to indicate the header search options are invalid, or false
    158   /// otherwise.
    159   virtual bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
    160                                        StringRef SpecificModuleCachePath,
    161                                        bool Complain) {
    162     return false;
    163   }
    164 
    165   /// \brief Receives the preprocessor options.
    166   ///
    167   /// \param SuggestedPredefines Can be filled in with the set of predefines
    168   /// that are suggested by the preprocessor options. Typically only used when
    169   /// loading a precompiled header.
    170   ///
    171   /// \returns true to indicate the preprocessor options are invalid, or false
    172   /// otherwise.
    173   virtual bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
    174                                        bool Complain,
    175                                        std::string &SuggestedPredefines) {
    176     return false;
    177   }
    178 
    179   /// \brief Receives __COUNTER__ value.
    180   virtual void ReadCounter(const serialization::ModuleFile &M,
    181                            unsigned Value) {}
    182 
    183   /// This is called for each AST file loaded.
    184   virtual void visitModuleFile(StringRef Filename,
    185                                serialization::ModuleKind Kind) {}
    186 
    187   /// \brief Returns true if this \c ASTReaderListener wants to receive the
    188   /// input files of the AST file via \c visitInputFile, false otherwise.
    189   virtual bool needsInputFileVisitation() { return false; }
    190   /// \brief Returns true if this \c ASTReaderListener wants to receive the
    191   /// system input files of the AST file via \c visitInputFile, false otherwise.
    192   virtual bool needsSystemInputFileVisitation() { return false; }
    193   /// \brief if \c needsInputFileVisitation returns true, this is called for
    194   /// each non-system input file of the AST File. If
    195   /// \c needsSystemInputFileVisitation is true, then it is called for all
    196   /// system input files as well.
    197   ///
    198   /// \returns true to continue receiving the next input file, false to stop.
    199   virtual bool visitInputFile(StringRef Filename, bool isSystem,
    200                               bool isOverridden, bool isExplicitModule) {
    201     return true;
    202   }
    203 
    204   /// \brief Returns true if this \c ASTReaderListener wants to receive the
    205   /// imports of the AST file via \c visitImport, false otherwise.
    206   virtual bool needsImportVisitation() const { return false; }
    207   /// \brief If needsImportVisitation returns \c true, this is called for each
    208   /// AST file imported by this AST file.
    209   virtual void visitImport(StringRef Filename) {}
    210 
    211   /// Indicates that a particular module file extension has been read.
    212   virtual void readModuleFileExtension(
    213                  const ModuleFileExtensionMetadata &Metadata) {}
    214 };
    215 
    216 /// \brief Simple wrapper class for chaining listeners.
    217 class ChainedASTReaderListener : public ASTReaderListener {
    218   std::unique_ptr<ASTReaderListener> First;
    219   std::unique_ptr<ASTReaderListener> Second;
    220 
    221 public:
    222   /// Takes ownership of \p First and \p Second.
    223   ChainedASTReaderListener(std::unique_ptr<ASTReaderListener> First,
    224                            std::unique_ptr<ASTReaderListener> Second)
    225       : First(std::move(First)), Second(std::move(Second)) {}
    226 
    227   std::unique_ptr<ASTReaderListener> takeFirst() { return std::move(First); }
    228   std::unique_ptr<ASTReaderListener> takeSecond() { return std::move(Second); }
    229 
    230   bool ReadFullVersionInformation(StringRef FullVersion) override;
    231   void ReadModuleName(StringRef ModuleName) override;
    232   void ReadModuleMapFile(StringRef ModuleMapPath) override;
    233   bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
    234                            bool AllowCompatibleDifferences) override;
    235   bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
    236                          bool AllowCompatibleDifferences) override;
    237   bool ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
    238                              bool Complain) override;
    239   bool ReadFileSystemOptions(const FileSystemOptions &FSOpts,
    240                              bool Complain) override;
    241 
    242   bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
    243                                StringRef SpecificModuleCachePath,
    244                                bool Complain) override;
    245   bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
    246                                bool Complain,
    247                                std::string &SuggestedPredefines) override;
    248 
    249   void ReadCounter(const serialization::ModuleFile &M, unsigned Value) override;
    250   bool needsInputFileVisitation() override;
    251   bool needsSystemInputFileVisitation() override;
    252   void visitModuleFile(StringRef Filename,
    253                        serialization::ModuleKind Kind) override;
    254   bool visitInputFile(StringRef Filename, bool isSystem,
    255                       bool isOverridden, bool isExplicitModule) override;
    256   void readModuleFileExtension(
    257          const ModuleFileExtensionMetadata &Metadata) override;
    258 };
    259 
    260 /// \brief ASTReaderListener implementation to validate the information of
    261 /// the PCH file against an initialized Preprocessor.
    262 class PCHValidator : public ASTReaderListener {
    263   Preprocessor &PP;
    264   ASTReader &Reader;
    265 
    266 public:
    267   PCHValidator(Preprocessor &PP, ASTReader &Reader)
    268     : PP(PP), Reader(Reader) {}
    269 
    270   bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
    271                            bool AllowCompatibleDifferences) override;
    272   bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
    273                          bool AllowCompatibleDifferences) override;
    274   bool ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
    275                              bool Complain) override;
    276   bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool Complain,
    277                                std::string &SuggestedPredefines) override;
    278   bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
    279                                StringRef SpecificModuleCachePath,
    280                                bool Complain) override;
    281   void ReadCounter(const serialization::ModuleFile &M, unsigned Value) override;
    282 
    283 private:
    284   void Error(const char *Msg);
    285 };
    286 
    287 namespace serialization {
    288 
    289 class ReadMethodPoolVisitor;
    290 
    291 namespace reader {
    292   class ASTIdentifierLookupTrait;
    293   /// \brief The on-disk hash table(s) used for DeclContext name lookup.
    294   struct DeclContextLookupTable;
    295 }
    296 
    297 } // end namespace serialization
    298 
    299 /// \brief Reads an AST files chain containing the contents of a translation
    300 /// unit.
    301 ///
    302 /// The ASTReader class reads bitstreams (produced by the ASTWriter
    303 /// class) containing the serialized representation of a given
    304 /// abstract syntax tree and its supporting data structures. An
    305 /// instance of the ASTReader can be attached to an ASTContext object,
    306 /// which will provide access to the contents of the AST files.
    307 ///
    308 /// The AST reader provides lazy de-serialization of declarations, as
    309 /// required when traversing the AST. Only those AST nodes that are
    310 /// actually required will be de-serialized.
    311 class ASTReader
    312   : public ExternalPreprocessorSource,
    313     public ExternalPreprocessingRecordSource,
    314     public ExternalHeaderFileInfoSource,
    315     public ExternalSemaSource,
    316     public IdentifierInfoLookup,
    317     public ExternalSLocEntrySource
    318 {
    319 public:
    320   typedef SmallVector<uint64_t, 64> RecordData;
    321   typedef SmallVectorImpl<uint64_t> RecordDataImpl;
    322 
    323   /// \brief The result of reading the control block of an AST file, which
    324   /// can fail for various reasons.
    325   enum ASTReadResult {
    326     /// \brief The control block was read successfully. Aside from failures,
    327     /// the AST file is safe to read into the current context.
    328     Success,
    329     /// \brief The AST file itself appears corrupted.
    330     Failure,
    331     /// \brief The AST file was missing.
    332     Missing,
    333     /// \brief The AST file is out-of-date relative to its input files,
    334     /// and needs to be regenerated.
    335     OutOfDate,
    336     /// \brief The AST file was written by a different version of Clang.
    337     VersionMismatch,
    338     /// \brief The AST file was writtten with a different language/target
    339     /// configuration.
    340     ConfigurationMismatch,
    341     /// \brief The AST file has errors.
    342     HadErrors
    343   };
    344 
    345   /// \brief Types of AST files.
    346   friend class PCHValidator;
    347   friend class ASTDeclReader;
    348   friend class ASTStmtReader;
    349   friend class ASTIdentifierIterator;
    350   friend class serialization::reader::ASTIdentifierLookupTrait;
    351   friend class TypeLocReader;
    352   friend class ASTWriter;
    353   friend class ASTUnit; // ASTUnit needs to remap source locations.
    354   friend class serialization::ReadMethodPoolVisitor;
    355 
    356   typedef serialization::ModuleFile ModuleFile;
    357   typedef serialization::ModuleKind ModuleKind;
    358   typedef serialization::ModuleManager ModuleManager;
    359 
    360   typedef ModuleManager::ModuleIterator ModuleIterator;
    361   typedef ModuleManager::ModuleConstIterator ModuleConstIterator;
    362   typedef ModuleManager::ModuleReverseIterator ModuleReverseIterator;
    363 
    364 private:
    365   /// \brief The receiver of some callbacks invoked by ASTReader.
    366   std::unique_ptr<ASTReaderListener> Listener;
    367 
    368   /// \brief The receiver of deserialization events.
    369   ASTDeserializationListener *DeserializationListener;
    370   bool OwnsDeserializationListener;
    371 
    372   SourceManager &SourceMgr;
    373   FileManager &FileMgr;
    374   const PCHContainerReader &PCHContainerRdr;
    375   DiagnosticsEngine &Diags;
    376 
    377   /// \brief The semantic analysis object that will be processing the
    378   /// AST files and the translation unit that uses it.
    379   Sema *SemaObj;
    380 
    381   /// \brief The preprocessor that will be loading the source file.
    382   Preprocessor &PP;
    383 
    384   /// \brief The AST context into which we'll read the AST files.
    385   ASTContext &Context;
    386 
    387   /// \brief The AST consumer.
    388   ASTConsumer *Consumer;
    389 
    390   /// \brief The module manager which manages modules and their dependencies
    391   ModuleManager ModuleMgr;
    392 
    393   /// A mapping from extension block names to module file extensions.
    394   llvm::StringMap<IntrusiveRefCntPtr<ModuleFileExtension>> ModuleFileExtensions;
    395 
    396   /// \brief A timer used to track the time spent deserializing.
    397   std::unique_ptr<llvm::Timer> ReadTimer;
    398 
    399   /// \brief The location where the module file will be considered as
    400   /// imported from. For non-module AST types it should be invalid.
    401   SourceLocation CurrentImportLoc;
    402 
    403   /// \brief The global module index, if loaded.
    404   std::unique_ptr<GlobalModuleIndex> GlobalIndex;
    405 
    406   /// \brief A map of global bit offsets to the module that stores entities
    407   /// at those bit offsets.
    408   ContinuousRangeMap<uint64_t, ModuleFile*, 4> GlobalBitOffsetsMap;
    409 
    410   /// \brief A map of negated SLocEntryIDs to the modules containing them.
    411   ContinuousRangeMap<unsigned, ModuleFile*, 64> GlobalSLocEntryMap;
    412 
    413   typedef ContinuousRangeMap<unsigned, ModuleFile*, 64> GlobalSLocOffsetMapType;
    414 
    415   /// \brief A map of reversed (SourceManager::MaxLoadedOffset - SLocOffset)
    416   /// SourceLocation offsets to the modules containing them.
    417   GlobalSLocOffsetMapType GlobalSLocOffsetMap;
    418 
    419   /// \brief Types that have already been loaded from the chain.
    420   ///
    421   /// When the pointer at index I is non-NULL, the type with
    422   /// ID = (I + 1) << FastQual::Width has already been loaded
    423   std::vector<QualType> TypesLoaded;
    424 
    425   typedef ContinuousRangeMap<serialization::TypeID, ModuleFile *, 4>
    426     GlobalTypeMapType;
    427 
    428   /// \brief Mapping from global type IDs to the module in which the
    429   /// type resides along with the offset that should be added to the
    430   /// global type ID to produce a local ID.
    431   GlobalTypeMapType GlobalTypeMap;
    432 
    433   /// \brief Declarations that have already been loaded from the chain.
    434   ///
    435   /// When the pointer at index I is non-NULL, the declaration with ID
    436   /// = I + 1 has already been loaded.
    437   std::vector<Decl *> DeclsLoaded;
    438 
    439   typedef ContinuousRangeMap<serialization::DeclID, ModuleFile *, 4>
    440     GlobalDeclMapType;
    441 
    442   /// \brief Mapping from global declaration IDs to the module in which the
    443   /// declaration resides.
    444   GlobalDeclMapType GlobalDeclMap;
    445 
    446   typedef std::pair<ModuleFile *, uint64_t> FileOffset;
    447   typedef SmallVector<FileOffset, 2> FileOffsetsTy;
    448   typedef llvm::DenseMap<serialization::DeclID, FileOffsetsTy>
    449       DeclUpdateOffsetsMap;
    450 
    451   /// \brief Declarations that have modifications residing in a later file
    452   /// in the chain.
    453   DeclUpdateOffsetsMap DeclUpdateOffsets;
    454 
    455   /// \brief Declaration updates for already-loaded declarations that we need
    456   /// to apply once we finish processing an import.
    457   llvm::SmallVector<std::pair<serialization::GlobalDeclID, Decl*>, 16>
    458       PendingUpdateRecords;
    459 
    460   enum class PendingFakeDefinitionKind { NotFake, Fake, FakeLoaded };
    461 
    462   /// \brief The DefinitionData pointers that we faked up for class definitions
    463   /// that we needed but hadn't loaded yet.
    464   llvm::DenseMap<void *, PendingFakeDefinitionKind> PendingFakeDefinitionData;
    465 
    466   /// \brief Exception specification updates that have been loaded but not yet
    467   /// propagated across the relevant redeclaration chain. The map key is the
    468   /// canonical declaration (used only for deduplication) and the value is a
    469   /// declaration that has an exception specification.
    470   llvm::SmallMapVector<Decl *, FunctionDecl *, 4> PendingExceptionSpecUpdates;
    471 
    472   struct ReplacedDeclInfo {
    473     ModuleFile *Mod;
    474     uint64_t Offset;
    475     unsigned RawLoc;
    476 
    477     ReplacedDeclInfo() : Mod(nullptr), Offset(0), RawLoc(0) {}
    478     ReplacedDeclInfo(ModuleFile *Mod, uint64_t Offset, unsigned RawLoc)
    479       : Mod(Mod), Offset(Offset), RawLoc(RawLoc) {}
    480   };
    481 
    482   typedef llvm::DenseMap<serialization::DeclID, ReplacedDeclInfo>
    483       DeclReplacementMap;
    484   /// \brief Declarations that have been replaced in a later file in the chain.
    485   DeclReplacementMap ReplacedDecls;
    486 
    487   /// \brief Declarations that have been imported and have typedef names for
    488   /// linkage purposes.
    489   llvm::DenseMap<std::pair<DeclContext*, IdentifierInfo*>, NamedDecl*>
    490       ImportedTypedefNamesForLinkage;
    491 
    492   /// \brief Mergeable declaration contexts that have anonymous declarations
    493   /// within them, and those anonymous declarations.
    494   llvm::DenseMap<DeclContext*, llvm::SmallVector<NamedDecl*, 2>>
    495     AnonymousDeclarationsForMerging;
    496 
    497   struct FileDeclsInfo {
    498     ModuleFile *Mod;
    499     ArrayRef<serialization::LocalDeclID> Decls;
    500 
    501     FileDeclsInfo() : Mod(nullptr) {}
    502     FileDeclsInfo(ModuleFile *Mod, ArrayRef<serialization::LocalDeclID> Decls)
    503       : Mod(Mod), Decls(Decls) {}
    504   };
    505 
    506   /// \brief Map from a FileID to the file-level declarations that it contains.
    507   llvm::DenseMap<FileID, FileDeclsInfo> FileDeclIDs;
    508 
    509   /// \brief An array of lexical contents of a declaration context, as a sequence of
    510   /// Decl::Kind, DeclID pairs.
    511   typedef ArrayRef<llvm::support::unaligned_uint32_t> LexicalContents;
    512 
    513   /// \brief Map from a DeclContext to its lexical contents.
    514   llvm::DenseMap<const DeclContext*, std::pair<ModuleFile*, LexicalContents>>
    515       LexicalDecls;
    516 
    517   /// \brief Map from the TU to its lexical contents from each module file.
    518   std::vector<std::pair<ModuleFile*, LexicalContents>> TULexicalDecls;
    519 
    520   /// \brief Map from a DeclContext to its lookup tables.
    521   llvm::DenseMap<const DeclContext *,
    522                  serialization::reader::DeclContextLookupTable> Lookups;
    523 
    524   // Updates for visible decls can occur for other contexts than just the
    525   // TU, and when we read those update records, the actual context may not
    526   // be available yet, so have this pending map using the ID as a key. It
    527   // will be realized when the context is actually loaded.
    528   struct PendingVisibleUpdate {
    529     ModuleFile *Mod;
    530     const unsigned char *Data;
    531   };
    532   typedef SmallVector<PendingVisibleUpdate, 1> DeclContextVisibleUpdates;
    533 
    534   /// \brief Updates to the visible declarations of declaration contexts that
    535   /// haven't been loaded yet.
    536   llvm::DenseMap<serialization::DeclID, DeclContextVisibleUpdates>
    537       PendingVisibleUpdates;
    538 
    539   /// \brief The set of C++ or Objective-C classes that have forward
    540   /// declarations that have not yet been linked to their definitions.
    541   llvm::SmallPtrSet<Decl *, 4> PendingDefinitions;
    542 
    543   typedef llvm::MapVector<Decl *, uint64_t,
    544                           llvm::SmallDenseMap<Decl *, unsigned, 4>,
    545                           SmallVector<std::pair<Decl *, uint64_t>, 4> >
    546     PendingBodiesMap;
    547 
    548   /// \brief Functions or methods that have bodies that will be attached.
    549   PendingBodiesMap PendingBodies;
    550 
    551   /// \brief Definitions for which we have added merged definitions but not yet
    552   /// performed deduplication.
    553   llvm::SetVector<NamedDecl*> PendingMergedDefinitionsToDeduplicate;
    554 
    555   /// \brief Read the record that describes the lexical contents of a DC.
    556   bool ReadLexicalDeclContextStorage(ModuleFile &M,
    557                                      llvm::BitstreamCursor &Cursor,
    558                                      uint64_t Offset, DeclContext *DC);
    559   /// \brief Read the record that describes the visible contents of a DC.
    560   bool ReadVisibleDeclContextStorage(ModuleFile &M,
    561                                      llvm::BitstreamCursor &Cursor,
    562                                      uint64_t Offset, serialization::DeclID ID);
    563 
    564   /// \brief A vector containing identifiers that have already been
    565   /// loaded.
    566   ///
    567   /// If the pointer at index I is non-NULL, then it refers to the
    568   /// IdentifierInfo for the identifier with ID=I+1 that has already
    569   /// been loaded.
    570   std::vector<IdentifierInfo *> IdentifiersLoaded;
    571 
    572   typedef ContinuousRangeMap<serialization::IdentID, ModuleFile *, 4>
    573     GlobalIdentifierMapType;
    574 
    575   /// \brief Mapping from global identifier IDs to the module in which the
    576   /// identifier resides along with the offset that should be added to the
    577   /// global identifier ID to produce a local ID.
    578   GlobalIdentifierMapType GlobalIdentifierMap;
    579 
    580   /// \brief A vector containing macros that have already been
    581   /// loaded.
    582   ///
    583   /// If the pointer at index I is non-NULL, then it refers to the
    584   /// MacroInfo for the identifier with ID=I+1 that has already
    585   /// been loaded.
    586   std::vector<MacroInfo *> MacrosLoaded;
    587 
    588   typedef std::pair<IdentifierInfo *, serialization::SubmoduleID>
    589       LoadedMacroInfo;
    590 
    591   /// \brief A set of #undef directives that we have loaded; used to
    592   /// deduplicate the same #undef information coming from multiple module
    593   /// files.
    594   llvm::DenseSet<LoadedMacroInfo> LoadedUndefs;
    595 
    596   typedef ContinuousRangeMap<serialization::MacroID, ModuleFile *, 4>
    597     GlobalMacroMapType;
    598 
    599   /// \brief Mapping from global macro IDs to the module in which the
    600   /// macro resides along with the offset that should be added to the
    601   /// global macro ID to produce a local ID.
    602   GlobalMacroMapType GlobalMacroMap;
    603 
    604   /// \brief A vector containing submodules that have already been loaded.
    605   ///
    606   /// This vector is indexed by the Submodule ID (-1). NULL submodule entries
    607   /// indicate that the particular submodule ID has not yet been loaded.
    608   SmallVector<Module *, 2> SubmodulesLoaded;
    609 
    610   typedef ContinuousRangeMap<serialization::SubmoduleID, ModuleFile *, 4>
    611     GlobalSubmoduleMapType;
    612 
    613   /// \brief Mapping from global submodule IDs to the module file in which the
    614   /// submodule resides along with the offset that should be added to the
    615   /// global submodule ID to produce a local ID.
    616   GlobalSubmoduleMapType GlobalSubmoduleMap;
    617 
    618   /// \brief A set of hidden declarations.
    619   typedef SmallVector<Decl*, 2> HiddenNames;
    620   typedef llvm::DenseMap<Module *, HiddenNames> HiddenNamesMapType;
    621 
    622   /// \brief A mapping from each of the hidden submodules to the deserialized
    623   /// declarations in that submodule that could be made visible.
    624   HiddenNamesMapType HiddenNamesMap;
    625 
    626 
    627   /// \brief A module import, export, or conflict that hasn't yet been resolved.
    628   struct UnresolvedModuleRef {
    629     /// \brief The file in which this module resides.
    630     ModuleFile *File;
    631 
    632     /// \brief The module that is importing or exporting.
    633     Module *Mod;
    634 
    635     /// \brief The kind of module reference.
    636     enum { Import, Export, Conflict } Kind;
    637 
    638     /// \brief The local ID of the module that is being exported.
    639     unsigned ID;
    640 
    641     /// \brief Whether this is a wildcard export.
    642     unsigned IsWildcard : 1;
    643 
    644     /// \brief String data.
    645     StringRef String;
    646   };
    647 
    648   /// \brief The set of module imports and exports that still need to be
    649   /// resolved.
    650   SmallVector<UnresolvedModuleRef, 2> UnresolvedModuleRefs;
    651 
    652   /// \brief A vector containing selectors that have already been loaded.
    653   ///
    654   /// This vector is indexed by the Selector ID (-1). NULL selector
    655   /// entries indicate that the particular selector ID has not yet
    656   /// been loaded.
    657   SmallVector<Selector, 16> SelectorsLoaded;
    658 
    659   typedef ContinuousRangeMap<serialization::SelectorID, ModuleFile *, 4>
    660     GlobalSelectorMapType;
    661 
    662   /// \brief Mapping from global selector IDs to the module in which the
    663 
    664   /// global selector ID to produce a local ID.
    665   GlobalSelectorMapType GlobalSelectorMap;
    666 
    667   /// \brief The generation number of the last time we loaded data from the
    668   /// global method pool for this selector.
    669   llvm::DenseMap<Selector, unsigned> SelectorGeneration;
    670 
    671   struct PendingMacroInfo {
    672     ModuleFile *M;
    673     uint64_t MacroDirectivesOffset;
    674 
    675     PendingMacroInfo(ModuleFile *M, uint64_t MacroDirectivesOffset)
    676         : M(M), MacroDirectivesOffset(MacroDirectivesOffset) {}
    677   };
    678 
    679   typedef llvm::MapVector<IdentifierInfo *, SmallVector<PendingMacroInfo, 2> >
    680     PendingMacroIDsMap;
    681 
    682   /// \brief Mapping from identifiers that have a macro history to the global
    683   /// IDs have not yet been deserialized to the global IDs of those macros.
    684   PendingMacroIDsMap PendingMacroIDs;
    685 
    686   typedef ContinuousRangeMap<unsigned, ModuleFile *, 4>
    687     GlobalPreprocessedEntityMapType;
    688 
    689   /// \brief Mapping from global preprocessing entity IDs to the module in
    690   /// which the preprocessed entity resides along with the offset that should be
    691   /// added to the global preprocessing entitiy ID to produce a local ID.
    692   GlobalPreprocessedEntityMapType GlobalPreprocessedEntityMap;
    693 
    694   /// \name CodeGen-relevant special data
    695   /// \brief Fields containing data that is relevant to CodeGen.
    696   //@{
    697 
    698   /// \brief The IDs of all declarations that fulfill the criteria of
    699   /// "interesting" decls.
    700   ///
    701   /// This contains the data loaded from all EAGERLY_DESERIALIZED_DECLS blocks
    702   /// in the chain. The referenced declarations are deserialized and passed to
    703   /// the consumer eagerly.
    704   SmallVector<uint64_t, 16> EagerlyDeserializedDecls;
    705 
    706   /// \brief The IDs of all tentative definitions stored in the chain.
    707   ///
    708   /// Sema keeps track of all tentative definitions in a TU because it has to
    709   /// complete them and pass them on to CodeGen. Thus, tentative definitions in
    710   /// the PCH chain must be eagerly deserialized.
    711   SmallVector<uint64_t, 16> TentativeDefinitions;
    712 
    713   /// \brief The IDs of all CXXRecordDecls stored in the chain whose VTables are
    714   /// used.
    715   ///
    716   /// CodeGen has to emit VTables for these records, so they have to be eagerly
    717   /// deserialized.
    718   SmallVector<uint64_t, 64> VTableUses;
    719 
    720   /// \brief A snapshot of the pending instantiations in the chain.
    721   ///
    722   /// This record tracks the instantiations that Sema has to perform at the
    723   /// end of the TU. It consists of a pair of values for every pending
    724   /// instantiation where the first value is the ID of the decl and the second
    725   /// is the instantiation location.
    726   SmallVector<uint64_t, 64> PendingInstantiations;
    727 
    728   //@}
    729 
    730   /// \name DiagnosticsEngine-relevant special data
    731   /// \brief Fields containing data that is used for generating diagnostics
    732   //@{
    733 
    734   /// \brief A snapshot of Sema's unused file-scoped variable tracking, for
    735   /// generating warnings.
    736   SmallVector<uint64_t, 16> UnusedFileScopedDecls;
    737 
    738   /// \brief A list of all the delegating constructors we've seen, to diagnose
    739   /// cycles.
    740   SmallVector<uint64_t, 4> DelegatingCtorDecls;
    741 
    742   /// \brief Method selectors used in a @selector expression. Used for
    743   /// implementation of -Wselector.
    744   SmallVector<uint64_t, 64> ReferencedSelectorsData;
    745 
    746   /// \brief A snapshot of Sema's weak undeclared identifier tracking, for
    747   /// generating warnings.
    748   SmallVector<uint64_t, 64> WeakUndeclaredIdentifiers;
    749 
    750   /// \brief The IDs of type aliases for ext_vectors that exist in the chain.
    751   ///
    752   /// Used by Sema for finding sugared names for ext_vectors in diagnostics.
    753   SmallVector<uint64_t, 4> ExtVectorDecls;
    754 
    755   //@}
    756 
    757   /// \name Sema-relevant special data
    758   /// \brief Fields containing data that is used for semantic analysis
    759   //@{
    760 
    761   /// \brief The IDs of all potentially unused typedef names in the chain.
    762   ///
    763   /// Sema tracks these to emit warnings.
    764   SmallVector<uint64_t, 16> UnusedLocalTypedefNameCandidates;
    765 
    766   /// \brief The IDs of the declarations Sema stores directly.
    767   ///
    768   /// Sema tracks a few important decls, such as namespace std, directly.
    769   SmallVector<uint64_t, 4> SemaDeclRefs;
    770 
    771   /// \brief The IDs of the types ASTContext stores directly.
    772   ///
    773   /// The AST context tracks a few important types, such as va_list, directly.
    774   SmallVector<uint64_t, 16> SpecialTypes;
    775 
    776   /// \brief The IDs of CUDA-specific declarations ASTContext stores directly.
    777   ///
    778   /// The AST context tracks a few important decls, currently cudaConfigureCall,
    779   /// directly.
    780   SmallVector<uint64_t, 2> CUDASpecialDeclRefs;
    781 
    782   /// \brief The floating point pragma option settings.
    783   SmallVector<uint64_t, 1> FPPragmaOptions;
    784 
    785   /// \brief The pragma clang optimize location (if the pragma state is "off").
    786   SourceLocation OptimizeOffPragmaLocation;
    787 
    788   /// \brief The OpenCL extension settings.
    789   SmallVector<uint64_t, 1> OpenCLExtensions;
    790 
    791   /// \brief A list of the namespaces we've seen.
    792   SmallVector<uint64_t, 4> KnownNamespaces;
    793 
    794   /// \brief A list of undefined decls with internal linkage followed by the
    795   /// SourceLocation of a matching ODR-use.
    796   SmallVector<uint64_t, 8> UndefinedButUsed;
    797 
    798   /// \brief Delete expressions to analyze at the end of translation unit.
    799   SmallVector<uint64_t, 8> DelayedDeleteExprs;
    800 
    801   // \brief A list of late parsed template function data.
    802   SmallVector<uint64_t, 1> LateParsedTemplates;
    803 
    804   struct ImportedSubmodule {
    805     serialization::SubmoduleID ID;
    806     SourceLocation ImportLoc;
    807 
    808     ImportedSubmodule(serialization::SubmoduleID ID, SourceLocation ImportLoc)
    809       : ID(ID), ImportLoc(ImportLoc) {}
    810   };
    811 
    812   /// \brief A list of modules that were imported by precompiled headers or
    813   /// any other non-module AST file.
    814   SmallVector<ImportedSubmodule, 2> ImportedModules;
    815   //@}
    816 
    817   /// \brief The directory that the PCH we are reading is stored in.
    818   std::string CurrentDir;
    819 
    820   /// \brief The system include root to be used when loading the
    821   /// precompiled header.
    822   std::string isysroot;
    823 
    824   /// \brief Whether to disable the normal validation performed on precompiled
    825   /// headers when they are loaded.
    826   bool DisableValidation;
    827 
    828   /// \brief Whether to accept an AST file with compiler errors.
    829   bool AllowASTWithCompilerErrors;
    830 
    831   /// \brief Whether to accept an AST file that has a different configuration
    832   /// from the current compiler instance.
    833   bool AllowConfigurationMismatch;
    834 
    835   /// \brief Whether validate system input files.
    836   bool ValidateSystemInputs;
    837 
    838   /// \brief Whether we are allowed to use the global module index.
    839   bool UseGlobalIndex;
    840 
    841   /// \brief Whether we have tried loading the global module index yet.
    842   bool TriedLoadingGlobalIndex;
    843 
    844   typedef llvm::DenseMap<unsigned, SwitchCase *> SwitchCaseMapTy;
    845   /// \brief Mapping from switch-case IDs in the chain to switch-case statements
    846   ///
    847   /// Statements usually don't have IDs, but switch cases need them, so that the
    848   /// switch statement can refer to them.
    849   SwitchCaseMapTy SwitchCaseStmts;
    850 
    851   SwitchCaseMapTy *CurrSwitchCaseStmts;
    852 
    853   /// \brief The number of source location entries de-serialized from
    854   /// the PCH file.
    855   unsigned NumSLocEntriesRead;
    856 
    857   /// \brief The number of source location entries in the chain.
    858   unsigned TotalNumSLocEntries;
    859 
    860   /// \brief The number of statements (and expressions) de-serialized
    861   /// from the chain.
    862   unsigned NumStatementsRead;
    863 
    864   /// \brief The total number of statements (and expressions) stored
    865   /// in the chain.
    866   unsigned TotalNumStatements;
    867 
    868   /// \brief The number of macros de-serialized from the chain.
    869   unsigned NumMacrosRead;
    870 
    871   /// \brief The total number of macros stored in the chain.
    872   unsigned TotalNumMacros;
    873 
    874   /// \brief The number of lookups into identifier tables.
    875   unsigned NumIdentifierLookups;
    876 
    877   /// \brief The number of lookups into identifier tables that succeed.
    878   unsigned NumIdentifierLookupHits;
    879 
    880   /// \brief The number of selectors that have been read.
    881   unsigned NumSelectorsRead;
    882 
    883   /// \brief The number of method pool entries that have been read.
    884   unsigned NumMethodPoolEntriesRead;
    885 
    886   /// \brief The number of times we have looked up a selector in the method
    887   /// pool.
    888   unsigned NumMethodPoolLookups;
    889 
    890   /// \brief The number of times we have looked up a selector in the method
    891   /// pool and found something.
    892   unsigned NumMethodPoolHits;
    893 
    894   /// \brief The number of times we have looked up a selector in the method
    895   /// pool within a specific module.
    896   unsigned NumMethodPoolTableLookups;
    897 
    898   /// \brief The number of times we have looked up a selector in the method
    899   /// pool within a specific module and found something.
    900   unsigned NumMethodPoolTableHits;
    901 
    902   /// \brief The total number of method pool entries in the selector table.
    903   unsigned TotalNumMethodPoolEntries;
    904 
    905   /// Number of lexical decl contexts read/total.
    906   unsigned NumLexicalDeclContextsRead, TotalLexicalDeclContexts;
    907 
    908   /// Number of visible decl contexts read/total.
    909   unsigned NumVisibleDeclContextsRead, TotalVisibleDeclContexts;
    910 
    911   /// Total size of modules, in bits, currently loaded
    912   uint64_t TotalModulesSizeInBits;
    913 
    914   /// \brief Number of Decl/types that are currently deserializing.
    915   unsigned NumCurrentElementsDeserializing;
    916 
    917   /// \brief Set true while we are in the process of passing deserialized
    918   /// "interesting" decls to consumer inside FinishedDeserializing().
    919   /// This is used as a guard to avoid recursively repeating the process of
    920   /// passing decls to consumer.
    921   bool PassingDeclsToConsumer;
    922 
    923   /// \brief The set of identifiers that were read while the AST reader was
    924   /// (recursively) loading declarations.
    925   ///
    926   /// The declarations on the identifier chain for these identifiers will be
    927   /// loaded once the recursive loading has completed.
    928   llvm::MapVector<IdentifierInfo *, SmallVector<uint32_t, 4> >
    929     PendingIdentifierInfos;
    930 
    931   /// \brief The set of lookup results that we have faked in order to support
    932   /// merging of partially deserialized decls but that we have not yet removed.
    933   llvm::SmallMapVector<IdentifierInfo *, SmallVector<NamedDecl*, 2>, 16>
    934     PendingFakeLookupResults;
    935 
    936   /// \brief The generation number of each identifier, which keeps track of
    937   /// the last time we loaded information about this identifier.
    938   llvm::DenseMap<IdentifierInfo *, unsigned> IdentifierGeneration;
    939 
    940   /// \brief Contains declarations and definitions that will be
    941   /// "interesting" to the ASTConsumer, when we get that AST consumer.
    942   ///
    943   /// "Interesting" declarations are those that have data that may
    944   /// need to be emitted, such as inline function definitions or
    945   /// Objective-C protocols.
    946   std::deque<Decl *> InterestingDecls;
    947 
    948   /// \brief The list of redeclaration chains that still need to be
    949   /// reconstructed, and the local offset to the corresponding list
    950   /// of redeclarations.
    951   SmallVector<std::pair<Decl *, uint64_t>, 16> PendingDeclChains;
    952 
    953   /// \brief The list of canonical declarations whose redeclaration chains
    954   /// need to be marked as incomplete once we're done deserializing things.
    955   SmallVector<Decl *, 16> PendingIncompleteDeclChains;
    956 
    957   /// \brief The Decl IDs for the Sema/Lexical DeclContext of a Decl that has
    958   /// been loaded but its DeclContext was not set yet.
    959   struct PendingDeclContextInfo {
    960     Decl *D;
    961     serialization::GlobalDeclID SemaDC;
    962     serialization::GlobalDeclID LexicalDC;
    963   };
    964 
    965   /// \brief The set of Decls that have been loaded but their DeclContexts are
    966   /// not set yet.
    967   ///
    968   /// The DeclContexts for these Decls will be set once recursive loading has
    969   /// been completed.
    970   std::deque<PendingDeclContextInfo> PendingDeclContextInfos;
    971 
    972   /// \brief The set of NamedDecls that have been loaded, but are members of a
    973   /// context that has been merged into another context where the corresponding
    974   /// declaration is either missing or has not yet been loaded.
    975   ///
    976   /// We will check whether the corresponding declaration is in fact missing
    977   /// once recursing loading has been completed.
    978   llvm::SmallVector<NamedDecl *, 16> PendingOdrMergeChecks;
    979 
    980   /// \brief Record definitions in which we found an ODR violation.
    981   llvm::SmallDenseMap<CXXRecordDecl *, llvm::TinyPtrVector<CXXRecordDecl *>, 2>
    982       PendingOdrMergeFailures;
    983 
    984   /// \brief DeclContexts in which we have diagnosed an ODR violation.
    985   llvm::SmallPtrSet<DeclContext*, 2> DiagnosedOdrMergeFailures;
    986 
    987   /// \brief The set of Objective-C categories that have been deserialized
    988   /// since the last time the declaration chains were linked.
    989   llvm::SmallPtrSet<ObjCCategoryDecl *, 16> CategoriesDeserialized;
    990 
    991   /// \brief The set of Objective-C class definitions that have already been
    992   /// loaded, for which we will need to check for categories whenever a new
    993   /// module is loaded.
    994   SmallVector<ObjCInterfaceDecl *, 16> ObjCClassesLoaded;
    995 
    996   typedef llvm::DenseMap<Decl *, SmallVector<serialization::DeclID, 2> >
    997     KeyDeclsMap;
    998 
    999   /// \brief A mapping from canonical declarations to the set of global
   1000   /// declaration IDs for key declaration that have been merged with that
   1001   /// canonical declaration. A key declaration is a formerly-canonical
   1002   /// declaration whose module did not import any other key declaration for that
   1003   /// entity. These are the IDs that we use as keys when finding redecl chains.
   1004   KeyDeclsMap KeyDecls;
   1005 
   1006   /// \brief A mapping from DeclContexts to the semantic DeclContext that we
   1007   /// are treating as the definition of the entity. This is used, for instance,
   1008   /// when merging implicit instantiations of class templates across modules.
   1009   llvm::DenseMap<DeclContext *, DeclContext *> MergedDeclContexts;
   1010 
   1011   /// \brief A mapping from canonical declarations of enums to their canonical
   1012   /// definitions. Only populated when using modules in C++.
   1013   llvm::DenseMap<EnumDecl *, EnumDecl *> EnumDefinitions;
   1014 
   1015   /// \brief When reading a Stmt tree, Stmt operands are placed in this stack.
   1016   SmallVector<Stmt *, 16> StmtStack;
   1017 
   1018   /// \brief What kind of records we are reading.
   1019   enum ReadingKind {
   1020     Read_None, Read_Decl, Read_Type, Read_Stmt
   1021   };
   1022 
   1023   /// \brief What kind of records we are reading.
   1024   ReadingKind ReadingKind;
   1025 
   1026   /// \brief RAII object to change the reading kind.
   1027   class ReadingKindTracker {
   1028     ASTReader &Reader;
   1029     enum ReadingKind PrevKind;
   1030 
   1031     ReadingKindTracker(const ReadingKindTracker &) = delete;
   1032     void operator=(const ReadingKindTracker &) = delete;
   1033 
   1034   public:
   1035     ReadingKindTracker(enum ReadingKind newKind, ASTReader &reader)
   1036       : Reader(reader), PrevKind(Reader.ReadingKind) {
   1037       Reader.ReadingKind = newKind;
   1038     }
   1039 
   1040     ~ReadingKindTracker() { Reader.ReadingKind = PrevKind; }
   1041   };
   1042 
   1043   /// \brief Suggested contents of the predefines buffer, after this
   1044   /// PCH file has been processed.
   1045   ///
   1046   /// In most cases, this string will be empty, because the predefines
   1047   /// buffer computed to build the PCH file will be identical to the
   1048   /// predefines buffer computed from the command line. However, when
   1049   /// there are differences that the PCH reader can work around, this
   1050   /// predefines buffer may contain additional definitions.
   1051   std::string SuggestedPredefines;
   1052 
   1053   /// \brief Reads a statement from the specified cursor.
   1054   Stmt *ReadStmtFromStream(ModuleFile &F);
   1055 
   1056   struct InputFileInfo {
   1057     std::string Filename;
   1058     off_t StoredSize;
   1059     time_t StoredTime;
   1060     bool Overridden;
   1061     bool Transient;
   1062   };
   1063 
   1064   /// \brief Reads the stored information about an input file.
   1065   InputFileInfo readInputFileInfo(ModuleFile &F, unsigned ID);
   1066 
   1067   /// \brief Retrieve the file entry and 'overridden' bit for an input
   1068   /// file in the given module file.
   1069   serialization::InputFile getInputFile(ModuleFile &F, unsigned ID,
   1070                                         bool Complain = true);
   1071 
   1072 public:
   1073   void ResolveImportedPath(ModuleFile &M, std::string &Filename);
   1074   static void ResolveImportedPath(std::string &Filename, StringRef Prefix);
   1075 
   1076   /// \brief Returns the first key declaration for the given declaration. This
   1077   /// is one that is formerly-canonical (or still canonical) and whose module
   1078   /// did not import any other key declaration of the entity.
   1079   Decl *getKeyDeclaration(Decl *D) {
   1080     D = D->getCanonicalDecl();
   1081     if (D->isFromASTFile())
   1082       return D;
   1083 
   1084     auto I = KeyDecls.find(D);
   1085     if (I == KeyDecls.end() || I->second.empty())
   1086       return D;
   1087     return GetExistingDecl(I->second[0]);
   1088   }
   1089   const Decl *getKeyDeclaration(const Decl *D) {
   1090     return getKeyDeclaration(const_cast<Decl*>(D));
   1091   }
   1092 
   1093   /// \brief Run a callback on each imported key declaration of \p D.
   1094   template <typename Fn>
   1095   void forEachImportedKeyDecl(const Decl *D, Fn Visit) {
   1096     D = D->getCanonicalDecl();
   1097     if (D->isFromASTFile())
   1098       Visit(D);
   1099 
   1100     auto It = KeyDecls.find(const_cast<Decl*>(D));
   1101     if (It != KeyDecls.end())
   1102       for (auto ID : It->second)
   1103         Visit(GetExistingDecl(ID));
   1104   }
   1105 
   1106   /// \brief Get the loaded lookup tables for \p Primary, if any.
   1107   const serialization::reader::DeclContextLookupTable *
   1108   getLoadedLookupTables(DeclContext *Primary) const;
   1109 
   1110 private:
   1111   struct ImportedModule {
   1112     ModuleFile *Mod;
   1113     ModuleFile *ImportedBy;
   1114     SourceLocation ImportLoc;
   1115 
   1116     ImportedModule(ModuleFile *Mod,
   1117                    ModuleFile *ImportedBy,
   1118                    SourceLocation ImportLoc)
   1119       : Mod(Mod), ImportedBy(ImportedBy), ImportLoc(ImportLoc) { }
   1120   };
   1121 
   1122   ASTReadResult ReadASTCore(StringRef FileName, ModuleKind Type,
   1123                             SourceLocation ImportLoc, ModuleFile *ImportedBy,
   1124                             SmallVectorImpl<ImportedModule> &Loaded,
   1125                             off_t ExpectedSize, time_t ExpectedModTime,
   1126                             serialization::ASTFileSignature ExpectedSignature,
   1127                             unsigned ClientLoadCapabilities);
   1128   ASTReadResult ReadControlBlock(ModuleFile &F,
   1129                                  SmallVectorImpl<ImportedModule> &Loaded,
   1130                                  const ModuleFile *ImportedBy,
   1131                                  unsigned ClientLoadCapabilities);
   1132   static ASTReadResult ReadOptionsBlock(
   1133       llvm::BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
   1134       bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
   1135       std::string &SuggestedPredefines);
   1136   ASTReadResult ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities);
   1137   ASTReadResult ReadExtensionBlock(ModuleFile &F);
   1138   bool ParseLineTable(ModuleFile &F, const RecordData &Record);
   1139   bool ReadSourceManagerBlock(ModuleFile &F);
   1140   llvm::BitstreamCursor &SLocCursorForID(int ID);
   1141   SourceLocation getImportLocation(ModuleFile *F);
   1142   ASTReadResult ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
   1143                                        const ModuleFile *ImportedBy,
   1144                                        unsigned ClientLoadCapabilities);
   1145   ASTReadResult ReadSubmoduleBlock(ModuleFile &F,
   1146                                    unsigned ClientLoadCapabilities);
   1147   static bool ParseLanguageOptions(const RecordData &Record, bool Complain,
   1148                                    ASTReaderListener &Listener,
   1149                                    bool AllowCompatibleDifferences);
   1150   static bool ParseTargetOptions(const RecordData &Record, bool Complain,
   1151                                  ASTReaderListener &Listener,
   1152                                  bool AllowCompatibleDifferences);
   1153   static bool ParseDiagnosticOptions(const RecordData &Record, bool Complain,
   1154                                      ASTReaderListener &Listener);
   1155   static bool ParseFileSystemOptions(const RecordData &Record, bool Complain,
   1156                                      ASTReaderListener &Listener);
   1157   static bool ParseHeaderSearchOptions(const RecordData &Record, bool Complain,
   1158                                        ASTReaderListener &Listener);
   1159   static bool ParsePreprocessorOptions(const RecordData &Record, bool Complain,
   1160                                        ASTReaderListener &Listener,
   1161                                        std::string &SuggestedPredefines);
   1162 
   1163   struct RecordLocation {
   1164     RecordLocation(ModuleFile *M, uint64_t O)
   1165       : F(M), Offset(O) {}
   1166     ModuleFile *F;
   1167     uint64_t Offset;
   1168   };
   1169 
   1170   QualType readTypeRecord(unsigned Index);
   1171   void readExceptionSpec(ModuleFile &ModuleFile,
   1172                          SmallVectorImpl<QualType> &ExceptionStorage,
   1173                          FunctionProtoType::ExceptionSpecInfo &ESI,
   1174                          const RecordData &Record, unsigned &Index);
   1175   RecordLocation TypeCursorForIndex(unsigned Index);
   1176   void LoadedDecl(unsigned Index, Decl *D);
   1177   Decl *ReadDeclRecord(serialization::DeclID ID);
   1178   void markIncompleteDeclChain(Decl *Canon);
   1179 
   1180   /// \brief Returns the most recent declaration of a declaration (which must be
   1181   /// of a redeclarable kind) that is either local or has already been loaded
   1182   /// merged into its redecl chain.
   1183   Decl *getMostRecentExistingDecl(Decl *D);
   1184 
   1185   RecordLocation DeclCursorForID(serialization::DeclID ID,
   1186                                  unsigned &RawLocation);
   1187   void loadDeclUpdateRecords(serialization::DeclID ID, Decl *D);
   1188   void loadPendingDeclChain(Decl *D, uint64_t LocalOffset);
   1189   void loadObjCCategories(serialization::GlobalDeclID ID, ObjCInterfaceDecl *D,
   1190                           unsigned PreviousGeneration = 0);
   1191 
   1192   RecordLocation getLocalBitOffset(uint64_t GlobalOffset);
   1193   uint64_t getGlobalBitOffset(ModuleFile &M, uint32_t LocalOffset);
   1194 
   1195   /// \brief Returns the first preprocessed entity ID that begins or ends after
   1196   /// \arg Loc.
   1197   serialization::PreprocessedEntityID
   1198   findPreprocessedEntity(SourceLocation Loc, bool EndsAfter) const;
   1199 
   1200   /// \brief Find the next module that contains entities and return the ID
   1201   /// of the first entry.
   1202   ///
   1203   /// \param SLocMapI points at a chunk of a module that contains no
   1204   /// preprocessed entities or the entities it contains are not the
   1205   /// ones we are looking for.
   1206   serialization::PreprocessedEntityID
   1207     findNextPreprocessedEntity(
   1208                         GlobalSLocOffsetMapType::const_iterator SLocMapI) const;
   1209 
   1210   /// \brief Returns (ModuleFile, Local index) pair for \p GlobalIndex of a
   1211   /// preprocessed entity.
   1212   std::pair<ModuleFile *, unsigned>
   1213     getModulePreprocessedEntity(unsigned GlobalIndex);
   1214 
   1215   /// \brief Returns (begin, end) pair for the preprocessed entities of a
   1216   /// particular module.
   1217   llvm::iterator_range<PreprocessingRecord::iterator>
   1218   getModulePreprocessedEntities(ModuleFile &Mod) const;
   1219 
   1220   class ModuleDeclIterator
   1221       : public llvm::iterator_adaptor_base<
   1222             ModuleDeclIterator, const serialization::LocalDeclID *,
   1223             std::random_access_iterator_tag, const Decl *, ptrdiff_t,
   1224             const Decl *, const Decl *> {
   1225     ASTReader *Reader;
   1226     ModuleFile *Mod;
   1227 
   1228   public:
   1229     ModuleDeclIterator()
   1230         : iterator_adaptor_base(nullptr), Reader(nullptr), Mod(nullptr) {}
   1231 
   1232     ModuleDeclIterator(ASTReader *Reader, ModuleFile *Mod,
   1233                        const serialization::LocalDeclID *Pos)
   1234         : iterator_adaptor_base(Pos), Reader(Reader), Mod(Mod) {}
   1235 
   1236     value_type operator*() const {
   1237       return Reader->GetDecl(Reader->getGlobalDeclID(*Mod, *I));
   1238     }
   1239     value_type operator->() const { return **this; }
   1240 
   1241     bool operator==(const ModuleDeclIterator &RHS) const {
   1242       assert(Reader == RHS.Reader && Mod == RHS.Mod);
   1243       return I == RHS.I;
   1244     }
   1245   };
   1246 
   1247   llvm::iterator_range<ModuleDeclIterator>
   1248   getModuleFileLevelDecls(ModuleFile &Mod);
   1249 
   1250   void PassInterestingDeclsToConsumer();
   1251   void PassInterestingDeclToConsumer(Decl *D);
   1252 
   1253   void finishPendingActions();
   1254   void diagnoseOdrViolations();
   1255 
   1256   void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name);
   1257 
   1258   void addPendingDeclContextInfo(Decl *D,
   1259                                  serialization::GlobalDeclID SemaDC,
   1260                                  serialization::GlobalDeclID LexicalDC) {
   1261     assert(D);
   1262     PendingDeclContextInfo Info = { D, SemaDC, LexicalDC };
   1263     PendingDeclContextInfos.push_back(Info);
   1264   }
   1265 
   1266   /// \brief Produce an error diagnostic and return true.
   1267   ///
   1268   /// This routine should only be used for fatal errors that have to
   1269   /// do with non-routine failures (e.g., corrupted AST file).
   1270   void Error(StringRef Msg);
   1271   void Error(unsigned DiagID, StringRef Arg1 = StringRef(),
   1272              StringRef Arg2 = StringRef());
   1273 
   1274   ASTReader(const ASTReader &) = delete;
   1275   void operator=(const ASTReader &) = delete;
   1276 public:
   1277   /// \brief Load the AST file and validate its contents against the given
   1278   /// Preprocessor.
   1279   ///
   1280   /// \param PP the preprocessor associated with the context in which this
   1281   /// precompiled header will be loaded.
   1282   ///
   1283   /// \param Context the AST context that this precompiled header will be
   1284   /// loaded into.
   1285   ///
   1286   /// \param PCHContainerRdr the PCHContainerOperations to use for loading and
   1287   /// creating modules.
   1288   ///
   1289   /// \param Extensions the list of module file extensions that can be loaded
   1290   /// from the AST files.
   1291   ///
   1292   /// \param isysroot If non-NULL, the system include path specified by the
   1293   /// user. This is only used with relocatable PCH files. If non-NULL,
   1294   /// a relocatable PCH file will use the default path "/".
   1295   ///
   1296   /// \param DisableValidation If true, the AST reader will suppress most
   1297   /// of its regular consistency checking, allowing the use of precompiled
   1298   /// headers that cannot be determined to be compatible.
   1299   ///
   1300   /// \param AllowASTWithCompilerErrors If true, the AST reader will accept an
   1301   /// AST file the was created out of an AST with compiler errors,
   1302   /// otherwise it will reject it.
   1303   ///
   1304   /// \param AllowConfigurationMismatch If true, the AST reader will not check
   1305   /// for configuration differences between the AST file and the invocation.
   1306   ///
   1307   /// \param ValidateSystemInputs If true, the AST reader will validate
   1308   /// system input files in addition to user input files. This is only
   1309   /// meaningful if \p DisableValidation is false.
   1310   ///
   1311   /// \param UseGlobalIndex If true, the AST reader will try to load and use
   1312   /// the global module index.
   1313   ///
   1314   /// \param ReadTimer If non-null, a timer used to track the time spent
   1315   /// deserializing.
   1316   ASTReader(Preprocessor &PP, ASTContext &Context,
   1317             const PCHContainerReader &PCHContainerRdr,
   1318             ArrayRef<IntrusiveRefCntPtr<ModuleFileExtension>> Extensions,
   1319             StringRef isysroot = "", bool DisableValidation = false,
   1320             bool AllowASTWithCompilerErrors = false,
   1321             bool AllowConfigurationMismatch = false,
   1322             bool ValidateSystemInputs = false, bool UseGlobalIndex = true,
   1323             std::unique_ptr<llvm::Timer> ReadTimer = {});
   1324 
   1325   ~ASTReader() override;
   1326 
   1327   SourceManager &getSourceManager() const { return SourceMgr; }
   1328   FileManager &getFileManager() const { return FileMgr; }
   1329   DiagnosticsEngine &getDiags() const { return Diags; }
   1330 
   1331   /// \brief Flags that indicate what kind of AST loading failures the client
   1332   /// of the AST reader can directly handle.
   1333   ///
   1334   /// When a client states that it can handle a particular kind of failure,
   1335   /// the AST reader will not emit errors when producing that kind of failure.
   1336   enum LoadFailureCapabilities {
   1337     /// \brief The client can't handle any AST loading failures.
   1338     ARR_None = 0,
   1339     /// \brief The client can handle an AST file that cannot load because it
   1340     /// is missing.
   1341     ARR_Missing = 0x1,
   1342     /// \brief The client can handle an AST file that cannot load because it
   1343     /// is out-of-date relative to its input files.
   1344     ARR_OutOfDate = 0x2,
   1345     /// \brief The client can handle an AST file that cannot load because it
   1346     /// was built with a different version of Clang.
   1347     ARR_VersionMismatch = 0x4,
   1348     /// \brief The client can handle an AST file that cannot load because it's
   1349     /// compiled configuration doesn't match that of the context it was
   1350     /// loaded into.
   1351     ARR_ConfigurationMismatch = 0x8
   1352   };
   1353 
   1354   /// \brief Load the AST file designated by the given file name.
   1355   ///
   1356   /// \param FileName The name of the AST file to load.
   1357   ///
   1358   /// \param Type The kind of AST being loaded, e.g., PCH, module, main file,
   1359   /// or preamble.
   1360   ///
   1361   /// \param ImportLoc the location where the module file will be considered as
   1362   /// imported from. For non-module AST types it should be invalid.
   1363   ///
   1364   /// \param ClientLoadCapabilities The set of client load-failure
   1365   /// capabilities, represented as a bitset of the enumerators of
   1366   /// LoadFailureCapabilities.
   1367   ASTReadResult ReadAST(const std::string &FileName, ModuleKind Type,
   1368                         SourceLocation ImportLoc,
   1369                         unsigned ClientLoadCapabilities);
   1370 
   1371   /// \brief Make the entities in the given module and any of its (non-explicit)
   1372   /// submodules visible to name lookup.
   1373   ///
   1374   /// \param Mod The module whose names should be made visible.
   1375   ///
   1376   /// \param NameVisibility The level of visibility to give the names in the
   1377   /// module.  Visibility can only be increased over time.
   1378   ///
   1379   /// \param ImportLoc The location at which the import occurs.
   1380   void makeModuleVisible(Module *Mod,
   1381                          Module::NameVisibilityKind NameVisibility,
   1382                          SourceLocation ImportLoc);
   1383 
   1384   /// \brief Make the names within this set of hidden names visible.
   1385   void makeNamesVisible(const HiddenNames &Names, Module *Owner);
   1386 
   1387   /// \brief Take the AST callbacks listener.
   1388   std::unique_ptr<ASTReaderListener> takeListener() {
   1389     return std::move(Listener);
   1390   }
   1391 
   1392   /// \brief Set the AST callbacks listener.
   1393   void setListener(std::unique_ptr<ASTReaderListener> Listener) {
   1394     this->Listener = std::move(Listener);
   1395   }
   1396 
   1397   /// \brief Add an AST callback listener.
   1398   ///
   1399   /// Takes ownership of \p L.
   1400   void addListener(std::unique_ptr<ASTReaderListener> L) {
   1401     if (Listener)
   1402       L = llvm::make_unique<ChainedASTReaderListener>(std::move(L),
   1403                                                       std::move(Listener));
   1404     Listener = std::move(L);
   1405   }
   1406 
   1407   /// RAII object to temporarily add an AST callback listener.
   1408   class ListenerScope {
   1409     ASTReader &Reader;
   1410     bool Chained;
   1411 
   1412   public:
   1413     ListenerScope(ASTReader &Reader, std::unique_ptr<ASTReaderListener> L)
   1414         : Reader(Reader), Chained(false) {
   1415       auto Old = Reader.takeListener();
   1416       if (Old) {
   1417         Chained = true;
   1418         L = llvm::make_unique<ChainedASTReaderListener>(std::move(L),
   1419                                                         std::move(Old));
   1420       }
   1421       Reader.setListener(std::move(L));
   1422     }
   1423     ~ListenerScope() {
   1424       auto New = Reader.takeListener();
   1425       if (Chained)
   1426         Reader.setListener(static_cast<ChainedASTReaderListener *>(New.get())
   1427                                ->takeSecond());
   1428     }
   1429   };
   1430 
   1431   /// \brief Set the AST deserialization listener.
   1432   void setDeserializationListener(ASTDeserializationListener *Listener,
   1433                                   bool TakeOwnership = false);
   1434 
   1435   /// \brief Determine whether this AST reader has a global index.
   1436   bool hasGlobalIndex() const { return (bool)GlobalIndex; }
   1437 
   1438   /// \brief Return global module index.
   1439   GlobalModuleIndex *getGlobalIndex() { return GlobalIndex.get(); }
   1440 
   1441   /// \brief Reset reader for a reload try.
   1442   void resetForReload() { TriedLoadingGlobalIndex = false; }
   1443 
   1444   /// \brief Attempts to load the global index.
   1445   ///
   1446   /// \returns true if loading the global index has failed for any reason.
   1447   bool loadGlobalIndex();
   1448 
   1449   /// \brief Determine whether we tried to load the global index, but failed,
   1450   /// e.g., because it is out-of-date or does not exist.
   1451   bool isGlobalIndexUnavailable() const;
   1452 
   1453   /// \brief Initializes the ASTContext
   1454   void InitializeContext();
   1455 
   1456   /// \brief Update the state of Sema after loading some additional modules.
   1457   void UpdateSema();
   1458 
   1459   /// \brief Add in-memory (virtual file) buffer.
   1460   void addInMemoryBuffer(StringRef &FileName,
   1461                          std::unique_ptr<llvm::MemoryBuffer> Buffer) {
   1462     ModuleMgr.addInMemoryBuffer(FileName, std::move(Buffer));
   1463   }
   1464 
   1465   /// \brief Finalizes the AST reader's state before writing an AST file to
   1466   /// disk.
   1467   ///
   1468   /// This operation may undo temporary state in the AST that should not be
   1469   /// emitted.
   1470   void finalizeForWriting();
   1471 
   1472   /// \brief Retrieve the module manager.
   1473   ModuleManager &getModuleManager() { return ModuleMgr; }
   1474 
   1475   /// \brief Retrieve the preprocessor.
   1476   Preprocessor &getPreprocessor() const { return PP; }
   1477 
   1478   /// \brief Retrieve the name of the original source file name for the primary
   1479   /// module file.
   1480   StringRef getOriginalSourceFile() {
   1481     return ModuleMgr.getPrimaryModule().OriginalSourceFileName;
   1482   }
   1483 
   1484   /// \brief Retrieve the name of the original source file name directly from
   1485   /// the AST file, without actually loading the AST file.
   1486   static std::string
   1487   getOriginalSourceFile(const std::string &ASTFileName, FileManager &FileMgr,
   1488                         const PCHContainerReader &PCHContainerRdr,
   1489                         DiagnosticsEngine &Diags);
   1490 
   1491   /// \brief Read the control block for the named AST file.
   1492   ///
   1493   /// \returns true if an error occurred, false otherwise.
   1494   static bool
   1495   readASTFileControlBlock(StringRef Filename, FileManager &FileMgr,
   1496                           const PCHContainerReader &PCHContainerRdr,
   1497                           bool FindModuleFileExtensions,
   1498                           ASTReaderListener &Listener);
   1499 
   1500   /// \brief Determine whether the given AST file is acceptable to load into a
   1501   /// translation unit with the given language and target options.
   1502   static bool isAcceptableASTFile(StringRef Filename, FileManager &FileMgr,
   1503                                   const PCHContainerReader &PCHContainerRdr,
   1504                                   const LangOptions &LangOpts,
   1505                                   const TargetOptions &TargetOpts,
   1506                                   const PreprocessorOptions &PPOpts,
   1507                                   std::string ExistingModuleCachePath);
   1508 
   1509   /// \brief Returns the suggested contents of the predefines buffer,
   1510   /// which contains a (typically-empty) subset of the predefines
   1511   /// build prior to including the precompiled header.
   1512   const std::string &getSuggestedPredefines() { return SuggestedPredefines; }
   1513 
   1514   /// \brief Read a preallocated preprocessed entity from the external source.
   1515   ///
   1516   /// \returns null if an error occurred that prevented the preprocessed
   1517   /// entity from being loaded.
   1518   PreprocessedEntity *ReadPreprocessedEntity(unsigned Index) override;
   1519 
   1520   /// \brief Returns a pair of [Begin, End) indices of preallocated
   1521   /// preprocessed entities that \p Range encompasses.
   1522   std::pair<unsigned, unsigned>
   1523       findPreprocessedEntitiesInRange(SourceRange Range) override;
   1524 
   1525   /// \brief Optionally returns true or false if the preallocated preprocessed
   1526   /// entity with index \p Index came from file \p FID.
   1527   Optional<bool> isPreprocessedEntityInFileID(unsigned Index,
   1528                                               FileID FID) override;
   1529 
   1530   /// \brief Read the header file information for the given file entry.
   1531   HeaderFileInfo GetHeaderFileInfo(const FileEntry *FE) override;
   1532 
   1533   void ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag);
   1534 
   1535   /// \brief Returns the number of source locations found in the chain.
   1536   unsigned getTotalNumSLocs() const {
   1537     return TotalNumSLocEntries;
   1538   }
   1539 
   1540   /// \brief Returns the number of identifiers found in the chain.
   1541   unsigned getTotalNumIdentifiers() const {
   1542     return static_cast<unsigned>(IdentifiersLoaded.size());
   1543   }
   1544 
   1545   /// \brief Returns the number of macros found in the chain.
   1546   unsigned getTotalNumMacros() const {
   1547     return static_cast<unsigned>(MacrosLoaded.size());
   1548   }
   1549 
   1550   /// \brief Returns the number of types found in the chain.
   1551   unsigned getTotalNumTypes() const {
   1552     return static_cast<unsigned>(TypesLoaded.size());
   1553   }
   1554 
   1555   /// \brief Returns the number of declarations found in the chain.
   1556   unsigned getTotalNumDecls() const {
   1557     return static_cast<unsigned>(DeclsLoaded.size());
   1558   }
   1559 
   1560   /// \brief Returns the number of submodules known.
   1561   unsigned getTotalNumSubmodules() const {
   1562     return static_cast<unsigned>(SubmodulesLoaded.size());
   1563   }
   1564 
   1565   /// \brief Returns the number of selectors found in the chain.
   1566   unsigned getTotalNumSelectors() const {
   1567     return static_cast<unsigned>(SelectorsLoaded.size());
   1568   }
   1569 
   1570   /// \brief Returns the number of preprocessed entities known to the AST
   1571   /// reader.
   1572   unsigned getTotalNumPreprocessedEntities() const {
   1573     unsigned Result = 0;
   1574     for (ModuleConstIterator I = ModuleMgr.begin(),
   1575         E = ModuleMgr.end(); I != E; ++I) {
   1576       Result += (*I)->NumPreprocessedEntities;
   1577     }
   1578 
   1579     return Result;
   1580   }
   1581 
   1582   /// \brief Reads a TemplateArgumentLocInfo appropriate for the
   1583   /// given TemplateArgument kind.
   1584   TemplateArgumentLocInfo
   1585   GetTemplateArgumentLocInfo(ModuleFile &F, TemplateArgument::ArgKind Kind,
   1586                              const RecordData &Record, unsigned &Idx);
   1587 
   1588   /// \brief Reads a TemplateArgumentLoc.
   1589   TemplateArgumentLoc
   1590   ReadTemplateArgumentLoc(ModuleFile &F,
   1591                           const RecordData &Record, unsigned &Idx);
   1592 
   1593   const ASTTemplateArgumentListInfo*
   1594   ReadASTTemplateArgumentListInfo(ModuleFile &F,
   1595                                   const RecordData &Record, unsigned &Index);
   1596 
   1597   /// \brief Reads a declarator info from the given record.
   1598   TypeSourceInfo *GetTypeSourceInfo(ModuleFile &F,
   1599                                     const RecordData &Record, unsigned &Idx);
   1600 
   1601   /// \brief Resolve a type ID into a type, potentially building a new
   1602   /// type.
   1603   QualType GetType(serialization::TypeID ID);
   1604 
   1605   /// \brief Resolve a local type ID within a given AST file into a type.
   1606   QualType getLocalType(ModuleFile &F, unsigned LocalID);
   1607 
   1608   /// \brief Map a local type ID within a given AST file into a global type ID.
   1609   serialization::TypeID getGlobalTypeID(ModuleFile &F, unsigned LocalID) const;
   1610 
   1611   /// \brief Read a type from the current position in the given record, which
   1612   /// was read from the given AST file.
   1613   QualType readType(ModuleFile &F, const RecordData &Record, unsigned &Idx) {
   1614     if (Idx >= Record.size())
   1615       return QualType();
   1616 
   1617     return getLocalType(F, Record[Idx++]);
   1618   }
   1619 
   1620   /// \brief Map from a local declaration ID within a given module to a
   1621   /// global declaration ID.
   1622   serialization::DeclID getGlobalDeclID(ModuleFile &F,
   1623                                       serialization::LocalDeclID LocalID) const;
   1624 
   1625   /// \brief Returns true if global DeclID \p ID originated from module \p M.
   1626   bool isDeclIDFromModule(serialization::GlobalDeclID ID, ModuleFile &M) const;
   1627 
   1628   /// \brief Retrieve the module file that owns the given declaration, or NULL
   1629   /// if the declaration is not from a module file.
   1630   ModuleFile *getOwningModuleFile(const Decl *D);
   1631 
   1632   /// \brief Get the best name we know for the module that owns the given
   1633   /// declaration, or an empty string if the declaration is not from a module.
   1634   std::string getOwningModuleNameForDiagnostic(const Decl *D);
   1635 
   1636   /// \brief Returns the source location for the decl \p ID.
   1637   SourceLocation getSourceLocationForDeclID(serialization::GlobalDeclID ID);
   1638 
   1639   /// \brief Resolve a declaration ID into a declaration, potentially
   1640   /// building a new declaration.
   1641   Decl *GetDecl(serialization::DeclID ID);
   1642   Decl *GetExternalDecl(uint32_t ID) override;
   1643 
   1644   /// \brief Resolve a declaration ID into a declaration. Return 0 if it's not
   1645   /// been loaded yet.
   1646   Decl *GetExistingDecl(serialization::DeclID ID);
   1647 
   1648   /// \brief Reads a declaration with the given local ID in the given module.
   1649   Decl *GetLocalDecl(ModuleFile &F, uint32_t LocalID) {
   1650     return GetDecl(getGlobalDeclID(F, LocalID));
   1651   }
   1652 
   1653   /// \brief Reads a declaration with the given local ID in the given module.
   1654   ///
   1655   /// \returns The requested declaration, casted to the given return type.
   1656   template<typename T>
   1657   T *GetLocalDeclAs(ModuleFile &F, uint32_t LocalID) {
   1658     return cast_or_null<T>(GetLocalDecl(F, LocalID));
   1659   }
   1660 
   1661   /// \brief Map a global declaration ID into the declaration ID used to
   1662   /// refer to this declaration within the given module fule.
   1663   ///
   1664   /// \returns the global ID of the given declaration as known in the given
   1665   /// module file.
   1666   serialization::DeclID
   1667   mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
   1668                                   serialization::DeclID GlobalID);
   1669 
   1670   /// \brief Reads a declaration ID from the given position in a record in the
   1671   /// given module.
   1672   ///
   1673   /// \returns The declaration ID read from the record, adjusted to a global ID.
   1674   serialization::DeclID ReadDeclID(ModuleFile &F, const RecordData &Record,
   1675                                    unsigned &Idx);
   1676 
   1677   /// \brief Reads a declaration from the given position in a record in the
   1678   /// given module.
   1679   Decl *ReadDecl(ModuleFile &F, const RecordData &R, unsigned &I) {
   1680     return GetDecl(ReadDeclID(F, R, I));
   1681   }
   1682 
   1683   /// \brief Reads a declaration from the given position in a record in the
   1684   /// given module.
   1685   ///
   1686   /// \returns The declaration read from this location, casted to the given
   1687   /// result type.
   1688   template<typename T>
   1689   T *ReadDeclAs(ModuleFile &F, const RecordData &R, unsigned &I) {
   1690     return cast_or_null<T>(GetDecl(ReadDeclID(F, R, I)));
   1691   }
   1692 
   1693   /// \brief If any redeclarations of \p D have been imported since it was
   1694   /// last checked, this digs out those redeclarations and adds them to the
   1695   /// redeclaration chain for \p D.
   1696   void CompleteRedeclChain(const Decl *D) override;
   1697 
   1698   /// \brief Read a CXXBaseSpecifiers ID form the given record and
   1699   /// return its global bit offset.
   1700   uint64_t readCXXBaseSpecifiers(ModuleFile &M, const RecordData &Record,
   1701                                  unsigned &Idx);
   1702 
   1703   CXXBaseSpecifier *GetExternalCXXBaseSpecifiers(uint64_t Offset) override;
   1704 
   1705   /// \brief Resolve the offset of a statement into a statement.
   1706   ///
   1707   /// This operation will read a new statement from the external
   1708   /// source each time it is called, and is meant to be used via a
   1709   /// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
   1710   Stmt *GetExternalDeclStmt(uint64_t Offset) override;
   1711 
   1712   /// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
   1713   /// specified cursor.  Read the abbreviations that are at the top of the block
   1714   /// and then leave the cursor pointing into the block.
   1715   static bool ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor, unsigned BlockID);
   1716 
   1717   /// \brief Finds all the visible declarations with a given name.
   1718   /// The current implementation of this method just loads the entire
   1719   /// lookup table as unmaterialized references.
   1720   bool FindExternalVisibleDeclsByName(const DeclContext *DC,
   1721                                       DeclarationName Name) override;
   1722 
   1723   /// \brief Read all of the declarations lexically stored in a
   1724   /// declaration context.
   1725   ///
   1726   /// \param DC The declaration context whose declarations will be
   1727   /// read.
   1728   ///
   1729   /// \param IsKindWeWant A predicate indicating which declaration kinds
   1730   /// we are interested in.
   1731   ///
   1732   /// \param Decls Vector that will contain the declarations loaded
   1733   /// from the external source. The caller is responsible for merging
   1734   /// these declarations with any declarations already stored in the
   1735   /// declaration context.
   1736   void
   1737   FindExternalLexicalDecls(const DeclContext *DC,
   1738                            llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
   1739                            SmallVectorImpl<Decl *> &Decls) override;
   1740 
   1741   /// \brief Get the decls that are contained in a file in the Offset/Length
   1742   /// range. \p Length can be 0 to indicate a point at \p Offset instead of
   1743   /// a range.
   1744   void FindFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
   1745                            SmallVectorImpl<Decl *> &Decls) override;
   1746 
   1747   /// \brief Notify ASTReader that we started deserialization of
   1748   /// a decl or type so until FinishedDeserializing is called there may be
   1749   /// decls that are initializing. Must be paired with FinishedDeserializing.
   1750   void StartedDeserializing() override;
   1751 
   1752   /// \brief Notify ASTReader that we finished the deserialization of
   1753   /// a decl or type. Must be paired with StartedDeserializing.
   1754   void FinishedDeserializing() override;
   1755 
   1756   /// \brief Function that will be invoked when we begin parsing a new
   1757   /// translation unit involving this external AST source.
   1758   ///
   1759   /// This function will provide all of the external definitions to
   1760   /// the ASTConsumer.
   1761   void StartTranslationUnit(ASTConsumer *Consumer) override;
   1762 
   1763   /// \brief Print some statistics about AST usage.
   1764   void PrintStats() override;
   1765 
   1766   /// \brief Dump information about the AST reader to standard error.
   1767   void dump();
   1768 
   1769   /// Return the amount of memory used by memory buffers, breaking down
   1770   /// by heap-backed versus mmap'ed memory.
   1771   void getMemoryBufferSizes(MemoryBufferSizes &sizes) const override;
   1772 
   1773   /// \brief Initialize the semantic source with the Sema instance
   1774   /// being used to perform semantic analysis on the abstract syntax
   1775   /// tree.
   1776   void InitializeSema(Sema &S) override;
   1777 
   1778   /// \brief Inform the semantic consumer that Sema is no longer available.
   1779   void ForgetSema() override { SemaObj = nullptr; }
   1780 
   1781   /// \brief Retrieve the IdentifierInfo for the named identifier.
   1782   ///
   1783   /// This routine builds a new IdentifierInfo for the given identifier. If any
   1784   /// declarations with this name are visible from translation unit scope, their
   1785   /// declarations will be deserialized and introduced into the declaration
   1786   /// chain of the identifier.
   1787   IdentifierInfo *get(StringRef Name) override;
   1788 
   1789   /// \brief Retrieve an iterator into the set of all identifiers
   1790   /// in all loaded AST files.
   1791   IdentifierIterator *getIdentifiers() override;
   1792 
   1793   /// \brief Load the contents of the global method pool for a given
   1794   /// selector.
   1795   void ReadMethodPool(Selector Sel) override;
   1796 
   1797   /// \brief Load the set of namespaces that are known to the external source,
   1798   /// which will be used during typo correction.
   1799   void ReadKnownNamespaces(
   1800                          SmallVectorImpl<NamespaceDecl *> &Namespaces) override;
   1801 
   1802   void ReadUndefinedButUsed(
   1803                llvm::DenseMap<NamedDecl *, SourceLocation> &Undefined) override;
   1804 
   1805   void ReadMismatchingDeleteExpressions(llvm::MapVector<
   1806       FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
   1807                                             Exprs) override;
   1808 
   1809   void ReadTentativeDefinitions(
   1810                             SmallVectorImpl<VarDecl *> &TentativeDefs) override;
   1811 
   1812   void ReadUnusedFileScopedDecls(
   1813                        SmallVectorImpl<const DeclaratorDecl *> &Decls) override;
   1814 
   1815   void ReadDelegatingConstructors(
   1816                          SmallVectorImpl<CXXConstructorDecl *> &Decls) override;
   1817 
   1818   void ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) override;
   1819 
   1820   void ReadUnusedLocalTypedefNameCandidates(
   1821       llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) override;
   1822 
   1823   void ReadReferencedSelectors(
   1824           SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) override;
   1825 
   1826   void ReadWeakUndeclaredIdentifiers(
   1827           SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WI) override;
   1828 
   1829   void ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) override;
   1830 
   1831   void ReadPendingInstantiations(
   1832                  SmallVectorImpl<std::pair<ValueDecl *,
   1833                                            SourceLocation> > &Pending) override;
   1834 
   1835   void ReadLateParsedTemplates(
   1836       llvm::MapVector<const FunctionDecl *, LateParsedTemplate *> &LPTMap)
   1837       override;
   1838 
   1839   /// \brief Load a selector from disk, registering its ID if it exists.
   1840   void LoadSelector(Selector Sel);
   1841 
   1842   void SetIdentifierInfo(unsigned ID, IdentifierInfo *II);
   1843   void SetGloballyVisibleDecls(IdentifierInfo *II,
   1844                                const SmallVectorImpl<uint32_t> &DeclIDs,
   1845                                SmallVectorImpl<Decl *> *Decls = nullptr);
   1846 
   1847   /// \brief Report a diagnostic.
   1848   DiagnosticBuilder Diag(unsigned DiagID);
   1849 
   1850   /// \brief Report a diagnostic.
   1851   DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
   1852 
   1853   IdentifierInfo *DecodeIdentifierInfo(serialization::IdentifierID ID);
   1854 
   1855   IdentifierInfo *GetIdentifierInfo(ModuleFile &M, const RecordData &Record,
   1856                                     unsigned &Idx) {
   1857     return DecodeIdentifierInfo(getGlobalIdentifierID(M, Record[Idx++]));
   1858   }
   1859 
   1860   IdentifierInfo *GetIdentifier(serialization::IdentifierID ID) override {
   1861     // Note that we are loading an identifier.
   1862     Deserializing AnIdentifier(this);
   1863 
   1864     return DecodeIdentifierInfo(ID);
   1865   }
   1866 
   1867   IdentifierInfo *getLocalIdentifier(ModuleFile &M, unsigned LocalID);
   1868 
   1869   serialization::IdentifierID getGlobalIdentifierID(ModuleFile &M,
   1870                                                     unsigned LocalID);
   1871 
   1872   void resolvePendingMacro(IdentifierInfo *II, const PendingMacroInfo &PMInfo);
   1873 
   1874   /// \brief Retrieve the macro with the given ID.
   1875   MacroInfo *getMacro(serialization::MacroID ID);
   1876 
   1877   /// \brief Retrieve the global macro ID corresponding to the given local
   1878   /// ID within the given module file.
   1879   serialization::MacroID getGlobalMacroID(ModuleFile &M, unsigned LocalID);
   1880 
   1881   /// \brief Read the source location entry with index ID.
   1882   bool ReadSLocEntry(int ID) override;
   1883 
   1884   /// \brief Retrieve the module import location and module name for the
   1885   /// given source manager entry ID.
   1886   std::pair<SourceLocation, StringRef> getModuleImportLoc(int ID) override;
   1887 
   1888   /// \brief Retrieve the global submodule ID given a module and its local ID
   1889   /// number.
   1890   serialization::SubmoduleID
   1891   getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID);
   1892 
   1893   /// \brief Retrieve the submodule that corresponds to a global submodule ID.
   1894   ///
   1895   Module *getSubmodule(serialization::SubmoduleID GlobalID);
   1896 
   1897   /// \brief Retrieve the module that corresponds to the given module ID.
   1898   ///
   1899   /// Note: overrides method in ExternalASTSource
   1900   Module *getModule(unsigned ID) override;
   1901 
   1902   /// \brief Retrieve the module file with a given local ID within the specified
   1903   /// ModuleFile.
   1904   ModuleFile *getLocalModuleFile(ModuleFile &M, unsigned ID);
   1905 
   1906   /// \brief Get an ID for the given module file.
   1907   unsigned getModuleFileID(ModuleFile *M);
   1908 
   1909   /// \brief Return a descriptor for the corresponding module.
   1910   llvm::Optional<ASTSourceDescriptor> getSourceDescriptor(unsigned ID) override;
   1911 
   1912   /// \brief Retrieve a selector from the given module with its local ID
   1913   /// number.
   1914   Selector getLocalSelector(ModuleFile &M, unsigned LocalID);
   1915 
   1916   Selector DecodeSelector(serialization::SelectorID Idx);
   1917 
   1918   Selector GetExternalSelector(serialization::SelectorID ID) override;
   1919   uint32_t GetNumExternalSelectors() override;
   1920 
   1921   Selector ReadSelector(ModuleFile &M, const RecordData &Record, unsigned &Idx) {
   1922     return getLocalSelector(M, Record[Idx++]);
   1923   }
   1924 
   1925   /// \brief Retrieve the global selector ID that corresponds to this
   1926   /// the local selector ID in a given module.
   1927   serialization::SelectorID getGlobalSelectorID(ModuleFile &F,
   1928                                                 unsigned LocalID) const;
   1929 
   1930   /// \brief Read a declaration name.
   1931   DeclarationName ReadDeclarationName(ModuleFile &F,
   1932                                       const RecordData &Record, unsigned &Idx);
   1933   void ReadDeclarationNameLoc(ModuleFile &F,
   1934                               DeclarationNameLoc &DNLoc, DeclarationName Name,
   1935                               const RecordData &Record, unsigned &Idx);
   1936   void ReadDeclarationNameInfo(ModuleFile &F, DeclarationNameInfo &NameInfo,
   1937                                const RecordData &Record, unsigned &Idx);
   1938 
   1939   void ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
   1940                          const RecordData &Record, unsigned &Idx);
   1941 
   1942   NestedNameSpecifier *ReadNestedNameSpecifier(ModuleFile &F,
   1943                                                const RecordData &Record,
   1944                                                unsigned &Idx);
   1945 
   1946   NestedNameSpecifierLoc ReadNestedNameSpecifierLoc(ModuleFile &F,
   1947                                                     const RecordData &Record,
   1948                                                     unsigned &Idx);
   1949 
   1950   /// \brief Read a template name.
   1951   TemplateName ReadTemplateName(ModuleFile &F, const RecordData &Record,
   1952                                 unsigned &Idx);
   1953 
   1954   /// \brief Read a template argument.
   1955   TemplateArgument ReadTemplateArgument(ModuleFile &F, const RecordData &Record,
   1956                                         unsigned &Idx,
   1957                                         bool Canonicalize = false);
   1958 
   1959   /// \brief Read a template parameter list.
   1960   TemplateParameterList *ReadTemplateParameterList(ModuleFile &F,
   1961                                                    const RecordData &Record,
   1962                                                    unsigned &Idx);
   1963 
   1964   /// \brief Read a template argument array.
   1965   void ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
   1966                                 ModuleFile &F, const RecordData &Record,
   1967                                 unsigned &Idx, bool Canonicalize = false);
   1968 
   1969   /// \brief Read a UnresolvedSet structure.
   1970   void ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
   1971                          const RecordData &Record, unsigned &Idx);
   1972 
   1973   /// \brief Read a C++ base specifier.
   1974   CXXBaseSpecifier ReadCXXBaseSpecifier(ModuleFile &F,
   1975                                         const RecordData &Record,unsigned &Idx);
   1976 
   1977   /// \brief Read a CXXCtorInitializer array.
   1978   CXXCtorInitializer **
   1979   ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
   1980                           unsigned &Idx);
   1981 
   1982   /// \brief Read a CXXCtorInitializers ID from the given record and
   1983   /// return its global bit offset.
   1984   uint64_t ReadCXXCtorInitializersRef(ModuleFile &M, const RecordData &Record,
   1985                                       unsigned &Idx);
   1986 
   1987   /// \brief Read the contents of a CXXCtorInitializer array.
   1988   CXXCtorInitializer **GetExternalCXXCtorInitializers(uint64_t Offset) override;
   1989 
   1990   /// \brief Read a source location from raw form.
   1991   SourceLocation ReadSourceLocation(ModuleFile &ModuleFile, unsigned Raw) const {
   1992     SourceLocation Loc = SourceLocation::getFromRawEncoding(Raw);
   1993     assert(ModuleFile.SLocRemap.find(Loc.getOffset()) != ModuleFile.SLocRemap.end() &&
   1994            "Cannot find offset to remap.");
   1995     int Remap = ModuleFile.SLocRemap.find(Loc.getOffset())->second;
   1996     return Loc.getLocWithOffset(Remap);
   1997   }
   1998 
   1999   /// \brief Read a source location.
   2000   SourceLocation ReadSourceLocation(ModuleFile &ModuleFile,
   2001                                     const RecordDataImpl &Record,
   2002                                     unsigned &Idx) {
   2003     return ReadSourceLocation(ModuleFile, Record[Idx++]);
   2004   }
   2005 
   2006   /// \brief Read a source range.
   2007   SourceRange ReadSourceRange(ModuleFile &F,
   2008                               const RecordData &Record, unsigned &Idx);
   2009 
   2010   /// \brief Read an integral value
   2011   llvm::APInt ReadAPInt(const RecordData &Record, unsigned &Idx);
   2012 
   2013   /// \brief Read a signed integral value
   2014   llvm::APSInt ReadAPSInt(const RecordData &Record, unsigned &Idx);
   2015 
   2016   /// \brief Read a floating-point value
   2017   llvm::APFloat ReadAPFloat(const RecordData &Record,
   2018                             const llvm::fltSemantics &Sem, unsigned &Idx);
   2019 
   2020   // \brief Read a string
   2021   static std::string ReadString(const RecordData &Record, unsigned &Idx);
   2022 
   2023   // \brief Read a path
   2024   std::string ReadPath(ModuleFile &F, const RecordData &Record, unsigned &Idx);
   2025 
   2026   /// \brief Read a version tuple.
   2027   static VersionTuple ReadVersionTuple(const RecordData &Record, unsigned &Idx);
   2028 
   2029   CXXTemporary *ReadCXXTemporary(ModuleFile &F, const RecordData &Record,
   2030                                  unsigned &Idx);
   2031 
   2032   /// \brief Reads attributes from the current stream position.
   2033   void ReadAttributes(ModuleFile &F, AttrVec &Attrs,
   2034                       const RecordData &Record, unsigned &Idx);
   2035 
   2036   /// \brief Reads a statement.
   2037   Stmt *ReadStmt(ModuleFile &F);
   2038 
   2039   /// \brief Reads an expression.
   2040   Expr *ReadExpr(ModuleFile &F);
   2041 
   2042   /// \brief Reads a sub-statement operand during statement reading.
   2043   Stmt *ReadSubStmt() {
   2044     assert(ReadingKind == Read_Stmt &&
   2045            "Should be called only during statement reading!");
   2046     // Subexpressions are stored from last to first, so the next Stmt we need
   2047     // is at the back of the stack.
   2048     assert(!StmtStack.empty() && "Read too many sub-statements!");
   2049     return StmtStack.pop_back_val();
   2050   }
   2051 
   2052   /// \brief Reads a sub-expression operand during statement reading.
   2053   Expr *ReadSubExpr();
   2054 
   2055   /// \brief Reads a token out of a record.
   2056   Token ReadToken(ModuleFile &M, const RecordDataImpl &Record, unsigned &Idx);
   2057 
   2058   /// \brief Reads the macro record located at the given offset.
   2059   MacroInfo *ReadMacroRecord(ModuleFile &F, uint64_t Offset);
   2060 
   2061   /// \brief Determine the global preprocessed entity ID that corresponds to
   2062   /// the given local ID within the given module.
   2063   serialization::PreprocessedEntityID
   2064   getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const;
   2065 
   2066   /// \brief Add a macro to deserialize its macro directive history.
   2067   ///
   2068   /// \param II The name of the macro.
   2069   /// \param M The module file.
   2070   /// \param MacroDirectivesOffset Offset of the serialized macro directive
   2071   /// history.
   2072   void addPendingMacro(IdentifierInfo *II, ModuleFile *M,
   2073                        uint64_t MacroDirectivesOffset);
   2074 
   2075   /// \brief Read the set of macros defined by this external macro source.
   2076   void ReadDefinedMacros() override;
   2077 
   2078   /// \brief Update an out-of-date identifier.
   2079   void updateOutOfDateIdentifier(IdentifierInfo &II) override;
   2080 
   2081   /// \brief Note that this identifier is up-to-date.
   2082   void markIdentifierUpToDate(IdentifierInfo *II);
   2083 
   2084   /// \brief Load all external visible decls in the given DeclContext.
   2085   void completeVisibleDeclsMap(const DeclContext *DC) override;
   2086 
   2087   /// \brief Retrieve the AST context that this AST reader supplements.
   2088   ASTContext &getContext() { return Context; }
   2089 
   2090   // \brief Contains the IDs for declarations that were requested before we have
   2091   // access to a Sema object.
   2092   SmallVector<uint64_t, 16> PreloadedDeclIDs;
   2093 
   2094   /// \brief Retrieve the semantic analysis object used to analyze the
   2095   /// translation unit in which the precompiled header is being
   2096   /// imported.
   2097   Sema *getSema() { return SemaObj; }
   2098 
   2099   /// \brief Retrieve the identifier table associated with the
   2100   /// preprocessor.
   2101   IdentifierTable &getIdentifierTable();
   2102 
   2103   /// \brief Record that the given ID maps to the given switch-case
   2104   /// statement.
   2105   void RecordSwitchCaseID(SwitchCase *SC, unsigned ID);
   2106 
   2107   /// \brief Retrieve the switch-case statement with the given ID.
   2108   SwitchCase *getSwitchCaseWithID(unsigned ID);
   2109 
   2110   void ClearSwitchCaseIDs();
   2111 
   2112   /// \brief Cursors for comments blocks.
   2113   SmallVector<std::pair<llvm::BitstreamCursor,
   2114                         serialization::ModuleFile *>, 8> CommentsCursors;
   2115 
   2116   /// \brief Loads comments ranges.
   2117   void ReadComments() override;
   2118 };
   2119 
   2120 /// \brief Helper class that saves the current stream position and
   2121 /// then restores it when destroyed.
   2122 struct SavedStreamPosition {
   2123   explicit SavedStreamPosition(llvm::BitstreamCursor &Cursor)
   2124     : Cursor(Cursor), Offset(Cursor.GetCurrentBitNo()) { }
   2125 
   2126   ~SavedStreamPosition() {
   2127     Cursor.JumpToBit(Offset);
   2128   }
   2129 
   2130 private:
   2131   llvm::BitstreamCursor &Cursor;
   2132   uint64_t Offset;
   2133 };
   2134 
   2135 inline void PCHValidator::Error(const char *Msg) {
   2136   Reader.Error(Msg);
   2137 }
   2138 
   2139 } // end namespace clang
   2140 
   2141 #endif
   2142