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