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