ASTReader.h revision 6f42b62b6194f53bcbc349f5d17388e1936535d7
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  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 Read the records that describe the contents of declcontexts.
339  bool ReadDeclContextStorage(ModuleFile &M,
340                              llvm::BitstreamCursor &Cursor,
341                              const std::pair<uint64_t, uint64_t> &Offsets,
342                              serialization::DeclContextInfo &Info);
343
344  /// \brief A vector containing identifiers that have already been
345  /// loaded.
346  ///
347  /// If the pointer at index I is non-NULL, then it refers to the
348  /// IdentifierInfo for the identifier with ID=I+1 that has already
349  /// been loaded.
350  std::vector<IdentifierInfo *> IdentifiersLoaded;
351
352  typedef ContinuousRangeMap<serialization::IdentID, ModuleFile *, 4>
353    GlobalIdentifierMapType;
354
355  /// \brief Mapping from global identifer IDs to the module in which the
356  /// identifier resides along with the offset that should be added to the
357  /// global identifier ID to produce a local ID.
358  GlobalIdentifierMapType GlobalIdentifierMap;
359
360  /// \brief A vector containing submodules that have already been loaded.
361  ///
362  /// This vector is indexed by the Submodule ID (-1). NULL submodule entries
363  /// indicate that the particular submodule ID has not yet been loaded.
364  SmallVector<Module *, 2> SubmodulesLoaded;
365
366  typedef ContinuousRangeMap<serialization::SubmoduleID, ModuleFile *, 4>
367    GlobalSubmoduleMapType;
368
369  /// \brief Mapping from global submodule IDs to the module file in which the
370  /// submodule resides along with the offset that should be added to the
371  /// global submodule ID to produce a local ID.
372  GlobalSubmoduleMapType GlobalSubmoduleMap;
373
374  /// \brief A set of hidden declarations.
375  typedef llvm::SmallVector<llvm::PointerUnion<Decl *, IdentifierInfo *>, 2>
376    HiddenNames;
377
378  typedef llvm::DenseMap<Module *, HiddenNames> HiddenNamesMapType;
379
380  /// \brief A mapping from each of the hidden submodules to the deserialized
381  /// declarations in that submodule that could be made visible.
382  HiddenNamesMapType HiddenNamesMap;
383
384
385  /// \brief A module import or export that hasn't yet been resolved.
386  struct UnresolvedModuleImportExport {
387    /// \brief The file in which this module resides.
388    ModuleFile *File;
389
390    /// \brief The module that is importing or exporting.
391    Module *Mod;
392
393    /// \brief The local ID of the module that is being exported.
394    unsigned ID;
395
396    /// \brief Whether this is an import (vs. an export).
397    unsigned IsImport : 1;
398
399    /// \brief Whether this is a wildcard export.
400    unsigned IsWildcard : 1;
401  };
402
403  /// \brief The set of module imports and exports that still need to be
404  /// resolved.
405  llvm::SmallVector<UnresolvedModuleImportExport, 2>
406    UnresolvedModuleImportExports;
407
408  /// \brief A vector containing selectors that have already been loaded.
409  ///
410  /// This vector is indexed by the Selector ID (-1). NULL selector
411  /// entries indicate that the particular selector ID has not yet
412  /// been loaded.
413  SmallVector<Selector, 16> SelectorsLoaded;
414
415  typedef ContinuousRangeMap<serialization::SelectorID, ModuleFile *, 4>
416    GlobalSelectorMapType;
417
418  /// \brief Mapping from global selector IDs to the module in which the
419  /// selector resides along with the offset that should be added to the
420  /// global selector ID to produce a local ID.
421  GlobalSelectorMapType GlobalSelectorMap;
422
423  /// \brief The generation number of the last time we loaded data from the
424  /// global method pool for this selector.
425  llvm::DenseMap<Selector, unsigned> SelectorGeneration;
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 each identifier, which keeps track of
660  /// the last time we loaded information about this identifier.
661  llvm::DenseMap<IdentifierInfo *, unsigned> IdentifierGeneration;
662
663  /// \brief Contains declarations and definitions that will be
664  /// "interesting" to the ASTConsumer, when we get that AST consumer.
665  ///
666  /// "Interesting" declarations are those that have data that may
667  /// need to be emitted, such as inline function definitions or
668  /// Objective-C protocols.
669  std::deque<Decl *> InterestingDecls;
670
671  /// \brief The set of redeclarable declaraations that have been deserialized
672  /// since the last time the declaration chains were linked.
673  llvm::SmallPtrSet<Decl *, 16> RedeclsDeserialized;
674
675  /// \brief The list of redeclaration chains that still need to be
676  /// reconstructed.
677  ///
678  /// Each element is the global declaration ID of the first declaration in
679  /// the chain. Elements in this vector should be unique; use
680  /// PendingDeclChainsKnown to ensure uniqueness.
681  llvm::SmallVector<serialization::DeclID, 16> PendingDeclChains;
682
683  /// \brief Keeps track of the elements added to PendingDeclChains.
684  llvm::SmallSet<serialization::DeclID, 16> PendingDeclChainsKnown;
685
686  /// \brief The set of Objective-C categories that have been deserialized
687  /// since the last time the declaration chains were linked.
688  llvm::SmallPtrSet<ObjCCategoryDecl *, 16> CategoriesDeserialized;
689
690  /// \brief The set of Objective-C class definitions that have already been
691  /// loaded, for which we will need to check for categories whenever a new
692  /// module is loaded.
693  llvm::SmallVector<ObjCInterfaceDecl *, 16> ObjCClassesLoaded;
694
695  typedef llvm::DenseMap<Decl *, llvm::SmallVector<serialization::DeclID, 2> >
696    MergedDeclsMap;
697
698  /// \brief A mapping from canonical declarations to the set of additional
699  /// (global, previously-canonical) declaration IDs that have been merged with
700  /// that canonical declaration.
701  MergedDeclsMap MergedDecls;
702
703  typedef llvm::DenseMap<serialization::GlobalDeclID,
704                         llvm::SmallVector<serialization::DeclID, 2> >
705    StoredMergedDeclsMap;
706
707  /// \brief A mapping from canonical declaration IDs to the set of additional
708  /// declaration IDs that have been merged with that canonical declaration.
709  ///
710  /// This is the deserialized representation of the entries in MergedDecls.
711  /// When we query entries in MergedDecls, they will be augmented with entries
712  /// from StoredMergedDecls.
713  StoredMergedDeclsMap StoredMergedDecls;
714
715  /// \brief Combine the stored merged declarations for the given canonical
716  /// declaration into the set of merged declarations.
717  ///
718  /// \returns An iterator into MergedDecls that corresponds to the position of
719  /// the given canonical declaration.
720  MergedDeclsMap::iterator
721  combineStoredMergedDecls(Decl *Canon, serialization::GlobalDeclID CanonID);
722
723  /// \brief Ready to load the previous declaration of the given Decl.
724  void loadAndAttachPreviousDecl(Decl *D, serialization::DeclID ID);
725
726  /// \brief When reading a Stmt tree, Stmt operands are placed in this stack.
727  SmallVector<Stmt *, 16> StmtStack;
728
729  /// \brief What kind of records we are reading.
730  enum ReadingKind {
731    Read_Decl, Read_Type, Read_Stmt
732  };
733
734  /// \brief What kind of records we are reading.
735  ReadingKind ReadingKind;
736
737  /// \brief RAII object to change the reading kind.
738  class ReadingKindTracker {
739    ASTReader &Reader;
740    enum ReadingKind PrevKind;
741
742    ReadingKindTracker(const ReadingKindTracker&); // do not implement
743    ReadingKindTracker &operator=(const ReadingKindTracker&);// do not implement
744
745  public:
746    ReadingKindTracker(enum ReadingKind newKind, ASTReader &reader)
747      : Reader(reader), PrevKind(Reader.ReadingKind) {
748      Reader.ReadingKind = newKind;
749    }
750
751    ~ReadingKindTracker() { Reader.ReadingKind = PrevKind; }
752  };
753
754  /// \brief All predefines buffers in the chain, to be treated as if
755  /// concatenated.
756  PCHPredefinesBlocks PCHPredefinesBuffers;
757
758  /// \brief Suggested contents of the predefines buffer, after this
759  /// PCH file has been processed.
760  ///
761  /// In most cases, this string will be empty, because the predefines
762  /// buffer computed to build the PCH file will be identical to the
763  /// predefines buffer computed from the command line. However, when
764  /// there are differences that the PCH reader can work around, this
765  /// predefines buffer may contain additional definitions.
766  std::string SuggestedPredefines;
767
768  /// \brief Reads a statement from the specified cursor.
769  Stmt *ReadStmtFromStream(ModuleFile &F);
770
771  /// \brief Get a FileEntry out of stored-in-PCH filename, making sure we take
772  /// into account all the necessary relocations.
773  const FileEntry *getFileEntry(StringRef filename);
774
775  void MaybeAddSystemRootToFilename(std::string &Filename);
776
777  ASTReadResult ReadASTCore(StringRef FileName, ModuleKind Type,
778                            ModuleFile *ImportedBy);
779  ASTReadResult ReadASTBlock(ModuleFile &F);
780  bool CheckPredefinesBuffers();
781  bool ParseLineTable(ModuleFile &F, SmallVectorImpl<uint64_t> &Record);
782  ASTReadResult ReadSourceManagerBlock(ModuleFile &F);
783  ASTReadResult ReadSLocEntryRecord(int ID);
784  llvm::BitstreamCursor &SLocCursorForID(int ID);
785  SourceLocation getImportLocation(ModuleFile *F);
786  ASTReadResult ReadSubmoduleBlock(ModuleFile &F);
787  bool ParseLanguageOptions(const SmallVectorImpl<uint64_t> &Record);
788
789  struct RecordLocation {
790    RecordLocation(ModuleFile *M, uint64_t O)
791      : F(M), Offset(O) {}
792    ModuleFile *F;
793    uint64_t Offset;
794  };
795
796  QualType readTypeRecord(unsigned Index);
797  RecordLocation TypeCursorForIndex(unsigned Index);
798  void LoadedDecl(unsigned Index, Decl *D);
799  Decl *ReadDeclRecord(serialization::DeclID ID);
800  RecordLocation DeclCursorForID(serialization::DeclID ID,
801                                 unsigned &RawLocation);
802  void loadDeclUpdateRecords(serialization::DeclID ID, Decl *D);
803  void loadPendingDeclChain(serialization::GlobalDeclID ID);
804  void loadObjCCategories(serialization::GlobalDeclID ID, ObjCInterfaceDecl *D,
805                          unsigned PreviousGeneration = 0);
806
807  RecordLocation getLocalBitOffset(uint64_t GlobalOffset);
808  uint64_t getGlobalBitOffset(ModuleFile &M, uint32_t LocalOffset);
809
810  /// \brief Returns the first preprocessed entity ID that ends after \arg BLoc.
811  serialization::PreprocessedEntityID
812    findBeginPreprocessedEntity(SourceLocation BLoc) const;
813
814  /// \brief Returns the first preprocessed entity ID that begins after \arg
815  /// ELoc.
816  serialization::PreprocessedEntityID
817    findEndPreprocessedEntity(SourceLocation ELoc) const;
818
819  /// \brief \arg SLocMapI points at a chunk of a module that contains no
820  /// preprocessed entities or the entities it contains are not the ones we are
821  /// looking for. Find the next module that contains entities and return the ID
822  /// of the first entry.
823  serialization::PreprocessedEntityID
824    findNextPreprocessedEntity(
825                        GlobalSLocOffsetMapType::const_iterator SLocMapI) const;
826
827  /// \brief Returns (ModuleFile, Local index) pair for \arg GlobalIndex of a
828  /// preprocessed entity.
829  std::pair<ModuleFile *, unsigned>
830    getModulePreprocessedEntity(unsigned GlobalIndex);
831
832  void PassInterestingDeclsToConsumer();
833  void PassInterestingDeclToConsumer(Decl *D);
834
835  void finishPendingActions();
836
837  /// \brief Produce an error diagnostic and return true.
838  ///
839  /// This routine should only be used for fatal errors that have to
840  /// do with non-routine failures (e.g., corrupted AST file).
841  void Error(StringRef Msg);
842  void Error(unsigned DiagID, StringRef Arg1 = StringRef(),
843             StringRef Arg2 = StringRef());
844
845  ASTReader(const ASTReader&); // do not implement
846  ASTReader &operator=(const ASTReader &); // do not implement
847public:
848  typedef SmallVector<uint64_t, 64> RecordData;
849
850  /// \brief Load the AST file and validate its contents against the given
851  /// Preprocessor.
852  ///
853  /// \param PP the preprocessor associated with the context in which this
854  /// precompiled header will be loaded.
855  ///
856  /// \param Context the AST context that this precompiled header will be
857  /// loaded into.
858  ///
859  /// \param isysroot If non-NULL, the system include path specified by the
860  /// user. This is only used with relocatable PCH files. If non-NULL,
861  /// a relocatable PCH file will use the default path "/".
862  ///
863  /// \param DisableValidation If true, the AST reader will suppress most
864  /// of its regular consistency checking, allowing the use of precompiled
865  /// headers that cannot be determined to be compatible.
866  ///
867  /// \param DisableStatCache If true, the AST reader will ignore the
868  /// stat cache in the AST files. This performance pessimization can
869  /// help when an AST file is being used in cases where the
870  /// underlying files in the file system may have changed, but
871  /// parsing should still continue.
872  ASTReader(Preprocessor &PP, ASTContext &Context, StringRef isysroot = "",
873            bool DisableValidation = false, bool DisableStatCache = false);
874
875  ~ASTReader();
876
877  SourceManager &getSourceManager() const { return SourceMgr; }
878
879  /// \brief Load the AST file designated by the given file name.
880  ASTReadResult ReadAST(const std::string &FileName, ModuleKind Type);
881
882  /// \brief Checks that no file that is stored in PCH is out-of-sync with
883  /// the actual file in the file system.
884  ASTReadResult validateFileEntries(ModuleFile &M);
885
886  /// \brief Make the entities in the given module and any of its (non-explicit)
887  /// submodules visible to name lookup.
888  ///
889  /// \param Mod The module whose names should be made visible.
890  ///
891  /// \param Visibility The level of visibility to give the names in the module.
892  /// Visibility can only be increased over time.
893  void makeModuleVisible(Module *Mod,
894                         Module::NameVisibilityKind NameVisibility);
895
896  /// \brief Make the names within this set of hidden names visible.
897  void makeNamesVisible(const HiddenNames &Names);
898
899  /// \brief Set the AST callbacks listener.
900  void setListener(ASTReaderListener *listener) {
901    Listener.reset(listener);
902  }
903
904  /// \brief Set the AST deserialization listener.
905  void setDeserializationListener(ASTDeserializationListener *Listener);
906
907  /// \brief Initializes the ASTContext
908  void InitializeContext();
909
910  /// \brief Add in-memory (virtual file) buffer.
911  void addInMemoryBuffer(StringRef &FileName, llvm::MemoryBuffer *Buffer) {
912    ModuleMgr.addInMemoryBuffer(FileName, Buffer);
913  }
914
915  /// \brief Finalizes the AST reader's state before writing an AST file to
916  /// disk.
917  ///
918  /// This operation may undo temporary state in the AST that should not be
919  /// emitted.
920  void finalizeForWriting();
921
922  /// \brief Retrieve the module manager.
923  ModuleManager &getModuleManager() { return ModuleMgr; }
924
925  /// \brief Retrieve the preprocessor.
926  Preprocessor &getPreprocessor() const { return PP; }
927
928  /// \brief Retrieve the name of the original source file name
929  const std::string &getOriginalSourceFile() { return OriginalFileName; }
930
931  /// \brief Retrieve the name of the original source file name directly from
932  /// the AST file, without actually loading the AST file.
933  static std::string getOriginalSourceFile(const std::string &ASTFileName,
934                                           FileManager &FileMgr,
935                                           DiagnosticsEngine &Diags);
936
937  /// \brief Returns the suggested contents of the predefines buffer,
938  /// which contains a (typically-empty) subset of the predefines
939  /// build prior to including the precompiled header.
940  const std::string &getSuggestedPredefines() { return SuggestedPredefines; }
941
942  /// \brief Read a preallocated preprocessed entity from the external source.
943  ///
944  /// \returns null if an error occurred that prevented the preprocessed
945  /// entity from being loaded.
946  virtual PreprocessedEntity *ReadPreprocessedEntity(unsigned Index);
947
948  /// \brief Returns a pair of [Begin, End) indices of preallocated
949  /// preprocessed entities that \arg Range encompasses.
950  virtual std::pair<unsigned, unsigned>
951      findPreprocessedEntitiesInRange(SourceRange Range);
952
953  /// \brief Optionally returns true or false if the preallocated preprocessed
954  /// entity with index \arg Index came from file \arg FID.
955  virtual llvm::Optional<bool> isPreprocessedEntityInFileID(unsigned Index,
956                                                            FileID FID);
957
958  /// \brief Read the header file information for the given file entry.
959  virtual HeaderFileInfo GetHeaderFileInfo(const FileEntry *FE);
960
961  void ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag);
962
963  /// \brief Returns the number of source locations found in the chain.
964  unsigned getTotalNumSLocs() const {
965    return TotalNumSLocEntries;
966  }
967
968  /// \brief Returns the number of identifiers found in the chain.
969  unsigned getTotalNumIdentifiers() const {
970    return static_cast<unsigned>(IdentifiersLoaded.size());
971  }
972
973  /// \brief Returns the number of types found in the chain.
974  unsigned getTotalNumTypes() const {
975    return static_cast<unsigned>(TypesLoaded.size());
976  }
977
978  /// \brief Returns the number of declarations found in the chain.
979  unsigned getTotalNumDecls() const {
980    return static_cast<unsigned>(DeclsLoaded.size());
981  }
982
983  /// \brief Returns the number of submodules known.
984  unsigned getTotalNumSubmodules() const {
985    return static_cast<unsigned>(SubmodulesLoaded.size());
986  }
987
988  /// \brief Returns the number of selectors found in the chain.
989  unsigned getTotalNumSelectors() const {
990    return static_cast<unsigned>(SelectorsLoaded.size());
991  }
992
993  /// \brief Returns the number of preprocessed entities known to the AST
994  /// reader.
995  unsigned getTotalNumPreprocessedEntities() const {
996    unsigned Result = 0;
997    for (ModuleConstIterator I = ModuleMgr.begin(),
998        E = ModuleMgr.end(); I != E; ++I) {
999      Result += (*I)->NumPreprocessedEntities;
1000    }
1001
1002    return Result;
1003  }
1004
1005  /// \brief Returns the number of C++ base specifiers found in the chain.
1006  unsigned getTotalNumCXXBaseSpecifiers() const {
1007    return NumCXXBaseSpecifiersLoaded;
1008  }
1009
1010  /// \brief Reads a TemplateArgumentLocInfo appropriate for the
1011  /// given TemplateArgument kind.
1012  TemplateArgumentLocInfo
1013  GetTemplateArgumentLocInfo(ModuleFile &F, TemplateArgument::ArgKind Kind,
1014                             const RecordData &Record, unsigned &Idx);
1015
1016  /// \brief Reads a TemplateArgumentLoc.
1017  TemplateArgumentLoc
1018  ReadTemplateArgumentLoc(ModuleFile &F,
1019                          const RecordData &Record, unsigned &Idx);
1020
1021  /// \brief Reads a declarator info from the given record.
1022  TypeSourceInfo *GetTypeSourceInfo(ModuleFile &F,
1023                                    const RecordData &Record, unsigned &Idx);
1024
1025  /// \brief Resolve a type ID into a type, potentially building a new
1026  /// type.
1027  QualType GetType(serialization::TypeID ID);
1028
1029  /// \brief Resolve a local type ID within a given AST file into a type.
1030  QualType getLocalType(ModuleFile &F, unsigned LocalID);
1031
1032  /// \brief Map a local type ID within a given AST file into a global type ID.
1033  serialization::TypeID getGlobalTypeID(ModuleFile &F, unsigned LocalID) const;
1034
1035  /// \brief Read a type from the current position in the given record, which
1036  /// was read from the given AST file.
1037  QualType readType(ModuleFile &F, const RecordData &Record, unsigned &Idx) {
1038    if (Idx >= Record.size())
1039      return QualType();
1040
1041    return getLocalType(F, Record[Idx++]);
1042  }
1043
1044  /// \brief Map from a local declaration ID within a given module to a
1045  /// global declaration ID.
1046  serialization::DeclID getGlobalDeclID(ModuleFile &F, unsigned LocalID) const;
1047
1048  /// \brief Returns true if global DeclID \arg ID originated from module
1049  /// \arg M.
1050  bool isDeclIDFromModule(serialization::GlobalDeclID ID, ModuleFile &M) const;
1051
1052  /// \brief Retrieve the module file that owns the given declaration, or NULL
1053  /// if the declaration is not from a module file.
1054  ModuleFile *getOwningModuleFile(Decl *D);
1055
1056  /// \brief Returns the source location for the decl \arg ID.
1057  SourceLocation getSourceLocationForDeclID(serialization::GlobalDeclID ID);
1058
1059  /// \brief Resolve a declaration ID into a declaration, potentially
1060  /// building a new declaration.
1061  Decl *GetDecl(serialization::DeclID ID);
1062  virtual Decl *GetExternalDecl(uint32_t ID);
1063
1064  /// \brief Reads a declaration with the given local ID in the given module.
1065  Decl *GetLocalDecl(ModuleFile &F, uint32_t LocalID) {
1066    return GetDecl(getGlobalDeclID(F, LocalID));
1067  }
1068
1069  /// \brief Reads a declaration with the given local ID in the given module.
1070  ///
1071  /// \returns The requested declaration, casted to the given return type.
1072  template<typename T>
1073  T *GetLocalDeclAs(ModuleFile &F, uint32_t LocalID) {
1074    return cast_or_null<T>(GetLocalDecl(F, LocalID));
1075  }
1076
1077  /// \brief Map a global declaration ID into the declaration ID used to
1078  /// refer to this declaration within the given module fule.
1079  ///
1080  /// \returns the global ID of the given declaration as known in the given
1081  /// module file.
1082  serialization::DeclID
1083  mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
1084                                  serialization::DeclID GlobalID);
1085
1086  /// \brief Reads a declaration ID from the given position in a record in the
1087  /// given module.
1088  ///
1089  /// \returns The declaration ID read from the record, adjusted to a global ID.
1090  serialization::DeclID ReadDeclID(ModuleFile &F, const RecordData &Record,
1091                                   unsigned &Idx);
1092
1093  /// \brief Reads a declaration from the given position in a record in the
1094  /// given module.
1095  Decl *ReadDecl(ModuleFile &F, const RecordData &R, unsigned &I) {
1096    return GetDecl(ReadDeclID(F, R, I));
1097  }
1098
1099  /// \brief Reads a declaration from the given position in a record in the
1100  /// given module.
1101  ///
1102  /// \returns The declaration read from this location, casted to the given
1103  /// result type.
1104  template<typename T>
1105  T *ReadDeclAs(ModuleFile &F, const RecordData &R, unsigned &I) {
1106    return cast_or_null<T>(GetDecl(ReadDeclID(F, R, I)));
1107  }
1108
1109  /// \brief Read a CXXBaseSpecifiers ID form the given record and
1110  /// return its global bit offset.
1111  uint64_t readCXXBaseSpecifiers(ModuleFile &M, const RecordData &Record,
1112                                 unsigned &Idx);
1113
1114  virtual CXXBaseSpecifier *GetExternalCXXBaseSpecifiers(uint64_t Offset);
1115
1116  /// \brief Resolve the offset of a statement into a statement.
1117  ///
1118  /// This operation will read a new statement from the external
1119  /// source each time it is called, and is meant to be used via a
1120  /// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
1121  virtual Stmt *GetExternalDeclStmt(uint64_t Offset);
1122
1123  /// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1124  /// specified cursor.  Read the abbreviations that are at the top of the block
1125  /// and then leave the cursor pointing into the block.
1126  bool ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor, unsigned BlockID);
1127
1128  /// \brief Finds all the visible declarations with a given name.
1129  /// The current implementation of this method just loads the entire
1130  /// lookup table as unmaterialized references.
1131  virtual DeclContext::lookup_result
1132  FindExternalVisibleDeclsByName(const DeclContext *DC,
1133                                 DeclarationName Name);
1134
1135  /// \brief Read all of the declarations lexically stored in a
1136  /// declaration context.
1137  ///
1138  /// \param DC The declaration context whose declarations will be
1139  /// read.
1140  ///
1141  /// \param Decls Vector that will contain the declarations loaded
1142  /// from the external source. The caller is responsible for merging
1143  /// these declarations with any declarations already stored in the
1144  /// declaration context.
1145  ///
1146  /// \returns true if there was an error while reading the
1147  /// declarations for this declaration context.
1148  virtual ExternalLoadResult FindExternalLexicalDecls(const DeclContext *DC,
1149                                        bool (*isKindWeWant)(Decl::Kind),
1150                                        SmallVectorImpl<Decl*> &Decls);
1151
1152  /// \brief Get the decls that are contained in a file in the Offset/Length
1153  /// range. \arg Length can be 0 to indicate a point at \arg Offset instead of
1154  /// a range.
1155  virtual void FindFileRegionDecls(FileID File, unsigned Offset,unsigned Length,
1156                                   SmallVectorImpl<Decl *> &Decls);
1157
1158  /// \brief Notify ASTReader that we started deserialization of
1159  /// a decl or type so until FinishedDeserializing is called there may be
1160  /// decls that are initializing. Must be paired with FinishedDeserializing.
1161  virtual void StartedDeserializing() { ++NumCurrentElementsDeserializing; }
1162
1163  /// \brief Notify ASTReader that we finished the deserialization of
1164  /// a decl or type. Must be paired with StartedDeserializing.
1165  virtual void FinishedDeserializing();
1166
1167  /// \brief Function that will be invoked when we begin parsing a new
1168  /// translation unit involving this external AST source.
1169  ///
1170  /// This function will provide all of the external definitions to
1171  /// the ASTConsumer.
1172  virtual void StartTranslationUnit(ASTConsumer *Consumer);
1173
1174  /// \brief Print some statistics about AST usage.
1175  virtual void PrintStats();
1176
1177  /// \brief Dump information about the AST reader to standard error.
1178  void dump();
1179
1180  /// Return the amount of memory used by memory buffers, breaking down
1181  /// by heap-backed versus mmap'ed memory.
1182  virtual void getMemoryBufferSizes(MemoryBufferSizes &sizes) const;
1183
1184  /// \brief Initialize the semantic source with the Sema instance
1185  /// being used to perform semantic analysis on the abstract syntax
1186  /// tree.
1187  virtual void InitializeSema(Sema &S);
1188
1189  /// \brief Inform the semantic consumer that Sema is no longer available.
1190  virtual void ForgetSema() { SemaObj = 0; }
1191
1192  /// \brief Retrieve the IdentifierInfo for the named identifier.
1193  ///
1194  /// This routine builds a new IdentifierInfo for the given identifier. If any
1195  /// declarations with this name are visible from translation unit scope, their
1196  /// declarations will be deserialized and introduced into the declaration
1197  /// chain of the identifier.
1198  virtual IdentifierInfo *get(const char *NameStart, const char *NameEnd);
1199  IdentifierInfo *get(StringRef Name) {
1200    return get(Name.begin(), Name.end());
1201  }
1202
1203  /// \brief Retrieve an iterator into the set of all identifiers
1204  /// in all loaded AST files.
1205  virtual IdentifierIterator *getIdentifiers() const;
1206
1207  /// \brief Load the contents of the global method pool for a given
1208  /// selector.
1209  virtual void ReadMethodPool(Selector Sel);
1210
1211  /// \brief Load the set of namespaces that are known to the external source,
1212  /// which will be used during typo correction.
1213  virtual void ReadKnownNamespaces(
1214                           SmallVectorImpl<NamespaceDecl *> &Namespaces);
1215
1216  virtual void ReadTentativeDefinitions(
1217                 SmallVectorImpl<VarDecl *> &TentativeDefs);
1218
1219  virtual void ReadUnusedFileScopedDecls(
1220                 SmallVectorImpl<const DeclaratorDecl *> &Decls);
1221
1222  virtual void ReadDelegatingConstructors(
1223                 SmallVectorImpl<CXXConstructorDecl *> &Decls);
1224
1225  virtual void ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls);
1226
1227  virtual void ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls);
1228
1229  virtual void ReadLocallyScopedExternalDecls(
1230                 SmallVectorImpl<NamedDecl *> &Decls);
1231
1232  virtual void ReadReferencedSelectors(
1233                 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels);
1234
1235  virtual void ReadWeakUndeclaredIdentifiers(
1236                 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WI);
1237
1238  virtual void ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables);
1239
1240  virtual void ReadPendingInstantiations(
1241                 SmallVectorImpl<std::pair<ValueDecl *,
1242                                           SourceLocation> > &Pending);
1243
1244  /// \brief Load a selector from disk, registering its ID if it exists.
1245  void LoadSelector(Selector Sel);
1246
1247  void SetIdentifierInfo(unsigned ID, IdentifierInfo *II);
1248  void SetGloballyVisibleDecls(IdentifierInfo *II,
1249                               const SmallVectorImpl<uint32_t> &DeclIDs,
1250                               bool Nonrecursive = false);
1251
1252  /// \brief Report a diagnostic.
1253  DiagnosticBuilder Diag(unsigned DiagID);
1254
1255  /// \brief Report a diagnostic.
1256  DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
1257
1258  IdentifierInfo *DecodeIdentifierInfo(serialization::IdentifierID ID);
1259
1260  IdentifierInfo *GetIdentifierInfo(ModuleFile &M, const RecordData &Record,
1261                                    unsigned &Idx) {
1262    return DecodeIdentifierInfo(getGlobalIdentifierID(M, Record[Idx++]));
1263  }
1264
1265  virtual IdentifierInfo *GetIdentifier(serialization::IdentifierID ID) {
1266    return DecodeIdentifierInfo(ID);
1267  }
1268
1269  IdentifierInfo *getLocalIdentifier(ModuleFile &M, unsigned LocalID);
1270
1271  serialization::IdentifierID getGlobalIdentifierID(ModuleFile &M,
1272                                                    unsigned LocalID);
1273
1274  /// \brief Read the source location entry with index ID.
1275  virtual bool ReadSLocEntry(int ID);
1276
1277  /// \brief Retrieve the global submodule ID given a module and its local ID
1278  /// number.
1279  serialization::SubmoduleID
1280  getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID);
1281
1282  /// \brief Retrieve the submodule that corresponds to a global submodule ID.
1283  ///
1284  Module *getSubmodule(serialization::SubmoduleID GlobalID);
1285
1286  /// \brief Retrieve a selector from the given module with its local ID
1287  /// number.
1288  Selector getLocalSelector(ModuleFile &M, unsigned LocalID);
1289
1290  Selector DecodeSelector(serialization::SelectorID Idx);
1291
1292  virtual Selector GetExternalSelector(serialization::SelectorID ID);
1293  uint32_t GetNumExternalSelectors();
1294
1295  Selector ReadSelector(ModuleFile &M, const RecordData &Record, unsigned &Idx) {
1296    return getLocalSelector(M, Record[Idx++]);
1297  }
1298
1299  /// \brief Retrieve the global selector ID that corresponds to this
1300  /// the local selector ID in a given module.
1301  serialization::SelectorID getGlobalSelectorID(ModuleFile &F,
1302                                                unsigned LocalID) const;
1303
1304  /// \brief Read a declaration name.
1305  DeclarationName ReadDeclarationName(ModuleFile &F,
1306                                      const RecordData &Record, unsigned &Idx);
1307  void ReadDeclarationNameLoc(ModuleFile &F,
1308                              DeclarationNameLoc &DNLoc, DeclarationName Name,
1309                              const RecordData &Record, unsigned &Idx);
1310  void ReadDeclarationNameInfo(ModuleFile &F, DeclarationNameInfo &NameInfo,
1311                               const RecordData &Record, unsigned &Idx);
1312
1313  void ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
1314                         const RecordData &Record, unsigned &Idx);
1315
1316  NestedNameSpecifier *ReadNestedNameSpecifier(ModuleFile &F,
1317                                               const RecordData &Record,
1318                                               unsigned &Idx);
1319
1320  NestedNameSpecifierLoc ReadNestedNameSpecifierLoc(ModuleFile &F,
1321                                                    const RecordData &Record,
1322                                                    unsigned &Idx);
1323
1324  /// \brief Read a template name.
1325  TemplateName ReadTemplateName(ModuleFile &F, const RecordData &Record,
1326                                unsigned &Idx);
1327
1328  /// \brief Read a template argument.
1329  TemplateArgument ReadTemplateArgument(ModuleFile &F,
1330                                        const RecordData &Record,unsigned &Idx);
1331
1332  /// \brief Read a template parameter list.
1333  TemplateParameterList *ReadTemplateParameterList(ModuleFile &F,
1334                                                   const RecordData &Record,
1335                                                   unsigned &Idx);
1336
1337  /// \brief Read a template argument array.
1338  void
1339  ReadTemplateArgumentList(SmallVector<TemplateArgument, 8> &TemplArgs,
1340                           ModuleFile &F, const RecordData &Record,
1341                           unsigned &Idx);
1342
1343  /// \brief Read a UnresolvedSet structure.
1344  void ReadUnresolvedSet(ModuleFile &F, UnresolvedSetImpl &Set,
1345                         const RecordData &Record, unsigned &Idx);
1346
1347  /// \brief Read a C++ base specifier.
1348  CXXBaseSpecifier ReadCXXBaseSpecifier(ModuleFile &F,
1349                                        const RecordData &Record,unsigned &Idx);
1350
1351  /// \brief Read a CXXCtorInitializer array.
1352  std::pair<CXXCtorInitializer **, unsigned>
1353  ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
1354                          unsigned &Idx);
1355
1356  /// \brief Read a source location from raw form.
1357  SourceLocation ReadSourceLocation(ModuleFile &ModuleFile, unsigned Raw) const {
1358    SourceLocation Loc = SourceLocation::getFromRawEncoding(Raw);
1359    assert(ModuleFile.SLocRemap.find(Loc.getOffset()) != ModuleFile.SLocRemap.end() &&
1360           "Cannot find offset to remap.");
1361    int Remap = ModuleFile.SLocRemap.find(Loc.getOffset())->second;
1362    return Loc.getLocWithOffset(Remap);
1363  }
1364
1365  /// \brief Read a source location.
1366  SourceLocation ReadSourceLocation(ModuleFile &ModuleFile,
1367                                    const RecordData &Record, unsigned& Idx) {
1368    return ReadSourceLocation(ModuleFile, Record[Idx++]);
1369  }
1370
1371  /// \brief Read a source range.
1372  SourceRange ReadSourceRange(ModuleFile &F,
1373                              const RecordData &Record, unsigned& Idx);
1374
1375  /// \brief Read an integral value
1376  llvm::APInt ReadAPInt(const RecordData &Record, unsigned &Idx);
1377
1378  /// \brief Read a signed integral value
1379  llvm::APSInt ReadAPSInt(const RecordData &Record, unsigned &Idx);
1380
1381  /// \brief Read a floating-point value
1382  llvm::APFloat ReadAPFloat(const RecordData &Record, unsigned &Idx);
1383
1384  // \brief Read a string
1385  std::string ReadString(const RecordData &Record, unsigned &Idx);
1386
1387  /// \brief Read a version tuple.
1388  VersionTuple ReadVersionTuple(const RecordData &Record, unsigned &Idx);
1389
1390  CXXTemporary *ReadCXXTemporary(ModuleFile &F, const RecordData &Record,
1391                                 unsigned &Idx);
1392
1393  /// \brief Reads attributes from the current stream position.
1394  void ReadAttributes(ModuleFile &F, AttrVec &Attrs,
1395                      const RecordData &Record, unsigned &Idx);
1396
1397  /// \brief Reads a statement.
1398  Stmt *ReadStmt(ModuleFile &F);
1399
1400  /// \brief Reads an expression.
1401  Expr *ReadExpr(ModuleFile &F);
1402
1403  /// \brief Reads a sub-statement operand during statement reading.
1404  Stmt *ReadSubStmt() {
1405    assert(ReadingKind == Read_Stmt &&
1406           "Should be called only during statement reading!");
1407    // Subexpressions are stored from last to first, so the next Stmt we need
1408    // is at the back of the stack.
1409    assert(!StmtStack.empty() && "Read too many sub statements!");
1410    return StmtStack.pop_back_val();
1411  }
1412
1413  /// \brief Reads a sub-expression operand during statement reading.
1414  Expr *ReadSubExpr();
1415
1416  /// \brief Reads the macro record located at the given offset.
1417  void ReadMacroRecord(ModuleFile &F, uint64_t Offset);
1418
1419  /// \brief Determine the global preprocessed entity ID that corresponds to
1420  /// the given local ID within the given module.
1421  serialization::PreprocessedEntityID
1422  getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const;
1423
1424  /// \brief Note that the identifier is a macro whose record will be loaded
1425  /// from the given AST file at the given (file-local) offset.
1426  ///
1427  /// \param II The name of the macro.
1428  ///
1429  /// \param F The module file from which the macro definition was deserialized.
1430  ///
1431  /// \param Offset The offset into the module file at which the macro
1432  /// definition is located.
1433  ///
1434  /// \param Visible Whether the macro should be made visible.
1435  void setIdentifierIsMacro(IdentifierInfo *II, ModuleFile &F,
1436                            uint64_t Offset, bool Visible);
1437
1438  /// \brief Read the set of macros defined by this external macro source.
1439  virtual void ReadDefinedMacros();
1440
1441  /// \brief Read the macro definition for this identifier.
1442  virtual void LoadMacroDefinition(IdentifierInfo *II);
1443
1444  /// \brief Update an out-of-date identifier.
1445  virtual void updateOutOfDateIdentifier(IdentifierInfo &II);
1446
1447  /// \brief Note that this identifier is up-to-date.
1448  void markIdentifierUpToDate(IdentifierInfo *II);
1449
1450  /// \brief Read the macro definition corresponding to this iterator
1451  /// into the unread macro record offsets table.
1452  void LoadMacroDefinition(
1453                     llvm::DenseMap<IdentifierInfo *, uint64_t>::iterator Pos);
1454
1455  /// \brief Retrieve the AST context that this AST reader supplements.
1456  ASTContext &getContext() { return Context; }
1457
1458  // \brief Contains declarations that were loaded before we have
1459  // access to a Sema object.
1460  SmallVector<NamedDecl *, 16> PreloadedDecls;
1461
1462  /// \brief Retrieve the semantic analysis object used to analyze the
1463  /// translation unit in which the precompiled header is being
1464  /// imported.
1465  Sema *getSema() { return SemaObj; }
1466
1467  /// \brief Retrieve the identifier table associated with the
1468  /// preprocessor.
1469  IdentifierTable &getIdentifierTable();
1470
1471  /// \brief Record that the given ID maps to the given switch-case
1472  /// statement.
1473  void RecordSwitchCaseID(SwitchCase *SC, unsigned ID);
1474
1475  /// \brief Retrieve the switch-case statement with the given ID.
1476  SwitchCase *getSwitchCaseWithID(unsigned ID);
1477
1478  void ClearSwitchCaseIDs();
1479};
1480
1481/// \brief Helper class that saves the current stream position and
1482/// then restores it when destroyed.
1483struct SavedStreamPosition {
1484  explicit SavedStreamPosition(llvm::BitstreamCursor &Cursor)
1485  : Cursor(Cursor), Offset(Cursor.GetCurrentBitNo()) { }
1486
1487  ~SavedStreamPosition() {
1488    Cursor.JumpToBit(Offset);
1489  }
1490
1491private:
1492  llvm::BitstreamCursor &Cursor;
1493  uint64_t Offset;
1494};
1495
1496inline void PCHValidator::Error(const char *Msg) {
1497  Reader.Error(Msg);
1498}
1499
1500} // end namespace clang
1501
1502#endif
1503