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