Coverage Report

Created: 2023-11-11 10:31

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