Coverage Report

Created: 2024-01-17 10:31

/src/llvm-project/clang/lib/Serialization/ASTReader.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- ASTReader.cpp - AST File Reader ------------------------------------===//
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
#include "ASTCommon.h"
14
#include "ASTReaderInternals.h"
15
#include "clang/AST/ASTConsumer.h"
16
#include "clang/AST/ASTContext.h"
17
#include "clang/AST/ASTMutationListener.h"
18
#include "clang/AST/ASTStructuralEquivalence.h"
19
#include "clang/AST/ASTUnresolvedSet.h"
20
#include "clang/AST/AbstractTypeReader.h"
21
#include "clang/AST/Decl.h"
22
#include "clang/AST/DeclBase.h"
23
#include "clang/AST/DeclCXX.h"
24
#include "clang/AST/DeclFriend.h"
25
#include "clang/AST/DeclGroup.h"
26
#include "clang/AST/DeclObjC.h"
27
#include "clang/AST/DeclTemplate.h"
28
#include "clang/AST/DeclarationName.h"
29
#include "clang/AST/Expr.h"
30
#include "clang/AST/ExprCXX.h"
31
#include "clang/AST/ExternalASTSource.h"
32
#include "clang/AST/NestedNameSpecifier.h"
33
#include "clang/AST/ODRDiagsEmitter.h"
34
#include "clang/AST/ODRHash.h"
35
#include "clang/AST/OpenMPClause.h"
36
#include "clang/AST/RawCommentList.h"
37
#include "clang/AST/TemplateBase.h"
38
#include "clang/AST/TemplateName.h"
39
#include "clang/AST/Type.h"
40
#include "clang/AST/TypeLoc.h"
41
#include "clang/AST/TypeLocVisitor.h"
42
#include "clang/AST/UnresolvedSet.h"
43
#include "clang/Basic/CommentOptions.h"
44
#include "clang/Basic/Diagnostic.h"
45
#include "clang/Basic/DiagnosticError.h"
46
#include "clang/Basic/DiagnosticOptions.h"
47
#include "clang/Basic/DiagnosticSema.h"
48
#include "clang/Basic/ExceptionSpecificationType.h"
49
#include "clang/Basic/FileManager.h"
50
#include "clang/Basic/FileSystemOptions.h"
51
#include "clang/Basic/IdentifierTable.h"
52
#include "clang/Basic/LLVM.h"
53
#include "clang/Basic/LangOptions.h"
54
#include "clang/Basic/Module.h"
55
#include "clang/Basic/ObjCRuntime.h"
56
#include "clang/Basic/OpenMPKinds.h"
57
#include "clang/Basic/OperatorKinds.h"
58
#include "clang/Basic/PragmaKinds.h"
59
#include "clang/Basic/Sanitizers.h"
60
#include "clang/Basic/SourceLocation.h"
61
#include "clang/Basic/SourceManager.h"
62
#include "clang/Basic/SourceManagerInternals.h"
63
#include "clang/Basic/Specifiers.h"
64
#include "clang/Basic/TargetInfo.h"
65
#include "clang/Basic/TargetOptions.h"
66
#include "clang/Basic/TokenKinds.h"
67
#include "clang/Basic/Version.h"
68
#include "clang/Lex/HeaderSearch.h"
69
#include "clang/Lex/HeaderSearchOptions.h"
70
#include "clang/Lex/MacroInfo.h"
71
#include "clang/Lex/ModuleMap.h"
72
#include "clang/Lex/PreprocessingRecord.h"
73
#include "clang/Lex/Preprocessor.h"
74
#include "clang/Lex/PreprocessorOptions.h"
75
#include "clang/Lex/Token.h"
76
#include "clang/Sema/ObjCMethodList.h"
77
#include "clang/Sema/Scope.h"
78
#include "clang/Sema/Sema.h"
79
#include "clang/Sema/Weak.h"
80
#include "clang/Serialization/ASTBitCodes.h"
81
#include "clang/Serialization/ASTDeserializationListener.h"
82
#include "clang/Serialization/ASTRecordReader.h"
83
#include "clang/Serialization/ContinuousRangeMap.h"
84
#include "clang/Serialization/GlobalModuleIndex.h"
85
#include "clang/Serialization/InMemoryModuleCache.h"
86
#include "clang/Serialization/ModuleFile.h"
87
#include "clang/Serialization/ModuleFileExtension.h"
88
#include "clang/Serialization/ModuleManager.h"
89
#include "clang/Serialization/PCHContainerOperations.h"
90
#include "clang/Serialization/SerializationDiagnostic.h"
91
#include "llvm/ADT/APFloat.h"
92
#include "llvm/ADT/APInt.h"
93
#include "llvm/ADT/APSInt.h"
94
#include "llvm/ADT/ArrayRef.h"
95
#include "llvm/ADT/DenseMap.h"
96
#include "llvm/ADT/FloatingPointMode.h"
97
#include "llvm/ADT/FoldingSet.h"
98
#include "llvm/ADT/Hashing.h"
99
#include "llvm/ADT/IntrusiveRefCntPtr.h"
100
#include "llvm/ADT/STLExtras.h"
101
#include "llvm/ADT/ScopeExit.h"
102
#include "llvm/ADT/SmallPtrSet.h"
103
#include "llvm/ADT/SmallString.h"
104
#include "llvm/ADT/SmallVector.h"
105
#include "llvm/ADT/StringExtras.h"
106
#include "llvm/ADT/StringMap.h"
107
#include "llvm/ADT/StringRef.h"
108
#include "llvm/ADT/iterator_range.h"
109
#include "llvm/Bitstream/BitstreamReader.h"
110
#include "llvm/Support/Casting.h"
111
#include "llvm/Support/Compiler.h"
112
#include "llvm/Support/Compression.h"
113
#include "llvm/Support/DJB.h"
114
#include "llvm/Support/Endian.h"
115
#include "llvm/Support/Error.h"
116
#include "llvm/Support/ErrorHandling.h"
117
#include "llvm/Support/FileSystem.h"
118
#include "llvm/Support/LEB128.h"
119
#include "llvm/Support/MemoryBuffer.h"
120
#include "llvm/Support/Path.h"
121
#include "llvm/Support/SaveAndRestore.h"
122
#include "llvm/Support/TimeProfiler.h"
123
#include "llvm/Support/Timer.h"
124
#include "llvm/Support/VersionTuple.h"
125
#include "llvm/Support/raw_ostream.h"
126
#include "llvm/TargetParser/Triple.h"
127
#include <algorithm>
128
#include <cassert>
129
#include <cstddef>
130
#include <cstdint>
131
#include <cstdio>
132
#include <ctime>
133
#include <iterator>
134
#include <limits>
135
#include <map>
136
#include <memory>
137
#include <optional>
138
#include <string>
139
#include <system_error>
140
#include <tuple>
141
#include <utility>
142
#include <vector>
143
144
using namespace clang;
145
using namespace clang::serialization;
146
using namespace clang::serialization::reader;
147
using llvm::BitstreamCursor;
148
149
//===----------------------------------------------------------------------===//
150
// ChainedASTReaderListener implementation
151
//===----------------------------------------------------------------------===//
152
153
bool
154
0
ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
155
0
  return First->ReadFullVersionInformation(FullVersion) ||
156
0
         Second->ReadFullVersionInformation(FullVersion);
157
0
}
158
159
0
void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
160
0
  First->ReadModuleName(ModuleName);
161
0
  Second->ReadModuleName(ModuleName);
162
0
}
163
164
0
void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
165
0
  First->ReadModuleMapFile(ModuleMapPath);
166
0
  Second->ReadModuleMapFile(ModuleMapPath);
167
0
}
168
169
bool
170
ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
171
                                              bool Complain,
172
0
                                              bool AllowCompatibleDifferences) {
173
0
  return First->ReadLanguageOptions(LangOpts, Complain,
174
0
                                    AllowCompatibleDifferences) ||
175
0
         Second->ReadLanguageOptions(LangOpts, Complain,
176
0
                                     AllowCompatibleDifferences);
177
0
}
178
179
bool ChainedASTReaderListener::ReadTargetOptions(
180
    const TargetOptions &TargetOpts, bool Complain,
181
0
    bool AllowCompatibleDifferences) {
182
0
  return First->ReadTargetOptions(TargetOpts, Complain,
183
0
                                  AllowCompatibleDifferences) ||
184
0
         Second->ReadTargetOptions(TargetOpts, Complain,
185
0
                                   AllowCompatibleDifferences);
186
0
}
187
188
bool ChainedASTReaderListener::ReadDiagnosticOptions(
189
0
    IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
190
0
  return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
191
0
         Second->ReadDiagnosticOptions(DiagOpts, Complain);
192
0
}
193
194
bool
195
ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
196
0
                                                bool Complain) {
197
0
  return First->ReadFileSystemOptions(FSOpts, Complain) ||
198
0
         Second->ReadFileSystemOptions(FSOpts, Complain);
199
0
}
200
201
bool ChainedASTReaderListener::ReadHeaderSearchOptions(
202
    const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
203
0
    bool Complain) {
204
0
  return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
205
0
                                        Complain) ||
206
0
         Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
207
0
                                         Complain);
208
0
}
209
210
bool ChainedASTReaderListener::ReadPreprocessorOptions(
211
    const PreprocessorOptions &PPOpts, bool ReadMacros, bool Complain,
212
0
    std::string &SuggestedPredefines) {
213
0
  return First->ReadPreprocessorOptions(PPOpts, ReadMacros, Complain,
214
0
                                        SuggestedPredefines) ||
215
0
         Second->ReadPreprocessorOptions(PPOpts, ReadMacros, Complain,
216
0
                                         SuggestedPredefines);
217
0
}
218
219
void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
220
0
                                           unsigned Value) {
221
0
  First->ReadCounter(M, Value);
222
0
  Second->ReadCounter(M, Value);
223
0
}
224
225
0
bool ChainedASTReaderListener::needsInputFileVisitation() {
226
0
  return First->needsInputFileVisitation() ||
227
0
         Second->needsInputFileVisitation();
228
0
}
229
230
0
bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
231
0
  return First->needsSystemInputFileVisitation() ||
232
0
  Second->needsSystemInputFileVisitation();
233
0
}
234
235
void ChainedASTReaderListener::visitModuleFile(StringRef Filename,
236
0
                                               ModuleKind Kind) {
237
0
  First->visitModuleFile(Filename, Kind);
238
0
  Second->visitModuleFile(Filename, Kind);
239
0
}
240
241
bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
242
                                              bool isSystem,
243
                                              bool isOverridden,
244
0
                                              bool isExplicitModule) {
245
0
  bool Continue = false;
246
0
  if (First->needsInputFileVisitation() &&
247
0
      (!isSystem || First->needsSystemInputFileVisitation()))
248
0
    Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
249
0
                                      isExplicitModule);
250
0
  if (Second->needsInputFileVisitation() &&
251
0
      (!isSystem || Second->needsSystemInputFileVisitation()))
252
0
    Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
253
0
                                       isExplicitModule);
254
0
  return Continue;
255
0
}
256
257
void ChainedASTReaderListener::readModuleFileExtension(
258
0
       const ModuleFileExtensionMetadata &Metadata) {
259
0
  First->readModuleFileExtension(Metadata);
260
0
  Second->readModuleFileExtension(Metadata);
261
0
}
262
263
//===----------------------------------------------------------------------===//
264
// PCH validator implementation
265
//===----------------------------------------------------------------------===//
266
267
0
ASTReaderListener::~ASTReaderListener() = default;
268
269
/// Compare the given set of language options against an existing set of
270
/// language options.
271
///
272
/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
273
/// \param AllowCompatibleDifferences If true, differences between compatible
274
///        language options will be permitted.
275
///
276
/// \returns true if the languagae options mis-match, false otherwise.
277
static bool checkLanguageOptions(const LangOptions &LangOpts,
278
                                 const LangOptions &ExistingLangOpts,
279
                                 DiagnosticsEngine *Diags,
280
0
                                 bool AllowCompatibleDifferences = true) {
281
0
#define LANGOPT(Name, Bits, Default, Description)                   \
282
0
  if (ExistingLangOpts.Name != LangOpts.Name) {                     \
283
0
    if (Diags) {                                                    \
284
0
      if (Bits == 1)                                                \
285
0
        Diags->Report(diag::err_pch_langopt_mismatch)               \
286
0
          << Description << LangOpts.Name << ExistingLangOpts.Name; \
287
0
      else                                                          \
288
0
        Diags->Report(diag::err_pch_langopt_value_mismatch)         \
289
0
          << Description;                                           \
290
0
    }                                                               \
291
0
    return true;                                                    \
292
0
  }
293
294
0
#define VALUE_LANGOPT(Name, Bits, Default, Description)   \
295
0
  if (ExistingLangOpts.Name != LangOpts.Name) {           \
296
0
    if (Diags)                                            \
297
0
      Diags->Report(diag::err_pch_langopt_value_mismatch) \
298
0
        << Description;                                   \
299
0
    return true;                                          \
300
0
  }
301
302
0
#define ENUM_LANGOPT(Name, Type, Bits, Default, Description)   \
303
0
  if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) {  \
304
0
    if (Diags)                                                 \
305
0
      Diags->Report(diag::err_pch_langopt_value_mismatch)      \
306
0
        << Description;                                        \
307
0
    return true;                                               \
308
0
  }
309
310
0
#define COMPATIBLE_LANGOPT(Name, Bits, Default, Description)  \
311
0
  if (!AllowCompatibleDifferences)                            \
312
0
    LANGOPT(Name, Bits, Default, Description)
313
314
0
#define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description)  \
315
0
  if (!AllowCompatibleDifferences)                                 \
316
0
    ENUM_LANGOPT(Name, Bits, Default, Description)
317
318
0
#define COMPATIBLE_VALUE_LANGOPT(Name, Bits, Default, Description) \
319
0
  if (!AllowCompatibleDifferences)                                 \
320
0
    VALUE_LANGOPT(Name, Bits, Default, Description)
321
322
0
#define BENIGN_LANGOPT(Name, Bits, Default, Description)
323
0
#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
324
0
#define BENIGN_VALUE_LANGOPT(Name, Bits, Default, Description)
325
0
#include "clang/Basic/LangOptions.def"
326
327
0
  if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
328
0
    if (Diags)
329
0
      Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
330
0
    return true;
331
0
  }
332
333
0
  if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
334
0
    if (Diags)
335
0
      Diags->Report(diag::err_pch_langopt_value_mismatch)
336
0
      << "target Objective-C runtime";
337
0
    return true;
338
0
  }
339
340
0
  if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
341
0
      LangOpts.CommentOpts.BlockCommandNames) {
342
0
    if (Diags)
343
0
      Diags->Report(diag::err_pch_langopt_value_mismatch)
344
0
        << "block command names";
345
0
    return true;
346
0
  }
347
348
  // Sanitizer feature mismatches are treated as compatible differences. If
349
  // compatible differences aren't allowed, we still only want to check for
350
  // mismatches of non-modular sanitizers (the only ones which can affect AST
351
  // generation).
352
0
  if (!AllowCompatibleDifferences) {
353
0
    SanitizerMask ModularSanitizers = getPPTransparentSanitizers();
354
0
    SanitizerSet ExistingSanitizers = ExistingLangOpts.Sanitize;
355
0
    SanitizerSet ImportedSanitizers = LangOpts.Sanitize;
356
0
    ExistingSanitizers.clear(ModularSanitizers);
357
0
    ImportedSanitizers.clear(ModularSanitizers);
358
0
    if (ExistingSanitizers.Mask != ImportedSanitizers.Mask) {
359
0
      const std::string Flag = "-fsanitize=";
360
0
      if (Diags) {
361
0
#define SANITIZER(NAME, ID)                                                    \
362
0
  {                                                                            \
363
0
    bool InExistingModule = ExistingSanitizers.has(SanitizerKind::ID);         \
364
0
    bool InImportedModule = ImportedSanitizers.has(SanitizerKind::ID);         \
365
0
    if (InExistingModule != InImportedModule)                                  \
366
0
      Diags->Report(diag::err_pch_targetopt_feature_mismatch)                  \
367
0
          << InExistingModule << (Flag + NAME);                                \
368
0
  }
369
0
#include "clang/Basic/Sanitizers.def"
370
0
      }
371
0
      return true;
372
0
    }
373
0
  }
374
375
0
  return false;
376
0
}
377
378
/// Compare the given set of target options against an existing set of
379
/// target options.
380
///
381
/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
382
///
383
/// \returns true if the target options mis-match, false otherwise.
384
static bool checkTargetOptions(const TargetOptions &TargetOpts,
385
                               const TargetOptions &ExistingTargetOpts,
386
                               DiagnosticsEngine *Diags,
387
0
                               bool AllowCompatibleDifferences = true) {
388
0
#define CHECK_TARGET_OPT(Field, Name)                             \
389
0
  if (TargetOpts.Field != ExistingTargetOpts.Field) {             \
390
0
    if (Diags)                                                    \
391
0
      Diags->Report(diag::err_pch_targetopt_mismatch)             \
392
0
        << Name << TargetOpts.Field << ExistingTargetOpts.Field;  \
393
0
    return true;                                                  \
394
0
  }
395
396
  // The triple and ABI must match exactly.
397
0
  CHECK_TARGET_OPT(Triple, "target");
398
0
  CHECK_TARGET_OPT(ABI, "target ABI");
399
400
  // We can tolerate different CPUs in many cases, notably when one CPU
401
  // supports a strict superset of another. When allowing compatible
402
  // differences skip this check.
403
0
  if (!AllowCompatibleDifferences) {
404
0
    CHECK_TARGET_OPT(CPU, "target CPU");
405
0
    CHECK_TARGET_OPT(TuneCPU, "tune CPU");
406
0
  }
407
408
0
#undef CHECK_TARGET_OPT
409
410
  // Compare feature sets.
411
0
  SmallVector<StringRef, 4> ExistingFeatures(
412
0
                                             ExistingTargetOpts.FeaturesAsWritten.begin(),
413
0
                                             ExistingTargetOpts.FeaturesAsWritten.end());
414
0
  SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
415
0
                                         TargetOpts.FeaturesAsWritten.end());
416
0
  llvm::sort(ExistingFeatures);
417
0
  llvm::sort(ReadFeatures);
418
419
  // We compute the set difference in both directions explicitly so that we can
420
  // diagnose the differences differently.
421
0
  SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
422
0
  std::set_difference(
423
0
      ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
424
0
      ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
425
0
  std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
426
0
                      ExistingFeatures.begin(), ExistingFeatures.end(),
427
0
                      std::back_inserter(UnmatchedReadFeatures));
428
429
  // If we are allowing compatible differences and the read feature set is
430
  // a strict subset of the existing feature set, there is nothing to diagnose.
431
0
  if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
432
0
    return false;
433
434
0
  if (Diags) {
435
0
    for (StringRef Feature : UnmatchedReadFeatures)
436
0
      Diags->Report(diag::err_pch_targetopt_feature_mismatch)
437
0
          << /* is-existing-feature */ false << Feature;
438
0
    for (StringRef Feature : UnmatchedExistingFeatures)
439
0
      Diags->Report(diag::err_pch_targetopt_feature_mismatch)
440
0
          << /* is-existing-feature */ true << Feature;
441
0
  }
442
443
0
  return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
444
0
}
445
446
bool
447
PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
448
                                  bool Complain,
449
0
                                  bool AllowCompatibleDifferences) {
450
0
  const LangOptions &ExistingLangOpts = PP.getLangOpts();
451
0
  return checkLanguageOptions(LangOpts, ExistingLangOpts,
452
0
                              Complain ? &Reader.Diags : nullptr,
453
0
                              AllowCompatibleDifferences);
454
0
}
455
456
bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
457
                                     bool Complain,
458
0
                                     bool AllowCompatibleDifferences) {
459
0
  const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
460
0
  return checkTargetOptions(TargetOpts, ExistingTargetOpts,
461
0
                            Complain ? &Reader.Diags : nullptr,
462
0
                            AllowCompatibleDifferences);
463
0
}
464
465
namespace {
466
467
using MacroDefinitionsMap =
468
    llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>;
469
using DeclsMap = llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8>>;
470
471
} // namespace
472
473
static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
474
                                         DiagnosticsEngine &Diags,
475
0
                                         bool Complain) {
476
0
  using Level = DiagnosticsEngine::Level;
477
478
  // Check current mappings for new -Werror mappings, and the stored mappings
479
  // for cases that were explicitly mapped to *not* be errors that are now
480
  // errors because of options like -Werror.
481
0
  DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
482
483
0
  for (DiagnosticsEngine *MappingSource : MappingSources) {
484
0
    for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
485
0
      diag::kind DiagID = DiagIDMappingPair.first;
486
0
      Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
487
0
      if (CurLevel < DiagnosticsEngine::Error)
488
0
        continue; // not significant
489
0
      Level StoredLevel =
490
0
          StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
491
0
      if (StoredLevel < DiagnosticsEngine::Error) {
492
0
        if (Complain)
493
0
          Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
494
0
              Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
495
0
        return true;
496
0
      }
497
0
    }
498
0
  }
499
500
0
  return false;
501
0
}
502
503
0
static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
504
0
  diag::Severity Ext = Diags.getExtensionHandlingBehavior();
505
0
  if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
506
0
    return true;
507
0
  return Ext >= diag::Severity::Error;
508
0
}
509
510
static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
511
                                    DiagnosticsEngine &Diags, bool IsSystem,
512
                                    bool SystemHeaderWarningsInModule,
513
0
                                    bool Complain) {
514
  // Top-level options
515
0
  if (IsSystem) {
516
0
    if (Diags.getSuppressSystemWarnings())
517
0
      return false;
518
    // If -Wsystem-headers was not enabled before, and it was not explicit,
519
    // be conservative
520
0
    if (StoredDiags.getSuppressSystemWarnings() &&
521
0
        !SystemHeaderWarningsInModule) {
522
0
      if (Complain)
523
0
        Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
524
0
      return true;
525
0
    }
526
0
  }
527
528
0
  if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
529
0
    if (Complain)
530
0
      Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
531
0
    return true;
532
0
  }
533
534
0
  if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
535
0
      !StoredDiags.getEnableAllWarnings()) {
536
0
    if (Complain)
537
0
      Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
538
0
    return true;
539
0
  }
540
541
0
  if (isExtHandlingFromDiagsError(Diags) &&
542
0
      !isExtHandlingFromDiagsError(StoredDiags)) {
543
0
    if (Complain)
544
0
      Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
545
0
    return true;
546
0
  }
547
548
0
  return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
549
0
}
550
551
/// Return the top import module if it is implicit, nullptr otherwise.
552
static Module *getTopImportImplicitModule(ModuleManager &ModuleMgr,
553
0
                                          Preprocessor &PP) {
554
  // If the original import came from a file explicitly generated by the user,
555
  // don't check the diagnostic mappings.
556
  // FIXME: currently this is approximated by checking whether this is not a
557
  // module import of an implicitly-loaded module file.
558
  // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
559
  // the transitive closure of its imports, since unrelated modules cannot be
560
  // imported until after this module finishes validation.
561
0
  ModuleFile *TopImport = &*ModuleMgr.rbegin();
562
0
  while (!TopImport->ImportedBy.empty())
563
0
    TopImport = TopImport->ImportedBy[0];
564
0
  if (TopImport->Kind != MK_ImplicitModule)
565
0
    return nullptr;
566
567
0
  StringRef ModuleName = TopImport->ModuleName;
568
0
  assert(!ModuleName.empty() && "diagnostic options read before module name");
569
570
0
  Module *M =
571
0
      PP.getHeaderSearchInfo().lookupModule(ModuleName, TopImport->ImportLoc);
572
0
  assert(M && "missing module");
573
0
  return M;
574
0
}
575
576
bool PCHValidator::ReadDiagnosticOptions(
577
0
    IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
578
0
  DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
579
0
  IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
580
0
  IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
581
0
      new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
582
  // This should never fail, because we would have processed these options
583
  // before writing them to an ASTFile.
584
0
  ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
585
586
0
  ModuleManager &ModuleMgr = Reader.getModuleManager();
587
0
  assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
588
589
0
  Module *TopM = getTopImportImplicitModule(ModuleMgr, PP);
590
0
  if (!TopM)
591
0
    return false;
592
593
0
  Module *Importer = PP.getCurrentModule();
594
595
0
  DiagnosticOptions &ExistingOpts = ExistingDiags.getDiagnosticOptions();
596
0
  bool SystemHeaderWarningsInModule =
597
0
      Importer && llvm::is_contained(ExistingOpts.SystemHeaderWarningsModules,
598
0
                                     Importer->Name);
599
600
  // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
601
  // contains the union of their flags.
602
0
  return checkDiagnosticMappings(*Diags, ExistingDiags, TopM->IsSystem,
603
0
                                 SystemHeaderWarningsInModule, Complain);
604
0
}
605
606
/// Collect the macro definitions provided by the given preprocessor
607
/// options.
608
static void
609
collectMacroDefinitions(const PreprocessorOptions &PPOpts,
610
                        MacroDefinitionsMap &Macros,
611
0
                        SmallVectorImpl<StringRef> *MacroNames = nullptr) {
612
0
  for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
613
0
    StringRef Macro = PPOpts.Macros[I].first;
614
0
    bool IsUndef = PPOpts.Macros[I].second;
615
616
0
    std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
617
0
    StringRef MacroName = MacroPair.first;
618
0
    StringRef MacroBody = MacroPair.second;
619
620
    // For an #undef'd macro, we only care about the name.
621
0
    if (IsUndef) {
622
0
      if (MacroNames && !Macros.count(MacroName))
623
0
        MacroNames->push_back(MacroName);
624
625
0
      Macros[MacroName] = std::make_pair("", true);
626
0
      continue;
627
0
    }
628
629
    // For a #define'd macro, figure out the actual definition.
630
0
    if (MacroName.size() == Macro.size())
631
0
      MacroBody = "1";
632
0
    else {
633
      // Note: GCC drops anything following an end-of-line character.
634
0
      StringRef::size_type End = MacroBody.find_first_of("\n\r");
635
0
      MacroBody = MacroBody.substr(0, End);
636
0
    }
637
638
0
    if (MacroNames && !Macros.count(MacroName))
639
0
      MacroNames->push_back(MacroName);
640
0
    Macros[MacroName] = std::make_pair(MacroBody, false);
641
0
  }
642
0
}
643
644
enum OptionValidation {
645
  OptionValidateNone,
646
  OptionValidateContradictions,
647
  OptionValidateStrictMatches,
648
};
649
650
/// Check the preprocessor options deserialized from the control block
651
/// against the preprocessor options in an existing preprocessor.
652
///
653
/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
654
/// \param Validation If set to OptionValidateNone, ignore differences in
655
///        preprocessor options. If set to OptionValidateContradictions,
656
///        require that options passed both in the AST file and on the command
657
///        line (-D or -U) match, but tolerate options missing in one or the
658
///        other. If set to OptionValidateContradictions, require that there
659
///        are no differences in the options between the two.
660
static bool checkPreprocessorOptions(
661
    const PreprocessorOptions &PPOpts,
662
    const PreprocessorOptions &ExistingPPOpts, bool ReadMacros,
663
    DiagnosticsEngine *Diags, FileManager &FileMgr,
664
    std::string &SuggestedPredefines, const LangOptions &LangOpts,
665
0
    OptionValidation Validation = OptionValidateContradictions) {
666
0
  if (ReadMacros) {
667
    // Check macro definitions.
668
0
    MacroDefinitionsMap ASTFileMacros;
669
0
    collectMacroDefinitions(PPOpts, ASTFileMacros);
670
0
    MacroDefinitionsMap ExistingMacros;
671
0
    SmallVector<StringRef, 4> ExistingMacroNames;
672
0
    collectMacroDefinitions(ExistingPPOpts, ExistingMacros,
673
0
                            &ExistingMacroNames);
674
675
    // Use a line marker to enter the <command line> file, as the defines and
676
    // undefines here will have come from the command line.
677
0
    SuggestedPredefines += "# 1 \"<command line>\" 1\n";
678
679
0
    for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
680
      // Dig out the macro definition in the existing preprocessor options.
681
0
      StringRef MacroName = ExistingMacroNames[I];
682
0
      std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
683
684
      // Check whether we know anything about this macro name or not.
685
0
      llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>::iterator Known =
686
0
          ASTFileMacros.find(MacroName);
687
0
      if (Validation == OptionValidateNone || Known == ASTFileMacros.end()) {
688
0
        if (Validation == OptionValidateStrictMatches) {
689
          // If strict matches are requested, don't tolerate any extra defines
690
          // on the command line that are missing in the AST file.
691
0
          if (Diags) {
692
0
            Diags->Report(diag::err_pch_macro_def_undef) << MacroName << true;
693
0
          }
694
0
          return true;
695
0
        }
696
        // FIXME: Check whether this identifier was referenced anywhere in the
697
        // AST file. If so, we should reject the AST file. Unfortunately, this
698
        // information isn't in the control block. What shall we do about it?
699
700
0
        if (Existing.second) {
701
0
          SuggestedPredefines += "#undef ";
702
0
          SuggestedPredefines += MacroName.str();
703
0
          SuggestedPredefines += '\n';
704
0
        } else {
705
0
          SuggestedPredefines += "#define ";
706
0
          SuggestedPredefines += MacroName.str();
707
0
          SuggestedPredefines += ' ';
708
0
          SuggestedPredefines += Existing.first.str();
709
0
          SuggestedPredefines += '\n';
710
0
        }
711
0
        continue;
712
0
      }
713
714
      // If the macro was defined in one but undef'd in the other, we have a
715
      // conflict.
716
0
      if (Existing.second != Known->second.second) {
717
0
        if (Diags) {
718
0
          Diags->Report(diag::err_pch_macro_def_undef)
719
0
              << MacroName << Known->second.second;
720
0
        }
721
0
        return true;
722
0
      }
723
724
      // If the macro was #undef'd in both, or if the macro bodies are
725
      // identical, it's fine.
726
0
      if (Existing.second || Existing.first == Known->second.first) {
727
0
        ASTFileMacros.erase(Known);
728
0
        continue;
729
0
      }
730
731
      // The macro bodies differ; complain.
732
0
      if (Diags) {
733
0
        Diags->Report(diag::err_pch_macro_def_conflict)
734
0
            << MacroName << Known->second.first << Existing.first;
735
0
      }
736
0
      return true;
737
0
    }
738
739
    // Leave the <command line> file and return to <built-in>.
740
0
    SuggestedPredefines += "# 1 \"<built-in>\" 2\n";
741
742
0
    if (Validation == OptionValidateStrictMatches) {
743
      // If strict matches are requested, don't tolerate any extra defines in
744
      // the AST file that are missing on the command line.
745
0
      for (const auto &MacroName : ASTFileMacros.keys()) {
746
0
        if (Diags) {
747
0
          Diags->Report(diag::err_pch_macro_def_undef) << MacroName << false;
748
0
        }
749
0
        return true;
750
0
      }
751
0
    }
752
0
  }
753
754
  // Check whether we're using predefines.
755
0
  if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines &&
756
0
      Validation != OptionValidateNone) {
757
0
    if (Diags) {
758
0
      Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
759
0
    }
760
0
    return true;
761
0
  }
762
763
  // Detailed record is important since it is used for the module cache hash.
764
0
  if (LangOpts.Modules &&
765
0
      PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord &&
766
0
      Validation != OptionValidateNone) {
767
0
    if (Diags) {
768
0
      Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
769
0
    }
770
0
    return true;
771
0
  }
772
773
  // Compute the #include and #include_macros lines we need.
774
0
  for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
775
0
    StringRef File = ExistingPPOpts.Includes[I];
776
777
0
    if (!ExistingPPOpts.ImplicitPCHInclude.empty() &&
778
0
        !ExistingPPOpts.PCHThroughHeader.empty()) {
779
      // In case the through header is an include, we must add all the includes
780
      // to the predefines so the start point can be determined.
781
0
      SuggestedPredefines += "#include \"";
782
0
      SuggestedPredefines += File;
783
0
      SuggestedPredefines += "\"\n";
784
0
      continue;
785
0
    }
786
787
0
    if (File == ExistingPPOpts.ImplicitPCHInclude)
788
0
      continue;
789
790
0
    if (llvm::is_contained(PPOpts.Includes, File))
791
0
      continue;
792
793
0
    SuggestedPredefines += "#include \"";
794
0
    SuggestedPredefines += File;
795
0
    SuggestedPredefines += "\"\n";
796
0
  }
797
798
0
  for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
799
0
    StringRef File = ExistingPPOpts.MacroIncludes[I];
800
0
    if (llvm::is_contained(PPOpts.MacroIncludes, File))
801
0
      continue;
802
803
0
    SuggestedPredefines += "#__include_macros \"";
804
0
    SuggestedPredefines += File;
805
0
    SuggestedPredefines += "\"\n##\n";
806
0
  }
807
808
0
  return false;
809
0
}
810
811
bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
812
                                           bool ReadMacros, bool Complain,
813
0
                                           std::string &SuggestedPredefines) {
814
0
  const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
815
816
0
  return checkPreprocessorOptions(
817
0
      PPOpts, ExistingPPOpts, ReadMacros, Complain ? &Reader.Diags : nullptr,
818
0
      PP.getFileManager(), SuggestedPredefines, PP.getLangOpts());
819
0
}
820
821
bool SimpleASTReaderListener::ReadPreprocessorOptions(
822
    const PreprocessorOptions &PPOpts, bool ReadMacros, bool Complain,
823
0
    std::string &SuggestedPredefines) {
824
0
  return checkPreprocessorOptions(PPOpts, PP.getPreprocessorOpts(), ReadMacros,
825
0
                                  nullptr, PP.getFileManager(),
826
0
                                  SuggestedPredefines, PP.getLangOpts(),
827
0
                                  OptionValidateNone);
828
0
}
829
830
/// Check the header search options deserialized from the control block
831
/// against the header search options in an existing preprocessor.
832
///
833
/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
834
static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
835
                                     StringRef SpecificModuleCachePath,
836
                                     StringRef ExistingModuleCachePath,
837
                                     DiagnosticsEngine *Diags,
838
                                     const LangOptions &LangOpts,
839
0
                                     const PreprocessorOptions &PPOpts) {
840
0
  if (LangOpts.Modules) {
841
0
    if (SpecificModuleCachePath != ExistingModuleCachePath &&
842
0
        !PPOpts.AllowPCHWithDifferentModulesCachePath) {
843
0
      if (Diags)
844
0
        Diags->Report(diag::err_pch_modulecache_mismatch)
845
0
          << SpecificModuleCachePath << ExistingModuleCachePath;
846
0
      return true;
847
0
    }
848
0
  }
849
850
0
  return false;
851
0
}
852
853
bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
854
                                           StringRef SpecificModuleCachePath,
855
0
                                           bool Complain) {
856
0
  return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
857
0
                                  PP.getHeaderSearchInfo().getModuleCachePath(),
858
0
                                  Complain ? &Reader.Diags : nullptr,
859
0
                                  PP.getLangOpts(), PP.getPreprocessorOpts());
860
0
}
861
862
0
void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
863
0
  PP.setCounterValue(Value);
864
0
}
865
866
//===----------------------------------------------------------------------===//
867
// AST reader implementation
868
//===----------------------------------------------------------------------===//
869
870
0
static uint64_t readULEB(const unsigned char *&P) {
871
0
  unsigned Length = 0;
872
0
  const char *Error = nullptr;
873
874
0
  uint64_t Val = llvm::decodeULEB128(P, &Length, nullptr, &Error);
875
0
  if (Error)
876
0
    llvm::report_fatal_error(Error);
877
0
  P += Length;
878
0
  return Val;
879
0
}
880
881
/// Read ULEB-encoded key length and data length.
882
static std::pair<unsigned, unsigned>
883
0
readULEBKeyDataLength(const unsigned char *&P) {
884
0
  unsigned KeyLen = readULEB(P);
885
0
  if ((unsigned)KeyLen != KeyLen)
886
0
    llvm::report_fatal_error("key too large");
887
888
0
  unsigned DataLen = readULEB(P);
889
0
  if ((unsigned)DataLen != DataLen)
890
0
    llvm::report_fatal_error("data too large");
891
892
0
  return std::make_pair(KeyLen, DataLen);
893
0
}
894
895
void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
896
0
                                           bool TakeOwnership) {
897
0
  DeserializationListener = Listener;
898
0
  OwnsDeserializationListener = TakeOwnership;
899
0
}
900
901
0
unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
902
0
  return serialization::ComputeHash(Sel);
903
0
}
904
905
std::pair<unsigned, unsigned>
906
0
ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
907
0
  return readULEBKeyDataLength(d);
908
0
}
909
910
ASTSelectorLookupTrait::internal_key_type
911
0
ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
912
0
  using namespace llvm::support;
913
914
0
  SelectorTable &SelTable = Reader.getContext().Selectors;
915
0
  unsigned N =
916
0
      endian::readNext<uint16_t, llvm::endianness::little, unaligned>(d);
917
0
  IdentifierInfo *FirstII = Reader.getLocalIdentifier(
918
0
      F, endian::readNext<uint32_t, llvm::endianness::little, unaligned>(d));
919
0
  if (N == 0)
920
0
    return SelTable.getNullarySelector(FirstII);
921
0
  else if (N == 1)
922
0
    return SelTable.getUnarySelector(FirstII);
923
924
0
  SmallVector<IdentifierInfo *, 16> Args;
925
0
  Args.push_back(FirstII);
926
0
  for (unsigned I = 1; I != N; ++I)
927
0
    Args.push_back(Reader.getLocalIdentifier(
928
0
        F, endian::readNext<uint32_t, llvm::endianness::little, unaligned>(d)));
929
930
0
  return SelTable.getSelector(N, Args.data());
931
0
}
932
933
ASTSelectorLookupTrait::data_type
934
ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
935
0
                                 unsigned DataLen) {
936
0
  using namespace llvm::support;
937
938
0
  data_type Result;
939
940
0
  Result.ID = Reader.getGlobalSelectorID(
941
0
      F, endian::readNext<uint32_t, llvm::endianness::little, unaligned>(d));
942
0
  unsigned FullInstanceBits =
943
0
      endian::readNext<uint16_t, llvm::endianness::little, unaligned>(d);
944
0
  unsigned FullFactoryBits =
945
0
      endian::readNext<uint16_t, llvm::endianness::little, unaligned>(d);
946
0
  Result.InstanceBits = FullInstanceBits & 0x3;
947
0
  Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
948
0
  Result.FactoryBits = FullFactoryBits & 0x3;
949
0
  Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
950
0
  unsigned NumInstanceMethods = FullInstanceBits >> 3;
951
0
  unsigned NumFactoryMethods = FullFactoryBits >> 3;
952
953
  // Load instance methods
954
0
  for (unsigned I = 0; I != NumInstanceMethods; ++I) {
955
0
    if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
956
0
            F,
957
0
            endian::readNext<uint32_t, llvm::endianness::little, unaligned>(d)))
958
0
      Result.Instance.push_back(Method);
959
0
  }
960
961
  // Load factory methods
962
0
  for (unsigned I = 0; I != NumFactoryMethods; ++I) {
963
0
    if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
964
0
            F,
965
0
            endian::readNext<uint32_t, llvm::endianness::little, unaligned>(d)))
966
0
      Result.Factory.push_back(Method);
967
0
  }
968
969
0
  return Result;
970
0
}
971
972
0
unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
973
0
  return llvm::djbHash(a);
974
0
}
975
976
std::pair<unsigned, unsigned>
977
0
ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
978
0
  return readULEBKeyDataLength(d);
979
0
}
980
981
ASTIdentifierLookupTraitBase::internal_key_type
982
0
ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
983
0
  assert(n >= 2 && d[n-1] == '\0');
984
0
  return StringRef((const char*) d, n-1);
985
0
}
986
987
/// Whether the given identifier is "interesting".
988
static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
989
0
                                    bool IsModule) {
990
0
  return II.hadMacroDefinition() || II.isPoisoned() ||
991
0
         (!IsModule && II.getObjCOrBuiltinID()) ||
992
0
         II.hasRevertedTokenIDToIdentifier() ||
993
0
         (!(IsModule && Reader.getPreprocessor().getLangOpts().CPlusPlus) &&
994
0
          II.getFETokenInfo());
995
0
}
996
997
0
static bool readBit(unsigned &Bits) {
998
0
  bool Value = Bits & 0x1;
999
0
  Bits >>= 1;
1000
0
  return Value;
1001
0
}
1002
1003
0
IdentID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) {
1004
0
  using namespace llvm::support;
1005
1006
0
  unsigned RawID =
1007
0
      endian::readNext<uint32_t, llvm::endianness::little, unaligned>(d);
1008
0
  return Reader.getGlobalIdentifierID(F, RawID >> 1);
1009
0
}
1010
1011
0
static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II) {
1012
0
  if (!II.isFromAST()) {
1013
0
    II.setIsFromAST();
1014
0
    bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
1015
0
    if (isInterestingIdentifier(Reader, II, IsModule))
1016
0
      II.setChangedSinceDeserialization();
1017
0
  }
1018
0
}
1019
1020
IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
1021
                                                   const unsigned char* d,
1022
0
                                                   unsigned DataLen) {
1023
0
  using namespace llvm::support;
1024
1025
0
  unsigned RawID =
1026
0
      endian::readNext<uint32_t, llvm::endianness::little, unaligned>(d);
1027
0
  bool IsInteresting = RawID & 0x01;
1028
1029
  // Wipe out the "is interesting" bit.
1030
0
  RawID = RawID >> 1;
1031
1032
  // Build the IdentifierInfo and link the identifier ID with it.
1033
0
  IdentifierInfo *II = KnownII;
1034
0
  if (!II) {
1035
0
    II = &Reader.getIdentifierTable().getOwn(k);
1036
0
    KnownII = II;
1037
0
  }
1038
0
  markIdentifierFromAST(Reader, *II);
1039
0
  Reader.markIdentifierUpToDate(II);
1040
1041
0
  IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
1042
0
  if (!IsInteresting) {
1043
    // For uninteresting identifiers, there's nothing else to do. Just notify
1044
    // the reader that we've finished loading this identifier.
1045
0
    Reader.SetIdentifierInfo(ID, II);
1046
0
    return II;
1047
0
  }
1048
1049
0
  unsigned ObjCOrBuiltinID =
1050
0
      endian::readNext<uint16_t, llvm::endianness::little, unaligned>(d);
1051
0
  unsigned Bits =
1052
0
      endian::readNext<uint16_t, llvm::endianness::little, unaligned>(d);
1053
0
  bool CPlusPlusOperatorKeyword = readBit(Bits);
1054
0
  bool HasRevertedTokenIDToIdentifier = readBit(Bits);
1055
0
  bool Poisoned = readBit(Bits);
1056
0
  bool ExtensionToken = readBit(Bits);
1057
0
  bool HadMacroDefinition = readBit(Bits);
1058
1059
0
  assert(Bits == 0 && "Extra bits in the identifier?");
1060
0
  DataLen -= 8;
1061
1062
  // Set or check the various bits in the IdentifierInfo structure.
1063
  // Token IDs are read-only.
1064
0
  if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
1065
0
    II->revertTokenIDToIdentifier();
1066
0
  if (!F.isModule())
1067
0
    II->setObjCOrBuiltinID(ObjCOrBuiltinID);
1068
0
  assert(II->isExtensionToken() == ExtensionToken &&
1069
0
         "Incorrect extension token flag");
1070
0
  (void)ExtensionToken;
1071
0
  if (Poisoned)
1072
0
    II->setIsPoisoned(true);
1073
0
  assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
1074
0
         "Incorrect C++ operator keyword flag");
1075
0
  (void)CPlusPlusOperatorKeyword;
1076
1077
  // If this identifier is a macro, deserialize the macro
1078
  // definition.
1079
0
  if (HadMacroDefinition) {
1080
0
    uint32_t MacroDirectivesOffset =
1081
0
        endian::readNext<uint32_t, llvm::endianness::little, unaligned>(d);
1082
0
    DataLen -= 4;
1083
1084
0
    Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
1085
0
  }
1086
1087
0
  Reader.SetIdentifierInfo(ID, II);
1088
1089
  // Read all of the declarations visible at global scope with this
1090
  // name.
1091
0
  if (DataLen > 0) {
1092
0
    SmallVector<uint32_t, 4> DeclIDs;
1093
0
    for (; DataLen > 0; DataLen -= 4)
1094
0
      DeclIDs.push_back(Reader.getGlobalDeclID(
1095
0
          F,
1096
0
          endian::readNext<uint32_t, llvm::endianness::little, unaligned>(d)));
1097
0
    Reader.SetGloballyVisibleDecls(II, DeclIDs);
1098
0
  }
1099
1100
0
  return II;
1101
0
}
1102
1103
DeclarationNameKey::DeclarationNameKey(DeclarationName Name)
1104
0
    : Kind(Name.getNameKind()) {
1105
0
  switch (Kind) {
1106
0
  case DeclarationName::Identifier:
1107
0
    Data = (uint64_t)Name.getAsIdentifierInfo();
1108
0
    break;
1109
0
  case DeclarationName::ObjCZeroArgSelector:
1110
0
  case DeclarationName::ObjCOneArgSelector:
1111
0
  case DeclarationName::ObjCMultiArgSelector:
1112
0
    Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
1113
0
    break;
1114
0
  case DeclarationName::CXXOperatorName:
1115
0
    Data = Name.getCXXOverloadedOperator();
1116
0
    break;
1117
0
  case DeclarationName::CXXLiteralOperatorName:
1118
0
    Data = (uint64_t)Name.getCXXLiteralIdentifier();
1119
0
    break;
1120
0
  case DeclarationName::CXXDeductionGuideName:
1121
0
    Data = (uint64_t)Name.getCXXDeductionGuideTemplate()
1122
0
               ->getDeclName().getAsIdentifierInfo();
1123
0
    break;
1124
0
  case DeclarationName::CXXConstructorName:
1125
0
  case DeclarationName::CXXDestructorName:
1126
0
  case DeclarationName::CXXConversionFunctionName:
1127
0
  case DeclarationName::CXXUsingDirective:
1128
0
    Data = 0;
1129
0
    break;
1130
0
  }
1131
0
}
1132
1133
0
unsigned DeclarationNameKey::getHash() const {
1134
0
  llvm::FoldingSetNodeID ID;
1135
0
  ID.AddInteger(Kind);
1136
1137
0
  switch (Kind) {
1138
0
  case DeclarationName::Identifier:
1139
0
  case DeclarationName::CXXLiteralOperatorName:
1140
0
  case DeclarationName::CXXDeductionGuideName:
1141
0
    ID.AddString(((IdentifierInfo*)Data)->getName());
1142
0
    break;
1143
0
  case DeclarationName::ObjCZeroArgSelector:
1144
0
  case DeclarationName::ObjCOneArgSelector:
1145
0
  case DeclarationName::ObjCMultiArgSelector:
1146
0
    ID.AddInteger(serialization::ComputeHash(Selector(Data)));
1147
0
    break;
1148
0
  case DeclarationName::CXXOperatorName:
1149
0
    ID.AddInteger((OverloadedOperatorKind)Data);
1150
0
    break;
1151
0
  case DeclarationName::CXXConstructorName:
1152
0
  case DeclarationName::CXXDestructorName:
1153
0
  case DeclarationName::CXXConversionFunctionName:
1154
0
  case DeclarationName::CXXUsingDirective:
1155
0
    break;
1156
0
  }
1157
1158
0
  return ID.ComputeHash();
1159
0
}
1160
1161
ModuleFile *
1162
0
ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
1163
0
  using namespace llvm::support;
1164
1165
0
  uint32_t ModuleFileID =
1166
0
      endian::readNext<uint32_t, llvm::endianness::little, unaligned>(d);
1167
0
  return Reader.getLocalModuleFile(F, ModuleFileID);
1168
0
}
1169
1170
std::pair<unsigned, unsigned>
1171
0
ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
1172
0
  return readULEBKeyDataLength(d);
1173
0
}
1174
1175
ASTDeclContextNameLookupTrait::internal_key_type
1176
0
ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
1177
0
  using namespace llvm::support;
1178
1179
0
  auto Kind = (DeclarationName::NameKind)*d++;
1180
0
  uint64_t Data;
1181
0
  switch (Kind) {
1182
0
  case DeclarationName::Identifier:
1183
0
  case DeclarationName::CXXLiteralOperatorName:
1184
0
  case DeclarationName::CXXDeductionGuideName:
1185
0
    Data = (uint64_t)Reader.getLocalIdentifier(
1186
0
        F, endian::readNext<uint32_t, llvm::endianness::little, unaligned>(d));
1187
0
    break;
1188
0
  case DeclarationName::ObjCZeroArgSelector:
1189
0
  case DeclarationName::ObjCOneArgSelector:
1190
0
  case DeclarationName::ObjCMultiArgSelector:
1191
0
    Data =
1192
0
        (uint64_t)Reader
1193
0
            .getLocalSelector(
1194
0
                F,
1195
0
                endian::readNext<uint32_t, llvm::endianness::little, unaligned>(
1196
0
                    d))
1197
0
            .getAsOpaquePtr();
1198
0
    break;
1199
0
  case DeclarationName::CXXOperatorName:
1200
0
    Data = *d++; // OverloadedOperatorKind
1201
0
    break;
1202
0
  case DeclarationName::CXXConstructorName:
1203
0
  case DeclarationName::CXXDestructorName:
1204
0
  case DeclarationName::CXXConversionFunctionName:
1205
0
  case DeclarationName::CXXUsingDirective:
1206
0
    Data = 0;
1207
0
    break;
1208
0
  }
1209
1210
0
  return DeclarationNameKey(Kind, Data);
1211
0
}
1212
1213
void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
1214
                                                 const unsigned char *d,
1215
                                                 unsigned DataLen,
1216
0
                                                 data_type_builder &Val) {
1217
0
  using namespace llvm::support;
1218
1219
0
  for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) {
1220
0
    uint32_t LocalID =
1221
0
        endian::readNext<uint32_t, llvm::endianness::little, unaligned>(d);
1222
0
    Val.insert(Reader.getGlobalDeclID(F, LocalID));
1223
0
  }
1224
0
}
1225
1226
bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
1227
                                              BitstreamCursor &Cursor,
1228
                                              uint64_t Offset,
1229
0
                                              DeclContext *DC) {
1230
0
  assert(Offset != 0);
1231
1232
0
  SavedStreamPosition SavedPosition(Cursor);
1233
0
  if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1234
0
    Error(std::move(Err));
1235
0
    return true;
1236
0
  }
1237
1238
0
  RecordData Record;
1239
0
  StringRef Blob;
1240
0
  Expected<unsigned> MaybeCode = Cursor.ReadCode();
1241
0
  if (!MaybeCode) {
1242
0
    Error(MaybeCode.takeError());
1243
0
    return true;
1244
0
  }
1245
0
  unsigned Code = MaybeCode.get();
1246
1247
0
  Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1248
0
  if (!MaybeRecCode) {
1249
0
    Error(MaybeRecCode.takeError());
1250
0
    return true;
1251
0
  }
1252
0
  unsigned RecCode = MaybeRecCode.get();
1253
0
  if (RecCode != DECL_CONTEXT_LEXICAL) {
1254
0
    Error("Expected lexical block");
1255
0
    return true;
1256
0
  }
1257
1258
0
  assert(!isa<TranslationUnitDecl>(DC) &&
1259
0
         "expected a TU_UPDATE_LEXICAL record for TU");
1260
  // If we are handling a C++ class template instantiation, we can see multiple
1261
  // lexical updates for the same record. It's important that we select only one
1262
  // of them, so that field numbering works properly. Just pick the first one we
1263
  // see.
1264
0
  auto &Lex = LexicalDecls[DC];
1265
0
  if (!Lex.first) {
1266
0
    Lex = std::make_pair(
1267
0
        &M, llvm::ArrayRef(
1268
0
                reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
1269
0
                    Blob.data()),
1270
0
                Blob.size() / 4));
1271
0
  }
1272
0
  DC->setHasExternalLexicalStorage(true);
1273
0
  return false;
1274
0
}
1275
1276
bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1277
                                              BitstreamCursor &Cursor,
1278
                                              uint64_t Offset,
1279
0
                                              DeclID ID) {
1280
0
  assert(Offset != 0);
1281
1282
0
  SavedStreamPosition SavedPosition(Cursor);
1283
0
  if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1284
0
    Error(std::move(Err));
1285
0
    return true;
1286
0
  }
1287
1288
0
  RecordData Record;
1289
0
  StringRef Blob;
1290
0
  Expected<unsigned> MaybeCode = Cursor.ReadCode();
1291
0
  if (!MaybeCode) {
1292
0
    Error(MaybeCode.takeError());
1293
0
    return true;
1294
0
  }
1295
0
  unsigned Code = MaybeCode.get();
1296
1297
0
  Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1298
0
  if (!MaybeRecCode) {
1299
0
    Error(MaybeRecCode.takeError());
1300
0
    return true;
1301
0
  }
1302
0
  unsigned RecCode = MaybeRecCode.get();
1303
0
  if (RecCode != DECL_CONTEXT_VISIBLE) {
1304
0
    Error("Expected visible lookup table block");
1305
0
    return true;
1306
0
  }
1307
1308
  // We can't safely determine the primary context yet, so delay attaching the
1309
  // lookup table until we're done with recursive deserialization.
1310
0
  auto *Data = (const unsigned char*)Blob.data();
1311
0
  PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
1312
0
  return false;
1313
0
}
1314
1315
0
void ASTReader::Error(StringRef Msg) const {
1316
0
  Error(diag::err_fe_pch_malformed, Msg);
1317
0
  if (PP.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
1318
0
      !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
1319
0
    Diag(diag::note_module_cache_path)
1320
0
      << PP.getHeaderSearchInfo().getModuleCachePath();
1321
0
  }
1322
0
}
1323
1324
void ASTReader::Error(unsigned DiagID, StringRef Arg1, StringRef Arg2,
1325
0
                      StringRef Arg3) const {
1326
0
  if (Diags.isDiagnosticInFlight())
1327
0
    Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2, Arg3);
1328
0
  else
1329
0
    Diag(DiagID) << Arg1 << Arg2 << Arg3;
1330
0
}
1331
1332
0
void ASTReader::Error(llvm::Error &&Err) const {
1333
0
  llvm::Error RemainingErr =
1334
0
      handleErrors(std::move(Err), [this](const DiagnosticError &E) {
1335
0
        auto Diag = E.getDiagnostic().second;
1336
1337
        // Ideally we'd just emit it, but have to handle a possible in-flight
1338
        // diagnostic. Note that the location is currently ignored as well.
1339
0
        auto NumArgs = Diag.getStorage()->NumDiagArgs;
1340
0
        assert(NumArgs <= 3 && "Can only have up to 3 arguments");
1341
0
        StringRef Arg1, Arg2, Arg3;
1342
0
        switch (NumArgs) {
1343
0
        case 3:
1344
0
          Arg3 = Diag.getStringArg(2);
1345
0
          [[fallthrough]];
1346
0
        case 2:
1347
0
          Arg2 = Diag.getStringArg(1);
1348
0
          [[fallthrough]];
1349
0
        case 1:
1350
0
          Arg1 = Diag.getStringArg(0);
1351
0
        }
1352
0
        Error(Diag.getDiagID(), Arg1, Arg2, Arg3);
1353
0
      });
1354
0
  if (RemainingErr)
1355
0
    Error(toString(std::move(RemainingErr)));
1356
0
}
1357
1358
//===----------------------------------------------------------------------===//
1359
// Source Manager Deserialization
1360
//===----------------------------------------------------------------------===//
1361
1362
/// Read the line table in the source manager block.
1363
0
void ASTReader::ParseLineTable(ModuleFile &F, const RecordData &Record) {
1364
0
  unsigned Idx = 0;
1365
0
  LineTableInfo &LineTable = SourceMgr.getLineTable();
1366
1367
  // Parse the file names
1368
0
  std::map<int, int> FileIDs;
1369
0
  FileIDs[-1] = -1; // For unspecified filenames.
1370
0
  for (unsigned I = 0; Record[Idx]; ++I) {
1371
    // Extract the file name
1372
0
    auto Filename = ReadPath(F, Record, Idx);
1373
0
    FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1374
0
  }
1375
0
  ++Idx;
1376
1377
  // Parse the line entries
1378
0
  std::vector<LineEntry> Entries;
1379
0
  while (Idx < Record.size()) {
1380
0
    FileID FID = ReadFileID(F, Record, Idx);
1381
1382
    // Extract the line entries
1383
0
    unsigned NumEntries = Record[Idx++];
1384
0
    assert(NumEntries && "no line entries for file ID");
1385
0
    Entries.clear();
1386
0
    Entries.reserve(NumEntries);
1387
0
    for (unsigned I = 0; I != NumEntries; ++I) {
1388
0
      unsigned FileOffset = Record[Idx++];
1389
0
      unsigned LineNo = Record[Idx++];
1390
0
      int FilenameID = FileIDs[Record[Idx++]];
1391
0
      SrcMgr::CharacteristicKind FileKind
1392
0
        = (SrcMgr::CharacteristicKind)Record[Idx++];
1393
0
      unsigned IncludeOffset = Record[Idx++];
1394
0
      Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1395
0
                                       FileKind, IncludeOffset));
1396
0
    }
1397
0
    LineTable.AddEntry(FID, Entries);
1398
0
  }
1399
0
}
1400
1401
/// Read a source manager block
1402
0
llvm::Error ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1403
0
  using namespace SrcMgr;
1404
1405
0
  BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
1406
1407
  // Set the source-location entry cursor to the current position in
1408
  // the stream. This cursor will be used to read the contents of the
1409
  // source manager block initially, and then lazily read
1410
  // source-location entries as needed.
1411
0
  SLocEntryCursor = F.Stream;
1412
1413
  // The stream itself is going to skip over the source manager block.
1414
0
  if (llvm::Error Err = F.Stream.SkipBlock())
1415
0
    return Err;
1416
1417
  // Enter the source manager block.
1418
0
  if (llvm::Error Err = SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID))
1419
0
    return Err;
1420
0
  F.SourceManagerBlockStartOffset = SLocEntryCursor.GetCurrentBitNo();
1421
1422
0
  RecordData Record;
1423
0
  while (true) {
1424
0
    Expected<llvm::BitstreamEntry> MaybeE =
1425
0
        SLocEntryCursor.advanceSkippingSubblocks();
1426
0
    if (!MaybeE)
1427
0
      return MaybeE.takeError();
1428
0
    llvm::BitstreamEntry E = MaybeE.get();
1429
1430
0
    switch (E.Kind) {
1431
0
    case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1432
0
    case llvm::BitstreamEntry::Error:
1433
0
      return llvm::createStringError(std::errc::illegal_byte_sequence,
1434
0
                                     "malformed block record in AST file");
1435
0
    case llvm::BitstreamEntry::EndBlock:
1436
0
      return llvm::Error::success();
1437
0
    case llvm::BitstreamEntry::Record:
1438
      // The interesting case.
1439
0
      break;
1440
0
    }
1441
1442
    // Read a record.
1443
0
    Record.clear();
1444
0
    StringRef Blob;
1445
0
    Expected<unsigned> MaybeRecord =
1446
0
        SLocEntryCursor.readRecord(E.ID, Record, &Blob);
1447
0
    if (!MaybeRecord)
1448
0
      return MaybeRecord.takeError();
1449
0
    switch (MaybeRecord.get()) {
1450
0
    default:  // Default behavior: ignore.
1451
0
      break;
1452
1453
0
    case SM_SLOC_FILE_ENTRY:
1454
0
    case SM_SLOC_BUFFER_ENTRY:
1455
0
    case SM_SLOC_EXPANSION_ENTRY:
1456
      // Once we hit one of the source location entries, we're done.
1457
0
      return llvm::Error::success();
1458
0
    }
1459
0
  }
1460
0
}
1461
1462
llvm::Expected<SourceLocation::UIntTy>
1463
0
ASTReader::readSLocOffset(ModuleFile *F, unsigned Index) {
1464
0
  BitstreamCursor &Cursor = F->SLocEntryCursor;
1465
0
  SavedStreamPosition SavedPosition(Cursor);
1466
0
  if (llvm::Error Err = Cursor.JumpToBit(F->SLocEntryOffsetsBase +
1467
0
                                         F->SLocEntryOffsets[Index]))
1468
0
    return std::move(Err);
1469
1470
0
  Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
1471
0
  if (!MaybeEntry)
1472
0
    return MaybeEntry.takeError();
1473
1474
0
  llvm::BitstreamEntry Entry = MaybeEntry.get();
1475
0
  if (Entry.Kind != llvm::BitstreamEntry::Record)
1476
0
    return llvm::createStringError(
1477
0
        std::errc::illegal_byte_sequence,
1478
0
        "incorrectly-formatted source location entry in AST file");
1479
1480
0
  RecordData Record;
1481
0
  StringRef Blob;
1482
0
  Expected<unsigned> MaybeSLOC = Cursor.readRecord(Entry.ID, Record, &Blob);
1483
0
  if (!MaybeSLOC)
1484
0
    return MaybeSLOC.takeError();
1485
1486
0
  switch (MaybeSLOC.get()) {
1487
0
  default:
1488
0
    return llvm::createStringError(
1489
0
        std::errc::illegal_byte_sequence,
1490
0
        "incorrectly-formatted source location entry in AST file");
1491
0
  case SM_SLOC_FILE_ENTRY:
1492
0
  case SM_SLOC_BUFFER_ENTRY:
1493
0
  case SM_SLOC_EXPANSION_ENTRY:
1494
0
    return F->SLocEntryBaseOffset + Record[0];
1495
0
  }
1496
0
}
1497
1498
0
int ASTReader::getSLocEntryID(SourceLocation::UIntTy SLocOffset) {
1499
0
  auto SLocMapI =
1500
0
      GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset - SLocOffset - 1);
1501
0
  assert(SLocMapI != GlobalSLocOffsetMap.end() &&
1502
0
         "Corrupted global sloc offset map");
1503
0
  ModuleFile *F = SLocMapI->second;
1504
1505
0
  bool Invalid = false;
1506
1507
0
  auto It = llvm::upper_bound(
1508
0
      llvm::index_range(0, F->LocalNumSLocEntries), SLocOffset,
1509
0
      [&](SourceLocation::UIntTy Offset, std::size_t LocalIndex) {
1510
0
        int ID = F->SLocEntryBaseID + LocalIndex;
1511
0
        std::size_t Index = -ID - 2;
1512
0
        if (!SourceMgr.SLocEntryOffsetLoaded[Index]) {
1513
0
          assert(!SourceMgr.SLocEntryLoaded[Index]);
1514
0
          auto MaybeEntryOffset = readSLocOffset(F, LocalIndex);
1515
0
          if (!MaybeEntryOffset) {
1516
0
            Error(MaybeEntryOffset.takeError());
1517
0
            Invalid = true;
1518
0
            return true;
1519
0
          }
1520
0
          SourceMgr.LoadedSLocEntryTable[Index] =
1521
0
              SrcMgr::SLocEntry::getOffsetOnly(*MaybeEntryOffset);
1522
0
          SourceMgr.SLocEntryOffsetLoaded[Index] = true;
1523
0
        }
1524
0
        return Offset < SourceMgr.LoadedSLocEntryTable[Index].getOffset();
1525
0
      });
1526
1527
0
  if (Invalid)
1528
0
    return 0;
1529
1530
  // The iterator points to the first entry with start offset greater than the
1531
  // offset of interest. The previous entry must contain the offset of interest.
1532
0
  return F->SLocEntryBaseID + *std::prev(It);
1533
0
}
1534
1535
0
bool ASTReader::ReadSLocEntry(int ID) {
1536
0
  if (ID == 0)
1537
0
    return false;
1538
1539
0
  if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1540
0
    Error("source location entry ID out-of-range for AST file");
1541
0
    return true;
1542
0
  }
1543
1544
  // Local helper to read the (possibly-compressed) buffer data following the
1545
  // entry record.
1546
0
  auto ReadBuffer = [this](
1547
0
      BitstreamCursor &SLocEntryCursor,
1548
0
      StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1549
0
    RecordData Record;
1550
0
    StringRef Blob;
1551
0
    Expected<unsigned> MaybeCode = SLocEntryCursor.ReadCode();
1552
0
    if (!MaybeCode) {
1553
0
      Error(MaybeCode.takeError());
1554
0
      return nullptr;
1555
0
    }
1556
0
    unsigned Code = MaybeCode.get();
1557
1558
0
    Expected<unsigned> MaybeRecCode =
1559
0
        SLocEntryCursor.readRecord(Code, Record, &Blob);
1560
0
    if (!MaybeRecCode) {
1561
0
      Error(MaybeRecCode.takeError());
1562
0
      return nullptr;
1563
0
    }
1564
0
    unsigned RecCode = MaybeRecCode.get();
1565
1566
0
    if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
1567
      // Inspect the first byte to differentiate zlib (\x78) and zstd
1568
      // (little-endian 0xFD2FB528).
1569
0
      const llvm::compression::Format F =
1570
0
          Blob.size() > 0 && Blob.data()[0] == 0x78
1571
0
              ? llvm::compression::Format::Zlib
1572
0
              : llvm::compression::Format::Zstd;
1573
0
      if (const char *Reason = llvm::compression::getReasonIfUnsupported(F)) {
1574
0
        Error(Reason);
1575
0
        return nullptr;
1576
0
      }
1577
0
      SmallVector<uint8_t, 0> Decompressed;
1578
0
      if (llvm::Error E = llvm::compression::decompress(
1579
0
              F, llvm::arrayRefFromStringRef(Blob), Decompressed, Record[0])) {
1580
0
        Error("could not decompress embedded file contents: " +
1581
0
              llvm::toString(std::move(E)));
1582
0
        return nullptr;
1583
0
      }
1584
0
      return llvm::MemoryBuffer::getMemBufferCopy(
1585
0
          llvm::toStringRef(Decompressed), Name);
1586
0
    } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1587
0
      return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1588
0
    } else {
1589
0
      Error("AST record has invalid code");
1590
0
      return nullptr;
1591
0
    }
1592
0
  };
1593
1594
0
  ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1595
0
  if (llvm::Error Err = F->SLocEntryCursor.JumpToBit(
1596
0
          F->SLocEntryOffsetsBase +
1597
0
          F->SLocEntryOffsets[ID - F->SLocEntryBaseID])) {
1598
0
    Error(std::move(Err));
1599
0
    return true;
1600
0
  }
1601
1602
0
  BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
1603
0
  SourceLocation::UIntTy BaseOffset = F->SLocEntryBaseOffset;
1604
1605
0
  ++NumSLocEntriesRead;
1606
0
  Expected<llvm::BitstreamEntry> MaybeEntry = SLocEntryCursor.advance();
1607
0
  if (!MaybeEntry) {
1608
0
    Error(MaybeEntry.takeError());
1609
0
    return true;
1610
0
  }
1611
0
  llvm::BitstreamEntry Entry = MaybeEntry.get();
1612
1613
0
  if (Entry.Kind != llvm::BitstreamEntry::Record) {
1614
0
    Error("incorrectly-formatted source location entry in AST file");
1615
0
    return true;
1616
0
  }
1617
1618
0
  RecordData Record;
1619
0
  StringRef Blob;
1620
0
  Expected<unsigned> MaybeSLOC =
1621
0
      SLocEntryCursor.readRecord(Entry.ID, Record, &Blob);
1622
0
  if (!MaybeSLOC) {
1623
0
    Error(MaybeSLOC.takeError());
1624
0
    return true;
1625
0
  }
1626
0
  switch (MaybeSLOC.get()) {
1627
0
  default:
1628
0
    Error("incorrectly-formatted source location entry in AST file");
1629
0
    return true;
1630
1631
0
  case SM_SLOC_FILE_ENTRY: {
1632
    // We will detect whether a file changed and return 'Failure' for it, but
1633
    // we will also try to fail gracefully by setting up the SLocEntry.
1634
0
    unsigned InputID = Record[4];
1635
0
    InputFile IF = getInputFile(*F, InputID);
1636
0
    OptionalFileEntryRef File = IF.getFile();
1637
0
    bool OverriddenBuffer = IF.isOverridden();
1638
1639
    // Note that we only check if a File was returned. If it was out-of-date
1640
    // we have complained but we will continue creating a FileID to recover
1641
    // gracefully.
1642
0
    if (!File)
1643
0
      return true;
1644
1645
0
    SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1646
0
    if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1647
      // This is the module's main file.
1648
0
      IncludeLoc = getImportLocation(F);
1649
0
    }
1650
0
    SrcMgr::CharacteristicKind
1651
0
      FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1652
0
    FileID FID = SourceMgr.createFileID(*File, IncludeLoc, FileCharacter, ID,
1653
0
                                        BaseOffset + Record[0]);
1654
0
    SrcMgr::FileInfo &FileInfo =
1655
0
          const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1656
0
    FileInfo.NumCreatedFIDs = Record[5];
1657
0
    if (Record[3])
1658
0
      FileInfo.setHasLineDirectives();
1659
1660
0
    unsigned NumFileDecls = Record[7];
1661
0
    if (NumFileDecls && ContextObj) {
1662
0
      const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1663
0
      assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1664
0
      FileDeclIDs[FID] =
1665
0
          FileDeclsInfo(F, llvm::ArrayRef(FirstDecl, NumFileDecls));
1666
0
    }
1667
1668
0
    const SrcMgr::ContentCache &ContentCache =
1669
0
        SourceMgr.getOrCreateContentCache(*File, isSystem(FileCharacter));
1670
0
    if (OverriddenBuffer && !ContentCache.BufferOverridden &&
1671
0
        ContentCache.ContentsEntry == ContentCache.OrigEntry &&
1672
0
        !ContentCache.getBufferIfLoaded()) {
1673
0
      auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
1674
0
      if (!Buffer)
1675
0
        return true;
1676
0
      SourceMgr.overrideFileContents(*File, std::move(Buffer));
1677
0
    }
1678
1679
0
    break;
1680
0
  }
1681
1682
0
  case SM_SLOC_BUFFER_ENTRY: {
1683
0
    const char *Name = Blob.data();
1684
0
    unsigned Offset = Record[0];
1685
0
    SrcMgr::CharacteristicKind
1686
0
      FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1687
0
    SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1688
0
    if (IncludeLoc.isInvalid() && F->isModule()) {
1689
0
      IncludeLoc = getImportLocation(F);
1690
0
    }
1691
1692
0
    auto Buffer = ReadBuffer(SLocEntryCursor, Name);
1693
0
    if (!Buffer)
1694
0
      return true;
1695
0
    FileID FID = SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
1696
0
                                        BaseOffset + Offset, IncludeLoc);
1697
0
    if (Record[3]) {
1698
0
      auto &FileInfo =
1699
0
          const_cast<SrcMgr::FileInfo &>(SourceMgr.getSLocEntry(FID).getFile());
1700
0
      FileInfo.setHasLineDirectives();
1701
0
    }
1702
0
    break;
1703
0
  }
1704
1705
0
  case SM_SLOC_EXPANSION_ENTRY: {
1706
0
    LocSeq::State Seq;
1707
0
    SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1], Seq);
1708
0
    SourceLocation ExpansionBegin = ReadSourceLocation(*F, Record[2], Seq);
1709
0
    SourceLocation ExpansionEnd = ReadSourceLocation(*F, Record[3], Seq);
1710
0
    SourceMgr.createExpansionLoc(SpellingLoc, ExpansionBegin, ExpansionEnd,
1711
0
                                 Record[5], Record[4], ID,
1712
0
                                 BaseOffset + Record[0]);
1713
0
    break;
1714
0
  }
1715
0
  }
1716
1717
0
  return false;
1718
0
}
1719
1720
0
std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1721
0
  if (ID == 0)
1722
0
    return std::make_pair(SourceLocation(), "");
1723
1724
0
  if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1725
0
    Error("source location entry ID out-of-range for AST file");
1726
0
    return std::make_pair(SourceLocation(), "");
1727
0
  }
1728
1729
  // Find which module file this entry lands in.
1730
0
  ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
1731
0
  if (!M->isModule())
1732
0
    return std::make_pair(SourceLocation(), "");
1733
1734
  // FIXME: Can we map this down to a particular submodule? That would be
1735
  // ideal.
1736
0
  return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
1737
0
}
1738
1739
/// Find the location where the module F is imported.
1740
0
SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1741
0
  if (F->ImportLoc.isValid())
1742
0
    return F->ImportLoc;
1743
1744
  // Otherwise we have a PCH. It's considered to be "imported" at the first
1745
  // location of its includer.
1746
0
  if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
1747
    // Main file is the importer.
1748
0
    assert(SourceMgr.getMainFileID().isValid() && "missing main file");
1749
0
    return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
1750
0
  }
1751
0
  return F->ImportedBy[0]->FirstLoc;
1752
0
}
1753
1754
/// Enter a subblock of the specified BlockID with the specified cursor. Read
1755
/// the abbreviations that are at the top of the block and then leave the cursor
1756
/// pointing into the block.
1757
llvm::Error ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor,
1758
                                        unsigned BlockID,
1759
0
                                        uint64_t *StartOfBlockOffset) {
1760
0
  if (llvm::Error Err = Cursor.EnterSubBlock(BlockID))
1761
0
    return Err;
1762
1763
0
  if (StartOfBlockOffset)
1764
0
    *StartOfBlockOffset = Cursor.GetCurrentBitNo();
1765
1766
0
  while (true) {
1767
0
    uint64_t Offset = Cursor.GetCurrentBitNo();
1768
0
    Expected<unsigned> MaybeCode = Cursor.ReadCode();
1769
0
    if (!MaybeCode)
1770
0
      return MaybeCode.takeError();
1771
0
    unsigned Code = MaybeCode.get();
1772
1773
    // We expect all abbrevs to be at the start of the block.
1774
0
    if (Code != llvm::bitc::DEFINE_ABBREV) {
1775
0
      if (llvm::Error Err = Cursor.JumpToBit(Offset))
1776
0
        return Err;
1777
0
      return llvm::Error::success();
1778
0
    }
1779
0
    if (llvm::Error Err = Cursor.ReadAbbrevRecord())
1780
0
      return Err;
1781
0
  }
1782
0
}
1783
1784
Token ASTReader::ReadToken(ModuleFile &M, const RecordDataImpl &Record,
1785
0
                           unsigned &Idx) {
1786
0
  Token Tok;
1787
0
  Tok.startToken();
1788
0
  Tok.setLocation(ReadSourceLocation(M, Record, Idx));
1789
0
  Tok.setKind((tok::TokenKind)Record[Idx++]);
1790
0
  Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1791
1792
0
  if (Tok.isAnnotation()) {
1793
0
    Tok.setAnnotationEndLoc(ReadSourceLocation(M, Record, Idx));
1794
0
    switch (Tok.getKind()) {
1795
0
    case tok::annot_pragma_loop_hint: {
1796
0
      auto *Info = new (PP.getPreprocessorAllocator()) PragmaLoopHintInfo;
1797
0
      Info->PragmaName = ReadToken(M, Record, Idx);
1798
0
      Info->Option = ReadToken(M, Record, Idx);
1799
0
      unsigned NumTokens = Record[Idx++];
1800
0
      SmallVector<Token, 4> Toks;
1801
0
      Toks.reserve(NumTokens);
1802
0
      for (unsigned I = 0; I < NumTokens; ++I)
1803
0
        Toks.push_back(ReadToken(M, Record, Idx));
1804
0
      Info->Toks = llvm::ArrayRef(Toks).copy(PP.getPreprocessorAllocator());
1805
0
      Tok.setAnnotationValue(static_cast<void *>(Info));
1806
0
      break;
1807
0
    }
1808
0
    case tok::annot_pragma_pack: {
1809
0
      auto *Info = new (PP.getPreprocessorAllocator()) Sema::PragmaPackInfo;
1810
0
      Info->Action = static_cast<Sema::PragmaMsStackAction>(Record[Idx++]);
1811
0
      auto SlotLabel = ReadString(Record, Idx);
1812
0
      Info->SlotLabel =
1813
0
          llvm::StringRef(SlotLabel).copy(PP.getPreprocessorAllocator());
1814
0
      Info->Alignment = ReadToken(M, Record, Idx);
1815
0
      Tok.setAnnotationValue(static_cast<void *>(Info));
1816
0
      break;
1817
0
    }
1818
    // Some annotation tokens do not use the PtrData field.
1819
0
    case tok::annot_pragma_openmp:
1820
0
    case tok::annot_pragma_openmp_end:
1821
0
    case tok::annot_pragma_unused:
1822
0
    case tok::annot_pragma_openacc:
1823
0
    case tok::annot_pragma_openacc_end:
1824
0
      break;
1825
0
    default:
1826
0
      llvm_unreachable("missing deserialization code for annotation token");
1827
0
    }
1828
0
  } else {
1829
0
    Tok.setLength(Record[Idx++]);
1830
0
    if (IdentifierInfo *II = getLocalIdentifier(M, Record[Idx++]))
1831
0
      Tok.setIdentifierInfo(II);
1832
0
  }
1833
0
  return Tok;
1834
0
}
1835
1836
0
MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
1837
0
  BitstreamCursor &Stream = F.MacroCursor;
1838
1839
  // Keep track of where we are in the stream, then jump back there
1840
  // after reading this macro.
1841
0
  SavedStreamPosition SavedPosition(Stream);
1842
1843
0
  if (llvm::Error Err = Stream.JumpToBit(Offset)) {
1844
    // FIXME this drops errors on the floor.
1845
0
    consumeError(std::move(Err));
1846
0
    return nullptr;
1847
0
  }
1848
0
  RecordData Record;
1849
0
  SmallVector<IdentifierInfo*, 16> MacroParams;
1850
0
  MacroInfo *Macro = nullptr;
1851
0
  llvm::MutableArrayRef<Token> MacroTokens;
1852
1853
0
  while (true) {
1854
    // Advance to the next record, but if we get to the end of the block, don't
1855
    // pop it (removing all the abbreviations from the cursor) since we want to
1856
    // be able to reseek within the block and read entries.
1857
0
    unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
1858
0
    Expected<llvm::BitstreamEntry> MaybeEntry =
1859
0
        Stream.advanceSkippingSubblocks(Flags);
1860
0
    if (!MaybeEntry) {
1861
0
      Error(MaybeEntry.takeError());
1862
0
      return Macro;
1863
0
    }
1864
0
    llvm::BitstreamEntry Entry = MaybeEntry.get();
1865
1866
0
    switch (Entry.Kind) {
1867
0
    case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1868
0
    case llvm::BitstreamEntry::Error:
1869
0
      Error("malformed block record in AST file");
1870
0
      return Macro;
1871
0
    case llvm::BitstreamEntry::EndBlock:
1872
0
      return Macro;
1873
0
    case llvm::BitstreamEntry::Record:
1874
      // The interesting case.
1875
0
      break;
1876
0
    }
1877
1878
    // Read a record.
1879
0
    Record.clear();
1880
0
    PreprocessorRecordTypes RecType;
1881
0
    if (Expected<unsigned> MaybeRecType = Stream.readRecord(Entry.ID, Record))
1882
0
      RecType = (PreprocessorRecordTypes)MaybeRecType.get();
1883
0
    else {
1884
0
      Error(MaybeRecType.takeError());
1885
0
      return Macro;
1886
0
    }
1887
0
    switch (RecType) {
1888
0
    case PP_MODULE_MACRO:
1889
0
    case PP_MACRO_DIRECTIVE_HISTORY:
1890
0
      return Macro;
1891
1892
0
    case PP_MACRO_OBJECT_LIKE:
1893
0
    case PP_MACRO_FUNCTION_LIKE: {
1894
      // If we already have a macro, that means that we've hit the end
1895
      // of the definition of the macro we were looking for. We're
1896
      // done.
1897
0
      if (Macro)
1898
0
        return Macro;
1899
1900
0
      unsigned NextIndex = 1; // Skip identifier ID.
1901
0
      SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
1902
0
      MacroInfo *MI = PP.AllocateMacroInfo(Loc);
1903
0
      MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
1904
0
      MI->setIsUsed(Record[NextIndex++]);
1905
0
      MI->setUsedForHeaderGuard(Record[NextIndex++]);
1906
0
      MacroTokens = MI->allocateTokens(Record[NextIndex++],
1907
0
                                       PP.getPreprocessorAllocator());
1908
0
      if (RecType == PP_MACRO_FUNCTION_LIKE) {
1909
        // Decode function-like macro info.
1910
0
        bool isC99VarArgs = Record[NextIndex++];
1911
0
        bool isGNUVarArgs = Record[NextIndex++];
1912
0
        bool hasCommaPasting = Record[NextIndex++];
1913
0
        MacroParams.clear();
1914
0
        unsigned NumArgs = Record[NextIndex++];
1915
0
        for (unsigned i = 0; i != NumArgs; ++i)
1916
0
          MacroParams.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1917
1918
        // Install function-like macro info.
1919
0
        MI->setIsFunctionLike();
1920
0
        if (isC99VarArgs) MI->setIsC99Varargs();
1921
0
        if (isGNUVarArgs) MI->setIsGNUVarargs();
1922
0
        if (hasCommaPasting) MI->setHasCommaPasting();
1923
0
        MI->setParameterList(MacroParams, PP.getPreprocessorAllocator());
1924
0
      }
1925
1926
      // Remember that we saw this macro last so that we add the tokens that
1927
      // form its body to it.
1928
0
      Macro = MI;
1929
1930
0
      if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1931
0
          Record[NextIndex]) {
1932
        // We have a macro definition. Register the association
1933
0
        PreprocessedEntityID
1934
0
            GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1935
0
        PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
1936
0
        PreprocessingRecord::PPEntityID PPID =
1937
0
            PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1938
0
        MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1939
0
            PPRec.getPreprocessedEntity(PPID));
1940
0
        if (PPDef)
1941
0
          PPRec.RegisterMacroDefinition(Macro, PPDef);
1942
0
      }
1943
1944
0
      ++NumMacrosRead;
1945
0
      break;
1946
0
    }
1947
1948
0
    case PP_TOKEN: {
1949
      // If we see a TOKEN before a PP_MACRO_*, then the file is
1950
      // erroneous, just pretend we didn't see this.
1951
0
      if (!Macro) break;
1952
0
      if (MacroTokens.empty()) {
1953
0
        Error("unexpected number of macro tokens for a macro in AST file");
1954
0
        return Macro;
1955
0
      }
1956
1957
0
      unsigned Idx = 0;
1958
0
      MacroTokens[0] = ReadToken(F, Record, Idx);
1959
0
      MacroTokens = MacroTokens.drop_front();
1960
0
      break;
1961
0
    }
1962
0
    }
1963
0
  }
1964
0
}
1965
1966
PreprocessedEntityID
1967
ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M,
1968
0
                                         unsigned LocalID) const {
1969
0
  if (!M.ModuleOffsetMap.empty())
1970
0
    ReadModuleOffsetMap(M);
1971
1972
0
  ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1973
0
    I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1974
0
  assert(I != M.PreprocessedEntityRemap.end()
1975
0
         && "Invalid index into preprocessed entity index remap");
1976
1977
0
  return LocalID + I->second;
1978
0
}
1979
1980
0
const FileEntry *HeaderFileInfoTrait::getFile(const internal_key_type &Key) {
1981
0
  FileManager &FileMgr = Reader.getFileManager();
1982
0
  if (!Key.Imported) {
1983
0
    if (auto File = FileMgr.getFile(Key.Filename))
1984
0
      return *File;
1985
0
    return nullptr;
1986
0
  }
1987
1988
0
  std::string Resolved = std::string(Key.Filename);
1989
0
  Reader.ResolveImportedPath(M, Resolved);
1990
0
  if (auto File = FileMgr.getFile(Resolved))
1991
0
    return *File;
1992
0
  return nullptr;
1993
0
}
1994
1995
0
unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1996
0
  return llvm::hash_combine(ikey.Size, ikey.ModTime);
1997
0
}
1998
1999
HeaderFileInfoTrait::internal_key_type
2000
0
HeaderFileInfoTrait::GetInternalKey(external_key_type ekey) {
2001
0
  internal_key_type ikey = {ekey.getSize(),
2002
0
                            M.HasTimestamps ? ekey.getModificationTime() : 0,
2003
0
                            ekey.getName(), /*Imported*/ false};
2004
0
  return ikey;
2005
0
}
2006
2007
0
bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
2008
0
  if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
2009
0
    return false;
2010
2011
0
  if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
2012
0
    return true;
2013
2014
  // Determine whether the actual files are equivalent.
2015
0
  const FileEntry *FEA = getFile(a);
2016
0
  const FileEntry *FEB = getFile(b);
2017
0
  return FEA && FEA == FEB;
2018
0
}
2019
2020
std::pair<unsigned, unsigned>
2021
0
HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
2022
0
  return readULEBKeyDataLength(d);
2023
0
}
2024
2025
HeaderFileInfoTrait::internal_key_type
2026
0
HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
2027
0
  using namespace llvm::support;
2028
2029
0
  internal_key_type ikey;
2030
0
  ikey.Size =
2031
0
      off_t(endian::readNext<uint64_t, llvm::endianness::little, unaligned>(d));
2032
0
  ikey.ModTime = time_t(
2033
0
      endian::readNext<uint64_t, llvm::endianness::little, unaligned>(d));
2034
0
  ikey.Filename = (const char *)d;
2035
0
  ikey.Imported = true;
2036
0
  return ikey;
2037
0
}
2038
2039
HeaderFileInfoTrait::data_type
2040
HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
2041
0
                              unsigned DataLen) {
2042
0
  using namespace llvm::support;
2043
2044
0
  const unsigned char *End = d + DataLen;
2045
0
  HeaderFileInfo HFI;
2046
0
  unsigned Flags = *d++;
2047
2048
0
  bool Included = (Flags >> 6) & 0x01;
2049
0
  if (Included)
2050
0
    if (const FileEntry *FE = getFile(key))
2051
      // Not using \c Preprocessor::markIncluded(), since that would attempt to
2052
      // deserialize this header file info again.
2053
0
      Reader.getPreprocessor().getIncludedFiles().insert(FE);
2054
2055
  // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
2056
0
  HFI.isImport |= (Flags >> 5) & 0x01;
2057
0
  HFI.isPragmaOnce |= (Flags >> 4) & 0x01;
2058
0
  HFI.DirInfo = (Flags >> 1) & 0x07;
2059
0
  HFI.IndexHeaderMapHeader = Flags & 0x01;
2060
0
  HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
2061
0
      M, endian::readNext<uint32_t, llvm::endianness::little, unaligned>(d));
2062
0
  if (unsigned FrameworkOffset =
2063
0
          endian::readNext<uint32_t, llvm::endianness::little, unaligned>(d)) {
2064
    // The framework offset is 1 greater than the actual offset,
2065
    // since 0 is used as an indicator for "no framework name".
2066
0
    StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
2067
0
    HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
2068
0
  }
2069
2070
0
  assert((End - d) % 4 == 0 &&
2071
0
         "Wrong data length in HeaderFileInfo deserialization");
2072
0
  while (d != End) {
2073
0
    uint32_t LocalSMID =
2074
0
        endian::readNext<uint32_t, llvm::endianness::little, unaligned>(d);
2075
0
    auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 7);
2076
0
    LocalSMID >>= 3;
2077
2078
    // This header is part of a module. Associate it with the module to enable
2079
    // implicit module import.
2080
0
    SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
2081
0
    Module *Mod = Reader.getSubmodule(GlobalSMID);
2082
0
    FileManager &FileMgr = Reader.getFileManager();
2083
0
    ModuleMap &ModMap =
2084
0
        Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
2085
2086
0
    std::string Filename = std::string(key.Filename);
2087
0
    if (key.Imported)
2088
0
      Reader.ResolveImportedPath(M, Filename);
2089
0
    if (auto FE = FileMgr.getOptionalFileRef(Filename)) {
2090
      // FIXME: NameAsWritten
2091
0
      Module::Header H = {std::string(key.Filename), "", *FE};
2092
0
      ModMap.addHeader(Mod, H, HeaderRole, /*Imported=*/true);
2093
0
    }
2094
0
    HFI.isModuleHeader |= ModuleMap::isModular(HeaderRole);
2095
0
  }
2096
2097
  // This HeaderFileInfo was externally loaded.
2098
0
  HFI.External = true;
2099
0
  HFI.IsValid = true;
2100
0
  return HFI;
2101
0
}
2102
2103
void ASTReader::addPendingMacro(IdentifierInfo *II, ModuleFile *M,
2104
0
                                uint32_t MacroDirectivesOffset) {
2105
0
  assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
2106
0
  PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
2107
0
}
2108
2109
0
void ASTReader::ReadDefinedMacros() {
2110
  // Note that we are loading defined macros.
2111
0
  Deserializing Macros(this);
2112
2113
0
  for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
2114
0
    BitstreamCursor &MacroCursor = I.MacroCursor;
2115
2116
    // If there was no preprocessor block, skip this file.
2117
0
    if (MacroCursor.getBitcodeBytes().empty())
2118
0
      continue;
2119
2120
0
    BitstreamCursor Cursor = MacroCursor;
2121
0
    if (llvm::Error Err = Cursor.JumpToBit(I.MacroStartOffset)) {
2122
0
      Error(std::move(Err));
2123
0
      return;
2124
0
    }
2125
2126
0
    RecordData Record;
2127
0
    while (true) {
2128
0
      Expected<llvm::BitstreamEntry> MaybeE = Cursor.advanceSkippingSubblocks();
2129
0
      if (!MaybeE) {
2130
0
        Error(MaybeE.takeError());
2131
0
        return;
2132
0
      }
2133
0
      llvm::BitstreamEntry E = MaybeE.get();
2134
2135
0
      switch (E.Kind) {
2136
0
      case llvm::BitstreamEntry::SubBlock: // Handled for us already.
2137
0
      case llvm::BitstreamEntry::Error:
2138
0
        Error("malformed block record in AST file");
2139
0
        return;
2140
0
      case llvm::BitstreamEntry::EndBlock:
2141
0
        goto NextCursor;
2142
2143
0
      case llvm::BitstreamEntry::Record: {
2144
0
        Record.clear();
2145
0
        Expected<unsigned> MaybeRecord = Cursor.readRecord(E.ID, Record);
2146
0
        if (!MaybeRecord) {
2147
0
          Error(MaybeRecord.takeError());
2148
0
          return;
2149
0
        }
2150
0
        switch (MaybeRecord.get()) {
2151
0
        default:  // Default behavior: ignore.
2152
0
          break;
2153
2154
0
        case PP_MACRO_OBJECT_LIKE:
2155
0
        case PP_MACRO_FUNCTION_LIKE: {
2156
0
          IdentifierInfo *II = getLocalIdentifier(I, Record[0]);
2157
0
          if (II->isOutOfDate())
2158
0
            updateOutOfDateIdentifier(*II);
2159
0
          break;
2160
0
        }
2161
2162
0
        case PP_TOKEN:
2163
          // Ignore tokens.
2164
0
          break;
2165
0
        }
2166
0
        break;
2167
0
      }
2168
0
      }
2169
0
    }
2170
0
    NextCursor:  ;
2171
0
  }
2172
0
}
2173
2174
namespace {
2175
2176
  /// Visitor class used to look up identifirs in an AST file.
2177
  class IdentifierLookupVisitor {
2178
    StringRef Name;
2179
    unsigned NameHash;
2180
    unsigned PriorGeneration;
2181
    unsigned &NumIdentifierLookups;
2182
    unsigned &NumIdentifierLookupHits;
2183
    IdentifierInfo *Found = nullptr;
2184
2185
  public:
2186
    IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
2187
                            unsigned &NumIdentifierLookups,
2188
                            unsigned &NumIdentifierLookupHits)
2189
      : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
2190
        PriorGeneration(PriorGeneration),
2191
        NumIdentifierLookups(NumIdentifierLookups),
2192
0
        NumIdentifierLookupHits(NumIdentifierLookupHits) {}
2193
2194
0
    bool operator()(ModuleFile &M) {
2195
      // If we've already searched this module file, skip it now.
2196
0
      if (M.Generation <= PriorGeneration)
2197
0
        return true;
2198
2199
0
      ASTIdentifierLookupTable *IdTable
2200
0
        = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
2201
0
      if (!IdTable)
2202
0
        return false;
2203
2204
0
      ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
2205
0
                                     Found);
2206
0
      ++NumIdentifierLookups;
2207
0
      ASTIdentifierLookupTable::iterator Pos =
2208
0
          IdTable->find_hashed(Name, NameHash, &Trait);
2209
0
      if (Pos == IdTable->end())
2210
0
        return false;
2211
2212
      // Dereferencing the iterator has the effect of building the
2213
      // IdentifierInfo node and populating it with the various
2214
      // declarations it needs.
2215
0
      ++NumIdentifierLookupHits;
2216
0
      Found = *Pos;
2217
0
      return true;
2218
0
    }
2219
2220
    // Retrieve the identifier info found within the module
2221
    // files.
2222
0
    IdentifierInfo *getIdentifierInfo() const { return Found; }
2223
  };
2224
2225
} // namespace
2226
2227
0
void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
2228
  // Note that we are loading an identifier.
2229
0
  Deserializing AnIdentifier(this);
2230
2231
0
  unsigned PriorGeneration = 0;
2232
0
  if (getContext().getLangOpts().Modules)
2233
0
    PriorGeneration = IdentifierGeneration[&II];
2234
2235
  // If there is a global index, look there first to determine which modules
2236
  // provably do not have any results for this identifier.
2237
0
  GlobalModuleIndex::HitSet Hits;
2238
0
  GlobalModuleIndex::HitSet *HitsPtr = nullptr;
2239
0
  if (!loadGlobalIndex()) {
2240
0
    if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
2241
0
      HitsPtr = &Hits;
2242
0
    }
2243
0
  }
2244
2245
0
  IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
2246
0
                                  NumIdentifierLookups,
2247
0
                                  NumIdentifierLookupHits);
2248
0
  ModuleMgr.visit(Visitor, HitsPtr);
2249
0
  markIdentifierUpToDate(&II);
2250
0
}
2251
2252
0
void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
2253
0
  if (!II)
2254
0
    return;
2255
2256
0
  II->setOutOfDate(false);
2257
2258
  // Update the generation for this identifier.
2259
0
  if (getContext().getLangOpts().Modules)
2260
0
    IdentifierGeneration[II] = getGeneration();
2261
0
}
2262
2263
void ASTReader::resolvePendingMacro(IdentifierInfo *II,
2264
0
                                    const PendingMacroInfo &PMInfo) {
2265
0
  ModuleFile &M = *PMInfo.M;
2266
2267
0
  BitstreamCursor &Cursor = M.MacroCursor;
2268
0
  SavedStreamPosition SavedPosition(Cursor);
2269
0
  if (llvm::Error Err =
2270
0
          Cursor.JumpToBit(M.MacroOffsetsBase + PMInfo.MacroDirectivesOffset)) {
2271
0
    Error(std::move(Err));
2272
0
    return;
2273
0
  }
2274
2275
0
  struct ModuleMacroRecord {
2276
0
    SubmoduleID SubModID;
2277
0
    MacroInfo *MI;
2278
0
    SmallVector<SubmoduleID, 8> Overrides;
2279
0
  };
2280
0
  llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
2281
2282
  // We expect to see a sequence of PP_MODULE_MACRO records listing exported
2283
  // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
2284
  // macro histroy.
2285
0
  RecordData Record;
2286
0
  while (true) {
2287
0
    Expected<llvm::BitstreamEntry> MaybeEntry =
2288
0
        Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
2289
0
    if (!MaybeEntry) {
2290
0
      Error(MaybeEntry.takeError());
2291
0
      return;
2292
0
    }
2293
0
    llvm::BitstreamEntry Entry = MaybeEntry.get();
2294
2295
0
    if (Entry.Kind != llvm::BitstreamEntry::Record) {
2296
0
      Error("malformed block record in AST file");
2297
0
      return;
2298
0
    }
2299
2300
0
    Record.clear();
2301
0
    Expected<unsigned> MaybePP = Cursor.readRecord(Entry.ID, Record);
2302
0
    if (!MaybePP) {
2303
0
      Error(MaybePP.takeError());
2304
0
      return;
2305
0
    }
2306
0
    switch ((PreprocessorRecordTypes)MaybePP.get()) {
2307
0
    case PP_MACRO_DIRECTIVE_HISTORY:
2308
0
      break;
2309
2310
0
    case PP_MODULE_MACRO: {
2311
0
      ModuleMacros.push_back(ModuleMacroRecord());
2312
0
      auto &Info = ModuleMacros.back();
2313
0
      Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
2314
0
      Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
2315
0
      for (int I = 2, N = Record.size(); I != N; ++I)
2316
0
        Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
2317
0
      continue;
2318
0
    }
2319
2320
0
    default:
2321
0
      Error("malformed block record in AST file");
2322
0
      return;
2323
0
    }
2324
2325
    // We found the macro directive history; that's the last record
2326
    // for this macro.
2327
0
    break;
2328
0
  }
2329
2330
  // Module macros are listed in reverse dependency order.
2331
0
  {
2332
0
    std::reverse(ModuleMacros.begin(), ModuleMacros.end());
2333
0
    llvm::SmallVector<ModuleMacro*, 8> Overrides;
2334
0
    for (auto &MMR : ModuleMacros) {
2335
0
      Overrides.clear();
2336
0
      for (unsigned ModID : MMR.Overrides) {
2337
0
        Module *Mod = getSubmodule(ModID);
2338
0
        auto *Macro = PP.getModuleMacro(Mod, II);
2339
0
        assert(Macro && "missing definition for overridden macro");
2340
0
        Overrides.push_back(Macro);
2341
0
      }
2342
2343
0
      bool Inserted = false;
2344
0
      Module *Owner = getSubmodule(MMR.SubModID);
2345
0
      PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
2346
0
    }
2347
0
  }
2348
2349
  // Don't read the directive history for a module; we don't have anywhere
2350
  // to put it.
2351
0
  if (M.isModule())
2352
0
    return;
2353
2354
  // Deserialize the macro directives history in reverse source-order.
2355
0
  MacroDirective *Latest = nullptr, *Earliest = nullptr;
2356
0
  unsigned Idx = 0, N = Record.size();
2357
0
  while (Idx < N) {
2358
0
    MacroDirective *MD = nullptr;
2359
0
    SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
2360
0
    MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
2361
0
    switch (K) {
2362
0
    case MacroDirective::MD_Define: {
2363
0
      MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
2364
0
      MD = PP.AllocateDefMacroDirective(MI, Loc);
2365
0
      break;
2366
0
    }
2367
0
    case MacroDirective::MD_Undefine:
2368
0
      MD = PP.AllocateUndefMacroDirective(Loc);
2369
0
      break;
2370
0
    case MacroDirective::MD_Visibility:
2371
0
      bool isPublic = Record[Idx++];
2372
0
      MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
2373
0
      break;
2374
0
    }
2375
2376
0
    if (!Latest)
2377
0
      Latest = MD;
2378
0
    if (Earliest)
2379
0
      Earliest->setPrevious(MD);
2380
0
    Earliest = MD;
2381
0
  }
2382
2383
0
  if (Latest)
2384
0
    PP.setLoadedMacroDirective(II, Earliest, Latest);
2385
0
}
2386
2387
bool ASTReader::shouldDisableValidationForFile(
2388
0
    const serialization::ModuleFile &M) const {
2389
0
  if (DisableValidationKind == DisableValidationForModuleKind::None)
2390
0
    return false;
2391
2392
  // If a PCH is loaded and validation is disabled for PCH then disable
2393
  // validation for the PCH and the modules it loads.
2394
0
  ModuleKind K = CurrentDeserializingModuleKind.value_or(M.Kind);
2395
2396
0
  switch (K) {
2397
0
  case MK_MainFile:
2398
0
  case MK_Preamble:
2399
0
  case MK_PCH:
2400
0
    return bool(DisableValidationKind & DisableValidationForModuleKind::PCH);
2401
0
  case MK_ImplicitModule:
2402
0
  case MK_ExplicitModule:
2403
0
  case MK_PrebuiltModule:
2404
0
    return bool(DisableValidationKind & DisableValidationForModuleKind::Module);
2405
0
  }
2406
2407
0
  return false;
2408
0
}
2409
2410
0
InputFileInfo ASTReader::getInputFileInfo(ModuleFile &F, unsigned ID) {
2411
  // If this ID is bogus, just return an empty input file.
2412
0
  if (ID == 0 || ID > F.InputFileInfosLoaded.size())
2413
0
    return InputFileInfo();
2414
2415
  // If we've already loaded this input file, return it.
2416
0
  if (!F.InputFileInfosLoaded[ID - 1].Filename.empty())
2417
0
    return F.InputFileInfosLoaded[ID - 1];
2418
2419
  // Go find this input file.
2420
0
  BitstreamCursor &Cursor = F.InputFilesCursor;
2421
0
  SavedStreamPosition SavedPosition(Cursor);
2422
0
  if (llvm::Error Err = Cursor.JumpToBit(F.InputFilesOffsetBase +
2423
0
                                         F.InputFileOffsets[ID - 1])) {
2424
    // FIXME this drops errors on the floor.
2425
0
    consumeError(std::move(Err));
2426
0
  }
2427
2428
0
  Expected<unsigned> MaybeCode = Cursor.ReadCode();
2429
0
  if (!MaybeCode) {
2430
    // FIXME this drops errors on the floor.
2431
0
    consumeError(MaybeCode.takeError());
2432
0
  }
2433
0
  unsigned Code = MaybeCode.get();
2434
0
  RecordData Record;
2435
0
  StringRef Blob;
2436
2437
0
  if (Expected<unsigned> Maybe = Cursor.readRecord(Code, Record, &Blob))
2438
0
    assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE &&
2439
0
           "invalid record type for input file");
2440
0
  else {
2441
    // FIXME this drops errors on the floor.
2442
0
    consumeError(Maybe.takeError());
2443
0
  }
2444
2445
0
  assert(Record[0] == ID && "Bogus stored ID or offset");
2446
0
  InputFileInfo R;
2447
0
  R.StoredSize = static_cast<off_t>(Record[1]);
2448
0
  R.StoredTime = static_cast<time_t>(Record[2]);
2449
0
  R.Overridden = static_cast<bool>(Record[3]);
2450
0
  R.Transient = static_cast<bool>(Record[4]);
2451
0
  R.TopLevel = static_cast<bool>(Record[5]);
2452
0
  R.ModuleMap = static_cast<bool>(Record[6]);
2453
0
  std::tie(R.FilenameAsRequested, R.Filename) = [&]() {
2454
0
    uint16_t AsRequestedLength = Record[7];
2455
2456
0
    std::string NameAsRequested = Blob.substr(0, AsRequestedLength).str();
2457
0
    std::string Name = Blob.substr(AsRequestedLength).str();
2458
2459
0
    ResolveImportedPath(F, NameAsRequested);
2460
0
    ResolveImportedPath(F, Name);
2461
2462
0
    if (Name.empty())
2463
0
      Name = NameAsRequested;
2464
2465
0
    return std::make_pair(std::move(NameAsRequested), std::move(Name));
2466
0
  }();
2467
2468
0
  Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
2469
0
  if (!MaybeEntry) // FIXME this drops errors on the floor.
2470
0
    consumeError(MaybeEntry.takeError());
2471
0
  llvm::BitstreamEntry Entry = MaybeEntry.get();
2472
0
  assert(Entry.Kind == llvm::BitstreamEntry::Record &&
2473
0
         "expected record type for input file hash");
2474
2475
0
  Record.clear();
2476
0
  if (Expected<unsigned> Maybe = Cursor.readRecord(Entry.ID, Record))
2477
0
    assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE_HASH &&
2478
0
           "invalid record type for input file hash");
2479
0
  else {
2480
    // FIXME this drops errors on the floor.
2481
0
    consumeError(Maybe.takeError());
2482
0
  }
2483
0
  R.ContentHash = (static_cast<uint64_t>(Record[1]) << 32) |
2484
0
                  static_cast<uint64_t>(Record[0]);
2485
2486
  // Note that we've loaded this input file info.
2487
0
  F.InputFileInfosLoaded[ID - 1] = R;
2488
0
  return R;
2489
0
}
2490
2491
static unsigned moduleKindForDiagnostic(ModuleKind Kind);
2492
0
InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
2493
  // If this ID is bogus, just return an empty input file.
2494
0
  if (ID == 0 || ID > F.InputFilesLoaded.size())
2495
0
    return InputFile();
2496
2497
  // If we've already loaded this input file, return it.
2498
0
  if (F.InputFilesLoaded[ID-1].getFile())
2499
0
    return F.InputFilesLoaded[ID-1];
2500
2501
0
  if (F.InputFilesLoaded[ID-1].isNotFound())
2502
0
    return InputFile();
2503
2504
  // Go find this input file.
2505
0
  BitstreamCursor &Cursor = F.InputFilesCursor;
2506
0
  SavedStreamPosition SavedPosition(Cursor);
2507
0
  if (llvm::Error Err = Cursor.JumpToBit(F.InputFilesOffsetBase +
2508
0
                                         F.InputFileOffsets[ID - 1])) {
2509
    // FIXME this drops errors on the floor.
2510
0
    consumeError(std::move(Err));
2511
0
  }
2512
2513
0
  InputFileInfo FI = getInputFileInfo(F, ID);
2514
0
  off_t StoredSize = FI.StoredSize;
2515
0
  time_t StoredTime = FI.StoredTime;
2516
0
  bool Overridden = FI.Overridden;
2517
0
  bool Transient = FI.Transient;
2518
0
  StringRef Filename = FI.FilenameAsRequested;
2519
0
  uint64_t StoredContentHash = FI.ContentHash;
2520
2521
  // For standard C++ modules, we don't need to check the inputs.
2522
0
  bool SkipChecks = F.StandardCXXModule;
2523
2524
0
  const HeaderSearchOptions &HSOpts =
2525
0
      PP.getHeaderSearchInfo().getHeaderSearchOpts();
2526
2527
  // The option ForceCheckCXX20ModulesInputFiles is only meaningful for C++20
2528
  // modules.
2529
0
  if (F.StandardCXXModule && HSOpts.ForceCheckCXX20ModulesInputFiles) {
2530
0
    SkipChecks = false;
2531
0
    Overridden = false;
2532
0
  }
2533
2534
0
  auto File = FileMgr.getOptionalFileRef(Filename, /*OpenFile=*/false);
2535
2536
  // For an overridden file, create a virtual file with the stored
2537
  // size/timestamp.
2538
0
  if ((Overridden || Transient || SkipChecks) && !File)
2539
0
    File = FileMgr.getVirtualFileRef(Filename, StoredSize, StoredTime);
2540
2541
0
  if (!File) {
2542
0
    if (Complain) {
2543
0
      std::string ErrorStr = "could not find file '";
2544
0
      ErrorStr += Filename;
2545
0
      ErrorStr += "' referenced by AST file '";
2546
0
      ErrorStr += F.FileName;
2547
0
      ErrorStr += "'";
2548
0
      Error(ErrorStr);
2549
0
    }
2550
    // Record that we didn't find the file.
2551
0
    F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2552
0
    return InputFile();
2553
0
  }
2554
2555
  // Check if there was a request to override the contents of the file
2556
  // that was part of the precompiled header. Overriding such a file
2557
  // can lead to problems when lexing using the source locations from the
2558
  // PCH.
2559
0
  SourceManager &SM = getSourceManager();
2560
  // FIXME: Reject if the overrides are different.
2561
0
  if ((!Overridden && !Transient) && !SkipChecks &&
2562
0
      SM.isFileOverridden(*File)) {
2563
0
    if (Complain)
2564
0
      Error(diag::err_fe_pch_file_overridden, Filename);
2565
2566
    // After emitting the diagnostic, bypass the overriding file to recover
2567
    // (this creates a separate FileEntry).
2568
0
    File = SM.bypassFileContentsOverride(*File);
2569
0
    if (!File) {
2570
0
      F.InputFilesLoaded[ID - 1] = InputFile::getNotFound();
2571
0
      return InputFile();
2572
0
    }
2573
0
  }
2574
2575
0
  struct Change {
2576
0
    enum ModificationKind {
2577
0
      Size,
2578
0
      ModTime,
2579
0
      Content,
2580
0
      None,
2581
0
    } Kind;
2582
0
    std::optional<int64_t> Old = std::nullopt;
2583
0
    std::optional<int64_t> New = std::nullopt;
2584
0
  };
2585
0
  auto HasInputContentChanged = [&](Change OriginalChange) {
2586
0
    assert(ValidateASTInputFilesContent &&
2587
0
           "We should only check the content of the inputs with "
2588
0
           "ValidateASTInputFilesContent enabled.");
2589
2590
0
    if (StoredContentHash == static_cast<uint64_t>(llvm::hash_code(-1)))
2591
0
      return OriginalChange;
2592
2593
0
    auto MemBuffOrError = FileMgr.getBufferForFile(*File);
2594
0
    if (!MemBuffOrError) {
2595
0
      if (!Complain)
2596
0
        return OriginalChange;
2597
0
      std::string ErrorStr = "could not get buffer for file '";
2598
0
      ErrorStr += File->getName();
2599
0
      ErrorStr += "'";
2600
0
      Error(ErrorStr);
2601
0
      return OriginalChange;
2602
0
    }
2603
2604
    // FIXME: hash_value is not guaranteed to be stable!
2605
0
    auto ContentHash = hash_value(MemBuffOrError.get()->getBuffer());
2606
0
    if (StoredContentHash == static_cast<uint64_t>(ContentHash))
2607
0
      return Change{Change::None};
2608
2609
0
    return Change{Change::Content};
2610
0
  };
2611
0
  auto HasInputFileChanged = [&]() {
2612
0
    if (StoredSize != File->getSize())
2613
0
      return Change{Change::Size, StoredSize, File->getSize()};
2614
0
    if (!shouldDisableValidationForFile(F) && StoredTime &&
2615
0
        StoredTime != File->getModificationTime()) {
2616
0
      Change MTimeChange = {Change::ModTime, StoredTime,
2617
0
                            File->getModificationTime()};
2618
2619
      // In case the modification time changes but not the content,
2620
      // accept the cached file as legit.
2621
0
      if (ValidateASTInputFilesContent)
2622
0
        return HasInputContentChanged(MTimeChange);
2623
2624
0
      return MTimeChange;
2625
0
    }
2626
0
    return Change{Change::None};
2627
0
  };
2628
2629
0
  bool IsOutOfDate = false;
2630
0
  auto FileChange = SkipChecks ? Change{Change::None} : HasInputFileChanged();
2631
  // When ForceCheckCXX20ModulesInputFiles and ValidateASTInputFilesContent
2632
  // enabled, it is better to check the contents of the inputs. Since we can't
2633
  // get correct modified time information for inputs from overriden inputs.
2634
0
  if (HSOpts.ForceCheckCXX20ModulesInputFiles && ValidateASTInputFilesContent &&
2635
0
      F.StandardCXXModule && FileChange.Kind == Change::None)
2636
0
    FileChange = HasInputContentChanged(FileChange);
2637
2638
  // For an overridden file, there is nothing to validate.
2639
0
  if (!Overridden && FileChange.Kind != Change::None) {
2640
0
    if (Complain && !Diags.isDiagnosticInFlight()) {
2641
      // Build a list of the PCH imports that got us here (in reverse).
2642
0
      SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2643
0
      while (!ImportStack.back()->ImportedBy.empty())
2644
0
        ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
2645
2646
      // The top-level PCH is stale.
2647
0
      StringRef TopLevelPCHName(ImportStack.back()->FileName);
2648
0
      Diag(diag::err_fe_ast_file_modified)
2649
0
          << Filename << moduleKindForDiagnostic(ImportStack.back()->Kind)
2650
0
          << TopLevelPCHName << FileChange.Kind
2651
0
          << (FileChange.Old && FileChange.New)
2652
0
          << llvm::itostr(FileChange.Old.value_or(0))
2653
0
          << llvm::itostr(FileChange.New.value_or(0));
2654
2655
      // Print the import stack.
2656
0
      if (ImportStack.size() > 1) {
2657
0
        Diag(diag::note_pch_required_by)
2658
0
          << Filename << ImportStack[0]->FileName;
2659
0
        for (unsigned I = 1; I < ImportStack.size(); ++I)
2660
0
          Diag(diag::note_pch_required_by)
2661
0
            << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
2662
0
      }
2663
2664
0
      Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
2665
0
    }
2666
2667
0
    IsOutOfDate = true;
2668
0
  }
2669
  // FIXME: If the file is overridden and we've already opened it,
2670
  // issue an error (or split it into a separate FileEntry).
2671
2672
0
  InputFile IF = InputFile(*File, Overridden || Transient, IsOutOfDate);
2673
2674
  // Note that we've loaded this input file.
2675
0
  F.InputFilesLoaded[ID-1] = IF;
2676
0
  return IF;
2677
0
}
2678
2679
/// If we are loading a relocatable PCH or module file, and the filename
2680
/// is not an absolute path, add the system or module root to the beginning of
2681
/// the file name.
2682
0
void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2683
  // Resolve relative to the base directory, if we have one.
2684
0
  if (!M.BaseDirectory.empty())
2685
0
    return ResolveImportedPath(Filename, M.BaseDirectory);
2686
0
}
2687
2688
0
void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
2689
0
  if (Filename.empty() || llvm::sys::path::is_absolute(Filename) ||
2690
0
      Filename == "<built-in>" || Filename == "<command line>")
2691
0
    return;
2692
2693
0
  SmallString<128> Buffer;
2694
0
  llvm::sys::path::append(Buffer, Prefix, Filename);
2695
0
  Filename.assign(Buffer.begin(), Buffer.end());
2696
0
}
2697
2698
0
static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2699
0
  switch (ARR) {
2700
0
  case ASTReader::Failure: return true;
2701
0
  case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2702
0
  case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2703
0
  case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2704
0
  case ASTReader::ConfigurationMismatch:
2705
0
    return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2706
0
  case ASTReader::HadErrors: return true;
2707
0
  case ASTReader::Success: return false;
2708
0
  }
2709
2710
0
  llvm_unreachable("unknown ASTReadResult");
2711
0
}
2712
2713
ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2714
    BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2715
    bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
2716
0
    std::string &SuggestedPredefines) {
2717
0
  if (llvm::Error Err = Stream.EnterSubBlock(OPTIONS_BLOCK_ID)) {
2718
    // FIXME this drops errors on the floor.
2719
0
    consumeError(std::move(Err));
2720
0
    return Failure;
2721
0
  }
2722
2723
  // Read all of the records in the options block.
2724
0
  RecordData Record;
2725
0
  ASTReadResult Result = Success;
2726
0
  while (true) {
2727
0
    Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
2728
0
    if (!MaybeEntry) {
2729
      // FIXME this drops errors on the floor.
2730
0
      consumeError(MaybeEntry.takeError());
2731
0
      return Failure;
2732
0
    }
2733
0
    llvm::BitstreamEntry Entry = MaybeEntry.get();
2734
2735
0
    switch (Entry.Kind) {
2736
0
    case llvm::BitstreamEntry::Error:
2737
0
    case llvm::BitstreamEntry::SubBlock:
2738
0
      return Failure;
2739
2740
0
    case llvm::BitstreamEntry::EndBlock:
2741
0
      return Result;
2742
2743
0
    case llvm::BitstreamEntry::Record:
2744
      // The interesting case.
2745
0
      break;
2746
0
    }
2747
2748
    // Read and process a record.
2749
0
    Record.clear();
2750
0
    Expected<unsigned> MaybeRecordType = Stream.readRecord(Entry.ID, Record);
2751
0
    if (!MaybeRecordType) {
2752
      // FIXME this drops errors on the floor.
2753
0
      consumeError(MaybeRecordType.takeError());
2754
0
      return Failure;
2755
0
    }
2756
0
    switch ((OptionsRecordTypes)MaybeRecordType.get()) {
2757
0
    case LANGUAGE_OPTIONS: {
2758
0
      bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2759
0
      if (ParseLanguageOptions(Record, Complain, Listener,
2760
0
                               AllowCompatibleConfigurationMismatch))
2761
0
        Result = ConfigurationMismatch;
2762
0
      break;
2763
0
    }
2764
2765
0
    case TARGET_OPTIONS: {
2766
0
      bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2767
0
      if (ParseTargetOptions(Record, Complain, Listener,
2768
0
                             AllowCompatibleConfigurationMismatch))
2769
0
        Result = ConfigurationMismatch;
2770
0
      break;
2771
0
    }
2772
2773
0
    case FILE_SYSTEM_OPTIONS: {
2774
0
      bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2775
0
      if (!AllowCompatibleConfigurationMismatch &&
2776
0
          ParseFileSystemOptions(Record, Complain, Listener))
2777
0
        Result = ConfigurationMismatch;
2778
0
      break;
2779
0
    }
2780
2781
0
    case HEADER_SEARCH_OPTIONS: {
2782
0
      bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2783
0
      if (!AllowCompatibleConfigurationMismatch &&
2784
0
          ParseHeaderSearchOptions(Record, Complain, Listener))
2785
0
        Result = ConfigurationMismatch;
2786
0
      break;
2787
0
    }
2788
2789
0
    case PREPROCESSOR_OPTIONS:
2790
0
      bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2791
0
      if (!AllowCompatibleConfigurationMismatch &&
2792
0
          ParsePreprocessorOptions(Record, Complain, Listener,
2793
0
                                   SuggestedPredefines))
2794
0
        Result = ConfigurationMismatch;
2795
0
      break;
2796
0
    }
2797
0
  }
2798
0
}
2799
2800
ASTReader::ASTReadResult
2801
ASTReader::ReadControlBlock(ModuleFile &F,
2802
                            SmallVectorImpl<ImportedModule> &Loaded,
2803
                            const ModuleFile *ImportedBy,
2804
0
                            unsigned ClientLoadCapabilities) {
2805
0
  BitstreamCursor &Stream = F.Stream;
2806
2807
0
  if (llvm::Error Err = Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2808
0
    Error(std::move(Err));
2809
0
    return Failure;
2810
0
  }
2811
2812
  // Lambda to read the unhashed control block the first time it's called.
2813
  //
2814
  // For PCM files, the unhashed control block cannot be read until after the
2815
  // MODULE_NAME record.  However, PCH files have no MODULE_NAME, and yet still
2816
  // need to look ahead before reading the IMPORTS record.  For consistency,
2817
  // this block is always read somehow (see BitstreamEntry::EndBlock).
2818
0
  bool HasReadUnhashedControlBlock = false;
2819
0
  auto readUnhashedControlBlockOnce = [&]() {
2820
0
    if (!HasReadUnhashedControlBlock) {
2821
0
      HasReadUnhashedControlBlock = true;
2822
0
      if (ASTReadResult Result =
2823
0
              readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities))
2824
0
        return Result;
2825
0
    }
2826
0
    return Success;
2827
0
  };
2828
2829
0
  bool DisableValidation = shouldDisableValidationForFile(F);
2830
2831
  // Read all of the records and blocks in the control block.
2832
0
  RecordData Record;
2833
0
  unsigned NumInputs = 0;
2834
0
  unsigned NumUserInputs = 0;
2835
0
  StringRef BaseDirectoryAsWritten;
2836
0
  while (true) {
2837
0
    Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
2838
0
    if (!MaybeEntry) {
2839
0
      Error(MaybeEntry.takeError());
2840
0
      return Failure;
2841
0
    }
2842
0
    llvm::BitstreamEntry Entry = MaybeEntry.get();
2843
2844
0
    switch (Entry.Kind) {
2845
0
    case llvm::BitstreamEntry::Error:
2846
0
      Error("malformed block record in AST file");
2847
0
      return Failure;
2848
0
    case llvm::BitstreamEntry::EndBlock: {
2849
      // Validate the module before returning.  This call catches an AST with
2850
      // no module name and no imports.
2851
0
      if (ASTReadResult Result = readUnhashedControlBlockOnce())
2852
0
        return Result;
2853
2854
      // Validate input files.
2855
0
      const HeaderSearchOptions &HSOpts =
2856
0
          PP.getHeaderSearchInfo().getHeaderSearchOpts();
2857
2858
      // All user input files reside at the index range [0, NumUserInputs), and
2859
      // system input files reside at [NumUserInputs, NumInputs). For explicitly
2860
      // loaded module files, ignore missing inputs.
2861
0
      if (!DisableValidation && F.Kind != MK_ExplicitModule &&
2862
0
          F.Kind != MK_PrebuiltModule) {
2863
0
        bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
2864
2865
        // If we are reading a module, we will create a verification timestamp,
2866
        // so we verify all input files.  Otherwise, verify only user input
2867
        // files.
2868
2869
0
        unsigned N = ValidateSystemInputs ? NumInputs : NumUserInputs;
2870
0
        if (HSOpts.ModulesValidateOncePerBuildSession &&
2871
0
            F.InputFilesValidationTimestamp > HSOpts.BuildSessionTimestamp &&
2872
0
            F.Kind == MK_ImplicitModule)
2873
0
          N = NumUserInputs;
2874
2875
0
        for (unsigned I = 0; I < N; ++I) {
2876
0
          InputFile IF = getInputFile(F, I+1, Complain);
2877
0
          if (!IF.getFile() || IF.isOutOfDate())
2878
0
            return OutOfDate;
2879
0
        }
2880
0
      }
2881
2882
0
      if (Listener)
2883
0
        Listener->visitModuleFile(F.FileName, F.Kind);
2884
2885
0
      if (Listener && Listener->needsInputFileVisitation()) {
2886
0
        unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2887
0
                                                                : NumUserInputs;
2888
0
        for (unsigned I = 0; I < N; ++I) {
2889
0
          bool IsSystem = I >= NumUserInputs;
2890
0
          InputFileInfo FI = getInputFileInfo(F, I + 1);
2891
0
          Listener->visitInputFile(
2892
0
              FI.FilenameAsRequested, IsSystem, FI.Overridden,
2893
0
              F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule);
2894
0
        }
2895
0
      }
2896
2897
0
      return Success;
2898
0
    }
2899
2900
0
    case llvm::BitstreamEntry::SubBlock:
2901
0
      switch (Entry.ID) {
2902
0
      case INPUT_FILES_BLOCK_ID:
2903
0
        F.InputFilesCursor = Stream;
2904
0
        if (llvm::Error Err = Stream.SkipBlock()) {
2905
0
          Error(std::move(Err));
2906
0
          return Failure;
2907
0
        }
2908
0
        if (ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2909
0
          Error("malformed block record in AST file");
2910
0
          return Failure;
2911
0
        }
2912
0
        F.InputFilesOffsetBase = F.InputFilesCursor.GetCurrentBitNo();
2913
0
        continue;
2914
2915
0
      case OPTIONS_BLOCK_ID:
2916
        // If we're reading the first module for this group, check its options
2917
        // are compatible with ours. For modules it imports, no further checking
2918
        // is required, because we checked them when we built it.
2919
0
        if (Listener && !ImportedBy) {
2920
          // Should we allow the configuration of the module file to differ from
2921
          // the configuration of the current translation unit in a compatible
2922
          // way?
2923
          //
2924
          // FIXME: Allow this for files explicitly specified with -include-pch.
2925
0
          bool AllowCompatibleConfigurationMismatch =
2926
0
              F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
2927
2928
0
          ASTReadResult Result =
2929
0
              ReadOptionsBlock(Stream, ClientLoadCapabilities,
2930
0
                               AllowCompatibleConfigurationMismatch, *Listener,
2931
0
                               SuggestedPredefines);
2932
0
          if (Result == Failure) {
2933
0
            Error("malformed block record in AST file");
2934
0
            return Result;
2935
0
          }
2936
2937
0
          if (DisableValidation ||
2938
0
              (AllowConfigurationMismatch && Result == ConfigurationMismatch))
2939
0
            Result = Success;
2940
2941
          // If we can't load the module, exit early since we likely
2942
          // will rebuild the module anyway. The stream may be in the
2943
          // middle of a block.
2944
0
          if (Result != Success)
2945
0
            return Result;
2946
0
        } else if (llvm::Error Err = Stream.SkipBlock()) {
2947
0
          Error(std::move(Err));
2948
0
          return Failure;
2949
0
        }
2950
0
        continue;
2951
2952
0
      default:
2953
0
        if (llvm::Error Err = Stream.SkipBlock()) {
2954
0
          Error(std::move(Err));
2955
0
          return Failure;
2956
0
        }
2957
0
        continue;
2958
0
      }
2959
2960
0
    case llvm::BitstreamEntry::Record:
2961
      // The interesting case.
2962
0
      break;
2963
0
    }
2964
2965
    // Read and process a record.
2966
0
    Record.clear();
2967
0
    StringRef Blob;
2968
0
    Expected<unsigned> MaybeRecordType =
2969
0
        Stream.readRecord(Entry.ID, Record, &Blob);
2970
0
    if (!MaybeRecordType) {
2971
0
      Error(MaybeRecordType.takeError());
2972
0
      return Failure;
2973
0
    }
2974
0
    switch ((ControlRecordTypes)MaybeRecordType.get()) {
2975
0
    case METADATA: {
2976
0
      if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2977
0
        if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
2978
0
          Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2979
0
                                        : diag::err_pch_version_too_new);
2980
0
        return VersionMismatch;
2981
0
      }
2982
2983
0
      bool hasErrors = Record[7];
2984
0
      if (hasErrors && !DisableValidation) {
2985
        // If requested by the caller and the module hasn't already been read
2986
        // or compiled, mark modules on error as out-of-date.
2987
0
        if ((ClientLoadCapabilities & ARR_TreatModuleWithErrorsAsOutOfDate) &&
2988
0
            canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
2989
0
          return OutOfDate;
2990
2991
0
        if (!AllowASTWithCompilerErrors) {
2992
0
          Diag(diag::err_pch_with_compiler_errors);
2993
0
          return HadErrors;
2994
0
        }
2995
0
      }
2996
0
      if (hasErrors) {
2997
0
        Diags.ErrorOccurred = true;
2998
0
        Diags.UncompilableErrorOccurred = true;
2999
0
        Diags.UnrecoverableErrorOccurred = true;
3000
0
      }
3001
3002
0
      F.RelocatablePCH = Record[4];
3003
      // Relative paths in a relocatable PCH are relative to our sysroot.
3004
0
      if (F.RelocatablePCH)
3005
0
        F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
3006
3007
0
      F.StandardCXXModule = Record[5];
3008
3009
0
      F.HasTimestamps = Record[6];
3010
3011
0
      const std::string &CurBranch = getClangFullRepositoryVersion();
3012
0
      StringRef ASTBranch = Blob;
3013
0
      if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
3014
0
        if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
3015
0
          Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
3016
0
        return VersionMismatch;
3017
0
      }
3018
0
      break;
3019
0
    }
3020
3021
0
    case IMPORTS: {
3022
      // Validate the AST before processing any imports (otherwise, untangling
3023
      // them can be error-prone and expensive).  A module will have a name and
3024
      // will already have been validated, but this catches the PCH case.
3025
0
      if (ASTReadResult Result = readUnhashedControlBlockOnce())
3026
0
        return Result;
3027
3028
      // Load each of the imported PCH files.
3029
0
      unsigned Idx = 0, N = Record.size();
3030
0
      while (Idx < N) {
3031
        // Read information about the AST file.
3032
0
        ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
3033
        // Whether we're importing a standard c++ module.
3034
0
        bool IsImportingStdCXXModule = Record[Idx++];
3035
        // The import location will be the local one for now; we will adjust
3036
        // all import locations of module imports after the global source
3037
        // location info are setup, in ReadAST.
3038
0
        SourceLocation ImportLoc =
3039
0
            ReadUntranslatedSourceLocation(Record[Idx++]);
3040
0
        off_t StoredSize = !IsImportingStdCXXModule ? (off_t)Record[Idx++] : 0;
3041
0
        time_t StoredModTime =
3042
0
            !IsImportingStdCXXModule ? (time_t)Record[Idx++] : 0;
3043
3044
0
        ASTFileSignature StoredSignature;
3045
0
        if (!IsImportingStdCXXModule) {
3046
0
          auto FirstSignatureByte = Record.begin() + Idx;
3047
0
          StoredSignature = ASTFileSignature::create(
3048
0
              FirstSignatureByte, FirstSignatureByte + ASTFileSignature::size);
3049
0
          Idx += ASTFileSignature::size;
3050
0
        }
3051
3052
0
        std::string ImportedName = ReadString(Record, Idx);
3053
0
        std::string ImportedFile;
3054
3055
        // For prebuilt and explicit modules first consult the file map for
3056
        // an override. Note that here we don't search prebuilt module
3057
        // directories if we're not importing standard c++ module, only the
3058
        // explicit name to file mappings. Also, we will still verify the
3059
        // size/signature making sure it is essentially the same file but
3060
        // perhaps in a different location.
3061
0
        if (ImportedKind == MK_PrebuiltModule || ImportedKind == MK_ExplicitModule)
3062
0
          ImportedFile = PP.getHeaderSearchInfo().getPrebuiltModuleFileName(
3063
0
              ImportedName, /*FileMapOnly*/ !IsImportingStdCXXModule);
3064
3065
        // For C++20 Modules, we won't record the path to the imported modules
3066
        // in the BMI
3067
0
        if (!IsImportingStdCXXModule) {
3068
0
          if (ImportedFile.empty()) {
3069
            // Use BaseDirectoryAsWritten to ensure we use the same path in the
3070
            // ModuleCache as when writing.
3071
0
            ImportedFile = ReadPath(BaseDirectoryAsWritten, Record, Idx);
3072
0
          } else
3073
0
            SkipPath(Record, Idx);
3074
0
        } else if (ImportedFile.empty()) {
3075
0
          Diag(clang::diag::err_failed_to_find_module_file) << ImportedName;
3076
0
          return Missing;
3077
0
        }
3078
3079
        // If our client can't cope with us being out of date, we can't cope with
3080
        // our dependency being missing.
3081
0
        unsigned Capabilities = ClientLoadCapabilities;
3082
0
        if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3083
0
          Capabilities &= ~ARR_Missing;
3084
3085
        // Load the AST file.
3086
0
        auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
3087
0
                                  Loaded, StoredSize, StoredModTime,
3088
0
                                  StoredSignature, Capabilities);
3089
3090
        // If we diagnosed a problem, produce a backtrace.
3091
0
        bool recompilingFinalized =
3092
0
            Result == OutOfDate && (Capabilities & ARR_OutOfDate) &&
3093
0
            getModuleManager().getModuleCache().isPCMFinal(F.FileName);
3094
0
        if (isDiagnosedResult(Result, Capabilities) || recompilingFinalized)
3095
0
          Diag(diag::note_module_file_imported_by)
3096
0
              << F.FileName << !F.ModuleName.empty() << F.ModuleName;
3097
0
        if (recompilingFinalized)
3098
0
          Diag(diag::note_module_file_conflict);
3099
3100
0
        switch (Result) {
3101
0
        case Failure: return Failure;
3102
          // If we have to ignore the dependency, we'll have to ignore this too.
3103
0
        case Missing:
3104
0
        case OutOfDate: return OutOfDate;
3105
0
        case VersionMismatch: return VersionMismatch;
3106
0
        case ConfigurationMismatch: return ConfigurationMismatch;
3107
0
        case HadErrors: return HadErrors;
3108
0
        case Success: break;
3109
0
        }
3110
0
      }
3111
0
      break;
3112
0
    }
3113
3114
0
    case ORIGINAL_FILE:
3115
0
      F.OriginalSourceFileID = FileID::get(Record[0]);
3116
0
      F.ActualOriginalSourceFileName = std::string(Blob);
3117
0
      F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
3118
0
      ResolveImportedPath(F, F.OriginalSourceFileName);
3119
0
      break;
3120
3121
0
    case ORIGINAL_FILE_ID:
3122
0
      F.OriginalSourceFileID = FileID::get(Record[0]);
3123
0
      break;
3124
3125
0
    case MODULE_NAME:
3126
0
      F.ModuleName = std::string(Blob);
3127
0
      Diag(diag::remark_module_import)
3128
0
          << F.ModuleName << F.FileName << (ImportedBy ? true : false)
3129
0
          << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
3130
0
      if (Listener)
3131
0
        Listener->ReadModuleName(F.ModuleName);
3132
3133
      // Validate the AST as soon as we have a name so we can exit early on
3134
      // failure.
3135
0
      if (ASTReadResult Result = readUnhashedControlBlockOnce())
3136
0
        return Result;
3137
3138
0
      break;
3139
3140
0
    case MODULE_DIRECTORY: {
3141
      // Save the BaseDirectory as written in the PCM for computing the module
3142
      // filename for the ModuleCache.
3143
0
      BaseDirectoryAsWritten = Blob;
3144
0
      assert(!F.ModuleName.empty() &&
3145
0
             "MODULE_DIRECTORY found before MODULE_NAME");
3146
0
      F.BaseDirectory = std::string(Blob);
3147
0
      if (!PP.getPreprocessorOpts().ModulesCheckRelocated)
3148
0
        break;
3149
      // If we've already loaded a module map file covering this module, we may
3150
      // have a better path for it (relative to the current build).
3151
0
      Module *M = PP.getHeaderSearchInfo().lookupModule(
3152
0
          F.ModuleName, SourceLocation(), /*AllowSearch*/ true,
3153
0
          /*AllowExtraModuleMapSearch*/ true);
3154
0
      if (M && M->Directory) {
3155
        // If we're implicitly loading a module, the base directory can't
3156
        // change between the build and use.
3157
        // Don't emit module relocation error if we have -fno-validate-pch
3158
0
        if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
3159
0
                  DisableValidationForModuleKind::Module) &&
3160
0
            F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {
3161
0
          auto BuildDir = PP.getFileManager().getOptionalDirectoryRef(Blob);
3162
0
          if (!BuildDir || *BuildDir != M->Directory) {
3163
0
            if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
3164
0
              Diag(diag::err_imported_module_relocated)
3165
0
                  << F.ModuleName << Blob << M->Directory->getName();
3166
0
            return OutOfDate;
3167
0
          }
3168
0
        }
3169
0
        F.BaseDirectory = std::string(M->Directory->getName());
3170
0
      }
3171
0
      break;
3172
0
    }
3173
3174
0
    case MODULE_MAP_FILE:
3175
0
      if (ASTReadResult Result =
3176
0
              ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
3177
0
        return Result;
3178
0
      break;
3179
3180
0
    case INPUT_FILE_OFFSETS:
3181
0
      NumInputs = Record[0];
3182
0
      NumUserInputs = Record[1];
3183
0
      F.InputFileOffsets =
3184
0
          (const llvm::support::unaligned_uint64_t *)Blob.data();
3185
0
      F.InputFilesLoaded.resize(NumInputs);
3186
0
      F.InputFileInfosLoaded.resize(NumInputs);
3187
0
      F.NumUserInputFiles = NumUserInputs;
3188
0
      break;
3189
0
    }
3190
0
  }
3191
0
}
3192
3193
llvm::Error ASTReader::ReadASTBlock(ModuleFile &F,
3194
0
                                    unsigned ClientLoadCapabilities) {
3195
0
  BitstreamCursor &Stream = F.Stream;
3196
3197
0
  if (llvm::Error Err = Stream.EnterSubBlock(AST_BLOCK_ID))
3198
0
    return Err;
3199
0
  F.ASTBlockStartOffset = Stream.GetCurrentBitNo();
3200
3201
  // Read all of the records and blocks for the AST file.
3202
0
  RecordData Record;
3203
0
  while (true) {
3204
0
    Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3205
0
    if (!MaybeEntry)
3206
0
      return MaybeEntry.takeError();
3207
0
    llvm::BitstreamEntry Entry = MaybeEntry.get();
3208
3209
0
    switch (Entry.Kind) {
3210
0
    case llvm::BitstreamEntry::Error:
3211
0
      return llvm::createStringError(
3212
0
          std::errc::illegal_byte_sequence,
3213
0
          "error at end of module block in AST file");
3214
0
    case llvm::BitstreamEntry::EndBlock:
3215
      // Outside of C++, we do not store a lookup map for the translation unit.
3216
      // Instead, mark it as needing a lookup map to be built if this module
3217
      // contains any declarations lexically within it (which it always does!).
3218
      // This usually has no cost, since we very rarely need the lookup map for
3219
      // the translation unit outside C++.
3220
0
      if (ASTContext *Ctx = ContextObj) {
3221
0
        DeclContext *DC = Ctx->getTranslationUnitDecl();
3222
0
        if (DC->hasExternalLexicalStorage() && !Ctx->getLangOpts().CPlusPlus)
3223
0
          DC->setMustBuildLookupTable();
3224
0
      }
3225
3226
0
      return llvm::Error::success();
3227
0
    case llvm::BitstreamEntry::SubBlock:
3228
0
      switch (Entry.ID) {
3229
0
      case DECLTYPES_BLOCK_ID:
3230
        // We lazily load the decls block, but we want to set up the
3231
        // DeclsCursor cursor to point into it.  Clone our current bitcode
3232
        // cursor to it, enter the block and read the abbrevs in that block.
3233
        // With the main cursor, we just skip over it.
3234
0
        F.DeclsCursor = Stream;
3235
0
        if (llvm::Error Err = Stream.SkipBlock())
3236
0
          return Err;
3237
0
        if (llvm::Error Err = ReadBlockAbbrevs(
3238
0
                F.DeclsCursor, DECLTYPES_BLOCK_ID, &F.DeclsBlockStartOffset))
3239
0
          return Err;
3240
0
        break;
3241
3242
0
      case PREPROCESSOR_BLOCK_ID:
3243
0
        F.MacroCursor = Stream;
3244
0
        if (!PP.getExternalSource())
3245
0
          PP.setExternalSource(this);
3246
3247
0
        if (llvm::Error Err = Stream.SkipBlock())
3248
0
          return Err;
3249
0
        if (llvm::Error Err =
3250
0
                ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID))
3251
0
          return Err;
3252
0
        F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
3253
0
        break;
3254
3255
0
      case PREPROCESSOR_DETAIL_BLOCK_ID:
3256
0
        F.PreprocessorDetailCursor = Stream;
3257
3258
0
        if (llvm::Error Err = Stream.SkipBlock()) {
3259
0
          return Err;
3260
0
        }
3261
0
        if (llvm::Error Err = ReadBlockAbbrevs(F.PreprocessorDetailCursor,
3262
0
                                               PREPROCESSOR_DETAIL_BLOCK_ID))
3263
0
          return Err;
3264
0
        F.PreprocessorDetailStartOffset
3265
0
        = F.PreprocessorDetailCursor.GetCurrentBitNo();
3266
3267
0
        if (!PP.getPreprocessingRecord())
3268
0
          PP.createPreprocessingRecord();
3269
0
        if (!PP.getPreprocessingRecord()->getExternalSource())
3270
0
          PP.getPreprocessingRecord()->SetExternalSource(*this);
3271
0
        break;
3272
3273
0
      case SOURCE_MANAGER_BLOCK_ID:
3274
0
        if (llvm::Error Err = ReadSourceManagerBlock(F))
3275
0
          return Err;
3276
0
        break;
3277
3278
0
      case SUBMODULE_BLOCK_ID:
3279
0
        if (llvm::Error Err = ReadSubmoduleBlock(F, ClientLoadCapabilities))
3280
0
          return Err;
3281
0
        break;
3282
3283
0
      case COMMENTS_BLOCK_ID: {
3284
0
        BitstreamCursor C = Stream;
3285
3286
0
        if (llvm::Error Err = Stream.SkipBlock())
3287
0
          return Err;
3288
0
        if (llvm::Error Err = ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID))
3289
0
          return Err;
3290
0
        CommentsCursors.push_back(std::make_pair(C, &F));
3291
0
        break;
3292
0
      }
3293
3294
0
      default:
3295
0
        if (llvm::Error Err = Stream.SkipBlock())
3296
0
          return Err;
3297
0
        break;
3298
0
      }
3299
0
      continue;
3300
3301
0
    case llvm::BitstreamEntry::Record:
3302
      // The interesting case.
3303
0
      break;
3304
0
    }
3305
3306
    // Read and process a record.
3307
0
    Record.clear();
3308
0
    StringRef Blob;
3309
0
    Expected<unsigned> MaybeRecordType =
3310
0
        Stream.readRecord(Entry.ID, Record, &Blob);
3311
0
    if (!MaybeRecordType)
3312
0
      return MaybeRecordType.takeError();
3313
0
    ASTRecordTypes RecordType = (ASTRecordTypes)MaybeRecordType.get();
3314
3315
    // If we're not loading an AST context, we don't care about most records.
3316
0
    if (!ContextObj) {
3317
0
      switch (RecordType) {
3318
0
      case IDENTIFIER_TABLE:
3319
0
      case IDENTIFIER_OFFSET:
3320
0
      case INTERESTING_IDENTIFIERS:
3321
0
      case STATISTICS:
3322
0
      case PP_ASSUME_NONNULL_LOC:
3323
0
      case PP_CONDITIONAL_STACK:
3324
0
      case PP_COUNTER_VALUE:
3325
0
      case SOURCE_LOCATION_OFFSETS:
3326
0
      case MODULE_OFFSET_MAP:
3327
0
      case SOURCE_MANAGER_LINE_TABLE:
3328
0
      case PPD_ENTITIES_OFFSETS:
3329
0
      case HEADER_SEARCH_TABLE:
3330
0
      case IMPORTED_MODULES:
3331
0
      case MACRO_OFFSET:
3332
0
        break;
3333
0
      default:
3334
0
        continue;
3335
0
      }
3336
0
    }
3337
3338
0
    switch (RecordType) {
3339
0
    default:  // Default behavior: ignore.
3340
0
      break;
3341
3342
0
    case TYPE_OFFSET: {
3343
0
      if (F.LocalNumTypes != 0)
3344
0
        return llvm::createStringError(
3345
0
            std::errc::illegal_byte_sequence,
3346
0
            "duplicate TYPE_OFFSET record in AST file");
3347
0
      F.TypeOffsets = reinterpret_cast<const UnderalignedInt64 *>(Blob.data());
3348
0
      F.LocalNumTypes = Record[0];
3349
0
      unsigned LocalBaseTypeIndex = Record[1];
3350
0
      F.BaseTypeIndex = getTotalNumTypes();
3351
3352
0
      if (F.LocalNumTypes > 0) {
3353
        // Introduce the global -> local mapping for types within this module.
3354
0
        GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
3355
3356
        // Introduce the local -> global mapping for types within this module.
3357
0
        F.TypeRemap.insertOrReplace(
3358
0
          std::make_pair(LocalBaseTypeIndex,
3359
0
                         F.BaseTypeIndex - LocalBaseTypeIndex));
3360
3361
0
        TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
3362
0
      }
3363
0
      break;
3364
0
    }
3365
3366
0
    case DECL_OFFSET: {
3367
0
      if (F.LocalNumDecls != 0)
3368
0
        return llvm::createStringError(
3369
0
            std::errc::illegal_byte_sequence,
3370
0
            "duplicate DECL_OFFSET record in AST file");
3371
0
      F.DeclOffsets = (const DeclOffset *)Blob.data();
3372
0
      F.LocalNumDecls = Record[0];
3373
0
      unsigned LocalBaseDeclID = Record[1];
3374
0
      F.BaseDeclID = getTotalNumDecls();
3375
3376
0
      if (F.LocalNumDecls > 0) {
3377
        // Introduce the global -> local mapping for declarations within this
3378
        // module.
3379
0
        GlobalDeclMap.insert(
3380
0
          std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
3381
3382
        // Introduce the local -> global mapping for declarations within this
3383
        // module.
3384
0
        F.DeclRemap.insertOrReplace(
3385
0
          std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
3386
3387
        // Introduce the global -> local mapping for declarations within this
3388
        // module.
3389
0
        F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
3390
3391
0
        DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
3392
0
      }
3393
0
      break;
3394
0
    }
3395
3396
0
    case TU_UPDATE_LEXICAL: {
3397
0
      DeclContext *TU = ContextObj->getTranslationUnitDecl();
3398
0
      LexicalContents Contents(
3399
0
          reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
3400
0
              Blob.data()),
3401
0
          static_cast<unsigned int>(Blob.size() / 4));
3402
0
      TULexicalDecls.push_back(std::make_pair(&F, Contents));
3403
0
      TU->setHasExternalLexicalStorage(true);
3404
0
      break;
3405
0
    }
3406
3407
0
    case UPDATE_VISIBLE: {
3408
0
      unsigned Idx = 0;
3409
0
      serialization::DeclID ID = ReadDeclID(F, Record, Idx);
3410
0
      auto *Data = (const unsigned char*)Blob.data();
3411
0
      PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
3412
      // If we've already loaded the decl, perform the updates when we finish
3413
      // loading this block.
3414
0
      if (Decl *D = GetExistingDecl(ID))
3415
0
        PendingUpdateRecords.push_back(
3416
0
            PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3417
0
      break;
3418
0
    }
3419
3420
0
    case IDENTIFIER_TABLE:
3421
0
      F.IdentifierTableData =
3422
0
          reinterpret_cast<const unsigned char *>(Blob.data());
3423
0
      if (Record[0]) {
3424
0
        F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
3425
0
            F.IdentifierTableData + Record[0],
3426
0
            F.IdentifierTableData + sizeof(uint32_t),
3427
0
            F.IdentifierTableData,
3428
0
            ASTIdentifierLookupTrait(*this, F));
3429
3430
0
        PP.getIdentifierTable().setExternalIdentifierLookup(this);
3431
0
      }
3432
0
      break;
3433
3434
0
    case IDENTIFIER_OFFSET: {
3435
0
      if (F.LocalNumIdentifiers != 0)
3436
0
        return llvm::createStringError(
3437
0
            std::errc::illegal_byte_sequence,
3438
0
            "duplicate IDENTIFIER_OFFSET record in AST file");
3439
0
      F.IdentifierOffsets = (const uint32_t *)Blob.data();
3440
0
      F.LocalNumIdentifiers = Record[0];
3441
0
      unsigned LocalBaseIdentifierID = Record[1];
3442
0
      F.BaseIdentifierID = getTotalNumIdentifiers();
3443
3444
0
      if (F.LocalNumIdentifiers > 0) {
3445
        // Introduce the global -> local mapping for identifiers within this
3446
        // module.
3447
0
        GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
3448
0
                                                  &F));
3449
3450
        // Introduce the local -> global mapping for identifiers within this
3451
        // module.
3452
0
        F.IdentifierRemap.insertOrReplace(
3453
0
          std::make_pair(LocalBaseIdentifierID,
3454
0
                         F.BaseIdentifierID - LocalBaseIdentifierID));
3455
3456
0
        IdentifiersLoaded.resize(IdentifiersLoaded.size()
3457
0
                                 + F.LocalNumIdentifiers);
3458
0
      }
3459
0
      break;
3460
0
    }
3461
3462
0
    case INTERESTING_IDENTIFIERS:
3463
0
      F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
3464
0
      break;
3465
3466
0
    case EAGERLY_DESERIALIZED_DECLS:
3467
      // FIXME: Skip reading this record if our ASTConsumer doesn't care
3468
      // about "interesting" decls (for instance, if we're building a module).
3469
0
      for (unsigned I = 0, N = Record.size(); I != N; ++I)
3470
0
        EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
3471
0
      break;
3472
3473
0
    case MODULAR_CODEGEN_DECLS:
3474
      // FIXME: Skip reading this record if our ASTConsumer doesn't care about
3475
      // them (ie: if we're not codegenerating this module).
3476
0
      if (F.Kind == MK_MainFile ||
3477
0
          getContext().getLangOpts().BuildingPCHWithObjectFile)
3478
0
        for (unsigned I = 0, N = Record.size(); I != N; ++I)
3479
0
          EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
3480
0
      break;
3481
3482
0
    case SPECIAL_TYPES:
3483
0
      if (SpecialTypes.empty()) {
3484
0
        for (unsigned I = 0, N = Record.size(); I != N; ++I)
3485
0
          SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
3486
0
        break;
3487
0
      }
3488
3489
0
      if (SpecialTypes.size() != Record.size())
3490
0
        return llvm::createStringError(std::errc::illegal_byte_sequence,
3491
0
                                       "invalid special-types record");
3492
3493
0
      for (unsigned I = 0, N = Record.size(); I != N; ++I) {
3494
0
        serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
3495
0
        if (!SpecialTypes[I])
3496
0
          SpecialTypes[I] = ID;
3497
        // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
3498
        // merge step?
3499
0
      }
3500
0
      break;
3501
3502
0
    case STATISTICS:
3503
0
      TotalNumStatements += Record[0];
3504
0
      TotalNumMacros += Record[1];
3505
0
      TotalLexicalDeclContexts += Record[2];
3506
0
      TotalVisibleDeclContexts += Record[3];
3507
0
      break;
3508
3509
0
    case UNUSED_FILESCOPED_DECLS:
3510
0
      for (unsigned I = 0, N = Record.size(); I != N; ++I)
3511
0
        UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
3512
0
      break;
3513
3514
0
    case DELEGATING_CTORS:
3515
0
      for (unsigned I = 0, N = Record.size(); I != N; ++I)
3516
0
        DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
3517
0
      break;
3518
3519
0
    case WEAK_UNDECLARED_IDENTIFIERS:
3520
0
      if (Record.size() % 3 != 0)
3521
0
        return llvm::createStringError(std::errc::illegal_byte_sequence,
3522
0
                                       "invalid weak identifiers record");
3523
3524
      // FIXME: Ignore weak undeclared identifiers from non-original PCH
3525
      // files. This isn't the way to do it :)
3526
0
      WeakUndeclaredIdentifiers.clear();
3527
3528
      // Translate the weak, undeclared identifiers into global IDs.
3529
0
      for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
3530
0
        WeakUndeclaredIdentifiers.push_back(
3531
0
          getGlobalIdentifierID(F, Record[I++]));
3532
0
        WeakUndeclaredIdentifiers.push_back(
3533
0
          getGlobalIdentifierID(F, Record[I++]));
3534
0
        WeakUndeclaredIdentifiers.push_back(
3535
0
            ReadSourceLocation(F, Record, I).getRawEncoding());
3536
0
      }
3537
0
      break;
3538
3539
0
    case SELECTOR_OFFSETS: {
3540
0
      F.SelectorOffsets = (const uint32_t *)Blob.data();
3541
0
      F.LocalNumSelectors = Record[0];
3542
0
      unsigned LocalBaseSelectorID = Record[1];
3543
0
      F.BaseSelectorID = getTotalNumSelectors();
3544
3545
0
      if (F.LocalNumSelectors > 0) {
3546
        // Introduce the global -> local mapping for selectors within this
3547
        // module.
3548
0
        GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
3549
3550
        // Introduce the local -> global mapping for selectors within this
3551
        // module.
3552
0
        F.SelectorRemap.insertOrReplace(
3553
0
          std::make_pair(LocalBaseSelectorID,
3554
0
                         F.BaseSelectorID - LocalBaseSelectorID));
3555
3556
0
        SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
3557
0
      }
3558
0
      break;
3559
0
    }
3560
3561
0
    case METHOD_POOL:
3562
0
      F.SelectorLookupTableData = (const unsigned char *)Blob.data();
3563
0
      if (Record[0])
3564
0
        F.SelectorLookupTable
3565
0
          = ASTSelectorLookupTable::Create(
3566
0
                        F.SelectorLookupTableData + Record[0],
3567
0
                        F.SelectorLookupTableData,
3568
0
                        ASTSelectorLookupTrait(*this, F));
3569
0
      TotalNumMethodPoolEntries += Record[1];
3570
0
      break;
3571
3572
0
    case REFERENCED_SELECTOR_POOL:
3573
0
      if (!Record.empty()) {
3574
0
        for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
3575
0
          ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
3576
0
                                                                Record[Idx++]));
3577
0
          ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
3578
0
                                              getRawEncoding());
3579
0
        }
3580
0
      }
3581
0
      break;
3582
3583
0
    case PP_ASSUME_NONNULL_LOC: {
3584
0
      unsigned Idx = 0;
3585
0
      if (!Record.empty())
3586
0
        PP.setPreambleRecordedPragmaAssumeNonNullLoc(
3587
0
            ReadSourceLocation(F, Record, Idx));
3588
0
      break;
3589
0
    }
3590
3591
0
    case PP_CONDITIONAL_STACK:
3592
0
      if (!Record.empty()) {
3593
0
        unsigned Idx = 0, End = Record.size() - 1;
3594
0
        bool ReachedEOFWhileSkipping = Record[Idx++];
3595
0
        std::optional<Preprocessor::PreambleSkipInfo> SkipInfo;
3596
0
        if (ReachedEOFWhileSkipping) {
3597
0
          SourceLocation HashToken = ReadSourceLocation(F, Record, Idx);
3598
0
          SourceLocation IfTokenLoc = ReadSourceLocation(F, Record, Idx);
3599
0
          bool FoundNonSkipPortion = Record[Idx++];
3600
0
          bool FoundElse = Record[Idx++];
3601
0
          SourceLocation ElseLoc = ReadSourceLocation(F, Record, Idx);
3602
0
          SkipInfo.emplace(HashToken, IfTokenLoc, FoundNonSkipPortion,
3603
0
                           FoundElse, ElseLoc);
3604
0
        }
3605
0
        SmallVector<PPConditionalInfo, 4> ConditionalStack;
3606
0
        while (Idx < End) {
3607
0
          auto Loc = ReadSourceLocation(F, Record, Idx);
3608
0
          bool WasSkipping = Record[Idx++];
3609
0
          bool FoundNonSkip = Record[Idx++];
3610
0
          bool FoundElse = Record[Idx++];
3611
0
          ConditionalStack.push_back(
3612
0
              {Loc, WasSkipping, FoundNonSkip, FoundElse});
3613
0
        }
3614
0
        PP.setReplayablePreambleConditionalStack(ConditionalStack, SkipInfo);
3615
0
      }
3616
0
      break;
3617
3618
0
    case PP_COUNTER_VALUE:
3619
0
      if (!Record.empty() && Listener)
3620
0
        Listener->ReadCounter(F, Record[0]);
3621
0
      break;
3622
3623
0
    case FILE_SORTED_DECLS:
3624
0
      F.FileSortedDecls = (const DeclID *)Blob.data();
3625
0
      F.NumFileSortedDecls = Record[0];
3626
0
      break;
3627
3628
0
    case SOURCE_LOCATION_OFFSETS: {
3629
0
      F.SLocEntryOffsets = (const uint32_t *)Blob.data();
3630
0
      F.LocalNumSLocEntries = Record[0];
3631
0
      SourceLocation::UIntTy SLocSpaceSize = Record[1];
3632
0
      F.SLocEntryOffsetsBase = Record[2] + F.SourceManagerBlockStartOffset;
3633
0
      std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
3634
0
          SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
3635
0
                                              SLocSpaceSize);
3636
0
      if (!F.SLocEntryBaseID) {
3637
0
        if (!Diags.isDiagnosticInFlight()) {
3638
0
          Diags.Report(SourceLocation(), diag::remark_sloc_usage);
3639
0
          SourceMgr.noteSLocAddressSpaceUsage(Diags);
3640
0
        }
3641
0
        return llvm::createStringError(std::errc::invalid_argument,
3642
0
                                       "ran out of source locations");
3643
0
      }
3644
      // Make our entry in the range map. BaseID is negative and growing, so
3645
      // we invert it. Because we invert it, though, we need the other end of
3646
      // the range.
3647
0
      unsigned RangeStart =
3648
0
          unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
3649
0
      GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
3650
0
      F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
3651
3652
      // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
3653
0
      assert((F.SLocEntryBaseOffset & SourceLocation::MacroIDBit) == 0);
3654
0
      GlobalSLocOffsetMap.insert(
3655
0
          std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
3656
0
                           - SLocSpaceSize,&F));
3657
3658
      // Initialize the remapping table.
3659
      // Invalid stays invalid.
3660
0
      F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
3661
      // This module. Base was 2 when being compiled.
3662
0
      F.SLocRemap.insertOrReplace(std::make_pair(
3663
0
          2U, static_cast<SourceLocation::IntTy>(F.SLocEntryBaseOffset - 2)));
3664
3665
0
      TotalNumSLocEntries += F.LocalNumSLocEntries;
3666
0
      break;
3667
0
    }
3668
3669
0
    case MODULE_OFFSET_MAP:
3670
0
      F.ModuleOffsetMap = Blob;
3671
0
      break;
3672
3673
0
    case SOURCE_MANAGER_LINE_TABLE:
3674
0
      ParseLineTable(F, Record);
3675
0
      break;
3676
3677
0
    case EXT_VECTOR_DECLS:
3678
0
      for (unsigned I = 0, N = Record.size(); I != N; ++I)
3679
0
        ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
3680
0
      break;
3681
3682
0
    case VTABLE_USES:
3683
0
      if (Record.size() % 3 != 0)
3684
0
        return llvm::createStringError(std::errc::illegal_byte_sequence,
3685
0
                                       "Invalid VTABLE_USES record");
3686
3687
      // Later tables overwrite earlier ones.
3688
      // FIXME: Modules will have some trouble with this. This is clearly not
3689
      // the right way to do this.
3690
0
      VTableUses.clear();
3691
3692
0
      for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3693
0
        VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3694
0
        VTableUses.push_back(
3695
0
          ReadSourceLocation(F, Record, Idx).getRawEncoding());
3696
0
        VTableUses.push_back(Record[Idx++]);
3697
0
      }
3698
0
      break;
3699
3700
0
    case PENDING_IMPLICIT_INSTANTIATIONS:
3701
0
      if (PendingInstantiations.size() % 2 != 0)
3702
0
        return llvm::createStringError(
3703
0
            std::errc::illegal_byte_sequence,
3704
0
            "Invalid existing PendingInstantiations");
3705
3706
0
      if (Record.size() % 2 != 0)
3707
0
        return llvm::createStringError(
3708
0
            std::errc::illegal_byte_sequence,
3709
0
            "Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
3710
3711
0
      for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3712
0
        PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3713
0
        PendingInstantiations.push_back(
3714
0
          ReadSourceLocation(F, Record, I).getRawEncoding());
3715
0
      }
3716
0
      break;
3717
3718
0
    case SEMA_DECL_REFS:
3719
0
      if (Record.size() != 3)
3720
0
        return llvm::createStringError(std::errc::illegal_byte_sequence,
3721
0
                                       "Invalid SEMA_DECL_REFS block");
3722
0
      for (unsigned I = 0, N = Record.size(); I != N; ++I)
3723
0
        SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3724
0
      break;
3725
3726
0
    case PPD_ENTITIES_OFFSETS: {
3727
0
      F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3728
0
      assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3729
0
      F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
3730
3731
0
      unsigned LocalBasePreprocessedEntityID = Record[0];
3732
3733
0
      unsigned StartingID;
3734
0
      if (!PP.getPreprocessingRecord())
3735
0
        PP.createPreprocessingRecord();
3736
0
      if (!PP.getPreprocessingRecord()->getExternalSource())
3737
0
        PP.getPreprocessingRecord()->SetExternalSource(*this);
3738
0
      StartingID
3739
0
        = PP.getPreprocessingRecord()
3740
0
            ->allocateLoadedEntities(F.NumPreprocessedEntities);
3741
0
      F.BasePreprocessedEntityID = StartingID;
3742
3743
0
      if (F.NumPreprocessedEntities > 0) {
3744
        // Introduce the global -> local mapping for preprocessed entities in
3745
        // this module.
3746
0
        GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
3747
3748
        // Introduce the local -> global mapping for preprocessed entities in
3749
        // this module.
3750
0
        F.PreprocessedEntityRemap.insertOrReplace(
3751
0
          std::make_pair(LocalBasePreprocessedEntityID,
3752
0
            F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3753
0
      }
3754
3755
0
      break;
3756
0
    }
3757
3758
0
    case PPD_SKIPPED_RANGES: {
3759
0
      F.PreprocessedSkippedRangeOffsets = (const PPSkippedRange*)Blob.data();
3760
0
      assert(Blob.size() % sizeof(PPSkippedRange) == 0);
3761
0
      F.NumPreprocessedSkippedRanges = Blob.size() / sizeof(PPSkippedRange);
3762
3763
0
      if (!PP.getPreprocessingRecord())
3764
0
        PP.createPreprocessingRecord();
3765
0
      if (!PP.getPreprocessingRecord()->getExternalSource())
3766
0
        PP.getPreprocessingRecord()->SetExternalSource(*this);
3767
0
      F.BasePreprocessedSkippedRangeID = PP.getPreprocessingRecord()
3768
0
          ->allocateSkippedRanges(F.NumPreprocessedSkippedRanges);
3769
3770
0
      if (F.NumPreprocessedSkippedRanges > 0)
3771
0
        GlobalSkippedRangeMap.insert(
3772
0
            std::make_pair(F.BasePreprocessedSkippedRangeID, &F));
3773
0
      break;
3774
0
    }
3775
3776
0
    case DECL_UPDATE_OFFSETS:
3777
0
      if (Record.size() % 2 != 0)
3778
0
        return llvm::createStringError(
3779
0
            std::errc::illegal_byte_sequence,
3780
0
            "invalid DECL_UPDATE_OFFSETS block in AST file");
3781
0
      for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3782
0
        GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3783
0
        DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3784
3785
        // If we've already loaded the decl, perform the updates when we finish
3786
        // loading this block.
3787
0
        if (Decl *D = GetExistingDecl(ID))
3788
0
          PendingUpdateRecords.push_back(
3789
0
              PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3790
0
      }
3791
0
      break;
3792
3793
0
    case OBJC_CATEGORIES_MAP:
3794
0
      if (F.LocalNumObjCCategoriesInMap != 0)
3795
0
        return llvm::createStringError(
3796
0
            std::errc::illegal_byte_sequence,
3797
0
            "duplicate OBJC_CATEGORIES_MAP record in AST file");
3798
3799
0
      F.LocalNumObjCCategoriesInMap = Record[0];
3800
0
      F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
3801
0
      break;
3802
3803
0
    case OBJC_CATEGORIES:
3804
0
      F.ObjCCategories.swap(Record);
3805
0
      break;
3806
3807
0
    case CUDA_SPECIAL_DECL_REFS:
3808
      // Later tables overwrite earlier ones.
3809
      // FIXME: Modules will have trouble with this.
3810
0
      CUDASpecialDeclRefs.clear();
3811
0
      for (unsigned I = 0, N = Record.size(); I != N; ++I)
3812
0
        CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3813
0
      break;
3814
3815
0
    case HEADER_SEARCH_TABLE:
3816
0
      F.HeaderFileInfoTableData = Blob.data();
3817
0
      F.LocalNumHeaderFileInfos = Record[1];
3818
0
      if (Record[0]) {
3819
0
        F.HeaderFileInfoTable
3820
0
          = HeaderFileInfoLookupTable::Create(
3821
0
                   (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3822
0
                   (const unsigned char *)F.HeaderFileInfoTableData,
3823
0
                   HeaderFileInfoTrait(*this, F,
3824
0
                                       &PP.getHeaderSearchInfo(),
3825
0
                                       Blob.data() + Record[2]));
3826
3827
0
        PP.getHeaderSearchInfo().SetExternalSource(this);
3828
0
        if (!PP.getHeaderSearchInfo().getExternalLookup())
3829
0
          PP.getHeaderSearchInfo().SetExternalLookup(this);
3830
0
      }
3831
0
      break;
3832
3833
0
    case FP_PRAGMA_OPTIONS:
3834
      // Later tables overwrite earlier ones.
3835
0
      FPPragmaOptions.swap(Record);
3836
0
      break;
3837
3838
0
    case OPENCL_EXTENSIONS:
3839
0
      for (unsigned I = 0, E = Record.size(); I != E; ) {
3840
0
        auto Name = ReadString(Record, I);
3841
0
        auto &OptInfo = OpenCLExtensions.OptMap[Name];
3842
0
        OptInfo.Supported = Record[I++] != 0;
3843
0
        OptInfo.Enabled = Record[I++] != 0;
3844
0
        OptInfo.WithPragma = Record[I++] != 0;
3845
0
        OptInfo.Avail = Record[I++];
3846
0
        OptInfo.Core = Record[I++];
3847
0
        OptInfo.Opt = Record[I++];
3848
0
      }
3849
0
      break;
3850
3851
0
    case TENTATIVE_DEFINITIONS:
3852
0
      for (unsigned I = 0, N = Record.size(); I != N; ++I)
3853
0
        TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3854
0
      break;
3855
3856
0
    case KNOWN_NAMESPACES:
3857
0
      for (unsigned I = 0, N = Record.size(); I != N; ++I)
3858
0
        KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3859
0
      break;
3860
3861
0
    case UNDEFINED_BUT_USED:
3862
0
      if (UndefinedButUsed.size() % 2 != 0)
3863
0
        return llvm::createStringError(std::errc::illegal_byte_sequence,
3864
0
                                       "Invalid existing UndefinedButUsed");
3865
3866
0
      if (Record.size() % 2 != 0)
3867
0
        return llvm::createStringError(std::errc::illegal_byte_sequence,
3868
0
                                       "invalid undefined-but-used record");
3869
0
      for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3870
0
        UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3871
0
        UndefinedButUsed.push_back(
3872
0
            ReadSourceLocation(F, Record, I).getRawEncoding());
3873
0
      }
3874
0
      break;
3875
3876
0
    case DELETE_EXPRS_TO_ANALYZE:
3877
0
      for (unsigned I = 0, N = Record.size(); I != N;) {
3878
0
        DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3879
0
        const uint64_t Count = Record[I++];
3880
0
        DelayedDeleteExprs.push_back(Count);
3881
0
        for (uint64_t C = 0; C < Count; ++C) {
3882
0
          DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3883
0
          bool IsArrayForm = Record[I++] == 1;
3884
0
          DelayedDeleteExprs.push_back(IsArrayForm);
3885
0
        }
3886
0
      }
3887
0
      break;
3888
3889
0
    case IMPORTED_MODULES:
3890
0
      if (!F.isModule()) {
3891
        // If we aren't loading a module (which has its own exports), make
3892
        // all of the imported modules visible.
3893
        // FIXME: Deal with macros-only imports.
3894
0
        for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3895
0
          unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3896
0
          SourceLocation Loc = ReadSourceLocation(F, Record, I);
3897
0
          if (GlobalID) {
3898
0
            PendingImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
3899
0
            if (DeserializationListener)
3900
0
              DeserializationListener->ModuleImportRead(GlobalID, Loc);
3901
0
          }
3902
0
        }
3903
0
      }
3904
0
      break;
3905
3906
0
    case MACRO_OFFSET: {
3907
0
      if (F.LocalNumMacros != 0)
3908
0
        return llvm::createStringError(
3909
0
            std::errc::illegal_byte_sequence,
3910
0
            "duplicate MACRO_OFFSET record in AST file");
3911
0
      F.MacroOffsets = (const uint32_t *)Blob.data();
3912
0
      F.LocalNumMacros = Record[0];
3913
0
      unsigned LocalBaseMacroID = Record[1];
3914
0
      F.MacroOffsetsBase = Record[2] + F.ASTBlockStartOffset;
3915
0
      F.BaseMacroID = getTotalNumMacros();
3916
3917
0
      if (F.LocalNumMacros > 0) {
3918
        // Introduce the global -> local mapping for macros within this module.
3919
0
        GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3920
3921
        // Introduce the local -> global mapping for macros within this module.
3922
0
        F.MacroRemap.insertOrReplace(
3923
0
          std::make_pair(LocalBaseMacroID,
3924
0
                         F.BaseMacroID - LocalBaseMacroID));
3925
3926
0
        MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
3927
0
      }
3928
0
      break;
3929
0
    }
3930
3931
0
    case LATE_PARSED_TEMPLATE:
3932
0
      LateParsedTemplates.emplace_back(
3933
0
          std::piecewise_construct, std::forward_as_tuple(&F),
3934
0
          std::forward_as_tuple(Record.begin(), Record.end()));
3935
0
      break;
3936
3937
0
    case OPTIMIZE_PRAGMA_OPTIONS:
3938
0
      if (Record.size() != 1)
3939
0
        return llvm::createStringError(std::errc::illegal_byte_sequence,
3940
0
                                       "invalid pragma optimize record");
3941
0
      OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3942
0
      break;
3943
3944
0
    case MSSTRUCT_PRAGMA_OPTIONS:
3945
0
      if (Record.size() != 1)
3946
0
        return llvm::createStringError(std::errc::illegal_byte_sequence,
3947
0
                                       "invalid pragma ms_struct record");
3948
0
      PragmaMSStructState = Record[0];
3949
0
      break;
3950
3951
0
    case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS:
3952
0
      if (Record.size() != 2)
3953
0
        return llvm::createStringError(
3954
0
            std::errc::illegal_byte_sequence,
3955
0
            "invalid pragma pointers to members record");
3956
0
      PragmaMSPointersToMembersState = Record[0];
3957
0
      PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
3958
0
      break;
3959
3960
0
    case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3961
0
      for (unsigned I = 0, N = Record.size(); I != N; ++I)
3962
0
        UnusedLocalTypedefNameCandidates.push_back(
3963
0
            getGlobalDeclID(F, Record[I]));
3964
0
      break;
3965
3966
0
    case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH:
3967
0
      if (Record.size() != 1)
3968
0
        return llvm::createStringError(std::errc::illegal_byte_sequence,
3969
0
                                       "invalid cuda pragma options record");
3970
0
      ForceCUDAHostDeviceDepth = Record[0];
3971
0
      break;
3972
3973
0
    case ALIGN_PACK_PRAGMA_OPTIONS: {
3974
0
      if (Record.size() < 3)
3975
0
        return llvm::createStringError(std::errc::illegal_byte_sequence,
3976
0
                                       "invalid pragma pack record");
3977
0
      PragmaAlignPackCurrentValue = ReadAlignPackInfo(Record[0]);
3978
0
      PragmaAlignPackCurrentLocation = ReadSourceLocation(F, Record[1]);
3979
0
      unsigned NumStackEntries = Record[2];
3980
0
      unsigned Idx = 3;
3981
      // Reset the stack when importing a new module.
3982
0
      PragmaAlignPackStack.clear();
3983
0
      for (unsigned I = 0; I < NumStackEntries; ++I) {
3984
0
        PragmaAlignPackStackEntry Entry;
3985
0
        Entry.Value = ReadAlignPackInfo(Record[Idx++]);
3986
0
        Entry.Location = ReadSourceLocation(F, Record[Idx++]);
3987
0
        Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
3988
0
        PragmaAlignPackStrings.push_back(ReadString(Record, Idx));
3989
0
        Entry.SlotLabel = PragmaAlignPackStrings.back();
3990
0
        PragmaAlignPackStack.push_back(Entry);
3991
0
      }
3992
0
      break;
3993
0
    }
3994
3995
0
    case FLOAT_CONTROL_PRAGMA_OPTIONS: {
3996
0
      if (Record.size() < 3)
3997
0
        return llvm::createStringError(std::errc::illegal_byte_sequence,
3998
0
                                       "invalid pragma float control record");
3999
0
      FpPragmaCurrentValue = FPOptionsOverride::getFromOpaqueInt(Record[0]);
4000
0
      FpPragmaCurrentLocation = ReadSourceLocation(F, Record[1]);
4001
0
      unsigned NumStackEntries = Record[2];
4002
0
      unsigned Idx = 3;
4003
      // Reset the stack when importing a new module.
4004
0
      FpPragmaStack.clear();
4005
0
      for (unsigned I = 0; I < NumStackEntries; ++I) {
4006
0
        FpPragmaStackEntry Entry;
4007
0
        Entry.Value = FPOptionsOverride::getFromOpaqueInt(Record[Idx++]);
4008
0
        Entry.Location = ReadSourceLocation(F, Record[Idx++]);
4009
0
        Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
4010
0
        FpPragmaStrings.push_back(ReadString(Record, Idx));
4011
0
        Entry.SlotLabel = FpPragmaStrings.back();
4012
0
        FpPragmaStack.push_back(Entry);
4013
0
      }
4014
0
      break;
4015
0
    }
4016
4017
0
    case DECLS_TO_CHECK_FOR_DEFERRED_DIAGS:
4018
0
      for (unsigned I = 0, N = Record.size(); I != N; ++I)
4019
0
        DeclsToCheckForDeferredDiags.insert(getGlobalDeclID(F, Record[I]));
4020
0
      break;
4021
0
    }
4022
0
  }
4023
0
}
4024
4025
0
void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
4026
0
  assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");
4027
4028
  // Additional remapping information.
4029
0
  const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();
4030
0
  const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();
4031
0
  F.ModuleOffsetMap = StringRef();
4032
4033
  // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
4034
0
  if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
4035
0
    F.SLocRemap.insert(std::make_pair(0U, 0));
4036
0
    F.SLocRemap.insert(std::make_pair(2U, 1));
4037
0
  }
4038
4039
  // Continuous range maps we may be updating in our module.
4040
0
  using SLocRemapBuilder =
4041
0
      ContinuousRangeMap<SourceLocation::UIntTy, SourceLocation::IntTy,
4042
0
                         2>::Builder;
4043
0
  using RemapBuilder = ContinuousRangeMap<uint32_t, int, 2>::Builder;
4044
0
  SLocRemapBuilder SLocRemap(F.SLocRemap);
4045
0
  RemapBuilder IdentifierRemap(F.IdentifierRemap);
4046
0
  RemapBuilder MacroRemap(F.MacroRemap);
4047
0
  RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
4048
0
  RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
4049
0
  RemapBuilder SelectorRemap(F.SelectorRemap);
4050
0
  RemapBuilder DeclRemap(F.DeclRemap);
4051
0
  RemapBuilder TypeRemap(F.TypeRemap);
4052
4053
0
  while (Data < DataEnd) {
4054
    // FIXME: Looking up dependency modules by filename is horrible. Let's
4055
    // start fixing this with prebuilt, explicit and implicit modules and see
4056
    // how it goes...
4057
0
    using namespace llvm::support;
4058
0
    ModuleKind Kind = static_cast<ModuleKind>(
4059
0
        endian::readNext<uint8_t, llvm::endianness::little, unaligned>(Data));
4060
0
    uint16_t Len =
4061
0
        endian::readNext<uint16_t, llvm::endianness::little, unaligned>(Data);
4062
0
    StringRef Name = StringRef((const char*)Data, Len);
4063
0
    Data += Len;
4064
0
    ModuleFile *OM = (Kind == MK_PrebuiltModule || Kind == MK_ExplicitModule ||
4065
0
                              Kind == MK_ImplicitModule
4066
0
                          ? ModuleMgr.lookupByModuleName(Name)
4067
0
                          : ModuleMgr.lookupByFileName(Name));
4068
0
    if (!OM) {
4069
0
      std::string Msg =
4070
0
          "SourceLocation remap refers to unknown module, cannot find ";
4071
0
      Msg.append(std::string(Name));
4072
0
      Error(Msg);
4073
0
      return;
4074
0
    }
4075
4076
0
    SourceLocation::UIntTy SLocOffset =
4077
0
        endian::readNext<uint32_t, llvm::endianness::little, unaligned>(Data);
4078
0
    uint32_t IdentifierIDOffset =
4079
0
        endian::readNext<uint32_t, llvm::endianness::little, unaligned>(Data);
4080
0
    uint32_t MacroIDOffset =
4081
0
        endian::readNext<uint32_t, llvm::endianness::little, unaligned>(Data);
4082
0
    uint32_t PreprocessedEntityIDOffset =
4083
0
        endian::readNext<uint32_t, llvm::endianness::little, unaligned>(Data);
4084
0
    uint32_t SubmoduleIDOffset =
4085
0
        endian::readNext<uint32_t, llvm::endianness::little, unaligned>(Data);
4086
0
    uint32_t SelectorIDOffset =
4087
0
        endian::readNext<uint32_t, llvm::endianness::little, unaligned>(Data);
4088
0
    uint32_t DeclIDOffset =
4089
0
        endian::readNext<uint32_t, llvm::endianness::little, unaligned>(Data);
4090
0
    uint32_t TypeIndexOffset =
4091
0
        endian::readNext<uint32_t, llvm::endianness::little, unaligned>(Data);
4092
4093
0
    auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
4094
0
                         RemapBuilder &Remap) {
4095
0
      constexpr uint32_t None = std::numeric_limits<uint32_t>::max();
4096
0
      if (Offset != None)
4097
0
        Remap.insert(std::make_pair(Offset,
4098
0
                                    static_cast<int>(BaseOffset - Offset)));
4099
0
    };
4100
4101
0
    constexpr SourceLocation::UIntTy SLocNone =
4102
0
        std::numeric_limits<SourceLocation::UIntTy>::max();
4103
0
    if (SLocOffset != SLocNone)
4104
0
      SLocRemap.insert(std::make_pair(
4105
0
          SLocOffset, static_cast<SourceLocation::IntTy>(
4106
0
                          OM->SLocEntryBaseOffset - SLocOffset)));
4107
4108
0
    mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
4109
0
    mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
4110
0
    mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
4111
0
              PreprocessedEntityRemap);
4112
0
    mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
4113
0
    mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
4114
0
    mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
4115
0
    mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
4116
4117
    // Global -> local mappings.
4118
0
    F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
4119
0
  }
4120
0
}
4121
4122
ASTReader::ASTReadResult
4123
ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
4124
                                  const ModuleFile *ImportedBy,
4125
0
                                  unsigned ClientLoadCapabilities) {
4126
0
  unsigned Idx = 0;
4127
0
  F.ModuleMapPath = ReadPath(F, Record, Idx);
4128
4129
  // Try to resolve ModuleName in the current header search context and
4130
  // verify that it is found in the same module map file as we saved. If the
4131
  // top-level AST file is a main file, skip this check because there is no
4132
  // usable header search context.
4133
0
  assert(!F.ModuleName.empty() &&
4134
0
         "MODULE_NAME should come before MODULE_MAP_FILE");
4135
0
  if (PP.getPreprocessorOpts().ModulesCheckRelocated &&
4136
0
      F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) {
4137
    // An implicitly-loaded module file should have its module listed in some
4138
    // module map file that we've already loaded.
4139
0
    Module *M =
4140
0
        PP.getHeaderSearchInfo().lookupModule(F.ModuleName, F.ImportLoc);
4141
0
    auto &Map = PP.getHeaderSearchInfo().getModuleMap();
4142
0
    OptionalFileEntryRef ModMap =
4143
0
        M ? Map.getModuleMapFileForUniquing(M) : std::nullopt;
4144
    // Don't emit module relocation error if we have -fno-validate-pch
4145
0
    if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
4146
0
              DisableValidationForModuleKind::Module) &&
4147
0
        !ModMap) {
4148
0
      if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities)) {
4149
0
        if (auto ASTFE = M ? M->getASTFile() : std::nullopt) {
4150
          // This module was defined by an imported (explicit) module.
4151
0
          Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
4152
0
                                               << ASTFE->getName();
4153
0
        } else {
4154
          // This module was built with a different module map.
4155
0
          Diag(diag::err_imported_module_not_found)
4156
0
              << F.ModuleName << F.FileName
4157
0
              << (ImportedBy ? ImportedBy->FileName : "") << F.ModuleMapPath
4158
0
              << !ImportedBy;
4159
          // In case it was imported by a PCH, there's a chance the user is
4160
          // just missing to include the search path to the directory containing
4161
          // the modulemap.
4162
0
          if (ImportedBy && ImportedBy->Kind == MK_PCH)
4163
0
            Diag(diag::note_imported_by_pch_module_not_found)
4164
0
                << llvm::sys::path::parent_path(F.ModuleMapPath);
4165
0
        }
4166
0
      }
4167
0
      return OutOfDate;
4168
0
    }
4169
4170
0
    assert(M && M->Name == F.ModuleName && "found module with different name");
4171
4172
    // Check the primary module map file.
4173
0
    auto StoredModMap = FileMgr.getFile(F.ModuleMapPath);
4174
0
    if (!StoredModMap || *StoredModMap != ModMap) {
4175
0
      assert(ModMap && "found module is missing module map file");
4176
0
      assert((ImportedBy || F.Kind == MK_ImplicitModule) &&
4177
0
             "top-level import should be verified");
4178
0
      bool NotImported = F.Kind == MK_ImplicitModule && !ImportedBy;
4179
0
      if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4180
0
        Diag(diag::err_imported_module_modmap_changed)
4181
0
            << F.ModuleName << (NotImported ? F.FileName : ImportedBy->FileName)
4182
0
            << ModMap->getName() << F.ModuleMapPath << NotImported;
4183
0
      return OutOfDate;
4184
0
    }
4185
4186
0
    ModuleMap::AdditionalModMapsSet AdditionalStoredMaps;
4187
0
    for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
4188
      // FIXME: we should use input files rather than storing names.
4189
0
      std::string Filename = ReadPath(F, Record, Idx);
4190
0
      auto SF = FileMgr.getOptionalFileRef(Filename, false, false);
4191
0
      if (!SF) {
4192
0
        if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4193
0
          Error("could not find file '" + Filename +"' referenced by AST file");
4194
0
        return OutOfDate;
4195
0
      }
4196
0
      AdditionalStoredMaps.insert(*SF);
4197
0
    }
4198
4199
    // Check any additional module map files (e.g. module.private.modulemap)
4200
    // that are not in the pcm.
4201
0
    if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
4202
0
      for (FileEntryRef ModMap : *AdditionalModuleMaps) {
4203
        // Remove files that match
4204
        // Note: SmallPtrSet::erase is really remove
4205
0
        if (!AdditionalStoredMaps.erase(ModMap)) {
4206
0
          if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4207
0
            Diag(diag::err_module_different_modmap)
4208
0
              << F.ModuleName << /*new*/0 << ModMap.getName();
4209
0
          return OutOfDate;
4210
0
        }
4211
0
      }
4212
0
    }
4213
4214
    // Check any additional module map files that are in the pcm, but not
4215
    // found in header search. Cases that match are already removed.
4216
0
    for (FileEntryRef ModMap : AdditionalStoredMaps) {
4217
0
      if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4218
0
        Diag(diag::err_module_different_modmap)
4219
0
          << F.ModuleName << /*not new*/1 << ModMap.getName();
4220
0
      return OutOfDate;
4221
0
    }
4222
0
  }
4223
4224
0
  if (Listener)
4225
0
    Listener->ReadModuleMapFile(F.ModuleMapPath);
4226
0
  return Success;
4227
0
}
4228
4229
/// Move the given method to the back of the global list of methods.
4230
0
static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
4231
  // Find the entry for this selector in the method pool.
4232
0
  Sema::GlobalMethodPool::iterator Known
4233
0
    = S.MethodPool.find(Method->getSelector());
4234
0
  if (Known == S.MethodPool.end())
4235
0
    return;
4236
4237
  // Retrieve the appropriate method list.
4238
0
  ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
4239
0
                                                    : Known->second.second;
4240
0
  bool Found = false;
4241
0
  for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
4242
0
    if (!Found) {
4243
0
      if (List->getMethod() == Method) {
4244
0
        Found = true;
4245
0
      } else {
4246
        // Keep searching.
4247
0
        continue;
4248
0
      }
4249
0
    }
4250
4251
0
    if (List->getNext())
4252
0
      List->setMethod(List->getNext()->getMethod());
4253
0
    else
4254
0
      List->setMethod(Method);
4255
0
  }
4256
0
}
4257
4258
0
void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
4259
0
  assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
4260
0
  for (Decl *D : Names) {
4261
0
    bool wasHidden = !D->isUnconditionallyVisible();
4262
0
    D->setVisibleDespiteOwningModule();
4263
4264
0
    if (wasHidden && SemaObj) {
4265
0
      if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
4266
0
        moveMethodToBackOfGlobalList(*SemaObj, Method);
4267
0
      }
4268
0
    }
4269
0
  }
4270
0
}
4271
4272
void ASTReader::makeModuleVisible(Module *Mod,
4273
                                  Module::NameVisibilityKind NameVisibility,
4274
0
                                  SourceLocation ImportLoc) {
4275
0
  llvm::SmallPtrSet<Module *, 4> Visited;
4276
0
  SmallVector<Module *, 4> Stack;
4277
0
  Stack.push_back(Mod);
4278
0
  while (!Stack.empty()) {
4279
0
    Mod = Stack.pop_back_val();
4280
4281
0
    if (NameVisibility <= Mod->NameVisibility) {
4282
      // This module already has this level of visibility (or greater), so
4283
      // there is nothing more to do.
4284
0
      continue;
4285
0
    }
4286
4287
0
    if (Mod->isUnimportable()) {
4288
      // Modules that aren't importable cannot be made visible.
4289
0
      continue;
4290
0
    }
4291
4292
    // Update the module's name visibility.
4293
0
    Mod->NameVisibility = NameVisibility;
4294
4295
    // If we've already deserialized any names from this module,
4296
    // mark them as visible.
4297
0
    HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
4298
0
    if (Hidden != HiddenNamesMap.end()) {
4299
0
      auto HiddenNames = std::move(*Hidden);
4300
0
      HiddenNamesMap.erase(Hidden);
4301
0
      makeNamesVisible(HiddenNames.second, HiddenNames.first);
4302
0
      assert(!HiddenNamesMap.contains(Mod) &&
4303
0
             "making names visible added hidden names");
4304
0
    }
4305
4306
    // Push any exported modules onto the stack to be marked as visible.
4307
0
    SmallVector<Module *, 16> Exports;
4308
0
    Mod->getExportedModules(Exports);
4309
0
    for (SmallVectorImpl<Module *>::iterator
4310
0
           I = Exports.begin(), E = Exports.end(); I != E; ++I) {
4311
0
      Module *Exported = *I;
4312
0
      if (Visited.insert(Exported).second)
4313
0
        Stack.push_back(Exported);
4314
0
    }
4315
0
  }
4316
0
}
4317
4318
/// We've merged the definition \p MergedDef into the existing definition
4319
/// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
4320
/// visible.
4321
void ASTReader::mergeDefinitionVisibility(NamedDecl *Def,
4322
0
                                          NamedDecl *MergedDef) {
4323
0
  if (!Def->isUnconditionallyVisible()) {
4324
    // If MergedDef is visible or becomes visible, make the definition visible.
4325
0
    if (MergedDef->isUnconditionallyVisible())
4326
0
      Def->setVisibleDespiteOwningModule();
4327
0
    else {
4328
0
      getContext().mergeDefinitionIntoModule(
4329
0
          Def, MergedDef->getImportedOwningModule(),
4330
0
          /*NotifyListeners*/ false);
4331
0
      PendingMergedDefinitionsToDeduplicate.insert(Def);
4332
0
    }
4333
0
  }
4334
0
}
4335
4336
0
bool ASTReader::loadGlobalIndex() {
4337
0
  if (GlobalIndex)
4338
0
    return false;
4339
4340
0
  if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
4341
0
      !PP.getLangOpts().Modules)
4342
0
    return true;
4343
4344
  // Try to load the global index.
4345
0
  TriedLoadingGlobalIndex = true;
4346
0
  StringRef ModuleCachePath
4347
0
    = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
4348
0
  std::pair<GlobalModuleIndex *, llvm::Error> Result =
4349
0
      GlobalModuleIndex::readIndex(ModuleCachePath);
4350
0
  if (llvm::Error Err = std::move(Result.second)) {
4351
0
    assert(!Result.first);
4352
0
    consumeError(std::move(Err)); // FIXME this drops errors on the floor.
4353
0
    return true;
4354
0
  }
4355
4356
0
  GlobalIndex.reset(Result.first);
4357
0
  ModuleMgr.setGlobalIndex(GlobalIndex.get());
4358
0
  return false;
4359
0
}
4360
4361
0
bool ASTReader::isGlobalIndexUnavailable() const {
4362
0
  return PP.getLangOpts().Modules && UseGlobalIndex &&
4363
0
         !hasGlobalIndex() && TriedLoadingGlobalIndex;
4364
0
}
4365
4366
0
static void updateModuleTimestamp(ModuleFile &MF) {
4367
  // Overwrite the timestamp file contents so that file's mtime changes.
4368
0
  std::string TimestampFilename = MF.getTimestampFilename();
4369
0
  std::error_code EC;
4370
0
  llvm::raw_fd_ostream OS(TimestampFilename, EC,
4371
0
                          llvm::sys::fs::OF_TextWithCRLF);
4372
0
  if (EC)
4373
0
    return;
4374
0
  OS << "Timestamp file\n";
4375
0
  OS.close();
4376
0
  OS.clear_error(); // Avoid triggering a fatal error.
4377
0
}
4378
4379
/// Given a cursor at the start of an AST file, scan ahead and drop the
4380
/// cursor into the start of the given block ID, returning false on success and
4381
/// true on failure.
4382
0
static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
4383
0
  while (true) {
4384
0
    Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
4385
0
    if (!MaybeEntry) {
4386
      // FIXME this drops errors on the floor.
4387
0
      consumeError(MaybeEntry.takeError());
4388
0
      return true;
4389
0
    }
4390
0
    llvm::BitstreamEntry Entry = MaybeEntry.get();
4391
4392
0
    switch (Entry.Kind) {
4393
0
    case llvm::BitstreamEntry::Error:
4394
0
    case llvm::BitstreamEntry::EndBlock:
4395
0
      return true;
4396
4397
0
    case llvm::BitstreamEntry::Record:
4398
      // Ignore top-level records.
4399
0
      if (Expected<unsigned> Skipped = Cursor.skipRecord(Entry.ID))
4400
0
        break;
4401
0
      else {
4402
        // FIXME this drops errors on the floor.
4403
0
        consumeError(Skipped.takeError());
4404
0
        return true;
4405
0
      }
4406
4407
0
    case llvm::BitstreamEntry::SubBlock:
4408
0
      if (Entry.ID == BlockID) {
4409
0
        if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) {
4410
          // FIXME this drops the error on the floor.
4411
0
          consumeError(std::move(Err));
4412
0
          return true;
4413
0
        }
4414
        // Found it!
4415
0
        return false;
4416
0
      }
4417
4418
0
      if (llvm::Error Err = Cursor.SkipBlock()) {
4419
        // FIXME this drops the error on the floor.
4420
0
        consumeError(std::move(Err));
4421
0
        return true;
4422
0
      }
4423
0
    }
4424
0
  }
4425
0
}
4426
4427
ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName, ModuleKind Type,
4428
                                            SourceLocation ImportLoc,
4429
                                            unsigned ClientLoadCapabilities,
4430
0
                                            ModuleFile **NewLoadedModuleFile) {
4431
0
  llvm::TimeTraceScope scope("ReadAST", FileName);
4432
4433
0
  llvm::SaveAndRestore SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
4434
0
  llvm::SaveAndRestore<std::optional<ModuleKind>> SetCurModuleKindRAII(
4435
0
      CurrentDeserializingModuleKind, Type);
4436
4437
  // Defer any pending actions until we get to the end of reading the AST file.
4438
0
  Deserializing AnASTFile(this);
4439
4440
  // Bump the generation number.
4441
0
  unsigned PreviousGeneration = 0;
4442
0
  if (ContextObj)
4443
0
    PreviousGeneration = incrementGeneration(*ContextObj);
4444
4445
0
  unsigned NumModules = ModuleMgr.size();
4446
0
  SmallVector<ImportedModule, 4> Loaded;
4447
0
  if (ASTReadResult ReadResult =
4448
0
          ReadASTCore(FileName, Type, ImportLoc,
4449
0
                      /*ImportedBy=*/nullptr, Loaded, 0, 0, ASTFileSignature(),
4450
0
                      ClientLoadCapabilities)) {
4451
0
    ModuleMgr.removeModules(ModuleMgr.begin() + NumModules);
4452
4453
    // If we find that any modules are unusable, the global index is going
4454
    // to be out-of-date. Just remove it.
4455
0
    GlobalIndex.reset();
4456
0
    ModuleMgr.setGlobalIndex(nullptr);
4457
0
    return ReadResult;
4458
0
  }
4459
4460
0
  if (NewLoadedModuleFile && !Loaded.empty())
4461
0
    *NewLoadedModuleFile = Loaded.back().Mod;
4462
4463
  // Here comes stuff that we only do once the entire chain is loaded. Do *not*
4464
  // remove modules from this point. Various fields are updated during reading
4465
  // the AST block and removing the modules would result in dangling pointers.
4466
  // They are generally only incidentally dereferenced, ie. a binary search
4467
  // runs over `GlobalSLocEntryMap`, which could cause an invalid module to
4468
  // be dereferenced but it wouldn't actually be used.
4469
4470
  // Load the AST blocks of all of the modules that we loaded. We can still
4471
  // hit errors parsing the ASTs at this point.
4472
0
  for (ImportedModule &M : Loaded) {
4473
0
    ModuleFile &F = *M.Mod;
4474
0
    llvm::TimeTraceScope Scope2("Read Loaded AST", F.ModuleName);
4475
4476
    // Read the AST block.
4477
0
    if (llvm::Error Err = ReadASTBlock(F, ClientLoadCapabilities)) {
4478
0
      Error(std::move(Err));
4479
0
      return Failure;
4480
0
    }
4481
4482
    // The AST block should always have a definition for the main module.
4483
0
    if (F.isModule() && !F.DidReadTopLevelSubmodule) {
4484
0
      Error(diag::err_module_file_missing_top_level_submodule, F.FileName);
4485
0
      return Failure;
4486
0
    }
4487
4488
    // Read the extension blocks.
4489
0
    while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
4490
0
      if (llvm::Error Err = ReadExtensionBlock(F)) {
4491
0
        Error(std::move(Err));
4492
0
        return Failure;
4493
0
      }
4494
0
    }
4495
4496
    // Once read, set the ModuleFile bit base offset and update the size in
4497
    // bits of all files we've seen.
4498
0
    F.GlobalBitOffset = TotalModulesSizeInBits;
4499
0
    TotalModulesSizeInBits += F.SizeInBits;
4500
0
    GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
4501
0
  }
4502
4503
  // Preload source locations and interesting indentifiers.
4504
0
  for (ImportedModule &M : Loaded) {
4505
0
    ModuleFile &F = *M.Mod;
4506
4507
    // Map the original source file ID into the ID space of the current
4508
    // compilation.
4509
0
    if (F.OriginalSourceFileID.isValid())
4510
0
      F.OriginalSourceFileID = TranslateFileID(F, F.OriginalSourceFileID);
4511
4512
0
    for (auto Offset : F.PreloadIdentifierOffsets) {
4513
0
      const unsigned char *Data = F.IdentifierTableData + Offset;
4514
4515
0
      ASTIdentifierLookupTrait Trait(*this, F);
4516
0
      auto KeyDataLen = Trait.ReadKeyDataLength(Data);
4517
0
      auto Key = Trait.ReadKey(Data, KeyDataLen.first);
4518
4519
0
      IdentifierInfo *II;
4520
0
      if (!PP.getLangOpts().CPlusPlus) {
4521
        // Identifiers present in both the module file and the importing
4522
        // instance are marked out-of-date so that they can be deserialized
4523
        // on next use via ASTReader::updateOutOfDateIdentifier().
4524
        // Identifiers present in the module file but not in the importing
4525
        // instance are ignored for now, preventing growth of the identifier
4526
        // table. They will be deserialized on first use via ASTReader::get().
4527
0
        auto It = PP.getIdentifierTable().find(Key);
4528
0
        if (It == PP.getIdentifierTable().end())
4529
0
          continue;
4530
0
        II = It->second;
4531
0
      } else {
4532
        // With C++ modules, not many identifiers are considered interesting.
4533
        // All identifiers in the module file can be placed into the identifier
4534
        // table of the importing instance and marked as out-of-date. This makes
4535
        // ASTReader::get() a no-op, and deserialization will take place on
4536
        // first/next use via ASTReader::updateOutOfDateIdentifier().
4537
0
        II = &PP.getIdentifierTable().getOwn(Key);
4538
0
      }
4539
4540
0
      II->setOutOfDate(true);
4541
4542
      // Mark this identifier as being from an AST file so that we can track
4543
      // whether we need to serialize it.
4544
0
      markIdentifierFromAST(*this, *II);
4545
4546
      // Associate the ID with the identifier so that the writer can reuse it.
4547
0
      auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
4548
0
      SetIdentifierInfo(ID, II);
4549
0
    }
4550
0
  }
4551
4552
  // Builtins and library builtins have already been initialized. Mark all
4553
  // identifiers as out-of-date, so that they are deserialized on first use.
4554
0
  if (Type == MK_PCH || Type == MK_Preamble || Type == MK_MainFile)
4555
0
    for (auto &Id : PP.getIdentifierTable())
4556
0
      Id.second->setOutOfDate(true);
4557
4558
  // Mark selectors as out of date.
4559
0
  for (const auto &Sel : SelectorGeneration)
4560
0
    SelectorOutOfDate[Sel.first] = true;
4561
4562
  // Setup the import locations and notify the module manager that we've
4563
  // committed to these module files.
4564
0
  for (ImportedModule &M : Loaded) {
4565
0
    ModuleFile &F = *M.Mod;
4566
4567
0
    ModuleMgr.moduleFileAccepted(&F);
4568
4569
    // Set the import location.
4570
0
    F.DirectImportLoc = ImportLoc;
4571
    // FIXME: We assume that locations from PCH / preamble do not need
4572
    // any translation.
4573
0
    if (!M.ImportedBy)
4574
0
      F.ImportLoc = M.ImportLoc;
4575
0
    else
4576
0
      F.ImportLoc = TranslateSourceLocation(*M.ImportedBy, M.ImportLoc);
4577
0
  }
4578
4579
  // Resolve any unresolved module exports.
4580
0
  for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
4581
0
    UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
4582
0
    SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
4583
0
    Module *ResolvedMod = getSubmodule(GlobalID);
4584
4585
0
    switch (Unresolved.Kind) {
4586
0
    case UnresolvedModuleRef::Conflict:
4587
0
      if (ResolvedMod) {
4588
0
        Module::Conflict Conflict;
4589
0
        Conflict.Other = ResolvedMod;
4590
0
        Conflict.Message = Unresolved.String.str();
4591
0
        Unresolved.Mod->Conflicts.push_back(Conflict);
4592
0
      }
4593
0
      continue;
4594
4595
0
    case UnresolvedModuleRef::Import:
4596
0
      if (ResolvedMod)
4597
0
        Unresolved.Mod->Imports.insert(ResolvedMod);
4598
0
      continue;
4599
4600
0
    case UnresolvedModuleRef::Affecting:
4601
0
      if (ResolvedMod)
4602
0
        Unresolved.Mod->AffectingClangModules.insert(ResolvedMod);
4603
0
      continue;
4604
4605
0
    case UnresolvedModuleRef::Export:
4606
0
      if (ResolvedMod || Unresolved.IsWildcard)
4607
0
        Unresolved.Mod->Exports.push_back(
4608
0
          Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
4609
0
      continue;
4610
0
    }
4611
0
  }
4612
0
  UnresolvedModuleRefs.clear();
4613
4614
  // FIXME: How do we load the 'use'd modules? They may not be submodules.
4615
  // Might be unnecessary as use declarations are only used to build the
4616
  // module itself.
4617
4618
0
  if (ContextObj)
4619
0
    InitializeContext();
4620
4621
0
  if (SemaObj)
4622
0
    UpdateSema();
4623
4624
0
  if (DeserializationListener)
4625
0
    DeserializationListener->ReaderInitialized(this);
4626
4627
0
  ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
4628
0
  if (PrimaryModule.OriginalSourceFileID.isValid()) {
4629
    // If this AST file is a precompiled preamble, then set the
4630
    // preamble file ID of the source manager to the file source file
4631
    // from which the preamble was built.
4632
0
    if (Type == MK_Preamble) {
4633
0
      SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
4634
0
    } else if (Type == MK_MainFile) {
4635
0
      SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
4636
0
    }
4637
0
  }
4638
4639
  // For any Objective-C class definitions we have already loaded, make sure
4640
  // that we load any additional categories.
4641
0
  if (ContextObj) {
4642
0
    for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
4643
0
      loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
4644
0
                         ObjCClassesLoaded[I],
4645
0
                         PreviousGeneration);
4646
0
    }
4647
0
  }
4648
4649
0
  HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts();
4650
0
  if (HSOpts.ModulesValidateOncePerBuildSession) {
4651
    // Now we are certain that the module and all modules it depends on are
4652
    // up-to-date. For implicitly-built module files, ensure the corresponding
4653
    // timestamp files are up-to-date in this build session.
4654
0
    for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
4655
0
      ImportedModule &M = Loaded[I];
4656
0
      if (M.Mod->Kind == MK_ImplicitModule &&
4657
0
          M.Mod->InputFilesValidationTimestamp < HSOpts.BuildSessionTimestamp)
4658
0
        updateModuleTimestamp(*M.Mod);
4659
0
    }
4660
0
  }
4661
4662
0
  return Success;
4663
0
}
4664
4665
static ASTFileSignature readASTFileSignature(StringRef PCH);
4666
4667
/// Whether \p Stream doesn't start with the AST/PCH file magic number 'CPCH'.
4668
0
static llvm::Error doesntStartWithASTFileMagic(BitstreamCursor &Stream) {
4669
  // FIXME checking magic headers is done in other places such as
4670
  // SerializedDiagnosticReader and GlobalModuleIndex, but error handling isn't
4671
  // always done the same. Unify it all with a helper.
4672
0
  if (!Stream.canSkipToPos(4))
4673
0
    return llvm::createStringError(std::errc::illegal_byte_sequence,
4674
0
                                   "file too small to contain AST file magic");
4675
0
  for (unsigned C : {'C', 'P', 'C', 'H'})
4676
0
    if (Expected<llvm::SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) {
4677
0
      if (Res.get() != C)
4678
0
        return llvm::createStringError(
4679
0
            std::errc::illegal_byte_sequence,
4680
0
            "file doesn't start with AST file magic");
4681
0
    } else
4682
0
      return Res.takeError();
4683
0
  return llvm::Error::success();
4684
0
}
4685
4686
0
static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
4687
0
  switch (Kind) {
4688
0
  case MK_PCH:
4689
0
    return 0; // PCH
4690
0
  case MK_ImplicitModule:
4691
0
  case MK_ExplicitModule:
4692
0
  case MK_PrebuiltModule:
4693
0
    return 1; // module
4694
0
  case MK_MainFile:
4695
0
  case MK_Preamble:
4696
0
    return 2; // main source file
4697
0
  }
4698
0
  llvm_unreachable("unknown module kind");
4699
0
}
4700
4701
ASTReader::ASTReadResult
4702
ASTReader::ReadASTCore(StringRef FileName,
4703
                       ModuleKind Type,
4704
                       SourceLocation ImportLoc,
4705
                       ModuleFile *ImportedBy,
4706
                       SmallVectorImpl<ImportedModule> &Loaded,
4707
                       off_t ExpectedSize, time_t ExpectedModTime,
4708
                       ASTFileSignature ExpectedSignature,
4709
0
                       unsigned ClientLoadCapabilities) {
4710
0
  ModuleFile *M;
4711
0
  std::string ErrorStr;
4712
0
  ModuleManager::AddModuleResult AddResult
4713
0
    = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
4714
0
                          getGeneration(), ExpectedSize, ExpectedModTime,
4715
0
                          ExpectedSignature, readASTFileSignature,
4716
0
                          M, ErrorStr);
4717
4718
0
  switch (AddResult) {
4719
0
  case ModuleManager::AlreadyLoaded:
4720
0
    Diag(diag::remark_module_import)
4721
0
        << M->ModuleName << M->FileName << (ImportedBy ? true : false)
4722
0
        << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
4723
0
    return Success;
4724
4725
0
  case ModuleManager::NewlyLoaded:
4726
    // Load module file below.
4727
0
    break;
4728
4729
0
  case ModuleManager::Missing:
4730
    // The module file was missing; if the client can handle that, return
4731
    // it.
4732
0
    if (ClientLoadCapabilities & ARR_Missing)
4733
0
      return Missing;
4734
4735
    // Otherwise, return an error.
4736
0
    Diag(diag::err_ast_file_not_found)
4737
0
        << moduleKindForDiagnostic(Type) << FileName << !ErrorStr.empty()
4738
0
        << ErrorStr;
4739
0
    return Failure;
4740
4741
0
  case ModuleManager::OutOfDate:
4742
    // We couldn't load the module file because it is out-of-date. If the
4743
    // client can handle out-of-date, return it.
4744
0
    if (ClientLoadCapabilities & ARR_OutOfDate)
4745
0
      return OutOfDate;
4746
4747
    // Otherwise, return an error.
4748
0
    Diag(diag::err_ast_file_out_of_date)
4749
0
        << moduleKindForDiagnostic(Type) << FileName << !ErrorStr.empty()
4750
0
        << ErrorStr;
4751
0
    return Failure;
4752
0
  }
4753
4754
0
  assert(M && "Missing module file");
4755
4756
0
  bool ShouldFinalizePCM = false;
4757
0
  auto FinalizeOrDropPCM = llvm::make_scope_exit([&]() {
4758
0
    auto &MC = getModuleManager().getModuleCache();
4759
0
    if (ShouldFinalizePCM)
4760
0
      MC.finalizePCM(FileName);
4761
0
    else
4762
0
      MC.tryToDropPCM(FileName);
4763
0
  });
4764
0
  ModuleFile &F = *M;
4765
0
  BitstreamCursor &Stream = F.Stream;
4766
0
  Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
4767
0
  F.SizeInBits = F.Buffer->getBufferSize() * 8;
4768
4769
  // Sniff for the signature.
4770
0
  if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4771
0
    Diag(diag::err_ast_file_invalid)
4772
0
        << moduleKindForDiagnostic(Type) << FileName << std::move(Err);
4773
0
    return Failure;
4774
0
  }
4775
4776
  // This is used for compatibility with older PCH formats.
4777
0
  bool HaveReadControlBlock = false;
4778
0
  while (true) {
4779
0
    Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4780
0
    if (!MaybeEntry) {
4781
0
      Error(MaybeEntry.takeError());
4782
0
      return Failure;
4783
0
    }
4784
0
    llvm::BitstreamEntry Entry = MaybeEntry.get();
4785
4786
0
    switch (Entry.Kind) {
4787
0
    case llvm::BitstreamEntry::Error:
4788
0
    case llvm::BitstreamEntry::Record:
4789
0
    case llvm::BitstreamEntry::EndBlock:
4790
0
      Error("invalid record at top-level of AST file");
4791
0
      return Failure;
4792
4793
0
    case llvm::BitstreamEntry::SubBlock:
4794
0
      break;
4795
0
    }
4796
4797
0
    switch (Entry.ID) {
4798
0
    case CONTROL_BLOCK_ID:
4799
0
      HaveReadControlBlock = true;
4800
0
      switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
4801
0
      case Success:
4802
        // Check that we didn't try to load a non-module AST file as a module.
4803
        //
4804
        // FIXME: Should we also perform the converse check? Loading a module as
4805
        // a PCH file sort of works, but it's a bit wonky.
4806
0
        if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule ||
4807
0
             Type == MK_PrebuiltModule) &&
4808
0
            F.ModuleName.empty()) {
4809
0
          auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
4810
0
          if (Result != OutOfDate ||
4811
0
              (ClientLoadCapabilities & ARR_OutOfDate) == 0)
4812
0
            Diag(diag::err_module_file_not_module) << FileName;
4813
0
          return Result;
4814
0
        }
4815
0
        break;
4816
4817
0
      case Failure: return Failure;
4818
0
      case Missing: return Missing;
4819
0
      case OutOfDate: return OutOfDate;
4820
0
      case VersionMismatch: return VersionMismatch;
4821
0
      case ConfigurationMismatch: return ConfigurationMismatch;
4822
0
      case HadErrors: return HadErrors;
4823
0
      }
4824
0
      break;
4825
4826
0
    case AST_BLOCK_ID:
4827
0
      if (!HaveReadControlBlock) {
4828
0
        if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
4829
0
          Diag(diag::err_pch_version_too_old);
4830
0
        return VersionMismatch;
4831
0
      }
4832
4833
      // Record that we've loaded this module.
4834
0
      Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
4835
0
      ShouldFinalizePCM = true;
4836
0
      return Success;
4837
4838
0
    default:
4839
0
      if (llvm::Error Err = Stream.SkipBlock()) {
4840
0
        Error(std::move(Err));
4841
0
        return Failure;
4842
0
      }
4843
0
      break;
4844
0
    }
4845
0
  }
4846
4847
0
  llvm_unreachable("unexpected break; expected return");
4848
0
}
4849
4850
ASTReader::ASTReadResult
4851
ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
4852
0
                                    unsigned ClientLoadCapabilities) {
4853
0
  const HeaderSearchOptions &HSOpts =
4854
0
      PP.getHeaderSearchInfo().getHeaderSearchOpts();
4855
0
  bool AllowCompatibleConfigurationMismatch =
4856
0
      F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
4857
0
  bool DisableValidation = shouldDisableValidationForFile(F);
4858
4859
0
  ASTReadResult Result = readUnhashedControlBlockImpl(
4860
0
      &F, F.Data, ClientLoadCapabilities, AllowCompatibleConfigurationMismatch,
4861
0
      Listener.get(),
4862
0
      WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions);
4863
4864
  // If F was directly imported by another module, it's implicitly validated by
4865
  // the importing module.
4866
0
  if (DisableValidation || WasImportedBy ||
4867
0
      (AllowConfigurationMismatch && Result == ConfigurationMismatch))
4868
0
    return Success;
4869
4870
0
  if (Result == Failure) {
4871
0
    Error("malformed block record in AST file");
4872
0
    return Failure;
4873
0
  }
4874
4875
0
  if (Result == OutOfDate && F.Kind == MK_ImplicitModule) {
4876
    // If this module has already been finalized in the ModuleCache, we're stuck
4877
    // with it; we can only load a single version of each module.
4878
    //
4879
    // This can happen when a module is imported in two contexts: in one, as a
4880
    // user module; in another, as a system module (due to an import from
4881
    // another module marked with the [system] flag).  It usually indicates a
4882
    // bug in the module map: this module should also be marked with [system].
4883
    //
4884
    // If -Wno-system-headers (the default), and the first import is as a
4885
    // system module, then validation will fail during the as-user import,
4886
    // since -Werror flags won't have been validated.  However, it's reasonable
4887
    // to treat this consistently as a system module.
4888
    //
4889
    // If -Wsystem-headers, the PCM on disk was built with
4890
    // -Wno-system-headers, and the first import is as a user module, then
4891
    // validation will fail during the as-system import since the PCM on disk
4892
    // doesn't guarantee that -Werror was respected.  However, the -Werror
4893
    // flags were checked during the initial as-user import.
4894
0
    if (getModuleManager().getModuleCache().isPCMFinal(F.FileName)) {
4895
0
      Diag(diag::warn_module_system_bit_conflict) << F.FileName;
4896
0
      return Success;
4897
0
    }
4898
0
  }
4899
4900
0
  return Result;
4901
0
}
4902
4903
ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl(
4904
    ModuleFile *F, llvm::StringRef StreamData, unsigned ClientLoadCapabilities,
4905
    bool AllowCompatibleConfigurationMismatch, ASTReaderListener *Listener,
4906
0
    bool ValidateDiagnosticOptions) {
4907
  // Initialize a stream.
4908
0
  BitstreamCursor Stream(StreamData);
4909
4910
  // Sniff for the signature.
4911
0
  if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4912
    // FIXME this drops the error on the floor.
4913
0
    consumeError(std::move(Err));
4914
0
    return Failure;
4915
0
  }
4916
4917
  // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4918
0
  if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
4919
0
    return Failure;
4920
4921
  // Read all of the records in the options block.
4922
0
  RecordData Record;
4923
0
  ASTReadResult Result = Success;
4924
0
  while (true) {
4925
0
    Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4926
0
    if (!MaybeEntry) {
4927
      // FIXME this drops the error on the floor.
4928
0
      consumeError(MaybeEntry.takeError());
4929
0
      return Failure;
4930
0
    }
4931
0
    llvm::BitstreamEntry Entry = MaybeEntry.get();
4932
4933
0
    switch (Entry.Kind) {
4934
0
    case llvm::BitstreamEntry::Error:
4935
0
    case llvm::BitstreamEntry::SubBlock:
4936
0
      return Failure;
4937
4938
0
    case llvm::BitstreamEntry::EndBlock:
4939
0
      return Result;
4940
4941
0
    case llvm::BitstreamEntry::Record:
4942
      // The interesting case.
4943
0
      break;
4944
0
    }
4945
4946
    // Read and process a record.
4947
0
    Record.clear();
4948
0
    StringRef Blob;
4949
0
    Expected<unsigned> MaybeRecordType =
4950
0
        Stream.readRecord(Entry.ID, Record, &Blob);
4951
0
    if (!MaybeRecordType) {
4952
      // FIXME this drops the error.
4953
0
      return Failure;
4954
0
    }
4955
0
    switch ((UnhashedControlBlockRecordTypes)MaybeRecordType.get()) {
4956
0
    case SIGNATURE:
4957
0
      if (F) {
4958
0
        F->Signature = ASTFileSignature::create(Blob.begin(), Blob.end());
4959
0
        assert(F->Signature != ASTFileSignature::createDummy() &&
4960
0
               "Dummy AST file signature not backpatched in ASTWriter.");
4961
0
      }
4962
0
      break;
4963
0
    case AST_BLOCK_HASH:
4964
0
      if (F) {
4965
0
        F->ASTBlockHash = ASTFileSignature::create(Blob.begin(), Blob.end());
4966
0
        assert(F->ASTBlockHash != ASTFileSignature::createDummy() &&
4967
0
               "Dummy AST block hash not backpatched in ASTWriter.");
4968
0
      }
4969
0
      break;
4970
0
    case DIAGNOSTIC_OPTIONS: {
4971
0
      bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
4972
0
      if (Listener && ValidateDiagnosticOptions &&
4973
0
          !AllowCompatibleConfigurationMismatch &&
4974
0
          ParseDiagnosticOptions(Record, Complain, *Listener))
4975
0
        Result = OutOfDate; // Don't return early.  Read the signature.
4976
0
      break;
4977
0
    }
4978
0
    case HEADER_SEARCH_PATHS: {
4979
0
      bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
4980
0
      if (!AllowCompatibleConfigurationMismatch &&
4981
0
          ParseHeaderSearchPaths(Record, Complain, *Listener))
4982
0
        Result = ConfigurationMismatch;
4983
0
      break;
4984
0
    }
4985
0
    case DIAG_PRAGMA_MAPPINGS:
4986
0
      if (!F)
4987
0
        break;
4988
0
      if (F->PragmaDiagMappings.empty())
4989
0
        F->PragmaDiagMappings.swap(Record);
4990
0
      else
4991
0
        F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(),
4992
0
                                     Record.begin(), Record.end());
4993
0
      break;
4994
0
    case HEADER_SEARCH_ENTRY_USAGE:
4995
0
      if (!F)
4996
0
        break;
4997
0
      unsigned Count = Record[0];
4998
0
      const char *Byte = Blob.data();
4999
0
      F->SearchPathUsage = llvm::BitVector(Count, false);
5000
0
      for (unsigned I = 0; I < Count; ++Byte)
5001
0
        for (unsigned Bit = 0; Bit < 8 && I < Count; ++Bit, ++I)
5002
0
          if (*Byte & (1 << Bit))
5003
0
            F->SearchPathUsage[I] = true;
5004
0
      break;
5005
0
    }
5006
0
  }
5007
0
}
5008
5009
/// Parse a record and blob containing module file extension metadata.
5010
static bool parseModuleFileExtensionMetadata(
5011
              const SmallVectorImpl<uint64_t> &Record,
5012
              StringRef Blob,
5013
0
              ModuleFileExtensionMetadata &Metadata) {
5014
0
  if (Record.size() < 4) return true;
5015
5016
0
  Metadata.MajorVersion = Record[0];
5017
0
  Metadata.MinorVersion = Record[1];
5018
5019
0
  unsigned BlockNameLen = Record[2];
5020
0
  unsigned UserInfoLen = Record[3];
5021
5022
0
  if (BlockNameLen + UserInfoLen > Blob.size()) return true;
5023
5024
0
  Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
5025
0
  Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
5026
0
                                  Blob.data() + BlockNameLen + UserInfoLen);
5027
0
  return false;
5028
0
}
5029
5030
0
llvm::Error ASTReader::ReadExtensionBlock(ModuleFile &F) {
5031
0
  BitstreamCursor &Stream = F.Stream;
5032
5033
0
  RecordData Record;
5034
0
  while (true) {
5035
0
    Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5036
0
    if (!MaybeEntry)
5037
0
      return MaybeEntry.takeError();
5038
0
    llvm::BitstreamEntry Entry = MaybeEntry.get();
5039
5040
0
    switch (Entry.Kind) {
5041
0
    case llvm::BitstreamEntry::SubBlock:
5042
0
      if (llvm::Error Err = Stream.SkipBlock())
5043
0
        return Err;
5044
0
      continue;
5045
0
    case llvm::BitstreamEntry::EndBlock:
5046
0
      return llvm::Error::success();
5047
0
    case llvm::BitstreamEntry::Error:
5048
0
      return llvm::createStringError(std::errc::illegal_byte_sequence,
5049
0
                                     "malformed block record in AST file");
5050
0
    case llvm::BitstreamEntry::Record:
5051
0
      break;
5052
0
    }
5053
5054
0
    Record.clear();
5055
0
    StringRef Blob;
5056
0
    Expected<unsigned> MaybeRecCode =
5057
0
        Stream.readRecord(Entry.ID, Record, &Blob);
5058
0
    if (!MaybeRecCode)
5059
0
      return MaybeRecCode.takeError();
5060
0
    switch (MaybeRecCode.get()) {
5061
0
    case EXTENSION_METADATA: {
5062
0
      ModuleFileExtensionMetadata Metadata;
5063
0
      if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
5064
0
        return llvm::createStringError(
5065
0
            std::errc::illegal_byte_sequence,
5066
0
            "malformed EXTENSION_METADATA in AST file");
5067
5068
      // Find a module file extension with this block name.
5069
0
      auto Known = ModuleFileExtensions.find(Metadata.BlockName);
5070
0
      if (Known == ModuleFileExtensions.end()) break;
5071
5072
      // Form a reader.
5073
0
      if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
5074
0
                                                             F, Stream)) {
5075
0
        F.ExtensionReaders.push_back(std::move(Reader));
5076
0
      }
5077
5078
0
      break;
5079
0
    }
5080
0
    }
5081
0
  }
5082
5083
0
  return llvm::Error::success();
5084
0
}
5085
5086
0
void ASTReader::InitializeContext() {
5087
0
  assert(ContextObj && "no context to initialize");
5088
0
  ASTContext &Context = *ContextObj;
5089
5090
  // If there's a listener, notify them that we "read" the translation unit.
5091
0
  if (DeserializationListener)
5092
0
    DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
5093
0
                                      Context.getTranslationUnitDecl());
5094
5095
  // FIXME: Find a better way to deal with collisions between these
5096
  // built-in types. Right now, we just ignore the problem.
5097
5098
  // Load the special types.
5099
0
  if (SpecialTypes.size() >= NumSpecialTypeIDs) {
5100
0
    if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
5101
0
      if (!Context.CFConstantStringTypeDecl)
5102
0
        Context.setCFConstantStringType(GetType(String));
5103
0
    }
5104
5105
0
    if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
5106
0
      QualType FileType = GetType(File);
5107
0
      if (FileType.isNull()) {
5108
0
        Error("FILE type is NULL");
5109
0
        return;
5110
0
      }
5111
5112
0
      if (!Context.FILEDecl) {
5113
0
        if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
5114
0
          Context.setFILEDecl(Typedef->getDecl());
5115
0
        else {
5116
0
          const TagType *Tag = FileType->getAs<TagType>();
5117
0
          if (!Tag) {
5118
0
            Error("Invalid FILE type in AST file");
5119
0
            return;
5120
0
          }
5121
0
          Context.setFILEDecl(Tag->getDecl());
5122
0
        }
5123
0
      }
5124
0
    }
5125
5126
0
    if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
5127
0
      QualType Jmp_bufType = GetType(Jmp_buf);
5128
0
      if (Jmp_bufType.isNull()) {
5129
0
        Error("jmp_buf type is NULL");
5130
0
        return;
5131
0
      }
5132
5133
0
      if (!Context.jmp_bufDecl) {
5134
0
        if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
5135
0
          Context.setjmp_bufDecl(Typedef->getDecl());
5136
0
        else {
5137
0
          const TagType *Tag = Jmp_bufType->getAs<TagType>();
5138
0
          if (!Tag) {
5139
0
            Error("Invalid jmp_buf type in AST file");
5140
0
            return;
5141
0
          }
5142
0
          Context.setjmp_bufDecl(Tag->getDecl());
5143
0
        }
5144
0
      }
5145
0
    }
5146
5147
0
    if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
5148
0
      QualType Sigjmp_bufType = GetType(Sigjmp_buf);
5149
0
      if (Sigjmp_bufType.isNull()) {
5150
0
        Error("sigjmp_buf type is NULL");
5151
0
        return;
5152
0
      }
5153
5154
0
      if (!Context.sigjmp_bufDecl) {
5155
0
        if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
5156
0
          Context.setsigjmp_bufDecl(Typedef->getDecl());
5157
0
        else {
5158
0
          const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
5159
0
          assert(Tag && "Invalid sigjmp_buf type in AST file");
5160
0
          Context.setsigjmp_bufDecl(Tag->getDecl());
5161
0
        }
5162
0
      }
5163
0
    }
5164
5165
0
    if (unsigned ObjCIdRedef
5166
0
          = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
5167
0
      if (Context.ObjCIdRedefinitionType.isNull())
5168
0
        Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
5169
0
    }
5170
5171
0
    if (unsigned ObjCClassRedef
5172
0
          = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
5173
0
      if (Context.ObjCClassRedefinitionType.isNull())
5174
0
        Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
5175
0
    }
5176
5177
0
    if (unsigned ObjCSelRedef
5178
0
          = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
5179
0
      if (Context.ObjCSelRedefinitionType.isNull())
5180
0
        Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
5181
0
    }
5182
5183
0
    if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
5184
0
      QualType Ucontext_tType = GetType(Ucontext_t);
5185
0
      if (Ucontext_tType.isNull()) {
5186
0
        Error("ucontext_t type is NULL");
5187
0
        return;
5188
0
      }
5189
5190
0
      if (!Context.ucontext_tDecl) {
5191
0
        if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
5192
0
          Context.setucontext_tDecl(Typedef->getDecl());
5193
0
        else {
5194
0
          const TagType *Tag = Ucontext_tType->getAs<TagType>();
5195
0
          assert(Tag && "Invalid ucontext_t type in AST file");
5196
0
          Context.setucontext_tDecl(Tag->getDecl());
5197
0
        }
5198
0
      }
5199
0
    }
5200
0
  }
5201
5202
0
  ReadPragmaDiagnosticMappings(Context.getDiagnostics());
5203
5204
  // If there were any CUDA special declarations, deserialize them.
5205
0
  if (!CUDASpecialDeclRefs.empty()) {
5206
0
    assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
5207
0
    Context.setcudaConfigureCallDecl(
5208
0
                           cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
5209
0
  }
5210
5211
  // Re-export any modules that were imported by a non-module AST file.
5212
  // FIXME: This does not make macro-only imports visible again.
5213
0
  for (auto &Import : PendingImportedModules) {
5214
0
    if (Module *Imported = getSubmodule(Import.ID)) {
5215
0
      makeModuleVisible(Imported, Module::AllVisible,
5216
0
                        /*ImportLoc=*/Import.ImportLoc);
5217
0
      if (Import.ImportLoc.isValid())
5218
0
        PP.makeModuleVisible(Imported, Import.ImportLoc);
5219
      // This updates visibility for Preprocessor only. For Sema, which can be
5220
      // nullptr here, we do the same later, in UpdateSema().
5221
0
    }
5222
0
  }
5223
5224
  // Hand off these modules to Sema.
5225
0
  PendingImportedModulesSema.append(PendingImportedModules);
5226
0
  PendingImportedModules.clear();
5227
0
}
5228
5229
0
void ASTReader::finalizeForWriting() {
5230
  // Nothing to do for now.
5231
0
}
5232
5233
/// Reads and return the signature record from \p PCH's control block, or
5234
/// else returns 0.
5235
0
static ASTFileSignature readASTFileSignature(StringRef PCH) {
5236
0
  BitstreamCursor Stream(PCH);
5237
0
  if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5238
    // FIXME this drops the error on the floor.
5239
0
    consumeError(std::move(Err));
5240
0
    return ASTFileSignature();
5241
0
  }
5242
5243
  // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
5244
0
  if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
5245
0
    return ASTFileSignature();
5246
5247
  // Scan for SIGNATURE inside the diagnostic options block.
5248
0
  ASTReader::RecordData Record;
5249
0
  while (true) {
5250
0
    Expected<llvm::BitstreamEntry> MaybeEntry =
5251
0
        Stream.advanceSkippingSubblocks();
5252
0
    if (!MaybeEntry) {
5253
      // FIXME this drops the error on the floor.
5254
0
      consumeError(MaybeEntry.takeError());
5255
0
      return ASTFileSignature();
5256
0
    }
5257
0
    llvm::BitstreamEntry Entry = MaybeEntry.get();
5258
5259
0
    if (Entry.Kind != llvm::BitstreamEntry::Record)
5260
0
      return ASTFileSignature();
5261
5262
0
    Record.clear();
5263
0
    StringRef Blob;
5264
0
    Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
5265
0
    if (!MaybeRecord) {
5266
      // FIXME this drops the error on the floor.
5267
0
      consumeError(MaybeRecord.takeError());
5268
0
      return ASTFileSignature();
5269
0
    }
5270
0
    if (SIGNATURE == MaybeRecord.get()) {
5271
0
      auto Signature = ASTFileSignature::create(Blob.begin(), Blob.end());
5272
0
      assert(Signature != ASTFileSignature::createDummy() &&
5273
0
             "Dummy AST file signature not backpatched in ASTWriter.");
5274
0
      return Signature;
5275
0
    }
5276
0
  }
5277
0
}
5278
5279
/// Retrieve the name of the original source file name
5280
/// directly from the AST file, without actually loading the AST
5281
/// file.
5282
std::string ASTReader::getOriginalSourceFile(
5283
    const std::string &ASTFileName, FileManager &FileMgr,
5284
0
    const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
5285
  // Open the AST file.
5286
0
  auto Buffer = FileMgr.getBufferForFile(ASTFileName, /*IsVolatile=*/false,
5287
0
                                         /*RequiresNullTerminator=*/false);
5288
0
  if (!Buffer) {
5289
0
    Diags.Report(diag::err_fe_unable_to_read_pch_file)
5290
0
        << ASTFileName << Buffer.getError().message();
5291
0
    return std::string();
5292
0
  }
5293
5294
  // Initialize the stream
5295
0
  BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
5296
5297
  // Sniff for the signature.
5298
0
  if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5299
0
    Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName << std::move(Err);
5300
0
    return std::string();
5301
0
  }
5302
5303
  // Scan for the CONTROL_BLOCK_ID block.
5304
0
  if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
5305
0
    Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
5306
0
    return std::string();
5307
0
  }
5308
5309
  // Scan for ORIGINAL_FILE inside the control block.
5310
0
  RecordData Record;
5311
0
  while (true) {
5312
0
    Expected<llvm::BitstreamEntry> MaybeEntry =
5313
0
        Stream.advanceSkippingSubblocks();
5314
0
    if (!MaybeEntry) {
5315
      // FIXME this drops errors on the floor.
5316
0
      consumeError(MaybeEntry.takeError());
5317
0
      return std::string();
5318
0
    }
5319
0
    llvm::BitstreamEntry Entry = MaybeEntry.get();
5320
5321
0
    if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
5322
0
      return std::string();
5323
5324
0
    if (Entry.Kind != llvm::BitstreamEntry::Record) {
5325
0
      Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
5326
0
      return std::string();
5327
0
    }
5328
5329
0
    Record.clear();
5330
0
    StringRef Blob;
5331
0
    Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
5332
0
    if (!MaybeRecord) {
5333
      // FIXME this drops the errors on the floor.
5334
0
      consumeError(MaybeRecord.takeError());
5335
0
      return std::string();
5336
0
    }
5337
0
    if (ORIGINAL_FILE == MaybeRecord.get())
5338
0
      return Blob.str();
5339
0
  }
5340
0
}
5341
5342
namespace {
5343
5344
  class SimplePCHValidator : public ASTReaderListener {
5345
    const LangOptions &ExistingLangOpts;
5346
    const TargetOptions &ExistingTargetOpts;
5347
    const PreprocessorOptions &ExistingPPOpts;
5348
    std::string ExistingModuleCachePath;
5349
    FileManager &FileMgr;
5350
    bool StrictOptionMatches;
5351
5352
  public:
5353
    SimplePCHValidator(const LangOptions &ExistingLangOpts,
5354
                       const TargetOptions &ExistingTargetOpts,
5355
                       const PreprocessorOptions &ExistingPPOpts,
5356
                       StringRef ExistingModuleCachePath, FileManager &FileMgr,
5357
                       bool StrictOptionMatches)
5358
        : ExistingLangOpts(ExistingLangOpts),
5359
          ExistingTargetOpts(ExistingTargetOpts),
5360
          ExistingPPOpts(ExistingPPOpts),
5361
          ExistingModuleCachePath(ExistingModuleCachePath), FileMgr(FileMgr),
5362
0
          StrictOptionMatches(StrictOptionMatches) {}
5363
5364
    bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
5365
0
                             bool AllowCompatibleDifferences) override {
5366
0
      return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
5367
0
                                  AllowCompatibleDifferences);
5368
0
    }
5369
5370
    bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
5371
0
                           bool AllowCompatibleDifferences) override {
5372
0
      return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
5373
0
                                AllowCompatibleDifferences);
5374
0
    }
5375
5376
    bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
5377
                                 StringRef SpecificModuleCachePath,
5378
0
                                 bool Complain) override {
5379
0
      return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
5380
0
                                      ExistingModuleCachePath, nullptr,
5381
0
                                      ExistingLangOpts, ExistingPPOpts);
5382
0
    }
5383
5384
    bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
5385
                                 bool ReadMacros, bool Complain,
5386
0
                                 std::string &SuggestedPredefines) override {
5387
0
      return checkPreprocessorOptions(
5388
0
          PPOpts, ExistingPPOpts, ReadMacros, /*Diags=*/nullptr, FileMgr,
5389
0
          SuggestedPredefines, ExistingLangOpts,
5390
0
          StrictOptionMatches ? OptionValidateStrictMatches
5391
0
                              : OptionValidateContradictions);
5392
0
    }
5393
  };
5394
5395
} // namespace
5396
5397
bool ASTReader::readASTFileControlBlock(
5398
    StringRef Filename, FileManager &FileMgr,
5399
    const InMemoryModuleCache &ModuleCache,
5400
    const PCHContainerReader &PCHContainerRdr, bool FindModuleFileExtensions,
5401
0
    ASTReaderListener &Listener, bool ValidateDiagnosticOptions) {
5402
  // Open the AST file.
5403
0
  std::unique_ptr<llvm::MemoryBuffer> OwnedBuffer;
5404
0
  llvm::MemoryBuffer *Buffer = ModuleCache.lookupPCM(Filename);
5405
0
  if (!Buffer) {
5406
    // FIXME: We should add the pcm to the InMemoryModuleCache if it could be
5407
    // read again later, but we do not have the context here to determine if it
5408
    // is safe to change the result of InMemoryModuleCache::getPCMState().
5409
5410
    // FIXME: This allows use of the VFS; we do not allow use of the
5411
    // VFS when actually loading a module.
5412
0
    auto BufferOrErr = FileMgr.getBufferForFile(Filename);
5413
0
    if (!BufferOrErr)
5414
0
      return true;
5415
0
    OwnedBuffer = std::move(*BufferOrErr);
5416
0
    Buffer = OwnedBuffer.get();
5417
0
  }
5418
5419
  // Initialize the stream
5420
0
  StringRef Bytes = PCHContainerRdr.ExtractPCH(*Buffer);
5421
0
  BitstreamCursor Stream(Bytes);
5422
5423
  // Sniff for the signature.
5424
0
  if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5425
0
    consumeError(std::move(Err)); // FIXME this drops errors on the floor.
5426
0
    return true;
5427
0
  }
5428
5429
  // Scan for the CONTROL_BLOCK_ID block.
5430
0
  if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
5431
0
    return true;
5432
5433
0
  bool NeedsInputFiles = Listener.needsInputFileVisitation();
5434
0
  bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
5435
0
  bool NeedsImports = Listener.needsImportVisitation();
5436
0
  BitstreamCursor InputFilesCursor;
5437
0
  uint64_t InputFilesOffsetBase = 0;
5438
5439
0
  RecordData Record;
5440
0
  std::string ModuleDir;
5441
0
  bool DoneWithControlBlock = false;
5442
0
  while (!DoneWithControlBlock) {
5443
0
    Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5444
0
    if (!MaybeEntry) {
5445
      // FIXME this drops the error on the floor.
5446
0
      consumeError(MaybeEntry.takeError());
5447
0
      return true;
5448
0
    }
5449
0
    llvm::BitstreamEntry Entry = MaybeEntry.get();
5450
5451
0
    switch (Entry.Kind) {
5452
0
    case llvm::BitstreamEntry::SubBlock: {
5453
0
      switch (Entry.ID) {
5454
0
      case OPTIONS_BLOCK_ID: {
5455
0
        std::string IgnoredSuggestedPredefines;
5456
0
        if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
5457
0
                             /*AllowCompatibleConfigurationMismatch*/ false,
5458
0
                             Listener, IgnoredSuggestedPredefines) != Success)
5459
0
          return true;
5460
0
        break;
5461
0
      }
5462
5463
0
      case INPUT_FILES_BLOCK_ID:
5464
0
        InputFilesCursor = Stream;
5465
0
        if (llvm::Error Err = Stream.SkipBlock()) {
5466
          // FIXME this drops the error on the floor.
5467
0
          consumeError(std::move(Err));
5468
0
          return true;
5469
0
        }
5470
0
        if (NeedsInputFiles &&
5471
0
            ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID))
5472
0
          return true;
5473
0
        InputFilesOffsetBase = InputFilesCursor.GetCurrentBitNo();
5474
0
        break;
5475
5476
0
      default:
5477
0
        if (llvm::Error Err = Stream.SkipBlock()) {
5478
          // FIXME this drops the error on the floor.
5479
0
          consumeError(std::move(Err));
5480
0
          return true;
5481
0
        }
5482
0
        break;
5483
0
      }
5484
5485
0
      continue;
5486
0
    }
5487
5488
0
    case llvm::BitstreamEntry::EndBlock:
5489
0
      DoneWithControlBlock = true;
5490
0
      break;
5491
5492
0
    case llvm::BitstreamEntry::Error:
5493
0
      return true;
5494
5495
0
    case llvm::BitstreamEntry::Record:
5496
0
      break;
5497
0
    }
5498
5499
0
    if (DoneWithControlBlock) break;
5500
5501
0
    Record.clear();
5502
0
    StringRef Blob;
5503
0
    Expected<unsigned> MaybeRecCode =
5504
0
        Stream.readRecord(Entry.ID, Record, &Blob);
5505
0
    if (!MaybeRecCode) {
5506
      // FIXME this drops the error.
5507
0
      return Failure;
5508
0
    }
5509
0
    switch ((ControlRecordTypes)MaybeRecCode.get()) {
5510
0
    case METADATA:
5511
0
      if (Record[0] != VERSION_MAJOR)
5512
0
        return true;
5513
0
      if (Listener.ReadFullVersionInformation(Blob))
5514
0
        return true;
5515
0
      break;
5516
0
    case MODULE_NAME:
5517
0
      Listener.ReadModuleName(Blob);
5518
0
      break;
5519
0
    case MODULE_DIRECTORY:
5520
0
      ModuleDir = std::string(Blob);
5521
0
      break;
5522
0
    case MODULE_MAP_FILE: {
5523
0
      unsigned Idx = 0;
5524
0
      auto Path = ReadString(Record, Idx);
5525
0
      ResolveImportedPath(Path, ModuleDir);
5526
0
      Listener.ReadModuleMapFile(Path);
5527
0
      break;
5528
0
    }
5529
0
    case INPUT_FILE_OFFSETS: {
5530
0
      if (!NeedsInputFiles)
5531
0
        break;
5532
5533
0
      unsigned NumInputFiles = Record[0];
5534
0
      unsigned NumUserFiles = Record[1];
5535
0
      const llvm::support::unaligned_uint64_t *InputFileOffs =
5536
0
          (const llvm::support::unaligned_uint64_t *)Blob.data();
5537
0
      for (unsigned I = 0; I != NumInputFiles; ++I) {
5538
        // Go find this input file.
5539
0
        bool isSystemFile = I >= NumUserFiles;
5540
5541
0
        if (isSystemFile && !NeedsSystemInputFiles)
5542
0
          break; // the rest are system input files
5543
5544
0
        BitstreamCursor &Cursor = InputFilesCursor;
5545
0
        SavedStreamPosition SavedPosition(Cursor);
5546
0
        if (llvm::Error Err =
5547
0
                Cursor.JumpToBit(InputFilesOffsetBase + InputFileOffs[I])) {
5548
          // FIXME this drops errors on the floor.
5549
0
          consumeError(std::move(Err));
5550
0
        }
5551
5552
0
        Expected<unsigned> MaybeCode = Cursor.ReadCode();
5553
0
        if (!MaybeCode) {
5554
          // FIXME this drops errors on the floor.
5555
0
          consumeError(MaybeCode.takeError());
5556
0
        }
5557
0
        unsigned Code = MaybeCode.get();
5558
5559
0
        RecordData Record;
5560
0
        StringRef Blob;
5561
0
        bool shouldContinue = false;
5562
0
        Expected<unsigned> MaybeRecordType =
5563
0
            Cursor.readRecord(Code, Record, &Blob);
5564
0
        if (!MaybeRecordType) {
5565
          // FIXME this drops errors on the floor.
5566
0
          consumeError(MaybeRecordType.takeError());
5567
0
        }
5568
0
        switch ((InputFileRecordTypes)MaybeRecordType.get()) {
5569
0
        case INPUT_FILE_HASH:
5570
0
          break;
5571
0
        case INPUT_FILE:
5572
0
          bool Overridden = static_cast<bool>(Record[3]);
5573
0
          std::string Filename = std::string(Blob);
5574
0
          ResolveImportedPath(Filename, ModuleDir);
5575
0
          shouldContinue = Listener.visitInputFile(
5576
0
              Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
5577
0
          break;
5578
0
        }
5579
0
        if (!shouldContinue)
5580
0
          break;
5581
0
      }
5582
0
      break;
5583
0
    }
5584
5585
0
    case IMPORTS: {
5586
0
      if (!NeedsImports)
5587
0
        break;
5588
5589
0
      unsigned Idx = 0, N = Record.size();
5590
0
      while (Idx < N) {
5591
        // Read information about the AST file.
5592
5593
        // Skip Kind
5594
0
        Idx++;
5595
0
        bool IsStandardCXXModule = Record[Idx++];
5596
5597
        // Skip ImportLoc
5598
0
        Idx++;
5599
5600
        // In C++20 Modules, we don't record the path to imported
5601
        // modules in the BMI files.
5602
0
        if (IsStandardCXXModule) {
5603
0
          std::string ModuleName = ReadString(Record, Idx);
5604
0
          Listener.visitImport(ModuleName, /*Filename=*/"");
5605
0
          continue;
5606
0
        }
5607
5608
        // Skip Size, ModTime and Signature
5609
0
        Idx += 1 + 1 + ASTFileSignature::size;
5610
0
        std::string ModuleName = ReadString(Record, Idx);
5611
0
        std::string Filename = ReadString(Record, Idx);
5612
0
        ResolveImportedPath(Filename, ModuleDir);
5613
0
        Listener.visitImport(ModuleName, Filename);
5614
0
      }
5615
0
      break;
5616
0
    }
5617
5618
0
    default:
5619
      // No other validation to perform.
5620
0
      break;
5621
0
    }
5622
0
  }
5623
5624
  // Look for module file extension blocks, if requested.
5625
0
  if (FindModuleFileExtensions) {
5626
0
    BitstreamCursor SavedStream = Stream;
5627
0
    while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
5628
0
      bool DoneWithExtensionBlock = false;
5629
0
      while (!DoneWithExtensionBlock) {
5630
0
        Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5631
0
        if (!MaybeEntry) {
5632
          // FIXME this drops the error.
5633
0
          return true;
5634
0
        }
5635
0
        llvm::BitstreamEntry Entry = MaybeEntry.get();
5636
5637
0
        switch (Entry.Kind) {
5638
0
        case llvm::BitstreamEntry::SubBlock:
5639
0
          if (llvm::Error Err = Stream.SkipBlock()) {
5640
            // FIXME this drops the error on the floor.
5641
0
            consumeError(std::move(Err));
5642
0
            return true;
5643
0
          }
5644
0
          continue;
5645
5646
0
        case llvm::BitstreamEntry::EndBlock:
5647
0
          DoneWithExtensionBlock = true;
5648
0
          continue;
5649
5650
0
        case llvm::BitstreamEntry::Error:
5651
0
          return true;
5652
5653
0
        case llvm::BitstreamEntry::Record:
5654
0
          break;
5655
0
        }
5656
5657
0
       Record.clear();
5658
0
       StringRef Blob;
5659
0
       Expected<unsigned> MaybeRecCode =
5660
0
           Stream.readRecord(Entry.ID, Record, &Blob);
5661
0
       if (!MaybeRecCode) {
5662
         // FIXME this drops the error.
5663
0
         return true;
5664
0
       }
5665
0
       switch (MaybeRecCode.get()) {
5666
0
       case EXTENSION_METADATA: {
5667
0
         ModuleFileExtensionMetadata Metadata;
5668
0
         if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
5669
0
           return true;
5670
5671
0
         Listener.readModuleFileExtension(Metadata);
5672
0
         break;
5673
0
       }
5674
0
       }
5675
0
      }
5676
0
    }
5677
0
    Stream = SavedStream;
5678
0
  }
5679
5680
  // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
5681
0
  if (readUnhashedControlBlockImpl(
5682
0
          nullptr, Bytes, ARR_ConfigurationMismatch | ARR_OutOfDate,
5683
0
          /*AllowCompatibleConfigurationMismatch*/ false, &Listener,
5684
0
          ValidateDiagnosticOptions) != Success)
5685
0
    return true;
5686
5687
0
  return false;
5688
0
}
5689
5690
bool ASTReader::isAcceptableASTFile(StringRef Filename, FileManager &FileMgr,
5691
                                    const InMemoryModuleCache &ModuleCache,
5692
                                    const PCHContainerReader &PCHContainerRdr,
5693
                                    const LangOptions &LangOpts,
5694
                                    const TargetOptions &TargetOpts,
5695
                                    const PreprocessorOptions &PPOpts,
5696
                                    StringRef ExistingModuleCachePath,
5697
0
                                    bool RequireStrictOptionMatches) {
5698
0
  SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
5699
0
                               ExistingModuleCachePath, FileMgr,
5700
0
                               RequireStrictOptionMatches);
5701
0
  return !readASTFileControlBlock(Filename, FileMgr, ModuleCache,
5702
0
                                  PCHContainerRdr,
5703
0
                                  /*FindModuleFileExtensions=*/false, validator,
5704
0
                                  /*ValidateDiagnosticOptions=*/true);
5705
0
}
5706
5707
llvm::Error ASTReader::ReadSubmoduleBlock(ModuleFile &F,
5708
0
                                          unsigned ClientLoadCapabilities) {
5709
  // Enter the submodule block.
5710
0
  if (llvm::Error Err = F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID))
5711
0
    return Err;
5712
5713
0
  ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
5714
0
  bool First = true;
5715
0
  Module *CurrentModule = nullptr;
5716
0
  RecordData Record;
5717
0
  while (true) {
5718
0
    Expected<llvm::BitstreamEntry> MaybeEntry =
5719
0
        F.Stream.advanceSkippingSubblocks();
5720
0
    if (!MaybeEntry)
5721
0
      return MaybeEntry.takeError();
5722
0
    llvm::BitstreamEntry Entry = MaybeEntry.get();
5723
5724
0
    switch (Entry.Kind) {
5725
0
    case llvm::BitstreamEntry::SubBlock: // Handled for us already.
5726
0
    case llvm::BitstreamEntry::Error:
5727
0
      return llvm::createStringError(std::errc::illegal_byte_sequence,
5728
0
                                     "malformed block record in AST file");
5729
0
    case llvm::BitstreamEntry::EndBlock:
5730
0
      return llvm::Error::success();
5731
0
    case llvm::BitstreamEntry::Record:
5732
      // The interesting case.
5733
0
      break;
5734
0
    }
5735
5736
    // Read a record.
5737
0
    StringRef Blob;
5738
0
    Record.clear();
5739
0
    Expected<unsigned> MaybeKind = F.Stream.readRecord(Entry.ID, Record, &Blob);
5740
0
    if (!MaybeKind)
5741
0
      return MaybeKind.takeError();
5742
0
    unsigned Kind = MaybeKind.get();
5743
5744
0
    if ((Kind == SUBMODULE_METADATA) != First)
5745
0
      return llvm::createStringError(
5746
0
          std::errc::illegal_byte_sequence,
5747
0
          "submodule metadata record should be at beginning of block");
5748
0
    First = false;
5749
5750
    // Submodule information is only valid if we have a current module.
5751
    // FIXME: Should we error on these cases?
5752
0
    if (!CurrentModule && Kind != SUBMODULE_METADATA &&
5753
0
        Kind != SUBMODULE_DEFINITION)
5754
0
      continue;
5755
5756
0
    switch (Kind) {
5757
0
    default:  // Default behavior: ignore.
5758
0
      break;
5759
5760
0
    case SUBMODULE_DEFINITION: {
5761
0
      if (Record.size() < 13)
5762
0
        return llvm::createStringError(std::errc::illegal_byte_sequence,
5763
0
                                       "malformed module definition");
5764
5765
0
      StringRef Name = Blob;
5766
0
      unsigned Idx = 0;
5767
0
      SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
5768
0
      SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
5769
0
      Module::ModuleKind Kind = (Module::ModuleKind)Record[Idx++];
5770
0
      SourceLocation DefinitionLoc = ReadSourceLocation(F, Record[Idx++]);
5771
0
      bool IsFramework = Record[Idx++];
5772
0
      bool IsExplicit = Record[Idx++];
5773
0
      bool IsSystem = Record[Idx++];
5774
0
      bool IsExternC = Record[Idx++];
5775
0
      bool InferSubmodules = Record[Idx++];
5776
0
      bool InferExplicitSubmodules = Record[Idx++];
5777
0
      bool InferExportWildcard = Record[Idx++];
5778
0
      bool ConfigMacrosExhaustive = Record[Idx++];
5779
0
      bool ModuleMapIsPrivate = Record[Idx++];
5780
0
      bool NamedModuleHasInit = Record[Idx++];
5781
5782
0
      Module *ParentModule = nullptr;
5783
0
      if (Parent)
5784
0
        ParentModule = getSubmodule(Parent);
5785
5786
      // Retrieve this (sub)module from the module map, creating it if
5787
      // necessary.
5788
0
      CurrentModule =
5789
0
          ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit)
5790
0
              .first;
5791
5792
      // FIXME: Call ModMap.setInferredModuleAllowedBy()
5793
5794
0
      SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
5795
0
      if (GlobalIndex >= SubmodulesLoaded.size() ||
5796
0
          SubmodulesLoaded[GlobalIndex])
5797
0
        return llvm::createStringError(std::errc::invalid_argument,
5798
0
                                       "too many submodules");
5799
5800
0
      if (!ParentModule) {
5801
0
        if (OptionalFileEntryRef CurFile = CurrentModule->getASTFile()) {
5802
          // Don't emit module relocation error if we have -fno-validate-pch
5803
0
          if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
5804
0
                    DisableValidationForModuleKind::Module) &&
5805
0
              CurFile != F.File) {
5806
0
            auto ConflictError =
5807
0
                PartialDiagnostic(diag::err_module_file_conflict,
5808
0
                                  ContextObj->DiagAllocator)
5809
0
                << CurrentModule->getTopLevelModuleName() << CurFile->getName()
5810
0
                << F.File.getName();
5811
0
            return DiagnosticError::create(CurrentImportLoc, ConflictError);
5812
0
          }
5813
0
        }
5814
5815
0
        F.DidReadTopLevelSubmodule = true;
5816
0
        CurrentModule->setASTFile(F.File);
5817
0
        CurrentModule->PresumedModuleMapFile = F.ModuleMapPath;
5818
0
      }
5819
5820
0
      CurrentModule->Kind = Kind;
5821
0
      CurrentModule->DefinitionLoc = DefinitionLoc;
5822
0
      CurrentModule->Signature = F.Signature;
5823
0
      CurrentModule->IsFromModuleFile = true;
5824
0
      CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
5825
0
      CurrentModule->IsExternC = IsExternC;
5826
0
      CurrentModule->InferSubmodules = InferSubmodules;
5827
0
      CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
5828
0
      CurrentModule->InferExportWildcard = InferExportWildcard;
5829
0
      CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
5830
0
      CurrentModule->ModuleMapIsPrivate = ModuleMapIsPrivate;
5831
0
      CurrentModule->NamedModuleHasInit = NamedModuleHasInit;
5832
0
      if (DeserializationListener)
5833
0
        DeserializationListener->ModuleRead(GlobalID, CurrentModule);
5834
5835
0
      SubmodulesLoaded[GlobalIndex] = CurrentModule;
5836
5837
      // Clear out data that will be replaced by what is in the module file.
5838
0
      CurrentModule->LinkLibraries.clear();
5839
0
      CurrentModule->ConfigMacros.clear();
5840
0
      CurrentModule->UnresolvedConflicts.clear();
5841
0
      CurrentModule->Conflicts.clear();
5842
5843
      // The module is available unless it's missing a requirement; relevant
5844
      // requirements will be (re-)added by SUBMODULE_REQUIRES records.
5845
      // Missing headers that were present when the module was built do not
5846
      // make it unavailable -- if we got this far, this must be an explicitly
5847
      // imported module file.
5848
0
      CurrentModule->Requirements.clear();
5849
0
      CurrentModule->MissingHeaders.clear();
5850
0
      CurrentModule->IsUnimportable =
5851
0
          ParentModule && ParentModule->IsUnimportable;
5852
0
      CurrentModule->IsAvailable = !CurrentModule->IsUnimportable;
5853
0
      break;
5854
0
    }
5855
5856
0
    case SUBMODULE_UMBRELLA_HEADER: {
5857
      // FIXME: This doesn't work for framework modules as `Filename` is the
5858
      //        name as written in the module file and does not include
5859
      //        `Headers/`, so this path will never exist.
5860
0
      std::string Filename = std::string(Blob);
5861
0
      ResolveImportedPath(F, Filename);
5862
0
      if (auto Umbrella = PP.getFileManager().getOptionalFileRef(Filename)) {
5863
0
        if (!CurrentModule->getUmbrellaHeaderAsWritten()) {
5864
          // FIXME: NameAsWritten
5865
0
          ModMap.setUmbrellaHeaderAsWritten(CurrentModule, *Umbrella, Blob, "");
5866
0
        }
5867
        // Note that it's too late at this point to return out of date if the
5868
        // name from the PCM doesn't match up with the one in the module map,
5869
        // but also quite unlikely since we will have already checked the
5870
        // modification time and size of the module map file itself.
5871
0
      }
5872
0
      break;
5873
0
    }
5874
5875
0
    case SUBMODULE_HEADER:
5876
0
    case SUBMODULE_EXCLUDED_HEADER:
5877
0
    case SUBMODULE_PRIVATE_HEADER:
5878
      // We lazily associate headers with their modules via the HeaderInfo table.
5879
      // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
5880
      // of complete filenames or remove it entirely.
5881
0
      break;
5882
5883
0
    case SUBMODULE_TEXTUAL_HEADER:
5884
0
    case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
5885
      // FIXME: Textual headers are not marked in the HeaderInfo table. Load
5886
      // them here.
5887
0
      break;
5888
5889
0
    case SUBMODULE_TOPHEADER: {
5890
0
      std::string HeaderName(Blob);
5891
0
      ResolveImportedPath(F, HeaderName);
5892
0
      CurrentModule->addTopHeaderFilename(HeaderName);
5893
0
      break;
5894
0
    }
5895
5896
0
    case SUBMODULE_UMBRELLA_DIR: {
5897
      // See comments in SUBMODULE_UMBRELLA_HEADER
5898
0
      std::string Dirname = std::string(Blob);
5899
0
      ResolveImportedPath(F, Dirname);
5900
0
      if (auto Umbrella =
5901
0
              PP.getFileManager().getOptionalDirectoryRef(Dirname)) {
5902
0
        if (!CurrentModule->getUmbrellaDirAsWritten()) {
5903
          // FIXME: NameAsWritten
5904
0
          ModMap.setUmbrellaDirAsWritten(CurrentModule, *Umbrella, Blob, "");
5905
0
        }
5906
0
      }
5907
0
      break;
5908
0
    }
5909
5910
0
    case SUBMODULE_METADATA: {
5911
0
      F.BaseSubmoduleID = getTotalNumSubmodules();
5912
0
      F.LocalNumSubmodules = Record[0];
5913
0
      unsigned LocalBaseSubmoduleID = Record[1];
5914
0
      if (F.LocalNumSubmodules > 0) {
5915
        // Introduce the global -> local mapping for submodules within this
5916
        // module.
5917
0
        GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
5918
5919
        // Introduce the local -> global mapping for submodules within this
5920
        // module.
5921
0
        F.SubmoduleRemap.insertOrReplace(
5922
0
          std::make_pair(LocalBaseSubmoduleID,
5923
0
                         F.BaseSubmoduleID - LocalBaseSubmoduleID));
5924
5925
0
        SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
5926
0
      }
5927
0
      break;
5928
0
    }
5929
5930
0
    case SUBMODULE_IMPORTS:
5931
0
      for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
5932
0
        UnresolvedModuleRef Unresolved;
5933
0
        Unresolved.File = &F;
5934
0
        Unresolved.Mod = CurrentModule;
5935
0
        Unresolved.ID = Record[Idx];
5936
0
        Unresolved.Kind = UnresolvedModuleRef::Import;
5937
0
        Unresolved.IsWildcard = false;
5938
0
        UnresolvedModuleRefs.push_back(Unresolved);
5939
0
      }
5940
0
      break;
5941
5942
0
    case SUBMODULE_AFFECTING_MODULES:
5943
0
      for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
5944
0
        UnresolvedModuleRef Unresolved;
5945
0
        Unresolved.File = &F;
5946
0
        Unresolved.Mod = CurrentModule;
5947
0
        Unresolved.ID = Record[Idx];
5948
0
        Unresolved.Kind = UnresolvedModuleRef::Affecting;
5949
0
        Unresolved.IsWildcard = false;
5950
0
        UnresolvedModuleRefs.push_back(Unresolved);
5951
0
      }
5952
0
      break;
5953
5954
0
    case SUBMODULE_EXPORTS:
5955
0
      for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
5956
0
        UnresolvedModuleRef Unresolved;
5957
0
        Unresolved.File = &F;
5958
0
        Unresolved.Mod = CurrentModule;
5959
0
        Unresolved.ID = Record[Idx];
5960
0
        Unresolved.Kind = UnresolvedModuleRef::Export;
5961
0
        Unresolved.IsWildcard = Record[Idx + 1];
5962
0
        UnresolvedModuleRefs.push_back(Unresolved);
5963
0
      }
5964
5965
      // Once we've loaded the set of exports, there's no reason to keep
5966
      // the parsed, unresolved exports around.
5967
0
      CurrentModule->UnresolvedExports.clear();
5968
0
      break;
5969
5970
0
    case SUBMODULE_REQUIRES:
5971
0
      CurrentModule->addRequirement(Blob, Record[0], PP.getLangOpts(),
5972
0
                                    PP.getTargetInfo());
5973
0
      break;
5974
5975
0
    case SUBMODULE_LINK_LIBRARY:
5976
0
      ModMap.resolveLinkAsDependencies(CurrentModule);
5977
0
      CurrentModule->LinkLibraries.push_back(
5978
0
          Module::LinkLibrary(std::string(Blob), Record[0]));
5979
0
      break;
5980
5981
0
    case SUBMODULE_CONFIG_MACRO:
5982
0
      CurrentModule->ConfigMacros.push_back(Blob.str());
5983
0
      break;
5984
5985
0
    case SUBMODULE_CONFLICT: {
5986
0
      UnresolvedModuleRef Unresolved;
5987
0
      Unresolved.File = &F;
5988
0
      Unresolved.Mod = CurrentModule;
5989
0
      Unresolved.ID = Record[0];
5990
0
      Unresolved.Kind = UnresolvedModuleRef::Conflict;
5991
0
      Unresolved.IsWildcard = false;
5992
0
      Unresolved.String = Blob;
5993
0
      UnresolvedModuleRefs.push_back(Unresolved);
5994
0
      break;
5995
0
    }
5996
5997
0
    case SUBMODULE_INITIALIZERS: {
5998
0
      if (!ContextObj)
5999
0
        break;
6000
0
      SmallVector<uint32_t, 16> Inits;
6001
0
      for (auto &ID : Record)
6002
0
        Inits.push_back(getGlobalDeclID(F, ID));
6003
0
      ContextObj->addLazyModuleInitializers(CurrentModule, Inits);
6004
0
      break;
6005
0
    }
6006
6007
0
    case SUBMODULE_EXPORT_AS:
6008
0
      CurrentModule->ExportAsModule = Blob.str();
6009
0
      ModMap.addLinkAsDependency(CurrentModule);
6010
0
      break;
6011
0
    }
6012
0
  }
6013
0
}
6014
6015
/// Parse the record that corresponds to a LangOptions data
6016
/// structure.
6017
///
6018
/// This routine parses the language options from the AST file and then gives
6019
/// them to the AST listener if one is set.
6020
///
6021
/// \returns true if the listener deems the file unacceptable, false otherwise.
6022
bool ASTReader::ParseLanguageOptions(const RecordData &Record,
6023
                                     bool Complain,
6024
                                     ASTReaderListener &Listener,
6025
0
                                     bool AllowCompatibleDifferences) {
6026
0
  LangOptions LangOpts;
6027
0
  unsigned Idx = 0;
6028
0
#define LANGOPT(Name, Bits, Default, Description) \
6029
0
  LangOpts.Name = Record[Idx++];
6030
0
#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
6031
0
  LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
6032
0
#include "clang/Basic/LangOptions.def"
6033
0
#define SANITIZER(NAME, ID)                                                    \
6034
0
  LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
6035
0
#include "clang/Basic/Sanitizers.def"
6036
6037
0
  for (unsigned N = Record[Idx++]; N; --N)
6038
0
    LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
6039
6040
0
  ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
6041
0
  VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
6042
0
  LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
6043
6044
0
  LangOpts.CurrentModule = ReadString(Record, Idx);
6045
6046
  // Comment options.
6047
0
  for (unsigned N = Record[Idx++]; N; --N) {
6048
0
    LangOpts.CommentOpts.BlockCommandNames.push_back(
6049
0
      ReadString(Record, Idx));
6050
0
  }
6051
0
  LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
6052
6053
  // OpenMP offloading options.
6054
0
  for (unsigned N = Record[Idx++]; N; --N) {
6055
0
    LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
6056
0
  }
6057
6058
0
  LangOpts.OMPHostIRFile = ReadString(Record, Idx);
6059
6060
0
  return Listener.ReadLanguageOptions(LangOpts, Complain,
6061
0
                                      AllowCompatibleDifferences);
6062
0
}
6063
6064
bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
6065
                                   ASTReaderListener &Listener,
6066
0
                                   bool AllowCompatibleDifferences) {
6067
0
  unsigned Idx = 0;
6068
0
  TargetOptions TargetOpts;
6069
0
  TargetOpts.Triple = ReadString(Record, Idx);
6070
0
  TargetOpts.CPU = ReadString(Record, Idx);
6071
0
  TargetOpts.TuneCPU = ReadString(Record, Idx);
6072
0
  TargetOpts.ABI = ReadString(Record, Idx);
6073
0
  for (unsigned N = Record[Idx++]; N; --N) {
6074
0
    TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
6075
0
  }
6076
0
  for (unsigned N = Record[Idx++]; N; --N) {
6077
0
    TargetOpts.Features.push_back(ReadString(Record, Idx));
6078
0
  }
6079
6080
0
  return Listener.ReadTargetOptions(TargetOpts, Complain,
6081
0
                                    AllowCompatibleDifferences);
6082
0
}
6083
6084
bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
6085
0
                                       ASTReaderListener &Listener) {
6086
0
  IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
6087
0
  unsigned Idx = 0;
6088
0
#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
6089
0
#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
6090
0
  DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
6091
0
#include "clang/Basic/DiagnosticOptions.def"
6092
6093
0
  for (unsigned N = Record[Idx++]; N; --N)
6094
0
    DiagOpts->Warnings.push_back(ReadString(Record, Idx));
6095
0
  for (unsigned N = Record[Idx++]; N; --N)
6096
0
    DiagOpts->Remarks.push_back(ReadString(Record, Idx));
6097
6098
0
  return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
6099
0
}
6100
6101
bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
6102
0
                                       ASTReaderListener &Listener) {
6103
0
  FileSystemOptions FSOpts;
6104
0
  unsigned Idx = 0;
6105
0
  FSOpts.WorkingDir = ReadString(Record, Idx);
6106
0
  return Listener.ReadFileSystemOptions(FSOpts, Complain);
6107
0
}
6108
6109
bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
6110
                                         bool Complain,
6111
0
                                         ASTReaderListener &Listener) {
6112
0
  HeaderSearchOptions HSOpts;
6113
0
  unsigned Idx = 0;
6114
0
  HSOpts.Sysroot = ReadString(Record, Idx);
6115
6116
0
  HSOpts.ResourceDir = ReadString(Record, Idx);
6117
0
  HSOpts.ModuleCachePath = ReadString(Record, Idx);
6118
0
  HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
6119
0
  HSOpts.DisableModuleHash = Record[Idx++];
6120
0
  HSOpts.ImplicitModuleMaps = Record[Idx++];
6121
0
  HSOpts.ModuleMapFileHomeIsCwd = Record[Idx++];
6122
0
  HSOpts.EnablePrebuiltImplicitModules = Record[Idx++];
6123
0
  HSOpts.UseBuiltinIncludes = Record[Idx++];
6124
0
  HSOpts.UseStandardSystemIncludes = Record[Idx++];
6125
0
  HSOpts.UseStandardCXXIncludes = Record[Idx++];
6126
0
  HSOpts.UseLibcxx = Record[Idx++];
6127
0
  std::string SpecificModuleCachePath = ReadString(Record, Idx);
6128
6129
0
  return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
6130
0
                                          Complain);
6131
0
}
6132
6133
bool ASTReader::ParseHeaderSearchPaths(const RecordData &Record, bool Complain,
6134
0
                                       ASTReaderListener &Listener) {
6135
0
  HeaderSearchOptions HSOpts;
6136
0
  unsigned Idx = 0;
6137
6138
  // Include entries.
6139
0
  for (unsigned N = Record[Idx++]; N; --N) {
6140
0
    std::string Path = ReadString(Record, Idx);
6141
0
    frontend::IncludeDirGroup Group
6142
0
      = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
6143
0
    bool IsFramework = Record[Idx++];
6144
0
    bool IgnoreSysRoot = Record[Idx++];
6145
0
    HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
6146
0
                                    IgnoreSysRoot);
6147
0
  }
6148
6149
  // System header prefixes.
6150
0
  for (unsigned N = Record[Idx++]; N; --N) {
6151
0
    std::string Prefix = ReadString(Record, Idx);
6152
0
    bool IsSystemHeader = Record[Idx++];
6153
0
    HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
6154
0
  }
6155
6156
  // VFS overlay files.
6157
0
  for (unsigned N = Record[Idx++]; N; --N) {
6158
0
    std::string VFSOverlayFile = ReadString(Record, Idx);
6159
0
    HSOpts.VFSOverlayFiles.emplace_back(std::move(VFSOverlayFile));
6160
0
  }
6161
6162
0
  return Listener.ReadHeaderSearchPaths(HSOpts, Complain);
6163
0
}
6164
6165
bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
6166
                                         bool Complain,
6167
                                         ASTReaderListener &Listener,
6168
0
                                         std::string &SuggestedPredefines) {
6169
0
  PreprocessorOptions PPOpts;
6170
0
  unsigned Idx = 0;
6171
6172
  // Macro definitions/undefs
6173
0
  bool ReadMacros = Record[Idx++];
6174
0
  if (ReadMacros) {
6175
0
    for (unsigned N = Record[Idx++]; N; --N) {
6176
0
      std::string Macro = ReadString(Record, Idx);
6177
0
      bool IsUndef = Record[Idx++];
6178
0
      PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
6179
0
    }
6180
0
  }
6181
6182
  // Includes
6183
0
  for (unsigned N = Record[Idx++]; N; --N) {
6184
0
    PPOpts.Includes.push_back(ReadString(Record, Idx));
6185
0
  }
6186
6187
  // Macro Includes
6188
0
  for (unsigned N = Record[Idx++]; N; --N) {
6189
0
    PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
6190
0
  }
6191
6192
0
  PPOpts.UsePredefines = Record[Idx++];
6193
0
  PPOpts.DetailedRecord = Record[Idx++];
6194
0
  PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
6195
0
  PPOpts.ObjCXXARCStandardLibrary =
6196
0
    static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
6197
0
  SuggestedPredefines.clear();
6198
0
  return Listener.ReadPreprocessorOptions(PPOpts, ReadMacros, Complain,
6199
0
                                          SuggestedPredefines);
6200
0
}
6201
6202
std::pair<ModuleFile *, unsigned>
6203
0
ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
6204
0
  GlobalPreprocessedEntityMapType::iterator
6205
0
  I = GlobalPreprocessedEntityMap.find(GlobalIndex);
6206
0
  assert(I != GlobalPreprocessedEntityMap.end() &&
6207
0
         "Corrupted global preprocessed entity map");
6208
0
  ModuleFile *M = I->second;
6209
0
  unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
6210
0
  return std::make_pair(M, LocalIndex);
6211
0
}
6212
6213
llvm::iterator_range<PreprocessingRecord::iterator>
6214
0
ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
6215
0
  if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
6216
0
    return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
6217
0
                                             Mod.NumPreprocessedEntities);
6218
6219
0
  return llvm::make_range(PreprocessingRecord::iterator(),
6220
0
                          PreprocessingRecord::iterator());
6221
0
}
6222
6223
bool ASTReader::canRecoverFromOutOfDate(StringRef ModuleFileName,
6224
0
                                        unsigned int ClientLoadCapabilities) {
6225
0
  return ClientLoadCapabilities & ARR_OutOfDate &&
6226
0
         !getModuleManager().getModuleCache().isPCMFinal(ModuleFileName);
6227
0
}
6228
6229
llvm::iterator_range<ASTReader::ModuleDeclIterator>
6230
0
ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
6231
0
  return llvm::make_range(
6232
0
      ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
6233
0
      ModuleDeclIterator(this, &Mod,
6234
0
                         Mod.FileSortedDecls + Mod.NumFileSortedDecls));
6235
0
}
6236
6237
0
SourceRange ASTReader::ReadSkippedRange(unsigned GlobalIndex) {
6238
0
  auto I = GlobalSkippedRangeMap.find(GlobalIndex);
6239
0
  assert(I != GlobalSkippedRangeMap.end() &&
6240
0
    "Corrupted global skipped range map");
6241
0
  ModuleFile *M = I->second;
6242
0
  unsigned LocalIndex = GlobalIndex - M->BasePreprocessedSkippedRangeID;
6243
0
  assert(LocalIndex < M->NumPreprocessedSkippedRanges);
6244
0
  PPSkippedRange RawRange = M->PreprocessedSkippedRangeOffsets[LocalIndex];
6245
0
  SourceRange Range(TranslateSourceLocation(*M, RawRange.getBegin()),
6246
0
                    TranslateSourceLocation(*M, RawRange.getEnd()));
6247
0
  assert(Range.isValid());
6248
0
  return Range;
6249
0
}
6250
6251
0
PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
6252
0
  PreprocessedEntityID PPID = Index+1;
6253
0
  std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
6254
0
  ModuleFile &M = *PPInfo.first;
6255
0
  unsigned LocalIndex = PPInfo.second;
6256
0
  const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
6257
6258
0
  if (!PP.getPreprocessingRecord()) {
6259
0
    Error("no preprocessing record");
6260
0
    return nullptr;
6261
0
  }
6262
6263
0
  SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
6264
0
  if (llvm::Error Err = M.PreprocessorDetailCursor.JumpToBit(
6265
0
          M.MacroOffsetsBase + PPOffs.BitOffset)) {
6266
0
    Error(std::move(Err));
6267
0
    return nullptr;
6268
0
  }
6269
6270
0
  Expected<llvm::BitstreamEntry> MaybeEntry =
6271
0
      M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
6272
0
  if (!MaybeEntry) {
6273
0
    Error(MaybeEntry.takeError());
6274
0
    return nullptr;
6275
0
  }
6276
0
  llvm::BitstreamEntry Entry = MaybeEntry.get();
6277
6278
0
  if (Entry.Kind != llvm::BitstreamEntry::Record)
6279
0
    return nullptr;
6280
6281
  // Read the record.
6282
0
  SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()),
6283
0
                    TranslateSourceLocation(M, PPOffs.getEnd()));
6284
0
  PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
6285
0
  StringRef Blob;
6286
0
  RecordData Record;
6287
0
  Expected<unsigned> MaybeRecType =
6288
0
      M.PreprocessorDetailCursor.readRecord(Entry.ID, Record, &Blob);
6289
0
  if (!MaybeRecType) {
6290
0
    Error(MaybeRecType.takeError());
6291
0
    return nullptr;
6292
0
  }
6293
0
  switch ((PreprocessorDetailRecordTypes)MaybeRecType.get()) {
6294
0
  case PPD_MACRO_EXPANSION: {
6295
0
    bool isBuiltin = Record[0];
6296
0
    IdentifierInfo *Name = nullptr;
6297
0
    MacroDefinitionRecord *Def = nullptr;
6298
0
    if (isBuiltin)
6299
0
      Name = getLocalIdentifier(M, Record[1]);
6300
0
    else {
6301
0
      PreprocessedEntityID GlobalID =
6302
0
          getGlobalPreprocessedEntityID(M, Record[1]);
6303
0
      Def = cast<MacroDefinitionRecord>(
6304
0
          PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
6305
0
    }
6306
6307
0
    MacroExpansion *ME;
6308
0
    if (isBuiltin)
6309
0
      ME = new (PPRec) MacroExpansion(Name, Range);
6310
0
    else
6311
0
      ME = new (PPRec) MacroExpansion(Def, Range);
6312
6313
0
    return ME;
6314
0
  }
6315
6316
0
  case PPD_MACRO_DEFINITION: {
6317
    // Decode the identifier info and then check again; if the macro is
6318
    // still defined and associated with the identifier,
6319
0
    IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
6320
0
    MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
6321
6322
0
    if (DeserializationListener)
6323
0
      DeserializationListener->MacroDefinitionRead(PPID, MD);
6324
6325
0
    return MD;
6326
0
  }
6327
6328
0
  case PPD_INCLUSION_DIRECTIVE: {
6329
0
    const char *FullFileNameStart = Blob.data() + Record[0];
6330
0
    StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
6331
0
    OptionalFileEntryRef File;
6332
0
    if (!FullFileName.empty())
6333
0
      File = PP.getFileManager().getOptionalFileRef(FullFileName);
6334
6335
    // FIXME: Stable encoding
6336
0
    InclusionDirective::InclusionKind Kind
6337
0
      = static_cast<InclusionDirective::InclusionKind>(Record[2]);
6338
0
    InclusionDirective *ID
6339
0
      = new (PPRec) InclusionDirective(PPRec, Kind,
6340
0
                                       StringRef(Blob.data(), Record[0]),
6341
0
                                       Record[1], Record[3],
6342
0
                                       File,
6343
0
                                       Range);
6344
0
    return ID;
6345
0
  }
6346
0
  }
6347
6348
0
  llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
6349
0
}
6350
6351
/// Find the next module that contains entities and return the ID
6352
/// of the first entry.
6353
///
6354
/// \param SLocMapI points at a chunk of a module that contains no
6355
/// preprocessed entities or the entities it contains are not the ones we are
6356
/// looking for.
6357
PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
6358
0
                       GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
6359
0
  ++SLocMapI;
6360
0
  for (GlobalSLocOffsetMapType::const_iterator
6361
0
         EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
6362
0
    ModuleFile &M = *SLocMapI->second;
6363
0
    if (M.NumPreprocessedEntities)
6364
0
      return M.BasePreprocessedEntityID;
6365
0
  }
6366
6367
0
  return getTotalNumPreprocessedEntities();
6368
0
}
6369
6370
namespace {
6371
6372
struct PPEntityComp {
6373
  const ASTReader &Reader;
6374
  ModuleFile &M;
6375
6376
0
  PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) {}
6377
6378
0
  bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
6379
0
    SourceLocation LHS = getLoc(L);
6380
0
    SourceLocation RHS = getLoc(R);
6381
0
    return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6382
0
  }
6383
6384
0
  bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
6385
0
    SourceLocation LHS = getLoc(L);
6386
0
    return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6387
0
  }
6388
6389
0
  bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
6390
0
    SourceLocation RHS = getLoc(R);
6391
0
    return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6392
0
  }
6393
6394
0
  SourceLocation getLoc(const PPEntityOffset &PPE) const {
6395
0
    return Reader.TranslateSourceLocation(M, PPE.getBegin());
6396
0
  }
6397
};
6398
6399
} // namespace
6400
6401
PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
6402
0
                                                       bool EndsAfter) const {
6403
0
  if (SourceMgr.isLocalSourceLocation(Loc))
6404
0
    return getTotalNumPreprocessedEntities();
6405
6406
0
  GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
6407
0
      SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
6408
0
  assert(SLocMapI != GlobalSLocOffsetMap.end() &&
6409
0
         "Corrupted global sloc offset map");
6410
6411
0
  if (SLocMapI->second->NumPreprocessedEntities == 0)
6412
0
    return findNextPreprocessedEntity(SLocMapI);
6413
6414
0
  ModuleFile &M = *SLocMapI->second;
6415
6416
0
  using pp_iterator = const PPEntityOffset *;
6417
6418
0
  pp_iterator pp_begin = M.PreprocessedEntityOffsets;
6419
0
  pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
6420
6421
0
  size_t Count = M.NumPreprocessedEntities;
6422
0
  size_t Half;
6423
0
  pp_iterator First = pp_begin;
6424
0
  pp_iterator PPI;
6425
6426
0
  if (EndsAfter) {
6427
0
    PPI = std::upper_bound(pp_begin, pp_end, Loc,
6428
0
                           PPEntityComp(*this, M));
6429
0
  } else {
6430
    // Do a binary search manually instead of using std::lower_bound because
6431
    // The end locations of entities may be unordered (when a macro expansion
6432
    // is inside another macro argument), but for this case it is not important
6433
    // whether we get the first macro expansion or its containing macro.
6434
0
    while (Count > 0) {
6435
0
      Half = Count / 2;
6436
0
      PPI = First;
6437
0
      std::advance(PPI, Half);
6438
0
      if (SourceMgr.isBeforeInTranslationUnit(
6439
0
              TranslateSourceLocation(M, PPI->getEnd()), Loc)) {
6440
0
        First = PPI;
6441
0
        ++First;
6442
0
        Count = Count - Half - 1;
6443
0
      } else
6444
0
        Count = Half;
6445
0
    }
6446
0
  }
6447
6448
0
  if (PPI == pp_end)
6449
0
    return findNextPreprocessedEntity(SLocMapI);
6450
6451
0
  return M.BasePreprocessedEntityID + (PPI - pp_begin);
6452
0
}
6453
6454
/// Returns a pair of [Begin, End) indices of preallocated
6455
/// preprocessed entities that \arg Range encompasses.
6456
std::pair<unsigned, unsigned>
6457
0
    ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
6458
0
  if (Range.isInvalid())
6459
0
    return std::make_pair(0,0);
6460
0
  assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
6461
6462
0
  PreprocessedEntityID BeginID =
6463
0
      findPreprocessedEntity(Range.getBegin(), false);
6464
0
  PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
6465
0
  return std::make_pair(BeginID, EndID);
6466
0
}
6467
6468
/// Optionally returns true or false if the preallocated preprocessed
6469
/// entity with index \arg Index came from file \arg FID.
6470
std::optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
6471
0
                                                            FileID FID) {
6472
0
  if (FID.isInvalid())
6473
0
    return false;
6474
6475
0
  std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
6476
0
  ModuleFile &M = *PPInfo.first;
6477
0
  unsigned LocalIndex = PPInfo.second;
6478
0
  const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
6479
6480
0
  SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin());
6481
0
  if (Loc.isInvalid())
6482
0
    return false;
6483
6484
0
  if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
6485
0
    return true;
6486
0
  else
6487
0
    return false;
6488
0
}
6489
6490
namespace {
6491
6492
  /// Visitor used to search for information about a header file.
6493
  class HeaderFileInfoVisitor {
6494
  FileEntryRef FE;
6495
    std::optional<HeaderFileInfo> HFI;
6496
6497
  public:
6498
0
    explicit HeaderFileInfoVisitor(FileEntryRef FE) : FE(FE) {}
6499
6500
0
    bool operator()(ModuleFile &M) {
6501
0
      HeaderFileInfoLookupTable *Table
6502
0
        = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
6503
0
      if (!Table)
6504
0
        return false;
6505
6506
      // Look in the on-disk hash table for an entry for this file name.
6507
0
      HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
6508
0
      if (Pos == Table->end())
6509
0
        return false;
6510
6511
0
      HFI = *Pos;
6512
0
      return true;
6513
0
    }
6514
6515
0
    std::optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
6516
  };
6517
6518
} // namespace
6519
6520
0
HeaderFileInfo ASTReader::GetHeaderFileInfo(FileEntryRef FE) {
6521
0
  HeaderFileInfoVisitor Visitor(FE);
6522
0
  ModuleMgr.visit(Visitor);
6523
0
  if (std::optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
6524
0
      return *HFI;
6525
6526
0
  return HeaderFileInfo();
6527
0
}
6528
6529
0
void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
6530
0
  using DiagState = DiagnosticsEngine::DiagState;
6531
0
  SmallVector<DiagState *, 32> DiagStates;
6532
6533
0
  for (ModuleFile &F : ModuleMgr) {
6534
0
    unsigned Idx = 0;
6535
0
    auto &Record = F.PragmaDiagMappings;
6536
0
    if (Record.empty())
6537
0
      continue;
6538
6539
0
    DiagStates.clear();
6540
6541
0
    auto ReadDiagState = [&](const DiagState &BasedOn,
6542
0
                             bool IncludeNonPragmaStates) {
6543
0
      unsigned BackrefID = Record[Idx++];
6544
0
      if (BackrefID != 0)
6545
0
        return DiagStates[BackrefID - 1];
6546
6547
      // A new DiagState was created here.
6548
0
      Diag.DiagStates.push_back(BasedOn);
6549
0
      DiagState *NewState = &Diag.DiagStates.back();
6550
0
      DiagStates.push_back(NewState);
6551
0
      unsigned Size = Record[Idx++];
6552
0
      assert(Idx + Size * 2 <= Record.size() &&
6553
0
             "Invalid data, not enough diag/map pairs");
6554
0
      while (Size--) {
6555
0
        unsigned DiagID = Record[Idx++];
6556
0
        DiagnosticMapping NewMapping =
6557
0
            DiagnosticMapping::deserialize(Record[Idx++]);
6558
0
        if (!NewMapping.isPragma() && !IncludeNonPragmaStates)
6559
0
          continue;
6560
6561
0
        DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID);
6562
6563
        // If this mapping was specified as a warning but the severity was
6564
        // upgraded due to diagnostic settings, simulate the current diagnostic
6565
        // settings (and use a warning).
6566
0
        if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) {
6567
0
          NewMapping.setSeverity(diag::Severity::Warning);
6568
0
          NewMapping.setUpgradedFromWarning(false);
6569
0
        }
6570
6571
0
        Mapping = NewMapping;
6572
0
      }
6573
0
      return NewState;
6574
0
    };
6575
6576
    // Read the first state.
6577
0
    DiagState *FirstState;
6578
0
    if (F.Kind == MK_ImplicitModule) {
6579
      // Implicitly-built modules are reused with different diagnostic
6580
      // settings.  Use the initial diagnostic state from Diag to simulate this
6581
      // compilation's diagnostic settings.
6582
0
      FirstState = Diag.DiagStatesByLoc.FirstDiagState;
6583
0
      DiagStates.push_back(FirstState);
6584
6585
      // Skip the initial diagnostic state from the serialized module.
6586
0
      assert(Record[1] == 0 &&
6587
0
             "Invalid data, unexpected backref in initial state");
6588
0
      Idx = 3 + Record[2] * 2;
6589
0
      assert(Idx < Record.size() &&
6590
0
             "Invalid data, not enough state change pairs in initial state");
6591
0
    } else if (F.isModule()) {
6592
      // For an explicit module, preserve the flags from the module build
6593
      // command line (-w, -Weverything, -Werror, ...) along with any explicit
6594
      // -Wblah flags.
6595
0
      unsigned Flags = Record[Idx++];
6596
0
      DiagState Initial;
6597
0
      Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1;
6598
0
      Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1;
6599
0
      Initial.WarningsAsErrors = Flags & 1; Flags >>= 1;
6600
0
      Initial.EnableAllWarnings = Flags & 1; Flags >>= 1;
6601
0
      Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1;
6602
0
      Initial.ExtBehavior = (diag::Severity)Flags;
6603
0
      FirstState = ReadDiagState(Initial, true);
6604
6605
0
      assert(F.OriginalSourceFileID.isValid());
6606
6607
      // Set up the root buffer of the module to start with the initial
6608
      // diagnostic state of the module itself, to cover files that contain no
6609
      // explicit transitions (for which we did not serialize anything).
6610
0
      Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID]
6611
0
          .StateTransitions.push_back({FirstState, 0});
6612
0
    } else {
6613
      // For prefix ASTs, start with whatever the user configured on the
6614
      // command line.
6615
0
      Idx++; // Skip flags.
6616
0
      FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState, false);
6617
0
    }
6618
6619
    // Read the state transitions.
6620
0
    unsigned NumLocations = Record[Idx++];
6621
0
    while (NumLocations--) {
6622
0
      assert(Idx < Record.size() &&
6623
0
             "Invalid data, missing pragma diagnostic states");
6624
0
      SourceLocation Loc = ReadSourceLocation(F, Record[Idx++]);
6625
0
      auto IDAndOffset = SourceMgr.getDecomposedLoc(Loc);
6626
0
      assert(IDAndOffset.first.isValid() && "invalid FileID for transition");
6627
0
      assert(IDAndOffset.second == 0 && "not a start location for a FileID");
6628
0
      unsigned Transitions = Record[Idx++];
6629
6630
      // Note that we don't need to set up Parent/ParentOffset here, because
6631
      // we won't be changing the diagnostic state within imported FileIDs
6632
      // (other than perhaps appending to the main source file, which has no
6633
      // parent).
6634
0
      auto &F = Diag.DiagStatesByLoc.Files[IDAndOffset.first];
6635
0
      F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
6636
0
      for (unsigned I = 0; I != Transitions; ++I) {
6637
0
        unsigned Offset = Record[Idx++];
6638
0
        auto *State = ReadDiagState(*FirstState, false);
6639
0
        F.StateTransitions.push_back({State, Offset});
6640
0
      }
6641
0
    }
6642
6643
    // Read the final state.
6644
0
    assert(Idx < Record.size() &&
6645
0
           "Invalid data, missing final pragma diagnostic state");
6646
0
    SourceLocation CurStateLoc = ReadSourceLocation(F, Record[Idx++]);
6647
0
    auto *CurState = ReadDiagState(*FirstState, false);
6648
6649
0
    if (!F.isModule()) {
6650
0
      Diag.DiagStatesByLoc.CurDiagState = CurState;
6651
0
      Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
6652
6653
      // Preserve the property that the imaginary root file describes the
6654
      // current state.
6655
0
      FileID NullFile;
6656
0
      auto &T = Diag.DiagStatesByLoc.Files[NullFile].StateTransitions;
6657
0
      if (T.empty())
6658
0
        T.push_back({CurState, 0});
6659
0
      else
6660
0
        T[0].State = CurState;
6661
0
    }
6662
6663
    // Don't try to read these mappings again.
6664
0
    Record.clear();
6665
0
  }
6666
0
}
6667
6668
/// Get the correct cursor and offset for loading a type.
6669
0
ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
6670
0
  GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
6671
0
  assert(I != GlobalTypeMap.end() && "Corrupted global type map");
6672
0
  ModuleFile *M = I->second;
6673
0
  return RecordLocation(
6674
0
      M, M->TypeOffsets[Index - M->BaseTypeIndex].getBitOffset() +
6675
0
             M->DeclsBlockStartOffset);
6676
0
}
6677
6678
0
static std::optional<Type::TypeClass> getTypeClassForCode(TypeCode code) {
6679
0
  switch (code) {
6680
0
#define TYPE_BIT_CODE(CLASS_ID, CODE_ID, CODE_VALUE) \
6681
0
  case TYPE_##CODE_ID: return Type::CLASS_ID;
6682
0
#include "clang/Serialization/TypeBitCodes.def"
6683
0
  default:
6684
0
    return std::nullopt;
6685
0
  }
6686
0
}
6687
6688
/// Read and return the type with the given index..
6689
///
6690
/// The index is the type ID, shifted and minus the number of predefs. This
6691
/// routine actually reads the record corresponding to the type at the given
6692
/// location. It is a helper routine for GetType, which deals with reading type
6693
/// IDs.
6694
0
QualType ASTReader::readTypeRecord(unsigned Index) {
6695
0
  assert(ContextObj && "reading type with no AST context");
6696
0
  ASTContext &Context = *ContextObj;
6697
0
  RecordLocation Loc = TypeCursorForIndex(Index);
6698
0
  BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
6699
6700
  // Keep track of where we are in the stream, then jump back there
6701
  // after reading this type.
6702
0
  SavedStreamPosition SavedPosition(DeclsCursor);
6703
6704
0
  ReadingKindTracker ReadingKind(Read_Type, *this);
6705
6706
  // Note that we are loading a type record.
6707
0
  Deserializing AType(this);
6708
6709
0
  if (llvm::Error Err = DeclsCursor.JumpToBit(Loc.Offset)) {
6710
0
    Error(std::move(Err));
6711
0
    return QualType();
6712
0
  }
6713
0
  Expected<unsigned> RawCode = DeclsCursor.ReadCode();
6714
0
  if (!RawCode) {
6715
0
    Error(RawCode.takeError());
6716
0
    return QualType();
6717
0
  }
6718
6719
0
  ASTRecordReader Record(*this, *Loc.F);
6720
0
  Expected<unsigned> Code = Record.readRecord(DeclsCursor, RawCode.get());
6721
0
  if (!Code) {
6722
0
    Error(Code.takeError());
6723
0
    return QualType();
6724
0
  }
6725
0
  if (Code.get() == TYPE_EXT_QUAL) {
6726
0
    QualType baseType = Record.readQualType();
6727
0
    Qualifiers quals = Record.readQualifiers();
6728
0
    return Context.getQualifiedType(baseType, quals);
6729
0
  }
6730
6731
0
  auto maybeClass = getTypeClassForCode((TypeCode) Code.get());
6732
0
  if (!maybeClass) {
6733
0
    Error("Unexpected code for type");
6734
0
    return QualType();
6735
0
  }
6736
6737
0
  serialization::AbstractTypeReader<ASTRecordReader> TypeReader(Record);
6738
0
  return TypeReader.read(*maybeClass);
6739
0
}
6740
6741
namespace clang {
6742
6743
class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
6744
  using LocSeq = SourceLocationSequence;
6745
6746
  ASTRecordReader &Reader;
6747
  LocSeq *Seq;
6748
6749
0
  SourceLocation readSourceLocation() { return Reader.readSourceLocation(Seq); }
6750
0
  SourceRange readSourceRange() { return Reader.readSourceRange(Seq); }
6751
6752
0
  TypeSourceInfo *GetTypeSourceInfo() {
6753
0
    return Reader.readTypeSourceInfo();
6754
0
  }
6755
6756
0
  NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
6757
0
    return Reader.readNestedNameSpecifierLoc();
6758
0
  }
6759
6760
0
  Attr *ReadAttr() {
6761
0
    return Reader.readAttr();
6762
0
  }
6763
6764
public:
6765
  TypeLocReader(ASTRecordReader &Reader, LocSeq *Seq)
6766
0
      : Reader(Reader), Seq(Seq) {}
6767
6768
  // We want compile-time assurance that we've enumerated all of
6769
  // these, so unfortunately we have to declare them first, then
6770
  // define them out-of-line.
6771
#define ABSTRACT_TYPELOC(CLASS, PARENT)
6772
#define TYPELOC(CLASS, PARENT) \
6773
  void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
6774
#include "clang/AST/TypeLocNodes.def"
6775
6776
  void VisitFunctionTypeLoc(FunctionTypeLoc);
6777
  void VisitArrayTypeLoc(ArrayTypeLoc);
6778
};
6779
6780
} // namespace clang
6781
6782
0
void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6783
  // nothing to do
6784
0
}
6785
6786
0
void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
6787
0
  TL.setBuiltinLoc(readSourceLocation());
6788
0
  if (TL.needsExtraLocalData()) {
6789
0
    TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Reader.readInt()));
6790
0
    TL.setWrittenSignSpec(static_cast<TypeSpecifierSign>(Reader.readInt()));
6791
0
    TL.setWrittenWidthSpec(static_cast<TypeSpecifierWidth>(Reader.readInt()));
6792
0
    TL.setModeAttr(Reader.readInt());
6793
0
  }
6794
0
}
6795
6796
0
void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
6797
0
  TL.setNameLoc(readSourceLocation());
6798
0
}
6799
6800
0
void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
6801
0
  TL.setStarLoc(readSourceLocation());
6802
0
}
6803
6804
0
void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6805
  // nothing to do
6806
0
}
6807
6808
0
void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6809
  // nothing to do
6810
0
}
6811
6812
0
void TypeLocReader::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
6813
0
  TL.setExpansionLoc(readSourceLocation());
6814
0
}
6815
6816
0
void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
6817
0
  TL.setCaretLoc(readSourceLocation());
6818
0
}
6819
6820
0
void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
6821
0
  TL.setAmpLoc(readSourceLocation());
6822
0
}
6823
6824
0
void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
6825
0
  TL.setAmpAmpLoc(readSourceLocation());
6826
0
}
6827
6828
0
void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
6829
0
  TL.setStarLoc(readSourceLocation());
6830
0
  TL.setClassTInfo(GetTypeSourceInfo());
6831
0
}
6832
6833
0
void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
6834
0
  TL.setLBracketLoc(readSourceLocation());
6835
0
  TL.setRBracketLoc(readSourceLocation());
6836
0
  if (Reader.readBool())
6837
0
    TL.setSizeExpr(Reader.readExpr());
6838
0
  else
6839
0
    TL.setSizeExpr(nullptr);
6840
0
}
6841
6842
0
void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
6843
0
  VisitArrayTypeLoc(TL);
6844
0
}
6845
6846
0
void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
6847
0
  VisitArrayTypeLoc(TL);
6848
0
}
6849
6850
0
void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
6851
0
  VisitArrayTypeLoc(TL);
6852
0
}
6853
6854
void TypeLocReader::VisitDependentSizedArrayTypeLoc(
6855
0
                                            DependentSizedArrayTypeLoc TL) {
6856
0
  VisitArrayTypeLoc(TL);
6857
0
}
6858
6859
void TypeLocReader::VisitDependentAddressSpaceTypeLoc(
6860
0
    DependentAddressSpaceTypeLoc TL) {
6861
6862
0
    TL.setAttrNameLoc(readSourceLocation());
6863
0
    TL.setAttrOperandParensRange(readSourceRange());
6864
0
    TL.setAttrExprOperand(Reader.readExpr());
6865
0
}
6866
6867
void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
6868
0
                                        DependentSizedExtVectorTypeLoc TL) {
6869
0
  TL.setNameLoc(readSourceLocation());
6870
0
}
6871
6872
0
void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
6873
0
  TL.setNameLoc(readSourceLocation());
6874
0
}
6875
6876
void TypeLocReader::VisitDependentVectorTypeLoc(
6877
0
    DependentVectorTypeLoc TL) {
6878
0
  TL.setNameLoc(readSourceLocation());
6879
0
}
6880
6881
0
void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
6882
0
  TL.setNameLoc(readSourceLocation());
6883
0
}
6884
6885
0
void TypeLocReader::VisitConstantMatrixTypeLoc(ConstantMatrixTypeLoc TL) {
6886
0
  TL.setAttrNameLoc(readSourceLocation());
6887
0
  TL.setAttrOperandParensRange(readSourceRange());
6888
0
  TL.setAttrRowOperand(Reader.readExpr());
6889
0
  TL.setAttrColumnOperand(Reader.readExpr());
6890
0
}
6891
6892
void TypeLocReader::VisitDependentSizedMatrixTypeLoc(
6893
0
    DependentSizedMatrixTypeLoc TL) {
6894
0
  TL.setAttrNameLoc(readSourceLocation());
6895
0
  TL.setAttrOperandParensRange(readSourceRange());
6896
0
  TL.setAttrRowOperand(Reader.readExpr());
6897
0
  TL.setAttrColumnOperand(Reader.readExpr());
6898
0
}
6899
6900
0
void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
6901
0
  TL.setLocalRangeBegin(readSourceLocation());
6902
0
  TL.setLParenLoc(readSourceLocation());
6903
0
  TL.setRParenLoc(readSourceLocation());
6904
0
  TL.setExceptionSpecRange(readSourceRange());
6905
0
  TL.setLocalRangeEnd(readSourceLocation());
6906
0
  for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
6907
0
    TL.setParam(i, Reader.readDeclAs<ParmVarDecl>());
6908
0
  }
6909
0
}
6910
6911
0
void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
6912
0
  VisitFunctionTypeLoc(TL);
6913
0
}
6914
6915
0
void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
6916
0
  VisitFunctionTypeLoc(TL);
6917
0
}
6918
6919
0
void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
6920
0
  TL.setNameLoc(readSourceLocation());
6921
0
}
6922
6923
0
void TypeLocReader::VisitUsingTypeLoc(UsingTypeLoc TL) {
6924
0
  TL.setNameLoc(readSourceLocation());
6925
0
}
6926
6927
0
void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
6928
0
  TL.setNameLoc(readSourceLocation());
6929
0
}
6930
6931
0
void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
6932
0
  TL.setTypeofLoc(readSourceLocation());
6933
0
  TL.setLParenLoc(readSourceLocation());
6934
0
  TL.setRParenLoc(readSourceLocation());
6935
0
}
6936
6937
0
void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
6938
0
  TL.setTypeofLoc(readSourceLocation());
6939
0
  TL.setLParenLoc(readSourceLocation());
6940
0
  TL.setRParenLoc(readSourceLocation());
6941
0
  TL.setUnmodifiedTInfo(GetTypeSourceInfo());
6942
0
}
6943
6944
0
void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
6945
0
  TL.setDecltypeLoc(readSourceLocation());
6946
0
  TL.setRParenLoc(readSourceLocation());
6947
0
}
6948
6949
0
void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
6950
0
  TL.setKWLoc(readSourceLocation());
6951
0
  TL.setLParenLoc(readSourceLocation());
6952
0
  TL.setRParenLoc(readSourceLocation());
6953
0
  TL.setUnderlyingTInfo(GetTypeSourceInfo());
6954
0
}
6955
6956
0
ConceptReference *ASTRecordReader::readConceptReference() {
6957
0
  auto NNS = readNestedNameSpecifierLoc();
6958
0
  auto TemplateKWLoc = readSourceLocation();
6959
0
  auto ConceptNameLoc = readDeclarationNameInfo();
6960
0
  auto FoundDecl = readDeclAs<NamedDecl>();
6961
0
  auto NamedConcept = readDeclAs<ConceptDecl>();
6962
0
  auto *CR = ConceptReference::Create(
6963
0
      getContext(), NNS, TemplateKWLoc, ConceptNameLoc, FoundDecl, NamedConcept,
6964
0
      (readBool() ? readASTTemplateArgumentListInfo() : nullptr));
6965
0
  return CR;
6966
0
}
6967
6968
0
void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
6969
0
  TL.setNameLoc(readSourceLocation());
6970
0
  if (Reader.readBool())
6971
0
    TL.setConceptReference(Reader.readConceptReference());
6972
0
  if (Reader.readBool())
6973
0
    TL.setRParenLoc(readSourceLocation());
6974
0
}
6975
6976
void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
6977
0
    DeducedTemplateSpecializationTypeLoc TL) {
6978
0
  TL.setTemplateNameLoc(readSourceLocation());
6979
0
}
6980
6981
0
void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
6982
0
  TL.setNameLoc(readSourceLocation());
6983
0
}
6984
6985
0
void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
6986
0
  TL.setNameLoc(readSourceLocation());
6987
0
}
6988
6989
0
void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
6990
0
  TL.setAttr(ReadAttr());
6991
0
}
6992
6993
0
void TypeLocReader::VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
6994
  // Nothing to do.
6995
0
}
6996
6997
0
void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
6998
0
  TL.setNameLoc(readSourceLocation());
6999
0
}
7000
7001
void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
7002
0
                                            SubstTemplateTypeParmTypeLoc TL) {
7003
0
  TL.setNameLoc(readSourceLocation());
7004
0
}
7005
7006
void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
7007
0
                                          SubstTemplateTypeParmPackTypeLoc TL) {
7008
0
  TL.setNameLoc(readSourceLocation());
7009
0
}
7010
7011
void TypeLocReader::VisitTemplateSpecializationTypeLoc(
7012
0
                                           TemplateSpecializationTypeLoc TL) {
7013
0
  TL.setTemplateKeywordLoc(readSourceLocation());
7014
0
  TL.setTemplateNameLoc(readSourceLocation());
7015
0
  TL.setLAngleLoc(readSourceLocation());
7016
0
  TL.setRAngleLoc(readSourceLocation());
7017
0
  for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
7018
0
    TL.setArgLocInfo(i,
7019
0
                     Reader.readTemplateArgumentLocInfo(
7020
0
                         TL.getTypePtr()->template_arguments()[i].getKind()));
7021
0
}
7022
7023
0
void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
7024
0
  TL.setLParenLoc(readSourceLocation());
7025
0
  TL.setRParenLoc(readSourceLocation());
7026
0
}
7027
7028
0
void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
7029
0
  TL.setElaboratedKeywordLoc(readSourceLocation());
7030
0
  TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7031
0
}
7032
7033
0
void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
7034
0
  TL.setNameLoc(readSourceLocation());
7035
0
}
7036
7037
0
void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
7038
0
  TL.setElaboratedKeywordLoc(readSourceLocation());
7039
0
  TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7040
0
  TL.setNameLoc(readSourceLocation());
7041
0
}
7042
7043
void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
7044
0
       DependentTemplateSpecializationTypeLoc TL) {
7045
0
  TL.setElaboratedKeywordLoc(readSourceLocation());
7046
0
  TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7047
0
  TL.setTemplateKeywordLoc(readSourceLocation());
7048
0
  TL.setTemplateNameLoc(readSourceLocation());
7049
0
  TL.setLAngleLoc(readSourceLocation());
7050
0
  TL.setRAngleLoc(readSourceLocation());
7051
0
  for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
7052
0
    TL.setArgLocInfo(I,
7053
0
                     Reader.readTemplateArgumentLocInfo(
7054
0
                         TL.getTypePtr()->template_arguments()[I].getKind()));
7055
0
}
7056
7057
0
void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
7058
0
  TL.setEllipsisLoc(readSourceLocation());
7059
0
}
7060
7061
0
void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
7062
0
  TL.setNameLoc(readSourceLocation());
7063
0
  TL.setNameEndLoc(readSourceLocation());
7064
0
}
7065
7066
0
void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
7067
0
  if (TL.getNumProtocols()) {
7068
0
    TL.setProtocolLAngleLoc(readSourceLocation());
7069
0
    TL.setProtocolRAngleLoc(readSourceLocation());
7070
0
  }
7071
0
  for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
7072
0
    TL.setProtocolLoc(i, readSourceLocation());
7073
0
}
7074
7075
0
void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
7076
0
  TL.setHasBaseTypeAsWritten(Reader.readBool());
7077
0
  TL.setTypeArgsLAngleLoc(readSourceLocation());
7078
0
  TL.setTypeArgsRAngleLoc(readSourceLocation());
7079
0
  for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
7080
0
    TL.setTypeArgTInfo(i, GetTypeSourceInfo());
7081
0
  TL.setProtocolLAngleLoc(readSourceLocation());
7082
0
  TL.setProtocolRAngleLoc(readSourceLocation());
7083
0
  for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
7084
0
    TL.setProtocolLoc(i, readSourceLocation());
7085
0
}
7086
7087
0
void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
7088
0
  TL.setStarLoc(readSourceLocation());
7089
0
}
7090
7091
0
void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
7092
0
  TL.setKWLoc(readSourceLocation());
7093
0
  TL.setLParenLoc(readSourceLocation());
7094
0
  TL.setRParenLoc(readSourceLocation());
7095
0
}
7096
7097
0
void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
7098
0
  TL.setKWLoc(readSourceLocation());
7099
0
}
7100
7101
0
void TypeLocReader::VisitBitIntTypeLoc(clang::BitIntTypeLoc TL) {
7102
0
  TL.setNameLoc(readSourceLocation());
7103
0
}
7104
void TypeLocReader::VisitDependentBitIntTypeLoc(
7105
0
    clang::DependentBitIntTypeLoc TL) {
7106
0
  TL.setNameLoc(readSourceLocation());
7107
0
}
7108
7109
0
void ASTRecordReader::readTypeLoc(TypeLoc TL, LocSeq *ParentSeq) {
7110
0
  LocSeq::State Seq(ParentSeq);
7111
0
  TypeLocReader TLR(*this, Seq);
7112
0
  for (; !TL.isNull(); TL = TL.getNextTypeLoc())
7113
0
    TLR.Visit(TL);
7114
0
}
7115
7116
0
TypeSourceInfo *ASTRecordReader::readTypeSourceInfo() {
7117
0
  QualType InfoTy = readType();
7118
0
  if (InfoTy.isNull())
7119
0
    return nullptr;
7120
7121
0
  TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
7122
0
  readTypeLoc(TInfo->getTypeLoc());
7123
0
  return TInfo;
7124
0
}
7125
7126
0
QualType ASTReader::GetType(TypeID ID) {
7127
0
  assert(ContextObj && "reading type with no AST context");
7128
0
  ASTContext &Context = *ContextObj;
7129
7130
0
  unsigned FastQuals = ID & Qualifiers::FastMask;
7131
0
  unsigned Index = ID >> Qualifiers::FastWidth;
7132
7133
0
  if (Index < NUM_PREDEF_TYPE_IDS) {
7134
0
    QualType T;
7135
0
    switch ((PredefinedTypeIDs)Index) {
7136
0
    case PREDEF_TYPE_LAST_ID:
7137
      // We should never use this one.
7138
0
      llvm_unreachable("Invalid predefined type");
7139
0
      break;
7140
0
    case PREDEF_TYPE_NULL_ID:
7141
0
      return QualType();
7142
0
    case PREDEF_TYPE_VOID_ID:
7143
0
      T = Context.VoidTy;
7144
0
      break;
7145
0
    case PREDEF_TYPE_BOOL_ID:
7146
0
      T = Context.BoolTy;
7147
0
      break;
7148
0
    case PREDEF_TYPE_CHAR_U_ID:
7149
0
    case PREDEF_TYPE_CHAR_S_ID:
7150
      // FIXME: Check that the signedness of CharTy is correct!
7151
0
      T = Context.CharTy;
7152
0
      break;
7153
0
    case PREDEF_TYPE_UCHAR_ID:
7154
0
      T = Context.UnsignedCharTy;
7155
0
      break;
7156
0
    case PREDEF_TYPE_USHORT_ID:
7157
0
      T = Context.UnsignedShortTy;
7158
0
      break;
7159
0
    case PREDEF_TYPE_UINT_ID:
7160
0
      T = Context.UnsignedIntTy;
7161
0
      break;
7162
0
    case PREDEF_TYPE_ULONG_ID:
7163
0
      T = Context.UnsignedLongTy;
7164
0
      break;
7165
0
    case PREDEF_TYPE_ULONGLONG_ID:
7166
0
      T = Context.UnsignedLongLongTy;
7167
0
      break;
7168
0
    case PREDEF_TYPE_UINT128_ID:
7169
0
      T = Context.UnsignedInt128Ty;
7170
0
      break;
7171
0
    case PREDEF_TYPE_SCHAR_ID:
7172
0
      T = Context.SignedCharTy;
7173
0
      break;
7174
0
    case PREDEF_TYPE_WCHAR_ID:
7175
0
      T = Context.WCharTy;
7176
0
      break;
7177
0
    case PREDEF_TYPE_SHORT_ID:
7178
0
      T = Context.ShortTy;
7179
0
      break;
7180
0
    case PREDEF_TYPE_INT_ID:
7181
0
      T = Context.IntTy;
7182
0
      break;
7183
0
    case PREDEF_TYPE_LONG_ID:
7184
0
      T = Context.LongTy;
7185
0
      break;
7186
0
    case PREDEF_TYPE_LONGLONG_ID:
7187
0
      T = Context.LongLongTy;
7188
0
      break;
7189
0
    case PREDEF_TYPE_INT128_ID:
7190
0
      T = Context.Int128Ty;
7191
0
      break;
7192
0
    case PREDEF_TYPE_BFLOAT16_ID:
7193
0
      T = Context.BFloat16Ty;
7194
0
      break;
7195
0
    case PREDEF_TYPE_HALF_ID:
7196
0
      T = Context.HalfTy;
7197
0
      break;
7198
0
    case PREDEF_TYPE_FLOAT_ID:
7199
0
      T = Context.FloatTy;
7200
0
      break;
7201
0
    case PREDEF_TYPE_DOUBLE_ID:
7202
0
      T = Context.DoubleTy;
7203
0
      break;
7204
0
    case PREDEF_TYPE_LONGDOUBLE_ID:
7205
0
      T = Context.LongDoubleTy;
7206
0
      break;
7207
0
    case PREDEF_TYPE_SHORT_ACCUM_ID:
7208
0
      T = Context.ShortAccumTy;
7209
0
      break;
7210
0
    case PREDEF_TYPE_ACCUM_ID:
7211
0
      T = Context.AccumTy;
7212
0
      break;
7213
0
    case PREDEF_TYPE_LONG_ACCUM_ID:
7214
0
      T = Context.LongAccumTy;
7215
0
      break;
7216
0
    case PREDEF_TYPE_USHORT_ACCUM_ID:
7217
0
      T = Context.UnsignedShortAccumTy;
7218
0
      break;
7219
0
    case PREDEF_TYPE_UACCUM_ID:
7220
0
      T = Context.UnsignedAccumTy;
7221
0
      break;
7222
0
    case PREDEF_TYPE_ULONG_ACCUM_ID:
7223
0
      T = Context.UnsignedLongAccumTy;
7224
0
      break;
7225
0
    case PREDEF_TYPE_SHORT_FRACT_ID:
7226
0
      T = Context.ShortFractTy;
7227
0
      break;
7228
0
    case PREDEF_TYPE_FRACT_ID:
7229
0
      T = Context.FractTy;
7230
0
      break;
7231
0
    case PREDEF_TYPE_LONG_FRACT_ID:
7232
0
      T = Context.LongFractTy;
7233
0
      break;
7234
0
    case PREDEF_TYPE_USHORT_FRACT_ID:
7235
0
      T = Context.UnsignedShortFractTy;
7236
0
      break;
7237
0
    case PREDEF_TYPE_UFRACT_ID:
7238
0
      T = Context.UnsignedFractTy;
7239
0
      break;
7240
0
    case PREDEF_TYPE_ULONG_FRACT_ID:
7241
0
      T = Context.UnsignedLongFractTy;
7242
0
      break;
7243
0
    case PREDEF_TYPE_SAT_SHORT_ACCUM_ID:
7244
0
      T = Context.SatShortAccumTy;
7245
0
      break;
7246
0
    case PREDEF_TYPE_SAT_ACCUM_ID:
7247
0
      T = Context.SatAccumTy;
7248
0
      break;
7249
0
    case PREDEF_TYPE_SAT_LONG_ACCUM_ID:
7250
0
      T = Context.SatLongAccumTy;
7251
0
      break;
7252
0
    case PREDEF_TYPE_SAT_USHORT_ACCUM_ID:
7253
0
      T = Context.SatUnsignedShortAccumTy;
7254
0
      break;
7255
0
    case PREDEF_TYPE_SAT_UACCUM_ID:
7256
0
      T = Context.SatUnsignedAccumTy;
7257
0
      break;
7258
0
    case PREDEF_TYPE_SAT_ULONG_ACCUM_ID:
7259
0
      T = Context.SatUnsignedLongAccumTy;
7260
0
      break;
7261
0
    case PREDEF_TYPE_SAT_SHORT_FRACT_ID:
7262
0
      T = Context.SatShortFractTy;
7263
0
      break;
7264
0
    case PREDEF_TYPE_SAT_FRACT_ID:
7265
0
      T = Context.SatFractTy;
7266
0
      break;
7267
0
    case PREDEF_TYPE_SAT_LONG_FRACT_ID:
7268
0
      T = Context.SatLongFractTy;
7269
0
      break;
7270
0
    case PREDEF_TYPE_SAT_USHORT_FRACT_ID:
7271
0
      T = Context.SatUnsignedShortFractTy;
7272
0
      break;
7273
0
    case PREDEF_TYPE_SAT_UFRACT_ID:
7274
0
      T = Context.SatUnsignedFractTy;
7275
0
      break;
7276
0
    case PREDEF_TYPE_SAT_ULONG_FRACT_ID:
7277
0
      T = Context.SatUnsignedLongFractTy;
7278
0
      break;
7279
0
    case PREDEF_TYPE_FLOAT16_ID:
7280
0
      T = Context.Float16Ty;
7281
0
      break;
7282
0
    case PREDEF_TYPE_FLOAT128_ID:
7283
0
      T = Context.Float128Ty;
7284
0
      break;
7285
0
    case PREDEF_TYPE_IBM128_ID:
7286
0
      T = Context.Ibm128Ty;
7287
0
      break;
7288
0
    case PREDEF_TYPE_OVERLOAD_ID:
7289
0
      T = Context.OverloadTy;
7290
0
      break;
7291
0
    case PREDEF_TYPE_BOUND_MEMBER:
7292
0
      T = Context.BoundMemberTy;
7293
0
      break;
7294
0
    case PREDEF_TYPE_PSEUDO_OBJECT:
7295
0
      T = Context.PseudoObjectTy;
7296
0
      break;
7297
0
    case PREDEF_TYPE_DEPENDENT_ID:
7298
0
      T = Context.DependentTy;
7299
0
      break;
7300
0
    case PREDEF_TYPE_UNKNOWN_ANY:
7301
0
      T = Context.UnknownAnyTy;
7302
0
      break;
7303
0
    case PREDEF_TYPE_NULLPTR_ID:
7304
0
      T = Context.NullPtrTy;
7305
0
      break;
7306
0
    case PREDEF_TYPE_CHAR8_ID:
7307
0
      T = Context.Char8Ty;
7308
0
      break;
7309
0
    case PREDEF_TYPE_CHAR16_ID:
7310
0
      T = Context.Char16Ty;
7311
0
      break;
7312
0
    case PREDEF_TYPE_CHAR32_ID:
7313
0
      T = Context.Char32Ty;
7314
0
      break;
7315
0
    case PREDEF_TYPE_OBJC_ID:
7316
0
      T = Context.ObjCBuiltinIdTy;
7317
0
      break;
7318
0
    case PREDEF_TYPE_OBJC_CLASS:
7319
0
      T = Context.ObjCBuiltinClassTy;
7320
0
      break;
7321
0
    case PREDEF_TYPE_OBJC_SEL:
7322
0
      T = Context.ObjCBuiltinSelTy;
7323
0
      break;
7324
0
#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7325
0
    case PREDEF_TYPE_##Id##_ID: \
7326
0
      T = Context.SingletonId; \
7327
0
      break;
7328
0
#include "clang/Basic/OpenCLImageTypes.def"
7329
0
#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
7330
0
    case PREDEF_TYPE_##Id##_ID: \
7331
0
      T = Context.Id##Ty; \
7332
0
      break;
7333
0
#include "clang/Basic/OpenCLExtensionTypes.def"
7334
0
    case PREDEF_TYPE_SAMPLER_ID:
7335
0
      T = Context.OCLSamplerTy;
7336
0
      break;
7337
0
    case PREDEF_TYPE_EVENT_ID:
7338
0
      T = Context.OCLEventTy;
7339
0
      break;
7340
0
    case PREDEF_TYPE_CLK_EVENT_ID:
7341
0
      T = Context.OCLClkEventTy;
7342
0
      break;
7343
0
    case PREDEF_TYPE_QUEUE_ID:
7344
0
      T = Context.OCLQueueTy;
7345
0
      break;
7346
0
    case PREDEF_TYPE_RESERVE_ID_ID:
7347
0
      T = Context.OCLReserveIDTy;
7348
0
      break;
7349
0
    case PREDEF_TYPE_AUTO_DEDUCT:
7350
0
      T = Context.getAutoDeductType();
7351
0
      break;
7352
0
    case PREDEF_TYPE_AUTO_RREF_DEDUCT:
7353
0
      T = Context.getAutoRRefDeductType();
7354
0
      break;
7355
0
    case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
7356
0
      T = Context.ARCUnbridgedCastTy;
7357
0
      break;
7358
0
    case PREDEF_TYPE_BUILTIN_FN:
7359
0
      T = Context.BuiltinFnTy;
7360
0
      break;
7361
0
    case PREDEF_TYPE_INCOMPLETE_MATRIX_IDX:
7362
0
      T = Context.IncompleteMatrixIdxTy;
7363
0
      break;
7364
0
    case PREDEF_TYPE_OMP_ARRAY_SECTION:
7365
0
      T = Context.OMPArraySectionTy;
7366
0
      break;
7367
0
    case PREDEF_TYPE_OMP_ARRAY_SHAPING:
7368
0
      T = Context.OMPArraySectionTy;
7369
0
      break;
7370
0
    case PREDEF_TYPE_OMP_ITERATOR:
7371
0
      T = Context.OMPIteratorTy;
7372
0
      break;
7373
0
#define SVE_TYPE(Name, Id, SingletonId) \
7374
0
    case PREDEF_TYPE_##Id##_ID: \
7375
0
      T = Context.SingletonId; \
7376
0
      break;
7377
0
#include "clang/Basic/AArch64SVEACLETypes.def"
7378
0
#define PPC_VECTOR_TYPE(Name, Id, Size) \
7379
0
    case PREDEF_TYPE_##Id##_ID: \
7380
0
      T = Context.Id##Ty; \
7381
0
      break;
7382
0
#include "clang/Basic/PPCTypes.def"
7383
0
#define RVV_TYPE(Name, Id, SingletonId) \
7384
0
    case PREDEF_TYPE_##Id##_ID: \
7385
0
      T = Context.SingletonId; \
7386
0
      break;
7387
0
#include "clang/Basic/RISCVVTypes.def"
7388
0
#define WASM_TYPE(Name, Id, SingletonId)                                       \
7389
0
  case PREDEF_TYPE_##Id##_ID:                                                  \
7390
0
    T = Context.SingletonId;                                                   \
7391
0
    break;
7392
0
#include "clang/Basic/WebAssemblyReferenceTypes.def"
7393
0
    }
7394
7395
0
    assert(!T.isNull() && "Unknown predefined type");
7396
0
    return T.withFastQualifiers(FastQuals);
7397
0
  }
7398
7399
0
  Index -= NUM_PREDEF_TYPE_IDS;
7400
0
  assert(Index < TypesLoaded.size() && "Type index out-of-range");
7401
0
  if (TypesLoaded[Index].isNull()) {
7402
0
    TypesLoaded[Index] = readTypeRecord(Index);
7403
0
    if (TypesLoaded[Index].isNull())
7404
0
      return QualType();
7405
7406
0
    TypesLoaded[Index]->setFromAST();
7407
0
    if (DeserializationListener)
7408
0
      DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
7409
0
                                        TypesLoaded[Index]);
7410
0
  }
7411
7412
0
  return TypesLoaded[Index].withFastQualifiers(FastQuals);
7413
0
}
7414
7415
0
QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
7416
0
  return GetType(getGlobalTypeID(F, LocalID));
7417
0
}
7418
7419
serialization::TypeID
7420
0
ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
7421
0
  unsigned FastQuals = LocalID & Qualifiers::FastMask;
7422
0
  unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
7423
7424
0
  if (LocalIndex < NUM_PREDEF_TYPE_IDS)
7425
0
    return LocalID;
7426
7427
0
  if (!F.ModuleOffsetMap.empty())
7428
0
    ReadModuleOffsetMap(F);
7429
7430
0
  ContinuousRangeMap<uint32_t, int, 2>::iterator I
7431
0
    = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
7432
0
  assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
7433
7434
0
  unsigned GlobalIndex = LocalIndex + I->second;
7435
0
  return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
7436
0
}
7437
7438
TemplateArgumentLocInfo
7439
0
ASTRecordReader::readTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind) {
7440
0
  switch (Kind) {
7441
0
  case TemplateArgument::Expression:
7442
0
    return readExpr();
7443
0
  case TemplateArgument::Type:
7444
0
    return readTypeSourceInfo();
7445
0
  case TemplateArgument::Template: {
7446
0
    NestedNameSpecifierLoc QualifierLoc =
7447
0
      readNestedNameSpecifierLoc();
7448
0
    SourceLocation TemplateNameLoc = readSourceLocation();
7449
0
    return TemplateArgumentLocInfo(getASTContext(), QualifierLoc,
7450
0
                                   TemplateNameLoc, SourceLocation());
7451
0
  }
7452
0
  case TemplateArgument::TemplateExpansion: {
7453
0
    NestedNameSpecifierLoc QualifierLoc = readNestedNameSpecifierLoc();
7454
0
    SourceLocation TemplateNameLoc = readSourceLocation();
7455
0
    SourceLocation EllipsisLoc = readSourceLocation();
7456
0
    return TemplateArgumentLocInfo(getASTContext(), QualifierLoc,
7457
0
                                   TemplateNameLoc, EllipsisLoc);
7458
0
  }
7459
0
  case TemplateArgument::Null:
7460
0
  case TemplateArgument::Integral:
7461
0
  case TemplateArgument::Declaration:
7462
0
  case TemplateArgument::NullPtr:
7463
0
  case TemplateArgument::Pack:
7464
    // FIXME: Is this right?
7465
0
    return TemplateArgumentLocInfo();
7466
0
  }
7467
0
  llvm_unreachable("unexpected template argument loc");
7468
0
}
7469
7470
0
TemplateArgumentLoc ASTRecordReader::readTemplateArgumentLoc() {
7471
0
  TemplateArgument Arg = readTemplateArgument();
7472
7473
0
  if (Arg.getKind() == TemplateArgument::Expression) {
7474
0
    if (readBool()) // bool InfoHasSameExpr.
7475
0
      return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
7476
0
  }
7477
0
  return TemplateArgumentLoc(Arg, readTemplateArgumentLocInfo(Arg.getKind()));
7478
0
}
7479
7480
void ASTRecordReader::readTemplateArgumentListInfo(
7481
0
    TemplateArgumentListInfo &Result) {
7482
0
  Result.setLAngleLoc(readSourceLocation());
7483
0
  Result.setRAngleLoc(readSourceLocation());
7484
0
  unsigned NumArgsAsWritten = readInt();
7485
0
  for (unsigned i = 0; i != NumArgsAsWritten; ++i)
7486
0
    Result.addArgument(readTemplateArgumentLoc());
7487
0
}
7488
7489
const ASTTemplateArgumentListInfo *
7490
0
ASTRecordReader::readASTTemplateArgumentListInfo() {
7491
0
  TemplateArgumentListInfo Result;
7492
0
  readTemplateArgumentListInfo(Result);
7493
0
  return ASTTemplateArgumentListInfo::Create(getContext(), Result);
7494
0
}
7495
7496
0
Decl *ASTReader::GetExternalDecl(uint32_t ID) {
7497
0
  return GetDecl(ID);
7498
0
}
7499
7500
0
void ASTReader::CompleteRedeclChain(const Decl *D) {
7501
0
  if (NumCurrentElementsDeserializing) {
7502
    // We arrange to not care about the complete redeclaration chain while we're
7503
    // deserializing. Just remember that the AST has marked this one as complete
7504
    // but that it's not actually complete yet, so we know we still need to
7505
    // complete it later.
7506
0
    PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
7507
0
    return;
7508
0
  }
7509
7510
0
  if (!D->getDeclContext()) {
7511
0
    assert(isa<TranslationUnitDecl>(D) && "Not a TU?");
7512
0
    return;
7513
0
  }
7514
7515
0
  const DeclContext *DC = D->getDeclContext()->getRedeclContext();
7516
7517
  // If this is a named declaration, complete it by looking it up
7518
  // within its context.
7519
  //
7520
  // FIXME: Merging a function definition should merge
7521
  // all mergeable entities within it.
7522
0
  if (isa<TranslationUnitDecl, NamespaceDecl, RecordDecl, EnumDecl>(DC)) {
7523
0
    if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
7524
0
      if (!getContext().getLangOpts().CPlusPlus &&
7525
0
          isa<TranslationUnitDecl>(DC)) {
7526
        // Outside of C++, we don't have a lookup table for the TU, so update
7527
        // the identifier instead. (For C++ modules, we don't store decls
7528
        // in the serialized identifier table, so we do the lookup in the TU.)
7529
0
        auto *II = Name.getAsIdentifierInfo();
7530
0
        assert(II && "non-identifier name in C?");
7531
0
        if (II->isOutOfDate())
7532
0
          updateOutOfDateIdentifier(*II);
7533
0
      } else
7534
0
        DC->lookup(Name);
7535
0
    } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
7536
      // Find all declarations of this kind from the relevant context.
7537
0
      for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
7538
0
        auto *DC = cast<DeclContext>(DCDecl);
7539
0
        SmallVector<Decl*, 8> Decls;
7540
0
        FindExternalLexicalDecls(
7541
0
            DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
7542
0
      }
7543
0
    }
7544
0
  }
7545
7546
0
  if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
7547
0
    CTSD->getSpecializedTemplate()->LoadLazySpecializations();
7548
0
  if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
7549
0
    VTSD->getSpecializedTemplate()->LoadLazySpecializations();
7550
0
  if (auto *FD = dyn_cast<FunctionDecl>(D)) {
7551
0
    if (auto *Template = FD->getPrimaryTemplate())
7552
0
      Template->LoadLazySpecializations();
7553
0
  }
7554
0
}
7555
7556
CXXCtorInitializer **
7557
0
ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
7558
0
  RecordLocation Loc = getLocalBitOffset(Offset);
7559
0
  BitstreamCursor &Cursor = Loc.F->DeclsCursor;
7560
0
  SavedStreamPosition SavedPosition(Cursor);
7561
0
  if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
7562
0
    Error(std::move(Err));
7563
0
    return nullptr;
7564
0
  }
7565
0
  ReadingKindTracker ReadingKind(Read_Decl, *this);
7566
0
  Deserializing D(this);
7567
7568
0
  Expected<unsigned> MaybeCode = Cursor.ReadCode();
7569
0
  if (!MaybeCode) {
7570
0
    Error(MaybeCode.takeError());
7571
0
    return nullptr;
7572
0
  }
7573
0
  unsigned Code = MaybeCode.get();
7574
7575
0
  ASTRecordReader Record(*this, *Loc.F);
7576
0
  Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
7577
0
  if (!MaybeRecCode) {
7578
0
    Error(MaybeRecCode.takeError());
7579
0
    return nullptr;
7580
0
  }
7581
0
  if (MaybeRecCode.get() != DECL_CXX_CTOR_INITIALIZERS) {
7582
0
    Error("malformed AST file: missing C++ ctor initializers");
7583
0
    return nullptr;
7584
0
  }
7585
7586
0
  return Record.readCXXCtorInitializers();
7587
0
}
7588
7589
0
CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
7590
0
  assert(ContextObj && "reading base specifiers with no AST context");
7591
0
  ASTContext &Context = *ContextObj;
7592
7593
0
  RecordLocation Loc = getLocalBitOffset(Offset);
7594
0
  BitstreamCursor &Cursor = Loc.F->DeclsCursor;
7595
0
  SavedStreamPosition SavedPosition(Cursor);
7596
0
  if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
7597
0
    Error(std::move(Err));
7598
0
    return nullptr;
7599
0
  }
7600
0
  ReadingKindTracker ReadingKind(Read_Decl, *this);
7601
0
  Deserializing D(this);
7602
7603
0
  Expected<unsigned> MaybeCode = Cursor.ReadCode();
7604
0
  if (!MaybeCode) {
7605
0
    Error(MaybeCode.takeError());
7606
0
    return nullptr;
7607
0
  }
7608
0
  unsigned Code = MaybeCode.get();
7609
7610
0
  ASTRecordReader Record(*this, *Loc.F);
7611
0
  Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
7612
0
  if (!MaybeRecCode) {
7613
0
    Error(MaybeCode.takeError());
7614
0
    return nullptr;
7615
0
  }
7616
0
  unsigned RecCode = MaybeRecCode.get();
7617
7618
0
  if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
7619
0
    Error("malformed AST file: missing C++ base specifiers");
7620
0
    return nullptr;
7621
0
  }
7622
7623
0
  unsigned NumBases = Record.readInt();
7624
0
  void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
7625
0
  CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
7626
0
  for (unsigned I = 0; I != NumBases; ++I)
7627
0
    Bases[I] = Record.readCXXBaseSpecifier();
7628
0
  return Bases;
7629
0
}
7630
7631
serialization::DeclID
7632
0
ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
7633
0
  if (LocalID < NUM_PREDEF_DECL_IDS)
7634
0
    return LocalID;
7635
7636
0
  if (!F.ModuleOffsetMap.empty())
7637
0
    ReadModuleOffsetMap(F);
7638
7639
0
  ContinuousRangeMap<uint32_t, int, 2>::iterator I
7640
0
    = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
7641
0
  assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
7642
7643
0
  return LocalID + I->second;
7644
0
}
7645
7646
bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
7647
0
                                   ModuleFile &M) const {
7648
  // Predefined decls aren't from any module.
7649
0
  if (ID < NUM_PREDEF_DECL_IDS)
7650
0
    return false;
7651
7652
0
  return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
7653
0
         ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
7654
0
}
7655
7656
0
ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
7657
0
  if (!D->isFromASTFile())
7658
0
    return nullptr;
7659
0
  GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
7660
0
  assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7661
0
  return I->second;
7662
0
}
7663
7664
0
SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
7665
0
  if (ID < NUM_PREDEF_DECL_IDS)
7666
0
    return SourceLocation();
7667
7668
0
  unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7669
7670
0
  if (Index > DeclsLoaded.size()) {
7671
0
    Error("declaration ID out-of-range for AST file");
7672
0
    return SourceLocation();
7673
0
  }
7674
7675
0
  if (Decl *D = DeclsLoaded[Index])
7676
0
    return D->getLocation();
7677
7678
0
  SourceLocation Loc;
7679
0
  DeclCursorForID(ID, Loc);
7680
0
  return Loc;
7681
0
}
7682
7683
0
static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
7684
0
  switch (ID) {
7685
0
  case PREDEF_DECL_NULL_ID:
7686
0
    return nullptr;
7687
7688
0
  case PREDEF_DECL_TRANSLATION_UNIT_ID:
7689
0
    return Context.getTranslationUnitDecl();
7690
7691
0
  case PREDEF_DECL_OBJC_ID_ID:
7692
0
    return Context.getObjCIdDecl();
7693
7694
0
  case PREDEF_DECL_OBJC_SEL_ID:
7695
0
    return Context.getObjCSelDecl();
7696
7697
0
  case PREDEF_DECL_OBJC_CLASS_ID:
7698
0
    return Context.getObjCClassDecl();
7699
7700
0
  case PREDEF_DECL_OBJC_PROTOCOL_ID:
7701
0
    return Context.getObjCProtocolDecl();
7702
7703
0
  case PREDEF_DECL_INT_128_ID:
7704
0
    return Context.getInt128Decl();
7705
7706
0
  case PREDEF_DECL_UNSIGNED_INT_128_ID:
7707
0
    return Context.getUInt128Decl();
7708
7709
0
  case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
7710
0
    return Context.getObjCInstanceTypeDecl();
7711
7712
0
  case PREDEF_DECL_BUILTIN_VA_LIST_ID:
7713
0
    return Context.getBuiltinVaListDecl();
7714
7715
0
  case PREDEF_DECL_VA_LIST_TAG:
7716
0
    return Context.getVaListTagDecl();
7717
7718
0
  case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
7719
0
    return Context.getBuiltinMSVaListDecl();
7720
7721
0
  case PREDEF_DECL_BUILTIN_MS_GUID_ID:
7722
0
    return Context.getMSGuidTagDecl();
7723
7724
0
  case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
7725
0
    return Context.getExternCContextDecl();
7726
7727
0
  case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
7728
0
    return Context.getMakeIntegerSeqDecl();
7729
7730
0
  case PREDEF_DECL_CF_CONSTANT_STRING_ID:
7731
0
    return Context.getCFConstantStringDecl();
7732
7733
0
  case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
7734
0
    return Context.getCFConstantStringTagDecl();
7735
7736
0
  case PREDEF_DECL_TYPE_PACK_ELEMENT_ID:
7737
0
    return Context.getTypePackElementDecl();
7738
0
  }
7739
0
  llvm_unreachable("PredefinedDeclIDs unknown enum value");
7740
0
}
7741
7742
0
Decl *ASTReader::GetExistingDecl(DeclID ID) {
7743
0
  assert(ContextObj && "reading decl with no AST context");
7744
0
  if (ID < NUM_PREDEF_DECL_IDS) {
7745
0
    Decl *D = getPredefinedDecl(*ContextObj, (PredefinedDeclIDs)ID);
7746
0
    if (D) {
7747
      // Track that we have merged the declaration with ID \p ID into the
7748
      // pre-existing predefined declaration \p D.
7749
0
      auto &Merged = KeyDecls[D->getCanonicalDecl()];
7750
0
      if (Merged.empty())
7751
0
        Merged.push_back(ID);
7752
0
    }
7753
0
    return D;
7754
0
  }
7755
7756
0
  unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7757
7758
0
  if (Index >= DeclsLoaded.size()) {
7759
0
    assert(0 && "declaration ID out-of-range for AST file");
7760
0
    Error("declaration ID out-of-range for AST file");
7761
0
    return nullptr;
7762
0
  }
7763
7764
0
  return DeclsLoaded[Index];
7765
0
}
7766
7767
0
Decl *ASTReader::GetDecl(DeclID ID) {
7768
0
  if (ID < NUM_PREDEF_DECL_IDS)
7769
0
    return GetExistingDecl(ID);
7770
7771
0
  unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7772
7773
0
  if (Index >= DeclsLoaded.size()) {
7774
0
    assert(0 && "declaration ID out-of-range for AST file");
7775
0
    Error("declaration ID out-of-range for AST file");
7776
0
    return nullptr;
7777
0
  }
7778
7779
0
  if (!DeclsLoaded[Index]) {
7780
0
    ReadDeclRecord(ID);
7781
0
    if (DeserializationListener)
7782
0
      DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
7783
0
  }
7784
7785
0
  return DeclsLoaded[Index];
7786
0
}
7787
7788
DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
7789
0
                                                  DeclID GlobalID) {
7790
0
  if (GlobalID < NUM_PREDEF_DECL_IDS)
7791
0
    return GlobalID;
7792
7793
0
  GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
7794
0
  assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7795
0
  ModuleFile *Owner = I->second;
7796
7797
0
  llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
7798
0
    = M.GlobalToLocalDeclIDs.find(Owner);
7799
0
  if (Pos == M.GlobalToLocalDeclIDs.end())
7800
0
    return 0;
7801
7802
0
  return GlobalID - Owner->BaseDeclID + Pos->second;
7803
0
}
7804
7805
serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
7806
                                            const RecordData &Record,
7807
0
                                            unsigned &Idx) {
7808
0
  if (Idx >= Record.size()) {
7809
0
    Error("Corrupted AST file");
7810
0
    return 0;
7811
0
  }
7812
7813
0
  return getGlobalDeclID(F, Record[Idx++]);
7814
0
}
7815
7816
/// Resolve the offset of a statement into a statement.
7817
///
7818
/// This operation will read a new statement from the external
7819
/// source each time it is called, and is meant to be used via a
7820
/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
7821
0
Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
7822
  // Switch case IDs are per Decl.
7823
0
  ClearSwitchCaseIDs();
7824
7825
  // Offset here is a global offset across the entire chain.
7826
0
  RecordLocation Loc = getLocalBitOffset(Offset);
7827
0
  if (llvm::Error Err = Loc.F->DeclsCursor.JumpToBit(Loc.Offset)) {
7828
0
    Error(std::move(Err));
7829
0
    return nullptr;
7830
0
  }
7831
0
  assert(NumCurrentElementsDeserializing == 0 &&
7832
0
         "should not be called while already deserializing");
7833
0
  Deserializing D(this);
7834
0
  return ReadStmtFromStream(*Loc.F);
7835
0
}
7836
7837
void ASTReader::FindExternalLexicalDecls(
7838
    const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
7839
0
    SmallVectorImpl<Decl *> &Decls) {
7840
0
  bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
7841
7842
0
  auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
7843
0
    assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
7844
0
    for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
7845
0
      auto K = (Decl::Kind)+LexicalDecls[I];
7846
0
      if (!IsKindWeWant(K))
7847
0
        continue;
7848
7849
0
      auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
7850
7851
      // Don't add predefined declarations to the lexical context more
7852
      // than once.
7853
0
      if (ID < NUM_PREDEF_DECL_IDS) {
7854
0
        if (PredefsVisited[ID])
7855
0
          continue;
7856
7857
0
        PredefsVisited[ID] = true;
7858
0
      }
7859
7860
0
      if (Decl *D = GetLocalDecl(*M, ID)) {
7861
0
        assert(D->getKind() == K && "wrong kind for lexical decl");
7862
0
        if (!DC->isDeclInLexicalTraversal(D))
7863
0
          Decls.push_back(D);
7864
0
      }
7865
0
    }
7866
0
  };
7867
7868
0
  if (isa<TranslationUnitDecl>(DC)) {
7869
0
    for (const auto &Lexical : TULexicalDecls)
7870
0
      Visit(Lexical.first, Lexical.second);
7871
0
  } else {
7872
0
    auto I = LexicalDecls.find(DC);
7873
0
    if (I != LexicalDecls.end())
7874
0
      Visit(I->second.first, I->second.second);
7875
0
  }
7876
7877
0
  ++NumLexicalDeclContextsRead;
7878
0
}
7879
7880
namespace {
7881
7882
class DeclIDComp {
7883
  ASTReader &Reader;
7884
  ModuleFile &Mod;
7885
7886
public:
7887
0
  DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
7888
7889
0
  bool operator()(LocalDeclID L, LocalDeclID R) const {
7890
0
    SourceLocation LHS = getLocation(L);
7891
0
    SourceLocation RHS = getLocation(R);
7892
0
    return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7893
0
  }
7894
7895
0
  bool operator()(SourceLocation LHS, LocalDeclID R) const {
7896
0
    SourceLocation RHS = getLocation(R);
7897
0
    return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7898
0
  }
7899
7900
0
  bool operator()(LocalDeclID L, SourceLocation RHS) const {
7901
0
    SourceLocation LHS = getLocation(L);
7902
0
    return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7903
0
  }
7904
7905
0
  SourceLocation getLocation(LocalDeclID ID) const {
7906
0
    return Reader.getSourceManager().getFileLoc(
7907
0
            Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
7908
0
  }
7909
};
7910
7911
} // namespace
7912
7913
void ASTReader::FindFileRegionDecls(FileID File,
7914
                                    unsigned Offset, unsigned Length,
7915
0
                                    SmallVectorImpl<Decl *> &Decls) {
7916
0
  SourceManager &SM = getSourceManager();
7917
7918
0
  llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
7919
0
  if (I == FileDeclIDs.end())
7920
0
    return;
7921
7922
0
  FileDeclsInfo &DInfo = I->second;
7923
0
  if (DInfo.Decls.empty())
7924
0
    return;
7925
7926
0
  SourceLocation
7927
0
    BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
7928
0
  SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
7929
7930
0
  DeclIDComp DIDComp(*this, *DInfo.Mod);
7931
0
  ArrayRef<serialization::LocalDeclID>::iterator BeginIt =
7932
0
      llvm::lower_bound(DInfo.Decls, BeginLoc, DIDComp);
7933
0
  if (BeginIt != DInfo.Decls.begin())
7934
0
    --BeginIt;
7935
7936
  // If we are pointing at a top-level decl inside an objc container, we need
7937
  // to backtrack until we find it otherwise we will fail to report that the
7938
  // region overlaps with an objc container.
7939
0
  while (BeginIt != DInfo.Decls.begin() &&
7940
0
         GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
7941
0
             ->isTopLevelDeclInObjCContainer())
7942
0
    --BeginIt;
7943
7944
0
  ArrayRef<serialization::LocalDeclID>::iterator EndIt =
7945
0
      llvm::upper_bound(DInfo.Decls, EndLoc, DIDComp);
7946
0
  if (EndIt != DInfo.Decls.end())
7947
0
    ++EndIt;
7948
7949
0
  for (ArrayRef<serialization::LocalDeclID>::iterator
7950
0
         DIt = BeginIt; DIt != EndIt; ++DIt)
7951
0
    Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
7952
0
}
7953
7954
bool
7955
ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
7956
0
                                          DeclarationName Name) {
7957
0
  assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
7958
0
         "DeclContext has no visible decls in storage");
7959
0
  if (!Name)
7960
0
    return false;
7961
7962
0
  auto It = Lookups.find(DC);
7963
0
  if (It == Lookups.end())
7964
0
    return false;
7965
7966
0
  Deserializing LookupResults(this);
7967
7968
  // Load the list of declarations.
7969
0
  SmallVector<NamedDecl *, 64> Decls;
7970
0
  llvm::SmallPtrSet<NamedDecl *, 8> Found;
7971
0
  for (DeclID ID : It->second.Table.find(Name)) {
7972
0
    NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
7973
0
    if (ND->getDeclName() == Name && Found.insert(ND).second)
7974
0
      Decls.push_back(ND);
7975
0
  }
7976
7977
0
  ++NumVisibleDeclContextsRead;
7978
0
  SetExternalVisibleDeclsForName(DC, Name, Decls);
7979
0
  return !Decls.empty();
7980
0
}
7981
7982
0
void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
7983
0
  if (!DC->hasExternalVisibleStorage())
7984
0
    return;
7985
7986
0
  auto It = Lookups.find(DC);
7987
0
  assert(It != Lookups.end() &&
7988
0
         "have external visible storage but no lookup tables");
7989
7990
0
  DeclsMap Decls;
7991
7992
0
  for (DeclID ID : It->second.Table.findAll()) {
7993
0
    NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
7994
0
    Decls[ND->getDeclName()].push_back(ND);
7995
0
  }
7996
7997
0
  ++NumVisibleDeclContextsRead;
7998
7999
0
  for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
8000
0
    SetExternalVisibleDeclsForName(DC, I->first, I->second);
8001
0
  }
8002
0
  const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
8003
0
}
8004
8005
const serialization::reader::DeclContextLookupTable *
8006
0
ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
8007
0
  auto I = Lookups.find(Primary);
8008
0
  return I == Lookups.end() ? nullptr : &I->second;
8009
0
}
8010
8011
/// Under non-PCH compilation the consumer receives the objc methods
8012
/// before receiving the implementation, and codegen depends on this.
8013
/// We simulate this by deserializing and passing to consumer the methods of the
8014
/// implementation before passing the deserialized implementation decl.
8015
static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
8016
0
                                       ASTConsumer *Consumer) {
8017
0
  assert(ImplD && Consumer);
8018
8019
0
  for (auto *I : ImplD->methods())
8020
0
    Consumer->HandleInterestingDecl(DeclGroupRef(I));
8021
8022
0
  Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
8023
0
}
8024
8025
0
void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
8026
0
  if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
8027
0
    PassObjCImplDeclToConsumer(ImplD, Consumer);
8028
0
  else
8029
0
    Consumer->HandleInterestingDecl(DeclGroupRef(D));
8030
0
}
8031
8032
0
void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
8033
0
  this->Consumer = Consumer;
8034
8035
0
  if (Consumer)
8036
0
    PassInterestingDeclsToConsumer();
8037
8038
0
  if (DeserializationListener)
8039
0
    DeserializationListener->ReaderInitialized(this);
8040
0
}
8041
8042
0
void ASTReader::PrintStats() {
8043
0
  std::fprintf(stderr, "*** AST File Statistics:\n");
8044
8045
0
  unsigned NumTypesLoaded =
8046
0
      TypesLoaded.size() - llvm::count(TypesLoaded.materialized(), QualType());
8047
0
  unsigned NumDeclsLoaded =
8048
0
      DeclsLoaded.size() -
8049
0
      llvm::count(DeclsLoaded.materialized(), (Decl *)nullptr);
8050
0
  unsigned NumIdentifiersLoaded =
8051
0
      IdentifiersLoaded.size() -
8052
0
      llvm::count(IdentifiersLoaded, (IdentifierInfo *)nullptr);
8053
0
  unsigned NumMacrosLoaded =
8054
0
      MacrosLoaded.size() - llvm::count(MacrosLoaded, (MacroInfo *)nullptr);
8055
0
  unsigned NumSelectorsLoaded =
8056
0
      SelectorsLoaded.size() - llvm::count(SelectorsLoaded, Selector());
8057
8058
0
  if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
8059
0
    std::fprintf(stderr, "  %u/%u source location entries read (%f%%)\n",
8060
0
                 NumSLocEntriesRead, TotalNumSLocEntries,
8061
0
                 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
8062
0
  if (!TypesLoaded.empty())
8063
0
    std::fprintf(stderr, "  %u/%u types read (%f%%)\n",
8064
0
                 NumTypesLoaded, (unsigned)TypesLoaded.size(),
8065
0
                 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
8066
0
  if (!DeclsLoaded.empty())
8067
0
    std::fprintf(stderr, "  %u/%u declarations read (%f%%)\n",
8068
0
                 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
8069
0
                 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
8070
0
  if (!IdentifiersLoaded.empty())
8071
0
    std::fprintf(stderr, "  %u/%u identifiers read (%f%%)\n",
8072
0
                 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
8073
0
                 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
8074
0
  if (!MacrosLoaded.empty())
8075
0
    std::fprintf(stderr, "  %u/%u macros read (%f%%)\n",
8076
0
                 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
8077
0
                 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
8078
0
  if (!SelectorsLoaded.empty())
8079
0
    std::fprintf(stderr, "  %u/%u selectors read (%f%%)\n",
8080
0
                 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
8081
0
                 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
8082
0
  if (TotalNumStatements)
8083
0
    std::fprintf(stderr, "  %u/%u statements read (%f%%)\n",
8084
0
                 NumStatementsRead, TotalNumStatements,
8085
0
                 ((float)NumStatementsRead/TotalNumStatements * 100));
8086
0
  if (TotalNumMacros)
8087
0
    std::fprintf(stderr, "  %u/%u macros read (%f%%)\n",
8088
0
                 NumMacrosRead, TotalNumMacros,
8089
0
                 ((float)NumMacrosRead/TotalNumMacros * 100));
8090
0
  if (TotalLexicalDeclContexts)
8091
0
    std::fprintf(stderr, "  %u/%u lexical declcontexts read (%f%%)\n",
8092
0
                 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
8093
0
                 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
8094
0
                  * 100));
8095
0
  if (TotalVisibleDeclContexts)
8096
0
    std::fprintf(stderr, "  %u/%u visible declcontexts read (%f%%)\n",
8097
0
                 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
8098
0
                 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
8099
0
                  * 100));
8100
0
  if (TotalNumMethodPoolEntries)
8101
0
    std::fprintf(stderr, "  %u/%u method pool entries read (%f%%)\n",
8102
0
                 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
8103
0
                 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
8104
0
                  * 100));
8105
0
  if (NumMethodPoolLookups)
8106
0
    std::fprintf(stderr, "  %u/%u method pool lookups succeeded (%f%%)\n",
8107
0
                 NumMethodPoolHits, NumMethodPoolLookups,
8108
0
                 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
8109
0
  if (NumMethodPoolTableLookups)
8110
0
    std::fprintf(stderr, "  %u/%u method pool table lookups succeeded (%f%%)\n",
8111
0
                 NumMethodPoolTableHits, NumMethodPoolTableLookups,
8112
0
                 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
8113
0
                  * 100.0));
8114
0
  if (NumIdentifierLookupHits)
8115
0
    std::fprintf(stderr,
8116
0
                 "  %u / %u identifier table lookups succeeded (%f%%)\n",
8117
0
                 NumIdentifierLookupHits, NumIdentifierLookups,
8118
0
                 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
8119
8120
0
  if (GlobalIndex) {
8121
0
    std::fprintf(stderr, "\n");
8122
0
    GlobalIndex->printStats();
8123
0
  }
8124
8125
0
  std::fprintf(stderr, "\n");
8126
0
  dump();
8127
0
  std::fprintf(stderr, "\n");
8128
0
}
8129
8130
template<typename Key, typename ModuleFile, unsigned InitialCapacity>
8131
LLVM_DUMP_METHOD static void
8132
dumpModuleIDMap(StringRef Name,
8133
                const ContinuousRangeMap<Key, ModuleFile *,
8134
0
                                         InitialCapacity> &Map) {
8135
0
  if (Map.begin() == Map.end())
8136
0
    return;
8137
8138
0
  using MapType = ContinuousRangeMap<Key, ModuleFile *, InitialCapacity>;
8139
8140
0
  llvm::errs() << Name << ":\n";
8141
0
  for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
8142
0
       I != IEnd; ++I) {
8143
0
    llvm::errs() << "  " << I->first << " -> " << I->second->FileName
8144
0
      << "\n";
8145
0
  }
8146
0
}
Unexecuted instantiation: ASTReader.cpp:void dumpModuleIDMap<unsigned long, clang::serialization::ModuleFile, 4u>(llvm::StringRef, clang::ContinuousRangeMap<unsigned long, clang::serialization::ModuleFile*, 4u> const&)
Unexecuted instantiation: ASTReader.cpp:void dumpModuleIDMap<unsigned int, clang::serialization::ModuleFile, 64u>(llvm::StringRef, clang::ContinuousRangeMap<unsigned int, clang::serialization::ModuleFile*, 64u> const&)
Unexecuted instantiation: ASTReader.cpp:void dumpModuleIDMap<unsigned int, clang::serialization::ModuleFile, 4u>(llvm::StringRef, clang::ContinuousRangeMap<unsigned int, clang::serialization::ModuleFile*, 4u> const&)
8147
8148
0
LLVM_DUMP_METHOD void ASTReader::dump() {
8149
0
  llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
8150
0
  dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
8151
0
  dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
8152
0
  dumpModuleIDMap("Global type map", GlobalTypeMap);
8153
0
  dumpModuleIDMap("Global declaration map", GlobalDeclMap);
8154
0
  dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
8155
0
  dumpModuleIDMap("Global macro map", GlobalMacroMap);
8156
0
  dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
8157
0
  dumpModuleIDMap("Global selector map", GlobalSelectorMap);
8158
0
  dumpModuleIDMap("Global preprocessed entity map",
8159
0
                  GlobalPreprocessedEntityMap);
8160
8161
0
  llvm::errs() << "\n*** PCH/Modules Loaded:";
8162
0
  for (ModuleFile &M : ModuleMgr)
8163
0
    M.dump();
8164
0
}
8165
8166
/// Return the amount of memory used by memory buffers, breaking down
8167
/// by heap-backed versus mmap'ed memory.
8168
0
void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
8169
0
  for (ModuleFile &I : ModuleMgr) {
8170
0
    if (llvm::MemoryBuffer *buf = I.Buffer) {
8171
0
      size_t bytes = buf->getBufferSize();
8172
0
      switch (buf->getBufferKind()) {
8173
0
        case llvm::MemoryBuffer::MemoryBuffer_Malloc:
8174
0
          sizes.malloc_bytes += bytes;
8175
0
          break;
8176
0
        case llvm::MemoryBuffer::MemoryBuffer_MMap:
8177
0
          sizes.mmap_bytes += bytes;
8178
0
          break;
8179
0
      }
8180
0
    }
8181
0
  }
8182
0
}
8183
8184
0
void ASTReader::InitializeSema(Sema &S) {
8185
0
  SemaObj = &S;
8186
0
  S.addExternalSource(this);
8187
8188
  // Makes sure any declarations that were deserialized "too early"
8189
  // still get added to the identifier's declaration chains.
8190
0
  for (uint64_t ID : PreloadedDeclIDs) {
8191
0
    NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
8192
0
    pushExternalDeclIntoScope(D, D->getDeclName());
8193
0
  }
8194
0
  PreloadedDeclIDs.clear();
8195
8196
  // FIXME: What happens if these are changed by a module import?
8197
0
  if (!FPPragmaOptions.empty()) {
8198
0
    assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
8199
0
    FPOptionsOverride NewOverrides =
8200
0
        FPOptionsOverride::getFromOpaqueInt(FPPragmaOptions[0]);
8201
0
    SemaObj->CurFPFeatures =
8202
0
        NewOverrides.applyOverrides(SemaObj->getLangOpts());
8203
0
  }
8204
8205
0
  SemaObj->OpenCLFeatures = OpenCLExtensions;
8206
8207
0
  UpdateSema();
8208
0
}
8209
8210
0
void ASTReader::UpdateSema() {
8211
0
  assert(SemaObj && "no Sema to update");
8212
8213
  // Load the offsets of the declarations that Sema references.
8214
  // They will be lazily deserialized when needed.
8215
0
  if (!SemaDeclRefs.empty()) {
8216
0
    assert(SemaDeclRefs.size() % 3 == 0);
8217
0
    for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
8218
0
      if (!SemaObj->StdNamespace)
8219
0
        SemaObj->StdNamespace = SemaDeclRefs[I];
8220
0
      if (!SemaObj->StdBadAlloc)
8221
0
        SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
8222
0
      if (!SemaObj->StdAlignValT)
8223
0
        SemaObj->StdAlignValT = SemaDeclRefs[I+2];
8224
0
    }
8225
0
    SemaDeclRefs.clear();
8226
0
  }
8227
8228
  // Update the state of pragmas. Use the same API as if we had encountered the
8229
  // pragma in the source.
8230
0
  if(OptimizeOffPragmaLocation.isValid())
8231
0
    SemaObj->ActOnPragmaOptimize(/* On = */ false, OptimizeOffPragmaLocation);
8232
0
  if (PragmaMSStructState != -1)
8233
0
    SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
8234
0
  if (PointersToMembersPragmaLocation.isValid()) {
8235
0
    SemaObj->ActOnPragmaMSPointersToMembers(
8236
0
        (LangOptions::PragmaMSPointersToMembersKind)
8237
0
            PragmaMSPointersToMembersState,
8238
0
        PointersToMembersPragmaLocation);
8239
0
  }
8240
0
  SemaObj->ForceCUDAHostDeviceDepth = ForceCUDAHostDeviceDepth;
8241
8242
0
  if (PragmaAlignPackCurrentValue) {
8243
    // The bottom of the stack might have a default value. It must be adjusted
8244
    // to the current value to ensure that the packing state is preserved after
8245
    // popping entries that were included/imported from a PCH/module.
8246
0
    bool DropFirst = false;
8247
0
    if (!PragmaAlignPackStack.empty() &&
8248
0
        PragmaAlignPackStack.front().Location.isInvalid()) {
8249
0
      assert(PragmaAlignPackStack.front().Value ==
8250
0
                 SemaObj->AlignPackStack.DefaultValue &&
8251
0
             "Expected a default alignment value");
8252
0
      SemaObj->AlignPackStack.Stack.emplace_back(
8253
0
          PragmaAlignPackStack.front().SlotLabel,
8254
0
          SemaObj->AlignPackStack.CurrentValue,
8255
0
          SemaObj->AlignPackStack.CurrentPragmaLocation,
8256
0
          PragmaAlignPackStack.front().PushLocation);
8257
0
      DropFirst = true;
8258
0
    }
8259
0
    for (const auto &Entry :
8260
0
         llvm::ArrayRef(PragmaAlignPackStack).drop_front(DropFirst ? 1 : 0)) {
8261
0
      SemaObj->AlignPackStack.Stack.emplace_back(
8262
0
          Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation);
8263
0
    }
8264
0
    if (PragmaAlignPackCurrentLocation.isInvalid()) {
8265
0
      assert(*PragmaAlignPackCurrentValue ==
8266
0
                 SemaObj->AlignPackStack.DefaultValue &&
8267
0
             "Expected a default align and pack value");
8268
      // Keep the current values.
8269
0
    } else {
8270
0
      SemaObj->AlignPackStack.CurrentValue = *PragmaAlignPackCurrentValue;
8271
0
      SemaObj->AlignPackStack.CurrentPragmaLocation =
8272
0
          PragmaAlignPackCurrentLocation;
8273
0
    }
8274
0
  }
8275
0
  if (FpPragmaCurrentValue) {
8276
    // The bottom of the stack might have a default value. It must be adjusted
8277
    // to the current value to ensure that fp-pragma state is preserved after
8278
    // popping entries that were included/imported from a PCH/module.
8279
0
    bool DropFirst = false;
8280
0
    if (!FpPragmaStack.empty() && FpPragmaStack.front().Location.isInvalid()) {
8281
0
      assert(FpPragmaStack.front().Value ==
8282
0
                 SemaObj->FpPragmaStack.DefaultValue &&
8283
0
             "Expected a default pragma float_control value");
8284
0
      SemaObj->FpPragmaStack.Stack.emplace_back(
8285
0
          FpPragmaStack.front().SlotLabel, SemaObj->FpPragmaStack.CurrentValue,
8286
0
          SemaObj->FpPragmaStack.CurrentPragmaLocation,
8287
0
          FpPragmaStack.front().PushLocation);
8288
0
      DropFirst = true;
8289
0
    }
8290
0
    for (const auto &Entry :
8291
0
         llvm::ArrayRef(FpPragmaStack).drop_front(DropFirst ? 1 : 0))
8292
0
      SemaObj->FpPragmaStack.Stack.emplace_back(
8293
0
          Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation);
8294
0
    if (FpPragmaCurrentLocation.isInvalid()) {
8295
0
      assert(*FpPragmaCurrentValue == SemaObj->FpPragmaStack.DefaultValue &&
8296
0
             "Expected a default pragma float_control value");
8297
      // Keep the current values.
8298
0
    } else {
8299
0
      SemaObj->FpPragmaStack.CurrentValue = *FpPragmaCurrentValue;
8300
0
      SemaObj->FpPragmaStack.CurrentPragmaLocation = FpPragmaCurrentLocation;
8301
0
    }
8302
0
  }
8303
8304
  // For non-modular AST files, restore visiblity of modules.
8305
0
  for (auto &Import : PendingImportedModulesSema) {
8306
0
    if (Import.ImportLoc.isInvalid())
8307
0
      continue;
8308
0
    if (Module *Imported = getSubmodule(Import.ID)) {
8309
0
      SemaObj->makeModuleVisible(Imported, Import.ImportLoc);
8310
0
    }
8311
0
  }
8312
0
  PendingImportedModulesSema.clear();
8313
0
}
8314
8315
0
IdentifierInfo *ASTReader::get(StringRef Name) {
8316
  // Note that we are loading an identifier.
8317
0
  Deserializing AnIdentifier(this);
8318
8319
0
  IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
8320
0
                                  NumIdentifierLookups,
8321
0
                                  NumIdentifierLookupHits);
8322
8323
  // We don't need to do identifier table lookups in C++ modules (we preload
8324
  // all interesting declarations, and don't need to use the scope for name
8325
  // lookups). Perform the lookup in PCH files, though, since we don't build
8326
  // a complete initial identifier table if we're carrying on from a PCH.
8327
0
  if (PP.getLangOpts().CPlusPlus) {
8328
0
    for (auto *F : ModuleMgr.pch_modules())
8329
0
      if (Visitor(*F))
8330
0
        break;
8331
0
  } else {
8332
    // If there is a global index, look there first to determine which modules
8333
    // provably do not have any results for this identifier.
8334
0
    GlobalModuleIndex::HitSet Hits;
8335
0
    GlobalModuleIndex::HitSet *HitsPtr = nullptr;
8336
0
    if (!loadGlobalIndex()) {
8337
0
      if (GlobalIndex->lookupIdentifier(Name, Hits)) {
8338
0
        HitsPtr = &Hits;
8339
0
      }
8340
0
    }
8341
8342
0
    ModuleMgr.visit(Visitor, HitsPtr);
8343
0
  }
8344
8345
0
  IdentifierInfo *II = Visitor.getIdentifierInfo();
8346
0
  markIdentifierUpToDate(II);
8347
0
  return II;
8348
0
}
8349
8350
namespace clang {
8351
8352
  /// An identifier-lookup iterator that enumerates all of the
8353
  /// identifiers stored within a set of AST files.
8354
  class ASTIdentifierIterator : public IdentifierIterator {
8355
    /// The AST reader whose identifiers are being enumerated.
8356
    const ASTReader &Reader;
8357
8358
    /// The current index into the chain of AST files stored in
8359
    /// the AST reader.
8360
    unsigned Index;
8361
8362
    /// The current position within the identifier lookup table
8363
    /// of the current AST file.
8364
    ASTIdentifierLookupTable::key_iterator Current;
8365
8366
    /// The end position within the identifier lookup table of
8367
    /// the current AST file.
8368
    ASTIdentifierLookupTable::key_iterator End;
8369
8370
    /// Whether to skip any modules in the ASTReader.
8371
    bool SkipModules;
8372
8373
  public:
8374
    explicit ASTIdentifierIterator(const ASTReader &Reader,
8375
                                   bool SkipModules = false);
8376
8377
    StringRef Next() override;
8378
  };
8379
8380
} // namespace clang
8381
8382
ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader,
8383
                                             bool SkipModules)
8384
0
    : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
8385
0
}
8386
8387
0
StringRef ASTIdentifierIterator::Next() {
8388
0
  while (Current == End) {
8389
    // If we have exhausted all of our AST files, we're done.
8390
0
    if (Index == 0)
8391
0
      return StringRef();
8392
8393
0
    --Index;
8394
0
    ModuleFile &F = Reader.ModuleMgr[Index];
8395
0
    if (SkipModules && F.isModule())
8396
0
      continue;
8397
8398
0
    ASTIdentifierLookupTable *IdTable =
8399
0
        (ASTIdentifierLookupTable *)F.IdentifierLookupTable;
8400
0
    Current = IdTable->key_begin();
8401
0
    End = IdTable->key_end();
8402
0
  }
8403
8404
  // We have any identifiers remaining in the current AST file; return
8405
  // the next one.
8406
0
  StringRef Result = *Current;
8407
0
  ++Current;
8408
0
  return Result;
8409
0
}
8410
8411
namespace {
8412
8413
/// A utility for appending two IdentifierIterators.
8414
class ChainedIdentifierIterator : public IdentifierIterator {
8415
  std::unique_ptr<IdentifierIterator> Current;
8416
  std::unique_ptr<IdentifierIterator> Queued;
8417
8418
public:
8419
  ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
8420
                            std::unique_ptr<IdentifierIterator> Second)
8421
0
      : Current(std::move(First)), Queued(std::move(Second)) {}
8422
8423
0
  StringRef Next() override {
8424
0
    if (!Current)
8425
0
      return StringRef();
8426
8427
0
    StringRef result = Current->Next();
8428
0
    if (!result.empty())
8429
0
      return result;
8430
8431
    // Try the queued iterator, which may itself be empty.
8432
0
    Current.reset();
8433
0
    std::swap(Current, Queued);
8434
0
    return Next();
8435
0
  }
8436
};
8437
8438
} // namespace
8439
8440
0
IdentifierIterator *ASTReader::getIdentifiers() {
8441
0
  if (!loadGlobalIndex()) {
8442
0
    std::unique_ptr<IdentifierIterator> ReaderIter(
8443
0
        new ASTIdentifierIterator(*this, /*SkipModules=*/true));
8444
0
    std::unique_ptr<IdentifierIterator> ModulesIter(
8445
0
        GlobalIndex->createIdentifierIterator());
8446
0
    return new ChainedIdentifierIterator(std::move(ReaderIter),
8447
0
                                         std::move(ModulesIter));
8448
0
  }
8449
8450
0
  return new ASTIdentifierIterator(*this);
8451
0
}
8452
8453
namespace clang {
8454
namespace serialization {
8455
8456
  class ReadMethodPoolVisitor {
8457
    ASTReader &Reader;
8458
    Selector Sel;
8459
    unsigned PriorGeneration;
8460
    unsigned InstanceBits = 0;
8461
    unsigned FactoryBits = 0;
8462
    bool InstanceHasMoreThanOneDecl = false;
8463
    bool FactoryHasMoreThanOneDecl = false;
8464
    SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
8465
    SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
8466
8467
  public:
8468
    ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
8469
                          unsigned PriorGeneration)
8470
0
        : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) {}
8471
8472
0
    bool operator()(ModuleFile &M) {
8473
0
      if (!M.SelectorLookupTable)
8474
0
        return false;
8475
8476
      // If we've already searched this module file, skip it now.
8477
0
      if (M.Generation <= PriorGeneration)
8478
0
        return true;
8479
8480
0
      ++Reader.NumMethodPoolTableLookups;
8481
0
      ASTSelectorLookupTable *PoolTable
8482
0
        = (ASTSelectorLookupTable*)M.SelectorLookupTable;
8483
0
      ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
8484
0
      if (Pos == PoolTable->end())
8485
0
        return false;
8486
8487
0
      ++Reader.NumMethodPoolTableHits;
8488
0
      ++Reader.NumSelectorsRead;
8489
      // FIXME: Not quite happy with the statistics here. We probably should
8490
      // disable this tracking when called via LoadSelector.
8491
      // Also, should entries without methods count as misses?
8492
0
      ++Reader.NumMethodPoolEntriesRead;
8493
0
      ASTSelectorLookupTrait::data_type Data = *Pos;
8494
0
      if (Reader.DeserializationListener)
8495
0
        Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
8496
8497
      // Append methods in the reverse order, so that later we can process them
8498
      // in the order they appear in the source code by iterating through
8499
      // the vector in the reverse order.
8500
0
      InstanceMethods.append(Data.Instance.rbegin(), Data.Instance.rend());
8501
0
      FactoryMethods.append(Data.Factory.rbegin(), Data.Factory.rend());
8502
0
      InstanceBits = Data.InstanceBits;
8503
0
      FactoryBits = Data.FactoryBits;
8504
0
      InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
8505
0
      FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
8506
0
      return false;
8507
0
    }
8508
8509
    /// Retrieve the instance methods found by this visitor.
8510
0
    ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
8511
0
      return InstanceMethods;
8512
0
    }
8513
8514
    /// Retrieve the instance methods found by this visitor.
8515
0
    ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
8516
0
      return FactoryMethods;
8517
0
    }
8518
8519
0
    unsigned getInstanceBits() const { return InstanceBits; }
8520
0
    unsigned getFactoryBits() const { return FactoryBits; }
8521
8522
0
    bool instanceHasMoreThanOneDecl() const {
8523
0
      return InstanceHasMoreThanOneDecl;
8524
0
    }
8525
8526
0
    bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
8527
  };
8528
8529
} // namespace serialization
8530
} // namespace clang
8531
8532
/// Add the given set of methods to the method list.
8533
static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
8534
0
                             ObjCMethodList &List) {
8535
0
  for (ObjCMethodDecl *M : llvm::reverse(Methods))
8536
0
    S.addMethodToGlobalList(&List, M);
8537
0
}
8538
8539
0
void ASTReader::ReadMethodPool(Selector Sel) {
8540
  // Get the selector generation and update it to the current generation.
8541
0
  unsigned &Generation = SelectorGeneration[Sel];
8542
0
  unsigned PriorGeneration = Generation;
8543
0
  Generation = getGeneration();
8544
0
  SelectorOutOfDate[Sel] = false;
8545
8546
  // Search for methods defined with this selector.
8547
0
  ++NumMethodPoolLookups;
8548
0
  ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
8549
0
  ModuleMgr.visit(Visitor);
8550
8551
0
  if (Visitor.getInstanceMethods().empty() &&
8552
0
      Visitor.getFactoryMethods().empty())
8553
0
    return;
8554
8555
0
  ++NumMethodPoolHits;
8556
8557
0
  if (!getSema())
8558
0
    return;
8559
8560
0
  Sema &S = *getSema();
8561
0
  Sema::GlobalMethodPool::iterator Pos =
8562
0
      S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethodPool::Lists()))
8563
0
          .first;
8564
8565
0
  Pos->second.first.setBits(Visitor.getInstanceBits());
8566
0
  Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
8567
0
  Pos->second.second.setBits(Visitor.getFactoryBits());
8568
0
  Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
8569
8570
  // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
8571
  // when building a module we keep every method individually and may need to
8572
  // update hasMoreThanOneDecl as we add the methods.
8573
0
  addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
8574
0
  addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
8575
0
}
8576
8577
0
void ASTReader::updateOutOfDateSelector(Selector Sel) {
8578
0
  if (SelectorOutOfDate[Sel])
8579
0
    ReadMethodPool(Sel);
8580
0
}
8581
8582
void ASTReader::ReadKnownNamespaces(
8583
0
                          SmallVectorImpl<NamespaceDecl *> &Namespaces) {
8584
0
  Namespaces.clear();
8585
8586
0
  for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
8587
0
    if (NamespaceDecl *Namespace
8588
0
                = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
8589
0
      Namespaces.push_back(Namespace);
8590
0
  }
8591
0
}
8592
8593
void ASTReader::ReadUndefinedButUsed(
8594
0
    llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
8595
0
  for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
8596
0
    NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
8597
0
    SourceLocation Loc =
8598
0
        SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
8599
0
    Undefined.insert(std::make_pair(D, Loc));
8600
0
  }
8601
0
}
8602
8603
void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
8604
    FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
8605
0
                                                     Exprs) {
8606
0
  for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
8607
0
    FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
8608
0
    uint64_t Count = DelayedDeleteExprs[Idx++];
8609
0
    for (uint64_t C = 0; C < Count; ++C) {
8610
0
      SourceLocation DeleteLoc =
8611
0
          SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
8612
0
      const bool IsArrayForm = DelayedDeleteExprs[Idx++];
8613
0
      Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
8614
0
    }
8615
0
  }
8616
0
}
8617
8618
void ASTReader::ReadTentativeDefinitions(
8619
0
                  SmallVectorImpl<VarDecl *> &TentativeDefs) {
8620
0
  for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
8621
0
    VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
8622
0
    if (Var)
8623
0
      TentativeDefs.push_back(Var);
8624
0
  }
8625
0
  TentativeDefinitions.clear();
8626
0
}
8627
8628
void ASTReader::ReadUnusedFileScopedDecls(
8629
0
                               SmallVectorImpl<const DeclaratorDecl *> &Decls) {
8630
0
  for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
8631
0
    DeclaratorDecl *D
8632
0
      = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
8633
0
    if (D)
8634
0
      Decls.push_back(D);
8635
0
  }
8636
0
  UnusedFileScopedDecls.clear();
8637
0
}
8638
8639
void ASTReader::ReadDelegatingConstructors(
8640
0
                                 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
8641
0
  for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
8642
0
    CXXConstructorDecl *D
8643
0
      = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
8644
0
    if (D)
8645
0
      Decls.push_back(D);
8646
0
  }
8647
0
  DelegatingCtorDecls.clear();
8648
0
}
8649
8650
0
void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
8651
0
  for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
8652
0
    TypedefNameDecl *D
8653
0
      = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
8654
0
    if (D)
8655
0
      Decls.push_back(D);
8656
0
  }
8657
0
  ExtVectorDecls.clear();
8658
0
}
8659
8660
void ASTReader::ReadUnusedLocalTypedefNameCandidates(
8661
0
    llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
8662
0
  for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
8663
0
       ++I) {
8664
0
    TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
8665
0
        GetDecl(UnusedLocalTypedefNameCandidates[I]));
8666
0
    if (D)
8667
0
      Decls.insert(D);
8668
0
  }
8669
0
  UnusedLocalTypedefNameCandidates.clear();
8670
0
}
8671
8672
void ASTReader::ReadDeclsToCheckForDeferredDiags(
8673
0
    llvm::SmallSetVector<Decl *, 4> &Decls) {
8674
0
  for (auto I : DeclsToCheckForDeferredDiags) {
8675
0
    auto *D = dyn_cast_or_null<Decl>(GetDecl(I));
8676
0
    if (D)
8677
0
      Decls.insert(D);
8678
0
  }
8679
0
  DeclsToCheckForDeferredDiags.clear();
8680
0
}
8681
8682
void ASTReader::ReadReferencedSelectors(
8683
0
       SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) {
8684
0
  if (ReferencedSelectorsData.empty())
8685
0
    return;
8686
8687
  // If there are @selector references added them to its pool. This is for
8688
  // implementation of -Wselector.
8689
0
  unsigned int DataSize = ReferencedSelectorsData.size()-1;
8690
0
  unsigned I = 0;
8691
0
  while (I < DataSize) {
8692
0
    Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
8693
0
    SourceLocation SelLoc
8694
0
      = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
8695
0
    Sels.push_back(std::make_pair(Sel, SelLoc));
8696
0
  }
8697
0
  ReferencedSelectorsData.clear();
8698
0
}
8699
8700
void ASTReader::ReadWeakUndeclaredIdentifiers(
8701
0
       SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WeakIDs) {
8702
0
  if (WeakUndeclaredIdentifiers.empty())
8703
0
    return;
8704
8705
0
  for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
8706
0
    IdentifierInfo *WeakId
8707
0
      = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
8708
0
    IdentifierInfo *AliasId
8709
0
      = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
8710
0
    SourceLocation Loc =
8711
0
        SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
8712
0
    WeakInfo WI(AliasId, Loc);
8713
0
    WeakIDs.push_back(std::make_pair(WeakId, WI));
8714
0
  }
8715
0
  WeakUndeclaredIdentifiers.clear();
8716
0
}
8717
8718
0
void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
8719
0
  for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
8720
0
    ExternalVTableUse VT;
8721
0
    VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
8722
0
    VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
8723
0
    VT.DefinitionRequired = VTableUses[Idx++];
8724
0
    VTables.push_back(VT);
8725
0
  }
8726
8727
0
  VTableUses.clear();
8728
0
}
8729
8730
void ASTReader::ReadPendingInstantiations(
8731
0
       SmallVectorImpl<std::pair<ValueDecl *, SourceLocation>> &Pending) {
8732
0
  for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
8733
0
    ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
8734
0
    SourceLocation Loc
8735
0
      = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
8736
8737
0
    Pending.push_back(std::make_pair(D, Loc));
8738
0
  }
8739
0
  PendingInstantiations.clear();
8740
0
}
8741
8742
void ASTReader::ReadLateParsedTemplates(
8743
    llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
8744
0
        &LPTMap) {
8745
0
  for (auto &LPT : LateParsedTemplates) {
8746
0
    ModuleFile *FMod = LPT.first;
8747
0
    RecordDataImpl &LateParsed = LPT.second;
8748
0
    for (unsigned Idx = 0, N = LateParsed.size(); Idx < N;
8749
0
         /* In loop */) {
8750
0
      FunctionDecl *FD =
8751
0
          cast<FunctionDecl>(GetLocalDecl(*FMod, LateParsed[Idx++]));
8752
8753
0
      auto LT = std::make_unique<LateParsedTemplate>();
8754
0
      LT->D = GetLocalDecl(*FMod, LateParsed[Idx++]);
8755
0
      LT->FPO = FPOptions::getFromOpaqueInt(LateParsed[Idx++]);
8756
8757
0
      ModuleFile *F = getOwningModuleFile(LT->D);
8758
0
      assert(F && "No module");
8759
8760
0
      unsigned TokN = LateParsed[Idx++];
8761
0
      LT->Toks.reserve(TokN);
8762
0
      for (unsigned T = 0; T < TokN; ++T)
8763
0
        LT->Toks.push_back(ReadToken(*F, LateParsed, Idx));
8764
8765
0
      LPTMap.insert(std::make_pair(FD, std::move(LT)));
8766
0
    }
8767
0
  }
8768
8769
0
  LateParsedTemplates.clear();
8770
0
}
8771
8772
0
void ASTReader::AssignedLambdaNumbering(const CXXRecordDecl *Lambda) {
8773
0
  if (Lambda->getLambdaContextDecl()) {
8774
    // Keep track of this lambda so it can be merged with another lambda that
8775
    // is loaded later.
8776
0
    LambdaDeclarationsForMerging.insert(
8777
0
        {{Lambda->getLambdaContextDecl()->getCanonicalDecl(),
8778
0
          Lambda->getLambdaIndexInContext()},
8779
0
         const_cast<CXXRecordDecl *>(Lambda)});
8780
0
  }
8781
0
}
8782
8783
0
void ASTReader::LoadSelector(Selector Sel) {
8784
  // It would be complicated to avoid reading the methods anyway. So don't.
8785
0
  ReadMethodPool(Sel);
8786
0
}
8787
8788
0
void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
8789
0
  assert(ID && "Non-zero identifier ID required");
8790
0
  assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
8791
0
  IdentifiersLoaded[ID - 1] = II;
8792
0
  if (DeserializationListener)
8793
0
    DeserializationListener->IdentifierRead(ID, II);
8794
0
}
8795
8796
/// Set the globally-visible declarations associated with the given
8797
/// identifier.
8798
///
8799
/// If the AST reader is currently in a state where the given declaration IDs
8800
/// cannot safely be resolved, they are queued until it is safe to resolve
8801
/// them.
8802
///
8803
/// \param II an IdentifierInfo that refers to one or more globally-visible
8804
/// declarations.
8805
///
8806
/// \param DeclIDs the set of declaration IDs with the name @p II that are
8807
/// visible at global scope.
8808
///
8809
/// \param Decls if non-null, this vector will be populated with the set of
8810
/// deserialized declarations. These declarations will not be pushed into
8811
/// scope.
8812
void
8813
ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
8814
                              const SmallVectorImpl<uint32_t> &DeclIDs,
8815
0
                                   SmallVectorImpl<Decl *> *Decls) {
8816
0
  if (NumCurrentElementsDeserializing && !Decls) {
8817
0
    PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
8818
0
    return;
8819
0
  }
8820
8821
0
  for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
8822
0
    if (!SemaObj) {
8823
      // Queue this declaration so that it will be added to the
8824
      // translation unit scope and identifier's declaration chain
8825
      // once a Sema object is known.
8826
0
      PreloadedDeclIDs.push_back(DeclIDs[I]);
8827
0
      continue;
8828
0
    }
8829
8830
0
    NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
8831
8832
    // If we're simply supposed to record the declarations, do so now.
8833
0
    if (Decls) {
8834
0
      Decls->push_back(D);
8835
0
      continue;
8836
0
    }
8837
8838
    // Introduce this declaration into the translation-unit scope
8839
    // and add it to the declaration chain for this identifier, so
8840
    // that (unqualified) name lookup will find it.
8841
0
    pushExternalDeclIntoScope(D, II);
8842
0
  }
8843
0
}
8844
8845
0
IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
8846
0
  if (ID == 0)
8847
0
    return nullptr;
8848
8849
0
  if (IdentifiersLoaded.empty()) {
8850
0
    Error("no identifier table in AST file");
8851
0
    return nullptr;
8852
0
  }
8853
8854
0
  ID -= 1;
8855
0
  if (!IdentifiersLoaded[ID]) {
8856
0
    GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
8857
0
    assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
8858
0
    ModuleFile *M = I->second;
8859
0
    unsigned Index = ID - M->BaseIdentifierID;
8860
0
    const unsigned char *Data =
8861
0
        M->IdentifierTableData + M->IdentifierOffsets[Index];
8862
8863
0
    ASTIdentifierLookupTrait Trait(*this, *M);
8864
0
    auto KeyDataLen = Trait.ReadKeyDataLength(Data);
8865
0
    auto Key = Trait.ReadKey(Data, KeyDataLen.first);
8866
0
    auto &II = PP.getIdentifierTable().get(Key);
8867
0
    IdentifiersLoaded[ID] = &II;
8868
0
    markIdentifierFromAST(*this,  II);
8869
0
    if (DeserializationListener)
8870
0
      DeserializationListener->IdentifierRead(ID + 1, &II);
8871
0
  }
8872
8873
0
  return IdentifiersLoaded[ID];
8874
0
}
8875
8876
0
IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
8877
0
  return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
8878
0
}
8879
8880
0
IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
8881
0
  if (LocalID < NUM_PREDEF_IDENT_IDS)
8882
0
    return LocalID;
8883
8884
0
  if (!M.ModuleOffsetMap.empty())
8885
0
    ReadModuleOffsetMap(M);
8886
8887
0
  ContinuousRangeMap<uint32_t, int, 2>::iterator I
8888
0
    = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
8889
0
  assert(I != M.IdentifierRemap.end()
8890
0
         && "Invalid index into identifier index remap");
8891
8892
0
  return LocalID + I->second;
8893
0
}
8894
8895
0
MacroInfo *ASTReader::getMacro(MacroID ID) {
8896
0
  if (ID == 0)
8897
0
    return nullptr;
8898
8899
0
  if (MacrosLoaded.empty()) {
8900
0
    Error("no macro table in AST file");
8901
0
    return nullptr;
8902
0
  }
8903
8904
0
  ID -= NUM_PREDEF_MACRO_IDS;
8905
0
  if (!MacrosLoaded[ID]) {
8906
0
    GlobalMacroMapType::iterator I
8907
0
      = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
8908
0
    assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
8909
0
    ModuleFile *M = I->second;
8910
0
    unsigned Index = ID - M->BaseMacroID;
8911
0
    MacrosLoaded[ID] =
8912
0
        ReadMacroRecord(*M, M->MacroOffsetsBase + M->MacroOffsets[Index]);
8913
8914
0
    if (DeserializationListener)
8915
0
      DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
8916
0
                                         MacrosLoaded[ID]);
8917
0
  }
8918
8919
0
  return MacrosLoaded[ID];
8920
0
}
8921
8922
0
MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
8923
0
  if (LocalID < NUM_PREDEF_MACRO_IDS)
8924
0
    return LocalID;
8925
8926
0
  if (!M.ModuleOffsetMap.empty())
8927
0
    ReadModuleOffsetMap(M);
8928
8929
0
  ContinuousRangeMap<uint32_t, int, 2>::iterator I
8930
0
    = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
8931
0
  assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
8932
8933
0
  return LocalID + I->second;
8934
0
}
8935
8936
serialization::SubmoduleID
8937
0
ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
8938
0
  if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
8939
0
    return LocalID;
8940
8941
0
  if (!M.ModuleOffsetMap.empty())
8942
0
    ReadModuleOffsetMap(M);
8943
8944
0
  ContinuousRangeMap<uint32_t, int, 2>::iterator I
8945
0
    = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
8946
0
  assert(I != M.SubmoduleRemap.end()
8947
0
         && "Invalid index into submodule index remap");
8948
8949
0
  return LocalID + I->second;
8950
0
}
8951
8952
0
Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
8953
0
  if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
8954
0
    assert(GlobalID == 0 && "Unhandled global submodule ID");
8955
0
    return nullptr;
8956
0
  }
8957
8958
0
  if (GlobalID > SubmodulesLoaded.size()) {
8959
0
    Error("submodule ID out of range in AST file");
8960
0
    return nullptr;
8961
0
  }
8962
8963
0
  return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
8964
0
}
8965
8966
0
Module *ASTReader::getModule(unsigned ID) {
8967
0
  return getSubmodule(ID);
8968
0
}
8969
8970
0
ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &M, unsigned ID) {
8971
0
  if (ID & 1) {
8972
    // It's a module, look it up by submodule ID.
8973
0
    auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(M, ID >> 1));
8974
0
    return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
8975
0
  } else {
8976
    // It's a prefix (preamble, PCH, ...). Look it up by index.
8977
0
    unsigned IndexFromEnd = ID >> 1;
8978
0
    assert(IndexFromEnd && "got reference to unknown module file");
8979
0
    return getModuleManager().pch_modules().end()[-IndexFromEnd];
8980
0
  }
8981
0
}
8982
8983
0
unsigned ASTReader::getModuleFileID(ModuleFile *M) {
8984
0
  if (!M)
8985
0
    return 1;
8986
8987
  // For a file representing a module, use the submodule ID of the top-level
8988
  // module as the file ID. For any other kind of file, the number of such
8989
  // files loaded beforehand will be the same on reload.
8990
  // FIXME: Is this true even if we have an explicit module file and a PCH?
8991
0
  if (M->isModule())
8992
0
    return ((M->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
8993
8994
0
  auto PCHModules = getModuleManager().pch_modules();
8995
0
  auto I = llvm::find(PCHModules, M);
8996
0
  assert(I != PCHModules.end() && "emitting reference to unknown file");
8997
0
  return (I - PCHModules.end()) << 1;
8998
0
}
8999
9000
0
std::optional<ASTSourceDescriptor> ASTReader::getSourceDescriptor(unsigned ID) {
9001
0
  if (Module *M = getSubmodule(ID))
9002
0
    return ASTSourceDescriptor(*M);
9003
9004
  // If there is only a single PCH, return it instead.
9005
  // Chained PCH are not supported.
9006
0
  const auto &PCHChain = ModuleMgr.pch_modules();
9007
0
  if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {
9008
0
    ModuleFile &MF = ModuleMgr.getPrimaryModule();
9009
0
    StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
9010
0
    StringRef FileName = llvm::sys::path::filename(MF.FileName);
9011
0
    return ASTSourceDescriptor(ModuleName,
9012
0
                               llvm::sys::path::parent_path(MF.FileName),
9013
0
                               FileName, MF.Signature);
9014
0
  }
9015
0
  return std::nullopt;
9016
0
}
9017
9018
0
ExternalASTSource::ExtKind ASTReader::hasExternalDefinitions(const Decl *FD) {
9019
0
  auto I = DefinitionSource.find(FD);
9020
0
  if (I == DefinitionSource.end())
9021
0
    return EK_ReplyHazy;
9022
0
  return I->second ? EK_Never : EK_Always;
9023
0
}
9024
9025
0
Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
9026
0
  return DecodeSelector(getGlobalSelectorID(M, LocalID));
9027
0
}
9028
9029
0
Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
9030
0
  if (ID == 0)
9031
0
    return Selector();
9032
9033
0
  if (ID > SelectorsLoaded.size()) {
9034
0
    Error("selector ID out of range in AST file");
9035
0
    return Selector();
9036
0
  }
9037
9038
0
  if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
9039
    // Load this selector from the selector table.
9040
0
    GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
9041
0
    assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
9042
0
    ModuleFile &M = *I->second;
9043
0
    ASTSelectorLookupTrait Trait(*this, M);
9044
0
    unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
9045
0
    SelectorsLoaded[ID - 1] =
9046
0
      Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
9047
0
    if (DeserializationListener)
9048
0
      DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
9049
0
  }
9050
9051
0
  return SelectorsLoaded[ID - 1];
9052
0
}
9053
9054
0
Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
9055
0
  return DecodeSelector(ID);
9056
0
}
9057
9058
0
uint32_t ASTReader::GetNumExternalSelectors() {
9059
  // ID 0 (the null selector) is considered an external selector.
9060
0
  return getTotalNumSelectors() + 1;
9061
0
}
9062
9063
serialization::SelectorID
9064
0
ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
9065
0
  if (LocalID < NUM_PREDEF_SELECTOR_IDS)
9066
0
    return LocalID;
9067
9068
0
  if (!M.ModuleOffsetMap.empty())
9069
0
    ReadModuleOffsetMap(M);
9070
9071
0
  ContinuousRangeMap<uint32_t, int, 2>::iterator I
9072
0
    = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
9073
0
  assert(I != M.SelectorRemap.end()
9074
0
         && "Invalid index into selector index remap");
9075
9076
0
  return LocalID + I->second;
9077
0
}
9078
9079
DeclarationNameLoc
9080
0
ASTRecordReader::readDeclarationNameLoc(DeclarationName Name) {
9081
0
  switch (Name.getNameKind()) {
9082
0
  case DeclarationName::CXXConstructorName:
9083
0
  case DeclarationName::CXXDestructorName:
9084
0
  case DeclarationName::CXXConversionFunctionName:
9085
0
    return DeclarationNameLoc::makeNamedTypeLoc(readTypeSourceInfo());
9086
9087
0
  case DeclarationName::CXXOperatorName:
9088
0
    return DeclarationNameLoc::makeCXXOperatorNameLoc(readSourceRange());
9089
9090
0
  case DeclarationName::CXXLiteralOperatorName:
9091
0
    return DeclarationNameLoc::makeCXXLiteralOperatorNameLoc(
9092
0
        readSourceLocation());
9093
9094
0
  case DeclarationName::Identifier:
9095
0
  case DeclarationName::ObjCZeroArgSelector:
9096
0
  case DeclarationName::ObjCOneArgSelector:
9097
0
  case DeclarationName::ObjCMultiArgSelector:
9098
0
  case DeclarationName::CXXUsingDirective:
9099
0
  case DeclarationName::CXXDeductionGuideName:
9100
0
    break;
9101
0
  }
9102
0
  return DeclarationNameLoc();
9103
0
}
9104
9105
0
DeclarationNameInfo ASTRecordReader::readDeclarationNameInfo() {
9106
0
  DeclarationNameInfo NameInfo;
9107
0
  NameInfo.setName(readDeclarationName());
9108
0
  NameInfo.setLoc(readSourceLocation());
9109
0
  NameInfo.setInfo(readDeclarationNameLoc(NameInfo.getName()));
9110
0
  return NameInfo;
9111
0
}
9112
9113
0
void ASTRecordReader::readQualifierInfo(QualifierInfo &Info) {
9114
0
  Info.QualifierLoc = readNestedNameSpecifierLoc();
9115
0
  unsigned NumTPLists = readInt();
9116
0
  Info.NumTemplParamLists = NumTPLists;
9117
0
  if (NumTPLists) {
9118
0
    Info.TemplParamLists =
9119
0
        new (getContext()) TemplateParameterList *[NumTPLists];
9120
0
    for (unsigned i = 0; i != NumTPLists; ++i)
9121
0
      Info.TemplParamLists[i] = readTemplateParameterList();
9122
0
  }
9123
0
}
9124
9125
TemplateParameterList *
9126
0
ASTRecordReader::readTemplateParameterList() {
9127
0
  SourceLocation TemplateLoc = readSourceLocation();
9128
0
  SourceLocation LAngleLoc = readSourceLocation();
9129
0
  SourceLocation RAngleLoc = readSourceLocation();
9130
9131
0
  unsigned NumParams = readInt();
9132
0
  SmallVector<NamedDecl *, 16> Params;
9133
0
  Params.reserve(NumParams);
9134
0
  while (NumParams--)
9135
0
    Params.push_back(readDeclAs<NamedDecl>());
9136
9137
0
  bool HasRequiresClause = readBool();
9138
0
  Expr *RequiresClause = HasRequiresClause ? readExpr() : nullptr;
9139
9140
0
  TemplateParameterList *TemplateParams = TemplateParameterList::Create(
9141
0
      getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, RequiresClause);
9142
0
  return TemplateParams;
9143
0
}
9144
9145
void ASTRecordReader::readTemplateArgumentList(
9146
                        SmallVectorImpl<TemplateArgument> &TemplArgs,
9147
0
                        bool Canonicalize) {
9148
0
  unsigned NumTemplateArgs = readInt();
9149
0
  TemplArgs.reserve(NumTemplateArgs);
9150
0
  while (NumTemplateArgs--)
9151
0
    TemplArgs.push_back(readTemplateArgument(Canonicalize));
9152
0
}
9153
9154
/// Read a UnresolvedSet structure.
9155
0
void ASTRecordReader::readUnresolvedSet(LazyASTUnresolvedSet &Set) {
9156
0
  unsigned NumDecls = readInt();
9157
0
  Set.reserve(getContext(), NumDecls);
9158
0
  while (NumDecls--) {
9159
0
    DeclID ID = readDeclID();
9160
0
    AccessSpecifier AS = (AccessSpecifier) readInt();
9161
0
    Set.addLazyDecl(getContext(), ID, AS);
9162
0
  }
9163
0
}
9164
9165
CXXBaseSpecifier
9166
0
ASTRecordReader::readCXXBaseSpecifier() {
9167
0
  bool isVirtual = readBool();
9168
0
  bool isBaseOfClass = readBool();
9169
0
  AccessSpecifier AS = static_cast<AccessSpecifier>(readInt());
9170
0
  bool inheritConstructors = readBool();
9171
0
  TypeSourceInfo *TInfo = readTypeSourceInfo();
9172
0
  SourceRange Range = readSourceRange();
9173
0
  SourceLocation EllipsisLoc = readSourceLocation();
9174
0
  CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
9175
0
                          EllipsisLoc);
9176
0
  Result.setInheritConstructors(inheritConstructors);
9177
0
  return Result;
9178
0
}
9179
9180
CXXCtorInitializer **
9181
0
ASTRecordReader::readCXXCtorInitializers() {
9182
0
  ASTContext &Context = getContext();
9183
0
  unsigned NumInitializers = readInt();
9184
0
  assert(NumInitializers && "wrote ctor initializers but have no inits");
9185
0
  auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
9186
0
  for (unsigned i = 0; i != NumInitializers; ++i) {
9187
0
    TypeSourceInfo *TInfo = nullptr;
9188
0
    bool IsBaseVirtual = false;
9189
0
    FieldDecl *Member = nullptr;
9190
0
    IndirectFieldDecl *IndirectMember = nullptr;
9191
9192
0
    CtorInitializerType Type = (CtorInitializerType) readInt();
9193
0
    switch (Type) {
9194
0
    case CTOR_INITIALIZER_BASE:
9195
0
      TInfo = readTypeSourceInfo();
9196
0
      IsBaseVirtual = readBool();
9197
0
      break;
9198
9199
0
    case CTOR_INITIALIZER_DELEGATING:
9200
0
      TInfo = readTypeSourceInfo();
9201
0
      break;
9202
9203
0
     case CTOR_INITIALIZER_MEMBER:
9204
0
      Member = readDeclAs<FieldDecl>();
9205
0
      break;
9206
9207
0
     case CTOR_INITIALIZER_INDIRECT_MEMBER:
9208
0
      IndirectMember = readDeclAs<IndirectFieldDecl>();
9209
0
      break;
9210
0
    }
9211
9212
0
    SourceLocation MemberOrEllipsisLoc = readSourceLocation();
9213
0
    Expr *Init = readExpr();
9214
0
    SourceLocation LParenLoc = readSourceLocation();
9215
0
    SourceLocation RParenLoc = readSourceLocation();
9216
9217
0
    CXXCtorInitializer *BOMInit;
9218
0
    if (Type == CTOR_INITIALIZER_BASE)
9219
0
      BOMInit = new (Context)
9220
0
          CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
9221
0
                             RParenLoc, MemberOrEllipsisLoc);
9222
0
    else if (Type == CTOR_INITIALIZER_DELEGATING)
9223
0
      BOMInit = new (Context)
9224
0
          CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
9225
0
    else if (Member)
9226
0
      BOMInit = new (Context)
9227
0
          CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
9228
0
                             Init, RParenLoc);
9229
0
    else
9230
0
      BOMInit = new (Context)
9231
0
          CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
9232
0
                             LParenLoc, Init, RParenLoc);
9233
9234
0
    if (/*IsWritten*/readBool()) {
9235
0
      unsigned SourceOrder = readInt();
9236
0
      BOMInit->setSourceOrder(SourceOrder);
9237
0
    }
9238
9239
0
    CtorInitializers[i] = BOMInit;
9240
0
  }
9241
9242
0
  return CtorInitializers;
9243
0
}
9244
9245
NestedNameSpecifierLoc
9246
0
ASTRecordReader::readNestedNameSpecifierLoc() {
9247
0
  ASTContext &Context = getContext();
9248
0
  unsigned N = readInt();
9249
0
  NestedNameSpecifierLocBuilder Builder;
9250
0
  for (unsigned I = 0; I != N; ++I) {
9251
0
    auto Kind = readNestedNameSpecifierKind();
9252
0
    switch (Kind) {
9253
0
    case NestedNameSpecifier::Identifier: {
9254
0
      IdentifierInfo *II = readIdentifier();
9255
0
      SourceRange Range = readSourceRange();
9256
0
      Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
9257
0
      break;
9258
0
    }
9259
9260
0
    case NestedNameSpecifier::Namespace: {
9261
0
      NamespaceDecl *NS = readDeclAs<NamespaceDecl>();
9262
0
      SourceRange Range = readSourceRange();
9263
0
      Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
9264
0
      break;
9265
0
    }
9266
9267
0
    case NestedNameSpecifier::NamespaceAlias: {
9268
0
      NamespaceAliasDecl *Alias = readDeclAs<NamespaceAliasDecl>();
9269
0
      SourceRange Range = readSourceRange();
9270
0
      Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
9271
0
      break;
9272
0
    }
9273
9274
0
    case NestedNameSpecifier::TypeSpec:
9275
0
    case NestedNameSpecifier::TypeSpecWithTemplate: {
9276
0
      bool Template = readBool();
9277
0
      TypeSourceInfo *T = readTypeSourceInfo();
9278
0
      if (!T)
9279
0
        return NestedNameSpecifierLoc();
9280
0
      SourceLocation ColonColonLoc = readSourceLocation();
9281
9282
      // FIXME: 'template' keyword location not saved anywhere, so we fake it.
9283
0
      Builder.Extend(Context,
9284
0
                     Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
9285
0
                     T->getTypeLoc(), ColonColonLoc);
9286
0
      break;
9287
0
    }
9288
9289
0
    case NestedNameSpecifier::Global: {
9290
0
      SourceLocation ColonColonLoc = readSourceLocation();
9291
0
      Builder.MakeGlobal(Context, ColonColonLoc);
9292
0
      break;
9293
0
    }
9294
9295
0
    case NestedNameSpecifier::Super: {
9296
0
      CXXRecordDecl *RD = readDeclAs<CXXRecordDecl>();
9297
0
      SourceRange Range = readSourceRange();
9298
0
      Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
9299
0
      break;
9300
0
    }
9301
0
    }
9302
0
  }
9303
9304
0
  return Builder.getWithLocInContext(Context);
9305
0
}
9306
9307
SourceRange ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
9308
0
                                       unsigned &Idx, LocSeq *Seq) {
9309
0
  SourceLocation beg = ReadSourceLocation(F, Record, Idx, Seq);
9310
0
  SourceLocation end = ReadSourceLocation(F, Record, Idx, Seq);
9311
0
  return SourceRange(beg, end);
9312
0
}
9313
9314
/// Read a floating-point value
9315
0
llvm::APFloat ASTRecordReader::readAPFloat(const llvm::fltSemantics &Sem) {
9316
0
  return llvm::APFloat(Sem, readAPInt());
9317
0
}
9318
9319
// Read a string
9320
0
std::string ASTReader::ReadString(const RecordDataImpl &Record, unsigned &Idx) {
9321
0
  unsigned Len = Record[Idx++];
9322
0
  std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
9323
0
  Idx += Len;
9324
0
  return Result;
9325
0
}
9326
9327
std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
9328
0
                                unsigned &Idx) {
9329
0
  std::string Filename = ReadString(Record, Idx);
9330
0
  ResolveImportedPath(F, Filename);
9331
0
  return Filename;
9332
0
}
9333
9334
std::string ASTReader::ReadPath(StringRef BaseDirectory,
9335
0
                                const RecordData &Record, unsigned &Idx) {
9336
0
  std::string Filename = ReadString(Record, Idx);
9337
0
  if (!BaseDirectory.empty())
9338
0
    ResolveImportedPath(Filename, BaseDirectory);
9339
0
  return Filename;
9340
0
}
9341
9342
VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
9343
0
                                         unsigned &Idx) {
9344
0
  unsigned Major = Record[Idx++];
9345
0
  unsigned Minor = Record[Idx++];
9346
0
  unsigned Subminor = Record[Idx++];
9347
0
  if (Minor == 0)
9348
0
    return VersionTuple(Major);
9349
0
  if (Subminor == 0)
9350
0
    return VersionTuple(Major, Minor - 1);
9351
0
  return VersionTuple(Major, Minor - 1, Subminor - 1);
9352
0
}
9353
9354
CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
9355
                                          const RecordData &Record,
9356
0
                                          unsigned &Idx) {
9357
0
  CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
9358
0
  return CXXTemporary::Create(getContext(), Decl);
9359
0
}
9360
9361
0
DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
9362
0
  return Diag(CurrentImportLoc, DiagID);
9363
0
}
9364
9365
0
DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) const {
9366
0
  return Diags.Report(Loc, DiagID);
9367
0
}
9368
9369
/// Retrieve the identifier table associated with the
9370
/// preprocessor.
9371
0
IdentifierTable &ASTReader::getIdentifierTable() {
9372
0
  return PP.getIdentifierTable();
9373
0
}
9374
9375
/// Record that the given ID maps to the given switch-case
9376
/// statement.
9377
0
void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
9378
0
  assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
9379
0
         "Already have a SwitchCase with this ID");
9380
0
  (*CurrSwitchCaseStmts)[ID] = SC;
9381
0
}
9382
9383
/// Retrieve the switch-case statement with the given ID.
9384
0
SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
9385
0
  assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
9386
0
  return (*CurrSwitchCaseStmts)[ID];
9387
0
}
9388
9389
0
void ASTReader::ClearSwitchCaseIDs() {
9390
0
  CurrSwitchCaseStmts->clear();
9391
0
}
9392
9393
0
void ASTReader::ReadComments() {
9394
0
  ASTContext &Context = getContext();
9395
0
  std::vector<RawComment *> Comments;
9396
0
  for (SmallVectorImpl<std::pair<BitstreamCursor,
9397
0
                                 serialization::ModuleFile *>>::iterator
9398
0
       I = CommentsCursors.begin(),
9399
0
       E = CommentsCursors.end();
9400
0
       I != E; ++I) {
9401
0
    Comments.clear();
9402
0
    BitstreamCursor &Cursor = I->first;
9403
0
    serialization::ModuleFile &F = *I->second;
9404
0
    SavedStreamPosition SavedPosition(Cursor);
9405
9406
0
    RecordData Record;
9407
0
    while (true) {
9408
0
      Expected<llvm::BitstreamEntry> MaybeEntry =
9409
0
          Cursor.advanceSkippingSubblocks(
9410
0
              BitstreamCursor::AF_DontPopBlockAtEnd);
9411
0
      if (!MaybeEntry) {
9412
0
        Error(MaybeEntry.takeError());
9413
0
        return;
9414
0
      }
9415
0
      llvm::BitstreamEntry Entry = MaybeEntry.get();
9416
9417
0
      switch (Entry.Kind) {
9418
0
      case llvm::BitstreamEntry::SubBlock: // Handled for us already.
9419
0
      case llvm::BitstreamEntry::Error:
9420
0
        Error("malformed block record in AST file");
9421
0
        return;
9422
0
      case llvm::BitstreamEntry::EndBlock:
9423
0
        goto NextCursor;
9424
0
      case llvm::BitstreamEntry::Record:
9425
        // The interesting case.
9426
0
        break;
9427
0
      }
9428
9429
      // Read a record.
9430
0
      Record.clear();
9431
0
      Expected<unsigned> MaybeComment = Cursor.readRecord(Entry.ID, Record);
9432
0
      if (!MaybeComment) {
9433
0
        Error(MaybeComment.takeError());
9434
0
        return;
9435
0
      }
9436
0
      switch ((CommentRecordTypes)MaybeComment.get()) {
9437
0
      case COMMENTS_RAW_COMMENT: {
9438
0
        unsigned Idx = 0;
9439
0
        SourceRange SR = ReadSourceRange(F, Record, Idx);
9440
0
        RawComment::CommentKind Kind =
9441
0
            (RawComment::CommentKind) Record[Idx++];
9442
0
        bool IsTrailingComment = Record[Idx++];
9443
0
        bool IsAlmostTrailingComment = Record[Idx++];
9444
0
        Comments.push_back(new (Context) RawComment(
9445
0
            SR, Kind, IsTrailingComment, IsAlmostTrailingComment));
9446
0
        break;
9447
0
      }
9448
0
      }
9449
0
    }
9450
0
  NextCursor:
9451
0
    llvm::DenseMap<FileID, std::map<unsigned, RawComment *>>
9452
0
        FileToOffsetToComment;
9453
0
    for (RawComment *C : Comments) {
9454
0
      SourceLocation CommentLoc = C->getBeginLoc();
9455
0
      if (CommentLoc.isValid()) {
9456
0
        std::pair<FileID, unsigned> Loc =
9457
0
            SourceMgr.getDecomposedLoc(CommentLoc);
9458
0
        if (Loc.first.isValid())
9459
0
          Context.Comments.OrderedComments[Loc.first].emplace(Loc.second, C);
9460
0
      }
9461
0
    }
9462
0
  }
9463
0
}
9464
9465
void ASTReader::visitInputFileInfos(
9466
    serialization::ModuleFile &MF, bool IncludeSystem,
9467
    llvm::function_ref<void(const serialization::InputFileInfo &IFI,
9468
                            bool IsSystem)>
9469
0
        Visitor) {
9470
0
  unsigned NumUserInputs = MF.NumUserInputFiles;
9471
0
  unsigned NumInputs = MF.InputFilesLoaded.size();
9472
0
  assert(NumUserInputs <= NumInputs);
9473
0
  unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
9474
0
  for (unsigned I = 0; I < N; ++I) {
9475
0
    bool IsSystem = I >= NumUserInputs;
9476
0
    InputFileInfo IFI = getInputFileInfo(MF, I+1);
9477
0
    Visitor(IFI, IsSystem);
9478
0
  }
9479
0
}
9480
9481
void ASTReader::visitInputFiles(serialization::ModuleFile &MF,
9482
                                bool IncludeSystem, bool Complain,
9483
                    llvm::function_ref<void(const serialization::InputFile &IF,
9484
0
                                            bool isSystem)> Visitor) {
9485
0
  unsigned NumUserInputs = MF.NumUserInputFiles;
9486
0
  unsigned NumInputs = MF.InputFilesLoaded.size();
9487
0
  assert(NumUserInputs <= NumInputs);
9488
0
  unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
9489
0
  for (unsigned I = 0; I < N; ++I) {
9490
0
    bool IsSystem = I >= NumUserInputs;
9491
0
    InputFile IF = getInputFile(MF, I+1, Complain);
9492
0
    Visitor(IF, IsSystem);
9493
0
  }
9494
0
}
9495
9496
void ASTReader::visitTopLevelModuleMaps(
9497
    serialization::ModuleFile &MF,
9498
0
    llvm::function_ref<void(FileEntryRef FE)> Visitor) {
9499
0
  unsigned NumInputs = MF.InputFilesLoaded.size();
9500
0
  for (unsigned I = 0; I < NumInputs; ++I) {
9501
0
    InputFileInfo IFI = getInputFileInfo(MF, I + 1);
9502
0
    if (IFI.TopLevel && IFI.ModuleMap)
9503
0
      if (auto FE = getInputFile(MF, I + 1).getFile())
9504
0
        Visitor(*FE);
9505
0
  }
9506
0
}
9507
9508
0
void ASTReader::finishPendingActions() {
9509
0
  while (
9510
0
      !PendingIdentifierInfos.empty() || !PendingDeducedFunctionTypes.empty() ||
9511
0
      !PendingDeducedVarTypes.empty() || !PendingIncompleteDeclChains.empty() ||
9512
0
      !PendingDeclChains.empty() || !PendingMacroIDs.empty() ||
9513
0
      !PendingDeclContextInfos.empty() || !PendingUpdateRecords.empty() ||
9514
0
      !PendingObjCExtensionIvarRedeclarations.empty()) {
9515
    // If any identifiers with corresponding top-level declarations have
9516
    // been loaded, load those declarations now.
9517
0
    using TopLevelDeclsMap =
9518
0
        llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2>>;
9519
0
    TopLevelDeclsMap TopLevelDecls;
9520
9521
0
    while (!PendingIdentifierInfos.empty()) {
9522
0
      IdentifierInfo *II = PendingIdentifierInfos.back().first;
9523
0
      SmallVector<uint32_t, 4> DeclIDs =
9524
0
          std::move(PendingIdentifierInfos.back().second);
9525
0
      PendingIdentifierInfos.pop_back();
9526
9527
0
      SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
9528
0
    }
9529
9530
    // Load each function type that we deferred loading because it was a
9531
    // deduced type that might refer to a local type declared within itself.
9532
0
    for (unsigned I = 0; I != PendingDeducedFunctionTypes.size(); ++I) {
9533
0
      auto *FD = PendingDeducedFunctionTypes[I].first;
9534
0
      FD->setType(GetType(PendingDeducedFunctionTypes[I].second));
9535
9536
      // If we gave a function a deduced return type, remember that we need to
9537
      // propagate that along the redeclaration chain.
9538
0
      auto *DT = FD->getReturnType()->getContainedDeducedType();
9539
0
      if (DT && DT->isDeduced())
9540
0
        PendingDeducedTypeUpdates.insert(
9541
0
            {FD->getCanonicalDecl(), FD->getReturnType()});
9542
0
    }
9543
0
    PendingDeducedFunctionTypes.clear();
9544
9545
    // Load each variable type that we deferred loading because it was a
9546
    // deduced type that might refer to a local type declared within itself.
9547
0
    for (unsigned I = 0; I != PendingDeducedVarTypes.size(); ++I) {
9548
0
      auto *VD = PendingDeducedVarTypes[I].first;
9549
0
      VD->setType(GetType(PendingDeducedVarTypes[I].second));
9550
0
    }
9551
0
    PendingDeducedVarTypes.clear();
9552
9553
    // For each decl chain that we wanted to complete while deserializing, mark
9554
    // it as "still needs to be completed".
9555
0
    for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
9556
0
      markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
9557
0
    }
9558
0
    PendingIncompleteDeclChains.clear();
9559
9560
    // Load pending declaration chains.
9561
0
    for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
9562
0
      loadPendingDeclChain(PendingDeclChains[I].first,
9563
0
                           PendingDeclChains[I].second);
9564
0
    PendingDeclChains.clear();
9565
9566
    // Make the most recent of the top-level declarations visible.
9567
0
    for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
9568
0
           TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
9569
0
      IdentifierInfo *II = TLD->first;
9570
0
      for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
9571
0
        pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
9572
0
      }
9573
0
    }
9574
9575
    // Load any pending macro definitions.
9576
0
    for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
9577
0
      IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
9578
0
      SmallVector<PendingMacroInfo, 2> GlobalIDs;
9579
0
      GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
9580
      // Initialize the macro history from chained-PCHs ahead of module imports.
9581
0
      for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
9582
0
           ++IDIdx) {
9583
0
        const PendingMacroInfo &Info = GlobalIDs[IDIdx];
9584
0
        if (!Info.M->isModule())
9585
0
          resolvePendingMacro(II, Info);
9586
0
      }
9587
      // Handle module imports.
9588
0
      for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
9589
0
           ++IDIdx) {
9590
0
        const PendingMacroInfo &Info = GlobalIDs[IDIdx];
9591
0
        if (Info.M->isModule())
9592
0
          resolvePendingMacro(II, Info);
9593
0
      }
9594
0
    }
9595
0
    PendingMacroIDs.clear();
9596
9597
    // Wire up the DeclContexts for Decls that we delayed setting until
9598
    // recursive loading is completed.
9599
0
    while (!PendingDeclContextInfos.empty()) {
9600
0
      PendingDeclContextInfo Info = PendingDeclContextInfos.front();
9601
0
      PendingDeclContextInfos.pop_front();
9602
0
      DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
9603
0
      DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
9604
0
      Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
9605
0
    }
9606
9607
    // Perform any pending declaration updates.
9608
0
    while (!PendingUpdateRecords.empty()) {
9609
0
      auto Update = PendingUpdateRecords.pop_back_val();
9610
0
      ReadingKindTracker ReadingKind(Read_Decl, *this);
9611
0
      loadDeclUpdateRecords(Update);
9612
0
    }
9613
9614
0
    while (!PendingObjCExtensionIvarRedeclarations.empty()) {
9615
0
      auto ExtensionsPair = PendingObjCExtensionIvarRedeclarations.back().first;
9616
0
      auto DuplicateIvars =
9617
0
          PendingObjCExtensionIvarRedeclarations.back().second;
9618
0
      llvm::DenseSet<std::pair<Decl *, Decl *>> NonEquivalentDecls;
9619
0
      StructuralEquivalenceContext Ctx(
9620
0
          ExtensionsPair.first->getASTContext(),
9621
0
          ExtensionsPair.second->getASTContext(), NonEquivalentDecls,
9622
0
          StructuralEquivalenceKind::Default, /*StrictTypeSpelling =*/false,
9623
0
          /*Complain =*/false,
9624
0
          /*ErrorOnTagTypeMismatch =*/true);
9625
0
      if (Ctx.IsEquivalent(ExtensionsPair.first, ExtensionsPair.second)) {
9626
        // Merge redeclared ivars with their predecessors.
9627
0
        for (auto IvarPair : DuplicateIvars) {
9628
0
          ObjCIvarDecl *Ivar = IvarPair.first, *PrevIvar = IvarPair.second;
9629
          // Change semantic DeclContext but keep the lexical one.
9630
0
          Ivar->setDeclContextsImpl(PrevIvar->getDeclContext(),
9631
0
                                    Ivar->getLexicalDeclContext(),
9632
0
                                    getContext());
9633
0
          getContext().setPrimaryMergedDecl(Ivar, PrevIvar->getCanonicalDecl());
9634
0
        }
9635
        // Invalidate duplicate extension and the cached ivar list.
9636
0
        ExtensionsPair.first->setInvalidDecl();
9637
0
        ExtensionsPair.second->getClassInterface()
9638
0
            ->getDefinition()
9639
0
            ->setIvarList(nullptr);
9640
0
      } else {
9641
0
        for (auto IvarPair : DuplicateIvars) {
9642
0
          Diag(IvarPair.first->getLocation(),
9643
0
               diag::err_duplicate_ivar_declaration)
9644
0
              << IvarPair.first->getIdentifier();
9645
0
          Diag(IvarPair.second->getLocation(), diag::note_previous_definition);
9646
0
        }
9647
0
      }
9648
0
      PendingObjCExtensionIvarRedeclarations.pop_back();
9649
0
    }
9650
0
  }
9651
9652
  // At this point, all update records for loaded decls are in place, so any
9653
  // fake class definitions should have become real.
9654
0
  assert(PendingFakeDefinitionData.empty() &&
9655
0
         "faked up a class definition but never saw the real one");
9656
9657
  // If we deserialized any C++ or Objective-C class definitions, any
9658
  // Objective-C protocol definitions, or any redeclarable templates, make sure
9659
  // that all redeclarations point to the definitions. Note that this can only
9660
  // happen now, after the redeclaration chains have been fully wired.
9661
0
  for (Decl *D : PendingDefinitions) {
9662
0
    if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
9663
0
      if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
9664
        // Make sure that the TagType points at the definition.
9665
0
        const_cast<TagType*>(TagT)->decl = TD;
9666
0
      }
9667
9668
0
      if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
9669
0
        for (auto *R = getMostRecentExistingDecl(RD); R;
9670
0
             R = R->getPreviousDecl()) {
9671
0
          assert((R == D) ==
9672
0
                     cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
9673
0
                 "declaration thinks it's the definition but it isn't");
9674
0
          cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
9675
0
        }
9676
0
      }
9677
9678
0
      continue;
9679
0
    }
9680
9681
0
    if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
9682
      // Make sure that the ObjCInterfaceType points at the definition.
9683
0
      const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
9684
0
        ->Decl = ID;
9685
9686
0
      for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
9687
0
        cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
9688
9689
0
      continue;
9690
0
    }
9691
9692
0
    if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
9693
0
      for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
9694
0
        cast<ObjCProtocolDecl>(R)->Data = PD->Data;
9695
9696
0
      continue;
9697
0
    }
9698
9699
0
    auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
9700
0
    for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
9701
0
      cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
9702
0
  }
9703
0
  PendingDefinitions.clear();
9704
9705
  // Load the bodies of any functions or methods we've encountered. We do
9706
  // this now (delayed) so that we can be sure that the declaration chains
9707
  // have been fully wired up (hasBody relies on this).
9708
  // FIXME: We shouldn't require complete redeclaration chains here.
9709
0
  for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
9710
0
                               PBEnd = PendingBodies.end();
9711
0
       PB != PBEnd; ++PB) {
9712
0
    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
9713
      // For a function defined inline within a class template, force the
9714
      // canonical definition to be the one inside the canonical definition of
9715
      // the template. This ensures that we instantiate from a correct view
9716
      // of the template.
9717
      //
9718
      // Sadly we can't do this more generally: we can't be sure that all
9719
      // copies of an arbitrary class definition will have the same members
9720
      // defined (eg, some member functions may not be instantiated, and some
9721
      // special members may or may not have been implicitly defined).
9722
0
      if (auto *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalParent()))
9723
0
        if (RD->isDependentContext() && !RD->isThisDeclarationADefinition())
9724
0
          continue;
9725
9726
      // FIXME: Check for =delete/=default?
9727
0
      const FunctionDecl *Defn = nullptr;
9728
0
      if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) {
9729
0
        FD->setLazyBody(PB->second);
9730
0
      } else {
9731
0
        auto *NonConstDefn = const_cast<FunctionDecl*>(Defn);
9732
0
        mergeDefinitionVisibility(NonConstDefn, FD);
9733
9734
0
        if (!FD->isLateTemplateParsed() &&
9735
0
            !NonConstDefn->isLateTemplateParsed() &&
9736
0
            FD->getODRHash() != NonConstDefn->getODRHash()) {
9737
0
          if (!isa<CXXMethodDecl>(FD)) {
9738
0
            PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
9739
0
          } else if (FD->getLexicalParent()->isFileContext() &&
9740
0
                     NonConstDefn->getLexicalParent()->isFileContext()) {
9741
            // Only diagnose out-of-line method definitions.  If they are
9742
            // in class definitions, then an error will be generated when
9743
            // processing the class bodies.
9744
0
            PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
9745
0
          }
9746
0
        }
9747
0
      }
9748
0
      continue;
9749
0
    }
9750
9751
0
    ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
9752
0
    if (!getContext().getLangOpts().Modules || !MD->hasBody())
9753
0
      MD->setLazyBody(PB->second);
9754
0
  }
9755
0
  PendingBodies.clear();
9756
9757
  // Inform any classes that had members added that they now have more members.
9758
0
  for (auto [RD, MD] : PendingAddedClassMembers) {
9759
0
    RD->addedMember(MD);
9760
0
  }
9761
0
  PendingAddedClassMembers.clear();
9762
9763
  // Do some cleanup.
9764
0
  for (auto *ND : PendingMergedDefinitionsToDeduplicate)
9765
0
    getContext().deduplicateMergedDefinitonsFor(ND);
9766
0
  PendingMergedDefinitionsToDeduplicate.clear();
9767
0
}
9768
9769
0
void ASTReader::diagnoseOdrViolations() {
9770
0
  if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty() &&
9771
0
      PendingRecordOdrMergeFailures.empty() &&
9772
0
      PendingFunctionOdrMergeFailures.empty() &&
9773
0
      PendingEnumOdrMergeFailures.empty() &&
9774
0
      PendingObjCInterfaceOdrMergeFailures.empty() &&
9775
0
      PendingObjCProtocolOdrMergeFailures.empty())
9776
0
    return;
9777
9778
  // Trigger the import of the full definition of each class that had any
9779
  // odr-merging problems, so we can produce better diagnostics for them.
9780
  // These updates may in turn find and diagnose some ODR failures, so take
9781
  // ownership of the set first.
9782
0
  auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
9783
0
  PendingOdrMergeFailures.clear();
9784
0
  for (auto &Merge : OdrMergeFailures) {
9785
0
    Merge.first->buildLookup();
9786
0
    Merge.first->decls_begin();
9787
0
    Merge.first->bases_begin();
9788
0
    Merge.first->vbases_begin();
9789
0
    for (auto &RecordPair : Merge.second) {
9790
0
      auto *RD = RecordPair.first;
9791
0
      RD->decls_begin();
9792
0
      RD->bases_begin();
9793
0
      RD->vbases_begin();
9794
0
    }
9795
0
  }
9796
9797
  // Trigger the import of the full definition of each record in C/ObjC.
9798
0
  auto RecordOdrMergeFailures = std::move(PendingRecordOdrMergeFailures);
9799
0
  PendingRecordOdrMergeFailures.clear();
9800
0
  for (auto &Merge : RecordOdrMergeFailures) {
9801
0
    Merge.first->decls_begin();
9802
0
    for (auto &D : Merge.second)
9803
0
      D->decls_begin();
9804
0
  }
9805
9806
  // Trigger the import of the full interface definition.
9807
0
  auto ObjCInterfaceOdrMergeFailures =
9808
0
      std::move(PendingObjCInterfaceOdrMergeFailures);
9809
0
  PendingObjCInterfaceOdrMergeFailures.clear();
9810
0
  for (auto &Merge : ObjCInterfaceOdrMergeFailures) {
9811
0
    Merge.first->decls_begin();
9812
0
    for (auto &InterfacePair : Merge.second)
9813
0
      InterfacePair.first->decls_begin();
9814
0
  }
9815
9816
  // Trigger the import of functions.
9817
0
  auto FunctionOdrMergeFailures = std::move(PendingFunctionOdrMergeFailures);
9818
0
  PendingFunctionOdrMergeFailures.clear();
9819
0
  for (auto &Merge : FunctionOdrMergeFailures) {
9820
0
    Merge.first->buildLookup();
9821
0
    Merge.first->decls_begin();
9822
0
    Merge.first->getBody();
9823
0
    for (auto &FD : Merge.second) {
9824
0
      FD->buildLookup();
9825
0
      FD->decls_begin();
9826
0
      FD->getBody();
9827
0
    }
9828
0
  }
9829
9830
  // Trigger the import of enums.
9831
0
  auto EnumOdrMergeFailures = std::move(PendingEnumOdrMergeFailures);
9832
0
  PendingEnumOdrMergeFailures.clear();
9833
0
  for (auto &Merge : EnumOdrMergeFailures) {
9834
0
    Merge.first->decls_begin();
9835
0
    for (auto &Enum : Merge.second) {
9836
0
      Enum->decls_begin();
9837
0
    }
9838
0
  }
9839
9840
  // Trigger the import of the full protocol definition.
9841
0
  auto ObjCProtocolOdrMergeFailures =
9842
0
      std::move(PendingObjCProtocolOdrMergeFailures);
9843
0
  PendingObjCProtocolOdrMergeFailures.clear();
9844
0
  for (auto &Merge : ObjCProtocolOdrMergeFailures) {
9845
0
    Merge.first->decls_begin();
9846
0
    for (auto &ProtocolPair : Merge.second)
9847
0
      ProtocolPair.first->decls_begin();
9848
0
  }
9849
9850
  // For each declaration from a merged context, check that the canonical
9851
  // definition of that context also contains a declaration of the same
9852
  // entity.
9853
  //
9854
  // Caution: this loop does things that might invalidate iterators into
9855
  // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
9856
0
  while (!PendingOdrMergeChecks.empty()) {
9857
0
    NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
9858
9859
    // FIXME: Skip over implicit declarations for now. This matters for things
9860
    // like implicitly-declared special member functions. This isn't entirely
9861
    // correct; we can end up with multiple unmerged declarations of the same
9862
    // implicit entity.
9863
0
    if (D->isImplicit())
9864
0
      continue;
9865
9866
0
    DeclContext *CanonDef = D->getDeclContext();
9867
9868
0
    bool Found = false;
9869
0
    const Decl *DCanon = D->getCanonicalDecl();
9870
9871
0
    for (auto *RI : D->redecls()) {
9872
0
      if (RI->getLexicalDeclContext() == CanonDef) {
9873
0
        Found = true;
9874
0
        break;
9875
0
      }
9876
0
    }
9877
0
    if (Found)
9878
0
      continue;
9879
9880
    // Quick check failed, time to do the slow thing. Note, we can't just
9881
    // look up the name of D in CanonDef here, because the member that is
9882
    // in CanonDef might not be found by name lookup (it might have been
9883
    // replaced by a more recent declaration in the lookup table), and we
9884
    // can't necessarily find it in the redeclaration chain because it might
9885
    // be merely mergeable, not redeclarable.
9886
0
    llvm::SmallVector<const NamedDecl*, 4> Candidates;
9887
0
    for (auto *CanonMember : CanonDef->decls()) {
9888
0
      if (CanonMember->getCanonicalDecl() == DCanon) {
9889
        // This can happen if the declaration is merely mergeable and not
9890
        // actually redeclarable (we looked for redeclarations earlier).
9891
        //
9892
        // FIXME: We should be able to detect this more efficiently, without
9893
        // pulling in all of the members of CanonDef.
9894
0
        Found = true;
9895
0
        break;
9896
0
      }
9897
0
      if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
9898
0
        if (ND->getDeclName() == D->getDeclName())
9899
0
          Candidates.push_back(ND);
9900
0
    }
9901
9902
0
    if (!Found) {
9903
      // The AST doesn't like TagDecls becoming invalid after they've been
9904
      // completed. We only really need to mark FieldDecls as invalid here.
9905
0
      if (!isa<TagDecl>(D))
9906
0
        D->setInvalidDecl();
9907
9908
      // Ensure we don't accidentally recursively enter deserialization while
9909
      // we're producing our diagnostic.
9910
0
      Deserializing RecursionGuard(this);
9911
9912
0
      std::string CanonDefModule =
9913
0
          ODRDiagsEmitter::getOwningModuleNameForDiagnostic(
9914
0
              cast<Decl>(CanonDef));
9915
0
      Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
9916
0
        << D << ODRDiagsEmitter::getOwningModuleNameForDiagnostic(D)
9917
0
        << CanonDef << CanonDefModule.empty() << CanonDefModule;
9918
9919
0
      if (Candidates.empty())
9920
0
        Diag(cast<Decl>(CanonDef)->getLocation(),
9921
0
             diag::note_module_odr_violation_no_possible_decls) << D;
9922
0
      else {
9923
0
        for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
9924
0
          Diag(Candidates[I]->getLocation(),
9925
0
               diag::note_module_odr_violation_possible_decl)
9926
0
            << Candidates[I];
9927
0
      }
9928
9929
0
      DiagnosedOdrMergeFailures.insert(CanonDef);
9930
0
    }
9931
0
  }
9932
9933
0
  if (OdrMergeFailures.empty() && RecordOdrMergeFailures.empty() &&
9934
0
      FunctionOdrMergeFailures.empty() && EnumOdrMergeFailures.empty() &&
9935
0
      ObjCInterfaceOdrMergeFailures.empty() &&
9936
0
      ObjCProtocolOdrMergeFailures.empty())
9937
0
    return;
9938
9939
0
  ODRDiagsEmitter DiagsEmitter(Diags, getContext(),
9940
0
                               getPreprocessor().getLangOpts());
9941
9942
  // Issue any pending ODR-failure diagnostics.
9943
0
  for (auto &Merge : OdrMergeFailures) {
9944
    // If we've already pointed out a specific problem with this class, don't
9945
    // bother issuing a general "something's different" diagnostic.
9946
0
    if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
9947
0
      continue;
9948
9949
0
    bool Diagnosed = false;
9950
0
    CXXRecordDecl *FirstRecord = Merge.first;
9951
0
    for (auto &RecordPair : Merge.second) {
9952
0
      if (DiagsEmitter.diagnoseMismatch(FirstRecord, RecordPair.first,
9953
0
                                        RecordPair.second)) {
9954
0
        Diagnosed = true;
9955
0
        break;
9956
0
      }
9957
0
    }
9958
9959
0
    if (!Diagnosed) {
9960
      // All definitions are updates to the same declaration. This happens if a
9961
      // module instantiates the declaration of a class template specialization
9962
      // and two or more other modules instantiate its definition.
9963
      //
9964
      // FIXME: Indicate which modules had instantiations of this definition.
9965
      // FIXME: How can this even happen?
9966
0
      Diag(Merge.first->getLocation(),
9967
0
           diag::err_module_odr_violation_different_instantiations)
9968
0
          << Merge.first;
9969
0
    }
9970
0
  }
9971
9972
  // Issue any pending ODR-failure diagnostics for RecordDecl in C/ObjC. Note
9973
  // that in C++ this is done as a part of CXXRecordDecl ODR checking.
9974
0
  for (auto &Merge : RecordOdrMergeFailures) {
9975
    // If we've already pointed out a specific problem with this class, don't
9976
    // bother issuing a general "something's different" diagnostic.
9977
0
    if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
9978
0
      continue;
9979
9980
0
    RecordDecl *FirstRecord = Merge.first;
9981
0
    bool Diagnosed = false;
9982
0
    for (auto *SecondRecord : Merge.second) {
9983
0
      if (DiagsEmitter.diagnoseMismatch(FirstRecord, SecondRecord)) {
9984
0
        Diagnosed = true;
9985
0
        break;
9986
0
      }
9987
0
    }
9988
0
    (void)Diagnosed;
9989
0
    assert(Diagnosed && "Unable to emit ODR diagnostic.");
9990
0
  }
9991
9992
  // Issue ODR failures diagnostics for functions.
9993
0
  for (auto &Merge : FunctionOdrMergeFailures) {
9994
0
    FunctionDecl *FirstFunction = Merge.first;
9995
0
    bool Diagnosed = false;
9996
0
    for (auto &SecondFunction : Merge.second) {
9997
0
      if (DiagsEmitter.diagnoseMismatch(FirstFunction, SecondFunction)) {
9998
0
        Diagnosed = true;
9999
0
        break;
10000
0
      }
10001
0
    }
10002
0
    (void)Diagnosed;
10003
0
    assert(Diagnosed && "Unable to emit ODR diagnostic.");
10004
0
  }
10005
10006
  // Issue ODR failures diagnostics for enums.
10007
0
  for (auto &Merge : EnumOdrMergeFailures) {
10008
    // If we've already pointed out a specific problem with this enum, don't
10009
    // bother issuing a general "something's different" diagnostic.
10010
0
    if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
10011
0
      continue;
10012
10013
0
    EnumDecl *FirstEnum = Merge.first;
10014
0
    bool Diagnosed = false;
10015
0
    for (auto &SecondEnum : Merge.second) {
10016
0
      if (DiagsEmitter.diagnoseMismatch(FirstEnum, SecondEnum)) {
10017
0
        Diagnosed = true;
10018
0
        break;
10019
0
      }
10020
0
    }
10021
0
    (void)Diagnosed;
10022
0
    assert(Diagnosed && "Unable to emit ODR diagnostic.");
10023
0
  }
10024
10025
0
  for (auto &Merge : ObjCInterfaceOdrMergeFailures) {
10026
    // If we've already pointed out a specific problem with this interface,
10027
    // don't bother issuing a general "something's different" diagnostic.
10028
0
    if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
10029
0
      continue;
10030
10031
0
    bool Diagnosed = false;
10032
0
    ObjCInterfaceDecl *FirstID = Merge.first;
10033
0
    for (auto &InterfacePair : Merge.second) {
10034
0
      if (DiagsEmitter.diagnoseMismatch(FirstID, InterfacePair.first,
10035
0
                                        InterfacePair.second)) {
10036
0
        Diagnosed = true;
10037
0
        break;
10038
0
      }
10039
0
    }
10040
0
    (void)Diagnosed;
10041
0
    assert(Diagnosed && "Unable to emit ODR diagnostic.");
10042
0
  }
10043
10044
0
  for (auto &Merge : ObjCProtocolOdrMergeFailures) {
10045
    // If we've already pointed out a specific problem with this protocol,
10046
    // don't bother issuing a general "something's different" diagnostic.
10047
0
    if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
10048
0
      continue;
10049
10050
0
    ObjCProtocolDecl *FirstProtocol = Merge.first;
10051
0
    bool Diagnosed = false;
10052
0
    for (auto &ProtocolPair : Merge.second) {
10053
0
      if (DiagsEmitter.diagnoseMismatch(FirstProtocol, ProtocolPair.first,
10054
0
                                        ProtocolPair.second)) {
10055
0
        Diagnosed = true;
10056
0
        break;
10057
0
      }
10058
0
    }
10059
0
    (void)Diagnosed;
10060
0
    assert(Diagnosed && "Unable to emit ODR diagnostic.");
10061
0
  }
10062
0
}
10063
10064
0
void ASTReader::StartedDeserializing() {
10065
0
  if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
10066
0
    ReadTimer->startTimer();
10067
0
}
10068
10069
0
void ASTReader::FinishedDeserializing() {
10070
0
  assert(NumCurrentElementsDeserializing &&
10071
0
         "FinishedDeserializing not paired with StartedDeserializing");
10072
0
  if (NumCurrentElementsDeserializing == 1) {
10073
    // We decrease NumCurrentElementsDeserializing only after pending actions
10074
    // are finished, to avoid recursively re-calling finishPendingActions().
10075
0
    finishPendingActions();
10076
0
  }
10077
0
  --NumCurrentElementsDeserializing;
10078
10079
0
  if (NumCurrentElementsDeserializing == 0) {
10080
    // Propagate exception specification and deduced type updates along
10081
    // redeclaration chains.
10082
    //
10083
    // We do this now rather than in finishPendingActions because we want to
10084
    // be able to walk the complete redeclaration chains of the updated decls.
10085
0
    while (!PendingExceptionSpecUpdates.empty() ||
10086
0
           !PendingDeducedTypeUpdates.empty()) {
10087
0
      auto ESUpdates = std::move(PendingExceptionSpecUpdates);
10088
0
      PendingExceptionSpecUpdates.clear();
10089
0
      for (auto Update : ESUpdates) {
10090
0
        ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
10091
0
        auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
10092
0
        auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
10093
0
        if (auto *Listener = getContext().getASTMutationListener())
10094
0
          Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
10095
0
        for (auto *Redecl : Update.second->redecls())
10096
0
          getContext().adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
10097
0
      }
10098
10099
0
      auto DTUpdates = std::move(PendingDeducedTypeUpdates);
10100
0
      PendingDeducedTypeUpdates.clear();
10101
0
      for (auto Update : DTUpdates) {
10102
0
        ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
10103
        // FIXME: If the return type is already deduced, check that it matches.
10104
0
        getContext().adjustDeducedFunctionResultType(Update.first,
10105
0
                                                     Update.second);
10106
0
      }
10107
0
    }
10108
10109
0
    if (ReadTimer)
10110
0
      ReadTimer->stopTimer();
10111
10112
0
    diagnoseOdrViolations();
10113
10114
    // We are not in recursive loading, so it's safe to pass the "interesting"
10115
    // decls to the consumer.
10116
0
    if (Consumer)
10117
0
      PassInterestingDeclsToConsumer();
10118
0
  }
10119
0
}
10120
10121
0
void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
10122
0
  if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
10123
    // Remove any fake results before adding any real ones.
10124
0
    auto It = PendingFakeLookupResults.find(II);
10125
0
    if (It != PendingFakeLookupResults.end()) {
10126
0
      for (auto *ND : It->second)
10127
0
        SemaObj->IdResolver.RemoveDecl(ND);
10128
      // FIXME: this works around module+PCH performance issue.
10129
      // Rather than erase the result from the map, which is O(n), just clear
10130
      // the vector of NamedDecls.
10131
0
      It->second.clear();
10132
0
    }
10133
0
  }
10134
10135
0
  if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
10136
0
    SemaObj->TUScope->AddDecl(D);
10137
0
  } else if (SemaObj->TUScope) {
10138
    // Adding the decl to IdResolver may have failed because it was already in
10139
    // (even though it was not added in scope). If it is already in, make sure
10140
    // it gets in the scope as well.
10141
0
    if (llvm::is_contained(SemaObj->IdResolver.decls(Name), D))
10142
0
      SemaObj->TUScope->AddDecl(D);
10143
0
  }
10144
0
}
10145
10146
ASTReader::ASTReader(Preprocessor &PP, InMemoryModuleCache &ModuleCache,
10147
                     ASTContext *Context,
10148
                     const PCHContainerReader &PCHContainerRdr,
10149
                     ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
10150
                     StringRef isysroot,
10151
                     DisableValidationForModuleKind DisableValidationKind,
10152
                     bool AllowASTWithCompilerErrors,
10153
                     bool AllowConfigurationMismatch, bool ValidateSystemInputs,
10154
                     bool ValidateASTInputFilesContent, bool UseGlobalIndex,
10155
                     std::unique_ptr<llvm::Timer> ReadTimer)
10156
    : Listener(bool(DisableValidationKind &DisableValidationForModuleKind::PCH)
10157
                   ? cast<ASTReaderListener>(new SimpleASTReaderListener(PP))
10158
                   : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
10159
      SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
10160
      PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP),
10161
      ContextObj(Context), ModuleMgr(PP.getFileManager(), ModuleCache,
10162
                                     PCHContainerRdr, PP.getHeaderSearchInfo()),
10163
      DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
10164
      DisableValidationKind(DisableValidationKind),
10165
      AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
10166
      AllowConfigurationMismatch(AllowConfigurationMismatch),
10167
      ValidateSystemInputs(ValidateSystemInputs),
10168
      ValidateASTInputFilesContent(ValidateASTInputFilesContent),
10169
0
      UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
10170
0
  SourceMgr.setExternalSLocEntrySource(this);
10171
10172
0
  for (const auto &Ext : Extensions) {
10173
0
    auto BlockName = Ext->getExtensionMetadata().BlockName;
10174
0
    auto Known = ModuleFileExtensions.find(BlockName);
10175
0
    if (Known != ModuleFileExtensions.end()) {
10176
0
      Diags.Report(diag::warn_duplicate_module_file_extension)
10177
0
        << BlockName;
10178
0
      continue;
10179
0
    }
10180
10181
0
    ModuleFileExtensions.insert({BlockName, Ext});
10182
0
  }
10183
0
}
10184
10185
0
ASTReader::~ASTReader() {
10186
0
  if (OwnsDeserializationListener)
10187
0
    delete DeserializationListener;
10188
0
}
10189
10190
0
IdentifierResolver &ASTReader::getIdResolver() {
10191
0
  return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
10192
0
}
10193
10194
Expected<unsigned> ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor,
10195
0
                                               unsigned AbbrevID) {
10196
0
  Idx = 0;
10197
0
  Record.clear();
10198
0
  return Cursor.readRecord(AbbrevID, Record);
10199
0
}
10200
//===----------------------------------------------------------------------===//
10201
//// OMPClauseReader implementation
10202
////===----------------------------------------------------------------------===//
10203
10204
// This has to be in namespace clang because it's friended by all
10205
// of the OMP clauses.
10206
namespace clang {
10207
10208
class OMPClauseReader : public OMPClauseVisitor<OMPClauseReader> {
10209
  ASTRecordReader &Record;
10210
  ASTContext &Context;
10211
10212
public:
10213
  OMPClauseReader(ASTRecordReader &Record)
10214
0
      : Record(Record), Context(Record.getContext()) {}
10215
#define GEN_CLANG_CLAUSE_CLASS
10216
#define CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(Class *C);
10217
#include "llvm/Frontend/OpenMP/OMP.inc"
10218
  OMPClause *readClause();
10219
  void VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C);
10220
  void VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C);
10221
};
10222
10223
} // end namespace clang
10224
10225
0
OMPClause *ASTRecordReader::readOMPClause() {
10226
0
  return OMPClauseReader(*this).readClause();
10227
0
}
10228
10229
0
OMPClause *OMPClauseReader::readClause() {
10230
0
  OMPClause *C = nullptr;
10231
0
  switch (llvm::omp::Clause(Record.readInt())) {
10232
0
  case llvm::omp::OMPC_if:
10233
0
    C = new (Context) OMPIfClause();
10234
0
    break;
10235
0
  case llvm::omp::OMPC_final:
10236
0
    C = new (Context) OMPFinalClause();
10237
0
    break;
10238
0
  case llvm::omp::OMPC_num_threads:
10239
0
    C = new (Context) OMPNumThreadsClause();
10240
0
    break;
10241
0
  case llvm::omp::OMPC_safelen:
10242
0
    C = new (Context) OMPSafelenClause();
10243
0
    break;
10244
0
  case llvm::omp::OMPC_simdlen:
10245
0
    C = new (Context) OMPSimdlenClause();
10246
0
    break;
10247
0
  case llvm::omp::OMPC_sizes: {
10248
0
    unsigned NumSizes = Record.readInt();
10249
0
    C = OMPSizesClause::CreateEmpty(Context, NumSizes);
10250
0
    break;
10251
0
  }
10252
0
  case llvm::omp::OMPC_full:
10253
0
    C = OMPFullClause::CreateEmpty(Context);
10254
0
    break;
10255
0
  case llvm::omp::OMPC_partial:
10256
0
    C = OMPPartialClause::CreateEmpty(Context);
10257
0
    break;
10258
0
  case llvm::omp::OMPC_allocator:
10259
0
    C = new (Context) OMPAllocatorClause();
10260
0
    break;
10261
0
  case llvm::omp::OMPC_collapse:
10262
0
    C = new (Context) OMPCollapseClause();
10263
0
    break;
10264
0
  case llvm::omp::OMPC_default:
10265
0
    C = new (Context) OMPDefaultClause();
10266
0
    break;
10267
0
  case llvm::omp::OMPC_proc_bind:
10268
0
    C = new (Context) OMPProcBindClause();
10269
0
    break;
10270
0
  case llvm::omp::OMPC_schedule:
10271
0
    C = new (Context) OMPScheduleClause();
10272
0
    break;
10273
0
  case llvm::omp::OMPC_ordered:
10274
0
    C = OMPOrderedClause::CreateEmpty(Context, Record.readInt());
10275
0
    break;
10276
0
  case llvm::omp::OMPC_nowait:
10277
0
    C = new (Context) OMPNowaitClause();
10278
0
    break;
10279
0
  case llvm::omp::OMPC_untied:
10280
0
    C = new (Context) OMPUntiedClause();
10281
0
    break;
10282
0
  case llvm::omp::OMPC_mergeable:
10283
0
    C = new (Context) OMPMergeableClause();
10284
0
    break;
10285
0
  case llvm::omp::OMPC_read:
10286
0
    C = new (Context) OMPReadClause();
10287
0
    break;
10288
0
  case llvm::omp::OMPC_write:
10289
0
    C = new (Context) OMPWriteClause();
10290
0
    break;
10291
0
  case llvm::omp::OMPC_update:
10292
0
    C = OMPUpdateClause::CreateEmpty(Context, Record.readInt());
10293
0
    break;
10294
0
  case llvm::omp::OMPC_capture:
10295
0
    C = new (Context) OMPCaptureClause();
10296
0
    break;
10297
0
  case llvm::omp::OMPC_compare:
10298
0
    C = new (Context) OMPCompareClause();
10299
0
    break;
10300
0
  case llvm::omp::OMPC_fail:
10301
0
    C = new (Context) OMPFailClause();
10302
0
    break;
10303
0
  case llvm::omp::OMPC_seq_cst:
10304
0
    C = new (Context) OMPSeqCstClause();
10305
0
    break;
10306
0
  case llvm::omp::OMPC_acq_rel:
10307
0
    C = new (Context) OMPAcqRelClause();
10308
0
    break;
10309
0
  case llvm::omp::OMPC_acquire:
10310
0
    C = new (Context) OMPAcquireClause();
10311
0
    break;
10312
0
  case llvm::omp::OMPC_release:
10313
0
    C = new (Context) OMPReleaseClause();
10314
0
    break;
10315
0
  case llvm::omp::OMPC_relaxed:
10316
0
    C = new (Context) OMPRelaxedClause();
10317
0
    break;
10318
0
  case llvm::omp::OMPC_threads:
10319
0
    C = new (Context) OMPThreadsClause();
10320
0
    break;
10321
0
  case llvm::omp::OMPC_simd:
10322
0
    C = new (Context) OMPSIMDClause();
10323
0
    break;
10324
0
  case llvm::omp::OMPC_nogroup:
10325
0
    C = new (Context) OMPNogroupClause();
10326
0
    break;
10327
0
  case llvm::omp::OMPC_unified_address:
10328
0
    C = new (Context) OMPUnifiedAddressClause();
10329
0
    break;
10330
0
  case llvm::omp::OMPC_unified_shared_memory:
10331
0
    C = new (Context) OMPUnifiedSharedMemoryClause();
10332
0
    break;
10333
0
  case llvm::omp::OMPC_reverse_offload:
10334
0
    C = new (Context) OMPReverseOffloadClause();
10335
0
    break;
10336
0
  case llvm::omp::OMPC_dynamic_allocators:
10337
0
    C = new (Context) OMPDynamicAllocatorsClause();
10338
0
    break;
10339
0
  case llvm::omp::OMPC_atomic_default_mem_order:
10340
0
    C = new (Context) OMPAtomicDefaultMemOrderClause();
10341
0
    break;
10342
0
  case llvm::omp::OMPC_at:
10343
0
    C = new (Context) OMPAtClause();
10344
0
    break;
10345
0
  case llvm::omp::OMPC_severity:
10346
0
    C = new (Context) OMPSeverityClause();
10347
0
    break;
10348
0
  case llvm::omp::OMPC_message:
10349
0
    C = new (Context) OMPMessageClause();
10350
0
    break;
10351
0
  case llvm::omp::OMPC_private:
10352
0
    C = OMPPrivateClause::CreateEmpty(Context, Record.readInt());
10353
0
    break;
10354
0
  case llvm::omp::OMPC_firstprivate:
10355
0
    C = OMPFirstprivateClause::CreateEmpty(Context, Record.readInt());
10356
0
    break;
10357
0
  case llvm::omp::OMPC_lastprivate:
10358
0
    C = OMPLastprivateClause::CreateEmpty(Context, Record.readInt());
10359
0
    break;
10360
0
  case llvm::omp::OMPC_shared:
10361
0
    C = OMPSharedClause::CreateEmpty(Context, Record.readInt());
10362
0
    break;
10363
0
  case llvm::omp::OMPC_reduction: {
10364
0
    unsigned N = Record.readInt();
10365
0
    auto Modifier = Record.readEnum<OpenMPReductionClauseModifier>();
10366
0
    C = OMPReductionClause::CreateEmpty(Context, N, Modifier);
10367
0
    break;
10368
0
  }
10369
0
  case llvm::omp::OMPC_task_reduction:
10370
0
    C = OMPTaskReductionClause::CreateEmpty(Context, Record.readInt());
10371
0
    break;
10372
0
  case llvm::omp::OMPC_in_reduction:
10373
0
    C = OMPInReductionClause::CreateEmpty(Context, Record.readInt());
10374
0
    break;
10375
0
  case llvm::omp::OMPC_linear:
10376
0
    C = OMPLinearClause::CreateEmpty(Context, Record.readInt());
10377
0
    break;
10378
0
  case llvm::omp::OMPC_aligned:
10379
0
    C = OMPAlignedClause::CreateEmpty(Context, Record.readInt());
10380
0
    break;
10381
0
  case llvm::omp::OMPC_copyin:
10382
0
    C = OMPCopyinClause::CreateEmpty(Context, Record.readInt());
10383
0
    break;
10384
0
  case llvm::omp::OMPC_copyprivate:
10385
0
    C = OMPCopyprivateClause::CreateEmpty(Context, Record.readInt());
10386
0
    break;
10387
0
  case llvm::omp::OMPC_flush:
10388
0
    C = OMPFlushClause::CreateEmpty(Context, Record.readInt());
10389
0
    break;
10390
0
  case llvm::omp::OMPC_depobj:
10391
0
    C = OMPDepobjClause::CreateEmpty(Context);
10392
0
    break;
10393
0
  case llvm::omp::OMPC_depend: {
10394
0
    unsigned NumVars = Record.readInt();
10395
0
    unsigned NumLoops = Record.readInt();
10396
0
    C = OMPDependClause::CreateEmpty(Context, NumVars, NumLoops);
10397
0
    break;
10398
0
  }
10399
0
  case llvm::omp::OMPC_device:
10400
0
    C = new (Context) OMPDeviceClause();
10401
0
    break;
10402
0
  case llvm::omp::OMPC_map: {
10403
0
    OMPMappableExprListSizeTy Sizes;
10404
0
    Sizes.NumVars = Record.readInt();
10405
0
    Sizes.NumUniqueDeclarations = Record.readInt();
10406
0
    Sizes.NumComponentLists = Record.readInt();
10407
0
    Sizes.NumComponents = Record.readInt();
10408
0
    C = OMPMapClause::CreateEmpty(Context, Sizes);
10409
0
    break;
10410
0
  }
10411
0
  case llvm::omp::OMPC_num_teams:
10412
0
    C = new (Context) OMPNumTeamsClause();
10413
0
    break;
10414
0
  case llvm::omp::OMPC_thread_limit:
10415
0
    C = new (Context) OMPThreadLimitClause();
10416
0
    break;
10417
0
  case llvm::omp::OMPC_priority:
10418
0
    C = new (Context) OMPPriorityClause();
10419
0
    break;
10420
0
  case llvm::omp::OMPC_grainsize:
10421
0
    C = new (Context) OMPGrainsizeClause();
10422
0
    break;
10423
0
  case llvm::omp::OMPC_num_tasks:
10424
0
    C = new (Context) OMPNumTasksClause();
10425
0
    break;
10426
0
  case llvm::omp::OMPC_hint:
10427
0
    C = new (Context) OMPHintClause();
10428
0
    break;
10429
0
  case llvm::omp::OMPC_dist_schedule:
10430
0
    C = new (Context) OMPDistScheduleClause();
10431
0
    break;
10432
0
  case llvm::omp::OMPC_defaultmap:
10433
0
    C = new (Context) OMPDefaultmapClause();
10434
0
    break;
10435
0
  case llvm::omp::OMPC_to: {
10436
0
    OMPMappableExprListSizeTy Sizes;
10437
0
    Sizes.NumVars = Record.readInt();
10438
0
    Sizes.NumUniqueDeclarations = Record.readInt();
10439
0
    Sizes.NumComponentLists = Record.readInt();
10440
0
    Sizes.NumComponents = Record.readInt();
10441
0
    C = OMPToClause::CreateEmpty(Context, Sizes);
10442
0
    break;
10443
0
  }
10444
0
  case llvm::omp::OMPC_from: {
10445
0
    OMPMappableExprListSizeTy Sizes;
10446
0
    Sizes.NumVars = Record.readInt();
10447
0
    Sizes.NumUniqueDeclarations = Record.readInt();
10448
0
    Sizes.NumComponentLists = Record.readInt();
10449
0
    Sizes.NumComponents = Record.readInt();
10450
0
    C = OMPFromClause::CreateEmpty(Context, Sizes);
10451
0
    break;
10452
0
  }
10453
0
  case llvm::omp::OMPC_use_device_ptr: {
10454
0
    OMPMappableExprListSizeTy Sizes;
10455
0
    Sizes.NumVars = Record.readInt();
10456
0
    Sizes.NumUniqueDeclarations = Record.readInt();
10457
0
    Sizes.NumComponentLists = Record.readInt();
10458
0
    Sizes.NumComponents = Record.readInt();
10459
0
    C = OMPUseDevicePtrClause::CreateEmpty(Context, Sizes);
10460
0
    break;
10461
0
  }
10462
0
  case llvm::omp::OMPC_use_device_addr: {
10463
0
    OMPMappableExprListSizeTy Sizes;
10464
0
    Sizes.NumVars = Record.readInt();
10465
0
    Sizes.NumUniqueDeclarations = Record.readInt();
10466
0
    Sizes.NumComponentLists = Record.readInt();
10467
0
    Sizes.NumComponents = Record.readInt();
10468
0
    C = OMPUseDeviceAddrClause::CreateEmpty(Context, Sizes);
10469
0
    break;
10470
0
  }
10471
0
  case llvm::omp::OMPC_is_device_ptr: {
10472
0
    OMPMappableExprListSizeTy Sizes;
10473
0
    Sizes.NumVars = Record.readInt();
10474
0
    Sizes.NumUniqueDeclarations = Record.readInt();
10475
0
    Sizes.NumComponentLists = Record.readInt();
10476
0
    Sizes.NumComponents = Record.readInt();
10477
0
    C = OMPIsDevicePtrClause::CreateEmpty(Context, Sizes);
10478
0
    break;
10479
0
  }
10480
0
  case llvm::omp::OMPC_has_device_addr: {
10481
0
    OMPMappableExprListSizeTy Sizes;
10482
0
    Sizes.NumVars = Record.readInt();
10483
0
    Sizes.NumUniqueDeclarations = Record.readInt();
10484
0
    Sizes.NumComponentLists = Record.readInt();
10485
0
    Sizes.NumComponents = Record.readInt();
10486
0
    C = OMPHasDeviceAddrClause::CreateEmpty(Context, Sizes);
10487
0
    break;
10488
0
  }
10489
0
  case llvm::omp::OMPC_allocate:
10490
0
    C = OMPAllocateClause::CreateEmpty(Context, Record.readInt());
10491
0
    break;
10492
0
  case llvm::omp::OMPC_nontemporal:
10493
0
    C = OMPNontemporalClause::CreateEmpty(Context, Record.readInt());
10494
0
    break;
10495
0
  case llvm::omp::OMPC_inclusive:
10496
0
    C = OMPInclusiveClause::CreateEmpty(Context, Record.readInt());
10497
0
    break;
10498
0
  case llvm::omp::OMPC_exclusive:
10499
0
    C = OMPExclusiveClause::CreateEmpty(Context, Record.readInt());
10500
0
    break;
10501
0
  case llvm::omp::OMPC_order:
10502
0
    C = new (Context) OMPOrderClause();
10503
0
    break;
10504
0
  case llvm::omp::OMPC_init:
10505
0
    C = OMPInitClause::CreateEmpty(Context, Record.readInt());
10506
0
    break;
10507
0
  case llvm::omp::OMPC_use:
10508
0
    C = new (Context) OMPUseClause();
10509
0
    break;
10510
0
  case llvm::omp::OMPC_destroy:
10511
0
    C = new (Context) OMPDestroyClause();
10512
0
    break;
10513
0
  case llvm::omp::OMPC_novariants:
10514
0
    C = new (Context) OMPNovariantsClause();
10515
0
    break;
10516
0
  case llvm::omp::OMPC_nocontext:
10517
0
    C = new (Context) OMPNocontextClause();
10518
0
    break;
10519
0
  case llvm::omp::OMPC_detach:
10520
0
    C = new (Context) OMPDetachClause();
10521
0
    break;
10522
0
  case llvm::omp::OMPC_uses_allocators:
10523
0
    C = OMPUsesAllocatorsClause::CreateEmpty(Context, Record.readInt());
10524
0
    break;
10525
0
  case llvm::omp::OMPC_affinity:
10526
0
    C = OMPAffinityClause::CreateEmpty(Context, Record.readInt());
10527
0
    break;
10528
0
  case llvm::omp::OMPC_filter:
10529
0
    C = new (Context) OMPFilterClause();
10530
0
    break;
10531
0
  case llvm::omp::OMPC_bind:
10532
0
    C = OMPBindClause::CreateEmpty(Context);
10533
0
    break;
10534
0
  case llvm::omp::OMPC_align:
10535
0
    C = new (Context) OMPAlignClause();
10536
0
    break;
10537
0
  case llvm::omp::OMPC_ompx_dyn_cgroup_mem:
10538
0
    C = new (Context) OMPXDynCGroupMemClause();
10539
0
    break;
10540
0
  case llvm::omp::OMPC_doacross: {
10541
0
    unsigned NumVars = Record.readInt();
10542
0
    unsigned NumLoops = Record.readInt();
10543
0
    C = OMPDoacrossClause::CreateEmpty(Context, NumVars, NumLoops);
10544
0
    break;
10545
0
  }
10546
0
  case llvm::omp::OMPC_ompx_attribute:
10547
0
    C = new (Context) OMPXAttributeClause();
10548
0
    break;
10549
0
  case llvm::omp::OMPC_ompx_bare:
10550
0
    C = new (Context) OMPXBareClause();
10551
0
    break;
10552
0
#define OMP_CLAUSE_NO_CLASS(Enum, Str)                                         \
10553
0
  case llvm::omp::Enum:                                                        \
10554
0
    break;
10555
0
#include "llvm/Frontend/OpenMP/OMPKinds.def"
10556
0
  default:
10557
0
    break;
10558
0
  }
10559
0
  assert(C && "Unknown OMPClause type");
10560
10561
0
  Visit(C);
10562
0
  C->setLocStart(Record.readSourceLocation());
10563
0
  C->setLocEnd(Record.readSourceLocation());
10564
10565
0
  return C;
10566
0
}
10567
10568
0
void OMPClauseReader::VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C) {
10569
0
  C->setPreInitStmt(Record.readSubStmt(),
10570
0
                    static_cast<OpenMPDirectiveKind>(Record.readInt()));
10571
0
}
10572
10573
0
void OMPClauseReader::VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C) {
10574
0
  VisitOMPClauseWithPreInit(C);
10575
0
  C->setPostUpdateExpr(Record.readSubExpr());
10576
0
}
10577
10578
0
void OMPClauseReader::VisitOMPIfClause(OMPIfClause *C) {
10579
0
  VisitOMPClauseWithPreInit(C);
10580
0
  C->setNameModifier(static_cast<OpenMPDirectiveKind>(Record.readInt()));
10581
0
  C->setNameModifierLoc(Record.readSourceLocation());
10582
0
  C->setColonLoc(Record.readSourceLocation());
10583
0
  C->setCondition(Record.readSubExpr());
10584
0
  C->setLParenLoc(Record.readSourceLocation());
10585
0
}
10586
10587
0
void OMPClauseReader::VisitOMPFinalClause(OMPFinalClause *C) {
10588
0
  VisitOMPClauseWithPreInit(C);
10589
0
  C->setCondition(Record.readSubExpr());
10590
0
  C->setLParenLoc(Record.readSourceLocation());
10591
0
}
10592
10593
0
void OMPClauseReader::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
10594
0
  VisitOMPClauseWithPreInit(C);
10595
0
  C->setNumThreads(Record.readSubExpr());
10596
0
  C->setLParenLoc(Record.readSourceLocation());
10597
0
}
10598
10599
0
void OMPClauseReader::VisitOMPSafelenClause(OMPSafelenClause *C) {
10600
0
  C->setSafelen(Record.readSubExpr());
10601
0
  C->setLParenLoc(Record.readSourceLocation());
10602
0
}
10603
10604
0
void OMPClauseReader::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
10605
0
  C->setSimdlen(Record.readSubExpr());
10606
0
  C->setLParenLoc(Record.readSourceLocation());
10607
0
}
10608
10609
0
void OMPClauseReader::VisitOMPSizesClause(OMPSizesClause *C) {
10610
0
  for (Expr *&E : C->getSizesRefs())
10611
0
    E = Record.readSubExpr();
10612
0
  C->setLParenLoc(Record.readSourceLocation());
10613
0
}
10614
10615
0
void OMPClauseReader::VisitOMPFullClause(OMPFullClause *C) {}
10616
10617
0
void OMPClauseReader::VisitOMPPartialClause(OMPPartialClause *C) {
10618
0
  C->setFactor(Record.readSubExpr());
10619
0
  C->setLParenLoc(Record.readSourceLocation());
10620
0
}
10621
10622
0
void OMPClauseReader::VisitOMPAllocatorClause(OMPAllocatorClause *C) {
10623
0
  C->setAllocator(Record.readExpr());
10624
0
  C->setLParenLoc(Record.readSourceLocation());
10625
0
}
10626
10627
0
void OMPClauseReader::VisitOMPCollapseClause(OMPCollapseClause *C) {
10628
0
  C->setNumForLoops(Record.readSubExpr());
10629
0
  C->setLParenLoc(Record.readSourceLocation());
10630
0
}
10631
10632
0
void OMPClauseReader::VisitOMPDefaultClause(OMPDefaultClause *C) {
10633
0
  C->setDefaultKind(static_cast<llvm::omp::DefaultKind>(Record.readInt()));
10634
0
  C->setLParenLoc(Record.readSourceLocation());
10635
0
  C->setDefaultKindKwLoc(Record.readSourceLocation());
10636
0
}
10637
10638
0
void OMPClauseReader::VisitOMPProcBindClause(OMPProcBindClause *C) {
10639
0
  C->setProcBindKind(static_cast<llvm::omp::ProcBindKind>(Record.readInt()));
10640
0
  C->setLParenLoc(Record.readSourceLocation());
10641
0
  C->setProcBindKindKwLoc(Record.readSourceLocation());
10642
0
}
10643
10644
0
void OMPClauseReader::VisitOMPScheduleClause(OMPScheduleClause *C) {
10645
0
  VisitOMPClauseWithPreInit(C);
10646
0
  C->setScheduleKind(
10647
0
       static_cast<OpenMPScheduleClauseKind>(Record.readInt()));
10648
0
  C->setFirstScheduleModifier(
10649
0
      static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
10650
0
  C->setSecondScheduleModifier(
10651
0
      static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
10652
0
  C->setChunkSize(Record.readSubExpr());
10653
0
  C->setLParenLoc(Record.readSourceLocation());
10654
0
  C->setFirstScheduleModifierLoc(Record.readSourceLocation());
10655
0
  C->setSecondScheduleModifierLoc(Record.readSourceLocation());
10656
0
  C->setScheduleKindLoc(Record.readSourceLocation());
10657
0
  C->setCommaLoc(Record.readSourceLocation());
10658
0
}
10659
10660
0
void OMPClauseReader::VisitOMPOrderedClause(OMPOrderedClause *C) {
10661
0
  C->setNumForLoops(Record.readSubExpr());
10662
0
  for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
10663
0
    C->setLoopNumIterations(I, Record.readSubExpr());
10664
0
  for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
10665
0
    C->setLoopCounter(I, Record.readSubExpr());
10666
0
  C->setLParenLoc(Record.readSourceLocation());
10667
0
}
10668
10669
0
void OMPClauseReader::VisitOMPDetachClause(OMPDetachClause *C) {
10670
0
  C->setEventHandler(Record.readSubExpr());
10671
0
  C->setLParenLoc(Record.readSourceLocation());
10672
0
}
10673
10674
0
void OMPClauseReader::VisitOMPNowaitClause(OMPNowaitClause *) {}
10675
10676
0
void OMPClauseReader::VisitOMPUntiedClause(OMPUntiedClause *) {}
10677
10678
0
void OMPClauseReader::VisitOMPMergeableClause(OMPMergeableClause *) {}
10679
10680
0
void OMPClauseReader::VisitOMPReadClause(OMPReadClause *) {}
10681
10682
0
void OMPClauseReader::VisitOMPWriteClause(OMPWriteClause *) {}
10683
10684
0
void OMPClauseReader::VisitOMPUpdateClause(OMPUpdateClause *C) {
10685
0
  if (C->isExtended()) {
10686
0
    C->setLParenLoc(Record.readSourceLocation());
10687
0
    C->setArgumentLoc(Record.readSourceLocation());
10688
0
    C->setDependencyKind(Record.readEnum<OpenMPDependClauseKind>());
10689
0
  }
10690
0
}
10691
10692
0
void OMPClauseReader::VisitOMPCaptureClause(OMPCaptureClause *) {}
10693
10694
0
void OMPClauseReader::VisitOMPCompareClause(OMPCompareClause *) {}
10695
10696
// Read the parameter of fail clause. This will have been saved when
10697
// OMPClauseWriter is called.
10698
0
void OMPClauseReader::VisitOMPFailClause(OMPFailClause *C) {
10699
0
  C->setLParenLoc(Record.readSourceLocation());
10700
0
  SourceLocation FailParameterLoc = Record.readSourceLocation();
10701
0
  C->setFailParameterLoc(FailParameterLoc);
10702
0
  OpenMPClauseKind CKind = Record.readEnum<OpenMPClauseKind>();
10703
0
  C->setFailParameter(CKind);
10704
0
}
10705
10706
0
void OMPClauseReader::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
10707
10708
0
void OMPClauseReader::VisitOMPAcqRelClause(OMPAcqRelClause *) {}
10709
10710
0
void OMPClauseReader::VisitOMPAcquireClause(OMPAcquireClause *) {}
10711
10712
0
void OMPClauseReader::VisitOMPReleaseClause(OMPReleaseClause *) {}
10713
10714
0
void OMPClauseReader::VisitOMPRelaxedClause(OMPRelaxedClause *) {}
10715
10716
0
void OMPClauseReader::VisitOMPThreadsClause(OMPThreadsClause *) {}
10717
10718
0
void OMPClauseReader::VisitOMPSIMDClause(OMPSIMDClause *) {}
10719
10720
0
void OMPClauseReader::VisitOMPNogroupClause(OMPNogroupClause *) {}
10721
10722
0
void OMPClauseReader::VisitOMPInitClause(OMPInitClause *C) {
10723
0
  unsigned NumVars = C->varlist_size();
10724
0
  SmallVector<Expr *, 16> Vars;
10725
0
  Vars.reserve(NumVars);
10726
0
  for (unsigned I = 0; I != NumVars; ++I)
10727
0
    Vars.push_back(Record.readSubExpr());
10728
0
  C->setVarRefs(Vars);
10729
0
  C->setIsTarget(Record.readBool());
10730
0
  C->setIsTargetSync(Record.readBool());
10731
0
  C->setLParenLoc(Record.readSourceLocation());
10732
0
  C->setVarLoc(Record.readSourceLocation());
10733
0
}
10734
10735
0
void OMPClauseReader::VisitOMPUseClause(OMPUseClause *C) {
10736
0
  C->setInteropVar(Record.readSubExpr());
10737
0
  C->setLParenLoc(Record.readSourceLocation());
10738
0
  C->setVarLoc(Record.readSourceLocation());
10739
0
}
10740
10741
0
void OMPClauseReader::VisitOMPDestroyClause(OMPDestroyClause *C) {
10742
0
  C->setInteropVar(Record.readSubExpr());
10743
0
  C->setLParenLoc(Record.readSourceLocation());
10744
0
  C->setVarLoc(Record.readSourceLocation());
10745
0
}
10746
10747
0
void OMPClauseReader::VisitOMPNovariantsClause(OMPNovariantsClause *C) {
10748
0
  VisitOMPClauseWithPreInit(C);
10749
0
  C->setCondition(Record.readSubExpr());
10750
0
  C->setLParenLoc(Record.readSourceLocation());
10751
0
}
10752
10753
0
void OMPClauseReader::VisitOMPNocontextClause(OMPNocontextClause *C) {
10754
0
  VisitOMPClauseWithPreInit(C);
10755
0
  C->setCondition(Record.readSubExpr());
10756
0
  C->setLParenLoc(Record.readSourceLocation());
10757
0
}
10758
10759
0
void OMPClauseReader::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}
10760
10761
void OMPClauseReader::VisitOMPUnifiedSharedMemoryClause(
10762
0
    OMPUnifiedSharedMemoryClause *) {}
10763
10764
0
void OMPClauseReader::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}
10765
10766
void
10767
0
OMPClauseReader::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) {
10768
0
}
10769
10770
void OMPClauseReader::VisitOMPAtomicDefaultMemOrderClause(
10771
0
    OMPAtomicDefaultMemOrderClause *C) {
10772
0
  C->setAtomicDefaultMemOrderKind(
10773
0
      static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Record.readInt()));
10774
0
  C->setLParenLoc(Record.readSourceLocation());
10775
0
  C->setAtomicDefaultMemOrderKindKwLoc(Record.readSourceLocation());
10776
0
}
10777
10778
0
void OMPClauseReader::VisitOMPAtClause(OMPAtClause *C) {
10779
0
  C->setAtKind(static_cast<OpenMPAtClauseKind>(Record.readInt()));
10780
0
  C->setLParenLoc(Record.readSourceLocation());
10781
0
  C->setAtKindKwLoc(Record.readSourceLocation());
10782
0
}
10783
10784
0
void OMPClauseReader::VisitOMPSeverityClause(OMPSeverityClause *C) {
10785
0
  C->setSeverityKind(static_cast<OpenMPSeverityClauseKind>(Record.readInt()));
10786
0
  C->setLParenLoc(Record.readSourceLocation());
10787
0
  C->setSeverityKindKwLoc(Record.readSourceLocation());
10788
0
}
10789
10790
0
void OMPClauseReader::VisitOMPMessageClause(OMPMessageClause *C) {
10791
0
  C->setMessageString(Record.readSubExpr());
10792
0
  C->setLParenLoc(Record.readSourceLocation());
10793
0
}
10794
10795
0
void OMPClauseReader::VisitOMPPrivateClause(OMPPrivateClause *C) {
10796
0
  C->setLParenLoc(Record.readSourceLocation());
10797
0
  unsigned NumVars = C->varlist_size();
10798
0
  SmallVector<Expr *, 16> Vars;
10799
0
  Vars.reserve(NumVars);
10800
0
  for (unsigned i = 0; i != NumVars; ++i)
10801
0
    Vars.push_back(Record.readSubExpr());
10802
0
  C->setVarRefs(Vars);
10803
0
  Vars.clear();
10804
0
  for (unsigned i = 0; i != NumVars; ++i)
10805
0
    Vars.push_back(Record.readSubExpr());
10806
0
  C->setPrivateCopies(Vars);
10807
0
}
10808
10809
0
void OMPClauseReader::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
10810
0
  VisitOMPClauseWithPreInit(C);
10811
0
  C->setLParenLoc(Record.readSourceLocation());
10812
0
  unsigned NumVars = C->varlist_size();
10813
0
  SmallVector<Expr *, 16> Vars;
10814
0
  Vars.reserve(NumVars);
10815
0
  for (unsigned i = 0; i != NumVars; ++i)
10816
0
    Vars.push_back(Record.readSubExpr());
10817
0
  C->setVarRefs(Vars);
10818
0
  Vars.clear();
10819
0
  for (unsigned i = 0; i != NumVars; ++i)
10820
0
    Vars.push_back(Record.readSubExpr());
10821
0
  C->setPrivateCopies(Vars);
10822
0
  Vars.clear();
10823
0
  for (unsigned i = 0; i != NumVars; ++i)
10824
0
    Vars.push_back(Record.readSubExpr());
10825
0
  C->setInits(Vars);
10826
0
}
10827
10828
0
void OMPClauseReader::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
10829
0
  VisitOMPClauseWithPostUpdate(C);
10830
0
  C->setLParenLoc(Record.readSourceLocation());
10831
0
  C->setKind(Record.readEnum<OpenMPLastprivateModifier>());
10832
0
  C->setKindLoc(Record.readSourceLocation());
10833
0
  C->setColonLoc(Record.readSourceLocation());
10834
0
  unsigned NumVars = C->varlist_size();
10835
0
  SmallVector<Expr *, 16> Vars;
10836
0
  Vars.reserve(NumVars);
10837
0
  for (unsigned i = 0; i != NumVars; ++i)
10838
0
    Vars.push_back(Record.readSubExpr());
10839
0
  C->setVarRefs(Vars);
10840
0
  Vars.clear();
10841
0
  for (unsigned i = 0; i != NumVars; ++i)
10842
0
    Vars.push_back(Record.readSubExpr());
10843
0
  C->setPrivateCopies(Vars);
10844
0
  Vars.clear();
10845
0
  for (unsigned i = 0; i != NumVars; ++i)
10846
0
    Vars.push_back(Record.readSubExpr());
10847
0
  C->setSourceExprs(Vars);
10848
0
  Vars.clear();
10849
0
  for (unsigned i = 0; i != NumVars; ++i)
10850
0
    Vars.push_back(Record.readSubExpr());
10851
0
  C->setDestinationExprs(Vars);
10852
0
  Vars.clear();
10853
0
  for (unsigned i = 0; i != NumVars; ++i)
10854
0
    Vars.push_back(Record.readSubExpr());
10855
0
  C->setAssignmentOps(Vars);
10856
0
}
10857
10858
0
void OMPClauseReader::VisitOMPSharedClause(OMPSharedClause *C) {
10859
0
  C->setLParenLoc(Record.readSourceLocation());
10860
0
  unsigned NumVars = C->varlist_size();
10861
0
  SmallVector<Expr *, 16> Vars;
10862
0
  Vars.reserve(NumVars);
10863
0
  for (unsigned i = 0; i != NumVars; ++i)
10864
0
    Vars.push_back(Record.readSubExpr());
10865
0
  C->setVarRefs(Vars);
10866
0
}
10867
10868
0
void OMPClauseReader::VisitOMPReductionClause(OMPReductionClause *C) {
10869
0
  VisitOMPClauseWithPostUpdate(C);
10870
0
  C->setLParenLoc(Record.readSourceLocation());
10871
0
  C->setModifierLoc(Record.readSourceLocation());
10872
0
  C->setColonLoc(Record.readSourceLocation());
10873
0
  NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
10874
0
  DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
10875
0
  C->setQualifierLoc(NNSL);
10876
0
  C->setNameInfo(DNI);
10877
10878
0
  unsigned NumVars = C->varlist_size();
10879
0
  SmallVector<Expr *, 16> Vars;
10880
0
  Vars.reserve(NumVars);
10881
0
  for (unsigned i = 0; i != NumVars; ++i)
10882
0
    Vars.push_back(Record.readSubExpr());
10883
0
  C->setVarRefs(Vars);
10884
0
  Vars.clear();
10885
0
  for (unsigned i = 0; i != NumVars; ++i)
10886
0
    Vars.push_back(Record.readSubExpr());
10887
0
  C->setPrivates(Vars);
10888
0
  Vars.clear();
10889
0
  for (unsigned i = 0; i != NumVars; ++i)
10890
0
    Vars.push_back(Record.readSubExpr());
10891
0
  C->setLHSExprs(Vars);
10892
0
  Vars.clear();
10893
0
  for (unsigned i = 0; i != NumVars; ++i)
10894
0
    Vars.push_back(Record.readSubExpr());
10895
0
  C->setRHSExprs(Vars);
10896
0
  Vars.clear();
10897
0
  for (unsigned i = 0; i != NumVars; ++i)
10898
0
    Vars.push_back(Record.readSubExpr());
10899
0
  C->setReductionOps(Vars);
10900
0
  if (C->getModifier() == OMPC_REDUCTION_inscan) {
10901
0
    Vars.clear();
10902
0
    for (unsigned i = 0; i != NumVars; ++i)
10903
0
      Vars.push_back(Record.readSubExpr());
10904
0
    C->setInscanCopyOps(Vars);
10905
0
    Vars.clear();
10906
0
    for (unsigned i = 0; i != NumVars; ++i)
10907
0
      Vars.push_back(Record.readSubExpr());
10908
0
    C->setInscanCopyArrayTemps(Vars);
10909
0
    Vars.clear();
10910
0
    for (unsigned i = 0; i != NumVars; ++i)
10911
0
      Vars.push_back(Record.readSubExpr());
10912
0
    C->setInscanCopyArrayElems(Vars);
10913
0
  }
10914
0
}
10915
10916
0
void OMPClauseReader::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
10917
0
  VisitOMPClauseWithPostUpdate(C);
10918
0
  C->setLParenLoc(Record.readSourceLocation());
10919
0
  C->setColonLoc(Record.readSourceLocation());
10920
0
  NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
10921
0
  DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
10922
0
  C->setQualifierLoc(NNSL);
10923
0
  C->setNameInfo(DNI);
10924
10925
0
  unsigned NumVars = C->varlist_size();
10926
0
  SmallVector<Expr *, 16> Vars;
10927
0
  Vars.reserve(NumVars);
10928
0
  for (unsigned I = 0; I != NumVars; ++I)
10929
0
    Vars.push_back(Record.readSubExpr());
10930
0
  C->setVarRefs(Vars);
10931
0
  Vars.clear();
10932
0
  for (unsigned I = 0; I != NumVars; ++I)
10933
0
    Vars.push_back(Record.readSubExpr());
10934
0
  C->setPrivates(Vars);
10935
0
  Vars.clear();
10936
0
  for (unsigned I = 0; I != NumVars; ++I)
10937
0
    Vars.push_back(Record.readSubExpr());
10938
0
  C->setLHSExprs(Vars);
10939
0
  Vars.clear();
10940
0
  for (unsigned I = 0; I != NumVars; ++I)
10941
0
    Vars.push_back(Record.readSubExpr());
10942
0
  C->setRHSExprs(Vars);
10943
0
  Vars.clear();
10944
0
  for (unsigned I = 0; I != NumVars; ++I)
10945
0
    Vars.push_back(Record.readSubExpr());
10946
0
  C->setReductionOps(Vars);
10947
0
}
10948
10949
0
void OMPClauseReader::VisitOMPInReductionClause(OMPInReductionClause *C) {
10950
0
  VisitOMPClauseWithPostUpdate(C);
10951
0
  C->setLParenLoc(Record.readSourceLocation());
10952
0
  C->setColonLoc(Record.readSourceLocation());
10953
0
  NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
10954
0
  DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
10955
0
  C->setQualifierLoc(NNSL);
10956
0
  C->setNameInfo(DNI);
10957
10958
0
  unsigned NumVars = C->varlist_size();
10959
0
  SmallVector<Expr *, 16> Vars;
10960
0
  Vars.reserve(NumVars);
10961
0
  for (unsigned I = 0; I != NumVars; ++I)
10962
0
    Vars.push_back(Record.readSubExpr());
10963
0
  C->setVarRefs(Vars);
10964
0
  Vars.clear();
10965
0
  for (unsigned I = 0; I != NumVars; ++I)
10966
0
    Vars.push_back(Record.readSubExpr());
10967
0
  C->setPrivates(Vars);
10968
0
  Vars.clear();
10969
0
  for (unsigned I = 0; I != NumVars; ++I)
10970
0
    Vars.push_back(Record.readSubExpr());
10971
0
  C->setLHSExprs(Vars);
10972
0
  Vars.clear();
10973
0
  for (unsigned I = 0; I != NumVars; ++I)
10974
0
    Vars.push_back(Record.readSubExpr());
10975
0
  C->setRHSExprs(Vars);
10976
0
  Vars.clear();
10977
0
  for (unsigned I = 0; I != NumVars; ++I)
10978
0
    Vars.push_back(Record.readSubExpr());
10979
0
  C->setReductionOps(Vars);
10980
0
  Vars.clear();
10981
0
  for (unsigned I = 0; I != NumVars; ++I)
10982
0
    Vars.push_back(Record.readSubExpr());
10983
0
  C->setTaskgroupDescriptors(Vars);
10984
0
}
10985
10986
0
void OMPClauseReader::VisitOMPLinearClause(OMPLinearClause *C) {
10987
0
  VisitOMPClauseWithPostUpdate(C);
10988
0
  C->setLParenLoc(Record.readSourceLocation());
10989
0
  C->setColonLoc(Record.readSourceLocation());
10990
0
  C->setModifier(static_cast<OpenMPLinearClauseKind>(Record.readInt()));
10991
0
  C->setModifierLoc(Record.readSourceLocation());
10992
0
  unsigned NumVars = C->varlist_size();
10993
0
  SmallVector<Expr *, 16> Vars;
10994
0
  Vars.reserve(NumVars);
10995
0
  for (unsigned i = 0; i != NumVars; ++i)
10996
0
    Vars.push_back(Record.readSubExpr());
10997
0
  C->setVarRefs(Vars);
10998
0
  Vars.clear();
10999
0
  for (unsigned i = 0; i != NumVars; ++i)
11000
0
    Vars.push_back(Record.readSubExpr());
11001
0
  C->setPrivates(Vars);
11002
0
  Vars.clear();
11003
0
  for (unsigned i = 0; i != NumVars; ++i)
11004
0
    Vars.push_back(Record.readSubExpr());
11005
0
  C->setInits(Vars);
11006
0
  Vars.clear();
11007
0
  for (unsigned i = 0; i != NumVars; ++i)
11008
0
    Vars.push_back(Record.readSubExpr());
11009
0
  C->setUpdates(Vars);
11010
0
  Vars.clear();
11011
0
  for (unsigned i = 0; i != NumVars; ++i)
11012
0
    Vars.push_back(Record.readSubExpr());
11013
0
  C->setFinals(Vars);
11014
0
  C->setStep(Record.readSubExpr());
11015
0
  C->setCalcStep(Record.readSubExpr());
11016
0
  Vars.clear();
11017
0
  for (unsigned I = 0; I != NumVars + 1; ++I)
11018
0
    Vars.push_back(Record.readSubExpr());
11019
0
  C->setUsedExprs(Vars);
11020
0
}
11021
11022
0
void OMPClauseReader::VisitOMPAlignedClause(OMPAlignedClause *C) {
11023
0
  C->setLParenLoc(Record.readSourceLocation());
11024
0
  C->setColonLoc(Record.readSourceLocation());
11025
0
  unsigned NumVars = C->varlist_size();
11026
0
  SmallVector<Expr *, 16> Vars;
11027
0
  Vars.reserve(NumVars);
11028
0
  for (unsigned i = 0; i != NumVars; ++i)
11029
0
    Vars.push_back(Record.readSubExpr());
11030
0
  C->setVarRefs(Vars);
11031
0
  C->setAlignment(Record.readSubExpr());
11032
0
}
11033
11034
0
void OMPClauseReader::VisitOMPCopyinClause(OMPCopyinClause *C) {
11035
0
  C->setLParenLoc(Record.readSourceLocation());
11036
0
  unsigned NumVars = C->varlist_size();
11037
0
  SmallVector<Expr *, 16> Exprs;
11038
0
  Exprs.reserve(NumVars);
11039
0
  for (unsigned i = 0; i != NumVars; ++i)
11040
0
    Exprs.push_back(Record.readSubExpr());
11041
0
  C->setVarRefs(Exprs);
11042
0
  Exprs.clear();
11043
0
  for (unsigned i = 0; i != NumVars; ++i)
11044
0
    Exprs.push_back(Record.readSubExpr());
11045
0
  C->setSourceExprs(Exprs);
11046
0
  Exprs.clear();
11047
0
  for (unsigned i = 0; i != NumVars; ++i)
11048
0
    Exprs.push_back(Record.readSubExpr());
11049
0
  C->setDestinationExprs(Exprs);
11050
0
  Exprs.clear();
11051
0
  for (unsigned i = 0; i != NumVars; ++i)
11052
0
    Exprs.push_back(Record.readSubExpr());
11053
0
  C->setAssignmentOps(Exprs);
11054
0
}
11055
11056
0
void OMPClauseReader::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
11057
0
  C->setLParenLoc(Record.readSourceLocation());
11058
0
  unsigned NumVars = C->varlist_size();
11059
0
  SmallVector<Expr *, 16> Exprs;
11060
0
  Exprs.reserve(NumVars);
11061
0
  for (unsigned i = 0; i != NumVars; ++i)
11062
0
    Exprs.push_back(Record.readSubExpr());
11063
0
  C->setVarRefs(Exprs);
11064
0
  Exprs.clear();
11065
0
  for (unsigned i = 0; i != NumVars; ++i)
11066
0
    Exprs.push_back(Record.readSubExpr());
11067
0
  C->setSourceExprs(Exprs);
11068
0
  Exprs.clear();
11069
0
  for (unsigned i = 0; i != NumVars; ++i)
11070
0
    Exprs.push_back(Record.readSubExpr());
11071
0
  C->setDestinationExprs(Exprs);
11072
0
  Exprs.clear();
11073
0
  for (unsigned i = 0; i != NumVars; ++i)
11074
0
    Exprs.push_back(Record.readSubExpr());
11075
0
  C->setAssignmentOps(Exprs);
11076
0
}
11077
11078
0
void OMPClauseReader::VisitOMPFlushClause(OMPFlushClause *C) {
11079
0
  C->setLParenLoc(Record.readSourceLocation());
11080
0
  unsigned NumVars = C->varlist_size();
11081
0
  SmallVector<Expr *, 16> Vars;
11082
0
  Vars.reserve(NumVars);
11083
0
  for (unsigned i = 0; i != NumVars; ++i)
11084
0
    Vars.push_back(Record.readSubExpr());
11085
0
  C->setVarRefs(Vars);
11086
0
}
11087
11088
0
void OMPClauseReader::VisitOMPDepobjClause(OMPDepobjClause *C) {
11089
0
  C->setDepobj(Record.readSubExpr());
11090
0
  C->setLParenLoc(Record.readSourceLocation());
11091
0
}
11092
11093
0
void OMPClauseReader::VisitOMPDependClause(OMPDependClause *C) {
11094
0
  C->setLParenLoc(Record.readSourceLocation());
11095
0
  C->setModifier(Record.readSubExpr());
11096
0
  C->setDependencyKind(
11097
0
      static_cast<OpenMPDependClauseKind>(Record.readInt()));
11098
0
  C->setDependencyLoc(Record.readSourceLocation());
11099
0
  C->setColonLoc(Record.readSourceLocation());
11100
0
  C->setOmpAllMemoryLoc(Record.readSourceLocation());
11101
0
  unsigned NumVars = C->varlist_size();
11102
0
  SmallVector<Expr *, 16> Vars;
11103
0
  Vars.reserve(NumVars);
11104
0
  for (unsigned I = 0; I != NumVars; ++I)
11105
0
    Vars.push_back(Record.readSubExpr());
11106
0
  C->setVarRefs(Vars);
11107
0
  for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
11108
0
    C->setLoopData(I, Record.readSubExpr());
11109
0
}
11110
11111
0
void OMPClauseReader::VisitOMPDeviceClause(OMPDeviceClause *C) {
11112
0
  VisitOMPClauseWithPreInit(C);
11113
0
  C->setModifier(Record.readEnum<OpenMPDeviceClauseModifier>());
11114
0
  C->setDevice(Record.readSubExpr());
11115
0
  C->setModifierLoc(Record.readSourceLocation());
11116
0
  C->setLParenLoc(Record.readSourceLocation());
11117
0
}
11118
11119
0
void OMPClauseReader::VisitOMPMapClause(OMPMapClause *C) {
11120
0
  C->setLParenLoc(Record.readSourceLocation());
11121
0
  bool HasIteratorModifier = false;
11122
0
  for (unsigned I = 0; I < NumberOfOMPMapClauseModifiers; ++I) {
11123
0
    C->setMapTypeModifier(
11124
0
        I, static_cast<OpenMPMapModifierKind>(Record.readInt()));
11125
0
    C->setMapTypeModifierLoc(I, Record.readSourceLocation());
11126
0
    if (C->getMapTypeModifier(I) == OMPC_MAP_MODIFIER_iterator)
11127
0
      HasIteratorModifier = true;
11128
0
  }
11129
0
  C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
11130
0
  C->setMapperIdInfo(Record.readDeclarationNameInfo());
11131
0
  C->setMapType(
11132
0
     static_cast<OpenMPMapClauseKind>(Record.readInt()));
11133
0
  C->setMapLoc(Record.readSourceLocation());
11134
0
  C->setColonLoc(Record.readSourceLocation());
11135
0
  auto NumVars = C->varlist_size();
11136
0
  auto UniqueDecls = C->getUniqueDeclarationsNum();
11137
0
  auto TotalLists = C->getTotalComponentListNum();
11138
0
  auto TotalComponents = C->getTotalComponentsNum();
11139
11140
0
  SmallVector<Expr *, 16> Vars;
11141
0
  Vars.reserve(NumVars);
11142
0
  for (unsigned i = 0; i != NumVars; ++i)
11143
0
    Vars.push_back(Record.readExpr());
11144
0
  C->setVarRefs(Vars);
11145
11146
0
  SmallVector<Expr *, 16> UDMappers;
11147
0
  UDMappers.reserve(NumVars);
11148
0
  for (unsigned I = 0; I < NumVars; ++I)
11149
0
    UDMappers.push_back(Record.readExpr());
11150
0
  C->setUDMapperRefs(UDMappers);
11151
11152
0
  if (HasIteratorModifier)
11153
0
    C->setIteratorModifier(Record.readExpr());
11154
11155
0
  SmallVector<ValueDecl *, 16> Decls;
11156
0
  Decls.reserve(UniqueDecls);
11157
0
  for (unsigned i = 0; i < UniqueDecls; ++i)
11158
0
    Decls.push_back(Record.readDeclAs<ValueDecl>());
11159
0
  C->setUniqueDecls(Decls);
11160
11161
0
  SmallVector<unsigned, 16> ListsPerDecl;
11162
0
  ListsPerDecl.reserve(UniqueDecls);
11163
0
  for (unsigned i = 0; i < UniqueDecls; ++i)
11164
0
    ListsPerDecl.push_back(Record.readInt());
11165
0
  C->setDeclNumLists(ListsPerDecl);
11166
11167
0
  SmallVector<unsigned, 32> ListSizes;
11168
0
  ListSizes.reserve(TotalLists);
11169
0
  for (unsigned i = 0; i < TotalLists; ++i)
11170
0
    ListSizes.push_back(Record.readInt());
11171
0
  C->setComponentListSizes(ListSizes);
11172
11173
0
  SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
11174
0
  Components.reserve(TotalComponents);
11175
0
  for (unsigned i = 0; i < TotalComponents; ++i) {
11176
0
    Expr *AssociatedExprPr = Record.readExpr();
11177
0
    auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11178
0
    Components.emplace_back(AssociatedExprPr, AssociatedDecl,
11179
0
                            /*IsNonContiguous=*/false);
11180
0
  }
11181
0
  C->setComponents(Components, ListSizes);
11182
0
}
11183
11184
0
void OMPClauseReader::VisitOMPAllocateClause(OMPAllocateClause *C) {
11185
0
  C->setLParenLoc(Record.readSourceLocation());
11186
0
  C->setColonLoc(Record.readSourceLocation());
11187
0
  C->setAllocator(Record.readSubExpr());
11188
0
  unsigned NumVars = C->varlist_size();
11189
0
  SmallVector<Expr *, 16> Vars;
11190
0
  Vars.reserve(NumVars);
11191
0
  for (unsigned i = 0; i != NumVars; ++i)
11192
0
    Vars.push_back(Record.readSubExpr());
11193
0
  C->setVarRefs(Vars);
11194
0
}
11195
11196
0
void OMPClauseReader::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
11197
0
  VisitOMPClauseWithPreInit(C);
11198
0
  C->setNumTeams(Record.readSubExpr());
11199
0
  C->setLParenLoc(Record.readSourceLocation());
11200
0
}
11201
11202
0
void OMPClauseReader::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
11203
0
  VisitOMPClauseWithPreInit(C);
11204
0
  C->setThreadLimit(Record.readSubExpr());
11205
0
  C->setLParenLoc(Record.readSourceLocation());
11206
0
}
11207
11208
0
void OMPClauseReader::VisitOMPPriorityClause(OMPPriorityClause *C) {
11209
0
  VisitOMPClauseWithPreInit(C);
11210
0
  C->setPriority(Record.readSubExpr());
11211
0
  C->setLParenLoc(Record.readSourceLocation());
11212
0
}
11213
11214
0
void OMPClauseReader::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
11215
0
  VisitOMPClauseWithPreInit(C);
11216
0
  C->setModifier(Record.readEnum<OpenMPGrainsizeClauseModifier>());
11217
0
  C->setGrainsize(Record.readSubExpr());
11218
0
  C->setModifierLoc(Record.readSourceLocation());
11219
0
  C->setLParenLoc(Record.readSourceLocation());
11220
0
}
11221
11222
0
void OMPClauseReader::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
11223
0
  VisitOMPClauseWithPreInit(C);
11224
0
  C->setModifier(Record.readEnum<OpenMPNumTasksClauseModifier>());
11225
0
  C->setNumTasks(Record.readSubExpr());
11226
0
  C->setModifierLoc(Record.readSourceLocation());
11227
0
  C->setLParenLoc(Record.readSourceLocation());
11228
0
}
11229
11230
0
void OMPClauseReader::VisitOMPHintClause(OMPHintClause *C) {
11231
0
  C->setHint(Record.readSubExpr());
11232
0
  C->setLParenLoc(Record.readSourceLocation());
11233
0
}
11234
11235
0
void OMPClauseReader::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
11236
0
  VisitOMPClauseWithPreInit(C);
11237
0
  C->setDistScheduleKind(
11238
0
      static_cast<OpenMPDistScheduleClauseKind>(Record.readInt()));
11239
0
  C->setChunkSize(Record.readSubExpr());
11240
0
  C->setLParenLoc(Record.readSourceLocation());
11241
0
  C->setDistScheduleKindLoc(Record.readSourceLocation());
11242
0
  C->setCommaLoc(Record.readSourceLocation());
11243
0
}
11244
11245
0
void OMPClauseReader::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
11246
0
  C->setDefaultmapKind(
11247
0
       static_cast<OpenMPDefaultmapClauseKind>(Record.readInt()));
11248
0
  C->setDefaultmapModifier(
11249
0
      static_cast<OpenMPDefaultmapClauseModifier>(Record.readInt()));
11250
0
  C->setLParenLoc(Record.readSourceLocation());
11251
0
  C->setDefaultmapModifierLoc(Record.readSourceLocation());
11252
0
  C->setDefaultmapKindLoc(Record.readSourceLocation());
11253
0
}
11254
11255
0
void OMPClauseReader::VisitOMPToClause(OMPToClause *C) {
11256
0
  C->setLParenLoc(Record.readSourceLocation());
11257
0
  for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
11258
0
    C->setMotionModifier(
11259
0
        I, static_cast<OpenMPMotionModifierKind>(Record.readInt()));
11260
0
    C->setMotionModifierLoc(I, Record.readSourceLocation());
11261
0
  }
11262
0
  C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
11263
0
  C->setMapperIdInfo(Record.readDeclarationNameInfo());
11264
0
  C->setColonLoc(Record.readSourceLocation());
11265
0
  auto NumVars = C->varlist_size();
11266
0
  auto UniqueDecls = C->getUniqueDeclarationsNum();
11267
0
  auto TotalLists = C->getTotalComponentListNum();
11268
0
  auto TotalComponents = C->getTotalComponentsNum();
11269
11270
0
  SmallVector<Expr *, 16> Vars;
11271
0
  Vars.reserve(NumVars);
11272
0
  for (unsigned i = 0; i != NumVars; ++i)
11273
0
    Vars.push_back(Record.readSubExpr());
11274
0
  C->setVarRefs(Vars);
11275
11276
0
  SmallVector<Expr *, 16> UDMappers;
11277
0
  UDMappers.reserve(NumVars);
11278
0
  for (unsigned I = 0; I < NumVars; ++I)
11279
0
    UDMappers.push_back(Record.readSubExpr());
11280
0
  C->setUDMapperRefs(UDMappers);
11281
11282
0
  SmallVector<ValueDecl *, 16> Decls;
11283
0
  Decls.reserve(UniqueDecls);
11284
0
  for (unsigned i = 0; i < UniqueDecls; ++i)
11285
0
    Decls.push_back(Record.readDeclAs<ValueDecl>());
11286
0
  C->setUniqueDecls(Decls);
11287
11288
0
  SmallVector<unsigned, 16> ListsPerDecl;
11289
0
  ListsPerDecl.reserve(UniqueDecls);
11290
0
  for (unsigned i = 0; i < UniqueDecls; ++i)
11291
0
    ListsPerDecl.push_back(Record.readInt());
11292
0
  C->setDeclNumLists(ListsPerDecl);
11293
11294
0
  SmallVector<unsigned, 32> ListSizes;
11295
0
  ListSizes.reserve(TotalLists);
11296
0
  for (unsigned i = 0; i < TotalLists; ++i)
11297
0
    ListSizes.push_back(Record.readInt());
11298
0
  C->setComponentListSizes(ListSizes);
11299
11300
0
  SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
11301
0
  Components.reserve(TotalComponents);
11302
0
  for (unsigned i = 0; i < TotalComponents; ++i) {
11303
0
    Expr *AssociatedExprPr = Record.readSubExpr();
11304
0
    bool IsNonContiguous = Record.readBool();
11305
0
    auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11306
0
    Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous);
11307
0
  }
11308
0
  C->setComponents(Components, ListSizes);
11309
0
}
11310
11311
0
void OMPClauseReader::VisitOMPFromClause(OMPFromClause *C) {
11312
0
  C->setLParenLoc(Record.readSourceLocation());
11313
0
  for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
11314
0
    C->setMotionModifier(
11315
0
        I, static_cast<OpenMPMotionModifierKind>(Record.readInt()));
11316
0
    C->setMotionModifierLoc(I, Record.readSourceLocation());
11317
0
  }
11318
0
  C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
11319
0
  C->setMapperIdInfo(Record.readDeclarationNameInfo());
11320
0
  C->setColonLoc(Record.readSourceLocation());
11321
0
  auto NumVars = C->varlist_size();
11322
0
  auto UniqueDecls = C->getUniqueDeclarationsNum();
11323
0
  auto TotalLists = C->getTotalComponentListNum();
11324
0
  auto TotalComponents = C->getTotalComponentsNum();
11325
11326
0
  SmallVector<Expr *, 16> Vars;
11327
0
  Vars.reserve(NumVars);
11328
0
  for (unsigned i = 0; i != NumVars; ++i)
11329
0
    Vars.push_back(Record.readSubExpr());
11330
0
  C->setVarRefs(Vars);
11331
11332
0
  SmallVector<Expr *, 16> UDMappers;
11333
0
  UDMappers.reserve(NumVars);
11334
0
  for (unsigned I = 0; I < NumVars; ++I)
11335
0
    UDMappers.push_back(Record.readSubExpr());
11336
0
  C->setUDMapperRefs(UDMappers);
11337
11338
0
  SmallVector<ValueDecl *, 16> Decls;
11339
0
  Decls.reserve(UniqueDecls);
11340
0
  for (unsigned i = 0; i < UniqueDecls; ++i)
11341
0
    Decls.push_back(Record.readDeclAs<ValueDecl>());
11342
0
  C->setUniqueDecls(Decls);
11343
11344
0
  SmallVector<unsigned, 16> ListsPerDecl;
11345
0
  ListsPerDecl.reserve(UniqueDecls);
11346
0
  for (unsigned i = 0; i < UniqueDecls; ++i)
11347
0
    ListsPerDecl.push_back(Record.readInt());
11348
0
  C->setDeclNumLists(ListsPerDecl);
11349
11350
0
  SmallVector<unsigned, 32> ListSizes;
11351
0
  ListSizes.reserve(TotalLists);
11352
0
  for (unsigned i = 0; i < TotalLists; ++i)
11353
0
    ListSizes.push_back(Record.readInt());
11354
0
  C->setComponentListSizes(ListSizes);
11355
11356
0
  SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
11357
0
  Components.reserve(TotalComponents);
11358
0
  for (unsigned i = 0; i < TotalComponents; ++i) {
11359
0
    Expr *AssociatedExprPr = Record.readSubExpr();
11360
0
    bool IsNonContiguous = Record.readBool();
11361
0
    auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11362
0
    Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous);
11363
0
  }
11364
0
  C->setComponents(Components, ListSizes);
11365
0
}
11366
11367
0
void OMPClauseReader::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {
11368
0
  C->setLParenLoc(Record.readSourceLocation());
11369
0
  auto NumVars = C->varlist_size();
11370
0
  auto UniqueDecls = C->getUniqueDeclarationsNum();
11371
0
  auto TotalLists = C->getTotalComponentListNum();
11372
0
  auto TotalComponents = C->getTotalComponentsNum();
11373
11374
0
  SmallVector<Expr *, 16> Vars;
11375
0
  Vars.reserve(NumVars);
11376
0
  for (unsigned i = 0; i != NumVars; ++i)
11377
0
    Vars.push_back(Record.readSubExpr());
11378
0
  C->setVarRefs(Vars);
11379
0
  Vars.clear();
11380
0
  for (unsigned i = 0; i != NumVars; ++i)
11381
0
    Vars.push_back(Record.readSubExpr());
11382
0
  C->setPrivateCopies(Vars);
11383
0
  Vars.clear();
11384
0
  for (unsigned i = 0; i != NumVars; ++i)
11385
0
    Vars.push_back(Record.readSubExpr());
11386
0
  C->setInits(Vars);
11387
11388
0
  SmallVector<ValueDecl *, 16> Decls;
11389
0
  Decls.reserve(UniqueDecls);
11390
0
  for (unsigned i = 0; i < UniqueDecls; ++i)
11391
0
    Decls.push_back(Record.readDeclAs<ValueDecl>());
11392
0
  C->setUniqueDecls(Decls);
11393
11394
0
  SmallVector<unsigned, 16> ListsPerDecl;
11395
0
  ListsPerDecl.reserve(UniqueDecls);
11396
0
  for (unsigned i = 0; i < UniqueDecls; ++i)
11397
0
    ListsPerDecl.push_back(Record.readInt());
11398
0
  C->setDeclNumLists(ListsPerDecl);
11399
11400
0
  SmallVector<unsigned, 32> ListSizes;
11401
0
  ListSizes.reserve(TotalLists);
11402
0
  for (unsigned i = 0; i < TotalLists; ++i)
11403
0
    ListSizes.push_back(Record.readInt());
11404
0
  C->setComponentListSizes(ListSizes);
11405
11406
0
  SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
11407
0
  Components.reserve(TotalComponents);
11408
0
  for (unsigned i = 0; i < TotalComponents; ++i) {
11409
0
    auto *AssociatedExprPr = Record.readSubExpr();
11410
0
    auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11411
0
    Components.emplace_back(AssociatedExprPr, AssociatedDecl,
11412
0
                            /*IsNonContiguous=*/false);
11413
0
  }
11414
0
  C->setComponents(Components, ListSizes);
11415
0
}
11416
11417
0
void OMPClauseReader::VisitOMPUseDeviceAddrClause(OMPUseDeviceAddrClause *C) {
11418
0
  C->setLParenLoc(Record.readSourceLocation());
11419
0
  auto NumVars = C->varlist_size();
11420
0
  auto UniqueDecls = C->getUniqueDeclarationsNum();
11421
0
  auto TotalLists = C->getTotalComponentListNum();
11422
0
  auto TotalComponents = C->getTotalComponentsNum();
11423
11424
0
  SmallVector<Expr *, 16> Vars;
11425
0
  Vars.reserve(NumVars);
11426
0
  for (unsigned i = 0; i != NumVars; ++i)
11427
0
    Vars.push_back(Record.readSubExpr());
11428
0
  C->setVarRefs(Vars);
11429
11430
0
  SmallVector<ValueDecl *, 16> Decls;
11431
0
  Decls.reserve(UniqueDecls);
11432
0
  for (unsigned i = 0; i < UniqueDecls; ++i)
11433
0
    Decls.push_back(Record.readDeclAs<ValueDecl>());
11434
0
  C->setUniqueDecls(Decls);
11435
11436
0
  SmallVector<unsigned, 16> ListsPerDecl;
11437
0
  ListsPerDecl.reserve(UniqueDecls);
11438
0
  for (unsigned i = 0; i < UniqueDecls; ++i)
11439
0
    ListsPerDecl.push_back(Record.readInt());
11440
0
  C->setDeclNumLists(ListsPerDecl);
11441
11442
0
  SmallVector<unsigned, 32> ListSizes;
11443
0
  ListSizes.reserve(TotalLists);
11444
0
  for (unsigned i = 0; i < TotalLists; ++i)
11445
0
    ListSizes.push_back(Record.readInt());
11446
0
  C->setComponentListSizes(ListSizes);
11447
11448
0
  SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
11449
0
  Components.reserve(TotalComponents);
11450
0
  for (unsigned i = 0; i < TotalComponents; ++i) {
11451
0
    Expr *AssociatedExpr = Record.readSubExpr();
11452
0
    auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11453
0
    Components.emplace_back(AssociatedExpr, AssociatedDecl,
11454
0
                            /*IsNonContiguous*/ false);
11455
0
  }
11456
0
  C->setComponents(Components, ListSizes);
11457
0
}
11458
11459
0
void OMPClauseReader::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
11460
0
  C->setLParenLoc(Record.readSourceLocation());
11461
0
  auto NumVars = C->varlist_size();
11462
0
  auto UniqueDecls = C->getUniqueDeclarationsNum();
11463
0
  auto TotalLists = C->getTotalComponentListNum();
11464
0
  auto TotalComponents = C->getTotalComponentsNum();
11465
11466
0
  SmallVector<Expr *, 16> Vars;
11467
0
  Vars.reserve(NumVars);
11468
0
  for (unsigned i = 0; i != NumVars; ++i)
11469
0
    Vars.push_back(Record.readSubExpr());
11470
0
  C->setVarRefs(Vars);
11471
0
  Vars.clear();
11472
11473
0
  SmallVector<ValueDecl *, 16> Decls;
11474
0
  Decls.reserve(UniqueDecls);
11475
0
  for (unsigned i = 0; i < UniqueDecls; ++i)
11476
0
    Decls.push_back(Record.readDeclAs<ValueDecl>());
11477
0
  C->setUniqueDecls(Decls);
11478
11479
0
  SmallVector<unsigned, 16> ListsPerDecl;
11480
0
  ListsPerDecl.reserve(UniqueDecls);
11481
0
  for (unsigned i = 0; i < UniqueDecls; ++i)
11482
0
    ListsPerDecl.push_back(Record.readInt());
11483
0
  C->setDeclNumLists(ListsPerDecl);
11484
11485
0
  SmallVector<unsigned, 32> ListSizes;
11486
0
  ListSizes.reserve(TotalLists);
11487
0
  for (unsigned i = 0; i < TotalLists; ++i)
11488
0
    ListSizes.push_back(Record.readInt());
11489
0
  C->setComponentListSizes(ListSizes);
11490
11491
0
  SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
11492
0
  Components.reserve(TotalComponents);
11493
0
  for (unsigned i = 0; i < TotalComponents; ++i) {
11494
0
    Expr *AssociatedExpr = Record.readSubExpr();
11495
0
    auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11496
0
    Components.emplace_back(AssociatedExpr, AssociatedDecl,
11497
0
                            /*IsNonContiguous=*/false);
11498
0
  }
11499
0
  C->setComponents(Components, ListSizes);
11500
0
}
11501
11502
0
void OMPClauseReader::VisitOMPHasDeviceAddrClause(OMPHasDeviceAddrClause *C) {
11503
0
  C->setLParenLoc(Record.readSourceLocation());
11504
0
  auto NumVars = C->varlist_size();
11505
0
  auto UniqueDecls = C->getUniqueDeclarationsNum();
11506
0
  auto TotalLists = C->getTotalComponentListNum();
11507
0
  auto TotalComponents = C->getTotalComponentsNum();
11508
11509
0
  SmallVector<Expr *, 16> Vars;
11510
0
  Vars.reserve(NumVars);
11511
0
  for (unsigned I = 0; I != NumVars; ++I)
11512
0
    Vars.push_back(Record.readSubExpr());
11513
0
  C->setVarRefs(Vars);
11514
0
  Vars.clear();
11515
11516
0
  SmallVector<ValueDecl *, 16> Decls;
11517
0
  Decls.reserve(UniqueDecls);
11518
0
  for (unsigned I = 0; I < UniqueDecls; ++I)
11519
0
    Decls.push_back(Record.readDeclAs<ValueDecl>());
11520
0
  C->setUniqueDecls(Decls);
11521
11522
0
  SmallVector<unsigned, 16> ListsPerDecl;
11523
0
  ListsPerDecl.reserve(UniqueDecls);
11524
0
  for (unsigned I = 0; I < UniqueDecls; ++I)
11525
0
    ListsPerDecl.push_back(Record.readInt());
11526
0
  C->setDeclNumLists(ListsPerDecl);
11527
11528
0
  SmallVector<unsigned, 32> ListSizes;
11529
0
  ListSizes.reserve(TotalLists);
11530
0
  for (unsigned i = 0; i < TotalLists; ++i)
11531
0
    ListSizes.push_back(Record.readInt());
11532
0
  C->setComponentListSizes(ListSizes);
11533
11534
0
  SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
11535
0
  Components.reserve(TotalComponents);
11536
0
  for (unsigned I = 0; I < TotalComponents; ++I) {
11537
0
    Expr *AssociatedExpr = Record.readSubExpr();
11538
0
    auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11539
0
    Components.emplace_back(AssociatedExpr, AssociatedDecl,
11540
0
                            /*IsNonContiguous=*/false);
11541
0
  }
11542
0
  C->setComponents(Components, ListSizes);
11543
0
}
11544
11545
0
void OMPClauseReader::VisitOMPNontemporalClause(OMPNontemporalClause *C) {
11546
0
  C->setLParenLoc(Record.readSourceLocation());
11547
0
  unsigned NumVars = C->varlist_size();
11548
0
  SmallVector<Expr *, 16> Vars;
11549
0
  Vars.reserve(NumVars);
11550
0
  for (unsigned i = 0; i != NumVars; ++i)
11551
0
    Vars.push_back(Record.readSubExpr());
11552
0
  C->setVarRefs(Vars);
11553
0
  Vars.clear();
11554
0
  Vars.reserve(NumVars);
11555
0
  for (unsigned i = 0; i != NumVars; ++i)
11556
0
    Vars.push_back(Record.readSubExpr());
11557
0
  C->setPrivateRefs(Vars);
11558
0
}
11559
11560
0
void OMPClauseReader::VisitOMPInclusiveClause(OMPInclusiveClause *C) {
11561
0
  C->setLParenLoc(Record.readSourceLocation());
11562
0
  unsigned NumVars = C->varlist_size();
11563
0
  SmallVector<Expr *, 16> Vars;
11564
0
  Vars.reserve(NumVars);
11565
0
  for (unsigned i = 0; i != NumVars; ++i)
11566
0
    Vars.push_back(Record.readSubExpr());
11567
0
  C->setVarRefs(Vars);
11568
0
}
11569
11570
0
void OMPClauseReader::VisitOMPExclusiveClause(OMPExclusiveClause *C) {
11571
0
  C->setLParenLoc(Record.readSourceLocation());
11572
0
  unsigned NumVars = C->varlist_size();
11573
0
  SmallVector<Expr *, 16> Vars;
11574
0
  Vars.reserve(NumVars);
11575
0
  for (unsigned i = 0; i != NumVars; ++i)
11576
0
    Vars.push_back(Record.readSubExpr());
11577
0
  C->setVarRefs(Vars);
11578
0
}
11579
11580
0
void OMPClauseReader::VisitOMPUsesAllocatorsClause(OMPUsesAllocatorsClause *C) {
11581
0
  C->setLParenLoc(Record.readSourceLocation());
11582
0
  unsigned NumOfAllocators = C->getNumberOfAllocators();
11583
0
  SmallVector<OMPUsesAllocatorsClause::Data, 4> Data;
11584
0
  Data.reserve(NumOfAllocators);
11585
0
  for (unsigned I = 0; I != NumOfAllocators; ++I) {
11586
0
    OMPUsesAllocatorsClause::Data &D = Data.emplace_back();
11587
0
    D.Allocator = Record.readSubExpr();
11588
0
    D.AllocatorTraits = Record.readSubExpr();
11589
0
    D.LParenLoc = Record.readSourceLocation();
11590
0
    D.RParenLoc = Record.readSourceLocation();
11591
0
  }
11592
0
  C->setAllocatorsData(Data);
11593
0
}
11594
11595
0
void OMPClauseReader::VisitOMPAffinityClause(OMPAffinityClause *C) {
11596
0
  C->setLParenLoc(Record.readSourceLocation());
11597
0
  C->setModifier(Record.readSubExpr());
11598
0
  C->setColonLoc(Record.readSourceLocation());
11599
0
  unsigned NumOfLocators = C->varlist_size();
11600
0
  SmallVector<Expr *, 4> Locators;
11601
0
  Locators.reserve(NumOfLocators);
11602
0
  for (unsigned I = 0; I != NumOfLocators; ++I)
11603
0
    Locators.push_back(Record.readSubExpr());
11604
0
  C->setVarRefs(Locators);
11605
0
}
11606
11607
0
void OMPClauseReader::VisitOMPOrderClause(OMPOrderClause *C) {
11608
0
  C->setKind(Record.readEnum<OpenMPOrderClauseKind>());
11609
0
  C->setModifier(Record.readEnum<OpenMPOrderClauseModifier>());
11610
0
  C->setLParenLoc(Record.readSourceLocation());
11611
0
  C->setKindKwLoc(Record.readSourceLocation());
11612
0
  C->setModifierKwLoc(Record.readSourceLocation());
11613
0
}
11614
11615
0
void OMPClauseReader::VisitOMPFilterClause(OMPFilterClause *C) {
11616
0
  VisitOMPClauseWithPreInit(C);
11617
0
  C->setThreadID(Record.readSubExpr());
11618
0
  C->setLParenLoc(Record.readSourceLocation());
11619
0
}
11620
11621
0
void OMPClauseReader::VisitOMPBindClause(OMPBindClause *C) {
11622
0
  C->setBindKind(Record.readEnum<OpenMPBindClauseKind>());
11623
0
  C->setLParenLoc(Record.readSourceLocation());
11624
0
  C->setBindKindLoc(Record.readSourceLocation());
11625
0
}
11626
11627
0
void OMPClauseReader::VisitOMPAlignClause(OMPAlignClause *C) {
11628
0
  C->setAlignment(Record.readExpr());
11629
0
  C->setLParenLoc(Record.readSourceLocation());
11630
0
}
11631
11632
0
void OMPClauseReader::VisitOMPXDynCGroupMemClause(OMPXDynCGroupMemClause *C) {
11633
0
  VisitOMPClauseWithPreInit(C);
11634
0
  C->setSize(Record.readSubExpr());
11635
0
  C->setLParenLoc(Record.readSourceLocation());
11636
0
}
11637
11638
0
void OMPClauseReader::VisitOMPDoacrossClause(OMPDoacrossClause *C) {
11639
0
  C->setLParenLoc(Record.readSourceLocation());
11640
0
  C->setDependenceType(
11641
0
      static_cast<OpenMPDoacrossClauseModifier>(Record.readInt()));
11642
0
  C->setDependenceLoc(Record.readSourceLocation());
11643
0
  C->setColonLoc(Record.readSourceLocation());
11644
0
  unsigned NumVars = C->varlist_size();
11645
0
  SmallVector<Expr *, 16> Vars;
11646
0
  Vars.reserve(NumVars);
11647
0
  for (unsigned I = 0; I != NumVars; ++I)
11648
0
    Vars.push_back(Record.readSubExpr());
11649
0
  C->setVarRefs(Vars);
11650
0
  for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
11651
0
    C->setLoopData(I, Record.readSubExpr());
11652
0
}
11653
11654
0
void OMPClauseReader::VisitOMPXAttributeClause(OMPXAttributeClause *C) {
11655
0
  AttrVec Attrs;
11656
0
  Record.readAttributes(Attrs);
11657
0
  C->setAttrs(Attrs);
11658
0
  C->setLocStart(Record.readSourceLocation());
11659
0
  C->setLParenLoc(Record.readSourceLocation());
11660
0
  C->setLocEnd(Record.readSourceLocation());
11661
0
}
11662
11663
0
void OMPClauseReader::VisitOMPXBareClause(OMPXBareClause *C) {}
11664
11665
0
OMPTraitInfo *ASTRecordReader::readOMPTraitInfo() {
11666
0
  OMPTraitInfo &TI = getContext().getNewOMPTraitInfo();
11667
0
  TI.Sets.resize(readUInt32());
11668
0
  for (auto &Set : TI.Sets) {
11669
0
    Set.Kind = readEnum<llvm::omp::TraitSet>();
11670
0
    Set.Selectors.resize(readUInt32());
11671
0
    for (auto &Selector : Set.Selectors) {
11672
0
      Selector.Kind = readEnum<llvm::omp::TraitSelector>();
11673
0
      Selector.ScoreOrCondition = nullptr;
11674
0
      if (readBool())
11675
0
        Selector.ScoreOrCondition = readExprRef();
11676
0
      Selector.Properties.resize(readUInt32());
11677
0
      for (auto &Property : Selector.Properties)
11678
0
        Property.Kind = readEnum<llvm::omp::TraitProperty>();
11679
0
    }
11680
0
  }
11681
0
  return &TI;
11682
0
}
11683
11684
0
void ASTRecordReader::readOMPChildren(OMPChildren *Data) {
11685
0
  if (!Data)
11686
0
    return;
11687
0
  if (Reader->ReadingKind == ASTReader::Read_Stmt) {
11688
    // Skip NumClauses, NumChildren and HasAssociatedStmt fields.
11689
0
    skipInts(3);
11690
0
  }
11691
0
  SmallVector<OMPClause *, 4> Clauses(Data->getNumClauses());
11692
0
  for (unsigned I = 0, E = Data->getNumClauses(); I < E; ++I)
11693
0
    Clauses[I] = readOMPClause();
11694
0
  Data->setClauses(Clauses);
11695
0
  if (Data->hasAssociatedStmt())
11696
0
    Data->setAssociatedStmt(readStmt());
11697
0
  for (unsigned I = 0, E = Data->getNumChildren(); I < E; ++I)
11698
0
    Data->getChildren()[I] = readStmt();
11699
0
}