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