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