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