]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/include/clang/Serialization/ASTReader.h
Merge clang 7.0.1 and several follow-up changes
[FreeBSD/FreeBSD.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_SERIALIZATION_ASTREADER_H
15 #define LLVM_CLANG_SERIALIZATION_ASTREADER_H
16
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/DeclarationName.h"
20 #include "clang/AST/NestedNameSpecifier.h"
21 #include "clang/AST/TemplateBase.h"
22 #include "clang/AST/TemplateName.h"
23 #include "clang/AST/Type.h"
24 #include "clang/Basic/Diagnostic.h"
25 #include "clang/Basic/DiagnosticOptions.h"
26 #include "clang/Basic/IdentifierTable.h"
27 #include "clang/Basic/Module.h"
28 #include "clang/Basic/OpenCLOptions.h"
29 #include "clang/Basic/SourceLocation.h"
30 #include "clang/Basic/Version.h"
31 #include "clang/Lex/ExternalPreprocessorSource.h"
32 #include "clang/Lex/HeaderSearch.h"
33 #include "clang/Lex/PreprocessingRecord.h"
34 #include "clang/Lex/Token.h"
35 #include "clang/Sema/ExternalSemaSource.h"
36 #include "clang/Sema/IdentifierResolver.h"
37 #include "clang/Serialization/ASTBitCodes.h"
38 #include "clang/Serialization/ContinuousRangeMap.h"
39 #include "clang/Serialization/Module.h"
40 #include "clang/Serialization/ModuleFileExtension.h"
41 #include "clang/Serialization/ModuleManager.h"
42 #include "llvm/ADT/APFloat.h"
43 #include "llvm/ADT/APInt.h"
44 #include "llvm/ADT/APSInt.h"
45 #include "llvm/ADT/ArrayRef.h"
46 #include "llvm/ADT/DenseMap.h"
47 #include "llvm/ADT/DenseSet.h"
48 #include "llvm/ADT/IntrusiveRefCntPtr.h"
49 #include "llvm/ADT/MapVector.h"
50 #include "llvm/ADT/Optional.h"
51 #include "llvm/ADT/STLExtras.h"
52 #include "llvm/ADT/SetVector.h"
53 #include "llvm/ADT/SmallPtrSet.h"
54 #include "llvm/ADT/SmallVector.h"
55 #include "llvm/ADT/StringMap.h"
56 #include "llvm/ADT/StringRef.h"
57 #include "llvm/ADT/iterator.h"
58 #include "llvm/ADT/iterator_range.h"
59 #include "llvm/Bitcode/BitstreamReader.h"
60 #include "llvm/Support/Casting.h"
61 #include "llvm/Support/Endian.h"
62 #include "llvm/Support/MemoryBuffer.h"
63 #include "llvm/Support/Timer.h"
64 #include "llvm/Support/VersionTuple.h"
65 #include <cassert>
66 #include <cstddef>
67 #include <cstdint>
68 #include <ctime>
69 #include <deque>
70 #include <memory>
71 #include <set>
72 #include <string>
73 #include <utility>
74 #include <vector>
75
76 namespace clang {
77
78 class ASTConsumer;
79 class ASTContext;
80 class ASTDeserializationListener;
81 class ASTReader;
82 class ASTRecordReader;
83 class CXXTemporary;
84 class Decl;
85 class DeclaratorDecl;
86 class DeclContext;
87 class EnumDecl;
88 class Expr;
89 class FieldDecl;
90 class FileEntry;
91 class FileManager;
92 class FileSystemOptions;
93 class FunctionDecl;
94 class GlobalModuleIndex;
95 struct HeaderFileInfo;
96 class HeaderSearchOptions;
97 class LangOptions;
98 class LazyASTUnresolvedSet;
99 class MacroInfo;
100 class MemoryBufferCache;
101 class NamedDecl;
102 class NamespaceDecl;
103 class ObjCCategoryDecl;
104 class ObjCInterfaceDecl;
105 class PCHContainerReader;
106 class Preprocessor;
107 class PreprocessorOptions;
108 struct QualifierInfo;
109 class Sema;
110 class SourceManager;
111 class Stmt;
112 class SwitchCase;
113 class TargetOptions;
114 class TemplateParameterList;
115 class TypedefNameDecl;
116 class TypeSourceInfo;
117 class ValueDecl;
118 class VarDecl;
119
120 /// Abstract interface for callback invocations by the ASTReader.
121 ///
122 /// While reading an AST file, the ASTReader will call the methods of the
123 /// listener to pass on specific information. Some of the listener methods can
124 /// return true to indicate to the ASTReader that the information (and
125 /// consequently the AST file) is invalid.
126 class ASTReaderListener {
127 public:
128   virtual ~ASTReaderListener();
129
130   /// Receives the full Clang version information.
131   ///
132   /// \returns true to indicate that the version is invalid. Subclasses should
133   /// generally defer to this implementation.
134   virtual bool ReadFullVersionInformation(StringRef FullVersion) {
135     return FullVersion != getClangFullRepositoryVersion();
136   }
137
138   virtual void ReadModuleName(StringRef ModuleName) {}
139   virtual void ReadModuleMapFile(StringRef ModuleMapPath) {}
140
141   /// Receives the language options.
142   ///
143   /// \returns true to indicate the options are invalid or false otherwise.
144   virtual bool ReadLanguageOptions(const LangOptions &LangOpts,
145                                    bool Complain,
146                                    bool AllowCompatibleDifferences) {
147     return false;
148   }
149
150   /// Receives the target options.
151   ///
152   /// \returns true to indicate the target options are invalid, or false
153   /// otherwise.
154   virtual bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
155                                  bool AllowCompatibleDifferences) {
156     return false;
157   }
158
159   /// Receives the diagnostic options.
160   ///
161   /// \returns true to indicate the diagnostic options are invalid, or false
162   /// otherwise.
163   virtual bool
164   ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
165                         bool Complain) {
166     return false;
167   }
168
169   /// Receives the file system options.
170   ///
171   /// \returns true to indicate the file system options are invalid, or false
172   /// otherwise.
173   virtual bool ReadFileSystemOptions(const FileSystemOptions &FSOpts,
174                                      bool Complain) {
175     return false;
176   }
177
178   /// Receives the header search options.
179   ///
180   /// \returns true to indicate the header search options are invalid, or false
181   /// otherwise.
182   virtual bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
183                                        StringRef SpecificModuleCachePath,
184                                        bool Complain) {
185     return false;
186   }
187
188   /// Receives the preprocessor options.
189   ///
190   /// \param SuggestedPredefines Can be filled in with the set of predefines
191   /// that are suggested by the preprocessor options. Typically only used when
192   /// loading a precompiled header.
193   ///
194   /// \returns true to indicate the preprocessor options are invalid, or false
195   /// otherwise.
196   virtual bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
197                                        bool Complain,
198                                        std::string &SuggestedPredefines) {
199     return false;
200   }
201
202   /// Receives __COUNTER__ value.
203   virtual void ReadCounter(const serialization::ModuleFile &M,
204                            unsigned Value) {}
205
206   /// This is called for each AST file loaded.
207   virtual void visitModuleFile(StringRef Filename,
208                                serialization::ModuleKind Kind) {}
209
210   /// Returns true if this \c ASTReaderListener wants to receive the
211   /// input files of the AST file via \c visitInputFile, false otherwise.
212   virtual bool needsInputFileVisitation() { return false; }
213
214   /// Returns true if this \c ASTReaderListener wants to receive the
215   /// system input files of the AST file via \c visitInputFile, false otherwise.
216   virtual bool needsSystemInputFileVisitation() { return false; }
217
218   /// if \c needsInputFileVisitation returns true, this is called for
219   /// each non-system input file of the AST File. If
220   /// \c needsSystemInputFileVisitation is true, then it is called for all
221   /// system input files as well.
222   ///
223   /// \returns true to continue receiving the next input file, false to stop.
224   virtual bool visitInputFile(StringRef Filename, bool isSystem,
225                               bool isOverridden, bool isExplicitModule) {
226     return true;
227   }
228
229   /// Returns true if this \c ASTReaderListener wants to receive the
230   /// imports of the AST file via \c visitImport, false otherwise.
231   virtual bool needsImportVisitation() const { return false; }
232
233   /// If needsImportVisitation returns \c true, this is called for each
234   /// AST file imported by this AST file.
235   virtual void visitImport(StringRef Filename) {}
236
237   /// Indicates that a particular module file extension has been read.
238   virtual void readModuleFileExtension(
239                  const ModuleFileExtensionMetadata &Metadata) {}
240 };
241
242 /// Simple wrapper class for chaining listeners.
243 class ChainedASTReaderListener : public ASTReaderListener {
244   std::unique_ptr<ASTReaderListener> First;
245   std::unique_ptr<ASTReaderListener> Second;
246
247 public:
248   /// Takes ownership of \p First and \p Second.
249   ChainedASTReaderListener(std::unique_ptr<ASTReaderListener> First,
250                            std::unique_ptr<ASTReaderListener> Second)
251       : First(std::move(First)), Second(std::move(Second)) {}
252
253   std::unique_ptr<ASTReaderListener> takeFirst() { return std::move(First); }
254   std::unique_ptr<ASTReaderListener> takeSecond() { return std::move(Second); }
255
256   bool ReadFullVersionInformation(StringRef FullVersion) override;
257   void ReadModuleName(StringRef ModuleName) override;
258   void ReadModuleMapFile(StringRef ModuleMapPath) override;
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 ReadFileSystemOptions(const FileSystemOptions &FSOpts,
266                              bool Complain) override;
267
268   bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
269                                StringRef SpecificModuleCachePath,
270                                bool Complain) override;
271   bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
272                                bool Complain,
273                                std::string &SuggestedPredefines) override;
274
275   void ReadCounter(const serialization::ModuleFile &M, unsigned Value) override;
276   bool needsInputFileVisitation() override;
277   bool needsSystemInputFileVisitation() override;
278   void visitModuleFile(StringRef Filename,
279                        serialization::ModuleKind Kind) override;
280   bool visitInputFile(StringRef Filename, bool isSystem,
281                       bool isOverridden, bool isExplicitModule) override;
282   void readModuleFileExtension(
283          const ModuleFileExtensionMetadata &Metadata) override;
284 };
285
286 /// ASTReaderListener implementation to validate the information of
287 /// the PCH file against an initialized Preprocessor.
288 class PCHValidator : public ASTReaderListener {
289   Preprocessor &PP;
290   ASTReader &Reader;
291
292 public:
293   PCHValidator(Preprocessor &PP, ASTReader &Reader)
294       : PP(PP), Reader(Reader) {}
295
296   bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
297                            bool AllowCompatibleDifferences) override;
298   bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
299                          bool AllowCompatibleDifferences) override;
300   bool ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
301                              bool Complain) override;
302   bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool Complain,
303                                std::string &SuggestedPredefines) override;
304   bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
305                                StringRef SpecificModuleCachePath,
306                                bool Complain) override;
307   void ReadCounter(const serialization::ModuleFile &M, unsigned Value) override;
308
309 private:
310   void Error(const char *Msg);
311 };
312
313 /// ASTReaderListenter implementation to set SuggestedPredefines of
314 /// ASTReader which is required to use a pch file. This is the replacement
315 /// of PCHValidator or SimplePCHValidator when using a pch file without
316 /// validating it.
317 class SimpleASTReaderListener : public ASTReaderListener {
318   Preprocessor &PP;
319
320 public:
321   SimpleASTReaderListener(Preprocessor &PP) : PP(PP) {}
322
323   bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool Complain,
324                                std::string &SuggestedPredefines) override;
325 };
326
327 namespace serialization {
328
329 class ReadMethodPoolVisitor;
330
331 namespace reader {
332
333 class ASTIdentifierLookupTrait;
334
335 /// The on-disk hash table(s) used for DeclContext name lookup.
336 struct DeclContextLookupTable;
337
338 } // namespace reader
339
340 } // namespace serialization
341
342 /// Reads an AST files chain containing the contents of a translation
343 /// unit.
344 ///
345 /// The ASTReader class reads bitstreams (produced by the ASTWriter
346 /// class) containing the serialized representation of a given
347 /// abstract syntax tree and its supporting data structures. An
348 /// instance of the ASTReader can be attached to an ASTContext object,
349 /// which will provide access to the contents of the AST files.
350 ///
351 /// The AST reader provides lazy de-serialization of declarations, as
352 /// required when traversing the AST. Only those AST nodes that are
353 /// actually required will be de-serialized.
354 class ASTReader
355   : public ExternalPreprocessorSource,
356     public ExternalPreprocessingRecordSource,
357     public ExternalHeaderFileInfoSource,
358     public ExternalSemaSource,
359     public IdentifierInfoLookup,
360     public ExternalSLocEntrySource
361 {
362 public:
363   /// Types of AST files.
364   friend class ASTDeclReader;
365   friend class ASTIdentifierIterator;
366   friend class ASTRecordReader;
367   friend class ASTStmtReader;
368   friend class ASTUnit; // ASTUnit needs to remap source locations.
369   friend class ASTWriter;
370   friend class PCHValidator;
371   friend class serialization::reader::ASTIdentifierLookupTrait;
372   friend class serialization::ReadMethodPoolVisitor;
373   friend class TypeLocReader;
374
375   using RecordData = SmallVector<uint64_t, 64>;
376   using RecordDataImpl = SmallVectorImpl<uint64_t>;
377
378   /// The result of reading the control block of an AST file, which
379   /// can fail for various reasons.
380   enum ASTReadResult {
381     /// The control block was read successfully. Aside from failures,
382     /// the AST file is safe to read into the current context.
383     Success,
384
385     /// The AST file itself appears corrupted.
386     Failure,
387
388     /// The AST file was missing.
389     Missing,
390
391     /// The AST file is out-of-date relative to its input files,
392     /// and needs to be regenerated.
393     OutOfDate,
394
395     /// The AST file was written by a different version of Clang.
396     VersionMismatch,
397
398     /// The AST file was writtten with a different language/target
399     /// configuration.
400     ConfigurationMismatch,
401
402     /// The AST file has errors.
403     HadErrors
404   };
405
406   using ModuleFile = serialization::ModuleFile;
407   using ModuleKind = serialization::ModuleKind;
408   using ModuleManager = serialization::ModuleManager;
409   using ModuleIterator = ModuleManager::ModuleIterator;
410   using ModuleConstIterator = ModuleManager::ModuleConstIterator;
411   using ModuleReverseIterator = ModuleManager::ModuleReverseIterator;
412
413 private:
414   /// The receiver of some callbacks invoked by ASTReader.
415   std::unique_ptr<ASTReaderListener> Listener;
416
417   /// The receiver of deserialization events.
418   ASTDeserializationListener *DeserializationListener = nullptr;
419
420   bool OwnsDeserializationListener = false;
421
422   SourceManager &SourceMgr;
423   FileManager &FileMgr;
424   const PCHContainerReader &PCHContainerRdr;
425   DiagnosticsEngine &Diags;
426
427   /// The semantic analysis object that will be processing the
428   /// AST files and the translation unit that uses it.
429   Sema *SemaObj = nullptr;
430
431   /// The preprocessor that will be loading the source file.
432   Preprocessor &PP;
433
434   /// The AST context into which we'll read the AST files.
435   ASTContext *ContextObj = nullptr;
436
437   /// The AST consumer.
438   ASTConsumer *Consumer = nullptr;
439
440   /// The module manager which manages modules and their dependencies
441   ModuleManager ModuleMgr;
442
443   /// The cache that manages memory buffers for PCM files.
444   MemoryBufferCache &PCMCache;
445
446   /// A dummy identifier resolver used to merge TU-scope declarations in
447   /// C, for the cases where we don't have a Sema object to provide a real
448   /// identifier resolver.
449   IdentifierResolver DummyIdResolver;
450
451   /// A mapping from extension block names to module file extensions.
452   llvm::StringMap<std::shared_ptr<ModuleFileExtension>> ModuleFileExtensions;
453
454   /// A timer used to track the time spent deserializing.
455   std::unique_ptr<llvm::Timer> ReadTimer;
456
457   /// The location where the module file will be considered as
458   /// imported from. For non-module AST types it should be invalid.
459   SourceLocation CurrentImportLoc;
460
461   /// The global module index, if loaded.
462   std::unique_ptr<GlobalModuleIndex> GlobalIndex;
463
464   /// A map of global bit offsets to the module that stores entities
465   /// at those bit offsets.
466   ContinuousRangeMap<uint64_t, ModuleFile*, 4> GlobalBitOffsetsMap;
467
468   /// A map of negated SLocEntryIDs to the modules containing them.
469   ContinuousRangeMap<unsigned, ModuleFile*, 64> GlobalSLocEntryMap;
470
471   using GlobalSLocOffsetMapType =
472       ContinuousRangeMap<unsigned, ModuleFile *, 64>;
473
474   /// A map of reversed (SourceManager::MaxLoadedOffset - SLocOffset)
475   /// SourceLocation offsets to the modules containing them.
476   GlobalSLocOffsetMapType GlobalSLocOffsetMap;
477
478   /// Types that have already been loaded from the chain.
479   ///
480   /// When the pointer at index I is non-NULL, the type with
481   /// ID = (I + 1) << FastQual::Width has already been loaded
482   std::vector<QualType> TypesLoaded;
483
484   using GlobalTypeMapType =
485       ContinuousRangeMap<serialization::TypeID, ModuleFile *, 4>;
486
487   /// Mapping from global type IDs to the module in which the
488   /// type resides along with the offset that should be added to the
489   /// global type ID to produce a local ID.
490   GlobalTypeMapType GlobalTypeMap;
491
492   /// Declarations that have already been loaded from the chain.
493   ///
494   /// When the pointer at index I is non-NULL, the declaration with ID
495   /// = I + 1 has already been loaded.
496   std::vector<Decl *> DeclsLoaded;
497
498   using GlobalDeclMapType =
499       ContinuousRangeMap<serialization::DeclID, ModuleFile *, 4>;
500
501   /// Mapping from global declaration IDs to the module in which the
502   /// declaration resides.
503   GlobalDeclMapType GlobalDeclMap;
504
505   using FileOffset = std::pair<ModuleFile *, uint64_t>;
506   using FileOffsetsTy = SmallVector<FileOffset, 2>;
507   using DeclUpdateOffsetsMap =
508       llvm::DenseMap<serialization::DeclID, FileOffsetsTy>;
509
510   /// Declarations that have modifications residing in a later file
511   /// in the chain.
512   DeclUpdateOffsetsMap DeclUpdateOffsets;
513
514   struct PendingUpdateRecord {
515     Decl *D;
516     serialization::GlobalDeclID ID;
517
518     // Whether the declaration was just deserialized.
519     bool JustLoaded;
520
521     PendingUpdateRecord(serialization::GlobalDeclID ID, Decl *D,
522                         bool JustLoaded)
523         : D(D), ID(ID), JustLoaded(JustLoaded) {}
524   };
525
526   /// Declaration updates for already-loaded declarations that we need
527   /// to apply once we finish processing an import.
528   llvm::SmallVector<PendingUpdateRecord, 16> PendingUpdateRecords;
529
530   enum class PendingFakeDefinitionKind { NotFake, Fake, FakeLoaded };
531
532   /// The DefinitionData pointers that we faked up for class definitions
533   /// that we needed but hadn't loaded yet.
534   llvm::DenseMap<void *, PendingFakeDefinitionKind> PendingFakeDefinitionData;
535
536   /// Exception specification updates that have been loaded but not yet
537   /// propagated across the relevant redeclaration chain. The map key is the
538   /// canonical declaration (used only for deduplication) and the value is a
539   /// declaration that has an exception specification.
540   llvm::SmallMapVector<Decl *, FunctionDecl *, 4> PendingExceptionSpecUpdates;
541
542   /// Declarations that have been imported and have typedef names for
543   /// linkage purposes.
544   llvm::DenseMap<std::pair<DeclContext *, IdentifierInfo *>, NamedDecl *>
545       ImportedTypedefNamesForLinkage;
546
547   /// Mergeable declaration contexts that have anonymous declarations
548   /// within them, and those anonymous declarations.
549   llvm::DenseMap<Decl*, llvm::SmallVector<NamedDecl*, 2>>
550     AnonymousDeclarationsForMerging;
551
552   struct FileDeclsInfo {
553     ModuleFile *Mod = nullptr;
554     ArrayRef<serialization::LocalDeclID> Decls;
555
556     FileDeclsInfo() = default;
557     FileDeclsInfo(ModuleFile *Mod, ArrayRef<serialization::LocalDeclID> Decls)
558         : Mod(Mod), Decls(Decls) {}
559   };
560
561   /// Map from a FileID to the file-level declarations that it contains.
562   llvm::DenseMap<FileID, FileDeclsInfo> FileDeclIDs;
563
564   /// An array of lexical contents of a declaration context, as a sequence of
565   /// Decl::Kind, DeclID pairs.
566   using LexicalContents = ArrayRef<llvm::support::unaligned_uint32_t>;
567
568   /// Map from a DeclContext to its lexical contents.
569   llvm::DenseMap<const DeclContext*, std::pair<ModuleFile*, LexicalContents>>
570       LexicalDecls;
571
572   /// Map from the TU to its lexical contents from each module file.
573   std::vector<std::pair<ModuleFile*, LexicalContents>> TULexicalDecls;
574
575   /// Map from a DeclContext to its lookup tables.
576   llvm::DenseMap<const DeclContext *,
577                  serialization::reader::DeclContextLookupTable> Lookups;
578
579   // Updates for visible decls can occur for other contexts than just the
580   // TU, and when we read those update records, the actual context may not
581   // be available yet, so have this pending map using the ID as a key. It
582   // will be realized when the context is actually loaded.
583   struct PendingVisibleUpdate {
584     ModuleFile *Mod;
585     const unsigned char *Data;
586   };
587   using DeclContextVisibleUpdates = SmallVector<PendingVisibleUpdate, 1>;
588
589   /// Updates to the visible declarations of declaration contexts that
590   /// haven't been loaded yet.
591   llvm::DenseMap<serialization::DeclID, DeclContextVisibleUpdates>
592       PendingVisibleUpdates;
593
594   /// The set of C++ or Objective-C classes that have forward
595   /// declarations that have not yet been linked to their definitions.
596   llvm::SmallPtrSet<Decl *, 4> PendingDefinitions;
597
598   using PendingBodiesMap =
599       llvm::MapVector<Decl *, uint64_t,
600                       llvm::SmallDenseMap<Decl *, unsigned, 4>,
601                       SmallVector<std::pair<Decl *, uint64_t>, 4>>;
602
603   /// Functions or methods that have bodies that will be attached.
604   PendingBodiesMap PendingBodies;
605
606   /// Definitions for which we have added merged definitions but not yet
607   /// performed deduplication.
608   llvm::SetVector<NamedDecl *> PendingMergedDefinitionsToDeduplicate;
609
610   /// Read the record that describes the lexical contents of a DC.
611   bool ReadLexicalDeclContextStorage(ModuleFile &M,
612                                      llvm::BitstreamCursor &Cursor,
613                                      uint64_t Offset, DeclContext *DC);
614
615   /// Read the record that describes the visible contents of a DC.
616   bool ReadVisibleDeclContextStorage(ModuleFile &M,
617                                      llvm::BitstreamCursor &Cursor,
618                                      uint64_t Offset, serialization::DeclID ID);
619
620   /// A vector containing identifiers that have already been
621   /// loaded.
622   ///
623   /// If the pointer at index I is non-NULL, then it refers to the
624   /// IdentifierInfo for the identifier with ID=I+1 that has already
625   /// been loaded.
626   std::vector<IdentifierInfo *> IdentifiersLoaded;
627
628   using GlobalIdentifierMapType =
629       ContinuousRangeMap<serialization::IdentID, ModuleFile *, 4>;
630
631   /// Mapping from global identifier IDs to the module in which the
632   /// identifier resides along with the offset that should be added to the
633   /// global identifier ID to produce a local ID.
634   GlobalIdentifierMapType GlobalIdentifierMap;
635
636   /// A vector containing macros that have already been
637   /// loaded.
638   ///
639   /// If the pointer at index I is non-NULL, then it refers to the
640   /// MacroInfo for the identifier with ID=I+1 that has already
641   /// been loaded.
642   std::vector<MacroInfo *> MacrosLoaded;
643
644   using LoadedMacroInfo =
645       std::pair<IdentifierInfo *, serialization::SubmoduleID>;
646
647   /// A set of #undef directives that we have loaded; used to
648   /// deduplicate the same #undef information coming from multiple module
649   /// files.
650   llvm::DenseSet<LoadedMacroInfo> LoadedUndefs;
651
652   using GlobalMacroMapType =
653       ContinuousRangeMap<serialization::MacroID, ModuleFile *, 4>;
654
655   /// Mapping from global macro IDs to the module in which the
656   /// macro resides along with the offset that should be added to the
657   /// global macro ID to produce a local ID.
658   GlobalMacroMapType GlobalMacroMap;
659
660   /// A vector containing submodules that have already been loaded.
661   ///
662   /// This vector is indexed by the Submodule ID (-1). NULL submodule entries
663   /// indicate that the particular submodule ID has not yet been loaded.
664   SmallVector<Module *, 2> SubmodulesLoaded;
665
666   using GlobalSubmoduleMapType =
667       ContinuousRangeMap<serialization::SubmoduleID, ModuleFile *, 4>;
668
669   /// Mapping from global submodule IDs to the module file in which the
670   /// submodule resides along with the offset that should be added to the
671   /// global submodule ID to produce a local ID.
672   GlobalSubmoduleMapType GlobalSubmoduleMap;
673
674   /// A set of hidden declarations.
675   using HiddenNames = SmallVector<Decl *, 2>;
676   using HiddenNamesMapType = llvm::DenseMap<Module *, HiddenNames>;
677
678   /// A mapping from each of the hidden submodules to the deserialized
679   /// declarations in that submodule that could be made visible.
680   HiddenNamesMapType HiddenNamesMap;
681
682   /// A module import, export, or conflict that hasn't yet been resolved.
683   struct UnresolvedModuleRef {
684     /// The file in which this module resides.
685     ModuleFile *File;
686
687     /// The module that is importing or exporting.
688     Module *Mod;
689
690     /// The kind of module reference.
691     enum { Import, Export, Conflict } Kind;
692
693     /// The local ID of the module that is being exported.
694     unsigned ID;
695
696     /// Whether this is a wildcard export.
697     unsigned IsWildcard : 1;
698
699     /// String data.
700     StringRef String;
701   };
702
703   /// The set of module imports and exports that still need to be
704   /// resolved.
705   SmallVector<UnresolvedModuleRef, 2> UnresolvedModuleRefs;
706
707   /// A vector containing selectors that have already been loaded.
708   ///
709   /// This vector is indexed by the Selector ID (-1). NULL selector
710   /// entries indicate that the particular selector ID has not yet
711   /// been loaded.
712   SmallVector<Selector, 16> SelectorsLoaded;
713
714   using GlobalSelectorMapType =
715       ContinuousRangeMap<serialization::SelectorID, ModuleFile *, 4>;
716
717   /// Mapping from global selector IDs to the module in which the
718   /// global selector ID to produce a local ID.
719   GlobalSelectorMapType GlobalSelectorMap;
720
721   /// The generation number of the last time we loaded data from the
722   /// global method pool for this selector.
723   llvm::DenseMap<Selector, unsigned> SelectorGeneration;
724
725   /// Whether a selector is out of date. We mark a selector as out of date
726   /// if we load another module after the method pool entry was pulled in.
727   llvm::DenseMap<Selector, bool> SelectorOutOfDate;
728
729   struct PendingMacroInfo {
730     ModuleFile *M;
731     uint64_t MacroDirectivesOffset;
732
733     PendingMacroInfo(ModuleFile *M, uint64_t MacroDirectivesOffset)
734         : M(M), MacroDirectivesOffset(MacroDirectivesOffset) {}
735   };
736
737   using PendingMacroIDsMap =
738       llvm::MapVector<IdentifierInfo *, SmallVector<PendingMacroInfo, 2>>;
739
740   /// Mapping from identifiers that have a macro history to the global
741   /// IDs have not yet been deserialized to the global IDs of those macros.
742   PendingMacroIDsMap PendingMacroIDs;
743
744   using GlobalPreprocessedEntityMapType =
745       ContinuousRangeMap<unsigned, ModuleFile *, 4>;
746
747   /// Mapping from global preprocessing entity IDs to the module in
748   /// which the preprocessed entity resides along with the offset that should be
749   /// added to the global preprocessing entity ID to produce a local ID.
750   GlobalPreprocessedEntityMapType GlobalPreprocessedEntityMap;
751
752   using GlobalSkippedRangeMapType =
753       ContinuousRangeMap<unsigned, ModuleFile *, 4>;
754
755   /// Mapping from global skipped range base IDs to the module in which
756   /// the skipped ranges reside.
757   GlobalSkippedRangeMapType GlobalSkippedRangeMap;
758
759   /// \name CodeGen-relevant special data
760   /// Fields containing data that is relevant to CodeGen.
761   //@{
762
763   /// The IDs of all declarations that fulfill the criteria of
764   /// "interesting" decls.
765   ///
766   /// This contains the data loaded from all EAGERLY_DESERIALIZED_DECLS blocks
767   /// in the chain. The referenced declarations are deserialized and passed to
768   /// the consumer eagerly.
769   SmallVector<uint64_t, 16> EagerlyDeserializedDecls;
770
771   /// The IDs of all tentative definitions stored in the chain.
772   ///
773   /// Sema keeps track of all tentative definitions in a TU because it has to
774   /// complete them and pass them on to CodeGen. Thus, tentative definitions in
775   /// the PCH chain must be eagerly deserialized.
776   SmallVector<uint64_t, 16> TentativeDefinitions;
777
778   /// The IDs of all CXXRecordDecls stored in the chain whose VTables are
779   /// used.
780   ///
781   /// CodeGen has to emit VTables for these records, so they have to be eagerly
782   /// deserialized.
783   SmallVector<uint64_t, 64> VTableUses;
784
785   /// A snapshot of the pending instantiations in the chain.
786   ///
787   /// This record tracks the instantiations that Sema has to perform at the
788   /// end of the TU. It consists of a pair of values for every pending
789   /// instantiation where the first value is the ID of the decl and the second
790   /// is the instantiation location.
791   SmallVector<uint64_t, 64> PendingInstantiations;
792
793   //@}
794
795   /// \name DiagnosticsEngine-relevant special data
796   /// Fields containing data that is used for generating diagnostics
797   //@{
798
799   /// A snapshot of Sema's unused file-scoped variable tracking, for
800   /// generating warnings.
801   SmallVector<uint64_t, 16> UnusedFileScopedDecls;
802
803   /// A list of all the delegating constructors we've seen, to diagnose
804   /// cycles.
805   SmallVector<uint64_t, 4> DelegatingCtorDecls;
806
807   /// Method selectors used in a @selector expression. Used for
808   /// implementation of -Wselector.
809   SmallVector<uint64_t, 64> ReferencedSelectorsData;
810
811   /// A snapshot of Sema's weak undeclared identifier tracking, for
812   /// generating warnings.
813   SmallVector<uint64_t, 64> WeakUndeclaredIdentifiers;
814
815   /// The IDs of type aliases for ext_vectors that exist in the chain.
816   ///
817   /// Used by Sema for finding sugared names for ext_vectors in diagnostics.
818   SmallVector<uint64_t, 4> ExtVectorDecls;
819
820   //@}
821
822   /// \name Sema-relevant special data
823   /// Fields containing data that is used for semantic analysis
824   //@{
825
826   /// The IDs of all potentially unused typedef names in the chain.
827   ///
828   /// Sema tracks these to emit warnings.
829   SmallVector<uint64_t, 16> UnusedLocalTypedefNameCandidates;
830
831   /// Our current depth in #pragma cuda force_host_device begin/end
832   /// macros.
833   unsigned ForceCUDAHostDeviceDepth = 0;
834
835   /// The IDs of the declarations Sema stores directly.
836   ///
837   /// Sema tracks a few important decls, such as namespace std, directly.
838   SmallVector<uint64_t, 4> SemaDeclRefs;
839
840   /// The IDs of the types ASTContext stores directly.
841   ///
842   /// The AST context tracks a few important types, such as va_list, directly.
843   SmallVector<uint64_t, 16> SpecialTypes;
844
845   /// The IDs of CUDA-specific declarations ASTContext stores directly.
846   ///
847   /// The AST context tracks a few important decls, currently cudaConfigureCall,
848   /// directly.
849   SmallVector<uint64_t, 2> CUDASpecialDeclRefs;
850
851   /// The floating point pragma option settings.
852   SmallVector<uint64_t, 1> FPPragmaOptions;
853
854   /// The pragma clang optimize location (if the pragma state is "off").
855   SourceLocation OptimizeOffPragmaLocation;
856
857   /// The PragmaMSStructKind pragma ms_struct state if set, or -1.
858   int PragmaMSStructState = -1;
859
860   /// The PragmaMSPointersToMembersKind pragma pointers_to_members state.
861   int PragmaMSPointersToMembersState = -1;
862   SourceLocation PointersToMembersPragmaLocation;
863
864   /// The pragma pack state.
865   Optional<unsigned> PragmaPackCurrentValue;
866   SourceLocation PragmaPackCurrentLocation;
867   struct PragmaPackStackEntry {
868     unsigned Value;
869     SourceLocation Location;
870     SourceLocation PushLocation;
871     StringRef SlotLabel;
872   };
873   llvm::SmallVector<PragmaPackStackEntry, 2> PragmaPackStack;
874   llvm::SmallVector<std::string, 2> PragmaPackStrings;
875
876   /// The OpenCL extension settings.
877   OpenCLOptions OpenCLExtensions;
878
879   /// Extensions required by an OpenCL type.
880   llvm::DenseMap<const Type *, std::set<std::string>> OpenCLTypeExtMap;
881
882   /// Extensions required by an OpenCL declaration.
883   llvm::DenseMap<const Decl *, std::set<std::string>> OpenCLDeclExtMap;
884
885   /// A list of the namespaces we've seen.
886   SmallVector<uint64_t, 4> KnownNamespaces;
887
888   /// A list of undefined decls with internal linkage followed by the
889   /// SourceLocation of a matching ODR-use.
890   SmallVector<uint64_t, 8> UndefinedButUsed;
891
892   /// Delete expressions to analyze at the end of translation unit.
893   SmallVector<uint64_t, 8> DelayedDeleteExprs;
894
895   // A list of late parsed template function data.
896   SmallVector<uint64_t, 1> LateParsedTemplates;
897
898 public:
899   struct ImportedSubmodule {
900     serialization::SubmoduleID ID;
901     SourceLocation ImportLoc;
902
903     ImportedSubmodule(serialization::SubmoduleID ID, SourceLocation ImportLoc)
904         : ID(ID), ImportLoc(ImportLoc) {}
905   };
906
907 private:
908   /// A list of modules that were imported by precompiled headers or
909   /// any other non-module AST file.
910   SmallVector<ImportedSubmodule, 2> ImportedModules;
911   //@}
912
913   /// The system include root to be used when loading the
914   /// precompiled header.
915   std::string isysroot;
916
917   /// Whether to disable the normal validation performed on precompiled
918   /// headers when they are loaded.
919   bool DisableValidation;
920
921   /// Whether to accept an AST file with compiler errors.
922   bool AllowASTWithCompilerErrors;
923
924   /// Whether to accept an AST file that has a different configuration
925   /// from the current compiler instance.
926   bool AllowConfigurationMismatch;
927
928   /// Whether validate system input files.
929   bool ValidateSystemInputs;
930
931   /// Whether we are allowed to use the global module index.
932   bool UseGlobalIndex;
933
934   /// Whether we have tried loading the global module index yet.
935   bool TriedLoadingGlobalIndex = false;
936
937   ///Whether we are currently processing update records.
938   bool ProcessingUpdateRecords = false;
939
940   using SwitchCaseMapTy = llvm::DenseMap<unsigned, SwitchCase *>;
941
942   /// Mapping from switch-case IDs in the chain to switch-case statements
943   ///
944   /// Statements usually don't have IDs, but switch cases need them, so that the
945   /// switch statement can refer to them.
946   SwitchCaseMapTy SwitchCaseStmts;
947
948   SwitchCaseMapTy *CurrSwitchCaseStmts;
949
950   /// The number of source location entries de-serialized from
951   /// the PCH file.
952   unsigned NumSLocEntriesRead = 0;
953
954   /// The number of source location entries in the chain.
955   unsigned TotalNumSLocEntries = 0;
956
957   /// The number of statements (and expressions) de-serialized
958   /// from the chain.
959   unsigned NumStatementsRead = 0;
960
961   /// The total number of statements (and expressions) stored
962   /// in the chain.
963   unsigned TotalNumStatements = 0;
964
965   /// The number of macros de-serialized from the chain.
966   unsigned NumMacrosRead = 0;
967
968   /// The total number of macros stored in the chain.
969   unsigned TotalNumMacros = 0;
970
971   /// The number of lookups into identifier tables.
972   unsigned NumIdentifierLookups = 0;
973
974   /// The number of lookups into identifier tables that succeed.
975   unsigned NumIdentifierLookupHits = 0;
976
977   /// The number of selectors that have been read.
978   unsigned NumSelectorsRead = 0;
979
980   /// The number of method pool entries that have been read.
981   unsigned NumMethodPoolEntriesRead = 0;
982
983   /// The number of times we have looked up a selector in the method
984   /// pool.
985   unsigned NumMethodPoolLookups = 0;
986
987   /// The number of times we have looked up a selector in the method
988   /// pool and found something.
989   unsigned NumMethodPoolHits = 0;
990
991   /// The number of times we have looked up a selector in the method
992   /// pool within a specific module.
993   unsigned NumMethodPoolTableLookups = 0;
994
995   /// The number of times we have looked up a selector in the method
996   /// pool within a specific module and found something.
997   unsigned NumMethodPoolTableHits = 0;
998
999   /// The total number of method pool entries in the selector table.
1000   unsigned TotalNumMethodPoolEntries = 0;
1001
1002   /// Number of lexical decl contexts read/total.
1003   unsigned NumLexicalDeclContextsRead = 0, TotalLexicalDeclContexts = 0;
1004
1005   /// Number of visible decl contexts read/total.
1006   unsigned NumVisibleDeclContextsRead = 0, TotalVisibleDeclContexts = 0;
1007
1008   /// Total size of modules, in bits, currently loaded
1009   uint64_t TotalModulesSizeInBits = 0;
1010
1011   /// Number of Decl/types that are currently deserializing.
1012   unsigned NumCurrentElementsDeserializing = 0;
1013
1014   /// Set true while we are in the process of passing deserialized
1015   /// "interesting" decls to consumer inside FinishedDeserializing().
1016   /// This is used as a guard to avoid recursively repeating the process of
1017   /// passing decls to consumer.
1018   bool PassingDeclsToConsumer = false;
1019
1020   /// The set of identifiers that were read while the AST reader was
1021   /// (recursively) loading declarations.
1022   ///
1023   /// The declarations on the identifier chain for these identifiers will be
1024   /// loaded once the recursive loading has completed.
1025   llvm::MapVector<IdentifierInfo *, SmallVector<uint32_t, 4>>
1026     PendingIdentifierInfos;
1027
1028   /// The set of lookup results that we have faked in order to support
1029   /// merging of partially deserialized decls but that we have not yet removed.
1030   llvm::SmallMapVector<IdentifierInfo *, SmallVector<NamedDecl*, 2>, 16>
1031     PendingFakeLookupResults;
1032
1033   /// The generation number of each identifier, which keeps track of
1034   /// the last time we loaded information about this identifier.
1035   llvm::DenseMap<IdentifierInfo *, unsigned> IdentifierGeneration;
1036
1037   class InterestingDecl {
1038     Decl *D;
1039     bool DeclHasPendingBody;
1040
1041   public:
1042     InterestingDecl(Decl *D, bool HasBody)
1043         : D(D), DeclHasPendingBody(HasBody) {}
1044
1045     Decl *getDecl() { return D; }
1046
1047     /// Whether the declaration has a pending body.
1048     bool hasPendingBody() { return DeclHasPendingBody; }
1049   };
1050
1051   /// Contains declarations and definitions that could be
1052   /// "interesting" to the ASTConsumer, when we get that AST consumer.
1053   ///
1054   /// "Interesting" declarations are those that have data that may
1055   /// need to be emitted, such as inline function definitions or
1056   /// Objective-C protocols.
1057   std::deque<InterestingDecl> PotentiallyInterestingDecls;
1058
1059   /// The list of redeclaration chains that still need to be
1060   /// reconstructed, and the local offset to the corresponding list
1061   /// of redeclarations.
1062   SmallVector<std::pair<Decl *, uint64_t>, 16> PendingDeclChains;
1063
1064   /// The list of canonical declarations whose redeclaration chains
1065   /// need to be marked as incomplete once we're done deserializing things.
1066   SmallVector<Decl *, 16> PendingIncompleteDeclChains;
1067
1068   /// The Decl IDs for the Sema/Lexical DeclContext of a Decl that has
1069   /// been loaded but its DeclContext was not set yet.
1070   struct PendingDeclContextInfo {
1071     Decl *D;
1072     serialization::GlobalDeclID SemaDC;
1073     serialization::GlobalDeclID LexicalDC;
1074   };
1075
1076   /// The set of Decls that have been loaded but their DeclContexts are
1077   /// not set yet.
1078   ///
1079   /// The DeclContexts for these Decls will be set once recursive loading has
1080   /// been completed.
1081   std::deque<PendingDeclContextInfo> PendingDeclContextInfos;
1082
1083   /// The set of NamedDecls that have been loaded, but are members of a
1084   /// context that has been merged into another context where the corresponding
1085   /// declaration is either missing or has not yet been loaded.
1086   ///
1087   /// We will check whether the corresponding declaration is in fact missing
1088   /// once recursing loading has been completed.
1089   llvm::SmallVector<NamedDecl *, 16> PendingOdrMergeChecks;
1090
1091   using DataPointers =
1092       std::pair<CXXRecordDecl *, struct CXXRecordDecl::DefinitionData *>;
1093
1094   /// Record definitions in which we found an ODR violation.
1095   llvm::SmallDenseMap<CXXRecordDecl *, llvm::SmallVector<DataPointers, 2>, 2>
1096       PendingOdrMergeFailures;
1097
1098   /// Function definitions in which we found an ODR violation.
1099   llvm::SmallDenseMap<FunctionDecl *, llvm::SmallVector<FunctionDecl *, 2>, 2>
1100       PendingFunctionOdrMergeFailures;
1101
1102   /// Enum definitions in which we found an ODR violation.
1103   llvm::SmallDenseMap<EnumDecl *, llvm::SmallVector<EnumDecl *, 2>, 2>
1104       PendingEnumOdrMergeFailures;
1105
1106   /// DeclContexts in which we have diagnosed an ODR violation.
1107   llvm::SmallPtrSet<DeclContext*, 2> DiagnosedOdrMergeFailures;
1108
1109   /// The set of Objective-C categories that have been deserialized
1110   /// since the last time the declaration chains were linked.
1111   llvm::SmallPtrSet<ObjCCategoryDecl *, 16> CategoriesDeserialized;
1112
1113   /// The set of Objective-C class definitions that have already been
1114   /// loaded, for which we will need to check for categories whenever a new
1115   /// module is loaded.
1116   SmallVector<ObjCInterfaceDecl *, 16> ObjCClassesLoaded;
1117
1118   using KeyDeclsMap =
1119       llvm::DenseMap<Decl *, SmallVector<serialization::DeclID, 2>>;
1120
1121   /// A mapping from canonical declarations to the set of global
1122   /// declaration IDs for key declaration that have been merged with that
1123   /// canonical declaration. A key declaration is a formerly-canonical
1124   /// declaration whose module did not import any other key declaration for that
1125   /// entity. These are the IDs that we use as keys when finding redecl chains.
1126   KeyDeclsMap KeyDecls;
1127
1128   /// A mapping from DeclContexts to the semantic DeclContext that we
1129   /// are treating as the definition of the entity. This is used, for instance,
1130   /// when merging implicit instantiations of class templates across modules.
1131   llvm::DenseMap<DeclContext *, DeclContext *> MergedDeclContexts;
1132
1133   /// A mapping from canonical declarations of enums to their canonical
1134   /// definitions. Only populated when using modules in C++.
1135   llvm::DenseMap<EnumDecl *, EnumDecl *> EnumDefinitions;
1136
1137   /// When reading a Stmt tree, Stmt operands are placed in this stack.
1138   SmallVector<Stmt *, 16> StmtStack;
1139
1140   /// What kind of records we are reading.
1141   enum ReadingKind {
1142     Read_None, Read_Decl, Read_Type, Read_Stmt
1143   };
1144
1145   /// What kind of records we are reading.
1146   ReadingKind ReadingKind = Read_None;
1147
1148   /// RAII object to change the reading kind.
1149   class ReadingKindTracker {
1150     ASTReader &Reader;
1151     enum ReadingKind PrevKind;
1152
1153   public:
1154     ReadingKindTracker(enum ReadingKind newKind, ASTReader &reader)
1155         : Reader(reader), PrevKind(Reader.ReadingKind) {
1156       Reader.ReadingKind = newKind;
1157     }
1158
1159     ReadingKindTracker(const ReadingKindTracker &) = delete;
1160     ReadingKindTracker &operator=(const ReadingKindTracker &) = delete;
1161     ~ReadingKindTracker() { Reader.ReadingKind = PrevKind; }
1162   };
1163
1164   /// RAII object to mark the start of processing updates.
1165   class ProcessingUpdatesRAIIObj {
1166     ASTReader &Reader;
1167     bool PrevState;
1168
1169   public:
1170     ProcessingUpdatesRAIIObj(ASTReader &reader)
1171         : Reader(reader), PrevState(Reader.ProcessingUpdateRecords) {
1172       Reader.ProcessingUpdateRecords = true;
1173     }
1174
1175     ProcessingUpdatesRAIIObj(const ProcessingUpdatesRAIIObj &) = delete;
1176     ProcessingUpdatesRAIIObj &
1177     operator=(const ProcessingUpdatesRAIIObj &) = delete;
1178     ~ProcessingUpdatesRAIIObj() { Reader.ProcessingUpdateRecords = PrevState; }
1179   };
1180
1181   /// Suggested contents of the predefines buffer, after this
1182   /// PCH file has been processed.
1183   ///
1184   /// In most cases, this string will be empty, because the predefines
1185   /// buffer computed to build the PCH file will be identical to the
1186   /// predefines buffer computed from the command line. However, when
1187   /// there are differences that the PCH reader can work around, this
1188   /// predefines buffer may contain additional definitions.
1189   std::string SuggestedPredefines;
1190
1191   llvm::DenseMap<const Decl *, bool> DefinitionSource;
1192
1193   /// Reads a statement from the specified cursor.
1194   Stmt *ReadStmtFromStream(ModuleFile &F);
1195
1196   struct InputFileInfo {
1197     std::string Filename;
1198     off_t StoredSize;
1199     time_t StoredTime;
1200     bool Overridden;
1201     bool Transient;
1202     bool TopLevelModuleMap;
1203   };
1204
1205   /// Reads the stored information about an input file.
1206   InputFileInfo readInputFileInfo(ModuleFile &F, unsigned ID);
1207
1208   /// Retrieve the file entry and 'overridden' bit for an input
1209   /// file in the given module file.
1210   serialization::InputFile getInputFile(ModuleFile &F, unsigned ID,
1211                                         bool Complain = true);
1212
1213 public:
1214   void ResolveImportedPath(ModuleFile &M, std::string &Filename);
1215   static void ResolveImportedPath(std::string &Filename, StringRef Prefix);
1216
1217   /// Returns the first key declaration for the given declaration. This
1218   /// is one that is formerly-canonical (or still canonical) and whose module
1219   /// did not import any other key declaration of the entity.
1220   Decl *getKeyDeclaration(Decl *D) {
1221     D = D->getCanonicalDecl();
1222     if (D->isFromASTFile())
1223       return D;
1224
1225     auto I = KeyDecls.find(D);
1226     if (I == KeyDecls.end() || I->second.empty())
1227       return D;
1228     return GetExistingDecl(I->second[0]);
1229   }
1230   const Decl *getKeyDeclaration(const Decl *D) {
1231     return getKeyDeclaration(const_cast<Decl*>(D));
1232   }
1233
1234   /// Run a callback on each imported key declaration of \p D.
1235   template <typename Fn>
1236   void forEachImportedKeyDecl(const Decl *D, Fn Visit) {
1237     D = D->getCanonicalDecl();
1238     if (D->isFromASTFile())
1239       Visit(D);
1240
1241     auto It = KeyDecls.find(const_cast<Decl*>(D));
1242     if (It != KeyDecls.end())
1243       for (auto ID : It->second)
1244         Visit(GetExistingDecl(ID));
1245   }
1246
1247   /// Get the loaded lookup tables for \p Primary, if any.
1248   const serialization::reader::DeclContextLookupTable *
1249   getLoadedLookupTables(DeclContext *Primary) const;
1250
1251 private:
1252   struct ImportedModule {
1253     ModuleFile *Mod;
1254     ModuleFile *ImportedBy;
1255     SourceLocation ImportLoc;
1256
1257     ImportedModule(ModuleFile *Mod,
1258                    ModuleFile *ImportedBy,
1259                    SourceLocation ImportLoc)
1260         : Mod(Mod), ImportedBy(ImportedBy), ImportLoc(ImportLoc) {}
1261   };
1262
1263   ASTReadResult ReadASTCore(StringRef FileName, ModuleKind Type,
1264                             SourceLocation ImportLoc, ModuleFile *ImportedBy,
1265                             SmallVectorImpl<ImportedModule> &Loaded,
1266                             off_t ExpectedSize, time_t ExpectedModTime,
1267                             ASTFileSignature ExpectedSignature,
1268                             unsigned ClientLoadCapabilities);
1269   ASTReadResult ReadControlBlock(ModuleFile &F,
1270                                  SmallVectorImpl<ImportedModule> &Loaded,
1271                                  const ModuleFile *ImportedBy,
1272                                  unsigned ClientLoadCapabilities);
1273   static ASTReadResult ReadOptionsBlock(
1274       llvm::BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
1275       bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
1276       std::string &SuggestedPredefines);
1277
1278   /// Read the unhashed control block.
1279   ///
1280   /// This has no effect on \c F.Stream, instead creating a fresh cursor from
1281   /// \c F.Data and reading ahead.
1282   ASTReadResult readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
1283                                          unsigned ClientLoadCapabilities);
1284
1285   static ASTReadResult
1286   readUnhashedControlBlockImpl(ModuleFile *F, llvm::StringRef StreamData,
1287                                unsigned ClientLoadCapabilities,
1288                                bool AllowCompatibleConfigurationMismatch,
1289                                ASTReaderListener *Listener,
1290                                bool ValidateDiagnosticOptions);
1291
1292   ASTReadResult ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities);
1293   ASTReadResult ReadExtensionBlock(ModuleFile &F);
1294   void ReadModuleOffsetMap(ModuleFile &F) const;
1295   bool ParseLineTable(ModuleFile &F, const RecordData &Record);
1296   bool ReadSourceManagerBlock(ModuleFile &F);
1297   llvm::BitstreamCursor &SLocCursorForID(int ID);
1298   SourceLocation getImportLocation(ModuleFile *F);
1299   ASTReadResult ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
1300                                        const ModuleFile *ImportedBy,
1301                                        unsigned ClientLoadCapabilities);
1302   ASTReadResult ReadSubmoduleBlock(ModuleFile &F,
1303                                    unsigned ClientLoadCapabilities);
1304   static bool ParseLanguageOptions(const RecordData &Record, bool Complain,
1305                                    ASTReaderListener &Listener,
1306                                    bool AllowCompatibleDifferences);
1307   static bool ParseTargetOptions(const RecordData &Record, bool Complain,
1308                                  ASTReaderListener &Listener,
1309                                  bool AllowCompatibleDifferences);
1310   static bool ParseDiagnosticOptions(const RecordData &Record, bool Complain,
1311                                      ASTReaderListener &Listener);
1312   static bool ParseFileSystemOptions(const RecordData &Record, bool Complain,
1313                                      ASTReaderListener &Listener);
1314   static bool ParseHeaderSearchOptions(const RecordData &Record, bool Complain,
1315                                        ASTReaderListener &Listener);
1316   static bool ParsePreprocessorOptions(const RecordData &Record, bool Complain,
1317                                        ASTReaderListener &Listener,
1318                                        std::string &SuggestedPredefines);
1319
1320   struct RecordLocation {
1321     ModuleFile *F;
1322     uint64_t Offset;
1323
1324     RecordLocation(ModuleFile *M, uint64_t O) : F(M), Offset(O) {}
1325   };
1326
1327   QualType readTypeRecord(unsigned Index);
1328   void readExceptionSpec(ModuleFile &ModuleFile,
1329                          SmallVectorImpl<QualType> &ExceptionStorage,
1330                          FunctionProtoType::ExceptionSpecInfo &ESI,
1331                          const RecordData &Record, unsigned &Index);
1332   RecordLocation TypeCursorForIndex(unsigned Index);
1333   void LoadedDecl(unsigned Index, Decl *D);
1334   Decl *ReadDeclRecord(serialization::DeclID ID);
1335   void markIncompleteDeclChain(Decl *Canon);
1336
1337   /// Returns the most recent declaration of a declaration (which must be
1338   /// of a redeclarable kind) that is either local or has already been loaded
1339   /// merged into its redecl chain.
1340   Decl *getMostRecentExistingDecl(Decl *D);
1341
1342   RecordLocation DeclCursorForID(serialization::DeclID ID,
1343                                  SourceLocation &Location);
1344   void loadDeclUpdateRecords(PendingUpdateRecord &Record);
1345   void loadPendingDeclChain(Decl *D, uint64_t LocalOffset);
1346   void loadObjCCategories(serialization::GlobalDeclID ID, ObjCInterfaceDecl *D,
1347                           unsigned PreviousGeneration = 0);
1348
1349   RecordLocation getLocalBitOffset(uint64_t GlobalOffset);
1350   uint64_t getGlobalBitOffset(ModuleFile &M, uint32_t LocalOffset);
1351
1352   /// Returns the first preprocessed entity ID that begins or ends after
1353   /// \arg Loc.
1354   serialization::PreprocessedEntityID
1355   findPreprocessedEntity(SourceLocation Loc, bool EndsAfter) const;
1356
1357   /// Find the next module that contains entities and return the ID
1358   /// of the first entry.
1359   ///
1360   /// \param SLocMapI points at a chunk of a module that contains no
1361   /// preprocessed entities or the entities it contains are not the
1362   /// ones we are looking for.
1363   serialization::PreprocessedEntityID
1364     findNextPreprocessedEntity(
1365                         GlobalSLocOffsetMapType::const_iterator SLocMapI) const;
1366
1367   /// Returns (ModuleFile, Local index) pair for \p GlobalIndex of a
1368   /// preprocessed entity.
1369   std::pair<ModuleFile *, unsigned>
1370     getModulePreprocessedEntity(unsigned GlobalIndex);
1371
1372   /// Returns (begin, end) pair for the preprocessed entities of a
1373   /// particular module.
1374   llvm::iterator_range<PreprocessingRecord::iterator>
1375   getModulePreprocessedEntities(ModuleFile &Mod) const;
1376
1377 public:
1378   class ModuleDeclIterator
1379       : public llvm::iterator_adaptor_base<
1380             ModuleDeclIterator, const serialization::LocalDeclID *,
1381             std::random_access_iterator_tag, const Decl *, ptrdiff_t,
1382             const Decl *, const Decl *> {
1383     ASTReader *Reader = nullptr;
1384     ModuleFile *Mod = nullptr;
1385
1386   public:
1387     ModuleDeclIterator() : iterator_adaptor_base(nullptr) {}
1388
1389     ModuleDeclIterator(ASTReader *Reader, ModuleFile *Mod,
1390                        const serialization::LocalDeclID *Pos)
1391         : iterator_adaptor_base(Pos), Reader(Reader), Mod(Mod) {}
1392
1393     value_type operator*() const {
1394       return Reader->GetDecl(Reader->getGlobalDeclID(*Mod, *I));
1395     }
1396
1397     value_type operator->() const { return **this; }
1398
1399     bool operator==(const ModuleDeclIterator &RHS) const {
1400       assert(Reader == RHS.Reader && Mod == RHS.Mod);
1401       return I == RHS.I;
1402     }
1403   };
1404
1405   llvm::iterator_range<ModuleDeclIterator>
1406   getModuleFileLevelDecls(ModuleFile &Mod);
1407
1408 private:
1409   void PassInterestingDeclsToConsumer();
1410   void PassInterestingDeclToConsumer(Decl *D);
1411
1412   void finishPendingActions();
1413   void diagnoseOdrViolations();
1414
1415   void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name);
1416
1417   void addPendingDeclContextInfo(Decl *D,
1418                                  serialization::GlobalDeclID SemaDC,
1419                                  serialization::GlobalDeclID LexicalDC) {
1420     assert(D);
1421     PendingDeclContextInfo Info = { D, SemaDC, LexicalDC };
1422     PendingDeclContextInfos.push_back(Info);
1423   }
1424
1425   /// Produce an error diagnostic and return true.
1426   ///
1427   /// This routine should only be used for fatal errors that have to
1428   /// do with non-routine failures (e.g., corrupted AST file).
1429   void Error(StringRef Msg) const;
1430   void Error(unsigned DiagID, StringRef Arg1 = StringRef(),
1431              StringRef Arg2 = StringRef()) const;
1432
1433 public:
1434   /// Load the AST file and validate its contents against the given
1435   /// Preprocessor.
1436   ///
1437   /// \param PP the preprocessor associated with the context in which this
1438   /// precompiled header will be loaded.
1439   ///
1440   /// \param Context the AST context that this precompiled header will be
1441   /// loaded into, if any.
1442   ///
1443   /// \param PCHContainerRdr the PCHContainerOperations to use for loading and
1444   /// creating modules.
1445   ///
1446   /// \param Extensions the list of module file extensions that can be loaded
1447   /// from the AST files.
1448   ///
1449   /// \param isysroot If non-NULL, the system include path specified by the
1450   /// user. This is only used with relocatable PCH files. If non-NULL,
1451   /// a relocatable PCH file will use the default path "/".
1452   ///
1453   /// \param DisableValidation If true, the AST reader will suppress most
1454   /// of its regular consistency checking, allowing the use of precompiled
1455   /// headers that cannot be determined to be compatible.
1456   ///
1457   /// \param AllowASTWithCompilerErrors If true, the AST reader will accept an
1458   /// AST file the was created out of an AST with compiler errors,
1459   /// otherwise it will reject it.
1460   ///
1461   /// \param AllowConfigurationMismatch If true, the AST reader will not check
1462   /// for configuration differences between the AST file and the invocation.
1463   ///
1464   /// \param ValidateSystemInputs If true, the AST reader will validate
1465   /// system input files in addition to user input files. This is only
1466   /// meaningful if \p DisableValidation is false.
1467   ///
1468   /// \param UseGlobalIndex If true, the AST reader will try to load and use
1469   /// the global module index.
1470   ///
1471   /// \param ReadTimer If non-null, a timer used to track the time spent
1472   /// deserializing.
1473   ASTReader(Preprocessor &PP, ASTContext *Context,
1474             const PCHContainerReader &PCHContainerRdr,
1475             ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
1476             StringRef isysroot = "", bool DisableValidation = false,
1477             bool AllowASTWithCompilerErrors = false,
1478             bool AllowConfigurationMismatch = false,
1479             bool ValidateSystemInputs = false, bool UseGlobalIndex = true,
1480             std::unique_ptr<llvm::Timer> ReadTimer = {});
1481   ASTReader(const ASTReader &) = delete;
1482   ASTReader &operator=(const ASTReader &) = delete;
1483   ~ASTReader() override;
1484
1485   SourceManager &getSourceManager() const { return SourceMgr; }
1486   FileManager &getFileManager() const { return FileMgr; }
1487   DiagnosticsEngine &getDiags() const { return Diags; }
1488
1489   /// Flags that indicate what kind of AST loading failures the client
1490   /// of the AST reader can directly handle.
1491   ///
1492   /// When a client states that it can handle a particular kind of failure,
1493   /// the AST reader will not emit errors when producing that kind of failure.
1494   enum LoadFailureCapabilities {
1495     /// The client can't handle any AST loading failures.
1496     ARR_None = 0,
1497
1498     /// The client can handle an AST file that cannot load because it
1499     /// is missing.
1500     ARR_Missing = 0x1,
1501
1502     /// The client can handle an AST file that cannot load because it
1503     /// is out-of-date relative to its input files.
1504     ARR_OutOfDate = 0x2,
1505
1506     /// The client can handle an AST file that cannot load because it
1507     /// was built with a different version of Clang.
1508     ARR_VersionMismatch = 0x4,
1509
1510     /// The client can handle an AST file that cannot load because it's
1511     /// compiled configuration doesn't match that of the context it was
1512     /// loaded into.
1513     ARR_ConfigurationMismatch = 0x8
1514   };
1515
1516   /// Load the AST file designated by the given file name.
1517   ///
1518   /// \param FileName The name of the AST file to load.
1519   ///
1520   /// \param Type The kind of AST being loaded, e.g., PCH, module, main file,
1521   /// or preamble.
1522   ///
1523   /// \param ImportLoc the location where the module file will be considered as
1524   /// imported from. For non-module AST types it should be invalid.
1525   ///
1526   /// \param ClientLoadCapabilities The set of client load-failure
1527   /// capabilities, represented as a bitset of the enumerators of
1528   /// LoadFailureCapabilities.
1529   ///
1530   /// \param Imported optional out-parameter to append the list of modules
1531   /// that were imported by precompiled headers or any other non-module AST file
1532   ASTReadResult ReadAST(StringRef FileName, ModuleKind Type,
1533                         SourceLocation ImportLoc,
1534                         unsigned ClientLoadCapabilities,
1535                         SmallVectorImpl<ImportedSubmodule> *Imported = nullptr);
1536
1537   /// Make the entities in the given module and any of its (non-explicit)
1538   /// submodules visible to name lookup.
1539   ///
1540   /// \param Mod The module whose names should be made visible.
1541   ///
1542   /// \param NameVisibility The level of visibility to give the names in the
1543   /// module.  Visibility can only be increased over time.
1544   ///
1545   /// \param ImportLoc The location at which the import occurs.
1546   void makeModuleVisible(Module *Mod,
1547                          Module::NameVisibilityKind NameVisibility,
1548                          SourceLocation ImportLoc);
1549
1550   /// Make the names within this set of hidden names visible.
1551   void makeNamesVisible(const HiddenNames &Names, Module *Owner);
1552
1553   /// Note that MergedDef is a redefinition of the canonical definition
1554   /// Def, so Def should be visible whenever MergedDef is.
1555   void mergeDefinitionVisibility(NamedDecl *Def, NamedDecl *MergedDef);
1556
1557   /// Take the AST callbacks listener.
1558   std::unique_ptr<ASTReaderListener> takeListener() {
1559     return std::move(Listener);
1560   }
1561
1562   /// Set the AST callbacks listener.
1563   void setListener(std::unique_ptr<ASTReaderListener> Listener) {
1564     this->Listener = std::move(Listener);
1565   }
1566
1567   /// Add an AST callback listener.
1568   ///
1569   /// Takes ownership of \p L.
1570   void addListener(std::unique_ptr<ASTReaderListener> L) {
1571     if (Listener)
1572       L = llvm::make_unique<ChainedASTReaderListener>(std::move(L),
1573                                                       std::move(Listener));
1574     Listener = std::move(L);
1575   }
1576
1577   /// RAII object to temporarily add an AST callback listener.
1578   class ListenerScope {
1579     ASTReader &Reader;
1580     bool Chained = false;
1581
1582   public:
1583     ListenerScope(ASTReader &Reader, std::unique_ptr<ASTReaderListener> L)
1584         : Reader(Reader) {
1585       auto Old = Reader.takeListener();
1586       if (Old) {
1587         Chained = true;
1588         L = llvm::make_unique<ChainedASTReaderListener>(std::move(L),
1589                                                         std::move(Old));
1590       }
1591       Reader.setListener(std::move(L));
1592     }
1593
1594     ~ListenerScope() {
1595       auto New = Reader.takeListener();
1596       if (Chained)
1597         Reader.setListener(static_cast<ChainedASTReaderListener *>(New.get())
1598                                ->takeSecond());
1599     }
1600   };
1601
1602   /// Set the AST deserialization listener.
1603   void setDeserializationListener(ASTDeserializationListener *Listener,
1604                                   bool TakeOwnership = false);
1605
1606   /// Get the AST deserialization listener.
1607   ASTDeserializationListener *getDeserializationListener() {
1608     return DeserializationListener;
1609   }
1610
1611   /// Determine whether this AST reader has a global index.
1612   bool hasGlobalIndex() const { return (bool)GlobalIndex; }
1613
1614   /// Return global module index.
1615   GlobalModuleIndex *getGlobalIndex() { return GlobalIndex.get(); }
1616
1617   /// Reset reader for a reload try.
1618   void resetForReload() { TriedLoadingGlobalIndex = false; }
1619
1620   /// Attempts to load the global index.
1621   ///
1622   /// \returns true if loading the global index has failed for any reason.
1623   bool loadGlobalIndex();
1624
1625   /// Determine whether we tried to load the global index, but failed,
1626   /// e.g., because it is out-of-date or does not exist.
1627   bool isGlobalIndexUnavailable() const;
1628
1629   /// Initializes the ASTContext
1630   void InitializeContext();
1631
1632   /// Update the state of Sema after loading some additional modules.
1633   void UpdateSema();
1634
1635   /// Add in-memory (virtual file) buffer.
1636   void addInMemoryBuffer(StringRef &FileName,
1637                          std::unique_ptr<llvm::MemoryBuffer> Buffer) {
1638     ModuleMgr.addInMemoryBuffer(FileName, std::move(Buffer));
1639   }
1640
1641   /// Finalizes the AST reader's state before writing an AST file to
1642   /// disk.
1643   ///
1644   /// This operation may undo temporary state in the AST that should not be
1645   /// emitted.
1646   void finalizeForWriting();
1647
1648   /// Retrieve the module manager.
1649   ModuleManager &getModuleManager() { return ModuleMgr; }
1650
1651   /// Retrieve the preprocessor.
1652   Preprocessor &getPreprocessor() const { return PP; }
1653
1654   /// Retrieve the name of the original source file name for the primary
1655   /// module file.
1656   StringRef getOriginalSourceFile() {
1657     return ModuleMgr.getPrimaryModule().OriginalSourceFileName;
1658   }
1659
1660   /// Retrieve the name of the original source file name directly from
1661   /// the AST file, without actually loading the AST file.
1662   static std::string
1663   getOriginalSourceFile(const std::string &ASTFileName, FileManager &FileMgr,
1664                         const PCHContainerReader &PCHContainerRdr,
1665                         DiagnosticsEngine &Diags);
1666
1667   /// Read the control block for the named AST file.
1668   ///
1669   /// \returns true if an error occurred, false otherwise.
1670   static bool
1671   readASTFileControlBlock(StringRef Filename, FileManager &FileMgr,
1672                           const PCHContainerReader &PCHContainerRdr,
1673                           bool FindModuleFileExtensions,
1674                           ASTReaderListener &Listener,
1675                           bool ValidateDiagnosticOptions);
1676
1677   /// Determine whether the given AST file is acceptable to load into a
1678   /// translation unit with the given language and target options.
1679   static bool isAcceptableASTFile(StringRef Filename, FileManager &FileMgr,
1680                                   const PCHContainerReader &PCHContainerRdr,
1681                                   const LangOptions &LangOpts,
1682                                   const TargetOptions &TargetOpts,
1683                                   const PreprocessorOptions &PPOpts,
1684                                   StringRef ExistingModuleCachePath);
1685
1686   /// Returns the suggested contents of the predefines buffer,
1687   /// which contains a (typically-empty) subset of the predefines
1688   /// build prior to including the precompiled header.
1689   const std::string &getSuggestedPredefines() { return SuggestedPredefines; }
1690
1691   /// Read a preallocated preprocessed entity from the external source.
1692   ///
1693   /// \returns null if an error occurred that prevented the preprocessed
1694   /// entity from being loaded.
1695   PreprocessedEntity *ReadPreprocessedEntity(unsigned Index) override;
1696
1697   /// Returns a pair of [Begin, End) indices of preallocated
1698   /// preprocessed entities that \p Range encompasses.
1699   std::pair<unsigned, unsigned>
1700       findPreprocessedEntitiesInRange(SourceRange Range) override;
1701
1702   /// Optionally returns true or false if the preallocated preprocessed
1703   /// entity with index \p Index came from file \p FID.
1704   Optional<bool> isPreprocessedEntityInFileID(unsigned Index,
1705                                               FileID FID) override;
1706
1707   /// Read a preallocated skipped range from the external source.
1708   SourceRange ReadSkippedRange(unsigned Index) override;
1709
1710   /// Read the header file information for the given file entry.
1711   HeaderFileInfo GetHeaderFileInfo(const FileEntry *FE) override;
1712
1713   void ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag);
1714
1715   /// Returns the number of source locations found in the chain.
1716   unsigned getTotalNumSLocs() const {
1717     return TotalNumSLocEntries;
1718   }
1719
1720   /// Returns the number of identifiers found in the chain.
1721   unsigned getTotalNumIdentifiers() const {
1722     return static_cast<unsigned>(IdentifiersLoaded.size());
1723   }
1724
1725   /// Returns the number of macros found in the chain.
1726   unsigned getTotalNumMacros() const {
1727     return static_cast<unsigned>(MacrosLoaded.size());
1728   }
1729
1730   /// Returns the number of types found in the chain.
1731   unsigned getTotalNumTypes() const {
1732     return static_cast<unsigned>(TypesLoaded.size());
1733   }
1734
1735   /// Returns the number of declarations found in the chain.
1736   unsigned getTotalNumDecls() const {
1737     return static_cast<unsigned>(DeclsLoaded.size());
1738   }
1739
1740   /// Returns the number of submodules known.
1741   unsigned getTotalNumSubmodules() const {
1742     return static_cast<unsigned>(SubmodulesLoaded.size());
1743   }
1744
1745   /// Returns the number of selectors found in the chain.
1746   unsigned getTotalNumSelectors() const {
1747     return static_cast<unsigned>(SelectorsLoaded.size());
1748   }
1749
1750   /// Returns the number of preprocessed entities known to the AST
1751   /// reader.
1752   unsigned getTotalNumPreprocessedEntities() const {
1753     unsigned Result = 0;
1754     for (const auto &M : ModuleMgr)
1755       Result += M.NumPreprocessedEntities;
1756     return Result;
1757   }
1758
1759   /// Reads a TemplateArgumentLocInfo appropriate for the
1760   /// given TemplateArgument kind.
1761   TemplateArgumentLocInfo
1762   GetTemplateArgumentLocInfo(ModuleFile &F, TemplateArgument::ArgKind Kind,
1763                              const RecordData &Record, unsigned &Idx);
1764
1765   /// Reads a TemplateArgumentLoc.
1766   TemplateArgumentLoc
1767   ReadTemplateArgumentLoc(ModuleFile &F,
1768                           const RecordData &Record, unsigned &Idx);
1769
1770   const ASTTemplateArgumentListInfo*
1771   ReadASTTemplateArgumentListInfo(ModuleFile &F,
1772                                   const RecordData &Record, unsigned &Index);
1773
1774   /// Reads a declarator info from the given record.
1775   TypeSourceInfo *GetTypeSourceInfo(ModuleFile &F,
1776                                     const RecordData &Record, unsigned &Idx);
1777
1778   /// Raad the type locations for the given TInfo.
1779   void ReadTypeLoc(ModuleFile &F, const RecordData &Record, unsigned &Idx,
1780                    TypeLoc TL);
1781
1782   /// Resolve a type ID into a type, potentially building a new
1783   /// type.
1784   QualType GetType(serialization::TypeID ID);
1785
1786   /// Resolve a local type ID within a given AST file into a type.
1787   QualType getLocalType(ModuleFile &F, unsigned LocalID);
1788
1789   /// Map a local type ID within a given AST file into a global type ID.
1790   serialization::TypeID getGlobalTypeID(ModuleFile &F, unsigned LocalID) const;
1791
1792   /// Read a type from the current position in the given record, which
1793   /// was read from the given AST file.
1794   QualType readType(ModuleFile &F, const RecordData &Record, unsigned &Idx) {
1795     if (Idx >= Record.size())
1796       return {};
1797
1798     return getLocalType(F, Record[Idx++]);
1799   }
1800
1801   /// Map from a local declaration ID within a given module to a
1802   /// global declaration ID.
1803   serialization::DeclID getGlobalDeclID(ModuleFile &F,
1804                                       serialization::LocalDeclID LocalID) const;
1805
1806   /// Returns true if global DeclID \p ID originated from module \p M.
1807   bool isDeclIDFromModule(serialization::GlobalDeclID ID, ModuleFile &M) const;
1808
1809   /// Retrieve the module file that owns the given declaration, or NULL
1810   /// if the declaration is not from a module file.
1811   ModuleFile *getOwningModuleFile(const Decl *D);
1812
1813   /// Get the best name we know for the module that owns the given
1814   /// declaration, or an empty string if the declaration is not from a module.
1815   std::string getOwningModuleNameForDiagnostic(const Decl *D);
1816
1817   /// Returns the source location for the decl \p ID.
1818   SourceLocation getSourceLocationForDeclID(serialization::GlobalDeclID ID);
1819
1820   /// Resolve a declaration ID into a declaration, potentially
1821   /// building a new declaration.
1822   Decl *GetDecl(serialization::DeclID ID);
1823   Decl *GetExternalDecl(uint32_t ID) override;
1824
1825   /// Resolve a declaration ID into a declaration. Return 0 if it's not
1826   /// been loaded yet.
1827   Decl *GetExistingDecl(serialization::DeclID ID);
1828
1829   /// Reads a declaration with the given local ID in the given module.
1830   Decl *GetLocalDecl(ModuleFile &F, uint32_t LocalID) {
1831     return GetDecl(getGlobalDeclID(F, LocalID));
1832   }
1833
1834   /// Reads a declaration with the given local ID in the given module.
1835   ///
1836   /// \returns The requested declaration, casted to the given return type.
1837   template<typename T>
1838   T *GetLocalDeclAs(ModuleFile &F, uint32_t LocalID) {
1839     return cast_or_null<T>(GetLocalDecl(F, LocalID));
1840   }
1841
1842   /// Map a global declaration ID into the declaration ID used to
1843   /// refer to this declaration within the given module fule.
1844   ///
1845   /// \returns the global ID of the given declaration as known in the given
1846   /// module file.
1847   serialization::DeclID
1848   mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
1849                                   serialization::DeclID GlobalID);
1850
1851   /// Reads a declaration ID from the given position in a record in the
1852   /// given module.
1853   ///
1854   /// \returns The declaration ID read from the record, adjusted to a global ID.
1855   serialization::DeclID ReadDeclID(ModuleFile &F, const RecordData &Record,
1856                                    unsigned &Idx);
1857
1858   /// Reads a declaration from the given position in a record in the
1859   /// given module.
1860   Decl *ReadDecl(ModuleFile &F, const RecordData &R, unsigned &I) {
1861     return GetDecl(ReadDeclID(F, R, I));
1862   }
1863
1864   /// Reads a declaration from the given position in a record in the
1865   /// given module.
1866   ///
1867   /// \returns The declaration read from this location, casted to the given
1868   /// result type.
1869   template<typename T>
1870   T *ReadDeclAs(ModuleFile &F, const RecordData &R, unsigned &I) {
1871     return cast_or_null<T>(GetDecl(ReadDeclID(F, R, I)));
1872   }
1873
1874   /// If any redeclarations of \p D have been imported since it was
1875   /// last checked, this digs out those redeclarations and adds them to the
1876   /// redeclaration chain for \p D.
1877   void CompleteRedeclChain(const Decl *D) override;
1878
1879   CXXBaseSpecifier *GetExternalCXXBaseSpecifiers(uint64_t Offset) override;
1880
1881   /// Resolve the offset of a statement into a statement.
1882   ///
1883   /// This operation will read a new statement from the external
1884   /// source each time it is called, and is meant to be used via a
1885   /// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
1886   Stmt *GetExternalDeclStmt(uint64_t Offset) override;
1887
1888   /// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1889   /// specified cursor.  Read the abbreviations that are at the top of the block
1890   /// and then leave the cursor pointing into the block.
1891   static bool ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor, unsigned BlockID);
1892
1893   /// Finds all the visible declarations with a given name.
1894   /// The current implementation of this method just loads the entire
1895   /// lookup table as unmaterialized references.
1896   bool FindExternalVisibleDeclsByName(const DeclContext *DC,
1897                                       DeclarationName Name) override;
1898
1899   /// Read all of the declarations lexically stored in a
1900   /// declaration context.
1901   ///
1902   /// \param DC The declaration context whose declarations will be
1903   /// read.
1904   ///
1905   /// \param IsKindWeWant A predicate indicating which declaration kinds
1906   /// we are interested in.
1907   ///
1908   /// \param Decls Vector that will contain the declarations loaded
1909   /// from the external source. The caller is responsible for merging
1910   /// these declarations with any declarations already stored in the
1911   /// declaration context.
1912   void
1913   FindExternalLexicalDecls(const DeclContext *DC,
1914                            llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
1915                            SmallVectorImpl<Decl *> &Decls) override;
1916
1917   /// Get the decls that are contained in a file in the Offset/Length
1918   /// range. \p Length can be 0 to indicate a point at \p Offset instead of
1919   /// a range.
1920   void FindFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
1921                            SmallVectorImpl<Decl *> &Decls) override;
1922
1923   /// Notify ASTReader that we started deserialization of
1924   /// a decl or type so until FinishedDeserializing is called there may be
1925   /// decls that are initializing. Must be paired with FinishedDeserializing.
1926   void StartedDeserializing() override;
1927
1928   /// Notify ASTReader that we finished the deserialization of
1929   /// a decl or type. Must be paired with StartedDeserializing.
1930   void FinishedDeserializing() override;
1931
1932   /// Function that will be invoked when we begin parsing a new
1933   /// translation unit involving this external AST source.
1934   ///
1935   /// This function will provide all of the external definitions to
1936   /// the ASTConsumer.
1937   void StartTranslationUnit(ASTConsumer *Consumer) override;
1938
1939   /// Print some statistics about AST usage.
1940   void PrintStats() override;
1941
1942   /// Dump information about the AST reader to standard error.
1943   void dump();
1944
1945   /// Return the amount of memory used by memory buffers, breaking down
1946   /// by heap-backed versus mmap'ed memory.
1947   void getMemoryBufferSizes(MemoryBufferSizes &sizes) const override;
1948
1949   /// Initialize the semantic source with the Sema instance
1950   /// being used to perform semantic analysis on the abstract syntax
1951   /// tree.
1952   void InitializeSema(Sema &S) override;
1953
1954   /// Inform the semantic consumer that Sema is no longer available.
1955   void ForgetSema() override { SemaObj = nullptr; }
1956
1957   /// Retrieve the IdentifierInfo for the named identifier.
1958   ///
1959   /// This routine builds a new IdentifierInfo for the given identifier. If any
1960   /// declarations with this name are visible from translation unit scope, their
1961   /// declarations will be deserialized and introduced into the declaration
1962   /// chain of the identifier.
1963   IdentifierInfo *get(StringRef Name) override;
1964
1965   /// Retrieve an iterator into the set of all identifiers
1966   /// in all loaded AST files.
1967   IdentifierIterator *getIdentifiers() override;
1968
1969   /// Load the contents of the global method pool for a given
1970   /// selector.
1971   void ReadMethodPool(Selector Sel) override;
1972
1973   /// Load the contents of the global method pool for a given
1974   /// selector if necessary.
1975   void updateOutOfDateSelector(Selector Sel) override;
1976
1977   /// Load the set of namespaces that are known to the external source,
1978   /// which will be used during typo correction.
1979   void ReadKnownNamespaces(
1980                          SmallVectorImpl<NamespaceDecl *> &Namespaces) override;
1981
1982   void ReadUndefinedButUsed(
1983       llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) override;
1984
1985   void ReadMismatchingDeleteExpressions(llvm::MapVector<
1986       FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
1987                                             Exprs) override;
1988
1989   void ReadTentativeDefinitions(
1990                             SmallVectorImpl<VarDecl *> &TentativeDefs) override;
1991
1992   void ReadUnusedFileScopedDecls(
1993                        SmallVectorImpl<const DeclaratorDecl *> &Decls) override;
1994
1995   void ReadDelegatingConstructors(
1996                          SmallVectorImpl<CXXConstructorDecl *> &Decls) override;
1997
1998   void ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) override;
1999
2000   void ReadUnusedLocalTypedefNameCandidates(
2001       llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) override;
2002
2003   void ReadReferencedSelectors(
2004            SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) override;
2005
2006   void ReadWeakUndeclaredIdentifiers(
2007            SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WI) override;
2008
2009   void ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) override;
2010
2011   void ReadPendingInstantiations(
2012                   SmallVectorImpl<std::pair<ValueDecl *,
2013                                             SourceLocation>> &Pending) override;
2014
2015   void ReadLateParsedTemplates(
2016       llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
2017           &LPTMap) override;
2018
2019   /// Load a selector from disk, registering its ID if it exists.
2020   void LoadSelector(Selector Sel);
2021
2022   void SetIdentifierInfo(unsigned ID, IdentifierInfo *II);
2023   void SetGloballyVisibleDecls(IdentifierInfo *II,
2024                                const SmallVectorImpl<uint32_t> &DeclIDs,
2025                                SmallVectorImpl<Decl *> *Decls = nullptr);
2026
2027   /// Report a diagnostic.
2028   DiagnosticBuilder Diag(unsigned DiagID) const;
2029
2030   /// Report a diagnostic.
2031   DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) const;
2032
2033   IdentifierInfo *DecodeIdentifierInfo(serialization::IdentifierID ID);
2034
2035   IdentifierInfo *GetIdentifierInfo(ModuleFile &M, const RecordData &Record,
2036                                     unsigned &Idx) {
2037     return DecodeIdentifierInfo(getGlobalIdentifierID(M, Record[Idx++]));
2038   }
2039
2040   IdentifierInfo *GetIdentifier(serialization::IdentifierID ID) override {
2041     // Note that we are loading an identifier.
2042     Deserializing AnIdentifier(this);
2043
2044     return DecodeIdentifierInfo(ID);
2045   }
2046
2047   IdentifierInfo *getLocalIdentifier(ModuleFile &M, unsigned LocalID);
2048
2049   serialization::IdentifierID getGlobalIdentifierID(ModuleFile &M,
2050                                                     unsigned LocalID);
2051
2052   void resolvePendingMacro(IdentifierInfo *II, const PendingMacroInfo &PMInfo);
2053
2054   /// Retrieve the macro with the given ID.
2055   MacroInfo *getMacro(serialization::MacroID ID);
2056
2057   /// Retrieve the global macro ID corresponding to the given local
2058   /// ID within the given module file.
2059   serialization::MacroID getGlobalMacroID(ModuleFile &M, unsigned LocalID);
2060
2061   /// Read the source location entry with index ID.
2062   bool ReadSLocEntry(int ID) override;
2063
2064   /// Retrieve the module import location and module name for the
2065   /// given source manager entry ID.
2066   std::pair<SourceLocation, StringRef> getModuleImportLoc(int ID) override;
2067
2068   /// Retrieve the global submodule ID given a module and its local ID
2069   /// number.
2070   serialization::SubmoduleID
2071   getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID);
2072
2073   /// Retrieve the submodule that corresponds to a global submodule ID.
2074   ///
2075   Module *getSubmodule(serialization::SubmoduleID GlobalID);
2076
2077   /// Retrieve the module that corresponds to the given module ID.
2078   ///
2079   /// Note: overrides method in ExternalASTSource
2080   Module *getModule(unsigned ID) override;
2081
2082   bool DeclIsFromPCHWithObjectFile(const Decl *D) override;
2083
2084   /// Retrieve the module file with a given local ID within the specified
2085   /// ModuleFile.
2086   ModuleFile *getLocalModuleFile(ModuleFile &M, unsigned ID);
2087
2088   /// Get an ID for the given module file.
2089   unsigned getModuleFileID(ModuleFile *M);
2090
2091   /// Return a descriptor for the corresponding module.
2092   llvm::Optional<ASTSourceDescriptor> getSourceDescriptor(unsigned ID) override;
2093
2094   ExtKind hasExternalDefinitions(const Decl *D) override;
2095
2096   /// Retrieve a selector from the given module with its local ID
2097   /// number.
2098   Selector getLocalSelector(ModuleFile &M, unsigned LocalID);
2099
2100   Selector DecodeSelector(serialization::SelectorID Idx);
2101
2102   Selector GetExternalSelector(serialization::SelectorID ID) override;
2103   uint32_t GetNumExternalSelectors() override;
2104
2105   Selector ReadSelector(ModuleFile &M, const RecordData &Record, unsigned &Idx) {
2106     return getLocalSelector(M, Record[Idx++]);
2107   }
2108
2109   /// Retrieve the global selector ID that corresponds to this
2110   /// the local selector ID in a given module.
2111   serialization::SelectorID getGlobalSelectorID(ModuleFile &F,
2112                                                 unsigned LocalID) const;
2113
2114   /// Read a declaration name.
2115   DeclarationName ReadDeclarationName(ModuleFile &F,
2116                                       const RecordData &Record, unsigned &Idx);
2117   void ReadDeclarationNameLoc(ModuleFile &F,
2118                               DeclarationNameLoc &DNLoc, DeclarationName Name,
2119                               const RecordData &Record, unsigned &Idx);
2120   void ReadDeclarationNameInfo(ModuleFile &F, DeclarationNameInfo &NameInfo,
2121                                const RecordData &Record, unsigned &Idx);
2122
2123   void ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
2124                          const RecordData &Record, unsigned &Idx);
2125
2126   NestedNameSpecifier *ReadNestedNameSpecifier(ModuleFile &F,
2127                                                const RecordData &Record,
2128                                                unsigned &Idx);
2129
2130   NestedNameSpecifierLoc ReadNestedNameSpecifierLoc(ModuleFile &F,
2131                                                     const RecordData &Record,
2132                                                     unsigned &Idx);
2133
2134   /// Read a template name.
2135   TemplateName ReadTemplateName(ModuleFile &F, const RecordData &Record,
2136                                 unsigned &Idx);
2137
2138   /// Read a template argument.
2139   TemplateArgument ReadTemplateArgument(ModuleFile &F, const RecordData &Record,
2140                                         unsigned &Idx,
2141                                         bool Canonicalize = false);
2142
2143   /// Read a template parameter list.
2144   TemplateParameterList *ReadTemplateParameterList(ModuleFile &F,
2145                                                    const RecordData &Record,
2146                                                    unsigned &Idx);
2147
2148   /// Read a template argument array.
2149   void ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
2150                                 ModuleFile &F, const RecordData &Record,
2151                                 unsigned &Idx, bool Canonicalize = false);
2152
2153   /// Read a UnresolvedSet structure.
2154   void ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
2155                          const RecordData &Record, unsigned &Idx);
2156
2157   /// Read a C++ base specifier.
2158   CXXBaseSpecifier ReadCXXBaseSpecifier(ModuleFile &F,
2159                                         const RecordData &Record,unsigned &Idx);
2160
2161   /// Read a CXXCtorInitializer array.
2162   CXXCtorInitializer **
2163   ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
2164                           unsigned &Idx);
2165
2166   /// Read the contents of a CXXCtorInitializer array.
2167   CXXCtorInitializer **GetExternalCXXCtorInitializers(uint64_t Offset) override;
2168
2169   /// Read a source location from raw form and return it in its
2170   /// originating module file's source location space.
2171   SourceLocation ReadUntranslatedSourceLocation(uint32_t Raw) const {
2172     return SourceLocation::getFromRawEncoding((Raw >> 1) | (Raw << 31));
2173   }
2174
2175   /// Read a source location from raw form.
2176   SourceLocation ReadSourceLocation(ModuleFile &ModuleFile, uint32_t Raw) const {
2177     SourceLocation Loc = ReadUntranslatedSourceLocation(Raw);
2178     return TranslateSourceLocation(ModuleFile, Loc);
2179   }
2180
2181   /// Translate a source location from another module file's source
2182   /// location space into ours.
2183   SourceLocation TranslateSourceLocation(ModuleFile &ModuleFile,
2184                                          SourceLocation Loc) const {
2185     if (!ModuleFile.ModuleOffsetMap.empty())
2186       ReadModuleOffsetMap(ModuleFile);
2187     assert(ModuleFile.SLocRemap.find(Loc.getOffset()) !=
2188                ModuleFile.SLocRemap.end() &&
2189            "Cannot find offset to remap.");
2190     int Remap = ModuleFile.SLocRemap.find(Loc.getOffset())->second;
2191     return Loc.getLocWithOffset(Remap);
2192   }
2193
2194   /// Read a source location.
2195   SourceLocation ReadSourceLocation(ModuleFile &ModuleFile,
2196                                     const RecordDataImpl &Record,
2197                                     unsigned &Idx) {
2198     return ReadSourceLocation(ModuleFile, Record[Idx++]);
2199   }
2200
2201   /// Read a source range.
2202   SourceRange ReadSourceRange(ModuleFile &F,
2203                               const RecordData &Record, unsigned &Idx);
2204
2205   /// Read an integral value
2206   llvm::APInt ReadAPInt(const RecordData &Record, unsigned &Idx);
2207
2208   /// Read a signed integral value
2209   llvm::APSInt ReadAPSInt(const RecordData &Record, unsigned &Idx);
2210
2211   /// Read a floating-point value
2212   llvm::APFloat ReadAPFloat(const RecordData &Record,
2213                             const llvm::fltSemantics &Sem, unsigned &Idx);
2214
2215   // Read a string
2216   static std::string ReadString(const RecordData &Record, unsigned &Idx);
2217
2218   // Skip a string
2219   static void SkipString(const RecordData &Record, unsigned &Idx) {
2220     Idx += Record[Idx] + 1;
2221   }
2222
2223   // Read a path
2224   std::string ReadPath(ModuleFile &F, const RecordData &Record, unsigned &Idx);
2225
2226   // Skip a path
2227   static void SkipPath(const RecordData &Record, unsigned &Idx) {
2228     SkipString(Record, Idx);
2229   }
2230
2231   /// Read a version tuple.
2232   static VersionTuple ReadVersionTuple(const RecordData &Record, unsigned &Idx);
2233
2234   CXXTemporary *ReadCXXTemporary(ModuleFile &F, const RecordData &Record,
2235                                  unsigned &Idx);
2236
2237   /// Reads attributes from the current stream position.
2238   void ReadAttributes(ASTRecordReader &Record, AttrVec &Attrs);
2239
2240   /// Reads a statement.
2241   Stmt *ReadStmt(ModuleFile &F);
2242
2243   /// Reads an expression.
2244   Expr *ReadExpr(ModuleFile &F);
2245
2246   /// Reads a sub-statement operand during statement reading.
2247   Stmt *ReadSubStmt() {
2248     assert(ReadingKind == Read_Stmt &&
2249            "Should be called only during statement reading!");
2250     // Subexpressions are stored from last to first, so the next Stmt we need
2251     // is at the back of the stack.
2252     assert(!StmtStack.empty() && "Read too many sub-statements!");
2253     return StmtStack.pop_back_val();
2254   }
2255
2256   /// Reads a sub-expression operand during statement reading.
2257   Expr *ReadSubExpr();
2258
2259   /// Reads a token out of a record.
2260   Token ReadToken(ModuleFile &M, const RecordDataImpl &Record, unsigned &Idx);
2261
2262   /// Reads the macro record located at the given offset.
2263   MacroInfo *ReadMacroRecord(ModuleFile &F, uint64_t Offset);
2264
2265   /// Determine the global preprocessed entity ID that corresponds to
2266   /// the given local ID within the given module.
2267   serialization::PreprocessedEntityID
2268   getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const;
2269
2270   /// Add a macro to deserialize its macro directive history.
2271   ///
2272   /// \param II The name of the macro.
2273   /// \param M The module file.
2274   /// \param MacroDirectivesOffset Offset of the serialized macro directive
2275   /// history.
2276   void addPendingMacro(IdentifierInfo *II, ModuleFile *M,
2277                        uint64_t MacroDirectivesOffset);
2278
2279   /// Read the set of macros defined by this external macro source.
2280   void ReadDefinedMacros() override;
2281
2282   /// Update an out-of-date identifier.
2283   void updateOutOfDateIdentifier(IdentifierInfo &II) override;
2284
2285   /// Note that this identifier is up-to-date.
2286   void markIdentifierUpToDate(IdentifierInfo *II);
2287
2288   /// Load all external visible decls in the given DeclContext.
2289   void completeVisibleDeclsMap(const DeclContext *DC) override;
2290
2291   /// Retrieve the AST context that this AST reader supplements.
2292   ASTContext &getContext() {
2293     assert(ContextObj && "requested AST context when not loading AST");
2294     return *ContextObj;
2295   }
2296
2297   // Contains the IDs for declarations that were requested before we have
2298   // access to a Sema object.
2299   SmallVector<uint64_t, 16> PreloadedDeclIDs;
2300
2301   /// Retrieve the semantic analysis object used to analyze the
2302   /// translation unit in which the precompiled header is being
2303   /// imported.
2304   Sema *getSema() { return SemaObj; }
2305
2306   /// Get the identifier resolver used for name lookup / updates
2307   /// in the translation unit scope. We have one of these even if we don't
2308   /// have a Sema object.
2309   IdentifierResolver &getIdResolver();
2310
2311   /// Retrieve the identifier table associated with the
2312   /// preprocessor.
2313   IdentifierTable &getIdentifierTable();
2314
2315   /// Record that the given ID maps to the given switch-case
2316   /// statement.
2317   void RecordSwitchCaseID(SwitchCase *SC, unsigned ID);
2318
2319   /// Retrieve the switch-case statement with the given ID.
2320   SwitchCase *getSwitchCaseWithID(unsigned ID);
2321
2322   void ClearSwitchCaseIDs();
2323
2324   /// Cursors for comments blocks.
2325   SmallVector<std::pair<llvm::BitstreamCursor,
2326                         serialization::ModuleFile *>, 8> CommentsCursors;
2327
2328   /// Loads comments ranges.
2329   void ReadComments() override;
2330
2331   /// Visit all the input files of the given module file.
2332   void visitInputFiles(serialization::ModuleFile &MF,
2333                        bool IncludeSystem, bool Complain,
2334           llvm::function_ref<void(const serialization::InputFile &IF,
2335                                   bool isSystem)> Visitor);
2336
2337   /// Visit all the top-level module maps loaded when building the given module
2338   /// file.
2339   void visitTopLevelModuleMaps(serialization::ModuleFile &MF,
2340                                llvm::function_ref<
2341                                    void(const FileEntry *)> Visitor);
2342
2343   bool isProcessingUpdateRecords() { return ProcessingUpdateRecords; }
2344 };
2345
2346 /// An object for streaming information from a record.
2347 class ASTRecordReader {
2348   using ModuleFile = serialization::ModuleFile;
2349
2350   ASTReader *Reader;
2351   ModuleFile *F;
2352   unsigned Idx = 0;
2353   ASTReader::RecordData Record;
2354
2355   using RecordData = ASTReader::RecordData;
2356   using RecordDataImpl = ASTReader::RecordDataImpl;
2357
2358 public:
2359   /// Construct an ASTRecordReader that uses the default encoding scheme.
2360   ASTRecordReader(ASTReader &Reader, ModuleFile &F) : Reader(&Reader), F(&F) {}
2361
2362   /// Reads a record with id AbbrevID from Cursor, resetting the
2363   /// internal state.
2364   unsigned readRecord(llvm::BitstreamCursor &Cursor, unsigned AbbrevID);
2365
2366   /// Is this a module file for a module (rather than a PCH or similar).
2367   bool isModule() const { return F->isModule(); }
2368
2369   /// Retrieve the AST context that this AST reader supplements.
2370   ASTContext &getContext() { return Reader->getContext(); }
2371
2372   /// The current position in this record.
2373   unsigned getIdx() const { return Idx; }
2374
2375   /// The length of this record.
2376   size_t size() const { return Record.size(); }
2377
2378   /// An arbitrary index in this record.
2379   const uint64_t &operator[](size_t N) { return Record[N]; }
2380
2381   /// The last element in this record.
2382   const uint64_t &back() const { return Record.back(); }
2383
2384   /// Returns the current value in this record, and advances to the
2385   /// next value.
2386   const uint64_t &readInt() { return Record[Idx++]; }
2387
2388   /// Returns the current value in this record, without advancing.
2389   const uint64_t &peekInt() { return Record[Idx]; }
2390
2391   /// Skips the specified number of values.
2392   void skipInts(unsigned N) { Idx += N; }
2393
2394   /// Retrieve the global submodule ID its local ID number.
2395   serialization::SubmoduleID
2396   getGlobalSubmoduleID(unsigned LocalID) {
2397     return Reader->getGlobalSubmoduleID(*F, LocalID);
2398   }
2399
2400   /// Retrieve the submodule that corresponds to a global submodule ID.
2401   Module *getSubmodule(serialization::SubmoduleID GlobalID) {
2402     return Reader->getSubmodule(GlobalID);
2403   }
2404
2405   /// Read the record that describes the lexical contents of a DC.
2406   bool readLexicalDeclContextStorage(uint64_t Offset, DeclContext *DC) {
2407     return Reader->ReadLexicalDeclContextStorage(*F, F->DeclsCursor, Offset,
2408                                                  DC);
2409   }
2410
2411   /// Read the record that describes the visible contents of a DC.
2412   bool readVisibleDeclContextStorage(uint64_t Offset,
2413                                      serialization::DeclID ID) {
2414     return Reader->ReadVisibleDeclContextStorage(*F, F->DeclsCursor, Offset,
2415                                                  ID);
2416   }
2417
2418   void readExceptionSpec(SmallVectorImpl<QualType> &ExceptionStorage,
2419                          FunctionProtoType::ExceptionSpecInfo &ESI) {
2420     return Reader->readExceptionSpec(*F, ExceptionStorage, ESI, Record, Idx);
2421   }
2422
2423   /// Get the global offset corresponding to a local offset.
2424   uint64_t getGlobalBitOffset(uint32_t LocalOffset) {
2425     return Reader->getGlobalBitOffset(*F, LocalOffset);
2426   }
2427
2428   /// Reads a statement.
2429   Stmt *readStmt() { return Reader->ReadStmt(*F); }
2430
2431   /// Reads an expression.
2432   Expr *readExpr() { return Reader->ReadExpr(*F); }
2433
2434   /// Reads a sub-statement operand during statement reading.
2435   Stmt *readSubStmt() { return Reader->ReadSubStmt(); }
2436
2437   /// Reads a sub-expression operand during statement reading.
2438   Expr *readSubExpr() { return Reader->ReadSubExpr(); }
2439
2440   /// Reads a declaration with the given local ID in the given module.
2441   ///
2442   /// \returns The requested declaration, casted to the given return type.
2443   template<typename T>
2444   T *GetLocalDeclAs(uint32_t LocalID) {
2445     return cast_or_null<T>(Reader->GetLocalDecl(*F, LocalID));
2446   }
2447
2448   /// Reads a TemplateArgumentLocInfo appropriate for the
2449   /// given TemplateArgument kind, advancing Idx.
2450   TemplateArgumentLocInfo
2451   getTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind) {
2452     return Reader->GetTemplateArgumentLocInfo(*F, Kind, Record, Idx);
2453   }
2454
2455   /// Reads a TemplateArgumentLoc, advancing Idx.
2456   TemplateArgumentLoc
2457   readTemplateArgumentLoc() {
2458     return Reader->ReadTemplateArgumentLoc(*F, Record, Idx);
2459   }
2460
2461   const ASTTemplateArgumentListInfo*
2462   readASTTemplateArgumentListInfo() {
2463     return Reader->ReadASTTemplateArgumentListInfo(*F, Record, Idx);
2464   }
2465
2466   /// Reads a declarator info from the given record, advancing Idx.
2467   TypeSourceInfo *getTypeSourceInfo() {
2468     return Reader->GetTypeSourceInfo(*F, Record, Idx);
2469   }
2470
2471   /// Reads the location information for a type.
2472   void readTypeLoc(TypeLoc TL) {
2473     return Reader->ReadTypeLoc(*F, Record, Idx, TL);
2474   }
2475
2476   /// Map a local type ID within a given AST file to a global type ID.
2477   serialization::TypeID getGlobalTypeID(unsigned LocalID) const {
2478     return Reader->getGlobalTypeID(*F, LocalID);
2479   }
2480
2481   /// Read a type from the current position in the record.
2482   QualType readType() {
2483     return Reader->readType(*F, Record, Idx);
2484   }
2485
2486   /// Reads a declaration ID from the given position in this record.
2487   ///
2488   /// \returns The declaration ID read from the record, adjusted to a global ID.
2489   serialization::DeclID readDeclID() {
2490     return Reader->ReadDeclID(*F, Record, Idx);
2491   }
2492
2493   /// Reads a declaration from the given position in a record in the
2494   /// given module, advancing Idx.
2495   Decl *readDecl() {
2496     return Reader->ReadDecl(*F, Record, Idx);
2497   }
2498
2499   /// Reads a declaration from the given position in the record,
2500   /// advancing Idx.
2501   ///
2502   /// \returns The declaration read from this location, casted to the given
2503   /// result type.
2504   template<typename T>
2505   T *readDeclAs() {
2506     return Reader->ReadDeclAs<T>(*F, Record, Idx);
2507   }
2508
2509   IdentifierInfo *getIdentifierInfo() {
2510     return Reader->GetIdentifierInfo(*F, Record, Idx);
2511   }
2512
2513   /// Read a selector from the Record, advancing Idx.
2514   Selector readSelector() {
2515     return Reader->ReadSelector(*F, Record, Idx);
2516   }
2517
2518   /// Read a declaration name, advancing Idx.
2519   DeclarationName readDeclarationName() {
2520     return Reader->ReadDeclarationName(*F, Record, Idx);
2521   }
2522   void readDeclarationNameLoc(DeclarationNameLoc &DNLoc, DeclarationName Name) {
2523     return Reader->ReadDeclarationNameLoc(*F, DNLoc, Name, Record, Idx);
2524   }
2525   void readDeclarationNameInfo(DeclarationNameInfo &NameInfo) {
2526     return Reader->ReadDeclarationNameInfo(*F, NameInfo, Record, Idx);
2527   }
2528
2529   void readQualifierInfo(QualifierInfo &Info) {
2530     return Reader->ReadQualifierInfo(*F, Info, Record, Idx);
2531   }
2532
2533   NestedNameSpecifier *readNestedNameSpecifier() {
2534     return Reader->ReadNestedNameSpecifier(*F, Record, Idx);
2535   }
2536
2537   NestedNameSpecifierLoc readNestedNameSpecifierLoc() {
2538     return Reader->ReadNestedNameSpecifierLoc(*F, Record, Idx);
2539   }
2540
2541   /// Read a template name, advancing Idx.
2542   TemplateName readTemplateName() {
2543     return Reader->ReadTemplateName(*F, Record, Idx);
2544   }
2545
2546   /// Read a template argument, advancing Idx.
2547   TemplateArgument readTemplateArgument(bool Canonicalize = false) {
2548     return Reader->ReadTemplateArgument(*F, Record, Idx, Canonicalize);
2549   }
2550
2551   /// Read a template parameter list, advancing Idx.
2552   TemplateParameterList *readTemplateParameterList() {
2553     return Reader->ReadTemplateParameterList(*F, Record, Idx);
2554   }
2555
2556   /// Read a template argument array, advancing Idx.
2557   void readTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
2558                                 bool Canonicalize = false) {
2559     return Reader->ReadTemplateArgumentList(TemplArgs, *F, Record, Idx,
2560                                             Canonicalize);
2561   }
2562
2563   /// Read a UnresolvedSet structure, advancing Idx.
2564   void readUnresolvedSet(LazyASTUnresolvedSet &Set) {
2565     return Reader->ReadUnresolvedSet(*F, Set, Record, Idx);
2566   }
2567
2568   /// Read a C++ base specifier, advancing Idx.
2569   CXXBaseSpecifier readCXXBaseSpecifier() {
2570     return Reader->ReadCXXBaseSpecifier(*F, Record, Idx);
2571   }
2572
2573   /// Read a CXXCtorInitializer array, advancing Idx.
2574   CXXCtorInitializer **readCXXCtorInitializers() {
2575     return Reader->ReadCXXCtorInitializers(*F, Record, Idx);
2576   }
2577
2578   CXXTemporary *readCXXTemporary() {
2579     return Reader->ReadCXXTemporary(*F, Record, Idx);
2580   }
2581
2582   /// Read a source location, advancing Idx.
2583   SourceLocation readSourceLocation() {
2584     return Reader->ReadSourceLocation(*F, Record, Idx);
2585   }
2586
2587   /// Read a source range, advancing Idx.
2588   SourceRange readSourceRange() {
2589     return Reader->ReadSourceRange(*F, Record, Idx);
2590   }
2591
2592   /// Read an integral value, advancing Idx.
2593   llvm::APInt readAPInt() {
2594     return Reader->ReadAPInt(Record, Idx);
2595   }
2596
2597   /// Read a signed integral value, advancing Idx.
2598   llvm::APSInt readAPSInt() {
2599     return Reader->ReadAPSInt(Record, Idx);
2600   }
2601
2602   /// Read a floating-point value, advancing Idx.
2603   llvm::APFloat readAPFloat(const llvm::fltSemantics &Sem) {
2604     return Reader->ReadAPFloat(Record, Sem,Idx);
2605   }
2606
2607   /// Read a string, advancing Idx.
2608   std::string readString() {
2609     return Reader->ReadString(Record, Idx);
2610   }
2611
2612   /// Read a path, advancing Idx.
2613   std::string readPath() {
2614     return Reader->ReadPath(*F, Record, Idx);
2615   }
2616
2617   /// Read a version tuple, advancing Idx.
2618   VersionTuple readVersionTuple() {
2619     return ASTReader::ReadVersionTuple(Record, Idx);
2620   }
2621
2622   /// Reads attributes from the current stream position, advancing Idx.
2623   void readAttributes(AttrVec &Attrs) {
2624     return Reader->ReadAttributes(*this, Attrs);
2625   }
2626
2627   /// Reads a token out of a record, advancing Idx.
2628   Token readToken() {
2629     return Reader->ReadToken(*F, Record, Idx);
2630   }
2631
2632   void recordSwitchCaseID(SwitchCase *SC, unsigned ID) {
2633     Reader->RecordSwitchCaseID(SC, ID);
2634   }
2635
2636   /// Retrieve the switch-case statement with the given ID.
2637   SwitchCase *getSwitchCaseWithID(unsigned ID) {
2638     return Reader->getSwitchCaseWithID(ID);
2639   }
2640 };
2641
2642 /// Helper class that saves the current stream position and
2643 /// then restores it when destroyed.
2644 struct SavedStreamPosition {
2645   explicit SavedStreamPosition(llvm::BitstreamCursor &Cursor)
2646       : Cursor(Cursor), Offset(Cursor.GetCurrentBitNo()) {}
2647
2648   ~SavedStreamPosition() {
2649     Cursor.JumpToBit(Offset);
2650   }
2651
2652 private:
2653   llvm::BitstreamCursor &Cursor;
2654   uint64_t Offset;
2655 };
2656
2657 inline void PCHValidator::Error(const char *Msg) {
2658   Reader.Error(Msg);
2659 }
2660
2661 } // namespace clang
2662
2663 #endif // LLVM_CLANG_SERIALIZATION_ASTREADER_H