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