ASTReader.h revision f249bf3b9f8bd3af711ffe9de411fc435871a4f6
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/Serialization/ASTBitCodes.h"
18#include "clang/Serialization/ContinuousRangeMap.h"
19#include "clang/Serialization/Module.h"
20#include "clang/Serialization/ModuleManager.h"
21#include "clang/Sema/ExternalSemaSource.h"
22#include "clang/AST/DeclarationName.h"
23#include "clang/AST/DeclObjC.h"
24#include "clang/AST/TemplateBase.h"
25#include "clang/Lex/ExternalPreprocessorSource.h"
26#include "clang/Lex/HeaderSearch.h"
27#include "clang/Lex/PreprocessingRecord.h"
28#include "clang/Basic/Diagnostic.h"
29#include "clang/Basic/FileManager.h"
30#include "clang/Basic/FileSystemOptions.h"
31#include "clang/Basic/IdentifierTable.h"
32#include "clang/Basic/SourceManager.h"
33#include "llvm/ADT/APFloat.h"
34#include "llvm/ADT/APInt.h"
35#include "llvm/ADT/APSInt.h"
36#include "llvm/ADT/OwningPtr.h"
37#include "llvm/ADT/SmallVector.h"
38#include "llvm/ADT/StringRef.h"
39#include "llvm/Bitcode/BitstreamReader.h"
40#include "llvm/Support/DataTypes.h"
41#include <deque>
42#include <map>
43#include <string>
44#include <utility>
45#include <vector>
46
47namespace llvm {
48  class MemoryBuffer;
49}
50
51namespace clang {
52
53class AddrLabelExpr;
54class ASTConsumer;
55class ASTContext;
56class ASTIdentifierIterator;
57class ASTUnit; // FIXME: Layering violation and egregious hack.
58class Attr;
59class Decl;
60class DeclContext;
61class NestedNameSpecifier;
62class CXXBaseSpecifier;
63class CXXConstructorDecl;
64class CXXCtorInitializer;
65class GotoStmt;
66class MacroDefinition;
67class NamedDecl;
68class OpaqueValueExpr;
69class Preprocessor;
70class Sema;
71class SwitchCase;
72class ASTDeserializationListener;
73class ASTWriter;
74class ASTReader;
75class ASTDeclReader;
76class ASTStmtReader;
77class TypeLocReader;
78struct HeaderFileInfo;
79class VersionTuple;
80
81struct PCHPredefinesBlock {
82  /// \brief The file ID for this predefines buffer in a PCH file.
83  FileID BufferID;
84
85  /// \brief This predefines buffer in a PCH file.
86  StringRef Data;
87};
88typedef SmallVector<PCHPredefinesBlock, 2> PCHPredefinesBlocks;
89
90/// \brief Abstract interface for callback invocations by the ASTReader.
91///
92/// While reading an AST file, the ASTReader will call the methods of the
93/// listener to pass on specific information. Some of the listener methods can
94/// return true to indicate to the ASTReader that the information (and
95/// consequently the AST file) is invalid.
96class ASTReaderListener {
97public:
98  virtual ~ASTReaderListener();
99
100  /// \brief Receives the language options.
101  ///
102  /// \returns true to indicate the options are invalid or false otherwise.
103  virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
104    return false;
105  }
106
107  /// \brief Receives the target triple.
108  ///
109  /// \returns true to indicate the target triple is invalid or false otherwise.
110  virtual bool ReadTargetTriple(StringRef Triple) {
111    return false;
112  }
113
114  /// \brief Receives the contents of the predefines buffer.
115  ///
116  /// \param Buffers Information about the predefines buffers.
117  ///
118  /// \param OriginalFileName The original file name for the AST file, which
119  /// will appear as an entry in the predefines buffer.
120  ///
121  /// \param SuggestedPredefines If necessary, additional definitions are added
122  /// here.
123  ///
124  /// \returns true to indicate the predefines are invalid or false otherwise.
125  virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
126                                    StringRef OriginalFileName,
127                                    std::string &SuggestedPredefines,
128                                    FileManager &FileMgr) {
129    return false;
130  }
131
132  /// \brief Receives a HeaderFileInfo entry.
133  virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {}
134
135  /// \brief Receives __COUNTER__ value.
136  virtual void ReadCounter(unsigned Value) {}
137};
138
139/// \brief ASTReaderListener implementation to validate the information of
140/// the PCH file against an initialized Preprocessor.
141class PCHValidator : public ASTReaderListener {
142  Preprocessor &PP;
143  ASTReader &Reader;
144
145  unsigned NumHeaderInfos;
146
147public:
148  PCHValidator(Preprocessor &PP, ASTReader &Reader)
149    : PP(PP), Reader(Reader), NumHeaderInfos(0) {}
150
151  virtual bool ReadLanguageOptions(const LangOptions &LangOpts);
152  virtual bool ReadTargetTriple(StringRef Triple);
153  virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
154                                    StringRef OriginalFileName,
155                                    std::string &SuggestedPredefines,
156                                    FileManager &FileMgr);
157  virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID);
158  virtual void ReadCounter(unsigned Value);
159
160private:
161  void Error(const char *Msg);
162};
163
164namespace serialization {
165
166class ReadMethodPoolVisitor;
167
168namespace reader {
169  class ASTIdentifierLookupTrait;
170}
171
172} // end namespace serialization
173
174/// \brief Reads an AST files chain containing the contents of a translation
175/// unit.
176///
177/// The ASTReader class reads bitstreams (produced by the ASTWriter
178/// class) containing the serialized representation of a given
179/// abstract syntax tree and its supporting data structures. An
180/// instance of the ASTReader can be attached to an ASTContext object,
181/// which will provide access to the contents of the AST files.
182///
183/// The AST reader provides lazy de-serialization of declarations, as
184/// required when traversing the AST. Only those AST nodes that are
185/// actually required will be de-serialized.
186class ASTReader
187  : public ExternalPreprocessorSource,
188    public ExternalPreprocessingRecordSource,
189    public ExternalHeaderFileInfoSource,
190    public ExternalSemaSource,
191    public IdentifierInfoLookup,
192    public ExternalIdentifierLookup,
193    public ExternalSLocEntrySource
194{
195public:
196  enum ASTReadResult { Success, Failure, IgnorePCH };
197  /// \brief Types of AST files.
198  friend class PCHValidator;
199  friend class ASTDeclReader;
200  friend class ASTStmtReader;
201  friend class ASTIdentifierIterator;
202  friend class serialization::reader::ASTIdentifierLookupTrait;
203  friend class TypeLocReader;
204  friend class ASTWriter;
205  friend class ASTUnit; // ASTUnit needs to remap source locations.
206  friend class serialization::ReadMethodPoolVisitor;
207
208  typedef serialization::Module Module;
209  typedef serialization::ModuleKind ModuleKind;
210  typedef serialization::ModuleManager ModuleManager;
211
212  typedef ModuleManager::ModuleIterator ModuleIterator;
213  typedef ModuleManager::ModuleConstIterator ModuleConstIterator;
214  typedef ModuleManager::ModuleReverseIterator ModuleReverseIterator;
215
216private:
217  /// \brief The receiver of some callbacks invoked by ASTReader.
218  llvm::OwningPtr<ASTReaderListener> Listener;
219
220  /// \brief The receiver of deserialization events.
221  ASTDeserializationListener *DeserializationListener;
222
223  SourceManager &SourceMgr;
224  FileManager &FileMgr;
225  Diagnostic &Diags;
226
227  /// \brief The semantic analysis object that will be processing the
228  /// AST files and the translation unit that uses it.
229  Sema *SemaObj;
230
231  /// \brief The preprocessor that will be loading the source file.
232  Preprocessor *PP;
233
234  /// \brief The AST context into which we'll read the AST files.
235  ASTContext *Context;
236
237  /// \brief The AST consumer.
238  ASTConsumer *Consumer;
239
240  /// \brief The module manager which manages modules and their dependencies
241  ModuleManager ModuleMgr;
242
243  /// \brief A map of global bit offsets to the module that stores entities
244  /// at those bit offsets.
245  ContinuousRangeMap<uint64_t, Module*, 4> GlobalBitOffsetsMap;
246
247  /// \brief A map of negated SLocEntryIDs to the modules containing them.
248  ContinuousRangeMap<unsigned, Module*, 64> GlobalSLocEntryMap;
249
250  /// \brief Types that have already been loaded from the chain.
251  ///
252  /// When the pointer at index I is non-NULL, the type with
253  /// ID = (I + 1) << FastQual::Width has already been loaded
254  std::vector<QualType> TypesLoaded;
255
256  typedef ContinuousRangeMap<serialization::TypeID, Module *, 4>
257    GlobalTypeMapType;
258
259  /// \brief Mapping from global type IDs to the module in which the
260  /// type resides along with the offset that should be added to the
261  /// global type ID to produce a local ID.
262  GlobalTypeMapType GlobalTypeMap;
263
264  /// \brief Declarations that have already been loaded from the chain.
265  ///
266  /// When the pointer at index I is non-NULL, the declaration with ID
267  /// = I + 1 has already been loaded.
268  std::vector<Decl *> DeclsLoaded;
269
270  typedef ContinuousRangeMap<serialization::DeclID, Module *, 4>
271    GlobalDeclMapType;
272
273  /// \brief Mapping from global declaration IDs to the module in which the
274  /// declaration resides.
275  GlobalDeclMapType GlobalDeclMap;
276
277  typedef std::pair<Module *, uint64_t> FileOffset;
278  typedef SmallVector<FileOffset, 2> FileOffsetsTy;
279  typedef llvm::DenseMap<serialization::DeclID, FileOffsetsTy>
280      DeclUpdateOffsetsMap;
281
282  /// \brief Declarations that have modifications residing in a later file
283  /// in the chain.
284  DeclUpdateOffsetsMap DeclUpdateOffsets;
285
286  typedef llvm::DenseMap<serialization::DeclID,
287                         std::pair<Module *, uint64_t> >
288      DeclReplacementMap;
289  /// \brief Declarations that have been replaced in a later file in the chain.
290  DeclReplacementMap ReplacedDecls;
291
292  // Updates for visible decls can occur for other contexts than just the
293  // TU, and when we read those update records, the actual context will not
294  // be available yet (unless it's the TU), so have this pending map using the
295  // ID as a key. It will be realized when the context is actually loaded.
296  typedef SmallVector<std::pair<void *, Module*>, 1> DeclContextVisibleUpdates;
297  typedef llvm::DenseMap<serialization::DeclID, DeclContextVisibleUpdates>
298      DeclContextVisibleUpdatesPending;
299
300  /// \brief Updates to the visible declarations of declaration contexts that
301  /// haven't been loaded yet.
302  DeclContextVisibleUpdatesPending PendingVisibleUpdates;
303
304  typedef SmallVector<CXXRecordDecl *, 4> ForwardRefs;
305  typedef llvm::DenseMap<const CXXRecordDecl *, ForwardRefs>
306      PendingForwardRefsMap;
307  /// \brief Forward references that have a definition but the definition decl
308  /// is still initializing. When the definition gets read it will update
309  /// the DefinitionData pointer of all pending references.
310  PendingForwardRefsMap PendingForwardRefs;
311
312  typedef llvm::DenseMap<serialization::DeclID, serialization::DeclID>
313      FirstLatestDeclIDMap;
314  /// \brief Map of first declarations from a chained PCH that point to the
315  /// most recent declarations in another AST file.
316  FirstLatestDeclIDMap FirstLatestDeclIDs;
317
318  /// \brief Read the records that describe the contents of declcontexts.
319  bool ReadDeclContextStorage(Module &M,
320                              llvm::BitstreamCursor &Cursor,
321                              const std::pair<uint64_t, uint64_t> &Offsets,
322                              serialization::DeclContextInfo &Info);
323
324  /// \brief A vector containing identifiers that have already been
325  /// loaded.
326  ///
327  /// If the pointer at index I is non-NULL, then it refers to the
328  /// IdentifierInfo for the identifier with ID=I+1 that has already
329  /// been loaded.
330  std::vector<IdentifierInfo *> IdentifiersLoaded;
331
332  typedef ContinuousRangeMap<serialization::IdentID, Module *, 4>
333    GlobalIdentifierMapType;
334
335  /// \brief Mapping from global identifer IDs to the module in which the
336  /// identifier resides along with the offset that should be added to the
337  /// global identifier ID to produce a local ID.
338  GlobalIdentifierMapType GlobalIdentifierMap;
339
340  /// \brief A vector containing selectors that have already been loaded.
341  ///
342  /// This vector is indexed by the Selector ID (-1). NULL selector
343  /// entries indicate that the particular selector ID has not yet
344  /// been loaded.
345  SmallVector<Selector, 16> SelectorsLoaded;
346
347  typedef ContinuousRangeMap<serialization::SelectorID, Module *, 4>
348    GlobalSelectorMapType;
349
350  /// \brief Mapping from global selector IDs to the module in which the
351  /// selector resides along with the offset that should be added to the
352  /// global selector ID to produce a local ID.
353  GlobalSelectorMapType GlobalSelectorMap;
354
355  /// \brief The macro definitions we have already loaded.
356  SmallVector<MacroDefinition *, 16> MacroDefinitionsLoaded;
357
358  typedef ContinuousRangeMap<serialization::MacroID, Module *, 4>
359    GlobalMacroDefinitionMapType;
360
361  /// \brief Mapping from global macro definition IDs to the module in which the
362  /// selector resides along with the offset that should be added to the
363  /// global selector ID to produce a local ID.
364  GlobalMacroDefinitionMapType GlobalMacroDefinitionMap;
365
366  /// \brief Mapping from identifiers that represent macros whose definitions
367  /// have not yet been deserialized to the global offset where the macro
368  /// record resides.
369  llvm::DenseMap<IdentifierInfo *, uint64_t> UnreadMacroRecordOffsets;
370
371  typedef ContinuousRangeMap<unsigned, Module *, 4>
372    GlobalPreprocessedEntityMapType;
373
374  /// \brief Mapping from global preprocessing entity IDs to the module in
375  /// which the preprocessed entity resides along with the offset that should be
376  /// added to the global preprocessing entitiy ID to produce a local ID.
377  GlobalPreprocessedEntityMapType GlobalPreprocessedEntityMap;
378
379  /// \name CodeGen-relevant special data
380  /// \brief Fields containing data that is relevant to CodeGen.
381  //@{
382
383  /// \brief The IDs of all declarations that fulfill the criteria of
384  /// "interesting" decls.
385  ///
386  /// This contains the data loaded from all EXTERNAL_DEFINITIONS blocks in the
387  /// chain. The referenced declarations are deserialized and passed to the
388  /// consumer eagerly.
389  SmallVector<uint64_t, 16> ExternalDefinitions;
390
391  /// \brief The IDs of all tentative definitions stored in the the chain.
392  ///
393  /// Sema keeps track of all tentative definitions in a TU because it has to
394  /// complete them and pass them on to CodeGen. Thus, tentative definitions in
395  /// the PCH chain must be eagerly deserialized.
396  SmallVector<uint64_t, 16> TentativeDefinitions;
397
398  /// \brief The IDs of all CXXRecordDecls stored in the chain whose VTables are
399  /// used.
400  ///
401  /// CodeGen has to emit VTables for these records, so they have to be eagerly
402  /// deserialized.
403  SmallVector<uint64_t, 64> VTableUses;
404
405  /// \brief A snapshot of the pending instantiations in the chain.
406  ///
407  /// This record tracks the instantiations that Sema has to perform at the
408  /// end of the TU. It consists of a pair of values for every pending
409  /// instantiation where the first value is the ID of the decl and the second
410  /// is the instantiation location.
411  SmallVector<uint64_t, 64> PendingInstantiations;
412
413  //@}
414
415  /// \name Diagnostic-relevant special data
416  /// \brief Fields containing data that is used for generating diagnostics
417  //@{
418
419  /// \brief A snapshot of Sema's unused file-scoped variable tracking, for
420  /// generating warnings.
421  SmallVector<uint64_t, 16> UnusedFileScopedDecls;
422
423  /// \brief A list of all the delegating constructors we've seen, to diagnose
424  /// cycles.
425  SmallVector<uint64_t, 4> DelegatingCtorDecls;
426
427  /// \brief Method selectors used in a @selector expression. Used for
428  /// implementation of -Wselector.
429  SmallVector<uint64_t, 64> ReferencedSelectorsData;
430
431  /// \brief A snapshot of Sema's weak undeclared identifier tracking, for
432  /// generating warnings.
433  SmallVector<uint64_t, 64> WeakUndeclaredIdentifiers;
434
435  /// \brief The IDs of type aliases for ext_vectors that exist in the chain.
436  ///
437  /// Used by Sema for finding sugared names for ext_vectors in diagnostics.
438  SmallVector<uint64_t, 4> ExtVectorDecls;
439
440  //@}
441
442  /// \name Sema-relevant special data
443  /// \brief Fields containing data that is used for semantic analysis
444  //@{
445
446  /// \brief The IDs of all locally scoped external decls in the chain.
447  ///
448  /// Sema tracks these to validate that the types are consistent across all
449  /// local external declarations.
450  SmallVector<uint64_t, 16> LocallyScopedExternalDecls;
451
452  /// \brief The IDs of all dynamic class declarations in the chain.
453  ///
454  /// Sema tracks these because it checks for the key functions being defined
455  /// at the end of the TU, in which case it directs CodeGen to emit the VTable.
456  SmallVector<uint64_t, 16> DynamicClasses;
457
458  /// \brief The IDs of the declarations Sema stores directly.
459  ///
460  /// Sema tracks a few important decls, such as namespace std, directly.
461  SmallVector<uint64_t, 4> SemaDeclRefs;
462
463  /// \brief The IDs of the types ASTContext stores directly.
464  ///
465  /// The AST context tracks a few important types, such as va_list, directly.
466  SmallVector<uint64_t, 16> SpecialTypes;
467
468  /// \brief The IDs of CUDA-specific declarations ASTContext stores directly.
469  ///
470  /// The AST context tracks a few important decls, currently cudaConfigureCall,
471  /// directly.
472  SmallVector<uint64_t, 2> CUDASpecialDeclRefs;
473
474  /// \brief The floating point pragma option settings.
475  SmallVector<uint64_t, 1> FPPragmaOptions;
476
477  /// \brief The OpenCL extension settings.
478  SmallVector<uint64_t, 1> OpenCLExtensions;
479
480  /// \brief A list of the namespaces we've seen.
481  SmallVector<uint64_t, 4> KnownNamespaces;
482
483  //@}
484
485  /// \brief The original file name that was used to build the primary AST file,
486  /// which may have been modified for relocatable-pch support.
487  std::string OriginalFileName;
488
489  /// \brief The actual original file name that was used to build the primary
490  /// AST file.
491  std::string ActualOriginalFileName;
492
493  /// \brief The file ID for the original file that was used to build the
494  /// primary AST file.
495  FileID OriginalFileID;
496
497  /// \brief The directory that the PCH was originally created in. Used to
498  /// allow resolving headers even after headers+PCH was moved to a new path.
499  std::string OriginalDir;
500
501  /// \brief The directory that the PCH we are reading is stored in.
502  std::string CurrentDir;
503
504  /// \brief Whether this precompiled header is a relocatable PCH file.
505  bool RelocatablePCH;
506
507  /// \brief The system include root to be used when loading the
508  /// precompiled header.
509  std::string isysroot;
510
511  /// \brief Whether to disable the normal validation performed on precompiled
512  /// headers when they are loaded.
513  bool DisableValidation;
514
515  /// \brief Whether to disable the use of stat caches in AST files.
516  bool DisableStatCache;
517
518  /// \brief Mapping from switch-case IDs in the chain to switch-case statements
519  ///
520  /// Statements usually don't have IDs, but switch cases need them, so that the
521  /// switch statement can refer to them.
522  std::map<unsigned, SwitchCase *> SwitchCaseStmts;
523
524  /// \brief Mapping from opaque value IDs to OpaqueValueExprs.
525  std::map<unsigned, OpaqueValueExpr*> OpaqueValueExprs;
526
527  /// \brief The number of stat() calls that hit/missed the stat
528  /// cache.
529  unsigned NumStatHits, NumStatMisses;
530
531  /// \brief The number of source location entries de-serialized from
532  /// the PCH file.
533  unsigned NumSLocEntriesRead;
534
535  /// \brief The number of source location entries in the chain.
536  unsigned TotalNumSLocEntries;
537
538  /// \brief The number of statements (and expressions) de-serialized
539  /// from the chain.
540  unsigned NumStatementsRead;
541
542  /// \brief The total number of statements (and expressions) stored
543  /// in the chain.
544  unsigned TotalNumStatements;
545
546  /// \brief The number of macros de-serialized from the chain.
547  unsigned NumMacrosRead;
548
549  /// \brief The total number of macros stored in the chain.
550  unsigned TotalNumMacros;
551
552  /// \brief The number of selectors that have been read.
553  unsigned NumSelectorsRead;
554
555  /// \brief The number of method pool entries that have been read.
556  unsigned NumMethodPoolEntriesRead;
557
558  /// \brief The number of times we have looked up a selector in the method
559  /// pool and not found anything interesting.
560  unsigned NumMethodPoolMisses;
561
562  /// \brief The total number of method pool entries in the selector table.
563  unsigned TotalNumMethodPoolEntries;
564
565  /// Number of lexical decl contexts read/total.
566  unsigned NumLexicalDeclContextsRead, TotalLexicalDeclContexts;
567
568  /// Number of visible decl contexts read/total.
569  unsigned NumVisibleDeclContextsRead, TotalVisibleDeclContexts;
570
571  /// Total size of modules, in bits, currently loaded
572  uint64_t TotalModulesSizeInBits;
573
574  /// \brief Number of Decl/types that are currently deserializing.
575  unsigned NumCurrentElementsDeserializing;
576
577  /// Number of CXX base specifiers currently loaded
578  unsigned NumCXXBaseSpecifiersLoaded;
579
580  /// \brief An IdentifierInfo that has been loaded but whose top-level
581  /// declarations of the same name have not (yet) been loaded.
582  struct PendingIdentifierInfo {
583    IdentifierInfo *II;
584    SmallVector<uint32_t, 4> DeclIDs;
585  };
586
587  /// \brief The set of identifiers that were read while the AST reader was
588  /// (recursively) loading declarations.
589  ///
590  /// The declarations on the identifier chain for these identifiers will be
591  /// loaded once the recursive loading has completed.
592  std::deque<PendingIdentifierInfo> PendingIdentifierInfos;
593
594  /// \brief Contains declarations and definitions that will be
595  /// "interesting" to the ASTConsumer, when we get that AST consumer.
596  ///
597  /// "Interesting" declarations are those that have data that may
598  /// need to be emitted, such as inline function definitions or
599  /// Objective-C protocols.
600  std::deque<Decl *> InterestingDecls;
601
602  /// \brief We delay loading of the previous declaration chain to avoid
603  /// deeply nested calls when there are many redeclarations.
604  std::deque<std::pair<Decl *, serialization::DeclID> > PendingPreviousDecls;
605
606  /// \brief Ready to load the previous declaration of the given Decl.
607  void loadAndAttachPreviousDecl(Decl *D, serialization::DeclID ID);
608
609  /// \brief When reading a Stmt tree, Stmt operands are placed in this stack.
610  SmallVector<Stmt *, 16> StmtStack;
611
612  /// \brief What kind of records we are reading.
613  enum ReadingKind {
614    Read_Decl, Read_Type, Read_Stmt
615  };
616
617  /// \brief What kind of records we are reading.
618  ReadingKind ReadingKind;
619
620  /// \brief RAII object to change the reading kind.
621  class ReadingKindTracker {
622    ASTReader &Reader;
623    enum ReadingKind PrevKind;
624
625    ReadingKindTracker(const ReadingKindTracker&); // do not implement
626    ReadingKindTracker &operator=(const ReadingKindTracker&);// do not implement
627
628  public:
629    ReadingKindTracker(enum ReadingKind newKind, ASTReader &reader)
630      : Reader(reader), PrevKind(Reader.ReadingKind) {
631      Reader.ReadingKind = newKind;
632    }
633
634    ~ReadingKindTracker() { Reader.ReadingKind = PrevKind; }
635  };
636
637  /// \brief All predefines buffers in the chain, to be treated as if
638  /// concatenated.
639  PCHPredefinesBlocks PCHPredefinesBuffers;
640
641  /// \brief Suggested contents of the predefines buffer, after this
642  /// PCH file has been processed.
643  ///
644  /// In most cases, this string will be empty, because the predefines
645  /// buffer computed to build the PCH file will be identical to the
646  /// predefines buffer computed from the command line. However, when
647  /// there are differences that the PCH reader can work around, this
648  /// predefines buffer may contain additional definitions.
649  std::string SuggestedPredefines;
650
651  /// \brief Reads a statement from the specified cursor.
652  Stmt *ReadStmtFromStream(Module &F);
653
654  /// \brief Get a FileEntry out of stored-in-PCH filename, making sure we take
655  /// into account all the necessary relocations.
656  const FileEntry *getFileEntry(StringRef filename);
657
658  void MaybeAddSystemRootToFilename(std::string &Filename);
659
660  ASTReadResult ReadASTCore(StringRef FileName, ModuleKind Type,
661                            Module *ImportedBy);
662  ASTReadResult ReadASTBlock(Module &F);
663  bool CheckPredefinesBuffers();
664  bool ParseLineTable(Module &F, SmallVectorImpl<uint64_t> &Record);
665  ASTReadResult ReadSourceManagerBlock(Module &F);
666  ASTReadResult ReadSLocEntryRecord(int ID);
667  llvm::BitstreamCursor &SLocCursorForID(int ID);
668  SourceLocation getImportLocation(Module *F);
669  bool ParseLanguageOptions(const SmallVectorImpl<uint64_t> &Record);
670
671  struct RecordLocation {
672    RecordLocation(Module *M, uint64_t O)
673      : F(M), Offset(O) {}
674    Module *F;
675    uint64_t Offset;
676  };
677
678  QualType readTypeRecord(unsigned Index);
679  RecordLocation TypeCursorForIndex(unsigned Index);
680  void LoadedDecl(unsigned Index, Decl *D);
681  Decl *ReadDeclRecord(serialization::DeclID ID);
682  RecordLocation DeclCursorForID(serialization::DeclID ID);
683  void loadDeclUpdateRecords(serialization::DeclID ID, Decl *D);
684
685  RecordLocation getLocalBitOffset(uint64_t GlobalOffset);
686  uint64_t getGlobalBitOffset(Module &M, uint32_t LocalOffset);
687
688  void PassInterestingDeclsToConsumer();
689
690  /// \brief Produce an error diagnostic and return true.
691  ///
692  /// This routine should only be used for fatal errors that have to
693  /// do with non-routine failures (e.g., corrupted AST file).
694  void Error(StringRef Msg);
695  void Error(unsigned DiagID, StringRef Arg1 = StringRef(),
696             StringRef Arg2 = StringRef());
697
698  ASTReader(const ASTReader&); // do not implement
699  ASTReader &operator=(const ASTReader &); // do not implement
700public:
701  typedef SmallVector<uint64_t, 64> RecordData;
702
703  /// \brief Load the AST file and validate its contents against the given
704  /// Preprocessor.
705  ///
706  /// \param PP the preprocessor associated with the context in which this
707  /// precompiled header will be loaded.
708  ///
709  /// \param Context the AST context that this precompiled header will be
710  /// loaded into.
711  ///
712  /// \param isysroot If non-NULL, the system include path specified by the
713  /// user. This is only used with relocatable PCH files. If non-NULL,
714  /// a relocatable PCH file will use the default path "/".
715  ///
716  /// \param DisableValidation If true, the AST reader will suppress most
717  /// of its regular consistency checking, allowing the use of precompiled
718  /// headers that cannot be determined to be compatible.
719  ///
720  /// \param DisableStatCache If true, the AST reader will ignore the
721  /// stat cache in the AST files. This performance pessimization can
722  /// help when an AST file is being used in cases where the
723  /// underlying files in the file system may have changed, but
724  /// parsing should still continue.
725  ASTReader(Preprocessor &PP, ASTContext *Context, StringRef isysroot = "",
726            bool DisableValidation = false, bool DisableStatCache = false);
727
728  /// \brief Load the AST file without using any pre-initialized Preprocessor.
729  ///
730  /// The necessary information to initialize a Preprocessor later can be
731  /// obtained by setting a ASTReaderListener.
732  ///
733  /// \param SourceMgr the source manager into which the AST file will be loaded
734  ///
735  /// \param FileMgr the file manager into which the AST file will be loaded.
736  ///
737  /// \param Diags the diagnostics system to use for reporting errors and
738  /// warnings relevant to loading the AST file.
739  ///
740  /// \param isysroot If non-NULL, the system include path specified by the
741  /// user. This is only used with relocatable PCH files. If non-NULL,
742  /// a relocatable PCH file will use the default path "/".
743  ///
744  /// \param DisableValidation If true, the AST reader will suppress most
745  /// of its regular consistency checking, allowing the use of precompiled
746  /// headers that cannot be determined to be compatible.
747  ///
748  /// \param DisableStatCache If true, the AST reader will ignore the
749  /// stat cache in the AST files. This performance pessimization can
750  /// help when an AST file is being used in cases where the
751  /// underlying files in the file system may have changed, but
752  /// parsing should still continue.
753  ASTReader(SourceManager &SourceMgr, FileManager &FileMgr,
754            Diagnostic &Diags, StringRef isysroot = "",
755            bool DisableValidation = false, bool DisableStatCache = false);
756  ~ASTReader();
757
758  /// \brief Load the AST file designated by the given file name.
759  ASTReadResult ReadAST(const std::string &FileName, ModuleKind Type);
760
761  /// \brief Checks that no file that is stored in PCH is out-of-sync with
762  /// the actual file in the file system.
763  ASTReadResult validateFileEntries(Module &M);
764
765  /// \brief Set the AST callbacks listener.
766  void setListener(ASTReaderListener *listener) {
767    Listener.reset(listener);
768  }
769
770  /// \brief Set the AST deserialization listener.
771  void setDeserializationListener(ASTDeserializationListener *Listener);
772
773  /// \brief Set the Preprocessor to use.
774  void setPreprocessor(Preprocessor &pp);
775
776  /// \brief Sets and initializes the given Context.
777  void InitializeContext(ASTContext &Context);
778
779  /// \brief Add in-memory (virtual file) buffer.
780  void addInMemoryBuffer(StringRef &FileName, llvm::MemoryBuffer *Buffer) {
781    ModuleMgr.addInMemoryBuffer(FileName, Buffer);
782  }
783
784  /// \brief Retrieve the module manager.
785  ModuleManager &getModuleManager() { return ModuleMgr; }
786
787  /// \brief Retrieve the preprocessor.
788  Preprocessor &getPreprocessor() const {
789    assert(PP && "ASTReader does not have a preprocessor");
790    return *PP;
791  }
792
793  /// \brief Retrieve the name of the original source file name
794  const std::string &getOriginalSourceFile() { return OriginalFileName; }
795
796  /// \brief Retrieve the name of the original source file name directly from
797  /// the AST file, without actually loading the AST file.
798  static std::string getOriginalSourceFile(const std::string &ASTFileName,
799                                           FileManager &FileMgr,
800                                           Diagnostic &Diags);
801
802  /// \brief Returns the suggested contents of the predefines buffer,
803  /// which contains a (typically-empty) subset of the predefines
804  /// build prior to including the precompiled header.
805  const std::string &getSuggestedPredefines() { return SuggestedPredefines; }
806
807  /// \brief Read preprocessed entities into the preprocessing record.
808  virtual void ReadPreprocessedEntities();
809
810  /// \brief Read the preprocessed entity at the given offset.
811  virtual PreprocessedEntity *ReadPreprocessedEntityAtOffset(uint64_t Offset);
812
813  /// \brief Read the header file information for the given file entry.
814  virtual HeaderFileInfo GetHeaderFileInfo(const FileEntry *FE);
815
816  void ReadPragmaDiagnosticMappings(Diagnostic &Diag);
817
818  /// \brief Returns the number of source locations found in the chain.
819  unsigned getTotalNumSLocs() const {
820    return TotalNumSLocEntries;
821  }
822
823  /// \brief Returns the number of identifiers found in the chain.
824  unsigned getTotalNumIdentifiers() const {
825    return static_cast<unsigned>(IdentifiersLoaded.size());
826  }
827
828  /// \brief Returns the number of types found in the chain.
829  unsigned getTotalNumTypes() const {
830    return static_cast<unsigned>(TypesLoaded.size());
831  }
832
833  /// \brief Returns the number of declarations found in the chain.
834  unsigned getTotalNumDecls() const {
835    return static_cast<unsigned>(DeclsLoaded.size());
836  }
837
838  /// \brief Returns the number of selectors found in the chain.
839  unsigned getTotalNumSelectors() const {
840    return static_cast<unsigned>(SelectorsLoaded.size());
841  }
842
843  /// \brief Returns the number of preprocessed entities known to the AST
844  /// reader.
845  unsigned getTotalNumPreprocessedEntities() const {
846    unsigned Result = 0;
847    for (ModuleConstIterator I = ModuleMgr.begin(),
848        E = ModuleMgr.end(); I != E; ++I) {
849      Result += (*I)->NumPreallocatedPreprocessingEntities;
850    }
851
852    return Result;
853  }
854
855  /// \brief Returns the number of macro definitions found in the chain.
856  unsigned getTotalNumMacroDefinitions() const {
857    return static_cast<unsigned>(MacroDefinitionsLoaded.size());
858  }
859
860  /// \brief Returns the number of C++ base specifiers found in the chain.
861  unsigned getTotalNumCXXBaseSpecifiers() const {
862    return NumCXXBaseSpecifiersLoaded;
863  }
864
865  /// \brief Reads a TemplateArgumentLocInfo appropriate for the
866  /// given TemplateArgument kind.
867  TemplateArgumentLocInfo
868  GetTemplateArgumentLocInfo(Module &F, TemplateArgument::ArgKind Kind,
869                             const RecordData &Record, unsigned &Idx);
870
871  /// \brief Reads a TemplateArgumentLoc.
872  TemplateArgumentLoc
873  ReadTemplateArgumentLoc(Module &F,
874                          const RecordData &Record, unsigned &Idx);
875
876  /// \brief Reads a declarator info from the given record.
877  TypeSourceInfo *GetTypeSourceInfo(Module &F,
878                                    const RecordData &Record, unsigned &Idx);
879
880  /// \brief Resolve a type ID into a type, potentially building a new
881  /// type.
882  QualType GetType(serialization::TypeID ID);
883
884  /// \brief Resolve a local type ID within a given AST file into a type.
885  QualType getLocalType(Module &F, unsigned LocalID);
886
887  /// \brief Map a local type ID within a given AST file into a global type ID.
888  serialization::TypeID getGlobalTypeID(Module &F, unsigned LocalID) const;
889
890  /// \brief Read a type from the current position in the given record, which
891  /// was read from the given AST file.
892  QualType readType(Module &F, const RecordData &Record, unsigned &Idx) {
893    if (Idx >= Record.size())
894      return QualType();
895
896    return getLocalType(F, Record[Idx++]);
897  }
898
899  /// \brief Map from a local declaration ID within a given module to a
900  /// global declaration ID.
901  serialization::DeclID getGlobalDeclID(Module &F, unsigned LocalID) const;
902
903  /// \brief Resolve a declaration ID into a declaration, potentially
904  /// building a new declaration.
905  Decl *GetDecl(serialization::DeclID ID);
906  virtual Decl *GetExternalDecl(uint32_t ID);
907
908  /// \brief Reads a declaration with the given local ID in the given module.
909  Decl *GetLocalDecl(Module &F, uint32_t LocalID) {
910    return GetDecl(getGlobalDeclID(F, LocalID));
911  }
912
913  /// \brief Reads a declaration with the given local ID in the given module.
914  ///
915  /// \returns The requested declaration, casted to the given return type.
916  template<typename T>
917  T *GetLocalDeclAs(Module &F, uint32_t LocalID) {
918    return cast_or_null<T>(GetLocalDecl(F, LocalID));
919  }
920
921  /// \brief Reads a declaration ID from the given position in a record in the
922  /// given module.
923  ///
924  /// \returns The declaration ID read from the record, adjusted to a global ID.
925  serialization::DeclID ReadDeclID(Module &F, const RecordData &Record,
926                                   unsigned &Idx);
927
928  /// \brief Reads a declaration from the given position in a record in the
929  /// given module.
930  Decl *ReadDecl(Module &F, const RecordData &R, unsigned &I) {
931    return GetDecl(ReadDeclID(F, R, I));
932  }
933
934  /// \brief Reads a declaration from the given position in a record in the
935  /// given module.
936  ///
937  /// \returns The declaration read from this location, casted to the given
938  /// result type.
939  template<typename T>
940  T *ReadDeclAs(Module &F, const RecordData &R, unsigned &I) {
941    return cast_or_null<T>(GetDecl(ReadDeclID(F, R, I)));
942  }
943
944  /// \brief Read a CXXBaseSpecifiers ID form the given record and
945  /// return its global bit offset.
946  uint64_t readCXXBaseSpecifiers(Module &M, const RecordData &Record,
947                                 unsigned &Idx);
948
949  virtual CXXBaseSpecifier *GetExternalCXXBaseSpecifiers(uint64_t Offset);
950
951  /// \brief Resolve the offset of a statement into a statement.
952  ///
953  /// This operation will read a new statement from the external
954  /// source each time it is called, and is meant to be used via a
955  /// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
956  virtual Stmt *GetExternalDeclStmt(uint64_t Offset);
957
958  /// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
959  /// specified cursor.  Read the abbreviations that are at the top of the block
960  /// and then leave the cursor pointing into the block.
961  bool ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor, unsigned BlockID);
962
963  /// \brief Finds all the visible declarations with a given name.
964  /// The current implementation of this method just loads the entire
965  /// lookup table as unmaterialized references.
966  virtual DeclContext::lookup_result
967  FindExternalVisibleDeclsByName(const DeclContext *DC,
968                                 DeclarationName Name);
969
970  /// \brief Read all of the declarations lexically stored in a
971  /// declaration context.
972  ///
973  /// \param DC The declaration context whose declarations will be
974  /// read.
975  ///
976  /// \param Decls Vector that will contain the declarations loaded
977  /// from the external source. The caller is responsible for merging
978  /// these declarations with any declarations already stored in the
979  /// declaration context.
980  ///
981  /// \returns true if there was an error while reading the
982  /// declarations for this declaration context.
983  virtual ExternalLoadResult FindExternalLexicalDecls(const DeclContext *DC,
984                                        bool (*isKindWeWant)(Decl::Kind),
985                                        SmallVectorImpl<Decl*> &Decls);
986
987  /// \brief Notify ASTReader that we started deserialization of
988  /// a decl or type so until FinishedDeserializing is called there may be
989  /// decls that are initializing. Must be paired with FinishedDeserializing.
990  virtual void StartedDeserializing() { ++NumCurrentElementsDeserializing; }
991
992  /// \brief Notify ASTReader that we finished the deserialization of
993  /// a decl or type. Must be paired with StartedDeserializing.
994  virtual void FinishedDeserializing();
995
996  /// \brief Function that will be invoked when we begin parsing a new
997  /// translation unit involving this external AST source.
998  ///
999  /// This function will provide all of the external definitions to
1000  /// the ASTConsumer.
1001  virtual void StartTranslationUnit(ASTConsumer *Consumer);
1002
1003  /// \brief Print some statistics about AST usage.
1004  virtual void PrintStats();
1005
1006  /// \brief Dump information about the AST reader to standard error.
1007  void dump();
1008
1009  /// Return the amount of memory used by memory buffers, breaking down
1010  /// by heap-backed versus mmap'ed memory.
1011  virtual void getMemoryBufferSizes(MemoryBufferSizes &sizes) const;
1012
1013  /// \brief Initialize the semantic source with the Sema instance
1014  /// being used to perform semantic analysis on the abstract syntax
1015  /// tree.
1016  virtual void InitializeSema(Sema &S);
1017
1018  /// \brief Inform the semantic consumer that Sema is no longer available.
1019  virtual void ForgetSema() { SemaObj = 0; }
1020
1021  /// \brief Retrieve the IdentifierInfo for the named identifier.
1022  ///
1023  /// This routine builds a new IdentifierInfo for the given identifier. If any
1024  /// declarations with this name are visible from translation unit scope, their
1025  /// declarations will be deserialized and introduced into the declaration
1026  /// chain of the identifier.
1027  virtual IdentifierInfo *get(const char *NameStart, const char *NameEnd);
1028  IdentifierInfo *get(StringRef Name) {
1029    return get(Name.begin(), Name.end());
1030  }
1031
1032  /// \brief Retrieve an iterator into the set of all identifiers
1033  /// in all loaded AST files.
1034  virtual IdentifierIterator *getIdentifiers() const;
1035
1036  /// \brief Load the contents of the global method pool for a given
1037  /// selector.
1038  ///
1039  /// \returns a pair of Objective-C methods lists containing the
1040  /// instance and factory methods, respectively, with this selector.
1041  virtual std::pair<ObjCMethodList, ObjCMethodList>
1042    ReadMethodPool(Selector Sel);
1043
1044  /// \brief Load the set of namespaces that are known to the external source,
1045  /// which will be used during typo correction.
1046  virtual void ReadKnownNamespaces(
1047                           SmallVectorImpl<NamespaceDecl *> &Namespaces);
1048
1049  virtual void ReadTentativeDefinitions(
1050                 SmallVectorImpl<VarDecl *> &TentativeDefs);
1051
1052  virtual void ReadUnusedFileScopedDecls(
1053                 SmallVectorImpl<const DeclaratorDecl *> &Decls);
1054
1055  virtual void ReadDelegatingConstructors(
1056                 SmallVectorImpl<CXXConstructorDecl *> &Decls);
1057
1058  virtual void ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls);
1059
1060  virtual void ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls);
1061
1062  virtual void ReadLocallyScopedExternalDecls(
1063                 SmallVectorImpl<NamedDecl *> &Decls);
1064
1065  virtual void ReadReferencedSelectors(
1066                 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels);
1067
1068  virtual void ReadWeakUndeclaredIdentifiers(
1069                 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WI);
1070
1071  virtual void ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables);
1072
1073  virtual void ReadPendingInstantiations(
1074                 SmallVectorImpl<std::pair<ValueDecl *,
1075                                           SourceLocation> > &Pending);
1076
1077  /// \brief Load a selector from disk, registering its ID if it exists.
1078  void LoadSelector(Selector Sel);
1079
1080  void SetIdentifierInfo(unsigned ID, IdentifierInfo *II);
1081  void SetGloballyVisibleDecls(IdentifierInfo *II,
1082                               const SmallVectorImpl<uint32_t> &DeclIDs,
1083                               bool Nonrecursive = false);
1084
1085  /// \brief Report a diagnostic.
1086  DiagnosticBuilder Diag(unsigned DiagID);
1087
1088  /// \brief Report a diagnostic.
1089  DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
1090
1091  IdentifierInfo *DecodeIdentifierInfo(serialization::IdentifierID ID);
1092
1093  IdentifierInfo *GetIdentifierInfo(Module &M, const RecordData &Record,
1094                                    unsigned &Idx) {
1095    return DecodeIdentifierInfo(getGlobalIdentifierID(M, Record[Idx++]));
1096  }
1097
1098  virtual IdentifierInfo *GetIdentifier(serialization::IdentifierID ID) {
1099    return DecodeIdentifierInfo(ID);
1100  }
1101
1102  IdentifierInfo *getLocalIdentifier(Module &M, unsigned LocalID);
1103
1104  serialization::IdentifierID getGlobalIdentifierID(Module &M,
1105                                                    unsigned LocalID);
1106
1107  /// \brief Read the source location entry with index ID.
1108  virtual bool ReadSLocEntry(int ID);
1109
1110  /// \brief Retrieve a selector from the given module with its local ID
1111  /// number.
1112  Selector getLocalSelector(Module &M, unsigned LocalID);
1113
1114  Selector DecodeSelector(serialization::SelectorID Idx);
1115
1116  virtual Selector GetExternalSelector(serialization::SelectorID ID);
1117  uint32_t GetNumExternalSelectors();
1118
1119  Selector ReadSelector(Module &M, const RecordData &Record, unsigned &Idx) {
1120    return getLocalSelector(M, Record[Idx++]);
1121  }
1122
1123  /// \brief Retrieve the global selector ID that corresponds to this
1124  /// the local selector ID in a given module.
1125  serialization::SelectorID getGlobalSelectorID(Module &F,
1126                                                unsigned LocalID) const;
1127
1128  /// \brief Read a declaration name.
1129  DeclarationName ReadDeclarationName(Module &F,
1130                                      const RecordData &Record, unsigned &Idx);
1131  void ReadDeclarationNameLoc(Module &F,
1132                              DeclarationNameLoc &DNLoc, DeclarationName Name,
1133                              const RecordData &Record, unsigned &Idx);
1134  void ReadDeclarationNameInfo(Module &F, DeclarationNameInfo &NameInfo,
1135                               const RecordData &Record, unsigned &Idx);
1136
1137  void ReadQualifierInfo(Module &F, QualifierInfo &Info,
1138                         const RecordData &Record, unsigned &Idx);
1139
1140  NestedNameSpecifier *ReadNestedNameSpecifier(Module &F,
1141                                               const RecordData &Record,
1142                                               unsigned &Idx);
1143
1144  NestedNameSpecifierLoc ReadNestedNameSpecifierLoc(Module &F,
1145                                                    const RecordData &Record,
1146                                                    unsigned &Idx);
1147
1148  /// \brief Read a template name.
1149  TemplateName ReadTemplateName(Module &F, const RecordData &Record,
1150                                unsigned &Idx);
1151
1152  /// \brief Read a template argument.
1153  TemplateArgument ReadTemplateArgument(Module &F,
1154                                        const RecordData &Record,unsigned &Idx);
1155
1156  /// \brief Read a template parameter list.
1157  TemplateParameterList *ReadTemplateParameterList(Module &F,
1158                                                   const RecordData &Record,
1159                                                   unsigned &Idx);
1160
1161  /// \brief Read a template argument array.
1162  void
1163  ReadTemplateArgumentList(SmallVector<TemplateArgument, 8> &TemplArgs,
1164                           Module &F, const RecordData &Record,
1165                           unsigned &Idx);
1166
1167  /// \brief Read a UnresolvedSet structure.
1168  void ReadUnresolvedSet(Module &F, UnresolvedSetImpl &Set,
1169                         const RecordData &Record, unsigned &Idx);
1170
1171  /// \brief Read a C++ base specifier.
1172  CXXBaseSpecifier ReadCXXBaseSpecifier(Module &F,
1173                                        const RecordData &Record,unsigned &Idx);
1174
1175  /// \brief Read a CXXCtorInitializer array.
1176  std::pair<CXXCtorInitializer **, unsigned>
1177  ReadCXXCtorInitializers(Module &F, const RecordData &Record,
1178                          unsigned &Idx);
1179
1180  /// \brief Read a source location from raw form.
1181  SourceLocation ReadSourceLocation(Module &Module, unsigned Raw) {
1182    unsigned Flag = Raw & (1U << 31);
1183    unsigned Offset = Raw & ~(1U << 31);
1184    assert(Module.SLocRemap.find(Offset) != Module.SLocRemap.end() &&
1185           "Cannot find offset to remap.");
1186    int Remap = Module.SLocRemap.find(Offset)->second;
1187    Offset += Remap;
1188    assert((Offset & (1U << 31)) == 0 &&
1189           "Bad offset in reading source location");
1190    return SourceLocation::getFromRawEncoding(Offset | Flag);
1191  }
1192
1193  /// \brief Read a source location.
1194  SourceLocation ReadSourceLocation(Module &Module,
1195                                    const RecordData &Record, unsigned& Idx) {
1196    return ReadSourceLocation(Module, Record[Idx++]);
1197  }
1198
1199  /// \brief Read a source range.
1200  SourceRange ReadSourceRange(Module &F,
1201                              const RecordData &Record, unsigned& Idx);
1202
1203  /// \brief Read an integral value
1204  llvm::APInt ReadAPInt(const RecordData &Record, unsigned &Idx);
1205
1206  /// \brief Read a signed integral value
1207  llvm::APSInt ReadAPSInt(const RecordData &Record, unsigned &Idx);
1208
1209  /// \brief Read a floating-point value
1210  llvm::APFloat ReadAPFloat(const RecordData &Record, unsigned &Idx);
1211
1212  // \brief Read a string
1213  std::string ReadString(const RecordData &Record, unsigned &Idx);
1214
1215  /// \brief Read a version tuple.
1216  VersionTuple ReadVersionTuple(const RecordData &Record, unsigned &Idx);
1217
1218  CXXTemporary *ReadCXXTemporary(Module &F, const RecordData &Record,
1219                                 unsigned &Idx);
1220
1221  /// \brief Reads attributes from the current stream position.
1222  void ReadAttributes(Module &F, AttrVec &Attrs,
1223                      const RecordData &Record, unsigned &Idx);
1224
1225  /// \brief Reads a statement.
1226  Stmt *ReadStmt(Module &F);
1227
1228  /// \brief Reads an expression.
1229  Expr *ReadExpr(Module &F);
1230
1231  /// \brief Reads a sub-statement operand during statement reading.
1232  Stmt *ReadSubStmt() {
1233    assert(ReadingKind == Read_Stmt &&
1234           "Should be called only during statement reading!");
1235    // Subexpressions are stored from last to first, so the next Stmt we need
1236    // is at the back of the stack.
1237    assert(!StmtStack.empty() && "Read too many sub statements!");
1238    return StmtStack.pop_back_val();
1239  }
1240
1241  /// \brief Reads a sub-expression operand during statement reading.
1242  Expr *ReadSubExpr();
1243
1244  /// \brief Reads the macro record located at the given offset.
1245  void ReadMacroRecord(Module &F, uint64_t Offset);
1246
1247  /// \brief Reads the preprocessed entity located at the current stream
1248  /// position.
1249  PreprocessedEntity *LoadPreprocessedEntity(Module &F);
1250
1251  /// \brief Determine the global preprocessed entity ID that corresponds to
1252  /// the given local ID within the given module.
1253  serialization::PreprocessedEntityID
1254  getGlobalPreprocessedEntityID(Module &M, unsigned LocalID);
1255
1256  /// \brief Note that the identifier is a macro whose record will be loaded
1257  /// from the given AST file at the given (file-local) offset.
1258  void SetIdentifierIsMacro(IdentifierInfo *II, Module &F,
1259                            uint64_t Offset);
1260
1261  /// \brief Read the set of macros defined by this external macro source.
1262  virtual void ReadDefinedMacros();
1263
1264  /// \brief Read the macro definition for this identifier.
1265  virtual void LoadMacroDefinition(IdentifierInfo *II);
1266
1267  /// \brief Read the macro definition corresponding to this iterator
1268  /// into the unread macro record offsets table.
1269  void LoadMacroDefinition(
1270                     llvm::DenseMap<IdentifierInfo *, uint64_t>::iterator Pos);
1271
1272  /// \brief Retrieve the macro definition with the given ID.
1273  MacroDefinition *getMacroDefinition(serialization::MacroID ID);
1274
1275  /// \brief Retrieve the global macro definition ID that corresponds to the
1276  /// local macro definition ID within a given module.
1277  serialization::MacroID getGlobalMacroDefinitionID(Module &M,
1278                                                    unsigned LocalID);
1279
1280  /// \brief Deserialize a macro definition that is local to the given
1281  /// module.
1282  MacroDefinition *getLocalMacroDefinition(Module &M, unsigned LocalID) {
1283    return getMacroDefinition(getGlobalMacroDefinitionID(M, LocalID));
1284  }
1285
1286  /// \brief Retrieve the AST context that this AST reader supplements.
1287  ASTContext *getContext() { return Context; }
1288
1289  // \brief Contains declarations that were loaded before we have
1290  // access to a Sema object.
1291  SmallVector<NamedDecl *, 16> PreloadedDecls;
1292
1293  /// \brief Retrieve the semantic analysis object used to analyze the
1294  /// translation unit in which the precompiled header is being
1295  /// imported.
1296  Sema *getSema() { return SemaObj; }
1297
1298  /// \brief Retrieve the identifier table associated with the
1299  /// preprocessor.
1300  IdentifierTable &getIdentifierTable();
1301
1302  /// \brief Record that the given ID maps to the given switch-case
1303  /// statement.
1304  void RecordSwitchCaseID(SwitchCase *SC, unsigned ID);
1305
1306  /// \brief Retrieve the switch-case statement with the given ID.
1307  SwitchCase *getSwitchCaseWithID(unsigned ID);
1308
1309  void ClearSwitchCaseIDs();
1310};
1311
1312/// \brief Helper class that saves the current stream position and
1313/// then restores it when destroyed.
1314struct SavedStreamPosition {
1315  explicit SavedStreamPosition(llvm::BitstreamCursor &Cursor)
1316  : Cursor(Cursor), Offset(Cursor.GetCurrentBitNo()) { }
1317
1318  ~SavedStreamPosition() {
1319    Cursor.JumpToBit(Offset);
1320  }
1321
1322private:
1323  llvm::BitstreamCursor &Cursor;
1324  uint64_t Offset;
1325};
1326
1327inline void PCHValidator::Error(const char *Msg) {
1328  Reader.Error(Msg);
1329}
1330
1331} // end namespace clang
1332
1333#endif
1334