clang API Documentation

ASTReader.h
Go to the documentation of this file.
00001 //===--- ASTReader.h - AST File Reader --------------------------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 //  This file defines the ASTReader class, which reads AST files.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #ifndef LLVM_CLANG_SERIALIZATION_ASTREADER_H
00015 #define LLVM_CLANG_SERIALIZATION_ASTREADER_H
00016 
00017 #include "clang/AST/DeclObjC.h"
00018 #include "clang/AST/DeclarationName.h"
00019 #include "clang/AST/TemplateBase.h"
00020 #include "clang/Basic/Diagnostic.h"
00021 #include "clang/Basic/FileManager.h"
00022 #include "clang/Basic/FileSystemOptions.h"
00023 #include "clang/Basic/IdentifierTable.h"
00024 #include "clang/Basic/SourceManager.h"
00025 #include "clang/Basic/Version.h"
00026 #include "clang/Lex/ExternalPreprocessorSource.h"
00027 #include "clang/Lex/HeaderSearch.h"
00028 #include "clang/Lex/PreprocessingRecord.h"
00029 #include "clang/Sema/ExternalSemaSource.h"
00030 #include "clang/Serialization/ASTBitCodes.h"
00031 #include "clang/Serialization/ContinuousRangeMap.h"
00032 #include "clang/Serialization/Module.h"
00033 #include "clang/Serialization/ModuleManager.h"
00034 #include "llvm/ADT/APFloat.h"
00035 #include "llvm/ADT/APInt.h"
00036 #include "llvm/ADT/APSInt.h"
00037 #include "llvm/ADT/MapVector.h"
00038 #include "llvm/ADT/SmallPtrSet.h"
00039 #include "llvm/ADT/SmallSet.h"
00040 #include "llvm/ADT/SmallVector.h"
00041 #include "llvm/ADT/StringRef.h"
00042 #include "llvm/ADT/TinyPtrVector.h"
00043 #include "llvm/Bitcode/BitstreamReader.h"
00044 #include "llvm/Support/DataTypes.h"
00045 #include <deque>
00046 #include <map>
00047 #include <memory>
00048 #include <string>
00049 #include <utility>
00050 #include <vector>
00051 
00052 namespace llvm {
00053   class MemoryBuffer;
00054 }
00055 
00056 namespace clang {
00057 
00058 class AddrLabelExpr;
00059 class ASTConsumer;
00060 class ASTContext;
00061 class ASTIdentifierIterator;
00062 class ASTUnit; // FIXME: Layering violation and egregious hack.
00063 class Attr;
00064 class Decl;
00065 class DeclContext;
00066 class DefMacroDirective;
00067 class DiagnosticOptions;
00068 class NestedNameSpecifier;
00069 class CXXBaseSpecifier;
00070 class CXXConstructorDecl;
00071 class CXXCtorInitializer;
00072 class GlobalModuleIndex;
00073 class GotoStmt;
00074 class MacroDefinition;
00075 class MacroDirective;
00076 class NamedDecl;
00077 class OpaqueValueExpr;
00078 class Preprocessor;
00079 class PreprocessorOptions;
00080 class Sema;
00081 class SwitchCase;
00082 class ASTDeserializationListener;
00083 class ASTWriter;
00084 class ASTReader;
00085 class ASTDeclReader;
00086 class ASTStmtReader;
00087 class TypeLocReader;
00088 struct HeaderFileInfo;
00089 class VersionTuple;
00090 class TargetOptions;
00091 class LazyASTUnresolvedSet;
00092 
00093 /// \brief Abstract interface for callback invocations by the ASTReader.
00094 ///
00095 /// While reading an AST file, the ASTReader will call the methods of the
00096 /// listener to pass on specific information. Some of the listener methods can
00097 /// return true to indicate to the ASTReader that the information (and
00098 /// consequently the AST file) is invalid.
00099 class ASTReaderListener {
00100 public:
00101   virtual ~ASTReaderListener();
00102 
00103   /// \brief Receives the full Clang version information.
00104   ///
00105   /// \returns true to indicate that the version is invalid. Subclasses should
00106   /// generally defer to this implementation.
00107   virtual bool ReadFullVersionInformation(StringRef FullVersion) {
00108     return FullVersion != getClangFullRepositoryVersion();
00109   }
00110 
00111   virtual void ReadModuleName(StringRef ModuleName) {}
00112   virtual void ReadModuleMapFile(StringRef ModuleMapPath) {}
00113 
00114   /// \brief Receives the language options.
00115   ///
00116   /// \returns true to indicate the options are invalid or false otherwise.
00117   virtual bool ReadLanguageOptions(const LangOptions &LangOpts,
00118                                    bool Complain,
00119                                    bool AllowCompatibleDifferences) {
00120     return false;
00121   }
00122 
00123   /// \brief Receives the target options.
00124   ///
00125   /// \returns true to indicate the target options are invalid, or false
00126   /// otherwise.
00127   virtual bool ReadTargetOptions(const TargetOptions &TargetOpts,
00128                                  bool Complain) {
00129     return false;
00130   }
00131 
00132   /// \brief Receives the diagnostic options.
00133   ///
00134   /// \returns true to indicate the diagnostic options are invalid, or false
00135   /// otherwise.
00136   virtual bool
00137   ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
00138                         bool Complain) {
00139     return false;
00140   }
00141 
00142   /// \brief Receives the file system options.
00143   ///
00144   /// \returns true to indicate the file system options are invalid, or false
00145   /// otherwise.
00146   virtual bool ReadFileSystemOptions(const FileSystemOptions &FSOpts,
00147                                      bool Complain) {
00148     return false;
00149   }
00150 
00151   /// \brief Receives the header search options.
00152   ///
00153   /// \returns true to indicate the header search options are invalid, or false
00154   /// otherwise.
00155   virtual bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
00156                                        bool Complain) {
00157     return false;
00158   }
00159 
00160   /// \brief Receives the preprocessor options.
00161   ///
00162   /// \param SuggestedPredefines Can be filled in with the set of predefines
00163   /// that are suggested by the preprocessor options. Typically only used when
00164   /// loading a precompiled header.
00165   ///
00166   /// \returns true to indicate the preprocessor options are invalid, or false
00167   /// otherwise.
00168   virtual bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
00169                                        bool Complain,
00170                                        std::string &SuggestedPredefines) {
00171     return false;
00172   }
00173 
00174   /// \brief Receives __COUNTER__ value.
00175   virtual void ReadCounter(const serialization::ModuleFile &M,
00176                            unsigned Value) {}
00177 
00178   /// This is called for each AST file loaded.
00179   virtual void visitModuleFile(StringRef Filename) {}
00180 
00181   /// \brief Returns true if this \c ASTReaderListener wants to receive the
00182   /// input files of the AST file via \c visitInputFile, false otherwise.
00183   virtual bool needsInputFileVisitation() { return false; }
00184   /// \brief Returns true if this \c ASTReaderListener wants to receive the
00185   /// system input files of the AST file via \c visitInputFile, false otherwise.
00186   virtual bool needsSystemInputFileVisitation() { return false; }
00187   /// \brief if \c needsInputFileVisitation returns true, this is called for
00188   /// each non-system input file of the AST File. If
00189   /// \c needsSystemInputFileVisitation is true, then it is called for all
00190   /// system input files as well.
00191   ///
00192   /// \returns true to continue receiving the next input file, false to stop.
00193   virtual bool visitInputFile(StringRef Filename, bool isSystem,
00194                               bool isOverridden) {
00195     return true;
00196   }
00197 
00198   /// \brief Returns true if this \c ASTReaderListener wants to receive the
00199   /// imports of the AST file via \c visitImport, false otherwise.
00200   virtual bool needsImportVisitation() const { return false; }
00201   /// \brief If needsImportVisitation returns \c true, this is called for each
00202   /// AST file imported by this AST file.
00203   virtual void visitImport(StringRef Filename) {}
00204 };
00205 
00206 /// \brief Simple wrapper class for chaining listeners.
00207 class ChainedASTReaderListener : public ASTReaderListener {
00208   std::unique_ptr<ASTReaderListener> First;
00209   std::unique_ptr<ASTReaderListener> Second;
00210 
00211 public:
00212   /// Takes ownership of \p First and \p Second.
00213   ChainedASTReaderListener(std::unique_ptr<ASTReaderListener> First,
00214                            std::unique_ptr<ASTReaderListener> Second)
00215       : First(std::move(First)), Second(std::move(Second)) {}
00216 
00217   std::unique_ptr<ASTReaderListener> takeFirst() { return std::move(First); }
00218   std::unique_ptr<ASTReaderListener> takeSecond() { return std::move(Second); }
00219 
00220   bool ReadFullVersionInformation(StringRef FullVersion) override;
00221   void ReadModuleName(StringRef ModuleName) override;
00222   void ReadModuleMapFile(StringRef ModuleMapPath) override;
00223   bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
00224                            bool AllowCompatibleDifferences) override;
00225   bool ReadTargetOptions(const TargetOptions &TargetOpts,
00226                          bool Complain) override;
00227   bool ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
00228                              bool Complain) override;
00229   bool ReadFileSystemOptions(const FileSystemOptions &FSOpts,
00230                              bool Complain) override;
00231 
00232   bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
00233                                bool Complain) override;
00234   bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
00235                                bool Complain,
00236                                std::string &SuggestedPredefines) override;
00237 
00238   void ReadCounter(const serialization::ModuleFile &M, unsigned Value) override;
00239   bool needsInputFileVisitation() override;
00240   bool needsSystemInputFileVisitation() override;
00241   void visitModuleFile(StringRef Filename) override;
00242   bool visitInputFile(StringRef Filename, bool isSystem,
00243                       bool isOverridden) override;
00244 };
00245 
00246 /// \brief ASTReaderListener implementation to validate the information of
00247 /// the PCH file against an initialized Preprocessor.
00248 class PCHValidator : public ASTReaderListener {
00249   Preprocessor &PP;
00250   ASTReader &Reader;
00251 
00252 public:
00253   PCHValidator(Preprocessor &PP, ASTReader &Reader)
00254     : PP(PP), Reader(Reader) {}
00255 
00256   bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
00257                            bool AllowCompatibleDifferences) override;
00258   bool ReadTargetOptions(const TargetOptions &TargetOpts,
00259                          bool Complain) override;
00260   bool ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
00261                              bool Complain) override;
00262   bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool Complain,
00263                                std::string &SuggestedPredefines) override;
00264   void ReadCounter(const serialization::ModuleFile &M, unsigned Value) override;
00265 
00266 private:
00267   void Error(const char *Msg);
00268 };
00269 
00270 namespace serialization {
00271 
00272 class ReadMethodPoolVisitor;
00273 
00274 namespace reader {
00275   class ASTIdentifierLookupTrait;
00276   /// \brief The on-disk hash table used for the DeclContext's Name lookup table.
00277   typedef llvm::OnDiskIterableChainedHashTable<ASTDeclContextNameLookupTrait>
00278     ASTDeclContextNameLookupTable;
00279 }
00280 
00281 } // end namespace serialization
00282 
00283 /// \brief Reads an AST files chain containing the contents of a translation
00284 /// unit.
00285 ///
00286 /// The ASTReader class reads bitstreams (produced by the ASTWriter
00287 /// class) containing the serialized representation of a given
00288 /// abstract syntax tree and its supporting data structures. An
00289 /// instance of the ASTReader can be attached to an ASTContext object,
00290 /// which will provide access to the contents of the AST files.
00291 ///
00292 /// The AST reader provides lazy de-serialization of declarations, as
00293 /// required when traversing the AST. Only those AST nodes that are
00294 /// actually required will be de-serialized.
00295 class ASTReader
00296   : public ExternalPreprocessorSource,
00297     public ExternalPreprocessingRecordSource,
00298     public ExternalHeaderFileInfoSource,
00299     public ExternalSemaSource,
00300     public IdentifierInfoLookup,
00301     public ExternalIdentifierLookup,
00302     public ExternalSLocEntrySource
00303 {
00304 public:
00305   typedef SmallVector<uint64_t, 64> RecordData;
00306   typedef SmallVectorImpl<uint64_t> RecordDataImpl;
00307 
00308   /// \brief The result of reading the control block of an AST file, which
00309   /// can fail for various reasons.
00310   enum ASTReadResult {
00311     /// \brief The control block was read successfully. Aside from failures,
00312     /// the AST file is safe to read into the current context.
00313     Success,
00314     /// \brief The AST file itself appears corrupted.
00315     Failure,
00316     /// \brief The AST file was missing.
00317     Missing,
00318     /// \brief The AST file is out-of-date relative to its input files,
00319     /// and needs to be regenerated.
00320     OutOfDate,
00321     /// \brief The AST file was written by a different version of Clang.
00322     VersionMismatch,
00323     /// \brief The AST file was writtten with a different language/target
00324     /// configuration.
00325     ConfigurationMismatch,
00326     /// \brief The AST file has errors.
00327     HadErrors
00328   };
00329   
00330   /// \brief Types of AST files.
00331   friend class PCHValidator;
00332   friend class ASTDeclReader;
00333   friend class ASTStmtReader;
00334   friend class ASTIdentifierIterator;
00335   friend class serialization::reader::ASTIdentifierLookupTrait;
00336   friend class TypeLocReader;
00337   friend class ASTWriter;
00338   friend class ASTUnit; // ASTUnit needs to remap source locations.
00339   friend class serialization::ReadMethodPoolVisitor;
00340 
00341   typedef serialization::ModuleFile ModuleFile;
00342   typedef serialization::ModuleKind ModuleKind;
00343   typedef serialization::ModuleManager ModuleManager;
00344 
00345   typedef ModuleManager::ModuleIterator ModuleIterator;
00346   typedef ModuleManager::ModuleConstIterator ModuleConstIterator;
00347   typedef ModuleManager::ModuleReverseIterator ModuleReverseIterator;
00348 
00349 private:
00350   /// \brief The receiver of some callbacks invoked by ASTReader.
00351   std::unique_ptr<ASTReaderListener> Listener;
00352 
00353   /// \brief The receiver of deserialization events.
00354   ASTDeserializationListener *DeserializationListener;
00355   bool OwnsDeserializationListener;
00356 
00357   SourceManager &SourceMgr;
00358   FileManager &FileMgr;
00359   DiagnosticsEngine &Diags;
00360 
00361   /// \brief The semantic analysis object that will be processing the
00362   /// AST files and the translation unit that uses it.
00363   Sema *SemaObj;
00364 
00365   /// \brief The preprocessor that will be loading the source file.
00366   Preprocessor &PP;
00367 
00368   /// \brief The AST context into which we'll read the AST files.
00369   ASTContext &Context;
00370 
00371   /// \brief The AST consumer.
00372   ASTConsumer *Consumer;
00373 
00374   /// \brief The module manager which manages modules and their dependencies
00375   ModuleManager ModuleMgr;
00376 
00377   /// \brief The location where the module file will be considered as
00378   /// imported from. For non-module AST types it should be invalid.
00379   SourceLocation CurrentImportLoc;
00380 
00381   /// \brief The global module index, if loaded.
00382   std::unique_ptr<GlobalModuleIndex> GlobalIndex;
00383 
00384   /// \brief A map of global bit offsets to the module that stores entities
00385   /// at those bit offsets.
00386   ContinuousRangeMap<uint64_t, ModuleFile*, 4> GlobalBitOffsetsMap;
00387 
00388   /// \brief A map of negated SLocEntryIDs to the modules containing them.
00389   ContinuousRangeMap<unsigned, ModuleFile*, 64> GlobalSLocEntryMap;
00390 
00391   typedef ContinuousRangeMap<unsigned, ModuleFile*, 64> GlobalSLocOffsetMapType;
00392 
00393   /// \brief A map of reversed (SourceManager::MaxLoadedOffset - SLocOffset)
00394   /// SourceLocation offsets to the modules containing them.
00395   GlobalSLocOffsetMapType GlobalSLocOffsetMap;
00396 
00397   /// \brief Types that have already been loaded from the chain.
00398   ///
00399   /// When the pointer at index I is non-NULL, the type with
00400   /// ID = (I + 1) << FastQual::Width has already been loaded
00401   std::vector<QualType> TypesLoaded;
00402 
00403   typedef ContinuousRangeMap<serialization::TypeID, ModuleFile *, 4>
00404     GlobalTypeMapType;
00405 
00406   /// \brief Mapping from global type IDs to the module in which the
00407   /// type resides along with the offset that should be added to the
00408   /// global type ID to produce a local ID.
00409   GlobalTypeMapType GlobalTypeMap;
00410 
00411   /// \brief Declarations that have already been loaded from the chain.
00412   ///
00413   /// When the pointer at index I is non-NULL, the declaration with ID
00414   /// = I + 1 has already been loaded.
00415   std::vector<Decl *> DeclsLoaded;
00416 
00417   typedef ContinuousRangeMap<serialization::DeclID, ModuleFile *, 4>
00418     GlobalDeclMapType;
00419 
00420   /// \brief Mapping from global declaration IDs to the module in which the
00421   /// declaration resides.
00422   GlobalDeclMapType GlobalDeclMap;
00423 
00424   typedef std::pair<ModuleFile *, uint64_t> FileOffset;
00425   typedef SmallVector<FileOffset, 2> FileOffsetsTy;
00426   typedef llvm::DenseMap<serialization::DeclID, FileOffsetsTy>
00427       DeclUpdateOffsetsMap;
00428 
00429   /// \brief Declarations that have modifications residing in a later file
00430   /// in the chain.
00431   DeclUpdateOffsetsMap DeclUpdateOffsets;
00432 
00433   /// \brief Declaration updates for already-loaded declarations that we need
00434   /// to apply once we finish processing an import.
00435   llvm::SmallVector<std::pair<serialization::GlobalDeclID, Decl*>, 16>
00436       PendingUpdateRecords;
00437 
00438   struct ReplacedDeclInfo {
00439     ModuleFile *Mod;
00440     uint64_t Offset;
00441     unsigned RawLoc;
00442 
00443     ReplacedDeclInfo() : Mod(nullptr), Offset(0), RawLoc(0) {}
00444     ReplacedDeclInfo(ModuleFile *Mod, uint64_t Offset, unsigned RawLoc)
00445       : Mod(Mod), Offset(Offset), RawLoc(RawLoc) {}
00446   };
00447 
00448   typedef llvm::DenseMap<serialization::DeclID, ReplacedDeclInfo>
00449       DeclReplacementMap;
00450   /// \brief Declarations that have been replaced in a later file in the chain.
00451   DeclReplacementMap ReplacedDecls;
00452 
00453   /// \brief Declarations that have been imported and have typedef names for
00454   /// linkage purposes.
00455   llvm::DenseMap<std::pair<DeclContext*, IdentifierInfo*>, NamedDecl*>
00456       ImportedTypedefNamesForLinkage;
00457 
00458   /// \brief Mergeable declaration contexts that have anonymous declarations
00459   /// within them, and those anonymous declarations.
00460   llvm::DenseMap<DeclContext*, llvm::SmallVector<NamedDecl*, 2>>
00461     AnonymousDeclarationsForMerging;
00462 
00463   struct FileDeclsInfo {
00464     ModuleFile *Mod;
00465     ArrayRef<serialization::LocalDeclID> Decls;
00466 
00467     FileDeclsInfo() : Mod(nullptr) {}
00468     FileDeclsInfo(ModuleFile *Mod, ArrayRef<serialization::LocalDeclID> Decls)
00469       : Mod(Mod), Decls(Decls) {}
00470   };
00471 
00472   /// \brief Map from a FileID to the file-level declarations that it contains.
00473   llvm::DenseMap<FileID, FileDeclsInfo> FileDeclIDs;
00474 
00475   // Updates for visible decls can occur for other contexts than just the
00476   // TU, and when we read those update records, the actual context will not
00477   // be available yet (unless it's the TU), so have this pending map using the
00478   // ID as a key. It will be realized when the context is actually loaded.
00479   typedef
00480     SmallVector<std::pair<serialization::reader::ASTDeclContextNameLookupTable *,
00481                           ModuleFile*>, 1> DeclContextVisibleUpdates;
00482   typedef llvm::DenseMap<serialization::DeclID, DeclContextVisibleUpdates>
00483       DeclContextVisibleUpdatesPending;
00484 
00485   /// \brief Updates to the visible declarations of declaration contexts that
00486   /// haven't been loaded yet.
00487   DeclContextVisibleUpdatesPending PendingVisibleUpdates;
00488   
00489   /// \brief The set of C++ or Objective-C classes that have forward 
00490   /// declarations that have not yet been linked to their definitions.
00491   llvm::SmallPtrSet<Decl *, 4> PendingDefinitions;
00492 
00493   typedef llvm::MapVector<Decl *, uint64_t,
00494                           llvm::SmallDenseMap<Decl *, unsigned, 4>,
00495                           SmallVector<std::pair<Decl *, uint64_t>, 4> >
00496     PendingBodiesMap;
00497 
00498   /// \brief Functions or methods that have bodies that will be attached.
00499   PendingBodiesMap PendingBodies;
00500 
00501   /// \brief Read the records that describe the contents of declcontexts.
00502   bool ReadDeclContextStorage(ModuleFile &M,
00503                               llvm::BitstreamCursor &Cursor,
00504                               const std::pair<uint64_t, uint64_t> &Offsets,
00505                               serialization::DeclContextInfo &Info);
00506 
00507   /// \brief A vector containing identifiers that have already been
00508   /// loaded.
00509   ///
00510   /// If the pointer at index I is non-NULL, then it refers to the
00511   /// IdentifierInfo for the identifier with ID=I+1 that has already
00512   /// been loaded.
00513   std::vector<IdentifierInfo *> IdentifiersLoaded;
00514 
00515   typedef ContinuousRangeMap<serialization::IdentID, ModuleFile *, 4>
00516     GlobalIdentifierMapType;
00517 
00518   /// \brief Mapping from global identifier IDs to the module in which the
00519   /// identifier resides along with the offset that should be added to the
00520   /// global identifier ID to produce a local ID.
00521   GlobalIdentifierMapType GlobalIdentifierMap;
00522 
00523   /// \brief A vector containing macros that have already been
00524   /// loaded.
00525   ///
00526   /// If the pointer at index I is non-NULL, then it refers to the
00527   /// MacroInfo for the identifier with ID=I+1 that has already
00528   /// been loaded.
00529   std::vector<MacroInfo *> MacrosLoaded;
00530 
00531   typedef ContinuousRangeMap<serialization::MacroID, ModuleFile *, 4>
00532     GlobalMacroMapType;
00533 
00534   /// \brief Mapping from global macro IDs to the module in which the
00535   /// macro resides along with the offset that should be added to the
00536   /// global macro ID to produce a local ID.
00537   GlobalMacroMapType GlobalMacroMap;
00538 
00539   /// \brief A vector containing submodules that have already been loaded.
00540   ///
00541   /// This vector is indexed by the Submodule ID (-1). NULL submodule entries
00542   /// indicate that the particular submodule ID has not yet been loaded.
00543   SmallVector<Module *, 2> SubmodulesLoaded;
00544   
00545   typedef ContinuousRangeMap<serialization::SubmoduleID, ModuleFile *, 4>
00546     GlobalSubmoduleMapType;
00547   
00548   /// \brief Mapping from global submodule IDs to the module file in which the
00549   /// submodule resides along with the offset that should be added to the
00550   /// global submodule ID to produce a local ID.
00551   GlobalSubmoduleMapType GlobalSubmoduleMap;
00552 
00553   /// \brief Information on a macro definition or undefinition that is visible
00554   /// at the end of a submodule.
00555   struct ModuleMacroInfo;
00556 
00557   /// \brief An entity that has been hidden.
00558   class HiddenName {
00559   public:
00560     enum NameKind {
00561       Declaration,
00562       Macro
00563     } Kind;
00564 
00565   private:
00566     union {
00567       Decl *D;
00568       ModuleMacroInfo *MMI;
00569     };
00570 
00571     IdentifierInfo *Id;
00572 
00573   public:
00574     HiddenName(Decl *D) : Kind(Declaration), D(D), Id() { }
00575 
00576     HiddenName(IdentifierInfo *II, ModuleMacroInfo *MMI)
00577       : Kind(Macro), MMI(MMI), Id(II) { }
00578 
00579     NameKind getKind() const { return Kind; }
00580 
00581     Decl *getDecl() const {
00582       assert(getKind() == Declaration && "Hidden name is not a declaration");
00583       return D;
00584     }
00585 
00586     std::pair<IdentifierInfo *, ModuleMacroInfo *> getMacro() const {
00587       assert(getKind() == Macro && "Hidden name is not a macro!");
00588       return std::make_pair(Id, MMI);
00589     }
00590   };
00591 
00592   typedef llvm::SmallDenseMap<IdentifierInfo*,
00593                               ModuleMacroInfo*> HiddenMacrosMap;
00594 
00595   /// \brief A set of hidden declarations.
00596   struct HiddenNames {
00597     SmallVector<Decl*, 2> HiddenDecls;
00598     HiddenMacrosMap HiddenMacros;
00599   };
00600 
00601   typedef llvm::DenseMap<Module *, HiddenNames> HiddenNamesMapType;
00602 
00603   /// \brief A mapping from each of the hidden submodules to the deserialized
00604   /// declarations in that submodule that could be made visible.
00605   HiddenNamesMapType HiddenNamesMap;
00606   
00607   
00608   /// \brief A module import, export, or conflict that hasn't yet been resolved.
00609   struct UnresolvedModuleRef {
00610     /// \brief The file in which this module resides.
00611     ModuleFile *File;
00612     
00613     /// \brief The module that is importing or exporting.
00614     Module *Mod;
00615 
00616     /// \brief The kind of module reference.
00617     enum { Import, Export, Conflict } Kind;
00618 
00619     /// \brief The local ID of the module that is being exported.
00620     unsigned ID;
00621 
00622     /// \brief Whether this is a wildcard export.
00623     unsigned IsWildcard : 1;
00624 
00625     /// \brief String data.
00626     StringRef String;
00627   };
00628   
00629   /// \brief The set of module imports and exports that still need to be 
00630   /// resolved.
00631   SmallVector<UnresolvedModuleRef, 2> UnresolvedModuleRefs;
00632   
00633   /// \brief A vector containing selectors that have already been loaded.
00634   ///
00635   /// This vector is indexed by the Selector ID (-1). NULL selector
00636   /// entries indicate that the particular selector ID has not yet
00637   /// been loaded.
00638   SmallVector<Selector, 16> SelectorsLoaded;
00639 
00640   typedef ContinuousRangeMap<serialization::SelectorID, ModuleFile *, 4>
00641     GlobalSelectorMapType;
00642 
00643   /// \brief Mapping from global selector IDs to the module in which the
00644 
00645   /// global selector ID to produce a local ID.
00646   GlobalSelectorMapType GlobalSelectorMap;
00647 
00648   /// \brief The generation number of the last time we loaded data from the
00649   /// global method pool for this selector.
00650   llvm::DenseMap<Selector, unsigned> SelectorGeneration;
00651 
00652   struct PendingMacroInfo {
00653     ModuleFile *M;
00654 
00655     struct ModuleMacroDataTy {
00656       uint32_t MacID;
00657       serialization::SubmoduleID *Overrides;
00658     };
00659     struct PCHMacroDataTy {
00660       uint64_t MacroDirectivesOffset;
00661     };
00662 
00663     union {
00664       ModuleMacroDataTy ModuleMacroData;
00665       PCHMacroDataTy PCHMacroData;
00666     };
00667 
00668     PendingMacroInfo(ModuleFile *M,
00669                      uint32_t MacID,
00670                      serialization::SubmoduleID *Overrides) : M(M) {
00671       ModuleMacroData.MacID = MacID;
00672       ModuleMacroData.Overrides = Overrides;
00673     }
00674 
00675     PendingMacroInfo(ModuleFile *M, uint64_t MacroDirectivesOffset) : M(M) {
00676       PCHMacroData.MacroDirectivesOffset = MacroDirectivesOffset;
00677     }
00678   };
00679 
00680   typedef llvm::MapVector<IdentifierInfo *, SmallVector<PendingMacroInfo, 2> >
00681     PendingMacroIDsMap;
00682 
00683   /// \brief Mapping from identifiers that have a macro history to the global
00684   /// IDs have not yet been deserialized to the global IDs of those macros.
00685   PendingMacroIDsMap PendingMacroIDs;
00686 
00687   typedef ContinuousRangeMap<unsigned, ModuleFile *, 4>
00688     GlobalPreprocessedEntityMapType;
00689 
00690   /// \brief Mapping from global preprocessing entity IDs to the module in
00691   /// which the preprocessed entity resides along with the offset that should be
00692   /// added to the global preprocessing entitiy ID to produce a local ID.
00693   GlobalPreprocessedEntityMapType GlobalPreprocessedEntityMap;
00694 
00695   /// \name CodeGen-relevant special data
00696   /// \brief Fields containing data that is relevant to CodeGen.
00697   //@{
00698 
00699   /// \brief The IDs of all declarations that fulfill the criteria of
00700   /// "interesting" decls.
00701   ///
00702   /// This contains the data loaded from all EAGERLY_DESERIALIZED_DECLS blocks
00703   /// in the chain. The referenced declarations are deserialized and passed to
00704   /// the consumer eagerly.
00705   SmallVector<uint64_t, 16> EagerlyDeserializedDecls;
00706 
00707   /// \brief The IDs of all tentative definitions stored in the chain.
00708   ///
00709   /// Sema keeps track of all tentative definitions in a TU because it has to
00710   /// complete them and pass them on to CodeGen. Thus, tentative definitions in
00711   /// the PCH chain must be eagerly deserialized.
00712   SmallVector<uint64_t, 16> TentativeDefinitions;
00713 
00714   /// \brief The IDs of all CXXRecordDecls stored in the chain whose VTables are
00715   /// used.
00716   ///
00717   /// CodeGen has to emit VTables for these records, so they have to be eagerly
00718   /// deserialized.
00719   SmallVector<uint64_t, 64> VTableUses;
00720 
00721   /// \brief A snapshot of the pending instantiations in the chain.
00722   ///
00723   /// This record tracks the instantiations that Sema has to perform at the
00724   /// end of the TU. It consists of a pair of values for every pending
00725   /// instantiation where the first value is the ID of the decl and the second
00726   /// is the instantiation location.
00727   SmallVector<uint64_t, 64> PendingInstantiations;
00728 
00729   //@}
00730 
00731   /// \name DiagnosticsEngine-relevant special data
00732   /// \brief Fields containing data that is used for generating diagnostics
00733   //@{
00734 
00735   /// \brief A snapshot of Sema's unused file-scoped variable tracking, for
00736   /// generating warnings.
00737   SmallVector<uint64_t, 16> UnusedFileScopedDecls;
00738 
00739   /// \brief A list of all the delegating constructors we've seen, to diagnose
00740   /// cycles.
00741   SmallVector<uint64_t, 4> DelegatingCtorDecls;
00742 
00743   /// \brief Method selectors used in a @selector expression. Used for
00744   /// implementation of -Wselector.
00745   SmallVector<uint64_t, 64> ReferencedSelectorsData;
00746 
00747   /// \brief A snapshot of Sema's weak undeclared identifier tracking, for
00748   /// generating warnings.
00749   SmallVector<uint64_t, 64> WeakUndeclaredIdentifiers;
00750 
00751   /// \brief The IDs of type aliases for ext_vectors that exist in the chain.
00752   ///
00753   /// Used by Sema for finding sugared names for ext_vectors in diagnostics.
00754   SmallVector<uint64_t, 4> ExtVectorDecls;
00755 
00756   //@}
00757 
00758   /// \name Sema-relevant special data
00759   /// \brief Fields containing data that is used for semantic analysis
00760   //@{
00761 
00762   /// \brief The IDs of all locally scoped extern "C" decls in the chain.
00763   ///
00764   /// Sema tracks these to validate that the types are consistent across all
00765   /// local extern "C" declarations.
00766   SmallVector<uint64_t, 16> LocallyScopedExternCDecls;
00767 
00768   /// \brief The IDs of all dynamic class declarations in the chain.
00769   ///
00770   /// Sema tracks these because it checks for the key functions being defined
00771   /// at the end of the TU, in which case it directs CodeGen to emit the VTable.
00772   SmallVector<uint64_t, 16> DynamicClasses;
00773 
00774   /// \brief The IDs of all potentially unused typedef names in the chain.
00775   ///
00776   /// Sema tracks these to emit warnings.
00777   SmallVector<uint64_t, 16> UnusedLocalTypedefNameCandidates;
00778 
00779   /// \brief The IDs of the declarations Sema stores directly.
00780   ///
00781   /// Sema tracks a few important decls, such as namespace std, directly.
00782   SmallVector<uint64_t, 4> SemaDeclRefs;
00783 
00784   /// \brief The IDs of the types ASTContext stores directly.
00785   ///
00786   /// The AST context tracks a few important types, such as va_list, directly.
00787   SmallVector<uint64_t, 16> SpecialTypes;
00788 
00789   /// \brief The IDs of CUDA-specific declarations ASTContext stores directly.
00790   ///
00791   /// The AST context tracks a few important decls, currently cudaConfigureCall,
00792   /// directly.
00793   SmallVector<uint64_t, 2> CUDASpecialDeclRefs;
00794 
00795   /// \brief The floating point pragma option settings.
00796   SmallVector<uint64_t, 1> FPPragmaOptions;
00797 
00798   /// \brief The pragma clang optimize location (if the pragma state is "off").
00799   SourceLocation OptimizeOffPragmaLocation;
00800 
00801   /// \brief The OpenCL extension settings.
00802   SmallVector<uint64_t, 1> OpenCLExtensions;
00803 
00804   /// \brief A list of the namespaces we've seen.
00805   SmallVector<uint64_t, 4> KnownNamespaces;
00806 
00807   /// \brief A list of undefined decls with internal linkage followed by the
00808   /// SourceLocation of a matching ODR-use.
00809   SmallVector<uint64_t, 8> UndefinedButUsed;
00810 
00811   // \brief A list of late parsed template function data.
00812   SmallVector<uint64_t, 1> LateParsedTemplates;
00813 
00814   struct ImportedSubmodule {
00815     serialization::SubmoduleID ID;
00816     SourceLocation ImportLoc;
00817 
00818     ImportedSubmodule(serialization::SubmoduleID ID, SourceLocation ImportLoc)
00819       : ID(ID), ImportLoc(ImportLoc) {}
00820   };
00821 
00822   /// \brief A list of modules that were imported by precompiled headers or
00823   /// any other non-module AST file.
00824   SmallVector<ImportedSubmodule, 2> ImportedModules;
00825   //@}
00826 
00827   /// \brief The directory that the PCH we are reading is stored in.
00828   std::string CurrentDir;
00829 
00830   /// \brief The system include root to be used when loading the
00831   /// precompiled header.
00832   std::string isysroot;
00833 
00834   /// \brief Whether to disable the normal validation performed on precompiled
00835   /// headers when they are loaded.
00836   bool DisableValidation;
00837 
00838   /// \brief Whether to accept an AST file with compiler errors.
00839   bool AllowASTWithCompilerErrors;
00840 
00841   /// \brief Whether to accept an AST file that has a different configuration
00842   /// from the current compiler instance.
00843   bool AllowConfigurationMismatch;
00844 
00845   /// \brief Whether validate system input files.
00846   bool ValidateSystemInputs;
00847 
00848   /// \brief Whether we are allowed to use the global module index.
00849   bool UseGlobalIndex;
00850 
00851   /// \brief Whether we have tried loading the global module index yet.
00852   bool TriedLoadingGlobalIndex;
00853 
00854   typedef llvm::DenseMap<unsigned, SwitchCase *> SwitchCaseMapTy;
00855   /// \brief Mapping from switch-case IDs in the chain to switch-case statements
00856   ///
00857   /// Statements usually don't have IDs, but switch cases need them, so that the
00858   /// switch statement can refer to them.
00859   SwitchCaseMapTy SwitchCaseStmts;
00860 
00861   SwitchCaseMapTy *CurrSwitchCaseStmts;
00862 
00863   /// \brief The number of source location entries de-serialized from
00864   /// the PCH file.
00865   unsigned NumSLocEntriesRead;
00866 
00867   /// \brief The number of source location entries in the chain.
00868   unsigned TotalNumSLocEntries;
00869 
00870   /// \brief The number of statements (and expressions) de-serialized
00871   /// from the chain.
00872   unsigned NumStatementsRead;
00873 
00874   /// \brief The total number of statements (and expressions) stored
00875   /// in the chain.
00876   unsigned TotalNumStatements;
00877 
00878   /// \brief The number of macros de-serialized from the chain.
00879   unsigned NumMacrosRead;
00880 
00881   /// \brief The total number of macros stored in the chain.
00882   unsigned TotalNumMacros;
00883 
00884   /// \brief The number of lookups into identifier tables.
00885   unsigned NumIdentifierLookups;
00886 
00887   /// \brief The number of lookups into identifier tables that succeed.
00888   unsigned NumIdentifierLookupHits;
00889 
00890   /// \brief The number of selectors that have been read.
00891   unsigned NumSelectorsRead;
00892 
00893   /// \brief The number of method pool entries that have been read.
00894   unsigned NumMethodPoolEntriesRead;
00895 
00896   /// \brief The number of times we have looked up a selector in the method
00897   /// pool.
00898   unsigned NumMethodPoolLookups;
00899 
00900   /// \brief The number of times we have looked up a selector in the method
00901   /// pool and found something.
00902   unsigned NumMethodPoolHits;
00903 
00904   /// \brief The number of times we have looked up a selector in the method
00905   /// pool within a specific module.
00906   unsigned NumMethodPoolTableLookups;
00907 
00908   /// \brief The number of times we have looked up a selector in the method
00909   /// pool within a specific module and found something.
00910   unsigned NumMethodPoolTableHits;
00911 
00912   /// \brief The total number of method pool entries in the selector table.
00913   unsigned TotalNumMethodPoolEntries;
00914 
00915   /// Number of lexical decl contexts read/total.
00916   unsigned NumLexicalDeclContextsRead, TotalLexicalDeclContexts;
00917 
00918   /// Number of visible decl contexts read/total.
00919   unsigned NumVisibleDeclContextsRead, TotalVisibleDeclContexts;
00920 
00921   /// Total size of modules, in bits, currently loaded
00922   uint64_t TotalModulesSizeInBits;
00923 
00924   /// \brief Number of Decl/types that are currently deserializing.
00925   unsigned NumCurrentElementsDeserializing;
00926 
00927   /// \brief Set true while we are in the process of passing deserialized
00928   /// "interesting" decls to consumer inside FinishedDeserializing().
00929   /// This is used as a guard to avoid recursively repeating the process of
00930   /// passing decls to consumer.
00931   bool PassingDeclsToConsumer;
00932 
00933   /// Number of CXX base specifiers currently loaded
00934   unsigned NumCXXBaseSpecifiersLoaded;
00935 
00936   /// \brief The set of identifiers that were read while the AST reader was
00937   /// (recursively) loading declarations.
00938   ///
00939   /// The declarations on the identifier chain for these identifiers will be
00940   /// loaded once the recursive loading has completed.
00941   llvm::MapVector<IdentifierInfo *, SmallVector<uint32_t, 4> >
00942     PendingIdentifierInfos;
00943 
00944   /// \brief The generation number of each identifier, which keeps track of
00945   /// the last time we loaded information about this identifier.
00946   llvm::DenseMap<IdentifierInfo *, unsigned> IdentifierGeneration;
00947   
00948   /// \brief Contains declarations and definitions that will be
00949   /// "interesting" to the ASTConsumer, when we get that AST consumer.
00950   ///
00951   /// "Interesting" declarations are those that have data that may
00952   /// need to be emitted, such as inline function definitions or
00953   /// Objective-C protocols.
00954   std::deque<Decl *> InterestingDecls;
00955 
00956   /// \brief The set of redeclarable declarations that have been deserialized
00957   /// since the last time the declaration chains were linked.
00958   llvm::SmallPtrSet<Decl *, 16> RedeclsDeserialized;
00959   
00960   /// \brief The list of redeclaration chains that still need to be 
00961   /// reconstructed.
00962   ///
00963   /// Each element is the global declaration ID of the first declaration in
00964   /// the chain. Elements in this vector should be unique; use 
00965   /// PendingDeclChainsKnown to ensure uniqueness.
00966   SmallVector<serialization::DeclID, 16> PendingDeclChains;
00967 
00968   /// \brief Keeps track of the elements added to PendingDeclChains.
00969   llvm::SmallSet<serialization::DeclID, 16> PendingDeclChainsKnown;
00970 
00971   /// \brief The list of canonical declarations whose redeclaration chains
00972   /// need to be marked as incomplete once we're done deserializing things.
00973   SmallVector<Decl *, 16> PendingIncompleteDeclChains;
00974 
00975   /// \brief The Decl IDs for the Sema/Lexical DeclContext of a Decl that has
00976   /// been loaded but its DeclContext was not set yet.
00977   struct PendingDeclContextInfo {
00978     Decl *D;
00979     serialization::GlobalDeclID SemaDC;
00980     serialization::GlobalDeclID LexicalDC;
00981   };
00982 
00983   /// \brief The set of Decls that have been loaded but their DeclContexts are
00984   /// not set yet.
00985   ///
00986   /// The DeclContexts for these Decls will be set once recursive loading has
00987   /// been completed.
00988   std::deque<PendingDeclContextInfo> PendingDeclContextInfos;
00989 
00990   /// \brief The set of NamedDecls that have been loaded, but are members of a
00991   /// context that has been merged into another context where the corresponding
00992   /// declaration is either missing or has not yet been loaded.
00993   ///
00994   /// We will check whether the corresponding declaration is in fact missing
00995   /// once recursing loading has been completed.
00996   llvm::SmallVector<NamedDecl *, 16> PendingOdrMergeChecks;
00997 
00998   /// \brief Record definitions in which we found an ODR violation.
00999   llvm::SmallDenseMap<CXXRecordDecl *, llvm::TinyPtrVector<CXXRecordDecl *>, 2>
01000       PendingOdrMergeFailures;
01001 
01002   /// \brief DeclContexts in which we have diagnosed an ODR violation.
01003   llvm::SmallPtrSet<DeclContext*, 2> DiagnosedOdrMergeFailures;
01004 
01005   /// \brief The set of Objective-C categories that have been deserialized
01006   /// since the last time the declaration chains were linked.
01007   llvm::SmallPtrSet<ObjCCategoryDecl *, 16> CategoriesDeserialized;
01008 
01009   /// \brief The set of Objective-C class definitions that have already been
01010   /// loaded, for which we will need to check for categories whenever a new
01011   /// module is loaded.
01012   SmallVector<ObjCInterfaceDecl *, 16> ObjCClassesLoaded;
01013 
01014   /// \brief A mapping from a primary context for a declaration chain to the
01015   /// other declarations of that entity that also have name lookup tables.
01016   /// Used when we merge together two class definitions that have different
01017   /// sets of declared special member functions.
01018   llvm::DenseMap<const DeclContext*, SmallVector<const DeclContext*, 2>>
01019       MergedLookups;
01020 
01021   typedef llvm::DenseMap<Decl *, SmallVector<serialization::DeclID, 2> >
01022     MergedDeclsMap;
01023     
01024   /// \brief A mapping from canonical declarations to the set of additional
01025   /// (global, previously-canonical) declaration IDs that have been merged with
01026   /// that canonical declaration.
01027   MergedDeclsMap MergedDecls;
01028   
01029   typedef llvm::DenseMap<serialization::GlobalDeclID, 
01030                          SmallVector<serialization::DeclID, 2> >
01031     StoredMergedDeclsMap;
01032   
01033   /// \brief A mapping from canonical declaration IDs to the set of additional
01034   /// declaration IDs that have been merged with that canonical declaration.
01035   ///
01036   /// This is the deserialized representation of the entries in MergedDecls.
01037   /// When we query entries in MergedDecls, they will be augmented with entries
01038   /// from StoredMergedDecls.
01039   StoredMergedDeclsMap StoredMergedDecls;
01040   
01041   /// \brief Combine the stored merged declarations for the given canonical
01042   /// declaration into the set of merged declarations.
01043   ///
01044   /// \returns An iterator into MergedDecls that corresponds to the position of
01045   /// the given canonical declaration.
01046   MergedDeclsMap::iterator
01047   combineStoredMergedDecls(Decl *Canon, serialization::GlobalDeclID CanonID);
01048 
01049   /// \brief A mapping from DeclContexts to the semantic DeclContext that we
01050   /// are treating as the definition of the entity. This is used, for instance,
01051   /// when merging implicit instantiations of class templates across modules.
01052   llvm::DenseMap<DeclContext *, DeclContext *> MergedDeclContexts;
01053 
01054   /// \brief A mapping from canonical declarations of enums to their canonical
01055   /// definitions. Only populated when using modules in C++.
01056   llvm::DenseMap<EnumDecl *, EnumDecl *> EnumDefinitions;
01057 
01058   /// \brief When reading a Stmt tree, Stmt operands are placed in this stack.
01059   SmallVector<Stmt *, 16> StmtStack;
01060 
01061   /// \brief What kind of records we are reading.
01062   enum ReadingKind {
01063     Read_None, Read_Decl, Read_Type, Read_Stmt
01064   };
01065 
01066   /// \brief What kind of records we are reading.
01067   ReadingKind ReadingKind;
01068 
01069   /// \brief RAII object to change the reading kind.
01070   class ReadingKindTracker {
01071     ASTReader &Reader;
01072     enum ReadingKind PrevKind;
01073 
01074     ReadingKindTracker(const ReadingKindTracker &) LLVM_DELETED_FUNCTION;
01075     void operator=(const ReadingKindTracker &) LLVM_DELETED_FUNCTION;
01076 
01077   public:
01078     ReadingKindTracker(enum ReadingKind newKind, ASTReader &reader)
01079       : Reader(reader), PrevKind(Reader.ReadingKind) {
01080       Reader.ReadingKind = newKind;
01081     }
01082 
01083     ~ReadingKindTracker() { Reader.ReadingKind = PrevKind; }
01084   };
01085 
01086   /// \brief Suggested contents of the predefines buffer, after this
01087   /// PCH file has been processed.
01088   ///
01089   /// In most cases, this string will be empty, because the predefines
01090   /// buffer computed to build the PCH file will be identical to the
01091   /// predefines buffer computed from the command line. However, when
01092   /// there are differences that the PCH reader can work around, this
01093   /// predefines buffer may contain additional definitions.
01094   std::string SuggestedPredefines;
01095 
01096   /// \brief Reads a statement from the specified cursor.
01097   Stmt *ReadStmtFromStream(ModuleFile &F);
01098 
01099   struct InputFileInfo {
01100     std::string Filename;
01101     off_t StoredSize;
01102     time_t StoredTime;
01103     bool Overridden;
01104   };
01105 
01106   /// \brief Reads the stored information about an input file.
01107   InputFileInfo readInputFileInfo(ModuleFile &F, unsigned ID);
01108   /// \brief A convenience method to read the filename from an input file.
01109   std::string getInputFileName(ModuleFile &F, unsigned ID);
01110 
01111   /// \brief Retrieve the file entry and 'overridden' bit for an input
01112   /// file in the given module file.
01113   serialization::InputFile getInputFile(ModuleFile &F, unsigned ID,
01114                                         bool Complain = true);
01115 
01116   /// \brief Get a FileEntry out of stored-in-PCH filename, making sure we take
01117   /// into account all the necessary relocations.
01118   const FileEntry *getFileEntry(StringRef filename);
01119 
01120   void MaybeAddSystemRootToFilename(ModuleFile &M, std::string &Filename);
01121 
01122   struct ImportedModule {
01123     ModuleFile *Mod;
01124     ModuleFile *ImportedBy;
01125     SourceLocation ImportLoc;
01126 
01127     ImportedModule(ModuleFile *Mod,
01128                    ModuleFile *ImportedBy,
01129                    SourceLocation ImportLoc)
01130       : Mod(Mod), ImportedBy(ImportedBy), ImportLoc(ImportLoc) { }
01131   };
01132 
01133   ASTReadResult ReadASTCore(StringRef FileName, ModuleKind Type,
01134                             SourceLocation ImportLoc, ModuleFile *ImportedBy,
01135                             SmallVectorImpl<ImportedModule> &Loaded,
01136                             off_t ExpectedSize, time_t ExpectedModTime,
01137                             serialization::ASTFileSignature ExpectedSignature,
01138                             unsigned ClientLoadCapabilities);
01139   ASTReadResult ReadControlBlock(ModuleFile &F,
01140                                  SmallVectorImpl<ImportedModule> &Loaded,
01141                                  const ModuleFile *ImportedBy,
01142                                  unsigned ClientLoadCapabilities);
01143   ASTReadResult ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities);
01144   bool ParseLineTable(ModuleFile &F, SmallVectorImpl<uint64_t> &Record);
01145   bool ReadSourceManagerBlock(ModuleFile &F);
01146   llvm::BitstreamCursor &SLocCursorForID(int ID);
01147   SourceLocation getImportLocation(ModuleFile *F);
01148   ASTReadResult ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
01149                                        const ModuleFile *ImportedBy,
01150                                        unsigned ClientLoadCapabilities);
01151   ASTReadResult ReadSubmoduleBlock(ModuleFile &F,
01152                                    unsigned ClientLoadCapabilities);
01153   static bool ParseLanguageOptions(const RecordData &Record, bool Complain,
01154                                    ASTReaderListener &Listener,
01155                                    bool AllowCompatibleDifferences);
01156   static bool ParseTargetOptions(const RecordData &Record, bool Complain,
01157                                  ASTReaderListener &Listener);
01158   static bool ParseDiagnosticOptions(const RecordData &Record, bool Complain,
01159                                      ASTReaderListener &Listener);
01160   static bool ParseFileSystemOptions(const RecordData &Record, bool Complain,
01161                                      ASTReaderListener &Listener);
01162   static bool ParseHeaderSearchOptions(const RecordData &Record, bool Complain,
01163                                        ASTReaderListener &Listener);
01164   static bool ParsePreprocessorOptions(const RecordData &Record, bool Complain,
01165                                        ASTReaderListener &Listener,
01166                                        std::string &SuggestedPredefines);
01167 
01168   struct RecordLocation {
01169     RecordLocation(ModuleFile *M, uint64_t O)
01170       : F(M), Offset(O) {}
01171     ModuleFile *F;
01172     uint64_t Offset;
01173   };
01174 
01175   QualType readTypeRecord(unsigned Index);
01176   void readExceptionSpec(ModuleFile &ModuleFile,
01177                          SmallVectorImpl<QualType> &ExceptionStorage,
01178                          FunctionProtoType::ExceptionSpecInfo &ESI,
01179                          const RecordData &Record, unsigned &Index);
01180   RecordLocation TypeCursorForIndex(unsigned Index);
01181   void LoadedDecl(unsigned Index, Decl *D);
01182   Decl *ReadDeclRecord(serialization::DeclID ID);
01183   void markIncompleteDeclChain(Decl *Canon);
01184   RecordLocation DeclCursorForID(serialization::DeclID ID,
01185                                  unsigned &RawLocation);
01186   void loadDeclUpdateRecords(serialization::DeclID ID, Decl *D);
01187   void loadPendingDeclChain(serialization::GlobalDeclID ID);
01188   void loadObjCCategories(serialization::GlobalDeclID ID, ObjCInterfaceDecl *D,
01189                           unsigned PreviousGeneration = 0);
01190 
01191   RecordLocation getLocalBitOffset(uint64_t GlobalOffset);
01192   uint64_t getGlobalBitOffset(ModuleFile &M, uint32_t LocalOffset);
01193 
01194   /// \brief Returns the first preprocessed entity ID that begins or ends after
01195   /// \arg Loc.
01196   serialization::PreprocessedEntityID
01197   findPreprocessedEntity(SourceLocation Loc, bool EndsAfter) const;
01198 
01199   /// \brief Find the next module that contains entities and return the ID
01200   /// of the first entry.
01201   ///
01202   /// \param SLocMapI points at a chunk of a module that contains no
01203   /// preprocessed entities or the entities it contains are not the
01204   /// ones we are looking for.
01205   serialization::PreprocessedEntityID
01206     findNextPreprocessedEntity(
01207                         GlobalSLocOffsetMapType::const_iterator SLocMapI) const;
01208 
01209   /// \brief Returns (ModuleFile, Local index) pair for \p GlobalIndex of a
01210   /// preprocessed entity.
01211   std::pair<ModuleFile *, unsigned>
01212     getModulePreprocessedEntity(unsigned GlobalIndex);
01213 
01214   /// \brief Returns (begin, end) pair for the preprocessed entities of a
01215   /// particular module.
01216   std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
01217     getModulePreprocessedEntities(ModuleFile &Mod) const;
01218 
01219   class ModuleDeclIterator {
01220     ASTReader *Reader;
01221     ModuleFile *Mod;
01222     const serialization::LocalDeclID *Pos;
01223 
01224   public:
01225     typedef const Decl *value_type;
01226     typedef value_type&         reference;
01227     typedef value_type*         pointer;
01228 
01229     ModuleDeclIterator() : Reader(nullptr), Mod(nullptr), Pos(nullptr) { }
01230 
01231     ModuleDeclIterator(ASTReader *Reader, ModuleFile *Mod,
01232                        const serialization::LocalDeclID *Pos)
01233       : Reader(Reader), Mod(Mod), Pos(Pos) { }
01234 
01235     value_type operator*() const {
01236       return Reader->GetDecl(Reader->getGlobalDeclID(*Mod, *Pos));
01237     }
01238 
01239     ModuleDeclIterator &operator++() {
01240       ++Pos;
01241       return *this;
01242     }
01243 
01244     ModuleDeclIterator operator++(int) {
01245       ModuleDeclIterator Prev(*this);
01246       ++Pos;
01247       return Prev;
01248     }
01249 
01250     ModuleDeclIterator &operator--() {
01251       --Pos;
01252       return *this;
01253     }
01254 
01255     ModuleDeclIterator operator--(int) {
01256       ModuleDeclIterator Prev(*this);
01257       --Pos;
01258       return Prev;
01259     }
01260 
01261     friend bool operator==(const ModuleDeclIterator &LHS,
01262                            const ModuleDeclIterator &RHS) {
01263       assert(LHS.Reader == RHS.Reader && LHS.Mod == RHS.Mod);
01264       return LHS.Pos == RHS.Pos;
01265     }
01266 
01267     friend bool operator!=(const ModuleDeclIterator &LHS,
01268                            const ModuleDeclIterator &RHS) {
01269       assert(LHS.Reader == RHS.Reader && LHS.Mod == RHS.Mod);
01270       return LHS.Pos != RHS.Pos;
01271     }
01272   };
01273 
01274   std::pair<ModuleDeclIterator, ModuleDeclIterator>
01275     getModuleFileLevelDecls(ModuleFile &Mod);
01276 
01277   void PassInterestingDeclsToConsumer();
01278   void PassInterestingDeclToConsumer(Decl *D);
01279 
01280   void finishPendingActions();
01281   void diagnoseOdrViolations();
01282 
01283   void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name);
01284 
01285   void addPendingDeclContextInfo(Decl *D,
01286                                  serialization::GlobalDeclID SemaDC,
01287                                  serialization::GlobalDeclID LexicalDC) {
01288     assert(D);
01289     PendingDeclContextInfo Info = { D, SemaDC, LexicalDC };
01290     PendingDeclContextInfos.push_back(Info);
01291   }
01292 
01293   /// \brief Produce an error diagnostic and return true.
01294   ///
01295   /// This routine should only be used for fatal errors that have to
01296   /// do with non-routine failures (e.g., corrupted AST file).
01297   void Error(StringRef Msg);
01298   void Error(unsigned DiagID, StringRef Arg1 = StringRef(),
01299              StringRef Arg2 = StringRef());
01300 
01301   ASTReader(const ASTReader &) LLVM_DELETED_FUNCTION;
01302   void operator=(const ASTReader &) LLVM_DELETED_FUNCTION;
01303 public:
01304   /// \brief Load the AST file and validate its contents against the given
01305   /// Preprocessor.
01306   ///
01307   /// \param PP the preprocessor associated with the context in which this
01308   /// precompiled header will be loaded.
01309   ///
01310   /// \param Context the AST context that this precompiled header will be
01311   /// loaded into.
01312   ///
01313   /// \param isysroot If non-NULL, the system include path specified by the
01314   /// user. This is only used with relocatable PCH files. If non-NULL,
01315   /// a relocatable PCH file will use the default path "/".
01316   ///
01317   /// \param DisableValidation If true, the AST reader will suppress most
01318   /// of its regular consistency checking, allowing the use of precompiled
01319   /// headers that cannot be determined to be compatible.
01320   ///
01321   /// \param AllowASTWithCompilerErrors If true, the AST reader will accept an
01322   /// AST file the was created out of an AST with compiler errors,
01323   /// otherwise it will reject it.
01324   ///
01325   /// \param AllowConfigurationMismatch If true, the AST reader will not check
01326   /// for configuration differences between the AST file and the invocation.
01327   ///
01328   /// \param ValidateSystemInputs If true, the AST reader will validate
01329   /// system input files in addition to user input files. This is only
01330   /// meaningful if \p DisableValidation is false.
01331   ///
01332   /// \param UseGlobalIndex If true, the AST reader will try to load and use
01333   /// the global module index.
01334   ASTReader(Preprocessor &PP, ASTContext &Context, StringRef isysroot = "",
01335             bool DisableValidation = false,
01336             bool AllowASTWithCompilerErrors = false,
01337             bool AllowConfigurationMismatch = false,
01338             bool ValidateSystemInputs = false,
01339             bool UseGlobalIndex = true);
01340 
01341   ~ASTReader();
01342 
01343   SourceManager &getSourceManager() const { return SourceMgr; }
01344   FileManager &getFileManager() const { return FileMgr; }
01345 
01346   /// \brief Flags that indicate what kind of AST loading failures the client
01347   /// of the AST reader can directly handle.
01348   ///
01349   /// When a client states that it can handle a particular kind of failure,
01350   /// the AST reader will not emit errors when producing that kind of failure.
01351   enum LoadFailureCapabilities {
01352     /// \brief The client can't handle any AST loading failures.
01353     ARR_None = 0,
01354     /// \brief The client can handle an AST file that cannot load because it
01355     /// is missing.
01356     ARR_Missing = 0x1,
01357     /// \brief The client can handle an AST file that cannot load because it
01358     /// is out-of-date relative to its input files.
01359     ARR_OutOfDate = 0x2,
01360     /// \brief The client can handle an AST file that cannot load because it
01361     /// was built with a different version of Clang.
01362     ARR_VersionMismatch = 0x4,
01363     /// \brief The client can handle an AST file that cannot load because it's
01364     /// compiled configuration doesn't match that of the context it was
01365     /// loaded into.
01366     ARR_ConfigurationMismatch = 0x8
01367   };
01368 
01369   /// \brief Load the AST file designated by the given file name.
01370   ///
01371   /// \param FileName The name of the AST file to load.
01372   ///
01373   /// \param Type The kind of AST being loaded, e.g., PCH, module, main file,
01374   /// or preamble.
01375   ///
01376   /// \param ImportLoc the location where the module file will be considered as
01377   /// imported from. For non-module AST types it should be invalid.
01378   ///
01379   /// \param ClientLoadCapabilities The set of client load-failure
01380   /// capabilities, represented as a bitset of the enumerators of
01381   /// LoadFailureCapabilities.
01382   ASTReadResult ReadAST(const std::string &FileName, ModuleKind Type,
01383                         SourceLocation ImportLoc,
01384                         unsigned ClientLoadCapabilities);
01385 
01386   /// \brief Make the entities in the given module and any of its (non-explicit)
01387   /// submodules visible to name lookup.
01388   ///
01389   /// \param Mod The module whose names should be made visible.
01390   ///
01391   /// \param NameVisibility The level of visibility to give the names in the
01392   /// module.  Visibility can only be increased over time.
01393   ///
01394   /// \param ImportLoc The location at which the import occurs.
01395   ///
01396   /// \param Complain Whether to complain about conflicting module imports.
01397   void makeModuleVisible(Module *Mod,
01398                          Module::NameVisibilityKind NameVisibility,
01399                          SourceLocation ImportLoc,
01400                          bool Complain);
01401 
01402   /// \brief Make the names within this set of hidden names visible.
01403   void makeNamesVisible(const HiddenNames &Names, Module *Owner,
01404                         bool FromFinalization);
01405 
01406   /// \brief Take the AST callbacks listener.
01407   std::unique_ptr<ASTReaderListener> takeListener() {
01408     return std::move(Listener);
01409   }
01410 
01411   /// \brief Set the AST callbacks listener.
01412   void setListener(std::unique_ptr<ASTReaderListener> Listener) {
01413     this->Listener = std::move(Listener);
01414   }
01415 
01416   /// \brief Add an AST callback listener.
01417   ///
01418   /// Takes ownership of \p L.
01419   void addListener(std::unique_ptr<ASTReaderListener> L) {
01420     if (Listener)
01421       L = llvm::make_unique<ChainedASTReaderListener>(std::move(L),
01422                                                       std::move(Listener));
01423     Listener = std::move(L);
01424   }
01425 
01426   /// RAII object to temporarily add an AST callback listener.
01427   class ListenerScope {
01428     ASTReader &Reader;
01429     bool Chained;
01430 
01431   public:
01432     ListenerScope(ASTReader &Reader, std::unique_ptr<ASTReaderListener> L)
01433         : Reader(Reader), Chained(false) {
01434       auto Old = Reader.takeListener();
01435       if (Old) {
01436         Chained = true;
01437         L = llvm::make_unique<ChainedASTReaderListener>(std::move(L),
01438                                                         std::move(Old));
01439       }
01440       Reader.setListener(std::move(L));
01441     }
01442     ~ListenerScope() {
01443       auto New = Reader.takeListener();
01444       if (Chained)
01445         Reader.setListener(static_cast<ChainedASTReaderListener *>(New.get())
01446                                ->takeSecond());
01447     }
01448   };
01449 
01450   /// \brief Set the AST deserialization listener.
01451   void setDeserializationListener(ASTDeserializationListener *Listener,
01452                                   bool TakeOwnership = false);
01453 
01454   /// \brief Determine whether this AST reader has a global index.
01455   bool hasGlobalIndex() const { return (bool)GlobalIndex; }
01456 
01457   /// \brief Return global module index.
01458   GlobalModuleIndex *getGlobalIndex() { return GlobalIndex.get(); }
01459 
01460   /// \brief Reset reader for a reload try.
01461   void resetForReload() { TriedLoadingGlobalIndex = false; }
01462 
01463   /// \brief Attempts to load the global index.
01464   ///
01465   /// \returns true if loading the global index has failed for any reason.
01466   bool loadGlobalIndex();
01467 
01468   /// \brief Determine whether we tried to load the global index, but failed,
01469   /// e.g., because it is out-of-date or does not exist.
01470   bool isGlobalIndexUnavailable() const;
01471   
01472   /// \brief Initializes the ASTContext
01473   void InitializeContext();
01474 
01475   /// \brief Update the state of Sema after loading some additional modules.
01476   void UpdateSema();
01477 
01478   /// \brief Add in-memory (virtual file) buffer.
01479   void addInMemoryBuffer(StringRef &FileName,
01480                          std::unique_ptr<llvm::MemoryBuffer> Buffer) {
01481     ModuleMgr.addInMemoryBuffer(FileName, std::move(Buffer));
01482   }
01483 
01484   /// \brief Finalizes the AST reader's state before writing an AST file to
01485   /// disk.
01486   ///
01487   /// This operation may undo temporary state in the AST that should not be
01488   /// emitted.
01489   void finalizeForWriting();
01490 
01491   /// \brief Retrieve the module manager.
01492   ModuleManager &getModuleManager() { return ModuleMgr; }
01493 
01494   /// \brief Retrieve the preprocessor.
01495   Preprocessor &getPreprocessor() const { return PP; }
01496 
01497   /// \brief Retrieve the name of the original source file name for the primary
01498   /// module file.
01499   StringRef getOriginalSourceFile() {
01500     return ModuleMgr.getPrimaryModule().OriginalSourceFileName; 
01501   }
01502 
01503   /// \brief Retrieve the name of the original source file name directly from
01504   /// the AST file, without actually loading the AST file.
01505   static std::string getOriginalSourceFile(const std::string &ASTFileName,
01506                                            FileManager &FileMgr,
01507                                            DiagnosticsEngine &Diags);
01508 
01509   /// \brief Read the control block for the named AST file.
01510   ///
01511   /// \returns true if an error occurred, false otherwise.
01512   static bool readASTFileControlBlock(StringRef Filename,
01513                                       FileManager &FileMgr,
01514                                       ASTReaderListener &Listener);
01515 
01516   /// \brief Determine whether the given AST file is acceptable to load into a
01517   /// translation unit with the given language and target options.
01518   static bool isAcceptableASTFile(StringRef Filename,
01519                                   FileManager &FileMgr,
01520                                   const LangOptions &LangOpts,
01521                                   const TargetOptions &TargetOpts,
01522                                   const PreprocessorOptions &PPOpts);
01523 
01524   /// \brief Returns the suggested contents of the predefines buffer,
01525   /// which contains a (typically-empty) subset of the predefines
01526   /// build prior to including the precompiled header.
01527   const std::string &getSuggestedPredefines() { return SuggestedPredefines; }
01528 
01529   /// \brief Read a preallocated preprocessed entity from the external source.
01530   ///
01531   /// \returns null if an error occurred that prevented the preprocessed
01532   /// entity from being loaded.
01533   PreprocessedEntity *ReadPreprocessedEntity(unsigned Index) override;
01534 
01535   /// \brief Returns a pair of [Begin, End) indices of preallocated
01536   /// preprocessed entities that \p Range encompasses.
01537   std::pair<unsigned, unsigned>
01538       findPreprocessedEntitiesInRange(SourceRange Range) override;
01539 
01540   /// \brief Optionally returns true or false if the preallocated preprocessed
01541   /// entity with index \p Index came from file \p FID.
01542   Optional<bool> isPreprocessedEntityInFileID(unsigned Index,
01543                                               FileID FID) override;
01544 
01545   /// \brief Read the header file information for the given file entry.
01546   HeaderFileInfo GetHeaderFileInfo(const FileEntry *FE) override;
01547 
01548   void ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag);
01549 
01550   /// \brief Returns the number of source locations found in the chain.
01551   unsigned getTotalNumSLocs() const {
01552     return TotalNumSLocEntries;
01553   }
01554 
01555   /// \brief Returns the number of identifiers found in the chain.
01556   unsigned getTotalNumIdentifiers() const {
01557     return static_cast<unsigned>(IdentifiersLoaded.size());
01558   }
01559 
01560   /// \brief Returns the number of macros found in the chain.
01561   unsigned getTotalNumMacros() const {
01562     return static_cast<unsigned>(MacrosLoaded.size());
01563   }
01564 
01565   /// \brief Returns the number of types found in the chain.
01566   unsigned getTotalNumTypes() const {
01567     return static_cast<unsigned>(TypesLoaded.size());
01568   }
01569 
01570   /// \brief Returns the number of declarations found in the chain.
01571   unsigned getTotalNumDecls() const {
01572     return static_cast<unsigned>(DeclsLoaded.size());
01573   }
01574 
01575   /// \brief Returns the number of submodules known.
01576   unsigned getTotalNumSubmodules() const {
01577     return static_cast<unsigned>(SubmodulesLoaded.size());
01578   }
01579   
01580   /// \brief Returns the number of selectors found in the chain.
01581   unsigned getTotalNumSelectors() const {
01582     return static_cast<unsigned>(SelectorsLoaded.size());
01583   }
01584 
01585   /// \brief Returns the number of preprocessed entities known to the AST
01586   /// reader.
01587   unsigned getTotalNumPreprocessedEntities() const {
01588     unsigned Result = 0;
01589     for (ModuleConstIterator I = ModuleMgr.begin(),
01590         E = ModuleMgr.end(); I != E; ++I) {
01591       Result += (*I)->NumPreprocessedEntities;
01592     }
01593 
01594     return Result;
01595   }
01596 
01597   /// \brief Returns the number of C++ base specifiers found in the chain.
01598   unsigned getTotalNumCXXBaseSpecifiers() const {
01599     return NumCXXBaseSpecifiersLoaded;
01600   }
01601 
01602   /// \brief Reads a TemplateArgumentLocInfo appropriate for the
01603   /// given TemplateArgument kind.
01604   TemplateArgumentLocInfo
01605   GetTemplateArgumentLocInfo(ModuleFile &F, TemplateArgument::ArgKind Kind,
01606                              const RecordData &Record, unsigned &Idx);
01607 
01608   /// \brief Reads a TemplateArgumentLoc.
01609   TemplateArgumentLoc
01610   ReadTemplateArgumentLoc(ModuleFile &F,
01611                           const RecordData &Record, unsigned &Idx);
01612 
01613   const ASTTemplateArgumentListInfo*
01614   ReadASTTemplateArgumentListInfo(ModuleFile &F,
01615                                   const RecordData &Record, unsigned &Index);
01616 
01617   /// \brief Reads a declarator info from the given record.
01618   TypeSourceInfo *GetTypeSourceInfo(ModuleFile &F,
01619                                     const RecordData &Record, unsigned &Idx);
01620 
01621   /// \brief Resolve a type ID into a type, potentially building a new
01622   /// type.
01623   QualType GetType(serialization::TypeID ID);
01624 
01625   /// \brief Resolve a local type ID within a given AST file into a type.
01626   QualType getLocalType(ModuleFile &F, unsigned LocalID);
01627 
01628   /// \brief Map a local type ID within a given AST file into a global type ID.
01629   serialization::TypeID getGlobalTypeID(ModuleFile &F, unsigned LocalID) const;
01630 
01631   /// \brief Read a type from the current position in the given record, which
01632   /// was read from the given AST file.
01633   QualType readType(ModuleFile &F, const RecordData &Record, unsigned &Idx) {
01634     if (Idx >= Record.size())
01635       return QualType();
01636 
01637     return getLocalType(F, Record[Idx++]);
01638   }
01639 
01640   /// \brief Map from a local declaration ID within a given module to a
01641   /// global declaration ID.
01642   serialization::DeclID getGlobalDeclID(ModuleFile &F,
01643                                       serialization::LocalDeclID LocalID) const;
01644 
01645   /// \brief Returns true if global DeclID \p ID originated from module \p M.
01646   bool isDeclIDFromModule(serialization::GlobalDeclID ID, ModuleFile &M) const;
01647 
01648   /// \brief Retrieve the module file that owns the given declaration, or NULL
01649   /// if the declaration is not from a module file.
01650   ModuleFile *getOwningModuleFile(const Decl *D);
01651 
01652   /// \brief Get the best name we know for the module that owns the given
01653   /// declaration, or an empty string if the declaration is not from a module.
01654   std::string getOwningModuleNameForDiagnostic(const Decl *D);
01655 
01656   /// \brief Returns the source location for the decl \p ID.
01657   SourceLocation getSourceLocationForDeclID(serialization::GlobalDeclID ID);
01658 
01659   /// \brief Resolve a declaration ID into a declaration, potentially
01660   /// building a new declaration.
01661   Decl *GetDecl(serialization::DeclID ID);
01662   Decl *GetExternalDecl(uint32_t ID) override;
01663 
01664   /// \brief Resolve a declaration ID into a declaration. Return 0 if it's not
01665   /// been loaded yet.
01666   Decl *GetExistingDecl(serialization::DeclID ID);
01667 
01668   /// \brief Reads a declaration with the given local ID in the given module.
01669   Decl *GetLocalDecl(ModuleFile &F, uint32_t LocalID) {
01670     return GetDecl(getGlobalDeclID(F, LocalID));
01671   }
01672 
01673   /// \brief Reads a declaration with the given local ID in the given module.
01674   ///
01675   /// \returns The requested declaration, casted to the given return type.
01676   template<typename T>
01677   T *GetLocalDeclAs(ModuleFile &F, uint32_t LocalID) {
01678     return cast_or_null<T>(GetLocalDecl(F, LocalID));
01679   }
01680 
01681   /// \brief Map a global declaration ID into the declaration ID used to 
01682   /// refer to this declaration within the given module fule.
01683   ///
01684   /// \returns the global ID of the given declaration as known in the given
01685   /// module file.
01686   serialization::DeclID 
01687   mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
01688                                   serialization::DeclID GlobalID);
01689   
01690   /// \brief Reads a declaration ID from the given position in a record in the
01691   /// given module.
01692   ///
01693   /// \returns The declaration ID read from the record, adjusted to a global ID.
01694   serialization::DeclID ReadDeclID(ModuleFile &F, const RecordData &Record,
01695                                    unsigned &Idx);
01696 
01697   /// \brief Reads a declaration from the given position in a record in the
01698   /// given module.
01699   Decl *ReadDecl(ModuleFile &F, const RecordData &R, unsigned &I) {
01700     return GetDecl(ReadDeclID(F, R, I));
01701   }
01702 
01703   /// \brief Reads a declaration from the given position in a record in the
01704   /// given module.
01705   ///
01706   /// \returns The declaration read from this location, casted to the given
01707   /// result type.
01708   template<typename T>
01709   T *ReadDeclAs(ModuleFile &F, const RecordData &R, unsigned &I) {
01710     return cast_or_null<T>(GetDecl(ReadDeclID(F, R, I)));
01711   }
01712 
01713   /// \brief If any redeclarations of \p D have been imported since it was
01714   /// last checked, this digs out those redeclarations and adds them to the
01715   /// redeclaration chain for \p D.
01716   void CompleteRedeclChain(const Decl *D) override;
01717 
01718   /// \brief Read a CXXBaseSpecifiers ID form the given record and
01719   /// return its global bit offset.
01720   uint64_t readCXXBaseSpecifiers(ModuleFile &M, const RecordData &Record,
01721                                  unsigned &Idx);
01722 
01723   CXXBaseSpecifier *GetExternalCXXBaseSpecifiers(uint64_t Offset) override;
01724 
01725   /// \brief Resolve the offset of a statement into a statement.
01726   ///
01727   /// This operation will read a new statement from the external
01728   /// source each time it is called, and is meant to be used via a
01729   /// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
01730   Stmt *GetExternalDeclStmt(uint64_t Offset) override;
01731 
01732   /// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
01733   /// specified cursor.  Read the abbreviations that are at the top of the block
01734   /// and then leave the cursor pointing into the block.
01735   bool ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor, unsigned BlockID);
01736 
01737   /// \brief Finds all the visible declarations with a given name.
01738   /// The current implementation of this method just loads the entire
01739   /// lookup table as unmaterialized references.
01740   bool FindExternalVisibleDeclsByName(const DeclContext *DC,
01741                                       DeclarationName Name) override;
01742 
01743   /// \brief Read all of the declarations lexically stored in a
01744   /// declaration context.
01745   ///
01746   /// \param DC The declaration context whose declarations will be
01747   /// read.
01748   ///
01749   /// \param Decls Vector that will contain the declarations loaded
01750   /// from the external source. The caller is responsible for merging
01751   /// these declarations with any declarations already stored in the
01752   /// declaration context.
01753   ///
01754   /// \returns true if there was an error while reading the
01755   /// declarations for this declaration context.
01756   ExternalLoadResult FindExternalLexicalDecls(const DeclContext *DC,
01757                                 bool (*isKindWeWant)(Decl::Kind),
01758                                 SmallVectorImpl<Decl*> &Decls) override;
01759 
01760   /// \brief Get the decls that are contained in a file in the Offset/Length
01761   /// range. \p Length can be 0 to indicate a point at \p Offset instead of
01762   /// a range.
01763   void FindFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
01764                            SmallVectorImpl<Decl *> &Decls) override;
01765 
01766   /// \brief Notify ASTReader that we started deserialization of
01767   /// a decl or type so until FinishedDeserializing is called there may be
01768   /// decls that are initializing. Must be paired with FinishedDeserializing.
01769   void StartedDeserializing() override { ++NumCurrentElementsDeserializing; }
01770 
01771   /// \brief Notify ASTReader that we finished the deserialization of
01772   /// a decl or type. Must be paired with StartedDeserializing.
01773   void FinishedDeserializing() override;
01774 
01775   /// \brief Function that will be invoked when we begin parsing a new
01776   /// translation unit involving this external AST source.
01777   ///
01778   /// This function will provide all of the external definitions to
01779   /// the ASTConsumer.
01780   void StartTranslationUnit(ASTConsumer *Consumer) override;
01781 
01782   /// \brief Print some statistics about AST usage.
01783   void PrintStats() override;
01784 
01785   /// \brief Dump information about the AST reader to standard error.
01786   void dump();
01787 
01788   /// Return the amount of memory used by memory buffers, breaking down
01789   /// by heap-backed versus mmap'ed memory.
01790   void getMemoryBufferSizes(MemoryBufferSizes &sizes) const override;
01791 
01792   /// \brief Initialize the semantic source with the Sema instance
01793   /// being used to perform semantic analysis on the abstract syntax
01794   /// tree.
01795   void InitializeSema(Sema &S) override;
01796 
01797   /// \brief Inform the semantic consumer that Sema is no longer available.
01798   void ForgetSema() override { SemaObj = nullptr; }
01799 
01800   /// \brief Retrieve the IdentifierInfo for the named identifier.
01801   ///
01802   /// This routine builds a new IdentifierInfo for the given identifier. If any
01803   /// declarations with this name are visible from translation unit scope, their
01804   /// declarations will be deserialized and introduced into the declaration
01805   /// chain of the identifier.
01806   virtual IdentifierInfo *get(const char *NameStart, const char *NameEnd);
01807   IdentifierInfo *get(StringRef Name) override {
01808     return get(Name.begin(), Name.end());
01809   }
01810 
01811   /// \brief Retrieve an iterator into the set of all identifiers
01812   /// in all loaded AST files.
01813   IdentifierIterator *getIdentifiers() override;
01814 
01815   /// \brief Load the contents of the global method pool for a given
01816   /// selector.
01817   void ReadMethodPool(Selector Sel) override;
01818 
01819   /// \brief Load the set of namespaces that are known to the external source,
01820   /// which will be used during typo correction.
01821   void ReadKnownNamespaces(
01822                          SmallVectorImpl<NamespaceDecl *> &Namespaces) override;
01823 
01824   void ReadUndefinedButUsed(
01825                llvm::DenseMap<NamedDecl *, SourceLocation> &Undefined) override;
01826 
01827   void ReadTentativeDefinitions(
01828                             SmallVectorImpl<VarDecl *> &TentativeDefs) override;
01829 
01830   void ReadUnusedFileScopedDecls(
01831                        SmallVectorImpl<const DeclaratorDecl *> &Decls) override;
01832 
01833   void ReadDelegatingConstructors(
01834                          SmallVectorImpl<CXXConstructorDecl *> &Decls) override;
01835 
01836   void ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) override;
01837 
01838   void ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls) override;
01839 
01840   void ReadUnusedLocalTypedefNameCandidates(
01841       llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) override;
01842 
01843   void ReadLocallyScopedExternCDecls(
01844                                   SmallVectorImpl<NamedDecl *> &Decls) override;
01845 
01846   void ReadReferencedSelectors(
01847           SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) override;
01848 
01849   void ReadWeakUndeclaredIdentifiers(
01850           SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WI) override;
01851 
01852   void ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) override;
01853 
01854   void ReadPendingInstantiations(
01855                  SmallVectorImpl<std::pair<ValueDecl *,
01856                                            SourceLocation> > &Pending) override;
01857 
01858   void ReadLateParsedTemplates(
01859                          llvm::DenseMap<const FunctionDecl *,
01860                                         LateParsedTemplate *> &LPTMap) override;
01861 
01862   /// \brief Load a selector from disk, registering its ID if it exists.
01863   void LoadSelector(Selector Sel);
01864 
01865   void SetIdentifierInfo(unsigned ID, IdentifierInfo *II);
01866   void SetGloballyVisibleDecls(IdentifierInfo *II,
01867                                const SmallVectorImpl<uint32_t> &DeclIDs,
01868                                SmallVectorImpl<Decl *> *Decls = nullptr);
01869 
01870   /// \brief Report a diagnostic.
01871   DiagnosticBuilder Diag(unsigned DiagID);
01872 
01873   /// \brief Report a diagnostic.
01874   DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
01875 
01876   IdentifierInfo *DecodeIdentifierInfo(serialization::IdentifierID ID);
01877 
01878   IdentifierInfo *GetIdentifierInfo(ModuleFile &M, const RecordData &Record,
01879                                     unsigned &Idx) {
01880     return DecodeIdentifierInfo(getGlobalIdentifierID(M, Record[Idx++]));
01881   }
01882 
01883   IdentifierInfo *GetIdentifier(serialization::IdentifierID ID) override {
01884     // Note that we are loading an identifier.
01885     Deserializing AnIdentifier(this);
01886 
01887     return DecodeIdentifierInfo(ID);
01888   }
01889 
01890   IdentifierInfo *getLocalIdentifier(ModuleFile &M, unsigned LocalID);
01891 
01892   serialization::IdentifierID getGlobalIdentifierID(ModuleFile &M,
01893                                                     unsigned LocalID);
01894 
01895   ModuleMacroInfo *getModuleMacro(const PendingMacroInfo &PMInfo);
01896 
01897   void resolvePendingMacro(IdentifierInfo *II, const PendingMacroInfo &PMInfo);
01898 
01899   void installPCHMacroDirectives(IdentifierInfo *II,
01900                                  ModuleFile &M, uint64_t Offset);
01901 
01902   void installImportedMacro(IdentifierInfo *II, ModuleMacroInfo *MMI,
01903                             Module *Owner);
01904 
01905   typedef llvm::TinyPtrVector<DefMacroDirective *> AmbiguousMacros;
01906   llvm::DenseMap<IdentifierInfo*, AmbiguousMacros> AmbiguousMacroDefs;
01907 
01908   void
01909   removeOverriddenMacros(IdentifierInfo *II, SourceLocation Loc,
01910                          AmbiguousMacros &Ambig,
01911                          ArrayRef<serialization::SubmoduleID> Overrides);
01912 
01913   AmbiguousMacros *
01914   removeOverriddenMacros(IdentifierInfo *II, SourceLocation Loc,
01915                          ArrayRef<serialization::SubmoduleID> Overrides);
01916 
01917   /// \brief Retrieve the macro with the given ID.
01918   MacroInfo *getMacro(serialization::MacroID ID);
01919 
01920   /// \brief Retrieve the global macro ID corresponding to the given local
01921   /// ID within the given module file.
01922   serialization::MacroID getGlobalMacroID(ModuleFile &M, unsigned LocalID);
01923 
01924   /// \brief Read the source location entry with index ID.
01925   bool ReadSLocEntry(int ID) override;
01926 
01927   /// \brief Retrieve the module import location and module name for the
01928   /// given source manager entry ID.
01929   std::pair<SourceLocation, StringRef> getModuleImportLoc(int ID) override;
01930 
01931   /// \brief Retrieve the global submodule ID given a module and its local ID
01932   /// number.
01933   serialization::SubmoduleID 
01934   getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID);
01935   
01936   /// \brief Retrieve the submodule that corresponds to a global submodule ID.
01937   ///
01938   Module *getSubmodule(serialization::SubmoduleID GlobalID);
01939 
01940   /// \brief Retrieve the module that corresponds to the given module ID.
01941   ///
01942   /// Note: overrides method in ExternalASTSource
01943   Module *getModule(unsigned ID) override;
01944 
01945   /// \brief Retrieve a selector from the given module with its local ID
01946   /// number.
01947   Selector getLocalSelector(ModuleFile &M, unsigned LocalID);
01948 
01949   Selector DecodeSelector(serialization::SelectorID Idx);
01950 
01951   Selector GetExternalSelector(serialization::SelectorID ID) override;
01952   uint32_t GetNumExternalSelectors() override;
01953 
01954   Selector ReadSelector(ModuleFile &M, const RecordData &Record, unsigned &Idx) {
01955     return getLocalSelector(M, Record[Idx++]);
01956   }
01957 
01958   /// \brief Retrieve the global selector ID that corresponds to this
01959   /// the local selector ID in a given module.
01960   serialization::SelectorID getGlobalSelectorID(ModuleFile &F,
01961                                                 unsigned LocalID) const;
01962 
01963   /// \brief Read a declaration name.
01964   DeclarationName ReadDeclarationName(ModuleFile &F,
01965                                       const RecordData &Record, unsigned &Idx);
01966   void ReadDeclarationNameLoc(ModuleFile &F,
01967                               DeclarationNameLoc &DNLoc, DeclarationName Name,
01968                               const RecordData &Record, unsigned &Idx);
01969   void ReadDeclarationNameInfo(ModuleFile &F, DeclarationNameInfo &NameInfo,
01970                                const RecordData &Record, unsigned &Idx);
01971 
01972   void ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
01973                          const RecordData &Record, unsigned &Idx);
01974 
01975   NestedNameSpecifier *ReadNestedNameSpecifier(ModuleFile &F,
01976                                                const RecordData &Record,
01977                                                unsigned &Idx);
01978 
01979   NestedNameSpecifierLoc ReadNestedNameSpecifierLoc(ModuleFile &F,
01980                                                     const RecordData &Record,
01981                                                     unsigned &Idx);
01982 
01983   /// \brief Read a template name.
01984   TemplateName ReadTemplateName(ModuleFile &F, const RecordData &Record,
01985                                 unsigned &Idx);
01986 
01987   /// \brief Read a template argument.
01988   TemplateArgument ReadTemplateArgument(ModuleFile &F,
01989                                         const RecordData &Record,unsigned &Idx);
01990 
01991   /// \brief Read a template parameter list.
01992   TemplateParameterList *ReadTemplateParameterList(ModuleFile &F,
01993                                                    const RecordData &Record,
01994                                                    unsigned &Idx);
01995 
01996   /// \brief Read a template argument array.
01997   void
01998   ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
01999                            ModuleFile &F, const RecordData &Record,
02000                            unsigned &Idx);
02001 
02002   /// \brief Read a UnresolvedSet structure.
02003   void ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
02004                          const RecordData &Record, unsigned &Idx);
02005 
02006   /// \brief Read a C++ base specifier.
02007   CXXBaseSpecifier ReadCXXBaseSpecifier(ModuleFile &F,
02008                                         const RecordData &Record,unsigned &Idx);
02009 
02010   /// \brief Read a CXXCtorInitializer array.
02011   std::pair<CXXCtorInitializer **, unsigned>
02012   ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
02013                           unsigned &Idx);
02014 
02015   /// \brief Read a source location from raw form.
02016   SourceLocation ReadSourceLocation(ModuleFile &ModuleFile, unsigned Raw) const {
02017     SourceLocation Loc = SourceLocation::getFromRawEncoding(Raw);
02018     assert(ModuleFile.SLocRemap.find(Loc.getOffset()) != ModuleFile.SLocRemap.end() &&
02019            "Cannot find offset to remap.");
02020     int Remap = ModuleFile.SLocRemap.find(Loc.getOffset())->second;
02021     return Loc.getLocWithOffset(Remap);
02022   }
02023 
02024   /// \brief Read a source location.
02025   SourceLocation ReadSourceLocation(ModuleFile &ModuleFile,
02026                                     const RecordDataImpl &Record,
02027                                     unsigned &Idx) {
02028     return ReadSourceLocation(ModuleFile, Record[Idx++]);
02029   }
02030 
02031   /// \brief Read a source range.
02032   SourceRange ReadSourceRange(ModuleFile &F,
02033                               const RecordData &Record, unsigned &Idx);
02034 
02035   /// \brief Read an integral value
02036   llvm::APInt ReadAPInt(const RecordData &Record, unsigned &Idx);
02037 
02038   /// \brief Read a signed integral value
02039   llvm::APSInt ReadAPSInt(const RecordData &Record, unsigned &Idx);
02040 
02041   /// \brief Read a floating-point value
02042   llvm::APFloat ReadAPFloat(const RecordData &Record,
02043                             const llvm::fltSemantics &Sem, unsigned &Idx);
02044 
02045   // \brief Read a string
02046   static std::string ReadString(const RecordData &Record, unsigned &Idx);
02047 
02048   /// \brief Read a version tuple.
02049   static VersionTuple ReadVersionTuple(const RecordData &Record, unsigned &Idx);
02050 
02051   CXXTemporary *ReadCXXTemporary(ModuleFile &F, const RecordData &Record,
02052                                  unsigned &Idx);
02053 
02054   /// \brief Reads attributes from the current stream position.
02055   void ReadAttributes(ModuleFile &F, AttrVec &Attrs,
02056                       const RecordData &Record, unsigned &Idx);
02057 
02058   /// \brief Reads a statement.
02059   Stmt *ReadStmt(ModuleFile &F);
02060 
02061   /// \brief Reads an expression.
02062   Expr *ReadExpr(ModuleFile &F);
02063 
02064   /// \brief Reads a sub-statement operand during statement reading.
02065   Stmt *ReadSubStmt() {
02066     assert(ReadingKind == Read_Stmt &&
02067            "Should be called only during statement reading!");
02068     // Subexpressions are stored from last to first, so the next Stmt we need
02069     // is at the back of the stack.
02070     assert(!StmtStack.empty() && "Read too many sub-statements!");
02071     return StmtStack.pop_back_val();
02072   }
02073 
02074   /// \brief Reads a sub-expression operand during statement reading.
02075   Expr *ReadSubExpr();
02076 
02077   /// \brief Reads a token out of a record.
02078   Token ReadToken(ModuleFile &M, const RecordDataImpl &Record, unsigned &Idx);
02079 
02080   /// \brief Reads the macro record located at the given offset.
02081   MacroInfo *ReadMacroRecord(ModuleFile &F, uint64_t Offset);
02082 
02083   /// \brief Determine the global preprocessed entity ID that corresponds to
02084   /// the given local ID within the given module.
02085   serialization::PreprocessedEntityID
02086   getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const;
02087 
02088   /// \brief Add a macro to resolve imported from a module.
02089   ///
02090   /// \param II The name of the macro.
02091   /// \param M The module file.
02092   /// \param GMacID The global macro ID that is associated with this identifier.
02093   void addPendingMacroFromModule(IdentifierInfo *II,
02094                                  ModuleFile *M,
02095                                  serialization::GlobalMacroID GMacID,
02096                                  ArrayRef<serialization::SubmoduleID>);
02097 
02098   /// \brief Add a macro to deserialize its macro directive history from a PCH.
02099   ///
02100   /// \param II The name of the macro.
02101   /// \param M The module file.
02102   /// \param MacroDirectivesOffset Offset of the serialized macro directive
02103   /// history.
02104   void addPendingMacroFromPCH(IdentifierInfo *II,
02105                               ModuleFile *M, uint64_t MacroDirectivesOffset);
02106 
02107   /// \brief Read the set of macros defined by this external macro source.
02108   void ReadDefinedMacros() override;
02109 
02110   /// \brief Update an out-of-date identifier.
02111   void updateOutOfDateIdentifier(IdentifierInfo &II) override;
02112 
02113   /// \brief Note that this identifier is up-to-date.
02114   void markIdentifierUpToDate(IdentifierInfo *II);
02115 
02116   /// \brief Load all external visible decls in the given DeclContext.
02117   void completeVisibleDeclsMap(const DeclContext *DC) override;
02118 
02119   /// \brief Retrieve the AST context that this AST reader supplements.
02120   ASTContext &getContext() { return Context; }
02121 
02122   // \brief Contains the IDs for declarations that were requested before we have
02123   // access to a Sema object.
02124   SmallVector<uint64_t, 16> PreloadedDeclIDs;
02125 
02126   /// \brief Retrieve the semantic analysis object used to analyze the
02127   /// translation unit in which the precompiled header is being
02128   /// imported.
02129   Sema *getSema() { return SemaObj; }
02130 
02131   /// \brief Retrieve the identifier table associated with the
02132   /// preprocessor.
02133   IdentifierTable &getIdentifierTable();
02134 
02135   /// \brief Record that the given ID maps to the given switch-case
02136   /// statement.
02137   void RecordSwitchCaseID(SwitchCase *SC, unsigned ID);
02138 
02139   /// \brief Retrieve the switch-case statement with the given ID.
02140   SwitchCase *getSwitchCaseWithID(unsigned ID);
02141 
02142   void ClearSwitchCaseIDs();
02143 
02144   /// \brief Cursors for comments blocks.
02145   SmallVector<std::pair<llvm::BitstreamCursor,
02146                         serialization::ModuleFile *>, 8> CommentsCursors;
02147 
02148   //RIDErief Loads comments ranges.
02149   void ReadComments() override;
02150 
02151   /// Return all input files for the given module file.
02152   void getInputFiles(ModuleFile &F,
02153                      SmallVectorImpl<serialization::InputFile> &Files);
02154 };
02155 
02156 /// \brief Helper class that saves the current stream position and
02157 /// then restores it when destroyed.
02158 struct SavedStreamPosition {
02159   explicit SavedStreamPosition(llvm::BitstreamCursor &Cursor)
02160     : Cursor(Cursor), Offset(Cursor.GetCurrentBitNo()) { }
02161 
02162   ~SavedStreamPosition() {
02163     Cursor.JumpToBit(Offset);
02164   }
02165 
02166 private:
02167   llvm::BitstreamCursor &Cursor;
02168   uint64_t Offset;
02169 };
02170 
02171 inline void PCHValidator::Error(const char *Msg) {
02172   Reader.Error(Msg);
02173 }
02174 
02175 } // end namespace clang
02176 
02177 #endif